diff --git a/lean/OAI/Computability/MinUncut/Estimates/RowListBridge.lean b/lean/OAI/Computability/MinUncut/Estimates/RowListBridge.lean new file mode 100644 index 0000000000000000000000000000000000000000..f630a378f03e628d1fb72efcaaef9dc91d048726 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Estimates/RowListBridge.lean @@ -0,0 +1,63 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.InnerAssembly +import OAI.Computability.MinUncut.Estimates.FourthTest + +namespace OAI + +section +noncomputable section +open scoped BigOperators +namespace MinUncut.Composition +open BinaryFourier hiding F₂ +open MinUncut.Inner RowNoise +attribute [local instance] Classical.propDecidable BinaryFourier.dualFintype +variable {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 + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Estimates/SamplerAssembly.lean b/lean/OAI/Computability/MinUncut/Estimates/SamplerAssembly.lean new file mode 100644 index 0000000000000000000000000000000000000000..f2a8f06521bfbdf377d1791bd6b00e6271a8cbbf --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Estimates/SamplerAssembly.lean @@ -0,0 +1,93 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.SamplerCost +import OAI.Computability.MinUncut.Search.RationalDenominatorArithmetic + +namespace OAI + +section +noncomputable section +open scoped BigOperators +namespace MinUncut.Outer +open MinUncut.Inner MinUncut.FiniteGaussian MinUncut.FiniteProof OuterSmoothness +attribute [local instance] Classical.propDecidable coordsDecEq +variable {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 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] + rfl +end MinUncut.Outer + +namespace MinUncut.Outer +open MinUncut.Inner MinUncut.FiniteGaussian MinUncut.FiniteProof OuterSmoothness +attribute [local instance] Classical.propDecidable coordsDecEq +variable {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 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 + 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 h +end MinUncut.Inner +namespace MinUncut.RowNoise +open MeasureTheory ProbabilityTheory BinaryFourier GaussianHermite +open scoped BigOperators +attribute [local instance] Classical.propDecidable +local instance secondFailureDualFintype {U : Type*} [AddCommGroup U] [Module F₂ U] [Fintype U] : + Fintype (Module.Dual F₂ U) := BinaryFourier.dualFintype +variable {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] in +lemma 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] in +lemma 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] in +lemma 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 ι] in +lemma 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 ι] in +lemma 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 ι] in +lemma 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] + ring +end MinUncut.RowNoise + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Estimates/SelectedProject.lean b/lean/OAI/Computability/MinUncut/Estimates/SelectedProject.lean new file mode 100644 index 0000000000000000000000000000000000000000..34a2e7a6b5f6757ef6f45a3aaa9cd6ebe6871358 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Estimates/SelectedProject.lean @@ -0,0 +1,59 @@ +import Mathlib +import OAI.Computability.MinUncut.Analysis.MaskHermite + +namespace OAI + +noncomputable section +open scoped BigOperators +open MeasureTheory ProbabilityTheory Filter +open scoped Topology NNReal +open scoped BigOperators +open MeasureTheory ProbabilityTheory Polynomial Filter +open scoped BigOperators Topology +open MeasureTheory ProbabilityTheory WithLp +open scoped BigOperators RealInnerProductSpace +namespace MinUncut.RowNoise +open MeasureTheory ProbabilityTheory BinaryFourier GaussianHermite +open scoped BigOperators +local instance selectedProjectDualFintype {U : Type*} [AddCommGroup U] [Module F₂ U] [Fintype U] : + Fintype (Module.Dual F₂ U) := BinaryFourier.dualFintype +variable {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] in +lemma 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]; ring +end MinUncut.RowNoise +open scoped BigOperators + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Estimates/SelectedProjectSliceContinuous.lean b/lean/OAI/Computability/MinUncut/Estimates/SelectedProjectSliceContinuous.lean new file mode 100644 index 0000000000000000000000000000000000000000..6abbd8dd268511c615e443fa84184bec8ff30522 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Estimates/SelectedProjectSliceContinuous.lean @@ -0,0 +1,53 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.FaceUpdateSelf +import OAI.Computability.MinUncut.Games.JointInner + +namespace OAI + +noncomputable section +open scoped BigOperators +open MeasureTheory ProbabilityTheory Filter +open scoped Topology NNReal +open scoped BigOperators +open MeasureTheory ProbabilityTheory Polynomial Filter +open scoped BigOperators Topology +open MeasureTheory ProbabilityTheory WithLp +open scoped BigOperators RealInnerProductSpace +open scoped BigOperators +namespace MinUncut.RowNoise +open MeasureTheory GaussianHermite +open scoped BigOperators +variable {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] in +lemma 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.Slice +open MeasureTheory +variable {Ω : 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_const +end MinUncut.Slice + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Estimates/SelectedSyntax.lean b/lean/OAI/Computability/MinUncut/Estimates/SelectedSyntax.lean new file mode 100644 index 0000000000000000000000000000000000000000..5d8c01f2b1ddf9a2a44a73e719506c3f75aed0f4 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Estimates/SelectedSyntax.lean @@ -0,0 +1,57 @@ +import Mathlib +import OAI.Computability.MinUncut.Graphs.CompleteGraphProgram +import OAI.Computability.MinUncut.Graphs.Graph + +namespace OAI + +section +noncomputable section +namespace MinUncut.Preprocess +attribute [local irreducible] selectedInner selectedOuter +open MinUncut.Inner MinUncut.Outer MinUncut.Outer.LocalTemplate +open MinUncutGames.Foundations MinUncutGames.Foundations.Hastad +open MinUncutGames.Integration.SourceParameters MinUncut.Costed.SourceWords MinUncut.SourceTemplate +def chosenError (K : ℕ) := (selectedParameters K).sourceError +def 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 sourceStageProgram +lemma 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 + rfl +end MinUncut.Preprocess + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Estimates/SingleRow.lean b/lean/OAI/Computability/MinUncut/Estimates/SingleRow.lean new file mode 100644 index 0000000000000000000000000000000000000000..3f0276d146f29dd5cb5b006c9a8595b54499172e --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Estimates/SingleRow.lean @@ -0,0 +1,125 @@ +import Mathlib +import OAI.Computability.MinUncut.Games.JointCoefficient +import OAI.Computability.MinUncut.Analysis.Hermite + +namespace OAI + +noncomputable section +open scoped BigOperators +open MeasureTheory ProbabilityTheory Filter +open scoped Topology NNReal +open scoped BigOperators +open MeasureTheory ProbabilityTheory Polynomial Filter +open scoped BigOperators Topology +open MeasureTheory ProbabilityTheory WithLp +open scoped BigOperators RealInnerProductSpace +namespace MinUncut.Inner +open scoped BigOperators +attribute [local instance] Classical.propDecidable +variable {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] in +lemma 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 hh +end MinUncut.Inner + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Estimates/TM2Costed.lean b/lean/OAI/Computability/MinUncut/Estimates/TM2Costed.lean new file mode 100644 index 0000000000000000000000000000000000000000..9e6fbab3fdca9db868a5651f9066664f51a684c1 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Estimates/TM2Costed.lean @@ -0,0 +1,724 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.CodeComputability + +namespace OAI + +section +namespace 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.PartrecToTM2 +open scoped _root_.Turing _root_.Turing.PartrecToTM2 +open Function +open MinUncut.Costed +open _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.WordTransducer +open _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, Fintype +abbrev 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.Costed +open _root_.Turing _root_.Turing.ToPartrec _root_.Turing.PartrecToTM2 + _root_.OAI.Turing.PartrecToTM2 Function +open _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_.Turing +namespace FiniteControl +variable {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] in +lemma 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 FiniteControl +end MinUncut.Costed + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Estimates/TableLawPacking.lean b/lean/OAI/Computability/MinUncut/Estimates/TableLawPacking.lean new file mode 100644 index 0000000000000000000000000000000000000000..1b95ea61cb005863bfbef716f9f61f5e19f4bdc3 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Estimates/TableLawPacking.lean @@ -0,0 +1,92 @@ +import Mathlib +import OAI.Computability.MinUncut.Analysis.LiteralGaussian + +namespace OAI + +section +noncomputable section +open scoped BigOperators +open MeasureTheory ProbabilityTheory +namespace MinUncut.FiniteGaussian +open GaussianBudget MinUncut.Inner +attribute [local instance] Classical.propDecidable +variable {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 + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Estimates/TableTestFunctions.lean b/lean/OAI/Computability/MinUncut/Estimates/TableTestFunctions.lean new file mode 100644 index 0000000000000000000000000000000000000000..a2f39b02b09173cad18ad23b12bb823354beaa83 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Estimates/TableTestFunctions.lean @@ -0,0 +1,101 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.ActualBoxBound +import OAI.Computability.MinUncut.Estimates.FourthTest +import OAI.Computability.MinUncut.Estimates.TableLawPacking + +namespace OAI + +section +noncomputable section +open scoped BigOperators +open MeasureTheory ProbabilityTheory +namespace MinUncut.FiniteGaussian +open GaussianBudget MinUncut.Inner +attribute [local instance] Classical.propDecidable +variable {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] in +lemma 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] in +lemma 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] in +lemma 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'] in +lemma 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] in +lemma 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] in +lemma 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] in +lemma 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'] in +lemma 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 + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Estimates/TemplateExpressions.lean b/lean/OAI/Computability/MinUncut/Estimates/TemplateExpressions.lean new file mode 100644 index 0000000000000000000000000000000000000000..c4ce4dac59cd04dcf3e20940651d93f0f7a432b1 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Estimates/TemplateExpressions.lean @@ -0,0 +1,376 @@ +import Mathlib +import OAI.Computability.MinUncut.Search.UniformQuantifier +import OAI.Computability.MinUncut.Estimates.UniformTransport +import OAI.Computability.MinUncut.Encoding.SignatureEncoding +import OAI.Computability.MinUncut.Search.TemplateArithmetic + +namespace OAI + +section +namespace MinUncut.SourceTemplate +open MinUncutGames.Foundations MinUncutGames.Foundations.Target +open PCP Hastad Hastad.SourceContexts Hastad.SourceOccurrences +open MinUncutGames.Reduction.CloneGap +open MinUncut.Costed +open 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 + +end +section +noncomputable section +namespace MinUncut.Preprocess.Syntax +open MinUncutGames.Foundations.Hastad.SourceOccurrences +open MinUncut.FiniteProof MinUncut.Costed MinUncut.CodeEffective Turing.ToPartrec UEncoding +variable {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] + rfl +lemma 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] + rfl +lemma 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 + +end +end +section +namespace MinUncut.Preprocess.Source +open MinUncutGames.Foundations MinUncutGames.Foundations.Target +open PCP Hastad Hastad.SourceContexts Hastad.SourceOccurrences +open MinUncut.SourceTemplate UEncoding + +def positions : UEncoding ℕ Fin := UEncoding.fin id Computable.id +def slots : UEncoding ℕ (fun _=>Slot) := fixed slotEncoding +def answers : UEncoding ℕ (fun _=>ClauseAnswer) := fixed clauseAnswerEncoding +def lefts : UEncoding ℕ I := positions.function bool +def rights : UEncoding ℕ J := positions.function answers +def coordinates : UEncoding ℕ (fun u=>Fin u × Slot) := positions.prod slots +def 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 := rfl +lemma 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) hb +lemma 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 + +end +section +namespace MinUncut.Preprocess.Source +open MinUncutGames.Foundations MinUncutGames.Foundations.Target +open PCP Hastad Hastad.SourceContexts Hastad.SourceOccurrences +open 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.UEncoding +open MinUncutGames.Foundations.Hastad.SourceOccurrences +open MinUncutGames.Foundations.Hastad +variable {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 + +end +section +namespace MinUncut.SourceTemplate +open MinUncutGames.Foundations MinUncutGames.Foundations.Target +open PCP Hastad Hastad.SourceContexts Hastad.SourceOccurrences +open 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] + rfl +end MinUncut.SourceTemplate + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Estimates/UniformAlgebra.lean b/lean/OAI/Computability/MinUncut/Estimates/UniformAlgebra.lean new file mode 100644 index 0000000000000000000000000000000000000000..d92eb36566e92cadbf14174fa672de1edceecd12 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Estimates/UniformAlgebra.lean @@ -0,0 +1,90 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.UniformTransport +import OAI.Computability.MinUncut.Estimates.UniformRestrict +import OAI.Computability.MinUncut.Encoding.QuestionEncoding + +namespace OAI + +section +namespace MinUncut.Preprocess +open MinUncutGames.Foundations.Hastad.SourceOccurrences +open scoped BigOperators +variable {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 UEncoding +variable {A B Γ : P → Type} +omit [AddCommMonoid X] in +lemma 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 0 +lemma 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).toFixed +lemma 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).toFixed +lemma 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).toFixed +end UEncoding +end MinUncut.Preprocess + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Estimates/UniformBoolean.lean b/lean/OAI/Computability/MinUncut/Estimates/UniformBoolean.lean new file mode 100644 index 0000000000000000000000000000000000000000..cc42cfabf110efe035dca414d7a32b13958f4467 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Estimates/UniformBoolean.lean @@ -0,0 +1,97 @@ +import Mathlib +import OAI.Computability.MinUncut.Encoding.UniformEncoding + +namespace OAI + +section +namespace MinUncut.Preprocess +open MinUncutGames.Foundations.Hastad.SourceOccurrences +namespace UEncoding +variable {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.bool +def 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 hf +lemma 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 hg +lemma 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 UEncoding +end MinUncut.Preprocess + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Estimates/UniformEquation.lean b/lean/OAI/Computability/MinUncut/Estimates/UniformEquation.lean new file mode 100644 index 0000000000000000000000000000000000000000..3d08e5e79c3ee12c8a4cd8e4e9d5e05ed7f6fc07 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Estimates/UniformEquation.lean @@ -0,0 +1,288 @@ +import Mathlib +import OAI.Computability.MinUncut.Search.UniformFind +import OAI.Computability.MinUncut.Estimates.UniformAlgebra +import OAI.Computability.MinUncut.Analysis.UniformCube + +namespace OAI + +namespace MinUncut.Preprocess.Source +open MinUncutGames.Foundations MinUncutGames.Foundations.Target +open PCP Hastad Hastad.SourceContexts Hastad.SourceOccurrences +open MinUncutGames.Reduction.CloneGap +open 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 lefts +def rs : UEncoding Par (fun p=>J p.1) := up rights +def fc := ls.function bool +def gc := rs.function bool +def 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.snd +def 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 signatures +def sls := up slotContexts +def context := (sigs.prod sls).prod tapes + +lemma map_context_signature : context.Map sigs (fun _ x=>x.1.1) := + (map_fst sigs sls).first +lemma map_context_slot : context.Map sls (fun _ x=>x.1.2) := + (map_snd sigs sls).first +lemma 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.2 +end MinUncut.Preprocess.Source + +noncomputable section +namespace MinUncut.Preprocess.Syntax +open MinUncutGames.Foundations.PCP +open MinUncutGames.Foundations.Hastad.SourceOccurrences +open MinUncutGames.Foundations.Hastad.SourceContexts +open MinUncut.Costed MinUncut.SourceTemplate UEncoding +variable {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 hf +lemma 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.unit +lemma 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))).toC +lemma 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)))).toC +lemma 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 hu +end MinUncut.Preprocess.Syntax + +namespace MinUncut.Preprocess.Face +open MinUncut.Inner MinUncut.FiniteProof +open MinUncutGames.Foundations.Hastad.SourceOccurrences +open UEncoding +open scoped BigOperators +variable {P : Type} [Primcodable P] +variable (m n : P → ℕ) (hm : Computable m) (hn : Computable n) (hnpos : ∀p,0if 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 in +lemma 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 OAI diff --git a/lean/OAI/Computability/MinUncut/Estimates/UniformEquationOutput.lean b/lean/OAI/Computability/MinUncut/Estimates/UniformEquationOutput.lean new file mode 100644 index 0000000000000000000000000000000000000000..e0281ed716015e412b9593de342d850016693f76 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Estimates/UniformEquationOutput.lean @@ -0,0 +1,298 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.UniformOutput +import OAI.Computability.MinUncut.Graphs.CanonicalSamplerGraph +import OAI.Computability.MinUncut.Estimates.BlocksEffectivity + +namespace OAI + +section +namespace MinUncut.Preprocess.UEncoding +open MinUncutGames.Foundations.Hastad.SourceOccurrences MinUncutGames.Reduction.CloneGap +variable {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 + 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] + rfl +lemma 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 hh +lemma 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 hh +lemma 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 hh +lemma 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 hh +end MinUncut.Preprocess.UEncoding +namespace MinUncut.Preprocess.Source +open MinUncutGames.Foundations.Hastad.SourceOccurrences MinUncut.SourceTemplate UEncoding +lemma 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 <;> rfl +lemma 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 <;> rfl +end MinUncut.Preprocess.Source + +end +namespace MinUncut.SourceTemplate +open MinUncutGames.Foundations MinUncutGames.Foundations.Target +open PCP Hastad Hastad.SourceContexts Hastad.SourceOccurrences +open MinUncutGames.Reduction MinUncut.Costed +noncomputable 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(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.tapes +lemma 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.CodeEffective +lemma 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] + rfl +end MinUncut.Preprocess.Syntax + +open scoped BigOperators +namespace MinUncut.Costed.SourceWords +open MinUncut.Inner MinUncut.Outer MinUncut.Outer.LocalTemplate +open MinUncut.PathRealization MinUncut.FiniteProof MinUncutGames.Reduction MinUncut.SourceBridge +open MinUncutGames.Foundations.Hastad.SourceOccurrences +attribute [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).symm +end MinUncut.Costed.SourceWords + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Estimates/UniformFaceArray.lean b/lean/OAI/Computability/MinUncut/Estimates/UniformFaceArray.lean new file mode 100644 index 0000000000000000000000000000000000000000..c7bab9307f9f56adea2a646e7e6dc470e3213af5 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Estimates/UniformFaceArray.lean @@ -0,0 +1,36 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.UniformEquation +import OAI.Computability.MinUncut.Machines.UniformAlphabet + +namespace OAI + +section +noncomputable section +namespace MinUncut.Preprocess.Alphabet +open MinUncut.Inner MinUncut.FiniteProof MinUncut.Outer +open UEncoding +variable {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,0FaceArray (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 + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Estimates/UniformGrid.lean b/lean/OAI/Computability/MinUncut/Estimates/UniformGrid.lean new file mode 100644 index 0000000000000000000000000000000000000000..d6e6b1f10f3f7058deae4ab3b8935e8696d72653 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Estimates/UniformGrid.lean @@ -0,0 +1,483 @@ +import Mathlib +import OAI.Computability.MinUncut.Search.ParameterFields +import OAI.Computability.MinUncut.Search.UniformRational +import OAI.Computability.MinUncut.Games.QuestionExpressions +import OAI.Computability.MinUncut.Estimates.UniformFaceArray +import OAI.Computability.MinUncut.Machines.UniformDemandAlphabet +import OAI.Computability.MinUncut.Estimates.UniformProduct + +namespace OAI + +noncomputable section +namespace MinUncut.Preprocess +open MinUncut.FiniteGaussian +open scoped BigOperators +lemma 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 primitive +lemma 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 Grid +open UEncoding MinUncut.Inner +variable {P : Type} [Primcodable P] +variable (m n : P → ℕ) (hm : Computable m) (hn : Computable n) (hnpos : ∀p,0TestCoordinates (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_midpoint +lemma 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_rawCellWeight +lemma 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_ratMul +end Grid +end MinUncut.Preprocess + +namespace MinUncut.Preprocess.Grid +open MinUncut.Inner MinUncut.FiniteGaussian UEncoding +variable {P : Type} [Primcodable P] +variable (m n : P → ℕ) (hm : Computable m) (hn : Computable n) (hnpos : ∀p,0midpoint (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_comp +lemma 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.Preprocess +open MinUncut.Inner MinUncut.FiniteProof MinUncut.FiniteGaussian MinUncut.Outer +open MinUncutGames.Foundations.Hastad.SourceOccurrences UEncoding +open scoped BigOperators +attribute [local irreducible] gridWeight +namespace UEncoding +variable {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).unit +end UEncoding +abbrev tests (P : Type) [Primcodable P] : UEncoding P (fun _=>Test) := + fixed SampleEnumeration.tests.encoding +instance primcodableTest : Primcodable Test := + Primcodable.ofEquiv (Fin SampleEnumeration.tests.encoding.size) SampleEnumeration.tests.encoding.code +namespace Weights +variable {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,0RowNoise.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_ratMul +lemma 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 Weights +namespace Denominator +variable {P : Type} [Primcodable P] +variable (t m n : P → ℕ) (ht : Computable t) (hm : Computable m) (hn : Computable n) (hnpos : ∀p,0faceCardBound (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 in +lemma 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 _ + rfl +lemma 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_comp +include ht hm hn hnpos hg in +lemma 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.FiniteGaussian +open MinUncutGames.Foundations.Hastad.SourceOccurrences UEncoding +namespace UEncoding +variable {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 <;> rfl +end UEncoding +namespace Queries +variable {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,0Query (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 hh +lemma 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 hh +lemma 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 in +lemma 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 in +lemma 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 in +lemma 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 Queries +end MinUncut.Preprocess + +namespace MinUncut.Preprocess.Queries +open MinUncut.Inner MinUncut.Outer MinUncut.Outer.LocalTemplate MinUncut.FiniteProof MinUncut.FiniteGaussian +open MinUncutGames.Foundations.Hastad.SourceOccurrences UEncoding +variable {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 hh +include hQ hp hs in +lemma 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 in +lemma 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 in +lemma 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 in +lemma 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 in +lemma 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 in +lemma 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 BigOperators +namespace MinUncut.Costed.SourceWords +open MinUncut.Inner MinUncut.Outer MinUncut.Outer.LocalTemplate +open 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 OAI diff --git a/lean/OAI/Computability/MinUncut/Estimates/UniformOutput.lean b/lean/OAI/Computability/MinUncut/Estimates/UniformOutput.lean new file mode 100644 index 0000000000000000000000000000000000000000..0f84e4b19aac8fe6af219b49a88d448525eaec74 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Estimates/UniformOutput.lean @@ -0,0 +1,27 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.UniformRestrict +import OAI.Computability.MinUncut.Estimates.UniformTransport + +namespace OAI + +section +namespace MinUncut.Preprocess.UEncoding +variable {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_comp +lemma 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_comp +end MinUncut.Preprocess.UEncoding + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Estimates/UniformProduct.lean b/lean/OAI/Computability/MinUncut/Estimates/UniformProduct.lean new file mode 100644 index 0000000000000000000000000000000000000000..8de8183592dc8981a2467314fd1122c46c403414 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Estimates/UniformProduct.lean @@ -0,0 +1,65 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.UniformRestrict + +namespace OAI + +section +namespace MinUncut.Preprocess +open MinUncutGames.Foundations.Hastad.SourceOccurrences +open scoped BigOperators +variable {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 UEncoding +variable {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] in +lemma 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 UEncoding +end MinUncut.Preprocess + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Estimates/UniformRestrict.lean b/lean/OAI/Computability/MinUncut/Estimates/UniformRestrict.lean new file mode 100644 index 0000000000000000000000000000000000000000..4eae55ba18cebb6660d2427bfca10b5e6496522c --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Estimates/UniformRestrict.lean @@ -0,0 +1,195 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.UniformBoolean + +namespace OAI + +namespace MinUncut.Preprocess +open MinUncutGames.Foundations.Hastad.SourceOccurrences +namespace UEncoding +variable {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 UEncoding +variable {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 x +lemma 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 hf +lemma 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 _).symm +lemma 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 := hf +lemma 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 UEncoding +end MinUncut.Preprocess + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Estimates/UniformSets.lean b/lean/OAI/Computability/MinUncut/Estimates/UniformSets.lean new file mode 100644 index 0000000000000000000000000000000000000000..bba5079c2c7ad74e95a065150f1c75dcc90eea6b --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Estimates/UniformSets.lean @@ -0,0 +1,59 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.UniformAlgebra +import OAI.Computability.MinUncut.Encoding.DerivedResolver +import OAI.Computability.MinUncut.Estimates.UniformOutput + +namespace OAI + +section +noncomputable section +namespace MinUncut.Preprocess +open MinUncut.Outer MinUncutGames.Foundations.Hastad.SourceOccurrences UEncoding +open scoped BigOperators +def 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 S +lemma 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) ht +lemma 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] + simp +lemma 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 + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Estimates/UniformTransport.lean b/lean/OAI/Computability/MinUncut/Estimates/UniformTransport.lean new file mode 100644 index 0000000000000000000000000000000000000000..3502acf110b127eb73fe1eeacd835f09a63cfcea --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Estimates/UniformTransport.lean @@ -0,0 +1,119 @@ +import Mathlib +import OAI.Computability.MinUncut.Encoding.UniformEncoding + +namespace OAI + +namespace MinUncut.Preprocess +open MinUncutGames.Foundations.Hastad.SourceOccurrences +namespace UEncoding +variable {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.computableSize +lemma 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 hf +lemma 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) hf +lemma 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 UEncoding +variable {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.computableSize +omit [Primcodable P] in +lemma 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 := rfl +omit [Primcodable P] in +lemma 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 := rfl +lemma 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 + 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 he +end UEncoding +end MinUncut.Preprocess + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Estimates/WeightedTestLaw.lean b/lean/OAI/Computability/MinUncut/Estimates/WeightedTestLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..6860a70a73620b09c662b6d15b6208d12c47dae4 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Estimates/WeightedTestLaw.lean @@ -0,0 +1,187 @@ +import Mathlib +import OAI.Computability.MinUncut.Search.FiniteAverageBounds +import OAI.Computability.MinUncut.Estimates.LiteralTestQueries +import OAI.Computability.MinUncut.Analysis.RationalRowNoise + +namespace OAI + +noncomputable section +open scoped BigOperators +namespace MinUncut.Outer +open MinUncut.Inner MinUncut.FiniteGaussian MinUncut.FiniteProof +attribute [local instance] Classical.propDecidable coordsDecEq +variable {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 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.Outer +open MinUncut.Inner MinUncut.FiniteGaussian MinUncut.FiniteProof OuterSmoothness +attribute [local instance] Classical.propDecidable coordsDecEq +variable {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 + (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 <;> rfl +end MinUncut.Outer + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Games/Actual.lean b/lean/OAI/Computability/MinUncut/Games/Actual.lean new file mode 100644 index 0000000000000000000000000000000000000000..b3741918fd3baf0fe1cf877dffc33d750f08f621 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Games/Actual.lean @@ -0,0 +1,688 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.Folding +import OAI.Computability.MinUncut.Encoding.BinaryLinear + +namespace OAI + +section +namespace 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 s +abbrev 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 + +end +section +namespace MinUncutGames.Reduction.Incidence + +universe u v +variable {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 + +end +section +namespace 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 + +end +section +namespace 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 + +end +section +namespace 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 OAI diff --git a/lean/OAI/Computability/MinUncut/Games/AdaptiveKernel.lean b/lean/OAI/Computability/MinUncut/Games/AdaptiveKernel.lean new file mode 100644 index 0000000000000000000000000000000000000000..03b5d1c07017ac5757e91a98d82c0b2584e0f20f --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Games/AdaptiveKernel.lean @@ -0,0 +1,83 @@ +import Mathlib +import OAI.Computability.MinUncut.Games.TripleKernel + +namespace OAI + +section +noncomputable section +open scoped BigOperators +namespace MinUncut.Composition +open BinaryFourier OuterSmoothness +attribute [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] in +lemma adaptiveKernel_abs (f : (J → V) → V → ℝ) {M u : ℝ} + (hM : 0≤M) (hu : 0 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] in +lemma 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 + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Games/AffineLabels.lean b/lean/OAI/Computability/MinUncut/Games/AffineLabels.lean new file mode 100644 index 0000000000000000000000000000000000000000..ef95482af17b6a02ac1b7d6418d54b9d233512a3 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Games/AffineLabels.lean @@ -0,0 +1,91 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.F2 + +namespace OAI + +section +noncomputable section +namespace MinUncut.Inner +open BinaryFourier +variable {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) := rfl +end MinUncut.Inner + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Games/Basic.lean b/lean/OAI/Computability/MinUncut/Games/Basic.lean new file mode 100644 index 0000000000000000000000000000000000000000..b5e8e79da5821b2a2b27a678d55e3984cac70f26 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Games/Basic.lean @@ -0,0 +1,684 @@ +import Mathlib +import 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 OAI diff --git a/lean/OAI/Computability/MinUncut/Games/FinalCNFHeader.lean b/lean/OAI/Computability/MinUncut/Games/FinalCNFHeader.lean new file mode 100644 index 0000000000000000000000000000000000000000..6f3e8efd700d79f4d7c1ceefccb8503cabfb5cfb --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Games/FinalCNFHeader.lean @@ -0,0 +1,733 @@ +import Mathlib +import OAI.Computability.MinUncut.Games.FinalCNFPattern +import OAI.Computability.MinUncut.Machines.RawInitialMachineFinish + +namespace OAI + +namespace MinUncutGames.Foundations.Complexity.FinalCNFMachine.Program + +open Turing +open 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 OAI diff --git a/lean/OAI/Computability/MinUncut/Games/FinalCNFOutput.lean b/lean/OAI/Computability/MinUncut/Games/FinalCNFOutput.lean new file mode 100644 index 0000000000000000000000000000000000000000..0ed7e0b5767e63d760645bb67640baba02351772 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Games/FinalCNFOutput.lean @@ -0,0 +1,406 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.PoweringFinalConstants +import 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 MachineComposition +open 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 OAI diff --git a/lean/OAI/Computability/MinUncut/Games/FinalCNFPattern.lean b/lean/OAI/Computability/MinUncut/Games/FinalCNFPattern.lean new file mode 100644 index 0000000000000000000000000000000000000000..5bbeba29246ca31c71793b142c3074d6b5775319 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Games/FinalCNFPattern.lean @@ -0,0 +1,103 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.FinalBooleanVerifier + +namespace OAI + +section +namespace MinUncutGames.Foundations.Complexity.FinalCNFPattern + +open PCP +open 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 OAI diff --git a/lean/OAI/Computability/MinUncut/Games/FinalCNFStream.lean b/lean/OAI/Computability/MinUncut/Games/FinalCNFStream.lean new file mode 100644 index 0000000000000000000000000000000000000000..4fd55c9009ab8a533552a79bece5ed4808797520 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Games/FinalCNFStream.lean @@ -0,0 +1,688 @@ +import Mathlib +import 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 OAI diff --git a/lean/OAI/Computability/MinUncut/Games/FiniteNoise.lean b/lean/OAI/Computability/MinUncut/Games/FiniteNoise.lean new file mode 100644 index 0000000000000000000000000000000000000000..8488d5631c67c55964c02073f8f86672441ad25f --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Games/FiniteNoise.lean @@ -0,0 +1,94 @@ +import Mathlib +import OAI.Computability.MinUncut.Encoding.ThreeBitTest + +namespace OAI + +section +namespace MinUncutGames.Reduction.FiniteNoise + +open scoped BigOperators +open 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] in +theorem 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 OAI diff --git a/lean/OAI/Computability/MinUncut/Games/GraphCounterModel.lean b/lean/OAI/Computability/MinUncut/Games/GraphCounterModel.lean new file mode 100644 index 0000000000000000000000000000000000000000..52c68552c326e30f3b4422ca68c47e226c6c6900 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Games/GraphCounterModel.lean @@ -0,0 +1,563 @@ +import Mathlib +import 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 ⊕ ExtraTape +abbrev Label := Fin 5 ⊕ ExtraLabel +abbrev Alphabet (_ : Tape) := Bool +abbrev 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 OAI diff --git a/lean/OAI/Computability/MinUncut/Games/GraphIterationBounds.lean b/lean/OAI/Computability/MinUncut/Games/GraphIterationBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..d478a942ea092fc2876d3764a5c76cd9c69f9a60 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Games/GraphIterationBounds.lean @@ -0,0 +1,77 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.TableIteration +import OAI.Computability.MinUncut.Games.GraphCounterModel +import OAI.Computability.MinUncut.Machines.PCPIterationMachine + +namespace OAI + +section +namespace 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 OAI diff --git a/lean/OAI/Computability/MinUncut/Games/HintSections.lean b/lean/OAI/Computability/MinUncut/Games/HintSections.lean new file mode 100644 index 0000000000000000000000000000000000000000..4cb35ee3f21cf18dd9149b2cd8b752d7ef5945d4 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Games/HintSections.lean @@ -0,0 +1,83 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.OuterSampling +import OAI.Computability.MinUncut.Estimates.PatchExpectation + +namespace OAI + +section +noncomputable section +open scoped BigOperators +namespace MinUncut.Outer +open MinUncut.Inner +attribute [local instance] Classical.propDecidable +variable {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] in +lemma 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] in +lemma 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 + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Games/HintSimulation.lean b/lean/OAI/Computability/MinUncut/Games/HintSimulation.lean new file mode 100644 index 0000000000000000000000000000000000000000..217841400432193d259fb93c7337d01f748ce194 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Games/HintSimulation.lean @@ -0,0 +1,154 @@ +import Mathlib +import OAI.Computability.MinUncut.Games.Sampling + +namespace OAI + +noncomputable section +open scoped BigOperators +namespace MinUncut.Outer +open MinUncut.Inner +attribute [local instance] Classical.propDecidable +variable {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] in +lemma 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] in +lemma 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.Outer +open MinUncut.Inner +attribute [local instance] Classical.propDecidable +variable {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 OAI diff --git a/lean/OAI/Computability/MinUncut/Games/HintSoundness.lean b/lean/OAI/Computability/MinUncut/Games/HintSoundness.lean new file mode 100644 index 0000000000000000000000000000000000000000..5759ee446cc1bc7e7d985eee9224b38752fd91dd --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Games/HintSoundness.lean @@ -0,0 +1,74 @@ +import Mathlib +import OAI.Computability.MinUncut.Games.HintSections +import OAI.Computability.MinUncut.Estimates.CoefficientMoments + +namespace OAI + +section +noncomputable section +open scoped BigOperators +namespace MinUncut.Outer +open MinUncut.Inner +attribute [local instance] Classical.propDecidable BinaryFourier.dualFintype +variable {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] in +lemma 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 + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Games/IncidenceProbability.lean b/lean/OAI/Computability/MinUncut/Games/IncidenceProbability.lean new file mode 100644 index 0000000000000000000000000000000000000000..b9ec84ba2235b772158988a247c6204d82f3e678 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Games/IncidenceProbability.lean @@ -0,0 +1,527 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.SamplerAssembly +import OAI.Computability.MinUncut.Games.Actual + +namespace OAI + +section +namespace MinUncutGames.Reduction.IncidenceProbability + +variable {Variable : Type*} {Index : Type*} {I : Type*} {Coin : Type*} + +open Incidence +open 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.Games +open 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 + +end +section +namespace 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 OAI diff --git a/lean/OAI/Computability/MinUncut/Games/JointCoefficient.lean b/lean/OAI/Computability/MinUncut/Games/JointCoefficient.lean new file mode 100644 index 0000000000000000000000000000000000000000..03afb1d4e443b4ca72ce0e0a9320e80029ea5550 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Games/JointCoefficient.lean @@ -0,0 +1,86 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.Parity + +namespace OAI + +noncomputable section +open scoped BigOperators +open MeasureTheory ProbabilityTheory Filter +open scoped Topology NNReal +open scoped BigOperators +open MeasureTheory ProbabilityTheory Polynomial Filter +open scoped BigOperators Topology +open MeasureTheory ProbabilityTheory WithLp +open scoped BigOperators RealInnerProductSpace +namespace MinUncut.Inner +open MeasureTheory ProbabilityTheory +open scoped BigOperators +variable {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] in +lemma 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 OAI diff --git a/lean/OAI/Computability/MinUncut/Games/JointHintBound.lean b/lean/OAI/Computability/MinUncut/Games/JointHintBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..34bca07d82ea6631181d4178ab82559a7d0b4cff --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Games/JointHintBound.lean @@ -0,0 +1,141 @@ +import Mathlib +import OAI.Computability.MinUncut.Games.JointHintSampling +import OAI.Computability.MinUncut.Estimates.PatchDensity + +namespace OAI + +noncomputable section +open scoped BigOperators +namespace MinUncut.Outer +open MinUncut.Inner OuterSmoothness +attribute [local instance] Classical.propDecidable BinaryFourier.dualFintype +variable {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.Outer +open MinUncut.Inner OuterSmoothness +attribute [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 OAI diff --git a/lean/OAI/Computability/MinUncut/Games/JointHintSampling.lean b/lean/OAI/Computability/MinUncut/Games/JointHintSampling.lean new file mode 100644 index 0000000000000000000000000000000000000000..dbf0626f19bc098dc88716bce39483eea0dc0963 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Games/JointHintSampling.lean @@ -0,0 +1,74 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.ListDecoding + +namespace OAI + +section +noncomputable section +open scoped BigOperators +namespace MinUncut.Outer +open MinUncut.Inner OuterSmoothness +attribute [local instance] Classical.propDecidable BinaryFourier.dualFintype +variable {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.1 +def 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] in +lemma 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 + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Games/JointInner.lean b/lean/OAI/Computability/MinUncut/Games/JointInner.lean new file mode 100644 index 0000000000000000000000000000000000000000..93476d0c4c2e56a077559707f023a0bcd75063fe --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Games/JointInner.lean @@ -0,0 +1,208 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.SelectedProject + +namespace OAI + +noncomputable section +open scoped BigOperators +open MeasureTheory ProbabilityTheory Filter +open scoped Topology NNReal +open scoped BigOperators +open MeasureTheory ProbabilityTheory Polynomial Filter +open scoped BigOperators Topology +open MeasureTheory ProbabilityTheory WithLp +open scoped BigOperators RealInnerProductSpace +open scoped BigOperators +namespace MinUncut.RowNoise +open MeasureTheory ProbabilityTheory BinaryFourier GaussianHermite +open scoped BigOperators +local instance jointInnerDualFintype {U : Type*} [AddCommGroup U] [Module F₂ U] [Fintype U] : + Fintype (Module.Dual F₂ U) := BinaryFourier.dualFintype +variable {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] in +lemma 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] in +lemma 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] in +lemma 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] in +lemma 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] in +lemma 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] in +lemma 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] in +lemma 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] in +lemma 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 _ u +end MinUncut.RowNoise + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Games/KernelSampling.lean b/lean/OAI/Computability/MinUncut/Games/KernelSampling.lean new file mode 100644 index 0000000000000000000000000000000000000000..67ad37a99352cfe80f605cec27cfe8d176dc94c2 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Games/KernelSampling.lean @@ -0,0 +1,208 @@ +import Mathlib +import OAI.Computability.MinUncut.Games.OuterQuestions + +namespace OAI + +namespace MinUncutGames.Foundations.Games + +open scoped BigOperators +noncomputable 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 q +def 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 KernelSampling +end +end MinUncutGames.Foundations.Games + +namespace MinUncutGames.Foundations.Games.FiniteDistribution + +open scoped BigOperators +noncomputable 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] + +end +end MinUncutGames.Foundations.Games.FiniteDistribution + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Games/LabelBound.lean b/lean/OAI/Computability/MinUncut/Games/LabelBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..0b6cabcd716af94faefa6c1a7c3ceb9592ee9667 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Games/LabelBound.lean @@ -0,0 +1,267 @@ +import Mathlib +import 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 σ] in +theorem 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 OAI diff --git a/lean/OAI/Computability/MinUncut/Games/MaskRowKernel.lean b/lean/OAI/Computability/MinUncut/Games/MaskRowKernel.lean new file mode 100644 index 0000000000000000000000000000000000000000..843659bfb54e16832883502d35a5b81c3acfd188 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Games/MaskRowKernel.lean @@ -0,0 +1,143 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.Density +import OAI.Computability.MinUncut.Estimates.Convolution + +namespace OAI + +noncomputable section +open scoped BigOperators +open MeasureTheory ProbabilityTheory Filter +open scoped Topology NNReal +open scoped BigOperators +open MeasureTheory ProbabilityTheory Polynomial Filter +open scoped BigOperators Topology +open MeasureTheory ProbabilityTheory WithLp +open scoped BigOperators RealInnerProductSpace +namespace MinUncut.RowNoise +open BinaryFourier +open scoped BigOperators +local instance maskRowKernelDualFintype {U : Type*} [AddCommGroup U] [Module F₂ U] [Fintype U] : + Fintype (Module.Dual F₂ U) := BinaryFourier.dualFintype +variable {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] in +lemma 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] in +lemma 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] in +lemma 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] in +lemma 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] in +lemma 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 _ _ _).symm +end MinUncut.RowNoise + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Games/OuterQuestions.lean b/lean/OAI/Computability/MinUncut/Games/OuterQuestions.lean new file mode 100644 index 0000000000000000000000000000000000000000..420fce1917fc0266fc15da4ed1460d0c7aa2a1f5 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Games/OuterQuestions.lean @@ -0,0 +1,757 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.FaceUpdateSelf +import OAI.Computability.MinUncut.Games.AffineLabels +import OAI.Computability.MinUncut.Machines.OuterAlphabets + +namespace OAI + +noncomputable section +open scoped BigOperators +namespace MinUncut.Outer +open MinUncut.Inner +attribute [local instance] Classical.propDecidable +variable {Name I : Type*} + +abbrev SecondQuestion (Name : Type*) := Name ⊕ Equation Name + +def secondSlotCount : SecondQuestion Name → ℕ + | .inl _ => 1 + | .inr _ => 3 +abbrev 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)).direction +abbrev 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.Inner +attribute [local instance] Classical.propDecidable +variable {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 + +end +namespace 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₂] in +theorem 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 FiniteDistribution +variable {Ω Γ 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 Game +variable {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₂] in +theorem 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 Game +end +end MinUncutGames.Foundations.Games + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Games/Parameters.lean b/lean/OAI/Computability/MinUncut/Games/Parameters.lean new file mode 100644 index 0000000000000000000000000000000000000000..6f7c722975fba1f675bdcf1d5075fa9f3814ee88 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Games/Parameters.lean @@ -0,0 +1,110 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.SelectionSequence +import OAI.Computability.MinUncut.PCP.Game + +namespace OAI + +section +namespace 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 OAI diff --git a/lean/OAI/Computability/MinUncut/Games/Pinsker.lean b/lean/OAI/Computability/MinUncut/Games/Pinsker.lean new file mode 100644 index 0000000000000000000000000000000000000000..4f7dec32163126f757888ce68ba89b4e94daea25 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Games/Pinsker.lean @@ -0,0 +1,517 @@ +import Mathlib +import 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 OAI diff --git a/lean/OAI/Computability/MinUncut/Games/PoweringGlobalEnumeration.lean b/lean/OAI/Computability/MinUncut/Games/PoweringGlobalEnumeration.lean new file mode 100644 index 0000000000000000000000000000000000000000..20ae1f3b5777f25225f28f14570d24bb0fa757cb --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Games/PoweringGlobalEnumeration.lean @@ -0,0 +1,91 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.PoweringMachineRotor + +namespace OAI + +section +namespace 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 OAI diff --git a/lean/OAI/Computability/MinUncut/Games/PoweringInitializeFrame.lean b/lean/OAI/Computability/MinUncut/Games/PoweringInitializeFrame.lean new file mode 100644 index 0000000000000000000000000000000000000000..390a069fa79d3edd4dd89b82a17433f2b07addc1 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Games/PoweringInitializeFrame.lean @@ -0,0 +1,222 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.PoweringMachineGlobal + +namespace OAI + +namespace MinUncutGames.Foundations.Complexity.PoweringInitializeFrame + +open Turing PCP + +variable {vertices d : Nat} + +def initialExtra (graph : PortTables.Table vertices d) (n : Nat) : + PoweringMachineInitialize.ExtraTape (PoweringMachineRowBody.capacity n) → List Bool := + fun tape => if tape = .inl (PoweringMachineTapes.table (PoweringMachineRowBody.capacity n)) + then PortTables.tableBits graph else [] + +@[simp] theorem initialExtra_table (graph : PortTables.Table vertices d) (n : Nat) : + initialExtra graph n (.inl (PoweringMachineTapes.table (PoweringMachineRowBody.capacity n))) = + PortTables.tableBits graph := by simp [initialExtra] + +theorem initialExtra_other (graph : PortTables.Table vertices d) (n : Nat) + (tape : PoweringMachineInitialize.ExtraTape (PoweringMachineRowBody.capacity n)) + (hne : tape ≠ .inl (PoweringMachineTapes.table (PoweringMachineRowBody.capacity n))) : + initialExtra graph n tape = [] := by simp [initialExtra, hne] + +@[simp] theorem initialExtra_scratch (graph : PortTables.Table vertices d) (n : Nat) : + initialExtra graph n + (.inl (PoweringMachineTapes.scratch (PoweringMachineRowBody.capacity n))) = [] := by + simp [initialExtra, PoweringMachineTapes.table, PoweringMachineTapes.scratch] + +def preparedTapes (graph : PortTables.Table vertices d) (n : Nat) : + PoweringMachineGlobal.Tape n → List Bool := + PoweringMachineInitialize.mergeTapes + (PoweringMachineLoop.finalTapes (PoweringTableLayout.blockSize d n) vertices []) + (initialExtra graph n) + +theorem prepared_commonRole (graph : PortTables.Table vertices d) (n : Nat) + (j : Fin 11) (hne : j ≠ 1) : + preparedTapes graph n (PoweringMachineGlobal.placement n (.inl j)) = + if j = 0 then PortTables.tableBits graph else [] := by + simp [preparedTapes, PoweringMachineGlobal.placement, + PoweringMachineInitialize.commonPlacement, PoweringMachineTapes.start, + PoweringMachineInitialize.mergeTapes, initialExtra, PoweringMachineTapes.table, hne] + +theorem prepared_ready (graph : PortTables.Table vertices d) (n : Nat) : + PoweringMachineOuterLoop.Ready graph n (PoweringMachineGlobal.placement n) + (preparedTapes graph n) := by + constructor + · simpa using prepared_commonRole graph n 0 (by decide) + · simpa using prepared_commonRole graph n 5 (by decide) + · simpa using prepared_commonRole graph n 8 (by decide) + · simpa using prepared_commonRole graph n 9 (by decide) + · simpa using prepared_commonRole graph n 10 (by decide) + +@[simp] theorem prepared_start (graph : PortTables.Table vertices d) (n : Nat) : + preparedTapes graph n (PoweringMachineGlobal.placement n (.inl 1)) = + encodeWord vertices := by + simpa only [preparedTapes, PoweringMachineGlobal.placement, PoweringMachineTapes.start] using + PoweringMachineInitialize.final_counter (PoweringMachineRowBody.capacity n) + (PoweringTableLayout.blockSize d n) vertices (initialExtra graph n) + +theorem prepared_counter (graph : PortTables.Table vertices d) (n : Nat) : + PoweringMachineOuterLoop.counter (PoweringMachineGlobal.placement n) + (preparedTapes graph n) vertices = preparedTapes graph n := by + unfold PoweringMachineOuterLoop.counter MachineUnaryCounter.counterTapes + rw [List.append_nil, ← prepared_start graph n] + simp only [Function.update_eq_self] + +@[simp] theorem prepared_output (graph : PortTables.Table vertices d) (n : Nat) : + preparedTapes graph n (PoweringMachineGlobal.outputTape n) = [] := by + simp [preparedTapes, PoweringMachineGlobal.outputTape, PoweringMachineInitialize.finalOutput, + PoweringMachineInitialize.mergeTapes, initialExtra] + +@[simp] theorem prepared_vertices (graph : PortTables.Table vertices d) (n : Nat) : + preparedTapes graph n (PoweringMachineGlobal.headerVertices n) = encodeWord vertices := rfl + +@[simp] theorem prepared_darts (graph : PortTables.Table vertices d) (n : Nat) : + preparedTapes graph n (PoweringMachineGlobal.headerDarts n) = + encodeWord (PoweringTableLayout.blockSize d n * vertices) := rfl + +@[simp] theorem prepared_source (graph : PortTables.Table vertices d) (n : Nat) : + preparedTapes graph n (.inl PoweringMachineLoop.HeaderTape.source) = [] := rfl + +def preparedCfg (graph : PortTables.Table vertices d) (n : Nat) : + (PoweringMachineGlobal.machine d n).Cfg := + ⟨some (PoweringMachineGlobal.guardLabel d n), + PoweringMasterState.clean (PoweringMachineRowBody.bufferSize d n), preparedTapes graph n⟩ + +theorem initialGlobalTapes_eq (graph : PortTables.Table vertices d) (n : Nat) : + PoweringMachineInitialize.initialGlobalTapes (initialExtra graph n) = + fun tape => if tape = PoweringMachineGlobal.inputTape n + then PortTables.tableBits graph else [] := by + funext tape + cases tape with + | inl field => + simp [PoweringMachineInitialize.initialGlobalTapes, PoweringMachineInitialize.mergeTapes, + PoweringMachineGlobal.inputTape, PoweringMachineGlobal.placement, + PoweringMachineInitialize.commonPlacement_table] + | inr field => + simp [PoweringMachineInitialize.initialGlobalTapes, PoweringMachineInitialize.mergeTapes, + PoweringMachineGlobal.inputTape, PoweringMachineGlobal.placement, + PoweringMachineInitialize.commonPlacement_table, initialExtra] + +private theorem machine_initialStacks (d n : Nat) (input : List Bool) : + (initList (PoweringMachineGlobal.machine d n) input).stk = + fun tape => if tape = PoweringMachineGlobal.inputTape n then input else [] := by + funext tape + rfl + +theorem initList_eq (graph : PortTables.Table vertices d) (n : Nat) : + initList (PoweringMachineGlobal.machine d n) (PortTables.tableBits graph) = + ⟨some (PoweringMachineGlobal.main d n), + PoweringMasterState.clean (PoweringMachineRowBody.bufferSize d n), + PoweringMachineInitialize.initialGlobalTapes (initialExtra graph n)⟩ := by + have ht := (machine_initialStacks d n (PortTables.tableBits graph)).trans + (initialGlobalTapes_eq graph n).symm + exact congrArg (TM2.Cfg.mk _ _) ht + +theorem tableBits_head (graph : PortTables.Table vertices d) : + PortTables.tableBits graph = encodeWord vertices ++ + encodeWords (PortTables.tableWords graph).tail := rfl + +def initializeInTime (graph : PortTables.Table vertices d) (n : Nat) : + StateTransition.EvalsToInTime (PoweringMachineGlobal.machine d n).step + (initList (PoweringMachineGlobal.machine d n) (PortTables.tableBits graph)) + (some (preparedCfg graph n)) (3 * vertices + 5) := by + rw [initList_eq] + exact PoweringMachineInitialize.initializeAtInTime + (PoweringMachineRowBody.capacity n) (PoweringMachineRowBody.bufferSize d n) + (PoweringTableLayout.blockSize d n) vertices + (PoweringMachineGlobal.initLabels d n) (some (PoweringMachineGlobal.guardLabel d n)) + (PoweringMachineGlobal.program d n) (PoweringMachineGlobal.atInit d n) + (initialExtra graph n) (encodeWords (PortTables.tableWords graph).tail) + (by rw [initialExtra_table, tableBits_head]) (initialExtra_scratch graph n) + (PoweringMasterState.clean (PoweringMachineRowBody.bufferSize d n)) + +end MinUncutGames.Foundations.Complexity.PoweringInitializeFrame + +namespace MinUncutGames.Foundations.Complexity.PoweringGlobalConfiguration + +open Turing PoweringMachineGlobal + +theorem placement_injective (n : Nat) : Function.Injective (placement n) := + PoweringMachineInitialize.commonPlacement_injective (PoweringMachineRowBody.capacity n) + +theorem placement_ne_output (n : Nat) + (tape : PoweringMachineTapes.Tape (PoweringMachineRowBody.capacity n)) : + placement n tape ≠ outputTape n := + PoweringMachineInitialize.commonPlacement_ne_finalOutput + (PoweringMachineRowBody.capacity n) tape + +theorem output_ne_placement (n : Nat) + (tape : PoweringMachineTapes.Tape (PoweringMachineRowBody.capacity n)) : + outputTape n ≠ placement n tape := Ne.symm (placement_ne_output n tape) + +theorem headerVertices_ne_placement (n : Nat) + (tape : PoweringMachineTapes.Tape (PoweringMachineRowBody.capacity n)) : + headerVertices n ≠ placement n tape := + Ne.symm (PoweringMachineInitialize.commonPlacement_ne_header + (PoweringMachineRowBody.capacity n) tape .vertices (by decide)) + +theorem headerDarts_ne_placement (n : Nat) + (tape : PoweringMachineTapes.Tape (PoweringMachineRowBody.capacity n)) : + headerDarts n ≠ placement n tape := + Ne.symm (PoweringMachineInitialize.commonPlacement_ne_header + (PoweringMachineRowBody.capacity n) tape .darts (by decide)) + +theorem placement_ne_headerVertices (n : Nat) + (tape : PoweringMachineTapes.Tape (PoweringMachineRowBody.capacity n)) : + placement n tape ≠ headerVertices n := Ne.symm (headerVertices_ne_placement n tape) + +theorem placement_ne_headerDarts (n : Nat) + (tape : PoweringMachineTapes.Tape (PoweringMachineRowBody.capacity n)) : + placement n tape ≠ headerDarts n := Ne.symm (headerDarts_ne_placement n tape) + +theorem headerVertices_ne_headerDarts (n : Nat) : headerVertices n ≠ headerDarts n := by + simp [headerVertices, headerDarts] + +theorem headerVertices_ne_output (n : Nat) : headerVertices n ≠ outputTape n := by + simp [headerVertices, outputTape, PoweringMachineInitialize.finalOutput] + +theorem headerDarts_ne_output (n : Nat) : headerDarts n ≠ outputTape n := by + simp [headerDarts, outputTape, PoweringMachineInitialize.finalOutput] + +theorem headerVertices_ne_scratch (n : Nat) : + headerVertices n ≠ + placement n (PoweringMachineTapes.scratch (PoweringMachineRowBody.capacity n)) := + headerVertices_ne_placement n _ + +theorem headerDarts_ne_scratch (n : Nat) : + headerDarts n ≠ + placement n (PoweringMachineTapes.scratch (PoweringMachineRowBody.capacity n)) := + headerDarts_ne_placement n _ + +theorem scratch_ne_output (n : Nat) : + placement n (PoweringMachineTapes.scratch (PoweringMachineRowBody.capacity n)) ≠ + outputTape n := + placement_ne_output n _ + +@[simp] theorem boolList_mpr_eq (h : List Bool = List Bool) (bits : List Bool) : + h.mpr bits = bits := rfl + +theorem haltList_tapes (d n : Nat) (output : List Bool) : + (Turing.haltList (machine d n) output).stk = + MachineDrainMany.haltTapes (outputTape n) output := by + funext tape + simp only [machine] + rfl + +theorem haltList_eq (d n : Nat) (output : List Bool) : + Turing.haltList (machine d n) output = + (⟨none, PoweringMasterState.clean (PoweringMachineRowBody.bufferSize d n), + MachineDrainMany.haltTapes (outputTape n) output⟩ : (machine d n).Cfg) := by + change (⟨none, PoweringMasterState.clean (PoweringMachineRowBody.bufferSize d n), + (Turing.haltList (machine d n) output).stk⟩ : (machine d n).Cfg) = _ + exact congrArg + (fun tapes => (⟨none, PoweringMasterState.clean (PoweringMachineRowBody.bufferSize d n), + tapes⟩ : (machine d n).Cfg)) (haltList_tapes d n output) + +end MinUncutGames.Foundations.Complexity.PoweringGlobalConfiguration + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Games/PoweringMasterState.lean b/lean/OAI/Computability/MinUncut/Games/PoweringMasterState.lean new file mode 100644 index 0000000000000000000000000000000000000000..fd87eae635717c7d26e6905772088b11e3193528 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Games/PoweringMasterState.lean @@ -0,0 +1,157 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineFiniteAlphabet +import OAI.Computability.MinUncut.Machines.PoweringMachineRow + +namespace OAI + +section +namespace MinUncutGames.Foundations.Complexity.PoweringMasterState + +open Turing +open MachineFixedBlockMap + +abbrev OtherRegisters (N : Nat) := Buffer N × (Bool × Option Bool) +abbrev Master (N : Nat) := OtherRegisters N × Option Bool +abbrev CompareState (N : Nat) := Buffer N × (Bool × (Option Bool × Option Bool)) +abbrev RowState (N : Nat) := (Bool × (Option Bool × Option Bool)) × Buffer N + +def compareEquiv (N : Nat) : Master N ≃ CompareState N := + (MachineUnaryEqualityBit.compareStateEquiv (Buffer N)).symm + +def rowEquiv (N : Nat) : Master N ≃ RowState N where + toFun state := ((state.1.2.1, (state.1.2.2, state.2)), state.1.1) + invFun state := ((state.2, (state.1.1, state.1.2.1)), state.1.2.2) + left_inv := by rintro ⟨⟨buffer, ⟨flag, left⟩⟩, right⟩; rfl + right_inv := by rintro ⟨⟨flag, ⟨left, right⟩⟩, buffer⟩; rfl + +@[simp] theorem compareEquiv_apply (N : Nat) (buffer : Buffer N) + (flag : Bool) (left right : Option Bool) : + compareEquiv N ((buffer, (flag, left)), right) = (buffer, (flag, (left, right))) := rfl + +@[simp] theorem compareEquiv_symm_apply (N : Nat) (buffer : Buffer N) + (flag : Bool) (left right : Option Bool) : + (compareEquiv N).symm (buffer, (flag, (left, right))) = ((buffer, (flag, left)), right) := rfl + +@[simp] theorem rowEquiv_apply (N : Nat) (buffer : Buffer N) + (flag : Bool) (left right : Option Bool) : + rowEquiv N ((buffer, (flag, left)), right) = ((flag, (left, right)), buffer) := rfl + +@[simp] theorem rowEquiv_symm_apply (N : Nat) (buffer : Buffer N) + (flag : Bool) (left right : Option Bool) : + (rowEquiv N).symm ((flag, (left, right)), buffer) = ((buffer, (flag, left)), right) := rfl + +def withBuffer {N : Nat} (buffer : Buffer N) : Master N := + ((buffer, (false, none)), none) + +def clean (N : Nat) : Master N := withBuffer (emptyBuffer N) + +@[simp] theorem equalityBit_clean {N : Nat} (buffer : Buffer N) : + MachineUnaryEqualityBit.clean buffer = withBuffer buffer := rfl + +@[simp] theorem rowEquiv_withBuffer {N : Nat} (buffer : Buffer N) : + rowEquiv N (withBuffer buffer) = ((false, (none, none)), buffer) := rfl + +@[simp] theorem compareEquiv_withBuffer {N : Nat} (buffer : Buffer N) : + compareEquiv N (withBuffer buffer) = (buffer, (false, (none, none))) := rfl + +def clearBuffer {N : Nat} (state : Master N) : Master N := + (rowEquiv N).symm ((rowEquiv N state).1, emptyBuffer N) + +@[simp] theorem clearBuffer_apply {N : Nat} (buffer : Buffer N) + (flag : Bool) (left right : Option Bool) : + clearBuffer ((buffer, (flag, left)), right) = + ((emptyBuffer N, (flag, left)), right) := rfl + +@[simp] theorem clearBuffer_withBuffer {N : Nat} (buffer : Buffer N) : + clearBuffer (withBuffer buffer) = clean N := rfl + +section Row + +variable {K Λ : Type} [DecidableEq K] {N M : Nat} + +def encodedBlockAt (src dst : K) (F : Buffer N → Buffer M) (exit : Option Λ) : + TM2.Stmt (fun _ : K => Bool) Λ (Master N) := + MachineStateEquiv.statement (rowEquiv N).symm + (PoweringMachineRow.encodedBlockAt src dst F exit) + +theorem stepAux_encodedBlockAt (src dst : K) (F : Buffer N → Buffer M) + (exit : Option Λ) (hne : src ≠ dst) (bits : Buffer N) (suffix : List Bool) + (state : Master N) (tapes : K → List Bool) + (hinput : tapes src = PoweringMachineRow.encodeBits (List.ofFn bits) ++ suffix) : + TM2.stepAux (encodedBlockAt src dst F exit) state tapes = + { l := exit, var := clearBuffer state, + stk := Function.update (Function.update tapes src suffix) dst + (PoweringMachineRow.encodeBits (List.ofFn (F bits)) ++ tapes dst) } := by + rw [encodedBlockAt, MachineStateEquiv.stepAux_transport_symm, Equiv.symm_symm] + rw [PoweringMachineRow.stepAux_encodedBlockAt src dst F exit hne bits suffix + (rowEquiv N state) tapes hinput] + rfl + +theorem step_encodedBlockAt (src dst : K) (F : Buffer N → Buffer M) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (Master N)) + (label : Λ) (atLabel : program label = encodedBlockAt src dst F exit) + (hne : src ≠ dst) (bits : Buffer N) (suffix : List Bool) + (state : Master N) (tapes : K → List Bool) + (hinput : tapes src = PoweringMachineRow.encodeBits (List.ofFn bits) ++ suffix) : + TM2.step program ⟨some label, state, tapes⟩ = + some ⟨exit, clearBuffer state, + Function.update (Function.update tapes src suffix) dst + (PoweringMachineRow.encodeBits (List.ofFn (F bits)) ++ tapes dst)⟩ := by + simp only [TM2.step, atLabel, stepAux_encodedBlockAt src dst F exit hne bits suffix state tapes hinput] + +def rowAt {t S q : Nat} (src dst : K) + (labelAt : Fin q → Fin S → PCP.GraphTables.Label) (exit : Option Λ) : + TM2.Stmt (fun _ : K => Bool) Λ (Master (PoweringMachineRow.inputSize t S)) := + encodedBlockAt src dst (PoweringMachineRow.rowBlock labelAt) exit + +theorem step_rowAt_clean {t S q : Nat} (src dst : K) + (labelAt : Fin q → Fin S → PCP.GraphTables.Label) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ + (Master (PoweringMachineRow.inputSize t S))) + (label : Λ) (atLabel : program label = rowAt (t := t) src dst labelAt exit) + (hne : src ≠ dst) (bits register : Buffer (PoweringMachineRow.inputSize t S)) + (suffix : List Bool) (tapes : K → List Bool) + (hinput : tapes src = PoweringMachineRow.encodeBits (List.ofFn bits) ++ suffix) : + TM2.step program ⟨some label, withBuffer register, tapes⟩ = + some ⟨exit, clean (PoweringMachineRow.inputSize t S), + Function.update (Function.update tapes src suffix) dst + (PoweringMachineRow.encodeBits (List.ofFn (PoweringMachineRow.rowBlock labelAt bits)) ++ + tapes dst)⟩ := by + simpa only [rowAt, clearBuffer_withBuffer] using + step_encodedBlockAt src dst (PoweringMachineRow.rowBlock labelAt) exit + program label atLabel hne bits suffix (withBuffer register) tapes hinput + +def rowInTime {t S q : Nat} (src dst : K) + (labelAt : Fin q → Fin S → PCP.GraphTables.Label) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ + (Master (PoweringMachineRow.inputSize t S))) + (label : Λ) (atLabel : program label = rowAt (t := t) src dst labelAt exit) + (hne : src ≠ dst) (bits register : Buffer (PoweringMachineRow.inputSize t S)) + (suffix : List Bool) (tapes : K → List Bool) + (hinput : tapes src = PoweringMachineRow.encodeBits (List.ofFn bits) ++ suffix) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some label, withBuffer register, tapes⟩ + (some ⟨exit, clean (PoweringMachineRow.inputSize t S), + Function.update (Function.update tapes src suffix) dst + (PoweringMachineRow.encodeBits (List.ofFn (PoweringMachineRow.rowBlock labelAt bits)) ++ + tapes dst)⟩) 1 where + steps := 1 + evals_in_steps := by + simpa only [Function.iterate_one, flip, bind, Option.bind] using + step_rowAt_clean src dst labelAt exit program label atLabel hne bits register suffix tapes hinput + steps_le_m := le_rfl + +end Row + +def headerInTime (N B n : Nat) (suffix : List Bool) (state : Master N) : + StateTransition.EvalsToInTime + (TM2.step (PoweringMachineLoop.headerProgram (σ := OtherRegisters N) B)) + ⟨some .initialize, state, PoweringMachineLoop.initialTapes n suffix⟩ + (some (PoweringMachineLoop.finalConfiguration B n suffix state.1)) (n + 2) := + PoweringMachineLoop.headerInTime B n suffix state.1 state.2 + +end MinUncutGames.Foundations.Complexity.PoweringMasterState + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Games/PoweringPlanBudget.lean b/lean/OAI/Computability/MinUncut/Games/PoweringPlanBudget.lean new file mode 100644 index 0000000000000000000000000000000000000000..3010df641c6fd5b622e5370c88450c6f11a4931b --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Games/PoweringPlanBudget.lean @@ -0,0 +1,131 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.PoweringMachineField + +namespace OAI + +section +namespace MinUncutGames.Foundations.Complexity.PoweringPlanBudget + +open Turing MachineComposition PCP PoweringFieldPlan + +variable {K Λ A : Type} [DecidableEq K] {vertices d max : Nat} + + +def fieldBudget (max inputLength : Nat) : Nat := + (28 * max + 10) * inputLength + 24 * max + 15 + +theorem field_steps_le (graph : PortTables.Table vertices d) (vertex : Fin vertices) + (op : Instruction d) (bounded : op.radius ≤ max) : + PoweringMachineField.steps graph vertex op ≤ + fieldBudget max (PortTables.tableBits graph).length := by + cases op with + | relation path port left right => + change path.length ≤ max at bounded + have h := PoweringMachineRelationField.steps_le path port left right graph vertex + have coefficient : 14 * path.length + 9 ≤ 28 * max + 10 := by omega + have product := Nat.mul_le_mul_right (PortTables.tableBits graph).length coefficient + change PoweringMachineRelationField.steps path port left right graph vertex ≤ _ + unfold fieldBudget + omega + | equal left right => + change Nat.max left.length right.length ≤ max at bounded + have hl : left.length ≤ max := (le_max_left _ _).trans bounded + have hr : right.length ≤ max := (le_max_right _ _).trans bounded + have h := PoweringMachineEqualityField.steps_le graph vertex left.get right.get + have coefficient : 14 * (left.length + right.length) + 10 ≤ 28 * max + 10 := by + omega + have product := Nat.mul_le_mul_right (PortTables.tableBits graph).length coefficient + change PoweringMachineEqualityField.steps graph vertex left.get right.get ≤ _ + unfold fieldBudget + omega + +theorem plan_steps_le (graph : PortTables.Table vertices d) + (placement : PoweringMachineTapes.Tape max → K) (vertex : Fin vertices) + (commands : List (PoweringMachinePlan.Command d max)) (base : K → List Bool) : + PoweringMachinePlan.steps graph placement vertex commands base ≤ + commands.length * fieldBudget max (PortTables.tableBits graph).length := by + induction commands generalizing base with + | nil => simp only [PoweringMachinePlan.steps, MachineFiniteSequence.steps, + List.length_nil, Nat.zero_mul, Nat.le_refl] + | cons op commands ih => + have first := field_steps_le graph vertex op.val op.property + have rest := ih (PoweringMachinePlan.result graph placement vertex op base) + change PoweringMachineField.steps graph vertex op.val + + PoweringMachinePlan.steps graph placement vertex commands + (PoweringMachinePlan.result graph placement vertex op base) ≤ _ + simpa only [List.length_cons, Nat.add_mul, Nat.one_mul, Nat.add_comm] using + Nat.add_le_add first rest + +@[simp] theorem boundedRowPlan_length (n : Nat) + (ports : Fin (n + 1) → Fin d) (direction : Bool) : + (PoweringMachinePlan.boundedRowPlan n ports direction).length = + PoweringMachineRow.inputSize (n + 1) (PoweringRowData.slotCount d n) := by + simp only [PoweringMachinePlan.boundedRowPlan, List.length_ofFn] + +def rowBudget (d n inputLength : Nat) : Nat := + PoweringMachineRow.inputSize (n + 1) (PoweringRowData.slotCount d n) * + fieldBudget (2 * (n + 1)) inputLength + +theorem rowPlan_steps_le (graph : PortTables.Table vertices d) (n : Nat) + (ports : Fin (n + 1) → Fin d) (direction : Bool) + (placement : PoweringMachineTapes.Tape (2 * (n + 1)) → K) + (vertex : Fin vertices) (base : K → List Bool) : + PoweringMachinePlan.steps graph placement vertex + (PoweringMachinePlan.boundedRowPlan n ports direction).reverse base ≤ + PoweringMachineRow.inputSize (n + 1) (PoweringRowData.slotCount d n) * + ((28 * (2 * (n + 1)) + 10) * (PortTables.tableBits graph).length + + 24 * (2 * (n + 1)) + 15) := by + have h := plan_steps_le graph placement vertex + (PoweringMachinePlan.boundedRowPlan n ports direction).reverse base + simpa only [List.length_reverse, boundedRowPlan_length, fieldBudget] using h + +def planInTime (graph : PortTables.Table vertices d) + (placement : PoweringMachineTapes.Tape max → K) (distinct : Function.Injective placement) + (vertex : Fin vertices) (commands : List (PoweringMachinePlan.Command d max)) + (labels : PoweringMachinePlan.Label commands → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (MachineUnaryEqualityBit.State A)) + (atLabels : ∀ l, program (labels l) = + PoweringMachinePlan.instruction placement commands labels exit l) + (base : K → List Bool) (suffix : List Bool) + (ready : PoweringMachineField.Ready graph placement vertex suffix base) (ambient : A) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨PoweringMachinePlan.entry commands labels exit, MachineUnaryEqualityBit.clean ambient, base⟩ + (some ⟨exit, MachineUnaryEqualityBit.clean ambient, + PoweringMachinePlan.finalTapes graph placement vertex commands base⟩) + (commands.length * fieldBudget max (PortTables.tableBits graph).length) where + steps := PoweringMachinePlan.steps graph placement vertex commands base + evals_in_steps := PoweringMachinePlan.planTrace graph placement distinct vertex commands + labels exit program atLabels base suffix ready ambient + steps_le_m := plan_steps_le graph placement vertex commands base + +def rowPlanInTime (graph : PortTables.Table vertices d) (n : Nat) + (ports : Fin (n + 1) → Fin d) (direction : Bool) + (placement : PoweringMachineTapes.Tape (2 * (n + 1)) → K) + (distinct : Function.Injective placement) (vertex : Fin vertices) + (labels : PoweringMachinePlan.Label + (PoweringMachinePlan.boundedRowPlan n ports direction).reverse → Λ) + (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (MachineUnaryEqualityBit.State A)) + (atLabels : ∀ l, program (labels l) = PoweringMachinePlan.instruction placement + (PoweringMachinePlan.boundedRowPlan n ports direction).reverse labels exit l) + (base : K → List Bool) (suffix : List Bool) + (ready : PoweringMachineField.Ready graph placement vertex suffix base) (ambient : A) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨PoweringMachinePlan.entry (PoweringMachinePlan.boundedRowPlan n ports direction).reverse + labels exit, MachineUnaryEqualityBit.clean ambient, base⟩ + (some ⟨exit, MachineUnaryEqualityBit.clean ambient, + PoweringMachinePlan.finalTapes graph placement vertex + (PoweringMachinePlan.boundedRowPlan n ports direction).reverse base⟩) + (rowBudget d n (PortTables.tableBits graph).length) where + steps := PoweringMachinePlan.steps graph placement vertex + (PoweringMachinePlan.boundedRowPlan n ports direction).reverse base + evals_in_steps := PoweringMachinePlan.planTrace graph placement distinct vertex + (PoweringMachinePlan.boundedRowPlan n ports direction).reverse + labels exit program atLabels base suffix ready ambient + steps_le_m := rowPlan_steps_le graph n ports direction placement vertex base + +end MinUncutGames.Foundations.Complexity.PoweringPlanBudget + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Games/PoweringPolynomialBudget.lean b/lean/OAI/Computability/MinUncut/Games/PoweringPolynomialBudget.lean new file mode 100644 index 0000000000000000000000000000000000000000..d42fd7f978844c6d232be842c735820301a2eb53 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Games/PoweringPolynomialBudget.lean @@ -0,0 +1,144 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.PoweringMachineVertex + +namespace OAI + +section +namespace MinUncutGames.Foundations.Complexity.PoweringPolynomialBudget + +open PCP + +def preBudget (d n vertices inputLength : Nat) : Nat := + (3 * vertices + 5) + + (vertices * (PoweringMachineVertex.budget d n inputLength + 2) + 1) + +def finishBudget (d n pushBound tapeCount vertices inputLength prior : Nat) : Nat := + 2 * (vertices + PoweringTableLayout.blockSize d n * vertices) + 6 + + tapeCount * (inputLength + prior * pushBound + vertices + + PoweringTableLayout.blockSize d n * vertices + 3) + +def totalBudget (d n pushBound tapeCount vertices inputLength : Nat) : Nat := + preBudget d n vertices inputLength + + finishBudget d n pushBound tapeCount vertices inputLength + (preBudget d n vertices inputLength) + +theorem preBudget_mono_vertices (d n inputLength : Nat) {v w : Nat} (h : v ≤ w) : + preBudget d n v inputLength ≤ preBudget d n w inputLength := by + have hthree := Nat.mul_le_mul_left 3 h + have hloop := Nat.mul_le_mul_right (PoweringMachineVertex.budget d n inputLength + 2) h + unfold preBudget + omega + +theorem finishBudget_mono (d n pushBound tapeCount inputLength : Nat) + {v w prior later : Nat} (hvertices : v ≤ w) (hprior : prior ≤ later) : + finishBudget d n pushBound tapeCount v inputLength prior ≤ + finishBudget d n pushBound tapeCount w inputLength later := by + have hdarts := Nat.mul_le_mul_left (PoweringTableLayout.blockSize d n) hvertices + have hheader := Nat.mul_le_mul_left 2 (Nat.add_le_add hvertices hdarts) + have hgrowth := Nat.mul_le_mul_right pushBound hprior + have hinside : inputLength + prior * pushBound + v + + PoweringTableLayout.blockSize d n * v + 3 ≤ + inputLength + later * pushBound + w + PoweringTableLayout.blockSize d n * w + 3 := by + omega + have hclear := Nat.mul_le_mul_left tapeCount hinside + unfold finishBudget + omega + +theorem totalBudget_mono_vertices (d n pushBound tapeCount inputLength : Nat) + {v w : Nat} (hvertices : v ≤ w) : + totalBudget d n pushBound tapeCount v inputLength ≤ + totalBudget d n pushBound tapeCount w inputLength := by + have hpre := preBudget_mono_vertices d n inputLength hvertices + unfold totalBudget + exact Nat.add_le_add hpre + (finishBudget_mono d n pushBound tapeCount inputLength hvertices hpre) + +noncomputable def rowTime (d n : Nat) : Polynomial Nat := + Polynomial.C (PoweringMachineRowBody.bufferSize d n) * + (Polynomial.C (28 * (2 * (n + 1)) + 10) * Polynomial.X + + Polynomial.C (24 * (2 * (n + 1)) + 15)) + Polynomial.C 1 + + (Polynomial.C (14 * (n + 1) + 4) * Polynomial.X + + Polynomial.C (12 * (n + 1)) + Polynomial.C 6) + +@[simp] theorem rowTime_eval (d n inputLength : Nat) : + (rowTime d n).eval inputLength = PoweringMachineRowBody.budget d n inputLength := by + simp only [rowTime, Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_C, + Polynomial.eval_X, PoweringMachineRowBody.budget, PoweringPlanBudget.rowBudget, + PoweringPlanBudget.fieldBudget, PoweringMachineRowBody.bufferSize, Nat.add_assoc] + +noncomputable def vertexTime (d n : Nat) : Polynomial Nat := + Polynomial.C (PoweringTableLayout.blockSize d n) * rowTime d n + +@[simp] theorem vertexTime_eval (d n inputLength : Nat) : + (vertexTime d n).eval inputLength = PoweringMachineVertex.budget d n inputLength := by + simp only [vertexTime, Polynomial.eval_mul, Polynomial.eval_C, rowTime_eval, + PoweringMachineVertex.budget] + +noncomputable def preTime (d n : Nat) : Polynomial Nat := + (Polynomial.C 3 * Polynomial.X + Polynomial.C 5) + + (Polynomial.X * (vertexTime d n + Polynomial.C 2) + Polynomial.C 1) + +@[simp] theorem preTime_eval (d n inputLength : Nat) : + (preTime d n).eval inputLength = preBudget d n inputLength inputLength := by + simp only [preTime, Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_C, + Polynomial.eval_X, vertexTime_eval, preBudget] + +noncomputable def time (d n pushBound tapeCount : Nat) : Polynomial Nat := + preTime d n + + (Polynomial.C 2 * + (Polynomial.X + Polynomial.C (PoweringTableLayout.blockSize d n) * Polynomial.X) + + Polynomial.C 6 + Polynomial.C tapeCount * + (Polynomial.X + preTime d n * Polynomial.C pushBound + Polynomial.X + + Polynomial.C (PoweringTableLayout.blockSize d n) * Polynomial.X + Polynomial.C 3)) + +@[simp] theorem time_eval (d n pushBound tapeCount inputLength : Nat) : + (time d n pushBound tapeCount).eval inputLength = + totalBudget d n pushBound tapeCount inputLength inputLength := by + simp only [time, Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_C, + Polynomial.eval_X, preTime_eval, totalBudget, finishBudget] + +theorem totalBudget_le_time (d n pushBound tapeCount vertices inputLength : Nat) + (hvertices : vertices ≤ inputLength) : + totalBudget d n pushBound tapeCount vertices inputLength ≤ + (time d n pushBound tapeCount).eval inputLength := by + rw [time_eval] + exact totalBudget_mono_vertices d n pushBound tapeCount inputLength hvertices + +theorem setup_loop_finish_le_time (d n pushBound tapeCount vertices inputLength : Nat) + (hvertices : vertices ≤ inputLength) : + ((3 * vertices + 5) + + (vertices * (PoweringMachineVertex.budget d n inputLength + 2) + 1)) + + (2 * (vertices + (2 * d ^ (n + 1)) * vertices) + 6 + + tapeCount * (inputLength + + ((3 * vertices + 5) + + (vertices * (PoweringMachineVertex.budget d n inputLength + 2) + 1)) * pushBound + + vertices + (2 * d ^ (n + 1)) * vertices + 3)) ≤ + (time d n pushBound tapeCount).eval inputLength := by + simpa only [totalBudget, preBudget, finishBudget, PoweringTableLayout.blockSize] using + totalBudget_le_time d n pushBound tapeCount vertices inputLength hvertices + +theorem execution_budget_le_time (d n pushBound tapeCount vertices inputLength : Nat) + (hvertices : vertices ≤ inputLength) {preSteps finishSteps : Nat} + (hpre : preSteps ≤ preBudget d n vertices inputLength) + (hfinish : finishSteps ≤ finishBudget d n pushBound tapeCount vertices inputLength + (preBudget d n vertices inputLength)) : + preSteps + finishSteps ≤ (time d n pushBound tapeCount).eval inputLength := by + calc + preSteps + finishSteps ≤ totalBudget d n pushBound tapeCount vertices inputLength := by + unfold totalBudget + exact Nat.add_le_add hpre hfinish + _ ≤ (time d n pushBound tapeCount).eval inputLength := + totalBudget_le_time d n pushBound tapeCount vertices inputLength hvertices + +theorem graph_totalBudget_le_time {vertices d : Nat} (graph : PortTables.Table vertices d) + (n pushBound tapeCount : Nat) : + totalBudget d n pushBound tapeCount vertices (PortTables.tableBits graph).length ≤ + (time d n pushBound tapeCount).eval (PortTables.tableBits graph).length := + totalBudget_le_time d n pushBound tapeCount vertices (PortTables.tableBits graph).length + (PortTables.vertices_le_tableBits_length graph) + +end MinUncutGames.Foundations.Complexity.PoweringPolynomialBudget + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Games/QuestionArithmetic.lean b/lean/OAI/Computability/MinUncut/Games/QuestionArithmetic.lean new file mode 100644 index 0000000000000000000000000000000000000000..429cf981cc39344ff78dd7da507d47ec9ad58f4c --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Games/QuestionArithmetic.lean @@ -0,0 +1,75 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.Bridge + +namespace OAI + +section +noncomputable section +open scoped BigOperators +namespace MinUncut.Outer.LocalTemplate +open MinUncut.Inner MinUncut.FiniteProof +open MinUncutGames.Foundations.Hastad.SourceOccurrences +variable {N t : ℕ} + +def equationNumber (E : Equation (Fin N)) : ℕ := + E.rhs.val+2*∑p : Fin 3, (E.names p).val*N^p.val + +def firstNumber (U : Fin t → Equation (Fin N)) : ℕ := + ∑i : Fin t,equationNumber (U i)*(N^3*2)^i.val + +def secondNumber (U : Fin t → Equation (Fin N)) (h : Fin t → Bool) (pos : Fin t → Fin 3) : ℕ := + ∑i : Fin t,(if h i then ((U i).names (pos i)).val else N+equationNumber (U i))*(N+N^3*2)^i.val + +lemma equation_code (E : Equation (Fin N)) : ((equationEncoding N).code E).val=equationNumber E := rfl +lemma first_code (U : Fin t → Equation (Fin N)) : + ((questionEncoding N t).code (.inl U)).val=firstNumber U := rfl +lemma second_code (U : Fin t → Equation (Fin N)) (h : Fin t → Bool) (pos : Fin t → Fin 3) : + ((questionEncoding N t).code (.inr (secondQuestion U h pos))).val= + (N^3*2)^t+secondNumber U h pos := by + change (N^3*2)^t+(∑i : Fin t, ((secondQuestionEncoding N).code (slotQuestion (U i) (h i) (pos i))).val*(N+N^3*2)^i.val)=_ + congr 1 + apply Finset.sum_congr rfl + intro i _ + cases h i <;> rfl + +def tableNumber (f : (Fin t → Triple) → Bool) : ℕ := + (((ambientEncoding t).function Encoding.bool).code f).val + +lemma variable_number (v : FamilyVariable (Fin N) (Fin t)) : + (variableCode v).val= tableNumber (extendTable v.1 v.2.val)+ + 2^((2^3)^t)*((questionEncoding N t).code v.1).val := rfl + +variable {h : Fin t → Bool} +def Query.leftNumber (T : Query h) (U : Fin t → Equation (Fin N)) (pos : Fin t → Fin 3) : ℕ := + tableNumber (T.leftTable pos (signature U))+ + 2^((2^3)^t)*(if T.first then firstNumber U else (N^3*2)^t+secondNumber U h pos) + +def Query.rightNumber (T : Query h) (U : Fin t → Equation (Fin N)) (pos : Fin t → Fin 3) : ℕ := + tableNumber T.rightTable+2^((2^3)^t)*((N^3*2)^t+secondNumber U h pos) + +lemma Query.left_number (T : Query h) (U : Fin t → Equation (Fin N)) (pos : Fin t → Fin 3) : + (variableCode ((T.realize U pos).signed familyBase).left).val=T.leftNumber U pos := by + rw [variable_number] + change tableNumber (extendTable _ (rep (familyBase _) (T.realize U pos).left.2).val)+_= _ + rw [T.left_extended] + unfold Query.leftNumber Query.realize + by_cases hf : T.first=true + · simp only [ite_eq_left hf,comparison,QueryDemand.signed,vertex,first_code] + · simp only [ite_eq_right hf,comparison,QueryDemand.signed,vertex,second_code] + +lemma Query.right_number (T : Query h) (U : Fin t → Equation (Fin N)) (pos : Fin t → Fin 3) : + (variableCode ((T.realize U pos).signed familyBase).right).val=T.rightNumber U pos := by + rw [variable_number] + change tableNumber (extendTable _ (rep (familyBase _) (T.realize U pos).right.2).val)+_= _ + rw [T.right_extended] + unfold Query.rightNumber Query.realize + by_cases hf : T.first=true + · simp only [ite_eq_left hf,comparison,QueryDemand.signed,vertex,second_code] + · simp only [ite_eq_right hf,comparison,QueryDemand.signed,vertex,second_code] + +end MinUncut.Outer.LocalTemplate + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Games/QuestionExpressions.lean b/lean/OAI/Computability/MinUncut/Games/QuestionExpressions.lean new file mode 100644 index 0000000000000000000000000000000000000000..2787223d66e0d534b2620908882ff0551f92b427 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Games/QuestionExpressions.lean @@ -0,0 +1,82 @@ +import Mathlib +import OAI.Computability.MinUncut.Games.QuestionArithmetic + +namespace OAI + +section +noncomputable section +open scoped BigOperators +namespace MinUncut.Costed.SourceWords +open MinUncut.Inner MinUncut.Outer MinUncut.Outer.LocalTemplate +open MinUncutGames.Reduction MinUncut.SourceBridge + +variable {t : ℕ} + +def tupleDigit (j : ℕ) : AExpr := .mod (.div (.reg 0) ((AExpr.reg 2).pow j)) (.reg 2) +def slotExpr (j p : ℕ) : AExpr := .at (.add (.add (.const 3) (.mul (.const 4) (tupleDigit j))) (.const p)) +def inputTuple (input : SourceEncoding.Input) (u : Fin t → Fin input.equations.length) : List ℕ := + (finFunctionFinEquiv u).val::SourceEncoding.inputWords input + +lemma tupleDigit_eval (input : SourceEncoding.Input) (u : Fin t → Fin input.equations.length) (j : Fin t) : + (tupleDigit j.val).eval (inputTuple input u)=(u j).val := by + have hh := congrArg Fin.val (congrFun (finFunctionFinEquiv.symm_apply_apply u) j) + change (finFunctionFinEquiv u).val/input.equations.length^j.val%input.equations.length=(u j).val at hh + simpa only [tupleDigit,AExpr.eval,AExpr.eval_pow,inputTuple,SourceEncoding.inputWords, + List.cons_append,List.nil_append,List.drop_succ_cons,List.drop_zero,List.headI_cons] using hh + +lemma slotExpr_name (input : SourceEncoding.Input) (u : Fin t → Fin input.equations.length) (j : Fin t) (p : Fin 3) : + (slotExpr j.val p.val).eval (inputTuple input u)=((equations input (u j)).names p).val := by + simp only [slotExpr,AExpr.eval,tupleDigit_eval] + have he : 3+4*(u j).val+p.val=(2+4*(u j).val+p.val)+1 := by omega + rw [he] + exact input_name input (u j) p + +lemma slotExpr_rhs (input : SourceEncoding.Input) (u : Fin t → Fin input.equations.length) (j : Fin t) : + (slotExpr j.val 3).eval (inputTuple input u)=(equations input (u j)).rhs.val := by + simp only [slotExpr,AExpr.eval,tupleDigit_eval] + have he : 3+4*(u j).val+3=(2+4*(u j).val+3)+1 := by omega + rw [he] + exact input_rhs input (u j) + +def equationExpr (j : ℕ) : AExpr := .add (slotExpr j 3) (.mul (.const 2) + (AExpr.sum (List.ofFn (fun p : Fin 3=>.mul (slotExpr j p.val) ((AExpr.reg 1).pow p.val))))) + +def firstExpr (t : ℕ) : AExpr := AExpr.sum (List.ofFn (fun i : Fin t=> + .mul (equationExpr i.val) ((AExpr.mul ((AExpr.reg 1).pow 3) (.const 2)).pow i.val))) + +def secondExpr {t : ℕ} (h : Fin t → Bool) (pos : Fin t → Fin 3) : AExpr := + AExpr.sum (List.ofFn (fun i : Fin t=> + .mul (if h i then slotExpr i.val (pos i).val else .add (.reg 1) (equationExpr i.val)) + ((AExpr.add (.reg 1) (.mul ((AExpr.reg 1).pow 3) (.const 2))).pow i.val))) + +lemma reg1_eval (input : SourceEncoding.Input) (u : Fin t → Fin input.equations.length) : + (AExpr.reg 1).eval (inputTuple input u)=input.«variables» := rfl + +lemma inputTuple_reg1 (input : SourceEncoding.Input) (u : Fin t → Fin input.equations.length) : + ((inputTuple input u).drop 1).headI=input.«variables» := rfl + +lemma equationExpr_eval (input : SourceEncoding.Input) (u : Fin t → Fin input.equations.length) (j : Fin t) : + (equationExpr j.val).eval (inputTuple input u)=equationNumber (equations input (u j)) := by + simp only [equationExpr,AExpr.eval,AExpr.eval_sum,List.map_ofFn,Function.comp_def,List.sum_ofFn, + slotExpr_rhs,slotExpr_name,AExpr.eval_pow,inputTuple_reg1,equationNumber] + +lemma firstExpr_eval (input : SourceEncoding.Input) (u : Fin t → Fin input.equations.length) : + (firstExpr t).eval (inputTuple input u)=firstNumber (fun j=>equations input (u j)) := by + simp only [firstExpr,AExpr.eval_sum,List.map_ofFn,Function.comp_def,List.sum_ofFn,AExpr.eval, + equationExpr_eval,AExpr.eval_pow,inputTuple_reg1,firstNumber] + +lemma secondExpr_eval (input : SourceEncoding.Input) (u : Fin t → Fin input.equations.length) + (h : Fin t → Bool) (pos : Fin t → Fin 3) : + (secondExpr h pos).eval (inputTuple input u)=secondNumber (fun j=>equations input (u j)) h pos := by + simp only [secondExpr,AExpr.eval_sum,List.map_ofFn,Function.comp_def,List.sum_ofFn,AExpr.eval,AExpr.eval_pow, + inputTuple_reg1,secondNumber] + apply Finset.sum_congr rfl + intro j _ + cases h j <;> simp only [Bool.false_eq_true,ite_false,ite_true,AExpr.eval,equationExpr_eval,slotExpr_name,inputTuple_reg1] + +end MinUncut.Costed.SourceWords + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Games/Reindexing.lean b/lean/OAI/Computability/MinUncut/Games/Reindexing.lean new file mode 100644 index 0000000000000000000000000000000000000000..600ae720147a40d84bcb21fa4c3a5638fa192bc4 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Games/Reindexing.lean @@ -0,0 +1,193 @@ +import Mathlib +import OAI.Computability.MinUncut.Games.TotalVariation + +namespace OAI + +section +noncomputable section + +namespace MinUncutGames.Foundations.Games + +open scoped BigOperators + +namespace FiniteDistribution + +def reindexEquiv {ι κ Ω : Type*} (e : κ ≃ ι) : (ι → Ω) ≃ (κ → Ω) where + toFun f := f ∘ e + invFun g := g ∘ e.symm + left_inv f := by funext i; simp + right_inv g := by funext i; simp + +theorem pushforward_equiv {Ω Γ : Type*} [Fintype Ω] [Fintype Γ] + (μ : FiniteDistribution Ω) (e : Ω ≃ Γ) : + μ.pushforward e = μ.transport e := by + classical + apply eq_of_weight_eq + intro y + simp only [pushforward, transport] + have he : ∀ x : Ω, (e x = y) = (x = e.symm y) := by + intro x + apply propext + constructor + · intro h + simpa using congrArg e.symm h + · intro h + rw [h, e.apply_symm_apply] + simp_rw [he] + simp + +theorem table_const_reindex {ι κ Ω : Type*} + [Fintype ι] [Fintype κ] [Fintype Ω] [DecidableEq ι] [DecidableEq κ] + (μ : FiniteDistribution Ω) (e : κ ≃ ι) : + (table (fun _ : ι => μ)).pushforward (fun f => f ∘ e) = + table (fun _ : κ => μ) := by + classical + change (table (fun _ : ι => μ)).pushforward (reindexEquiv e) = _ + rw [pushforward_equiv] + apply eq_of_weight_eq + intro g + change (∏ i : ι, μ.weight (g (e.symm i))) = ∏ k : κ, μ.weight (g k) + exact e.symm.prod_comp (fun k => μ.weight (g k)) + +theorem iid_reindex {Ω : Type*} [Fintype Ω] + (μ : FiniteDistribution Ω) {n m : Nat} (e : Fin m ≃ Fin n) : + (μ.iid n).pushforward (fun f => f ∘ e) = μ.iid m := by + classical + change (μ.iid n).pushforward (reindexEquiv e) = _ + rw [pushforward_equiv] + apply eq_of_weight_eq + intro g + change (∏ i : Fin n, μ.weight (g (e.symm i))) = ∏ k : Fin m, μ.weight (g k) + exact e.symm.prod_comp (fun k => μ.weight (g k)) + +theorem probability_reindex_of_weight {Ω Γ : Type*} [Fintype Ω] [Fintype Γ] + (μ : FiniteDistribution Ω) (ν : FiniteDistribution Γ) (e : Ω ≃ Γ) + (hweight : ∀ x, ν.weight (e x) = μ.weight x) (event : Γ → Bool) : + ν.probability event = μ.probability (fun x => event (e x)) := by + classical + change (∑ y, if event y then ν.weight y else 0) = + ∑ x, if event (e x) then μ.weight x else 0 + rw [← e.sum_comp (fun y => if event y then ν.weight y else 0)] + apply Finset.sum_congr rfl + intro x _ + rw [hweight] + +end FiniteDistribution + +namespace Game + +variable {Q₁ Q₂ A₁ A₂ : Type*} +variable [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂] + +def questionReindexEquiv {n m : Nat} (e : Fin m ≃ Fin n) : + ((Fin n → Q₁) × (Fin n → Q₂)) ≃ ((Fin m → Q₁) × (Fin m → Q₂)) := + Equiv.prodCongr (FiniteDistribution.reindexEquiv e) + (FiniteDistribution.reindexEquiv e) + +def reindexStrategy {n m : Nat} (e : Fin m ≃ Fin n) + (s : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) : + Strategy (Fin m → Q₁) (Fin m → Q₂) (Fin m → A₁) (Fin m → A₂) := + (fun x i => s.1 (x ∘ e.symm) (e i), + fun y i => s.2 (y ∘ e.symm) (e i)) + +theorem repetition_question_weight_reindex (G : Game Q₁ Q₂ A₁ A₂) + {n m : Nat} (e : Fin m ≃ Fin n) + (q : (Fin n → Q₁) × (Fin n → Q₂)) : + (G.repetition m).questions.weight (questionReindexEquiv e q) = + (G.repetition n).questions.weight q := by + classical + rw [repetition_question_weight, repetition_question_weight] + change (∏ i : Fin m, G.questions.weight (q.1 (e i), q.2 (e i))) = + ∏ j : Fin n, G.questions.weight (q.1 j, q.2 j) + exact e.prod_comp (fun j => G.questions.weight (q.1 j, q.2 j)) + +theorem repetition_questions_reindex (G : Game Q₁ Q₂ A₁ A₂) + {n m : Nat} (e : Fin m ≃ Fin n) : + (G.repetition n).questions.pushforward (questionReindexEquiv e) = + (G.repetition m).questions := by + classical + rw [FiniteDistribution.pushforward_equiv] + apply FiniteDistribution.eq_of_weight_eq + intro q + change (G.repetition n).questions.weight ((questionReindexEquiv e).symm q) = + (G.repetition m).questions.weight q + have h := repetition_question_weight_reindex G e ((questionReindexEquiv e).symm q) + simpa only [Equiv.apply_symm_apply] using h.symm + +theorem coordinateWin_reindex (G : Game Q₁ Q₂ A₁ A₂) + {n m : Nat} (e : Fin m ≃ Fin n) + (s : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (i : Fin m) (q : (Fin n → Q₁) × (Fin n → Q₂)) : + G.coordinateWin (reindexStrategy e s) i (questionReindexEquiv e q) = + G.coordinateWin s (e i) q := by + have h₁ : (fun j : Fin n => q.1 (e (e.symm j))) = q.1 := by + funext j + rw [e.apply_symm_apply] + have h₂ : (fun j : Fin n => q.2 (e (e.symm j))) = q.2 := by + funext j + rw [e.apply_symm_apply] + change G.accepts (q.1 (e i)) (q.2 (e i)) + (s.1 (fun j => q.1 (e (e.symm j))) (e i)) + (s.2 (fun j => q.2 (e (e.symm j))) (e i)) = + G.accepts (q.1 (e i)) (q.2 (e i)) (s.1 q.1 (e i)) (s.2 q.2 (e i)) + rw [h₁, h₂] + +theorem selectedWins_reindex (G : Game Q₁ Q₂ A₁ A₂) + {n m : Nat} (e : Fin m ≃ Fin n) + (s : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (S : Finset (Fin m)) (q : (Fin n → Q₁) × (Fin n → Q₂)) : + G.selectedWins (reindexStrategy e s) S (questionReindexEquiv e q) = + G.selectedWins s (S.map e.toEmbedding) q := by + classical + unfold selectedWins + congr 1 + apply propext + constructor + · intro h j hj + obtain ⟨i, hi, rfl⟩ := Finset.mem_map.mp hj + have hw := h i hi + rw [coordinateWin_reindex] at hw + exact hw + · intro h i hi + rw [coordinateWin_reindex] + exact h (e i) (Finset.mem_map.mpr ⟨i, hi, rfl⟩) + +theorem selectedSuccess_reindex (G : Game Q₁ Q₂ A₁ A₂) + {n m : Nat} (e : Fin m ≃ Fin n) + (s : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (S : Finset (Fin m)) : + G.selectedSuccess (reindexStrategy e s) S = + G.selectedSuccess s (S.map e.toEmbedding) := by + classical + unfold selectedSuccess + rw [FiniteDistribution.probability_reindex_of_weight + (G.repetition n).questions (G.repetition m).questions (questionReindexEquiv e) + (repetition_question_weight_reindex G e)] + congr 1 + funext q + exact selectedWins_reindex G e s S q + +theorem repetition_success_reindex (G : Game Q₁ Q₂ A₁ A₂) + {n m : Nat} (e : Fin m ≃ Fin n) + (s : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) : + (G.repetition m).success (reindexStrategy e s) = + (G.repetition n).success s := by + classical + have huniv : (Finset.univ : Finset (Fin m)).map e.toEmbedding = Finset.univ := by + ext j + constructor + · intro _ + exact Finset.mem_univ j + · intro _ + exact Finset.mem_map.mpr ⟨e.symm j, Finset.mem_univ _, e.apply_symm_apply j⟩ + have h := selectedSuccess_reindex G e s Finset.univ + rw [huniv, selectedSuccess_univ, selectedSuccess_univ] at h + exact h + +end Game +end MinUncutGames.Foundations.Games + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Games/Sampling.lean b/lean/OAI/Computability/MinUncut/Games/Sampling.lean new file mode 100644 index 0000000000000000000000000000000000000000..adfc1e1412b9bcb4fdf6f57564ed9ca995c766c3 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Games/Sampling.lean @@ -0,0 +1,502 @@ +import Mathlib +import OAI.Computability.MinUncut.Games.OuterQuestions + +namespace OAI + +namespace MinUncutGames.Foundations.Games.FiniteDistribution +open scoped BigOperators +noncomputable section + +theorem iid_pushforward {Ω Γ : Type*} [Fintype Ω] [Fintype Γ] + (μ : FiniteDistribution Ω) (f : Ω → Γ) (n : Nat) : + (μ.pushforward f).iid n = + (μ.iid n).pushforward (fun answers i => f (answers i)) := by + classical + apply eq_of_weight_eq + intro y + simp only [iid, pushforward] + rw [Fintype.prod_sum] + apply Finset.sum_congr rfl + intro x _ + by_cases h : (fun i => f (x i)) = y + · have hp : ∀ i, f (x i) = y i := congrFun h + simp [hp] + · rw [ite_eq_right h] + have hn : ¬ ∀ i, f (x i) = y i := fun hp => h (funext hp) + obtain ⟨i, hi⟩ := not_forall.mp hn + apply Finset.prod_eq_zero (Finset.mem_univ i) + simp [hi] + +def uniform (Ω : Type*) [Fintype Ω] [Nonempty Ω] : FiniteDistribution Ω where + weight _ := 1 / (Fintype.card Ω : ℝ) + nonnegative _ := div_nonneg zero_le_one (Nat.cast_nonneg _) + normalized := by + have hn : (Fintype.card Ω : ℝ) ≠ 0 := + Nat.cast_ne_zero.mpr Fintype.card_ne_zero + simp only [Finset.sum_const, Finset.card_univ, nsmul_eq_mul, one_div] + exact mul_inv_cancel₀ hn + +theorem iid_uniform {Ω : Type*} [Fintype Ω] [Nonempty Ω] (n : Nat) : + (uniform Ω).iid n = uniform (Fin n → Ω) := by + classical + apply eq_of_weight_eq + intro x + simp [iid, uniform, Nat.cast_pow, one_div] + +theorem expectation_uniform {Ω : Type*} [Fintype Ω] [Nonempty Ω] (f : Ω → ℝ) : + (uniform Ω).expectation f = (∑ x, f x) / (Fintype.card Ω : ℝ) := by + unfold expectation uniform + rw [← Finset.mul_sum] + simp [div_eq_mul_inv, mul_comm] + +end +end MinUncutGames.Foundations.Games.FiniteDistribution + +noncomputable section +open scoped BigOperators +namespace MinUncut.Outer +open MinUncut.Inner MinUncutGames.Foundations.Games +attribute [local instance] Classical.propDecidable +variable {Name S : Type*} + +instance equationFintype [Fintype Name] : Fintype (Equation Name) := + Fintype.ofEquiv ((Fin 3 → Name) × F₂) + { toFun := fun x => ⟨x.1,x.2⟩ + invFun := fun E => (E.names,E.rhs) + left_inv := fun _ => rfl + right_inv := fun _ => rfl } + +def ordinaryAccepts (E : Equation Name) (x : Name) (a : Triple) (b : F₂) : Bool := + decide (Valid E a ∧ ∀ p, E.names p=x → a p=b) + +lemma ordinary_all_implies_satisfied (E : Equation Name) (a : Triple) (s : Name → F₂) + (h : ∀ p, ordinaryAccepts E (E.names p) a (s (E.names p))=true) : + Satisfied s E := by + have hvalid : Valid E a := (of_decide_eq_true (h 0)).1 + have he : a=evaluatedTriple s E := by + funext p + exact (of_decide_eq_true (h p)).2 p rfl + simpa only [Satisfied,← he] using hvalid.1 + +lemma ordinary_coordinate_bound (E : Equation Name) (a : Triple) (s : Name → F₂) : + (∑ p : Fin 3, if ordinaryAccepts E (E.names p) a (s (E.names p)) then (1 : ℝ) else 0) + ≤ 2+(if Satisfied s E then (1 : ℝ) else 0) := by + have hall := ordinary_all_implies_satisfied E a s + simp only [Fin.sum_univ_three] + by_cases h0 : ordinaryAccepts E (E.names 0) a (s (E.names 0))=true + <;> by_cases h1 : ordinaryAccepts E (E.names 1) a (s (E.names 1))=true + <;> by_cases h2 : ordinaryAccepts E (E.names 2) a (s (E.names 2))=true + · have hs : Satisfied s E := hall (by intro p; fin_cases p <;> assumption) + norm_num [h0,h1,h2,hs] + all_goals simp only [h0,h1,h2,Bool.false_eq_true,↓reduceIte]; split <;> norm_num + +variable [Fintype S] [Nonempty S] + +def equationFraction (equations : S → Equation Name) (s : Name → F₂) : ℝ := + (∑ i, if Satisfied s (equations i) then (1 : ℝ) else 0)/(Fintype.card S : ℝ) + +variable [Fintype Name] + +def ordinaryGame (equations : S → Equation Name) : + Game (Equation Name) Name Triple F₂ where + questions := (FiniteDistribution.uniform (S × Fin 3)).pushforward + (fun ip => (equations ip.1,(equations ip.1).names ip.2)) + accepts := ordinaryAccepts + +lemma ordinary_success_formula (equations : S → Equation Name) + (strategy : Strategy (Equation Name) Name Triple F₂) : + (ordinaryGame equations).success strategy = + (∑ i, ∑ p : Fin 3, + if ordinaryAccepts (equations i) ((equations i).names p) + (strategy.1 (equations i)) (strategy.2 ((equations i).names p)) then + (1 : ℝ) else 0) / ((Fintype.card S : ℝ)*3) := by + unfold Game.success + dsimp only [ordinaryGame] + rw [FiniteDistribution.probability_pushforward] + simp only [FiniteDistribution.probability,FiniteDistribution.uniform,Game.wins, + Fintype.card_prod,Fintype.card_fin,Nat.cast_mul,Nat.cast_ofNat] + rw [Fintype.sum_prod_type] + simp only [Finset.sum_div,ite_div,zero_div] + +lemma ordinary_success_le (equations : S → Equation Name) + (strategy : Strategy (Equation Name) Name Triple F₂) : + (ordinaryGame equations).success strategy ≤ + (2+equationFraction equations strategy.2)/3 := by + have hc : (0 : ℝ) ordinary_coordinate_bound (equations i) (strategy.1 (equations i)) strategy.2) + simp only [Finset.sum_add_distrib,Finset.sum_const,Finset.card_univ,nsmul_eq_mul] at hsum + unfold equationFraction + apply (div_le_iff₀ (mul_pos hc (by norm_num : (0 : ℝ)<3))).2 + calc + _ ≤ (Fintype.card S : ℝ)*2 + + ∑ i, if Satisfied strategy.2 (equations i) then (1 : ℝ) else 0 := hsum + _ = _ := by field_simp + +theorem ordinary_value_le (equations : S → Equation Name) + (hsound : ∀ s : Name → F₂, equationFraction equations s ≤ 3/4) : + (ordinaryGame equations).value ≤ 11/12 := by + apply (Game.value_le_iff _ _).2 + intro strategy + have h := ordinary_success_le equations strategy + have hs := hsound strategy.2 + linarith + +end MinUncut.Outer + +end +namespace MinUncutGames.Foundations.Information + +open scoped BigOperators + +variable {α : Type*} [Fintype α] + +def IsProbability (p : α → ℝ) : Prop := + (∀ a, 0 ≤ p a) ∧ ∑ a, p a = 1 + +def SupportedBy (p q : α → ℝ) : Prop := ∀ a, p a ≠ 0 → q a ≠ 0 + +noncomputable def relativeEntropy (p q : α → ℝ) : ℝ := + ∑ a, p a * Real.log (p a / q a) + +noncomputable def totalVariation (p q : α → ℝ) : ℝ := + (∑ a, |p a - q a|) / 2 + +noncomputable def posterior (p w : α → ℝ) (z : ℝ) : α → ℝ := + fun a => p a * w a / z + +theorem posterior_isProbability (p w : α → ℝ) (hp : IsProbability p) + (hw : ∀ a, 0 ≤ w a) {z : ℝ} (hz : 0 < z) + (hmass : ∑ a, p a * w a = z) : IsProbability (posterior p w z) := by + constructor + · intro a + exact div_nonneg (mul_nonneg (hp.1 a) (hw a)) hz.le + · simp only [posterior, div_eq_mul_inv, ← Finset.sum_mul, hmass, + mul_inv_cancel₀ hz.ne'] + +omit [Fintype α] in +theorem posterior_supportedBy (p w : α → ℝ) (z : ℝ) : + SupportedBy (posterior p w z) p := by + intro a ha hp + exact ha (by simp [posterior, hp]) + +theorem mul_log_div_ge_sub {x y : ℝ} (hx : 0 < x) (hy : 0 < y) : + x - y ≤ x * Real.log (x / y) := by + have h := Real.one_sub_inv_le_log_of_pos (div_pos hx hy) + have hm := mul_le_mul_of_nonneg_left h hx.le + have he : x * (1 - (x / y)⁻¹) = x - y := by + field_simp [hx.ne', hy.ne'] + rwa [he] at hm + +theorem relativeEntropy_nonneg (p q : α → ℝ) (hp : IsProbability p) + (hq : IsProbability q) (hs : SupportedBy p q) : 0 ≤ relativeEntropy p q := by + have hpoint : ∀ a, p a - q a ≤ p a * Real.log (p a / q a) := by + intro a + by_cases hpa : p a = 0 + · simp only [hpa, zero_sub, zero_div, zero_mul] + exact neg_nonpos.mpr (hq.1 a) + · exact mul_log_div_ge_sub (lt_of_le_of_ne (hp.1 a) (Ne.symm hpa)) + (lt_of_le_of_ne (hq.1 a) (Ne.symm (hs a hpa))) + have hsum := Finset.sum_le_sum (fun a (_ : a ∈ (Finset.univ : Finset α)) => hpoint a) + simpa [relativeEntropy, Finset.sum_sub_distrib, hp.2, hq.2] using hsum + +theorem posterior_relativeEntropy_le (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) : + relativeEntropy (posterior p w z) p ≤ Real.log (1 / z) := by + have hpost := posterior_isProbability p w hp hw hz hmass + have hpoint : ∀ a, posterior p w z a * Real.log (posterior p w z a / p a) ≤ + posterior p w z a * Real.log (1 / z) := by + intro a + by_cases hpa : posterior p w z a = 0 + · simp [hpa] + have hpne := posterior_supportedBy p w z a hpa + have hppos : 0 < p a := lt_of_le_of_ne (hp.1 a) (Ne.symm hpne) + have hpostpos : 0 < posterior p w z a := + lt_of_le_of_ne (hpost.1 a) (Ne.symm hpa) + have hr : posterior p w z a / p a = w a / z := by + dsimp [posterior] + field_simp [hpne, hz.ne'] + apply mul_le_mul_of_nonneg_left _ (hpost.1 a) + apply Real.log_le_log (div_pos hpostpos hppos) + rw [hr] + exact div_le_div_of_nonneg_right (hw_one a) hz.le + have hsum := Finset.sum_le_sum (fun a (_ : a ∈ (Finset.univ : Finset α)) => hpoint a) + simpa only [relativeEntropy, ← Finset.sum_mul, hpost.2, one_mul] using hsum + +theorem totalVariation_nonneg (p q : α → ℝ) : 0 ≤ totalVariation p q := by + exact div_nonneg (Finset.sum_nonneg (fun a _ => abs_nonneg (p a - q a))) (by norm_num) + +theorem totalVariation_symm (p q : α → ℝ) : totalVariation p q = totalVariation q p := by + simp only [totalVariation, abs_sub_comm] + +theorem totalVariation_le_one (p q : α → ℝ) (hp : IsProbability p) + (hq : IsProbability q) : totalVariation p q ≤ 1 := by + have hpoint : ∀ a, |p a - q a| ≤ p a + q a := by + intro a + rw [abs_le] + constructor <;> linarith [hp.1 a, hq.1 a] + have hsum := Finset.sum_le_sum (fun a (_ : a ∈ (Finset.univ : Finset α)) => hpoint a) + simp only [Finset.sum_add_distrib, hp.2, hq.2] at hsum + dsimp [totalVariation] + linarith + +theorem le_binaryLog_of_le_log {r x : ℝ} (hr : 0 ≤ r) (h : r ≤ Real.log x) : + r ≤ Real.log x / Real.log 2 := by + have htwo : 0 < Real.log 2 := Real.log_pos (by norm_num) + have htwo_one : Real.log 2 ≤ 1 := by + have ht := Real.log_le_sub_one_of_pos (show (0 : ℝ) < 2 by norm_num) + norm_num at ht ⊢ + exact ht + apply (le_div_iff₀ htwo).2 + exact (mul_le_mul_of_nonneg_left htwo_one hr).trans (by simpa using h) + +theorem weighted_sum_sq_le (w x : α → ℝ) (hw : IsProbability w) : + (∑ a, w a * x a)^2 ≤ ∑ a, w a * (x a)^2 := by + have hcs := Finset.sum_mul_sq_le_sq_mul_sq (Finset.univ : Finset α) + (fun a => Real.sqrt (w a)) (fun a => Real.sqrt (w a) * x a) + have hfirst : ∀ a, Real.sqrt (w a) * (Real.sqrt (w a) * x a) = w a * x a := by + intro a + rw [← mul_assoc, Real.mul_self_sqrt (hw.1 a)] + have hsecond : ∀ a, (Real.sqrt (w a) * x a)^2 = w a * (x a)^2 := by + intro a + rw [mul_pow, Real.sq_sqrt (hw.1 a)] + simpa only [hfirst, hsecond, Real.sq_sqrt (hw.1 _), hw.2, one_mul] using hcs + +open scoped BigOperators + +variable {α β : Type*} [Fintype α] [Fintype β] + +noncomputable def firstMarginal (p : α × β → ℝ) (a : α) : ℝ := ∑ b, p (a, b) + +noncomputable def secondMarginal (p : α × β → ℝ) (b : β) : ℝ := ∑ a, p (a, b) + +def product (p : α → ℝ) (q : β → ℝ) : α × β → ℝ := fun ab => p ab.1 * q ab.2 + +theorem firstMarginal_isProbability (p : α × β → ℝ) (hp : IsProbability p) : + IsProbability (firstMarginal p) := by + constructor + · intro a + exact Finset.sum_nonneg (fun b _ => hp.1 (a, b)) + · simpa only [firstMarginal, Fintype.sum_prod_type] using hp.2 + +theorem secondMarginal_isProbability (p : α × β → ℝ) (hp : IsProbability p) : + IsProbability (secondMarginal p) := by + constructor + · intro b + exact Finset.sum_nonneg (fun a _ => hp.1 (a, b)) + · change (∑ b, ∑ a, p (a, b)) = 1 + rw [Finset.sum_comm] + exact (firstMarginal_isProbability p hp).2 + +theorem product_isProbability (p : α → ℝ) (q : β → ℝ) + (hp : IsProbability p) (hq : IsProbability q) : IsProbability (product p q) := by + constructor + · intro ab + exact mul_nonneg (hp.1 ab.1) (hq.1 ab.2) + · simp only [product, Fintype.sum_prod_type, ← Finset.mul_sum, hq.2, mul_one, hp.2] + +theorem point_le_firstMarginal (p : α × β → ℝ) (hp : IsProbability p) (a : α) (b : β) : + p (a, b) ≤ firstMarginal p a := by + classical + exact Finset.single_le_sum (fun b _ => hp.1 (a, b)) (Finset.mem_univ b) + +theorem point_le_secondMarginal (p : α × β → ℝ) (hp : IsProbability p) (a : α) (b : β) : + p (a, b) ≤ secondMarginal p b := by + classical + exact Finset.single_le_sum (fun a _ => hp.1 (a, b)) (Finset.mem_univ a) + +theorem joint_supportedBy_product_marginals (p : α × β → ℝ) (hp : IsProbability p) : + SupportedBy p (product (firstMarginal p) (secondMarginal p)) := by + intro ab hpne + have hpos : 0 < p ab := lt_of_le_of_ne (hp.1 ab) (Ne.symm hpne) + exact mul_ne_zero + (ne_of_gt (hpos.trans_le (point_le_firstMarginal p hp ab.1 ab.2))) + (ne_of_gt (hpos.trans_le (point_le_secondMarginal p hp ab.1 ab.2))) + +theorem relativeEntropy_product_reference (p : α × β → ℝ) (u : α → ℝ) (v : β → ℝ) + (hp : IsProbability p) (hu : IsProbability u) (hv : IsProbability v) + (hsu : SupportedBy (firstMarginal p) u) (hsv : SupportedBy (secondMarginal p) v) : + relativeEntropy p (product u v) = + relativeEntropy p (product (firstMarginal p) (secondMarginal p)) + + relativeEntropy (firstMarginal p) u + relativeEntropy (secondMarginal p) v := by + have hpoint : ∀ ab : α × β, p ab * Real.log (p ab / product u v ab) = + p ab * Real.log (p ab / product (firstMarginal p) (secondMarginal p) ab) + + p ab * Real.log (firstMarginal p ab.1 / u ab.1) + + p ab * Real.log (secondMarginal p ab.2 / v ab.2) := by + intro ab + by_cases hzero : p ab = 0 + · simp [hzero] + have hpos : 0 < p ab := lt_of_le_of_ne (hp.1 ab) (Ne.symm hzero) + have hleft := ne_of_gt (hpos.trans_le (point_le_firstMarginal p hp ab.1 ab.2)) + have hright := ne_of_gt (hpos.trans_le (point_le_secondMarginal p hp ab.1 ab.2)) + have hune := (lt_of_le_of_ne (hu.1 ab.1) (Ne.symm (hsu ab.1 hleft))).ne' + have hvne := (lt_of_le_of_ne (hv.1 ab.2) (Ne.symm (hsv ab.2 hright))).ne' + simp only [product, Real.log_div hzero (mul_ne_zero hune hvne), + Real.log_div hzero (mul_ne_zero hleft hright), Real.log_mul hune hvne, + Real.log_mul hleft hright, Real.log_div hleft hune, Real.log_div hright hvne] + ring + have hleftSum : (∑ ab : α × β, p ab * Real.log (firstMarginal p ab.1 / u ab.1)) = + relativeEntropy (firstMarginal p) u := by + simp only [Fintype.sum_prod_type, ← Finset.sum_mul, relativeEntropy, firstMarginal] + have hrightSum : (∑ ab : α × β, p ab * Real.log (secondMarginal p ab.2 / v ab.2)) = + relativeEntropy (secondMarginal p) v := by + rw [Fintype.sum_prod_type, Finset.sum_comm] + simp only [← Finset.sum_mul, relativeEntropy, secondMarginal] + unfold relativeEntropy + simp_rw [hpoint] + rw [Finset.sum_add_distrib, Finset.sum_add_distrib, hleftSum, hrightSum] + rfl + +theorem marginal_relativeEntropy_sum_le (p : α × β → ℝ) (u : α → ℝ) (v : β → ℝ) + (hp : IsProbability p) (hu : IsProbability u) (hv : IsProbability v) + (hsu : SupportedBy (firstMarginal p) u) (hsv : SupportedBy (secondMarginal p) v) : + relativeEntropy (firstMarginal p) u + relativeEntropy (secondMarginal p) v ≤ + relativeEntropy p (product u v) := by + rw [relativeEntropy_product_reference p u v hp hu hv hsu hsv] + have hn := relativeEntropy_nonneg p (product (firstMarginal p) (secondMarginal p)) hp + (product_isProbability _ _ (firstMarginal_isProbability p hp) + (secondMarginal_isProbability p hp)) (joint_supportedBy_product_marginals p hp) + linarith + +noncomputable def conditionalKernel + (p : α × β → ℝ) (fallback : β → ℝ) (a : α) (b : β) : ℝ := by + classical + exact if firstMarginal p a = 0 then fallback b + else p (a, b) / firstMarginal p a + +theorem conditionalKernel_isProbability + (p : α × β → ℝ) (fallback : β → ℝ) + (hp : IsProbability p) (hf : IsProbability fallback) (a : α) : + IsProbability (conditionalKernel p fallback a) := by + classical + by_cases hm : firstMarginal p a = 0 + · simpa only [IsProbability, conditionalKernel, ite_eq_left hm] using hf + · constructor + · intro b + simp only [conditionalKernel, ite_eq_right hm] + exact div_nonneg (hp.1 (a, b)) + ((firstMarginal_isProbability p hp).1 a) + · simp only [conditionalKernel, ite_eq_right hm, div_eq_mul_inv, ← Finset.sum_mul] + change firstMarginal p a * (firstMarginal p a)⁻¹ = 1 + exact mul_inv_cancel₀ hm + +theorem marginal_mul_conditionalKernel + (p : α × β → ℝ) (fallback : β → ℝ) + (hp : IsProbability p) (a : α) (b : β) : + firstMarginal p a * conditionalKernel p fallback a b = p (a, b) := by + classical + by_cases hm : firstMarginal p a = 0 + · have hpoint := point_le_firstMarginal p hp a b + rw [hm] at hpoint + have hz : p (a, b) = 0 := le_antisymm hpoint (hp.1 (a, b)) + simp [conditionalKernel, hm, hz] + · simp only [conditionalKernel, ite_eq_right hm] + calc + firstMarginal p a * (p (a, b) / firstMarginal p a) + = p (a, b) * + (firstMarginal p a / firstMarginal p a) := by ring + _ = p (a, b) := by rw [div_self hm, mul_one] + +theorem law_of_total_probability + (p : α × β → ℝ) (fallback : β → ℝ) + (hp : IsProbability p) (b : β) : + (∑ a, firstMarginal p a * conditionalKernel p fallback a b) = + secondMarginal p b := by + simp only [marginal_mul_conditionalKernel p fallback hp, secondMarginal] + +theorem kernelProduct_isProbability + (r : α → ℝ) (k : α → β → ℝ) + (hr : IsProbability r) (hk : ∀ a, IsProbability (k a)) : + IsProbability (fun ab : α × β => r ab.1 * k ab.1 ab.2) := by + constructor + · intro ab + exact mul_nonneg (hr.1 ab.1) ((hk ab.1).1 ab.2) + · simp only [Fintype.sum_prod_type, ← Finset.mul_sum, + (hk _).2, mul_one, hr.2] + +theorem alternativeInput_conditionalProduct_isProbability + (p : α × β → ℝ) (fallback : β → ℝ) (r : α → ℝ) + (hp : IsProbability p) (hf : IsProbability fallback) + (hr : IsProbability r) : + IsProbability + (fun ab : α × β => r ab.1 * conditionalKernel p fallback ab.1 ab.2) := + kernelProduct_isProbability r (conditionalKernel p fallback) hr + (conditionalKernel_isProbability p fallback hp hf) + +theorem totalVariation_joint_common_weights (w : α → ℝ) (p q : α → β → ℝ) + (hw : ∀ a, 0 ≤ w a) : + totalVariation (fun ab : α × β => w ab.1 * p ab.1 ab.2) + (fun ab : α × β => w ab.1 * q ab.1 ab.2) = + ∑ a, w a * totalVariation (p a) (q a) := by + have hpoint : ∀ a b, |w a * p a b - w a * q a b| = w a * |p a b - q a b| := by + intro a b + rw [← mul_sub, abs_mul, abs_of_nonneg (hw a)] + simp only [totalVariation, Fintype.sum_prod_type, hpoint, ← Finset.mul_sum, + div_eq_mul_inv, Finset.sum_mul, mul_assoc] + +theorem totalVariation_joint_common_kernel (p q : α → ℝ) (k : α → β → ℝ) + (hk : ∀ a, IsProbability (k a)) : + totalVariation (fun ab : α × β => p ab.1 * k ab.1 ab.2) + (fun ab : α × β => q ab.1 * k ab.1 ab.2) = totalVariation p q := by + have hpoint : ∀ a b, |p a * k a b - q a * k a b| = |p a - q a| * k a b := by + intro a b + rw [← sub_mul, abs_mul, abs_of_nonneg ((hk a).1 b)] + simp only [totalVariation, Fintype.sum_prod_type, hpoint, ← Finset.mul_sum, + (hk _).2, mul_one] + +theorem totalVariation_condition_le (p q : α → ℝ) (event : α → Prop) + [DecidablePred event] {c : ℝ} (hc : 0 < c) : + totalVariation (fun a => if event a then p a / c else 0) + (fun a => if event a then q a / c else 0) ≤ totalVariation p q / c := by + have hpoint : ∀ a, |(if event a then p a / c else 0) - + (if event a then q a / c else 0)| ≤ |p a - q a| / c := by + intro a + by_cases he : event a + · simp only [ite_eq_left he, ← sub_div, abs_div, abs_of_pos hc, le_refl] + · simp only [ite_eq_right he, sub_self, abs_zero] + exact div_nonneg (abs_nonneg _) hc.le + have hsum := Finset.sum_le_sum (fun a (_ : a ∈ (Finset.univ : Finset α)) => hpoint a) + simp only [div_eq_mul_inv, ← Finset.sum_mul] at hsum + have hd := div_le_div_of_nonneg_right hsum (show (0 : ℝ) ≤ 2 by norm_num) + have hreorder : ((∑ a, |p a - q a|) * c⁻¹) / 2 = + ((∑ a, |p a - q a|) / 2) / c := by ring + rw [hreorder] at hd + simpa only [totalVariation, div_eq_mul_inv] using hd + +theorem weighted_coordinate_sum_sq_le + (w : α → ℝ) (d : α → β → ℝ) (C : α → ℝ) + (hw : IsProbability w) + (hbudget : ∀ a, w a * (∑ b, d a b ^ 2) ≤ w a * C a) : + (∑ b, ∑ a, w a * d a b)^2 ≤ + (Fintype.card β : ℝ) * (∑ a, w a * C a) := by + have hv := Finset.sum_le_sum + (fun b (_ : b ∈ (Finset.univ : Finset β)) => + weighted_sum_sq_le w (fun a => d a b) hw) + have he : + (∑ b, ∑ a, w a * d a b ^ 2) = + ∑ a, w a * (∑ b, d a b ^ 2) := by + rw [Finset.sum_comm] + simp only [Finset.mul_sum] + rw [he] at hv + have hb := Finset.sum_le_sum + (fun a (_ : a ∈ (Finset.univ : Finset α)) => hbudget a) + have hs := hv.trans hb + have hcs := Finset.sum_mul_sq_le_sq_mul_sq + (Finset.univ : Finset β) + (fun b => ∑ a, w a * d a b) (fun _ => (1 : ℝ)) + simp only [mul_one, one_pow, Finset.sum_const, + Finset.card_univ, nsmul_eq_mul, mul_one] at hcs + calc + (∑ b, ∑ a, w a * d a b)^2 + ≤ (∑ b, (∑ a, w a * d a b)^2) * + (Fintype.card β : ℝ) := hcs + _ = (Fintype.card β : ℝ) * + (∑ b, (∑ a, w a * d a b)^2) := mul_comm _ _ + _ ≤ (Fintype.card β : ℝ) * (∑ a, w a * C a) := + mul_le_mul_of_nonneg_left hs (Nat.cast_nonneg _) + +end MinUncutGames.Foundations.Information + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Games/Target.lean b/lean/OAI/Computability/MinUncut/Games/Target.lean new file mode 100644 index 0000000000000000000000000000000000000000..9cb572be74a64b26f18e87992e06048ce70e59d5 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Games/Target.lean @@ -0,0 +1,111 @@ +import Mathlib +import OAI.Computability.MinUncut.Model + +namespace OAI + +section +namespace MinUncutGames.Foundations.Target + +structure Literal («variables» : Nat) where + variableIndex : Fin «variables» + positive : Bool + deriving DecidableEq + +def Literal.eval {n : Nat} (literal : Literal n) (assignment : Fin n → Bool) : Bool := + if literal.positive then assignment literal.variableIndex else !(assignment literal.variableIndex) + +abbrev Clause («variables» : Nat) := Vector (Literal «variables») 3 + +def Clause.eval {n : Nat} (clause : Clause n) (assignment : Fin n → Bool) : Bool := + (clause[0].eval assignment || clause[1].eval assignment) || clause[2].eval assignment + +structure Formula where + «variables» : Nat + clauses : List (Clause «variables») + +def Formula.Satisfiable (formula : Formula) : Prop := + ∃ assignment : Fin formula.«variables» → Bool, + ∀ clause ∈ formula.clauses, clause.eval assignment = true + +structure PermutationTable (alphabet : Nat) where + images : Vector (Fin alphabet) alphabet + inverseImages : Vector (Fin alphabet) alphabet + leftInverse : ∀ label : Fin alphabet, inverseImages[images[label]] = label + rightInverse : ∀ label : Fin alphabet, images[inverseImages[label]] = label + +theorem PermutationTable.images_injective {q : Nat} (table : PermutationTable q) + {x y : Fin q} (h : table.images[x] = table.images[y]) : x = y := by + have inverseEquality := congrArg (fun label : Fin q => table.inverseImages[label]) h + simpa only [table.leftInverse] using inverseEquality + +theorem PermutationTable.images_surjective {q : Nat} (table : PermutationTable q) + (label : Fin q) : ∃ preimage : Fin q, table.images[preimage] = label := + ⟨table.inverseImages[label], table.rightInverse label⟩ + +structure Constraint (vertices alphabet : Nat) where + source : Fin vertices + target : Fin vertices + permutation : PermutationTable alphabet + +def Constraint.satisfied {n q : Nat} (constraint : Constraint n q) + (labeling : Fin n → Fin q) : Bool := + decide (constraint.permutation.images[labeling constraint.source] = labeling constraint.target) + +structure Instance (alphabet : Nat) where + vertices : Nat + constraints : List (Constraint vertices alphabet) + nonempty : constraints ≠ [] + +def countSatisfied {n q : Nat} (labeling : Fin n → Fin q) : + List (Constraint n q) → Nat + | [] => 0 + | constraint :: rest => + (if constraint.satisfied labeling then 1 else 0) + countSatisfied labeling rest + +theorem countSatisfied_le_length {n q : Nat} (labeling : Fin n → Fin q) + (constraints : List (Constraint n q)) : + countSatisfied labeling constraints ≤ constraints.length := by + induction constraints with + | nil => simp [countSatisfied] + | cons constraint rest ih => + simp only [countSatisfied, List.length_cons] + split <;> omega + +theorem Instance.constraintCount_positive {q : Nat} (game : Instance q) : + 0 < game.constraints.length := by + cases h : game.constraints with + | nil => exact False.elim (game.nonempty h) + | cons constraint rest => simp + +structure RationalError where + numerator : Nat + denominator : Nat + numeratorPositive : 0 < numerator + denominatorPositive : 0 < denominator + belowHalf : 2 * numerator < denominator + +def CompleteAt {q : Nat} (error : RationalError) (game : Instance q) : Prop := + ∃ labeling : Fin game.vertices → Fin q, + error.denominator * game.constraints.length ≤ + error.denominator * countSatisfied labeling game.constraints + + error.numerator * game.constraints.length + +def SoundAt {q : Nat} (error : RationalError) (game : Instance q) : Prop := + ∀ labeling : Fin game.vertices → Fin q, + error.denominator * countSatisfied labeling game.constraints ≤ + error.numerator * game.constraints.length + +structure SemanticGapReduction (completenessError soundnessError : RationalError) where + alphabet : Nat + alphabetAtLeastTwo : 2 ≤ alphabet + reduce : Formula → Instance alphabet + completeness : ∀ formula : Formula, + formula.Satisfiable → CompleteAt completenessError (reduce formula) + soundness : ∀ formula : Formula, + ¬ formula.Satisfiable → SoundAt soundnessError (reduce formula) + +end MinUncutGames.Foundations.Target + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Games/TotalVariation.lean b/lean/OAI/Computability/MinUncut/Games/TotalVariation.lean new file mode 100644 index 0000000000000000000000000000000000000000..fb8ef0aa07eca47df713d1132769fd8c8971924e --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Games/TotalVariation.lean @@ -0,0 +1,287 @@ +import Mathlib +import OAI.Computability.MinUncut.Games.Sampling + +namespace OAI + +namespace MinUncutGames.Foundations.Games.FiniteDistribution + +open scoped BigOperators +noncomputable section + +variable {Ω : Type*} [Fintype Ω] + +def totalVariation (μ ν : FiniteDistribution Ω) : ℝ := + (∑ x, |μ.weight x - ν.weight x|) / 2 + +theorem totalVariation_nonnegative (μ ν : FiniteDistribution Ω) : + 0 ≤ μ.totalVariation ν := + div_nonneg (Finset.sum_nonneg fun _ _ => abs_nonneg _) (by norm_num) + +theorem totalVariation_comm (μ ν : FiniteDistribution Ω) : + μ.totalVariation ν = ν.totalVariation μ := by + unfold totalVariation + congr 1 + apply Finset.sum_congr rfl + intro x _ + exact abs_sub_comm _ _ + +theorem probability_sub_le_totalVariation (μ ν : FiniteDistribution Ω) + (event : Ω → Bool) : + μ.probability event - ν.probability event ≤ μ.totalVariation ν := by + have pointwise (x : Ω) : + 2 * ((if event x then μ.weight x else 0) - + (if event x then ν.weight x else 0)) ≤ + |μ.weight x - ν.weight x| + (μ.weight x - ν.weight x) := by + have h₁ := le_abs_self (μ.weight x - ν.weight x) + have h₂ := neg_le_abs (μ.weight x - ν.weight x) + cases event x <;> simp only [Bool.false_eq_true, ↓reduceIte] <;> linarith + have summed := Finset.sum_le_sum (s := Finset.univ) fun x _ => pointwise x + simp only [← Finset.mul_sum, Finset.sum_add_distrib, Finset.sum_sub_distrib, + μ.normalized, ν.normalized, sub_self, add_zero] at summed + unfold probability totalVariation + linarith + +theorem probability_abs_sub_le_totalVariation (μ ν : FiniteDistribution Ω) + (event : Ω → Bool) : + |μ.probability event - ν.probability event| ≤ μ.totalVariation ν := by + apply abs_le.mpr + constructor + · have h := ν.probability_sub_le_totalVariation μ event + rw [totalVariation_comm] at h + linarith + · exact μ.probability_sub_le_totalVariation ν event + +theorem probability_le_add_totalVariation (μ ν : FiniteDistribution Ω) + (event : Ω → Bool) : + μ.probability event ≤ ν.probability event + μ.totalVariation ν := by + have h := μ.probability_sub_le_totalVariation ν event + linarith + +end +end MinUncutGames.Foundations.Games.FiniteDistribution + +namespace MinUncutGames.Foundations.Games + +open scoped BigOperators + +noncomputable section + +namespace FiniteDistribution + +variable {Ω : Type*} [Fintype Ω] + +def condition (μ : FiniteDistribution Ω) (given : Ω → Bool) + (positive : 0 < μ.probability given) : FiniteDistribution Ω where + weight x := if given x then μ.weight x / μ.probability given else 0 + nonnegative x := by + split + · exact div_nonneg (μ.nonnegative x) positive.le + · exact le_rfl + normalized := by + calc + _ = (∑ x, if given x then μ.weight x else 0) / μ.probability given := by + simp only [div_eq_mul_inv, Finset.sum_mul] + apply Finset.sum_congr rfl + intro x _ + by_cases hx : given x = true <;> simp [hx] + _ = 1 := div_self (ne_of_gt positive) + +theorem probability_condition (μ : FiniteDistribution Ω) (given event : Ω → Bool) + (positive : 0 < μ.probability given) : + (μ.condition given positive).probability event = + μ.probability (fun x => given x && event x) / μ.probability given := by + simp only [probability, condition, div_eq_mul_inv, Finset.sum_mul] + apply Finset.sum_congr rfl + intro x _ + by_cases hg : given x = true <;> by_cases he : event x = true <;> simp [hg, he] + +theorem probability_inter_eq_mul_conditional (μ : FiniteDistribution Ω) + (given event : Ω → Bool) (positive : 0 < μ.probability given) : + μ.probability (fun x => given x && event x) = + μ.probability given * (μ.condition given positive).probability event := by + have h := (eq_div_iff (ne_of_gt positive)).mp + (μ.probability_condition given event positive) + simpa only [mul_comm] using h.symm + +theorem probability_and_le_left (μ : FiniteDistribution Ω) (event event' : Ω → Bool) : + μ.probability (fun x => event x && event' x) ≤ μ.probability event := by + apply μ.probability_mono + intro x hx + have h : event x = true ∧ event' x = true := by simpa using hx + exact h.1 + +theorem probability_and_le_right (μ : FiniteDistribution Ω) (event event' : Ω → Bool) : + μ.probability (fun x => event x && event' x) ≤ μ.probability event' := by + apply μ.probability_mono + intro x hx + have h : event x = true ∧ event' x = true := by simpa using hx + exact h.2 + +theorem probability_and_eq_zero_of_probability_eq_zero (μ : FiniteDistribution Ω) + (given event : Ω → Bool) (zero : μ.probability given = 0) : + μ.probability (fun x => given x && event x) = 0 := by + apply le_antisymm + · exact (μ.probability_and_le_left given event).trans_eq zero + · exact μ.probability_nonnegative _ + +@[simp] theorem probability_condition_given (μ : FiniteDistribution Ω) + (given : Ω → Bool) (positive : 0 < μ.probability given) : + (μ.condition given positive).probability given = 1 := by + rw [μ.probability_condition] + simpa only [Bool.and_self] using div_self (ne_of_gt positive) + +end FiniteDistribution + +namespace Game + +variable {Q₁ Q₂ A₁ A₂ : Type*} + [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂] + {n : Nat} + +theorem selectedWins_insert (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (coordinate : Fin n) : + G.selectedWins strategy (insert coordinate selected) = + fun questions => + G.selectedWins strategy selected questions && G.coordinateWin strategy coordinate questions := by + classical + funext questions + apply Bool.eq_iff_iff.mpr + simp [selectedWins, and_comm] + +def selectedSuccess (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) : ℝ := + (G.repetition n).questions.probability (G.selectedWins strategy selected) + +theorem selectedSuccess_nonnegative (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) : 0 ≤ G.selectedSuccess strategy selected := + (G.repetition n).questions.probability_nonnegative _ + +theorem selectedSuccess_le_one (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) : G.selectedSuccess strategy selected ≤ 1 := + (G.repetition n).questions.probability_le_one _ + +@[simp] theorem selectedSuccess_empty (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) : + G.selectedSuccess strategy ∅ = 1 := by + have h : G.selectedWins strategy ∅ = fun _ => true := + funext (G.selectedWins_empty strategy) + rw [selectedSuccess, h, FiniteDistribution.probability_true] + +theorem selectedSuccess_univ (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) : + G.selectedSuccess strategy Finset.univ = (G.repetition n).success strategy := by + rw [selectedSuccess, G.selectedWins_univ] + rfl + +theorem selectedSuccess_antitone (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) : + Antitone (G.selectedSuccess strategy) := by + intro selected selected' h + exact G.selectedWins_mono strategy h + +theorem selectedSuccess_insert (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (coordinate : Fin n) + (positive : 0 < G.selectedSuccess strategy selected) : + G.selectedSuccess strategy (insert coordinate selected) = + G.selectedSuccess strategy selected * + ((G.repetition n).questions.condition (G.selectedWins strategy selected) positive).probability + (G.coordinateWin strategy coordinate) := by + unfold selectedSuccess + rw [G.selectedWins_insert] + exact (G.repetition n).questions.probability_inter_eq_mul_conditional _ _ positive + +theorem selectedSuccess_insert_eq_zero (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (coordinate : Fin n) + (zero : G.selectedSuccess strategy selected = 0) : + G.selectedSuccess strategy (insert coordinate selected) = 0 := by + apply le_antisymm + · exact (G.selectedSuccess_antitone strategy (Finset.subset_insert coordinate selected)).trans_eq zero + · exact G.selectedSuccess_nonnegative _ _ + +end Game + +end + +end MinUncutGames.Foundations.Games + +namespace MinUncutGames.Foundations.Information + +open scoped BigOperators + +variable {α β : Type*} [Fintype α] [Fintype β] + +theorem gameLaw_isProbability (μ : Games.FiniteDistribution α) : IsProbability μ.weight := + ⟨μ.nonnegative, μ.normalized⟩ + +def toGameLaw (p : α → ℝ) (hp : IsProbability p) : Games.FiniteDistribution α where + weight := p + nonnegative := hp.1 + normalized := hp.2 + +def gameLawEquiv : Games.FiniteDistribution α ≃ {p : α → ℝ // IsProbability p} where + toFun μ := ⟨μ.weight, gameLaw_isProbability μ⟩ + invFun p := toGameLaw p.1 p.2 + left_inv μ := by cases μ; rfl + right_inv p := by cases p; rfl + +theorem totalVariation_gameLaw (μ ν : Games.FiniteDistribution α) : + totalVariation μ.weight ν.weight = μ.totalVariation ν := rfl + +noncomputable def gameConditionalKernel (μ : Games.FiniteDistribution (α × β)) + (fallback : Games.FiniteDistribution β) (a : α) : Games.FiniteDistribution β := + toGameLaw (conditionalKernel μ.weight fallback.weight a) + (conditionalKernel_isProbability μ.weight fallback.weight + (gameLaw_isProbability μ) (gameLaw_isProbability fallback) a) + +theorem gameConditionalKernel_recombine (μ : Games.FiniteDistribution (α × β)) + (fallback : Games.FiniteDistribution β) (a : α) (b : β) : + firstMarginal μ.weight a * (gameConditionalKernel μ fallback a).weight b = + μ.weight (a, b) := + marginal_mul_conditionalKernel μ.weight fallback.weight (gameLaw_isProbability μ) a b + +noncomputable def gameConditionalProduct (μ : Games.FiniteDistribution (α × β)) + (fallback : Games.FiniteDistribution β) (newInput : Games.FiniteDistribution α) : + Games.FiniteDistribution (α × β) := + toGameLaw (fun ab => newInput.weight ab.1 * conditionalKernel μ.weight fallback.weight ab.1 ab.2) + (alternativeInput_conditionalProduct_isProbability μ.weight fallback.weight newInput.weight + (gameLaw_isProbability μ) (gameLaw_isProbability fallback) (gameLaw_isProbability newInput)) + +theorem gameConditionalProduct_weight (μ : Games.FiniteDistribution (α × β)) + (fallback : Games.FiniteDistribution β) (newInput : Games.FiniteDistribution α) + (a : α) (b : β) : + (gameConditionalProduct μ fallback newInput).weight (a, b) = + newInput.weight a * (gameConditionalKernel μ fallback a).weight b := rfl + +theorem gameCondition_weight (μ : Games.FiniteDistribution α) (event : α → Bool) + (positive : 0 < μ.probability event) : + (μ.condition event positive).weight = + posterior μ.weight (fun a => if event a then 1 else 0) (μ.probability event) := by + funext a + cases he : event a <;> simp [Games.FiniteDistribution.condition, posterior, he] + +theorem gameCondition_relativeEntropy_le (μ : Games.FiniteDistribution α) (event : α → Bool) + (positive : 0 < μ.probability event) : + relativeEntropy (μ.condition event positive).weight μ.weight ≤ + Real.log (1 / μ.probability event) := by + rw [gameCondition_weight] + apply posterior_relativeEntropy_le μ.weight (fun a => if event a then 1 else 0) + (gameLaw_isProbability μ) + · intro a + cases event a <;> norm_num + · intro a + cases event a <;> norm_num + · exact positive + · unfold Games.FiniteDistribution.probability + apply Finset.sum_congr rfl + intro a _ + cases event a <;> simp + +end MinUncutGames.Foundations.Information + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Games/TripleKernel.lean b/lean/OAI/Computability/MinUncut/Games/TripleKernel.lean new file mode 100644 index 0000000000000000000000000000000000000000..8538456173a4f5190886ebf141953b79b0b33741 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Games/TripleKernel.lean @@ -0,0 +1,61 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.Density + +namespace OAI + +noncomputable section +open scoped BigOperators +open MeasureTheory ProbabilityTheory Filter +open scoped Topology NNReal +open scoped BigOperators +namespace MinUncut.Composition +open BinaryFourier OuterSmoothness +variable {W : Type*} [AddCommGroup W] [Module F₂ W] [Fintype W] +local instance tripleKernelDecidableEq : DecidableEq W := Classical.decEq W +attribute [local instance] BinaryFourier.dualFintype + +def tripleKernel (f : W → ℝ) (v : W × W × W) : ℝ := + f v.1 * f v.2.1 * f v.2.2 * f (v.1+v.2.1+v.2.2) + +lemma tripleKernel_mean (f : W → ℝ) : + (𝔼 v : W × W × W, tripleKernel f v) = + ∑ α : Module.Dual F₂ W, coefficient f α ^ 4 := by + unfold tripleKernel + rw [expect_pair] + simp_rw [expect_pair] + exact fourth_moment f + +omit [Module F₂ W] [Fintype W] in +lemma tripleKernel_abs (f : W → ℝ) {M : ℝ} (hM : 0 ≤ M) + (hf : ∀ w, |f w| ≤ M) (v : W × W × W) : |tripleKernel f v| ≤ M^4 := by + simp only [tripleKernel, abs_mul] + calc _ ≤ M * M * M * M := by + gcongr <;> exact hf _ + _ = _ := by ring + +theorem adaptive_fourth_moment {B : Type*} [Fintype B] [Nonempty B] + (p : Density (B × (W × W × W))) (f : B → W → ℝ) {M u : ℝ} + (hM : 0 ≤ M) (hu : 0 < u) (hf : ∀ b w, |f b w| ≤ M) : + (𝔼 z, p z * tripleKernel (remainder (f z.1) u) z.2) ≤ + u^2 * M^2 + 2 * p.tvUniform * (M + M^2/u)^4 := by + let g : B × (W × W × W) → ℝ := fun z => tripleKernel (remainder (f z.1) u) z.2 + have hMr : 0 ≤ M + M^2/u := by positivity + have hg (z : B × (W × W × W)) : |g z| ≤ (M + M^2/u)^4 := + tripleKernel_abs _ hMr (remainder_abs_bound (f z.1) hM hu (hf z.1)) z.2 + have hdiff := Density.expect_difference p g (pow_nonneg hMr _) hg + have hmean : (𝔼 z, g z) ≤ u^2 * M^2 := by + change (𝔼 z : B × (W × W × W), tripleKernel (remainder (f z.1) u) z.2) ≤ _ + rw [expect_pair] + simp_rw [tripleKernel_mean] + calc _ ≤ 𝔼 b : B, u^2 * M^2 := Finset.expect_le_expect (fun b _ => + remainder_fourth_bound (f b) hM hu (hf b)) + _ = _ := Fintype.expect_const _ + have habs := le_abs_self ((𝔼 z, p z * g z) - (𝔼 z, g z)) + dsimp only [g] at hdiff hmean habs + linarith + +end MinUncut.Composition + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Graphs/CanonicalPathGraph.lean b/lean/OAI/Computability/MinUncut/Graphs/CanonicalPathGraph.lean new file mode 100644 index 0000000000000000000000000000000000000000..b3a03e5bd1b1e94501baa8a8c7a45dd1930409c8 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Graphs/CanonicalPathGraph.lean @@ -0,0 +1,461 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.Occurrences +import OAI.Computability.MinUncut.Graphs.GraphOutput +import OAI.Computability.MinUncut.Estimates.PolynomialRecursor + +namespace OAI + +section +open scoped BigOperators +namespace MinUncut.PathRealization + +def number (N M : ℕ) : Vertex (Fin N) (Fin M) ≃ Fin (N+M*3) := + (Equiv.sumCongr (Equiv.refl _) finProdFinEquiv).trans finSumFinEquiv + +lemma number_left (N M : ℕ) (v : Fin N) : (number N M (.inl v)).val=v.val := rfl +lemma number_right (N M : ℕ) (d : Fin M) (i : Fin 3) : + (number N M (.inr (d,i))).val=N+i.val+3*d.val := by + simp [number,finProdFinEquiv,finSumFinEquiv,Nat.add_assoc] + +def canonicalAdjacent {N M : ℕ} (e : Fin M → Demand (Fin N)) + (u v : Fin (N+M*3)) : Bool := + decide (∃ d : Fin M, ∃ j : Fin 4, + j.val < (if (e d).equal then 4 else 3) ∧ + ((u=number N M (ends e (d,j)).1 ∧ v=number N M (ends e (d,j)).2) ∨ + (v=number N M (ends e (d,j)).1 ∧ u=number N M (ends e (d,j)).2))) + +lemma canonicalAdjacent_symmetric {N M : ℕ} (e : Fin M → Demand (Fin N)) + (u v : Fin (N+M*3)) : canonicalAdjacent e u v=canonicalAdjacent e v u := by + simp only [canonicalAdjacent,decide_eq_decide] + apply exists_congr + intro d + apply exists_congr + intro j + exact and_congr_right (fun _ => or_comm) + +lemma canonicalAdjacent_loopless {N M : ℕ} (e : Fin M → Demand (Fin N)) + (u : Fin (N+M*3)) : canonicalAdjacent e u u=false := by + simp only [canonicalAdjacent,decide_eq_false_iff_not] + rintro ⟨d,j,hj,h|h⟩ <;> + exact ends_ne e ⟨(d,j),hj⟩ ((number N M).injective (h.1.symm.trans h.2)) + +def canonicalOutput {N M : ℕ} (e : Fin M → Demand (Fin N)) (k : ℕ) (hk : 1≤k) : Output where + vertices := N+M*3 + adjacent := canonicalAdjacent e + symmetric := canonicalAdjacent_symmetric e + loopless := canonicalAdjacent_loopless e + threshold := k + threshold_pos := hk + +lemma canonicalOutput_eq {N M : ℕ} (e : Fin M → Demand (Fin N)) (k : ℕ) (hk : 1≤k) : + canonicalOutput e k hk=output e (number N M) k hk := by + have ha : canonicalAdjacent e=(output e (number N M) k hk).adjacent := by + funext u v + apply Bool.eq_iff_iff.mpr + rw [output_adjacent_iff] + simp only [canonicalAdjacent,decide_eq_true_eq] + constructor + · rintro ⟨d,j,hj,h⟩ + refine ⟨⟨(d,j),hj⟩,?_⟩ + change s(u,v)=s(number N M (ends e (d,j)).1,number N M (ends e (d,j)).2) + exact Sym2.eq_iff.mpr (h.imp id And.symm) + · rintro ⟨⟨⟨d,j⟩,hj⟩,h⟩ + exact ⟨d,j,hj,(Sym2.eq_iff.mp h).imp id And.symm⟩ + unfold output at ha + unfold canonicalOutput output + congr 1 + +lemma canonicalOutput_yes {N M : ℕ} (e : Fin M → Demand (Fin N)) (k : ℕ) (hk : 1≤k) + (s : Fin N → Bool) (h : totalFailure e s≤k) : (canonicalOutput e k hk).opt≤k := by + rw [canonicalOutput_eq] + exact output_yes _ _ _ _ s h + +lemma canonicalOutput_no {N M : ℕ} (e : Fin M → Demand (Fin N)) (k : ℕ) (hk : 1≤k) + (K : ℕ) (h : ∀ s, K*k[0]) (fun w=>[accumulatedEdge.eval w]) v + +lemma cumulative_le_one (v : List ℕ) (n : ℕ) : cumulative v n≤1 := by + cases n with + | zero => simp only [cumulative,scalarRec,List.headI_cons]; omega + | succ n => exact accumulatedEdge_le_one _ + +noncomputable def adjacencyProgram : PolyProgram (fun v=>[cumulative v (v.drop 1).headI]) := + (prec (const 0) accumulatedEdge.program 1 (by + intro n v i hi + simpa only [eval_one,cumulative] using cumulative_le_one v i)).comp + ((projection 1).cons id) + +open PolyProgram Polynomial + +structure RenderState where + N : ℕ + M : ℕ + threshold : ℕ + V : ℕ + row : ℕ + col : ℕ + q : ℕ + tape : List ℕ + +def RenderState.encode (s : RenderState) : List ℕ := + s.N::s.M::s.threshold::s.V::s.row::s.col::s.q::s.tape + +def parseState (v : List ℕ) : RenderState := + ⟨v.headI,(v.drop 1).headI,(v.drop 2).headI,(v.drop 3).headI, + (v.drop 4).headI,(v.drop 5).headI,(v.drop 6).headI,v.drop 7⟩ + +@[simp] lemma parse_encode (s : RenderState) : parseState s.encode=s := by + cases s; rfl + +def RenderState.tick (s : RenderState) : RenderState := + {s with row := if s.col=0 then s.row-1 else s.row + col := if s.col=0 then s.V-1 else s.col-1 + q := s.q+1 + tape := cumulative s.encode s.M::s.tape} + +def renderTick (v : List ℕ) : List ℕ := (parseState v).tick.encode + +lemma renderTick_encode (s : RenderState) : renderTick s.encode=s.tick.encode := by + simp only [renderTick,parse_encode] + +def nextRow : Expr := .cond (.reg 5) (.sub (.reg 4) (.const 1)) (.reg 4) +def nextCol : Expr := .cond (.reg 5) (.sub (.reg 3) (.const 1)) (.sub (.reg 5) (.const 1)) +def nextCount : Expr := .add (.reg 6) (.const 1) + +noncomputable def normalizeProgram : PolyProgram (fun v=>(parseState v).encode) := + ((projection 0).cons ((projection 1).cons ((projection 2).cons ((projection 3).cons + ((projection 4).cons ((projection 5).cons ((projection 6).cons (drop 7)))))))).ofEq (by intro v; rfl) + +noncomputable def tickProgram : PolyProgram renderTick := + (((projection 0).cons ((projection 1).cons ((projection 2).cons ((projection 3).cons + (nextRow.program.cons (nextCol.program.cons (nextCount.program.cons + (adjacencyProgram.cons (drop 7))))))))).comp normalizeProgram).ofEq (by + intro v + rfl) + +lemma parse_encode_magnitude (v : List ℕ) : magnitude (parseState v).encode≤8*magnitude v+7 := by + have h (i : ℕ) := (magnitude_head (v.drop i)).trans (magnitude_drop i v) + have h₀ := h 0; have h₁ := h 1; have h₂ := h 2; have h₃ := h 3 + have h₄ := h 4; have h₅ := h 5; have h₆ := h 6 + have ht := magnitude_drop 7 v + simp only [parseState,RenderState.encode,magnitude_cons] + simp only [List.drop_zero] at h₀ + omega + +lemma tick_V (s : RenderState) : s.tick.V=s.V := rfl + +lemma tick_magnitude (s : RenderState) : + magnitude s.tick.encode≤ magnitude s.encode+s.V+3 := by + have h := cumulative_le_one s.encode s.M + simp only [RenderState.encode] at h + have hr : (if s.col=0 then s.row-1 else s.row)≤ s.row := by split_ifs <;> omega + have hc : (if s.col=0 then s.V-1 else s.col-1)≤ s.col+s.V := by split_ifs <;> omega + simp only [RenderState.encode,RenderState.tick,magnitude_cons] + omega + +lemma tick_iter_V (n : ℕ) (s : RenderState) : (RenderState.tick^[n] s).V=s.V := by + induction n with + | zero => rfl + | succ n ih => simpa only [Function.iterate_succ_apply',tick_V] using ih + +lemma tick_iter_magnitude (n : ℕ) (s : RenderState) : + magnitude (RenderState.tick^[n] s).encode≤ magnitude s.encode+n*(s.V+3) := by + induction n with + | zero => simp + | succ n ih => + have h := tick_magnitude (RenderState.tick^[n] s) + rw [tick_iter_V] at h + simp only [Function.iterate_succ_apply'] + simp only [Nat.succ_mul] at * + omega + +lemma renderTick_iter_encode (n : ℕ) (s : RenderState) : + renderTick^[n] s.encode=(RenderState.tick^[n] s).encode := by + induction n with + | zero => rfl + | succ n ih => simp only [Function.iterate_succ_apply',ih,renderTick_encode] + +lemma renderTick_iter_succ (n : ℕ) (v : List ℕ) : + renderTick^[n+1] v=(RenderState.tick^[n+1] (parseState v)).encode := by + rw [Function.iterate_succ_apply,renderTick,renderTick_iter_encode,Function.iterate_succ_apply] + +lemma renderTick_iter_bound (n : ℕ) (v : List ℕ) (i : ℕ) (hi : i≤n) : + magnitude (renderTick^[i] v)≤(C 20*(X+1)^2:Polynomial ℕ).eval (magnitude (n::v)) := by + simp only [Polynomial.eval_mul, Polynomial.eval_C, Polynomial.eval_pow, + Polynomial.eval_add, Polynomial.eval_X, Polynomial.eval_one, magnitude_cons] + let s := n+1+magnitude v+1 + have hs : 1≤ s := by dsimp [s]; omega + have hm : magnitude v≤ s := by dsimp [s]; omega + have hn : n≤ s := by dsimp [s]; omega + have hsq : s≤ s^2 := Nat.le_self_pow (by omega) _ + cases i with + | zero => simp only [Function.iterate_zero,Function.id_def]; nlinarith + | succ i => + rw [renderTick_iter_succ] + have h := tick_iter_magnitude (i+1) (parseState v) + have h₀ := parse_encode_magnitude v + have hv : (parseState v).V≤ magnitude v := + (magnitude_head (v.drop 3)).trans (magnitude_drop 3 v) + have hprod : (i+1)*((parseState v).V+3)≤ s*(3*s) := + Nat.mul_le_mul (by omega) (by omega) + have hh : magnitude (RenderState.tick^[i+1] (parseState v)).encode≤8*s+7+3*s^2 := by + nlinarith + change _≤20*s^2 + nlinarith + +noncomputable def renderLoop : PolyProgram (fun v=>renderTick^[v.headI] v.tail) := + iterate tickProgram (C 20*(X+1)^2) renderTick_iter_bound + +open MinUncut.PathRealization +open PolyProgram + +def queryState (N M k V u v : ℕ) (acc data : List ℕ) : RenderState := + ⟨N,M,k,V,u,v,acc.length,acc++2::k::data⟩ + +def endpoint (u v a b : ℕ) : Prop := (u=a ∧ v=b) ∨ (u=b ∧ v=a) +instance (u v a b : ℕ) : Decidable (endpoint u v a b) := inferInstanceAs (Decidable (_∨_)) + +def localAdj (N d l r e u v : ℕ) : Prop := + endpoint u v l (N+3*d) ∨ endpoint u v (N+3*d) (N+3*d+1) ∨ + if e=0 then endpoint u v (N+3*d+1) r + else endpoint u v (N+3*d+1) (N+3*d+2) ∨ endpoint u v (N+3*d+2) r +instance (N d l r e u v : ℕ) : Decidable (localAdj N d l r e u v) := by + unfold localAdj; infer_instance + +def rawLocal (N d : ℕ) (data : List ℕ) (u v : ℕ) : Prop := + localAdj N d (data.drop (3*d)).headI (data.drop (3*d+1)).headI + (data.drop (3*d+2)).headI u v +instance (N d : ℕ) (data : List ℕ) (u v : ℕ) : Decidable (rawLocal N d data u v) := + inferInstanceAs (Decidable (localAdj ..)) + +lemma data_address (N M k V u v d a j : ℕ) (acc data : List ℕ) : + ((d::a::(queryState N M k V u v acc data).encode).drop + (11+acc.length+3*d+j)).headI=(data.drop (3*d+j)).headI := by + have he : 11+acc.length+3*d+j=9+(acc.length+(2+(3*d+j))) := by omega + rw [he,← List.drop_drop] + change ((acc++2::k::data).drop (acc.length+(2+(3*d+j)))).headI=_ + rw [← List.drop_drop,List.drop_left] + rw [Nat.add_comm 2 _] + rfl + +lemma bit_or (P Q : Prop) [Decidable P] [Decidable Q] : + (if (if P then 1 else 0 : ℕ)=0 then (if Q then 1 else 0) else 1)= + if P∨Q then 1 else 0 := by + by_cases hp : P <;> by_cases hq : Q <;> simp [hp,hq] + +lemma localEdge_query (N M k V u v d a : ℕ) (acc data : List ℕ) : + localEdge.eval (d::a::(queryState N M k V u v acc data).encode)= + if rawLocal N d data u v then 1 else 0 := by + have hL : demandLeft.eval (d::a::(queryState N M k V u v acc data).encode)= + (data.drop (3*d)).headI := by + simpa only [demandLeft,demandOffset,Expr.eval,queryState,RenderState.encode, + List.drop_succ_cons,List.drop_zero,List.headI_cons,Nat.add_zero,Nat.add_assoc] + using data_address N M k V u v d a 0 acc data + have hR : demandRight.eval (d::a::(queryState N M k V u v acc data).encode)= + (data.drop (3*d+1)).headI := by + simpa only [demandRight,demandOffset,Expr.eval,queryState,RenderState.encode, + List.drop_succ_cons,List.drop_zero,List.headI_cons,Nat.add_assoc] + using data_address N M k V u v d a 1 acc data + have hE : demandEqual.eval (d::a::(queryState N M k V u v acc data).encode)= + (data.drop (3*d+2)).headI := by + simpa only [demandEqual,demandOffset,Expr.eval,queryState,RenderState.encode, + List.drop_succ_cons,List.drop_zero,List.headI_cons,Nat.add_assoc] + using data_address N M k V u v d a 2 acc data + simp only [localEdge,Expr.eval_or,Expr.eval_edge,Expr.eval_cond,hL,hR,hE] + simp only [privateBase,Expr.eval_add,Expr.eval_mul,Expr.eval_const,Expr.eval_reg, + queryState,RenderState.encode,List.drop_succ_cons,List.drop_zero,List.headI_cons] + simp only [rawLocal,localAdj,endpoint] + by_cases he : (data.drop (3*d+2)).headI=0 <;> + simp only [he,ite_true,ite_false,bit_or] + +lemma cumulative_query (N M k V u v n : ℕ) (acc data : List ℕ) : + cumulative (queryState N M k V u v acc data).encode n= + if ∃d simp [cumulative,scalarRec] + | succ n ih => + change (if cumulative (queryState N M k V u v acc data).encode n=0 then + localEdge.eval (n::cumulative (queryState N M k V u v acc data).encode n:: + (queryState N M k V u v acc data).encode) else 1)=_ + rw [localEdge_query,ih,bit_or] + congr 1 + apply propext + constructor + · rintro (⟨d,hd,h⟩|h) + · exact ⟨d,by omega,h⟩ + · exact ⟨n,by omega,h⟩ + · rintro ⟨d,hd,h⟩ + by_cases he : drawRow N M data u c) + +lemma tick_query (N M k V u v : ℕ) (acc data : List ℕ) : + (queryState N M k V u v acc data).tick= + queryState N M k V (if v=0 then u-1 else u) (if v=0 then V-1 else v-1) + (rawCell N M data u v::acc) data := by + simp only [RenderState.tick,cumulative_query] + unfold queryState rawCell + simp only [List.length_cons,List.cons_append] + +lemma tick_row (N M k V r c : ℕ) (acc data : List ℕ) : + RenderState.tick^[c+1] (queryState N M k V r c acc data)= + queryState N M k V (r-1) (V-1) (rawRow N M data r (c+1)++acc) data := by + induction c generalizing acc with + | zero => + simp only [Nat.zero_add,Function.iterate_one,tick_query] + simp [rawRow] + | succ c ih => + rw [Function.iterate_succ_apply,tick_query] + simp only [Nat.succ_ne_zero,ite_false,Nat.add_sub_cancel] + rw [ih] + simp only [rawRow,List.range_succ,List.map_append,List.map_cons,List.map_nil,List.append_assoc,List.cons_append,List.nil_append] + +lemma tick_rows (N M k V r : ℕ) (hV : 0 + simpa only [Nat.zero_add,Nat.one_mul,Nat.zero_sub,rawTable,List.range_one, + List.flatMap_cons,List.flatMap_nil,List.append_nil] using hrow 0 acc + | succ r ih => + rw [show (r+1+1)*V=(r+1)*V+V by ring,Function.iterate_add_apply,hrow] + simp only [Nat.add_sub_cancel] + rw [ih] + simp only [rawTable,List.range_succ,List.flatMap_append, + List.flatMap_cons,List.flatMap_nil,List.append_nil,List.append_assoc] + +lemma tick_table (N M k V : ℕ) (acc data : List ℕ) : + (RenderState.tick^[V^2] (queryState N M k V (V-1) (V-1) acc data)).tape= + rawTable N M data V V++(acc++2::k::data) := by + by_cases hV : V=0 + · subst V + simp [rawTable,queryState] + · have hp : 0 failure d s)).sum + +lemma listFailure_eq {V : Type*} (ds : List (Demand V)) (s : V → Bool) : + listFailure ds s=totalFailure (fun i : Fin ds.length => ds[i]) s := by + unfold listFailure totalFailure + simp only [Fin.getElem_fin] + rw [← List.sum_ofFn] + exact (congrArg List.sum (List.ofFn_getElem_eq_map ds (fun d => failure d s))).symm + +def demandList {V E : Type} (D : ℕ) (w : E → ℚ) (d : E → Demand V) (enc : Encoding E) : List (Demand V) := + enc.enumerate.flatMap (fun e => List.replicate (multiplicity D (w e)) (d e)) + +lemma sum_enumerate {E : Type} [Fintype E] (enc : Encoding E) (f : E → ℕ) : + (enc.enumerate.map f).sum=∑e, f e := by + simp only [Encoding.enumerate,List.map_ofFn,List.sum_ofFn] + exact Equiv.sum_comp enc.code.symm f + +lemma listFailure_demandList {E V : Type} [Fintype E] (D : ℕ) (w : E → ℚ) + (d : E → Demand V) (enc : Encoding E) (s : V → Bool) : + listFailure (demandList D w d enc) s=∑e, multiplicity D (w e)*failure (d e) s := by + have h : ∀ es : List E, + ((es.flatMap (fun e => List.replicate (multiplicity D (w e)) (d e))).map + (fun d => failure d s)).sum = + (es.map (fun e => multiplicity D (w e)*failure (d e) s)).sum := by + intro es + induction es with + | nil => simp + | cons e es ih => + simp only [List.flatMap_cons,List.map_append,List.sum_append,List.map_replicate, + List.sum_replicate,nsmul_eq_mul,Nat.cast_id,List.map_cons,List.sum_cons,ih] + unfold listFailure demandList + rw [h] + exact sum_enumerate enc _ + +lemma length_demandList {E V : Type} [Fintype E] (D : ℕ) (w : E → ℚ) + (d : E → Demand V) (enc : Encoding E) : + (demandList D w d enc).length=∑e, multiplicity D (w e) := by + rw [demandList,List.length_flatMap] + simp only [List.length_replicate] + exact sum_enumerate enc _ + +noncomputable def extendAssignment {V W : Type*} (f : V → W) (s : V → Bool) (w : W) : Bool := + by + classical + exact if h : ∃ v, f v=w then s (Classical.choose h) else false + +lemma extendAssignment_apply {V W : Type*} (f : V → W) (hf : Function.Injective f) (s : V → Bool) (v : V) : + extendAssignment f s (f v)=s v := by + rw [extendAssignment,dite_eq_left ⟨v,rfl⟩] + exact congrArg s (hf (Classical.choose_spec (show ∃u, f u=f v from ⟨v,rfl⟩))) + +lemma mapDemand_extend {V W : Type*} (f : V → W) (hf : Function.Injective f) (s : V → Bool) (d : Demand V) : + failure (d.map f) (extendAssignment f s)=failure d s := by + simp only [failure,Demand.map,extendAssignment_apply f hf] + +end MinUncut.PathRealization + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Graphs/CanonicalSamplerGraph.lean b/lean/OAI/Computability/MinUncut/Graphs/CanonicalSamplerGraph.lean new file mode 100644 index 0000000000000000000000000000000000000000..58d4fbf843f1306fbd4b7f3d894c558f2c37c571 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Graphs/CanonicalSamplerGraph.lean @@ -0,0 +1,214 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.LiteralLocalTemplates +import OAI.Computability.MinUncut.Estimates.ReversePrefixProgram +import OAI.Computability.MinUncut.Encoding.RawGraphEncoding + +namespace OAI + +section +open scoped BigOperators +namespace MinUncut.PathRealization +open MinUncut.FiniteProof MinUncutGames.Foundations.Hastad.SourceOccurrences + +lemma listFailure_map {V W : Type*} (f : V → W) (ds : List (Demand V)) (s : W → Bool) : + listFailure (ds.map (Demand.map f)) s=listFailure ds (s ∘ f) := by + simp only [listFailure,List.map_map,Function.comp_def,failure_map] + +def listOutput {N : ℕ} (ds : List (Demand (Fin N))) (k : ℕ) (hk : 1≤k) : Output := + canonicalOutput (fun i : Fin ds.length => ds[i]) k hk + +lemma listOutput_yes {N : ℕ} (ds : List (Demand (Fin N))) (k : ℕ) (hk : 1≤k) + (s : Fin N → Bool) (hs : listFailure ds s≤k) : (listOutput ds k hk).opt≤k := + canonicalOutput_yes _ k hk s (by simpa only [← listFailure_eq] using hs) + +lemma listOutput_no {N : ℕ} (ds : List (Demand (Fin N))) (k : ℕ) (hk : 1≤k) + (K : ℕ) (hs : ∀ s, K*k + (List.finRange (N+ds.length*3)).map fun v=>canonicalAdjacent (fun d:Fin ds.length=>ds[d]) u v + +lemma rawRow_pack {N : ℕ} (ds : List (Demand (Fin N))) (u : Fin (N+ds.length*3)) : + rawRow N ds.length (packDemands ds) u.val (N+ds.length*3)= + ((List.finRange (N+ds.length*3)).map fun v=> + canonicalAdjacent (fun d:Fin ds.length=>ds[d]) u v).map Bool.toNat := by + rw [rawRow,←finRange_vals,List.map_map,List.map_map] + congr 1 + funext v + exact rawCell_canonical ds u v + +lemma rawTable_pack {N : ℕ} (ds : List (Demand (Fin N))) : + rawTable N ds.length (packDemands ds) (N+ds.length*3) (N+ds.length*3)= + (canonicalTable ds).map Bool.toNat := by + rw [rawTable,←finRange_vals,List.flatMap_map,canonicalTable,List.map_flatMap] + congr 1 + funext u + exact rawRow_pack ds u + +lemma listOutput_bits {N : ℕ} (ds : List (Demand (Fin N))) (k : ℕ) (hk : 1≤k) : + (listOutput ds k hk).bits=MinUncutGames.BinaryEncoding.nameBits (N+ds.length*3)++ + canonicalTable ds++MinUncutGames.BinaryEncoding.nameBits k := rfl + +end MinUncut.Costed.GraphRegisters + +noncomputable section +namespace MinUncut.Costed.SourceWords +open MinUncut.Inner MinUncut.Outer MinUncut.Outer.LocalTemplate +open MinUncut.PathRealization MinUncutGames.Reduction MinUncut.SourceBridge +open MinUncutGames.Foundations.Hastad.SourceOccurrences + +variable {t k m n : ℕ} {g : MinUncut.FiniteGaussian.GridData} + +def demandExpressions (σ η : ℚ) (e : Index (Fin t) k m n g) : List AExpr := + let T := indexQuery σ η e + [leftExpr T e.2.2.1,rightExpr T e.2.2.1,signExpr T e.2.2.1] + +def localExpressions (E : Enumeration (Index (Fin t) k m n g)) (a : ℚ) + (b : MinUncut.Outer.Test → ℚ) (σ η : ℚ) : List AExpr := + E.values.flatMap (fun e=>(List.replicate (repetitions a b e) (demandExpressions σ η e)).flatten) + +def tupleDemands (input : SourceEncoding.Input) (u : Fin t → Fin input.equations.length) + (E : Enumeration (Index (Fin t) k m n g)) (a : ℚ) (b : MinUncut.Outer.Test → ℚ) + (σ η : ℚ) : List (Demand (Fin (paddedVariableEncoding input.«variables» t).size)) := + E.values.flatMap (fun e=>List.replicate (repetitions a b e) + ((allDemand (equations input) g σ η (occurrence (equations input) (u,e))).map variableCode)) + +lemma demandExpressions_eval (input : SourceEncoding.Input) + (u : Fin t → Fin input.equations.length) (e : Index (Fin t) k m n g) (σ η : ℚ) (rest : List ℕ) : + (demandExpressions σ η e).map (fun x=>x.eval (inputTuple input u++rest))= + GraphRegisters.packDemand ((allDemand (equations input) g σ η + (occurrence (equations input) (u,e))).map variableCode) := by + change queryWords (indexQuery σ η e) e.2.2.1 (inputTuple input u++rest)=_ + rw [queryWords_append,queryWords_eq,occurrence_demand] + rfl + +lemma localExpressions_eval (input : SourceEncoding.Input) + (u : Fin t → Fin input.equations.length) (E : Enumeration (Index (Fin t) k m n g)) + (a : ℚ) (b : MinUncut.Outer.Test → ℚ) (σ η : ℚ) (rest : List ℕ) : + (localExpressions E a b σ η).map (fun x=>x.eval (inputTuple input u++rest))= + GraphRegisters.packDemands (tupleDemands input u E a b σ η) := by + simp only [localExpressions,tupleDemands,GraphRegisters.packDemands,List.map_flatMap, + List.map_flatten,List.flatMap_assoc] + apply congrArg (List.flatMap · E.values) + funext e + simp only [List.map_replicate, demandExpressions_eval,List.flatMap_replicate] + +def tupleList (input : SourceEncoding.Input) (t : ℕ) : List (Fin t → Fin input.equations.length) := + (List.finRange (input.equations.length^t)).map finFunctionFinEquiv.symm + +def generatedDemands (input : SourceEncoding.Input) (E : Enumeration (Index (Fin t) k m n g)) + (a : ℚ) (b : MinUncut.Outer.Test → ℚ) (σ η : ℚ) : + List (Demand (Fin (paddedVariableEncoding input.«variables» t).size)) := + (tupleList input t).flatMap (fun u=>tupleDemands input u E a b σ η) + +lemma emitted_demands (input : SourceEncoding.Input) (E : Enumeration (Index (Fin t) k m n g)) + (a : ℚ) (b : MinUncut.Outer.Test → ℚ) (σ η : ℚ) (rest : List ℕ) : + Blocks.emitted (localExpressions E a b σ η) (input.equations.length^t) + (SourceEncoding.inputWords input++rest)= + GraphRegisters.packDemands (generatedDemands input E a b σ η) := by + rw [Blocks.emitted,←GraphRegisters.finRange_vals] + simp only [generatedDemands,tupleList,List.flatMap_map,GraphRegisters.packDemands, + List.flatMap_assoc] + apply congrArg (List.flatMap · (List.finRange (input.equations.length^t))) + funext z + have h := localExpressions_eval input (finFunctionFinEquiv.symm z) E a b σ η rest + simpa only [Blocks.block,inputTuple,Equiv.apply_symm_apply,List.cons_append,GraphRegisters.packDemands] using h + +end MinUncut.Costed.SourceWords + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Graphs/CompleteGraphProgram.lean b/lean/OAI/Computability/MinUncut/Graphs/CompleteGraphProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..b05b5adcb1de6f8ccc214f76dbff297551dd3de0 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Graphs/CompleteGraphProgram.lean @@ -0,0 +1,140 @@ +import Mathlib +import OAI.Computability.MinUncut.Search.ArithmeticTactic +import OAI.Computability.MinUncut.Graphs.DemandStageEffectivity +import OAI.Computability.MinUncut.Estimates.UniformEquationOutput + +namespace OAI + +noncomputable section +namespace MinUncut.Costed.SourceWords +open MinUncut.Inner MinUncut.Outer MinUncut.Outer.LocalTemplate +open MinUncut.PathRealization MinUncut.FiniteProof MinUncutGames.Reduction MinUncut.SourceBridge +open MinUncutGames.Foundations.Hastad.SourceOccurrences +open MinUncutGames.Foundations.Target MinUncut.SourceTemplate GraphRegisters + +variable {J : ℕ} (P : Parameters J) + (E : Enumeration (Index (Fin P.o.t) P.o.k P.d.m P.d.n P.grid)) + +def graphStageWords (v : List ℕ) : List ℕ := + GraphRegisters.renderRaw (demandStageWords + (localExpressions E (rationalRate J P.d) (rationalBudgets J P.d P.o) + (rationalSigma J) (rationalEta J)) P.o.t P.denominatorCoefficient v) + +def graphStageProgram : PolyProgram (graphStageWords P E) := + GraphRegisters.rawRenderer.comp (demandStageProgram + (localExpressions E (rationalRate J P.d) (rationalBudgets J P.d P.o) + (rationalSigma J) (rationalEta J)) P.o.t P.denominatorCoefficient) + +def completeGraphWords (u D : ℕ) (v : List ℕ) : List ℕ := + graphStageWords P E (sourceStageWords u D v) + +def completeGraphProgram (u D : ℕ) : PolyProgram (completeGraphWords P E u D) := + (graphStageProgram P E).comp (sourceStageProgram u D) + +lemma graphStageWords_spec (input : SourceEncoding.Input) (rest : List ℕ) : + ∃junk,graphStageWords P E (SourceEncoding.inputWords input++rest)= + let ds := generatedDemands input E (rationalRate J P.d) (rationalBudgets J P.d P.o) + (rationalSigma J) (rationalEta J) + ((paddedVariableEncoding input.«variables» P.o.t).size+ds.length*3):: + ((canonicalTable ds).map Bool.toNat++2::(5*P.denominator (Fin input.equations.length))::junk) := by + obtain ⟨junk,hj⟩:=demandStageWords_spec P input E rest + simp only [graphStageWords,hj,GraphRegisters.renderer_pack] + exact ⟨_,rfl⟩ + +lemma completeGraphWords_spec (F : Formula) (u D : ℕ) (hD : 0rationalBudgets (parameterJ K) (selectedInner K) (selectedOuter K) j) := by + let q := tests ℕ + have hc := ca_ratInv (ca_ratCast (computableCard (Face.codes chosenM chosenN c_chosenM c_chosenN chosenN_pos))) + have first : q.Map bool (fun _ j=>decide (j=Test.first)) := + map_fixed_apply SampleEnumeration.tests.encoding Encoding.bool (fun j=>decide (j=Test.first)) (map_id q) + have second : q.Map bool (fun _ j=>decide (j=Test.second)) := + map_fixed_apply SampleEnumeration.tests.encoding Encoding.bool (fun j=>decide (j=Test.second)) (map_id q) + have third : q.Map bool (fun _ j=>decide (j=Test.third)) := + map_fixed_apply SampleEnumeration.tests.encoding Encoding.bool (fun j=>decide (j=Test.third)) (map_id q) + have h := Out.cond first (out_const q (ca_ratMul (ca_const 10) (c_sigma.comp c_parameterJ))) + (Out.cond second (out_const q (ca_ratMul (ca_const 10) + (ca_ratAdd (c_eta.comp c_parameterJ) (c_eta.comp c_parameterJ)))) + (Out.cond third (out_const q hc) (out_const q (c_outerData_b4.comp c_selectedOuter)))) + exact h.ofEq (by intro K j; cases j <;> rfl) +lemma c_chosenAccuracy : Computable (fun K=>tableAccuracy (parameterJ K) (selectedInner K) (selectedOuter K)) := by + exact ca_ratDiv (ca_const 1) (ca_ratMul (ca_const 8) + (ca_ratAdd (ca_const 1) (computable_sum out_chosenBudgets.ratInv computable_ratAdd))) + +lemma c_chosenGrid : Computable (fun K=>(selectedParameters K).grid) := by + have hc := c_selectedGrid.comp + ((computableCard (Grid.coordinates chosenM chosenN c_chosenM c_chosenN chosenN_pos)).pair + ((computableCard (Grid.indices chosenM chosenN c_chosenM c_chosenN chosenN_pos)).pair + ((ca_ratAdd (ca_ratMul (ca_const 2) (ca_ratCast (ca_pow c_chosenN c_chosenM))) (ca_const 1)).pair + c_chosenAccuracy))) + apply hc.of_eq + intro K + exact selectedGrid_eq _ _ _ _ (by positivity) (tableAccuracy_pos (parameterJ_pos K) _ (selectedInner_check K) _ (selectedOuter_check K)) + +lemma c_chosenRate : Computable (fun K=>rationalRate (parameterJ K) (selectedInner K)) := + ca_ratDiv (ca_ratPow (c_eta.comp c_parameterJ) (ca_const 2)) (ca_ratCast c_chosenM) +lemma c_fixedSetCard : Computable (fun K=>Fintype.card (FixedSets (Fin (chosenT K)) (chosenL K))) := by + let a:=sets chosenT c_chosenT + let d:∀K,Finset (Fin (chosenT K))→Bool:=fun K S=>decide (S.card=chosenL K) + have hd : a.Map bool d := ((out_setCard chosenT c_chosenT).pair (out_const a c_chosenL)).map Primrec.eq.computablePred.decide |>.toBool + have hc := computableCard (a.restrict d hd) + apply hc.of_eq + intro K + exact Fintype.card_congr (Equiv.subtypeEquivRight (fun S=>by simp [d])) + +lemma c_chosenDenominator : Computable (fun K=>(selectedParameters K).denominatorCoefficient) := by + exact ca_mul (ca_mul c_fixedSetCard (ca_pow (ca_const 3) c_chosenT)) + (Denominator.c_innerDenominator chosenT chosenM chosenN c_chosenT c_chosenM c_chosenN chosenN_pos + (fun K=>(selectedParameters K).grid) c_chosenGrid + _ c_chosenRate _ out_chosenBudgets) + +def chosenEnumeration (K : ℕ) := + DemandOrder.enumeration (chosenT K) (chosenL K) (chosenM K) (chosenN K) (chosenN_pos K) (selectedParameters K).grid +lemma c_chosenExpressions : Computable (fun K=>(localExpressions (chosenEnumeration K) + (rationalRate (parameterJ K) (selectedInner K)) + (rationalBudgets (parameterJ K) (selectedInner K) (selectedOuter K)) + (rationalSigma (parameterJ K)) (rationalEta (parameterJ K))).map (fun e=>e.program.code)) := + DemandOrder.c_localExpressions chosenT chosenL c_chosenT c_chosenL chosenM chosenN + c_chosenM c_chosenN chosenN_pos _ c_chosenGrid _ c_chosenRate _ out_chosenBudgets + _ _ (c_sigma.comp c_parameterJ) (c_eta.comp c_parameterJ) + +lemma c_completeGraphCode (u D : ℕ) : Computable (fun K=> + (completeGraphProgram (selectedParameters K) (chosenEnumeration K) u D).code) := by + have hd := Syntax.c_demandStageCode _ c_chosenExpressions chosenT + (fun K=>(selectedParameters K).denominatorCoefficient) c_chosenT c_chosenDenominator + exact MinUncut.CodeEffective.computable_comp.comp + (MinUncut.CodeEffective.computable_comp.comp (ca_const GraphRegisters.rawRenderer.code) hd) + (ca_const (sourceStageProgram u D).code) +end MinUncut.Preprocess + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Graphs/DemandExpressions.lean b/lean/OAI/Computability/MinUncut/Graphs/DemandExpressions.lean new file mode 100644 index 0000000000000000000000000000000000000000..72aee60fb95271932a609d0a21b7ea54fc1010d4 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Graphs/DemandExpressions.lean @@ -0,0 +1,127 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.UniformGrid + +namespace OAI + +noncomputable section +namespace MinUncut.Costed.SourceWords +open MinUncut.Inner MinUncut.Outer MinUncut.Outer.LocalTemplate +open MinUncutGames.Reduction MinUncut.SourceBridge + +variable {t : ℕ} {h : Fin t → Bool} + +def secondAddress (h : Fin t → Bool) (pos : Fin t → Fin 3) : AExpr := + .add ((AExpr.mul ((AExpr.reg 1).pow 3) (.const 2)).pow t) (secondExpr h pos) +def leftExpr (T : Query h) (pos : Fin t → Fin 3) : AExpr := + .add (signatureLookup (fun s=>tableNumber (T.leftTable pos s))) + (.mul (.const (2^((2^3)^t))) (if T.first then firstExpr t else secondAddress h pos)) +def rightExpr (T : Query h) (pos : Fin t → Fin 3) : AExpr := + .add (.const (tableNumber T.rightTable)) (.mul (.const (2^((2^3)^t))) (secondAddress h pos)) +def signExpr (T : Query h) (pos : Fin t → Fin 3) : AExpr := + signatureLookup (fun s=>(T.localSign pos s).toNat) + +lemma secondAddress_eval (input : SourceEncoding.Input) (u : Fin t → Fin input.equations.length) + (h : Fin t → Bool) (pos : Fin t → Fin 3) : + (secondAddress h pos).eval (inputTuple input u)= + (input.«variables»^3*2)^t+secondNumber (fun j=>equations input (u j)) h pos := by + simp only [secondAddress,AExpr.eval,AExpr.eval_pow,inputTuple_reg1,secondExpr_eval] +lemma leftExpr_eval (input : SourceEncoding.Input) (u : Fin t → Fin input.equations.length) + (T : Query h) (pos : Fin t → Fin 3) : + (leftExpr T pos).eval (inputTuple input u)=T.leftNumber (fun j=>equations input (u j)) pos := by + simp only [leftExpr,AExpr.eval,signatureLookup_eval,Query.leftNumber] + cases T.first <;> simp only [Bool.false_eq_true,ite_false,ite_true,firstExpr_eval,secondAddress_eval] +lemma rightExpr_eval (input : SourceEncoding.Input) (u : Fin t → Fin input.equations.length) + (T : Query h) (pos : Fin t → Fin 3) : + (rightExpr T pos).eval (inputTuple input u)=T.rightNumber (fun j=>equations input (u j)) pos := by + simp only [rightExpr,AExpr.eval,secondAddress_eval,Query.rightNumber] +lemma signExpr_eval (input : SourceEncoding.Input) (u : Fin t → Fin input.equations.length) + (T : Query h) (pos : Fin t → Fin 3) : + (signExpr T pos).eval (inputTuple input u)= + ((T.realize (fun j=>equations input (u j)) pos).signed familyBase).equal.toNat := by + rw [Query.signed_equal] + exact signatureLookup_eval input u _ + +def queryWords (T : Query h) (pos : Fin t → Fin 3) (v : List ℕ) : List ℕ := + [(leftExpr T pos).eval v,(rightExpr T pos).eval v,(signExpr T pos).eval v] +def queryProgram (T : Query h) (pos : Fin t → Fin 3) : PolyProgram (queryWords T pos) := + ((leftExpr T pos).program.cons ((rightExpr T pos).program.cons + ((signExpr T pos).program.cons PolyProgram.nil))).ofEq (by intro v; rfl) + +lemma queryWords_eq (input : SourceEncoding.Input) (u : Fin t → Fin input.equations.length) + (T : Query h) (pos : Fin t → Fin 3) : + queryWords T pos (inputTuple input u)= + [(variableCode ((T.realize (fun j=>equations input (u j)) pos).signed familyBase).left).val, + (variableCode ((T.realize (fun j=>equations input (u j)) pos).signed familyBase).right).val, + ((T.realize (fun j=>equations input (u j)) pos).signed familyBase).equal.toNat] := by + simp only [queryWords,leftExpr_eval,rightExpr_eval,signExpr_eval,Query.left_number,Query.right_number] + +end MinUncut.Costed.SourceWords + +namespace MinUncut.Preprocess.Syntax +open MinUncut.Costed MinUncut.Costed.SourceWords +open MinUncut.Outer MinUncut.Outer.LocalTemplate UEncoding +variable {P : Type} [Primcodable P] {A : P → Type} {c : UEncoding P A} +lemma O.demandDigit {i : ∀p,A p → ℕ} (hi : c.Out i) : + O c (fun p x=>MinUncut.Costed.SourceWords.tupleDigit (i p x)) := + ((O.fixed (.reg 0)).div ((O.fixed (.reg 2)).pow hi)).mod (O.fixed (.reg 2)) +lemma O.slotExpr {i j : ∀p,A p → ℕ} (hi : c.Out i) (hj : c.Out j) : + O c (fun p x=>MinUncut.Costed.SourceWords.slotExpr (i p x) (j p x)) := + ((O.fixed (.const 3)).add ((O.fixed (.const 4)).mul (O.demandDigit hi))).add (O.const hj) |>.at +lemma O.equationExpr {i : ∀p,A p → ℕ} (hi : c.Out i) : + O c (fun p x=>MinUncut.Costed.SourceWords.equationExpr (i p x)) := by + have hp : (c.prod (fin (fun _ : P=>3) (Computable.const 3))).Out (fun _ x=>x.2.val) := + (out_code (fin (P:=P) (fun _=>3) (Computable.const 3))).second + have hw := (O.slotExpr hi.first hp).mul ((O.fixed (.reg 1)).pow hp) + exact (O.slotExpr hi (out_const c (Computable.const 3))).add + ((O.fixed (.const 2)).mul (hw.sum_fin (Computable.const 3))) +lemma c_firstExpr : C MinUncut.Costed.SourceWords.firstExpr := by + let c := unitN.prod (fin id Computable.id) + have hi : c.Out (fun _ x=>x.2.val) := (out_code (fin id Computable.id)).second + have hbase : O c (fun _ _=>.mul ((AExpr.reg 1).pow 3) (.const 2)) := O.fixed _ + exact ((O.equationExpr hi).mul (hbase.pow hi) |>.sum_fin Computable.id).toC +lemma O.secondExpr {t : P → ℕ} (ht : Computable t) {h : ∀p,A p → Fin (t p) → Bool} + {pos : ∀p,A p → Fin (t p) → Fin 3} + (hh : c.Map ((fin t ht).function bool) h) + (hp : c.Map (Alphabet.positionsList t ht) pos) : + O c (fun p x=>MinUncut.Costed.SourceWords.secondExpr (h p x) (pos p x)) := by + let d:=c.prod (fin t ht) + have hi : d.Out (fun _ x=>x.2.val) := (out_code (fin t ht)).second + have hj := map_apply hp.first (map_snd c (fin t ht)) + have hjn := (out_code (fin (fun _ : P=>3) (Computable.const 3))).comp hj + have hb:=map_apply hh.first (map_snd c (fin t ht)) + have left:=O.slotExpr hi hjn + have right:=(O.fixed (.reg 1)).add (O.equationExpr hi) + have base : O d (fun _ _=>.add (.reg 1) (.mul ((AExpr.reg 1).pow 3) (.const 2))) := O.fixed _ + exact ((O.choose hb left right).mul (base.pow hi)).sum_fin ht + +lemma c_demandSignatureExpr : C MinUncut.Costed.SourceWords.signatureExpr := by + let axes:=fin (P:=ℕ) id Computable.id + let pos:=fin (P:=ℕ) (fun _=>3) (Computable.const 3) + let c:=unitN.prod axes + let d:=c.prod pos + let e:=d.prod pos + have hi : e.Out (fun _ x=>x.1.1.2.val) := (out_code axes).second.first.first + have hp : e.Out (fun _ x=>x.1.2.val) := (out_code pos).second.first + have hq : e.Out (fun _ x=>x.2.val) := (out_code pos).second + have eqs := (O.slotExpr hi hp).eq (O.slotExpr hi hq) + have powq := hq.map (ca_pow (Computable.const 2) Computable.id) + have inner := (eqs.mul (O.const powq)).sum_fin (Computable.const 3) + have pcode : d.Out (fun _ x=>x.2.val) := (out_code pos).second + have powp := pcode.map (ca_pow (Computable.const (2^3)) Computable.id) + have mid := (inner.mul (O.const powp)).sum_fin (Computable.const 3) + have ii : c.Out (fun _ x=>x.2.val) := (out_code axes).second + have outer := (mid.mul (O.const (ii.map (ca_pow (Computable.const ((2^3)^3)) Computable.id)))).sum_fin Computable.id + have rhs := ((O.slotExpr ii (out_const c (Computable.const 3))).mul + (O.const (ii.map (ca_pow (Computable.const 2) Computable.id)))).sum_fin Computable.id + have co := O.const (out_const unitN (ca_pow (Computable.const ((2^3)^3)) Computable.id)) + exact (outer.add (co.mul rhs)).toC +lemma O.demandLookup {t : P → ℕ} (ht : Computable t) + {f : ∀p,A p × Signature (Fin (t p)) → ℕ} + (hf : (c.prod (Alphabet.signatures t ht)).Out f) : + O c (fun p x=>MinUncut.Costed.SourceWords.signatureLookup (fun s=>f p (x,s))) := + (O.fromC (c_demandSignatureExpr.precomp ht)).lookup (out_constantTable hf) +end MinUncut.Preprocess.Syntax + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Graphs/DemandOrder.lean b/lean/OAI/Computability/MinUncut/Graphs/DemandOrder.lean new file mode 100644 index 0000000000000000000000000000000000000000..062196d2b750657ed20ddda071ed6e200afbbc39 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Graphs/DemandOrder.lean @@ -0,0 +1,249 @@ +import Mathlib +import OAI.Computability.MinUncut.Graphs.CanonicalSamplerGraph +import OAI.Computability.MinUncut.Estimates.LocalBodyEffectivity +import OAI.Computability.MinUncut.Search.EnumerationPlain +import OAI.Computability.MinUncut.Estimates.UniformSets + +namespace OAI + +noncomputable section +namespace MinUncut.Preprocess.DemandOrder +open MinUncut.OuterSmoothness MinUncut.Inner MinUncut.Outer MinUncut.Outer.LocalTemplate MinUncut.FiniteGaussian MinUncut.FiniteProof +open MinUncutGames.Foundations.Hastad.SourceOccurrences UEncoding +open MinUncut.Costed MinUncut.Costed.SourceWords +attribute [local irreducible] localWeight MinUncut.FiniteProof.multiplicity innerDenominator rationalScoreTable MinUncut.FiniteGaussian.midpoint +abbrev Body (t : ℕ) (h : Fin t → Bool) (m n : ℕ) (g : GridData) := + (LocalSample (Alphabet h) m n g × Test) × (Fin t → Fin 3) +def bodyEncoding (t : ℕ) (h : Fin t → Bool) (m n : ℕ) (hn : 0t) (ca_const t) (fun _=>h) + (ca_const ((((Encoding.fin t).function Encoding.bool).code h).val)) + (fun _=>m) (fun _=>n) (ca_const m) (ca_const n) (fun _=>hn) (fun _=>g) (ca_const g)).enc () +lemma samples_enc {P : Type} [Primcodable P] (t : P → ℕ) (ht : Computable t) (h : ∀p,Fin (t p) → Bool) + (hc : Computable (fun p=>(((Encoding.fin (t p)).function Encoding.bool).code (h p)).val)) + (m n : P → ℕ) (hm : Computable m) (hn : Computable n) (hnpos : ∀p,0midpoint g.T g.L (x.1.1.2.2.2 i))) x.1.2 + [leftExpr Q x.2,rightExpr Q x.2,signExpr Q x.2] +def bodyRepetitions {t m n : ℕ} {h : Fin t → Bool} {g : GridData} (a : ℚ) (b : Test → ℚ) (x : Body t h m n g) := + multiplicity (innerDenominator t m n g a b) (localWeight g a (b x.1.2) x.1.2 x.1.1) +def bodyExpressions (t : ℕ) (h : Fin t → Bool) (m n : ℕ) (hn : 0 + (List.replicate (bodyRepetitions a b x) (bodyExpr σ η x)).flatten) +def indexEquiv (t k m n : ℕ) (g : GridData) : + (ΣH:FixedSets (Fin t) k,Body t (hiddenSet H.val) m n g) ≃ Index (Fin t) k m n g where + toFun x := (x.2.1.2,⟨x.1,x.2.2,x.2.1.1⟩) + invFun x := ⟨x.2.1,((x.2.2.2,x.1),x.2.2.1)⟩ + left_inv _ := rfl + right_inv _ := rfl +def enumeration (t k m n : ℕ) (hn : 0S.card=k) |>.bind + (fun H=>Enumeration.ofEncoding (bodyEncoding t (hiddenSet H.val) m n hn g))).mapEquiv (indexEquiv t k m n g) +lemma localExpressions_eq (t k m n : ℕ) (hn : 0if S.card=k then + bodyExpressions t (hiddenSet S) m n hn g a b σ η else []) := by + unfold localExpressions enumeration Enumeration.mapEquiv Enumeration.bind + simp only [List.flatMap_map,List.flatMap_assoc] + have he : ∀(H:FixedSets (Fin t) k) (x:Body t (hiddenSet H.val) m n g), + repetitions a b ((indexEquiv t k m n g) ⟨H,x⟩)=bodyRepetitions a b x := by + intro H x + simp only [repetitions,weight,indexEquiv,Equiv.coe_fn_mk,bodyRepetitions,Fintype.card_fin] + congr 2 + exact Subsingleton.elim _ _ + simp only [he] + change ((Enumeration.ofEncoding (setEncoding t)).filterSubtype (fun S=>S.card=k)).values.flatMap + (fun H=>bodyExpressions t (hiddenSet H.val) m n hn g a b σ η)=_ + exact Enumeration.filterSubtype_flatMap (Enumeration.ofEncoding (setEncoding t)) (fun S=>S.card=k) + (fun S=>bodyExpressions t (hiddenSet S) m n hn g a b σ η) + +lemma c_bodyExpressions {P : Type} [Primcodable P] + (t : P → ℕ) (ht : Computable t) (h : ∀p,Fin (t p) → Bool) + (hc : Computable (fun p=>(((Encoding.fin (t p)).function Encoding.bool).code (h p)).val)) + (m n : P → ℕ) (hm : Computable m) (hn : Computable n) (hnpos : ∀p,0b p j)) + (σ η : P → ℚ) (hσ : Computable σ) (hη : Computable η) : + Computable (fun p=>(bodyExpressions (t p) (h p) (m p) (n p) (hnpos p) (g p) (a p) (b p) (σ p) (η p)).map + (fun e=>e.program.code)) := by + have hh := Primrec.list_flatten.to_comp.comp + (DemandBody.out_repeatedExpressions t ht h hc m n hm hn hnpos g hg a ha b hb σ η hσ hη).enumerate + apply hh.of_eq + intro p + rw [samples_enc] + simp only [bodyExpressions,List.flatMap_def,List.map_flatten,List.map_map,List.map_replicate, + bodyRepetitions,bodyExpr,DemandBody.bodyQuery,Function.comp_def] + +open MinUncut.Inner MinUncut.Outer MinUncut.FiniteGaussian MinUncut.Costed MinUncut.Costed.SourceWords UEncoding +variable {P : Type} [Primcodable P] +lemma out_bodyExpressions + (t : P → ℕ) (ht : Computable t) (m n : P → ℕ) (hm : Computable m) (hn : Computable n) + (hnpos : ∀p,0b p j)) + (σ η : P → ℚ) (hσ : Computable σ) (hη : Computable η) : + (sets t ht).Out (fun p S=>(bodyExpressions (t p) (hiddenSet S) (m p) (n p) (hnpos p) + (g p) (a p) (b p) (σ p) (η p)).map (fun e=>e.program.code)) := by + have hc := c_bodyExpressions (fun q : P × ℕ=>t q.1) (ht.comp Computable.fst) + (fun q=>hiddenSet (rawSet (t q.1) q.2)) + (c_rawHidden _ (ht.comp Computable.fst) _ Computable.snd) + (fun q=>m q.1) (fun q=>n q.1) (hm.comp Computable.fst) (hn.comp Computable.fst) + (fun q=>hnpos q.1) (fun q=>g q.1) (hg.comp Computable.fst) + (fun q=>a q.1) (ha.comp Computable.fst) (fun q=>b q.1) (hb.pullback Computable.fst) + (fun q=>σ q.1) (fun q=>η q.1) (hσ.comp Computable.fst) (hη.comp Computable.fst) + refine ⟨_,hc,?_⟩ + intro p S + change (bodyExpressions _ (hiddenSet (rawSet _ ((setEncoding (t p)).code S).val)) _ _ _ _ _ _ _ _).map _=_ + rw [rawSet_code] +lemma c_localExpressions + (t k : P → ℕ) (ht : Computable t) (hk : Computable k) + (m n : P → ℕ) (hm : Computable m) (hn : Computable n) (hnpos : ∀p,0b p j)) + (σ η : P → ℚ) (hσ : Computable σ) (hη : Computable η) : + Computable (fun p=>(localExpressions (enumeration (t p) (k p) (m p) (n p) (hnpos p) (g p)) + (a p) (b p) (σ p) (η p)).map (fun e=>e.program.code)) := by + have how := out_bodyExpressions t ht m n hm hn hnpos g hg a ha b hb σ η hσ hη + have cond := ((out_setCard t ht).pair (out_const (sets t ht) hk)).map Primrec.eq.computablePred.decide + have hc := (Primrec.list_flatten.to_comp.comp + (Out.cond cond.toBool how (out_const (sets t ht) (ca_const []))).enumerate) + apply hc.of_eq + intro p + rw [localExpressions_eq] + simp only [List.flatMap_def,List.map_flatten,List.map_map,Function.comp_def] + congr 1 + apply List.map_congr_left + intro S hS + split_ifs <;> simp_all +end MinUncut.Preprocess.DemandOrder + +end +namespace MinUncut.Costed.GraphRegisters +open PolyProgram + +def vertexExpr : Expr := .add (.reg 0) (.mul (.reg 1) (.const 3)) +def lastVertexExpr : Expr := .sub vertexExpr (.const 1) + +def initRender (v : List ℕ) : List ℕ := + let V := v.headI+(v.drop 1).headI*3 + V^2::(queryState v.headI (v.drop 1).headI (v.drop 2).headI V (V-1) (V-1) [] (v.drop 3)).encode + +noncomputable def initProgram : PolyProgram initRender := + ((vertexExpr.mul vertexExpr).program.cons ((projection 0).cons ((projection 1).cons + ((projection 2).cons (vertexExpr.program.cons (lastVertexExpr.program.cons + (lastVertexExpr.program.cons ((const 0).cons ((const 2).cons ((projection 2).cons (drop 3))))))))))).ofEq (by + intro v + simp only [Expr.eval,vertexExpr,lastVertexExpr,initRender,queryState,RenderState.encode, + List.headI_cons,List.length_nil,List.nil_append,List.drop_zero,pow_two]) + +def rawGraphWords (N M k : ℕ) (data : List ℕ) : List ℕ := + let V := N+M*3 + V::(rawTable N M data V V++2::k::data) + +def renderRaw (v : List ℕ) : List ℕ := + rawGraphWords v.headI (v.drop 1).headI (v.drop 2).headI (v.drop 3) + +noncomputable def rawRenderer : PolyProgram renderRaw := + (((projection 3).cons (drop 7)).comp (renderLoop.comp initProgram)).ofEq (by + intro v + simp only [Function.comp_apply,initRender,List.headI_cons,List.tail_cons] + rw [renderTick_iter_encode] + change (RenderState.tick^[(_+_*3)^2] _).V::(RenderState.tick^[(_+_*3)^2] _).tape=_ + rw [tick_iter_V,tick_table] + rfl) + +lemma renderRaw_encode (N M k : ℕ) (data : List ℕ) : + renderRaw (N::M::k::data)=rawGraphWords N M k data := rfl + +open MinUncut.PathRealization + +lemma length_packDemands {N : ℕ} (ds : List (Demand (Fin N))) : + (packDemands ds).length=3*ds.length := by + induction ds with + | nil => rfl + | cons d ds ih => simp only [packDemands,List.flatMap_cons,List.length_append, + packDemand,List.length_cons,List.length_nil,List.length_cons] at ih ⊢; omega + +lemma rawLocal_append (N d : ℕ) (data rest : List ℕ) (u v : ℕ) (h : 3*d+2 rintro ⟨d,hd,he⟩ <;> refine ⟨d,hd,?_⟩ + · rwa [rawLocal_append N d data rest u v (by omega)] at he + · rwa [rawLocal_append N d data rest u v (by omega)] + +lemma rawTable_append (N M : ℕ) (data rest : List ℕ) (r c : ℕ) (h : 3*M≤data.length) : + rawTable N M (data++rest) r c=rawTable N M data r c := by + unfold rawTable rawRow + have hh : rawCell N M (data++rest)=rawCell N M data := by + funext u v + exact rawCell_append N M data rest u v h + rw [hh] + +lemma renderer_pack {N : ℕ} (ds : List (Demand (Fin N))) (k : ℕ) (rest : List ℕ) : + renderRaw (N::ds.length::k::(packDemands ds++rest))= + (N+ds.length*3)::((canonicalTable ds).map Bool.toNat++2::k::(packDemands ds++rest)) := by + rw [renderRaw_encode,rawGraphWords,rawTable_append N ds.length _ rest _ _ (by rw [length_packDemands]), + rawTable_pack] +end MinUncut.Costed.GraphRegisters + +noncomputable section +open scoped BigOperators +namespace MinUncut.Outer.Parameters +open MinUncut.Inner MinUncut.FiniteGaussian MinUncut.FiniteProof +attribute [local instance] Classical.propDecidable +variable {Name S : Type*} [Fintype Name] [Fintype S] [Nonempty S] + +def graph {J : ℕ} (P : Parameters J) (equations : S → Equation Name) : MinUncut.Output := + rationalGraph (P.denominator S) P.denominator_pos (P.weight equations) (P.demand equations) + +lemma graph_threshold {J : ℕ} (P : Parameters J) (equations : S → Equation Name) : + (P.graph equations).threshold=5*P.denominator S := rfl + +lemma graph_yes {J : ℕ} (P : Parameters J) (equations : S → Equation Name) (s : Name → F₂) + (hs : (P.o.t:ℝ)*(1-equationFraction equations s)≤P.o.b4) : + (P.graph equations).opt≤(P.graph equations).threshold := by + apply rationalGraph_yes _ _ _ (P.weight_nonneg equations) (P.weight_den equations) _ + (honestProof (I := Fin P.o.t) s).assignment + rw [P.failure_eq,ProofFamily.variableProof_assignment] + exact (finite_honest_cost P.hJ P.d P.hd P.o P.ho equations s (Fintype.card_fin _) hs).le + +lemma graph_no {K J : ℕ} (hK : 2≤K) (hKJ : 8*K≤J) (P : Parameters J) + (equations : S → Equation Name) (hs : ∀ s : Name → F₂, equationFraction equations s≤3/4) : + K*(P.graph equations).threshold<(P.graph equations).opt := by + let : NeZero P.o.t := ⟨ne_of_gt P.t_pos⟩ + apply rationalGraph_no hK _ _ _ (P.weight_nonneg equations) (P.weight_den equations) + intro y + rw [P.failure_eq] + have hh := finite_unsound_cost P.hJ P.d P.hd P.o P.ho (variableProof y) equations + (Fintype.card_fin _) hs + change (J:ℝ)-1/2 < (variableProof y).finiteCost _ _ P.grid equations at hh + have hJ' : 8*(K:ℝ)≤J := by exact_mod_cast hKJ + linarith + +lemma graph_vertices {J : ℕ} (P : Parameters J) (equations : S → Equation Name) : + (P.graph equations).vertices = Fintype.card (FamilyVariable Name (Fin P.o.t))+ + 3*Fintype.card (UnitDemand (P.denominator S) (P.weight equations)) := by + rw [graph,rationalGraph_vertices,expanded_card] + +omit [Fintype Name] in +lemma graph_demands {J : ℕ} (P : Parameters J) (equations : S → Equation Name) : + (Fintype.card (UnitDemand (P.denominator S) (P.weight equations)):ℚ)= + (P.denominator S:ℚ)*rationalWeight J P.d P.o := by + rw [expanded_card_cast _ _ (P.weight_nonneg equations) (P.weight_den equations),P.weight_sum] + +end MinUncut.Outer.Parameters + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Graphs/DemandQueryEffectivity.lean b/lean/OAI/Computability/MinUncut/Graphs/DemandQueryEffectivity.lean new file mode 100644 index 0000000000000000000000000000000000000000..7df033e06d54eb1700ae849714b788d881d7f805 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Graphs/DemandQueryEffectivity.lean @@ -0,0 +1,59 @@ +import Mathlib +import OAI.Computability.MinUncut.Graphs.DemandExpressions +import OAI.Computability.MinUncut.Estimates.UniformOutput + +namespace OAI + +section +noncomputable section +namespace MinUncut.Preprocess.Syntax +open MinUncut.Costed MinUncut.Costed.SourceWords +open MinUncut.Outer MinUncut.Outer.LocalTemplate UEncoding +open MinUncutGames.Foundations.Hastad.SourceOccurrences +variable {P : Type} [Primcodable P] {A : P → Type} {c : UEncoding P A} +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 {Q : ∀p,A p → Query (h p)} {pos : ∀p,A p → Fin (t p) → Fin 3} +variable (hQ : c.Map (Queries.queries t ht h hc) Q) +variable (hp : c.Map (Alphabet.positionsList t ht) pos) +include hp hc in +lemma O.secondAddress : O c (fun p x=>secondAddress (h p) (pos p x)) := by + have hh : c.Map ((fin t ht).function bool) (fun p _=>h p) := map_const hc + exact ((O.fixed (.mul ((AExpr.reg 1).pow 3) (.const 2))).pow (out_const c ht)).add + (O.secondExpr ht hh hp) +include hQ hp in +lemma O.leftExpr : O c (fun p x=>leftExpr (Q p x) (pos p x)) := by + let s:=Alphabet.signatures t ht + have htab:=Queries.map_leftTable t ht h hc hQ.first hp.first (map_snd c s) + have hnum : (c.prod s).Out (fun p x=>tableNumber ((Q p x.1).leftTable (pos p x.1) x.2)) := + (out_code ((Alphabet.ambient t ht).function bool)).comp htab + have hl:=O.demandLookup ht hnum + have hf:=map_comp hQ (Queries.map_first t ht h hc) + have hfirst := O.fromC (c_firstExpr.precomp ht) (c:=c) + have hsecond:=O.secondAddress t ht h hc hp + exact hl.add ((O.const (out_const c (ca_pow (Computable.const 2) + (ca_pow (Computable.const (2^3)) ht)))).mul (O.choose hf hfirst hsecond)) +include hQ hp in +lemma O.rightExpr : O c (fun p x=>rightExpr (Q p x) (pos p x)) := by + have htab:=Queries.map_rightTable t ht h hc hQ + have hnum : c.Out (fun p x=>tableNumber (Q p x).rightTable) := + (out_code ((Alphabet.ambient t ht).function bool)).comp htab + exact (O.const hnum).add ((O.const (out_const c (ca_pow (Computable.const 2) + (ca_pow (Computable.const (2^3)) ht)))).mul (O.secondAddress t ht h hc hp)) +include hQ hp in +lemma O.signExpr : O c (fun p x=>signExpr (Q p x) (pos p x)) := by + let s:=Alphabet.signatures t ht + have hs:=Queries.map_localSign t ht h hc hQ.first hp.first (map_snd c s) + exact O.demandLookup ht (out_boolNat hs) +include hQ hp in +lemma out_queryExpressions : c.Out (fun p x=> + ([leftExpr (Q p x) (pos p x),rightExpr (Q p x) (pos p x),signExpr (Q p x) (pos p x)]).map + (fun e=>e.program.code)) := + (O.leftExpr t ht h hc hQ hp).cons ((O.rightExpr t ht h hc hQ hp).cons + ((O.signExpr t ht h hc hQ hp).cons (out_const c (Computable.const [])))) +end MinUncut.Preprocess.Syntax + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Graphs/DemandStageEffectivity.lean b/lean/OAI/Computability/MinUncut/Graphs/DemandStageEffectivity.lean new file mode 100644 index 0000000000000000000000000000000000000000..e47144fc2e78d03d321e64b977adab863a77130b --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Graphs/DemandStageEffectivity.lean @@ -0,0 +1,38 @@ +import Mathlib +import OAI.Computability.MinUncut.Graphs.GraphSize +import OAI.Computability.MinUncut.Estimates.BlocksEffectivity + +namespace OAI + +section +noncomputable section +namespace MinUncut.Preprocess.Syntax +open MinUncut.Costed MinUncut.Costed.SourceWords MinUncut.CodeEffective +lemma c_tupleCountExpr : C tupleCountExpr := (C.fixed (.reg 1)).pow Computable.id +lemma c_variableCountExpr : C variableCountExpr := by + exact ((((C.fixed (.reg 0)).pow (ca_const 3)).mul (C.fixed (.const 2))).pow Computable.id |>.add + (((C.fixed (.reg 0)).add (((C.fixed (.reg 0)).pow (ca_const 3)).mul + (C.fixed (.const 2)))).pow Computable.id)).mul + (C.const (ca_pow (ca_const 2) (ca_pow (ca_const (2^3)) Computable.id))) +lemma c_demandStageCode {P : Type} [Primcodable P] (es : P → List AExpr) + (he : Computable (fun p=>(es p).map (fun e=>e.program.code))) + (t D : P → ℕ) (ht : Computable t) (hD : Computable D) : + Computable (fun p=>(demandStageProgram (es p) (t p) (D p)).code) := by + have hl : Computable (fun p=>(es p).length) := + (Computable.list_length.comp he).of_eq (fun p=>List.length_map ..) + have hv := c_variableCountExpr.precomp ht + have hu : C (fun p=>unitCountExpr (es p) (t p)) := + ((c_tupleCountExpr.precomp ht).mul (C.const hl)).div (C.fixed (.const 3)) + have hk : C (fun p=>thresholdExpr (t p) (D p)) := + (C.const (ca_mul (ca_const 5) hD)).mul (c_tupleCountExpr.precomp ht) + have hf := p_forwardCode.to_comp.comp he (c_tupleCountExpr.precomp ht) + apply (computable_cons.comp hv (computable_cons.comp hu (computable_cons.comp hk hf))).of_eq + intro p + rw [forwardCode_eq] + rfl +end MinUncut.Preprocess.Syntax + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Graphs/EdgeMean.lean b/lean/OAI/Computability/MinUncut/Graphs/EdgeMean.lean new file mode 100644 index 0000000000000000000000000000000000000000..773b9baf54e4b6b01b4b36dab2f4a7b23668fd61 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Graphs/EdgeMean.lean @@ -0,0 +1,58 @@ +import Mathlib +import OAI.Computability.MinUncut.Games.JointHintSampling + +namespace OAI + +section +noncomputable section +open scoped BigOperators +namespace MinUncut.Outer +open MinUncut.Inner OuterSmoothness MeasureTheory +attribute [local instance] Classical.propDecidable BinaryFourier.dualFintype +variable {Name I S : Type*} [Fintype I] [Fintype S] + +abbrev EdgeStatistic (Name I : Type*) [Fintype I] := + (U : I → Equation Name) → (hidden : I → Bool) → (pos : I → Fin 3) → ℝ + +def edgeMean (equations : S → Equation Name) (k : ℕ) (F : EdgeStatistic Name I) : ℝ := + 𝔼 H : FixedSets I k, 𝔼 a : I → S, 𝔼 pos : I → Fin 3, + F (fun i => equations (a i)) (hiddenSet H.val) pos + +lemma edgeMean_mono (equations : S → Equation Name) (k : ℕ) {F G : EdgeStatistic Name I} + (h : ∀ U hidden pos, F U hidden pos ≤ G U hidden pos) : + edgeMean equations k F ≤ edgeMean equations k G := by + exact Finset.expect_le_expect (fun H _ => Finset.expect_le_expect (fun a _ => + Finset.expect_le_expect (fun pos _ => h _ _ _))) + +lemma edgeMean_add (equations : S → Equation Name) (k : ℕ) (F G : EdgeStatistic Name I) : + edgeMean equations k (fun U h pos => F U h pos+G U h pos) = + edgeMean equations k F+edgeMean equations k G := by + simp only [edgeMean,Finset.expect_add_distrib] + +lemma edgeMean_mul (equations : S → Equation Name) (k : ℕ) (F : EdgeStatistic Name I) (t : ℝ) : + edgeMean equations k (fun U h pos => t*F U h pos) = t*edgeMean equations k F := by + simp only [edgeMean,← Finset.mul_expect] + +lemma edgeMean_expect {X : Type*} [Fintype X] (equations : S → Equation Name) (k : ℕ) + (F : X → EdgeStatistic Name I) : + (𝔼 x, edgeMean equations k (F x)) = edgeMean equations k (fun U h pos => 𝔼 x,F x U h pos) := by + unfold edgeMean + rw [Finset.expect_comm] + congr 1 + funext H + rw [Finset.expect_comm] + congr 1 + funext a + rw [Finset.expect_comm] + +lemma edgeMean_const [Nonempty S] (equations : S → Equation Name) {k : ℕ} + (hk : k≤Fintype.card I) (t : ℝ) : edgeMean (I := I) equations k (fun _ _ _ => t)=t := by + let : Nonempty (FixedSets I k) := fixedSets_nonempty hk + simp only [edgeMean,Fintype.expect_const] + +end MinUncut.Outer + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Graphs/GeneratedGraph.lean b/lean/OAI/Computability/MinUncut/Graphs/GeneratedGraph.lean new file mode 100644 index 0000000000000000000000000000000000000000..de43e847e0c2284484d878dda9ad76c68f8cd6ae --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Graphs/GeneratedGraph.lean @@ -0,0 +1,188 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.UniformEquationOutput + +namespace OAI + +section +noncomputable section +open scoped BigOperators +namespace MinUncut.Costed.SourceWords +open MinUncut.Inner MinUncut.Outer MinUncut.Outer.LocalTemplate +open MinUncut.PathRealization MinUncut.FiniteProof MinUncutGames.Reduction MinUncut.SourceBridge +open MinUncutGames.Foundations.Hastad.SourceOccurrences +attribute [local instance] Classical.propDecidable +variable {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)) + +def generatedGraph : MinUncut.Output := + listOutput (generatedDemands input E (rationalRate J P.d) (rationalBudgets J P.d P.o) + (rationalSigma J) (rationalEta J)) (5*P.denominator (Fin input.equations.length)) + (threshold_positive P.denominator_pos) + +lemma generatedGraph_yes (s : Fin input.«variables» → F₂) + (hs : (P.o.t:ℝ)*(1-equationFraction (equations input) s)≤P.o.b4) : + (generatedGraph P input E).opt≤(generatedGraph P input E).threshold := by + let y := (honestProof (I:=Fin P.o.t) s).assignment + have hy : ∑e,(P.weight (equations input) e:ℝ)*(failure (P.demand (equations input) e) y:ℝ)≤9/2 := by + rw [P.failure_eq,ProofFamily.variableProof_assignment] + exact (finite_honest_cost P.hJ P.d P.hd P.o P.ho (equations input) s (Fintype.card_fin _) hs).le + apply listOutput_yes _ _ _ (extendAssignment variableCode y) + rw [generated_failure_eq] + have hh := listFailure_weight (P.denominator (Fin input.equations.length)) (P.weight (equations input)) + (P.weight_nonneg _) (P.weight_den _) (P.demand (equations input)) + (SampleEnumeration.all (equations input) P.o.k P.d.m P.d.n P.grid).encoding y + have he : listFailure (P.canonicalDemands (equations input)) (extendAssignment variableCode y)= + listFailure (demandList (P.denominator (Fin input.equations.length)) (P.weight (equations input)) + (P.demand (equations input)) + (SampleEnumeration.all (equations input) P.o.k P.d.m P.d.n P.grid).encoding) y := + listFailure_extend variableCode variableCode_injective _ y + have hD : (0:ℝ) rfl + | cons n a ih => + rw [List.cons_append,read_old (a++h) n p (by simp; omega),ih] +lemma ListRep.mono {h h' p v} (hv : ListRep h p v) (he : Extends h h') : ListRep h' p v := by + obtain ⟨a,rfl⟩ := he + exact hv.prepend a +lemma CodeAt.mono {h h' p c} (hc : CodeAt h p c) (he : Extends h h') : CodeAt h' p c := by + obtain ⟨a,rfl⟩ := he + exact hc.prepend a + +def Trace (s s' : State) (n : ℕ) : Prop := State.tick^[n] s=s' +lemma Trace.refl (s : State) : Trace s s 0 := rfl +lemma Trace.one {s s'} (he : s.tick=s') : Trace s s' 1 := he +lemma Trace.trans {s s' s'' n m} (h : Trace s s' n) (h' : Trace s' s'' m) : + Trace s s'' (n+m) := by + unfold Trace at * + rw [Nat.add_comm n m,Function.iterate_add_apply,h,h'] + +def Simulates (c : Code) (v w : List ℕ) (B : ℕ) : Prop := + ∀h pc env kont,CodeAt h pc c → ListRep h env v → + ∃h' out n,n≤B ∧ Extends h h' ∧ ListRep h' out w ∧ + Trace ⟨0,pc,env,kont,h⟩ ⟨1,0,out,kont,h'⟩ n + +lemma simulate_zero (v : List ℕ) : Simulates .zero' v (0::v) 1 := by + intro h pc env k hc hv + cases hc with + | zero hp hb ht => + refine ⟨node 0 env 0 0::h,h.length+1,1,le_rfl,Extends.cons h _,hv.push 0,Trace.one ?_⟩ + simp only [State.tick,ht,ite_true] + +lemma simulate_succ (v : List ℕ) : Simulates .succ v [v.headI+1] 1 := by + intro h pc env k hc hv + cases hc with + | succ hp hb ht => + refine ⟨node (v.headI+1) 0 0 0::h,h.length+1,1,le_rfl,Extends.cons h _,ListRep.nil.push _,Trace.one ?_⟩ + simp only [State.tick,ht,ite_true,hv.head] + +lemma simulate_tail (v : List ℕ) : Simulates .tail v v.tail 1 := by + intro h pc env k hc hv + cases hc with + | tail hp hb ht => + refine ⟨h,read h env 1,1,le_rfl,Extends.refl h,hv.tail,Trace.one ?_⟩ + simp only [State.tick,ht,ite_true] + +lemma simulate_comp {f g v u w A B} (hg : Simulates g v u A) (hf : Simulates f u w B) : + Simulates (.comp f g) v w (A+B+2) := by + intro h pc env k hc hv + cases hc with + | comp hp hb ht hcf hcg => + let frame := node 2 (read h pc 1) 0 k + let h₁ := frame::h + have hv₁ : ListRep h₁ env v := hv.extend frame + have hc₁ := hcg.extend frame + obtain ⟨h₂,out,n,hn,he,ho,htrace⟩ := hg h₁ (read h pc 2) env (h.length+1) hc₁ hv₁ + have hh : Extends h h₂ := (Extends.cons h frame).trans he + have hr (j : Fin 4) : read h₂ (h.length+1) j=frame j := by + rw [he.read _ (by simp [h₁]),read_new] + have hs : Trace ⟨0,pc,env,k,h⟩ ⟨0,read h pc 2,env,h.length+1,h₁⟩ 1 := by + apply Trace.one + simp only [State.tick,ht,ite_true,h₁,frame] + have hs' : Trace ⟨1,0,out,h.length+1,h₂⟩ ⟨0,read h pc 1,out,k,h₂⟩ 1 := by + apply Trace.one + simp only [State.tick,show (1:ℕ)≠0 by omega,ite_false,ite_true, + show h.length+1≠0 by omega,hr,frame,node_zero,node_one,node_three] + obtain ⟨h₃,out',m,hm,he',ho',htrace'⟩ := hf h₂ (read h pc 1) out k (hcf.mono hh) ho + refine ⟨h₃,out',1+n+1+m,by omega,hh.trans he',ho',?_⟩ + exact ((hs.trans htrace).trans hs').trans htrace' + +lemma simulate_caseZero {f g v w A} (hz : v.headI=0) (hf : Simulates f v.tail w A) : + Simulates (.case f g) v w (A+1) := by + intro h pc env k hc hv + cases hc with + | case hp hb ht hcf hcg => + obtain ⟨h',out,n,hn,he,ho,tr⟩ := hf h (read h pc 1) (read h env 1) k hcf hv.tail + refine ⟨h',out,1+n,by omega,he,ho,(Trace.one ?_).trans tr⟩ + simp only [State.tick,ht,ite_true,hv.head,hz] + +lemma simulate_caseSucc {f g v a w A} (hg : Simulates g (a::v) w A) : + Simulates (.case f g) ((a+1)::v) w (A+1) := by + intro h pc env k hc hv + cases hc with + | case hp hb ht hcf hcg => + let cell := node a (read h env 1) 0 0 + have hh := hv.tail.push a + obtain ⟨h',out,n,hn,he,ho,tr⟩ := hg (cell::h) (read h pc 2) (h.length+1) k + (hcg.extend cell) hh + refine ⟨h',out,1+n,by omega,(Extends.cons h cell).trans he,ho,(Trace.one ?_).trans tr⟩ + simp only [State.tick,ht,ite_true,hv.head,List.headI_cons,show a+1≠0 by omega,ite_false, + Nat.add_sub_cancel,cell] + +end MinUncut.Costed.Arena + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Graphs/Graph.lean b/lean/OAI/Computability/MinUncut/Graphs/Graph.lean new file mode 100644 index 0000000000000000000000000000000000000000..aaa8a832e1e65418b386a60b396b70c663c83a05 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Graphs/Graph.lean @@ -0,0 +1,78 @@ +import Mathlib +import OAI.Computability.MinUncut.Encoding.Binary +import OAI.Computability.MinUncut.Graphs.DemandOrder + +namespace OAI + +section +noncomputable section +namespace MinUncut.Outer.Parameters +open MinUncut.Inner MinUncut.SourceBridge +open MinUncutGames MinUncutGames.Reduction MinUncutGames.Foundations + +def sourceError {J : ℕ} (P : Parameters J) : ℚ := min (1/2) (P.o.b4/P.o.t) + +lemma sourceError_pos {J : ℕ} (P : Parameters J) : 0 + uv.1 s (edgePair e number p).1=s (edgePair e number p).2).image (edgePair e number) := by + ext uv + simp only [Finset.mem_filter,Finset.mem_univ,true_and,Finset.mem_image] + constructor + · rintro ⟨hu,ha,hs⟩ + obtain ⟨p,hp⟩ := (output_forward_edge_iff e number k hk uv.1 uv.2).mp ⟨hu,ha⟩ + exact ⟨p,by simpa only [hp] using hs,hp⟩ + · rintro ⟨p,hs,hp⟩ + have hh := (output_forward_edge_iff e number k hk uv.1 uv.2).mpr ⟨p,hp⟩ + exact ⟨hh.1,hh.2,by simpa only [hp] using hs⟩ + unfold MinUncut.Output.uncut + erw [he,Finset.card_image_of_injective _ (edgePair_injective e number)] + change _=∑ p : EdgeIndex e, mono (s (number (ends e p.val).1)) (s (number (ends e p.val).2)) + simp_rw [← edgePair_mono] + simp only [mono,Finset.card_filter] + +lemma output_opt_le (G : MinUncut.Output) (s : Fin G.vertices → Bool) : G.opt ≤ G.uncut s := by + exact Finset.min'_le _ _ (Finset.mem_image.mpr ⟨s,Finset.mem_univ _,rfl⟩) + +lemma le_output_opt (G : MinUncut.Output) (r : ℕ) (h : ∀ s, r ≤ G.uncut s) : r ≤ G.opt := by + apply Finset.le_min' + intro x hx + obtain ⟨s,_,rfl⟩ := Finset.mem_image.mp hx + exact h s + +omit [Fintype V] in +lemma output_yes (e : D → Demand V) (number : Vertex V D ≃ Fin N) (k : ℕ) (hk : 1 ≤ k) + (s : V → Bool) (h : totalFailure e s ≤ k) : (output e number k hk).opt ≤ k := by + apply (output_opt_le _ ((extend e s) ∘ number.symm)).trans + erw [output_uncut] + have he : ((extend e s) ∘ number.symm) ∘ number=extend e s := by ext v; simp + erw [he,uncut_extend] + exact h + +omit [Fintype V] in +lemma output_no (e : D → Demand V) (number : Vertex V D ≃ Fin N) (k : ℕ) (hk : 1 ≤ k) + (R : ℕ) (h : ∀ s : V → Bool, R s (number (.inl v)))).trans_le (uncut_lower e (s ∘ number)) +end MinUncut.PathRealization + +open scoped BigOperators +namespace MinUncut.FiniteProof +open PathRealization +variable {E V : Type*} [Fintype E] + +def multiplicity (D : ℕ) (w : ℚ) : ℕ := w.num.toNat*(D/w.den) + +lemma multiplicity_cast {D : ℕ} {w : ℚ} (hw : 0≤w) (hD : w.den ∣ D) : + (multiplicity D w:ℚ)=(D:ℚ)*w := by + have hn : 0≤w.num := Rat.num_nonneg.mpr hw + have hncast : (w.num.toNat:ℚ)=(w.num:ℚ) := by exact_mod_cast Int.toNat_of_nonneg hn + calc + (multiplicity D w:ℚ)=(w.num:ℚ)*((D:ℚ)/(w.den:ℚ)) := by + unfold multiplicity + rw [Nat.cast_mul,Nat.cast_div_charZero hD,hncast] + _ = (D:ℚ)*((w.num:ℚ)/(w.den:ℚ)) := by ring + _ = (D:ℚ)*w := by rw [Rat.num_div_den] + +abbrev UnitDemand (D : ℕ) (w : E → ℚ) := Σ e, Fin (multiplicity D (w e)) + +def expanded (D : ℕ) (w : E → ℚ) (d : E → Demand V) : UnitDemand D w → Demand V := + fun p => d p.1 + +lemma expanded_failure (D : ℕ) (w : E → ℚ) (d : E → Demand V) (y : V → Bool) : + totalFailure (expanded D w d) y = ∑ e, multiplicity D (w e)*failure (d e) y := by + simp [totalFailure,expanded,Fintype.sum_sigma] + +lemma expanded_weight (D : ℕ) (w : E → ℚ) (hw : ∀ e, 0≤w e) (hD : ∀ e, (w e).den ∣ D) + (d : E → Demand V) (y : V → Bool) : + (totalFailure (expanded D w d) y:ℝ)=(D:ℝ)*∑ e, (w e:ℝ)*(failure (d e) y:ℝ) := by + rw [expanded_failure] + push_cast + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro e _ + have h : (multiplicity D (w e):ℝ)=(D:ℝ)*(w e:ℝ) := by + exact_mod_cast multiplicity_cast (hw e) (hD e) + rw [h,mul_assoc] + +lemma expanded_card (D : ℕ) (w : E → ℚ) : + Fintype.card (UnitDemand D w)=∑ e, multiplicity D (w e) := by + simp [Fintype.card_sigma] + +lemma expanded_card_cast (D : ℕ) (w : E → ℚ) (hw : ∀ e, 0≤w e) (hD : ∀ e, (w e).den ∣ D) : + (Fintype.card (UnitDemand D w):ℚ)=(D:ℚ)*∑ e, w e := by + rw [expanded_card,Nat.cast_sum,Finset.mul_sum] + exact Finset.sum_congr rfl (fun e _ => multiplicity_cast (hw e) (hD e)) + + +open scoped BigOperators +open PathRealization +attribute [local instance] Classical.propDecidable +variable {E V : Type*} [Fintype E] [Fintype V] [DecidableEq V] + +lemma threshold_positive {D : ℕ} (hD : 0 rfl + +lemma tupleCountExpr_eval (input : SourceEncoding.Input) (rest : List ℕ) (t : ℕ) : + (tupleCountExpr t).eval (SourceEncoding.inputWords input++rest)=input.equations.length^t := by + simp only [tupleCountExpr,AExpr.eval_pow,AExpr.eval,(input_regs input rest).2] + +lemma variableCountExpr_eval (input : SourceEncoding.Input) (rest : List ℕ) (t : ℕ) : + (variableCountExpr t).eval (SourceEncoding.inputWords input++rest)= + (paddedVariableEncoding input.«variables» t).size := by + simp only [variableCountExpr,AExpr.eval,AExpr.eval_pow,List.drop_zero,(input_regs input rest).1, + paddedVariableEncoding_size] + +lemma unitCountExpr_eval {t k m n : ℕ} {g : MinUncut.FiniteGaussian.GridData} + (input : SourceEncoding.Input) (rest : List ℕ) + (E : Enumeration (Index (Fin t) k m n g)) (a : ℚ) (b : MinUncut.Outer.Test → ℚ) (σ η : ℚ) : + (unitCountExpr (localExpressions E a b σ η) t).eval (SourceEncoding.inputWords input++rest)= + (generatedDemands input E a b σ η).length := by + have h := congrArg List.length (emitted_demands input E a b σ η rest) + rw [Blocks.length_emitted,GraphRegisters.length_packDemands] at h + simp only [unitCountExpr,AExpr.eval,tupleCountExpr_eval,h] + omega + +lemma thresholdExpr_eval {J : ℕ} (P : Parameters J) (input : SourceEncoding.Input) (rest : List ℕ) : + (thresholdExpr P.o.t P.denominatorCoefficient).eval (SourceEncoding.inputWords input++rest)= + 5*P.denominator (Fin input.equations.length) := by + simp only [thresholdExpr,AExpr.eval,tupleCountExpr_eval,P.denominator_eq,Fintype.card_fin,mul_assoc] + +lemma demandStageWords_spec {J : ℕ} (P : Parameters J) (input : SourceEncoding.Input) + (E : Enumeration (Index (Fin P.o.t) P.o.k P.d.m P.d.n P.grid)) (rest : List ℕ) : + ∃junk, demandStageWords (localExpressions E (rationalRate J P.d) (rationalBudgets J P.d P.o) + (rationalSigma J) (rationalEta J)) P.o.t P.denominatorCoefficient + (SourceEncoding.inputWords input++rest)= + (paddedVariableEncoding input.«variables» P.o.t).size:: + (generatedDemands input E (rationalRate J P.d) (rationalBudgets J P.d P.o) + (rationalSigma J) (rationalEta J)).length::(5*P.denominator (Fin input.equations.length)):: + (GraphRegisters.packDemands (generatedDemands input E (rationalRate J P.d) + (rationalBudgets J P.d P.o) (rationalSigma J) (rationalEta J))++junk) := by + refine ⟨Blocks.retained (localExpressions E (rationalRate J P.d) (rationalBudgets J P.d P.o) + (rationalSigma J) (rationalEta J)) (input.equations.length^P.o.t) + (SourceEncoding.inputWords input++rest),?_⟩ + simp only [demandStageWords,variableCountExpr_eval,unitCountExpr_eval,thresholdExpr_eval, + tupleCountExpr_eval,emitted_demands] + +end +end MinUncut.Costed.SourceWords + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Graphs/GraphWordCodec.lean b/lean/OAI/Computability/MinUncut/Graphs/GraphWordCodec.lean new file mode 100644 index 0000000000000000000000000000000000000000..7a56a5f4616b18da561f96b0104c15a5a62333b5 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Graphs/GraphWordCodec.lean @@ -0,0 +1,137 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.TM2Costed + +namespace OAI + +section + +namespace MinUncut.Costed.GraphCodec +open _root_.Turing _root_.OAI.Turing _root_.Turing.PartrecToTM2 _root_.OAI.Turing.PartrecToTM2 +open MinUncutGames.BinaryEncoding + +inductive Mode | header | cell | one | zeroBit | marker | threshold | done + deriving DecidableEq + +protected abbrev Mode.enumList : List Mode := [.header, .cell, .one, .zeroBit, .marker, + .threshold, .done] + +protected theorem Mode.enumList_getElem?_ctorIdx_eq (x : Mode) : + Mode.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem Mode.enumList_nodup : Mode.enumList.Nodup := by decide + +instance : Fintype Mode where + elems := ⟨Mode.enumList, Mode.enumList_nodup⟩ + complete x := by cases x <;> decide + +def bitSymbol (b : Bool) : Γ' := if b then .bit1 else .bit0 + +def next : Mode → Γ' → Mode + | .header,.cons => .cell + | .threshold,.cons => .done + | .header,_ => .header + | .threshold,_ => .threshold + | .done,_ => .done + | .cell,.bit1 => .one + | .cell,.bit0 => .zeroBit + | .cell,_ => .cell + | .one,_ => .cell + | .zeroBit,.bit1 => .marker + | .zeroBit,_ => .cell + | .marker,.cons => .threshold + | .marker,_ => .marker + +def emit : Mode → Γ' → List Bool + | .header,.bit0 | .threshold,.bit0 => [true,false] + | .header,.bit1 | .threshold,.bit1 => [true,true] + | .header,.cons | .threshold,.cons | .cell,.cons => [false] + | .one,.cons => [true] + | _,_ => [] + +def machine : FinTM2 := WordTransducer.machine .header next emit + +lemma trPosNum_bits (n : PosNum) : trPosNum n=(n:ℕ).bits.map bitSymbol := by + induction n with + | one => simp [trPosNum,Nat.one_bits,bitSymbol] + | bit0 n ih => + have hn : (n:ℕ)≠0 := ne_of_gt n.to_nat_pos + simpa [trPosNum,PosNum.cast_bit0,← two_mul,Nat.bit0_bits _ hn,bitSymbol] using + congrArg (List.cons Γ'.bit0) ih + | bit1 n ih => + simpa [trPosNum,PosNum.cast_bit1,← two_mul,Nat.bit1_bits,bitSymbol] using + congrArg (List.cons Γ'.bit1) ih + +lemma trNat_bits (n : ℕ) : trNat n=n.bits.map bitSymbol := by + have hh (a : Num) : trNum a=(a:ℕ).bits.map bitSymbol := by + cases a with + | zero => simp [trNum,Nat.zero_bits] + | pos a => exact trPosNum_bits a + simpa only [trNat,Num.to_of_nat] using hh (n:Num) + +lemma done_output (v : List Γ') : WordTransducer.output next emit .done v=[] := by + induction v with + | nil => rfl + | cons a v ih => cases a <;> simpa [WordTransducer.output,next,emit] using ih + +lemma header_output (v : List Bool) (rest : List Γ') : + WordTransducer.output next emit .header (v.map bitSymbol++Γ'.cons::rest)= + frame v++WordTransducer.output next emit .cell rest := by + induction v with + | nil => rfl + | cons b v ih => + cases b <;> simp [WordTransducer.output,next,emit,bitSymbol,frame,ih] + +lemma threshold_output (v : List Bool) (rest : List Γ') : + WordTransducer.output next emit .threshold (v.map bitSymbol++Γ'.cons::rest)=frame v := by + induction v with + | nil => simp [WordTransducer.output,next,emit,frame,done_output] + | cons b v ih => + cases b <;> simp [WordTransducer.output,next,emit,bitSymbol,frame,ih] + +lemma cells_output (v : List Bool) (k : ℕ) (rest : List ℕ) : + WordTransducer.output next emit .cell (trList (v.map Bool.toNat++2::k::rest))= + v++nameBits k := by + induction v with + | nil => + change WordTransducer.output next emit .cell + ([.bit0,.bit1,.cons]++(trNat k++Γ'.cons::trList rest))=nameBits k + simp only [List.cons_append,List.nil_append,WordTransducer.output,next,emit] + rw [trNat_bits,threshold_output] + rfl + | cons b v ih => + cases b with + | false => + change false::WordTransducer.output next emit .cell + (trList (v.map Bool.toNat++2::k::rest))=false::(v++nameBits k) + exact congrArg (List.cons false) ih + | true => + change true::WordTransducer.output next emit .cell + (trList (v.map Bool.toNat++2::k::rest))=true::(v++nameBits k) + exact congrArg (List.cons true) ih + +lemma output (n k : ℕ) (v : List Bool) (rest : List ℕ) : + WordTransducer.output next emit .header (trList (n::(v.map Bool.toNat++2::k::rest)))= + nameBits n++v++nameBits k := by + rw [trList,trNat_bits,header_output,cells_output] + simp only [nameBits,List.append_assoc] + +lemma finiteAlphabet (k : machine.K) : Finite (machine.Γ k) := + WordTransducer.finiteAlphabet _ _ _ k + +def outputsInTime (n k : ℕ) (v : List Bool) (rest : List ℕ) : + TM2OutputsInTime machine (trList (n::(v.map Bool.toNat++2::k::rest))) + (some (nameBits n++v++nameBits k)) + (2*bitsize (n::(v.map Bool.toNat++2::k::rest))+ + (nameBits n++v++nameBits k).length+2) := by + have hh := WordTransducer.outputsInTime .header next emit (trList (n::(v.map Bool.toNat++2::k::rest))) + exact (congrArg (fun w : List Bool => + TM2OutputsInTime machine (trList (n :: (v.map Bool.toNat ++ 2 :: k :: rest))) + (some w) (2 * bitsize (n :: (v.map Bool.toNat ++ 2 :: k :: rest)) + w.length + 2)) + (output n k v rest)).mp hh + +end MinUncut.Costed.GraphCodec + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Graphs/HonestBudgets.lean b/lean/OAI/Computability/MinUncut/Graphs/HonestBudgets.lean new file mode 100644 index 0000000000000000000000000000000000000000..5c2ece2115cd018f0bdadb33f43ff2cc10117cf2 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Graphs/HonestBudgets.lean @@ -0,0 +1,163 @@ +import Mathlib +import OAI.Computability.MinUncut.Graphs.HonestComparisons +import OAI.Computability.MinUncut.Estimates.ComparisonSoundness + +namespace OAI + +noncomputable section +open scoped BigOperators +namespace MinUncut.Inner +open MeasureTheory RowNoise GaussianBudget +attribute [local instance] Classical.propDecidable +variable {V A : Type*} [AddCommGroup V] [Module F₂ V] [AddTorsor V A] [Fintype A] +variable {m n : ℕ} + +lemma secondError_evaluation_le (a : A) (hn : 0 < n) (hm : 0 < m) + {σ η δ : ℝ} (hσ : 0 ≤ σ) (hσ1 : σ ≤ 1) (hη : 0 ≤ η) (hδ : 0 ≤ δ) + (hρ : δ^2/(m:ℝ) ≤ 1) : + secondError (m := m) (n := n) (evaluationProof a) (δ^2/(m:ℝ)) σ η ≤ 8*δ+4*η := by + have hρ0 : 0 ≤ δ^2/(m:ℝ) := by positivity + have hB (B : FaceArray A m n) : + (𝔼 C : FaceArray A m n, density (δ^2/(m:ℝ)) B C* + (∫ c, secondRejection (evaluationProof a) B C σ η c ∂gauss (Point m n))) ≤ 8*δ+4*η := by + calc + _ ≤ 𝔼 C : FaceArray A m n, density (δ^2/(m:ℝ)) B C* + (4*‖vector (codeVector (labelCode B a))-vector (codeVector (labelCode C a))‖+4*η) := by + apply Finset.expect_le_expect + intro C _ + exact mul_le_mul_of_nonneg_left (secondRejection_evaluation_le a B C hn hσ hσ1 hη) + (density_nonneg hρ0 hρ B C) + _ = 4*(𝔼 C : FaceArray A m n, density (δ^2/(m:ℝ)) B C* + ‖vector (codeVector (labelCode B a))-vector (codeVector (labelCode C a))‖)+4*η := by + simp_rw [mul_add,mul_left_comm (density _ B _),Finset.expect_add_distrib, + ← Finset.mul_expect] + rw [← Finset.expect_mul,density_mean,one_mul] + _ ≤ _ := by have h := noise_vector_le a B hn hm hδ hρ; linarith + exact (Finset.expect_le_expect (fun B _ => hB B)).trans_eq (Fintype.expect_const _) + +lemma honest_first_budget (a : A) (hn : 0 < n) {J : ℝ} (hJ : 1 ≤ J) : + firstError (m := m) (n := n) (evaluationProof a) (sourceSigma J) (sourceEta J) ≤ + 10*sourceSigma J := by + have h := firstError_evaluation_le (m := m) a hn (sourceSigma_pos hJ).le (sourceEta_pos hJ).le + have := sourceEta_le_sigma hJ + have := sourceSigma_pos hJ + linarith + +lemma honest_second_budget (a : A) (hn : 0 < n) (hm : 0 < m) {J : ℝ} (hJ : 1 ≤ J) : + secondError (m := m) (n := n) (evaluationProof a) ((sourceEta J)^2/(m:ℝ)) + (sourceSigma J) (sourceEta J) ≤ 10*(sourceEta J+sourceEta J) := by + have h := secondError_evaluation_le a hn hm (sourceSigma_pos hJ).le (sourceSigma_le_one hJ) + (sourceEta_pos hJ).le (sourceEta_pos hJ).le (source_row_rate hJ hm).2.1 + have := sourceEta_pos hJ + linarith +end MinUncut.Inner + +namespace MinUncut.Inner +open MeasureTheory +attribute [local instance] Classical.propDecidable +variable {V A W B : Type*} [AddCommGroup V] [Module F₂ V] [AddTorsor V A] [Fintype A] + [AddCommGroup W] [Module F₂ W] [AddTorsor W B] [Fintype B] {m n : ℕ} + +omit [Fintype A] [Fintype B] in +lemma labelCode_pullback (π : A →ᵃ[F₂] B) (C : FaceArray B m n) (a : A) : + labelCode (pullbackFaces π C) a=labelCode C (π a) := by + apply Subtype.ext + funext x + rfl + +omit [Fintype A] in +lemma fourthError_evaluation (π : A →ᵃ[F₂] B) (a : A) (σ η : ℝ) : + fourthError (m := m) (n := n) π (evaluationProof a) (evaluationProof (π a)) σ η=0 := by + simp only [fourthError,comparisonRejection,comparisonFailure,evaluationProof,pullQuery, + labelCode_pullback,ite_true,integral_zero,Finset.expect_const_zero] + +lemma fourthError_le_one (π : A →ᵃ[F₂] B) (f : FoldedProof A) (g : FoldedProof B) (σ η : ℝ) : + fourthError (m := m) (n := n) π f g σ η ≤ 1 := by + have hC (C : FaceArray B m n) : + (∫ c, comparisonRejection f g (pullbackFaces π C) C σ η c ∂gauss (Point m n)) ≤ 1 := by + simpa only [integral_const,probReal_univ,one_smul] using + integral_mono (comparisonRejection_integrable f g _ _ σ η) (integrable_const 1) + (fun c => (comparisonRejection_range f g _ _ σ η c).2) + exact (Finset.expect_le_expect (fun C _ => hC C)).trans_eq (Fintype.expect_const _) +end MinUncut.Inner +namespace MinUncut.Outer +open MinUncut.Inner OuterSmoothness +attribute [local instance] Classical.propDecidable BinaryFourier.dualFintype +variable {Name I S : Type*} [Fintype I] [Fintype S] [Nonempty S] + +def honestProof (s : Name → F₂) : ProofFamily Name I where + first U := evaluationProof (firstLabel s U) + second Q := evaluationProof (secondLabel s Q) + +lemma honest_fourth_point (s : Name → F₂) (U : I → Equation Name) (h : I → Bool) + (pos : I → Fin 3) (m n : ℕ) (σ η : ℝ) : + (honestProof (I := I) s).fourthTotal (m := m) (n := n) σ η U h pos ≤ + ∑ i, if Satisfied s (U i) then (0:ℝ) else 1 := by + by_cases hall : ∀ i, Satisfied s (U i) + · have hp := honest_projection s U hall h pos + simp only [ProofFamily.fourthTotal,honestProof] + rw [← hp,fourthError_evaluation] + simp only [hall,ite_eq_left,Finset.sum_const_zero,le_refl] + · obtain ⟨i,hi⟩ := not_forall.mp hall + have hs : (1:ℝ) ≤ ∑ j, if Satisfied s (U j) then (0:ℝ) else 1 := by + simpa only [hi,ite_false] using + (Finset.single_le_sum (a := i) (fun j _ => by split <;> norm_num : ∀ j ∈ Finset.univ, 0 ≤ if Satisfied s (U j) then (0:ℝ) else 1) (Finset.mem_univ i)) + exact (fourthError_le_one (projection U h pos) _ _ σ η).trans hs + +lemma failure_fraction (equations : S → Equation Name) (s : Name → F₂) : + (𝔼 a : S, if Satisfied s (equations a) then (0:ℝ) else 1)=1-equationFraction equations s := by + have he (a : S) : (if Satisfied s (equations a) then (0:ℝ) else 1)= + 1-(if Satisfied s (equations a) then (1:ℝ) else 0) := by split <;> norm_num + simp_rw [he,Finset.expect_sub_distrib,Fintype.expect_const,Fintype.expect_eq_sum_div_card] + rfl + +lemma honest_fourth_mean (equations : S → Equation Name) (s : Name → F₂) {k : ℕ} + (hk : k ≤ Fintype.card I) (m n : ℕ) (σ η : ℝ) : + edgeMean equations k ((honestProof (I := I) s).fourthTotal (m := m) (n := n) σ η) ≤ + (Fintype.card I:ℝ)*(1-equationFraction equations s) := by + apply (edgeMean_mono equations k (fun U h p => honest_fourth_point s U h p m n σ η)).trans_eq + let : Nonempty (FixedSets I k) := fixedSets_nonempty hk + have hcoord (i : I) : (𝔼 a : I → S, if Satisfied s (equations (a i)) then (0:ℝ) else 1)= + 1-equationFraction equations s := + (Subbox.expect_coordinate (B := fun _ : I => S) i + (fun b => if Satisfied s (equations b) then (0:ℝ) else 1)).trans (failure_fraction equations s) + simp only [edgeMean,Fintype.expect_const,Finset.expect_sum_comm,hcoord,Finset.sum_const, + Finset.card_univ,nsmul_eq_mul] + +attribute [local irreducible] firstError secondError thirdError fourthError edgeMean + +lemma honest_errors_le {J : ℝ} (hJ : 1 ≤ J) (P : InnerParameters J) (O : OuterParameters J P) + (equations : S → Equation Name) (s : Name → F₂) (hcard : Fintype.card I=O.t) + (hs : (O.t:ℝ)*(1-equationFraction equations s) ≤ O.b4) (j : Test) : + (honestProof (I := I) s).testErrors P O equations j ≤ budgets P O j := by + have hk : O.k ≤ Fintype.card I := by simpa only [hcard] using O.hk + have hn : 0 < P.n := by have := P.hn; omega + have hm : 0 < P.m := by have := P.hm; omega + cases j <;> simp only [ProofFamily.testErrors,budgets,honestProof] + · apply (edgeMean_mono equations O.k (fun U h pos => honest_first_budget (V := SecondAlphabet (secondQuestion U h pos)) (secondLabel s (secondQuestion U h pos)) hn hJ)).trans_eq + exact edgeMean_const equations hk _ + · apply (edgeMean_mono equations O.k (fun U h pos => honest_second_budget (V := SecondAlphabet (secondQuestion U h pos)) (secondLabel s (secondQuestion U h pos)) hn hm hJ)).trans_eq + exact edgeMean_const equations hk _ + · apply le_of_eq + simp only [thirdError_evaluation] + exact edgeMean_const equations hk _ + · exact (honest_fourth_mean equations s hk P.m P.n (sourceSigma J) (sourceEta J)).trans + (by simpa only [hcard] using hs) + +lemma honest_cost_le {J : ℝ} (hJ : 1 ≤ J) (P : InnerParameters J) (O : OuterParameters J P) + (equations : S → Equation Name) (s : Name → F₂) (hcard : Fintype.card I=O.t) + (hs : (O.t:ℝ)*(1-equationFraction equations s) ≤ O.b4) : + (honestProof (I := I) s).cost P O equations ≤ 4 := by + have hh : (honestProof (I := I) s).cost P O equations ≤ ∑ _ : Test, (1:ℝ) := by + apply Finset.sum_le_sum + intro j _ + exact (div_le_one (budgets_pos hJ P O j)).mpr (honest_errors_le hJ P O equations s hcard hs j) + have hc : (∑ _ : Test, (1:ℝ))=4 := by + have hc : Fintype.card Test=4 := by decide + simp [hc] + exact hh.trans_eq hc +end MinUncut.Outer + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Graphs/HonestComparisons.lean b/lean/OAI/Computability/MinUncut/Graphs/HonestComparisons.lean new file mode 100644 index 0000000000000000000000000000000000000000..7c4d7ff05f49e1379fec1a3204f6f6a5be08eef2 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Graphs/HonestComparisons.lean @@ -0,0 +1,176 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.FirstError +import OAI.Computability.MinUncut.Analysis.FreshCorrelation +import OAI.Computability.MinUncut.Graphs.HonestRows +import OAI.Computability.MinUncut.Analysis.GaussianPacking + +namespace OAI + +noncomputable section +open scoped BigOperators +open MeasureTheory ProbabilityTheory +namespace MinUncut.Inner +open GaussianBudget +attribute [local instance] Classical.propDecidable +variable {V A : Type*} [AddCommGroup V] [Module F₂ V] [AddTorsor V A] [Fintype A] +variable {m n : ℕ} + +lemma score_query (z : Code m n) (u : Point m n → ℝ) (d : Code m n → ℝ) : + query u d z=decide (0 ≤ score (codeVector z) u+d z) := by + rw [score_codeVector] + rfl + +lemma score_add_noise (v c g : Point m n → ℝ) (σ : ℝ) : + score v (c+σ•g)=score v c+σ*score v g := by + simp only [score,Pi.add_apply,Pi.smul_apply,smul_eq_mul,mul_add,Finset.sum_add_distrib] + rw [Finset.mul_sum] + congr 1 + apply Finset.sum_congr rfl + intro x _ + ring + +omit [Fintype A] in +lemma firstFailure_evaluation (a : A) (B : FaceArray A m n) (σ η : ℝ) + (c g : Point m n → ℝ) (l : Code m n → ℝ) : + firstFailure (evaluationProof a) B σ η c g l = + signFailure (score (codeVector (labelCode B a)) c) + (score (codeVector (labelCode B a)) c+σ*score (codeVector (labelCode B a)) g+η*l (labelCode B a)) := by + simp only [firstFailure,evaluationProof,pullQuery,score_query,Pi.zero_apply,add_zero, + score_add_noise,Pi.smul_apply,smul_eq_mul,decide_eq_decide,signFailure] + +omit [Fintype A] in +lemma firstRejection_evaluation_le (a : A) (B : FaceArray A m n) (hn : 0 firstRejection_evaluation_le a B hn hσ hη)).trans_eq + (Fintype.expect_const _) + +omit [Fintype A] in +lemma secondFailure_evaluation (a : A) (B C : FaceArray A m n) (σ η : ℝ) + (c : Point m n → ℝ) (p : (Point m n → ℝ) × (Code m n → ℝ)) : + secondFailure (evaluationProof a) B C σ η c p = + signFailure (score (codeVector (labelCode B a)) c+σ*score (codeVector (labelCode B a)) p.1+η*p.2 (labelCode B a)) + (score (codeVector (labelCode C a)) c+σ*score (codeVector (labelCode C a)) p.1+η*p.2 (labelCode C a)) := by + simp only [secondFailure,evaluationProof,pullQuery,score_query,score_add_noise, + Pi.smul_apply,smul_eq_mul,decide_eq_decide,signFailure] + +omit [Fintype A] in +lemma secondRejection_evaluation_le (a : A) (B C : FaceArray A m n) (hn : 0 gaussianReal 0 1)).prod (Measure.pi (fun _ : Code m n => gaussianReal 0 1))) = + ∫ g, ∫ l, + signFailure (score (codeVector (labelCode B a)) c+σ*score (codeVector (labelCode B a)) g+η*l (labelCode B a)) + (score (codeVector (labelCode C a)) c+σ*score (codeVector (labelCode C a)) g+η*l (labelCode C a)) + ∂Measure.pi (fun _ : Code m n => gaussianReal 0 1) ∂Measure.pi (fun _ : Point m n => gaussianReal 0 1) := by + apply integral_prod + apply signFailure_integrable <;> unfold score <;> fun_prop + simp_rw [he] + exact second_triple_bound (codeVector_norm hn _) (codeVector_norm hn _) hσ hσ1 hη _ _ + +omit [Fintype A] in +lemma thirdFailure_evaluation (a : A) (B : FaceArray A m n) (η : ℝ) + (u : Point m n → ℝ) (l : Code m n → ℝ) (z : Code m n) : + thirdFailure (evaluationProof a) B η u l z=if z=labelCode B a then 1 else 0 := by + unfold thirdFailure evaluationProof + by_cases h : z=labelCode B a + · subst z; simp + · simp [Function.update_of_ne (Ne.symm h),h] + +omit [Fintype A] in +lemma thirdRejection_evaluation (a : A) (B : FaceArray A m n) (σ η : ℝ) + (c : Point m n → ℝ) : thirdRejection (evaluationProof a) B σ η c=(Fintype.card (Code m n):ℝ)⁻¹ := by + simp only [thirdRejection,thirdFailure_evaluation,integral_const,probReal_univ,one_smul, + Fintype.expect_eq_sum_div_card] + simp + +lemma thirdError_evaluation (a : A) (σ η : ℝ) : + thirdError (m := m) (n := n) (evaluationProof a) σ η=(Fintype.card (Code m n):ℝ)⁻¹ := by + simp only [thirdError,thirdRejection_evaluation,integral_const,probReal_univ,one_smul,Fintype.expect_const] +end MinUncut.Inner + +end +noncomputable section +open scoped BigOperators +namespace MinUncut.Inner +open BinaryFourier RowNoise GaussianBudget +attribute [local instance] Classical.propDecidable +variable {V A : Type*} [AddCommGroup V] [Module F₂ V] [AddTorsor V A] [Fintype A] +variable {m n : ℕ} + +lemma codeVector_distance_sq (hn : 0 mul_nonneg (hw t) (sq_nonneg _)) + have he (t : T) : w t*(f t-M)^2=w t*(f t)^2-2*M*(w t*f t)+M^2*w t := by ring + simp_rw [he,Finset.expect_add_distrib,Finset.expect_sub_distrib,← Finset.mul_expect,hw1,mul_one] at hz + change 0 ≤ (𝔼 t, w t*(f t)^2)-2*M*M+M^2 at hz + change M^2 ≤ _ + nlinarith only [hz] + +lemma noise_vector_le (a : A) (B : FaceArray A m n) (hn : 0 ‖vector (codeVector (labelCode B a))-vector (codeVector (labelCode C a))‖) + (density_nonneg hρ hρ1 B) (density_mean _ B) + have hb := noise_vector_sq_le a B hn hρ hρ1 + have hmp : (0:ℝ)< m := by exact_mod_cast hm + have he : 2*(m:ℝ)*(δ^2/(m:ℝ))=2*δ^2 := by field_simp + rw [he] at hb + have hM : 0 ≤ 𝔼 C : FaceArray A m n, density (δ^2/(m:ℝ)) B C* + ‖vector (codeVector (labelCode B a))-vector (codeVector (labelCode C a))‖ := + Finset.expect_nonneg (fun C _ => mul_nonneg (density_nonneg hρ hρ1 B C) (norm_nonneg _)) + have hs' := hs.trans hb + exact (sq_le_sq₀ hM (by positivity)).mp (by nlinarith [sq_nonneg δ]) +end MinUncut.Inner + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Graphs/HonestRows.lean b/lean/OAI/Computability/MinUncut/Graphs/HonestRows.lean new file mode 100644 index 0000000000000000000000000000000000000000..be3bbb767df700131a23b7cc82ba34d0f97cfccc --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Graphs/HonestRows.lean @@ -0,0 +1,97 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.Convolution +import OAI.Computability.MinUncut.Analysis.GaussianSmallBall + +namespace OAI + +section +noncomputable section +open scoped BigOperators +namespace MinUncut.Inner +open BinaryFourier RowNoise GaussianBudget +attribute [local instance] Classical.propDecidable +variable {V A : Type*} [AddCommGroup V] [Module F₂ V] [AddTorsor V A] [Fintype A] +variable {m n : ℕ} + +def evaluationProof (a : A) : FoldedProof A where + answer P := P a + folded _ := rfl + +def codeVector (z : Code m n) : Point m n → ℝ := + fun x => (Real.sqrt (n^m:ℕ))⁻¹ * BinaryFourier.sign (z.val x) + +lemma codeVector_norm (hn : 0 (⟨i,face x i⟩ : Row m n)) := by + intro r hr + by_contra h + have hneq : ∀ i : Fin m, (⟨i,face x i⟩ : Row m n)≠r := by + intro i hi + exact h (Finset.mem_image.mpr ⟨i,Finset.mem_univ _,hi⟩) + have hz : frequency (labelFunctional a x) r=0 := by + ext b + simp only [frequency,LinearMap.comp_apply,labelFunctional,LinearMap.coe_mk,AddHom.coe_mk, + LinearMap.single_apply] + change (∑ i : Fin m, (Pi.single r b : FaceArray A m n) ⟨i,face x i⟩ a)=0 + apply Finset.sum_eq_zero + intro i _ + rw [Pi.single_eq_of_ne (hneq i)] + rfl + exact (Finset.mem_filter.mp hr).2 hz + exact (Finset.card_le_card hs).trans ((Finset.card_image_le).trans_eq (by simp)) + +lemma character_noise_distance {R W : Type*} [Fintype R] [DecidableEq R] + [Fintype W] [DecidableEq W] [AddCommGroup W] [Module F₂ W] + (a : ℝ) (α : Module.Dual F₂ (R → W)) (B : R → W) : + (𝔼 C, density a B C*(character α B-character α C)^2)=2*(1-(1-a)^degree α) := by + have he (C : R → W) : density a B C*(character α B-character α C)^2= + 2*density a B C-2*character α B*(density a B C*character α C) := by + have hb := character_sq α B + have hc := character_sq α C + nlinarith only [congrArg (fun t => density a B C*t) hb,congrArg (fun t => density a B C*t) hc] + simp_rw [he,Finset.expect_sub_distrib,← Finset.mul_expect,density_mean,mul_one] + change 2-2*character α B*noise a (character α) B=_ + rw [noise_character] + have hb := character_sq α B + nlinarith only [congrArg (fun t => (1-a)^degree α*t) hb] + +lemma character_noise_distance_le {R W : Type*} [Fintype R] [DecidableEq R] + [Fintype W] [DecidableEq W] [AddCommGroup W] [Module F₂ W] + {ρ : ℝ} (hρ1 : ρ≤1) (α : Module.Dual F₂ (R → W)) (B : R → W) : + (𝔼 C, density ρ B C*(character α B-character α C)^2)≤2*(degree α:ℝ)*ρ := by + rw [character_noise_distance] + have h := one_add_mul_le_pow (by linarith : -2 ≤ -ρ) (degree α) + simp only [mul_neg,← sub_eq_add_neg] at h + linarith + +end MinUncut.Inner + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Graphs/SelectedGraphEndpoint.lean b/lean/OAI/Computability/MinUncut/Graphs/SelectedGraphEndpoint.lean new file mode 100644 index 0000000000000000000000000000000000000000..8e81478bca8ab9d708fb1d54165f242a9fa4b181 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Graphs/SelectedGraphEndpoint.lean @@ -0,0 +1,71 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineTableIteration +import OAI.Computability.MinUncut.Graphs.GeneratedGraph +import OAI.Computability.MinUncut.Estimates.SelectedSyntax + +namespace OAI + +section +noncomputable section +namespace MinUncut.Uniform +open MinUncut.Preprocess MinUncut.Inner MinUncut.Outer MinUncut.SourceBridge +open MinUncut.Costed MinUncut.Costed.SourceWords +open MinUncutGames MinUncutGames.Foundations MinUncutGames.Foundations.Complexity +open MinUncutGames.Foundations.Hastad MinUncutGames.Foundations.Hastad.SourceOccurrences +open MinUncutGames.Reduction + +def frontend (F : BinaryFormula.Formula) : SourceGeneratorContract.NonemptyFormula := + MinUncutGames.Outer.HastadSource.gapInput Parameters.baseTable (BinaryOccurrenceRename.renamed F) +def frontendMachine : Turing.TM2ComputableInPolyTime BinaryEncoding.formulaBits + SourceGeneratorContract.inputEncoding frontend := + MachineSequential.composeBits (f := BinaryOccurrenceRename.renamed) + (g := MinUncutGames.Outer.HastadSource.gapInput Parameters.baseTable) BinaryRenameMachine.computableInPolyTime + (MinUncutGames.Outer.HastadSource.gapMachine Parameters.baseTable) +lemma frontend_finite : MachineFiniteAlphabet.FiniteAlphabet frontendMachine.tm := + MachineFiniteAlphabet.composeBits _ _ BinaryRenameMachine.computation_finiteAlphabet + (TableIterationFiniteAlphabet.gapMap Parameters.baseTable + (MinUncutGames.Outer.HastadSource.roundMachine Parameters.baseTable) + (MinUncutGames.Outer.HastadSource.roundMachine_finite Parameters.baseTable)) + +def program (K : ℕ) := completeGraphProgram (selectedParameters K) (chosenEnumeration K) + (chosenRepetition K) (chosenNoise K) +lemma program_computable : Computable (fun K=>(program K).code) := c_selectedGraphCode + +def source (K : ℕ) (F : BinaryFormula.Formula) : SourceEncoding.Input := + (selectedParameters K).sourceReduction.reduce F +lemma source_eq (K : ℕ) (F : BinaryFormula.Formula) : + source K F=sourceInput (frontend F).val (chosenRepetition K) (chosenNoise K) + (SourceNoiseParameter.noiseDenominator_pos (chosenError K)) := rfl + +def output (K : ℕ) (F : BinaryFormula.Formula) : MinUncut.Output := + generatedGraph (selectedParameters K) (source K F) (chosenEnumeration K) +lemma output_yes (K : ℕ) (F : BinaryFormula.Formula) (hF : F.Satisfiable) : + (output K F).opt≤(output K F).threshold := by + obtain ⟨s,hs⟩:=binaryReduction_complete (selectedParameters K).sourceReduction F hF + (selectedParameters K).o.t (selectedParameters K).o.b4 (selectedParameters K).sourceError_budget + exact generatedGraph_yes (selectedParameters K) (source K F) (chosenEnumeration K) s hs +lemma output_no (K : ℕ) (hK : 2≤K) (F : BinaryFormula.Formula) (hF : ¬F.Satisfiable) : + K*(output K F).threshold<(output K F).opt := by + apply generatedGraph_no (selectedParameters K) (source K F) (chosenEnumeration K) hK + (show 8*K≤parameterJ K by unfold parameterJ; omega) + exact binaryReduction_sound (selectedParameters K).sourceError_small + (selectedParameters K).sourceReduction F hF + +lemma output_words (K : ℕ) (F : BinaryFormula.Formula) : + ∃table junk,completeGraphWords (selectedParameters K) (chosenEnumeration K) + (chosenRepetition K) (chosenNoise K) (formulaWords (frontend F).val)= + (output K F).vertices::((table : List Bool).map Bool.toNat++2::(output K F).threshold::junk) ∧ + (output K F).bits=BinaryEncoding.nameBits (output K F).vertices++table++ + BinaryEncoding.nameBits (output K F).threshold := by + obtain ⟨junk,hj⟩:=completeGraphWords_spec (selectedParameters K) (chosenEnumeration K) + (frontend F).val (chosenRepetition K) (chosenNoise K) + (SourceNoiseParameter.noiseDenominator_pos (chosenError K)) (frontend F).property + rw [←source_eq] at hj + refine ⟨_,junk,hj,?_⟩ + exact GraphRegisters.listOutput_bits _ _ _ +end MinUncut.Uniform + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Graphs/SignedGraph.lean b/lean/OAI/Computability/MinUncut/Graphs/SignedGraph.lean new file mode 100644 index 0000000000000000000000000000000000000000..43e3fd30a155f283dd7aa2050d09a3a695621dbe --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Graphs/SignedGraph.lean @@ -0,0 +1,210 @@ +import Mathlib +import OAI.Computability.MinUncut.Model + +namespace OAI + +noncomputable section +open scoped BigOperators +namespace MinUncut.PathRealization +attribute [local instance] Classical.propDecidable + +structure Demand (V : Type*) where + left : V + right : V + equal : Bool + +variable {V D : Type*} +abbrev Vertex (V D : Type*) := V ⊕ (D × Fin 3) + +def failure (e : Demand V) (s : V → Bool) : ℕ := + if (s e.left == s e.right) = e.equal then 0 else 1 + +def mono (x y : Bool) : ℕ := if x=y then 1 else 0 + +def localCost (equal x y a b c : Bool) : ℕ := + mono x a + mono a b + if equal then mono b c+mono c y else mono b y + +lemma local_lower (equal x y a b c : Bool) : + (if (x==y) = equal then 0 else 1) ≤ localCost equal x y a b c := by + cases equal <;> cases x <;> cases y <;> cases a <;> cases b <;> cases c <;> + decide + +lemma local_extension (equal x y : Bool) : + localCost equal x y (!x) x (!x) = (if (x==y)=equal then 0 else 1) := by + cases equal <;> cases x <;> cases y <;> decide + +abbrev EdgeIndex (e : D → Demand V) := {p : D×Fin 4 // p.2.val < if (e p.1).equal then 4 else 3} + +def ends (e : D → Demand V) (p : D×Fin 4) : Vertex V D × Vertex V D := + match p.2.val with + | 0 => (.inl (e p.1).left,.inr (p.1,0)) + | 1 => (.inr (p.1,0),.inr (p.1,1)) + | 2 => if (e p.1).equal then (.inr (p.1,1),.inr (p.1,2)) + else (.inr (p.1,1),.inl (e p.1).right) + | _ => (.inr (p.1,2),.inl (e p.1).right) + +def edge (e : D → Demand V) (p : EdgeIndex e) : Sym2 (Vertex V D) := + s((ends e p.val).1,(ends e p.val).2) + +lemma ends_ne (e : D → Demand V) (p : EdgeIndex e) : + (ends e p.val).1 ≠ (ends e p.val).2 := by + obtain ⟨⟨d,i⟩,hi⟩ := p + fin_cases i <;> simp only [ends] <;> (try split_ifs) <;> simp + +lemma edge_injective (e : D → Demand V) : Function.Injective (edge e) := by + intro p q he + obtain ⟨⟨d,i⟩,hi⟩ := p + obtain ⟨⟨f,j⟩,hj⟩ := q + apply Subtype.ext + fin_cases i <;> fin_cases j <;> + simp only [edge,ends] at he <;> (try split_ifs at he) <;> + simp_all + +variable [Fintype V] [Fintype D] [DecidableEq V] [DecidableEq D] + +def edgeSet (e : D → Demand V) : Finset (Sym2 (Vertex V D)) := + Finset.univ.image (edge e) + +omit [Fintype V] in +lemma edgeSet_nondiag (e : D → Demand V) (z : Sym2 (Vertex V D)) (hz : z ∈ edgeSet e) : + ¬ z.IsDiag := by + obtain ⟨p,_,rfl⟩ := Finset.mem_image.mp hz + simpa only [edge,Sym2.mk_isDiag_iff] using ends_ne e p + +def graph (e : D → Demand V) : SimpleGraph (Vertex V D) where + Adj x y := s(x,y) ∈ edgeSet e + symm := ⟨by intro x y h; simpa only [Sym2.eq_swap] using h⟩ + loopless := ⟨by intro x hx; exact edgeSet_nondiag e s(x,x) hx (by simp)⟩ + +instance (e : D → Demand V) : DecidableRel (graph e).Adj := Classical.decRel _ + +lemma graph_edgeFinset (e : D → Demand V) : (graph e).edgeFinset=edgeSet e := by + ext z + induction z using Sym2.inductionOn with + | _ x y => + simp only [SimpleGraph.edgeFinset, Set.mem_toFinset] + rfl + +def uncut (e : D → Demand V) (s : Vertex V D → Bool) : ℕ := + ∑ p : EdgeIndex e, mono (s (ends e p.val).1) (s (ends e p.val).2) + +def totalFailure (e : D → Demand V) (s : V → Bool) : ℕ := ∑ d, failure (e d) s + +def extend (e : D → Demand V) (s : V → Bool) : Vertex V D → Bool + | .inl v => s v + | .inr (d,i) => if i.val=1 then s (e d).left else !(s (e d).left) + +omit [Fintype V] [DecidableEq V] [DecidableEq D] in +lemma uncut_locals (e : D → Demand V) (s : Vertex V D → Bool) : + uncut e s = ∑ d, localCost (e d).equal (s (.inl (e d).left)) (s (.inl (e d).right)) + (s (.inr (d,0))) (s (.inr (d,1))) (s (.inr (d,2))) := by + unfold uncut + rw [← Finset.sum_subtype (Finset.univ.filter (fun p : D×Fin 4 => p.2.val < if (e p.1).equal then 4 else 3)) (by simp) (fun p : D×Fin 4 => mono (s (ends e p).1) (s (ends e p).2))] + rw [Finset.sum_filter] + simp only [Fintype.sum_prod_type] + apply Finset.sum_congr rfl + intro d _ + rw [Fin.sum_univ_four] + cases h : (e d).equal <;> simp [h,ends,localCost,add_assoc] + +omit [Fintype V] [DecidableEq V] [DecidableEq D] in +lemma uncut_lower (e : D → Demand V) (s : Vertex V D → Bool) : + totalFailure e (fun v => s (.inl v)) ≤ uncut e s := by + rw [uncut_locals] + exact Finset.sum_le_sum (fun d _ => local_lower _ _ _ _ _ _) + +omit [Fintype V] [DecidableEq V] [DecidableEq D] in +lemma uncut_extend (e : D → Demand V) (s : V → Bool) : uncut e (extend e s)=totalFailure e s := by + rw [uncut_locals] + apply Finset.sum_congr rfl + intro d _ + simpa [extend,failure] using + local_extension (e d).equal (s (e d).left) (s (e d).right) + +end MinUncut.PathRealization + +end +namespace MinUncut.FiniteProof + +def orient (b x : Bool) : Bool := if b then x else !x + +def rep {A : Type*} (a : A) (P : A → Bool) : {R : A → Bool // R a=true} := + ⟨fun x => P a == P x, by simp⟩ + +lemma rep_not {A : Type*} (a : A) (P : A → Bool) : + rep a (fun x => !(P x))=rep a P := by + apply Subtype.ext + funext x + simp [rep] + +lemma rep_restore {A : Type*} (a : A) (P : A → Bool) : + (fun x => orient (P a) ((rep a P).val x))=P := by + funext x + cases h : P a <;> cases hx : P x <;> simp [orient,rep,h,hx] + +lemma rep_fixed {A : Type*} (a : A) (R : {R : A → Bool // R a=true}) : + rep a R.val=R := by + apply Subtype.ext + funext x + simp [rep,R.property] + +variable {Q : Type*} {A : Q → Type*} (base : ∀ q, A q) + +abbrev Query := Σ q, A q → Bool +abbrev Variable := Σ q, {R : A q → Bool // R (base q)=true} + +def vertex (p : Query (A := A)) : Variable base := ⟨p.1,rep (base p.1) p.2⟩ + +def answer (y : Variable base → Bool) (q : Q) (P : A q → Bool) : Bool := + orient (P (base q)) (y (vertex base ⟨q,P⟩)) + +def Folded (f : ∀ q, (A q → Bool) → Bool) : Prop := + ∀ q P, f q (fun x => !(P x))= !(f q P) + +lemma answer_folded (y : Variable base → Bool) : Folded (answer base y) := by + intro q P + simp only [answer,vertex,rep_not] + cases h : P (base q) <;> simp [orient] + +lemma answer_rep (y : Variable base → Bool) (q : Q) + (R : {R : A q → Bool // R (base q)=true}) : answer base y q R.val=y ⟨q,R⟩ := by + simp [answer,vertex,R.property,rep_fixed,orient] + +lemma answer_of_folded (f : ∀ q, (A q → Bool) → Bool) (hf : Folded f) : + answer base (fun p => f p.1 p.2.val)=f := by + funext q P + unfold answer vertex + cases h : P (base q) + · have hr : (rep (base q) P).val=(fun x => !(P x)) := by + funext x + simp [rep,h] + simp only [hr,orient,Bool.false_eq_true,ite_false,hf q P,Bool.not_not] + · have hr : (rep (base q) P).val=P := by + funext x + simp [rep,h] + simp [hr,orient] + +structure QueryDemand where + left : Query (A := A) + right : Query (A := A) + equal : Bool + +def QueryDemand.signed (d : QueryDemand (A := A)) : PathRealization.Demand (Variable base) where + left := vertex base d.left + right := vertex base d.right + equal := if d.equal then (d.left.2 (base d.left.1)==d.right.2 (base d.right.1)) + else !(d.left.2 (base d.left.1)==d.right.2 (base d.right.1)) + +def QueryDemand.failure (d : QueryDemand (A := A)) + (f : ∀ q, (A q → Bool) → Bool) : ℕ := + if (f d.left.1 d.left.2 == f d.right.1 d.right.2)=d.equal then 0 else 1 + +lemma QueryDemand.failure_signed (d : QueryDemand (A := A)) (y : Variable base → Bool) : + PathRealization.failure (d.signed base) y=d.failure (answer base y) := by + unfold PathRealization.failure QueryDemand.signed QueryDemand.failure answer + cases d.equal <;> cases d.left.2 (base d.left.1) <;> cases d.right.2 (base d.right.1) <;> + cases y (vertex base d.left) <;> cases y (vertex base d.right) <;> rfl + +end MinUncut.FiniteProof + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Graphs/UnboundedGraphBase.lean b/lean/OAI/Computability/MinUncut/Graphs/UnboundedGraphBase.lean new file mode 100644 index 0000000000000000000000000000000000000000..3d31797c13d23072cf93cd3af68caded5e709657 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Graphs/UnboundedGraphBase.lean @@ -0,0 +1,56 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.UnboundedGraphMachine + +namespace OAI + +section +namespace MinUncut.Costed.Arena +open _root_.Turing _root_.OAI.Turing _root_.Turing.PartrecToTM2 _root_.OAI.Turing.PartrecToTM2 Turing.ToPartrec Polynomial +open MinUncutGames.Foundations.Complexity +noncomputable section + +def unboundedGraphMachine_outputs_base {c : Code} {v : List ℕ} {B n k : ℕ} + {table : List Bool} {rest : List ℕ} (base : Heap) + (hc : Runs c v (n::(table.map Bool.toNat++2::k::rest)) B) + (hl : (n::(table.map Bool.toNat++2::k::rest)).length≤B) : + TM2OutputsInTime unboundedGraphMachine (trList ((initialState c v base).encode)) + (some (MinUncutGames.BinaryEncoding.nameBits n++table++MinUncutGames.BinaryEncoding.nameBits k)) + (unboundedGraphTime.eval (magnitude (B::(initialState c v base).encode))) := by + apply Classical.choice + obtain ⟨h,hr,hm⟩ := unboundedWords_run hc hl base + let junk := rest++(n::(table.map Bool.toNat++2::k::rest)).reverse++2::words h + have he' : (n::(table.map Bool.toNat++2::k::rest))++ + (n::(table.map Bool.toNat++2::k::rest)).reverse++2::words h= + n::(table.map Bool.toNat++2::k::junk) := by + simp only [List.cons_append,List.append_assoc,junk] + rw [he'] at hr hm + obtain ⟨t,ht,hr⟩ := hr + have h1 := hr.finiteMachine + have h2 := GraphCodec.outputsInTime n k table junk + have h2' : TM2OutputsInTime GraphCodec.machine + ((trList (n::(table.map Bool.toNat++2::k::junk))).map id) + (some (MinUncutGames.BinaryEncoding.nameBits n++table++MinUncutGames.BinaryEncoding.nameBits k)) + (2*bitsize (n::(table.map Bool.toNat++2::k::junk))+ + (MinUncutGames.BinaryEncoding.nameBits n++table++MinUncutGames.BinaryEncoding.nameBits k).length+2) := by + have input_eq : @List.map (GraphCodec.machine.Γ GraphCodec.machine.k₀) + (GraphCodec.machine.Γ GraphCodec.machine.k₀) id + (trList (n::(table.map Bool.toNat++2::k::junk))) = + trList (n::(table.map Bool.toNat++2::k::junk)) := List.map_id _ + simpa only [input_eq] using h2 + have hh := MachineSequential.execute (codeMachine unboundedWordsCode) GraphCodec.machine id Γ'.cons + _ _ _ _ _ h1 h2' + have hb := bitsize_le_magnitude (n::(table.map Bool.toNat++2::k::junk)) + have ho := GraphRegisters.codec_length_le n k table junk + refine ⟨⟨hh.toEvalsTo,hh.steps_le_m.trans ?_⟩⟩ + change t+1+2*((trList (n::(table.map Bool.toNat++2::k::junk))).length+1)+ + (2*bitsize (n::(table.map Bool.toNat++2::k::junk))+ + (MinUncutGames.BinaryEncoding.nameBits n++table++MinUncutGames.BinaryEncoding.nameBits k).length+2)≤_ + simp only [unboundedGraphTime,eval_add,eval_mul,eval_C,eval_ofNat] + simp only [bitsize] at hb ⊢ + omega +end +end MinUncut.Costed.Arena + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Graphs/Vertex.lean b/lean/OAI/Computability/MinUncut/Graphs/Vertex.lean new file mode 100644 index 0000000000000000000000000000000000000000..39346e26179a91f0b0e0072dacb264a1590b647f --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Graphs/Vertex.lean @@ -0,0 +1,178 @@ +import Mathlib +import OAI.Computability.MinUncut.Model + +namespace OAI + +noncomputable section +open scoped BigOperators +open MeasureTheory ProbabilityTheory Filter +open scoped Topology NNReal +open scoped BigOperators +open MeasureTheory ProbabilityTheory Polynomial Filter +open scoped BigOperators Topology +open MeasureTheory ProbabilityTheory WithLp +open scoped BigOperators RealInnerProductSpace +open scoped BigOperators +namespace MinUncut.Box +variable {A : Type*} [Fintype A] [Nonempty A] + +def vertex {m : ℕ} (b : Fin m → Bool) (x y : Fin m → A) : Fin m → A := + fun i => if b i then x i else y i + +def moment {m : ℕ} (f : (Fin m → A) → ℝ) : ℝ := + 𝔼 x, 𝔼 y, ∏ b : Fin m → Bool, f (vertex b x y) + +def correlation {m : ℕ} (f : (Fin m → A) → ℝ) + (a : Fin m → (Fin m → A) → ℝ) : ℝ := + 𝔼 x, f x * ∏ i, a i x + +def Local {m : ℕ} (a : Fin m → (Fin m → A) → ℝ) : Prop := + ∀ i x z, a i (Function.update x i z) = a i x + +omit [Nonempty A] in +lemma expect_cons {m : ℕ} (f : (Fin (m+1) → A) → ℝ) : + (𝔼 x, f x) = 𝔼 z, 𝔼 x, f (Fin.cons z x) := by + rw [← Finset.expect_product', Finset.univ_product_univ] + exact Fintype.expect_equiv (Fin.consEquiv (fun _ : Fin (m+1) => A)).symm _ _ (fun x => congrArg f (Fin.cons_self_tail x).symm) + +lemma prod_cons {m : ℕ} (f : (Fin (m+1) → Bool) → ℝ) : + (∏ b, f b) = ∏ z : Bool, ∏ b, f (Fin.cons z b) := by + rw [← Finset.prod_product' ] + rw [Finset.univ_product_univ] + exact Fintype.prod_equiv (Fin.consEquiv (fun _ : Fin (m+1) => Bool)).symm _ _ (fun x => congrArg f (Fin.cons_self_tail x).symm) + +omit [Fintype A] [Nonempty A] in +@[simp] lemma vertex_cons {m : ℕ} (b : Bool) (bs : Fin m → Bool) + (x y : A) (xs ys : Fin m → A) : + vertex (Fin.cons b bs) (Fin.cons x xs) (Fin.cons y ys) = + Fin.cons (if b then x else y) (vertex bs xs ys) := by + ext i + refine Fin.cases ?_ (fun j => ?_) i <;> simp [vertex] + +omit [Nonempty A] in +lemma moment_succ {m : ℕ} (f : (Fin (m+1) → A) → ℝ) : + moment f = 𝔼 z, 𝔼 w, moment (fun x => f (Fin.cons z x) * f (Fin.cons w x)) := by + unfold moment + rw [expect_cons] + conv_lhs => arg 2; ext z; arg 2; ext x; rw [expect_cons] + simp_rw [prod_cons, Fintype.prod_bool, vertex_cons] + simp only [Bool.false_eq_true, ↓reduceIte, Finset.prod_mul_distrib] + apply Finset.expect_congr rfl + intro z _ + rw [Finset.expect_comm] + +lemma expect_pow_two_pow {T : Type*} [Fintype T] [Nonempty T] (f : T → ℝ) (m : ℕ) : + (𝔼 t, f t)^(2^m) ≤ 𝔼 t, (f t)^(2^m) := by + cases m with + | zero => simp + | succ m => + have he : Even (2^(m+1)) := ⟨2^m, by rw [pow_succ]; omega⟩ + have h := Real.pow_arith_mean_le_arith_mean_pow_of_even Finset.univ + (fun _ : T => (Fintype.card T : ℝ)⁻¹) f (fun _ _ => by positivity) + (by simp [Fintype.card_ne_zero]) he + simpa only [Finset.expect_eq_sum_div_card, Finset.card_univ, ← Finset.mul_sum, + ← Finset.sum_mul, div_eq_mul_inv, mul_comm] using h + +lemma expect_sq_le {T : Type*} [Fintype T] [Nonempty T] (f : T → ℝ) : + (𝔼 t, f t)^2 ≤ 𝔼 t, (f t)^2 := by + simpa using expect_pow_two_pow f 1 + +omit [Fintype A] [Nonempty A] in +lemma face_zero {m : ℕ} (a : Fin (m+1) → (Fin (m+1) → A) → ℝ) + (ha : Local a) (z w : A) (x : Fin m → A) : + a 0 (Fin.cons z x) = a 0 (Fin.cons w x) := by + simpa only [Fin.update_cons_zero] using ha 0 (Fin.cons w x) z + +lemma first_step {m : ℕ} (f : (Fin (m+1) → A) → ℝ) + (a : Fin (m+1) → (Fin (m+1) → A) → ℝ) + (ha : Local a) (hb : ∀ i x, |a i x| ≤ 1) : + (correlation f a)^2 ≤ 𝔼 z, 𝔼 w, + correlation (fun x => f (Fin.cons z x)*f (Fin.cons w x)) + (fun i x => a i.succ (Fin.cons z x)*a i.succ (Fin.cons w x)) := by + let z₀ := Classical.choice (inferInstance : Nonempty A) + let g (x : Fin m → A) : ℝ := 𝔼 z, f (Fin.cons z x) * ∏ i : Fin m, a i.succ (Fin.cons z x) + have hc : correlation f a = 𝔼 x, a 0 (Fin.cons z₀ x) * g x := by + unfold correlation + rw [expect_cons, Finset.expect_comm] + apply Finset.expect_congr rfl + intro x _ + simp only [Fin.prod_univ_succ] + simp_rw [face_zero a ha _ z₀ x] + dsimp [g] + rw [Finset.mul_expect] + apply Finset.expect_congr rfl + intro z _ + ring + rw [hc] + calc + _ ≤ 𝔼 x, (a 0 (Fin.cons z₀ x)*g x)^2 := expect_sq_le _ + _ ≤ 𝔼 x, (g x)^2 := by + apply Finset.expect_le_expect + intro x _ + rw [mul_pow] + have hs : (a 0 (Fin.cons z₀ x))^2 ≤ 1 := by + nlinarith [sq_abs (a 0 (Fin.cons z₀ x)), hb 0 (Fin.cons z₀ x), abs_nonneg (a 0 (Fin.cons z₀ x))] + simpa only [one_mul] using mul_le_mul_of_nonneg_right hs (sq_nonneg (g x)) + _ = _ := by + dsimp [g, correlation] + simp only [sq, Finset.expect_mul_expect] + rw [Finset.expect_comm] + apply Finset.expect_congr rfl + intro z _ + rw [Finset.expect_comm] + apply Finset.expect_congr rfl + intro w _ + apply Finset.expect_congr rfl + intro x _ + rw [Finset.prod_mul_distrib] + ring + +theorem box_cs (m : ℕ) (f : (Fin m → A) → ℝ) + (a : Fin m → (Fin m → A) → ℝ) (ha : Local a) (hb : ∀ i x, |a i x|≤1) : + (correlation f a)^(2^m) ≤ moment f := by + induction m with + | zero => + have hf : ∀ x : Fin 0 → A, f x = f (fun i => Fin.elim0 i) := + fun x => congrArg f (Subsingleton.elim _ _) + simp [correlation, moment, hf] + | succ m ih => + let g := fun z w (x : Fin m → A) => f (Fin.cons z x)*f (Fin.cons w x) + let b := fun z w (i : Fin m) (x : Fin m → A) => + a i.succ (Fin.cons z x)*a i.succ (Fin.cons w x) + have h₁ := first_step f a ha hb + have hlocal (z w : A) : Local (b z w) := by + intro i x t + dsimp [b] + simp only [Fin.cons_update, ha i.succ] + have hbound (z w : A) (i : Fin m) (x : Fin m → A) : |b z w i x|≤1 := by + dsimp [b] + rw [abs_mul] + simpa using mul_le_mul (hb i.succ (Fin.cons z x)) (hb i.succ (Fin.cons w x)) + (abs_nonneg _) (by norm_num : (0:ℝ)≤1) + calc + _ = ((correlation f a)^2)^(2^m) := by rw [← pow_mul, pow_succ]; congr 1; omega + _ ≤ (𝔼 z, 𝔼 w, correlation (g z w) (b z w))^(2^m) := + pow_le_pow_left₀ (sq_nonneg _) h₁ _ + _ ≤ 𝔼 z, (𝔼 w, correlation (g z w) (b z w))^(2^m) := expect_pow_two_pow _ m + _ ≤ 𝔼 z, 𝔼 w, (correlation (g z w) (b z w))^(2^m) := + Finset.expect_le_expect (fun z _ => expect_pow_two_pow _ m) + _ ≤ 𝔼 z, 𝔼 w, moment (g z w) := by + apply Finset.expect_le_expect + intro z _ + apply Finset.expect_le_expect + intro w _ + exact ih _ _ (hlocal z w) (hbound z w) + _ = _ := (moment_succ f).symm + +lemma abs_correlation_cs {m : ℕ} (hm : 0 < m) (f : (Fin m → A) → ℝ) + (a : Fin m → (Fin m → A) → ℝ) (ha : Local a) (hb : ∀ i x, |a i x|≤1) : + |correlation f a|^(2^m) ≤ moment f := by + have he : Even (2^m) := by + obtain ⟨k,rfl⟩ := Nat.exists_eq_succ_of_ne_zero (Nat.ne_of_gt hm) + exact ⟨2^k, by rw [pow_succ]; omega⟩ + simpa only [he.pow_abs] using box_cs m f a ha hb +end MinUncut.Box + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Graphs/VertexInjective.lean b/lean/OAI/Computability/MinUncut/Graphs/VertexInjective.lean new file mode 100644 index 0000000000000000000000000000000000000000..1a7b0b1aab8bddc5bc7fe517320b356566766043 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Graphs/VertexInjective.lean @@ -0,0 +1,56 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.FaceUpdateSelf + +namespace OAI + +noncomputable section +open scoped BigOperators +open MeasureTheory ProbabilityTheory Filter +open scoped Topology NNReal +open scoped BigOperators +open MeasureTheory ProbabilityTheory Polynomial Filter +open scoped BigOperators Topology +open MeasureTheory ProbabilityTheory WithLp +open scoped BigOperators RealInnerProductSpace +open scoped BigOperators +namespace MinUncut.CubeRows +open MeasureTheory ProbabilityTheory Filter +open scoped BigOperators +variable {ι A : Type*} [Fintype ι] [DecidableEq ι] [Fintype A] [DecidableEq A] [Nonempty A] + +omit [Fintype ι] [DecidableEq ι] [Fintype A] [DecidableEq A] [Nonempty A] in +lemma vertex_injective (x y : ι → A) (hxy : ∀ i, x i≠y i) : + Function.Injective (fun ν : ι → Bool => vertex ν x y) := by + intro ν ω he + funext i + exact bool_choice_injective (hxy i) (congrFun he i) + +omit [DecidableEq A] [Nonempty A] in +lemma independent_points (μ : Measure ℝ) [IsProbabilityMeasure μ] + (V : (ι → A) → ℝ → ℝ) (hV : ∀ x, Measurable (V x)) + (x y : ι → A) (hxy : ∀ i, x i≠y i) : + (∫ c, ∏ ν : ι → Bool, V (vertex ν x y) (c (vertex ν x y)) ∂Measure.pi (fun _ : ι → A => μ)) = + ∏ ν : ι → Bool, ∫ t, V (vertex ν x y) t ∂μ := by + have hi := (iIndepFun_pi (μ := fun _ : ι → A => μ) (X := fun z t => V z t) + (fun z => (hV z).aemeasurable)).precomp (vertex_injective x y hxy) + rw [hi.integral_fun_prod_eq_prod_integral (fun ν => ((hV _).comp (measurable_pi_apply _)).aestronglyMeasurable)] + apply Finset.prod_congr rfl + intro ν _ + have hh := integral_map (μ := Measure.pi (fun _ : ι → A => μ)) + (measurable_pi_apply (vertex ν x y)).aemeasurable (hV (vertex ν x y)).aestronglyMeasurable + rw [(measurePreserving_eval (fun _ : ι → A => μ) (vertex ν x y)).map_eq] at hh + exact hh.symm + +omit [DecidableEq A] [Nonempty A] in +lemma centered_point_cube_zero (μ : Measure ℝ) [IsProbabilityMeasure μ] + (V : (ι → A) → ℝ → ℝ) (hV : ∀ x, Measurable (V x)) + (hmean : ∀ x, (∫ t, V x t ∂μ)=0) (x y : ι → A) (hxy : ∀ i, x i≠y i) : + (∫ c, ∏ ν : ι → Bool, V (vertex ν x y) (c (vertex ν x y)) ∂Measure.pi (fun _ : ι → A => μ))=0 := by + rw [independent_points μ V hV x y hxy] + apply Finset.prod_eq_zero (Finset.mem_univ (fun _ => false)) + exact hmean _ +end MinUncut.CubeRows + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/Addresses.lean b/lean/OAI/Computability/MinUncut/Machines/Addresses.lean new file mode 100644 index 0000000000000000000000000000000000000000..92261814fd43341a4cd96580034482ddc966dc9c --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/Addresses.lean @@ -0,0 +1,760 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.RuntimeModel2 + +namespace OAI + +namespace MinUncutGames.Foundations.PCP.AlphabetTable.Addresses + +open MinUncutGames.Foundations.Hastad +open Enumeration + +abbrev Terms := List (Fin 5 × Nat) + +structure Field (bound : Nat) where + terms : Terms + offset : Fin bound + +def values (n m edge tail head : Nat) : Fin 5 → Nat := ![n, m, edge, tail, head] + +def eval {bound : Nat} (field : Field bound) (inputs : Fin 5 → Nat) : Nat := + Emitter.affineValue field.terms inputs field.offset.val + +def fieldBound (q : Nat) : Nat := + 12 * localCount q + tapeCount q + pairTapeCount q + 1 + +theorem fieldBound_pos (q : Nat) : 0 < fieldBound q := by + unfold fieldBound + omega + +theorem tapeCount_lt_bound (q : Nat) : tapeCount q < fieldBound q := by + unfold fieldBound + omega + +theorem pairTapeCount_lt_bound (q : Nat) : pairTapeCount q < fieldBound q := by + unfold fieldBound + omega + +theorem localCount_lt_bound (q : Nat) : localCount q < fieldBound q := by + unfold fieldBound + omega + +theorem local_add_pair_lt_bound (q : Nat) : localCount q + pairTapeCount q < fieldBound q := by + unfold fieldBound + omega + +theorem twelve_local_lt_bound (q : Nat) : 12 * localCount q < fieldBound q := by + unfold fieldBound + omega + +def zeroOffset (q : Nat) : Fin (fieldBound q) := ⟨0, fieldBound_pos q⟩ + +def eventOffset (q : Nat) (event : AlphabetGraph.LocalEvent (Fin q)) : Fin (fieldBound q) := + ⟨(localEventEquiv q event).val, + (localEventEquiv q event).isLt.trans (localCount_lt_bound q)⟩ + +def rawQueryOffset (q : Nat) : Queries.RawQuery q → Fin (fieldBound q) + | .inl (_, tape) => + ⟨(cubeEquiv q tape).val, (cubeEquiv q tape).isLt.trans (tapeCount_lt_bound q)⟩ + | .inr tape => + ⟨(pairCubeEquiv q tape).val, (pairCubeEquiv q tape).isLt.trans (pairTapeCount_lt_bound q)⟩ + +def reverseOffset (q : Nat) (event : AlphabetGraph.LocalEvent (Fin q)) + (slot : Fin 6) (orientation : Bool) : Fin (fieldBound q) := + ⟨(localEventEquiv q event).val * 12 + slot.val * 2 + bitValue (!orientation), by + have he := (localEventEquiv q event).isLt + have hs := slot.isLt + have hb : bitValue (!orientation) < 2 := by + simpa only [boolEquiv_val] using (boolEquiv (!orientation)).isLt + have hbound := twelve_local_lt_bound q + omega⟩ + +def headerVertices (q : Nat) : Field (fieldBound q) := + ⟨[(0, tapeCount q), (1, localCount q + pairTapeCount q)], zeroOffset q⟩ + +def headerDarts (q : Nat) : Field (fieldBound q) := + ⟨[(1, 12 * localCount q)], zeroOffset q⟩ + +def eventVertexField (q : Nat) (event : AlphabetGraph.LocalEvent (Fin q)) : + Field (fieldBound q) := + ⟨[(2, localCount q)], eventOffset q event⟩ + +def vertexQueryTerms (q : Nat) (side : Bool) : Terms := + [(1, localCount q), (if side then 4 else 3, tapeCount q)] + +def edgeQueryTerms (q : Nat) : Terms := + [(1, localCount q), (0, tapeCount q), (2, pairTapeCount q)] + +def rawQueryTerms (q : Nat) : Queries.RawQuery q → Terms + | .inl (side, _) => vertexQueryTerms q side + | .inr _ => edgeQueryTerms q + +def rawQueryField (q : Nat) (query : Queries.RawQuery q) : Field (fieldBound q) := + ⟨rawQueryTerms q query, rawQueryOffset q query⟩ + +def reverseDartField (q : Nat) (event : AlphabetGraph.LocalEvent (Fin q)) + (slot : Fin 6) (orientation : Bool) : Field (fieldBound q) := + ⟨[(2, 12 * localCount q)], reverseOffset q event slot orientation⟩ + +theorem headerVertices_eval (q n m edge tail head : Nat) : + eval (headerVertices q) (values n m edge tail head) = vertexCount n m q := by + simp [eval, headerVertices, values, zeroOffset, Emitter.affineValue, + vertexCount, eventCount, addressCount, Nat.mul_add, + Nat.mul_comm, Nat.add_comm, Nat.add_assoc] + +theorem headerDarts_eval (q n m edge tail head : Nat) : + eval (headerDarts q) (values n m edge tail head) = dartCount m q := by + simp [eval, headerDarts, values, zeroOffset, Emitter.affineValue, + dartCount, eventCount, Nat.mul_comm, Nat.mul_assoc] + +theorem eventVertexField_eval (n m q : Nat) (edge : Fin m) + (event : AlphabetGraph.LocalEvent (Fin q)) (tail head : Nat) : + eval (eventVertexField q event) (values n m edge.val tail head) = + (vertexEquiv n m q (.inl (edge, event))).val := by + rw [vertexEquiv_event_val, eventEquiv_val] + simp [eval, eventVertexField, eventOffset, values, Emitter.affineValue, Nat.mul_comm] + +theorem rawQueryField_eval (n m q : Nat) (edge : Fin m) (tail head : Fin n) + (query : Queries.RawQuery q) : + eval (rawQueryField q query) (values n m edge.val tail.val head.val) = + (vertexEquiv n m q (.inr (Queries.globalize tail head edge query))).val := by + cases query with + | inl query => + rcases query with ⟨side, tape⟩ + cases side <;> + simp [eval, rawQueryField, rawQueryTerms, vertexQueryTerms, rawQueryOffset, + values, Emitter.affineValue, Queries.globalize, eventCount, + Nat.mul_comm, Nat.add_assoc] + | inr tape => + simp [eval, rawQueryField, rawQueryTerms, edgeQueryTerms, rawQueryOffset, + values, Emitter.affineValue, Queries.globalize, eventCount, + Nat.mul_comm, Nat.add_assoc] + +theorem reverseDartField_eval (n m q : Nat) (edge : Fin m) + (event : AlphabetGraph.LocalEvent (Fin q)) (slot : Fin 6) (orientation : Bool) + (tail head : Nat) : + eval (reverseDartField q event slot orientation) (values n m edge.val tail head) = + (dartEquiv m q (QueryIncidence.reverse (((edge, event), slot), orientation))).val := by + rw [dartEquiv_reverse_val, eventEquiv_val] + simp [eval, reverseDartField, reverseOffset, values, Emitter.affineValue, + Nat.mul_add, Nat.mul_comm, Nat.mul_assoc, + Nat.add_assoc] + +def queryEventTerms (q : Nat) (event : AlphabetGraph.LocalEvent (Fin q)) + (slot : Fin 6) : Terms := + rawQueryTerms q (Queries.query (fun _ _ => false) event slot) + +theorem rawQueryTerms_query (q : Nat) (P : Fin q → Fin q → Bool) + (event : AlphabetGraph.LocalEvent (Fin q)) (slot : Fin 6) : + rawQueryTerms q (Queries.query P event slot) = queryEventTerms q event slot := by + rcases event with ⟨kind, ⟨side, tape⟩, f, g, r₀, r₁, r₂⟩ + by_cases hk₀ : kind = 0 <;> by_cases hk₁ : kind = 1 <;> by_cases hk₂ : kind = 2 <;> + simp only [queryEventTerms, Queries.query, hk₀, hk₁, hk₂, ite_true, ite_false] + all_goals split_ifs <;> rfl + +def queryEventOffset (q : Nat) (event : AlphabetGraph.LocalEvent (Fin q)) + (slot : Fin 6) (P : Fin q → Fin q → Bool) : Fin (fieldBound q) := + rawQueryOffset q (Queries.query P event slot) + +def fieldForQueryEvent (q : Nat) (event : AlphabetGraph.LocalEvent (Fin q)) + (slot : Fin 6) (P : Fin q → Fin q → Bool) : Field (fieldBound q) := + ⟨queryEventTerms q event slot, queryEventOffset q event slot P⟩ + +theorem fieldForQueryEvent_eq_rawQueryField (q : Nat) + (event : AlphabetGraph.LocalEvent (Fin q)) (slot : Fin 6) + (P : Fin q → Fin q → Bool) : + fieldForQueryEvent q event slot P = rawQueryField q (Queries.query P event slot) := by + unfold fieldForQueryEvent queryEventOffset rawQueryField + rw [rawQueryTerms_query] + +theorem fieldForQueryEvent_eval (n m q : Nat) (edge : Fin m) (tail head : Fin n) + (event : AlphabetGraph.LocalEvent (Fin q)) (slot : Fin 6) + (P : Fin q → Fin q → Bool) : + eval (fieldForQueryEvent q event slot P) (values n m edge.val tail.val head.val) = + (vertexEquiv n m q + (.inr (Queries.globalize tail head edge (Queries.query P event slot)))).val := by + rw [fieldForQueryEvent_eq_rawQueryField] + exact rawQueryField_eval n m q edge tail head _ + +theorem fieldForQueryEvent_eval_verifier (n m q : Nat) + (G : ConstraintGraph (Fin n) (Fin m) (Fin q)) (edge : Fin m) + (event : AlphabetGraph.LocalEvent (Fin q)) (slot : Fin 6) : + eval (fieldForQueryEvent q event slot (G.accepts edge)) + (values n m edge.val (G.tail edge).val (G.head edge).val) = + (vertexEquiv n m q (.inr ((AlphabetGraph.verifier G).query (edge, event) slot))).val := by + rw [← Queries.globalize_query G edge event slot] + exact fieldForQueryEvent_eval n m q edge (G.tail edge) (G.head edge) event slot _ + +def dartTailTerms (q : Nat) (event : AlphabetGraph.LocalEvent (Fin q)) + (slot : Fin 6) (orientation : Bool) : Terms := + if orientation then queryEventTerms q event slot else [(2, localCount q)] + +def dartTailOffset (q : Nat) (event : AlphabetGraph.LocalEvent (Fin q)) + (slot : Fin 6) (orientation : Bool) (P : Fin q → Fin q → Bool) : Fin (fieldBound q) := + if orientation then queryEventOffset q event slot P else eventOffset q event + +def fieldForDartTail (q : Nat) (event : AlphabetGraph.LocalEvent (Fin q)) + (slot : Fin 6) (orientation : Bool) (P : Fin q → Fin q → Bool) : Field (fieldBound q) := + ⟨dartTailTerms q event slot orientation, dartTailOffset q event slot orientation P⟩ + +theorem fieldForDartTail_eval (n m q : Nat) (edge : Fin m) (tail head : Fin n) + (event : AlphabetGraph.LocalEvent (Fin q)) (slot : Fin 6) (orientation : Bool) + (P : Fin q → Fin q → Bool) : + eval (fieldForDartTail q event slot orientation P) + (values n m edge.val tail.val head.val) = + (vertexEquiv n m q (if orientation then + .inr (Queries.globalize tail head edge (Queries.query P event slot)) + else .inl (edge, event))).val := by + cases orientation with + | false => exact eventVertexField_eval n m q edge event tail.val head.val + | true => exact fieldForQueryEvent_eval n m q edge tail head event slot P + +def CoefficientsBounded (q : Nat) (terms : Terms) : Prop := + ∀ term ∈ terms, term.2 < fieldBound q + +theorem headerVertices_coefficients (q : Nat) : CoefficientsBounded q (headerVertices q).terms := by + simp only [CoefficientsBounded, headerVertices, List.mem_cons, List.not_mem_nil, or_false] + intro term h + rcases h with rfl | rfl + · exact tapeCount_lt_bound q + · exact local_add_pair_lt_bound q + +theorem headerDarts_coefficients (q : Nat) : CoefficientsBounded q (headerDarts q).terms := by + intro term h + have heq : term = (1, 12 * localCount q) := by simpa [headerDarts] using h + subst term + exact twelve_local_lt_bound q + +theorem eventVertexField_coefficients (q : Nat) (event : AlphabetGraph.LocalEvent (Fin q)) : + CoefficientsBounded q (eventVertexField q event).terms := by + intro term h + have heq : term = (2, localCount q) := by simpa [eventVertexField] using h + subst term + exact localCount_lt_bound q + +theorem rawQueryTerms_coefficients (q : Nat) (query : Queries.RawQuery q) : + CoefficientsBounded q (rawQueryTerms q query) := by + cases query with + | inl query => + rcases query with ⟨side, tape⟩ + intro term h + simp only [rawQueryTerms, vertexQueryTerms, List.mem_cons, List.not_mem_nil, or_false] at h + rcases h with rfl | rfl + · exact localCount_lt_bound q + · exact tapeCount_lt_bound q + | inr tape => + intro term h + simp only [rawQueryTerms, edgeQueryTerms, List.mem_cons, List.not_mem_nil, or_false] at h + rcases h with rfl | rfl | rfl + · exact localCount_lt_bound q + · exact tapeCount_lt_bound q + · exact pairTapeCount_lt_bound q + +theorem queryEventTerms_coefficients (q : Nat) (event : AlphabetGraph.LocalEvent (Fin q)) + (slot : Fin 6) : CoefficientsBounded q (queryEventTerms q event slot) := + rawQueryTerms_coefficients q _ + +theorem reverseDartField_coefficients (q : Nat) (event : AlphabetGraph.LocalEvent (Fin q)) + (slot : Fin 6) (orientation : Bool) : + CoefficientsBounded q (reverseDartField q event slot orientation).terms := by + intro term h + have heq : term = (2, 12 * localCount q) := by simpa [reverseDartField] using h + subst term + exact twelve_local_lt_bound q + +theorem rawQueryTerms_length_le (q : Nat) (query : Queries.RawQuery q) : + (rawQueryTerms q query).length ≤ 3 := by + cases query with + | inl query => rcases query with ⟨side, tape⟩; simp [rawQueryTerms, vertexQueryTerms] + | inr tape => simp [rawQueryTerms, edgeQueryTerms] + +theorem queryEventTerms_length_le (q : Nat) (event : AlphabetGraph.LocalEvent (Fin q)) + (slot : Fin 6) : (queryEventTerms q event slot).length ≤ 3 := + rawQueryTerms_length_le q _ + +theorem dartTailTerms_coefficients (q : Nat) (event : AlphabetGraph.LocalEvent (Fin q)) + (slot : Fin 6) (orientation : Bool) : + CoefficientsBounded q (dartTailTerms q event slot orientation) := by + cases orientation with + | false => exact eventVertexField_coefficients q event + | true => exact queryEventTerms_coefficients q event slot + +theorem dartTailTerms_length_le (q : Nat) (event : AlphabetGraph.LocalEvent (Fin q)) + (slot : Fin 6) (orientation : Bool) : + (dartTailTerms q event slot orientation).length ≤ 3 := by + cases orientation with + | false => simp [dartTailTerms] + | true => exact queryEventTerms_length_le q event slot + +theorem offset_lt {bound : Nat} (field : Field bound) : field.offset.val < bound := + field.offset.isLt + +end MinUncutGames.Foundations.PCP.AlphabetTable.Addresses + +namespace MinUncutGames.Foundations.PCP.AlphabetTable.EmitRows + +open Turing +open MinUncutGames.Foundations.Complexity +open Emitter + +abbrev Context (q : Nat) := Vector Bool (q * q) × Bool +abbrev RowCommand (q : Nat) := Command 5 (Context q) (Addresses.fieldBound q) + +def relationBits (q : Nat) (event : AlphabetGraph.LocalEvent (Fin q)) + (slot : Fin 6) (orientation : Bool) : List (Context q → Bool) := + List.ofFn fun index : Fin 4096 => fun context => + (Relations.relationFromTable context.1 context.2 event slot orientation)[index] + +private theorem vector_list_ofFn {α : Type} {n : Nat} (vector : Vector α n) : + List.ofFn (fun index : Fin n => vector[index]) = vector.toList := by + have equality := congrArg Vector.toList (Vector.ofFn_getElem (xs := vector)) + simpa only [Vector.toList_ofFn, Fin.getElem_fin] using equality + +private theorem bitValues_ofFn {σ : Type} {n : Nat} + (relation : σ → Vector Bool n) (context : σ) : + (List.ofFn (fun index : Fin n => fun state => (relation state)[index])).map + (fun bit => if bit context then 1 else 0) = + (relation context).toList.map GraphTables.bitWord := by + rw [← vector_list_ofFn (relation context)] + simp only [List.map_ofFn] + rfl + +theorem relationBits_values (q : Nat) (event : AlphabetGraph.LocalEvent (Fin q)) + (slot : Fin 6) (orientation : Bool) (context : Context q) : + (relationBits q event slot orientation).map (fun bit => if bit context then 1 else 0) = + GraphTables.relationWords + (Relations.relationFromTable context.1 context.2 event slot orientation) := by + exact bitValues_ofFn (fun state : Context q => + Relations.relationFromTable state.1 state.2 event slot orientation) context + +def rowCommands (q : Nat) (event : AlphabetGraph.LocalEvent (Fin q)) + (slot : Fin 6) (orientation : Bool) : List (RowCommand q) := + affineCommands (Addresses.dartTailTerms q event slot orientation) + (fun context => Addresses.dartTailOffset q event slot orientation + (Relations.oldPredicate context.1)) ++ + affineCommands (Addresses.reverseDartField q event slot orientation).terms + (fun _ => (Addresses.reverseDartField q event slot orientation).offset) ++ + bitCommands (relationBits q event slot orientation) + +def rowContext {q : Nat} (input : GenericGraphTables.Table q) (edge : Fin input.darts) : Context q := + let old := input.rows[edge] + (old.relation, decide (old.tail = input.rows[old.reverseIndex].tail)) + +def rowValues {q : Nat} (input : GenericGraphTables.Table q) + (edge : Fin input.darts) : Fin 5 → Nat := + let old := input.rows[edge] + Addresses.values input.vertices input.darts edge.val old.tail.val + input.rows[old.reverseIndex].tail.val + +private theorem encodedRow {n m : Nat} (row : GraphTables.DartRow n m) : + encodeWords (GraphTables.rowWords row) = + encodeWord row.tail.val ++ (encodeWord row.reverseIndex.val ++ + encodeWords (GraphTables.relationWords row.relation)) := by + simp only [GraphTables.rowWords, List.cons_append, List.nil_append, encodeWords] + +theorem rowCommands_bits {q : Nat} (input : GenericGraphTables.Table q) + (edge : Fin input.darts) (event : AlphabetGraph.LocalEvent (Fin q)) + (slot : Fin 6) (orientation : Bool) : + (rowCommands q event slot orientation).flatMap + (commandBits (rowValues input edge) (rowContext input edge)) = + encodeWords (GraphTables.rowWords + (Table.rowFromDart input (((edge, event), slot), orientation))) := by + rw [rowCommands, List.flatMap_append, List.flatMap_append, + affineCommands_bits, affineCommands_bits, bitCommands_bits, relationBits_values] + have htail := Addresses.fieldForDartTail_eval input.vertices input.darts q edge + input.rows[edge].tail input.rows[input.rows[edge].reverseIndex].tail event slot orientation + (Relations.oldPredicate input.rows[edge].relation) + have hreverse := Addresses.reverseDartField_eval input.vertices input.darts q edge + event slot orientation input.rows[edge].tail.val + input.rows[input.rows[edge].reverseIndex].tail.val + let row := Table.rowFromDart input (((edge, event), slot), orientation) + have tailEq : affineValue (Addresses.dartTailTerms q event slot orientation) + (rowValues input edge) (Addresses.dartTailOffset q event slot orientation + (Relations.oldPredicate (rowContext input edge).1)).val = row.tail.val := htail + have reverseEq : affineValue (Addresses.reverseDartField q event slot orientation).terms + (rowValues input edge) (Addresses.reverseDartField q event slot orientation).offset.val = + row.reverseIndex.val := hreverse + have relationEq : Relations.relationFromTable (rowContext input edge).1 + (rowContext input edge).2 event slot orientation = row.relation := rfl + rw [encodedRow] + have combined := congrArg₂ (fun a b : List Bool => a ++ b) + (congrArg encodeWord tailEq) + (congrArg₂ (fun a b : List Bool => a ++ b) (congrArg encodeWord reverseEq) + (congrArg (fun relation => encodeWords (GraphTables.relationWords relation)) relationEq)) + simpa only [List.append_assoc] using combined + +def blockCommands (q : Nat) : List (RowCommand q) := + (Enumeration.localEvents q).flatMap fun event => + (List.finRange 6).flatMap fun slot => + [false, true].flatMap fun orientation => rowCommands q event slot orientation + +def blockWords {q : Nat} (input : GenericGraphTables.Table q) + (edge : Fin input.darts) : List Nat := + (Enumeration.localEvents q).flatMap fun event => + (List.finRange 6).flatMap fun slot => + [false, true].flatMap fun orientation => + GraphTables.rowWords (Table.rowFromDart input (((edge, event), slot), orientation)) + +theorem tableWords_eq_blocks {q : Nat} + (input : GenericGraphTables.Table q) : + GraphTables.tableWords (Table.build input) = + [Enumeration.vertexCount input.vertices input.darts q, + Enumeration.dartCount input.darts q] ++ + (List.finRange input.darts).flatMap (blockWords input) := by + rw [Table.tableWords_eq_ordered, Enumeration.ordered_dart] + unfold blockWords + simp only [List.flatMap_assoc, List.flatMap_cons, List.flatMap_nil, + List.append_nil] + +def headerCommands (q : Nat) (σ : Type) : List (Command 2 σ (Addresses.fieldBound q)) := + affineCommands [(0, Enumeration.tapeCount q), + (1, Enumeration.localCount q + Enumeration.pairTapeCount q)] + (fun _ => Addresses.zeroOffset q) ++ + affineCommands [(1, 12 * Enumeration.localCount q)] (fun _ => Addresses.zeroOffset q) + +theorem headerCommands_bits {σ : Type} (q n m : Nat) (ambient : σ) : + (headerCommands q σ).flatMap (commandBits ![n, m] ambient) = + encodeWords [Enumeration.vertexCount n m q, Enumeration.dartCount m q] := by + rw [headerCommands, List.flatMap_append, affineCommands_bits, affineCommands_bits] + have vertices : affineValue + [(0, Enumeration.tapeCount q), (1, Enumeration.localCount q + Enumeration.pairTapeCount q)] + ![n, m] (Addresses.zeroOffset q).val = Enumeration.vertexCount n m q := by + exact Addresses.headerVertices_eval q n m 0 0 0 + have darts : affineValue [(1, 12 * Enumeration.localCount q)] ![n, m] + (Addresses.zeroOffset q).val = Enumeration.dartCount m q := by + exact Addresses.headerDarts_eval q n m 0 0 0 + rw [vertices, darts] + simp [encodeWords] + +@[simp] theorem headerCommands_length (q : Nat) (σ : Type) : + (headerCommands q σ).length = 7 := by + simp [headerCommands, affineCommands_length] + +def headerInTime {K Λ σ : Type} [DecidableEq K] (q n m : Nat) + (sources : Fin 2 → K) (scratch output : K) + (sourceScratch : ∀ i, sources i ≠ scratch) + (sourceOutput : ∀ i, sources i ≠ output) (scratchOutput : scratch ≠ output) + (labels : Label (headerCommands q σ).length (Addresses.fieldBound q) → Λ) (exit : Option Λ) + (p : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ label, p (labels label) = statement (listCommands (headerCommands q σ)) + sources scratch output labels exit label) + (base : K → List Bool) (operands : ∀ i, base (sources i) = encodeWord (![n, m] i)) + (scratchEmpty : base scratch = []) (ambient : σ) (N : Nat) (hn : n ≤ N) (hm : m ≤ N) : + StateTransition.EvalsToInTime (TM2.step p) + ⟨some (labels (labelAt (headerCommands q σ).length (Addresses.fieldBound q) 0 .entry)), + ((ambient, ()), none), base⟩ + (some ⟨exit, ((ambient, ()), none), resultTapes output base + (encodeWords [Enumeration.vertexCount n m q, Enumeration.dartCount m q])⟩) + (7 * (3 * (N + 1) + 3) + 1) := by + have bounded : ∀ i : Fin 2, ![n, m] i ≤ N := by + intro i + fin_cases i <;> simp [hn, hm] + have run := planInTime (listCommands (headerCommands q σ)) sources scratch output + sourceScratch sourceOutput scratchOutput labels exit p atLabels ![n, m] base operands + scratchEmpty ambient N bounded + rw [bits_listCommands, headerCommands_bits] at run + simpa only [headerCommands_length] using run + +theorem encodeWords_flatMap {α : Type} (items : List α) (words : α → List Nat) : + encodeWords (items.flatMap words) = items.flatMap (fun item => encodeWords (words item)) := by + induction items with + | nil => rfl + | cons item items ih => simp [encodeWords_append, ih] + +theorem blockCommands_bits {q : Nat} (input : GenericGraphTables.Table q) + (edge : Fin input.darts) : + (blockCommands q).flatMap (commandBits (rowValues input edge) (rowContext input edge)) = + encodeWords (blockWords input edge) := by + simp only [blockCommands, blockWords, List.flatMap_assoc, encodeWords_flatMap, + rowCommands_bits] + +theorem rowCommands_length_le (q : Nat) (event : AlphabetGraph.LocalEvent (Fin q)) + (slot : Fin 6) (orientation : Bool) : (rowCommands q event slot orientation).length ≤ 4104 := by + have htail := Addresses.dartTailTerms_length_le q event slot orientation + simp only [rowCommands, List.length_append, affineCommands_length, + Addresses.reverseDartField, List.length_cons, List.length_nil, + bitCommands, List.length_map, relationBits, List.length_ofFn] + omega + +theorem flatMap_length_le {α β : Type} (items : List α) (f : α → List β) + (bound : Nat) (bounded : ∀ item ∈ items, (f item).length ≤ bound) : + (items.flatMap f).length ≤ items.length * bound := by + induction items with + | nil => simp + | cons item items ih => + have hh := bounded item (by simp) + have ht := ih (fun x hx => bounded x (by simp [hx])) + simp only [List.flatMap_cons, List.length_append, List.length_cons, Nat.succ_mul] + omega + +theorem blockCommands_length_le (q : Nat) : + (blockCommands q).length ≤ Enumeration.localCount q * (6 * (2 * 4104)) := by + unfold blockCommands + apply le_trans (flatMap_length_le _ _ (6 * (2 * 4104)) ?_) (by simp) + intro event _ + apply le_trans (flatMap_length_le _ _ (2 * 4104) ?_) (by simp) + intro slot _ + apply le_trans (flatMap_length_le _ _ 4104 ?_) (by simp) + intro orientation _ + exact rowCommands_length_le q event slot orientation + +def blockInTime {K Λ : Type} [DecidableEq K] {q : Nat} + (input : GenericGraphTables.Table q) (edge : Fin input.darts) + (sources : Fin 5 → K) (scratch output : K) + (sourceScratch : ∀ i, sources i ≠ scratch) + (sourceOutput : ∀ i, sources i ≠ output) (scratchOutput : scratch ≠ output) + (labels : Label (blockCommands q).length (Addresses.fieldBound q) → Λ) (exit : Option Λ) + (p : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State (Context q))) + (atLabels : ∀ label, p (labels label) = statement (listCommands (blockCommands q)) + sources scratch output labels exit label) + (base : K → List Bool) + (operands : ∀ i, base (sources i) = encodeWord (rowValues input edge i)) + (scratchEmpty : base scratch = []) (N : Nat) + (bounded : ∀ i, rowValues input edge i ≤ N) : + StateTransition.EvalsToInTime (TM2.step p) + ⟨some (labels (labelAt (blockCommands q).length (Addresses.fieldBound q) 0 .entry)), + ((rowContext input edge, ()), none), base⟩ + (some ⟨exit, ((rowContext input edge, ()), none), + resultTapes output base (encodeWords (blockWords input edge))⟩) + (Enumeration.localCount q * (6 * (2 * 4104)) * (3 * (N + 1) + 3) + 1) := by + let run := planInTime (listCommands (blockCommands q)) sources scratch output sourceScratch + sourceOutput scratchOutput labels exit p atLabels (rowValues input edge) base operands + scratchEmpty (rowContext input edge) N bounded + have hbits := bits_listCommands (blockCommands q) (rowValues input edge) (rowContext input edge) + rw [blockCommands_bits] at hbits + rw [hbits] at run + exact { toEvalsTo := run.toEvalsTo, steps_le_m := + run.steps_le_m.trans (Nat.add_le_add_right + (Nat.mul_le_mul_right _ (blockCommands_length_le q)) 1) } + +def blockCommandsIn {σ : Type} (q : Nat) (context : σ → Context q) : + List (Command 5 σ (Addresses.fieldBound q)) := + (blockCommands q).map (fun command => command.mapAmbient context) + +theorem blockCommandsIn_bits {σ : Type} {q : Nat} + (input : GenericGraphTables.Table q) (edge : Fin input.darts) + (context : σ → Context q) (ambient : σ) (hcontext : context ambient = rowContext input edge) : + (blockCommandsIn q context).flatMap (commandBits (rowValues input edge) ambient) = + encodeWords (blockWords input edge) := by + simp only [blockCommandsIn, List.flatMap_map, commandBits_mapAmbient] + rw [hcontext] + exact blockCommands_bits input edge + +def blockInTimeAmbient {K Λ σ : Type} [DecidableEq K] {q : Nat} + (input : GenericGraphTables.Table q) (edge : Fin input.darts) + (context : σ → Context q) (ambient : σ) (hcontext : context ambient = rowContext input edge) + (sources : Fin 5 → K) (scratch output : K) + (sourceScratch : ∀ i, sources i ≠ scratch) + (sourceOutput : ∀ i, sources i ≠ output) (scratchOutput : scratch ≠ output) + (labels : Label (blockCommandsIn q context).length (Addresses.fieldBound q) → Λ) + (exit : Option Λ) (p : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ label, p (labels label) = statement (listCommands (blockCommandsIn q context)) + sources scratch output labels exit label) + (base : K → List Bool) + (operands : ∀ i, base (sources i) = encodeWord (rowValues input edge i)) + (scratchEmpty : base scratch = []) (N : Nat) + (bounded : ∀ i, rowValues input edge i ≤ N) : + StateTransition.EvalsToInTime (TM2.step p) + ⟨some (labels (labelAt (blockCommandsIn q context).length (Addresses.fieldBound q) 0 .entry)), + ((ambient, ()), none), base⟩ + (some ⟨exit, ((ambient, ()), none), + resultTapes output base (encodeWords (blockWords input edge))⟩) + (Enumeration.localCount q * (6 * (2 * 4104)) * (3 * (N + 1) + 3) + 1) := by + have run := planInTime (listCommands (blockCommandsIn q context)) sources scratch output + sourceScratch sourceOutput scratchOutput labels exit p atLabels (rowValues input edge) + base operands scratchEmpty ambient N bounded + rw [bits_listCommands, blockCommandsIn_bits input edge context ambient hcontext] at run + have lengthBound : (blockCommandsIn q context).length ≤ + Enumeration.localCount q * (6 * (2 * 4104)) := by + simpa only [blockCommandsIn, List.length_map] using blockCommands_length_le q + refine { toEvalsTo := run.toEvalsTo, steps_le_m := ?_ } + exact run.steps_le_m.trans (Nat.add_le_add_right (Nat.mul_le_mul_right _ lengthBound) 1) + +end MinUncutGames.Foundations.PCP.AlphabetTable.EmitRows + +namespace MinUncutGames.Foundations.PCP.AlphabetTable.Cleanup + +open Turing +open Complexity +open scoped BigOperators + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool + +def finish (initial : σ) (exit : Option Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) := + .load (fun _ => (initial, none)) + (match exit with | none => .halt | some label => .goto fun _ => label) + +def instruction {n : Nat} (selected : Fin n → K) (labels : Fin (n + 1) → Λ) + (initial : σ) (exit : Option Λ) (phase : Fin (n + 1)) : + TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) := + if h : phase.val < n then + MachineDrain.drain (selected ⟨phase.val, h⟩) (labels phase) + (some (labels ⟨phase.val + 1, Nat.succ_lt_succ h⟩)) + else finish initial exit + +omit [DecidableEq K] in +@[simp] theorem instruction_drain {n : Nat} (selected : Fin n → K) + (labels : Fin (n + 1) → Λ) (initial : σ) (exit : Option Λ) (i : Fin n) : + instruction selected labels initial exit i.castSucc = + MachineDrain.drain (selected i) (labels i.castSucc) (some (labels i.succ)) := by + simp [instruction, i.isLt] + rfl + +omit [DecidableEq K] in +@[simp] theorem instruction_finish {n : Nat} (selected : Fin n → K) + (labels : Fin (n + 1) → Λ) (initial : σ) (exit : Option Λ) : + instruction selected labels initial exit (Fin.last n) = finish initial exit := by + simp [instruction] + +def clearTapes : {n : Nat} → (Fin n → K) → (K → List Bool) → K → List Bool + | 0, _, base => base + | n + 1, selected, base => + clearTapes (fun i : Fin n => selected i.succ) (Function.update base (selected 0) []) + +def actualCost : {n : Nat} → (Fin n → K) → (K → List Bool) → Nat + | 0, _, _ => 1 + | n + 1, selected, base => + actualCost (fun i : Fin n => selected i.succ) (Function.update base (selected 0) []) + + ((base (selected 0)).length + 1) + +theorem clearTapes_apply {n : Nat} (selected : Fin n → K) (base : K → List Bool) (k : K) : + clearTapes selected base k = if ∃ i, selected i = k then [] else base k := by + induction n generalizing base with + | zero => simp [clearTapes] + | succ n ih => + rw [clearTapes, ih] + by_cases first : selected 0 = k + · subst k + simp [Function.update] + · have notFirst : k ≠ selected 0 := Ne.symm first + by_cases later : ∃ i : Fin n, selected i.succ = k <;> + simp [Fin.exists_fin_succ, first, later, Function.update, notFirst] + +@[simp] theorem clearTapes_selected {n : Nat} (selected : Fin n → K) + (base : K → List Bool) (i : Fin n) : clearTapes selected base (selected i) = [] := by + rw [clearTapes_apply, ite_eq_left ⟨i, rfl⟩] + +theorem clearTapes_unselected {n : Nat} (selected : Fin n → K) + (base : K → List Bool) (k : K) (notSelected : ∀ i, selected i ≠ k) : + clearTapes selected base k = base k := by + rw [clearTapes_apply] + simp [notSelected] + +theorem actualCost_le {n : Nat} (selected : Fin n → K) (base : K → List Bool) : + actualCost selected base ≤ (∑ i, (base (selected i)).length) + n + 1 := by + induction n generalizing base with + | zero => simp [actualCost] + | succ n ih => + have tailBound := ih (fun i : Fin n => selected i.succ) + (Function.update base (selected 0) []) + have sumBound : + (∑ i : Fin n, ((Function.update base (selected 0) []) (selected i.succ)).length) ≤ + ∑ i : Fin n, (base (selected i.succ)).length := by + apply Finset.sum_le_sum + intro i _ + by_cases h : selected i.succ = selected 0 <;> simp [h] + rw [actualCost, Fin.sum_univ_succ] + omega + +theorem cleanupTrace {n : Nat} (selected : Fin n → K) (labels : Fin (n + 1) → Λ) + (initial : σ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atDrain : ∀ i : Fin n, program (labels i.castSucc) = + MachineDrain.drain (selected i) (labels i.castSucc) (some (labels i.succ))) + (atFinish : program (labels (Fin.last n)) = finish initial exit) + (base : K → List Bool) (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[actualCost selected base] + (some ⟨some (labels 0), (ambient, register), base⟩) = + some ⟨exit, (initial, none), clearTapes selected base⟩ := by + induction n generalizing base ambient register with + | zero => + change some (TM2.stepAux (program (labels 0)) (ambient, register) base) = _ + rw [show program (labels 0) = finish initial exit from atFinish] + cases exit <;> rfl + | succ n ih => + rw [actualCost, Function.iterate_add_apply] + have first := MachineDrain.drainTrace (selected 0) (labels (0 : Fin (n + 1)).castSucc) + (some (labels (0 : Fin (n + 1)).succ)) program (atDrain 0) + base (base (selected 0)) ambient register + simp only [Function.update_eq_self, Fin.castSucc_zero] at first + rw [first] + exact ih (fun i : Fin n => selected i.succ) (fun i => labels i.succ) + (fun i => atDrain i.succ) atFinish (Function.update base (selected 0) []) ambient none + +def cleanupInTime {n : Nat} (selected : Fin n → K) (labels : Fin (n + 1) → Λ) + (initial : σ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atDrain : ∀ i : Fin n, program (labels i.castSucc) = + MachineDrain.drain (selected i) (labels i.castSucc) (some (labels i.succ))) + (atFinish : program (labels (Fin.last n)) = finish initial exit) + (base : K → List Bool) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels 0), (ambient, register), base⟩ + (some ⟨exit, (initial, none), clearTapes selected base⟩) + ((∑ i, (base (selected i)).length) + n + 1) where + steps := actualCost selected base + evals_in_steps := cleanupTrace selected labels initial exit program atDrain atFinish + base ambient register + steps_le_m := actualCost_le selected base + +def program {n : Nat} (selected : Fin n → K) (initial : σ) : + Fin (n + 1) → TM2.Stmt (Alphabet (K := K)) (Fin (n + 1)) (σ × Option Bool) := + instruction selected id initial none + +def machine [Fintype K] [Fintype σ] {n : Nat} (selected : Fin n → K) + (input output : K) (initial : σ) : FinTM2 where + K := K + k₀ := input + k₁ := output + Γ := Alphabet + Λ := Fin (n + 1) + main := 0 + σ := σ × Option Bool + initialState := (initial, none) + m := program selected initial + +def machineInTime [Fintype K] [Fintype σ] {n : Nat} (selected : Fin n → K) + (input output : K) (initial : σ) (base : K → List Bool) + (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (machine selected input output initial).step + ⟨some (0 : Fin (n + 1)), (ambient, register), base⟩ + (some ⟨none, (initial, none), clearTapes selected base⟩) + ((∑ i, (base (selected i)).length) + n + 1) := + cleanupInTime selected id initial none (program selected initial) + (fun i => instruction_drain selected id initial none i) + (instruction_finish selected id initial none) base ambient register + +theorem clearTapes_outputOnly {n : Nat} (selected : Fin n → K) + (output : K) (base : K → List Bool) + (excludesOutput : ∀ i, selected i ≠ output) + (coversOther : ∀ k, k ≠ output → ∃ i, selected i = k) : + clearTapes selected base = fun k => if k = output then base output else [] := by + funext k + by_cases h : k = output + · subst k + simp [clearTapes_unselected selected base output excludesOutput] + · rw [clearTapes_apply] + simp [h, coversOther k h] + +def machineHaltInTime [Fintype K] [Fintype σ] {n : Nat} (selected : Fin n → K) + (input output : K) (initial : σ) (base : K → List Bool) + (ambient : σ) (register : Option Bool) + (excludesOutput : ∀ i, selected i ≠ output) + (coversOther : ∀ k, k ≠ output → ∃ i, selected i = k) : + StateTransition.EvalsToInTime (machine selected input output initial).step + ⟨some (0 : Fin (n + 1)), (ambient, register), base⟩ + (some (haltList (machine selected input output initial) (base output))) + ((∑ i, (base (selected i)).length) + n + 1) := by + have tapeEq := clearTapes_outputOnly selected output base excludesOutput coversOther + have haltEq : (⟨none, (initial, none), clearTapes selected base⟩ : + (machine selected input output initial).Cfg) = + haltList (machine selected input output initial) (base output) := by + congr 1 + rw [← haltEq] + exact machineInTime selected input output initial base ambient register + +end MinUncutGames.Foundations.PCP.AlphabetTable.Cleanup + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/Alphabet.lean b/lean/OAI/Computability/MinUncut/Machines/Alphabet.lean new file mode 100644 index 0000000000000000000000000000000000000000..d30b29ba7a444a696a035394be59970c493b27d5 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/Alphabet.lean @@ -0,0 +1,1033 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachinePaddedExpanderFamilyBounds +import OAI.Computability.MinUncut.Machines.MachineCloudSelect +import OAI.Computability.MinUncut.PCP.PreprocessingInternalRows + +namespace OAI + +section +namespace MinUncutGames.Foundations.Complexity.MachineRegularInternalRow + +open Turing MachineComposition +open PCP +open Reduction.MachineSubstitution (pushWord stepAux_pushWord) + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool + +def equalityBits : List Bool := + encodeWords (GraphTables.relationWords PreprocessingInternalRows.equalityRelation) + +theorem equalityBits_length_le : equalityBits.length ≤ 8192 := + GraphTables.relationBits_length_le _ + +def emittedBits (q x z r : Nat) : List Bool := + encodeWord x ++ encodeWord ((q + 1) * z + r) ++ equalityBits + +theorem emittedBits_length (q x z r : Nat) : + (emittedBits q x z r).length = x + ((q + 1) * z + r) + equalityBits.length + 2 := by + simp only [emittedBits, List.length_append, encodeWord_length] + omega + +theorem emittedBits_eq_row (t : GraphTables.Table) (padding : Fin t.vertices → Nat) + {q : Nat} (tables : ∀ v, ExpanderTables.Table + (PreprocessingCloudIndex.cloudSize t v + padding v) q) + (v : Fin t.vertices) (x : PreprocessingCloudIndex.PaddedCloud t padding v) (p : Fin q) : + emittedBits q (PreprocessingRegularTables.vertexOrder t padding x.val).val + (PreprocessingInternalRows.selectedIndex t padding v + (PreprocessingInternalRows.localStep t padding tables v x p).1) + (PreprocessingInternalRows.localStep t padding tables v x p).2.val = + encodeWords (GraphTables.rowWords + (PreprocessingInternalRows.row t padding tables v x p)) := by + rw [MachineTableRows.rowBits_eq, PreprocessingInternalRows.row_tail, + PreprocessingInternalRows.row_reverse_selectedIndex, PreprocessingInternalRows.row_relation] + rfl + +theorem selected_rotation {n q : Nat} (table : ExpanderTables.Table n q) + (i : Fin n) (p : Fin q) : + (ExpanderTableWords.rotationWords table)[q * i.val + p.val]? = + some (q * (ExpanderTables.lookup table (i, p)).1.val + + (ExpanderTables.lookup table (i, p)).2.val) := by + simpa only [Nat.add_comm] using ExpanderTableWords.rotationWords_row_order table (i, p) + +theorem selected_rotation_div {n q : Nat} (positive : 0 < q) + (table : ExpanderTables.Table n q) (i : Fin n) (p : Fin q) : + (q * (ExpanderTables.lookup table (i, p)).1.val + + (ExpanderTables.lookup table (i, p)).2.val) / q = + (ExpanderTables.lookup table (i, p)).1.val := by + rw [Nat.add_comm, Nat.add_mul_div_left _ _ positive, + Nat.div_eq_of_lt (ExpanderTables.lookup table (i, p)).2.isLt, Nat.zero_add] + +theorem selected_rotation_mod {n q : Nat} (_positive : 0 < q) + (table : ExpanderTables.Table n q) (i : Fin n) (p : Fin q) : + (q * (ExpanderTables.lookup table (i, p)).1.val + + (ExpanderTables.lookup table (i, p)).2.val) % q = + (ExpanderTables.lookup table (i, p)).2.val := by + rw [Nat.mul_add_mod_self_left, + Nat.mod_eq_of_lt (ExpanderTables.lookup table (i, p)).2.isLt] + +theorem rotationLookupTrace {n q : Nat} (table : ExpanderTables.Table n q) + (i : Fin n) (p : Fin q) (source : K) (tape : Fin 5 → K) + (distinct : Function.Injective tape) (outside : ∀ a, source ≠ tape a) + (labels : MachineAffineLookup.Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (code : ∀ l, program (labels l) = + MachineAffineLookup.instruction source tape q p.val labels exit l) + (base : K → List Bool) + (tableWord : base (tape 0) = encodeWords (ExpanderTableWords.rotationWords table)) + (scratchEmpty : base (tape 4) = []) (suffix : List Bool) + (sourceWord : base source = encodeWord i.val ++ suffix) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[MachineAffineLookup.steps + (ExpanderTableWords.rotationWords table) i.val q p.val] + (some ⟨some (labels .seed), (ambient, register), base⟩) = + some ⟨exit, (ambient, none), MachineAffineLookup.finalTapes tape base + (ExpanderTableWords.rotationWords table) (q * i.val + p.val) + (q * (ExpanderTables.lookup table (i, p)).1.val + + (ExpanderTables.lookup table (i, p)).2.val)⟩ := + MachineAffineLookup.affineLookupTrace source tape distinct outside q p.val labels exit + program code base _ tableWord scratchEmpty i.val suffix sourceWord _ + (selected_rotation table i p) ambient register + +inductive FinishLabel + | seedReturn | copyReturn | restoreReturn | affine | restoreTarget | equality + | row (stage : MachineTableRows.Label) + | clearReverse | clearEquality + deriving DecidableEq, Fintype + +def finishFields (tape : Fin 8 → K) : Fin 3 → K := fun i => + if i = 0 then tape 0 else if i = 1 then tape 4 else tape 5 + +omit [DecidableEq K] in +@[simp] theorem finishFields_zero (tape : Fin 8 → K) : finishFields tape 0 = tape 0 := rfl +omit [DecidableEq K] in +@[simp] theorem finishFields_one (tape : Fin 8 → K) : finishFields tape 1 = tape 4 := rfl +omit [DecidableEq K] in +@[simp] theorem finishFields_two (tape : Fin 8 → K) : finishFields tape 2 = tape 5 := rfl + +def finishInstruction (q : Nat) (tape : Fin 8 → K) (labels : FinishLabel → Λ) + (exit : Option Λ) : FinishLabel → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) + | .seedReturn => MachineUnaryAffineAt.seed (tape 4) 0 (labels .copyReturn) + | .copyReturn => MachineUnaryAffineAt.scan (tape 2) (tape 3) (tape 4) 1 + (labels .copyReturn) (labels .restoreReturn) + | .restoreReturn => Reduction.MachineTransfer.loopAt (tape 3) (tape 2) id false + (labels .restoreReturn) (some (labels .affine)) + | .affine => MachineUnaryAffineAt.scan (tape 1) (tape 3) (tape 4) (q + 1) + (labels .affine) (labels .restoreTarget) + | .restoreTarget => Reduction.MachineTransfer.loopAt (tape 3) (tape 1) id false + (labels .restoreTarget) (some (labels .equality)) + | .equality => pushWord (tape 5) equalityBits.reverse + (.goto fun _ => labels (.row .relationRead)) + | .row stage => MachineTableRows.routine (finishFields tape) (tape 6) (tape 7) (tape 3) + (fun l => labels (.row l)) (some (labels .clearReverse)) stage + | .clearReverse => MachineDrain.drain (tape 4) (labels .clearReverse) + (some (labels .clearEquality)) + | .clearEquality => MachineDrain.drain (tape 5) (labels .clearEquality) exit + +def finishSteps (q x z r outputLength : Nat) : Nat := + (2 * (r + 1) + 1) + 2 * (z + 1) + 1 + + (4 * (x + ((q + 1) * z + r) + equalityBits.length + 2) + 2 * outputLength + 9) + + (((q + 1) * z + r) + 2) + (equalityBits.length + 1) + +theorem finishSteps_le (q x z r outputLength : Nat) : + finishSteps q x z r outputLength ≤ + (5 * q + 7) * z + 7 * r + 4 * x + 2 * outputLength + 40986 := by + have h := equalityBits_length_le + unfold finishSteps + nlinarith + +theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +theorem finishTrace (q : Nat) (tape : Fin 8 → K) (distinct : Function.Injective tape) + (labels : FinishLabel → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (code : ∀ l, program (labels l) = finishInstruction q tape labels exit l) + (base : K → List Bool) (x z r : Nat) + (tailWord : base (tape 0) = encodeWord x) + (targetWord : base (tape 1) = encodeWord z) + (returnWord : base (tape 2) = encodeWord r) + (scratchEmpty : base (tape 3) = []) (reverseEmpty : base (tape 4) = []) + (equalityEmpty : base (tape 5) = []) (rowEmpty : base (tape 6) = []) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[finishSteps q x z r (base (tape 7)).length] + (some ⟨some (labels .seedReturn), (ambient, register), base⟩) = + some ⟨exit, (ambient, none), + Function.update base (tape 7) (base (tape 7) ++ emittedBits q x z r)⟩ := by + have hd (i j : Fin 8) (h : i ≠ j) : tape i ≠ tape j := fun e => h (distinct e) + let w := (q + 1) * z + r + let copied := Function.update base (tape 4) (encodeWord r) + let computed := Function.update base (tape 4) (encodeWord w) + let initialized := Function.update computed (tape 5) equalityBits + let appended := Function.update initialized (tape 7) + (base (tape 7) ++ emittedBits q x z r) + let drained := Function.update appended (tape 4) [] + have copyRun : (advance (TM2.step program))^[2 * (r + 1) + 1] + (some ⟨some (labels .seedReturn), (ambient, register), base⟩) = + some ⟨some (labels .affine), (ambient, none), copied⟩ := by + simpa only [copied, Nat.one_mul, Nat.add_zero, reverseEmpty, List.append_nil] using + MachineUnaryAffineAt.seededAffineTrace (tape 2) (tape 3) (tape 4) + (hd 2 3 (by decide)) (hd 2 4 (by decide)) (hd 3 4 (by decide)) 1 0 + (labels .seedReturn) (labels .copyReturn) (labels .restoreReturn) + (some (labels .affine)) program (code .seedReturn) (code .copyReturn) + (code .restoreReturn) base r [] (by simpa using returnWord) scratchEmpty ambient register + have affineFrame (u : Nat) : + MachineUnaryAffineAt.tapes (tape 1) (tape 3) (tape 4) base + (encodeWord z ++ []) [] (encodeWord u ++ []) = + Function.update base (tape 4) (encodeWord u) := by + simp only [List.append_nil] + rw [← targetWord, ← scratchEmpty] + simp only [MachineUnaryAffineAt.tapes, MachineCopy.forkTapes, Function.update_eq_self] + have affineRun : (advance (TM2.step program))^[2 * (z + 1)] + (some ⟨some (labels .affine), (ambient, none), copied⟩) = + some ⟨some (labels .equality), (ambient, none), computed⟩ := by + simpa only [affineFrame, copied, computed, w] using + MachineUnaryAffineAt.affineTrace (tape 1) (tape 3) (tape 4) + (hd 1 3 (by decide)) (hd 1 4 (by decide)) (hd 3 4 (by decide)) (q + 1) + (labels .affine) (labels .restoreTarget) (some (labels .equality)) program + (code .affine) (code .restoreTarget) base z r [] [] ambient none + have initRun : (advance (TM2.step program))^[1] + (some ⟨some (labels .equality), (ambient, none), computed⟩) = + some ⟨some (labels (.row .relationRead)), (ambient, none), initialized⟩ := by + change some (TM2.stepAux (program (labels .equality)) _ _) = _ + rw [code] + simp [finishInstruction, stepAux_pushWord, TM2.stepAux, computed, initialized, + hd 5 4 (by decide), equalityEmpty] + have hfields : ∀ i, finishFields tape i ≠ tape 6 ∧ finishFields tape i ≠ tape 3 := by + intro i + fin_cases i + all_goals exact ⟨hd _ _ (by decide), hd _ _ (by decide)⟩ + have hbits : MachineTableRows.fieldBits (finishFields tape) initialized = + emittedBits q x z r := by + simp [MachineTableRows.fieldBits, initialized, computed, finishFields, tailWord, + hd 0 4 (by decide), hd 0 5 (by decide), hd 4 5 (by decide), emittedBits, w] + have hsize : MachineTableRows.fieldSize (finishFields tape) initialized = + x + w + equalityBits.length + 2 := by + rw [← MachineTableRows.fieldBits_length, hbits, emittedBits_length] + have hout : initialized (tape 7) = base (tape 7) := by + simp [initialized, computed, hd 7 4 (by decide), hd 7 5 (by decide)] + have rowRun : (advance (TM2.step program))^[ + 4 * (x + w + equalityBits.length + 2) + 2 * (base (tape 7)).length + 9] + (some ⟨some (labels (.row .relationRead)), (ambient, none), initialized⟩) = + some ⟨some (labels .clearReverse), (ambient, none), appended⟩ := by + simpa only [hbits, hsize, hout, appended] using + MachineTableRows.appendTrace (finishFields tape) (tape 6) (tape 7) (tape 3) + hfields (hd 6 7 (by decide)) (hd 6 3 (by decide)) (hd 7 3 (by decide)) + (fun l => labels (.row l)) (some (labels .clearReverse)) program + (fun l => code (.row l)) initialized + (by simp [initialized, computed, hd 6 4 (by decide), hd 6 5 (by decide), rowEmpty]) + (by simp [initialized, computed, hd 3 4 (by decide), hd 3 5 (by decide), scratchEmpty]) + ambient none + have hreverse : appended (tape 4) = encodeWord w := by + simp [appended, initialized, computed, hd 4 7 (by decide), hd 4 5 (by decide)] + have reverseRun : (advance (TM2.step program))^[w + 2] + (some ⟨some (labels .clearReverse), (ambient, none), appended⟩) = + some ⟨some (labels .clearEquality), (ambient, none), drained⟩ := by + have h := MachineDrain.drainTrace (tape 4) (labels .clearReverse) + (some (labels .clearEquality)) program (code .clearReverse) + appended (appended (tape 4)) ambient none + rw [Function.update_eq_self, hreverse, encodeWord_length] at h + exact h + have hequality : drained (tape 5) = equalityBits := by + simp [drained, appended, initialized, hd 5 4 (by decide), hd 5 7 (by decide)] + have finalFrame : Function.update drained (tape 5) [] = + Function.update base (tape 7) (base (tape 7) ++ emittedBits q x z r) := by + funext k + by_cases h4 : k = tape 4 + · subst k + simp [drained, hd 4 5 (by decide), hd 4 7 (by decide), reverseEmpty] + · by_cases h5 : k = tape 5 + · subst k + simp [hd 5 7 (by decide), equalityEmpty] + · by_cases h7 : k = tape 7 + · subst k + simp [drained, appended, h4, h5] + · simp [drained, appended, initialized, computed, h4, h5, h7] + have equalityRun : (advance (TM2.step program))^[equalityBits.length + 1] + (some ⟨some (labels .clearEquality), (ambient, none), drained⟩) = + some ⟨exit, (ambient, none), + Function.update base (tape 7) (base (tape 7) ++ emittedBits q x z r)⟩ := by + have h := MachineDrain.drainTrace (tape 5) (labels .clearEquality) exit program + (code .clearEquality) drained (drained (tape 5)) ambient none + rw [Function.update_eq_self, hequality, finalFrame] at h + exact h + exact joinTrace (joinTrace (joinTrace (joinTrace (joinTrace + copyRun affineRun) initRun) rowRun) reverseRun) equalityRun + +inductive RotorLabel (q : Nat) + | lookup (stage : MachineAffineLookup.Label) + | initialize | divide | emit (r : Fin q) + deriving DecidableEq, Fintype + +def rotorLookupTapes (tape : Fin 8 → K) (j : Fin 5) : K := + tape ⟨j.val + 1, by omega⟩ + +omit [DecidableEq K] in +theorem rotorLookupTapes_injective (tape : Fin 8 → K) (h : Function.Injective tape) : + Function.Injective (rotorLookupTapes tape) := by + intro i j hij + have hv := congrArg Fin.val (h hij) + apply Fin.ext + simpa only [Fin.val_mk, Nat.add_left_inj] using hv + +omit [DecidableEq K] in +theorem rotorLookupTapes_outside (tape : Fin 8 → K) (h : Function.Injective tape) + (i : Fin 5) : tape 0 ≠ rotorLookupTapes tape i := by + intro he + have hv := congrArg Fin.val (h he) + change 0 = i.val + 1 at hv + omega + +def rotorInstruction (q : Nat) (positive : 0 < q) (p : Fin q) + (tape : Fin 8 → K) (labels : RotorLabel q → Λ) (exit : Option Λ) : + RotorLabel q → TM2.Stmt (Alphabet (K := K)) Λ (MachineFixedDivMod.State σ q) + | .lookup stage => MachineAffineLookup.instruction (tape 0) (rotorLookupTapes tape) + q p.val (fun l => labels (.lookup l)) (some (labels .initialize)) stage + | .initialize => .push (tape 6) (fun _ => false) + (.push (tape 7) (fun _ => false) (.goto fun _ => labels .divide)) + | .divide => MachineFixedDivMod.scanLoop q positive (tape 4) (tape 6) + (labels .divide) (fun r => labels (.emit r)) + | .emit r => MachineFixedDivMod.emitter q positive (tape 7) exit r + +def rotorFinalTapes {n q : Nat} (table : ExpanderTables.Table n q) (i : Fin n) (p : Fin q) + (tape : Fin 8 → K) (base : K → List Bool) : K → List Bool := + MachineFixedDivMod.unaryTapes (tape 4) (tape 6) (tape 7) + (MachineAffineLookup.finalTapes (rotorLookupTapes tape) base + (ExpanderTableWords.rotationWords table) (q * i.val + p.val) + (q * (ExpanderTables.lookup table (i, p)).1.val + + (ExpanderTables.lookup table (i, p)).2.val)) + 0 (ExpanderTables.lookup table (i, p)).1.val + (ExpanderTables.lookup table (i, p)).2.val [] [] [] + +def rotorSteps {n q : Nat} (table : ExpanderTables.Table n q) (i : Fin n) (p : Fin q) : Nat := + MachineAffineLookup.steps (ExpanderTableWords.rotationWords table) i.val q p.val + + 1 + (q * (ExpanderTables.lookup table (i, p)).1.val + + (ExpanderTables.lookup table (i, p)).2.val + 2) + +theorem rotorTrace {n q : Nat} (positive : 0 < q) (table : ExpanderTables.Table n q) + (i : Fin n) (p : Fin q) (tape : Fin 8 → K) (distinct : Function.Injective tape) + (labels : RotorLabel q → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (MachineFixedDivMod.State σ q)) + (code : ∀ l, program (labels l) = rotorInstruction q positive p tape labels exit l) + (base : K → List Bool) + (sourceWord : base (tape 0) = encodeWord i.val) + (tableWord : base (tape 1) = encodeWords (ExpanderTableWords.rotationWords table)) + (flatEmpty : base (tape 4) = []) (scratchEmpty : base (tape 5) = []) + (localEmpty : base (tape 6) = []) (returnEmpty : base (tape 7) = []) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[rotorSteps table i p] + (some ⟨some (labels (.lookup .seed)), + ((ambient, MachineFixedDivMod.residue q positive 0), register), base⟩) = + some ⟨exit, ((ambient, MachineFixedDivMod.residue q positive 0), none), + rotorFinalTapes table i p tape base⟩ := by + have hd (a b : Fin 8) (h : a ≠ b) : tape a ≠ tape b := fun e => h (distinct e) + let a := q * (ExpanderTables.lookup table (i, p)).1.val + + (ExpanderTables.lookup table (i, p)).2.val + let looked := MachineAffineLookup.finalTapes (rotorLookupTapes tape) base + (ExpanderTableWords.rotationWords table) (q * i.val + p.val) a + let initialized := Function.update (Function.update looked (tape 6) (encodeWord 0)) + (tape 7) (encodeWord 0) + have lookupRun : (advance (TM2.step program))^[MachineAffineLookup.steps + (ExpanderTableWords.rotationWords table) i.val q p.val] + (some ⟨some (labels (.lookup .seed)), + ((ambient, MachineFixedDivMod.residue q positive 0), register), base⟩) = + some ⟨some (labels .initialize), + ((ambient, MachineFixedDivMod.residue q positive 0), none), looked⟩ := by + exact rotationLookupTrace table i p (tape 0) (rotorLookupTapes tape) + (rotorLookupTapes_injective tape distinct) (rotorLookupTapes_outside tape distinct) + (fun l => labels (.lookup l)) (some (labels .initialize)) program + (fun l => code (.lookup l)) base tableWord scratchEmpty [] + (by simpa using sourceWord) (ambient, MachineFixedDivMod.residue q positive 0) register + have lookedOther (k : Fin 8) (h2 : k ≠ 2) (h3 : k ≠ 3) (h4 : k ≠ 4) : + looked (tape k) = base (tape k) := by + exact MachineAffineLookup.finalTapes_other (rotorLookupTapes tape) base + (ExpanderTableWords.rotationWords table) (q * i.val + p.val) a (tape k) + (hd k 2 h2) (hd k 3 h3) (hd k 4 h4) + have lookedFlat : looked (tape 4) = encodeWord a := by + change MachineAffineLookup.finalTapes (rotorLookupTapes tape) base + (ExpanderTableWords.rotationWords table) (q * i.val + p.val) a + (rotorLookupTapes tape 3) = _ + rw [MachineAffineLookup.finalTapes_output] + change encodeWord a ++ base (tape 4) = _ + rw [flatEmpty, List.append_nil] + have initRun : (advance (TM2.step program))^[1] + (some ⟨some (labels .initialize), + ((ambient, MachineFixedDivMod.residue q positive 0), none), looked⟩) = + some ⟨some (labels .divide), + ((ambient, MachineFixedDivMod.residue q positive 0), none), initialized⟩ := by + change some (TM2.stepAux (program (labels .initialize)) _ _) = _ + rw [code] + simp [rotorInstruction, TM2.stepAux, initialized, encodeWord, + lookedOther 6 (by decide) (by decide) (by decide), + lookedOther 7 (by decide) (by decide) (by decide), + hd 7 6 (by decide), localEmpty, returnEmpty] + have initialFrame : MachineFixedDivMod.unaryTapes (tape 4) (tape 6) (tape 7) + looked a 0 0 [] [] [] = initialized := by + simp only [MachineFixedDivMod.unaryTapes, MachineFixedDivMod.tapes, + MachineCopy.forkTapes, List.append_nil, ← lookedFlat, Function.update_eq_self, + initialized] + have finalFrame : MachineFixedDivMod.unaryTapes (tape 4) (tape 6) (tape 7) + looked 0 (a / q) (a % q) [] [] [] = rotorFinalTapes table i p tape base := by + dsimp only [a] + rw [selected_rotation_div positive, selected_rotation_mod positive] + rfl + have divideRun : (advance (TM2.step program))^[a + 2] + (some ⟨some (labels .divide), + ((ambient, MachineFixedDivMod.residue q positive 0), none), initialized⟩) = + some ⟨exit, ((ambient, MachineFixedDivMod.residue q positive 0), none), + rotorFinalTapes table i p tape base⟩ := by + simpa only [initialFrame, finalFrame] using + MachineFixedDivMod.divModTrace q positive (tape 4) (tape 6) (tape 7) + (hd 4 6 (by decide)) (hd 4 7 (by decide)) (hd 6 7 (by decide)) + (labels .divide) (fun r => labels (.emit r)) exit program (code .divide) + (fun r => code (.emit r)) looked a [] [] [] ambient none + exact joinTrace (joinTrace lookupRun initRun) divideRun + +theorem rotorSteps_le {n q : Nat} (table : ExpanderTables.Table n q) (i : Fin n) (p : Fin q) : + rotorSteps table i p ≤ 2 * i.val + + 5 * (encodeWords (ExpanderTableWords.rotationWords table)).length + n * q + 8 := by + have hl := MachineAffineLookup.steps_le (ExpanderTableWords.rotationWords table) + i.val q p.val _ (selected_rotation table i p) + have hb := (ExpanderTables.rowIndex n q (ExpanderTables.lookup table (i, p))).isLt + rw [ExpanderTables.rowIndex_val] at hb + unfold rotorSteps + omega + +inductive SelectExtraTape + | localIndex | owner | cloudSize | prefixOffset | darts + | savedLeft | savedRight | localWork | sizeWork + deriving DecidableEq + +protected abbrev SelectExtraTape.enumList : List SelectExtraTape := [.localIndex, .owner, + .cloudSize, .prefixOffset, .darts, .savedLeft, .savedRight, .localWork, .sizeWork] + +protected theorem SelectExtraTape.enumList_getElem?_ctorIdx_eq (x : SelectExtraTape) : + SelectExtraTape.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem SelectExtraTape.enumList_nodup : SelectExtraTape.enumList.Nodup := by decide + +instance : Fintype SelectExtraTape where + elems := ⟨SelectExtraTape.enumList, SelectExtraTape.enumList_nodup⟩ + complete x := by cases x <;> decide + +abbrev SelectTape := MachineCloudSelect.Tape ⊕ SelectExtraTape +abbrev RawSelectAlphabet : SelectTape → Type := + MachineEmbedding.Alphabet MachineCloudSelect.Alphabet (fun _ : SelectExtraTape => Bool) +abbrev SelectAlphabet (_ : SelectTape) := Bool + +theorem selectAlphabet_eq : RawSelectAlphabet = SelectAlphabet := by + funext k + cases k with + | inl k => cases k <;> rfl + | inr k => rfl + +def selectToBoolWord : (k : SelectTape) → List (RawSelectAlphabet k) → List Bool + | .inl (.inl _), word => word + | .inl (.inr _), word => word + | .inr _, word => word + +def selectToBoolTapes (base : ∀ k, List (RawSelectAlphabet k)) : SelectTape → List Bool := + fun k => selectToBoolWord k (base k) + +private theorem alphabet_tapes_apply {K : Type} {Γ Δ : K → Type} + (h : Γ = Δ) (base : ∀ k, List (Γ k)) (k : K) : + MachineAlphabetTransport.tapes h base k = + Eq.mp (congrArg (fun alphabet => List (alphabet k)) h) (base k) := by + cases h + rfl + +theorem selectToBoolTapes_eq (base : ∀ k, List (RawSelectAlphabet k)) : + selectToBoolTapes base = MachineAlphabetTransport.tapes selectAlphabet_eq base := by + funext k + rw [alphabet_tapes_apply] + cases k with + | inl k => cases k <;> rfl + | inr k => rfl + +abbrev SelectState (σ : Type) := MachineUnaryLessAt.State (σ × MachineCloudSelect.Phase) + +def selectStateEquiv (σ : Type) : (MachineCloudSelect.State σ × Unit) ≃ SelectState σ where + toFun s := (((s.1.1.1.1, s.1.2), s.1.1.1.2), s.1.1.2) + invFun s := ((((s.1.1.1, s.1.2), s.2), s.1.1.2), ()) + left_inv s := by rcases s with ⟨⟨⟨⟨a, b⟩, c⟩, d⟩, ⟨⟩⟩; rfl + right_inv s := by rcases s with ⟨⟨⟨a, b⟩, c⟩, d⟩; rfl + +def selectScratch : SelectTape := .inl (.inl .scratch) +def selectQuery : SelectTape := .inl (.inl .target) +def selectOutput : SelectTape := .inl (.inr ()) + +def compareSlots : Fin 4 ↪ SelectTape where + toFun i := ![.inr .localIndex, .inr .cloudSize, .inr .savedLeft, .inr .savedRight] i + inj' := by intro i j h; fin_cases i <;> fin_cases j <;> simp_all + +def subtractSlots : Fin 4 ↪ SelectTape where + toFun i := ![.inr .localWork, .inr .sizeWork, .inr .savedLeft, .inr .savedRight] i + inj' := by intro i j h; fin_cases i <;> fin_cases j <;> simp_all + +inductive SelectCopy + | oldLocal | oldOwner | dummyLocal | dummySize | dummyDifference + deriving DecidableEq + +protected abbrev SelectCopy.enumList : List SelectCopy := [.oldLocal, .oldOwner, .dummyLocal, + .dummySize, .dummyDifference] + +protected theorem SelectCopy.enumList_getElem?_ctorIdx_eq (x : SelectCopy) : + SelectCopy.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem SelectCopy.enumList_nodup : SelectCopy.enumList.Nodup := by decide + +instance : Fintype SelectCopy where + elems := ⟨SelectCopy.enumList, SelectCopy.enumList_nodup⟩ + complete x := by cases x <;> decide + +inductive SelectAdd + | prefixOffset | darts + deriving DecidableEq + +protected abbrev SelectAdd.enumList : List SelectAdd := [.prefixOffset, .darts] + +protected theorem SelectAdd.enumList_getElem?_ctorIdx_eq (x : SelectAdd) : + SelectAdd.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem SelectAdd.enumList_nodup : SelectAdd.enumList.Nodup := by decide + +instance : Fintype SelectAdd where + elems := ⟨SelectAdd.enumList, SelectAdd.enumList_nodup⟩ + complete x := by cases x <;> decide + +inductive SelectAddStage + | scan | restore + deriving DecidableEq + +protected abbrev SelectAddStage.enumList : List SelectAddStage := [.scan, .restore] + +protected theorem SelectAddStage.enumList_getElem?_ctorIdx_eq (x : SelectAddStage) : + SelectAddStage.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem SelectAddStage.enumList_nodup : SelectAddStage.enumList.Nodup := by decide + +instance : Fintype SelectAddStage where + elems := ⟨SelectAddStage.enumList, SelectAddStage.enumList_nodup⟩ + complete x := by cases x <;> decide + +inductive SelectControl + | compare (stage : MachineUnaryLessAt.Label) + | choose + | copy (kind : SelectCopy) (stage : MachineUnaryAffineAt.Label) + | subtract + | add (kind : SelectAdd) (stage : SelectAddStage) + | cleanup (i : Fin 5) + deriving DecidableEq, Fintype + +abbrev SelectLabel := MachineCloudSelect.Label ⊕ SelectControl + +def copySource : SelectCopy → SelectTape + | .oldLocal | .dummyLocal => .inr .localIndex + | .oldOwner => .inr .owner + | .dummySize => .inr .cloudSize + | .dummyDifference => .inr .localWork + +def copyDestination : SelectCopy → SelectTape + | .oldLocal | .oldOwner => selectQuery + | .dummyLocal => .inr .localWork + | .dummySize => .inr .sizeWork + | .dummyDifference => selectOutput + +def afterCopy : SelectCopy → SelectLabel + | .oldLocal => .inr (.copy .oldOwner .seed) + | .oldOwner => .inl (.inr .initialize) + | .dummyLocal => .inr (.copy .dummySize .seed) + | .dummySize => .inr .subtract + | .dummyDifference => .inr (.add .prefixOffset .scan) + +def addSource : SelectAdd → SelectTape + | .prefixOffset => .inr .prefixOffset + | .darts => .inr .darts + +def afterAdd : SelectAdd → SelectLabel + | .prefixOffset => .inr (.add .darts .scan) + | .darts => .inr (.cleanup 0) + +def cleanupTape (i : Fin 5) : SelectTape := + ![selectQuery, .inr .localWork, .inr .sizeWork, .inr .savedLeft, .inr .savedRight] i + +def afterCleanup (i : Fin 5) : Option SelectLabel := + if h : i.val + 1 < 5 then some (.inr (.cleanup ⟨i.val + 1, h⟩)) else none + +def selectControl : SelectControl → TM2.Stmt SelectAlphabet SelectLabel (SelectState σ) + | .compare stage => MachineUnaryLessAt.statement compareSlots + (fun s => .inr (.compare s)) (some (.inr .choose)) stage + | .choose => .branch (fun s => s.1.2) + (.load (fun s => ((s.1.1, false), none)) + (.goto fun _ => .inr (.copy .oldLocal .seed))) + (.load (fun s => ((s.1.1, false), none)) + (.goto fun _ => .inr (.copy .dummyLocal .seed))) + | .copy kind .seed => MachineUnaryAffineAt.seed (copyDestination kind) 0 + (.inr (.copy kind .scan)) + | .copy kind .scan => MachineUnaryAffineAt.scan (copySource kind) selectScratch + (copyDestination kind) 1 (.inr (.copy kind .scan)) (.inr (.copy kind .restore)) + | .copy kind .restore => Reduction.MachineTransfer.loopAt selectScratch (copySource kind) + id false (.inr (.copy kind .restore)) (some (afterCopy kind)) + | .subtract => MachineUnaryLessAt.scan subtractSlots (.inr .subtract) + (.inr (.copy .dummyDifference .seed)) + | .add kind .scan => MachineUnaryAffineAt.scan (addSource kind) selectScratch selectOutput 1 + (.inr (.add kind .scan)) (.inr (.add kind .restore)) + | .add kind .restore => Reduction.MachineTransfer.loopAt selectScratch (addSource kind) + id false (.inr (.add kind .restore)) (some (afterAdd kind)) + | .cleanup i => MachineDrain.drain (cleanupTape i) (.inr (.cleanup i)) (afterCleanup i) + +def rawSelectProgram : SelectLabel → TM2.Stmt RawSelectAlphabet SelectLabel (SelectState σ) := + MachineStateEquiv.program (selectStateEquiv σ) + (MachineEmbedding.program (some (.inr (.cleanup 0))) MachineCloudSelect.program + (fun control => MachineStateEquiv.statement (selectStateEquiv σ).symm + (MachineAlphabetTransport.statement selectAlphabet_eq.symm (selectControl control)))) + +def selectProgram : SelectLabel → TM2.Stmt SelectAlphabet SelectLabel (SelectState σ) := + MachineAlphabetTransport.program selectAlphabet_eq rawSelectProgram + +@[simp] theorem selectProgram_control (l : SelectControl) : + selectProgram (σ := σ) (.inr l) = selectControl l := by + change MachineAlphabetTransport.statement selectAlphabet_eq + (MachineStateEquiv.statement (selectStateEquiv σ) + (MachineStateEquiv.statement (selectStateEquiv σ).symm + (MachineAlphabetTransport.statement selectAlphabet_eq.symm (selectControl l)))) = _ + have h := MachineStateEquiv.statement_symm_statement (selectStateEquiv σ).symm + (MachineAlphabetTransport.statement selectAlphabet_eq.symm (selectControl (σ := σ) l)) + simp only [Equiv.symm_symm] at h + rw [h] + exact MachineAlphabetTransport.statement_roundtrip selectAlphabet_eq _ + +def selectCleanState (ambient : σ) (register : Option Bool) : SelectState σ := + (((ambient, .checking), false), register) + +theorem selectComparisonTrace (base : SelectTape → List Bool) (j k : Nat) + (hj : base (.inr .localIndex) = encodeWord j) + (hk : base (.inr .cloudSize) = encodeWord k) + (hl : base (.inr .savedLeft) = []) (hr : base (.inr .savedRight) = []) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step selectProgram))^[MachineUnaryLessAt.steps j k + 1] + (some ⟨some (.inr (.compare .scan)), selectCleanState ambient register, base⟩) = + some ⟨some (.inr (.copy (if j < k then .oldLocal else .dummyLocal) .seed)), + selectCleanState ambient none, base⟩ := by + have h := MachineUnaryLessAt.lessThanTrace compareSlots + (fun l => .inr (.compare l)) (some (.inr .choose)) selectProgram + (fun l => by rw [selectProgram_control]; rfl) + base j k [] [] (by change base (.inr .localIndex) = _; simpa only [List.append_nil] using hj) + (by change base (.inr .cloudSize) = _; simpa only [List.append_nil] using hk) hl hr + (ambient, MachineCloudSelect.Phase.checking) false register + simp only [selectCleanState] + rw [Function.iterate_succ_apply', h, advance_some] + change some (TM2.stepAux (selectProgram (.inr .choose)) _ _) = _ + rw [selectProgram_control] + by_cases hlt : j < k <;> simp [selectControl, TM2.stepAux, hlt] + +theorem selectCopyTrace (kind : SelectCopy) (base : SelectTape → List Bool) + (a : Nat) (hword : base (copySource kind) = encodeWord a) + (hscratch : base selectScratch = []) (ambient : σ) (register : Option Bool) : + (advance (TM2.step selectProgram))^[2 * (a + 1) + 1] + (some ⟨some (.inr (.copy kind .seed)), selectCleanState ambient register, base⟩) = + some ⟨some (afterCopy kind), selectCleanState ambient none, + Function.update base (copyDestination kind) + (encodeWord a ++ base (copyDestination kind))⟩ := by + have h₁ : copySource kind ≠ selectScratch := by cases kind <;> decide + have h₂ : copySource kind ≠ copyDestination kind := by cases kind <;> decide + have h₃ : selectScratch ≠ copyDestination kind := by cases kind <;> decide + simpa only [Nat.one_mul, Nat.add_zero, selectCleanState] using + MachineUnaryAffineAt.seededAffineTrace (copySource kind) selectScratch (copyDestination kind) + h₁ h₂ h₃ 1 0 (.inr (.copy kind .seed)) (.inr (.copy kind .scan)) + (.inr (.copy kind .restore)) (some (afterCopy kind)) selectProgram + (by rw [selectProgram_control]; rfl) (by rw [selectProgram_control]; rfl) + (by rw [selectProgram_control]; rfl) base a [] (by simpa using hword) hscratch + ((ambient, MachineCloudSelect.Phase.checking), false) register + +theorem selectAddTrace (kind : SelectAdd) (base : SelectTape → List Bool) + (a b : Nat) (hword : base (addSource kind) = encodeWord a) + (houtput : base selectOutput = encodeWord b) (hscratch : base selectScratch = []) + (ambient : σ) : + (advance (TM2.step selectProgram))^[2 * (a + 1)] + (some ⟨some (.inr (.add kind .scan)), selectCleanState ambient none, base⟩) = + some ⟨some (afterAdd kind), selectCleanState ambient none, + Function.update base selectOutput (encodeWord (a + b))⟩ := by + have h₁ : addSource kind ≠ selectScratch := by cases kind <;> decide + have h₂ : addSource kind ≠ selectOutput := by cases kind <;> decide + have h₃ : selectScratch ≠ selectOutput := by decide + have frame (n : Nat) : MachineUnaryAffineAt.tapes (addSource kind) selectScratch selectOutput + base (encodeWord a ++ []) [] (encodeWord n ++ []) = + Function.update base selectOutput (encodeWord n) := by + simp only [List.append_nil] + rw [← hword, ← hscratch] + simp only [MachineUnaryAffineAt.tapes, MachineCopy.forkTapes, Function.update_eq_self] + have h := MachineUnaryAffineAt.affineTrace (addSource kind) selectScratch selectOutput + h₁ h₂ h₃ 1 (.inr (.add kind .scan)) (.inr (.add kind .restore)) + (some (afterAdd kind)) selectProgram + (by rw [selectProgram_control]; rfl) (by rw [selectProgram_control]; rfl) + base a b [] [] ((ambient, MachineCloudSelect.Phase.checking), false) none + rw [frame, frame] at h + rw [← houtput, Function.update_eq_self] at h + simpa only [Nat.one_mul, selectCleanState] using h + +abbrev CoreTape := Fin 27 +abbrev CoreState (σ : Type) (q : Nat) := + (σ × (MachineFixedBlockMap.Buffer 4096 × + (Fin q × (Bool × MachineCloudSelect.Phase)))) × Option Bool + +inductive CoreLabel (q : Nat) + | rotor (stage : RotorLabel q) + | select (stage : SelectLabel) + | finish (stage : FinishLabel) + | cleanup (i : Fin 10) + deriving DecidableEq, Fintype + +def coreEntry (q : Nat) : CoreLabel q := .rotor (.lookup .seed) + +theorem selectCloudTrace (t : GraphTables.Table) (v : Fin t.vertices) + (i : Fin (PreprocessingCloudIndex.cloudSize t v)) + (extra : SelectExtraTape → List Bool) (ambient : σ) (register : Option Bool) : + (advance (TM2.step selectProgram))^[MachineCloudSelect.cloudSelectSteps t v i []] + (some ⟨some (.inl (.inr .initialize)), selectCleanState ambient register, + selectToBoolTapes (MachineEmbedding.tapes + (MachineCloudSelect.memory (GraphTables.tableBits t) [] + (MachineCloudSelect.queryWord v.val i.val []) [] [] [] []) extra)⟩) = + some ⟨some (.inr (.cleanup 0)), selectCleanState ambient none, + selectToBoolTapes (MachineEmbedding.tapes + (MachineCloudSelect.memory (GraphTables.tableBits t) [] + (MachineCloudSelect.queryWord v.val i.val []) [] [] [] + (encodeWord (PreprocessingCloudIndex.cloudSelect t v i).val.val)) extra)⟩ := by + let source := MachineCloudSelect.program (σ := σ) + let more := fun c => MachineStateEquiv.statement (selectStateEquiv σ).symm + (MachineAlphabetTransport.statement selectAlphabet_eq.symm (selectControl (σ := σ) c)) + let caller := MachineEmbedding.program (some (.inr (.cleanup 0))) source more + let embed := MachineEmbedding.configuration (K := MachineCloudSelect.Tape) + (Γ := MachineCloudSelect.Alphabet) (σ := MachineCloudSelect.State σ) + (some (Sum.inr (SelectControl.cleanup 0)) : Option SelectLabel) () extra + have sourceRun := MachineCloudSelect.cloudSelectTrace t v i [] [] ambient register + have lifted := liftSuccessfulTrace (TM2.step source) (TM2.step caller) embed + (MachineEmbedding.step_simulation (some (.inr (.cleanup 0))) () extra source more) + _ _ _ sourceRun + have transported := MachineStateEquiv.trace (selectStateEquiv σ) caller _ _ _ lifted + have boolean := MachineAlphabetTransport.successfulTrace selectAlphabet_eq + (MachineStateEquiv.program (selectStateEquiv σ) caller) _ _ _ transported + simp only [embed, MachineCloudSelect.cfg, MachineStateEquiv.configuration, MachineEmbedding.configuration, + MachineEmbedding.label, selectStateEquiv, List.append_nil, + MachineAlphabetTransport.configuration_mk, ← selectToBoolTapes_eq] at boolean + convert boolean using 1 <;> rfl + +def selectExtraMemory (j v k offset m : Nat) + (savedLeft savedRight localWork sizeWork : List Bool) : + SelectExtraTape → List Bool + | .localIndex => encodeWord j + | .owner => encodeWord v + | .cloudSize => encodeWord k + | .prefixOffset => encodeWord offset + | .darts => encodeWord m + | .savedLeft => savedLeft + | .savedRight => savedRight + | .localWork => localWork + | .sizeWork => sizeWork + +def selectMemory (graph : List Bool) (j v k offset m : Nat) + (query output savedLeft savedRight localWork sizeWork : List Bool) : + SelectTape → List Bool := + selectToBoolTapes (MachineEmbedding.tapes + (MachineCloudSelect.memory graph [] query [] [] [] output) + (selectExtraMemory j v k offset m savedLeft savedRight localWork sizeWork)) + +@[simp] theorem selectMemory_query (graph : List Bool) (j v k o m : Nat) + (query output a b c d : List Bool) : + selectMemory graph j v k o m query output a b c d selectQuery = query := rfl + +@[simp] theorem selectMemory_output (graph : List Bool) (j v k o m : Nat) + (query output a b c d : List Bool) : + selectMemory graph j v k o m query output a b c d selectOutput = output := rfl + +@[simp] theorem selectMemory_scratch (graph : List Bool) (j v k o m : Nat) + (query output a b c d : List Bool) : + selectMemory graph j v k o m query output a b c d selectScratch = [] := rfl + +@[simp] theorem selectMemory_extra (graph : List Bool) (j v k o m : Nat) + (query output a b c d : List Bool) (z : SelectExtraTape) : + selectMemory graph j v k o m query output a b c d (.inr z) = + selectExtraMemory j v k o m a b c d z := rfl + +@[simp] theorem update_selectMemory_query (graph : List Bool) (j v k o m : Nat) + (query output a b c d word : List Bool) : + Function.update (selectMemory graph j v k o m query output a b c d) selectQuery word = + selectMemory graph j v k o m word output a b c d := by + funext z + cases z with + | inl z => + cases z with + | inl z => cases z <;> rfl + | inr z => cases z; rfl + | inr z => cases z <;> rfl + +@[simp] theorem update_selectMemory_output (graph : List Bool) (j v k o m : Nat) + (query output a b c d word : List Bool) : + Function.update (selectMemory graph j v k o m query output a b c d) selectOutput word = + selectMemory graph j v k o m query word a b c d := by + funext z + cases z with + | inl z => + cases z with + | inl z => cases z <;> rfl + | inr z => cases z; rfl + | inr z => cases z <;> rfl + +@[simp] theorem update_selectMemory_local (graph : List Bool) (j v k o m : Nat) + (query output a b c d word : List Bool) : + Function.update (selectMemory graph j v k o m query output a b c d) (.inr .localWork) word = + selectMemory graph j v k o m query output a b word d := by + funext z + cases z with + | inl z => + cases z with + | inl z => cases z <;> rfl + | inr z => cases z; rfl + | inr z => cases z <;> rfl + +@[simp] theorem update_selectMemory_size (graph : List Bool) (j v k o m : Nat) + (query output a b c d word : List Bool) : + Function.update (selectMemory graph j v k o m query output a b c d) (.inr .sizeWork) word = + selectMemory graph j v k o m query output a b c word := by + funext z + cases z with + | inl z => + cases z with + | inl z => cases z <;> rfl + | inr z => cases z; rfl + | inr z => cases z <;> rfl + +@[simp] theorem update_selectMemory_left (graph : List Bool) (j v k o m : Nat) + (query output a b c d word : List Bool) : + Function.update (selectMemory graph j v k o m query output a b c d) (.inr .savedLeft) word = + selectMemory graph j v k o m query output word b c d := by + funext z + cases z with + | inl z => + cases z with + | inl z => cases z <;> rfl + | inr z => cases z; rfl + | inr z => cases z <;> rfl + +@[simp] theorem update_selectMemory_right (graph : List Bool) (j v k o m : Nat) + (query output a b c d word : List Bool) : + Function.update (selectMemory graph j v k o m query output a b c d) (.inr .savedRight) word = + selectMemory graph j v k o m query output a word c d := by + funext z + cases z with + | inl z => + cases z with + | inl z => cases z <;> rfl + | inr z => cases z; rfl + | inr z => cases z <;> rfl + +theorem selectCleanupTrace (graph : List Bool) (j v k o m : Nat) + (query output a b c d : List Bool) (ambient : σ) : + (advance (TM2.step selectProgram))^[query.length + c.length + d.length + a.length + b.length + 5] + (some ⟨some (.inr (.cleanup 0)), selectCleanState ambient none, + selectMemory graph j v k o m query output a b c d⟩) = + some ⟨none, selectCleanState ambient none, + selectMemory graph j v k o m [] output [] [] [] []⟩ := by + have h0 := MachineDrain.drainTrace selectQuery (.inr (.cleanup 0)) + (some (.inr (.cleanup 1))) selectProgram + (by rw [selectProgram_control]; rfl) + (selectMemory graph j v k o m query output a b c d) query + ((ambient, MachineCloudSelect.Phase.checking), false) none + simp only [update_selectMemory_query] at h0 + have h1 := MachineDrain.drainTrace (.inr .localWork) (.inr (.cleanup 1)) + (some (.inr (.cleanup 2))) selectProgram + (by rw [selectProgram_control]; rfl) + (selectMemory graph j v k o m [] output a b c d) c + ((ambient, MachineCloudSelect.Phase.checking), false) none + simp only [update_selectMemory_local] at h1 + have h2 := MachineDrain.drainTrace (.inr .sizeWork) (.inr (.cleanup 2)) + (some (.inr (.cleanup 3))) selectProgram + (by rw [selectProgram_control]; rfl) + (selectMemory graph j v k o m [] output a b [] d) d + ((ambient, MachineCloudSelect.Phase.checking), false) none + simp only [update_selectMemory_size] at h2 + have h3 := MachineDrain.drainTrace (.inr .savedLeft) (.inr (.cleanup 3)) + (some (.inr (.cleanup 4))) selectProgram + (by rw [selectProgram_control]; rfl) + (selectMemory graph j v k o m [] output a b [] []) a + ((ambient, MachineCloudSelect.Phase.checking), false) none + simp only [update_selectMemory_left] at h3 + have h4 := MachineDrain.drainTrace (.inr .savedRight) (.inr (.cleanup 4)) + none selectProgram (by rw [selectProgram_control]; rfl) + (selectMemory graph j v k o m [] output [] b [] []) b + ((ambient, MachineCloudSelect.Phase.checking), false) none + simp only [update_selectMemory_right] at h4 + have total := joinTrace (joinTrace (joinTrace (joinTrace h0 h1) h2) h3) h4 + have hn : query.length + c.length + d.length + a.length + b.length + 5 = + ((((query.length + 1) + (c.length + 1)) + (d.length + 1)) + (a.length + 1)) + + (b.length + 1) := by omega + rw [hn] + exact total + +def oldSelectSteps (t : GraphTables.Table) (v : Fin t.vertices) + (i : Fin (PreprocessingCloudIndex.cloudSize t v)) : Nat := + (2 * (i.val + 1) + 1) + (2 * (v.val + 1) + 1) + + MachineCloudSelect.cloudSelectSteps t v i [] + (v.val + i.val + 7) + +theorem selectOldTrace (t : GraphTables.Table) (v : Fin t.vertices) + (i : Fin (PreprocessingCloudIndex.cloudSize t v)) (o : Nat) (ambient : σ) : + (advance (TM2.step selectProgram))^[oldSelectSteps t v i] + (some ⟨some (.inr (.copy .oldLocal .seed)), selectCleanState ambient none, + selectMemory (GraphTables.tableBits t) i.val v.val + (PreprocessingCloudIndex.cloudSize t v) o t.darts [] [] [] [] [] []⟩) = + some ⟨none, selectCleanState ambient none, + selectMemory (GraphTables.tableBits t) i.val v.val + (PreprocessingCloudIndex.cloudSize t v) o t.darts [] + (encodeWord (PreprocessingCloudIndex.cloudSelect t v i).val.val) [] [] [] []⟩ := by + let graph := GraphTables.tableBits t + let k := PreprocessingCloudIndex.cloudSize t v + have hi := selectCopyTrace .oldLocal + (selectMemory graph i.val v.val k o t.darts [] [] [] [] [] []) + i.val rfl rfl ambient none + simp only [copyDestination, afterCopy, selectMemory_query, update_selectMemory_query, List.append_nil] at hi + have hv := selectCopyTrace .oldOwner + (selectMemory graph i.val v.val k o t.darts (encodeWord i.val) [] [] [] [] []) + v.val rfl rfl ambient none + simp only [copyDestination, afterCopy, selectMemory_query, update_selectMemory_query] at hv + have hc := selectCloudTrace t v i (selectExtraMemory i.val v.val k o t.darts [] [] [] []) + ambient none + have hq : MachineCloudSelect.queryWord v.val i.val [] = + encodeWord v.val ++ encodeWord i.val := by + simp only [MachineCloudSelect.queryWord, MachineCloudRank.queryWord, List.append_nil] + change (advance (TM2.step selectProgram))^[MachineCloudSelect.cloudSelectSteps t v i []] + (some ⟨some (.inl (.inr .initialize)), selectCleanState ambient none, + selectMemory graph i.val v.val k o t.darts + (MachineCloudSelect.queryWord v.val i.val []) [] [] [] [] []⟩) = + some ⟨some (.inr (.cleanup 0)), selectCleanState ambient none, + selectMemory graph i.val v.val k o t.darts + (MachineCloudSelect.queryWord v.val i.val []) + (encodeWord (PreprocessingCloudIndex.cloudSelect t v i).val.val) [] [] [] []⟩ at hc + rw [hq] at hc + have hd := selectCleanupTrace graph i.val v.val k o t.darts + (encodeWord v.val ++ encodeWord i.val) + (encodeWord (PreprocessingCloudIndex.cloudSelect t v i).val.val) [] [] [] [] ambient + have hn : (encodeWord v.val ++ encodeWord i.val).length + ([] : List Bool).length + ([] : List Bool).length + + ([] : List Bool).length + ([] : List Bool).length + 5 = v.val + i.val + 7 := by + simp only [List.length_append, encodeWord_length, List.length_nil] + omega + rw [hn] at hd + exact joinTrace (joinTrace (joinTrace hi hv) hc) hd + +def dummySelectSteps (j k o m : Nat) : Nat := + (2 * (j + 1) + 1) + (2 * (k + 1) + 1) + (k + 1) + + (2 * (j - k + 1) + 1) + 2 * (o + 1) + 2 * (m + 1) + (j + k + 7) + +theorem dummySelectSteps_eq (j k o m : Nat) (h : k ≤ j) : + dummySelectSteps j k o m = 5 * j + 2 * k + 2 * o + 2 * m + 21 := by + unfold dummySelectSteps + omega + +theorem selectDummyTrace (graph : List Bool) (j v k o m : Nat) (hk : k ≤ j) + (ambient : σ) : + (advance (TM2.step selectProgram))^[dummySelectSteps j k o m] + (some ⟨some (.inr (.copy .dummyLocal .seed)), selectCleanState ambient none, + selectMemory graph j v k o m [] [] [] [] [] []⟩) = + some ⟨none, selectCleanState ambient none, + selectMemory graph j v k o m [] (encodeWord (m + o + (j - k))) [] [] [] []⟩ := by + have hjcopy := selectCopyTrace .dummyLocal + (selectMemory graph j v k o m [] [] [] [] [] []) j rfl rfl ambient none + simp only [copyDestination, afterCopy, selectMemory_extra, selectExtraMemory, + update_selectMemory_local, List.append_nil] at hjcopy + have hkcopy := selectCopyTrace .dummySize + (selectMemory graph j v k o m [] [] [] [] (encodeWord j) []) k rfl rfl ambient none + simp only [copyDestination, afterCopy, selectMemory_extra, selectExtraMemory, + update_selectMemory_size, List.append_nil] at hkcopy + have scanFrame (left right savedLeft savedRight : List Bool) : + MachineUnaryLessAt.tapes subtractSlots + (selectMemory graph j v k o m [] [] [] [] [] []) + left right savedLeft savedRight = + selectMemory graph j v k o m [] [] savedLeft savedRight left right := by + simp only [MachineUnaryLessAt.tapes, + show subtractSlots 0 = .inr .localWork from rfl, + show subtractSlots 1 = .inr .sizeWork from rfl, + show subtractSlots 2 = .inr .savedLeft from rfl, + show subtractSlots 3 = .inr .savedRight from rfl, + update_selectMemory_local, update_selectMemory_size, + update_selectMemory_left, update_selectMemory_right] + have hscan := MachineUnaryLessAt.scanTrace subtractSlots (.inr .subtract) + (.inr (.copy .dummyDifference .seed)) selectProgram + (by rw [selectProgram_control]; rfl) + (selectMemory graph j v k o m [] [] [] [] [] []) + j k [] [] [] [] (ambient, MachineCloudSelect.Phase.checking) false none + simp only [List.append_nil, scanFrame, Nat.min_eq_right hk, Nat.sub_eq_zero_of_le hk, + show ¬ j < k from Nat.not_lt_of_ge hk, decide_false] at hscan + have hdiffcopy := selectCopyTrace .dummyDifference + (selectMemory graph j v k o m [] [] (List.replicate k true) (List.replicate k true) + (encodeWord (j - k)) (encodeWord 0)) (j - k) rfl rfl ambient none + simp only [copyDestination, afterCopy, selectMemory_output, update_selectMemory_output, List.append_nil] at hdiffcopy + have hprefix := selectAddTrace .prefixOffset + (selectMemory graph j v k o m [] (encodeWord (j - k)) + (List.replicate k true) (List.replicate k true) (encodeWord (j - k)) (encodeWord 0)) + o (j - k) rfl rfl rfl ambient + simp only [afterAdd, update_selectMemory_output] at hprefix + have hm := selectAddTrace .darts + (selectMemory graph j v k o m [] (encodeWord (o + (j - k))) + (List.replicate k true) (List.replicate k true) (encodeWord (j - k)) (encodeWord 0)) + m (o + (j - k)) rfl rfl rfl ambient + simp only [afterAdd, update_selectMemory_output, ← Nat.add_assoc] at hm + have hcleanup := selectCleanupTrace graph j v k o m [] + (encodeWord (m + o + (j - k))) (List.replicate k true) (List.replicate k true) + (encodeWord (j - k)) (encodeWord 0) ambient + have hcleanSteps : ([] : List Bool).length + (encodeWord (j - k)).length + (encodeWord 0).length + + (List.replicate k true).length + (List.replicate k true).length + 5 = j + k + 7 := by + simp only [List.length_nil, encodeWord_length, List.length_replicate] + omega + rw [hcleanSteps] at hcleanup + exact joinTrace (joinTrace (joinTrace (joinTrace (joinTrace (joinTrace + hjcopy hkcopy) hscan) hdiffcopy) hprefix) hm) hcleanup + +def selectionSteps (t : GraphTables.Table) (padding : Fin t.vertices → Nat) + (v : Fin t.vertices) (i : Fin (PreprocessingCloudIndex.cloudSize t v + padding v)) : Nat := + MachineUnaryLessAt.steps i.val (PreprocessingCloudIndex.cloudSize t v) + 1 + + if hi : i.val < PreprocessingCloudIndex.cloudSize t v then + oldSelectSteps t v ⟨i.val, hi⟩ + else dummySelectSteps i.val (PreprocessingCloudIndex.cloudSize t v) + (PreprocessingPaddingOffsets.offset padding v.val) t.darts + +theorem selectionTrace (t : GraphTables.Table) (padding : Fin t.vertices → Nat) + (v : Fin t.vertices) (i : Fin (PreprocessingCloudIndex.cloudSize t v + padding v)) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step selectProgram))^[selectionSteps t padding v i] + (some ⟨some (.inr (.compare .scan)), selectCleanState ambient register, + selectMemory (GraphTables.tableBits t) i.val v.val + (PreprocessingCloudIndex.cloudSize t v) + (PreprocessingPaddingOffsets.offset padding v.val) t.darts [] [] [] [] [] []⟩) = + some ⟨none, selectCleanState ambient none, + selectMemory (GraphTables.tableBits t) i.val v.val + (PreprocessingCloudIndex.cloudSize t v) + (PreprocessingPaddingOffsets.offset padding v.val) t.darts [] + (encodeWord (PreprocessingInternalRows.selectedIndex t padding v i)) [] [] [] []⟩ := by + have hc := selectComparisonTrace + (selectMemory (GraphTables.tableBits t) i.val v.val + (PreprocessingCloudIndex.cloudSize t v) + (PreprocessingPaddingOffsets.offset padding v.val) t.darts [] [] [] [] [] []) + i.val (PreprocessingCloudIndex.cloudSize t v) rfl rfl rfl rfl ambient register + by_cases hi : i.val < PreprocessingCloudIndex.cloudSize t v + · simp only [ite_eq_left hi] at hc + have hb := selectOldTrace t v ⟨i.val, hi⟩ + (PreprocessingPaddingOffsets.offset padding v.val) ambient + simpa only [selectionSteps, dite_eq_left hi, + PreprocessingInternalRows.selectedIndex_old t padding v i hi] using joinTrace hc hb + · simp only [ite_eq_right hi] at hc + have hb := selectDummyTrace (GraphTables.tableBits t) i.val v.val + (PreprocessingCloudIndex.cloudSize t v) + (PreprocessingPaddingOffsets.offset padding v.val) t.darts (Nat.le_of_not_gt hi) ambient + simpa only [selectionSteps, dite_eq_right hi, + PreprocessingInternalRows.selectedIndex_dummy t padding v i (Nat.le_of_not_gt hi)] + using joinTrace hc hb + +end MinUncutGames.Foundations.Complexity.MachineRegularInternalRow +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/AlphabetBudget.lean b/lean/OAI/Computability/MinUncut/Machines/AlphabetBudget.lean new file mode 100644 index 0000000000000000000000000000000000000000..2a5c041778c6727d748b37eed1f6b47c931c25fa --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/AlphabetBudget.lean @@ -0,0 +1,117 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.CompletedSampling + +namespace OAI + +section +namespace MinUncutGames.Foundations.Repetition + +open scoped BigOperators +open Games +noncomputable section + +variable {Q₁ Q₂ A₁ A₂ : Type*} + [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂] + [DecidableEq Q₁] [DecidableEq Q₂] {n : ℕ} + +theorem selectedLabels_card (selected : Finset (Fin n)) : + Fintype.card (SelectedLabels (A₁ := A₁) (A₂ := A₂) selected) = + (Fintype.card A₁ * Fintype.card A₂) ^ selected.card := by + simp [SelectedLabels, Fintype.card_prod, mul_pow] + +theorem unusedCoordinates_card (selected : Finset (Fin n)) : + Fintype.card {i : Fin n // i ∉ selected} = n - selected.card := by + classical + simp [Fintype.card_subtype_compl] + +theorem unusedCoordinates_card_real (selected : Finset (Fin n)) : + (Fintype.card {i : Fin n // i ∉ selected} : ℝ) = (n : ℝ) - selected.card := by + have hs : selected.card ≤ n := by simpa using Finset.card_le_univ selected + rw [unusedCoordinates_card, Nat.cast_sub hs] + +theorem log_le_logTwo {x : ℝ} (hx : 1 ≤ x) : Real.log x ≤ logTwo x := by + have hlog : 0 ≤ Real.log x := Real.log_nonneg hx + have htwo : 0 < Real.log 2 := Real.log_pos (by norm_num) + have htwo_le : Real.log 2 ≤ 1 := by + convert Real.log_le_sub_one_of_pos (by norm_num : (0 : ℝ) < 2) using 1 + norm_num + unfold logTwo + apply (le_div_iff₀ htwo).2 + simpa using mul_le_mul_of_nonneg_left htwo_le hlog + +theorem selectedLabels_log_le [Nonempty A₁] [Nonempty A₂] + (selected : Finset (Fin n)) (ell : ℝ) + (hell : logTwo ((Fintype.card A₁ : ℝ) * (Fintype.card A₂ : ℝ)) ≤ ell) : + Real.log (Fintype.card (SelectedLabels (A₁ := A₁) (A₂ := A₂) selected) : ℝ) ≤ + (selected.card : ℝ) * ell := by + have ha : (1 : ℝ) ≤ Fintype.card A₁ := by exact_mod_cast Fintype.card_pos (α := A₁) + have hb : (1 : ℝ) ≤ Fintype.card A₂ := by exact_mod_cast Fintype.card_pos (α := A₂) + have hab : (1 : ℝ) ≤ (Fintype.card A₁ : ℝ) * (Fintype.card A₂ : ℝ) := by nlinarith + rw [selectedLabels_card, Nat.cast_pow, Nat.cast_mul, Real.log_pow] + exact mul_le_mul_of_nonneg_left ((log_le_logTwo hab).trans hell) (Nat.cast_nonneg _) + +omit [DecidableEq Q₁] [DecidableEq Q₂] in +theorem selectedInformationRadius_le [Nonempty A₁] [Nonempty A₂] + (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) + (ell : ℝ) + (hell : logTwo ((Fintype.card A₁ : ℝ) * (Fintype.card A₂ : ℝ)) ≤ ell) : + selectedInformationRadius G strategy selected ≤ + Real.sqrt (((n : ℝ) - selected.card) * + ((selected.card : ℝ) * ell + logTwo (1 / G.selectedSuccess strategy selected))) := by + have hprob : 1 ≤ 1 / G.selectedSuccess strategy selected := by + apply (le_div_iff₀ positive).2 + simpa using G.selectedSuccess_le_one strategy selected + have hbudget := add_le_add (selectedLabels_log_le (A₁ := A₁) (A₂ := A₂) selected ell hell) + (log_le_logTwo hprob) + unfold selectedInformationRadius + rw [← unusedCoordinates_card_real selected] + apply Real.sqrt_le_sqrt + exact mul_le_mul_of_nonneg_left hbudget (Nat.cast_nonneg _) + +theorem sqrt_budget_factor (a b : ℝ) (ha : 0 < a) : + Real.sqrt (a * b) = a * Real.sqrt (b / a) := by + have he : a * b = a ^ 2 * (b / a) := by + field_simp + rw [he, Real.sqrt_mul (sq_nonneg a), Real.sqrt_sq (le_of_lt ha)] + +omit [DecidableEq Q₁] [DecidableEq Q₂] in +theorem exists_coordinate_le_information_budget [Nonempty A₁] [Nonempty A₂] + (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) + (ell : ℝ) + (hell : logTwo ((Fintype.card A₁ : ℝ) * (Fintype.card A₂ : ℝ)) ≤ ell) + (hselected : selected.card < n) + (error : {i : Fin n // i ∉ selected} → ℝ) + (hsum : (∑ j, error j) ≤ 15 * selectedInformationRadius G strategy selected) : + ∃ j : {i : Fin n // i ∉ selected}, error j ≤ 15 * Real.sqrt + (((selected.card : ℝ) * ell + logTwo (1 / G.selectedSuccess strategy selected)) / + ((n : ℝ) - selected.card)) := by + classical + have hcard : 0 < Fintype.card {i : Fin n // i ∉ selected} := by + rw [unusedCoordinates_card] + exact Nat.sub_pos_of_lt hselected + let : Nonempty {i : Fin n // i ∉ selected} := Fintype.card_pos_iff.mp hcard + have hden : 0 < (n : ℝ) - selected.card := by + rw [← unusedCoordinates_card_real selected] + exact_mod_cast hcard + have htotal := hsum.trans (mul_le_mul_of_nonneg_left + (selectedInformationRadius_le G strategy selected positive ell hell) (by norm_num : (0 : ℝ) ≤ 15)) + rw [sqrt_budget_factor _ _ hden] at htotal + have havg : (∑ j, error j) ≤ ∑ _j : {i : Fin n // i ∉ selected}, + 15 * Real.sqrt + (((selected.card : ℝ) * ell + logTwo (1 / G.selectedSuccess strategy selected)) / + ((n : ℝ) - selected.card)) := by + simpa only [Finset.sum_const, Finset.card_univ, nsmul_eq_mul, + unusedCoordinates_card_real, mul_assoc, mul_left_comm] using htotal + obtain ⟨j, _, hj⟩ := Finset.exists_le_of_sum_le Finset.univ_nonempty havg + exact ⟨j, hj⟩ + +end +end MinUncutGames.Foundations.Repetition + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/AlphabetGraph.lean b/lean/OAI/Computability/MinUncut/Machines/AlphabetGraph.lean new file mode 100644 index 0000000000000000000000000000000000000000..c3d14d287a9f7c7b2e9bc5487b0941dc0f9aa5ee --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/AlphabetGraph.lean @@ -0,0 +1,786 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.AlphabetReduction +import OAI.Computability.MinUncut.PCP.UniformRestriction + +namespace OAI + +noncomputable section + +namespace MinUncutGames.Foundations.PCP.AlphabetGraph + +open MinUncutGames.Foundations.Hastad +open scoped BigOperators + +abbrev Address (V E A : Type*) := (V × Cube A) ⊕ (E × Cube (A × A)) + +abbrev LocalEvent (A : Type*) := Fin 4 × AlphabetReduction.InputCoordinate A × + Cube (A × A) × Cube (A × A) × Cube (A × A) × Cube (A × A) × Cube (A × A) + +abbrev Event (E A : Type*) := E × LocalEvent A + +variable {V E A : Type*} [Fintype A] [DecidableEq A] [Nonempty A] + +abbrev legal (G : ConstraintGraph V E A) (e : E) (p : A × A) : Prop := + G.accepts e p.1 p.2 = true + +instance legalDecidable (G : ConstraintGraph V E A) (e : E) : + DecidablePred (legal G e) := + fun p => inferInstanceAs (Decidable (G.accepts e p.1 p.2 = true)) + +def restrictTape (G : ConstraintGraph V E A) (e : E) (f : Cube (A × A)) : + Cube (AlphabetReduction.LegalPair (G.accepts e)) := UniformRestriction.restrict (legal G e) f + +def extendTape (G : ConstraintGraph V E A) (e : E) + (f : Cube (AlphabetReduction.LegalPair (G.accepts e))) : Cube (A × A) := + UniformRestriction.extend (legal G e) f + +def globalizeQuery (G : ConstraintGraph V E A) (e : E) : + AlphabetReduction.InputCoordinate A ⊕ Cube (AlphabetReduction.LegalPair (G.accepts e)) → Address V E A + | .inl (side, tape) => .inl ((if side then G.head e else G.tail e), tape) + | .inr tape => .inr (e, extendTape G e tape) + +def verifier (G : ConstraintGraph V E A) : QueryIncidence.Verifier (Event E A) (Address V E A) 6 where + query := fun (e, kind, k, f, g, r₀, r₁, r₂) slot => + globalizeQuery G e (AssignmentTester.eventQueries (AlphabetReduction.pairEncoding (G.accepts e)) kind k + (restrictTape G e f) (restrictTape G e g) (restrictTape G e r₀) + (restrictTape G e r₁) (restrictTape G e r₂) slot) + accepts := fun (_, kind, _, _, _, _, _, _) b => AssignmentTester.eventAccepts kind b + +def vertexBlock (assignment : Address V E A → Bool) (v : V) : Cube A → Bool := + fun tape => assignment (.inl (v, tape)) + +def edgeOracle (G : ConstraintGraph V E A) (assignment : Address V E A → Bool) (e : E) : + Cube (AlphabetReduction.LegalPair (G.accepts e)) → Bool := + fun tape => assignment (.inr (e, extendTape G e tape)) + +omit [Fintype A] [DecidableEq A] [Nonempty A] in +theorem oracleAnswer_globalize (G : ConstraintGraph V E A) + (assignment : Address V E A → Bool) (e : E) + (x : AlphabetReduction.InputCoordinate A ⊕ Cube (AlphabetReduction.LegalPair (G.accepts e))) : + assignment (globalizeQuery G e x) = + AssignmentTester.oracleAnswer + (CodeComposition.pairWord (vertexBlock assignment (G.tail e)) + (vertexBlock assignment (G.head e))) (edgeOracle G assignment e) x := by + rcases x with ⟨side, tape⟩ | tape + · cases side <;> rfl + · rfl + +omit [Fintype A] [DecidableEq A] [Nonempty A] in +theorem response_eq_local (G : ConstraintGraph V E A) + (assignment : Address V E A → Bool) (e : E) (kind : Fin 4) + (k : AlphabetReduction.InputCoordinate A) (f g r₀ r₁ r₂ : Cube (A × A)) : + QueryIncidence.response (verifier G) assignment (e, kind, k, f, g, r₀, r₁, r₂) = + fun slot => AssignmentTester.oracleAnswer + (CodeComposition.pairWord (vertexBlock assignment (G.tail e)) + (vertexBlock assignment (G.head e))) (edgeOracle G assignment e) + (AssignmentTester.eventQueries (AlphabetReduction.pairEncoding (G.accepts e)) kind k + (restrictTape G e f) (restrictTape G e g) (restrictTape G e r₀) + (restrictTape G e r₁) (restrictTape G e r₂) slot) := by + funext slot + exact oracleAnswer_globalize G assignment e _ + +def eventReject (G : ConstraintGraph V E A) (assignment : Address V E A → Bool) + (event : Event E A) : ℝ := + AssignmentTester.truth (!((verifier G).accepts event (QueryIncidence.response (verifier G) assignment event))) + +omit [Fintype A] [DecidableEq A] [Nonempty A] in +theorem eventReject_eq_local (G : ConstraintGraph V E A) + (assignment : Address V E A → Bool) (e : E) (kind : Fin 4) + (k : AlphabetReduction.InputCoordinate A) (f g r₀ r₁ r₂ : Cube (A × A)) : + eventReject G assignment (e, kind, k, f, g, r₀, r₁, r₂) = + AssignmentTester.eventReject (AlphabetReduction.pairEncoding (G.accepts e)) + (CodeComposition.pairWord (vertexBlock assignment (G.tail e)) + (vertexBlock assignment (G.head e))) (edgeOracle G assignment e) kind k + (restrictTape G e f) (restrictTape G e g) (restrictTape G e r₀) + (restrictTape G e r₁) (restrictTape G e r₂) := by + unfold eventReject + rw [response_eq_local] + rfl + +theorem expect_prod {I J : Type*} [Fintype I] [Fintype J] (f : I × J → ℝ) : + (𝔼 z : I × J, f z) = 𝔼 i : I, 𝔼 j : J, f (i, j) := by + simpa only [Finset.univ_product_univ] using + Finset.expect_product (Finset.univ : Finset I) (Finset.univ : Finset J) f + +def localAverage (G : ConstraintGraph V E A) (assignment : Address V E A → Bool) + (e : E) : ℝ := 𝔼 sample : LocalEvent A, eventReject G assignment (e, sample) + +theorem expect_restrict_five {B : Type*} [Fintype B] [DecidableEq B] + (p : B → Prop) [DecidablePred p] + (h : ({b // p b} → Bool) → ({b // p b} → Bool) → ({b // p b} → Bool) → + ({b // p b} → Bool) → ({b // p b} → Bool) → ℝ) : + (𝔼 f : B → Bool, 𝔼 g : B → Bool, 𝔼 r₀ : B → Bool, + 𝔼 r₁ : B → Bool, 𝔼 r₂ : B → Bool, + h (UniformRestriction.restrict p f) (UniformRestriction.restrict p g) + (UniformRestriction.restrict p r₀) (UniformRestriction.restrict p r₁) + (UniformRestriction.restrict p r₂)) = + 𝔼 f : {b // p b} → Bool, 𝔼 g : {b // p b} → Bool, + 𝔼 r₀ : {b // p b} → Bool, 𝔼 r₁ : {b // p b} → Bool, + 𝔼 r₂ : {b // p b} → Bool, h f g r₀ r₁ r₂ := by + rw [UniformRestriction.expect_restrict p + (fun f => 𝔼 g : B → Bool, 𝔼 r₀ : B → Bool, 𝔼 r₁ : B → Bool, + 𝔼 r₂ : B → Bool, h f (UniformRestriction.restrict p g) + (UniformRestriction.restrict p r₀) (UniformRestriction.restrict p r₁) + (UniformRestriction.restrict p r₂))] + apply Finset.expect_congr rfl + intro f _ + rw [UniformRestriction.expect_restrict p + (fun g => 𝔼 r₀ : B → Bool, 𝔼 r₁ : B → Bool, 𝔼 r₂ : B → Bool, + h f g (UniformRestriction.restrict p r₀) (UniformRestriction.restrict p r₁) + (UniformRestriction.restrict p r₂))] + apply Finset.expect_congr rfl + intro g _ + rw [UniformRestriction.expect_restrict p + (fun r₀ => 𝔼 r₁ : B → Bool, 𝔼 r₂ : B → Bool, + h f g r₀ (UniformRestriction.restrict p r₁) (UniformRestriction.restrict p r₂))] + apply Finset.expect_congr rfl + intro r₀ _ + rw [UniformRestriction.expect_restrict p + (fun r₁ => 𝔼 r₂ : B → Bool, h f g r₀ r₁ (UniformRestriction.restrict p r₂))] + apply Finset.expect_congr rfl + intro r₁ _ + exact UniformRestriction.expect_restrict p (h f g r₀ r₁) + +omit [Nonempty A] in +theorem localAverage_eq_tester (G : ConstraintGraph V E A) + (assignment : Address V E A → Bool) (e : E) : + localAverage G assignment e = AlphabetReduction.edgeTesterReject (G.accepts e) + (vertexBlock assignment (G.tail e)) (vertexBlock assignment (G.head e)) + (edgeOracle G assignment e) := by + unfold localAverage AlphabetReduction.edgeTesterReject AssignmentTester.explicitTesterReject + simp only [LocalEvent, expect_prod, eventReject_eq_local, restrictTape] + apply Finset.expect_congr rfl + intro kind _ + apply Finset.expect_congr rfl + intro side _ + apply Finset.expect_congr rfl + intro tape _ + exact expect_restrict_five (legal G e) + (AssignmentTester.eventReject (AlphabetReduction.pairEncoding (G.accepts e)) + (CodeComposition.pairWord (vertexBlock assignment (G.tail e)) + (vertexBlock assignment (G.head e))) (edgeOracle G assignment e) kind (side, tape)) + +def average [Fintype E] (G : ConstraintGraph V E A) + (assignment : Address V E A → Bool) : ℝ := + 𝔼 event : Event E A, eventReject G assignment event + +omit [Nonempty A] in +theorem average_eq_testers [Fintype E] (G : ConstraintGraph V E A) + (assignment : Address V E A → Bool) : + average G assignment = 𝔼 e : E, AlphabetReduction.edgeTesterReject (G.accepts e) + (vertexBlock assignment (G.tail e)) (vertexBlock assignment (G.head e)) + (edgeOracle G assignment e) := by + unfold average + rw [expect_prod] + exact Finset.expect_congr rfl (fun e _ => localAverage_eq_tester G assignment e) + +def decodedLabeling (assignment : Address V E A → Bool) : V → A := + fun v => CodeComposition.nearest (vertexBlock assignment v) + +theorem local_gap (G : ConstraintGraph V E A) + (assignment : Address V E A → Bool) (e : E) : + AssignmentTester.truth (!(G.edgeSatisfied (decodedLabeling assignment) e)) / 2048 ≤ + localAverage G assignment e := by + cases h : G.edgeSatisfied (decodedLabeling assignment) e with + | false => + rw [localAverage_eq_tester] + simpa [AssignmentTester.truth] using + AlphabetReduction.rejected_edge_tester_bound (G.accepts e) + (vertexBlock assignment (G.tail e)) (vertexBlock assignment (G.head e)) + (edgeOracle G assignment e) h + | true => + simp only [Bool.not_true, AssignmentTester.truth, Bool.false_eq_true, ite_false, zero_div] + apply Finset.expect_nonneg + intro sample _ + exact AssignmentTester.truth_nonneg _ + +theorem average_gap [Fintype E] (G : ConstraintGraph V E A) + (assignment : Address V E A → Bool) : + (𝔼 e : E, AssignmentTester.truth (!(G.edgeSatisfied (decodedLabeling assignment) e))) / 2048 ≤ + average G assignment := by + unfold average + rw [expect_prod, Finset.expect_div] + exact Finset.expect_le_expect (fun e _ => local_gap G assignment e) + +theorem expect_rejection_eq_count {I : Type*} [Fintype I] (b : I → Bool) : + (𝔼 i : I, AssignmentTester.truth (!(b i))) = + ((Finset.univ.filter (fun i => b i = false)).card : ℝ) / Fintype.card I := by + rw [Fintype.expect_eq_sum_div_card] + congr 1 + calc + (∑ i : I, AssignmentTester.truth (!(b i))) = ∑ i : I, if b i = false then (1 : ℝ) else 0 := by + apply Finset.sum_congr rfl + intro i _ + cases b i <;> norm_num [AssignmentTester.truth] + _ = _ := Finset.sum_boole _ _ + +omit [Nonempty A] in +theorem average_eq_count [Fintype E] (G : ConstraintGraph V E A) + (assignment : Address V E A → Bool) : + average G assignment = (QueryIncidence.verifierRejectionCount (verifier G) assignment : ℝ) / + Fintype.card (Event E A) := + expect_rejection_eq_count _ + +omit [Nonempty A] in +@[simp] theorem card_event [Fintype E] : + Fintype.card (Event E A) = Fintype.card E * Fintype.card (LocalEvent A) := + Fintype.card_prod _ _ + +omit [Nonempty A] in +theorem card_localEvent : + Fintype.card (LocalEvent A) = + 4 * (2 * 2 ^ Fintype.card A) * (2 ^ (Fintype.card A * Fintype.card A)) ^ 5 := by + simp [LocalEvent, AlphabetReduction.InputCoordinate, Cube, Fintype.card_prod, + pow_succ, Nat.mul_assoc, Nat.mul_comm, Nat.mul_left_comm] + +omit [Nonempty A] in +theorem card_address [Fintype V] [Fintype E] : + Fintype.card (Address V E A) = + Fintype.card V * 2 ^ Fintype.card A + + Fintype.card E * 2 ^ (Fintype.card A * Fintype.card A) := by + simp [Address, Cube, Fintype.card_sum, Fintype.card_prod] + +theorem rejection_count_bound [Fintype E] (G : ConstraintGraph V E A) + (assignment : Address V E A → Bool) : + Fintype.card (LocalEvent A) * G.rejectionCount (decodedLabeling assignment) ≤ + 2048 * QueryIncidence.verifierRejectionCount (verifier G) assignment := by + classical + cases isEmpty_or_nonempty E with + | inl empty => + let := empty + simp [ConstraintGraph.rejectionCount, ConstraintGraph.rejectedDarts] + | inr inhabited => + let := inhabited + have h := average_gap G assignment + rw [average_eq_count, expect_rejection_eq_count, card_event, Nat.cast_mul, + div_div] at h + have he : (0 : ℝ) < Fintype.card E := by exact_mod_cast Fintype.card_pos + have hl : (0 : ℝ) < Fintype.card (LocalEvent A) := by + exact_mod_cast Fintype.card_pos + have hc := (div_le_div_iff₀ (mul_pos he (by norm_num)) (mul_pos he hl)).mp h + have hc' : + ((Fintype.card (LocalEvent A) : ℝ) * + (G.rejectionCount (decodedLabeling assignment) : ℝ)) * Fintype.card E ≤ + (2048 * (QueryIncidence.verifierRejectionCount (verifier G) assignment : ℝ)) * Fintype.card E := by + simpa only [ConstraintGraph.rejectionCount, ConstraintGraph.rejectedDarts, + mul_assoc, mul_comm, mul_left_comm] using hc + have result := (mul_le_mul_iff_left₀ he).mp hc' + exact_mod_cast result + +def honestAssignment (G : ConstraintGraph V E A) (labeling : V → A) : Address V E A → Bool + | .inl (v, tape) => tape (labeling v) + | .inr (e, tape) => tape (labeling (G.tail e), labeling (G.head e)) + +omit [Fintype A] [DecidableEq A] [Nonempty A] in +@[simp] theorem honest_vertexBlock (G : ConstraintGraph V E A) (labeling : V → A) (v : V) : + vertexBlock (honestAssignment G labeling) v = CodeComposition.codeword (labeling v) := rfl + +omit [Fintype A] [DecidableEq A] [Nonempty A] in +theorem honest_edgeOracle (G : ConstraintGraph V E A) (labeling : V → A) (e : E) + (h : G.edgeSatisfied labeling e = true) : + edgeOracle G (honestAssignment G labeling) e = + fun tape => tape ⟨(labeling (G.tail e), labeling (G.head e)), h⟩ := by + funext tape + exact UniformRestriction.extend_apply_of_mem (legal G e) tape + (labeling (G.tail e), labeling (G.head e)) h + +omit [Fintype A] [DecidableEq A] [Nonempty A] in +theorem honest_event (G : ConstraintGraph V E A) (labeling : V → A) + (satisfied : ∀ e, G.edgeSatisfied labeling e = true) (event : Event E A) : + (verifier G).accepts event (QueryIncidence.response (verifier G) (honestAssignment G labeling) event) = + true := by + rcases event with ⟨e, kind, k, f, g, r₀, r₁, r₂⟩ + rw [response_eq_local, honest_edgeOracle G labeling e (satisfied e)] + simp only [honest_vertexBlock] + exact AssignmentTester.event_perfect_completeness (AlphabetReduction.pairEncoding (G.accepts e)) + ⟨(labeling (G.tail e), labeling (G.head e)), satisfied e⟩ kind k + (restrictTape G e f) (restrictTape G e g) (restrictTape G e r₀) + (restrictTape G e r₁) (restrictTape G e r₂) + +def graph [DecidableEq V] [DecidableEq E] (G : ConstraintGraph V E A) : + ConstraintGraph (QueryIncidence.Vertex (Event E A) (Address V E A)) + (QueryIncidence.Dart (Event E A) 6) (QueryIncidence.Label 6) := QueryIncidence.graph (verifier G) (by omega) + +omit [DecidableEq A] [Nonempty A] in +theorem perfect_completeness [DecidableEq V] [DecidableEq E] (G : ConstraintGraph V E A) + (satisfied : G.Satisfiable) : (graph G).Satisfiable := by + obtain ⟨labeling, h⟩ := satisfied + exact QueryIncidence.satisfiable_of_verifier_satisfiable (verifier G) (by omega) + ⟨honestAssignment G labeling, honest_event G labeling h⟩ + +theorem gap_transfer [Fintype E] [DecidableEq V] [DecidableEq E] + (G : ConstraintGraph V E A) (a b : Nat) + (source : ∀ labeling : V → A, + a * Fintype.card E ≤ b * G.rejectionCount labeling) + (labeling : QueryIncidence.Vertex (Event E A) (Address V E A) → QueryIncidence.Label 6) : + a * Fintype.card (QueryIncidence.Dart (Event E A) 6) ≤ + (b * 12288) * (graph G).rejectionCount labeling := by + have verifierGap (assignment : Address V E A → Bool) : + a * Fintype.card (Event E A) ≤ + (b * 2048) * QueryIncidence.verifierRejectionCount (verifier G) assignment := by + rw [card_event] + calc + a * (Fintype.card E * Fintype.card (LocalEvent A)) = + Fintype.card (LocalEvent A) * (a * Fintype.card E) := by ac_rfl + _ ≤ Fintype.card (LocalEvent A) * (b * G.rejectionCount (decodedLabeling assignment)) := + Nat.mul_le_mul_left _ (source (decodedLabeling assignment)) + _ = b * (Fintype.card (LocalEvent A) * G.rejectionCount (decodedLabeling assignment)) := by + ac_rfl + _ ≤ b * (2048 * QueryIncidence.verifierRejectionCount (verifier G) assignment) := + Nat.mul_le_mul_left _ (rejection_count_bound G assignment) + _ = (b * 2048) * QueryIncidence.verifierRejectionCount (verifier G) assignment := by ac_rfl + have h := QueryIncidence.gap_transfer (verifier G) (by omega) a (b * 2048) verifierGap labeling + have hcoef : b * 2048 * 6 = b * 12288 := by omega + rw [hcoef] at h + exact h + +theorem alphabet_card : Fintype.card (QueryIncidence.Label 6) = 64 := QueryIncidence.six_query_alphabet + +end MinUncutGames.Foundations.PCP.AlphabetGraph + +end +namespace MinUncutGames.Foundations.PCP.AlphabetTable.Enumeration + +open MinUncutGames.Foundations.Hastad +open scoped BigOperators + +def bitValue (bit : Bool) : Nat := if bit then 1 else 0 + +def boolEquiv : Bool ≃ Fin 2 := finTwoEquiv.symm + +@[simp] theorem boolEquiv_val (bit : Bool) : (boolEquiv bit).val = bitValue bit := by + cases bit <;> rfl + +def productEquiv {A B : Type*} {a b : Nat} (left : A ≃ Fin a) (right : B ≃ Fin b) : + A × B ≃ Fin (a * b) := + (Equiv.prodCongr left right).trans finProdFinEquiv + +@[simp] theorem productEquiv_val {A B : Type*} {a b : Nat} + (left : A ≃ Fin a) (right : B ≃ Fin b) (x : A) (y : B) : + (productEquiv left right (x, y)).val = (left x).val * b + (right y).val := by + change (right y).val + b * (left x).val = _ + simp [Nat.mul_comm, Nat.add_comm] + +def sumEquiv {A B : Type*} {a b : Nat} (left : A ≃ Fin a) (right : B ≃ Fin b) : + A ⊕ B ≃ Fin (a + b) := + (Equiv.sumCongr left right).trans finSumFinEquiv + +@[simp] theorem sumEquiv_inl_val {A B : Type*} {a b : Nat} + (left : A ≃ Fin a) (right : B ≃ Fin b) (x : A) : + (sumEquiv left right (.inl x)).val = (left x).val := rfl + +@[simp] theorem sumEquiv_inr_val {A B : Type*} {a b : Nat} + (left : A ≃ Fin a) (right : B ≃ Fin b) (y : B) : + (sumEquiv left right (.inr y)).val = a + (right y).val := rfl + +def tapeCount (q : Nat) : Nat := 2 ^ q +def pairTapeCount (q : Nat) : Nat := 2 ^ (q * q) +def fiveTapeCount (q : Nat) : Nat := pairTapeCount q ^ 5 +def localCount (q : Nat) : Nat := 4 * (2 * tapeCount q) * fiveTapeCount q +def eventCount (m q : Nat) : Nat := m * localCount q +def addressCount (n m q : Nat) : Nat := n * tapeCount q + m * pairTapeCount q +def vertexCount (n m q : Nat) : Nat := eventCount m q + addressCount n m q +def dartCount (m q : Nat) : Nat := eventCount m q * 12 + +def cubeEquiv (q : Nat) : Cube (Fin q) ≃ Fin (tapeCount q) := + (Equiv.arrowCongr (Equiv.refl (Fin q)) boolEquiv).trans finFunctionFinEquiv + +def cubeRank {q : Nat} (tape : Cube (Fin q)) : Fin (tapeCount q) := cubeEquiv q tape +def cubeUnrank {q : Nat} (index : Fin (tapeCount q)) : Cube (Fin q) := + (cubeEquiv q).symm index + +@[simp] theorem cubeUnrank_cubeRank {q : Nat} (tape : Cube (Fin q)) : + cubeUnrank (cubeRank tape) = tape := (cubeEquiv q).symm_apply_apply tape + +@[simp] theorem cubeRank_cubeUnrank {q : Nat} (index : Fin (tapeCount q)) : + cubeRank (cubeUnrank index) = index := (cubeEquiv q).apply_symm_apply index + +theorem cubeUnrank_digit {q : Nat} (index : Fin (tapeCount q)) (i : Fin q) : + bitValue (cubeUnrank index i) = index.val / 2 ^ i.val % 2 := by + have digit : boolEquiv (cubeUnrank index i) = + (⟨index.val / 2 ^ i.val % 2, Nat.mod_lt _ (by decide)⟩ : Fin 2) := by + change boolEquiv (boolEquiv.symm _) = _ + exact boolEquiv.apply_symm_apply _ + simpa only [boolEquiv_val] using congrArg Fin.val digit + +theorem cubeEquiv_val (q : Nat) (tape : Cube (Fin q)) : + (cubeEquiv q tape).val = ∑ i : Fin q, bitValue (tape i) * 2 ^ i.val := by + change (finFunctionFinEquiv (fun i => boolEquiv (tape i))).val = _ + rw [finFunctionFinEquiv_apply] + simp only [boolEquiv_val] + +def pairIndex (q : Nat) : Fin q × Fin q ≃ Fin (q * q) := finProdFinEquiv + +theorem pairIndex_val (q : Nat) (i j : Fin q) : + (pairIndex q (i, j)).val = i.val * q + j.val := by + change j.val + q * i.val = _ + simp [Nat.mul_comm, Nat.add_comm] + +def pairCubeEquiv (q : Nat) : Cube (Fin q × Fin q) ≃ Fin (pairTapeCount q) := + (Equiv.arrowCongr (pairIndex q) (Equiv.refl Bool)).trans (cubeEquiv (q * q)) + +def pairCubeRank {q : Nat} (tape : Cube (Fin q × Fin q)) : Fin (pairTapeCount q) := + pairCubeEquiv q tape + +def pairCubeUnrank {q : Nat} (index : Fin (pairTapeCount q)) : Cube (Fin q × Fin q) := + (pairCubeEquiv q).symm index + +@[simp] theorem pairCubeUnrank_pairCubeRank {q : Nat} (tape : Cube (Fin q × Fin q)) : + pairCubeUnrank (pairCubeRank tape) = tape := (pairCubeEquiv q).symm_apply_apply tape + +@[simp] theorem pairCubeRank_pairCubeUnrank {q : Nat} (index : Fin (pairTapeCount q)) : + pairCubeRank (pairCubeUnrank index) = index := (pairCubeEquiv q).apply_symm_apply index + +theorem pairCubeEquiv_val (q : Nat) (tape : Cube (Fin q × Fin q)) : + (pairCubeEquiv q tape).val = + ∑ i : Fin (q * q), bitValue (tape ((pairIndex q).symm i)) * 2 ^ i.val := + cubeEquiv_val (q * q) _ + +def inputCoordinateEquiv (q : Nat) : + AlphabetReduction.InputCoordinate (Fin q) ≃ Fin (2 * tapeCount q) := + productEquiv boolEquiv (cubeEquiv q) + +def fivePairTapesEquiv (q : Nat) : + (Cube (Fin q × Fin q) × Cube (Fin q × Fin q) × Cube (Fin q × Fin q) × + Cube (Fin q × Fin q) × Cube (Fin q × Fin q)) ≃ Fin (fiveTapeCount q) := + (productEquiv (pairCubeEquiv q) + (productEquiv (pairCubeEquiv q) + (productEquiv (pairCubeEquiv q) + (productEquiv (pairCubeEquiv q) (pairCubeEquiv q))))).trans + (finCongr (by simp [fiveTapeCount, pow_succ, Nat.mul_assoc])) + +def localEventEquiv (q : Nat) : AlphabetGraph.LocalEvent (Fin q) ≃ Fin (localCount q) := + (productEquiv (Equiv.refl (Fin 4)) + (productEquiv (inputCoordinateEquiv q) (fivePairTapesEquiv q))).trans + (finCongr (by simp [localCount, Nat.mul_assoc])) + +def eventEquiv (m q : Nat) : + AlphabetGraph.Event (Fin m) (Fin q) ≃ Fin (eventCount m q) := + productEquiv (Equiv.refl (Fin m)) (localEventEquiv q) + +def addressEquiv (n m q : Nat) : + AlphabetGraph.Address (Fin n) (Fin m) (Fin q) ≃ Fin (addressCount n m q) := + sumEquiv (productEquiv (Equiv.refl (Fin n)) (cubeEquiv q)) + (productEquiv (Equiv.refl (Fin m)) (pairCubeEquiv q)) + +def vertexEquiv (n m q : Nat) : + QueryIncidence.Vertex (AlphabetGraph.Event (Fin m) (Fin q)) + (AlphabetGraph.Address (Fin n) (Fin m) (Fin q)) ≃ Fin (vertexCount n m q) := + sumEquiv (eventEquiv m q) (addressEquiv n m q) + +def dartEquiv (m q : Nat) : + QueryIncidence.Dart (AlphabetGraph.Event (Fin m) (Fin q)) 6 ≃ Fin (dartCount m q) := + (productEquiv (productEquiv (eventEquiv m q) (Equiv.refl (Fin 6))) boolEquiv).trans + (finCongr (by simp [dartCount, Nat.mul_assoc])) + +def labelEquiv : QueryIncidence.Label 6 ≃ Fin 64 := cubeEquiv 6 + +theorem labelEquiv_val (label : QueryIncidence.Label 6) : + (labelEquiv label).val = ∑ i : Fin 6, bitValue (label i) * 2 ^ i.val := + cubeEquiv_val 6 label + +@[simp] theorem inputCoordinateEquiv_val (q : Nat) (side : Bool) (tape : Cube (Fin q)) : + (inputCoordinateEquiv q (side, tape)).val = + bitValue side * tapeCount q + (cubeEquiv q tape).val := by + simp [inputCoordinateEquiv] + +theorem fivePairTapesEquiv_val (q : Nat) (f g r₀ r₁ r₂ : Cube (Fin q × Fin q)) : + (fivePairTapesEquiv q (f, g, r₀, r₁, r₂)).val = + (pairCubeEquiv q f).val * pairTapeCount q ^ 4 + + (pairCubeEquiv q g).val * pairTapeCount q ^ 3 + + (pairCubeEquiv q r₀).val * pairTapeCount q ^ 2 + + (pairCubeEquiv q r₁).val * pairTapeCount q + (pairCubeEquiv q r₂).val := by + simp [fivePairTapesEquiv, productEquiv_val, pow_succ, Nat.mul_assoc, Nat.add_assoc] + +theorem localEventEquiv_val (q : Nat) (kind : Fin 4) + (coordinate : AlphabetReduction.InputCoordinate (Fin q)) + (f g r₀ r₁ r₂ : Cube (Fin q × Fin q)) : + (localEventEquiv q (kind, coordinate, f, g, r₀, r₁, r₂)).val = + kind.val * (2 * tapeCount q * fiveTapeCount q) + + (inputCoordinateEquiv q coordinate).val * fiveTapeCount q + + (fivePairTapesEquiv q (f, g, r₀, r₁, r₂)).val := by + simp [localEventEquiv, productEquiv_val, Nat.add_assoc] + +@[simp] theorem eventEquiv_val (m q : Nat) (edge : Fin m) + (sample : AlphabetGraph.LocalEvent (Fin q)) : + (eventEquiv m q (edge, sample)).val = edge.val * localCount q + + (localEventEquiv q sample).val := by + change (localEventEquiv q sample).val + localCount q * edge.val = _ + simp [Nat.mul_comm, Nat.add_comm] + +@[simp] theorem addressEquiv_inl_val (n m q : Nat) (vertex : Fin n) + (tape : Cube (Fin q)) : + (addressEquiv n m q (.inl (vertex, tape))).val = + vertex.val * tapeCount q + (cubeEquiv q tape).val := by + change (cubeEquiv q tape).val + tapeCount q * vertex.val = _ + simp [Nat.mul_comm, Nat.add_comm] + +@[simp] theorem addressEquiv_inr_val (n m q : Nat) (edge : Fin m) + (tape : Cube (Fin q × Fin q)) : + (addressEquiv n m q (.inr (edge, tape))).val = + n * tapeCount q + (edge.val * pairTapeCount q + (pairCubeEquiv q tape).val) := by + change n * tapeCount q + ((pairCubeEquiv q tape).val + pairTapeCount q * edge.val) = _ + simp [Nat.mul_comm, Nat.add_comm] + +@[simp] theorem vertexEquiv_event_val (n m q : Nat) + (event : AlphabetGraph.Event (Fin m) (Fin q)) : + (vertexEquiv n m q (.inl event)).val = (eventEquiv m q event).val := rfl + +@[simp] theorem vertexEquiv_vertexAddress_val (n m q : Nat) (vertex : Fin n) + (tape : Cube (Fin q)) : + (vertexEquiv n m q (.inr (.inl (vertex, tape)))).val = + eventCount m q + (vertex.val * tapeCount q + (cubeEquiv q tape).val) := by + change eventCount m q + (addressEquiv n m q (.inl (vertex, tape))).val = _ + rw [addressEquiv_inl_val] + +@[simp] theorem vertexEquiv_edgeAddress_val (n m q : Nat) (edge : Fin m) + (tape : Cube (Fin q × Fin q)) : + (vertexEquiv n m q (.inr (.inr (edge, tape)))).val = + eventCount m q + (n * tapeCount q + + (edge.val * pairTapeCount q + (pairCubeEquiv q tape).val)) := by + change eventCount m q + (addressEquiv n m q (.inr (edge, tape))).val = _ + rw [addressEquiv_inr_val] + +@[simp] theorem dartEquiv_val (m q : Nat) + (event : AlphabetGraph.Event (Fin m) (Fin q)) (slot : Fin 6) (orientation : Bool) : + (dartEquiv m q ((event, slot), orientation)).val = + (eventEquiv m q event).val * 12 + slot.val * 2 + bitValue orientation := by + change (boolEquiv orientation).val + 2 * (slot.val + 6 * (eventEquiv m q event).val) = _ + rw [boolEquiv_val] + omega + +theorem dartEquiv_reverse_val (m q : Nat) + (event : AlphabetGraph.Event (Fin m) (Fin q)) (slot : Fin 6) (orientation : Bool) : + (dartEquiv m q (QueryIncidence.reverse ((event, slot), orientation))).val = + (eventEquiv m q event).val * 12 + slot.val * 2 + bitValue (!orientation) := + dartEquiv_val m q event slot (!orientation) + +def ordered {A : Type*} {count : Nat} (order : A ≃ Fin count) : List A := + List.ofFn order.symm + +@[simp] theorem ordered_length {A : Type*} {count : Nat} (order : A ≃ Fin count) : + (ordered order).length = count := by simp [ordered] + +theorem mem_ordered {A : Type*} {count : Nat} (order : A ≃ Fin count) (x : A) : + x ∈ ordered order := by + simp only [ordered, List.mem_ofFn] + exact ⟨order x, order.symm_apply_apply x⟩ + +theorem ordered_nodup {A : Type*} {count : Nat} (order : A ≃ Fin count) : + (ordered order).Nodup := by + rw [ordered, List.nodup_ofFn] + exact order.symm.injective + +@[simp] theorem ordered_refl (n : Nat) : ordered (Equiv.refl (Fin n)) = List.finRange n := rfl + +@[simp] theorem ordered_bool : ordered boolEquiv = [false, true] := rfl + +theorem ordered_trans_finCongr {A : Type*} {a b : Nat} + (order : A ≃ Fin a) (sameCount : a = b) : + ordered (order.trans (finCongr sameCount)) = ordered order := by + cases sameCount + rfl + +theorem ordered_product {A B : Type*} {a b : Nat} + (left : A ≃ Fin a) (right : B ≃ Fin b) : + ordered (productEquiv left right) = + (ordered left).flatMap (fun x => (ordered right).map (fun y => (x, y))) := by + have atIndex (i : Fin a) (j : Fin b) (h : i.val * b + j.val < a * b) : + (productEquiv left right).symm ⟨i.val * b + j.val, h⟩ = + (left.symm i, right.symm j) := by + have same : (⟨i.val * b + j.val, h⟩ : Fin (a * b)) = finProdFinEquiv (i, j) := by + apply Fin.ext + simp [finProdFinEquiv, Nat.mul_comm, Nat.add_comm] + rw [same] + simp [productEquiv] + unfold ordered + rw [List.ofFn_mul] + simp only [atIndex, List.flatMap_def, List.map_ofFn, Function.comp_def] + +theorem ordered_sum {A B : Type*} {a b : Nat} + (left : A ≃ Fin a) (right : B ≃ Fin b) : + ordered (sumEquiv left right) = + (ordered left).map Sum.inl ++ (ordered right).map Sum.inr := by + have atLeft (i : Fin a) : + (sumEquiv left right).symm (i.castLE (Nat.le_add_right a b)) = + Sum.inl (left.symm i) := by + change (Equiv.sumCongr left right).symm + (finSumFinEquiv.symm (Fin.castAdd b i)) = _ + rw [finSumFinEquiv_symm_apply_castAdd] + rfl + have atRight (j : Fin b) : + (sumEquiv left right).symm (j.natAdd a) = Sum.inr (right.symm j) := by + change (Equiv.sumCongr left right).symm (finSumFinEquiv.symm (j.natAdd a)) = _ + rw [finSumFinEquiv_symm_apply_natAdd] + rfl + unfold ordered + rw [List.ofFn_add] + simp only [atLeft, atRight, List.map_ofFn, Function.comp_def] + +def localEvents (q : Nat) : List (AlphabetGraph.LocalEvent (Fin q)) := + ordered (localEventEquiv q) + +@[simp] theorem localEvents_length (q : Nat) : (localEvents q).length = localCount q := + ordered_length _ + +theorem ordered_event (m q : Nat) : + ordered (eventEquiv m q) = + (List.finRange m).flatMap (fun edge => (localEvents q).map (fun event => (edge, event))) := by + change ordered (productEquiv (Equiv.refl (Fin m)) (localEventEquiv q)) = _ + rw [ordered_product, ordered_refl] + rfl + +theorem ordered_dart (m q : Nat) : + ordered (dartEquiv m q) = + (List.finRange m).flatMap (fun edge => + (localEvents q).flatMap (fun event => + (List.finRange 6).flatMap (fun slot => + [(((edge, event), slot), false), (((edge, event), slot), true)]))) := by + rw [dartEquiv] + erw [ordered_trans_finCongr] + rw [ordered_product, ordered_product, ordered_event] + simp only [ordered_refl, ordered_bool, List.flatMap_assoc, List.flatMap_map, + List.map_cons, List.map_nil] + +@[simp] theorem card_cube (q : Nat) : Fintype.card (Cube (Fin q)) = tapeCount q := by + simpa using Fintype.card_congr (cubeEquiv q) + +@[simp] theorem card_pairCube (q : Nat) : + Fintype.card (Cube (Fin q × Fin q)) = pairTapeCount q := by + simpa using Fintype.card_congr (pairCubeEquiv q) + +@[simp] theorem card_localEvent (q : Nat) : + Fintype.card (AlphabetGraph.LocalEvent (Fin q)) = localCount q := by + simpa using Fintype.card_congr (localEventEquiv q) + +@[simp] theorem card_event (m q : Nat) : + Fintype.card (AlphabetGraph.Event (Fin m) (Fin q)) = eventCount m q := by + simpa using Fintype.card_congr (eventEquiv m q) + +@[simp] theorem card_address (n m q : Nat) : + Fintype.card (AlphabetGraph.Address (Fin n) (Fin m) (Fin q)) = addressCount n m q := by + simpa using Fintype.card_congr (addressEquiv n m q) + +@[simp] theorem card_vertex (n m q : Nat) : + Fintype.card (QueryIncidence.Vertex (AlphabetGraph.Event (Fin m) (Fin q)) + (AlphabetGraph.Address (Fin n) (Fin m) (Fin q))) = vertexCount n m q := by + simpa using Fintype.card_congr (vertexEquiv n m q) + +@[simp] theorem card_dart (m q : Nat) : + Fintype.card (QueryIncidence.Dart (AlphabetGraph.Event (Fin m) (Fin q)) 6) = + dartCount m q := by + simpa using Fintype.card_congr (dartEquiv m q) + +@[simp] theorem localCount_formula (q : Nat) : + localCount q = 4 * (2 * 2 ^ q) * (2 ^ (q * q)) ^ 5 := rfl + +end MinUncutGames.Foundations.PCP.AlphabetTable.Enumeration + +namespace MinUncutGames.Foundations.PCP.AlphabetTable.Queries + +open MinUncutGames.Foundations.Hastad + +abbrev RawQuery (q : Nat) := + (Bool × Cube (Fin q)) ⊕ Cube (Fin q × Fin q) + +abbrev LocalEvent (q : Nat) := AlphabetGraph.LocalEvent (Fin q) + +def mask {q : Nat} (P : Fin q → Fin q → Bool) (f : Cube (Fin q × Fin q)) : + Cube (Fin q × Fin q) := fun p => if P p.1 p.2 then f p else false + +def xorTape {A : Type*} (f g : Cube A) : Cube A := fun a => f a ^^ g a + +def andTape {A : Type*} (f g : Cube A) : Cube A := fun a => f a && g a + +def inputPairTape {q : Nat} (k : Bool × Cube (Fin q)) : Cube (Fin q × Fin q) := + fun p => if k.1 then k.2 p.2 else k.2 p.1 + +def query {q : Nat} (P : Fin q → Fin q → Bool) (event : LocalEvent q) + (slot : Fin 6) : RawQuery q := + match event with + | (kind, k, f, g, r₀, r₁, r₂) => + if kind = 0 then + if slot = 0 then .inr (mask P f) else + if slot = 1 then .inr (mask P g) else .inr (mask P (xorTape f g)) + else if kind = 1 then + if slot = 0 then .inr (mask P r₀) else + if slot = 1 then .inr (mask P (xorTape r₀ (andTape f g))) else + if slot = 2 then .inr (mask P r₁) else + if slot = 3 then .inr (mask P (xorTape r₁ f)) else + if slot = 4 then .inr (mask P r₂) else .inr (mask P (xorTape r₂ g)) + else if kind = 2 then + if slot = 0 then .inr (mask P r₀) else + .inr (mask P (xorTape r₀ (fun _ => true))) + else + if slot = 0 then .inl k else + if slot = 1 then .inr (mask P r₀) else + .inr (mask P (xorTape r₀ (inputPairTape k))) + +def globalize {q : Nat} {V E : Type*} (tail head : V) (edge : E) : + RawQuery q → AlphabetGraph.Address V E (Fin q) + | .inl (side, tape) => .inl ((if side then head else tail), tape) + | .inr tape => .inr (edge, tape) + +@[simp] theorem mask_idempotent {q : Nat} (P : Fin q → Fin q → Bool) + (f : Cube (Fin q × Fin q)) : mask P (mask P f) = mask P f := by + funext p + cases hp : P p.1 p.2 <;> simp [mask, hp] + +theorem mask_of_empty {q : Nat} (P : Fin q → Fin q → Bool) + (empty : ∀ a b, P a b = false) (f : Cube (Fin q × Fin q)) : + mask P f = fun _ => false := by + funext p + simp [mask, empty] + +theorem query_is_masked {q : Nat} (P : Fin q → Fin q → Bool) + (event : LocalEvent q) (slot : Fin 6) : + match query P event slot with + | .inl _ => True + | .inr tape => mask P tape = tape := by + rcases event with ⟨kind, k, f, g, r₀, r₁, r₂⟩ + by_cases hk₀ : kind = 0 <;> by_cases hk₁ : kind = 1 <;> by_cases hk₂ : kind = 2 <;> + simp only [query, hk₀, hk₁, hk₂, ite_true, ite_false] <;> + split_ifs <;> simp + +def extendQuery {q : Nat} (P : Fin q → Fin q → Bool) : + AlphabetReduction.InputCoordinate (Fin q) ⊕ Cube (AlphabetReduction.LegalPair P) → + RawQuery q + | .inl k => .inl k + | .inr tape => .inr (UniformRestriction.extend (fun p : Fin q × Fin q => P p.1 p.2 = true) tape) + +theorem query_eq_extend_eventQueries {q : Nat} (P : Fin q → Fin q → Bool) + (kind : Fin 4) (k : AlphabetReduction.InputCoordinate (Fin q)) + (f g r₀ r₁ r₂ : Cube (Fin q × Fin q)) (slot : Fin 6) : + query P (kind, k, f, g, r₀, r₁, r₂) slot = + extendQuery P (AssignmentTester.eventQueries (AlphabetReduction.pairEncoding P) kind k + (UniformRestriction.restrict (fun p : Fin q × Fin q => P p.1 p.2 = true) f) + (UniformRestriction.restrict (fun p : Fin q × Fin q => P p.1 p.2 = true) g) + (UniformRestriction.restrict (fun p : Fin q × Fin q => P p.1 p.2 = true) r₀) + (UniformRestriction.restrict (fun p : Fin q × Fin q => P p.1 p.2 = true) r₁) + (UniformRestriction.restrict (fun p : Fin q × Fin q => P p.1 p.2 = true) r₂) slot) := by + by_cases hk₀ : kind = 0 <;> by_cases hk₁ : kind = 1 <;> by_cases hk₂ : kind = 2 <;> + simp only [query, AssignmentTester.eventQueries, hk₀, hk₁, hk₂, ite_true, ite_false] + all_goals split_ifs <;> simp_all only [extendQuery] + all_goals rfl + +theorem globalize_extendQuery {q : Nat} {V E : Type*} + (G : ConstraintGraph V E (Fin q)) (e : E) + (x : AlphabetReduction.InputCoordinate (Fin q) ⊕ + Cube (AlphabetReduction.LegalPair (G.accepts e))) : + globalize (G.tail e) (G.head e) e (extendQuery (G.accepts e) x) = + AlphabetGraph.globalizeQuery G e x := by + cases x with + | inl k => cases k; rfl + | inr tape => rfl + +theorem globalize_query {q : Nat} {V E : Type*} + (G : ConstraintGraph V E (Fin q)) (e : E) (event : LocalEvent q) (slot : Fin 6) : + globalize (G.tail e) (G.head e) e (query (G.accepts e) event slot) = + (AlphabetGraph.verifier G).query (e, event) slot := by + rcases event with ⟨kind, k, f, g, r₀, r₁, r₂⟩ + rw [query_eq_extend_eventQueries] + exact globalize_extendQuery G e _ + +end MinUncutGames.Foundations.PCP.AlphabetTable.Queries + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/AlphabetReduction.lean b/lean/OAI/Computability/MinUncut/Machines/AlphabetReduction.lean new file mode 100644 index 0000000000000000000000000000000000000000..528be2c8502e5b5ee0bb366023b351f71ccd6e63 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/AlphabetReduction.lean @@ -0,0 +1,59 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.PoweringTableSemantics + +namespace OAI + +section +noncomputable section + +namespace MinUncutGames.Foundations.PCP.AlphabetReduction + +open MinUncutGames.Foundations.Hastad +open CodeComposition + +variable {A : Type*} [Fintype A] [DecidableEq A] [Nonempty A] + +abbrev LegalPair (accepts : A → A → Bool) := + {p : A × A // accepts p.1 p.2 = true} + +abbrev InputCoordinate (A : Type*) := Bool × Cube A + +def pairEncoding (accepts : A → A → Bool) (p : LegalPair accepts) : + InputCoordinate A → Bool := + pairWord (codeword p.1.1) (codeword p.1.2) + +def edgeTesterReject (accepts : A → A → Bool) (left right : Cube A → Bool) + (F : Cube (LegalPair accepts) → Bool) : ℝ := + AssignmentTester.explicitTesterReject (pairEncoding accepts) (pairWord left right) F + +theorem rejected_edge_tester_bound (accepts : A → A → Bool) + (left right : Cube A → Bool) + (F : Cube (LegalPair accepts) → Bool) + (hbad : accepts (nearest left) (nearest right) = false) : + 1 / 2048 ≤ edgeTesterReject accepts left right F := by + have hfar (p : LegalPair accepts) : + (1 / 8 : ℝ) ≤ AssignmentTester.distance (pairWord left right) (pairEncoding accepts p) := by + have h := rejected_pair_far accepts left right hbad p.1.1 p.1.2 p.2 + convert h using 1 + rfl + have h := AssignmentTester.explicit_proximity_soundness (pairEncoding accepts) + (pairWord left right) F (δ := 1 / 8) (by norm_num) (by norm_num) hfar + norm_num at h + exact h + +omit [Nonempty A] in +theorem honest_edge_tester (accepts : A → A → Bool) (a b : A) + (hab : accepts a b = true) : + edgeTesterReject accepts (codeword a) (codeword b) + (fun f => f ⟨(a, b), hab⟩) = 0 := by + unfold edgeTesterReject + rw [AssignmentTester.explicitTesterReject_eq] + exact AssignmentTester.tester_perfect_completeness + (pairEncoding accepts) ⟨(a, b), hab⟩ + +end MinUncutGames.Foundations.PCP.AlphabetReduction + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/AlphabetRetraction.lean b/lean/OAI/Computability/MinUncut/Machines/AlphabetRetraction.lean new file mode 100644 index 0000000000000000000000000000000000000000..06030f00c009832d2f571783d4a489cdc450bf0a --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/AlphabetRetraction.lean @@ -0,0 +1,75 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.PoweringTableSemantics +import OAI.Computability.MinUncut.PCP.InitialGraph + +namespace OAI + +section +namespace MinUncutGames.Foundations.PCP.AlphabetRetraction + +variable {V E A B : Type*} + +def pullback (G : ConstraintGraph V E A) (decode : B → A) : ConstraintGraph V E B where + reverse := G.reverse + reverse_involutive := G.reverse_involutive + tail := G.tail + accepts := fun e b c => G.accepts e (decode b) (decode c) + reverse_accepts := fun e b c => G.reverse_accepts e (decode b) (decode c) + +@[simp] theorem edgeSatisfied_pullback (G : ConstraintGraph V E A) + (decode : B → A) (labeling : V → B) (e : E) : + (pullback G decode).edgeSatisfied labeling e = + G.edgeSatisfied (decode ∘ labeling) e := rfl + +@[simp] theorem rejectionCount_pullback [Fintype E] (G : ConstraintGraph V E A) + (decode : B → A) (labeling : V → B) : + (pullback G decode).rejectionCount labeling = + G.rejectionCount (decode ∘ labeling) := rfl + +theorem satisfiable_pullback_iff (G : ConstraintGraph V E A) + (decode : B → A) (encode : A → B) (sectionLaw : ∀ a, decode (encode a) = a) : + (pullback G decode).Satisfiable ↔ G.Satisfiable := by + constructor + · rintro ⟨labeling, h⟩ + exact ⟨decode ∘ labeling, h⟩ + · rintro ⟨labeling, h⟩ + refine ⟨encode ∘ labeling, fun e => ?_⟩ + change G.accepts e (decode (encode (labeling (G.tail e)))) + (decode (encode (labeling (G.head e)))) = true + simpa only [ConstraintGraph.edgeSatisfied, sectionLaw] using h e + +abbrev Label64 := QueryIncidence.Label 6 + +def decode64 (label : Label64) : InitialGraph.Label := (label 0, label 1, label 2) + +def encode64 (label : InitialGraph.Label) : Label64 := + fun i => if i = 0 then label.1 else if i = 1 then label.2.1 else label.2.2 + +@[simp] theorem decode_encode64 (label : InitialGraph.Label) : + decode64 (encode64 label) = label := by + rcases label with ⟨a, b, c⟩ + rfl + +def initial64 (F : MinUncutGames.Foundations.Target.Formula) : + ConstraintGraph (InitialGraph.CompactVertex F) (InitialGraph.CompactDart F) Label64 := + pullback (InitialGraph.build F) decode64 + +theorem initial64_satisfiable_iff (F : MinUncutGames.Foundations.Target.Formula) : + (initial64 F).Satisfiable ↔ F.Satisfiable := + (satisfiable_pullback_iff (InitialGraph.build F) decode64 encode64 decode_encode64).trans + (InitialGraph.build_satisfiable_iff F) + +theorem initial64_alphabet : Fintype.card Label64 = 64 := + QueryIncidence.six_query_alphabet + +theorem initial64_inverse_size_gap (F : MinUncutGames.Foundations.Target.Formula) + (unsat : ¬ F.Satisfiable) (labeling : InitialGraph.CompactVertex F → Label64) : + Fintype.card (InitialGraph.CompactDart F) ≤ + (6 * F.clauses.length + 1) * (initial64 F).rejectionCount labeling := + InitialGraph.build_inverse_size_gap F unsat (decode64 ∘ labeling) + +end MinUncutGames.Foundations.PCP.AlphabetRetraction + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/AlphabetSize.lean b/lean/OAI/Computability/MinUncut/Machines/AlphabetSize.lean new file mode 100644 index 0000000000000000000000000000000000000000..62dbd72a6befcdc2ce2afaa16c4c4fced9295f23 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/AlphabetSize.lean @@ -0,0 +1,51 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.FiniteAlphabetBounds +import OAI.Computability.MinUncut.Search.ArithmeticExpression + +namespace OAI + +section +noncomputable section +open scoped BigOperators +namespace MinUncut.Outer +open MinUncut.Inner MinUncut.FiniteProof +attribute [local instance] Classical.propDecidable +variable {Name I : Type*} [Fintype I] [Fintype Name] +lemma variable_card_bound {L : ℕ} (hN : Fintype.card Name≤L) : + Fintype.card (FamilyVariable Name I)≤ + ((2*L^3)^Fintype.card I+(L+2*L^3)^Fintype.card I)*2^(2^(3*Fintype.card I)) := by + have hcard : Fintype.card (FamilyVariable Name I)≤ + ((2*Fintype.card Name^3)^Fintype.card I+ + (Fintype.card Name+2*Fintype.card Name^3)^Fintype.card I)*2^(2^(3*Fintype.card I)) := by + rw [← familyQuestion_card] + exact familyVariable_card_le + have h3 := Nat.mul_le_mul_left 2 (Nat.pow_le_pow_left hN 3) + have ha := Nat.pow_le_pow_left h3 (Fintype.card I) + have hb := Nat.pow_le_pow_left (Nat.add_le_add hN h3) (Fintype.card I) + exact hcard.trans (Nat.mul_le_mul_right _ (Nat.add_le_add ha hb)) +lemma variable_nat_card_bound {L : ℕ} (hN : Fintype.card Name≤L) : + Nat.card (FamilyVariable Name I)≤ + ((2*L^3)^Fintype.card I+(L+2*L^3)^Fintype.card I)*2^(2^(3*Fintype.card I)) := by + rw [Nat.card_eq_fintype_card] + exact variable_card_bound (Name := Name) (I := I) hN + +def alphabetSizePolynomial (t : ℕ) : Polynomial ℕ := + ((Polynomial.C 2*Polynomial.X^3)^t+ + (Polynomial.X+Polynomial.C 2*Polynomial.X^3)^t)*Polynomial.C (2^(2^(3*t))) + +lemma alphabetSizePolynomial_bound {Name : Type*} [Fintype Name] (t L : ℕ) + (hN : Fintype.card Name≤L) : + Fintype.card (FamilyVariable Name (Fin t))≤(alphabetSizePolynomial t).eval L := by + have hh := variable_nat_card_bound (Name := Name) (I := Fin t) (L := L) hN + have hr : ((2*L^3)^Fintype.card (Fin t)+(L+2*L^3)^Fintype.card (Fin t))* + 2^(2^(3*Fintype.card (Fin t)))=(alphabetSizePolynomial t).eval L := by + simp only [Fintype.card_fin,alphabetSizePolynomial,Polynomial.eval_mul,Polynomial.eval_add, + Polynomial.eval_pow,Polynomial.eval_C,Polynomial.eval_X] + rw [← Nat.card_eq_fintype_card] + exact Nat.le_trans hh (Nat.le_of_eq hr) +end MinUncut.Outer + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/ArenaMachineProgram.lean b/lean/OAI/Computability/MinUncut/Machines/ArenaMachineProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..725bbdf5de6c30fc1ebb461f50aae34738e0dc75 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/ArenaMachineProgram.lean @@ -0,0 +1,91 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.CodeContinuations + +namespace OAI + +section +namespace MinUncut.Costed.Arena + +def keepTick (v : List ℕ) : List ℕ := v.headI::rawTick v.tail +noncomputable def keepTickProgram : PolyProgram keepTick := + PolyProgram.head.cons (tickProgram.comp PolyProgram.tail) + +lemma keepTick_safe (v : List ℕ) : + (keepTick v).length≤v.length+10 ∧ maximum (keepTick v)≤ maximum v+3 := by + have hh := rawTick_safe v.tail + have ht : v.tail=v.drop 1 := (List.drop_one (l := v)).symm + have hm := maximum_drop v 1 + have hl : v.tail.length≤v.length := by cases v <;> simp + have he := head_le_maximum v + rw [←ht] at hm + simp only [keepTick,List.length_cons,maximum_cons] + constructor + · omega + · exact max_le (by omega) (by omega) + +lemma keepTick_iter (B i : ℕ) (v : List ℕ) : + keepTick^[i] (B::v)=B::rawTick^[i] v := by + induction i with + | zero => rfl + | succ i ih => rw [Function.iterate_succ_apply',ih]; + change B::rawTick (rawTick^[i] v)=_; rw [Function.iterate_succ_apply'] + +def control (v : List ℕ) : List ℕ := keepTick^[3*v.headI+1] v +noncomputable def controlProgram : PolyProgram control := + (PolyProgram.safeIterate keepTickProgram 10 3 keepTick_safe).comp + ((Expr.add (.mul (c 3) (r 0)) (c 1)).program.cons PolyProgram.id) + +lemma outputStep_safe (v : List ℕ) : + (outputStep v).length≤v.length+4 ∧ maximum (outputStep v)≤ maximum v+1 := by + have hr (j : Fin 4) : (outRead j).eval v≤ maximum v := by + change (v.drop _).headI≤_ + exact (head_le_maximum _).trans (maximum_drop v _) + have h1 := reg_le_maximum v 1 + have h2 := reg_le_maximum v 2 + have h0 := hr 0 + have h3 := hr 1 + have ht := maximum_drop v 3 + simp only [outputStep] + split_ifs + · constructor <;> omega + · simp only [List.cons_append,List.nil_append,List.length_cons,List.length_drop,maximum_cons] + constructor + · omega + · exact max_le (by omega) (max_le (by omega) (max_le (by omega) (max_le (by omega) (by omega)))) + +noncomputable def outputLoopProgram : PolyProgram (fun v=>outputStep^[v.headI] v.tail) := + PolyProgram.safeIterate outputStepProgram 4 1 outputStep_safe + +def prepareOutput (v : List ℕ) : List ℕ := + [v.headI,(r 3).eval v,(r 5).eval v,0,2]++v.drop 6 +noncomputable def prepareOutputProgram : PolyProgram prepareOutput := + PolyProgram.head.cons ((r 3).program.cons ((r 5).program.cons + ((c 0).program.cons ((c 2).program.cons (PolyProgram.drop 6))))) + +def universalRaw (v : List ℕ) : List ℕ := + let z := prepareOutput (control v) + (outputStep^[z.headI] z.tail).drop 3 + +noncomputable def universalProgram : PolyProgram universalRaw := + (PolyProgram.drop 3).comp (outputLoopProgram.comp (prepareOutputProgram.comp controlProgram)) + +lemma universalRaw_spec {c v w B} (hr : Runs c v w B) (hl : w.length≤B) (base : Heap) : + ∃h,universalRaw (B::(initialState c v base).encode)=w.reverse++2::words h := by + obtain ⟨t,ht,hc⟩ := hr + obtain ⟨h,out,ho,he⟩ := CodeRun.interpreted hc base ht + refine ⟨h,?_⟩ + have hh : control (B::(initialState c v base).encode)=B::(State.mk 2 0 out 0 h).encode := by + simpa only [control,List.headI_cons,keepTick_iter] using congrArg (List.cons B) he + simp only [universalRaw,hh] + have hp : prepareOutput (B::(State.mk 2 0 out 0 h).encode)=B::(OutputState.mk out h []).encode := rfl + rw [hp] + simp only [List.headI_cons,List.tail_cons] + rw [ho.output_padded [] hl] + simp only [List.append_nil,OutputState.encode,List.cons_append,List.nil_append] + rfl + +end MinUncut.Costed.Arena + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/CodeFiniteMachine.lean b/lean/OAI/Computability/MinUncut/Machines/CodeFiniteMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..ca5f8a160f06ae9362d6bc20d488a29b98ad1a24 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/CodeFiniteMachine.lean @@ -0,0 +1,179 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineSubstitution +import OAI.Computability.MinUncut.Estimates.TM2Costed + +namespace OAI + +section + +namespace MinUncut.Costed +open _root_.Turing _root_.OAI.Turing _root_.Turing.PartrecToTM2 _root_.OAI.Turing.PartrecToTM2 Turing.ToPartrec +noncomputable section + +local instance : Fintype K' := ⟨{.main,.rev,.aux,.stack}, by intro k; cases k <;> simp⟩ + +def codeMachine (c : Code) : FinTM2 where + K := K' + k₀ := .main + k₁ := .main + Γ _ := Γ' + Λ := codeSupp c .halt + main := ⟨trNormal c .halt,codeSupp_self c .halt (trStmts₁_self _)⟩ + σ := Option Γ' + initialState := none + m := FiniteControl.program (codeSupp c .halt) tr + (fun _ h => codeSupp_supports (Finset.Subset.refl _) _ h) + +lemma codeMachine_finiteAlphabet (c : Code) (k : (codeMachine c).K) : + Finite ((codeMachine c).Γ k) := inferInstanceAs (Finite Γ') + +lemma codeMachine_init (c : Code) (v : List ℕ) : + FiniteControl.project (codeSupp c .halt) (initList (codeMachine c) (trList v))= + ⟨some (trNormal c .halt),none,K'.elim (trList v) [] [] []⟩ := by + change TM2.Cfg.mk _ _ _=TM2.Cfg.mk _ _ _ + congr 1 + funext k + cases k <;> rfl + +lemma codeMachine_halt (c : Code) (v : List ℕ) : + FiniteControl.project (codeSupp c .halt) (haltList (codeMachine c) (trList v))= + ⟨none,none,K'.elim (trList v) [] [] []⟩ := by + change TM2.Cfg.mk _ _ _=TM2.Cfg.mk _ _ _ + congr 1 + funext k + cases k <;> rfl + +def CodeRun.finiteMachine {c v w t} (h : CodeRun c v w t) : + TM2OutputsInTime (codeMachine c) (trList v) (some (trList w)) (t+1) := by + apply Classical.choice + obtain ⟨s,ht⟩ := h.compiled .halt none [] + have he : Within (TM2.step tr) (t+1) + ⟨some (trNormal c .halt),none,K'.elim (trList v) [] [] []⟩ + ⟨none,none,K'.elim (trList w) [] [] []⟩ := + ht.trans (within_one rfl) + obtain ⟨n,hn,hsteps⟩ := he + have hi := FiniteControl.projected_iterate (codeMachine c).step (TM2.step tr) + (FiniteControl.project (codeSupp c .halt)) + (FiniteControl.project_step _ _ (fun _ h => codeSupp_supports (Finset.Subset.refl _) _ h)) n (some (initList (codeMachine c) (trList v))) + have hs : Steps (codeMachine c).step n + (initList (codeMachine c) (trList v)) (haltList (codeMachine c) (trList w)) := by + apply Option.map_injective (FiniteControl.project_injective (codeSupp c .halt)) + dsimp only [Steps] at hsteps ⊢ + exact hi.trans ((congrArg + (fun cfg : Option (TM2.Cfg (fun _ : K' => Γ') Λ' (Option Γ')) => + (fun x => x.bind (TM2.step tr))^[n] cfg) + (congrArg some (codeMachine_init c v))).trans + (hsteps.trans (congrArg some (codeMachine_halt c w)).symm)) + exact ⟨steps_timed hs hn⟩ + +end +end MinUncut.Costed + +end +section +namespace MinUncut.Costed +open _root_.Turing _root_.OAI.Turing _root_.Turing.PartrecToTM2 _root_.OAI.Turing.PartrecToTM2 Turing.ToPartrec +open MinUncutGames.Foundations.Complexity +noncomputable section +namespace BooleanAdapter + +def encodedWord (b : Bool) : List Γ' := if b then [.bit1,.cons] else [.cons] +def encodeMachine : FinTM2 := WordTransducer.machine () (fun (_ : Unit) (_ : Bool) => ()) + (fun _ b => encodedWord b) + +lemma encode_output (v : List Bool) : + WordTransducer.output (fun (_ : Unit) (_ : Bool) => ()) (fun _ b => encodedWord b) () v= + trList (v.map Bool.toNat) := by + induction v with + | nil => rfl + | cons b v ih => + simp only [List.map_cons,trList,WordTransducer.output] + rw [ih] + cases b <;> rfl + +def next (q : Bool) : Γ' → Bool + | .bit1 => true + | .cons | .consₗ => false + | .bit0 => q + +def emit (q : Bool) : Γ' → List Bool + | .cons => [q] + | _ => [] + +def decodeMachine : FinTM2 := WordTransducer.machine false next emit + +lemma decode_output (v : List Bool) : + WordTransducer.output next emit false (trList (v.map Bool.toNat))=v := by + induction v with + | nil => rfl + | cons b v ih => + cases b <;> simp [WordTransducer.output,next,emit,trList,trNat,trNum,trPosNum,ih] + +lemma trList_bool_length (v : List Bool) : + (trList (v.map Bool.toNat)).length≤2*v.length := by + induction v with + | nil => rfl + | cons b v ih => + cases b <;> simp [trList,trNat,trNum,trPosNum] <;> omega + +def encode_run (v : List Bool) : + TM2OutputsInTime encodeMachine v (some (trList (v.map Bool.toNat))) + (2*v.length+(trList (v.map Bool.toNat)).length+2) := by + have h := WordTransducer.outputsInTime () (fun (_ : Unit) (_ : Bool) => ()) (fun _ b => encodedWord b) v + erw [encode_output] at h + exact h + +def decode_run (v : List Bool) : + TM2OutputsInTime decodeMachine (trList (v.map Bool.toNat)) (some v) + (2*(trList (v.map Bool.toNat)).length+v.length+2) := by + have h := WordTransducer.outputsInTime false next emit (trList (v.map Bool.toNat)) + erw [decode_output] at h + exact h + +end BooleanAdapter +open BooleanAdapter + +def booleanCodeMachine (c : Code) : FinTM2 := + MachineSequential.machine + (MachineSequential.machine encodeMachine (codeMachine c) id .cons) + decodeMachine id .cons + +lemma sequential_finiteAlphabet (a b : FinTM2) (r : a.Γ a.k₁→b.Γ b.k₀) + (fallback : b.Γ b.k₀) (ha : ∀k,Finite (a.Γ k)) (hb : ∀k,Finite (b.Γ k)) + (k : (MachineSequential.machine a b r fallback).K) : + Finite ((MachineSequential.machine a b r fallback).Γ k) := by + rcases k with k | k + · exact ha k + · rcases k with k | k + · exact hb k + · exact hb b.k₀ + +lemma booleanCodeMachine_finiteAlphabet (c : Code) (k : (booleanCodeMachine c).K) : + Finite ((booleanCodeMachine c).Γ k) := + sequential_finiteAlphabet _ _ _ _ + (sequential_finiteAlphabet _ _ _ _ + (WordTransducer.finiteAlphabet _ _ _) (codeMachine_finiteAlphabet c)) + (WordTransducer.finiteAlphabet _ _ _) k + +def CodeRun.booleanMachine {c : Code} {v w : List Bool} {t : ℕ} + (h : CodeRun c (v.map Bool.toNat) (w.map Bool.toNat) t) : + TM2OutputsInTime (booleanCodeMachine c) v (some w) (t+8*v.length+9*w.length+9) := by + have h₁ := MachineSequential.execute encodeMachine (codeMachine c) id Γ'.cons v _ _ _ _ (encode_run v) (by erw [List.map_id]; exact h.finiteMachine) + have h₂ := MachineSequential.execute (MachineSequential.machine encodeMachine (codeMachine c) id .cons) + decodeMachine id Γ'.cons v _ _ _ _ h₁ (by erw [List.map_id]; exact decode_run w) + have hv := trList_bool_length v + have hw := trList_bool_length w + have bound : h₂.steps ≤ + (2 * v.length + (trList (v.map Bool.toNat)).length + 2) + + 2 * ((trList (v.map Bool.toNat)).length + 1) + (t + 1) + + 2 * ((trList (w.map Bool.toNat)).length + 1) + + (2 * (trList (w.map Bool.toNat)).length + w.length + 2) := h₂.steps_le_m + refine ⟨h₂.toEvalsTo, le_trans bound ?_⟩ + omega + +end +end MinUncut.Costed + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/Driver.lean b/lean/OAI/Computability/MinUncut/Machines/Driver.lean new file mode 100644 index 0000000000000000000000000000000000000000..5e3d40c780d10388963cd453030bf4ccb7fc4dfe --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/Driver.lean @@ -0,0 +1,753 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineLookup +import OAI.Computability.MinUncut.Machines.Addresses + +namespace OAI + +namespace MinUncutGames.Foundations.PCP.AlphabetTable.Driver + +open Turing +open MinUncutGames.Foundations.Complexity +open MinUncutGames.Foundations.Hastad +open RuntimeModel + +def headerPlan (q : Nat) := EmitRows.headerCommands q (Ambient q) +def rowPlan (q : Nat) := EmitRows.blockCommandsIn q (@context q) + +inductive Label (q : Nat) + | setup (label : Setup.Label) + | header (label : Emitter.Label (headerPlan q).length (Addresses.fieldBound q)) + | guard | tailStart | tailLoop | reverseStart | reverseLoop | readPredicate + | headCopyFirst | headCopySecond | indexCopyFirst | indexCopySecond + | headVertices | headDarts | headLookup (label : Lookup.Label) + | compare (label : CompareLoop.Label) + | emit (label : Emitter.Label (rowPlan q).length (Addresses.fieldBound q)) + | clearField (slot : Fin 3) + | increment | reverseOutput | cleanup (slot : Fin 16) + deriving DecidableEq, Fintype + +def headerEntry (q : Nat) : Label q := + .header (Emitter.labelAt (headerPlan q).length (Addresses.fieldBound q) 0 .entry) + +def rowEntry (q : Nat) : Label q := + .emit (Emitter.labelAt (rowPlan q).length (Addresses.fieldBound q) 0 .entry) + +def clearNext {q : Nat} (slot : Fin 3) : Label q := + if h : slot.val < 2 then .clearField ⟨slot.val + 1, by omega⟩ else .increment + +def program (q : Nat) : Label q → TM2.Stmt Alphabet (Label q) (State q) + | .setup label => Setup.statement setupPorts Label.setup (some (headerEntry q)) label + | .header label => emitterStatement + (Emitter.statement (Emitter.listCommands (headerPlan q)) headerSources .scratch .reversed + Label.header (some .guard) label) + | .guard => MachineUnaryCounter.guard .counter .tailStart .reverseOutput + | .tailStart => SourceMachine.fieldStart .tail .tailLoop + | .tailLoop => SourceMachine.fieldLoop .cursor .tail .tailLoop (some .reverseStart) + | .reverseStart => SourceMachine.fieldStart .reverseIndex .reverseLoop + | .reverseLoop => SourceMachine.fieldLoop .cursor .reverseIndex .reverseLoop (some .readPredicate) + | .readPredicate => ReadRelation.parser .cursor .headCopyFirst + | .headCopyFirst => Reduction.MachineTransfer.loopAt .original .scratch id false + .headCopyFirst (some .headCopySecond) + | .headCopySecond => MachineCopy.forkLoop .scratch .original .scan false + .headCopySecond (some .indexCopyFirst) + | .indexCopyFirst => Reduction.MachineTransfer.loopAt .reverseIndex .scratch id false + .indexCopyFirst (some .indexCopySecond) + | .indexCopySecond => MachineCopy.forkLoop .scratch .reverseIndex .indexScan false + .indexCopySecond (some .headVertices) + | .headVertices => MachineLookup.discard .scan .headVertices .headDarts + | .headDarts => MachineLookup.discard .scan .headDarts (.headLookup .guard) + | .headLookup label => Lookup.statement q .indexScan .scan .head Label.headLookup + (some (.compare .leftFirst)) label + | .compare label => CompareLoop.statement Label.compare (rowEntry q) label + | .emit label => emitterStatement + (Emitter.statement (Emitter.listCommands (rowPlan q)) rowSources .scratch .reversed + Label.emit (some (.clearField 0)) label) + | .clearField slot => MachineDrain.drain (fieldPorts slot) (.clearField slot) + (some (clearNext slot)) + | .increment => nextRow .guard + | .reverseOutput => Reduction.MachineTransfer.loopAt .reversed .output id false + .reverseOutput (some (.cleanup 0)) + | .cleanup slot => Cleanup.instruction cleanupPorts Label.cleanup (initial q).1 none slot + +def machine (q : Nat) : FinTM2 := by + letI := ReadRelation.stateFintype Flags q + exact { + K := Tape + k₀ := .original + k₁ := .output + Γ := Alphabet + Λ := Label q + main := .setup .copyFirst + σ := State q + initialState := initial q + m := program q } + +@[simp] theorem program_setup (q : Nat) (label : Setup.Label) : + program q (.setup label) = + Setup.statement setupPorts Label.setup (some (headerEntry q)) label := rfl + +@[simp] theorem program_guard (q : Nat) : program q .guard = + MachineUnaryCounter.guard .counter .tailStart .reverseOutput := rfl + +@[simp] theorem program_headLookup (q : Nat) (label : Lookup.Label) : + program q (.headLookup label) = Lookup.statement q .indexScan .scan .head + Label.headLookup (some (.compare .leftFirst)) label := rfl + +@[simp] theorem program_compare (q : Nat) (label : CompareLoop.Label) : + program q (.compare label) = CompareLoop.statement Label.compare (rowEntry q) label := rfl + +@[simp] theorem program_increment (q : Nat) : program q .increment = nextRow .guard := rfl + +end MinUncutGames.Foundations.PCP.AlphabetTable.Driver + +namespace MinUncutGames.Foundations.PCP.AlphabetTable.LoopState + +open MinUncutGames.Foundations.Complexity +open RuntimeModel + +variable {q : Nat} + +def inputBits (input : GenericGraphTables.Table q) : List Bool := + GenericGraphTables.tableBits input + +def prefixWords (input : GenericGraphTables.Table q) (e : Nat) : List Nat := + [Enumeration.vertexCount input.vertices input.darts q, + Enumeration.dartCount input.darts q] ++ + ((List.finRange input.darts).take e).flatMap (EmitRows.blockWords input) + +def prefixBits (input : GenericGraphTables.Table q) (e : Nat) : List Bool := + encodeWords (prefixWords input e) + +def cursorWords (input : GenericGraphTables.Table q) (e : Nat) : List Nat := + ((GenericGraphTables.rowList input).drop e).flatMap GenericGraphTables.rowWords + +def cursorBits (input : GenericGraphTables.Table q) (e : Nat) : List Bool := + encodeWords (cursorWords input e) + +@[simp] theorem prefixWords_zero (input : GenericGraphTables.Table q) : + prefixWords input 0 = + [Enumeration.vertexCount input.vertices input.darts q, + Enumeration.dartCount input.darts q] := by + simp [prefixWords] + +@[simp] theorem prefixBits_zero (input : GenericGraphTables.Table q) : + prefixBits input 0 = encodeWords + [Enumeration.vertexCount input.vertices input.darts q, + Enumeration.dartCount input.darts q] := by + rw [prefixBits, prefixWords_zero] + +theorem prefixWords_succ (input : GenericGraphTables.Table q) (e : Nat) + (he : e < input.darts) : + prefixWords input (e + 1) = + prefixWords input e ++ EmitRows.blockWords input ⟨e, he⟩ := by + have bound : e < (List.finRange input.darts).length := by simpa using he + have take := List.take_succ_eq_append_getElem bound + have atIndex : (List.finRange input.darts)[e]'bound = (⟨e, he⟩ : Fin input.darts) := by + simp + rw [atIndex] at take + unfold prefixWords + rw [take, List.flatMap_append] + simp only [List.flatMap_cons, List.flatMap_nil, List.append_nil, List.append_assoc] + +theorem prefixBits_succ (input : GenericGraphTables.Table q) (e : Nat) + (he : e < input.darts) : + prefixBits input (e + 1) = + prefixBits input e ++ encodeWords (EmitRows.blockWords input ⟨e, he⟩) := by + rw [prefixBits, prefixWords_succ input e he, encodeWords_append] + rfl + +theorem prefixBits_reverse_succ (input : GenericGraphTables.Table q) (e : Nat) + (he : e < input.darts) : + (prefixBits input (e + 1)).reverse = + (encodeWords (EmitRows.blockWords input ⟨e, he⟩)).reverse ++ + (prefixBits input e).reverse := by + rw [prefixBits_succ input e he, List.reverse_append] + +theorem prefixWords_full (input : GenericGraphTables.Table q) : + prefixWords input input.darts = GraphTables.tableWords (Table.build input) := by + have allRows : (List.finRange input.darts).take input.darts = List.finRange input.darts := by + apply List.take_of_length_le + simp + unfold prefixWords + rw [allRows] + exact (EmitRows.tableWords_eq_blocks input).symm + +theorem prefixBits_full (input : GenericGraphTables.Table q) : + prefixBits input input.darts = GraphTables.tableBits (Table.build input) := by + rw [prefixBits, prefixWords_full] + rfl + +@[simp] theorem cursorBits_zero (input : GenericGraphTables.Table q) : + cursorBits input 0 = + encodeWords ((GenericGraphTables.rowList input).flatMap GenericGraphTables.rowWords) := by + simp [cursorBits, cursorWords] + +theorem cursorWords_succ (input : GenericGraphTables.Table q) (e : Nat) + (he : e < input.darts) : + cursorWords input e = + GenericGraphTables.rowWords input.rows[(⟨e, he⟩ : Fin input.darts)] ++ + cursorWords input (e + 1) := by + have bound : e < (GenericGraphTables.rowList input).length := by + simpa only [GenericGraphTables.rowList_length] using he + unfold cursorWords + rw [List.drop_eq_getElem_cons bound, List.flatMap_cons] + simp only [GenericGraphTables.rowList, Vector.getElem_toList, Fin.getElem_fin] + +theorem cursorBits_succ (input : GenericGraphTables.Table q) (e : Nat) + (he : e < input.darts) : + cursorBits input e = + encodeWords (GenericGraphTables.rowWords input.rows[(⟨e, he⟩ : Fin input.darts)]) ++ + cursorBits input (e + 1) := by + rw [cursorBits, cursorWords_succ input e he, encodeWords_append] + rfl + +@[simp] theorem cursorBits_full (input : GenericGraphTables.Table q) : + cursorBits input input.darts = [] := by + have finished := List.drop_length (l := GenericGraphTables.rowList input) + rw [GenericGraphTables.rowList_length] at finished + unfold cursorBits cursorWords + rw [finished] + rfl + +structure Ready (input : GenericGraphTables.Table q) (e : Nat) + (base : Tape → List Bool) : Prop where + le_darts : e ≤ input.darts + original : base .original = inputBits input + cursor : base .cursor = cursorBits input e + vertices : base .vertices = encodeWord input.vertices + darts : base .darts = encodeWord input.darts + counter : base .counter = encodeWord (input.darts - e) + edge : base .edge = encodeWord e + tail : base .tail = [] + reverseIndex : base .reverseIndex = [] + head : base .head = [] + scratch : base .scratch = [] + compareLeft : base .compareLeft = [] + compareRight : base .compareRight = [] + output : base .output = [] + reversed : base .reversed = (prefixBits input e).reverse + +theorem Ready.of_agree {input : GenericGraphTables.Table q} {e : Nat} + {base next : Tape → List Bool} (ready : Ready input e base) + (agree : ∀ tape, tape ≠ .scan → tape ≠ .indexScan → next tape = base tape) : + Ready input e next where + le_darts := ready.le_darts + original := (agree .original (by decide) (by decide)).trans ready.original + cursor := (agree .cursor (by decide) (by decide)).trans ready.cursor + vertices := (agree .vertices (by decide) (by decide)).trans ready.vertices + darts := (agree .darts (by decide) (by decide)).trans ready.darts + counter := (agree .counter (by decide) (by decide)).trans ready.counter + edge := (agree .edge (by decide) (by decide)).trans ready.edge + tail := (agree .tail (by decide) (by decide)).trans ready.tail + reverseIndex := (agree .reverseIndex (by decide) (by decide)).trans ready.reverseIndex + head := (agree .head (by decide) (by decide)).trans ready.head + scratch := (agree .scratch (by decide) (by decide)).trans ready.scratch + compareLeft := (agree .compareLeft (by decide) (by decide)).trans ready.compareLeft + compareRight := (agree .compareRight (by decide) (by decide)).trans ready.compareRight + output := (agree .output (by decide) (by decide)).trans ready.output + reversed := (agree .reversed (by decide) (by decide)).trans ready.reversed + +theorem Ready.update_scan {input : GenericGraphTables.Table q} {e : Nat} + {base : Tape → List Bool} (ready : Ready input e base) (word : List Bool) : + Ready input e (Function.update base .scan word) := by + apply ready.of_agree + intro tape notScan _ + simp [notScan] + +theorem Ready.update_indexScan {input : GenericGraphTables.Table q} {e : Nat} + {base : Tape → List Bool} (ready : Ready input e base) (word : List Bool) : + Ready input e (Function.update base .indexScan word) := by + apply ready.of_agree + intro tape _ notIndexScan + simp [notIndexScan] + +theorem Ready.counter_succ {input : GenericGraphTables.Table q} {e : Nat} + {base : Tape → List Bool} (ready : Ready input e base) (he : e < input.darts) : + base .counter = encodeWord (input.darts - (e + 1) + 1) := by + rw [ready.counter] + congr 1 + omega + +theorem Ready.counter_at_end {input : GenericGraphTables.Table q} + {base : Tape → List Bool} (ready : Ready input input.darts base) : + base .counter = encodeWord 0 := by + simpa only [Nat.sub_self] using ready.counter + +theorem Ready.cursor_at_end {input : GenericGraphTables.Table q} + {base : Tape → List Bool} (ready : Ready input input.darts base) : + base .cursor = [] := ready.cursor.trans (cursorBits_full input) + +theorem Ready.reversed_at_end {input : GenericGraphTables.Table q} + {base : Tape → List Bool} (ready : Ready input input.darts base) : + base .reversed = (GraphTables.tableBits (Table.build input)).reverse := by + rw [ready.reversed, prefixBits_full] + +end MinUncutGames.Foundations.PCP.AlphabetTable.LoopState + +namespace MinUncutGames.Foundations.PCP.AlphabetTable.Body + +open Turing +open MinUncutGames.Foundations.Complexity +open RuntimeModel + +variable {q : Nat} + +def bodyTime (q N : Nat) : Nat := + (32 + 8 * (Enumeration.localCount q * (6 * (2 * 4104)))) * (N + 1) + +structure RowStepResult (input : GenericGraphTables.Table q) (e : Fin input.darts) + (base : Tape → List Bool) (oldRelation : GenericGraphTables.RelationTable q) + (oldFlag : Bool) where + tapes : Tape → List Bool + ready : LoopState.Ready input (e.val + 1) tapes + run : StateTransition.EvalsToInTime (TM2.step (Driver.program q)) + ⟨some .guard, normal oldRelation oldFlag, base⟩ + (some ⟨some .guard, CompareLoop.rowState input e, tapes⟩) + (bodyTime q (LoopState.inputBits input).length) + +def guardTapes (input : GenericGraphTables.Table q) (e : Fin input.darts) + (base : Tape → List Bool) : Tape → List Bool := + Function.update base .counter (encodeWord (input.darts - (e.val + 1))) + +def parsedTapes (input : GenericGraphTables.Table q) (e : Fin input.darts) + (base : Tape → List Bool) : Tape → List Bool := + Lookup.readRowTapes .cursor .tail .reverseIndex (guardTapes input e base) + input.rows[e] (LoopState.cursorBits input (e.val + 1)) + +def workingTapes (input : GenericGraphTables.Table q) (e : Fin input.darts) + (base : Tape → List Bool) : Tape → List Bool := + Lookup.headLookupTapes headPorts (parsedTapes input e base) input e + +def emittedTapes (input : GenericGraphTables.Table q) (e : Fin input.darts) + (base : Tape → List Bool) : Tape → List Bool := + Emitter.resultTapes .reversed (workingTapes input e base) + (encodeWords (EmitRows.blockWords input e)) + +def clearFieldsTapes (base : Tape → List Bool) : Tape → List Bool := + Function.update (Function.update (Function.update base .tail []) .reverseIndex []) .head [] + +def resultTapes (input : GenericGraphTables.Table q) (e : Fin input.darts) + (base : Tape → List Bool) : Tape → List Bool := + Function.update (clearFieldsTapes (emittedTapes input e base)) .edge + (encodeWord (e.val + 1)) + +private theorem workingTapes_other (input : GenericGraphTables.Table q) + (e : Fin input.darts) (base : Tape → List Bool) (other : Tape) + (hcounter : other ≠ .counter) (hcursor : other ≠ .cursor) + (htail : other ≠ .tail) (hreverse : other ≠ .reverseIndex) + (hscan : other ≠ .scan) (hindex : other ≠ .indexScan) (hhead : other ≠ .head) : + workingTapes input e base other = base other := by + simp [workingTapes, Lookup.headLookupTapes, MachineLookup.tapes, headPorts, + parsedTapes, Lookup.readRowTapes, guardTapes, hcounter, hcursor, htail, + hreverse, hscan, hindex, hhead] + +private theorem workingTapes_counter (input : GenericGraphTables.Table q) + (e : Fin input.darts) (base : Tape → List Bool) : + workingTapes input e base .counter = encodeWord (input.darts - (e.val + 1)) := by + simp [workingTapes, Lookup.headLookupTapes, MachineLookup.tapes, headPorts, + parsedTapes, Lookup.readRowTapes, guardTapes] + +private theorem workingTapes_cursor (input : GenericGraphTables.Table q) + (e : Fin input.darts) (base : Tape → List Bool) : + workingTapes input e base .cursor = LoopState.cursorBits input (e.val + 1) := by + simp [workingTapes, Lookup.headLookupTapes, MachineLookup.tapes, headPorts, + parsedTapes, Lookup.readRowTapes] + +private theorem workingTapes_tail (input : GenericGraphTables.Table q) + (e : Fin input.darts) (base : Tape → List Bool) : + workingTapes input e base .tail = encodeWord input.rows[e].tail.val := by + simp [workingTapes, Lookup.headLookupTapes, MachineLookup.tapes, headPorts, + parsedTapes, Lookup.readRowTapes] + +private theorem workingTapes_reverse (input : GenericGraphTables.Table q) + (e : Fin input.darts) (base : Tape → List Bool) : + workingTapes input e base .reverseIndex = encodeWord input.rows[e].reverseIndex.val := by + simp [workingTapes, Lookup.headLookupTapes, MachineLookup.tapes, headPorts, + parsedTapes, Lookup.readRowTapes] + +private theorem workingTapes_head (input : GenericGraphTables.Table q) + (e : Fin input.darts) (base : Tape → List Bool) : + workingTapes input e base .head = + encodeWord input.rows[input.rows[e].reverseIndex].tail.val := by + simp [workingTapes, Lookup.headLookupTapes, MachineLookup.tapes, headPorts, + Lookup.headValue, Lookup.headIndex] + +def clearFieldsInTime (base : Tape → List Bool) (ambient : Ambient q) : + StateTransition.EvalsToInTime (TM2.step (Driver.program q)) + ⟨some (.clearField 0), (ambient, none), base⟩ + (some ⟨some .increment, (ambient, none), clearFieldsTapes base⟩) + ((base .tail).length + (base .reverseIndex).length + (base .head).length + 3) := by + let first := MachineDrain.drainInTime Tape.tail (Driver.Label.clearField 0) + (some (.clearField 1)) (Driver.program q) (by rfl) base ambient none + let second := MachineDrain.drainInTime Tape.reverseIndex (Driver.Label.clearField 1) + (some (.clearField 2)) (Driver.program q) (by rfl) + (Function.update base .tail []) ambient none + let third := MachineDrain.drainInTime Tape.head (Driver.Label.clearField 2) + (some .increment) (Driver.program q) (by rfl) + (Function.update (Function.update base .tail []) .reverseIndex []) ambient none + let firstTwo := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ first second + let run := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ firstTwo third + refine { toEvalsTo := run.toEvalsTo, steps_le_m := ?_ } + have h := run.steps_le_m + simp only [Function.update_of_ne (by decide : Tape.reverseIndex ≠ .tail), + Function.update_of_ne (by decide : Tape.head ≠ .reverseIndex), + Function.update_of_ne (by decide : Tape.head ≠ .tail)] at h + omega + +def incrementInTime (base : Tape → List Bool) (ambient : Ambient q) + (e : Nat) (he : base .edge = encodeWord e) : + StateTransition.EvalsToInTime (TM2.step (Driver.program q)) + ⟨some .increment, (ambient, none), base⟩ + (some ⟨some .guard, (ambient, none), Function.update base .edge (encodeWord (e + 1))⟩) + 1 where + steps := 1 + evals_in_steps := by + change some (TM2.stepAux (nextRow (Driver.Label.guard : Driver.Label q)) + (ambient, none) base) = _ + simpa only [List.append_nil] using congrArg some + (stepAux_nextRow (Driver.Label.guard : Driver.Label q) (ambient, none) base e [] + (by simpa only [List.append_nil] using he)) + steps_le_m := Nat.le_refl _ + +private theorem emitterView_at (label : + Emitter.Label (Driver.rowPlan q).length (Addresses.fieldBound q)) : + (MachineControl.program (Equiv.refl (Driver.Label q)) (emitterEquiv q).symm + (Driver.program q)) (.emit label) = + Emitter.statement (Emitter.listCommands (Driver.rowPlan q)) rowSources + Tape.scratch Tape.reversed Driver.Label.emit (some (.clearField 0)) label := by + change MachineControl.statement id (emitterEquiv q).symm + (MachineControl.statement id (emitterEquiv q) _) = _ + exact MachineFieldProfile.statement_roundtrip (emitterEquiv q).symm _ + +private theorem context_rowState (input : GenericGraphTables.Table q) + (e : Fin input.darts) : + context (CompareLoop.rowState input e).1 = EmitRows.rowContext input e := by + change (input.rows[e].relation, + decide (input.rows[e].tail.val = input.rows[input.rows[e].reverseIndex].tail.val)) = + (input.rows[e].relation, + decide (input.rows[e].tail = input.rows[input.rows[e].reverseIndex].tail)) + simp only [Fin.val_inj] + +def emitInTime (input : GenericGraphTables.Table q) (e : Fin input.darts) + (base : Tape → List Bool) + (operands : ∀ i, base (rowSources i) = encodeWord (EmitRows.rowValues input e i)) + (scratchEmpty : base .scratch = []) : + StateTransition.EvalsToInTime (TM2.step (Driver.program q)) + ⟨some (Driver.rowEntry q), CompareLoop.rowState input e, base⟩ + (some ⟨some (.clearField 0), CompareLoop.rowState input e, + Emitter.resultTapes .reversed base (encodeWords (EmitRows.blockWords input e))⟩) + (Enumeration.localCount q * (6 * (2 * 4104)) * + (3 * ((LoopState.inputBits input).length + 1) + 3) + 1) := by + let view := MachineControl.program (Equiv.refl (Driver.Label q)) (emitterEquiv q).symm + (Driver.program q) + have sourceScratch : ∀ i : Fin 5, rowSources i ≠ Tape.scratch := by + intro i; fin_cases i <;> decide + have sourceOutput : ∀ i : Fin 5, rowSources i ≠ Tape.reversed := by + intro i; fin_cases i <;> decide + have bounded : ∀ i, EmitRows.rowValues input e i ≤ (LoopState.inputBits input).length := by + have hn := GenericGraphTables.vertices_le_tableBits_length input + have hm := GenericGraphTables.darts_le_tableBits_length input + have he := e.isLt + have ht := input.rows[e].tail.isLt + have hh := input.rows[input.rows[e].reverseIndex].tail.isLt + intro i + fin_cases i <;> simp [EmitRows.rowValues, Addresses.values, LoopState.inputBits] <;> omega + have run := EmitRows.blockInTimeAmbient input e (@context q) + (CompareLoop.rowState input e).1 (context_rowState input e) + rowSources Tape.scratch Tape.reversed sourceScratch sourceOutput (by decide) + Driver.Label.emit (some (.clearField 0)) view emitterView_at base operands + scratchEmpty (LoopState.inputBits input).length bounded + have restored : MachineControl.program (Equiv.refl (Driver.Label q)) (emitterEquiv q) view = + Driver.program q := by + funext label + exact MachineFieldProfile.statement_roundtrip (emitterEquiv q) (Driver.program q label) + have transported := transportInTime (emitterEquiv q) view run + rw [restored] at transported + simpa [MachineControl.configuration, emitterEquiv, Option.map_some, id_eq, + Driver.rowEntry, Driver.rowPlan, CompareLoop.rowState, normal] using transported + +private theorem result_ready (input : GenericGraphTables.Table q) (e : Fin input.darts) + (base : Tape → List Bool) (ready : LoopState.Ready input e.val base) : + LoopState.Ready input (e.val + 1) (resultTapes input e base) := by + constructor + · exact Nat.succ_le_of_lt e.isLt + all_goals simp [resultTapes, clearFieldsTapes, emittedTapes, Emitter.resultTapes, + workingTapes, Lookup.headLookupTapes, MachineLookup.tapes, headPorts, + parsedTapes, Lookup.readRowTapes, guardTapes, ready.original, ready.vertices, + ready.darts, ready.scratch, ready.compareLeft, ready.compareRight, ready.output, + ready.reversed, LoopState.prefixBits_reverse_succ input e.val e.isLt] + +private theorem workingOperands (input : GenericGraphTables.Table q) (e : Fin input.darts) + (base : Tape → List Bool) (ready : LoopState.Ready input e.val base) : + ∀ i, workingTapes input e base (rowSources i) = + encodeWord (EmitRows.rowValues input e i) := by + intro i + fin_cases i <;> simp [rowSources, EmitRows.rowValues, Addresses.values, + workingTapes, Lookup.headLookupTapes, MachineLookup.tapes, headPorts, + parsedTapes, Lookup.readRowTapes, guardTapes, Lookup.headValue, Lookup.headIndex, + ready.vertices, ready.darts, ready.edge] + +def rowStep (input : GenericGraphTables.Table q) (e : Fin input.darts) + (base : Tape → List Bool) (ready : LoopState.Ready input e.val base) + (oldRelation : GenericGraphTables.RelationTable q) (oldFlag : Bool) : + RowStepResult input e base oldRelation oldFlag := by + let N := (LoopState.inputBits input).length + have guarded : StateTransition.EvalsToInTime (TM2.step (Driver.program q)) + ⟨some .guard, normal oldRelation oldFlag, base⟩ + (some ⟨some .tailStart, normal oldRelation oldFlag, guardTapes input e base⟩) 1 := by + have hbase : MachineUnaryCounter.counterTapes .counter base + (input.darts - (e.val + 1) + 1) [] = base := by + simp only [MachineUnaryCounter.counterTapes, List.append_nil, + ← ready.counter_succ e.isLt, Function.update_eq_self] + have run := MachineUnaryCounter.guardInTime_succ Tape.counter Driver.Label.guard + .tailStart .reverseOutput (Driver.program q) (by rfl) base + (input.darts - (e.val + 1)) [] (normal oldRelation oldFlag).1 none + rw [hbase] at run + simpa only [MachineUnaryCounter.counterTapes, List.append_nil, guardTapes, + normal] using run + have parsed : StateTransition.EvalsToInTime (TM2.step (Driver.program q)) + ⟨some .tailStart, normal oldRelation oldFlag, guardTapes input e base⟩ + (some ⟨some .headCopyFirst, normal input.rows[e].relation oldFlag, + parsedTapes input e base⟩) (Lookup.readRowCost input.rows[e]) := by + have hcursor : guardTapes input e base .cursor = Lookup.rowBits input.rows[e] ++ + LoopState.cursorBits input (e.val + 1) := by + simpa only [guardTapes, Function.update_of_ne (by decide : Tape.cursor ≠ .counter), + Lookup.rowBits] using ready.cursor.trans (LoopState.cursorBits_succ input e.val e.isLt) + have htail : guardTapes input e base .tail = [] := by simp [guardTapes, ready.tail] + have hreverse : guardTapes input e base .reverseIndex = [] := by + simp [guardTapes, ready.reverseIndex] + simpa only [normal, parsedTapes] using + Lookup.readRowInTime Tape.cursor Tape.tail Tape.reverseIndex + (by decide) (by decide) (by decide) Driver.Label.tailStart .tailLoop + .reverseStart .reverseLoop .readPredicate .headCopyFirst (Driver.program q) + (by rfl) (by rfl) (by rfl) (by rfl) (by rfl) + (guardTapes input e base) input.rows[e] (LoopState.cursorBits input (e.val + 1)) + hcursor htail hreverse (oldFlag, false, none) oldRelation none + have looked : StateTransition.EvalsToInTime (TM2.step (Driver.program q)) + ⟨some .headCopyFirst, normal input.rows[e].relation oldFlag, parsedTapes input e base⟩ + (some ⟨some (.compare .leftFirst), normal input.rows[e].relation oldFlag, + workingTapes input e base⟩) (7 * N + 5) := by + have htable : parsedTapes input e base (headPorts 0) = GenericGraphTables.tableBits input := by + simpa [headPorts, parsedTapes, Lookup.readRowTapes, guardTapes, + LoopState.inputBits] using ready.original + have hreverse : parsedTapes input e base (headPorts 1) = + encodeWord (Lookup.headIndex input e).val := by + simp [headPorts, parsedTapes, Lookup.readRowTapes, Lookup.headIndex] + have hhead : parsedTapes input e base (headPorts 4) = [] := by + simp [headPorts, parsedTapes, Lookup.readRowTapes, guardTapes, ready.head] + have hscratch : parsedTapes input e base (headPorts 5) = [] := by + simp [headPorts, parsedTapes, Lookup.readRowTapes, guardTapes, ready.scratch] + have run := Lookup.headLookupInTime headPorts headPorts_injective + Driver.Label.headCopyFirst .headCopySecond .indexCopyFirst .indexCopySecond + .headVertices .headDarts Driver.Label.headLookup (some (.compare .leftFirst)) + (Driver.program q) (by rfl) (by rfl) (by rfl) (by rfl) (by rfl) (by rfl) + (fun _ => rfl) (parsedTapes input e base) input e htable hreverse hhead hscratch + (normal input.rows[e].relation oldFlag).1 none + simpa only [workingTapes, normal, N, LoopState.inputBits, Lookup.headTimePolynomial, + Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_C, Polynomial.eval_X] using run + have hleft : workingTapes input e base .compareLeft = [] := + (workingTapes_other input e base .compareLeft (by decide) (by decide) (by decide) + (by decide) (by decide) (by decide) (by decide)).trans ready.compareLeft + have hright : workingTapes input e base .compareRight = [] := + (workingTapes_other input e base .compareRight (by decide) (by decide) (by decide) + (by decide) (by decide) (by decide) (by decide)).trans ready.compareRight + have hscratch : workingTapes input e base .scratch = [] := + (workingTapes_other input e base .scratch (by decide) (by decide) (by decide) + (by decide) (by decide) (by decide) (by decide)).trans ready.scratch + let compared := CompareLoop.compareRowInTime Driver.Label.compare (Driver.rowEntry q) + (Driver.program q) (fun _ => rfl) input e (workingTapes input e base) + (workingTapes_tail input e base) (workingTapes_head input e base) + hleft hright hscratch oldFlag + let emitted := emitInTime input e (workingTapes input e base) + (workingOperands input e base ready) hscratch + let cleared := clearFieldsInTime (emittedTapes input e base) (CompareLoop.rowState input e).1 + have hedge : clearFieldsTapes (emittedTapes input e base) .edge = encodeWord e.val := by + simp [clearFieldsTapes, emittedTapes, Emitter.resultTapes, workingTapes, + Lookup.headLookupTapes, MachineLookup.tapes, headPorts, parsedTapes, + Lookup.readRowTapes, guardTapes, ready.edge] + let incremented := incrementInTime (clearFieldsTapes (emittedTapes input e base)) + (CompareLoop.rowState input e).1 e.val hedge + let run₁ := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ guarded parsed + let run₂ := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ run₁ looked + let run₃ := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ run₂ compared + let run₄ := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ run₃ emitted + let run₅ := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ run₄ cleared + let run := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ run₅ incremented + refine { + tapes := resultTapes input e base + ready := result_ready input e base ready + run := { toEvalsTo := run.toEvalsTo, steps_le_m := ?_ } + } + have hn : input.vertices ≤ N := GenericGraphTables.vertices_le_tableBits_length input + have hm : input.darts ≤ N := GenericGraphTables.darts_le_tableBits_length input + have hr : Lookup.readRowCost input.rows[e] ≤ 2 * N + 5 := + Lookup.readRowCost_table_le input e + have ht : (emittedTapes input e base .tail).length ≤ N := by + simp only [emittedTapes, Emitter.resultTapes, + Function.update_of_ne (by decide : Tape.tail ≠ .reversed), workingTapes_tail, + encodeWord_length] + exact (Nat.succ_le_of_lt input.rows[e].tail.isLt).trans hn + have hv : (emittedTapes input e base .reverseIndex).length ≤ N := by + simp only [emittedTapes, Emitter.resultTapes, + Function.update_of_ne (by decide : Tape.reverseIndex ≠ .reversed), workingTapes_reverse, + encodeWord_length] + exact (Nat.succ_le_of_lt input.rows[e].reverseIndex.isLt).trans hm + have hh : (emittedTapes input e base .head).length ≤ N := by + simp only [emittedTapes, Emitter.resultTapes, + Function.update_of_ne (by decide : Tape.head ≠ .reversed), workingTapes_head, + encodeWord_length] + exact (Nat.succ_le_of_lt input.rows[input.rows[e].reverseIndex].tail.isLt).trans hn + have budget := run.steps_le_m + change run.steps ≤ (32 + 8 * (Enumeration.localCount q * (6 * (2 * 4104)))) * (N + 1) + nlinarith + +end MinUncutGames.Foundations.PCP.AlphabetTable.Body + +namespace MinUncutGames.Foundations.PCP.AlphabetTable.Initialization + +open Turing +open MinUncutGames.Foundations.Complexity +open RuntimeModel + +variable {q : Nat} + +def inputTapes (input : GenericGraphTables.Table q) : Tape → List Bool + | .original => GenericGraphTables.tableBits input + | _ => [] + +def rowsBits (input : GenericGraphTables.Table q) : List Bool := + encodeWords ((GenericGraphTables.rowList input).flatMap GenericGraphTables.rowWords) + +def headerBits (input : GenericGraphTables.Table q) : List Bool := + encodeWords [Enumeration.vertexCount input.vertices input.darts q, + Enumeration.dartCount input.darts q] + +def setupTapes (input : GenericGraphTables.Table q) : Tape → List Bool + | .original => GenericGraphTables.tableBits input + | .cursor => rowsBits input + | .vertices => encodeWord input.vertices + | .darts | .counter => encodeWord input.darts + | .edge => encodeWord 0 + | _ => [] + +def loopTapes (input : GenericGraphTables.Table q) : Tape → List Bool + | .original => GenericGraphTables.tableBits input + | .cursor => rowsBits input + | .vertices => encodeWord input.vertices + | .darts | .counter => encodeWord input.darts + | .edge => encodeWord 0 + | .reversed => (headerBits input).reverse + | _ => [] + +def loopStart (input : GenericGraphTables.Table q) : + TM2.Cfg Alphabet (Driver.Label q) (State q) := + ⟨some .guard, initial q, loopTapes input⟩ + +theorem setupResult_eq (input : GenericGraphTables.Table q) : + Setup.resultTapes setupPorts (inputTapes input) input.vertices input.darts (rowsBits input) = + setupTapes input := by + funext tape + cases tape <;> simp [Setup.resultTapes, setupPorts, inputTapes, setupTapes] + +theorem headerResult_eq (input : GenericGraphTables.Table q) : + Emitter.resultTapes Tape.reversed (setupTapes input) (headerBits input) = loopTapes input := by + funext tape + cases tape <;> simp [Emitter.resultTapes, setupTapes, loopTapes] + +theorem machineInitial_eq (input : GenericGraphTables.Table q) : + initList (Driver.machine q) (GenericGraphTables.tableBits input) = + (⟨some (.setup .copyFirst), initial q, inputTapes input⟩ : + TM2.Cfg Alphabet (Driver.Label q) (State q)) := by + change (⟨some (.setup .copyFirst), initial q, _⟩ : + TM2.Cfg Alphabet (Driver.Label q) (State q)) = _ + congr 1 + funext tape + cases tape <;> rfl + +def setupInTime (input : GenericGraphTables.Table q) : + StateTransition.EvalsToInTime (TM2.step (Driver.program q)) + (initList (Driver.machine q) (GenericGraphTables.tableBits input)) + (some ⟨some (Driver.headerEntry q), initial q, setupTapes input⟩) + (6 * (GenericGraphTables.tableBits input).length + 11) := by + have initialized : ∀ i : Fin 7, inputTapes input (setupPorts i) = + if i = 0 then GenericGraphTables.tableBits input else [] := by + intro i + fin_cases i <;> rfl + have run := Setup.tableSetupInTime setupPorts setupPorts_injective Driver.Label.setup + (some (Driver.headerEntry q)) (Driver.program q) (Driver.program_setup q) + (inputTapes input) input initialized (initial q).1 none + have initialState : ((initial q).1, (none : Option Bool)) = initial q := rfl + have result := setupResult_eq input + unfold rowsBits at result + rw [initialState, result] at run + rw [machineInitial_eq] + exact run + +private theorem headerView_at (label : Emitter.Label (Driver.headerPlan q).length + (Addresses.fieldBound q)) : + (MachineControl.program (Equiv.refl (Driver.Label q)) (emitterEquiv q).symm + (Driver.program q)) (.header label) = + Emitter.statement (Emitter.listCommands (Driver.headerPlan q)) headerSources + Tape.scratch Tape.reversed Driver.Label.header (some .guard) label := by + change MachineControl.statement id (emitterEquiv q).symm + (MachineControl.statement id (emitterEquiv q) _) = _ + exact MachineFieldProfile.statement_roundtrip (emitterEquiv q).symm _ + +def headerInTime (input : GenericGraphTables.Table q) : + StateTransition.EvalsToInTime (TM2.step (Driver.program q)) + ⟨some (Driver.headerEntry q), initial q, setupTapes input⟩ + (some (loopStart input)) + (7 * (3 * ((GenericGraphTables.tableBits input).length + 1) + 3) + 1) := by + let view := MachineControl.program (Equiv.refl (Driver.Label q)) (emitterEquiv q).symm + (Driver.program q) + have sourceScratch : ∀ i : Fin 2, headerSources i ≠ Tape.scratch := by + intro i + fin_cases i <;> decide + have sourceOutput : ∀ i : Fin 2, headerSources i ≠ Tape.reversed := by + intro i + fin_cases i <;> decide + have operands : ∀ i : Fin 2, setupTapes input (headerSources i) = + encodeWord (![input.vertices, input.darts] i) := by + intro i + fin_cases i <;> rfl + have run := EmitRows.headerInTime q input.vertices input.darts headerSources + Tape.scratch Tape.reversed sourceScratch sourceOutput (by decide) + Driver.Label.header (some .guard) view headerView_at + (setupTapes input) operands (by rfl) (initial q).1 + (GenericGraphTables.tableBits input).length + (GenericGraphTables.vertices_le_tableBits_length input) + (GenericGraphTables.darts_le_tableBits_length input) + have restored : MachineControl.program (Equiv.refl (Driver.Label q)) (emitterEquiv q) view = + Driver.program q := by + funext label + exact MachineFieldProfile.statement_roundtrip (emitterEquiv q) (Driver.program q label) + have transported := transportInTime (emitterEquiv q) view run + rw [restored] at transported + change StateTransition.EvalsToInTime (TM2.step (Driver.program q)) + ⟨some (Driver.headerEntry q), initial q, setupTapes input⟩ + (some ⟨some .guard, initial q, + Emitter.resultTapes Tape.reversed (setupTapes input) (headerBits input)⟩) + (7 * (3 * ((GenericGraphTables.tableBits input).length + 1) + 3) + 1) at transported + rw [headerResult_eq] at transported + exact transported + +def time (N : Nat) : Nat := (6 * N + 11) + (7 * (3 * (N + 1) + 3) + 1) + +theorem time_eq (N : Nat) : time N = 27 * N + 54 := by + unfold time + omega + +def initializeInTime (input : GenericGraphTables.Table q) : + StateTransition.EvalsToInTime (TM2.step (Driver.program q)) + (initList (Driver.machine q) (GenericGraphTables.tableBits input)) + (some (loopStart input)) (time (GenericGraphTables.tableBits input).length) := by + let run := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ + (setupInTime input) (headerInTime input) + refine { toEvalsTo := run.toEvalsTo, steps_le_m := ?_ } + have bound := run.steps_le_m + unfold time + omega + +end MinUncutGames.Foundations.PCP.AlphabetTable.Initialization + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/FiberGraphMachine.lean b/lean/OAI/Computability/MinUncut/Machines/FiberGraphMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..e88e78550679be9ee058fdc30e3db49a8e7286a9 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/FiberGraphMachine.lean @@ -0,0 +1,85 @@ +import Mathlib +import OAI.Computability.MinUncut.Graphs.UnboundedGraphBase + +namespace OAI + +section +noncomputable section +namespace MinUncut.Costed.Arena +open _root_.Turing _root_.OAI.Turing Turing.ToPartrec _root_.Turing.PartrecToTM2 _root_.OAI.Turing.PartrecToTM2 Polynomial +open MinUncutGames.Foundations.Complexity MinUncutGames.BinaryEncoding + +def initializedGraphMachine (c : Code) : FinTM2 := + MachineSequential.machine (codeMachine c) unboundedGraphMachine id .cons +lemma initializedGraphMachine_finite (c : Code) (k : (initializedGraphMachine c).K) : + Finite ((initializedGraphMachine c).Γ k) := + sequential_finiteAlphabet _ _ _ _ (codeMachine_finiteAlphabet _) unboundedGraphMachine_finiteAlphabet k + +lemma magnitude_words (xs : List ℕ) : magnitude xs=(encodeWords xs).length := by + induction xs with + | nil => rfl + | cons a xs ih=> simp only [magnitude_cons,encodeWords,List.length_append,encodeWord_length,ih] + +lemma exists_graph_initializer {f : ℕ → List ℕ → List ℕ} (P : ∀K,PolyProgram (f K)) + (he : Computable (fun K=>(P K).code)) : + ∃c : Code,∀K,∃p : Polynomial ℕ,∀xs n table k junk, + f K xs=n::((table : List Bool).map Bool.toNat++2::k::junk) → + Nonempty (TM2OutputsInTime (initializedGraphMachine c) + (trList (K::(encodeWords xs).map FrameDecode.symbol)) + (some (nameBits n++table++nameBits k)) (p.eval (encodeWords xs).length)) := by + obtain ⟨c,hc⟩:=Init.exists_initializer he + refine ⟨c,fun K=>?_⟩ + obtain ⟨p,hp⟩:=hc K + let q:Polynomial ℕ:=p.comp (C (K+1)+C 3*X) + let r:Polynomial ℕ:=q+1+C 2*(q+1)+unboundedGraphTime.comp ((P K).bound+1+q) + refine ⟨r,fun xs n table k junk ho=>?_⟩ + let v:=(encodeWords xs).map FrameDecode.symbol + let b:=Init.base (P K).code xs K v + let w:=(initialState (P K).code xs b).encode + have hs:magnitude (K::v)≤(C (K+1)+C 3*X : Polynomial ℕ).eval (encodeWords xs).length:=by + have hh:=FrameDecode.magnitude_symbols (encodeWords xs) + simp only [magnitude_cons,eval_add,eval_C,eval_mul,eval_X] + dsimp only [v] + omega + have hpbound:=evalNat_mono p hs + have hir: Runs c (K::v) w (q.eval (encodeWords xs).length):= + (hp xs).1.mono (by simpa only [q,eval_comp] using hpbound) + have his: magnitude w≤q.eval (encodeWords xs).length:= + (hp xs).2.trans (by simpa only [q,eval_comp] using hpbound) + have hg:Runs (P K).code xs (n::(table.map Bool.toNat++2::k::junk)) + ((P K).bound.eval (encodeWords xs).length):=by + have hh:=(P K).run xs + rw [ho,magnitude_words] at hh + exact hh + have hl:(n::(table.map Bool.toNat++2::k::junk)).length≤(P K).bound.eval (encodeWords xs).length:=by + have hh:=(magnitude_length (f K xs)).trans ((P K).size xs) + simpa only [ho,magnitude_words] using hh + let h2:=unboundedGraphMachine_outputs_base b hg hl + obtain ⟨t,ht,hr⟩:=hir + let h1:=hr.finiteMachine + let h2':TM2OutputsInTime unboundedGraphMachine ((trList w).map id) + (some (nameBits n++table++nameBits k)) + (unboundedGraphTime.eval (magnitude ((P K).bound.eval (encodeWords xs).length::w))) := by + have input_eq : @List.map (unboundedGraphMachine.Γ unboundedGraphMachine.k₀) + (unboundedGraphMachine.Γ unboundedGraphMachine.k₀) id (trList w) = trList w := + List.map_id _ + simpa only [input_eq] using h2 + have hh:=MachineSequential.execute (codeMachine c) unboundedGraphMachine id Γ'.cons + _ _ _ _ _ h1 h2' + have hwb: (trList w).length≤q.eval (encodeWords xs).length:= (bitsize_le_magnitude w).trans his + have hm:magnitude ((P K).bound.eval (encodeWords xs).length::w)≤ + (((P K).bound+1+q).eval (encodeWords xs).length):=by + simp only [magnitude_cons,eval_add,eval_one] + omega + have hb:=evalNat_mono unboundedGraphTime hm + simp only [eval_add,eval_one] at hb + exact ⟨⟨hh.toEvalsTo,hh.steps_le_m.trans (by + simp only [r,eval_add,eval_one,eval_mul,eval_C,eval_comp] + change t+1+2*((trList w).length+1)+_≤_ + omega)⟩⟩ +end MinUncut.Costed.Arena + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/FiniteAlphabetBounds.lean b/lean/OAI/Computability/MinUncut/Machines/FiniteAlphabetBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..3537cb00a56fc18a5bd2759e92e42c2d13869b48 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/FiniteAlphabetBounds.lean @@ -0,0 +1,85 @@ +import Mathlib +import OAI.Computability.MinUncut.Search.FiniteQueryFamily + +namespace OAI + +section +noncomputable section +open scoped BigOperators +namespace MinUncut.Outer +open MinUncut.Inner MinUncut.FiniteProof +attribute [local instance] Classical.propDecidable +variable {Name I : Type*} [Fintype I] + +lemma secondSlot_card_le (q : SecondQuestion Name) : Fintype.card (secondSlot q)≤8 := by + cases q <;> norm_num [secondSlot,secondSlotCount,Fintype.card_fun,F₂,ZMod.card] + +lemma secondAlphabet_card_le (Q : I → SecondQuestion Name) : + Fintype.card (SecondAlphabet Q)≤2^(3*Fintype.card I) := by + calc + Fintype.card (SecondAlphabet Q)=∏ i, Fintype.card (secondSlot (Q i)) := Fintype.card_pi + _ ≤ ∏ _i : I, 8 := Finset.prod_le_prod (fun i _ => secondSlot_card_le (Q i)) + _ = 2^(3*Fintype.card I) := by rw [Finset.prod_const,Finset.card_univ,pow_mul]; norm_num + +lemma alphabet_card_le (E : Equation Name) : Fintype.card (alphabet E)≤8 := by + have hh := Fintype.card_le_of_injective (fun a : alphabet E => (a:Triple)) Subtype.val_injective + convert hh using 1; norm_num [Triple,Fintype.card_fun,F₂,ZMod.card] + +lemma firstAlphabet_card_le (U : I → Equation Name) : + Fintype.card (FirstAlphabet U)≤2^(3*Fintype.card I) := by + calc + Fintype.card (FirstAlphabet U)=∏ i, Fintype.card (alphabet (U i)) := Fintype.card_pi + _ ≤ ∏ _i : I, 8 := Finset.prod_le_prod (fun i _ => alphabet_card_le (U i)) + _ = 2^(3*Fintype.card I) := by rw [Finset.prod_const,Finset.card_univ,pow_mul]; norm_num + +lemma familyAlphabet_card_le (q : FamilyQuestion Name I) : + Fintype.card (FamilyAlphabet q)≤2^(3*Fintype.card I) := by + cases q with + | inl U => exact firstAlphabet_card_le U + | inr Q => exact secondAlphabet_card_le Q + +lemma forms_card_le {V A : Type*} [AddCommGroup V] [Module F₂ V] [AddTorsor V A] [Fintype A] : + Fintype.card (Forms A)≤2^Fintype.card A := by + have hh := Fintype.card_le_of_injective (fun f : Forms A => (f : A → F₂)) AffineMap.coeFn_injective + simpa only [Fintype.card_fun,F₂,ZMod.card] using hh + +def faceCardBound (t m n : ℕ) := (2^(2^(3*t)))^Fintype.card (Row m n) + +lemma faceArray_card_le (Q : I → SecondQuestion Name) (m n : ℕ) : + Fintype.card (FaceArray (SecondAlphabet Q) m n)≤faceCardBound (Fintype.card I) m n := by + simp only [FaceArray,Fintype.card_fun,faceCardBound] + exact Nat.pow_le_pow_left ((forms_card_le).trans (Nat.pow_le_pow_right (by omega) (secondAlphabet_card_le Q))) _ + +variable [Fintype Name] +lemma equation_card : Fintype.card (Equation Name)=2*Fintype.card Name^3 := by + let e : Equation Name ≃ ((Fin 3 → Name) × F₂) := + ⟨fun E => (E.names,E.rhs),fun p => ⟨p.1,p.2⟩,fun _ => rfl,fun _ => rfl⟩ + rw [Fintype.card_congr e,Fintype.card_prod,Fintype.card_fun,Fintype.card_fin] + simp only [F₂,ZMod.card,mul_comm] + +lemma familyQuestion_card : Fintype.card (FamilyQuestion Name I)= + (2*Fintype.card Name^3)^Fintype.card I+ + (Fintype.card Name+2*Fintype.card Name^3)^Fintype.card I := by + simp only [FamilyQuestion,Fintype.card_sum,Fintype.card_fun,SecondQuestion,equation_card] + +lemma familyVariable_card_le : Fintype.card (FamilyVariable Name I)≤ + Fintype.card (FamilyQuestion Name I)*2^(2^(3*Fintype.card I)) := by + calc + Fintype.card (FamilyVariable Name I)= + ∑ q : FamilyQuestion Name I, Fintype.card {R : FamilyAlphabet q → Bool // R (familyBase q)=true} := + Fintype.card_sigma + _ ≤ ∑ q : FamilyQuestion Name I, 2^(2^(3*Fintype.card I)) := by + apply Finset.sum_le_sum + intro q _ + have hh := Fintype.card_le_of_injective + (fun R : {R : FamilyAlphabet q → Bool // R (familyBase q)=true} => R.val) Subtype.val_injective + have hh' : Fintype.card {R : FamilyAlphabet q → Bool // R (familyBase q)=true}≤ + 2^Fintype.card (FamilyAlphabet q) := by simpa only [Fintype.card_fun,Fintype.card_bool] using hh + exact hh'.trans (Nat.pow_le_pow_right (by omega) (familyAlphabet_card_le q)) + _ = _ := by simp only [Finset.sum_const,Finset.card_univ,smul_eq_mul] +end MinUncut.Outer + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/FramedWordDecoder.lean b/lean/OAI/Computability/MinUncut/Machines/FramedWordDecoder.lean new file mode 100644 index 0000000000000000000000000000000000000000..4fea04927c17b1b24aaeda9c7589b24c671f6106 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/FramedWordDecoder.lean @@ -0,0 +1,84 @@ +import Mathlib +import OAI.Computability.MinUncut.Graphs.GraphWordCodec +import OAI.Computability.MinUncut.Estimates.FiberPrefix + +namespace OAI + +section +namespace MinUncut.Costed.FrameDecode +open _root_.Turing _root_.OAI.Turing _root_.Turing.PartrecToTM2 _root_.OAI.Turing.PartrecToTM2 MinUncutGames.BinaryEncoding +inductive Mode + | flag | payload | suffix + deriving DecidableEq + +protected abbrev Mode.enumList : List Mode := [.flag, .payload, .suffix] + +protected theorem Mode.enumList_getElem?_ctorIdx_eq (x : Mode) : + Mode.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem Mode.enumList_nodup : Mode.enumList.Nodup := by decide + +instance : Fintype Mode where + elems := ⟨Mode.enumList, Mode.enumList_nodup⟩ + complete x := by cases x <;> decide + +def next : Mode → Bool → Mode + | .flag,true => .payload + | .flag,false => .suffix + | .payload,_ => .flag + | .suffix,_ => .suffix + +def symbol (b : Bool) : ℕ := b.toNat+1 + +def emit : Mode → Bool → List Γ' + | .flag,true => [] + | .flag,false => [.cons] + | .payload,b => [GraphCodec.bitSymbol b] + | .suffix,b => trNat (symbol b)++[.cons] + +def machine : FinTM2 := WordTransducer.machine .flag next emit +lemma finiteAlphabet (k : machine.K) : Finite (machine.Γ k) := + WordTransducer.finiteAlphabet .flag next emit k +lemma suffix_output (v : List Bool) : + WordTransducer.output next emit .suffix v=trList (v.map symbol) := by + induction v with + | nil => rfl + | cons b v ih => + simp only [WordTransducer.output,next,emit,List.map_cons,trList,ih,List.append_assoc,List.singleton_append] +lemma frame_output (v w : List Bool) : + WordTransducer.output next emit .flag (frame v++w)= + v.map GraphCodec.bitSymbol++Γ'.cons::trList (w.map symbol) := by + induction v with + | nil => simpa only [frame,List.cons_append,List.nil_append,WordTransducer.output,next,emit, + List.singleton_append,List.map_nil] using congrArg (List.cons Γ'.cons) (suffix_output w) + | cons b v ih => + simp only [frame,List.cons_append,WordTransducer.output,next,emit,List.nil_append, + List.map_cons,ih] +lemma output_spec (K : ℕ) (w : List Bool) : + WordTransducer.output next emit .flag (nameBits K++w)=trList (K::w.map symbol) := by + rw [nameBits,frame_output,←GraphCodec.trNat_bits] + rfl +def outputs (K : ℕ) (w : List Bool) : + TM2OutputsInTime machine (nameBits K++w) (some (trList (K::w.map symbol))) + (2*(nameBits K++w).length+(trList (K::w.map symbol)).length+2) := by + have h := WordTransducer.outputsInTime .flag next emit (nameBits K++w) + erw [output_spec] at h + exact h +lemma count_symbols (v : List Bool) : UnaryWords.count (v.map symbol)=v.length := by + induction v with + | nil => rfl + | cons b v ih => + simp only [List.map_cons,UnaryWords.count,symbol,show b.toNat+1≠0 by omega,ite_false,ih,List.length_cons] +lemma magnitude_symbols (v : List Bool) : magnitude (v.map symbol)≤3*v.length := by + induction v with + | nil => rfl + | cons b v ih => + have hb : b.toNat≤1 := by cases b <;> decide + simp only [List.map_cons,magnitude_cons,List.length_cons,symbol] + omega +end MinUncut.Costed.FrameDecode + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/GraphCoreMachine.lean b/lean/OAI/Computability/MinUncut/Machines/GraphCoreMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..c5e204a49c9bafa5788593b200b3bc78b7a76566 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/GraphCoreMachine.lean @@ -0,0 +1,245 @@ +import Mathlib +import OAI.Computability.MinUncut.Graphs.SelectedGraphEndpoint +import OAI.Computability.MinUncut.Encoding.DecodedGraphCore + +namespace OAI + +section +noncomputable section +namespace MinUncut.Uniform +open MinUncut.Preprocess MinUncut.Costed MinUncut.Costed.Arena +open _root_.Turing _root_.OAI.Turing Turing.ToPartrec _root_.Turing.PartrecToTM2 _root_.OAI.Turing.PartrecToTM2 Polynomial +open MinUncutGames MinUncutGames.BinaryEncoding MinUncutGames.Foundations.Complexity + +attribute [local irreducible] selectedInner selectedOuter program + +lemma initializer_exists : ∃c : Code,∀K,∃p : Polynomial ℕ,∀xs n table k junk, + (MinUncut.Costed.SourceWords.completeGraphWords (selectedParameters K) (chosenEnumeration K) + (chosenRepetition K) (chosenNoise K)) xs=n::((table : List Bool).map Bool.toNat++2::k::junk) → + Nonempty (TM2OutputsInTime (initializedGraphMachine c) + (trList (K::(encodeWords xs).map FrameDecode.symbol)) + (some (nameBits n++table++nameBits k)) (p.eval (encodeWords xs).length)) := + by + have hh := exists_graph_initializer program program_computable + exact hh + +def initializerCode : Code := Classical.choose initializer_exists +def initializerTime (K : ℕ) : Polynomial ℕ := Classical.choose (Classical.choose_spec initializer_exists K) +def initializer_outputs (K : ℕ) (F : BinaryFormula.Formula) : + TM2OutputsInTime (initializedGraphMachine initializerCode) + (trList (K::(formulaBits (frontend F).val).map FrameDecode.symbol)) + (some (output K F).bits) ((initializerTime K).eval (formulaBits (frontend F).val).length) := by + apply Classical.choice + obtain ⟨table,junk,hj,hbits⟩:=output_words K F + have hh:=Classical.choose_spec (Classical.choose_spec initializer_exists K) + (formulaWords (frontend F).val) (output K F).vertices table (output K F).threshold junk hj + rw [←hbits] at hh + exact hh + +attribute [local irreducible] frontend output initializerCode initializerTime + +def coreMachine : FinTM2 := + decodedMachine initializerCode +lemma core_finite (k : coreMachine.K) : Finite (coreMachine.Γ k) := + decodedMachine_finite _ k + +def coreTime (K : ℕ) : Polynomial ℕ := + initializerTime K+C (2*(nameBits K).length+3*(K+1)+4)+C 11*X + +def core_outputs (K : ℕ) (F : BinaryFormula.Formula) : + TM2OutputsInTime coreMachine (nameBits K++formulaBits (frontend F).val) + (some (output K F).bits) ((coreTime K).eval (formulaBits (frontend F).val).length) := by + have hh:=decoded_outputs initializerCode K (formulaBits (frontend F).val) (output K F).bits + ((initializerTime K).eval (formulaBits (frontend F).val).length) (initializer_outputs K F) + refine ⟨hh.toEvalsTo,hh.steps_le_m.trans ?_⟩ + simp only [coreTime,eval_add,eval_C,eval_mul,eval_X] + omega +end MinUncut.Uniform + +end +end +section +noncomputable section +namespace MinUncut.Costed.Framed +open _root_.Turing _root_.OAI.Turing MinUncutGames.Foundations.Complexity +variable (M : FinTM2) (ei : M.Γ M.k₀ ≃ Bool) (eo : M.Γ M.k₁ ≃ Bool) +abbrev Tape := M.K ⊕ Unit +abbrev Alphabet : Tape M → Type := MachineEmbedding.Alphabet M.Γ (fun _ : Unit=>Bool) +abbrev Label := M.Λ ⊕ Option Bool +abbrev State := M.σ × Option Bool + +def extra : Option Bool → TM2.Stmt (Alphabet M) (Label M) (State M) + | none => .pop (.inl M.k₀) (fun s a=>(s.1,a.map ei)) + (.push (.inr ()) (fun s=>s.2.getD false) + (.branch (fun s=>s.2.getD false) + (.load (fun s=>(s.1,none)) (.goto fun _=>.inr (some false))) + (.load (fun s=>(s.1,none)) (.goto fun _=>.inl M.main)))) + | some false => .pop (.inl M.k₀) (fun s a=>(s.1,a.map ei)) + (.push (.inr ()) (fun s=>s.2.getD false) + (.load (fun s=>(s.1,none)) (.goto fun _=>.inr none))) + | some true => .pop (.inr ()) (fun s a=>(s.1,a)) + (.branch (fun s=>s.2.isSome) + (.push (.inl M.k₁) (fun s=>eo.symm (s.2.getD false)) + (.load (fun s=>(s.1,none)) (.goto fun _=>.inr (some true)))) + (.load (fun s=>(s.1,none)) .halt)) +def program : Label M → TM2.Stmt (Alphabet M) (Label M) (State M) := + MachineEmbedding.program (some (.inr (some true))) M.m (extra M ei eo) +def machine : FinTM2 where + K := Tape M + kFin := by letI:=M.kFin; exact inferInstanceAs (Fintype (M.K ⊕ Unit)) + k₀ := .inl M.k₀ + k₁ := .inl M.k₁ + Γ := Alphabet M + Γk₀Fin := M.Γk₀Fin + Λ := Label M + ΛFin := by letI:=M.ΛFin; exact inferInstanceAs (Fintype (M.Λ ⊕ Option Bool)) + main := .inr none + σ := State M + σFin := by letI:=M.σFin; exact inferInstanceAs (Fintype (M.σ × Option Bool)) + initialState := (M.initialState,none) + m := program M ei eo +lemma finiteAlphabet (hm : MachineFiniteAlphabet.FiniteAlphabet M) + (k : (machine M ei eo).K) : Finite ((machine M ei eo).Γ k) := by + cases k with + | inl k => exact hm k + | inr k => exact inferInstanceAs (Finite Bool) + +def readTapes (v acc : List Bool) : ∀k,List (Alphabet M k) := + MachineEmbedding.tapes (initList M (v.map ei.symm)).stk (fun _=>acc) +def readCfg (label : Option Bool) (v acc : List Bool) : (machine M ei eo).Cfg := + ⟨some (.inr label),(M.initialState,none),readTapes M ei v acc⟩ +def embedded (acc : List Bool) (c : M.Cfg) : (machine M ei eo).Cfg := + MachineEmbedding.configuration (some (.inr (some true))) none (fun _ : Unit=>acc) c +lemma read_input (v acc : List Bool) : (readTapes M ei v acc) (.inl M.k₀)=v.map ei.symm := by + simp [readTapes,initList] +lemma read_extra (v acc : List Bool) : (readTapes M ei v acc) (.inr ())=acc := rfl +lemma read_put_input (v acc w : List Bool) : + Function.update (readTapes M ei v acc) (.inl M.k₀) (w.map ei.symm)=readTapes M ei w acc := by + funext k + cases k with + | inl k => + by_cases h:k=M.k₀ + · subst k; simp [readTapes,initList] + · simp [readTapes,initList,Function.update,h] + | inr k => simp [readTapes,Function.update] +lemma read_put_extra (v acc w : List Bool) : + Function.update (readTapes M ei v acc) (.inr ()) w=readTapes M ei v w := by + funext k + cases k with + | inl k => simp [readTapes,Function.update] + | inr k => cases k; simp [readTapes] +lemma read_step (b : Bool) (v acc : List Bool) : + (machine M ei eo).step (readCfg M ei eo none (b::v) acc)= + some (if b then readCfg M ei eo (some false) v (b::acc) + else embedded M ei eo (b::acc) (initList M (v.map ei.symm))) := by + change some (TM2.stepAux (extra M ei eo none) (M.initialState,none) (readTapes M ei (b::v) acc))=_ + cases b <;> simp only [extra,TM2.stepAux,read_input,List.map_cons,List.head?_cons,Option.map_some, + Equiv.apply_symm_apply,Option.getD_some,List.tail_cons, + Bool.cond_false,Bool.cond_true,Bool.false_eq_true,ite_false,ite_true] + all_goals + congr 2 + funext k + cases k with + | inl k => + by_cases h:k=M.k₀ + · subst k; simp [readTapes,initList] + · simp [readTapes,initList,Function.update,h] + | inr k => cases k; simp [readTapes,Function.update] +lemma payload_step (b : Bool) (v acc : List Bool) : + (machine M ei eo).step (readCfg M ei eo (some false) (b::v) acc)= + some (readCfg M ei eo none v (b::acc)) := by + change some (TM2.stepAux (extra M ei eo (some false)) (M.initialState,none) (readTapes M ei (b::v) acc))=_ + simp only [extra,TM2.stepAux,read_input,List.map_cons,List.head?_cons,Option.map_some, + Equiv.apply_symm_apply,Option.getD_some,List.tail_cons] + congr 2 + funext k + cases k with + | inl k => + by_cases h:k=M.k₀ + · subst k; simp [readTapes,initList] + · simp [readTapes,initList,Function.update,h] + | inr k => cases k; simp [readTapes,Function.update] +open MinUncutGames.BinaryEncoding +lemma read_frames (bits v acc : List Bool) : + Steps (machine M ei eo).step (frame bits).length + (readCfg M ei eo none (frame bits++v) acc) + (embedded M ei eo ((frame bits).reverse++acc) (initList M (v.map ei.symm))) := by + induction bits generalizing acc with + | nil => exact steps_one (read_step M ei eo false v acc) + | cons b bits ih => + have h1 := steps_one (read_step M ei eo true (b::(frame bits++v)) acc) + have h2 := steps_one (payload_step M ei eo b (frame bits++v) (true::acc)) + have hh := steps_trans (steps_trans h1 h2) (ih (b::true::acc)) + simpa only [frame,List.cons_append,List.length_cons,List.reverse_cons,List.append_assoc, + List.singleton_append,List.nil_append,Nat.add_comm,Nat.add_left_comm,Nat.add_assoc] using hh +lemma read_init (v : List Bool) : + readCfg M ei eo none v []=initList (machine M ei eo) (v.map ei.symm) := by + change TM2.Cfg.mk _ _ _=TM2.Cfg.mk _ _ _ + congr 1 + funext k + cases k with + | inl k => + by_cases h:k=M.k₀ <;> simp [readTapes,initList,h,machine] + rfl + | inr k => simp [readTapes,initList,machine] +lemma finish_step (b : Bool) (w acc : List Bool) : + (machine M ei eo).step (embedded M ei eo (b::acc) (haltList M (w.map eo.symm)))= + some (embedded M ei eo acc (haltList M ((b::w).map eo.symm))) := by + change some (TM2.stepAux (extra M ei eo (some true)) (M.initialState,none) + (MachineEmbedding.tapes (haltList M (w.map eo.symm)).stk (fun _ : Unit=>b::acc)))=_ + simp only [extra,TM2.stepAux,MachineEmbedding.tapes_inr,List.head?_cons,List.tail_cons, + Option.isSome_some,Bool.cond_true,Option.getD_some] + congr 2 + funext k + cases k with + | inl k => + by_cases h:k=M.k₁ + · subst k; simp [haltList,Function.update] + · simp [haltList,Function.update,h] + | inr k => cases k; simp [haltList,Function.update] +lemma finish_empty (w : List Bool) : + (machine M ei eo).step (embedded M ei eo [] (haltList M (w.map eo.symm)))= + some (haltList (machine M ei eo) (w.map eo.symm)) := by + change some (TM2.stepAux (extra M ei eo (some true)) (M.initialState,none) + (MachineEmbedding.tapes (haltList M (w.map eo.symm)).stk (fun _ : Unit=>[])))=_ + simp only [extra,TM2.stepAux,MachineEmbedding.tapes_inr,List.head?_nil,List.tail_nil, + Option.isSome_none,Bool.cond_false] + congr 2 + funext k + cases k with + | inl k => + by_cases h:k=M.k₁ + · subst k + simp [haltList,Function.update,machine] + rfl + · simp [haltList,Function.update,h,machine] + | inr k => cases k; simp [Function.update,machine] +lemma finish_steps (w acc : List Bool) : + Steps (machine M ei eo).step (acc.length+1) + (embedded M ei eo acc (haltList M (w.map eo.symm))) + (haltList (machine M ei eo) ((acc.reverse++w).map eo.symm)) := by + induction acc generalizing w with + | nil => exact steps_one (finish_empty M ei eo w) + | cons b acc ih => + have hh:=steps_head (finish_step M ei eo b w acc) (ih (b::w)) + simpa only [List.length_cons,List.reverse_cons,List.append_assoc,List.singleton_append] using hh + +def execute (K : ℕ) (v w : List Bool) (B : ℕ) + (h : TM2OutputsInTime M (v.map ei.symm) (some (w.map eo.symm)) B) : + TM2OutputsInTime (machine M ei eo) ((nameBits K++v).map ei.symm) + (some ((nameBits K++w).map eo.symm)) (B+2*(nameBits K).length+1) := by + have hr := steps_timed (read_frames M ei eo K.bits v []) le_rfl + simp only [List.append_nil,read_init] at hr + let hm := MachineComposition.embeddedExecution (some (.inr (some true))) none + (fun _ : Unit=>(nameBits K).reverse) M.m (extra M ei eo) h + have hf := steps_timed (finish_steps M ei eo w (nameBits K).reverse) le_rfl + simp only [List.length_reverse,List.reverse_reverse] at hf + let hh := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ hr hm + let hh' := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ hh hf + exact ⟨hh'.toEvalsTo,by have hb:=hh'.steps_le_m; change _≤B+2*(nameBits K).length+1; simp only [nameBits] at hb ⊢; omega⟩ +end MinUncut.Costed.Framed + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/GraphRenderMachine.lean b/lean/OAI/Computability/MinUncut/Machines/GraphRenderMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..625ce980312818650410f0568f9573783acc878e --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/GraphRenderMachine.lean @@ -0,0 +1,171 @@ +import Mathlib +import OAI.Computability.MinUncut.Graphs.DemandOrder +import OAI.Computability.MinUncut.Machines.ArenaMachineProgram +import OAI.Computability.MinUncut.Machines.CodeFiniteMachine +import OAI.Computability.MinUncut.Graphs.GraphWordCodec + +namespace OAI + +namespace MinUncut.Costed.GraphRegisters +open _root_.Turing _root_.OAI.Turing _root_.Turing.PartrecToTM2 _root_.OAI.Turing.PartrecToTM2 Polynomial MinUncutGames.Foundations.Complexity +open MinUncut.PathRealization +noncomputable section + +def fullGraphMachine : FinTM2 := + MachineSequential.machine (codeMachine rawRenderer.code) GraphCodec.machine id .cons + +lemma fullGraphMachine_finiteAlphabet (k : fullGraphMachine.K) : + Finite (fullGraphMachine.Γ k) := + sequential_finiteAlphabet _ _ _ _ (codeMachine_finiteAlphabet _) GraphCodec.finiteAlphabet k + +def renderTime : Polynomial ℕ := C 10*rawRenderer.bound+10 + +def packedInput {N : ℕ} (ds : List (Demand (Fin N))) (k : ℕ) : List ℕ := + N::ds.length::k::packDemands ds + +lemma rawRenderer_output {N : ℕ} (ds : List (Demand (Fin N))) (k : ℕ) : + renderRaw (packedInput ds k)= + (N+ds.length*3)::((canonicalTable ds).map Bool.toNat++2::k::packDemands ds) := by + rw [packedInput,renderRaw_encode,rawGraphWords,rawTable_pack] + +lemma codec_length_le (n k : ℕ) (v : List Bool) (rest : List ℕ) : + (MinUncutGames.BinaryEncoding.nameBits n++v++MinUncutGames.BinaryEncoding.nameBits k).length≤ + 2*magnitude (n::(v.map Bool.toNat++2::k::rest)) := by + have hf (a : ℕ) : (MinUncutGames.BinaryEncoding.nameBits a).length≤2*a+1 := by + have h := trNat_length_le a + rw [GraphCodec.trNat_bits,List.length_map] at h + have hg (w : List Bool) : (MinUncutGames.BinaryEncoding.frame w).length=2*w.length+1 := by + induction w with + | nil => rfl + | cons b w ih => simp only [MinUncutGames.BinaryEncoding.frame,List.length_cons,ih]; omega + rw [MinUncutGames.BinaryEncoding.nameBits,hg] + omega + have hm (w : List Bool) : w.length+k+3≤ magnitude (w.map Bool.toNat++2::k::rest) := by + induction w with + | nil => simp only [List.map_nil,List.nil_append,magnitude_cons,List.length_nil]; omega + | cons b w ih => + simp only [List.map_cons,List.cons_append,magnitude_cons,List.length_cons] + omega + have hn := hf n; have hk := hf k; have h := hm v + simp only [List.length_append,magnitude_cons] + omega + +def fullGraphMachine_outputs {N : ℕ} (ds : List (Demand (Fin N))) (k : ℕ) (hk : 1≤k) : + TM2OutputsInTime fullGraphMachine (trList (packedInput ds k)) + (some (listOutput ds k hk).bits) (renderTime.eval (magnitude (packedInput ds k))) := by + apply Classical.choice + obtain ⟨t,ht,hc⟩ := rawRenderer.run (packedInput ds k) + rw [rawRenderer_output] at hc + have h1 := hc.finiteMachine + have h2 := GraphCodec.outputsInTime (N+ds.length*3) k (canonicalTable ds) (packDemands ds) + have h2' : TM2OutputsInTime GraphCodec.machine + ((trList ((N+ds.length*3)::((canonicalTable ds).map Bool.toNat++2::k::packDemands ds))).map id) + (some (MinUncutGames.BinaryEncoding.nameBits (N+ds.length*3)++canonicalTable ds++MinUncutGames.BinaryEncoding.nameBits k)) + (2*bitsize ((N+ds.length*3)::((canonicalTable ds).map Bool.toNat++2::k::packDemands ds))+ + (MinUncutGames.BinaryEncoding.nameBits (N+ds.length*3)++canonicalTable ds++MinUncutGames.BinaryEncoding.nameBits k).length+2) := by + erw [List.map_id] + exact h2 + have h := MachineSequential.execute (codeMachine rawRenderer.code) GraphCodec.machine id Γ'.cons + _ _ _ _ _ h1 h2' + have hm := rawRenderer.size (packedInput ds k) + rw [rawRenderer_output] at hm + have hb := (bitsize_le_magnitude _).trans hm + have hl := codec_length_le (N+ds.length*3) k (canonicalTable ds) (packDemands ds) + rw [←listOutput_bits ds k hk] at h + refine ⟨⟨h.toEvalsTo,le_trans h.steps_le_m ?_⟩⟩ + simp only [renderTime,eval_add,eval_mul,eval_C,eval_ofNat] + have hb2 := bitsize_le_magnitude ((N+ds.length*3)::((canonicalTable ds).map Bool.toNat++2::k::packDemands ds)) + have hl2 := hl + rw [←listOutput_bits ds k hk] at hl2 + change t + 1 + 2 * ((trList ((N+ds.length*3)::((canonicalTable ds).map Bool.toNat++2::k::packDemands ds))).length + 1) + + (2*bitsize ((N+ds.length*3)::((canonicalTable ds).map Bool.toNat++2::k::packDemands ds))+(listOutput ds k hk).bits.length+2) ≤ _ + simp only [bitsize] at hb hb2 ⊢ + omega + +end +end MinUncut.Costed.GraphRegisters + +namespace MinUncut.Costed.Arena +open _root_.Turing _root_.OAI.Turing _root_.Turing.PartrecToTM2 _root_.OAI.Turing.PartrecToTM2 Turing.ToPartrec Polynomial +open MinUncutGames.Foundations.Complexity +noncomputable section + +def universalWords (v : List ℕ) : List ℕ := + let z := prepareOutput (control v) + let r := (outputStep^[z.headI] z.tail).drop 2 + (prefixStep^[r.headI] (0::r.tail)).tail + +def universalWordsProgram : PolyProgram universalWords := + reversePrefixProgram.comp ((PolyProgram.drop 2).comp + (outputLoopProgram.comp (prepareOutputProgram.comp controlProgram))) + +lemma universalWords_spec {c v w B} (hr : Runs c v w B) (hl : w.length≤B) (base : Heap) : + ∃h,universalWords (B::(initialState c v base).encode)=w++w.reverse++2::words h := by + obtain ⟨t,ht,hc⟩ := hr + obtain ⟨h,out,ho,he⟩ := CodeRun.interpreted hc base ht + refine ⟨h,?_⟩ + have hh : control (B::(initialState c v base).encode)=B::(State.mk 2 0 out 0 h).encode := by + simpa only [control,List.headI_cons,keepTick_iter] using congrArg (List.cons B) he + simp only [universalWords,hh] + have hp : prepareOutput (B::(State.mk 2 0 out 0 h).encode)=B::(OutputState.mk out h []).encode := rfl + rw [hp] + simp only [List.headI_cons,List.tail_cons] + rw [ho.output_padded [] hl] + simp only [List.append_nil,OutputState.encode,List.cons_append,List.nil_append, + List.drop_succ_cons,List.drop_zero,List.headI_cons,List.tail_cons] + rw [reversePrefix_spec,List.reverse_reverse,List.append_assoc] + +def universalGraphMachine : FinTM2 := + MachineSequential.machine (codeMachine universalWordsProgram.code) GraphCodec.machine id .cons + +lemma universalGraphMachine_finiteAlphabet (k : universalGraphMachine.K) : + Finite (universalGraphMachine.Γ k) := + sequential_finiteAlphabet _ _ _ _ (codeMachine_finiteAlphabet _) GraphCodec.finiteAlphabet k + +def universalGraphTime : Polynomial ℕ := C 10*universalWordsProgram.bound+10 + +def graphPacked (c : Code) (v : List ℕ) (B : ℕ) : List ℕ := B::(initialState c v []).encode + +def universalGraphMachine_outputs {c : Code} {v : List ℕ} {B n k : ℕ} + {table : List Bool} {rest : List ℕ} + (hc : Runs c v (n::(table.map Bool.toNat++2::k::rest)) B) + (hl : (n::(table.map Bool.toNat++2::k::rest)).length≤B) : + TM2OutputsInTime universalGraphMachine (trList (graphPacked c v B)) + (some (MinUncutGames.BinaryEncoding.nameBits n++table++MinUncutGames.BinaryEncoding.nameBits k)) + (universalGraphTime.eval (magnitude (graphPacked c v B))) := by + apply Classical.choice + obtain ⟨h,he⟩ := universalWords_spec hc hl [] + let junk := rest++(n::(table.map Bool.toNat++2::k::rest)).reverse++2::words h + have he' : universalWords (graphPacked c v B)=n::(table.map Bool.toNat++2::k::junk) := by + simpa only [graphPacked,List.cons_append,List.append_assoc,junk] using he + obtain ⟨t,ht,hr⟩ := universalWordsProgram.run (graphPacked c v B) + rw [he'] at hr + have h1 := hr.finiteMachine + have h2 := GraphCodec.outputsInTime n k table junk + have h2' : TM2OutputsInTime GraphCodec.machine + ((trList (n::(table.map Bool.toNat++2::k::junk))).map id) + (some (MinUncutGames.BinaryEncoding.nameBits n++table++MinUncutGames.BinaryEncoding.nameBits k)) + (2*bitsize (n::(table.map Bool.toNat++2::k::junk))+ + (MinUncutGames.BinaryEncoding.nameBits n++table++MinUncutGames.BinaryEncoding.nameBits k).length+2) := by + have input_eq : @List.map (GraphCodec.machine.Γ GraphCodec.machine.k₀) + (GraphCodec.machine.Γ GraphCodec.machine.k₀) id + (trList (n::(table.map Bool.toNat++2::k::junk))) = + trList (n::(table.map Bool.toNat++2::k::junk)) := List.map_id _ + simpa only [input_eq] using h2 + have hh := MachineSequential.execute (codeMachine universalWordsProgram.code) GraphCodec.machine id Γ'.cons + _ _ _ _ _ h1 h2' + have hm := universalWordsProgram.size (graphPacked c v B) + rw [he'] at hm + have hb := bitsize_le_magnitude (n::(table.map Bool.toNat++2::k::junk)) + have ho := GraphRegisters.codec_length_le n k table junk + refine ⟨⟨hh.toEvalsTo,hh.steps_le_m.trans ?_⟩⟩ + change t+1+2*((trList (n::(table.map Bool.toNat++2::k::junk))).length+1)+ + (2*bitsize (n::(table.map Bool.toNat++2::k::junk))+ + (MinUncutGames.BinaryEncoding.nameBits n++table++MinUncutGames.BinaryEncoding.nameBits k).length+2)≤_ + simp only [universalGraphTime,eval_add,eval_mul,eval_C,eval_ofNat] + simp only [bitsize] at hb ⊢ + omega +end +end MinUncut.Costed.Arena + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/Input.lean b/lean/OAI/Computability/MinUncut/Machines/Input.lean new file mode 100644 index 0000000000000000000000000000000000000000..b8f5721a97166d6ca5decb486c072157fc9fb82e --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/Input.lean @@ -0,0 +1,785 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.PoweringOpinionTables + +namespace OAI + +section +namespace MinUncutGames.Foundations.PCP.AlphabetTable.Input + +open MinUncutGames.Foundations.Complexity + +export GenericGraphTables (Label RelationTable DartRow Rows Valid Table + relationIndex relationIndex_val relationAt relationOf relationAt_relationOf + reverseAt acceptsAt rowList rowList_length semantics semantics_reverse + semantics_tail semantics_accepts ofGraph semantics_ofGraph ofEnumeratedGraph + bitWord relationWords relationWords_length rowWords rowWords_length + rowsWords_length tableWords tableWords_length tableBits encoding + parseRelation parseRow parseRows decodeTableWords decodeTableBits + parseRelation_encoded parseRow_encoded parseRows_encoded + decodeTableWords_encoded decodeTableBits_encoded tableBits_injective + relationBits_length_le rowBits_length_le rowsBits_length_le tableWords_length_le_bits + tableBits_length_le vertices_le_tableBits_length darts_le_tableBits_length) + +variable {q n m : Nat} + +abbrev rowWidth (q : Nat) : Nat := q * q + 2 + +def rowOffset (q e : Nat) : Nat := 2 + rowWidth q * e + +theorem rowsWords_split (rows : List (DartRow q n m)) (e : Nat) + (he : e < rows.length) : + rows.flatMap rowWords = (rows.take e).flatMap rowWords ++ + (rowWords rows[e] ++ (rows.drop (e + 1)).flatMap rowWords) := by + have hs : rows.take e ++ rows[e] :: rows.drop (e + 1) = rows := by + rw [List.getElem_cons_drop he, List.take_append_drop] + have hw := congrArg (fun rs : List (DartRow q n m) => rs.flatMap rowWords) hs + simpa only [List.flatMap_append, List.flatMap_cons, List.append_assoc] using hw.symm + +theorem rowsBits_split (rows : List (DartRow q n m)) (e : Nat) + (he : e < rows.length) : + encodeWords (rows.flatMap rowWords) = + encodeWords ((rows.take e).flatMap rowWords) ++ + (encodeWords (rowWords rows[e]) ++ + encodeWords ((rows.drop (e + 1)).flatMap rowWords)) := by + rw [rowsWords_split rows e he] + simp only [encodeWords_append] + +theorem rowsBits_append_split (rows : List (DartRow q n m)) (e : Nat) + (he : e < rows.length) (suffix : List Bool) : + encodeWords (rows.flatMap rowWords) ++ suffix = + encodeWords ((rows.take e).flatMap rowWords) ++ + (encodeWords (rowWords rows[e]) ++ + (encodeWords ((rows.drop (e + 1)).flatMap rowWords) ++ suffix)) := by + rw [rowsBits_split rows e he] + simp only [List.append_assoc] + +def prefixWords (table : Table q) (e : Fin table.darts) : List Nat := + [table.vertices, table.darts] ++ ((rowList table).take e.val).flatMap rowWords + +def suffixWords (table : Table q) (e : Fin table.darts) : List Nat := + ((rowList table).drop (e.val + 1)).flatMap rowWords + +theorem prefixWords_length (table : Table q) (e : Fin table.darts) : + (prefixWords table e).length = rowOffset q e.val := by + simp [prefixWords, rowOffset, rowWidth, Nat.mul_comm, Nat.add_comm] + omega + +theorem tableWords_at_row (table : Table q) (e : Fin table.darts) : + tableWords table = prefixWords table e ++ + (rowWords table.rows[e] ++ suffixWords table e) := by + have hs := rowsWords_split (rowList table) e.val (by simpa only [rowList_length] using e.isLt) + simp only [rowList, Vector.getElem_toList] at hs + unfold tableWords prefixWords suffixWords rowList + rw [hs] + simp only [List.append_assoc, Fin.getElem_fin] + +theorem tableBits_at_row (table : Table q) (e : Fin table.darts) : + tableBits table = encodeWords (prefixWords table e) ++ + (encodeWords (rowWords table.rows[e]) ++ encodeWords (suffixWords table e)) := by + rw [tableBits, tableWords_at_row table e] + simp only [encodeWords_append] + +theorem tableBits_header (table : Table q) : + tableBits table = encodeWord table.vertices ++ + (encodeWord table.darts ++ encodeWords ((rowList table).flatMap rowWords)) := by + simp [tableBits, tableWords, encodeWords] + +theorem tableWords_drop_row (table : Table q) (e : Fin table.darts) : + (tableWords table).drop (rowOffset q e.val) = + rowWords table.rows[e] ++ suffixWords table e := by + rw [tableWords_at_row table e] + exact List.drop_left' (l₂ := rowWords table.rows[e] ++ suffixWords table e) + (prefixWords_length table e) + +theorem tableWords_take_row (table : Table q) (e : Fin table.darts) : + ((tableWords table).drop (rowOffset q e.val)).take (rowWidth q) = + rowWords table.rows[e] := by + rw [tableWords_drop_row] + exact List.take_left' (l₂ := suffixWords table e) (rowWords_length table.rows[e]) + +theorem tableWords_get_tail (table : Table q) (e : Fin table.darts) : + (tableWords table)[rowOffset q e.val]? = some table.rows[e].tail.val := by + have h := congrArg (fun words : List Nat => words[0]?) (tableWords_drop_row table e) + simpa [List.getElem?_drop, rowWords] using h + +theorem tableWords_get_reverse (table : Table q) (e : Fin table.darts) : + (tableWords table)[rowOffset q e.val + 1]? = some table.rows[e].reverseIndex.val := by + have h := congrArg (fun words : List Nat => words[1]?) (tableWords_drop_row table e) + simpa [List.getElem?_drop, rowWords] using h + +theorem tableWords_drop_relation (table : Table q) (e : Fin table.darts) : + (tableWords table).drop (rowOffset q e.val + 2) = + relationWords table.rows[e].relation ++ suffixWords table e := by + rw [← List.drop_drop, tableWords_drop_row] + simp [rowWords] + +theorem relationWords_get (relation : RelationTable q) (j : Fin (q * q)) : + (relationWords relation)[j.val]? = some (bitWord relation[j]) := by + rw [List.getElem?_eq_getElem (by simpa only [relationWords_length] using j.isLt)] + simp [relationWords] + +theorem tableWords_get_relation (table : Table q) (e : Fin table.darts) + (j : Fin (q * q)) : + (tableWords table)[rowOffset q e.val + 2 + j.val]? = + some (bitWord table.rows[e].relation[j]) := by + have h := congrArg (fun words : List Nat => words[j.val]?) + (tableWords_drop_relation table e) + rw [List.getElem?_drop, + List.getElem?_append_left (by simpa only [relationWords_length] using j.isLt), relationWords_get] at h + exact h + +theorem tableWords_get_predicate (table : Table q) (e : Fin table.darts) + (a b : Label q) : + (tableWords table)[rowOffset q e.val + 2 + (b.val + q * a.val)]? = + some (bitWord ((semantics table).accepts e a b)) := by + simpa only [relationIndex_val, semantics_accepts, relationAt] using + tableWords_get_relation table e ((relationIndex q) (a, b)) + +theorem rowOffset_lt_length (table : Table q) (e : Fin table.darts) : + rowOffset q e.val < (tableWords table).length := by + rw [tableWords_length] + have h := Nat.mul_le_mul_left (rowWidth q) (Nat.succ_le_of_lt e.isLt) + rw [Nat.mul_succ] at h + unfold rowOffset rowWidth at * + omega + +theorem relationOffset_lt_length (table : Table q) (e : Fin table.darts) + (j : Fin (q * q)) : + rowOffset q e.val + 2 + j.val < (tableWords table).length := by + rw [tableWords_length] + have h := Nat.mul_le_mul_left (rowWidth q) (Nat.succ_le_of_lt e.isLt) + rw [Nat.mul_succ] at h + have hj := j.isLt + unfold rowOffset rowWidth at * + omega + +end MinUncutGames.Foundations.PCP.AlphabetTable.Input + +end +section +namespace MinUncutGames.Foundations.PCP.AlphabetTable.Setup + +open Turing +open MinUncutGames.Foundations.Complexity +open MinUncutGames.Foundations.Hastad + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool + +abbrev Ports (K : Type) := Fin 7 → K + +inductive Label + | copyFirst | copySecond | verticesStart | verticesLoop + | dartsStart | dartsLoop | counterFirst | counterSecond | initialize + deriving DecidableEq + +protected abbrev Label.enumList : List Label := [.copyFirst, .copySecond, .verticesStart, + .verticesLoop, .dartsStart, .dartsLoop, .counterFirst, .counterSecond, .initialize] + +protected theorem Label.enumList_getElem?_ctorIdx_eq (x : Label) : + Label.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem Label.enumList_nodup : Label.enumList.Nodup := by decide + +instance : Fintype Label where + elems := ⟨Label.enumList, Label.enumList_nodup⟩ + complete x := by cases x <;> decide + +def statement (ports : Ports K) (labels : Label → Λ) (exit : Option Λ) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) + | .copyFirst => Reduction.MachineTransfer.loopAt (ports 0) (ports 5) id false + (labels .copyFirst) (some (labels .copySecond)) + | .copySecond => MachineCopy.forkLoop (ports 5) (ports 0) (ports 1) false + (labels .copySecond) (some (labels .verticesStart)) + | .verticesStart => SourceMachine.fieldStart (ports 2) (labels .verticesLoop) + | .verticesLoop => SourceMachine.fieldLoop (ports 1) (ports 2) + (labels .verticesLoop) (some (labels .dartsStart)) + | .dartsStart => SourceMachine.fieldStart (ports 3) (labels .dartsLoop) + | .dartsLoop => SourceMachine.fieldLoop (ports 1) (ports 3) + (labels .dartsLoop) (some (labels .counterFirst)) + | .counterFirst => Reduction.MachineTransfer.loopAt (ports 3) (ports 5) id false + (labels .counterFirst) (some (labels .counterSecond)) + | .counterSecond => MachineCopy.forkLoop (ports 5) (ports 3) (ports 4) false + (labels .counterSecond) (some (labels .initialize)) + | .initialize => .push (ports 6) (fun _ => false) + (.load (fun state => (state.1, none)) (Reduction.MachineTransfer.exitAt (ports 6) exit)) + +def resultTapes (ports : Ports K) (base : K → List Bool) + (n m : Nat) (rows : List Bool) : K → List Bool := + Function.update + (Function.update + (Function.update + (Function.update (Function.update base (ports 1) rows) + (ports 2) (encodeWord n)) (ports 3) (encodeWord m)) + (ports 4) (encodeWord m)) (ports 6) (encodeWord 0) + +theorem resultTapes_other (ports : Ports K) (base : K → List Bool) + (n m : Nat) (rows : List Bool) (tape : K) + (h : ∀ i : Fin 7, i ≠ 0 → i ≠ 5 → tape ≠ ports i) : + resultTapes ports base n m rows tape = base tape := by + simp [resultTapes, h] + +def setupInTime (ports : Ports K) (distinct : Function.Injective ports) + (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atLabels : ∀ label, program (labels label) = statement ports labels exit label) + (base : K → List Bool) (n m : Nat) (rows : List Bool) + (initial : ∀ i : Fin 7, base (ports i) = + if i = 0 then encodeWord n ++ (encodeWord m ++ rows) else []) + (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .copyFirst), (ambient, register), base⟩ + (some ⟨exit, (ambient, none), resultTapes ports base n m rows⟩) + (2 * (encodeWord n ++ (encodeWord m ++ rows)).length + n + 3 * m + 11) := by + let input := encodeWord n ++ (encodeWord m ++ rows) + let t₀ := Function.update base (ports 1) input + let t₁ := SourceMachine.afterField (ports 1) (ports 2) t₀ n (encodeWord m ++ rows) + let t₂ := SourceMachine.afterField (ports 1) (ports 3) t₁ m rows + let t₃ := Function.update t₂ (ports 4) (encodeWord m) + have hne {i j : Fin 7} (h : i ≠ j) : ports i ≠ ports j := fun e => h (distinct e) + have run₀ := MachineCopy.copyInTime (ports 0) (ports 1) (ports 5) + (hne (by decide)) (hne (by decide)) (hne (by decide)) false + (labels .copyFirst) (labels .copySecond) (some (labels .verticesStart)) + program (atLabels .copyFirst) (atLabels .copySecond) base + (by simp [initial]) ambient register + have hb0 : base (ports 0) = input := by simpa [input] using initial 0 + have hb1 : base (ports 1) = [] := by simpa using initial 1 + rw [hb0, hb1, List.append_nil] at run₀ + change StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .copyFirst), (ambient, register), base⟩ + (some ⟨some (labels .verticesStart), (ambient, none), t₀⟩) + (2 * (input.length + 1)) at run₀ + have run₁ := SourceMachine.fieldInTime (ports 1) (ports 2) (hne (by decide)) + (labels .verticesStart) (labels .verticesLoop) (some (labels .dartsStart)) + program (atLabels .verticesStart) (atLabels .verticesLoop) + t₀ n (encodeWord m ++ rows) (by simp [t₀, input]) ambient none + have run₂ := SourceMachine.fieldInTime (ports 1) (ports 3) (hne (by decide)) + (labels .dartsStart) (labels .dartsLoop) (some (labels .counterFirst)) + program (atLabels .dartsStart) (atLabels .dartsLoop) + t₁ m rows (by simp [t₁, SourceMachine.afterField, distinct.eq_iff]) ambient none + have h₂m : t₂ (ports 3) = encodeWord m := by + simp [t₂, t₁, t₀, SourceMachine.afterField, SourceMachine.fieldTapes, + distinct.eq_iff, initial] + have h₂c : t₂ (ports 4) = [] := by + simp [t₂, t₁, t₀, SourceMachine.afterField, SourceMachine.fieldTapes, + distinct.eq_iff, initial] + have h₂s : t₂ (ports 5) = [] := by + simp [t₂, t₁, t₀, SourceMachine.afterField, SourceMachine.fieldTapes, + distinct.eq_iff, initial] + have run₃ := MachineCopy.copyInTime (ports 3) (ports 4) (ports 5) + (hne (by decide)) (hne (by decide)) (hne (by decide)) false + (labels .counterFirst) (labels .counterSecond) (some (labels .initialize)) + program (atLabels .counterFirst) (atLabels .counterSecond) t₂ h₂s ambient none + rw [h₂m, h₂c, List.append_nil, encodeWord_length] at run₃ + have h₃e : t₃ (ports 6) = [] := by + simp [t₃, t₂, t₁, t₀, SourceMachine.afterField, SourceMachine.fieldTapes, + distinct.eq_iff, initial] + have hresult : Function.update t₃ (ports 6) [false] = + resultTapes ports base n m rows := by + funext tape + by_cases h1 : tape = ports 1 + · subst tape; simp [t₃, t₂, t₁, t₀, SourceMachine.afterField, + SourceMachine.fieldTapes, resultTapes, distinct.eq_iff] + · by_cases h2 : tape = ports 2 + · subst tape; simp [t₃, t₂, t₁, t₀, SourceMachine.afterField, + SourceMachine.fieldTapes, resultTapes, distinct.eq_iff, initial] + · by_cases h3 : tape = ports 3 + · subst tape; simp [t₃, t₂, t₁, t₀, SourceMachine.afterField, + SourceMachine.fieldTapes, resultTapes, distinct.eq_iff, initial] + · simp [t₃, t₂, t₁, t₀, SourceMachine.afterField, SourceMachine.fieldTapes, + resultTapes, Function.update_apply, h1, h2, h3, encodeWord] + have run₄ : StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .initialize), (ambient, none), t₃⟩ + (some ⟨exit, (ambient, none), resultTapes ports base n m rows⟩) 1 := { + steps := 1 + evals_in_steps := by + change some (TM2.stepAux (program (labels .initialize)) (ambient, none) t₃) = _ + rw [atLabels] + cases exit <;> simp [statement, TM2.stepAux, Reduction.MachineTransfer.exitAt, + h₃e, hresult] + steps_le_m := Nat.le_refl _ } + 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₄ + exact { + toEvalsTo := run.toEvalsTo + steps_le_m := by + have h := run.steps_le_m + dsimp [input] at h + omega } + +def tableSetupInTime {q : Nat} (ports : Ports K) (distinct : Function.Injective ports) + (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atLabels : ∀ label, program (labels label) = statement ports labels exit label) + (base : K → List Bool) (table : GenericGraphTables.Table q) + (initial : ∀ i : Fin 7, base (ports i) = + if i = 0 then GenericGraphTables.tableBits table else []) + (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .copyFirst), (ambient, register), base⟩ + (some ⟨exit, (ambient, none), resultTapes ports base table.vertices table.darts + (encodeWords ((GenericGraphTables.rowList table).flatMap GenericGraphTables.rowWords))⟩) + (6 * (GenericGraphTables.tableBits table).length + 11) := by + have hb := Input.tableBits_header table + let run := setupInTime ports distinct labels exit program atLabels base + table.vertices table.darts + (encodeWords ((GenericGraphTables.rowList table).flatMap GenericGraphTables.rowWords)) + (by intro i; rw [initial i, hb]) ambient register + have hn := GenericGraphTables.vertices_le_tableBits_length table + have hm := GenericGraphTables.darts_le_tableBits_length table + exact { + toEvalsTo := run.toEvalsTo + steps_le_m := by + have h := run.steps_le_m + have hlen := congrArg List.length hb + omega } + +def program (ports : Ports K) : Label → TM2.Stmt (Alphabet (K := K)) Label (σ × Option Bool) := + statement ports id none + +def machine : FinTM2 where + K := Fin 7 + k₀ := 0 + k₁ := 1 + Γ _ := Bool + Λ := Label + main := .copyFirst + σ := Unit × Option Bool + initialState := ((), none) + m := program id + +end MinUncutGames.Foundations.PCP.AlphabetTable.Setup + +end +section +namespace MinUncutGames.Foundations.PCP.AlphabetTable.ReadRelation + +open Turing +open MinUncutGames.Foundations.Complexity +open GenericGraphTables + +variable {K Λ σ : Type} [DecidableEq K] {q : Nat} + +abbrev Alphabet (_ : K) := Bool +abbrev State (σ : Type) (q : Nat) := (σ × RelationTable q) × Option Bool + +def relationEquiv (q : Nat) : RelationTable q ≃ (Fin (q * q) → Bool) where + toFun relation i := relation[i.val] + invFun := Vector.ofFn + left_inv relation := Vector.ofFn_getElem + right_inv bits := by funext i; simp + +@[instance_reducible] def relationFintype (q : Nat) : Fintype (RelationTable q) := + Fintype.ofEquiv (Fin (q * q) → Bool) (relationEquiv q).symm + +@[instance_reducible] def stateFintype (σ : Type) (q : Nat) [Fintype σ] : + Fintype (State σ q) := by + letI := relationFintype q + exact inferInstance + +def readSlot (source : K) (i : Fin (q * q)) + (next : TM2.Stmt (Alphabet (K := K)) Λ (State σ q)) : + TM2.Stmt (Alphabet (K := K)) Λ (State σ q) := + .pop source + (fun state head => + ((state.1.1, state.1.2.set i.val (head.getD false) i.isLt), head)) + (.branch (fun state => state.2.getD false) + (.pop source (fun state _ => (state.1, none)) next) + (.load (fun state => (state.1, none)) next)) + +theorem stepAux_readSlot (source : K) (i : Fin (q * q)) (bit : Bool) + (next : TM2.Stmt (Alphabet (K := K)) Λ (State σ q)) + (base : K → List Bool) (suffix : List Bool) (ambient : σ) + (initial : RelationTable q) (register : Option Bool) : + TM2.stepAux (readSlot source i next) ((ambient, initial), register) + (Function.update base source (encodeWord (bitWord bit) ++ suffix)) = + TM2.stepAux next ((ambient, initial.set i.val bit i.isLt), none) + (Function.update base source suffix) := by + cases bit <;> simp [readSlot, TM2.stepAux, bitWord, encodeWord] + +def readSlots (source : K) : List (Fin (q * q)) → + TM2.Stmt (Alphabet (K := K)) Λ (State σ q) → + TM2.Stmt (Alphabet (K := K)) Λ (State σ q) + | [], next => .load (fun state => (state.1, none)) next + | i :: indices, next => readSlot source i (readSlots source indices next) + +def indexedWords (relation : RelationTable q) (indices : List (Fin (q * q))) : List Nat := + indices.map (fun i => bitWord relation[i.val]) + +def fillSlots (relation : RelationTable q) : List (Fin (q * q)) → + RelationTable q → RelationTable q + | [], initial => initial + | i :: indices, initial => + fillSlots relation indices (initial.set i.val relation[i.val] i.isLt) + +theorem fillSlots_preserves_correct (relation : RelationTable q) + (indices : List (Fin (q * q))) (initial : RelationTable q) (i : Fin (q * q)) + (hcorrect : initial[i.val] = relation[i.val]) : + (fillSlots relation indices initial)[i.val] = relation[i.val] := by + induction indices generalizing initial with + | nil => exact hcorrect + | cons j indices ih => + apply ih + by_cases hji : j.val = i.val + · simp [hji] + · simp [hji, hcorrect] + +theorem fillSlots_mem (relation : RelationTable q) (indices : List (Fin (q * q))) + (initial : RelationTable q) (i : Fin (q * q)) (hi : i ∈ indices) : + (fillSlots relation indices initial)[i.val] = relation[i.val] := by + induction indices generalizing initial with + | nil => simp at hi + | cons j indices ih => + change (fillSlots relation indices (initial.set j.val relation[j.val] j.isLt))[i.val] = _ + rcases List.mem_cons.mp hi with h | h + · subst j + apply fillSlots_preserves_correct + simp + · exact ih _ h + +theorem fillSlots_finRange (relation initial : RelationTable q) : + fillSlots relation (List.finRange (q * q)) initial = relation := by + apply Vector.ext + intro i hi + exact fillSlots_mem relation (List.finRange (q * q)) initial ⟨i, hi⟩ + (List.mem_finRange _) + +theorem indexedWords_finRange (relation : RelationTable q) : + indexedWords relation (List.finRange (q * q)) = relationWords relation := by + have h : (List.finRange (q * q)).map (fun i => relation[i.val]) = relation.toList := by + rw [List.finRange, List.map_ofFn] + change List.ofFn (fun i : Fin (q * q) => relation[i.val]) = relation.toList + rw [← Vector.toList_ofFn, Vector.ofFn_getElem] + calc + _ = ((List.finRange (q * q)).map (fun i => relation[i.val])).map bitWord := by + simp only [indexedWords, List.map_map, Function.comp_def] + _ = relation.toList.map bitWord := congrArg (fun bits : List Bool => bits.map bitWord) h + _ = _ := rfl + +theorem stepAux_readSlots (source : K) (indices : List (Fin (q * q))) + (relation : RelationTable q) + (next : TM2.Stmt (Alphabet (K := K)) Λ (State σ q)) + (base : K → List Bool) (suffix : List Bool) (ambient : σ) + (initial : RelationTable q) (register : Option Bool) : + TM2.stepAux (readSlots source indices next) ((ambient, initial), register) + (Function.update base source (encodeWords (indexedWords relation indices) ++ suffix)) = + TM2.stepAux next ((ambient, fillSlots relation indices initial), none) + (Function.update base source suffix) := by + induction indices generalizing initial register with + | nil => simp [readSlots, fillSlots, indexedWords, encodeWords, TM2.stepAux] + | cons i indices ih => + simp only [readSlots, indexedWords, List.map_cons, encodeWords, List.append_assoc, fillSlots] + rw [stepAux_readSlot] + exact ih _ none + +def readRelation (source : K) + (next : TM2.Stmt (Alphabet (K := K)) Λ (State σ q)) : + TM2.Stmt (Alphabet (K := K)) Λ (State σ q) := + readSlots source (List.finRange (q * q)) next + +theorem stepAux_readRelation (source : K) (relation : RelationTable q) + (next : TM2.Stmt (Alphabet (K := K)) Λ (State σ q)) + (base : K → List Bool) (suffix : List Bool) (ambient : σ) + (initial : RelationTable q) (register : Option Bool) : + TM2.stepAux (readRelation source next) ((ambient, initial), register) + (Function.update base source (encodeWords (relationWords relation) ++ suffix)) = + TM2.stepAux next ((ambient, relation), none) (Function.update base source suffix) := by + simpa only [readRelation, indexedWords_finRange, fillSlots_finRange] using + stepAux_readSlots source (List.finRange (q * q)) relation next + base suffix ambient initial register + +theorem stepAux_readRelation_fromTapes (source : K) (relation : RelationTable q) + (next : TM2.Stmt (Alphabet (K := K)) Λ (State σ q)) + (base : K → List Bool) (suffix : List Bool) + (hinput : base source = encodeWords (relationWords relation) ++ suffix) + (ambient : σ) (initial : RelationTable q) (register : Option Bool) : + TM2.stepAux (readRelation source next) ((ambient, initial), register) base = + TM2.stepAux next ((ambient, relation), none) (Function.update base source suffix) := by + have h := stepAux_readRelation source relation next base suffix ambient initial register + have hbase : Function.update base source (encodeWords (relationWords relation) ++ suffix) = + base := by rw [← hinput]; exact Function.update_eq_self source base + rw [hbase] at h + exact h + +omit [DecidableEq K] in +theorem readSlots_pushBound (source : K) (indices : List (Fin (q * q))) + (next : TM2.Stmt (Alphabet (K := K)) Λ (State σ q)) : + Runtime.statementPushBound (readSlots source indices next) = + Runtime.statementPushBound next := by + induction indices with + | nil => rfl + | cons i indices ih => + simp only [readSlots, readSlot, Runtime.statementPushBound, ih, max_self] + +omit [DecidableEq K] in +theorem readRelation_pushBound (source : K) + (next : TM2.Stmt (Alphabet (K := K)) Λ (State σ q)) : + Runtime.statementPushBound (readRelation source next) = + Runtime.statementPushBound next := + readSlots_pushBound source (List.finRange (q * q)) next + +def parser (source : K) (exitLabel : Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (State σ q) := + readRelation source (.goto fun _ => exitLabel) + +omit [DecidableEq K] in +theorem parser_pushBound (source : K) (exitLabel : Λ) : + Runtime.statementPushBound (parser (σ := σ) (q := q) source exitLabel) = 0 := by + rw [parser, readRelation_pushBound] + rfl + +theorem parserStep (source : K) (readLabel exitLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ q)) + (atRead : program readLabel = parser source exitLabel) + (base : K → List Bool) (relation : RelationTable q) (suffix : List Bool) + (ambient : σ) (initial : RelationTable q) (register : Option Bool) : + TM2.step program + ⟨some readLabel, ((ambient, initial), register), + Function.update base source (encodeWords (relationWords relation) ++ suffix)⟩ = + some ⟨some exitLabel, ((ambient, relation), none), Function.update base source suffix⟩ := by + change some (TM2.stepAux (program readLabel) ((ambient, initial), register) + (Function.update base source (encodeWords (relationWords relation) ++ suffix))) = _ + rw [atRead, parser, stepAux_readRelation] + rfl + +theorem parserTrace (source : K) (readLabel exitLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ q)) + (atRead : program readLabel = parser source exitLabel) + (base : K → List Bool) (relation : RelationTable q) (suffix : List Bool) + (ambient : σ) (initial : RelationTable q) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[1] + (some ⟨some readLabel, ((ambient, initial), register), + Function.update base source (encodeWords (relationWords relation) ++ suffix)⟩) = + some ⟨some exitLabel, ((ambient, relation), none), Function.update base source suffix⟩ := by + simpa only [Function.iterate_one, MachineComposition.advance_some] using + parserStep source readLabel exitLabel program atRead base relation suffix ambient initial register + +def parserInTime (source : K) (readLabel exitLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ q)) + (atRead : program readLabel = parser source exitLabel) + (base : K → List Bool) (relation : RelationTable q) (suffix : List Bool) + (ambient : σ) (initial : RelationTable q) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some readLabel, ((ambient, initial), register), + Function.update base source (encodeWords (relationWords relation) ++ suffix)⟩ + (some ⟨some exitLabel, ((ambient, relation), none), Function.update base source suffix⟩) 1 where + steps := 1 + evals_in_steps := by + change (MachineComposition.advance (TM2.step program))^[1] _ = _ + exact parserTrace source readLabel exitLabel program atRead base relation suffix ambient initial register + steps_le_m := Nat.le_refl _ + +end MinUncutGames.Foundations.PCP.AlphabetTable.ReadRelation + +end +section +namespace MinUncutGames.Foundations.Complexity.MachineLookupSpec + +def skipWord : List Bool → List Bool + | [] => [] + | true :: bs => skipWord bs + | false :: bs => bs + +@[simp] theorem skipWord_encodeWord (n : Nat) (bs : List Bool) : + skipWord (encodeWord n ++ bs) = bs := by + induction n with + | zero => simp [encodeWord, skipWord] + | succ n ih => + simpa [encodeWord, List.replicate_succ, skipWord] using ih + +theorem skipWord_iterate_encodeWords (i : Nat) (values : List Nat) : + (skipWord^[i]) (encodeWords values) = encodeWords (values.drop i) := by + induction i generalizing values with + | zero => rfl + | succ i ih => + rw [Function.iterate_succ_apply] + cases values with + | nil => simpa [encodeWords, skipWord] using ih [] + | cons n ns => + simpa only [encodeWords, skipWord_encodeWord, List.drop_succ_cons] using ih ns + +def headWord : List Bool → Option (List Bool) + | [] => none + | false :: _ => some [false] + | true :: bs => (headWord bs).map (true :: ·) + +@[simp] theorem headWord_encodeWord (n : Nat) (bs : List Bool) : + headWord (encodeWord n ++ bs) = some (encodeWord n) := by + induction n with + | zero => simp [encodeWord, headWord] + | succ n ih => + simpa [encodeWord, List.replicate_succ, headWord] using + congrArg (Option.map (true :: ·)) ih + +@[simp] theorem headWord_encodeWords (values : List Nat) : + headWord (encodeWords values) = values.head?.map encodeWord := by + cases values with + | nil => rfl + | cons n ns => exact headWord_encodeWord n (encodeWords ns) + +def lookupBits (i : Nat) (table : List Bool) : Option (List Bool) := + headWord ((skipWord^[i]) table) + +@[simp] theorem lookupBits_encodeWords (i : Nat) (values : List Nat) : + lookupBits i (encodeWords values) = values[i]?.map encodeWord := by + rw [lookupBits, skipWord_iterate_encodeWords, headWord_encodeWords, + List.head?_drop] + +def lookupEncoded (index table : List Bool) : Option (List Bool) := + match decodeWords index with + | some [i] => lookupBits i table + | _ => none + +@[simp] theorem decodeWords_encodeWord (i : Nat) : + decodeWords (encodeWord i) = some [i] := by + simpa [encodeWords] using decodeWords_encodeWords [i] + +@[simp] theorem lookupEncoded_encode (i : Nat) (values : List Nat) : + lookupEncoded (encodeWord i) (encodeWords values) = + values[i]?.map encodeWord := by + simp [lookupEncoded] + +theorem lookupEncoded_some (i value : Nat) (values : List Nat) + (h : values[i]? = some value) : + lookupEncoded (encodeWord i) (encodeWords values) = some (encodeWord value) := by + simp [h] + +theorem lookupEncoded_none (i : Nat) (values : List Nat) + (h : values.length ≤ i) : + lookupEncoded (encodeWord i) (encodeWords values) = none := by + simp [List.getElem?_eq_none h] + +theorem encoded_selected_split (values : List Nat) (i value : Nat) + (h : values[i]? = some value) : + encodeWords values = encodeWords (values.take i) ++ encodeWord value ++ + encodeWords (values.drop (i + 1)) := by + rcases List.getElem?_eq_some_iff.mp h with ⟨hi, hv⟩ + have hs : values = values.take i ++ value :: values.drop (i + 1) := by + calc + values = values.take i ++ values.drop i := (List.take_append_drop i values).symm + _ = _ := by rw [List.drop_eq_getElem_cons hi, hv] + simpa only [encodeWords_append, encodeWords, List.append_assoc] using + congrArg encodeWords hs + +def scannedBits (values : List Nat) (i : Nat) : Nat := + (encodeWords (values.take (i + 1))).length + +theorem encoded_prefix_length_le (values : List Nat) (i : Nat) : + (encodeWords (values.take i)).length ≤ (encodeWords values).length := by + have hs : encodeWords (values.take i) ++ encodeWords (values.drop i) = + encodeWords values := by + rw [← encodeWords_append, List.take_append_drop] + have hl := congrArg List.length hs + simp only [List.length_append] at hl + omega + +theorem scannedBits_le (values : List Nat) (i : Nat) : + scannedBits values i ≤ (encodeWords values).length := + encoded_prefix_length_le values (i + 1) + +theorem scannedBits_of_some (values : List Nat) (i value : Nat) + (h : values[i]? = some value) : + scannedBits values i = (encodeWords (values.take i)).length + value + 1 := by + rcases List.getElem?_eq_some_iff.mp h with ⟨hi, hv⟩ + simp [scannedBits, List.take_succ_eq_append_getElem hi, hv, encodeWords, + Nat.add_assoc] + +theorem selected_scan_length_le (values : List Nat) (i value : Nat) + (h : values[i]? = some value) : + (encodeWords (values.take i)).length + value + 1 ≤ + (encodeWords values).length := by + rw [← scannedBits_of_some values i value h] + exact scannedBits_le values i + +theorem output_length_le (values : List Nat) (i value : Nat) + (h : values[i]? = some value) : + (encodeWord value).length ≤ (encodeWords values).length := by + have hs := selected_scan_length_le values i value h + rw [encodeWord_length] + omega + +theorem index_length_le (values : List Nat) (i value : Nat) + (h : values[i]? = some value) : + (encodeWord i).length ≤ (encodeWords values).length := by + rcases List.getElem?_eq_some_iff.mp h with ⟨hi, _⟩ + have hp : i ≤ (encodeWords (values.take i)).length := by + simp only [encodeWords_length, List.length_take, Nat.min_eq_left (Nat.le_of_lt hi)] + omega + have hs := selected_scan_length_le values i value h + rw [encodeWord_length] + omega + +def steps : List Nat → Nat → Nat + | [], i => 2 * i + 2 + | n :: _, 0 => n + 3 + | n :: ns, i + 1 => n + 2 + steps ns i + +theorem steps_le_encoded_length_strong (values : List Nat) (i : Nat) : + steps values i ≤ (encodeWords values).length + 2 * i + 2 := by + induction values generalizing i with + | nil => simp [steps, encodeWords] + | cons n ns ih => + cases i with + | zero => + simp only [steps, encodeWords, List.length_append, encodeWord_length] + omega + | succ i => + have ht := ih i + simp only [steps, encodeWords, List.length_append, encodeWord_length] + omega + +theorem steps_le_encoded_length (values : List Nat) (i : Nat) : + steps values i ≤ (encodeWords values).length + 2 * i + 3 := by + have h := steps_le_encoded_length_strong values i + omega + +theorem steps_eq_scannedBits_of_lt (values : List Nat) (i : Nat) + (h : i < values.length) : + steps values i = scannedBits values i + i + 2 := by + induction values generalizing i with + | nil => simp at h + | cons n ns ih => + cases i with + | zero => simp [steps, scannedBits, encodeWords, Nat.add_assoc] + | succ i => + have ht := ih i (by simpa using h) + simp only [scannedBits] at ht + simp only [steps, scannedBits, List.take_succ_cons, encodeWords, + List.length_append, encodeWord_length] + omega + +theorem steps_eq_scannedBits_of_some (values : List Nat) (i value : Nat) + (h : values[i]? = some value) : + steps values i = scannedBits values i + i + 2 := by + rcases List.getElem?_eq_some_iff.mp h with ⟨hi, _⟩ + exact steps_eq_scannedBits_of_lt values i hi + +theorem steps_add_length_of_invalid (values : List Nat) (i : Nat) + (h : values.length ≤ i) : + steps values i + values.length = (encodeWords values).length + 2 * i + 2 := by + induction values generalizing i with + | nil => simp [steps, encodeWords] + | cons n ns ih => + cases i with + | zero => simp at h + | succ i => + have ht := ih i (by simpa using h) + simp only [steps, encodeWords, List.length_append, encodeWord_length, + List.length_cons] + omega + +theorem steps_le_input_encoding_size (values : List Nat) (i : Nat) : + steps values i ≤ (encodeWords values).length + 2 * (encodeWord i).length := by + have h := steps_le_encoded_length_strong values i + rw [encodeWord_length] + omega + +end MinUncutGames.Foundations.Complexity.MachineLookupSpec + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/LoopInitialization.lean b/lean/OAI/Computability/MinUncut/Machines/LoopInitialization.lean new file mode 100644 index 0000000000000000000000000000000000000000..6b09f9d188cf9551ff187767caed0cfbc90c8ca8 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/LoopInitialization.lean @@ -0,0 +1,862 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.Driver + +namespace OAI + +section +namespace MinUncutGames.Foundations.PCP.AlphabetTable.LoopInitialization + +open MinUncutGames.Foundations.Complexity +open RuntimeModel LoopState + +theorem initialization_ready {q : Nat} (input : GenericGraphTables.Table q) : + Ready input 0 (Initialization.loopTapes input) where + le_darts := Nat.zero_le _ + original := rfl + cursor := by + change Initialization.rowsBits input = cursorBits input 0 + rw [cursorBits_zero] + rfl + vertices := rfl + darts := rfl + counter := by simp [Initialization.loopTapes] + edge := rfl + tail := rfl + reverseIndex := rfl + head := rfl + scratch := rfl + compareLeft := rfl + compareRight := rfl + output := rfl + reversed := by + change (Initialization.headerBits input).reverse = (prefixBits input 0).reverse + rw [prefixBits_zero] + rfl + +end MinUncutGames.Foundations.PCP.AlphabetTable.LoopInitialization + +end +section +namespace MinUncutGames.Foundations.PCP.AlphabetTable.Loop + +open Turing +open MinUncutGames.Foundations.Complexity +open RuntimeModel + +variable {q : Nat} + +def zeroGuardInTime (input : GenericGraphTables.Table q) (base : Tape → List Bool) + (ready : LoopState.Ready input input.darts base) + (relation : GenericGraphTables.RelationTable q) (flag : Bool) : + StateTransition.EvalsToInTime (TM2.step (Driver.program q)) + ⟨some .guard, normal relation flag, base⟩ + (some ⟨some .reverseOutput, normal relation flag, base⟩) 1 := by + have counterSelf : MachineUnaryCounter.counterTapes Tape.counter base 0 [] = base := by + simp only [MachineUnaryCounter.counterTapes, List.append_nil, + ← ready.counter_at_end, Function.update_eq_self] + have run := MachineUnaryCounter.guardInTime_zero Tape.counter + (Driver.Label.guard : Driver.Label q) .tailStart .reverseOutput + (Driver.program q) (Driver.program_guard q) base [] (normal relation flag).1 none + simpa only [counterSelf, normal] using run + +structure LoopResult (input : GenericGraphTables.Table q) (e remaining : Nat) + (base : Tape → List Bool) (oldRelation : GenericGraphTables.RelationTable q) + (oldFlag : Bool) where + tapes : Tape → List Bool + relation : GenericGraphTables.RelationTable q + flag : Bool + ready : LoopState.Ready input input.darts tapes + run : StateTransition.EvalsToInTime (TM2.step (Driver.program q)) + ⟨some .guard, normal oldRelation oldFlag, base⟩ + (some ⟨some .reverseOutput, normal relation flag, tapes⟩) + (remaining * Body.bodyTime q (LoopState.inputBits input).length + 1) + +def runRemaining (input : GenericGraphTables.Table q) : + (remaining e : Nat) → e + remaining = input.darts → + (base : Tape → List Bool) → LoopState.Ready input e base → + (oldRelation : GenericGraphTables.RelationTable q) → (oldFlag : Bool) → + LoopResult input e remaining base oldRelation oldFlag + | 0, e, finished, base, ready, oldRelation, oldFlag => by + have atEnd : e = input.darts := by omega + subst e + exact { + tapes := base + relation := oldRelation + flag := oldFlag + ready := ready + run := by + simpa only [Nat.zero_mul, Nat.zero_add] using + zeroGuardInTime input base ready oldRelation oldFlag } + | remaining + 1, e, finished, base, ready, oldRelation, oldFlag => by + have beforeEnd : e < input.darts := by omega + let edge : Fin input.darts := ⟨e, beforeEnd⟩ + let one := Body.rowStep input edge base ready oldRelation oldFlag + let rest := runRemaining input remaining (e + 1) (by omega) one.tapes one.ready + input.rows[edge].relation (CompareLoop.rowLoop input edge) + let composed := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ one.run rest.run + refine { + tapes := rest.tapes + relation := rest.relation + flag := rest.flag + ready := rest.ready + run := { toEvalsTo := composed.toEvalsTo, steps_le_m := ?_ } } + have budget := composed.steps_le_m + simpa only [Nat.succ_mul, Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using budget + +def prefixTime (q N : Nat) : Nat := + Initialization.time N + N * Body.bodyTime q N + 1 + +private noncomputable local instance prefixRunSizeOf (input : GenericGraphTables.Table q) + (tapes : Tape → List Bool) (relation : GenericGraphTables.RelationTable q) (flag : Bool) : + SizeOf (StateTransition.EvalsToInTime (TM2.step (Driver.program q)) + (initList (Driver.machine q) (GenericGraphTables.tableBits input)) + (some ⟨some .reverseOutput, normal relation flag, tapes⟩) + (prefixTime q (LoopState.inputBits input).length)) := + @StateTransition.EvalsToInTime._sizeOf_inst + (TM2.Cfg Alphabet (Driver.Label q) (State q)) + (TM2.step (Driver.program q)) + (initList (Driver.machine q) (GenericGraphTables.tableBits input)) + (some ⟨some .reverseOutput, normal relation flag, tapes⟩) + (prefixTime q (LoopState.inputBits input).length) inferInstance + +structure PrefixResult (input : GenericGraphTables.Table q) where + tapes : Tape → List Bool + relation : GenericGraphTables.RelationTable q + flag : Bool + ready : LoopState.Ready input input.darts tapes + run : StateTransition.EvalsToInTime (TM2.step (Driver.program q)) + (initList (Driver.machine q) (GenericGraphTables.tableBits input)) + (some ⟨some .reverseOutput, normal relation flag, tapes⟩) + (prefixTime q (LoopState.inputBits input).length) + +def runPrefix (input : GenericGraphTables.Table q) : PrefixResult input := by + let rows := runRemaining input input.darts 0 (by simp) + (Initialization.loopTapes input) (LoopInitialization.initialization_ready input) + (Vector.replicate (q * q) false) false + let composed := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ + (Initialization.initializeInTime input) rows.run + refine { + tapes := rows.tapes + relation := rows.relation + flag := rows.flag + ready := rows.ready + run := { toEvalsTo := composed.toEvalsTo, steps_le_m := ?_ } } + have budget := composed.steps_le_m + change composed.steps ≤ + input.darts * Body.bodyTime q (LoopState.inputBits input).length + 1 + + Initialization.time (LoopState.inputBits input).length at budget + have rowCount : input.darts ≤ (LoopState.inputBits input).length := + GenericGraphTables.darts_le_tableBits_length input + have rowBudget := Nat.mul_le_mul_right (Body.bodyTime q (LoopState.inputBits input).length) + rowCount + unfold prefixTime + omega + +theorem PrefixResult.reversed {input : GenericGraphTables.Table q} (result : PrefixResult input) : + result.tapes .reversed = (GraphTables.tableBits (Table.build input)).reverse := + result.ready.reversed_at_end + +theorem PrefixResult.output {input : GenericGraphTables.Table q} (result : PrefixResult input) : + result.tapes .output = [] := result.ready.output + +end MinUncutGames.Foundations.PCP.AlphabetTable.Loop + +end +section +namespace MinUncutGames.Foundations.PCP.AlphabetTable.Finish + +open Turing +open MinUncutGames.Foundations.Complexity +open RuntimeModel +open scoped BigOperators + +def afterReversal (base : Tape → List Bool) (word : List Bool) : Tape → List Bool := + Reduction.MachineTransfer.tapesAt .reversed .output base [] word + +@[simp] theorem afterReversal_output (base : Tape → List Bool) (word : List Bool) : + afterReversal base word .output = word := by + simp [afterReversal, Reduction.MachineTransfer.tapesAt] + +@[simp] theorem afterReversal_reversed (base : Tape → List Bool) (word : List Bool) : + afterReversal base word .reversed = [] := by + simp [afterReversal, Reduction.MachineTransfer.tapesAt] + +def finishBudget (base : Tape → List Bool) (word : List Bool) : Nat := + word.length + 1 + (∑ i : Fin 15, (afterReversal base word (cleanupPorts i)).length) + 16 + +def reverseInTime (q : Nat) (base : Tape → List Bool) (word : List Bool) + (state : State q) (hreversed : base .reversed = word.reverse) + (houtput : base .output = []) : + StateTransition.EvalsToInTime (Driver.machine q).step + ⟨some .reverseOutput, state, base⟩ + (some ⟨some (.cleanup 0), (state.1, none), afterReversal base word⟩) + (word.length + 1) := by + have run := Reduction.MachineTransfer.transferAtInTime + (σ := Ambient q) Tape.reversed Tape.output (by decide) id false + Driver.Label.reverseOutput (some (.cleanup 0)) (Driver.program q) rfl + base state.1 state.2 + simpa only [hreversed, houtput, List.length_reverse, List.reverse_reverse, + List.map_id, List.append_nil, afterReversal, Driver.machine, FinTM2.step] using! run + +theorem cleared_eq_haltList (q : Nat) (base : Tape → List Bool) : + (⟨none, initial q, Cleanup.clearTapes cleanupPorts base⟩ : (Driver.machine q).Cfg) = + haltList (Driver.machine q) (base .output) := by + have tapes := Cleanup.clearTapes_outputOnly cleanupPorts Tape.output base + cleanupPorts_ne_output cleanupPorts_cover + congr 1 + +def cleanupInTime (q : Nat) (base : Tape → List Bool) (state : State q) : + StateTransition.EvalsToInTime (Driver.machine q).step + ⟨some (.cleanup 0), state, base⟩ + (some (haltList (Driver.machine q) (base .output))) + ((∑ i : Fin 15, (base (cleanupPorts i)).length) + 16) := by + have run := Cleanup.cleanupInTime cleanupPorts Driver.Label.cleanup (initial q).1 none + (Driver.program q) + (fun i => by simp only [Driver.program, Cleanup.instruction_drain]) + (by simp only [Driver.program, Cleanup.instruction_finish]) base state.1 state.2 + change StateTransition.EvalsToInTime (Driver.machine q).step + ⟨some (.cleanup 0), state, base⟩ + (some ⟨none, initial q, Cleanup.clearTapes cleanupPorts base⟩) + ((∑ i : Fin 15, (base (cleanupPorts i)).length) + 15 + 1) at run + rw [cleared_eq_haltList] at run + simpa only [Nat.add_assoc] using run + +def finishInTime (q : Nat) (base : Tape → List Bool) (word : List Bool) + (state : State q) (hreversed : base .reversed = word.reverse) + (houtput : base .output = []) : + StateTransition.EvalsToInTime (Driver.machine q).step + ⟨some .reverseOutput, state, base⟩ + (some (haltList (Driver.machine q) word)) (finishBudget base word) := by + have first := reverseInTime q base word state hreversed houtput + have last := cleanupInTime q (afterReversal base word) (state.1, none) + rw [afterReversal_output] at last + have run := StateTransition.EvalsToInTime.trans (Driver.machine q).step _ _ + ⟨some .reverseOutput, state, base⟩ + ⟨some (.cleanup 0), (state.1, none), afterReversal base word⟩ + (some (haltList (Driver.machine q) word)) first last + refine { toEvalsTo := run.toEvalsTo, steps_le_m := ?_ } + have budgetEq : ((∑ i : Fin 15, (afterReversal base word (cleanupPorts i)).length) + 16) + + (word.length + 1) = + finishBudget base word := by + dsimp only [finishBudget] + omega + exact run.steps_le_m.trans (Nat.le_of_eq budgetEq) + +theorem afterReversal_selected_length_le (base : Tape → List Bool) (word : List Bool) + (i : Fin 15) : + (afterReversal base word (cleanupPorts i)).length ≤ (base (cleanupPorts i)).length := by + have ho := cleanupPorts_ne_output i + by_cases hr : cleanupPorts i = .reversed <;> + simp [afterReversal, Reduction.MachineTransfer.tapesAt, ho, hr] + +theorem stackLength_after_prefix (q : Nat) (input : List Bool) + (base : Tape → List Bool) (state : State q) (budget : Nat) + (prefixRun : StateTransition.EvalsToInTime (Driver.machine q).step + (initList (Driver.machine q) input) (some ⟨some .reverseOutput, state, base⟩) budget) + (k : Tape) : + (base k).length ≤ input.length + budget * Runtime.programPushBound (Driver.machine q) := by + have bound := Runtime.executionSizeBound (Driver.machine q).step + (fun cfg => (cfg.stk k).length) (Runtime.programPushBound (Driver.machine q)) + (Runtime.stepStackLength (Driver.machine q) k) prefixRun + exact bound.trans (Nat.add_le_add_right + (Runtime.initialStackLength (Driver.machine q) input k) _) + +theorem finishBudget_le_of_prefix (q : Nat) (input : List Bool) + (base : Tape → List Bool) (word : List Bool) (state : State q) (budget : Nat) + (prefixRun : StateTransition.EvalsToInTime (Driver.machine q).step + (initList (Driver.machine q) input) (some ⟨some .reverseOutput, state, base⟩) budget) + (hreversed : base .reversed = word.reverse) : + finishBudget base word ≤ + 16 * (input.length + budget * Runtime.programPushBound (Driver.machine q)) + 17 := by + let B := input.length + budget * Runtime.programPushBound (Driver.machine q) + have wordBound : word.length ≤ B := by + simpa only [hreversed, List.length_reverse] using + stackLength_after_prefix q input base state budget prefixRun .reversed + have sumBound : (∑ i : Fin 15, (afterReversal base word (cleanupPorts i)).length) ≤ 15 * B := by + calc + _ ≤ ∑ _i : Fin 15, B := by + apply Finset.sum_le_sum + intro i _ + exact (afterReversal_selected_length_le base word i).trans + (stackLength_after_prefix q input base state budget prefixRun (cleanupPorts i)) + _ = 15 * B := by simp + dsimp only [finishBudget] + omega + +noncomputable def completedPolynomial (q : Nat) (prefixTime : Polynomial Nat) : Polynomial Nat := + prefixTime + Polynomial.C 16 * + (Polynomial.X + Polynomial.C (Runtime.programPushBound (Driver.machine q)) * prefixTime) + + Polynomial.C 17 + +def finishAfterPrefix (q : Nat) (input : List Bool) (base : Tape → List Bool) + (word : List Bool) (state : State q) (budget : Nat) + (prefixRun : StateTransition.EvalsToInTime (Driver.machine q).step + (initList (Driver.machine q) input) (some ⟨some .reverseOutput, state, base⟩) budget) + (hreversed : base .reversed = word.reverse) (houtput : base .output = []) : + TM2OutputsInTime (Driver.machine q) input (some word) + (budget + 16 * (input.length + budget * Runtime.programPushBound (Driver.machine q)) + 17) := by + have last := finishInTime q base word state hreversed houtput + let run := StateTransition.EvalsToInTime.trans (Driver.machine q).step _ _ + (initList (Driver.machine q) input) ⟨some .reverseOutput, state, base⟩ + (some (haltList (Driver.machine q) word)) prefixRun last + refine { toEvalsTo := run.toEvalsTo, steps_le_m := ?_ } + have finishBound := finishBudget_le_of_prefix q input base word state budget prefixRun hreversed + have allBound := run.steps_le_m + omega + +def finishAfterPolynomialPrefix (q : Nat) (input : List Bool) (base : Tape → List Bool) + (word : List Bool) (state : State q) (prefixTime : Polynomial Nat) + (prefixRun : StateTransition.EvalsToInTime (Driver.machine q).step + (initList (Driver.machine q) input) (some ⟨some .reverseOutput, state, base⟩) + (prefixTime.eval input.length)) + (hreversed : base .reversed = word.reverse) (houtput : base .output = []) : + TM2OutputsInTime (Driver.machine q) input (some word) + ((completedPolynomial q prefixTime).eval input.length) := by + have run := finishAfterPrefix q input base word state (prefixTime.eval input.length) + prefixRun hreversed houtput + refine { toEvalsTo := run.toEvalsTo, steps_le_m := ?_ } + simpa only [completedPolynomial, Polynomial.eval_add, Polynomial.eval_mul, + Polynomial.eval_C, Polynomial.eval_X, Nat.mul_comm] using run.steps_le_m + +end MinUncutGames.Foundations.PCP.AlphabetTable.Finish + +end +section +namespace MinUncutGames.Foundations.PCP.AlphabetTable.Runtime + +open Turing +open MinUncutGames.Foundations.Complexity +open RuntimeModel + +noncomputable def prefixPolynomial (q : Nat) : Polynomial Nat := + Polynomial.C 27 * Polynomial.X + Polynomial.C 54 + + Polynomial.X * + (Polynomial.C (32 + 8 * (Enumeration.localCount q * (6 * (2 * 4104)))) * + (Polynomial.X + Polynomial.C 1)) + Polynomial.C 1 + +theorem prefixPolynomial_eval (q N : Nat) : + (prefixPolynomial q).eval N = Loop.prefixTime q N := by + simp only [prefixPolynomial, Polynomial.eval_add, Polynomial.eval_mul, + Polynomial.eval_C, Polynomial.eval_X, Loop.prefixTime, + Initialization.time, Body.bodyTime] + ring + +noncomputable def time (q : Nat) : Polynomial Nat := + Finish.completedPolynomial q (prefixPolynomial q) + +noncomputable def tableOutputsInTime {q : Nat} (input : GenericGraphTables.Table q) : + TM2OutputsInTime (Driver.machine q) (GenericGraphTables.tableBits input) + (some (GraphTables.tableBits (Table.build input))) + ((time q).eval (GenericGraphTables.tableBits input).length) := by + let prefixRun := Loop.runPrefix input + have hrun : StateTransition.EvalsToInTime (Driver.machine q).step + (initList (Driver.machine q) (GenericGraphTables.tableBits input)) + (some ⟨some .reverseOutput, normal prefixRun.relation prefixRun.flag, prefixRun.tapes⟩) + ((prefixPolynomial q).eval (GenericGraphTables.tableBits input).length) := by + rw [prefixPolynomial_eval] + exact prefixRun.run + exact Finish.finishAfterPolynomialPrefix q (GenericGraphTables.tableBits input) + prefixRun.tapes (GraphTables.tableBits (Table.build input)) + (normal prefixRun.relation prefixRun.flag) (prefixPolynomial q) hrun + prefixRun.ready.reversed_at_end prefixRun.ready.output + +noncomputable def tablePolynomialTime (q : Nat) : + TM2ComputableInPolyTime (GenericGraphTables.tableBits (q := q)) + GraphTables.tableBits (Table.build (q := q)) where + tm := Driver.machine q + inputAlphabet := Equiv.refl Bool + outputAlphabet := Equiv.refl Bool + time := time q + outputsFun input := by + change TM2OutputsInTime (Driver.machine q) + ((GenericGraphTables.tableBits input).map id) + (some ((GraphTables.tableBits (Table.build input)).map id)) _ + have input_eq : @List.map ((Driver.machine q).Γ (Driver.machine q).k₀) + ((Driver.machine q).Γ (Driver.machine q).k₀) id + (GenericGraphTables.tableBits input) = GenericGraphTables.tableBits input := List.map_id _ + have output_eq : @List.map ((Driver.machine q).Γ (Driver.machine q).k₁) + ((Driver.machine q).Γ (Driver.machine q).k₁) id + (GraphTables.tableBits (Table.build input)) = + GraphTables.tableBits (Table.build input) := List.map_id _ + simpa only [input_eq, output_eq] using tableOutputsInTime input + +end MinUncutGames.Foundations.PCP.AlphabetTable.Runtime + +end +section +namespace MinUncutGames.Foundations.Complexity.MachineRepeat +open Turing + +inductive ExtraTape + | counter | temporary | output + deriving DecidableEq + +protected abbrev ExtraTape.enumList : List ExtraTape := [.counter, .temporary, .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 Phase + | parse | guard | bodyToTemp | tempToBody | finalToTemp | tempToOutput + deriving DecidableEq + +protected abbrev Phase.enumList : List Phase := [.parse, .guard, .bodyToTemp, .tempToBody, + .finalToTemp, .tempToOutput] + +protected theorem Phase.enumList_getElem?_ctorIdx_eq (x : Phase) : + Phase.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem Phase.enumList_nodup : Phase.enumList.Nodup := by decide + +instance : Fintype Phase where + elems := ⟨Phase.enumList, Phase.enumList_nodup⟩ + complete x := by cases x <;> decide + +abbrev Tape (M : FinTM2) := M.K ⊕ ExtraTape +abbrev Symbols (M : FinTM2) := MachineEmbedding.Alphabet M.Γ (fun _ : ExtraTape => M.Γ M.k₀) +abbrev Label (M : FinTM2) := M.Λ ⊕ Phase +abbrev State (M : FinTM2) := M.σ × Option (M.Γ M.k₀) + +def extraTapes (M : FinTM2) (counter temporary output : List (M.Γ M.k₀)) : + ExtraTape → List (M.Γ M.k₀) + | .counter => counter + | .temporary => temporary + | .output => output + +def auxProgram (M : FinTM2) (input : M.Γ M.k₀ ≃ Bool) (output : M.Γ M.k₁ ≃ Bool) : + Phase → TM2.Stmt (Symbols M) (Label M) (State M) + | .parse => .pop (.inl M.k₀) (fun s v => (s.1,v)) + (.branch (fun s => input (s.2.getD (input.symm false))) + (.push (.inr .counter) (fun _ => input.symm true) + (.load (fun s => (s.1,none)) (.goto (fun _ => .inr .parse)))) + (.load (fun s => (s.1,none)) (.goto (fun _ => .inr .guard)))) + | .guard => .pop (.inr .counter) (fun s v => (s.1,v)) + (.branch (fun s => s.2.isSome) + (.load (fun s => (s.1,none)) (.goto (fun _ => .inl M.main))) + (.load (fun s => (s.1,none)) (.goto (fun _ => .inr .finalToTemp)))) + | .bodyToTemp => Reduction.MachineTransfer.loopAt (Γ := Symbols M) (Λ := Label M) (.inl M.k₁) (.inr .temporary) + (fun b => input.symm (output b)) (input.symm false) + (.inr .bodyToTemp) (some (.inr .tempToBody)) + | .tempToBody => Reduction.MachineTransfer.loopAt (Γ := Symbols M) (Λ := Label M) (.inr .temporary) (.inl M.k₀) + id (input.symm false) (.inr .tempToBody) (some (.inr .guard)) + | .finalToTemp => Reduction.MachineTransfer.loopAt (Γ := Symbols M) (Λ := Label M) (.inl M.k₀) (.inr .temporary) + id (input.symm false) (.inr .finalToTemp) (some (.inr .tempToOutput)) + | .tempToOutput => Reduction.MachineTransfer.loopAt (Γ := Symbols M) (Λ := Label M) (.inr .temporary) (.inr .output) + id (input.symm false) (.inr .tempToOutput) none + +def program (M : FinTM2) (input : M.Γ M.k₀ ≃ Bool) (output : M.Γ M.k₁ ≃ Bool) : + Label M → TM2.Stmt (Symbols M) (Label M) (State M) := + MachineEmbedding.program (some (.inr .bodyToTemp)) M.m (auxProgram M input output) + +def machine (M : FinTM2) (input : M.Γ M.k₀ ≃ Bool) (output : M.Γ M.k₁ ≃ Bool) : FinTM2 where + K := Tape M + kFin := by letI := M.kFin; exact inferInstanceAs (Fintype (Tape M)) + k₀ := .inl M.k₀ + k₁ := .inr .output + Γ := Symbols M + Λ := Label M + ΛFin := by letI := M.ΛFin; exact inferInstanceAs (Fintype (Label M)) + main := .inr .parse + σ := State M + σFin := by + letI := M.σFin + letI := M.Γk₀Fin + exact inferInstanceAs (Fintype (State M)) + initialState := (M.initialState,none) + Γk₀Fin := M.Γk₀Fin + m := program M input output + +def inputTapes (M : FinTM2) (word counter : List (M.Γ M.k₀)) : ∀k, List (Symbols M k) := + MachineEmbedding.tapes (initList M word).stk (extraTapes M counter [] []) + +@[simp] theorem inputTapes_input (M : FinTM2) (word counter : List (M.Γ M.k₀)) : + inputTapes M word counter (.inl M.k₀) = word := by + simp [inputTapes, initList] + +@[simp] theorem inputTapes_counter (M : FinTM2) (word counter : List (M.Γ M.k₀)) : + inputTapes M word counter (.inr .counter) = counter := rfl + +def inputConfig (M : FinTM2) (phase : Phase) (word counter : List (M.Γ M.k₀)) : + TM2.Cfg (Symbols M) (Label M) (State M) := + ⟨some (.inr phase),(M.initialState,none),inputTapes M word counter⟩ + +def embedded (M : FinTM2) (counter : List (M.Γ M.k₀)) (c : M.Cfg) : + TM2.Cfg (Symbols M) (Label M) (State M) := + MachineEmbedding.configuration (some (.inr .bodyToTemp)) (none : Option (M.Γ M.k₀)) + (extraTapes M counter [] []) c + +def temporaryTapes (M : FinTM2) (word counter : List (M.Γ M.k₀)) : ∀k, List (Symbols M k) := + MachineEmbedding.tapes (fun _ => []) (extraTapes M counter word []) + +def temporaryConfig (M : FinTM2) (phase : Phase) (word counter : List (M.Γ M.k₀)) : + TM2.Cfg (Symbols M) (Label M) (State M) := + ⟨some (.inr phase),(M.initialState,none),temporaryTapes M word counter⟩ + +private theorem inputTapes_update_input (M : FinTM2) + (word counter replacement : List (M.Γ M.k₀)) : + Function.update (inputTapes M word counter) (.inl M.k₀) replacement = + inputTapes M replacement counter := by + funext k + cases k with + | inl k => + by_cases h : k = M.k₀ + · subst k; simp [inputTapes, initList] + · simp [inputTapes, initList, h] + | inr k => simp [inputTapes] + +private theorem inputTapes_update_counter (M : FinTM2) + (word counter replacement : List (M.Γ M.k₀)) : + Function.update (inputTapes M word counter) (.inr .counter) replacement = + inputTapes M word replacement := by + funext k + cases k with + | inl k => simp [inputTapes] + | inr k => cases k <;> simp [inputTapes, extraTapes] + +def oneStep {α : Type*} (step : α → Option α) (a b : α) + (h : step a = some b) : StateTransition.EvalsToInTime step a (some b) 1 where + steps := 1 + evals_in_steps := by change step a = some b; exact h + steps_le_m := le_refl _ + +variable (M : FinTM2) (input : M.Γ M.k₀ ≃ Bool) (output : M.Γ M.k₁ ≃ Bool) + +theorem parseStep_true (word counter : List (M.Γ M.k₀)) : + (machine M input output).step + (inputConfig M .parse (input.symm true :: word) counter) = + some (inputConfig M .parse word (input.symm true :: counter)) := by + change some (TM2.stepAux (auxProgram M input output .parse) + (M.initialState,none) (inputTapes M (input.symm true :: word) counter)) = _ + simp [auxProgram, TM2.stepAux, inputTapes_update_input, inputTapes_update_counter, + inputConfig] + +theorem parseStep_false (word counter : List (M.Γ M.k₀)) : + (machine M input output).step + (inputConfig M .parse (input.symm false :: word) counter) = + some (inputConfig M .guard word counter) := by + change some (TM2.stepAux (auxProgram M input output .parse) + (M.initialState,none) (inputTapes M (input.symm false :: word) counter)) = _ + simp [auxProgram, TM2.stepAux, inputTapes_update_input, inputTapes_update_counter, + inputConfig] + +theorem parseTrace (count : Nat) (word counter : List (M.Γ M.k₀)) : + (MachineComposition.advance (machine M input output).step)^[count+1] + (some (inputConfig M .parse ((encodeWord count).map input.symm ++ word) counter)) = + some (inputConfig M .guard word (List.replicate count (input.symm true) ++ counter)) := by + induction count generalizing counter with + | zero => + simpa only [encodeWord, List.replicate_zero, List.nil_append, List.map_singleton, + List.singleton_append, Nat.zero_add, Function.iterate_one, MachineComposition.advance_some] + using! parseStep_false M input output word counter + | succ count ih => + rw [Function.iterate_succ_apply] + change (MachineComposition.advance (machine M input output).step)^[count+1] + ((machine M input output).step + (inputConfig M .parse ((encodeWord (count+1)).map input.symm ++ word) counter)) = _ + simp only [encodeWord, List.replicate_succ, List.cons_append, List.map_cons, + List.map_append, List.map_replicate] + rw [parseStep_true] + have h := ih (input.symm true :: counter) + have hc : List.replicate count (input.symm true) ++ input.symm true :: counter = + input.symm true :: (List.replicate count (input.symm true) ++ counter) := by + rw [← List.singleton_append, ← List.append_assoc, + ← List.replicate_succ', List.replicate_succ, List.cons_append] + rw [hc] at h + simpa only [encodeWord, List.map_append, List.map_replicate, List.map_singleton, + List.map_nil, List.singleton_append, List.append_assoc] using! h + +theorem guardStep_some (word counter : List (M.Γ M.k₀)) (symbol : M.Γ M.k₀) : + (machine M input output).step (inputConfig M .guard word (symbol :: counter)) = + some (embedded M counter (initList M word)) := by + change some (TM2.stepAux (auxProgram M input output .guard) + (M.initialState,none) (inputTapes M word (symbol :: counter))) = _ + simp [auxProgram, TM2.stepAux, inputTapes_update_counter, + embedded, MachineEmbedding.configuration] + exact ⟨rfl,rfl,rfl⟩ + +theorem guardStep_none (word : List (M.Γ M.k₀)) : + (machine M input output).step (inputConfig M .guard word []) = + some (inputConfig M .finalToTemp word []) := by + change some (TM2.stepAux (auxProgram M input output .guard) + (M.initialState,none) (inputTapes M word [])) = _ + simp [auxProgram, TM2.stepAux, inputTapes_update_counter, inputConfig] + +def bodyExecution (counter : List (M.Γ M.k₀)) + (word : List (M.Γ M.k₀)) (result : List (M.Γ M.k₁)) (budget : Nat) + (run : TM2OutputsInTime M word (some result) budget) : + StateTransition.EvalsToInTime (machine M input output).step + (embedded M counter (initList M word)) + (some (embedded M counter (haltList M result))) budget := + MachineComposition.embeddedExecution (some (.inr .bodyToTemp : Label M)) + (none : Option (M.Γ M.k₀)) (extraTapes M counter [] []) M.m + (auxProgram M input output) run + +private theorem bodyToTemp_tapes (result : List (M.Γ M.k₁)) (counter : List (M.Γ M.k₀)) : + Reduction.MachineTransfer.tapesAt (.inl M.k₁) (.inr .temporary) + (embedded M counter (haltList M result)).stk [] + (result.reverse.map (fun b => input.symm (output b))) = + temporaryTapes M (result.reverse.map (fun b => input.symm (output b))) counter := by + funext k + cases k with + | inl k => + by_cases h : k = M.k₁ + · subst k; simp [Reduction.MachineTransfer.tapesAt, temporaryTapes] + · simp [Reduction.MachineTransfer.tapesAt, temporaryTapes, embedded, + MachineEmbedding.configuration, haltList, h] + | inr k => + cases k <;> simp [Reduction.MachineTransfer.tapesAt, temporaryTapes, embedded, + MachineEmbedding.configuration, extraTapes] + +private theorem tempToBody_tapes (word counter : List (M.Γ M.k₀)) : + Reduction.MachineTransfer.tapesAt (Γ := Symbols M) (.inr .temporary) (.inl M.k₀) + (temporaryTapes M word counter) [] word.reverse = inputTapes M word.reverse counter := by + funext k + cases k with + | inl k => + by_cases h : k = M.k₀ + · subst k; simp [Reduction.MachineTransfer.tapesAt, inputTapes, initList] + · simp [Reduction.MachineTransfer.tapesAt, inputTapes, temporaryTapes, initList, h] + | inr k => + cases k <;> simp [Reduction.MachineTransfer.tapesAt, inputTapes, temporaryTapes, extraTapes] + +private theorem finalToTemp_tapes (word : List (M.Γ M.k₀)) : + Reduction.MachineTransfer.tapesAt (Γ := Symbols M) (.inl M.k₀) (.inr .temporary) + (inputTapes M word []) [] word.reverse = temporaryTapes M word.reverse [] := by + funext k + cases k with + | inl k => + by_cases h : k = M.k₀ + · subst k; simp [Reduction.MachineTransfer.tapesAt, temporaryTapes] + · simp [Reduction.MachineTransfer.tapesAt, inputTapes, temporaryTapes, initList, h] + | inr k => + cases k <;> simp [Reduction.MachineTransfer.tapesAt, inputTapes, temporaryTapes, extraTapes] + +private theorem tempToOutput_tapes (word : List (M.Γ M.k₀)) : + Reduction.MachineTransfer.tapesAt (Γ := Symbols M) (.inr .temporary) (.inr .output) + (temporaryTapes M word []) [] word.reverse = + (haltList (machine M input output) word.reverse).stk := by + funext k + cases k with + | inl k => simp [Reduction.MachineTransfer.tapesAt, temporaryTapes, haltList, machine] + | inr k => + cases k <;> simp [Reduction.MachineTransfer.tapesAt, temporaryTapes, haltList, + machine, extraTapes] + rfl + +def bodyToTemp (result : List (M.Γ M.k₁)) (counter : List (M.Γ M.k₀)) : + StateTransition.EvalsToInTime (machine M input output).step + (embedded M counter (haltList M result)) + (some (temporaryConfig M .tempToBody + (result.reverse.map (fun b => input.symm (output b))) counter)) (result.length+1) := by + have run := Reduction.MachineTransfer.transferAtInTime + (Γ := Symbols M) (.inl M.k₁) (.inr .temporary) (by intro h; cases h) + (fun b => input.symm (output b)) (input.symm false) + (.inr .bodyToTemp) (some (.inr .tempToBody)) (program M input output) rfl + (embedded M counter (haltList M result)).stk M.initialState none + have hs : (embedded M counter (haltList M result)).stk (.inl M.k₁) = result := by + simp [embedded, MachineEmbedding.configuration, haltList] + have hd : (embedded M counter (haltList M result)).stk (.inr .temporary) = [] := rfl + rw [hs,hd,List.append_nil,bodyToTemp_tapes] at run + exact run + +def tempToBody (word counter : List (M.Γ M.k₀)) : + StateTransition.EvalsToInTime (machine M input output).step + (temporaryConfig M .tempToBody word counter) + (some (inputConfig M .guard word.reverse counter)) (word.length+1) := by + have run := Reduction.MachineTransfer.transferAtInTime + (Γ := Symbols M) (.inr .temporary) (.inl M.k₀) (by intro h; cases h) + id (input.symm false) (.inr .tempToBody) (some (.inr .guard)) + (program M input output) rfl (temporaryTapes M word counter) M.initialState none + simp only [temporaryTapes, MachineEmbedding.tapes, extraTapes, + List.map_id, List.append_nil] at run + rw [show Reduction.MachineTransfer.tapesAt (Γ := Symbols M) (.inr .temporary) (.inl M.k₀) + (MachineEmbedding.tapes (fun _ => []) (extraTapes M counter word [])) [] word.reverse = + inputTapes M word.reverse counter from tempToBody_tapes M word counter] at run + exact run + +def finalToTemp (word : List (M.Γ M.k₀)) : + StateTransition.EvalsToInTime (machine M input output).step + (inputConfig M .finalToTemp word []) + (some (temporaryConfig M .tempToOutput word.reverse [])) (word.length+1) := by + have run := Reduction.MachineTransfer.transferAtInTime + (Γ := Symbols M) (.inl M.k₀) (.inr .temporary) (by intro h; cases h) + id (input.symm false) (.inr .finalToTemp) (some (.inr .tempToOutput)) + (program M input output) rfl (inputTapes M word []) M.initialState none + have hd : inputTapes M word [] (.inr .temporary) = [] := rfl + rw [inputTapes_input,hd,List.map_id,List.append_nil,finalToTemp_tapes] at run + exact run + +def tempToOutput (word : List (M.Γ M.k₀)) : + StateTransition.EvalsToInTime (machine M input output).step + (temporaryConfig M .tempToOutput word []) + (some (haltList (machine M input output) word.reverse)) (word.length+1) := by + have run := Reduction.MachineTransfer.transferAtInTime + (Γ := Symbols M) (.inr .temporary) (.inr .output) (by intro h; cases h) + id (input.symm false) (.inr .tempToOutput) none + (program M input output) rfl (temporaryTapes M word []) M.initialState none + have hs : temporaryTapes M word [] (.inr .temporary) = word := rfl + have hd : temporaryTapes M word [] (.inr .output) = [] := rfl + rw [hs,hd,List.map_id,List.append_nil,tempToOutput_tapes] at run + exact run + +def bodyReturn (result : List (M.Γ M.k₁)) (counter : List (M.Γ M.k₀)) : + StateTransition.EvalsToInTime (machine M input output).step + (embedded M counter (haltList M result)) + (some (inputConfig M .guard (result.map (fun b => input.symm (output b))) counter)) + (2*(result.length+1)) := by + have first := bodyToTemp M input output result counter + have second := tempToBody M input output (result.reverse.map (fun b => input.symm (output b))) counter + simp only [List.map_reverse,List.reverse_reverse,List.length_reverse,List.length_map] at first second + have full := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ first second + exact { toEvalsTo := full.toEvalsTo, steps_le_m := by have h := full.steps_le_m; omega } + +def finish (word : List (M.Γ M.k₀)) : + StateTransition.EvalsToInTime (machine M input output).step + (inputConfig M .guard word []) (some (haltList (machine M input output) word)) + (2*word.length+3) := by + have guard := oneStep _ _ _ (guardStep_none M input output word) + have first := finalToTemp M input output word + have second := tempToOutput M input output word.reverse + simp only [List.reverse_reverse,List.length_reverse] at second + have gfirst := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ guard first + have full := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ gfirst second + exact { toEvalsTo := full.toEvalsTo, steps_le_m := by have h := full.steps_le_m; omega } + +def loopBudget : Nat → (Nat → List Bool) → (Nat → Nat) → Nat + | 0, words, _ => 2*(words 0).length+3 + | count+1, words, budgets => budgets 0 + 2*(words 1).length+3 + + loopBudget count (fun i => words (i+1)) (fun i => budgets (i+1)) + +def loopExecution (count : Nat) (words : Nat → List Bool) (budgets : Nat → Nat) + (runs : ∀ i, i < count → TM2OutputsInTime M ((words i).map input.symm) + (some ((words (i+1)).map output.symm)) (budgets i)) : + StateTransition.EvalsToInTime (machine M input output).step + (inputConfig M .guard ((words 0).map input.symm) + (List.replicate count (input.symm true))) + (some (haltList (machine M input output) ((words count).map input.symm))) + (loopBudget count words budgets) := by + induction count generalizing words budgets with + | zero => + simpa only [loopBudget,List.replicate_zero,List.length_map] using! + finish M input output ((words 0).map input.symm) + | succ count ih => + rw [List.replicate_succ] + have guard := oneStep _ _ _ (guardStep_some M input output ((words 0).map input.symm) + (List.replicate count (input.symm true)) (input.symm true)) + have body := bodyExecution M input output (List.replicate count (input.symm true)) + ((words 0).map input.symm) ((words 1).map output.symm) (budgets 0) + (runs 0 (Nat.zero_lt_succ count)) + have returned := bodyReturn M input output ((words 1).map output.symm) + (List.replicate count (input.symm true)) + have handoff : ((words 1).map output.symm).map (fun b => input.symm (output b)) = + (words 1).map input.symm := by + simp only [List.map_map,Function.comp_def,Equiv.apply_symm_apply] + rw [handoff,List.length_map] at returned + have tail := ih (fun i => words (i+1)) (fun i => budgets (i+1)) + (fun i hi => runs (i+1) (Nat.succ_lt_succ hi)) + have first := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ guard body + have second := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ first returned + have full := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ second tail + exact { + toEvalsTo := full.toEvalsTo + steps_le_m := by + have h := full.steps_le_m + simp only [loopBudget] + omega + } + +private theorem inputConfig_init (word : List (M.Γ M.k₀)) : + inputConfig M .parse word [] = initList (machine M input output) word := by + unfold inputConfig initList + congr 1 + funext k + cases k with + | inl k => + by_cases h : k = M.k₀ + · subst k; simp [inputTapes,initList,machine]; rfl + · simp [inputTapes,initList,machine,h] + | inr k => cases k <;> simp [inputTapes,initList,machine,extraTapes] + +def executeSequence (count : Nat) (words : Nat → List Bool) (budgets : Nat → Nat) + (runs : ∀ i, i < count → TM2OutputsInTime M ((words i).map input.symm) + (some ((words (i+1)).map output.symm)) (budgets i)) : + TM2OutputsInTime (machine M input output) + ((encodeWord count ++ words 0).map input.symm) + (some ((words count).map input.symm)) + (count+1 + loopBudget count words budgets) := by + let parsed : StateTransition.EvalsToInTime (machine M input output).step + (inputConfig M .parse ((encodeWord count).map input.symm ++ (words 0).map input.symm) []) + (some (inputConfig M .guard ((words 0).map input.symm) + (List.replicate count (input.symm true)))) (count+1) := { + steps := count+1 + evals_in_steps := by + change (MachineComposition.advance (machine M input output).step)^[count+1] + (some (inputConfig M .parse ((encodeWord count).map input.symm ++ (words 0).map input.symm) [])) = _ + simpa only [List.append_nil] using! parseTrace M input output count + ((words 0).map input.symm) [] + steps_le_m := le_refl _ + } + have body := loopExecution M input output count words budgets runs + have full := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ parsed body + rw [inputConfig_init M input output] at full + erw [List.map_append] + simpa only [TM2OutputsInTime,Option.map_some,Nat.add_comm] using! full + +omit M input output in + +theorem loopBudget_eq_sum (count : Nat) (words : Nat → List Bool) (budgets : Nat → Nat) : + loopBudget count words budgets = + (∑ i ∈ Finset.range count, (budgets i + 2*(words (i+1)).length+3)) + + 2*(words count).length+3 := by + induction count generalizing words budgets with + | zero => simp [loopBudget] + | succ count ih => + rw [loopBudget, ih, Finset.sum_range_succ'] + simp only [Nat.zero_add] + omega + +def executeSequenceSum (count : Nat) (words : Nat → List Bool) (budgets : Nat → Nat) + (runs : ∀ i, i < count → TM2OutputsInTime M ((words i).map input.symm) + (some ((words (i+1)).map output.symm)) (budgets i)) : + TM2OutputsInTime (machine M input output) + ((encodeWord count ++ words 0).map input.symm) + (some ((words count).map input.symm)) + (count+1 + ((∑ i ∈ Finset.range count, (budgets i+2*(words (i+1)).length+3)) + + 2*(words count).length+3)) := by + rw [← loopBudget_eq_sum] + exact executeSequence M input output count words budgets runs + +omit M input output in + +theorem loopBudget_le (count : Nat) (words : Nat → List Bool) (budgets : Nat → Nat) + (bodyBound lengthBound : Nat) + (hb : ∀i, i (state.1, head)) + (.branch (fun state => state.2.getD false) + (.push destination (fun _ => true) (.goto fun _ => loopLabel)) + (.load (fun state => (state.1, none)) + (Reduction.MachineTransfer.exitAt destination exit))) + +def fieldStart (destination : K) (loopLabel : Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) := + .push destination (fun _ => false) (.goto fun _ => loopLabel) + +def fieldTapes (source destination : K) (base : K → List Bool) + (input output : List Bool) : K → List Bool := + Function.update (Function.update base source input) destination output + +@[simp] theorem fieldTapes_source (source destination : K) (hne : source ≠ destination) + (base : K → List Bool) (input output : List Bool) : + fieldTapes source destination base input output source = input := by + simp [fieldTapes, hne] + +@[simp] theorem fieldTapes_destination (source destination : K) + (base : K → List Bool) (input output : List Bool) : + fieldTapes source destination base input output destination = output := by + simp [fieldTapes] + +@[simp] theorem fieldTapes_self (source destination : K) (base : K → List Bool) : + fieldTapes source destination base (base source) (base destination) = base := by + simp [fieldTapes] + +theorem fieldTapes_other (source destination p : K) + (hpS : p ≠ source) (hpD : p ≠ destination) + (base : K → List Bool) (input output : List Bool) : + fieldTapes source destination base input output p = base p := by + simp [fieldTapes, hpS, hpD] + +private theorem update_field_source (source destination : K) (hne : source ≠ destination) + (base : K → List Bool) (input output replacement : List Bool) : + Function.update (fieldTapes source destination base input output) source replacement = + fieldTapes source destination base replacement output := by + funext p + by_cases hs : p = source + · subst p; simp [fieldTapes, hne] + · by_cases hd : p = destination + · subst p; simp [fieldTapes, Ne.symm hne] + · simp [fieldTapes, hs, hd] + +private theorem update_field_destination (source destination : K) + (base : K → List Bool) (input output replacement : List Bool) : + Function.update (fieldTapes source destination base input output) destination replacement = + fieldTapes source destination base input replacement := by + simp [fieldTapes] + +theorem fieldStep_delimiter (source destination : K) (hne : source ≠ destination) + (loopLabel : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atLoop : program loopLabel = fieldLoop source destination loopLabel exit) + (base : K → List Bool) (suffix output : List Bool) (ambient : σ) (register : Option Bool) : + TM2.step program + ⟨some loopLabel, (ambient, register), fieldTapes source destination base (false :: suffix) output⟩ = + some ⟨exit, (ambient, none), fieldTapes source destination base suffix output⟩ := by + change some (TM2.stepAux (program loopLabel) (ambient, register) + (fieldTapes source destination base (false :: suffix) output)) = _ + rw [atLoop] + cases exit <;> + simp [fieldLoop, Reduction.MachineTransfer.exitAt, TM2.stepAux, hne, update_field_source] + +theorem fieldStep_true (source destination : K) (hne : source ≠ destination) + (loopLabel : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atLoop : program loopLabel = fieldLoop source destination loopLabel exit) + (base : K → List Bool) (input output : List Bool) (ambient : σ) (register : Option Bool) : + TM2.step program + ⟨some loopLabel, (ambient, register), fieldTapes source destination base (true :: input) output⟩ = + some ⟨some loopLabel, (ambient, some true), + fieldTapes source destination base input (true :: output)⟩ := by + change some (TM2.stepAux (program loopLabel) (ambient, register) + (fieldTapes source destination base (true :: input) output)) = _ + rw [atLoop] + simp [fieldLoop, TM2.stepAux, hne, update_field_source, update_field_destination] + +theorem fieldLoopTrace (source destination : K) (hne : source ≠ destination) + (loopLabel : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atLoop : program loopLabel = fieldLoop source destination loopLabel exit) + (base : K → List Bool) (n : Nat) (suffix output : List Bool) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[n + 1] + (some ⟨some loopLabel, (ambient, register), + fieldTapes source destination base (encodeWord n ++ suffix) output⟩) = + some ⟨exit, (ambient, none), + fieldTapes source destination base suffix (List.replicate n true ++ output)⟩ := by + induction n generalizing output register with + | zero => + simpa only [Nat.zero_add, Function.iterate_one, MachineComposition.advance_some, + encodeWord, List.replicate_zero, List.nil_append, List.singleton_append] using + fieldStep_delimiter source destination hne loopLabel exit program atLoop + base suffix output ambient register + | succ n ih => + rw [Function.iterate_succ_apply] + simp only [encodeWord, List.replicate_succ, List.cons_append] + change (MachineComposition.advance (TM2.step program))^[n + 1] + (TM2.step program ⟨some loopLabel, (ambient, register), + fieldTapes source destination base (true :: (encodeWord n ++ suffix)) output⟩) = _ + rw [fieldStep_true source destination hne loopLabel exit program atLoop, ih] + have hrotate : List.replicate n true ++ true :: output = + true :: (List.replicate n true ++ output) := by + calc + _ = (List.replicate n true ++ [true]) ++ output := by simp + _ = List.replicate (n + 1) true ++ output := by rw [List.replicate_succ'] + _ = _ := by rw [List.replicate_succ, List.cons_append] + rw [hrotate] + +theorem fieldStartStep (source destination : K) + (startLabel loopLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atStart : program startLabel = fieldStart destination loopLabel) + (base : K → List Bool) (input output : List Bool) (ambient : σ) (register : Option Bool) : + TM2.step program + ⟨some startLabel, (ambient, register), fieldTapes source destination base input output⟩ = + some ⟨some loopLabel, (ambient, register), + fieldTapes source destination base input (false :: output)⟩ := by + change some (TM2.stepAux (program startLabel) (ambient, register) + (fieldTapes source destination base input output)) = _ + rw [atStart] + simp [fieldStart, TM2.stepAux, update_field_destination] + +def fieldInTime (source destination : K) (hne : source ≠ destination) + (startLabel loopLabel : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atStart : program startLabel = fieldStart destination loopLabel) + (atLoop : program loopLabel = fieldLoop source destination loopLabel exit) + (base : K → List Bool) (n : Nat) (suffix : List Bool) + (hinput : base source = encodeWord n ++ suffix) + (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some startLabel, (ambient, register), base⟩ + (some ⟨exit, (ambient, none), + fieldTapes source destination base suffix (encodeWord n ++ base destination)⟩) + (n + 2) where + steps := n + 2 + evals_in_steps := by + have hbase : fieldTapes source destination base (encodeWord n ++ suffix) + (base destination) = base := by rw [← hinput, fieldTapes_self] + conv_lhs => rw [← hbase] + change (MachineComposition.advance (TM2.step program))^[(n + 1) + 1] + (some ⟨some startLabel, (ambient, register), + fieldTapes source destination base (encodeWord n ++ suffix) (base destination)⟩) = _ + rw [Function.iterate_succ_apply] + change (MachineComposition.advance (TM2.step program))^[n + 1] + (TM2.step program ⟨some startLabel, (ambient, register), + fieldTapes source destination base (encodeWord n ++ suffix) (base destination)⟩) = _ + rw [fieldStartStep source destination startLabel loopLabel program atStart, + fieldLoopTrace source destination hne loopLabel exit program atLoop] + simp [encodeWord, List.append_assoc] + steps_le_m := Nat.le_refl _ + +def afterField (source destination : K) (base : K → List Bool) + (n : Nat) (suffix : List Bool) : K → List Bool := + fieldTapes source destination base suffix (encodeWord n ++ base destination) + +def fieldNext (start : Fin 4 → Λ) (exit : Option Λ) (j : Fin 4) : Option Λ := + match j.val with + | 0 => some (start 1) + | 1 => some (start 2) + | 2 => some (start 3) + | _ => exit + +def fourTapes (source : K) (destination : Fin 4 → K) (base : K → List Bool) + (a b c d : Nat) (suffix : List Bool) : K → List Bool := + let t₀ := afterField source (destination 0) base a (encodeWords [b, c, d] ++ suffix) + let t₁ := afterField source (destination 1) t₀ b (encodeWords [c, d] ++ suffix) + let t₂ := afterField source (destination 2) t₁ c (encodeWords [d] ++ suffix) + afterField source (destination 3) t₂ d suffix + +theorem fourTapes_source (source : K) (destination : Fin 4 → K) + (hsep : ∀ j, source ≠ destination j) (base : K → List Bool) + (a b c d : Nat) (suffix : List Bool) : + fourTapes source destination base a b c d suffix source = suffix := by + simp [fourTapes, afterField, hsep] + +theorem fourTapes_other (source : K) (destination : Fin 4 → K) + (p : K) (hpS : p ≠ source) (hpD : ∀ j, p ≠ destination j) + (base : K → List Bool) (a b c d : Nat) (suffix : List Bool) : + fourTapes source destination base a b c d suffix p = base p := by + simp [fourTapes, afterField, fieldTapes_other, hpS, hpD] + +theorem fourField_time_eq_length (a b c d : Nat) : + a + b + c + d + 8 = (encodeWords [a, b, c, d]).length + 4 := by + simp [encodeWords, encodeWord] + omega + +def fourFieldsInTime (source : K) (destination : Fin 4 → K) + (hsep : ∀ j, source ≠ destination j) + (start loopLabel : Fin 4 → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atStart : ∀ j, program (start j) = fieldStart (destination j) (loopLabel j)) + (atLoop : ∀ j, program (loopLabel j) = + fieldLoop source (destination j) (loopLabel j) (fieldNext start exit j)) + (base : K → List Bool) (a b c d : Nat) (suffix : List Bool) + (hinput : base source = encodeWords [a, b, c, d] ++ suffix) + (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (start 0), (ambient, register), base⟩ + (some ⟨exit, (ambient, none), fourTapes source destination base a b c d suffix⟩) + (a + b + c + d + 8) := by + let t₀ := afterField source (destination 0) base a (encodeWords [b, c, d] ++ suffix) + let t₁ := afterField source (destination 1) t₀ b (encodeWords [c, d] ++ suffix) + let t₂ := afterField source (destination 2) t₁ c (encodeWords [d] ++ suffix) + have h₀ : base source = encodeWord a ++ (encodeWords [b, c, d] ++ suffix) := by + simpa only [encodeWords, List.append_assoc] using hinput + have h₁ : t₀ source = encodeWord b ++ (encodeWords [c, d] ++ suffix) := by + simp [t₀, afterField, hsep, encodeWords, List.append_assoc] + have h₂ : t₁ source = encodeWord c ++ (encodeWords [d] ++ suffix) := by + simp [t₁, afterField, hsep, encodeWords, List.append_assoc] + have h₃ : t₂ source = encodeWord d ++ suffix := by + simp [t₂, afterField, hsep, encodeWords] + have p₀ := fieldInTime source (destination 0) (hsep 0) (start 0) (loopLabel 0) + (some (start 1)) program (atStart 0) (atLoop 0) base a + (encodeWords [b, c, d] ++ suffix) h₀ ambient register + have p₁ := fieldInTime source (destination 1) (hsep 1) (start 1) (loopLabel 1) + (some (start 2)) program (atStart 1) (atLoop 1) t₀ b + (encodeWords [c, d] ++ suffix) h₁ ambient none + have p₂ := fieldInTime source (destination 2) (hsep 2) (start 2) (loopLabel 2) + (some (start 3)) program (atStart 2) (atLoop 2) t₁ c + (encodeWords [d] ++ suffix) h₂ ambient none + have p₃ := fieldInTime source (destination 3) (hsep 3) (start 3) (loopLabel 3) + exit program (atStart 3) (atLoop 3) t₂ d suffix h₃ ambient none + 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; omega + } + +def fieldDestination (j : Fin 4) : Fin 5 := ⟨j.val + 1, by omega⟩ + +theorem fourTapes_concrete (base : Fin 5 → List Bool) (a b c d : Nat) (suffix : List Bool) : + fourTapes 0 fieldDestination base a b c d suffix = + fun p : Fin 5 => if p = 0 then suffix + else if p = 1 then encodeWord a ++ base 1 + else if p = 2 then encodeWord b ++ base 2 + else if p = 3 then encodeWord c ++ base 3 + else encodeWord d ++ base 4 := by + funext p + have hp : p = 0 ∨ p = 1 ∨ p = 2 ∨ p = 3 ∨ p = 4 := by omega + rcases hp with rfl | rfl | rfl | rfl | rfl <;> + simp [fourTapes, afterField, fieldTapes, fieldDestination] + +def groupingProgram (label : Fin 4 × Bool) : + TM2.Stmt (fun _ : Fin 5 => Bool) (Fin 4 × Bool) (Unit × Option Bool) := + if label.2 then + fieldLoop 0 (fieldDestination label.1) (label.1, true) + (fieldNext (fun j => (j, false)) none label.1) + else fieldStart (fieldDestination label.1) (label.1, true) + +def groupingMachine : FinTM2 where + K := Fin 5 + k₀ := 0 + k₁ := 1 + Γ _ := Bool + Λ := Fin 4 × Bool + main := (0, false) + σ := Unit × Option Bool + initialState := ((), none) + m := groupingProgram + +def groupingMachineInTime (base : Fin 5 → List Bool) (a b c d : Nat) (suffix : List Bool) + (hinput : base 0 = encodeWords [a, b, c, d] ++ suffix) (register : Option Bool) : + StateTransition.EvalsToInTime groupingMachine.step + ⟨some (0, false), ((), register), base⟩ + (some ⟨none, ((), none), fourTapes (0 : Fin 5) fieldDestination base a b c d suffix⟩) + (a + b + c + d + 8) := + fourFieldsInTime (0 : Fin 5) fieldDestination (by + intro j h + have hh := congrArg Fin.val h + change 0 = j.val + 1 at hh + omega) + (fun j => (j, false)) (fun j => (j, true)) none groupingProgram + (by intro j; simp [groupingProgram]) (by intro j; simp [groupingProgram]) + base a b c d suffix hinput () register + +end MinUncutGames.Foundations.Hastad.SourceMachine + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineBinaryFormula.lean b/lean/OAI/Computability/MinUncut/Machines/MachineBinaryFormula.lean new file mode 100644 index 0000000000000000000000000000000000000000..25183f7f29191dfba6af074501b30e18beb2d737 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineBinaryFormula.lean @@ -0,0 +1,384 @@ +import Mathlib +import OAI.Computability.MinUncut.Encoding.FormulaEncoding + +namespace OAI + +section +namespace MinUncutGames.BinaryFormula + +open MinUncutGames.Foundations + +def clauseNames (c : Clause) : List Nat := + [(c)[0].name, (c)[1].name, (c)[2].name] + +def sourceNames (F : Formula) : List Nat := + F.clauses.flatMap clauseNames + +def activeNames (F : Formula) : List Nat := + (sourceNames F).eraseDups + +theorem literal_mem_active (F : Formula) (c : Clause) + (hc : c ∈ F.clauses) (i : Fin 3) : (c)[i].name ∈ activeNames F := by + simp only [activeNames, List.mem_eraseDups] + apply List.mem_flatMap.mpr + refine ⟨c, hc, ?_⟩ + have hi : i = 0 ∨ i = 1 ∨ i = 2 := by omega + rcases hi with rfl | rfl | rfl <;> simp [clauseNames] + +def compactIndex (F : Formula) (v : Nat) + (hv : v ∈ activeNames F) : Fin (activeNames F).length := + ⟨(activeNames F).idxOf v, List.idxOf_lt_length_iff.mpr hv⟩ + +def decodeName (F : Formula) (v : Fin (activeNames F).length) : Nat := + (activeNames F)[v.val] + +def compactLiteral (F : Formula) (l : Literal) + (hl : l.name ∈ activeNames F) : Target.Literal (activeNames F).length := + ⟨compactIndex F l.name hl, l.positive⟩ + +def compactClause (F : Formula) (c : Clause) + (hc : c ∈ F.clauses) : Target.Clause (activeNames F).length := + #v[compactLiteral F (c)[0] (literal_mem_active F c hc 0), + compactLiteral F (c)[1] (literal_mem_active F c hc 1), + compactLiteral F (c)[2] (literal_mem_active F c hc 2)] + +def compactClauses (F : Formula) : List (Target.Clause (activeNames F).length) := + F.clauses.attach.map (fun c => compactClause F c.val c.property) + +def dense (F : Formula) : Target.Formula where + «variables» := (activeNames F).length + clauses := compactClauses F + +def restrictAssignment (F : Formula) (A : Nat → Bool) : + Fin (activeNames F).length → Bool := fun v => A (decodeName F v) + +def extendAssignment (F : Formula) (B : Fin (activeNames F).length → Bool) + (v : Nat) : Bool := + if hv : v ∈ activeNames F then B (compactIndex F v hv) else false + +@[simp] theorem decode_compactIndex (F : Formula) (v : Nat) + (hv : v ∈ activeNames F) : decodeName F (compactIndex F v hv) = v := by + exact List.getElem_idxOf (List.idxOf_lt_length_iff.mpr hv) + +theorem compactIndex_injective (F : Formula) (u v : Nat) + (hu : u ∈ activeNames F) (hv : v ∈ activeNames F) + (h : compactIndex F u hu = compactIndex F v hv) : u = v := by + have decoded := congrArg (decodeName F) h + simpa only [decode_compactIndex] using decoded + +@[simp] theorem compactLiteral_positive (F : Formula) (l : Literal) + (hl : l.name ∈ activeNames F) : (compactLiteral F l hl).positive = l.positive := rfl + +@[simp] theorem eval_compact_restrict (F : Formula) (c : Clause) + (hc : c ∈ F.clauses) (A : Nat → Bool) : + (compactClause F c hc).eval (restrictAssignment F A) = c.eval A := by + simp [compactClause, compactLiteral, Target.Clause.eval, Target.Literal.eval, + Clause.eval, Literal.eval, restrictAssignment, decode_compactIndex] + +@[simp] theorem eval_compact_extend (F : Formula) (c : Clause) + (hc : c ∈ F.clauses) (B : Fin (activeNames F).length → Bool) : + (compactClause F c hc).eval B = c.eval (extendAssignment F B) := by + have h₀ : (c)[0].name ∈ activeNames F := literal_mem_active F c hc 0 + have h₁ : (c)[1].name ∈ activeNames F := literal_mem_active F c hc 1 + have h₂ : (c)[2].name ∈ activeNames F := literal_mem_active F c hc 2 + simp [compactClause, compactLiteral, Target.Clause.eval, Target.Literal.eval, + Clause.eval, Literal.eval, extendAssignment, h₀, h₁, h₂] + rfl + +def evaluationList (F : Formula) (A : Nat → Bool) : List Bool := + F.clauses.map (fun c => c.eval A) + +theorem evaluationList_restrict (F : Formula) (A : Nat → Bool) : + PCP.NameCompaction.evaluationList (dense F) (restrictAssignment F A) = + evaluationList F A := by + simp only [PCP.NameCompaction.evaluationList, evaluationList, dense, compactClauses, + List.map_map] + simpa only [Function.comp_def, eval_compact_restrict] using + PCP.NameCompaction.map_attach_val F.clauses (fun c => c.eval A) + +theorem evaluationList_extend (F : Formula) (B : Fin (dense F).«variables» → Bool) : + PCP.NameCompaction.evaluationList (dense F) B = + evaluationList F (extendAssignment F B) := by + simp only [PCP.NameCompaction.evaluationList, evaluationList, dense, compactClauses, + List.map_map] + change F.clauses.attach.map (fun c => (compactClause F c.val c.property).eval B) = _ + calc + _ = F.clauses.attach.map (fun c => c.val.eval (extendAssignment F B)) := by + apply List.map_congr_left + intro c _ + exact eval_compact_extend F c.val c.property B + _ = _ := PCP.NameCompaction.map_attach_val F.clauses + (fun c => c.eval (extendAssignment F B)) + +def failedCount (F : Formula) (A : Nat → Bool) : Nat := + (evaluationList F A).count false + +theorem failedCount_restrict (F : Formula) (A : Nat → Bool) : + PCP.NameCompaction.failedCount (dense F) (restrictAssignment F A) = failedCount F A := by + simp only [PCP.NameCompaction.failedCount, failedCount, evaluationList_restrict] + +theorem failedCount_extend (F : Formula) (B : Fin (dense F).«variables» → Bool) : + PCP.NameCompaction.failedCount (dense F) B = failedCount F (extendAssignment F B) := by + simp only [PCP.NameCompaction.failedCount, failedCount, evaluationList_extend] + +theorem clauseNames_flat_length (cs : List Clause) : + (cs.flatMap clauseNames).length = 3 * cs.length := by + induction cs with + | nil => simp + | cons c cs ih => + simp only [List.flatMap_cons, List.length_append, clauseNames, + List.length_cons, List.length_nil, ih] + omega + +@[simp] theorem dense_clause_count (F : Formula) : + (dense F).clauses.length = F.clauses.length := by + simp [dense, compactClauses] + +theorem dense_variable_bound (F : Formula) : + (dense F).«variables» ≤ 3 * F.clauses.length := by + have h := PCP.NameCompaction.length_eraseDups_le (sourceNames F) + simpa only [sourceNames, clauseNames_flat_length, dense, activeNames] using h + +theorem dense_completeness (F : Formula) (hs : F.Satisfiable) : + (dense F).Satisfiable := by + rcases hs with ⟨A, hA⟩ + refine ⟨restrictAssignment F A, ?_⟩ + intro d hd + change d ∈ F.clauses.attach.map (fun c => compactClause F c.val c.property) at hd + rcases List.mem_map.mp hd with ⟨c, _, rfl⟩ + exact (eval_compact_restrict F c.val c.property A).trans (hA c.val c.property) + +theorem dense_reflects (F : Formula) (hs : (dense F).Satisfiable) : F.Satisfiable := by + rcases hs with ⟨B, hB⟩ + refine ⟨extendAssignment F B, ?_⟩ + intro c hc + have hm : compactClause F c hc ∈ (dense F).clauses := by + change _ ∈ F.clauses.attach.map (fun d => compactClause F d.val d.property) + exact List.mem_map.mpr ⟨⟨c, hc⟩, by simp, rfl⟩ + rw [← eval_compact_extend F c hc B] + exact hB _ hm + +theorem dense_satisfiable_iff (F : Formula) : + (dense F).Satisfiable ↔ F.Satisfiable := + ⟨dense_reflects F, dense_completeness F⟩ + +theorem dense_preserves_gap (F : Formula) (a b : Nat) + (gap : ∀ A, a * F.clauses.length ≤ b * failedCount F A) + (B : Fin (dense F).«variables» → Bool) : + a * (dense F).clauses.length ≤ b * PCP.NameCompaction.failedCount (dense F) B := by + rw [dense_clause_count, failedCount_extend] + exact gap (extendAssignment F B) + +theorem dense_encoding_bound (F : Formula) : + (Complexity.formulaBits (dense F)).length ≤ + 9 * F.clauses.length * F.clauses.length + 10 * F.clauses.length + 2 := by + have enc := Complexity.formulaBits_length_le (dense F) + rw [dense_clause_count] at enc + have active := dense_variable_bound F + have h₁ := Nat.add_le_add_right active (F.clauses.length + 2) + have h₂ := Nat.mul_le_mul_left F.clauses.length + (Nat.mul_le_mul_left 3 (Nat.add_le_add_right active 2)) + have total := Nat.add_le_add h₁ h₂ + have polynomial : 3 * F.clauses.length + (F.clauses.length + 2) + + F.clauses.length * (3 * (3 * F.clauses.length + 2)) = + 9 * F.clauses.length * F.clauses.length + 10 * F.clauses.length + 2 := by + ring + rw [polynomial] at total + omega + +end MinUncutGames.BinaryFormula + +end +section +namespace MinUncutGames.BinaryEncoding + +open BinaryFormula + +def bitsValue : List Bool → Nat + | [] => 0 + | b :: bits => Nat.bit b (bitsValue bits) + +@[simp] theorem bitsValue_bits (n : Nat) : bitsValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [bitsValue] + | bit b n hn ih => + rw [Nat.bits_append_bit n b hn] + simp only [bitsValue, ih] + +def parseFrame : List Bool → Option (List Bool × List Bool) + | false :: rest => some ([], rest) + | true :: b :: rest => do + let (bits, trailing) ← parseFrame rest + return (b :: bits, trailing) + | _ => none + +@[simp] theorem parseFrame_encoded (bits trailing : List Bool) : + parseFrame (frame bits ++ trailing) = some (bits, trailing) := by + induction bits with + | nil => rfl + | cons b bits ih => simp [frame, parseFrame, ih] + +@[simp] theorem frame_length (bits : List Bool) : + (frame bits).length = 2 * bits.length + 1 := by + induction bits with + | nil => rfl + | cons b bits ih => simp [frame, ih]; omega + +def parseName (input : List Bool) : Option (Nat × List Bool) := do + let (digits, rest) ← parseFrame input + let name := bitsValue digits + if digits = name.bits then some (name, rest) else none + +@[simp] theorem parseName_encoded (name : Nat) (rest : List Bool) : + parseName (nameBits name ++ rest) = some (name, rest) := by + simp [parseName, nameBits] + +@[simp] theorem nameBits_length (name : Nat) : + (nameBits name).length = 2 * name.size + 1 := by + simp [nameBits, Nat.size_eq_bits_len] + +theorem nameBits_length_le_of_lt_pow (name width : Nat) (bound : name < 2 ^ width) : + (nameBits name).length ≤ 2 * width + 1 := by + rw [nameBits_length] + have h := Nat.size_le.mpr bound + omega + +def parseLiteral : List Bool → Option (Literal × List Bool) + | sign :: input => do + let (name, rest) ← parseName input + return (⟨name, sign⟩, rest) + | [] => none + +@[simp] theorem parseLiteral_encoded (literal : Literal) (rest : List Bool) : + parseLiteral (literalBits literal ++ rest) = some (literal, rest) := by + cases literal with + | mk name sign => simp [literalBits, parseLiteral] + +@[simp] theorem literalBits_length (literal : Literal) : + (literalBits literal).length = 2 * literal.name.size + 2 := by + simp [literalBits] + +def parseClause (input : List Bool) : Option (Clause × List Bool) := do + let (a, input) ← parseLiteral input + let (b, input) ← parseLiteral input + let (c, rest) ← parseLiteral input + return (#v[a, b, c], rest) + +theorem clause_three_entries (clause : Clause) : #v[clause[0], clause[1], clause[2]] = clause := by + apply Vector.ext + intro i hi + have cases_i : i = 0 ∨ i = 1 ∨ i = 2 := by omega + rcases cases_i with rfl | rfl | rfl <;> rfl + +@[simp] theorem parseClause_encoded (clause : Clause) (rest : List Bool) : + parseClause (clauseBits clause ++ rest) = some (clause, rest) := by + simp [clauseBits, List.append_assoc, parseClause, clause_three_entries] + +def clauseNameSize (clause : Clause) : Nat := + ((clauseNames clause).map Nat.size).sum + +@[simp] theorem clauseBits_length (clause : Clause) : + (clauseBits clause).length = 2 * clauseNameSize clause + 6 := by + simp [clauseBits, clauseNameSize, clauseNames] + omega + +def namesBitSize (clauses : List Clause) : Nat := + ((clauses.flatMap clauseNames).map Nat.size).sum + +@[simp] theorem namesBitSize_nil : namesBitSize [] = 0 := rfl + +@[simp] theorem namesBitSize_cons (clause : Clause) (clauses : List Clause) : + namesBitSize (clause :: clauses) = clauseNameSize clause + namesBitSize clauses := by + simp [namesBitSize, clauseNameSize] + +theorem clausesBits_length (clauses : List Clause) : + (clausesBits clauses).length = 7 * clauses.length + 2 * namesBitSize clauses + 1 := by + induction clauses with + | nil => rfl + | cons clause clauses ih => + simp only [clausesBits, List.length_cons, List.length_append, clauseBits_length, + namesBitSize_cons, ih] + omega + +theorem formulaBits_length (formula : Formula) : + (formulaBits formula).length = + 7 * formula.clauses.length + 2 * namesBitSize formula.clauses + 1 := + clausesBits_length formula.clauses + +theorem clauses_length_lt_bits (clauses : List Clause) : + clauses.length < (clausesBits clauses).length := by + rw [clausesBits_length] + omega + +def ordinarySize (formula : Formula) : Nat := + 3 * formula.clauses.length + namesBitSize formula.clauses + 1 + +theorem ordinarySize_le_bits (formula : Formula) : + ordinarySize formula ≤ (formulaBits formula).length := by + rw [formulaBits_length] + unfold ordinarySize + omega + +theorem bits_le_three_ordinarySize (formula : Formula) : + (formulaBits formula).length ≤ 3 * ordinarySize formula := by + rw [formulaBits_length] + unfold ordinarySize + omega + +def parseClauses : Nat → List Bool → Option (List Clause × List Bool) + | 0, _ => none + | _ + 1, false :: rest => some ([], rest) + | fuel + 1, true :: input => do + let (clause, input) ← parseClause input + let (clauses, rest) ← parseClauses fuel input + return (clause :: clauses, rest) + | _ + 1, [] => none + +@[simp] theorem parseClauses_encoded (clauses : List Clause) (rest : List Bool) + (fuel : Nat) (enough : clauses.length < fuel) : + parseClauses fuel (clausesBits clauses ++ rest) = some (clauses, rest) := by + induction clauses generalizing fuel with + | nil => + cases fuel with + | zero => omega + | succ fuel => simp [clausesBits, parseClauses] + | cons clause clauses ih => + cases fuel with + | zero => omega + | succ fuel => + have hrest : clauses.length < fuel := by simp only [List.length_cons] at enough; omega + simp [clausesBits, parseClauses, List.append_assoc, ih fuel hrest] + +def decodeFormula (input : List Bool) : Option Formula := do + let (clauses, rest) ← parseClauses (input.length + 1) input + if rest = [] then some ⟨clauses⟩ else none + +@[simp] theorem decodeFormula_encoded (formula : Formula) : + decodeFormula (formulaBits formula) = some formula := by + cases formula with + | mk clauses => + have hlen := clauses_length_lt_bits clauses + have parsed := parseClauses_encoded clauses [] ((clausesBits clauses).length + 1) (by omega) + simp only [List.append_nil] at parsed + simp [formulaBits, decodeFormula, parsed] + +theorem formulaBits_injective {first second : Formula} + (same : formulaBits first = formulaBits second) : first = second := by + have parsed := congrArg decodeFormula same + simpa only [decodeFormula_encoded, Option.some.injEq] using parsed + +theorem dense_encoding_bound (formula : Formula) : + (MinUncutGames.Foundations.Complexity.formulaBits (dense formula)).length ≤ + 9 * (formulaBits formula).length * (formulaBits formula).length + + 10 * (formulaBits formula).length + 2 := by + have h := BinaryFormula.dense_encoding_bound formula + have hm : formula.clauses.length ≤ (formulaBits formula).length := + (clauses_length_lt_bits formula.clauses).le + have hsq := Nat.mul_self_le_mul_self hm + nlinarith + +end MinUncutGames.BinaryEncoding + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineBinaryLiteralMachine.lean b/lean/OAI/Computability/MinUncut/Machines/MachineBinaryLiteralMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..e82337c3ed42c9f9a24823b4cbc0a2e18e497f74 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineBinaryLiteralMachine.lean @@ -0,0 +1,761 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineBinaryNameMachine + +namespace OAI + +namespace MinUncutGames.BinaryLiteralMachine + +open Turing +open MinUncutGames.Foundations.Complexity +open MachineComposition +open MinUncutGames.Reduction.MachineTransfer + +variable {K Λ A : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool +abbrev State (A : Type) := BinaryNameCompare.State (A × Bool) +abbrev clean (ambient : A) (sign : Bool := false) : State A := + BinaryNameCompare.clean (ambient, sign) + +inductive Label + | readSign | scanKey | copyOut | copyBack + | search (label : BinaryNameSearch.Label) + | drainSearch | drainKey | emitIndex | emitSign + deriving DecidableEq, Fintype + +def searchTapes (tape : Fin 9 → K) : Fin 6 → K + | 0 => tape 3 + | 1 => tape 2 + | 2 => tape 4 + | 3 => tape 5 + | 4 => tape 6 + | 5 => tape 7 + +omit [DecidableEq K] in +theorem searchTapes_injective (tape : Fin 9 → K) (distinct : Function.Injective tape) : + Function.Injective (searchTapes tape) := by + intro i j h + fin_cases i <;> fin_cases j <;> simp only [searchTapes] at h + all_goals first | rfl | have heq := congrArg Fin.val (distinct h); norm_num at heq + +def finish (exit : Option Λ) : TM2.Stmt (Alphabet (K := K)) Λ (State A) := + .load (fun state => clean state.1.1.1) + (match exit with + | none => .halt + | some label => .goto fun _ => label) + +def readSign (tape : Fin 9 → K) (next : Λ) (malformed : Option Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (State A) := + .push (tape 7) (fun _ => false) + (.pop (tape 0) (fun state head => (state.1, head)) + (.branch (fun state => state.2.isSome) + (.load (fun state => clean state.1.1.1 (state.2.getD false)) (.goto fun _ => next)) + (finish malformed))) + +def emitSign (output : K) (exit : Option Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (State A) := + .branch (fun state => state.1.1.2) + (.push output (fun _ => true) (.push output (fun _ => false) (finish exit))) + (.push output (fun _ => false) (finish exit)) + +def instruction (tape : Fin 9 → K) (labels : Label → Λ) + (exit malformed : Option Λ) : Label → TM2.Stmt (Alphabet (K := K)) Λ (State A) + | .readSign => readSign tape (labels .scanKey) malformed + | .scanKey => MachineStateEquiv.statement (BinaryNameCompare.scanStateEquiv (A × Bool)) + (BinaryNameMachine.scan (tape 0) (tape 2) (labels .scanKey) + (some (labels .copyOut)) malformed) + | .copyOut => loopAt (tape 1) (tape 6) id false + (labels .copyOut) (some (labels .copyBack)) + | .copyBack => MachineCopy.forkLoop (tape 6) (tape 1) (tape 3) false + (labels .copyBack) (some (labels (.search .sign))) + | .search l => BinaryNameSearch.instruction (searchTapes tape) + (fun l => labels (.search l)) (some (labels .drainSearch)) malformed malformed l + | .drainSearch => MachineDrain.drain (tape 3) (labels .drainSearch) + (some (labels .drainKey)) + | .drainKey => MachineDrain.drain (tape 2) (labels .drainKey) + (some (labels .emitIndex)) + | .emitIndex => loopAt (tape 7) (tape 8) id false + (labels .emitIndex) (some (labels .emitSign)) + | .emitSign => emitSign (tape 8) exit + +def signWord (sign : Bool) : List Bool := encodeWord (if sign then 1 else 0) + +def index (tokens : List BinaryNameSearch.Token) (bits : List Bool) : Nat := + (BinaryNameSearch.payloads tokens).idxOf bits + +def outputWord (tokens : List BinaryNameSearch.Token) (bits : List Bool) (sign : Bool) : + List Bool := encodeWord (index tokens bits) ++ signWord sign + +def steps (tokens : List BinaryNameSearch.Token) (bits : List Bool) : Nat := + 1 + (bits.length + 1) + 2 * ((BinaryNameSearch.stream tokens).length + 1) + + BinaryNameSearch.steps tokens bits + + ((BinaryNameSearch.stream (BinaryNameSearch.afterMatch tokens bits)).length + 1) + + (bits.length + 1) + (index tokens bits + 2) + 1 + +theorem afterMatch_length_le (tokens : List BinaryNameSearch.Token) (bits : List Bool) : + (BinaryNameSearch.stream (BinaryNameSearch.afterMatch tokens bits)).length ≤ + (BinaryNameSearch.stream tokens).length := by + induction tokens with + | nil => simp [BinaryNameSearch.afterMatch] + | cons token tokens ih => + simp only [BinaryNameSearch.afterMatch, BinaryNameSearch.stream_cons, List.length_append] + split <;> omega + +theorem steps_le (tokens : List BinaryNameSearch.Token) (bits : List Bool) + (present : bits ∈ BinaryNameSearch.payloads tokens) : + steps tokens bits ≤ + 3 * ((BinaryNameSearch.stream tokens).length + bits.length) ^ 2 + + 13 * ((BinaryNameSearch.stream tokens).length + bits.length) + 9 := by + have search := BinaryNameSearch.steps_le_stream tokens bits + have suffix := afterMatch_length_le tokens bits + have idx : index tokens bits < tokens.length := by + have h := List.idxOf_lt_length_iff.mpr present + simpa [index, BinaryNameSearch.payloads] using h + have count : tokens.length ≤ (BinaryNameSearch.stream tokens).length := by + rw [BinaryNameSearch.stream_length] + omega + unfold steps + nlinarith [Nat.zero_le ((BinaryNameSearch.stream tokens).length * bits.length)] + +@[simp] theorem stepAux_finish (exit : Option Λ) (state : State A) (base : K → List Bool) : + TM2.stepAux (finish exit) state base = ⟨exit, clean state.1.1.1, base⟩ := by + cases exit <;> rfl + +theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +theorem literalTrace (tape : Fin 9 → K) (distinct : Function.Injective tape) + (labels : Label → Λ) (exit malformed : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ l, program (labels l) = instruction tape labels exit malformed l) + (base : K → List Bool) (tokens : List BinaryNameSearch.Token) + (sign : Bool) (bits suffix : List Bool) + (canonical : BinaryNameMachine.canonical bits = true) + (tokensCanonical : ∀ token ∈ tokens, BinaryNameMachine.canonical token.2 = true) + (present : bits ∈ BinaryNameSearch.payloads tokens) + (cursor : base (tape 0) = sign :: (BinaryNameMachine.frame bits ++ suffix)) + (permanent : base (tape 1) = BinaryNameSearch.stream tokens) + (empty : ∀ i : Fin 9, 2 ≤ i.val → i.val ≤ 7 → base (tape i) = []) + (ambient : A) : + (advance (TM2.step program))^[steps tokens bits] + (some ⟨some (labels .readSign), clean ambient, base⟩) = + some ⟨exit, clean ambient, + Function.update (Function.update base (tape 0) suffix) (tape 8) + ((outputWord tokens bits sign).reverse ++ base (tape 8))⟩ := by + have hd (i j : Fin 9) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + have he (i : Fin 9) (hlo : 2 ≤ i.val := by decide) (hhi : i.val ≤ 7 := by decide) : + base (tape i) = [] := empty i hlo hhi + let s₁ := Function.update (Function.update base (tape 7) [false]) (tape 0) + (BinaryNameMachine.frame bits ++ suffix) + let s₂ := Function.update (Function.update s₁ (tape 0) suffix) (tape 2) bits.reverse + let s₃ := Function.update s₂ (tape 3) (BinaryNameSearch.stream tokens) + let tail := BinaryNameSearch.stream (BinaryNameSearch.afterMatch tokens bits) + let s₄ := tapesAt (tape 3) (tape 7) s₃ tail (encodeWord (index tokens bits)) + let s₅ := Function.update s₄ (tape 3) [] + let s₆ := Function.update s₅ (tape 2) [] + let s₇ := tapesAt (tape 7) (tape 8) s₆ [] + ((encodeWord (index tokens bits)).reverse ++ s₆ (tape 8)) + let s₈ := Function.update s₇ (tape 8) ((signWord sign).reverse ++ s₇ (tape 8)) + have signRun : (advance (TM2.step program))^[1] + (some ⟨some (labels .readSign), clean ambient, base⟩) = + some ⟨some (labels .scanKey), clean ambient sign, s₁⟩ := by + change some (TM2.stepAux (program (labels .readSign)) _ _) = _ + rw [atLabels .readSign] + simp [instruction, readSign, TM2.stepAux, clean, BinaryNameCompare.clean, + cursor, he 7, hd 0 7 (by decide), s₁] + have s₁cursor : s₁ (tape 0) = BinaryNameMachine.frame bits ++ suffix := by simp [s₁] + have s₁key : s₁ (tape 2) = [] := by + simp [s₁, hd 2 0 (by decide), hd 2 7 (by decide), he 2] + have keyRun : (advance (TM2.step program))^[bits.length + 1] + (some ⟨some (labels .scanKey), clean ambient sign, s₁⟩) = + some ⟨some (labels .copyOut), clean ambient sign, s₂⟩ := by + let e := BinaryNameCompare.scanStateEquiv (A × Bool) + let back := MachineStateEquiv.program e.symm program + have atScan : back (labels .scanKey) = + BinaryNameMachine.scan (tape 0) (tape 2) (labels .scanKey) + (some (labels .copyOut)) malformed := by + change MachineStateEquiv.statement e.symm (program (labels .scanKey)) = _ + rw [atLabels .scanKey] + exact MachineStateEquiv.statement_symm_statement e _ + have backForward : MachineStateEquiv.program e back = program := by + funext l + change MachineStateEquiv.statement e (MachineStateEquiv.statement e.symm (program l)) = _ + exact MachineStateEquiv.statement_symm_statement e.symm _ + have initial : tapesAt (tape 0) (tape 2) s₁ + (BinaryNameMachine.frame bits ++ suffix) [] = s₁ := by + rw [← s₁cursor, ← s₁key] + exact tapesAt_self _ _ _ + have native := BinaryNameMachine.framedTrace (tape 0) (tape 2) (hd 0 2 (by decide)) + (labels .scanKey) (some (labels .copyOut)) malformed back atScan s₁ + ((ambient, sign), false) bits suffix [] none + simp only [canonical, ↓reduceIte, initial, List.append_nil] at native + have transported := MachineStateEquiv.trace e back _ _ _ native + rw [backForward] at transported + simpa only [MachineStateEquiv.configuration, e, BinaryNameCompare.scanStateEquiv, Equiv.coe_fn_mk, + BinaryNameMachine.clean, clean, BinaryNameCompare.clean, s₂, tapesAt] using transported + have s₂permanent : s₂ (tape 1) = BinaryNameSearch.stream tokens := by + simpa [s₂, s₁, hd 1 0 (by decide), hd 1 2 (by decide), hd 1 7 (by decide)] using permanent + have s₂empty (i : Fin 9) (hi : i = 3 ∨ i = 4 ∨ i = 5 ∨ i = 6) : s₂ (tape i) = [] := by + rcases hi with rfl | rfl | rfl | rfl <;> + simp [s₂, s₁, hd, he] + have copyRun : (advance (TM2.step program))^[2 * ((BinaryNameSearch.stream tokens).length + 1)] + (some ⟨some (labels .copyOut), clean ambient sign, s₂⟩) = + some ⟨some (labels (.search .sign)), clean ambient sign, s₃⟩ := by + have h := MachineCopy.copyTrace (tape 1) (tape 3) (tape 6) + (hd 1 3 (by decide)) (hd 1 6 (by decide)) (hd 3 6 (by decide)) false + (labels .copyOut) (labels .copyBack) (some (labels (.search .sign))) program + (atLabels .copyOut) (atLabels .copyBack) s₂ + (s₂empty 6 (by simp)) ((ambient, sign), false, none) none + simpa only [s₂permanent, s₂empty 3 (by simp), List.append_nil, + clean, BinaryNameCompare.clean, s₃] using h + have s₃key : s₃ (tape 2) = bits.reverse := by + simp [s₃, s₂, hd 2 3 (by decide)] + have s₃counter : s₃ (tape 7) = [false] := by + simp [s₃, s₂, s₁, hd 7 3 (by decide), hd 7 2 (by decide), hd 7 0 (by decide)] + have s₃stream : s₃ (tape 3) = BinaryNameSearch.stream tokens := by simp [s₃] + have searchRun : (advance (TM2.step program))^[BinaryNameSearch.steps tokens bits] + (some ⟨some (labels (.search .sign)), clean ambient sign, s₃⟩) = + some ⟨some (labels .drainSearch), clean ambient sign, s₄⟩ := by + have h := BinaryNameSearch.searchTrace (searchTapes tape) + (searchTapes_injective tape distinct) (fun l => labels (.search l)) + (some (labels .drainSearch)) malformed malformed program + (fun l => atLabels (.search l)) s₃ (ambient, sign) tokens bits [] [false] + tokensCanonical present s₃key + (by simpa [s₃, searchTapes, hd 4 3 (by decide)] using s₂empty 4 (by simp)) + (by simpa [s₃, searchTapes, hd 5 3 (by decide)] using s₂empty 5 (by simp)) + (by simpa [s₃, searchTapes, hd 6 3 (by decide)] using s₂empty 6 (by simp)) + have initial : tapesAt (tape 3) (tape 7) s₃ (BinaryNameSearch.stream tokens) [false] = s₃ := by + rw [← s₃stream, ← s₃counter] + exact tapesAt_self _ _ _ + simpa only [searchTapes, List.append_nil, initial, clean, BinaryNameSearch.clean, + s₄, tail, encodeWord, index] using h + have s₄stream : s₄ (tape 3) = tail := by simp [s₄, hd 3 7 (by decide)] + have drainSearchRun : (advance (TM2.step program))^[tail.length + 1] + (some ⟨some (labels .drainSearch), clean ambient sign, s₄⟩) = + some ⟨some (labels .drainKey), clean ambient sign, s₅⟩ := by + have h := MachineDrain.drainTrace (tape 3) (labels .drainSearch) + (some (labels .drainKey)) program (atLabels .drainSearch) s₄ tail + ((ambient, sign), false, none) none + have initial : Function.update s₄ (tape 3) tail = s₄ := by + rw [← s₄stream]; exact Function.update_eq_self _ _ + simpa only [initial, clean, BinaryNameCompare.clean, s₅] using h + have s₅key : s₅ (tape 2) = bits.reverse := by + simp [s₅, s₄, tapesAt, hd 2 3 (by decide), hd 2 7 (by decide), s₃key] + have drainKeyRun : (advance (TM2.step program))^[bits.length + 1] + (some ⟨some (labels .drainKey), clean ambient sign, s₅⟩) = + some ⟨some (labels .emitIndex), clean ambient sign, s₆⟩ := by + have h := MachineDrain.drainTrace (tape 2) (labels .drainKey) + (some (labels .emitIndex)) program (atLabels .drainKey) s₅ bits.reverse + ((ambient, sign), false, none) none + have initial : Function.update s₅ (tape 2) bits.reverse = s₅ := by + rw [← s₅key]; exact Function.update_eq_self _ _ + simpa only [initial, List.length_reverse, clean, BinaryNameCompare.clean, s₆] using h + have s₆index : s₆ (tape 7) = encodeWord (index tokens bits) := by + simp [s₆, s₅, s₄, hd 7 2 (by decide), hd 7 3 (by decide)] + have indexRun : (advance (TM2.step program))^[index tokens bits + 2] + (some ⟨some (labels .emitIndex), clean ambient sign, s₆⟩) = + some ⟨some (labels .emitSign), clean ambient sign, s₇⟩ := by + change (nextAt (Γ := Alphabet) (tape 8) program)^[index tokens bits + 2] + (some ⟨some (labels .emitIndex), (((ambient, sign), false, none), none), s₆⟩) = + some ⟨some (labels .emitSign), (((ambient, sign), false, none), none), s₇⟩ + have h := transferAt_fromTapes (Γ := Alphabet) (tape 7) (tape 8) + (hd 7 8 (by decide)) id false (labels .emitIndex) (some (labels .emitSign)) program + (atLabels .emitIndex) s₆ ((ambient, sign), false, none) none + have time : index tokens bits + 1 + 1 = index tokens bits + 2 := by omega + simpa only [s₆index, encodeWord_length, List.map_id_fun, id_eq, time, s₇] using h + have emitRun : (advance (TM2.step program))^[1] + (some ⟨some (labels .emitSign), clean ambient sign, s₇⟩) = + some ⟨exit, clean ambient, s₈⟩ := by + change some (TM2.stepAux (program (labels .emitSign)) _ _) = _ + rw [atLabels .emitSign] + cases sign <;> simp [instruction, emitSign, clean, BinaryNameCompare.clean, + TM2.stepAux, signWord, encodeWord, s₈, Function.update_idem] + have full := joinTrace (joinTrace (joinTrace (joinTrace (joinTrace (joinTrace + (joinTrace signRun keyRun) copyRun) searchRun) drainSearchRun) drainKeyRun) indexRun) emitRun + have finalTapes : s₈ = Function.update (Function.update base (tape 0) suffix) (tape 8) + ((outputWord tokens bits sign).reverse ++ base (tape 8)) := by + funext k + by_cases h8 : k = tape 8 + · subst k + simp [s₈, s₇, s₆, s₅, s₄, s₃, s₂, s₁, tapesAt, outputWord, + List.reverse_append, List.append_assoc, hd] + · by_cases h0 : k = tape 0 + · subst k + simp [s₈, s₇, s₆, s₅, s₄, s₃, s₂, s₁, tapesAt, hd] + · by_cases h2 : k = tape 2 + · subst k + simp [s₈, s₇, s₆, s₅, s₄, s₃, s₂, s₁, tapesAt, hd, he 2] + · by_cases h3 : k = tape 3 + · subst k + simp [s₈, s₇, s₆, s₅, s₄, s₃, s₂, s₁, tapesAt, hd, he 3] + · by_cases h7 : k = tape 7 + · subst k + simp [s₈, s₇, s₆, s₅, s₄, s₃, s₂, s₁, tapesAt, hd, he 7] + · simp [s₈, s₇, s₆, s₅, s₄, s₃, s₂, s₁, tapesAt, h8, h0, h2, h3, h7] + simpa only [steps, tail, finalTapes] using full + +def literalInTime (tape : Fin 9 → K) (distinct : Function.Injective tape) + (labels : Label → Λ) (exit malformed : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ l, program (labels l) = instruction tape labels exit malformed l) + (base : K → List Bool) (tokens : List BinaryNameSearch.Token) + (sign : Bool) (bits suffix : List Bool) + (canonical : BinaryNameMachine.canonical bits = true) + (tokensCanonical : ∀ token ∈ tokens, BinaryNameMachine.canonical token.2 = true) + (present : bits ∈ BinaryNameSearch.payloads tokens) + (cursor : base (tape 0) = sign :: (BinaryNameMachine.frame bits ++ suffix)) + (permanent : base (tape 1) = BinaryNameSearch.stream tokens) + (empty : ∀ i : Fin 9, 2 ≤ i.val → i.val ≤ 7 → base (tape i) = []) + (ambient : A) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .readSign), clean ambient, base⟩ + (some ⟨exit, clean ambient, + Function.update (Function.update base (tape 0) suffix) (tape 8) + ((outputWord tokens bits sign).reverse ++ base (tape 8))⟩) + (3 * ((BinaryNameSearch.stream tokens).length + bits.length) ^ 2 + + 13 * ((BinaryNameSearch.stream tokens).length + bits.length) + 9) where + steps := steps tokens bits + evals_in_steps := literalTrace tape distinct labels exit malformed program atLabels base + tokens sign bits suffix canonical tokensCanonical present cursor permanent empty ambient + steps_le_m := steps_le tokens bits present + +end MinUncutGames.BinaryLiteralMachine + +namespace MinUncutGames.BinaryRenameLoop + +open Turing +open MinUncutGames.Foundations.Complexity +open MachineComposition + +abbrev Token := BinaryNameSearch.Token + +def nextSlot (slot : Fin 3) : Fin 3 := if slot = 0 then 1 else if slot = 1 then 2 else 0 + +def clauseIncrement (slot : Fin 3) : Nat := if slot = 2 then 1 else 0 + +def finalSlot : Nat → Fin 3 → Fin 3 + | 0, slot => slot + | n + 1, slot => finalSlot n (nextSlot slot) + +def completedClauses : Nat → Fin 3 → Nat + | 0, _ => 0 + | n + 1, slot => completedClauses n (nextSlot slot) + clauseIncrement slot + +theorem finalSlot_three (n : Nat) : finalSlot (n + 3) 0 = finalSlot n 0 := by + simp [finalSlot, nextSlot] + +theorem completedClauses_three (n : Nat) : + completedClauses (n + 3) 0 = completedClauses n 0 + 1 := by + simp [completedClauses, nextSlot, clauseIncrement] + +@[simp] theorem finalSlot_triples (n : Nat) : finalSlot (3 * n) 0 = 0 := by + induction n with + | zero => rfl + | succ n ih => rw [Nat.mul_succ, finalSlot_three, ih] + +@[simp] theorem completedClauses_triples (n : Nat) : completedClauses (3 * n) 0 = n := by + induction n with + | zero => rfl + | succ n ih => rw [Nat.mul_succ, completedClauses_three, ih] + +def outputBody (tokens input : List Token) : List Bool := + input.flatMap (fun token => BinaryLiteralMachine.outputWord tokens token.2 token.1) + +@[simp] theorem outputBody_nil (tokens : List Token) : outputBody tokens [] = [] := rfl + +@[simp] theorem outputBody_cons (tokens : List Token) (token : Token) (input : List Token) : + outputBody tokens (token :: input) = + BinaryLiteralMachine.outputWord tokens token.2 token.1 ++ outputBody tokens input := rfl + +def steps (tokens : List Token) : List Token → Nat + | [] => 1 + | token :: input => BinaryLiteralMachine.steps tokens token.2 + 2 + steps tokens input + +theorem payload_length_le_stream (tokens : List Token) (bits : List Bool) + (present : bits ∈ BinaryNameSearch.payloads tokens) : + bits.length ≤ (BinaryNameSearch.stream tokens).length := by + induction tokens with + | nil => simp at present + | cons token tokens ih => + rcases List.mem_cons.mp present with equal | remaining + · rw [equal] + simp only [BinaryNameSearch.stream_cons, List.length_append, + BinaryNameSearch.tokenBits, List.length_cons, BinaryNameMachine.frame_length] + omega + · have tail := ih remaining + simp only [BinaryNameSearch.stream_cons, List.length_append] + omega + +def perLiteralBound (streamLength : Nat) : Nat := + 12 * streamLength ^ 2 + 26 * streamLength + 11 + +theorem literal_steps_le (tokens : List Token) (bits : List Bool) + (present : bits ∈ BinaryNameSearch.payloads tokens) : + BinaryLiteralMachine.steps tokens bits + 2 ≤ + perLiteralBound (BinaryNameSearch.stream tokens).length := by + have body := BinaryLiteralMachine.steps_le tokens bits present + have size := payload_length_le_stream tokens bits present + have sumBound : (BinaryNameSearch.stream tokens).length + bits.length ≤ + 2 * (BinaryNameSearch.stream tokens).length := by omega + have sq := Nat.mul_self_le_mul_self sumBound + unfold perLiteralBound + nlinarith + +theorem steps_le (tokens input : List Token) (included : ∀ token ∈ input, token ∈ tokens) : + steps tokens input ≤ + perLiteralBound (BinaryNameSearch.stream tokens).length * input.length + 1 := by + induction input with + | nil => simp [steps] + | cons token input ih => + have present : token.2 ∈ BinaryNameSearch.payloads tokens := + List.mem_map.mpr ⟨token, included token (by simp), rfl⟩ + have head := literal_steps_le tokens token.2 present + have tail := ih (fun t ht => included t (by simp [ht])) + simp only [steps, List.length_cons] + nlinarith + +theorem steps_le_cubic (tokens input : List Token) + (included : ∀ token ∈ input, token ∈ tokens) + (countBound : input.length ≤ (BinaryNameSearch.stream tokens).length) : + steps tokens input ≤ + 12 * (BinaryNameSearch.stream tokens).length ^ 3 + + 26 * (BinaryNameSearch.stream tokens).length ^ 2 + + 11 * (BinaryNameSearch.stream tokens).length + 1 := by + calc + steps tokens input ≤ + perLiteralBound (BinaryNameSearch.stream tokens).length * input.length + 1 := + steps_le tokens input included + _ ≤ perLiteralBound (BinaryNameSearch.stream tokens).length * + (BinaryNameSearch.stream tokens).length + 1 := + Nat.add_le_add_right (Nat.mul_le_mul_left _ countBound) _ + _ = _ := by unfold perLiteralBound; ring + +variable {K Λ A : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool +abbrev State (A : Type) := BinaryLiteralMachine.State (A × Fin 3) +abbrev clean (ambient : A) (slot : Fin 3) : State A := + BinaryLiteralMachine.clean (ambient, slot) + +inductive Label + | entry + | literal (label : BinaryLiteralMachine.Label) + | tally + deriving DecidableEq, Fintype + +def literalTapes (tape : Fin 11 → K) : Fin 9 → K := fun i => tape i.castSucc.castSucc + +omit [DecidableEq K] in +theorem literalTapes_injective (tape : Fin 11 → K) (distinct : Function.Injective tape) : + Function.Injective (literalTapes tape) := by + intro i j h + apply Fin.ext + exact congrArg (fun i : Fin 11 => i.val) (distinct h) + +def finish (exit : Option Λ) : TM2.Stmt (Alphabet (K := K)) Λ (State A) := + .load (fun state => clean state.1.1.1.1 state.1.1.1.2) + (match exit with + | none => .halt + | some label => .goto fun _ => label) + +def next (again : Λ) : TM2.Stmt (Alphabet (K := K)) Λ (State A) := + .load (fun state => clean state.1.1.1.1 (nextSlot state.1.1.1.2)) + (.goto fun _ => again) + +def instruction (tape : Fin 11 → K) (labels : Label → Λ) + (done malformed : Option Λ) : Label → TM2.Stmt (Alphabet (K := K)) Λ (State A) + | .entry => + .pop (tape 0) (fun state head => (state.1, head)) + (.branch (fun state => state.2.isSome) + (.push (tape 0) (fun state => state.2.getD false) + (finish (some (labels (.literal .readSign))))) + (finish done)) + | .literal l => BinaryLiteralMachine.instruction (literalTapes tape) + (fun l => labels (.literal l)) (some (labels .tally)) malformed l + | .tally => + .push (tape 9) (fun _ => true) + (.branch (fun state => state.1.1.1.2 == (2 : Fin 3)) + (.push (tape 10) (fun _ => true) (next (labels .entry))) + (next (labels .entry))) + +def loopTapes (tape : Fin 11 → K) (base : K → List Bool) + (cursor output variableCounter clauses : List Bool) : K → List Bool := + Function.update (Function.update (Function.update (Function.update base + (tape 0) cursor) (tape 8) output) (tape 9) variableCounter) (tape 10) clauses + +theorem loopTapes_cursor (tape : Fin 11 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (cursor output variableCounter clauses : List Bool) : + loopTapes tape base cursor output variableCounter clauses (tape 0) = cursor := by + have hd (i j : Fin 11) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + simp [loopTapes, hd] + +theorem loopTapes_output (tape : Fin 11 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (cursor output variableCounter clauses : List Bool) : + loopTapes tape base cursor output variableCounter clauses (tape 8) = output := by + have hd (i j : Fin 11) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + simp [loopTapes, hd] + +theorem loopTapes_variables (tape : Fin 11 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (cursor output variableCounter clauses : List Bool) : + loopTapes tape base cursor output variableCounter clauses (tape 9) = variableCounter := by + have hd (i j : Fin 11) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + simp [loopTapes, hd] + +theorem loopTapes_clauses (tape : Fin 11 → K) + (base : K → List Bool) (cursor output variableCounter clauses : List Bool) : + loopTapes tape base cursor output variableCounter clauses (tape 10) = clauses := by + simp [loopTapes] + +private theorem update_cursor (tape : Fin 11 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (cursor output variableCounter clauses replacement : List Bool) : + Function.update (loopTapes tape base cursor output variableCounter clauses) (tape 0) replacement = + loopTapes tape base replacement output variableCounter clauses := by + have hd (i j : Fin 11) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + funext k + by_cases h : k = tape 0 + · subst k; simp [loopTapes, hd] + · simp [loopTapes, h, Function.update_apply] + +private theorem update_output (tape : Fin 11 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (cursor output variableCounter clauses replacement : List Bool) : + Function.update (loopTapes tape base cursor output variableCounter clauses) (tape 8) replacement = + loopTapes tape base cursor replacement variableCounter clauses := by + have hd (i j : Fin 11) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + funext k + by_cases h : k = tape 8 + · subst k; simp [loopTapes, hd] + · simp [loopTapes, h, Function.update_apply] + +theorem update_variables (tape : Fin 11 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (cursor output variableCounter clauses replacement : List Bool) : + Function.update (loopTapes tape base cursor output variableCounter clauses) (tape 9) replacement = + loopTapes tape base cursor output replacement clauses := by + have hd (i j : Fin 11) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + funext k + by_cases h : k = tape 9 + · subst k; simp [loopTapes, hd] + · simp [loopTapes, h, Function.update_apply] + +theorem update_clauses (tape : Fin 11 → K) + (base : K → List Bool) (cursor output variableCounter clauses replacement : List Bool) : + Function.update (loopTapes tape base cursor output variableCounter clauses) (tape 10) replacement = + loopTapes tape base cursor output variableCounter replacement := by + simp [loopTapes] + +theorem loopTapes_other (tape : Fin 11 → K) (base : K → List Bool) + (cursor output variableCounter clauses : List Bool) (k : K) + (h0 : k ≠ tape 0) (h8 : k ≠ tape 8) (h9 : k ≠ tape 9) (h10 : k ≠ tape 10) : + loopTapes tape base cursor output variableCounter clauses k = base k := by + simp [loopTapes, h0, h8, h9, h10] + +@[simp] theorem stepAux_finish (exit : Option Λ) (state : State A) (base : K → List Bool) : + TM2.stepAux (finish exit) state base = + ⟨exit, clean state.1.1.1.1 state.1.1.1.2, base⟩ := by + cases exit <;> rfl + +theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +variable (tape : Fin 11 → K) (distinct : Function.Injective tape) +variable (labels : Label → Λ) (done malformed : Option Λ) +variable (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) +variable (atLabels : ∀ l, program (labels l) = instruction tape labels done malformed l) +variable (base : K → List Bool) (ambient : A) + +include distinct atLabels + +theorem peekStep (slot : Fin 3) (head : Bool) (tail output variableCounter clauses : List Bool) : + TM2.step program + ⟨some (labels .entry), clean ambient slot, + loopTapes tape base (head :: tail) output variableCounter clauses⟩ = + some ⟨some (labels (.literal .readSign)), clean ambient slot, + loopTapes tape base (head :: tail) output variableCounter clauses⟩ := by + have hd (i j : Fin 11) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + change some (TM2.stepAux (program (labels .entry)) _ _) = _ + rw [atLabels .entry] + simp [instruction, TM2.stepAux, clean, BinaryLiteralMachine.clean, BinaryNameCompare.clean, + loopTapes_cursor tape distinct, update_cursor tape distinct] + +theorem emptyStep (slot : Fin 3) (output variableCounter clauses : List Bool) : + TM2.step program + ⟨some (labels .entry), clean ambient slot, + loopTapes tape base [] output variableCounter clauses⟩ = + some ⟨done, clean ambient slot, loopTapes tape base [] output variableCounter clauses⟩ := by + have hd (i j : Fin 11) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + change some (TM2.stepAux (program (labels .entry)) _ _) = _ + rw [atLabels .entry] + simp [instruction, TM2.stepAux, clean, BinaryLiteralMachine.clean, BinaryNameCompare.clean, + loopTapes_cursor tape distinct, update_cursor tape distinct] + +theorem tallyStep (slot : Fin 3) (cursor output variableCounter clauses : List Bool) : + TM2.step program + ⟨some (labels .tally), clean ambient slot, + loopTapes tape base cursor output variableCounter clauses⟩ = + some ⟨some (labels .entry), clean ambient (nextSlot slot), + loopTapes tape base cursor output (true :: variableCounter) + (List.replicate (clauseIncrement slot) true ++ clauses)⟩ := by + have hd (i j : Fin 11) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + change some (TM2.stepAux (program (labels .tally)) _ _) = _ + rw [atLabels .tally] + fin_cases slot <;> + simp [instruction, TM2.stepAux, clean, BinaryLiteralMachine.clean, BinaryNameCompare.clean, + next, nextSlot, clauseIncrement, loopTapes_variables tape distinct, loopTapes_clauses, + update_variables tape distinct, update_clauses] + +theorem bodyTrace (tokens : List Token) (token : Token) (slot : Fin 3) + (suffix output variableCounter clauses : List Bool) + (canonical : BinaryNameMachine.canonical token.2 = true) + (tokensCanonical : ∀ t ∈ tokens, BinaryNameMachine.canonical t.2 = true) + (present : token.2 ∈ BinaryNameSearch.payloads tokens) + (permanent : base (tape 1) = BinaryNameSearch.stream tokens) + (empty : ∀ i : Fin 11, 2 ≤ i.val → i.val ≤ 7 → base (tape i) = []) : + (advance (TM2.step program))^[BinaryLiteralMachine.steps tokens token.2 + 2] + (some ⟨some (labels .entry), clean ambient slot, + loopTapes tape base (BinaryNameSearch.tokenBits token ++ suffix) output variableCounter clauses⟩) = + some ⟨some (labels .entry), clean ambient (nextSlot slot), + loopTapes tape base suffix + ((BinaryLiteralMachine.outputWord tokens token.2 token.1).reverse ++ output) + (true :: variableCounter) (List.replicate (clauseIncrement slot) true ++ clauses)⟩ := by + have hd (i j : Fin 11) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + let initial := loopTapes tape base (BinaryNameSearch.tokenBits token ++ suffix) + output variableCounter clauses + have first : (advance (TM2.step program))^[1] + (some ⟨some (labels .entry), clean ambient slot, initial⟩) = + some ⟨some (labels (.literal .readSign)), clean ambient slot, initial⟩ := by + simpa only [Function.iterate_one, advance_some, initial, + BinaryNameSearch.tokenBits, List.cons_append] using + peekStep tape distinct labels done malformed program atLabels base ambient slot token.1 + (BinaryNameMachine.frame token.2 ++ suffix) output variableCounter clauses + have workEmpty (i : Fin 11) (lo : 2 ≤ i.val) (hi : i.val ≤ 7) : + initial (tape i) = [] := by + have h0 : i ≠ 0 := by intro h; subst i; omega + have h8 : i ≠ 8 := by intro h; subst i; omega + have h9 : i ≠ 9 := by intro h; subst i; omega + have h10 : i ≠ 10 := by intro h; subst i; omega + simpa [initial, loopTapes, hd i 0 h0, hd i 8 h8, hd i 9 h9, hd i 10 h10] + using empty i lo hi + have literal := BinaryLiteralMachine.literalTrace (literalTapes tape) + (literalTapes_injective tape distinct) (fun l => labels (.literal l)) + (some (labels .tally)) malformed program (fun l => atLabels (.literal l)) + initial tokens token.1 token.2 suffix canonical tokensCanonical present + (by simp [initial, literalTapes, loopTapes, BinaryNameSearch.tokenBits, hd]) + (by simpa [initial, literalTapes, loopTapes, hd] using permanent) + (fun i lo hi => workEmpty i.castSucc.castSucc lo hi) (ambient, slot) + have finalTapes : + Function.update (Function.update initial (literalTapes tape 0) suffix) + (literalTapes tape 8) + ((BinaryLiteralMachine.outputWord tokens token.2 token.1).reverse ++ + initial (literalTapes tape 8)) = + loopTapes tape base suffix + ((BinaryLiteralMachine.outputWord tokens token.2 token.1).reverse ++ output) + variableCounter clauses := by + have out : initial (literalTapes tape 8) = output := by + simp [initial, literalTapes, loopTapes, hd] + rw [out] + change Function.update (Function.update + (loopTapes tape base (BinaryNameSearch.tokenBits token ++ suffix) output variableCounter clauses) + (tape 0) suffix) (tape 8) _ = _ + rw [update_cursor tape distinct, update_output tape distinct] + rw [finalTapes] at literal + have tally : (advance (TM2.step program))^[1] + (some ⟨some (labels .tally), clean ambient slot, + loopTapes tape base suffix + ((BinaryLiteralMachine.outputWord tokens token.2 token.1).reverse ++ output) + variableCounter clauses⟩) = + some ⟨some (labels .entry), clean ambient (nextSlot slot), + loopTapes tape base suffix + ((BinaryLiteralMachine.outputWord tokens token.2 token.1).reverse ++ output) + (true :: variableCounter) (List.replicate (clauseIncrement slot) true ++ clauses)⟩ := by + simpa only [Function.iterate_one, advance_some] using + tallyStep tape distinct labels done malformed program atLabels base ambient slot suffix + ((BinaryLiteralMachine.outputWord tokens token.2 token.1).reverse ++ output) + variableCounter clauses + have full := joinTrace (joinTrace first literal) tally + simpa only [show 1 + BinaryLiteralMachine.steps tokens token.2 + 1 = + BinaryLiteralMachine.steps tokens token.2 + 2 by omega] using full + +theorem loopTrace (tokens input : List Token) (slot : Fin 3) + (output variableCounter clauses : List Bool) + (tokensCanonical : ∀ t ∈ tokens, BinaryNameMachine.canonical t.2 = true) + (included : ∀ t ∈ input, t ∈ tokens) + (permanent : base (tape 1) = BinaryNameSearch.stream tokens) + (empty : ∀ i : Fin 11, 2 ≤ i.val → i.val ≤ 7 → base (tape i) = []) : + (advance (TM2.step program))^[steps tokens input] + (some ⟨some (labels .entry), clean ambient slot, + loopTapes tape base (BinaryNameSearch.stream input) output variableCounter clauses⟩) = + some ⟨done, clean ambient (finalSlot input.length slot), + loopTapes tape base [] ((outputBody tokens input).reverse ++ output) + (List.replicate input.length true ++ variableCounter) + (List.replicate (completedClauses input.length slot) true ++ clauses)⟩ := by + induction input generalizing slot output variableCounter clauses with + | nil => + simpa only [steps, Function.iterate_one, advance_some, BinaryNameSearch.stream_nil, + List.length_nil, outputBody_nil, List.reverse_nil, List.nil_append, + finalSlot, completedClauses, List.replicate_zero] using + emptyStep tape distinct labels done malformed program atLabels base ambient + slot output variableCounter clauses + | cons token input ih => + have member := included token (by simp) + have present : token.2 ∈ BinaryNameSearch.payloads tokens := + List.mem_map.mpr ⟨token, member, rfl⟩ + have first := bodyTrace tape distinct labels done malformed program atLabels base ambient + tokens token slot (BinaryNameSearch.stream input) output variableCounter clauses + (tokensCanonical token member) tokensCanonical present permanent empty + have rest := ih (nextSlot slot) + ((BinaryLiteralMachine.outputWord tokens token.2 token.1).reverse ++ output) + (true :: variableCounter) (List.replicate (clauseIncrement slot) true ++ clauses) + (fun t ht => included t (by simp [ht])) + have full := joinTrace first rest + have variableEq : List.replicate input.length true ++ (true :: variableCounter) = + List.replicate (input.length + 1) true ++ variableCounter := by + rw [List.replicate_succ'] + simp only [List.append_assoc, List.singleton_append] + have clauseEq : List.replicate (completedClauses input.length (nextSlot slot)) true ++ + (List.replicate (clauseIncrement slot) true ++ clauses) = + List.replicate (completedClauses (input.length + 1) slot) true ++ clauses := by + rw [← List.append_assoc, ← List.replicate_add] + rfl + simpa only [steps, BinaryNameSearch.stream_cons, List.length_cons, finalSlot, + outputBody_cons, List.reverse_append, List.append_assoc, variableEq, clauseEq] using full + +theorem triplesTrace (tokens input : List Token) (count : Nat) + (length_eq : input.length = 3 * count) (output variableCounter clauses : List Bool) + (tokensCanonical : ∀ t ∈ tokens, BinaryNameMachine.canonical t.2 = true) + (included : ∀ t ∈ input, t ∈ tokens) + (permanent : base (tape 1) = BinaryNameSearch.stream tokens) + (empty : ∀ i : Fin 11, 2 ≤ i.val → i.val ≤ 7 → base (tape i) = []) : + (advance (TM2.step program))^[steps tokens input] + (some ⟨some (labels .entry), clean ambient 0, + loopTapes tape base (BinaryNameSearch.stream input) output variableCounter clauses⟩) = + some ⟨done, clean ambient 0, + loopTapes tape base [] ((outputBody tokens input).reverse ++ output) + (List.replicate (3 * count) true ++ variableCounter) + (List.replicate count true ++ clauses)⟩ := by + have h := loopTrace tape distinct labels done malformed program atLabels base ambient + tokens input 0 output variableCounter clauses tokensCanonical included permanent empty + simpa only [length_eq, finalSlot_triples, completedClauses_triples] using h + +def triplesInTime (tokens input : List Token) (count : Nat) + (length_eq : input.length = 3 * count) (output variableCounter clauses : List Bool) + (tokensCanonical : ∀ t ∈ tokens, BinaryNameMachine.canonical t.2 = true) + (included : ∀ t ∈ input, t ∈ tokens) + (permanent : base (tape 1) = BinaryNameSearch.stream tokens) + (empty : ∀ i : Fin 11, 2 ≤ i.val → i.val ≤ 7 → base (tape i) = []) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .entry), clean ambient 0, + loopTapes tape base (BinaryNameSearch.stream input) output variableCounter clauses⟩ + (some ⟨done, clean ambient 0, + loopTapes tape base [] ((outputBody tokens input).reverse ++ output) + (List.replicate (3 * count) true ++ variableCounter) + (List.replicate count true ++ clauses)⟩) + (perLiteralBound (BinaryNameSearch.stream tokens).length * input.length + 1) where + steps := steps tokens input + evals_in_steps := triplesTrace tape distinct labels done malformed program atLabels base ambient + tokens input count length_eq output variableCounter clauses tokensCanonical included permanent empty + steps_le_m := steps_le tokens input included + +end MinUncutGames.BinaryRenameLoop + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineBinaryNameMachine.lean b/lean/OAI/Computability/MinUncut/Machines/MachineBinaryNameMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..cfa6e8eed0587c97ad4291fba5c840adf9b05c4c --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineBinaryNameMachine.lean @@ -0,0 +1,787 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineFiniteAlphabet + +namespace OAI + +section +namespace MinUncutGames.BinaryNameMachine + +open Turing +open MinUncutGames.Foundations.Complexity +open MachineComposition +open MinUncutGames.Reduction.MachineTransfer + +def frame : List Bool → List Bool + | [] => [false] + | bit :: bits => true :: bit :: frame bits + +def finalDigit : List Bool → Option Bool → Option Bool + | [], previous => previous + | bit :: bits, _ => finalDigit bits (some bit) + +def canonical (bits : List Bool) : Bool := (finalDigit bits none).getD true + +structure Result where + accepted : Bool + remaining : List Bool + reversedPayload : List Bool + deriving DecidableEq + +def scanSpec : List Bool → List Bool → Option Bool → Result + | [], acc, _ => ⟨false, [], acc⟩ + | false :: rest, acc, last => ⟨last.getD true, rest, acc⟩ + | [true], acc, _ => ⟨false, [], acc⟩ + | true :: bit :: rest, acc, _ => scanSpec rest (bit :: acc) (some bit) + +def steps : List Bool → Nat + | true :: _ :: rest => steps rest + 1 + | _ => 1 + +theorem steps_le (input : List Bool) : steps input ≤ input.length + 1 := by + induction input using List.twoStepInduction with + | nil => simp [steps] + | singleton bit => cases bit <;> simp [steps] + | cons_cons flag bit rest ih _ => + cases flag <;> simp only [steps, List.length_cons] + · omega + · omega + +@[simp] theorem frame_length (bits : List Bool) : + (frame bits).length = 2 * bits.length + 1 := by + induction bits with + | nil => simp [frame] + | cons bit bits ih => simp only [frame, List.length_cons, ih]; omega + +theorem scanSpec_frame (bits suffix acc : List Bool) (last : Option Bool) : + scanSpec (frame bits ++ suffix) acc last = + ⟨(finalDigit bits last).getD true, suffix, bits.reverse ++ acc⟩ := by + induction bits generalizing acc last with + | nil => simp [frame, scanSpec, finalDigit] + | cons bit bits ih => + simpa [frame, scanSpec, finalDigit, List.reverse_cons, List.append_assoc] using + ih (bit :: acc) (some bit) + +@[simp] theorem steps_frame (bits suffix : List Bool) : + steps (frame bits ++ suffix) = bits.length + 1 := by + induction bits with + | nil => simp [frame, steps] + | cons bit bits ih => simp [frame, steps, ih] + +section Program + +variable {K Λ A : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool +abbrev State (A : Type) := A × Option Bool × Option Bool + +def clean (ambient : A) : State A := (ambient, none, none) + +def exitAt (exit : Option Λ) : TM2.Stmt (Alphabet (K := K)) Λ (State A) := + match exit with + | none => .halt + | some label => .goto fun _ => label + +def finish (exit : Option Λ) : TM2.Stmt (Alphabet (K := K)) Λ (State A) := + .load (fun state => clean state.1) (exitAt exit) + +def scan (source destination : K) (again : Λ) (accepted rejected : Option Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (State A) := + .pop source (fun state head => (state.1, state.2.1, head)) + (.branch (fun state => state.2.2.isNone) + (finish rejected) + (.branch (fun state => state.2.2.getD false) + (.pop source (fun state head => (state.1, state.2.1, head)) + (.branch (fun state => state.2.2.isSome) + (.push destination (fun state => state.2.2.getD false) + (.load (fun state => (state.1, state.2.2, none)) + (.goto fun _ => again))) + (finish rejected))) + (.branch (fun state => state.2.1.getD true) + (finish accepted) (finish rejected)))) + +@[simp] theorem stepAux_finish (exit : Option Λ) (state : State A) + (base : K → List Bool) : + TM2.stepAux (finish exit) state base = ⟨exit, clean state.1, base⟩ := by + cases exit <;> rfl + +private theorem update_source (source destination : K) (distinct : source ≠ destination) + (base : K → List Bool) (input output replacement : List Bool) : + Function.update (tapesAt source destination base input output) source replacement = + tapesAt source destination base replacement output := by + funext k + by_cases hs : k = source + · subst k; simp [tapesAt, distinct] + · by_cases hd : k = destination + · subst k; simp [tapesAt, Ne.symm distinct] + · simp [tapesAt, hs, hd] + +theorem update_destination (source destination : K) + (base : K → List Bool) (input output replacement : List Bool) : + Function.update (tapesAt source destination base input output) destination replacement = + tapesAt source destination base input replacement := by + simp [tapesAt] + +variable (source destination : K) (distinct : source ≠ destination) +variable (again : Λ) (accepted rejected : Option Λ) +variable (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) +variable (atScan : program again = scan source destination again accepted rejected) +variable (base : K → List Bool) (ambient : A) + +include distinct atScan + +theorem step_empty (output : List Bool) (last register : Option Bool) : + TM2.step program + ⟨some again, (ambient, last, register), tapesAt source destination base [] output⟩ = + some ⟨rejected, clean ambient, tapesAt source destination base [] output⟩ := by + change some (TM2.stepAux (program again) _ _) = _ + rw [atScan] + simp [scan, TM2.stepAux, distinct, update_source] + +theorem step_end (rest output : List Bool) (last register : Option Bool) : + TM2.step program + ⟨some again, (ambient, last, register), + tapesAt source destination base (false :: rest) output⟩ = + some ⟨if last.getD true then accepted else rejected, clean ambient, + tapesAt source destination base rest output⟩ := by + change some (TM2.stepAux (program again) _ _) = _ + rw [atScan] + cases h : last.getD true <;> + simp [scan, TM2.stepAux, distinct, update_source, h] + +theorem step_truncated (output : List Bool) (last register : Option Bool) : + TM2.step program + ⟨some again, (ambient, last, register), tapesAt source destination base [true] output⟩ = + some ⟨rejected, clean ambient, tapesAt source destination base [] output⟩ := by + change some (TM2.stepAux (program again) _ _) = _ + rw [atScan] + simp [scan, TM2.stepAux, distinct, update_source] + +theorem step_digit (bit : Bool) (rest output : List Bool) (last register : Option Bool) : + TM2.step program + ⟨some again, (ambient, last, register), + tapesAt source destination base (true :: bit :: rest) output⟩ = + some ⟨some again, (ambient, some bit, none), + tapesAt source destination base rest (bit :: output)⟩ := by + change some (TM2.stepAux (program again) _ _) = _ + rw [atScan] + simp [scan, TM2.stepAux, distinct, update_source, update_destination] + +theorem scanTrace (input output : List Bool) (last register : Option Bool) : + (advance (TM2.step program))^[steps input] + (some ⟨some again, (ambient, last, register), + tapesAt source destination base input output⟩) = + some ⟨if (scanSpec input output last).accepted then accepted else rejected, + clean ambient, tapesAt source destination base + (scanSpec input output last).remaining (scanSpec input output last).reversedPayload⟩ := by + induction input using List.twoStepInduction generalizing output last register with + | nil => + simpa only [steps, scanSpec, Bool.false_eq_true, ite_false, + Function.iterate_one, advance_some] using + step_empty source destination distinct again accepted rejected program atScan base ambient + output last register + | singleton flag => + cases flag + · have h := step_end source destination distinct again accepted rejected program atScan + base ambient [] output last register + cases hlast : last.getD true <;> + simpa [steps, scanSpec, hlast] using h + · simpa only [steps, scanSpec, Bool.false_eq_true, ite_false, + Function.iterate_one, advance_some] using + step_truncated source destination distinct again accepted rejected program atScan base ambient + output last register + | cons_cons flag bit rest ih _ => + cases flag + · have h := step_end source destination distinct again accepted rejected program atScan + base ambient (bit :: rest) output last register + cases hlast : last.getD true <;> + simpa [steps, scanSpec, hlast] using h + · rw [steps, Function.iterate_succ_apply] + simp only [advance_some] + rw [step_digit source destination distinct again accepted rejected program atScan] + exact ih (bit :: output) (some bit) none + +def scanInTime (input output : List Bool) (last register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some again, (ambient, last, register), tapesAt source destination base input output⟩ + (some ⟨if (scanSpec input output last).accepted then accepted else rejected, + clean ambient, tapesAt source destination base + (scanSpec input output last).remaining (scanSpec input output last).reversedPayload⟩) + (input.length + 1) where + steps := steps input + evals_in_steps := scanTrace source destination distinct again accepted rejected program atScan + base ambient input output last register + steps_le_m := steps_le input + +theorem framedTrace (bits suffix output : List Bool) (register : Option Bool) : + (advance (TM2.step program))^[bits.length + 1] + (some ⟨some again, (ambient, none, register), + tapesAt source destination base (frame bits ++ suffix) output⟩) = + some ⟨if canonical bits then accepted else rejected, clean ambient, + tapesAt source destination base suffix (bits.reverse ++ output)⟩ := by + have h := scanTrace source destination distinct again accepted rejected program atScan + base ambient (frame bits ++ suffix) output none register + cases hlast : (finalDigit bits none).getD true <;> + simpa [steps_frame, scanSpec_frame, canonical, hlast] using h + +end Program + +def machine : FinTM2 where + K := Bool + k₀ := false + k₁ := true + Γ _ := Bool + Λ := Fin 3 + main := 0 + σ := State Unit + initialState := clean () + m label := if label = 0 then scan false true 0 (some 1) (some 2) else .halt + +theorem machine_finiteAlphabet (k : machine.K) : Finite (machine.Γ k) := by + change Finite Bool + infer_instance + +def machineInTime (input output : List Bool) : + StateTransition.EvalsToInTime machine.step + ⟨some (0 : Fin 3), clean (), tapesAt false true (fun _ : Bool => []) input output⟩ + (some ⟨if (scanSpec input output none).accepted then some (1 : Fin 3) else some (2 : Fin 3), + clean (), tapesAt false true (fun _ : Bool => []) + (scanSpec input output none).remaining (scanSpec input output none).reversedPayload⟩) + (input.length + 1) := + scanInTime false true (by decide) (0 : Fin 3) (some 1) (some 2) machine.m + (by simp [machine]) (fun _ : Bool => []) () input output none none + +end MinUncutGames.BinaryNameMachine + +end +section +namespace MinUncutGames.BinaryNameCompare + +open Turing +open MinUncutGames.Foundations.Complexity +open MachineComposition + +variable {K Λ A : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool +abbrev State (A : Type) := (A × Bool × Option Bool) × Option Bool + +def clean (ambient : A) : State A := ((ambient, false, none), none) + +def scanStateEquiv (A : Type) : BinaryNameMachine.State (A × Bool) ≃ State A where + toFun s := ((s.1.1, s.1.2, s.2.1), s.2.2) + invFun s := ((s.1.1, s.1.2.1), s.1.2.2, s.2) + left_inv := by rintro ⟨⟨a, b⟩, c, d⟩; rfl + right_inv := by rintro ⟨⟨a, b, c⟩, d⟩; rfl + +def compareStateEquiv (A : Type) : MachineCompare.State A ≃ State A where + toFun s := ((s.1, s.2.1, s.2.2.1), s.2.2.2) + invFun s := (s.1.1, s.1.2.1, s.1.2.2, s.2) + left_inv := by rintro ⟨a, b, c, d⟩; rfl + right_inv := by rintro ⟨⟨a, b, c⟩, d⟩; rfl + +inductive Label + | scan | copyOut | copyBack | compare + deriving DecidableEq + +protected abbrev Label.enumList : List Label := [.scan, .copyOut, .copyBack, .compare] + +protected theorem Label.enumList_getElem?_ctorIdx_eq (x : Label) : + Label.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem Label.enumList_nodup : Label.enumList.Nodup := by decide + +instance : Fintype Label where + elems := ⟨Label.enumList, Label.enumList_nodup⟩ + complete x := by cases x <;> decide + +def instruction (tape : Fin 5 → K) (labels : Label → Λ) + (equalExit differentExit malformedExit : Option Λ) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (State A) + | .scan => MachineStateEquiv.statement (scanStateEquiv A) + (BinaryNameMachine.scan (tape 0) (tape 2) (labels .scan) + (some (labels .copyOut)) malformedExit) + | .copyOut => MinUncutGames.Reduction.MachineTransfer.loopAt (tape 1) (tape 4) id false + (labels .copyOut) (some (labels .copyBack)) + | .copyBack => MachineCopy.forkLoop (tape 4) (tape 1) (tape 3) false + (labels .copyBack) (some (labels .compare)) + | .compare => MachineStateEquiv.statement (compareStateEquiv A) + (MachineCompare.loop (tape 2) (tape 3) (labels .compare) equalExit differentExit) + +def steps (payloadLength keyLength : Nat) : Nat := + (payloadLength + 1) + 2 * (keyLength + 1) + (max payloadLength keyLength + 1) + +theorem steps_le (payloadLength keyLength : Nat) : + steps payloadLength keyLength ≤ 2 * payloadLength + 3 * keyLength + 4 := by + unfold steps + omega + +theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +theorem compareTrace (tape : Fin 5 → K) (distinct : Function.Injective tape) + (labels : Label → Λ) (equalExit differentExit malformedExit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ l, program (labels l) = + instruction tape labels equalExit differentExit malformedExit l) + (base : K → List Bool) (bits suffix key : List Bool) + (canonical : BinaryNameMachine.canonical bits = true) + (sourceWord : base (tape 0) = BinaryNameMachine.frame bits ++ suffix) + (keyWord : base (tape 1) = key) + (candidateEmpty : base (tape 2) = []) (copyEmpty : base (tape 3) = []) + (scratchEmpty : base (tape 4) = []) (ambient : A) : + (advance (TM2.step program))^[steps bits.length key.length] + (some ⟨some (labels .scan), clean ambient, base⟩) = + some ⟨if bits.reverse = key then equalExit else differentExit, + clean ambient, Function.update base (tape 0) suffix⟩ := by + have hd (i j : Fin 5) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + let finalBase := Function.update base (tape 0) suffix + let afterScan := Function.update finalBase (tape 2) bits.reverse + let afterCopy := Function.update afterScan (tape 3) key + have scanRun : (advance (TM2.step program))^[bits.length + 1] + (some ⟨some (labels .scan), clean ambient, base⟩) = + some ⟨some (labels .copyOut), clean ambient, afterScan⟩ := by + let back := MachineStateEquiv.program (scanStateEquiv A).symm program + have atScan : back (labels .scan) = + BinaryNameMachine.scan (tape 0) (tape 2) (labels .scan) + (some (labels .copyOut)) malformedExit := by + change MachineStateEquiv.statement (scanStateEquiv A).symm + (program (labels .scan)) = _ + rw [atLabels .scan] + exact MachineStateEquiv.statement_symm_statement (scanStateEquiv A) _ + have backForward : MachineStateEquiv.program (scanStateEquiv A) back = program := by + funext l + change MachineStateEquiv.statement (scanStateEquiv A) + (MachineStateEquiv.statement (scanStateEquiv A).symm (program l)) = _ + simpa only [Equiv.symm_symm] using + MachineStateEquiv.statement_symm_statement (scanStateEquiv A).symm (program l) + have initialTapes : MinUncutGames.Reduction.MachineTransfer.tapesAt (tape 0) (tape 2) + base (BinaryNameMachine.frame bits ++ suffix) [] = base := by + rw [← sourceWord, ← candidateEmpty] + exact MinUncutGames.Reduction.MachineTransfer.tapesAt_self _ _ _ + have native := BinaryNameMachine.framedTrace (tape 0) (tape 2) (hd 0 2 (by decide)) + (labels .scan) (some (labels .copyOut)) malformedExit back atScan base (ambient, false) + bits suffix [] none + simp only [canonical, ↓reduceIte, initialTapes, List.append_nil] at native + have transported := MachineStateEquiv.trace (scanStateEquiv A) back _ _ _ native + rw [backForward] at transported + simpa only [MachineStateEquiv.configuration, scanStateEquiv, Equiv.coe_fn_mk, BinaryNameMachine.clean, + clean, afterScan, finalBase, MinUncutGames.Reduction.MachineTransfer.tapesAt] using transported + have afterScanKey : afterScan (tape 1) = key := by + simpa [afterScan, finalBase, hd 1 2 (by decide), hd 1 0 (by decide)] using keyWord + have afterScanCopy : afterScan (tape 3) = [] := by + simpa [afterScan, finalBase, hd 3 2 (by decide), hd 3 0 (by decide)] using copyEmpty + have afterScanScratch : afterScan (tape 4) = [] := by + simpa [afterScan, finalBase, hd 4 2 (by decide), hd 4 0 (by decide)] using scratchEmpty + have copyRun : (advance (TM2.step program))^[2 * (key.length + 1)] + (some ⟨some (labels .copyOut), clean ambient, afterScan⟩) = + some ⟨some (labels .compare), clean ambient, afterCopy⟩ := by + have h := MachineCopy.copyTrace (tape 1) (tape 3) (tape 4) + (hd 1 3 (by decide)) (hd 1 4 (by decide)) (hd 3 4 (by decide)) false + (labels .copyOut) (labels .copyBack) (some (labels .compare)) program + (atLabels .copyOut) (atLabels .copyBack) afterScan afterScanScratch + (ambient, false, none) none + simpa only [afterScanKey, afterScanCopy, List.append_nil, clean, afterCopy] using h + have candidateWord : afterCopy (tape 2) = bits.reverse := by + simp [afterCopy, afterScan, hd 2 3 (by decide)] + have copiedWord : afterCopy (tape 3) = key := by simp [afterCopy] + have restored : MinUncutGames.Reduction.MachineTransfer.tapesAt (tape 2) (tape 3) + afterCopy [] [] = finalBase := by + funext k + by_cases hc : k = tape 2 + · subst k + simp [MinUncutGames.Reduction.MachineTransfer.tapesAt, afterCopy, afterScan, finalBase, + hd 2 3 (by decide), hd 2 0 (by decide), candidateEmpty] + · by_cases hk : k = tape 3 + · subst k + simp [MinUncutGames.Reduction.MachineTransfer.tapesAt, afterCopy, afterScan, finalBase, + hd 3 0 (by decide), copyEmpty] + · simp [MinUncutGames.Reduction.MachineTransfer.tapesAt, afterCopy, afterScan, hc, hk] + have comparisonRun : (advance (TM2.step program))^[max bits.length key.length + 1] + (some ⟨some (labels .compare), clean ambient, afterCopy⟩) = + some ⟨if bits.reverse = key then equalExit else differentExit, + clean ambient, finalBase⟩ := by + let back := MachineStateEquiv.program (compareStateEquiv A).symm program + have atCompare : back (labels .compare) = + MachineCompare.loop (tape 2) (tape 3) (labels .compare) equalExit differentExit := by + change MachineStateEquiv.statement (compareStateEquiv A).symm + (program (labels .compare)) = _ + rw [atLabels .compare] + exact MachineStateEquiv.statement_symm_statement (compareStateEquiv A) _ + have backForward : MachineStateEquiv.program (compareStateEquiv A) back = program := by + funext l + change MachineStateEquiv.statement (compareStateEquiv A) + (MachineStateEquiv.statement (compareStateEquiv A).symm (program l)) = _ + simpa only [Equiv.symm_symm] using + MachineStateEquiv.statement_symm_statement (compareStateEquiv A).symm (program l) + have native := MachineCompare.compareTrace_fromTapes (tape 2) (tape 3) + (hd 2 3 (by decide)) (labels .compare) equalExit differentExit back atCompare afterCopy + ambient none none + rw [candidateWord, copiedWord, restored, List.length_reverse] at native + have transported := MachineStateEquiv.trace (compareStateEquiv A) back _ _ _ native + rw [backForward] at transported + simpa only [MachineStateEquiv.configuration, compareStateEquiv, Equiv.coe_fn_mk, clean] using transported + exact joinTrace (joinTrace scanRun copyRun) comparisonRun + +def compareInTime (tape : Fin 5 → K) (distinct : Function.Injective tape) + (labels : Label → Λ) (equalExit differentExit malformedExit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ l, program (labels l) = + instruction tape labels equalExit differentExit malformedExit l) + (base : K → List Bool) (bits suffix key : List Bool) + (canonical : BinaryNameMachine.canonical bits = true) + (sourceWord : base (tape 0) = BinaryNameMachine.frame bits ++ suffix) + (keyWord : base (tape 1) = key) + (candidateEmpty : base (tape 2) = []) (copyEmpty : base (tape 3) = []) + (scratchEmpty : base (tape 4) = []) (ambient : A) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .scan), clean ambient, base⟩ + (some ⟨if bits.reverse = key then equalExit else differentExit, + clean ambient, Function.update base (tape 0) suffix⟩) + (2 * bits.length + 3 * key.length + 4) where + steps := steps bits.length key.length + evals_in_steps := compareTrace tape distinct labels equalExit differentExit malformedExit + program atLabels base bits suffix key canonical sourceWord keyWord + candidateEmpty copyEmpty scratchEmpty ambient + steps_le_m := steps_le bits.length key.length + +def machine : FinTM2 where + K := Fin 5 + k₀ := 0 + k₁ := 1 + Γ _ := Bool + Λ := Label ⊕ Fin 3 + main := .inl .scan + σ := State Unit + initialState := clean () + m label := match label with + | .inl l => instruction id Sum.inl (some (.inr 0)) (some (.inr 1)) (some (.inr 2)) l + | .inr _ => .halt + +theorem machine_finiteAlphabet (k : machine.K) : Finite (machine.Γ k) := by + change Finite Bool + infer_instance + +end MinUncutGames.BinaryNameCompare + +end +section +namespace MinUncutGames.BinaryNameSearch + +open Turing +open MinUncutGames.Foundations.Complexity +open MachineComposition +open MinUncutGames.Reduction.MachineTransfer + +abbrev Token := Bool × List Bool + +def tokenBits (token : Token) : List Bool := + token.1 :: BinaryNameMachine.frame token.2 + +def stream : List Token → List Bool + | [] => [] + | token :: tokens => tokenBits token ++ stream tokens + +def payloads (tokens : List Token) : List (List Bool) := tokens.map Prod.snd + +def afterMatch : List Token → List Bool → List Token + | [], _ => [] + | token :: tokens, key => if token.2 = key then tokens else afterMatch tokens key + +def steps : List Token → List Bool → Nat + | [], _ => 0 + | token :: tokens, key => + 1 + BinaryNameCompare.steps token.2.length key.length + + if token.2 = key then 0 else 1 + steps tokens key + +def payloadSize (tokens : List Token) : Nat := (payloads tokens |>.map List.length).sum + +@[simp] theorem stream_nil : stream [] = [] := rfl + +@[simp] theorem stream_cons (token : Token) (tokens : List Token) : + stream (token :: tokens) = tokenBits token ++ stream tokens := rfl + +@[simp] theorem payloads_nil : payloads [] = [] := rfl + +@[simp] theorem payloads_cons (token : Token) (tokens : List Token) : + payloads (token :: tokens) = token.2 :: payloads tokens := rfl + +@[simp] theorem payloadSize_nil : payloadSize [] = 0 := rfl + +@[simp] theorem payloadSize_cons (token : Token) (tokens : List Token) : + payloadSize (token :: tokens) = token.2.length + payloadSize tokens := rfl + +@[simp] theorem stream_length (tokens : List Token) : + (stream tokens).length = 2 * payloadSize tokens + 2 * tokens.length := by + induction tokens with + | nil => rfl + | cons token tokens ih => + simp only [stream_cons, List.length_append, tokenBits, List.length_cons, + BinaryNameMachine.frame_length, ih, payloadSize_cons] + omega + +theorem steps_le (tokens : List Token) (key : List Bool) : + steps tokens key ≤ 2 * payloadSize tokens + (3 * key.length + 6) * tokens.length := by + induction tokens with + | nil => simp [steps] + | cons token tokens ih => + have h := BinaryNameCompare.steps_le token.2.length key.length + simp only [steps, payloadSize_cons, List.length_cons] + split <;> nlinarith + +theorem steps_le_stream (tokens : List Token) (key : List Bool) : + steps tokens key ≤ (3 * key.length + 7) * (stream tokens).length := by + have h := steps_le tokens key + rw [stream_length] + nlinarith + +section Program + +variable {K Λ A : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool +abbrev State (A : Type) := BinaryNameCompare.State A + +abbrev clean (ambient : A) : State A := BinaryNameCompare.clean ambient + +inductive Label + | sign + | comparison (label : BinaryNameCompare.Label) + | increment + deriving DecidableEq, Fintype + +def compareTapes (tape : Fin 6 → K) : Fin 5 → K := fun i => tape i.castSucc + +omit [DecidableEq K] in +theorem compareTapes_injective (tape : Fin 6 → K) (distinct : Function.Injective tape) : + Function.Injective (compareTapes tape) := by + intro i j h + apply Fin.ext + exact congrArg (fun i : Fin 6 => i.val) (distinct h) + +def exitAt (exit : Option Λ) : TM2.Stmt (Alphabet (K := K)) Λ (State A) := + match exit with + | none => .halt + | some label => .goto fun _ => label + +def finish (exit : Option Λ) : TM2.Stmt (Alphabet (K := K)) Λ (State A) := + .load (fun state => clean state.1.1) (exitAt exit) + +def instruction (tape : Fin 6 → K) (labels : Label → Λ) + (foundExit missingExit malformedExit : Option Λ) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (State A) + | .sign => + .pop (tape 0) (fun state head => (state.1, head)) + (.branch (fun state => state.2.isSome) + (finish (some (labels (.comparison .scan)))) (finish missingExit)) + | .comparison l => BinaryNameCompare.instruction (compareTapes tape) + (fun l => labels (.comparison l)) foundExit (some (labels .increment)) malformedExit l + | .increment => .push (tape 5) (fun _ => true) (.goto fun _ => labels .sign) + +@[simp] theorem stepAux_finish (exit : Option Λ) (state : State A) (base : K → List Bool) : + TM2.stepAux (finish exit) state base = ⟨exit, clean state.1.1, base⟩ := by + cases exit <;> rfl + +private theorem update_source (source counter : K) (distinct : source ≠ counter) + (base : K → List Bool) (input count replacement : List Bool) : + Function.update (tapesAt source counter base input count) source replacement = + tapesAt source counter base replacement count := by + funext k + by_cases hs : k = source + · subst k; simp [tapesAt, distinct] + · by_cases hc : k = counter + · subst k; simp [tapesAt, Ne.symm distinct] + · simp [tapesAt, hs, hc] + +private theorem update_counter (source counter : K) + (base : K → List Bool) (input count replacement : List Bool) : + Function.update (tapesAt source counter base input count) counter replacement = + tapesAt source counter base input replacement := by + simp [tapesAt] + +theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +variable (tape : Fin 6 → K) (distinct : Function.Injective tape) +variable (labels : Label → Λ) (foundExit missingExit malformedExit : Option Λ) +variable (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) +variable (atLabels : ∀ l, program (labels l) = + instruction tape labels foundExit missingExit malformedExit l) +variable (base : K → List Bool) (ambient : A) + +include distinct atLabels + +theorem signStep (sign : Bool) (input counter : List Bool) : + TM2.step program + ⟨some (labels .sign), clean ambient, + tapesAt (tape 0) (tape 5) base (sign :: input) counter⟩ = + some ⟨some (labels (.comparison .scan)), clean ambient, + tapesAt (tape 0) (tape 5) base input counter⟩ := by + have hd : tape 0 ≠ tape 5 := fun h => (by decide : (0 : Fin 6) ≠ 5) (distinct h) + change some (TM2.stepAux (program (labels .sign)) _ _) = _ + rw [atLabels .sign] + simp [instruction, TM2.stepAux, clean, BinaryNameCompare.clean, hd, update_source] + +theorem emptyStep (counter : List Bool) : + TM2.step program + ⟨some (labels .sign), clean ambient, + tapesAt (tape 0) (tape 5) base [] counter⟩ = + some ⟨missingExit, clean ambient, tapesAt (tape 0) (tape 5) base [] counter⟩ := by + have hd : tape 0 ≠ tape 5 := fun h => (by decide : (0 : Fin 6) ≠ 5) (distinct h) + change some (TM2.stepAux (program (labels .sign)) _ _) = _ + rw [atLabels .sign] + simp [instruction, TM2.stepAux, clean, BinaryNameCompare.clean, hd, update_source] + +omit distinct in +theorem incrementStep (input counter : List Bool) : + TM2.step program + ⟨some (labels .increment), clean ambient, + tapesAt (tape 0) (tape 5) base input counter⟩ = + some ⟨some (labels .sign), clean ambient, + tapesAt (tape 0) (tape 5) base input (true :: counter)⟩ := by + change some (TM2.stepAux (program (labels .increment)) _ _) = _ + rw [atLabels .increment] + simp [instruction, TM2.stepAux, update_counter] + +theorem tokenTrace (token : Token) (key suffix counter : List Bool) + (canonical : BinaryNameMachine.canonical token.2 = true) + (keyWord : base (tape 1) = key.reverse) + (candidateEmpty : base (tape 2) = []) (copyEmpty : base (tape 3) = []) + (scratchEmpty : base (tape 4) = []) : + (advance (TM2.step program))^[1 + BinaryNameCompare.steps token.2.length key.length] + (some ⟨some (labels .sign), clean ambient, + tapesAt (tape 0) (tape 5) base (tokenBits token ++ suffix) counter⟩) = + some ⟨if token.2 = key then foundExit else some (labels .increment), clean ambient, + tapesAt (tape 0) (tape 5) base suffix counter⟩ := by + have hd (i j : Fin 6) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + let initial := tapesAt (tape 0) (tape 5) base + (BinaryNameMachine.frame token.2 ++ suffix) counter + have first : (advance (TM2.step program))^[1] + (some ⟨some (labels .sign), clean ambient, + tapesAt (tape 0) (tape 5) base (tokenBits token ++ suffix) counter⟩) = + some ⟨some (labels (.comparison .scan)), clean ambient, initial⟩ := by + simpa only [Function.iterate_one, advance_some, tokenBits, List.cons_append] using + signStep tape distinct labels foundExit missingExit malformedExit program atLabels + base ambient token.1 (BinaryNameMachine.frame token.2 ++ suffix) counter + have second := BinaryNameCompare.compareTrace (compareTapes tape) + (compareTapes_injective tape distinct) (fun l => labels (.comparison l)) + foundExit (some (labels .increment)) malformedExit program + (fun l => atLabels (.comparison l)) initial token.2 suffix key.reverse canonical + (by simp [initial, compareTapes, hd 0 5 (by decide)]) + (by simpa [initial, compareTapes, tapesAt, + hd 1 0 (by decide), hd 1 5 (by decide)] using keyWord) + (by simpa [initial, compareTapes, tapesAt, hd 2 0 (by decide), hd 2 5 (by decide)] + using candidateEmpty) + (by simpa [initial, compareTapes, tapesAt, + hd 3 0 (by decide), hd 3 5 (by decide)] using copyEmpty) + (by simpa [initial, compareTapes, tapesAt, + hd 4 0 (by decide), hd 4 5 (by decide)] using scratchEmpty) + ambient + have heq : token.2.reverse = key.reverse ↔ token.2 = key := by + constructor + · intro h + have := congrArg List.reverse h + simpa only [List.reverse_reverse] using this + · intro h; rw [h] + simp only [List.length_reverse, heq] at second + rw [show Function.update initial (compareTapes tape 0) suffix = + tapesAt (tape 0) (tape 5) base suffix counter by + exact update_source _ _ (hd 0 5 (by decide)) base _ counter suffix] at second + exact joinTrace first second + +theorem searchTrace (tokens : List Token) (key suffix counter : List Bool) + (canonical : ∀ token ∈ tokens, BinaryNameMachine.canonical token.2 = true) + (present : key ∈ payloads tokens) + (keyWord : base (tape 1) = key.reverse) + (candidateEmpty : base (tape 2) = []) (copyEmpty : base (tape 3) = []) + (scratchEmpty : base (tape 4) = []) : + (advance (TM2.step program))^[steps tokens key] + (some ⟨some (labels .sign), clean ambient, + tapesAt (tape 0) (tape 5) base (stream tokens ++ suffix) counter⟩) = + some ⟨foundExit, clean ambient, + tapesAt (tape 0) (tape 5) base (stream (afterMatch tokens key) ++ suffix) + (List.replicate ((payloads tokens).idxOf key) true ++ counter)⟩ := by + induction tokens generalizing counter with + | nil => simp at present + | cons token tokens ih => + have headCanonical := canonical token (by simp) + have tailCanonical : ∀ t ∈ tokens, BinaryNameMachine.canonical t.2 = true := + fun t ht => canonical t (by simp [ht]) + have first := tokenTrace tape distinct labels foundExit missingExit malformedExit + program atLabels base ambient token key (stream tokens ++ suffix) counter + headCanonical keyWord candidateEmpty copyEmpty scratchEmpty + by_cases same : token.2 = key + · simpa only [steps, same, ite_true, Nat.add_zero, stream_cons, + List.append_assoc, afterMatch, payloads_cons, List.idxOf_cons_self, + List.replicate_zero, List.nil_append] using first + · have remaining : key ∈ payloads tokens := by + rcases List.mem_cons.mp present with equal | remaining + · exact False.elim (same equal.symm) + · exact remaining + have increment : (advance (TM2.step program))^[1] + (some ⟨some (labels .increment), clean ambient, + tapesAt (tape 0) (tape 5) base (stream tokens ++ suffix) counter⟩) = + some ⟨some (labels .sign), clean ambient, + tapesAt (tape 0) (tape 5) base (stream tokens ++ suffix) (true :: counter)⟩ := by + simpa only [Function.iterate_one, advance_some] using + incrementStep tape labels foundExit missingExit malformedExit program + atLabels base ambient (stream tokens ++ suffix) counter + have rest := ih (true :: counter) tailCanonical remaining + simp only [same, ite_false] at first + have full := joinTrace first (joinTrace increment rest) + have counterEq : List.replicate ((payloads tokens).idxOf key) true ++ + (true :: counter) = + List.replicate ((payloads tokens).idxOf key + 1) true ++ counter := by + rw [List.replicate_succ'] + simp only [List.append_assoc, List.singleton_append] + have indexEq : (token.2 :: payloads tokens).idxOf key = + (payloads tokens).idxOf key + 1 := by + exact List.idxOf_cons_ne _ same + simpa only [steps, same, ite_false, stream_cons, List.append_assoc, afterMatch, + payloads_cons, indexEq, counterEq] using full + +def searchInTime (tokens : List Token) (key suffix counter : List Bool) + (canonical : ∀ token ∈ tokens, BinaryNameMachine.canonical token.2 = true) + (present : key ∈ payloads tokens) + (keyWord : base (tape 1) = key.reverse) + (candidateEmpty : base (tape 2) = []) (copyEmpty : base (tape 3) = []) + (scratchEmpty : base (tape 4) = []) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .sign), clean ambient, + tapesAt (tape 0) (tape 5) base (stream tokens ++ suffix) counter⟩ + (some ⟨foundExit, clean ambient, + tapesAt (tape 0) (tape 5) base (stream (afterMatch tokens key) ++ suffix) + (List.replicate ((payloads tokens).idxOf key) true ++ counter)⟩) + ((3 * key.length + 7) * (stream tokens).length) where + steps := steps tokens key + evals_in_steps := searchTrace tape distinct labels foundExit missingExit malformedExit + program atLabels base ambient tokens key suffix counter canonical present keyWord + candidateEmpty copyEmpty scratchEmpty + steps_le_m := steps_le_stream tokens key + +end Program + +def machine : FinTM2 where + K := Fin 6 + k₀ := 0 + k₁ := 5 + Γ _ := Bool + Λ := Label ⊕ Fin 3 + main := .inl .sign + σ := State Unit + initialState := clean () + m label := match label with + | .inl l => instruction id Sum.inl (some (.inr 0)) (some (.inr 1)) (some (.inr 2)) l + | .inr _ => .halt + +theorem machine_finiteAlphabet (k : machine.K) : Finite (machine.Γ k) := by + change Finite Bool + infer_instance + +end MinUncutGames.BinaryNameSearch + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineBinaryOccurrenceRename.lean b/lean/OAI/Computability/MinUncut/Machines/MachineBinaryOccurrenceRename.lean new file mode 100644 index 0000000000000000000000000000000000000000..1c509863fae7c1bfea0055e1b0bf0d73580d7bfc --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineBinaryOccurrenceRename.lean @@ -0,0 +1,122 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineBinaryFormula + +namespace OAI + +section +namespace MinUncutGames.BinaryOccurrenceRename + +open BinaryFormula MinUncutGames.Foundations + +theorem literal_mem_names (F : Formula) (c : Clause) (hc : c ∈ F.clauses) + (i : Fin 3) : (c)[i].name ∈ sourceNames F := by + apply List.mem_flatMap.mpr + refine ⟨c, hc, ?_⟩ + have hi : i = 0 ∨ i = 1 ∨ i = 2 := by omega + rcases hi with rfl | rfl | rfl <;> simp [clauseNames] + +def nameIndex (F : Formula) (name : Nat) (mem : name ∈ sourceNames F) : + Fin (sourceNames F).length := + ⟨(sourceNames F).idxOf name, List.idxOf_lt_length_of_mem mem⟩ + +def literal (F : Formula) (l : Literal) (mem : l.name ∈ sourceNames F) : + Target.Literal (sourceNames F).length := + ⟨nameIndex F l.name mem, l.positive⟩ + +def clause (F : Formula) (c : Clause) (mem : c ∈ F.clauses) : + Target.Clause (sourceNames F).length := + #v[literal F (c)[0] (literal_mem_names F c mem 0), + literal F (c)[1] (literal_mem_names F c mem 1), + literal F (c)[2] (literal_mem_names F c mem 2)] + +def renamed (F : Formula) : Target.Formula where + «variables» := (sourceNames F).length + clauses := F.clauses.attach.map (fun c => clause F c.val c.property) + +def restrictAssignment (F : Formula) (A : Nat → Bool) : + Fin (sourceNames F).length → Bool := + fun i => A (sourceNames F)[i.val] + +def extendAssignment (F : Formula) (A : Fin (sourceNames F).length → Bool) : Nat → Bool := + fun name => if mem : name ∈ sourceNames F then A (nameIndex F name mem) else false + +@[simp] theorem nameIndex_reads_name (F : Formula) (name : Nat) + (mem : name ∈ sourceNames F) : (sourceNames F)[(nameIndex F name mem).val] = name := + List.getElem_idxOf _ + +@[simp] theorem clause_eval_restrict (F : Formula) (c : Clause) (mem : c ∈ F.clauses) + (A : Nat → Bool) : (clause F c mem).eval (restrictAssignment F A) = c.eval A := by + simp [clause, literal, Target.Clause.eval, Target.Literal.eval, + BinaryFormula.Clause.eval, BinaryFormula.Literal.eval, restrictAssignment] + +@[simp] theorem clause_eval_extend (F : Formula) (c : Clause) (mem : c ∈ F.clauses) + (A : Fin (sourceNames F).length → Bool) : + (clause F c mem).eval A = c.eval (extendAssignment F A) := by + have evalLiteral (l : Literal) (hl : l.name ∈ sourceNames F) : + (literal F l hl).eval A = l.eval (extendAssignment F A) := by + simp only [literal, Target.Literal.eval, BinaryFormula.Literal.eval, + extendAssignment, dite_eq_left hl] + rfl + simp [clause, Target.Clause.eval, BinaryFormula.Clause.eval, evalLiteral] + +@[simp] theorem renamed_clause_count (F : Formula) : + (renamed F).clauses.length = F.clauses.length := by simp [renamed] + +@[simp] theorem renamed_variable_count (F : Formula) : + (renamed F).«variables» = 3 * F.clauses.length := by + exact clauseNames_flat_length F.clauses + +theorem renamed_satisfiable_iff (F : Formula) : (renamed F).Satisfiable ↔ F.Satisfiable := by + constructor + · rintro ⟨A, hA⟩ + refine ⟨extendAssignment F A, ?_⟩ + intro c mem + have hc : clause F c mem ∈ (renamed F).clauses := + List.mem_map.mpr ⟨⟨c, mem⟩, by simp, rfl⟩ + exact (clause_eval_extend F c mem A).symm.trans (hA _ hc) + · rintro ⟨A, hA⟩ + refine ⟨restrictAssignment F A, ?_⟩ + intro c mem + obtain ⟨original, _, rfl⟩ := List.mem_map.mp mem + exact (clause_eval_restrict F original.val original.property A).trans + (hA original.val original.property) + +theorem nat_bits_injective : Function.Injective Nat.bits := by + intro a b same + have decoded := congrArg BinaryEncoding.bitsValue same + simpa only [BinaryEncoding.bitsValue_bits] using decoded + +theorem idxOf_binary_payloads (names : List Nat) (name : Nat) : + (names.map Nat.bits).idxOf name.bits = names.idxOf name := by + induction names with + | nil => rfl + | cons first names ih => + by_cases same : first = name + · subst first + simp + · have different : first.bits ≠ name.bits := fun h => same (nat_bits_injective h) + simp only [List.map_cons, List.idxOf_cons, beq_false_of_ne same, + beq_false_of_ne different, ih] + +theorem renamed_encoding_bound (F : Formula) : + (Complexity.formulaBits (renamed F)).length ≤ + 9 * F.clauses.length * F.clauses.length + 10 * F.clauses.length + 2 := by + have h := Complexity.formulaBits_length_le (renamed F) + simp only [renamed_clause_count, renamed_variable_count] at h + nlinarith + +theorem renamed_encoding_bound_bits (F : Formula) : + (Complexity.formulaBits (renamed F)).length ≤ + 9 * (BinaryEncoding.formulaBits F).length * (BinaryEncoding.formulaBits F).length + + 10 * (BinaryEncoding.formulaBits F).length + 2 := by + have h := renamed_encoding_bound F + have hm : F.clauses.length ≤ (BinaryEncoding.formulaBits F).length := + (BinaryEncoding.clauses_length_lt_bits F.clauses).le + have hsq := Nat.mul_self_le_mul_self hm + nlinarith + +end MinUncutGames.BinaryOccurrenceRename + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineBinaryParsing.lean b/lean/OAI/Computability/MinUncut/Machines/MachineBinaryParsing.lean new file mode 100644 index 0000000000000000000000000000000000000000..a4555de4c8ba1322109269f32d2c7ce3bda75309 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineBinaryParsing.lean @@ -0,0 +1,919 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineBinaryOccurrenceRename +import OAI.Computability.MinUncut.Machines.MachineBinaryNameMachine + +namespace OAI + +namespace MinUncutGames.BinaryParsing + +open BinaryEncoding BinaryFormula + +theorem frame_eq (bits : List Bool) : BinaryNameMachine.frame bits = frame bits := by + induction bits with + | nil => rfl + | cons bit bits ih => simp [BinaryNameMachine.frame, frame, ih] + +theorem canonical_cons_cons (a b : Bool) (bits : List Bool) : + BinaryNameMachine.canonical (a :: b :: bits) = BinaryNameMachine.canonical (b :: bits) := rfl + +theorem canonical_iff (bits : List Bool) : + BinaryNameMachine.canonical bits = true ↔ (bitsValue bits).bits = bits := by + induction bits with + | nil => simp [BinaryNameMachine.canonical, BinaryNameMachine.finalDigit, bitsValue] + | cons bit bits ih => + cases bits with + | nil => cases bit <;> decide + | cons next bits => + rw [canonical_cons_cons, ih] + constructor + · intro htail + have hn : bitsValue (next :: bits) ≠ 0 := by + intro hz + rw [hz, Nat.zero_bits] at htail + contradiction + rw [bitsValue, Nat.bits_append_bit _ bit (fun h => False.elim (hn h)), htail] + · intro hfull + calc + (bitsValue (next :: bits)).bits = + (Nat.bit bit (bitsValue (next :: bits))).div2.bits := by rw [Nat.div2_bit] + _ = (Nat.bit bit (bitsValue (next :: bits))).bits.tail := + Nat.div2_bits_eq_tail _ + _ = (bit :: next :: bits).tail := congrArg List.tail hfull + _ = next :: bits := rfl + +@[simp] theorem canonical_nat_bits (name : Nat) : + BinaryNameMachine.canonical name.bits = true := by + apply (canonical_iff _).mpr + rw [bitsValue_bits] + +theorem parseFrame_sound (input digits rest : List Bool) + (parsed : parseFrame input = some (digits, rest)) : input = frame digits ++ rest := by + induction input using List.twoStepInduction generalizing digits rest with + | nil => simp [parseFrame] at parsed + | singleton flag => + cases flag + · simp only [parseFrame, Option.some.injEq, Prod.mk.injEq] at parsed + rcases parsed with ⟨rfl, rfl⟩ + rfl + · simp [parseFrame] at parsed + | cons_cons flag bit input ih _ => + cases flag + · simp only [parseFrame, Option.some.injEq, Prod.mk.injEq] at parsed + rcases parsed with ⟨rfl, rfl⟩ + rfl + · cases h : parseFrame input with + | none => simp [parseFrame, h] at parsed + | some pair => + rcases pair with ⟨ds, tail⟩ + have hs := ih ds tail h + simp [parseFrame, h] at parsed + rcases parsed with ⟨rfl, rfl⟩ + simp [frame, hs] + +theorem parseName_sound (input : List Bool) (name : Nat) (rest : List Bool) + (parsed : parseName input = some (name, rest)) : input = nameBits name ++ rest := by + cases h : parseFrame input with + | none => simp [parseName, h] at parsed + | some pair => + rcases pair with ⟨digits, tail⟩ + by_cases canonical : digits = (bitsValue digits).bits + · simp only [parseName, h, Option.bind_eq_bind, Option.bind_some] at parsed + rw [ite_eq_left canonical] at parsed + simp only [Option.some.injEq, Prod.mk.injEq] at parsed + rcases parsed with ⟨rfl, rfl⟩ + have hs := parseFrame_sound input digits tail h + exact hs.trans (congrArg (fun ds => frame ds ++ tail) canonical) + · simp only [parseName, h, Option.bind_eq_bind, Option.bind_some, ite_eq_right canonical] at parsed + cases parsed + +theorem parseLiteral_sound (input : List Bool) (literal : Literal) (rest : List Bool) + (parsed : parseLiteral input = some (literal, rest)) : + input = literalBits literal ++ rest := by + cases input with + | nil => simp [parseLiteral] at parsed + | cons sign input => + cases h : parseName input with + | none => simp [parseLiteral, h] at parsed + | some pair => + rcases pair with ⟨name, tail⟩ + have hs := parseName_sound input name tail h + simp [parseLiteral, h] at parsed + rcases parsed with ⟨rfl, rfl⟩ + simp [literalBits, hs] + +theorem parseClause_sound (input : List Bool) (clause : Clause) (rest : List Bool) + (parsed : parseClause input = some (clause, rest)) : input = clauseBits clause ++ rest := by + cases ha : parseLiteral input with + | none => simp [parseClause, ha] at parsed + | some first => + rcases first with ⟨a, afterA⟩ + cases hb : parseLiteral afterA with + | none => simp [parseClause, ha, hb] at parsed + | some second => + rcases second with ⟨b, afterB⟩ + cases hc : parseLiteral afterB with + | none => simp [parseClause, ha, hb, hc] at parsed + | some third => + rcases third with ⟨c, afterC⟩ + have hA := parseLiteral_sound input a afterA ha + have hB := parseLiteral_sound afterA b afterB hb + have hC := parseLiteral_sound afterB c afterC hc + have pairEq : (#v[a, b, c], afterC) = (clause, rest) := by + apply Option.some.inj + simpa only [parseClause, ha, hb, hc, Option.bind_eq_bind, + Option.bind_some, Option.pure_def] using parsed + rcases Prod.mk.inj pairEq with ⟨rfl, rfl⟩ + simp [clauseBits, hA, hB, hC, List.append_assoc] + +theorem parseClauses_sound (fuel : Nat) (input : List Bool) + (clauses : List Clause) (rest : List Bool) + (parsed : parseClauses fuel input = some (clauses, rest)) : + input = clausesBits clauses ++ rest := by + induction fuel generalizing input clauses rest with + | zero => simp [parseClauses] at parsed + | succ fuel ih => + cases input with + | nil => simp [parseClauses] at parsed + | cons flag input => + cases flag + · simp only [parseClauses, Option.some.injEq, Prod.mk.injEq] at parsed + rcases parsed with ⟨rfl, rfl⟩ + rfl + · cases hc : parseClause input with + | none => simp [parseClauses, hc] at parsed + | some first => + rcases first with ⟨clause, afterClause⟩ + cases hs : parseClauses fuel afterClause with + | none => simp [parseClauses, hc, hs] at parsed + | some remaining => + rcases remaining with ⟨cs, tail⟩ + have hC := parseClause_sound input clause afterClause hc + have hS := ih afterClause cs tail hs + simp [parseClauses, hc, hs] at parsed + rcases parsed with ⟨rfl, rfl⟩ + simp [clausesBits, hC, hS, List.append_assoc] + +theorem decodeFormula_sound (input : List Bool) (formula : Formula) + (parsed : decodeFormula input = some formula) : input = formulaBits formula := by + cases h : parseClauses (input.length + 1) input with + | none => simp [decodeFormula, h] at parsed + | some pair => + rcases pair with ⟨clauses, rest⟩ + by_cases empty : rest = [] + · subst rest + simp [decodeFormula, h] at parsed + subst formula + simpa only [formulaBits, List.append_nil] using + parseClauses_sound (input.length + 1) input clauses [] h + · simp [decodeFormula, h, empty] at parsed + +theorem decodeFormula_eq_some_iff (input : List Bool) (formula : Formula) : + decodeFormula input = some formula ↔ input = formulaBits formula := + ⟨decodeFormula_sound input formula, fun h => h ▸ decodeFormula_encoded formula⟩ + +theorem scanSpec_nameBits (name : Nat) (suffix output : List Bool) : + BinaryNameMachine.scanSpec (nameBits name ++ suffix) output none = + ⟨true, suffix, name.bits.reverse ++ output⟩ := by + unfold nameBits + rw [← frame_eq, BinaryNameMachine.scanSpec_frame] + have h := canonical_nat_bits name + simpa only [BinaryNameMachine.canonical] using + congrArg (fun accepted => + (⟨accepted, suffix, name.bits.reverse ++ output⟩ : BinaryNameMachine.Result)) h + +end MinUncutGames.BinaryParsing + +namespace MinUncutGames.BinaryTokenMachine + +open Turing +open MinUncutGames.Foundations.Complexity +open MachineComposition +open MinUncutGames.Reduction.MachineTransfer +open BinaryFormula BinaryEncoding + +abbrev Tape := Fin 3 +abbrev Alphabet (_ : Tape) := Bool +abbrev State := Unit × Option Bool + +inductive Label where + | clause + | sign (slot : Fin 3) + | name (slot : Fin 3) + | restore + | accept + | reject + deriving DecidableEq, Fintype + +def afterName (slot : Fin 3) : Label := + if slot = 0 then .sign 1 else if slot = 1 then .sign 2 else .clause + +@[simp] theorem afterName_zero : afterName 0 = .sign 1 := rfl +@[simp] theorem afterName_one : afterName 1 = .sign 2 := rfl +@[simp] theorem afterName_two : afterName 2 = .clause := rfl + +def jump (label : Label) : TM2.Stmt Alphabet Label State := + .load (fun _ => ((), none)) (.goto fun _ => label) + +def clauseInstruction : TM2.Stmt Alphabet Label State := + .pop 0 (fun state head => (state.1, head)) + (.branch (fun state => state.2.isNone) + (jump .reject) + (.branch (fun state => state.2.getD false) + (jump (.sign 0)) (jump .restore))) + +def signInstruction (slot : Fin 3) : TM2.Stmt Alphabet Label State := + .pop 0 (fun state head => (state.1, head)) + (.branch (fun state => state.2.isSome) + (.push 1 (fun state => state.2.getD false) (jump (.name slot))) + (jump .reject)) + +def nameInstruction (slot : Fin 3) : TM2.Stmt Alphabet Label State := + .pop 0 (fun state head => (state.1, head)) + (.branch (fun state => state.2.isNone) + (jump .reject) + (.branch (fun state => state.2.getD false) + (.push 1 (fun _ => true) + (.pop 0 (fun state head => (state.1, head)) + (.branch (fun state => state.2.isSome) + (.push 1 (fun state => state.2.getD false) (jump (.name slot))) + (jump .reject)))) + (.push 1 (fun _ => false) (jump (afterName slot))))) + +def program : Label → TM2.Stmt Alphabet Label State + | .clause => clauseInstruction + | .sign slot => signInstruction slot + | .name slot => nameInstruction slot + | .restore => loopAt 1 2 id false .restore (some .accept) + | .accept => .halt + | .reject => .halt + +abbrev machine : FinTM2 where + K := Tape + k₀ := 0 + k₁ := 2 + Γ := Alphabet + Λ := Label + main := .clause + σ := State + initialState := ((), none) + m := program + +def tapes (input reversed output : List Bool) : Tape → List Bool := + fun k => if k = 0 then input else if k = 1 then reversed else output + +def cfg (label : Option Label) (input reversed output : List Bool) + (register : Option Bool := none) : machine.Cfg := + ⟨label, ((), register), tapes input reversed output⟩ + +@[simp] private theorem tapes_zero (input reversed output : List Bool) : + tapes input reversed output 0 = input := rfl + +@[simp] private theorem tapes_one (input reversed output : List Bool) : + tapes input reversed output 1 = reversed := rfl + +@[simp] private theorem tapes_two (input reversed output : List Bool) : + tapes input reversed output 2 = output := rfl + +private theorem update_zero (input reversed output replacement : List Bool) : + Function.update (tapes input reversed output) 0 replacement = + tapes replacement reversed output := by + funext k + fin_cases k <;> simp [tapes] + +private theorem update_one (input reversed output replacement : List Bool) : + Function.update (tapes input reversed output) 1 replacement = + tapes input replacement output := by + funext k + fin_cases k <;> simp [tapes] + +theorem clauseStep (input reversed output : List Bool) (register : Option Bool) : + machine.step (cfg (some .clause) (true :: input) reversed output register) = + some (cfg (some (.sign 0)) input reversed output) := by + change some (TM2.stepAux (program .clause) _ _) = _ + simp [program, clauseInstruction, jump, cfg, TM2.stepAux, update_zero]; rfl + +theorem finalStep (input reversed output : List Bool) (register : Option Bool) : + machine.step (cfg (some .clause) (false :: input) reversed output register) = + some (cfg (some .restore) input reversed output) := by + change some (TM2.stepAux (program .clause) _ _) = _ + simp [program, clauseInstruction, jump, cfg, TM2.stepAux, update_zero]; rfl + +theorem signStep (slot : Fin 3) (bit : Bool) (input reversed output : List Bool) + (register : Option Bool) : + machine.step (cfg (some (.sign slot)) (bit :: input) reversed output register) = + some (cfg (some (.name slot)) input (bit :: reversed) output) := by + change some (TM2.stepAux (program (.sign slot)) _ _) = _ + simp [program, signInstruction, jump, cfg, TM2.stepAux, update_zero, update_one]; rfl + +theorem nameEndStep (slot : Fin 3) (input reversed output : List Bool) + (register : Option Bool) : + machine.step (cfg (some (.name slot)) (false :: input) reversed output register) = + some (cfg (some (afterName slot)) input (false :: reversed) output) := by + change some (TM2.stepAux (program (.name slot)) _ _) = _ + simp [program, nameInstruction, jump, cfg, TM2.stepAux, update_zero, update_one]; rfl + +theorem nameDigitStep (slot : Fin 3) (bit : Bool) (input reversed output : List Bool) + (register : Option Bool) : + machine.step + (cfg (some (.name slot)) (true :: bit :: input) reversed output register) = + some (cfg (some (.name slot)) input (bit :: true :: reversed) output) := by + change some (TM2.stepAux (program (.name slot)) _ _) = _ + simp [program, nameInstruction, jump, cfg, TM2.stepAux, update_zero, update_one]; rfl + +theorem nameTrace (slot : Fin 3) (bits suffix reversed output : List Bool) + (register : Option Bool) : + (advance machine.step)^[bits.length + 1] + (some (cfg (some (.name slot)) (frame bits ++ suffix) reversed output register)) = + some (cfg (some (afterName slot)) suffix ((frame bits).reverse ++ reversed) output) := by + induction bits generalizing reversed register with + | nil => + simpa only [List.length_nil, Nat.zero_add, Function.iterate_one, advance_some, + frame, List.singleton_append, List.reverse_singleton] using + nameEndStep slot suffix reversed output register + | cons bit bits ih => + rw [List.length_cons, Function.iterate_succ_apply] + simp only [frame, List.cons_append, advance_some] + rw [nameDigitStep, ih] + simp only [List.reverse_cons, List.append_assoc, + List.cons_append, List.nil_append] + +theorem literalTrace (slot : Fin 3) (literal : Literal) + (suffix reversed output : List Bool) (register : Option Bool) : + (advance machine.step)^[literal.name.size + 2] + (some (cfg (some (.sign slot)) (literalBits literal ++ suffix) reversed output register)) = + some (cfg (some (afterName slot)) suffix + ((literalBits literal).reverse ++ reversed) output) := by + rw [show literal.name.size + 2 = (literal.name.bits.length + 1) + 1 by + rw [Nat.size_eq_bits_len]] + rw [Function.iterate_succ_apply] + simp only [literalBits, List.cons_append, advance_some] + rw [signStep] + change (advance machine.step)^[literal.name.bits.length + 1] + (some (cfg (some (.name slot)) (frame literal.name.bits ++ suffix) + (literal.positive :: reversed) output)) = _ + rw [nameTrace] + simp only [nameBits, List.reverse_cons, List.append_assoc, List.singleton_append] + +theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +theorem clauseTrace (clause : Clause) (suffix reversed output : List Bool) + (register : Option Bool) : + (advance machine.step)^[clauseNameSize clause + 6] + (some (cfg (some (.sign 0)) (clauseBits clause ++ suffix) reversed output register)) = + some (cfg (some .clause) suffix ((clauseBits clause).reverse ++ reversed) output) := by + have first := literalTrace 0 clause[0] + (literalBits clause[1] ++ literalBits clause[2] ++ suffix) reversed output register + have second := literalTrace 1 clause[1] (literalBits clause[2] ++ suffix) + ((literalBits clause[0]).reverse ++ reversed) output none + have third := literalTrace 2 clause[2] suffix + ((literalBits clause[1]).reverse ++ ((literalBits clause[0]).reverse ++ reversed)) output none + simp only [afterName_zero, afterName_one, afterName_two, List.append_assoc] + at first second third + have full := joinTrace (joinTrace first second) third + have htime : (clause[0].name.size + 2 + (clause[1].name.size + 2)) + + (clause[2].name.size + 2) = clauseNameSize clause + 6 := by + simp [clauseNameSize, clauseNames] + omega + rw [htime] at full + simpa only [clauseBits, List.append_assoc, List.reverse_append] using full + +def tokens (clauses : List Clause) : List Bool := clauses.flatMap clauseBits + +@[simp] theorem tokens_nil : tokens [] = [] := rfl + +@[simp] theorem tokens_cons (clause : Clause) (clauses : List Clause) : + tokens (clause :: clauses) = clauseBits clause ++ tokens clauses := by + simp [tokens] + +@[simp] theorem tokens_length (clauses : List Clause) : + (tokens clauses).length = 6 * clauses.length + 2 * namesBitSize clauses := by + induction clauses with + | nil => rfl + | cons clause clauses ih => + simp only [tokens_cons, List.length_append, clauseBits_length, ih, + List.length_cons, namesBitSize_cons] + omega + +theorem stripTrace (clauses : List Clause) (suffix reversed output : List Bool) + (register : Option Bool) : + (advance machine.step)^[7 * clauses.length + namesBitSize clauses + 1] + (some (cfg (some .clause) (clausesBits clauses ++ suffix) reversed output register)) = + some (cfg (some .restore) suffix ((tokens clauses).reverse ++ reversed) output) := by + induction clauses generalizing reversed register with + | nil => + simpa only [List.length_nil, Nat.mul_zero, namesBitSize_nil, Nat.add_zero, + Nat.zero_add, Function.iterate_one, advance_some, clausesBits, + List.singleton_append, tokens_nil, List.reverse_nil, List.nil_append] using + finalStep suffix reversed output register + | cons clause clauses ih => + have first : (advance machine.step)^[1] + (some (cfg (some .clause) + (true :: (clauseBits clause ++ (clausesBits clauses ++ suffix))) + reversed output register)) = + some (cfg (some (.sign 0)) + (clauseBits clause ++ (clausesBits clauses ++ suffix)) reversed output) := by + simpa only [Function.iterate_one, advance_some] using + clauseStep (clauseBits clause ++ (clausesBits clauses ++ suffix)) reversed output register + have second := clauseTrace clause (clausesBits clauses ++ suffix) reversed output none + have third := ih ((clauseBits clause).reverse ++ reversed) none + have full := joinTrace (joinTrace first second) third + have htime : (1 + (clauseNameSize clause + 6)) + + (7 * clauses.length + namesBitSize clauses + 1) = + 7 * (clause :: clauses).length + namesBitSize (clause :: clauses) + 1 := by + simp only [List.length_cons, namesBitSize_cons] + omega + rw [htime] at full + simpa only [clausesBits, List.cons_append, List.append_assoc, + tokens_cons, List.reverse_append] using full + +theorem restoreTrace (input unread output : List Bool) (register : Option Bool) : + (advance machine.step)^[input.length + 1] + (some (cfg (some .restore) unread input.reverse output register)) = + some (cfg (some .accept) unread [] (input ++ output)) := by + have h := transferAt_fromTapes (Γ := Alphabet) (σ := Unit) 1 2 (by decide) + id false .restore (some .accept) program rfl + (tapes unread input.reverse output) () register + have ht : tapesAt 1 2 (tapes unread input.reverse output) [] (input ++ output) = + tapes unread [] (input ++ output) := by + funext k + fin_cases k <;> simp [tapesAt, tapes] + change (nextAt 2 program)^[input.length + 1] + (some (cfg (some .restore) unread input.reverse output register)) = _ + simpa only [tapes_one, tapes_two, List.length_reverse, List.reverse_reverse, + List.map_id_fun, id_eq, ht, nextAt, advance, cfg] using! h + +theorem initList_eq (input : List Bool) : + initList machine input = cfg (some .clause) input [] [] := by + unfold initList cfg + congr 1 + funext k + fin_cases k <;> simp [tapes, machine] + +theorem haltList_eq (output : List Bool) : + haltList machine output = cfg none [] [] output := by + unfold haltList cfg + congr 1 + funext k + fin_cases k <;> simp [tapes, machine] + +theorem acceptTrace (formula : Formula) : + (advance machine.step)^[13 * formula.clauses.length + + 3 * namesBitSize formula.clauses + 2] + (some (initList machine (formulaBits formula))) = + some (cfg (some .accept) [] [] (tokens formula.clauses)) := by + have first := stripTrace formula.clauses [] [] [] none + simp only [List.append_nil] at first + have second := restoreTrace (tokens formula.clauses) [] [] none + simp only [List.append_nil] at second + have full := joinTrace first second + have htime : (7 * formula.clauses.length + namesBitSize formula.clauses + 1) + + ((tokens formula.clauses).length + 1) = + 13 * formula.clauses.length + 3 * namesBitSize formula.clauses + 2 := by + rw [tokens_length] + omega + rw [htime] at full + simpa only [initList_eq, BinaryEncoding.formulaBits] using full + +theorem haltStep (output : List Bool) : + machine.step (cfg (some .accept) [] [] output) = some (cfg none [] [] output) := by + change some (TM2.stepAux (program .accept) _ _) = _ + rfl + +theorem tokenTrace (formula : Formula) : + (advance machine.step)^[13 * formula.clauses.length + + 3 * namesBitSize formula.clauses + 3] + (some (initList machine (formulaBits formula))) = + some (haltList machine (tokens formula.clauses)) := by + rw [show 13 * formula.clauses.length + 3 * namesBitSize formula.clauses + 3 = + (13 * formula.clauses.length + 3 * namesBitSize formula.clauses + 2) + 1 by omega, + Function.iterate_succ_apply', acceptTrace, advance_some, haltStep, haltList_eq] + +theorem tokenSteps_le (formula : Formula) : + 13 * formula.clauses.length + 3 * namesBitSize formula.clauses + 3 ≤ + 3 * (formulaBits formula).length + 3 := by + rw [BinaryEncoding.formulaBits_length] + omega + +def outputsInTime (formula : Formula) : + TM2OutputsInTime machine (formulaBits formula) (some (tokens formula.clauses)) + (3 * (formulaBits formula).length + 3) where + steps := 13 * formula.clauses.length + 3 * namesBitSize formula.clauses + 3 + evals_in_steps := tokenTrace formula + steps_le_m := tokenSteps_le formula + +noncomputable def computableInPolyTime : + TM2ComputableInPolyTime BinaryEncoding.formulaBits (id : List Bool → List Bool) + (fun formula => tokens formula.clauses) where + tm := machine + inputAlphabet := Equiv.refl Bool + outputAlphabet := Equiv.refl Bool + time := Polynomial.C 3 * Polynomial.X + Polynomial.C 3 + outputsFun formula := by + change TM2OutputsInTime machine ((formulaBits formula).map id) + (some ((tokens formula.clauses).map id)) + ((Polynomial.C 3 * Polynomial.X + Polynomial.C 3 : Polynomial Nat).eval + (formulaBits formula).length) + simpa only [List.map_id_fun, id_eq, Polynomial.eval_add, Polynomial.eval_mul, + Polynomial.eval_C, Polynomial.eval_X] using outputsInTime formula + +theorem machine_finiteAlphabet (k : machine.K) : Finite (machine.Γ k) := by + change Finite Bool + infer_instance + +end MinUncutGames.BinaryTokenMachine + +namespace MinUncutGames.BinaryRenameWords + +open BinaryFormula MinUncutGames.Foundations + +def clauseLiterals (c : Clause) : List Literal := [(c)[0], (c)[1], (c)[2]] + +def literals (clauses : List Clause) : List Literal := clauses.flatMap clauseLiterals + +def token (literal : Literal) : BinaryNameSearch.Token := + (literal.positive, literal.name.bits) + +def tokens (clauses : List Clause) : List BinaryNameSearch.Token := + (literals clauses).map token + +@[simp] theorem literals_nil : literals [] = [] := rfl + +@[simp] theorem literals_cons (c : Clause) (cs : List Clause) : + literals (c :: cs) = (c)[0] :: (c)[1] :: (c)[2] :: literals cs := rfl + +@[simp] theorem literals_length (cs : List Clause) : + (literals cs).length = 3 * cs.length := by + induction cs with + | nil => rfl + | cons c cs ih => simp only [literals_cons, List.length_cons, ih]; omega + +@[simp] theorem tokens_length (cs : List Clause) : + (tokens cs).length = 3 * cs.length := by simp [tokens] + +theorem literals_names (F : Formula) : + (literals F.clauses).map Literal.name = sourceNames F := by + simp only [literals, sourceNames, List.map_flatMap] + rfl + +theorem tokens_payloads (F : Formula) : + BinaryNameSearch.payloads (tokens F.clauses) = (sourceNames F).map Nat.bits := by + rw [← literals_names] + simp only [BinaryNameSearch.payloads, tokens, List.map_map, token, Function.comp_def] + +theorem token_bits (literal : Literal) : + BinaryNameSearch.tokenBits (token literal) = BinaryEncoding.literalBits literal := by + simp only [BinaryNameSearch.tokenBits, token, BinaryEncoding.literalBits, + BinaryEncoding.nameBits, BinaryParsing.frame_eq] + +theorem tokens_stream (cs : List Clause) : + BinaryNameSearch.stream (tokens cs) = BinaryTokenMachine.tokens cs := by + induction cs with + | nil => rfl + | cons c cs ih => + simp only [tokens, literals_cons, List.map_cons, BinaryNameSearch.stream_cons, + token_bits, BinaryTokenMachine.tokens_cons, BinaryEncoding.clauseBits] + simpa only [tokens, List.append_assoc] using + congrArg (fun tail => BinaryEncoding.literalBits (c)[0] ++ + BinaryEncoding.literalBits (c)[1] ++ BinaryEncoding.literalBits (c)[2] ++ tail) ih + +theorem tokens_canonical (cs : List Clause) : + ∀ t ∈ tokens cs, BinaryNameMachine.canonical t.2 = true := by + intro t mem + obtain ⟨literal, _, rfl⟩ := List.mem_map.mp mem + exact BinaryParsing.canonical_nat_bits literal.name + +theorem payload_index (F : Formula) (name : Nat) : + (BinaryNameSearch.payloads (tokens F.clauses)).idxOf name.bits = + (sourceNames F).idxOf name := by + rw [tokens_payloads, BinaryOccurrenceRename.idxOf_binary_payloads] + +theorem token_payload_mem (cs : List Clause) (literal : Literal) + (mem : literal ∈ literals cs) : + literal.name.bits ∈ BinaryNameSearch.payloads (tokens cs) := by + apply List.mem_map.mpr + refine ⟨token literal, ?_, rfl⟩ + exact List.mem_map.mpr ⟨literal, mem, rfl⟩ + +theorem payloadSize_tokens (cs : List Clause) : + BinaryNameSearch.payloadSize (tokens cs) = BinaryEncoding.namesBitSize cs := by + induction cs with + | nil => rfl + | cons c cs ih => + simp only [tokens, literals_cons, List.map_cons, + BinaryNameSearch.payloadSize_cons, token, Nat.size_eq_bits_len, + BinaryEncoding.namesBitSize_cons] at * + simpa only [BinaryEncoding.clauseNameSize, BinaryFormula.clauseNames, + List.map_cons, List.map_nil, List.sum_cons, List.sum_nil, + Nat.add_zero, Nat.add_assoc] using congrArg + (fun tail => (c)[0].name.size + ((c)[1].name.size + ((c)[2].name.size + tail))) ih + +def outputLiteral (names : List Nat) (literal : Literal) : List Bool := + Complexity.encodeWord (names.idxOf literal.name) ++ + Complexity.encodeWord (if literal.positive then 1 else 0) + +def body (F : Formula) : List Bool := + (literals F.clauses).flatMap (outputLiteral (sourceNames F)) + +theorem encoded_clause (F : Formula) (c : Clause) (mem : c ∈ F.clauses) : + Complexity.encodeWords (Complexity.clauseWords (BinaryOccurrenceRename.clause F c mem)) = + (clauseLiterals c).flatMap (outputLiteral (sourceNames F)) := by + simp [Complexity.clauseWords, Complexity.literalWords, Complexity.encodeWords, + BinaryOccurrenceRename.clause, BinaryOccurrenceRename.literal, + BinaryOccurrenceRename.nameIndex, clauseLiterals, outputLiteral, List.append_assoc] + rfl + +private theorem encodeWords_flatMap {α : Type} (xs : List α) (f : α → List Nat) : + Complexity.encodeWords (xs.flatMap f) = + xs.flatMap (fun x => Complexity.encodeWords (f x)) := by + induction xs with + | nil => rfl + | cons x xs ih => simp only [List.flatMap_cons, Complexity.encodeWords_append, ih] + +theorem encoded_body (F : Formula) : + Complexity.encodeWords ((BinaryOccurrenceRename.renamed F).clauses.flatMap + Complexity.clauseWords) = body F := by + rw [encodeWords_flatMap] + change (F.clauses.attach.map (fun c => BinaryOccurrenceRename.clause F c.val c.property)).flatMap + (fun c => Complexity.encodeWords (Complexity.clauseWords c)) = body F + rw [List.flatMap_map] + simp only [encoded_clause] + have h := congrArg (fun cs : List Clause => + cs.flatMap (fun c => (clauseLiterals c).flatMap (outputLiteral (sourceNames F)))) + (List.attach_map_subtype_val F.clauses) + simpa only [List.flatMap_map, body, literals, List.flatMap_assoc] using h + +theorem encoded_renamed (F : Formula) : + Complexity.formulaBits (BinaryOccurrenceRename.renamed F) = + Complexity.encodeWord (3 * F.clauses.length) ++ + Complexity.encodeWord F.clauses.length ++ body F := by + simp only [Complexity.formulaBits, Complexity.formulaWords, Complexity.encodeWords_append, + Complexity.encodeWords, List.append_nil, + BinaryOccurrenceRename.renamed_variable_count, + BinaryOccurrenceRename.renamed_clause_count, encoded_body, List.append_assoc] + +end MinUncutGames.BinaryRenameWords + +namespace MinUncutGames.BinaryHeaderMachine + +open Turing +open MinUncutGames.Foundations.Complexity +open MachineComposition +open MinUncutGames.Reduction.MachineTransfer + +abbrev Alphabet {K : Type} (_ : K) := Bool +abbrev State (A : Type) := A × Option Bool + +section Placement + +variable {K Λ A : Type} [DecidableEq K] + +def delimiter (destination : K) (next : Λ) : TM2.Stmt (Alphabet (K := K)) Λ (State A) := + .push destination (fun _ => false) + (.load (fun state => (state.1, none)) (.goto fun _ => next)) + +def tapes (variableTape clauses destination : K) (base : K → List Bool) + (variableCounter clauseCounter output : List Bool) : K → List Bool := + Function.update (Function.update (Function.update base variableTape variableCounter) + clauses clauseCounter) destination output + +@[simp] theorem tapes_variables (variableTape clauses destination : K) + (vc : variableTape ≠ clauses) (vd : variableTape ≠ destination) (base : K → List Bool) + (variableCounter clauseCounter output : List Bool) : + tapes variableTape clauses destination base variableCounter clauseCounter output variableTape = + variableCounter := by + simp [tapes, vc, vd] + +@[simp] theorem tapes_clauses (variableTape clauses destination : K) + (cd : clauses ≠ destination) (base : K → List Bool) + (variableCounter clauseCounter output : List Bool) : + tapes variableTape clauses destination base variableCounter clauseCounter output clauses = + clauseCounter := by + simp [tapes, cd] + +@[simp] theorem tapes_destination (variableTape clauses destination : K) (base : K → List Bool) + (variableCounter clauseCounter output : List Bool) : + tapes variableTape clauses destination base variableCounter clauseCounter output destination = + output := by + simp [tapes] + +theorem tapes_other (variableTape clauses destination k : K) + (kv : k ≠ variableTape) (kc : k ≠ clauses) (kd : k ≠ destination) + (base : K → List Bool) (variableCounter clauseCounter output : List Bool) : + tapes variableTape clauses destination base variableCounter clauseCounter output k = base k := by + simp [tapes, kv, kc, kd] + +private theorem update_variables (variableTape clauses destination : K) + (vc : variableTape ≠ clauses) (vd : variableTape ≠ destination) (base : K → List Bool) + (variableCounter clauseCounter output replacement : List Bool) : + Function.update (tapes variableTape clauses destination base variableCounter clauseCounter output) + variableTape replacement = tapes variableTape clauses destination base replacement clauseCounter output := by + funext k + by_cases hv : k = variableTape + · subst k + simp [tapes, vc, vd] + · by_cases hd : k = destination + · subst k + simp [tapes, hv] + · by_cases hc : k = clauses + · subst k + simp [tapes, hv, hd] + · simp [tapes, hv, hc, hd] + +private theorem update_clauses (variableTape clauses destination : K) + (cd : clauses ≠ destination) (base : K → List Bool) + (variableCounter clauseCounter output replacement : List Bool) : + Function.update (tapes variableTape clauses destination base variableCounter clauseCounter output) + clauses replacement = tapes variableTape clauses destination base variableCounter replacement output := by + funext k + by_cases hc : k = clauses + · subst k + simp [tapes, cd] + · by_cases hd : k = destination + · subst k + simp [tapes, hc] + · simp [tapes, hc, hd] + +private theorem update_destination (variableTape clauses destination : K) (base : K → List Bool) + (variableCounter clauseCounter output replacement : List Bool) : + Function.update (tapes variableTape clauses destination base variableCounter clauseCounter output) + destination replacement = tapes variableTape clauses destination base variableCounter clauseCounter replacement := by + simp [tapes] + +variable (variableTape clauses destination : K) +variable (vc : variableTape ≠ clauses) (vd : variableTape ≠ destination) (cd : clauses ≠ destination) +variable (clauseStart clauseLoop variableStart variableLoop : Λ) (exit : Option Λ) +variable (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) +variable (atClauseStart : program clauseStart = delimiter destination clauseLoop) +variable (atClauseLoop : program clauseLoop = + loopAt clauses destination id false clauseLoop (some variableStart)) +variable (atVariableStart : program variableStart = delimiter destination variableLoop) +variable (atVariableLoop : program variableLoop = + loopAt variableTape destination id false variableLoop exit) +variable (base : K → List Bool) (ambient : A) + +include atClauseStart in +theorem clauseDelimiterStep (variableCounter clauseCounter output : List Bool) + (register : Option Bool) : + TM2.step program + ⟨some clauseStart, (ambient, register), + tapes variableTape clauses destination base variableCounter clauseCounter output⟩ = + some ⟨some clauseLoop, (ambient, none), + tapes variableTape clauses destination base variableCounter clauseCounter (false :: output)⟩ := by + change some (TM2.stepAux (program clauseStart) _ _) = _ + rw [atClauseStart] + simp [delimiter, TM2.stepAux, update_destination] + +include atVariableStart in +theorem variableDelimiterStep (variableCounter clauseCounter output : List Bool) + (register : Option Bool) : + TM2.step program + ⟨some variableStart, (ambient, register), + tapes variableTape clauses destination base variableCounter clauseCounter output⟩ = + some ⟨some variableLoop, (ambient, none), + tapes variableTape clauses destination base variableCounter clauseCounter (false :: output)⟩ := by + change some (TM2.stepAux (program variableStart) _ _) = _ + rw [atVariableStart] + simp [delimiter, TM2.stepAux, update_destination] + +include cd atClauseLoop in +theorem clauseCounterTrace (m : Nat) (variableCounter output : List Bool) + (register : Option Bool) : + (advance (TM2.step program))^[m + 1] + (some ⟨some clauseLoop, (ambient, register), + tapes variableTape clauses destination base variableCounter (List.replicate m true) output⟩) = + some ⟨some variableStart, (ambient, none), + tapes variableTape clauses destination base variableCounter [] (List.replicate m true ++ output)⟩ := by + have h := transferAt_fromTapes (Γ := Alphabet) clauses destination cd id false + clauseLoop (some variableStart) program atClauseLoop + (tapes variableTape clauses destination base variableCounter (List.replicate m true) output) + ambient register + change (nextAt destination program)^[m + 1] + (some ⟨some clauseLoop, (ambient, register), + tapes variableTape clauses destination base variableCounter (List.replicate m true) output⟩) = _ + simpa only [tapes_clauses variableTape clauses destination cd, tapes_destination, + List.length_replicate, List.reverse_replicate, List.map_id_fun, id_eq, + tapesAt, update_clauses variableTape clauses destination cd, update_destination, + nextAt, advance] using h + +include vc vd atVariableLoop in +theorem variableCounterTrace (n : Nat) (clauseCounter output : List Bool) + (register : Option Bool) : + (advance (TM2.step program))^[n + 1] + (some ⟨some variableLoop, (ambient, register), + tapes variableTape clauses destination base (List.replicate n true) clauseCounter output⟩) = + some ⟨exit, (ambient, none), + tapes variableTape clauses destination base [] clauseCounter (List.replicate n true ++ output)⟩ := by + have h := transferAt_fromTapes (Γ := Alphabet) variableTape destination vd id false + variableLoop exit program atVariableLoop + (tapes variableTape clauses destination base (List.replicate n true) clauseCounter output) + ambient register + change (nextAt destination program)^[n + 1] + (some ⟨some variableLoop, (ambient, register), + tapes variableTape clauses destination base (List.replicate n true) clauseCounter output⟩) = _ + simpa only [tapes_variables variableTape clauses destination vc vd, tapes_destination, + List.length_replicate, List.reverse_replicate, List.map_id_fun, id_eq, + tapesAt, update_variables variableTape clauses destination vc vd, update_destination, + nextAt, advance] using h + +theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +include vc vd cd atClauseStart atClauseLoop atVariableStart atVariableLoop + +theorem headerTrace (n m : Nat) (body : List Bool) (register : Option Bool) : + (advance (TM2.step program))^[n + m + 4] + (some ⟨some clauseStart, (ambient, register), + tapes variableTape clauses destination base + (List.replicate n true) (List.replicate m true) body⟩) = + some ⟨exit, (ambient, none), + tapes variableTape clauses destination base [] [] (encodeWord n ++ encodeWord m ++ body)⟩ := by + have first := clauseDelimiterStep variableTape clauses destination clauseStart clauseLoop program + atClauseStart base ambient (List.replicate n true) (List.replicate m true) body register + change (advance (TM2.step program))^[1] + (some ⟨some clauseStart, (ambient, register), + tapes variableTape clauses destination base (List.replicate n true) (List.replicate m true) body⟩) = _ at first + have second := clauseCounterTrace variableTape clauses destination cd clauseLoop variableStart program + atClauseLoop base ambient m (List.replicate n true) (false :: body) none + have third := variableDelimiterStep variableTape clauses destination variableStart variableLoop program + atVariableStart base ambient (List.replicate n true) [] + (List.replicate m true ++ false :: body) none + change (advance (TM2.step program))^[1] + (some ⟨some variableStart, (ambient, none), + tapes variableTape clauses destination base (List.replicate n true) [] + (List.replicate m true ++ false :: body)⟩) = _ at third + have fourth := variableCounterTrace variableTape clauses destination vc vd variableLoop exit program + atVariableLoop base ambient n [] (false :: (List.replicate m true ++ false :: body)) none + have full := joinTrace (joinTrace (joinTrace first second) third) fourth + have htime : ((1 + (m + 1)) + 1) + (n + 1) = n + m + 4 := by omega + rw [htime] at full + simpa only [encodeWord, List.append_assoc, List.singleton_append, + List.cons_append, List.nil_append] using full + +def headerInTime (n m : Nat) (body : List Bool) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some clauseStart, (ambient, register), + tapes variableTape clauses destination base (List.replicate n true) (List.replicate m true) body⟩ + (some ⟨exit, (ambient, none), + tapes variableTape clauses destination base [] [] (encodeWord n ++ encodeWord m ++ body)⟩) + (n + m + 4) where + steps := n + m + 4 + evals_in_steps := headerTrace variableTape clauses destination vc vd cd + clauseStart clauseLoop variableStart variableLoop exit program + atClauseStart atClauseLoop atVariableStart atVariableLoop base ambient n m body register + steps_le_m := Nat.le_refl _ + +end Placement + +abbrev ConcreteTape := Fin 3 +abbrev ConcreteLabel := Fin 4 + +def concreteProgram (label : ConcreteLabel) : + TM2.Stmt (Alphabet (K := ConcreteTape)) ConcreteLabel (State Unit) := + if label = 0 then delimiter 2 1 + else if label = 1 then loopAt 1 2 id false 1 (some 2) + else if label = 2 then delimiter 2 3 + else loopAt 0 2 id false 3 none + +abbrev machine : FinTM2 where + K := ConcreteTape + k₀ := 0 + k₁ := 2 + Γ := Alphabet + Λ := ConcreteLabel + main := 0 + σ := State Unit + initialState := ((), none) + m := concreteProgram + +def start (n m : Nat) (body : List Bool) : machine.Cfg := + ⟨some 0, ((), none), + tapes 0 1 2 (fun _ : ConcreteTape => []) (List.replicate n true) (List.replicate m true) body⟩ + +theorem haltList_eq (body : List Bool) : + haltList machine body = + ⟨none, ((), none), tapes 0 1 2 (fun _ : ConcreteTape => []) [] [] body⟩ := by + unfold haltList + congr 1 + funext k + fin_cases k <;> simp [machine, tapes] + +def machineInTime (n m : Nat) (body : List Bool) : + StateTransition.EvalsToInTime machine.step (start n m body) + (some (haltList machine (encodeWord n ++ encodeWord m ++ body))) (n + m + 4) := by + rw [haltList_eq] + exact headerInTime (0 : ConcreteTape) 1 2 (by decide) (by decide) (by decide) + (0 : ConcreteLabel) 1 2 3 none concreteProgram + (by simp [concreteProgram]) (by simp [concreteProgram]) + (by simp [concreteProgram]) (by simp [concreteProgram]) + (fun _ => []) () n m body none + +theorem machine_finiteAlphabet (k : machine.K) : Finite (machine.Γ k) := by + change Finite Bool + infer_instance + +end MinUncutGames.BinaryHeaderMachine + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineBinaryRenameMachine.lean b/lean/OAI/Computability/MinUncut/Machines/MachineBinaryRenameMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..d14ff8cf3f250586b7d0b126caa79c78a515be7d --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineBinaryRenameMachine.lean @@ -0,0 +1,342 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineBinaryLiteralMachine +import OAI.Computability.MinUncut.Machines.MachineBinaryParsing + +namespace OAI + +section +namespace MinUncutGames.BinaryRenameMachine + + +open Turing MinUncutGames.Foundations +open Complexity Complexity.MachineComposition +open MinUncutGames.Reduction.MachineTransfer + +abbrev Tape := Fin 12 +abbrev Alphabet (_ : Tape) := Bool +abbrev State := BinaryRenameLoop.State Unit + +inductive Label + | copyOut | copyBack + | loop (label : BinaryRenameLoop.Label) + | restore | clauseStart | clauseLoop | variableStart | variableLoop + | cleanup | reject + deriving DecidableEq, Fintype + +def loopTapes : Fin 11 → Tape := Fin.castSucc + +theorem loopTapes_injective : Function.Injective loopTapes := by + intro i j h + apply Fin.ext + exact congrArg (fun k : Tape => k.val) h + +def program : Label → TM2.Stmt Alphabet Label State + | .copyOut => loopAt 1 6 id false .copyOut (some .copyBack) + | .copyBack => MachineCopy.forkLoop 6 1 0 false .copyBack (some (.loop .entry)) + | .loop label => BinaryRenameLoop.instruction loopTapes Label.loop + (some .restore) (some .reject) label + | .restore => loopAt 8 11 id false .restore (some .clauseStart) + | .clauseStart => BinaryHeaderMachine.delimiter 11 .clauseLoop + | .clauseLoop => loopAt 10 11 id false .clauseLoop (some .variableStart) + | .variableStart => BinaryHeaderMachine.delimiter 11 .variableLoop + | .variableLoop => loopAt 9 11 id false .variableLoop (some .cleanup) + | .cleanup => MachineDrain.drain 1 .cleanup none + | .reject => .halt + +abbrev machine : FinTM2 where + K := Tape + k₀ := 1 + k₁ := 11 + Γ := Alphabet + Λ := Label + main := .copyOut + σ := State + initialState := BinaryRenameLoop.clean () 0 + m := program + +def tapes (permanent cursor reversed variableCounter clauseCounter output : List Bool) : + Tape → List Bool := fun k => + if k = 0 then cursor + else if k = 1 then permanent + else if k = 8 then reversed + else if k = 9 then variableCounter + else if k = 10 then clauseCounter + else if k = 11 then output + else [] + +def cfg (label : Option Label) + (permanent cursor reversed variableCounter clauseCounter output : List Bool) : machine.Cfg := + ⟨label, BinaryRenameLoop.clean () 0, + tapes permanent cursor reversed variableCounter clauseCounter output⟩ + +theorem initList_eq (input : List Bool) : + initList machine input = cfg (some .copyOut) input [] [] [] [] [] := by + unfold initList cfg + congr 1 + funext k + fin_cases k <;> simp [tapes, machine] + +theorem haltList_eq (output : List Bool) : + haltList machine output = cfg none [] [] [] [] [] output := by + unfold haltList cfg + congr 1 + funext k + fin_cases k <;> simp [tapes, machine] + +theorem copyTrace (input : List Bool) : + (advance machine.step)^[2 * (input.length + 1)] + (some (cfg (some .copyOut) input [] [] [] [] [])) = + some (cfg (some (.loop .entry)) input input [] [] [] []) := by + have updated : Function.update (tapes input [] [] [] [] []) 0 input = + tapes input input [] [] [] [] := by + funext k + fin_cases k <;> simp [tapes] + have h := MachineCopy.copyTrace (1 : Tape) 0 6 (by decide) (by decide) (by decide) + false .copyOut .copyBack (some (.loop .entry)) program rfl rfl + (tapes input [] [] [] [] []) (by simp [tapes]) + (BinaryRenameLoop.clean () 0).1 none + have first : tapes input [] [] [] [] [] 1 = input := rfl + have second : tapes input [] [] [] [] [] 0 = [] := rfl + rw [first, second, List.append_nil, updated] at h + exact h + +theorem restoreTrace (input body variableCounter clauseCounter : List Bool) : + (advance machine.step)^[body.length + 1] + (some (cfg (some .restore) input [] body.reverse variableCounter clauseCounter [])) = + some (cfg (some .clauseStart) input [] [] variableCounter clauseCounter body) := by + change (nextAt (11 : Tape) program)^[body.length + 1] + (some (cfg (some .restore) input [] body.reverse variableCounter clauseCounter [])) = _ + have updated : tapesAt (8 : Tape) 11 + (tapes input [] body.reverse variableCounter clauseCounter []) [] body = + tapes input [] [] variableCounter clauseCounter body := by + funext k + fin_cases k <;> simp [tapesAt, tapes] + have h := transferAt_fromTapes (Γ := Alphabet) (8 : Tape) 11 (by decide) id false + .restore (some .clauseStart) program rfl + (tapes input [] body.reverse variableCounter clauseCounter []) + (BinaryRenameLoop.clean () 0).1 none + have source : tapes input [] body.reverse variableCounter clauseCounter [] 8 = body.reverse := rfl + have output : tapes input [] body.reverse variableCounter clauseCounter [] 11 = [] := rfl + rw [source, output, List.length_reverse, List.reverse_reverse, List.map_id_fun, + List.append_nil, id_eq, updated] at h + exact h + +theorem headerTrace (input body : List Bool) (n m : Nat) : + (advance machine.step)^[n + m + 4] + (some (cfg (some .clauseStart) input [] [] + (List.replicate n true) (List.replicate m true) body)) = + some (cfg (some .cleanup) input [] [] [] [] + (encodeWord n ++ encodeWord m ++ body)) := by + change (advance (TM2.step program))^[n + m + 4] + (some ⟨some .clauseStart, ((BinaryRenameLoop.clean () 0).1, none), + tapes input [] [] (List.replicate n true) (List.replicate m true) body⟩) = + some ⟨some .cleanup, ((BinaryRenameLoop.clean () 0).1, none), + tapes input [] [] [] [] (encodeWord n ++ encodeWord m ++ body)⟩ + have updated (variableWord clauses output : List Bool) : + BinaryHeaderMachine.tapes (9 : Tape) 10 11 (tapes input [] [] [] [] []) + variableWord clauses output = tapes input [] [] variableWord clauses output := by + funext k + fin_cases k <;> simp [BinaryHeaderMachine.tapes, tapes] + have h := BinaryHeaderMachine.headerTrace (9 : Tape) 10 11 + (by decide) (by decide) (by decide) + .clauseStart .clauseLoop .variableStart .variableLoop (some .cleanup) program + rfl rfl rfl rfl (tapes input [] [] [] [] []) + (BinaryRenameLoop.clean () 0).1 n m body none + simp only [updated] at h + exact h + +theorem cleanupTrace (input output : List Bool) : + (advance machine.step)^[input.length + 1] + (some (cfg (some .cleanup) input [] [] [] [] output)) = + some (cfg none [] [] [] [] [] output) := by + change (advance (TM2.step program))^[input.length + 1] + (some ⟨some .cleanup, ((BinaryRenameLoop.clean () 0).1, none), + tapes input [] [] [] [] output⟩) = + some ⟨none, ((BinaryRenameLoop.clean () 0).1, none), tapes [] [] [] [] [] output⟩ + have updated (word : List Bool) : + Function.update (tapes [] [] [] [] [] output) 1 word = + tapes word [] [] [] [] output := by + funext k + fin_cases k <;> simp [tapes] + have h := MachineDrain.drainTrace (1 : Tape) .cleanup none program rfl + (tapes [] [] [] [] [] output) input (BinaryRenameLoop.clean () 0).1 none + simp only [updated] at h + exact h + +theorem outputBody_eq (formula : BinaryFormula.Formula) : + BinaryRenameLoop.outputBody (BinaryRenameWords.tokens formula.clauses) + (BinaryRenameWords.tokens formula.clauses) = BinaryRenameWords.body formula := by + change ((BinaryRenameWords.literals formula.clauses).map BinaryRenameWords.token).flatMap + (fun t => BinaryLiteralMachine.outputWord (BinaryRenameWords.tokens formula.clauses) + t.2 t.1) = (BinaryRenameWords.literals formula.clauses).flatMap + (BinaryRenameWords.outputLiteral (BinaryFormula.sourceNames formula)) + rw [List.flatMap_map] + apply List.flatMap_congr + intro literal _ + simp only [BinaryRenameWords.token, BinaryLiteralMachine.outputWord, + BinaryLiteralMachine.index, BinaryLiteralMachine.signWord, + BinaryRenameWords.payload_index, BinaryRenameWords.outputLiteral] + rfl + +theorem loopTrace (formula : BinaryFormula.Formula) : + (advance machine.step)^[BinaryRenameLoop.steps (BinaryRenameWords.tokens formula.clauses) + (BinaryRenameWords.tokens formula.clauses)] + (some (cfg (some (.loop .entry)) (BinaryTokenMachine.tokens formula.clauses) + (BinaryTokenMachine.tokens formula.clauses) [] [] [] [])) = + some (cfg (some .restore) (BinaryTokenMachine.tokens formula.clauses) [] + (BinaryRenameWords.body formula).reverse (List.replicate (3 * formula.clauses.length) true) + (List.replicate formula.clauses.length true) []) := by + change (advance (TM2.step program))^[BinaryRenameLoop.steps + (BinaryRenameWords.tokens formula.clauses) (BinaryRenameWords.tokens formula.clauses)] + (some ⟨some (.loop .entry), BinaryRenameLoop.clean () 0, + tapes (BinaryTokenMachine.tokens formula.clauses) (BinaryTokenMachine.tokens formula.clauses) + [] [] [] []⟩) = + some ⟨some .restore, BinaryRenameLoop.clean () 0, + tapes (BinaryTokenMachine.tokens formula.clauses) [] (BinaryRenameWords.body formula).reverse + (List.replicate (3 * formula.clauses.length) true) + (List.replicate formula.clauses.length true) []⟩ + let input := BinaryTokenMachine.tokens formula.clauses + have updated (cursor output variableWord clauseWord : List Bool) : + BinaryRenameLoop.loopTapes loopTapes (tapes input [] [] [] [] []) + cursor output variableWord clauseWord = + tapes input cursor output variableWord clauseWord [] := by + funext k + fin_cases k <;> simp [BinaryRenameLoop.loopTapes, loopTapes, tapes] + have scratch (i : Fin 11) (lo : 2 ≤ i.val) (hi : i.val ≤ 7) : + tapes input [] [] [] [] [] (loopTapes i) = [] := by + have n0 : loopTapes i ≠ 0 := by intro h; have := congrArg Fin.val h; simp [loopTapes] at this; omega + have n1 : loopTapes i ≠ 1 := by intro h; have := congrArg Fin.val h; simp [loopTapes] at this; omega + have n8 : loopTapes i ≠ 8 := by intro h; have := congrArg Fin.val h; simp [loopTapes] at this; omega + have n9 : loopTapes i ≠ 9 := by intro h; have := congrArg Fin.val h; simp [loopTapes] at this; omega + have n10 : loopTapes i ≠ 10 := by intro h; have := congrArg Fin.val h; simp [loopTapes] at this; omega + have n11 : loopTapes i ≠ 11 := by intro h; have := congrArg Fin.val h; simp [loopTapes] at this; omega + simp [tapes, n0, n1, n8, n9, n10, n11] + have run := BinaryRenameLoop.triplesTrace loopTapes loopTapes_injective Label.loop + (some .restore) (some .reject) program (fun _ => rfl) + (tapes input [] [] [] [] []) () + (BinaryRenameWords.tokens formula.clauses) (BinaryRenameWords.tokens formula.clauses) + formula.clauses.length (BinaryRenameWords.tokens_length formula.clauses) [] [] [] + (BinaryRenameWords.tokens_canonical formula.clauses) (fun _ h => h) + (by change input = _; rw [BinaryRenameWords.tokens_stream]) scratch + simp only [updated, BinaryRenameWords.tokens_stream, outputBody_eq, List.append_nil, input] at run + exact run + +private theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +def steps (formula : BinaryFormula.Formula) : Nat := + 2 * ((BinaryTokenMachine.tokens formula.clauses).length + 1) + + BinaryRenameLoop.steps (BinaryRenameWords.tokens formula.clauses) + (BinaryRenameWords.tokens formula.clauses) + + ((BinaryRenameWords.body formula).length + 1) + (4 * formula.clauses.length + 4) + + ((BinaryTokenMachine.tokens formula.clauses).length + 1) + +theorem renameTrace (formula : BinaryFormula.Formula) : + (advance machine.step)^[steps formula] + (some (initList machine (BinaryTokenMachine.tokens formula.clauses))) = + some (haltList machine (formulaBits (BinaryOccurrenceRename.renamed formula))) := by + have first := copyTrace (BinaryTokenMachine.tokens formula.clauses) + have second := loopTrace formula + have third := restoreTrace (BinaryTokenMachine.tokens formula.clauses) + (BinaryRenameWords.body formula) (List.replicate (3 * formula.clauses.length) true) + (List.replicate formula.clauses.length true) + have fourth := headerTrace (BinaryTokenMachine.tokens formula.clauses) + (BinaryRenameWords.body formula) (3 * formula.clauses.length) formula.clauses.length + have fifth := cleanupTrace (BinaryTokenMachine.tokens formula.clauses) + (encodeWord (3 * formula.clauses.length) ++ encodeWord formula.clauses.length ++ + BinaryRenameWords.body formula) + have full := joinTrace (joinTrace (joinTrace (joinTrace first second) third) fourth) fifth + have count : 3 * formula.clauses.length + formula.clauses.length + 4 = + 4 * formula.clauses.length + 4 := by omega + simpa only [steps, initList_eq, haltList_eq, BinaryRenameWords.encoded_renamed, count] using full + +theorem clause_count_le_stream (formula : BinaryFormula.Formula) : + formula.clauses.length ≤ (BinaryTokenMachine.tokens formula.clauses).length := by + rw [BinaryTokenMachine.tokens_length] + omega + +theorem body_length_le (formula : BinaryFormula.Formula) : + (BinaryRenameWords.body formula).length ≤ + 9 * (BinaryTokenMachine.tokens formula.clauses).length ^ 2 + + 10 * (BinaryTokenMachine.tokens formula.clauses).length + 2 := by + have initial := BinaryOccurrenceRename.renamed_encoding_bound formula + rw [BinaryRenameWords.encoded_renamed] at initial + simp only [List.length_append] at initial + have count := clause_count_le_stream formula + have square := Nat.mul_self_le_mul_self count + nlinarith + +noncomputable def timePolynomial : Polynomial Nat := + Polynomial.C 12 * Polynomial.X ^ 3 + Polynomial.C 35 * Polynomial.X ^ 2 + + Polynomial.C 28 * Polynomial.X + Polynomial.C 11 + +theorem steps_le (formula : BinaryFormula.Formula) : + steps formula ≤ timePolynomial.eval (BinaryTokenMachine.tokens formula.clauses).length := by + have loopBound := BinaryRenameLoop.steps_le + (BinaryRenameWords.tokens formula.clauses) (BinaryRenameWords.tokens formula.clauses) + (fun _ h => h) + rw [BinaryRenameWords.tokens_stream, BinaryRenameWords.tokens_length] at loopBound + have literalCount : 3 * formula.clauses.length ≤ + (BinaryTokenMachine.tokens formula.clauses).length := by + rw [BinaryTokenMachine.tokens_length] + omega + have product := Nat.mul_le_mul_left + (BinaryRenameLoop.perLiteralBound (BinaryTokenMachine.tokens formula.clauses).length) + literalCount + have output := body_length_le formula + have count := clause_count_le_stream formula + simp only [timePolynomial, Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_pow, + Polynomial.eval_C, Polynomial.eval_X] + unfold steps BinaryRenameLoop.perLiteralBound at * + nlinarith + +def outputsInTime (formula : BinaryFormula.Formula) : + TM2OutputsInTime machine (BinaryTokenMachine.tokens formula.clauses) + (some (formulaBits (BinaryOccurrenceRename.renamed formula))) + (timePolynomial.eval (BinaryTokenMachine.tokens formula.clauses).length) where + steps := steps formula + evals_in_steps := renameTrace formula + steps_le_m := steps_le formula + +noncomputable def tokenComputation : + TM2ComputableInPolyTime (fun formula : BinaryFormula.Formula => + BinaryTokenMachine.tokens formula.clauses) formulaBits BinaryOccurrenceRename.renamed where + tm := machine + inputAlphabet := Equiv.refl Bool + outputAlphabet := Equiv.refl Bool + time := timePolynomial + outputsFun formula := by + change TM2OutputsInTime machine ((BinaryTokenMachine.tokens formula.clauses).map id) + (some ((formulaBits (BinaryOccurrenceRename.renamed formula)).map id)) + (timePolynomial.eval (BinaryTokenMachine.tokens formula.clauses).length) + simpa only [List.map_id_fun, id_eq] using outputsInTime formula + +noncomputable def preprocessing : + TM2ComputableInPolyTime BinaryEncoding.formulaBits + (fun formula : BinaryFormula.Formula => BinaryTokenMachine.tokens formula.clauses) + (id : BinaryFormula.Formula → BinaryFormula.Formula) where + tm := BinaryTokenMachine.computableInPolyTime.tm + inputAlphabet := BinaryTokenMachine.computableInPolyTime.inputAlphabet + outputAlphabet := BinaryTokenMachine.computableInPolyTime.outputAlphabet + time := BinaryTokenMachine.computableInPolyTime.time + outputsFun := BinaryTokenMachine.computableInPolyTime.outputsFun + +noncomputable def computableInPolyTime : + TM2ComputableInPolyTime BinaryEncoding.formulaBits formulaBits + BinaryOccurrenceRename.renamed := + MachineSequential.composeBits preprocessing tokenComputation + +theorem machine_finiteAlphabet (k : machine.K) : Finite (machine.Γ k) := by + change Finite Bool + infer_instance + +theorem computation_finiteAlphabet : MachineFiniteAlphabet.FiniteAlphabet computableInPolyTime.tm := + MachineFiniteAlphabet.composeBits preprocessing tokenComputation + BinaryTokenMachine.machine_finiteAlphabet machine_finiteAlphabet + +end MinUncutGames.BinaryRenameMachine + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineCanonicalOutput.lean b/lean/OAI/Computability/MinUncut/Machines/MachineCanonicalOutput.lean new file mode 100644 index 0000000000000000000000000000000000000000..335907abf5bc33ef7aa9542053a3aa21faee9d23 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineCanonicalOutput.lean @@ -0,0 +1,273 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineFiniteAlphabet + +namespace OAI + +namespace MinUncutGames.Foundations.Complexity.MachineCanonicalOutput + +open Turing MachineComposition + +structure Program (K Λ σ : Type) where + input : K + output : K + main : Λ + initial : σ + code : Λ → TM2.Stmt (fun _ : K => Bool) Λ σ + +section Structural + +variable {K Λ Λ' σ : Type} [DecidableEq K] + +def extendedLabel (labels : Λ → Λ') (haltTarget : Option Λ') : Option Λ → Option Λ' + | none => haltTarget + | some label => some (labels label) + +def extendedCfg (labels : Λ → Λ') (haltTarget : Option Λ') (register : Option Bool) + (cfg : TM2.Cfg (fun _ : K => Bool) Λ σ) : + TM2.Cfg (fun _ : K => Bool) Λ' (σ × Option Bool) := + ⟨extendedLabel labels haltTarget cfg.l, (cfg.var, register), cfg.stk⟩ + +def extendedStmt (labels : Λ → Λ') (haltTarget : Option Λ') : + TM2.Stmt (fun _ : K => Bool) Λ σ → + TM2.Stmt (fun _ : K => Bool) Λ' (σ × Option Bool) + | .push k f next => .push k (fun state => f state.1) + (extendedStmt labels haltTarget next) + | .peek k f next => .peek k (fun state symbol => (f state.1 symbol, state.2)) + (extendedStmt labels haltTarget next) + | .pop k f next => .pop k (fun state symbol => (f state.1 symbol, state.2)) + (extendedStmt labels haltTarget next) + | .load f next => .load (fun state => (f state.1, state.2)) + (extendedStmt labels haltTarget next) + | .branch test yes no => .branch (fun state => test state.1) + (extendedStmt labels haltTarget yes) (extendedStmt labels haltTarget no) + | .goto label => .goto (fun state => labels (label state.1)) + | .halt => match haltTarget with + | none => .halt + | some label => .goto (fun _ => label) + +theorem stepAux_extended (labels : Λ → Λ') (haltTarget : Option Λ') + (stmt : TM2.Stmt (fun _ : K => Bool) Λ σ) (state : σ) + (register : Option Bool) (tapes : K → List Bool) : + TM2.stepAux (extendedStmt labels haltTarget stmt) (state, register) tapes = + extendedCfg labels haltTarget register (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 [extendedStmt, TM2.stepAux, h, Bool.cond_false] using ihNo state tapes + | true => + simpa only [extendedStmt, TM2.stepAux, h, Bool.cond_true] using ihYes state tapes + | goto label => rfl + | halt => cases haltTarget <;> rfl + +end Structural + +variable {K Λ σ : Type} [DecidableEq K] [Fintype K] [Fintype Λ] [Fintype σ] + +def sourceMachine (P : Program K Λ σ) : FinTM2 where + K := K + k₀ := P.input + k₁ := P.output + Γ _ := Bool + Λ := Λ + main := P.main + σ := σ + initialState := P.initial + m := P.code + +abbrev Label (Λ : Type) (chosen : List K) := Λ ⊕ (MachineDrainMany.Label chosen ⊕ Unit) + +def cleanupLabel (chosen : List K) : MachineDrainMany.Label chosen → Label Λ chosen := + fun label => .inr (.inl label) + +def resetLabel (chosen : List K) : Label Λ chosen := .inr (.inr ()) + +def cleanupEntry (chosen : List K) : Option (Label Λ chosen) := + MachineDrainMany.entry chosen (cleanupLabel chosen) (some (resetLabel chosen)) + +def completedProgram (P : Program K Λ σ) (chosen : List K) : + Label Λ chosen → TM2.Stmt (fun _ : K => Bool) (Label Λ chosen) (σ × Option Bool) + | .inl label => extendedStmt Sum.inl (cleanupEntry chosen) (P.code label) + | .inr (.inl label) => MachineDrainMany.instruction chosen (cleanupLabel chosen) + (some (resetLabel chosen)) label + | .inr (.inr _) => .load (fun _ => (P.initial, none)) .halt + +def completedMachine (P : Program K Λ σ) (chosen : List K) : FinTM2 where + K := K + k₀ := P.input + k₁ := P.output + Γ _ := Bool + Λ := Label Λ chosen + main := .inl P.main + σ := σ × Option Bool + initialState := (P.initial, none) + m := completedProgram P chosen + +theorem finiteAlphabet (P : Program K Λ σ) (chosen : List K) : + MachineFiniteAlphabet.FiniteAlphabet (completedMachine P chosen) := by + intro k + exact inferInstanceAs (Finite Bool) + +def embeddedCfg (P : Program K Λ σ) (chosen : List K) + (cfg : (sourceMachine P).Cfg) : (completedMachine P chosen).Cfg := + extendedCfg Sum.inl (cleanupEntry chosen) none cfg + +theorem step_simulation (P : Program K Λ σ) (chosen : List K) + (a b : (sourceMachine P).Cfg) (step : (sourceMachine P).step a = some b) : + (completedMachine P chosen).step (embeddedCfg P chosen a) = + some (embeddedCfg P chosen 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 (P.code label) state tapes = b := Option.some.inj step + rw [← hb] + change some (TM2.stepAux + (extendedStmt Sum.inl (cleanupEntry chosen) (P.code label)) (state, none) tapes) = _ + erw [stepAux_extended]; rfl + +@[simp] theorem embedded_init (P : Program K Λ σ) (chosen : List K) (input : List Bool) : + embeddedCfg P chosen (initList (sourceMachine P) input) = + initList (completedMachine P chosen) input := rfl + +omit [Fintype K] [Fintype Λ] [Fintype σ] in +theorem finalTapes_eq (P : Program K Λ σ) (chosen : List K) + (complete : ∀ k, k ∈ chosen ↔ k ≠ P.output) (base : K → List Bool) : + MachineDrainMany.finalTapes chosen base = + MachineDrainMany.haltTapes P.output (base P.output) := by + funext k + rw [MachineDrainMany.finalTapes_apply] + by_cases h : k = P.output + · subst k + simp [MachineDrainMany.haltTapes, complete] + · simp [MachineDrainMany.haltTapes, complete, h] + +theorem haltList_eq (P : Program K Λ σ) (chosen : List K) (output : List Bool) : + haltList (completedMachine P chosen) output = + ⟨none, (P.initial, none), MachineDrainMany.haltTapes P.output output⟩ := by + congr 1 + +def cleanupExecution (P : Program K Λ σ) (chosen : List K) + (complete : ∀ k, k ∈ chosen ↔ k ≠ P.output) (state : σ) + (register : Option Bool) (base : K → List Bool) : + StateTransition.EvalsToInTime (completedMachine P chosen).step + ⟨cleanupEntry chosen, (state, register), base⟩ + (some (haltList (completedMachine P chosen) (base P.output))) + (MachineDrainMany.steps chosen base + 1) := by + let after : (completedMachine P chosen).Cfg := + ⟨some (resetLabel chosen), (state, MachineDrainMany.finalRegister chosen register), + MachineDrainMany.finalTapes chosen base⟩ + have drains : StateTransition.EvalsToInTime (completedMachine P chosen).step + ⟨cleanupEntry chosen, (state, register), base⟩ (some after) + (MachineDrainMany.steps chosen base) := { + steps := MachineDrainMany.steps chosen base + evals_in_steps := MachineDrainMany.trace chosen (cleanupLabel chosen) + (some (resetLabel chosen)) (completedProgram P chosen) (fun _ => rfl) base state register + steps_le_m := le_rfl } + have reset : StateTransition.EvalsToInTime (completedMachine P chosen).step + after (some (haltList (completedMachine P chosen) (base P.output))) 1 := { + steps := 1 + evals_in_steps := by + change some (⟨none, (P.initial, none), MachineDrainMany.finalTapes chosen base⟩ : + (completedMachine P chosen).Cfg) = + some (haltList (completedMachine P chosen) (base P.output)) + erw [finalTapes_eq P chosen complete, 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 (P : Program K Λ σ) (chosen : List K) + (complete : ∀ k, k ∈ chosen ↔ k ≠ P.output) + (input output : List Bool) (state : σ) (base : K → List Bool) (budget : Nat) + (raw : StateTransition.EvalsToInTime (sourceMachine P).step + (initList (sourceMachine P) input) (some ⟨none, state, base⟩) budget) + (correctOutput : base P.output = output) : + TM2OutputsInTime (completedMachine P chosen) input (some output) + (budget + chosen.length * + (input.length + budget * Runtime.programPushBound (sourceMachine P) + 1) + 1) := by + let lifted := liftExecutionInTime (sourceMachine P).step + (completedMachine P chosen).step (embeddedCfg P chosen) (step_simulation P chosen) raw + have joined := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ lifted + (cleanupExecution P chosen complete state none base) + have stackBound : ∀ k, (base k).length ≤ + input.length + budget * Runtime.programPushBound (sourceMachine P) := by + intro k + have h := Runtime.executionSizeBound (sourceMachine P).step + (fun cfg => (cfg.stk k).length) (Runtime.programPushBound (sourceMachine P)) + (Runtime.stepStackLength (sourceMachine P) k) raw + exact h.trans (Nat.add_le_add_right (Runtime.initialStackLength (sourceMachine P) input k) _) + have cleanupBound := MachineDrainMany.steps_le_uniform chosen base _ stackBound + rw [embedded_init, correctOutput] at joined + exact { toEvalsTo := joined.toEvalsTo + steps_le_m := joined.steps_le_m.trans (by omega) } + +noncomputable def completedTime (P : Program K Λ σ) (chosen : List K) + (rawTime : Polynomial Nat) : Polynomial Nat := + rawTime + Polynomial.C chosen.length * + (Polynomial.X + rawTime * Polynomial.C (Runtime.programPushBound (sourceMachine P)) + 1) + 1 + +theorem completedTime_eval (P : Program K Λ σ) (chosen : List K) + (rawTime : Polynomial Nat) (n : Nat) : + (completedTime P chosen rawTime).eval n = + rawTime.eval n + chosen.length * + (n + rawTime.eval n * Runtime.programPushBound (sourceMachine P) + 1) + 1 := by + simp [completedTime] + +structure TerminalRun (P : Program K Λ σ) (input output : List Bool) (budget : Nat) where + state : σ + tapes : K → List Bool + execution : StateTransition.EvalsToInTime (sourceMachine P).step + (initList (sourceMachine P) input) (some ⟨none, state, tapes⟩) budget + output_eq : tapes P.output = output + +noncomputable def computableInPolyTime {α β : Type} + (P : Program K Λ σ) (chosen : List K) + (complete : ∀ k, k ∈ chosen ↔ k ≠ P.output) + (encodeIn : α → List Bool) (encodeOut : β → List Bool) (f : α → β) + (rawTime : Polynomial Nat) + (run : ∀ a, TerminalRun P (encodeIn a) (encodeOut (f a)) + (rawTime.eval (encodeIn a).length)) : + TM2ComputableInPolyTime encodeIn encodeOut f where + tm := completedMachine P chosen + inputAlphabet := Equiv.refl Bool + outputAlphabet := Equiv.refl Bool + time := completedTime P chosen rawTime + outputsFun a := by + change TM2OutputsInTime (completedMachine P chosen) ((encodeIn a).map id) + (some ((encodeOut (f a)).map id)) ((completedTime P chosen rawTime).eval _) + erw [List.map_id, List.map_id, completedTime_eval] + exact outputsInTime P chosen complete _ _ (run a).state (run a).tapes _ + (run a).execution (run a).output_eq + +theorem computableInPolyTime_finite_alphabet {α β : Type} + (P : Program K Λ σ) (chosen : List K) + (complete : ∀ k, k ∈ chosen ↔ k ≠ P.output) + (encodeIn : α → List Bool) (encodeOut : β → List Bool) (f : α → β) + (rawTime : Polynomial Nat) + (run : ∀ a, TerminalRun P (encodeIn a) (encodeOut (f a)) + (rawTime.eval (encodeIn a).length)) : + MachineFiniteAlphabet.FiniteAlphabet + (computableInPolyTime P chosen complete encodeIn encodeOut f rawTime run).tm := + finiteAlphabet P chosen + +noncomputable def computableInPolyTimeOfEnumeration {α β : Type} {N : Nat} + (P : Program K Λ σ) (enumeration : Fin N ≃ K) + (encodeIn : α → List Bool) (encodeOut : β → List Bool) (f : α → β) + (rawTime : Polynomial Nat) + (run : ∀ a, TerminalRun P (encodeIn a) (encodeOut (f a)) + (rawTime.eval (encodeIn a).length)) : + TM2ComputableInPolyTime encodeIn encodeOut f := + computableInPolyTime P (MachineDrainMany.workTapes enumeration P.output) + (fun k => MachineDrainMany.mem_workTapes enumeration P.output k) + encodeIn encodeOut f rawTime run + +end MinUncutGames.Foundations.Complexity.MachineCanonicalOutput + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineCloudCount.lean b/lean/OAI/Computability/MinUncut/Machines/MachineCloudCount.lean new file mode 100644 index 0000000000000000000000000000000000000000..0448d578055bb938c06e124f19314f657016e3f0 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineCloudCount.lean @@ -0,0 +1,1044 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.ExpanderFamily + +namespace OAI + +section +namespace MinUncutGames.Foundations.Complexity.MachineCloudCount + +open Turing +open MachineComposition + +inductive Tape + | original | work | target | scratch | count | spare + deriving DecidableEq + +protected abbrev Tape.enumList : List Tape := [.original, .work, .target, .scratch, .count, + .spare] + +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 + +abbrev Alphabet (_ : Tape) := Bool +abbrev State (σ : Type) := (σ × Bool) × Option Bool + +def memory (original work target scratch count spare : List Bool) : Tape → List Bool + | .original => original + | .work => work + | .target => target + | .scratch => scratch + | .count => count + | .spare => spare + +@[simp] theorem memory_original (a b c d e f : List Bool) : + memory a b c d e f .original = a := rfl +@[simp] theorem memory_work (a b c d e f : List Bool) : + memory a b c d e f .work = b := rfl +@[simp] theorem memory_target (a b c d e f : List Bool) : + memory a b c d e f .target = c := rfl +@[simp] theorem memory_scratch (a b c d e f : List Bool) : + memory a b c d e f .scratch = d := rfl +@[simp] theorem memory_count (a b c d e f : List Bool) : + memory a b c d e f .count = e := rfl +@[simp] theorem memory_spare (a b c d e f : List Bool) : + memory a b c d e f .spare = f := rfl + +@[simp] theorem update_memory_work (a b c d e f x : List Bool) : + Function.update (memory a b c d e f) .work x = memory a x c d e f := by + funext k + cases k <;> rfl +@[simp] theorem update_memory_target (a b c d e f x : List Bool) : + Function.update (memory a b c d e f) .target x = memory a b x d e f := by + funext k + cases k <;> rfl +@[simp] theorem update_memory_scratch (a b c d e f x : List Bool) : + Function.update (memory a b c d e f) .scratch x = memory a b c x e f := by + funext k + cases k <;> rfl +@[simp] theorem update_memory_count (a b c d e f x : List Bool) : + Function.update (memory a b c d e f) .count x = memory a b c d x f := by + funext k + cases k <;> rfl + +variable {Λ σ : Type} + +def finishField (restore : Λ) : TM2.Stmt Alphabet Λ (State σ) := + .load (fun state => ((state.1.1, false), none)) (.goto fun _ => restore) + +def fieldLoop (again restore : Λ) : TM2.Stmt Alphabet Λ (State σ) := + .pop .work (fun state head => (state.1, head)) + (.branch (fun state => state.2.getD false) + (.peek .target (fun state head => (state.1, head)) + (.branch (fun state => state.2.getD false) + (.pop .target (fun state _ => (state.1, none)) + (.push .scratch (fun _ => true) (.goto fun _ => again))) + (.load (fun state => ((state.1.1, true), none)) (.goto fun _ => again)))) + (.peek .target (fun state head => (state.1, head)) + (.branch (fun state => !state.1.2 && !(state.2.getD false)) + (.push .count (fun _ => true) (finishField restore)) + (finishField restore)))) + +def hit (flag : Bool) (x v : Nat) : Nat := if flag = false ∧ x = v then 1 else 0 + +theorem fieldStep_zero (again restore : Λ) + (program : Λ → TM2.Stmt Alphabet Λ (State σ)) + (atField : program again = fieldLoop again restore) + (original suffix targetSuffix spare : List Bool) (v : Nat) + (scratch count : List Bool) (ambient : σ) (flag : Bool) (register : Option Bool) : + TM2.step program + ⟨some again, ((ambient, flag), register), + memory original (encodeWord 0 ++ suffix) (encodeWord v ++ targetSuffix) + scratch count spare⟩ = + some ⟨some restore, ((ambient, false), none), + memory original suffix (encodeWord v ++ targetSuffix) scratch + (List.replicate (hit flag 0 v) true ++ count) spare⟩ := by + change some (TM2.stepAux (program again) _ _) = _ + rw [atField] + cases v <;> cases flag <;> + simp [fieldLoop, finishField, TM2.stepAux, encodeWord, hit, List.replicate_succ] + +theorem fieldStep_succ_zero (again restore : Λ) + (program : Λ → TM2.Stmt Alphabet Λ (State σ)) + (atField : program again = fieldLoop again restore) + (original suffix targetSuffix spare : List Bool) (x : Nat) + (scratch count : List Bool) (ambient : σ) (flag : Bool) (register : Option Bool) : + TM2.step program + ⟨some again, ((ambient, flag), register), + memory original (encodeWord (x + 1) ++ suffix) (encodeWord 0 ++ targetSuffix) + scratch count spare⟩ = + some ⟨some again, ((ambient, true), none), + memory original (encodeWord x ++ suffix) (encodeWord 0 ++ targetSuffix) + scratch count spare⟩ := by + change some (TM2.stepAux (program again) _ _) = _ + rw [atField] + simp [fieldLoop, TM2.stepAux, encodeWord, List.replicate_succ] + +theorem fieldStep_succ_succ (again restore : Λ) + (program : Λ → TM2.Stmt Alphabet Λ (State σ)) + (atField : program again = fieldLoop again restore) + (original suffix targetSuffix spare : List Bool) (x v : Nat) + (scratch count : List Bool) (ambient : σ) (flag : Bool) (register : Option Bool) : + TM2.step program + ⟨some again, ((ambient, flag), register), + memory original (encodeWord (x + 1) ++ suffix) + (encodeWord (v + 1) ++ targetSuffix) scratch count spare⟩ = + some ⟨some again, ((ambient, flag), none), + memory original (encodeWord x ++ suffix) (encodeWord v ++ targetSuffix) + (true :: scratch) count spare⟩ := by + change some (TM2.stepAux (program again) _ _) = _ + rw [atField] + simp [fieldLoop, TM2.stepAux, encodeWord, List.replicate_succ] + +theorem fieldTrace (again restore : Λ) + (program : Λ → TM2.Stmt Alphabet Λ (State σ)) + (atField : program again = fieldLoop again restore) + (original suffix targetSuffix spare : List Bool) (x v : Nat) + (scratch count : List Bool) (ambient : σ) (flag : Bool) (register : Option Bool) : + (advance (TM2.step program))^[x + 1] + (some ⟨some again, ((ambient, flag), register), + memory original (encodeWord x ++ suffix) (encodeWord v ++ targetSuffix) + scratch count spare⟩) = + some ⟨some restore, ((ambient, false), none), + memory original suffix (encodeWord (v - x) ++ targetSuffix) + (List.replicate (min x v) true ++ scratch) + (List.replicate (hit flag x v) true ++ count) spare⟩ := by + induction x generalizing v scratch flag register with + | zero => + simpa only [Nat.zero_add, Function.iterate_one, advance_some, Nat.sub_zero, + Nat.zero_min, List.replicate_zero, List.nil_append] using + fieldStep_zero again restore program atField original suffix targetSuffix spare v + scratch count ambient flag register + | succ x ih => + rw [Function.iterate_succ_apply] + change (advance (TM2.step program))^[x + 1] + (TM2.step program ⟨some again, ((ambient, flag), register), + memory original (encodeWord (x + 1) ++ suffix) (encodeWord v ++ targetSuffix) + scratch count spare⟩) = _ + cases v with + | zero => + rw [fieldStep_succ_zero again restore program atField] + simpa [hit] using ih 0 scratch true none + | succ v => + rw [fieldStep_succ_succ again restore program atField] + simpa [hit, Nat.succ_min_succ, List.replicate_succ', List.append_assoc] using + ih v (true :: scratch) flag none + +theorem replicate_encodeWord (a b : Nat) : + List.replicate a true ++ encodeWord b = encodeWord (a + b) := by + simp only [encodeWord, ← List.append_assoc, List.replicate_append_replicate] + +theorem preservingFieldTrace (again restore next : Λ) + (program : Λ → TM2.Stmt Alphabet Λ (State σ)) + (atField : program again = fieldLoop again restore) + (atRestore : program restore = Reduction.MachineTransfer.loopAt + .scratch .target id false restore (some next)) + (original suffix targetSuffix count spare : List Bool) (x v : Nat) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[x + min x v + 2] + (some ⟨some again, ((ambient, false), register), + memory original (encodeWord x ++ suffix) (encodeWord v ++ targetSuffix) + [] count spare⟩) = + some ⟨some next, ((ambient, false), none), + memory original suffix (encodeWord v ++ targetSuffix) [] + (List.replicate (if x = v then 1 else 0) true ++ count) spare⟩ := by + have hfield := fieldTrace again restore program atField original suffix targetSuffix spare + x v [] count ambient false register + simp only [List.append_nil, hit, true_and] at hfield + let after := memory original suffix (encodeWord (v - x) ++ targetSuffix) + (List.replicate (min x v) true) + (List.replicate (if x = v then 1 else 0) true ++ count) spare + have hrestore := Reduction.MachineTransfer.transferAt_fromTapes + Tape.scratch Tape.target (by decide) id false restore (some next) program atRestore + after (ambient, false) none + have hsum : min x v + (v - x) = v := by omega + simp only [after, memory_scratch, memory_target, List.length_replicate, + List.reverse_replicate, List.map_id, Reduction.MachineTransfer.tapesAt, + update_memory_scratch, update_memory_target] at hrestore + rw [← List.append_assoc, replicate_encodeWord, hsum] at hrestore + rw [show x + min x v + 2 = (min x v + 1) + (x + 1) by omega, + Function.iterate_add_apply, hfield] + exact hrestore + +def preservingFieldInTime (again restore next : Λ) + (program : Λ → TM2.Stmt Alphabet Λ (State σ)) + (atField : program again = fieldLoop again restore) + (atRestore : program restore = Reduction.MachineTransfer.loopAt + .scratch .target id false restore (some next)) + (original suffix targetSuffix count spare : List Bool) (x v : Nat) + (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some again, ((ambient, false), register), + memory original (encodeWord x ++ suffix) (encodeWord v ++ targetSuffix) + [] count spare⟩ + (some ⟨some next, ((ambient, false), none), + memory original suffix (encodeWord v ++ targetSuffix) [] + (List.replicate (if x = v then 1 else 0) true ++ count) spare⟩) + (2 * x + 2) where + steps := x + min x v + 2 + evals_in_steps := preservingFieldTrace again restore next program atField atRestore + original suffix targetSuffix count spare x v ambient register + steps_le_m := by have h := Nat.min_le_left x v; omega + +theorem discardFieldsTrace (labels : Nat → Λ) + (program : Λ → TM2.Stmt Alphabet Λ (State σ)) + (fields : List Nat) (offset : Nat) + (atField : ∀ i, i < fields.length → program (labels (offset + i)) = + MachineLookup.discard .work (labels (offset + i)) (labels (offset + i + 1))) + (original suffix target scratch count spare : List Bool) + (ambient : σ) (flag : Bool) (register : Option Bool) : + (advance (TM2.step program))^[(encodeWords fields).length] + (some ⟨some (labels offset), ((ambient, flag), register), + memory original (encodeWords fields ++ suffix) target scratch count spare⟩) = + some ⟨some (labels (offset + fields.length)), + ((ambient, flag), if fields = [] then register else none), + memory original suffix target scratch count spare⟩ := by + induction fields generalizing offset register with + | nil => simp only [encodeWords, List.length_nil, Function.iterate_zero_apply, + List.nil_append, Nat.add_zero, ↓reduceIte] + | cons x fields ih => + have hfirst := MachineLookup.discardTrace Tape.work (labels offset) (labels (offset + 1)) + program (by simpa only [Nat.add_zero] using atField 0 (by simp)) + (memory original (encodeWords (x :: fields) ++ suffix) target scratch count spare) + x (encodeWords fields ++ suffix) (by simp only [memory_work, encodeWords, List.append_assoc]) + (ambient, flag) register + simp only [update_memory_work] at hfirst + have hrest := ih (offset + 1) (by + intro i hi + have h := atField (i + 1) (by simpa only [List.length_cons] using Nat.succ_lt_succ hi) + simpa only [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using h) none + rw [show (encodeWords (x :: fields)).length = + (encodeWords fields).length + (x + 1) by + simp only [encodeWords, List.length_append, encodeWord_length] + omega, + Function.iterate_add_apply, hfirst] + simpa only [List.length_cons, List.cons_ne_nil, + ite_false, ite_self, Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using hrest + +inductive Label + | copyFirst | copySecond | headerFirst | headerSecond | row | field | restore + | skip (i : Fin 4097) + deriving DecidableEq, Fintype + +def skipLabel (i : Nat) : Label := + if h : i < 4097 then .skip ⟨i, h⟩ else .row + +def rowEntry : TM2.Stmt Alphabet Label (State σ) := + .peek .work (fun state head => (state.1, head)) + (.branch (fun state => state.2.isSome) + (.load (fun state => ((state.1.1, false), none)) (.goto fun _ => .field)) + (.load (fun state => ((state.1.1, false), none)) .halt)) + +def program : Label → TM2.Stmt Alphabet Label (State σ) + | .copyFirst => Reduction.MachineTransfer.loopAt + .original .spare id false .copyFirst (some .copySecond) + | .copySecond => MachineCopy.forkLoop + .spare .original .work false .copySecond (some .headerFirst) + | .headerFirst => MachineLookup.discard .work .headerFirst .headerSecond + | .headerSecond => MachineLookup.discard .work .headerSecond .row + | .row => rowEntry + | .field => fieldLoop .field .restore + | .restore => Reduction.MachineTransfer.loopAt + .scratch .target id false .restore (some (skipLabel 0)) + | .skip i => MachineLookup.discard .work (.skip i) (skipLabel (i.val + 1)) + +theorem program_skip {i : Nat} (hi : i < 4097) : + program (σ := σ) (skipLabel i) = + MachineLookup.discard .work (skipLabel i) (skipLabel (i + 1)) := by + simp only [skipLabel, dite_eq_left hi, program] + +theorem rowStep_nonempty (original work target scratch count spare : List Bool) + (hwork : work ≠ []) (ambient : σ) (flag : Bool) (register : Option Bool) : + TM2.step (program (σ := σ)) + ⟨some .row, ((ambient, flag), register), memory original work target scratch count spare⟩ = + some ⟨some .field, ((ambient, false), none), + memory original work target scratch count spare⟩ := by + cases work with + | nil => exact (hwork rfl).elim + | cons x xs => rfl + +theorem rowStep_empty (original target scratch count spare : List Bool) + (ambient : σ) (flag : Bool) (register : Option Bool) : + TM2.step (program (σ := σ)) + ⟨some .row, ((ambient, flag), register), memory original [] target scratch count spare⟩ = + some ⟨none, ((ambient, false), none), memory original [] target scratch count spare⟩ := rfl + +abbrev Row := Nat × List Nat + +def rowWords (r : Row) : List Nat := r.1 :: r.2 + +def rowTime (v : Nat) (r : Row) : Nat := + (encodeWords (rowWords r)).length + min r.1 v + 2 + +theorem rowTrace (r : Row) (hwidth : r.2.length = 4097) (v : Nat) + (original suffix targetSuffix count spare : List Bool) (ambient : σ) + (register : Option Bool) : + (advance (TM2.step (program (σ := σ))))^[rowTime v r] + (some ⟨some .row, ((ambient, false), register), + memory original (encodeWords (rowWords r) ++ suffix) (encodeWord v ++ targetSuffix) + [] count spare⟩) = + some ⟨some .row, ((ambient, false), none), + memory original suffix (encodeWord v ++ targetSuffix) [] + (List.replicate (if r.1 = v then 1 else 0) true ++ count) spare⟩ := by + have hfield := preservingFieldTrace Label.field Label.restore (skipLabel 0) + program rfl rfl original (encodeWords r.2 ++ suffix) targetSuffix count spare r.1 v ambient none + have hskip := discardFieldsTrace skipLabel (program (σ := σ)) r.2 0 + (by intro i hi; simpa only [Nat.zero_add] using program_skip (hwidth ▸ hi)) + original suffix (encodeWord v ++ targetSuffix) [] + (List.replicate (if r.1 = v then 1 else 0) true ++ count) spare ambient false none + have hnonempty : r.2 ≠ [] := by intro h; simp [h] at hwidth + simp only [Nat.zero_add, hwidth, skipLabel, lt_self_iff_false, ↓reduceDIte, + hnonempty, ite_false] at hskip + have htime : rowTime v r = (encodeWords r.2).length + (r.1 + min r.1 v + 2) + 1 := by + simp only [rowTime, rowWords, encodeWords, List.length_append, encodeWord_length] + omega + rw [htime, Function.iterate_succ_apply] + change (advance (TM2.step (program (σ := σ))))^[ + (encodeWords r.2).length + (r.1 + min r.1 v + 2)] + (TM2.step program ⟨some .row, ((ambient, false), register), + memory original (encodeWords (rowWords r) ++ suffix) (encodeWord v ++ targetSuffix) + [] count spare⟩) = _ + rw [rowStep_nonempty original _ _ [] count spare + (by simp [rowWords, encodeWords, encodeWord]) ambient false register, + Function.iterate_add_apply] + simp only [rowWords, encodeWords, List.append_assoc] + rw [hfield] + exact hskip + +def rowsHits (v : Nat) : List Row → Nat + | [] => 0 + | r :: rs => (if r.1 = v then 1 else 0) + rowsHits v rs + +def rowsTime (v : Nat) : List Row → Nat + | [] => 1 + | r :: rs => rowsTime v rs + rowTime v r + +theorem rowsTrace (rs : List Row) (hwidth : ∀ r ∈ rs, r.2.length = 4097) (v : Nat) + (original targetSuffix count spare : List Bool) (ambient : σ) (register : Option Bool) : + (advance (TM2.step (program (σ := σ))))^[rowsTime v rs] + (some ⟨some .row, ((ambient, false), register), + memory original (encodeWords (rs.flatMap rowWords)) (encodeWord v ++ targetSuffix) + [] count spare⟩) = + some ⟨none, ((ambient, false), none), + memory original [] (encodeWord v ++ targetSuffix) [] + (List.replicate (rowsHits v rs) true ++ count) spare⟩ := by + induction rs generalizing count register with + | nil => + simpa only [rowsTime, List.flatMap_nil, encodeWords, Function.iterate_one, advance_some, + rowsHits, List.replicate_zero, List.nil_append] using + rowStep_empty original (encodeWord v ++ targetSuffix) [] count spare ambient false register + | cons r rs ih => + have hrow := rowTrace r (hwidth r (by simp)) v original + (encodeWords (rs.flatMap rowWords)) targetSuffix count spare ambient register + have hrest := ih (by intro x hx; exact hwidth x (by simp [hx])) + (List.replicate (if r.1 = v then 1 else 0) true ++ count) none + simp only [rowsTime, List.flatMap_cons, encodeWords_append] + rw [Function.iterate_add_apply, hrow] + simpa only [rowsHits, ← List.append_assoc, List.replicate_append_replicate, + Nat.add_comm] using hrest + +theorem rowTime_le (v : Nat) (r : Row) : + rowTime v r ≤ 3 * (encodeWords (rowWords r)).length := by + have hmin := Nat.min_le_left r.1 v + have hlen : r.1 + 1 ≤ (encodeWords (rowWords r)).length := by + simp only [rowWords, encodeWords, List.length_append, encodeWord_length] + omega + unfold rowTime + omega + +theorem rowsTime_le (v : Nat) (rs : List Row) : + rowsTime v rs ≤ 3 * (encodeWords (rs.flatMap rowWords)).length + 1 := by + induction rs with + | nil => simp only [rowsTime, List.flatMap_nil, encodeWords, List.length_nil, + Nat.mul_zero, Nat.zero_add, le_refl] + | cons r rs ih => + have hr := rowTime_le v r + simp only [rowsTime, List.flatMap_cons, encodeWords_append, List.length_append] + omega + +def inputWord (n m : Nat) (rs : List Row) : List Bool := + encodeWords ([n, m] ++ rs.flatMap rowWords) + +theorem inputWord_eq (n m : Nat) (rs : List Row) : + inputWord n m rs = encodeWord n ++ (encodeWord m ++ encodeWords (rs.flatMap rowWords)) := by + simp only [inputWord, encodeWords_append, encodeWords, List.append_nil, List.append_assoc] + +theorem inputWord_length (n m : Nat) (rs : List Row) : + (inputWord n m rs).length = n + 1 + (m + 1) + + (encodeWords (rs.flatMap rowWords)).length := by + rw [inputWord_eq] + simp only [List.length_append, encodeWord_length] + omega + +def totalSteps (n m v : Nat) (rs : List Row) : Nat := + 2 * ((inputWord n m rs).length + 1) + (n + 1) + (m + 1) + rowsTime v rs + +theorem countTrace (n m v : Nat) (rs : List Row) + (hwidth : ∀ r ∈ rs, r.2.length = 4097) + (targetSuffix count : List Bool) (ambient : σ) (register : Option Bool) : + (advance (TM2.step (program (σ := σ))))^[totalSteps n m v rs] + (some ⟨some .copyFirst, ((ambient, false), register), + memory (inputWord n m rs) [] (encodeWord v ++ targetSuffix) [] count []⟩) = + some ⟨none, ((ambient, false), none), + memory (inputWord n m rs) [] (encodeWord v ++ targetSuffix) [] + (List.replicate (rowsHits v rs) true ++ count) []⟩ := by + have hcopy := MachineCopy.copyTrace Tape.original Tape.work Tape.spare + (by decide) (by decide) (by decide) false Label.copyFirst Label.copySecond + (some Label.headerFirst) program rfl rfl + (memory (inputWord n m rs) [] (encodeWord v ++ targetSuffix) [] count []) + rfl (ambient, false) register + simp only [memory_original, memory_work, List.append_nil, update_memory_work] at hcopy + have hfirst := MachineLookup.discardTrace Tape.work Label.headerFirst Label.headerSecond + program rfl + (memory (inputWord n m rs) (inputWord n m rs) (encodeWord v ++ targetSuffix) [] count []) + n (encodeWord m ++ encodeWords (rs.flatMap rowWords)) + (by exact inputWord_eq n m rs) (ambient, false) none + simp only [update_memory_work] at hfirst + have hsecond := MachineLookup.discardTrace Tape.work Label.headerSecond Label.row + program rfl + (memory (inputWord n m rs) (encodeWord m ++ encodeWords (rs.flatMap rowWords)) + (encodeWord v ++ targetSuffix) [] count []) + m (encodeWords (rs.flatMap rowWords)) rfl (ambient, false) none + simp only [update_memory_work] at hsecond + have hrows := rowsTrace rs hwidth v (inputWord n m rs) targetSuffix count [] ambient none + rw [show totalSteps n m v rs = rowsTime v rs + ((m + 1) + ((n + 1) + + 2 * ((inputWord n m rs).length + 1))) by unfold totalSteps; omega, + Function.iterate_add_apply _ (rowsTime v rs), + Function.iterate_add_apply _ (m + 1), Function.iterate_add_apply _ (n + 1), + hcopy, hfirst, hsecond] + exact hrows + +theorem totalSteps_le (n m v : Nat) (rs : List Row) : + totalSteps n m v rs ≤ 5 * (inputWord n m rs).length + 3 := by + have hrows := rowsTime_le v rs + have hlen := inputWord_length n m rs + unfold totalSteps + omega + +open MinUncutGames.Foundations.PCP + +def tableRows (t : GraphTables.Table) : List Row := + (GraphTables.rowList t).map (fun r => + (r.tail.val, r.reverseIndex.val :: GraphTables.relationWords r.relation)) + +theorem tableRows_width (t : GraphTables.Table) : + ∀ r ∈ tableRows t, r.2.length = 4097 := by + intro r hr + obtain ⟨a, ha, rfl⟩ := List.mem_map.mp hr + simp [GraphTables.relationWords] + +theorem tableRows_words (t : GraphTables.Table) : + (tableRows t).flatMap rowWords = (GraphTables.rowList t).flatMap GraphTables.rowWords := by + simp only [tableRows, List.flatMap_map] + apply congrArg (fun f => (GraphTables.rowList t).flatMap f) + funext r + rfl + +theorem tableRows_input (t : GraphTables.Table) : + inputWord t.vertices t.darts (tableRows t) = GraphTables.tableBits t := by + rw [inputWord, tableRows_words] + rfl + +theorem rowsHits_eq_filter (v : Nat) (rs : List Row) : + rowsHits v rs = (rs.filter (fun r => decide (r.1 = v))).length := by + induction rs with + | nil => rfl + | cons r rs ih => + by_cases h : r.1 = v <;> simp [rowsHits, h, ih, Nat.add_comm] + +theorem rowList_eq_finRange_map (t : GraphTables.Table) : + GraphTables.rowList t = (List.finRange t.darts).map (fun e => t.rows[e]) := by + apply List.ext_getElem + · simp [GraphTables.rowList] + · intro i hi hj + simp [GraphTables.rowList] + +theorem rowList_cloud_count (t : GraphTables.Table) (v : Fin t.vertices) : + ((GraphTables.rowList t).filter (fun r => decide (r.tail = v))).length = + PreprocessingCloudIndex.cloudSize t v := by + rw [rowList_eq_finRange_map, List.filter_map, List.length_map] + rfl + +theorem tableRows_hits (t : GraphTables.Table) (v : Fin t.vertices) : + rowsHits v.val (tableRows t) = PreprocessingCloudIndex.cloudSize t v := by + rw [rowsHits_eq_filter] + simp only [tableRows, List.filter_map, List.length_map] + simpa only [Function.comp_def, Fin.val_inj] using rowList_cloud_count t v + +theorem cloudCountTrace (t : GraphTables.Table) (v : Fin t.vertices) + (targetSuffix countSuffix : List Bool) (ambient : σ) (register : Option Bool) : + (advance (TM2.step (program (σ := σ))))^[totalSteps t.vertices t.darts v.val (tableRows t)] + (some ⟨some .copyFirst, ((ambient, false), register), + memory (GraphTables.tableBits t) [] (encodeWord v.val ++ targetSuffix) [] + (encodeWord 0 ++ countSuffix) []⟩) = + some ⟨none, ((ambient, false), none), + memory (GraphTables.tableBits t) [] (encodeWord v.val ++ targetSuffix) [] + (encodeWord (PreprocessingCloudIndex.cloudSize t v) ++ countSuffix) []⟩ := by + have h := countTrace t.vertices t.darts v.val (tableRows t) (tableRows_width t) + targetSuffix (encodeWord 0 ++ countSuffix) ambient register + rw [tableRows_input, tableRows_hits, ← List.append_assoc, replicate_encodeWord, Nat.add_zero] at h + exact h + +def cloudCountInTime (t : GraphTables.Table) (v : Fin t.vertices) + (targetSuffix countSuffix : List Bool) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step (program (σ := σ))) + ⟨some .copyFirst, ((ambient, false), register), + memory (GraphTables.tableBits t) [] (encodeWord v.val ++ targetSuffix) [] + (encodeWord 0 ++ countSuffix) []⟩ + (some ⟨none, ((ambient, false), none), + memory (GraphTables.tableBits t) [] (encodeWord v.val ++ targetSuffix) [] + (encodeWord (PreprocessingCloudIndex.cloudSize t v) ++ countSuffix) []⟩) + (5 * (GraphTables.tableBits t).length + 3) where + steps := totalSteps t.vertices t.darts v.val (tableRows t) + evals_in_steps := cloudCountTrace t v targetSuffix countSuffix ambient register + steps_le_m := by + simpa only [tableRows_input] using totalSteps_le t.vertices t.darts v.val (tableRows t) + +end MinUncutGames.Foundations.Complexity.MachineCloudCount + +end +section +namespace MinUncutGames.Foundations.Complexity.MachineCeilingPower + +open Turing +open MachineComposition +open MinUncutGames.Foundations.PCP + +inductive Tape + | input | work | power | saved | level | fuel | spare | product + deriving DecidableEq + +protected abbrev Tape.enumList : List Tape := [.input, .work, .power, .saved, .level, .fuel, + .spare, .product] + +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 + +inductive Label + | init | fuelFirst | fuelSecond | guard | copyFirst | copySecond + | compare | restore | decide | scale | transfer | cleanup + deriving DecidableEq + +protected abbrev Label.enumList : List Label := [.init, .fuelFirst, .fuelSecond, .guard, + .copyFirst, .copySecond, .compare, .restore, .decide, .scale, .transfer, .cleanup] + +protected theorem Label.enumList_getElem?_ctorIdx_eq (x : Label) : + Label.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem Label.enumList_nodup : Label.enumList.Nodup := by decide + +instance : Fintype Label where + elems := ⟨Label.enumList, Label.enumList_nodup⟩ + complete x := by cases x <;> decide + +abbrev Alphabet (_ : Tape) := Bool +abbrev State (σ : Type) := (σ × Bool) × Option Bool + +def memory (input work power saved level fuel spare product : List Bool) : Tape → List Bool + | .input => input + | .work => work + | .power => power + | .saved => saved + | .level => level + | .fuel => fuel + | .spare => spare + | .product => product + +@[simp] theorem update_work (a b c d e f g h x : List Bool) : + Function.update (memory a b c d e f g h) .work x = memory a x c d e f g h := by + funext k; cases k <;> rfl +@[simp] theorem update_power (a b c d e f g h x : List Bool) : + Function.update (memory a b c d e f g h) .power x = memory a b x d e f g h := by + funext k; cases k <;> rfl +@[simp] theorem update_saved (a b c d e f g h x : List Bool) : + Function.update (memory a b c d e f g h) .saved x = memory a b c x e f g h := by + funext k; cases k <;> rfl +@[simp] theorem update_level (a b c d e f g h x : List Bool) : + Function.update (memory a b c d e f g h) .level x = memory a b c d x f g h := by + funext k; cases k <;> rfl +@[simp] theorem update_fuel (a b c d e f g h x : List Bool) : + Function.update (memory a b c d e f g h) .fuel x = memory a b c d e x g h := by + funext k; cases k <;> rfl +@[simp] theorem update_product (a b c d e f g h x : List Bool) : + Function.update (memory a b c d e f g h) .product x = memory a b c d e f g x := by + funext k; cases k <;> rfl + +variable {σ : Type} + +def compareLoop : TM2.Stmt Alphabet Label (State σ) := + .pop .work (fun state head => (state.1, head)) + (.branch (fun state => state.2.getD false) + (.peek .power (fun state head => (state.1, head)) + (.branch (fun state => state.2.getD false) + (.pop .power (fun state _ => (state.1, none)) + (.push .saved (fun _ => true) (.goto fun _ => .compare))) + (.load (fun state => ((state.1.1, true), none)) (.goto fun _ => .compare)))) + (.load (fun state => (state.1, none)) (.goto fun _ => .restore))) + +def scaleLoop (g : Nat) : TM2.Stmt Alphabet Label (State σ) := + .pop .power (fun state head => (state.1, head)) + (.branch (fun state => state.2.getD false) + (Reduction.MachineSubstitution.pushWord .product (List.replicate g true) + (.goto fun _ => .scale)) + (.push .power (fun _ => false) + (.push .level (fun _ => true) + (.load (fun state => (state.1, none)) (.goto fun _ => .transfer))))) + +def program (g : Nat) : Label → TM2.Stmt Alphabet Label (State σ) + | .init => .push .power (fun _ => false) (.push .power (fun _ => true) + (.push .level (fun _ => false) (.goto fun _ => .fuelFirst))) + | .fuelFirst => Reduction.MachineTransfer.loopAt + .input .spare id false .fuelFirst (some .fuelSecond) + | .fuelSecond => MachineCopy.forkLoop + .spare .input .fuel false .fuelSecond (some .guard) + | .guard => MachineUnaryCounter.guard .fuel .copyFirst .cleanup + | .copyFirst => Reduction.MachineTransfer.loopAt + .input .spare id false .copyFirst (some .copySecond) + | .copySecond => MachineCopy.forkLoop + .spare .input .work false .copySecond (some .compare) + | .compare => compareLoop + | .restore => Reduction.MachineTransfer.loopAt + .saved .power id false .restore (some .decide) + | .decide => .branch (fun state => state.1.2) + (.load (fun state => ((state.1.1, false), none)) (.goto fun _ => .scale)) + (.load (fun state => ((state.1.1, false), none)) (.goto fun _ => .cleanup)) + | .scale => scaleLoop g + | .transfer => Reduction.MachineTransfer.loopAt + .product .power id false .transfer (some .guard) + | .cleanup => MachineDrain.drain .fuel .cleanup none + +def overflow (flag : Bool) (x p : Nat) : Bool := flag || decide (p < x) + +theorem compareStep_zero (g p : Nat) (input saved level fuel spare product : List Bool) + (ambient : σ) (flag : Bool) (register : Option Bool) : + TM2.step (program g) + ⟨some .compare, ((ambient, flag), register), + memory input (encodeWord 0) (encodeWord p) saved level fuel spare product⟩ = + some ⟨some .restore, ((ambient, flag), none), + memory input [] (encodeWord p) saved level fuel spare product⟩ := by + change some (TM2.stepAux compareLoop _ _) = _ + simp [compareLoop, TM2.stepAux, memory, encodeWord] + +theorem compareStep_succ_zero (g x : Nat) (input saved level fuel spare product : List Bool) + (ambient : σ) (flag : Bool) (register : Option Bool) : + TM2.step (program g) + ⟨some .compare, ((ambient, flag), register), + memory input (encodeWord (x + 1)) (encodeWord 0) saved level fuel spare product⟩ = + some ⟨some .compare, ((ambient, true), none), + memory input (encodeWord x) (encodeWord 0) saved level fuel spare product⟩ := by + change some (TM2.stepAux compareLoop _ _) = _ + simp [compareLoop, TM2.stepAux, memory, encodeWord, List.replicate_succ] + +theorem compareStep_succ_succ (g x p : Nat) (input saved level fuel spare product : List Bool) + (ambient : σ) (flag : Bool) (register : Option Bool) : + TM2.step (program g) + ⟨some .compare, ((ambient, flag), register), + memory input (encodeWord (x + 1)) (encodeWord (p + 1)) saved level fuel spare product⟩ = + some ⟨some .compare, ((ambient, flag), none), + memory input (encodeWord x) (encodeWord p) (true :: saved) level fuel spare product⟩ := by + change some (TM2.stepAux compareLoop _ _) = _ + simp [compareLoop, TM2.stepAux, memory, encodeWord, List.replicate_succ] + +theorem compareTrace (g x p : Nat) (input saved level fuel spare product : List Bool) + (ambient : σ) (flag : Bool) (register : Option Bool) : + (advance (TM2.step (program g)))^[x + 1] + (some ⟨some .compare, ((ambient, flag), register), + memory input (encodeWord x) (encodeWord p) saved level fuel spare product⟩) = + some ⟨some .restore, ((ambient, overflow flag x p), none), + memory input [] (encodeWord (p - x)) + (List.replicate (min x p) true ++ saved) level fuel spare product⟩ := by + induction x generalizing p saved flag register with + | zero => + simpa [overflow] using compareStep_zero g p input saved level fuel spare product ambient flag register + | succ x ih => + rw [Function.iterate_succ_apply] + change (advance (TM2.step (program g)))^[x + 1] + (TM2.step (program g) ⟨some .compare, ((ambient, flag), register), + memory input (encodeWord (x + 1)) (encodeWord p) saved level fuel spare product⟩) = _ + cases p with + | zero => + rw [compareStep_succ_zero] + simpa [overflow] using ih 0 saved true none + | succ p => + rw [compareStep_succ_succ] + simpa [overflow, Nat.succ_min_succ, List.replicate_succ', List.append_assoc] using + ih p (true :: saved) flag none + +theorem replicate_encodeWord (a b : Nat) : + List.replicate a true ++ encodeWord b = encodeWord (a + b) := by + simp only [encodeWord, ← List.append_assoc, List.replicate_append_replicate] + +theorem compareRestoredTrace (g k p : Nat) (level fuel : List Bool) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step (program g)))^[k + min k p + 2] + (some ⟨some .compare, ((ambient, false), register), + memory (encodeWord k) (encodeWord k) (encodeWord p) [] level fuel [] []⟩) = + some ⟨some .decide, ((ambient, decide (p < k)), none), + memory (encodeWord k) [] (encodeWord p) [] level fuel [] []⟩ := by + have hc := compareTrace g k p (encodeWord k) [] level fuel [] [] ambient false register + simp only [overflow, Bool.false_or, List.append_nil] at hc + let mid := memory (encodeWord k) [] (encodeWord (p - k)) + (List.replicate (min k p) true) level fuel [] [] + have hr := Reduction.MachineTransfer.transferAt_fromTapes Tape.saved Tape.power (by decide) + id false Label.restore (some Label.decide) (program g) rfl mid (ambient, decide (p < k)) none + have hsum : min k p + (p - k) = p := by omega + simp only [mid, memory, List.length_replicate, List.reverse_replicate, List.map_id, + Reduction.MachineTransfer.tapesAt, update_saved, update_power] at hr + rw [replicate_encodeWord, hsum] at hr + rw [show k + min k p + 2 = (min k p + 1) + (k + 1) by omega, + Function.iterate_add_apply, hc] + exact hr + +theorem appendTrace {α : Type*} (f : α → α) {a b c : α} {s t : Nat} + (hs : f^[s] a = b) (ht : f^[t] b = c) : f^[s + t] a = c := by + rw [Nat.add_comm s t, Function.iterate_add_apply, hs, ht] + +theorem scaleStep_succ (g p b : Nat) (input level fuel : List Bool) + (ambient : σ) (register : Option Bool) : + TM2.step (program g) + ⟨some .scale, ((ambient, false), register), + memory input [] (encodeWord (p + 1)) [] level fuel [] (List.replicate b true)⟩ = + some ⟨some .scale, ((ambient, false), some true), + memory input [] (encodeWord p) [] level fuel [] (List.replicate (g + b) true)⟩ := by + change some (TM2.stepAux (scaleLoop g) _ _) = _ + simp [scaleLoop, TM2.stepAux, memory, encodeWord, List.replicate_succ, + Reduction.MachineSubstitution.stepAux_pushWord] + +theorem scaleStep_zero (g b : Nat) (input level fuel : List Bool) + (ambient : σ) (register : Option Bool) : + TM2.step (program g) + ⟨some .scale, ((ambient, false), register), + memory input [] (encodeWord 0) [] level fuel [] (List.replicate b true)⟩ = + some ⟨some .transfer, ((ambient, false), none), + memory input [] (encodeWord 0) [] (true :: level) fuel [] (List.replicate b true)⟩ := by + change some (TM2.stepAux (scaleLoop g) _ _) = _ + simp [scaleLoop, TM2.stepAux, memory, encodeWord] + +theorem scaleScanTrace (g p b : Nat) (input level fuel : List Bool) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step (program g)))^[p + 1] + (some ⟨some .scale, ((ambient, false), register), + memory input [] (encodeWord p) [] level fuel [] (List.replicate b true)⟩) = + some ⟨some .transfer, ((ambient, false), none), + memory input [] (encodeWord 0) [] (true :: level) fuel [] (List.replicate (g * p + b) true)⟩ := by + induction p generalizing b register with + | zero => simpa using scaleStep_zero g b input level fuel ambient register + | succ p ih => + rw [Function.iterate_succ_apply] + change (advance (TM2.step (program g)))^[p + 1] + (TM2.step (program g) ⟨some .scale, ((ambient, false), register), + memory input [] (encodeWord (p + 1)) [] level fuel [] (List.replicate b true)⟩) = _ + rw [scaleStep_succ, ih] + have h : g * p + (g + b) = g * (p + 1) + b := by rw [Nat.mul_succ]; omega + rw [h] + +theorem scaleTrace (g k p e : Nat) (fuel : List Bool) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step (program g)))^[p + g * p + 2] + (some ⟨some .scale, ((ambient, false), register), + memory (encodeWord k) [] (encodeWord p) [] (encodeWord e) fuel [] []⟩) = + some ⟨some .guard, ((ambient, false), none), + memory (encodeWord k) [] (encodeWord (p * g)) [] (encodeWord (e + 1)) fuel [] []⟩ := by + have hs := scaleScanTrace g p 0 (encodeWord k) (encodeWord e) fuel ambient register + simp only [List.replicate_zero, Nat.add_zero] at hs + let mid := memory (encodeWord k) [] (encodeWord 0) [] (true :: encodeWord e) fuel [] + (List.replicate (g * p) true) + have ht := Reduction.MachineTransfer.transferAt_fromTapes Tape.product Tape.power (by decide) + id false Label.transfer (some Label.guard) (program g) rfl mid (ambient, false) none + simp only [mid, memory, List.length_replicate, List.reverse_replicate, List.map_id, + Reduction.MachineTransfer.tapesAt, update_product, update_power, + replicate_encodeWord, Nat.add_zero] at ht + have he : true :: encodeWord e = encodeWord (e + 1) := by simp [encodeWord, List.replicate_succ] + rw [he, Nat.mul_comm g p] at ht + rw [he, Nat.mul_comm g p] at hs + have h := appendTrace (advance (TM2.step (program g))) hs ht + simpa only [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm, Nat.mul_comm] using h + +theorem cleanupTrace (g k p e f : Nat) (ambient : σ) (register : Option Bool) : + (advance (TM2.step (program g)))^[f + 2] + (some ⟨some .cleanup, ((ambient, false), register), + memory (encodeWord k) [] (encodeWord p) [] (encodeWord e) (encodeWord f) [] []⟩) = + some ⟨none, ((ambient, false), none), + memory (encodeWord k) [] (encodeWord p) [] (encodeWord e) [] [] []⟩ := by + have h := MachineDrain.drainTrace Tape.fuel Label.cleanup none (program g) rfl + (memory (encodeWord k) [] (encodeWord p) [] (encodeWord e) [] [] []) + (encodeWord f) (ambient, false) register + simpa only [encodeWord_length, update_fuel, Nat.add_assoc] using h + +theorem guardStep_succ (g k p e f : Nat) (ambient : σ) (register : Option Bool) : + TM2.step (program g) + ⟨some .guard, ((ambient, false), register), + memory (encodeWord k) [] (encodeWord p) [] (encodeWord e) (encodeWord (f + 1)) [] []⟩ = + some ⟨some .copyFirst, ((ambient, false), none), + memory (encodeWord k) [] (encodeWord p) [] (encodeWord e) (encodeWord f) [] []⟩ := by + have h := MachineUnaryCounter.guardStep_succ Tape.fuel Label.guard Label.copyFirst Label.cleanup + (program g) rfl (memory (encodeWord k) [] (encodeWord p) [] (encodeWord e) [] [] []) + f [] (ambient, false) register + simpa only [MachineUnaryCounter.counterTapes, List.append_nil, update_fuel] using h + +theorem guardStep_zero (g k p e : Nat) (ambient : σ) (register : Option Bool) : + TM2.step (program g) + ⟨some .guard, ((ambient, false), register), + memory (encodeWord k) [] (encodeWord p) [] (encodeWord e) (encodeWord 0) [] []⟩ = + some ⟨some .cleanup, ((ambient, false), none), + memory (encodeWord k) [] (encodeWord p) [] (encodeWord e) (encodeWord 0) [] []⟩ := by + have h := MachineUnaryCounter.guardStep_zero Tape.fuel Label.guard Label.copyFirst Label.cleanup + (program g) rfl (memory (encodeWord k) [] (encodeWord p) [] (encodeWord e) [] [] []) + [] (ambient, false) register + simpa only [MachineUnaryCounter.counterTapes, List.append_nil, update_fuel] using h + +theorem decideStep (g k p e f : Nat) (ambient : σ) : + TM2.step (program g) + ⟨some .decide, ((ambient, decide (p < k)), none), + memory (encodeWord k) [] (encodeWord p) [] (encodeWord e) (encodeWord f) [] []⟩ = + some ⟨some (if k ≤ p then Label.cleanup else Label.scale), ((ambient, false), none), + memory (encodeWord k) [] (encodeWord p) [] (encodeWord e) (encodeWord f) [] []⟩ := by + by_cases h : k ≤ p + · have hn : ¬p < k := by omega + simp [TM2.step, program, TM2.stepAux, h, hn] + · have hn : p < k := by omega + simp [TM2.step, program, TM2.stepAux, h, hn] + +def prefixTime (k p : Nat) : Nat := (1 + 2 * (k + 2)) + (k + min k p + 2) + 1 + +theorem prefixTrace (g k p e f : Nat) (ambient : σ) (register : Option Bool) : + (advance (TM2.step (program g)))^[prefixTime k p] + (some ⟨some .guard, ((ambient, false), register), + memory (encodeWord k) [] (encodeWord p) [] (encodeWord e) (encodeWord (f + 1)) [] []⟩) = + some ⟨some (if k ≤ p then Label.cleanup else Label.scale), ((ambient, false), none), + memory (encodeWord k) [] (encodeWord p) [] (encodeWord e) (encodeWord f) [] []⟩ := by + have hg : (advance (TM2.step (program g)))^[1] + (some ⟨some .guard, ((ambient, false), register), + memory (encodeWord k) [] (encodeWord p) [] (encodeWord e) (encodeWord (f + 1)) [] []⟩) = + some ⟨some .copyFirst, ((ambient, false), none), + memory (encodeWord k) [] (encodeWord p) [] (encodeWord e) (encodeWord f) [] []⟩ := + guardStep_succ g k p e f ambient register + have hc := MachineCopy.copyTrace Tape.input Tape.work Tape.spare + (by decide) (by decide) (by decide) false Label.copyFirst Label.copySecond + (some Label.compare) (program g) rfl rfl + (memory (encodeWord k) [] (encodeWord p) [] (encodeWord e) (encodeWord f) [] []) + rfl (ambient, false) none + simp only [memory, encodeWord_length, List.append_nil, update_work] at hc + have hcmp := compareRestoredTrace g k p (encodeWord e) (encodeWord f) ambient none + have hd : (advance (TM2.step (program g)))^[1] + (some ⟨some .decide, ((ambient, decide (p < k)), none), + memory (encodeWord k) [] (encodeWord p) [] (encodeWord e) (encodeWord f) [] []⟩) = + some ⟨some (if k ≤ p then Label.cleanup else Label.scale), ((ambient, false), none), + memory (encodeWord k) [] (encodeWord p) [] (encodeWord e) (encodeWord f) [] []⟩ := + decideStep g k p e f ambient + exact appendTrace _ (appendTrace _ (appendTrace _ hg hc) hcmp) hd + +def coreTime (g k : Nat) : Nat → Nat → Nat + | 0, _ => 3 + | f + 1, p => prefixTime k p + + if k ≤ p then f + 2 else (p + g * p + 2) + coreTime g k f (p * g) + +theorem coreTrace (g k f e p : Nat) (ambient : σ) (register : Option Bool) : + (advance (TM2.step (program g)))^[coreTime g k f p] + (some ⟨some .guard, ((ambient, false), register), + memory (encodeWord k) [] (encodeWord p) [] (encodeWord e) (encodeWord f) [] []⟩) = + some ⟨none, ((ambient, false), none), + memory (encodeWord k) [] + (encodeWord (PreprocessingLevels.levelLoop g k f e p).2) [] + (encodeWord (PreprocessingLevels.levelLoop g k f e p).1) [] [] []⟩ := by + induction f generalizing e p register with + | zero => + have hg : (advance (TM2.step (program g)))^[1] + (some ⟨some .guard, ((ambient, false), register), + memory (encodeWord k) [] (encodeWord p) [] (encodeWord e) (encodeWord 0) [] []⟩) = + some ⟨some .cleanup, ((ambient, false), none), + memory (encodeWord k) [] (encodeWord p) [] (encodeWord e) (encodeWord 0) [] []⟩ := + guardStep_zero g k p e ambient register + exact appendTrace _ hg (cleanupTrace g k p e 0 ambient none) + | succ f ih => + have hpref := prefixTrace g k p e f ambient register + by_cases h : k ≤ p + · simp only [h, ite_true] at hpref + have hrun := appendTrace _ hpref (cleanupTrace g k p e f ambient none) + simpa only [coreTime, PreprocessingLevels.levelLoop, h, ite_true] using hrun + · simp only [h, ite_false] at hpref + have hscale := scaleTrace g k p e (encodeWord f) ambient none + have hrun := appendTrace _ hpref (appendTrace _ hscale (ih (e + 1) (p * g) none)) + simpa only [coreTime, PreprocessingLevels.levelLoop, h, ite_false] using hrun + +def roundBudget (g k : Nat) : Nat := (g + 8) * (k + 1) + 16 + +theorem prefixTime_le (k p : Nat) : prefixTime k p ≤ 4 * k + 8 := by + have h := Nat.min_le_left k p + unfold prefixTime + omega + +theorem prefixTime_le_roundBudget (g k p : Nat) : prefixTime k p ≤ roundBudget g k := by + have h := prefixTime_le k p + unfold roundBudget + simp only [Nat.add_mul, Nat.mul_add, Nat.mul_one] + omega + +theorem continuingTime_le (g k p : Nat) (h : p < k) : + prefixTime k p + (p + g * p + 2) ≤ roundBudget g k := by + have hprefix := prefixTime_le k p + have hmul := Nat.mul_le_mul_left g h.le + unfold roundBudget + simp only [Nat.add_mul, Nat.mul_add, Nat.mul_one] + omega + +theorem coreTime_le (g k f p : Nat) : + coreTime g k f p ≤ (f + 1) * roundBudget g k := by + have hB : 3 ≤ roundBudget g k := by unfold roundBudget; omega + induction f generalizing p with + | zero => simpa only [coreTime, Nat.zero_add, Nat.one_mul] using hB + | succ f ih => + rw [coreTime] + by_cases h : k ≤ p + · rw [ite_eq_left h] + have hp := prefixTime_le_roundBudget g k p + have hm := Nat.mul_le_mul_left (f + 1) hB + have hc : f + 2 ≤ (f + 1) * roundBudget g k := by omega + calc + prefixTime k p + (f + 2) ≤ roundBudget g k + (f + 1) * roundBudget g k := + Nat.add_le_add hp hc + _ = (f + 1 + 1) * roundBudget g k := by ring + · rw [ite_eq_right h] + have hb := continuingTime_le g k p (by omega) + have hr := ih (p * g) + calc + prefixTime k p + ((p + g * p + 2) + coreTime g k f (p * g)) = + (prefixTime k p + (p + g * p + 2)) + coreTime g k f (p * g) := by omega + _ ≤ roundBudget g k + (f + 1) * roundBudget g k := Nat.add_le_add hb hr + _ = (f + 1 + 1) * roundBudget g k := by ring + +theorem initStep (g k : Nat) (ambient : σ) (register : Option Bool) : + TM2.step (program g) + ⟨some .init, ((ambient, false), register), memory (encodeWord k) [] [] [] [] [] [] []⟩ = + some ⟨some .fuelFirst, ((ambient, false), register), + memory (encodeWord k) [] (encodeWord 1) [] (encodeWord 0) [] [] []⟩ := by + change some (TM2.stepAux (program g .init) _ _) = _ + simp [program, TM2.stepAux, memory, encodeWord] + +def totalTime (g k : Nat) : Nat := 1 + 2 * (k + 2) + coreTime g k k 1 + +theorem searchTrace (g k : Nat) (ambient : σ) (register : Option Bool) : + (advance (TM2.step (program g)))^[totalTime g k] + (some ⟨some .init, ((ambient, false), register), memory (encodeWord k) [] [] [] [] [] [] []⟩) = + some ⟨none, ((ambient, false), none), + memory (encodeWord k) [] + (encodeWord (PreprocessingLevels.levelLoop g k k 0 1).2) [] + (encodeWord (PreprocessingLevels.levelLoop g k k 0 1).1) [] [] []⟩ := by + have hi : (advance (TM2.step (program g)))^[1] + (some ⟨some .init, ((ambient, false), register), memory (encodeWord k) [] [] [] [] [] [] []⟩) = + some ⟨some .fuelFirst, ((ambient, false), register), + memory (encodeWord k) [] (encodeWord 1) [] (encodeWord 0) [] [] []⟩ := + initStep g k ambient register + have hc := MachineCopy.copyTrace Tape.input Tape.fuel Tape.spare + (by decide) (by decide) (by decide) false Label.fuelFirst Label.fuelSecond + (some Label.guard) (program g) rfl rfl + (memory (encodeWord k) [] (encodeWord 1) [] (encodeWord 0) [] [] []) + rfl (ambient, false) register + simp only [memory, encodeWord_length, List.append_nil, update_fuel] at hc + exact appendTrace _ (appendTrace _ hi hc) (coreTrace g k k 0 1 ambient none) + +def timeBound (g k : Nat) : Nat := (g + 8) * (k + 1) ^ 2 + 18 * (k + 1) + 3 + +theorem totalTime_le (g k : Nat) : totalTime g k ≤ timeBound g k := by + have h := coreTime_le g k k 1 + calc + totalTime g k ≤ 1 + 2 * (k + 2) + (k + 1) * roundBudget g k := + Nat.add_le_add_left h _ + _ = timeBound g k := by unfold roundBudget timeBound; ring + +noncomputable def timePolynomial (g : Nat) : Polynomial Nat := + Polynomial.C (g + 8) * Polynomial.X ^ 2 + 18 * Polynomial.X + 3 + +theorem timePolynomial_encoding (g k : Nat) : + (timePolynomial g).eval (encodeWord k).length = timeBound g k := by + simp [timePolynomial, timeBound, encodeWord_length] + +theorem paddingTrace (k : Nat) (ambient : σ) (register : Option Bool) : + (advance (TM2.step (program ExpanderFamily.growth)))^[totalTime ExpanderFamily.growth k] + (some ⟨some .init, ((ambient, false), register), memory (encodeWord k) [] [] [] [] [] [] []⟩) = + some ⟨none, ((ambient, false), none), + memory (encodeWord k) [] (encodeWord (PreprocessingLevels.paddedSize k)) [] + (encodeWord (PreprocessingLevels.boundedLevel k)) [] [] []⟩ := by + exact searchTrace ExpanderFamily.growth k ambient register + +def paddingInTime (k : Nat) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step (program ExpanderFamily.growth)) + ⟨some .init, ((ambient, false), register), memory (encodeWord k) [] [] [] [] [] [] []⟩ + (some ⟨none, ((ambient, false), none), + memory (encodeWord k) [] (encodeWord (PreprocessingLevels.paddedSize k)) [] + (encodeWord (PreprocessingLevels.boundedLevel k)) [] [] []⟩) + ((timePolynomial ExpanderFamily.growth).eval (encodeWord k).length) where + steps := totalTime ExpanderFamily.growth k + evals_in_steps := paddingTrace k ambient register + steps_le_m := by rw [timePolynomial_encoding]; exact totalTime_le _ _ + +theorem paddingOutput_bounds (k : Nat) : + PreprocessingLevels.boundedLevel k ≤ k ∧ + k ≤ PreprocessingLevels.paddedSize k ∧ + PreprocessingLevels.paddedSize k ≤ ExpanderFamily.growth * (k + 1) := by + refine ⟨PreprocessingLevels.boundedLevel_le_input k, PreprocessingLevels.le_paddedSize k, ?_⟩ + by_cases hk : k = 0 + · subst k + simpa using ExpanderFamily.growth_gt_one.le + · exact (PreprocessingLevels.paddedSize_bounds (Nat.pos_of_ne_zero hk)).2.trans + (Nat.mul_le_mul_left ExpanderFamily.growth (Nat.le_succ k)) + +end MinUncutGames.Foundations.Complexity.MachineCeilingPower + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineCloudPadding.lean b/lean/OAI/Computability/MinUncut/Machines/MachineCloudPadding.lean new file mode 100644 index 0000000000000000000000000000000000000000..d9458ef2badb331fdb47f8f829f724903ce98d4d --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineCloudPadding.lean @@ -0,0 +1,528 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineCloudCount + +namespace OAI + +section +namespace MinUncutGames.Foundations.Complexity.MachineCloudPadding + +open Turing +open MachineComposition +open MinUncutGames.Foundations.PCP + +namespace Placement + +variable {K K' Λ Λ' σ : Type} + +def tapes (view : K' → Option K) (source : K → List Bool) + (extra : K' → List Bool) : K' → List Bool := + fun j => match view j with + | some k => source k + | none => extra j + +def label (labels : Λ → Λ') (exit : Option Λ') : Option Λ → Option Λ' + | some l => some (labels l) + | none => exit + +def configuration (view : K' → Option K) (labels : Λ → Λ') (exit : Option Λ') + (extra : K' → List Bool) (c : TM2.Cfg (fun _ : K => Bool) Λ σ) : + TM2.Cfg (fun _ : K' => Bool) Λ' σ := + ⟨label labels exit c.l, c.var, tapes view c.stk extra⟩ + +def statement (tape : K → K') (labels : Λ → Λ') (exit : Option Λ') : + TM2.Stmt (fun _ : K => Bool) Λ σ → TM2.Stmt (fun _ : K' => Bool) Λ' σ + | .push k f next => .push (tape k) f (statement tape labels exit next) + | .peek k f next => .peek (tape k) f (statement tape labels exit next) + | .pop k f next => .pop (tape k) f (statement tape labels exit next) + | .load f next => .load f (statement tape labels exit next) + | .branch f yes no => .branch f (statement tape labels exit yes) (statement tape labels exit no) + | .goto f => .goto (fun state => labels (f state)) + | .halt => match exit with + | some l => .goto (fun _ => l) + | none => .halt + +variable [DecidableEq K] [DecidableEq K'] + +omit [DecidableEq K] [DecidableEq K'] in +theorem tapes_apply (tape : K → K') (view : K' → Option K) + (left : ∀ k, view (tape k) = some k) + (source : K → List Bool) (extra : K' → List Bool) (k : K) : + tapes view source extra (tape k) = source k := by + simp only [tapes, left] + +theorem tapes_update (tape : K → K') (view : K' → Option K) + (left : ∀ k, view (tape k) = some k) + (right : ∀ j k, view j = some k → tape k = j) + (source : K → List Bool) (extra : K' → List Bool) (k : K) (w : List Bool) : + tapes view (Function.update source k w) extra = + Function.update (tapes view source extra) (tape k) w := by + funext j + by_cases h : j = tape k + · subst j + simp [tapes, left] + · cases hv : view j with + | none => simp [tapes, hv, h] + | some i => + have hi : i ≠ k := by + intro hi + subst i + exact h (right j k hv).symm + simp [tapes, hv, h, hi] + +theorem stepAux_simulation (tape : K → K') (view : K' → Option K) + (left : ∀ k, view (tape k) = some k) + (right : ∀ j k, view j = some k → tape k = j) + (labels : Λ → Λ') (exit : Option Λ') (extra : K' → List Bool) + (q : TM2.Stmt (fun _ : K => Bool) Λ σ) (state : σ) (source : K → List Bool) : + TM2.stepAux (statement tape labels exit q) state (tapes view source extra) = + configuration view labels exit extra (TM2.stepAux q state source) := by + induction q generalizing state source with + | push k f next ih => + simp only [statement, TM2.stepAux, tapes_apply tape view left] + rw [← tapes_update tape view left right] + exact ih state (Function.update source k (f state :: source k)) + | peek k f next ih => + simpa only [statement, TM2.stepAux, tapes_apply tape view left] using + ih (f state (source k).head?) source + | pop k f next ih => + simp only [statement, TM2.stepAux, tapes_apply tape view left] + rw [← tapes_update tape view left right] + exact ih (f state (source k).head?) (Function.update source k (source k).tail) + | load f next ih => simpa only [statement, TM2.stepAux] using ih (f state) source + | branch f yes no ihYes ihNo => + cases h : f state with + | false => simpa only [statement, TM2.stepAux, h, Bool.cond_false] using ihNo state source + | true => simpa only [statement, TM2.stepAux, h, Bool.cond_true] using ihYes state source + | goto f => rfl + | halt => cases exit <;> rfl + +theorem step_simulation (tape : K → K') (view : K' → Option K) + (left : ∀ k, view (tape k) = some k) + (right : ∀ j k, view j = some k → tape k = j) + (labels : Λ → Λ') (exit : Option Λ') (extra : K' → List Bool) + (source : Λ → TM2.Stmt (fun _ : K => Bool) Λ σ) + (target : Λ' → TM2.Stmt (fun _ : K' => Bool) Λ' σ) + (atLabels : ∀ l, target (labels l) = statement tape labels exit (source l)) + (a b : TM2.Cfg (fun _ : K => Bool) Λ σ) (h : TM2.step source a = some b) : + TM2.step target (configuration view labels exit extra a) = + some (configuration view labels exit extra b) := by + cases a with + | mk l state sourceTapes => + cases l with + | none => simp [TM2.step] at h + | some l => + have hb : TM2.stepAux (source l) state sourceTapes = b := Option.some.inj h + rw [← hb] + change some (TM2.stepAux (target (labels l)) state (tapes view sourceTapes extra)) = _ + rw [atLabels, stepAux_simulation tape view left right] + +theorem trace (tape : K → K') (view : K' → Option K) + (left : ∀ k, view (tape k) = some k) + (right : ∀ j k, view j = some k → tape k = j) + (labels : Λ → Λ') (exit : Option Λ') (extra : K' → List Bool) + (source : Λ → TM2.Stmt (fun _ : K => Bool) Λ σ) + (target : Λ' → TM2.Stmt (fun _ : K' => Bool) Λ' σ) + (atLabels : ∀ l, target (labels l) = statement tape labels exit (source l)) + (n : Nat) (a b : TM2.Cfg (fun _ : K => Bool) Λ σ) + (run : (advance (TM2.step source))^[n] (some a) = some b) : + (advance (TM2.step target))^[n] + (some (configuration view labels exit extra a)) = + some (configuration view labels exit extra b) := + liftSuccessfulTrace _ _ _ + (step_simulation tape view left right labels exit extra source target atLabels) n a b run + +end Placement + +inductive Tape + | table | query | count | work | scratch | spare | power | level | fuel | product + deriving DecidableEq + +protected abbrev Tape.enumList : List Tape := [.table, .query, .count, .work, .scratch, .spare, + .power, .level, .fuel, .product] + +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 + +inductive Label + | init | countCode (l : MachineCloudCount.Label) + | branch | powerCode (l : MachineCeilingPower.Label) + | subtract | restore + deriving DecidableEq, Fintype + +abbrev Alphabet (_ : Tape) := Bool +abbrev State (σ : Type) := (σ × Bool) × Option Bool + +def memory (table query count work scratch spare power level fuel product : List Bool) : + Tape → List Bool + | .table => table + | .query => query + | .count => count + | .work => work + | .scratch => scratch + | .spare => spare + | .power => power + | .level => level + | .fuel => fuel + | .product => product + +@[simp] theorem update_count (a b c d e f g h i j x : List Bool) : + Function.update (memory a b c d e f g h i j) .count x = memory a b x d e f g h i j := by + funext k; cases k <;> rfl +@[simp] theorem update_scratch (a b c d e f g h i j x : List Bool) : + Function.update (memory a b c d e f g h i j) .scratch x = memory a b c d x f g h i j := by + funext k; cases k <;> rfl +@[simp] theorem update_power (a b c d e f g h i j x : List Bool) : + Function.update (memory a b c d e f g h i j) .power x = memory a b c d e f x h i j := by + funext k; cases k <;> rfl + +@[simp] theorem update_level (a b c d e f g h i j x : List Bool) : + Function.update (memory a b c d e f g h i j) .level x = memory a b c d e f g x i j := by + funext k; cases k <;> rfl + +def countTape : MachineCloudCount.Tape → Tape + | .original => .table + | .target => .query + | .count => .count + | .work => .work + | .scratch => .scratch + | .spare => .spare + +def countView : Tape → Option MachineCloudCount.Tape + | .table => some .original + | .query => some .target + | .count => some .count + | .work => some .work + | .scratch => some .scratch + | .spare => some .spare + | _ => none + +theorem countView_left (k : MachineCloudCount.Tape) : countView (countTape k) = some k := by + cases k <;> rfl +theorem countView_right (j : Tape) (k : MachineCloudCount.Tape) + (h : countView j = some k) : countTape k = j := by + cases j <;> cases k <;> simp_all [countView, countTape] + +def powerTape : MachineCeilingPower.Tape → Tape + | .input => .count + | .work => .work + | .power => .power + | .saved => .scratch + | .level => .level + | .fuel => .fuel + | .spare => .spare + | .product => .product + +def powerView : Tape → Option MachineCeilingPower.Tape + | .count => some .input + | .work => some .work + | .power => some .power + | .scratch => some .saved + | .level => some .level + | .fuel => some .fuel + | .spare => some .spare + | .product => some .product + | _ => none + +theorem powerView_left (k : MachineCeilingPower.Tape) : powerView (powerTape k) = some k := by + cases k <;> rfl +theorem powerView_right (j : Tape) (k : MachineCeilingPower.Tape) + (h : powerView j = some k) : powerTape k = j := by + cases j <;> cases k <;> simp_all [powerView, powerTape] + +@[simp] theorem countMemory (a b c d e f g h i j : List Bool) : + Placement.tapes countView (MachineCloudCount.memory a d b e c f) + (memory a b c d e f g h i j) = memory a b c d e f g h i j := by + funext k; cases k <;> rfl + +@[simp] theorem powerMemory (a b c d e f g h i j : List Bool) : + Placement.tapes powerView (MachineCeilingPower.memory c d g e h i f j) + (memory a b c d e f g h i j) = memory a b c d e f g h i j := by + funext k; cases k <;> rfl + +theorem countTapes (a b c d e f : List Bool) (extra : Tape → List Bool) : + Placement.tapes countView (MachineCloudCount.memory a d b e c f) extra = + memory a b c d e f (extra .power) (extra .level) (extra .fuel) (extra .product) := by + funext k; cases k <;> rfl + +theorem powerTapes (c d g e h i f j : List Bool) (extra : Tape → List Bool) : + Placement.tapes powerView (MachineCeilingPower.memory c d g e h i f j) extra = + memory (extra .table) (extra .query) c d e f g h i j := by + funext k; cases k <;> rfl + +variable {σ : Type} + +def subtractLoop : TM2.Stmt Alphabet Label (State σ) := + .pop .count (fun state head => (state.1, head)) + (.branch (fun state => state.2.getD false) + (.pop .power (fun state _ => (state.1, none)) + (.push .scratch (fun _ => true) (.goto fun _ => .subtract))) + (.push .count (fun _ => false) + (.load (fun state => (state.1, none)) (.goto fun _ => .restore)))) + +def program : Label → TM2.Stmt Alphabet Label (State σ) + | .init => .push .count (fun _ => false) (.goto fun _ => .countCode .copyFirst) + | .countCode l => Placement.statement countTape Label.countCode (some .branch) + (MachineCloudCount.program l) + | .branch => .peek .count (fun state head => (state.1, head)) + (.branch (fun state => state.2.getD false) + (.load (fun state => (state.1, none)) (.goto fun _ => .powerCode .init)) + (.push .power (fun _ => false) (.push .level (fun _ => false) + (.load (fun state => (state.1, none)) .halt)))) + | .powerCode l => Placement.statement powerTape Label.powerCode (some .subtract) + (MachineCeilingPower.program ExpanderFamily.growth l) + | .subtract => subtractLoop + | .restore => Reduction.MachineTransfer.loopAt + .scratch .count id false .restore none + +theorem appendTrace {α : Type} (f : α → α) {a b : Nat} {x y z : α} + (hs : f^[a] x = y) (ht : f^[b] y = z) : f^[a + b] x = z := by + rw [Nat.add_comm a b, Function.iterate_add_apply, hs, ht] + +theorem countTrace (t : GraphTables.Table) (v : Fin t.vertices) + (suffix : List Bool) (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[MachineCloudCount.totalSteps t.vertices t.darts v.val + (MachineCloudCount.tableRows t)] + (some ⟨some (.countCode .copyFirst), ((ambient, false), register), + memory (GraphTables.tableBits t) (encodeWord v.val ++ suffix) + (encodeWord 0) [] [] [] [] [] [] []⟩) = + some ⟨some .branch, ((ambient, false), none), + memory (GraphTables.tableBits t) (encodeWord v.val ++ suffix) + (encodeWord (PreprocessingCloudIndex.cloudSize t v)) [] [] [] [] [] [] []⟩ := by + have h := Placement.trace countTape countView countView_left countView_right + Label.countCode (some Label.branch) (fun _ => []) + (MachineCloudCount.program (σ := σ)) program (fun _ => rfl) _ _ _ + (MachineCloudCount.cloudCountTrace t v suffix [] ambient register) + simpa only [Placement.configuration, Placement.label, countTapes, List.append_nil] using h + +theorem powerTrace (table query : List Bool) (k : Nat) (ambient : σ) + (register : Option Bool) : + (advance (TM2.step program))^[MachineCeilingPower.totalTime ExpanderFamily.growth k] + (some ⟨some (.powerCode .init), ((ambient, false), register), + memory table query (encodeWord k) [] [] [] [] [] [] []⟩) = + some ⟨some .subtract, ((ambient, false), none), + memory table query (encodeWord k) [] [] [] + (encodeWord (PreprocessingLevels.paddedSize k)) + (encodeWord (PreprocessingLevels.boundedLevel k)) [] []⟩ := by + have h := Placement.trace powerTape powerView powerView_left powerView_right + Label.powerCode (some Label.subtract) (memory table query [] [] [] [] [] [] [] []) + (MachineCeilingPower.program ExpanderFamily.growth (σ := σ)) program (fun _ => rfl) + _ _ _ (MachineCeilingPower.paddingTrace k ambient register) + simpa only [Placement.configuration, Placement.label, powerTapes, memory] using h + +theorem subtractStep_zero (table query level saved : List Bool) (p : Nat) + (ambient : σ) (register : Option Bool) : + TM2.step program + ⟨some .subtract, ((ambient, false), register), + memory table query (encodeWord 0) [] saved [] (encodeWord p) level [] []⟩ = + some ⟨some .restore, ((ambient, false), none), + memory table query (encodeWord 0) [] saved [] (encodeWord p) level [] []⟩ := by + change some (TM2.stepAux subtractLoop _ _) = _ + simp [subtractLoop, TM2.stepAux, memory, encodeWord] + +theorem subtractStep_succ (table query level saved : List Bool) (k p : Nat) + (ambient : σ) (register : Option Bool) : + TM2.step program + ⟨some .subtract, ((ambient, false), register), + memory table query (encodeWord (k + 1)) [] saved [] (encodeWord (p + 1)) level [] []⟩ = + some ⟨some .subtract, ((ambient, false), none), + memory table query (encodeWord k) [] (true :: saved) [] (encodeWord p) level [] []⟩ := by + change some (TM2.stepAux subtractLoop _ _) = _ + simp [subtractLoop, TM2.stepAux, memory, encodeWord, List.replicate_succ] + +theorem subtractScanTrace (table query level : List Bool) (k p : Nat) + (saved : List Bool) (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[k + 1] + (some ⟨some .subtract, ((ambient, false), register), + memory table query (encodeWord k) [] saved [] (encodeWord (k + p)) level [] []⟩) = + some ⟨some .restore, ((ambient, false), none), + memory table query (encodeWord 0) [] (List.replicate k true ++ saved) [] + (encodeWord p) level [] []⟩ := by + induction k generalizing saved register with + | zero => simpa only [Nat.zero_add, Function.iterate_one, advance_some, + List.replicate_zero, List.nil_append] using + subtractStep_zero table query level saved p ambient register + | succ k ih => + rw [Function.iterate_succ_apply] + simp only [Nat.succ_add] + change (advance (TM2.step program))^[k + 1] + (TM2.step program ⟨some .subtract, ((ambient, false), register), + memory table query (encodeWord (k + 1)) [] saved [] + (encodeWord ((k + p) + 1)) level [] []⟩) = _ + rw [subtractStep_succ] + simpa only [List.replicate_succ', List.append_assoc, List.singleton_append] using + ih (true :: saved) none + +theorem subtractTrace (table query level : List Bool) (k p : Nat) (hkp : k ≤ p) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[2 * k + 2] + (some ⟨some .subtract, ((ambient, false), register), + memory table query (encodeWord k) [] [] [] (encodeWord p) level [] []⟩) = + some ⟨none, ((ambient, false), none), + memory table query (encodeWord k) [] [] [] (encodeWord (p - k)) level [] []⟩ := by + have hs := subtractScanTrace table query level k (p - k) [] ambient register + rw [show k + (p - k) = p by omega] at hs + simp only [List.append_nil] at hs + let mid := memory table query (encodeWord 0) [] (List.replicate k true) [] + (encodeWord (p - k)) level [] [] + have hr := Reduction.MachineTransfer.transferAt_fromTapes Tape.scratch Tape.count (by decide) + id false Label.restore none program rfl mid (ambient, false) none + simp only [mid, memory, List.length_replicate, List.reverse_replicate, List.map_id, + Reduction.MachineTransfer.tapesAt, update_scratch, update_count] at hr + rw [MachineCeilingPower.replicate_encodeWord, Nat.add_zero] at hr + have h := appendTrace _ hs hr + simpa only [show (k + 1) + (k + 1) = 2 * k + 2 by omega, Nat.add_zero] using h + +theorem branchStep_zero (table query : List Bool) (ambient : σ) (register : Option Bool) : + TM2.step program + ⟨some .branch, ((ambient, false), register), + memory table query (encodeWord 0) [] [] [] [] [] [] []⟩ = + some ⟨none, ((ambient, false), none), + memory table query (encodeWord 0) [] [] [] (encodeWord 0) (encodeWord 0) [] []⟩ := by + simp [TM2.step, program, TM2.stepAux, memory, encodeWord] + +theorem branchStep_succ (table query : List Bool) (k : Nat) (ambient : σ) + (register : Option Bool) : + TM2.step program + ⟨some .branch, ((ambient, false), register), + memory table query (encodeWord (k + 1)) [] [] [] [] [] [] []⟩ = + some ⟨some (.powerCode .init), ((ambient, false), none), + memory table query (encodeWord (k + 1)) [] [] [] [] [] [] []⟩ := by + simp [TM2.step, program, TM2.stepAux, memory, encodeWord, List.replicate_succ] + +def padding (k : Nat) : Nat := PreprocessingLevels.cloudPaddedSize k - k + +def postTime (k : Nat) : Nat := + 1 + if k = 0 then 0 else MachineCeilingPower.totalTime ExpanderFamily.growth k + (2 * k + 2) + +theorem postTrace (table query : List Bool) (k : Nat) (ambient : σ) + (register : Option Bool) : + (advance (TM2.step program))^[postTime k] + (some ⟨some .branch, ((ambient, false), register), + memory table query (encodeWord k) [] [] [] [] [] [] []⟩) = + some ⟨none, ((ambient, false), none), + memory table query (encodeWord k) [] [] [] (encodeWord (padding k)) + (encodeWord (PreprocessingLevels.boundedLevel k)) [] []⟩ := by + cases k with + | zero => + simpa only [postTime, ite_eq_left rfl, ite_true, Nat.add_zero, Function.iterate_one, advance_some, + padding, PreprocessingLevels.cloudPaddedSize_zero, Nat.sub_zero, + PreprocessingLevels.boundedLevel_zero] using branchStep_zero table query ambient register + | succ k => + have hb : (advance (TM2.step program))^[1] + (some ⟨some .branch, ((ambient, false), register), + memory table query (encodeWord (k + 1)) [] [] [] [] [] [] []⟩) = + some ⟨some (.powerCode .init), ((ambient, false), none), + memory table query (encodeWord (k + 1)) [] [] [] [] [] [] []⟩ := + branchStep_succ table query k ambient register + have hp := powerTrace table query (k + 1) ambient none + have hs := subtractTrace table query (encodeWord (PreprocessingLevels.boundedLevel (k + 1))) + (k + 1) (PreprocessingLevels.paddedSize (k + 1)) + (PreprocessingLevels.le_paddedSize (k + 1)) ambient none + have h := appendTrace _ hb (appendTrace _ hp hs) + simpa only [postTime, Nat.succ_ne_zero, ite_false, padding, + PreprocessingLevels.cloudPaddedSize_of_pos (Nat.succ_pos k)] using h + +theorem initStep (table query : List Bool) (ambient : σ) (register : Option Bool) : + TM2.step program + ⟨some .init, ((ambient, false), register), memory table query [] [] [] [] [] [] [] []⟩ = + some ⟨some (.countCode .copyFirst), ((ambient, false), register), + memory table query (encodeWord 0) [] [] [] [] [] [] []⟩ := by + simp [TM2.step, program, TM2.stepAux, memory, encodeWord] + +def totalTime (t : GraphTables.Table) (v : Fin t.vertices) : Nat := + (1 + MachineCloudCount.totalSteps t.vertices t.darts v.val (MachineCloudCount.tableRows t)) + + postTime (PreprocessingCloudIndex.cloudSize t v) + +theorem cloudPaddingTrace (t : GraphTables.Table) (v : Fin t.vertices) + (suffix : List Bool) (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[totalTime t v] + (some ⟨some .init, ((ambient, false), register), + memory (GraphTables.tableBits t) (encodeWord v.val ++ suffix) [] [] [] [] [] [] [] []⟩) = + some ⟨none, ((ambient, false), none), + memory (GraphTables.tableBits t) (encodeWord v.val ++ suffix) + (encodeWord (PreprocessingCloudIndex.cloudSize t v)) [] [] [] + (encodeWord (padding (PreprocessingCloudIndex.cloudSize t v))) + (encodeWord (PreprocessingLevels.boundedLevel (PreprocessingCloudIndex.cloudSize t v))) + [] []⟩ := by + have hi : (advance (TM2.step program))^[1] + (some ⟨some .init, ((ambient, false), register), + memory (GraphTables.tableBits t) (encodeWord v.val ++ suffix) [] [] [] [] [] [] [] []⟩) = + some ⟨some (.countCode .copyFirst), ((ambient, false), register), + memory (GraphTables.tableBits t) (encodeWord v.val ++ suffix) + (encodeWord 0) [] [] [] [] [] [] []⟩ := + initStep _ _ ambient register + exact appendTrace _ (appendTrace _ hi (countTrace t v suffix ambient register)) + (postTrace _ _ (PreprocessingCloudIndex.cloudSize t v) ambient none) + +def inputLength (t : GraphTables.Table) (v : Fin t.vertices) (suffix : List Bool) : Nat := + (GraphTables.tableBits t).length + (encodeWord v.val ++ suffix).length + +theorem count_length_le (t : GraphTables.Table) (v : Fin t.vertices) (suffix : List Bool) : + PreprocessingCloudIndex.cloudSize t v + 1 ≤ inputLength t v suffix := by + have h := (PreprocessingCloudIndex.cloudSize_le_darts t v).trans + (GraphTables.darts_le_tableBits_length t) + simp only [inputLength, List.length_append, encodeWord_length] + omega + +theorem table_length_le (t : GraphTables.Table) (v : Fin t.vertices) (suffix : List Bool) : + (GraphTables.tableBits t).length ≤ inputLength t v suffix := by + unfold inputLength + omega + +theorem postTime_le (k : Nat) : + postTime k ≤ 1 + MachineCeilingPower.timeBound ExpanderFamily.growth k + (2 * k + 2) := by + have h := MachineCeilingPower.totalTime_le ExpanderFamily.growth k + unfold postTime + split_ifs <;> omega + +noncomputable def timePolynomial : Polynomial Nat := + Polynomial.C (ExpanderFamily.growth + 8) * Polynomial.X ^ 2 + 25 * Polynomial.X + 10 + +theorem totalTime_le (t : GraphTables.Table) (v : Fin t.vertices) (suffix : List Bool) : + totalTime t v ≤ timePolynomial.eval (inputLength t v suffix) := by + have hc := MachineCloudCount.totalSteps_le t.vertices t.darts v.val (MachineCloudCount.tableRows t) + rw [MachineCloudCount.tableRows_input] at hc + have hp := postTime_le (PreprocessingCloudIndex.cloudSize t v) + have hk := count_length_le t v suffix + have ht := table_length_le t v suffix + have hsq := Nat.mul_le_mul_left (ExpanderFamily.growth + 8) + (Nat.pow_le_pow_left hk 2) + simp only [timePolynomial, Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_C, + Polynomial.eval_pow, Polynomial.eval_X, Polynomial.eval_ofNat] + unfold MachineCeilingPower.timeBound at hp + unfold totalTime + omega + +def cloudPaddingInTime (t : GraphTables.Table) (v : Fin t.vertices) + (suffix : List Bool) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some .init, ((ambient, false), register), + memory (GraphTables.tableBits t) (encodeWord v.val ++ suffix) [] [] [] [] [] [] [] []⟩ + (some ⟨none, ((ambient, false), none), + memory (GraphTables.tableBits t) (encodeWord v.val ++ suffix) + (encodeWord (PreprocessingCloudIndex.cloudSize t v)) [] [] [] + (encodeWord (padding (PreprocessingCloudIndex.cloudSize t v))) + (encodeWord (PreprocessingLevels.boundedLevel (PreprocessingCloudIndex.cloudSize t v))) + [] []⟩) + (timePolynomial.eval (inputLength t v suffix)) where + steps := totalTime t v + evals_in_steps := cloudPaddingTrace t v suffix ambient register + steps_le_m := totalTime_le t v suffix + +theorem count_add_padding (k : Nat) : k + padding k = PreprocessingLevels.cloudPaddedSize k := by + have h := (PreprocessingLevels.cloudPaddedSize_bounds k).1 + unfold padding + omega + +end MinUncutGames.Foundations.Complexity.MachineCloudPadding + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineCloudPrefix.lean b/lean/OAI/Computability/MinUncut/Machines/MachineCloudPrefix.lean new file mode 100644 index 0000000000000000000000000000000000000000..31fbfa111f1e3069d389ab6a2ea75d9ecbcc7079 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineCloudPrefix.lean @@ -0,0 +1,793 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachinePreservingLookup +import OAI.Computability.MinUncut.Machines.MachineCloudPadding +import OAI.Computability.MinUncut.PCP.PreprocessingPaddingOffsets + +namespace OAI + +namespace MinUncutGames.Foundations.Complexity.MachineCloudPrefix + +open Turing MachineComposition +open MinUncutGames.Foundations.PCP +open scoped BigOperators + +inductive Tape + | inner (k : MachineCloudPadding.Tape) + | bound | remaining | total + deriving DecidableEq, Fintype + +inductive Label + | init | copyFirst | copySecond | guard | done + | padding (l : MachineCloudPadding.Label) + | add | clearCount | clearLevel | increment + deriving DecidableEq, Fintype + +abbrev Alphabet (_ : Tape) := Bool +abbrev State (σ : Type) := (σ × Bool) × Option Bool + +def memory (inner : MachineCloudPadding.Tape → List Bool) (bound remaining total : List Bool) : + Tape → List Bool + | .inner k => inner k + | .bound => bound + | .remaining => remaining + | .total => total + +def frame (table query count power level bound remaining total : List Bool) : Tape → List Bool := + memory (MachineCloudPadding.memory table query count [] [] [] power level [] []) bound remaining total + +@[simp] theorem frame_query (a b c d e f g h : List Bool) : + frame a b c d e f g h (.inner .query) = b := rfl +@[simp] theorem frame_count (a b c d e f g h : List Bool) : + frame a b c d e f g h (.inner .count) = c := rfl +@[simp] theorem frame_power (a b c d e f g h : List Bool) : + frame a b c d e f g h (.inner .power) = d := rfl +@[simp] theorem frame_level (a b c d e f g h : List Bool) : + frame a b c d e f g h (.inner .level) = e := rfl +@[simp] theorem frame_bound (a b c d e f g h : List Bool) : + frame a b c d e f g h .bound = f := rfl +@[simp] theorem frame_remaining (a b c d e f g h : List Bool) : + frame a b c d e f g h .remaining = g := rfl +@[simp] theorem frame_total (a b c d e f g h : List Bool) : + frame a b c d e f g h .total = h := rfl + +@[simp] theorem update_frame_query (a b c d e f g h x : List Bool) : + Function.update (frame a b c d e f g h) (.inner .query) x = + frame a x c d e f g h := by + funext k; cases k with + | inner k => cases k <;> rfl + | bound => rfl + | remaining => rfl + | total => rfl +@[simp] theorem update_frame_count (a b c d e f g h x : List Bool) : + Function.update (frame a b c d e f g h) (.inner .count) x = + frame a b x d e f g h := by + funext k; cases k with + | inner k => cases k <;> rfl + | bound => rfl + | remaining => rfl + | total => rfl +@[simp] theorem update_frame_power (a b c d e f g h x : List Bool) : + Function.update (frame a b c d e f g h) (.inner .power) x = + frame a b c x e f g h := by + funext k; cases k with + | inner k => cases k <;> rfl + | bound => rfl + | remaining => rfl + | total => rfl +@[simp] theorem update_frame_level (a b c d e f g h x : List Bool) : + Function.update (frame a b c d e f g h) (.inner .level) x = + frame a b c d x f g h := by + funext k; cases k with + | inner k => cases k <;> rfl + | bound => rfl + | remaining => rfl + | total => rfl +@[simp] theorem update_frame_remaining (a b c d e f g h x : List Bool) : + Function.update (frame a b c d e f g h) .remaining x = + frame a b c d e f x h := by + funext k; cases k <;> rfl +@[simp] theorem update_frame_total (a b c d e f g h x : List Bool) : + Function.update (frame a b c d e f g h) .total x = + frame a b c d e f g x := by + funext k; cases k <;> rfl + +def paddingView : Tape → Option MachineCloudPadding.Tape + | .inner k => some k + | _ => none + +theorem paddingView_left (k : MachineCloudPadding.Tape) : paddingView (.inner k) = some k := rfl + +theorem paddingView_right (j : Tape) (k : MachineCloudPadding.Tape) + (h : paddingView j = some k) : Tape.inner k = j := by + cases j <;> simp_all [paddingView] + +theorem placedTapes (inner : MachineCloudPadding.Tape → List Bool) (extra : Tape → List Bool) : + MachineCloudPadding.Placement.tapes paddingView inner extra = + memory inner (extra .bound) (extra .remaining) (extra .total) := by + funext j; cases j <;> rfl + +variable {σ : Type} + +def program : Label → TM2.Stmt Alphabet Label (State σ) + | .init => .push (.inner .query) (fun _ => false) + (.push .total (fun _ => false) (.goto fun _ => .copyFirst)) + | .copyFirst => Reduction.MachineTransfer.loopAt + .bound (.inner .scratch) id false .copyFirst (some .copySecond) + | .copySecond => MachineCopy.forkLoop + (.inner .scratch) .bound .remaining false .copySecond (some .guard) + | .guard => MachineUnaryCounter.guard .remaining (.padding .init) .done + | .done => .halt + | .padding l => MachineCloudPadding.Placement.statement Tape.inner Label.padding (some .add) (MachineCloudPadding.program l) + | .add => MachineUnaryAddAt.loop (.inner .power) .total .add (some .clearCount) + | .clearCount => MachineLookup.discard (.inner .count) .clearCount .clearLevel + | .clearLevel => MachineLookup.discard (.inner .level) .clearLevel .increment + | .increment => .pop (.inner .power) (fun state _ => (state.1, none)) + (.push (.inner .query) (fun _ => true) (.goto fun _ => .guard)) + +theorem appendTrace {α : Type} (f : α → α) {a b : Nat} {x y z : α} + (hs : f^[a] x = y) (ht : f^[b] y = z) : f^[a + b] x = z := by + rw [Nat.add_comm a b, Function.iterate_add_apply, hs, ht] + +theorem paddingTrace (t : GraphTables.Table) (v : Fin t.vertices) + (bound remaining total : List Bool) (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[MachineCloudPadding.totalTime t v] + (some ⟨some (.padding .init), ((ambient, false), register), + frame (GraphTables.tableBits t) (encodeWord v.val) [] [] [] bound remaining total⟩) = + some ⟨some .add, ((ambient, false), none), + frame (GraphTables.tableBits t) (encodeWord v.val) + (encodeWord (PreprocessingCloudIndex.cloudSize t v)) + (encodeWord (MachineCloudPadding.padding (PreprocessingCloudIndex.cloudSize t v))) + (encodeWord (PreprocessingLevels.boundedLevel (PreprocessingCloudIndex.cloudSize t v))) + bound remaining total⟩ := by + have h := MachineCloudPadding.Placement.trace Tape.inner paddingView paddingView_left paddingView_right + Label.padding (some Label.add) (frame [] [] [] [] [] bound remaining total) + (MachineCloudPadding.program (σ := σ)) program (fun _ => rfl) _ _ _ + (MachineCloudPadding.cloudPaddingTrace t v [] ambient register) + simpa only [MachineCloudPadding.Placement.configuration, MachineCloudPadding.Placement.label, placedTapes, + frame_bound, frame_remaining, frame_total, List.append_nil, frame, memory] using h + +theorem incrementStep (table bound remaining total : List Bool) (v : Nat) + (ambient : σ) (register : Option Bool) : + TM2.step (program (σ := σ)) + ⟨some .increment, ((ambient, false), register), + frame table (encodeWord v) [] (encodeWord 0) [] bound remaining total⟩ = + some ⟨some .guard, ((ambient, false), none), + frame table (encodeWord (v + 1)) [] [] [] bound remaining total⟩ := by + simp [TM2.step, program, TM2.stepAux, encodeWord, List.replicate_succ] + +def bodyTime (t : GraphTables.Table) (v : Fin t.vertices) : Nat := + MachineCloudPadding.totalTime t v + (MachineCloudPadding.padding (PreprocessingCloudIndex.cloudSize t v) + 1) + + (PreprocessingCloudIndex.cloudSize t v + 1) + + (PreprocessingLevels.boundedLevel (PreprocessingCloudIndex.cloudSize t v) + 1) + 1 + +theorem bodyTrace (t : GraphTables.Table) (v : Fin t.vertices) + (bound remaining : List Bool) (acc : Nat) (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[bodyTime t v] + (some ⟨some (.padding .init), ((ambient, false), register), + frame (GraphTables.tableBits t) (encodeWord v.val) [] [] [] + bound remaining (encodeWord acc)⟩) = + some ⟨some .guard, ((ambient, false), none), + frame (GraphTables.tableBits t) (encodeWord (v.val + 1)) [] [] [] + bound remaining (encodeWord (MachineCloudPadding.padding (PreprocessingCloudIndex.cloudSize t v) + acc))⟩ := by + let k := PreprocessingCloudIndex.cloudSize t v + let p := MachineCloudPadding.padding k + let l := PreprocessingLevels.boundedLevel k + have hp := paddingTrace t v bound remaining (encodeWord acc) ambient register + have ha := MachineUnaryAddAt.addFromTapes (Tape.inner .power) Tape.total (by decide) + Label.add (some Label.clearCount) program rfl + (frame (GraphTables.tableBits t) (encodeWord v.val) (encodeWord k) + (encodeWord p) (encodeWord l) bound remaining (encodeWord acc)) + p acc [] [] (by simp) (by simp) (ambient, false) none + simp only [MachineUnaryAddAt.unaryTapes, Reduction.MachineTransfer.tapesAt, + List.append_nil, update_frame_power, update_frame_total] at ha + have hc := MachineLookup.discardTrace (Tape.inner .count) Label.clearCount Label.clearLevel + program rfl + (frame (GraphTables.tableBits t) (encodeWord v.val) (encodeWord k) + (encodeWord 0) (encodeWord l) bound remaining (encodeWord (p + acc))) + k [] (by simp) (ambient, false) none + simp only [update_frame_count] at hc + have hl := MachineLookup.discardTrace (Tape.inner .level) Label.clearLevel Label.increment + program rfl + (frame (GraphTables.tableBits t) (encodeWord v.val) [] + (encodeWord 0) (encodeWord l) bound remaining (encodeWord (p + acc))) + l [] (by simp) (ambient, false) none + simp only [update_frame_level] at hl + have hi : (advance (TM2.step program))^[1] + (some ⟨some .increment, ((ambient, false), none), + frame (GraphTables.tableBits t) (encodeWord v.val) [] (encodeWord 0) [] + bound remaining (encodeWord (p + acc))⟩) = + some ⟨some .guard, ((ambient, false), none), + frame (GraphTables.tableBits t) (encodeWord (v.val + 1)) [] [] [] + bound remaining (encodeWord (p + acc))⟩ := + incrementStep _ _ _ _ _ ambient none + exact appendTrace _ (appendTrace _ (appendTrace _ (appendTrace _ hp ha) hc) hl) hi + +theorem guardStep_succ (table bound suffix total : List Bool) (v n : Nat) + (ambient : σ) (register : Option Bool) : + TM2.step (program (σ := σ)) + ⟨some .guard, ((ambient, false), register), + frame table (encodeWord v) [] [] [] bound (encodeWord (n + 1) ++ suffix) total⟩ = + some ⟨some (.padding .init), ((ambient, false), none), + frame table (encodeWord v) [] [] [] bound (encodeWord n ++ suffix) total⟩ := by + simp [TM2.step, program, MachineUnaryCounter.guard, TM2.stepAux, encodeWord, + List.replicate_succ] + +theorem guardStep_zero (table bound suffix total : List Bool) (v : Nat) + (ambient : σ) (register : Option Bool) : + TM2.step (program (σ := σ)) + ⟨some .guard, ((ambient, false), register), + frame table (encodeWord v) [] [] [] bound (encodeWord 0 ++ suffix) total⟩ = + some ⟨some .done, ((ambient, false), none), + frame table (encodeWord v) [] [] [] bound (encodeWord 0 ++ suffix) total⟩ := rfl + +theorem zeroTrace (table bound suffix total : List Bool) (v : Nat) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step (program (σ := σ))))^[2] + (some ⟨some .guard, ((ambient, false), register), + frame table (encodeWord v) [] [] [] bound (encodeWord 0 ++ suffix) total⟩) = + some ⟨none, ((ambient, false), none), + frame table (encodeWord v) [] [] [] bound (encodeWord 0 ++ suffix) total⟩ := by + rw [Function.iterate_succ_apply] + change advance (TM2.step (program (σ := σ))) + (TM2.step program ⟨some .guard, ((ambient, false), register), + frame table (encodeWord v) [] [] [] bound (encodeWord 0 ++ suffix) total⟩) = _ + rw [guardStep_zero] + rfl + +def amount (t : GraphTables.Table) (v : Nat) : Nat := + if h : v < t.vertices then MachineCloudPadding.padding (PreprocessingCloudIndex.cloudSize t ⟨v, h⟩) else 0 + +def cycleTime (t : GraphTables.Table) (v : Nat) : Nat := + if h : v < t.vertices then 1 + bodyTime t ⟨v, h⟩ else 0 + +def sumFrom (t : GraphTables.Table) (v : Nat) : Nat → Nat + | 0 => 0 + | n + 1 => amount t v + sumFrom t (v + 1) n + +def loopTime (t : GraphTables.Table) (v : Nat) : Nat → Nat + | 0 => 2 + | n + 1 => cycleTime t v + loopTime t (v + 1) n + +theorem loopTrace (t : GraphTables.Table) (n v : Nat) (hvn : v + n ≤ t.vertices) + (bound suffix : List Bool) (acc : Nat) (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[loopTime t v n] + (some ⟨some .guard, ((ambient, false), register), + frame (GraphTables.tableBits t) (encodeWord v) [] [] [] + bound (encodeWord n ++ suffix) (encodeWord acc)⟩) = + some ⟨none, ((ambient, false), none), + frame (GraphTables.tableBits t) (encodeWord (v + n)) [] [] [] + bound (encodeWord 0 ++ suffix) (encodeWord (sumFrom t v n + acc))⟩ := by + induction n generalizing v acc register with + | zero => + simpa only [loopTime, sumFrom, Nat.add_zero, Nat.zero_add] using + zeroTrace _ bound suffix (encodeWord acc) v ambient register + | succ n ih => + have hv : v < t.vertices := by omega + have hnext : v + 1 + n ≤ t.vertices := by omega + have hg : (advance (TM2.step program))^[1] + (some ⟨some .guard, ((ambient, false), register), + frame (GraphTables.tableBits t) (encodeWord v) [] [] [] + bound (encodeWord (n + 1) ++ suffix) (encodeWord acc)⟩) = + some ⟨some (.padding .init), ((ambient, false), none), + frame (GraphTables.tableBits t) (encodeWord v) [] [] [] + bound (encodeWord n ++ suffix) (encodeWord acc)⟩ := + guardStep_succ _ bound suffix (encodeWord acc) v n ambient register + have hb := bodyTrace t ⟨v, hv⟩ bound (encodeWord n ++ suffix) acc ambient none + have ht := ih (v + 1) hnext + (MachineCloudPadding.padding (PreprocessingCloudIndex.cloudSize t ⟨v, hv⟩) + acc) none + have hall := appendTrace _ (appendTrace _ hg hb) ht + simpa only [loopTime, cycleTime, dite_eq_left hv, sumFrom, amount, + Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using hall + +theorem sumFrom_list (t : GraphTables.Table) (xs : List (Fin t.vertices)) (v : Nat) + (hseq : ∀ i (hi : i < xs.length), (xs[i]).val = v + i) : + sumFrom t v xs.length = (xs.map (PreprocessingRegularTables.padding t)).sum := by + induction xs generalizing v with + | nil => simp [sumFrom] + | cons x xs ih => + have hx : x.val = v := by simpa using! hseq 0 (by simp) + have hv : v < t.vertices := by simpa only [hx] using x.isLt + have he : (⟨v, hv⟩ : Fin t.vertices) = x := Fin.ext hx.symm + have hnext : ∀ i (hi : i < xs.length), (xs[i]).val = v + 1 + i := by + intro i hi + have h := hseq (i + 1) (by simpa using Nat.succ_lt_succ hi) + simpa only [List.getElem_cons_succ, Nat.add_assoc, Nat.add_comm, + Nat.add_left_comm] using h + simp only [List.length_cons, sumFrom, amount, dite_eq_left hv, he, + List.map_cons, List.sum_cons] + rw [ih (v + 1) hnext] + rfl + +theorem sumFrom_eq_offset (t : GraphTables.Table) (b : Nat) (hb : b ≤ t.vertices) : + sumFrom t 0 b = + PreprocessingPaddingOffsets.offset (PreprocessingRegularTables.padding t) b := by + have h := sumFrom_list t ((List.finRange t.vertices).take b) 0 + (by intro i hi; simp only [List.getElem_take, List.getElem_finRange, Fin.val_cast, + Nat.zero_add]) + simpa only [List.length_take, List.length_finRange, Nat.min_eq_left hb, + PreprocessingPaddingOffsets.offset] using h + +theorem initStep (table bound : List Bool) (ambient : σ) (register : Option Bool) : + TM2.step (program (σ := σ)) + ⟨some .init, ((ambient, false), register), frame table [] [] [] [] bound [] []⟩ = + some ⟨some .copyFirst, ((ambient, false), register), + frame table (encodeWord 0) [] [] [] bound [] (encodeWord 0)⟩ := by + simp [TM2.step, program, TM2.stepAux, encodeWord] + +def totalTime (t : GraphTables.Table) (b : Nat) (suffix : List Bool) : Nat := + (1 + 2 * ((encodeWord b ++ suffix).length + 1)) + loopTime t 0 b + +theorem prefixTrace (t : GraphTables.Table) (b : Nat) (hb : b ≤ t.vertices) + (suffix : List Bool) (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[totalTime t b suffix] + (some ⟨some .init, ((ambient, false), register), + frame (GraphTables.tableBits t) [] [] [] [] (encodeWord b ++ suffix) [] []⟩) = + some ⟨none, ((ambient, false), none), + frame (GraphTables.tableBits t) (encodeWord b) [] [] [] + (encodeWord b ++ suffix) (encodeWord 0 ++ suffix) + (encodeWord (PreprocessingPaddingOffsets.offset + (PreprocessingRegularTables.padding t) b))⟩ := by + have hi : (advance (TM2.step program))^[1] + (some ⟨some .init, ((ambient, false), register), + frame (GraphTables.tableBits t) [] [] [] [] (encodeWord b ++ suffix) [] []⟩) = + some ⟨some .copyFirst, ((ambient, false), register), + frame (GraphTables.tableBits t) (encodeWord 0) [] [] [] + (encodeWord b ++ suffix) [] (encodeWord 0)⟩ := + initStep _ _ ambient register + have hc := MachineCopy.copyTrace Tape.bound Tape.remaining (Tape.inner .scratch) + (by decide) (by decide) (by decide) false Label.copyFirst Label.copySecond + (some Label.guard) program rfl rfl + (frame (GraphTables.tableBits t) (encodeWord 0) [] [] [] + (encodeWord b ++ suffix) [] (encodeWord 0)) rfl (ambient, false) register + simp only [frame_bound, frame_remaining, List.append_nil, update_frame_remaining] at hc + have hl := loopTrace t b 0 (by simpa only [Nat.zero_add] using hb) + (encodeWord b ++ suffix) suffix 0 ambient none + simp only [Nat.zero_add, Nat.add_zero, sumFrom_eq_offset t b hb] at hl + exact appendTrace _ (appendTrace _ hi hc) hl + +def cycleBudget (L : Nat) : Nat := + (ExpanderFamily.growth + 8) * (2 * L) ^ 2 + 25 * (2 * L) + 10 + + (ExpanderFamily.growth + 2) * L + 5 + +theorem bodyTime_le (t : GraphTables.Table) (v : Fin t.vertices) (L : Nat) + (hL : (GraphTables.tableBits t).length ≤ L) : + 1 + bodyTime t v ≤ cycleBudget L := by + have hn := GraphTables.vertices_le_tableBits_length t + have hv := v.isLt + have hinput : MachineCloudPadding.inputLength t v [] ≤ 2 * L := by + simp only [MachineCloudPadding.inputLength, List.append_nil, encodeWord_length] + omega + have hp := (MachineCloudPadding.totalTime_le t v []).trans + (natPolynomial_eval_mono MachineCloudPadding.timePolynomial hinput) + simp only [MachineCloudPadding.timePolynomial, Polynomial.eval_add, Polynomial.eval_mul, + Polynomial.eval_C, Polynomial.eval_pow, Polynomial.eval_X, Polynomial.eval_ofNat] at hp + have hk : PreprocessingCloudIndex.cloudSize t v ≤ L := + (PreprocessingCloudIndex.cloudSize_le_darts t v).trans + ((GraphTables.darts_le_tableBits_length t).trans hL) + have hl := (PreprocessingLevels.boundedLevel_le_input + (PreprocessingCloudIndex.cloudSize t v)).trans hk + have hpad : MachineCloudPadding.padding (PreprocessingCloudIndex.cloudSize t v) ≤ + ExpanderFamily.growth * L := by + have hsize := (PreprocessingLevels.cloudPaddedSize_bounds + (PreprocessingCloudIndex.cloudSize t v)).2 + have hmul := Nat.mul_le_mul_left ExpanderFamily.growth hk + unfold MachineCloudPadding.padding + omega + unfold bodyTime cycleBudget + simp only [Nat.add_mul] at hp ⊢ + omega + +theorem loopTime_le (t : GraphTables.Table) (n v : Nat) (hvn : v + n ≤ t.vertices) + (L : Nat) (hL : (GraphTables.tableBits t).length ≤ L) : + loopTime t v n ≤ n * cycleBudget L + 2 := by + induction n generalizing v with + | zero => simp only [loopTime, Nat.zero_mul, Nat.zero_add, le_refl] + | succ n ih => + have hv : v < t.vertices := by omega + have hnext : v + 1 + n ≤ t.vertices := by omega + have hbody := bodyTime_le t ⟨v, hv⟩ L hL + have htail := ih (v + 1) hnext + simp only [loopTime, cycleTime, dite_eq_left hv, Nat.succ_mul] + omega + +def inputLength (t : GraphTables.Table) (b : Nat) (suffix : List Bool) : Nat := + (GraphTables.tableBits t).length + (encodeWord b ++ suffix).length + +noncomputable def timePolynomial : Polynomial Nat := + Polynomial.X * + (Polynomial.C (ExpanderFamily.growth + 8) * (2 * Polynomial.X) ^ 2 + + 25 * (2 * Polynomial.X) + 10 + + Polynomial.C (ExpanderFamily.growth + 2) * Polynomial.X + 5) + + 2 * (Polynomial.X + 1) + 3 + +theorem totalTime_le (t : GraphTables.Table) (b : Nat) (hb : b ≤ t.vertices) + (suffix : List Bool) : + totalTime t b suffix ≤ timePolynomial.eval (inputLength t b suffix) := by + let L := inputLength t b suffix + have htable : (GraphTables.tableBits t).length ≤ L := by + unfold L inputLength + omega + have hbound : (encodeWord b ++ suffix).length ≤ L := by + unfold L inputLength + omega + have hbL : b ≤ L := hb.trans ((GraphTables.vertices_le_tableBits_length t).trans htable) + have hloop := loopTime_le t b 0 (by simpa only [Nat.zero_add] using hb) L htable + have hmul := Nat.mul_le_mul_right (cycleBudget L) hbL + have htotal : totalTime t b suffix ≤ L * cycleBudget L + 2 * (L + 1) + 3 := by + unfold totalTime + omega + simpa only [timePolynomial, Polynomial.eval_add, Polynomial.eval_mul, + Polynomial.eval_C, Polynomial.eval_pow, Polynomial.eval_X, Polynomial.eval_ofNat, + Polynomial.eval_one, cycleBudget, L] using htotal + +def prefixInTime (t : GraphTables.Table) (b : Nat) (hb : b ≤ t.vertices) + (suffix : List Bool) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some .init, ((ambient, false), register), + frame (GraphTables.tableBits t) [] [] [] [] (encodeWord b ++ suffix) [] []⟩ + (some ⟨none, ((ambient, false), none), + frame (GraphTables.tableBits t) (encodeWord b) [] [] [] + (encodeWord b ++ suffix) (encodeWord 0 ++ suffix) + (encodeWord (PreprocessingPaddingOffsets.offset + (PreprocessingRegularTables.padding t) b))⟩) + (timePolynomial.eval (inputLength t b suffix)) where + steps := totalTime t b suffix + evals_in_steps := prefixTrace t b hb suffix ambient register + steps_le_m := totalTime_le t b hb suffix + +theorem all_padding_sum (t : GraphTables.Table) : + sumFrom t 0 t.vertices = ∑ v, PreprocessingRegularTables.padding t v := by + rw [sumFrom_eq_offset t t.vertices (Nat.le_refl _), PreprocessingPaddingOffsets.offset_all] + +theorem paddingOrder_eq_prefix (t : GraphTables.Table) (v : Fin t.vertices) + (j : Fin (PreprocessingRegularTables.padding t v)) : + (PreprocessingRegularTables.paddingOrder (PreprocessingRegularTables.padding t) ⟨v, j⟩).val = + sumFrom t 0 v.val + j.val := by + rw [PreprocessingPaddingOffsets.paddingOrder_val, + sumFrom_eq_offset t v.val v.isLt.le] + +end MinUncutGames.Foundations.Complexity.MachineCloudPrefix + +namespace MinUncutGames.Foundations.Complexity.MachinePreservingLookupClean + +open Turing +open MachineComposition + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool + +inductive Label + | run (label : MachinePreservingLookup.Label) + | cleanup + deriving DecidableEq, Fintype + +def statement (tape : Fin 5 → K) (labels : Label → Λ) (exit : Option Λ) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) + | .run label => MachineSubroutine.statement (fun label => labels (.run label)) + (some (labels .cleanup)) (MachinePreservingLookup.program tape label) + | .cleanup => MachineDrain.drain (tape 2) (labels .cleanup) exit + +def program (tape : Fin 5 → K) : + Label → TM2.Stmt (Alphabet (K := K)) Label (σ × Option Bool) := + statement tape id none + +def steps (values : List Nat) (index : Nat) : Nat := + (2 * ((encodeWords values).length + 1) + MachineLookupSpec.steps values index + 1) + + ((encodeWords (values.drop (index + 1))).length + 1) + +theorem remaining_length_le (values : List Nat) (index : Nat) : + (encodeWords (values.drop (index + 1))).length ≤ (encodeWords values).length := by + have h := congrArg (fun words : List Nat => (encodeWords words).length) + (List.take_append_drop (index + 1) values) + simp only [encodeWords_append, List.length_append] at h + omega + +theorem steps_le (values : List Nat) (index value : Nat) + (selected : values[index]? = some value) : + steps values index ≤ 6 * (encodeWords values).length + 4 := by + have hc := MachinePreservingLookup.preservingLookup_steps_le values index value selected + have hd := remaining_length_le values index + unfold steps + omega + +noncomputable def timePolynomial : Polynomial Nat := 6 * Polynomial.X + 4 + +theorem steps_le_timePolynomial (values : List Nat) (index value : Nat) + (selected : values[index]? = some value) : + steps values index ≤ timePolynomial.eval (encodeWords values).length := by + simpa only [timePolynomial, Polynomial.eval_add, Polynomial.eval_mul, + Polynomial.eval_ofNat, Polynomial.eval_X] using steps_le values index value selected + +theorem traceAt (tape : Fin 5 → K) (distinct : Function.Injective tape) + (labels : Label → Λ) (exit : Option Λ) + (target : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (code : ∀ label, target (labels label) = statement tape labels exit label) + (base : K → List Bool) (values : List Nat) + (tableWord : base (tape 0) = encodeWords values) + (scratchEmpty : base (tape 4) = []) + (index value : Nat) (selected : values[index]? = some value) + (indexSuffix output : List Bool) (ambient : σ) (register : Option Bool) : + (advance (TM2.step target))^[steps values index] + (some ⟨some (labels (.run .copyFirst)), (ambient, register), + MachinePreservingLookup.initialTapes tape base index indexSuffix [] output⟩) = + some ⟨exit, (ambient, none), + MachinePreservingLookup.initialTapes tape base 0 indexSuffix [] + (encodeWord value ++ output)⟩ := by + have hd (a b : Fin 5) (hne : a ≠ b) : tape a ≠ tape b := + fun h => hne (distinct h) + have raw := MachinePreservingLookup.preservingLookupTrace tape distinct + MachinePreservingLookup.Label.copyFirst MachinePreservingLookup.Label.copySecond + MachinePreservingLookup.Label.lookup none (MachinePreservingLookup.program tape) + rfl rfl (fun _ => rfl) base values tableWord scratchEmpty index value selected + indexSuffix [] output ambient register + have run := MachineSubroutine.trace (fun label => labels (.run label)) + (some (labels .cleanup)) (MachinePreservingLookup.program tape) target + (fun label => code (.run label)) + (2 * ((encodeWords values).length + 1) + MachineLookupSpec.steps values index + 1) + _ _ raw + simp only [MachineSubroutine.configuration, MachineSubroutine.label] at run + have cleanup := MachineDrain.drainTrace (tape 2) (labels .cleanup) exit target + (code .cleanup) + (MachinePreservingLookup.finalTapes tape base values index value indexSuffix [] output) + (encodeWords (values.drop (index + 1))) ambient none + have word : MachinePreservingLookup.finalTapes tape base values index value + indexSuffix [] output (tape 2) = encodeWords (values.drop (index + 1)) := by + simp only [MachinePreservingLookup.finalTapes, + MachineLookup.tapes_source _ _ _ (hd 2 3 (by decide)), List.append_nil] + have start : Function.update + (MachinePreservingLookup.finalTapes tape base values index value indexSuffix [] output) + (tape 2) (encodeWords (values.drop (index + 1))) = + MachinePreservingLookup.finalTapes tape base values index value indexSuffix [] output := by + rw [← word, Function.update_eq_self] + have finish : Function.update + (MachinePreservingLookup.finalTapes tape base values index value indexSuffix [] output) + (tape 2) [] = MachinePreservingLookup.initialTapes tape base 0 indexSuffix [] + (encodeWord value ++ output) := by + unfold MachinePreservingLookup.finalTapes MachinePreservingLookup.initialTapes + rw [MachineLookup.update_source _ _ _ (hd 2 3 (by decide))] + rw [start, finish] at cleanup + rw [show steps values index = + ((encodeWords (values.drop (index + 1))).length + 1) + + (2 * ((encodeWords values).length + 1) + MachineLookupSpec.steps values index + 1) by + unfold steps + omega, + Function.iterate_add_apply, run] + exact cleanup + +def inTimeAt (tape : Fin 5 → K) (distinct : Function.Injective tape) + (labels : Label → Λ) (exit : Option Λ) + (target : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (code : ∀ label, target (labels label) = statement tape labels exit label) + (base : K → List Bool) (values : List Nat) + (tableWord : base (tape 0) = encodeWords values) + (scratchEmpty : base (tape 4) = []) + (index value : Nat) (selected : values[index]? = some value) + (indexSuffix output : List Bool) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step target) + ⟨some (labels (.run .copyFirst)), (ambient, register), + MachinePreservingLookup.initialTapes tape base index indexSuffix [] output⟩ + (some ⟨exit, (ambient, none), + MachinePreservingLookup.initialTapes tape base 0 indexSuffix [] + (encodeWord value ++ output)⟩) + (timePolynomial.eval (encodeWords values).length) where + steps := steps values index + evals_in_steps := traceAt tape distinct labels exit target code base values tableWord + scratchEmpty index value selected indexSuffix output ambient register + steps_le_m := steps_le_timePolynomial values index value selected + +theorem initialTapes_eq (tape : Fin 5 → K) (base : K → List Bool) + (index : Nat) (indexSuffix : List Bool) + (counterWord : base (tape 1) = encodeWord index ++ indexSuffix) + (workEmpty : base (tape 2) = []) : + MachinePreservingLookup.initialTapes tape base index indexSuffix [] (base (tape 3)) = + base := by + simp only [MachinePreservingLookup.initialTapes, MachineLookup.tapes, + ← counterWord, ← workEmpty, Function.update_eq_self] + +theorem traceAt_fromTapes (tape : Fin 5 → K) (distinct : Function.Injective tape) + (labels : Label → Λ) (exit : Option Λ) + (target : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (code : ∀ label, target (labels label) = statement tape labels exit label) + (base : K → List Bool) (values : List Nat) + (tableWord : base (tape 0) = encodeWords values) + (scratchEmpty : base (tape 4) = []) + (index value : Nat) (selected : values[index]? = some value) + (indexSuffix : List Bool) + (counterWord : base (tape 1) = encodeWord index ++ indexSuffix) + (workEmpty : base (tape 2) = []) (ambient : σ) (register : Option Bool) : + (advance (TM2.step target))^[steps values index] + (some ⟨some (labels (.run .copyFirst)), (ambient, register), base⟩) = + some ⟨exit, (ambient, none), + MachinePreservingLookup.initialTapes tape base 0 indexSuffix [] + (encodeWord value ++ base (tape 3))⟩ := by + have h := traceAt tape distinct labels exit target code base values tableWord scratchEmpty + index value selected indexSuffix (base (tape 3)) ambient register + rw [initialTapes_eq tape base index indexSuffix counterWord workEmpty] at h + exact h + +def machine : FinTM2 where + K := Fin 5 + k₀ := 0 + k₁ := 3 + Γ _ := Bool + Λ := Label + main := .run .copyFirst + σ := Unit × Option Bool + initialState := ((), none) + m := program id + +def machineInTime (base : Fin 5 → List Bool) (values : List Nat) + (tableWord : base 0 = encodeWords values) (scratchEmpty : base 4 = []) + (index value : Nat) (selected : values[index]? = some value) + (indexSuffix output : List Bool) (register : Option Bool) : + StateTransition.EvalsToInTime machine.step + ⟨some (.run .copyFirst), ((), register), + MachinePreservingLookup.initialTapes id base index indexSuffix [] output⟩ + (some ⟨none, ((), none), + MachinePreservingLookup.initialTapes id base 0 indexSuffix [] + (encodeWord value ++ output)⟩) + (timePolynomial.eval (encodeWords values).length) := + inTimeAt id (fun _ _ h => h) id none (program id) (fun _ => rfl) + base values tableWord scratchEmpty index value selected indexSuffix output () register + +end MinUncutGames.Foundations.Complexity.MachinePreservingLookupClean + +namespace MinUncutGames.Foundations.Complexity.MachineAppendAt + +open Turing + +variable {K Λ σ β : Type} [DecidableEq K] + +abbrev Alphabet (β : Type) (_ : K) := β + +def appendTapes (source destination : K) (base : K → List β) : K → List β := + Reduction.MachineTransfer.tapesAt source destination base [] + (base destination ++ base source) + +@[simp] theorem appendTapes_source (source destination : K) + (distinct : source ≠ destination) (base : K → List β) : + appendTapes source destination base source = [] := by + simp [appendTapes, distinct] + +@[simp] theorem appendTapes_destination (source destination : K) (base : K → List β) : + appendTapes source destination base destination = base destination ++ base source := by + simp [appendTapes] + +theorem appendTapes_other (source destination k : K) + (notSource : k ≠ source) (notDestination : k ≠ destination) (base : K → List β) : + appendTapes source destination base k = base k := by + simp [appendTapes, Reduction.MachineTransfer.tapesAt, notSource, notDestination] + +theorem appendTapes_scratch (source destination scratch : K) + (sourceScratch : source ≠ scratch) (destinationScratch : destination ≠ scratch) + (base : K → List β) (scratchEmpty : base scratch = []) : + appendTapes source destination base scratch = [] := by + rw [appendTapes_other source destination scratch (Ne.symm sourceScratch) + (Ne.symm destinationScratch) base, scratchEmpty] + +def firstTapes (destination scratch : K) (base : K → List β) : K → List β := + Reduction.MachineTransfer.tapesAt destination scratch base [] (base destination).reverse + +private def secondTapes (source destination scratch : K) (base : K → List β) : K → List β := + Reduction.MachineTransfer.tapesAt source scratch (firstTapes destination scratch base) [] + ((base source).reverse ++ (base destination).reverse) + +theorem finalTapes_eq (source destination scratch : K) + (sourceDestination : source ≠ destination) (sourceScratch : source ≠ scratch) + (destinationScratch : destination ≠ scratch) (base : K → List β) + (scratchEmpty : base scratch = []) : + Reduction.MachineTransfer.tapesAt scratch destination + (secondTapes source destination scratch base) [] (base destination ++ base source) = + appendTapes source destination base := by + funext k + by_cases hs : k = source + · subst k + simp [appendTapes, secondTapes, firstTapes, Reduction.MachineTransfer.tapesAt, + sourceDestination, sourceScratch] + · by_cases hd : k = destination + · subst k + simp [appendTapes, Reduction.MachineTransfer.tapesAt] + · by_cases ht : k = scratch + · subst k + simp [appendTapes, Reduction.MachineTransfer.tapesAt, Ne.symm sourceScratch, + Ne.symm destinationScratch, scratchEmpty] + · simp [appendTapes, secondTapes, firstTapes, Reduction.MachineTransfer.tapesAt, + hs, hd, ht] + +theorem appendTrace (source destination scratch : K) + (sourceDestination : source ≠ destination) (sourceScratch : source ≠ scratch) + (destinationScratch : destination ≠ scratch) + (fallback : β) (firstLabel secondLabel thirdLabel : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K) β) Λ (σ × Option β)) + (atFirst : program firstLabel = Reduction.MachineTransfer.loopAt destination scratch + id fallback firstLabel (some secondLabel)) + (atSecond : program secondLabel = Reduction.MachineTransfer.loopAt source scratch + id fallback secondLabel (some thirdLabel)) + (atThird : program thirdLabel = Reduction.MachineTransfer.loopAt scratch destination + id fallback thirdLabel exit) + (base : K → List β) (scratchEmpty : base scratch = []) + (ambient : σ) (register : Option β) : + (MachineComposition.advance (TM2.step program))^[ + 2 * ((base source).length + (base destination).length) + 3] + (some ⟨some firstLabel, (ambient, register), base⟩) = + some ⟨exit, (ambient, none), appendTapes source destination base⟩ := by + have first := Reduction.MachineTransfer.transferAt_fromTapes destination scratch + destinationScratch id fallback firstLabel (some secondLabel) program atFirst + base ambient register + change (MachineComposition.advance (TM2.step program))^[(base destination).length + 1] + (some ⟨some firstLabel, (ambient, register), base⟩) = _ at first + simp only [List.map_id, scratchEmpty, List.append_nil] at first + change (MachineComposition.advance (TM2.step program))^[(base destination).length + 1] + (some ⟨some firstLabel, (ambient, register), base⟩) = + some ⟨some secondLabel, (ambient, none), firstTapes destination scratch base⟩ at first + have firstSource : firstTapes destination scratch base source = base source := by + simp [firstTapes, Reduction.MachineTransfer.tapesAt, sourceDestination, sourceScratch] + have firstScratch : firstTapes destination scratch base scratch = + (base destination).reverse := by + simp [firstTapes] + have second := Reduction.MachineTransfer.transferAt_fromTapes source scratch + sourceScratch id fallback secondLabel (some thirdLabel) program atSecond + (firstTapes destination scratch base) ambient none + change (MachineComposition.advance (TM2.step program))^[ + (firstTapes destination scratch base source).length + 1] + (some ⟨some secondLabel, (ambient, none), firstTapes destination scratch base⟩) = _ + at second + rw [firstSource, firstScratch] at second + simp only [List.map_id] at second + change (MachineComposition.advance (TM2.step program))^[(base source).length + 1] + (some ⟨some secondLabel, (ambient, none), firstTapes destination scratch base⟩) = + some ⟨some thirdLabel, (ambient, none), secondTapes source destination scratch base⟩ + at second + have secondScratch : secondTapes source destination scratch base scratch = + (base source).reverse ++ (base destination).reverse := by + simp [secondTapes] + have secondDestination : secondTapes source destination scratch base destination = [] := by + simp [secondTapes, firstTapes, Reduction.MachineTransfer.tapesAt, + Ne.symm sourceDestination, destinationScratch] + have third := Reduction.MachineTransfer.transferAt_fromTapes scratch destination + (Ne.symm destinationScratch) id fallback thirdLabel exit program atThird + (secondTapes source destination scratch base) ambient none + change (MachineComposition.advance (TM2.step program))^[ + (secondTapes source destination scratch base scratch).length + 1] + (some ⟨some thirdLabel, (ambient, none), secondTapes source destination scratch base⟩) = _ + at third + rw [secondScratch, secondDestination] at third + simp only [List.map_id, List.reverse_append, List.reverse_reverse, List.append_nil, + List.length_append, List.length_reverse] at third + rw [finalTapes_eq source destination scratch sourceDestination sourceScratch + destinationScratch base scratchEmpty] at third + rw [show 2 * ((base source).length + (base destination).length) + 3 = + ((base source).length + (base destination).length + 1) + + (((base source).length + 1) + ((base destination).length + 1)) by omega] + rw [Function.iterate_add_apply] + rw [Function.iterate_add_apply (m := (base source).length + 1) + (n := (base destination).length + 1), first, second] + exact third + +def appendInTime (source destination scratch : K) + (sourceDestination : source ≠ destination) (sourceScratch : source ≠ scratch) + (destinationScratch : destination ≠ scratch) + (fallback : β) (firstLabel secondLabel thirdLabel : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K) β) Λ (σ × Option β)) + (atFirst : program firstLabel = Reduction.MachineTransfer.loopAt destination scratch + id fallback firstLabel (some secondLabel)) + (atSecond : program secondLabel = Reduction.MachineTransfer.loopAt source scratch + id fallback secondLabel (some thirdLabel)) + (atThird : program thirdLabel = Reduction.MachineTransfer.loopAt scratch destination + id fallback thirdLabel exit) + (base : K → List β) (scratchEmpty : base scratch = []) + (ambient : σ) (register : Option β) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some firstLabel, (ambient, register), base⟩ + (some ⟨exit, (ambient, none), appendTapes source destination base⟩) + (2 * ((base source).length + (base destination).length) + 3) where + steps := 2 * ((base source).length + (base destination).length) + 3 + evals_in_steps := appendTrace source destination scratch sourceDestination sourceScratch + destinationScratch fallback firstLabel secondLabel thirdLabel exit program atFirst + atSecond atThird base scratchEmpty ambient register + steps_le_m := Nat.le_refl _ + +end MinUncutGames.Foundations.Complexity.MachineAppendAt + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineCloudSelect.lean b/lean/OAI/Computability/MinUncut/Machines/MachineCloudSelect.lean new file mode 100644 index 0000000000000000000000000000000000000000..51bffe25323b2c33d79f2c1e32781fa0c4f62150 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineCloudSelect.lean @@ -0,0 +1,642 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineRegularLift + +namespace OAI + +section +namespace MinUncutGames.Foundations.Complexity.MachineCloudSelect + +open Turing MachineComposition +open MachineCloudCount (Row rowWords rowTime rowsHits tableRows) + +abbrev BaseTape := MachineCloudCount.Tape +abbrev BaseAlphabet := MachineCloudCount.Alphabet +abbrev BaseState (σ : Type) := MachineCloudCount.State σ + +inductive BaseLabel + | queryFirst | querySecond | querySkip | tableFirst | tableSecond + | headerFirst | headerSecond | field | restore | done | clearWork | clearRank + | skip (i : Fin 4097) + deriving DecidableEq, Fintype + +def skipLabel (i : Nat) : BaseLabel := + if h : i < 4097 then .skip ⟨i, h⟩ else .done + +variable {σ : Type} + +def baseProgram : BaseLabel → TM2.Stmt BaseAlphabet BaseLabel (BaseState σ) + | .queryFirst => Reduction.MachineTransfer.loopAt .target .scratch id false + .queryFirst (some .querySecond) + | .querySecond => MachineCopy.forkLoop .scratch .target .spare false + .querySecond (some .querySkip) + | .querySkip => MachineLookup.discard .spare .querySkip .tableFirst + | .tableFirst => Reduction.MachineTransfer.loopAt .original .scratch id false + .tableFirst (some .tableSecond) + | .tableSecond => MachineCopy.forkLoop .scratch .original .work false + .tableSecond (some .headerFirst) + | .headerFirst => MachineLookup.discard .work .headerFirst .headerSecond + | .headerSecond => MachineLookup.discard .work .headerSecond .field + | .field => MachineCloudCount.fieldLoop .field .restore + | .restore => Reduction.MachineTransfer.loopAt .scratch .target id false + .restore (some .done) + | .skip i => MachineLookup.discard .work (.skip i) (skipLabel (i.val + 1)) + | .clearWork => MachineDrain.drain .work .clearWork (some .clearRank) + | .clearRank => MachineDrain.drain .spare .clearRank (some .done) + | .done => .halt + +theorem baseProgram_skip {i : Nat} (hi : i < 4097) : + baseProgram (σ := σ) (skipLabel i) = + MachineLookup.discard .work (skipLabel i) (skipLabel (i + 1)) := by + simp only [skipLabel, dite_eq_left hi, baseProgram] + +inductive Phase + | checking | advancing | finishing + deriving DecidableEq + +protected abbrev Phase.enumList : List Phase := [.checking, .advancing, .finishing] + +protected theorem Phase.enumList_getElem?_ctorIdx_eq (x : Phase) : + Phase.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem Phase.enumList_nodup : Phase.enumList.Nodup := by decide + +instance : Fintype Phase where + elems := ⟨Phase.enumList, Phase.enumList_nodup⟩ + complete x := by cases x <;> decide +inductive Control + | initialize | dispatch + deriving DecidableEq + +protected abbrev Control.enumList : List Control := [.initialize, .dispatch] + +protected theorem Control.enumList_getElem?_ctorIdx_eq (x : Control) : + Control.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem Control.enumList_nodup : Control.enumList.Nodup := by decide + +instance : Fintype Control where + elems := ⟨Control.enumList, Control.enumList_nodup⟩ + complete x := by cases x <;> decide + +abbrev Tape := BaseTape ⊕ Unit +abbrev Alphabet : Tape → Type := MachineEmbedding.Alphabet BaseAlphabet (fun _ : Unit => Bool) +abbrev Label := BaseLabel ⊕ Control +abbrev State (σ : Type) := BaseState σ × Phase + +def go (phase : Phase) (label : Label) : TM2.Stmt Alphabet Label (State σ) := + .load (fun s => ((s.1.1, none), phase)) (.goto fun _ => label) + +def dispatcher : TM2.Stmt Alphabet Label (State σ) := + .branch (fun s => decide (s.2 = .checking)) + (.pop (.inl .count) (fun s bit => ((s.1.1, bit), s.2)) + (.branch (fun s => s.1.2.getD false) + (.pop (.inl .spare) (fun s bit => ((s.1.1, bit), s.2)) + (.branch (fun s => s.1.2.getD false) + (go .advancing (.inl (skipLabel 0))) + (go .finishing (.inl .clearWork)))) + (go .advancing (.inl (skipLabel 0))))) + (.branch (fun s => decide (s.2 = .advancing)) + (.push (.inr ()) (fun _ => true) (go .checking (.inl .field))) + (.load (fun s => ((s.1.1, none), Phase.checking)) .halt)) + +def extra : Control → TM2.Stmt Alphabet Label (State σ) + | .initialize => .push (.inr ()) (fun _ => false) (go .checking (.inl .queryFirst)) + | .dispatch => dispatcher + +def program : Label → TM2.Stmt Alphabet Label (State σ) := + MachineEmbedding.program (some (.inr .dispatch)) baseProgram extra + +def memory (original work target scratch hit rank position : List Bool) : + ∀ k, List (Alphabet k) := + MachineEmbedding.tapes (MachineCloudCount.memory original work target scratch hit rank) + (fun _ : Unit => position) + +@[simp] theorem memory_inl (a b c d e f g : List Bool) (k : BaseTape) : + memory a b c d e f g (.inl k) = MachineCloudCount.memory a b c d e f k := rfl +@[simp] theorem memory_position (a b c d e f g : List Bool) : + memory a b c d e f g (.inr ()) = g := rfl + +@[simp] theorem update_memory_hit (a b c d e f g x : List Bool) : + Function.update (memory a b c d e f g) (.inl .count) x = memory a b c d x f g := by + funext k + cases k with + | inl k => cases k <;> rfl + | inr k => cases k; rfl +@[simp] theorem update_memory_rank (a b c d e f g x : List Bool) : + Function.update (memory a b c d e f g) (.inl .spare) x = memory a b c d e x g := by + funext k + cases k with + | inl k => cases k <;> rfl + | inr k => cases k; rfl +@[simp] theorem update_memory_position (a b c d e f g x : List Bool) : + Function.update (memory a b c d e f g) (.inr ()) x = memory a b c d e f x := by + funext k + cases k with + | inl k => cases k <;> rfl + | inr k => cases k; rfl + +def cfg (label : Option Label) (phase : Phase) + (original work target hit rank position : List Bool) + (ambient : σ) (register : Option Bool) : TM2.Cfg Alphabet Label (State σ) := + ⟨label, (((ambient, false), register), phase), memory original work target [] hit rank position⟩ + +theorem liftTrace (phase : Phase) (position : List Bool) (n : Nat) + (a b : TM2.Cfg BaseAlphabet BaseLabel (BaseState σ)) + (h : (advance (TM2.step baseProgram))^[n] (some a) = some b) : + (advance (TM2.step (program (σ := σ))))^[n] + (some (MachineEmbedding.configuration (some (.inr .dispatch)) phase + (fun _ : Unit => position) a)) = + some (MachineEmbedding.configuration (some (.inr .dispatch)) phase + (fun _ : Unit => position) b) := + liftSuccessfulTrace (TM2.step baseProgram) (TM2.step program) + (MachineEmbedding.configuration (some (.inr .dispatch)) phase (fun _ : Unit => position)) + (MachineEmbedding.step_simulation (some (.inr .dispatch)) phase + (fun _ : Unit => position) baseProgram extra) n a b h + +theorem compareTrace (original suffix targetSuffix rank position : List Bool) + (x v : Nat) (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[x + min x v + 3] + (some (cfg (some (.inl .field)) .checking original (encodeWord x ++ suffix) + (encodeWord v ++ targetSuffix) [] rank position ambient register)) = + some (cfg (some (.inr .dispatch)) .checking original suffix + (encodeWord v ++ targetSuffix) (List.replicate (if x = v then 1 else 0) true) + rank position ambient none) := by + have h := MachineCloudCount.preservingFieldTrace BaseLabel.field BaseLabel.restore BaseLabel.done + baseProgram rfl rfl original suffix targetSuffix [] rank x v ambient register + simp only [List.append_nil] at h + have hhalt : (advance (TM2.step baseProgram))^[x + min x v + 3] + (some ⟨some .field, ((ambient, false), register), + MachineCloudCount.memory original (encodeWord x ++ suffix) + (encodeWord v ++ targetSuffix) [] [] rank⟩) = + some ⟨none, ((ambient, false), none), + MachineCloudCount.memory original suffix (encodeWord v ++ targetSuffix) [] + (List.replicate (if x = v then 1 else 0) true) rank⟩ := by + rw [show x + min x v + 3 = (x + min x v + 2) + 1 by omega, + Function.iterate_succ_apply', h, advance_some] + rfl + convert liftTrace Phase.checking position _ _ _ hhalt using 1 <;> rfl + +theorem dispatch_miss (original work target rank position : List Bool) (ambient : σ) : + TM2.step program (cfg (some (.inr .dispatch)) .checking + original work target [] rank position ambient none) = + some (cfg (some (.inl (skipLabel 0))) .advancing + original work target [] rank position ambient none) := by + simp [program, MachineEmbedding.program, extra, dispatcher, go, TM2.stepAux, TM2.step, cfg] + +theorem dispatch_hit_succ (original work target rankSuffix position : List Bool) + (rank : Nat) (ambient : σ) : + TM2.step program (cfg (some (.inr .dispatch)) .checking + original work target [true] (encodeWord (rank + 1) ++ rankSuffix) position ambient none) = + some (cfg (some (.inl (skipLabel 0))) .advancing original work target [] + (encodeWord rank ++ rankSuffix) position ambient none) := by + simp [program, MachineEmbedding.program, extra, dispatcher, go, TM2.stepAux, TM2.step, + cfg, encodeWord, List.replicate_succ] + +theorem dispatch_hit_zero (original work target rankSuffix position : List Bool) (ambient : σ) : + TM2.step program (cfg (some (.inr .dispatch)) .checking + original work target [true] (encodeWord 0 ++ rankSuffix) position ambient none) = + some (cfg (some (.inl .clearWork)) .finishing + original work target [] rankSuffix position ambient none) := by + simp [program, MachineEmbedding.program, extra, dispatcher, go, TM2.stepAux, TM2.step, + cfg, encodeWord] + +theorem advanceStep (original work target rank positionSuffix : List Bool) + (position : Nat) (ambient : σ) : + TM2.step program (cfg (some (.inr .dispatch)) .advancing original work target [] + rank (encodeWord position ++ positionSuffix) ambient none) = + some (cfg (some (.inl .field)) .checking original work target [] + rank (encodeWord (position + 1) ++ positionSuffix) ambient none) := by + simp [program, MachineEmbedding.program, extra, dispatcher, go, TM2.stepAux, TM2.step, + cfg, encodeWord, List.replicate_succ] + +theorem finishStep (original target position : List Bool) (ambient : σ) : + TM2.step program (cfg (some (.inr .dispatch)) .finishing + original [] target [] [] position ambient none) = + some (cfg none .checking original [] target [] [] position ambient none) := by + simp [program, MachineEmbedding.program, extra, dispatcher, go, TM2.stepAux, TM2.step, cfg] + +theorem initializeStep (original target output : List Bool) (ambient : σ) (register : Option Bool) : + TM2.step program (cfg (some (.inr .initialize)) .checking + original [] target [] [] output ambient register) = + some (cfg (some (.inl .queryFirst)) .checking + original [] target [] [] (encodeWord 0 ++ output) ambient none) := by + simp [program, MachineEmbedding.program, extra, go, TM2.stepAux, TM2.step, cfg, encodeWord] + +theorem skipTrace (fields : List Nat) (hwidth : fields.length = 4097) + (original suffix target rank position : List Bool) (ambient : σ) : + (advance (TM2.step program))^[(encodeWords fields).length + 1] + (some (cfg (some (.inl (skipLabel 0))) .advancing original + (encodeWords fields ++ suffix) target [] rank position ambient none)) = + some (cfg (some (.inr .dispatch)) .advancing + original suffix target [] rank position ambient none) := by + have h := MachineCloudCount.discardFieldsTrace skipLabel (baseProgram (σ := σ)) fields 0 + (by intro i hi; simpa only [Nat.zero_add] using baseProgram_skip (hwidth ▸ hi)) + original suffix target [] [] rank ambient false none + have hnonempty : fields ≠ [] := by intro h; simp [h] at hwidth + simp only [Nat.zero_add, hwidth, skipLabel, lt_self_iff_false, ↓reduceDIte, + hnonempty, ite_false] at h + have raw : (advance (TM2.step baseProgram))^[(encodeWords fields).length + 1] + (some ⟨some (skipLabel 0), ((ambient, false), none), + MachineCloudCount.memory original (encodeWords fields ++ suffix) target [] [] rank⟩) = + some ⟨none, ((ambient, false), none), + MachineCloudCount.memory original suffix target [] [] rank⟩ := by + rw [Function.iterate_succ_apply'] + simp only [skipLabel, dite_eq_left (by decide : 0 < 4097)] at h ⊢ + rw [h, advance_some] + rfl + convert liftTrace Phase.advancing position _ _ _ raw using 1 <;> rfl + +theorem rowSkipTrace (r : Row) (hwidth : r.2.length = 4097) (v rank position : Nat) + (original suffix targetSuffix rankSuffix outputSuffix : List Bool) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[rowTime v r + 3] + (some (cfg (some (.inl .field)) .checking original + (encodeWords (rowWords r) ++ suffix) (encodeWord v ++ targetSuffix) [] + (encodeWord (rank + if r.1 = v then 1 else 0) ++ rankSuffix) + (encodeWord position ++ outputSuffix) ambient register)) = + some (cfg (some (.inl .field)) .checking original suffix + (encodeWord v ++ targetSuffix) [] (encodeWord rank ++ rankSuffix) + (encodeWord (position + 1) ++ outputSuffix) ambient none) := by + have hcompare := compareTrace original (encodeWords r.2 ++ suffix) targetSuffix + (encodeWord (rank + if r.1 = v then 1 else 0) ++ rankSuffix) + (encodeWord position ++ outputSuffix) r.1 v ambient register + have hdispatch : TM2.step program + (cfg (some (.inr .dispatch)) .checking original (encodeWords r.2 ++ suffix) + (encodeWord v ++ targetSuffix) (List.replicate (if r.1 = v then 1 else 0) true) + (encodeWord (rank + if r.1 = v then 1 else 0) ++ rankSuffix) + (encodeWord position ++ outputSuffix) ambient none) = + some (cfg (some (.inl (skipLabel 0))) .advancing original (encodeWords r.2 ++ suffix) + (encodeWord v ++ targetSuffix) [] (encodeWord rank ++ rankSuffix) + (encodeWord position ++ outputSuffix) ambient none) := by + by_cases hit : r.1 = v + · simpa only [ite_eq_left hit, List.replicate_succ, List.replicate_zero] using + dispatch_hit_succ original (encodeWords r.2 ++ suffix) (encodeWord v ++ targetSuffix) + rankSuffix (encodeWord position ++ outputSuffix) rank ambient + · simpa only [ite_eq_right hit, Nat.add_zero, List.replicate_zero] using + dispatch_miss original (encodeWords r.2 ++ suffix) (encodeWord v ++ targetSuffix) + (encodeWord rank ++ rankSuffix) (encodeWord position ++ outputSuffix) ambient + have hskip := skipTrace r.2 hwidth original suffix (encodeWord v ++ targetSuffix) + (encodeWord rank ++ rankSuffix) (encodeWord position ++ outputSuffix) ambient + have ht : rowTime v r + 3 = + 1 + (((encodeWords r.2).length + 1) + (1 + (r.1 + min r.1 v + 3))) := by + simp only [rowTime, rowWords, encodeWords, List.length_append, encodeWord_length] + omega + rw [ht, Function.iterate_add_apply _ 1, + Function.iterate_add_apply _ ((encodeWords r.2).length + 1), + Function.iterate_add_apply _ 1] + simp only [rowWords, encodeWords, List.append_assoc] + rw [hcompare, Function.iterate_one, advance_some, hdispatch, hskip, + advance_some] + exact advanceStep original suffix (encodeWord v ++ targetSuffix) + (encodeWord rank ++ rankSuffix) outputSuffix position ambient + +def prefixTime (v : Nat) : List Row → Nat + | [] => 0 + | r :: rs => prefixTime v rs + (rowTime v r + 3) + +theorem prefixTrace (rs : List Row) (hwidth : ∀ r ∈ rs, r.2.length = 4097) + (v rank position : Nat) (original suffix targetSuffix rankSuffix outputSuffix : List Bool) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[prefixTime v rs] + (some (cfg (some (.inl .field)) .checking original + (encodeWords (rs.flatMap rowWords) ++ suffix) (encodeWord v ++ targetSuffix) [] + (encodeWord (rowsHits v rs + rank) ++ rankSuffix) + (encodeWord position ++ outputSuffix) ambient register)) = + some (cfg (some (.inl .field)) .checking original suffix + (encodeWord v ++ targetSuffix) [] (encodeWord rank ++ rankSuffix) + (encodeWord (position + rs.length) ++ outputSuffix) ambient + (if rs = [] then register else none)) := by + induction rs generalizing position register with + | nil => simp [prefixTime, rowsHits, encodeWords] + | cons r rs ih => + have hrow := rowSkipTrace r (hwidth r (by simp)) v (rowsHits v rs + rank) position + original (encodeWords (rs.flatMap rowWords) ++ suffix) targetSuffix rankSuffix + outputSuffix ambient register + have hrest := ih (by intro x hx; exact hwidth x (by simp [hx])) (position + 1) none + simp only [prefixTime, List.flatMap_cons, encodeWords_append, List.append_assoc] + rw [Function.iterate_add_apply] + have hi : (if r.1 = v then 1 else 0) + rowsHits v rs + rank = + (rowsHits v rs + rank) + (if r.1 = v then 1 else 0) := by omega + simp only [rowsHits, hi] + rw [hrow] + simpa only [ite_self, List.cons_ne_nil, ite_false, List.length_cons, + Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using hrest + +theorem cleanupTrace (original work target rank position : List Bool) (ambient : σ) : + (advance (TM2.step program))^[work.length + rank.length + 4] + (some (cfg (some (.inl .clearWork)) .finishing + original work target [] rank position ambient none)) = + some (cfg none .checking original [] target [] [] position ambient none) := by + have hwork := MachineDrain.drainTrace MachineCloudCount.Tape.work BaseLabel.clearWork (some BaseLabel.clearRank) + baseProgram rfl (MachineCloudCount.memory original work target [] [] rank) work + (ambient, false) none + simp only [MachineCloudCount.update_memory_work] at hwork + have hrank := MachineDrain.drainTrace MachineCloudCount.Tape.spare BaseLabel.clearRank (some BaseLabel.done) + baseProgram rfl (MachineCloudCount.memory original [] target [] [] rank) rank + (ambient, false) none + simp only [MachineCloudRank.update_memory_spare] at hrank + have raw : (advance (TM2.step baseProgram))^[work.length + rank.length + 3] + (some ⟨some .clearWork, ((ambient, false), none), + MachineCloudCount.memory original work target [] [] rank⟩) = + some ⟨none, ((ambient, false), none), + MachineCloudCount.memory original [] target [] [] []⟩ := by + rw [show work.length + rank.length + 3 = + 1 + ((rank.length + 1) + (work.length + 1)) by omega, + Function.iterate_add_apply _ 1, Function.iterate_add_apply _ (rank.length + 1), + hwork, hrank, Function.iterate_one, advance_some] + rfl + have lifted := liftTrace Phase.finishing position _ _ _ raw + have h : (advance (TM2.step program))^[work.length + rank.length + 3] + (some (cfg (some (.inl .clearWork)) .finishing + original work target [] rank position ambient none)) = + some (cfg (some (.inr .dispatch)) .finishing + original [] target [] [] position ambient none) := by + convert lifted using 1 <;> rfl + rw [show work.length + rank.length + 4 = (work.length + rank.length + 3) + 1 by omega, + Function.iterate_succ_apply', h, advance_some] + exact finishStep original target position ambient + +theorem selectedTrace (v : Nat) (original work targetSuffix rankSuffix position : List Bool) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[2 * v + work.length + rankSuffix.length + 8] + (some (cfg (some (.inl .field)) .checking original (encodeWord v ++ work) + (encodeWord v ++ targetSuffix) [] (encodeWord 0 ++ rankSuffix) position ambient register)) = + some (cfg none .checking original [] (encodeWord v ++ targetSuffix) [] [] position ambient none) := by + have hcompare := compareTrace original work targetSuffix (encodeWord 0 ++ rankSuffix) + position v v ambient register + simp only [ite_true, List.replicate_succ, List.replicate_zero] at hcompare + rw [show 2 * v + work.length + rankSuffix.length + 8 = + (work.length + rankSuffix.length + 4) + (1 + (v + min v v + 3)) by + simp only [Nat.min_self]; omega, + Function.iterate_add_apply _ (work.length + rankSuffix.length + 4), + Function.iterate_add_apply _ 1, hcompare, Function.iterate_one, advance_some, + dispatch_hit_zero] + exact cleanupTrace original work (encodeWord v ++ targetSuffix) rankSuffix position ambient + +abbrev queryWord := MachineCloudRank.queryWord + +def prepareSteps (n m v rank : Nat) (rs : List Row) (querySuffix : List Bool) : Nat := + 2 * ((queryWord v rank querySuffix).length + 1) + (v + 1) + + 2 * ((MachineCloudCount.inputWord n m rs).length + 1) + (n + 1) + (m + 1) + +theorem prepareTrace (n m v rank : Nat) (rs : List Row) + (querySuffix position : List Bool) (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[prepareSteps n m v rank rs querySuffix] + (some (cfg (some (.inl .queryFirst)) .checking (MachineCloudCount.inputWord n m rs) + [] (queryWord v rank querySuffix) [] [] position ambient register)) = + some (cfg (some (.inl .field)) .checking (MachineCloudCount.inputWord n m rs) + (encodeWords (rs.flatMap rowWords)) (queryWord v rank querySuffix) [] + (encodeWord rank ++ querySuffix) position ambient none) := by + have hquery := MachineCopy.copyTrace MachineCloudCount.Tape.target MachineCloudCount.Tape.spare MachineCloudCount.Tape.scratch + (by decide) (by decide) (by decide) false BaseLabel.queryFirst BaseLabel.querySecond + (some BaseLabel.querySkip) baseProgram rfl rfl + (MachineCloudCount.memory (MachineCloudCount.inputWord n m rs) [] + (queryWord v rank querySuffix) [] [] []) rfl (ambient, false) register + simp only [MachineCloudCount.memory_target, MachineCloudCount.memory_spare, + List.append_nil, MachineCloudRank.update_memory_spare] at hquery + have hquerySkip := MachineLookup.discardTrace MachineCloudCount.Tape.spare BaseLabel.querySkip BaseLabel.tableFirst + baseProgram rfl (MachineCloudCount.memory (MachineCloudCount.inputWord n m rs) [] + (queryWord v rank querySuffix) [] [] (queryWord v rank querySuffix)) + v (encodeWord rank ++ querySuffix) rfl (ambient, false) none + simp only [MachineCloudRank.update_memory_spare] at hquerySkip + have hcopy := MachineCopy.copyTrace MachineCloudCount.Tape.original MachineCloudCount.Tape.work MachineCloudCount.Tape.scratch + (by decide) (by decide) (by decide) false BaseLabel.tableFirst BaseLabel.tableSecond + (some BaseLabel.headerFirst) baseProgram rfl rfl + (MachineCloudCount.memory (MachineCloudCount.inputWord n m rs) [] + (queryWord v rank querySuffix) [] [] (encodeWord rank ++ querySuffix)) + rfl (ambient, false) none + simp only [MachineCloudCount.memory_original, MachineCloudCount.memory_work, + List.append_nil, MachineCloudCount.update_memory_work] at hcopy + have hfirst := MachineLookup.discardTrace MachineCloudCount.Tape.work BaseLabel.headerFirst BaseLabel.headerSecond + baseProgram rfl (MachineCloudCount.memory (MachineCloudCount.inputWord n m rs) + (MachineCloudCount.inputWord n m rs) (queryWord v rank querySuffix) [] [] + (encodeWord rank ++ querySuffix)) + n (encodeWord m ++ encodeWords (rs.flatMap rowWords)) + (MachineCloudCount.inputWord_eq n m rs) (ambient, false) none + simp only [MachineCloudCount.update_memory_work] at hfirst + have hsecond := MachineLookup.discardTrace MachineCloudCount.Tape.work BaseLabel.headerSecond BaseLabel.field + baseProgram rfl (MachineCloudCount.memory (MachineCloudCount.inputWord n m rs) + (encodeWord m ++ encodeWords (rs.flatMap rowWords)) (queryWord v rank querySuffix) + [] [] (encodeWord rank ++ querySuffix)) + m (encodeWords (rs.flatMap rowWords)) rfl (ambient, false) none + simp only [MachineCloudCount.update_memory_work] at hsecond + have raw : (advance (TM2.step baseProgram))^[prepareSteps n m v rank rs querySuffix] + (some ⟨some .queryFirst, ((ambient, false), register), + MachineCloudCount.memory (MachineCloudCount.inputWord n m rs) [] + (queryWord v rank querySuffix) [] [] []⟩) = + some ⟨some .field, ((ambient, false), none), + MachineCloudCount.memory (MachineCloudCount.inputWord n m rs) + (encodeWords (rs.flatMap rowWords)) (queryWord v rank querySuffix) [] [] + (encodeWord rank ++ querySuffix)⟩ := by + rw [show prepareSteps n m v rank rs querySuffix = + (m + 1) + ((n + 1) + (2 * ((MachineCloudCount.inputWord n m rs).length + 1) + + ((v + 1) + 2 * ((queryWord v rank querySuffix).length + 1)))) by + unfold prepareSteps; omega, + Function.iterate_add_apply _ (m + 1), Function.iterate_add_apply _ (n + 1), + Function.iterate_add_apply _ (2 * ((MachineCloudCount.inputWord n m rs).length + 1)), + Function.iterate_add_apply _ (v + 1), hquery, hquerySkip, hcopy, hfirst] + exact hsecond + convert liftTrace Phase.checking position _ _ _ raw using 1 <;> rfl + +theorem prefixSelectedTrace (preceding : List Row) + (hwidth : ∀ r ∈ preceding, r.2.length = 4097) (v position : Nat) + (original work targetSuffix rankSuffix outputSuffix : List Bool) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[prefixTime v preceding + 2 * v + work.length + rankSuffix.length + 8] + (some (cfg (some (.inl .field)) .checking original + (encodeWords (preceding.flatMap rowWords) ++ (encodeWord v ++ work)) + (encodeWord v ++ targetSuffix) [] (encodeWord (rowsHits v preceding) ++ rankSuffix) + (encodeWord position ++ outputSuffix) ambient register)) = + some (cfg none .checking original [] (encodeWord v ++ targetSuffix) [] [] + (encodeWord (position + preceding.length) ++ outputSuffix) ambient none) := by + have hp := prefixTrace preceding hwidth v 0 position original (encodeWord v ++ work) + targetSuffix rankSuffix outputSuffix ambient register + simp only [Nat.add_zero] at hp + have hs := selectedTrace v original work targetSuffix rankSuffix + (encodeWord (position + preceding.length) ++ outputSuffix) ambient + (if preceding = [] then register else none) + rw [show prefixTime v preceding + 2 * v + work.length + rankSuffix.length + 8 = + (2 * v + work.length + rankSuffix.length + 8) + prefixTime v preceding by omega, + Function.iterate_add_apply, hp] + exact hs + +def totalSteps (n m v rank : Nat) (rs preceding : List Row) + (work querySuffix : List Bool) : Nat := + prepareSteps n m v rank rs querySuffix + prefixTime v preceding + + 2 * v + work.length + querySuffix.length + 9 + +theorem fullTrace (n m v rank : Nat) (rs preceding : List Row) (work : List Bool) + (hwidth : ∀ r ∈ preceding, r.2.length = 4097) + (hword : encodeWords (rs.flatMap rowWords) = + encodeWords (preceding.flatMap rowWords) ++ (encodeWord v ++ work)) + (hrank : rank = rowsHits v preceding) (querySuffix outputSuffix : List Bool) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[totalSteps n m v rank rs preceding work querySuffix] + (some (cfg (some (.inr .initialize)) .checking (MachineCloudCount.inputWord n m rs) + [] (queryWord v rank querySuffix) [] [] outputSuffix ambient register)) = + some (cfg none .checking (MachineCloudCount.inputWord n m rs) [] + (queryWord v rank querySuffix) [] [] (encodeWord preceding.length ++ outputSuffix) ambient none) := by + have hp := prepareTrace n m v rank rs querySuffix (encodeWord 0 ++ outputSuffix) ambient none + have hs := prefixSelectedTrace preceding hwidth v 0 (MachineCloudCount.inputWord n m rs) work + (encodeWord rank ++ querySuffix) querySuffix outputSuffix ambient none + simp only [Nat.zero_add] at hs + rw [← hrank, ← hword] at hs + rw [show totalSteps n m v rank rs preceding work querySuffix = + (prefixTime v preceding + 2 * v + work.length + querySuffix.length + 8) + + (prepareSteps n m v rank rs querySuffix + 1) by unfold totalSteps; omega, + Function.iterate_add_apply _ (prefixTime v preceding + 2 * v + work.length + querySuffix.length + 8), + Function.iterate_succ_apply _ (prepareSteps n m v rank rs querySuffix), + advance_some, initializeStep, hp] + exact hs + +theorem prefixTime_le (v : Nat) (rs : List Row) : + prefixTime v rs ≤ 6 * (encodeWords (rs.flatMap rowWords)).length := by + induction rs with + | nil => simp [prefixTime, encodeWords] + | cons r rs ih => + have hr := MachineCloudCount.rowTime_le v r + have hpos : 1 ≤ (encodeWords (rowWords r)).length := by + simp only [rowWords, encodeWords, List.length_append, encodeWord_length] + omega + simp only [prefixTime, List.flatMap_cons, encodeWords_append, List.length_append] + omega + +theorem totalSteps_le (n m v rank : Nat) (rs preceding : List Row) (work querySuffix : List Bool) + (hword : encodeWords (rs.flatMap rowWords) = + encodeWords (preceding.flatMap rowWords) ++ (encodeWord v ++ work)) : + totalSteps n m v rank rs preceding work querySuffix ≤ + 10 * ((MachineCloudCount.inputWord n m rs).length + (queryWord v rank querySuffix).length) + 20 := by + have hp := prefixTime_le v preceding + have hw := congrArg List.length hword + simp only [List.length_append, encodeWord_length] at hw + have ht := MachineCloudCount.inputWord_length n m rs + have hq : (queryWord v rank querySuffix).length = + v + 1 + (rank + 1) + querySuffix.length := by + simp only [queryWord, MachineCloudRank.queryWord, List.length_append, encodeWord_length] + omega + unfold totalSteps prepareSteps + omega + +open MinUncutGames.Foundations.PCP + +def remainder (t : GraphTables.Table) (e : Fin t.darts) : List Bool := + encodeWords (t.rows[e].reverseIndex.val :: GraphTables.relationWords t.rows[e].relation) ++ + encodeWords (((tableRows t).drop (e.val + 1)).flatMap rowWords) + +theorem tableRows_getElem (t : GraphTables.Table) (e : Fin t.darts) : + (tableRows t)[e.val]'(by rw [MachineCloudRank.tableRows_length]; exact e.isLt) = + (t.rows[e].tail.val, t.rows[e].reverseIndex.val :: GraphTables.relationWords t.rows[e].relation) := by + simp only [MachineCloudCount.tableRows, MachineCloudCount.rowList_eq_finRange_map, + List.getElem_map, List.getElem_finRange] + apply congrArg (fun j : Fin t.darts => + (t.rows[j].tail.val, t.rows[j].reverseIndex.val :: GraphTables.relationWords t.rows[j].relation)) + apply Fin.ext + rfl + +theorem tableWord_split (t : GraphTables.Table) (v : Fin t.vertices) (e : Fin t.darts) + (owner : t.rows[e].tail = v) : + encodeWords ((tableRows t).flatMap rowWords) = + encodeWords (((tableRows t).take e.val).flatMap rowWords) ++ + (encodeWord v.val ++ remainder t e) := by + have he : e.val < (tableRows t).length := by + rw [MachineCloudRank.tableRows_length] + exact e.isLt + rw [MachineCloudRank.encoded_rows_split (tableRows t) e.val, List.drop_eq_getElem_cons he] + simp only [List.flatMap_cons, encodeWords_append] + rw [tableRows_getElem] + simp only [rowWords, encodeWords, owner, remainder, List.append_assoc] + +def cloudSelectSteps (t : GraphTables.Table) (v : Fin t.vertices) + (i : Fin (PreprocessingCloudIndex.cloudSize t v)) (querySuffix : List Bool) : Nat := + let e := (PreprocessingCloudIndex.cloudSelect t v i).val + totalSteps t.vertices t.darts v.val i.val (tableRows t) ((tableRows t).take e.val) + (remainder t e) querySuffix + +theorem cloudSelectTrace (t : GraphTables.Table) (v : Fin t.vertices) + (i : Fin (PreprocessingCloudIndex.cloudSize t v)) (querySuffix outputSuffix : List Bool) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[cloudSelectSteps t v i querySuffix] + (some (cfg (some (.inr .initialize)) .checking (GraphTables.tableBits t) + [] (queryWord v.val i.val querySuffix) [] [] outputSuffix ambient register)) = + some (cfg none .checking (GraphTables.tableBits t) [] (queryWord v.val i.val querySuffix) + [] [] (encodeWord (PreprocessingCloudIndex.cloudSelect t v i).val.val ++ outputSuffix) + ambient none) := by + let e := PreprocessingCloudIndex.cloudSelect t v i + have hword := tableWord_split t v e.val e.property + have hrank : i.val = rowsHits v.val ((tableRows t).take e.val.val) := by + simpa only [PreprocessingCloudIndex.cloudRank_cloudSelect] using + MachineCloudRank.cloudRank_eq_prefix_count t v (PreprocessingCloudIndex.cloudSelect t v i) + have h := fullTrace t.vertices t.darts v.val i.val (tableRows t) + ((tableRows t).take e.val.val) (remainder t e.val) + (by intro r hr; exact MachineCloudCount.tableRows_width t r (List.mem_of_mem_take hr)) + hword hrank querySuffix outputSuffix ambient register + have htake : ((tableRows t).take e.val.val).length = e.val.val := by + rw [List.length_take, MachineCloudRank.tableRows_length, + Nat.min_eq_left e.val.isLt.le] + rw [MachineCloudCount.tableRows_input, htake] at h + exact h + +theorem cloudSelectSteps_le (t : GraphTables.Table) (v : Fin t.vertices) + (i : Fin (PreprocessingCloudIndex.cloudSize t v)) (querySuffix : List Bool) : + cloudSelectSteps t v i querySuffix ≤ + 10 * ((GraphTables.tableBits t).length + (queryWord v.val i.val querySuffix).length) + 20 := by + let e := PreprocessingCloudIndex.cloudSelect t v i + have h := totalSteps_le t.vertices t.darts v.val i.val (tableRows t) + ((tableRows t).take e.val.val) (remainder t e.val) querySuffix + (tableWord_split t v e.val e.property) + simpa only [cloudSelectSteps, e, MachineCloudCount.tableRows_input] using h + +noncomputable def timePolynomial : Polynomial Nat := + Polynomial.C 10 * Polynomial.X + Polynomial.C 20 + +def cloudSelectInTime (t : GraphTables.Table) (v : Fin t.vertices) + (i : Fin (PreprocessingCloudIndex.cloudSize t v)) (querySuffix outputSuffix : List Bool) + (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + (cfg (some (.inr .initialize)) .checking (GraphTables.tableBits t) + [] (queryWord v.val i.val querySuffix) [] [] outputSuffix ambient register) + (some (cfg none .checking (GraphTables.tableBits t) [] (queryWord v.val i.val querySuffix) + [] [] (encodeWord (PreprocessingCloudIndex.cloudSelect t v i).val.val ++ outputSuffix) + ambient none)) + (timePolynomial.eval ((GraphTables.tableBits t).length + (queryWord v.val i.val querySuffix).length)) where + steps := cloudSelectSteps t v i querySuffix + evals_in_steps := cloudSelectTrace t v i querySuffix outputSuffix ambient register + steps_le_m := by + simpa only [timePolynomial, Polynomial.eval_add, Polynomial.eval_mul, + Polynomial.eval_C, Polynomial.eval_X] using cloudSelectSteps_le t v i querySuffix + +def machine : FinTM2 where + K := Tape + k₀ := .inl .original + k₁ := .inr () + Γ := Alphabet + Λ := Label + main := .inr .initialize + σ := State Unit + initialState := ((((), false), none), .checking) + m := program + +def machineInTime (t : GraphTables.Table) (v : Fin t.vertices) + (i : Fin (PreprocessingCloudIndex.cloudSize t v)) (querySuffix outputSuffix : List Bool) + (register : Option Bool) : + StateTransition.EvalsToInTime machine.step + (cfg (some (.inr .initialize)) .checking (GraphTables.tableBits t) + [] (queryWord v.val i.val querySuffix) [] [] outputSuffix () register) + (some (cfg none .checking (GraphTables.tableBits t) [] (queryWord v.val i.val querySuffix) + [] [] (encodeWord (PreprocessingCloudIndex.cloudSelect t v i).val.val ++ outputSuffix) + () none)) + (timePolynomial.eval ((GraphTables.tableBits t).length + (queryWord v.val i.val querySuffix).length)) where + steps := cloudSelectSteps t v i querySuffix + evals_in_steps := by + convert cloudSelectTrace t v i querySuffix outputSuffix () register using 1; rfl + steps_le_m := by + simpa only [timePolynomial, Polynomial.eval_add, Polynomial.eval_mul, + Polynomial.eval_C, Polynomial.eval_X] using cloudSelectSteps_le t v i querySuffix + +end MinUncutGames.Foundations.Complexity.MachineCloudSelect + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineCompare.lean b/lean/OAI/Computability/MinUncut/Machines/MachineCompare.lean new file mode 100644 index 0000000000000000000000000000000000000000..9d7528ff847c18111ad20598f800cab97104985f --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineCompare.lean @@ -0,0 +1,726 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineUnaryCounter + +namespace OAI + +namespace MinUncutGames.Foundations.Complexity.MachineCompare + +open Turing +open MinUncutGames.Reduction.MachineTransfer + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev Alphabet (K : Type) : K → Type := fun _ => Bool +abbrev State (σ : Type) := σ × Bool × Option Bool × Option Bool + +def exitAt (exit : Option Λ) : TM2.Stmt (Alphabet K) Λ (State σ) := + match exit with + | none => .halt + | some label => .goto fun _ => label + +def finish (exit : Option Λ) : TM2.Stmt (Alphabet K) Λ (State σ) := + .load (fun state => (state.1, false, none, none)) (exitAt exit) + +def loop (left right : K) (loopLabel : Λ) (equalExit differentExit : Option Λ) : + TM2.Stmt (Alphabet K) Λ (State σ) := + .pop left (fun state head => (state.1, state.2.1, head, state.2.2.2)) + (.pop right (fun state head => (state.1, state.2.1, state.2.2.1, head)) + (.branch (fun state => state.2.2.1.isNone && state.2.2.2.isNone) + (.branch (fun state => state.2.1) (finish differentExit) (finish equalExit)) + (.load (fun state => + (state.1, state.2.1 || decide (state.2.2.1 ≠ state.2.2.2), none, none)) + (.goto fun _ => loopLabel)))) + +def mismatch (flag : Bool) (leftWord rightWord : List Bool) : Bool := + flag || decide (leftWord ≠ rightWord) + +@[simp] theorem mismatch_nil_nil (flag : Bool) : mismatch flag [] [] = flag := by + simp [mismatch] + +@[simp] theorem mismatch_nil_cons (flag head : Bool) (tail : List Bool) : + mismatch flag [] (head :: tail) = true := by simp [mismatch] + +@[simp] theorem mismatch_cons_nil (flag head : Bool) (tail : List Bool) : + mismatch flag (head :: tail) [] = true := by simp [mismatch] + +@[simp] theorem mismatch_true (leftWord rightWord : List Bool) : + mismatch true leftWord rightWord = true := by simp [mismatch] + +theorem mismatch_cons (flag leftHead rightHead : Bool) (leftTail rightTail : List Bool) : + mismatch (flag || decide (leftHead ≠ rightHead)) leftTail rightTail = + mismatch flag (leftHead :: leftTail) (rightHead :: rightTail) := by + cases flag <;> cases leftHead <;> cases rightHead <;> simp [mismatch] + +@[simp] theorem stepAux_exitAt (exit : Option Λ) (state : State σ) + (tapes : K → List Bool) : + TM2.stepAux (exitAt exit) state tapes = ⟨exit, state, tapes⟩ := by + cases exit <;> rfl + +@[simp] theorem stepAux_finish (exit : Option Λ) (state : State σ) + (tapes : K → List Bool) : + TM2.stepAux (finish exit) state tapes = + ⟨exit, (state.1, false, none, none), tapes⟩ := by + simp [finish, TM2.stepAux] + +private theorem update_left (left right : K) (distinct : left ≠ right) + (base : K → List Bool) (leftWord rightWord replacement : List Bool) : + Function.update (tapesAt left right base leftWord rightWord) left replacement = + tapesAt left right base replacement rightWord := by + funext k + by_cases hl : k = left + · subst k + simp [tapesAt, distinct] + · by_cases hr : k = right + · subst k + simp [tapesAt, Ne.symm distinct] + · simp [tapesAt, hl, hr] + +private theorem update_right (left right : K) (base : K → List Bool) + (leftWord rightWord replacement : List Bool) : + Function.update (tapesAt left right base leftWord rightWord) right replacement = + tapesAt left right base leftWord replacement := by + simp [tapesAt] + +theorem step_empty (left right : K) (distinct : left ≠ right) + (loopLabel : Λ) (equalExit differentExit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet K) Λ (State σ)) + (atLoop : program loopLabel = loop left right loopLabel equalExit differentExit) + (base : K → List Bool) (ambient : σ) (flag : Bool) + (leftRegister rightRegister : Option Bool) : + TM2.step program + ⟨some loopLabel, (ambient, flag, leftRegister, rightRegister), + tapesAt left right base [] []⟩ = + some ⟨if flag then differentExit else equalExit, (ambient, false, none, none), + tapesAt left right base [] []⟩ := by + change some (TM2.stepAux (program loopLabel) (ambient, flag, leftRegister, rightRegister) + (tapesAt left right base [] [])) = _ + rw [atLoop] + cases flag <;> + simp [loop, TM2.stepAux, distinct, update_left, update_right] + +theorem step_nil_cons (left right : K) (distinct : left ≠ right) + (loopLabel : Λ) (equalExit differentExit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet K) Λ (State σ)) + (atLoop : program loopLabel = loop left right loopLabel equalExit differentExit) + (base : K → List Bool) (head : Bool) (tail : List Bool) (ambient : σ) (flag : Bool) + (leftRegister rightRegister : Option Bool) : + TM2.step program + ⟨some loopLabel, (ambient, flag, leftRegister, rightRegister), + tapesAt left right base [] (head :: tail)⟩ = + some ⟨some loopLabel, (ambient, true, none, none), tapesAt left right base [] tail⟩ := by + change some (TM2.stepAux (program loopLabel) (ambient, flag, leftRegister, rightRegister) + (tapesAt left right base [] (head :: tail))) = _ + rw [atLoop] + simp [loop, TM2.stepAux, distinct, update_left, update_right] + +theorem step_cons_nil (left right : K) (distinct : left ≠ right) + (loopLabel : Λ) (equalExit differentExit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet K) Λ (State σ)) + (atLoop : program loopLabel = loop left right loopLabel equalExit differentExit) + (base : K → List Bool) (head : Bool) (tail : List Bool) (ambient : σ) (flag : Bool) + (leftRegister rightRegister : Option Bool) : + TM2.step program + ⟨some loopLabel, (ambient, flag, leftRegister, rightRegister), + tapesAt left right base (head :: tail) []⟩ = + some ⟨some loopLabel, (ambient, true, none, none), tapesAt left right base tail []⟩ := by + change some (TM2.stepAux (program loopLabel) (ambient, flag, leftRegister, rightRegister) + (tapesAt left right base (head :: tail) [])) = _ + rw [atLoop] + simp [loop, TM2.stepAux, distinct, update_left, update_right] + +theorem step_cons_cons (left right : K) (distinct : left ≠ right) + (loopLabel : Λ) (equalExit differentExit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet K) Λ (State σ)) + (atLoop : program loopLabel = loop left right loopLabel equalExit differentExit) + (base : K → List Bool) (leftHead rightHead : Bool) (leftTail rightTail : List Bool) + (ambient : σ) (flag : Bool) (leftRegister rightRegister : Option Bool) : + TM2.step program + ⟨some loopLabel, (ambient, flag, leftRegister, rightRegister), + tapesAt left right base (leftHead :: leftTail) (rightHead :: rightTail)⟩ = + some ⟨some loopLabel, + (ambient, flag || decide (leftHead ≠ rightHead), none, none), + tapesAt left right base leftTail rightTail⟩ := by + change some (TM2.stepAux (program loopLabel) (ambient, flag, leftRegister, rightRegister) + (tapesAt left right base (leftHead :: leftTail) (rightHead :: rightTail))) = _ + rw [atLoop] + simp [loop, TM2.stepAux, distinct, update_left, update_right] + +private theorem trace_left_empty (left right : K) (distinct : left ≠ right) + (loopLabel : Λ) (equalExit differentExit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet K) Λ (State σ)) + (atLoop : program loopLabel = loop left right loopLabel equalExit differentExit) + (base : K → List Bool) (rightWord : List Bool) (ambient : σ) (flag : Bool) + (leftRegister rightRegister : Option Bool) : + (MachineComposition.advance (TM2.step program))^[rightWord.length + 1] + (some ⟨some loopLabel, (ambient, flag, leftRegister, rightRegister), + tapesAt left right base [] rightWord⟩) = + some ⟨if mismatch flag [] rightWord then differentExit else equalExit, + (ambient, false, none, none), tapesAt left right base [] []⟩ := by + induction rightWord generalizing flag leftRegister rightRegister with + | nil => + simpa only [List.length_nil, Nat.zero_add, Function.iterate_one, + MachineComposition.advance_some, mismatch_nil_nil] using + step_empty left right distinct loopLabel equalExit differentExit program atLoop base + ambient flag leftRegister rightRegister + | cons head tail ih => + rw [List.length_cons, Function.iterate_succ_apply] + change (MachineComposition.advance (TM2.step program))^[tail.length + 1] + (TM2.step program ⟨some loopLabel, (ambient, flag, leftRegister, rightRegister), + tapesAt left right base [] (head :: tail)⟩) = _ + rw [step_nil_cons left right distinct loopLabel equalExit differentExit program atLoop] + simpa only [mismatch_true, mismatch_nil_cons] using ih true none none + +theorem compareTrace_flag (left right : K) (distinct : left ≠ right) + (loopLabel : Λ) (equalExit differentExit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet K) Λ (State σ)) + (atLoop : program loopLabel = loop left right loopLabel equalExit differentExit) + (base : K → List Bool) (leftWord rightWord : List Bool) (ambient : σ) (flag : Bool) + (leftRegister rightRegister : Option Bool) : + (MachineComposition.advance (TM2.step program))^[max leftWord.length rightWord.length + 1] + (some ⟨some loopLabel, (ambient, flag, leftRegister, rightRegister), + tapesAt left right base leftWord rightWord⟩) = + some ⟨if mismatch flag leftWord rightWord then differentExit else equalExit, + (ambient, false, none, none), tapesAt left right base [] []⟩ := by + induction leftWord generalizing rightWord flag leftRegister rightRegister with + | nil => + simpa only [List.length_nil, Nat.zero_max] using + trace_left_empty left right distinct loopLabel equalExit differentExit program atLoop + base rightWord ambient flag leftRegister rightRegister + | cons head tail ih => + cases rightWord with + | nil => + rw [List.length_cons, List.length_nil, Nat.max_zero, Function.iterate_succ_apply] + change (MachineComposition.advance (TM2.step program))^[tail.length + 1] + (TM2.step program ⟨some loopLabel, (ambient, flag, leftRegister, rightRegister), + tapesAt left right base (head :: tail) []⟩) = _ + rw [step_cons_nil left right distinct loopLabel equalExit differentExit program atLoop] + simpa only [List.length_nil, Nat.max_zero, mismatch_true, mismatch_cons_nil] using + ih [] true none none + | cons rightHead rightTail => + rw [List.length_cons, List.length_cons, Nat.succ_max_succ, Function.iterate_succ_apply] + change (MachineComposition.advance (TM2.step program))^[max tail.length rightTail.length + 1] + (TM2.step program ⟨some loopLabel, (ambient, flag, leftRegister, rightRegister), + tapesAt left right base (head :: tail) (rightHead :: rightTail)⟩) = _ + rw [step_cons_cons left right distinct loopLabel equalExit differentExit program atLoop] + simpa only [mismatch_cons] using + ih rightTail (flag || decide (head ≠ rightHead)) none none + +theorem compareTrace (left right : K) (distinct : left ≠ right) + (loopLabel : Λ) (equalExit differentExit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet K) Λ (State σ)) + (atLoop : program loopLabel = loop left right loopLabel equalExit differentExit) + (base : K → List Bool) (leftWord rightWord : List Bool) (ambient : σ) + (leftRegister rightRegister : Option Bool) : + (MachineComposition.advance (TM2.step program))^[max leftWord.length rightWord.length + 1] + (some ⟨some loopLabel, (ambient, false, leftRegister, rightRegister), + tapesAt left right base leftWord rightWord⟩) = + some ⟨if leftWord = rightWord then equalExit else differentExit, + (ambient, false, none, none), tapesAt left right base [] []⟩ := by + have h := compareTrace_flag left right distinct loopLabel equalExit differentExit program + atLoop base leftWord rightWord ambient false leftRegister rightRegister + by_cases heq : leftWord = rightWord <;> simpa [mismatch, heq] using h + +theorem compareTrace_fromTapes (left right : K) (distinct : left ≠ right) + (loopLabel : Λ) (equalExit differentExit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet K) Λ (State σ)) + (atLoop : program loopLabel = loop left right loopLabel equalExit differentExit) + (base : K → List Bool) (ambient : σ) (leftRegister rightRegister : Option Bool) : + (MachineComposition.advance (TM2.step program))^[max (base left).length (base right).length + 1] + (some ⟨some loopLabel, (ambient, false, leftRegister, rightRegister), base⟩) = + some ⟨if base left = base right then equalExit else differentExit, + (ambient, false, none, none), tapesAt left right base [] []⟩ := by + simpa only [tapesAt_self] using + compareTrace left right distinct loopLabel equalExit differentExit program atLoop base + (base left) (base right) ambient leftRegister rightRegister + +theorem drained_other (left right k : K) (notLeft : k ≠ left) (notRight : k ≠ right) + (base : K → List Bool) : tapesAt left right base [] [] k = base k := + tapesAt_other left right k notLeft notRight base [] [] + +def compareInTime (left right : K) (distinct : left ≠ right) + (loopLabel : Λ) (equalExit differentExit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet K) Λ (State σ)) + (atLoop : program loopLabel = loop left right loopLabel equalExit differentExit) + (base : K → List Bool) (ambient : σ) (leftRegister rightRegister : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some loopLabel, (ambient, false, leftRegister, rightRegister), base⟩ + (some ⟨if base left = base right then equalExit else differentExit, + (ambient, false, none, none), tapesAt left right base [] []⟩) + (max (base left).length (base right).length + 1) where + steps := max (base left).length (base right).length + 1 + evals_in_steps := compareTrace_fromTapes left right distinct loopLabel equalExit differentExit + program atLoop base ambient leftRegister rightRegister + steps_le_m := Nat.le_refl _ + +@[simp] theorem compareInTime_steps (left right : K) (distinct : left ≠ right) + (loopLabel : Λ) (equalExit differentExit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet K) Λ (State σ)) + (atLoop : program loopLabel = loop left right loopLabel equalExit differentExit) + (base : K → List Bool) (ambient : σ) (leftRegister rightRegister : Option Bool) : + (compareInTime left right distinct loopLabel equalExit differentExit program atLoop base + ambient leftRegister rightRegister).steps = + max (base left).length (base right).length + 1 := rfl + +end MinUncutGames.Foundations.Complexity.MachineCompare + +namespace MinUncutGames.Foundations.Complexity.MachineControl + +open Turing.TM2 + +variable {K Λ Λ' σ σ' : Type} {Γ : K → Type} + +def configuration (labels : Λ → Λ') (states : σ ≃ σ') (c : Cfg Γ Λ σ) : + Cfg Γ Λ' σ' where + l := c.l.map labels + var := states c.var + stk := c.stk + +def statement (labels : Λ → Λ') (states : σ ≃ σ') : Stmt Γ Λ σ → Stmt Γ Λ' σ' + | .push k f next => .push k (fun st => f (states.symm st)) (statement labels states next) + | .peek k f next => .peek k (fun st v => states (f (states.symm st) v)) + (statement labels states next) + | .pop k f next => .pop k (fun st v => states (f (states.symm st) v)) + (statement labels states next) + | .load f next => .load (fun st => states (f (states.symm st))) + (statement labels states next) + | .branch f yes no => .branch (fun st => f (states.symm st)) + (statement labels states yes) (statement labels states no) + | .goto f => .goto (fun st => labels (f (states.symm st))) + | .halt => .halt + +variable [DecidableEq K] + +theorem stepAux_simulation (labels : Λ → Λ') (states : σ ≃ σ') + (q : Stmt Γ Λ σ) (state : σ) (tapes : ∀ k, List (Γ k)) : + stepAux (statement labels states q) (states state) tapes = + configuration labels states (stepAux q state tapes) := by + induction q generalizing state tapes with + | push k f next ih => + simpa only [statement, stepAux, Equiv.symm_apply_apply] using + ih state (Function.update tapes k (f state :: tapes k)) + | peek k f next ih => + simpa only [statement, stepAux, Equiv.symm_apply_apply] using + ih (f state (tapes k).head?) tapes + | pop k f next ih => + simpa only [statement, stepAux, Equiv.symm_apply_apply] using + ih (f state (tapes k).head?) (Function.update tapes k (tapes k).tail) + | load f next ih => + simpa only [statement, stepAux, Equiv.symm_apply_apply] using ih (f state) tapes + | branch f yes no ihYes ihNo => + cases h : f state with + | false => + simpa only [statement, stepAux, Equiv.symm_apply_apply, h, Bool.cond_false] using + ihNo state tapes + | true => + simpa only [statement, stepAux, Equiv.symm_apply_apply, h, Bool.cond_true] using + ihYes state tapes + | goto f => simp [statement, stepAux, configuration] + | halt => rfl + +def program (labels : Λ ≃ Λ') (states : σ ≃ σ') (source : Λ → Stmt Γ Λ σ) : + Λ' → Stmt Γ Λ' σ' := fun l => statement labels states (source (labels.symm l)) + +theorem step_simulation (labels : Λ ≃ Λ') (states : σ ≃ σ') + (source : Λ → Stmt Γ Λ σ) (c : Cfg Γ Λ σ) : + step (program labels states source) (configuration labels states c) = + (step source c).map (configuration labels states) := by + cases c with + | mk l state tapes => + cases l with + | none => rfl + | some l => + change some (stepAux (statement labels states (source (labels.symm (labels l)))) + (states state) tapes) = _ + rw [Equiv.symm_apply_apply, stepAux_simulation] + rfl + +end MinUncutGames.Foundations.Complexity.MachineControl + +namespace MinUncutGames.Foundations.Complexity.MachineFieldProfile + +open Turing + +abbrev Profile (q : Nat) := Fin q → Fin q → Bool + +def equalityProfile {q : Nat} (words : Fin q → List Bool) : Profile q := + fun i j => decide (words i = words j) + +theorem equalityProfile_encodeWord {q : Nat} (names : Fin q → Nat) (i j : Fin q) : + equalityProfile (fun k => encodeWord (names k)) i j = decide (names i = names j) := by + have h : encodeWord (names i) = encodeWord (names j) ↔ names i = names j := by + constructor + · intro heq + have hh := congrArg List.length heq + simpa only [encodeWord_length, Nat.add_right_cancel_iff] using hh + · rintro heq + rw [heq] + simp only [equalityProfile, h] + +section Transport +variable {K Λ σ τ : Type} [DecidableEq K] + +omit [DecidableEq K] in +theorem statement_roundtrip (e : σ ≃ τ) + (q : TM2.Stmt (fun _ : K => Bool) Λ τ) : + MachineControl.statement id e (MachineControl.statement id e.symm q) = q := by + induction q <;> simp_all [MachineControl.statement] + +def copyStateEquiv (σ : Type) : + ((σ × Bool × Option Bool) × Option Bool) ≃ MachineCompare.State σ where + toFun s := (s.1.1, s.1.2.1, s.1.2.2, s.2) + invFun s := ((s.1, s.2.1, s.2.2.1), s.2.2.2) + left_inv _ := rfl + right_inv _ := rfl + +def normalState (ambient : σ) : MachineCompare.State σ := (ambient, false, none, none) + +def copyStatement (q : TM2.Stmt (fun _ : K => Bool) Λ + ((σ × Bool × Option Bool) × Option Bool)) : + TM2.Stmt (fun _ : K => Bool) Λ (MachineCompare.State σ) := + MachineControl.statement id (copyStateEquiv σ) q + +def copyInCompareState (source destination scratch : K) + (hSD : source ≠ destination) (hST : source ≠ scratch) (hDT : destination ≠ scratch) + (firstLabel secondLabel : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (MachineCompare.State σ)) + (atFirst : program firstLabel = copyStatement + (Reduction.MachineTransfer.loopAt source scratch id false firstLabel (some secondLabel))) + (atSecond : program secondLabel = copyStatement + (MachineCopy.forkLoop scratch source destination false secondLabel exit)) + (base : K → List Bool) (hScratch : base scratch = []) (ambient : σ) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some firstLabel, normalState ambient, base⟩ + (some ⟨exit, normalState ambient, + Function.update base destination (base source ++ base destination)⟩) + (2 * ((base source).length + 1)) := by + let e := copyStateEquiv σ + let view := MachineControl.program (Equiv.refl Λ) e.symm program + have hfirst : view firstLabel = + Reduction.MachineTransfer.loopAt source scratch id false firstLabel (some secondLabel) := by + dsimp [view, MachineControl.program] + rw [atFirst] + exact statement_roundtrip e.symm _ + have hsecond : view secondLabel = + MachineCopy.forkLoop scratch source destination false secondLabel exit := by + dsimp [view, MachineControl.program] + rw [atSecond] + exact statement_roundtrip e.symm _ + let run := MachineCopy.copyInTime source destination scratch hSD hST hDT false + firstLabel secondLabel exit view hfirst hsecond base hScratch (ambient, false, none) none + have hprogram : MachineControl.program (Equiv.refl Λ) e view = program := by + funext label + exact statement_roundtrip e (program label) + have hsim (a b : TM2.Cfg (fun _ : K => Bool) Λ ((σ × Bool × Option Bool) × Option Bool)) + (hab : TM2.step view a = some b) : + TM2.step program (MachineControl.configuration id e a) = + some (MachineControl.configuration id e b) := by + have hh := MachineControl.step_simulation (Equiv.refl Λ) e view a + rw [hprogram, hab] at hh + exact hh + have lifted := MachineComposition.liftExecutionInTime (TM2.step view) (TM2.step program) + (MachineControl.configuration id e) hsim run + simpa [MachineControl.configuration, copyStateEquiv, normalState, e] using lifted + +end Transport + +section PreservedComparison +variable {K Λ σ : Type} [DecidableEq K] + +def nonDestructiveCompareInTime (left right workLeft workRight scratch : K) + (hleft : left ≠ workLeft ∧ left ≠ workRight ∧ left ≠ scratch) + (hright : right ≠ workLeft ∧ right ≠ workRight ∧ right ≠ scratch) + (hwork : workLeft ≠ workRight ∧ workLeft ≠ scratch ∧ workRight ≠ scratch) + (leftFirst leftSecond rightFirst rightSecond compareLabel : Λ) + (equalExit differentExit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (MachineCompare.State σ)) + (atLeftFirst : program leftFirst = copyStatement + (Reduction.MachineTransfer.loopAt left scratch id false leftFirst (some leftSecond))) + (atLeftSecond : program leftSecond = copyStatement + (MachineCopy.forkLoop scratch left workLeft false leftSecond (some rightFirst))) + (atRightFirst : program rightFirst = copyStatement + (Reduction.MachineTransfer.loopAt right scratch id false rightFirst (some rightSecond))) + (atRightSecond : program rightSecond = copyStatement + (MachineCopy.forkLoop scratch right workRight false rightSecond (some compareLabel))) + (atCompare : program compareLabel = + MachineCompare.loop workLeft workRight compareLabel equalExit differentExit) + (base : K → List Bool) (hWL : base workLeft = []) (hWR : base workRight = []) + (hScratch : base scratch = []) (ambient : σ) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some leftFirst, normalState ambient, base⟩ + (some ⟨if base left = base right then equalExit else differentExit, + normalState ambient, base⟩) + (2 * ((base left).length + 1) + 2 * ((base right).length + 1) + + max (base left).length (base right).length + 1) := by + let t₁ := Function.update base workLeft (base left) + let t₂ := Function.update t₁ workRight (base right) + have h₁ := copyInCompareState left workLeft scratch hleft.1 hleft.2.2 hwork.2.1 + leftFirst leftSecond (some rightFirst) program atLeftFirst atLeftSecond base hScratch ambient + simp only [hWL, List.append_nil] at h₁ + have hSR : t₁ right = base right := by simp [t₁, hright.1] + have hDR : t₁ workRight = [] := by simp [t₁, Ne.symm hwork.1, hWR] + have hTR : t₁ scratch = [] := by simp [t₁, Ne.symm hwork.2.1, hScratch] + have h₂ := copyInCompareState right workRight scratch hright.2.1 hright.2.2 hwork.2.2 + rightFirst rightSecond (some compareLabel) program atRightFirst atRightSecond t₁ hTR ambient + rw [hSR, hDR] at h₂ + simp only [List.append_nil] at h₂ + have hL : t₂ workLeft = base left := by simp [t₂, t₁, hwork.1] + have hR : t₂ workRight = base right := by simp [t₂] + have hrestore : Reduction.MachineTransfer.tapesAt workLeft workRight t₂ [] [] = base := by + funext p + by_cases hl : p = workLeft + · subst p + simp [Reduction.MachineTransfer.tapesAt, hwork.1, hWL] + · by_cases hr : p = workRight + · subst p + simp [Reduction.MachineTransfer.tapesAt, hWR] + · simp [Reduction.MachineTransfer.tapesAt, t₂, t₁, hl, hr] + have h₃ := MachineCompare.compareInTime workLeft workRight hwork.1 compareLabel + equalExit differentExit program atCompare t₂ ambient none none + rw [hL, hR, hrestore] at h₃ + let h₁₂ := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ h₁ h₂ + let run := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ h₁₂ h₃ + exact { toEvalsTo := run.toEvalsTo, steps_le_m := by have h := run.steps_le_m; omega } + +end PreservedComparison + +def setEntry {q : Nat} (profile : Profile q) (pair : Fin q × Fin q) (bit : Bool) : Profile q := + Function.update profile pair.1 (Function.update (profile pair.1) pair.2 bit) + +theorem setEntry_apply {q : Nat} (profile : Profile q) (pair : Fin q × Fin q) + (bit : Bool) (i j : Fin q) : + setEntry profile pair bit i j = if (i, j) = pair then bit else profile i j := by + rcases pair with ⟨a, b⟩ + by_cases hi : i = a <;> by_cases hj : j = b <;> simp [setEntry, hi, hj] + +def setExpected {q : Nat} (words : Fin q → List Bool) (profile : Profile q) + (pair : Fin q × Fin q) : Profile q := + setEntry profile pair (equalityProfile words pair.1 pair.2) + +def foldProfile {q : Nat} (words : Fin q → List Bool) (initial : Profile q) + (cells : List (Fin q × Fin q)) : Profile q := cells.foldl (setExpected words) initial + +theorem foldProfile_apply {q : Nat} (words : Fin q → List Bool) (initial : Profile q) + (cells : List (Fin q × Fin q)) (i j : Fin q) : + foldProfile words initial cells i j = + if (i, j) ∈ cells then equalityProfile words i j else initial i j := by + induction cells generalizing initial with + | nil => rfl + | cons pair rest ih => + change foldProfile words (setExpected words initial pair) rest i j = _ + rw [ih] + by_cases hrest : (i, j) ∈ rest + · simp [hrest] + · by_cases hpair : (i, j) = pair + · subst pair + simp [hrest, setExpected, setEntry_apply] + · simp [hrest, hpair, setExpected, setEntry_apply] + +abbrev Tape (q : Nat) := Fin q ⊕ Fin 3 +abbrev Label {q : Nat} (cells : List (Fin q × Fin q)) := Fin (cells.length + 1) × Fin 7 + +def labelAt {q : Nat} (cells : List (Fin q × Fin q)) (r : Nat) (phase : Fin 7) : Label cells := + (⟨min r cells.length, by omega⟩, phase) + +def storePair {q : Nat} (pair : Fin q × Fin q) (bit : Bool) + {Λ : Type} (nextLabel : Λ) : + TM2.Stmt (fun _ : Tape q => Bool) Λ (MachineCompare.State (Profile q)) := + .load (fun state => normalState (setEntry state.1 pair bit)) (.goto fun _ => nextLabel) + +def profileProgram {q : Nat} (cells : List (Fin q × Fin q)) (label : Label cells) : + TM2.Stmt (fun _ : Tape q => Bool) (Label cells) (MachineCompare.State (Profile q)) := + if h : label.1.val < cells.length then + let pair := cells[label.1.val] + let r := label.1.val + match label.2.val with + | 0 => copyStatement (Reduction.MachineTransfer.loopAt (.inl pair.1) (.inr 2) id false + (labelAt cells r 0) (some (labelAt cells r 1))) + | 1 => copyStatement (MachineCopy.forkLoop (.inr 2) (.inl pair.1) (.inr 0) false + (labelAt cells r 1) (some (labelAt cells r 2))) + | 2 => copyStatement (Reduction.MachineTransfer.loopAt (.inl pair.2) (.inr 2) id false + (labelAt cells r 2) (some (labelAt cells r 3))) + | 3 => copyStatement (MachineCopy.forkLoop (.inr 2) (.inl pair.2) (.inr 1) false + (labelAt cells r 3) (some (labelAt cells r 4))) + | 4 => MachineCompare.loop (.inr 0) (.inr 1) (labelAt cells r 4) + (some (labelAt cells r 5)) (some (labelAt cells r 6)) + | 5 => storePair pair true (labelAt cells (r + 1) 0) + | _ => storePair pair false (labelAt cells (r + 1) 0) + else .halt + +def pairTime {q : Nat} (words : Fin q → List Bool) (pair : Fin q × Fin q) : Nat := + 2 * ((words pair.1).length + 1) + 2 * ((words pair.2).length + 1) + + max (words pair.1).length (words pair.2).length + 2 + +def prefixProfile {q : Nat} (words : Fin q → List Bool) (initial : Profile q) + (cells : List (Fin q × Fin q)) (r : Nat) : Profile q := + foldProfile words initial (cells.take r) + +def prefixTime {q : Nat} (words : Fin q → List Bool) + (cells : List (Fin q × Fin q)) (r : Nat) : Nat := + ((cells.take r).map (pairTime words)).sum + +theorem prefixProfile_succ {q : Nat} (words : Fin q → List Bool) (initial : Profile q) + (cells : List (Fin q × Fin q)) (r : Nat) (hr : r < cells.length) : + prefixProfile words initial cells (r + 1) = + setExpected words (prefixProfile words initial cells r) cells[r] := by + unfold prefixProfile foldProfile + rw [List.take_succ_eq_append_getElem hr, List.foldl_append] + rfl + +theorem prefixTime_succ {q : Nat} (words : Fin q → List Bool) + (cells : List (Fin q × Fin q)) (r : Nat) (hr : r < cells.length) : + prefixTime words cells (r + 1) = prefixTime words cells r + pairTime words cells[r] := by + unfold prefixTime + rw [List.take_succ_eq_append_getElem hr, List.map_append, List.sum_append] + rfl + +def stageInTime {q : Nat} (cells : List (Fin q × Fin q)) (r : Nat) (hr : r < cells.length) + (base : Tape q → List Bool) (hwork : ∀ w : Fin 3, base (.inr w) = []) (profile : Profile q) : + StateTransition.EvalsToInTime (TM2.step (profileProgram cells)) + ⟨some (labelAt cells r 0), normalState profile, base⟩ + (some ⟨some (labelAt cells (r + 1) 0), + normalState (setExpected (fun i => base (.inl i)) profile cells[r]), base⟩) + (pairTime (fun i => base (.inl i)) cells[r]) := by + let pair := cells[r] + have copied := nonDestructiveCompareInTime (.inl pair.1) (.inl pair.2) + (.inr 0 : Tape q) (.inr 1) (.inr 2) (by simp) (by simp) (by simp) + (labelAt cells r 0) (labelAt cells r 1) (labelAt cells r 2) (labelAt cells r 3) + (labelAt cells r 4) (some (labelAt cells r 5)) (some (labelAt cells r 6)) + (profileProgram cells) + (by simp [profileProgram, labelAt, Nat.min_eq_left hr.le, hr, pair]) + (by simp [profileProgram, labelAt, Nat.min_eq_left hr.le, hr, pair]) + (by simp [profileProgram, labelAt, Nat.min_eq_left hr.le, hr, pair]) + (by simp [profileProgram, labelAt, Nat.min_eq_left hr.le, hr, pair]) + (by simp [profileProgram, labelAt, Nat.min_eq_left hr.le, hr]) + base (hwork 0) (hwork 1) (hwork 2) profile + have stored : StateTransition.EvalsToInTime (TM2.step (profileProgram cells)) + ⟨if base (.inl pair.1) = base (.inl pair.2) then some (labelAt cells r 5) + else some (labelAt cells r 6), normalState profile, base⟩ + (some ⟨some (labelAt cells (r + 1) 0), + normalState (setExpected (fun i => base (.inl i)) profile pair), base⟩) 1 := { + steps := 1 + evals_in_steps := by + change TM2.step (profileProgram cells) + ⟨if base (.inl pair.1) = base (.inl pair.2) then some (labelAt cells r 5) + else some (labelAt cells r 6), normalState profile, base⟩ = _ + by_cases heq : base (.inl pair.1) = base (.inl pair.2) + · simp [heq, TM2.step, profileProgram, labelAt, + Nat.min_eq_left hr.le, hr, storePair, TM2.stepAux, normalState, + setExpected, equalityProfile, pair] + · simp [heq, TM2.step, profileProgram, labelAt, + Nat.min_eq_left hr.le, hr, storePair, TM2.stepAux, normalState, + setExpected, equalityProfile, pair] + steps_le_m := Nat.le_refl _ + } + let run := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ copied stored + refine { toEvalsTo := run.toEvalsTo, steps_le_m := ?_ } + have h := run.steps_le_m + dsimp only [pair] at h + dsimp only [pairTime] + omega + +def prefixInTime {q : Nat} (cells : List (Fin q × Fin q)) + (base : Tape q → List Bool) (hwork : ∀ w : Fin 3, base (.inr w) = []) (initial : Profile q) + (r : Nat) (hr : r ≤ cells.length) : + StateTransition.EvalsToInTime (TM2.step (profileProgram cells)) + ⟨some (labelAt cells 0 0), normalState initial, base⟩ + (some ⟨some (labelAt cells r 0), + normalState (prefixProfile (fun i => base (.inl i)) initial cells r), base⟩) + (prefixTime (fun i => base (.inl i)) cells r) := by + induction r with + | zero => + exact { steps := 0, evals_in_steps := rfl, steps_le_m := Nat.le_refl _ } + | succ r ih => + have hrl : r < cells.length := by omega + let first := ih (by omega) + let second := stageInTime cells r hrl base hwork + (prefixProfile (fun i => base (.inl i)) initial cells r) + let run := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ first second + rw [prefixProfile_succ _ _ _ _ hrl, prefixTime_succ _ _ _ hrl] + exact { toEvalsTo := run.toEvalsTo, steps_le_m := by have h := run.steps_le_m; omega } + +def allPairs (q : Nat) : List (Fin q × Fin q) := + (List.finRange q).flatMap fun i => (List.finRange q).map fun j => (i, j) + +theorem mem_allPairs {q : Nat} (i j : Fin q) : (i, j) ∈ allPairs q := by + simp [allPairs] + +theorem length_allPairs (q : Nat) : (allPairs q).length = q * q := by + simp [allPairs, List.length_flatMap] + +theorem foldProfile_allPairs {q : Nat} (words : Fin q → List Bool) (initial : Profile q) : + foldProfile words initial (allPairs q) = equalityProfile words := by + funext i j + simp [foldProfile_apply, mem_allPairs] + +def profileMachine (q : Nat) : FinTM2 where + K := Tape q + k₀ := .inr 0 + k₁ := .inr 0 + Γ _ := Bool + Λ := Label (allPairs q) + main := labelAt (allPairs q) 0 0 + σ := MachineCompare.State (Profile q) + initialState := normalState (fun _ _ => false) + m := profileProgram (allPairs q) + +def profileInTime (q : Nat) (base : Tape q → List Bool) + (hwork : ∀ w : Fin 3, base (.inr w) = []) (initial : Profile q) : + StateTransition.EvalsToInTime (profileMachine q).step + ⟨some (labelAt (allPairs q) 0 0), normalState initial, base⟩ + (some ⟨none, normalState (equalityProfile (fun i => base (.inl i))), base⟩) + (((allPairs q).map (pairTime (fun i => base (.inl i)))).sum + 1) := by + let cells := allPairs q + have first := prefixInTime cells base hwork initial cells.length (Nat.le_refl _) + have last : StateTransition.EvalsToInTime (TM2.step (profileProgram cells)) + ⟨some (labelAt cells cells.length 0), + normalState (prefixProfile (fun i => base (.inl i)) initial cells cells.length), base⟩ + (some ⟨none, normalState (equalityProfile (fun i => base (.inl i))), base⟩) 1 := { + steps := 1 + evals_in_steps := by + change TM2.step (profileProgram cells) + ⟨some (labelAt cells cells.length 0), + normalState (prefixProfile (fun i => base (.inl i)) initial cells cells.length), base⟩ = _ + simp [TM2.step, profileProgram, labelAt, TM2.stepAux, + prefixProfile, cells, foldProfile_allPairs] + steps_le_m := Nat.le_refl _ + } + let run := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ first last + refine { toEvalsTo := run.toEvalsTo, steps_le_m := ?_ } + have h := run.steps_le_m + simpa [prefixTime, cells, Nat.add_comm] using h + +theorem pairTime_le {q : Nat} (words : Fin q → List Bool) (L : Nat) + (hL : ∀ i, (words i).length ≤ L) (pair : Fin q × Fin q) : + pairTime words pair ≤ 5 * L + 6 := by + have hi := hL pair.1 + have hj := hL pair.2 + have hm := max_le hi hj + dsimp only [pairTime] + omega + +theorem totalTime_le {q : Nat} (words : Fin q → List Bool) (L : Nat) + (hL : ∀ i, (words i).length ≤ L) (cells : List (Fin q × Fin q)) : + (cells.map (pairTime words)).sum ≤ cells.length * (5 * L + 6) := by + induction cells with + | nil => simp + | cons pair rest ih => + have hp := pairTime_le words L hL pair + simp only [List.map_cons, List.sum_cons, List.length_cons, Nat.add_mul, Nat.one_mul] + omega + +def profileInTime_bounded (q : Nat) (base : Tape q → List Bool) + (hwork : ∀ w : Fin 3, base (.inr w) = []) (initial : Profile q) + (L : Nat) (hL : ∀ i, (base (.inl i)).length ≤ L) : + StateTransition.EvalsToInTime (profileMachine q).step + ⟨some (labelAt (allPairs q) 0 0), normalState initial, base⟩ + (some ⟨none, normalState (equalityProfile (fun i => base (.inl i))), base⟩) + (q * q * (5 * L + 6) + 1) := by + let run := profileInTime q base hwork initial + refine { toEvalsTo := run.toEvalsTo, steps_le_m := ?_ } + apply run.steps_le_m.trans + apply Nat.add_le_add_right + simpa only [length_allPairs] using totalTime_le (fun i => base (.inl i)) L hL (allPairs q) + +end MinUncutGames.Foundations.Complexity.MachineFieldProfile + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineDrain.lean b/lean/OAI/Computability/MinUncut/Machines/MachineDrain.lean new file mode 100644 index 0000000000000000000000000000000000000000..82ffbafe04c69595b6ea4d44707c72e93ebca79c --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineDrain.lean @@ -0,0 +1,63 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.Runtime + +namespace OAI + +section +namespace MinUncutGames.Foundations.Complexity.MachineDrain + +open Turing + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool + +def drain (source : K) (again : Λ) (exit : Option Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) := + .pop source (fun state head => (state.1, head)) + (.branch (fun state => state.2.isSome) + (.goto fun _ => again) + (.load (fun state => (state.1, none)) (Reduction.MachineTransfer.exitAt source exit))) + +theorem drainTrace (source : K) (again : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atDrain : program again = drain source again exit) + (base : K → List Bool) (word : List Bool) (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[word.length + 1] + (some ⟨some again, (ambient, register), Function.update base source word⟩) = + some ⟨exit, (ambient, none), Function.update base source []⟩ := by + induction word generalizing register with + | nil => + change some (TM2.stepAux (program again) (ambient, register) + (Function.update base source [])) = _ + rw [atDrain] + cases exit <;> simp [drain, TM2.stepAux, Reduction.MachineTransfer.exitAt] + | cons symbol word ih => + rw [List.length_cons, Function.iterate_succ_apply] + change (MachineComposition.advance (TM2.step program))^[word.length + 1] + (some (TM2.stepAux (program again) (ambient, register) + (Function.update base source (symbol :: word)))) = _ + rw [atDrain] + simpa [drain, TM2.stepAux] using ih (some symbol) + +def drainInTime (source : K) (again : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atDrain : program again = drain source again exit) + (base : K → List Bool) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some again, (ambient, register), base⟩ + (some ⟨exit, (ambient, none), Function.update base source []⟩) + ((base source).length + 1) where + steps := (base source).length + 1 + evals_in_steps := by + change (MachineComposition.advance (TM2.step program))^[(base source).length + 1] + (some ⟨some again, (ambient, register), base⟩) = _ + simpa only [Function.update_eq_self] using + drainTrace source again exit program atDrain base (base source) ambient register + steps_le_m := Nat.le_refl _ + +end MinUncutGames.Foundations.Complexity.MachineDrain + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineDummyRows.lean b/lean/OAI/Computability/MinUncut/Machines/MachineDummyRows.lean new file mode 100644 index 0000000000000000000000000000000000000000..ff0b0b3ee35e49c86e0af29c797352ac6852f4f0 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineDummyRows.lean @@ -0,0 +1,697 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineRegularLift + +namespace OAI + +section +namespace MinUncutGames.Foundations.Complexity.MachineDummyRows + +open Turing +open PCP.GraphTables +open Reduction.MachineSubstitution (pushWord stepAux_pushWord) + +def trueRelation : RelationTable := Vector.replicate 4096 true + +def trueBits : List Bool := encodeWords (relationWords trueRelation) + +theorem trueBits_length : trueBits.length = 8192 := by + simp only [trueBits, encodeWords_length, relationWords, trueRelation, + Vector.toList_replicate, List.map_replicate, List.sum_replicate_nat, + List.length_replicate] + rfl + +def rowBits (v e : Nat) : List Bool := encodeWord v ++ encodeWord e ++ trueBits + +theorem rowBits_length (v e : Nat) : (rowBits v e).length = v + e + 8194 := by + simp [rowBits, trueBits_length, encodeWord_length] + omega + +theorem rowBits_eq_graph_row {n m : Nat} (v : Fin n) (e : Fin m) : + rowBits v.val e.val = encodeWords (rowWords (⟨v, e, trueRelation⟩ : DartRow n m)) := by + rw [MachineTableRows.rowBits_eq] + rfl + +def rowsBits (v e : Nat) : Nat → List Bool + | 0 => [] + | count + 1 => rowBits v e ++ rowsBits v (e + 1) count + +abbrev Label (d : Nat) := Unit ⊕ (Fin d × (MachineTableRows.Label ⊕ Unit)) + +def start (d : Nat) : Label d := .inl () +def rowLabel {d : Nat} (p : Fin d) (stage : MachineTableRows.Label) : Label d := + .inr (p, .inl stage) +def bumpLabel {d : Nat} (p : Fin d) : Label d := .inr (p, .inr ()) + +def fields : Fin 3 → Fin 6 := fun i => i.castLE (by decide) + +def afterPort {d : Nat} (p : Fin d) : Option (Label d) := + if h : p.val + 1 < d then some (rowLabel ⟨p.val + 1, h⟩ .relationRead) else none + +def entry (d : Nat) : Option (Label d) := + if h : 0 < d then some (rowLabel ⟨0, h⟩ .relationRead) else none + +variable {σ : Type} + +abbrev Alphabet (_ : Fin 6) := Bool + +def continueAt {d : Nat} (exit : Option (Label d)) : + TM2.Stmt Alphabet (Label d) (σ × Option Bool) := + match exit with + | none => .halt + | some label => .goto fun _ => label + +theorem stepAux_continueAt {d : Nat} (exit : Option (Label d)) + (state : σ × Option Bool) (tapes : Fin 6 → List Bool) : + TM2.stepAux (continueAt exit) state tapes = ⟨exit, state, tapes⟩ := by + cases exit <;> rfl + +def program (d : Nat) : Label d → TM2.Stmt Alphabet (Label d) (σ × Option Bool) + | .inl () => pushWord 2 trueBits.reverse + (.load (fun state => (state.1, none)) (continueAt (entry d))) + | .inr (p, .inl stage) => MachineTableRows.routine fields 3 4 5 + (rowLabel p) (some (bumpLabel p)) stage + | .inr (p, .inr ()) => .push 1 (fun _ => true) (continueAt (afterPort p)) + +def fieldTapes (v e : Nat) (output : List Bool) : Fin 6 → List Bool := + ![encodeWord v, encodeWord e, trueBits, [], output, []] + +def initialTapes (v e : Nat) (output : List Bool) : Fin 6 → List Bool := + Function.update (fieldTapes v e output) 2 [] + +theorem initializeStep (d v e : Nat) (output : List Bool) + (ambient : σ) (register : Option Bool) : + TM2.step (program d) ⟨some (start d), (ambient, register), initialTapes v e output⟩ = + some ⟨entry d, (ambient, none), fieldTapes v e output⟩ := by + change some (TM2.stepAux (program d (start d)) (ambient, register) + (initialTapes v e output)) = _ + simp only [start, program, stepAux_pushWord, List.reverse_reverse, TM2.stepAux, + initialTapes, Function.update_self, List.append_nil, Function.update_idem] + have ht : Function.update (fieldTapes v e output) 2 trueBits = fieldTapes v e output := by + funext i + fin_cases i <;> simp [fieldTapes] + rw [ht, stepAux_continueAt] + +theorem rowTrace {d : Nat} (p : Fin d) (v e : Nat) (output : List Bool) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step (program d)))^[ + 4 * (v + e + 8194) + 2 * output.length + 9] + (some ⟨some (rowLabel p .relationRead), (ambient, register), fieldTapes v e output⟩) = + some ⟨some (bumpLabel p), (ambient, none), fieldTapes v e (output ++ rowBits v e)⟩ := by + have hfields (i : Fin 3) : fields i ≠ (3 : Fin 6) ∧ fields i ≠ (5 : Fin 6) := by + fin_cases i <;> decide + have h := MachineTableRows.appendTrace fields (3 : Fin 6) 4 5 hfields + (by decide) (by decide) (by decide) (rowLabel p) (some (bumpLabel p)) + (program d) (fun _ => rfl) (fieldTapes v e output) rfl rfl ambient register + have hbits : MachineTableRows.fieldBits fields (fieldTapes v e output) = rowBits v e := by + rfl + have hsize : MachineTableRows.fieldSize fields (fieldTapes v e output) = v + e + 8194 := by + rw [← MachineTableRows.fieldBits_length, hbits, rowBits_length] + have ht : Function.update (fieldTapes v e output) 4 (output ++ rowBits v e) = + fieldTapes v e (output ++ rowBits v e) := by + funext i + fin_cases i <;> simp [fieldTapes] + simpa only [hsize, hbits, show fieldTapes v e output 4 = output from rfl, ht] using h + +theorem bumpStep {d : Nat} (p : Fin d) (v e : Nat) (output : List Bool) (ambient : σ) : + TM2.step (program d) ⟨some (bumpLabel p), (ambient, none), fieldTapes v e output⟩ = + some ⟨afterPort p, (ambient, none), fieldTapes v (e + 1) output⟩ := by + change some (TM2.stepAux (program d (bumpLabel p)) (ambient, none) + (fieldTapes v e output)) = _ + simp only [bumpLabel, program, TM2.stepAux] + rw [stepAux_continueAt] + congr 2 + funext i + fin_cases i <;> simp [fieldTapes, encodeWord, List.replicate_succ] + +theorem rowAndBumpTrace {d : Nat} (p : Fin d) (v e : Nat) (output : List Bool) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step (program d)))^[ + 4 * (v + e + 8194) + 2 * output.length + 10] + (some ⟨some (rowLabel p .relationRead), (ambient, register), fieldTapes v e output⟩) = + some ⟨afterPort p, (ambient, none), fieldTapes v (e + 1) (output ++ rowBits v e)⟩ := by + rw [show 4 * (v + e + 8194) + 2 * output.length + 10 = + (4 * (v + e + 8194) + 2 * output.length + 9) + 1 by omega, + Function.iterate_succ_apply', rowTrace, MachineComposition.advance_some] + exact bumpStep p v e (output ++ rowBits v e) ambient + +def steps (v e : Nat) (output : List Bool) : Nat → Nat + | 0 => 0 + | count + 1 => (4 * (v + e + 8194) + 2 * output.length + 10) + + steps v (e + 1) (output ++ rowBits v e) count + +theorem suffixTrace {d : Nat} (count : Nat) (p : Fin d) (hp : p.val + count = d) + (v e : Nat) (output : List Bool) (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step (program d)))^[steps v e output count] + (some ⟨some (rowLabel p .relationRead), (ambient, register), fieldTapes v e output⟩) = + some ⟨none, (ambient, none), fieldTapes v (e + count) (output ++ rowsBits v e count)⟩ := by + induction count generalizing p v e output register with + | zero => + have hlt := p.isLt + omega + | succ count ih => + rw [steps, Nat.add_comm (4 * (v + e + 8194) + 2 * output.length + 10), + Function.iterate_add_apply, rowAndBumpTrace] + by_cases hc : count = 0 + · subst count + have hlast : ¬ p.val + 1 < d := by omega + simp [afterPort, hlast, steps, rowsBits] + · have hnext : p.val + 1 < d := by omega + rw [afterPort, dite_eq_left hnext] + have hh := ih ⟨p.val + 1, hnext⟩ (by change (p.val + 1) + count = d; omega) + v (e + 1) (output ++ rowBits v e) none + have he : (e + 1) + count = e + (count + 1) := by omega + simpa only [rowsBits, List.append_assoc, he] using hh + +theorem allTrace (d v e : Nat) (output : List Bool) (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step (program d)))^[steps v e output d + 1] + (some ⟨some (start d), (ambient, register), initialTapes v e output⟩) = + some ⟨none, (ambient, none), fieldTapes v (e + d) (output ++ rowsBits v e d)⟩ := by + rw [Function.iterate_succ_apply] + change (MachineComposition.advance (TM2.step (program d)))^[steps v e output d] + (TM2.step (program d) ⟨some (start d), (ambient, register), initialTapes v e output⟩) = _ + rw [initializeStep] + by_cases hd : 0 < d + · rw [entry, dite_eq_left hd] + exact suffixTrace d ⟨0, hd⟩ (by simp) v e output ambient none + · have hz : d = 0 := by omega + subst d + simp [entry, steps, rowsBits] + +def graphRows {n m : Nat} (v : Fin n) (e : Nat) : + (count : Nat) → e + count ≤ m → List (DartRow n m) + | 0, _ => [] + | count + 1, h => + ⟨v, ⟨e, by omega⟩, trueRelation⟩ :: + graphRows v (e + 1) count (by omega) + +theorem graphRows_length {n m : Nat} (v : Fin n) (e count : Nat) (h : e + count ≤ m) : + (graphRows v e count h).length = count := by + induction count generalizing e with + | zero => rfl + | succ count ih => simp [graphRows, ih] + +theorem rowsBits_eq_graphRows {n m : Nat} (v : Fin n) (e count : Nat) + (h : e + count ≤ m) : + rowsBits v.val e count = encodeWords ((graphRows v e count h).flatMap rowWords) := by + induction count generalizing e with + | zero => rfl + | succ count ih => + simp [rowsBits, graphRows, encodeWords_append, MachineTableRows.rowBits_eq, + rowBits, trueBits] + exact ih (e + 1) (by omega) + +def dummyRows {n : Nat} (d : Nat) (v : Fin n) : List (DartRow n (n * d)) := + graphRows v (d * v.val) d (by + have h := Nat.mul_le_mul_right d (Nat.succ_le_of_lt v.isLt) + simpa only [Nat.succ_mul, Nat.mul_comm] using h) + +theorem dummyRows_length {n : Nat} (d : Nat) (v : Fin n) : + (dummyRows d v).length = d := graphRows_length _ _ _ _ + +theorem dummyRowsTrace {n : Nat} (d : Nat) (v : Fin n) (output : List Bool) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step (program d)))^[steps v.val (d * v.val) output d + 1] + (some ⟨some (start d), (ambient, register), initialTapes v.val (d * v.val) output⟩) = + some ⟨none, (ambient, none), fieldTapes v.val (d * v.val + d) + (output ++ encodeWords ((dummyRows d v).flatMap rowWords))⟩ := by + have h := allTrace d v.val (d * v.val) output ambient register + rw [rowsBits_eq_graphRows v (d * v.val) d (by + have h := Nat.mul_le_mul_right d (Nat.succ_le_of_lt v.isLt) + simpa only [Nat.succ_mul, Nat.mul_comm] using h)] at h + exact h + +theorem steps_le_bound (v e : Nat) (output : List Bool) (count : Nat) : + steps v e output count ≤ count * + (4 * (v + e + count + 8194) + + 2 * (output.length + count * (v + e + count + 8194)) + 10) := by + induction count generalizing e output with + | zero => simp [steps] + | succ count ih => + let B := v + e + (count + 1) + 8194 + let C := 4 * B + 2 * (output.length + (count + 1) * B) + 10 + have hb : v + (e + 1) + count + 8194 = B := by dsimp [B]; omega + have hi := ih (e + 1) (output ++ rowBits v e) + rw [List.length_append, rowBits_length, hb] at hi + have hrow : v + e + 8194 ≤ B := by dsimp [B]; omega + have hout : output.length + (v + e + 8194) + count * B ≤ + output.length + (count + 1) * B := by + calc + _ ≤ output.length + B + count * B := + Nat.add_le_add_right (Nat.add_le_add_left hrow output.length) _ + _ = _ := by simp only [Nat.add_mul, Nat.one_mul]; omega + have hconstant : 4 * B + 2 * (output.length + (v + e + 8194) + count * B) + 10 ≤ C := by + exact Nat.add_le_add_right + (Nat.add_le_add_left (Nat.mul_le_mul_left 2 hout) (4 * B)) 10 + have hremaining := hi.trans (Nat.mul_le_mul_left count hconstant) + have hbody : 4 * (v + e + 8194) + 2 * output.length + 10 ≤ C := by + exact Nat.add_le_add_right (Nat.add_le_add (Nat.mul_le_mul_left 4 hrow) + (Nat.mul_le_mul_left 2 (Nat.le_add_right output.length ((count + 1) * B)))) 10 + change (4 * (v + e + 8194) + 2 * output.length + 10) + + steps v (e + 1) (output ++ rowBits v e) count ≤ (count + 1) * C + calc + _ ≤ C + count * C := Nat.add_le_add hbody hremaining + _ = (count + 1) * C := by rw [Nat.add_mul, Nat.one_mul]; omega + +def inputSize (v e : Nat) (output : List Bool) : Nat := + (encodeWord v).length + (encodeWord e).length + output.length + +noncomputable def timePolynomial (d : Nat) : Polynomial Nat := + Polynomial.C d * + (Polynomial.C 4 * (Polynomial.X + Polynomial.C (d + 8192)) + + Polynomial.C 2 * (Polynomial.X + Polynomial.C d * + (Polynomial.X + Polynomial.C (d + 8192))) + Polynomial.C 10) + 1 + +theorem timePolynomial_bounds (d v e : Nat) (output : List Bool) : + steps v e output d + 1 ≤ (timePolynomial d).eval (inputSize v e output) := by + have h := steps_le_bound v e output d + have hB : v + e + d + 8194 ≤ inputSize v e output + d + 8192 := by + simp only [inputSize, encodeWord_length] + omega + have hO : output.length ≤ inputSize v e output := by + simp only [inputSize, encodeWord_length] + omega + have hm := Nat.mul_le_mul_left d hB + have hinner : + 4 * (v + e + d + 8194) + 2 * (output.length + d * (v + e + d + 8194)) + 10 ≤ + 4 * (inputSize v e output + d + 8192) + + 2 * (inputSize v e output + d * (inputSize v e output + d + 8192)) + 10 := by + exact Nat.add_le_add_right (Nat.add_le_add (Nat.mul_le_mul_left 4 hB) + (Nat.mul_le_mul_left 2 (Nat.add_le_add hO hm))) 10 + have htotal := h.trans (Nat.mul_le_mul_left d hinner) + simp only [timePolynomial, Polynomial.eval_add, Polynomial.eval_mul, + Polynomial.eval_C, Polynomial.eval_X, Polynomial.eval_one] + simpa only [Nat.add_assoc] using Nat.add_le_add_right htotal 1 + +def machine (d : Nat) : FinTM2 where + K := Fin 6 + k₀ := 0 + k₁ := 4 + Γ _ := Bool + Λ := Label d + main := start d + σ := Unit × Option Bool + initialState := ((), none) + m := program d + +def machineInTime (d v e : Nat) (output : List Bool) (register : Option Bool) : + StateTransition.EvalsToInTime (machine d).step + ⟨some (start d), ((), register), initialTapes v e output⟩ + (some ⟨none, ((), none), fieldTapes v (e + d) (output ++ rowsBits v e d)⟩) + ((timePolynomial d).eval (inputSize v e output)) where + steps := steps v e output d + 1 + evals_in_steps := by + convert allTrace d v e output () register using 1 + rfl + steps_le_m := timePolynomial_bounds d v e output + +def machineDummyInTime {n : Nat} (d : Nat) (v : Fin n) + (output : List Bool) (register : Option Bool) : + StateTransition.EvalsToInTime (machine d).step + ⟨some (start d), ((), register), initialTapes v.val (d * v.val) output⟩ + (some ⟨none, ((), none), fieldTapes v.val (d * v.val + d) + (output ++ encodeWords ((dummyRows d v).flatMap rowWords))⟩) + ((timePolynomial d).eval (inputSize v.val (d * v.val) output)) where + steps := steps v.val (d * v.val) output d + 1 + evals_in_steps := by + convert dummyRowsTrace d v output () register using 1 + rfl + steps_le_m := timePolynomial_bounds d v.val (d * v.val) output + +theorem finalFrame (v e : Nat) (output : List Bool) : + fieldTapes v e output 0 = encodeWord v ∧ + fieldTapes v e output 2 = trueBits ∧ + fieldTapes v e output 3 = [] ∧ fieldTapes v e output 5 = [] := + ⟨rfl, rfl, rfl, rfl⟩ + +end MinUncutGames.Foundations.Complexity.MachineDummyRows + +end +section +namespace MinUncutGames.Foundations.Complexity.MachineRegularDummyRow + +open Turing MachineComposition PCP.GraphTables + +abbrev Tape := Fin 6 +abbrev Alphabet (_ : Tape) := Bool +abbrev State (σ : Type) := σ × Option Bool + +inductive Label + | affine (stage : MachineUnaryAffineAt.Label) + | row (stage : MachineDummyRows.Label 1) + | reverse | relation + deriving DecidableEq, Fintype + +def reverseIndex (q x : Nat) : Nat := (q + 1) * x + q + +def emittedBits (q x : Nat) : List Bool := + MachineDummyRows.rowBits x (reverseIndex q x) + +def instruction {σ Λ : Type} (q : Nat) (labels : Label → Λ) (exit : Option Λ) : + Label → TM2.Stmt Alphabet Λ (State σ) + | .affine .seed => MachineUnaryAffineAt.seed 1 q (labels (.affine .scan)) + | .affine .scan => MachineUnaryAffineAt.scan 0 3 1 (q + 1) + (labels (.affine .scan)) (labels (.affine .restore)) + | .affine .restore => Reduction.MachineTransfer.loopAt 3 0 id false + (labels (.affine .restore)) (some (labels (.row (MachineDummyRows.start 1)))) + | .row stage => MachineCloudPadding.Placement.statement (id : Tape → Tape) + (fun l => labels (.row l)) (some (labels .reverse)) + (MachineDummyRows.program 1 stage) + | .reverse => MachineDrain.drain 1 (labels .reverse) (some (labels .relation)) + | .relation => MachineDrain.drain 2 (labels .relation) exit + +structure Input (x : Nat) (base : Tape → List Bool) : Prop where + source : base 0 = encodeWord x + reverseEmpty : base 1 = [] + relationEmpty : base 2 = [] + scratchEmpty : base 3 = [] + rowEmpty : base 5 = [] + +def memory (x : Nat) (output : List Bool) : Tape → List Bool := + ![encodeWord x, [], [], [], output, []] + +theorem memory_input (x : Nat) (output : List Bool) : Input x (memory x output) := + ⟨rfl, rfl, rfl, rfl, rfl⟩ + +private theorem join_trace {A : Type*} {f : A → A} {m n : Nat} {a b c : A} + (first : f^[m] a = b) (second : f^[n] b = c) : f^[m + n] a = c := by + rw [Nat.add_comm m n, Function.iterate_add_apply, first, second] + +theorem affine_frame (x e : Nat) (base : Tape → List Bool) (input : Input x base) : + Function.update base 1 (encodeWord e) = + MachineDummyRows.initialTapes x e (base 4) := by + funext k + fin_cases k <;> + simp [MachineDummyRows.initialTapes, MachineDummyRows.fieldTapes, + input.source, input.relationEmpty, input.scratchEmpty, input.rowEmpty] + +theorem cleanup_frame (x e : Nat) (output : List Bool) + (base : Tape → List Bool) (input : Input x base) : + Function.update (Function.update (MachineDummyRows.fieldTapes x e output) 1 []) 2 [] = + Function.update base 4 output := by + funext k + fin_cases k <;> + simp [MachineDummyRows.fieldTapes, input.source, input.reverseEmpty, + input.relationEmpty, input.scratchEmpty, input.rowEmpty] + +theorem rowTraceAt {σ Λ : Type} (q : Nat) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt Alphabet Λ (State σ)) + (code : ∀ l, program (labels l) = instruction q labels exit l) + (x e : Nat) (output : List Bool) (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[MachineDummyRows.steps x e output 1 + 1] + (some ⟨some (labels (.row (MachineDummyRows.start 1))), (ambient, register), + MachineDummyRows.initialTapes x e output⟩) = + some ⟨some (labels .reverse), (ambient, none), + MachineDummyRows.fieldTapes x (e + 1) (output ++ MachineDummyRows.rowBits x e)⟩ := by + have run := MachineDummyRows.allTrace 1 x e output ambient register + have placed := MachineCloudPadding.Placement.trace (id : Tape → Tape) (fun k => some k) + (fun _ => rfl) (fun _ _ h => (Option.some.inj h).symm) + (fun l => labels (.row l)) (some (labels .reverse)) (fun _ => []) + (MachineDummyRows.program 1) program + (fun l => code (.row l)) _ _ _ run + have identityTapes (source : Tape → List Bool) : + MachineCloudPadding.Placement.tapes (fun k : Tape => some k) source + (fun _ : Tape => []) = source := rfl + simpa only [MachineCloudPadding.Placement.configuration, + MachineCloudPadding.Placement.label, identityTapes, + MachineDummyRows.rowsBits, List.append_nil] using placed + +theorem cleanupTraceAt {σ Λ : Type} (q : Nat) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt Alphabet Λ (State σ)) + (code : ∀ l, program (labels l) = instruction q labels exit l) + (x e : Nat) (output : List Bool) (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[ + ((encodeWord e).length + 1) + (MachineDummyRows.trueBits.length + 1)] + (some ⟨some (labels .reverse), (ambient, register), + MachineDummyRows.fieldTapes x e output⟩) = + some ⟨exit, (ambient, none), + Function.update (Function.update (MachineDummyRows.fieldTapes x e output) 1 []) 2 []⟩ := by + let base := MachineDummyRows.fieldTapes x e output + let mid := Function.update base (1 : Tape) [] + have first := MachineDrain.drainTrace (1 : Tape) (labels .reverse) + (some (labels .relation)) program (code .reverse) base (base 1) ambient register + have second := MachineDrain.drainTrace (2 : Tape) (labels .relation) + exit program (code .relation) mid (mid 2) ambient none + simp only [Function.update_eq_self] at first second + have hreverse : base 1 = encodeWord e := rfl + have hrelation : mid 2 = MachineDummyRows.trueBits := by + simp only [mid, Function.update_of_ne (by decide : (2 : Tape) ≠ 1)] + rfl + rw [hreverse] at first + rw [hrelation] at second + exact join_trace first second + +def steps (q x : Nat) (output : List Bool) : Nat := + ((2 * (x + 1) + 1) + (MachineDummyRows.steps x (reverseIndex q x) output 1 + 1)) + + (((encodeWord (reverseIndex q x + 1)).length + 1) + + (MachineDummyRows.trueBits.length + 1)) + +def timeBound (q x outputLength : Nat) : Nat := + (5 * q + 11) * x + 2 * outputLength + 5 * q + 40986 + +theorem steps_eq (q x : Nat) (output : List Bool) : + steps q x output = timeBound q x output.length := by + simp only [steps, MachineDummyRows.steps, encodeWord_length, MachineDummyRows.trueBits_length, + reverseIndex, timeBound] + ring + +theorem traceAt {σ Λ : Type} (q : Nat) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt Alphabet Λ (State σ)) + (code : ∀ l, program (labels l) = instruction q labels exit l) + (x : Nat) (base : Tape → List Bool) (input : Input x base) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[steps q x (base 4)] + (some ⟨some (labels (.affine .seed)), (ambient, register), base⟩) = + some ⟨exit, (ambient, none), Function.update base 4 (base 4 ++ emittedBits q x)⟩ := by + have affine := MachineUnaryAffineAt.seededAffineTrace (0 : Tape) 3 1 + (by decide) (by decide) (by decide) (q + 1) q + (labels (.affine .seed)) (labels (.affine .scan)) (labels (.affine .restore)) + (some (labels (.row (MachineDummyRows.start 1)))) program + (code (.affine .seed)) (code (.affine .scan)) (code (.affine .restore)) + base x [] (by simpa only [List.append_nil] using input.source) + input.scratchEmpty ambient register + simp only [input.reverseEmpty, List.append_nil] at affine + change (advance (TM2.step program))^[2 * (x + 1) + 1] + (some ⟨some (labels (.affine .seed)), (ambient, register), base⟩) = + some ⟨some (labels (.row (MachineDummyRows.start 1))), (ambient, none), + Function.update base 1 (encodeWord (reverseIndex q x))⟩ at affine + rw [affine_frame x (reverseIndex q x) base input] at affine + have row := rowTraceAt q labels exit program code x (reverseIndex q x) (base 4) ambient none + have clean := cleanupTraceAt q labels exit program code x (reverseIndex q x + 1) + (base 4 ++ MachineDummyRows.rowBits x (reverseIndex q x)) ambient none + rw [cleanup_frame x (reverseIndex q x + 1) _ base input] at clean + exact join_trace (join_trace affine row) clean + +def machine (q : Nat) : FinTM2 where + K := Tape + k₀ := 0 + k₁ := 4 + Γ := Alphabet + Λ := Label + main := .affine .seed + σ := State Unit + initialState := ((), none) + m := instruction q id none + +def machineInTime (q x : Nat) (base : Tape → List Bool) (input : Input x base) + (register : Option Bool) : + StateTransition.EvalsToInTime (machine q).step + ⟨some (.affine .seed), ((), register), base⟩ + (some ⟨none, ((), none), Function.update base (4 : Tape) + (base 4 ++ emittedBits q x)⟩) + (timeBound q x (base 4).length) where + steps := steps q x (base 4) + evals_in_steps := traceAt q id none (instruction q id none) + (fun _ => rfl) x base input () register + steps_le_m := (steps_eq q x (base 4)).le + +end MinUncutGames.Foundations.Complexity.MachineRegularDummyRow + +end +section +namespace MinUncutGames.Foundations.Complexity.MachinePaddingRows + +open Turing MachineComposition + +inductive Control + | initialize | guard | bump + deriving DecidableEq + +protected abbrev Control.enumList : List Control := [.initialize, .guard, .bump] + +protected theorem Control.enumList_getElem?_ctorIdx_eq (x : Control) : + Control.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem Control.enumList_nodup : Control.enumList.Nodup := by decide + +instance : Fintype Control where + elems := ⟨Control.enumList, Control.enumList_nodup⟩ + complete x := by cases x <;> decide + +abbrev Tape := Fin 6 ⊕ Unit +abbrev Label (d : Nat) := MachineDummyRows.Label d ⊕ Control +abbrev Alphabet : Tape → Type := MachineEmbedding.Alphabet + (fun _ : Fin 6 => Bool) (fun _ : Unit => Bool) +abbrev State := (Unit × Option Bool) × Unit + +def bodyEntry (d : Nat) (hd : 0 < d) : Label d := + .inl (MachineDummyRows.rowLabel ⟨0, hd⟩ .relationRead) + +def extra (d : Nat) (hd : 0 < d) : Control → TM2.Stmt Alphabet (Label d) State + | .initialize => Reduction.MachineSubstitution.pushWord (.inl 2) + MachineDummyRows.trueBits.reverse + (.load (fun _ => (((), none), ())) (.goto (fun _ => .inr .guard))) + | .guard => .pop (.inr ()) (fun _ bit => (((), bit), ())) + (.branch (fun s => s.1.2.getD false) + (.load (fun _ => (((), none), ())) (.goto (fun _ => bodyEntry d hd))) + (.push (.inr ()) (fun _ => false) + (.load (fun _ => (((), none), ())) .halt))) + | .bump => .push (.inl 0) (fun _ => true) (.goto (fun _ => .inr .guard)) + +def program (d : Nat) (hd : 0 < d) : Label d → TM2.Stmt Alphabet (Label d) State := + MachineEmbedding.program (some (.inr .bump)) (MachineDummyRows.program d) (extra d hd) + +def tapes (v e fuel : Nat) (output : List Bool) : ∀ k, List (Alphabet k) := + MachineEmbedding.tapes (MachineDummyRows.fieldTapes v e output) + (fun _ : Unit => encodeWord fuel) + +def cfg (d : Nat) (label : Option (Label d)) (v e fuel : Nat) + (output : List Bool) : TM2.Cfg Alphabet (Label d) State := + ⟨label, (((), none), ()), tapes v e fuel output⟩ + +theorem bodyTrace (d : Nat) (hd : 0 < d) (v e fuel : Nat) (output : List Bool) : + (advance (TM2.step (program d hd)))^[MachineDummyRows.steps v e output d] + (some (cfg d (some (bodyEntry d hd)) v e fuel output)) = + some (cfg d (some (.inr .bump)) v (e + d) fuel + (output ++ MachineDummyRows.rowsBits v e d)) := by + have run := MachineDummyRows.suffixTrace d ⟨0, hd⟩ (by simp) + v e output () none + have lifted := liftSuccessfulTrace + (TM2.step (MachineDummyRows.program d)) (TM2.step (program d hd)) + (MachineEmbedding.configuration (some (.inr .bump)) () + (fun _ : Unit => encodeWord fuel)) + (by + intro a b h + exact MachineEmbedding.step_simulation (some (.inr Control.bump)) () + (fun _ : Unit => encodeWord fuel) (MachineDummyRows.program d) (extra d hd) a b h) + (MachineDummyRows.steps v e output d) _ _ run + exact lifted + +theorem guard_succ (d : Nat) (hd : 0 < d) (v e fuel : Nat) (output : List Bool) : + TM2.step (program d hd) (cfg d (some (.inr .guard)) v e (fuel + 1) output) = + some (cfg d (some (bodyEntry d hd)) v e fuel output) := by + change some (TM2.stepAux (extra d hd .guard) _ _) = _ + simp only [extra, TM2.stepAux, tapes, MachineEmbedding.tapes_inr, + encodeWord, List.replicate_succ, List.cons_append, List.head?_cons, + List.tail_cons, Option.getD_some, Bool.cond_true] + congr 2 + funext k + cases k <;> simp [tapes, MachineEmbedding.tapes, Function.update, encodeWord] + +theorem guard_zero (d : Nat) (hd : 0 < d) (v e : Nat) (output : List Bool) : + TM2.step (program d hd) (cfg d (some (.inr .guard)) v e 0 output) = + some (cfg d none v e 0 output) := by + change some (TM2.stepAux (extra d hd .guard) _ _) = _ + simp only [extra, TM2.stepAux, tapes, MachineEmbedding.tapes_inr, + encodeWord, List.replicate_zero, List.nil_append, List.head?_cons, + List.tail_cons, Option.getD_some, Bool.cond_false] + congr 2 + funext k + cases k <;> simp [tapes, MachineEmbedding.tapes, Function.update, encodeWord] + +theorem bump_step (d : Nat) (hd : 0 < d) (v e fuel : Nat) (output : List Bool) : + TM2.step (program d hd) (cfg d (some (.inr .bump)) v e fuel output) = + some (cfg d (some (.inr .guard)) (v + 1) e fuel output) := by + change some (TM2.stepAux (extra d hd .bump) _ _) = _ + simp only [extra, TM2.stepAux] + congr 2 + funext k + cases k with + | inl k => fin_cases k <;> simp [tapes, MachineEmbedding.tapes, + MachineDummyRows.fieldTapes, encodeWord, List.replicate_succ] + | inr k => simp [tapes, MachineEmbedding.tapes] + +def paddingBits (d v e : Nat) : Nat → List Bool + | 0 => [] + | count + 1 => MachineDummyRows.rowsBits v e d ++ paddingBits d (v + 1) (e + d) count + +def steps (d v e : Nat) (output : List Bool) : Nat → Nat + | 0 => 1 + | count + 1 => (MachineDummyRows.steps v e output d + 2) + + steps d (v + 1) (e + d) (output ++ MachineDummyRows.rowsBits v e d) count + +theorem loopTrace (d : Nat) (hd : 0 < d) (count v e : Nat) (output : List Bool) : + (advance (TM2.step (program d hd)))^[steps d v e output count] + (some (cfg d (some (.inr .guard)) v e count output)) = + some (cfg d none (v + count) (e + count * d) 0 + (output ++ paddingBits d v e count)) := by + induction count generalizing v e output with + | zero => simpa [steps, paddingBits] using guard_zero d hd v e output + | succ count ih => + rw [steps, Nat.add_comm (MachineDummyRows.steps v e output d + 2), + Function.iterate_add_apply] + have hb : (advance (TM2.step (program d hd)))^[MachineDummyRows.steps v e output d + 2] + (some (cfg d (some (.inr .guard)) v e (count + 1) output)) = + some (cfg d (some (.inr .guard)) (v + 1) (e + d) count + (output ++ MachineDummyRows.rowsBits v e d)) := by + rw [show MachineDummyRows.steps v e output d + 2 = + (MachineDummyRows.steps v e output d + 1) + 1 by omega, + Function.iterate_succ_apply, advance_some, guard_succ, + Function.iterate_succ_apply', bodyTrace, advance_some, bump_step] + rw [hb, ih] + simp only [paddingBits, List.append_assoc, Nat.succ_mul] + congr 2 <;> omega + +def initialTapes (v e fuel : Nat) (output : List Bool) : ∀ k, List (Alphabet k) := + Function.update (tapes v e fuel output) (.inl 2) [] + +theorem initialize_step (d : Nat) (hd : 0 < d) (v e fuel : Nat) (output : List Bool) : + TM2.step (program d hd) + ⟨some (.inr .initialize), (((), none), ()), initialTapes v e fuel output⟩ = + some (cfg d (some (.inr .guard)) v e fuel output) := by + change some (TM2.stepAux (extra d hd .initialize) _ _) = _ + simp only [extra, Reduction.MachineSubstitution.stepAux_pushWord, + List.reverse_reverse, initialTapes, Function.update_self, List.append_nil, + Function.update_idem, TM2.stepAux] + congr 2 + funext k + cases k with + | inl k => fin_cases k <;> simp [tapes, MachineEmbedding.tapes, + MachineDummyRows.fieldTapes] + | inr k => simp [tapes, MachineEmbedding.tapes] + +theorem paddingTrace (d : Nat) (hd : 0 < d) (count v e : Nat) (output : List Bool) : + (advance (TM2.step (program d hd)))^[steps d v e output count + 1] + (some ⟨some (.inr .initialize), (((), none), ()), initialTapes v e count output⟩) = + some (cfg d none (v + count) (e + count * d) 0 + (output ++ paddingBits d v e count)) := by + rw [Function.iterate_succ_apply, advance_some, initialize_step, loopTrace] + +def machine (d : Nat) (hd : 0 < d) : FinTM2 where + K := Tape + k₀ := .inl 0 + k₁ := .inl 4 + Γ := Alphabet + Λ := Label d + main := .inr .initialize + σ := State + initialState := (((), none), ()) + m := program d hd + +def execution (d : Nat) (hd : 0 < d) (count v e : Nat) (output : List Bool) : + StateTransition.EvalsToInTime (machine d hd).step + ⟨some (.inr .initialize), (((), none), ()), initialTapes v e count output⟩ + (some (cfg d none (v + count) (e + count * d) 0 + (output ++ paddingBits d v e count))) + (steps d v e output count + 1) where + steps := steps d v e output count + 1 + evals_in_steps := by + convert paddingTrace d hd count v e output using 1 + rfl + steps_le_m := le_rfl + +end MinUncutGames.Foundations.Complexity.MachinePaddingRows + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineExpanderFamilyAffine.lean b/lean/OAI/Computability/MinUncut/Machines/MachineExpanderFamilyAffine.lean new file mode 100644 index 0000000000000000000000000000000000000000..cf373b992beb87f85e65fddeb6778bb8fc6505ed --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineExpanderFamilyAffine.lean @@ -0,0 +1,826 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineExpanderTableProgram + +namespace OAI + +namespace MinUncutGames.Foundations.Complexity.MachineExpanderFamily + +open Turing MachineComposition +open PCP.ExpanderTables PCP.ExpanderRowControl + +theorem affine_source_ne_scratch (phase : AffinePhase) : + affineSource phase ≠ .inr .unaryScratch := by cases phase <;> decide + +theorem affine_source_ne_destination (phase : AffinePhase) : + affineSource phase ≠ affineDestination phase := by cases phase <;> decide + +theorem affine_scratch_ne_destination (phase : AffinePhase) : + (.inr .unaryScratch : Tape) ≠ affineDestination phase := by cases phase <;> decide + +def affineResultTapes (d : Nat) (phase : AffinePhase) + (base : (tape : Tape) → List (Alphabet tape)) (n : Nat) : + (tape : Tape) → List (Alphabet tape) := + Function.update base (affineDestination phase) + (boolWord (affineDestination phase) + (encodeWord (affineCoefficient d phase * n) ++ toBoolTapes base (affineDestination phase))) + +theorem affineResultTapes_other (d : Nat) (phase : AffinePhase) + (base : (tape : Tape) → List (Alphabet tape)) (n : Nat) (tape : Tape) + (different : tape ≠ affineDestination phase) : + affineResultTapes d phase base n tape = base tape := by + simp [affineResultTapes, different] + +theorem affineResultTapes_source (d : Nat) (phase : AffinePhase) + (base : (tape : Tape) → List (Alphabet tape)) (n : Nat) : + affineResultTapes d phase base n (affineSource phase) = base (affineSource phase) := + affineResultTapes_other d phase base n _ (affine_source_ne_destination phase) + +theorem affineResultTapes_scratch (d : Nat) (phase : AffinePhase) + (base : (tape : Tape) → List (Alphabet tape)) (n : Nat) : + affineResultTapes d phase base n (.inr .unaryScratch) = base (.inr .unaryScratch) := + affineResultTapes_other d phase base n _ (affine_scratch_ne_destination phase) + +theorem affineResultTapes_destination (d : Nat) (phase : AffinePhase) + (base : (tape : Tape) → List (Alphabet tape)) (n : Nat) : + toBoolTapes (affineResultTapes d phase base n) (affineDestination phase) = + encodeWord (affineCoefficient d phase * n) ++ toBoolTapes base (affineDestination phase) := by + simp [affineResultTapes, toBoolTapes] + +variable {ρ : Type} [Fintype ρ] {d : Nat} + +theorem affinePhaseBoolTrace (positive : 0 < d) (H : Table (cloudSize d) d) + (growth : 1 < cloudSize d) (phase : AffinePhase) (base : Tape → List Bool) + (n : Nat) (suffix : List Bool) + (sourceWord : base (affineSource phase) = encodeWord n ++ suffix) + (scratchEmpty : base (.inr .unaryScratch) = []) (state : State ρ d) : + (advance (TM2.step (boolView positive H growth)))^[2 * (n + 1) + 1] + (some ⟨some (.inr (.affine phase .seed)), state, base⟩) = + some ⟨some (affineExit d phase), clearRegister state, + Function.update base (affineDestination phase) + (encodeWord (affineCoefficient d phase * n) ++ base (affineDestination phase))⟩ := by + let states := registerStates ρ d + let target := boolView (ρ := ρ) positive H growth + let sourceProgram := MachineControl.program (Equiv.refl (Label d)) states.symm target + have atSeed : sourceProgram (.inr (.affine phase .seed)) = + MachineUnaryAffineAt.seed (affineDestination phase) 0 (.inr (.affine phase .scan)) := by + change MachineControl.statement id states.symm + (boolView positive H growth (.inr (.affine phase .seed))) = _ + rw [boolView_outer] + exact controlStatementInverse states _ + have atScan : sourceProgram (.inr (.affine phase .scan)) = + MachineUnaryAffineAt.scan (affineSource phase) (.inr .unaryScratch) + (affineDestination phase) (affineCoefficient d phase) + (.inr (.affine phase .scan)) (.inr (.affine phase .restore)) := by + change MachineControl.statement id states.symm + (boolView positive H growth (.inr (.affine phase .scan))) = _ + rw [boolView_outer] + exact controlStatementInverse states _ + have atRestore : sourceProgram (.inr (.affine phase .restore)) = + Reduction.MachineTransfer.loopAt (.inr .unaryScratch) (affineSource phase) id false + (.inr (.affine phase .restore)) (some (affineExit d phase)) := by + change MachineControl.statement id states.symm + (boolView positive H growth (.inr (.affine phase .restore))) = _ + rw [boolView_outer] + exact controlStatementInverse states _ + have raw := MachineUnaryAffineAt.seededAffineTrace + (affineSource phase) (.inr .unaryScratch) (affineDestination phase) + (affine_source_ne_scratch phase) (affine_source_ne_destination phase) + (affine_scratch_ne_destination phase) (affineCoefficient d phase) 0 + (.inr (.affine phase .seed)) (.inr (.affine phase .scan)) (.inr (.affine phase .restore)) + (some (affineExit d phase)) sourceProgram atSeed atScan atRestore base n suffix + sourceWord scratchEmpty (states.symm state).1 (states.symm state).2 + have run := controlTrace states target (2 * (n + 1) + 1) _ _ raw + simpa only [states, target, MachineControl.configuration, Option.map_some, id_eq, Prod.mk.eta, + Equiv.apply_symm_apply, Nat.add_zero, registerStates_reset] using run + +theorem affinePhaseTrace (positive : 0 < d) (H : Table (cloudSize d) d) + (growth : 1 < cloudSize d) (phase : AffinePhase) + (base : (tape : Tape) → List (Alphabet tape)) (n : Nat) (suffix : List Bool) + (sourceWord : toBoolTapes base (affineSource phase) = encodeWord n ++ suffix) + (scratchEmpty : base (.inr .unaryScratch) = []) (state : State ρ d) : + (advance (TM2.step (program positive H growth)))^[2 * (n + 1) + 1] + (some ⟨some (.inr (.affine phase .seed)), state, base⟩) = + some ⟨some (affineExit d phase), clearRegister state, + affineResultTapes d phase base n⟩ := by + have raw := affinePhaseBoolTrace positive H growth phase (toBoolTapes base) n suffix + sourceWord scratchEmpty state + have transported := boolTraceActual positive H growth (2 * (n + 1) + 1) _ _ raw + simpa only [configuration_fromBool, fromBoolTapes_update, fromBool_toBool, + affineResultTapes] using transported + +def affinePhaseInTime (positive : 0 < d) (H : Table (cloudSize d) d) + (growth : 1 < cloudSize d) (phase : AffinePhase) + (base : (tape : Tape) → List (Alphabet tape)) (n : Nat) (suffix : List Bool) + (sourceWord : toBoolTapes base (affineSource phase) = encodeWord n ++ suffix) + (scratchEmpty : base (.inr .unaryScratch) = []) (state : State ρ d) : + StateTransition.EvalsToInTime (TM2.step (program positive H growth)) + ⟨some (.inr (.affine phase .seed)), state, base⟩ + (some ⟨some (affineExit d phase), clearRegister state, + affineResultTapes d phase base n⟩) (2 * (n + 1) + 1) where + steps := 2 * (n + 1) + 1 + evals_in_steps := affinePhaseTrace positive H growth phase base n suffix sourceWord scratchEmpty state + steps_le_m := Nat.le_refl _ + +def copyCountInTime (positive : 0 < d) (H : Table (cloudSize d) d) + (growth : 1 < cloudSize d) (base : (tape : Tape) → List (Alphabet tape)) + (n : Nat) (sourceWord : base (.inr .currentSize) = encodeWord n) + (scratchEmpty : base (.inr .unaryScratch) = []) + (destinationEmpty : base vertexCountTape = []) (state : State ρ d) : + StateTransition.EvalsToInTime (TM2.step (program positive H growth)) + ⟨some (.inr (.affine .copyCount .seed)), state, base⟩ + (some ⟨some (.inl (.inr .initialize)), clearRegister state, + Function.update base vertexCountTape (encodeWord n)⟩) (2 * (n + 1) + 1) := by + have run := affinePhaseInTime positive H growth .copyCount base n [] + (by simpa only [affineSource, toBoolTapes, toBoolWord, List.append_nil] using sourceWord) + scratchEmpty state + change base (.inl (.inr .vertexCount)) = [] at destinationEmpty + simpa only [affineExit, affineResultTapes, affineDestination, affineCoefficient, + Nat.one_mul, vertexCountTape, boolWord, toBoolTapes, toBoolWord, + destinationEmpty, List.append_nil] using run + +def multiplySizeInTime (positive : 0 < d) (H : Table (cloudSize d) d) + (growth : 1 < cloudSize d) (base : (tape : Tape) → List (Alphabet tape)) + (n : Nat) (sourceWord : base inputVertexTape = encodeWord n) + (scratchEmpty : base (.inr .unaryScratch) = []) + (destinationEmpty : base (.inr .currentSize) = []) (state : State ρ d) : + StateTransition.EvalsToInTime (TM2.step (program positive H growth)) + ⟨some (.inr (.affine .multiplySize .seed)), state, base⟩ + (some ⟨some (.inr .drainInputVertex), clearRegister state, + Function.update base (.inr .currentSize) (encodeWord (cloudSize d * n))⟩) + (2 * (n + 1) + 1) := by + have run := affinePhaseInTime positive H growth .multiplySize base n [] + (by simpa only [affineSource, inputVertexTape, toBoolTapes, toBoolWord, + List.append_nil] using sourceWord) + scratchEmpty state + simpa only [affineExit, affineResultTapes, affineDestination, affineCoefficient, + boolWord, toBoolTapes, toBoolWord, destinationEmpty, List.append_nil] using run + +end MinUncutGames.Foundations.Complexity.MachineExpanderFamily + +namespace MinUncutGames.Foundations.Complexity.MachineExpanderRow + +open Turing +open PCP.ExpanderTables PCP.ExpanderRowControl PCP.AlphabetTable + +def emitSteps (n : Nat) : Nat := 3 * (n + 1) + 6 + +theorem affinePlan_bits {σ : Type} {bound : Nat} (coefficient : Nat) + (offset : σ → Fin bound) (n : Nat) (ambient : σ) : + Emitter.prefixBits (affinePlan coefficient offset) (fun _ : Fin 1 => n) ambient 3 = + encodeWord (coefficient * n + (offset ambient).val) := by + change Emitter.prefixBits + (Emitter.listCommands (Emitter.affineCommands [((0 : Fin 1), coefficient)] offset)) + (fun _ : Fin 1 => n) ambient + (Emitter.affineCommands [((0 : Fin 1), coefficient)] offset).length = _ + rw [Emitter.bits_listCommands, Emitter.affineCommands_bits] + simp [Emitter.affineValue] + +theorem affinePlan_steps {σ : Type} {bound : Nat} (coefficient : Nat) + (offset : σ → Fin bound) (n : Nat) : + Emitter.prefixSteps (affinePlan coefficient offset) (fun _ : Fin 1 => n) 3 + 1 = + emitSteps n := by + simp [affinePlan, Emitter.prefixSteps, Emitter.commandAt, Emitter.listCommands, + Emitter.affineCommands, Emitter.commandSteps, emitSteps] + +def emittedWord {K : Type} [DecidableEq K] + (target : K) (base : K → List Bool) (value : Nat) : K → List Bool := + Function.update base target ((encodeWord value).reverse ++ base target) + +@[simp] theorem emittedWord_target {K : Type} [DecidableEq K] + (target : K) (base : K → List Bool) (value : Nat) : + emittedWord target base value target = (encodeWord value).reverse ++ base target := by + simp [emittedWord] + +theorem emittedWord_other {K : Type} [DecidableEq K] + (target : K) (base : K → List Bool) (value : Nat) + (tape : K) (different : tape ≠ target) : + emittedWord target base value tape = base tape := by + simp [emittedWord, different] + +variable {ρ : Type} [Fintype ρ] {d : Nat} + +@[simp] theorem program_firstEmit (positive : 0 < d) (H : Table (cloudSize d) d) + (label : Emitter.Label 3 (degree d)) : + program (ρ := ρ) positive H (.firstEmit label) = + Emitter.statement (firstPlan ρ d) (fun _ : Fin 1 => Tape.inputVertex) + .emitScratch .queryReverse Label.firstEmit (some Label.firstReverse) label := rfl + +@[simp] theorem program_secondEmit (positive : 0 < d) (H : Table (cloudSize d) d) + (label : Emitter.Label 3 (degree d)) : + program (ρ := ρ) positive H (.secondEmit label) = + Emitter.statement (secondPlan ρ d) (fun _ : Fin 1 => Tape.quotientFirst) + .emitScratch .queryReverse Label.secondEmit (some Label.secondReverse) label := rfl + +@[simp] theorem program_outputEmit (positive : 0 < d) (H : Table (cloudSize d) d) + (label : Emitter.Label 3 (rowFactor d)) : + program (ρ := ρ) positive H (.outputEmit label) = + Emitter.statement (outputPlan ρ d) (fun _ : Fin 1 => Tape.quotientSecond) + .emitScratch .output Label.outputEmit (some (Label.cleanup 0)) label := rfl + +section Embedded + +variable {K Λ : Type} [DecidableEq K] + +theorem firstEmitTraceAt (positive : 0 < d) (H : Table (cloudSize d) d) + (ports : Tape → K) (portsInjective : Function.Injective ports) + (labels : Label d → Λ) (exit : Option Λ) + (target : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State ρ d)) + (atLabels : ∀ l, target (labels l) = statement positive H ports labels exit l) + (n : Nat) (base : K → List Bool) + (source : base (ports .inputVertex) = encodeWord n) + (scratch : base (ports .emitScratch) = []) + (ambient : Ambient ρ d × Fin (degree d)) : + (MachineComposition.advance (TM2.step target))^[emitSteps n] + (some ⟨some (labels (.firstEmit (Emitter.labelAt 3 _ 0 .entry))), + ((ambient, ()), none), base⟩) = + some ⟨some (labels .firstReverse), ((ambient, ()), none), + emittedWord (ports .queryReverse) base (firstAddress n ambient.1.2)⟩ := by + have code : ∀ l, target (labels (.firstEmit l)) = + Emitter.statement (firstPlan ρ d) (fun _ : Fin 1 => ports .inputVertex) + (ports .emitScratch) (ports .queryReverse) (fun k => labels (.firstEmit k)) + (some (labels .firstReverse)) l := by + intro l + rw [atLabels] + rfl + have run := Emitter.planTrace (firstPlan ρ d) (fun _ : Fin 1 => ports .inputVertex) + (ports .emitScratch) (ports .queryReverse) + (by intro i h; have h' := portsInjective h; cases h') + (by intro i h; have h' := portsInjective h; cases h') + (by intro h; have h' := portsInjective h; cases h') + (fun k => labels (.firstEmit k)) (some (labels .firstReverse)) target code + (fun _ : Fin 1 => n) base (fun _ => source) scratch ambient + simpa only [firstPlan, affinePlan_steps, affinePlan_bits, Emitter.resultTapes, + emittedWord, firstAddress] using run + +theorem secondEmitTraceAt (positive : 0 < d) (H : Table (cloudSize d) d) + (ports : Tape → K) (portsInjective : Function.Injective ports) + (labels : Label d → Λ) (exit : Option Λ) + (target : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State ρ d)) + (atLabels : ∀ l, target (labels l) = statement positive H ports labels exit l) + (n : Nat) (base : K → List Bool) + (source : base (ports .quotientFirst) = encodeWord n) + (scratch : base (ports .emitScratch) = []) + (ambient : Ambient ρ d × Fin (degree d)) : + (MachineComposition.advance (TM2.step target))^[emitSteps n] + (some ⟨some (labels (.secondEmit (Emitter.labelAt 3 _ 0 .entry))), + ((ambient, ()), none), base⟩) = + some ⟨some (labels .secondReverse), ((ambient, ()), none), + emittedWord (ports .queryReverse) base (secondAddress n ambient.1.2)⟩ := by + have code : ∀ l, target (labels (.secondEmit l)) = + Emitter.statement (secondPlan ρ d) (fun _ : Fin 1 => ports .quotientFirst) + (ports .emitScratch) (ports .queryReverse) (fun k => labels (.secondEmit k)) + (some (labels .secondReverse)) l := by + intro l + rw [atLabels] + rfl + have run := Emitter.planTrace (secondPlan ρ d) (fun _ : Fin 1 => ports .quotientFirst) + (ports .emitScratch) (ports .queryReverse) + (by intro i h; have h' := portsInjective h; cases h') + (by intro i h; have h' := portsInjective h; cases h') + (by intro h; have h' := portsInjective h; cases h') + (fun k => labels (.secondEmit k)) (some (labels .secondReverse)) target code + (fun _ : Fin 1 => n) base (fun _ => source) scratch ambient + simpa only [secondPlan, affinePlan_steps, affinePlan_bits, Emitter.resultTapes, + emittedWord, secondAddress] using run + +theorem outputEmitTraceAt (positive : 0 < d) (H : Table (cloudSize d) d) + (ports : Tape → K) (portsInjective : Function.Injective ports) + (labels : Label d → Λ) (exit : Option Λ) + (target : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State ρ d)) + (atLabels : ∀ l, target (labels l) = statement positive H ports labels exit l) + (n : Nat) (base : K → List Bool) + (source : base (ports .quotientSecond) = encodeWord n) + (scratch : base (ports .emitScratch) = []) + (ambient : Ambient ρ d × Fin (degree d)) : + (MachineComposition.advance (TM2.step target))^[emitSteps n] + (some ⟨some (labels (.outputEmit (Emitter.labelAt 3 _ 0 .entry))), + ((ambient, ()), none), base⟩) = + some ⟨some (labels (.cleanup 0)), ((ambient, ()), none), + emittedWord (ports .output) base (outputAddress n ambient.1.2)⟩ := by + have code : ∀ l, target (labels (.outputEmit l)) = + Emitter.statement (outputPlan ρ d) (fun _ : Fin 1 => ports .quotientSecond) + (ports .emitScratch) (ports .output) (fun k => labels (.outputEmit k)) + (some (labels (.cleanup 0))) l := by + intro l + rw [atLabels] + rfl + have run := Emitter.planTrace (outputPlan ρ d) (fun _ : Fin 1 => ports .quotientSecond) + (ports .emitScratch) (ports .output) + (by intro i h; have h' := portsInjective h; cases h') + (by intro i h; have h' := portsInjective h; cases h') + (by intro h; have h' := portsInjective h; cases h') + (fun k => labels (.outputEmit k)) (some (labels (.cleanup 0))) target code + (fun _ : Fin 1 => n) base (fun _ => source) scratch ambient + simpa only [outputPlan, affinePlan_steps, affinePlan_bits, Emitter.resultTapes, + emittedWord, outputAddress] using run + +def firstEmitInTimeAt (positive : 0 < d) (H : Table (cloudSize d) d) + (ports : Tape → K) (portsInjective : Function.Injective ports) + (labels : Label d → Λ) (exit : Option Λ) + (target : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State ρ d)) + (atLabels : ∀ l, target (labels l) = statement positive H ports labels exit l) + (n : Nat) (base : K → List Bool) + (source : base (ports .inputVertex) = encodeWord n) + (scratch : base (ports .emitScratch) = []) + (ambient : Ambient ρ d × Fin (degree d)) : + StateTransition.EvalsToInTime (TM2.step target) + ⟨some (labels (.firstEmit (Emitter.labelAt 3 _ 0 .entry))), ((ambient, ()), none), base⟩ + (some ⟨some (labels .firstReverse), ((ambient, ()), none), + emittedWord (ports .queryReverse) base (firstAddress n ambient.1.2)⟩) (emitSteps n) where + steps := emitSteps n + evals_in_steps := firstEmitTraceAt positive H ports portsInjective labels exit target atLabels + n base source scratch ambient + steps_le_m := Nat.le_refl _ + +def secondEmitInTimeAt (positive : 0 < d) (H : Table (cloudSize d) d) + (ports : Tape → K) (portsInjective : Function.Injective ports) + (labels : Label d → Λ) (exit : Option Λ) + (target : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State ρ d)) + (atLabels : ∀ l, target (labels l) = statement positive H ports labels exit l) + (n : Nat) (base : K → List Bool) + (source : base (ports .quotientFirst) = encodeWord n) + (scratch : base (ports .emitScratch) = []) + (ambient : Ambient ρ d × Fin (degree d)) : + StateTransition.EvalsToInTime (TM2.step target) + ⟨some (labels (.secondEmit (Emitter.labelAt 3 _ 0 .entry))), ((ambient, ()), none), base⟩ + (some ⟨some (labels .secondReverse), ((ambient, ()), none), + emittedWord (ports .queryReverse) base (secondAddress n ambient.1.2)⟩) (emitSteps n) where + steps := emitSteps n + evals_in_steps := secondEmitTraceAt positive H ports portsInjective labels exit target atLabels + n base source scratch ambient + steps_le_m := Nat.le_refl _ + +def outputEmitInTimeAt (positive : 0 < d) (H : Table (cloudSize d) d) + (ports : Tape → K) (portsInjective : Function.Injective ports) + (labels : Label d → Λ) (exit : Option Λ) + (target : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State ρ d)) + (atLabels : ∀ l, target (labels l) = statement positive H ports labels exit l) + (n : Nat) (base : K → List Bool) + (source : base (ports .quotientSecond) = encodeWord n) + (scratch : base (ports .emitScratch) = []) + (ambient : Ambient ρ d × Fin (degree d)) : + StateTransition.EvalsToInTime (TM2.step target) + ⟨some (labels (.outputEmit (Emitter.labelAt 3 _ 0 .entry))), ((ambient, ()), none), base⟩ + (some ⟨some (labels (.cleanup 0)), ((ambient, ()), none), + emittedWord (ports .output) base (outputAddress n ambient.1.2)⟩) (emitSteps n) where + steps := emitSteps n + evals_in_steps := outputEmitTraceAt positive H ports portsInjective labels exit target atLabels + n base source scratch ambient + steps_le_m := Nat.le_refl _ + +end Embedded + +theorem firstEmitTrace (positive : 0 < d) (H : Table (cloudSize d) d) + (n : Nat) (base : Tape → List Bool) + (source : base .inputVertex = encodeWord n) (scratch : base .emitScratch = []) + (ambient : Ambient ρ d × Fin (degree d)) : + (MachineComposition.advance (TM2.step (program positive H)))^[emitSteps n] + (some ⟨some (.firstEmit (Emitter.labelAt 3 _ 0 .entry)), + ((ambient, ()), none), base⟩) = + some ⟨some .firstReverse, ((ambient, ()), none), + emittedWord .queryReverse base (firstAddress n ambient.1.2)⟩ := by + exact firstEmitTraceAt positive H id Function.injective_id id none (program positive H) + (fun _ => rfl) n base source scratch ambient + +theorem secondEmitTrace (positive : 0 < d) (H : Table (cloudSize d) d) + (n : Nat) (base : Tape → List Bool) + (source : base .quotientFirst = encodeWord n) (scratch : base .emitScratch = []) + (ambient : Ambient ρ d × Fin (degree d)) : + (MachineComposition.advance (TM2.step (program positive H)))^[emitSteps n] + (some ⟨some (.secondEmit (Emitter.labelAt 3 _ 0 .entry)), + ((ambient, ()), none), base⟩) = + some ⟨some .secondReverse, ((ambient, ()), none), + emittedWord .queryReverse base (secondAddress n ambient.1.2)⟩ := by + exact secondEmitTraceAt positive H id Function.injective_id id none (program positive H) + (fun _ => rfl) n base source scratch ambient + +theorem outputEmitTrace (positive : 0 < d) (H : Table (cloudSize d) d) + (n : Nat) (base : Tape → List Bool) + (source : base .quotientSecond = encodeWord n) (scratch : base .emitScratch = []) + (ambient : Ambient ρ d × Fin (degree d)) : + (MachineComposition.advance (TM2.step (program positive H)))^[emitSteps n] + (some ⟨some (.outputEmit (Emitter.labelAt 3 _ 0 .entry)), + ((ambient, ()), none), base⟩) = + some ⟨some (.cleanup 0), ((ambient, ()), none), + emittedWord .output base (outputAddress n ambient.1.2)⟩ := by + exact outputEmitTraceAt positive H id Function.injective_id id none (program positive H) + (fun _ => rfl) n base source scratch ambient + +def firstEmitInTime (positive : 0 < d) (H : Table (cloudSize d) d) + (n : Nat) (base : Tape → List Bool) + (source : base .inputVertex = encodeWord n) (scratch : base .emitScratch = []) + (ambient : Ambient ρ d × Fin (degree d)) : + StateTransition.EvalsToInTime (TM2.step (program positive H)) + ⟨some (.firstEmit (Emitter.labelAt 3 _ 0 .entry)), ((ambient, ()), none), base⟩ + (some ⟨some .firstReverse, ((ambient, ()), none), + emittedWord .queryReverse base (firstAddress n ambient.1.2)⟩) (emitSteps n) where + steps := emitSteps n + evals_in_steps := firstEmitTrace positive H n base source scratch ambient + steps_le_m := Nat.le_refl _ + +def secondEmitInTime (positive : 0 < d) (H : Table (cloudSize d) d) + (n : Nat) (base : Tape → List Bool) + (source : base .quotientFirst = encodeWord n) (scratch : base .emitScratch = []) + (ambient : Ambient ρ d × Fin (degree d)) : + StateTransition.EvalsToInTime (TM2.step (program positive H)) + ⟨some (.secondEmit (Emitter.labelAt 3 _ 0 .entry)), ((ambient, ()), none), base⟩ + (some ⟨some .secondReverse, ((ambient, ()), none), + emittedWord .queryReverse base (secondAddress n ambient.1.2)⟩) (emitSteps n) where + steps := emitSteps n + evals_in_steps := secondEmitTrace positive H n base source scratch ambient + steps_le_m := Nat.le_refl _ + +def outputEmitInTime (positive : 0 < d) (H : Table (cloudSize d) d) + (n : Nat) (base : Tape → List Bool) + (source : base .quotientSecond = encodeWord n) (scratch : base .emitScratch = []) + (ambient : Ambient ρ d × Fin (degree d)) : + StateTransition.EvalsToInTime (TM2.step (program positive H)) + ⟨some (.outputEmit (Emitter.labelAt 3 _ 0 .entry)), ((ambient, ()), none), base⟩ + (some ⟨some (.cleanup 0), ((ambient, ()), none), + emittedWord .output base (outputAddress n ambient.1.2)⟩) (emitSteps n) where + steps := emitSteps n + evals_in_steps := outputEmitTrace positive H n base source scratch ambient + steps_le_m := Nat.le_refl _ + +open Turing +open PCP.ExpanderTables PCP.ExpanderRowControl PCP.ExpanderTableWords +open MachineComposition + +def lookupPhaseLabel {d : Nat} (second : Bool) + (l : MachinePreservingLookupClean.Label) : Label d := + if second then .secondLookup l else .firstLookup l + +def scanPhaseLabel {d : Nat} (second : Bool) : Label d := + if second then .secondScan else .firstScan + +def reversePhaseLabel {d : Nat} (second : Bool) : Label d := + if second then .secondReverse else .firstReverse + +def lookupPhasePort {d : Nat} (second : Bool) (control : Control d) : Fin (degree d) := + if second then secondOffset control else firstOffset control + +def lookupPhaseAddress {d : Nat} (second : Bool) (vertex : Nat) (control : Control d) : Nat := + if second then secondAddress vertex control else firstAddress vertex control + +theorem lookupPhaseAddress_eq_rowIndex {v d : Nat} (second : Bool) + (vertex : Fin v) (control : Control d) : + lookupPhaseAddress second vertex.val control = + (rowIndex v (degree d) (vertex, lookupPhasePort second control)).val := by + cases second + · exact firstAddress_eq_rowIndex vertex control + · exact secondAddress_eq_rowIndex vertex control + +theorem lookupTape_injective : Function.Injective lookupTape := by decide + +variable {K Λ ρ : Type} [DecidableEq K] [Fintype ρ] + +def lookupResultTapes (ports : Tape → K) (base : K → List Bool) + (value : Nat) (indexSuffix : List Bool) : K → List Bool := + MachinePreservingLookup.initialTapes (ports ∘ lookupTape) base 0 indexSuffix [] + (encodeWord value ++ base (ports .lookupOutput)) + +theorem lookupResultTapes_index (ports : Tape → K) (distinct : Function.Injective ports) + (base : K → List Bool) (value : Nat) (indexSuffix : List Bool) : + lookupResultTapes ports base value indexSuffix (ports .queryIndex) = + encodeWord 0 ++ indexSuffix := by + apply MachineLookup.tapes_index + · exact fun h => (by decide : Tape.queryIndex ≠ .lookupWork) (distinct h) + · exact fun h => (by decide : Tape.queryIndex ≠ .lookupOutput) (distinct h) + +theorem lookupResultTapes_work (ports : Tape → K) (distinct : Function.Injective ports) + (base : K → List Bool) (value : Nat) (indexSuffix : List Bool) : + lookupResultTapes ports base value indexSuffix (ports .lookupWork) = [] := by + apply MachineLookup.tapes_source + exact fun h => (by decide : Tape.lookupWork ≠ .lookupOutput) (distinct h) + +theorem lookupResultTapes_output (ports : Tape → K) + (base : K → List Bool) (value : Nat) (indexSuffix : List Bool) : + lookupResultTapes ports base value indexSuffix (ports .lookupOutput) = + encodeWord value ++ base (ports .lookupOutput) := by + apply MachineLookup.tapes_destination + +theorem lookupResultTapes_other (ports : Tape → K) (base : K → List Bool) + (value : Nat) (indexSuffix : List Bool) (p : K) + (hi : p ≠ ports .queryIndex) (hw : p ≠ ports .lookupWork) + (ho : p ≠ ports .lookupOutput) : + lookupResultTapes ports base value indexSuffix p = base p := by + exact MachineLookup.tapes_other _ _ _ p hi hw ho _ _ _ _ + +theorem lookupResultTapes_table (ports : Tape → K) (distinct : Function.Injective ports) + (base : K → List Bool) (value : Nat) (indexSuffix : List Bool) : + lookupResultTapes ports base value indexSuffix (ports .table) = base (ports .table) := by + apply lookupResultTapes_other + all_goals intro h; have := distinct h; cases this + +theorem lookupResultTapes_restore (ports : Tape → K) (distinct : Function.Injective ports) + (base : K → List Bool) (value : Nat) (indexSuffix : List Bool) : + lookupResultTapes ports base value indexSuffix (ports .lookupRestore) = + base (ports .lookupRestore) := by + apply lookupResultTapes_other + all_goals intro h; have := distinct h; cases this + +section Lookup + +variable {v d : Nat} (second : Bool) (positive : 0 < d) + (H : Table (cloudSize d) d) (ports : Tape → K) + (distinct : Function.Injective ports) (labels : Label d → Λ) (exit : Option Λ) + (target : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State ρ d)) + (code : ∀ l, target (labels l) = statement positive H ports labels exit l) + (base : K → List Bool) (G : Table v (degree d)) + (tableWord : base (ports .table) = encodeWords (rotationWords G)) + (scratchEmpty : base (ports .lookupRestore) = []) + (x : Fin v × Fin (degree d)) (indexSuffix : List Bool) + (counterWord : base (ports .queryIndex) = + encodeWord (rowIndex v (degree d) x).val ++ indexSuffix) + (workEmpty : base (ports .lookupWork) = []) + (ambient : (Ambient ρ d × Fin (degree d)) × Unit) (register : Option Bool) + +include positive H distinct exit code tableWord scratchEmpty counterWord workEmpty + +theorem lookupPhaseTrace : + (advance (TM2.step target))^[MachinePreservingLookupClean.steps + (rotationWords G) (rowIndex v (degree d) x).val] + (some ⟨some (labels (lookupPhaseLabel second (.run .copyFirst))), + (ambient, register), base⟩) = + some ⟨some (labels (scanPhaseLabel second)), (ambient, none), + lookupResultTapes ports base (reverseIndex G (rowIndex v (degree d) x)).val + indexSuffix⟩ := by + apply MachinePreservingLookupClean.traceAt_fromTapes (ports ∘ lookupTape) + (distinct.comp lookupTape_injective) + (fun l => labels (lookupPhaseLabel second l)) (some (labels (scanPhaseLabel second))) + target + · intro l + cases second + · exact code (.firstLookup l) + · exact code (.secondLookup l) + · exact tableWord + · exact scratchEmpty + · exact rotationWords_getElem? G (rowIndex v (degree d) x) + · exact counterWord + · exact workEmpty + +def lookupPhaseInTime : + StateTransition.EvalsToInTime (TM2.step target) + ⟨some (labels (lookupPhaseLabel second (.run .copyFirst))), + (ambient, register), base⟩ + (some ⟨some (labels (scanPhaseLabel second)), (ambient, none), + lookupResultTapes ports base (reverseIndex G (rowIndex v (degree d) x)).val + indexSuffix⟩) + (6 * (encodeWords (rotationWords G)).length + 4) where + steps := MachinePreservingLookupClean.steps (rotationWords G) (rowIndex v (degree d) x).val + evals_in_steps := lookupPhaseTrace second positive H ports distinct labels exit target code + base G tableWord scratchEmpty x indexSuffix counterWord workEmpty ambient register + steps_le_m := MachinePreservingLookupClean.steps_le (rotationWords G) _ _ + (rotationWords_getElem? G (rowIndex v (degree d) x)) + +end Lookup + +section Reverse + +variable {d : Nat} (second : Bool) (positive : 0 < d) + (H : Table (cloudSize d) d) (ports : Tape → K) + (distinct : Function.Injective ports) (labels : Label d → Λ) (exit : Option Λ) + (target : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State ρ d)) + (code : ∀ l, target (labels l) = statement positive H ports labels exit l) + (base : K → List Bool) + (ambient : (Ambient ρ d × Fin (degree d)) × Unit) (register : Option Bool) + +include positive H distinct exit code + +theorem reversePhaseTrace : + (advance (TM2.step target))^[(base (ports .queryReverse)).length + 1] + (some ⟨some (labels (reversePhaseLabel second)), (ambient, register), base⟩) = + some ⟨some (labels (lookupPhaseLabel second (.run .copyFirst))), (ambient, none), + Reduction.MachineTransfer.tapesAt (ports .queryReverse) (ports .queryIndex) base [] + ((base (ports .queryReverse)).reverse ++ base (ports .queryIndex))⟩ := by + have h := Reduction.MachineTransfer.transferAt_fromTapes + (ports .queryReverse) (ports .queryIndex) + (fun h => (by decide : Tape.queryReverse ≠ .queryIndex) (distinct h)) + id false (labels (reversePhaseLabel second)) + (some (labels (lookupPhaseLabel second (.run .copyFirst)))) target + (by cases second <;> exact code _) base ambient register + unfold Reduction.MachineTransfer.nextAt at h + unfold advance + simpa only [List.map_id] using h + +def reversePhaseInTime : + StateTransition.EvalsToInTime (TM2.step target) + ⟨some (labels (reversePhaseLabel second)), (ambient, register), base⟩ + (some ⟨some (labels (lookupPhaseLabel second (.run .copyFirst))), (ambient, none), + Reduction.MachineTransfer.tapesAt (ports .queryReverse) (ports .queryIndex) base [] + ((base (ports .queryReverse)).reverse ++ base (ports .queryIndex))⟩) + ((base (ports .queryReverse)).length + 1) where + steps := (base (ports .queryReverse)).length + 1 + evals_in_steps := reversePhaseTrace second positive H ports distinct labels exit target code + base ambient register + steps_le_m := Nat.le_refl _ + +theorem reversePhaseTrace_unary (index : Nat) (suffix : List Bool) + (queryWord : base (ports .queryReverse) = (encodeWord index).reverse) + (indexWord : base (ports .queryIndex) = suffix) : + (advance (TM2.step target))^[index + 2] + (some ⟨some (labels (reversePhaseLabel second)), (ambient, register), base⟩) = + some ⟨some (labels (lookupPhaseLabel second (.run .copyFirst))), (ambient, none), + Reduction.MachineTransfer.tapesAt (ports .queryReverse) (ports .queryIndex) base [] + (encodeWord index ++ suffix)⟩ := by + have h := reversePhaseTrace second positive H ports distinct labels exit target code + base ambient register + simpa only [queryWord, indexWord, List.length_reverse, encodeWord_length, + List.reverse_reverse, Nat.add_assoc] using h + +end Reverse + +open Turing MachineComposition +open PCP.ExpanderTables PCP.ExpanderRowControl + +@[simp] private theorem dirtyTape_zero : dirtyTape 0 = .queryIndex := rfl +@[simp] private theorem dirtyTape_one : dirtyTape 1 = .lookupOutput := rfl +@[simp] private theorem dirtyTape_two : dirtyTape 2 = .quotientFirst := rfl +@[simp] private theorem dirtyTape_three : dirtyTape 3 = .quotientSecond := rfl +@[simp] private theorem dirtyTape_four : dirtyTape 4 = .remainderFirst := rfl +@[simp] private theorem dirtyTape_five : dirtyTape 5 = .remainderSecond := rfl + +variable {K Λ ρ : Type} [DecidableEq K] + +def cleanupTapes (ports : Tape → K) (base : K → List Bool) : K → List Bool := + Function.update + (Function.update + (Function.update + (Function.update + (Function.update + (Function.update base (ports .queryIndex) []) + (ports .lookupOutput) []) + (ports .quotientFirst) []) + (ports .quotientSecond) []) + (ports .remainderFirst) []) + (ports .remainderSecond) [] + +def cleanupSteps (ports : Tape → K) (base : K → List Bool) : Nat := + ((base (ports .queryIndex)).length + 1) + + ((base (ports .lookupOutput)).length + 1) + + ((base (ports .quotientFirst)).length + 1) + + ((base (ports .quotientSecond)).length + 1) + + ((base (ports .remainderFirst)).length + 1) + + ((base (ports .remainderSecond)).length + 1) + +omit [DecidableEq K] in +theorem cleanupSteps_eq_sum (ports : Tape → K) (base : K → List Bool) : + cleanupSteps ports base = ∑ i : Fin 6, ((base (ports (dirtyTape i))).length + 1) := by + simp [cleanupSteps, Fin.sum_univ_succ, Nat.add_assoc] + +@[simp] theorem cleanupTapes_dirty (ports : Tape → K) (distinct : Function.Injective ports) + (base : K → List Bool) (i : Fin 6) : + cleanupTapes ports base (ports (dirtyTape i)) = [] := by + fin_cases i <;> + simp [cleanupTapes, distinct.eq_iff] + +theorem cleanupTapes_other (ports : Tape → K) (base : K → List Bool) (k : K) + (outside : ∀ i : Fin 6, k ≠ ports (dirtyTape i)) : + cleanupTapes ports base k = base k := by + have h0 := outside 0 + have h1 := outside 1 + have h2 := outside 2 + have h3 := outside 3 + have h4 := outside 4 + have h5 := outside 5 + change k ≠ ports .queryIndex at h0 + change k ≠ ports .lookupOutput at h1 + change k ≠ ports .quotientFirst at h2 + change k ≠ ports .quotientSecond at h3 + change k ≠ ports .remainderFirst at h4 + change k ≠ ports .remainderSecond at h5 + simp [cleanupTapes, h0, h1, h2, h3, h4, h5] + +@[simp] theorem cleanupTapes_table (ports : Tape → K) (distinct : Function.Injective ports) + (base : K → List Bool) : + cleanupTapes ports base (ports .table) = base (ports .table) := by + simp [cleanupTapes, distinct.eq_iff] + +@[simp] theorem cleanupTapes_inputVertex (ports : Tape → K) + (distinct : Function.Injective ports) (base : K → List Bool) : + cleanupTapes ports base (ports .inputVertex) = base (ports .inputVertex) := by + simp [cleanupTapes, distinct.eq_iff] + +@[simp] theorem cleanupTapes_output (ports : Tape → K) (distinct : Function.Injective ports) + (base : K → List Bool) : + cleanupTapes ports base (ports .output) = base (ports .output) := by + simp [cleanupTapes, distinct.eq_iff] + +theorem join_trace {A : Type*} {f : A → A} {m n : Nat} {a b c : A} + (first : f^[m] a = b) (second : f^[n] b = c) : f^[m + n] a = c := by + rw [Nat.add_comm m n, Function.iterate_add_apply, first, second] + +variable [Fintype ρ] {d : Nat} + +theorem cleanupOneTraceAt (positive : 0 < d) (H : Table (cloudSize d) d) + (ports : Tape → K) (labels : Label d → Λ) (exit : Option Λ) + (target : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State ρ d)) + (code : ∀ label, target (labels label) = statement positive H ports labels exit label) + (i : Fin 6) (base : K → List Bool) (state : State ρ d) : + (advance (TM2.step target))^[((base (ports (dirtyTape i))).length + 1)] + (some ⟨some (labels (.cleanup i)), state, base⟩) = + some ⟨some (if hi : i.val + 1 < 6 then labels (.cleanup ⟨i.val + 1, hi⟩) + else labels .done), + (state.1, none), Function.update base (ports (dirtyTape i)) []⟩ := by + have run := MachineDrain.drainTrace (ports (dirtyTape i)) (labels (.cleanup i)) + (some (if hi : i.val + 1 < 6 then labels (.cleanup ⟨i.val + 1, hi⟩) + else labels .done)) target + (by simpa only [statement] using code (.cleanup i)) + base (base (ports (dirtyTape i))) state.1 state.2 + simpa only [Function.update_eq_self] using run + +theorem cleanupTraceAt (positive : 0 < d) (H : Table (cloudSize d) d) + (ports : Tape → K) (distinct : Function.Injective ports) + (labels : Label d → Λ) (exit : Option Λ) + (target : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State ρ d)) + (code : ∀ label, target (labels label) = statement positive H ports labels exit label) + (base : K → List Bool) (state : State ρ d) : + (advance (TM2.step target))^[cleanupSteps ports base] + (some ⟨some (labels (.cleanup 0)), state, base⟩) = + some ⟨some (labels .done), (state.1, none), cleanupTapes ports base⟩ := by + let t1 := Function.update base (ports .queryIndex) [] + let t2 := Function.update t1 (ports .lookupOutput) [] + let t3 := Function.update t2 (ports .quotientFirst) [] + let t4 := Function.update t3 (ports .quotientSecond) [] + let t5 := Function.update t4 (ports .remainderFirst) [] + have h0 := cleanupOneTraceAt positive H ports labels exit target code 0 base state + have h1 := cleanupOneTraceAt positive H ports labels exit target code 1 t1 (state.1, none) + have h2 := cleanupOneTraceAt positive H ports labels exit target code 2 t2 (state.1, none) + have h3 := cleanupOneTraceAt positive H ports labels exit target code 3 t3 (state.1, none) + have h4 := cleanupOneTraceAt positive H ports labels exit target code 4 t4 (state.1, none) + have h5 := cleanupOneTraceAt positive H ports labels exit target code 5 t5 (state.1, none) + simp [t1, t2, t3, t4, t5, distinct.eq_iff, + -Function.iterate_succ] at h0 h1 h2 h3 h4 h5 + have finished := join_trace (join_trace (join_trace (join_trace (join_trace h0 h1) h2) h3) h4) h5 + simpa only [cleanupSteps, cleanupTapes] using finished + +theorem doneStepAt (positive : 0 < d) (H : Table (cloudSize d) d) + (ports : Tape → K) (labels : Label d → Λ) (exit : Option Λ) + (target : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State ρ d)) + (code : ∀ label, target (labels label) = statement positive H ports labels exit label) + (base : K → List Bool) (state : State ρ d) : + TM2.step target ⟨some (labels .done), state, base⟩ = some ⟨exit, state, base⟩ := by + change some (TM2.stepAux (target (labels .done)) state base) = _ + rw [code] + cases exit <;> rfl + +theorem cleanupExitTraceAt (positive : 0 < d) (H : Table (cloudSize d) d) + (ports : Tape → K) (distinct : Function.Injective ports) + (labels : Label d → Λ) (exit : Option Λ) + (target : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State ρ d)) + (code : ∀ label, target (labels label) = statement positive H ports labels exit label) + (base : K → List Bool) (state : State ρ d) : + (advance (TM2.step target))^[cleanupSteps ports base + 1] + (some ⟨some (labels (.cleanup 0)), state, base⟩) = + some ⟨exit, (state.1, none), cleanupTapes ports base⟩ := by + have cleaned := cleanupTraceAt positive H ports distinct labels exit target code base state + have done : (advance (TM2.step target))^[1] + (some ⟨some (labels .done), (state.1, none), cleanupTapes ports base⟩) = + some ⟨exit, (state.1, none), cleanupTapes ports base⟩ := by + simpa only [Function.iterate_one, advance_some] using + doneStepAt positive H ports labels exit target code (cleanupTapes ports base) (state.1, none) + exact join_trace cleaned done + +def initializedTapes (ports : Tape → K) (base : K → List Bool) : K → List Bool := + Function.update + (Function.update + (Function.update + (Function.update base (ports .quotientFirst) (false :: base (ports .quotientFirst))) + (ports .quotientSecond) (false :: base (ports .quotientSecond))) + (ports .remainderFirst) (false :: base (ports .remainderFirst))) + (ports .remainderSecond) (false :: base (ports .remainderSecond)) + +theorem initializeStepAt (positive : 0 < d) (H : Table (cloudSize d) d) + (ports : Tape → K) (distinct : Function.Injective ports) + (labels : Label d → Λ) (exit : Option Λ) + (target : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State ρ d)) + (code : ∀ label, target (labels label) = statement positive H ports labels exit label) + (base : K → List Bool) (state : State ρ d) : + TM2.step target ⟨some (labels .initialize), state, base⟩ = + some ⟨some (labels (.firstEmit (PCP.AlphabetTable.Emitter.labelAt 3 _ 0 .entry))), + (state.1, none), initializedTapes ports base⟩ := by + change some (TM2.stepAux (target (labels .initialize)) state base) = _ + rw [code] + simp [statement, TM2.stepAux, initializedTapes, distinct.eq_iff] + +def clearedQueryTapes (ports : Tape → K) (base : K → List Bool) : K → List Bool := + Function.update + (Function.update base (ports .queryIndex) (base (ports .queryIndex)).tail) + (ports .lookupOutput) (base (ports .lookupOutput)).tail + +theorem clearQueryStepAt (positive : 0 < d) (H : Table (cloudSize d) d) + (ports : Tape → K) (distinct : Function.Injective ports) + (labels : Label d → Λ) (exit : Option Λ) + (target : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State ρ d)) + (code : ∀ label, target (labels label) = statement positive H ports labels exit label) + (base : K → List Bool) (state : State ρ d) : + TM2.step target ⟨some (labels .clearQuery), state, base⟩ = + some ⟨some (labels (.secondEmit (PCP.AlphabetTable.Emitter.labelAt 3 _ 0 .entry))), + state, clearedQueryTapes ports base⟩ := by + change some (TM2.stepAux (target (labels .clearQuery)) state base) = _ + rw [code] + simp [statement, TM2.stepAux, clearedQueryTapes, distinct.eq_iff] + +end MinUncutGames.Foundations.Complexity.MachineExpanderRow + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineExpanderFamilyCycle.lean b/lean/OAI/Computability/MinUncut/Machines/MachineExpanderFamilyCycle.lean new file mode 100644 index 0000000000000000000000000000000000000000..01db50f2f7f6e8841414921a8323bfc97d700a9e --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineExpanderFamilyCycle.lean @@ -0,0 +1,751 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineExpanderTableRows + +namespace OAI + +namespace MinUncutGames.Foundations.Complexity.MachineExpanderFamily + +open Turing +open PCP.ExpanderTables PCP.ExpanderRowControl PCP.ExpanderTableWords +open MachineExpanderFamilyBounds + +theorem installed_returnFrame (remaining current : Nat) (oldWord newWord suffix : List Bool) : + fromBoolTapes (installedTapes (toBoolTapes (returnFrame remaining current oldWord newWord suffix)) + newWord) = installedFrame remaining current newWord suffix := by + rw [returnFrame_eq_cycleTapes, toBool_cycleTapes] + funext tape + rcases tape with tape | tape + · rcases tape with row | extra + · cases row <;> rfl + · cases extra <;> rfl + · cases tape <;> rfl + +theorem cleaned_multipliedFrame (d remaining current : Nat) (newWord suffix : List Bool) : + fromBoolTapes (cleanedCounterTapes + (toBoolTapes (multipliedFrame d remaining current newWord suffix))) = + boundaryTapes remaining (current * cloudSize d) newWord suffix := by + rw [boundaryTapes_eq_cycleTapes] + unfold multipliedFrame + rw [toBool_cycleTapes] + have multiply : cloudSize d * current = current * cloudSize d := Nat.mul_comm _ _ + rw [multiply] + funext tape + rcases tape with tape | tape + · rcases tape with row | extra + · cases row <;> rfl + · cases extra <;> rfl + · cases tape <;> rfl + +structure ResizeRun {v d : Nat} {ρ : Type} [Fintype ρ] + (positive : 0 < d) (H : Table (cloudSize d) d) (growth : 1 < cloudSize d) + (G : Table v (degree d)) (remaining : Nat) (state : State ρ d) (suffix : List Bool) where + finalState : State ρ d + caller_preserved : caller finalState = caller state + execution : StateTransition.EvalsToInTime (TM2.step (program positive H growth)) + ⟨some (.inr (.affine .copyCount .seed)), state, + boundaryTapes remaining v (MachineExpanderTable.oldTableWord G) suffix⟩ + (some ⟨some (.inr .levelGuard), finalState, + boundaryTapes remaining (v * cloudSize d) + (encodeWords (rotationWords (step G H))) suffix⟩) + (resizeCost G H) + +noncomputable def resizeInTime {v d : Nat} {ρ : Type} [Fintype ρ] + (positive : 0 < d) (H : Table (cloudSize d) d) (growth : 1 < cloudSize d) + (G : Table v (degree d)) (remaining : Nat) (state : State ρ d) (suffix : List Bool) : + ResizeRun positive H growth G remaining state suffix := by + let oldWord := MachineExpanderTable.oldTableWord G + let newWord := encodeWords (rotationWords (step G H)) + have copy := copyCountInTime positive H growth + (boundaryTapes remaining v oldWord suffix) v rfl rfl rfl state + rw [copyFrame_eq_update] at copy + let called := MachineExpanderTable.tableInTime positive G H (clearRegister state).1 [] + let returned : State ρ d := (called.finalState, ()) + have eta : ((clearRegister state).1, ()) = clearRegister state := by + rcases state with ⟨state, extra⟩ + cases extra + rfl + have call : StateTransition.EvalsToInTime (TM2.step (program positive H growth)) + ⟨some (.inl (.inr .initialize)), clearRegister state, + copyFrame remaining v oldWord suffix⟩ + (some ⟨some (.inr .clearOldTable), returned, + returnFrame remaining v oldWord newWord suffix⟩) + ((MachineExpanderTable.timePolynomial d).eval oldWord.length) := by + simpa only [MachineEmbedding.configuration, MachineEmbedding.label, tableReturn, eta, + copyFrame, returnFrame, oldWord, newWord, returned] using + tableExecution positive H growth (extraFrame remaining v suffix) called.execution + have install := installTableInTime positive H growth + (returnFrame remaining v oldWord newWord suffix) newWord + (by rw [returnFrame_eq_cycleTapes, toBool_cycleTapes]; rfl) + (by rw [returnFrame_eq_cycleTapes, toBool_cycleTapes]; rfl) returned + rw [installed_returnFrame] at install + have installRun : StateTransition.EvalsToInTime (TM2.step (program positive H growth)) + ⟨some (.inr .clearOldTable), returned, returnFrame remaining v oldWord newWord suffix⟩ + (some ⟨some (.inr (.affine .multiplySize .seed)), clearRegister returned, + installedFrame remaining v newWord suffix⟩) + (oldWord.length + 2 * newWord.length + (v + 1) + 4) := by + simpa only [returnFrame_eq_cycleTapes, toBool_cycleTapes, cycleWords, tableTape, + encodeWord_length] using install + have multiply := multiplySizeInTime positive H growth + (installedFrame remaining v newWord suffix) v rfl rfl rfl (clearRegister returned) + rw [clearRegister_idempotent, multipliedFrame_eq_update] at multiply + have clean := cleanupCountersInTime positive H growth + (multipliedFrame d remaining v newWord suffix) (clearRegister returned) + rw [clearRegister_idempotent, cleaned_multipliedFrame] at clean + have cleanRun : StateTransition.EvalsToInTime (TM2.step (program positive H growth)) + ⟨some (.inr .drainInputVertex), clearRegister returned, + multipliedFrame d remaining v newWord suffix⟩ + (some ⟨some (.inr .levelGuard), clearRegister returned, + boundaryTapes remaining (v * cloudSize d) newWord suffix⟩) (v + 4) := by + simpa only [multipliedFrame, toBool_cycleTapes, cycleWords, inputVertexTape, + vertexCountTape, encodeWord_length, Nat.zero_add, Nat.add_assoc] using clean + let a := StateTransition.EvalsToInTime.trans (TM2.step (program positive H growth)) + _ _ _ _ _ copy call + let b := StateTransition.EvalsToInTime.trans (TM2.step (program positive H growth)) + _ _ _ _ _ a installRun + let c := StateTransition.EvalsToInTime.trans (TM2.step (program positive H growth)) + _ _ _ _ _ b multiply + let all := StateTransition.EvalsToInTime.trans (TM2.step (program positive H growth)) + _ _ _ _ _ c cleanRun + refine ⟨clearRegister returned, ?_, ?_⟩ + · exact (caller_clearRegister returned).trans + (called.caller_preserved.trans (caller_clearRegister state)) + · refine { toEvalsTo := all.toEvalsTo, steps_le_m := ?_ } + have bound := all.steps_le_m + unfold resizeCost + change _ ≤ (MachineExpanderTable.timePolynomial d).eval oldWord.length + + 6 * v + oldWord.length + 2 * newWord.length + 15 + omega + +open Turing +open PCP.ExpanderTables PCP.ExpanderRowControl + +variable {ρ : Type} {d : Nat} + +@[simp] theorem caller_initialState (positive : 0 < d) (H : Table (cloudSize d) d) + (ambient : ρ) : caller (initialState positive H ambient) = ambient := rfl + +@[simp] theorem caller_normalizeState (positive : 0 < d) (H : Table (cloudSize d) d) + (state : State ρ d) : caller (normalizeState positive H state) = caller state := rfl + +@[simp] theorem clearRegister_initialState (positive : 0 < d) + (H : Table (cloudSize d) d) (ambient : ρ) : + clearRegister (initialState positive H ambient) = initialState positive H ambient := rfl + +theorem boundaryTapes_update_level (remaining current next : Nat) + (word suffix : List Bool) : + Function.update (boundaryTapes remaining current word suffix) + (.inr .remainingLevel) (encodeWord next ++ suffix) = + boundaryTapes next current word suffix := by + funext tape + rcases tape with tape | extra + · rcases tape with row | extra + · cases row <;> simp [boundaryTapes, tableFrame, MachineEmbedding.tapes, Function.update] + · cases extra <;> simp [boundaryTapes, tableFrame, MachineEmbedding.tapes, Function.update] + · cases extra <;> simp [boundaryTapes, extraFrame, MachineEmbedding.tapes, Function.update] + +theorem initialTapes_initialize (level : Nat) (suffix : List Bool) : + Function.update + (Function.update (initialTapes level suffix) tableTape (initialEncoding d)) + (.inr .currentSize) (encodeWord 1) = + boundaryTapes level 1 (initialEncoding d) suffix := by + funext tape + rcases tape with tape | extra + · rcases tape with row | extra + · cases row <;> simp [initialTapes, boundaryTapes, tableFrame, + MachineEmbedding.tapes, Function.update, tableTape] + · cases extra <;> simp [initialTapes, boundaryTapes, tableFrame, + MachineEmbedding.tapes, Function.update, tableTape] + · cases extra <;> simp [initialTapes, boundaryTapes, extraFrame, + MachineEmbedding.tapes, Function.update, tableTape] + +variable [Fintype ρ] + +theorem actualStep_of_boolStep (positive : 0 < d) (H : Table (cloudSize d) d) + (growth : 1 < cloudSize d) + (start finish : TM2.Cfg BoolAlphabet (Label d) (State ρ d)) + (run : TM2.step (boolView positive H growth) start = some finish) : + TM2.step (program positive H growth) + (MachineAlphabetTransport.configuration alphabet_eq.symm start) = + some (MachineAlphabetTransport.configuration alphabet_eq.symm finish) := by + have h := MachineAlphabetTransport.step_simulation alphabet_eq.symm + (boolView positive H growth) start + rw [run] at h + simpa only [boolView, MachineAlphabetTransport.program_symm_roundtrip, + Option.map_some] using h + +theorem bool_initializeStep (positive : 0 < d) (H : Table (cloudSize d) d) + (growth : 1 < cloudSize d) (base : Tape → List Bool) (state : State ρ d) : + TM2.step (boolView positive H growth) ⟨some (.inr .initialize), state, base⟩ = + some ⟨some (.inr .levelGuard), normalizeState positive H state, + Function.update + (Function.update base tableTape (initialEncoding d ++ base (.inl (.inl .table)))) + (.inr .currentSize) (encodeWord 1 ++ base (.inr .currentSize))⟩ := by + change some (TM2.stepAux (boolView positive H growth (.inr .initialize)) state base) = _ + rw [boolView_outer] + simp only [boolOuterStatement, Reduction.MachineSubstitution.stepAux_pushWord, + List.reverse_reverse, TM2.stepAux] + rfl + +theorem bool_levelGuard_succStep (positive : 0 < d) (H : Table (cloudSize d) d) + (growth : 1 < cloudSize d) (base : Tape → List Bool) (state : State ρ d) + (remaining : Nat) (suffix : List Bool) + (counter : base (.inr .remainingLevel) = encodeWord (remaining + 1) ++ suffix) : + TM2.step (boolView positive H growth) ⟨some (.inr .levelGuard), state, base⟩ = + some ⟨some (.inr (.affine .copyCount .seed)), clearRegister state, + Function.update base (.inr .remainingLevel) (encodeWord remaining ++ suffix)⟩ := by + change some (TM2.stepAux (boolView positive H growth (.inr .levelGuard)) state base) = _ + rw [boolView_outer] + simp [boolOuterStatement, MachineControl.statement, MachineUnaryCounter.guard, + TM2.stepAux, registerStates, clearRegister, MachineExpanderTable.clearRegister, + counter, encodeWord, List.replicate_succ] + +theorem bool_levelGuard_zeroStep (positive : 0 < d) (H : Table (cloudSize d) d) + (growth : 1 < cloudSize d) (base : Tape → List Bool) (state : State ρ d) + (suffix : List Bool) + (counter : base (.inr .remainingLevel) = encodeWord 0 ++ suffix) : + TM2.step (boolView positive H growth) ⟨some (.inr .levelGuard), state, base⟩ = + some ⟨some (.inr .done), clearRegister state, base⟩ := by + change some (TM2.stepAux (boolView positive H growth (.inr .levelGuard)) state base) = _ + rw [boolView_outer] + simp [boolOuterStatement, MachineControl.statement, MachineUnaryCounter.guard, + TM2.stepAux, registerStates, clearRegister, MachineExpanderTable.clearRegister, + counter, encodeWord] + +theorem bool_doneStep (positive : 0 < d) (H : Table (cloudSize d) d) + (growth : 1 < cloudSize d) (base : Tape → List Bool) (state : State ρ d) : + TM2.step (boolView positive H growth) ⟨some (.inr .done), state, base⟩ = + some ⟨none, normalizeState positive H state, base⟩ := by + change some (TM2.stepAux (boolView positive H growth (.inr .done)) state base) = _ + rw [boolView_outer] + rfl + +theorem initializeStep (positive : 0 < d) (H : Table (cloudSize d) d) + (growth : 1 < cloudSize d) (base : ∀ tape, List (Alphabet tape)) (state : State ρ d) : + TM2.step (program positive H growth) ⟨some (.inr .initialize), state, base⟩ = + some ⟨some (.inr .levelGuard), normalizeState positive H state, + Function.update + (Function.update base tableTape (initialEncoding d ++ base (.inl (.inl .table)))) + (.inr .currentSize) (encodeWord 1 ++ base (.inr .currentSize))⟩ := by + have h := actualStep_of_boolStep positive H growth _ _ + (bool_initializeStep positive H growth (toBoolTapes base) state) + simp only [configuration_fromBool, fromBoolTapes_update, fromBool_toBool] at h + exact h + +theorem levelGuard_succStep (positive : 0 < d) (H : Table (cloudSize d) d) + (growth : 1 < cloudSize d) (base : ∀ tape, List (Alphabet tape)) (state : State ρ d) + (remaining : Nat) (suffix : List Bool) + (counter : base (.inr .remainingLevel) = encodeWord (remaining + 1) ++ suffix) : + TM2.step (program positive H growth) ⟨some (.inr .levelGuard), state, base⟩ = + some ⟨some (.inr (.affine .copyCount .seed)), clearRegister state, + Function.update base (.inr .remainingLevel) (encodeWord remaining ++ suffix)⟩ := by + have h := actualStep_of_boolStep positive H growth _ _ + (bool_levelGuard_succStep positive H growth (toBoolTapes base) state + remaining suffix counter) + simpa only [configuration_fromBool, fromBoolTapes_update, fromBool_toBool, + boolWord] using h + +theorem levelGuard_zeroStep (positive : 0 < d) (H : Table (cloudSize d) d) + (growth : 1 < cloudSize d) (base : ∀ tape, List (Alphabet tape)) (state : State ρ d) + (suffix : List Bool) + (counter : base (.inr .remainingLevel) = encodeWord 0 ++ suffix) : + TM2.step (program positive H growth) ⟨some (.inr .levelGuard), state, base⟩ = + some ⟨some (.inr .done), clearRegister state, base⟩ := by + have h := actualStep_of_boolStep positive H growth _ _ + (bool_levelGuard_zeroStep positive H growth (toBoolTapes base) state suffix counter) + simpa only [configuration_fromBool, fromBool_toBool] using h + +theorem doneStep (positive : 0 < d) (H : Table (cloudSize d) d) + (growth : 1 < cloudSize d) (base : ∀ tape, List (Alphabet tape)) (state : State ρ d) : + TM2.step (program positive H growth) ⟨some (.inr .done), state, base⟩ = + some ⟨none, normalizeState positive H state, base⟩ := by + have h := actualStep_of_boolStep positive H growth _ _ + (bool_doneStep positive H growth (toBoolTapes base) state) + simpa only [configuration_fromBool, fromBool_toBool] using h + +theorem initialize_boundaryStep (positive : 0 < d) (H : Table (cloudSize d) d) + (growth : 1 < cloudSize d) (level : Nat) (suffix : List Bool) (state : State ρ d) : + TM2.step (program positive H growth) + ⟨some (.inr .initialize), state, initialTapes level suffix⟩ = + some ⟨some (.inr .levelGuard), initialState positive H (caller state), + boundaryTapes level 1 (initialEncoding d) suffix⟩ := by + have h := initializeStep positive H growth (initialTapes level suffix) state + have ht : initialTapes level suffix (.inl (.inl .table)) = [] := rfl + have hc : initialTapes level suffix (.inr .currentSize) = [] := rfl + simp only [ht, hc, List.append_nil, normalizeState] at h + exact h.trans (congrArg + (fun tapes : ∀ tape, List (Alphabet tape) => + (some ⟨some (.inr .levelGuard), initialState positive H (caller state), tapes⟩ : + Option (TM2.Cfg Alphabet (Label d) (State ρ d)))) + (initialTapes_initialize level suffix)) + +theorem levelGuard_boundary_succStep (positive : 0 < d) (H : Table (cloudSize d) d) + (growth : 1 < cloudSize d) (remaining current : Nat) + (word suffix : List Bool) (state : State ρ d) : + TM2.step (program positive H growth) + ⟨some (.inr .levelGuard), state, boundaryTapes (remaining + 1) current word suffix⟩ = + some ⟨some (.inr (.affine .copyCount .seed)), clearRegister state, + boundaryTapes remaining current word suffix⟩ := by + simpa only [boundaryTapes_update_level] using + levelGuard_succStep positive H growth + (boundaryTapes (remaining + 1) current word suffix) state remaining suffix rfl + +theorem levelGuard_boundary_zeroStep (positive : 0 < d) (H : Table (cloudSize d) d) + (growth : 1 < cloudSize d) (current : Nat) + (word suffix : List Bool) (state : State ρ d) : + TM2.step (program positive H growth) + ⟨some (.inr .levelGuard), state, boundaryTapes 0 current word suffix⟩ = + some ⟨some (.inr .done), clearRegister state, + boundaryTapes 0 current word suffix⟩ := + levelGuard_zeroStep positive H growth + (boundaryTapes 0 current word suffix) state suffix rfl + +open Turing +open PCP.ExpanderTables PCP.ExpanderRowControl PCP.ExpanderTableWords +open MachineExpanderFamilyBounds + +noncomputable def levelLoopCost {d : Nat} (H : Table (cloudSize d) d) : Nat → Nat → Nat + | _, 0 => 1 + | start, remaining + 1 => 1 + resizeCost (family H start) H + + levelLoopCost H (start + 1) remaining + +theorem levelLoopCost_prefix {d : Nat} (H : Table (cloudSize d) d) (start remaining : Nat) : + levelLoopCost H start remaining + resizeSum H start = + resizeSum H (start + remaining) + remaining + 1 := by + induction remaining generalizing start with + | zero => simp [levelLoopCost, Nat.add_comm] + | succ remaining ih => + have h := ih (start + 1) + rw [resizeSum_succ] at h + have index : start + 1 + remaining = start + (remaining + 1) := by omega + rw [index] at h + simp only [levelLoopCost] + omega + +theorem levelLoopCost_zero_start {d : Nat} (H : Table (cloudSize d) d) (remaining : Nat) : + levelLoopCost H 0 remaining = resizeSum H remaining + remaining + 1 := by + simpa only [resizeSum_zero, Nat.add_zero, Nat.zero_add] using + levelLoopCost_prefix H 0 remaining + +def levelLoopTapes {d : Nat} (H : Table (cloudSize d) d) + (completed remaining : Nat) (suffix : List Bool) : ∀ tape, List (Alphabet tape) := + boundaryTapes remaining (vertexCount (degree d) completed) + (encodeWords (rotationWords (family H completed))) suffix + +structure LevelLoopRun {d : Nat} {ρ : Type} [Fintype ρ] + (positive : 0 < d) (H : Table (cloudSize d) d) (growth : 1 < cloudSize d) + (completed remaining : Nat) (state : State ρ d) (suffix : List Bool) where + finalState : State ρ d + caller_preserved : caller finalState = caller state + execution : StateTransition.EvalsToInTime (TM2.step (program positive H growth)) + ⟨some (.inr .levelGuard), state, levelLoopTapes H completed remaining suffix⟩ + (some ⟨some (.inr .done), finalState, familyTapes H (completed + remaining) suffix⟩) + (levelLoopCost H completed remaining) + +private def familySingleStep {S : Type*} (f : S → Option S) (a b : S) + (h : f a = some b) : StateTransition.EvalsToInTime f a (some b) 1 where + steps := 1 + evals_in_steps := by change f a = some b; exact h + steps_le_m := Nat.le_refl _ + +noncomputable def levelLoopInTime {d : Nat} {ρ : Type} [Fintype ρ] + (positive : 0 < d) (H : Table (cloudSize d) d) (growth : 1 < cloudSize d) + (completed remaining : Nat) (state : State ρ d) (suffix : List Bool) : + LevelLoopRun positive H growth completed remaining state suffix := by + induction remaining generalizing completed state with + | zero => + refine ⟨clearRegister state, caller_clearRegister state, ?_⟩ + simpa only [levelLoopCost, levelLoopTapes, familyTapes, Nat.add_zero] using + familySingleStep _ _ _ (levelGuard_boundary_zeroStep positive H growth + (vertexCount (degree d) completed) (encodeWords (rotationWords (family H completed))) + suffix state) + | succ remaining ih => + let cycle := resizeInTime positive H growth (family H completed) remaining + (clearRegister state) suffix + let rest := ih (completed + 1) cycle.finalState + let guard := familySingleStep _ _ _ (levelGuard_boundary_succStep positive H growth + remaining (vertexCount (degree d) completed) + (encodeWords (rotationWords (family H completed))) suffix state) + have cycleRun : StateTransition.EvalsToInTime (TM2.step (program positive H growth)) + ⟨some (.inr (.affine .copyCount .seed)), clearRegister state, + levelLoopTapes H completed remaining suffix⟩ + (some ⟨some (.inr .levelGuard), cycle.finalState, + levelLoopTapes H (completed + 1) remaining suffix⟩) + (resizeCost (family H completed) H) := cycle.execution + let first := StateTransition.EvalsToInTime.trans (TM2.step (program positive H growth)) + _ _ _ _ _ guard cycleRun + let all := StateTransition.EvalsToInTime.trans (TM2.step (program positive H growth)) + _ _ _ _ _ first rest.execution + have index : completed + 1 + remaining = completed + (remaining + 1) := by omega + refine ⟨rest.finalState, ?_, ?_⟩ + · exact rest.caller_preserved.trans + (cycle.caller_preserved.trans (caller_clearRegister state)) + · rw [index] at all + refine { toEvalsTo := all.toEvalsTo, steps_le_m := ?_ } + have bound := all.steps_le_m + simp only [levelLoopCost] + omega + +open Turing +open PCP.ExpanderTables PCP.ExpanderRowControl PCP.ExpanderTableWords +open MachineExpanderFamilyBounds + +private def singleFamilyStep {S : Type*} (f : S → Option S) (a b : S) + (h : f a = some b) : StateTransition.EvalsToInTime f a (some b) 1 where + steps := 1 + evals_in_steps := by change f a = some b; exact h + steps_le_m := Nat.le_refl _ + +noncomputable def familyInTime {d : Nat} {ρ : Type} [Fintype ρ] + (positive : 0 < d) (H : Table (cloudSize d) d) (growth : 1 < cloudSize d) + (level : Nat) (state : State ρ d) (suffix : List Bool) : + StateTransition.EvalsToInTime (TM2.step (program positive H growth)) + ⟨some (.inr .initialize), state, initialTapes level suffix⟩ + (some ⟨none, initialState positive H (caller state), familyTapes H level suffix⟩) + (familyBudget H level) := by + let loop := levelLoopInTime positive H growth 0 level + (initialState positive H (caller state)) suffix + have initialRun : StateTransition.EvalsToInTime (TM2.step (program positive H growth)) + ⟨some (.inr .initialize), state, initialTapes level suffix⟩ + (some ⟨some (.inr .levelGuard), initialState positive H (caller state), + levelLoopTapes H 0 level suffix⟩) 1 := + singleFamilyStep _ _ _ (initialize_boundaryStep positive H growth level suffix state) + have finalCaller : caller loop.finalState = caller state := loop.caller_preserved + have done : StateTransition.EvalsToInTime (TM2.step (program positive H growth)) + ⟨some (.inr .done), loop.finalState, familyTapes H level suffix⟩ + (some ⟨none, initialState positive H (caller state), familyTapes H level suffix⟩) 1 := by + simpa only [normalizeState, finalCaller] using + singleFamilyStep _ _ _ (doneStep positive H growth (familyTapes H level suffix) + loop.finalState) + have loopRun : StateTransition.EvalsToInTime (TM2.step (program positive H growth)) + ⟨some (.inr .levelGuard), initialState positive H (caller state), + levelLoopTapes H 0 level suffix⟩ + (some ⟨some (.inr .done), loop.finalState, familyTapes H level suffix⟩) + (levelLoopCost H 0 level) := by simpa only [Nat.zero_add] using loop.execution + let first := StateTransition.EvalsToInTime.trans (TM2.step (program positive H growth)) + _ _ _ _ _ initialRun loopRun + let all := StateTransition.EvalsToInTime.trans (TM2.step (program positive H growth)) + _ _ _ _ _ first done + refine { toEvalsTo := all.toEvalsTo, steps_le_m := ?_ } + have bound := all.steps_le_m + have costEquality := levelLoopCost_zero_start H level + unfold familyBudget + omega + +noncomputable def familyInOutputSizeTime {d : Nat} {ρ : Type} [Fintype ρ] + (positive : 0 < d) (H : Table (cloudSize d) d) (growth : 1 < cloudSize d) + (level : Nat) (state : State ρ d) (suffix : List Bool) : + StateTransition.EvalsToInTime (TM2.step (program positive H growth)) + ⟨some (.inr .initialize), state, initialTapes level suffix⟩ + (some ⟨none, initialState positive H (caller state), familyTapes H level suffix⟩) + ((resizeCoefficient d + 4) * (vertexCount (degree d) level + 1)^5) where + toEvalsTo := (familyInTime positive H growth level state suffix).toEvalsTo + steps_le_m := (familyInTime positive H growth level state suffix).steps_le_m.trans + (familyBudget_le H growth level) + +theorem baseDegree_cloud_growth : + cloudSize PCP.Expanders.baseDegree = PCP.ExpanderFamily.growth := by + unfold cloudSize degree PCP.ExpanderFamily.growth + ring + +theorem baseDegree_cloud_gt_one : 1 < cloudSize PCP.Expanders.baseDegree := by + rw [baseDegree_cloud_growth] + exact PCP.ExpanderFamily.growth_gt_one + +theorem baseDegree_positive : 0 < PCP.Expanders.baseDegree := by + have h := baseDegree_cloud_gt_one + unfold cloudSize degree at h + by_contra hn + have hz : PCP.Expanders.baseDegree = 0 := by omega + rw [hz] at h + norm_num at h + +noncomputable def paddedFamilyInTime {ρ : Type} [Fintype ρ] + (H : Table (cloudSize PCP.Expanders.baseDegree) PCP.Expanders.baseDegree) + (requested : Nat) (state : State ρ PCP.Expanders.baseDegree) (suffix : List Bool) : + StateTransition.EvalsToInTime + (TM2.step (program baseDegree_positive H baseDegree_cloud_gt_one)) + ⟨some (.inr .initialize), state, + initialTapes (PCP.PreprocessingLevels.boundedLevel requested) suffix⟩ + (some ⟨none, initialState baseDegree_positive H (caller state), + familyTapes H (PCP.PreprocessingLevels.boundedLevel requested) suffix⟩) + (inputCoefficient * (requested + 1)^5) where + toEvalsTo := (familyInTime baseDegree_positive H baseDegree_cloud_gt_one + (PCP.PreprocessingLevels.boundedLevel requested) state suffix).toEvalsTo + steps_le_m := (familyInTime baseDegree_positive H baseDegree_cloud_gt_one + (PCP.PreprocessingLevels.boundedLevel requested) state suffix).steps_le_m.trans + (familyBudget_at_boundedLevel_le H requested) + +end MinUncutGames.Foundations.Complexity.MachineExpanderFamily + +namespace MinUncutGames.Foundations.Complexity.MachinePaddedExpanderFamily + +open Turing +open PCP.ExpanderTables PCP.ExpanderRowControl + +abbrev fixedDegree := PCP.Expanders.baseDegree +abbrev SmallTable := Table (cloudSize fixedDegree) fixedDegree +abbrev Tape := MachineExpanderFamily.Tape ⊕ MachineCeilingPower.Tape +abbrev Alphabet (_ : Tape) := Bool +abbrev Label := MachineExpanderFamily.Label fixedDegree ⊕ MachineCeilingPower.Label +abbrev State (ρ : Type) := MachineExpanderFamily.State ρ fixedDegree × (Bool × Option Bool) + +def familyTape (tape : MachineExpanderFamily.Tape) : Tape := .inl tape + +def familyView : Tape → Option MachineExpanderFamily.Tape + | .inl tape => some tape + | .inr _ => none + +@[simp] theorem familyView_left (tape : MachineExpanderFamily.Tape) : + familyView (familyTape tape) = some tape := rfl + +theorem familyView_right (j : Tape) (tape : MachineExpanderFamily.Tape) + (h : familyView j = some tape) : familyTape tape = j := by + cases j with + | inl j => + have hj : j = tape := Option.some.inj h + subst tape + rfl + | inr j => simp [familyView] at h + +def ceilingTape : MachineCeilingPower.Tape → Tape + | .level => .inl (.inr .remainingLevel) + | tape => .inr tape + +def ceilingView : Tape → Option MachineCeilingPower.Tape + | .inl (.inr .remainingLevel) => some .level + | .inl _ => none + | .inr .level => none + | .inr tape => some tape + +@[simp] theorem ceilingView_left (tape : MachineCeilingPower.Tape) : + ceilingView (ceilingTape tape) = some tape := by + cases tape <;> rfl + +theorem ceilingView_right (j : Tape) (tape : MachineCeilingPower.Tape) + (h : ceilingView j = some tape) : ceilingTape tape = j := by + cases j with + | inl j => + cases j with + | inl j => simp [ceilingView] at h + | inr j => + cases j <;> simp_all [ceilingView, ceilingTape] + cases h + rfl + | inr j => cases j <;> simp_all [ceilingView, ceilingTape] <;> cases h <;> rfl + +def familyLabel (label : MachineExpanderFamily.Label fixedDegree) : Label := .inl label +def ceilingLabel (label : MachineCeilingPower.Label) : Label := .inr label +def main : Label := .inr .init +def familyEntry : Label := .inl (.inr .initialize) + +def ceilingStates (ρ : Type) : + MachineCeilingPower.State (MachineExpanderFamily.State ρ fixedDegree) ≃ State ρ := + Equiv.prodAssoc _ _ _ + +@[simp] theorem ceilingStates_apply (ρ : Type) + (state : MachineCeilingPower.State (MachineExpanderFamily.State ρ fixedDegree)) : + ceilingStates ρ state = (state.1.1, (state.1.2, state.2)) := rfl + +variable {ρ : Type} [Fintype ρ] + +def familySource (H : SmallTable) : MachineExpanderFamily.Label fixedDegree → + TM2.Stmt MachineExpanderFamily.BoolAlphabet + (MachineExpanderFamily.Label fixedDegree) (State ρ) := + MachineStateFrame.frameProgram (τ := Bool × Option Bool) + (MachineExpanderFamily.boolView MachineExpanderFamily.baseDegree_positive H + MachineExpanderFamily.baseDegree_cloud_gt_one) + +def ceilingSource : MachineCeilingPower.Label → + TM2.Stmt MachineCeilingPower.Alphabet MachineCeilingPower.Label (State ρ) := + MachineStateEquiv.program (ceilingStates ρ) + (MachineCeilingPower.program PCP.ExpanderFamily.growth) + +def program (H : SmallTable) : Label → TM2.Stmt Alphabet Label (State ρ) + | .inl label => + MachineCloudPadding.Placement.statement familyTape familyLabel none (familySource H label) + | .inr label => + MachineCloudPadding.Placement.statement ceilingTape ceilingLabel (some familyEntry) + (ceilingSource (ρ := ρ) label) + +@[simp] theorem program_family (H : SmallTable) + (label : MachineExpanderFamily.Label fixedDegree) : + program (ρ := ρ) H (familyLabel label) = + MachineCloudPadding.Placement.statement familyTape familyLabel none + (familySource H label) := rfl + +@[simp] theorem program_ceiling (H : SmallTable) (label : MachineCeilingPower.Label) : + program (ρ := ρ) H (ceilingLabel label) = + MachineCloudPadding.Placement.statement ceilingTape ceilingLabel (some familyEntry) + (ceilingSource (ρ := ρ) label) := rfl + +def initialState (state : MachineExpanderFamily.State ρ fixedDegree) + (register : Option Bool) : State ρ := (state, (false, register)) + +def finalState (H : SmallTable) (state : MachineExpanderFamily.State ρ fixedDegree) : State ρ := + (MachineExpanderFamily.initialState MachineExpanderFamily.baseDegree_positive H + (MachineExpanderFamily.caller state), (false, none)) + +def initialTapes (requested : Nat) : Tape → List Bool + | .inr .input => encodeWord requested + | _ => [] + +def retainedCeilingTapes (requested : Nat) : MachineCeilingPower.Tape → List Bool := + MachineCeilingPower.memory (encodeWord requested) [] + (encodeWord (PCP.PreprocessingLevels.paddedSize requested)) [] [] [] [] [] + +def handoffTapes (requested : Nat) : Tape → List Bool + | .inl tape => MachineExpanderFamily.toBoolTapes + (MachineExpanderFamily.initialTapes (PCP.PreprocessingLevels.boundedLevel requested) []) tape + | .inr tape => retainedCeilingTapes requested tape + +def finalTapes (H : SmallTable) (requested : Nat) : Tape → List Bool + | .inl tape => MachineExpanderFamily.toBoolTapes + (MachineExpanderFamily.familyTapes H (PCP.PreprocessingLevels.boundedLevel requested) []) tape + | .inr tape => retainedCeilingTapes requested tape + +@[simp] theorem initialTapes_input (requested : Nat) : + initialTapes requested (.inr .input) = encodeWord requested := rfl + +@[simp] theorem finalTapes_input (H : SmallTable) (requested : Nat) : + finalTapes H requested (.inr .input) = encodeWord requested := rfl + +@[simp] theorem finalTapes_power (H : SmallTable) (requested : Nat) : + finalTapes H requested (.inr .power) = + encodeWord (PCP.PreprocessingLevels.paddedSize requested) := rfl + +open Turing +open MachineCloudPadding +open PCP.ExpanderTables PCP.ExpanderRowControl PCP.ExpanderTableWords + +def ceilingInput (requested : Nat) : MachineCeilingPower.Tape → List Bool := + MachineCeilingPower.memory (encodeWord requested) [] [] [] [] [] [] [] + +def ceilingOutput (requested : Nat) : MachineCeilingPower.Tape → List Bool := + MachineCeilingPower.memory (encodeWord requested) [] + (encodeWord (PCP.PreprocessingLevels.paddedSize requested)) [] + (encodeWord (PCP.PreprocessingLevels.boundedLevel requested)) [] [] [] + +def retainedFrame (requested : Nat) : Tape → List Bool + | .inl _ => [] + | .inr tape => retainedCeilingTapes requested tape + +theorem ceiling_initial_tapes (requested : Nat) : + Placement.tapes ceilingView (ceilingInput requested) (fun _ => []) = + initialTapes requested := by + funext tape + rcases tape with tape | tape + · rcases tape with tape | tape + · rfl + · cases tape <;> rfl + · cases tape <;> rfl + +theorem ceiling_handoff_tapes (requested : Nat) : + Placement.tapes ceilingView (ceilingOutput requested) (fun _ => []) = + handoffTapes requested := by + funext tape + rcases tape with tape | tape + · rcases tape with tape | tape + · rcases tape with tape | tape + · cases tape <;> rfl + · cases tape <;> rfl + · cases tape <;> + simp [Placement.tapes, ceilingView, ceilingOutput, handoffTapes, + MachineExpanderFamily.toBoolTapes, MachineExpanderFamily.toBoolWord, + MachineExpanderFamily.initialTapes, MachineEmbedding.tapes, + MachineCeilingPower.memory] + · cases tape <;> rfl + +theorem family_initial_tapes (requested : Nat) : + Placement.tapes familyView + (MachineExpanderFamily.toBoolTapes + (MachineExpanderFamily.initialTapes (PCP.PreprocessingLevels.boundedLevel requested) [])) + (retainedFrame requested) = handoffTapes requested := by + funext tape + cases tape <;> rfl + +theorem family_final_tapes (H : SmallTable) (requested : Nat) : + Placement.tapes familyView + (MachineExpanderFamily.toBoolTapes + (MachineExpanderFamily.familyTapes H (PCP.PreprocessingLevels.boundedLevel requested) [])) + (retainedFrame requested) = finalTapes H requested := by + funext tape + cases tape <;> rfl + +theorem ceiling_initial_configuration {ρ : Type} (requested : Nat) + (state : MachineExpanderFamily.State ρ fixedDegree) (register : Option Bool) : + Placement.configuration ceilingView ceilingLabel (some familyEntry) (fun _ => []) + (MachineStateEquiv.configuration (ceilingStates ρ) + ⟨some .init, ((state, false), register), ceilingInput requested⟩) = + ⟨some main, initialState state register, initialTapes requested⟩ := by + simp only [Placement.configuration, Placement.label, MachineStateEquiv.configuration, + ceilingStates_apply, ceiling_initial_tapes, ceilingLabel, main, initialState] + +theorem ceiling_handoff_configuration {ρ : Type} (requested : Nat) + (state : MachineExpanderFamily.State ρ fixedDegree) : + Placement.configuration ceilingView ceilingLabel (some familyEntry) (fun _ => []) + (MachineStateEquiv.configuration (ceilingStates ρ) + ⟨none, ((state, false), none), ceilingOutput requested⟩) = + ⟨some familyEntry, (state, (false, none)), handoffTapes requested⟩ := by + simp only [Placement.configuration, Placement.label, MachineStateEquiv.configuration, + ceilingStates_apply, ceiling_handoff_tapes] + +theorem family_initial_configuration {ρ : Type} (requested : Nat) + (state : MachineExpanderFamily.State ρ fixedDegree) (metadata : Bool × Option Bool) : + Placement.configuration familyView familyLabel none (retainedFrame requested) + (MachineStateFrame.frameConfiguration metadata + (MachineAlphabetTransport.configuration MachineExpanderFamily.alphabet_eq + ⟨some (.inr .initialize), state, + MachineExpanderFamily.initialTapes (PCP.PreprocessingLevels.boundedLevel requested) []⟩)) = + ⟨some familyEntry, (state, metadata), handoffTapes requested⟩ := by + rw [MachineExpanderFamily.configuration_toBool] + simp only [MachineStateFrame.frameConfiguration, Placement.configuration, Placement.label, + family_initial_tapes, familyEntry, familyLabel] + +theorem family_final_configuration {ρ : Type} (H : SmallTable) (requested : Nat) + (state : MachineExpanderFamily.State ρ fixedDegree) : + Placement.configuration familyView familyLabel none (retainedFrame requested) + (MachineStateFrame.frameConfiguration (false, none) + (MachineAlphabetTransport.configuration MachineExpanderFamily.alphabet_eq + ⟨none, + MachineExpanderFamily.initialState MachineExpanderFamily.baseDegree_positive H + (MachineExpanderFamily.caller state), + MachineExpanderFamily.familyTapes H (PCP.PreprocessingLevels.boundedLevel requested) []⟩)) = + ⟨none, finalState H state, finalTapes H requested⟩ := by + rw [MachineExpanderFamily.configuration_toBool] + simp only [MachineStateFrame.frameConfiguration, Placement.configuration, Placement.label, + family_final_tapes, finalState] + +@[simp] theorem handoffTapes_level (requested : Nat) : + handoffTapes requested (ceilingTape .level) = + encodeWord (PCP.PreprocessingLevels.boundedLevel requested) := by + simp [handoffTapes, ceilingTape, MachineExpanderFamily.toBoolTapes, + MachineExpanderFamily.toBoolWord, MachineExpanderFamily.initialTapes, + MachineEmbedding.tapes] + +@[simp] theorem handoffTapes_level_shadow (requested : Nat) : + handoffTapes requested (.inr .level) = [] := rfl + +@[simp] theorem finalTapes_level_shadow (H : SmallTable) (requested : Nat) : + finalTapes H requested (.inr .level) = [] := rfl + +@[simp] theorem finalTapes_remainingLevel (H : SmallTable) (requested : Nat) : + finalTapes H requested (ceilingTape .level) = encodeWord 0 := by + simp [finalTapes, ceilingTape, MachineExpanderFamily.toBoolTapes, + MachineExpanderFamily.toBoolWord, MachineExpanderFamily.familyTapes, + MachineExpanderFamily.boundaryTapes, MachineExpanderFamily.extraFrame, + MachineEmbedding.tapes] + +theorem finalTapes_currentSize (H : SmallTable) (requested : Nat) : + finalTapes H requested (familyTape (.inr .currentSize)) = + encodeWord (PCP.PreprocessingLevels.paddedSize requested) := by + change encodeWord (vertexCount (degree fixedDegree) + (PCP.PreprocessingLevels.boundedLevel requested)) = _ + exact congrArg encodeWord (PCP.PreprocessingLevels.table_vertexCount_eq_paddedSize requested) + +theorem finalTapes_table (H : SmallTable) (requested : Nat) : + finalTapes H requested (familyTape MachineExpanderFamily.tableTape) = + encodeWords (rotationWords (family H (PCP.PreprocessingLevels.boundedLevel requested))) := rfl + +end MinUncutGames.Foundations.Complexity.MachinePaddedExpanderFamily + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineExpanderRowFrames.lean b/lean/OAI/Computability/MinUncut/Machines/MachineExpanderRowFrames.lean new file mode 100644 index 0000000000000000000000000000000000000000..15536e67ba0a1133fca890cc605f8fbdcb9a6443 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineExpanderRowFrames.lean @@ -0,0 +1,799 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineExpanderFamilyAffine + +namespace OAI + +namespace MinUncutGames.Foundations.Complexity.MachineExpanderRow + +open PCP.ExpanderTables PCP.ExpanderRowControl PCP.ExpanderTableWords + +structure RowData (v d : Nat) where + oldTable : Table v (degree d) + smallTable : Table (cloudSize d) d + inputVertex : Fin v + inputCloud : Fin (cloudSize d) + inputPort : Fin (degree d) + +def rowData {v d : Nat} (G : Table v (degree d)) (H : Table (cloudSize d) d) + (vertex : Fin v) (cloud : Fin (cloudSize d)) (port : Fin (degree d)) : RowData v d := + ⟨G, H, vertex, cloud, port⟩ + +namespace RowData + +variable {v d : Nat} (r : RowData v d) + +def control0 : Control d := start r.smallTable r.inputCloud r.inputPort +def firstRow : Fin (v * degree d) := rowIndex v (degree d) (r.inputVertex, firstOffset r.control0) +def firstValue : Nat := (reverseIndex r.oldTable r.firstRow).val +def firstPair : Fin v × Fin (degree d) := lookup r.oldTable (r.inputVertex, firstOffset r.control0) +def firstVertex : Fin v := r.firstPair.1 +def firstReturn : Fin (degree d) := r.firstPair.2 +def control1 : Control d := receiveFirst r.control0 r.firstReturn +def secondRow : Fin (v * degree d) := rowIndex v (degree d) (r.firstVertex, secondOffset r.control1) +def secondValue : Nat := (reverseIndex r.oldTable r.secondRow).val +def secondPair : Fin v × Fin (degree d) := lookup r.oldTable (r.firstVertex, secondOffset r.control1) +def secondVertex : Fin v := r.secondPair.1 +def secondReturn : Fin (degree d) := r.secondPair.2 +def control2 : Control d := receiveSecond r.smallTable r.control1 r.secondReturn +def query1 : Nat := firstAddress r.inputVertex.val r.control0 +def query2 : Nat := secondAddress r.firstVertex.val r.control1 +def finalValue : Nat := outputAddress r.secondVertex.val r.control2 +def tableLength : Nat := (encodeWords (rotationWords r.oldTable)).length + +theorem query1_eq_firstRow : r.query1 = r.firstRow.val := + firstAddress_eq_rowIndex r.inputVertex r.control0 + +theorem query2_eq_secondRow : r.query2 = r.secondRow.val := + secondAddress_eq_rowIndex r.firstVertex r.control1 + +@[simp] theorem firstValue_div_degree : r.firstValue / degree d = r.firstVertex.val := rfl +@[simp] theorem firstValue_mod_degree : r.firstValue % degree d = r.firstReturn.val := rfl +@[simp] theorem secondValue_div_degree : r.secondValue / degree d = r.secondVertex.val := rfl +@[simp] theorem secondValue_mod_degree : r.secondValue % degree d = r.secondReturn.val := rfl + +theorem firstReturn_eq_residue (positive : 0 < d) : + r.firstReturn = MachineFixedDivMod.residue (degree d) (Nat.mul_pos positive positive) + r.firstValue := Fin.ext rfl + +theorem secondReturn_eq_residue (positive : 0 < d) : + r.secondReturn = MachineFixedDivMod.residue (degree d) (Nat.mul_pos positive positive) + r.secondValue := Fin.ext rfl + +theorem receiveFirst_residue_eq_control1 (positive : 0 < d) : + receiveFirst r.control0 (MachineFixedDivMod.residue (degree d) + (Nat.mul_pos positive positive) r.firstValue) = r.control1 := by + rw [← r.firstReturn_eq_residue positive] + rfl + +theorem receiveSecond_residue_eq_control2 (positive : 0 < d) : + receiveSecond r.smallTable r.control1 (MachineFixedDivMod.residue (degree d) + (Nat.mul_pos positive positive) r.secondValue) = r.control2 := by + rw [← r.secondReturn_eq_residue positive] + rfl + +theorem firstSelected : (rotationWords r.oldTable)[r.query1]? = some r.firstValue := by + rw [query1_eq_firstRow] + exact rotationWords_getElem? r.oldTable r.firstRow + +theorem secondSelected : (rotationWords r.oldTable)[r.query2]? = some r.secondValue := by + rw [query2_eq_secondRow] + exact rotationWords_getElem? r.oldTable r.secondRow + +theorem evaluateRow_eq : evaluateRow r.oldTable r.smallTable r.inputVertex r.inputCloud r.inputPort = + (r.secondVertex, r.control2) := rfl + +theorem finalValue_eq_step_reverseIndex : + r.finalValue = (reverseIndex (step r.oldTable r.smallTable) + (rowIndex (v * cloudSize d) (degree d) + (rowIndex v (cloudSize d) (r.inputVertex, r.inputCloud), r.inputPort))).val := by + simpa only [evaluateRow_eq, finalValue] using outputAddress_eq_step_reverseIndex + r.oldTable r.smallTable r.inputVertex r.inputCloud r.inputPort + +theorem rows_le_tableLength : v * degree d ≤ r.tableLength := by + simp only [tableLength, encodeWords_length, rotationWords_length] + omega + +theorem query1_le_tableLength : r.query1 ≤ r.tableLength := by + rw [query1_eq_firstRow] + exact r.firstRow.isLt.le.trans r.rows_le_tableLength + +theorem query2_le_tableLength : r.query2 ≤ r.tableLength := by + rw [query2_eq_secondRow] + exact r.secondRow.isLt.le.trans r.rows_le_tableLength + +theorem firstValue_le_tableLength : r.firstValue ≤ r.tableLength := + (reverseIndex r.oldTable r.firstRow).isLt.le.trans r.rows_le_tableLength + +theorem secondValue_le_tableLength : r.secondValue ≤ r.tableLength := + (reverseIndex r.oldTable r.secondRow).isLt.le.trans r.rows_le_tableLength + +theorem inputVertex_le_tableLength : r.inputVertex.val ≤ r.tableLength := by + have hq : 1 ≤ degree d := Nat.zero_lt_of_lt r.inputPort.isLt + have hv : v ≤ v * degree d := by simpa using Nat.mul_le_mul_left v hq + exact r.inputVertex.isLt.le.trans (hv.trans r.rows_le_tableLength) + +theorem firstVertex_le_tableLength : r.firstVertex.val ≤ r.tableLength := by + rw [← firstValue_div_degree] + exact (Nat.div_le_self r.firstValue (degree d)).trans r.firstValue_le_tableLength + +theorem secondVertex_le_tableLength : r.secondVertex.val ≤ r.tableLength := by + rw [← secondValue_div_degree] + exact (Nat.div_le_self r.secondValue (degree d)).trans r.secondValue_le_tableLength + +theorem firstReturn_le_tableLength : r.firstReturn.val ≤ r.tableLength := by + rw [← firstValue_mod_degree] + exact (Nat.mod_le r.firstValue (degree d)).trans r.firstValue_le_tableLength + +theorem secondReturn_le_tableLength : r.secondReturn.val ≤ r.tableLength := by + rw [← secondValue_mod_degree] + exact (Nat.mod_le r.secondValue (degree d)).trans r.secondValue_le_tableLength + +end RowData + +variable {v d : Nat} + +def frameContents (r : RowData v d) (output : List Bool) + (qr qi lo q1 q2 r1 r2 : List Bool) : Tape → List Bool + | .inputVertex => encodeWord r.inputVertex.val + | .table => encodeWords (rotationWords r.oldTable) + | .output => output + | .queryReverse => qr + | .queryIndex => qi + | .lookupOutput => lo + | .quotientFirst => q1 + | .quotientSecond => q2 + | .remainderFirst => r1 + | .remainderSecond => r2 + | _ => [] + +def frame0 (r : RowData v d) (output : List Bool) : Tape → List Bool := + frameContents r output [] [] [] [] [] [] [] +def frame1 (r : RowData v d) (output : List Bool) : Tape → List Bool := + initializedTapes id (frame0 r output) +def frame2 (r : RowData v d) (output : List Bool) : Tape → List Bool := + emittedWord .queryReverse (frame1 r output) r.query1 +def frame3 (r : RowData v d) (output : List Bool) : Tape → List Bool := + Reduction.MachineTransfer.tapesAt .queryReverse .queryIndex (frame2 r output) [] + (encodeWord r.query1) +def frame4 (r : RowData v d) (output : List Bool) : Tape → List Bool := + lookupResultTapes id (frame3 r output) r.firstValue [] +def frame5 (r : RowData v d) (output : List Bool) : Tape → List Bool := + divisionOutput d id .quotientFirst .remainderFirst (frame4 r output) r.firstValue [] [] [] +def frame6 (r : RowData v d) (output : List Bool) : Tape → List Bool := + clearedQueryTapes id (frame5 r output) +def frame7 (r : RowData v d) (output : List Bool) : Tape → List Bool := + emittedWord .queryReverse (frame6 r output) r.query2 +def frame8 (r : RowData v d) (output : List Bool) : Tape → List Bool := + Reduction.MachineTransfer.tapesAt .queryReverse .queryIndex (frame7 r output) [] + (encodeWord r.query2) +def frame9 (r : RowData v d) (output : List Bool) : Tape → List Bool := + lookupResultTapes id (frame8 r output) r.secondValue [] +def frame10 (r : RowData v d) (output : List Bool) : Tape → List Bool := + divisionOutput d id .quotientSecond .remainderSecond (frame9 r output) r.secondValue [] [] [] +def frame11 (r : RowData v d) (output : List Bool) : Tape → List Bool := + emittedWord .output (frame10 r output) r.finalValue +def frame12 (r : RowData v d) (output : List Bool) : Tape → List Bool := + cleanupTapes id (frame11 r output) + +private theorem lookupResultTapes_id_eq (base : Tape → List Bool) + (value : Nat) (suffix : List Bool) : + lookupResultTapes id base value suffix = + Function.update + (Function.update (Function.update base .queryIndex (encodeWord 0 ++ suffix)) + .lookupWork []) + .lookupOutput (encodeWord value ++ base .lookupOutput) := rfl + +@[simp] theorem frame1_eq (r : RowData v d) (output : List Bool) : + frame1 r output = frameContents r output [] [] [] + (encodeWord 0) (encodeWord 0) (encodeWord 0) (encodeWord 0) := by + funext tape + cases tape <;> simp [frame1, frame0, frameContents, initializedTapes, encodeWord] + +@[simp] theorem frame2_eq (r : RowData v d) (output : List Bool) : + frame2 r output = frameContents r output (encodeWord r.query1).reverse [] [] + (encodeWord 0) (encodeWord 0) (encodeWord 0) (encodeWord 0) := by + funext tape + cases tape <;> simp [frame2, frameContents, emittedWord] + +@[simp] theorem frame3_eq (r : RowData v d) (output : List Bool) : + frame3 r output = frameContents r output [] (encodeWord r.query1) [] + (encodeWord 0) (encodeWord 0) (encodeWord 0) (encodeWord 0) := by + funext tape + cases tape <;> simp [frame3, frameContents, Reduction.MachineTransfer.tapesAt] + +@[simp] theorem frame4_eq (r : RowData v d) (output : List Bool) : + frame4 r output = frameContents r output [] (encodeWord 0) (encodeWord r.firstValue) + (encodeWord 0) (encodeWord 0) (encodeWord 0) (encodeWord 0) := by + funext tape + cases tape <;> simp [frame4, lookupResultTapes_id_eq, frameContents] + +@[simp] theorem frame5_eq (r : RowData v d) (output : List Bool) : + frame5 r output = frameContents r output [] (encodeWord 0) (encodeWord 0) + (encodeWord r.firstVertex.val) (encodeWord 0) + (encodeWord r.firstReturn.val) (encodeWord 0) := by + funext tape + cases tape <;> simp [frame5, divisionOutput, MachineFixedDivMod.unaryTapes, + MachineFixedDivMod.tapes, MachineCopy.forkTapes, frameContents] + +@[simp] theorem frame6_eq (r : RowData v d) (output : List Bool) : + frame6 r output = frameContents r output [] [] [] (encodeWord r.firstVertex.val) + (encodeWord 0) (encodeWord r.firstReturn.val) (encodeWord 0) := by + funext tape + cases tape <;> simp [frame6, clearedQueryTapes, frameContents, encodeWord] + +@[simp] theorem frame7_eq (r : RowData v d) (output : List Bool) : + frame7 r output = frameContents r output (encodeWord r.query2).reverse [] [] + (encodeWord r.firstVertex.val) (encodeWord 0) + (encodeWord r.firstReturn.val) (encodeWord 0) := by + funext tape + cases tape <;> simp [frame7, emittedWord, frameContents] + +@[simp] theorem frame8_eq (r : RowData v d) (output : List Bool) : + frame8 r output = frameContents r output [] (encodeWord r.query2) [] + (encodeWord r.firstVertex.val) (encodeWord 0) + (encodeWord r.firstReturn.val) (encodeWord 0) := by + funext tape + cases tape <;> simp [frame8, Reduction.MachineTransfer.tapesAt, frameContents] + +@[simp] theorem frame9_eq (r : RowData v d) (output : List Bool) : + frame9 r output = frameContents r output [] (encodeWord 0) (encodeWord r.secondValue) + (encodeWord r.firstVertex.val) (encodeWord 0) + (encodeWord r.firstReturn.val) (encodeWord 0) := by + funext tape + cases tape <;> simp [frame9, lookupResultTapes_id_eq, frameContents] + +@[simp] theorem frame10_eq (r : RowData v d) (output : List Bool) : + frame10 r output = frameContents r output [] (encodeWord 0) (encodeWord 0) + (encodeWord r.firstVertex.val) (encodeWord r.secondVertex.val) + (encodeWord r.firstReturn.val) (encodeWord r.secondReturn.val) := by + funext tape + cases tape <;> simp [frame10, divisionOutput, MachineFixedDivMod.unaryTapes, + MachineFixedDivMod.tapes, MachineCopy.forkTapes, frameContents] + +@[simp] theorem frame11_eq (r : RowData v d) (output : List Bool) : + frame11 r output = frameContents r ((encodeWord r.finalValue).reverse ++ output) + [] (encodeWord 0) (encodeWord 0) + (encodeWord r.firstVertex.val) (encodeWord r.secondVertex.val) + (encodeWord r.firstReturn.val) (encodeWord r.secondReturn.val) := by + funext tape + cases tape <;> simp [frame11, emittedWord, frameContents] + +@[simp] theorem frame12_eq (r : RowData v d) (output : List Bool) : + frame12 r output = frameContents r ((encodeWord r.finalValue).reverse ++ output) + [] [] [] [] [] [] [] := by + funext tape + cases tape <;> simp [frame12, cleanupTapes, frameContents] + +theorem final_frame_eq (r : RowData v d) (output : List Bool) : + frame12 r output = emittedWord .output (frame0 r output) r.finalValue := by + funext tape + cases tape <;> simp [frame0, emittedWord, frameContents] + +@[simp] theorem frame0_inputVertex (r : RowData v d) (output : List Bool) : + frame0 r output .inputVertex = encodeWord r.inputVertex.val := rfl + +@[simp] theorem frame0_table (r : RowData v d) (output : List Bool) : + frame0 r output .table = encodeWords (rotationWords r.oldTable) := rfl + +@[simp] theorem frame0_output (r : RowData v d) (output : List Bool) : + frame0 r output .output = output := rfl + +@[simp] theorem frame1_inputVertex (r : RowData v d) (output : List Bool) : + frame1 r output .inputVertex = encodeWord r.inputVertex.val := by simp [frameContents] + +@[simp] theorem frame1_emitScratch (r : RowData v d) (output : List Bool) : + frame1 r output .emitScratch = [] := by simp [frameContents] + +@[simp] theorem frame2_queryReverse (r : RowData v d) (output : List Bool) : + frame2 r output .queryReverse = (encodeWord r.query1).reverse := by simp [frameContents] + +@[simp] theorem frame2_queryIndex (r : RowData v d) (output : List Bool) : + frame2 r output .queryIndex = [] := by simp [frameContents] + +@[simp] theorem frame3_table (r : RowData v d) (output : List Bool) : + frame3 r output .table = encodeWords (rotationWords r.oldTable) := by simp [frameContents] + +@[simp] theorem frame3_lookupRestore (r : RowData v d) (output : List Bool) : + frame3 r output .lookupRestore = [] := by simp [frameContents] + +@[simp] theorem frame3_lookupWork (r : RowData v d) (output : List Bool) : + frame3 r output .lookupWork = [] := by simp [frameContents] + +@[simp] theorem frame3_lookupOutput (r : RowData v d) (output : List Bool) : + frame3 r output .lookupOutput = [] := by simp [frameContents] + +@[simp] theorem frame3_queryIndex (r : RowData v d) (output : List Bool) : + frame3 r output .queryIndex = encodeWord r.query1 := by simp [frameContents] + +@[simp] theorem frame4_lookupOutput (r : RowData v d) (output : List Bool) : + frame4 r output .lookupOutput = encodeWord r.firstValue := by simp [frameContents] + +@[simp] theorem frame4_quotientFirst (r : RowData v d) (output : List Bool) : + frame4 r output .quotientFirst = encodeWord 0 := by simp [frameContents] + +@[simp] theorem frame4_remainderFirst (r : RowData v d) (output : List Bool) : + frame4 r output .remainderFirst = encodeWord 0 := by simp [frameContents] + +@[simp] theorem frame6_quotientFirst (r : RowData v d) (output : List Bool) : + frame6 r output .quotientFirst = encodeWord r.firstVertex.val := by simp [frameContents] + +@[simp] theorem frame6_emitScratch (r : RowData v d) (output : List Bool) : + frame6 r output .emitScratch = [] := by simp [frameContents] + +@[simp] theorem frame7_queryReverse (r : RowData v d) (output : List Bool) : + frame7 r output .queryReverse = (encodeWord r.query2).reverse := by simp [frameContents] + +@[simp] theorem frame7_queryIndex (r : RowData v d) (output : List Bool) : + frame7 r output .queryIndex = [] := by simp [frameContents] + +@[simp] theorem frame8_table (r : RowData v d) (output : List Bool) : + frame8 r output .table = encodeWords (rotationWords r.oldTable) := by simp [frameContents] + +@[simp] theorem frame8_lookupRestore (r : RowData v d) (output : List Bool) : + frame8 r output .lookupRestore = [] := by simp [frameContents] + +@[simp] theorem frame8_lookupWork (r : RowData v d) (output : List Bool) : + frame8 r output .lookupWork = [] := by simp [frameContents] + +@[simp] theorem frame8_lookupOutput (r : RowData v d) (output : List Bool) : + frame8 r output .lookupOutput = [] := by simp [frameContents] + +@[simp] theorem frame8_queryIndex (r : RowData v d) (output : List Bool) : + frame8 r output .queryIndex = encodeWord r.query2 := by simp [frameContents] + +@[simp] theorem frame9_lookupOutput (r : RowData v d) (output : List Bool) : + frame9 r output .lookupOutput = encodeWord r.secondValue := by simp [frameContents] + +@[simp] theorem frame9_quotientSecond (r : RowData v d) (output : List Bool) : + frame9 r output .quotientSecond = encodeWord 0 := by simp [frameContents] + +@[simp] theorem frame9_remainderSecond (r : RowData v d) (output : List Bool) : + frame9 r output .remainderSecond = encodeWord 0 := by simp [frameContents] + +@[simp] theorem frame10_quotientSecond (r : RowData v d) (output : List Bool) : + frame10 r output .quotientSecond = encodeWord r.secondVertex.val := by simp [frameContents] + +@[simp] theorem frame10_emitScratch (r : RowData v d) (output : List Bool) : + frame10 r output .emitScratch = [] := by simp [frameContents] + +@[simp] theorem frame10_output (r : RowData v d) (output : List Bool) : + frame10 r output .output = output := by simp [frameContents] + +theorem final_dirty_word_length_le (r : RowData v d) (output : List Bool) (i : Fin 6) : + ((frame11 r output) (dirtyTape i)).length ≤ r.tableLength + 1 := by + have h1 := r.firstVertex_le_tableLength + have h2 := r.secondVertex_le_tableLength + have h3 := r.firstReturn_le_tableLength + have h4 := r.secondReturn_le_tableLength + fin_cases i <;> simp only [frame11_eq, dirtyTape, frameContents, encodeWord_length] <;> omega + +theorem cleanupSteps_le_tableLength (r : RowData v d) (output : List Bool) : + cleanupSteps id (frame11 r output) ≤ 6 * (r.tableLength + 1) + 6 := by + have h1 := r.firstVertex_le_tableLength + have h2 := r.secondVertex_le_tableLength + have h3 := r.firstReturn_le_tableLength + have h4 := r.secondReturn_le_tableLength + simp only [cleanupSteps, frame11_eq, id_eq, frameContents, encodeWord_length] + omega + +open Turing MachineComposition +open PCP.ExpanderTables PCP.ExpanderRowControl PCP.ExpanderTableWords PCP.AlphabetTable + +private theorem concatenate {A : Type*} {f : A → A} {m n : Nat} {a b c : A} + (first : f^[m] a = b) (second : f^[n] b = c) : f^[m + n] a = c := by + rw [Nat.add_comm m n, Function.iterate_add_apply, first, second] + +def rowSteps {v d : Nat} (r : RowData v d) (output : List Bool) : Nat := + 1 + emitSteps r.inputVertex.val + (r.query1 + 2) + + MachinePreservingLookupClean.steps (rotationWords r.oldTable) r.firstRow.val + + (r.firstValue + 2) + 1 + emitSteps r.firstVertex.val + (r.query2 + 2) + + MachinePreservingLookupClean.steps (rotationWords r.oldTable) r.secondRow.val + + (r.secondValue + 2) + emitSteps r.secondVertex.val + + (cleanupSteps id (frame11 r output) + 1) + +section Execution + +variable {v d : Nat} {ρ Λ : Type} [Fintype ρ] + (positive : 0 < d) (r : RowData v d) (output : List Bool) (ambient : ρ) + (labels : Label d → Λ) (exit : Option Λ) + (target : Λ → TM2.Stmt (fun _ : Tape => Bool) Λ (State ρ d)) + (code : ∀ l, target (labels l) = statement positive r.smallTable id labels exit l) + +include code + +theorem rowTraceAt : + (advance (TM2.step target))^[rowSteps r output] + (some ⟨some (labels .initialize), divisionState positive ambient r.control0 none, + frame0 r output⟩) = + some ⟨exit, divisionState positive ambient r.control2 none, + emittedWord .output (frame0 r output) r.finalValue⟩ := by + let zero := MachineFixedDivMod.residue (degree d) (Nat.mul_pos positive positive) 0 + have h0 : (advance (TM2.step target))^[1] + (some ⟨some (labels .initialize), divisionState positive ambient r.control0 none, + frame0 r output⟩) = + some ⟨some (labels (.firstEmit (Emitter.labelAt 3 _ 0 .entry))), + divisionState positive ambient r.control0 none, frame1 r output⟩ := by + simpa only [Function.iterate_one, advance_some, divisionState, frame1] using + initializeStepAt positive r.smallTable id Function.injective_id labels exit target code + (frame0 r output) (divisionState positive ambient r.control0 none) + have h1 := firstEmitTraceAt positive r.smallTable id Function.injective_id + labels exit target code r.inputVertex.val (frame1 r output) + (by simp) (by simp) ((ambient,r.control0),zero) + change (advance (TM2.step target))^[emitSteps r.inputVertex.val] + (some ⟨some (labels (.firstEmit (Emitter.labelAt 3 _ 0 .entry))), + divisionState positive ambient r.control0 none, frame1 r output⟩) = + some ⟨some (labels .firstReverse), divisionState positive ambient r.control0 none, + frame2 r output⟩ at h1 + have h2 := reversePhaseTrace_unary false positive r.smallTable id Function.injective_id + labels exit target code (frame2 r output) (((ambient,r.control0),zero),()) none + r.query1 [] (by simp) (by simp) + simp only [List.append_nil] at h2 + change (advance (TM2.step target))^[r.query1 + 2] + (some ⟨some (labels .firstReverse), divisionState positive ambient r.control0 none, + frame2 r output⟩) = + some ⟨some (labels (.firstLookup (.run .copyFirst))), + divisionState positive ambient r.control0 none, frame3 r output⟩ at h2 + have h3 := lookupPhaseTrace false positive r.smallTable id Function.injective_id + labels exit target code (frame3 r output) r.oldTable + (by simp) (by simp) + (r.inputVertex, firstOffset r.control0) [] + (by simpa [frameContents, RowData.firstRow] using + congrArg encodeWord r.query1_eq_firstRow) + (by simp) (((ambient,r.control0),zero),()) none + change (advance (TM2.step target))^[MachinePreservingLookupClean.steps + (rotationWords r.oldTable) r.firstRow.val] + (some ⟨some (labels (.firstLookup (.run .copyFirst))), + divisionState positive ambient r.control0 none, frame3 r output⟩) = + some ⟨some (labels .firstScan), divisionState positive ambient r.control0 none, + frame4 r output⟩ at h3 + have h4 := firstDivisionTrace positive r.smallTable id Function.injective_id labels exit + target code (frame4 r output) r.firstValue [] [] [] + (by simp) (by simp) (by simp) + ambient r.control0 none + rw [← r.firstReturn_eq_residue positive] at h4 + change (advance (TM2.step target))^[r.firstValue + 2] + (some ⟨some (labels .firstScan), divisionState positive ambient r.control0 none, + frame4 r output⟩) = + some ⟨some (labels .clearQuery), divisionState positive ambient r.control1 none, + frame5 r output⟩ at h4 + have h5 : (advance (TM2.step target))^[1] + (some ⟨some (labels .clearQuery), divisionState positive ambient r.control1 none, + frame5 r output⟩) = + some ⟨some (labels (.secondEmit (Emitter.labelAt 3 _ 0 .entry))), + divisionState positive ambient r.control1 none, frame6 r output⟩ := by + simpa only [Function.iterate_one, advance_some, frame6] using + clearQueryStepAt positive r.smallTable id Function.injective_id labels exit target code + (frame5 r output) (divisionState positive ambient r.control1 none) + have h6 := secondEmitTraceAt positive r.smallTable id Function.injective_id + labels exit target code r.firstVertex.val (frame6 r output) + (by simp) (by simp) ((ambient,r.control1),zero) + change (advance (TM2.step target))^[emitSteps r.firstVertex.val] + (some ⟨some (labels (.secondEmit (Emitter.labelAt 3 _ 0 .entry))), + divisionState positive ambient r.control1 none, frame6 r output⟩) = + some ⟨some (labels .secondReverse), divisionState positive ambient r.control1 none, + frame7 r output⟩ at h6 + have h7 := reversePhaseTrace_unary true positive r.smallTable id Function.injective_id + labels exit target code (frame7 r output) (((ambient,r.control1),zero),()) none + r.query2 [] (by simp) (by simp) + simp only [List.append_nil] at h7 + change (advance (TM2.step target))^[r.query2 + 2] + (some ⟨some (labels .secondReverse), divisionState positive ambient r.control1 none, + frame7 r output⟩) = + some ⟨some (labels (.secondLookup (.run .copyFirst))), + divisionState positive ambient r.control1 none, frame8 r output⟩ at h7 + have h8 := lookupPhaseTrace true positive r.smallTable id Function.injective_id + labels exit target code (frame8 r output) r.oldTable + (by simp) (by simp) + (r.firstVertex, secondOffset r.control1) [] + (by simpa [frameContents, RowData.secondRow] using + congrArg encodeWord r.query2_eq_secondRow) + (by simp) (((ambient,r.control1),zero),()) none + change (advance (TM2.step target))^[MachinePreservingLookupClean.steps + (rotationWords r.oldTable) r.secondRow.val] + (some ⟨some (labels (.secondLookup (.run .copyFirst))), + divisionState positive ambient r.control1 none, frame8 r output⟩) = + some ⟨some (labels .secondScan), divisionState positive ambient r.control1 none, + frame9 r output⟩ at h8 + have h9 := secondDivisionTrace positive r.smallTable id Function.injective_id labels exit + target code (frame9 r output) r.secondValue [] [] [] + (by simp) (by simp) (by simp) + ambient r.control1 none + rw [← r.secondReturn_eq_residue positive] at h9 + change (advance (TM2.step target))^[r.secondValue + 2] + (some ⟨some (labels .secondScan), divisionState positive ambient r.control1 none, + frame9 r output⟩) = + some ⟨some (labels (.outputEmit (Emitter.labelAt 3 _ 0 .entry))), + divisionState positive ambient r.control2 none, frame10 r output⟩ at h9 + have h10 := outputEmitTraceAt positive r.smallTable id Function.injective_id + labels exit target code r.secondVertex.val (frame10 r output) + (by simp) (by simp) ((ambient,r.control2),zero) + change (advance (TM2.step target))^[emitSteps r.secondVertex.val] + (some ⟨some (labels (.outputEmit (Emitter.labelAt 3 _ 0 .entry))), + divisionState positive ambient r.control2 none, frame10 r output⟩) = + some ⟨some (labels (.cleanup 0)), divisionState positive ambient r.control2 none, + frame11 r output⟩ at h10 + have h11 := cleanupExitTraceAt positive r.smallTable id Function.injective_id + labels exit target code (frame11 r output) (divisionState positive ambient r.control2 none) + change (advance (TM2.step target))^[cleanupSteps id (frame11 r output) + 1] + (some ⟨some (labels (.cleanup 0)), divisionState positive ambient r.control2 none, + frame11 r output⟩) = + some ⟨exit, divisionState positive ambient r.control2 none, frame12 r output⟩ at h11 + rw [final_frame_eq] at h11 + exact concatenate (concatenate (concatenate (concatenate (concatenate + (concatenate (concatenate (concatenate (concatenate (concatenate + (concatenate h0 h1) h2) h3) h4) h5) h6) h7) h8) h9) h10) h11 + +end Execution + +theorem rowSteps_le {v d : Nat} (r : RowData v d) (output : List Bool) : + rowSteps r output ≤ 80 * (r.tableLength + 1) := by + have lookup1 := MachinePreservingLookupClean.steps_le (rotationWords r.oldTable) + r.firstRow.val r.firstValue (rotationWords_getElem? r.oldTable r.firstRow) + have lookup2 := MachinePreservingLookupClean.steps_le (rotationWords r.oldTable) + r.secondRow.val r.secondValue (rotationWords_getElem? r.oldTable r.secondRow) + have h0 := r.inputVertex_le_tableLength + have h1 := r.query1_le_tableLength + have h2 := r.firstValue_le_tableLength + have h3 := r.firstVertex_le_tableLength + have h4 := r.query2_le_tableLength + have h5 := r.secondValue_le_tableLength + have h6 := r.secondVertex_le_tableLength + have clean := cleanupSteps_le_tableLength r output + change _ ≤ 6 * r.tableLength + 4 at lookup1 lookup2 + simp only [rowSteps, emitSteps] + omega + +def rowInTimeAt {v d : Nat} {ρ Λ : Type} [Fintype ρ] + (positive : 0 < d) (r : RowData v d) (output : List Bool) (ambient : ρ) + (labels : Label d → Λ) (exit : Option Λ) + (target : Λ → TM2.Stmt (fun _ : Tape => Bool) Λ (State ρ d)) + (code : ∀ l, target (labels l) = statement positive r.smallTable id labels exit l) : + StateTransition.EvalsToInTime (TM2.step target) + ⟨some (labels .initialize), divisionState positive ambient r.control0 none, + frame0 r output⟩ + (some ⟨exit, divisionState positive ambient r.control2 none, + emittedWord .output (frame0 r output) r.finalValue⟩) + (80 * (r.tableLength + 1)) where + steps := rowSteps r output + evals_in_steps := rowTraceAt positive r output ambient labels exit target code + steps_le_m := rowSteps_le r output + +def rowInTime {v d : Nat} {ρ : Type} [Fintype ρ] + (positive : 0 < d) (r : RowData v d) (output : List Bool) (ambient : ρ) : + StateTransition.EvalsToInTime (TM2.step (program positive r.smallTable)) + ⟨some .initialize, divisionState positive ambient r.control0 none, frame0 r output⟩ + (some ⟨none, divisionState positive ambient r.control2 none, + emittedWord .output (frame0 r output) r.finalValue⟩) + (80 * (r.tableLength + 1)) := + rowInTimeAt positive r output ambient id none (program positive r.smallTable) (fun _ => rfl) + +end MinUncutGames.Foundations.Complexity.MachineExpanderRow + +namespace MinUncutGames.Foundations.Complexity.MachineExpanderTable + +open Turing +open PCP.ExpanderTables PCP.ExpanderRowControl + +variable {ρ : Type} {d : Nat} + +@[simp] theorem caller_boundaryState (positive : 0 < d) (H : Table (cloudSize d) d) + (ambient : ρ) (position : Position d) : + caller (boundaryState positive H ambient position) = ambient := rfl + +@[simp] theorem prepareState_boundaryState (positive : 0 < d) (H : Table (cloudSize d) d) + (ambient : ρ) (position : Position d) : + prepareState positive H (boundaryState positive H ambient position) = + boundaryState positive H ambient position := rfl + +@[simp] theorem clearRegister_boundaryState (positive : 0 < d) (H : Table (cloudSize d) d) + (ambient : ρ) (position : Position d) : + clearRegister (boundaryState positive H ambient position) = + boundaryState positive H ambient position := rfl + +@[simp] theorem caller_prepareState (positive : 0 < d) (H : Table (cloudSize d) d) + (state : State ρ d) : caller (prepareState positive H state) = caller state := rfl + +@[simp] theorem caller_resetState (positive : 0 < d) (H : Table (cloudSize d) d) + (state : State ρ d) : caller (resetState positive H state) = caller state := rfl + +@[simp] theorem caller_clearRegister (state : State ρ d) : + caller (clearRegister state) = caller state := rfl + +@[simp] theorem caller_advancePositionState (positive : 0 < d) (state : State ρ d) : + caller (advancePositionState positive state) = caller state := rfl + +@[simp] theorem caller_resetPositionState (positive : 0 < d) (state : State ρ d) : + caller (resetPositionState positive state) = caller state := rfl + +theorem nextPosition_val_of_lt (positive : 0 < d) (position : Position d) + (more : position.val + 1 < rowFactor d) : + (nextPosition positive position).val = position.val + 1 := Nat.mod_eq_of_lt more + +theorem boundaryTapes_update_count (vertex remaining next : Nat) + (oldTable output countSuffix result : List Bool) : + Function.update (boundaryTapes vertex remaining oldTable output countSuffix result) + (.inr .vertexCount) (encodeWord next ++ countSuffix) = + boundaryTapes vertex next oldTable output countSuffix result := by + funext tape + rcases tape with row | extra + · cases row <;> simp [boundaryTapes, rowTapes, MachineEmbedding.tapes, Function.update] + · cases extra <;> simp [boundaryTapes, extraTapes, MachineEmbedding.tapes, Function.update] + +theorem boundaryTapes_increment_vertex (vertex remaining : Nat) + (oldTable output countSuffix result : List Bool) : + Function.update (boundaryTapes vertex remaining oldTable output countSuffix result) + (.inl .inputVertex) (true :: encodeWord vertex) = + boundaryTapes (vertex + 1) remaining oldTable output countSuffix result := by + funext tape + rcases tape with row | extra + · cases row <;> + simp [boundaryTapes, rowTapes, MachineEmbedding.tapes, Function.update, + encodeWord, List.replicate_succ] + · cases extra <;> + simp [boundaryTapes, extraTapes, MachineEmbedding.tapes, Function.update] + +theorem initialTapes_initialize (vertices : Nat) (oldTable countSuffix : List Bool) : + Function.update (initialTapes vertices oldTable countSuffix) (.inl .inputVertex) [false] = + boundaryTapes 0 vertices oldTable [] countSuffix [] := by + funext tape + rcases tape with row | extra + · cases row <;> + simp [initialTapes, boundaryTapes, rowTapes, MachineEmbedding.tapes, + Function.update, encodeWord] + · cases extra <;> + simp [initialTapes, boundaryTapes, extraTapes, MachineEmbedding.tapes, + Function.update] + +variable [Fintype ρ] + +theorem initializeStep (positive : 0 < d) (H : Table (cloudSize d) d) + (base : ∀ tape, List (Alphabet tape)) (state : State ρ d) : + TM2.step (program positive H) ⟨some (.inr .initialize), state, base⟩ = + some ⟨some (.inr .vertexGuard), resetState positive H state, + Function.update base (.inl .inputVertex) (false :: base (.inl .inputVertex))⟩ := by + change some (TM2.stepAux (program positive H (.inr .initialize)) state base) = _ + rw [program_outer] + rfl + +theorem initialize_boundaryStep (positive : 0 < d) (H : Table (cloudSize d) d) + (vertices : Nat) (oldTable countSuffix : List Bool) (state : State ρ d) : + TM2.step (program positive H) + ⟨some (.inr .initialize), state, initialTapes vertices oldTable countSuffix⟩ = + some ⟨some (.inr .vertexGuard), initialState positive H (caller state), + boundaryTapes 0 vertices oldTable [] countSuffix []⟩ := by + have h := initializeStep positive H (initialTapes vertices oldTable countSuffix) state + have input : initialTapes vertices oldTable countSuffix (.inl .inputVertex) = [] := rfl + simp only [input, resetState] at h + exact h.trans (congrArg + (fun tapes : ∀ tape, List (Alphabet tape) => + (some ⟨some (.inr .vertexGuard), initialState positive H (caller state), tapes⟩ : + Option (TM2.Cfg Alphabet (Label d) (State ρ d)))) + (initialTapes_initialize vertices oldTable countSuffix)) + +theorem vertexGuard_succStep (positive : 0 < d) (H : Table (cloudSize d) d) + (base : ∀ tape, List (Alphabet tape)) (state : State ρ d) + (remaining : Nat) (suffix : List Bool) + (counter : base (.inr .vertexCount) = encodeWord (remaining + 1) ++ suffix) : + TM2.step (program positive H) ⟨some (.inr .vertexGuard), state, base⟩ = + some ⟨some (.inr .prepareRow), clearRegister state, + Function.update base (.inr .vertexCount) (encodeWord remaining ++ suffix)⟩ := by + change some (TM2.stepAux (program positive H (.inr .vertexGuard)) state base) = _ + rw [program_outer] + simp [outerStatement, MachineControl.statement, vertexGuardCore, TM2.stepAux, + guardStates, clearRegister, counter, encodeWord, List.replicate_succ] + +theorem vertexGuard_zeroStep (positive : 0 < d) (H : Table (cloudSize d) d) + (base : ∀ tape, List (Alphabet tape)) (state : State ρ d) + (suffix : List Bool) + (counter : base (.inr .vertexCount) = encodeWord 0 ++ suffix) : + TM2.step (program positive H) ⟨some (.inr .vertexGuard), state, base⟩ = + some ⟨some (.inr .reverseOutput), clearRegister state, base⟩ := by + change some (TM2.stepAux (program positive H (.inr .vertexGuard)) state base) = _ + rw [program_outer] + simp [outerStatement, MachineControl.statement, vertexGuardCore, TM2.stepAux, + guardStates, clearRegister, counter, encodeWord] + +theorem vertexGuard_boundary_succStep (positive : 0 < d) (H : Table (cloudSize d) d) + (vertex remaining : Nat) (oldTable output countSuffix result : List Bool) + (state : State ρ d) : + TM2.step (program positive H) + ⟨some (.inr .vertexGuard), state, + boundaryTapes vertex (remaining + 1) oldTable output countSuffix result⟩ = + some ⟨some (.inr .prepareRow), clearRegister state, + boundaryTapes vertex remaining oldTable output countSuffix result⟩ := by + simpa only [boundaryTapes_update_count] using + vertexGuard_succStep positive H + (boundaryTapes vertex (remaining + 1) oldTable output countSuffix result) + state remaining countSuffix rfl + +theorem vertexGuard_boundary_zeroStep (positive : 0 < d) (H : Table (cloudSize d) d) + (vertex : Nat) (oldTable output countSuffix result : List Bool) (state : State ρ d) : + TM2.step (program positive H) + ⟨some (.inr .vertexGuard), state, + boundaryTapes vertex 0 oldTable output countSuffix result⟩ = + some ⟨some (.inr .reverseOutput), clearRegister state, + boundaryTapes vertex 0 oldTable output countSuffix result⟩ := + vertexGuard_zeroStep positive H + (boundaryTapes vertex 0 oldTable output countSuffix result) state countSuffix rfl + +theorem prepareRowStep (positive : 0 < d) (H : Table (cloudSize d) d) + (base : ∀ tape, List (Alphabet tape)) (state : State ρ d) : + TM2.step (program positive H) ⟨some (.inr .prepareRow), state, base⟩ = + some ⟨some (.inl .initialize), prepareState positive H state, base⟩ := by + change some (TM2.stepAux (program positive H (.inr .prepareRow)) state base) = _ + rw [program_outer] + rfl + +theorem afterRow_moreStep (positive : 0 < d) (H : Table (cloudSize d) d) + (base : ∀ tape, List (Alphabet tape)) (state : State ρ d) + (more : state.2.val + 1 < rowFactor d) : + TM2.step (program positive H) ⟨some (.inr .afterRow), state, base⟩ = + some ⟨some (.inr .prepareRow), advancePositionState positive state, base⟩ := by + change some (TM2.stepAux (program positive H (.inr .afterRow)) state base) = _ + rw [program_outer] + simp [outerStatement, TM2.stepAux, more] + +theorem afterRow_lastStep (positive : 0 < d) (H : Table (cloudSize d) d) + (base : ∀ tape, List (Alphabet tape)) (state : State ρ d) + (last : ¬ state.2.val + 1 < rowFactor d) : + TM2.step (program positive H) ⟨some (.inr .afterRow), state, base⟩ = + some ⟨some (.inr .vertexGuard), resetPositionState positive state, + Function.update base (.inl .inputVertex) (true :: base (.inl .inputVertex))⟩ := by + change some (TM2.stepAux (program positive H (.inr .afterRow)) state base) = _ + rw [program_outer] + simp [outerStatement, TM2.stepAux, last] + +theorem afterRow_last_boundaryStep (positive : 0 < d) (H : Table (cloudSize d) d) + (vertex remaining : Nat) (oldTable output countSuffix result : List Bool) + (state : State ρ d) (last : ¬ state.2.val + 1 < rowFactor d) : + TM2.step (program positive H) + ⟨some (.inr .afterRow), state, + boundaryTapes vertex remaining oldTable output countSuffix result⟩ = + some ⟨some (.inr .vertexGuard), resetPositionState positive state, + boundaryTapes (vertex + 1) remaining oldTable output countSuffix result⟩ := by + have input : boundaryTapes vertex remaining oldTable output countSuffix result + (.inl .inputVertex) = encodeWord vertex := rfl + have h := afterRow_lastStep positive H + (boundaryTapes vertex remaining oldTable output countSuffix result) state last + simp only [input] at h + exact h.trans (congrArg + (fun tapes : ∀ tape, List (Alphabet tape) => + (some ⟨some (.inr .vertexGuard), resetPositionState positive state, tapes⟩ : + Option (TM2.Cfg Alphabet (Label d) (State ρ d)))) + (boundaryTapes_increment_vertex vertex remaining oldTable output countSuffix result)) + +theorem reverseOutput_consStep (positive : 0 < d) (H : Table (cloudSize d) d) + (base : ∀ tape, List (Alphabet tape)) (state : State ρ d) + (symbol : Bool) (word : List Bool) (source : base (.inl .output) = symbol :: word) : + TM2.step (program positive H) ⟨some (.inr .reverseOutput), state, base⟩ = + some ⟨some (.inr .reverseOutput), ((state.1.1, some symbol), state.2), + Function.update (Function.update base (.inl .output) word) + (.inr .result) (symbol :: base (.inr .result))⟩ := by + change some (TM2.stepAux (program positive H (.inr .reverseOutput)) state base) = _ + rw [program_outer] + simp [outerStatement, MachineControl.statement, Reduction.MachineTransfer.loopAt, + Reduction.MachineTransfer.exitAt, TM2.stepAux, guardStates, source] + +theorem reverseOutput_nilStep (positive : 0 < d) (H : Table (cloudSize d) d) + (base : ∀ tape, List (Alphabet tape)) (state : State ρ d) + (source : base (.inl .output) = []) : + TM2.step (program positive H) ⟨some (.inr .reverseOutput), state, base⟩ = + some ⟨some (.inr .done), clearRegister state, base⟩ := by + have same : Function.update base (.inl .output) [] = base := by + simpa only [source] using Function.update_eq_self (.inl .output) base + change some (TM2.stepAux (program positive H (.inr .reverseOutput)) state base) = _ + rw [program_outer] + simp [outerStatement, MachineControl.statement, Reduction.MachineTransfer.loopAt, + Reduction.MachineTransfer.exitAt, TM2.stepAux, guardStates, clearRegister, source, same] + +theorem doneStep (positive : 0 < d) (H : Table (cloudSize d) d) + (base : ∀ tape, List (Alphabet tape)) (state : State ρ d) : + TM2.step (program positive H) ⟨some (.inr .done), state, base⟩ = + some ⟨none, state, base⟩ := by + change some (TM2.stepAux (program positive H (.inr .done)) state base) = _ + rw [program_outer] + rfl + +end MinUncutGames.Foundations.Complexity.MachineExpanderTable + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineExpanderTableProgram.lean b/lean/OAI/Computability/MinUncut/Machines/MachineExpanderTableProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..cbce309dcf64793393c95caf9d9cbccdc7ebc340 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineExpanderTableProgram.lean @@ -0,0 +1,988 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineFixedDivMod + +namespace OAI + +namespace MinUncutGames.Foundations.Complexity.MachineExpanderTable + +open Turing +open PCP.ExpanderTables PCP.ExpanderRowControl + +inductive ExtraTape + | vertexCount | result + deriving DecidableEq + +protected abbrev ExtraTape.enumList : List ExtraTape := [.vertexCount, .result] + +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 + +abbrev Tape := MachineExpanderRow.Tape ⊕ ExtraTape + +abbrev Alphabet : Tape → Type := + MachineEmbedding.Alphabet (fun _ : MachineExpanderRow.Tape => Bool) + (fun _ : ExtraTape => Bool) + +instance alphabetFintype (tape : Tape) : Fintype (Alphabet tape) := by + cases tape <;> exact inferInstanceAs (Fintype Bool) + +inductive OuterLabel + | initialize | vertexGuard | prepareRow | afterRow | reverseOutput | done + deriving DecidableEq + +protected abbrev OuterLabel.enumList : List OuterLabel := [.initialize, .vertexGuard, .prepareRow, + .afterRow, .reverseOutput, .done] + +protected theorem OuterLabel.enumList_getElem?_ctorIdx_eq (x : OuterLabel) : + OuterLabel.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem OuterLabel.enumList_nodup : OuterLabel.enumList.Nodup := by decide + +instance : Fintype OuterLabel where + elems := ⟨OuterLabel.enumList, OuterLabel.enumList_nodup⟩ + complete x := by cases x <;> decide + +abbrev Label (d : Nat) := MachineExpanderRow.Label d ⊕ OuterLabel +abbrev Position (d : Nat) := Fin (rowFactor d) +abbrev State (ρ : Type) (d : Nat) := MachineExpanderRow.State ρ d × Position d +abbrev RowStatePrefix (ρ : Type) (d : Nat) := + (MachineExpanderRow.Ambient ρ d × Fin (degree d)) × Unit + +def guardStates (ρ : Type) (d : Nat) : + ((RowStatePrefix ρ d × Position d) × Option Bool) ≃ State ρ d where + toFun s := ((s.1.1, s.2), s.1.2) + invFun s := ((s.1.1, s.2), s.1.2) + left_inv := by rintro ⟨⟨a, p⟩, b⟩; rfl + right_inv := by rintro ⟨⟨a, b⟩, p⟩; rfl + +@[simp] theorem guardStates_apply (ρ : Type) (d : Nat) + (s : (RowStatePrefix ρ d × Position d) × Option Bool) : + guardStates ρ d s = ((s.1.1, s.2), s.1.2) := rfl + +@[simp] theorem guardStates_symm_apply (ρ : Type) (d : Nat) (s : State ρ d) : + (guardStates ρ d).symm s = ((s.1.1, s.2), s.1.2) := rfl + +theorem rowFactor_pos {d : Nat} (positive : 0 < d) : 0 < rowFactor d := by + have hq : 0 < degree d := Nat.mul_pos positive positive + exact Nat.mul_pos (Nat.mul_pos hq hq) hq + +def zeroPosition {d : Nat} (positive : 0 < d) : Position d := + ⟨0, rowFactor_pos positive⟩ + +def nextPosition {d : Nat} (positive : 0 < d) (p : Position d) : Position d := + ⟨(p.val + 1) % rowFactor d, Nat.mod_lt _ (rowFactor_pos positive)⟩ + +def positionPair {d : Nat} (p : Position d) : Fin (cloudSize d) × Fin (degree d) := + (rowIndex (cloudSize d) (degree d)).symm p + +def caller {ρ : Type} {d : Nat} (s : State ρ d) : ρ := s.1.1.1.1.1 + +def boundaryState {ρ : Type} {d : Nat} (positive : 0 < d) + (H : Table (cloudSize d) d) (ambient : ρ) (p : Position d) : State ρ d := + (MachineExpanderRow.divisionState positive ambient + (start H (positionPair p).1 (positionPair p).2) none, p) + +def initialState {ρ : Type} {d : Nat} (positive : 0 < d) + (H : Table (cloudSize d) d) (ambient : ρ) : State ρ d := + boundaryState positive H ambient (zeroPosition positive) + +def prepareState {ρ : Type} {d : Nat} (positive : 0 < d) + (H : Table (cloudSize d) d) (s : State ρ d) : State ρ d := + boundaryState positive H (caller s) s.2 + +def resetState {ρ : Type} {d : Nat} (positive : 0 < d) + (H : Table (cloudSize d) d) (s : State ρ d) : State ρ d := + initialState positive H (caller s) + +def clearRegister {ρ : Type} {d : Nat} (s : State ρ d) : State ρ d := + ((s.1.1, none), s.2) + +def advancePositionState {ρ : Type} {d : Nat} (positive : 0 < d) + (s : State ρ d) : State ρ d := (s.1, nextPosition positive s.2) + +def resetPositionState {ρ : Type} {d : Nat} (positive : 0 < d) + (s : State ρ d) : State ρ d := (s.1, zeroPosition positive) + +def vertexGuardCore {ρ : Type} {d : Nat} : + TM2.Stmt Alphabet (Label d) ((RowStatePrefix ρ d × Position d) × Option Bool) := + .peek (.inr .vertexCount) (fun s head => (s.1, head)) + (.branch (fun s => s.2.getD false) + (.pop (.inr .vertexCount) (fun s _ => (s.1, none)) + (.goto fun _ => .inr .prepareRow)) + (.load (fun s => (s.1, none)) (.goto fun _ => .inr .reverseOutput))) + +variable {ρ : Type} [Fintype ρ] + +def outerStatement {d : Nat} (positive : 0 < d) (H : Table (cloudSize d) d) : + OuterLabel → TM2.Stmt Alphabet (Label d) (State ρ d) + | .initialize => + .push (.inl .inputVertex) (fun _ => false) + (.load (resetState positive H) (.goto fun _ => .inr .vertexGuard)) + | .vertexGuard => MachineControl.statement id (guardStates ρ d) vertexGuardCore + | .prepareRow => + .load (prepareState positive H) (.goto fun _ => .inl .initialize) + | .afterRow => + .branch (fun s => decide (s.2.val + 1 < rowFactor d)) + (.load (advancePositionState positive) (.goto fun _ => .inr .prepareRow)) + (.push (.inl .inputVertex) (fun _ => true) + (.load (resetPositionState positive) (.goto fun _ => .inr .vertexGuard))) + | .reverseOutput => + MachineControl.statement id (guardStates ρ d) + (Reduction.MachineTransfer.loopAt (Γ := Alphabet) (Λ := Label d) + (σ := RowStatePrefix ρ d × Position d) (.inl .output) (.inr .result) id false + (.inr .reverseOutput) (some (.inr .done))) + | .done => .halt + +def rowReturn (d : Nat) : Option (Label d) := some (.inr .afterRow) + +def program {d : Nat} (positive : 0 < d) (H : Table (cloudSize d) d) : + Label d → TM2.Stmt Alphabet (Label d) (State ρ d) := + MachineEmbedding.program (rowReturn d) (MachineExpanderRow.program positive H) + (outerStatement positive H) + +@[simp] theorem program_row {d : Nat} (positive : 0 < d) + (H : Table (cloudSize d) d) (label : MachineExpanderRow.Label d) : + program (ρ := ρ) positive H (.inl label) = + MachineEmbedding.statement (rowReturn d) + (MachineExpanderRow.program positive H label) := rfl + +@[simp] theorem program_outer {d : Nat} (positive : 0 < d) + (H : Table (cloudSize d) d) (label : OuterLabel) : + program (ρ := ρ) positive H (.inr label) = outerStatement positive H label := rfl + +def rowExecution {d : Nat} (positive : 0 < d) (H : Table (cloudSize d) d) + (position : Position d) (extra : ExtraTape → List Bool) + {a b : TM2.Cfg (fun _ : MachineExpanderRow.Tape => Bool) + (MachineExpanderRow.Label d) (MachineExpanderRow.State ρ d)} {budget : Nat} + (execution : StateTransition.EvalsToInTime + (TM2.step (MachineExpanderRow.program positive H)) a (some b) budget) : + StateTransition.EvalsToInTime (TM2.step (program positive H)) + (MachineEmbedding.configuration (rowReturn d) position extra a) + (some (MachineEmbedding.configuration (rowReturn d) position extra b)) budget := + MachineComposition.embeddedExecution (rowReturn d) position extra + (MachineExpanderRow.program positive H) (outerStatement positive H) execution + +@[simp] theorem rowExecution_steps {d : Nat} (positive : 0 < d) + (H : Table (cloudSize d) d) (position : Position d) (extra : ExtraTape → List Bool) + {a b : TM2.Cfg (fun _ : MachineExpanderRow.Tape => Bool) + (MachineExpanderRow.Label d) (MachineExpanderRow.State ρ d)} {budget : Nat} + (execution : StateTransition.EvalsToInTime + (TM2.step (MachineExpanderRow.program positive H)) a (some b) budget) : + (rowExecution positive H position extra execution).steps = execution.steps := rfl + +def rowTapes (vertex : Nat) (oldTable output : List Bool) : MachineExpanderRow.Tape → List Bool + | .inputVertex => encodeWord vertex + | .table => oldTable + | .output => output + | _ => [] + +def extraTapes (remaining : Nat) (countSuffix result : List Bool) : ExtraTape → List Bool + | .vertexCount => encodeWord remaining ++ countSuffix + | .result => result + +def boundaryTapes (vertex remaining : Nat) (oldTable output countSuffix result : List Bool) : + (tape : Tape) → List (Alphabet tape) := + MachineEmbedding.tapes (rowTapes vertex oldTable output) (extraTapes remaining countSuffix result) + +def initialTapes (vertices : Nat) (oldTable countSuffix : List Bool) : + (tape : Tape) → List (Alphabet tape) := + MachineEmbedding.tapes + (fun tape => match tape with | .table => oldTable | _ => []) + (extraTapes vertices countSuffix []) + +def finalTapes (vertices : Nat) (oldTable output countSuffix : List Bool) : + (tape : Tape) → List (Alphabet tape) := + boundaryTapes vertices 0 oldTable [] countSuffix output + +end MinUncutGames.Foundations.Complexity.MachineExpanderTable + +namespace MinUncutGames.Foundations.Complexity.MachineAlphabetTransport + +open Turing.TM2 + +variable {K Λ σ : Type} {Γ Δ : K → Type} + +def tapes (h : Γ = Δ) (source : ∀ k, List (Γ k)) : ∀ k, List (Δ k) := h ▸ source + +def statement (h : Γ = Δ) (source : Stmt Γ Λ σ) : Stmt Δ Λ σ := h ▸ source + +def configuration (h : Γ = Δ) (source : Cfg Γ Λ σ) : Cfg Δ Λ σ := h ▸ source + +def program (h : Γ = Δ) (source : Λ → Stmt Γ Λ σ) : Λ → Stmt Δ Λ σ := + fun label => statement h (source label) + +abbrev castStatement (h : Γ = Δ) (source : Stmt Γ Λ σ) : Stmt Δ Λ σ := statement h source +abbrev castConfiguration (h : Γ = Δ) (source : Cfg Γ Λ σ) : Cfg Δ Λ σ := configuration h source +abbrev castProgram (h : Γ = Δ) (source : Λ → Stmt Γ Λ σ) : Λ → Stmt Δ Λ σ := program h source + +@[simp] theorem tapes_rfl (source : ∀ k, List (Γ k)) : tapes rfl source = source := rfl +@[simp] theorem statement_rfl (source : Stmt Γ Λ σ) : statement rfl source = source := rfl +@[simp] theorem configuration_rfl (source : Cfg Γ Λ σ) : configuration rfl source = source := rfl +@[simp] theorem program_rfl (source : Λ → Stmt Γ Λ σ) : program rfl source = source := rfl + +@[simp] theorem program_apply (h : Γ = Δ) (source : Λ → Stmt Γ Λ σ) (label : Λ) : + program h source label = statement h (source label) := rfl + +@[simp] theorem statement_roundtrip (h : Γ = Δ) (source : Stmt Δ Λ σ) : + statement h (statement h.symm source) = source := by cases h; rfl + +@[simp] theorem statement_symm_roundtrip (h : Γ = Δ) (source : Stmt Γ Λ σ) : + statement h.symm (statement h source) = source := by cases h; rfl + +@[simp] theorem configuration_roundtrip (h : Γ = Δ) (source : Cfg Δ Λ σ) : + configuration h (configuration h.symm source) = source := by cases h; rfl + +@[simp] theorem configuration_symm_roundtrip (h : Γ = Δ) (source : Cfg Γ Λ σ) : + configuration h.symm (configuration h source) = source := by cases h; rfl + +@[simp] theorem program_roundtrip (h : Γ = Δ) (source : Λ → Stmt Δ Λ σ) : + program h (program h.symm source) = source := by cases h; rfl + +@[simp] theorem program_symm_roundtrip (h : Γ = Δ) (source : Λ → Stmt Γ Λ σ) : + program h.symm (program h source) = source := by cases h; rfl + +@[simp] theorem tapes_roundtrip (h : Γ = Δ) (source : ∀ k, List (Δ k)) : + tapes h (tapes h.symm source) = source := by cases h; rfl + +@[simp] theorem tapes_symm_roundtrip (h : Γ = Δ) (source : ∀ k, List (Γ k)) : + tapes h.symm (tapes h source) = source := by cases h; rfl + +@[simp] theorem configuration_label (h : Γ = Δ) (source : Cfg Γ Λ σ) : + (configuration h source).l = source.l := by cases h; rfl + +@[simp] theorem configuration_state (h : Γ = Δ) (source : Cfg Γ Λ σ) : + (configuration h source).var = source.var := by cases h; rfl + +@[simp] theorem configuration_tapes (h : Γ = Δ) (source : Cfg Γ Λ σ) : + (configuration h source).stk = tapes h source.stk := by cases h; rfl + +@[simp] theorem configuration_mk (h : Γ = Δ) (label : Option Λ) (state : σ) + (source : ∀ k, List (Γ k)) : + configuration h ⟨label, state, source⟩ = ⟨label, state, tapes h source⟩ := by cases h; rfl + +@[simp] theorem map_configuration_rfl (source : Option (Cfg Γ Λ σ)) : + source.map (configuration (rfl : Γ = Γ)) = source := by cases source <;> rfl + +variable [DecidableEq K] + +theorem stepAux_simulation (h : Γ = Δ) (source : Stmt Γ Λ σ) (state : σ) + (sourceTapes : ∀ k, List (Γ k)) : + stepAux (statement h source) state (tapes h sourceTapes) = + configuration h (stepAux source state sourceTapes) := by cases h; rfl + +theorem step_simulation (h : Γ = Δ) (source : Λ → Stmt Γ Λ σ) (start : Cfg Γ Λ σ) : + step (program h source) (configuration h start) = + (step source start).map (configuration h) := by + cases h + simp only [program_rfl, configuration_rfl, map_configuration_rfl] + +theorem trace_transport (h : Γ = Δ) (source : Λ → Stmt Γ Λ σ) + (n : Nat) (start : Option (Cfg Γ Λ σ)) : + (MachineComposition.advance (step (program h source)))^[n] + (start.map (configuration h)) = + ((MachineComposition.advance (step source))^[n] start).map (configuration h) := by + cases h + simp only [program_rfl, map_configuration_rfl] + +theorem successfulTrace (h : Γ = Δ) (source : Λ → Stmt Γ Λ σ) + (n : Nat) (start finish : Cfg Γ Λ σ) + (trace : (MachineComposition.advance (step source))^[n] (some start) = some finish) : + (MachineComposition.advance (step (program h source)))^[n] + (some (configuration h start)) = some (configuration h finish) := by + have transported := trace_transport h source n (some start) + simpa only [Option.map_some, trace] using transported + +def executionInTime (h : Γ = Δ) (source : Λ → Stmt Γ Λ σ) + {start : Cfg Γ Λ σ} {finish : Option (Cfg Γ Λ σ)} {budget : Nat} + (execution : StateTransition.EvalsToInTime (step source) start finish budget) : + StateTransition.EvalsToInTime (step (program h source)) (configuration h start) + (finish.map (configuration h)) budget where + steps := execution.steps + evals_in_steps := by + cases h + simpa only [program_rfl, configuration_rfl, map_configuration_rfl] + using execution.evals_in_steps + steps_le_m := execution.steps_le_m + +@[simp] theorem executionInTime_steps (h : Γ = Δ) (source : Λ → Stmt Γ Λ σ) + {start : Cfg Γ Λ σ} {finish : Option (Cfg Γ Λ σ)} {budget : Nat} + (execution : StateTransition.EvalsToInTime (step source) start finish budget) : + (executionInTime h source execution).steps = execution.steps := rfl + +def successfulExecutionInTime (h : Γ = Δ) (source : Λ → Stmt Γ Λ σ) + {start finish : Cfg Γ Λ σ} {budget : Nat} + (execution : StateTransition.EvalsToInTime (step source) start (some finish) budget) : + StateTransition.EvalsToInTime (step (program h source)) (configuration h start) + (some (configuration h finish)) budget := executionInTime h source execution + +@[simp] theorem successfulExecutionInTime_steps (h : Γ = Δ) (source : Λ → Stmt Γ Λ σ) + {start finish : Cfg Γ Λ σ} {budget : Nat} + (execution : StateTransition.EvalsToInTime (step source) start (some finish) budget) : + (successfulExecutionInTime h source execution).steps = execution.steps := rfl + +end MinUncutGames.Foundations.Complexity.MachineAlphabetTransport + +namespace MinUncutGames.Foundations.Complexity.MachineExpanderFamily + +open Turing +open PCP.ExpanderTables PCP.ExpanderRowControl PCP.ExpanderTableWords + +inductive ExtraTape + | remainingLevel | currentSize | unaryScratch | tableReverse + deriving DecidableEq + +protected abbrev ExtraTape.enumList : List ExtraTape := [.remainingLevel, .currentSize, + .unaryScratch, .tableReverse] + +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 + +abbrev Tape := MachineExpanderTable.Tape ⊕ ExtraTape +abbrev Alphabet : Tape → Type := + MachineEmbedding.Alphabet MachineExpanderTable.Alphabet (fun _ : ExtraTape => Bool) +abbrev BoolAlphabet (_ : Tape) := Bool + +theorem alphabet_eq : Alphabet = BoolAlphabet := by + funext tape + cases tape with + | inl tape => cases tape <;> rfl + | inr tape => rfl + +instance alphabetFintype (tape : Tape) : Fintype (Alphabet tape) := by + rw [alphabet_eq] + exact inferInstanceAs (Fintype Bool) + +inductive AffinePhase + | copyCount | multiplySize + deriving DecidableEq + +protected abbrev AffinePhase.enumList : List AffinePhase := [.copyCount, .multiplySize] + +protected theorem AffinePhase.enumList_getElem?_ctorIdx_eq (x : AffinePhase) : + AffinePhase.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem AffinePhase.enumList_nodup : AffinePhase.enumList.Nodup := by decide + +instance : Fintype AffinePhase where + elems := ⟨AffinePhase.enumList, AffinePhase.enumList_nodup⟩ + complete x := by cases x <;> decide + +inductive AffineLabel + | seed | scan | restore + deriving DecidableEq + +protected abbrev AffineLabel.enumList : List AffineLabel := [.seed, .scan, .restore] + +protected theorem AffineLabel.enumList_getElem?_ctorIdx_eq (x : AffineLabel) : + AffineLabel.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem AffineLabel.enumList_nodup : AffineLabel.enumList.Nodup := by decide + +instance : Fintype AffineLabel where + elems := ⟨AffineLabel.enumList, AffineLabel.enumList_nodup⟩ + complete x := by cases x <;> decide + +inductive OuterLabel + | initialize + | levelGuard + | affine (phase : AffinePhase) (label : AffineLabel) + | clearOldTable | reverseResult | reverseTable | clearCurrentSize + | drainInputVertex | drainVertexCount | done + deriving DecidableEq, Fintype + +abbrev Label (d : Nat) := MachineExpanderTable.Label d ⊕ OuterLabel +abbrev State (ρ : Type) (d : Nat) := MachineExpanderTable.State ρ d × Unit +abbrev RegisterAmbient (ρ : Type) (d : Nat) := + (MachineExpanderTable.RowStatePrefix ρ d × MachineExpanderTable.Position d) × Unit + +def registerStates (ρ : Type) (d : Nat) : + (RegisterAmbient ρ d × Option Bool) ≃ State ρ d where + toFun s := (((s.1.1.1, s.2), s.1.1.2), s.1.2) + invFun s := (((s.1.1.1, s.1.2), s.2), s.1.1.2) + left_inv := by rintro ⟨⟨⟨a, p⟩, u⟩, b⟩; rfl + right_inv := by rintro ⟨⟨⟨a, b⟩, p⟩, u⟩; rfl + +@[simp] theorem registerStates_apply (ρ : Type) (d : Nat) + (s : RegisterAmbient ρ d × Option Bool) : + registerStates ρ d s = (((s.1.1.1, s.2), s.1.1.2), s.1.2) := rfl + +@[simp] theorem registerStates_symm_apply (ρ : Type) (d : Nat) (s : State ρ d) : + (registerStates ρ d).symm s = (((s.1.1.1, s.1.2), s.2), s.1.1.2) := rfl + +def caller {ρ : Type} {d : Nat} (s : State ρ d) : ρ := + MachineExpanderTable.caller s.1 + +def initialState {ρ : Type} {d : Nat} (positive : 0 < d) + (H : Table (cloudSize d) d) (ambient : ρ) : State ρ d := + (MachineExpanderTable.initialState positive H ambient, ()) + +def normalizeState {ρ : Type} {d : Nat} (positive : 0 < d) + (H : Table (cloudSize d) d) (s : State ρ d) : State ρ d := + initialState positive H (caller s) + +def initialEncoding (d : Nat) : List Bool := encodeWords (rotationWords (initial d)) + +theorem initialEncoding_eq_family {d : Nat} (H : Table (cloudSize d) d) : + initialEncoding d = encodeWords (rotationWords (family H 0)) := rfl + +def tableTape : Tape := .inl (.inl .table) +def inputVertexTape : Tape := .inl (.inl .inputVertex) +def vertexCountTape : Tape := .inl (.inr .vertexCount) +def resultTape : Tape := .inl (.inr .result) + +def affineSource : AffinePhase → Tape + | .copyCount => .inr .currentSize + | .multiplySize => inputVertexTape + +def affineDestination : AffinePhase → Tape + | .copyCount => vertexCountTape + | .multiplySize => .inr .currentSize + +def affineCoefficient (d : Nat) : AffinePhase → Nat + | .multiplySize => cloudSize d + | .copyCount => 1 + +def affineExit (d : Nat) : AffinePhase → Label d + | .copyCount => .inl (.inr .initialize) + | .multiplySize => .inr .drainInputVertex + +def affineStatement {ρ : Type} {d : Nat} (phase : AffinePhase) : + AffineLabel → TM2.Stmt BoolAlphabet (Label d) (State ρ d) + | .seed => + MachineControl.statement id (registerStates ρ d) + (MachineUnaryAffineAt.seed (Λ := Label d) (σ := RegisterAmbient ρ d) + (affineDestination phase) 0 (.inr (.affine phase .scan))) + | .scan => + MachineControl.statement id (registerStates ρ d) + (MachineUnaryAffineAt.scan (Λ := Label d) (σ := RegisterAmbient ρ d) + (affineSource phase) (.inr .unaryScratch) + (affineDestination phase) (affineCoefficient d phase) + (.inr (.affine phase .scan)) (.inr (.affine phase .restore))) + | .restore => + MachineControl.statement id (registerStates ρ d) + (Reduction.MachineTransfer.loopAt (Γ := BoolAlphabet) (Λ := Label d) + (σ := RegisterAmbient ρ d) (.inr .unaryScratch) (affineSource phase) id false + (.inr (.affine phase .restore)) (some (affineExit d phase))) + +def drainStatement {ρ : Type} {d : Nat} (tape : Tape) (again next : OuterLabel) : + TM2.Stmt BoolAlphabet (Label d) (State ρ d) := + MachineControl.statement id (registerStates ρ d) + (MachineDrain.drain (Λ := Label d) (σ := RegisterAmbient ρ d) + tape (.inr again) (some (.inr next))) + +variable {ρ : Type} [Fintype ρ] + +def boolOuterStatement {d : Nat} (positive : 0 < d) (H : Table (cloudSize d) d) : + OuterLabel → TM2.Stmt BoolAlphabet (Label d) (State ρ d) + | .initialize => + Reduction.MachineSubstitution.pushWord tableTape (initialEncoding d).reverse + (Reduction.MachineSubstitution.pushWord (.inr .currentSize) (encodeWord 1).reverse + (.load (normalizeState positive H) + (.goto fun _ => .inr .levelGuard))) + | .levelGuard => + MachineControl.statement id (registerStates ρ d) + (MachineUnaryCounter.guard (K := Tape) (Λ := Label d) (σ := RegisterAmbient ρ d) + (.inr .remainingLevel) (.inr (.affine .copyCount .seed)) (.inr .done)) + | .affine phase label => affineStatement phase label + | .clearOldTable => drainStatement tableTape .clearOldTable .reverseResult + | .reverseResult => + MachineControl.statement id (registerStates ρ d) + (Reduction.MachineTransfer.loopAt (Γ := BoolAlphabet) (Λ := Label d) + (σ := RegisterAmbient ρ d) resultTape (.inr .tableReverse) id false + (.inr .reverseResult) (some (.inr .reverseTable))) + | .reverseTable => + MachineControl.statement id (registerStates ρ d) + (Reduction.MachineTransfer.loopAt (Γ := BoolAlphabet) (Λ := Label d) + (σ := RegisterAmbient ρ d) (.inr .tableReverse) tableTape id false + (.inr .reverseTable) (some (.inr .clearCurrentSize))) + | .clearCurrentSize => + drainStatement (.inr .currentSize) .clearCurrentSize (.affine .multiplySize .seed) + | .drainInputVertex => drainStatement inputVertexTape .drainInputVertex .drainVertexCount + | .drainVertexCount => drainStatement vertexCountTape .drainVertexCount .levelGuard + | .done => .load (normalizeState positive H) .halt + +def outerStatement {d : Nat} (positive : 0 < d) (H : Table (cloudSize d) d) + (label : OuterLabel) : TM2.Stmt Alphabet (Label d) (State ρ d) := + MachineAlphabetTransport.statement alphabet_eq.symm (boolOuterStatement positive H label) + +def tableReturn (d : Nat) : Option (Label d) := some (.inr .clearOldTable) + +def program {d : Nat} (positive : 0 < d) (H : Table (cloudSize d) d) + (_growth : 1 < cloudSize d) : Label d → TM2.Stmt Alphabet (Label d) (State ρ d) := + MachineEmbedding.program (tableReturn d) (MachineExpanderTable.program positive H) + (outerStatement positive H) + +@[simp] theorem program_table {d : Nat} (positive : 0 < d) + (H : Table (cloudSize d) d) (growth : 1 < cloudSize d) + (label : MachineExpanderTable.Label d) : + program (ρ := ρ) positive H growth (.inl label) = + MachineEmbedding.statement (tableReturn d) + (MachineExpanderTable.program positive H label) := rfl + +@[simp] theorem program_outer {d : Nat} (positive : 0 < d) + (H : Table (cloudSize d) d) (growth : 1 < cloudSize d) (label : OuterLabel) : + program (ρ := ρ) positive H growth (.inr label) = outerStatement positive H label := rfl + +def boolView {d : Nat} (positive : 0 < d) (H : Table (cloudSize d) d) + (growth : 1 < cloudSize d) : Label d → TM2.Stmt BoolAlphabet (Label d) (State ρ d) := + MachineAlphabetTransport.program alphabet_eq (program positive H growth) + +@[simp] theorem boolView_outer {d : Nat} (positive : 0 < d) + (H : Table (cloudSize d) d) (growth : 1 < cloudSize d) (label : OuterLabel) : + boolView (ρ := ρ) positive H growth (.inr label) = + boolOuterStatement positive H label := by + change MachineAlphabetTransport.statement alphabet_eq + (MachineAlphabetTransport.statement alphabet_eq.symm + (boolOuterStatement positive H label)) = _ + exact MachineAlphabetTransport.statement_roundtrip alphabet_eq _ + +def tableExecution {d : Nat} (positive : 0 < d) (H : Table (cloudSize d) d) + (growth : 1 < cloudSize d) (extra : ExtraTape → List Bool) + {a b : TM2.Cfg MachineExpanderTable.Alphabet (MachineExpanderTable.Label d) + (MachineExpanderTable.State ρ d)} {budget : Nat} + (execution : StateTransition.EvalsToInTime + (TM2.step (MachineExpanderTable.program positive H)) a (some b) budget) : + StateTransition.EvalsToInTime (TM2.step (program positive H growth)) + (MachineEmbedding.configuration (tableReturn d) () extra a) + (some (MachineEmbedding.configuration (tableReturn d) () extra b)) budget := + MachineComposition.embeddedExecution (tableReturn d) () extra + (MachineExpanderTable.program positive H) (outerStatement positive H) execution + +@[simp] theorem tableExecution_steps {d : Nat} (positive : 0 < d) + (H : Table (cloudSize d) d) (growth : 1 < cloudSize d) + (extra : ExtraTape → List Bool) + {a b : TM2.Cfg MachineExpanderTable.Alphabet (MachineExpanderTable.Label d) + (MachineExpanderTable.State ρ d)} {budget : Nat} + (execution : StateTransition.EvalsToInTime + (TM2.step (MachineExpanderTable.program positive H)) a (some b) budget) : + (tableExecution positive H growth extra execution).steps = execution.steps := rfl + +def tableFrame (word : List Bool) : (tape : MachineExpanderTable.Tape) → + List (MachineExpanderTable.Alphabet tape) + | .inl .table => word + | .inl _ => [] + | .inr _ => [] + +def extraFrame (remaining current : Nat) (levelSuffix : List Bool) : ExtraTape → List Bool + | .remainingLevel => encodeWord remaining ++ levelSuffix + | .currentSize => encodeWord current + | _ => [] + +def boundaryTapes (remaining current : Nat) (word levelSuffix : List Bool) : + (tape : Tape) → List (Alphabet tape) := + MachineEmbedding.tapes (tableFrame word) (extraFrame remaining current levelSuffix) + +def initialTapes (level : Nat) (levelSuffix : List Bool) : + (tape : Tape) → List (Alphabet tape) := + MachineEmbedding.tapes (tableFrame []) + (fun tape => match tape with + | .remainingLevel => encodeWord level ++ levelSuffix + | _ => []) + +def familyTapes {d : Nat} (H : Table (cloudSize d) d) (level : Nat) + (levelSuffix : List Bool) : (tape : Tape) → List (Alphabet tape) := + boundaryTapes 0 (vertexCount (degree d) level) + (encodeWords (rotationWords (family H level))) levelSuffix + +open Turing + +def boolWord : (tape : Tape) → List Bool → List (Alphabet tape) + | .inl (.inl _), word => word + | .inl (.inr _), word => word + | .inr _, word => word + +def toBoolWord : (tape : Tape) → List (Alphabet tape) → List Bool + | .inl (.inl _), word => word + | .inl (.inr _), word => word + | .inr _, word => word + +def fromBoolTapes (base : Tape → List Bool) : (tape : Tape) → List (Alphabet tape) := + fun tape => boolWord tape (base tape) + +def toBoolTapes (base : (tape : Tape) → List (Alphabet tape)) : Tape → List Bool := + fun tape => toBoolWord tape (base tape) + +@[simp] theorem toBoolWord_boolWord (tape : Tape) (word : List Bool) : + toBoolWord tape (boolWord tape word) = word := by + rcases tape with tape | tape + · cases tape <;> rfl + · rfl + +@[simp] theorem boolWord_toBoolWord (tape : Tape) (word : List (Alphabet tape)) : + boolWord tape (toBoolWord tape word) = word := by + rcases tape with tape | tape + · cases tape <;> rfl + · rfl + +@[simp] theorem toBool_fromBool (base : Tape → List Bool) : + toBoolTapes (fromBoolTapes base) = base := by + funext tape + exact toBoolWord_boolWord tape (base tape) + +@[simp] theorem fromBool_toBool (base : (tape : Tape) → List (Alphabet tape)) : + fromBoolTapes (toBoolTapes base) = base := by + funext tape + exact boolWord_toBoolWord tape (base tape) + +theorem transport_tapes_apply {K : Type} {Γ Δ : K → Type} + (h : Γ = Δ) (base : (k : K) → List (Γ k)) (k : K) : + MachineAlphabetTransport.tapes h base k = + Eq.mp (congrArg (fun alphabet => List (alphabet k)) h) (base k) := by + cases h + rfl + +theorem toBoolTapes_eq_transport (base : (tape : Tape) → List (Alphabet tape)) : + toBoolTapes base = MachineAlphabetTransport.tapes alphabet_eq base := by + funext tape + rw [transport_tapes_apply] + rcases tape with tape | tape + · cases tape <;> rfl + · rfl + +theorem fromBoolTapes_eq_transport (base : Tape → List Bool) : + fromBoolTapes base = MachineAlphabetTransport.tapes alphabet_eq.symm base := by + funext tape + rw [transport_tapes_apply] + rcases tape with tape | tape + · cases tape <;> rfl + · rfl + +@[simp] theorem fromBoolTapes_update (base : Tape → List Bool) (tape : Tape) (word : List Bool) : + fromBoolTapes (Function.update base tape word) = + Function.update (fromBoolTapes base) tape (boolWord tape word) := by + funext k + by_cases h : k = tape + · subst k + simp [fromBoolTapes] + · simp [fromBoolTapes, h] + +@[simp] theorem toBoolTapes_update (base : (tape : Tape) → List (Alphabet tape)) + (tape : Tape) (word : List (Alphabet tape)) : + toBoolTapes (Function.update base tape word) = + Function.update (toBoolTapes base) tape (toBoolWord tape word) := by + funext k + by_cases h : k = tape + · subst k + simp [toBoolTapes] + · simp [toBoolTapes, h] + +theorem configuration_fromBool {ρ : Type} {d : Nat} (label : Option (Label d)) + (state : State ρ d) (base : Tape → List Bool) : + MachineAlphabetTransport.configuration alphabet_eq.symm ⟨label, state, base⟩ = + ⟨label, state, fromBoolTapes base⟩ := by + rw [MachineAlphabetTransport.configuration_mk, fromBoolTapes_eq_transport] + +theorem configuration_toBool {ρ : Type} {d : Nat} (label : Option (Label d)) + (state : State ρ d) (base : (tape : Tape) → List (Alphabet tape)) : + MachineAlphabetTransport.configuration alphabet_eq ⟨label, state, base⟩ = + ⟨label, state, toBoolTapes base⟩ := by + rw [MachineAlphabetTransport.configuration_mk, toBoolTapes_eq_transport] + +open Turing MachineComposition +open PCP.ExpanderTables PCP.ExpanderRowControl + +theorem controlStatementInverse {K Λ σ τ : Type} {Γ : K → Type} + (states : σ ≃ τ) (q : TM2.Stmt Γ Λ σ) : + MachineControl.statement id states.symm (MachineControl.statement id states q) = q := by + induction q <;> + simp_all only [MachineControl.statement, Equiv.apply_symm_apply, + Equiv.symm_apply_apply, id_eq] + +theorem controlTrace {K Λ σ τ : Type} {Γ : K → Type} [DecidableEq K] + (states : σ ≃ τ) (target : Λ → TM2.Stmt Γ Λ τ) + (n : Nat) (start finish : TM2.Cfg Γ Λ σ) + (run : (advance (TM2.step (MachineControl.program (Equiv.refl Λ) states.symm target)))^[n] + (some start) = some finish) : + (advance (TM2.step target))^[n] + (some (MachineControl.configuration id states start)) = + some (MachineControl.configuration id states finish) := by + let source := MachineControl.program (Equiv.refl Λ) states.symm target + have roundtrip : MachineControl.program (Equiv.refl Λ) states source = target := by + funext label + change MachineControl.statement id states + (MachineControl.statement id states.symm (target label)) = target label + exact controlStatementInverse states.symm _ + have simulation : ∀ a b, TM2.step source a = some b → + TM2.step target (MachineControl.configuration id states a) = + some (MachineControl.configuration id states b) := by + intro a b hab + have h := MachineControl.step_simulation (Equiv.refl Λ) states source a + rw [roundtrip, hab] at h + exact h + exact liftSuccessfulTrace (TM2.step source) (TM2.step target) + (MachineControl.configuration id states) simulation n start finish run + +theorem controlDrainTrace {K Λ σ τ : Type} [DecidableEq K] + (states : (σ × Option Bool) ≃ τ) (source : K) (again : Λ) (exit : Option Λ) + (target : Λ → TM2.Stmt (fun _ : K => Bool) Λ τ) + (code : target again = MachineControl.statement id states + (MachineDrain.drain source again exit)) + (base : K → List Bool) (ambient : σ) (register : Option Bool) : + (advance (TM2.step target))^[(base source).length + 1] + (some ⟨some again, states (ambient, register), base⟩) = + some ⟨exit, states (ambient, none), Function.update base source []⟩ := by + let raw := MachineControl.program (Equiv.refl Λ) states.symm target + have atRaw : raw again = MachineDrain.drain source again exit := by + change MachineControl.statement id states.symm (target again) = _ + rw [code] + exact controlStatementInverse states _ + have run := MachineDrain.drainTrace source again exit raw atRaw base (base source) ambient register + simp only [Function.update_eq_self] at run + simpa only [MachineControl.configuration, Option.map_some, id_eq, Option.map_id] using + controlTrace states target ((base source).length + 1) _ _ run + +theorem controlTransferTrace {K Λ σ τ : Type} [DecidableEq K] + (states : (σ × Option Bool) ≃ τ) (source destination : K) + (distinct : source ≠ destination) (again : Λ) (exit : Option Λ) + (target : Λ → TM2.Stmt (fun _ : K => Bool) Λ τ) + (code : target again = MachineControl.statement id states + (Reduction.MachineTransfer.loopAt source destination id false again exit)) + (base : K → List Bool) (ambient : σ) (register : Option Bool) : + (advance (TM2.step target))^[(base source).length + 1] + (some ⟨some again, states (ambient, register), base⟩) = + some ⟨exit, states (ambient, none), + Reduction.MachineTransfer.tapesAt source destination base [] + ((base source).reverse ++ base destination)⟩ := by + let raw := MachineControl.program (Equiv.refl Λ) states.symm target + have atRaw : raw again = Reduction.MachineTransfer.loopAt source destination id false again exit := by + change MachineControl.statement id states.symm (target again) = _ + rw [code] + exact controlStatementInverse states _ + have run := Reduction.MachineTransfer.transferAt_fromTapes source destination distinct id false + again exit raw atRaw base ambient register + unfold Reduction.MachineTransfer.nextAt at run + simpa only [MachineControl.configuration, Option.map_some, id_eq, Option.map_id, + List.map_id] using controlTrace states target ((base source).length + 1) _ _ run + +variable {ρ : Type} {d : Nat} + +def clearRegister (state : State ρ d) : State ρ d := + (MachineExpanderTable.clearRegister state.1, state.2) + +@[simp] theorem registerStates_reset (state : State ρ d) : + registerStates ρ d (((registerStates ρ d).symm state).1, none) = + clearRegister state := rfl + +@[simp] theorem clearRegister_idempotent (state : State ρ d) : + clearRegister (clearRegister state) = clearRegister state := rfl + +@[simp] theorem caller_clearRegister (state : State ρ d) : + caller (clearRegister state) = caller state := rfl + +@[simp] theorem clearRegister_position (state : State ρ d) : + (clearRegister state).1.2 = state.1.2 := rfl + +@[simp] theorem clearRegister_register (state : State ρ d) : + (clearRegister state).1.1.2 = none := rfl + +variable [Fintype ρ] + +theorem boolTraceActual (positive : 0 < d) (H : Table (cloudSize d) d) + (growth : 1 < cloudSize d) (n : Nat) + (start finish : TM2.Cfg BoolAlphabet (Label d) (State ρ d)) + (run : (advance (TM2.step (boolView positive H growth)))^[n] (some start) = some finish) : + (advance (TM2.step (program positive H growth)))^[n] + (some (MachineAlphabetTransport.configuration alphabet_eq.symm start)) = + some (MachineAlphabetTransport.configuration alphabet_eq.symm finish) := by + have h := MachineAlphabetTransport.successfulTrace alphabet_eq.symm + (boolView positive H growth) n start finish run + simpa only [boolView, MachineAlphabetTransport.program_symm_roundtrip] using h + +theorem drainBoolTrace (positive : 0 < d) (H : Table (cloudSize d) d) + (growth : 1 < cloudSize d) (source : Tape) (again next : OuterLabel) + (code : boolOuterStatement (ρ := ρ) positive H again = drainStatement source again next) + (base : Tape → List Bool) (state : State ρ d) : + (advance (TM2.step (boolView positive H growth)))^[(base source).length + 1] + (some ⟨some (.inr again), state, base⟩) = + some ⟨some (.inr next), clearRegister state, Function.update base source []⟩ := by + have atLoop : boolView (ρ := ρ) positive H growth (.inr again) = + MachineControl.statement id (registerStates ρ d) + (MachineDrain.drain source (.inr again) (some (.inr next))) := by + rw [boolView_outer, code] + rfl + have h := controlDrainTrace (registerStates ρ d) source (.inr again) (some (.inr next)) + (boolView positive H growth) atLoop base + ((registerStates ρ d).symm state).1 ((registerStates ρ d).symm state).2 + simpa only [Prod.mk.eta, Equiv.apply_symm_apply, registerStates_reset] using h + +theorem transferBoolTrace (positive : 0 < d) (H : Table (cloudSize d) d) + (growth : 1 < cloudSize d) (source destination : Tape) (distinct : source ≠ destination) + (again next : OuterLabel) + (code : boolOuterStatement (ρ := ρ) positive H again = + MachineControl.statement id (registerStates ρ d) + (Reduction.MachineTransfer.loopAt (Γ := BoolAlphabet) source destination id false + (.inr again) (some (.inr next)))) + (base : Tape → List Bool) (state : State ρ d) : + (advance (TM2.step (boolView positive H growth)))^[(base source).length + 1] + (some ⟨some (.inr again), state, base⟩) = + some ⟨some (.inr next), clearRegister state, + Reduction.MachineTransfer.tapesAt source destination base [] + ((base source).reverse ++ base destination)⟩ := by + have atLoop : boolView (ρ := ρ) positive H growth (.inr again) = + MachineControl.statement id (registerStates ρ d) + (Reduction.MachineTransfer.loopAt source destination id false + (.inr again) (some (.inr next))) := by + rw [boolView_outer, code] + have h := controlTransferTrace (registerStates ρ d) source destination distinct + (.inr again) (some (.inr next)) (boolView positive H growth) atLoop base + ((registerStates ρ d).symm state).1 ((registerStates ρ d).symm state).2 + simpa only [Prod.mk.eta, Equiv.apply_symm_apply, registerStates_reset] using h + +def installedTapes (base : Tape → List Bool) (newWord : List Bool) : Tape → List Bool := + Function.update + (Function.update + (Function.update (Function.update base tableTape newWord) resultTape []) + (.inr .tableReverse) []) + (.inr .currentSize) [] + +def cleanedCounterTapes (base : Tape → List Bool) : Tape → List Bool := + Function.update (Function.update base inputVertexTape []) vertexCountTape [] + +theorem installTableBoolTrace (positive : 0 < d) (H : Table (cloudSize d) d) + (growth : 1 < cloudSize d) (base : Tape → List Bool) (newWord : List Bool) + (resultWord : base resultTape = newWord) (reverseEmpty : base (.inr .tableReverse) = []) + (state : State ρ d) : + (advance (TM2.step (boolView positive H growth)))^[ + (base tableTape).length + 2 * newWord.length + (base (.inr .currentSize)).length + 4] + (some ⟨some (.inr .clearOldTable), state, base⟩) = + some ⟨some (.inr (.affine .multiplySize .seed)), clearRegister state, + installedTapes base newWord⟩ := by + let b0 := Function.update base tableTape [] + let b1 := Function.update (Function.update b0 resultTape []) (.inr .tableReverse) newWord.reverse + let b2 := Function.update (Function.update b1 (.inr .tableReverse) []) tableTape newWord + let b3 := Function.update b2 (.inr .currentSize) [] + have h0 := drainBoolTrace positive H growth tableTape .clearOldTable .reverseResult rfl base state + have b0Result : b0 resultTape = newWord := by + simpa [b0, tableTape, resultTape] using resultWord + have b0Reverse : b0 (.inr .tableReverse) = [] := by + simpa [b0, tableTape] using reverseEmpty + have h1 : (advance (TM2.step (boolView positive H growth)))^[newWord.length + 1] + (some ⟨some (.inr .reverseResult), clearRegister state, b0⟩) = + some ⟨some (.inr .reverseTable), clearRegister state, b1⟩ := by + simpa only [b0Result, b0Reverse, List.append_nil, Reduction.MachineTransfer.tapesAt, + clearRegister_idempotent] using + transferBoolTrace positive H growth resultTape (.inr .tableReverse) (by decide) + .reverseResult .reverseTable rfl b0 (clearRegister state) + have b1Reverse : b1 (.inr .tableReverse) = newWord.reverse := by simp [b1] + have b1Table : b1 tableTape = [] := by simp [b1, b0, tableTape, resultTape] + have h2 : (advance (TM2.step (boolView positive H growth)))^[newWord.length + 1] + (some ⟨some (.inr .reverseTable), clearRegister state, b1⟩) = + some ⟨some (.inr .clearCurrentSize), clearRegister state, b2⟩ := by + simpa only [b1Reverse, b1Table, List.reverse_reverse, List.length_reverse, + List.append_nil, Reduction.MachineTransfer.tapesAt, clearRegister_idempotent] using + transferBoolTrace positive H growth (.inr .tableReverse) tableTape (by decide) + .reverseTable .clearCurrentSize rfl b1 (clearRegister state) + have b2Current : b2 (.inr .currentSize) = base (.inr .currentSize) := by + simp [b2, b1, b0, tableTape, resultTape] + have h3 : (advance (TM2.step (boolView positive H growth)))^[ + (base (.inr .currentSize)).length + 1] + (some ⟨some (.inr .clearCurrentSize), clearRegister state, b2⟩) = + some ⟨some (.inr (.affine .multiplySize .seed)), clearRegister state, b3⟩ := by + simpa only [b2Current, clearRegister_idempotent] using + drainBoolTrace positive H growth (.inr .currentSize) .clearCurrentSize + (.affine .multiplySize .seed) rfl b2 (clearRegister state) + have final : b3 = installedTapes base newWord := by + funext tape + rcases tape with table | extra + · rcases table with row | tableExtra + · cases row <;> simp [b3, b2, b1, b0, installedTapes, tableTape, resultTape] + · cases tableExtra <;> simp [b3, b2, b1, b0, installedTapes, tableTape, resultTape] + · cases extra <;> simp [b3, b2, b1, b0, installedTapes, tableTape, resultTape] + rw [show (base tableTape).length + 2 * newWord.length + + (base (.inr .currentSize)).length + 4 = + ((base (.inr .currentSize)).length + 1) + + ((newWord.length + 1) + ((newWord.length + 1) + ((base tableTape).length + 1))) by omega, + Function.iterate_add_apply _ ((base (.inr .currentSize)).length + 1), + Function.iterate_add_apply _ (newWord.length + 1) ((newWord.length + 1) + ((base tableTape).length + 1)), + Function.iterate_add_apply _ (newWord.length + 1) ((base tableTape).length + 1), + h0, h1, h2, h3, final] + +theorem cleanupCountersBoolTrace (positive : 0 < d) (H : Table (cloudSize d) d) + (growth : 1 < cloudSize d) (base : Tape → List Bool) (state : State ρ d) : + (advance (TM2.step (boolView positive H growth)))^[ + (base inputVertexTape).length + (base vertexCountTape).length + 2] + (some ⟨some (.inr .drainInputVertex), state, base⟩) = + some ⟨some (.inr .levelGuard), clearRegister state, cleanedCounterTapes base⟩ := by + have h0 := drainBoolTrace positive H growth inputVertexTape .drainInputVertex .drainVertexCount + rfl base state + have count : (Function.update base inputVertexTape []) vertexCountTape = base vertexCountTape := by + simp [inputVertexTape, vertexCountTape] + have h1 := drainBoolTrace positive H growth vertexCountTape .drainVertexCount .levelGuard + rfl (Function.update base inputVertexTape []) (clearRegister state) + simp only [count, clearRegister_idempotent] at h1 + rw [show (base inputVertexTape).length + (base vertexCountTape).length + 2 = + ((base vertexCountTape).length + 1) + ((base inputVertexTape).length + 1) by omega, + Function.iterate_add_apply, h0] + exact h1 + +theorem installTableTrace (positive : 0 < d) (H : Table (cloudSize d) d) + (growth : 1 < cloudSize d) (base : (tape : Tape) → List (Alphabet tape)) + (newWord : List Bool) (resultWord : toBoolTapes base resultTape = newWord) + (reverseEmpty : toBoolTapes base (.inr .tableReverse) = []) (state : State ρ d) : + (advance (TM2.step (program positive H growth)))^[ + (toBoolTapes base tableTape).length + 2 * newWord.length + + (toBoolTapes base (.inr .currentSize)).length + 4] + (some ⟨some (.inr .clearOldTable), state, base⟩) = + some ⟨some (.inr (.affine .multiplySize .seed)), clearRegister state, + fromBoolTapes (installedTapes (toBoolTapes base) newWord)⟩ := by + have h := installTableBoolTrace positive H growth (toBoolTapes base) newWord resultWord reverseEmpty state + simpa only [configuration_fromBool, fromBool_toBool] using boolTraceActual positive H growth _ _ _ h + +theorem cleanupCountersTrace (positive : 0 < d) (H : Table (cloudSize d) d) + (growth : 1 < cloudSize d) (base : (tape : Tape) → List (Alphabet tape)) + (state : State ρ d) : + (advance (TM2.step (program positive H growth)))^[ + (toBoolTapes base inputVertexTape).length + (toBoolTapes base vertexCountTape).length + 2] + (some ⟨some (.inr .drainInputVertex), state, base⟩) = + some ⟨some (.inr .levelGuard), clearRegister state, + fromBoolTapes (cleanedCounterTapes (toBoolTapes base))⟩ := by + have h := cleanupCountersBoolTrace positive H growth (toBoolTapes base) state + simpa only [configuration_fromBool, fromBool_toBool] using boolTraceActual positive H growth _ _ _ h + +def installTableInTime (positive : 0 < d) (H : Table (cloudSize d) d) + (growth : 1 < cloudSize d) (base : (tape : Tape) → List (Alphabet tape)) + (newWord : List Bool) (resultWord : toBoolTapes base resultTape = newWord) + (reverseEmpty : toBoolTapes base (.inr .tableReverse) = []) (state : State ρ d) : + StateTransition.EvalsToInTime (TM2.step (program positive H growth)) + ⟨some (.inr .clearOldTable), state, base⟩ + (some ⟨some (.inr (.affine .multiplySize .seed)), clearRegister state, + fromBoolTapes (installedTapes (toBoolTapes base) newWord)⟩) + ((toBoolTapes base tableTape).length + 2 * newWord.length + + (toBoolTapes base (.inr .currentSize)).length + 4) where + steps := (toBoolTapes base tableTape).length + 2 * newWord.length + + (toBoolTapes base (.inr .currentSize)).length + 4 + evals_in_steps := installTableTrace positive H growth base newWord resultWord reverseEmpty state + steps_le_m := Nat.le_refl _ + +def cleanupCountersInTime (positive : 0 < d) (H : Table (cloudSize d) d) + (growth : 1 < cloudSize d) (base : (tape : Tape) → List (Alphabet tape)) + (state : State ρ d) : + StateTransition.EvalsToInTime (TM2.step (program positive H growth)) + ⟨some (.inr .drainInputVertex), state, base⟩ + (some ⟨some (.inr .levelGuard), clearRegister state, + fromBoolTapes (cleanedCounterTapes (toBoolTapes base))⟩) + ((toBoolTapes base inputVertexTape).length + (toBoolTapes base vertexCountTape).length + 2) where + steps := (toBoolTapes base inputVertexTape).length + (toBoolTapes base vertexCountTape).length + 2 + evals_in_steps := cleanupCountersTrace positive H growth base state + steps_le_m := Nat.le_refl _ + +end MinUncutGames.Foundations.Complexity.MachineExpanderFamily + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineExpanderTableRows.lean b/lean/OAI/Computability/MinUncut/Machines/MachineExpanderTableRows.lean new file mode 100644 index 0000000000000000000000000000000000000000..6de615fb51de5c3789c707df16c6a0e0132cdabb --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineExpanderTableRows.lean @@ -0,0 +1,813 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineExpanderRowFrames +import OAI.Computability.MinUncut.PCP.ExpanderTableEnumeration + +namespace OAI + +namespace MinUncutGames.Foundations.Complexity.MachineExpanderTable + +open Turing +open PCP.ExpanderTables PCP.ExpanderRowControl PCP.ExpanderTableWords +open PCP.ExpanderTableEnumeration + +private def singleStep {α : Type*} (step : α → Option α) (a b : α) + (h : step a = some b) : StateTransition.EvalsToInTime step a (some b) 1 where + steps := 1 + evals_in_steps := by change step a = some b; exact h + steps_le_m := Nat.le_refl _ + +private def sequence {α : Type*} {step : α → Option α} {a b c : α} {m n : Nat} + (first : StateTransition.EvalsToInTime step a (some b) m) + (second : StateTransition.EvalsToInTime step b (some c) n) : + StateTransition.EvalsToInTime step a (some c) (m + n) := by + simpa only [Nat.add_comm n m] using + StateTransition.EvalsToInTime.trans step m n a b (some c) first second + +private def widen {α : Type*} {step : α → Option α} {a : α} {b : Option α} {m n : Nat} + (run : StateTransition.EvalsToInTime step a b m) (bound : m ≤ n) : + StateTransition.EvalsToInTime step a b n where + toEvalsTo := run.toEvalsTo + steps_le_m := run.steps_le_m.trans bound + +def tableRowData {v d : Nat} (G : Table v (degree d)) (H : Table (cloudSize d) d) + (vertex : Fin v) (position : Position d) : MachineExpanderRow.RowData v d := + MachineExpanderRow.rowData G H vertex (positionPair position).1 (positionPair position).2 + +theorem tableRowData_finalValue {v d : Nat} (G : Table v (degree d)) + (H : Table (cloudSize d) d) (vertex : Fin v) (position : Position d) : + (tableRowData G H vertex position).finalValue = rowValue G H vertex position := rfl + +theorem tableRowData_frame0 {v d : Nat} (G : Table v (degree d)) + (H : Table (cloudSize d) d) (vertex : Fin v) (position : Position d) (output : List Bool) : + MachineExpanderRow.frame0 (tableRowData G H vertex position) output = + rowTapes vertex.val (encodeWords (rotationWords G)) output := by + funext tape + cases tape <;> rfl + +theorem tableRowData_finalFrame {v d : Nat} (G : Table v (degree d)) + (H : Table (cloudSize d) d) (vertex : Fin v) (position : Position d) (output : List Bool) : + MachineExpanderRow.emittedWord .output + (MachineExpanderRow.frame0 (tableRowData G H vertex position) output) + (tableRowData G H vertex position).finalValue = + rowTapes vertex.val (encodeWords (rotationWords G)) + ((encodeWord (rowValue G H vertex position)).reverse ++ output) := by + rw [tableRowData_frame0, tableRowData_finalValue] + funext tape + cases tape <;> simp [MachineExpanderRow.emittedWord, rowTapes] + +variable {ρ : Type} [Fintype ρ] {v d : Nat} + +def rowAfterState (positive : 0 < d) (G : Table v (degree d)) + (H : Table (cloudSize d) d) (vertex : Fin v) (state : State ρ d) : State ρ d := + (MachineExpanderRow.divisionState positive (caller state) + (tableRowData G H vertex state.2).control2 none, state.2) + +omit [Fintype ρ] in +@[simp] theorem rowAfterState_position (positive : 0 < d) (G : Table v (degree d)) + (H : Table (cloudSize d) d) (vertex : Fin v) (state : State ρ d) : + (rowAfterState positive G H vertex state).2 = state.2 := rfl + +omit [Fintype ρ] in +@[simp] theorem caller_rowAfterState (positive : 0 < d) (G : Table v (degree d)) + (H : Table (cloudSize d) d) (vertex : Fin v) (state : State ρ d) : + caller (rowAfterState positive G H vertex state) = caller state := rfl + +def preparedRowInTime (positive : 0 < d) (G : Table v (degree d)) + (H : Table (cloudSize d) d) (vertex : Fin v) (state : State ρ d) + (remaining : Nat) (output countSuffix result : List Bool) : + StateTransition.EvalsToInTime (TM2.step (program positive H)) + ⟨some (.inr .prepareRow), state, + boundaryTapes vertex.val remaining (encodeWords (rotationWords G)) output countSuffix result⟩ + (some ⟨some (.inr .afterRow), rowAfterState positive G H vertex state, + boundaryTapes vertex.val remaining (encodeWords (rotationWords G)) + ((encodeWord (rowValue G H vertex state.2)).reverse ++ output) countSuffix result⟩) + (1 + 80 * ((encodeWords (rotationWords G)).length + 1)) := by + have raw := rowExecution positive H state.2 (extraTapes remaining countSuffix result) + (MachineExpanderRow.rowInTime positive (tableRowData G H vertex state.2) output (caller state)) + have run : StateTransition.EvalsToInTime (TM2.step (program positive H)) + ⟨some (.inl .initialize), prepareState positive H state, + boundaryTapes vertex.val remaining (encodeWords (rotationWords G)) output countSuffix result⟩ + (some ⟨some (.inr .afterRow), rowAfterState positive G H vertex state, + boundaryTapes vertex.val remaining (encodeWords (rotationWords G)) + ((encodeWord (rowValue G H vertex state.2)).reverse ++ output) countSuffix result⟩) + (80 * ((encodeWords (rotationWords G)).length + 1)) := by + rw [tableRowData_finalFrame, tableRowData_frame0] at raw + simpa only [MachineEmbedding.configuration, MachineEmbedding.label, rowReturn, + prepareState, boundaryState, rowAfterState, boundaryTapes, + MachineExpanderRow.RowData.tableLength, MachineExpanderRow.RowData.control0, + tableRowData, MachineExpanderRow.rowData] using raw + exact sequence + (singleStep _ _ _ (prepareRowStep positive H + (boundaryTapes vertex.val remaining (encodeWords (rotationWords G)) output countSuffix result) + state)) run + +structure VertexSuffixRun (positive : 0 < d) (G : Table v (degree d)) + (H : Table (cloudSize d) d) (vertex : Fin v) (state : State ρ d) + (remaining : Nat) (output countSuffix result : List Bool) where + finalState : State ρ d + caller_preserved : caller finalState = caller state + position_zero : finalState.2 = zeroPosition positive + execution : StateTransition.EvalsToInTime (TM2.step (program positive H)) + ⟨some (.inr .prepareRow), state, + boundaryTapes vertex.val remaining (encodeWords (rotationWords G)) output countSuffix result⟩ + (some ⟨some (.inr .vertexGuard), finalState, + boundaryTapes (vertex.val + 1) remaining (encodeWords (rotationWords G)) + (accumulate ((vertexWords G H vertex).drop state.2.val) output) countSuffix result⟩) + ((rowFactor d - state.2.val) * (80 * ((encodeWords (rotationWords G)).length + 1) + 2)) + +private def suffixRun_aux (positive : 0 < d) (G : Table v (degree d)) + (H : Table (cloudSize d) d) (vertex : Fin v) (remaining : Nat) + (countSuffix result : List Bool) (n : Nat) : + (state : State ρ d) → state.2.val + n = rowFactor d → (output : List Bool) → + VertexSuffixRun positive G H vertex state remaining output countSuffix result := by + induction n with + | zero => + intro state count output + have hp := state.2.isLt + exact False.elim (by omega) + | succ n ih => + intro state count output + let after := rowAfterState positive G H vertex state + let nextOutput := (encodeWord (rowValue G H vertex state.2)).reverse ++ output + have row := preparedRowInTime positive G H vertex state remaining output countSuffix result + by_cases last : n = 0 + · have hp : state.2.val + 1 = rowFactor d := by omega + have finish := singleStep _ _ _ (afterRow_last_boundaryStep positive H vertex.val remaining + (encodeWords (rotationWords G)) nextOutput countSuffix result after (by + change ¬ state.2.val + 1 < rowFactor d + omega)) + refine ⟨resetPositionState positive after, ?_, rfl, ?_⟩ + · rfl + · have all := sequence row finish + have words : accumulate ((vertexWords G H vertex).drop state.2.val) output = + nextOutput := by + rw [vertexWords_drop_last G H vertex state.2 hp] + rfl + have budget : rowFactor d - state.2.val = 1 := by omega + rw [words, budget, Nat.one_mul] + exact widen all (by omega) + · have more : state.2.val + 1 < rowFactor d := by omega + let next := advancePositionState positive after + have nextPositionValue : next.2.val = state.2.val + 1 := + nextPosition_val_of_lt positive state.2 more + have nextCount : next.2.val + n = rowFactor d := by omega + let tail := ih next nextCount nextOutput + have advance := singleStep _ _ _ (afterRow_moreStep positive H + (boundaryTapes vertex.val remaining (encodeWords (rotationWords G)) + nextOutput countSuffix result) after more) + have all := sequence (sequence row advance) tail.execution + refine ⟨tail.finalState, ?_, tail.position_zero, ?_⟩ + · exact tail.caller_preserved + · have words : accumulate ((vertexWords G H vertex).drop state.2.val) output = + accumulate ((vertexWords G H vertex).drop next.2.val) nextOutput := by + rw [vertexWords_drop_succ G H vertex state.2, nextPositionValue] + rfl + rw [words] + apply widen all + have hcount : rowFactor d - state.2.val = n + 1 := by omega + have hnext : rowFactor d - next.2.val = n := by omega + rw [hcount, hnext, Nat.add_mul, Nat.one_mul] + omega + +def suffixInTime (positive : 0 < d) (G : Table v (degree d)) + (H : Table (cloudSize d) d) (vertex : Fin v) (state : State ρ d) + (remaining : Nat) (output countSuffix result : List Bool) : + VertexSuffixRun positive G H vertex state remaining output countSuffix result := + suffixRun_aux positive G H vertex remaining countSuffix result + (rowFactor d - state.2.val) state (by have h := state.2.isLt; omega) output + +structure VertexRun (positive : 0 < d) (G : Table v (degree d)) + (H : Table (cloudSize d) d) (vertex : Fin v) (state : State ρ d) + (remaining : Nat) (output countSuffix result : List Bool) where + finalState : State ρ d + caller_preserved : caller finalState = caller state + position_zero : finalState.2 = zeroPosition positive + execution : StateTransition.EvalsToInTime (TM2.step (program positive H)) + ⟨some (.inr .prepareRow), state, + boundaryTapes vertex.val remaining (encodeWords (rotationWords G)) output countSuffix result⟩ + (some ⟨some (.inr .vertexGuard), finalState, + boundaryTapes (vertex.val + 1) remaining (encodeWords (rotationWords G)) + (accumulate (vertexWords G H vertex) output) countSuffix result⟩) + (rowFactor d * (80 * ((encodeWords (rotationWords G)).length + 1) + 2)) + +def vertexInTime (positive : 0 < d) (G : Table v (degree d)) + (H : Table (cloudSize d) d) (vertex : Fin v) (state : State ρ d) + (position : state.2 = zeroPosition positive) + (remaining : Nat) (output countSuffix result : List Bool) : + VertexRun positive G H vertex state remaining output countSuffix result := by + let run := suffixInTime positive G H vertex state remaining output countSuffix result + refine ⟨run.finalState, run.caller_preserved, run.position_zero, ?_⟩ + have zero : state.2.val = 0 := congrArg Fin.val position + simpa only [zero, List.drop_zero, Nat.sub_zero] using run.execution + +open Turing MachineComposition +open PCP.ExpanderTables PCP.ExpanderRowControl PCP.ExpanderTableWords +open PCP.ExpanderTableEnumeration + +def oldTableWord {v d : Nat} (G : Table v (degree d)) : List Bool := + encodeWords (rotationWords G) + +def accumulatedVertices {v d : Nat} (G : Table v (degree d)) + (H : Table (cloudSize d) d) (current : Nat) : List Bool := + accumulate (priorVertices G H current) [] + +@[simp] theorem accumulatedVertices_zero {v d : Nat} (G : Table v (degree d)) + (H : Table (cloudSize d) d) : accumulatedVertices G H 0 = [] := by + simp [accumulatedVertices, accumulate] + +theorem accumulatedVertices_succ {v d : Nat} (G : Table v (degree d)) + (H : Table (cloudSize d) d) (current : Nat) (valid : current < v) : + accumulatedVertices G H (current + 1) = + accumulate (vertexWords G H ⟨current, valid⟩) (accumulatedVertices G H current) := by + simp only [accumulatedVertices, priorVertices_succ G H current valid, accumulate_append] + +theorem accumulatedVertices_full {v d : Nat} (G : Table v (degree d)) + (H : Table (cloudSize d) d) : accumulatedVertices G H v = + (encodeWords (rotationWords (step G H))).reverse := by + simp [accumulatedVertices, accumulate_generatedWords] + +def vertexBodyBudget {v d : Nat} (G : Table v (degree d)) : Nat := + rowFactor d * (80 * ((oldTableWord G).length + 1) + 2) + +def vertexLoopBudget {v d : Nat} (G : Table v (degree d)) (remaining : Nat) : Nat := + remaining * (vertexBodyBudget G + 1) + 1 + +def vertexLoopTapes {v d : Nat} (G : Table v (degree d)) (H : Table (cloudSize d) d) + (current remaining : Nat) (suffix : List Bool) : ∀ tape, List (Alphabet tape) := + boundaryTapes current remaining (oldTableWord G) (accumulatedVertices G H current) suffix [] + +structure VertexLoopRun {v d : Nat} {ρ : Type} [Fintype ρ] + (positive : 0 < d) (G : Table v (degree d)) (H : Table (cloudSize d) d) + (current remaining : Nat) (state : State ρ d) (suffix : List Bool) where + finalState : State ρ d + caller_preserved : caller finalState = caller state + position_zero : finalState.2 = zeroPosition positive + execution : StateTransition.EvalsToInTime (TM2.step (program positive H)) + ⟨some (.inr .vertexGuard), state, vertexLoopTapes G H current remaining suffix⟩ + (some ⟨some (.inr .reverseOutput), finalState, vertexLoopTapes G H v 0 suffix⟩) + (vertexLoopBudget G remaining) + +private def boundarySingleStep {S : Type*} (f : S → Option S) (a b : S) + (h : f a = some b) : StateTransition.EvalsToInTime f a (some b) 1 where + steps := 1 + evals_in_steps := by change f a = some b; exact h + steps_le_m := Nat.le_refl _ + +def vertexLoopInTime {v d : Nat} {ρ : Type} [Fintype ρ] + (positive : 0 < d) (G : Table v (degree d)) (H : Table (cloudSize d) d) + (current remaining : Nat) (state : State ρ d) (suffix : List Bool) + (count : current + remaining = v) (position : state.2 = zeroPosition positive) : + VertexLoopRun positive G H current remaining state suffix := by + induction remaining generalizing current state with + | zero => + have hc : current = v := by omega + subst current + refine ⟨clearRegister state, caller_clearRegister state, ?_, ?_⟩ + · simpa only [clearRegister] using position + · simpa only [vertexLoopBudget, Nat.zero_mul, Nat.zero_add, vertexLoopTapes] using + boundarySingleStep _ _ _ (vertexGuard_boundary_zeroStep positive H v (oldTableWord G) + (accumulatedVertices G H v) suffix [] state) + | succ remaining ih => + have valid : current < v := by omega + let vertex : Fin v := ⟨current, valid⟩ + let body := vertexInTime positive G H vertex (clearRegister state) + (by simpa only [clearRegister] using position) remaining + (accumulatedVertices G H current) suffix [] + have nextCount : current + 1 + remaining = v := by omega + let rest := ih (current + 1) body.finalState nextCount body.position_zero + have output_eq : accumulate (vertexWords G H vertex) + (accumulatedVertices G H current) = accumulatedVertices G H (current + 1) := + (accumulatedVertices_succ G H current valid).symm + let guard := boundarySingleStep _ _ _ + (vertexGuard_boundary_succStep positive H current remaining (oldTableWord G) + (accumulatedVertices G H current) suffix [] state) + have bodyRun : StateTransition.EvalsToInTime (TM2.step (program positive H)) + ⟨some (.inr .prepareRow), clearRegister state, + boundaryTapes current remaining (oldTableWord G) + (accumulatedVertices G H current) suffix []⟩ + (some ⟨some (.inr .vertexGuard), body.finalState, + vertexLoopTapes G H (current + 1) remaining suffix⟩) + (vertexBodyBudget G) := by + simpa only [vertexLoopTapes, vertexBodyBudget, oldTableWord, output_eq] using body.execution + let first := StateTransition.EvalsToInTime.trans (TM2.step (program positive H)) + _ _ _ _ _ guard bodyRun + let all := StateTransition.EvalsToInTime.trans (TM2.step (program positive H)) + _ _ _ _ _ first rest.execution + refine ⟨rest.finalState, ?_, rest.position_zero, ?_⟩ + · exact rest.caller_preserved.trans + (body.caller_preserved.trans (caller_clearRegister state)) + · refine { toEvalsTo := all.toEvalsTo, steps_le_m := ?_ } + have bound := all.steps_le_m + simp only [vertexLoopBudget, Nat.succ_mul] at bound ⊢ + omega + +open Turing +open MachineComposition +open PCP.ExpanderTables PCP.ExpanderRowControl + +variable {ρ : Type} {d : Nat} + +@[simp] theorem clearRegister_position (state : State ρ d) : + (clearRegister state).2 = state.2 := rfl + +@[simp] theorem clearRegister_register (state : State ρ d) : + (clearRegister state).1.2 = none := rfl + +@[simp] theorem clearRegister_idempotent (state : State ρ d) : + clearRegister (clearRegister state) = clearRegister state := rfl + +theorem boundaryTapes_reverse_update (vertex remaining : Nat) + (oldTable output countSuffix result nextOutput nextResult : List Bool) : + Function.update + (Function.update (boundaryTapes vertex remaining oldTable output countSuffix result) + (.inl .output) nextOutput) + (.inr .result) nextResult = + boundaryTapes vertex remaining oldTable nextOutput countSuffix nextResult := by + funext tape + rcases tape with row | extra + · cases row <;> + simp [boundaryTapes, rowTapes, MachineEmbedding.tapes, Function.update] + · cases extra <;> + simp [boundaryTapes, extraTapes, MachineEmbedding.tapes, Function.update] + +variable [Fintype ρ] + +theorem reverseOutputTrace (positive : 0 < d) (H : Table (cloudSize d) d) + (vertex remaining : Nat) (oldTable output countSuffix result : List Bool) + (state : State ρ d) : + (advance (TM2.step (program positive H)))^[output.length + 1] + (some ⟨some (.inr .reverseOutput), state, + boundaryTapes vertex remaining oldTable output countSuffix result⟩) = + some ⟨some (.inr .done), clearRegister state, + boundaryTapes vertex remaining oldTable [] countSuffix (output.reverse ++ result)⟩ := by + induction output generalizing result state with + | nil => + simpa only [List.length_nil, Nat.zero_add, Function.iterate_one, advance_some, + List.reverse_nil, List.nil_append] using + reverseOutput_nilStep positive H + (boundaryTapes vertex remaining oldTable [] countSuffix result) state rfl + | cons symbol output ih => + rw [List.length_cons, Function.iterate_succ_apply] + simp only [advance_some] + rw [reverseOutput_consStep positive H + (boundaryTapes vertex remaining oldTable (symbol :: output) countSuffix result) + state symbol output rfl] + change (advance (TM2.step (program positive H)))^[output.length + 1] + (some ⟨some (.inr .reverseOutput), ((state.1.1, some symbol), state.2), + Function.update + (Function.update + (boundaryTapes vertex remaining oldTable (symbol :: output) countSuffix result) + (.inl .output) output) + (.inr .result) (symbol :: result)⟩) = _ + rw [boundaryTapes_reverse_update] + simpa only [clearRegister, List.reverse_cons, List.append_assoc, + List.singleton_append] using + ih (symbol :: result) ((state.1.1, some symbol), state.2) + +theorem reverseOutputHaltTrace (positive : 0 < d) (H : Table (cloudSize d) d) + (vertex remaining : Nat) (oldTable output countSuffix result : List Bool) + (state : State ρ d) : + (advance (TM2.step (program positive H)))^[output.length + 2] + (some ⟨some (.inr .reverseOutput), state, + boundaryTapes vertex remaining oldTable output countSuffix result⟩) = + some ⟨none, clearRegister state, + boundaryTapes vertex remaining oldTable [] countSuffix (output.reverse ++ result)⟩ := by + rw [show output.length + 2 = (output.length + 1) + 1 by omega, + Function.iterate_succ_apply', + reverseOutputTrace positive H vertex remaining oldTable output countSuffix result state] + exact doneStep positive H + (boundaryTapes vertex remaining oldTable [] countSuffix (output.reverse ++ result)) + (clearRegister state) + +def reverseOutputInTime (positive : 0 < d) (H : Table (cloudSize d) d) + (vertex remaining : Nat) (oldTable output countSuffix result : List Bool) + (state : State ρ d) : + StateTransition.EvalsToInTime (TM2.step (program positive H)) + ⟨some (.inr .reverseOutput), state, + boundaryTapes vertex remaining oldTable output countSuffix result⟩ + (some ⟨some (.inr .done), clearRegister state, + boundaryTapes vertex remaining oldTable [] countSuffix (output.reverse ++ result)⟩) + (output.length + 1) where + steps := output.length + 1 + evals_in_steps := reverseOutputTrace positive H vertex remaining oldTable output countSuffix result state + steps_le_m := Nat.le_refl _ + +def reverseOutputHaltInTime (positive : 0 < d) (H : Table (cloudSize d) d) + (vertex remaining : Nat) (oldTable output countSuffix result : List Bool) + (state : State ρ d) : + StateTransition.EvalsToInTime (TM2.step (program positive H)) + ⟨some (.inr .reverseOutput), state, + boundaryTapes vertex remaining oldTable output countSuffix result⟩ + (some ⟨none, clearRegister state, + boundaryTapes vertex remaining oldTable [] countSuffix (output.reverse ++ result)⟩) + (output.length + 2) where + steps := output.length + 2 + evals_in_steps := reverseOutputHaltTrace positive H vertex remaining oldTable output countSuffix result state + steps_le_m := Nat.le_refl _ + +open Turing MachineComposition +open PCP.ExpanderTables PCP.ExpanderRowControl PCP.ExpanderTableWords +open PCP.ExpanderTableEnumeration + +def completeBudget {v d : Nat} (G : Table v (degree d)) (H : Table (cloudSize d) d) : Nat := + 1 + vertexLoopBudget G v + ((encodeWords (rotationWords (step G H))).length + 2) + +def timeCoefficient (d : Nat) : Nat := + rowFactor d * (rowFactor d + 1) + 82 * rowFactor d + 5 + +noncomputable def timePolynomial (d : Nat) : Polynomial Nat := + Polynomial.C (timeCoefficient d) * (Polynomial.X + 1) ^ 2 + +theorem vertices_le_word_length {v d : Nat} (positive : 0 < d) + (G : Table v (degree d)) : v ≤ (oldTableWord G).length := by + have hq : 1 ≤ degree d := Nat.mul_pos positive positive + have hv : v ≤ v * degree d := by simpa using Nat.mul_le_mul_left v hq + have hr : v * degree d ≤ (oldTableWord G).length := by + simp only [oldTableWord, encodeWords_length, rotationWords_length] + omega + exact hv.trans hr + +theorem completeBudget_le {v d : Nat} (positive : 0 < d) + (G : Table v (degree d)) (H : Table (cloudSize d) d) : + completeBudget G H ≤ (timePolynomial d).eval (oldTableWord G).length := by + let L := (oldTableWord G).length + let M := rowFactor d + have vBound : v ≤ L + 1 := (vertices_le_word_length positive G).trans (Nat.le_succ L) + have emitBound : 80 * (L + 1) + 2 ≤ 82 * (L + 1) := by omega + have bodyBound : vertexBodyBudget G + 1 ≤ (82 * M + 1) * (L + 1) := by + have mulBound := Nat.mul_le_mul_left M emitBound + change M * (80 * (L + 1) + 2) + 1 ≤ _ + nlinarith + have iterations := Nat.mul_le_mul vBound bodyBound + have loopBound : v * (vertexBodyBudget G + 1) ≤ (82 * M + 1) * (L + 1)^2 := by + calc + _ ≤ (L + 1) * ((82 * M + 1) * (L + 1)) := iterations + _ = _ := by ring + have rowBound : v * M ≤ M * (L + 1) := by + simpa only [Nat.mul_comm v M] using Nat.mul_le_mul_left M vBound + have rowSuccBound : v * M + 1 ≤ (M + 1) * (L + 1) := by nlinarith + have productBound := Nat.mul_le_mul rowBound rowSuccBound + have lengthBound : (encodeWords (rotationWords (step G H))).length ≤ + M * (M + 1) * (L + 1)^2 := by + calc + _ ≤ (v * M) * (v * M + 1) := by + simpa only [generatedWords_eq_rotationWords] using encode_generatedWords_length_le G H + _ ≤ (M * (L + 1)) * ((M + 1) * (L + 1)) := productBound + _ = _ := by ring + have oneBound : 1 ≤ (L + 1)^2 := by nlinarith + have combined := Nat.add_le_add loopBound lengthBound + simp only [timePolynomial, Polynomial.eval_mul, Polynomial.eval_C, Polynomial.eval_pow, + Polynomial.eval_add, Polynomial.eval_X, Polynomial.eval_one] + change completeBudget G H ≤ (M * (M + 1) + 82 * M + 5) * (L + 1)^2 + unfold completeBudget vertexLoopBudget + nlinarith + +structure TableRun {v d : Nat} {ρ : Type} [Fintype ρ] + (positive : 0 < d) (G : Table v (degree d)) (H : Table (cloudSize d) d) + (state : State ρ d) (suffix : List Bool) where + finalState : State ρ d + caller_preserved : caller finalState = caller state + position_zero : finalState.2 = zeroPosition positive + execution : StateTransition.EvalsToInTime (TM2.step (program positive H)) + ⟨some (.inr .initialize), state, initialTapes v (oldTableWord G) suffix⟩ + (some ⟨none, finalState, + finalTapes v (oldTableWord G) (encodeWords (rotationWords (step G H))) suffix⟩) + ((timePolynomial d).eval (oldTableWord G).length) + +private def initializeInTime {v d : Nat} {ρ : Type} [Fintype ρ] + (positive : 0 < d) (G : Table v (degree d)) (H : Table (cloudSize d) d) + (state : State ρ d) (suffix : List Bool) : + StateTransition.EvalsToInTime (TM2.step (program positive H)) + ⟨some (.inr .initialize), state, initialTapes v (oldTableWord G) suffix⟩ + (some ⟨some (.inr .vertexGuard), initialState positive H (caller state), + vertexLoopTapes G H 0 v suffix⟩) 1 where + steps := 1 + evals_in_steps := by + change TM2.step (program (ρ := ρ) positive H) + ⟨some (.inr .initialize), state, initialTapes v (oldTableWord G) suffix⟩ = + some ⟨some (.inr .vertexGuard), initialState positive H (caller state), + vertexLoopTapes G H 0 v suffix⟩ + simpa only [vertexLoopTapes, accumulatedVertices_zero] using + initialize_boundaryStep positive H v (oldTableWord G) suffix state + steps_le_m := Nat.le_refl _ + +def tableInTime {v d : Nat} {ρ : Type} [Fintype ρ] + (positive : 0 < d) (G : Table v (degree d)) (H : Table (cloudSize d) d) + (state : State ρ d) (suffix : List Bool) : TableRun positive G H state suffix := by + let loop := vertexLoopInTime positive G H 0 v + (initialState positive H (caller state)) suffix (by omega) rfl + let initialRun := initializeInTime positive G H state suffix + have finish : StateTransition.EvalsToInTime (TM2.step (program positive H)) + ⟨some (.inr .reverseOutput), loop.finalState, vertexLoopTapes G H v 0 suffix⟩ + (some ⟨none, clearRegister loop.finalState, + finalTapes v (oldTableWord G) (encodeWords (rotationWords (step G H))) suffix⟩) + ((encodeWords (rotationWords (step G H))).length + 2) := by + simpa only [vertexLoopTapes, finalTapes, accumulatedVertices_full, List.reverse_reverse, + List.append_nil, List.length_reverse] using + reverseOutputHaltInTime positive H v 0 (oldTableWord G) + (accumulatedVertices G H v) suffix [] loop.finalState + let first := StateTransition.EvalsToInTime.trans (TM2.step (program positive H)) + _ _ _ _ _ initialRun loop.execution + let all := StateTransition.EvalsToInTime.trans (TM2.step (program positive H)) + _ _ _ _ _ first finish + refine ⟨clearRegister loop.finalState, ?_, ?_, ?_⟩ + · exact (caller_clearRegister loop.finalState).trans loop.caller_preserved + · simpa only [clearRegister] using loop.position_zero + · refine { toEvalsTo := all.toEvalsTo, steps_le_m := ?_ } + have bound := all.steps_le_m + have polynomialBound := completeBudget_le positive G H + unfold completeBudget at polynomialBound + omega + +end MinUncutGames.Foundations.Complexity.MachineExpanderTable + +namespace MinUncutGames.Foundations.Complexity.MachineExpanderFamily + +open PCP.ExpanderTables PCP.ExpanderRowControl PCP.ExpanderTableWords + +def cycleWords (remaining : Nat) (word current vertex count result suffix : List Bool) : + Tape → List Bool + | .inl (.inl .table) => word + | .inl (.inl .inputVertex) => vertex + | .inl (.inr .vertexCount) => count + | .inl (.inr .result) => result + | .inr .remainingLevel => encodeWord remaining ++ suffix + | .inr .currentSize => current + | _ => [] + +def cycleTapes (remaining : Nat) (word current vertex count result suffix : List Bool) : + (tape : Tape) → List (Alphabet tape) := + fromBoolTapes (cycleWords remaining word current vertex count result suffix) + +@[simp] theorem toBool_cycleTapes (remaining : Nat) + (word current vertex count result suffix : List Bool) : + toBoolTapes (cycleTapes remaining word current vertex count result suffix) = + cycleWords remaining word current vertex count result suffix := toBool_fromBool _ + +theorem boundaryTapes_eq_cycleTapes (remaining current : Nat) (word suffix : List Bool) : + boundaryTapes remaining current word suffix = + cycleTapes remaining word (encodeWord current) [] [] [] suffix := by + funext tape + rcases tape with tape | tape + · rcases tape with row | extra + · cases row <;> rfl + · cases extra <;> rfl + · cases tape <;> rfl + +def copyFrame (remaining current : Nat) (word suffix : List Bool) : + (tape : Tape) → List (Alphabet tape) := + MachineEmbedding.tapes (MachineExpanderTable.initialTapes current word []) + (extraFrame remaining current suffix) + +def returnFrame (remaining current : Nat) (oldWord newWord suffix : List Bool) : + (tape : Tape) → List (Alphabet tape) := + MachineEmbedding.tapes (MachineExpanderTable.finalTapes current oldWord newWord []) + (extraFrame remaining current suffix) + +def installedFrame (remaining current : Nat) (newWord suffix : List Bool) : + (tape : Tape) → List (Alphabet tape) := + cycleTapes remaining newWord [] (encodeWord current) (encodeWord 0) [] suffix + +def multipliedFrame (d remaining current : Nat) (newWord suffix : List Bool) : + (tape : Tape) → List (Alphabet tape) := + cycleTapes remaining newWord (encodeWord (cloudSize d * current)) + (encodeWord current) (encodeWord 0) [] suffix + +theorem copyFrame_eq_cycleTapes (remaining current : Nat) (word suffix : List Bool) : + copyFrame remaining current word suffix = + cycleTapes remaining word (encodeWord current) [] (encodeWord current) [] suffix := by + funext tape + rcases tape with tape | tape + · rcases tape with row | extra + · cases row <;> rfl + · cases extra <;> simp [copyFrame, MachineEmbedding.tapes, + MachineExpanderTable.initialTapes, MachineExpanderTable.extraTapes, + cycleTapes, fromBoolTapes, boolWord, cycleWords] + · cases tape <;> rfl + +theorem returnFrame_eq_cycleTapes (remaining current : Nat) + (oldWord newWord suffix : List Bool) : + returnFrame remaining current oldWord newWord suffix = + cycleTapes remaining oldWord (encodeWord current) (encodeWord current) + (encodeWord 0) newWord suffix := by + funext tape + rcases tape with tape | tape + · rcases tape with row | extra + · cases row <;> rfl + · cases extra <;> simp [returnFrame, MachineEmbedding.tapes, + MachineExpanderTable.finalTapes, MachineExpanderTable.boundaryTapes, + MachineExpanderTable.extraTapes, cycleTapes, fromBoolTapes, boolWord, cycleWords] + · cases tape <;> rfl + +theorem copyFrame_eq_update (remaining current : Nat) (word suffix : List Bool) : + Function.update (boundaryTapes remaining current word suffix) + vertexCountTape (encodeWord current) = copyFrame remaining current word suffix := by + rw [boundaryTapes_eq_cycleTapes, copyFrame_eq_cycleTapes] + funext tape + rcases tape with tape | tape + · rcases tape with row | extra + · cases row <;> rfl + · cases extra <;> rfl + · cases tape <;> rfl + +theorem multipliedFrame_eq_update (d remaining current : Nat) (word suffix : List Bool) : + Function.update (installedFrame remaining current word suffix) + (.inr .currentSize) (encodeWord (cloudSize d * current)) = + multipliedFrame d remaining current word suffix := by + funext tape + rcases tape with tape | tape + · rcases tape with row | extra + · cases row <;> rfl + · cases extra <;> rfl + · cases tape <;> rfl + +end MinUncutGames.Foundations.Complexity.MachineExpanderFamily + +namespace MinUncutGames.Foundations.Complexity.MachineExpanderFamilyBounds + +open PCP.ExpanderTables PCP.ExpanderRowControl PCP.ExpanderTableWords + +noncomputable def resizeCost {v d : Nat} (G : Table v (degree d)) + (H : Table (cloudSize d) d) : Nat := + (MachineExpanderTable.timePolynomial d).eval (MachineExpanderTable.oldTableWord G).length + + 6 * v + (MachineExpanderTable.oldTableWord G).length + + 2 * (encodeWords (rotationWords (step G H))).length + 15 + +def resizeCoefficient (d : Nat) : Nat := + MachineExpanderTable.timeCoefficient d * (degree d + 1) ^ 4 + + 3 * (degree d + 1) ^ 2 + 21 + +theorem wordLength_add_one_le {v q N : Nat} (G : Table v q) (hv : v ≤ N) : + (encodeWords (rotationWords G)).length + 1 ≤ (q + 1)^2 * (N + 1)^2 := by + have hlength := encode_rotationWords_length_le G + have hrow : v * q + 1 ≤ (q + 1) * (N + 1) := by + have h := Nat.mul_le_mul_right q hv + nlinarith + calc + _ ≤ (v * q + 1)^2 := by nlinarith + _ ≤ ((q + 1) * (N + 1))^2 := Nat.pow_le_pow_left hrow 2 + _ = _ := by ring + +theorem resizeCost_le {v d : Nat} (G : Table v (degree d)) + (H : Table (cloudSize d) d) (N : Nat) (hv : v ≤ N) + (hnext : v * cloudSize d ≤ N) : + resizeCost G H ≤ resizeCoefficient d * (N + 1)^4 := by + let oldL := (MachineExpanderTable.oldTableWord G).length + let newL := (encodeWords (rotationWords (step G H))).length + have oldBound : oldL + 1 ≤ (degree d + 1)^2 * (N + 1)^2 := + wordLength_add_one_le G hv + have newBound : newL + 1 ≤ (degree d + 1)^2 * (N + 1)^2 := + wordLength_add_one_le (step G H) hnext + have timeBound : (MachineExpanderTable.timePolynomial d).eval oldL ≤ + MachineExpanderTable.timeCoefficient d * (degree d + 1)^4 * (N + 1)^4 := by + simp only [MachineExpanderTable.timePolynomial, Polynomial.eval_mul, + Polynomial.eval_C, Polynomial.eval_pow, Polynomial.eval_add, + Polynomial.eval_X, Polynomial.eval_one] + calc + _ ≤ MachineExpanderTable.timeCoefficient d * + ((degree d + 1)^2 * (N + 1)^2)^2 := + Nat.mul_le_mul_left _ (Nat.pow_le_pow_left oldBound 2) + _ = _ := by ring + have pow24 : (N + 1)^2 ≤ (N + 1)^4 := + Nat.pow_le_pow_right (Nat.succ_pos N) (by decide) + have overheadBound : oldL + 2 * newL ≤ + 3 * (degree d + 1)^2 * (N + 1)^4 := by + have h := Nat.mul_le_mul_left ((degree d + 1)^2) pow24 + calc + _ ≤ 3 * ((degree d + 1)^2 * (N + 1)^2) := by omega + _ ≤ 3 * ((degree d + 1)^2 * (N + 1)^4) := Nat.mul_le_mul_left 3 h + _ = _ := by ring + have npow : N + 1 ≤ (N + 1)^4 := by + simpa only [pow_one] using + Nat.pow_le_pow_right (Nat.succ_pos N) (show 1 ≤ 4 by decide) + have linearBound : 6 * v + 15 ≤ 21 * (N + 1)^4 := by omega + change (MachineExpanderTable.timePolynomial d).eval oldL + 6 * v + oldL + + 2 * newL + 15 ≤ _ + unfold resizeCoefficient + nlinarith only [timeBound, overheadBound, linearBound] + +theorem vertexCount_monotone {q : Nat} (positive : 0 < q) : + Monotone (vertexCount q) := by + intro m n hmn + rw [vertexCount_eq, vertexCount_eq] + exact Nat.pow_le_pow_right (Nat.mul_pos positive positive) hmn + +theorem level_le_vertexCount {q : Nat} (growth : 1 < q * q) (level : Nat) : + level ≤ vertexCount q level := by + have positive : 0 < q := by nlinarith + induction level with + | zero => exact Nat.zero_le _ + | succ level ih => + have hpos := vertexCount_positive positive level + have hmul := Nat.mul_le_mul_left (vertexCount q level) + (show 2 ≤ q * q by omega) + change level + 1 ≤ vertexCount q level * (q * q) + nlinarith + +noncomputable def resizeSum {d : Nat} (H : Table (cloudSize d) d) (level : Nat) : Nat := + ∑ i ∈ Finset.range level, resizeCost (family H i) H + +@[simp] theorem resizeSum_zero {d : Nat} (H : Table (cloudSize d) d) : + resizeSum H 0 = 0 := by simp [resizeSum] + +theorem resizeSum_succ {d : Nat} (H : Table (cloudSize d) d) (level : Nat) : + resizeSum H (level + 1) = resizeSum H level + resizeCost (family H level) H := by + simp only [resizeSum, Finset.sum_range_succ] + +theorem resizeSum_add {d : Nat} (H : Table (cloudSize d) d) (start count : Nat) : + resizeSum H (start + count) = resizeSum H start + + ∑ i ∈ Finset.range count, resizeCost (family H (start + i)) H := + Finset.sum_range_add (fun i => resizeCost (family H i) H) start count + +noncomputable def familyBudget {d : Nat} (H : Table (cloudSize d) d) (level : Nat) : Nat := + resizeSum H level + level + 3 + +@[simp] theorem familyBudget_zero {d : Nat} (H : Table (cloudSize d) d) : + familyBudget H 0 = 3 := by simp [familyBudget] + +theorem familyBudget_succ {d : Nat} (H : Table (cloudSize d) d) (level : Nat) : + familyBudget H (level + 1) = + familyBudget H level + resizeCost (family H level) H + 1 := by + simp only [familyBudget, resizeSum_succ] + omega + +theorem resizeSum_le {d : Nat} (H : Table (cloudSize d) d) + (growth : 1 < cloudSize d) (level : Nat) : + resizeSum H level ≤ resizeCoefficient d * (vertexCount (degree d) level + 1)^5 := by + let N := vertexCount (degree d) level + have positive : 0 < degree d := by + have h : 1 < degree d * degree d := growth + nlinarith + have hmono := vertexCount_monotone positive + have hlevel : level ≤ N := level_le_vertexCount growth level + have eachBound : ∀ i ∈ Finset.range level, + resizeCost (family H i) H ≤ resizeCoefficient d * (N + 1)^4 := by + intro i hi + have hi' : i < level := Finset.mem_range.mp hi + apply resizeCost_le (family H i) H N + · exact hmono (by omega) + · exact hmono (show i + 1 ≤ level by omega) + have sumBound : resizeSum H level ≤ level * (resizeCoefficient d * (N + 1)^4) := by + calc + _ ≤ ∑ _i ∈ Finset.range level, resizeCoefficient d * (N + 1)^4 := + Finset.sum_le_sum eachBound + _ = _ := by simp + calc + _ ≤ level * (resizeCoefficient d * (N + 1)^4) := sumBound + _ ≤ (N + 1) * (resizeCoefficient d * (N + 1)^4) := + Nat.mul_le_mul_right _ (hlevel.trans (Nat.le_succ N)) + _ = _ := by ring + +theorem familyBudget_le {d : Nat} (H : Table (cloudSize d) d) + (growth : 1 < cloudSize d) (level : Nat) : + familyBudget H level ≤ + (resizeCoefficient d + 4) * (vertexCount (degree d) level + 1)^5 := by + have hsum := resizeSum_le H growth level + have hlevel := level_le_vertexCount growth level + have hpow : vertexCount (degree d) level + 1 ≤ + (vertexCount (degree d) level + 1)^5 := by + simpa only [pow_one] using Nat.pow_le_pow_right + (Nat.succ_pos (vertexCount (degree d) level)) (show 1 ≤ 5 by decide) + have overhead : level + 3 ≤ 4 * (vertexCount (degree d) level + 1)^5 := by omega + unfold familyBudget + nlinarith only [hsum, overhead] + +theorem paddedSize_le_succ_input (k : Nat) : + PCP.PreprocessingLevels.paddedSize k ≤ PCP.ExpanderFamily.growth * (k + 1) := by + by_cases hk : k = 0 + · subst k + have h := PCP.ExpanderFamily.growth_gt_one + simp only [PCP.PreprocessingLevels.paddedSize_zero, Nat.zero_add, Nat.mul_one] + omega + · exact (PCP.PreprocessingLevels.paddedSize_bounds (Nat.pos_of_ne_zero hk)).2.trans + (Nat.mul_le_mul_left _ (Nat.le_succ k)) + +def inputCoefficient : Nat := + (resizeCoefficient PCP.Expanders.baseDegree + 4) * (PCP.ExpanderFamily.growth + 1)^5 + +theorem familyBudget_at_boundedLevel_le + (H : Table (cloudSize PCP.Expanders.baseDegree) PCP.Expanders.baseDegree) (k : Nat) : + familyBudget H (PCP.PreprocessingLevels.boundedLevel k) ≤ inputCoefficient * (k + 1)^5 := by + have hg : cloudSize PCP.Expanders.baseDegree = PCP.ExpanderFamily.growth := by + unfold cloudSize degree PCP.ExpanderFamily.growth + ring + have growth : 1 < cloudSize PCP.Expanders.baseDegree := by + rw [hg] + exact PCP.ExpanderFamily.growth_gt_one + have bound := familyBudget_le H growth (PCP.PreprocessingLevels.boundedLevel k) + rw [PCP.PreprocessingLevels.table_vertexCount_eq_paddedSize] at bound + have sizeBound : PCP.PreprocessingLevels.paddedSize k + 1 ≤ + (PCP.ExpanderFamily.growth + 1) * (k + 1) := by + have h := paddedSize_le_succ_input k + nlinarith + calc + _ ≤ (resizeCoefficient PCP.Expanders.baseDegree + 4) * + (PCP.PreprocessingLevels.paddedSize k + 1)^5 := bound + _ ≤ (resizeCoefficient PCP.Expanders.baseDegree + 4) * + ((PCP.ExpanderFamily.growth + 1) * (k + 1))^5 := + Nat.mul_le_mul_left _ (Nat.pow_le_pow_left sizeBound 5) + _ = _ := by unfold inputCoefficient; ring + +end MinUncutGames.Foundations.Complexity.MachineExpanderFamilyBounds + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineFiniteAlphabet.lean b/lean/OAI/Computability/MinUncut/Machines/MachineFiniteAlphabet.lean new file mode 100644 index 0000000000000000000000000000000000000000..53ba89f602e2c9418f4054e7aba7439d803203dd --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineFiniteAlphabet.lean @@ -0,0 +1,860 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.LoopInitialization + +namespace OAI + +section +namespace MinUncutGames.Foundations.Complexity.MachineFiniteAlphabet + +open Turing + +def FiniteAlphabet (M : FinTM2) : Prop := ∀ k, Finite (M.Γ k) + +theorem input_finite (M : FinTM2) : Finite (M.Γ M.k₀) := by + let := M.Γk₀Fin + infer_instance + +theorem of_homogeneous (M : FinTM2) {α : Type} [Finite α] + (alphabet : ∀ k, M.Γ k = α) : FiniteAlphabet M := by + intro k + rw [alphabet k] + infer_instance + +theorem of_bool (M : FinTM2) (alphabet : ∀ k, M.Γ k = Bool) : FiniteAlphabet M := + of_homogeneous M alphabet + +theorem of_equiv (M : FinTM2) {α : Type} [Finite α] + (alphabet : ∀ k, M.Γ k ≃ α) : FiniteAlphabet M := by + intro k + exact Finite.of_equiv α (alphabet k).symm + +theorem symbols_finite (M : FinTM2) (finiteAlphabet : FiniteAlphabet M) : + Finite (Σ k, M.Γ k) := by + let := M.kFin + let : ∀ k, Finite (M.Γ k) := finiteAlphabet + infer_instance + +theorem sequential_machine (first second : FinTM2) + (relabel : first.Γ first.k₁ → second.Γ second.k₀) + (fallback : second.Γ second.k₀) + (hfirst : FiniteAlphabet first) (hsecond : FiniteAlphabet second) : + FiniteAlphabet (MachineSequential.machine first second relabel fallback) := by + intro tape + rcases tape with tape | tape | tape + · exact hfirst tape + · exact hsecond tape + · exact input_finite second + +theorem compose {α β γ αΓ βΓ γΓ : Type} + {ea : α → List αΓ} {eb : β → List βΓ} {ec : γ → List γΓ} + {f : α → β} {g : β → γ} + (first : TM2ComputableInPolyTime ea eb f) + (second : TM2ComputableInPolyTime eb ec g) (fallback : βΓ) + (hfirst : FiniteAlphabet first.tm) (hsecond : FiniteAlphabet second.tm) : + FiniteAlphabet (MachineSequential.compose first second fallback).tm := by + exact sequential_machine first.tm second.tm + (fun symbol => second.inputAlphabet.symm (first.outputAlphabet symbol)) + (second.inputAlphabet.symm fallback) hfirst hsecond + +theorem composeBits {α β γ : Type} + {ea : α → List Bool} {eb : β → List Bool} {ec : γ → List Bool} + {f : α → β} {g : β → γ} + (first : TM2ComputableInPolyTime ea eb f) + (second : TM2ComputableInPolyTime eb ec g) + (hfirst : FiniteAlphabet first.tm) (hsecond : FiniteAlphabet second.tm) : + FiniteAlphabet (MachineSequential.composeBits first second).tm := + compose first second false hfirst hsecond + +theorem repeat_machine (body : FinTM2) + (input : body.Γ body.k₀ ≃ Bool) (output : body.Γ body.k₁ ≃ Bool) + (hbody : FiniteAlphabet body) : + FiniteAlphabet (MachineRepeat.machine body input output) := by + intro tape + cases tape with + | inl tape => exact hbody tape + | inr _ => exact input_finite body + +end MinUncutGames.Foundations.Complexity.MachineFiniteAlphabet + +end +section +namespace MinUncutGames.Foundations.PCP.AlphabetTable + +open MinUncutGames.Foundations.Complexity + +theorem Driver.finiteAlphabet (q : Nat) : + MachineFiniteAlphabet.FiniteAlphabet (Driver.machine q) := by + intro k + change Finite Bool + infer_instance + +theorem Runtime.finiteAlphabet (q : Nat) : + MachineFiniteAlphabet.FiniteAlphabet (Runtime.tablePolynomialTime q).tm := + Driver.finiteAlphabet q + +end MinUncutGames.Foundations.PCP.AlphabetTable + +end +section +namespace MinUncutGames.Foundations.Complexity.MachineStateEquiv + +open Turing.TM2 + +variable {K Λ σ τ : Type} {Γ : K → Type} + +abbrev statement (e : σ ≃ τ) : Stmt Γ Λ σ → Stmt Γ Λ τ := + MachineControl.statement (id : Λ → Λ) e + +@[simp] theorem statement_symm_statement (e : σ ≃ τ) (q : Stmt Γ Λ σ) : + statement e.symm (statement e q) = q := by + induction q <;> + simp_all only [statement, MachineControl.statement, Equiv.symm_symm, + Equiv.symm_apply_apply, id_eq] + +def configuration (e : σ ≃ τ) (c : Cfg Γ Λ σ) : Cfg Γ Λ τ := + ⟨c.l, e c.var, c.stk⟩ + +@[simp] theorem configuration_label (e : σ ≃ τ) (c : Cfg Γ Λ σ) : + (configuration e c).l = c.l := rfl + +@[simp] theorem configuration_state (e : σ ≃ τ) (c : Cfg Γ Λ σ) : + (configuration e c).var = e c.var := rfl + +@[simp] theorem configuration_tapes (e : σ ≃ τ) (c : Cfg Γ Λ σ) : + (configuration e c).stk = c.stk := rfl + +@[simp] theorem configuration_symm_configuration (e : σ ≃ τ) (c : Cfg Γ Λ σ) : + configuration e.symm (configuration e c) = c := by + cases c + simp only [configuration, Equiv.symm_apply_apply] + +@[simp] theorem configuration_configuration_symm (e : σ ≃ τ) (c : Cfg Γ Λ τ) : + configuration e (configuration e.symm c) = c := by + cases c + simp only [configuration, Equiv.apply_symm_apply] + +def configurationEquiv (e : σ ≃ τ) : Cfg Γ Λ σ ≃ Cfg Γ Λ τ where + toFun := configuration e + invFun := configuration e.symm + left_inv := configuration_symm_configuration e + right_inv := configuration_configuration_symm e + +@[simp] theorem configurationEquiv_apply (e : σ ≃ τ) (c : Cfg Γ Λ σ) : + configurationEquiv e c = configuration e c := rfl + +@[simp] theorem control_configuration (e : σ ≃ τ) (c : Cfg Γ Λ σ) : + MachineControl.configuration (id : Λ → Λ) e c = configuration e c := by + cases c + simp [MachineControl.configuration, configuration] + +def program (e : σ ≃ τ) (source : Λ → Stmt Γ Λ σ) : Λ → Stmt Γ Λ τ := + fun l => statement e (source l) + +@[simp] theorem program_symm_program (e : σ ≃ τ) (source : Λ → Stmt Γ Λ σ) : + program e.symm (program e source) = source := by + funext l + exact statement_symm_statement e (source l) + +theorem statementPushBound (e : σ ≃ τ) (q : Stmt Γ Λ σ) : + Runtime.statementPushBound (statement e q) = Runtime.statementPushBound q := by + induction q <;> + simp_all only [statement, MachineControl.statement, Runtime.statementPushBound] + +theorem supportsStmt_iff (e : σ ≃ τ) (S : Finset Λ) (q : Stmt Γ Λ σ) : + SupportsStmt S (statement e q) ↔ SupportsStmt S q := by + induction q with + | push k f next ih => + simpa only [statement, MachineControl.statement, SupportsStmt] using ih + | peek k f next ih => + simpa only [statement, MachineControl.statement, SupportsStmt] using ih + | pop k f next ih => + simpa only [statement, MachineControl.statement, SupportsStmt] using ih + | load f next ih => + simpa only [statement, MachineControl.statement, SupportsStmt] using ih + | branch f yes no ihYes ihNo => + simp only [statement, MachineControl.statement, SupportsStmt, ihYes, ihNo] + | goto f => + change (∀ state : τ, f (e.symm state) ∈ S) ↔ ∀ state : σ, f state ∈ S + constructor + · intro h state + simpa only [Equiv.symm_apply_apply] using h (e state) + · intro h state + exact h (e.symm state) + | halt => rfl + +theorem supports_iff [Inhabited Λ] (e : σ ≃ τ) (source : Λ → Stmt Γ Λ σ) + (S : Finset Λ) : Supports (program e source) S ↔ Supports source S := by + simp only [Supports, program, supportsStmt_iff] + +variable [DecidableEq K] + +theorem stepAux_transport (e : σ ≃ τ) (q : Stmt Γ Λ σ) (state : σ) + (tapes : ∀ k, List (Γ k)) : + stepAux (statement e q) (e state) tapes = + configuration e (stepAux q state tapes) := by + simpa only [statement, control_configuration] using + MachineControl.stepAux_simulation (id : Λ → Λ) e q state tapes + +theorem stepAux_transport_symm (e : σ ≃ τ) (q : Stmt Γ Λ σ) (state : τ) + (tapes : ∀ k, List (Γ k)) : + stepAux (statement e q) state tapes = + configuration e (stepAux q (e.symm state) tapes) := by + simpa only [Equiv.apply_symm_apply] using + stepAux_transport e q (e.symm state) tapes + +theorem step_transport (e : σ ≃ τ) (source : Λ → Stmt Γ Λ σ) (c : Cfg Γ Λ σ) : + step (program e source) (configuration e c) = + (step source c).map (configuration e) := by + cases c with + | mk l state tapes => + cases l with + | none => rfl + | some l => + change some (stepAux (statement e (source l)) (e state) tapes) = _ + rw [stepAux_transport] + rfl + +theorem step_iff (e : σ ≃ τ) (source : Λ → Stmt Γ Λ σ) (a b : Cfg Γ Λ σ) : + step (program e source) (configuration e a) = some (configuration e b) ↔ + step source a = some b := by + rw [step_transport] + change (step source a).map (configuration e) = (some b).map (configuration e) ↔ _ + constructor + · intro h + apply Option.map_injective (configurationEquiv e).injective + change (step source a).map (configuration e) = (some b).map (configuration e) + exact h + · exact congrArg (Option.map (configuration e)) + +theorem advance_transport (e : σ ≃ τ) (source : Λ → Stmt Γ Λ σ) + (c : Option (Cfg Γ Λ σ)) : + MachineComposition.advance (step (program e source)) (c.map (configuration e)) = + (MachineComposition.advance (step source) c).map (configuration e) := by + cases c with + | none => rfl + | some c => exact step_transport e source c + +theorem iterate_transport (e : σ ≃ τ) (source : Λ → Stmt Γ Λ σ) (n : Nat) + (c : Option (Cfg Γ Λ σ)) : + (MachineComposition.advance (step (program e source)))^[n] + (c.map (configuration e)) = + ((MachineComposition.advance (step source))^[n] c).map (configuration e) := by + induction n with + | zero => rfl + | succ n ih => + rw [Function.iterate_succ_apply', ih, advance_transport, + Function.iterate_succ_apply'] + +theorem trace_iff (e : σ ≃ τ) (source : Λ → Stmt Γ Λ σ) (n : Nat) + (a b : Cfg Γ Λ σ) : + (MachineComposition.advance (step (program e source)))^[n] + (some (configuration e a)) = some (configuration e b) ↔ + (MachineComposition.advance (step source))^[n] (some a) = some b := by + change (MachineComposition.advance (step (program e source)))^[n] + ((some a).map (configuration e)) = (some b).map (configuration e) ↔ _ + rw [iterate_transport] + constructor + · intro h + apply Option.map_injective (configurationEquiv e).injective + change ((MachineComposition.advance (step source))^[n] (some a)).map (configuration e) = + (some b).map (configuration e) + exact h + · exact congrArg (Option.map (configuration e)) + +theorem trace (e : σ ≃ τ) (source : Λ → Stmt Γ Λ σ) (n : Nat) + (a b : Cfg Γ Λ σ) + (run : (MachineComposition.advance (step source))^[n] (some a) = some b) : + (MachineComposition.advance (step (program e source)))^[n] + (some (configuration e a)) = some (configuration e b) := + (trace_iff e source n a b).2 run + +def execution (e : σ ≃ τ) (source : Λ → Stmt Γ Λ σ) + {start : Cfg Γ Λ σ} {finish : Option (Cfg Γ Λ σ)} {budget : Nat} + (run : StateTransition.EvalsToInTime (step source) start finish budget) : + StateTransition.EvalsToInTime (step (program e source)) + (configuration e start) (finish.map (configuration e)) budget where + steps := run.steps + evals_in_steps := by + have h := run.evals_in_steps + change (MachineComposition.advance (step source))^[run.steps] (some start) = finish at h + change (MachineComposition.advance (step (program e source)))^[run.steps] + ((some start).map (configuration e)) = finish.map (configuration e) + rw [iterate_transport, h] + steps_le_m := run.steps_le_m + +@[simp] theorem execution_steps (e : σ ≃ τ) (source : Λ → Stmt Γ Λ σ) + {start : Cfg Γ Λ σ} {finish : Option (Cfg Γ Λ σ)} {budget : Nat} + (run : StateTransition.EvalsToInTime (step source) start finish budget) : + (execution e source run).steps = run.steps := rfl + +def execution_reflect (e : σ ≃ τ) (source : Λ → Stmt Γ Λ σ) + {start : Cfg Γ Λ σ} {finish : Option (Cfg Γ Λ σ)} {budget : Nat} + (run : StateTransition.EvalsToInTime (step (program e source)) + (configuration e start) (finish.map (configuration e)) budget) : + StateTransition.EvalsToInTime (step source) start finish budget where + steps := run.steps + evals_in_steps := by + change (MachineComposition.advance (step source))^[run.steps] (some start) = finish + apply Option.map_injective (configurationEquiv e).injective + change ((MachineComposition.advance (step source))^[run.steps] (some start)).map + (configuration e) = finish.map (configuration e) + rw [← iterate_transport] + exact run.evals_in_steps + steps_le_m := run.steps_le_m + +@[simp] theorem execution_reflect_steps (e : σ ≃ τ) (source : Λ → Stmt Γ Λ σ) + {start : Cfg Γ Λ σ} {finish : Option (Cfg Γ Λ σ)} {budget : Nat} + (run : StateTransition.EvalsToInTime (step (program e source)) + (configuration e start) (finish.map (configuration e)) budget) : + (execution_reflect e source run).steps = run.steps := rfl + +end MinUncutGames.Foundations.Complexity.MachineStateEquiv + +end +section +namespace MinUncutGames.Foundations.Complexity.MachineUnaryAffineAt + +open Turing +open MachineComposition +open Reduction.MachineSubstitution + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool + +def finish (restoreLabel : Λ) : TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) := + .load (fun s => (s.1,none)) (.goto (fun _ => restoreLabel)) + +def scan (source scratch destination : K) (coefficient : Nat) (scanLabel restoreLabel : Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) := + .pop source (fun s head => (s.1,head)) + (.branch (fun s => s.2.getD false) + (.push scratch (fun _ => true) + (pushWord destination (List.replicate coefficient true) (.goto (fun _ => scanLabel)))) + (.branch (fun s => s.2.isSome) + (.push source (fun _ => false) (finish restoreLabel)) + (finish restoreLabel))) + +def seed (destination : K) (offset : Nat) (scanLabel : Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) := + pushWord destination (encodeWord offset).reverse (.goto (fun _ => scanLabel)) + +def tapes (source scratch destination : K) (base : K → List Bool) + (input saved output : List Bool) : K → List Bool := + MachineCopy.forkTapes source scratch destination base input saved output + +@[simp] theorem tapes_source (source scratch destination : K) + (hs : source ≠ scratch) (hd : source ≠ destination) + (base : K → List Bool) (input saved output : List Bool) : + tapes source scratch destination base input saved output source = input := + MachineCopy.forkTapes_source source scratch destination hs hd base input saved output + +@[simp] theorem tapes_scratch (source scratch destination : K) (hsd : scratch ≠ destination) + (base : K → List Bool) (input saved output : List Bool) : + tapes source scratch destination base input saved output scratch = saved := + MachineCopy.forkTapes_left source scratch destination hsd base input saved output + +@[simp] theorem tapes_destination (source scratch destination : K) + (base : K → List Bool) (input saved output : List Bool) : + tapes source scratch destination base input saved output destination = output := + MachineCopy.forkTapes_right source scratch destination base input saved output + +theorem update_source (source scratch destination : K) + (hs : source ≠ scratch) (hd : source ≠ destination) (hsd : scratch ≠ destination) + (base : K → List Bool) (input saved output replacement : List Bool) : + Function.update (tapes source scratch destination base input saved output) source replacement = + tapes source scratch destination base replacement saved output := by + funext k + by_cases h₀ : k = source + · subst k; simp [tapes, MachineCopy.forkTapes, hs, hd] + · by_cases h₁ : k = scratch + · subst k; simp [tapes, MachineCopy.forkTapes, h₀, hsd] + · by_cases h₂ : k = destination + · subst k; simp [tapes, MachineCopy.forkTapes, h₀] + · simp [tapes, MachineCopy.forkTapes, h₀, h₁, h₂] + +theorem update_scratch (source scratch destination : K) (hsd : scratch ≠ destination) + (base : K → List Bool) (input saved output replacement : List Bool) : + Function.update (tapes source scratch destination base input saved output) scratch replacement = + tapes source scratch destination base input replacement output := by + funext k + by_cases h : k = scratch + · subst k; simp [tapes, MachineCopy.forkTapes, hsd] + · by_cases h' : k = destination + · subst k; simp [tapes, MachineCopy.forkTapes, h] + · simp [tapes, MachineCopy.forkTapes, h, h'] + +theorem update_destination (source scratch destination : K) + (base : K → List Bool) (input saved output replacement : List Bool) : + Function.update (tapes source scratch destination base input saved output) destination replacement = + tapes source scratch destination base input saved replacement := by + simp [tapes, MachineCopy.forkTapes] + +theorem prepend_replicate_word (c b : Nat) (suffix : List Bool) : + List.replicate c true ++ (encodeWord b ++ suffix) = + encodeWord (c + b) ++ suffix := by + simp only [encodeWord, List.replicate_add, List.append_assoc] + +theorem scan_step_succ (source scratch destination : K) + (hs : source ≠ scratch) (hd : source ≠ destination) (hsd : scratch ≠ destination) + (coefficient : Nat) (scanLabel restoreLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atScan : program scanLabel = scan source scratch destination coefficient scanLabel restoreLabel) + (base : K → List Bool) (a b : Nat) (suffix saved output : List Bool) + (ambient : σ) (register : Option Bool) : + TM2.step program ⟨some scanLabel, (ambient,register), tapes source scratch destination base + (encodeWord (a + 1) ++ suffix) saved (encodeWord b ++ output)⟩ = + some ⟨some scanLabel, (ambient,some true), tapes source scratch destination base + (encodeWord a ++ suffix) (true :: saved) (encodeWord (coefficient + b) ++ output)⟩ := by + change some (TM2.stepAux (program scanLabel) _ _) = _ + rw [atScan] + rw [show encodeWord (a + 1) ++ suffix = true :: (encodeWord a ++ suffix) by + simp [encodeWord, List.replicate_succ]] + simp [scan, TM2.stepAux, tapes_source _ _ _ hs hd, + update_source source scratch destination hs hd hsd, tapes_scratch _ _ _ hsd, + update_scratch _ _ _ hsd, stepAux_pushWord, tapes_destination, + prepend_replicate_word, update_destination] + +theorem scan_step_zero (source scratch destination : K) + (hs : source ≠ scratch) (hd : source ≠ destination) (hsd : scratch ≠ destination) + (coefficient : Nat) (scanLabel restoreLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atScan : program scanLabel = scan source scratch destination coefficient scanLabel restoreLabel) + (base : K → List Bool) (b : Nat) (suffix saved output : List Bool) + (ambient : σ) (register : Option Bool) : + TM2.step program ⟨some scanLabel, (ambient,register), tapes source scratch destination base + (encodeWord 0 ++ suffix) saved (encodeWord b ++ output)⟩ = + some ⟨some restoreLabel, (ambient,none), tapes source scratch destination base + (encodeWord 0 ++ suffix) saved (encodeWord b ++ output)⟩ := by + change some (TM2.stepAux (program scanLabel) _ _) = _ + rw [atScan] + rw [show encodeWord 0 ++ suffix = false :: suffix from rfl] + simp [scan, finish, TM2.stepAux, tapes_source _ _ _ hs hd, + update_source source scratch destination hs hd hsd] + +theorem scanTrace (source scratch destination : K) + (hs : source ≠ scratch) (hd : source ≠ destination) (hsd : scratch ≠ destination) + (coefficient : Nat) (scanLabel restoreLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atScan : program scanLabel = scan source scratch destination coefficient scanLabel restoreLabel) + (base : K → List Bool) (a b : Nat) (suffix saved output : List Bool) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[a + 1] + (some ⟨some scanLabel, (ambient,register), tapes source scratch destination base + (encodeWord a ++ suffix) saved (encodeWord b ++ output)⟩) = + some ⟨some restoreLabel, (ambient,none), tapes source scratch destination base + (encodeWord 0 ++ suffix) (List.replicate a true ++ saved) + (encodeWord (coefficient * a + b) ++ output)⟩ := by + induction a generalizing b saved register with + | zero => + simpa using scan_step_zero source scratch destination hs hd hsd coefficient scanLabel + restoreLabel program atScan base b suffix saved output ambient register + | succ a ih => + rw [Function.iterate_succ_apply] + simp only [advance_some] + rw [scan_step_succ source scratch destination hs hd hsd coefficient scanLabel restoreLabel + program atScan] + rw [ih] + have hval : coefficient * a + (coefficient + b) = coefficient * (a + 1) + b := by + rw [Nat.mul_succ]; omega + rw [hval] + have hsave : List.replicate a true ++ true :: saved = List.replicate (a + 1) true ++ saved := by + simp only [List.replicate_add, List.replicate_one, List.append_assoc, List.singleton_append] + rw [hsave] + +theorem restoreTapes (source scratch destination : K) + (hs : source ≠ scratch) (hd : source ≠ destination) (hsd : scratch ≠ destination) + (base : K → List Bool) (a value : Nat) (suffix output : List Bool) : + Reduction.MachineTransfer.tapesAt scratch source + (tapes source scratch destination base (encodeWord 0 ++ suffix) + (List.replicate a true) (encodeWord value ++ output)) + [] (encodeWord a ++ suffix) = + tapes source scratch destination base (encodeWord a ++ suffix) [] (encodeWord value ++ output) := by + funext k + by_cases h₀ : k = source + · subst k; simp [tapes, MachineCopy.forkTapes, Reduction.MachineTransfer.tapesAt, hs, hd] + · by_cases h₁ : k = scratch + · subst k + simp [tapes, MachineCopy.forkTapes, Reduction.MachineTransfer.tapesAt, Ne.symm hs, hsd] + · by_cases h₂ : k = destination + · subst k + simp [tapes, MachineCopy.forkTapes, Reduction.MachineTransfer.tapesAt, Ne.symm hd, Ne.symm hsd] + · simp [tapes, MachineCopy.forkTapes, Reduction.MachineTransfer.tapesAt, h₀, h₁, h₂] + +theorem affineTrace (source scratch destination : K) + (hs : source ≠ scratch) (hd : source ≠ destination) (hsd : scratch ≠ destination) + (coefficient : Nat) (scanLabel restoreLabel : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atScan : program scanLabel = scan source scratch destination coefficient scanLabel restoreLabel) + (atRestore : program restoreLabel = Reduction.MachineTransfer.loopAt + scratch source id false restoreLabel exit) + (base : K → List Bool) (a b : Nat) (suffix output : List Bool) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[2 * (a + 1)] + (some ⟨some scanLabel, (ambient,register), tapes source scratch destination base + (encodeWord a ++ suffix) [] (encodeWord b ++ output)⟩) = + some ⟨exit, (ambient,none), tapes source scratch destination base + (encodeWord a ++ suffix) [] (encodeWord (coefficient * a + b) ++ output)⟩ := by + have hscan := scanTrace source scratch destination hs hd hsd coefficient scanLabel restoreLabel + program atScan base a b suffix [] output ambient register + simp only [List.append_nil] at hscan + let mid := tapes source scratch destination base (encodeWord 0 ++ suffix) + (List.replicate a true) (encodeWord (coefficient * a + b) ++ output) + have hrestore := Reduction.MachineTransfer.transferAt_fromTapes scratch source (Ne.symm hs) + id false restoreLabel exit program atRestore mid ambient none + change (advance (TM2.step program))^[(mid scratch).length + 1] + (some ⟨some restoreLabel,(ambient,none),mid⟩) = _ at hrestore + have hsaved : mid scratch = List.replicate a true := by + simp [mid, tapes, hsd] + have hsource : mid source = encodeWord 0 ++ suffix := by + simp [mid, tapes, hs, hd] + rw [hsaved, hsource] at hrestore + simp only [List.length_replicate, List.reverse_replicate, List.map_id] at hrestore + have hword : List.replicate a true ++ (encodeWord 0 ++ suffix) = encodeWord a ++ suffix := by + simp [encodeWord, List.append_assoc] + rw [hword] at hrestore + simp only [mid, restoreTapes source scratch destination hs hd hsd] at hrestore + rw [show 2 * (a + 1) = (a + 1) + (a + 1) by omega, Function.iterate_add_apply, hscan] + exact hrestore + +def affineInTime (source scratch destination : K) + (hs : source ≠ scratch) (hd : source ≠ destination) (hsd : scratch ≠ destination) + (coefficient : Nat) (scanLabel restoreLabel : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atScan : program scanLabel = scan source scratch destination coefficient scanLabel restoreLabel) + (atRestore : program restoreLabel = Reduction.MachineTransfer.loopAt + scratch source id false restoreLabel exit) + (base : K → List Bool) (a b : Nat) (suffix output : List Bool) + (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some scanLabel, (ambient,register), tapes source scratch destination base + (encodeWord a ++ suffix) [] (encodeWord b ++ output)⟩ + (some ⟨exit, (ambient,none), tapes source scratch destination base + (encodeWord a ++ suffix) [] (encodeWord (coefficient * a + b) ++ output)⟩) + (2 * (a + 1)) where + steps := 2 * (a + 1) + evals_in_steps := affineTrace source scratch destination hs hd hsd coefficient scanLabel + restoreLabel exit program atScan atRestore base a b suffix output ambient register + steps_le_m := Nat.le_refl _ + +theorem seededAffineTrace (source scratch destination : K) + (hs : source ≠ scratch) (hd : source ≠ destination) (hsd : scratch ≠ destination) + (coefficient offset : Nat) (seedLabel scanLabel restoreLabel : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atSeed : program seedLabel = seed destination offset scanLabel) + (atScan : program scanLabel = scan source scratch destination coefficient scanLabel restoreLabel) + (atRestore : program restoreLabel = Reduction.MachineTransfer.loopAt + scratch source id false restoreLabel exit) + (base : K → List Bool) (a : Nat) (suffix : List Bool) + (sourceWord : base source = encodeWord a ++ suffix) (scratchEmpty : base scratch = []) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[2 * (a + 1) + 1] + (some ⟨some seedLabel, (ambient,register), base⟩) = + some ⟨exit, (ambient,none), + Function.update base destination (encodeWord (coefficient * a + offset) ++ base destination)⟩ := by + have hseed : TM2.step program ⟨some seedLabel,(ambient,register),base⟩ = + some ⟨some scanLabel,(ambient,register), + Function.update base destination (encodeWord offset ++ base destination)⟩ := by + change some (TM2.stepAux (program seedLabel) _ _) = _ + rw [atSeed, seed, stepAux_pushWord] + simp only [List.reverse_reverse, TM2.stepAux] + have hrun := affineTrace source scratch destination hs hd hsd coefficient scanLabel restoreLabel + exit program atScan atRestore base a offset suffix (base destination) ambient register + have hframe (word : List Bool) : + tapes source scratch destination base (encodeWord a ++ suffix) [] word = + Function.update base destination word := by + rw [← sourceWord, ← scratchEmpty] + simp only [tapes, MachineCopy.forkTapes, Function.update_eq_self] + rw [hframe, hframe] at hrun + rw [Function.iterate_succ_apply] + simp only [advance_some] + rw [hseed] + exact hrun + +inductive Label + | seed | scan | restore + deriving DecidableEq + +protected abbrev Label.enumList : List Label := [.seed, .scan, .restore] + +protected theorem Label.enumList_getElem?_ctorIdx_eq (x : Label) : + Label.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem Label.enumList_nodup : Label.enumList.Nodup := by decide + +instance : Fintype Label where + elems := ⟨Label.enumList, Label.enumList_nodup⟩ + complete x := by cases x <;> decide + +def program (source scratch destination : K) (coefficient offset : Nat) : + Label → TM2.Stmt (Alphabet (K := K)) Label (σ × Option Bool) + | .seed => seed destination offset .scan + | .scan => scan source scratch destination coefficient .scan .restore + | .restore => Reduction.MachineTransfer.loopAt scratch source id false .restore none + +def machine (coefficient offset : Nat) : FinTM2 where + K := Fin 3 + k₀ := 0 + k₁ := 2 + Γ _ := Bool + Λ := Label + main := .seed + σ := Unit × Option Bool + initialState := ((),none) + m := program 0 1 2 coefficient offset + +end MinUncutGames.Foundations.Complexity.MachineUnaryAffineAt + +end +section +namespace MinUncutGames.Foundations.Complexity.MachineUnaryEqualityBit + +open Turing +open MachineComposition + +variable {K Λ A : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool +abbrev State (A : Type) := (A × Bool × Option Bool) × Option Bool + +def clean (ambient : A) : State A := ((ambient, false, none), none) + +def compareStateEquiv (A : Type) : MachineCompare.State A ≃ State A where + toFun s := ((s.1, s.2.1, s.2.2.1), s.2.2.2) + invFun s := (s.1.1, s.1.2.1, s.1.2.2, s.2) + left_inv := by rintro ⟨a, b, c, d⟩; rfl + right_inv := by rintro ⟨⟨a, b, c⟩, d⟩; rfl + +inductive Label + | seedLeft | scanLeft | restoreLeft + | seedRight | scanRight | restoreRight + | compare | equal | different + deriving DecidableEq + +protected abbrev Label.enumList : List Label := [.seedLeft, .scanLeft, .restoreLeft, .seedRight, + .scanRight, .restoreRight, .compare, .equal, .different] + +protected theorem Label.enumList_getElem?_ctorIdx_eq (x : Label) : + Label.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem Label.enumList_nodup : Label.enumList.Nodup := by decide + +instance : Fintype Label where + elems := ⟨Label.enumList, Label.enumList_nodup⟩ + complete x := by cases x <;> decide + +def exitAt (exit : Option Λ) : TM2.Stmt (Alphabet (K := K)) Λ (State A) := + match exit with + | none => .halt + | some label => .goto fun _ => label + +def bitEncoding (bit : Bool) : List Bool := encodeWord (if bit then 1 else 0) + +def emit (destination : K) (bit : Bool) (exit : Option Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (State A) := + .push destination (fun _ => false) + (if bit then .push destination (fun _ => true) (exitAt exit) else exitAt exit) + +def instruction (tape : Fin 6 → K) (labels : Label → Λ) (exit : Option Λ) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (State A) + | .seedLeft => MachineUnaryAffineAt.seed (tape 2) 0 (labels .scanLeft) + | .scanLeft => MachineUnaryAffineAt.scan (tape 0) (tape 4) (tape 2) 1 + (labels .scanLeft) (labels .restoreLeft) + | .restoreLeft => Reduction.MachineTransfer.loopAt (tape 4) (tape 0) id false + (labels .restoreLeft) (some (labels .seedRight)) + | .seedRight => MachineUnaryAffineAt.seed (tape 3) 0 (labels .scanRight) + | .scanRight => MachineUnaryAffineAt.scan (tape 1) (tape 4) (tape 3) 1 + (labels .scanRight) (labels .restoreRight) + | .restoreRight => Reduction.MachineTransfer.loopAt (tape 4) (tape 1) id false + (labels .restoreRight) (some (labels .compare)) + | .compare => MachineStateEquiv.statement (compareStateEquiv A) + (MachineCompare.loop (tape 2) (tape 3) (labels .compare) + (some (labels .equal)) (some (labels .different))) + | .equal => emit (tape 5) true exit + | .different => emit (tape 5) false exit + +def copySteps (n : Nat) : Nat := 2 * (n + 1) + 1 +def compareSteps (a b : Nat) : Nat := max (a + 1) (b + 1) + 1 +def steps (a b : Nat) : Nat := copySteps a + copySteps b + compareSteps a b + 1 + +theorem steps_le (a b : Nat) : steps a b ≤ 3 * (a + b) + 9 := by + unfold steps copySteps compareSteps + omega + +theorem encodeWord_eq_iff (a b : Nat) : encodeWord a = encodeWord b ↔ a = b := by + constructor + · intro h + have hlength := congrArg List.length h + simp only [encodeWord_length] at hlength + omega + · rintro rfl + rfl + +theorem emit_step (destination : K) (bit : Bool) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (label : Λ) (atEmit : program label = emit destination bit exit) + (state : State A) (base : K → List Bool) : + TM2.step program ⟨some label, state, base⟩ = + some ⟨exit, state, + Function.update base destination (bitEncoding bit ++ base destination)⟩ := by + change some (TM2.stepAux (program label) state base) = _ + rw [atEmit] + cases bit <;> cases exit <;> + simp [emit, exitAt, TM2.stepAux, bitEncoding, encodeWord, Function.update_idem] + +theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +theorem equalityTrace (tape : Fin 6 → K) (distinct : Function.Injective tape) + (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ l, program (labels l) = instruction tape labels exit l) + (base : K → List Bool) (a b : Nat) (leftSuffix rightSuffix : List Bool) + (leftWord : base (tape 0) = encodeWord a ++ leftSuffix) + (rightWord : base (tape 1) = encodeWord b ++ rightSuffix) + (leftEmpty : base (tape 2) = []) (rightEmpty : base (tape 3) = []) + (scratchEmpty : base (tape 4) = []) (ambient : A) : + (advance (TM2.step program))^[steps a b] + (some ⟨some (labels .seedLeft), clean ambient, base⟩) = + some ⟨exit, clean ambient, + Function.update base (tape 5) (bitEncoding (decide (a = b)) ++ base (tape 5))⟩ := by + have hd (i j : Fin 6) (hne : i ≠ j) : tape i ≠ tape j := + fun h => hne (distinct h) + let midLeft := Function.update base (tape 2) (encodeWord a) + let midBoth := Function.update midLeft (tape 3) (encodeWord b) + have leftRun : (advance (TM2.step program))^[copySteps a] + (some ⟨some (labels .seedLeft), clean ambient, base⟩) = + some ⟨some (labels .seedRight), clean ambient, midLeft⟩ := by + simpa only [copySteps, clean, midLeft, Nat.one_mul, Nat.add_zero, + leftEmpty, List.append_nil] using + MachineUnaryAffineAt.seededAffineTrace (tape 0) (tape 4) (tape 2) + (hd 0 4 (by decide)) (hd 0 2 (by decide)) (hd 4 2 (by decide)) 1 0 + (labels .seedLeft) (labels .scanLeft) (labels .restoreLeft) + (some (labels .seedRight)) program (atLabels .seedLeft) + (atLabels .scanLeft) (atLabels .restoreLeft) + base a leftSuffix leftWord scratchEmpty (ambient, false, none) none + have rightSource : midLeft (tape 1) = encodeWord b ++ rightSuffix := by + simpa [midLeft, hd 1 2 (by decide)] using rightWord + have scratchAfterLeft : midLeft (tape 4) = [] := by + simpa [midLeft, hd 4 2 (by decide)] using scratchEmpty + have rightCopyAfterLeft : midLeft (tape 3) = [] := by + simpa [midLeft, hd 3 2 (by decide)] using rightEmpty + have rightRun : (advance (TM2.step program))^[copySteps b] + (some ⟨some (labels .seedRight), clean ambient, midLeft⟩) = + some ⟨some (labels .compare), clean ambient, midBoth⟩ := by + simpa only [copySteps, clean, midBoth, Nat.one_mul, Nat.add_zero, + rightCopyAfterLeft, List.append_nil] using + MachineUnaryAffineAt.seededAffineTrace (tape 1) (tape 4) (tape 3) + (hd 1 4 (by decide)) (hd 1 3 (by decide)) (hd 4 3 (by decide)) 1 0 + (labels .seedRight) (labels .scanRight) (labels .restoreRight) + (some (labels .compare)) program (atLabels .seedRight) + (atLabels .scanRight) (atLabels .restoreRight) + midLeft b rightSuffix rightSource scratchAfterLeft (ambient, false, none) none + have copyLeftWord : midBoth (tape 2) = encodeWord a := by + simp [midBoth, midLeft, hd 2 3 (by decide)] + have copyRightWord : midBoth (tape 3) = encodeWord b := by simp [midBoth] + have restored : Reduction.MachineTransfer.tapesAt (tape 2) (tape 3) midBoth [] [] = base := by + funext k + by_cases hl : k = tape 2 + · subst k + simp [Reduction.MachineTransfer.tapesAt, midBoth, midLeft, + hd 2 3 (by decide), leftEmpty] + · by_cases hr : k = tape 3 + · subst k + simp [Reduction.MachineTransfer.tapesAt, midBoth, midLeft, rightEmpty] + · simp [Reduction.MachineTransfer.tapesAt, midBoth, midLeft, hl, hr] + let back := MachineStateEquiv.program (compareStateEquiv A).symm program + have atCompare : back (labels .compare) = + MachineCompare.loop (tape 2) (tape 3) (labels .compare) + (some (labels .equal)) (some (labels .different)) := by + change MachineStateEquiv.statement (compareStateEquiv A).symm + (program (labels .compare)) = _ + rw [atLabels .compare] + exact MachineStateEquiv.statement_symm_statement (compareStateEquiv A) _ + have backForward : MachineStateEquiv.program (compareStateEquiv A) back = program := by + funext l + change MachineStateEquiv.statement (compareStateEquiv A) + (MachineStateEquiv.statement (compareStateEquiv A).symm (program l)) = program l + simpa only [Equiv.symm_symm] using + MachineStateEquiv.statement_symm_statement (compareStateEquiv A).symm (program l) + have compareRun : (advance (TM2.step program))^[compareSteps a b] + (some ⟨some (labels .compare), clean ambient, midBoth⟩) = + some ⟨if a = b then some (labels .equal) else some (labels .different), + clean ambient, base⟩ := by + have native := MachineCompare.compareTrace_fromTapes (tape 2) (tape 3) + (hd 2 3 (by decide)) (labels .compare) (some (labels .equal)) + (some (labels .different)) back atCompare midBoth ambient none none + rw [copyLeftWord, copyRightWord, restored] at native + simp only [encodeWord_eq_iff, encodeWord_length] at native + have transported := MachineStateEquiv.trace (compareStateEquiv A) back _ _ _ native + rw [backForward] at transported + simpa [MachineStateEquiv.configuration, compareStateEquiv, clean, compareSteps] using + transported + have emitRun : TM2.step program + ⟨if a = b then some (labels .equal) else some (labels .different), + clean ambient, base⟩ = + some ⟨exit, clean ambient, + Function.update base (tape 5) (bitEncoding (decide (a = b)) ++ base (tape 5))⟩ := by + by_cases heq : a = b + · simpa only [heq, ite_true, decide_true] using + emit_step (tape 5) true exit program (labels .equal) (atLabels .equal) + (clean ambient) base + · simpa only [heq, ite_false, decide_false] using + emit_step (tape 5) false exit program (labels .different) (atLabels .different) + (clean ambient) base + have copied := joinTrace leftRun rightRun + have compared := joinTrace copied compareRun + rw [steps, Function.iterate_succ_apply', compared, advance_some] + exact emitRun + +def equalityInTime (tape : Fin 6 → K) (distinct : Function.Injective tape) + (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ l, program (labels l) = instruction tape labels exit l) + (base : K → List Bool) (a b : Nat) (leftSuffix rightSuffix : List Bool) + (leftWord : base (tape 0) = encodeWord a ++ leftSuffix) + (rightWord : base (tape 1) = encodeWord b ++ rightSuffix) + (leftEmpty : base (tape 2) = []) (rightEmpty : base (tape 3) = []) + (scratchEmpty : base (tape 4) = []) (ambient : A) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .seedLeft), clean ambient, base⟩ + (some ⟨exit, clean ambient, + Function.update base (tape 5) (bitEncoding (decide (a = b)) ++ base (tape 5))⟩) + (3 * (a + b) + 9) where + steps := steps a b + evals_in_steps := equalityTrace tape distinct labels exit program atLabels base a b + leftSuffix rightSuffix leftWord rightWord leftEmpty rightEmpty scratchEmpty ambient + steps_le_m := steps_le a b + +def machine : FinTM2 where + K := Fin 6 + k₀ := 0 + k₁ := 5 + Γ _ := Bool + Λ := Label + main := .seedLeft + σ := State Unit + initialState := clean () + m := instruction id id none + +def machineInTime (base : Fin 6 → List Bool) (a b : Nat) + (leftSuffix rightSuffix : List Bool) + (leftWord : base 0 = encodeWord a ++ leftSuffix) + (rightWord : base 1 = encodeWord b ++ rightSuffix) + (leftEmpty : base 2 = []) (rightEmpty : base 3 = []) (scratchEmpty : base 4 = []) : + StateTransition.EvalsToInTime machine.step + ⟨some .seedLeft, clean (), base⟩ + (some ⟨none, clean (), + Function.update base (5 : Fin 6) (bitEncoding (decide (a = b)) ++ base (5 : Fin 6))⟩) + (3 * (a + b) + 9) := + equalityInTime id (fun _ _ h => h) id none (instruction id id none) (fun _ => rfl) + base a b leftSuffix rightSuffix leftWord rightWord leftEmpty rightEmpty scratchEmpty () + +end MinUncutGames.Foundations.Complexity.MachineUnaryEqualityBit + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineFiniteSequence.lean b/lean/OAI/Computability/MinUncut/Machines/MachineFiniteSequence.lean new file mode 100644 index 0000000000000000000000000000000000000000..d55b47a0a1f5f2867b8c568d44bf2d69770d3132 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineFiniteSequence.lean @@ -0,0 +1,302 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineDrain + +namespace OAI + +namespace MinUncutGames.Foundations.Complexity.MachineFiniteSequence + +open Turing MachineComposition + +variable {Command : Type} (LocalLabel : Command → Type) + +def Label : List Command → Type + | [] => Empty + | command :: commands => LocalLabel command ⊕ Label commands + +instance labelFintype [∀ command, Fintype (LocalLabel command)] + (commands : List Command) : Fintype (Label LocalLabel commands) := by + induction commands with + | nil => exact inferInstanceAs (Fintype Empty) + | cons command commands ih => + letI := ih + exact inferInstanceAs (Fintype (LocalLabel command ⊕ Label LocalLabel commands)) + +instance labelDecidableEq [∀ command, DecidableEq (LocalLabel command)] + (commands : List Command) : DecidableEq (Label LocalLabel commands) := by + induction commands with + | nil => exact inferInstanceAs (DecidableEq Empty) + | cons command commands ih => + letI := ih + exact inferInstanceAs (DecidableEq (LocalLabel command ⊕ Label LocalLabel commands)) + +variable (main : ∀ command, LocalLabel command) +variable {K Λ σ : Type} {Γ : K → Type} + +def entry : (commands : List Command) → (Label LocalLabel commands → Λ) → Option Λ → Option Λ + | [], _, exit => exit + | command :: _, labels, _ => some (labels (.inl (main command))) + +variable (localInstruction : ∀ command, (LocalLabel command → Λ) → Option Λ → + LocalLabel command → TM2.Stmt Γ Λ σ) + +def instruction : (commands : List Command) → (Label LocalLabel commands → Λ) → Option Λ → + Label LocalLabel commands → TM2.Stmt Γ Λ σ + | [], _, _, label => nomatch label + | command :: commands, labels, exit, .inl label => + localInstruction command (fun l => labels (.inl l)) + (entry LocalLabel main commands (fun l => labels (.inr l)) exit) label + | _ :: commands, labels, exit, .inr label => + instruction commands (fun l => labels (.inr l)) exit label + +variable {Data : Type} (result : Command → Data → Data) (cost : Command → Data → Nat) + +def resultOf : List Command → Data → Data + | [], data => data + | command :: commands, data => resultOf commands (result command data) + +def steps : List Command → Data → Nat + | [], _ => 0 + | command :: commands, data => cost command data + steps commands (result command data) + +variable [DecidableEq K] + +theorem trace (program : Λ → TM2.Stmt Γ Λ σ) + (invariant : Data → Prop) (state : Data → σ) (tapes : Data → ∀ k, List (Γ k)) + (commands : List Command) + (localInvariant : ∀ command ∈ commands, ∀ data, invariant data → + invariant (result command data)) + (localTrace : ∀ command ∈ commands, ∀ (labels : LocalLabel command → Λ) (exit : Option Λ), + (∀ l, program (labels l) = localInstruction command labels exit l) → + ∀ data, invariant data → + (advance (TM2.step program))^[cost command data] + (some ⟨some (labels (main command)), state data, tapes data⟩) = + some ⟨exit, state (result command data), tapes (result command data)⟩) + (labels : Label LocalLabel commands → Λ) (exit : Option Λ) + (atLabels : ∀ l, program (labels l) = + instruction LocalLabel main localInstruction commands labels exit l) + (data : Data) (valid : invariant data) : + (advance (TM2.step program))^[steps result cost commands data] + (some ⟨entry LocalLabel main commands labels exit, state data, tapes data⟩) = + some ⟨exit, state (resultOf result commands data), tapes (resultOf result commands data)⟩ := by + induction commands generalizing data with + | nil => rfl + | cons command commands ih => + have firstRun := localTrace command (by simp) + (fun l => labels (.inl l)) + (entry LocalLabel main commands (fun l => labels (.inr l)) exit) + (fun l => atLabels (.inl l)) data valid + have nextValid := localInvariant command (by simp) data valid + have tailRun := ih + (fun c hc d hd => localInvariant c (by simp [hc]) d hd) + (fun c hc => localTrace c (by simp [hc])) + (fun l => labels (.inr l)) (fun l => atLabels (.inr l)) + (result command data) nextValid + rw [steps, Nat.add_comm, Function.iterate_add_apply] + change (advance (TM2.step program))^[steps result cost commands (result command data)] + ((advance (TM2.step program))^[cost command data] + (some ⟨some (labels (.inl (main command))), state data, tapes data⟩)) = _ + rw [firstRun] + exact tailRun + +end MinUncutGames.Foundations.Complexity.MachineFiniteSequence + +namespace MinUncutGames.Foundations.Complexity.MachineDrainMany + +open Turing MachineComposition + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool +abbrev Tapes (K : Type) := K → List Bool +abbrev LocalLabel (_ : K) := Unit +abbrev Label (chosen : List K) := MachineFiniteSequence.Label (LocalLabel (K := K)) chosen +abbrev Data (K : Type) := Tapes K × Option Bool + +def entry (chosen : List K) (labels : Label chosen → Λ) (exit : Option Λ) : Option Λ := + MachineFiniteSequence.entry (LocalLabel (K := K)) (fun _ => ()) chosen labels exit + +def localInstruction (source : K) (labels : Unit → Λ) (exit : Option Λ) (_ : Unit) : + TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) := + MachineDrain.drain source (labels ()) exit + +def instruction (chosen : List K) (labels : Label chosen → Λ) (exit : Option Λ) : + Label chosen → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) := + MachineFiniteSequence.instruction (LocalLabel (K := K)) (fun _ => ()) + localInstruction chosen labels exit + +def result (source : K) (data : Data K) : Data K := + (Function.update data.1 source [], none) + +def cost (source : K) (data : Data K) : Nat := (data.1 source).length + 1 + +def finalTapes : List K → Tapes K → Tapes K + | [], base => base + | source :: chosen, base => finalTapes chosen (Function.update base source []) + +def finalRegister : List K → Option Bool → Option Bool + | [], register => register + | _ :: _, _ => none + +omit [DecidableEq K] in +@[simp] theorem finalRegister_none (chosen : List K) : finalRegister chosen none = none := by + cases chosen <;> rfl + +def steps : List K → Tapes K → Nat + | [], _ => 0 + | source :: chosen, base => (base source).length + 1 + + steps chosen (Function.update base source []) + +@[simp] theorem sequence_result (chosen : List K) (base : Tapes K) (register : Option Bool) : + MachineFiniteSequence.resultOf result chosen (base, register) = + (finalTapes chosen base, finalRegister chosen register) := by + induction chosen generalizing base register with + | nil => rfl + | cons source chosen ih => + change MachineFiniteSequence.resultOf result chosen (Function.update base source [], none) = + (finalTapes chosen (Function.update base source []), none) + rw [ih, finalRegister_none] + +@[simp] theorem sequence_steps (chosen : List K) (base : Tapes K) (register : Option Bool) : + MachineFiniteSequence.steps result cost chosen (base, register) = steps chosen base := by + induction chosen generalizing base register with + | nil => rfl + | cons source chosen ih => + simp only [MachineFiniteSequence.steps, result, cost, steps, ih] + +theorem finalTapes_apply (chosen : List K) (base : Tapes K) (k : K) : + finalTapes chosen base k = if k ∈ chosen then [] else base k := by + induction chosen generalizing base with + | nil => simp [finalTapes] + | cons source chosen ih => + rw [finalTapes, ih] + by_cases h : k = source + · subst k + simp + · simp [List.mem_cons, h] + +theorem finalTapes_mem (chosen : List K) (base : Tapes K) (k : K) (h : k ∈ chosen) : + finalTapes chosen base k = [] := by rw [finalTapes_apply, ite_eq_left h] + +theorem finalTapes_not_mem (chosen : List K) (base : Tapes K) (k : K) (h : k ∉ chosen) : + finalTapes chosen base k = base k := by rw [finalTapes_apply, ite_eq_right h] + +def lengthSum (chosen : List K) (base : Tapes K) : Nat := + (chosen.map (fun k => (base k).length)).sum + +omit [DecidableEq K] in +theorem lengthSum_mono (chosen : List K) (first second : Tapes K) + (h : ∀ k, (first k).length ≤ (second k).length) : + lengthSum chosen first ≤ lengthSum chosen second := by + induction chosen with + | nil => exact Nat.le_refl 0 + | cons source chosen ih => + simp only [lengthSum, List.map_cons, List.sum_cons] at ih ⊢ + exact Nat.add_le_add (h source) ih + +theorem steps_le (chosen : List K) (base : Tapes K) : + steps chosen base ≤ lengthSum chosen base + chosen.length := by + induction chosen generalizing base with + | nil => simp [steps, lengthSum] + | cons source chosen ih => + have hshort : ∀ k, ((Function.update base source []) k).length ≤ (base k).length := by + intro k + by_cases h : k = source + · subst k + simp + · simp [Function.update_of_ne h] + have hsum := lengthSum_mono chosen (Function.update base source []) base hshort + have htail := ih (Function.update base source []) + simp only [steps, lengthSum, List.map_cons, List.sum_cons, List.length_cons] at hsum htail ⊢ + omega + +theorem steps_le_uniform (chosen : List K) (base : Tapes K) (bound : Nat) + (h : ∀ k, (base k).length ≤ bound) : + steps chosen base ≤ chosen.length * (bound + 1) := by + have hsum : lengthSum chosen base ≤ chosen.length * bound := by + induction chosen with + | nil => simp [lengthSum] + | cons source chosen ih => + simp only [lengthSum, List.map_cons, List.sum_cons, List.length_cons, Nat.add_mul, + Nat.one_mul] at ih ⊢ + have hs := h source + omega + have hc := steps_le chosen base + rw [Nat.mul_add, Nat.mul_one] + omega + +theorem trace (chosen : List K) (labels : Label chosen → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atLabels : ∀ l, program (labels l) = instruction chosen labels exit l) + (base : Tapes K) (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[steps chosen base] + (some ⟨entry chosen labels exit, (ambient, register), base⟩) = + some ⟨exit, (ambient, finalRegister chosen register), finalTapes chosen base⟩ := by + have run := MachineFiniteSequence.trace + (LocalLabel := LocalLabel (K := K)) (main := fun _ => ()) + (localInstruction := localInstruction (σ := σ)) (result := result) (cost := cost) + program (fun _ : Data K => True) (fun data => (ambient, data.2)) (fun data => data.1) + chosen (by intros; trivial) + (by + intro source _ localLabels localExit atLocal data _ + rcases data with ⟨tapes, reg⟩ + simpa only [cost, result, Function.update_eq_self] using + MachineDrain.drainTrace source (localLabels ()) localExit program (atLocal ()) + tapes (tapes source) ambient reg) + labels exit atLabels (base, register) trivial + simpa only [sequence_steps, sequence_result, entry] using run + +def execution (chosen : List K) (labels : Label chosen → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atLabels : ∀ l, program (labels l) = instruction chosen labels exit l) + (base : Tapes K) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨entry chosen labels exit, (ambient, register), base⟩ + (some ⟨exit, (ambient, finalRegister chosen register), finalTapes chosen base⟩) + (lengthSum chosen base + chosen.length) where + steps := steps chosen base + evals_in_steps := trace chosen labels exit program atLabels base ambient register + steps_le_m := steps_le chosen base + +def workTapes {N : Nat} (enumeration : Fin N ≃ K) (output : K) : List K := + (List.ofFn (fun i => enumeration i)).filter (fun k => decide (k ≠ output)) + +@[simp] theorem mem_workTapes {N : Nat} (enumeration : Fin N ≃ K) (output k : K) : + k ∈ workTapes enumeration output ↔ k ≠ output := by + have hmem : k ∈ List.ofFn (fun i => enumeration i) := by + apply List.mem_ofFn.mpr + exact ⟨enumeration.symm k, enumeration.apply_symm_apply k⟩ + simp [workTapes, hmem] + +theorem workTapes_length_le {N : Nat} (enumeration : Fin N ≃ K) (output : K) : + (workTapes enumeration output).length ≤ N := by + simpa only [workTapes, List.length_ofFn] using + List.length_filter_le (fun k => decide (k ≠ output)) (List.ofFn (fun i => enumeration i)) + +def haltTapes (output : K) (word : List Bool) : Tapes K := + fun k => if k = output then word else [] + +theorem finalTapes_workTapes {N : Nat} (enumeration : Fin N ≃ K) (output : K) + (base : Tapes K) : + finalTapes (workTapes enumeration output) base = haltTapes output (base output) := by + funext k + rw [finalTapes_apply] + by_cases h : k = output + · subst k + simp [haltTapes] + · simp [haltTapes, h] + +theorem cleanupTrace {N : Nat} (enumeration : Fin N ≃ K) (output : K) + (labels : Label (workTapes enumeration output) → Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atLabels : ∀ l, program (labels l) = + instruction (workTapes enumeration output) labels none l) + (base : Tapes K) (ambient : σ) : + (advance (TM2.step program))^[steps (workTapes enumeration output) base] + (some ⟨entry (workTapes enumeration output) labels none, (ambient, none), base⟩) = + some ⟨none, (ambient, none), haltTapes output (base output)⟩ := by + simpa only [finalRegister_none, finalTapes_workTapes] using + trace (workTapes enumeration output) labels none program atLabels base ambient none + +end MinUncutGames.Foundations.Complexity.MachineDrainMany + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineFiniteTable.lean b/lean/OAI/Computability/MinUncut/Machines/MachineFiniteTable.lean new file mode 100644 index 0000000000000000000000000000000000000000..9ddd24785077764d75c2e362f6ac136c418120af --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineFiniteTable.lean @@ -0,0 +1,98 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineSubstitution + +namespace OAI + +section +namespace MinUncutGames.Foundations.Complexity.MachineFiniteTable + +open Turing +open MinUncutGames.Reduction.MachineSubstitution + +variable {K Λ σ : Type} [DecidableEq K] [DecidableEq σ] +variable {Γ : K → Type} + +def dispatch (dst : K) (table : σ → List (Γ dst)) + (next : TM2.Stmt Γ Λ σ) : List σ → TM2.Stmt Γ Λ σ + | [] => next + | key :: rest => + .branch (fun state => decide (state = key)) + (pushWord dst (table key).reverse next) (dispatch dst table next rest) + +theorem stepAux_dispatch (dst : K) (table : σ → List (Γ dst)) + (next : TM2.Stmt Γ Λ σ) (keys : List σ) (state : σ) + (hstate : state ∈ keys) (tapes : ∀ k, List (Γ k)) : + TM2.stepAux (dispatch dst table next keys) state tapes = + TM2.stepAux next state (Function.update tapes dst (table state ++ tapes dst)) := by + induction keys with + | nil => simp at hstate + | cons key rest ih => + by_cases h : state = key + · subst state + simp only [dispatch, TM2.stepAux, decide_true, Bool.cond_true] + simpa only [List.reverse_reverse] using + stepAux_pushWord dst (table key).reverse next key tapes + · have hm : state ∈ rest := (List.mem_cons.mp hstate).resolve_left h + simpa only [dispatch, TM2.stepAux, h, decide_false, Bool.cond_false] using ih hm + +omit [DecidableEq K] in + +theorem dispatch_push_bound (dst : K) (table : σ → List (Γ dst)) + (next : TM2.Stmt Γ Λ σ) (keys : List σ) : + Runtime.statementPushBound (dispatch dst table next keys) ≤ + (keys.map (fun state => (table state).length)).sum + + Runtime.statementPushBound next := by + induction keys with + | nil => simp [dispatch] + | cons key rest ih => + simp only [dispatch, Runtime.statementPushBound, statementPushBound_pushWord, + List.length_reverse, List.map_cons, List.sum_cons] + apply max_le <;> omega + +def emit (dst : K) (table : σ → List (Γ dst)) (keys : List σ) + (next : TM2.Stmt Γ Λ σ) : TM2.Stmt Γ Λ σ := + dispatch dst table next keys + +def tableBound (dst : K) (table : σ → List (Γ dst)) (keys : List σ) : ℕ := + (keys.map (fun state => (table state).length)).sum + +theorem stepAux_emit (dst : K) (table : σ → List (Γ dst)) + (keys : List σ) (hkeys : ∀ state, state ∈ keys) (next : TM2.Stmt Γ Λ σ) (state : σ) (tapes : ∀ k, List (Γ k)) : + TM2.stepAux (emit dst table keys next) state tapes = + TM2.stepAux next state (Function.update tapes dst (table state ++ tapes dst)) := + stepAux_dispatch dst table next keys state (hkeys state) tapes + +omit [DecidableEq K] in +theorem emit_push_bound (dst : K) (table : σ → List (Γ dst)) + (keys : List σ) (next : TM2.Stmt Γ Λ σ) : + Runtime.statementPushBound (emit dst table keys next) ≤ + tableBound dst table keys + Runtime.statementPushBound next := + dispatch_push_bound dst table next _ + +def emitInTime (dst : K) (table : σ → List (Γ dst)) + (keys : List σ) (hkeys : ∀ state, state ∈ keys) + (program : Λ → TM2.Stmt Γ Λ σ) (label exitLabel : Λ) + (atLabel : program label = emit dst table keys (.goto (fun _ => exitLabel))) + (state : σ) (tapes : ∀ k, List (Γ k)) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some label, state, tapes⟩ + (some ⟨some exitLabel, state, + Function.update tapes dst (table state ++ tapes dst)⟩) 1 where + steps := 1 + evals_in_steps := by + change some (TM2.stepAux (program label) state tapes) = _ + rw [atLabel, stepAux_emit dst table keys hkeys] + rfl + steps_le_m := Nat.le_refl _ + +omit [DecidableEq σ] in +theorem output_frame (dst : K) (table : σ → List (Γ dst)) + (state : σ) (tapes : ∀ k, List (Γ k)) (k : K) (h : k ≠ dst) : + (Function.update tapes dst (table state ++ tapes dst)) k = tapes k := by + simp [Function.update, h] + +end MinUncutGames.Foundations.Complexity.MachineFiniteTable + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineFixedDivMod.lean b/lean/OAI/Computability/MinUncut/Machines/MachineFixedDivMod.lean new file mode 100644 index 0000000000000000000000000000000000000000..4dfefca6ee83a71ee4d1e74afd907ad1a90b8a15 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineFixedDivMod.lean @@ -0,0 +1,910 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineCloudPrefix +import OAI.Computability.MinUncut.PCP.ExpanderRowControl + +namespace OAI + +namespace MinUncutGames.Foundations.Complexity.MachineFixedDivMod + +open Turing +open Reduction.MachineSubstitution (pushWord stepAux_pushWord statementPushBound_pushWord) + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool +abbrev State (σ : Type) (d : Nat) := (σ × Fin d) × Option Bool + +def residue (d : Nat) (positive : 0 < d) (n : Nat) : Fin d := + ⟨n % d, Nat.mod_lt n positive⟩ + +def nextResidue (d : Nat) (positive : 0 < d) (r : Fin d) : Fin d := + residue d positive (r.val + 1) + +theorem nextResidue_residue (d : Nat) (positive : 0 < d) (n : Nat) : + nextResidue d positive (residue d positive n) = residue d positive (n + 1) := by + apply Fin.ext + change (n % d + 1) % d = (n + 1) % d + simp only [Nat.add_mod, Nat.mod_mod] + +def scanLoop (d : Nat) (positive : 0 < d) (source quotient : K) + (scanLabel : Λ) (emitterLabel : Fin d → Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (State σ d) := + .pop source (fun state head => (state.1, head)) + (.branch (fun state => state.2.getD false) + (.branch (fun state => decide ((nextResidue d positive state.1.2).val = 0)) + (.push quotient (fun _ => true) + (.load (fun state => ((state.1.1, nextResidue d positive state.1.2), state.2)) + (.goto fun _ => scanLabel))) + (.load (fun state => ((state.1.1, nextResidue d positive state.1.2), state.2)) + (.goto fun _ => scanLabel))) + (.push source (fun _ => false) (.goto fun state => emitterLabel state.1.2))) + +def emitter (d : Nat) (positive : 0 < d) (remainder : K) (exit : Option Λ) + (r : Fin d) : TM2.Stmt (Alphabet (K := K)) Λ (State σ d) := + pushWord remainder (List.replicate r.val true) + (.load (fun state => ((state.1.1, residue d positive 0), none)) + (Reduction.MachineTransfer.exitAt remainder exit)) + +omit [DecidableEq K] in +theorem scanPushBound (d : Nat) (positive : 0 < d) (source quotient : K) + (scanLabel : Λ) (emitterLabel : Fin d → Λ) : + Runtime.statementPushBound (scanLoop (σ := σ) d positive source quotient scanLabel + emitterLabel) = 1 := rfl + +omit [DecidableEq K] in +theorem emitterPushBound (d : Nat) (positive : 0 < d) (remainder : K) + (exit : Option Λ) (r : Fin d) : + Runtime.statementPushBound (emitter (σ := σ) d positive remainder exit r) = r.val := by + cases exit <;> + simp [emitter, statementPushBound_pushWord, Runtime.statementPushBound, + Reduction.MachineTransfer.exitAt] + +abbrev tapes (source quotient remainder : K) (base : K → List Bool) + (input quotientWord remainderWord : List Bool) : K → List Bool := + MachineCopy.forkTapes source quotient remainder base input quotientWord remainderWord + +def unaryTapes (source quotient remainder : K) (base : K → List Bool) + (n q r : Nat) (sourceSuffix quotientSuffix remainderSuffix : List Bool) : K → List Bool := + tapes source quotient remainder base (encodeWord n ++ sourceSuffix) + (encodeWord q ++ quotientSuffix) (encodeWord r ++ remainderSuffix) + +@[simp] theorem unaryTapes_source (source quotient remainder : K) + (sourceQuotient : source ≠ quotient) (sourceRemainder : source ≠ remainder) + (base : K → List Bool) (n q r : Nat) + (sourceSuffix quotientSuffix remainderSuffix : List Bool) : + unaryTapes source quotient remainder base n q r sourceSuffix quotientSuffix + remainderSuffix source = encodeWord n ++ sourceSuffix := by + simp [unaryTapes, sourceQuotient, sourceRemainder] + +@[simp] theorem unaryTapes_quotient (source quotient remainder : K) + (quotientRemainder : quotient ≠ remainder) (base : K → List Bool) (n q r : Nat) + (sourceSuffix quotientSuffix remainderSuffix : List Bool) : + unaryTapes source quotient remainder base n q r sourceSuffix quotientSuffix + remainderSuffix quotient = encodeWord q ++ quotientSuffix := by + simp [unaryTapes, quotientRemainder] + +@[simp] theorem unaryTapes_remainder (source quotient remainder : K) + (base : K → List Bool) (n q r : Nat) + (sourceSuffix quotientSuffix remainderSuffix : List Bool) : + unaryTapes source quotient remainder base n q r sourceSuffix quotientSuffix + remainderSuffix remainder = encodeWord r ++ remainderSuffix := by + simp [unaryTapes] + +theorem unaryTapes_other (source quotient remainder other : K) + (notSource : other ≠ source) (notQuotient : other ≠ quotient) + (notRemainder : other ≠ remainder) (base : K → List Bool) (n q r : Nat) + (sourceSuffix quotientSuffix remainderSuffix : List Bool) : + unaryTapes source quotient remainder base n q r sourceSuffix quotientSuffix + remainderSuffix other = base other := by + simp [unaryTapes, tapes, MachineCopy.forkTapes, notSource, notQuotient, notRemainder] + +theorem update_source (source quotient remainder : K) + (sourceQuotient : source ≠ quotient) (sourceRemainder : source ≠ remainder) + (quotientRemainder : quotient ≠ remainder) (base : K → List Bool) + (input quotientWord remainderWord replacement : List Bool) : + Function.update (tapes source quotient remainder base input quotientWord remainderWord) + source replacement = tapes source quotient remainder base replacement quotientWord remainderWord := by + funext k + by_cases hs : k = source + · subst k + simp [tapes, MachineCopy.forkTapes, sourceQuotient, sourceRemainder] + · by_cases hq : k = quotient + · subst k + simp [tapes, MachineCopy.forkTapes, Ne.symm sourceQuotient, quotientRemainder] + · by_cases hr : k = remainder + · subst k + simp [tapes, MachineCopy.forkTapes, Ne.symm sourceRemainder] + · simp [tapes, MachineCopy.forkTapes, hs, hq, hr] + +private theorem update_quotient (source quotient remainder : K) + (quotientRemainder : quotient ≠ remainder) (base : K → List Bool) + (input quotientWord remainderWord replacement : List Bool) : + Function.update (tapes source quotient remainder base input quotientWord remainderWord) + quotient replacement = tapes source quotient remainder base input replacement remainderWord := by + funext k + by_cases hq : k = quotient + · subst k + simp [tapes, MachineCopy.forkTapes, quotientRemainder] + · by_cases hr : k = remainder + · subst k + simp [tapes, MachineCopy.forkTapes, Ne.symm quotientRemainder] + · simp [tapes, MachineCopy.forkTapes, hq, hr] + +private theorem update_remainder (source quotient remainder : K) (base : K → List Bool) + (input quotientWord remainderWord replacement : List Bool) : + Function.update (tapes source quotient remainder base input quotientWord remainderWord) + remainder replacement = tapes source quotient remainder base input quotientWord replacement := by + simp [tapes, MachineCopy.forkTapes] + +theorem scanAux_true (d : Nat) (positive : 0 < d) (source quotient remainder : K) + (sourceQuotient : source ≠ quotient) (sourceRemainder : source ≠ remainder) + (quotientRemainder : quotient ≠ remainder) (scanLabel : Λ) (emitterLabel : Fin d → Λ) + (base : K → List Bool) (input quotientWord remainderWord : List Bool) + (ambient : σ) (r : Fin d) (register : Option Bool) : + TM2.stepAux (scanLoop d positive source quotient scanLabel emitterLabel) + ((ambient, r), register) + (tapes source quotient remainder base (true :: input) quotientWord remainderWord) = + ⟨some scanLabel, ((ambient, nextResidue d positive r), some true), + tapes source quotient remainder base input + (if (nextResidue d positive r).val = 0 then true :: quotientWord else quotientWord) + remainderWord⟩ := by + by_cases hcarry : (nextResidue d positive r).val = 0 <;> + simp [scanLoop, TM2.stepAux, sourceQuotient, sourceRemainder, quotientRemainder, + update_source, update_quotient, hcarry] + +theorem scanAux_false (d : Nat) (positive : 0 < d) (source quotient remainder : K) + (sourceQuotient : source ≠ quotient) (sourceRemainder : source ≠ remainder) + (quotientRemainder : quotient ≠ remainder) (scanLabel : Λ) (emitterLabel : Fin d → Λ) + (base : K → List Bool) (input quotientWord remainderWord : List Bool) + (ambient : σ) (r : Fin d) (register : Option Bool) : + TM2.stepAux (scanLoop d positive source quotient scanLabel emitterLabel) + ((ambient, r), register) + (tapes source quotient remainder base (false :: input) quotientWord remainderWord) = + ⟨some (emitterLabel r), ((ambient, r), some false), + tapes source quotient remainder base (false :: input) quotientWord remainderWord⟩ := by + simp [scanLoop, TM2.stepAux, sourceQuotient, sourceRemainder, quotientRemainder, + update_source] + +theorem scanStep_succ (d : Nat) (positive : 0 < d) (source quotient remainder : K) + (sourceQuotient : source ≠ quotient) (sourceRemainder : source ≠ remainder) + (quotientRemainder : quotient ≠ remainder) (scanLabel : Λ) (emitterLabel : Fin d → Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ d)) + (atScan : program scanLabel = scanLoop d positive source quotient scanLabel emitterLabel) + (base : K → List Bool) (n k : Nat) + (sourceSuffix quotientSuffix remainderSuffix : List Bool) + (ambient : σ) (register : Option Bool) : + TM2.step program ⟨some scanLabel, ((ambient, residue d positive k), register), + unaryTapes source quotient remainder base (n + 1) (k / d) 0 + sourceSuffix quotientSuffix remainderSuffix⟩ = + some ⟨some scanLabel, ((ambient, residue d positive (k + 1)), some true), + unaryTapes source quotient remainder base n ((k + 1) / d) 0 + sourceSuffix quotientSuffix remainderSuffix⟩ := by + change some (TM2.stepAux (program scanLabel) ((ambient, residue d positive k), register) + (unaryTapes source quotient remainder base (n + 1) (k / d) 0 + sourceSuffix quotientSuffix remainderSuffix)) = _ + rw [atScan] + simp only [unaryTapes, encodeWord, List.replicate_succ, List.cons_append] + rw [scanAux_true d positive source quotient remainder sourceQuotient sourceRemainder + quotientRemainder, nextResidue_residue] + by_cases hmod : (k + 1) % d = 0 + · rw [Nat.succ_div_of_mod_eq_zero hmod] + simp [residue, hmod, List.replicate_succ] + · rw [Nat.succ_div_of_mod_ne_zero hmod] + simp [residue, hmod] + +theorem scanStep_zero (d : Nat) (positive : 0 < d) (source quotient remainder : K) + (sourceQuotient : source ≠ quotient) (sourceRemainder : source ≠ remainder) + (quotientRemainder : quotient ≠ remainder) (scanLabel : Λ) (emitterLabel : Fin d → Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ d)) + (atScan : program scanLabel = scanLoop d positive source quotient scanLabel emitterLabel) + (base : K → List Bool) (q : Nat) + (sourceSuffix quotientSuffix remainderSuffix : List Bool) + (ambient : σ) (r : Fin d) (register : Option Bool) : + TM2.step program ⟨some scanLabel, ((ambient, r), register), + unaryTapes source quotient remainder base 0 q 0 + sourceSuffix quotientSuffix remainderSuffix⟩ = + some ⟨some (emitterLabel r), ((ambient, r), some false), + unaryTapes source quotient remainder base 0 q 0 + sourceSuffix quotientSuffix remainderSuffix⟩ := by + change some (TM2.stepAux (program scanLabel) ((ambient, r), register) + (unaryTapes source quotient remainder base 0 q 0 + sourceSuffix quotientSuffix remainderSuffix)) = _ + rw [atScan] + simp only [unaryTapes, encodeWord, List.replicate_zero, List.nil_append, + List.singleton_append] + rw [scanAux_false d positive source quotient remainder sourceQuotient sourceRemainder + quotientRemainder] + +theorem emitterStep (d : Nat) (positive : 0 < d) (source quotient remainder : K) + (emitterLabel : Fin d → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ d)) + (atEmitter : ∀ r, program (emitterLabel r) = emitter d positive remainder exit r) + (base : K → List Bool) (n q : Nat) + (sourceSuffix quotientSuffix remainderSuffix : List Bool) + (ambient : σ) (r : Fin d) (register : Option Bool) : + TM2.step program ⟨some (emitterLabel r), ((ambient, r), register), + unaryTapes source quotient remainder base n q 0 + sourceSuffix quotientSuffix remainderSuffix⟩ = + some ⟨exit, ((ambient, residue d positive 0), none), + unaryTapes source quotient remainder base n q r.val + sourceSuffix quotientSuffix remainderSuffix⟩ := by + change some (TM2.stepAux (program (emitterLabel r)) ((ambient, r), register) + (unaryTapes source quotient remainder base n q 0 + sourceSuffix quotientSuffix remainderSuffix)) = _ + rw [atEmitter] + unfold emitter + rw [stepAux_pushWord] + simp only [unaryTapes, MachineCopy.forkTapes_right, List.reverse_replicate] + rw [update_remainder] + cases exit <;> + simp [TM2.stepAux, Reduction.MachineTransfer.exitAt, encodeWord, List.append_assoc] + +theorem trace_fromCount (d : Nat) (positive : 0 < d) (source quotient remainder : K) + (sourceQuotient : source ≠ quotient) (sourceRemainder : source ≠ remainder) + (quotientRemainder : quotient ≠ remainder) (scanLabel : Λ) (emitterLabel : Fin d → Λ) + (exit : Option Λ) (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ d)) + (atScan : program scanLabel = scanLoop d positive source quotient scanLabel emitterLabel) + (atEmitter : ∀ r, program (emitterLabel r) = emitter d positive remainder exit r) + (base : K → List Bool) (n k : Nat) + (sourceSuffix quotientSuffix remainderSuffix : List Bool) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[n + 2] + (some ⟨some scanLabel, ((ambient, residue d positive k), register), + unaryTapes source quotient remainder base n (k / d) 0 + sourceSuffix quotientSuffix remainderSuffix⟩) = + some ⟨exit, ((ambient, residue d positive 0), none), + unaryTapes source quotient remainder base 0 ((k + n) / d) ((k + n) % d) + sourceSuffix quotientSuffix remainderSuffix⟩ := by + induction n generalizing k register with + | zero => + change (TM2.step program ⟨some scanLabel, ((ambient, residue d positive k), register), + unaryTapes source quotient remainder base 0 (k / d) 0 + sourceSuffix quotientSuffix remainderSuffix⟩).bind (TM2.step program) = _ + rw [scanStep_zero d positive source quotient remainder sourceQuotient sourceRemainder + quotientRemainder scanLabel emitterLabel program atScan, Option.bind_some] + simpa only [residue, Nat.add_zero] using + emitterStep d positive source quotient remainder emitterLabel exit program atEmitter + base 0 (k / d) sourceSuffix quotientSuffix remainderSuffix ambient + (residue d positive k) (some false) + | succ n ih => + rw [Function.iterate_succ_apply] + change (MachineComposition.advance (TM2.step program))^[n + 2] + (TM2.step program ⟨some scanLabel, ((ambient, residue d positive k), register), + unaryTapes source quotient remainder base (n + 1) (k / d) 0 + sourceSuffix quotientSuffix remainderSuffix⟩) = _ + rw [scanStep_succ d positive source quotient remainder sourceQuotient sourceRemainder + quotientRemainder scanLabel emitterLabel program atScan] + simpa only [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using ih (k + 1) (some true) + +theorem divModTrace (d : Nat) (positive : 0 < d) (source quotient remainder : K) + (sourceQuotient : source ≠ quotient) (sourceRemainder : source ≠ remainder) + (quotientRemainder : quotient ≠ remainder) (scanLabel : Λ) (emitterLabel : Fin d → Λ) + (exit : Option Λ) (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ d)) + (atScan : program scanLabel = scanLoop d positive source quotient scanLabel emitterLabel) + (atEmitter : ∀ r, program (emitterLabel r) = emitter d positive remainder exit r) + (base : K → List Bool) (n : Nat) + (sourceSuffix quotientSuffix remainderSuffix : List Bool) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[n + 2] + (some ⟨some scanLabel, ((ambient, residue d positive 0), register), + unaryTapes source quotient remainder base n 0 0 + sourceSuffix quotientSuffix remainderSuffix⟩) = + some ⟨exit, ((ambient, residue d positive 0), none), + unaryTapes source quotient remainder base 0 (n / d) (n % d) + sourceSuffix quotientSuffix remainderSuffix⟩ := by + simpa only [Nat.zero_add, Nat.zero_div] using + trace_fromCount d positive source quotient remainder sourceQuotient sourceRemainder + quotientRemainder scanLabel emitterLabel exit program atScan atEmitter base n 0 + sourceSuffix quotientSuffix remainderSuffix ambient register + +theorem divModFromTapes (d : Nat) (positive : 0 < d) (source quotient remainder : K) + (sourceQuotient : source ≠ quotient) (sourceRemainder : source ≠ remainder) + (quotientRemainder : quotient ≠ remainder) (scanLabel : Λ) (emitterLabel : Fin d → Λ) + (exit : Option Λ) (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ d)) + (atScan : program scanLabel = scanLoop d positive source quotient scanLabel emitterLabel) + (atEmitter : ∀ r, program (emitterLabel r) = emitter d positive remainder exit r) + (base : K → List Bool) (n : Nat) + (sourceSuffix quotientSuffix remainderSuffix : List Bool) + (sourceInput : base source = encodeWord n ++ sourceSuffix) + (quotientInput : base quotient = encodeWord 0 ++ quotientSuffix) + (remainderInput : base remainder = encodeWord 0 ++ remainderSuffix) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[n + 2] + (some ⟨some scanLabel, ((ambient, residue d positive 0), register), base⟩) = + some ⟨exit, ((ambient, residue d positive 0), none), + unaryTapes source quotient remainder base 0 (n / d) (n % d) + sourceSuffix quotientSuffix remainderSuffix⟩ := by + have hbase : unaryTapes source quotient remainder base n 0 0 sourceSuffix quotientSuffix + remainderSuffix = base := by + simp only [unaryTapes, ← sourceInput, ← quotientInput, ← remainderInput, + MachineCopy.forkTapes_self] + have h := divModTrace d positive source quotient remainder sourceQuotient sourceRemainder + quotientRemainder scanLabel emitterLabel exit program atScan atEmitter base n + sourceSuffix quotientSuffix remainderSuffix ambient register + rw [hbase] at h + exact h + +def divModInTime (d : Nat) (positive : 0 < d) (source quotient remainder : K) + (sourceQuotient : source ≠ quotient) (sourceRemainder : source ≠ remainder) + (quotientRemainder : quotient ≠ remainder) (scanLabel : Λ) (emitterLabel : Fin d → Λ) + (exit : Option Λ) (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ d)) + (atScan : program scanLabel = scanLoop d positive source quotient scanLabel emitterLabel) + (atEmitter : ∀ r, program (emitterLabel r) = emitter d positive remainder exit r) + (base : K → List Bool) (n : Nat) + (sourceSuffix quotientSuffix remainderSuffix : List Bool) + (sourceInput : base source = encodeWord n ++ sourceSuffix) + (quotientInput : base quotient = encodeWord 0 ++ quotientSuffix) + (remainderInput : base remainder = encodeWord 0 ++ remainderSuffix) + (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some scanLabel, ((ambient, residue d positive 0), register), base⟩ + (some ⟨exit, ((ambient, residue d positive 0), none), + unaryTapes source quotient remainder base 0 (n / d) (n % d) + sourceSuffix quotientSuffix remainderSuffix⟩) (n + 2) where + steps := n + 2 + evals_in_steps := divModFromTapes d positive source quotient remainder sourceQuotient + sourceRemainder quotientRemainder scanLabel emitterLabel exit program atScan atEmitter + base n sourceSuffix quotientSuffix remainderSuffix sourceInput quotientInput remainderInput + ambient register + steps_le_m := Nat.le_refl _ + +theorem scanTrace_fromCount (d : Nat) (positive : 0 < d) (source quotient remainder : K) + (sourceQuotient : source ≠ quotient) (sourceRemainder : source ≠ remainder) + (quotientRemainder : quotient ≠ remainder) (scanLabel : Λ) (emitterLabel : Fin d → Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ d)) + (atScan : program scanLabel = scanLoop d positive source quotient scanLabel emitterLabel) + (base : K → List Bool) (n k : Nat) + (sourceSuffix quotientSuffix remainderSuffix : List Bool) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[n + 1] + (some ⟨some scanLabel, ((ambient, residue d positive k), register), + unaryTapes source quotient remainder base n (k / d) 0 + sourceSuffix quotientSuffix remainderSuffix⟩) = + some ⟨some (emitterLabel (residue d positive (k + n))), + ((ambient, residue d positive (k + n)), some false), + unaryTapes source quotient remainder base 0 ((k + n) / d) 0 + sourceSuffix quotientSuffix remainderSuffix⟩ := by + induction n generalizing k register with + | zero => + simpa only [Nat.zero_add, Nat.add_zero, Function.iterate_one, + MachineComposition.advance_some] using + scanStep_zero d positive source quotient remainder sourceQuotient sourceRemainder + quotientRemainder scanLabel emitterLabel program atScan base (k / d) + sourceSuffix quotientSuffix remainderSuffix ambient (residue d positive k) register + | succ n ih => + rw [Function.iterate_succ_apply] + change (MachineComposition.advance (TM2.step program))^[n + 1] + (TM2.step program ⟨some scanLabel, ((ambient, residue d positive k), register), + unaryTapes source quotient remainder base (n + 1) (k / d) 0 + sourceSuffix quotientSuffix remainderSuffix⟩) = _ + rw [scanStep_succ d positive source quotient remainder sourceQuotient sourceRemainder + quotientRemainder scanLabel emitterLabel program atScan] + simpa only [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using ih (k + 1) (some true) + +def emitterWithFinish [Fintype σ] (d : Nat) (positive : 0 < d) (remainder : K) + (exit : Option Λ) (finish : σ → Fin d → σ) (r : Fin d) : + TM2.Stmt (Alphabet (K := K)) Λ (State σ d) := + pushWord remainder (List.replicate r.val true) + (.load (fun state => ((finish state.1.1 r, residue d positive 0), none)) + (Reduction.MachineTransfer.exitAt remainder exit)) + +omit [DecidableEq K] in +theorem emitterWithFinishPushBound [Fintype σ] (d : Nat) (positive : 0 < d) + (remainder : K) (exit : Option Λ) (finish : σ → Fin d → σ) (r : Fin d) : + Runtime.statementPushBound (emitterWithFinish d positive remainder exit finish r) = + r.val := by + cases exit <;> + simp [emitterWithFinish, statementPushBound_pushWord, Runtime.statementPushBound, + Reduction.MachineTransfer.exitAt] + +theorem emitterWithFinishStep [Fintype σ] (d : Nat) (positive : 0 < d) + (source quotient remainder : K) (emitterLabel : Fin d → Λ) (exit : Option Λ) + (finish : σ → Fin d → σ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ d)) + (atEmitter : ∀ r, program (emitterLabel r) = + emitterWithFinish d positive remainder exit finish r) + (base : K → List Bool) (n q : Nat) + (sourceSuffix quotientSuffix remainderSuffix : List Bool) + (ambient : σ) (r : Fin d) (register : Option Bool) : + TM2.step program ⟨some (emitterLabel r), ((ambient, r), register), + unaryTapes source quotient remainder base n q 0 + sourceSuffix quotientSuffix remainderSuffix⟩ = + some ⟨exit, ((finish ambient r, residue d positive 0), none), + unaryTapes source quotient remainder base n q r.val + sourceSuffix quotientSuffix remainderSuffix⟩ := by + change some (TM2.stepAux (program (emitterLabel r)) ((ambient, r), register) + (unaryTapes source quotient remainder base n q 0 + sourceSuffix quotientSuffix remainderSuffix)) = _ + rw [atEmitter] + unfold emitterWithFinish + rw [stepAux_pushWord] + simp only [unaryTapes, MachineCopy.forkTapes_right, List.reverse_replicate] + rw [update_remainder] + cases exit <;> + simp [TM2.stepAux, Reduction.MachineTransfer.exitAt, encodeWord, List.append_assoc] + +theorem divModTraceWithFinish [Fintype σ] (d : Nat) (positive : 0 < d) + (source quotient remainder : K) + (sourceQuotient : source ≠ quotient) (sourceRemainder : source ≠ remainder) + (quotientRemainder : quotient ≠ remainder) (scanLabel : Λ) (emitterLabel : Fin d → Λ) + (exit : Option Λ) (finish : σ → Fin d → σ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ d)) + (atScan : program scanLabel = scanLoop d positive source quotient scanLabel emitterLabel) + (atEmitter : ∀ r, program (emitterLabel r) = + emitterWithFinish d positive remainder exit finish r) + (base : K → List Bool) (n : Nat) + (sourceSuffix quotientSuffix remainderSuffix : List Bool) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[n + 2] + (some ⟨some scanLabel, ((ambient, residue d positive 0), register), + unaryTapes source quotient remainder base n 0 0 + sourceSuffix quotientSuffix remainderSuffix⟩) = + some ⟨exit, ((finish ambient (residue d positive n), residue d positive 0), none), + unaryTapes source quotient remainder base 0 (n / d) (n % d) + sourceSuffix quotientSuffix remainderSuffix⟩ := by + have hscan := scanTrace_fromCount d positive source quotient remainder + sourceQuotient sourceRemainder quotientRemainder scanLabel emitterLabel program atScan + base n 0 sourceSuffix quotientSuffix remainderSuffix ambient register + simp only [Nat.zero_add, Nat.zero_div] at hscan + rw [Function.iterate_succ_apply', hscan, MachineComposition.advance_some] + exact emitterWithFinishStep d positive source quotient remainder emitterLabel exit finish + program atEmitter base 0 (n / d) sourceSuffix quotientSuffix remainderSuffix ambient + (residue d positive n) (some false) + +theorem divModFromTapesWithFinish [Fintype σ] (d : Nat) (positive : 0 < d) + (source quotient remainder : K) + (sourceQuotient : source ≠ quotient) (sourceRemainder : source ≠ remainder) + (quotientRemainder : quotient ≠ remainder) (scanLabel : Λ) (emitterLabel : Fin d → Λ) + (exit : Option Λ) (finish : σ → Fin d → σ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ d)) + (atScan : program scanLabel = scanLoop d positive source quotient scanLabel emitterLabel) + (atEmitter : ∀ r, program (emitterLabel r) = + emitterWithFinish d positive remainder exit finish r) + (base : K → List Bool) (n : Nat) + (sourceSuffix quotientSuffix remainderSuffix : List Bool) + (sourceInput : base source = encodeWord n ++ sourceSuffix) + (quotientInput : base quotient = encodeWord 0 ++ quotientSuffix) + (remainderInput : base remainder = encodeWord 0 ++ remainderSuffix) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[n + 2] + (some ⟨some scanLabel, ((ambient, residue d positive 0), register), base⟩) = + some ⟨exit, ((finish ambient (residue d positive n), residue d positive 0), none), + unaryTapes source quotient remainder base 0 (n / d) (n % d) + sourceSuffix quotientSuffix remainderSuffix⟩ := by + have hbase : unaryTapes source quotient remainder base n 0 0 sourceSuffix quotientSuffix + remainderSuffix = base := by + simp only [unaryTapes, ← sourceInput, ← quotientInput, ← remainderInput, + MachineCopy.forkTapes_self] + have h := divModTraceWithFinish d positive source quotient remainder sourceQuotient + sourceRemainder quotientRemainder scanLabel emitterLabel exit finish program atScan + atEmitter base n sourceSuffix quotientSuffix remainderSuffix ambient register + rw [hbase] at h + exact h + +end MinUncutGames.Foundations.Complexity.MachineFixedDivMod + +namespace MinUncutGames.Foundations.Complexity.MachineExpanderRow + +open Turing +open PCP.ExpanderTables PCP.ExpanderRowControl + +inductive Tape + | inputVertex | table | output + | emitScratch | queryReverse | queryIndex + | lookupOutput | lookupWork | lookupRestore + | quotientFirst | quotientSecond | remainderFirst | remainderSecond + deriving DecidableEq + +protected abbrev Tape.enumList : List Tape := [.inputVertex, .table, .output, .emitScratch, + .queryReverse, .queryIndex, .lookupOutput, .lookupWork, .lookupRestore, .quotientFirst, + .quotientSecond, .remainderFirst, .remainderSecond] + +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 + +inductive Label (d : Nat) + | initialize + | firstEmit (label : PCP.AlphabetTable.Emitter.Label 3 (degree d)) + | firstReverse + | firstLookup (label : MachinePreservingLookupClean.Label) + | firstScan + | firstResidue (r : Fin (degree d)) + | clearQuery + | secondEmit (label : PCP.AlphabetTable.Emitter.Label 3 (degree d)) + | secondReverse + | secondLookup (label : MachinePreservingLookupClean.Label) + | secondScan + | secondResidue (r : Fin (degree d)) + | outputEmit (label : PCP.AlphabetTable.Emitter.Label 3 (rowFactor d)) + | cleanup (i : Fin 6) + | done + deriving DecidableEq, Fintype + +abbrev Ambient (ρ : Type) (d : Nat) := ρ × Control d +abbrev State (ρ : Type) (d : Nat) := + PCP.AlphabetTable.Emitter.State (Ambient ρ d × Fin (degree d)) + +def divisionStates (ρ : Type) (d : Nat) : + MachineFixedDivMod.State (Ambient ρ d × Unit) (degree d) ≃ State ρ d where + toFun s := (((s.1.1.1, s.1.2), ()), s.2) + invFun s := (((s.1.1.1, ()), s.1.1.2), s.2) + left_inv := by rintro ⟨⟨⟨a, u⟩, r⟩, b⟩; cases u; rfl + right_inv := by rintro ⟨⟨⟨a, r⟩, u⟩, b⟩; cases u; rfl + +def firstFinish {ρ : Type} {d : Nat} (s : Ambient ρ d × Unit) + (r : Fin (degree d)) : Ambient ρ d × Unit := + ((s.1.1, receiveFirst s.1.2 r), ()) + +def secondFinish {ρ : Type} {d : Nat} (H : Table (cloudSize d) d) + (s : Ambient ρ d × Unit) (r : Fin (degree d)) : Ambient ρ d × Unit := + ((s.1.1, receiveSecond H s.1.2 r), ()) + +def affinePlan {σ : Type} {bound : Nat} (coefficient : Nat) (offset : σ → Fin bound) : + Fin 3 → PCP.AlphabetTable.Emitter.Command 1 σ bound := + PCP.AlphabetTable.Emitter.listCommands + (PCP.AlphabetTable.Emitter.affineCommands [(0, coefficient)] offset) + +def firstPlan (ρ : Type) (d : Nat) : + Fin 3 → PCP.AlphabetTable.Emitter.Command 1 (Ambient ρ d × Fin (degree d)) (degree d) := + affinePlan (degree d) (fun s => firstOffset s.1.2) + +def secondPlan (ρ : Type) (d : Nat) : + Fin 3 → PCP.AlphabetTable.Emitter.Command 1 (Ambient ρ d × Fin (degree d)) (degree d) := + affinePlan (degree d) (fun s => secondOffset s.1.2) + +def outputPlan (ρ : Type) (d : Nat) : + Fin 3 → PCP.AlphabetTable.Emitter.Command 1 (Ambient ρ d × Fin (degree d)) (rowFactor d) := + affinePlan (rowFactor d) (fun s => outputOffset s.1.2) + +def lookupTape : Fin 5 → Tape + | ⟨0, _⟩ => .table + | ⟨1, _⟩ => .queryIndex + | ⟨2, _⟩ => .lookupWork + | ⟨3, _⟩ => .lookupOutput + | _ => .lookupRestore + +def dirtyTape : Fin 6 → Tape + | ⟨0, _⟩ => .queryIndex + | ⟨1, _⟩ => .lookupOutput + | ⟨2, _⟩ => .quotientFirst + | ⟨3, _⟩ => .quotientSecond + | ⟨4, _⟩ => .remainderFirst + | _ => .remainderSecond + +variable {K Λ ρ : Type} [DecidableEq K] [Fintype ρ] + +def statement {d : Nat} (positive : 0 < d) (H : Table (cloudSize d) d) + (ports : Tape → K) (labels : Label d → Λ) (exit : Option Λ) : + Label d → TM2.Stmt (fun _ : K => Bool) Λ (State ρ d) + | .initialize => + .push (ports .quotientFirst) (fun _ => false) + (.push (ports .quotientSecond) (fun _ => false) + (.push (ports .remainderFirst) (fun _ => false) + (.push (ports .remainderSecond) (fun _ => false) + (.load (fun s => (s.1, none)) + (.goto fun _ => labels (.firstEmit (PCP.AlphabetTable.Emitter.labelAt 3 _ 0 .entry))))))) + | .firstEmit l => + PCP.AlphabetTable.Emitter.statement (firstPlan ρ d) (fun _ => ports .inputVertex) + (ports .emitScratch) (ports .queryReverse) (fun k => labels (.firstEmit k)) + (some (labels .firstReverse)) l + | .firstReverse => + Reduction.MachineTransfer.loopAt (ports .queryReverse) (ports .queryIndex) + id false (labels .firstReverse) + (some (labels (.firstLookup (.run .copyFirst)))) + | .firstLookup l => + MachinePreservingLookupClean.statement (ports ∘ lookupTape) + (fun k => labels (.firstLookup k)) (some (labels .firstScan)) l + | .firstScan => + MachineControl.statement id (divisionStates ρ d) + (MachineFixedDivMod.scanLoop (degree d) (Nat.mul_pos positive positive) + (ports .lookupOutput) (ports .quotientFirst) (labels .firstScan) + (fun r => labels (.firstResidue r))) + | .firstResidue r => + MachineControl.statement id (divisionStates ρ d) + (MachineFixedDivMod.emitterWithFinish (degree d) (Nat.mul_pos positive positive) + (ports .remainderFirst) (some (labels .clearQuery)) firstFinish r) + | .clearQuery => + .pop (ports .queryIndex) (fun s _ => s) + (.pop (ports .lookupOutput) (fun s _ => s) + (.goto fun _ => labels (.secondEmit (PCP.AlphabetTable.Emitter.labelAt 3 _ 0 .entry)))) + | .secondEmit l => + PCP.AlphabetTable.Emitter.statement (secondPlan ρ d) (fun _ => ports .quotientFirst) + (ports .emitScratch) (ports .queryReverse) (fun k => labels (.secondEmit k)) + (some (labels .secondReverse)) l + | .secondReverse => + Reduction.MachineTransfer.loopAt (ports .queryReverse) (ports .queryIndex) + id false (labels .secondReverse) + (some (labels (.secondLookup (.run .copyFirst)))) + | .secondLookup l => + MachinePreservingLookupClean.statement (ports ∘ lookupTape) + (fun k => labels (.secondLookup k)) (some (labels .secondScan)) l + | .secondScan => + MachineControl.statement id (divisionStates ρ d) + (MachineFixedDivMod.scanLoop (degree d) (Nat.mul_pos positive positive) + (ports .lookupOutput) (ports .quotientSecond) (labels .secondScan) + (fun r => labels (.secondResidue r))) + | .secondResidue r => + MachineControl.statement id (divisionStates ρ d) + (MachineFixedDivMod.emitterWithFinish (degree d) (Nat.mul_pos positive positive) + (ports .remainderSecond) + (some (labels (.outputEmit (PCP.AlphabetTable.Emitter.labelAt 3 _ 0 .entry)))) + (secondFinish H) r) + | .outputEmit l => + PCP.AlphabetTable.Emitter.statement (outputPlan ρ d) (fun _ => ports .quotientSecond) + (ports .emitScratch) (ports .output) (fun k => labels (.outputEmit k)) + (some (labels (.cleanup 0))) l + | .cleanup i => + MachineDrain.drain (ports (dirtyTape i)) (labels (.cleanup i)) + (some (if hi : i.val + 1 < 6 then labels (.cleanup ⟨i.val + 1, hi⟩) else labels .done)) + | .done => Reduction.MachineTransfer.exitAt (ports .output) exit + +def program {d : Nat} (positive : 0 < d) (H : Table (cloudSize d) d) : + Label d → TM2.Stmt (fun _ : Tape => Bool) (Label d) (State ρ d) := + statement positive H id id none + +open Turing +open PCP.ExpanderTables PCP.ExpanderRowControl + +private theorem controlStatement_inverse {K Λ σ τ : Type} {Γ : K → Type} + (e : σ ≃ τ) (q : TM2.Stmt Γ Λ σ) : + MachineControl.statement id e.symm (MachineControl.statement id e q) = q := by + induction q <;> + simp_all only [MachineControl.statement, Equiv.apply_symm_apply, + Equiv.symm_apply_apply, id_eq] + +private theorem transportedDivision {K Λ σ τ : Type} [DecidableEq K] [Fintype σ] + (q : Nat) (positive : 0 < q) (source quotient remainder : K) + (sourceQuotient : source ≠ quotient) (sourceRemainder : source ≠ remainder) + (quotientRemainder : quotient ≠ remainder) + (states : MachineFixedDivMod.State σ q ≃ τ) + (scanLabel : Λ) (emitterLabel : Fin q → Λ) (exit : Option Λ) + (finish : σ → Fin q → σ) + (target : Λ → TM2.Stmt (fun _ : K => Bool) Λ τ) + (atScan : target scanLabel = MachineControl.statement id states + (MachineFixedDivMod.scanLoop q positive source quotient scanLabel emitterLabel)) + (atEmitter : ∀ r, target (emitterLabel r) = MachineControl.statement id states + (MachineFixedDivMod.emitterWithFinish q positive remainder exit finish r)) + (base : K → List Bool) (n : Nat) + (sourceSuffix quotientSuffix remainderSuffix : List Bool) + (sourceInput : base source = encodeWord n ++ sourceSuffix) + (quotientInput : base quotient = encodeWord 0 ++ quotientSuffix) + (remainderInput : base remainder = encodeWord 0 ++ remainderSuffix) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step target))^[n + 2] + (some (MachineControl.configuration id states + ⟨some scanLabel, ((ambient, MachineFixedDivMod.residue q positive 0), register), base⟩)) = + some (MachineControl.configuration id states + ⟨exit, ((finish ambient (MachineFixedDivMod.residue q positive n), + MachineFixedDivMod.residue q positive 0), none), + MachineFixedDivMod.unaryTapes source quotient remainder base 0 (n / q) (n % q) + sourceSuffix quotientSuffix remainderSuffix⟩) := by + let sourceProgram := MachineControl.program (Equiv.refl Λ) states.symm target + have sourceScan : sourceProgram scanLabel = + MachineFixedDivMod.scanLoop q positive source quotient scanLabel emitterLabel := by + change MachineControl.statement id states.symm (target scanLabel) = _ + rw [atScan] + exact controlStatement_inverse states _ + have sourceEmit : ∀ r, sourceProgram (emitterLabel r) = + MachineFixedDivMod.emitterWithFinish q positive remainder exit finish r := by + intro r + change MachineControl.statement id states.symm (target (emitterLabel r)) = _ + rw [atEmitter] + exact controlStatement_inverse states _ + have htrace := MachineFixedDivMod.divModFromTapesWithFinish q positive source quotient + remainder sourceQuotient sourceRemainder quotientRemainder scanLabel emitterLabel exit + finish sourceProgram sourceScan sourceEmit base n sourceSuffix quotientSuffix remainderSuffix + sourceInput quotientInput remainderInput ambient register + have roundtrip : MachineControl.program (Equiv.refl Λ) states sourceProgram = target := by + funext label + change MachineControl.statement id states + (MachineControl.statement id states.symm (target label)) = target label + exact controlStatement_inverse states.symm _ + have simulation : ∀ a b, TM2.step sourceProgram a = some b → + TM2.step target (MachineControl.configuration id states a) = + some (MachineControl.configuration id states b) := by + intro a b hab + have h := MachineControl.step_simulation (Equiv.refl Λ) states sourceProgram a + rw [roundtrip, hab] at h + exact h + exact MachineComposition.liftSuccessfulTrace (TM2.step sourceProgram) (TM2.step target) + (MachineControl.configuration id states) simulation (n + 2) _ _ htrace + +variable {K Λ ρ : Type} [DecidableEq K] [Fintype ρ] + +@[simp] theorem divisionStates_apply (ρ : Type) (d : Nat) + (s : MachineFixedDivMod.State (Ambient ρ d × Unit) (degree d)) : + divisionStates ρ d s = (((s.1.1.1, s.1.2), ()), s.2) := rfl + +def divisionState {d : Nat} (positive : 0 < d) (ambient : ρ) (control : Control d) + (register : Option Bool) : State ρ d := + ((((ambient, control), + MachineFixedDivMod.residue (degree d) (Nat.mul_pos positive positive) 0), ()), register) + +def divisionOutput (d : Nat) (ports : Tape → K) (quotient remainder : Tape) + (base : K → List Bool) (n : Nat) + (sourceSuffix quotientSuffix remainderSuffix : List Bool) : K → List Bool := + MachineFixedDivMod.unaryTapes (ports .lookupOutput) (ports quotient) (ports remainder) + base 0 (n / degree d) (n % degree d) sourceSuffix quotientSuffix remainderSuffix + +theorem firstDivisionTrace {d : Nat} (positive : 0 < d) (H : Table (cloudSize d) d) + (ports : Tape → K) (portsInjective : Function.Injective ports) + (labels : Label d → Λ) (exit : Option Λ) + (target : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State ρ d)) + (atProgram : ∀ label, target (labels label) = statement positive H ports labels exit label) + (base : K → List Bool) (n : Nat) + (sourceSuffix quotientSuffix remainderSuffix : List Bool) + (sourceInput : base (ports .lookupOutput) = encodeWord n ++ sourceSuffix) + (quotientInput : base (ports .quotientFirst) = encodeWord 0 ++ quotientSuffix) + (remainderInput : base (ports .remainderFirst) = encodeWord 0 ++ remainderSuffix) + (ambient : ρ) (control : Control d) (register : Option Bool) : + (MachineComposition.advance (TM2.step target))^[n + 2] + (some ⟨some (labels .firstScan), divisionState positive ambient control register, base⟩) = + some ⟨some (labels .clearQuery), divisionState positive ambient + (receiveFirst control (MachineFixedDivMod.residue (degree d) + (Nat.mul_pos positive positive) n)) none, + divisionOutput d ports .quotientFirst .remainderFirst base n + sourceSuffix quotientSuffix remainderSuffix⟩ := by + have hsq : ports .lookupOutput ≠ ports .quotientFirst := + fun h => Tape.noConfusion (portsInjective h) + have hsr : ports .lookupOutput ≠ ports .remainderFirst := + fun h => Tape.noConfusion (portsInjective h) + have hqr : ports .quotientFirst ≠ ports .remainderFirst := + fun h => Tape.noConfusion (portsInjective h) + have hs : target (labels .firstScan) = MachineControl.statement id (divisionStates ρ d) + (MachineFixedDivMod.scanLoop (degree d) (Nat.mul_pos positive positive) + (ports .lookupOutput) (ports .quotientFirst) (labels .firstScan) + (fun r => labels (.firstResidue r))) := atProgram .firstScan + have he : ∀ r, target (labels (.firstResidue r)) = + MachineControl.statement id (divisionStates ρ d) + (MachineFixedDivMod.emitterWithFinish (degree d) (Nat.mul_pos positive positive) + (ports .remainderFirst) (some (labels .clearQuery)) firstFinish r) := + fun r => atProgram (.firstResidue r) + have h := transportedDivision (degree d) (Nat.mul_pos positive positive) + (ports .lookupOutput) (ports .quotientFirst) (ports .remainderFirst) hsq hsr hqr + (divisionStates ρ d) (labels .firstScan) (fun r => labels (.firstResidue r)) + (some (labels .clearQuery)) firstFinish target hs he base n sourceSuffix quotientSuffix + remainderSuffix sourceInput quotientInput remainderInput ((ambient, control), ()) register + simpa only [MachineControl.configuration, divisionStates_apply, firstFinish, divisionState, + divisionOutput, Option.map_some, id_eq] using h + +theorem secondDivisionTrace {d : Nat} (positive : 0 < d) (H : Table (cloudSize d) d) + (ports : Tape → K) (portsInjective : Function.Injective ports) + (labels : Label d → Λ) (exit : Option Λ) + (target : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State ρ d)) + (atProgram : ∀ label, target (labels label) = statement positive H ports labels exit label) + (base : K → List Bool) (n : Nat) + (sourceSuffix quotientSuffix remainderSuffix : List Bool) + (sourceInput : base (ports .lookupOutput) = encodeWord n ++ sourceSuffix) + (quotientInput : base (ports .quotientSecond) = encodeWord 0 ++ quotientSuffix) + (remainderInput : base (ports .remainderSecond) = encodeWord 0 ++ remainderSuffix) + (ambient : ρ) (control : Control d) (register : Option Bool) : + (MachineComposition.advance (TM2.step target))^[n + 2] + (some ⟨some (labels .secondScan), divisionState positive ambient control register, base⟩) = + some ⟨some (labels (.outputEmit (PCP.AlphabetTable.Emitter.labelAt 3 _ 0 .entry))), + divisionState positive ambient + (receiveSecond H control (MachineFixedDivMod.residue (degree d) + (Nat.mul_pos positive positive) n)) none, + divisionOutput d ports .quotientSecond .remainderSecond base n + sourceSuffix quotientSuffix remainderSuffix⟩ := by + have hsq : ports .lookupOutput ≠ ports .quotientSecond := + fun h => Tape.noConfusion (portsInjective h) + have hsr : ports .lookupOutput ≠ ports .remainderSecond := + fun h => Tape.noConfusion (portsInjective h) + have hqr : ports .quotientSecond ≠ ports .remainderSecond := + fun h => Tape.noConfusion (portsInjective h) + have hs : target (labels .secondScan) = MachineControl.statement id (divisionStates ρ d) + (MachineFixedDivMod.scanLoop (degree d) (Nat.mul_pos positive positive) + (ports .lookupOutput) (ports .quotientSecond) (labels .secondScan) + (fun r => labels (.secondResidue r))) := atProgram .secondScan + have he : ∀ r, target (labels (.secondResidue r)) = + MachineControl.statement id (divisionStates ρ d) + (MachineFixedDivMod.emitterWithFinish (degree d) (Nat.mul_pos positive positive) + (ports .remainderSecond) + (some (labels (.outputEmit (PCP.AlphabetTable.Emitter.labelAt 3 _ 0 .entry)))) + (secondFinish H) r) := fun r => atProgram (.secondResidue r) + have h := transportedDivision (degree d) (Nat.mul_pos positive positive) + (ports .lookupOutput) (ports .quotientSecond) (ports .remainderSecond) hsq hsr hqr + (divisionStates ρ d) (labels .secondScan) (fun r => labels (.secondResidue r)) + (some (labels (.outputEmit (PCP.AlphabetTable.Emitter.labelAt 3 _ 0 .entry)))) + (secondFinish H) target hs he base n sourceSuffix quotientSuffix remainderSuffix + sourceInput quotientInput remainderInput ((ambient, control), ()) register + simpa only [MachineControl.configuration, divisionStates_apply, secondFinish, divisionState, + divisionOutput, Option.map_some, id_eq] using h + +@[simp] theorem divisionOutput_source (d : Nat) (ports : Tape → K) + (portsInjective : Function.Injective ports) (quotient remainder : Tape) + (notSourceQuotient : Tape.lookupOutput ≠ quotient) + (notSourceRemainder : Tape.lookupOutput ≠ remainder) + (base : K → List Bool) (n : Nat) + (sourceSuffix quotientSuffix remainderSuffix : List Bool) : + divisionOutput d ports quotient remainder base n sourceSuffix quotientSuffix remainderSuffix + (ports .lookupOutput) = encodeWord 0 ++ sourceSuffix := by + exact MachineFixedDivMod.unaryTapes_source _ _ _ + (fun h => notSourceQuotient (portsInjective h)) + (fun h => notSourceRemainder (portsInjective h)) _ _ _ _ _ _ _ + +@[simp] theorem divisionOutput_quotient (d : Nat) (ports : Tape → K) + (portsInjective : Function.Injective ports) (quotient remainder : Tape) + (distinct : quotient ≠ remainder) (base : K → List Bool) (n : Nat) + (sourceSuffix quotientSuffix remainderSuffix : List Bool) : + divisionOutput d ports quotient remainder base n sourceSuffix quotientSuffix remainderSuffix + (ports quotient) = encodeWord (n / degree d) ++ quotientSuffix := by + exact MachineFixedDivMod.unaryTapes_quotient _ _ _ + (fun h => distinct (portsInjective h)) _ _ _ _ _ _ _ + +@[simp] theorem divisionOutput_remainder (d : Nat) (ports : Tape → K) + (quotient remainder : Tape) (base : K → List Bool) (n : Nat) + (sourceSuffix quotientSuffix remainderSuffix : List Bool) : + divisionOutput d ports quotient remainder base n sourceSuffix quotientSuffix remainderSuffix + (ports remainder) = encodeWord (n % degree d) ++ remainderSuffix := by + exact MachineFixedDivMod.unaryTapes_remainder _ _ _ _ _ _ _ _ _ _ + +theorem divisionOutput_other (d : Nat) (ports : Tape → K) (quotient remainder : Tape) + (base : K → List Bool) (n : Nat) + (sourceSuffix quotientSuffix remainderSuffix : List Bool) (other : K) + (notSource : other ≠ ports .lookupOutput) (notQuotient : other ≠ ports quotient) + (notRemainder : other ≠ ports remainder) : + divisionOutput d ports quotient remainder base n sourceSuffix quotientSuffix remainderSuffix + other = base other := by + exact MachineFixedDivMod.unaryTapes_other _ _ _ other notSource notQuotient notRemainder + _ _ _ _ _ _ _ + +def firstDivisionInTime {d : Nat} (positive : 0 < d) (H : Table (cloudSize d) d) + (ports : Tape → K) (portsInjective : Function.Injective ports) + (labels : Label d → Λ) (exit : Option Λ) + (target : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State ρ d)) + (atProgram : ∀ label, target (labels label) = statement positive H ports labels exit label) + (base : K → List Bool) (n : Nat) + (sourceSuffix quotientSuffix remainderSuffix : List Bool) + (sourceInput : base (ports .lookupOutput) = encodeWord n ++ sourceSuffix) + (quotientInput : base (ports .quotientFirst) = encodeWord 0 ++ quotientSuffix) + (remainderInput : base (ports .remainderFirst) = encodeWord 0 ++ remainderSuffix) + (ambient : ρ) (control : Control d) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step target) + ⟨some (labels .firstScan), divisionState positive ambient control register, base⟩ + (some ⟨some (labels .clearQuery), divisionState positive ambient + (receiveFirst control (MachineFixedDivMod.residue (degree d) + (Nat.mul_pos positive positive) n)) none, + divisionOutput d ports .quotientFirst .remainderFirst base n + sourceSuffix quotientSuffix remainderSuffix⟩) (n + 2) where + steps := n + 2 + evals_in_steps := firstDivisionTrace positive H ports portsInjective labels exit target atProgram + base n sourceSuffix quotientSuffix remainderSuffix sourceInput quotientInput remainderInput + ambient control register + steps_le_m := Nat.le_refl _ + +def secondDivisionInTime {d : Nat} (positive : 0 < d) (H : Table (cloudSize d) d) + (ports : Tape → K) (portsInjective : Function.Injective ports) + (labels : Label d → Λ) (exit : Option Λ) + (target : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State ρ d)) + (atProgram : ∀ label, target (labels label) = statement positive H ports labels exit label) + (base : K → List Bool) (n : Nat) + (sourceSuffix quotientSuffix remainderSuffix : List Bool) + (sourceInput : base (ports .lookupOutput) = encodeWord n ++ sourceSuffix) + (quotientInput : base (ports .quotientSecond) = encodeWord 0 ++ quotientSuffix) + (remainderInput : base (ports .remainderSecond) = encodeWord 0 ++ remainderSuffix) + (ambient : ρ) (control : Control d) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step target) + ⟨some (labels .secondScan), divisionState positive ambient control register, base⟩ + (some ⟨some (labels (.outputEmit (PCP.AlphabetTable.Emitter.labelAt 3 _ 0 .entry))), + divisionState positive ambient + (receiveSecond H control (MachineFixedDivMod.residue (degree d) + (Nat.mul_pos positive positive) n)) none, + divisionOutput d ports .quotientSecond .remainderSecond base n + sourceSuffix quotientSuffix remainderSuffix⟩) (n + 2) where + steps := n + 2 + evals_in_steps := secondDivisionTrace positive H ports portsInjective labels exit target atProgram + base n sourceSuffix quotientSuffix remainderSuffix sourceInput quotientInput remainderInput + ambient control register + steps_le_m := Nat.le_refl _ + +end MinUncutGames.Foundations.Complexity.MachineExpanderRow + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineInitialHeaders.lean b/lean/OAI/Computability/MinUncut/Machines/MachineInitialHeaders.lean new file mode 100644 index 0000000000000000000000000000000000000000..802316bd0eb1f61746957f8b5b5ac89dc7281efe --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineInitialHeaders.lean @@ -0,0 +1,716 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.RawInitialPredicate + +namespace OAI + +section +namespace MinUncutGames.Foundations.Complexity.MachineInitialHeaders + +open Turing +open Reduction.MachineTransfer +open Reduction.MachineSubstitution +open MachineCopy + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool + +def prefixScan (source scratch output : K) (scale : ℕ) (again restore : Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) := + .pop source (fun state head => (state.1, head)) + (.branch (fun state => state.2.getD false) + (.push scratch (fun _ => true) + (pushWord output (List.replicate scale true) (.goto fun _ => again))) + (.branch (fun state => state.2.isSome) + (.push source (fun _ => false) + (.load (fun state => (state.1, none)) (.goto fun _ => restore))) + (.load (fun state => (state.1, none)) (.goto fun _ => restore)))) + +theorem update_source (source scratch output : K) + (hst : source ≠ scratch) (hso : source ≠ output) (hto : scratch ≠ output) + (base : K → List Bool) (input saved emitted replacement : List Bool) : + Function.update (forkTapes source scratch output base input saved emitted) + source replacement = forkTapes source scratch output base replacement saved emitted := by + funext k + by_cases hs : k = source + · subst k; simp [forkTapes, hst, hso] + · by_cases ht : k = scratch + · subst k; simp [forkTapes, Ne.symm hst, hto] + · by_cases ho : k = output + · subst k; simp [forkTapes, Ne.symm hso] + · simp [forkTapes, hs, ht, ho] + +private theorem update_scratch (source scratch output : K) (hto : scratch ≠ output) + (base : K → List Bool) (input saved emitted replacement : List Bool) : + Function.update (forkTapes source scratch output base input saved emitted) + scratch replacement = forkTapes source scratch output base input replacement emitted := by + funext k + by_cases ht : k = scratch + · subst k; simp [forkTapes, hto] + · by_cases ho : k = output + · subst k; simp [forkTapes, Ne.symm hto] + · simp [forkTapes, ht, ho] + +theorem update_output (source scratch output : K) + (base : K → List Bool) (input saved emitted replacement : List Bool) : + Function.update (forkTapes source scratch output base input saved emitted) + output replacement = forkTapes source scratch output base input saved replacement := by + simp [forkTapes] + +theorem prefixStep_true (source scratch output : K) + (hst : source ≠ scratch) (hso : source ≠ output) (hto : scratch ≠ output) + (scale : ℕ) (again restore : Λ) (base : K → List Bool) + (input saved emitted : List Bool) (ambient : σ) (register : Option Bool) : + TM2.stepAux (prefixScan source scratch output scale again restore) + (ambient, register) (forkTapes source scratch output base (true :: input) saved emitted) = + ⟨some again, (ambient, some true), forkTapes source scratch output base input + (true :: saved) (List.replicate scale true ++ emitted)⟩ := by + simp [prefixScan, TM2.stepAux, hst, hso, hto, update_source, update_scratch, + stepAux_pushWord, update_output] + +theorem prefixStep_false (source scratch output : K) + (hst : source ≠ scratch) (hso : source ≠ output) (hto : scratch ≠ output) + (scale : ℕ) (again restore : Λ) (base : K → List Bool) + (suffix saved emitted : List Bool) (ambient : σ) (register : Option Bool) : + TM2.stepAux (prefixScan source scratch output scale again restore) + (ambient, register) (forkTapes source scratch output base (false :: suffix) saved emitted) = + ⟨some restore, (ambient, none), + forkTapes source scratch output base (false :: suffix) saved emitted⟩ := by + simp [prefixScan, TM2.stepAux, hst, hso, hto, update_source] + +private theorem replicate_append_cons (n : ℕ) (xs : List Bool) : + List.replicate n true ++ true :: xs = List.replicate (n + 1) true ++ xs := by + rw [List.replicate_add] + simp + +theorem prefixScanTrace (source scratch output : K) + (hst : source ≠ scratch) (hso : source ≠ output) (hto : scratch ≠ output) + (scale : ℕ) (again restore : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atScan : program again = prefixScan source scratch output scale again restore) + (base : K → List Bool) (n : ℕ) (suffix saved emitted : List Bool) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[n + 1] + (some ⟨some again, (ambient, register), + forkTapes source scratch output base (encodeWord n ++ suffix) saved emitted⟩) = + some ⟨some restore, (ambient, none), + forkTapes source scratch output base (false :: suffix) + (List.replicate n true ++ saved) (List.replicate (scale * n) true ++ emitted)⟩ := by + induction n generalizing saved emitted register with + | zero => + simp only [Nat.zero_add, Function.iterate_one, MachineComposition.advance_some, + encodeWord, List.replicate_zero, List.nil_append, List.singleton_append, + Nat.mul_zero] + change some (TM2.stepAux (program again) _ _) = _ + rw [atScan, prefixStep_false source scratch output hst hso hto] + | succ n ih => + rw [Function.iterate_succ_apply] + change (MachineComposition.advance (TM2.step program))^[n + 1] + (some (TM2.stepAux (program again) _ _)) = _ + rw [atScan] + simp only [encodeWord, List.replicate_succ, List.cons_append] + rw [prefixStep_true source scratch output hst hso hto] + change (MachineComposition.advance (TM2.step program))^[n + 1] + (some ⟨some again, (ambient, some true), + forkTapes source scratch output base (encodeWord n ++ suffix) + (true :: saved) (List.replicate scale true ++ emitted)⟩) = _ + rw [ih] + have hs : List.replicate n true ++ true :: saved = + true :: (List.replicate n true ++ saved) := by + rw [replicate_append_cons, List.replicate_succ, List.cons_append] + simp only [hs, Nat.mul_succ, List.replicate_add, List.append_assoc] + +theorem prefixTrace (source scratch output : K) + (hst : source ≠ scratch) (hso : source ≠ output) (hto : scratch ≠ output) + (scale : ℕ) (again restore : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atScan : program again = prefixScan source scratch output scale again restore) + (atRestore : program restore = loopAt scratch source id false restore exit) + (base : K → List Bool) (n : ℕ) (suffix : List Bool) + (hsource : base source = encodeWord n ++ suffix) (scratchEmpty : base scratch = []) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[2 * n + 2] + (some ⟨some again, (ambient, register), base⟩) = + some ⟨exit, (ambient, none), Function.update base output + (List.replicate (scale * n) true ++ base output)⟩ := by + have scan := prefixScanTrace source scratch output hst hso hto scale again restore + program atScan base n suffix [] (base output) ambient register + have hstart : forkTapes source scratch output base (encodeWord n ++ suffix) [] + (base output) = base := by + rw [← hsource, ← scratchEmpty] + exact forkTapes_self source scratch output base + rw [hstart] at scan + simp only [List.append_nil] at scan + let emitted := List.replicate (scale * n) true ++ base output + let scanned := forkTapes source scratch output base (false :: suffix) + (List.replicate n true) emitted + have restoreTrace := transferAt_fromTapes scratch source (Ne.symm hst) id false + restore exit program atRestore scanned ambient none + change (MachineComposition.advance (TM2.step program))^[(scanned scratch).length + 1] + (some ⟨some restore, (ambient, none), scanned⟩) = _ at restoreTrace + have hs : scanned scratch = List.replicate n true := by simp [scanned, hto] + have hi : scanned source = false :: suffix := by simp [scanned, hst, hso] + rw [hs, hi] at restoreTrace + simp only [List.length_replicate, List.reverse_replicate, List.map_id] at restoreTrace + have hrestored : tapesAt scratch source scanned [] + (List.replicate n true ++ false :: suffix) = Function.update base output emitted := by + funext k + by_cases hks : k = source + · subst k + simp [tapesAt, hso, hsource, encodeWord] + · by_cases hkt : k = scratch + · subst k + simp [tapesAt, Ne.symm hst, hto, scratchEmpty] + · by_cases hko : k = output + · subst k + simp [tapesAt, scanned, forkTapes, Ne.symm hso, Ne.symm hto] + · simp [tapesAt, scanned, forkTapes, hks, hkt, hko] + rw [hrestored] at restoreTrace + rw [show 2 * n + 2 = (n + 1) + (n + 1) by omega, + Function.iterate_add_apply, scan] + exact restoreTrace + +def prefixInTime (source scratch output : K) + (hst : source ≠ scratch) (hso : source ≠ output) (hto : scratch ≠ output) + (scale : ℕ) (again restore : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atScan : program again = prefixScan source scratch output scale again restore) + (atRestore : program restore = loopAt scratch source id false restore exit) + (base : K → List Bool) (n : ℕ) (suffix : List Bool) + (hsource : base source = encodeWord n ++ suffix) (scratchEmpty : base scratch = []) + (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some again, (ambient, register), base⟩ + (some ⟨exit, (ambient, none), Function.update base output + (List.replicate (scale * n) true ++ base output)⟩) (2 * n + 2) where + steps := 2 * n + 2 + evals_in_steps := prefixTrace source scratch output hst hso hto scale again restore exit + program atScan atRestore base n suffix hsource scratchEmpty ambient register + steps_le_m := Nat.le_refl _ + +omit [DecidableEq K] in +theorem prefixScan_pushBound (source scratch output : K) (scale : ℕ) (again restore : Λ) : + Runtime.statementPushBound (prefixScan (σ := σ) source scratch output scale again restore) = + scale + 1 := by + simp only [prefixScan, Runtime.statementPushBound, statementPushBound_pushWord, + List.length_replicate] + omega + +theorem literalTrace (output : K) (word : List Bool) (label : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atLabel : program label = pushWord output word (exitAt output exit)) + (base : K → List Bool) (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[1] + (some ⟨some label, (ambient, register), base⟩) = + some ⟨exit, (ambient, register), + Function.update base output (word.reverse ++ base output)⟩ := by + simp only [Function.iterate_one, MachineComposition.advance_some] + change some (TM2.stepAux (program label) _ _) = _ + rw [atLabel, stepAux_pushWord] + cases exit <;> rfl + +theorem trace_trans {α : Type*} (f : α → α) {a b : ℕ} {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 headerTrace (nTape mTape scratch output : K) + (_hnm : nTape ≠ mTape) (hnt : nTape ≠ scratch) (hno : nTape ≠ output) + (hmt : mTape ≠ scratch) (hmo : mTape ≠ output) (hto : scratch ≠ output) + (scanN restoreN scanM1 restoreM1 closeFirst scanM6 restoreM6 closeSecond : Λ) + (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atScanN : program scanN = prefixScan nTape scratch output 1 scanN restoreN) + (atRestoreN : program restoreN = loopAt scratch nTape id false restoreN (some scanM1)) + (atScanM1 : program scanM1 = prefixScan mTape scratch output 1 scanM1 restoreM1) + (atRestoreM1 : program restoreM1 = loopAt scratch mTape id false restoreM1 (some closeFirst)) + (atCloseFirst : program closeFirst = pushWord output [true, false] + (exitAt output (some scanM6))) + (atScanM6 : program scanM6 = prefixScan mTape scratch output 6 scanM6 restoreM6) + (atRestoreM6 : program restoreM6 = loopAt scratch mTape id false restoreM6 (some closeSecond)) + (atCloseSecond : program closeSecond = pushWord output [true, false] (exitAt output exit)) + (base : K → List Bool) (n m : ℕ) (nSuffix mSuffix : List Bool) + (hn : base nTape = encodeWord n ++ nSuffix) + (hm : base mTape = encodeWord m ++ mSuffix) (ht : base scratch = []) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[2 * n + 4 * m + 8] + (some ⟨some scanN, (ambient, register), base⟩) = + some ⟨exit, (ambient, none), Function.update base output + ((encodeWords [n + m + 1, 6 * m + 1]).reverse ++ base output)⟩ := by + let out1 := List.replicate n true ++ base output + let out2 := List.replicate m true ++ out1 + let out3 := [false, true] ++ out2 + let out4 := List.replicate (6 * m) true ++ out3 + let out5 := [false, true] ++ out4 + let b1 := Function.update base output out1 + let b2 := Function.update base output out2 + let b3 := Function.update base output out3 + let b4 := Function.update base output out4 + let b5 := Function.update base output out5 + have first := prefixTrace nTape scratch output hnt hno hto 1 scanN restoreN + (some scanM1) program atScanN atRestoreN base n nSuffix hn ht ambient register + simp only [Nat.one_mul] at first + change (MachineComposition.advance (TM2.step program))^[2 * n + 2] + (some ⟨some scanN, (ambient, register), base⟩) = + some ⟨some scanM1, (ambient, none), b1⟩ at first + have second := prefixTrace mTape scratch output hmt hmo hto 1 scanM1 restoreM1 + (some closeFirst) program atScanM1 atRestoreM1 b1 m mSuffix + (by simp [b1, hmo, hm]) (by simp [b1, hto, ht]) ambient none + simp only [Nat.one_mul, b1, Function.update_self, Function.update_idem] at second + change (MachineComposition.advance (TM2.step program))^[2 * m + 2] + (some ⟨some scanM1, (ambient, none), b1⟩) = + some ⟨some closeFirst, (ambient, none), b2⟩ at second + have third := literalTrace output [true, false] closeFirst (some scanM6) + program atCloseFirst b2 ambient none + simp only [b2, Function.update_self, Function.update_idem] at third + change (MachineComposition.advance (TM2.step program))^[1] + (some ⟨some closeFirst, (ambient, none), b2⟩) = + some ⟨some scanM6, (ambient, none), b3⟩ at third + have fourth := prefixTrace mTape scratch output hmt hmo hto 6 scanM6 restoreM6 + (some closeSecond) program atScanM6 atRestoreM6 b3 m mSuffix + (by simp [b3, hmo, hm]) (by simp [b3, hto, ht]) ambient none + simp only [b3, Function.update_self, Function.update_idem] at fourth + change (MachineComposition.advance (TM2.step program))^[2 * m + 2] + (some ⟨some scanM6, (ambient, none), b3⟩) = + some ⟨some closeSecond, (ambient, none), b4⟩ at fourth + have fifth := literalTrace output [true, false] closeSecond exit + program atCloseSecond b4 ambient none + simp only [b4, Function.update_self, Function.update_idem] at fifth + change (MachineComposition.advance (TM2.step program))^[1] + (some ⟨some closeSecond, (ambient, none), b4⟩) = + some ⟨exit, (ambient, none), b5⟩ at fifth + have total := trace_trans _ (trace_trans _ (trace_trans _ (trace_trans _ first second) + third) fourth) fifth + have hsteps : (((2 * n + 2) + (2 * m + 2)) + 1 + (2 * m + 2)) + 1 = + 2 * n + 4 * m + 8 := by omega + rw [hsteps] at total + have hout : out5 = (encodeWords [n + m + 1, 6 * m + 1]).reverse ++ base output := by + simp only [out5, out4, out3, out2, out1, encodeWords, encodeWord, + List.reverse_append, List.reverse_replicate, List.reverse_cons, List.reverse_nil, + List.append_nil, List.nil_append, List.append_assoc, List.singleton_append] + rw [show n + m + 1 = 1 + m + n by omega, + show 6 * m + 1 = 1 + 6 * m by omega] + simp only [List.replicate_add, List.replicate_one, List.cons_append, + List.nil_append, List.append_assoc] + simpa only [b5, hout] using total + +def headerInTime (nTape mTape scratch output : K) + (hnm : nTape ≠ mTape) (hnt : nTape ≠ scratch) (hno : nTape ≠ output) + (hmt : mTape ≠ scratch) (hmo : mTape ≠ output) (hto : scratch ≠ output) + (scanN restoreN scanM1 restoreM1 closeFirst scanM6 restoreM6 closeSecond : Λ) + (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atScanN : program scanN = prefixScan nTape scratch output 1 scanN restoreN) + (atRestoreN : program restoreN = loopAt scratch nTape id false restoreN (some scanM1)) + (atScanM1 : program scanM1 = prefixScan mTape scratch output 1 scanM1 restoreM1) + (atRestoreM1 : program restoreM1 = loopAt scratch mTape id false restoreM1 (some closeFirst)) + (atCloseFirst : program closeFirst = pushWord output [true, false] + (exitAt output (some scanM6))) + (atScanM6 : program scanM6 = prefixScan mTape scratch output 6 scanM6 restoreM6) + (atRestoreM6 : program restoreM6 = loopAt scratch mTape id false restoreM6 (some closeSecond)) + (atCloseSecond : program closeSecond = pushWord output [true, false] (exitAt output exit)) + (base : K → List Bool) (n m : ℕ) (nSuffix mSuffix : List Bool) + (hn : base nTape = encodeWord n ++ nSuffix) + (hm : base mTape = encodeWord m ++ mSuffix) (ht : base scratch = []) + (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some scanN, (ambient, register), base⟩ + (some ⟨exit, (ambient, none), Function.update base output + ((encodeWords [n + m + 1, 6 * m + 1]).reverse ++ base output)⟩) + (2 * n + 4 * m + 8) where + steps := 2 * n + 4 * m + 8 + evals_in_steps := headerTrace nTape mTape scratch output hnm hnt hno hmt hmo hto + scanN restoreN scanM1 restoreM1 closeFirst scanM6 restoreM6 closeSecond exit + program atScanN atRestoreN atScanM1 atRestoreM1 atCloseFirst atScanM6 atRestoreM6 + atCloseSecond base n m nSuffix mSuffix hn hm ht ambient register + steps_le_m := Nat.le_refl _ + +end MinUncutGames.Foundations.Complexity.MachineInitialHeaders + +end +section +namespace MinUncutGames.Foundations.PCP.RawInitialMachineModel + +open Turing Complexity Hastad + +inductive Tape + | input | «variables» | counter | index | field (slot : Fin 6) + | scratch | reversed | output + deriving DecidableEq, Fintype + +abbrev Signs := Bool × Bool × Bool +abbrev State := Signs × Option Bool +abbrev Alphabet (_ : Tape) := Bool + +inductive CopyPhase + | tailVariables (slot : Fin 3) + | tailIndex (slot : Fin 3) + | variableName (slot : Fin 3) + | reverseIndex (slot : Fin 3) (orientation : Bool) + | dummyVariables | dummyIndex | dummyReverse + deriving DecidableEq, Fintype + +inductive Label + | headerStart (slot : Fin 2) | headerLoop (slot : Fin 2) + | scanN | restoreN | scanM1 | restoreM1 | closeFirst + | scanM6 | restoreM6 | closeSecond | initializeIndex | guard + | fieldStart (slot : Fin 6) | fieldLoop (slot : Fin 6) | loadSigns + | scan (phase : CopyPhase) | restore (phase : CopyPhase) + | closeTail (slot : Fin 3) (orientation : Bool) + | closeReverse (slot : Fin 3) (orientation : Bool) + | relation (slot : Fin 3) (orientation : Bool) + | cleanupField (slot : Fin 6) | incrementIndex + | closeDummyTail | closeDummyReverse | dummyRelation + | cleanupFinal (slot : Fin 3) | reset | finalReverse + deriving DecidableEq, Fintype + +def initialState : State := ((false, false, false), none) + +def stateKeys : List State := + [false, true].flatMap fun a => [false, true].flatMap fun b => + [false, true].flatMap fun c => + [none, some false, some true].map fun register => ((a, b, c), register) + +theorem stateKeys_complete (state : State) : state ∈ stateKeys := by + rcases state with ⟨⟨a, b, c⟩, register⟩ + cases a <;> cases b <;> cases c <;> cases register with + | none => simp [stateKeys] + | some bit => cases bit <;> simp [stateKeys] + +def nameField (slot : Fin 3) : Fin 6 := ⟨2 * slot.val, by omega⟩ + +def copySource : CopyPhase → Tape + | .tailVariables _ | .dummyVariables => .«variables» + | .variableName slot => .field (nameField slot) + | _ => .index + +def copyScale : CopyPhase → Nat + | .reverseIndex _ _ | .dummyReverse => 6 + | _ => 1 + +def copyNext : CopyPhase → Label + | .tailVariables slot => .scan (.tailIndex slot) + | .tailIndex slot => .closeTail slot false + | .variableName slot => .closeTail slot true + | .reverseIndex slot orientation => .closeReverse slot orientation + | .dummyVariables => .scan .dummyIndex + | .dummyIndex => .closeDummyTail + | .dummyReverse => .closeDummyReverse + +def relationNext (slot : Fin 3) (orientation : Bool) : Label := + if orientation then + if h : slot.val + 1 < 3 then .scan (.tailVariables ⟨slot.val + 1, h⟩) + else .cleanupField 0 + else .scan (.variableName slot) + +def finalTape (slot : Fin 3) : Tape := + if slot.val = 0 then .«variables» else if slot.val = 1 then .counter else .index + +def drain (tape : Tape) (again next : Label) : TM2.Stmt Alphabet Label State := + MachineDrain.drain tape again (some next) + +def headerTape (slot : Fin 2) : Tape := if slot.val = 0 then .«variables» else .counter + +def relationOutput (slot : Fin 3) (orientation : Bool) (state : State) : List Bool := + (encodeWords (RawInitialRows.relationWordsFor state.1 + (RawInitialTables.slotOrder.symm slot) orientation)).reverse + +def program : Label → TM2.Stmt Alphabet Label State + | .headerStart slot => SourceMachine.fieldStart (headerTape slot) (.headerLoop slot) + | .headerLoop slot => SourceMachine.fieldLoop .input (headerTape slot) (.headerLoop slot) + (if slot.val = 0 then some (.headerStart 1) else some .scanN) + | .scanN => MachineInitialHeaders.prefixScan .«variables» .scratch .reversed 1 .scanN .restoreN + | .restoreN => Reduction.MachineTransfer.loopAt .scratch .«variables» id false .restoreN (some .scanM1) + | .scanM1 => MachineInitialHeaders.prefixScan .counter .scratch .reversed 1 .scanM1 .restoreM1 + | .restoreM1 => Reduction.MachineTransfer.loopAt .scratch .counter id false .restoreM1 (some .closeFirst) + | .closeFirst => Reduction.MachineSubstitution.pushWord .reversed [true, false] + (.goto fun _ => .scanM6) + | .scanM6 => MachineInitialHeaders.prefixScan .counter .scratch .reversed 6 .scanM6 .restoreM6 + | .restoreM6 => Reduction.MachineTransfer.loopAt .scratch .counter id false .restoreM6 (some .closeSecond) + | .closeSecond => Reduction.MachineSubstitution.pushWord .reversed [true, false] + (.goto fun _ => .initializeIndex) + | .initializeIndex => .push .index (fun _ => false) (.goto fun _ => .guard) + | .guard => MachineUnaryCounter.guard .counter (.fieldStart 0) (.scan .dummyVariables) + | .fieldStart slot => SourceMachine.fieldStart (.field slot) (.fieldLoop slot) + | .fieldLoop slot => SourceMachine.fieldLoop .input (.field slot) (.fieldLoop slot) + (if h : slot.val + 1 < 6 then some (.fieldStart ⟨slot.val + 1, h⟩) + else some .loadSigns) + | .loadSigns => + .peek (.field 1) (fun state head => ((head.getD false, state.1.2), state.2)) + (.peek (.field 3) (fun state head => ((state.1.1, head.getD false, state.1.2.2), state.2)) + (.peek (.field 5) (fun state head => ((state.1.1, state.1.2.1, head.getD false), state.2)) + (.load (fun state => (state.1, none)) (.goto fun _ => .scan (.tailVariables 0))))) + | .scan phase => MachineInitialHeaders.prefixScan (copySource phase) .scratch .reversed + (copyScale phase) (.scan phase) (.restore phase) + | .restore phase => Reduction.MachineTransfer.loopAt .scratch (copySource phase) id false + (.restore phase) (some (copyNext phase)) + | .closeTail slot orientation => .push .reversed (fun _ => false) + (.goto fun _ => .scan (.reverseIndex slot orientation)) + | .closeReverse slot orientation => Reduction.MachineSubstitution.pushWord .reversed + (encodeWord (2 * slot.val + if orientation then 0 else 1)) + (.goto fun _ => .relation slot orientation) + | .relation slot orientation => MachineFiniteTable.emit .reversed + (relationOutput slot orientation) + stateKeys (.goto fun _ => relationNext slot orientation) + | .cleanupField slot => drain (.field slot) (.cleanupField slot) + (if h : slot.val + 1 < 6 then .cleanupField ⟨slot.val + 1, h⟩ else .incrementIndex) + | .incrementIndex => .push .index (fun _ => true) (.goto fun _ => .guard) + | .closeDummyTail => .push .reversed (fun _ => false) (.goto fun _ => .scan .dummyReverse) + | .closeDummyReverse => .push .reversed (fun _ => false) (.goto fun _ => .dummyRelation) + | .dummyRelation => Reduction.MachineSubstitution.pushWord .reversed + (encodeWords (GraphTables.relationWords (GraphTables.relationOf (fun _ _ => true)))) + (.goto fun _ => .cleanupFinal 0) + | .cleanupFinal slot => drain (finalTape slot) (.cleanupFinal slot) + (if h : slot.val + 1 < 3 then .cleanupFinal ⟨slot.val + 1, h⟩ else .reset) + | .reset => .load (fun _ => initialState) (.goto fun _ => .finalReverse) + | .finalReverse => Reduction.MachineTransfer.loopAt .reversed .output id false .finalReverse none + +def machine : FinTM2 where + K := Tape + k₀ := .input + k₁ := .output + Γ := Alphabet + Λ := Label + main := .headerStart 0 + σ := State + initialState := initialState + m := program + +end MinUncutGames.Foundations.PCP.RawInitialMachineModel + +end +section +namespace MinUncutGames.Foundations.PCP.RawInitialMachineStart + +open Turing Complexity Hastad RawInitialMachineModel + +def inputTapes (bits : List Bool) : Tape → List Bool + | .input => bits + | _ => [] + +private def firstTapes (n m : ℕ) (clauseBits : List Bool) : Tape → List Bool + | .input => encodeWord m ++ clauseBits + | .«variables» => encodeWord n + | _ => [] + +def counterTapes (n m : ℕ) (clauseBits : List Bool) : Tape → List Bool + | .input => clauseBits + | .«variables» => encodeWord n + | .counter => encodeWord m + | _ => [] + +private def headerTapes (n m : ℕ) (clauseBits : List Bool) : Tape → List Bool + | .input => clauseBits + | .«variables» => encodeWord n + | .counter => encodeWord m + | .reversed => (encodeWords [n + m + 1, 6 * m + 1]).reverse + | _ => [] + +def startTapes (n m : ℕ) (clauseBits : List Bool) : Tape → List Bool + | .input => clauseBits + | .«variables» => encodeWord n + | .counter => encodeWord m + | .index => [false] + | .reversed => (encodeWords [n + m + 1, 6 * m + 1]).reverse + | _ => [] + +theorem initList_eq (bits : List Bool) : + initList machine bits = + ⟨some (.headerStart 0), initialState, inputTapes bits⟩ := by + unfold initList + congr 1 + funext k + change Tape at k + cases k <;> rfl + +theorem trace_trans {α : Type*} (f : α → α) {a b : ℕ} {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 readCountersTrace (n m : ℕ) (clauseBits : List Bool) : + (MachineComposition.advance (TM2.step program))^[n + m + 4] + (some (initList machine (encodeWords [n, m] ++ clauseBits))) = + some ⟨some .scanN, initialState, counterTapes n m clauseBits⟩ := by + let t0 := inputTapes (encodeWords [n, m] ++ clauseBits) + have first := (SourceMachine.fieldInTime .input .«variables» (by decide) + (.headerStart 0) (.headerLoop 0) (some (.headerStart 1)) program rfl rfl + t0 n (encodeWord m ++ clauseBits) + (by simp [t0, inputTapes, encodeWords, List.append_assoc]) + (false, false, false) none).evals_in_steps + change (MachineComposition.advance (TM2.step program))^[n + 2] + (some ⟨some (.headerStart 0), initialState, t0⟩) = _ at first + have firstFrame : SourceMachine.fieldTapes .input .«variables» t0 + (encodeWord m ++ clauseBits) (encodeWord n ++ t0 .«variables») = + firstTapes n m clauseBits := by + funext k + cases k <;> simp [SourceMachine.fieldTapes, t0, inputTapes, firstTapes] + rw [firstFrame] at first + have second := (SourceMachine.fieldInTime .input .counter (by decide) + (.headerStart 1) (.headerLoop 1) (some .scanN) program rfl rfl + (firstTapes n m clauseBits) m clauseBits rfl (false, false, false) none).evals_in_steps + change (MachineComposition.advance (TM2.step program))^[m + 2] + (some ⟨some (.headerStart 1), initialState, firstTapes n m clauseBits⟩) = _ at second + have secondFrame : SourceMachine.fieldTapes .input .counter (firstTapes n m clauseBits) + clauseBits (encodeWord m ++ firstTapes n m clauseBits .counter) = + counterTapes n m clauseBits := by + funext k + cases k <;> simp [SourceMachine.fieldTapes, firstTapes, counterTapes] + rw [secondFrame] at second + have total := trace_trans _ first second + rw [show (n + 2) + (m + 2) = n + m + 4 by omega] at total + simpa only [initList_eq, t0, initialState] using! total + +theorem headersTrace (n m : ℕ) (clauseBits : List Bool) : + (MachineComposition.advance (TM2.step program))^[2 * n + 4 * m + 8] + (some ⟨some .scanN, initialState, counterTapes n m clauseBits⟩) = + some ⟨some .initializeIndex, initialState, headerTapes n m clauseBits⟩ := by + have h := MachineInitialHeaders.headerTrace .«variables» .counter .scratch .reversed + (by decide) (by decide) (by decide) (by decide) (by decide) (by decide) + .scanN .restoreN .scanM1 .restoreM1 .closeFirst .scanM6 .restoreM6 .closeSecond + (some .initializeIndex) program rfl rfl rfl rfl rfl rfl rfl rfl + (counterTapes n m clauseBits) n m [] [] + (by simp [counterTapes]) (by simp [counterTapes]) rfl + (false, false, false) none + have frame : Function.update (counterTapes n m clauseBits) .reversed + ((encodeWords [n + m + 1, 6 * m + 1]).reverse ++ + counterTapes n m clauseBits .reversed) = headerTapes n m clauseBits := by + funext k + cases k <;> simp [counterTapes, headerTapes] + rw [frame] at h + exact h + +theorem initializeIndexTrace (n m : ℕ) (clauseBits : List Bool) : + (MachineComposition.advance (TM2.step program))^[1] + (some ⟨some .initializeIndex, initialState, headerTapes n m clauseBits⟩) = + some ⟨some .guard, initialState, startTapes n m clauseBits⟩ := by + simp only [Function.iterate_one, MachineComposition.advance_some] + change some (TM2.stepAux (program .initializeIndex) initialState + (headerTapes n m clauseBits)) = _ + simp only [program, TM2.stepAux] + congr 2 + funext k + cases k <;> simp [headerTapes, startTapes] + +theorem startTrace (n m : ℕ) (clauseBits : List Bool) : + (MachineComposition.advance (TM2.step program))^[3 * n + 5 * m + 13] + (some (initList machine (encodeWords [n, m] ++ clauseBits))) = + some ⟨some .guard, initialState, startTapes n m clauseBits⟩ := by + have total := trace_trans _ + (trace_trans _ (readCountersTrace n m clauseBits) (headersTrace n m clauseBits)) + (initializeIndexTrace n m clauseBits) + simpa only [show (n + m + 4) + (2 * n + 4 * m + 8) + 1 = + 3 * n + 5 * m + 13 by omega] using total + +theorem formulaStartTrace (F : Target.Formula) : + (MachineComposition.advance (TM2.step program))^[ + 3 * F.«variables» + 5 * F.clauses.length + 13] + (some (initList machine (formulaBits F))) = + some ⟨some .guard, initialState, + startTapes F.«variables» F.clauses.length + (encodeWords (F.clauses.flatMap clauseWords))⟩ := by + simpa only [formulaBits, formulaWords, encodeWords_append] using + startTrace F.«variables» F.clauses.length (encodeWords (F.clauses.flatMap clauseWords)) + +def startInTime (n m : ℕ) (clauseBits : List Bool) : + StateTransition.EvalsToInTime (TM2.step program) + (initList machine (encodeWords [n, m] ++ clauseBits)) + (some ⟨some .guard, initialState, startTapes n m clauseBits⟩) + (3 * n + 5 * m + 13) where + steps := 3 * n + 5 * m + 13 + evals_in_steps := startTrace n m clauseBits + steps_le_m := Nat.le_refl _ + +def formulaStartInTime (F : Target.Formula) : + StateTransition.EvalsToInTime (TM2.step program) (initList machine (formulaBits F)) + (some ⟨some .guard, initialState, + startTapes F.«variables» F.clauses.length + (encodeWords (F.clauses.flatMap clauseWords))⟩) + (3 * F.«variables» + 5 * F.clauses.length + 13) where + steps := 3 * F.«variables» + 5 * F.clauses.length + 13 + evals_in_steps := formulaStartTrace F + steps_le_m := Nat.le_refl _ + +end MinUncutGames.Foundations.PCP.RawInitialMachineStart + +end +section +namespace MinUncutGames.Foundations.PCP.RawInitialMachineLoopData + +open Target Complexity RawInitialMachineModel + +def clauseInput {n : Nat} (clauses : List (Clause n)) : List Bool := + encodeWords (clauses.flatMap Complexity.clauseWords) + +@[simp] theorem clauseInput_nil (n : Nat) : clauseInput ([] : List (Clause n)) = [] := rfl + +@[simp] theorem clauseInput_cons {n : Nat} (c : Clause n) (cs : List (Clause n)) : + clauseInput (c :: cs) = encodeWords (Complexity.clauseWords c) ++ clauseInput cs := by + simp only [clauseInput, List.flatMap_cons, encodeWords_append] + +def clauseOutput (n i : Nat) (clauses : List (Clause n)) : List Nat := + (clauses.mapIdx fun offset c => RawInitialRows.clauseWords n (i + offset) + (RawInitialRows.clauseNames c) (RawInitialRows.clauseSigns c)).flatten + +private theorem mapIdx_ofFn {α β : Type} (xs : List α) (f : Nat → α → β) : + xs.mapIdx f = List.ofFn (fun i : Fin xs.length => f i.val (xs.get i)) := by + induction xs generalizing f with + | nil => simp + | cons x xs ih => simp [ih] + +@[simp] theorem clauseOutput_nil (n i : Nat) : clauseOutput n i [] = [] := rfl + +@[simp] theorem clauseOutput_cons (n i : Nat) (c : Clause n) (cs : List (Clause n)) : + clauseOutput n i (c :: cs) = + RawInitialRows.clauseWords n i (RawInitialRows.clauseNames c) + (RawInitialRows.clauseSigns c) ++ clauseOutput n (i + 1) cs := by + simp only [clauseOutput, List.mapIdx_cons, Nat.add_zero, List.flatten_cons, + Nat.add_comm, Nat.add_left_comm] + +theorem clauseOutput_numbered (F : Formula) : + clauseOutput F.«variables» 0 F.clauses = + (List.finRange F.clauses.length).flatMap (fun i => + RawInitialRows.clauseWords F.«variables» i.val + (RawInitialRows.clauseNames (clauseAt F i)) + (RawInitialRows.clauseSigns (clauseAt F i))) := by + simp only [clauseOutput, mapIdx_ofFn, List.ofFn_eq_map, + Nat.zero_add, clauseAt] + rfl + +theorem tableWords_decomposition (F : Formula) : + GraphTables.tableWords (RawInitialTables.table F) = + [F.«variables» + F.clauses.length + 1, 6 * F.clauses.length + 1] ++ + clauseOutput F.«variables» 0 F.clauses ++ + RawInitialRows.dummyWords F.«variables» F.clauses.length := by + rw [RawInitialRows.tableWords_eq, clauseOutput_numbered] + +def loopTapes (n i remaining : Nat) (input reversed : List Bool) : Tape → List Bool + | .input => input + | .«variables» => encodeWord n + | .counter => encodeWord remaining + | .index => encodeWord i + | .reversed => reversed + | _ => [] + +theorem startTapes_eq (n m : Nat) (input : List Bool) : + RawInitialMachineStart.startTapes n m input = + loopTapes n 0 m input (encodeWords [n + m + 1, 6 * m + 1]).reverse := by + funext tape + cases tape <;> rfl + +theorem decrement_counter (n i remaining : Nat) (input reversed : List Bool) : + Function.update (loopTapes n i (remaining + 1) input reversed) + Tape.counter (encodeWord remaining) = loopTapes n i remaining input reversed := by + funext tape + cases tape <;> simp [loopTapes] + +theorem increment_index (n i remaining : Nat) (input reversed : List Bool) : + Function.update (loopTapes n i remaining input reversed) + Tape.index (true :: encodeWord i) = loopTapes n (i + 1) remaining input reversed := by + funext tape + cases tape <;> simp [loopTapes, encodeWord, List.replicate_succ] + +end MinUncutGames.Foundations.PCP.RawInitialMachineLoopData + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineLazyRows.lean b/lean/OAI/Computability/MinUncut/Machines/MachineLazyRows.lean new file mode 100644 index 0000000000000000000000000000000000000000..1fd7cd16c91287d315d53fc3779e4fe88490515b --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineLazyRows.lean @@ -0,0 +1,733 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineRegularLift +import OAI.Computability.MinUncut.Machines.MachinePortReindex +import OAI.Computability.MinUncut.PCP.PreprocessingLazyWords + +namespace OAI + +section +namespace MinUncutGames.Foundations.Complexity.MachineLazyRows + +open Turing MachineComposition PCP.GraphTables +open PCP.PreprocessingLazyWords (reverseMap moveRow moveRow_words) + +variable {K Λ A : Type} [DecidableEq K] + +abbrev Label (d : Nat) := MachinePortReindex.Label d ⊕ MachineTableRows.Label +abbrev State (A : Type) (d : Nat) := MachinePortReindex.State A d + +def addressIndex : Fin 5 → Fin 9 := ![1, 3, 4, 5, 6] + +theorem addressIndex_injective : Function.Injective addressIndex := by + intro i j h + fin_cases i <;> fin_cases j <;> simp_all [addressIndex] + +def fields (tape : Fin 9 → K) : Fin 3 → K := ![tape 0, tape 6, tape 2] + +def reindexInstruction (d : Nat) (positive : 0 < d) (c b : Nat) (tape : Fin 9 → K) + (labels : Label d → Λ) (exit : Option Λ) : + Label d → TM2.Stmt (fun _ : K => Bool) Λ (State A d) + | .inl stage => MachinePortReindex.instruction d positive c b + (tape ∘ addressIndex) (fun stage => labels (.inl stage)) + (some (labels (.inr .relationRead))) stage + | .inr stage => MachineTableRows.routine (fields tape) (tape 8) (tape 7) (tape 3) + (fun stage => labels (.inr stage)) exit stage + +def instruction (d : Nat) (positive : 0 < d) (tape : Fin 9 → K) + (labels : Label d → Λ) (exit : Option Λ) : + Label d → TM2.Stmt (fun _ : K => Bool) Λ (State A d) := + reindexInstruction d positive (2 * d) d tape labels exit + +def reindexRowBits (d c b v j : Nat) (relation : RelationTable) : List Bool := + encodeWord v ++ encodeWord (MachinePortReindex.value d c b j) ++ + encodeWords (relationWords relation) + +def reindexMappedTapes (d c b j : Nat) (tape : Fin 9 → K) + (base : K → List Bool) : K → List Bool := + Function.update base (tape 6) (encodeWord (MachinePortReindex.value d c b j)) + +def reindexResultTapes (d c b v j : Nat) (relation : RelationTable) + (tape : Fin 9 → K) (base : K → List Bool) : K → List Bool := + Function.update (reindexMappedTapes d c b j tape base) (tape 7) + (base (tape 7) ++ reindexRowBits d c b v j relation) + +def reindexSteps (d c b v j : Nat) (relation : RelationTable) (output : List Bool) : Nat := + MachinePortReindex.steps d j + 4 * (reindexRowBits d c b v j relation).length + + 2 * output.length + 9 + +def rowBits (d v j : Nat) (relation : RelationTable) : List Bool := + encodeWord v ++ encodeWord (reverseMap d j) ++ encodeWords (relationWords relation) + +def mappedTapes (d j : Nat) (tape : Fin 9 → K) (base : K → List Bool) : K → List Bool := + Function.update base (tape 6) (encodeWord (reverseMap d j)) + +def resultTapes (d v j : Nat) (relation : RelationTable) + (tape : Fin 9 → K) (base : K → List Bool) : K → List Bool := + Function.update (mappedTapes d j tape base) (tape 7) + (base (tape 7) ++ rowBits d v j relation) + +def steps (d v j : Nat) (relation : RelationTable) (output : List Bool) : Nat := + MachinePortReindex.steps d j + 4 * (rowBits d v j relation).length + 2 * output.length + 9 + +theorem reindexRowTrace (d : Nat) (positive : 0 < d) (c b : Nat) (tape : Fin 9 → K) + (distinct : Function.Injective tape) (labels : Label d → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State A d)) + (atLabels : ∀ l, program (labels l) = reindexInstruction d positive c b tape labels exit l) + (base : K → List Bool) (v j : Nat) (relation : RelationTable) + (tailWord : base (tape 0) = encodeWord v) + (reverseWord : base (tape 1) = encodeWord j) + (relationWord : base (tape 2) = encodeWords (relationWords relation)) + (scratchEmpty : base (tape 3) = []) (workEmpty : base (tape 4) = []) + (quotientEmpty : base (tape 5) = []) (newReverseEmpty : base (tape 6) = []) + (rowEmpty : base (tape 8) = []) (ambient : A) : + (advance (TM2.step program))^[reindexSteps d c b v j relation (base (tape 7))] + (some ⟨some (labels (.inl .copySeed)), MachinePortReindex.clean d positive ambient, base⟩) = + some ⟨exit, MachinePortReindex.clean d positive ambient, + reindexResultTapes d c b v j relation tape base⟩ := by + have hd (i k : Fin 9) (h : i ≠ k) : tape i ≠ tape k := fun e => h (distinct e) + have ha0 : addressIndex 0 = 1 := rfl + have ha4 : addressIndex 4 = 6 := rfl + have mapRun := MachinePortReindex.reindexTrace d positive c b + (tape ∘ addressIndex) (distinct.comp addressIndex_injective) + (fun stage => labels (.inl stage)) (some (labels (.inr .relationRead))) + program (fun stage => atLabels (.inl stage)) base j [] + (by simpa only [Function.comp_apply, ha0, List.append_nil] using reverseWord) + scratchEmpty workEmpty quotientEmpty ambient + simp only [Function.comp_apply, ha4, newReverseEmpty, + List.append_nil] at mapRun + change (advance (TM2.step program))^[MachinePortReindex.steps d j] + (some ⟨some (labels (.inl .copySeed)), MachinePortReindex.clean d positive ambient, base⟩) = + some ⟨some (labels (.inr .relationRead)), MachinePortReindex.clean d positive ambient, + reindexMappedTapes d c b j tape base⟩ at mapRun + have hfields (i : Fin 3) : fields tape i ≠ tape 8 ∧ fields tape i ≠ tape 3 := by + fin_cases i + · exact ⟨hd 0 8 (by decide), hd 0 3 (by decide)⟩ + · exact ⟨hd 6 8 (by decide), hd 6 3 (by decide)⟩ + · exact ⟨hd 2 8 (by decide), hd 2 3 (by decide)⟩ + have hbits : MachineTableRows.fieldBits (fields tape) (reindexMappedTapes d c b j tape base) = + reindexRowBits d c b v j relation := by + simp [MachineTableRows.fieldBits, fields, reindexMappedTapes, hd 0 6 (by decide), + hd 2 6 (by decide), tailWord, relationWord, reindexRowBits] + have hsize : MachineTableRows.fieldSize (fields tape) (reindexMappedTapes d c b j tape base) = + (reindexRowBits d c b v j relation).length := by + rw [← MachineTableRows.fieldBits_length, hbits] + have hout : reindexMappedTapes d c b j tape base (tape 7) = base (tape 7) := by + simp [reindexMappedTapes, hd 7 6 (by decide)] + have appendRun := MachineTableRows.appendTrace (fields tape) (tape 8) (tape 7) (tape 3) + hfields (hd 8 7 (by decide)) (hd 8 3 (by decide)) (hd 7 3 (by decide)) + (fun stage => labels (.inr stage)) exit program + (fun stage => atLabels (.inr stage)) (reindexMappedTapes d c b j tape base) + (by simp [reindexMappedTapes, hd 8 6 (by decide), rowEmpty]) + (by simp [reindexMappedTapes, hd 3 6 (by decide), scratchEmpty]) + (ambient, MachineFixedDivMod.residue d positive 0) none + rw [hsize, hout, hbits] at appendRun + change (advance (TM2.step program))^[4 * (reindexRowBits d c b v j relation).length + + 2 * (base (tape 7)).length + 9] + (some ⟨some (labels (.inr .relationRead)), MachinePortReindex.clean d positive ambient, + reindexMappedTapes d c b j tape base⟩) = + some ⟨exit, MachinePortReindex.clean d positive ambient, + reindexResultTapes d c b v j relation tape base⟩ at appendRun + rw [show reindexSteps d c b v j relation (base (tape 7)) = + (4 * (reindexRowBits d c b v j relation).length + 2 * (base (tape 7)).length + 9) + + MachinePortReindex.steps d j by unfold reindexSteps; omega, + Function.iterate_add_apply, mapRun, appendRun] + +theorem rowTrace (d : Nat) (positive : 0 < d) (tape : Fin 9 → K) + (distinct : Function.Injective tape) (labels : Label d → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State A d)) + (atLabels : ∀ l, program (labels l) = instruction d positive tape labels exit l) + (base : K → List Bool) (v j : Nat) (relation : RelationTable) + (tailWord : base (tape 0) = encodeWord v) + (reverseWord : base (tape 1) = encodeWord j) + (relationWord : base (tape 2) = encodeWords (relationWords relation)) + (scratchEmpty : base (tape 3) = []) (workEmpty : base (tape 4) = []) + (quotientEmpty : base (tape 5) = []) (newReverseEmpty : base (tape 6) = []) + (rowEmpty : base (tape 8) = []) (ambient : A) : + (advance (TM2.step program))^[steps d v j relation (base (tape 7))] + (some ⟨some (labels (.inl .copySeed)), MachinePortReindex.clean d positive ambient, base⟩) = + some ⟨exit, MachinePortReindex.clean d positive ambient, + resultTapes d v j relation tape base⟩ := by + simpa only [reindexSteps, reindexResultTapes, reindexMappedTapes, reindexRowBits, + MachinePortReindex.lazy_value, reverseMap, steps, resultTapes, mappedTapes, rowBits] using + reindexRowTrace d positive (2 * d) d tape distinct labels exit program atLabels + base v j relation tailWord reverseWord relationWord scratchEmpty workEmpty + quotientEmpty newReverseEmpty rowEmpty ambient + +theorem rowBits_eq_moveRow {n d : Nat} (table : PCP.PortTables.Table n d) + (v : Fin n) (p : Fin d) : + rowBits d v.val (PCP.PreprocessingLazyWords.row table v p).reverseIndex.val + (PCP.PreprocessingLazyWords.row table v p).relation = + encodeWords (rowWords (moveRow table v p)) := by + rw [moveRow_words] + simp [rowBits, encodeWords] + +def machine (d : Nat) (positive : 0 < d) : FinTM2 where + K := Fin 9 + k₀ := 1 + k₁ := 7 + Γ _ := Bool + Λ := Label d + main := .inl .copySeed + σ := State Unit d + initialState := MachinePortReindex.clean d positive () + m := instruction d positive id id none + +abbrev Buffer := MachineRegularOriginalRow.Buffer +abbrev StreamState (A : Type) (d : Nat) := State (A × Buffer) d + +def streamClean (d : Nat) (positive : 0 < d) (ambient : A) : StreamState A d := + MachinePortReindex.clean d positive (ambient, MachineRegularOriginalRow.zeroBuffer) + +def relationStateEquiv (A : Type) (d : Nat) : + MachineRegularOriginalRow.State (A × Fin d) ≃ StreamState A d where + toFun s := (((s.1.1.1, s.1.2), s.1.1.2), s.2) + invFun s := (((s.1.1.1, s.1.2), s.1.1.2), s.2) + left_inv _ := rfl + right_inv _ := rfl + +def streamRelationCopy (d : Nat) (source destination : K) (exit : Option Λ) : + TM2.Stmt (fun _ : K => Bool) Λ (StreamState A d) := + MachineStateEquiv.statement (relationStateEquiv A d) + (MachineRegularOriginalRow.relationCopyAt source destination exit) + +theorem streamRelationCopy_step (d : Nat) (positive : 0 < d) + (source destination : K) (different : source ≠ destination) + (label : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (StreamState A d)) + (code : program label = streamRelationCopy d source destination exit) + (relation : RelationTable) (suffix : List Bool) (base : K → List Bool) + (input : base source = encodeWords (relationWords relation) ++ suffix) (ambient : A) : + TM2.step program ⟨some label, streamClean d positive ambient, base⟩ = + some ⟨exit, streamClean d positive ambient, + Function.update (Function.update base source suffix) destination + (encodeWords (relationWords relation) ++ base destination)⟩ := by + have hraw := MachineRegularOriginalRow.relationCopy_step source destination different label exit + (fun _ => MachineRegularOriginalRow.relationCopyAt source destination exit) rfl + relation suffix base input (ambient, MachineFixedDivMod.residue d positive 0) + MachineRegularOriginalRow.zeroBuffer none + have haux := Option.some.inj hraw + change some (TM2.stepAux (program label) (streamClean d positive ambient) base) = _ + rw [code, streamRelationCopy, MachineStateEquiv.stepAux_transport_symm] + change some (MachineStateEquiv.configuration (relationStateEquiv A d) + (TM2.stepAux (MachineRegularOriginalRow.relationCopyAt source destination exit) + (((ambient, MachineFixedDivMod.residue d positive 0), + MachineRegularOriginalRow.zeroBuffer), none) base)) = _ + rw [haux] + rfl + +def bodyIndex (i : Fin 9) : Fin 10 := i.castSucc + +theorem bodyIndex_injective : Function.Injective bodyIndex := by + intro i j h + apply Fin.ext + exact congrArg (fun k : Fin 10 => k.val) h + +inductive StreamLabel (d : Nat) + | tailStart | tailRead | reverseStart | reverseRead | copyRelation + | row (stage : Label d) + | clearTail | clearOld | clearRelation | clearNew + deriving DecidableEq, Fintype + +def streamInstruction (d : Nat) (positive : 0 < d) (c b : Nat) (tape : Fin 10 → K) + (labels : StreamLabel d → Λ) (exit : Option Λ) : + StreamLabel d → TM2.Stmt (fun _ : K => Bool) Λ (StreamState A d) + | .tailStart => Hastad.SourceMachine.fieldStart (tape 0) (labels .tailRead) + | .tailRead => Hastad.SourceMachine.fieldLoop (tape 9) (tape 0) (labels .tailRead) + (some (labels .reverseStart)) + | .reverseStart => Hastad.SourceMachine.fieldStart (tape 1) (labels .reverseRead) + | .reverseRead => Hastad.SourceMachine.fieldLoop (tape 9) (tape 1) (labels .reverseRead) + (some (labels .copyRelation)) + | .copyRelation => streamRelationCopy d (tape 9) (tape 2) + (some (labels (.row (.inl .copySeed)))) + | .row stage => reindexInstruction d positive c b (tape ∘ bodyIndex) + (fun stage => labels (.row stage)) (some (labels .clearTail)) stage + | .clearTail => MachineDrain.drain (tape 0) (labels .clearTail) (some (labels .clearOld)) + | .clearOld => MachineDrain.drain (tape 1) (labels .clearOld) (some (labels .clearRelation)) + | .clearRelation => MachineDrain.drain (tape 2) (labels .clearRelation) (some (labels .clearNew)) + | .clearNew => MachineDrain.drain (tape 6) (labels .clearNew) exit + +def inputRowBits (v j : Nat) (relation : RelationTable) : List Bool := + encodeWord v ++ encodeWord j ++ encodeWords (relationWords relation) + +def streamRowSteps (d c b v j : Nat) (relation : RelationTable) (output : List Bool) : Nat := + (v + 2) + (j + 2) + 1 + reindexSteps d c b v j relation output + + (v + 2) + (j + 2) + ((encodeWords (relationWords relation)).length + 1) + + (MachinePortReindex.value d c b j + 2) + +def streamResultTapes (d c b v j : Nat) (relation : RelationTable) + (tape : Fin 10 → K) (base : K → List Bool) (suffix : List Bool) : K → List Bool := + Function.update (Function.update base (tape 9) suffix) (tape 7) + (base (tape 7) ++ reindexRowBits d c b v j relation) + +theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +theorem streamRowTrace (d : Nat) (positive : 0 < d) (c b : Nat) (tape : Fin 10 → K) + (distinct : Function.Injective tape) (labels : StreamLabel d → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (StreamState A d)) + (atLabels : ∀ l, program (labels l) = streamInstruction d positive c b tape labels exit l) + (base : K → List Bool) (v j : Nat) (relation : RelationTable) (suffix : List Bool) + (input : base (tape 9) = inputRowBits v j relation ++ suffix) + (empty : ∀ i : Fin 10, i ≠ 7 → i ≠ 9 → base (tape i) = []) (ambient : A) : + (advance (TM2.step program))^[streamRowSteps d c b v j relation (base (tape 7))] + (some ⟨some (labels .tailStart), streamClean d positive ambient, base⟩) = + some ⟨exit, streamClean d positive ambient, + streamResultTapes d c b v j relation tape base suffix⟩ := by + have hd (i k : Fin 10) (h : i ≠ k) : tape i ≠ tape k := fun x => h (distinct x) + have hb6 : bodyIndex 6 = 6 := rfl + have hb7 : bodyIndex 7 = 7 := rfl + have h₀ := empty 0 (by decide) (by decide) + have h₁ := empty 1 (by decide) (by decide) + have h₂ := empty 2 (by decide) (by decide) + have h₃ := empty 3 (by decide) (by decide) + have h₄ := empty 4 (by decide) (by decide) + have h₅ := empty 5 (by decide) (by decide) + have h₆ := empty 6 (by decide) (by decide) + have h₈ := empty 8 (by decide) (by decide) + let relationBits := encodeWords (relationWords relation) + let tailLoaded := Function.update (Function.update base (tape 9) + (encodeWord j ++ (relationBits ++ suffix))) (tape 0) (encodeWord v) + let reverseLoaded := Function.update (Function.update tailLoaded (tape 9) + (relationBits ++ suffix)) (tape 1) (encodeWord j) + let loaded := Function.update (Function.update reverseLoaded (tape 9) suffix) (tape 2) relationBits + let rowed := reindexResultTapes d c b v j relation (tape ∘ bodyIndex) loaded + let tailCleared := Function.update rowed (tape 0) [] + let oldCleared := Function.update tailCleared (tape 1) [] + let relationCleared := Function.update oldCleared (tape 2) [] + have tailRun : (advance (TM2.step program))^[v + 2] + (some ⟨some (labels .tailStart), streamClean d positive ambient, base⟩) = + some ⟨some (labels .reverseStart), streamClean d positive ambient, tailLoaded⟩ := by + have h := (Hastad.SourceMachine.fieldInTime (tape 9) (tape 0) (hd 9 0 (by decide)) + (labels .tailStart) (labels .tailRead) (some (labels .reverseStart)) program + (atLabels .tailStart) (atLabels .tailRead) base v + (encodeWord j ++ (relationBits ++ suffix)) + (by simpa only [inputRowBits, List.append_assoc] using input) + ((ambient, MachineRegularOriginalRow.zeroBuffer), + MachineFixedDivMod.residue d positive 0) none).evals_in_steps + simp only [Hastad.SourceMachine.fieldInTime, Hastad.SourceMachine.fieldTapes, + h₀, List.append_nil] at h + convert h using 1 <;> rfl + have reverseRun : (advance (TM2.step program))^[j + 2] + (some ⟨some (labels .reverseStart), streamClean d positive ambient, tailLoaded⟩) = + some ⟨some (labels .copyRelation), streamClean d positive ambient, reverseLoaded⟩ := by + have hstart : tailLoaded (tape 1) = [] := by + simp [tailLoaded, hd 1 0 (by decide), hd 1 9 (by decide), h₁] + have h := (Hastad.SourceMachine.fieldInTime (tape 9) (tape 1) (hd 9 1 (by decide)) + (labels .reverseStart) (labels .reverseRead) (some (labels .copyRelation)) program + (atLabels .reverseStart) (atLabels .reverseRead) tailLoaded j (relationBits ++ suffix) + (by simp [tailLoaded, hd 9 0 (by decide)]) + ((ambient, MachineRegularOriginalRow.zeroBuffer), + MachineFixedDivMod.residue d positive 0) none).evals_in_steps + simp only [Hastad.SourceMachine.fieldInTime, Hastad.SourceMachine.fieldTapes, + hstart, List.append_nil] at h + convert h using 1 <;> rfl + have copyRun : (advance (TM2.step program))^[1] + (some ⟨some (labels .copyRelation), streamClean d positive ambient, reverseLoaded⟩) = + some ⟨some (labels (.row (.inl .copySeed))), streamClean d positive ambient, loaded⟩ := by + have hempty : reverseLoaded (tape 2) = [] := by + simp [reverseLoaded, tailLoaded, hd 2 1 (by decide), hd 2 9 (by decide), + hd 2 0 (by decide), h₂] + have h := streamRelationCopy_step d positive (tape 9) (tape 2) (hd 9 2 (by decide)) + (labels .copyRelation) (some (labels (.row (.inl .copySeed)))) program + (atLabels .copyRelation) relation suffix reverseLoaded + (by simp [reverseLoaded, relationBits, hd 9 1 (by decide)]) ambient + simpa only [Function.iterate_one, advance_some, hempty, List.append_nil, loaded] using h + have hs (i : Fin 10) (hi : i ≠ 0) (hi' : i ≠ 1) (hi'' : i ≠ 2) (hi''' : i ≠ 9) : + loaded (tape i) = base (tape i) := by + simp [loaded, reverseLoaded, tailLoaded, hd i 0 hi, hd i 1 hi', + hd i 2 hi'', hd i 9 hi'''] + have loadedTail : loaded (tape 0) = encodeWord v := by + simp [loaded, reverseLoaded, tailLoaded, hd 0 2 (by decide), hd 0 9 (by decide), + hd 0 1 (by decide)] + have loadedReverse : loaded (tape 1) = encodeWord j := by + simp [loaded, reverseLoaded, hd 1 2 (by decide), hd 1 9 (by decide)] + have loadedRelation : loaded (tape 2) = relationBits := by simp [loaded] + have bodyRun := reindexRowTrace d positive c b (tape ∘ bodyIndex) + (distinct.comp bodyIndex_injective) (fun stage => labels (.row stage)) + (some (labels .clearTail)) program (fun stage => atLabels (.row stage)) loaded v j relation + loadedTail loadedReverse loadedRelation + ((hs 3 (by decide) (by decide) (by decide) (by decide)).trans h₃) + ((hs 4 (by decide) (by decide) (by decide) (by decide)).trans h₄) + ((hs 5 (by decide) (by decide) (by decide) (by decide)).trans h₅) + ((hs 6 (by decide) (by decide) (by decide) (by decide)).trans h₆) + ((hs 8 (by decide) (by decide) (by decide) (by decide)).trans h₈) + (ambient, MachineRegularOriginalRow.zeroBuffer) + have hout : loaded ((tape ∘ bodyIndex) 7) = base (tape 7) := + hs 7 (by decide) (by decide) (by decide) (by decide) + rw [hout] at bodyRun + change (advance (TM2.step program))^[reindexSteps d c b v j relation (base (tape 7))] + (some ⟨some (labels (.row (.inl .copySeed))), streamClean d positive ambient, loaded⟩) = + some ⟨some (labels .clearTail), streamClean d positive ambient, rowed⟩ at bodyRun + have rowedTail : rowed (tape 0) = encodeWord v := by + simp only [rowed, reindexResultTapes, reindexMappedTapes, Function.comp_apply, hb6, hb7] + simpa only [Function.update_of_ne (hd 0 7 (by decide)), + Function.update_of_ne (hd 0 6 (by decide))] using loadedTail + have rowedOld : tailCleared (tape 1) = encodeWord j := by + simp only [tailCleared, rowed, reindexResultTapes, reindexMappedTapes, + Function.comp_apply, hb6, hb7] + simpa only [Function.update_of_ne (hd 1 0 (by decide)), + Function.update_of_ne (hd 1 7 (by decide)), Function.update_of_ne (hd 1 6 (by decide))] + using loadedReverse + have rowedRelation : oldCleared (tape 2) = relationBits := by + simp only [oldCleared, tailCleared, rowed, reindexResultTapes, reindexMappedTapes, + Function.comp_apply, hb6, hb7] + simpa only [Function.update_of_ne (hd 2 1 (by decide)), + Function.update_of_ne (hd 2 0 (by decide)), Function.update_of_ne (hd 2 7 (by decide)), + Function.update_of_ne (hd 2 6 (by decide))] using loadedRelation + have rowedNew : relationCleared (tape 6) = encodeWord (MachinePortReindex.value d c b j) := by + simp [relationCleared, oldCleared, tailCleared, rowed, reindexResultTapes, + reindexMappedTapes, Function.comp_apply, bodyIndex, hd 6 2 (by decide), + hd 6 1 (by decide), hd 6 0 (by decide), hd 6 7 (by decide)] + have clearTail := (MachineDrain.drainInTime (tape 0) (labels .clearTail) + (some (labels .clearOld)) program (atLabels .clearTail) rowed + ((ambient, MachineRegularOriginalRow.zeroBuffer), + MachineFixedDivMod.residue d positive 0) none).evals_in_steps + change (advance (TM2.step program))^[(rowed (tape 0)).length + 1] + (some ⟨some (labels .clearTail), streamClean d positive ambient, rowed⟩) = + some ⟨some (labels .clearOld), streamClean d positive ambient, tailCleared⟩ at clearTail + rw [rowedTail, encodeWord_length] at clearTail + have clearOld := (MachineDrain.drainInTime (tape 1) (labels .clearOld) + (some (labels .clearRelation)) program (atLabels .clearOld) tailCleared + ((ambient, MachineRegularOriginalRow.zeroBuffer), + MachineFixedDivMod.residue d positive 0) none).evals_in_steps + change (advance (TM2.step program))^[(tailCleared (tape 1)).length + 1] + (some ⟨some (labels .clearOld), streamClean d positive ambient, tailCleared⟩) = + some ⟨some (labels .clearRelation), streamClean d positive ambient, oldCleared⟩ at clearOld + rw [rowedOld, encodeWord_length] at clearOld + have clearRelation := (MachineDrain.drainInTime (tape 2) (labels .clearRelation) + (some (labels .clearNew)) program (atLabels .clearRelation) oldCleared + ((ambient, MachineRegularOriginalRow.zeroBuffer), + MachineFixedDivMod.residue d positive 0) none).evals_in_steps + change (advance (TM2.step program))^[(oldCleared (tape 2)).length + 1] + (some ⟨some (labels .clearRelation), streamClean d positive ambient, oldCleared⟩) = + some ⟨some (labels .clearNew), streamClean d positive ambient, relationCleared⟩ at clearRelation + rw [rowedRelation] at clearRelation + have clearNew := (MachineDrain.drainInTime (tape 6) (labels .clearNew) + exit program (atLabels .clearNew) relationCleared + ((ambient, MachineRegularOriginalRow.zeroBuffer), + MachineFixedDivMod.residue d positive 0) none).evals_in_steps + change (advance (TM2.step program))^[(relationCleared (tape 6)).length + 1] + (some ⟨some (labels .clearNew), streamClean d positive ambient, relationCleared⟩) = + some ⟨exit, streamClean d positive ambient, + Function.update relationCleared (tape 6) []⟩ at clearNew + rw [rowedNew, encodeWord_length] at clearNew + have finalFrame : Function.update relationCleared (tape 6) [] = + streamResultTapes d c b v j relation tape base suffix := by + funext k + by_cases h6 : k = tape 6 + · subst k + simp [streamResultTapes, hd 6 7 (by decide), hd 6 9 (by decide), h₆] + · by_cases h2 : k = tape 2 + · subst k + simp [relationCleared, streamResultTapes, hd 2 6 (by decide), + hd 2 7 (by decide), hd 2 9 (by decide), h₂] + · by_cases h1 : k = tape 1 + · subst k + simp [relationCleared, oldCleared, streamResultTapes, + hd 1 6 (by decide), hd 1 2 (by decide), hd 1 7 (by decide), + hd 1 9 (by decide), h₁] + · by_cases h0 : k = tape 0 + · subst k + simp [relationCleared, oldCleared, tailCleared, streamResultTapes, + hd 0 6 (by decide), hd 0 2 (by decide), hd 0 1 (by decide), + hd 0 7 (by decide), hd 0 9 (by decide), h₀] + · by_cases h7 : k = tape 7 + · subst k + simp [relationCleared, oldCleared, tailCleared, rowed, reindexResultTapes, + reindexMappedTapes, Function.comp_apply, bodyIndex, streamResultTapes, + loaded, reverseLoaded, tailLoaded, hd 7 6 (by decide), hd 7 2 (by decide), + hd 7 1 (by decide), hd 7 0 (by decide), hd 7 9 (by decide)] + · by_cases h9 : k = tape 9 + · subst k + simp [relationCleared, oldCleared, tailCleared, rowed, reindexResultTapes, + reindexMappedTapes, Function.comp_apply, bodyIndex, loaded, reverseLoaded, + tailLoaded, streamResultTapes, hd 9 6 (by decide), hd 9 2 (by decide), + hd 9 1 (by decide), hd 9 0 (by decide), hd 9 7 (by decide)] + · simp [relationCleared, oldCleared, tailCleared, rowed, reindexResultTapes, + reindexMappedTapes, Function.comp_apply, bodyIndex, loaded, reverseLoaded, + tailLoaded, streamResultTapes, h6, h2, h1, h0, h7, h9] + rw [finalFrame] at clearNew + exact joinTrace (joinTrace (joinTrace (joinTrace (joinTrace (joinTrace + (joinTrace tailRun reverseRun) copyRun) bodyRun) clearTail) clearOld) clearRelation) clearNew + +abbrev VertexLabel (d : Nat) := Fin (d + 1) × Option (StreamLabel d) + +def vertexInstruction (d : Nat) (positive : 0 < d) (c b : Nat) (tape : Fin 10 → K) + (labels : VertexLabel d → Λ) (exit : Option Λ) : + VertexLabel d → TM2.Stmt (fun _ : K => Bool) Λ (StreamState A d) + | (i, none) => if i.val < d then .goto fun _ => labels (i, some .tailStart) + else MachinePortReindex.exitAt exit + | (i, some stage) => if h : i.val < d then + streamInstruction d positive c b tape (fun stage => labels (i, some stage)) + (some (labels (⟨i.val + 1, by omega⟩, none))) stage + else MachinePortReindex.exitAt exit + +def recordsInput {n m : Nat} (rows : List (DartRow n m)) : List Bool := + rows.flatMap (fun r => inputRowBits r.tail.val r.reverseIndex.val r.relation) + +def recordsOutput {n m : Nat} (d c b : Nat) (rows : List (DartRow n m)) : List Bool := + rows.flatMap (fun r => reindexRowBits d c b r.tail.val r.reverseIndex.val r.relation) + +def streamFrame {n m : Nat} (tape : Fin 10 → K) (base : K → List Bool) + (rows : List (DartRow n m)) (output : List Bool) : K → List Bool := + Function.update (Function.update base (tape 9) (recordsInput rows ++ base (tape 9))) + (tape 7) output + +def vertexSteps {n m : Nat} (d c b : Nat) : List (DartRow n m) → List Bool → Nat + | [], _ => 1 + | r :: rows, output => 1 + streamRowSteps d c b r.tail.val r.reverseIndex.val r.relation output + + vertexSteps d c b rows + (output ++ reindexRowBits d c b r.tail.val r.reverseIndex.val r.relation) + +theorem recordsInput_eq_codec {n m : Nat} (rows : List (DartRow n m)) : + recordsInput rows = encodeWords (rows.flatMap rowWords) := by + induction rows with + | nil => rfl + | cons r rows ih => + simp only [recordsInput, List.flatMap_cons, encodeWords_append, + MachineTableRows.rowBits_eq, inputRowBits] at ih ⊢ + rw [ih] + +theorem streamFrame_afterRow {n m : Nat} (d c b : Nat) (r : DartRow n m) + (tape : Fin 10 → K) (distinct : Function.Injective tape) (base : K → List Bool) + (rows : List (DartRow n m)) (output : List Bool) : + streamResultTapes d c b r.tail.val r.reverseIndex.val r.relation tape + (streamFrame tape base (r :: rows) output) (recordsInput rows ++ base (tape 9)) = + streamFrame tape base rows + (output ++ reindexRowBits d c b r.tail.val r.reverseIndex.val r.relation) := by + have h79 : tape 7 ≠ tape 9 := fun h => (by decide : (7 : Fin 10) ≠ 9) (distinct h) + funext k + by_cases h7 : k = tape 7 + · subst k + simp [streamResultTapes, streamFrame] + · by_cases h9 : k = tape 9 + · subst k + simp [streamResultTapes, streamFrame, Ne.symm h79] + · simp [streamResultTapes, streamFrame, h7, h9] + +theorem vertexSuffixTrace {n m : Nat} (d : Nat) (positive : 0 < d) (c b : Nat) + (tape : Fin 10 → K) (distinct : Function.Injective tape) + (labels : VertexLabel d → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (StreamState A d)) + (atLabels : ∀ l, program (labels l) = vertexInstruction d positive c b tape labels exit l) + (base : K → List Bool) (rows : Fin d → DartRow n m) + (empty : ∀ i : Fin 10, i ≠ 7 → i ≠ 9 → base (tape i) = []) (ambient : A) + (remaining : Nat) (i : Fin (d + 1)) (count : i.val + remaining = d) (output : List Bool) : + (advance (TM2.step program))^[vertexSteps d c b ((List.ofFn rows).drop i.val) output] + (some ⟨some (labels (i, none)), streamClean d positive ambient, + streamFrame tape base ((List.ofFn rows).drop i.val) output⟩) = + some ⟨exit, streamClean d positive ambient, + streamFrame (n := n) (m := m) tape base [] + (output ++ recordsOutput d c b ((List.ofFn rows).drop i.val))⟩ := by + have hd (a k : Fin 10) (h : a ≠ k) : tape a ≠ tape k := fun x => h (distinct x) + induction remaining generalizing i output with + | zero => + have hi : i.val = d := by omega + have hdrop : (List.ofFn rows).drop i.val = [] := by + apply List.drop_eq_nil_of_le + simp only [List.length_ofFn, hi, le_refl] + rw [hdrop] + simp only [vertexSteps, recordsOutput, List.flatMap_nil, List.append_nil] + change some (TM2.stepAux (program (labels (i, none))) _ _) = _ + rw [atLabels] + cases exit <;> simp [vertexInstruction, hi, MachinePortReindex.exitAt, TM2.stepAux] + | succ remaining ih => + have hi : i.val < d := by omega + let port : Fin d := ⟨i.val, hi⟩ + let next : Fin (d + 1) := ⟨i.val + 1, by omega⟩ + let rest := (List.ofFn rows).drop (i.val + 1) + have split : (List.ofFn rows).drop i.val = rows port :: rest := by + have h := List.getElem_cons_drop (as := List.ofFn rows) + (i := i.val) (by simpa only [List.length_ofFn] using hi) + simpa only [List.getElem_ofFn, port, rest] using h.symm + let initial := streamFrame tape base (rows port :: rest) output + have boundary : (advance (TM2.step program))^[1] + (some ⟨some (labels (i, none)), streamClean d positive ambient, initial⟩) = + some ⟨some (labels (i, some .tailStart)), streamClean d positive ambient, initial⟩ := by + change some (TM2.stepAux (program (labels (i, none))) _ _) = _ + rw [atLabels] + simp [vertexInstruction, hi, TM2.stepAux] + have body := streamRowTrace d positive c b tape distinct + (fun stage => labels (i, some stage)) (some (labels (next, none))) program + (by + intro stage + simpa only [vertexInstruction, hi, dite_true, next] using (atLabels (i, some stage))) + initial (rows port).tail.val (rows port).reverseIndex.val (rows port).relation + (recordsInput rest ++ base (tape 9)) + (by simp [initial, streamFrame, hd 9 7 (by decide), recordsInput, List.append_assoc]) + (by + intro k hk7 hk9 + simp [initial, streamFrame, hd k 7 hk7, hd k 9 hk9, empty k hk7 hk9]) ambient + have initialOutput : initial (tape 7) = output := by simp [initial, streamFrame] + rw [initialOutput] at body + change (advance (TM2.step program))^[streamRowSteps d c b + (rows port).tail.val (rows port).reverseIndex.val (rows port).relation output] + (some ⟨some (labels (i, some .tailStart)), streamClean d positive ambient, initial⟩) = + some ⟨some (labels (next, none)), streamClean d positive ambient, + streamResultTapes d c b (rows port).tail.val (rows port).reverseIndex.val + (rows port).relation tape initial (recordsInput rest ++ base (tape 9))⟩ at body + rw [show streamResultTapes d c b (rows port).tail.val (rows port).reverseIndex.val + (rows port).relation tape initial (recordsInput rest ++ base (tape 9)) = + streamFrame tape base rest + (output ++ reindexRowBits d c b (rows port).tail.val + (rows port).reverseIndex.val (rows port).relation) from + streamFrame_afterRow d c b (rows port) tape distinct base rest output] at body + have nextCount : next.val + remaining = d := by dsimp [next]; omega + have tail := ih next nextCount + (output ++ reindexRowBits d c b (rows port).tail.val + (rows port).reverseIndex.val (rows port).relation) + change (advance (TM2.step program))^[vertexSteps d c b rest + (output ++ reindexRowBits d c b (rows port).tail.val + (rows port).reverseIndex.val (rows port).relation)] + (some ⟨some (labels (next, none)), streamClean d positive ambient, + streamFrame tape base rest (output ++ reindexRowBits d c b (rows port).tail.val + (rows port).reverseIndex.val (rows port).relation)⟩) = + some ⟨exit, streamClean d positive ambient, + streamFrame (n := n) (m := m) tape base [] ((output ++ reindexRowBits d c b (rows port).tail.val + (rows port).reverseIndex.val (rows port).relation) ++ recordsOutput d c b rest)⟩ at tail + rw [split] + have all := joinTrace (joinTrace boundary body) tail + simpa only [vertexSteps, initial, recordsOutput, List.flatMap_cons, List.append_assoc] using all + +theorem vertexTrace {n m : Nat} (d : Nat) (positive : 0 < d) (c b : Nat) + (tape : Fin 10 → K) (distinct : Function.Injective tape) + (labels : VertexLabel d → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (StreamState A d)) + (atLabels : ∀ l, program (labels l) = vertexInstruction d positive c b tape labels exit l) + (base : K → List Bool) (rows : Fin d → DartRow n m) + (empty : ∀ i : Fin 10, i ≠ 7 → i ≠ 9 → base (tape i) = []) + (ambient : A) (output : List Bool) : + (advance (TM2.step program))^[vertexSteps d c b (List.ofFn rows) output] + (some ⟨some (labels (0, none)), streamClean d positive ambient, + streamFrame tape base (List.ofFn rows) output⟩) = + some ⟨exit, streamClean d positive ambient, + streamFrame (n := n) (m := m) tape base [] (output ++ recordsOutput d c b (List.ofFn rows))⟩ := by + simpa only [Fin.val_zero, List.drop_zero] using vertexSuffixTrace d positive c b tape distinct + labels exit program atLabels base rows empty ambient d 0 (by simp) output + +theorem encodeWords_flatMap {α : Type*} (items : List α) (words : α → List Nat) : + encodeWords (items.flatMap words) = items.flatMap (fun x => encodeWords (words x)) := by + induction items with + | nil => rfl + | cons item items ih => simp only [List.flatMap_cons, encodeWords_append, ih] + +theorem recordsOutput_lazy {n d : Nat} (table : PCP.PortTables.Table n d) (v : Fin n) : + recordsOutput d (2 * d) d (List.ofFn (PCP.PreprocessingLazyWords.row table v)) = + encodeWords ((List.ofFn (moveRow table v)).flatMap rowWords) := by + rw [encodeWords_flatMap] + simp only [recordsOutput, List.flatMap_def, List.map_ofFn] + apply congrArg List.flatten + apply congrArg List.ofFn + funext p + change reindexRowBits d (2 * d) d v.val + (PCP.PreprocessingLazyWords.row table v p).reverseIndex.val + (PCP.PreprocessingLazyWords.row table v p).relation = + encodeWords (rowWords (moveRow table v p)) + have h := rowBits_eq_moveRow table v p + simpa only [rowBits, reindexRowBits, MachinePortReindex.lazy_value, reverseMap] using h + +def valueBound (c b m : Nat) : Nat := c * m + m + b +def rowSizeBound (c b n m : Nat) : Nat := n + valueBound c b m + 8194 +def rowCostBound (c b n m : Nat) : Nat := + 2 * n + 8 * m + valueBound c b m + 4 * rowSizeBound c b n m + 8224 + +theorem reindexValue_le {n m : Nat} (d c b : Nat) (r : DartRow n m) : + MachinePortReindex.value d c b r.reverseIndex.val ≤ valueBound c b m := by + have hj := r.reverseIndex.isLt.le + have hdiv := (Nat.div_le_self r.reverseIndex.val d).trans hj + have hmod := (Nat.mod_le r.reverseIndex.val d).trans hj + have hmul := Nat.mul_le_mul_left c hdiv + unfold MachinePortReindex.value valueBound + omega + +theorem reindexRowBits_length_le {n m : Nat} (d c b : Nat) (r : DartRow n m) : + (reindexRowBits d c b r.tail.val r.reverseIndex.val r.relation).length ≤ + rowSizeBound c b n m := by + have htail := r.tail.isLt.le + have hvalue := reindexValue_le d c b r + have hrelation := relationBits_length_le r.relation + simp only [reindexRowBits, List.length_append, encodeWord_length] + unfold rowSizeBound + omega + +theorem streamRowSteps_le {n m : Nat} (d c b : Nat) (r : DartRow n m) (output : List Bool) : + streamRowSteps d c b r.tail.val r.reverseIndex.val r.relation output ≤ + rowCostBound c b n m + 2 * output.length := by + have htail := r.tail.isLt.le + have hj := r.reverseIndex.isLt.le + have hdiv := (Nat.div_le_self r.reverseIndex.val d).trans hj + have hvalue := reindexValue_le d c b r + have hrelation := relationBits_length_le r.relation + have hsize := reindexRowBits_length_le d c b r + unfold streamRowSteps reindexSteps MachinePortReindex.steps rowCostBound + omega + +theorem vertexSteps_le_capacity {n m : Nat} (d c b capacity : Nat) + (rows : List (DartRow n m)) (output : List Bool) + (room : output.length + rows.length * rowSizeBound c b n m ≤ capacity) : + vertexSteps d c b rows output ≤ + rows.length * (rowCostBound c b n m + 2 * capacity + 1) + 1 := by + induction rows generalizing output with + | nil => simp [vertexSteps] + | cons r rows ih => + have hsize := reindexRowBits_length_le d c b r + have hcost := streamRowSteps_le d c b r output + have hout : output.length ≤ capacity := by omega + have hroom : (output ++ reindexRowBits d c b r.tail.val r.reverseIndex.val r.relation).length + + rows.length * rowSizeBound c b n m ≤ capacity := by + rw [List.length_append] + simp only [List.length_cons, Nat.succ_mul] at room + omega + have htail := ih + (output ++ reindexRowBits d c b r.tail.val r.reverseIndex.val r.relation) hroom + change 1 + streamRowSteps d c b r.tail.val r.reverseIndex.val r.relation output + + vertexSteps d c b rows + (output ++ reindexRowBits d c b r.tail.val r.reverseIndex.val r.relation) ≤ + (rows.length + 1) * (rowCostBound c b n m + 2 * capacity + 1) + 1 + rw [Nat.add_mul, Nat.one_mul] + omega + +theorem vertexSteps_le {n m : Nat} (d c b : Nat) (rows : List (DartRow n m)) + (output : List Bool) : + vertexSteps d c b rows output ≤ rows.length * (rowCostBound c b n m + + 2 * (output.length + rows.length * rowSizeBound c b n m) + 1) + 1 := + vertexSteps_le_capacity d c b _ rows output (Nat.le_refl _) + +def vertexInTime {n m : Nat} (d : Nat) (positive : 0 < d) (c b : Nat) + (tape : Fin 10 → K) (distinct : Function.Injective tape) + (labels : VertexLabel d → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (StreamState A d)) + (atLabels : ∀ l, program (labels l) = vertexInstruction d positive c b tape labels exit l) + (base : K → List Bool) (rows : Fin d → DartRow n m) + (empty : ∀ i : Fin 10, i ≠ 7 → i ≠ 9 → base (tape i) = []) + (ambient : A) (output : List Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels (0, none)), streamClean d positive ambient, + streamFrame tape base (List.ofFn rows) output⟩ + (some ⟨exit, streamClean d positive ambient, + streamFrame (n := n) (m := m) tape base [] + (output ++ recordsOutput d c b (List.ofFn rows))⟩) + (d * (rowCostBound c b n m + 2 * (output.length + d * rowSizeBound c b n m) + 1) + 1) where + steps := vertexSteps d c b (List.ofFn rows) output + evals_in_steps := vertexTrace d positive c b tape distinct labels exit program atLabels + base rows empty ambient output + steps_le_m := by + simpa only [List.length_ofFn] using vertexSteps_le d c b (List.ofFn rows) output + +def vertexMachine (d : Nat) (positive : 0 < d) (c b : Nat) : FinTM2 where + K := Fin 10 + k₀ := 9 + k₁ := 7 + Γ _ := Bool + Λ := VertexLabel d + main := (0, none) + σ := StreamState Unit d + initialState := streamClean d positive () + m := vertexInstruction d positive c b id id none + +end MinUncutGames.Foundations.Complexity.MachineLazyRows + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineLazyTable.lean b/lean/OAI/Computability/MinUncut/Machines/MachineLazyTable.lean new file mode 100644 index 0000000000000000000000000000000000000000..86d7f3e9d66029b4d3273a7be1e6aca04fb29983 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineLazyTable.lean @@ -0,0 +1,875 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachinePaddedOverlay + +namespace OAI + +section +namespace MinUncutGames.Foundations.Complexity.MachineLazyTable + +open Turing MachineComposition PCP +open Reduction.MachineSubstitution (pushWord stepAux_pushWord) + + +inductive Tape + | input | output | source | vertices | darts | fuel | vertex | reverse + | tail | old | relation | scratch | divided | quotient | newReverse | rowBuffer + deriving DecidableEq + +protected abbrev Tape.enumList : List Tape := [.input, .output, .source, .vertices, .darts, .fuel, + .vertex, .reverse, .tail, .old, .relation, .scratch, .divided, .quotient, .newReverse, + .rowBuffer] + +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 + +abbrev State (d : Nat) := MachineLazyRows.StreamState Unit d + +def clean (d : Nat) (positive : 0 < d) : State d := + MachineLazyRows.streamClean d positive () + +theorem clean_pair (d : Nat) (positive : 0 < d) : + ((clean d positive).1, (none : Option Bool)) = clean d positive := rfl + +def splitRoles : Fin 5 → Tape := ![.input, .source, .scratch, .vertices, .darts] +def splitView : Tape → Option (Fin 5) + | .input => some 0 | .source => some 1 | .scratch => some 2 + | .vertices => some 3 | .darts => some 4 | _ => none + +def dummyRoles : Fin 6 → Tape := ![.tail, .reverse, .relation, .rowBuffer, .output, .scratch] +def dummyView : Tape → Option (Fin 6) + | .tail => some 0 | .reverse => some 1 | .relation => some 2 + | .rowBuffer => some 3 | .output => some 4 | .scratch => some 5 | _ => none + +def oldRoles : Fin 10 → Tape := + ![.tail, .old, .relation, .scratch, .divided, .quotient, .newReverse, + .output, .rowBuffer, .source] + +theorem splitRoles_left (i : Fin 5) : splitView (splitRoles i) = some i := by + fin_cases i <;> rfl + +theorem splitRoles_right (t : Tape) (i : Fin 5) (h : splitView t = some i) : splitRoles i = t := by + cases t <;> fin_cases i <;> simp_all [splitView, splitRoles] + +theorem dummyRoles_left (i : Fin 6) : dummyView (dummyRoles i) = some i := by + fin_cases i <;> rfl + +theorem dummyRoles_right (t : Tape) (i : Fin 6) (h : dummyView t = some i) : dummyRoles i = t := by + cases t <;> fin_cases i <;> simp_all [dummyView, dummyRoles] + +theorem oldRoles_injective : Function.Injective oldRoles := by decide + +inductive Label (d : Nat) + | split (label : MachineTableSplit.Label) + | dartSeed | dartScan | dartRestore | vertexSeed | vertexScan | vertexRestore + | fuelFirst | fuelSecond | seedCounters | guard | copyVertexFirst | copyVertexSecond + | dummy (label : MachineDummyRows.Label d) + | clearDummyTail | clearDummyRelation + | oldRows (label : MachineLazyRows.VertexLabel d) + | nextVertex | clearVertices | clearDarts | clearFuel | clearVertex | clearReverse + deriving DecidableEq, Fintype + +def program (d : Nat) (positive : 0 < d) : + Label d → TM2.Stmt (fun _ : Tape => Bool) (Label d) (State d) + | .split label => MachineCloudPadding.Placement.statement splitRoles Label.split + (some .dartSeed) (MachineTableSplit.program label) + | .dartSeed => MachineUnaryAffineAt.seed .output 0 .dartScan + | .dartScan => MachineUnaryAffineAt.scan .darts .scratch .output 2 .dartScan .dartRestore + | .dartRestore => Reduction.MachineTransfer.loopAt .scratch .darts id false + .dartRestore (some .vertexSeed) + | .vertexSeed => MachineUnaryAffineAt.seed .output 0 .vertexScan + | .vertexScan => MachineUnaryAffineAt.scan .vertices .scratch .output 1 .vertexScan .vertexRestore + | .vertexRestore => Reduction.MachineTransfer.loopAt .scratch .vertices id false + .vertexRestore (some .fuelFirst) + | .fuelFirst => Reduction.MachineTransfer.loopAt .vertices .scratch id false + .fuelFirst (some .fuelSecond) + | .fuelSecond => MachineCopy.forkLoop .scratch .vertices .fuel false + .fuelSecond (some .seedCounters) + | .seedCounters => .push .vertex (fun _ => false) + (.push .reverse (fun _ => false) (.goto fun _ => .guard)) + | .guard => MachineUnaryCounter.guard .fuel .copyVertexFirst .clearVertices + | .copyVertexFirst => Reduction.MachineTransfer.loopAt .vertex .scratch id false + .copyVertexFirst (some .copyVertexSecond) + | .copyVertexSecond => MachineCopy.forkLoop .scratch .vertex .tail false + .copyVertexSecond (some (.dummy (MachineDummyRows.start d))) + | .dummy label => MachineCloudPadding.Placement.statement dummyRoles Label.dummy + (some .clearDummyTail) (MachineDummyRows.program d label) + | .clearDummyTail => MachineDrain.drain .tail .clearDummyTail (some .clearDummyRelation) + | .clearDummyRelation => MachineDrain.drain .relation .clearDummyRelation (some (.oldRows (0, none))) + | .oldRows label => MachineLazyRows.vertexInstruction d positive (2 * d) d oldRoles + Label.oldRows (some .nextVertex) label + | .nextVertex => pushWord .reverse (List.replicate d true) + (.push .vertex (fun _ => true) (.goto fun _ => .guard)) + | .clearVertices => MachineDrain.drain .vertices .clearVertices (some .clearDarts) + | .clearDarts => MachineDrain.drain .darts .clearDarts (some .clearFuel) + | .clearFuel => MachineDrain.drain .fuel .clearFuel (some .clearVertex) + | .clearVertex => MachineDrain.drain .vertex .clearVertex (some .clearReverse) + | .clearReverse => MachineDrain.drain .reverse .clearReverse none + +def frame (input source output vertices darts fuel vertex reverse : List Bool) : Tape → List Bool + | .input => input | .source => source | .output => output + | .vertices => vertices | .darts => darts | .fuel => fuel + | .vertex => vertex | .reverse => reverse | _ => [] + +def initialTapes (input : List Bool) : Tape → List Bool := frame input [] [] [] [] [] [] [] + +def loopTapes (d : Nat) (input : List Bool) (n m left v : Nat) + (source output : List Bool) : Tape → List Bool := + frame input source output (encodeWord n) (encodeWord m) (encodeWord left) + (encodeWord v) (encodeWord (2 * d * v)) + +def finalTapes (input output : List Bool) : Tape → List Bool := frame input [] output [] [] [] [] [] + +theorem joinTrace {X : Type} {f : X → X} {a b c : X} {s t : Nat} + (first : f^[s] a = b) (second : f^[t] b = c) : f^[s + t] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +theorem dummyTrace (d : Nat) (positive : 0 < d) (base : Tape → List Bool) (v e : Nat) + (ht : base .tail = encodeWord v) (he : base .reverse = encodeWord e) + (hr : base .relation = []) (hb : base .rowBuffer = []) (hs : base .scratch = []) : + (advance (TM2.step (program d positive)))^[MachineDummyRows.steps v e (base .output) d + 1] + (some ⟨some (.dummy (MachineDummyRows.start d)), clean d positive, base⟩) = + some ⟨some .clearDummyTail, clean d positive, + Function.update (Function.update (Function.update base .reverse (encodeWord (e + d))) + .relation MachineDummyRows.trueBits) + .output (base .output ++ MachineDummyRows.rowsBits v e d)⟩ := by + have initial : MachineCloudPadding.Placement.tapes dummyView + (MachineDummyRows.initialTapes v e (base .output)) base = base := by + funext t + cases t <;> simp [MachineCloudPadding.Placement.tapes, dummyView, + MachineDummyRows.initialTapes, MachineDummyRows.fieldTapes, ht, he, hr, hb, hs] + have final : MachineCloudPadding.Placement.tapes dummyView + (MachineDummyRows.fieldTapes v (e + d) (base .output ++ MachineDummyRows.rowsBits v e d)) + base = Function.update (Function.update (Function.update base .reverse (encodeWord (e + d))) + .relation MachineDummyRows.trueBits) + .output (base .output ++ MachineDummyRows.rowsBits v e d) := by + funext t + cases t <;> simp [MachineCloudPadding.Placement.tapes, dummyView, + MachineDummyRows.fieldTapes, ht, hb, hs] + have run := MachineCloudPadding.Placement.trace dummyRoles dummyView + dummyRoles_left dummyRoles_right Label.dummy (some .clearDummyTail) base + (MachineDummyRows.program d) (program d positive) (fun _ => rfl) _ _ _ + (MachineDummyRows.allTrace d v e (base .output) (clean d positive).1 none) + simpa only [clean_pair, MachineCloudPadding.Placement.configuration, + MachineCloudPadding.Placement.label, initial, final] using run + +theorem oldTrace {n m : Nat} (d : Nat) (positive : 0 < d) + (base : Tape → List Bool) (rows : Fin d → GraphTables.DartRow n m) (rest : List Bool) + (hi : base .source = MachineLazyRows.recordsInput (List.ofFn rows) ++ rest) + (empty : ∀ i : Fin 10, i ≠ 7 → i ≠ 9 → base (oldRoles i) = []) : + (advance (TM2.step (program d positive)))^[MachineLazyRows.vertexSteps d (2 * d) d + (List.ofFn rows) (base .output)] + (some ⟨some (.oldRows (0, none)), clean d positive, base⟩) = + some ⟨some .nextVertex, clean d positive, + Function.update (Function.update base .source rest) .output + (base .output ++ MachineLazyRows.recordsOutput d (2 * d) d (List.ofFn rows))⟩ := by + let tailBase := Function.update base Tape.source rest + have cleanBase : ∀ i : Fin 10, i ≠ 7 → i ≠ 9 → tailBase (oldRoles i) = [] := by + intro i h7 h9 + have hn : oldRoles i ≠ Tape.source := by + intro h + have h' : oldRoles i = oldRoles 9 := h + exact h9 (oldRoles_injective h') + simpa only [tailBase, Function.update_of_ne hn] using empty i h7 h9 + have initial : MachineLazyRows.streamFrame oldRoles tailBase (List.ofFn rows) (base .output) = base := by + funext t + cases t <;> simp [MachineLazyRows.streamFrame, tailBase, oldRoles, hi] + have final : MachineLazyRows.streamFrame (n := n) (m := m) oldRoles tailBase [] + (base .output ++ MachineLazyRows.recordsOutput d (2 * d) d (List.ofFn rows)) = + Function.update (Function.update base .source rest) .output + (base .output ++ MachineLazyRows.recordsOutput d (2 * d) d (List.ofFn rows)) := by + funext t + cases t <;> simp [MachineLazyRows.streamFrame, MachineLazyRows.recordsInput, tailBase, oldRoles] + have run := MachineLazyRows.vertexTrace d positive (2 * d) d oldRoles oldRoles_injective + Label.oldRows (some .nextVertex) (program d positive) (fun _ => rfl) + tailBase rows cleanBase () (base .output) + simpa only [initial, final, clean] using run + +def prefixSteps (n m : Nat) (rows : List Bool) : Nat := + 2 * (encodeWords [n, m] ++ rows).length + 5 * n + 3 * m + 17 + +theorem prefixTrace (d : Nat) (positive : 0 < d) (n m : Nat) (rows : List Bool) : + (advance (TM2.step (program d positive)))^[prefixSteps n m rows] + (some ⟨some (.split .copyFirst), clean d positive, + initialTapes (encodeWords [n, m] ++ rows)⟩) = + some ⟨some .guard, clean d positive, + loopTapes d (encodeWords [n, m] ++ rows) n m n 0 rows (encodeWords [n, 2 * m])⟩ := by + let word := encodeWords [n, m] ++ rows + let header := encodeWords [n, 2 * m] + let b₁ := frame word rows [] (encodeWord n) (encodeWord m) [] [] [] + let b₂ := frame word rows (encodeWord (2 * m)) (encodeWord n) (encodeWord m) [] [] [] + let b₃ := frame word rows header (encodeWord n) (encodeWord m) [] [] [] + let b₄ := frame word rows header (encodeWord n) (encodeWord m) (encodeWord n) [] [] + have hstart : MachineCloudPadding.Placement.tapes splitView + (MachineTableSplit.initialTapes word) (fun _ => []) = initialTapes word := by + funext t + cases t <;> simp [MachineCloudPadding.Placement.tapes, splitView, + MachineTableSplit.initialTapes, MachineTableSplit.tapes, initialTapes, frame] + have hend : MachineCloudPadding.Placement.tapes splitView + (MachineTableSplit.resultTapes n m rows) (fun _ => []) = b₁ := by + funext t + cases t <;> simp [MachineCloudPadding.Placement.tapes, splitView, + MachineTableSplit.resultTapes, MachineTableSplit.tapes, b₁, frame, word] + have split := MachineCloudPadding.Placement.trace splitRoles splitView + splitRoles_left splitRoles_right Label.split (some .dartSeed) (fun _ => []) + MachineTableSplit.program (program d positive) (fun _ => rfl) _ _ _ + (MachineTableSplit.splitTrace n m rows (clean d positive).1 none) + have c₀ : (advance (TM2.step (program d positive)))^[MachineTableSplit.exactSteps n m rows] + (some ⟨some (.split .copyFirst), clean d positive, initialTapes word⟩) = + some ⟨some .dartSeed, clean d positive, b₁⟩ := by + simp only [MachineCloudPadding.Placement.configuration, + MachineCloudPadding.Placement.label] at split + rw [hstart, hend] at split + simpa only [clean_pair] using split + have hdart : Function.update b₁ Tape.output (encodeWord (2 * m + 0) ++ b₁ .output) = b₂ := by + funext t; cases t <;> simp [b₁, b₂, frame] + have dart := MachineUnaryAffineAt.seededAffineTrace Tape.darts .scratch .output + (by decide) (by decide) (by decide) 2 0 .dartSeed .dartScan .dartRestore + (some .vertexSeed) (program d positive) rfl rfl rfl b₁ m [] + (by simp [b₁, frame]) rfl (clean d positive).1 none + have c₁ : (advance (TM2.step (program d positive)))^[2 * (m + 1) + 1] + (some ⟨some .dartSeed, clean d positive, b₁⟩) = + some ⟨some .vertexSeed, clean d positive, b₂⟩ := by + simpa only [hdart, clean_pair] using dart + have hv : Function.update b₂ Tape.output (encodeWord (1 * n + 0) ++ b₂ .output) = b₃ := by + funext t; cases t <;> simp [b₂, b₃, frame, header, encodeWords] + have vertex := MachineUnaryAffineAt.seededAffineTrace Tape.vertices .scratch .output + (by decide) (by decide) (by decide) 1 0 .vertexSeed .vertexScan .vertexRestore + (some .fuelFirst) (program d positive) rfl rfl rfl b₂ n [] + (by simp [b₂, frame]) rfl (clean d positive).1 none + have c₂ : (advance (TM2.step (program d positive)))^[2 * (n + 1) + 1] + (some ⟨some .vertexSeed, clean d positive, b₂⟩) = + some ⟨some .fuelFirst, clean d positive, b₃⟩ := by + simpa only [hv, clean_pair] using vertex + have hf : Function.update b₃ Tape.fuel (b₃ .vertices ++ b₃ .fuel) = b₄ := by + funext t; cases t <;> simp [b₃, b₄, frame] + have fuel := MachineCopy.copyTrace Tape.vertices .fuel .scratch + (by decide) (by decide) (by decide) false .fuelFirst .fuelSecond + (some .seedCounters) (program d positive) rfl rfl b₃ rfl (clean d positive).1 none + rw [hf] at fuel + have c₃ : (advance (TM2.step (program d positive)))^[2 * (n + 2)] + (some ⟨some .fuelFirst, clean d positive, b₃⟩) = + some ⟨some .seedCounters, clean d positive, b₄⟩ := by + simpa only [clean_pair, show b₃ .vertices = encodeWord n from rfl, encodeWord_length, + Nat.add_assoc] using fuel + have c₄ : (advance (TM2.step (program d positive)))^[1] + (some ⟨some .seedCounters, clean d positive, b₄⟩) = + some ⟨some .guard, clean d positive, + loopTapes d word n m n 0 rows header⟩ := by + have ht : Function.update (Function.update b₄ Tape.vertex [false]) Tape.reverse [false] = + loopTapes d word n m n 0 rows header := by + funext t; cases t <;> simp [b₄, loopTapes, frame, encodeWord] + simp only [Function.iterate_one, advance_some, TM2.step, program, TM2.stepAux] + apply congrArg some + exact congrArg (TM2.Cfg.mk _ _) ht + have all := joinTrace (joinTrace (joinTrace (joinTrace c₀ c₁) c₂) c₃) c₄ + have hc : MachineTableSplit.exactSteps n m rows + (2 * (m + 1) + 1) + + (2 * (n + 1) + 1) + 2 * (n + 2) + 1 = prefixSteps n m rows := by + dsimp [MachineTableSplit.exactSteps, prefixSteps] + omega + rw [hc] at all + exact all + +def vertexBlock {n m : Nat} (d v : Nat) (rows : Fin d → GraphTables.DartRow n m) : List Bool := + MachineDummyRows.rowsBits v (2 * d * v) d ++ + MachineLazyRows.recordsOutput d (2 * d) d (List.ofFn rows) + +def bodySteps {n m : Nat} (d v : Nat) (rows : Fin d → GraphTables.DartRow n m) + (output : List Bool) : Nat := + 2 * (v + 2) + (MachineDummyRows.steps v (2 * d * v) output d + 1) + (v + 2) + 8193 + + MachineLazyRows.vertexSteps d (2 * d) d (List.ofFn rows) + (output ++ MachineDummyRows.rowsBits v (2 * d * v) d) + 1 + +theorem frame_old_empty (input source output vertices darts fuel vertex reverse : List Bool) + (i : Fin 10) (h7 : i ≠ 7) (h9 : i ≠ 9) : + frame input source output vertices darts fuel vertex reverse (oldRoles i) = [] := by + fin_cases i <;> simp_all [frame, oldRoles] + +theorem bodyTrace {n m : Nat} (d : Nat) (positive : 0 < d) (input : List Bool) + (left v : Nat) (rows : Fin d → GraphTables.DartRow n m) (rest output : List Bool) : + (advance (TM2.step (program d positive)))^[bodySteps d v rows output] + (some ⟨some .copyVertexFirst, clean d positive, + loopTapes d input n m left v (MachineLazyRows.recordsInput (List.ofFn rows) ++ rest) output⟩) = + some ⟨some .guard, clean d positive, + loopTapes d input n m left (v + 1) rest (output ++ vertexBlock d v rows)⟩ := by + let source := MachineLazyRows.recordsInput (List.ofFn rows) ++ rest + let dummy := MachineDummyRows.rowsBits v (2 * d * v) d + let moving := MachineLazyRows.recordsOutput d (2 * d) d (List.ofFn rows) + let b₀ := loopTapes d input n m left v source output + let b₁ := Function.update b₀ Tape.tail (encodeWord v) + let b₄ := frame input source (output ++ dummy) (encodeWord n) (encodeWord m) + (encodeWord left) (encodeWord v) (encodeWord (2 * d * v + d)) + let b₂ := Function.update (Function.update b₄ Tape.tail (encodeWord v)) + Tape.relation MachineDummyRows.trueBits + let b₃ := Function.update b₄ Tape.relation MachineDummyRows.trueBits + let b₅ := frame input rest ((output ++ dummy) ++ moving) (encodeWord n) (encodeWord m) + (encodeWord left) (encodeWord v) (encodeWord (2 * d * v + d)) + have hcopy : Function.update b₀ Tape.tail (b₀ .vertex ++ b₀ .tail) = b₁ := by + simp [b₀, b₁, loopTapes, frame] + have copy := MachineCopy.copyTrace Tape.vertex .tail .scratch + (by decide) (by decide) (by decide) false .copyVertexFirst .copyVertexSecond + (some (.dummy (MachineDummyRows.start d))) (program d positive) rfl rfl b₀ rfl + (clean d positive).1 none + rw [hcopy] at copy + have c₀ : (advance (TM2.step (program d positive)))^[2 * (v + 2)] + (some ⟨some .copyVertexFirst, clean d positive, b₀⟩) = + some ⟨some (.dummy (MachineDummyRows.start d)), clean d positive, b₁⟩ := by + simpa only [clean_pair, show b₀ .vertex = encodeWord v from rfl, encodeWord_length, + Nat.add_assoc] using copy + have hdummy : Function.update (Function.update (Function.update b₁ Tape.reverse + (encodeWord (2 * d * v + d))) Tape.relation MachineDummyRows.trueBits) + Tape.output (b₁ .output ++ dummy) = b₂ := by + funext t; cases t <;> simp [b₀, b₁, b₂, b₄, loopTapes, frame] + have dummies := dummyTrace d positive b₁ v (2 * d * v) + (by simp [b₁]) (by simp [b₁, b₀, loopTapes, frame]) + (by simp [b₁, b₀, loopTapes, frame]) (by simp [b₁, b₀, loopTapes, frame]) + (by simp [b₁, b₀, loopTapes, frame]) + have c₁ : (advance (TM2.step (program d positive)))^[MachineDummyRows.steps v + (2 * d * v) output d + 1] + (some ⟨some (.dummy (MachineDummyRows.start d)), clean d positive, b₁⟩) = + some ⟨some .clearDummyTail, clean d positive, b₂⟩ := by + change (advance (TM2.step (program d positive)))^[_] _ = + some ⟨some .clearDummyTail, clean d positive, + Function.update (Function.update (Function.update b₁ Tape.reverse + (encodeWord (2 * d * v + d))) Tape.relation MachineDummyRows.trueBits) + Tape.output (b₁ .output ++ dummy)⟩ at dummies + rw [hdummy] at dummies + simpa only [show b₁ .output = output by simp [b₁, b₀, loopTapes, frame]] using dummies + have ht : Function.update b₂ Tape.tail [] = b₃ := by + funext t; cases t <;> simp [b₂, b₃, b₄, frame] + have drainTail := MachineDrain.drainTrace Tape.tail .clearDummyTail (some .clearDummyRelation) + (program d positive) rfl b₂ (b₂ .tail) (clean d positive).1 none + simp only [Function.update_eq_self, ht] at drainTail + have c₂ : (advance (TM2.step (program d positive)))^[v + 2] + (some ⟨some .clearDummyTail, clean d positive, b₂⟩) = + some ⟨some .clearDummyRelation, clean d positive, b₃⟩ := by + simpa only [clean_pair, show b₂ .tail = encodeWord v by simp [b₂], encodeWord_length, + Nat.add_assoc] using drainTail + have hr : Function.update b₃ Tape.relation [] = b₄ := by + funext t; cases t <;> simp [b₃, b₄, frame] + have drainRelation := MachineDrain.drainTrace Tape.relation .clearDummyRelation + (some (.oldRows (0, none))) (program d positive) rfl b₃ (b₃ .relation) + (clean d positive).1 none + simp only [Function.update_eq_self, hr] at drainRelation + have c₃ : (advance (TM2.step (program d positive)))^[8193] + (some ⟨some .clearDummyRelation, clean d positive, b₃⟩) = + some ⟨some (.oldRows (0, none)), clean d positive, b₄⟩ := by + simpa only [clean_pair, show b₃ .relation = MachineDummyRows.trueBits by simp [b₃], + MachineDummyRows.trueBits_length] using drainRelation + have hmoving : Function.update (Function.update b₄ Tape.source rest) Tape.output + (b₄ .output ++ moving) = b₅ := by + funext t; cases t <;> simp [b₄, b₅, frame] + have old := oldTrace d positive b₄ rows rest rfl + (fun i h7 h9 => frame_old_empty _ _ _ _ _ _ _ _ i h7 h9) + have c₄ : (advance (TM2.step (program d positive)))^[MachineLazyRows.vertexSteps d (2 * d) d + (List.ofFn rows) (output ++ dummy)] + (some ⟨some (.oldRows (0, none)), clean d positive, b₄⟩) = + some ⟨some .nextVertex, clean d positive, b₅⟩ := by + change (advance (TM2.step (program d positive)))^[_] _ = + some ⟨some .nextVertex, clean d positive, + Function.update (Function.update b₄ Tape.source rest) Tape.output + (b₄ .output ++ moving)⟩ at old + rw [hmoving] at old + exact old + have c₅ : (advance (TM2.step (program d positive)))^[1] + (some ⟨some .nextVertex, clean d positive, b₅⟩) = + some ⟨some .guard, clean d positive, + loopTapes d input n m left (v + 1) rest (output ++ vertexBlock d v rows)⟩ := by + have hrev : List.replicate d true ++ encodeWord (2 * d * v + d) = + encodeWord (2 * d * (v + 1)) := by + have hw := MachineUnaryAffineAt.prepend_replicate_word d (2 * d * v + d) [] + simp only [List.append_nil] at hw + rw [hw] + exact congrArg encodeWord (show d + (2 * d * v + d) = 2 * d * (v + 1) by + simp only [Nat.mul_add, Nat.mul_one] + omega) + have ht : Function.update (Function.update b₅ Tape.reverse + ((List.replicate d true).reverse ++ b₅ .reverse)) Tape.vertex (true :: b₅ .vertex) = + loopTapes d input n m left (v + 1) rest (output ++ vertexBlock d v rows) := by + funext t + cases t <;> simp [b₅, frame, loopTapes, vertexBlock, dummy, moving, + hrev, List.append_assoc] + simp [encodeWord, List.replicate_succ] + simp only [Function.iterate_one, advance_some, TM2.step, program, + stepAux_pushWord, TM2.stepAux] + apply congrArg some + exact congrArg (TM2.Cfg.mk _ _) ht + have all := joinTrace (joinTrace (joinTrace (joinTrace (joinTrace c₀ c₁) c₂) c₃) c₄) c₅ + exact all + +theorem drainPhase (d : Nat) (positive : 0 < d) (tape : Tape) (label : Label d) + (exit : Option (Label d)) + (atLabel : program d positive label = MachineDrain.drain tape label exit) + (base : Tape → List Bool) : + (advance (TM2.step (program d positive)))^[(base tape).length + 1] + (some ⟨some label, clean d positive, base⟩) = + some ⟨exit, clean d positive, Function.update base tape []⟩ := by + simpa only [Function.update_eq_self, clean_pair] using + MachineDrain.drainTrace tape label exit (program d positive) atLabel base + (base tape) (clean d positive).1 none + +def finishSteps (d n m v : Nat) : Nat := n + m + v + 2 * d * v + 11 + +theorem finishTrace (d : Nat) (positive : 0 < d) (input output : List Bool) (n m v : Nat) : + (advance (TM2.step (program d positive)))^[finishSteps d n m v] + (some ⟨some .guard, clean d positive, loopTapes d input n m 0 v [] output⟩) = + some ⟨none, clean d positive, finalTapes input output⟩ := by + let b₀ := loopTapes d input n m 0 v [] output + let b₁ := Function.update b₀ Tape.vertices [] + let b₂ := Function.update b₁ Tape.darts [] + let b₃ := Function.update b₂ Tape.fuel [] + let b₄ := Function.update b₃ Tape.vertex [] + have hframe : MachineUnaryCounter.counterTapes Tape.fuel b₀ 0 [] = b₀ := by + funext t; cases t <;> simp [MachineUnaryCounter.counterTapes, b₀, loopTapes, frame] + have guard := MachineUnaryCounter.guardTrace_zero Tape.fuel .guard .copyVertexFirst + .clearVertices (program d positive) rfl b₀ [] (clean d positive).1 none + have c₀ : (advance (TM2.step (program d positive)))^[1] + (some ⟨some .guard, clean d positive, b₀⟩) = + some ⟨some .clearVertices, clean d positive, b₀⟩ := by + simpa only [hframe, clean_pair] using guard + have c₁ : (advance (TM2.step (program d positive)))^[n + 2] + (some ⟨some .clearVertices, clean d positive, b₀⟩) = + some ⟨some .clearDarts, clean d positive, b₁⟩ := by + simpa only [show b₀ .vertices = encodeWord n from rfl, encodeWord_length, Nat.add_assoc] using + drainPhase d positive .vertices .clearVertices (some .clearDarts) rfl b₀ + have c₂ : (advance (TM2.step (program d positive)))^[m + 2] + (some ⟨some .clearDarts, clean d positive, b₁⟩) = + some ⟨some .clearFuel, clean d positive, b₂⟩ := by + have hv : b₁ .darts = encodeWord m := by simp [b₁, b₀, loopTapes, frame] + simpa only [hv, encodeWord_length, Nat.add_assoc] using + drainPhase d positive .darts .clearDarts (some .clearFuel) rfl b₁ + have c₃ : (advance (TM2.step (program d positive)))^[2] + (some ⟨some .clearFuel, clean d positive, b₂⟩) = + some ⟨some .clearVertex, clean d positive, b₃⟩ := by + have hv : b₂ .fuel = encodeWord 0 := by simp [b₂, b₁, b₀, loopTapes, frame] + simpa only [hv, encodeWord_length] using + drainPhase d positive .fuel .clearFuel (some .clearVertex) rfl b₂ + have c₄ : (advance (TM2.step (program d positive)))^[v + 2] + (some ⟨some .clearVertex, clean d positive, b₃⟩) = + some ⟨some .clearReverse, clean d positive, b₄⟩ := by + have hv : b₃ .vertex = encodeWord v := by simp [b₃, b₂, b₁, b₀, loopTapes, frame] + simpa only [hv, encodeWord_length, Nat.add_assoc] using + drainPhase d positive .vertex .clearVertex (some .clearReverse) rfl b₃ + have hend : Function.update b₄ Tape.reverse [] = finalTapes input output := by + funext t; cases t <;> simp [b₄, b₃, b₂, b₁, b₀, loopTapes, finalTapes, frame] + have c₅ : (advance (TM2.step (program d positive)))^[2 * d * v + 2] + (some ⟨some .clearReverse, clean d positive, b₄⟩) = + some ⟨none, clean d positive, finalTapes input output⟩ := by + have hv : b₄ .reverse = encodeWord (2 * d * v) := by + simp [b₄, b₃, b₂, b₁, b₀, loopTapes, frame] + simpa only [hv, encodeWord_length, Nat.add_assoc, hend] using + drainPhase d positive .reverse .clearReverse none rfl b₄ + have all := joinTrace (joinTrace (joinTrace (joinTrace (joinTrace c₀ c₁) c₂) c₃) c₄) c₅ + have hc : 1 + (n + 2) + (m + 2) + 2 + (v + 2) + (2 * d * v + 2) = + finishSteps d n m v := by dsimp [finishSteps]; omega + rw [hc] at all + exact all + +def remaining (n r : Nat) : List (Fin n) := (List.finRange n).drop r + +@[simp] theorem remaining_zero (n : Nat) : remaining n 0 = List.finRange n := by simp [remaining] +@[simp] theorem remaining_done (n : Nat) : remaining n n = [] := by simp [remaining] + +theorem remaining_cons (n r : Nat) (h : r < n) : + remaining n r = ⟨r, h⟩ :: remaining n (r + 1) := by + unfold remaining + rw [List.drop_eq_getElem_cons (l := List.finRange n) (i := r) (by simpa using h)] + simp + +def inputBlocks {n d : Nat} (table : PortTables.Table n d) (events : List (Fin n)) : List Bool := + events.flatMap (fun v => MachineLazyRows.recordsInput (List.ofFn (PreprocessingLazyWords.row table v))) + +def outputBlocks {n d : Nat} (table : PortTables.Table n d) (events : List (Fin n)) : List Bool := + events.flatMap (fun v => vertexBlock d v.val (PreprocessingLazyWords.row table v)) + +theorem vertexBlock_codec {n d : Nat} (table : PortTables.Table n d) (v : Fin n) : + vertexBlock d v.val (PreprocessingLazyWords.row table v) = + encodeWords ((PreprocessingLazyWords.vertexRows table v).flatMap GraphTables.rowWords) := by + rw [vertexBlock, MachineLazyCodec.rowsBits_stay, MachineLazyRows.recordsOutput_lazy, + PreprocessingLazyWords.vertexRows, List.flatMap_append, encodeWords_append] + +theorem encodeWords_flatMap {α : Type} (xs : List α) (f : α → List Nat) : + encodeWords (xs.flatMap f) = xs.flatMap (fun x => encodeWords (f x)) := by + induction xs with + | nil => rfl + | cons x xs ih => simp only [List.flatMap_cons, encodeWords_append, ih] + +theorem inputBlocks_codec {n d : Nat} (table : PortTables.Table n d) (events : List (Fin n)) : + inputBlocks table events = encodeWords + ((events.flatMap (fun v => List.ofFn (PreprocessingLazyWords.row table v))).flatMap + GraphTables.rowWords) := by + rw [List.flatMap_assoc, encodeWords_flatMap] + simp only [inputBlocks, MachineLazyRows.recordsInput_eq_codec] + +theorem outputBlocks_codec {n d : Nat} (table : PortTables.Table n d) (events : List (Fin n)) : + outputBlocks table events = encodeWords + ((events.flatMap (PreprocessingLazyWords.vertexRows table)).flatMap GraphTables.rowWords) := by + rw [List.flatMap_assoc, encodeWords_flatMap] + simp only [outputBlocks, vertexBlock_codec] + +theorem input_table_codec {n d : Nat} (table : PortTables.Table n d) : + PortTables.tableBits table = encodeWords [n, n * d] ++ inputBlocks table (List.finRange n) := by + rw [inputBlocks_codec] + change encodeWords (PortTables.tableWords table) = _ + rw [PortTables.tableWords_eq, PreprocessingLazyWords.flatRows_list, encodeWords_append] + have hrows : (List.ofFn (fun v => List.ofFn (PreprocessingLazyWords.row table v))).flatten = + (List.finRange n).flatMap (fun v => List.ofFn (PreprocessingLazyWords.row table v)) := by + rw [List.ofFn_eq_map] + rfl + rw [hrows] + +theorem output_table_codec {n d : Nat} (table : PortTables.Table n d) : + PortTables.tableBits (PreprocessingOverlayTables.lazy table) = + encodeWords [n, 2 * (n * d)] ++ outputBlocks table (List.finRange n) := by + rw [outputBlocks_codec, PreprocessingLazyWords.tableBits_lazy, encodeWords_append] + have hm : n * (2 * d) = 2 * (n * d) := by ac_rfl + have hrows : (List.ofFn (PreprocessingLazyWords.vertexRows table)).flatten = + (List.finRange n).flatMap (PreprocessingLazyWords.vertexRows table) := by + rw [List.ofFn_eq_map] + rfl + exact congrArg₂ List.append (congrArg (fun k => encodeWords [n, k]) hm) + (congrArg (fun rows => encodeWords (rows.flatMap GraphTables.rowWords)) hrows) + +def loopSteps {n d : Nat} (table : PortTables.Table n d) (r : Nat) : Nat → List Bool → Nat + | 0, _ => finishSteps d n (n * d) r + | count + 1, output => if h : r < n then + (1 + bodySteps d r (PreprocessingLazyWords.row table ⟨r, h⟩) output) + + loopSteps table (r + 1) count + (output ++ vertexBlock d r (PreprocessingLazyWords.row table ⟨r, h⟩)) + else 0 + +theorem loopTrace {n d : Nat} (table : PortTables.Table n d) (positive : 0 < d) + (input : List Bool) (count r : Nat) (hsum : r + count = n) (output : List Bool) : + (advance (TM2.step (program d positive)))^[loopSteps table r count output] + (some ⟨some .guard, clean d positive, + loopTapes d input n (n * d) count r (inputBlocks table (remaining n r)) output⟩) = + some ⟨none, clean d positive, + finalTapes input (output ++ outputBlocks table (remaining n r))⟩ := by + induction count generalizing r output with + | zero => + have hr : r = n := by omega + subst r + simpa only [loopSteps, remaining_done, inputBlocks, outputBlocks, List.flatMap_nil, + List.append_nil] using finishTrace d positive input output n (n * d) n + | succ count ih => + have hr : r < n := by omega + let rows := PreprocessingLazyWords.row table (⟨r, hr⟩ : Fin n) + let rest := inputBlocks table (remaining n (r + 1)) + let source := MachineLazyRows.recordsInput (List.ofFn rows) ++ rest + let b₀ := loopTapes d input n (n * d) (count + 1) r source output + let b₁ := loopTapes d input n (n * d) count r source output + have hguard (k : Nat) : MachineUnaryCounter.counterTapes Tape.fuel b₀ k [] = + loopTapes d input n (n * d) k r source output := by + funext t; cases t <;> simp [MachineUnaryCounter.counterTapes, b₀, loopTapes, frame] + have guard := MachineUnaryCounter.guardTrace_succ Tape.fuel .guard .copyVertexFirst + .clearVertices (program d positive) rfl b₀ count [] (clean d positive).1 none + have c₀ : (advance (TM2.step (program d positive)))^[1] + (some ⟨some .guard, clean d positive, b₀⟩) = + some ⟨some .copyVertexFirst, clean d positive, b₁⟩ := by + simpa only [hguard, clean_pair] using guard + have c₁ := bodyTrace d positive input count r rows rest output + have c₂ := ih (r + 1) (by omega) (output ++ vertexBlock d r rows) + have all := joinTrace (joinTrace c₀ c₁) c₂ + have hi : inputBlocks table (remaining n r) = source := by + rw [remaining_cons n r hr] + rfl + have ho : outputBlocks table (remaining n r) = + vertexBlock d r rows ++ outputBlocks table (remaining n (r + 1)) := by + rw [remaining_cons n r hr] + rfl + simpa only [loopSteps, dite_eq_left hr, hi, ho, List.append_assoc] using all + +def totalSteps {n d : Nat} (table : PortTables.Table n d) : Nat := + prefixSteps n (n * d) (inputBlocks table (List.finRange n)) + + loopSteps table 0 n (encodeWords [n, 2 * (n * d)]) + +theorem tableTrace {n d : Nat} (table : PortTables.Table n d) (positive : 0 < d) : + (advance (TM2.step (program d positive)))^[totalSteps table] + (some ⟨some (.split .copyFirst), clean d positive, initialTapes (PortTables.tableBits table)⟩) = + some ⟨none, clean d positive, + finalTapes (PortTables.tableBits table) + (PortTables.tableBits (PreprocessingOverlayTables.lazy table))⟩ := by + have prefixRun := prefixTrace d positive n (n * d) (inputBlocks table (List.finRange n)) + rw [← input_table_codec table] at prefixRun + have loop := loopTrace table positive (PortTables.tableBits table) n 0 (by omega) + (encodeWords [n, 2 * (n * d)]) + simp only [remaining_zero] at loop + have all := joinTrace prefixRun loop + rw [← output_table_codec table] at all + exact all + +private theorem dummyRows_length_le (v e count : Nat) : + (MachineDummyRows.rowsBits v e count).length ≤ count * (v + e + count + 8194) := by + induction count generalizing e with + | zero => simp [MachineDummyRows.rowsBits] + | succ count ih => + simp only [MachineDummyRows.rowsBits, List.length_append, MachineDummyRows.rowBits_length] + have h := ih (e + 1) + have he : v + (e + 1) + count + 8194 = v + e + (count + 1) + 8194 := by omega + rw [he] at h + nlinarith only [h] + +theorem bodySteps_le {n d : Nat} (rows : Fin d → GraphTables.DartRow n (n * d)) + (v L : Nat) (output : List Bool) (hv : v ≤ n) (hn : n ≤ L) (hm : n * d ≤ L) + (ho : output.length ≤ 20000 * (L + 1) ^ 2) : + bodySteps d v rows output ≤ 1000000 * (d + 1) ^ 3 * (L + 1) ^ 2 := by + let D := d + 1 + let N := L + 1 + let P := D * N + let Q := P * P + let S := v + 2 * d * v + d + 8194 + let V := (2 * d) * (n * d) + n * d + d + let R := n + V + 8194 + let C := 2 * n + 8 * (n * d) + V + 4 * R + 8224 + let dummy := MachineDummyRows.rowsBits v (2 * d * v) d + let after := output ++ dummy + have hD : 1 ≤ D := by dsimp [D]; omega + have hN : 1 ≤ N := by dsimp [N]; omega + have hdD : d ≤ D := by dsimp [D]; omega + have hLN : L ≤ N := by dsimp [N]; omega + have hDP : D ≤ P := by + have h := Nat.mul_le_mul_left D hN + simpa [P] using h + have hNP : N ≤ P := by + have h := Nat.mul_le_mul_right N hD + simpa [P] using h + have hP : 1 ≤ P := hN.trans hNP + have hPQ : P ≤ Q := by + have h := Nat.mul_le_mul_right P hP + simpa [Q] using h + have hQ : 1 ≤ Q := hP.trans hPQ + have hdP : d ≤ P := hdD.trans hDP + have hvN : v ≤ N := hv.trans (hn.trans hLN) + have hvP : v ≤ P := hvN.trans hNP + have hnP : n ≤ P := hn.trans (hLN.trans hNP) + have hmN : n * d ≤ N := hm.trans hLN + have hmP : n * d ≤ P := hmN.trans hNP + have hdv : d * v ≤ P := by simpa [P] using Nat.mul_le_mul hdD hvN + have hdm : d * (n * d) ≤ P := by simpa [P] using Nat.mul_le_mul hdD hmN + have hdPQ : d * P ≤ Q := by simpa [Q] using Nat.mul_le_mul_right P hdP + have hNQ : N ^ 2 ≤ Q := by simpa [pow_two, Q] using Nat.mul_le_mul hNP hNP + have hS : S ≤ 10000 * P := by + have hconst := Nat.mul_le_mul_left 8194 hP + dsimp [S] + nlinarith only [hvP, hdP, hdv, hconst, hP] + have hV : V ≤ 4 * P := by + dsimp [V] + nlinarith only [hdm, hmP, hdP] + have hR : R ≤ 10000 * P := by + have hconst := Nat.mul_le_mul_left 8194 hP + dsimp [R] + nlinarith only [hnP, hV, hconst, hP] + have hC : C ≤ 50000 * P := by + have hconst := Nat.mul_le_mul_left 8224 hP + dsimp [C] + nlinarith only [hnP, hmP, hV, hR, hconst, hP] + have hSQ : S ≤ 10000 * Q := hS.trans (Nat.mul_le_mul_left 10000 hPQ) + have hCQ : C ≤ 50000 * Q := hC.trans (Nat.mul_le_mul_left 50000 hPQ) + have hdSQ : d * S ≤ 10000 * Q := by + calc + d * S ≤ d * (10000 * P) := Nat.mul_le_mul_left d hS + _ = 10000 * (d * P) := by ring + _ ≤ 10000 * Q := Nat.mul_le_mul_left 10000 hdPQ + have hdRQ : d * R ≤ 10000 * Q := by + calc + d * R ≤ d * (10000 * P) := Nat.mul_le_mul_left d hR + _ = 10000 * (d * P) := by ring + _ ≤ 10000 * Q := Nat.mul_le_mul_left 10000 hdPQ + have hOut : output.length ≤ 20000 * Q := by + change output.length ≤ 20000 * N ^ 2 at ho + exact ho.trans (Nat.mul_le_mul_left 20000 hNQ) + have hDummyLength : dummy.length ≤ 10000 * Q := by + have h := dummyRows_length_le v (2 * d * v) d + change dummy.length ≤ d * S at h + exact h.trans hdSQ + have hAfter : after.length ≤ 30000 * Q := by + dsimp [after] + rw [List.length_append] + omega + have hDummyInside : 4 * S + 2 * (output.length + d * S) + 10 ≤ 100010 * Q := by + have hconst := Nat.mul_le_mul_left 10 hQ + nlinarith only [hSQ, hOut, hdSQ, hconst] + have hDummySteps : MachineDummyRows.steps v (2 * d * v) output d ≤ 100010 * d * Q := by + calc + MachineDummyRows.steps v (2 * d * v) output d ≤ + d * (4 * S + 2 * (output.length + d * S) + 10) := by + simpa only [S] using MachineDummyRows.steps_le_bound v (2 * d * v) output d + _ ≤ d * (100010 * Q) := Nat.mul_le_mul_left d hDummyInside + _ = 100010 * d * Q := by ring + have hOldInside : C + 2 * (after.length + d * R) + 1 ≤ 130001 * Q := by + nlinarith only [hCQ, hAfter, hdRQ, hQ] + have hOldSteps : MachineLazyRows.vertexSteps d (2 * d) d (List.ofFn rows) after ≤ + 130001 * d * Q + 1 := by + have h := MachineLazyRows.vertexSteps_le d (2 * d) d (List.ofFn rows) after + simp only [List.length_ofFn] at h + change MachineLazyRows.vertexSteps d (2 * d) d (List.ofFn rows) after ≤ + d * (C + 2 * (after.length + d * R) + 1) + 1 at h + calc + MachineLazyRows.vertexSteps d (2 * d) d (List.ofFn rows) after ≤ + d * (C + 2 * (after.length + d * R) + 1) + 1 := h + _ ≤ d * (130001 * Q) + 1 := + Nat.add_le_add_right (Nat.mul_le_mul_left d hOldInside) 1 + _ = 130001 * d * Q + 1 := by ring + have hvQ : v ≤ Q := hvP.trans hPQ + have hOverhead : 3 * v + 8201 ≤ 10000 * Q := by + have hconst := Nat.mul_le_mul_left 8201 hQ + nlinarith only [hvQ, hconst, hQ] + have hBody : bodySteps d v rows output ≤ 230011 * d * Q + 10000 * Q + 1 := by + change 2 * (v + 2) + (MachineDummyRows.steps v (2 * d * v) output d + 1) + + (v + 2) + 8193 + MachineLazyRows.vertexSteps d (2 * d) d (List.ofFn rows) after + 1 ≤ _ + nlinarith only [hDummySteps, hOldSteps, hOverhead] + have hdQQ : d * Q ≤ D * Q := Nat.mul_le_mul_right Q hdD + have hQQ : Q ≤ D * Q := by simpa using Nat.mul_le_mul_right Q hD + have hDQ : 1 ≤ D * Q := hQ.trans hQQ + have hCoarse : bodySteps d v rows output ≤ 300000 * D * Q := by + nlinarith only [hBody, hdQQ, hQQ, hDQ] + calc + bodySteps d v rows output ≤ 300000 * D * Q := hCoarse + _ ≤ 1000000 * D * Q := by + have h := Nat.mul_le_mul_right (D * Q) (by norm_num : (300000 : Nat) ≤ 1000000) + simpa only [Nat.mul_assoc] using h + _ = 1000000 * (d + 1) ^ 3 * (L + 1) ^ 2 := by dsimp [D, N, P, Q]; ring + +theorem output_length_le {n d : Nat} (table : PortTables.Table n d) : + (PortTables.tableBits (PreprocessingOverlayTables.lazy table)).length ≤ + 20000 * ((PortTables.tableBits table).length + 1) ^ 2 := by + let L := (PortTables.tableBits table).length + have hn : n ≤ L := PortTables.vertices_le_tableBits_length table + have hm : n * d ≤ L := GraphTables.darts_le_tableBits_length (PortTables.graphTable table) + have h := GraphTables.tableBits_length_le + (PortTables.graphTable (PreprocessingOverlayTables.lazy table)) + change (PortTables.tableBits (PreprocessingOverlayTables.lazy table)).length ≤ + n + n * (2 * d) + 2 + n * (2 * d) * (n + n * (2 * d) + 8192) at h + have hdouble : n * (2 * d) = 2 * (n * d) := by ac_rfl + rw [hdouble] at h + have hmul := Nat.mul_le_mul (Nat.mul_le_mul_left 2 hm) + (Nat.add_le_add_right (Nat.add_le_add hn (Nat.mul_le_mul_left 2 hm)) 8192) + change _ ≤ 20000 * (L + 1) ^ 2 + nlinarith only [h, hn, hm, hmul] + +theorem loopSteps_le {n d : Nat} (table : PortTables.Table n d) (L count r : Nat) + (hsum : r + count = n) (hn : n ≤ L) (hm : n * d ≤ L) (output : List Bool) + (hout : (output ++ outputBlocks table (remaining n r)).length ≤ 20000 * (L + 1) ^ 2) : + loopSteps table r count output ≤ + count * (1 + 1000000 * (d + 1) ^ 3 * (L + 1) ^ 2) + 5 * L + 11 := by + induction count generalizing r output with + | zero => + have hr : r = n := by omega + subst r + have hdouble : 2 * d * n = 2 * (n * d) := by ac_rfl + simp only [loopSteps, finishSteps, Nat.zero_mul, Nat.zero_add, hdouble] + omega + | succ count ih => + have hr : r < n := by omega + let rows := PreprocessingLazyWords.row table (⟨r, hr⟩ : Fin n) + have ho : output.length ≤ 20000 * (L + 1) ^ 2 := by + rw [List.length_append] at hout + omega + have hb := bodySteps_le rows r L output hr.le hn hm ho + have hs : outputBlocks table (remaining n r) = + vertexBlock d r rows ++ outputBlocks table (remaining n (r + 1)) := by + rw [remaining_cons n r hr] + rfl + have hout' : ((output ++ vertexBlock d r rows) ++ + outputBlocks table (remaining n (r + 1))).length ≤ 20000 * (L + 1) ^ 2 := by + simpa only [hs, List.append_assoc] using hout + have ht := ih (r + 1) (by omega) (output ++ vertexBlock d r rows) hout' + simp only [loopSteps, dite_eq_left hr] + change (1 + bodySteps d r rows output) + + loopSteps table (r + 1) count (output ++ vertexBlock d r rows) ≤ _ + nlinarith only [hb, ht] + +noncomputable def timePolynomial (d : Nat) : Polynomial Nat := + Polynomial.C (1000000 * (d + 1) ^ 3 + 100) * (Polynomial.X + 1) ^ 3 + +@[simp] theorem timePolynomial_eval (d L : Nat) : + (timePolynomial d).eval L = (1000000 * (d + 1) ^ 3 + 100) * (L + 1) ^ 3 := by + simp [timePolynomial] + +theorem totalSteps_le {n d : Nat} (table : PortTables.Table n d) : + totalSteps table ≤ (timePolynomial d).eval (PortTables.tableBits table).length := by + let L := (PortTables.tableBits table).length + let N := L + 1 + let C := 1000000 * (d + 1) ^ 3 + have hn : n ≤ L := PortTables.vertices_le_tableBits_length table + have hm : n * d ≤ L := GraphTables.darts_le_tableBits_length (PortTables.graphTable table) + have hout : (encodeWords [n, 2 * (n * d)] ++ + outputBlocks table (remaining n 0)).length ≤ 20000 * (L + 1) ^ 2 := by + rw [remaining_zero, ← output_table_codec] + exact output_length_le table + have hl := loopSteps_le table L n 0 (by omega) hn hm _ hout + have hp : prefixSteps n (n * d) (inputBlocks table (List.finRange n)) ≤ 10 * L + 17 := by + unfold prefixSteps + rw [← input_table_codec table] + change 2 * L + 5 * n + 3 * (n * d) + 17 ≤ _ + omega + have hN : 1 ≤ N := by dsimp [N]; omega + have hnN : n ≤ N := by dsimp [N]; omega + have hN2 : 1 ≤ N ^ 2 := by nlinarith only [hN] + have hN3 : N ≤ N ^ 3 := by + have h := Nat.mul_le_mul_left N hN2 + nlinarith only [h] + have hc := Nat.mul_le_mul_right (1 + C * N ^ 2) hnN + change loopSteps table 0 n (encodeWords [n, 2 * (n * d)]) ≤ n * (1 + C * N ^ 2) + 5 * L + 11 at hl + rw [timePolynomial_eval] + change totalSteps table ≤ (C + 100) * N ^ 3 + unfold totalSteps + have hLN : L + 1 = N := rfl + nlinarith only [hp, hl, hc, hN, hN3, hLN] + +def machine (d : Nat) (positive : 0 < d) : FinTM2 where + K := Tape + k₀ := .input + k₁ := .output + Γ _ := Bool + Λ := Label d + main := .split .copyFirst + σ := State d + initialState := clean d positive + m := program d positive + +theorem machine_alphabet_finite (d : Nat) (positive : 0 < d) : + ∀ k, Finite ((machine d positive).Γ k) := by + intro k + change Finite Bool + infer_instance + +theorem initial_configuration (d : Nat) (positive : 0 < d) (input : List Bool) : + initList (machine d positive) input = + ⟨some (.split .copyFirst), clean d positive, initialTapes input⟩ := by + have ht : (initList (machine d positive) input).stk = initialTapes input := by + funext t + cases t <;> simp [initList, machine, initialTapes, frame] + rfl + exact congrArg (TM2.Cfg.mk _ _) ht + +@[simp] theorem finalTapes_input (input output : List Bool) : finalTapes input output .input = input := rfl +@[simp] theorem finalTapes_output (input output : List Bool) : finalTapes input output .output = output := rfl + +theorem finalTapes_work_empty (input output : List Bool) (t : Tape) + (hi : t ≠ .input) (ho : t ≠ .output) : finalTapes input output t = [] := by + cases t <;> simp_all [finalTapes, frame] + +def machineInTime {n d : Nat} (table : PortTables.Table n d) (positive : 0 < d) : + StateTransition.EvalsToInTime (machine d positive).step + (initList (machine d positive) (PortTables.tableBits table)) + (some ⟨none, clean d positive, finalTapes (PortTables.tableBits table) + (PortTables.tableBits (PreprocessingOverlayTables.lazy table))⟩) + ((timePolynomial d).eval (PortTables.tableBits table).length) where + steps := totalSteps table + evals_in_steps := by + rw [initial_configuration] + exact tableTrace table positive + steps_le_m := totalSteps_le table + +end MinUncutGames.Foundations.Complexity.MachineLazyTable + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineLazyTableRuntime.lean b/lean/OAI/Computability/MinUncut/Machines/MachineLazyTableRuntime.lean new file mode 100644 index 0000000000000000000000000000000000000000..92d8fa1d5ff42cc567347b9f2f6157e459d4322f --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineLazyTableRuntime.lean @@ -0,0 +1,498 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineLazyTable + +namespace OAI + +section +namespace MinUncutGames.Foundations.Complexity.MachineLazyTableRuntime + +open Turing PCP +open MachineLazyTable (Tape Label State) + + +def rawProgram (d : Nat) (positive : 0 < d) : + MachineCanonicalOutput.Program Tape (Label d) (State d) where + input := .input + output := .output + main := .split .copyFirst + initial := MachineLazyTable.clean d positive + code := MachineLazyTable.program d positive + +theorem sourceMachine_eq (d : Nat) (positive : 0 < d) : + MachineCanonicalOutput.sourceMachine (rawProgram d positive) = + MachineLazyTable.machine d positive := rfl + +def cleanupTapes : List Tape := + [.input, .source, .vertices, .darts, .fuel, .vertex, .reverse, + .tail, .old, .relation, .scratch, .divided, .quotient, .newReverse, .rowBuffer] + +theorem cleanup_complete (d : Nat) (positive : 0 < d) (k : Tape) : + k ∈ cleanupTapes ↔ k ≠ (rawProgram d positive).output := by + cases k <;> simp [cleanupTapes, rawProgram] + +def terminalRun (d : Nat) (positive : 0 < d) (a : PortTables.Input d) : + MachineCanonicalOutput.TerminalRun (rawProgram d positive) (PortTables.inputBits a) + (PortTables.inputBits (PreprocessingStageMaps.lazy d a)) + ((MachineLazyTable.timePolynomial d).eval (PortTables.inputBits a).length) where + state := MachineLazyTable.clean d positive + tapes := MachineLazyTable.finalTapes (PortTables.inputBits a) + (PortTables.inputBits (PreprocessingStageMaps.lazy d a)) + execution := MachineLazyTable.machineInTime a.2 positive + output_eq := rfl + +noncomputable def computableInPolyTime (d : Nat) (positive : 0 < d) : + TM2ComputableInPolyTime (PortTables.inputBits (ports := d)) + (PortTables.inputBits (ports := 2 * d)) (PreprocessingStageMaps.lazy d) := + MachineCanonicalOutput.computableInPolyTime (rawProgram d positive) cleanupTapes + (cleanup_complete d positive) PortTables.inputBits PortTables.inputBits + (PreprocessingStageMaps.lazy d) (MachineLazyTable.timePolynomial d) (terminalRun d positive) + +theorem finite_alphabet (d : Nat) (positive : 0 < d) : + ∀ k, Finite ((computableInPolyTime d positive).tm.Γ k) := + MachineCanonicalOutput.computableInPolyTime_finite_alphabet (rawProgram d positive) cleanupTapes + (cleanup_complete d positive) PortTables.inputBits PortTables.inputBits + (PreprocessingStageMaps.lazy d) (MachineLazyTable.timePolynomial d) (terminalRun d positive) + +end MinUncutGames.Foundations.Complexity.MachineLazyTableRuntime + +end +section +namespace MinUncutGames.Foundations.PCP.PreprocessingFinishRuntime + +open Turing MinUncutGames.Foundations.Complexity +open PreprocessingRegularTables + +def finish (H : PreprocessingTables.BaseTable) (d : Nat) (input : PortTables.Input d) : + PortTables.Input (2 * (d + internalDegree)) := + PreprocessingStageMaps.lazy (d + internalDegree) + (PreprocessingStageMaps.paddedOverlay H d input) + +theorem output_eq_finish (H : PreprocessingTables.BaseTable) (t : GraphTables.Table) : + PreprocessingTables.output H t = + finish H (internalDegree + 1) (PreprocessingStageMaps.regular H t) := rfl + +theorem finish_degree_positive (d : Nat) (hd : 0 < d) : 0 < d + internalDegree := + hd.trans_le (Nat.le_add_right d internalDegree) + +noncomputable def computableInPolyTime (H : PreprocessingTables.BaseTable) + (d : Nat) (hd : 0 < d) : + TM2ComputableInPolyTime (PortTables.inputBits (ports := d)) + (PortTables.inputBits (ports := 2 * (d + internalDegree))) (finish H d) := by + change TM2ComputableInPolyTime _ _ + (fun input => PreprocessingStageMaps.lazy (d + internalDegree) + (PreprocessingStageMaps.paddedOverlay H d input)) + exact MachineSequential.composeBits (MachinePaddedOverlayRuntime.computableInPolyTime H d hd) + (MachineLazyTableRuntime.computableInPolyTime (d + internalDegree) + (finish_degree_positive d hd)) + +theorem finite_alphabet (H : PreprocessingTables.BaseTable) (d : Nat) (hd : 0 < d) : + MachineFiniteAlphabet.FiniteAlphabet (computableInPolyTime H d hd).tm := + MachineFiniteAlphabet.composeBits + (MachinePaddedOverlayRuntime.computableInPolyTime H d hd) + (MachineLazyTableRuntime.computableInPolyTime (d + internalDegree) + (finish_degree_positive d hd)) + (MachinePaddedOverlayRuntime.finite_alphabet H d hd) + (MachineLazyTableRuntime.finite_alphabet (d + internalDegree) + (finish_degree_positive d hd)) + +end MinUncutGames.Foundations.PCP.PreprocessingFinishRuntime + +end +section +namespace MinUncutGames.Foundations.PCP.PreprocessingRuntime +open Turing MinUncutGames.Foundations.Complexity +open PreprocessingRegularTables + +noncomputable def tablePolynomialTime (H : PreprocessingTables.BaseTable) : + TM2ComputableInPolyTime GraphTables.tableBits + (PortTables.inputBits (ports := PreprocessingTables.degree)) + (PreprocessingTables.output H) := by + change TM2ComputableInPolyTime GraphTables.tableBits + (PortTables.inputBits (ports := 2 * ((internalDegree + 1) + internalDegree))) + (fun t => PreprocessingFinishRuntime.finish H (internalDegree + 1) + (PreprocessingStageMaps.regular H t)) + exact MachineSequential.composeBits + (MachineRegularTableRuntime.computableInPolyTime H) + (PreprocessingFinishRuntime.computableInPolyTime H (internalDegree + 1) + (Nat.succ_pos internalDegree)) + +theorem finiteAlphabet (H : PreprocessingTables.BaseTable) : + MachineFiniteAlphabet.FiniteAlphabet (tablePolynomialTime H).tm := + MachineFiniteAlphabet.composeBits + (MachineRegularTableRuntime.computableInPolyTime H) + (PreprocessingFinishRuntime.computableInPolyTime H (internalDegree + 1) + (Nat.succ_pos internalDegree)) + (MachineRegularTableRuntime.finite_alphabet H) + (PreprocessingFinishRuntime.finite_alphabet H (internalDegree + 1) + (Nat.succ_pos internalDegree)) + +end MinUncutGames.Foundations.PCP.PreprocessingRuntime + +end +section +namespace MinUncutGames.Foundations.Complexity.MachineLogCounter + +open Turing + + +def bitLength (n : Nat) : Nat := if n = 0 then 0 else n.log2 + 1 + +@[simp] theorem bitLength_zero : bitLength 0 = 0 := rfl + +theorem bitLength_positive {n : Nat} (h : n ≠ 0) : bitLength n = n.log2 + 1 := by + simp [bitLength, h] + +theorem bitLength_half {n : Nat} (h : n ≠ 0) : bitLength n = bitLength (n / 2) + 1 := by + by_cases hone : n = 1 + · subst n; rfl + have hn : 2 ≤ n := by omega + have hh : n / 2 ≠ 0 := by omega + rw [bitLength_positive h, bitLength_positive hh, Nat.log2_def n, ite_eq_left hn] + +def increments (n : Nat) (started : Bool) : Nat := + if n = 0 then (if started then 0 else 1) else bitLength n + +@[simp] theorem increments_true (n : Nat) : increments n true = bitLength n := by + by_cases hn : n = 0 <;> simp [increments, hn] + +theorem increments_half {n : Nat} (h : n ≠ 0) (started : Bool) : + increments n started = increments (n / 2) true + 1 := by + rw [increments, ite_eq_right h, increments_true, bitLength_half h] + +theorem increments_false (n : Nat) : increments n false = n.log2 + 1 := by + by_cases hn : n = 0 + · subst n; rfl + · simp [increments, bitLength, hn] + +def coreTime (n : Nat) : Nat := + if h : n = 0 then 1 else n + n / 2 + 3 + coreTime (n / 2) +termination_by n +decreasing_by omega + +@[simp] theorem coreTime_zero : coreTime 0 = 1 := by rw [coreTime]; rfl + +theorem coreTime_positive {n : Nat} (h : n ≠ 0) : + coreTime n = n + n / 2 + 3 + coreTime (n / 2) := by + rw [coreTime, dite_eq_right h] + +theorem coreTime_bound (n : Nat) : coreTime n ≤ 6 * n + 1 := by + induction n using Nat.strong_induction_on with + | h n ih => + by_cases hn : n = 0 + · subst n; simp + · rw [coreTime_positive hn] + have smaller : n / 2 < n := by omega + have bound := ih (n / 2) smaller + omega + +abbrev Alphabet (_ : Fin 3) := Bool +abbrev State := (Bool × Bool) × Option Bool + +def initialState : State := ((false, false), none) + +def rawTapes (input scratch output : List Bool) : Fin 3 → List Bool + | 0 => input + | 1 => scratch + | 2 => output + +theorem update_input (input scratch output replacement : List Bool) : + Function.update (rawTapes input scratch output) 0 replacement = rawTapes replacement scratch output := by + funext k + fin_cases k <;> rfl + +theorem update_scratch (input scratch output replacement : List Bool) : + Function.update (rawTapes input scratch output) 1 replacement = rawTapes input replacement output := by + funext k + fin_cases k <;> rfl + +theorem update_output (input scratch output replacement : List Bool) : + Function.update (rawTapes input scratch output) 2 replacement = rawTapes input scratch replacement := by + funext k + fin_cases k <;> rfl + +def stripLoop : TM2.Stmt Alphabet (Fin 5) State := + .pop 0 (fun state head => (state.1, head)) + (.branch (fun state => state.2.getD false) + (.push 1 (fun _ => true) (.goto fun _ => (1 : Fin 5))) + (.load (fun _ => initialState) (.goto fun _ => 4))) + +def guardLoop : TM2.Stmt Alphabet (Fin 5) State := + .peek 0 (fun state head => (state.1, head)) + (.branch (fun state => state.2.isSome) + (.push 2 (fun _ => true) + (.load (fun _ => ((false, true), none)) (.goto fun _ => 3))) + (.branch (fun state => state.1.2) + (.load (fun _ => initialState) .halt) + (.push 2 (fun _ => true) (.load (fun _ => initialState) .halt)))) + +def halfLoop : TM2.Stmt Alphabet (Fin 5) State := + .pop 0 (fun state head => (state.1, head)) + (.branch (fun state => state.2.isSome) + (.branch (fun state => state.1.1) + (.push 1 (fun _ => true) + (.load (fun state => ((false, state.1.2), state.2)) (.goto fun _ => 3))) + (.load (fun state => ((true, state.1.2), state.2)) (.goto fun _ => 3))) + (.load (fun state => ((false, state.1.2), none)) (.goto fun _ => 4))) + +def program : Fin 5 → TM2.Stmt Alphabet (Fin 5) State + | 0 => .push 2 (fun _ => false) (.goto fun _ => 1) + | 1 => stripLoop + | 2 => guardLoop + | 3 => halfLoop + | 4 => Reduction.MachineTransfer.loopAt 1 0 id false 4 (some 2) + +def machine : FinTM2 where + K := Fin 3 + k₀ := 0 + k₁ := 2 + Γ := Alphabet + Λ := Fin 5 + main := 0 + σ := State + initialState := initialState + m := program + +def configuration (label : Option (Fin 5)) (state : State) + (input scratch output : List Bool) : machine.Cfg := + ⟨label, state, rawTapes input scratch output⟩ + +def next := MachineComposition.advance machine.step + +theorem stripStep_true (input scratch output : List Bool) (state : State) : + machine.step (configuration (some 1) state (true :: input) scratch output) = + some (configuration (some 1) (state.1, some true) input (true :: scratch) output) := by + change some (TM2.stepAux stripLoop state (rawTapes (true :: input) scratch output)) = _ + simp [stripLoop, TM2.stepAux, rawTapes, configuration] + rw [update_input, update_scratch] + rfl + +theorem stripStep_false (scratch output : List Bool) (state : State) : + machine.step (configuration (some 1) state [false] scratch output) = + some (configuration (some 4) initialState [] scratch output) := by + change some (TM2.stepAux stripLoop state (rawTapes [false] scratch output)) = _ + simp [stripLoop, TM2.stepAux, rawTapes, configuration] + rw [update_input] + rfl + +theorem stripTrace (n : Nat) (scratch output : List Bool) (state : State) : + next^[n + 1] (some (configuration (some 1) state (encodeWord n) scratch output)) = + some (configuration (some 4) initialState [] (List.replicate n true ++ scratch) output) := by + induction n generalizing scratch state with + | zero => + simpa only [encodeWord, List.replicate_zero, List.nil_append, Nat.zero_add, + Function.iterate_one, next, MachineComposition.advance_some] using + stripStep_false scratch output state + | succ n ih => + rw [Function.iterate_succ_apply] + change next^[n + 1] + (machine.step (configuration (some 1) state (true :: encodeWord n) scratch output)) = _ + rw [stripStep_true, ih] + congr 2 + simp only [List.replicate_add, List.replicate_one, List.append_assoc, List.singleton_append] + +theorem halfStep_nil (scratch output : List Bool) (parity started : Bool) (register : Option Bool) : + machine.step (configuration (some 3) ((parity, started), register) [] scratch output) = + some (configuration (some 4) ((false, started), none) [] scratch output) := by + change some (TM2.stepAux halfLoop ((parity, started), register) (rawTapes [] scratch output)) = _ + simp [halfLoop, TM2.stepAux, rawTapes, configuration] + rw [update_input] + rfl + +theorem halfStep_false (input scratch output : List Bool) (started : Bool) (register : Option Bool) : + machine.step (configuration (some 3) ((false, started), register) (true :: input) scratch output) = + some (configuration (some 3) ((true, started), some true) input scratch output) := by + change some (TM2.stepAux halfLoop ((false, started), register) + (rawTapes (true :: input) scratch output)) = _ + simp [halfLoop, TM2.stepAux, rawTapes, configuration] + rw [update_input] + rfl + +theorem halfStep_true (input scratch output : List Bool) (started : Bool) (register : Option Bool) : + machine.step (configuration (some 3) ((true, started), register) (true :: input) scratch output) = + some (configuration (some 3) ((false, started), some true) input (true :: scratch) output) := by + change some (TM2.stepAux halfLoop ((true, started), register) + (rawTapes (true :: input) scratch output)) = _ + simp [halfLoop, TM2.stepAux, rawTapes, configuration] + rw [update_input, update_scratch] + rfl + +theorem halfTrace (n m : Nat) (output : List Bool) (parity started : Bool) + (register : Option Bool) : + next^[n + 1] (some (configuration (some 3) ((parity, started), register) + (List.replicate n true) (List.replicate m true) output)) = + some (configuration (some 4) ((false, started), none) [] + (List.replicate (m + (n + if parity then 1 else 0) / 2) true) output) := by + induction n generalizing m parity register with + | zero => + cases parity <;> + simpa only [Nat.zero_add, Function.iterate_one, next, MachineComposition.advance_some, + List.replicate_zero, Bool.false_eq_true, ite_false, ite_true, Nat.zero_div, + Nat.add_zero, Nat.reduceDiv] using + halfStep_nil (List.replicate m true) output _ started register + | succ n ih => + rw [Function.iterate_succ_apply] + change next^[n + 1] + (machine.step (configuration (some 3) ((parity, started), register) + (true :: List.replicate n true) (List.replicate m true) output)) = _ + cases parity with + | false => + rw [halfStep_false, ih] + congr 2 + | true => + rw [halfStep_true] + change next^[n + 1] (some (configuration (some 3) ((false, started), some true) + (List.replicate n true) (List.replicate (m + 1) true) output)) = _ + rw [ih] + congr 2 + congr 1 + change m + 1 + n / 2 = m + (n + 1 + 1) / 2 + omega + +theorem restoreTrace (n : Nat) (output : List Bool) (started : Bool) : + next^[n + 1] (some (configuration (some 4) ((false, started), none) + [] (List.replicate n true) output)) = + some (configuration (some 2) ((false, started), none) (List.replicate n true) [] output) := by + have run := Reduction.MachineTransfer.transferAt_fromTapes (1 : Fin 3) 0 (by decide) + id false (4 : Fin 5) (some 2) program rfl + (rawTapes [] (List.replicate n true) output) (false, started) none + simp only [rawTapes, List.length_replicate, List.reverse_replicate, List.map_id, + List.append_nil] at run + have tapesEq : Reduction.MachineTransfer.tapesAt (1 : Fin 3) 0 + (rawTapes [] (List.replicate n true) output) [] (List.replicate n true) = + rawTapes (List.replicate n true) [] output := by + funext k + fin_cases k <;> rfl + rw [tapesEq] at run + exact run + +theorem guardStep_zero (output : List Bool) (started : Bool) : + machine.step (configuration (some 2) ((false, started), none) [] [] output) = + some (configuration none initialState [] [] (if started then output else true :: output)) := by + change some (TM2.stepAux guardLoop ((false, started), none) (rawTapes [] [] output)) = _ + cases started <;> simp [guardLoop, TM2.stepAux, rawTapes, configuration] + rw [update_output] + all_goals rfl + +theorem guardStep_positive (n : Nat) (output : List Bool) (started : Bool) : + machine.step (configuration (some 2) ((false, started), none) + (List.replicate (n + 1) true) [] output) = + some (configuration (some 3) ((false, true), none) + (List.replicate (n + 1) true) [] (true :: output)) := by + change some (TM2.stepAux guardLoop ((false, started), none) + (rawTapes (true :: List.replicate n true) [] output)) = _ + simp [guardLoop, TM2.stepAux, rawTapes, configuration] + rw [update_output] + simp only [List.replicate_succ] + rfl + +theorem coreTrace (n : Nat) (output : List Bool) (started : Bool) : + next^[coreTime n] (some (configuration (some 2) ((false, started), none) + (List.replicate n true) [] output)) = + some (configuration none initialState [] [] + (List.replicate (increments n started) true ++ output)) := by + induction n using Nat.strong_induction_on generalizing output started with + | h n ih => + cases n with + | zero => + cases started with + | false => simpa [increments, next] using! guardStep_zero output false + | true => simpa [increments, next] using! guardStep_zero output true + | succ n => + have nonzero : n + 1 ≠ 0 := by omega + have smaller : (n + 1) / 2 < n + 1 := by omega + have recursive := ih ((n + 1) / 2) smaller (true :: output) true + have half := halfTrace (n + 1) 0 (true :: output) false true none + simp only [Bool.false_eq_true, ↓reduceIte, Nat.add_zero, Nat.zero_add, + List.replicate_zero] at half + have restore := restoreTrace ((n + 1) / 2) (true :: output) true + rw [coreTime_positive nonzero] + rw [show n + 1 + (n + 1) / 2 + 3 + coreTime ((n + 1) / 2) = + (coreTime ((n + 1) / 2) + ((n + 1) / 2 + 1) + (n + 1 + 1)) + 1 by omega, + Function.iterate_succ_apply] + change next^[coreTime ((n + 1) / 2) + ((n + 1) / 2 + 1) + (n + 1 + 1)] + (machine.step (configuration (some 2) ((false, started), none) + (List.replicate (n + 1) true) [] output)) = _ + rw [guardStep_positive, Function.iterate_add_apply, half, + Function.iterate_add_apply, restore, recursive] + rw [increments_half nonzero started] + simp only [List.replicate_add, List.replicate_one, List.append_assoc, List.singleton_append] + +theorem initList_eq (input : List Bool) : + initList machine input = configuration (some 0) initialState input [] [] := by + unfold initList configuration + congr 1 + funext k + change Fin 3 at k + fin_cases k <;> rfl + +theorem haltList_eq (output : List Bool) : + haltList machine output = configuration none initialState [] [] output := by + unfold haltList configuration + congr 1 + funext k + change Fin 3 at k + fin_cases k <;> rfl + +theorem initialStep (input : List Bool) : + machine.step (configuration (some 0) initialState input [] []) = + some (configuration (some 1) initialState input [] [false]) := by + change some (TM2.stepAux (.push (2 : Fin 3) (fun _ : State => false) (.goto fun _ => (1 : Fin 5))) + initialState (rawTapes input [] [])) = _ + simp only [TM2.stepAux, rawTapes] + rw [update_output] + rfl + +def totalTime (n : Nat) : Nat := 2 * n + 3 + coreTime n + +theorem totalTime_bound (n : Nat) : totalTime n ≤ 8 * n + 4 := by + have bound := coreTime_bound n + unfold totalTime + omega + +theorem machineTrace (n : Nat) : + next^[totalTime n] (some (initList machine (encodeWord n))) = + some (haltList machine (encodeWord (n.log2 + 1))) := by + rw [initList_eq, haltList_eq] + rw [show totalTime n = (coreTime n + (n + 1) + (n + 1)) + 1 by + unfold totalTime; omega, Function.iterate_succ_apply] + change next^[coreTime n + (n + 1) + (n + 1)] + (machine.step (configuration (some 0) initialState (encodeWord n) [] [])) = _ + rw [initialStep, Function.iterate_add_apply, stripTrace] + simp only [List.append_nil] + rw [Function.iterate_add_apply] + dsimp only [initialState] + rw [restoreTrace n [false] false, coreTrace, increments_false] + rfl + +def outputsInTime (n : Nat) : + TM2OutputsInTime machine (encodeWord n) (some (encodeWord (n.log2 + 1))) (8 * n + 4) where + steps := totalTime n + evals_in_steps := machineTrace n + steps_le_m := totalTime_bound n + +noncomputable def computableInPolyTime : + TM2ComputableInPolyTime encodeWord encodeWord (fun n => n.log2 + 1) where + tm := machine + inputAlphabet := Equiv.refl Bool + outputAlphabet := Equiv.refl Bool + time := 8 * Polynomial.X + 4 + outputsFun n := by + change TM2OutputsInTime machine ((encodeWord n).map id) + (some ((encodeWord (n.log2 + 1)).map id)) + ((8 * Polynomial.X + 4 : Polynomial Nat).eval (encodeWord n).length) + have hi := @List.map_id (machine.Γ machine.k₀) (encodeWord n) + have ho := @List.map_id (machine.Γ machine.k₁) (encodeWord (n.log2 + 1)) + rw [hi, ho] + have execution := outputsInTime n + refine { + toEvalsTo := execution.toEvalsTo + steps_le_m := Nat.le_trans execution.steps_le_m ?_ + } + simp only [Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_ofNat, Polynomial.eval_X] + simp [encodeWord] + +end MinUncutGames.Foundations.Complexity.MachineLogCounter + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineLookup.lean b/lean/OAI/Computability/MinUncut/Machines/MachineLookup.lean new file mode 100644 index 0000000000000000000000000000000000000000..deb8bf3ab3f493504020f3383e75d5df741dbeec --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineLookup.lean @@ -0,0 +1,1214 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.Input + +namespace OAI + +section +namespace MinUncutGames.Foundations.Complexity.MachineLookup + +open Turing +open MachineComposition + +variable {K σ : Type} [DecidableEq K] + +theorem guard_step_succ (index source destination : K) + (his : index ≠ source) (hid : index ≠ destination) + (base : K → List Bool) (i : Nat) (indexSuffix input output : List Bool) + (ambient : σ) (register : Option Bool) : + TM2.step (program index source destination) + ⟨some .guard, (ambient, register), tapes index source destination base + (encodeWord (i + 1) ++ indexSuffix) input output⟩ = + some ⟨some .skip, (ambient, none), tapes index source destination base + (encodeWord i ++ indexSuffix) input output⟩ := by + change some (TM2.stepAux (program index source destination .guard) _ _) = _ + simp [program, MachineUnaryCounter.guard, TM2.stepAux, + tapes_index, his, hid, encodeWord, List.replicate_succ, update_index] + +theorem guard_step_zero (index source destination : K) + (his : index ≠ source) (hid : index ≠ destination) + (base : K → List Bool) (indexSuffix input output : List Bool) + (ambient : σ) (register : Option Bool) : + TM2.step (program index source destination) + ⟨some .guard, (ambient, register), tapes index source destination base + (encodeWord 0 ++ indexSuffix) input output⟩ = + some ⟨some .select, (ambient, none), tapes index source destination base + (encodeWord 0 ++ indexSuffix) input output⟩ := by + change some (TM2.stepAux (program index source destination .guard) _ _) = _ + simp [program, MachineUnaryCounter.guard, TM2.stepAux, + tapes_index, his, hid, encodeWord] + +theorem select_step_nonempty (index source destination : K) + (hsd : source ≠ destination) (base : K → List Bool) + (counter input output : List Bool) (hinput : input ≠ []) + (ambient : σ) (register : Option Bool) : + TM2.step (program index source destination) + ⟨some .select, (ambient, register), + tapes index source destination base counter input output⟩ = + some ⟨some .copy, (ambient, input.head?), + tapes index source destination base counter input (false :: output)⟩ := by + change some (TM2.stepAux (program index source destination .select) _ _) = _ + cases input with + | nil => exact (hinput rfl).elim + | cons head tail => + simp [program, select, Hastad.SourceMachine.fieldStart, TM2.stepAux, + tapes_source, hsd, update_destination] + +theorem select_step_empty (index source destination : K) + (hsd : source ≠ destination) (base : K → List Bool) + (counter output : List Bool) (ambient : σ) (register : Option Bool) : + TM2.step (program index source destination) + ⟨some .select, (ambient, register), + tapes index source destination base counter [] output⟩ = + some ⟨some .rejected, (ambient, none), + tapes index source destination base counter [] output⟩ := by + change some (TM2.stepAux (program index source destination .select) _ _) = _ + simp [program, select, TM2.stepAux, tapes_source, hsd] + +theorem copyTrace (index source destination : K) + (hsd : source ≠ destination) (base : K → List Bool) + (counter : List Bool) (n : Nat) (suffix output : List Bool) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step (program index source destination)))^[n + 1] + (some ⟨some .copy, (ambient, register), tapes index source destination base + counter (encodeWord n ++ suffix) (false :: output)⟩) = + some ⟨some .accepted, (ambient, none), tapes index source destination base + counter suffix (encodeWord n ++ output)⟩ := by + have h := Hastad.SourceMachine.fieldLoopTrace source destination hsd + Label.copy (some Label.accepted) (program index source destination) rfl + (Function.update base index counter) n suffix (false :: output) ambient register + simpa only [Hastad.SourceMachine.fieldTapes, tapes, encodeWord, + List.append_assoc, List.singleton_append] using h + +theorem selectTrace (index source destination : K) + (hsd : source ≠ destination) (base : K → List Bool) + (counter : List Bool) (n : Nat) (suffix output : List Bool) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step (program index source destination)))^[n + 2] + (some ⟨some .select, (ambient, register), tapes index source destination base + counter (encodeWord n ++ suffix) output⟩) = + some ⟨some .accepted, (ambient, none), tapes index source destination base + counter suffix (encodeWord n ++ output)⟩ := by + rw [show n + 2 = (n + 1) + 1 by omega, Function.iterate_succ_apply] + simp only [advance_some] + rw [select_step_nonempty index source destination hsd base counter + (encodeWord n ++ suffix) output (by simp [encodeWord]) ambient register] + exact copyTrace index source destination hsd base counter n suffix output ambient _ + +theorem skipCycleTrace (index source destination : K) + (his : index ≠ source) (hid : index ≠ destination) (hsd : source ≠ destination) + (base : K → List Bool) (i n : Nat) (indexSuffix suffix output : List Bool) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step (program index source destination)))^[n + 2] + (some ⟨some .guard, (ambient, register), tapes index source destination base + (encodeWord (i + 1) ++ indexSuffix) (encodeWord n ++ suffix) output⟩) = + some ⟨some .guard, (ambient, none), tapes index source destination base + (encodeWord i ++ indexSuffix) suffix output⟩ := by + rw [show n + 2 = (n + 1) + 1 by omega, Function.iterate_succ_apply] + simp only [advance_some] + rw [guard_step_succ index source destination his hid] + have h := discardTrace source Label.skip Label.guard + (program index source destination) rfl + (tapes index source destination base (encodeWord i ++ indexSuffix) + (encodeWord n ++ suffix) output) n suffix (by simp [hsd]) ambient none + simpa only [update_source index source destination hsd] using h + +theorem emptyCycleTrace (index source destination : K) + (his : index ≠ source) (hid : index ≠ destination) (hsd : source ≠ destination) + (base : K → List Bool) (i : Nat) (indexSuffix output : List Bool) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step (program index source destination)))^[2] + (some ⟨some .guard, (ambient, register), tapes index source destination base + (encodeWord (i + 1) ++ indexSuffix) [] output⟩) = + some ⟨some .guard, (ambient, none), tapes index source destination base + (encodeWord i ++ indexSuffix) [] output⟩ := by + rw [show 2 = 1 + 1 from rfl, Function.iterate_succ_apply] + simp only [Function.iterate_one, advance_some] + rw [guard_step_succ index source destination his hid] + exact discard_empty_step source Label.skip Label.guard (program index source destination) + rfl (tapes index source destination base (encodeWord i ++ indexSuffix) [] output) + (by simp [hsd]) ambient none + +theorem successPrefixTrace (index source destination : K) + (his : index ≠ source) (hid : index ≠ destination) (hsd : source ≠ destination) + (base : K → List Bool) (prior : List Nat) (value : Nat) + (indexSuffix suffix output : List Bool) (ambient : σ) (register : Option Bool) : + (advance (TM2.step (program index source destination)))^[ + (encodeWords prior).length + prior.length + value + 3] + (some ⟨some .guard, (ambient, register), tapes index source destination base + (encodeWord prior.length ++ indexSuffix) + (encodeWords prior ++ (encodeWord value ++ suffix)) output⟩) = + some ⟨some .accepted, (ambient, none), tapes index source destination base + (encodeWord 0 ++ indexSuffix) suffix (encodeWord value ++ output)⟩ := by + induction prior generalizing register with + | nil => + simp only [encodeWords, List.length_nil, Nat.zero_add, List.nil_append] + rw [show value + 3 = (value + 2) + 1 by omega, Function.iterate_succ_apply] + simp only [advance_some] + rw [guard_step_zero index source destination his hid] + exact selectTrace index source destination hsd base _ value suffix output ambient none + | cons n prior ih => + simp only [encodeWords, List.length_cons, List.length_append, encodeWord_length] + rw [show n + 1 + (encodeWords prior).length + (prior.length + 1) + value + 3 = + ((encodeWords prior).length + prior.length + value + 3) + (n + 2) by omega, + Function.iterate_add_apply] + rw [List.append_assoc, + skipCycleTrace index source destination his hid hsd base prior.length n] + exact ih none + +theorem lookupTrace_some (index source destination : K) + (his : index ≠ source) (hid : index ≠ destination) (hsd : source ≠ destination) + (base : K → List Bool) (values : List Nat) (i value : Nat) + (selected : values[i]? = some value) + (indexSuffix suffix output : List Bool) (ambient : σ) (register : Option Bool) : + (advance (TM2.step (program index source destination)))^[MachineLookupSpec.steps values i] + (some ⟨some .guard, (ambient, register), tapes index source destination base + (encodeWord i ++ indexSuffix) (encodeWords values ++ suffix) output⟩) = + some ⟨some .accepted, (ambient, none), tapes index source destination base + (encodeWord 0 ++ indexSuffix) (encodeWords (values.drop (i + 1)) ++ suffix) + (encodeWord value ++ output)⟩ := by + have hi := (List.getElem?_eq_some_iff.mp selected).1 + have hlength : (values.take i).length = i := by + simp [List.length_take, Nat.min_eq_left (Nat.le_of_lt hi)] + have hsource : encodeWords (values.take i) ++ + (encodeWord value ++ (encodeWords (values.drop (i + 1)) ++ suffix)) = + encodeWords values ++ suffix := by + rw [MachineLookupSpec.encoded_selected_split values i value selected] + simp only [List.append_assoc] + have htime : MachineLookupSpec.steps values i = + (encodeWords (values.take i)).length + i + value + 3 := by + rw [MachineLookupSpec.steps_eq_scannedBits_of_some values i value selected, + MachineLookupSpec.scannedBits_of_some values i value selected] + omega + have h := successPrefixTrace index source destination his hid hsd base (values.take i) + value indexSuffix (encodeWords (values.drop (i + 1)) ++ suffix) output ambient register + rw [hlength, hsource] at h + simpa only [htime] using h + +theorem emptyTrace (index source destination : K) + (his : index ≠ source) (hid : index ≠ destination) (hsd : source ≠ destination) + (base : K → List Bool) (i : Nat) (indexSuffix output : List Bool) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step (program index source destination)))^[2 * i + 2] + (some ⟨some .guard, (ambient, register), tapes index source destination base + (encodeWord i ++ indexSuffix) [] output⟩) = + some ⟨some .rejected, (ambient, none), tapes index source destination base + (encodeWord 0 ++ indexSuffix) [] output⟩ := by + induction i generalizing register with + | zero => + simp only [Nat.mul_zero, Nat.zero_add] + rw [show 2 = 1 + 1 from rfl, Function.iterate_succ_apply] + simp only [Function.iterate_one, advance_some] + rw [guard_step_zero index source destination his hid] + exact select_step_empty index source destination hsd base _ output ambient none + | succ i ih => + rw [show 2 * (i + 1) + 2 = (2 * i + 2) + 2 by omega, + Function.iterate_add_apply, emptyCycleTrace index source destination his hid hsd] + exact ih none + +theorem lookupTrace_invalid (index source destination : K) + (his : index ≠ source) (hid : index ≠ destination) (hsd : source ≠ destination) + (base : K → List Bool) (values : List Nat) (i : Nat) (invalid : values.length ≤ i) + (indexSuffix output : List Bool) (ambient : σ) (register : Option Bool) : + (advance (TM2.step (program index source destination)))^[MachineLookupSpec.steps values i] + (some ⟨some .guard, (ambient, register), tapes index source destination base + (encodeWord i ++ indexSuffix) (encodeWords values) output⟩) = + some ⟨some .rejected, (ambient, none), tapes index source destination base + (encodeWord 0 ++ indexSuffix) [] output⟩ := by + induction values generalizing i register with + | nil => + simpa only [MachineLookupSpec.steps, encodeWords] using + emptyTrace index source destination his hid hsd base i indexSuffix output ambient register + | cons n values ih => + cases i with + | zero => simp at invalid + | succ i => + simp only [MachineLookupSpec.steps, encodeWords] + rw [Nat.add_comm (n + 2), Function.iterate_add_apply, + skipCycleTrace index source destination his hid hsd] + exact ih i (by simpa using invalid) none + +def resultLabel (values : List Nat) (i : Nat) : Label := + match values[i]? with + | some _ => .accepted + | none => .rejected + +def resultOutput (values : List Nat) (i : Nat) (output : List Bool) : List Bool := + match values[i]? with + | some value => encodeWord value ++ output + | none => output + +theorem lookupTrace (index source destination : K) + (his : index ≠ source) (hid : index ≠ destination) (hsd : source ≠ destination) + (base : K → List Bool) (values : List Nat) (i : Nat) + (indexSuffix output : List Bool) (ambient : σ) (register : Option Bool) : + (advance (TM2.step (program index source destination)))^[MachineLookupSpec.steps values i] + (some ⟨some .guard, (ambient, register), tapes index source destination base + (encodeWord i ++ indexSuffix) (encodeWords values) output⟩) = + some ⟨some (resultLabel values i), (ambient, none), tapes index source destination base + (encodeWord 0 ++ indexSuffix) (encodeWords (values.drop (i + 1))) + (resultOutput values i output)⟩ := by + cases selected : values[i]? with + | some value => + simpa only [List.append_nil, resultLabel, resultOutput, selected] using + lookupTrace_some index source destination his hid hsd base values i value selected + indexSuffix [] output ambient register + | none => + have invalid : values.length ≤ i := List.getElem?_eq_none_iff.mp selected + have hdrop : values.drop (i + 1) = [] := List.drop_eq_nil_of_le (by omega) + simpa only [resultLabel, resultOutput, selected, hdrop, encodeWords] using + lookupTrace_invalid index source destination his hid hsd base values i invalid + indexSuffix output ambient register + +def lookupInTime (index source destination : K) + (his : index ≠ source) (hid : index ≠ destination) (hsd : source ≠ destination) + (base : K → List Bool) (values : List Nat) (i : Nat) + (indexSuffix output : List Bool) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step (program index source destination)) + ⟨some .guard, (ambient, register), tapes index source destination base + (encodeWord i ++ indexSuffix) (encodeWords values) output⟩ + (some ⟨some (resultLabel values i), (ambient, none), tapes index source destination base + (encodeWord 0 ++ indexSuffix) (encodeWords (values.drop (i + 1))) + (resultOutput values i output)⟩) + ((encodeWords values).length + 2 * (encodeWord i).length) where + steps := MachineLookupSpec.steps values i + evals_in_steps := lookupTrace index source destination his hid hsd base values i + indexSuffix output ambient register + steps_le_m := MachineLookupSpec.steps_le_input_encoding_size values i + +theorem lookupHaltTrace (index source destination : K) + (his : index ≠ source) (hid : index ≠ destination) (hsd : source ≠ destination) + (base : K → List Bool) (values : List Nat) (i : Nat) + (indexSuffix output : List Bool) (ambient : σ) (register : Option Bool) : + (advance (TM2.step (program index source destination)))^[MachineLookupSpec.steps values i + 1] + (some ⟨some .guard, (ambient, register), tapes index source destination base + (encodeWord i ++ indexSuffix) (encodeWords values) output⟩) = + some ⟨none, (ambient, none), tapes index source destination base + (encodeWord 0 ++ indexSuffix) (encodeWords (values.drop (i + 1))) + (resultOutput values i output)⟩ := by + rw [Function.iterate_succ_apply', lookupTrace index source destination his hid hsd] + simp only [advance_some] + cases selected : values[i]? <;> simp [resultLabel, selected, TM2.step, program, TM2.stepAux] + +noncomputable def timePolynomial : Polynomial Nat := Polynomial.C 2 * Polynomial.X + 1 + +theorem timePolynomial_bounds (values : List Nat) (i : Nat) : + MachineLookupSpec.steps values i + 1 ≤ + timePolynomial.eval ((encodeWords values).length + (encodeWord i).length) := by + have h := MachineLookupSpec.steps_le_input_encoding_size values i + simp only [timePolynomial, Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_C, + Polynomial.eval_X, Polynomial.eval_one] + omega + +def machineInTime (base : Fin 3 → List Bool) (values : List Nat) (i : Nat) + (indexSuffix output : List Bool) (register : Option Bool) : + StateTransition.EvalsToInTime machine.step + ⟨some .guard, ((), register), tapes (K := Fin 3) 0 1 2 base + (encodeWord i ++ indexSuffix) (encodeWords values) output⟩ + (some ⟨none, ((), none), tapes (K := Fin 3) 0 1 2 base + (encodeWord 0 ++ indexSuffix) (encodeWords (values.drop (i + 1))) + (resultOutput values i output)⟩) + (timePolynomial.eval ((encodeWords values).length + (encodeWord i).length)) where + steps := MachineLookupSpec.steps values i + 1 + evals_in_steps := lookupHaltTrace (0 : Fin 3) 1 2 (by decide) (by decide) (by decide) + base values i indexSuffix output () register + steps_le_m := timePolynomial_bounds values i + +end MinUncutGames.Foundations.Complexity.MachineLookup + +end +section +namespace MinUncutGames.Foundations.Complexity.MachineFixedBlockMap + +open Turing + +abbrev Buffer (N : Nat) := Fin N → Bool + +def emptyBuffer (N : Nat) : Buffer N := fun _ => false + +section Chains + +variable {K Λ σ : Type} {N : Nat} + +def readSlots (src : K) : List (Fin N) → + TM2.Stmt (fun _ : K => Bool) Λ (σ × Buffer N) → + TM2.Stmt (fun _ : K => Bool) Λ (σ × Buffer N) + | [], next => next + | i :: slots, next => + .pop src (fun state head => + (state.1, Function.update state.2 i (head.getD false))) + (readSlots src slots next) + +def fill (slots : List (Fin N)) (bits buffer : Buffer N) : Buffer N := + slots.foldl (fun buffer i => Function.update buffer i (bits i)) buffer + +theorem fill_apply (slots : List (Fin N)) (bits buffer : Buffer N) (i : Fin N) : + fill slots bits buffer i = if i ∈ slots then bits i else buffer i := by + induction slots generalizing buffer with + | nil => simp [fill] + | cons j slots ih => + change fill slots bits (Function.update buffer j (bits j)) i = _ + rw [ih] + by_cases hm : i ∈ slots + · simp [hm] + · by_cases he : i = j <;> simp [hm, he] + +@[simp] theorem fill_all (bits buffer : Buffer N) : + fill (List.ofFn id) bits buffer = bits := by + funext i + simp [fill_apply, List.mem_ofFn] + +variable [DecidableEq K] + +theorem stepAux_readSlots (src : K) (slots : List (Fin N)) + (next : TM2.Stmt (fun _ : K => Bool) Λ (σ × Buffer N)) + (ambient : σ) (bits buffer : Buffer N) (tapes : K → List Bool) + (suffix : List Bool) : + TM2.stepAux (readSlots src slots next) (ambient, buffer) + (Function.update tapes src (slots.map bits ++ suffix)) = + TM2.stepAux next (ambient, fill slots bits buffer) + (Function.update tapes src suffix) := by + induction slots generalizing buffer tapes with + | nil => simp [readSlots, fill] + | cons i slots ih => + simpa only [readSlots, List.map_cons, List.cons_append, TM2.stepAux, + Function.update_self, List.head?_cons, Option.getD_some, List.tail_cons, + Function.update_idem, fill, List.foldl_cons] using + ih (Function.update buffer i (bits i)) tapes + +theorem stepAux_readAll (src : K) + (next : TM2.Stmt (fun _ : K => Bool) Λ (σ × Buffer N)) + (state : σ × Buffer N) (bits : Buffer N) (tapes : K → List Bool) + (suffix : List Bool) (hinput : tapes src = List.ofFn bits ++ suffix) : + TM2.stepAux (readSlots src (List.ofFn id) next) state tapes = + TM2.stepAux next (state.1, bits) (Function.update tapes src suffix) := by + have h := stepAux_readSlots src (List.ofFn id) next state.1 bits state.2 tapes suffix + have hin : Function.update tapes src ((List.ofFn id).map bits ++ suffix) = tapes := by + simpa only [List.map_ofFn, Function.comp_id, ← hinput] using + Function.update_eq_self src tapes + rw [hin, fill_all] at h + exact h + +omit [DecidableEq K] in +theorem statementPushBound_readSlots (src : K) (slots : List (Fin N)) + (next : TM2.Stmt (fun _ : K => Bool) Λ (σ × Buffer N)) : + Runtime.statementPushBound (readSlots src slots next) = + Runtime.statementPushBound next := by + induction slots with + | nil => rfl + | cons i slots ih => exact ih + +def writeSlots {M : Nat} (dst : K) (emit : σ → Buffer M) : List (Fin M) → + TM2.Stmt (fun _ : K => Bool) Λ σ → TM2.Stmt (fun _ : K => Bool) Λ σ + | [], next => next + | i :: slots, next => .push dst (fun state => emit state i) (writeSlots dst emit slots next) + +theorem stepAux_writeSlots {M : Nat} (dst : K) (emit : σ → Buffer M) + (slots : List (Fin M)) (next : TM2.Stmt (fun _ : K => Bool) Λ σ) + (state : σ) (tapes : K → List Bool) : + TM2.stepAux (writeSlots dst emit slots next) state tapes = + TM2.stepAux next state + (Function.update tapes dst ((slots.map (emit state)).reverse ++ tapes dst)) := by + induction slots generalizing tapes with + | nil => simp [writeSlots] + | cons i slots ih => + simp only [writeSlots, TM2.stepAux] + rw [ih] + simp only [Function.update_self, Function.update_idem, List.map_cons, + List.reverse_cons, List.append_assoc, List.singleton_append] + +omit [DecidableEq K] in +theorem statementPushBound_writeSlots {M : Nat} (dst : K) (emit : σ → Buffer M) + (slots : List (Fin M)) (next : TM2.Stmt (fun _ : K => Bool) Λ σ) : + Runtime.statementPushBound (writeSlots dst emit slots next) = + slots.length + Runtime.statementPushBound next := by + induction slots with + | nil => simp [writeSlots] + | cons i slots ih => + simp only [writeSlots, Runtime.statementPushBound, ih, List.length_cons] + omega + +end Chains + +section Block + +variable {K Λ σ : Type} {N M : Nat} + +def blockStmt (src dst : K) (F : Buffer N → Buffer M) + (next : TM2.Stmt (fun _ : K => Bool) Λ (σ × Buffer N)) : + TM2.Stmt (fun _ : K => Bool) Λ (σ × Buffer N) := + readSlots src (List.ofFn id) + (writeSlots dst (fun state => F state.2) (List.ofFn id).reverse + (.load (fun state => (state.1, emptyBuffer N)) next)) + +def finishAt (exit : Option Λ) : TM2.Stmt (fun _ : K => Bool) Λ σ := + match exit with + | none => .halt + | some label => .goto fun _ => label + +def blockMapAt (src dst : K) (F : Buffer N → Buffer M) (exit : Option Λ) : + TM2.Stmt (fun _ : K => Bool) Λ (σ × Buffer N) := + blockStmt src dst F (finishAt exit) + +theorem statementPushBound_blockStmt (src dst : K) (F : Buffer N → Buffer M) + (next : TM2.Stmt (fun _ : K => Bool) Λ (σ × Buffer N)) : + Runtime.statementPushBound (blockStmt src dst F next) = + M + Runtime.statementPushBound next := by + simp only [blockStmt, statementPushBound_readSlots, statementPushBound_writeSlots, + Runtime.statementPushBound, List.length_reverse, List.length_ofFn] + +theorem statementPushBound_blockMapAt (src dst : K) (F : Buffer N → Buffer M) + (exit : Option Λ) : + Runtime.statementPushBound (blockMapAt (σ := σ) src dst F exit) = M := by + cases exit <;> simp [blockMapAt, statementPushBound_blockStmt, finishAt, + Runtime.statementPushBound] + +variable [DecidableEq K] + +theorem stepAux_blockStmt (src dst : K) (F : Buffer N → Buffer M) + (next : TM2.Stmt (fun _ : K => Bool) Λ (σ × Buffer N)) + (hne : src ≠ dst) (bits : Buffer N) (suffix : List Bool) + (state : σ × Buffer N) (tapes : K → List Bool) + (hinput : tapes src = List.ofFn bits ++ suffix) : + TM2.stepAux (blockStmt src dst F next) state tapes = + TM2.stepAux next (state.1, emptyBuffer N) + (Function.update (Function.update tapes src suffix) dst + (List.ofFn (F bits) ++ tapes dst)) := by + unfold blockStmt + rw [stepAux_readAll src _ state bits tapes suffix hinput, stepAux_writeSlots] + simp only [List.map_reverse, List.map_ofFn, Function.comp_id, List.reverse_reverse, + Function.update_of_ne (Ne.symm hne), TM2.stepAux] + +theorem stepAux_blockMapAt (src dst : K) (F : Buffer N → Buffer M) + (exit : Option Λ) (hne : src ≠ dst) (bits : Buffer N) (suffix : List Bool) + (state : σ × Buffer N) (tapes : K → List Bool) + (hinput : tapes src = List.ofFn bits ++ suffix) : + TM2.stepAux (blockMapAt src dst F exit) state tapes = + { l := exit, var := (state.1, emptyBuffer N), + stk := Function.update (Function.update tapes src suffix) dst + (List.ofFn (F bits) ++ tapes dst) } := by + rw [blockMapAt, stepAux_blockStmt src dst F _ hne bits suffix state tapes hinput] + cases exit <;> rfl + +theorem step_blockMapAt (src dst : K) (F : Buffer N → Buffer M) + (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (σ × Buffer N)) + (label : Λ) (hprogram : program label = blockMapAt src dst F exit) + (hne : src ≠ dst) (bits : Buffer N) (suffix : List Bool) + (state : σ × Buffer N) (tapes : K → List Bool) + (hinput : tapes src = List.ofFn bits ++ suffix) : + TM2.step program { l := some label, var := state, stk := tapes } = + some { l := exit + var := (state.1, emptyBuffer N) + stk := Function.update (Function.update tapes src suffix) dst + (List.ofFn (F bits) ++ tapes dst) } := by + simp only [TM2.step, hprogram, + stepAux_blockMapAt src dst F exit hne bits suffix state tapes hinput] + +end Block + +def machine {N M : Nat} (F : Buffer N → Buffer M) : FinTM2 where + K := Bool + k₀ := false + k₁ := true + Γ _ := Bool + Λ := Unit + main := () + σ := Unit × Buffer N + initialState := ((), emptyBuffer N) + m _ := blockMapAt false true F none + +theorem machine_statementPushBound {N M : Nat} (F : Buffer N → Buffer M) : + Runtime.statementPushBound ((machine F).m ()) = M := + statementPushBound_blockMapAt false true F none + +end MinUncutGames.Foundations.Complexity.MachineFixedBlockMap + +end +section +namespace MinUncutGames.Foundations.PCP.AlphabetTable.Lookup + +open Turing +open MinUncutGames.Foundations.Complexity +open MachineComposition GenericGraphTables + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool + +def skipBits (source : K) : Nat → + TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) → + TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) + | 0, next => .load (fun state => (state.1, none)) next + | count + 1, next => + let rest := skipBits source count next + .pop source (fun state head => (state.1, head)) + (.branch (fun state => state.2.getD false) + (.pop source (fun state _ => (state.1, none)) rest) + (.load (fun state => (state.1, none)) rest)) + +theorem stepAux_skipBits (source : K) (bits : List Bool) + (next : TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (base : K → List Bool) (suffix : List Bool) (ambient : σ) (register : Option Bool) : + TM2.stepAux (skipBits source bits.length next) (ambient, register) + (Function.update base source (encodeWords (bits.map bitWord) ++ suffix)) = + TM2.stepAux next (ambient, none) (Function.update base source suffix) := by + induction bits generalizing register with + | nil => simp [skipBits, encodeWords, TM2.stepAux] + | cons bit bits ih => + cases bit <;> + simpa only [List.length_cons, skipBits, List.map_cons, bitWord, Bool.false_eq_true, + ite_false, ite_true, encodeWords, encodeWord, List.replicate_zero, + List.replicate_succ, List.nil_append, List.cons_append, List.singleton_append, + TM2.stepAux, Function.update_self, List.head?_cons, List.tail_cons, + Option.getD_some, Bool.cond_false, Bool.cond_true, Function.update_idem] using + ih none + +theorem stepAux_skipBits_fromTapes (source : K) (bits : List Bool) + (next : TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (base : K → List Bool) (suffix : List Bool) + (hinput : base source = encodeWords (bits.map bitWord) ++ suffix) + (ambient : σ) (register : Option Bool) : + TM2.stepAux (skipBits source bits.length next) (ambient, register) base = + TM2.stepAux next (ambient, none) (Function.update base source suffix) := by + have h := stepAux_skipBits source bits next base suffix ambient register + have hbase : Function.update base source (encodeWords (bits.map bitWord) ++ suffix) = + base := by rw [← hinput]; exact Function.update_eq_self source base + rw [hbase] at h + exact h + +omit [DecidableEq K] in +theorem skipBits_pushBound (source : K) (count : Nat) + (next : TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) : + Runtime.statementPushBound (skipBits source count next) = + Runtime.statementPushBound next := by + induction count with + | zero => rfl + | succ count ih => simp only [skipBits, Runtime.statementPushBound, ih, max_self] + +inductive Label + | guard | skipTail | skipReverse | skipPredicate | select | copy + deriving DecidableEq + +protected abbrev Label.enumList : List Label := [.guard, .skipTail, .skipReverse, .skipPredicate, + .select, .copy] + +protected theorem Label.enumList_getElem?_ctorIdx_eq (x : Label) : + Label.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem Label.enumList_nodup : Label.enumList.Nodup := by decide + +instance : Fintype Label where + elems := ⟨Label.enumList, Label.enumList_nodup⟩ + complete x := by cases x <;> decide + +def statement (q : Nat) (counter source destination : K) (labels : Label → Λ) + (exit : Option Λ) : Label → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) + | .guard => MachineUnaryCounter.guard counter (labels .skipTail) (labels .select) + | .skipTail => MachineLookup.discard source (labels .skipTail) (labels .skipReverse) + | .skipReverse => MachineLookup.discard source (labels .skipReverse) (labels .skipPredicate) + | .skipPredicate => skipBits source (q * q) (.goto fun _ => labels .guard) + | .select => Hastad.SourceMachine.fieldStart destination (labels .copy) + | .copy => Hastad.SourceMachine.fieldLoop source destination (labels .copy) exit + +def program (q : Nat) (counter source destination : K) : + Label → TM2.Stmt (Alphabet (K := K)) Label (σ × Option Bool) := + statement q counter source destination id none + +def rowBits {q n m : Nat} (row : DartRow q n m) : List Bool := encodeWords (rowWords row) + +theorem rowBits_eq {q n m : Nat} (row : DartRow q n m) : + rowBits row = encodeWord row.tail.val ++ + (encodeWord row.reverseIndex.val ++ encodeWords (relationWords row.relation)) := by + simp [rowBits, rowWords, encodeWords] + +def rowsBits {q n m : Nat} (rows : List (DartRow q n m)) : List Bool := + encodeWords (rows.flatMap rowWords) + +@[simp] theorem rowsBits_nil {q n m : Nat} : rowsBits ([] : List (DartRow q n m)) = [] := rfl + +@[simp] theorem rowsBits_cons {q n m : Nat} (row : DartRow q n m) + (rows : List (DartRow q n m)) : rowsBits (row :: rows) = rowBits row ++ rowsBits rows := by + simp only [rowsBits, List.flatMap_cons, encodeWords_append, rowBits] + +def skipCost {q n m : Nat} (row : DartRow q n m) : Nat := + row.tail.val + row.reverseIndex.val + 4 + +def prefixCost {q n m : Nat} (rows : List (DartRow q n m)) : Nat := + (rows.map skipCost).sum + +def lookupCost {q n m : Nat} (prior : List (DartRow q n m)) (row : DartRow q n m) : Nat := + prefixCost prior + row.tail.val + 3 + +section Ambient + +variable {q n m : Nat} (counter source destination : K) (labels : Label → Λ) + (exit : Option Λ) + (P : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atStatement : ∀ label, P (labels label) = statement q counter source destination labels exit label) + +include atStatement + +theorem skipRowTrace (base : K → List Bool) (row : DartRow q n m) (suffix : List Bool) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step P))^[row.tail.val + row.reverseIndex.val + 3] + (some ⟨some (labels .skipTail), (ambient, register), + Function.update base source (rowBits row ++ suffix)⟩) = + some ⟨some (labels .guard), (ambient, none), Function.update base source suffix⟩ := by + have ht := MachineLookup.discardTrace_update source (labels .skipTail) (labels .skipReverse) + P (atStatement .skipTail) base row.tail.val + (encodeWord row.reverseIndex.val ++ (encodeWords (relationWords row.relation) ++ suffix)) + ambient register + have hr := MachineLookup.discardTrace_update source (labels .skipReverse) (labels .skipPredicate) + P (atStatement .skipReverse) base row.reverseIndex.val + (encodeWords (relationWords row.relation) ++ suffix) ambient none + have hp : TM2.step P + ⟨some (labels .skipPredicate), (ambient, none), Function.update base source + (encodeWords (relationWords row.relation) ++ suffix)⟩ = + some ⟨some (labels .guard), (ambient, none), Function.update base source suffix⟩ := by + change some (TM2.stepAux (P (labels .skipPredicate)) _ _) = _ + rw [atStatement .skipPredicate] + have h := congrArg some (stepAux_skipBits source row.relation.toList + (.goto fun _ => labels .guard) base suffix ambient none) + simpa only [statement, Vector.length_toList, relationWords, TM2.stepAux] using h + rw [rowBits_eq] + simp only [List.append_assoc] + rw [show row.tail.val + row.reverseIndex.val + 3 = + 1 + ((row.reverseIndex.val + 1) + (row.tail.val + 1)) by omega, + Function.iterate_add_apply, Function.iterate_add_apply, ht, hr, + Function.iterate_one, advance_some, hp] + +theorem skipRowTrace_fromTapes (base : K → List Bool) (row : DartRow q n m) + (suffix : List Bool) (hinput : base source = rowBits row ++ suffix) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step P))^[row.tail.val + row.reverseIndex.val + 3] + (some ⟨some (labels .skipTail), (ambient, register), base⟩) = + some ⟨some (labels .guard), (ambient, none), Function.update base source suffix⟩ := by + have h := skipRowTrace counter source destination labels exit P atStatement + base row suffix ambient register + have hb : Function.update base source (rowBits row ++ suffix) = base := by + rw [← hinput] + exact Function.update_eq_self source base + rw [hb] at h + exact h + +theorem selectTrace (hsd : source ≠ destination) (base : K → List Bool) + (row : DartRow q n m) (suffix : List Bool) + (hinput : base source = rowBits row ++ suffix) (ambient : σ) (register : Option Bool) : + (advance (TM2.step P))^[row.tail.val + 2] + (some ⟨some (labels .select), (ambient, register), base⟩) = + some ⟨exit, (ambient, none), Hastad.SourceMachine.fieldTapes source destination base + (encodeWord row.reverseIndex.val ++ (encodeWords (relationWords row.relation) ++ suffix)) + (encodeWord row.tail.val ++ base destination)⟩ := by + let ht := Hastad.SourceMachine.fieldInTime source destination hsd + (labels .select) (labels .copy) exit P (atStatement .select) (atStatement .copy) + base row.tail.val + (encodeWord row.reverseIndex.val ++ (encodeWords (relationWords row.relation) ++ suffix)) + (by simpa only [rowBits_eq, List.append_assoc] using hinput) ambient register + have hsteps : ht.steps = row.tail.val + 2 := rfl + have htrace := ht.evals_in_steps + rw [hsteps] at htrace + exact htrace + +theorem lookupTailTrace + (hcs : counter ≠ source) (hcd : counter ≠ destination) (hsd : source ≠ destination) + (base : K → List Bool) (prior : List (DartRow q n m)) (row : DartRow q n m) + (counterSuffix suffix output : List Bool) (ambient : σ) (register : Option Bool) : + (advance (TM2.step P))^[lookupCost prior row] + (some ⟨some (labels .guard), (ambient, register), + MachineLookup.tapes counter source destination base + (encodeWord prior.length ++ counterSuffix) + (rowsBits prior ++ (rowBits row ++ suffix)) output⟩) = + some ⟨exit, (ambient, none), + MachineLookup.tapes counter source destination base + (encodeWord 0 ++ counterSuffix) + (encodeWord row.reverseIndex.val ++ (encodeWords (relationWords row.relation) ++ suffix)) + (encodeWord row.tail.val ++ output)⟩ := by + induction prior generalizing register with + | nil => + simp only [lookupCost, prefixCost, List.map_nil, List.sum_nil, Nat.zero_add, + List.length_nil, rowsBits_nil, List.nil_append] + rw [show row.tail.val + 3 = (row.tail.val + 2) + 1 by omega, + Function.iterate_succ_apply] + have hg := MachineUnaryCounter.guardStep_zero counter (labels .guard) + (labels .skipTail) (labels .select) P (atStatement .guard) + (MachineLookup.tapes counter source destination base + (encodeWord 0 ++ counterSuffix) (rowBits row ++ suffix) output) + counterSuffix ambient register + have hcounter : MachineUnaryCounter.counterTapes counter + (MachineLookup.tapes counter source destination base + (encodeWord 0 ++ counterSuffix) (rowBits row ++ suffix) output) 0 counterSuffix = + MachineLookup.tapes counter source destination base + (encodeWord 0 ++ counterSuffix) (rowBits row ++ suffix) output := by + simp only [MachineUnaryCounter.counterTapes, MachineLookup.update_index _ _ _ hcs hcd] + rw [hcounter] at hg + simp only [advance_some] + rw [hg] + have hs := selectTrace counter source destination labels exit P atStatement hsd + (MachineLookup.tapes counter source destination base + (encodeWord 0 ++ counterSuffix) (rowBits row ++ suffix) output) + row suffix (by simp [hsd]) ambient none + simpa only [MachineLookup.tapes_destination, + MachineLookup.fieldTapes_eq _ _ _ hsd] using hs + | cons first prior ih => + simp only [lookupCost, prefixCost, List.map_cons, List.sum_cons, List.length_cons, + rowsBits_cons, List.append_assoc] + rw [show skipCost first + (prior.map skipCost).sum + row.tail.val + 3 = + ((prior.map skipCost).sum + row.tail.val + 3) + + (first.tail.val + first.reverseIndex.val + 3) + 1 by simp only [skipCost]; omega, + Function.iterate_succ_apply] + have hg := MachineUnaryCounter.guardStep_succ counter (labels .guard) + (labels .skipTail) (labels .select) P (atStatement .guard) + (MachineLookup.tapes counter source destination base + (encodeWord prior.length ++ counterSuffix) + (rowBits first ++ (rowsBits prior ++ (rowBits row ++ suffix))) output) + prior.length counterSuffix ambient register + simp only [MachineUnaryCounter.counterTapes, + MachineLookup.update_index _ _ _ hcs hcd] at hg + simp only [advance_some] + rw [hg, Function.iterate_add_apply] + have hs := skipRowTrace_fromTapes counter source destination labels exit P atStatement + (MachineLookup.tapes counter source destination base + (encodeWord prior.length ++ counterSuffix) + (rowBits first ++ (rowsBits prior ++ (rowBits row ++ suffix))) output) + first (rowsBits prior ++ (rowBits row ++ suffix)) (by simp [hsd]) ambient none + rw [hs] + simp only [MachineLookup.update_source _ _ _ hsd] + exact ih none + +end Ambient + +theorem lookupCost_le {q n m : Nat} (prior : List (DartRow q n m)) (row : DartRow q n m) : + lookupCost prior row ≤ (rowsBits prior ++ rowBits row).length + + 2 * (encodeWord prior.length).length + 1 := by + have hp : prefixCost prior ≤ (rowsBits prior).length + 2 * prior.length := by + induction prior with + | nil => simp [prefixCost] + | cons first prior ih => + have hb : skipCost first ≤ (rowBits first).length + 2 := by + simp only [skipCost, rowBits_eq, List.length_append, encodeWord_length] + omega + simp only [prefixCost, List.map_cons, List.sum_cons, rowsBits_cons, + List.length_append, List.length_cons] at * + omega + have hr : row.tail.val + 1 ≤ (rowBits row).length := by + simp only [rowBits_eq, List.length_append, encodeWord_length] + omega + simp only [lookupCost, List.length_append, encodeWord_length] + omega + +def lookupTailInTime {q n m : Nat} + (counter source destination : K) (labels : Label → Λ) (exit : Option Λ) + (P : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atStatement : ∀ label, P (labels label) = statement q counter source destination labels exit label) + (hcs : counter ≠ source) (hcd : counter ≠ destination) (hsd : source ≠ destination) + (base : K → List Bool) (prior : List (DartRow q n m)) (row : DartRow q n m) + (counterSuffix suffix output : List Bool) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step P) + ⟨some (labels .guard), (ambient, register), + MachineLookup.tapes counter source destination base + (encodeWord prior.length ++ counterSuffix) + (rowsBits prior ++ (rowBits row ++ suffix)) output⟩ + (some ⟨exit, (ambient, none), + MachineLookup.tapes counter source destination base + (encodeWord 0 ++ counterSuffix) + (encodeWord row.reverseIndex.val ++ (encodeWords (relationWords row.relation) ++ suffix)) + (encodeWord row.tail.val ++ output)⟩) + ((rowsBits prior ++ rowBits row).length + 2 * (encodeWord prior.length).length + 1) where + steps := lookupCost prior row + evals_in_steps := lookupTailTrace counter source destination labels exit P atStatement + hcs hcd hsd base prior row counterSuffix suffix output ambient register + steps_le_m := lookupCost_le prior row + +theorem tableTailTrace {q : Nat} + (counter source destination : K) (labels : Label → Λ) (exit : Option Λ) + (P : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atStatement : ∀ label, P (labels label) = statement q counter source destination labels exit label) + (hcs : counter ≠ source) (hcd : counter ≠ destination) (hsd : source ≠ destination) + (base : K → List Bool) (table : Table q) (e : Fin table.darts) + (counterSuffix suffix output : List Bool) (ambient : σ) (register : Option Bool) : + (advance (TM2.step P))^[lookupCost ((rowList table).take e.val) table.rows[e]] + (some ⟨some (labels .guard), (ambient, register), + MachineLookup.tapes counter source destination base + (encodeWord e.val ++ counterSuffix) (rowsBits (rowList table) ++ suffix) output⟩) = + some ⟨exit, (ambient, none), + MachineLookup.tapes counter source destination base + (encodeWord 0 ++ counterSuffix) + (encodeWord table.rows[e].reverseIndex.val ++ + (encodeWords (relationWords table.rows[e].relation) ++ + (rowsBits ((rowList table).drop (e.val + 1)) ++ suffix))) + (encodeWord table.rows[e].tail.val ++ output)⟩ := by + have h := lookupTailTrace counter source destination labels exit P atStatement + hcs hcd hsd base ((rowList table).take e.val) table.rows[e] counterSuffix + (rowsBits ((rowList table).drop (e.val + 1)) ++ suffix) output ambient register + have hlength : ((rowList table).take e.val).length = e.val := by + simp only [List.length_take, rowList_length, Nat.min_eq_left (Nat.le_of_lt e.isLt)] + have hsplit : rowsBits (rowList table) ++ suffix = + rowsBits ((rowList table).take e.val) ++ + (rowBits table.rows[e] ++ (rowsBits ((rowList table).drop (e.val + 1)) ++ suffix)) := by + have hrow : table.rows[e.val] = table.rows[e] := rfl + simpa only [rowsBits, rowBits, rowList, Vector.getElem_toList, hrow] using + Input.rowsBits_append_split (rowList table) e.val (by simp) suffix + rw [hlength, ← hsplit] at h + exact h + +theorem fullTableTailTrace {q : Nat} + (counter source destination : K) (labels : Label → Λ) (exit : Option Λ) + (headerVertices headerDarts : Λ) + (P : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atStatement : ∀ label, P (labels label) = statement q counter source destination labels exit label) + (atVertices : P headerVertices = MachineLookup.discard source headerVertices headerDarts) + (atDarts : P headerDarts = MachineLookup.discard source headerDarts (labels .guard)) + (hcs : counter ≠ source) (hcd : counter ≠ destination) (hsd : source ≠ destination) + (base : K → List Bool) (table : Table q) (e : Fin table.darts) + (counterSuffix suffix output : List Bool) (ambient : σ) (register : Option Bool) : + (advance (TM2.step P))^[lookupCost ((rowList table).take e.val) table.rows[e] + + (table.darts + 1) + (table.vertices + 1)] + (some ⟨some headerVertices, (ambient, register), + MachineLookup.tapes counter source destination base + (encodeWord e.val ++ counterSuffix) (tableBits table ++ suffix) output⟩) = + some ⟨exit, (ambient, none), + MachineLookup.tapes counter source destination base + (encodeWord 0 ++ counterSuffix) + (encodeWord table.rows[e].reverseIndex.val ++ + (encodeWords (relationWords table.rows[e].relation) ++ + (rowsBits ((rowList table).drop (e.val + 1)) ++ suffix))) + (encodeWord table.rows[e].tail.val ++ output)⟩ := by + have hv := MachineLookup.discardTrace source headerVertices headerDarts P atVertices + (MachineLookup.tapes counter source destination base + (encodeWord e.val ++ counterSuffix) (tableBits table ++ suffix) output) + table.vertices (encodeWord table.darts ++ (rowsBits (rowList table) ++ suffix)) + (by simp only [MachineLookup.tapes_source _ _ _ hsd, Input.tableBits_header, + rowsBits, List.append_assoc]) ambient register + rw [Function.iterate_add_apply, hv] + simp only [MachineLookup.update_source _ _ _ hsd] + have hd := MachineLookup.discardTrace source headerDarts (labels .guard) P atDarts + (MachineLookup.tapes counter source destination base + (encodeWord e.val ++ counterSuffix) + (encodeWord table.darts ++ (rowsBits (rowList table) ++ suffix)) output) + table.darts (rowsBits (rowList table) ++ suffix) (by simp [hsd]) ambient none + rw [Function.iterate_add_apply, hd] + simp only [MachineLookup.update_source _ _ _ hsd] + exact tableTailTrace counter source destination labels exit P atStatement hcs hcd hsd + base table e counterSuffix suffix output ambient none + +theorem lookup_frame (counter source destination other : K) + (hc : other ≠ counter) (hs : other ≠ source) (hd : other ≠ destination) + (base : K → List Bool) (counterBits input output : List Bool) : + MachineLookup.tapes counter source destination base counterBits input output other = base other := + MachineLookup.tapes_other counter source destination other hc hs hd base counterBits input output + +def tableTailCost {q : Nat} (table : Table q) (e : Fin table.darts) : Nat := + lookupCost ((rowList table).take e.val) table.rows[e] + + (table.darts + 1) + (table.vertices + 1) + +theorem tableTailCost_le {q : Nat} (table : Table q) (e : Fin table.darts) : + tableTailCost table e ≤ (tableBits table).length + 2 * (encodeWord e.val).length + 1 := by + have htake : ((rowList table).take e.val).length = e.val := by + simp only [List.length_take, rowList_length, Nat.min_eq_left (Nat.le_of_lt e.isLt)] + have hrow : table.rows[e.val] = table.rows[e] := rfl + have hsplit : rowsBits (rowList table) = rowsBits ((rowList table).take e.val) ++ + (rowBits table.rows[e] ++ rowsBits ((rowList table).drop (e.val + 1))) := by + simpa only [rowsBits, rowBits, rowList, Vector.getElem_toList, hrow] using + Input.rowsBits_split (rowList table) e.val (by simp) + have hp : (rowsBits ((rowList table).take e.val) ++ rowBits table.rows[e]).length ≤ + (rowsBits (rowList table)).length := by + rw [hsplit] + simp only [List.length_append] + omega + have hb := lookupCost_le ((rowList table).take e.val) table.rows[e] + rw [htake] at hb + have hh := congrArg List.length (Input.tableBits_header table) + change (tableBits table).length = + (encodeWord table.vertices ++ (encodeWord table.darts ++ rowsBits (rowList table))).length at hh + simp only [List.length_append, encodeWord_length] at hh + unfold tableTailCost + omega + +def headIndex {q : Nat} (table : Table q) (e : Fin table.darts) : Fin table.darts := + table.rows[e].reverseIndex + +def headValue {q : Nat} (table : Table q) (e : Fin table.darts) : Nat := + table.rows[headIndex table e].tail.val + +theorem headValue_eq_semantics {q : Nat} (table : Table q) (e : Fin table.darts) : + headValue table e = ((semantics table).head e).val := rfl + +abbrev HeadTapes (K : Type) := Fin 6 → K + +def headLookupTapes {q : Nat} (tape : HeadTapes K) (base : K → List Bool) + (table : Table q) (e : Fin table.darts) : K → List Bool := + MachineLookup.tapes (tape 3) (tape 2) (tape 4) base + (encodeWord 0 ++ base (tape 3)) + (encodeWord table.rows[headIndex table e].reverseIndex.val ++ + (encodeWords (relationWords table.rows[headIndex table e].relation) ++ + (rowsBits ((rowList table).drop ((headIndex table e).val + 1)) ++ base (tape 2)))) + (encodeWord (headValue table e)) + +def headLookupCost {q : Nat} (table : Table q) (e : Fin table.darts) : Nat := + 2 * ((tableBits table).length + 1) + + 2 * ((encodeWord (headIndex table e).val).length + 1) + tableTailCost table (headIndex table e) + +theorem headLookupCost_le {q : Nat} (table : Table q) (e : Fin table.darts) : + headLookupCost table e ≤ 7 * (tableBits table).length + 5 := by + have hi : (encodeWord (headIndex table e).val).length ≤ (tableBits table).length := by + rw [encodeWord_length] + exact (Nat.succ_le_of_lt (headIndex table e).isLt).trans (darts_le_tableBits_length table) + have hl := tableTailCost_le table (headIndex table e) + unfold headLookupCost + omega + +noncomputable def headTimePolynomial : Polynomial Nat := + Polynomial.C 7 * Polynomial.X + Polynomial.C 5 + +def headLookupInTime {q : Nat} + (tape : HeadTapes K) (hinj : Function.Injective tape) + (tableFirst tableSecond indexFirst indexSecond headerVertices headerDarts : Λ) + (labels : Label → Λ) (exit : Option Λ) + (P : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atTableFirst : P tableFirst = Reduction.MachineTransfer.loopAt + (tape 0) (tape 5) id false tableFirst (some tableSecond)) + (atTableSecond : P tableSecond = MachineCopy.forkLoop + (tape 5) (tape 0) (tape 2) false tableSecond (some indexFirst)) + (atIndexFirst : P indexFirst = Reduction.MachineTransfer.loopAt + (tape 1) (tape 5) id false indexFirst (some indexSecond)) + (atIndexSecond : P indexSecond = MachineCopy.forkLoop + (tape 5) (tape 1) (tape 3) false indexSecond (some headerVertices)) + (atVertices : P headerVertices = MachineLookup.discard (tape 2) headerVertices headerDarts) + (atDarts : P headerDarts = MachineLookup.discard (tape 2) headerDarts (labels .guard)) + (atStatement : ∀ label, + P (labels label) = statement q (tape 3) (tape 2) (tape 4) labels exit label) + (base : K → List Bool) (table : Table q) (e : Fin table.darts) + (hTable : base (tape 0) = tableBits table) + (hReverse : base (tape 1) = encodeWord (headIndex table e).val) + (hHead : base (tape 4) = []) (hScratch : base (tape 5) = []) + (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step P) + ⟨some tableFirst, (ambient, register), base⟩ + (some ⟨exit, (ambient, none), headLookupTapes tape base table e⟩) + (headTimePolynomial.eval (tableBits table).length) := by + have hne (i j : Fin 6) (h : i ≠ j) : tape i ≠ tape j := fun heq => h (hinj heq) + let t₁ := Function.update base (tape 2) (tableBits table ++ base (tape 2)) + let t₂ := Function.update t₁ (tape 3) (encodeWord (headIndex table e).val ++ base (tape 3)) + have run₁ : StateTransition.EvalsToInTime (TM2.step P) + ⟨some tableFirst, (ambient, register), base⟩ + (some ⟨some indexFirst, (ambient, none), t₁⟩) + (2 * ((tableBits table).length + 1)) := by + simpa only [hTable, t₁] using MachineCopy.copyInTime (tape 0) (tape 2) (tape 5) + (hne 0 2 (by decide)) (hne 0 5 (by decide)) (hne 2 5 (by decide)) false + tableFirst tableSecond (some indexFirst) P atTableFirst atTableSecond + base hScratch ambient register + have hsrc : t₁ (tape 1) = encodeWord (headIndex table e).val := by + simp only [t₁, Function.update_of_ne (hne 1 2 (by decide)), hReverse] + have hdst : t₁ (tape 3) = base (tape 3) := by + simp only [t₁, Function.update_of_ne (hne 3 2 (by decide))] + have hscratch₁ : t₁ (tape 5) = [] := by + simp only [t₁, Function.update_of_ne (hne 5 2 (by decide)), hScratch] + have run₂ : StateTransition.EvalsToInTime (TM2.step P) + ⟨some indexFirst, (ambient, none), t₁⟩ + (some ⟨some headerVertices, (ambient, none), t₂⟩) + (2 * ((encodeWord (headIndex table e).val).length + 1)) := by + simpa only [hsrc, hdst, t₂] using MachineCopy.copyInTime (tape 1) (tape 3) (tape 5) + (hne 1 3 (by decide)) (hne 1 5 (by decide)) (hne 3 5 (by decide)) false + indexFirst indexSecond (some headerVertices) P atIndexFirst atIndexSecond + t₁ hscratch₁ ambient none + have ht₂ : t₂ = MachineLookup.tapes (tape 3) (tape 2) (tape 4) base + (encodeWord (headIndex table e).val ++ base (tape 3)) + (tableBits table ++ base (tape 2)) [] := by + funext k + by_cases hi : k = tape 3 + · subst k + simp [t₂, MachineLookup.tapes, hne 3 2 (by decide), hne 3 4 (by decide)] + · by_cases hs : k = tape 2 + · subst k + simp [t₂, t₁, MachineLookup.tapes, hne 2 3 (by decide), hne 2 4 (by decide)] + · by_cases hh : k = tape 4 + · subst k + simp [t₂, t₁, MachineLookup.tapes, hne 4 3 (by decide), + hne 4 2 (by decide), hHead] + · simp [t₂, t₁, MachineLookup.tapes, hi, hs, hh] + let run₃ : StateTransition.EvalsToInTime (TM2.step P) + ⟨some headerVertices, (ambient, none), t₂⟩ + (some ⟨exit, (ambient, none), headLookupTapes tape base table e⟩) + (tableTailCost table (headIndex table e)) := { + steps := tableTailCost table (headIndex table e) + evals_in_steps := by + change (advance (TM2.step P))^[tableTailCost table (headIndex table e)] + (some ⟨some headerVertices, (ambient, none), t₂⟩) = + some ⟨exit, (ambient, none), headLookupTapes tape base table e⟩ + rw [ht₂] + simpa only [headLookupTapes, headValue, tableTailCost, List.append_nil] using + fullTableTailTrace (tape 3) (tape 2) (tape 4) labels exit + headerVertices headerDarts P atStatement atVertices atDarts + (hne 3 2 (by decide)) (hne 3 4 (by decide)) (hne 2 4 (by decide)) + base table (headIndex table e) (base (tape 3)) (base (tape 2)) [] ambient none + steps_le_m := Nat.le_refl _ } + let run₁₂ := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ run₁ run₂ + let run := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ run₁₂ run₃ + refine { toEvalsTo := run.toEvalsTo, steps_le_m := ?_ } + have ht := run.steps_le_m + have hb := headLookupCost_le table e + simp only [headTimePolynomial, Polynomial.eval_add, Polynomial.eval_mul, + Polynomial.eval_C, Polynomial.eval_X] + unfold headLookupCost at hb + omega + +theorem headLookupTapes_head {q : Nat} (tape : HeadTapes K) (base : K → List Bool) + (table : Table q) (e : Fin table.darts) : + headLookupTapes tape base table e (tape 4) = encodeWord (headValue table e) := by + simp [headLookupTapes] + +theorem headLookupTapes_frame {q : Nat} (tape : HeadTapes K) (base : K → List Bool) + (table : Table q) (e : Fin table.darts) (other : K) + (hc : other ≠ tape 3) (hs : other ≠ tape 2) (hh : other ≠ tape 4) : + headLookupTapes tape base table e other = base other := + lookup_frame (tape 3) (tape 2) (tape 4) other hc hs hh base _ _ _ + +def readRowTapes {q n m : Nat} (source tail reverse : K) (base : K → List Bool) + (row : DartRow q n m) (suffix : List Bool) : K → List Bool := + Function.update (Function.update (Function.update base source suffix) + tail (encodeWord row.tail.val)) reverse (encodeWord row.reverseIndex.val) + +theorem readRowTapes_source {q n m : Nat} (source tail reverse : K) + (hst : source ≠ tail) (hsr : source ≠ reverse) + (base : K → List Bool) (row : DartRow q n m) (suffix : List Bool) : + readRowTapes source tail reverse base row suffix source = suffix := by + simp [readRowTapes, hst, hsr] + +theorem readRowTapes_tail {q n m : Nat} (source tail reverse : K) + (htr : tail ≠ reverse) (base : K → List Bool) + (row : DartRow q n m) (suffix : List Bool) : + readRowTapes source tail reverse base row suffix tail = encodeWord row.tail.val := by + simp [readRowTapes, htr] + +theorem readRowTapes_reverse {q n m : Nat} (source tail reverse : K) + (base : K → List Bool) (row : DartRow q n m) (suffix : List Bool) : + readRowTapes source tail reverse base row suffix reverse = + encodeWord row.reverseIndex.val := by + simp [readRowTapes] + +theorem readRowTapes_frame {q n m : Nat} (source tail reverse other : K) + (hs : other ≠ source) (ht : other ≠ tail) (hr : other ≠ reverse) + (base : K → List Bool) (row : DartRow q n m) (suffix : List Bool) : + readRowTapes source tail reverse base row suffix other = base other := by + simp [readRowTapes, hs, ht, hr] + +def readRowCost {q n m : Nat} (row : DartRow q n m) : Nat := + row.tail.val + row.reverseIndex.val + 5 + +theorem readRowCost_le {q n m : Nat} (row : DartRow q n m) : + readRowCost row ≤ (rowBits row).length + 3 := by + rw [rowBits_eq] + simp only [List.length_append, encodeWord_length] + unfold readRowCost + omega + +theorem readRowCost_table_le {q : Nat} (table : Table q) (e : Fin table.darts) : + readRowCost table.rows[e] ≤ 2 * (tableBits table).length + 5 := by + have ht := (Nat.le_of_lt table.rows[e].tail.isLt).trans + (vertices_le_tableBits_length table) + have hr := (Nat.le_of_lt table.rows[e].reverseIndex.isLt).trans + (darts_le_tableBits_length table) + unfold readRowCost + omega + +def readRowInTime {q n m : Nat} (source tail reverse : K) + (hst : source ≠ tail) (hsr : source ≠ reverse) (htr : tail ≠ reverse) + (tailStart tailLoop reverseStart reverseLoop readLabel exitLabel : Λ) + (P : Λ → TM2.Stmt (Alphabet (K := K)) Λ (ReadRelation.State σ q)) + (atTailStart : P tailStart = Hastad.SourceMachine.fieldStart tail tailLoop) + (atTailLoop : P tailLoop = + Hastad.SourceMachine.fieldLoop source tail tailLoop (some reverseStart)) + (atReverseStart : P reverseStart = Hastad.SourceMachine.fieldStart reverse reverseLoop) + (atReverseLoop : P reverseLoop = + Hastad.SourceMachine.fieldLoop source reverse reverseLoop (some readLabel)) + (atRead : P readLabel = ReadRelation.parser source exitLabel) + (base : K → List Bool) (row : DartRow q n m) (suffix : List Bool) + (hinput : base source = rowBits row ++ suffix) + (hTail : base tail = []) (hReverse : base reverse = []) + (ambient : σ) (initial : RelationTable q) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step P) + ⟨some tailStart, ((ambient, initial), register), base⟩ + (some ⟨some exitLabel, ((ambient, row.relation), none), + readRowTapes source tail reverse base row suffix⟩) + (readRowCost row) := by + let relationInput := encodeWords (relationWords row.relation) ++ suffix + let reverseInput := encodeWord row.reverseIndex.val ++ relationInput + let t₁ := Hastad.SourceMachine.fieldTapes source tail base reverseInput + (encodeWord row.tail.val) + let t₂ := Hastad.SourceMachine.fieldTapes source reverse t₁ relationInput + (encodeWord row.reverseIndex.val) + have hinput₁ : base source = encodeWord row.tail.val ++ reverseInput := by + simpa only [rowBits_eq, List.append_assoc, reverseInput, relationInput] using hinput + have run₁ : StateTransition.EvalsToInTime (TM2.step P) + ⟨some tailStart, ((ambient, initial), register), base⟩ + (some ⟨some reverseStart, ((ambient, initial), none), t₁⟩) + (row.tail.val + 2) := by + simpa only [hTail, List.append_nil, t₁] using + Hastad.SourceMachine.fieldInTime source tail hst tailStart tailLoop + (some reverseStart) P atTailStart atTailLoop base row.tail.val reverseInput + hinput₁ (ambient, initial) register + have hinput₂ : t₁ source = encodeWord row.reverseIndex.val ++ relationInput := by + simp only [t₁, Hastad.SourceMachine.fieldTapes_source source tail hst, reverseInput] + have hreverse₁ : t₁ reverse = [] := by + simp [t₁, Hastad.SourceMachine.fieldTapes, Ne.symm hsr, Ne.symm htr, hReverse] + have run₂ : StateTransition.EvalsToInTime (TM2.step P) + ⟨some reverseStart, ((ambient, initial), none), t₁⟩ + (some ⟨some readLabel, ((ambient, initial), none), t₂⟩) + (row.reverseIndex.val + 2) := by + simpa only [hreverse₁, List.append_nil, t₂] using + Hastad.SourceMachine.fieldInTime source reverse hsr reverseStart reverseLoop + (some readLabel) P atReverseStart atReverseLoop t₁ row.reverseIndex.val relationInput + hinput₂ (ambient, initial) none + have hinput₃ : t₂ source = encodeWords (relationWords row.relation) ++ suffix := by + simp only [t₂, Hastad.SourceMachine.fieldTapes_source source reverse hsr, relationInput] + have hrestore : Function.update t₂ source + (encodeWords (relationWords row.relation) ++ suffix) = t₂ := by + rw [← hinput₃] + exact Function.update_eq_self source t₂ + have hfinal : Function.update t₂ source suffix = + readRowTapes source tail reverse base row suffix := by + funext k + by_cases hs : k = source + · subst k + simp [readRowTapes, hst, hsr] + · by_cases ht : k = tail + · subst k + simp [t₂, t₁, Hastad.SourceMachine.fieldTapes, readRowTapes, hs, htr] + · by_cases hr : k = reverse + · subst k + simp [t₂, Hastad.SourceMachine.fieldTapes, readRowTapes, hs] + · simp [t₂, t₁, Hastad.SourceMachine.fieldTapes, readRowTapes, hs, ht, hr] + have run₃ : StateTransition.EvalsToInTime (TM2.step P) + ⟨some readLabel, ((ambient, initial), none), t₂⟩ + (some ⟨some exitLabel, ((ambient, row.relation), none), + readRowTapes source tail reverse base row suffix⟩) 1 := { + steps := 1 + evals_in_steps := by + change (advance (TM2.step P))^[1] _ = _ + simpa only [hrestore, hfinal] using ReadRelation.parserTrace source readLabel exitLabel + P atRead t₂ row.relation suffix ambient initial none + steps_le_m := Nat.le_refl _ } + let run₁₂ := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ run₁ run₂ + let run := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ run₁₂ run₃ + refine { toEvalsTo := run.toEvalsTo, steps_le_m := ?_ } + have ht := run.steps_le_m + unfold readRowCost + omega + +def machine (q : Nat) : FinTM2 where + K := Fin 3 + k₀ := 1 + k₁ := 2 + Γ _ := Bool + Λ := Label + main := .guard + σ := Unit × Option Bool + initialState := ((), none) + m := program q 0 1 2 + +end MinUncutGames.Foundations.PCP.AlphabetTable.Lookup + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineOverlayRows.lean b/lean/OAI/Computability/MinUncut/Machines/MachineOverlayRows.lean new file mode 100644 index 0000000000000000000000000000000000000000..4faa526586f7279b60ed92c5078bc45cb329f39e --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineOverlayRows.lean @@ -0,0 +1,489 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineLazyRows +import OAI.Computability.MinUncut.PCP.PreprocessingOverlayWords + +namespace OAI + +section +namespace MinUncutGames.Foundations.Complexity.MachineOverlayRows + +open Turing MachineComposition +open PCP.GraphTables PCP.PreprocessingOverlayWords +open Reduction.MachineSubstitution (pushWord stepAux_pushWord) + +variable {K Λ A : Type} [DecidableEq K] +variable {e : Nat} + +abbrev State (A : Type) (e : Nat) := MachinePortReindex.State A e + +inductive Label (e : Nat) + | loadStart | loadLoop | seedRelation + | row (stage : MachineLazyRows.Label e) + | drainOld | drainNew | drainRelation + deriving DecidableEq, Fintype + +def bodyIndex (i : Fin 9) : Fin 10 := i.castSucc + +theorem bodyIndex_injective : Function.Injective bodyIndex := by + intro i j h + exact Fin.castSucc_injective 9 h + +def trueBits : List Bool := encodeWords (relationWords trueRelation) + +def instruction (d e : Nat) (positive : 0 < e) (tape : Fin 10 → K) + (labels : Label e → Λ) (exit : Option Λ) : + Label e → TM2.Stmt (fun _ : K => Bool) Λ (State A e) + | .loadStart => Hastad.SourceMachine.fieldStart (tape 1) (labels .loadLoop) + | .loadLoop => Hastad.SourceMachine.fieldLoop (tape 9) (tape 1) + (labels .loadLoop) (some (labels .seedRelation)) + | .seedRelation => pushWord (tape 2) trueBits.reverse + (.goto fun _ => labels (.row (.inl .copySeed))) + | .row stage => MachineLazyRows.reindexInstruction e positive (d + e) d + (tape ∘ bodyIndex) (fun stage => labels (.row stage)) + (some (labels .drainOld)) stage + | .drainOld => MachineDrain.drain (tape 1) (labels .drainOld) (some (labels .drainNew)) + | .drainNew => MachineDrain.drain (tape 6) (labels .drainNew) (some (labels .drainRelation)) + | .drainRelation => MachineDrain.drain (tape 2) (labels .drainRelation) exit + +def rowBits (d e v j : Nat) : List Bool := + MachineLazyRows.reindexRowBits e (d + e) d v j trueRelation + +def rowSteps (d e v j : Nat) (output : List Bool) : Nat := + (j + 2) + 1 + MachineLazyRows.reindexSteps e (d + e) d v j trueRelation output + + (j + 2) + (MachinePortReindex.value e (d + e) d j + 2) + (trueBits.length + 1) + +def resultTapes (d e v j : Nat) (tape : Fin 10 → K) (base : K → List Bool) + (suffix : List Bool) : K → List Bool := + Function.update (Function.update base (tape 9) suffix) (tape 7) + (base (tape 7) ++ rowBits d e v j) + +theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +theorem rowTrace (d e : Nat) (positive : 0 < e) (tape : Fin 10 → K) + (distinct : Function.Injective tape) (labels : Label e → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State A e)) + (atLabels : ∀ l, program (labels l) = instruction d e positive tape labels exit l) + (base : K → List Bool) (v j : Nat) (suffix : List Bool) + (tailWord : base (tape 0) = encodeWord v) + (inputWord : base (tape 9) = encodeWord j ++ suffix) + (empty : ∀ i : Fin 10, i ≠ 0 → i ≠ 7 → i ≠ 9 → base (tape i) = []) + (ambient : A) : + (advance (TM2.step program))^[rowSteps d e v j (base (tape 7))] + (some ⟨some (labels .loadStart), MachinePortReindex.clean e positive ambient, base⟩) = + some ⟨exit, MachinePortReindex.clean e positive ambient, + resultTapes d e v j tape base suffix⟩ := by + have hd (i k : Fin 10) (h : i ≠ k) : tape i ≠ tape k := fun x => h (distinct x) + have h₁ := empty 1 (by decide) (by decide) (by decide) + have h₂ := empty 2 (by decide) (by decide) (by decide) + have h₃ := empty 3 (by decide) (by decide) (by decide) + have h₄ := empty 4 (by decide) (by decide) (by decide) + have h₅ := empty 5 (by decide) (by decide) (by decide) + have h₆ := empty 6 (by decide) (by decide) (by decide) + have h₈ := empty 8 (by decide) (by decide) (by decide) + have hi0 : bodyIndex 0 = 0 := rfl + have hi3 : bodyIndex 3 = 3 := rfl + have hi4 : bodyIndex 4 = 4 := rfl + have hi5 : bodyIndex 5 = 5 := rfl + have hi6 : bodyIndex 6 = 6 := rfl + have hi8 : bodyIndex 8 = 8 := rfl + let loaded := Function.update (Function.update base (tape 9) suffix) (tape 1) (encodeWord j) + let seeded := Function.update loaded (tape 2) trueBits + let rowed := MachineLazyRows.reindexResultTapes e (d + e) d v j trueRelation + (tape ∘ bodyIndex) seeded + let oldCleared := Function.update rowed (tape 1) [] + let newCleared := Function.update oldCleared (tape 6) [] + have loadRun : (advance (TM2.step program))^[j + 2] + (some ⟨some (labels .loadStart), MachinePortReindex.clean e positive ambient, base⟩) = + some ⟨some (labels .seedRelation), MachinePortReindex.clean e positive ambient, loaded⟩ := by + have h := (Hastad.SourceMachine.fieldInTime (tape 9) (tape 1) (hd 9 1 (by decide)) + (labels .loadStart) (labels .loadLoop) (some (labels .seedRelation)) program + (atLabels .loadStart) (atLabels .loadLoop) base j suffix inputWord + (ambient, MachineFixedDivMod.residue e positive 0) none).evals_in_steps + change (advance (TM2.step program))^[j + 2] + (some ⟨some (labels .loadStart), MachinePortReindex.clean e positive ambient, base⟩) = + some ⟨some (labels .seedRelation), MachinePortReindex.clean e positive ambient, + Hastad.SourceMachine.fieldTapes (tape 9) (tape 1) base suffix + (encodeWord j ++ base (tape 1))⟩ at h + simpa only [Hastad.SourceMachine.fieldTapes, + h₁, List.append_nil, MachinePortReindex.clean, loaded] using h + have seedRun : (advance (TM2.step program))^[1] + (some ⟨some (labels .seedRelation), MachinePortReindex.clean e positive ambient, loaded⟩) = + some ⟨some (labels (.row (.inl .copySeed))), + MachinePortReindex.clean e positive ambient, seeded⟩ := by + change some (TM2.stepAux (program (labels .seedRelation)) _ _) = _ + rw [atLabels] + simp [instruction, stepAux_pushWord, TM2.stepAux, seeded, loaded, + hd 2 1 (by decide), hd 2 9 (by decide), h₂] + have hs (i : Fin 10) (hi : i ≠ 1) (hi' : i ≠ 2) (hi'' : i ≠ 9) : + seeded (tape i) = base (tape i) := by + simp [seeded, loaded, hd i 1 hi, hd i 2 hi', hd i 9 hi''] + have bodyRun := MachineLazyRows.reindexRowTrace e positive (d + e) d + (tape ∘ bodyIndex) (distinct.comp bodyIndex_injective) (fun s => labels (.row s)) + (some (labels .drainOld)) program (fun s => atLabels (.row s)) seeded v j trueRelation + (by simpa only [Function.comp_apply, hi0] using + (hs 0 (by decide) (by decide) (by decide)).trans tailWord) + (by simp [seeded, loaded, Function.comp_apply, bodyIndex, hd 1 2 (by decide)]) + (by simp [seeded, Function.comp_apply, bodyIndex, trueBits]) + (by simpa only [Function.comp_apply, hi3] using + (hs 3 (by decide) (by decide) (by decide)).trans h₃) + (by simpa only [Function.comp_apply, hi4] using + (hs 4 (by decide) (by decide) (by decide)).trans h₄) + (by simpa only [Function.comp_apply, hi5] using + (hs 5 (by decide) (by decide) (by decide)).trans h₅) + (by simpa only [Function.comp_apply, hi6] using + (hs 6 (by decide) (by decide) (by decide)).trans h₆) + (by simpa only [Function.comp_apply, hi8] using + (hs 8 (by decide) (by decide) (by decide)).trans h₈) ambient + have hout : seeded ((tape ∘ bodyIndex) 7) = base (tape 7) := + hs 7 (by decide) (by decide) (by decide) + rw [hout] at bodyRun + change (advance (TM2.step program))^[MachineLazyRows.reindexSteps e (d + e) d v j + trueRelation (base (tape 7))] + (some ⟨some (labels (.row (.inl .copySeed))), MachinePortReindex.clean e positive ambient, seeded⟩) = + some ⟨some (labels .drainOld), MachinePortReindex.clean e positive ambient, rowed⟩ at bodyRun + have rowedOld : rowed (tape 1) = encodeWord j := by + simp [rowed, MachineLazyRows.reindexResultTapes, MachineLazyRows.reindexMappedTapes, + Function.comp_apply, bodyIndex, seeded, loaded, hd 1 7 (by decide), + hd 1 6 (by decide), hd 1 2 (by decide)] + have rowedNew : oldCleared (tape 6) = encodeWord (MachinePortReindex.value e (d + e) d j) := by + simp [oldCleared, rowed, MachineLazyRows.reindexResultTapes, + MachineLazyRows.reindexMappedTapes, Function.comp_apply, bodyIndex, + hd 6 1 (by decide), hd 6 7 (by decide)] + have rowedRelation : newCleared (tape 2) = trueBits := by + simp [newCleared, oldCleared, rowed, MachineLazyRows.reindexResultTapes, + MachineLazyRows.reindexMappedTapes, Function.comp_apply, bodyIndex, seeded, + hd 2 6 (by decide), hd 2 1 (by decide), hd 2 7 (by decide)] + have drainOld := (MachineDrain.drainInTime (tape 1) (labels .drainOld) + (some (labels .drainNew)) program (atLabels .drainOld) rowed + (ambient, MachineFixedDivMod.residue e positive 0) none).evals_in_steps + change (advance (TM2.step program))^[(rowed (tape 1)).length + 1] + (some ⟨some (labels .drainOld), MachinePortReindex.clean e positive ambient, rowed⟩) = + some ⟨some (labels .drainNew), MachinePortReindex.clean e positive ambient, oldCleared⟩ at drainOld + rw [rowedOld, encodeWord_length] at drainOld + have drainNew := (MachineDrain.drainInTime (tape 6) (labels .drainNew) + (some (labels .drainRelation)) program (atLabels .drainNew) oldCleared + (ambient, MachineFixedDivMod.residue e positive 0) none).evals_in_steps + change (advance (TM2.step program))^[(oldCleared (tape 6)).length + 1] + (some ⟨some (labels .drainNew), MachinePortReindex.clean e positive ambient, oldCleared⟩) = + some ⟨some (labels .drainRelation), MachinePortReindex.clean e positive ambient, newCleared⟩ at drainNew + rw [rowedNew, encodeWord_length] at drainNew + have drainRelation := (MachineDrain.drainInTime (tape 2) (labels .drainRelation) + exit program (atLabels .drainRelation) newCleared + (ambient, MachineFixedDivMod.residue e positive 0) none).evals_in_steps + change (advance (TM2.step program))^[(newCleared (tape 2)).length + 1] + (some ⟨some (labels .drainRelation), MachinePortReindex.clean e positive ambient, newCleared⟩) = + some ⟨exit, MachinePortReindex.clean e positive ambient, + Function.update newCleared (tape 2) []⟩ at drainRelation + rw [rowedRelation] at drainRelation + have finalFrame : Function.update newCleared (tape 2) [] = resultTapes d e v j tape base suffix := by + funext k + by_cases h2 : k = tape 2 + · subst k + simp [resultTapes, hd 2 7 (by decide), hd 2 9 (by decide), h₂] + · by_cases h6 : k = tape 6 + · subst k + simp [newCleared, resultTapes, hd 6 2 (by decide), hd 6 7 (by decide), + hd 6 9 (by decide), h₆] + · by_cases h1 : k = tape 1 + · subst k + simp [newCleared, oldCleared, resultTapes, hd 1 2 (by decide), + hd 1 6 (by decide), hd 1 7 (by decide), hd 1 9 (by decide), h₁] + · by_cases h7 : k = tape 7 + · subst k + simp [newCleared, oldCleared, rowed, MachineLazyRows.reindexResultTapes, + MachineLazyRows.reindexMappedTapes, Function.comp_apply, bodyIndex, + resultTapes, rowBits, seeded, loaded, hd 7 2 (by decide), + hd 7 6 (by decide), hd 7 1 (by decide), hd 7 9 (by decide)] + · simp [newCleared, oldCleared, rowed, MachineLazyRows.reindexResultTapes, + MachineLazyRows.reindexMappedTapes, Function.comp_apply, bodyIndex, + seeded, loaded, resultTapes, h2, h6, h1, h7] + rw [finalFrame] at drainRelation + exact joinTrace (joinTrace (joinTrace (joinTrace (joinTrace loadRun seedRun) bodyRun) + drainOld) drainNew) drainRelation + +theorem rowBits_eq_expanderRow {n : Nat} (d : Nat) (H : PCP.ExpanderTables.Table n e) + (v : Fin n) (p : Fin e) : + rowBits d e v.val (PCP.ExpanderTables.reverseIndex H + (PCP.ExpanderTables.rowIndex n e (v, p))).val = + encodeWords (rowWords (expanderRow d H v p)) := by + rw [expanderRow_words] + have h (j : Nat) : MachinePortReindex.value e (d + e) d j = expanderReverseMap d e j := by + unfold MachinePortReindex.value expanderReverseMap + omega + simp only [rowBits, MachineLazyRows.reindexRowBits, h, + PCP.PreprocessingLazyWords.relationWords_true, List.cons_append, + List.nil_append, encodeWords, List.append_assoc] + +def machine (d e : Nat) (positive : 0 < e) : FinTM2 where + K := Fin 10 + k₀ := 9 + k₁ := 7 + Γ _ := Bool + Λ := Label e + main := .loadStart + σ := State Unit e + initialState := MachinePortReindex.clean e positive () + m := instruction d e positive id id none + +abbrev VertexLabel (e : Nat) := Fin (e + 1) × Option (Label e) + +def vertexInstruction (d e : Nat) (positive : 0 < e) (tape : Fin 10 → K) + (labels : VertexLabel e → Λ) (exit : Option Λ) : + VertexLabel e → TM2.Stmt (fun _ : K => Bool) Λ (State A e) + | (i, none) => if i.val < e then .goto fun _ => labels (i, some .loadStart) + else MachinePortReindex.exitAt exit + | (i, some stage) => if h : i.val < e then + instruction d e positive tape (fun stage => labels (i, some stage)) + (some (labels (⟨i.val + 1, by omega⟩, none))) stage + else MachinePortReindex.exitAt exit + +def streamFrame (tape : Fin 10 → K) (base : K → List Bool) + (words : List Nat) (output : List Bool) : K → List Bool := + Function.update (Function.update base (tape 9) (encodeWords words ++ base (tape 9))) + (tape 7) output + +def streamOutput (d e v : Nat) (words : List Nat) : List Bool := + words.flatMap (rowBits d e v) + +def vertexSteps (d e v : Nat) : List Nat → List Bool → Nat + | [], _ => 1 + | j :: words, output => 1 + rowSteps d e v j output + + vertexSteps d e v words (output ++ rowBits d e v j) + +def valueBound (d e B : Nat) : Nat := (d + e) * B + B + d +def rowSizeBound (d e v B : Nat) : Nat := v + valueBound d e B + trueBits.length + 2 +def rowCostBound (d e v B : Nat) : Nat := + 8 * B + 4 * rowSizeBound d e v B + valueBound d e B + trueBits.length + 28 + +theorem value_le (d e j B : Nat) (hj : j ≤ B) : + MachinePortReindex.value e (d + e) d j ≤ valueBound d e B := by + have hdiv := (Nat.div_le_self j e).trans hj + have hmod := (Nat.mod_le j e).trans hj + have hmul := Nat.mul_le_mul_left (d + e) hdiv + unfold MachinePortReindex.value valueBound + omega + +theorem rowBits_length (d e v j : Nat) : + (rowBits d e v j).length = v + MachinePortReindex.value e (d + e) d j + trueBits.length + 2 := by + simp only [rowBits, MachineLazyRows.reindexRowBits, List.length_append, encodeWord_length, + trueBits] + omega + +theorem rowBits_length_le (d e v j B : Nat) (hj : j ≤ B) : + (rowBits d e v j).length ≤ rowSizeBound d e v B := by + rw [rowBits_length] + have h := value_le d e j B hj + unfold rowSizeBound + omega + +theorem rowSteps_le (d e v j B : Nat) (hj : j ≤ B) (output : List Bool) : + rowSteps d e v j output ≤ rowCostBound d e v B + 2 * output.length := by + have hdiv := (Nat.div_le_self j e).trans hj + have hval := value_le d e j B hj + have hsize := rowBits_length_le d e v j B hj + change (MachineLazyRows.reindexRowBits e (d + e) d v j trueRelation).length ≤ + rowSizeBound d e v B at hsize + unfold rowSteps MachineLazyRows.reindexSteps MachinePortReindex.steps rowCostBound + omega + +private theorem vertexSteps_le_capacity (d e v B capacity : Nat) + (words : List Nat) (bounded : ∀ j ∈ words, j ≤ B) (output : List Bool) + (room : output.length + words.length * rowSizeBound d e v B ≤ capacity) : + vertexSteps d e v words output ≤ + words.length * (rowCostBound d e v B + 2 * capacity + 1) + 1 := by + induction words generalizing output with + | nil => simp [vertexSteps] + | cons j words ih => + have hj := bounded j (by simp) + have hb : ∀ k ∈ words, k ≤ B := fun k hk => bounded k (by simp [hk]) + have hsize := rowBits_length_le d e v j B hj + have hcost := rowSteps_le d e v j B hj output + have hout : output.length ≤ capacity := by omega + have hroom : (output ++ rowBits d e v j).length + + words.length * rowSizeBound d e v B ≤ capacity := by + rw [List.length_append] + simp only [List.length_cons, Nat.succ_mul] at room + omega + have htail := ih hb (output ++ rowBits d e v j) hroom + change 1 + rowSteps d e v j output + + vertexSteps d e v words (output ++ rowBits d e v j) ≤ + (words.length + 1) * (rowCostBound d e v B + 2 * capacity + 1) + 1 + rw [Nat.add_mul, Nat.one_mul] + omega + +theorem vertexSteps_le (d e v B : Nat) (words : List Nat) + (bounded : ∀ j ∈ words, j ≤ B) (output : List Bool) : + vertexSteps d e v words output ≤ + words.length * (rowCostBound d e v B + + 2 * (output.length + words.length * rowSizeBound d e v B) + 1) + 1 := + vertexSteps_le_capacity d e v B _ words bounded output (Nat.le_refl _) + +private theorem streamFrame_afterRow (d e v j : Nat) (tape : Fin 10 → K) + (distinct : Function.Injective tape) (base : K → List Bool) + (words : List Nat) (output : List Bool) : + resultTapes d e v j tape (streamFrame tape base (j :: words) output) + (encodeWords words ++ base (tape 9)) = + streamFrame tape base words (output ++ rowBits d e v j) := by + have h79 : tape 7 ≠ tape 9 := fun h => (by decide : (7 : Fin 10) ≠ 9) (distinct h) + funext k + by_cases h7 : k = tape 7 + · subst k + simp [resultTapes, streamFrame] + · by_cases h9 : k = tape 9 + · subst k + simp [resultTapes, streamFrame, Ne.symm h79] + · simp [resultTapes, streamFrame, h7, h9] + +theorem vertexSuffixTrace (d e : Nat) (positive : 0 < e) (tape : Fin 10 → K) + (distinct : Function.Injective tape) (labels : VertexLabel e → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State A e)) + (atLabels : ∀ l, program (labels l) = vertexInstruction d e positive tape labels exit l) + (base : K → List Bool) (v : Nat) (values : Fin e → Nat) + (tailWord : base (tape 0) = encodeWord v) + (empty : ∀ i : Fin 10, i ≠ 0 → i ≠ 7 → i ≠ 9 → base (tape i) = []) + (ambient : A) (remaining : Nat) (i : Fin (e + 1)) (count : i.val + remaining = e) + (output : List Bool) : + (advance (TM2.step program))^[vertexSteps d e v ((List.ofFn values).drop i.val) output] + (some ⟨some (labels (i, none)), MachinePortReindex.clean e positive ambient, + streamFrame tape base ((List.ofFn values).drop i.val) output⟩) = + some ⟨exit, MachinePortReindex.clean e positive ambient, + streamFrame tape base [] (output ++ streamOutput d e v ((List.ofFn values).drop i.val))⟩ := by + have hd (a b : Fin 10) (h : a ≠ b) : tape a ≠ tape b := fun x => h (distinct x) + induction remaining generalizing i output with + | zero => + have hi : i.val = e := by omega + have hdrop : (List.ofFn values).drop i.val = [] := by + apply List.drop_eq_nil_of_le + simp only [List.length_ofFn, hi, le_refl] + rw [hdrop] + simp only [vertexSteps, streamOutput, List.flatMap_nil, List.append_nil] + change some (TM2.stepAux (program (labels (i, none))) _ _) = _ + rw [atLabels] + cases exit <;> simp [vertexInstruction, hi, MachinePortReindex.exitAt, TM2.stepAux] + | succ remaining ih => + have hi : i.val < e := by omega + let port : Fin e := ⟨i.val, hi⟩ + let next : Fin (e + 1) := ⟨i.val + 1, by omega⟩ + let rest := (List.ofFn values).drop (i.val + 1) + have split : (List.ofFn values).drop i.val = values port :: rest := by + have h := List.getElem_cons_drop (as := List.ofFn values) + (i := i.val) (by simpa only [List.length_ofFn] using hi) + simpa only [List.getElem_ofFn, port, rest] using h.symm + let initial := streamFrame tape base (values port :: rest) output + have boundary : (advance (TM2.step program))^[1] + (some ⟨some (labels (i, none)), MachinePortReindex.clean e positive ambient, initial⟩) = + some ⟨some (labels (i, some .loadStart)), MachinePortReindex.clean e positive ambient, initial⟩ := by + change some (TM2.stepAux (program (labels (i, none))) _ _) = _ + rw [atLabels] + simp [vertexInstruction, hi, TM2.stepAux] + have body := rowTrace d e positive tape distinct (fun stage => labels (i, some stage)) + (some (labels (next, none))) program + (by + intro stage + simpa only [vertexInstruction, hi, dite_true, next] using + (atLabels (i, some stage))) initial v (values port) + (encodeWords rest ++ base (tape 9)) + (by simp [initial, streamFrame, hd 0 7 (by decide), hd 0 9 (by decide), tailWord]) + (by simp [initial, streamFrame, hd 9 7 (by decide), encodeWords, List.append_assoc]) + (by + intro k hk0 hk7 hk9 + simp [initial, streamFrame, hd k 7 hk7, hd k 9 hk9, empty k hk0 hk7 hk9]) ambient + have initialOutput : initial (tape 7) = output := by simp [initial, streamFrame] + rw [initialOutput] at body + change (advance (TM2.step program))^[rowSteps d e v (values port) output] + (some ⟨some (labels (i, some .loadStart)), MachinePortReindex.clean e positive ambient, initial⟩) = + some ⟨some (labels (next, none)), MachinePortReindex.clean e positive ambient, + resultTapes d e v (values port) tape initial (encodeWords rest ++ base (tape 9))⟩ at body + rw [show resultTapes d e v (values port) tape initial (encodeWords rest ++ base (tape 9)) = + streamFrame tape base rest (output ++ rowBits d e v (values port)) from + streamFrame_afterRow d e v (values port) tape distinct base rest output] at body + have nextCount : next.val + remaining = e := by dsimp [next]; omega + have tail := ih next nextCount (output ++ rowBits d e v (values port)) + change (advance (TM2.step program))^[vertexSteps d e v rest (output ++ rowBits d e v (values port))] + (some ⟨some (labels (next, none)), MachinePortReindex.clean e positive ambient, + streamFrame tape base rest (output ++ rowBits d e v (values port))⟩) = + some ⟨exit, MachinePortReindex.clean e positive ambient, + streamFrame tape base [] ((output ++ rowBits d e v (values port)) ++ streamOutput d e v rest)⟩ at tail + rw [split] + have all := joinTrace (joinTrace boundary body) tail + simpa only [vertexSteps, initial, streamOutput, List.flatMap_cons, List.append_assoc] using all + +theorem vertexTrace (d e : Nat) (positive : 0 < e) (tape : Fin 10 → K) + (distinct : Function.Injective tape) (labels : VertexLabel e → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State A e)) + (atLabels : ∀ l, program (labels l) = vertexInstruction d e positive tape labels exit l) + (base : K → List Bool) (v : Nat) (values : Fin e → Nat) + (tailWord : base (tape 0) = encodeWord v) + (empty : ∀ i : Fin 10, i ≠ 0 → i ≠ 7 → i ≠ 9 → base (tape i) = []) + (ambient : A) (output : List Bool) : + (advance (TM2.step program))^[vertexSteps d e v (List.ofFn values) output] + (some ⟨some (labels (0, none)), MachinePortReindex.clean e positive ambient, + streamFrame tape base (List.ofFn values) output⟩) = + some ⟨exit, MachinePortReindex.clean e positive ambient, + streamFrame tape base [] (output ++ streamOutput d e v (List.ofFn values))⟩ := by + simpa only [Fin.val_zero, List.drop_zero] using vertexSuffixTrace d e positive tape distinct + labels exit program atLabels base v values tailWord empty ambient e 0 (by simp) output + +def vertexInTime (d e : Nat) (positive : 0 < e) (tape : Fin 10 → K) + (distinct : Function.Injective tape) (labels : VertexLabel e → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State A e)) + (atLabels : ∀ l, program (labels l) = vertexInstruction d e positive tape labels exit l) + (base : K → List Bool) (v B : Nat) (values : Fin e → Nat) + (bounded : ∀ p, values p ≤ B) + (tailWord : base (tape 0) = encodeWord v) + (empty : ∀ i : Fin 10, i ≠ 0 → i ≠ 7 → i ≠ 9 → base (tape i) = []) + (ambient : A) (output : List Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels (0, none)), MachinePortReindex.clean e positive ambient, + streamFrame tape base (List.ofFn values) output⟩ + (some ⟨exit, MachinePortReindex.clean e positive ambient, + streamFrame tape base [] (output ++ streamOutput d e v (List.ofFn values))⟩) + (e * (rowCostBound d e v B + 2 * (output.length + e * rowSizeBound d e v B) + 1) + 1) where + steps := vertexSteps d e v (List.ofFn values) output + evals_in_steps := vertexTrace d e positive tape distinct labels exit program atLabels + base v values tailWord empty ambient output + steps_le_m := by + simpa only [List.length_ofFn] using vertexSteps_le d e v B (List.ofFn values) + (by intro j hj; obtain ⟨p, rfl⟩ := List.mem_ofFn.mp hj; exact bounded p) output + +theorem encodeWords_flatMap {α : Type*} (items : List α) (words : α → List Nat) : + encodeWords (items.flatMap words) = items.flatMap (fun x => encodeWords (words x)) := by + induction items with + | nil => rfl + | cons item items ih => simp only [List.flatMap_cons, encodeWords_append, ih] + +theorem streamOutput_expanderRows {n : Nat} (d : Nat) (H : PCP.ExpanderTables.Table n e) + (v : Fin n) : + streamOutput d e v.val (List.ofFn fun p : Fin e => + (PCP.ExpanderTables.reverseIndex H (PCP.ExpanderTables.rowIndex n e (v, p))).val) = + encodeWords ((List.ofFn (expanderRow d H v)).flatMap rowWords) := by + rw [encodeWords_flatMap] + simp only [streamOutput, List.flatMap_def, List.map_ofFn] + apply congrArg List.flatten + apply congrArg List.ofFn + funext p + exact rowBits_eq_expanderRow d H v p + +theorem expanderValues_bounded {n : Nat} (H : PCP.ExpanderTables.Table n e) (v : Fin n) + (p : Fin e) : + (PCP.ExpanderTables.reverseIndex H (PCP.ExpanderTables.rowIndex n e (v, p))).val ≤ n * e := + (PCP.ExpanderTables.reverseIndex H (PCP.ExpanderTables.rowIndex n e (v, p))).isLt.le + +def vertexMachine (d e : Nat) (positive : 0 < e) : FinTM2 where + K := Fin 10 + k₀ := 9 + k₁ := 7 + Γ _ := Bool + Λ := VertexLabel e + main := (0, none) + σ := State Unit e + initialState := MachinePortReindex.clean e positive () + m := vertexInstruction d e positive id id none + +end MinUncutGames.Foundations.Complexity.MachineOverlayRows + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineOverlayTable.lean b/lean/OAI/Computability/MinUncut/Machines/MachineOverlayTable.lean new file mode 100644 index 0000000000000000000000000000000000000000..94ea7a9678128be17a63207c22af6261651cb209 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineOverlayTable.lean @@ -0,0 +1,947 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineRegularTableRuntime +import OAI.Computability.MinUncut.Machines.MachineOverlayRows + +namespace OAI + +section +namespace MinUncutGames.Foundations.Complexity.MachineOverlayTable + +open Turing MachineComposition +open PCP PCP.GraphTables PCP.PreprocessingOverlayWords +open MachineCloudPadding + + +variable {A : Type} {d e : Nat} + +abbrev Tape := Fin 5 ⊕ Fin 12 +abbrev Ambient (A : Type) (d e : Nat) := ((A × Fin e) × MachineLazyRows.Buffer) × Fin d +abbrev State (A : Type) (d e : Nat) := Ambient A d e × Option Bool + +def graphArchive : Tape := .inl 0 +def graphStream : Tape := .inl 1 +def scratch : Tape := .inl 2 +def vertexCount : Tape := .inl 3 +def dartCount : Tape := .inl 4 +def expanderArchive : Tape := .inr 0 +def expanderStream : Tape := .inr 1 +def fuel : Tape := .inr 2 +def vertex : Tape := .inr 3 +def tail : Tape := .inr 4 +def oldReverse : Tape := .inr 5 +def relation : Tape := .inr 6 +def dividedCopy : Tape := .inr 7 +def quotient : Tape := .inr 8 +def newReverse : Tape := .inr 9 +def rowBuffer : Tape := .inr 10 +def output : Tape := .inr 11 + +def oldTapes : Fin 10 → Tape := + ![tail, oldReverse, relation, scratch, dividedCopy, quotient, newReverse, + output, rowBuffer, graphStream] + +def expanderTapes : Fin 10 → Tape := + ![tail, oldReverse, relation, scratch, dividedCopy, quotient, newReverse, + output, rowBuffer, expanderStream] + +theorem oldTapes_injective : Function.Injective oldTapes := by + intro i j h + fin_cases i <;> fin_cases j <;> + simp_all [oldTapes, tail, oldReverse, relation, scratch, dividedCopy, quotient, + newReverse, output, rowBuffer, graphStream] + +theorem expanderTapes_injective : Function.Injective expanderTapes := by + intro i j h + fin_cases i <;> fin_cases j <;> + simp_all [expanderTapes, tail, oldReverse, relation, scratch, dividedCopy, quotient, + newReverse, output, rowBuffer, expanderStream] + +def clean (d e : Nat) (hd : 0 < d) (he : 0 < e) (a : A) : State A d e := + MachineLazyRows.streamClean d hd (a, MachineFixedDivMod.residue e he 0) + +def expanderState (A : Type) (d e : Nat) : + MachineOverlayRows.State ((A × MachineLazyRows.Buffer) × Fin d) e ≃ State A d e where + toFun + | ((((a, buffer), rd), re), bit) => ((((a, re), buffer), rd), bit) + invFun + | ((((a, re), buffer), rd), bit) => ((((a, buffer), rd), re), bit) + left_inv := by rintro ⟨⟨⟨⟨a, buffer⟩, rd⟩, re⟩, bit⟩; rfl + right_inv := by rintro ⟨⟨⟨⟨a, re⟩, buffer⟩, rd⟩, bit⟩; rfl + +theorem expanderState_clean (d e : Nat) (hd : 0 < d) (he : 0 < e) (a : A) : + expanderState A d e (MachinePortReindex.clean e he + ((a, MachineRegularOriginalRow.zeroBuffer), MachineFixedDivMod.residue d hd 0)) = + clean d e hd he a := rfl + +inductive MainLabel (d e : Nat) + | copyHFirst | copyHSecond + | countSeed | countScan | countRestore + | headerSeed | headerScan | headerRestore + | fuelSeed | fuelScan | fuelRestore | vertexSeed | guard + | old (stage : MachineLazyRows.VertexLabel d) + | tailSeed | tailScan | tailRestore + | expander (stage : MachineOverlayRows.VertexLabel e) + | drainTail | increment + | drainFuel | drainVertex | drainVertexCount | drainDartCount + deriving DecidableEq, Fintype + +abbrev Label (d e : Nat) := MachineTableSplit.Label ⊕ MainLabel d e + +def next (l : MainLabel d e) : Option (Label d e) := some (.inr l) + +def mainInstruction (d e : Nat) (hd : 0 < d) (he : 0 < e) : + MainLabel d e → TM2.Stmt (fun _ : Tape => Bool) (Label d e) (State A d e) + | .copyHFirst => Reduction.MachineTransfer.loopAt expanderArchive scratch id false + (.inr .copyHFirst) (next .copyHSecond) + | .copyHSecond => MachineCopy.forkLoop scratch expanderArchive expanderStream false + (.inr .copyHSecond) (next .countSeed) + | .countSeed => MachineUnaryAffineAt.seed output 0 (.inr .countScan) + | .countScan => MachineUnaryAffineAt.scan vertexCount scratch output (d + e) + (.inr .countScan) (.inr .countRestore) + | .countRestore => Reduction.MachineTransfer.loopAt scratch vertexCount id false + (.inr .countRestore) (next .headerSeed) + | .headerSeed => MachineUnaryAffineAt.seed output 0 (.inr .headerScan) + | .headerScan => MachineUnaryAffineAt.scan vertexCount scratch output 1 + (.inr .headerScan) (.inr .headerRestore) + | .headerRestore => Reduction.MachineTransfer.loopAt scratch vertexCount id false + (.inr .headerRestore) (next .fuelSeed) + | .fuelSeed => MachineUnaryAffineAt.seed fuel 0 (.inr .fuelScan) + | .fuelScan => MachineUnaryAffineAt.scan vertexCount scratch fuel 1 + (.inr .fuelScan) (.inr .fuelRestore) + | .fuelRestore => Reduction.MachineTransfer.loopAt scratch vertexCount id false + (.inr .fuelRestore) (next .vertexSeed) + | .vertexSeed => .push vertex (fun _ => false) (.goto fun _ => .inr .guard) + | .guard => MachineUnaryCounter.guard fuel (.inr (.old (0, none))) (.inr .drainFuel) + | .old stage => MachineLazyRows.vertexInstruction d hd (d + e) 0 oldTapes + (fun stage => .inr (.old stage)) (next .tailSeed) stage + | .tailSeed => MachineUnaryAffineAt.seed tail 0 (.inr .tailScan) + | .tailScan => MachineUnaryAffineAt.scan vertex scratch tail 1 + (.inr .tailScan) (.inr .tailRestore) + | .tailRestore => Reduction.MachineTransfer.loopAt scratch vertex id false + (.inr .tailRestore) (next (.expander (0, none))) + | .expander stage => MachineStateEquiv.statement (expanderState A d e) + (MachineOverlayRows.vertexInstruction d e he expanderTapes + (fun stage => .inr (.expander stage)) (next .drainTail) stage) + | .drainTail => MachineDrain.drain tail (.inr .drainTail) (next .increment) + | .increment => .push vertex (fun _ => true) (.goto fun _ => .inr .guard) + | .drainFuel => MachineDrain.drain fuel (.inr .drainFuel) (next .drainVertex) + | .drainVertex => MachineDrain.drain vertex (.inr .drainVertex) (next .drainVertexCount) + | .drainVertexCount => MachineDrain.drain vertexCount (.inr .drainVertexCount) (next .drainDartCount) + | .drainDartCount => MachineDrain.drain dartCount (.inr .drainDartCount) none + +def program (d e : Nat) (hd : 0 < d) (he : 0 < e) : + Label d e → TM2.Stmt (fun _ : Tape => Bool) (Label d e) (State A d e) + | .inl l => Placement.statement Sum.inl Sum.inl (next .copyHFirst) + (MachineTableSplit.program l) + | .inr l => mainInstruction d e hd he l + +theorem program_main (d e : Nat) (hd : 0 < d) (he : 0 < e) (l : MainLabel d e) : + program (A := A) d e hd he (.inr l) = mainInstruction d e hd he l := rfl + +def extraTapes (rawH : List Bool) : Fin 12 → List Bool := + fun i => if i = 0 then rawH else [] + +def splitView : Tape → Option (Fin 5) + | .inl i => some i + | .inr _ => none + +def combine (left : Fin 5 → List Bool) (rawH : List Bool) : Tape → List Bool + | .inl i => left i + | .inr i => extraTapes rawH i + +def initialTapes (graph rawH : List Bool) : Tape → List Bool := + combine (MachineTableSplit.initialTapes graph) rawH + +def splitTapes (n m : Nat) (rows rawH : List Bool) : Tape → List Bool := + combine (MachineTableSplit.resultTapes n m rows) rawH + +theorem placedTapes (left : Fin 5 → List Bool) (rawH : List Bool) : + Placement.tapes splitView left (initialTapes [] rawH) = combine left rawH := by + funext k + cases k <;> rfl + +theorem splitTrace (d e : Nat) (hd : 0 < d) (he : 0 < e) + (table : GraphTables.Table) (rawH : List Bool) (a : A) : + (advance (TM2.step (program d e hd he)))^[MachineTableSplit.exactSteps + table.vertices table.darts (MachineTableSplit.rowsBits table)] + (some ⟨some (.inl .copyFirst), clean d e hd he a, + initialTapes (GraphTables.tableBits table) rawH⟩) = + some ⟨next .copyHFirst, clean d e hd he a, + splitTapes table.vertices table.darts (MachineTableSplit.rowsBits table) rawH⟩ := by + let ambient := (clean d e hd he a).1 + have source := MachineTableSplit.tableTrace table ambient none + have placed := Placement.trace (Sum.inl : Fin 5 → Tape) splitView (fun _ => rfl) + (by intro j k h; cases j <;> simp_all [splitView]) + (Sum.inl : MachineTableSplit.Label → Label d e) (next .copyHFirst) + (initialTapes [] rawH) MachineTableSplit.program (program d e hd he) (fun _ => rfl) + _ _ _ source + simp only [Placement.configuration, Placement.label] at placed + rw [placedTapes, placedTapes] at placed + simpa only [initialTapes, + splitTapes, ambient, clean, MachineLazyRows.streamClean, MachinePortReindex.clean] using placed + +def memory (g h gs hs n m f v t out : List Bool) : Tape → List Bool + | .inl i => ![g, gs, [], n, m] i + | .inr i => ![h, hs, f, v, t, [], [], [], [], [], [], out] i + +@[simp] theorem memory_graphArchive (g h gs hs n m f v t out : List Bool) : + memory g h gs hs n m f v t out graphArchive = g := rfl +@[simp] theorem memory_graphStream (g h gs hs n m f v t out : List Bool) : + memory g h gs hs n m f v t out graphStream = gs := rfl +@[simp] theorem memory_scratch (g h gs hs n m f v t out : List Bool) : + memory g h gs hs n m f v t out scratch = [] := rfl +@[simp] theorem memory_vertexCount (g h gs hs n m f v t out : List Bool) : + memory g h gs hs n m f v t out vertexCount = n := rfl +@[simp] theorem memory_dartCount (g h gs hs n m f v t out : List Bool) : + memory g h gs hs n m f v t out dartCount = m := rfl +@[simp] theorem memory_expanderArchive (g h gs hs n m f v t out : List Bool) : + memory g h gs hs n m f v t out expanderArchive = h := rfl +@[simp] theorem memory_expanderStream (g h gs hs n m f v t out : List Bool) : + memory g h gs hs n m f v t out expanderStream = hs := rfl +@[simp] theorem memory_fuel (g h gs hs n m f v t out : List Bool) : + memory g h gs hs n m f v t out fuel = f := rfl +@[simp] theorem memory_vertex (g h gs hs n m f v t out : List Bool) : + memory g h gs hs n m f v t out vertex = v := rfl +@[simp] theorem memory_tail (g h gs hs n m f v t out : List Bool) : + memory g h gs hs n m f v t out tail = t := rfl +@[simp] theorem memory_oldReverse (g h gs hs n m f v t out : List Bool) : + memory g h gs hs n m f v t out oldReverse = [] := rfl +@[simp] theorem memory_relation (g h gs hs n m f v t out : List Bool) : + memory g h gs hs n m f v t out relation = [] := rfl +@[simp] theorem memory_dividedCopy (g h gs hs n m f v t out : List Bool) : + memory g h gs hs n m f v t out dividedCopy = [] := rfl +@[simp] theorem memory_quotient (g h gs hs n m f v t out : List Bool) : + memory g h gs hs n m f v t out quotient = [] := rfl +@[simp] theorem memory_newReverse (g h gs hs n m f v t out : List Bool) : + memory g h gs hs n m f v t out newReverse = [] := rfl +@[simp] theorem memory_rowBuffer (g h gs hs n m f v t out : List Bool) : + memory g h gs hs n m f v t out rowBuffer = [] := rfl +@[simp] theorem memory_output (g h gs hs n m f v t out : List Bool) : + memory g h gs hs n m f v t out output = out := rfl + +@[simp] theorem update_output (g h gs hs n m f v t out x : List Bool) : + Function.update (memory g h gs hs n m f v t out) output x = memory g h gs hs n m f v t x := by + funext k; rcases k with i | i <;> fin_cases i <;> rfl +@[simp] theorem update_expanderStream (g h gs hs n m f v t out x : List Bool) : + Function.update (memory g h gs hs n m f v t out) expanderStream x = + memory g h gs x n m f v t out := by + funext k; rcases k with i | i <;> fin_cases i <;> rfl +@[simp] theorem update_graphStream (g h gs hs n m f v t out x : List Bool) : + Function.update (memory g h gs hs n m f v t out) graphStream x = + memory g h x hs n m f v t out := by + funext k; rcases k with i | i <;> fin_cases i <;> rfl +@[simp] theorem update_fuel (g h gs hs n m f v t out x : List Bool) : + Function.update (memory g h gs hs n m f v t out) fuel x = memory g h gs hs n m x v t out := by + funext k; rcases k with i | i <;> fin_cases i <;> rfl +@[simp] theorem update_vertex (g h gs hs n m f v t out x : List Bool) : + Function.update (memory g h gs hs n m f v t out) vertex x = memory g h gs hs n m f x t out := by + funext k; rcases k with i | i <;> fin_cases i <;> rfl +@[simp] theorem update_tail (g h gs hs n m f v t out x : List Bool) : + Function.update (memory g h gs hs n m f v t out) tail x = memory g h gs hs n m f v x out := by + funext k; rcases k with i | i <;> fin_cases i <;> rfl +@[simp] theorem update_vertexCount (g h gs hs n m f v t out x : List Bool) : + Function.update (memory g h gs hs n m f v t out) vertexCount x = memory g h gs hs x m f v t out := by + funext k; rcases k with i | i <;> fin_cases i <;> rfl +@[simp] theorem update_dartCount (g h gs hs n m f v t out x : List Bool) : + Function.update (memory g h gs hs n m f v t out) dartCount x = memory g h gs hs n x f v t out := by + funext k; rcases k with i | i <;> fin_cases i <;> rfl + +theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +theorem initialTapes_memory (g h : List Bool) : + initialTapes g h = memory g h [] [] [] [] [] [] [] [] := by + funext k + rcases k with i | i <;> fin_cases i <;> + simp [initialTapes, combine, extraTapes, MachineTableSplit.initialTapes, + MachineTableSplit.tapes, memory] + +theorem splitTapes_memory (n m : Nat) (rows rawH : List Bool) : + splitTapes n m rows rawH = memory (encodeWords [n, m] ++ rows) rawH rows [] + (encodeWord n) (encodeWord m) [] [] [] [] := by + funext k + rcases k with i | i <;> fin_cases i <;> + simp [splitTapes, combine, extraTapes, MachineTableSplit.resultTapes, + MachineTableSplit.tapes, memory] + +def preparationSteps (n : Nat) (h : List Bool) : Nat := 2 * (h.length + 1) + 6 * (n + 1) + 4 + +theorem preparationTrace (d e : Nat) (hd : 0 < d) (he : 0 < e) + (g h gs : List Bool) (n m : Nat) (a : A) : + (advance (TM2.step (program d e hd he)))^[preparationSteps n h] + (some ⟨next .copyHFirst, clean d e hd he a, + memory g h gs [] (encodeWord n) (encodeWord m) [] [] [] []⟩) = + some ⟨next .guard, clean d e hd he a, + memory g h gs h (encodeWord n) (encodeWord m) (encodeWord n) (encodeWord 0) [] + (encodeWords [n, n * (d + e)])⟩ := by + let b0 := memory g h gs [] (encodeWord n) (encodeWord m) [] [] [] [] + let b1 := memory g h gs h (encodeWord n) (encodeWord m) [] [] [] [] + let b2 := memory g h gs h (encodeWord n) (encodeWord m) [] [] [] (encodeWord ((d + e) * n)) + let b3 := memory g h gs h (encodeWord n) (encodeWord m) [] [] [] + (encodeWords [n, n * (d + e)]) + let b4 := memory g h gs h (encodeWord n) (encodeWord m) (encodeWord n) [] [] + (encodeWords [n, n * (d + e)]) + let ambient := (clean d e hd he a).1 + have hcopy := MachineCopy.copyTrace expanderArchive expanderStream scratch + (by decide) (by decide) (by decide) false (.inr .copyHFirst) (.inr .copyHSecond) + (next .countSeed) (program d e hd he) rfl rfl b0 rfl ambient none + have copyRun : (advance (TM2.step (program d e hd he)))^[2 * (h.length + 1)] + (some ⟨next .copyHFirst, clean d e hd he a, b0⟩) = + some ⟨next .countSeed, clean d e hd he a, b1⟩ := by + simpa only [b0, b1, memory_expanderArchive, memory_expanderStream, next, List.append_nil, + update_expanderStream, ambient, clean, MachineLazyRows.streamClean, + MachinePortReindex.clean] using hcopy + have hcount := MachineUnaryAffineAt.seededAffineTrace vertexCount scratch output + (by decide) (by decide) (by decide) (d + e) 0 + (.inr .countSeed) (.inr .countScan) (.inr .countRestore) (next .headerSeed) + (program d e hd he) rfl rfl rfl b1 n [] (by simp [b1, memory, vertexCount]) rfl ambient none + have countRun : (advance (TM2.step (program d e hd he)))^[2 * (n + 1) + 1] + (some ⟨next .countSeed, clean d e hd he a, b1⟩) = + some ⟨next .headerSeed, clean d e hd he a, b2⟩ := by + simpa only [b1, b2, memory_output, next, List.append_nil, Nat.add_zero, update_output, + ambient, clean, MachineLazyRows.streamClean, MachinePortReindex.clean] using hcount + have hheader := MachineUnaryAffineAt.seededAffineTrace vertexCount scratch output + (by decide) (by decide) (by decide) 1 0 + (.inr .headerSeed) (.inr .headerScan) (.inr .headerRestore) (next .fuelSeed) + (program d e hd he) rfl rfl rfl b2 n [] (by simp [b2, memory, vertexCount]) rfl ambient none + have headerRun : (advance (TM2.step (program d e hd he)))^[2 * (n + 1) + 1] + (some ⟨next .headerSeed, clean d e hd he a, b2⟩) = + some ⟨next .fuelSeed, clean d e hd he a, b3⟩ := by + simpa only [b2, b3, memory_output, next, Nat.one_mul, Nat.add_zero, update_output, + Nat.mul_comm (d + e) n, encodeWords, List.append_nil, + ambient, clean, MachineLazyRows.streamClean, MachinePortReindex.clean] using hheader + have hfuel := MachineUnaryAffineAt.seededAffineTrace vertexCount scratch fuel + (by decide) (by decide) (by decide) 1 0 + (.inr .fuelSeed) (.inr .fuelScan) (.inr .fuelRestore) (next .vertexSeed) + (program d e hd he) rfl rfl rfl b3 n [] (by simp [b3, memory, vertexCount]) rfl ambient none + have fuelRun : (advance (TM2.step (program d e hd he)))^[2 * (n + 1) + 1] + (some ⟨next .fuelSeed, clean d e hd he a, b3⟩) = + some ⟨next .vertexSeed, clean d e hd he a, b4⟩ := by + simpa only [b3, b4, memory_fuel, next, List.append_nil, Nat.one_mul, Nat.add_zero, + update_fuel, ambient, clean, MachineLazyRows.streamClean, MachinePortReindex.clean] using hfuel + have seedRun : (advance (TM2.step (program d e hd he)))^[1] + (some ⟨next .vertexSeed, clean d e hd he a, b4⟩) = + some ⟨next .guard, clean d e hd he a, + memory g h gs h (encodeWord n) (encodeWord m) (encodeWord n) (encodeWord 0) [] + (encodeWords [n, n * (d + e)])⟩ := by + change some (TM2.stepAux (program d e hd he (.inr .vertexSeed)) _ _) = _ + simp only [program, mainInstruction, TM2.stepAux, b4, memory_vertex, + update_vertex, next, encodeWord, List.replicate_zero, List.nil_append] + have all := joinTrace (joinTrace (joinTrace (joinTrace copyRun countRun) headerRun) fuelRun) seedRun + have count : preparationSteps n h = + (((2 * (h.length + 1) + (2 * (n + 1) + 1)) + (2 * (n + 1) + 1)) + + (2 * (n + 1) + 1)) + 1 := by unfold preparationSteps; omega + rw [count] + exact all + +theorem encodeWords_flatMap {α : Type*} (items : List α) (words : α → List Nat) : + encodeWords (items.flatMap words) = items.flatMap (fun x => encodeWords (words x)) := by + induction items with + | nil => rfl + | cons item items ih => simp only [List.flatMap_cons, encodeWords_append, ih] + +private theorem encodeWords_flatten (items : List (List Nat)) : + encodeWords items.flatten = (items.map encodeWords).flatten := by + induction items with + | nil => rfl + | cons item items ih => simp only [List.flatten_cons, List.map_cons, encodeWords_append, ih] + +private theorem encodeWords_flatten_flatMap {α : Type*} (items : List (List α)) + (words : α → List Nat) : + encodeWords (items.flatten.flatMap words) = + (items.map fun xs => encodeWords (xs.flatMap words)).flatten := by + induction items with + | nil => rfl + | cons item items ih => + simp only [List.flatten_cons, List.flatMap_append, encodeWords_append, List.map_cons, ih] + +def oldRows {n d : Nat} (G : PortTables.Table n d) (v : Fin n) := List.ofFn (row G v) +def expanderValues {n e : Nat} (H : ExpanderTables.Table n e) (v : Fin n) (p : Fin e) : Nat := + (ExpanderTables.reverseIndex H (ExpanderTables.rowIndex n e (v, p))).val + +def oldBlock {n d : Nat} (G : PortTables.Table n d) (v : Fin n) : List Bool := + MachineLazyRows.recordsInput (oldRows G v) +def expanderBlock {n e : Nat} (H : ExpanderTables.Table n e) (v : Fin n) : List Bool := + encodeWords (List.ofFn (expanderValues H v)) + +def oldOutput {n d : Nat} (G : PortTables.Table n d) (e : Nat) (v : Fin n) : List Bool := + MachineLazyRows.recordsOutput d (d + e) 0 (oldRows G v) +def expanderOutput {n e : Nat} (d : Nat) (H : ExpanderTables.Table n e) (v : Fin n) : List Bool := + MachineOverlayRows.streamOutput d e v.val (List.ofFn (expanderValues H v)) +def outputBlock {n d e : Nat} (G : PortTables.Table n d) (H : ExpanderTables.Table n e) + (v : Fin n) : List Bool := oldOutput G e v ++ expanderOutput d H v + +theorem oldOutput_eq {n d : Nat} (G : PortTables.Table n d) (e : Nat) (v : Fin n) : + oldOutput G e v = encodeWords ((List.ofFn (oldRow G e v)).flatMap rowWords) := by + rw [encodeWords_flatMap] + simp only [oldOutput, oldRows, MachineLazyRows.recordsOutput, List.flatMap_def, List.map_ofFn] + apply congrArg List.flatten + apply congrArg List.ofFn + funext p + change MachineLazyRows.reindexRowBits d (d + e) 0 (row G v p).tail.val + (row G v p).reverseIndex.val (row G v p).relation = encodeWords (rowWords (oldRow G e v p)) + rw [oldRow_words] + simp only [MachineLazyRows.reindexRowBits, MachinePortReindex.value, Nat.add_zero, + oldReverseMap, row, PreprocessingLazyWords.row, List.cons_append, List.nil_append, + encodeWords, List.append_assoc] + +theorem expanderOutput_eq {n e : Nat} (d : Nat) (H : ExpanderTables.Table n e) (v : Fin n) : + expanderOutput d H v = encodeWords ((List.ofFn (expanderRow d H v)).flatMap rowWords) := + MachineOverlayRows.streamOutput_expanderRows d H v + +theorem outputBlock_eq {n d e : Nat} (G : PortTables.Table n d) + (H : ExpanderTables.Table n e) (v : Fin n) : + outputBlock G H v = encodeWords ((vertexRows G H v).flatMap rowWords) := by + rw [outputBlock, oldOutput_eq, expanderOutput_eq] + simp only [vertexRows, List.flatMap_append, encodeWords_append] + +theorem graphRows_blocks {n d : Nat} (G : PortTables.Table n d) : + MachineTableSplit.rowsBits (PortTables.graphTable G) = (List.ofFn (oldBlock G)).flatten := by + change encodeWords ((PortTables.flatRows G).toList.flatMap rowWords) = _ + rw [PreprocessingLazyWords.flatRows_list, encodeWords_flatten_flatMap, List.map_ofFn] + apply congrArg List.flatten + apply congrArg List.ofFn + funext v + exact (MachineLazyRows.recordsInput_eq_codec (oldRows G v)).symm + +theorem expanderRows_blocks {n e : Nat} (H : ExpanderTables.Table n e) : + encodeWords (ExpanderTableWords.rotationWords H) = (List.ofFn (expanderBlock H)).flatten := by + rw [rotationWords_vertices, encodeWords_flatten, List.map_ofFn] + rfl + +theorem tableBits_blocks {n d e : Nat} (G : PortTables.Table n d) + (H : ExpanderTables.Table n e) : + PortTables.tableBits (PreprocessingOverlayTables.overlay G H) = + encodeWords [n, n * (d + e)] ++ (List.ofFn (outputBlock G H)).flatten := by + rw [tableBits_overlay, encodeWords_append, encodeWords_flatten_flatMap, List.map_ofFn] + congr 1 + apply congrArg List.flatten + apply congrArg List.ofFn + funext v + exact (outputBlock_eq G H v).symm + +def remaining {n : Nat} (block : Fin n → List Bool) (k : Nat) : List Bool := + ((List.ofFn block).drop k).flatten +def emittedPrefix {n : Nat} (block : Fin n → List Bool) (k : Nat) : List Bool := + ((List.ofFn block).take k).flatten + +theorem remaining_step {n : Nat} (block : Fin n → List Bool) (v : Fin n) : + remaining block v.val = block v ++ remaining block (v.val + 1) := by + have hs := List.getElem_cons_drop (as := List.ofFn block) (i := v.val) + (by simpa only [List.length_ofFn] using v.isLt) + unfold remaining + rw [← hs] + simp only [List.flatten_cons, List.getElem_ofFn, Fin.eta] + +theorem prefix_step {n : Nat} (block : Fin n → List Bool) (v : Fin n) : + emittedPrefix block (v.val + 1) = emittedPrefix block v.val ++ block v := by + unfold emittedPrefix + rw [List.take_succ_eq_append_getElem (by simpa only [List.length_ofFn] using v.isLt)] + simp only [List.flatten_append, List.flatten_cons, List.flatten_nil, List.append_nil, + List.getElem_ofFn, Fin.eta] + +@[simp] theorem remaining_zero {n : Nat} (block : Fin n → List Bool) : + remaining block 0 = (List.ofFn block).flatten := by simp [remaining] +@[simp] theorem remaining_end {n : Nat} (block : Fin n → List Bool) : + remaining block n = [] := by + unfold remaining + rw [List.drop_eq_nil_iff.mpr (by simpa only [List.length_ofFn] using (Nat.le_refl n)), List.flatten_nil] +@[simp] theorem prefix_zero {n : Nat} (block : Fin n → List Bool) : emittedPrefix block 0 = [] := by + simp [emittedPrefix] +@[simp] theorem prefix_end {n : Nat} (block : Fin n → List Bool) : + emittedPrefix block n = (List.ofFn block).flatten := by + unfold emittedPrefix + have ht : (List.ofFn block).take n = List.ofFn block := + List.take_of_length_le (by simpa only [List.length_ofFn] using (Nat.le_refl n)) + rw [ht] + +theorem oldFrame {n m : Nat} (g h gs hs nv mv f v out : List Bool) + (rows : List (DartRow n m)) : + MachineLazyRows.streamFrame oldTapes (memory g h gs hs nv mv f v [] []) rows out = + memory g h (MachineLazyRows.recordsInput rows ++ gs) hs nv mv f v [] out := by + funext k + rcases k with i | i <;> fin_cases i <;> + simp [MachineLazyRows.streamFrame, oldTapes, memory, tail, oldReverse, relation, + scratch, dividedCopy, quotient, newReverse, output, rowBuffer, graphStream] + +theorem expanderFrame (g h gs hs nv mv f v t out : List Bool) (words : List Nat) : + MachineOverlayRows.streamFrame expanderTapes (memory g h gs hs nv mv f v t []) words out = + memory g h gs (encodeWords words ++ hs) nv mv f v t out := by + funext k + rcases k with i | i <;> fin_cases i <;> + simp [MachineOverlayRows.streamFrame, expanderTapes, memory, tail, oldReverse, + relation, scratch, dividedCopy, quotient, newReverse, output, rowBuffer, expanderStream] + +theorem oldVertexTrace {n : Nat} (d e : Nat) (hd : 0 < d) (he : 0 < e) + (G : PortTables.Table n d) (v : Fin n) (g h gs hs nv mv f current out : List Bool) (a : A) : + (advance (TM2.step (program d e hd he)))^[MachineLazyRows.vertexSteps d (d + e) 0 (oldRows G v) out] + (some ⟨next (.old (0, none)), clean d e hd he a, + memory g h (oldBlock G v ++ gs) hs nv mv f current [] out⟩) = + some ⟨next .tailSeed, clean d e hd he a, + memory g h gs hs nv mv f current [] (out ++ oldOutput G e v)⟩ := by + have hrun := MachineLazyRows.vertexTrace d hd (d + e) 0 oldTapes oldTapes_injective + (fun stage => .inr (.old stage)) (next .tailSeed) (program d e hd he) (fun _ => rfl) + (memory g h gs hs nv mv f current [] []) (row G v) + (by + intro i hi7 hi9 + fin_cases i <;> simp_all [oldTapes, memory, tail, oldReverse, relation, scratch, + dividedCopy, quotient, newReverse, output, rowBuffer, graphStream]) + (a, MachineFixedDivMod.residue e he 0) out + simpa only [next, oldFrame, MachineLazyRows.recordsInput, List.flatMap_nil, List.nil_append, + clean, oldBlock, oldRows, oldOutput] using hrun + +theorem expanderVertexTrace {n : Nat} (d e : Nat) (hd : 0 < d) (he : 0 < e) + (H : ExpanderTables.Table n e) (v : Fin n) (g h gs hs nv mv f current out : List Bool) (a : A) : + (advance (TM2.step (program d e hd he)))^[MachineOverlayRows.vertexSteps d e v.val + (List.ofFn (expanderValues H v)) out] + (some ⟨next (.expander (0, none)), clean d e hd he a, + memory g h gs (expanderBlock H v ++ hs) nv mv f current (encodeWord v.val) out⟩) = + some ⟨next .drainTail, clean d e hd he a, + memory g h gs hs nv mv f current (encodeWord v.val) (out ++ expanderOutput d H v)⟩ := by + let source := MachineStateEquiv.program (expanderState A d e).symm (program d e hd he) + have code (stage : MachineOverlayRows.VertexLabel e) : source (.inr (.expander stage)) = + MachineOverlayRows.vertexInstruction d e he expanderTapes + (fun stage => .inr (.expander stage)) (next .drainTail) stage := by + change MachineStateEquiv.statement (expanderState A d e).symm + (MachineStateEquiv.statement (expanderState A d e) _) = _ + exact MachineStateEquiv.statement_symm_statement _ _ + have native := MachineOverlayRows.vertexTrace d e he expanderTapes expanderTapes_injective + (fun stage => .inr (.expander stage)) (next .drainTail) source code + (memory g h gs hs nv mv f current (encodeWord v.val) []) v.val (expanderValues H v) + rfl + (by + intro i hi0 hi7 hi9 + fin_cases i <;> simp_all [expanderTapes, memory, tail, oldReverse, relation, scratch, + dividedCopy, quotient, newReverse, output, rowBuffer, expanderStream]) + ((a, MachineRegularOriginalRow.zeroBuffer), MachineFixedDivMod.residue d hd 0) out + have transported := MachineStateEquiv.trace (expanderState A d e) source _ _ _ native + have back : MachineStateEquiv.program (expanderState A d e) source = program d e hd he := + MachineStateEquiv.program_symm_program (expanderState A d e).symm _ + rw [back] at transported + simpa only [next, MachineStateEquiv.configuration, expanderState_clean, expanderFrame, + encodeWords, List.nil_append, expanderBlock, expanderOutput] using transported + +theorem tailCopyTrace (d e : Nat) (hd : 0 < d) (he : 0 < e) + (g h gs hs nv mv f out : List Bool) (k : Nat) (a : A) : + (advance (TM2.step (program d e hd he)))^[2 * (k + 1) + 1] + (some ⟨next .tailSeed, clean d e hd he a, + memory g h gs hs nv mv f (encodeWord k) [] out⟩) = + some ⟨next (.expander (0, none)), clean d e hd he a, + memory g h gs hs nv mv f (encodeWord k) (encodeWord k) out⟩ := by + let ambient := (clean d e hd he a).1 + have hrun := MachineUnaryAffineAt.seededAffineTrace vertex scratch tail + (by decide) (by decide) (by decide) 1 0 + (.inr .tailSeed) (.inr .tailScan) (.inr .tailRestore) (next (.expander (0, none))) + (program d e hd he) rfl rfl rfl + (memory g h gs hs nv mv f (encodeWord k) [] out) k [] + (by simp [memory, vertex]) rfl ambient none + simpa only [memory_tail, next, List.append_nil, Nat.one_mul, Nat.add_zero, update_tail, + ambient, clean, MachineLazyRows.streamClean, MachinePortReindex.clean] using hrun + +theorem tailFinishTrace (d e : Nat) (hd : 0 < d) (he : 0 < e) + (g h gs hs nv mv f out : List Bool) (k : Nat) (a : A) : + (advance (TM2.step (program d e hd he)))^[k + 3] + (some ⟨next .drainTail, clean d e hd he a, + memory g h gs hs nv mv f (encodeWord k) (encodeWord k) out⟩) = + some ⟨next .guard, clean d e hd he a, + memory g h gs hs nv mv f (encodeWord (k + 1)) [] out⟩ := by + let ambient := (clean d e hd he a).1 + have hd₀ := MachineDrain.drainTrace tail (.inr .drainTail) (next .increment) + (program d e hd he) rfl (memory g h gs hs nv mv f (encodeWord k) [] out) + (encodeWord k) ambient none + have drain : (advance (TM2.step (program d e hd he)))^[k + 2] + (some ⟨next .drainTail, clean d e hd he a, + memory g h gs hs nv mv f (encodeWord k) (encodeWord k) out⟩) = + some ⟨next .increment, clean d e hd he a, + memory g h gs hs nv mv f (encodeWord k) [] out⟩ := by + simpa only [next, encodeWord_length, Nat.add_assoc, update_tail, ambient, clean, + MachineLazyRows.streamClean, MachinePortReindex.clean] using hd₀ + have increment : (advance (TM2.step (program d e hd he)))^[1] + (some ⟨next .increment, clean d e hd he a, + memory g h gs hs nv mv f (encodeWord k) [] out⟩) = + some ⟨next .guard, clean d e hd he a, + memory g h gs hs nv mv f (encodeWord (k + 1)) [] out⟩ := by + change some (TM2.stepAux (program d e hd he (.inr .increment)) _ _) = _ + simp only [program, mainInstruction, TM2.stepAux, memory_vertex, next, + update_vertex, encodeWord, List.replicate_succ, List.cons_append] + have all := joinTrace drain increment + simpa only [Nat.add_assoc] using all + +def pairSteps {n d e : Nat} (G : PortTables.Table n d) (H : ExpanderTables.Table n e) + (v : Fin n) (out : List Bool) : Nat := + MachineLazyRows.vertexSteps d (d + e) 0 (oldRows G v) out + (2 * (v.val + 1) + 1) + + MachineOverlayRows.vertexSteps d e v.val (List.ofFn (expanderValues H v)) + (out ++ oldOutput G e v) + (v.val + 3) + +theorem pairTrace {n : Nat} (d e : Nat) (hd : 0 < d) (he : 0 < e) + (G : PortTables.Table n d) (H : ExpanderTables.Table n e) (v : Fin n) + (g h gs hs nv mv f out : List Bool) (a : A) : + (advance (TM2.step (program d e hd he)))^[pairSteps G H v out] + (some ⟨next (.old (0, none)), clean d e hd he a, + memory g h (oldBlock G v ++ gs) (expanderBlock H v ++ hs) + nv mv f (encodeWord v.val) [] out⟩) = + some ⟨next .guard, clean d e hd he a, + memory g h gs hs nv mv f (encodeWord (v.val + 1)) [] (out ++ outputBlock G H v)⟩ := by + have h₁ := oldVertexTrace d e hd he G v g h gs (expanderBlock H v ++ hs) + nv mv f (encodeWord v.val) out a + have h₂ := tailCopyTrace d e hd he g h gs (expanderBlock H v ++ hs) + nv mv f (out ++ oldOutput G e v) v.val a + have h₃ := expanderVertexTrace d e hd he H v g h gs hs nv mv f + (encodeWord v.val) (out ++ oldOutput G e v) a + have h₄ := tailFinishTrace d e hd he g h gs hs nv mv f + ((out ++ oldOutput G e v) ++ expanderOutput d H v) v.val a + simpa only [pairSteps, outputBlock, List.append_assoc] using + joinTrace (joinTrace (joinTrace h₁ h₂) h₃) h₄ + +def cleanupSteps (n m : Nat) : Nat := 2 * n + m + 8 + +theorem cleanupTrace (d e : Nat) (hd : 0 < d) (he : 0 < e) + (g h out : List Bool) (n m : Nat) (a : A) : + (advance (TM2.step (program d e hd he)))^[cleanupSteps n m] + (some ⟨next .drainFuel, clean d e hd he a, + memory g h [] [] (encodeWord n) (encodeWord m) (encodeWord 0) (encodeWord n) [] out⟩) = + some ⟨none, clean d e hd he a, memory g h [] [] [] [] [] [] [] out⟩ := by + let ambient := (clean d e hd he a).1 + have h₁ := MachineDrain.drainTrace fuel (.inr .drainFuel) (next .drainVertex) + (program d e hd he) rfl + (memory g h [] [] (encodeWord n) (encodeWord m) [] (encodeWord n) [] out) + (encodeWord 0) ambient none + have h₂ := MachineDrain.drainTrace vertex (.inr .drainVertex) (next .drainVertexCount) + (program d e hd he) rfl + (memory g h [] [] (encodeWord n) (encodeWord m) [] [] [] out) + (encodeWord n) ambient none + have h₃ := MachineDrain.drainTrace vertexCount (.inr .drainVertexCount) (next .drainDartCount) + (program d e hd he) rfl (memory g h [] [] [] (encodeWord m) [] [] [] out) + (encodeWord n) ambient none + have h₄ := MachineDrain.drainTrace dartCount (.inr .drainDartCount) none + (program d e hd he) rfl (memory g h [] [] [] [] [] [] [] out) + (encodeWord m) ambient none + simp only [encodeWord_length, update_fuel, update_vertex, update_vertexCount, update_dartCount] at h₁ h₂ h₃ h₄ + have all := joinTrace (joinTrace (joinTrace h₁ h₂) h₃) h₄ + have hsteps : cleanupSteps n m = ((0 + 1 + 1 + (n + 1 + 1)) + (n + 1 + 1)) + (m + 1 + 1) := by + unfold cleanupSteps + omega + rw [hsteps] + exact all + +def rawExpander {n e : Nat} (H : ExpanderTables.Table n e) : List Bool := + encodeWords (ExpanderTableWords.rotationWords H) + +def outputPrefix {n d e : Nat} (G : PortTables.Table n d) (H : ExpanderTables.Table n e) + (k : Nat) : List Bool := encodeWords [n, n * (d + e)] ++ emittedPrefix (outputBlock G H) k + +theorem outputPrefix_step {n d e : Nat} (G : PortTables.Table n d) + (H : ExpanderTables.Table n e) (v : Fin n) : + outputPrefix G H (v.val + 1) = outputPrefix G H v.val ++ outputBlock G H v := by + simp only [outputPrefix, prefix_step, List.append_assoc] + +def loopBase {n d e : Nat} (G : PortTables.Table n d) (H : ExpanderTables.Table n e) + (r : Nat) : Tape → List Bool := + memory (PortTables.tableBits G) (rawExpander H) + (remaining (oldBlock G) (n - r)) (remaining (expanderBlock H) (n - r)) + (encodeWord n) (encodeWord (n * d)) [] (encodeWord (n - r)) [] (outputPrefix G H (n - r)) + +def loopCost {n d e : Nat} (G : PortTables.Table n d) (H : ExpanderTables.Table n e) + (r : Nat) : Nat := + if hr : r < n then + pairSteps G H ⟨n - (r + 1), by omega⟩ (outputPrefix G H (n - (r + 1))) + else 0 + +theorem loopBodyTraces {n : Nat} (d e : Nat) (hd : 0 < d) (he : 0 < e) + (G : PortTables.Table n d) (H : ExpanderTables.Table n e) (a : A) : + MachineCountedLoop.BodyTraces fuel (.inr .guard) (.inr (.old (0, none))) + (program d e hd he) [] (fun _ => (clean d e hd he a).1) (fun _ => none) + (loopBase G H) (loopCost G H) n := by + intro r hr + let v : Fin n := ⟨n - (r + 1), by omega⟩ + have hv : v.val + 1 = n - r := by dsimp [v]; omega + have hinput : MachineUnaryCounter.counterTapes fuel (loopBase G H (r + 1)) r [] = + memory (PortTables.tableBits G) (rawExpander H) + (oldBlock G v ++ remaining (oldBlock G) (v.val + 1)) + (expanderBlock H v ++ remaining (expanderBlock H) (v.val + 1)) + (encodeWord n) (encodeWord (n * d)) (encodeWord r) (encodeWord v.val) [] + (outputPrefix G H v.val) := by + simp only [MachineUnaryCounter.counterTapes, loopBase, List.append_nil, update_fuel] + change memory _ _ (remaining (oldBlock G) v.val) (remaining (expanderBlock H) v.val) + _ _ _ _ _ _ = _ + rw [remaining_step (oldBlock G) v, remaining_step (expanderBlock H) v] + have houtput : MachineUnaryCounter.counterTapes fuel (loopBase G H r) r [] = + memory (PortTables.tableBits G) (rawExpander H) + (remaining (oldBlock G) (v.val + 1)) (remaining (expanderBlock H) (v.val + 1)) + (encodeWord n) (encodeWord (n * d)) (encodeWord r) (encodeWord (v.val + 1)) [] + (outputPrefix G H v.val ++ outputBlock G H v) := by + simp only [MachineUnaryCounter.counterTapes, loopBase, List.append_nil, update_fuel] + rw [← hv, outputPrefix_step] + have run := pairTrace d e hd he G H v (PortTables.tableBits G) (rawExpander H) + (remaining (oldBlock G) (v.val + 1)) (remaining (expanderBlock H) (v.val + 1)) + (encodeWord n) (encodeWord (n * d)) (encodeWord r) (outputPrefix G H v.val) a + change (advance (TM2.step (program d e hd he)))^[loopCost G H r] + (some ⟨next (.old (0, none)), clean d e hd he a, + MachineUnaryCounter.counterTapes fuel (loopBase G H (r + 1)) r []⟩) = + some ⟨next .guard, clean d e hd he a, + MachineUnaryCounter.counterTapes fuel (loopBase G H r) r []⟩ + rw [hinput, houtput] + simpa only [loopCost, dite_eq_left hr, v] using run + +theorem loopTrace {n : Nat} (d e : Nat) (hd : 0 < d) (he : 0 < e) + (G : PortTables.Table n d) (H : ExpanderTables.Table n e) (a : A) : + (advance (TM2.step (program d e hd he)))^[MachineCountedLoop.totalSteps (loopCost G H) n] + (some ⟨next .guard, clean d e hd he a, + memory (PortTables.tableBits G) (rawExpander H) + (MachineTableSplit.rowsBits (PortTables.graphTable G)) (rawExpander H) + (encodeWord n) (encodeWord (n * d)) (encodeWord n) (encodeWord 0) [] + (encodeWords [n, n * (d + e)])⟩) = + some ⟨next .drainFuel, clean d e hd he a, + memory (PortTables.tableBits G) (rawExpander H) [] [] + (encodeWord n) (encodeWord (n * d)) (encodeWord 0) (encodeWord n) [] + (PortTables.tableBits (PreprocessingOverlayTables.overlay G H))⟩ := by + have run := MachineCountedLoop.loopTrace fuel (.inr .guard) (.inr (.old (0, none))) + (.inr .drainFuel) (program d e hd he) rfl [] + (fun _ => (clean d e hd he a).1) (fun _ => none) (loopBase G H) (loopCost G H) n + (loopBodyTraces d e hd he G H a) + have startFrame : MachineUnaryCounter.counterTapes fuel (loopBase G H n) n [] = + memory (PortTables.tableBits G) (rawExpander H) + (MachineTableSplit.rowsBits (PortTables.graphTable G)) (rawExpander H) + (encodeWord n) (encodeWord (n * d)) (encodeWord n) (encodeWord 0) [] + (encodeWords [n, n * (d + e)]) := by + simp only [MachineUnaryCounter.counterTapes, loopBase, List.append_nil, update_fuel, + Nat.sub_self, remaining_zero, outputPrefix, prefix_zero] + simp only [graphRows_blocks, rawExpander, expanderRows_blocks] + have endFrame : MachineUnaryCounter.counterTapes fuel (loopBase G H 0) 0 [] = + memory (PortTables.tableBits G) (rawExpander H) [] [] + (encodeWord n) (encodeWord (n * d)) (encodeWord 0) (encodeWord n) [] + (PortTables.tableBits (PreprocessingOverlayTables.overlay G H)) := by + simp only [MachineUnaryCounter.counterTapes, loopBase, List.append_nil, update_fuel, + Nat.sub_zero, remaining_end, outputPrefix, prefix_end, tableBits_blocks] + simp only [MachineCountedLoop.guardConfiguration, MachineCountedLoop.exitConfiguration] at run + rw [startFrame, endFrame] at run + simpa only [next, clean, MachineLazyRows.streamClean, MachinePortReindex.clean] using run + +def tableSteps {n d e : Nat} (G : PortTables.Table n d) (H : ExpanderTables.Table n e) : Nat := + MachineTableSplit.exactSteps n (n * d) (MachineTableSplit.rowsBits (PortTables.graphTable G)) + + preparationSteps n (rawExpander H) + MachineCountedLoop.totalSteps (loopCost G H) n + + cleanupSteps n (n * d) + +theorem tableTrace {n : Nat} (d e : Nat) (hd : 0 < d) (he : 0 < e) + (G : PortTables.Table n d) (H : ExpanderTables.Table n e) (a : A) : + (advance (TM2.step (program d e hd he)))^[tableSteps G H] + (some ⟨some (.inl .copyFirst), clean d e hd he a, + initialTapes (PortTables.tableBits G) (rawExpander H)⟩) = + some ⟨none, clean d e hd he a, + memory (PortTables.tableBits G) (rawExpander H) [] [] [] [] [] [] [] + (PortTables.tableBits (PreprocessingOverlayTables.overlay G H))⟩ := by + have h₁ := splitTrace d e hd he (PortTables.graphTable G) (rawExpander H) a + rw [splitTapes_memory] at h₁ + have header : encodeWords [n, n * d] ++ MachineTableSplit.rowsBits (PortTables.graphTable G) = + PortTables.tableBits G := (MachineTableSplit.tableBits_header_rows (PortTables.graphTable G)).symm + change (advance (TM2.step (program d e hd he)))^[MachineTableSplit.exactSteps n (n * d) + (MachineTableSplit.rowsBits (PortTables.graphTable G))] + (some ⟨some (.inl .copyFirst), clean d e hd he a, + initialTapes (PortTables.tableBits G) (rawExpander H)⟩) = + some ⟨next .copyHFirst, clean d e hd he a, + memory (encodeWords [n, n * d] ++ MachineTableSplit.rowsBits (PortTables.graphTable G)) + (rawExpander H) (MachineTableSplit.rowsBits (PortTables.graphTable G)) [] + (encodeWord n) (encodeWord (n * d)) [] [] [] []⟩ at h₁ + rw [header] at h₁ + have h₂ := preparationTrace d e hd he (PortTables.tableBits G) (rawExpander H) + (MachineTableSplit.rowsBits (PortTables.graphTable G)) n (n * d) a + have h₃ := loopTrace d e hd he G H a + have h₄ := cleanupTrace d e hd he (PortTables.tableBits G) (rawExpander H) + (PortTables.tableBits (PreprocessingOverlayTables.overlay G H)) n (n * d) a + exact joinTrace (joinTrace (joinTrace h₁ h₂) h₃) h₄ + +private theorem flatMap_length_le {α : Type*} (items : List α) (f : α → List Bool) + (B : Nat) (bounded : ∀ x ∈ items, (f x).length ≤ B) : + (items.flatMap f).length ≤ items.length * B := by + induction items with + | nil => simp + | cons x xs ih => + have hx := bounded x (by simp) + have ht := ih (fun y hy => bounded y (by simp [hy])) + simp only [List.flatMap_cons, List.length_append, List.length_cons] + rw [Nat.add_mul, Nat.one_mul] + omega + +private theorem flatten_length_le (items : List (List Bool)) (B : Nat) + (bounded : ∀ x ∈ items, x.length ≤ B) : items.flatten.length ≤ items.length * B := by + simpa only [List.flatMap_id] using flatMap_length_le items id B bounded + +def oldSize (d e n : Nat) : Nat := MachineLazyRows.rowSizeBound (d + e) 0 n (n * d) +def expanderSize (d e n : Nat) : Nat := MachineOverlayRows.rowSizeBound d e n (n * e) +def blockSize (d e n : Nat) : Nat := d * oldSize d e n + e * expanderSize d e n + +theorem oldOutput_length_le {n d : Nat} (G : PortTables.Table n d) (e : Nat) (v : Fin n) : + (oldOutput G e v).length ≤ d * oldSize d e n := by + have bound := flatMap_length_le (oldRows G v) + (fun r => MachineLazyRows.reindexRowBits d (d + e) 0 r.tail.val r.reverseIndex.val r.relation) + (oldSize d e n) (fun r _ => MachineLazyRows.reindexRowBits_length_le d (d + e) 0 r) + simpa only [oldOutput, MachineLazyRows.recordsOutput, oldRows, List.length_ofFn] using bound + +theorem expanderOutput_length_le {n e : Nat} (d : Nat) (H : ExpanderTables.Table n e) + (v : Fin n) : (expanderOutput d H v).length ≤ e * expanderSize d e n := by + have bound := flatMap_length_le (List.ofFn (expanderValues H v)) + (MachineOverlayRows.rowBits d e v.val) (expanderSize d e n) (by + intro j hj + obtain ⟨p, rfl⟩ := List.mem_ofFn.mp hj + have hrow := MachineOverlayRows.rowBits_length_le d e v.val (expanderValues H v p) + (n * e) (MachineOverlayRows.expanderValues_bounded H v p) + have hv := v.isLt.le + unfold expanderSize MachineOverlayRows.rowSizeBound at * + omega) + simpa only [expanderOutput, MachineOverlayRows.streamOutput, List.length_ofFn] using bound + +theorem outputBlock_length_le {n d e : Nat} (G : PortTables.Table n d) + (H : ExpanderTables.Table n e) (v : Fin n) : + (outputBlock G H v).length ≤ blockSize d e n := by + have hg := oldOutput_length_le G e v + have hh := expanderOutput_length_le d H v + simp only [outputBlock, List.length_append, blockSize] + omega + +def outputCapacity (d e n : Nat) : Nat := n + n * (d + e) + 2 + n * blockSize d e n + +theorem outputPrefix_length_le {n d e : Nat} (G : PortTables.Table n d) + (H : ExpanderTables.Table n e) (k : Nat) : + (outputPrefix G H k).length ≤ outputCapacity d e n := by + have hblocks := flatten_length_le ((List.ofFn (outputBlock G H)).take k) + (blockSize d e n) (by + intro xs hx + have hm := List.mem_of_mem_take hx + obtain ⟨v, rfl⟩ := List.mem_ofFn.mp hm + exact outputBlock_length_le G H v) + have hlen : ((List.ofFn (outputBlock G H)).take k).length ≤ n := by + simp only [List.length_take, List.length_ofFn] + exact Nat.min_le_right _ _ + have hcap := Nat.mul_le_mul_right (blockSize d e n) hlen + simp only [outputPrefix, emittedPrefix, List.length_append, encodeWords_length, + List.sum_cons, List.sum_nil, List.length_cons, List.length_nil, Nat.add_zero, outputCapacity] + omega + +def pairBudget (d e n : Nat) : Nat := + (d * (MachineLazyRows.rowCostBound (d + e) 0 n (n * d) + + 2 * (outputCapacity d e n + d * oldSize d e n) + 1) + 1) + + (e * (MachineOverlayRows.rowCostBound d e n (n * e) + + 2 * (outputCapacity d e n + d * oldSize d e n + e * expanderSize d e n) + 1) + 1) + + (3 * n + 6) + +theorem pairSteps_le {n d e : Nat} (G : PortTables.Table n d) + (H : ExpanderTables.Table n e) (v : Fin n) (out : List Bool) + (hout : out.length ≤ outputCapacity d e n) : pairSteps G H v out ≤ pairBudget d e n := by + have hold := MachineLazyRows.vertexSteps_le d (d + e) 0 (oldRows G v) out + simp only [oldRows, List.length_ofFn] at hold + have hgsize := oldOutput_length_le G e v + have hnew := MachineOverlayRows.vertexSteps_le d e v.val (n * e) + (List.ofFn (expanderValues H v)) (by + intro j hj + obtain ⟨p, rfl⟩ := List.mem_ofFn.mp hj + exact MachineOverlayRows.expanderValues_bounded H v p) (out ++ oldOutput G e v) + simp only [List.length_ofFn, List.length_append] at hnew + have hv := v.isLt.le + have hsize : MachineOverlayRows.rowSizeBound d e v.val (n * e) ≤ expanderSize d e n := by + unfold expanderSize MachineOverlayRows.rowSizeBound + omega + have hcost : MachineOverlayRows.rowCostBound d e v.val (n * e) ≤ + MachineOverlayRows.rowCostBound d e n (n * e) := by + unfold MachineOverlayRows.rowCostBound + change _ ≤ 8 * (n * e) + 4 * expanderSize d e n + _ + _ + 28 + omega + have hsizeMul := Nat.mul_le_mul_left e hsize + have holdBudget := Nat.mul_le_mul_left d + (show MachineLazyRows.rowCostBound (d + e) 0 n (n * d) + + 2 * (out.length + d * MachineLazyRows.rowSizeBound (d + e) 0 n (n * d)) + 1 ≤ + MachineLazyRows.rowCostBound (d + e) 0 n (n * d) + + 2 * (outputCapacity d e n + d * oldSize d e n) + 1 by + unfold oldSize + omega) + have hnewBudget := Nat.mul_le_mul_left e + (show MachineOverlayRows.rowCostBound d e v.val (n * e) + + 2 * (out.length + (oldOutput G e v).length + e * MachineOverlayRows.rowSizeBound d e v.val (n * e)) + 1 ≤ + MachineOverlayRows.rowCostBound d e n (n * e) + + 2 * (outputCapacity d e n + d * oldSize d e n + e * expanderSize d e n) + 1 by omega) + unfold pairSteps pairBudget oldRows + omega + +theorem loopSteps_le {n d e : Nat} (G : PortTables.Table n d) (H : ExpanderTables.Table n e) : + MachineCountedLoop.totalSteps (loopCost G H) n ≤ n * (pairBudget d e n + 1) + 1 := by + apply MachineCountedLoop.totalSteps_le + intro r hr + rw [loopCost, dite_eq_left hr] + exact pairSteps_le G H _ _ (outputPrefix_length_le G H _) + +noncomputable def phasePolynomial (d e : Nat) : Polynomial Nat := + let x := Polynomial.X + let C := Polynomial.C (R := Nat) + let oldValue := C (d + e) * (x * C d) + x * C d + C 0 + let os := x + oldValue + C 8194 + let newValue := C (d + e) * (x * C e) + x * C e + C d + let es := x + newValue + C MachineOverlayRows.trueBits.length + C 2 + let block := C d * os + C e * es + let cap := x + x * C (d + e) + C 2 + x * block + let oldCost := C 2 * x + C 8 * (x * C d) + oldValue + C 4 * os + C 8224 + let newCost := C 8 * (x * C e) + C 4 * es + newValue + C MachineOverlayRows.trueBits.length + C 28 + let pair := (C d * (oldCost + C 2 * (cap + C d * os) + C 1) + C 1) + + (C e * (newCost + C 2 * (cap + C d * os + C e * es) + C 1) + C 1) + + (C 3 * x + C 6) + x * (pair + C 1) + C 1 + (C 2 * x + x * C d + C 8) + +@[simp] theorem phasePolynomial_eval (d e n : Nat) : + (phasePolynomial d e).eval n = n * (pairBudget d e n + 1) + 1 + cleanupSteps n (n * d) := by + simp only [phasePolynomial, Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_C, + Polynomial.eval_X, pairBudget, outputCapacity, blockSize, oldSize, expanderSize, + MachineLazyRows.rowSizeBound, MachineLazyRows.rowCostBound, MachineLazyRows.valueBound, + MachineOverlayRows.rowSizeBound, MachineOverlayRows.rowCostBound, + MachineOverlayRows.valueBound, cleanupSteps] + +noncomputable def timePolynomial (d e : Nat) : Polynomial Nat := + Polynomial.C 12 * Polynomial.X + Polynomial.C 18 + phasePolynomial d e + +theorem tableSteps_le {n d e : Nat} (G : PortTables.Table n d) (H : ExpanderTables.Table n e) : + tableSteps G H ≤ (timePolynomial d e).eval ((PortTables.tableBits G).length + (rawExpander H).length) := by + have hsplit := MachineTableSplit.exactSteps_le n (n * d) + (MachineTableSplit.rowsBits (PortTables.graphTable G)) + have header : encodeWords [n, n * d] ++ MachineTableSplit.rowsBits (PortTables.graphTable G) = + PortTables.tableBits G := (MachineTableSplit.tableBits_header_rows (PortTables.graphTable G)).symm + rw [header, MachineTableSplit.timePolynomial_eval] at hsplit + have hn := PortTables.vertices_le_tableBits_length G + have hloop := loopSteps_le G H + have hmono := natPolynomial_eval_mono (phasePolynomial d e) + (show n ≤ (PortTables.tableBits G).length + (rawExpander H).length by omega) + rw [phasePolynomial_eval] at hmono + simp only [timePolynomial, Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_C, + Polynomial.eval_X] + unfold tableSteps preparationSteps + omega + +def tableInTime {n : Nat} (d e : Nat) (hd : 0 < d) (he : 0 < e) + (G : PortTables.Table n d) (H : ExpanderTables.Table n e) (a : A) : + StateTransition.EvalsToInTime (TM2.step (program d e hd he)) + ⟨some (.inl .copyFirst), clean d e hd he a, + initialTapes (PortTables.tableBits G) (rawExpander H)⟩ + (some ⟨none, clean d e hd he a, + memory (PortTables.tableBits G) (rawExpander H) [] [] [] [] [] [] [] + (PortTables.tableBits (PreprocessingOverlayTables.overlay G H))⟩) + ((timePolynomial d e).eval ((PortTables.tableBits G).length + (rawExpander H).length)) where + steps := tableSteps G H + evals_in_steps := tableTrace d e hd he G H a + steps_le_m := tableSteps_le G H + +def machine (d e : Nat) (hd : 0 < d) (he : 0 < e) : FinTM2 where + K := Tape + k₀ := graphArchive + k₁ := output + Γ _ := Bool + Λ := Label d e + main := .inl .copyFirst + σ := State Unit d e + initialState := clean d e hd he () + m := program d e hd he + +theorem machine_alphabet_finite (d e : Nat) (hd : 0 < d) (he : 0 < e) : + ∀ k, Finite ((machine d e hd he).Γ k) := fun _ => inferInstanceAs (Finite Bool) + +end MinUncutGames.Foundations.Complexity.MachineOverlayTable + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachinePaddedExpanderFamilyBounds.lean b/lean/OAI/Computability/MinUncut/Machines/MachinePaddedExpanderFamilyBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..b09aeb44d3da9d94fa31cb4d382a4f895c95db6d --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachinePaddedExpanderFamilyBounds.lean @@ -0,0 +1,882 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineExpanderFamilyCycle + +namespace OAI + +section +namespace MinUncutGames.Foundations.Complexity.MachinePaddedExpanderFamilyBounds + +open PCP.ExpanderTables PCP.ExpanderRowControl PCP.ExpanderTableWords + +def timeCoefficient : Nat := + MachineExpanderFamilyBounds.inputCoefficient + PCP.ExpanderFamily.growth + 29 + +noncomputable def timePolynomial : Polynomial Nat := + Polynomial.C timeCoefficient * Polynomial.X^5 + +theorem timePolynomial_encoding (k : Nat) : + timePolynomial.eval (encodeWord k).length = timeCoefficient * (k + 1)^5 := by + simp only [timePolynomial, Polynomial.eval_mul, Polynomial.eval_C, + Polynomial.eval_pow, Polynomial.eval_X, encodeWord_length] + +theorem ceilingCost_le (g k : Nat) : + (MachineCeilingPower.timePolynomial g).eval (encodeWord k).length ≤ + (g + 29) * (k + 1)^5 := by + rw [MachineCeilingPower.timePolynomial_encoding] + have squareBound : (k + 1)^2 ≤ (k + 1)^5 := + Nat.pow_le_pow_right (Nat.succ_pos k) (by decide) + have linearBound : k + 1 ≤ (k + 1)^5 := by + simpa only [pow_one] using Nat.pow_le_pow_right + (Nat.succ_pos k) (show 1 ≤ 5 by decide) + have constantBound : 1 ≤ (k + 1)^5 := by omega + have squareCost := Nat.mul_le_mul_left (g + 8) squareBound + have linearCost := Nat.mul_le_mul_left 18 linearBound + have constantCost := Nat.mul_le_mul_left 3 constantBound + unfold MachineCeilingPower.timeBound + nlinarith only [squareCost, linearCost, constantCost] + +theorem combinedCost_le (k : Nat) : + (MachineCeilingPower.timePolynomial PCP.ExpanderFamily.growth).eval + (encodeWord k).length + + MachineExpanderFamilyBounds.inputCoefficient * (k + 1)^5 ≤ + timePolynomial.eval (encodeWord k).length := by + rw [timePolynomial_encoding] + have h := ceilingCost_le PCP.ExpanderFamily.growth k + unfold timeCoefficient + nlinarith only [h] + +theorem familyCost_le + (H : Table (cloudSize PCP.Expanders.baseDegree) PCP.Expanders.baseDegree) (k : Nat) : + (MachineCeilingPower.timePolynomial PCP.ExpanderFamily.growth).eval + (encodeWord k).length + + MachineExpanderFamilyBounds.familyBudget H (PCP.PreprocessingLevels.boundedLevel k) ≤ + timePolynomial.eval (encodeWord k).length := by + exact (Nat.add_le_add_left + (MachineExpanderFamilyBounds.familyBudget_at_boundedLevel_le H k) _).trans + (combinedCost_le k) + +def outputWord + (H : Table (cloudSize PCP.Expanders.baseDegree) PCP.Expanders.baseDegree) (k : Nat) : + List Bool := + encodeWords (rotationWords (family H (PCP.PreprocessingLevels.boundedLevel k))) + +def outputCoefficient : Nat := + (PCP.ExpanderFamily.growth * degree PCP.Expanders.baseDegree + 1)^2 + +theorem outputWord_length_le + (H : Table (cloudSize PCP.Expanders.baseDegree) PCP.Expanders.baseDegree) (k : Nat) : + (outputWord H k).length ≤ outputCoefficient * (k + 1)^2 := by + let q := degree PCP.Expanders.baseDegree + let N := vertexCount q (PCP.PreprocessingLevels.boundedLevel k) + have sizeBound : N ≤ PCP.ExpanderFamily.growth * (k + 1) := by + change vertexCount (PCP.Expanders.baseDegree * PCP.Expanders.baseDegree) + (PCP.PreprocessingLevels.boundedLevel k) ≤ _ + rw [PCP.PreprocessingLevels.table_vertexCount_eq_paddedSize] + exact MachineExpanderFamilyBounds.paddedSize_le_succ_input k + have rowBound := Nat.mul_le_mul_right q sizeBound + have rowSuccBound : N * q + 1 ≤ (PCP.ExpanderFamily.growth * q + 1) * (k + 1) := by + nlinarith only [rowBound, Nat.zero_le k] + have lengthBound : (outputWord H k).length ≤ (N * q) * (N * q + 1) := + encode_rotationWords_length_le (family H (PCP.PreprocessingLevels.boundedLevel k)) + calc + _ ≤ (N * q + 1)^2 := by nlinarith only [lengthBound, Nat.zero_le (N * q)] + _ ≤ ((PCP.ExpanderFamily.growth * q + 1) * (k + 1))^2 := + Nat.pow_le_pow_left rowSuccBound 2 + _ = _ := by unfold outputCoefficient; dsimp [q]; ring + +end MinUncutGames.Foundations.Complexity.MachinePaddedExpanderFamilyBounds + +end +section +namespace MinUncutGames.Foundations.Complexity.MachinePaddedExpanderFamily + +open Turing +open MachineCloudPadding +open MachineComposition + + +variable {ρ : Type} [Fintype ρ] + +noncomputable def ceilingInTime (H : SmallTable) (requested : Nat) + (state : MachineExpanderFamily.State ρ fixedDegree) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step (program H)) + ⟨some main, initialState state register, initialTapes requested⟩ + (some ⟨some familyEntry, (state, (false, none)), handoffTapes requested⟩) + ((MachineCeilingPower.timePolynomial PCP.ExpanderFamily.growth).eval + (encodeWord requested).length) := by + let original := MachineCeilingPower.paddingInTime requested state register + let renamed := MachineStateEquiv.execution (ceilingStates ρ) + (MachineCeilingPower.program PCP.ExpanderFamily.growth) original + let placed := liftExecutionInTime (TM2.step (ceilingSource (ρ := ρ))) + (TM2.step (program H)) + (Placement.configuration ceilingView ceilingLabel (some familyEntry) (fun _ => [])) + (Placement.step_simulation ceilingTape ceilingView ceilingView_left ceilingView_right + ceilingLabel (some familyEntry) (fun _ => []) (ceilingSource (ρ := ρ)) + (program H) (program_ceiling H)) renamed + have initialEq := ceiling_initial_configuration requested state register + have finalEq := ceiling_handoff_configuration requested state + unfold ceilingInput at initialEq + unfold ceilingOutput at finalEq + simpa only [initialEq, finalEq] using placed + +noncomputable def materializeInTime (H : SmallTable) (requested : Nat) + (state : MachineExpanderFamily.State ρ fixedDegree) : + StateTransition.EvalsToInTime (TM2.step (program H)) + ⟨some familyEntry, (state, (false, none)), handoffTapes requested⟩ + (some ⟨none, finalState H state, finalTapes H requested⟩) + (MachineExpanderFamilyBounds.inputCoefficient * (requested + 1)^5) := by + let original := MachineExpanderFamily.paddedFamilyInTime H requested state [] + let boolean := MachineAlphabetTransport.executionInTime MachineExpanderFamily.alphabet_eq + (MachineExpanderFamily.program MachineExpanderFamily.baseDegree_positive H + MachineExpanderFamily.baseDegree_cloud_gt_one) original + let framed := MachineStateFrame.frameExecution + (MachineExpanderFamily.boolView MachineExpanderFamily.baseDegree_positive H + MachineExpanderFamily.baseDegree_cloud_gt_one) (false, (none : Option Bool)) boolean + let placed := liftExecutionInTime (TM2.step (familySource H)) (TM2.step (program H)) + (Placement.configuration familyView familyLabel none (retainedFrame requested)) + (Placement.step_simulation familyTape familyView familyView_left familyView_right + familyLabel none (retainedFrame requested) (familySource H) (program H) + (program_family H)) framed + simpa only [family_initial_configuration, family_final_configuration] using placed + +noncomputable def paddedInTime (H : SmallTable) (requested : Nat) + (state : MachineExpanderFamily.State ρ fixedDegree) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step (program H)) + ⟨some main, initialState state register, initialTapes requested⟩ + (some ⟨none, finalState H state, finalTapes H requested⟩) + (MachinePaddedExpanderFamilyBounds.timePolynomial.eval (encodeWord requested).length) := by + let first := ceilingInTime H requested state register + let second := materializeInTime H requested state + let all := StateTransition.EvalsToInTime.trans (TM2.step (program H)) + _ _ _ _ _ first second + exact + { toEvalsTo := all.toEvalsTo + steps_le_m := all.steps_le_m.trans + (by simpa only [Nat.add_comm] using + MachinePaddedExpanderFamilyBounds.combinedCost_le requested) } + +noncomputable def placedInTime {K Λ : Type} [DecidableEq K] + (tape : Tape → K) (view : K → Option Tape) + (left : ∀ t, view (tape t) = some t) + (right : ∀ j t, view j = some t → tape t = j) + (labels : Label → Λ) (exit : Option Λ) (extra : K → List Bool) + (H : SmallTable) (target : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State ρ)) + (code : ∀ l, target (labels l) = Placement.statement tape labels exit (program H l)) + (requested : Nat) (state : MachineExpanderFamily.State ρ fixedDegree) + (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step target) + (Placement.configuration view labels exit extra + ⟨some main, initialState state register, initialTapes requested⟩) + (some (Placement.configuration view labels exit extra + ⟨none, finalState H state, finalTapes H requested⟩)) + (MachinePaddedExpanderFamilyBounds.timePolynomial.eval (encodeWord requested).length) := + liftExecutionInTime (TM2.step (program H)) (TM2.step target) + (Placement.configuration view labels exit extra) + (Placement.step_simulation tape view left right labels exit extra (program H) target code) + (paddedInTime H requested state register) + +end MinUncutGames.Foundations.Complexity.MachinePaddedExpanderFamily + +end +section +namespace MinUncutGames.Foundations.Complexity.MachineRegularFamily + +open Turing MachineComposition +open MachineCloudPadding + + +abbrev CoreTape := Fin 27 +abbrev NativeTape := MachinePaddedExpanderFamily.Tape +abbrev Tape := CoreTape ⊕ NativeTape +abbrev Alphabet (_ : Tape) := Bool +abbrev SmallTable := MachinePaddedExpanderFamily.SmallTable +abbrev FamilyState := MachineExpanderFamily.State Unit MachinePaddedExpanderFamily.fixedDegree +abbrev State := (FamilyState × Bool) × Option Bool + +def inputNative : NativeTape := .inr .input +def outputNative : NativeTape := .inl MachineExpanderFamily.tableTape +def powerNative : NativeTape := .inr .power +def sizeNative : NativeTape := .inl (.inr .currentSize) +def levelNative : NativeTape := .inl (.inr .remainingLevel) + +def powerTape : Tape := .inr powerNative +def sizeTape : Tape := .inr sizeNative +def levelTape : Tape := .inr levelNative + +def familyTape (t : NativeTape) : Tape := + if t = inputNative then .inl 4 else if t = outputNative then .inl 7 else .inr t + +def familyView : Tape → Option NativeTape + | .inl i => if i = 4 then some inputNative else if i = 7 then some outputNative else none + | .inr t => if t = inputNative then none else if t = outputNative then none else some t + +theorem familyView_left (t : NativeTape) : familyView (familyTape t) = some t := by + by_cases hi : t = inputNative + · subst t; simp [familyTape, familyView] + · by_cases ho : t = outputNative + · subst t; simp [familyTape, familyView, hi] + · simp [familyTape, familyView, hi, ho] + +theorem familyView_right (j : Tape) (t : NativeTape) + (h : familyView j = some t) : familyTape t = j := by + cases j with + | inl i => + by_cases hi : i = 4 + · subst i + have ht : inputNative = t := by simpa [familyView] using h + subst t; simp [familyTape] + · by_cases ho : i = 7 + · subst i + have ht : outputNative = t := by simpa [familyView] using h + subst t; simp [familyTape, inputNative, outputNative] + · simp [familyView, hi, ho] at h + | inr j => + by_cases hi : j = inputNative + · simp [familyView, hi] at h + · by_cases ho : j = outputNative + · simp [familyView, ho] at h + · have ht : j = t := by simpa [familyView, hi, ho] using h + subst t; simp [familyTape, hi, ho] + +def stateEquiv : MachinePaddedExpanderFamily.State Unit ≃ State := + (Equiv.prodAssoc FamilyState Bool (Option Bool)).symm + +def seedState (H : SmallTable) : FamilyState := + MachineExpanderFamily.initialState MachineExpanderFamily.baseDegree_positive H () + +def readyState (H : SmallTable) : State := ((seedState H, false), none) + +def sourceProgram (H : SmallTable) : MachinePaddedExpanderFamily.Label → + TM2.Stmt (fun _ : NativeTape => Bool) MachinePaddedExpanderFamily.Label State := + MachineStateEquiv.program stateEquiv (MachinePaddedExpanderFamily.program (ρ := Unit) H) + +inductive Label + | start + | family (label : MachinePaddedExpanderFamily.Label) + | drainPower | drainSize | drainLevel + deriving DecidableEq, Fintype + +def program (H : SmallTable) : Label → TM2.Stmt Alphabet Label State + | .start => .load (fun _ => readyState H) (.goto fun _ => .family MachinePaddedExpanderFamily.main) + | .family l => Placement.statement familyTape Label.family (some .drainPower) (sourceProgram H l) + | .drainPower => MachineDrain.drain powerTape .drainPower (some .drainSize) + | .drainSize => MachineDrain.drain sizeTape .drainSize (some .drainLevel) + | .drainLevel => MachineDrain.drain levelTape .drainLevel none + +def frame (core : CoreTape → List Bool) : Tape → List Bool + | .inl i => core i + | .inr _ => [] + +def rotor (H : SmallTable) (k : Nat) : List Bool := + MachinePaddedExpanderFamilyBounds.outputWord H k + +def resultCore (H : SmallTable) (k : Nat) (core : CoreTape → List Bool) : + CoreTape → List Bool := Function.update core 7 (rotor H k) + +def working (core : CoreTape → List Bool) (power size level : List Bool) : Tape → List Bool + | .inl i => core i + | .inr t => if t = powerNative then power + else if t = sizeNative then size else if t = levelNative then level else [] + +@[simp] theorem working_power (core : CoreTape → List Bool) (p s l : List Bool) : + working core p s l powerTape = p := by simp [working, powerTape] + +@[simp] theorem working_size (core : CoreTape → List Bool) (p s l : List Bool) : + working core p s l sizeTape = s := by + simp [working, sizeTape, powerNative, sizeNative] + +@[simp] theorem working_level (core : CoreTape → List Bool) (p s l : List Bool) : + working core p s l levelTape = l := by + simp [working, levelTape, powerNative, sizeNative, levelNative] + +theorem update_working_power (core : CoreTape → List Bool) (p s l p' : List Bool) : + Function.update (working core p s l) powerTape p' = working core p' s l := by + funext t + cases t with + | inl i => simp [working, powerTape] + | inr t => by_cases h : t = powerNative <;> simp [working, powerTape, h] + +theorem update_working_size (core : CoreTape → List Bool) (p s l s' : List Bool) : + Function.update (working core p s l) sizeTape s' = working core p s' l := by + funext t + cases t with + | inl i => simp [working, sizeTape] + | inr t => + by_cases h : t = sizeNative + · subst t; simp [working, sizeTape, powerNative, sizeNative] + · simp [working, sizeTape, h] + +theorem update_working_level (core : CoreTape → List Bool) (p s l l' : List Bool) : + Function.update (working core p s l) levelTape l' = working core p s l' := by + funext t + cases t with + | inl i => simp [working, levelTape] + | inr t => + by_cases h : t = levelNative + · subst t; simp [working, levelTape, powerNative, sizeNative, levelNative] + · simp [working, levelTape, h] + +@[simp] theorem working_empty (core : CoreTape → List Bool) : + working core [] [] [] = frame core := by + funext t; cases t <;> simp [working, frame] + +private theorem initial_other (k : Nat) (t : NativeTape) (h : t ≠ inputNative) : + MachinePaddedExpanderFamily.initialTapes k t = [] := by + cases t with + | inl t => rfl + | inr t => cases t <;> simp_all [MachinePaddedExpanderFamily.initialTapes, inputNative] + +private theorem final_other (H : SmallTable) (k : Nat) (t : NativeTape) + (hi : t ≠ inputNative) (ho : t ≠ outputNative) (hp : t ≠ powerNative) + (hs : t ≠ sizeNative) (hl : t ≠ levelNative) : + MachinePaddedExpanderFamily.finalTapes H k t = [] := by + rcases t with ((row | tableExtra) | familyExtra) | ceiling + · cases row <;> + simp_all [inputNative, outputNative, MachineExpanderFamily.tableTape, + MachinePaddedExpanderFamily.finalTapes, MachineExpanderFamily.toBoolTapes, + MachineExpanderFamily.toBoolWord, MachineExpanderFamily.familyTapes, + MachineExpanderFamily.boundaryTapes, MachineExpanderFamily.tableFrame, + MachineEmbedding.tapes] + · cases tableExtra <;> rfl + · cases familyExtra <;> + simp_all [sizeNative, levelNative, MachinePaddedExpanderFamily.finalTapes, + MachineExpanderFamily.toBoolTapes, MachineExpanderFamily.toBoolWord, + MachineExpanderFamily.familyTapes, MachineExpanderFamily.boundaryTapes, + MachineExpanderFamily.extraFrame, MachineEmbedding.tapes] + · cases ceiling <;> + simp_all [inputNative, powerNative, MachinePaddedExpanderFamily.finalTapes, + MachinePaddedExpanderFamily.retainedCeilingTapes, MachineCeilingPower.memory] + +theorem initial_placement (k : Nat) (core : CoreTape → List Bool) + (hinput : core 4 = encodeWord k) (houtput : core 7 = []) : + Placement.tapes familyView (MachinePaddedExpanderFamily.initialTapes k) (frame core) = + frame core := by + funext t + cases t with + | inl i => + by_cases hi : i = 4 + · subst i; simp [Placement.tapes, familyView, frame, inputNative, hinput] + · by_cases ho : i = 7 + · subst i + simp [Placement.tapes, familyView, frame, outputNative, + MachinePaddedExpanderFamily.initialTapes, houtput] + · simp [Placement.tapes, familyView, frame, hi, ho] + | inr t => + by_cases hi : t = inputNative + · simp [Placement.tapes, familyView, frame, hi] + · by_cases ho : t = outputNative + · simp [Placement.tapes, familyView, frame, ho] + · simp [Placement.tapes, familyView, frame, hi, ho, initial_other k t hi] + +theorem final_placement (H : SmallTable) (k : Nat) (core : CoreTape → List Bool) + (hinput : core 4 = encodeWord k) : + Placement.tapes familyView (MachinePaddedExpanderFamily.finalTapes H k) (frame core) = + working (resultCore H k core) + (encodeWord (PCP.PreprocessingLevels.paddedSize k)) + (encodeWord (PCP.PreprocessingLevels.paddedSize k)) (encodeWord 0) := by + funext t + cases t with + | inl i => + by_cases hi : i = 4 + · subst i + simp [Placement.tapes, familyView, working, resultCore, inputNative, hinput] + · by_cases ho : i = 7 + · subst i + simp [Placement.tapes, familyView, working, resultCore, outputNative, + rotor, MachinePaddedExpanderFamilyBounds.outputWord] + change MachinePaddedExpanderFamily.finalTapes H k + (MachinePaddedExpanderFamily.familyTape MachineExpanderFamily.tableTape) = _ + exact MachinePaddedExpanderFamily.finalTapes_table H k + · simp [Placement.tapes, familyView, working, resultCore, frame, hi, ho] + | inr t => + by_cases hi : t = inputNative + · subst t + simp [Placement.tapes, familyView, working, frame, + inputNative, powerNative, sizeNative, levelNative] + · by_cases ho : t = outputNative + · subst t + simp [Placement.tapes, familyView, working, frame, + outputNative, MachineExpanderFamily.tableTape, inputNative, + powerNative, sizeNative, levelNative] + · by_cases hp : t = powerNative + · subst t + simp [Placement.tapes, familyView, working, powerNative, inputNative, outputNative] + · by_cases hs : t = sizeNative + · subst t + simpa [Placement.tapes, familyView, working, sizeNative, + powerNative, inputNative, outputNative, MachineExpanderFamily.tableTape, + MachinePaddedExpanderFamily.familyTape] using + MachinePaddedExpanderFamily.finalTapes_currentSize H k + · by_cases hl : t = levelNative + · subst t + simpa [Placement.tapes, familyView, working, levelNative, + sizeNative, powerNative, inputNative, outputNative, + MachineExpanderFamily.tableTape, MachinePaddedExpanderFamily.ceilingTape] using + MachinePaddedExpanderFamily.finalTapes_remainingLevel H k + · simp [Placement.tapes, familyView, working, hi, ho, hp, hs, hl, + final_other H k t hi ho hp hs hl] + +@[simp] theorem source_initial_state (H : SmallTable) : + stateEquiv (MachinePaddedExpanderFamily.initialState (seedState H) none) = + readyState H := rfl + +@[simp] theorem source_final_state (H : SmallTable) : + stateEquiv (MachinePaddedExpanderFamily.finalState H (seedState H)) = + readyState H := by + simp [stateEquiv, MachinePaddedExpanderFamily.finalState, readyState, seedState] + +noncomputable def familyInTime (H : SmallTable) (k : Nat) (core : CoreTape → List Bool) + (hinput : core 4 = encodeWord k) (houtput : core 7 = []) : + StateTransition.EvalsToInTime (TM2.step (program H)) + ⟨some (.family MachinePaddedExpanderFamily.main), readyState H, frame core⟩ + (some ⟨some .drainPower, readyState H, + working (resultCore H k core) + (encodeWord (PCP.PreprocessingLevels.paddedSize k)) + (encodeWord (PCP.PreprocessingLevels.paddedSize k)) (encodeWord 0)⟩) + (MachinePaddedExpanderFamilyBounds.timePolynomial.eval (encodeWord k).length) := by + let raw := MachinePaddedExpanderFamily.paddedInTime H k (seedState H) none + let renamed := MachineStateEquiv.execution stateEquiv + (MachinePaddedExpanderFamily.program (ρ := Unit) H) raw + let placed := liftExecutionInTime (TM2.step (sourceProgram H)) (TM2.step (program H)) + (Placement.configuration familyView Label.family (some .drainPower) (frame core)) + (Placement.step_simulation familyTape familyView familyView_left familyView_right + Label.family (some .drainPower) (frame core) (sourceProgram H) (program H) + (fun _ => rfl)) renamed + simpa only [MachineStateEquiv.configuration, Placement.configuration, Placement.label, + source_initial_state, source_final_state, initial_placement k core hinput houtput, + final_placement H k core hinput] using placed + +theorem appendTrace {α : Type} (f : α → α) {a b : Nat} {x y z : α} + (hs : f^[a] x = y) (ht : f^[b] y = z) : f^[a+b] x = z := by + rw [Nat.add_comm a b, Function.iterate_add_apply, hs, ht] + +theorem cleanupTrace (H : SmallTable) (m : Nat) (core : CoreTape → List Bool) : + (advance (TM2.step (program H)))^[2*m+6] + (some ⟨some .drainPower, readyState H, + working core (encodeWord m) (encodeWord m) (encodeWord 0)⟩) = + some ⟨none, readyState H, frame core⟩ := by + have first := (MachineDrain.drainInTime powerTape .drainPower (some .drainSize) + (program H) rfl (working core (encodeWord m) (encodeWord m) (encodeWord 0)) + (seedState H, false) none).evals_in_steps + have second := (MachineDrain.drainInTime sizeTape .drainSize (some .drainLevel) + (program H) rfl (working core [] (encodeWord m) (encodeWord 0)) + (seedState H, false) none).evals_in_steps + have third := (MachineDrain.drainInTime levelTape .drainLevel none + (program H) rfl (working core [] [] (encodeWord 0)) + (seedState H, false) none).evals_in_steps + simp only [MachineDrain.drainInTime, working_power, working_size, working_level, + encodeWord_length, update_working_power, update_working_size, + update_working_level, working_empty] at first second third + have all := appendTrace _ (appendTrace _ first second) third + have count : 2*m+6 = (m+1+1)+(m+1+1)+(0+1+1) := by omega + rw [count] + exact all + +def cleanupInTime (H : SmallTable) (m : Nat) (core : CoreTape → List Bool) : + StateTransition.EvalsToInTime (TM2.step (program H)) + ⟨some .drainPower, readyState H, + working core (encodeWord m) (encodeWord m) (encodeWord 0)⟩ + (some ⟨none, readyState H, frame core⟩) (2*m+6) where + steps := 2*m+6 + evals_in_steps := cleanupTrace H m core + steps_le_m := le_rfl + +def startInTime (H : SmallTable) (core : CoreTape → List Bool) (state : State) : + StateTransition.EvalsToInTime (TM2.step (program H)) + ⟨some .start, state, frame core⟩ + (some ⟨some (.family MachinePaddedExpanderFamily.main), readyState H, frame core⟩) 1 where + steps := 1 + evals_in_steps := by + change some (TM2.stepAux (program H .start) state (frame core)) = _ + rfl + steps_le_m := le_rfl + +noncomputable def timePolynomial : Polynomial Nat := + MachinePaddedExpanderFamilyBounds.timePolynomial + + Polynomial.C (2 * PCP.ExpanderFamily.growth) * Polynomial.X + 7 + +theorem totalBudget_le (k : Nat) : + 1 + MachinePaddedExpanderFamilyBounds.timePolynomial.eval (encodeWord k).length + + (2 * PCP.PreprocessingLevels.paddedSize k + 6) ≤ + timePolynomial.eval (encodeWord k).length := by + have hs := MachineExpanderFamilyBounds.paddedSize_le_succ_input k + have hm := Nat.mul_le_mul_left 2 hs + simp only [timePolynomial, Polynomial.eval_add, Polynomial.eval_mul, + Polynomial.eval_C, Polynomial.eval_X, Polynomial.eval_ofNat, encodeWord_length] + simp only [Nat.mul_assoc] at hm ⊢ + omega + +noncomputable def familyCleanInTime (H : SmallTable) (k : Nat) + (core : CoreTape → List Bool) (hinput : core 4 = encodeWord k) + (houtput : core 7 = []) (state : State) : + StateTransition.EvalsToInTime (TM2.step (program H)) + ⟨some .start, state, frame core⟩ + (some ⟨none, readyState H, frame (resultCore H k core)⟩) + (timePolynomial.eval (encodeWord k).length) := by + let first := startInTime H core state + let second := familyInTime H k core hinput houtput + let third := cleanupInTime H (PCP.PreprocessingLevels.paddedSize k) (resultCore H k core) + let pair := StateTransition.EvalsToInTime.trans (TM2.step (program H)) _ _ _ _ _ first second + let all := StateTransition.EvalsToInTime.trans (TM2.step (program H)) _ _ _ _ _ pair third + refine { toEvalsTo := all.toEvalsTo, steps_le_m := ?_ } + exact all.steps_le_m.trans + (by simpa only [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using totalBudget_le k) + +@[simp] theorem result_output (H : SmallTable) (k : Nat) (core : CoreTape → List Bool) : + frame (resultCore H k core) (.inl 7) = rotor H k := by simp [frame, resultCore] + +theorem result_preserves_core (H : SmallTable) (k : Nat) (core : CoreTape → List Bool) + (i : CoreTape) (hi : i ≠ 7) : frame (resultCore H k core) (.inl i) = core i := by + simp [frame, resultCore, hi] + +@[simp] theorem result_private_empty (H : SmallTable) (k : Nat) + (core : CoreTape → List Bool) (t : NativeTape) : + frame (resultCore H k core) (.inr t) = [] := rfl + +noncomputable def placedInTime {K Λ : Type} [DecidableEq K] + (tape : Tape → K) (view : K → Option Tape) + (left : ∀ t, view (tape t) = some t) + (right : ∀ j t, view j = some t → tape t = j) + (labels : Label → Λ) (exit : Option Λ) (extra : K → List Bool) + (H : SmallTable) (target : Λ → TM2.Stmt (fun _ : K => Bool) Λ State) + (code : ∀ l, target (labels l) = Placement.statement tape labels exit (program H l)) + (k : Nat) (core : CoreTape → List Bool) (hinput : core 4 = encodeWord k) + (houtput : core 7 = []) (state : State) : + StateTransition.EvalsToInTime (TM2.step target) + (Placement.configuration view labels exit extra ⟨some .start, state, frame core⟩) + (some (Placement.configuration view labels exit extra + ⟨none, readyState H, frame (resultCore H k core)⟩)) + (timePolynomial.eval (encodeWord k).length) := + liftExecutionInTime (TM2.step (program H)) (TM2.step target) + (Placement.configuration view labels exit extra) + (Placement.step_simulation tape view left right labels exit extra (program H) target code) + (familyCleanInTime H k core hinput houtput state) + +end MinUncutGames.Foundations.Complexity.MachineRegularFamily + +end +section +namespace MinUncutGames.Foundations.Complexity.MachineUnaryLessAt + +open Turing MachineComposition + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool +abbrev State (σ : Type) := (σ × Bool) × Option Bool + +def zeroTest (operand : K) (exit : Option Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (State σ) := + .peek operand (fun s head => (s.1, head)) + (.load (fun s => ((s.1.1, !(s.2.getD false)), none)) + (Reduction.MachineTransfer.exitAt operand exit)) + +theorem zeroTestTrace (operand : K) (testLabel : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atTest : program testLabel = zeroTest operand exit) + (base : K → List Bool) (n : Nat) (suffix : List Bool) + (word : base operand = encodeWord n ++ suffix) + (ambient : σ) (flag : Bool) (register : Option Bool) : + (advance (TM2.step program))^[1] + (some ⟨some testLabel, ((ambient, flag), register), base⟩) = + some ⟨exit, ((ambient, decide (n = 0)), none), base⟩ := by + change some (TM2.stepAux (program testLabel) _ _) = _ + rw [atTest] + cases n <;> cases exit <;> + simp [zeroTest, TM2.stepAux, word, encodeWord, List.replicate_succ, + Reduction.MachineTransfer.exitAt] + +def tapes (slots : Fin 4 ↪ K) (base : K → List Bool) + (left right savedLeft savedRight : List Bool) : K → List Bool := + Function.update (Function.update (Function.update (Function.update base + (slots 0) left) (slots 1) right) (slots 2) savedLeft) (slots 3) savedRight + +@[simp] theorem tapes_left (slots : Fin 4 ↪ K) (base : K → List Bool) + (left right savedLeft savedRight : List Bool) : + tapes slots base left right savedLeft savedRight (slots 0) = left := by + simp [tapes, slots.injective.eq_iff] + +@[simp] theorem tapes_right (slots : Fin 4 ↪ K) (base : K → List Bool) + (left right savedLeft savedRight : List Bool) : + tapes slots base left right savedLeft savedRight (slots 1) = right := by + simp [tapes, slots.injective.eq_iff] + +@[simp] theorem tapes_savedLeft (slots : Fin 4 ↪ K) (base : K → List Bool) + (left right savedLeft savedRight : List Bool) : + tapes slots base left right savedLeft savedRight (slots 2) = savedLeft := by + simp [tapes, slots.injective.eq_iff] + +@[simp] theorem tapes_savedRight (slots : Fin 4 ↪ K) (base : K → List Bool) + (left right savedLeft savedRight : List Bool) : + tapes slots base left right savedLeft savedRight (slots 3) = savedRight := by + simp [tapes] + +@[simp] theorem update_tapes (slots : Fin 4 ↪ K) (base : K → List Bool) + (left right savedLeft savedRight replacement : List Bool) (i : Fin 4) : + Function.update (tapes slots base left right savedLeft savedRight) (slots i) replacement = + tapes slots base (if i = 0 then replacement else left) + (if i = 1 then replacement else right) (if i = 2 then replacement else savedLeft) + (if i = 3 then replacement else savedRight) := by + fin_cases i <;> funext k + all_goals + by_cases h₀ : k = slots 0 + · subst k; simp [tapes, slots.injective.eq_iff] + · by_cases h₁ : k = slots 1 + · subst k; simp [tapes, slots.injective.eq_iff] + · by_cases h₂ : k = slots 2 + · subst k; simp [tapes, slots.injective.eq_iff] + · by_cases h₃ : k = slots 3 + · subst k; simp [tapes, slots.injective.eq_iff] + · simp [tapes, h₀, h₁, h₂, h₃] + +@[simp] theorem tapes_self (slots : Fin 4 ↪ K) (base : K → List Bool) : + tapes slots base (base (slots 0)) (base (slots 1)) (base (slots 2)) (base (slots 3)) = base := by + simp [tapes] + +def stop (result : Bool) (restoreLabel : Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (State σ) := + .load (fun s => ((s.1.1, result), none)) (.goto fun _ => restoreLabel) + +def scan (slots : Fin 4 ↪ K) (scanLabel restoreLabel : Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (State σ) := + .peek (slots 0) (fun s head => (s.1, head)) + (.branch (fun s => s.2.getD false) + (.peek (slots 1) (fun s head => (s.1, head)) + (.branch (fun s => s.2.getD false) + (.pop (slots 0) (fun s _ => s) + (.pop (slots 1) (fun s _ => s) + (.push (slots 2) (fun _ => true) + (.push (slots 3) (fun _ => true) (.goto fun _ => scanLabel))))) + (stop false restoreLabel))) + (.peek (slots 1) (fun s head => (s.1, head)) + (.branch (fun s => s.2.getD false) + (stop true restoreLabel) (stop false restoreLabel)))) + +theorem scan_step_zero_left (slots : Fin 4 ↪ K) (scanLabel restoreLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atScan : program scanLabel = scan slots scanLabel restoreLabel) + (base : K → List Bool) (b : Nat) (leftSuffix rightSuffix savedLeft savedRight : List Bool) + (ambient : σ) (flag : Bool) (register : Option Bool) : + TM2.step program ⟨some scanLabel, ((ambient, flag), register), + tapes slots base (encodeWord 0 ++ leftSuffix) (encodeWord b ++ rightSuffix) savedLeft savedRight⟩ = + some ⟨some restoreLabel, ((ambient, decide (0 < b)), none), + tapes slots base (encodeWord 0 ++ leftSuffix) (encodeWord b ++ rightSuffix) savedLeft savedRight⟩ := by + change some (TM2.stepAux (program scanLabel) _ _) = _ + rw [atScan] + cases b <;> simp [scan, stop, TM2.stepAux, encodeWord, List.replicate_succ] + +theorem scan_step_zero_right (slots : Fin 4 ↪ K) (scanLabel restoreLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atScan : program scanLabel = scan slots scanLabel restoreLabel) + (base : K → List Bool) (a : Nat) (leftSuffix rightSuffix savedLeft savedRight : List Bool) + (ambient : σ) (flag : Bool) (register : Option Bool) : + TM2.step program ⟨some scanLabel, ((ambient, flag), register), + tapes slots base (encodeWord (a + 1) ++ leftSuffix) (encodeWord 0 ++ rightSuffix) savedLeft savedRight⟩ = + some ⟨some restoreLabel, ((ambient, false), none), + tapes slots base (encodeWord (a + 1) ++ leftSuffix) (encodeWord 0 ++ rightSuffix) savedLeft savedRight⟩ := by + change some (TM2.stepAux (program scanLabel) _ _) = _ + rw [atScan] + simp [scan, stop, TM2.stepAux, encodeWord, List.replicate_succ] + +theorem scan_step_succ (slots : Fin 4 ↪ K) (scanLabel restoreLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atScan : program scanLabel = scan slots scanLabel restoreLabel) + (base : K → List Bool) (a b : Nat) (leftSuffix rightSuffix savedLeft savedRight : List Bool) + (ambient : σ) (flag : Bool) (register : Option Bool) : + TM2.step program ⟨some scanLabel, ((ambient, flag), register), + tapes slots base (encodeWord (a + 1) ++ leftSuffix) (encodeWord (b + 1) ++ rightSuffix) + savedLeft savedRight⟩ = + some ⟨some scanLabel, ((ambient, flag), some true), + tapes slots base (encodeWord a ++ leftSuffix) (encodeWord b ++ rightSuffix) + (true :: savedLeft) (true :: savedRight)⟩ := by + change some (TM2.stepAux (program scanLabel) _ _) = _ + rw [atScan] + simp [scan, TM2.stepAux, encodeWord, List.replicate_succ] + +theorem scanTrace (slots : Fin 4 ↪ K) (scanLabel restoreLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atScan : program scanLabel = scan slots scanLabel restoreLabel) + (base : K → List Bool) (a b : Nat) (leftSuffix rightSuffix savedLeft savedRight : List Bool) + (ambient : σ) (flag : Bool) (register : Option Bool) : + (advance (TM2.step program))^[min a b + 1] + (some ⟨some scanLabel, ((ambient, flag), register), + tapes slots base (encodeWord a ++ leftSuffix) (encodeWord b ++ rightSuffix) savedLeft savedRight⟩) = + some ⟨some restoreLabel, ((ambient, decide (a < b)), none), + tapes slots base (encodeWord (a - b) ++ leftSuffix) (encodeWord (b - a) ++ rightSuffix) + (List.replicate (min a b) true ++ savedLeft) (List.replicate (min a b) true ++ savedRight)⟩ := by + induction a generalizing b savedLeft savedRight register with + | zero => + simpa using scan_step_zero_left slots scanLabel restoreLabel program atScan base b + leftSuffix rightSuffix savedLeft savedRight ambient flag register + | succ a ih => + cases b with + | zero => + simpa using scan_step_zero_right slots scanLabel restoreLabel program atScan base a + leftSuffix rightSuffix savedLeft savedRight ambient flag register + | succ b => + have hm : min (a + 1) (b + 1) = min a b + 1 := by omega + rw [hm, Function.iterate_succ_apply] + simp only [advance_some] + rw [scan_step_succ slots scanLabel restoreLabel program atScan, ih] + have hsave (xs : List Bool) : + List.replicate (min a b) true ++ true :: xs = + List.replicate (min a b + 1) true ++ xs := by + simp [List.replicate_add, List.append_assoc] + simp only [hsave, Nat.add_sub_add_right, Nat.add_lt_add_iff_right] + +@[simp] theorem transferLeft_tapes (slots : Fin 4 ↪ K) (base : K → List Bool) + (left right savedLeft savedRight replacementSaved replacementLeft : List Bool) : + Reduction.MachineTransfer.tapesAt (slots 2) (slots 0) + (tapes slots base left right savedLeft savedRight) replacementSaved replacementLeft = + tapes slots base replacementLeft right replacementSaved savedRight := by + simp [Reduction.MachineTransfer.tapesAt] + +@[simp] theorem transferRight_tapes (slots : Fin 4 ↪ K) (base : K → List Bool) + (left right savedLeft savedRight replacementSaved replacementRight : List Bool) : + Reduction.MachineTransfer.tapesAt (slots 3) (slots 1) + (tapes slots base left right savedLeft savedRight) replacementSaved replacementRight = + tapes slots base left replacementRight savedLeft replacementSaved := by + simp [Reduction.MachineTransfer.tapesAt] + +inductive Label where + | scan + | restoreLeft + | restoreRight + deriving DecidableEq + +instance : Fintype Label where + elems := { .scan, .restoreLeft, .restoreRight } + complete l := by cases l <;> simp + +def statement (slots : Fin 4 ↪ K) (labels : Label → Λ) (exit : Option Λ) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (State σ) + | .scan => scan slots (labels .scan) (labels .restoreLeft) + | .restoreLeft => Reduction.MachineTransfer.loopAt (slots 2) (slots 0) id false + (labels .restoreLeft) (some (labels .restoreRight)) + | .restoreRight => Reduction.MachineTransfer.loopAt (slots 3) (slots 1) id false + (labels .restoreRight) exit + +def steps (a b : Nat) : Nat := 3 * (min a b + 1) + +theorem comparisonTrace (slots : Fin 4 ↪ K) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ l, program (labels l) = statement slots labels exit l) + (base : K → List Bool) (a b : Nat) (leftSuffix rightSuffix : List Bool) + (ambient : σ) (flag : Bool) (register : Option Bool) : + (advance (TM2.step program))^[steps a b] + (some ⟨some (labels .scan), ((ambient, flag), register), + tapes slots base (encodeWord a ++ leftSuffix) (encodeWord b ++ rightSuffix) [] []⟩) = + some ⟨exit, ((ambient, decide (a < b)), none), + tapes slots base (encodeWord a ++ leftSuffix) (encodeWord b ++ rightSuffix) [] []⟩ := by + have hscan := scanTrace slots (labels .scan) (labels .restoreLeft) program (atLabels .scan) + base a b leftSuffix rightSuffix [] [] ambient flag register + simp only [List.append_nil] at hscan + have hwordLeft : List.replicate (min a b) true ++ (encodeWord (a - b) ++ leftSuffix) = + encodeWord a ++ leftSuffix := by + rw [MachineUnaryAffineAt.prepend_replicate_word, + show min a b + (a - b) = a by omega] + have hwordRight : List.replicate (min a b) true ++ (encodeWord (b - a) ++ rightSuffix) = + encodeWord b ++ rightSuffix := by + rw [MachineUnaryAffineAt.prepend_replicate_word, + show min a b + (b - a) = b by omega] + let middle := tapes slots base (encodeWord (a - b) ++ leftSuffix) + (encodeWord (b - a) ++ rightSuffix) (List.replicate (min a b) true) (List.replicate (min a b) true) + have hleft := Reduction.MachineTransfer.transferAt_fromTapes + (Γ := fun _ : K => Bool) (σ := σ × Bool) (slots 2) (slots 0) + (slots.injective.ne (by decide)) id false (labels .restoreLeft) (some (labels .restoreRight)) + program (by simpa only [statement] using atLabels .restoreLeft) + middle (ambient, decide (a < b)) none + change (advance (TM2.step program))^[(middle (slots 2)).length + 1] + (some ⟨some (labels .restoreLeft), ((ambient, decide (a < b)), none), middle⟩) = _ at hleft + simp only [middle, tapes_savedLeft, tapes_left, List.length_replicate, List.reverse_replicate, + List.map_id, hwordLeft, transferLeft_tapes] at hleft + let afterLeft := tapes slots base (encodeWord a ++ leftSuffix) + (encodeWord (b - a) ++ rightSuffix) [] (List.replicate (min a b) true) + have hright := Reduction.MachineTransfer.transferAt_fromTapes + (Γ := fun _ : K => Bool) (σ := σ × Bool) (slots 3) (slots 1) + (slots.injective.ne (by decide)) id false (labels .restoreRight) exit + program (by simpa only [statement] using atLabels .restoreRight) + afterLeft (ambient, decide (a < b)) none + change (advance (TM2.step program))^[(afterLeft (slots 3)).length + 1] + (some ⟨some (labels .restoreRight), ((ambient, decide (a < b)), none), afterLeft⟩) = _ at hright + simp only [afterLeft, tapes_savedRight, tapes_right, List.length_replicate, List.reverse_replicate, + List.map_id, hwordRight, transferRight_tapes] at hright + have hfirst : (advance (TM2.step program))^[(min a b + 1) + (min a b + 1)] + (some ⟨some (labels .scan), ((ambient, flag), register), + tapes slots base (encodeWord a ++ leftSuffix) (encodeWord b ++ rightSuffix) [] []⟩) = + some ⟨some (labels .restoreRight), ((ambient, decide (a < b)), none), afterLeft⟩ := by + rw [Function.iterate_add_apply, hscan] + exact hleft + rw [show steps a b = (min a b + 1) + ((min a b + 1) + (min a b + 1)) by + unfold steps; omega, Function.iterate_add_apply, hfirst] + exact hright + +theorem lessThanTrace (slots : Fin 4 ↪ K) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ l, program (labels l) = statement slots labels exit l) + (base : K → List Bool) (a b : Nat) (leftSuffix rightSuffix : List Bool) + (leftWord : base (slots 0) = encodeWord a ++ leftSuffix) + (rightWord : base (slots 1) = encodeWord b ++ rightSuffix) + (leftEmpty : base (slots 2) = []) (rightEmpty : base (slots 3) = []) + (ambient : σ) (flag : Bool) (register : Option Bool) : + (advance (TM2.step program))^[steps a b] + (some ⟨some (labels .scan), ((ambient, flag), register), base⟩) = + some ⟨exit, ((ambient, decide (a < b)), none), base⟩ := by + have h := comparisonTrace slots labels exit program atLabels base a b leftSuffix rightSuffix + ambient flag register + have hframe := tapes_self slots base + rw [leftWord, rightWord, leftEmpty, rightEmpty] at hframe + rw [hframe] at h + exact h + +noncomputable def timePolynomial : Polynomial Nat := Polynomial.C 3 * Polynomial.X + Polynomial.C 3 + +theorem steps_le_time (a b : Nat) : steps a b ≤ timePolynomial.eval (a + b) := by + simp only [steps, timePolynomial, Polynomial.eval_add, Polynomial.eval_mul, + Polynomial.eval_C, Polynomial.eval_X] + have := Nat.min_le_left a b + omega + +def lessThanInPolynomialTime (slots : Fin 4 ↪ K) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ l, program (labels l) = statement slots labels exit l) + (base : K → List Bool) (a b : Nat) (leftSuffix rightSuffix : List Bool) + (leftWord : base (slots 0) = encodeWord a ++ leftSuffix) + (rightWord : base (slots 1) = encodeWord b ++ rightSuffix) + (leftEmpty : base (slots 2) = []) (rightEmpty : base (slots 3) = []) + (ambient : σ) (flag : Bool) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .scan), ((ambient, flag), register), base⟩ + (some ⟨exit, ((ambient, decide (a < b)), none), base⟩) (timePolynomial.eval (a + b)) where + steps := steps a b + evals_in_steps := lessThanTrace slots labels exit program atLabels base a b leftSuffix rightSuffix + leftWord rightWord leftEmpty rightEmpty ambient flag register + steps_le_m := steps_le_time a b + +abbrev machine : Turing.FinTM2 where + K := Fin 4 + k₀ := 0 + k₁ := 1 + Γ _ := Bool + Λ := Label + main := .scan + σ := State Unit + initialState := (((), false), none) + m := statement (Function.Embedding.refl _) id none + +def machineInPolynomialTime (base : Fin 4 → List Bool) (a b : Nat) + (leftSuffix rightSuffix : List Bool) + (leftWord : base 0 = encodeWord a ++ leftSuffix) + (rightWord : base 1 = encodeWord b ++ rightSuffix) + (leftEmpty : base 2 = []) (rightEmpty : base 3 = []) : + StateTransition.EvalsToInTime machine.step + ⟨some .scan, (((), false), none), base⟩ + (some ⟨none, (((), decide (a < b)), none), base⟩) (timePolynomial.eval (a + b)) := + lessThanInPolynomialTime (Function.Embedding.refl _) id none machine.m (fun _ => rfl) + base a b leftSuffix rightSuffix leftWord rightWord leftEmpty rightEmpty () false none + +end MinUncutGames.Foundations.Complexity.MachineUnaryLessAt + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachinePaddedOverlay.lean b/lean/OAI/Computability/MinUncut/Machines/MachinePaddedOverlay.lean new file mode 100644 index 0000000000000000000000000000000000000000..44c074b85e3d27ee2261d429f632cdd979ebd703 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachinePaddedOverlay.lean @@ -0,0 +1,633 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineOverlayTable + +namespace OAI + +section +namespace MinUncutGames.Foundations.Complexity.MachinePaddedOverlay + +open Turing MachineComposition MachineCloudPadding +open PCP + + +abbrev BaseTable := PreprocessingStageMaps.BaseTable +abbrev baseDegree := Expanders.baseDegree +abbrev overlayDegree := PreprocessingRegularTables.internalDegree +abbrev Tape := MachineVertexPadding.Tape ⊕ (MachineExpanderFamily.Tape ⊕ MachineOverlayTable.Tape) +abbrev Alphabet (_ : Tape) := Bool +abbrev Label (d : Nat) := MachineVertexPadding.Label d ⊕ (MachineExpanderFamily.Label baseDegree ⊕ MachineOverlayTable.Label d overlayDegree) +abbrev State (d : Nat) := MachineVertexPadding.State (MachineExpanderFamily.State Unit baseDegree × MachineOverlayTable.State Unit d overlayDegree) + +theorem overlayDegree_positive : 0 < overlayDegree := + Nat.mul_pos MachineExpanderFamily.baseDegree_positive MachineExpanderFamily.baseDegree_positive + +def paddingTape (k : MachineVertexPadding.Tape) : Tape := .inl k + +def paddingView : Tape → Option MachineVertexPadding.Tape + | .inl k => some k + | .inr _ => none + +@[simp] theorem paddingView_left (k : MachineVertexPadding.Tape) : paddingView (paddingTape k) = some k := rfl + +theorem paddingView_right (j : Tape) (k : MachineVertexPadding.Tape) + (h : paddingView j = some k) : paddingTape k = j := by + cases j with + | inl j => cases Option.some.inj h; rfl + | inr j => simp [paddingView] at h + +def familyTape (k : MachineExpanderFamily.Tape) : Tape := + if k = .inr .remainingLevel then .inl .level else .inr (.inl k) + +def familyView : Tape → Option MachineExpanderFamily.Tape + | .inl .level => some (.inr .remainingLevel) + | .inr (.inl k) => if k = .inr .remainingLevel then none else some k + | _ => none + +@[simp] theorem familyView_left (k : MachineExpanderFamily.Tape) : familyView (familyTape k) = some k := by + by_cases h : k = .inr .remainingLevel + · subst k; rfl + · simp [familyTape, familyView, h] + +theorem familyView_right (j : Tape) (k : MachineExpanderFamily.Tape) + (h : familyView j = some k) : familyTape k = j := by + rcases j with j | j + · cases j <;> simp_all [familyView, familyTape] + · rcases j with j | j + · by_cases hj : j = .inr .remainingLevel <;> simp_all [familyView, familyTape] + · simp [familyView] at h + +def overlayTape (k : MachineOverlayTable.Tape) : Tape := + if k = MachineOverlayTable.graphArchive then .inl .output + else if k = MachineOverlayTable.expanderArchive then .inr (.inl MachineExpanderFamily.tableTape) + else .inr (.inr k) + +def overlayView : Tape → Option MachineOverlayTable.Tape + | .inl .output => some MachineOverlayTable.graphArchive + | .inr (.inl k) => if k = MachineExpanderFamily.tableTape then some MachineOverlayTable.expanderArchive else none + | .inr (.inr k) => + if k = MachineOverlayTable.graphArchive ∨ k = MachineOverlayTable.expanderArchive then none else some k + | _ => none + +@[simp] theorem overlayView_left (k : MachineOverlayTable.Tape) : overlayView (overlayTape k) = some k := by + by_cases hg : k = MachineOverlayTable.graphArchive + · subst k; rfl + · by_cases he : k = MachineOverlayTable.expanderArchive + · subst k; rfl + · simp [overlayTape, overlayView, hg, he] + +theorem overlayView_right (j : Tape) (k : MachineOverlayTable.Tape) + (h : overlayView j = some k) : overlayTape k = j := by + rcases j with j | j + · cases j <;> simp_all [overlayView, overlayTape, MachineOverlayTable.graphArchive] + · rcases j with j | j + · by_cases hj : j = MachineExpanderFamily.tableTape + · subst j + have hk : MachineOverlayTable.expanderArchive = k := by + simpa [overlayView] using h + subst k + rfl + · simp [overlayView, hj] at h + · by_cases hg : j = MachineOverlayTable.graphArchive + · simp [overlayView, hg] at h + · by_cases he : j = MachineOverlayTable.expanderArchive + · simp [overlayView, he] at h + · simp_all [overlayView, overlayTape] + +variable {degree : Nat} + +def paddingLabel (l : MachineVertexPadding.Label degree) : Label degree := .inl l +def familyLabel (l : MachineExpanderFamily.Label baseDegree) : Label degree := .inr (.inl l) +def overlayLabel (l : MachineOverlayTable.Label degree overlayDegree) : Label degree := .inr (.inr l) +def main : Label degree := paddingLabel (.splitCode .copyFirst) +def familyEntry : Label degree := familyLabel (.inr .initialize) +def overlayEntry : Label degree := overlayLabel (.inl .copyFirst) + +def familyStates (d : Nat) : + (MachineExpanderFamily.State Unit baseDegree × ((MachineOverlayTable.State Unit d overlayDegree × Bool) × Option Bool)) ≃ + State d where + toFun s := (((s.1, s.2.1.1), s.2.1.2), s.2.2) + invFun s := (s.1.1.1, ((s.1.1.2, s.1.2), s.2)) + left_inv := by rintro ⟨f, ⟨⟨o, b⟩, r⟩⟩; rfl + right_inv := by rintro ⟨⟨⟨f, o⟩, b⟩, r⟩; rfl + +def overlayStates (d : Nat) : + (MachineOverlayTable.State Unit d overlayDegree × ((MachineExpanderFamily.State Unit baseDegree × Bool) × Option Bool)) ≃ + State d where + toFun s := (((s.2.1.1, s.1), s.2.1.2), s.2.2) + invFun s := (s.1.1.2, ((s.1.1.1, s.1.2), s.2)) + left_inv := by rintro ⟨o, ⟨⟨f, b⟩, r⟩⟩; rfl + right_inv := by rintro ⟨⟨⟨f, o⟩, b⟩, r⟩; rfl + +def familySource (H : BaseTable) (d : Nat) : MachineExpanderFamily.Label baseDegree → + TM2.Stmt MachineExpanderFamily.BoolAlphabet (MachineExpanderFamily.Label baseDegree) (State d) := + MachineStateEquiv.program (familyStates d) (MachineStateFrame.frameProgram + (MachineExpanderFamily.boolView MachineExpanderFamily.baseDegree_positive H MachineExpanderFamily.baseDegree_cloud_gt_one)) + +def overlaySource (d : Nat) (hd : 0 < d) : MachineOverlayTable.Label d overlayDegree → + TM2.Stmt (fun _ : MachineOverlayTable.Tape => Bool) (MachineOverlayTable.Label d overlayDegree) (State d) := + MachineStateEquiv.program (overlayStates d) (MachineStateFrame.frameProgram + (MachineOverlayTable.program d overlayDegree hd overlayDegree_positive)) + +def program (H : BaseTable) (d : Nat) (hd : 0 < d) : + Label d → TM2.Stmt Alphabet (Label d) (State d) + | .inl l => Placement.statement paddingTape paddingLabel (some familyEntry) (MachineVertexPadding.program d hd l) + | .inr (.inl l) => Placement.statement familyTape familyLabel (some overlayEntry) + (familySource H d l) + | .inr (.inr l) => Placement.statement overlayTape overlayLabel none (overlaySource d hd l) + +def clean (H : BaseTable) (d : Nat) (hd : 0 < d) : State d := + (((MachineExpanderFamily.initialState MachineExpanderFamily.baseDegree_positive H (), + MachineOverlayTable.clean d overlayDegree hd overlayDegree_positive ()), false), none) + +def memory (input padded level rotor count output : List Bool) : Tape → List Bool + | .inl k => MachineVertexPadding.memory input padded [] [] [] level [] [] k + | .inr (.inl (.inl (.inl .table))) => rotor + | .inr (.inl (.inr .currentSize)) => count + | .inr (.inl _) => [] + | .inr (.inr k) => if k = MachineOverlayTable.output then output else [] + +def padded {n d : Nat} (t : PortTables.Table n d) := + PreprocessingPaddingTables.pad t (PreprocessingLevels.le_paddedSize n) + +def rotor (H : BaseTable) (n : Nat) : List Bool := + encodeWords (ExpanderTableWords.rotationWords + (ExpanderTables.family H (PreprocessingLevels.boundedLevel n))) + +def initialTapes {n d : Nat} (t : PortTables.Table n d) : Tape → List Bool := + memory (PortTables.tableBits t) [] [] [] [] [] + +def paddedTapes {n d : Nat} (t : PortTables.Table n d) : Tape → List Bool := + memory (PortTables.tableBits t) (PortTables.tableBits (padded t)) + (encodeWord (PreprocessingLevels.boundedLevel n)) [] [] [] + +def familyTapes (H : BaseTable) {n d : Nat} (t : PortTables.Table n d) : Tape → List Bool := + memory (PortTables.tableBits t) (PortTables.tableBits (padded t)) + (encodeWord 0) (rotor H n) (encodeWord (PreprocessingLevels.paddedSize n)) [] + +def finalTapes (H : BaseTable) {n d : Nat} (t : PortTables.Table n d) : Tape → List Bool := + memory (PortTables.tableBits t) (PortTables.tableBits (padded t)) + (encodeWord 0) (rotor H n) (encodeWord (PreprocessingLevels.paddedSize n)) + (PortTables.tableBits (PreprocessingStageMaps.paddedOverlay H d ⟨n, t⟩).2) + +private def placeExecution {K Λ S : Type} [DecidableEq K] + (tape : K → Tape) (view : Tape → Option K) + (left : ∀ k, view (tape k) = some k) + (right : ∀ j k, view j = some k → tape k = j) + (labels : Λ → Label degree) (exit : Option (Label degree)) (extra : Tape → List Bool) + (source : Λ → TM2.Stmt (fun _ : K => Bool) Λ S) + (target : Label degree → TM2.Stmt Alphabet (Label degree) S) + (atLabels : ∀ l, target (labels l) = Placement.statement tape labels exit (source l)) + {a b : TM2.Cfg (fun _ : K => Bool) Λ S} {budget : Nat} + (run : StateTransition.EvalsToInTime (TM2.step source) a (some b) budget) : + StateTransition.EvalsToInTime (TM2.step target) + (Placement.configuration view labels exit extra a) + (some (Placement.configuration view labels exit extra b)) budget := + liftExecutionInTime _ _ _ + (Placement.step_simulation tape view left right labels exit extra source target atLabels) run + +theorem padding_initial_memory (input : List Bool) : + Placement.tapes paddingView (MachineVertexPadding.memory input [] [] [] [] [] [] []) (fun _ => []) = + memory input [] [] [] [] [] := by + funext k + rcases k with k | k + · rfl + · rcases k with k | k + · rcases k with k | k + · rcases k with k | k <;> cases k <;> rfl + · cases k <;> rfl + · simp [Placement.tapes, paddingView, memory] + +theorem padding_final_memory (input output level : List Bool) : + Placement.tapes paddingView (MachineVertexPadding.memory input output [] [] [] level [] []) (fun _ => []) = + memory input output level [] [] [] := by + funext k + rcases k with k | k + · rfl + · rcases k with k | k + · rcases k with k | k + · rcases k with k | k <;> cases k <;> rfl + · cases k <;> rfl + · simp [Placement.tapes, paddingView, memory] + +noncomputable def paddingInTime (H : BaseTable) {n d : Nat} (hd : 0 < d) (t : PortTables.Table n d) : + StateTransition.EvalsToInTime (TM2.step (program H d hd)) + ⟨some main, clean H d hd, initialTapes t⟩ + (some ⟨some familyEntry, clean H d hd, paddedTapes t⟩) + ((MachineVertexPadding.timePolynomial d).eval (PortTables.tableBits t).length) := by + let ambient := (MachineExpanderFamily.initialState MachineExpanderFamily.baseDegree_positive H (), + MachineOverlayTable.clean d overlayDegree hd overlayDegree_positive ()) + have run := placeExecution paddingTape paddingView paddingView_left paddingView_right + paddingLabel (some familyEntry) (fun _ => []) (MachineVertexPadding.program d hd) (program H d hd) + (fun _ => rfl) (MachineVertexPadding.vertexPaddingInTime hd t ambient none) + simpa only [Placement.configuration, Placement.label, padding_initial_memory, + padding_final_memory, initialTapes, paddedTapes, padded, main, clean, ambient] using run + +theorem family_initial_memory (input output : List Bool) (level : Nat) : + Placement.tapes familyView + (MachineExpanderFamily.toBoolTapes (MachineExpanderFamily.initialTapes level [])) + (memory input output (encodeWord level) [] [] []) = + memory input output (encodeWord level) [] [] [] := by + funext k + rcases k with k | k + · cases k <;> simp [Placement.tapes, familyView, memory, + MachineVertexPadding.memory, MachineExpanderFamily.toBoolTapes, + MachineExpanderFamily.toBoolWord, MachineExpanderFamily.initialTapes, + MachineEmbedding.tapes] + · rcases k with k | k + · rcases k with k | k + · rcases k with k | k <;> cases k <;> + simp [Placement.tapes, familyView, memory, MachineExpanderFamily.toBoolTapes, + MachineExpanderFamily.toBoolWord, MachineExpanderFamily.initialTapes, + MachineExpanderFamily.tableFrame, MachineEmbedding.tapes] + · cases k <;> + simp [Placement.tapes, familyView, memory, MachineExpanderFamily.toBoolTapes, + MachineExpanderFamily.toBoolWord, MachineExpanderFamily.initialTapes, + MachineEmbedding.tapes] + · rfl + +theorem family_final_memory (H : BaseTable) (input output : List Bool) (level : Nat) : + Placement.tapes familyView + (MachineExpanderFamily.toBoolTapes (MachineExpanderFamily.familyTapes H level [])) + (memory input output (encodeWord level) [] [] []) = + memory input output (encodeWord 0) + (encodeWords (ExpanderTableWords.rotationWords (ExpanderTables.family H level))) + (encodeWord (ExpanderTables.vertexCount overlayDegree level)) [] := by + funext k + rcases k with k | k + · cases k <;> simp [Placement.tapes, familyView, memory, + MachineVertexPadding.memory, MachineExpanderFamily.toBoolTapes, + MachineExpanderFamily.toBoolWord, MachineExpanderFamily.familyTapes, + MachineExpanderFamily.boundaryTapes, MachineExpanderFamily.extraFrame, + MachineEmbedding.tapes] + · rcases k with k | k + · rcases k with k | k + · rcases k with k | k <;> cases k <;> + simp [Placement.tapes, familyView, memory, MachineExpanderFamily.toBoolTapes, + MachineExpanderFamily.toBoolWord, MachineExpanderFamily.familyTapes, + MachineExpanderFamily.boundaryTapes, MachineExpanderFamily.tableFrame, + MachineEmbedding.tapes] + · cases k <;> + simp [Placement.tapes, familyView, memory, MachineExpanderFamily.toBoolTapes, + MachineExpanderFamily.toBoolWord, MachineExpanderFamily.familyTapes, + MachineExpanderFamily.boundaryTapes, MachineExpanderFamily.extraFrame, + MachineEmbedding.tapes, overlayDegree, PreprocessingRegularTables.internalDegree, + ExpanderRowControl.degree] + · simp [Placement.tapes, familyView, memory] + +noncomputable def familyInTime (H : BaseTable) {n d : Nat} (hd : 0 < d) + (t : PortTables.Table n d) : + StateTransition.EvalsToInTime (TM2.step (program H d hd)) + ⟨some familyEntry, clean H d hd, paddedTapes t⟩ + (some ⟨some overlayEntry, clean H d hd, familyTapes H t⟩) + (MachineExpanderFamilyBounds.inputCoefficient * (n + 1)^5) := by + let f := MachineExpanderFamily.initialState MachineExpanderFamily.baseDegree_positive H () + let o := MachineOverlayTable.clean d overlayDegree hd overlayDegree_positive () + have caller : MachineExpanderFamily.caller f = () := Subsingleton.elim _ _ + have castRun := MachineAlphabetTransport.successfulExecutionInTime + MachineExpanderFamily.alphabet_eq + (MachineExpanderFamily.program MachineExpanderFamily.baseDegree_positive H + MachineExpanderFamily.baseDegree_cloud_gt_one) + (MachineExpanderFamily.paddedFamilyInTime H n f []) + have boolRun : StateTransition.EvalsToInTime + (TM2.step (MachineExpanderFamily.boolView MachineExpanderFamily.baseDegree_positive H + MachineExpanderFamily.baseDegree_cloud_gt_one)) + ⟨some (.inr .initialize), f, MachineExpanderFamily.toBoolTapes + (MachineExpanderFamily.initialTapes (PreprocessingLevels.boundedLevel n) [])⟩ + (some ⟨none, f, MachineExpanderFamily.toBoolTapes + (MachineExpanderFamily.familyTapes H (PreprocessingLevels.boundedLevel n) [])⟩) + (MachineExpanderFamilyBounds.inputCoefficient * (n + 1)^5) := by + simpa only [MachineExpanderFamily.boolView, MachineExpanderFamily.configuration_toBool, + caller] using castRun + have framed := MachineStateFrame.frameExecution + (MachineExpanderFamily.boolView MachineExpanderFamily.baseDegree_positive H + MachineExpanderFamily.baseDegree_cloud_gt_one) ((o, false), (none : Option Bool)) boolRun + have transported := MachineStateEquiv.execution (familyStates d) + (MachineStateFrame.frameProgram + (MachineExpanderFamily.boolView MachineExpanderFamily.baseDegree_positive H + MachineExpanderFamily.baseDegree_cloud_gt_one)) framed + have sourceRun : StateTransition.EvalsToInTime (TM2.step (familySource H d)) + ⟨some (.inr .initialize), clean H d hd, MachineExpanderFamily.toBoolTapes + (MachineExpanderFamily.initialTapes (PreprocessingLevels.boundedLevel n) [])⟩ + (some ⟨none, clean H d hd, MachineExpanderFamily.toBoolTapes + (MachineExpanderFamily.familyTapes H (PreprocessingLevels.boundedLevel n) [])⟩) + (MachineExpanderFamilyBounds.inputCoefficient * (n + 1)^5) := by + simpa only [familySource, MachineStateEquiv.configuration, + MachineStateFrame.frameConfiguration, Option.map_some, familyStates, + Equiv.coe_fn_mk, clean, f, o] + using transported + have run := placeExecution familyTape familyView familyView_left familyView_right + familyLabel (some overlayEntry) (paddedTapes t) (familySource H d) (program H d hd) + (fun _ => rfl) sourceRun + have finishRaw := family_final_memory H (PortTables.tableBits t) + (PortTables.tableBits (padded t)) (PreprocessingLevels.boundedLevel n) + have hsize : ExpanderTables.vertexCount overlayDegree (PreprocessingLevels.boundedLevel n) = + PreprocessingLevels.paddedSize n := PreprocessingLevels.table_vertexCount_eq_paddedSize n + have count : memory (PortTables.tableBits t) (PortTables.tableBits (padded t)) + (encodeWord 0) (rotor H n) + (encodeWord (ExpanderTables.vertexCount overlayDegree (PreprocessingLevels.boundedLevel n))) [] = + familyTapes H t := + congrArg (fun size => memory (PortTables.tableBits t) (PortTables.tableBits (padded t)) + (encodeWord 0) (rotor H n) (encodeWord size) []) hsize + have finish := finishRaw.trans count + simpa only [Placement.configuration, Placement.label, paddedTapes, + family_initial_memory, finish, familyEntry] using run + +theorem rotationWords_resize {n m q : Nat} (h : n = m) (H : ExpanderTables.Table n q) : + ExpanderTableWords.rotationWords (PreprocessingRegularTables.resizeTable h H) = + ExpanderTableWords.rotationWords H := by + cases h + rfl + +theorem rotor_familyAt (H : BaseTable) (n : Nat) : + MachineOverlayTable.rawExpander (PreprocessingStageMaps.familyAt H n) = rotor H n := by + unfold MachineOverlayTable.rawExpander PreprocessingStageMaps.familyAt rotor + exact congrArg encodeWords (rotationWords_resize + (PreprocessingLevels.table_vertexCount_eq_paddedSize n) + (ExpanderTables.family H (PreprocessingLevels.boundedLevel n))) + +theorem overlay_memory (input graph raw count output : List Bool) : + Placement.tapes overlayView + (MachineOverlayTable.memory graph raw [] [] [] [] [] [] [] output) + (memory input graph (encodeWord 0) raw count []) = + memory input graph (encodeWord 0) raw count output := by + funext k + rcases k with k | k + · cases k <;> simp [Placement.tapes, overlayView, memory, MachineVertexPadding.memory, + MachineOverlayTable.memory, MachineOverlayTable.graphArchive] + · rcases k with k | k + · rcases k with k | k + · rcases k with k | k <;> cases k <;> + simp [Placement.tapes, overlayView, memory, MachineExpanderFamily.tableTape, + MachineOverlayTable.memory, MachineOverlayTable.expanderArchive] + · cases k <;> + simp [Placement.tapes, overlayView, memory, MachineExpanderFamily.tableTape] + · rcases k with k | k <;> fin_cases k <;> + simp [Placement.tapes, overlayView, memory, MachineOverlayTable.memory, + MachineOverlayTable.graphArchive, MachineOverlayTable.expanderArchive, + MachineOverlayTable.output] + +noncomputable def overlayInTime (H : BaseTable) {n d : Nat} (hd : 0 < d) + (t : PortTables.Table n d) : + StateTransition.EvalsToInTime (TM2.step (program H d hd)) + ⟨some overlayEntry, clean H d hd, familyTapes H t⟩ + (some ⟨none, clean H d hd, finalTapes H t⟩) + ((MachineOverlayTable.timePolynomial d overlayDegree).eval + ((PortTables.tableBits (padded t)).length + (rotor H n).length)) := by + let f := MachineExpanderFamily.initialState MachineExpanderFamily.baseDegree_positive H () + have original := MachineOverlayTable.tableInTime d overlayDegree hd overlayDegree_positive + (padded t) (PreprocessingStageMaps.familyAt H n) () + have framed := MachineStateFrame.frameExecution + (MachineOverlayTable.program d overlayDegree hd overlayDegree_positive) + ((f, false), (none : Option Bool)) + original + have transported := MachineStateEquiv.execution (overlayStates d) + (MachineStateFrame.frameProgram + (MachineOverlayTable.program d overlayDegree hd overlayDegree_positive)) framed + have sourceRun : StateTransition.EvalsToInTime (TM2.step (overlaySource d hd)) + ⟨some (.inl .copyFirst), clean H d hd, + MachineOverlayTable.initialTapes (PortTables.tableBits (padded t)) (rotor H n)⟩ + (some ⟨none, clean H d hd, + MachineOverlayTable.memory (PortTables.tableBits (padded t)) (rotor H n) + [] [] [] [] [] [] [] + (PortTables.tableBits (PreprocessingStageMaps.paddedOverlay H d ⟨n, t⟩).2)⟩) + ((MachineOverlayTable.timePolynomial d overlayDegree).eval + ((PortTables.tableBits (padded t)).length + (rotor H n).length)) := by + simpa only [overlaySource, MachineStateEquiv.configuration, + MachineStateFrame.frameConfiguration, Option.map_some, overlayStates, Equiv.coe_fn_mk, clean, f, + rotor_familyAt, PreprocessingStageMaps.paddedOverlay, PreprocessingStageMaps.padding, + padded] using transported + have run := placeExecution overlayTape overlayView overlayView_left overlayView_right + overlayLabel none (familyTapes H t) (overlaySource d hd) (program H d hd) + (fun _ => rfl) sourceRun + simpa only [Placement.configuration, Placement.label, familyTapes, finalTapes, + MachineOverlayTable.initialTapes_memory, overlay_memory, overlayEntry] using run + +noncomputable def sizePolynomial : Polynomial Nat := + Polynomial.C ExpanderFamily.growth * (Polynomial.X + 1) + +noncomputable def archivePolynomial (d : Nat) : Polynomial Nat := + let s := sizePolynomial + s + s * Polynomial.C d + 2 + + (s * Polynomial.C d) * (s + s * Polynomial.C d + 8192) + + (s * Polynomial.C overlayDegree) * (s * Polynomial.C overlayDegree + 1) + +theorem archive_length_le (H : BaseTable) {n d : Nat} (t : PortTables.Table n d) : + (PortTables.tableBits (padded t)).length + (rotor H n).length ≤ + (archivePolynomial d).eval (PortTables.tableBits t).length := by + let m := PreprocessingLevels.paddedSize n + let s := ExpanderFamily.growth * ((PortTables.tableBits t).length + 1) + have hm : m ≤ s := MachineVertexPadding.power_length_bound t + have hmd : m*d ≤ s*d := Nat.mul_le_mul_right d hm + have hmq : m*overlayDegree ≤ s*overlayDegree := Nat.mul_le_mul_right overlayDegree hm + have hg := GraphTables.tableBits_length_le (PortTables.graphTable (padded t)) + change (PortTables.tableBits (padded t)).length ≤ + m + m*d + 2 + m*d*(m + m*d + 8192) at hg + have hg' := hg.trans (Nat.add_le_add + (Nat.add_le_add_right (Nat.add_le_add hm hmd) 2) + (Nat.mul_le_mul hmd (Nat.add_le_add_right (Nat.add_le_add hm hmd) 8192))) + have hr := ExpanderTableWords.encode_rotationWords_length_le + (PreprocessingStageMaps.familyAt H n) + change (MachineOverlayTable.rawExpander (PreprocessingStageMaps.familyAt H n)).length ≤ + (m*overlayDegree)*(m*overlayDegree+1) at hr + rw [rotor_familyAt] at hr + have hr' := hr.trans (Nat.mul_le_mul hmq (Nat.add_le_add_right hmq 1)) + have h := Nat.add_le_add hg' hr' + simpa only [archivePolynomial, sizePolynomial, Polynomial.eval_add, Polynomial.eval_mul, + Polynomial.eval_C, Polynomial.eval_X, Polynomial.eval_one, Polynomial.eval_ofNat, + s] using h + +noncomputable def familyPolynomial : Polynomial Nat := + Polynomial.C MachineExpanderFamilyBounds.inputCoefficient * (Polynomial.X + 1)^5 + +noncomputable def timePolynomial (d : Nat) : Polynomial Nat := + MachineVertexPadding.timePolynomial d + familyPolynomial + + (MachineOverlayTable.timePolynomial d overlayDegree).comp (archivePolynomial d) + +noncomputable def execution (H : BaseTable) {n d : Nat} (hd : 0 < d) + (t : PortTables.Table n d) : + StateTransition.EvalsToInTime (TM2.step (program H d hd)) + ⟨some main, clean H d hd, initialTapes t⟩ + (some ⟨none, clean H d hd, finalTapes H t⟩) + ((timePolynomial d).eval (PortTables.tableBits t).length) := by + let first := paddingInTime H hd t + let second := familyInTime H hd t + let third := overlayInTime H hd t + let firstTwo := StateTransition.EvalsToInTime.trans (TM2.step (program H d hd)) + _ _ _ _ _ first second + let all := StateTransition.EvalsToInTime.trans (TM2.step (program H d hd)) + _ _ _ _ _ firstTwo third + refine { toEvalsTo := all.toEvalsTo, steps_le_m := all.steps_le_m.trans ?_ } + have hn := PortTables.vertices_le_tableBits_length t + have hf := Nat.mul_le_mul_left MachineExpanderFamilyBounds.inputCoefficient + (Nat.pow_le_pow_left (Nat.add_le_add_right hn 1) 5) + have ho := natPolynomial_eval_mono (MachineOverlayTable.timePolynomial d overlayDegree) + (archive_length_le H t) + have h := Nat.add_le_add + (Nat.add_le_add (Nat.le_refl ((MachineVertexPadding.timePolynomial d).eval + (PortTables.tableBits t).length)) hf) ho + simpa only [timePolynomial, familyPolynomial, Polynomial.eval_add, Polynomial.eval_comp, + Polynomial.eval_mul, Polynomial.eval_C, Polynomial.eval_pow, Polynomial.eval_X, + Polynomial.eval_one, Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using h + +def machine (H : BaseTable) (d : Nat) (hd : 0 < d) : FinTM2 where + K := Tape + k₀ := .inl .original + k₁ := .inr (.inr MachineOverlayTable.output) + Γ := Alphabet + Λ := Label d + main := main + σ := State d + initialState := clean H d hd + m := program H d hd + +theorem alphabet_finite (H : BaseTable) (d : Nat) (hd : 0 < d) : + ∀ k, Finite ((machine H d hd).Γ k) := by + intro k + change Finite Bool + infer_instance + +theorem initial_configuration (H : BaseTable) {n d : Nat} (hd : 0 < d) + (t : PortTables.Table n d) : + initList (machine H d hd) (PortTables.tableBits t) = + ⟨some main, clean H d hd, initialTapes t⟩ := by + have ht : (initList (machine H d hd) (PortTables.tableBits t)).stk = initialTapes t := by + funext k + rcases k with k | k + · cases k <;> simp [initList, machine, initialTapes, memory, MachineVertexPadding.memory] + rfl + · rcases k with k | k + · rcases k with k | k + · rcases k with k | k <;> cases k <;> + simp [initList, machine, initialTapes, memory] + · cases k <;> simp [initList, machine, initialTapes, memory] + · simp [initList, machine, initialTapes, memory] + exact congrArg (TM2.Cfg.mk _ _) ht + +theorem final_output (H : BaseTable) {n d : Nat} (hd : 0 < d) + (t : PortTables.Table n d) : + finalTapes H t (machine H d hd).k₁ = + PortTables.inputBits (PreprocessingStageMaps.paddedOverlay H d ⟨n, t⟩) := by + simp [finalTapes, machine, memory, PortTables.inputBits] + +theorem original_preserved (H : BaseTable) {n d : Nat} (t : PortTables.Table n d) : + finalTapes H t (.inl .original) = PortTables.tableBits t := rfl + +end MinUncutGames.Foundations.Complexity.MachinePaddedOverlay + +end +section +namespace MinUncutGames.Foundations.Complexity.MachinePaddedOverlayRuntime + +open Turing +open PCP +open MachinePaddedOverlay (BaseTable Tape Label State) + + +def rawProgram (H : BaseTable) (d : Nat) (hd : 0 < d) : + MachineCanonicalOutput.Program Tape (Label d) (State d) where + input := .inl .original + output := .inr (.inr MachineOverlayTable.output) + main := MachinePaddedOverlay.main + initial := MachinePaddedOverlay.clean H d hd + code := MachinePaddedOverlay.program H d hd + +theorem sourceMachine_eq (H : BaseTable) (d : Nat) (hd : 0 < d) : + MachineCanonicalOutput.sourceMachine (rawProgram H d hd) = + MachinePaddedOverlay.machine H d hd := rfl + +noncomputable def cleanupTapes : List Tape := + (Finset.univ.erase (.inr (.inr MachineOverlayTable.output) : Tape)).toList + +theorem cleanup_complete (H : BaseTable) (d : Nat) (hd : 0 < d) (k : Tape) : + k ∈ cleanupTapes ↔ k ≠ (rawProgram H d hd).output := by + simp [cleanupTapes, rawProgram] + +theorem initial_configuration (H : BaseTable) (d : Nat) (hd : 0 < d) + (a : PortTables.Input d) : + initList (MachineCanonicalOutput.sourceMachine (rawProgram H d hd)) + (PortTables.inputBits a) = + ⟨some MachinePaddedOverlay.main, MachinePaddedOverlay.clean H d hd, + MachinePaddedOverlay.initialTapes a.2⟩ := by + change initList (MachinePaddedOverlay.machine H d hd) (PortTables.tableBits a.2) = _ + exact MachinePaddedOverlay.initial_configuration H hd a.2 + +noncomputable def terminalRun (H : BaseTable) (d : Nat) (hd : 0 < d) + (a : PortTables.Input d) : + MachineCanonicalOutput.TerminalRun (rawProgram H d hd) (PortTables.inputBits a) + (PortTables.inputBits (PreprocessingStageMaps.paddedOverlay H d a)) + ((MachinePaddedOverlay.timePolynomial d).eval (PortTables.inputBits a).length) where + state := MachinePaddedOverlay.clean H d hd + tapes := MachinePaddedOverlay.finalTapes H a.2 + execution := by + rw [initial_configuration] + exact MachinePaddedOverlay.execution H hd a.2 + output_eq := MachinePaddedOverlay.final_output H hd a.2 + +noncomputable def computableInPolyTime (H : BaseTable) (d : Nat) (hd : 0 < d) : + TM2ComputableInPolyTime (PortTables.inputBits (ports := d)) + (PortTables.inputBits (ports := d + MachinePaddedOverlay.overlayDegree)) + (PreprocessingStageMaps.paddedOverlay H d) := + MachineCanonicalOutput.computableInPolyTime (rawProgram H d hd) cleanupTapes + (cleanup_complete H d hd) PortTables.inputBits PortTables.inputBits + (PreprocessingStageMaps.paddedOverlay H d) (MachinePaddedOverlay.timePolynomial d) + (terminalRun H d hd) + +theorem finite_alphabet (H : BaseTable) (d : Nat) (hd : 0 < d) : + ∀ k, Finite ((computableInPolyTime H d hd).tm.Γ k) := + MachineCanonicalOutput.computableInPolyTime_finite_alphabet (rawProgram H d hd) cleanupTapes + (cleanup_complete H d hd) PortTables.inputBits PortTables.inputBits + (PreprocessingStageMaps.paddedOverlay H d) (MachinePaddedOverlay.timePolynomial d) + (terminalRun H d hd) + +end MinUncutGames.Foundations.Complexity.MachinePaddedOverlayRuntime + +end +section +namespace MinUncutGames.Foundations.Complexity.MachineLazyCodec +open PCP.GraphTables PCP.PreprocessingLazyWords + +theorem rowsBits_ofFn (v e count : Nat) : + MachineDummyRows.rowsBits v e count = + (List.ofFn fun p : Fin count => MachineDummyRows.rowBits v (e + p.val)).flatten := by + induction count generalizing e with + | zero => rfl + | succ count ih => + rw [MachineDummyRows.rowsBits, List.ofFn_succ, List.flatten_cons] + simp only [Fin.val_zero, Nat.add_zero] + apply congrArg (MachineDummyRows.rowBits v e ++ ·) + rw [ih] + apply congrArg List.flatten + congr 1 + funext p + simp only [Fin.val_succ] + congr 1 + omega + +theorem encodeWords_flatMap {α : Type*} (items : List α) (words : α → List Nat) : + encodeWords (items.flatMap words) = items.flatMap (fun x => encodeWords (words x)) := by + induction items with + | nil => rfl + | cons item items ih => simp only [List.flatMap_cons, encodeWords_append, ih] + +theorem rowBits_stay {n d : Nat} (v : Fin n) (p : Fin d) : + MachineDummyRows.rowBits v.val (2 * d * v.val + p.val) = + encodeWords (rowWords (stayRow d v p)) := by + have h := MachineDummyRows.rowBits_eq_graph_row v (stayRow d v p).reverseIndex + rw [stayRow_reverse_val] at h + exact h + +theorem rowsBits_stay {n d : Nat} (v : Fin n) : + MachineDummyRows.rowsBits v.val (2 * d * v.val) d = + encodeWords ((List.ofFn (stayRow d v)).flatMap rowWords) := by + rw [rowsBits_ofFn, encodeWords_flatMap] + simp only [List.flatMap_def, List.map_ofFn] + apply congrArg List.flatten + congr 1 + funext p + exact rowBits_stay v p + +end MinUncutGames.Foundations.Complexity.MachineLazyCodec + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachinePortReindex.lean b/lean/OAI/Computability/MinUncut/Machines/MachinePortReindex.lean new file mode 100644 index 0000000000000000000000000000000000000000..2a13901d00136ec380a90c7c8b5c72788c5b7b24 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachinePortReindex.lean @@ -0,0 +1,290 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineFixedDivMod + +namespace OAI + +section +namespace MinUncutGames.Foundations.Complexity.MachinePortReindex + +open Turing MachineComposition +open Reduction.MachineSubstitution (pushWord stepAux_pushWord) + +variable {K Λ A : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool +abbrev State (A : Type) (d : Nat) := MachineFixedDivMod.State A d + +def clean (d : Nat) (positive : 0 < d) (ambient : A) : State A d := + ((ambient, MachineFixedDivMod.residue d positive 0), none) + +inductive Label (d : Nat) + | copySeed | copyScan | copyRestore | initialize | divide + | emit (r : Fin d) + | affineScan | affineRestore | drainQuotient | finish + deriving DecidableEq, Fintype + +def exitAt {divisor : Nat} (exit : Option Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (State A divisor) := + match exit with + | none => .halt + | some label => .goto fun _ => label + +def emit (d : Nat) (positive : 0 < d) (output : K) (b : Nat) + (r : Fin d) (next : Λ) : TM2.Stmt (Alphabet (K := K)) Λ (State A d) := + pushWord output (List.replicate (r.val + b) true) + (.load (fun s => clean d positive s.1.1) (.goto fun _ => next)) + +def instruction (d : Nat) (positive : 0 < d) (c b : Nat) + (tape : Fin 5 → K) (labels : Label d → Λ) (exit : Option Λ) : + Label d → TM2.Stmt (Alphabet (K := K)) Λ (State A d) + | .copySeed => MachineUnaryAffineAt.seed (tape 2) 0 (labels .copyScan) + | .copyScan => MachineUnaryAffineAt.scan (tape 0) (tape 1) (tape 2) 1 + (labels .copyScan) (labels .copyRestore) + | .copyRestore => Reduction.MachineTransfer.loopAt (tape 1) (tape 0) id false + (labels .copyRestore) (some (labels .initialize)) + | .initialize => .push (tape 3) (fun _ => false) + (.push (tape 4) (fun _ => false) (.goto fun _ => labels .divide)) + | .divide => MachineFixedDivMod.scanLoop d positive (tape 2) (tape 3) + (labels .divide) (fun r => labels (.emit r)) + | .emit r => emit d positive (tape 4) b r (labels .affineScan) + | .affineScan => MachineUnaryAffineAt.scan (tape 3) (tape 1) (tape 4) c + (labels .affineScan) (labels .affineRestore) + | .affineRestore => Reduction.MachineTransfer.loopAt (tape 1) (tape 3) id false + (labels .affineRestore) (some (labels .drainQuotient)) + | .drainQuotient => MachineDrain.drain (tape 3) (labels .drainQuotient) + (some (labels .finish)) + | .finish => .pop (tape 2) (fun s _ => clean d positive s.1.1) (exitAt exit) + +def steps (d j : Nat) : Nat := 3 * j + 3 * (j / d) + 11 + +theorem steps_le (d j : Nat) : steps d j ≤ 6 * j + 11 := by + have h := Nat.div_le_self j d + unfold steps + omega + +theorem steps_le_encodedLength (d j : Nat) : + steps d j ≤ 6 * (encodeWord j).length + 5 := by + have h := steps_le d j + rw [encodeWord_length] + omega + +def value (d c b j : Nat) : Nat := c * (j / d) + (j % d) + b + +def frame (tape : Fin 5 → K) (base : K → List Bool) + (work quotient output : List Bool) : K → List Bool := + MachineCopy.forkTapes (tape 2) (tape 3) (tape 4) base work quotient output + +theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +theorem reindexTrace (d : Nat) (positive : 0 < d) (c b : Nat) + (tape : Fin 5 → K) (distinct : Function.Injective tape) + (labels : Label d → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A d)) + (atLabels : ∀ l, program (labels l) = instruction d positive c b tape labels exit l) + (base : K → List Bool) (j : Nat) (suffix : List Bool) + (sourceWord : base (tape 0) = encodeWord j ++ suffix) + (scratchEmpty : base (tape 1) = []) (workEmpty : base (tape 2) = []) + (quotientEmpty : base (tape 3) = []) (ambient : A) : + (advance (TM2.step program))^[steps d j] + (some ⟨some (labels .copySeed), clean d positive ambient, base⟩) = + some ⟨exit, clean d positive ambient, + Function.update base (tape 4) (encodeWord (value d c b j) ++ base (tape 4))⟩ := by + have hd (i k : Fin 5) (h : i ≠ k) : tape i ≠ tape k := fun e => h (distinct e) + let q := j / d + let r := MachineFixedDivMod.residue d positive j + let copied := Function.update base (tape 2) (encodeWord j) + let initialized := frame tape base (encodeWord j) (encodeWord 0) + (encodeWord 0 ++ base (tape 4)) + let divided := frame tape base (encodeWord 0) (encodeWord q) + (encodeWord 0 ++ base (tape 4)) + let emitted := frame tape base (encodeWord 0) (encodeWord q) + (encodeWord (r.val + b) ++ base (tape 4)) + let computed := frame tape base (encodeWord 0) (encodeWord q) + (encodeWord (c * q + (r.val + b)) ++ base (tape 4)) + let drained := frame tape base (encodeWord 0) [] + (encodeWord (c * q + (r.val + b)) ++ base (tape 4)) + have copyRun : (advance (TM2.step program))^[2 * (j + 1) + 1] + (some ⟨some (labels .copySeed), clean d positive ambient, base⟩) = + some ⟨some (labels .initialize), clean d positive ambient, copied⟩ := by + simpa only [clean, copied, Nat.one_mul, Nat.add_zero, workEmpty, List.append_nil] using + MachineUnaryAffineAt.seededAffineTrace (tape 0) (tape 1) (tape 2) + (hd 0 1 (by decide)) (hd 0 2 (by decide)) (hd 1 2 (by decide)) 1 0 + (labels .copySeed) (labels .copyScan) (labels .copyRestore) + (some (labels .initialize)) program (atLabels .copySeed) (atLabels .copyScan) + (atLabels .copyRestore) base j suffix sourceWord scratchEmpty + (ambient, MachineFixedDivMod.residue d positive 0) none + have initRun : (advance (TM2.step program))^[1] + (some ⟨some (labels .initialize), clean d positive ambient, copied⟩) = + some ⟨some (labels .divide), clean d positive ambient, initialized⟩ := by + change some (TM2.stepAux (program (labels .initialize)) _ _) = _ + rw [atLabels] + simp [instruction, TM2.stepAux, copied, initialized, frame, MachineCopy.forkTapes, + hd 3 2 (by decide), hd 4 2 (by decide), hd 4 3 (by decide), quotientEmpty, encodeWord] + have divisionInput : MachineFixedDivMod.unaryTapes (tape 2) (tape 3) (tape 4) + base j 0 0 [] [] (base (tape 4)) = initialized := by + simp only [MachineFixedDivMod.unaryTapes, MachineFixedDivMod.tapes, + List.append_nil, initialized, frame] + have divisionOutput : MachineFixedDivMod.unaryTapes (tape 2) (tape 3) (tape 4) + base 0 q 0 [] [] (base (tape 4)) = divided := by + simp only [MachineFixedDivMod.unaryTapes, MachineFixedDivMod.tapes, + List.append_nil, divided, frame] + have divideRun : (advance (TM2.step program))^[j + 1] + (some ⟨some (labels .divide), clean d positive ambient, initialized⟩) = + some ⟨some (labels (.emit r)), ((ambient, r), some false), divided⟩ := by + have h := MachineFixedDivMod.scanTrace_fromCount d positive (tape 2) (tape 3) (tape 4) + (hd 2 3 (by decide)) (hd 2 4 (by decide)) (hd 3 4 (by decide)) + (labels .divide) (fun a => labels (.emit a)) program (atLabels .divide) + base j 0 [] [] (base (tape 4)) ambient none + simpa only [Nat.zero_div, Nat.zero_add, divisionInput, divisionOutput, clean, r, q] using h + have emitRun : (advance (TM2.step program))^[1] + (some ⟨some (labels (.emit r)), ((ambient, r), some false), divided⟩) = + some ⟨some (labels .affineScan), clean d positive ambient, emitted⟩ := by + change some (TM2.stepAux (program (labels (.emit r))) _ _) = _ + rw [atLabels] + simp [instruction, emit, stepAux_pushWord, TM2.stepAux, divided, emitted, frame, + MachineCopy.forkTapes, List.reverse_replicate, encodeWord, List.append_assoc] + have affineInput : MachineUnaryAffineAt.tapes (tape 3) (tape 1) (tape 4) + emitted (encodeWord q ++ []) [] (encodeWord (r.val + b) ++ base (tape 4)) = emitted := by + have heq : emitted (tape 3) = encodeWord q := by + simp [emitted, frame, MachineCopy.forkTapes, hd 3 4 (by decide)] + have hempty : emitted (tape 1) = [] := by + simp [emitted, frame, MachineCopy.forkTapes, hd 1 2 (by decide), + hd 1 3 (by decide), hd 1 4 (by decide), scratchEmpty] + have hout : emitted (tape 4) = encodeWord (r.val + b) ++ base (tape 4) := by + simp [emitted, frame, MachineCopy.forkTapes] + rw [List.append_nil, ← heq, ← hempty, ← hout] + exact MachineCopy.forkTapes_self _ _ _ _ + have affineOutput : MachineUnaryAffineAt.tapes (tape 3) (tape 1) (tape 4) + emitted (encodeWord q ++ []) [] (encodeWord (c * q + (r.val + b)) ++ base (tape 4)) = + computed := by + funext k + by_cases h1 : k = tape 1 + · subst k + simp [MachineUnaryAffineAt.tapes, emitted, computed, frame, MachineCopy.forkTapes, + hd 1 2 (by decide), hd 1 3 (by decide), hd 1 4 (by decide), scratchEmpty] + · by_cases h3 : k = tape 3 + · subst k + simp [MachineUnaryAffineAt.tapes, emitted, computed, frame, MachineCopy.forkTapes, + hd 3 1 (by decide), hd 3 4 (by decide)] + · by_cases h4 : k = tape 4 + · subst k; simp [MachineUnaryAffineAt.tapes, computed, frame, MachineCopy.forkTapes] + · simp [MachineUnaryAffineAt.tapes, emitted, computed, frame, MachineCopy.forkTapes, + h1, h3, h4] + have affineRun : (advance (TM2.step program))^[2 * (q + 1)] + (some ⟨some (labels .affineScan), clean d positive ambient, emitted⟩) = + some ⟨some (labels .drainQuotient), clean d positive ambient, computed⟩ := by + have h := MachineUnaryAffineAt.affineTrace (tape 3) (tape 1) (tape 4) + (hd 3 1 (by decide)) (hd 3 4 (by decide)) (hd 1 4 (by decide)) c + (labels .affineScan) (labels .affineRestore) (some (labels .drainQuotient)) + program (atLabels .affineScan) (atLabels .affineRestore) emitted q (r.val + b) + [] (base (tape 4)) (ambient, MachineFixedDivMod.residue d positive 0) none + simpa only [affineInput, affineOutput, clean] using h + have quotientWord : computed (tape 3) = encodeWord q := by + simp [computed, frame, MachineCopy.forkTapes, hd 3 4 (by decide)] + have drainOutput : Function.update computed (tape 3) [] = drained := by + funext k + by_cases h3 : k = tape 3 + · subst k + simp [drained, frame, MachineCopy.forkTapes, hd 3 4 (by decide)] + · by_cases h4 : k = tape 4 + · subst k + simp [computed, drained, frame, MachineCopy.forkTapes, hd 4 3 (by decide)] + · simp [computed, drained, frame, MachineCopy.forkTapes, h3, h4] + have drainRun : (advance (TM2.step program))^[q + 2] + (some ⟨some (labels .drainQuotient), clean d positive ambient, computed⟩) = + some ⟨some (labels .finish), clean d positive ambient, drained⟩ := by + have h := MachineDrain.drainTrace (tape 3) (labels .drainQuotient) + (some (labels .finish)) program (atLabels .drainQuotient) + computed (computed (tape 3)) (ambient, MachineFixedDivMod.residue d positive 0) none + rw [Function.update_eq_self, drainOutput, quotientWord, encodeWord_length] at h + exact h + have finishOutput : Function.update drained (tape 2) [] = + Function.update base (tape 4) (encodeWord (value d c b j) ++ base (tape 4)) := by + have hv : c * q + (r.val + b) = value d c b j := by + simp [value, q, r, MachineFixedDivMod.residue, Nat.add_assoc] + funext k + by_cases h2 : k = tape 2 + · subst k + simp [hd 2 4 (by decide), workEmpty] + · by_cases h3 : k = tape 3 + · subst k + simp [drained, frame, MachineCopy.forkTapes, hd 3 2 (by decide), + hd 3 4 (by decide), quotientEmpty] + · by_cases h4 : k = tape 4 + · subst k + simp [drained, frame, MachineCopy.forkTapes, hd 4 2 (by decide), hv] + · simp [drained, frame, MachineCopy.forkTapes, h2, h3, h4] + have finishRun : (advance (TM2.step program))^[1] + (some ⟨some (labels .finish), clean d positive ambient, drained⟩) = + some ⟨exit, clean d positive ambient, + Function.update base (tape 4) (encodeWord (value d c b j) ++ base (tape 4))⟩ := by + have hw : drained (tape 2) = encodeWord 0 := by + simp [drained, frame, MachineCopy.forkTapes, hd 2 3 (by decide), hd 2 4 (by decide)] + change some (TM2.stepAux (program (labels .finish)) _ _) = _ + rw [atLabels] + cases exit <;> simp [instruction, TM2.stepAux, exitAt, hw, encodeWord, finishOutput, clean] + have total := joinTrace (joinTrace (joinTrace (joinTrace (joinTrace + (joinTrace copyRun initRun) divideRun) emitRun) affineRun) drainRun) finishRun + have hsteps : steps d j = + (((((2 * (j + 1) + 1) + 1) + (j + 1)) + 1) + 2 * (q + 1)) + (q + 2) + 1 := by + dsimp [steps, q] + omega + rw [hsteps] + exact total + +def reindexInTime (d : Nat) (positive : 0 < d) (c b : Nat) + (tape : Fin 5 → K) (distinct : Function.Injective tape) + (labels : Label d → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A d)) + (atLabels : ∀ l, program (labels l) = instruction d positive c b tape labels exit l) + (base : K → List Bool) (j : Nat) (suffix : List Bool) + (sourceWord : base (tape 0) = encodeWord j ++ suffix) + (scratchEmpty : base (tape 1) = []) (workEmpty : base (tape 2) = []) + (quotientEmpty : base (tape 3) = []) (ambient : A) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .copySeed), clean d positive ambient, base⟩ + (some ⟨exit, clean d positive ambient, + Function.update base (tape 4) (encodeWord (value d c b j) ++ base (tape 4))⟩) + (6 * j + 11) where + steps := steps d j + evals_in_steps := reindexTrace d positive c b tape distinct labels exit program atLabels + base j suffix sourceWord scratchEmpty workEmpty quotientEmpty ambient + steps_le_m := steps_le d j + +def machine (d : Nat) (positive : 0 < d) (c b : Nat) : FinTM2 where + K := Fin 5 + k₀ := 0 + k₁ := 4 + Γ _ := Bool + Λ := Label d + main := .copySeed + σ := State Unit d + initialState := clean d positive () + m := instruction d positive c b id id none + +def machineInTime (d : Nat) (positive : 0 < d) (c b : Nat) + (base : Fin 5 → List Bool) (j : Nat) (suffix : List Bool) + (sourceWord : base 0 = encodeWord j ++ suffix) + (scratchEmpty : base 1 = []) (workEmpty : base 2 = []) + (quotientEmpty : base 3 = []) : + StateTransition.EvalsToInTime (machine d positive c b).step + ⟨some .copySeed, clean d positive (), base⟩ + (some ⟨none, clean d positive (), + Function.update base (4 : Fin 5) (encodeWord (value d c b j) ++ base 4)⟩) + (6 * j + 11) := + reindexInTime d positive c b id (fun _ _ h => h) id none + (instruction d positive c b id id none) (fun _ => rfl) + base j suffix sourceWord scratchEmpty workEmpty quotientEmpty () + +theorem lazy_value (d j : Nat) : value d (2 * d) d j = + 2 * d * (j / d) + d + (j % d) := by + unfold value + omega + +end MinUncutGames.Foundations.Complexity.MachinePortReindex + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachinePreservingLookup.lean b/lean/OAI/Computability/MinUncut/Machines/MachinePreservingLookup.lean new file mode 100644 index 0000000000000000000000000000000000000000..29cf88b7ae31291f4cb827ba6300951ec6934bf7 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachinePreservingLookup.lean @@ -0,0 +1,275 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineFiniteAlphabet + +namespace OAI + +namespace MinUncutGames.Foundations.Complexity.MachinePreservingLookup + +open Turing +open MachineComposition + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool + +def initialTapes (tape : Fin 5 → K) (base : K → List Bool) + (index : Nat) (indexSuffix workSuffix output : List Bool) : K → List Bool := + MachineLookup.tapes (tape 1) (tape 2) (tape 3) base + (encodeWord index ++ indexSuffix) workSuffix output + +def finalTapes (tape : Fin 5 → K) (base : K → List Bool) + (values : List Nat) (index value : Nat) + (indexSuffix workSuffix output : List Bool) : K → List Bool := + MachineLookup.tapes (tape 1) (tape 2) (tape 3) base + (encodeWord 0 ++ indexSuffix) + (encodeWords (values.drop (index + 1)) ++ workSuffix) (encodeWord value ++ output) + +theorem lookupFramedHaltTrace_some (index source destination : K) + (his : index ≠ source) (hid : index ≠ destination) (hsd : source ≠ destination) + (base : K → List Bool) (values : List Nat) (i value : Nat) + (selected : values[i]? = some value) (indexSuffix suffix output : List Bool) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step (MachineLookup.program index source destination)))^[ + MachineLookupSpec.steps values i + 1] + (some ⟨some MachineLookup.Label.guard, (ambient,register), + MachineLookup.tapes index source destination base (encodeWord i ++ indexSuffix) + (encodeWords values ++ suffix) output⟩) = + some ⟨none, (ambient,none), MachineLookup.tapes index source destination base + (encodeWord 0 ++ indexSuffix) (encodeWords (values.drop (i + 1)) ++ suffix) + (encodeWord value ++ output)⟩ := by + rw [Function.iterate_succ_apply', + MachineLookup.lookupTrace_some index source destination his hid hsd + base values i value selected indexSuffix suffix output ambient register] + simp only [advance_some, TM2.step, MachineLookup.program, TM2.stepAux] + +theorem preservingLookupTrace (tape : Fin 5 → K) (distinct : Function.Injective tape) + (firstLabel secondLabel : Λ) (lookupLabels : MachineLookup.Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atFirst : program firstLabel = Reduction.MachineTransfer.loopAt + (tape 0) (tape 4) id false firstLabel (some secondLabel)) + (atSecond : program secondLabel = MachineCopy.forkLoop + (tape 4) (tape 0) (tape 2) false secondLabel (some (lookupLabels .guard))) + (atLookup : ∀ l, program (lookupLabels l) = + MachineSubroutine.statement lookupLabels exit (MachineLookup.program (tape 1) (tape 2) (tape 3) l)) + (base : K → List Bool) (values : List Nat) (tableWord : base (tape 0) = encodeWords values) + (scratchEmpty : base (tape 4) = []) (i value : Nat) (selected : values[i]? = some value) + (indexSuffix workSuffix output : List Bool) (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[ + 2 * ((encodeWords values).length + 1) + MachineLookupSpec.steps values i + 1] + (some ⟨some firstLabel, (ambient,register), + initialTapes tape base i indexSuffix workSuffix output⟩) = + some ⟨exit, (ambient,none), finalTapes tape base values i value indexSuffix workSuffix output⟩ := by + have hd (a b : Fin 5) (hne : a ≠ b) : tape a ≠ tape b := fun h => hne (distinct h) + let start := initialTapes tape base i indexSuffix workSuffix output + have htable : start (tape 0) = encodeWords values := by + simpa only [start, initialTapes, MachineLookup.tapes_other _ _ _ _ + (hd 0 1 (by decide)) (hd 0 2 (by decide)) (hd 0 3 (by decide))] using tableWord + have hs : start (tape 4) = [] := by + simpa only [start, initialTapes, MachineLookup.tapes_other _ _ _ _ + (hd 4 1 (by decide)) (hd 4 2 (by decide)) (hd 4 3 (by decide))] using scratchEmpty + have hwork : start (tape 2) = workSuffix := by + simp only [start, initialTapes, MachineLookup.tapes_source _ _ _ (hd 2 3 (by decide))] + have hcopy := MachineCopy.copyTrace (tape 0) (tape 2) (tape 4) + (hd 0 2 (by decide)) (hd 0 4 (by decide)) (hd 2 4 (by decide)) false + firstLabel secondLabel (some (lookupLabels .guard)) program atFirst atSecond start hs ambient register + rw [htable, hwork] at hcopy + simp only [start, initialTapes, MachineLookup.update_source _ _ _ (hd 2 3 (by decide))] at hcopy + have hlookup := MachineSubroutine.trace lookupLabels exit + (MachineLookup.program (tape 1) (tape 2) (tape 3)) program atLookup + (MachineLookupSpec.steps values i + 1) _ _ + (lookupFramedHaltTrace_some (tape 1) (tape 2) (tape 3) + (hd 1 2 (by decide)) (hd 1 3 (by decide)) (hd 2 3 (by decide)) + base values i value selected indexSuffix workSuffix output ambient none) + simp only [MachineSubroutine.configuration, MachineSubroutine.label] at hlookup + rw [show 2 * ((encodeWords values).length + 1) + MachineLookupSpec.steps values i + 1 = + (MachineLookupSpec.steps values i + 1) + 2 * ((encodeWords values).length + 1) by omega, + Function.iterate_add_apply] + change (advance (TM2.step program))^[MachineLookupSpec.steps values i + 1] + ((advance (TM2.step program))^[2 * ((encodeWords values).length + 1)] + (some ⟨some firstLabel, (ambient,register), + MachineLookup.tapes (tape 1) (tape 2) (tape 3) base + (encodeWord i ++ indexSuffix) workSuffix output⟩)) = _ + rw [hcopy] + exact hlookup + +theorem preservingLookup_steps_le (values : List Nat) (i value : Nat) + (selected : values[i]? = some value) : + 2 * ((encodeWords values).length + 1) + MachineLookupSpec.steps values i + 1 ≤ + 5 * (encodeWords values).length + 3 := by + have ht := MachineLookupSpec.steps_le_input_encoding_size values i + have hi := MachineLookupSpec.index_length_le values i value selected + omega + +def preservingLookupInTime (tape : Fin 5 → K) (distinct : Function.Injective tape) + (firstLabel secondLabel : Λ) (lookupLabels : MachineLookup.Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atFirst : program firstLabel = Reduction.MachineTransfer.loopAt + (tape 0) (tape 4) id false firstLabel (some secondLabel)) + (atSecond : program secondLabel = MachineCopy.forkLoop + (tape 4) (tape 0) (tape 2) false secondLabel (some (lookupLabels .guard))) + (atLookup : ∀ l, program (lookupLabels l) = + MachineSubroutine.statement lookupLabels exit (MachineLookup.program (tape 1) (tape 2) (tape 3) l)) + (base : K → List Bool) (values : List Nat) (tableWord : base (tape 0) = encodeWords values) + (scratchEmpty : base (tape 4) = []) (i value : Nat) (selected : values[i]? = some value) + (indexSuffix workSuffix output : List Bool) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some firstLabel, (ambient,register), initialTapes tape base i indexSuffix workSuffix output⟩ + (some ⟨exit, (ambient,none), finalTapes tape base values i value indexSuffix workSuffix output⟩) + (5 * (encodeWords values).length + 3) where + steps := 2 * ((encodeWords values).length + 1) + MachineLookupSpec.steps values i + 1 + evals_in_steps := preservingLookupTrace tape distinct firstLabel secondLabel lookupLabels exit + program atFirst atSecond atLookup base values tableWord scratchEmpty i value selected + indexSuffix workSuffix output ambient register + steps_le_m := preservingLookup_steps_le values i value selected + +inductive Label + | copyFirst | copySecond | lookup (l : MachineLookup.Label) + deriving DecidableEq, Fintype + +def program (tape : Fin 5 → K) : + Label → TM2.Stmt (Alphabet (K := K)) Label (σ × Option Bool) + | .copyFirst => Reduction.MachineTransfer.loopAt (tape 0) (tape 4) id false .copyFirst (some .copySecond) + | .copySecond => MachineCopy.forkLoop (tape 4) (tape 0) (tape 2) false .copySecond (some (.lookup .guard)) + | .lookup l => MachineSubroutine.statement Label.lookup none + (MachineLookup.program (tape 1) (tape 2) (tape 3) l) + +def machine : FinTM2 where + K := Fin 5 + k₀ := 0 + k₁ := 3 + Γ _ := Bool + Λ := Label + main := .copyFirst + σ := Unit × Option Bool + initialState := ((),none) + m := program id + +end MinUncutGames.Foundations.Complexity.MachinePreservingLookup + +namespace MinUncutGames.Foundations.Complexity.MachineAffineLookup + +open Turing +open MachineComposition + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool + +inductive Label + | seed | scan | restore | copyFirst | copySecond + | lookup (l : MachineLookup.Label) + deriving DecidableEq, Fintype + +def instruction (source : K) (tape : Fin 5 → K) (coefficient offset : Nat) + (labels : Label → Λ) (exit : Option Λ) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) + | .seed => MachineUnaryAffineAt.seed (tape 1) offset (labels .scan) + | .scan => MachineUnaryAffineAt.scan source (tape 4) (tape 1) + coefficient (labels .scan) (labels .restore) + | .restore => Reduction.MachineTransfer.loopAt (tape 4) source id false + (labels .restore) (some (labels .copyFirst)) + | .copyFirst => Reduction.MachineTransfer.loopAt (tape 0) (tape 4) id false + (labels .copyFirst) (some (labels .copySecond)) + | .copySecond => MachineCopy.forkLoop (tape 4) (tape 0) (tape 2) false + (labels .copySecond) (some (labels (.lookup .guard))) + | .lookup l => MachineSubroutine.statement (fun q => labels (.lookup q)) exit + (MachineLookup.program (tape 1) (tape 2) (tape 3) l) + +def steps (values : List Nat) (a coefficient offset : Nat) : Nat := + (2 * (a + 1) + 1) + + (2 * ((encodeWords values).length + 1) + + MachineLookupSpec.steps values (coefficient * a + offset) + 1) + +def finalTapes (tape : Fin 5 → K) (base : K → List Bool) + (values : List Nat) (index value : Nat) : K → List Bool := + MachinePreservingLookup.finalTapes tape base values index value + (base (tape 1)) (base (tape 2)) (base (tape 3)) + +theorem initialTapes_eq_update (tape : Fin 5 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (i : Nat) : + MachinePreservingLookup.initialTapes tape base i + (base (tape 1)) (base (tape 2)) (base (tape 3)) = + Function.update base (tape 1) (encodeWord i ++ base (tape 1)) := by + have hd (a b : Fin 5) (hne : a ≠ b) : tape a ≠ tape b := fun h => hne (distinct h) + funext k + by_cases h₁ : k = tape 1 + · subst k + simp [MachinePreservingLookup.initialTapes, MachineLookup.tapes, + hd 1 2 (by decide), hd 1 3 (by decide)] + · by_cases h₂ : k = tape 2 + · subst k + simp [MachinePreservingLookup.initialTapes, MachineLookup.tapes, h₁, + hd 2 3 (by decide)] + · by_cases h₃ : k = tape 3 + · subst k + simp [MachinePreservingLookup.initialTapes, MachineLookup.tapes, h₁] + · simp [MachinePreservingLookup.initialTapes, MachineLookup.tapes, h₁, h₂, h₃] + +theorem affineLookupTrace (source : K) (tape : Fin 5 → K) + (distinct : Function.Injective tape) (outside : ∀ i, source ≠ tape i) + (coefficient offset : Nat) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atLabels : ∀ l, program (labels l) = instruction source tape coefficient offset labels exit l) + (base : K → List Bool) (values : List Nat) + (tableWord : base (tape 0) = encodeWords values) (scratchEmpty : base (tape 4) = []) + (a : Nat) (suffix : List Bool) (sourceWord : base source = encodeWord a ++ suffix) + (value : Nat) (selected : values[coefficient * a + offset]? = some value) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[steps values a coefficient offset] + (some ⟨some (labels .seed), (ambient,register), base⟩) = + some ⟨exit, (ambient,none), finalTapes tape base values (coefficient * a + offset) value⟩ := by + have hd (i j : Fin 5) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + have haffine := MachineUnaryAffineAt.seededAffineTrace source (tape 4) (tape 1) + (outside 4) (outside 1) (hd 4 1 (by decide)) coefficient offset + (labels .seed) (labels .scan) (labels .restore) (some (labels .copyFirst)) + program (atLabels .seed) (atLabels .scan) (atLabels .restore) + base a suffix sourceWord scratchEmpty ambient register + have hlookup := MachinePreservingLookup.preservingLookupTrace tape distinct + (labels .copyFirst) (labels .copySecond) (fun q => labels (.lookup q)) exit + program (atLabels .copyFirst) (atLabels .copySecond) (fun q => atLabels (.lookup q)) + base values tableWord scratchEmpty (coefficient * a + offset) value selected + (base (tape 1)) (base (tape 2)) (base (tape 3)) ambient none + rw [initialTapes_eq_update tape distinct] at hlookup + rw [steps, Nat.add_comm, Function.iterate_add_apply, haffine] + exact hlookup + +theorem steps_le (values : List Nat) (a coefficient offset value : Nat) + (selected : values[coefficient * a + offset]? = some value) : + steps values a coefficient offset ≤ 2 * a + 5 * (encodeWords values).length + 6 := by + have h := MachinePreservingLookup.preservingLookup_steps_le values + (coefficient * a + offset) value selected + unfold steps + omega + +theorem steps_le_table (values : List Nat) (a coefficient offset value : Nat) + (selected : values[coefficient * a + offset]? = some value) + (ha : a ≤ (encodeWords values).length) : + steps values a coefficient offset ≤ 7 * (encodeWords values).length + 6 := by + have h := steps_le values a coefficient offset value selected + omega + +theorem finalTapes_other (tape : Fin 5 → K) (base : K → List Bool) + (values : List Nat) (index value : Nat) (k : K) + (h₁ : k ≠ tape 1) (h₂ : k ≠ tape 2) (h₃ : k ≠ tape 3) : + finalTapes tape base values index value k = base k := + MachineLookup.tapes_other _ _ _ _ h₁ h₂ h₃ _ _ _ _ + +theorem finalTapes_output (tape : Fin 5 → K) (base : K → List Bool) + (values : List Nat) (index value : Nat) : + finalTapes tape base values index value (tape 3) = encodeWord value ++ base (tape 3) := + MachineLookup.tapes_destination _ _ _ _ _ _ _ + +def machine (coefficient offset : Nat) : FinTM2 where + K := Fin 6 + k₀ := 0 + k₁ := 4 + Γ _ := Bool + Λ := Label + main := .seed + σ := Unit × Option Bool + initialState := ((),none) + m := instruction 0 Fin.succ coefficient offset id none + +end MinUncutGames.Foundations.Complexity.MachineAffineLookup + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineRegisterEmit.lean b/lean/OAI/Computability/MinUncut/Machines/MachineRegisterEmit.lean new file mode 100644 index 0000000000000000000000000000000000000000..964acb0be9d43574c34a37bd4adfa84d52ce188a --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineRegisterEmit.lean @@ -0,0 +1,174 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineSubstitution + +namespace OAI + +section +namespace MinUncutGames.Foundations.Complexity.MachineRegisterEmit + +open Turing +open MinUncutGames.Reduction.MachineSubstitution + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool + +def finish (exit : Option Λ) : TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) := + match exit with + | none => .halt + | some label => .goto fun _ => label + +def emitStatement (destination : K) (offset : Nat) (exit : Option Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) := + pushWord destination (List.replicate offset true) (finish exit) + +theorem emitStep (destination : K) (offset : Nat) (emitLabel : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atEmit : program emitLabel = emitStatement destination offset exit) + (base : K → List Bool) (ambient : σ) (register : Option Bool) : + TM2.step program ⟨some emitLabel, (ambient, register), base⟩ = + some ⟨exit, (ambient, register), + Function.update base destination (List.replicate offset true ++ base destination)⟩ := by + change some (TM2.stepAux (program emitLabel) (ambient, register) base) = _ + rw [atEmit, emitStatement, stepAux_pushWord] + cases exit <;> simp [finish, TM2.stepAux] + +theorem prefix_encodeWord (offset n : Nat) : + List.replicate offset true ++ encodeWord n = encodeWord (offset + n) := by + simp only [encodeWord, List.replicate_add, List.append_assoc] + +theorem registerEmitTrace (source destination scratch : K) + (sourceDestination : source ≠ destination) (sourceScratch : source ≠ scratch) + (destinationScratch : destination ≠ scratch) (offset : Nat) + (firstLabel secondLabel emitLabel : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atFirst : program firstLabel = + Reduction.MachineTransfer.loopAt source scratch id false firstLabel (some secondLabel)) + (atSecond : program secondLabel = + MachineCopy.forkLoop scratch source destination false secondLabel (some emitLabel)) + (atEmit : program emitLabel = emitStatement destination offset exit) + (base : K → List Bool) (n : Nat) (sourceWord : base source = encodeWord n) + (scratchEmpty : base scratch = []) (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[2 * n + 5] + (some ⟨some firstLabel, (ambient, register), base⟩) = + some ⟨exit, (ambient, none), + Function.update base destination (encodeWord (offset + n) ++ base destination)⟩ := by + have copied := MachineCopy.copyTrace source destination scratch sourceDestination + sourceScratch destinationScratch false firstLabel secondLabel (some emitLabel) + program atFirst atSecond base scratchEmpty ambient register + rw [sourceWord, encodeWord_length] at copied + rw [show 2 * n + 5 = 1 + 2 * (n + 1 + 1) by omega, + Function.iterate_add_apply, copied, Function.iterate_one] + change TM2.step program + ⟨some emitLabel, (ambient, none), + Function.update base destination (encodeWord n ++ base destination)⟩ = _ + rw [emitStep destination offset emitLabel exit program atEmit] + simp only [Function.update_self, Function.update_idem] + rw [← List.append_assoc, prefix_encodeWord] + +def registerEmitInTime (source destination scratch : K) + (sourceDestination : source ≠ destination) (sourceScratch : source ≠ scratch) + (destinationScratch : destination ≠ scratch) (offset : Nat) + (firstLabel secondLabel emitLabel : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atFirst : program firstLabel = + Reduction.MachineTransfer.loopAt source scratch id false firstLabel (some secondLabel)) + (atSecond : program secondLabel = + MachineCopy.forkLoop scratch source destination false secondLabel (some emitLabel)) + (atEmit : program emitLabel = emitStatement destination offset exit) + (base : K → List Bool) (n : Nat) (sourceWord : base source = encodeWord n) + (scratchEmpty : base scratch = []) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some firstLabel, (ambient, register), base⟩ + (some ⟨exit, (ambient, none), + Function.update base destination (encodeWord (offset + n) ++ base destination)⟩) + (2 * n + 5) where + steps := 2 * n + 5 + evals_in_steps := registerEmitTrace source destination scratch sourceDestination sourceScratch + destinationScratch offset firstLabel secondLabel emitLabel exit program atFirst atSecond + atEmit base n sourceWord scratchEmpty ambient register + steps_le_m := Nat.le_refl _ + +def program (source destination scratch : K) (offset : Nat) (exit : Option (Fin 3)) : + Fin 3 → TM2.Stmt (Alphabet (K := K)) (Fin 3) (σ × Option Bool) := + fun label => if label = 0 then + Reduction.MachineTransfer.loopAt source scratch id false 0 (some 1) + else if label = 1 then + MachineCopy.forkLoop scratch source destination false 1 (some 2) + else emitStatement destination offset exit + +def programInTime (source destination scratch : K) + (sourceDestination : source ≠ destination) (sourceScratch : source ≠ scratch) + (destinationScratch : destination ≠ scratch) (offset : Nat) (exit : Option (Fin 3)) + (base : K → List Bool) (n : Nat) (sourceWord : base source = encodeWord n) + (scratchEmpty : base scratch = []) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step (program source destination scratch offset exit)) + ⟨some 0, (ambient, register), base⟩ + (some ⟨exit, (ambient, none), + Function.update base destination (encodeWord (offset + n) ++ base destination)⟩) + (2 * n + 5) := + registerEmitInTime source destination scratch sourceDestination sourceScratch + destinationScratch offset 0 1 2 exit (program source destination scratch offset exit) + (by simp [program]) (by simp [program]) (by simp [program]) + base n sourceWord scratchEmpty ambient register + +def machine (offset : Nat) : FinTM2 where + K := Fin 3 + k₀ := 0 + k₁ := 1 + Γ _ := Bool + Λ := Fin 3 + main := 0 + σ := Unit × Option Bool + initialState := ((), none) + m := program 0 1 2 offset none + +def machineInTime (offset : Nat) (base : Fin 3 → List Bool) (n : Nat) + (sourceWord : base 0 = encodeWord n) (scratchEmpty : base 2 = []) + (register : Option Bool) : + StateTransition.EvalsToInTime (machine offset).step + ⟨some (0 : Fin 3), ((), register), base⟩ + (some ⟨none, ((), none), + Function.update base (1 : Fin 3) (encodeWord (offset + n) ++ base 1)⟩) + (2 * n + 5) := + programInTime (0 : Fin 3) 1 2 (by decide) (by decide) (by decide) + offset none base n sourceWord scratchEmpty () register + +omit [DecidableEq K] in +theorem emitStatement_pushes (destination : K) (offset : Nat) (exit : Option Λ) : + Runtime.statementPushBound (emitStatement (σ := σ) destination offset exit) = offset := by + cases exit <;> simp [emitStatement, statementPushBound_pushWord, finish, + Runtime.statementPushBound] + +omit [DecidableEq K] in +theorem program_pushes_le (source destination scratch : K) (offset : Nat) + (exit : Option (Fin 3)) (label : Fin 3) : + Runtime.statementPushBound + (program (σ := σ) source destination scratch offset exit label) ≤ max 2 offset := by + unfold program + split + · simp [Reduction.MachineTransfer.loopAt, Reduction.MachineTransfer.exitAt, + Runtime.statementPushBound] + · split + · simp [MachineCopy.forkLoop, Reduction.MachineTransfer.exitAt, + Runtime.statementPushBound] + · simpa only [emitStatement_pushes] using (Nat.le_max_right 2 offset) + +theorem machine_pushes_le (offset : Nat) : + Runtime.programPushBound (machine offset) ≤ max 2 offset := by + have h : ∀ labels : List (Fin 3), + Runtime.maxLabelPushes (machine offset).m labels ≤ max 2 offset := by + intro labels + change Runtime.maxLabelPushes (program (σ := Unit) (0 : Fin 3) 1 2 offset none) + labels ≤ max 2 offset + induction labels with + | nil => exact Nat.zero_le _ + | cons label labels ih => + exact max_le (program_pushes_le (σ := Unit) (0 : Fin 3) 1 2 offset none label) ih + exact h _ + +end MinUncutGames.Foundations.Complexity.MachineRegisterEmit + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineRegularLift.lean b/lean/OAI/Computability/MinUncut/Machines/MachineRegularLift.lean new file mode 100644 index 0000000000000000000000000000000000000000..c4e276760f5d42cea007d7b59423e4d591b2e782 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineRegularLift.lean @@ -0,0 +1,1130 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.PoweringMachineRow +import OAI.Computability.MinUncut.Machines.MachineCloudPrefix + +namespace OAI + +section +namespace MinUncutGames.Foundations.Complexity.MachineRegularTable + +open Turing MachineComposition + +namespace Lift + +open MachineCloudPadding + +variable {K K' Λ Λ' σ τ υ : Type} + +def statement (tape : K → K') (labels : Λ → Λ') (exit : Option Λ') + (registers : (σ × τ) ≃ υ) (q : TM2.Stmt (fun _ : K => Bool) Λ σ) : + TM2.Stmt (fun _ : K' => Bool) Λ' υ := + MachineStateEquiv.statement registers + (MachineStateFrame.frameStatement (Placement.statement tape labels exit q)) + +def configuration (view : K' → Option K) (labels : Λ → Λ') (exit : Option Λ') + (registers : (σ × τ) ≃ υ) (ambient : τ) (extra : K' → List Bool) + (c : TM2.Cfg (fun _ : K => Bool) Λ σ) : TM2.Cfg (fun _ : K' => Bool) Λ' υ := + ⟨Placement.label labels exit c.l, registers (c.var, ambient), + Placement.tapes view c.stk extra⟩ + +variable [DecidableEq K] [DecidableEq K'] + +theorem stepAux (tape : K → K') (view : K' → Option K) + (left : ∀ k, view (tape k) = some k) + (right : ∀ j k, view j = some k → tape k = j) + (labels : Λ → Λ') (exit : Option Λ') (registers : (σ × τ) ≃ υ) + (ambient : τ) (extra : K' → List Bool) + (q : TM2.Stmt (fun _ : K => Bool) Λ σ) (state : σ) (source : K → List Bool) : + TM2.stepAux (statement tape labels exit registers q) (registers (state, ambient)) + (Placement.tapes view source extra) = + configuration view labels exit registers ambient extra (TM2.stepAux q state source) := by + rw [statement, MachineStateEquiv.stepAux_transport, MachineStateFrame.frame_stepAux, + Placement.stepAux_simulation tape view left right] + rfl + +theorem step (tape : K → K') (view : K' → Option K) + (left : ∀ k, view (tape k) = some k) + (right : ∀ j k, view j = some k → tape k = j) + (labels : Λ → Λ') (exit : Option Λ') (registers : (σ × τ) ≃ υ) + (ambient : τ) (extra : K' → List Bool) + (source : Λ → TM2.Stmt (fun _ : K => Bool) Λ σ) + (target : Λ' → TM2.Stmt (fun _ : K' => Bool) Λ' υ) + (code : ∀ l, target (labels l) = statement tape labels exit registers (source l)) + (a b : TM2.Cfg (fun _ : K => Bool) Λ σ) (h : TM2.step source a = some b) : + TM2.step target (configuration view labels exit registers ambient extra a) = + some (configuration view labels exit registers ambient extra b) := by + cases a with + | mk label state sourceTapes => + cases label with + | none => simp [TM2.step] at h + | some label => + have hb : TM2.stepAux (source label) state sourceTapes = b := Option.some.inj h + rw [← hb] + change some (TM2.stepAux (target (labels label)) (registers (state, ambient)) + (Placement.tapes view sourceTapes extra)) = _ + rw [code, stepAux tape view left right] + +theorem trace (tape : K → K') (view : K' → Option K) + (left : ∀ k, view (tape k) = some k) + (right : ∀ j k, view j = some k → tape k = j) + (labels : Λ → Λ') (exit : Option Λ') (registers : (σ × τ) ≃ υ) + (ambient : τ) (extra : K' → List Bool) + (source : Λ → TM2.Stmt (fun _ : K => Bool) Λ σ) + (target : Λ' → TM2.Stmt (fun _ : K' => Bool) Λ' υ) + (code : ∀ l, target (labels l) = statement tape labels exit registers (source l)) + (steps : Nat) (a b : TM2.Cfg (fun _ : K => Bool) Λ σ) + (run : (advance (TM2.step source))^[steps] (some a) = some b) : + (advance (TM2.step target))^[steps] + (some (configuration view labels exit registers ambient extra a)) = + some (configuration view labels exit registers ambient extra b) := + liftSuccessfulTrace _ _ _ + (step tape view left right labels exit registers ambient extra source target code) steps a b run + +end Lift + +end MinUncutGames.Foundations.Complexity.MachineRegularTable + +end +section +namespace MinUncutGames.Foundations.Complexity.MachineCloudRank + +open Turing MachineComposition MachineCloudCount + +variable {σ : Type} + +@[simp] theorem update_memory_spare (a b c d e f x : List Bool) : + Function.update (memory a b c d e f) .spare x = memory a b c d e x := by + funext k + cases k <;> rfl + +inductive RankLabel + | queryFirst | querySecond | querySkip | tableFirst | tableSecond + | headerFirst | headerSecond | row | field | restore | done + | skip (i : Fin 4097) + deriving DecidableEq, Fintype + +def rankSkip (i : Nat) : RankLabel := + if h : i < 4097 then .skip ⟨i, h⟩ else .row + +def rankProgram : RankLabel → TM2.Stmt Alphabet RankLabel (State σ) + | .queryFirst => Reduction.MachineTransfer.loopAt + .target .scratch id false .queryFirst (some .querySecond) + | .querySecond => MachineCopy.forkLoop + .scratch .target .spare false .querySecond (some .querySkip) + | .querySkip => MachineLookup.discard .spare .querySkip .tableFirst + | .tableFirst => Reduction.MachineTransfer.loopAt + .original .scratch id false .tableFirst (some .tableSecond) + | .tableSecond => MachineCopy.forkLoop + .scratch .original .work false .tableSecond (some .headerFirst) + | .headerFirst => MachineLookup.discard .work .headerFirst .headerSecond + | .headerSecond => MachineLookup.discard .work .headerSecond .row + | .row => MachineUnaryCounter.guard .spare .field .done + | .field => fieldLoop .field .restore + | .restore => Reduction.MachineTransfer.loopAt + .scratch .target id false .restore (some (rankSkip 0)) + | .skip i => MachineLookup.discard .work (.skip i) (rankSkip (i.val + 1)) + | .done => .halt + +theorem rankProgram_skip {i : Nat} (hi : i < 4097) : + rankProgram (σ := σ) (rankSkip i) = + MachineLookup.discard .work (rankSkip i) (rankSkip (i + 1)) := by + simp only [rankSkip, dite_eq_left hi, rankProgram] + +theorem rowGuard_succ (original work target scratch count fuelSuffix : List Bool) + (k : Nat) (ambient : σ) (flag : Bool) (register : Option Bool) : + TM2.step (rankProgram (σ := σ)) + ⟨some .row, ((ambient, flag), register), + memory original work target scratch count (encodeWord (k + 1) ++ fuelSuffix)⟩ = + some ⟨some .field, ((ambient, flag), none), + memory original work target scratch count (encodeWord k ++ fuelSuffix)⟩ := by + change some (TM2.stepAux (rankProgram .row) _ _) = _ + simp [rankProgram, MachineUnaryCounter.guard, TM2.stepAux, encodeWord, + List.replicate_succ] + +theorem rowGuard_zero (original work target scratch count fuelSuffix : List Bool) + (ambient : σ) (flag : Bool) (register : Option Bool) : + TM2.step (rankProgram (σ := σ)) + ⟨some .row, ((ambient, flag), register), + memory original work target scratch count (encodeWord 0 ++ fuelSuffix)⟩ = + some ⟨some .done, ((ambient, flag), none), + memory original work target scratch count (encodeWord 0 ++ fuelSuffix)⟩ := rfl + +theorem zeroRowsTrace (original work target scratch count fuelSuffix : List Bool) + (ambient : σ) (flag : Bool) (register : Option Bool) : + (advance (TM2.step (rankProgram (σ := σ))))^[2] + (some ⟨some .row, ((ambient, flag), register), + memory original work target scratch count (encodeWord 0 ++ fuelSuffix)⟩) = + some ⟨none, ((ambient, flag), none), + memory original work target scratch count (encodeWord 0 ++ fuelSuffix)⟩ := by + rw [Function.iterate_succ_apply] + change advance (TM2.step (rankProgram (σ := σ))) + (TM2.step rankProgram ⟨some .row, ((ambient, flag), register), + memory original work target scratch count (encodeWord 0 ++ fuelSuffix)⟩) = _ + rw [rowGuard_zero] + rfl + +theorem rankRowTrace (r : Row) (hwidth : r.2.length = 4097) (v k : Nat) + (original suffix targetSuffix fuelSuffix count : List Bool) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step (rankProgram (σ := σ))))^[rowTime v r] + (some ⟨some .row, ((ambient, false), register), + memory original (encodeWords (rowWords r) ++ suffix) (encodeWord v ++ targetSuffix) + [] count (encodeWord (k + 1) ++ fuelSuffix)⟩) = + some ⟨some .row, ((ambient, false), none), + memory original suffix (encodeWord v ++ targetSuffix) [] + (List.replicate (if r.1 = v then 1 else 0) true ++ count) + (encodeWord k ++ fuelSuffix)⟩ := by + have hfield := preservingFieldTrace RankLabel.field RankLabel.restore (rankSkip 0) + rankProgram rfl rfl original (encodeWords r.2 ++ suffix) targetSuffix count + (encodeWord k ++ fuelSuffix) r.1 v ambient none + have hskip := discardFieldsTrace rankSkip (rankProgram (σ := σ)) r.2 0 + (by intro i hi; simpa only [Nat.zero_add] using rankProgram_skip (hwidth ▸ hi)) + original suffix (encodeWord v ++ targetSuffix) [] + (List.replicate (if r.1 = v then 1 else 0) true ++ count) + (encodeWord k ++ fuelSuffix) ambient false none + have hnonempty : r.2 ≠ [] := by intro h; simp [h] at hwidth + simp only [Nat.zero_add, hwidth, rankSkip, lt_self_iff_false, ↓reduceDIte, + hnonempty, ite_false] at hskip + have htime : rowTime v r = (encodeWords r.2).length + (r.1 + min r.1 v + 2) + 1 := by + simp only [rowTime, rowWords, encodeWords, List.length_append, encodeWord_length] + omega + rw [htime, Function.iterate_succ_apply] + change (advance (TM2.step (rankProgram (σ := σ))))^[ + (encodeWords r.2).length + (r.1 + min r.1 v + 2)] + (TM2.step rankProgram ⟨some .row, ((ambient, false), register), + memory original (encodeWords (rowWords r) ++ suffix) (encodeWord v ++ targetSuffix) + [] count (encodeWord (k + 1) ++ fuelSuffix)⟩) = _ + rw [rowGuard_succ, Function.iterate_add_apply] + simp only [rowWords, encodeWords, List.append_assoc] + rw [hfield] + exact hskip + +def prefixTime (v : Nat) : List Row → Nat + | [] => 2 + | r :: rs => prefixTime v rs + rowTime v r + +theorem prefixTrace (rs : List Row) (hwidth : ∀ r ∈ rs, r.2.length = 4097) (v : Nat) + (original suffix targetSuffix fuelSuffix count : List Bool) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step (rankProgram (σ := σ))))^[prefixTime v rs] + (some ⟨some .row, ((ambient, false), register), + memory original (encodeWords (rs.flatMap rowWords) ++ suffix) + (encodeWord v ++ targetSuffix) [] count (encodeWord rs.length ++ fuelSuffix)⟩) = + some ⟨none, ((ambient, false), none), + memory original suffix (encodeWord v ++ targetSuffix) [] + (List.replicate (rowsHits v rs) true ++ count) (encodeWord 0 ++ fuelSuffix)⟩ := by + induction rs generalizing count register with + | nil => + simpa only [prefixTime, List.flatMap_nil, encodeWords, List.nil_append, + List.length_nil, rowsHits, List.replicate_zero] using + zeroRowsTrace original suffix (encodeWord v ++ targetSuffix) [] count fuelSuffix + ambient false register + | cons r rs ih => + have hrow := rankRowTrace r (hwidth r (by simp)) v rs.length original + (encodeWords (rs.flatMap rowWords) ++ suffix) targetSuffix fuelSuffix count ambient register + have hrest := ih (by intro x hx; exact hwidth x (by simp [hx])) + (List.replicate (if r.1 = v then 1 else 0) true ++ count) none + simp only [prefixTime, List.flatMap_cons, encodeWords_append, List.append_assoc, + List.length_cons] + rw [Function.iterate_add_apply, hrow] + simpa only [rowsHits, ← List.append_assoc, List.replicate_append_replicate, + Nat.add_comm] using hrest + +theorem prefixTime_le (v : Nat) (rs : List Row) : + prefixTime v rs ≤ 3 * (encodeWords (rs.flatMap rowWords)).length + 2 := by + induction rs with + | nil => simp only [prefixTime, List.flatMap_nil, encodeWords, List.length_nil, + Nat.mul_zero, Nat.zero_add, le_refl] + | cons r rs ih => + have hr := rowTime_le v r + simp only [prefixTime, List.flatMap_cons, encodeWords_append, List.length_append] + omega + +def queryWord (v k : Nat) (suffix : List Bool) : List Bool := + encodeWord v ++ (encodeWord k ++ suffix) + +theorem encoded_rows_split (rs : List Row) (k : Nat) : + encodeWords (rs.flatMap rowWords) = + encodeWords ((rs.take k).flatMap rowWords) ++ + encodeWords ((rs.drop k).flatMap rowWords) := by + have h := congrArg (fun xs : List Row => encodeWords (xs.flatMap rowWords)) + (List.take_append_drop k rs) + simpa only [List.flatMap_append, encodeWords_append] using h.symm + +def rankSteps (n m v k : Nat) (rs : List Row) (querySuffix : List Bool) : Nat := + 2 * ((queryWord v k querySuffix).length + 1) + (v + 1) + + 2 * ((inputWord n m rs).length + 1) + (n + 1) + (m + 1) + + prefixTime v (rs.take k) + +theorem rankTrace (n m v k : Nat) (rs : List Row) (hk : k ≤ rs.length) + (hwidth : ∀ r ∈ rs, r.2.length = 4097) (querySuffix count : List Bool) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step (rankProgram (σ := σ))))^[rankSteps n m v k rs querySuffix] + (some ⟨some .queryFirst, ((ambient, false), register), + memory (inputWord n m rs) [] (queryWord v k querySuffix) [] count []⟩) = + some ⟨none, ((ambient, false), none), + memory (inputWord n m rs) (encodeWords ((rs.drop k).flatMap rowWords)) + (queryWord v k querySuffix) [] + (List.replicate (rowsHits v (rs.take k)) true ++ count) + (encodeWord 0 ++ querySuffix)⟩ := by + have hquery := MachineCopy.copyTrace Tape.target Tape.spare Tape.scratch + (by decide) (by decide) (by decide) false RankLabel.queryFirst RankLabel.querySecond + (some RankLabel.querySkip) rankProgram rfl rfl + (memory (inputWord n m rs) [] (queryWord v k querySuffix) [] count []) + rfl (ambient, false) register + simp only [memory_target, memory_spare, List.append_nil, update_memory_spare] at hquery + have hquerySkip := MachineLookup.discardTrace Tape.spare RankLabel.querySkip RankLabel.tableFirst + rankProgram rfl + (memory (inputWord n m rs) [] (queryWord v k querySuffix) [] count (queryWord v k querySuffix)) + v (encodeWord k ++ querySuffix) rfl (ambient, false) none + simp only [update_memory_spare] at hquerySkip + have hcopy := MachineCopy.copyTrace Tape.original Tape.work Tape.scratch + (by decide) (by decide) (by decide) false RankLabel.tableFirst RankLabel.tableSecond + (some RankLabel.headerFirst) rankProgram rfl rfl + (memory (inputWord n m rs) [] (queryWord v k querySuffix) [] count + (encodeWord k ++ querySuffix)) rfl (ambient, false) none + simp only [memory_original, memory_work, List.append_nil, update_memory_work] at hcopy + have hfirst := MachineLookup.discardTrace Tape.work RankLabel.headerFirst RankLabel.headerSecond + rankProgram rfl + (memory (inputWord n m rs) (inputWord n m rs) (queryWord v k querySuffix) [] count + (encodeWord k ++ querySuffix)) + n (encodeWord m ++ encodeWords (rs.flatMap rowWords)) + (inputWord_eq n m rs) (ambient, false) none + simp only [update_memory_work] at hfirst + have hsecond := MachineLookup.discardTrace Tape.work RankLabel.headerSecond RankLabel.row + rankProgram rfl + (memory (inputWord n m rs) (encodeWord m ++ encodeWords (rs.flatMap rowWords)) + (queryWord v k querySuffix) [] count (encodeWord k ++ querySuffix)) + m (encodeWords (rs.flatMap rowWords)) rfl (ambient, false) none + simp only [update_memory_work] at hsecond + have hprefix := prefixTrace (rs.take k) + (by intro r hr; exact hwidth r (List.mem_of_mem_take hr)) v + (inputWord n m rs) (encodeWords ((rs.drop k).flatMap rowWords)) + (encodeWord k ++ querySuffix) querySuffix count ambient none + have htake : (rs.take k).length = k := by + simp only [List.length_take, Nat.min_eq_left hk] + rw [htake, ← encoded_rows_split rs k] at hprefix + rw [show rankSteps n m v k rs querySuffix = prefixTime v (rs.take k) + + ((m + 1) + ((n + 1) + (2 * ((inputWord n m rs).length + 1) + + ((v + 1) + 2 * ((queryWord v k querySuffix).length + 1))))) by + unfold rankSteps; omega, + Function.iterate_add_apply _ (prefixTime v (rs.take k)), + Function.iterate_add_apply _ (m + 1), Function.iterate_add_apply _ (n + 1), + Function.iterate_add_apply _ (2 * ((inputWord n m rs).length + 1)), + Function.iterate_add_apply _ (v + 1), hquery, hquerySkip, hcopy, hfirst, hsecond] + exact hprefix + +theorem rankSteps_le (n m v k : Nat) (rs : List Row) (querySuffix : List Bool) : + rankSteps n m v k rs querySuffix ≤ + 5 * (inputWord n m rs).length + 3 * (queryWord v k querySuffix).length + 6 := by + have hprefix := prefixTime_le v (rs.take k) + have hsplit := congrArg List.length (encoded_rows_split rs k) + simp only [List.length_append] at hsplit + have hinput := inputWord_length n m rs + have hquery : v + 1 ≤ (queryWord v k querySuffix).length := by + simp only [queryWord, List.length_append, encodeWord_length] + omega + unfold rankSteps + omega + +theorem idxOf_filter_prefix {α : Type*} [BEq α] [LawfulBEq α] + (p : α → Bool) (a : α) (hp : p a = true) : + ∀ xs : List α, a ∈ xs → + (xs.filter p).idxOf a = ((xs.take (xs.idxOf a)).filter p).length := by + classical + intro xs + induction xs with + | nil => intro ha; simp at ha + | cons b xs ih => + intro ha + by_cases hba : b = a + · subst b + simp [hp] + · have ha' : a ∈ xs := by simpa [hba, Ne.symm hba] using ha + cases hb : p b <;> + simp [hba, hb, ih ha'] + +open MinUncutGames.Foundations.PCP + +theorem tableRows_length (t : GraphTables.Table) : (tableRows t).length = t.darts := by + simp only [tableRows, List.length_map, GraphTables.rowList_length] + +theorem cloudRank_eq_prefix_count (t : GraphTables.Table) (v : Fin t.vertices) + (e : DegreeReplacement.Cloud (GraphTables.semantics t) v) : + (PreprocessingCloudIndex.cloudRank t v e).val = + rowsHits v.val ((tableRows t).take e.val.val) := by + have hindex := idxOf_filter_prefix (fun x : Fin t.darts => decide (t.rows[x].tail = v)) + e.val (by simpa using e.property) (List.finRange t.darts) (List.mem_finRange e.val) + simp only [List.idxOf_finRange] at hindex + change (PreprocessingCloudIndex.cloudDarts t v).idxOf e.val = _ + unfold PreprocessingCloudIndex.cloudDarts + rw [hindex, rowsHits_eq_filter] + simp only [tableRows, rowList_eq_finRange_map, ← List.map_take, List.filter_map, + List.length_map, Function.comp_def, Fin.val_inj] + +theorem cloudRankTrace (t : GraphTables.Table) (v : Fin t.vertices) + (e : DegreeReplacement.Cloud (GraphTables.semantics t) v) + (querySuffix countSuffix : List Bool) (ambient : σ) (register : Option Bool) : + (advance (TM2.step (rankProgram (σ := σ))))^[ + rankSteps t.vertices t.darts v.val e.val.val (tableRows t) querySuffix] + (some ⟨some .queryFirst, ((ambient, false), register), + memory (GraphTables.tableBits t) [] (queryWord v.val e.val.val querySuffix) [] + (encodeWord 0 ++ countSuffix) []⟩) = + some ⟨none, ((ambient, false), none), + memory (GraphTables.tableBits t) + (encodeWords (((tableRows t).drop e.val.val).flatMap rowWords)) + (queryWord v.val e.val.val querySuffix) [] + (encodeWord (PreprocessingCloudIndex.cloudRank t v e).val ++ countSuffix) + (encodeWord 0 ++ querySuffix)⟩ := by + have hk : e.val.val ≤ (tableRows t).length := by + rw [tableRows_length] + exact e.val.isLt.le + have h := rankTrace t.vertices t.darts v.val e.val.val (tableRows t) hk + (tableRows_width t) querySuffix (encodeWord 0 ++ countSuffix) ambient register + rw [tableRows_input, ← cloudRank_eq_prefix_count t v e, ← List.append_assoc, + replicate_encodeWord, Nat.add_zero] at h + exact h + +def cloudRankInTime (t : GraphTables.Table) (v : Fin t.vertices) + (e : DegreeReplacement.Cloud (GraphTables.semantics t) v) + (querySuffix countSuffix : List Bool) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step (rankProgram (σ := σ))) + ⟨some .queryFirst, ((ambient, false), register), + memory (GraphTables.tableBits t) [] (queryWord v.val e.val.val querySuffix) [] + (encodeWord 0 ++ countSuffix) []⟩ + (some ⟨none, ((ambient, false), none), + memory (GraphTables.tableBits t) + (encodeWords (((tableRows t).drop e.val.val).flatMap rowWords)) + (queryWord v.val e.val.val querySuffix) [] + (encodeWord (PreprocessingCloudIndex.cloudRank t v e).val ++ countSuffix) + (encodeWord 0 ++ querySuffix)⟩) + (5 * (GraphTables.tableBits t).length + + 3 * (queryWord v.val e.val.val querySuffix).length + 6) where + steps := rankSteps t.vertices t.darts v.val e.val.val (tableRows t) querySuffix + evals_in_steps := cloudRankTrace t v e querySuffix countSuffix ambient register + steps_le_m := by + simpa only [tableRows_input] using + rankSteps_le t.vertices t.darts v.val e.val.val (tableRows t) querySuffix + +end MinUncutGames.Foundations.Complexity.MachineCloudRank + +end +section +namespace MinUncutGames.Foundations.Complexity.MachineTableRows + +open Turing +open PCP.GraphTables + +inductive Label + | relationRead | relationRestore | reverseRead | reverseRestore + | tailRead | tailRestore | appendOld | appendRow | appendBack + deriving DecidableEq + +protected abbrev Label.enumList : List Label := [.relationRead, .relationRestore, .reverseRead, + .reverseRestore, .tailRead, .tailRestore, .appendOld, .appendRow, .appendBack] + +protected theorem Label.enumList_getElem?_ctorIdx_eq (x : Label) : + Label.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem Label.enumList_nodup : Label.enumList.Nodup := by decide + +instance : Fintype Label where + elems := ⟨Label.enumList, Label.enumList_nodup⟩ + complete x := by cases x <;> decide + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool + +def routine (fields : Fin 3 → K) (row output scratch : K) + (labels : Label → Λ) (exit : Option Λ) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) + | .relationRead => Reduction.MachineTransfer.loopAt (fields 2) scratch id false + (labels .relationRead) (some (labels .relationRestore)) + | .relationRestore => MachineCopy.forkLoop scratch (fields 2) row false + (labels .relationRestore) (some (labels .reverseRead)) + | .reverseRead => Reduction.MachineTransfer.loopAt (fields 1) scratch id false + (labels .reverseRead) (some (labels .reverseRestore)) + | .reverseRestore => MachineCopy.forkLoop scratch (fields 1) row false + (labels .reverseRestore) (some (labels .tailRead)) + | .tailRead => Reduction.MachineTransfer.loopAt (fields 0) scratch id false + (labels .tailRead) (some (labels .tailRestore)) + | .tailRestore => MachineCopy.forkLoop scratch (fields 0) row false + (labels .tailRestore) (some (labels .appendOld)) + | .appendOld => Reduction.MachineTransfer.loopAt output scratch id false + (labels .appendOld) (some (labels .appendRow)) + | .appendRow => Reduction.MachineTransfer.loopAt row scratch id false + (labels .appendRow) (some (labels .appendBack)) + | .appendBack => Reduction.MachineTransfer.loopAt scratch output id false + (labels .appendBack) exit + +def fieldBits (fields : Fin 3 → K) (base : K → List Bool) : List Bool := + base (fields 0) ++ base (fields 1) ++ base (fields 2) + +def fieldSize (fields : Fin 3 → K) (base : K → List Bool) : Nat := + (base (fields 0)).length + (base (fields 1)).length + (base (fields 2)).length + +omit [DecidableEq K] in +@[simp] theorem fieldBits_length (fields : Fin 3 → K) (base : K → List Bool) : + (fieldBits fields base).length = fieldSize fields base := by + simp [fieldBits, fieldSize, Nat.add_assoc] + +def prefixTapes (fields : Fin 3 → K) (row : K) (base : K → List Bool) : K → List Bool := + Function.update base row (fieldBits fields base ++ base row) + +theorem prefixTrace (fields : Fin 3 → K) (row output scratch : K) + (hfields : ∀ i, fields i ≠ row ∧ fields i ≠ scratch) + (hrowScratch : row ≠ scratch) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (hprogram : ∀ label, program (labels label) = routine fields row output scratch labels exit label) + (base : K → List Bool) (hscratch : base scratch = []) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[2 * (fieldSize fields base + 3)] + (some ⟨some (labels .relationRead), (ambient, register), base⟩) = + some ⟨some (labels .appendOld), (ambient, none), prefixTapes fields row base⟩ := by + let afterRelation := Function.update base row (base (fields 2) ++ base row) + let afterReverse := Function.update afterRelation row + (base (fields 1) ++ afterRelation row) + have hfirst := MachineCopy.copyTrace (fields 2) row scratch + (hfields 2).1 (hfields 2).2 hrowScratch false + (labels .relationRead) (labels .relationRestore) (some (labels .reverseRead)) + program (hprogram .relationRead) (hprogram .relationRestore) base hscratch ambient register + change (MachineComposition.advance (TM2.step program))^[2 * ((base (fields 2)).length + 1)] + (some ⟨some (labels .relationRead), (ambient, register), base⟩) = + some ⟨some (labels .reverseRead), (ambient, none), afterRelation⟩ at hfirst + have hsecond := MachineCopy.copyTrace (fields 1) row scratch + (hfields 1).1 (hfields 1).2 hrowScratch false + (labels .reverseRead) (labels .reverseRestore) (some (labels .tailRead)) + program (hprogram .reverseRead) (hprogram .reverseRestore) afterRelation + (by simp [afterRelation, Ne.symm hrowScratch, hscratch]) ambient none + have hrev : afterRelation (fields 1) = base (fields 1) := by + simp [afterRelation, (hfields 1).1] + rw [hrev] at hsecond + change (MachineComposition.advance (TM2.step program))^[2 * ((base (fields 1)).length + 1)] + (some ⟨some (labels .reverseRead), (ambient, none), afterRelation⟩) = + some ⟨some (labels .tailRead), (ambient, none), afterReverse⟩ at hsecond + have hthird := MachineCopy.copyTrace (fields 0) row scratch + (hfields 0).1 (hfields 0).2 hrowScratch false + (labels .tailRead) (labels .tailRestore) (some (labels .appendOld)) + program (hprogram .tailRead) (hprogram .tailRestore) afterReverse + (by simp [afterReverse, afterRelation, Ne.symm hrowScratch, hscratch]) ambient none + have htail : afterReverse (fields 0) = base (fields 0) := by + simp [afterReverse, afterRelation, (hfields 0).1] + rw [htail] at hthird + have hfinal : Function.update afterReverse row + (base (fields 0) ++ afterReverse row) = prefixTapes fields row base := by + simp [afterReverse, afterRelation, prefixTapes, fieldBits, List.append_assoc] + rw [hfinal] at hthird + rw [show 2 * (fieldSize fields base + 3) = + 2 * ((base (fields 0)).length + 1) + + (2 * ((base (fields 1)).length + 1) + 2 * ((base (fields 2)).length + 1)) by + simp only [fieldSize]; omega, + Function.iterate_add_apply, + Function.iterate_add_apply (m := 2 * ((base (fields 1)).length + 1)) + (n := 2 * ((base (fields 2)).length + 1)), hfirst, hsecond] + exact hthird + +theorem appendTrace (fields : Fin 3 → K) (row output scratch : K) + (hfields : ∀ i, fields i ≠ row ∧ fields i ≠ scratch) + (hrowOutput : row ≠ output) (hrowScratch : row ≠ scratch) + (houtputScratch : output ≠ scratch) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (hprogram : ∀ label, program (labels label) = routine fields row output scratch labels exit label) + (base : K → List Bool) (hrow : base row = []) (hscratch : base scratch = []) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[ + 4 * fieldSize fields base + 2 * (base output).length + 9] + (some ⟨some (labels .relationRead), (ambient, register), base⟩) = + some ⟨exit, (ambient, none), + Function.update base output (base output ++ fieldBits fields base)⟩ := by + have hprefix := prefixTrace fields row output scratch hfields hrowScratch + labels exit program hprogram base hscratch ambient register + have happend := MachineAppendAt.appendTrace row output scratch hrowOutput hrowScratch + houtputScratch false (labels .appendOld) (labels .appendRow) (labels .appendBack) + exit program (hprogram .appendOld) (hprogram .appendRow) (hprogram .appendBack) + (prefixTapes fields row base) + (by simp [prefixTapes, Ne.symm hrowScratch, hscratch]) ambient none + have hrowbits : prefixTapes fields row base row = fieldBits fields base := by + simp [prefixTapes, hrow] + have hout : prefixTapes fields row base output = base output := by + simp [prefixTapes, Ne.symm hrowOutput] + rw [hrowbits, hout, fieldBits_length] at happend + have hfinal : MachineAppendAt.appendTapes row output (prefixTapes fields row base) = + Function.update base output (base output ++ fieldBits fields base) := by + funext k + by_cases ho : k = output + · subst k + simp [MachineAppendAt.appendTapes, hrowbits, hout] + · by_cases hr : k = row + · subst k + simp [MachineAppendAt.appendTapes, Reduction.MachineTransfer.tapesAt, + prefixTapes, hrowOutput, hrow] + · simp [MachineAppendAt.appendTapes, Reduction.MachineTransfer.tapesAt, + prefixTapes, ho, hr] + rw [hfinal] at happend + rw [show 4 * fieldSize fields base + 2 * (base output).length + 9 = + (2 * (fieldSize fields base + (base output).length) + 3) + + 2 * (fieldSize fields base + 3) by omega, + Function.iterate_add_apply, hprefix] + exact happend + +theorem rowBits_eq {n m : Nat} (r : DartRow n m) : + encodeWords (rowWords r) = encodeWord r.tail.val ++ + encodeWord r.reverseIndex.val ++ encodeWords (relationWords r.relation) := by + simp [rowWords, encodeWords] + +omit [DecidableEq K] in +theorem fieldBits_eq_rowBits {n m : Nat} (r : DartRow n m) + (fields : Fin 3 → K) (base : K → List Bool) + (htail : base (fields 0) = encodeWord r.tail.val) + (hreverse : base (fields 1) = encodeWord r.reverseIndex.val) + (hrelation : base (fields 2) = encodeWords (relationWords r.relation)) : + fieldBits fields base = encodeWords (rowWords r) := by + rw [fieldBits, htail, hreverse, hrelation, rowBits_eq] + +noncomputable def timePolynomial : Polynomial Nat := Polynomial.C 4 * Polynomial.X + Polynomial.C 9 + +omit [DecidableEq K] in +theorem timePolynomial_bounds (fields : Fin 3 → K) (base : K → List Bool) (output : K) : + 4 * fieldSize fields base + 2 * (base output).length + 9 ≤ + timePolynomial.eval (fieldSize fields base + (base output).length) := by + simp only [timePolynomial, Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_C, + Polynomial.eval_X] + omega + +def rowAppendInTime {n m : Nat} (r : DartRow n m) + (fields : Fin 3 → K) (row output scratch : K) + (hfields : ∀ i, fields i ≠ row ∧ fields i ≠ scratch) + (hrowOutput : row ≠ output) (hrowScratch : row ≠ scratch) + (houtputScratch : output ≠ scratch) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (hprogram : ∀ label, program (labels label) = routine fields row output scratch labels exit label) + (base : K → List Bool) (hrow : base row = []) (hscratch : base scratch = []) + (htail : base (fields 0) = encodeWord r.tail.val) + (hreverse : base (fields 1) = encodeWord r.reverseIndex.val) + (hrelation : base (fields 2) = encodeWords (relationWords r.relation)) + (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .relationRead), (ambient, register), base⟩ + (some ⟨exit, (ambient, none), + Function.update base output (base output ++ encodeWords (rowWords r))⟩) + (timePolynomial.eval (fieldSize fields base + (base output).length)) where + steps := 4 * fieldSize fields base + 2 * (base output).length + 9 + evals_in_steps := by + change (MachineComposition.advance (TM2.step program))^[_] _ = _ + rw [← fieldBits_eq_rowBits r fields base htail hreverse hrelation] + exact appendTrace fields row output scratch hfields hrowOutput hrowScratch + houtputScratch labels exit program hprogram base hrow hscratch ambient register + steps_le_m := timePolynomial_bounds fields base output + +def machine : FinTM2 where + K := Fin 6 + k₀ := 0 + k₁ := 4 + Γ _ := Bool + Λ := Label + main := .relationRead + σ := Unit × Option Bool + initialState := ((), none) + m := routine (fun i : Fin 3 => i.castLE (by decide)) 3 4 5 id none + +def machineRowInTime {n m : Nat} (r : DartRow n m) (base : Fin 6 → List Bool) + (hrow : base 3 = []) (hscratch : base 5 = []) + (htail : base 0 = encodeWord r.tail.val) + (hreverse : base 1 = encodeWord r.reverseIndex.val) + (hrelation : base 2 = encodeWords (relationWords r.relation)) (register : Option Bool) : + StateTransition.EvalsToInTime machine.step + ⟨some .relationRead, ((), register), base⟩ + (some ⟨none, ((), none), + Function.update base (4 : Fin 6) (base 4 ++ encodeWords (rowWords r))⟩) + (timePolynomial.eval ((encodeWords (rowWords r)).length + (base 4).length)) := by + let fields : Fin 3 → Fin 6 := fun i => i.castLE (by decide) + have hfields (i : Fin 3) : fields i ≠ 3 ∧ fields i ≠ 5 := by + constructor + · intro h + have he := congrArg Fin.val h + change i.val = 3 at he + omega + · intro h + have he := congrArg Fin.val h + change i.val = 5 at he + omega + have hsize : fieldSize fields base = (encodeWords (rowWords r)).length := by + rw [← fieldBits_length, fieldBits_eq_rowBits r fields base htail hreverse hrelation] + have run := rowAppendInTime r fields (3 : Fin 6) 4 5 hfields (by decide) (by decide) + (by decide) id none machine.m (fun _ => rfl) base hrow hscratch + htail hreverse hrelation () register + rw [hsize] at run + convert run using 1 + rfl + +theorem outputFrame (base : K → List Bool) (output k : K) (hk : k ≠ output) + (bits : List Bool) : + Function.update base output (base output ++ bits) k = base k := by + simp [hk] + +end MinUncutGames.Foundations.Complexity.MachineTableRows + +end +section +namespace MinUncutGames.Foundations.Complexity.MachineRegularOriginalRow + +open Turing MachineComposition +open PCP PCP.GraphTables PCP.PreprocessingRegularTables + +def inheritedIndex (_H : BaseTable) (t : Table) (e : Fin t.darts) : + Fin (vertexCount t (padding t) * (internalDegree + 1)) := + PortTables.rowIndex _ _ + (vertexOrder t (padding t) (.inl e), portOrder internalDegree (.inr ())) + +def inheritedRow (H : BaseTable) (t : Table) (e : Fin t.darts) : + DartRow (vertexCount t (padding t)) + (vertexCount t (padding t) * (internalDegree + 1)) := + (PortTables.flatRows (regularize H t))[inheritedIndex H t e] + +theorem inheritedRow_eq (H : BaseTable) (t : Table) (e : Fin t.darts) : + inheritedRow H t e = + ⟨((PortTables.rowIndex _ _).symm (inheritedIndex H t e)).1, + (regularize H t).reverseIndex[inheritedIndex H t e], + (regularize H t).relations[inheritedIndex H t e]⟩ := by + simp only [inheritedRow, PortTables.flatRows, Fin.getElem_fin, + Vector.getElem_ofFn, Fin.eta] + +@[simp] theorem inheritedRow_tail (H : BaseTable) (t : Table) (e : Fin t.darts) : + (inheritedRow H t e).tail.val = e.val := by + simp only [inheritedRow_eq, inheritedIndex, Equiv.symm_apply_apply, + vertexOrder_original] + +@[simp] theorem inheritedRow_reverse (H : BaseTable) (t : Table) (e : Fin t.darts) : + (inheritedRow H t e).reverseIndex.val = + (internalDegree + 1) * t.rows[e].reverseIndex.val + internalDegree := by + rw [inheritedRow_eq] + change ((regularize H t).reverseIndex[PortTables.rowIndex _ _ + (vertexOrder t (padding t) (.inl e), portOrder internalDegree (.inr ()))]).val = _ + rw [← PortTables.rowIndex_rotation, regularize, rotation_ofCloudTables] + change (PortTables.rowIndex _ _ + (vertexOrder t (padding t) (.inl (reverseAt t.rows e)), + portOrder internalDegree (.inr ()))).val = _ + rw [PortTables.rowIndex_val, vertexOrder_original, portOrder_inherited] + exact Nat.add_comm _ _ + +@[simp] theorem inheritedRow_relation (H : BaseTable) (t : Table) (e : Fin t.darts) : + (inheritedRow H t e).relation = t.rows[e].relation := by + rw [inheritedRow_eq] + apply Vector.ext + intro i hi + let j : Fin 4096 := ⟨i, hi⟩ + let ab := relationIndex.symm j + have h := accepts_original t (padding t) (familyCloudTable H t) e ab.1 ab.2 + change relationAt ((regularize H t).relations[inheritedIndex H t e]) ab.1 ab.2 = + relationAt t.rows[e].relation ab.1 ab.2 at h + have hj : relationIndex (ab.1, ab.2) = j := relationIndex.apply_symm_apply j + simpa only [relationAt, hj, Fin.getElem_fin, j] using h + +theorem inheritedRow_words (H : BaseTable) (t : Table) (e : Fin t.darts) : + rowWords (inheritedRow H t e) = e.val :: + ((internalDegree + 1) * t.rows[e].reverseIndex.val + internalDegree) :: + relationWords t.rows[e].relation := by + simp only [rowWords, inheritedRow_tail, inheritedRow_reverse, inheritedRow_relation, + List.cons_append, List.nil_append] + +def prefixWords (t : Table) (e : Fin t.darts) : List Nat := + [t.vertices, t.darts] ++ ((rowList t).take e.val).flatMap rowWords + +def suffixWords (t : Table) (e : Fin t.darts) : List Nat := + ((rowList t).drop (e.val + 1)).flatMap rowWords + +theorem prefixWords_length (t : Table) (e : Fin t.darts) : + (prefixWords t e).length = 2 + 4098 * e.val := by + simp only [prefixWords, List.length_append, List.length_cons, List.length_nil, + rowsWords_length, List.length_take, rowList_length, Nat.min_eq_left e.isLt.le] + +theorem tableWords_at_row (t : Table) (e : Fin t.darts) : + GraphTables.tableWords t = prefixWords t e ++ (rowWords t.rows[e] ++ suffixWords t e) := by + have he : e.val < (rowList t).length := by simpa only [rowList_length] using e.isLt + have hs : (rowList t).take e.val ++ (rowList t)[e.val] :: + (rowList t).drop (e.val + 1) = rowList t := by + rw [List.getElem_cons_drop he, List.take_append_drop] + have hw := congrArg (fun rs : List (DartRow t.vertices t.darts) => rs.flatMap rowWords) hs + simp only [List.flatMap_append, List.flatMap_cons, rowList, Vector.getElem_toList] at hw + unfold GraphTables.tableWords prefixWords suffixWords rowList + rw [← hw] + simp only [List.append_assoc, Fin.getElem_fin] + +theorem tableWords_drop_row (t : Table) (e : Fin t.darts) : + (GraphTables.tableWords t).drop (2 + 4098 * e.val) = rowWords t.rows[e] ++ suffixWords t e := by + rw [tableWords_at_row] + exact List.drop_left' (l₂ := rowWords t.rows[e] ++ suffixWords t e) + (prefixWords_length t e) + +theorem selected_reverse (t : Table) (e : Fin t.darts) : + (GraphTables.tableWords t)[4098 * e.val + 3]? = some t.rows[e].reverseIndex.val := by + have h := congrArg (fun words : List Nat => words[1]?) (tableWords_drop_row t e) + simp only [List.getElem?_drop] at h + rw [show 2 + 4098 * e.val + 1 = 4098 * e.val + 3 by omega] at h + simpa [rowWords] using h + +theorem remaining_relation (t : Table) (e : Fin t.darts) : + (GraphTables.tableWords t).drop (4098 * e.val + 3 + 1) = + relationWords t.rows[e].relation ++ suffixWords t e := by + rw [show 4098 * e.val + 3 + 1 = (2 + 4098 * e.val) + 2 by omega, + ← List.drop_drop, tableWords_drop_row] + simp only [rowWords, List.cons_append, List.drop_succ_cons, List.drop_zero, List.nil_append] + +abbrev Tape := Fin 10 +abbrev Buffer := MachineFixedBlockMap.Buffer 4096 +abbrev State (σ : Type) := (σ × Buffer) × Option Bool +abbrev Alphabet (_ : Tape) := Bool + +def zeroBuffer : Buffer := MachineFixedBlockMap.emptyBuffer 4096 + +def lookupTape (i : Fin 5) : Tape := ⟨i.val + 1, by omega⟩ + +theorem lookupTape_injective : Function.Injective lookupTape := by + intro i j h + apply Fin.ext + have hv := congrArg Fin.val h + simp only [lookupTape] at hv + omega + +theorem source_outside (i : Fin 5) : (0 : Tape) ≠ lookupTape i := by + intro h + have hv := congrArg Fin.val h + simp only [lookupTape] at hv + omega + +def fields : Fin 3 → Tape := Fin.cases 0 (Fin.cases 6 (fun _ => 7)) + +@[simp] theorem fields_zero : fields 0 = 0 := rfl +@[simp] theorem fields_one : fields 1 = 6 := rfl +@[simp] theorem fields_two : fields 2 = 7 := rfl + +theorem fields_separate (i : Fin 3) : fields i ≠ 8 ∧ fields i ≠ 5 := by + fin_cases i <;> decide + +def copyStateEquiv (σ : Type) : ((σ × Option Bool) × Buffer) ≃ State σ where + toFun s := ((s.1.1, s.2), s.1.2) + invFun s := ((s.1.1, s.2), s.1.2) + left_inv _ := rfl + right_inv _ := rfl + +inductive Label + | lookup (label : MachineAffineLookup.Label) + | copyRelation | reverseSeed | reverseScan | reverseRestore + | emit (label : MachineTableRows.Label) + deriving DecidableEq, Fintype + +def relationCopyAt {K σ Λ : Type} (src dst : K) (exit : Option Λ) : + TM2.Stmt (fun _ : K => Bool) Λ (State σ) := + MachineStateEquiv.statement (copyStateEquiv σ) + (PoweringMachineRow.encodedBlockAt src dst (id : Buffer → Buffer) exit) + +def instruction {σ Λ : Type} (q : Nat) (labels : Label → Λ) (exit : Option Λ) : + Label → TM2.Stmt Alphabet Λ (State σ) + | .lookup l => MachineAffineLookup.instruction 0 lookupTape 4098 3 + (fun l => labels (.lookup l)) (some (labels .copyRelation)) l + | .copyRelation => relationCopyAt 3 7 (some (labels .reverseSeed)) + | .reverseSeed => MachineUnaryAffineAt.seed 6 q (labels .reverseScan) + | .reverseScan => MachineUnaryAffineAt.scan 4 5 6 (q + 1) + (labels .reverseScan) (labels .reverseRestore) + | .reverseRestore => Reduction.MachineTransfer.loopAt 5 4 id false + (labels .reverseRestore) (some (labels (.emit .relationRead))) + | .emit l => MachineTableRows.routine fields 8 9 5 (fun l => labels (.emit l)) exit l + +def machine (q : Nat) : FinTM2 where + K := Tape + k₀ := 1 + k₁ := 9 + Γ := Alphabet + Λ := Label + main := .lookup .seed + σ := State Unit + initialState := (((), zeroBuffer), none) + m := instruction q id none + +def looked (t : Table) (e : Fin t.darts) (base : Tape → List Bool) : Tape → List Bool := + MachineAffineLookup.finalTapes lookupTape base (GraphTables.tableWords t) (4098 * e.val + 3) + t.rows[e].reverseIndex.val + +def copied (t : Table) (e : Fin t.darts) (base : Tape → List Bool) : Tape → List Bool := + Function.update (Function.update (looked t e base) 3 + (encodeWords (suffixWords t e) ++ base 3)) 7 + (encodeWords (relationWords t.rows[e].relation) ++ base 7) + +def affined (q : Nat) (t : Table) (e : Fin t.darts) (base : Tape → List Bool) : + Tape → List Bool := + Function.update (copied t e base) 6 + (encodeWord ((q + 1) * t.rows[e].reverseIndex.val + q) ++ base 6) + +theorem looked_other (t : Table) (e : Fin t.darts) (base : Tape → List Bool) + (k : Tape) (h₂ : k ≠ 2) (h₃ : k ≠ 3) (h₄ : k ≠ 4) : + looked t e base k = base k := + MachineAffineLookup.finalTapes_other lookupTape base _ _ _ k h₂ h₃ h₄ + +theorem looked_reverse (t : Table) (e : Fin t.darts) (base : Tape → List Bool) : + looked t e base 4 = encodeWord t.rows[e].reverseIndex.val ++ base 4 := + MachineAffineLookup.finalTapes_output lookupTape base _ _ _ + +theorem looked_relation (t : Table) (e : Fin t.darts) (base : Tape → List Bool) : + looked t e base 3 = encodeWords (relationWords t.rows[e].relation) ++ + (encodeWords (suffixWords t e) ++ base 3) := by + change MachineLookup.tapes (2 : Tape) 3 4 base + (encodeWord 0 ++ base 2) + (encodeWords ((GraphTables.tableWords t).drop (4098 * e.val + 3 + 1)) ++ base 3) + (encodeWord t.rows[e].reverseIndex.val ++ base 4) 3 = _ + rw [MachineLookup.tapes_source _ _ _ (by decide), remaining_relation, encodeWords_append] + exact List.append_assoc _ _ _ + +theorem vectorBits_eq_encodedBlock {n : Nat} (relation : Vector Bool n) : + PoweringMachineRow.encodeBits (List.ofFn (fun i : Fin n => relation[i])) = + encodeWords (relation.toList.map GraphTables.bitWord) := by + rw [PoweringMachineRow.encodeBits_graphWords] + congr 1 + congr 1 + have hvec : Vector.ofFn (fun i : Fin n => relation[i]) = relation := by + apply Vector.ext + intro i hi + simp only [Vector.getElem_ofFn, Fin.getElem_fin] + exact Vector.toList_ofFn.symm.trans (congrArg Vector.toList hvec) + +theorem relationBits_eq_encodedBlock (relation : RelationTable) : + PoweringMachineRow.encodeBits (List.ofFn (fun i : Fin 4096 => relation[i])) = + encodeWords (relationWords relation) := vectorBits_eq_encodedBlock relation + +theorem relationCopy_step {K Λ σ : Type} [DecidableEq K] + (src dst : K) (hne : src ≠ dst) (label : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State σ)) + (code : program label = relationCopyAt src dst exit) + (relation : RelationTable) (suffix : List Bool) (base : K → List Bool) + (input : base src = encodeWords (relationWords relation) ++ suffix) + (ambient : σ) (buffer : Buffer) (register : Option Bool) : + TM2.step program ⟨some label, ((ambient, buffer), register), base⟩ = + some ⟨exit, ((ambient, zeroBuffer), register), + Function.update (Function.update base src suffix) dst + (encodeWords (relationWords relation) ++ base dst)⟩ := by + change some (TM2.stepAux (program label) _ base) = _ + rw [code] + unfold relationCopyAt + rw [MachineStateEquiv.stepAux_transport_symm] + change some (MachineStateEquiv.configuration (copyStateEquiv σ) + (TM2.stepAux (PoweringMachineRow.encodedBlockAt src dst (id : Buffer → Buffer) exit) + ((ambient, register), buffer) base)) = _ + have hinput : base src = PoweringMachineRow.encodeBits + (List.ofFn (fun i : Fin 4096 => relation[i])) ++ suffix := by + rw [relationBits_eq_encodedBlock] + exact input + rw [PoweringMachineRow.stepAux_encodedBlockAt src dst (id : Buffer → Buffer) + exit hne (fun i : Fin 4096 => relation[i]) suffix + ((ambient, register), buffer) base hinput] + simp only [id_eq, relationBits_eq_encodedBlock, MachineStateEquiv.configuration, + copyStateEquiv, zeroBuffer] + rfl + +theorem relationCopy_pushBound {K Λ σ : Type} (src dst : K) (exit : Option Λ) : + Runtime.statementPushBound (relationCopyAt (σ := σ) src dst exit) = 8192 := by + rw [relationCopyAt, MachineStateEquiv.statementPushBound, + PoweringMachineRow.statementPushBound_encodedBlockAt] + +theorem copied_other (t : Table) (e : Fin t.darts) (base : Tape → List Bool) + (k : Tape) (h₂ : k ≠ 2) (h₃ : k ≠ 3) (h₄ : k ≠ 4) (h₇ : k ≠ 7) : + copied t e base k = base k := by + simp only [copied, Function.update_of_ne h₇, Function.update_of_ne h₃, + looked_other t e base k h₂ h₃ h₄] + +theorem copied_reverse (t : Table) (e : Fin t.darts) (base : Tape → List Bool) : + copied t e base 4 = encodeWord t.rows[e].reverseIndex.val ++ base 4 := by + simp only [copied, Function.update_of_ne (by decide : (4 : Tape) ≠ 7), + Function.update_of_ne (by decide : (4 : Tape) ≠ 3), looked_reverse] + +theorem copied_relation (t : Table) (e : Fin t.darts) (base : Tape → List Bool) : + copied t e base 7 = encodeWords (relationWords t.rows[e].relation) ++ base 7 := by + simp only [copied, Function.update_self] + +theorem affined_other (q : Nat) (t : Table) (e : Fin t.darts) (base : Tape → List Bool) + (k : Tape) (h₂ : k ≠ 2) (h₃ : k ≠ 3) (h₄ : k ≠ 4) (h₆ : k ≠ 6) (h₇ : k ≠ 7) : + affined q t e base k = base k := by + simp only [affined, Function.update_of_ne h₆, copied_other t e base k h₂ h₃ h₄ h₇] + +theorem affined_reverse (q : Nat) (t : Table) (e : Fin t.darts) (base : Tape → List Bool) : + affined q t e base 6 = encodeWord ((q + 1) * t.rows[e].reverseIndex.val + q) ++ base 6 := by + simp only [affined, Function.update_self] + +theorem affined_relation (q : Nat) (t : Table) (e : Fin t.darts) (base : Tape → List Bool) : + affined q t e base 7 = encodeWords (relationWords t.rows[e].relation) ++ base 7 := by + simp only [affined, Function.update_of_ne (by decide : (7 : Tape) ≠ 6), copied_relation] + +structure Input (t : Table) (e : Fin t.darts) (base : Tape → List Bool) : Prop where + indexWord : base 0 = encodeWord e.val + tableWord : base 1 = tableBits t + reverseEmpty : base 4 = [] + scratchEmpty : base 5 = [] + computedEmpty : base 6 = [] + relationEmpty : base 7 = [] + rowEmpty : base 8 = [] + +def emittedWords (q : Nat) (t : Table) (e : Fin t.darts) : List Nat := + e.val :: ((q + 1) * t.rows[e].reverseIndex.val + q) :: relationWords t.rows[e].relation + +theorem affined_fields (q : Nat) (t : Table) (e : Fin t.darts) + (base : Tape → List Bool) (input : Input t e base) : + MachineTableRows.fieldBits fields (affined q t e base) = encodeWords (emittedWords q t e) := by + have htail := affined_other q t e base 0 (by decide) (by decide) (by decide) + (by decide) (by decide) + simp only [MachineTableRows.fieldBits, fields_zero, fields_one, fields_two, + htail, input.indexWord, affined_reverse, input.computedEmpty, + affined_relation, input.relationEmpty, List.append_nil, + emittedWords, encodeWords, List.append_assoc] + +def rowSteps (q : Nat) (t : Table) (e : Fin t.darts) (base : Tape → List Bool) : Nat := + 4 * (encodeWords (emittedWords q t e)).length + 2 * (base 9).length + 9 + +def steps (q : Nat) (t : Table) (e : Fin t.darts) (base : Tape → List Bool) : Nat := + MachineAffineLookup.steps (GraphTables.tableWords t) e.val 4098 3 + 1 + + (2 * (t.rows[e].reverseIndex.val + 1) + 1) + rowSteps q t e base + +def finalTapes (q : Nat) (t : Table) (e : Fin t.darts) (base : Tape → List Bool) : + Tape → List Bool := + Function.update (affined q t e base) 9 (base 9 ++ encodeWords (emittedWords q t e)) + +section Execution + +variable {Λ σ : Type} + +theorem join_trace {A : Type*} {f : A → A} {m n : Nat} {a b c : A} + (first : f^[m] a = b) (second : f^[n] b = c) : f^[m + n] a = c := by + rw [Nat.add_comm m n, Function.iterate_add_apply, first, second] + +theorem lookupTrace (q : Nat) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt Alphabet Λ (State σ)) + (code : ∀ l, program (labels l) = instruction q labels exit l) + (t : Table) (e : Fin t.darts) (base : Tape → List Bool) (input : Input t e base) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[MachineAffineLookup.steps (GraphTables.tableWords t) e.val 4098 3] + (some ⟨some (labels (.lookup .seed)), ((ambient, zeroBuffer), register), base⟩) = + some ⟨some (labels .copyRelation), ((ambient, zeroBuffer), none), looked t e base⟩ := by + exact MachineAffineLookup.affineLookupTrace 0 lookupTape lookupTape_injective source_outside + 4098 3 (fun l => labels (.lookup l)) (some (labels .copyRelation)) program + (fun l => code (.lookup l)) base (GraphTables.tableWords t) input.tableWord input.scratchEmpty + e.val [] (by simpa only [List.append_nil] using input.indexWord) + t.rows[e].reverseIndex.val (selected_reverse t e) (ambient, zeroBuffer) register + +theorem copyTrace (q : Nat) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt Alphabet Λ (State σ)) + (code : ∀ l, program (labels l) = instruction q labels exit l) + (t : Table) (e : Fin t.darts) (base : Tape → List Bool) (ambient : σ) : + (advance (TM2.step program))^[1] + (some ⟨some (labels .copyRelation), ((ambient, zeroBuffer), none), looked t e base⟩) = + some ⟨some (labels .reverseSeed), ((ambient, zeroBuffer), none), copied t e base⟩ := by + simp only [Function.iterate_one, advance_some] + have run := relationCopy_step (3 : Tape) 7 (by decide) (labels .copyRelation) + (some (labels .reverseSeed)) program (code .copyRelation) t.rows[e].relation + (encodeWords (suffixWords t e) ++ base 3) (looked t e base) (looked_relation t e base) + ambient zeroBuffer none + rw [looked_other t e base 7 (by decide) (by decide) (by decide)] at run + exact run + +theorem affineTrace (q : Nat) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt Alphabet Λ (State σ)) + (code : ∀ l, program (labels l) = instruction q labels exit l) + (t : Table) (e : Fin t.darts) (base : Tape → List Bool) (input : Input t e base) + (ambient : σ) : + (advance (TM2.step program))^[2 * (t.rows[e].reverseIndex.val + 1) + 1] + (some ⟨some (labels .reverseSeed), ((ambient, zeroBuffer), none), copied t e base⟩) = + some ⟨some (labels (.emit .relationRead)), ((ambient, zeroBuffer), none), + affined q t e base⟩ := by + have hsource : copied t e base 4 = encodeWord t.rows[e].reverseIndex.val ++ [] := by + rw [copied_reverse, input.reverseEmpty] + have hscratch : copied t e base 5 = [] := by + rw [copied_other t e base 5 (by decide) (by decide) (by decide) (by decide), input.scratchEmpty] + have run := MachineUnaryAffineAt.seededAffineTrace (4 : Tape) 5 6 (by decide) (by decide) + (by decide) (q + 1) q (labels .reverseSeed) (labels .reverseScan) (labels .reverseRestore) + (some (labels (.emit .relationRead))) program (code .reverseSeed) (code .reverseScan) + (code .reverseRestore) (copied t e base) t.rows[e].reverseIndex.val [] hsource hscratch + (ambient, zeroBuffer) none + rw [copied_other t e base 6 (by decide) (by decide) (by decide) (by decide)] at run + exact run + +theorem emitTrace (q : Nat) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt Alphabet Λ (State σ)) + (code : ∀ l, program (labels l) = instruction q labels exit l) + (t : Table) (e : Fin t.darts) (base : Tape → List Bool) (input : Input t e base) + (ambient : σ) : + (advance (TM2.step program))^[rowSteps q t e base] + (some ⟨some (labels (.emit .relationRead)), ((ambient, zeroBuffer), none), affined q t e base⟩) = + some ⟨exit, ((ambient, zeroBuffer), none), finalTapes q t e base⟩ := by + have hrow : affined q t e base 8 = [] := by + rw [affined_other q t e base 8 (by decide) (by decide) (by decide) (by decide) + (by decide), input.rowEmpty] + have hscratch : affined q t e base 5 = [] := by + rw [affined_other q t e base 5 (by decide) (by decide) (by decide) (by decide) + (by decide), input.scratchEmpty] + have hout := affined_other q t e base 9 (by decide) (by decide) (by decide) + (by decide) (by decide) + have hfields := affined_fields q t e base input + have hsize : MachineTableRows.fieldSize fields (affined q t e base) = + (encodeWords (emittedWords q t e)).length := by + rw [← MachineTableRows.fieldBits_length, hfields] + have run := MachineTableRows.appendTrace fields (8 : Tape) 9 5 fields_separate + (by decide) (by decide) (by decide) (fun l => labels (.emit l)) exit program + (fun l => code (.emit l)) (affined q t e base) hrow hscratch (ambient, zeroBuffer) none + rw [hsize, hout, hfields] at run + exact run + +theorem traceAt (q : Nat) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt Alphabet Λ (State σ)) + (code : ∀ l, program (labels l) = instruction q labels exit l) + (t : Table) (e : Fin t.darts) (base : Tape → List Bool) (input : Input t e base) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[steps q t e base] + (some ⟨some (labels (.lookup .seed)), ((ambient, zeroBuffer), register), base⟩) = + some ⟨exit, ((ambient, zeroBuffer), none), finalTapes q t e base⟩ := by + have hlookup := lookupTrace q labels exit program code t e base input ambient register + have hcopy := copyTrace q labels exit program code t e base ambient + have haffine := affineTrace q labels exit program code t e base input ambient + have hemit := emitTrace q labels exit program code t e base input ambient + exact join_trace (join_trace (join_trace hlookup hcopy) haffine) hemit + +end Execution + +def timeBound (q inputLength outputLength : Nat) : Nat := + (4 * q + 17) * inputLength + 2 * outputLength + 4 * q + 32795 + +theorem steps_le (q : Nat) (t : Table) (e : Fin t.darts) (base : Tape → List Bool) : + steps q t e base ≤ timeBound q (tableBits t).length (base 9).length := by + have hl := MachineAffineLookup.steps_le (GraphTables.tableWords t) e.val 4098 3 + t.rows[e].reverseIndex.val (selected_reverse t e) + have htable := tableWords_length_le_bits t + have he : e.val ≤ (tableBits t).length := by have he := e.isLt; omega + have hr : t.rows[e].reverseIndex.val ≤ (tableBits t).length := by + have hrlt := t.rows[e].reverseIndex.isLt + omega + have hrel := relationBits_length_le t.rows[e].relation + have hmul := Nat.mul_le_mul_left (4 * (q + 1) + 2) hr + change MachineAffineLookup.steps (GraphTables.tableWords t) e.val 4098 3 ≤ + 2 * e.val + 5 * (tableBits t).length + 6 at hl + unfold steps rowSteps timeBound emittedWords + simp only [encodeWords, List.length_append, encodeWord_length] + nlinarith + +def machineInTime (H : BaseTable) (t : Table) (e : Fin t.darts) + (base : Tape → List Bool) (input : Input t e base) (register : Option Bool) : + StateTransition.EvalsToInTime (machine internalDegree).step + ⟨some (.lookup .seed), (((), zeroBuffer), register), base⟩ + (some ⟨none, (((), zeroBuffer), none), + Function.update (affined internalDegree t e base) (9 : Tape) + (base (9 : Tape) ++ encodeWords (rowWords (inheritedRow H t e)))⟩) + (timeBound internalDegree (tableBits t).length (base (9 : Tape)).length) where + steps := steps internalDegree t e base + evals_in_steps := by + change (advance (TM2.step (instruction internalDegree id none)))^[_] _ = _ + rw [inheritedRow_words] + exact traceAt internalDegree id none (instruction internalDegree id none) + (fun _ => rfl) t e base input () register + steps_le_m := steps_le internalDegree t e base + +end MinUncutGames.Foundations.Complexity.MachineRegularOriginalRow + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineRegularMetadata.lean b/lean/OAI/Computability/MinUncut/Machines/MachineRegularMetadata.lean new file mode 100644 index 0000000000000000000000000000000000000000..97ac80205358ac640d5b406177b046b35307d986 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineRegularMetadata.lean @@ -0,0 +1,667 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineRegularLift + +namespace OAI + +section +namespace MinUncutGames.Foundations.Complexity.MachineRegularMetadata + +open Turing MachineComposition +open MinUncutGames.Foundations.PCP + + +inductive Extra + | padding | level + deriving DecidableEq + +protected abbrev Extra.enumList : List Extra := [.padding, .level] + +protected theorem Extra.enumList_getElem?_ctorIdx_eq (x : Extra) : + Extra.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem Extra.enumList_nodup : Extra.enumList.Nodup := by decide + +instance : Fintype Extra where + elems := ⟨Extra.enumList, Extra.enumList_nodup⟩ + complete x := by cases x <;> decide + +abbrev Tape := Fin 27 ⊕ Extra +abbrev Alphabet (_ : Tape) := Bool +abbrev State (σ : Type) := (σ × Bool) × Option Bool + +inductive Label + | owner (l : MachineAffineLookup.Label) + | ownerClearQuery | ownerClearWork + | copyXFirst | copyXSecond | copyOwnerFirst | copyOwnerSecond | rankInit + | rank (l : MachineCloudRank.RankLabel) + | rankClearQuery | rankClearWork | rankClearFuel + | prefixCode (l : MachineCloudPrefix.Label) + | prefixClearQuery | prefixClearFuel + | cloud (l : MachineCloudPadding.Label) + deriving DecidableEq, Fintype + +def ownerTapes : Fin 5 → Tape := ![.inl 0, .inl 9, .inl 10, .inl 2, .inl 11] + +def rankTape : MachineCloudCount.Tape → Tape + | .original => .inl 0 + | .work => .inl 10 + | .target => .inl 9 + | .scratch => .inl 11 + | .count => .inl 3 + | .spare => .inl 12 + +def prefixTape : MachineCloudPrefix.Tape → Tape + | .inner .table => .inl 0 + | .inner .query => .inl 9 + | .inner .count => .inl 10 + | .inner .work => .inl 11 + | .inner .scratch => .inl 12 + | .inner .spare => .inl 13 + | .inner .power => .inl 14 + | .inner .level => .inl 15 + | .inner .fuel => .inl 16 + | .inner .product => .inl 17 + | .bound => .inl 2 + | .remaining => .inl 18 + | .total => .inl 5 + +def cloudTape : MachineCloudPadding.Tape → Tape + | .table => .inl 0 + | .query => .inl 2 + | .count => .inl 4 + | .work => .inl 9 + | .scratch => .inl 10 + | .spare => .inl 11 + | .power => .inr .padding + | .level => .inr .level + | .fuel => .inl 12 + | .product => .inl 13 + +variable {σ : Type} + +def program : Label → TM2.Stmt Alphabet Label (State σ) + | .owner l => MachineAffineLookup.instruction (.inl 1) ownerTapes 4098 2 + Label.owner (some .ownerClearQuery) l + | .ownerClearQuery => MachineDrain.drain (.inl 9) .ownerClearQuery (some .ownerClearWork) + | .ownerClearWork => MachineDrain.drain (.inl 10) .ownerClearWork (some .copyXFirst) + | .copyXFirst => Reduction.MachineTransfer.loopAt (.inl 1) (.inl 10) id false + .copyXFirst (some .copyXSecond) + | .copyXSecond => MachineCopy.forkLoop (.inl 10) (.inl 1) (.inl 9) false + .copyXSecond (some .copyOwnerFirst) + | .copyOwnerFirst => Reduction.MachineTransfer.loopAt (.inl 2) (.inl 10) id false + .copyOwnerFirst (some .copyOwnerSecond) + | .copyOwnerSecond => MachineCopy.forkLoop (.inl 10) (.inl 2) (.inl 9) false + .copyOwnerSecond (some .rankInit) + | .rankInit => .push (.inl 3) (fun _ => false) (.goto fun _ => .rank .queryFirst) + | .rank l => MachineCloudPadding.Placement.statement rankTape Label.rank + (some .rankClearQuery) (MachineCloudRank.rankProgram l) + | .rankClearQuery => MachineDrain.drain (.inl 9) .rankClearQuery (some .rankClearWork) + | .rankClearWork => MachineDrain.drain (.inl 10) .rankClearWork (some .rankClearFuel) + | .rankClearFuel => MachineDrain.drain (.inl 12) .rankClearFuel (some (.prefixCode .init)) + | .prefixCode l => MachineCloudPadding.Placement.statement prefixTape Label.prefixCode + (some .prefixClearQuery) (MachineCloudPrefix.program l) + | .prefixClearQuery => MachineDrain.drain (.inl 9) .prefixClearQuery (some .prefixClearFuel) + | .prefixClearFuel => MachineDrain.drain (.inl 18) .prefixClearFuel (some (.cloud .init)) + | .cloud l => MachineCloudPadding.Placement.statement cloudTape Label.cloud none + (MachineCloudPadding.program l) + +def rankView : Tape → Option MachineCloudCount.Tape + | .inl i => match i.val with + | 0 => some .original + | 10 => some .work + | 9 => some .target + | 11 => some .scratch + | 3 => some .count + | 12 => some .spare + | _ => none + | .inr _ => none + +def prefixView : Tape → Option MachineCloudPrefix.Tape + | .inl i => match i.val with + | 0 => some (.inner .table) + | 9 => some (.inner .query) + | 10 => some (.inner .count) + | 11 => some (.inner .work) + | 12 => some (.inner .scratch) + | 13 => some (.inner .spare) + | 14 => some (.inner .power) + | 15 => some (.inner .level) + | 16 => some (.inner .fuel) + | 17 => some (.inner .product) + | 2 => some .bound + | 18 => some .remaining + | 5 => some .total + | _ => none + | .inr _ => none + +def cloudView : Tape → Option MachineCloudPadding.Tape + | .inl i => match i.val with + | 0 => some .table + | 2 => some .query + | 4 => some .count + | 9 => some .work + | 10 => some .scratch + | 11 => some .spare + | 12 => some .fuel + | 13 => some .product + | _ => none + | .inr .padding => some .power + | .inr .level => some .level + +theorem rankView_left (k : MachineCloudCount.Tape) : rankView (rankTape k) = some k := by + cases k <;> rfl +theorem rankView_right (j : Tape) (k : MachineCloudCount.Tape) + (h : rankView j = some k) : rankTape k = j := by + cases j with + | inl j => fin_cases j <;> simp_all [rankView, rankTape] <;> subst k <;> rfl + | inr j => simp_all [rankView] + +theorem prefixView_left (k : MachineCloudPrefix.Tape) : prefixView (prefixTape k) = some k := by + cases k with + | inner k => cases k <;> rfl + | bound => rfl + | remaining => rfl + | total => rfl +theorem prefixView_right (j : Tape) (k : MachineCloudPrefix.Tape) + (h : prefixView j = some k) : prefixTape k = j := by + cases j with + | inl j => fin_cases j <;> simp_all [prefixView, prefixTape] <;> subst k <;> rfl + | inr j => simp_all [prefixView] + +theorem cloudView_left (k : MachineCloudPadding.Tape) : cloudView (cloudTape k) = some k := by + cases k <;> rfl +theorem cloudView_right (j : Tape) (k : MachineCloudPadding.Tape) + (h : cloudView j = some k) : cloudTape k = j := by + cases j with + | inl j => fin_cases j <;> simp_all [cloudView, cloudTape] <;> subst k <;> rfl + | inr j => cases j <;> simp_all [cloudView, cloudTape] <;> subst k <;> rfl + +structure Data where + table : List Bool + globalIndex : List Bool + owner : List Bool + localRank : List Bool + count : List Bool + offset : List Bool + darts : List Bool + rotor : List Bool + output : List Bool + padding : List Bool + level : List Bool + +def frame (data : Data) : Tape → List Bool + | .inl i => match i.val with + | 0 => data.table + | 1 => data.globalIndex + | 2 => data.owner + | 3 => data.localRank + | 4 => data.count + | 5 => data.offset + | 6 => data.darts + | 7 => data.rotor + | 8 => data.output + | _ => [] + | .inr .padding => data.padding + | .inr .level => data.level + +@[simp] theorem frame_index (data : Data) : + frame data (.inl 1) = data.globalIndex := rfl + +@[simp] theorem frame_query_empty (data : Data) : + frame data (.inl 9) = [] := rfl + +def cfg (label : Option Label) (data : Data) (ambient : σ) (register : Option Bool) : + TM2.Cfg Alphabet Label (State σ) := + ⟨label, ((ambient, false), register), frame data⟩ + +def cloudData (t : GraphTables.Table) (v : Fin t.vertices) (data : Data) : Data := + { data with + count := encodeWord (PreprocessingCloudIndex.cloudSize t v) + padding := encodeWord (MachineCloudPadding.padding (PreprocessingCloudIndex.cloudSize t v)) + level := encodeWord (PreprocessingLevels.boundedLevel (PreprocessingCloudIndex.cloudSize t v)) } + +theorem cloudTrace (t : GraphTables.Table) (v : Fin t.vertices) (data : Data) + (htable : data.table = GraphTables.tableBits t) (howner : data.owner = encodeWord v.val) + (hcount : data.count = []) (hpadding : data.padding = []) (hlevel : data.level = []) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[MachineCloudPadding.totalTime t v] + (some (cfg (some (.cloud .init)) data ambient register)) = + some (cfg none (cloudData t v data) ambient none) := by + have raw := MachineCloudPadding.cloudPaddingTrace t v [] ambient register + simp only [List.append_nil] at raw + have placed := MachineCloudPadding.Placement.trace cloudTape cloudView cloudView_left cloudView_right + Label.cloud none (frame data) MachineCloudPadding.program program (fun _ => rfl) + (MachineCloudPadding.totalTime t v) _ _ raw + have hstart : MachineCloudPadding.Placement.tapes cloudView + (MachineCloudPadding.memory (GraphTables.tableBits t) (encodeWord v.val) + [] [] [] [] [] [] [] []) (frame data) = frame data := by + funext j + cases j with + | inl j => fin_cases j <;> + simp_all [MachineCloudPadding.Placement.tapes, cloudView, frame, MachineCloudPadding.memory] + | inr j => cases j <;> + simp_all [MachineCloudPadding.Placement.tapes, cloudView, frame, MachineCloudPadding.memory] + have hfinish : MachineCloudPadding.Placement.tapes cloudView + (MachineCloudPadding.memory (GraphTables.tableBits t) (encodeWord v.val) + (encodeWord (PreprocessingCloudIndex.cloudSize t v)) [] [] [] + (encodeWord (MachineCloudPadding.padding (PreprocessingCloudIndex.cloudSize t v))) + (encodeWord (PreprocessingLevels.boundedLevel (PreprocessingCloudIndex.cloudSize t v))) [] []) + (frame data) = frame (cloudData t v data) := by + funext j + cases j with + | inl j => fin_cases j <;> + simp_all [MachineCloudPadding.Placement.tapes, cloudView, frame, cloudData, MachineCloudPadding.memory] + | inr j => cases j <;> + simp_all [MachineCloudPadding.Placement.tapes, cloudView, frame, cloudData, MachineCloudPadding.memory] + simpa only [MachineCloudPadding.Placement.configuration, MachineCloudPadding.Placement.label, + hstart, hfinish, cfg] using placed + +theorem join_trace {A : Type*} {f : A → A} {m n : Nat} {a b c : A} + (first : f^[m] a = b) (second : f^[n] b = c) : f^[m + n] a = c := by + rw [Nat.add_comm m n, Function.iterate_add_apply, first, second] + +private theorem drainAt (source : Tape) (again : Label) (exit : Option Label) + (code : program (σ := σ) again = MachineDrain.drain source again exit) + (base : Tape → List Bool) (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[(base source).length + 1] + (some ⟨some again, ((ambient, false), register), base⟩) = + some ⟨exit, ((ambient, false), none), Function.update base source []⟩ := by + simpa only [Function.update_eq_self] using + MachineDrain.drainTrace source again exit program code base (base source) + (ambient, false) register + +def prefixData (t : GraphTables.Table) (v : Fin t.vertices) (data : Data) : Data := + { data with offset := encodeWord (PreprocessingPaddingOffsets.offset + (PreprocessingRegularTables.padding t) v.val) } + +def prefixSteps (t : GraphTables.Table) (v : Fin t.vertices) : Nat := + MachineCloudPrefix.totalTime t v.val [] + (v.val + 2) + 2 + +theorem prefixTrace (t : GraphTables.Table) (v : Fin t.vertices) (data : Data) + (htable : data.table = GraphTables.tableBits t) (howner : data.owner = encodeWord v.val) + (hoffset : data.offset = []) (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[prefixSteps t v] + (some (cfg (some (.prefixCode .init)) data ambient register)) = + some (cfg (some (.cloud .init)) (prefixData t v data) ambient none) := by + have raw := MachineCloudPrefix.prefixTrace t v.val v.isLt.le [] ambient register + simp only [List.append_nil] at raw + let mid := MachineCloudPadding.Placement.tapes prefixView + (MachineCloudPrefix.frame (GraphTables.tableBits t) (encodeWord v.val) [] [] [] + (encodeWord v.val) (encodeWord 0) + (encodeWord (PreprocessingPaddingOffsets.offset + (PreprocessingRegularTables.padding t) v.val))) (frame data) + have placed := MachineCloudPadding.Placement.trace prefixTape prefixView prefixView_left + prefixView_right Label.prefixCode (some .prefixClearQuery) (frame data) + MachineCloudPrefix.program program (fun _ => rfl) + (MachineCloudPrefix.totalTime t v.val []) _ _ raw + have hstart : MachineCloudPadding.Placement.tapes prefixView + (MachineCloudPrefix.frame (GraphTables.tableBits t) [] [] [] [] (encodeWord v.val) [] []) + (frame data) = frame data := by + funext j + cases j with + | inl j => fin_cases j <;> + simp [htable, howner, hoffset, MachineCloudPadding.Placement.tapes, prefixView, frame, + MachineCloudPrefix.frame, MachineCloudPrefix.memory, MachineCloudPadding.memory] + | inr j => cases j <;> rfl + have phase : (advance (TM2.step program))^[MachineCloudPrefix.totalTime t v.val []] + (some (cfg (some (.prefixCode .init)) data ambient register)) = + some ⟨some .prefixClearQuery, ((ambient, false), none), mid⟩ := by + simpa only [MachineCloudPadding.Placement.configuration, + MachineCloudPadding.Placement.label, hstart, cfg, mid] using placed + have first := drainAt (.inl 9) .prefixClearQuery (some .prefixClearFuel) rfl mid ambient none + have second := drainAt (.inl 18) .prefixClearFuel (some (.cloud .init)) rfl + (Function.update mid (.inl 9) []) ambient none + have hquery : (mid (.inl 9)).length + 1 = v.val + 2 := by + simp [mid, MachineCloudPadding.Placement.tapes, prefixView, MachineCloudPrefix.frame, MachineCloudPrefix.memory, + MachineCloudPadding.memory, encodeWord_length] + have hfuel : ((Function.update mid (.inl 9) []) (.inl 18)).length + 1 = 2 := by + simp [mid, MachineCloudPadding.Placement.tapes, prefixView, MachineCloudPrefix.frame, MachineCloudPrefix.memory, + encodeWord_length] + have hfinish : Function.update (Function.update mid (.inl 9) []) (.inl 18) [] = + frame (prefixData t v data) := by + funext j + cases j with + | inl j => fin_cases j <;> + simp [htable, howner, mid, MachineCloudPadding.Placement.tapes, prefixView, frame, prefixData, + MachineCloudPrefix.frame, MachineCloudPrefix.memory, MachineCloudPadding.memory] + | inr j => cases j <;> rfl + rw [hquery] at first + rw [hfuel, hfinish] at second + exact join_trace (join_trace phase first) second + +theorem selected_owner (t : GraphTables.Table) (e : Fin t.darts) : + (GraphTables.tableWords t)[4098 * e.val + 2]? = some t.rows[e].tail.val := by + have h := congrArg (fun words : List Nat => words[0]?) + (MachineRegularOriginalRow.tableWords_drop_row t e) + simp only [List.getElem?_drop, Nat.add_zero] at h + rw [show 2 + 4098 * e.val = 4098 * e.val + 2 by omega] at h + simpa [GraphTables.rowWords] using h + +def ownerData (t : GraphTables.Table) (e : Fin t.darts) (data : Data) : Data := + { data with owner := encodeWord t.rows[e].tail.val } + +def ownerRemainder (t : GraphTables.Table) (e : Fin t.darts) : List Bool := + encodeWords ((GraphTables.tableWords t).drop (4098 * e.val + 2 + 1)) + +def ownerSteps (t : GraphTables.Table) (e : Fin t.darts) : Nat := + MachineAffineLookup.steps (GraphTables.tableWords t) e.val 4098 2 + 2 + + ((ownerRemainder t e).length + 1) + +theorem ownerTrace (t : GraphTables.Table) (e : Fin t.darts) (data : Data) + (htable : data.table = GraphTables.tableBits t) + (hindex : data.globalIndex = encodeWord e.val) (howner : data.owner = []) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[ownerSteps t e] + (some (cfg (some (.owner .seed)) data ambient register)) = + some (cfg (some .copyXFirst) (ownerData t e data) ambient none) := by + have distinct : Function.Injective ownerTapes := by + intro i j h + fin_cases i <;> fin_cases j <;> simp_all [ownerTapes] + have outside : ∀ i, (.inl 1 : Tape) ≠ ownerTapes i := by + intro i + fin_cases i <;> decide + let mid := MachineAffineLookup.finalTapes ownerTapes (frame data) + (GraphTables.tableWords t) (4098 * e.val + 2) t.rows[e].tail.val + have phase : (advance (TM2.step program))^[ + MachineAffineLookup.steps (GraphTables.tableWords t) e.val 4098 2] + (some (cfg (some (.owner .seed)) data ambient register)) = + some ⟨some .ownerClearQuery, ((ambient, false), none), mid⟩ := by + exact MachineAffineLookup.affineLookupTrace (.inl 1) ownerTapes distinct outside 4098 2 + Label.owner (some .ownerClearQuery) program (fun _ => rfl) (frame data) + (GraphTables.tableWords t) htable rfl e.val [] + (by change data.globalIndex = encodeWord e.val ++ []; + simpa only [List.append_nil] using hindex) + t.rows[e].tail.val (selected_owner t e) (ambient, false) register + have first := drainAt (.inl 9) .ownerClearQuery (some .ownerClearWork) rfl mid ambient none + have second := drainAt (.inl 10) .ownerClearWork (some .copyXFirst) rfl + (Function.update mid (.inl 9) []) ambient none + have hquery : (mid (.inl 9)).length + 1 = 2 := by + simp [mid, MachineAffineLookup.finalTapes, MachinePreservingLookup.finalTapes, + MachineLookup.tapes, ownerTapes, frame, encodeWord_length] + have hwork : (Function.update mid (.inl 9) []) (.inl 10) = ownerRemainder t e := by + simp [mid, MachineAffineLookup.finalTapes, MachinePreservingLookup.finalTapes, + MachineLookup.tapes, ownerTapes, frame, ownerRemainder] + have hfinish : Function.update (Function.update mid (.inl 9) []) (.inl 10) [] = + frame (ownerData t e data) := by + funext j + cases j with + | inl j => fin_cases j <;> + simp [howner, mid, MachineAffineLookup.finalTapes, MachinePreservingLookup.finalTapes, + MachineLookup.tapes, ownerTapes, frame, ownerData] + | inr j => cases j <;> rfl + rw [hquery] at first + rw [hwork, hfinish] at second + exact join_trace (join_trace phase first) second + +def rankQuery (v x : Nat) : List Bool := MachineCloudRank.queryWord v x [] + +def queryFrame (data : Data) (v x : Nat) : Tape → List Bool := + Function.update (Function.update (frame data) (.inl 9) (rankQuery v x)) + (.inl 3) (encodeWord 0) + +def querySteps (v x : Nat) : Nat := 2 * (x + 2) + 2 * (v + 2) + 1 + +theorem queryTrace (data : Data) (v x : Nat) + (howner : data.owner = encodeWord v) (hindex : data.globalIndex = encodeWord x) + (hrank : data.localRank = []) (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[querySteps v x] + (some (cfg (some .copyXFirst) data ambient register)) = + some ⟨some (.rank .queryFirst), ((ambient, false), none), queryFrame data v x⟩ := by + let first := Function.update (frame data) (.inl 9) data.globalIndex + let second := Function.update first (.inl 9) (data.owner ++ data.globalIndex) + have copyX := MachineCopy.copyTrace (.inl 1 : Tape) (.inl 9) (.inl 10) + (by decide) (by decide) (by decide) false Label.copyXFirst Label.copyXSecond + (some .copyOwnerFirst) program rfl rfl (frame data) rfl (ambient, false) register + have copyOwner := MachineCopy.copyTrace (.inl 2 : Tape) (.inl 9) (.inl 10) + (by decide) (by decide) (by decide) false Label.copyOwnerFirst Label.copyOwnerSecond + (some .rankInit) program rfl rfl first (by simp [first, frame]) (ambient, false) none + have firstRun : (advance (TM2.step program))^[2 * (x + 2)] + (some (cfg (some .copyXFirst) data ambient register)) = + some ⟨some .copyOwnerFirst, ((ambient, false), none), first⟩ := by + simpa only [frame_index, frame_query_empty, hindex, encodeWord_length, + List.append_nil, cfg, first] using copyX + have secondRun : (advance (TM2.step program))^[2 * (v + 2)] + (some ⟨some .copyOwnerFirst, ((ambient, false), none), first⟩) = + some ⟨some .rankInit, ((ambient, false), none), second⟩ := by + simpa [first, frame, howner, encodeWord_length, second] using copyOwner + have init : (advance (TM2.step program))^[1] + (some ⟨some .rankInit, ((ambient, false), none), second⟩) = + some ⟨some (.rank .queryFirst), ((ambient, false), none), queryFrame data v x⟩ := by + have ht : Function.update second (.inl 3) (false :: second (.inl 3)) = + queryFrame data v x := by + funext j + cases j with + | inl j => fin_cases j <;> + simp_all [queryFrame, second, first, frame, rankQuery, + MachineCloudRank.queryWord, encodeWord] + | inr j => cases j <;> rfl + simp only [Function.iterate_one, advance_some, TM2.step, program, TM2.stepAux, ht] + exact join_trace (join_trace firstRun secondRun) init + +def rankData (t : GraphTables.Table) (v : Fin t.vertices) + (e : DegreeReplacement.Cloud (GraphTables.semantics t) v) (data : Data) : Data := + { data with localRank := encodeWord (PreprocessingCloudIndex.cloudRank t v e).val } + +def rankRemainder (t : GraphTables.Table) + (v : Fin t.vertices) (e : DegreeReplacement.Cloud (GraphTables.semantics t) v) : List Bool := + encodeWords (((MachineCloudCount.tableRows t).drop e.val.val).flatMap MachineCloudCount.rowWords) + +def rankSteps (t : GraphTables.Table) (v : Fin t.vertices) + (e : DegreeReplacement.Cloud (GraphTables.semantics t) v) : Nat := + querySteps v.val e.val.val + + MachineCloudRank.rankSteps t.vertices t.darts v.val e.val.val (MachineCloudCount.tableRows t) [] + + ((rankQuery v.val e.val.val).length + 1) + ((rankRemainder t v e).length + 1) + 2 + +theorem rankTrace (t : GraphTables.Table) (v : Fin t.vertices) + (e : DegreeReplacement.Cloud (GraphTables.semantics t) v) (data : Data) + (htable : data.table = GraphTables.tableBits t) + (howner : data.owner = encodeWord v.val) (hindex : data.globalIndex = encodeWord e.val.val) + (hrank : data.localRank = []) (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[rankSteps t v e] + (some (cfg (some .copyXFirst) data ambient register)) = + some (cfg (some (.prefixCode .init)) (rankData t v e data) ambient none) := by + have query := queryTrace data v.val e.val.val howner hindex hrank ambient register + have raw := MachineCloudRank.cloudRankTrace t v e [] [] ambient none + simp only [List.append_nil] at raw + let mid := MachineCloudPadding.Placement.tapes rankView + (MachineCloudCount.memory (GraphTables.tableBits t) (rankRemainder t v e) + (rankQuery v.val e.val.val) [] + (encodeWord (PreprocessingCloudIndex.cloudRank t v e).val) (encodeWord 0)) (frame data) + have placed := MachineCloudPadding.Placement.trace rankTape rankView rankView_left + rankView_right Label.rank (some .rankClearQuery) (frame data) + MachineCloudRank.rankProgram program (fun _ => rfl) + (MachineCloudRank.rankSteps t.vertices t.darts v.val e.val.val (MachineCloudCount.tableRows t) []) + _ _ raw + have hstart : MachineCloudPadding.Placement.tapes rankView + (MachineCloudCount.memory (GraphTables.tableBits t) [] + (rankQuery v.val e.val.val) [] (encodeWord 0) []) (frame data) = + queryFrame data v.val e.val.val := by + funext j + cases j with + | inl j => fin_cases j <;> + simp [MachineCloudPadding.Placement.tapes, rankView, frame, + queryFrame, MachineCloudCount.memory, htable, howner, hindex] + | inr j => cases j <;> rfl + simp only [rankQuery] at hstart + have phase : (advance (TM2.step program))^[ + MachineCloudRank.rankSteps t.vertices t.darts v.val e.val.val (MachineCloudCount.tableRows t) []] + (some ⟨some (.rank .queryFirst), ((ambient, false), none), queryFrame data v.val e.val.val⟩) = + some ⟨some .rankClearQuery, ((ambient, false), none), mid⟩ := by + simpa only [MachineCloudPadding.Placement.configuration, MachineCloudPadding.Placement.label, + hstart, mid, rankQuery, rankRemainder] using placed + have first := drainAt (.inl 9) .rankClearQuery (some .rankClearWork) rfl mid ambient none + have second := drainAt (.inl 10) .rankClearWork (some .rankClearFuel) rfl + (Function.update mid (.inl 9) []) ambient none + have third := drainAt (.inl 12) .rankClearFuel (some (.prefixCode .init)) rfl + (Function.update (Function.update mid (.inl 9) []) (.inl 10) []) ambient none + have hquery : mid (.inl 9) = rankQuery v.val e.val.val := rfl + have hwork : Function.update mid (.inl 9) [] (.inl 10) = rankRemainder t v e := by + simp [mid, MachineCloudPadding.Placement.tapes, rankView, MachineCloudCount.memory] + have hfuel : ((Function.update (Function.update mid (.inl 9) []) (.inl 10) []) + (.inl 12)).length + 1 = 2 := by + simp [mid, MachineCloudPadding.Placement.tapes, rankView, MachineCloudCount.memory, + encodeWord_length] + have hfinish : Function.update + (Function.update (Function.update mid (.inl 9) []) (.inl 10) []) (.inl 12) [] = + frame (rankData t v e data) := by + funext j + cases j with + | inl j => fin_cases j <;> + simp [mid, MachineCloudPadding.Placement.tapes, rankView, frame, rankData, + MachineCloudCount.memory, htable] + | inr j => cases j <;> rfl + rw [hquery] at first + rw [hwork] at second + rw [hfuel, hfinish] at third + exact join_trace (join_trace (join_trace (join_trace query phase) first) second) third + +def originalMember (t : GraphTables.Table) (e : Fin t.darts) : + DegreeReplacement.Cloud (GraphTables.semantics t) t.rows[e].tail := ⟨e, rfl⟩ + +def originalData (t : GraphTables.Table) (e : Fin t.darts) (data : Data) : Data := + cloudData t t.rows[e].tail (prefixData t t.rows[e].tail + (rankData t t.rows[e].tail (originalMember t e) (ownerData t e data))) + +def totalTime (t : GraphTables.Table) (e : Fin t.darts) : Nat := + ownerSteps t e + rankSteps t t.rows[e].tail (originalMember t e) + + prefixSteps t t.rows[e].tail + MachineCloudPadding.totalTime t t.rows[e].tail + +theorem originalTrace (t : GraphTables.Table) (e : Fin t.darts) (data : Data) + (htable : data.table = GraphTables.tableBits t) + (hindex : data.globalIndex = encodeWord e.val) + (howner : data.owner = []) (hrank : data.localRank = []) (hcount : data.count = []) + (hoffset : data.offset = []) (hpadding : data.padding = []) (hlevel : data.level = []) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[totalTime t e] + (some (cfg (some (.owner .seed)) data ambient register)) = + some (cfg none (originalData t e data) ambient none) := by + have own := ownerTrace t e data htable hindex howner ambient register + have rank := rankTrace t t.rows[e].tail (originalMember t e) (ownerData t e data) + htable rfl hindex hrank ambient none + have pref := prefixTrace t t.rows[e].tail + (rankData t t.rows[e].tail (originalMember t e) (ownerData t e data)) + htable rfl hoffset ambient none + have cloud := cloudTrace t t.rows[e].tail + (prefixData t t.rows[e].tail + (rankData t t.rows[e].tail (originalMember t e) (ownerData t e data))) + htable rfl hcount hpadding hlevel ambient none + exact join_trace (join_trace (join_trace own rank) pref) cloud + +private theorem encodeWords_drop_length_le (values : List Nat) (n : Nat) : + (encodeWords (values.drop n)).length ≤ (encodeWords values).length := by + have h := congrArg (fun words : List Nat => (encodeWords words).length) + (List.take_append_drop n values) + simp only [encodeWords_append, List.length_append] at h + omega + +theorem ownerRemainder_length_le (t : GraphTables.Table) (e : Fin t.darts) : + (ownerRemainder t e).length ≤ (GraphTables.tableBits t).length := + encodeWords_drop_length_le _ _ + +theorem rankRemainder_length_le (t : GraphTables.Table) (v : Fin t.vertices) + (e : DegreeReplacement.Cloud (GraphTables.semantics t) v) : + (rankRemainder t v e).length ≤ (GraphTables.tableBits t).length := by + have split := congrArg List.length + (MachineCloudRank.encoded_rows_split (MachineCloudCount.tableRows t) e.val.val) + have input := MachineCloudCount.inputWord_length t.vertices t.darts (MachineCloudCount.tableRows t) + rw [MachineCloudCount.tableRows_input] at input + simp only [List.length_append] at split + unfold rankRemainder + omega + +noncomputable def timePolynomial : Polynomial Nat := + (MachineCloudPrefix.timePolynomial + MachineCloudPadding.timePolynomial).comp + (2 * Polynomial.X) + 40 * (Polynomial.X + 1) + +def overhead (N x v : Nat) : Nat := + (2*x + 5*N + 6) + 2 + (N+1) + 2*(x+2) + 2*(v+2) + 1 + + (5*N + 3*(v+x+2) + 6) + (v+x+3) + (N+1) + 2 + (v+2) + 2 + +theorem overhead_le (N x v : Nat) (hx : x ≤ N) (hv : v ≤ N) : + overhead N x v ≤ 40*(N+1) := by + unfold overhead + omega + +theorem totalTime_le (t : GraphTables.Table) (e : Fin t.darts) : + totalTime t e ≤ timePolynomial.eval (GraphTables.tableBits t).length := by + let v := t.rows[e].tail + let c := originalMember t e + let N := (GraphTables.tableBits t).length + have hn := GraphTables.vertices_le_tableBits_length t + have hm := GraphTables.darts_le_tableBits_length t + have hv : v.val < N := lt_of_lt_of_le v.isLt hn + have hx : e.val ≤ N := e.isLt.le.trans hm + have ownerBound := MachineAffineLookup.steps_le (GraphTables.tableWords t) + e.val 4098 2 t.rows[e].tail.val (selected_owner t e) + have ownerRest := ownerRemainder_length_le t e + have rankBound := MachineCloudRank.rankSteps_le t.vertices t.darts v.val e.val + (MachineCloudCount.tableRows t) [] + rw [MachineCloudCount.tableRows_input] at rankBound + have rankRest := rankRemainder_length_le t v c + have hpIn : MachineCloudPrefix.inputLength t v.val [] ≤ 2*N := by + simp only [MachineCloudPrefix.inputLength, List.append_nil, encodeWord_length] + omega + have hcIn : MachineCloudPadding.inputLength t v [] ≤ 2*N := by + simp only [MachineCloudPadding.inputLength, List.append_nil, encodeWord_length] + omega + have hp := (MachineCloudPrefix.totalTime_le t v.val v.isLt.le []).trans + (natPolynomial_eval_mono MachineCloudPrefix.timePolynomial hpIn) + have hc := (MachineCloudPadding.totalTime_le t v []).trans + (natPolynomial_eval_mono MachineCloudPadding.timePolynomial hcIn) + have ho := overhead_le N e.val v.val hx hv.le + have hsmall : ownerSteps t e + rankSteps t v c + (v.val+2) + 2 ≤ + overhead N e.val v.val := by + simp only [MachineCloudRank.queryWord, List.length_append, encodeWord_length, + List.length_nil] at rankBound + simp only [ownerSteps, rankSteps, querySteps, rankQuery, MachineCloudRank.queryWord, + List.length_append, encodeWord_length, List.length_nil, overhead] + change _ ≤ _ at ownerBound + dsimp only [c, originalMember] at rankRest ⊢ + change MachineAffineLookup.steps (GraphTables.tableWords t) e.val 4098 2 ≤ + 2*e.val+5*N+6 at ownerBound + omega + have htotal : totalTime t e = ownerSteps t e + rankSteps t v c + + MachineCloudPrefix.totalTime t v.val [] + (v.val+2) + 2 + + MachineCloudPadding.totalTime t v := by + simp only [totalTime, prefixSteps, v, c] + omega + rw [htotal] + simp only [timePolynomial, Polynomial.eval_add, Polynomial.eval_comp, + Polynomial.eval_mul, Polynomial.eval_ofNat, Polynomial.eval_X, Polynomial.eval_one] + change _ ≤ MachineCloudPrefix.timePolynomial.eval (2*N) + + MachineCloudPadding.timePolynomial.eval (2*N) + 40*(N+1) + omega + +def originalInTime (t : GraphTables.Table) (e : Fin t.darts) (data : Data) + (htable : data.table = GraphTables.tableBits t) + (hindex : data.globalIndex = encodeWord e.val) + (howner : data.owner = []) (hrank : data.localRank = []) (hcount : data.count = []) + (hoffset : data.offset = []) (hpadding : data.padding = []) (hlevel : data.level = []) + (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + (cfg (some (.owner .seed)) data ambient register) + (some (cfg none (originalData t e data) ambient none)) + (timePolynomial.eval (GraphTables.tableBits t).length) where + steps := totalTime t e + evals_in_steps := originalTrace t e data htable hindex howner hrank hcount hoffset + hpadding hlevel ambient register + steps_le_m := totalTime_le t e + +def cloudInTime (t : GraphTables.Table) (v : Fin t.vertices) (data : Data) + (htable : data.table = GraphTables.tableBits t) (howner : data.owner = encodeWord v.val) + (hcount : data.count = []) (hpadding : data.padding = []) (hlevel : data.level = []) + (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + (cfg (some (.cloud .init)) data ambient register) + (some (cfg none (cloudData t v data) ambient none)) + (MachineCloudPadding.timePolynomial.eval (MachineCloudPadding.inputLength t v [])) where + steps := MachineCloudPadding.totalTime t v + evals_in_steps := cloudTrace t v data htable howner hcount hpadding hlevel ambient register + steps_le_m := MachineCloudPadding.totalTime_le t v [] + +end MinUncutGames.Foundations.Complexity.MachineRegularMetadata + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineRegularOriginalBody.lean b/lean/OAI/Computability/MinUncut/Machines/MachineRegularOriginalBody.lean new file mode 100644 index 0000000000000000000000000000000000000000..aab8b40261704a913fac5c08b5c1f71404cb5a3a --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineRegularOriginalBody.lean @@ -0,0 +1,583 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineRegularMetadata +import OAI.Computability.MinUncut.Machines.MachineRegularVertexBlock +import OAI.Computability.MinUncut.PCP.PreprocessingFamilyBridge + +namespace OAI + +namespace MinUncutGames.Foundations.Complexity.MachineRegularOriginalBody + +open Turing MachineComposition PCP +open PreprocessingCloudIndex PreprocessingRegularTables +open MachineRegularTable + +abbrev Tape := Fin 27 ⊕ (MachineRegularMetadata.Extra ⊕ MachinePaddedExpanderFamily.Tape) +abbrev Alphabet (_ : Tape) := Bool +abbrev CoreState := MachineRegularInternalRow.CoreState Unit internalDegree +abbrev MetaState := MachineRegularMetadata.State Unit +abbrev FamilyState := MachineRegularFamily.State +abbrev State := (CoreState × MetaState) × FamilyState +abbrev Data := MachineRegularMetadata.Data +abbrev BaseTable := PreprocessingRegularTables.BaseTable + +theorem degree_positive : 0 < internalDegree := + Nat.mul_pos MachineExpanderFamily.baseDegree_positive MachineExpanderFamily.baseDegree_positive + +def readyState (H : BaseTable) : State := + ((MachineRegularInternalRow.coreInitialState internalDegree degree_positive (), + (((), false), none)), MachineRegularFamily.readyState H) + +def metadataTape : MachineRegularMetadata.Tape → Tape + | .inl i => .inl i + | .inr e => .inr (.inl e) + +def metadataView : Tape → Option MachineRegularMetadata.Tape + | .inl i => some (.inl i) + | .inr (.inl e) => some (.inr e) + | .inr (.inr _) => none + +def familyTape : MachineRegularFamily.Tape → Tape + | .inl i => .inl i + | .inr e => .inr (.inr e) + +def familyView : Tape → Option MachineRegularFamily.Tape + | .inl i => some (.inl i) + | .inr (.inl _) => none + | .inr (.inr e) => some (.inr e) + +def vertexView : Tape → Option (Fin 27) + | .inl i => some i + | .inr _ => none + +theorem metadataView_left (k : MachineRegularMetadata.Tape) : + metadataView (metadataTape k) = some k := by cases k <;> rfl + +theorem metadataView_right (j : Tape) (k : MachineRegularMetadata.Tape) + (h : metadataView j = some k) : metadataTape k = j := by + cases j with + | inl i => cases h; rfl + | inr j => cases j with + | inl e => cases h; rfl + | inr e => cases h + +theorem familyView_left (k : MachineRegularFamily.Tape) : + familyView (familyTape k) = some k := by cases k <;> rfl + +theorem familyView_right (j : Tape) (k : MachineRegularFamily.Tape) + (h : familyView j = some k) : familyTape k = j := by + cases j with + | inl i => cases h; rfl + | inr j => cases j with + | inl e => cases h + | inr e => cases h; rfl + +theorem vertexView_left (k : Fin 27) : vertexView (.inl k) = some k := rfl + +theorem vertexView_right (j : Tape) (k : Fin 27) + (h : vertexView j = some k) : Sum.inl k = j := by + cases j with + | inl i => cases h; rfl + | inr e => cases h + +def metadataStates : (MetaState × (CoreState × FamilyState)) ≃ State where + toFun p := ((p.2.1, p.1), p.2.2) + invFun p := (p.1.2, (p.1.1, p.2)) + left_inv _ := rfl + right_inv _ := rfl + +def familyStates : (FamilyState × (CoreState × MetaState)) ≃ State := Equiv.prodComm _ _ +def vertexStates : (CoreState × (MetaState × FamilyState)) ≃ State := + (Equiv.prodAssoc _ _ _).symm + +inductive Label + | metadata (l : MachineRegularMetadata.Label) + | family (l : MachineRegularFamily.Label) + | vertex (l : MachineRegularVertexBlock.Label internalDegree) + | clear (i : Fin 7) + deriving DecidableEq, Fintype + +def entry : Label := .metadata (.owner .seed) + +def clearTape : Fin 7 → Tape := + ![.inl 2, .inl 3, .inl 4, .inl 5, .inl 7, + .inr (.inl .padding), .inr (.inl .level)] + +def clearEntry (k : Nat) : Option Label := + if h : k < 7 then some (.clear ⟨k, h⟩) else none + +def clearSource (source : Tape) : Unit → TM2.Stmt Alphabet Unit MetaState := + fun _ => MachineDrain.drain source () none + +def vertexSource : MachineRegularVertexBlock.Label internalDegree → + TM2.Stmt (fun _ : Fin 27 => Bool) (MachineRegularVertexBlock.Label internalDegree) CoreState := + MachineRegularVertexBlock.instruction internalDegree degree_positive id none + +def program (H : BaseTable) : Label → TM2.Stmt Alphabet Label State + | .metadata l => Lift.statement metadataTape Label.metadata (some (.family .start)) + metadataStates (MachineRegularMetadata.program l) + | .family l => Lift.statement familyTape Label.family + (some (.vertex (MachineRegularVertexBlock.originalEntry internalDegree degree_positive))) + familyStates (MachineRegularFamily.program H l) + | .vertex l => Lift.statement Sum.inl Label.vertex (clearEntry 0) + vertexStates (vertexSource l) + | .clear i => Lift.statement id (fun _ : Unit => .clear i) (clearEntry (i.val + 1)) + metadataStates (clearSource (clearTape i) ()) + +def frame (data : Data) : Tape → List Bool + | .inl i => MachineRegularMetadata.frame data (.inl i) + | .inr (.inl e) => MachineRegularMetadata.frame data (.inr e) + | .inr (.inr _) => [] + +def coreFrame (data : Data) (i : Fin 27) : List Bool := + MachineRegularMetadata.frame data (.inl i) + +def cfg (H : BaseTable) (label : Option Label) (data : Data) : TM2.Cfg Alphabet Label State := + ⟨label, readyState H, frame data⟩ + +def initialData (t : GraphTables.Table) (e : Fin t.darts) (output : List Bool) : Data where + table := GraphTables.tableBits t + globalIndex := encodeWord e.val + owner := [] + localRank := [] + count := [] + offset := [] + darts := encodeWord t.darts + rotor := [] + output := output + padding := [] + level := [] + +def metadataData (t : GraphTables.Table) (e : Fin t.darts) (output : List Bool) : Data := + MachineRegularMetadata.originalData t e (initialData t e output) + +def familyData (H : BaseTable) (t : GraphTables.Table) (e : Fin t.darts) + (output : List Bool) : Data := + { metadataData t e output with + rotor := MachineRegularFamily.rotor H (cloudSize t t.rows[e].tail) } + +def emittedBits (H : BaseTable) (t : GraphTables.Table) (e : Fin t.darts) : List Bool := + PreprocessingRegularWords.originalVertexBits t (padding t) (familyCloudTable H t) e + +def emittedData (H : BaseTable) (t : GraphTables.Table) (e : Fin t.darts) + (output : List Bool) : Data := + { familyData H t e output with output := output ++ emittedBits H t e } + +theorem joinTrace {A : Type*} {f : A → A} {m n : Nat} {a b c : A} + (first : f^[m] a = b) (second : f^[n] b = c) : f^[m + n] a = c := by + rw [Nat.add_comm m n, Function.iterate_add_apply, first, second] + +theorem metadataPlacement (data extra : Data) : + MachineCloudPadding.Placement.tapes metadataView (MachineRegularMetadata.frame data) + (frame extra) = frame data := by + funext j + cases j with + | inl i => rfl + | inr j => cases j <;> rfl + +theorem metadataTrace (H : BaseTable) (t : GraphTables.Table) (e : Fin t.darts) + (output : List Bool) : + (advance (TM2.step (program H)))^[MachineRegularMetadata.totalTime t e] + (some (cfg H (some entry) (initialData t e output))) = + some (cfg H (some (.family .start)) (metadataData t e output)) := by + have raw := MachineRegularMetadata.originalTrace t e (initialData t e output) + rfl rfl rfl rfl rfl rfl rfl rfl () none + have placed := Lift.trace metadataTape metadataView metadataView_left metadataView_right + Label.metadata (some (.family .start)) metadataStates + (MachineRegularInternalRow.coreInitialState internalDegree degree_positive (), + MachineRegularFamily.readyState H) (frame (initialData t e output)) + MachineRegularMetadata.program (program H) (fun _ => rfl) _ _ _ raw + simpa only [Lift.configuration, MachineCloudPadding.Placement.label, + metadataPlacement, MachineRegularMetadata.cfg, metadataData, cfg, readyState, + metadataStates, Equiv.coe_fn_mk, entry] using placed + +theorem familyPlacement (data : Data) : + MachineCloudPadding.Placement.tapes familyView (MachineRegularFamily.frame (coreFrame data)) + (frame data) = frame data := by + funext j + cases j with + | inl i => rfl + | inr j => cases j <;> rfl + +theorem familyResultPlacement (H : BaseTable) (k : Nat) (data : Data) : + MachineCloudPadding.Placement.tapes familyView + (MachineRegularFamily.frame (MachineRegularFamily.resultCore H k (coreFrame data))) + (frame data) = frame { data with rotor := MachineRegularFamily.rotor H k } := by + funext j + cases j with + | inl i => fin_cases i <;> + simp [MachineCloudPadding.Placement.tapes, familyView, MachineRegularFamily.frame, + MachineRegularFamily.resultCore, coreFrame, frame, MachineRegularMetadata.frame] + | inr j => cases j with + | inl e => cases e <;> rfl + | inr e => rfl + +noncomputable def familyExecution (H : BaseTable) (t : GraphTables.Table) + (e : Fin t.darts) (output : List Bool) := + MachineRegularFamily.familyCleanInTime H (cloudSize t t.rows[e].tail) + (coreFrame (metadataData t e output)) rfl rfl (MachineRegularFamily.readyState H) + +noncomputable def familySteps (H : BaseTable) (t : GraphTables.Table) + (e : Fin t.darts) (output : List Bool) : Nat := + (familyExecution H t e output).steps + +theorem familyTrace (H : BaseTable) (t : GraphTables.Table) (e : Fin t.darts) + (output : List Bool) : + (advance (TM2.step (program H)))^[familySteps H t e output] + (some (cfg H (some (.family .start)) (metadataData t e output))) = + some (cfg H (some (.vertex (MachineRegularVertexBlock.originalEntry + internalDegree degree_positive))) (familyData H t e output)) := by + have raw := (familyExecution H t e output).evals_in_steps + have placed := Lift.trace familyTape familyView familyView_left familyView_right + Label.family (some (.vertex (MachineRegularVertexBlock.originalEntry internalDegree degree_positive))) + familyStates + (MachineRegularInternalRow.coreInitialState internalDegree degree_positive (), + ((((), false), none) : MetaState)) (frame (metadataData t e output)) + (MachineRegularFamily.program H) (program H) (fun _ => rfl) _ _ _ raw + simpa only [Lift.configuration, MachineCloudPadding.Placement.label, + familyPlacement, familyResultPlacement, familyData, familySteps, cfg, readyState, + familyStates, Equiv.prodComm_apply, Prod.swap_prod_mk] using placed + +def clearMemory (base : Tape → List Bool) : Nat → Tape → List Bool + | 0 => base + | k + 1 => if h : k < 7 then + Function.update (clearMemory base k) (clearTape ⟨k, h⟩) [] else clearMemory base k + +def clearSteps (base : Tape → List Bool) : Nat → Nat + | 0 => 0 + | k + 1 => clearSteps base k + if h : k < 7 then + ((clearMemory base k) (clearTape ⟨k, h⟩)).length + 1 else 0 + +private theorem identityPlacement (base extra : Tape → List Bool) : + MachineCloudPadding.Placement.tapes some base extra = base := rfl + +theorem drainTrace (H : BaseTable) (i : Fin 7) (base : Tape → List Bool) : + (advance (TM2.step (program H)))^[(base (clearTape i)).length + 1] + (some ⟨some (.clear i), readyState H, base⟩) = + some ⟨clearEntry (i.val + 1), readyState H, Function.update base (clearTape i) []⟩ := by + have raw := MachineDrain.drainTrace (clearTape i) () none (clearSource (clearTape i)) rfl + base (base (clearTape i)) ((), false) none + simp only [Function.update_eq_self] at raw + have placed := Lift.trace id some (fun _ => rfl) + (fun j k h => (Option.some.inj h).symm) + (fun _ : Unit => Label.clear i) (clearEntry (i.val + 1)) metadataStates + (MachineRegularInternalRow.coreInitialState internalDegree degree_positive (), + MachineRegularFamily.readyState H) base (clearSource (clearTape i)) (program H) + (fun _ => rfl) _ _ _ raw + simpa only [Lift.configuration, MachineCloudPadding.Placement.label, + identityPlacement, metadataStates, Equiv.coe_fn_mk, readyState] using placed + +theorem clearPrefixTrace (H : BaseTable) (base : Tape → List Bool) + (k : Nat) (hk : k ≤ 7) : + (advance (TM2.step (program H)))^[clearSteps base k] + (some ⟨clearEntry 0, readyState H, base⟩) = + some ⟨clearEntry k, readyState H, clearMemory base k⟩ := by + induction k with + | zero => rfl + | succ k ih => + have h : k < 7 := by omega + have first := ih (by omega) + have second := drainTrace H ⟨k, h⟩ (clearMemory base k) + have atEntry : clearEntry k = some (.clear ⟨k, h⟩) := by simp only [clearEntry, dite_eq_left h] + rw [atEntry] at first + simpa only [clearSteps, clearMemory, dite_eq_left h] using joinTrace first second + +theorem clearTrace (H : BaseTable) (base : Tape → List Bool) : + (advance (TM2.step (program H)))^[clearSteps base 7] + (some ⟨clearEntry 0, readyState H, base⟩) = + some ⟨none, readyState H, clearMemory base 7⟩ := by + simpa only [clearEntry, lt_self_iff_false, dite_false] using clearPrefixTrace H base 7 le_rfl + +theorem clearFrame (data : Data) : clearMemory (frame data) 7 = + frame { data with + owner := [] + localRank := [] + count := [] + offset := [] + rotor := [] + padding := [] + level := [] } := by + funext j + cases j with + | inl i => fin_cases i <;> + simp [clearMemory, clearTape, frame, MachineRegularMetadata.frame] + | inr j => cases j with + | inl e => cases e <;> + simp [clearMemory, clearTape, frame, MachineRegularMetadata.frame] + | inr e => simp [clearMemory, clearTape, frame] + +theorem coreFrame_eq (H : BaseTable) (t : GraphTables.Table) (e : Fin t.darts) + (output : List Bool) : + coreFrame (familyData H t e output) = + MachineRegularInternalRow.coreInputTapes t (padding t) (familyCloudTable H t) + t.rows[e].tail (MachineRegularVertexBlock.oldCloud t (padding t) e) output := by + have rotor : MachineRegularFamily.rotor H (cloudSize t t.rows[e].tail) = + encodeWords (ExpanderTableWords.rotationWords (familyCloudTable H t t.rows[e].tail)) := + PreprocessingFamilyBridge.familyRotor_eq_familyCloudTable H t t.rows[e].tail + (PreprocessingFamilyBridge.cloudSize_pos_of_dart t e) + funext i + fin_cases i <;> + simp [coreFrame, familyData, metadataData, MachineRegularMetadata.originalData, + MachineRegularMetadata.cloudData, MachineRegularMetadata.prefixData, + MachineRegularMetadata.rankData, MachineRegularMetadata.ownerData, + MachineRegularMetadata.frame, initialData, + MachineRegularInternalRow.coreInputTapes, MachineRegularInternalRow.coreMemory, + MachineRegularVertexBlock.oldCloud, paddedOld, + MachineRegularMetadata.originalMember] + all_goals first | exact rotor | rfl + +theorem emittedData_eq (H : BaseTable) (t : GraphTables.Table) (e : Fin t.darts) + (output : List Bool) : emittedData H t e output = + familyData H t e (output ++ emittedBits H t e) := rfl + +theorem vertexPlacement (H : BaseTable) (t : GraphTables.Table) (e : Fin t.darts) + (output output' : List Bool) : + MachineCloudPadding.Placement.tapes vertexView (coreFrame (familyData H t e output')) + (frame (familyData H t e output)) = frame (familyData H t e output') := by + funext j + cases j with + | inl i => rfl + | inr j => cases j with + | inl e => cases e <;> rfl + | inr e => rfl + +def vertexSteps (H : BaseTable) (t : GraphTables.Table) (e : Fin t.darts) + (output : List Bool) : Nat := + MachineRegularVertexBlock.originalSteps t (padding t) (familyCloudTable H t) e output.length + +theorem vertexTrace (H : BaseTable) (t : GraphTables.Table) (e : Fin t.darts) + (output : List Bool) : + (advance (TM2.step (program H)))^[vertexSteps H t e output] + (some (cfg H (some (.vertex (MachineRegularVertexBlock.originalEntry + internalDegree degree_positive))) (familyData H t e output))) = + some (cfg H (clearEntry 0) (emittedData H t e output)) := by + have raw := MachineRegularVertexBlock.originalTraceAt internalDegree degree_positive id none + vertexSource (fun _ => rfl) t (padding t) (familyCloudTable H t) e output () + have finished := coreFrame_eq H t e (output ++ emittedBits H t e) + simp only [emittedBits] at finished + rw [← coreFrame_eq H t e output, ← finished] at raw + have placed := Lift.trace Sum.inl vertexView vertexView_left vertexView_right + Label.vertex (clearEntry 0) vertexStates + (((((), false), none) : MetaState), MachineRegularFamily.readyState H) + (frame (familyData H t e output)) vertexSource (program H) (fun _ => rfl) _ _ _ raw + simpa only [Lift.configuration, MachineCloudPadding.Placement.label, vertexPlacement, + emittedData_eq, cfg, readyState, vertexStates, Equiv.prodAssoc_symm_apply, + vertexSteps, emittedBits, id_eq] using placed + +noncomputable def totalSteps (H : BaseTable) (t : GraphTables.Table) (e : Fin t.darts) + (output : List Bool) : Nat := + MachineRegularMetadata.totalTime t e + familySteps H t e output + vertexSteps H t e output + + clearSteps (frame (emittedData H t e output)) 7 + +theorem originalTrace (H : BaseTable) (t : GraphTables.Table) (e : Fin t.darts) + (output : List Bool) : + (advance (TM2.step (program H)))^[totalSteps H t e output] + (some (cfg H (some entry) (initialData t e output))) = + some (cfg H none (initialData t e (output ++ emittedBits H t e))) := by + have metadata := metadataTrace H t e output + have family := familyTrace H t e output + have vertex := vertexTrace H t e output + have cleanup := clearTrace H (frame (emittedData H t e output)) + have final : clearMemory (frame (emittedData H t e output)) 7 = + frame (initialData t e (output ++ emittedBits H t e)) := by + rw [clearFrame] + rfl + rw [final] at cleanup + exact joinTrace (joinTrace (joinTrace metadata family) vertex) cleanup + +noncomputable def originalExecution (H : BaseTable) (t : GraphTables.Table) (e : Fin t.darts) + (output : List Bool) : + StateTransition.EvalsToInTime (TM2.step (program H)) + (cfg H (some entry) (initialData t e output)) + (some (cfg H none (initialData t e (output ++ emittedBits H t e)))) + (totalSteps H t e output) where + steps := totalSteps H t e output + evals_in_steps := originalTrace H t e output + steps_le_m := le_rfl + +end MinUncutGames.Foundations.Complexity.MachineRegularOriginalBody + +namespace MinUncutGames.Foundations.Complexity.MachineRegularOwnerCleanup + +open Turing MachineComposition + +variable {LabelType : Type} + +abbrev Tape := MachineRegularOriginalBody.Tape ⊕ Fin 2 +abbrev State := MachineRegularOriginalBody.State × Option Bool +abbrev Alphabet (_ : Tape) := Bool + +def sumDecidableEq {A B : Type} (left : DecidableEq A) (right : DecidableEq B) : + DecidableEq (A ⊕ B) + | .inl a, .inl b => match left a b with + | .isTrue h => .isTrue (congrArg (Sum.inl : A → A ⊕ B) h) + | .isFalse h => .isFalse (fun e => h (Sum.inl.inj e)) + | .inr a, .inr b => match right a b with + | .isTrue h => .isTrue (congrArg (Sum.inr : B → A ⊕ B) h) + | .isFalse h => .isFalse (fun e => h (Sum.inr.inj e)) + | .inl _, .inr _ => .isFalse (by intro h; cases h) + | .inr _, .inl _ => .isFalse (by intro h; cases h) + +instance tapeDecidableEq : DecidableEq Tape := + sumDecidableEq + (sumDecidableEq (inferInstanceAs (DecidableEq (Fin 27))) + (sumDecidableEq (inferInstanceAs (DecidableEq MachineRegularMetadata.Extra)) + (sumDecidableEq + (sumDecidableEq + (sumDecidableEq (inferInstanceAs (DecidableEq MachineExpanderRow.Tape)) + (inferInstanceAs (DecidableEq MachineExpanderTable.ExtraTape))) + (inferInstanceAs (DecidableEq MachineExpanderFamily.ExtraTape))) + (inferInstanceAs (DecidableEq MachineCeilingPower.Tape))))) + (inferInstanceAs (DecidableEq (Fin 2))) + +instance tapeBEq : BEq Tape where + beq a b := decide (a = b) + +instance tapeLawfulBEq : LawfulBEq Tape where + eq_of_beq := of_decide_eq_true + rfl := of_decide_eq_self_eq_true _ + +instance tapeFintype : Fintype Tape := by + change Fintype + ((Fin 27 ⊕ (MachineRegularMetadata.Extra ⊕ + (((MachineExpanderRow.Tape ⊕ MachineExpanderTable.ExtraTape) ⊕ + MachineExpanderFamily.ExtraTape) ⊕ MachineCeilingPower.Tape))) ⊕ Fin 2) + infer_instance + +def core (k : Fin 27) : Tape := .inl (.inl k) +def localRank : Tape := core 3 +def count : Tape := core 4 +def prefixTape : Tape := core 5 +def rotor : Tape := core 7 +def padding : Tape := .inl (.inr (.inl .padding)) +def level : Tape := .inl (.inr (.inl .level)) +def dummyFuel : Tape := .inr 0 +def scratch : Tape := .inr 1 + +def cleanupTapes : List Tape := [localRank, count, rotor, padding, level, dummyFuel] + +inductive Label + | scan + | restore + | drain (l : MachineDrainMany.Label cleanupTapes) + deriving DecidableEq, Fintype + +def entry : Label := .scan + +def cleanupEntry (labels : Label → LabelType) (exit : Option LabelType) : Option LabelType := + MachineDrainMany.entry cleanupTapes (fun l => labels (.drain l)) exit + +def instruction (labels : Label → LabelType) (exit : Option LabelType) : + Label → TM2.Stmt Alphabet LabelType State + | .scan => MachineUnaryAffineAt.scan padding scratch prefixTape 1 + (labels .scan) (labels .restore) + | .restore => Reduction.MachineTransfer.loopAt scratch padding id false + (labels .restore) (cleanupEntry labels exit) + | .drain l => MachineDrainMany.instruction cleanupTapes + (fun l => labels (.drain l)) exit l + +def afterAddition (base : Tape → List Bool) (d o : Nat) : Tape → List Bool := + Function.update base prefixTape (encodeWord (d + o)) + +def finalTapes (base : Tape → List Bool) (d o : Nat) : Tape → List Bool := + MachineDrainMany.finalTapes cleanupTapes (afterAddition base d o) + +def steps (base : Tape → List Bool) (d : Nat) : Nat := + 2 * (d + 1) + (cleanupTapes.map (fun k => (base k).length + 1)).sum + +theorem finalTapes_apply (base : Tape → List Bool) (d o : Nat) (k : Tape) : + finalTapes base d o k = + if k ∈ cleanupTapes then [] + else if k = prefixTape then encodeWord (d + o) else base k := by + simp only [finalTapes, MachineDrainMany.finalTapes_apply, afterAddition, + Function.update_apply] + +@[simp] theorem finalTapes_prefix (base : Tape → List Bool) (d o : Nat) : + finalTapes base d o prefixTape = encodeWord (d + o) := by + simp [finalTapes_apply, cleanupTapes, prefixTape, localRank, count, rotor, + padding, level, dummyFuel, core] + +theorem finalTapes_empty (base : Tape → List Bool) (d o : Nat) (k : Tape) + (hk : k ∈ cleanupTapes) : finalTapes base d o k = [] := by + rw [finalTapes_apply, ite_eq_left hk] + +theorem finalTapes_other (base : Tape → List Bool) (d o : Nat) (k : Tape) + (hk : k ∉ cleanupTapes) (hp : k ≠ prefixTape) : + finalTapes base d o k = base k := by + rw [finalTapes_apply, ite_eq_right hk, ite_eq_right hp] + +@[simp] theorem finalTapes_scratch (base : Tape → List Bool) (d o : Nat) : + finalTapes base d o scratch = base scratch := by + apply finalTapes_other + · simp [cleanupTapes, scratch, localRank, count, rotor, padding, level, dummyFuel, core] + · decide + +theorem drainSteps_eq (base : Tape → List Bool) (d o : Nat) : + MachineDrainMany.steps cleanupTapes (afterAddition base d o) = + (cleanupTapes.map (fun k => (base k).length + 1)).sum := by + simp [MachineDrainMany.steps, cleanupTapes, afterAddition, prefixTape, + localRank, count, rotor, padding, level, dummyFuel, core] + +theorem additionTraceAt (labels : Label → LabelType) (exit : Option LabelType) + (program : LabelType → TM2.Stmt Alphabet LabelType State) + (code : ∀ l, program (labels l) = instruction labels exit l) + (base : Tape → List Bool) (d o : Nat) + (paddingWord : base padding = encodeWord d) + (prefixWord : base prefixTape = encodeWord o) + (scratchEmpty : base scratch = []) + (ambient : MachineRegularOriginalBody.State) (register : Option Bool) : + (advance (TM2.step program))^[2 * (d + 1)] + (some ⟨some (labels entry), (ambient, register), base⟩) = + some ⟨cleanupEntry labels exit, (ambient, none), afterAddition base d o⟩ := by + have frame (word : List Bool) : + MachineUnaryAffineAt.tapes padding scratch prefixTape base (encodeWord d) [] word = + Function.update base prefixTape word := by + rw [← paddingWord, ← scratchEmpty] + simp only [MachineUnaryAffineAt.tapes, MachineCopy.forkTapes, Function.update_eq_self] + have initial : MachineUnaryAffineAt.tapes padding scratch prefixTape base + (encodeWord d) [] (encodeWord o) = base := by + rw [frame, ← prefixWord, Function.update_eq_self] + have run := MachineUnaryAffineAt.affineTrace padding scratch prefixTape + (by decide) (by decide) (by decide) 1 (labels .scan) (labels .restore) + (cleanupEntry labels exit) program (code .scan) (code .restore) + base d o [] [] ambient register + simpa only [List.append_nil, Nat.one_mul, initial, frame, entry, afterAddition] using run + +theorem traceAt (labels : Label → LabelType) (exit : Option LabelType) + (program : LabelType → TM2.Stmt Alphabet LabelType State) + (code : ∀ l, program (labels l) = instruction labels exit l) + (base : Tape → List Bool) (d o : Nat) + (paddingWord : base padding = encodeWord d) + (prefixWord : base prefixTape = encodeWord o) + (scratchEmpty : base scratch = []) + (ambient : MachineRegularOriginalBody.State) (register : Option Bool) : + (advance (TM2.step program))^[steps base d] + (some ⟨some (labels entry), (ambient, register), base⟩) = + some ⟨exit, (ambient, none), finalTapes base d o⟩ := by + have first := additionTraceAt labels exit program code base d o + paddingWord prefixWord scratchEmpty ambient register + have second := MachineDrainMany.trace cleanupTapes (fun l => labels (.drain l)) exit + program (fun l => code (.drain l)) (afterAddition base d o) ambient none + simp only [MachineDrainMany.finalRegister_none, drainSteps_eq] at second + unfold steps + rw [Nat.add_comm, Function.iterate_add_apply, first] + exact second + +def executionAt (labels : Label → LabelType) (exit : Option LabelType) + (program : LabelType → TM2.Stmt Alphabet LabelType State) + (code : ∀ l, program (labels l) = instruction labels exit l) + (base : Tape → List Bool) (d o : Nat) + (paddingWord : base padding = encodeWord d) + (prefixWord : base prefixTape = encodeWord o) + (scratchEmpty : base scratch = []) + (ambient : MachineRegularOriginalBody.State) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels entry), (ambient, register), base⟩ + (some ⟨exit, (ambient, none), finalTapes base d o⟩) (steps base d) where + steps := steps base d + evals_in_steps := traceAt labels exit program code base d o + paddingWord prefixWord scratchEmpty ambient register + steps_le_m := Nat.le_refl _ + +end MinUncutGames.Foundations.Complexity.MachineRegularOwnerCleanup + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineRegularOwnerProgram.lean b/lean/OAI/Computability/MinUncut/Machines/MachineRegularOwnerProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..ebd76a659583d1467bee588437cdeaa451b5ed0c --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineRegularOwnerProgram.lean @@ -0,0 +1,775 @@ +import Mathlib +import OAI.Computability.MinUncut.Encoding.FormulaEncoding +import OAI.Computability.MinUncut.Machines.MachineRegularOriginalBody +import OAI.Computability.MinUncut.PCP.PreprocessingRegularLoopWords + +namespace OAI + +namespace MinUncutGames.Foundations.Complexity.MachineRegularOwnerBody + +open Turing MachineComposition PCP +open PreprocessingCloudIndex PreprocessingRegularTables +open MachineRegularTable +open PreprocessingRegularLoopWords + +abbrev Tape := MachineRegularOriginalBody.Tape ⊕ Fin 2 +abbrev Alphabet (_ : Tape) := Bool +abbrev State := MachineRegularOriginalBody.State × Option Bool +abbrev Data := MachineRegularMetadata.Data +abbrev CoreState := MachineRegularOriginalBody.CoreState +abbrev MetaState := MachineRegularOriginalBody.MetaState +abbrev FamilyState := MachineRegularOriginalBody.FamilyState +abbrev BaseTable := PreprocessingRegularTables.BaseTable + +instance : DecidableEq Tape := MachineRegularOwnerCleanup.tapeDecidableEq +instance : Fintype Tape := MachineRegularOwnerCleanup.tapeFintype + +def core (k : Fin 27) : Tape := .inl (.inl k) +def paddingTape : Tape := .inl (.inr (.inl .padding)) +def levelTape : Tape := .inl (.inr (.inl .level)) +def dummyFuel : Tape := .inr 0 +def scratch : Tape := .inr 1 + +def readyState (H : BaseTable) : State := (MachineRegularOriginalBody.readyState H, none) + +def metadataTape (k : MachineRegularMetadata.Tape) : Tape := + .inl (MachineRegularOriginalBody.metadataTape k) + +def metadataView : Tape → Option MachineRegularMetadata.Tape + | .inl k => MachineRegularOriginalBody.metadataView k + | .inr _ => none + +def familyTape (k : MachineRegularFamily.Tape) : Tape := + .inl (MachineRegularOriginalBody.familyTape k) + +def familyView : Tape → Option MachineRegularFamily.Tape + | .inl k => MachineRegularOriginalBody.familyView k + | .inr _ => none + +def vertexView : Tape → Option (Fin 27) + | .inl k => MachineRegularOriginalBody.vertexView k + | .inr _ => none + +theorem metadataView_left (k : MachineRegularMetadata.Tape) : + metadataView (metadataTape k) = some k := MachineRegularOriginalBody.metadataView_left k + +theorem metadataView_right (j : Tape) (k : MachineRegularMetadata.Tape) + (h : metadataView j = some k) : metadataTape k = j := by + cases j with + | inl j => exact congrArg Sum.inl (MachineRegularOriginalBody.metadataView_right j k h) + | inr j => cases h + +theorem familyView_left (k : MachineRegularFamily.Tape) : + familyView (familyTape k) = some k := MachineRegularOriginalBody.familyView_left k + +theorem familyView_right (j : Tape) (k : MachineRegularFamily.Tape) + (h : familyView j = some k) : familyTape k = j := by + cases j with + | inl j => exact congrArg Sum.inl (MachineRegularOriginalBody.familyView_right j k h) + | inr j => cases h + +theorem vertexView_left (k : Fin 27) : vertexView (core k) = some k := rfl + +theorem vertexView_right (j : Tape) (k : Fin 27) + (h : vertexView j = some k) : core k = j := by + cases j with + | inl j => exact congrArg Sum.inl (MachineRegularOriginalBody.vertexView_right j k h) + | inr j => cases h + +def metadataStates : (MetaState × ((CoreState × FamilyState) × Option Bool)) ≃ State where + toFun p := (((p.2.1.1, p.1), p.2.1.2), p.2.2) + invFun p := (p.1.1.2, ((p.1.1.1, p.1.2), p.2)) + left_inv _ := rfl + right_inv _ := rfl + +def familyStates : (FamilyState × ((CoreState × MetaState) × Option Bool)) ≃ State where + toFun p := ((p.2.1, p.1), p.2.2) + invFun p := (p.1.2, (p.1.1, p.2)) + left_inv _ := rfl + right_inv _ := rfl + +def vertexStates : (CoreState × ((MetaState × FamilyState) × Option Bool)) ≃ State where + toFun p := (((p.1, p.2.1.1), p.2.1.2), p.2.2) + invFun p := (p.1.1.1, ((p.1.1.2, p.1.2), p.2)) + left_inv _ := rfl + right_inv _ := rfl + +inductive Label + | metadata (l : MachineRegularMetadata.Label) + | copyCount (l : MachineUnaryAffineAt.Label) + | copyFuel (l : MachineUnaryAffineAt.Label) + | guard + | family (l : MachineRegularFamily.Label) + | loop + | vertex (l : MachineRegularVertexBlock.Label internalDegree) + | bump + | cleanup (l : MachineRegularOwnerCleanup.Label) + deriving DecidableEq, Fintype + +def entry : Label := .metadata (.cloud .init) + +def program (H : BaseTable) : Label → TM2.Stmt Alphabet Label State + | .metadata l => Lift.statement metadataTape Label.metadata (some (.copyCount .seed)) + metadataStates (MachineRegularMetadata.program l) + | .copyCount .seed => MachineUnaryAffineAt.seed (core 3) 0 (.copyCount .scan) + | .copyCount .scan => MachineUnaryAffineAt.scan (core 4) scratch (core 3) 1 + (.copyCount .scan) (.copyCount .restore) + | .copyCount .restore => Reduction.MachineTransfer.loopAt scratch (core 4) id false + (.copyCount .restore) (some (.copyFuel .seed)) + | .copyFuel .seed => MachineUnaryAffineAt.seed dummyFuel 0 (.copyFuel .scan) + | .copyFuel .scan => MachineUnaryAffineAt.scan paddingTape scratch dummyFuel 1 + (.copyFuel .scan) (.copyFuel .restore) + | .copyFuel .restore => Reduction.MachineTransfer.loopAt scratch paddingTape id false + (.copyFuel .restore) (some .guard) + | .guard => .peek dummyFuel (fun state head => (state.1, head)) + (.branch (fun state => state.2.getD false) + (.load (fun state => (state.1, none)) (.goto fun _ => .family .start)) + (.load (fun state => (state.1, none)) + (.goto fun _ => .cleanup MachineRegularOwnerCleanup.entry))) + | .family l => Lift.statement familyTape Label.family (some .loop) + familyStates (MachineRegularFamily.program H l) + | .loop => .peek dummyFuel (fun state head => (state.1, head)) + (.branch (fun state => state.2.getD false) + (.pop dummyFuel (fun state _ => (state.1, none)) + (.goto fun _ => .vertex (MachineRegularVertexBlock.dummyEntry internalDegree + MachineRegularOriginalBody.degree_positive))) + (.load (fun state => (state.1, none)) + (.goto fun _ => .cleanup MachineRegularOwnerCleanup.entry))) + | .vertex l => Lift.statement core Label.vertex (some .bump) + vertexStates (MachineRegularOriginalBody.vertexSource l) + | .bump => .push (core 1) (fun _ => true) + (.push (core 3) (fun _ => true) (.goto fun _ => .loop)) + | .cleanup l => MachineRegularOwnerCleanup.instruction Label.cleanup none l + +def working (data : Data) (fuel saved : List Bool) : Tape → List Bool + | .inl k => MachineRegularOriginalBody.frame data k + | .inr i => if i = 0 then fuel else saved + +def frame (data : Data) : Tape → List Bool := working data [] [] + +def cfg (H : BaseTable) (label : Option Label) (data : Data) : TM2.Cfg Alphabet Label State := + ⟨label, readyState H, frame data⟩ + +def initialData (t : GraphTables.Table) (v : Fin t.vertices) (output : List Bool) : Data where + table := GraphTables.tableBits t + globalIndex := encodeWord (t.darts + PreprocessingPaddingOffsets.offset (padding t) v.val) + owner := encodeWord v.val + localRank := [] + count := [] + offset := encodeWord (PreprocessingPaddingOffsets.offset (padding t) v.val) + darts := encodeWord t.darts + rotor := [] + output := output + padding := [] + level := [] + +def metadataData (t : GraphTables.Table) (v : Fin t.vertices) (output : List Bool) : Data := + MachineRegularMetadata.cloudData t v (initialData t v output) + +def seededData (t : GraphTables.Table) (v : Fin t.vertices) (output : List Bool) : Data := + { metadataData t v output with localRank := encodeWord (cloudSize t v) } + +def ownerBits (H : BaseTable) (t : GraphTables.Table) (v : Fin t.vertices) : List Bool := + (List.ofFn (PreprocessingRegularWords.dummyVertexBits t (padding t) (familyCloudTable H t) v)).flatten + +def finalData (H : BaseTable) (t : GraphTables.Table) (v : Fin t.vertices) + (output : List Bool) : Data := + { initialData t v output with + globalIndex := encodeWord (t.darts + PreprocessingPaddingOffsets.offset (padding t) v.val + padding t v) + offset := encodeWord (PreprocessingPaddingOffsets.offset (padding t) v.val + padding t v) + output := output ++ ownerBits H t v } + +open Turing MachineComposition PCP +open PreprocessingCloudIndex PreprocessingRegularTables +open MachineRegularTable PreprocessingRegularLoopWords + +theorem joinTrace {A : Type*} {f : A → A} {m n : Nat} {a b c : A} + (first : f^[m] a = b) (second : f^[n] b = c) : f^[m + n] a = c := by + rw [Nat.add_comm m n, Function.iterate_add_apply, first, second] + +private theorem oneStep {A : Type} {f : A → Option A} {a b : A} + (h : f a = some b) : (advance f)^[1] (some a) = some b := by + simpa only [Function.iterate_one, advance_some] using h + +theorem metadataPlacement (data extra : Data) : + MachineCloudPadding.Placement.tapes metadataView (MachineRegularMetadata.frame data) + (frame extra) = frame data := by + funext j + cases j with + | inl j => cases j with + | inl i => rfl + | inr j => cases j <;> rfl + | inr i => rfl + +theorem metadataTrace (H : BaseTable) (t : GraphTables.Table) (v : Fin t.vertices) + (output : List Bool) : + (advance (TM2.step (program H)))^[MachineCloudPadding.totalTime t v] + (some (cfg H (some entry) (initialData t v output))) = + some (cfg H (some (.copyCount .seed)) (metadataData t v output)) := by + have raw := MachineRegularMetadata.cloudTrace t v (initialData t v output) + rfl rfl rfl rfl rfl () none + have placed := Lift.trace metadataTape metadataView metadataView_left metadataView_right + Label.metadata (some (.copyCount .seed)) metadataStates + ((MachineRegularInternalRow.coreInitialState internalDegree + MachineRegularOriginalBody.degree_positive (), MachineRegularFamily.readyState H), none) + (frame (initialData t v output)) MachineRegularMetadata.program (program H) + (fun _ => rfl) _ _ _ raw + simpa only [Lift.configuration, MachineCloudPadding.Placement.label, + metadataPlacement, MachineRegularMetadata.cfg, metadataData, cfg, readyState, + MachineRegularOriginalBody.readyState, metadataStates, Equiv.coe_fn_mk, entry] using placed + +theorem working_update_local (data : Data) (fuel saved word : List Bool) : + Function.update (working data fuel saved) (core 3) word = + working { data with localRank := word } fuel saved := by + funext j + cases j with + | inl j => cases j with + | inl i => fin_cases i <;> + simp [working, core, MachineRegularOriginalBody.frame, MachineRegularMetadata.frame] + | inr j => cases j with + | inl e => cases e <;> + simp [working, core, MachineRegularOriginalBody.frame, MachineRegularMetadata.frame] + | inr e => simp [working, core, MachineRegularOriginalBody.frame] + | inr i => simp [working, core] + +theorem working_update_fuel (data : Data) (fuel saved word : List Bool) : + Function.update (working data fuel saved) dummyFuel word = working data word saved := by + funext j + cases j with + | inl j => simp [working, dummyFuel] + | inr i => fin_cases i <;> simp [working, dummyFuel] + +theorem working_update_global (data : Data) (fuel saved word : List Bool) : + Function.update (working data fuel saved) (core 1) word = + working { data with globalIndex := word } fuel saved := by + funext j + cases j with + | inl j => cases j with + | inl i => fin_cases i <;> + simp [working, core, MachineRegularOriginalBody.frame, MachineRegularMetadata.frame] + | inr j => cases j with + | inl e => cases e <;> + simp [working, core, MachineRegularOriginalBody.frame, MachineRegularMetadata.frame] + | inr e => simp [working, core, MachineRegularOriginalBody.frame] + | inr i => simp [working, core] + +theorem working_update_output (data : Data) (fuel saved word : List Bool) : + Function.update (working data fuel saved) (core 8) word = + working { data with output := word } fuel saved := by + funext j + cases j with + | inl j => cases j with + | inl i => fin_cases i <;> + simp [working, core, MachineRegularOriginalBody.frame, MachineRegularMetadata.frame] + | inr j => cases j with + | inl e => cases e <;> + simp [working, core, MachineRegularOriginalBody.frame, MachineRegularMetadata.frame] + | inr e => simp [working, core, MachineRegularOriginalBody.frame] + | inr i => simp [working, core] + +theorem copyCountTrace (H : BaseTable) (t : GraphTables.Table) (v : Fin t.vertices) + (output : List Bool) : + (advance (TM2.step (program H)))^[2 * (cloudSize t v + 1) + 1] + (some (cfg H (some (.copyCount .seed)) (metadataData t v output))) = + some (cfg H (some (.copyFuel .seed)) (seededData t v output)) := by + have run := MachineUnaryAffineAt.seededAffineTrace (core 4) scratch (core 3) + (by decide) (by decide) (by decide) 1 0 + (.copyCount .seed) (.copyCount .scan) (.copyCount .restore) (some (.copyFuel .seed)) + (program H) rfl rfl rfl (frame (metadataData t v output)) (cloudSize t v) [] + (by simp only [List.append_nil]; rfl) rfl + (MachineRegularOriginalBody.readyState H) none + have hempty : frame (metadataData t v output) (core 3) = [] := rfl + rw [hempty, List.append_nil] at run + simpa only [Nat.one_mul, Nat.add_zero, List.append_nil, cfg, readyState, + frame, working_update_local, seededData] using run + +theorem copyFuelTrace (H : BaseTable) (t : GraphTables.Table) (v : Fin t.vertices) + (output : List Bool) : + (advance (TM2.step (program H)))^[2 * (padding t v + 1) + 1] + (some (cfg H (some (.copyFuel .seed)) (seededData t v output))) = + some ⟨some .guard, readyState H, + working (seededData t v output) (encodeWord (padding t v)) []⟩ := by + have run := MachineUnaryAffineAt.seededAffineTrace paddingTape scratch dummyFuel + (by decide) (by decide) (by decide) 1 0 + (.copyFuel .seed) (.copyFuel .scan) (.copyFuel .restore) (some .guard) + (program H) rfl rfl rfl (frame (seededData t v output)) (padding t v) [] + (by simp only [List.append_nil]; rfl) rfl + (MachineRegularOriginalBody.readyState H) none + have hempty : frame (seededData t v output) dummyFuel = [] := rfl + rw [hempty, List.append_nil] at run + simpa only [Nat.one_mul, Nat.add_zero, List.append_nil, cfg, readyState, + frame, working_update_fuel] using run + +theorem guardZeroStep (H : BaseTable) (data : Data) : + TM2.step (program H) ⟨some .guard, readyState H, working data (encodeWord 0) []⟩ = + some ⟨some (.cleanup MachineRegularOwnerCleanup.entry), readyState H, + working data (encodeWord 0) []⟩ := by + rfl + +theorem guardPositiveStep (H : BaseTable) (data : Data) (d : Nat) (hd : 0 < d) : + TM2.step (program H) ⟨some .guard, readyState H, working data (encodeWord d) []⟩ = + some ⟨some (.family .start), readyState H, working data (encodeWord d) []⟩ := by + cases d with + | zero => omega + | succ d => + simp [TM2.step, program, TM2.stepAux, working, dummyFuel, encodeWord, + List.replicate_succ, readyState] + +def dummyBits (H : BaseTable) (t : GraphTables.Table) (v : Fin t.vertices) : + Fin (padding t v) → List Bool := + PreprocessingRegularWords.dummyVertexBits t (padding t) (familyCloudTable H t) v + +def vertexData (H : BaseTable) (t : GraphTables.Table) (v : Fin t.vertices) + (n : Nat) (output : List Bool) : Data := + { seededData t v output with + globalIndex := encodeWord (t.darts + PreprocessingPaddingOffsets.offset (padding t) v.val + n) + localRank := encodeWord (cloudSize t v + n) + rotor := MachineRegularFamily.rotor H (cloudSize t v) } + +def loopData (H : BaseTable) (t : GraphTables.Table) (v : Fin t.vertices) + (output : List Bool) (n : Nat) : Data := + vertexData H t v n (output ++ blocksPrefix (dummyBits H t v) n) + +def loopFrame (H : BaseTable) (t : GraphTables.Table) (v : Fin t.vertices) + (output : List Bool) (n : Nat) : Tape → List Bool := + working (loopData H t v output n) (encodeWord (padding t v - n)) [] + +def preSteps (t : GraphTables.Table) (v : Fin t.vertices) : Nat := + MachineCloudPadding.totalTime t v + (2 * (cloudSize t v + 1) + 1) + + (2 * (padding t v + 1) + 1) + +def loopSteps (H : BaseTable) (t : GraphTables.Table) (v : Fin t.vertices) + (output : List Bool) : (n : Nat) → n ≤ padding t v → Nat + | 0, _ => 0 + | n + 1, hn => loopSteps H t v output n (by omega) + + (1 + MachineRegularVertexBlock.dummySteps t (padding t) (familyCloudTable H t) + v ⟨n, by omega⟩ (output ++ blocksPrefix (dummyBits H t v) n).length + 1) + +def cleanupCost (H : BaseTable) (t : GraphTables.Table) (v : Fin t.vertices) + (output : List Bool) : Nat := + if padding t v = 0 then + MachineRegularOwnerCleanup.steps (working (seededData t v output) (encodeWord 0) []) (padding t v) + else MachineRegularOwnerCleanup.steps (loopFrame H t v output (padding t v)) (padding t v) + +noncomputable def ownerTime (H : BaseTable) (t : GraphTables.Table) (v : Fin t.vertices) + (output : List Bool) : Nat := + preSteps t v + 1 + (if padding t v = 0 then 0 else + MachineRegularFamily.timePolynomial.eval (encodeWord (cloudSize t v)).length + + loopSteps H t v output (padding t v) le_rfl + 1) + cleanupCost H t v output + +theorem familyPlacement (data : Data) (fuel saved : List Bool) : + MachineCloudPadding.Placement.tapes familyView + (MachineRegularFamily.frame (MachineRegularOriginalBody.coreFrame data)) + (working data fuel saved) = working data fuel saved := by + funext j + cases j with + | inl j => exact congrFun (MachineRegularOriginalBody.familyPlacement data) j + | inr i => rfl + +theorem familyResultPlacement (H : BaseTable) (k : Nat) (data : Data) (fuel saved : List Bool) : + MachineCloudPadding.Placement.tapes familyView + (MachineRegularFamily.frame (MachineRegularFamily.resultCore H k + (MachineRegularOriginalBody.coreFrame data))) + (working data fuel saved) = + working { data with rotor := MachineRegularFamily.rotor H k } fuel saved := by + funext j + cases j with + | inl j => exact congrFun (MachineRegularOriginalBody.familyResultPlacement H k data) j + | inr i => rfl + +noncomputable def familyExecution (H : BaseTable) (t : GraphTables.Table) + (v : Fin t.vertices) (output : List Bool) := + MachineRegularFamily.familyCleanInTime H (cloudSize t v) + (MachineRegularOriginalBody.coreFrame (seededData t v output)) rfl rfl + (MachineRegularFamily.readyState H) + +noncomputable def familySteps (H : BaseTable) (t : GraphTables.Table) + (v : Fin t.vertices) (output : List Bool) : Nat := + (familyExecution H t v output).steps + +theorem familyTrace (H : BaseTable) (t : GraphTables.Table) (v : Fin t.vertices) + (output : List Bool) : + (advance (TM2.step (program H)))^[familySteps H t v output] + (some ⟨some (.family .start), readyState H, + working (seededData t v output) (encodeWord (padding t v)) []⟩) = + some ⟨some .loop, readyState H, loopFrame H t v output 0⟩ := by + have raw := (familyExecution H t v output).evals_in_steps + have placed := Lift.trace familyTape familyView familyView_left familyView_right + Label.family (some .loop) familyStates + ((MachineRegularInternalRow.coreInitialState internalDegree + MachineRegularOriginalBody.degree_positive (), ((((), false), none) : MetaState)), none) + (working (seededData t v output) (encodeWord (padding t v)) []) + (MachineRegularFamily.program H) (program H) (fun _ => rfl) _ _ _ raw + simpa only [Lift.configuration, MachineCloudPadding.Placement.label, + familyPlacement, familyResultPlacement, familySteps, readyState, + MachineRegularOriginalBody.readyState, familyStates, Equiv.coe_fn_mk, + loopFrame, loopData, vertexData, blocksPrefix_zero, List.append_nil, Nat.sub_zero, + Nat.add_zero, seededData, metadataData, MachineRegularMetadata.cloudData, + initialData] using placed + +theorem coreFrame_eq (H : BaseTable) (t : GraphTables.Table) (v : Fin t.vertices) + (j : Fin (padding t v)) (output : List Bool) : + MachineRegularOriginalBody.coreFrame (vertexData H t v j.val output) = + MachineRegularInternalRow.coreInputTapes t (padding t) (familyCloudTable H t) + v (paddedNew t (padding t) v j) output := by + have rotor : MachineRegularFamily.rotor H (cloudSize t v) = + encodeWords (ExpanderTableWords.rotationWords (familyCloudTable H t v)) := + PreprocessingFamilyBridge.familyRotor_eq_familyCloudTable H t v + (PreprocessingFamilyBridge.cloudSize_pos_of_dummy t v j) + funext i + fin_cases i <;> + simp [MachineRegularOriginalBody.coreFrame, vertexData, seededData, metadataData, + MachineRegularMetadata.cloudData, MachineRegularMetadata.frame, initialData, + MachineRegularInternalRow.coreInputTapes, MachineRegularInternalRow.coreMemory, + paddedNew, + PreprocessingPaddingOffsets.paddingOrder_val, Nat.add_assoc] + all_goals first | exact rotor | rfl + +theorem vertexPlacement (H : BaseTable) (t : GraphTables.Table) (v : Fin t.vertices) + (n : Nat) (output output' fuel : List Bool) : + MachineCloudPadding.Placement.tapes vertexView + (MachineRegularOriginalBody.coreFrame (vertexData H t v n output')) + (working (vertexData H t v n output) fuel []) = + working (vertexData H t v n output') fuel [] := by + funext j + cases j with + | inl j => cases j with + | inl i => rfl + | inr j => cases j with + | inl e => cases e <;> rfl + | inr e => rfl + | inr i => rfl + +theorem vertexTrace (H : BaseTable) (t : GraphTables.Table) (v : Fin t.vertices) + (j : Fin (padding t v)) (output fuel : List Bool) : + (advance (TM2.step (program H)))^[ + MachineRegularVertexBlock.dummySteps t (padding t) (familyCloudTable H t) v j output.length] + (some ⟨some (.vertex (MachineRegularVertexBlock.dummyEntry internalDegree + MachineRegularOriginalBody.degree_positive)), readyState H, + working (vertexData H t v j.val output) fuel []⟩) = + some ⟨some .bump, readyState H, + working (vertexData H t v j.val (output ++ dummyBits H t v j)) fuel []⟩ := by + have raw := MachineRegularVertexBlock.dummyTraceAt internalDegree + MachineRegularOriginalBody.degree_positive id none MachineRegularOriginalBody.vertexSource + (fun _ => rfl) t (padding t) (familyCloudTable H t) v j output () + have finished := coreFrame_eq H t v j (output ++ dummyBits H t v j) + simp only [dummyBits] at finished + rw [← coreFrame_eq H t v j output, ← finished] at raw + have placed := Lift.trace core vertexView vertexView_left vertexView_right + Label.vertex (some .bump) vertexStates + ((((((), false), none) : MetaState), MachineRegularFamily.readyState H), none) + (working (vertexData H t v j.val output) fuel []) + MachineRegularOriginalBody.vertexSource (program H) (fun _ => rfl) _ _ _ raw + simpa only [Lift.configuration, MachineCloudPadding.Placement.label, vertexPlacement, + readyState, MachineRegularOriginalBody.readyState, vertexStates, Equiv.coe_fn_mk, + dummyBits, id_eq] using placed + +@[simp] theorem working_fuel (data : Data) (fuel saved : List Bool) : + working data fuel saved dummyFuel = fuel := rfl + +@[simp] theorem working_scratch (data : Data) (fuel saved : List Bool) : + working data fuel saved scratch = saved := rfl + +theorem loopPositiveStep (H : BaseTable) (data : Data) (d : Nat) : + TM2.step (program H) ⟨some .loop, readyState H, working data (encodeWord (d + 1)) []⟩ = + some ⟨some (.vertex (MachineRegularVertexBlock.dummyEntry internalDegree + MachineRegularOriginalBody.degree_positive)), readyState H, + working data (encodeWord d) []⟩ := by + change some (TM2.stepAux (program H .loop) _ _) = _ + simp only [program, TM2.stepAux, working_fuel, encodeWord, List.replicate_succ, + List.cons_append, List.head?_cons, Option.getD_some, Bool.cond_true, + List.tail_cons, working_update_fuel] + rfl + +theorem loopZeroStep (H : BaseTable) (data : Data) : + TM2.step (program H) ⟨some .loop, readyState H, working data (encodeWord 0) []⟩ = + some ⟨some (.cleanup MachineRegularOwnerCleanup.entry), readyState H, + working data (encodeWord 0) []⟩ := by rfl + +theorem bumpStep (H : BaseTable) (t : GraphTables.Table) (v : Fin t.vertices) + (n : Nat) (output fuel : List Bool) : + TM2.step (program H) ⟨some .bump, readyState H, working (vertexData H t v n output) fuel []⟩ = + some ⟨some .loop, readyState H, working (vertexData H t v (n + 1) output) fuel []⟩ := by + change some (TM2.stepAux (program H .bump) _ _) = _ + simp only [program, TM2.stepAux, + Function.update_of_ne (by decide : core 3 ≠ core 1), + working_update_global, working_update_local] + congr 2 + +theorem loopPrefixTrace (H : BaseTable) (t : GraphTables.Table) (v : Fin t.vertices) + (output : List Bool) (n : Nat) (hn : n ≤ padding t v) : + (advance (TM2.step (program H)))^[loopSteps H t v output n hn] + (some ⟨some .loop, readyState H, loopFrame H t v output 0⟩) = + some ⟨some .loop, readyState H, loopFrame H t v output n⟩ := by + induction n with + | zero => rfl + | succ n ih => + have h : n < padding t v := by omega + have first := ih (by omega) + have hremaining : padding t v - n = (padding t v - (n + 1)) + 1 := by omega + have guard := loopPositiveStep H (loopData H t v output n) (padding t v - (n + 1)) + rw [← hremaining] at guard + have guardRun : (advance (TM2.step (program H)))^[1] + (some ⟨some .loop, readyState H, loopFrame H t v output n⟩) = + some ⟨some (.vertex (MachineRegularVertexBlock.dummyEntry internalDegree + MachineRegularOriginalBody.degree_positive)), readyState H, + working (loopData H t v output n) (encodeWord (padding t v - (n + 1))) []⟩ := oneStep guard + have vertex := vertexTrace H t v ⟨n, h⟩ + (output ++ blocksPrefix (dummyBits H t v) n) (encodeWord (padding t v - (n + 1))) + have bump := bumpStep H t v n + ((output ++ blocksPrefix (dummyBits H t v) n) ++ dummyBits H t v ⟨n, h⟩) + (encodeWord (padding t v - (n + 1))) + have bumpRun := oneStep bump + have all := joinTrace (joinTrace (joinTrace first guardRun) vertex) bumpRun + simpa only [loopSteps, loopFrame, loopData, blocksPrefix_succ _ n h, + List.append_assoc, Nat.add_assoc] using all + +theorem preparationTrace (H : BaseTable) (t : GraphTables.Table) (v : Fin t.vertices) + (output : List Bool) : + (advance (TM2.step (program H)))^[preSteps t v] + (some (cfg H (some entry) (initialData t v output))) = + some ⟨some .guard, readyState H, + working (seededData t v output) (encodeWord (padding t v)) []⟩ := + joinTrace (joinTrace (metadataTrace H t v output) (copyCountTrace H t v output)) + (copyFuelTrace H t v output) + +theorem cleanupFrame (data : Data) (fuel : List Bool) (d o : Nat) : + MachineRegularOwnerCleanup.finalTapes (working data fuel []) d o = + frame { data with + localRank := [] + count := [] + rotor := [] + padding := [] + level := [] + offset := encodeWord (d + o) } := by + funext j + rw [MachineRegularOwnerCleanup.finalTapes_apply] + cases j with + | inl j => cases j with + | inl i => fin_cases i <;> + simp [MachineRegularOwnerCleanup.cleanupTapes, MachineRegularOwnerCleanup.localRank, + MachineRegularOwnerCleanup.count, MachineRegularOwnerCleanup.rotor, + MachineRegularOwnerCleanup.padding, MachineRegularOwnerCleanup.level, + MachineRegularOwnerCleanup.dummyFuel, MachineRegularOwnerCleanup.prefixTape, + MachineRegularOwnerCleanup.core, frame, working, MachineRegularOriginalBody.frame, + MachineRegularMetadata.frame] + | inr j => cases j with + | inl e => cases e <;> + simp [MachineRegularOwnerCleanup.cleanupTapes, MachineRegularOwnerCleanup.localRank, + MachineRegularOwnerCleanup.count, MachineRegularOwnerCleanup.rotor, + MachineRegularOwnerCleanup.padding, MachineRegularOwnerCleanup.level, + MachineRegularOwnerCleanup.dummyFuel, + MachineRegularOwnerCleanup.core, frame, working, MachineRegularOriginalBody.frame, + MachineRegularMetadata.frame] + | inr e => + simp [MachineRegularOwnerCleanup.cleanupTapes, MachineRegularOwnerCleanup.localRank, + MachineRegularOwnerCleanup.count, MachineRegularOwnerCleanup.rotor, + MachineRegularOwnerCleanup.padding, MachineRegularOwnerCleanup.level, + MachineRegularOwnerCleanup.dummyFuel, MachineRegularOwnerCleanup.prefixTape, + MachineRegularOwnerCleanup.core, frame, working, MachineRegularOriginalBody.frame] + | inr i => fin_cases i <;> + simp [MachineRegularOwnerCleanup.cleanupTapes, MachineRegularOwnerCleanup.localRank, + MachineRegularOwnerCleanup.count, MachineRegularOwnerCleanup.rotor, + MachineRegularOwnerCleanup.padding, MachineRegularOwnerCleanup.level, + MachineRegularOwnerCleanup.dummyFuel, MachineRegularOwnerCleanup.prefixTape, + MachineRegularOwnerCleanup.core, frame, working] + +theorem ownerBits_zero (H : BaseTable) (t : GraphTables.Table) (v : Fin t.vertices) + (hp : padding t v = 0) : ownerBits H t v = [] := by + have hnil : List.ofFn (dummyBits H t v) = [] := by + apply List.length_eq_zero_iff.mp + simpa only [List.length_ofFn] using hp + exact congrArg List.flatten hnil + +theorem cleanupZeroFrame (H : BaseTable) (t : GraphTables.Table) (v : Fin t.vertices) + (output : List Bool) (hp : padding t v = 0) : + MachineRegularOwnerCleanup.finalTapes + (working (seededData t v output) (encodeWord 0) []) (padding t v) + (PreprocessingPaddingOffsets.offset (padding t) v.val) = frame (finalData H t v output) := by + rw [cleanupFrame] + apply congrArg frame + simp only [seededData, metadataData, MachineRegularMetadata.cloudData, initialData, + finalData, hp, ownerBits_zero H t v hp, List.append_nil, Nat.add_zero, Nat.zero_add] + +theorem cleanupLoopFrame (H : BaseTable) (t : GraphTables.Table) (v : Fin t.vertices) + (output : List Bool) : + MachineRegularOwnerCleanup.finalTapes (loopFrame H t v output (padding t v)) + (padding t v) (PreprocessingPaddingOffsets.offset (padding t) v.val) = + frame (finalData H t v output) := by + rw [loopFrame, cleanupFrame] + apply congrArg frame + simp only [loopData, vertexData, seededData, metadataData, MachineRegularMetadata.cloudData, + initialData, finalData, blocksPrefix_all, dummyBits, ownerBits, + Nat.add_comm (padding t v) (PreprocessingPaddingOffsets.offset (padding t) v.val)] + +theorem cleanupZeroTrace (H : BaseTable) (t : GraphTables.Table) (v : Fin t.vertices) + (output : List Bool) (hp : padding t v = 0) : + (advance (TM2.step (program H)))^[MachineRegularOwnerCleanup.steps + (working (seededData t v output) (encodeWord 0) []) (padding t v)] + (some ⟨some (.cleanup MachineRegularOwnerCleanup.entry), readyState H, + working (seededData t v output) (encodeWord 0) []⟩) = + some (cfg H none (finalData H t v output)) := by + have run := MachineRegularOwnerCleanup.traceAt Label.cleanup none (program H) (fun _ => rfl) + (working (seededData t v output) (encodeWord 0) []) (padding t v) + (PreprocessingPaddingOffsets.offset (padding t) v.val) rfl rfl rfl + (MachineRegularOriginalBody.readyState H) none + rw [cleanupZeroFrame H t v output hp] at run + exact run + +theorem cleanupLoopTrace (H : BaseTable) (t : GraphTables.Table) (v : Fin t.vertices) + (output : List Bool) : + (advance (TM2.step (program H)))^[MachineRegularOwnerCleanup.steps + (loopFrame H t v output (padding t v)) (padding t v)] + (some ⟨some (.cleanup MachineRegularOwnerCleanup.entry), readyState H, + loopFrame H t v output (padding t v)⟩) = + some (cfg H none (finalData H t v output)) := by + have run := MachineRegularOwnerCleanup.traceAt Label.cleanup none (program H) (fun _ => rfl) + (loopFrame H t v output (padding t v)) (padding t v) + (PreprocessingPaddingOffsets.offset (padding t) v.val) rfl rfl rfl + (MachineRegularOriginalBody.readyState H) none + rw [cleanupLoopFrame] at run + exact run + +theorem loopTrace (H : BaseTable) (t : GraphTables.Table) (v : Fin t.vertices) + (output : List Bool) : + (advance (TM2.step (program H)))^[loopSteps H t v output (padding t v) le_rfl + 1] + (some ⟨some .loop, readyState H, loopFrame H t v output 0⟩) = + some ⟨some (.cleanup MachineRegularOwnerCleanup.entry), readyState H, + loopFrame H t v output (padding t v)⟩ := by + have first := loopPrefixTrace H t v output (padding t v) le_rfl + have last : (advance (TM2.step (program H)))^[1] + (some ⟨some .loop, readyState H, loopFrame H t v output (padding t v)⟩) = + some ⟨some (.cleanup MachineRegularOwnerCleanup.entry), readyState H, + loopFrame H t v output (padding t v)⟩ := by + simpa only [loopFrame, Nat.sub_self] using + oneStep (loopZeroStep H (loopData H t v output (padding t v))) + exact joinTrace first last + +noncomputable def ownerInTime (H : BaseTable) (t : GraphTables.Table) + (v : Fin t.vertices) (output : List Bool) : + StateTransition.EvalsToInTime (TM2.step (program H)) + (cfg H (some entry) (initialData t v output)) + (some (cfg H none (finalData H t v output))) (ownerTime H t v output) := by + have prepared := preparationTrace H t v output + by_cases hp : padding t v = 0 + · have gate : (advance (TM2.step (program H)))^[1] + (some ⟨some .guard, readyState H, + working (seededData t v output) (encodeWord (padding t v)) []⟩) = + some ⟨some (.cleanup MachineRegularOwnerCleanup.entry), readyState H, + working (seededData t v output) (encodeWord 0) []⟩ := by + simpa only [hp] using oneStep (guardZeroStep H (seededData t v output)) + have all := joinTrace (joinTrace prepared gate) (cleanupZeroTrace H t v output hp) + refine { steps := _, evals_in_steps := all, steps_le_m := ?_ } + simp only [ownerTime, cleanupCost, ite_eq_left hp, Nat.add_zero, le_refl] + · have gate : (advance (TM2.step (program H)))^[1] + (some ⟨some .guard, readyState H, + working (seededData t v output) (encodeWord (padding t v)) []⟩) = + some ⟨some (.family .start), readyState H, + working (seededData t v output) (encodeWord (padding t v)) []⟩ := + oneStep (guardPositiveStep H (seededData t v output) (padding t v) (Nat.pos_of_ne_zero hp)) + have all := joinTrace + (joinTrace (joinTrace (joinTrace prepared gate) (familyTrace H t v output)) + (loopTrace H t v output)) (cleanupLoopTrace H t v output) + refine { steps := _, evals_in_steps := all, steps_le_m := ?_ } + have hb : familySteps H t v output ≤ + MachineRegularFamily.timePolynomial.eval (encodeWord (cloudSize t v)).length := + (familyExecution H t v output).steps_le_m + simp only [ownerTime, cleanupCost, ite_eq_right hp] + omega + +noncomputable def totalSteps (H : BaseTable) (t : GraphTables.Table) + (v : Fin t.vertices) (output : List Bool) : Nat := (ownerInTime H t v output).steps + +theorem ownerTrace (H : BaseTable) (t : GraphTables.Table) (v : Fin t.vertices) + (output : List Bool) : + (advance (TM2.step (program H)))^[totalSteps H t v output] + (some (cfg H (some entry) (initialData t v output))) = + some (cfg H none (finalData H t v output)) := (ownerInTime H t v output).evals_in_steps + +theorem totalSteps_le (H : BaseTable) (t : GraphTables.Table) (v : Fin t.vertices) + (output : List Bool) : totalSteps H t v output ≤ ownerTime H t v output := + (ownerInTime H t v output).steps_le_m + +end MinUncutGames.Foundations.Complexity.MachineRegularOwnerBody + +namespace MinUncutGames.Foundations.Complexity + +def naturalWordsEncoding : Computability.Encoding (List Nat) Bool where + encode := encodeWords + decode := decodeWords + decode_encode := decodeWords_encodeWords + +def formulaEncoding : Computability.Encoding Target.Formula Bool where + encode := formulaBits + decode := decodeFormulaBits + decode_encode := decodeFormulaBits_encoded + +def gameEncoding (alphabet : Nat) : Computability.Encoding (Target.Instance alphabet) Bool where + encode := gameBits + decode := decodeGameBits alphabet + decode_encode := decodeGameBits_encoded + +def prefixBitMachine (bit : Bool) : Turing.FinTM2 where + K := Unit + k₀ := () + k₁ := () + Γ _ := Bool + Λ := Unit + main := () + σ := Unit + initialState := () + m _ := .push () (fun _ => bit) .halt + +noncomputable def prefixBitPolyTime (bit : Bool) : + Turing.TM2ComputableInPolyTime (id : List Bool → List Bool) id (bit :: ·) where + tm := prefixBitMachine bit + inputAlphabet := Equiv.refl Bool + outputAlphabet := Equiv.refl Bool + time := 1 + outputsFun bs := { + steps := 1 + evals_in_steps := by + change some (Turing.TM2.stepAux (.push () (fun _ => bit) .halt) () + (fun _ : Unit => bs.map id)) = + some { l := none, var := (), stk := fun _ : Unit => (bit :: bs).map id } + simp [Turing.TM2.stepAux] + funext k + cases k + rfl + steps_le_m := by simp + } + +def enlargePolynomialBound {α β αΓ βΓ : Type} + {ea : α → List αΓ} {eb : β → List βΓ} {f : α → β} + (certificate : Turing.TM2ComputableInPolyTime ea eb f) + (bound : Polynomial Nat) + (larger : ∀ n, certificate.time.eval n ≤ bound.eval n) : + Turing.TM2ComputableInPolyTime ea eb f where + toTM2ComputableAux := certificate.toTM2ComputableAux + time := bound + outputsFun a := { + toEvalsTo := (certificate.outputsFun a).toEvalsTo + steps_le_m := Nat.le_trans (certificate.outputsFun a).steps_le_m (larger _) + } + +def composeMachinePhases {σ : Type} (step : σ → Option σ) + (start intermediate : σ) (finish : Option σ) + (p q : Polynomial Nat) (inputLength : Nat) + (first : StateTransition.EvalsToInTime step start (some intermediate) (p.eval inputLength)) + (second : StateTransition.EvalsToInTime step intermediate finish (q.eval inputLength)) : + StateTransition.EvalsToInTime step start finish ((p + q).eval inputLength) := by + have composed := StateTransition.EvalsToInTime.trans step (p.eval inputLength) + (q.eval inputLength) start intermediate finish first second + simpa only [Polynomial.eval_add, Nat.add_comm] using composed + +open Target + +structure PolynomialGapReduction + (completenessError soundnessError : RationalError) + extends SemanticGapReduction completenessError soundnessError where + computation : Turing.TM2ComputableInPolyTime formulaEncoding.encode + (gameEncoding alphabet).encode reduce + +end MinUncutGames.Foundations.Complexity + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineRegularTableRuntime.lean b/lean/OAI/Computability/MinUncut/Machines/MachineRegularTableRuntime.lean new file mode 100644 index 0000000000000000000000000000000000000000..adac4dee65d0755f9b4c6a0667e3dca911ddbea5 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineRegularTableRuntime.lean @@ -0,0 +1,1092 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineRegularTableTrace +import OAI.Computability.MinUncut.Machines.MachineCanonicalOutput +import OAI.Computability.MinUncut.PCP.PreprocessingStageMaps + +namespace OAI + +section +namespace MinUncutGames.Foundations.Complexity.MachineRegularTableRuntime + +open Turing +open PCP +open MachineRegularTable.Top (Tape Label State coreTape readyState) + + +def rawProgram (H : PreprocessingRegularTables.BaseTable) : + MachineCanonicalOutput.Program Tape Label State where + input := coreTape 0 + output := coreTape 8 + main := .header .init + initial := readyState H + code := MachineRegularTable.Top.program H + +theorem sourceMachine_eq (H : PreprocessingRegularTables.BaseTable) : + MachineCanonicalOutput.sourceMachine (rawProgram H) = + MachineRegularTable.Top.machine H := rfl + +noncomputable def cleanupTapes : List Tape := + (Finset.univ : Finset Tape).toList.filter (fun k => decide (k ≠ coreTape 8)) + +theorem cleanup_complete (H : PreprocessingRegularTables.BaseTable) (k : Tape) : + k ∈ cleanupTapes ↔ k ≠ (rawProgram H).output := by + simp [cleanupTapes, rawProgram] + +noncomputable def terminalRun (H : PreprocessingRegularTables.BaseTable) + (t : GraphTables.Table) : + MachineCanonicalOutput.TerminalRun (rawProgram H) (GraphTables.tableBits t) + (PortTables.inputBits (PreprocessingStageMaps.regular H t)) + (MachineRegularTable.Top.timePolynomial.eval (GraphTables.tableBits t).length) where + state := readyState H + tapes := Function.update + (initList (MachineRegularTable.Top.machine H) (GraphTables.tableBits t)).stk + (coreTape 8) (PortTables.inputBits (PreprocessingStageMaps.regular H t)) + execution := by + simpa only [sourceMachine_eq, FinTM2.Cfg, FinTM2.step, MachineRegularTable.Top.machine, + PreprocessingMachineBounds.inputLength, PreprocessingStageMaps.regular, + PortTables.inputBits] using! + MachineRegularTable.Top.machineInTime H t + output_eq := by exact Function.update_self _ _ _ + +noncomputable def computableInPolyTime (H : PreprocessingRegularTables.BaseTable) : + TM2ComputableInPolyTime GraphTables.tableBits + (PortTables.inputBits (ports := PreprocessingRegularTables.internalDegree + 1)) + (PreprocessingStageMaps.regular H) := + MachineCanonicalOutput.computableInPolyTime (rawProgram H) cleanupTapes + (cleanup_complete H) GraphTables.tableBits PortTables.inputBits + (PreprocessingStageMaps.regular H) MachineRegularTable.Top.timePolynomial (terminalRun H) + +theorem finite_alphabet (H : PreprocessingRegularTables.BaseTable) : + ∀ k, Finite ((computableInPolyTime H).tm.Γ k) := + MachineCanonicalOutput.computableInPolyTime_finite_alphabet (rawProgram H) cleanupTapes + (cleanup_complete H) GraphTables.tableBits PortTables.inputBits + (PreprocessingStageMaps.regular H) MachineRegularTable.Top.timePolynomial (terminalRun H) + +end MinUncutGames.Foundations.Complexity.MachineRegularTableRuntime + +end +section +namespace MinUncutGames.Foundations.Complexity.MachineTableSplit + +open Turing MachineComposition + + +abbrev Tape := Fin 5 +abbrev State (σ : Type) := σ × Option Bool + +inductive Label + | copyFirst | copySecond | startVertices | readVertices | startDarts | readDarts + deriving DecidableEq + +protected abbrev Label.enumList : List Label := [.copyFirst, .copySecond, .startVertices, + .readVertices, .startDarts, .readDarts] + +protected theorem Label.enumList_getElem?_ctorIdx_eq (x : Label) : + Label.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem Label.enumList_nodup : Label.enumList.Nodup := by decide + +instance : Fintype Label where + elems := ⟨Label.enumList, Label.enumList_nodup⟩ + complete x := by cases x <;> decide + +def tapes (original work vertices darts : List Bool) : Tape → List Bool := + fun k => if k = 0 then original else if k = 1 then work + else if k = 3 then vertices else if k = 4 then darts else [] + +def initialTapes (input : List Bool) : Tape → List Bool := tapes input [] [] [] + +def resultTapes (n m : Nat) (rowsBits : List Bool) : Tape → List Bool := + tapes (encodeWords [n, m] ++ rowsBits) rowsBits (encodeWord n) (encodeWord m) + +@[simp] theorem resultTapes_original (n m : Nat) (rowsBits : List Bool) : + resultTapes n m rowsBits 0 = encodeWords [n, m] ++ rowsBits := by + simp [resultTapes, tapes] + +@[simp] theorem resultTapes_work (n m : Nat) (rowsBits : List Bool) : + resultTapes n m rowsBits 1 = rowsBits := by simp [resultTapes, tapes] + +@[simp] theorem resultTapes_scratch (n m : Nat) (rowsBits : List Bool) : + resultTapes n m rowsBits 2 = [] := by simp [resultTapes, tapes] + +@[simp] theorem resultTapes_vertices (n m : Nat) (rowsBits : List Bool) : + resultTapes n m rowsBits 3 = encodeWord n := by simp [resultTapes, tapes] + +@[simp] theorem resultTapes_darts (n m : Nat) (rowsBits : List Bool) : + resultTapes n m rowsBits 4 = encodeWord m := by simp [resultTapes, tapes] + +def program {σ : Type} : Label → TM2.Stmt (fun _ : Tape => Bool) Label (State σ) + | .copyFirst => Reduction.MachineTransfer.loopAt 0 2 id false .copyFirst (some .copySecond) + | .copySecond => MachineCopy.forkLoop 2 0 1 false .copySecond (some .startVertices) + | .startVertices => Hastad.SourceMachine.fieldStart 3 .readVertices + | .readVertices => Hastad.SourceMachine.fieldLoop 1 3 .readVertices (some .startDarts) + | .startDarts => Hastad.SourceMachine.fieldStart 4 .readDarts + | .readDarts => Hastad.SourceMachine.fieldLoop 1 4 .readDarts none + +def exactSteps (n m : Nat) (rowsBits : List Bool) : Nat := + 2 * (encodeWords [n, m] ++ rowsBits).length + n + m + 6 + +theorem splitTrace {σ : Type} (n m : Nat) (rowsBits : List Bool) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step (program (σ := σ))))^[exactSteps n m rowsBits] + (some ⟨some .copyFirst, (ambient, register), + initialTapes (encodeWords [n, m] ++ rowsBits)⟩) = + some ⟨none, (ambient, none), resultTapes n m rowsBits⟩ := by + let word := encodeWords [n, m] ++ rowsBits + let b₀ := initialTapes word + let b₁ := tapes word word [] [] + let b₂ := tapes word (encodeWord m ++ rowsBits) (encodeWord n) [] + let b₃ := resultTapes n m rowsBits + have h₀ : Function.update b₀ (1 : Tape) (b₀ 0 ++ b₀ 1) = b₁ := by + funext k; fin_cases k <;> simp [b₀, b₁, initialTapes, tapes] + have h₁ : Hastad.SourceMachine.fieldTapes (1 : Tape) 3 b₁ + (encodeWord m ++ rowsBits) (encodeWord n ++ b₁ 3) = b₂ := by + funext k; fin_cases k <;> simp [b₁, b₂, tapes, Hastad.SourceMachine.fieldTapes] + have h₂ : Hastad.SourceMachine.fieldTapes (1 : Tape) 4 b₂ + rowsBits (encodeWord m ++ b₂ 4) = b₃ := by + funext k; fin_cases k <;> + simp [b₂, b₃, resultTapes, tapes, word, Hastad.SourceMachine.fieldTapes] + have copy := MachineCopy.copyTrace (0 : Tape) 1 2 + (by decide) (by decide) (by decide) false .copyFirst .copySecond (some .startVertices) + (program (σ := σ)) rfl rfl b₀ (by simp [b₀, initialTapes, tapes]) ambient register + rw [h₀] at copy + have c₀ : (advance (TM2.step (program (σ := σ))))^[2 * (word.length + 1)] + (some ⟨some .copyFirst, (ambient, register), b₀⟩) = + some ⟨some .startVertices, (ambient, none), b₁⟩ := by + simpa only [show b₀ 0 = word by simp [b₀, initialTapes, tapes]] using copy + have scan₁ := (Hastad.SourceMachine.fieldInTime (1 : Tape) 3 (by decide) + .startVertices .readVertices (some .startDarts) (program (σ := σ)) rfl rfl + b₁ n (encodeWord m ++ rowsBits) + (by simp [b₁, tapes, word, encodeWords, List.append_assoc]) ambient none).evals_in_steps + have c₁ : (advance (TM2.step (program (σ := σ))))^[n + 2] + (some ⟨some .startVertices, (ambient, none), b₁⟩) = + some ⟨some .startDarts, (ambient, none), b₂⟩ := by + dsimp only [Hastad.SourceMachine.fieldInTime] at scan₁ + change (advance (TM2.step (program (σ := σ))))^[n + 2] + (some ⟨some .startVertices, (ambient, none), b₁⟩) = + some ⟨some .startDarts, (ambient, none), + Hastad.SourceMachine.fieldTapes (1 : Tape) 3 b₁ (encodeWord m ++ rowsBits) + (encodeWord n ++ b₁ 3)⟩ at scan₁ + simpa only [h₁] using scan₁ + have scan₂ := (Hastad.SourceMachine.fieldInTime (1 : Tape) 4 (by decide) + .startDarts .readDarts none (program (σ := σ)) rfl rfl + b₂ m rowsBits (by simp [b₂, tapes]) ambient none).evals_in_steps + have c₂ : (advance (TM2.step (program (σ := σ))))^[m + 2] + (some ⟨some .startDarts, (ambient, none), b₂⟩) = + some ⟨none, (ambient, none), b₃⟩ := by + dsimp only [Hastad.SourceMachine.fieldInTime] at scan₂ + change (advance (TM2.step (program (σ := σ))))^[m + 2] + (some ⟨some .startDarts, (ambient, none), b₂⟩) = + some ⟨none, (ambient, none), + Hastad.SourceMachine.fieldTapes (1 : Tape) 4 b₂ rowsBits + (encodeWord m ++ b₂ 4)⟩ at scan₂ + simpa only [h₂] using scan₂ + have c₀₁ : (advance (TM2.step (program (σ := σ))))^[(n + 2) + 2 * (word.length + 1)] + (some ⟨some .copyFirst, (ambient, register), b₀⟩) = + some ⟨some .startDarts, (ambient, none), b₂⟩ := by + rw [Function.iterate_add_apply, c₀, c₁] + have c₀₁₂ : (advance (TM2.step (program (σ := σ))))^[(m + 2) + + ((n + 2) + 2 * (word.length + 1))] + (some ⟨some .copyFirst, (ambient, register), b₀⟩) = + some ⟨none, (ambient, none), b₃⟩ := by + rw [Function.iterate_add_apply, c₀₁, c₂] + have count : exactSteps n m rowsBits = (m + 2) + ((n + 2) + 2 * (word.length + 1)) := by + dsimp [exactSteps, word] + omega + rw [count] + exact c₀₁₂ + +noncomputable def timePolynomial : Polynomial Nat := Polynomial.C 4 * Polynomial.X + Polynomial.C 6 + +@[simp] theorem timePolynomial_eval (length : Nat) : + timePolynomial.eval length = 4 * length + 6 := by simp [timePolynomial] + +theorem exactSteps_le (n m : Nat) (rowsBits : List Bool) : + exactSteps n m rowsBits ≤ timePolynomial.eval (encodeWords [n, m] ++ rowsBits).length := by + rw [timePolynomial_eval] + simp only [exactSteps, List.length_append, encodeWords_length, List.sum_cons, + List.sum_nil, List.length_cons, List.length_nil] + omega + +def splitInTime {σ : Type} (n m : Nat) (rowsBits : List Bool) + (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step (program (σ := σ))) + ⟨some .copyFirst, (ambient, register), initialTapes (encodeWords [n, m] ++ rowsBits)⟩ + (some ⟨none, (ambient, none), resultTapes n m rowsBits⟩) + (timePolynomial.eval (encodeWords [n, m] ++ rowsBits).length) where + steps := exactSteps n m rowsBits + evals_in_steps := splitTrace n m rowsBits ambient register + steps_le_m := exactSteps_le n m rowsBits + +def machine : FinTM2 where + K := Tape + k₀ := 0 + k₁ := 1 + Γ _ := Bool + Λ := Label + main := .copyFirst + σ := State Unit + initialState := ((), none) + m := program + +theorem initial_configuration (input : List Bool) : + initList machine input = ⟨some .copyFirst, ((), none), initialTapes input⟩ := by + have ht : (initList machine input).stk = initialTapes input := by + let : Fintype machine.K := (inferInstance : Fintype Tape) + funext k + fin_cases k <;> simp [initList, machine, initialTapes, tapes] + rfl + exact congrArg (TM2.Cfg.mk _ _) ht + +def rowsBits (table : PCP.GraphTables.Table) : List Bool := + encodeWords ((PCP.GraphTables.rowList table).flatMap PCP.GraphTables.rowWords) + +theorem tableBits_header_rows (table : PCP.GraphTables.Table) : + PCP.GraphTables.tableBits table = encodeWords [table.vertices, table.darts] ++ rowsBits table := by + simp only [PCP.GraphTables.tableBits, PCP.GraphTables.tableWords, encodeWords_append, rowsBits] + +theorem tableTrace {σ : Type} (table : PCP.GraphTables.Table) (ambient : σ) + (register : Option Bool) : + (advance (TM2.step (program (σ := σ))))^[exactSteps table.vertices table.darts (rowsBits table)] + (some ⟨some .copyFirst, (ambient, register), initialTapes (PCP.GraphTables.tableBits table)⟩) = + some ⟨none, (ambient, none), resultTapes table.vertices table.darts (rowsBits table)⟩ := by + rw [tableBits_header_rows] + exact splitTrace table.vertices table.darts (rowsBits table) ambient register + +def initializedTableInTime (table : PCP.GraphTables.Table) : + StateTransition.EvalsToInTime machine.step (initList machine (PCP.GraphTables.tableBits table)) + (some ⟨none, ((), none), resultTapes table.vertices table.darts (rowsBits table)⟩) + (timePolynomial.eval (PCP.GraphTables.tableBits table).length) := by + rw [initial_configuration, tableBits_header_rows] + exact splitInTime table.vertices table.darts (rowsBits table) () none + +end MinUncutGames.Foundations.Complexity.MachineTableSplit + +end +section +namespace MinUncutGames.Foundations.Complexity.MachinePaddingBounds + +theorem rowsBits_length_le (v e count : Nat) : + (MachineDummyRows.rowsBits v e count).length ≤ count * (v + e + count + 8194) := by + induction count generalizing e with + | zero => simp [MachineDummyRows.rowsBits] + | succ count ih => + have hi := ih (e + 1) + have hb : v + (e + 1) + count + 8194 = v + e + (count + 1) + 8194 := by omega + rw [hb] at hi + have hr : v + e + 8194 ≤ v + e + (count + 1) + 8194 := by omega + simp only [MachineDummyRows.rowsBits, List.length_append, MachineDummyRows.rowBits_length] + calc + _ ≤ (v + e + (count + 1) + 8194) + + count * (v + e + (count + 1) + 8194) := Nat.add_le_add hr hi + _ = _ := by rw [Nat.add_mul, Nat.one_mul]; omega + +def rowBound (d v e count : Nat) : Nat := v + count + e + (count + 1) * d + 8194 + +theorem rowBound_next (d v e count : Nat) : + rowBound d (v + 1) (e + d) count = rowBound d v e (count + 1) := by + simp only [rowBound, Nat.add_mul, Nat.one_mul] + omega + +theorem blockRow_le_rowBound (d v e count : Nat) : + v + e + d + 8194 ≤ rowBound d v e (count + 1) := by + simp only [rowBound, Nat.add_mul, Nat.one_mul] + omega + +theorem steps_le_bound (d v e : Nat) (output : List Bool) (count : Nat) : + MachinePaddingRows.steps d v e output count ≤ + count * (d * (4 * rowBound d v e count + + 2 * (output.length + count * d * rowBound d v e count) + 10) + 2) + 1 := by + induction count generalizing v e output with + | zero => simp [MachinePaddingRows.steps] + | succ count ih => + let B := rowBound d v e (count + 1) + let C := d * (4 * B + 2 * (output.length + (count + 1) * d * B) + 10) + 2 + have hb : rowBound d (v + 1) (e + d) count = B := rowBound_next d v e count + have hr : v + e + d + 8194 ≤ B := blockRow_le_rowBound d v e count + have hlen : (MachineDummyRows.rowsBits v e d).length ≤ d * B := + (rowsBits_length_le v e d).trans (Nat.mul_le_mul_left d hr) + have hout : (output ++ MachineDummyRows.rowsBits v e d).length + count * d * B ≤ + output.length + (count + 1) * d * B := by + rw [List.length_append] + calc + _ ≤ output.length + d * B + count * d * B := + Nat.add_le_add_right (Nat.add_le_add_left hlen output.length) _ + _ = _ := by simp only [Nat.add_mul, Nat.one_mul]; omega + have hi := ih (v + 1) (e + d) (output ++ MachineDummyRows.rowsBits v e d) + rw [hb] at hi + have hconstant : + d * (4 * B + 2 * ((output ++ MachineDummyRows.rowsBits v e d).length + + count * d * B) + 10) + 2 ≤ C := by + exact Nat.add_le_add_right (Nat.mul_le_mul_left d + (Nat.add_le_add_right (Nat.add_le_add_left (Nat.mul_le_mul_left 2 hout) (4 * B)) 10)) 2 + have hremaining := hi.trans + (Nat.add_le_add_right (Nat.mul_le_mul_left count hconstant) 1) + have hcount : d * B ≤ (count + 1) * d * B := by + simpa only [Nat.one_mul, Nat.mul_assoc] using + Nat.mul_le_mul_right (d * B) (Nat.succ_le_succ (Nat.zero_le count)) + have hbodyOutput : output.length + d * (v + e + d + 8194) ≤ + output.length + (count + 1) * d * B := + Nat.add_le_add_left ((Nat.mul_le_mul_left d hr).trans hcount) output.length + have hbodyInner : 4 * (v + e + d + 8194) + + 2 * (output.length + d * (v + e + d + 8194)) + 10 ≤ + 4 * B + 2 * (output.length + (count + 1) * d * B) + 10 := by + exact Nat.add_le_add_right (Nat.add_le_add (Nat.mul_le_mul_left 4 hr) + (Nat.mul_le_mul_left 2 hbodyOutput)) 10 + have hbody : MachineDummyRows.steps v e output d + 2 ≤ C := + Nat.add_le_add_right ((MachineDummyRows.steps_le_bound v e output d).trans + (Nat.mul_le_mul_left d hbodyInner)) 2 + change (MachineDummyRows.steps v e output d + 2) + + MachinePaddingRows.steps d (v + 1) (e + d) + (output ++ MachineDummyRows.rowsBits v e d) count ≤ (count + 1) * C + 1 + calc + _ ≤ C + (count * C + 1) := Nat.add_le_add hbody hremaining + _ = _ := by rw [Nat.add_mul, Nat.one_mul]; omega + +def inputSize (v e count : Nat) (output : List Bool) : Nat := + (encodeWord v).length + (encodeWord e).length + (encodeWord count).length + output.length + +def rowCap (d size : Nat) : Nat := size + (size + 1) * d + 8194 + +theorem rowBound_le_cap (d v e count : Nat) (output : List Bool) : + rowBound d v e count ≤ rowCap d (inputSize v e count output) := by + have hbase : v + e + count ≤ inputSize v e count output := by + simp only [inputSize, encodeWord_length] + omega + have hcount : count ≤ inputSize v e count output := by + simp only [inputSize, encodeWord_length] + omega + have hmul := Nat.mul_le_mul_right d (Nat.succ_le_succ hcount) + have h := Nat.add_le_add_right (Nat.add_le_add hbase hmul) 8194 + simpa only [rowBound, rowCap, Nat.succ_eq_add_one, Nat.add_assoc, + Nat.add_comm, Nat.add_left_comm] using h + +noncomputable def rowPolynomial (d : Nat) : Polynomial Nat := + Polynomial.X + (Polynomial.X + 1) * Polynomial.C d + Polynomial.C 8194 + +noncomputable def timePolynomial (d : Nat) : Polynomial Nat := + Polynomial.X * (Polynomial.C d * + (Polynomial.C 4 * rowPolynomial d + + Polynomial.C 2 * (Polynomial.X + Polynomial.X * Polynomial.C d * rowPolynomial d) + + Polynomial.C 10) + Polynomial.C 2) + 1 + +theorem timePolynomial_bounds (d v e count : Nat) (output : List Bool) : + MachinePaddingRows.steps d v e output count ≤ + (timePolynomial d).eval (inputSize v e count output) := by + have hc : count ≤ inputSize v e count output := by + simp only [inputSize, encodeWord_length] + omega + have ho : output.length ≤ inputSize v e count output := by + simp only [inputSize, encodeWord_length] + omega + have hb := rowBound_le_cap d v e count output + have hp := Nat.mul_le_mul (Nat.mul_le_mul_right d hc) hb + have hout := Nat.add_le_add ho hp + have hinner := Nat.add_le_add_right + (Nat.add_le_add (Nat.mul_le_mul_left 4 hb) (Nat.mul_le_mul_left 2 hout)) 10 + have hbody := Nat.add_le_add_right (Nat.mul_le_mul_left d hinner) 2 + have h := (steps_le_bound d v e output count).trans + (Nat.add_le_add_right (Nat.mul_le_mul hc hbody) 1) + simpa only [timePolynomial, rowPolynomial, rowCap, Polynomial.eval_add, + Polynomial.eval_mul, Polynomial.eval_C, Polynomial.eval_X, Polynomial.eval_one] using h + +end MinUncutGames.Foundations.Complexity.MachinePaddingBounds + +end +section +namespace MinUncutGames.Foundations.Complexity.MachinePaddingCertificate + +open MachinePaddingRows + +noncomputable def timePolynomial (d : Nat) : Polynomial Nat := + MachinePaddingBounds.timePolynomial d + 1 + +def execution (d : Nat) (hd : 0 < d) (count v e : Nat) (output : List Bool) : + StateTransition.EvalsToInTime (machine d hd).step + ⟨some (.inr .initialize), (((), none), ()), initialTapes v e count output⟩ + (some (cfg d none (v + count) (e + count * d) 0 + (output ++ paddingBits d v e count))) + ((timePolynomial d).eval (MachinePaddingBounds.inputSize v e count output)) where + steps := steps d v e output count + 1 + evals_in_steps := by + convert paddingTrace d hd count v e output using 1 + rfl + steps_le_m := by + simp only [timePolynomial, Polynomial.eval_add, Polynomial.eval_one] + exact Nat.add_le_add_right + (MachinePaddingBounds.timePolynomial_bounds d v e count output) 1 + +end MinUncutGames.Foundations.Complexity.MachinePaddingCertificate + +end +section +namespace MinUncutGames.Foundations.Complexity.MachinePaddingTable + +open PCP MachinePaddingRows + +def initialOutput {n d m : Nat} (table : PortTables.Table n d) : List Bool := + encodeWords [m, m * d] ++ PreprocessingPaddingWords.rowsBits table + +def execution {n d m : Nat} (table : PortTables.Table n d) (h : n ≤ m) (hd : 0 < d) : + StateTransition.EvalsToInTime (machine d hd).step + ⟨some (.inr .initialize), (((), none), ()), + initialTapes n (n * d) (m - n) (initialOutput (m := m) table)⟩ + (some (cfg d none m (m * d) 0 + (PortTables.tableBits (PreprocessingPaddingTables.pad table h)))) + ((MachinePaddingCertificate.timePolynomial d).eval + (MachinePaddingBounds.inputSize n (n * d) (m - n) (initialOutput (m := m) table))) where + steps := steps d n (n * d) (initialOutput (m := m) table) (m - n) + 1 + evals_in_steps := by + have run := paddingTrace d hd (m - n) n (n * d) (initialOutput (m := m) table) + have hv : n + (m - n) = m := Nat.add_sub_of_le h + have he : n * d + (m - n) * d = m * d := by rw [← Nat.add_mul, hv] + have hout : initialOutput (m := m) table ++ paddingBits d n (n * d) (m - n) = + PortTables.tableBits (PreprocessingPaddingTables.pad table h) := by + rw [PreprocessingPaddingWords.tableBits_pad] + rfl + rw [hv, he, hout] at run + convert run using 1 + rfl + steps_le_m := by + simp only [MachinePaddingCertificate.timePolynomial, Polynomial.eval_add, Polynomial.eval_one] + exact Nat.add_le_add_right + (MachinePaddingBounds.timePolynomial_bounds d n (n * d) (m - n) (initialOutput (m := m) table)) 1 + +end MinUncutGames.Foundations.Complexity.MachinePaddingTable + +end +section +namespace MinUncutGames.Foundations.Complexity.MachineVertexPadding + +open Turing MachineComposition +open MinUncutGames.Foundations.PCP +open MachineCloudPadding + + +inductive Tape + | original | output | vertex | edge | power | level | fuel | relation + | scratch | work | saved | product | rowWork | rowSpare + deriving DecidableEq + +protected abbrev Tape.enumList : List Tape := [.original, .output, .vertex, .edge, .power, .level, + .fuel, .relation, .scratch, .work, .saved, .product, .rowWork, .rowSpare] + +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 + +inductive Label (d : Nat) + | splitCode (l : MachineTableSplit.Label) + | powerCode (l : MachineCeilingPower.Label) + | dartSeed | dartScan | dartRestore | vertexSeed | vertexScan | vertexRestore + | copyFirst | copySecond | subtractCode (l : MachineCloudPadding.Label) + | rowsCode (l : MachinePaddingRows.Label d) + | cleanVertex | cleanEdge | cleanPower | cleanRelation | cleanFuel + deriving DecidableEq, Fintype + +abbrev Alphabet (_ : Tape) := Bool +abbrev State (σ : Type) := (σ × Bool) × Option Bool + +def memory (input output vertex edge power level fuel relation : List Bool) : Tape → List Bool + | .original => input + | .output => output + | .vertex => vertex + | .edge => edge + | .power => power + | .level => level + | .fuel => fuel + | .relation => relation + | _ => [] + +@[simp] theorem update_output (a b c d e f g h x : List Bool) : + Function.update (memory a b c d e f g h) .output x = memory a x c d e f g h := by + funext k; cases k <;> rfl +@[simp] theorem update_vertex (a b c d e f g h x : List Bool) : + Function.update (memory a b c d e f g h) .vertex x = memory a b x d e f g h := by + funext k; cases k <;> rfl +@[simp] theorem update_edge (a b c d e f g h x : List Bool) : + Function.update (memory a b c d e f g h) .edge x = memory a b c x e f g h := by + funext k; cases k <;> rfl +@[simp] theorem update_power (a b c d e f g h x : List Bool) : + Function.update (memory a b c d e f g h) .power x = memory a b c d x f g h := by + funext k; cases k <;> rfl +@[simp] theorem update_fuel (a b c d e f g h x : List Bool) : + Function.update (memory a b c d e f g h) .fuel x = memory a b c d e f x h := by + funext k; cases k <;> rfl +@[simp] theorem update_relation (a b c d e f g h x : List Bool) : + Function.update (memory a b c d e f g h) .relation x = memory a b c d e f g x := by + funext k; cases k <;> rfl + +def splitTape : MachineTableSplit.Tape → Tape := ![.original, .output, .scratch, .vertex, .edge] +def splitView : Tape → Option MachineTableSplit.Tape + | .original => some 0 + | .output => some 1 + | .scratch => some 2 + | .vertex => some 3 + | .edge => some 4 + | _ => none + +theorem splitView_left (k : MachineTableSplit.Tape) : splitView (splitTape k) = some k := by + fin_cases k <;> rfl +theorem splitView_right (j : Tape) (k : MachineTableSplit.Tape) + (h : splitView j = some k) : splitTape k = j := by + cases j <;> fin_cases k <;> simp_all [splitView, splitTape] + +def powerTape : MachineCeilingPower.Tape → Tape + | .input => .vertex + | .work => .work + | .power => .power + | .saved => .saved + | .level => .level + | .fuel => .fuel + | .spare => .scratch + | .product => .product +def powerView : Tape → Option MachineCeilingPower.Tape + | .vertex => some .input + | .work => some .work + | .power => some .power + | .saved => some .saved + | .level => some .level + | .fuel => some .fuel + | .scratch => some .spare + | .product => some .product + | _ => none + +theorem powerView_left (k : MachineCeilingPower.Tape) : powerView (powerTape k) = some k := by + cases k <;> rfl +theorem powerView_right (j : Tape) (k : MachineCeilingPower.Tape) + (h : powerView j = some k) : powerTape k = j := by + cases j <;> cases k <;> simp_all [powerView, powerTape] + +def subtractTape : MachineCloudPadding.Tape → Tape + | .table => .original + | .query => .output + | .count => .vertex + | .work => .work + | .scratch => .saved + | .spare => .scratch + | .power => .fuel + | .level => .level + | .fuel => .product + | .product => .rowSpare +def subtractView : Tape → Option MachineCloudPadding.Tape + | .original => some .table + | .output => some .query + | .vertex => some .count + | .work => some .work + | .saved => some .scratch + | .scratch => some .spare + | .fuel => some .power + | .level => some .level + | .product => some .fuel + | .rowSpare => some .product + | _ => none + +theorem subtractView_left (k : MachineCloudPadding.Tape) : + subtractView (subtractTape k) = some k := by cases k <;> rfl +theorem subtractView_right (j : Tape) (k : MachineCloudPadding.Tape) + (h : subtractView j = some k) : subtractTape k = j := by + cases j <;> cases k <;> simp_all [subtractView, subtractTape] + +def rowTape : MachinePaddingRows.Tape → Tape + | .inl k => (![.vertex, .edge, .relation, .rowWork, .output, .rowSpare] : Fin 6 → Tape) k + | .inr _ => .fuel +def rowView : Tape → Option MachinePaddingRows.Tape + | .vertex => some (.inl 0) + | .edge => some (.inl 1) + | .relation => some (.inl 2) + | .rowWork => some (.inl 3) + | .output => some (.inl 4) + | .rowSpare => some (.inl 5) + | .fuel => some (.inr ()) + | _ => none + +theorem rowView_left (k : MachinePaddingRows.Tape) : rowView (rowTape k) = some k := by + rcases k with k | k + · fin_cases k <;> rfl + · cases k; rfl +theorem rowView_right (j : Tape) (k : MachinePaddingRows.Tape) + (h : rowView j = some k) : rowTape k = j := by + rcases k with k | k + · cases j <;> fin_cases k <;> simp_all [rowView, rowTape] + · cases k; cases j <;> simp_all [rowView, rowTape] + +theorem rowAlphabet_eq : MachinePaddingRows.Alphabet = (fun _ : MachinePaddingRows.Tape => Bool) := by + funext k; cases k <;> rfl + +def rowStateEquiv (σ : Type) : (MachinePaddingRows.State × (σ × Bool)) ≃ State σ where + toFun x := (x.2, x.1.1.2) + invFun x := ((((), x.2), ()), x.1) + left_inv := by rintro ⟨⟨⟨⟨⟩, r⟩, ⟨⟩⟩, a⟩; rfl + right_inv := by rintro ⟨a, r⟩; rfl + +def rowProgram {σ : Type} (d : Nat) (hd : 0 < d) : + MachinePaddingRows.Label d → + TM2.Stmt (fun _ : MachinePaddingRows.Tape => Bool) (MachinePaddingRows.Label d) (State σ) := + MachineStateEquiv.program (rowStateEquiv σ) + (MachineStateFrame.frameProgram + (MachineAlphabetTransport.program rowAlphabet_eq (MachinePaddingRows.program d hd))) + +def program {σ : Type} (d : Nat) (hd : 0 < d) : Label d → TM2.Stmt Alphabet (Label d) (State σ) + | .splitCode l => Placement.statement splitTape Label.splitCode (some (.powerCode .init)) + (MachineTableSplit.program l) + | .powerCode l => Placement.statement powerTape Label.powerCode (some .dartSeed) + (MachineCeilingPower.program ExpanderFamily.growth l) + | .dartSeed => MachineUnaryAffineAt.seed .output 0 .dartScan + | .dartScan => MachineUnaryAffineAt.scan .power .scratch .output d .dartScan .dartRestore + | .dartRestore => Reduction.MachineTransfer.loopAt + .scratch .power id false .dartRestore (some .vertexSeed) + | .vertexSeed => MachineUnaryAffineAt.seed .output 0 .vertexScan + | .vertexScan => MachineUnaryAffineAt.scan .power .scratch .output 1 .vertexScan .vertexRestore + | .vertexRestore => Reduction.MachineTransfer.loopAt + .scratch .power id false .vertexRestore (some .copyFirst) + | .copyFirst => Reduction.MachineTransfer.loopAt + .power .scratch id false .copyFirst (some .copySecond) + | .copySecond => MachineCopy.forkLoop + .scratch .power .fuel false .copySecond (some (.subtractCode .subtract)) + | .subtractCode l => Placement.statement subtractTape Label.subtractCode + (some (.rowsCode (.inr .initialize))) (MachineCloudPadding.program l) + | .rowsCode l => Placement.statement rowTape Label.rowsCode (some .cleanVertex) (rowProgram d hd l) + | .cleanVertex => MachineDrain.drain .vertex .cleanVertex (some .cleanEdge) + | .cleanEdge => MachineDrain.drain .edge .cleanEdge (some .cleanPower) + | .cleanPower => MachineDrain.drain .power .cleanPower (some .cleanRelation) + | .cleanRelation => MachineDrain.drain .relation .cleanRelation (some .cleanFuel) + | .cleanFuel => MachineDrain.drain .fuel .cleanFuel none + +private theorem appendTrace {α : Type} (f : α → α) {a b : Nat} {x y z : α} + (hs : f^[a] x = y) (ht : f^[b] y = z) : f^[a + b] x = z := by + rw [Nat.add_comm a b, Function.iterate_add_apply, hs, ht] + +theorem tableBits_split {n d : Nat} (t : PortTables.Table n d) : + PortTables.tableBits t = encodeWords [n, n * d] ++ PreprocessingPaddingWords.rowsBits t := by + change encodeWords (PortTables.tableWords t) = _ + rw [PortTables.tableWords_eq, encodeWords_append] + rfl + +theorem splitInitialTapes (word : List Bool) : + Placement.tapes splitView (MachineTableSplit.initialTapes word) (fun _ => []) = + memory word [] [] [] [] [] [] [] := by + funext k; cases k <;> simp [Placement.tapes, splitView, MachineTableSplit.initialTapes, + MachineTableSplit.tapes, memory] + +theorem splitResultTapes (n e : Nat) (rows : List Bool) : + Placement.tapes splitView (MachineTableSplit.resultTapes n e rows) (fun _ => []) = + memory (encodeWords [n, e] ++ rows) rows (encodeWord n) (encodeWord e) [] [] [] [] := by + funext k; cases k <;> simp [Placement.tapes, splitView, MachineTableSplit.resultTapes, + MachineTableSplit.tapes, memory] + +theorem splitTrace {σ : Type} {n d : Nat} (hd : 0 < d) (t : PortTables.Table n d) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step (program d hd)))^[MachineTableSplit.exactSteps n (n * d) + (PreprocessingPaddingWords.rowsBits t)] + (some ⟨some (.splitCode .copyFirst), ((ambient, false), register), + memory (PortTables.tableBits t) [] [] [] [] [] [] []⟩) = + some ⟨some (.powerCode .init), ((ambient, false), none), + memory (PortTables.tableBits t) (PreprocessingPaddingWords.rowsBits t) + (encodeWord n) (encodeWord (n * d)) [] [] [] []⟩ := by + have h := Placement.trace splitTape splitView splitView_left splitView_right + (Label.splitCode (d := d)) (some (.powerCode .init)) (fun _ => []) + (MachineTableSplit.program (σ := σ × Bool)) (program d hd) (fun _ => rfl) _ _ _ + (MachineTableSplit.splitTrace n (n * d) (PreprocessingPaddingWords.rowsBits t) + (ambient, false) register) + simpa only [Placement.configuration, Placement.label, splitInitialTapes, splitResultTapes, + ← tableBits_split] using h + +theorem powerTapes (input output vertex edge power level : List Bool) : + Placement.tapes powerView (MachineCeilingPower.memory vertex [] power [] level [] [] []) + (memory input output [] edge [] [] [] []) = memory input output vertex edge power level [] [] := by + funext k; cases k <;> rfl + +theorem powerTrace {σ : Type} (d : Nat) (hd : 0 < d) + (input output edge : List Bool) (n : Nat) (ambient : σ) (register : Option Bool) : + (advance (TM2.step (program d hd)))^[MachineCeilingPower.totalTime ExpanderFamily.growth n] + (some ⟨some (.powerCode .init), ((ambient, false), register), + memory input output (encodeWord n) edge [] [] [] []⟩) = + some ⟨some .dartSeed, ((ambient, false), none), + memory input output (encodeWord n) edge (encodeWord (PreprocessingLevels.paddedSize n)) + (encodeWord (PreprocessingLevels.boundedLevel n)) [] []⟩ := by + have h := Placement.trace powerTape powerView powerView_left powerView_right + (Label.powerCode (d := d)) (some .dartSeed) (memory input output [] edge [] [] [] []) + (MachineCeilingPower.program ExpanderFamily.growth (σ := σ)) (program d hd) + (fun _ => rfl) _ _ _ (MachineCeilingPower.paddingTrace n ambient register) + simpa only [Placement.configuration, Placement.label, powerTapes] using h + +theorem affineTapes (input output vertex edge power level fuel relation : List Bool) : + MachineUnaryAffineAt.tapes Tape.power Tape.scratch Tape.output + (memory input output vertex edge power level fuel relation) power [] output = + memory input output vertex edge power level fuel relation := by + funext k + cases k <;> simp [MachineUnaryAffineAt.tapes, MachineCopy.forkTapes, memory] + +theorem affineOutputTrace {σ : Type} (d : Nat) (hd : 0 < d) + (coefficient : Nat) (seed scan restore : Label d) (exit : Option (Label d)) + (atSeed : program (σ := σ) d hd seed = MachineUnaryAffineAt.seed (σ := σ × Bool) .output 0 scan) + (atScan : program (σ := σ) d hd scan = MachineUnaryAffineAt.scan (σ := σ × Bool) .power .scratch .output + coefficient scan restore) + (atRestore : program (σ := σ) d hd restore = Reduction.MachineTransfer.loopAt (σ := σ × Bool) + .scratch .power id false restore exit) + (input output vertex edge level fuel relation : List Bool) (m : Nat) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step (program d hd)))^[1 + 2 * (m + 1)] + (some ⟨some seed, ((ambient, false), register), + memory input output vertex edge (encodeWord m) level fuel relation⟩) = + some ⟨exit, ((ambient, false), none), + memory input (encodeWord (coefficient * m) ++ output) vertex edge + (encodeWord m) level fuel relation⟩ := by + have hs : (advance (TM2.step (program d hd)))^[1] + (some ⟨some seed, ((ambient, false), register), + memory input output vertex edge (encodeWord m) level fuel relation⟩) = + some ⟨some scan, ((ambient, false), register), + memory input (encodeWord 0 ++ output) vertex edge (encodeWord m) level fuel relation⟩ := by + change some (TM2.stepAux (program d hd seed) _ _) = _ + rw [atSeed] + simp [MachineUnaryAffineAt.seed, Reduction.MachineSubstitution.stepAux_pushWord, + TM2.stepAux, encodeWord, memory] + let base := memory input output vertex edge (encodeWord m) level fuel relation + have ht := MachineUnaryAffineAt.affineTrace Tape.power Tape.scratch Tape.output + (by decide) (by decide) (by decide) coefficient scan restore exit (program d hd) + atScan atRestore base m 0 [] output (ambient, false) register + have hstart : MachineUnaryAffineAt.tapes Tape.power Tape.scratch Tape.output base + (encodeWord m ++ []) [] (encodeWord 0 ++ output) = + memory input (encodeWord 0 ++ output) vertex edge (encodeWord m) level fuel relation := by + funext k + cases k <;> simp [MachineUnaryAffineAt.tapes, MachineCopy.forkTapes, base, memory] + have hfinish : MachineUnaryAffineAt.tapes Tape.power Tape.scratch Tape.output base + (encodeWord m ++ []) [] (encodeWord (coefficient * m + 0) ++ output) = + memory input (encodeWord (coefficient * m) ++ output) vertex edge + (encodeWord m) level fuel relation := by + funext k + cases k <;> simp [MachineUnaryAffineAt.tapes, MachineCopy.forkTapes, base, memory] + rw [hstart, hfinish] at ht + exact appendTrace _ hs ht + +theorem headersTrace {σ : Type} (d : Nat) (hd : 0 < d) + (input output vertex edge level : List Bool) (m : Nat) (ambient : σ) + (register : Option Bool) : + (advance (TM2.step (program d hd)))^[4 * (m + 1) + 2] + (some ⟨some .dartSeed, ((ambient, false), register), + memory input output vertex edge (encodeWord m) level [] []⟩) = + some ⟨some .copyFirst, ((ambient, false), none), + memory input (encodeWords [m, m * d] ++ output) vertex edge (encodeWord m) level [] []⟩ := by + have h₁ := affineOutputTrace d hd d .dartSeed .dartScan .dartRestore (some .vertexSeed) + rfl rfl rfl input output vertex edge level [] [] m ambient register + have h₂ := affineOutputTrace d hd 1 .vertexSeed .vertexScan .vertexRestore (some .copyFirst) + rfl rfl rfl input (encodeWord (d * m) ++ output) vertex edge level [] [] m ambient none + have h := appendTrace _ h₁ h₂ + simpa only [Nat.one_mul, Nat.mul_comm d m, encodeWords, List.append_nil, List.append_assoc, + show (1 + 2 * (m + 1)) + (1 + 2 * (m + 1)) = 4 * (m + 1) + 2 by omega] using h + +theorem copyPowerTrace {σ : Type} (d : Nat) (hd : 0 < d) + (input output vertex edge level : List Bool) (m : Nat) (ambient : σ) + (register : Option Bool) : + (advance (TM2.step (program d hd)))^[2 * (m + 2)] + (some ⟨some .copyFirst, ((ambient, false), register), + memory input output vertex edge (encodeWord m) level [] []⟩) = + some ⟨some (.subtractCode .subtract), ((ambient, false), none), + memory input output vertex edge (encodeWord m) level (encodeWord m) []⟩ := by + have h := MachineCopy.copyTrace Tape.power Tape.fuel Tape.scratch + (by decide) (by decide) (by decide) false (Label.copyFirst (d := d)) .copySecond + (some (.subtractCode .subtract)) (program d hd) rfl rfl + (memory input output vertex edge (encodeWord m) level [] []) rfl (ambient, false) register + simpa only [memory, encodeWord_length, List.append_nil, update_fuel] using h + +theorem subtractTapes (input output vertex edge power level fuel : List Bool) : + Placement.tapes subtractView + (MachineCloudPadding.memory input output vertex [] [] [] fuel level [] []) + (memory [] [] [] edge power [] [] []) = + memory input output vertex edge power level fuel [] := by + funext k; cases k <;> rfl + +theorem subtractTrace {σ : Type} (d : Nat) (hd : 0 < d) + (input output edge power level : List Bool) (n m : Nat) (hnm : n ≤ m) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step (program d hd)))^[2 * n + 2] + (some ⟨some (.subtractCode .subtract), ((ambient, false), register), + memory input output (encodeWord n) edge power level (encodeWord m) []⟩) = + some ⟨some (.rowsCode (.inr .initialize)), ((ambient, false), none), + memory input output (encodeWord n) edge power level (encodeWord (m - n)) []⟩ := by + have h := Placement.trace subtractTape subtractView subtractView_left subtractView_right + (Label.subtractCode (d := d)) (some (.rowsCode (.inr .initialize))) + (memory [] [] [] edge power [] [] []) + (MachineCloudPadding.program (σ := σ)) (program d hd) (fun _ => rfl) _ _ _ + (MachineCloudPadding.subtractTrace input output level n m hnm ambient register) + simpa only [Placement.configuration, Placement.label, subtractTapes] using h + +def rowBoolTapes (base : (k : MachinePaddingRows.Tape) → List (MachinePaddingRows.Alphabet k)) : + MachinePaddingRows.Tape → List Bool + | .inl k => base (.inl k) + | .inr k => base (.inr k) + +private theorem transport_tapes_apply {K : Type} {Γ Δ : K → Type} + (h : Γ = Δ) (base : (k : K) → List (Γ k)) (k : K) : + MachineAlphabetTransport.tapes h base k = + Eq.mp (congrArg (fun alphabet => List (alphabet k)) h) (base k) := by + cases h + rfl + +theorem rowCastTapes (base : (k : MachinePaddingRows.Tape) → List (MachinePaddingRows.Alphabet k)) : + MachineAlphabetTransport.tapes rowAlphabet_eq base = rowBoolTapes base := by + funext k + rw [transport_tapes_apply] + cases k <;> rfl + +theorem rowInitialTapes (input power level output : List Bool) (v e fuel : Nat) : + Placement.tapes rowView (rowBoolTapes (MachinePaddingRows.initialTapes v e fuel output)) + (memory input [] [] [] power level [] []) = + memory input output (encodeWord v) (encodeWord e) power level (encodeWord fuel) [] := by + funext k + cases k <;> rfl + +theorem rowFinalTapes (input power level output : List Bool) (v e fuel : Nat) : + Placement.tapes rowView (rowBoolTapes (MachinePaddingRows.tapes v e fuel output)) + (memory input [] [] [] power level [] []) = + memory input output (encodeWord v) (encodeWord e) power level (encodeWord fuel) + MachineDummyRows.trueBits := by + funext k + cases k <;> rfl + +def rowTime {n d m : Nat} (t : PortTables.Table n d) : Nat := + MachinePaddingRows.steps d n (n * d) (MachinePaddingTable.initialOutput (m := m) t) (m - n) + 1 + +private theorem frameTrace {K Λ σ τ : Type} {Γ : K → Type} [DecidableEq K] + (source : Λ → TM2.Stmt Γ Λ σ) (ambient : τ) (n : Nat) + (a b : TM2.Cfg Γ Λ σ) (run : (advance (TM2.step source))^[n] (some a) = some b) : + (advance (TM2.step (MachineStateFrame.frameProgram source)))^[n] + (some (MachineStateFrame.frameConfiguration ambient a)) = + some (MachineStateFrame.frameConfiguration ambient b) := by + have h := MachineStateFrame.frame_iterate source ambient n (some a) + simpa only [Option.map_some, run] using h + +theorem rowsTrace {σ : Type} {n d m : Nat} (hd : 0 < d) (t : PortTables.Table n d) + (hnm : n ≤ m) (input power level : List Bool) (ambient : σ) : + (advance (TM2.step (program d hd)))^[rowTime (m := m) t] + (some ⟨some (.rowsCode (.inr .initialize)), ((ambient, false), none), + memory input (MachinePaddingTable.initialOutput (m := m) t) + (encodeWord n) (encodeWord (n * d)) power level (encodeWord (m - n)) []⟩) = + some ⟨some .cleanVertex, ((ambient, false), none), + memory input (PortTables.tableBits (PreprocessingPaddingTables.pad t hnm)) + (encodeWord m) (encodeWord (m * d)) power level (encodeWord 0) + MachineDummyRows.trueBits⟩ := by + have hraw := (MachinePaddingTable.execution t hnm hd).evals_in_steps + change (advance (TM2.step (MachinePaddingRows.program d hd)))^[rowTime (m := m) t] + (some ⟨some (.inr .initialize), (((), none), ()), + MachinePaddingRows.initialTapes n (n * d) (m - n) + (MachinePaddingTable.initialOutput (m := m) t)⟩) = + some (MachinePaddingRows.cfg d none m (m * d) 0 + (PortTables.tableBits (PreprocessingPaddingTables.pad t hnm))) at hraw + have hb := MachineAlphabetTransport.successfulTrace rowAlphabet_eq + (MachinePaddingRows.program d hd) _ _ _ hraw + have hf := frameTrace + (MachineAlphabetTransport.program rowAlphabet_eq (MachinePaddingRows.program d hd)) + (ambient, false) _ _ _ hb + have hs := MachineStateEquiv.trace (rowStateEquiv σ) + (MachineStateFrame.frameProgram + (MachineAlphabetTransport.program rowAlphabet_eq (MachinePaddingRows.program d hd))) + _ _ _ hf + have hp := Placement.trace rowTape rowView rowView_left rowView_right + (Label.rowsCode (d := d)) (some .cleanVertex) (memory input [] [] [] power level [] []) + (rowProgram d hd (σ := σ)) (program d hd) (fun _ => rfl) _ _ _ hs + simpa only [Placement.configuration, Placement.label, MachineStateEquiv.configuration, + MachineStateFrame.frameConfiguration, MachineAlphabetTransport.configuration_mk, + rowCastTapes, MachinePaddingRows.cfg, rowStateEquiv, Equiv.coe_fn_mk, + rowInitialTapes, rowFinalTapes] using hp + +def cleanupTime (d m : Nat) : Nat := 2 * m + m * d + 8201 + +theorem cleanupTrace {σ : Type} (d : Nat) (hd : 0 < d) + (input output level : List Bool) (m : Nat) (ambient : σ) : + (advance (TM2.step (program d hd)))^[cleanupTime d m] + (some ⟨some .cleanVertex, ((ambient, false), none), + memory input output (encodeWord m) (encodeWord (m * d)) (encodeWord m) level + (encodeWord 0) MachineDummyRows.trueBits⟩) = + some ⟨none, ((ambient, false), none), memory input output [] [] [] level [] []⟩ := by + have h₁ := (MachineDrain.drainInTime Tape.vertex (Label.cleanVertex (d := d)) (some .cleanEdge) + (program d hd) rfl + (memory input output (encodeWord m) (encodeWord (m * d)) (encodeWord m) level + (encodeWord 0) MachineDummyRows.trueBits) (ambient, false) none).evals_in_steps + have h₂ := (MachineDrain.drainInTime Tape.edge (Label.cleanEdge (d := d)) (some .cleanPower) + (program d hd) rfl + (memory input output [] (encodeWord (m * d)) (encodeWord m) level + (encodeWord 0) MachineDummyRows.trueBits) (ambient, false) none).evals_in_steps + have h₃ := (MachineDrain.drainInTime Tape.power (Label.cleanPower (d := d)) (some .cleanRelation) + (program d hd) rfl + (memory input output [] [] (encodeWord m) level (encodeWord 0) MachineDummyRows.trueBits) + (ambient, false) none).evals_in_steps + have h₄ := (MachineDrain.drainInTime Tape.relation (Label.cleanRelation (d := d)) (some .cleanFuel) + (program d hd) rfl + (memory input output [] [] [] level (encodeWord 0) MachineDummyRows.trueBits) + (ambient, false) none).evals_in_steps + have h₅ := (MachineDrain.drainInTime Tape.fuel (Label.cleanFuel (d := d)) none + (program d hd) rfl (memory input output [] [] [] level (encodeWord 0) []) + (ambient, false) none).evals_in_steps + simp only [MachineDrain.drainInTime, memory, encodeWord_length, MachineDummyRows.trueBits_length, + update_vertex, update_edge, update_power, update_relation, update_fuel] at h₁ h₂ h₃ h₄ h₅ + have h := appendTrace _ (appendTrace _ (appendTrace _ (appendTrace _ h₁ h₂) h₃) h₄) h₅ + have ht : cleanupTime d m = (((m + 2 + (m * d + 2)) + (m + 2)) + 8193) + 2 := by + unfold cleanupTime + omega + rw [ht] + exact h + +def otherTime {n d : Nat} (t : PortTables.Table n d) : Nat := + MachineTableSplit.exactSteps n (n * d) (PreprocessingPaddingWords.rowsBits t) + + MachineCeilingPower.totalTime ExpanderFamily.growth n + + (4 * (PreprocessingLevels.paddedSize n + 1) + 2) + + (2 * (PreprocessingLevels.paddedSize n + 2)) + (2 * n + 2) + + cleanupTime d (PreprocessingLevels.paddedSize n) + +def totalTime {n d : Nat} (t : PortTables.Table n d) : Nat := + otherTime t + rowTime (m := PreprocessingLevels.paddedSize n) t + +theorem vertexPaddingTrace {σ : Type} {n d : Nat} (hd : 0 < d) (t : PortTables.Table n d) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step (program d hd)))^[totalTime t] + (some ⟨some (.splitCode .copyFirst), ((ambient, false), register), + memory (PortTables.tableBits t) [] [] [] [] [] [] []⟩) = + some ⟨none, ((ambient, false), none), + memory (PortTables.tableBits t) + (PortTables.tableBits (PreprocessingPaddingTables.pad t (PreprocessingLevels.le_paddedSize n))) + [] [] [] (encodeWord (PreprocessingLevels.boundedLevel n)) [] []⟩ := by + let m := PreprocessingLevels.paddedSize n + let level := encodeWord (PreprocessingLevels.boundedLevel n) + let input := PortTables.tableBits t + let rows := PreprocessingPaddingWords.rowsBits t + let initialOutput := MachinePaddingTable.initialOutput (m := m) t + have h₁ := splitTrace hd t ambient register + have h₂ := powerTrace d hd input rows (encodeWord (n * d)) n ambient none + have h₃ := headersTrace d hd input rows (encodeWord n) (encodeWord (n * d)) level m ambient none + have h₄ := copyPowerTrace d hd input initialOutput (encodeWord n) (encodeWord (n * d)) + level m ambient none + have h₅ := subtractTrace d hd input initialOutput (encodeWord (n * d)) (encodeWord m) + level n m (PreprocessingLevels.le_paddedSize n) ambient none + have h₆ := rowsTrace hd t (PreprocessingLevels.le_paddedSize n) input (encodeWord m) level ambient + have h₇ := cleanupTrace d hd input + (PortTables.tableBits (PreprocessingPaddingTables.pad t (PreprocessingLevels.le_paddedSize n))) + level m ambient + have h := appendTrace _ (appendTrace _ (appendTrace _ (appendTrace _ + (appendTrace _ (appendTrace _ h₁ h₂) h₃) h₄) h₅) h₆) h₇ + have ht : totalTime t = + (((((MachineTableSplit.exactSteps n (n * d) rows + + MachineCeilingPower.totalTime ExpanderFamily.growth n) + (4 * (m + 1) + 2)) + + (2 * (m + 2))) + (2 * n + 2)) + rowTime (m := m) t) + cleanupTime d m := by + dsimp only [totalTime, otherTime, m, rows] + omega + rw [ht] + exact h + +theorem rows_length_le {n d : Nat} (t : PortTables.Table n d) : + (PreprocessingPaddingWords.rowsBits t).length ≤ (PortTables.tableBits t).length := by + rw [tableBits_split, List.length_append] + omega + +theorem darts_length_le {n d : Nat} (t : PortTables.Table n d) : + n * d ≤ (PortTables.tableBits t).length := + GraphTables.darts_le_tableBits_length (PortTables.graphTable t) + +theorem power_length_bound {n d : Nat} (t : PortTables.Table n d) : + PreprocessingLevels.paddedSize n ≤ ExpanderFamily.growth * ((PortTables.tableBits t).length + 1) := + (MachineCeilingPower.paddingOutput_bounds n).2.2.trans + (Nat.mul_le_mul_left _ (Nat.add_le_add_right (PortTables.vertices_le_tableBits_length t) 1)) + +theorem initialOutput_length {n d m : Nat} (t : PortTables.Table n d) : + (MachinePaddingTable.initialOutput (m := m) t).length = + m + m * d + 2 + (PreprocessingPaddingWords.rowsBits t).length := by + simp only [MachinePaddingTable.initialOutput, List.length_append, encodeWords_length, + List.sum_cons, List.sum_nil, List.length_cons, List.length_nil] + omega + +def intermediateCoefficient (d : Nat) : Nat := (d + 2) * ExpanderFamily.growth + 8 + +noncomputable def intermediatePolynomial (d : Nat) : Polynomial Nat := + Polynomial.C (intermediateCoefficient d) * (Polynomial.X + 1) + +theorem intermediate_bound {n d : Nat} (t : PortTables.Table n d) : + MachinePaddingBounds.inputSize n (n * d) (PreprocessingLevels.paddedSize n - n) + (MachinePaddingTable.initialOutput (m := PreprocessingLevels.paddedSize n) t) ≤ + (intermediatePolynomial d).eval (PortTables.tableBits t).length := by + have hn := PortTables.vertices_le_tableBits_length t + have he := darts_length_le t + have hr := rows_length_le t + have hm := power_length_bound t + have hs := Nat.sub_le (PreprocessingLevels.paddedSize n) n + have hmul := Nat.mul_le_mul_left (d + 2) hm + simp only [MachinePaddingBounds.inputSize, encodeWord_length, initialOutput_length, + intermediatePolynomial, Polynomial.eval_mul, Polynomial.eval_C, Polynomial.eval_add, + Polynomial.eval_X, Polynomial.eval_one, intermediateCoefficient] + nlinarith + +noncomputable def otherPolynomial (d : Nat) : Polynomial Nat := + Polynomial.C (ExpanderFamily.growth + 8) * (Polynomial.X + 1) ^ 2 + + Polynomial.C ((d + 8) * ExpanderFamily.growth + 24) * (Polynomial.X + 1) + 8222 + +theorem otherTime_le {n d : Nat} (t : PortTables.Table n d) : + otherTime t ≤ (otherPolynomial d).eval (PortTables.tableBits t).length := by + have hs := MachineTableSplit.exactSteps_le n (n * d) (PreprocessingPaddingWords.rowsBits t) + rw [← tableBits_split, MachineTableSplit.timePolynomial_eval] at hs + have hc := MachineCeilingPower.totalTime_le ExpanderFamily.growth n + have hn := PortTables.vertices_le_tableBits_length t + have hm := power_length_bound t + have hsq := Nat.mul_le_mul_left (ExpanderFamily.growth + 8) + (Nat.pow_le_pow_left (Nat.add_le_add_right hn 1) 2) + have hmul := Nat.mul_le_mul_left (d + 8) hm + simp only [otherPolynomial, Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_C, + Polynomial.eval_pow, Polynomial.eval_X, Polynomial.eval_one, Polynomial.eval_ofNat] + unfold otherTime cleanupTime + unfold MachineCeilingPower.timeBound at hc + nlinarith + +noncomputable def timePolynomial (d : Nat) : Polynomial Nat := + otherPolynomial d + (MachinePaddingCertificate.timePolynomial d).comp (intermediatePolynomial d) + +theorem totalTime_le {n d : Nat} (hd : 0 < d) (t : PortTables.Table n d) : + totalTime t ≤ (timePolynomial d).eval (PortTables.tableBits t).length := by + have hrow := (MachinePaddingTable.execution t (PreprocessingLevels.le_paddedSize n) hd).steps_le_m + change rowTime (m := PreprocessingLevels.paddedSize n) t ≤ + (MachinePaddingCertificate.timePolynomial d).eval + (MachinePaddingBounds.inputSize n (n * d) (PreprocessingLevels.paddedSize n - n) + (MachinePaddingTable.initialOutput (m := PreprocessingLevels.paddedSize n) t)) at hrow + have hmono := natPolynomial_eval_mono (MachinePaddingCertificate.timePolynomial d) (intermediate_bound t) + have h := Nat.add_le_add (otherTime_le t) (hrow.trans hmono) + simpa only [totalTime, timePolynomial, Polynomial.eval_add, Polynomial.eval_comp] using h + +def vertexPaddingInTime {σ : Type} {n d : Nat} (hd : 0 < d) (t : PortTables.Table n d) + (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step (program d hd)) + ⟨some (.splitCode .copyFirst), ((ambient, false), register), + memory (PortTables.tableBits t) [] [] [] [] [] [] []⟩ + (some ⟨none, ((ambient, false), none), + memory (PortTables.tableBits t) + (PortTables.tableBits (PreprocessingPaddingTables.pad t (PreprocessingLevels.le_paddedSize n))) + [] [] [] (encodeWord (PreprocessingLevels.boundedLevel n)) [] []⟩) + ((timePolynomial d).eval (PortTables.tableBits t).length) where + steps := totalTime t + evals_in_steps := vertexPaddingTrace hd t ambient register + steps_le_m := totalTime_le hd t + +def machine (d : Nat) (hd : 0 < d) : FinTM2 where + K := Tape + k₀ := .original + k₁ := .output + Γ := Alphabet + Λ := Label d + main := .splitCode .copyFirst + σ := State Unit + initialState := (((), false), none) + m := program d hd + +theorem alphabet_finite (d : Nat) (hd : 0 < d) : ∀ k, Finite ((machine d hd).Γ k) := by + intro k + exact inferInstanceAs (Finite Bool) + +end MinUncutGames.Foundations.Complexity.MachineVertexPadding + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineRegularTableTrace.lean b/lean/OAI/Computability/MinUncut/Machines/MachineRegularTableTrace.lean new file mode 100644 index 0000000000000000000000000000000000000000..635a8673d88e081ceba455bd41ac4676ada88e2c --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineRegularTableTrace.lean @@ -0,0 +1,791 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.InputData + +namespace OAI + +namespace MinUncutGames.Foundations.Complexity.MachineRegularTable.Top + +open Turing MachineComposition +open MinUncutGames.Foundations.PCP + +private theorem joinCompleteTrace {A : Type*} {f : A → A} {m n : Nat} {a b c : A} + (first : f^[m] a = b) (second : f^[n] b = c) : f^[m + n] a = c := by + rw [Nat.add_comm m n, Function.iterate_add_apply, first, second] + +private theorem normalizeEmptyAppend {A : Type*} (output : List Bool → A) + (bits : List Bool) : output ([] ++ bits) = output bits := + congrArg output (List.nil_append bits) + +theorem headerStartTrace (H : BaseTable) (t : GraphTables.Table) : + (advance (TM2.step (program H)))^[Header.totalTime PreprocessingRegularTables.internalDegree t []] + (some (cfg H (some (.header .init)) (inputData t []) (fun _ => []) + (counterStacks [] [] [] []))) = + some (cfg H (some .oldSeed) (headerData t (headerOutput t)) (headerStacks t) + (counterStacks [] [] [] [])) := by + have run := headerTrace H t [] (counterStacks [] [] [] []) + exact run.trans (normalizeEmptyAppend + (fun output : List Bool => some (cfg H (some Label.oldSeed) + (headerData t output) (headerStacks t) (counterStacks [] [] [] []))) + (Header.headerBits PreprocessingRegularTables.internalDegree t)) + +theorem headerOldTrace (H : BaseTable) (t : GraphTables.Table) : + (advance (TM2.step (program H)))^[ + Header.totalTime PreprocessingRegularTables.internalDegree t [] + + (1+2*(t.darts+2)+(oldElapsed H t (headerOutput t) t.darts+1))] + (some (cfg H (some (.header .init)) (inputData t []) (fun _ => []) + (counterStacks [] [] [] []))) = + some (cfg H (some .ownerSeed) (oldData t t.darts (oldOutput H t)) (headerStacks t) + (counterStacks [] [] [] [])) := by + have first := headerStartTrace H t + have second := oldStageTrace H t (headerOutput t) (headerStacks t) + have joined := joinCompleteTrace (f := advance (TM2.step (program H))) first second + have output_eq : headerOutput t ++ oldPrefix H t t.darts = oldOutput H t := rfl + exact joined.trans (congrArg + (fun output : List Bool => some (cfg H (some Label.ownerSeed) + (oldData t t.darts output) (headerStacks t) (counterStacks [] [] [] []))) output_eq) + +theorem beforeCleanupTrace (H : BaseTable) (t : GraphTables.Table) : + (advance (TM2.step (program H)))^[ + Header.totalTime PreprocessingRegularTables.internalDegree t [] + + (1+2*(t.darts+2)+(oldElapsed H t (headerOutput t) t.darts+1)) + + (1+2*(t.vertices+2)+(ownerElapsed H t (oldOutput H t) t.vertices+1))] + (some (cfg H (some (.header .init)) (inputData t []) (fun _ => []) + (counterStacks [] [] [] []))) = + some ⟨clearEntry 0, readyState H, finalStacks t (finalOutput H t)⟩ := by + have first := headerOldTrace H t + have second := ownerStageTrace H t (oldOutput H t) + have joined := joinCompleteTrace (f := advance (TM2.step (program H))) first second + have output_eq : oldOutput H t ++ ownerPrefix H t t.vertices = finalOutput H t := rfl + exact joined.trans (congrArg + (fun output : List Bool => some (cfg H (clearEntry 0) + (ownerData t t.vertices output) (headerStacks t) (counterStacks [] [] [] []))) output_eq) + +theorem cleanupFinalTrace (H : BaseTable) (t : GraphTables.Table) (output : List Bool) : + (advance (TM2.step (program H)))^[cleanupTime (finalStacks t output) 7] + (some ⟨clearEntry 0, readyState H, finalStacks t output⟩) = + some (cfg H none (inputData t output) (fun _ => []) (counterStacks [] [] [] [])) := + (cleanupTrace H (finalStacks t output)).trans + (congrArg (fun terminalStacks => some (⟨none, readyState H, terminalStacks⟩ : TM2.Cfg Alphabet Label State)) + (cleaned_finalStacks t output)) + +theorem fullTrace (H : BaseTable) (t : GraphTables.Table) : + (advance (TM2.step (program H)))^[totalTime H t] + (some (cfg H (some (.header .init)) (inputData t []) (fun _ => []) + (counterStacks [] [] [] []))) = + some (cfg H none (inputData t (finalOutput H t)) (fun _ => []) + (counterStacks [] [] [] [])) := + joinCompleteTrace (f := advance (TM2.step (program H))) (beforeCleanupTrace H t) (cleanupFinalTrace H t (finalOutput H t)) + +@[simp] theorem update_frame_output (data : Data) (header : Header.Tape → List Bool) + (counters : Fin 4 → List Bool) (replacement : List Bool) : + Function.update (frame data header counters) (coreTape 8) replacement = + frame { data with output := replacement } header counters := by + funext j + cases j with + | inl j => cases j with + | inl i => fin_cases i <;> rfl + | inr e => cases e with + | inl e => cases e <;> rfl + | inr e => rfl + | inr j => cases j <;> rfl + +theorem input_stacks_eq (H : BaseTable) (t : GraphTables.Table) : + frame (inputData t []) (fun _ => []) (counterStacks [] [] [] []) = + (Turing.initList (machine H) (GraphTables.tableBits t)).stk := by + funext j + cases j with + | inl j => cases j with + | inl i => + fin_cases i <;> + simp [Turing.initList, machine, coreTape, frame, inputData, + MachineRegularOriginalBody.frame, MachineRegularMetadata.frame] + rfl + | inr e => cases e with + | inl e => cases e <;> + simp [Turing.initList, machine, coreTape, frame, inputData, + MachineRegularOriginalBody.frame, MachineRegularMetadata.frame] + | inr e => + simp [Turing.initList, machine, coreTape, frame, + MachineRegularOriginalBody.frame] + | inr j => cases j with + | inl j => simp [Turing.initList, machine, coreTape, frame] + | inr j => fin_cases j <;> simp [Turing.initList, machine, coreTape, frame, counterStacks] + +theorem initial_cfg_eq (H : BaseTable) (t : GraphTables.Table) : + cfg H (some (.header .init)) (inputData t []) (fun _ => []) (counterStacks [] [] [] []) = + Turing.initList (machine H) (GraphTables.tableBits t) := by + change (⟨some (.header .init), readyState H, + frame (inputData t []) (fun _ => []) (counterStacks [] [] [] [])⟩ : TM2.Cfg Alphabet Label State) = + ⟨some (.header .init), readyState H, (Turing.initList (machine H) (GraphTables.tableBits t)).stk⟩ + rw [input_stacks_eq] + +theorem trace (H : BaseTable) (t : GraphTables.Table) : + (advance (TM2.step (program H)))^[totalTime H t] + (some (Turing.initList (machine H) (GraphTables.tableBits t))) = + some ⟨none, readyState H, + Function.update (Turing.initList (machine H) (GraphTables.tableBits t)).stk + (coreTape 8) (PortTables.tableBits (PreprocessingRegularTables.regularize H t))⟩ := by + have full := fullTrace H t + rw [initial_cfg_eq, finalOutput_eq] at full + have final_stacks : + frame (inputData t (PortTables.tableBits (PreprocessingRegularTables.regularize H t))) + (fun _ => []) (counterStacks [] [] [] []) = + Function.update (Turing.initList (machine H) (GraphTables.tableBits t)).stk (coreTape 8) + (PortTables.tableBits (PreprocessingRegularTables.regularize H t)) := by + rw [← input_stacks_eq] + erw [update_frame_output]; rfl + change (advance (TM2.step (program H)))^[totalTime H t] + (some (Turing.initList (machine H) (GraphTables.tableBits t))) = + some ⟨none, readyState H, + frame (inputData t (PortTables.tableBits (PreprocessingRegularTables.regularize H t))) + (fun _ => []) (counterStacks [] [] [] [])⟩ at full + rw [final_stacks] at full + exact full + +end MinUncutGames.Foundations.Complexity.MachineRegularTable.Top + +namespace MinUncutGames.Foundations.Complexity.MachineRegularExecutionBounds + +open Turing MachineComposition PCP PCP.PreprocessingRegularTables PCP.PreprocessingCloudIndex +open PCP.PreprocessingMachineBounds MachineRegularInternalRow + +theorem coreTimeBound_mono (q L R x v i k o m O L' R' x' v' i' k' o' m' O' : Nat) + (hL : L ≤ L') (hR : R ≤ R') (hx : x ≤ x') (hv : v ≤ v') (hi : i ≤ i') + (hk : k ≤ k') (ho : o ≤ o') (hm : m ≤ m') (hO : O ≤ O') : + coreTimeBound q L R x v i k o m O ≤ coreTimeBound q L' R' x' v' i' k' o' m' O' := by + unfold coreTimeBound + gcongr + +noncomputable def corePolynomial (q : Nat) : Polynomial Nat := + Polynomial.C (5*q+32) * rotorPolynomial q + 10 * Polynomial.X + + 2 * (Polynomial.C ExpanderFamily.growth * Polynomial.X) + 13 * Polynomial.X + + 5 * Polynomial.X + Polynomial.C (5*q+10) * + (Polynomial.X + Polynomial.C ExpanderFamily.growth * Polynomial.X) + + 4 * (Polynomial.C ExpanderFamily.growth * Polynomial.X) + + 2 * regularPolynomial + Polynomial.C (8*q+41066) + +theorem corePolynomial_eval (q L : Nat) : + (corePolynomial q).eval L = + coreTimeBound q L ((rotorPolynomial q).eval L) + (ExpanderFamily.growth*L) L (ExpanderFamily.growth*L) L + (ExpanderFamily.growth*L) L (regularPolynomial.eval L) := by + simp only [corePolynomial, coreTimeBound, Polynomial.eval_add, Polynomial.eval_mul, + Polynomial.eval_C, Polynomial.eval_X, Polynomial.eval_ofNat] + omega + +theorem internal_steps_le (q : Nat) (positive : 0 < q) (t : GraphTables.Table) + (tables : ∀ v, ExpanderTables.Table (cloudSize t v + padding t v) q) + (v : Fin t.vertices) (x : PaddedCloud t (padding t) v) (p : Fin q) + (outputLength : Nat) (houtput : outputLength ≤ regularPolynomial.eval (inputLength t)) : + coreSteps t (padding t) tables v x p outputLength ≤ + (corePolynomial q).eval (inputLength t) := by + have hx : (vertexOrder t (padding t) x.val).val ≤ ExpanderFamily.growth * inputLength t := + (vertexOrder t (padding t) x.val).isLt.le.trans (regularVertices_le_input t) + have hi : (paddedCloudRank t (padding t) v x).val ≤ ExpanderFamily.growth * inputLength t := + (paddedCloudRank t (padding t) v x).isLt.le.trans (cloudTotal_le_input t v) + have hv : v.val ≤ inputLength t := + v.isLt.le.trans (GraphTables.vertices_le_tableBits_length t) + have hm : t.darts ≤ inputLength t := GraphTables.darts_le_tableBits_length t + rw [corePolynomial_eval] + exact (coreSteps_le q positive t (padding t) tables v x p outputLength).trans + (coreTimeBound_mono q _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ le_rfl + (cloudRotorBits_le t v (tables v)) hx hv hi (cloudSize_le_input t v) + (prefix_le_input t v.val) hm houtput) + +noncomputable def familyPolynomial : Polynomial Nat := + MachinePaddedExpanderFamilyBounds.timePolynomial.comp (Polynomial.X + 1) + + Polynomial.C (2 * ExpanderFamily.growth) * (Polynomial.X + 1) + 7 + +theorem family_budget_le (t : GraphTables.Table) (v : Fin t.vertices) : + MachinePaddedExpanderFamilyBounds.timePolynomial.eval (cloudSize t v + 1) + + 2 * ExpanderFamily.growth * (cloudSize t v + 1) + 7 ≤ + familyPolynomial.eval (inputLength t) := by + have h := Nat.add_le_add_right (cloudSize_le_input t v) 1 + have hp := natPolynomial_eval_mono MachinePaddedExpanderFamilyBounds.timePolynomial h + have hm := Nat.mul_le_mul_left (2 * ExpanderFamily.growth) h + simp only [familyPolynomial, Polynomial.eval_add, Polynomial.eval_comp, + Polynomial.eval_mul, Polynomial.eval_C, Polynomial.eval_X, Polynomial.eval_one, + Polynomial.eval_ofNat] + omega + +noncomputable def rowPolynomial (q : Nat) : Polynomial Nat := + Polynomial.C ExpanderFamily.growth * Polynomial.X + + (Polynomial.C ExpanderFamily.growth * Polynomial.X) * Polynomial.C (q + 1) + 8192 + +theorem rowPolynomial_eval (q L : Nat) : + (rowPolynomial q).eval L = + ExpanderFamily.growth * L + (ExpanderFamily.growth * L) * (q + 1) + 8192 := by + simp only [rowPolynomial, Polynomial.eval_add, Polynomial.eval_mul, + Polynomial.eval_C, Polynomial.eval_X, Polynomial.eval_ofNat] + +theorem actual_row_bound_le (q : Nat) (t : GraphTables.Table) : + vertexCount t (padding t) + vertexCount t (padding t) * (q + 1) + 8192 ≤ + (rowPolynomial q).eval (inputLength t) := by + rw [rowPolynomial_eval] + have h := regularVertices_le_input t + exact Nat.add_le_add_right (Nat.add_le_add h (Nat.mul_le_mul_right _ h)) _ + +noncomputable def blockCorePolynomial (q : Nat) : Polynomial Nat := + corePolynomial q + Polynomial.C (2*q) * rowPolynomial q + +theorem coreTimeBound_add_output (q L R x v i k o m O A : Nat) : + coreTimeBound q L R x v i k o m (O + A) = + coreTimeBound q L R x v i k o m O + 2*A := by + unfold coreTimeBound + omega + +theorem block_core_bound_le (q : Nat) (t : GraphTables.Table) + (tables : ∀ v, ExpanderTables.Table (cloudSize t v + padding t v) q) + (v : Fin t.vertices) (x : PaddedCloud t (padding t) v) + (initialOutput : Nat) (houtput : initialOutput ≤ regularPolynomial.eval (inputLength t)) : + coreTimeBound q (GraphTables.tableBits t).length + (encodeWords (ExpanderTableWords.rotationWords (tables v))).length + (vertexOrder t (padding t) x.val).val v.val (paddedCloudRank t (padding t) v x).val + (cloudSize t v) (PreprocessingPaddingOffsets.offset (padding t) v.val) t.darts + (initialOutput + q * + (vertexCount t (padding t) + vertexCount t (padding t) * (q + 1) + 8192)) ≤ + (blockCorePolynomial q).eval (inputLength t) := by + have hx : (vertexOrder t (padding t) x.val).val ≤ ExpanderFamily.growth * inputLength t := + (vertexOrder t (padding t) x.val).isLt.le.trans (regularVertices_le_input t) + have hi : (paddedCloudRank t (padding t) v x).val ≤ ExpanderFamily.growth * inputLength t := + (paddedCloudRank t (padding t) v x).isLt.le.trans (cloudTotal_le_input t v) + have hv : v.val ≤ inputLength t := + v.isLt.le.trans (GraphTables.vertices_le_tableBits_length t) + have hm : t.darts ≤ inputLength t := GraphTables.darts_le_tableBits_length t + have hr := Nat.mul_le_mul_left q (actual_row_bound_le q t) + have hO := Nat.add_le_add houtput hr + have h := coreTimeBound_mono q (inputLength t) _ _ _ _ _ _ _ _ + (inputLength t) _ _ _ _ _ _ _ _ le_rfl + (cloudRotorBits_le t v (tables v)) hx hv hi (cloudSize_le_input t v) + (prefix_le_input t v.val) hm hO + simp only [coreTimeBound_add_output] at h ⊢ + rw [← corePolynomial_eval] at h + simpa only [inputLength, blockCorePolynomial, Polynomial.eval_add, Polynomial.eval_mul, + Polynomial.eval_C, Nat.mul_assoc] using h + +end MinUncutGames.Foundations.Complexity.MachineRegularExecutionBounds + +namespace MinUncutGames.Foundations.Complexity.MachineRegularOriginalBodyBounds + +open Turing MachineComposition PCP PreprocessingCloudIndex PreprocessingRegularTables +open PreprocessingMachineBounds MachineRegularOriginalBody + +noncomputable def wide : Polynomial Nat := Polynomial.C (ExpanderFamily.growth + 1) * Polynomial.X +noncomputable def rowPolynomial (q : Nat) : Polynomial Nat := + wide + wide * Polynomial.C (q + 1) + 8192 +noncomputable def outputPolynomial (q : Nat) : Polynomial Nat := + wide + Polynomial.C q * rowPolynomial q +noncomputable def corePolynomial (q : Nat) : Polynomial Nat := + Polynomial.C (5*q+32) * rotorPolynomial q + 10*wide + 2*wide + 13*wide + 5*wide + + Polynomial.C (5*q+10)*(wide+wide) + 4*wide + 2*outputPolynomial q + + Polynomial.C (8*q+41066) +noncomputable def blockPolynomial (q : Nat) : Polynomial Nat := + Polynomial.C q * corePolynomial q + Polynomial.C (5*q+20)*wide + + 2*outputPolynomial q + Polynomial.C (5*q+40995) +noncomputable def cleanupPolynomial (q : Nat) : Polynomial Nat := 6*wide + rotorPolynomial q + 13 +noncomputable def timePolynomial : Polynomial Nat := + MachineRegularMetadata.timePolynomial + MachineRegularExecutionBounds.familyPolynomial + + blockPolynomial internalDegree + cleanupPolynomial internalDegree + +def bodySize (t : GraphTables.Table) (output : List Bool) : Nat := + inputLength t + output.length + +theorem blockPolynomial_eval (q L : Nat) : + (blockPolynomial q).eval L = + MachineRegularVertexBlock.originalTimeBound q + ((ExpanderFamily.growth+1)*L) ((rotorPolynomial q).eval L) + ((ExpanderFamily.growth+1)*L) ((ExpanderFamily.growth+1)*L) + ((ExpanderFamily.growth+1)*L) ((ExpanderFamily.growth+1)*L) + ((ExpanderFamily.growth+1)*L) ((ExpanderFamily.growth+1)*L) + ((ExpanderFamily.growth+1)*L) ((ExpanderFamily.growth+1)*L) := by + simp only [blockPolynomial, corePolynomial, outputPolynomial, rowPolynomial, wide, + Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_C, Polynomial.eval_X, + Polynomial.eval_ofNat, MachineRegularVertexBlock.originalTimeBound, + MachineRegularVertexBlock.portTimeBound, MachineRegularInternalRow.coreTimeBound, + MachineRegularOriginalClean.timeBound, MachineRegularVertexBlock.rowSizeBound] + ring + +theorem originalTimeBound_le (q L R x v i k o m O V W R' : Nat) + (hL : L ≤ W) (hR : R ≤ R') (hx : x ≤ W) (hv : v ≤ W) + (hi : i ≤ W) (hk : k ≤ W) (ho : o ≤ W) (hm : m ≤ W) + (hO : O ≤ W) (hV : V ≤ W) : + MachineRegularVertexBlock.originalTimeBound q L R x v i k o m O V ≤ + MachineRegularVertexBlock.originalTimeBound q W R' W W W W W W W W := by + unfold MachineRegularVertexBlock.originalTimeBound MachineRegularVertexBlock.portTimeBound + MachineRegularInternalRow.coreTimeBound MachineRegularOriginalClean.timeBound + MachineRegularVertexBlock.rowSizeBound + gcongr + +theorem wide_le (t : GraphTables.Table) (output : List Bool) : + inputLength t ≤ (ExpanderFamily.growth+1)*bodySize t output ∧ + ExpanderFamily.growth*inputLength t ≤ (ExpanderFamily.growth+1)*bodySize t output ∧ + output.length ≤ (ExpanderFamily.growth+1)*bodySize t output := by + have hN : inputLength t ≤ bodySize t output := Nat.le_add_right _ _ + have hO : output.length ≤ bodySize t output := Nat.le_add_left _ _ + have hg := Nat.mul_le_mul_left ExpanderFamily.growth hN + rw [Nat.add_mul, Nat.one_mul] + omega + +theorem vertexSteps_le (H : PreprocessingRegularTables.BaseTable) (t : GraphTables.Table) (e : Fin t.darts) + (output : List Bool) : + MachineRegularOriginalBody.vertexSteps H t e output ≤ + (blockPolynomial internalDegree).eval (bodySize t output) := by + let v := t.rows[e].tail + let W := (ExpanderFamily.growth+1)*bodySize t output + have bounds := wide_le t output + have hx := e.isLt.le.trans (GraphTables.darts_le_tableBits_length t) + have hv := v.isLt.le.trans (GraphTables.vertices_le_tableBits_length t) + have hk := cloudSize_le_input t v + have hi := (cloudRank t v (MachineRegularMetadata.originalMember t e)).isLt.le.trans hk + have hm := GraphTables.darts_le_tableBits_length t + have ho := prefix_le_input t v.val + have hV := regularVertices_le_input t + have hR := (cloudRotorBits_le t v (familyCloudTable H t v)).trans + (natPolynomial_eval_mono (rotorPolynomial internalDegree) + (Nat.le_add_right (inputLength t) output.length)) + have raw := MachineRegularVertexBlock.originalSteps_le internalDegree degree_positive + t (padding t) (familyCloudTable H t) e output.length + have bound := originalTimeBound_le internalDegree _ _ _ _ _ _ _ _ _ _ W _ + bounds.1 hR (hx.trans bounds.1) (hv.trans bounds.1) (hi.trans bounds.1) + (hk.trans bounds.1) (ho.trans bounds.2.1) (hm.trans bounds.1) bounds.2.2 + (hV.trans bounds.2.1) + rw [blockPolynomial_eval] + exact raw.trans bound + +theorem clearSteps_frame (data : Data) : + clearSteps (frame data) 7 = data.owner.length + data.localRank.length + + data.count.length + data.offset.length + data.rotor.length + data.padding.length + + data.level.length + 7 := by + simp [clearSteps, clearMemory, clearTape, frame, MachineRegularMetadata.frame] + omega + +theorem cleanupSteps_le (H : PreprocessingRegularTables.BaseTable) (t : GraphTables.Table) (e : Fin t.darts) + (output : List Bool) : + clearSteps (frame (emittedData H t e output)) 7 ≤ + (cleanupPolynomial internalDegree).eval (bodySize t output) := by + let v := t.rows[e].tail + have bounds := wide_le t output + have hv := v.isLt.le.trans (GraphTables.vertices_le_tableBits_length t) + have hk := cloudSize_le_input t v + have hi := (cloudRank t v (MachineRegularMetadata.originalMember t e)).isLt.le.trans hk + have ho := prefix_le_input t v.val + have hp := cloudTotal_le_input t v + have hl := level_le_input t v + have hrotor := PreprocessingFamilyBridge.familyRotor_eq_familyCloudTable H t v + (PreprocessingFamilyBridge.cloudSize_pos_of_dart t e) + change MachineRegularFamily.rotor H (cloudSize t v) = _ at hrotor + have hR := (cloudRotorBits_le t v (familyCloudTable H t v)).trans + (natPolynomial_eval_mono (rotorPolynomial internalDegree) + (Nat.le_add_right (inputLength t) output.length)) + rw [← hrotor] at hR + rw [clearSteps_frame] + simp only [emittedData, familyData, metadataData, MachineRegularMetadata.originalData, + MachineRegularMetadata.cloudData, MachineRegularMetadata.prefixData, + MachineRegularMetadata.rankData, MachineRegularMetadata.ownerData, initialData, + encodeWord_length, cleanupPolynomial, wide, Polynomial.eval_add, Polynomial.eval_mul, + Polynomial.eval_C, Polynomial.eval_X, Polynomial.eval_ofNat] + change _ ≤ 6*((ExpanderFamily.growth+1)*bodySize t output) + + (rotorPolynomial internalDegree).eval (bodySize t output)+13 + change cloudSize t v + MachineCloudPadding.padding (cloudSize t v) ≤ _ at hp + dsimp only [v, bodySize, inputLength] at * + omega + +theorem totalSteps_le (H : PreprocessingRegularTables.BaseTable) (t : GraphTables.Table) (e : Fin t.darts) + (output : List Bool) : + totalSteps H t e output ≤ timePolynomial.eval (bodySize t output) := by + have hsize : inputLength t ≤ bodySize t output := Nat.le_add_right _ _ + have hm := (MachineRegularMetadata.totalTime_le t e).trans + (natPolynomial_eval_mono MachineRegularMetadata.timePolynomial hsize) + have hf := (familyExecution H t e output).steps_le_m + have hfb := MachineRegularExecutionBounds.family_budget_le t t.rows[e].tail + simp only [MachineRegularFamily.timePolynomial, encodeWord_length, + Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_C, Polynomial.eval_X, + Polynomial.eval_ofNat] at hf + have hf' := (hf.trans hfb).trans + (natPolynomial_eval_mono MachineRegularExecutionBounds.familyPolynomial hsize) + have hv := vertexSteps_le H t e output + have hc := cleanupSteps_le H t e output + simp only [totalSteps, familySteps, timePolynomial, Polynomial.eval_add] + omega + +noncomputable def originalInTime (H : PreprocessingRegularTables.BaseTable) (t : GraphTables.Table) (e : Fin t.darts) + (output : List Bool) : + StateTransition.EvalsToInTime (TM2.step (program H)) + (cfg H (some entry) (initialData t e output)) + (some (cfg H none (initialData t e (output ++ emittedBits H t e)))) + (timePolynomial.eval (bodySize t output)) where + steps := totalSteps H t e output + evals_in_steps := originalTrace H t e output + steps_le_m := totalSteps_le H t e output + +end MinUncutGames.Foundations.Complexity.MachineRegularOriginalBodyBounds + +namespace MinUncutGames.Foundations.Complexity.MachineRegularOwnerBodyBounds + +open Turing MachineComposition PCP PreprocessingCloudIndex PreprocessingRegularTables +open PreprocessingMachineBounds PreprocessingRegularLoopWords + +def bodySize (t : GraphTables.Table) (output : List Bool) : Nat := + inputLength t + output.length + +noncomputable def wide : Polynomial Nat := Polynomial.C (ExpanderFamily.growth + 1) * Polynomial.X + +noncomputable def rowPolynomial (q : Nat) : Polynomial Nat := + wide + wide * Polynomial.C (q + 1) + 8192 + +noncomputable def outputPolynomial (q : Nat) : Polynomial Nat := + wide + regularPolynomial + Polynomial.C q * rowPolynomial q + +noncomputable def corePolynomial (q : Nat) : Polynomial Nat := + Polynomial.C (5*q+32) * rotorPolynomial q + 10*wide + 2*wide + 13*wide + 5*wide + + Polynomial.C (5*q+10)*(wide+wide) + 4*wide + 2*outputPolynomial q + + Polynomial.C (8*q+41066) + +noncomputable def blockPolynomial (q : Nat) : Polynomial Nat := + Polynomial.C q * corePolynomial q + Polynomial.C (5*q+11)*wide + + 2*outputPolynomial q + Polynomial.C (5*q+40986) + +theorem blockPolynomial_eval (q L : Nat) : + (blockPolynomial q).eval L = + MachineRegularVertexBlock.dummyTimeBound q + ((ExpanderFamily.growth+1)*L) ((rotorPolynomial q).eval L) + ((ExpanderFamily.growth+1)*L) ((ExpanderFamily.growth+1)*L) + ((ExpanderFamily.growth+1)*L) ((ExpanderFamily.growth+1)*L) + ((ExpanderFamily.growth+1)*L) ((ExpanderFamily.growth+1)*L) + (((ExpanderFamily.growth+1)*L) + regularPolynomial.eval L) + ((ExpanderFamily.growth+1)*L) := by + simp only [blockPolynomial, corePolynomial, outputPolynomial, rowPolynomial, wide, + Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_C, Polynomial.eval_X, + Polynomial.eval_ofNat, MachineRegularVertexBlock.dummyTimeBound, + MachineRegularVertexBlock.portTimeBound, MachineRegularInternalRow.coreTimeBound, + MachineRegularDummyRow.timeBound, MachineRegularVertexBlock.rowSizeBound] + simp only [Nat.add_assoc] + +theorem dummyTimeBound_le (q L R x v i k o m O V W R' O' : Nat) + (hL : L ≤ W) (hR : R ≤ R') (hx : x ≤ W) (hv : v ≤ W) + (hi : i ≤ W) (hk : k ≤ W) (ho : o ≤ W) (hm : m ≤ W) + (hO : O ≤ O') (hV : V ≤ W) : + MachineRegularVertexBlock.dummyTimeBound q L R x v i k o m O V ≤ + MachineRegularVertexBlock.dummyTimeBound q W R' W W W W W W O' W := by + unfold MachineRegularVertexBlock.dummyTimeBound MachineRegularVertexBlock.portTimeBound + MachineRegularInternalRow.coreTimeBound MachineRegularDummyRow.timeBound + MachineRegularVertexBlock.rowSizeBound + gcongr + +theorem wide_le (t : GraphTables.Table) (output : List Bool) : + inputLength t ≤ (ExpanderFamily.growth+1)*bodySize t output ∧ + ExpanderFamily.growth*inputLength t ≤ (ExpanderFamily.growth+1)*bodySize t output ∧ + output.length ≤ (ExpanderFamily.growth+1)*bodySize t output := by + have hN : inputLength t ≤ bodySize t output := Nat.le_add_right _ _ + have hO : output.length ≤ bodySize t output := Nat.le_add_left _ _ + have hg := Nat.mul_le_mul_left ExpanderFamily.growth hN + rw [Nat.add_mul, Nat.one_mul] + omega + +theorem ownerPrefix_length_le (H : BaseTable) (t : GraphTables.Table) + (v : Fin t.vertices) (n : Nat) : + (blocksPrefix (PreprocessingRegularWords.dummyVertexBits t (padding t) + (familyCloudTable H t) v) n).length ≤ regularPolynomial.eval (inputLength t) := by + have h := PreprocessingRegularBounds.regular_dummyPrefix_le t H v n + simp only [PreprocessingRegularBounds.dummyPrefix, List.length_append] at h + omega + +theorem growingOutput_length_le (H : BaseTable) (t : GraphTables.Table) + (v : Fin t.vertices) (n : Nat) (output : List Bool) : + (output ++ blocksPrefix (PreprocessingRegularWords.dummyVertexBits t (padding t) + (familyCloudTable H t) v) n).length ≤ + (ExpanderFamily.growth+1)*bodySize t output + regularPolynomial.eval (bodySize t output) := by + have h := (ownerPrefix_length_le H t v n).trans + (natPolynomial_eval_mono regularPolynomial (Nat.le_add_right (inputLength t) output.length)) + have hO := (wide_le t output).2.2 + rw [List.length_append] + exact Nat.add_le_add hO h + +theorem dummySteps_le (H : BaseTable) (t : GraphTables.Table) (v : Fin t.vertices) + (j : Fin (padding t v)) (n : Nat) (output : List Bool) : + MachineRegularVertexBlock.dummySteps t (padding t) (familyCloudTable H t) v j + (output ++ blocksPrefix (PreprocessingRegularWords.dummyVertexBits t (padding t) + (familyCloudTable H t) v) n).length ≤ + (blockPolynomial internalDegree).eval (bodySize t output) := by + let x := paddedNew t (padding t) v j + let W := (ExpanderFamily.growth+1)*bodySize t output + have bounds := wide_le t output + have hx := (vertexOrder t (padding t) x.val).isLt.le.trans (regularVertices_le_input t) + have hv := v.isLt.le.trans (GraphTables.vertices_le_tableBits_length t) + have hi := (paddedCloudRank t (padding t) v x).isLt.le.trans (cloudTotal_le_input t v) + have hk := cloudSize_le_input t v + have hm := GraphTables.darts_le_tableBits_length t + have ho := prefix_le_input t v.val + have hV := regularVertices_le_input t + have hR := (cloudRotorBits_le t v (familyCloudTable H t v)).trans + (natPolynomial_eval_mono (rotorPolynomial internalDegree) + (Nat.le_add_right (inputLength t) output.length)) + have hO := growingOutput_length_le H t v n output + have raw := MachineRegularVertexBlock.dummySteps_le internalDegree + MachineRegularOriginalBody.degree_positive t (padding t) (familyCloudTable H t) v j + (output ++ blocksPrefix (PreprocessingRegularWords.dummyVertexBits t (padding t) + (familyCloudTable H t) v) n).length + have bound := dummyTimeBound_le internalDegree _ _ _ _ _ _ _ _ _ _ W _ _ + bounds.1 hR (hx.trans bounds.2.1) (hv.trans bounds.1) (hi.trans bounds.2.1) + (hk.trans bounds.1) (ho.trans bounds.2.1) (hm.trans bounds.1) hO + (hV.trans bounds.2.1) + rw [blockPolynomial_eval] + exact raw.trans bound + +noncomputable def prePolynomial : Polynomial Nat := + MachineCloudPadding.timePolynomial.comp (2*Polynomial.X+1) + 4*wide + 6 + +noncomputable def loopPolynomial : Polynomial Nat := + wide * (blockPolynomial internalDegree + 2) + +noncomputable def cleanupPolynomial : Polynomial Nat := + 6*wide + rotorPolynomial internalDegree + 13 + +noncomputable def timePolynomial : Polynomial Nat := + prePolynomial + MachineRegularExecutionBounds.familyPolynomial + loopPolynomial + + cleanupPolynomial + 2 + +theorem preSteps_le (t : GraphTables.Table) (v : Fin t.vertices) (output : List Bool) : + MachineRegularOwnerBody.preSteps t v ≤ prePolynomial.eval (bodySize t output) := by + have bounds := wide_le t output + have hk := cloudSize_le_input t v + have hd := cloudTotal_le_input t v + have hv := v.isLt.le.trans (GraphTables.vertices_le_tableBits_length t) + change v.val ≤ inputLength t at hv + have hN : inputLength t ≤ bodySize t output := Nat.le_add_right _ _ + have hinput : MachineCloudPadding.inputLength t v [] ≤ 2*bodySize t output+1 := by + simp only [MachineCloudPadding.inputLength, List.append_nil, encodeWord_length] + change inputLength t + (v.val+1) ≤ _ + omega + have hm := (MachineCloudPadding.totalTime_le t v []).trans + (natPolynomial_eval_mono MachineCloudPadding.timePolynomial hinput) + simp only [MachineRegularOwnerBody.preSteps, prePolynomial, wide, Polynomial.eval_add, + Polynomial.eval_mul, Polynomial.eval_comp, Polynomial.eval_C, Polynomial.eval_X, + Polynomial.eval_ofNat, Polynomial.eval_one] + omega + +theorem loopSteps_le (H : BaseTable) (t : GraphTables.Table) (v : Fin t.vertices) + (output : List Bool) (n : Nat) (hn : n ≤ padding t v) : + MachineRegularOwnerBody.loopSteps H t v output n hn ≤ + n * ((blockPolynomial internalDegree).eval (bodySize t output) + 2) := by + induction n with + | zero => simp only [MachineRegularOwnerBody.loopSteps, Nat.zero_mul, le_refl] + | succ n ih => + have h : n < padding t v := by omega + have first := ih (by omega) + have second := dummySteps_le H t v ⟨n, h⟩ n output + rw [MachineRegularOwnerBody.loopSteps, Nat.succ_mul] + change MachineRegularOwnerBody.loopSteps H t v output n _ + + (1 + MachineRegularVertexBlock.dummySteps t (padding t) (familyCloudTable H t) v ⟨n, h⟩ + (output ++ blocksPrefix (PreprocessingRegularWords.dummyVertexBits t (padding t) + (familyCloudTable H t) v) n).length + 1) ≤ _ + omega + +theorem allLoopSteps_le (H : BaseTable) (t : GraphTables.Table) (v : Fin t.vertices) + (output : List Bool) : + MachineRegularOwnerBody.loopSteps H t v output (padding t v) le_rfl ≤ + loopPolynomial.eval (bodySize t output) := by + have hd := (cloudTotal_le_input t v).trans (wide_le t output).2.1 + have hp : padding t v ≤ (ExpanderFamily.growth+1)*bodySize t output := by omega + have h := (loopSteps_le H t v output (padding t v) le_rfl).trans + (Nat.mul_le_mul_right _ hp) + simpa only [loopPolynomial, wide, Polynomial.eval_add, Polynomial.eval_mul, + Polynomial.eval_C, Polynomial.eval_X, Polynomial.eval_ofNat] using h + +theorem cleanupSteps_working (data : MachineRegularOwnerBody.Data) + (fuel saved : List Bool) (d : Nat) : + MachineRegularOwnerCleanup.steps (MachineRegularOwnerBody.working data fuel saved) d = + 2*(d+1) + data.localRank.length + data.count.length + data.rotor.length + + data.padding.length + data.level.length + fuel.length + 6 := by + change 2*(d+1) + ((data.localRank.length+1) + ((data.count.length+1) + + ((data.rotor.length+1) + ((data.padding.length+1) + ((data.level.length+1) + + ((fuel.length+1)+0)))))) = _ + omega + +theorem cleanupCost_le (H : BaseTable) (t : GraphTables.Table) (v : Fin t.vertices) + (output : List Bool) : + MachineRegularOwnerBody.cleanupCost H t v output ≤ + cleanupPolynomial.eval (bodySize t output) := by + have bounds := wide_le t output + have hk := (cloudSize_le_input t v).trans bounds.1 + have htotal := (cloudTotal_le_input t v).trans bounds.2.1 + have hl := (level_le_input t v).trans bounds.1 + have hp : MachineCloudPadding.padding (cloudSize t v) = padding t v := rfl + by_cases hd : padding t v = 0 + · rw [MachineRegularOwnerBody.cleanupCost, ite_eq_left hd, cleanupSteps_working] + simp only [MachineRegularOwnerBody.seededData, MachineRegularOwnerBody.metadataData, + MachineRegularMetadata.cloudData, MachineRegularOwnerBody.initialData, + hp, encodeWord_length, List.length_nil, cleanupPolynomial, wide, + Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_C, Polynomial.eval_X, + Polynomial.eval_ofNat] + omega + · have hpositive : 0 < padding t v := by omega + have hkpos := PreprocessingFamilyBridge.cloudSize_pos_of_dummy t v ⟨0, hpositive⟩ + have hrotor := PreprocessingFamilyBridge.familyRotor_eq_familyCloudTable H t v hkpos + change MachineRegularFamily.rotor H (cloudSize t v) = _ at hrotor + have hR := (cloudRotorBits_le t v (familyCloudTable H t v)).trans + (natPolynomial_eval_mono (rotorPolynomial internalDegree) + (Nat.le_add_right (inputLength t) output.length)) + rw [← hrotor] at hR + change (MachineRegularFamily.rotor H (cloudSize t v)).length ≤ + (rotorPolynomial internalDegree).eval (bodySize t output) at hR + rw [MachineRegularOwnerBody.cleanupCost, ite_eq_right hd, + MachineRegularOwnerBody.loopFrame, cleanupSteps_working] + simp only [MachineRegularOwnerBody.loopData, MachineRegularOwnerBody.vertexData, + MachineRegularOwnerBody.seededData, MachineRegularOwnerBody.metadataData, + MachineRegularMetadata.cloudData, MachineRegularOwnerBody.initialData, + hp, encodeWord_length, Nat.sub_self, cleanupPolynomial, wide, + Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_C, Polynomial.eval_X, + Polynomial.eval_ofNat] + omega + +theorem ownerTime_le (H : BaseTable) (t : GraphTables.Table) (v : Fin t.vertices) + (output : List Bool) : + MachineRegularOwnerBody.ownerTime H t v output ≤ timePolynomial.eval (bodySize t output) := by + have hp := preSteps_le t v output + have hc := cleanupCost_le H t v output + have hl := allLoopSteps_le H t v output + have hf := (MachineRegularExecutionBounds.family_budget_le t v).trans + (natPolynomial_eval_mono MachineRegularExecutionBounds.familyPolynomial + (Nat.le_add_right (inputLength t) output.length)) + have hfamily : MachineRegularFamily.timePolynomial.eval (encodeWord (cloudSize t v)).length ≤ + MachineRegularExecutionBounds.familyPolynomial.eval (bodySize t output) := by + simpa only [bodySize, MachineRegularFamily.timePolynomial, encodeWord_length, Polynomial.eval_add, + Polynomial.eval_mul, Polynomial.eval_C, Polynomial.eval_X, Polynomial.eval_ofNat] using hf + simp only [MachineRegularOwnerBody.ownerTime, timePolynomial, Polynomial.eval_add, + Polynomial.eval_ofNat] + split_ifs <;> omega + +theorem totalSteps_le (H : BaseTable) (t : GraphTables.Table) (v : Fin t.vertices) + (output : List Bool) : + MachineRegularOwnerBody.totalSteps H t v output ≤ timePolynomial.eval (bodySize t output) := + (MachineRegularOwnerBody.totalSteps_le H t v output).trans (ownerTime_le H t v output) + +noncomputable def ownerInTime (H : BaseTable) (t : GraphTables.Table) (v : Fin t.vertices) + (output : List Bool) : + StateTransition.EvalsToInTime (TM2.step (MachineRegularOwnerBody.program H)) + (MachineRegularOwnerBody.cfg H (some MachineRegularOwnerBody.entry) + (MachineRegularOwnerBody.initialData t v output)) + (some (MachineRegularOwnerBody.cfg H none + (MachineRegularOwnerBody.finalData H t v output))) + (timePolynomial.eval (bodySize t output)) where + steps := MachineRegularOwnerBody.totalSteps H t v output + evals_in_steps := MachineRegularOwnerBody.ownerTrace H t v output + steps_le_m := totalSteps_le H t v output + +end MinUncutGames.Foundations.Complexity.MachineRegularOwnerBodyBounds + +namespace MinUncutGames.Foundations.Complexity.MachineRegularTable.Top + +open Turing MachineComposition PCP PreprocessingRegularTables +open PreprocessingRegularBounds PreprocessingMachineBounds + +noncomputable def oldLoopPolynomial : Polynomial Nat := + Polynomial.X * + (MachineRegularOriginalBodyBounds.timePolynomial.comp + (Polynomial.X + regularPolynomial) + 2) + +noncomputable def ownerLoopPolynomial : Polynomial Nat := + Polynomial.X * + (MachineRegularOwnerBodyBounds.timePolynomial.comp + (Polynomial.X + regularPolynomial) + 2) + +noncomputable def timePolynomial : Polynomial Nat := + Header.timePolynomial internalDegree + oldLoopPolynomial + ownerLoopPolynomial + + 4 * Polynomial.X + 12 + + Polynomial.C (7 * (ExpanderFamily.growth * (internalDegree + 4) + 4)) * + (Polynomial.X + 1) + +theorem oldElapsed_prefix_le (H : BaseTable) (t : GraphTables.Table) (k : Nat) : + oldElapsed H t (Header.headerBits internalDegree t) k ≤ + k * (MachineRegularOriginalBodyBounds.timePolynomial.eval + (inputLength t + regularPolynomial.eval (inputLength t)) + 2) := by + induction k with + | zero => simp [oldElapsed] + | succ k ih => + simp only [oldElapsed] + split_ifs with hk + · have raw := MachineRegularOriginalBodyBounds.totalSteps_le H t ⟨k, hk⟩ + (Header.headerBits internalDegree t ++ oldPrefix H t k) + have hprefix : + (Header.headerBits internalDegree t ++ oldPrefix H t k).length ≤ + regularPolynomial.eval (inputLength t) := by + exact regular_originalPrefix_le t H k + have hcall := raw.trans (natPolynomial_eval_mono + MachineRegularOriginalBodyBounds.timePolynomial (Nat.add_le_add_left hprefix _)) + rw [Nat.succ_mul] + omega + · rw [Nat.succ_mul] + omega + +theorem oldElapsed_le (H : BaseTable) (t : GraphTables.Table) : + oldElapsed H t (Header.headerBits internalDegree t) t.darts ≤ + oldLoopPolynomial.eval (inputLength t) := by + have bound := (oldElapsed_prefix_le H t t.darts).trans + (Nat.mul_le_mul_right _ (GraphTables.darts_le_tableBits_length t)) + simpa only [oldLoopPolynomial, inputLength, Polynomial.eval_mul, Polynomial.eval_X, + Polynomial.eval_add, Polynomial.eval_comp, Polynomial.eval_ofNat] using bound + +theorem ownerElapsed_prefix_le (H : BaseTable) (t : GraphTables.Table) (k : Nat) : + ownerElapsed H t + (Header.headerBits internalDegree t ++ oldPrefix H t t.darts) k ≤ + k * (MachineRegularOwnerBodyBounds.timePolynomial.eval + (inputLength t + regularPolynomial.eval (inputLength t)) + 2) := by + induction k with + | zero => simp [ownerElapsed] + | succ k ih => + simp only [ownerElapsed] + split_ifs with hk + · have raw := MachineRegularOwnerBodyBounds.totalSteps_le H t ⟨k, hk⟩ + ((Header.headerBits internalDegree t ++ oldPrefix H t t.darts) ++ ownerPrefix H t k) + have hprefix : + ((Header.headerBits internalDegree t ++ oldPrefix H t t.darts) ++ + ownerPrefix H t k).length ≤ regularPolynomial.eval (inputLength t) := by + rw [owner_output_eq_ownerPrefix] + exact regular_ownerPrefix_le t H k + have hcall := raw.trans (natPolynomial_eval_mono + MachineRegularOwnerBodyBounds.timePolynomial (Nat.add_le_add_left hprefix _)) + rw [Nat.succ_mul] + omega + · rw [Nat.succ_mul] + omega + +theorem ownerElapsed_le (H : BaseTable) (t : GraphTables.Table) : + ownerElapsed H t + (Header.headerBits internalDegree t ++ oldPrefix H t t.darts) t.vertices ≤ + ownerLoopPolynomial.eval (inputLength t) := by + have bound := (ownerElapsed_prefix_le H t t.vertices).trans + (Nat.mul_le_mul_right _ (GraphTables.vertices_le_tableBits_length t)) + simpa only [ownerLoopPolynomial, inputLength, Polynomial.eval_mul, Polynomial.eval_X, + Polynomial.eval_add, Polynomial.eval_comp, Polynomial.eval_ofNat] using bound + +theorem totalTime_le (H : BaseTable) (t : GraphTables.Table) : + totalTime H t ≤ timePolynomial.eval (inputLength t) := by + have header := Header.totalTime_le internalDegree t [] + simp only [List.length_nil, Nat.add_zero] at header + change Header.totalTime internalDegree t [] ≤ + (Header.timePolynomial internalDegree).eval (inputLength t) at header + have old := oldElapsed_le H t + have owners := ownerElapsed_le H t + have cleanup := cleanupTime_final_le t (finalOutput H t) + have hm : t.darts ≤ inputLength t := GraphTables.darts_le_tableBits_length t + have hn : t.vertices ≤ inputLength t := GraphTables.vertices_le_tableBits_length t + simp only [totalTime, headerOutput, oldOutput, timePolynomial, + Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_C, Polynomial.eval_X, + Polynomial.eval_ofNat, Polynomial.eval_one] + omega + +noncomputable def machineInTime (H : BaseTable) (t : GraphTables.Table) : + StateTransition.EvalsToInTime (TM2.step (program H)) + (initList (machine H) (GraphTables.tableBits t)) + (some ⟨none, readyState H, + Function.update (initList (machine H) (GraphTables.tableBits t)).stk + (coreTape 8) (PortTables.tableBits (regularize H t))⟩) + (timePolynomial.eval (inputLength t)) where + steps := totalTime H t + evals_in_steps := trace H t + steps_le_m := totalTime_le H t + +end MinUncutGames.Foundations.Complexity.MachineRegularTable.Top + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineRegularVertexBlock.lean b/lean/OAI/Computability/MinUncut/Machines/MachineRegularVertexBlock.lean new file mode 100644 index 0000000000000000000000000000000000000000..926e272ac744e92a47b478c5dad010aad7adfc1c --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineRegularVertexBlock.lean @@ -0,0 +1,600 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.SelectorMachine +import OAI.Computability.MinUncut.PCP.PreprocessingPaddingWords + +namespace OAI + +section +namespace MinUncutGames.Foundations.Complexity.MachineRegularVertexBlock + +open Turing MachineComposition PCP MachineRegularInternalRow +open PreprocessingCloudIndex PreprocessingRegularTables + +variable {σ Λ : Type} + +abbrev PortLabel (q : Nat) := Fin q × CoreLabel q + +def portEntry (q : Nat) (labels : PortLabel q → Λ) (exit : Option Λ) (k : Nat) : + Option Λ := + if h : k < q then some (labels (⟨k, h⟩, coreEntry q)) else exit + +def portInstruction (q : Nat) (positive : 0 < q) (labels : PortLabel q → Λ) + (exit : Option Λ) (l : PortLabel q) : + TM2.Stmt (fun _ : CoreTape => Bool) Λ (CoreState σ q) := + coreInstruction q positive l.1 (fun s => labels (l.1, s)) + (portEntry q labels exit (l.1.val + 1)) l.2 + +def portBits {q : Nat} (bits : Fin q → List Bool) : Nat → List Bool + | 0 => [] + | k + 1 => portBits bits k ++ if h : k < q then bits ⟨k, h⟩ else [] + +theorem portBits_eq {q : Nat} (bits : Fin q → List Bool) (k : Nat) (hk : k ≤ q) : + portBits bits k = (List.ofFn (fun p : Fin k => bits ⟨p.val, lt_of_lt_of_le p.isLt hk⟩)).flatten := by + induction k with + | zero => rfl + | succ k ih => + have h : k < q := by omega + rw [portBits, dite_eq_left h, ih (by omega), List.ofFn_succ_last, List.flatten_append] + simp only [List.flatten_cons, List.flatten_nil, List.append_nil] + rfl + +theorem portBits_all {q : Nat} (bits : Fin q → List Bool) : + portBits bits q = (List.ofFn bits).flatten := by + simpa only [Fin.eta] using portBits_eq bits q (Nat.le_refl q) + +def rowBits (t : GraphTables.Table) (padding : Fin t.vertices → Nat) {q : Nat} + (tables : ∀ v, ExpanderTables.Table (cloudSize t v + padding v) q) + (v : Fin t.vertices) (x : PaddedCloud t padding v) (p : Fin q) : List Bool := + encodeWords (GraphTables.rowWords (PreprocessingInternalRows.row t padding tables v x p)) + +def portSteps (t : GraphTables.Table) (padding : Fin t.vertices → Nat) {q : Nat} + (tables : ∀ v, ExpanderTables.Table (cloudSize t v + padding v) q) + (v : Fin t.vertices) (x : PaddedCloud t padding v) (outputLength : Nat) : Nat → Nat + | 0 => 0 + | k + 1 => portSteps t padding tables v x outputLength k + + if h : k < q then coreSteps t padding tables v x ⟨k, h⟩ + (outputLength + (portBits (rowBits t padding tables v x) k).length) else 0 + +theorem joinTrace {A : Type*} {f : A → A} {m n : Nat} {a b c : A} + (first : f^[m] a = b) (second : f^[n] b = c) : f^[m + n] a = c := by + rw [Nat.add_comm m n, Function.iterate_add_apply, first, second] + +theorem portPrefixTrace (q : Nat) (positive : 0 < q) + (labels : PortLabel q → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : CoreTape => Bool) Λ (CoreState σ q)) + (code : ∀ l, program (labels l) = portInstruction q positive labels exit l) + (t : GraphTables.Table) (padding : Fin t.vertices → Nat) + (tables : ∀ v, ExpanderTables.Table (cloudSize t v + padding v) q) + (v : Fin t.vertices) (x : PaddedCloud t padding v) (output : List Bool) (ambient : σ) + (k : Nat) (hk : k ≤ q) : + (advance (TM2.step program))^[portSteps t padding tables v x output.length k] + (some ⟨portEntry q labels exit 0, coreInitialState q positive ambient, + coreInputTapes t padding tables v x output⟩) = + some ⟨portEntry q labels exit k, coreInitialState q positive ambient, + coreInputTapes t padding tables v x + (output ++ portBits (rowBits t padding tables v x) k)⟩ := by + induction k with + | zero => simp only [portSteps, portBits, List.append_nil, Function.iterate_zero, id_eq] + | succ k ih => + have h : k < q := by omega + have first := ih (by omega) + have second := coreTrace q positive ⟨k, h⟩ (fun s => labels (⟨k, h⟩, s)) + (portEntry q labels exit (k + 1)) program (fun s => code (⟨k, h⟩, s)) + t padding tables v x (output ++ portBits (rowBits t padding tables v x) k) ambient + have he : portEntry q labels exit k = some (labels (⟨k, h⟩, coreEntry q)) := by + simp only [portEntry, dite_eq_left h] + rw [he] at first + have total := joinTrace first second + simpa only [portSteps, dite_eq_left h, List.length_append, portBits, rowBits, + List.append_assoc] using total + +theorem portTrace (q : Nat) (positive : 0 < q) + (labels : PortLabel q → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : CoreTape => Bool) Λ (CoreState σ q)) + (code : ∀ l, program (labels l) = portInstruction q positive labels exit l) + (t : GraphTables.Table) (padding : Fin t.vertices → Nat) + (tables : ∀ v, ExpanderTables.Table (cloudSize t v + padding v) q) + (v : Fin t.vertices) (x : PaddedCloud t padding v) (output : List Bool) (ambient : σ) : + (advance (TM2.step program))^[portSteps t padding tables v x output.length q] + (some ⟨portEntry q labels exit 0, coreInitialState q positive ambient, + coreInputTapes t padding tables v x output⟩) = + some ⟨exit, coreInitialState q positive ambient, + coreInputTapes t padding tables v x + (output ++ (List.ofFn (rowBits t padding tables v x)).flatten)⟩ := by + simpa only [portEntry, lt_self_iff_false, dite_false, portBits_all] using + portPrefixTrace q positive labels exit program code t padding tables v x output ambient q le_rfl + +def originalTapes : MachineRegularOriginalClean.Tape → CoreTape := + ![1, 0, 10, 11, 12, 9, 24, 25, 26, 8] + +def originalView : CoreTape → Option MachineRegularOriginalClean.Tape := + ![some 1, some 0, none, none, none, none, none, none, some 9, some 5, + some 2, some 3, some 4, none, none, none, none, none, none, none, + none, none, none, none, some 6, some 7, some 8] + +theorem originalView_left (k : MachineRegularOriginalClean.Tape) : + originalView (originalTapes k) = some k := by fin_cases k <;> rfl + +theorem originalView_right (j : CoreTape) (k : MachineRegularOriginalClean.Tape) + (h : originalView j = some k) : originalTapes k = j := by + fin_cases j <;> simp [originalView] at h + all_goals subst k; rfl + +def originalStateEquiv (σ : Type) (q : Nat) : + MachineRegularOriginalClean.State (σ × (Fin q × (Bool × MachineCloudSelect.Phase))) ≃ + CoreState σ q where + toFun s := ((s.1.1.1, (s.1.2, s.1.1.2)), s.2) + invFun s := (((s.1.1, s.1.2.2), s.1.2.1), s.2) + left_inv s := by rcases s with ⟨⟨⟨a,b⟩,c⟩,d⟩; rfl + right_inv s := by rcases s with ⟨⟨a,⟨b,c⟩⟩,d⟩; rfl + +def originalCoreInstruction (q : Nat) (labels : MachineRegularOriginalClean.Label → Λ) + (exit : Option Λ) (l : MachineRegularOriginalClean.Label) : + TM2.Stmt (fun _ : CoreTape => Bool) Λ (CoreState σ q) := + MachineCloudPadding.Placement.statement originalTapes labels exit + (MachineStateEquiv.statement (originalStateEquiv σ q) + (MachineRegularOriginalClean.instruction q id none l)) + +def originalMemory (graph : List Bool) (x : Nat) (output : List Bool) : + MachineRegularOriginalClean.Tape → List Bool := + ![encodeWord x, graph, [], [], [], [], [], [], [], output] + +theorem originalMemory_input (t : GraphTables.Table) (e : Fin t.darts) (output : List Bool) : + MachineRegularOriginalClean.Input t e (originalMemory (GraphTables.tableBits t) e.val output) := + ⟨⟨rfl, rfl, rfl, rfl, rfl, rfl, rfl⟩, rfl, rfl⟩ + +theorem originalMemory_update (graph : List Bool) (x : Nat) (output output' : List Bool) : + Function.update (originalMemory graph x output) (9 : MachineRegularOriginalClean.Tape) output' = + originalMemory graph x output' := by funext j; fin_cases j <;> rfl + +theorem originalFrame (graph : List Bool) (x v i k o m : Nat) (rotor output output' : List Bool) : + MachineCloudPadding.Placement.tapes originalView (originalMemory graph x output') + (coreMemory graph x v i k o m rotor output [] [] [] [] [] []) = + coreMemory graph x v i k o m rotor output' [] [] [] [] [] [] := by + funext j; fin_cases j <;> rfl + +theorem originalCoreTrace (q : Nat) (positive : 0 < q) + (labels : MachineRegularOriginalClean.Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : CoreTape => Bool) Λ (CoreState σ q)) + (code : ∀ l, program (labels l) = originalCoreInstruction q labels exit l) + (t : GraphTables.Table) (e : Fin t.darts) (v i k o m : Nat) + (rotor output : List Bool) (ambient : σ) : + (advance (TM2.step program))^[MachineRegularOriginalClean.steps q t e + (originalMemory (GraphTables.tableBits t) e.val output)] + (some ⟨some (labels (.row (.lookup .seed))), coreInitialState q positive ambient, + coreMemory (GraphTables.tableBits t) e.val v i k o m rotor output [] [] [] [] [] []⟩) = + some ⟨exit, coreInitialState q positive ambient, + coreMemory (GraphTables.tableBits t) e.val v i k o m rotor + (output ++ encodeWords (MachineRegularOriginalRow.emittedWords q t e)) + [] [] [] [] [] []⟩ := by + let state := (ambient, (MachineFixedDivMod.residue q positive 0, + (false, MachineCloudSelect.Phase.checking))) + have run := MachineRegularOriginalClean.traceAt q id none + (MachineRegularOriginalClean.instruction q id none) (fun _ => rfl) t e + (originalMemory (GraphTables.tableBits t) e.val output) + (originalMemory_input t e output) state none + rw [originalMemory_update] at run + have moved := MachineStateEquiv.trace (originalStateEquiv σ q) + (MachineRegularOriginalClean.instruction q id none) _ _ _ run + have placed := MachineCloudPadding.Placement.trace originalTapes originalView + originalView_left originalView_right labels exit + (coreMemory (GraphTables.tableBits t) e.val v i k o m rotor output [] [] [] [] [] []) + (MachineStateEquiv.program (originalStateEquiv σ q) + (MachineRegularOriginalClean.instruction q id none)) program code _ _ _ moved + simp only [MachineCloudPadding.Placement.configuration, MachineCloudPadding.Placement.label, + MachineStateEquiv.configuration, originalFrame] at placed + convert placed using 1 <;> rfl + +def dummyTapes : MachineRegularDummyRow.Tape → CoreTape := ![1, 24, 25, 9, 8, 26] + +def dummyView : CoreTape → Option MachineRegularDummyRow.Tape := + ![none, some 0, none, none, none, none, none, none, some 4, some 3, + none, none, none, none, none, none, none, none, none, none, + none, none, none, none, some 1, some 2, some 5] + +theorem dummyView_left (k : MachineRegularDummyRow.Tape) : + dummyView (dummyTapes k) = some k := by fin_cases k <;> rfl + +theorem dummyView_right (j : CoreTape) (k : MachineRegularDummyRow.Tape) + (h : dummyView j = some k) : dummyTapes k = j := by + fin_cases j <;> simp [dummyView] at h + all_goals subst k; rfl + +def dummyCoreInstruction (q : Nat) (labels : MachineRegularDummyRow.Label → Λ) + (exit : Option Λ) (l : MachineRegularDummyRow.Label) : + TM2.Stmt (fun _ : CoreTape => Bool) Λ (CoreState σ q) := + MachineCloudPadding.Placement.statement dummyTapes labels exit + (MachineRegularDummyRow.instruction q id none l) + +theorem dummyMemory_update (x : Nat) (output output' : List Bool) : + Function.update (MachineRegularDummyRow.memory x output) + (4 : MachineRegularDummyRow.Tape) output' = MachineRegularDummyRow.memory x output' := by + funext j; fin_cases j <;> rfl + +theorem dummyFrame (graph : List Bool) (x v i k o m : Nat) (rotor output output' : List Bool) : + MachineCloudPadding.Placement.tapes dummyView (MachineRegularDummyRow.memory x output') + (coreMemory graph x v i k o m rotor output [] [] [] [] [] []) = + coreMemory graph x v i k o m rotor output' [] [] [] [] [] [] := by + funext j; fin_cases j <;> rfl + +theorem dummyCoreTrace (q : Nat) (positive : 0 < q) + (labels : MachineRegularDummyRow.Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : CoreTape => Bool) Λ (CoreState σ q)) + (code : ∀ l, program (labels l) = dummyCoreInstruction q labels exit l) + (graph : List Bool) (x v i k o m : Nat) (rotor output : List Bool) (ambient : σ) : + (advance (TM2.step program))^[MachineRegularDummyRow.timeBound q x output.length] + (some ⟨some (labels (.affine .seed)), coreInitialState q positive ambient, + coreMemory graph x v i k o m rotor output [] [] [] [] [] []⟩) = + some ⟨exit, coreInitialState q positive ambient, + coreMemory graph x v i k o m rotor + (output ++ MachineRegularDummyRow.emittedBits q x) [] [] [] [] [] []⟩ := by + let state := (ambient, (MachineFixedBlockMap.emptyBuffer 4096, + (MachineFixedDivMod.residue q positive 0, (false, MachineCloudSelect.Phase.checking)))) + have run := MachineRegularDummyRow.traceAt q id none + (MachineRegularDummyRow.instruction q id none) (fun _ => rfl) x + (MachineRegularDummyRow.memory x output) (MachineRegularDummyRow.memory_input x output) state none + rw [dummyMemory_update] at run + have placed := MachineCloudPadding.Placement.trace dummyTapes dummyView + dummyView_left dummyView_right labels exit + (coreMemory graph x v i k o m rotor output [] [] [] [] [] []) + (MachineRegularDummyRow.instruction q id none) program code _ _ _ run + simp only [MachineCloudPadding.Placement.configuration, MachineCloudPadding.Placement.label, + dummyFrame] at placed + have hs : MachineRegularDummyRow.steps q x output = + MachineRegularDummyRow.timeBound q x output.length := MachineRegularDummyRow.steps_eq q x output + change (advance (TM2.step program))^[MachineRegularDummyRow.steps q x output] _ = _ at placed + rw [hs] at placed + exact placed + +inductive Label (q : Nat) + | originalPort (l : PortLabel q) + | dummyPort (l : PortLabel q) + | original (l : MachineRegularOriginalClean.Label) + | dummy (l : MachineRegularDummyRow.Label) + deriving DecidableEq, Fintype + +def originalEntry (q : Nat) (positive : 0 < q) : Label q := + .originalPort (⟨0, positive⟩, coreEntry q) + +def dummyEntry (q : Nat) (positive : 0 < q) : Label q := + .dummyPort (⟨0, positive⟩, coreEntry q) + +def instruction (q : Nat) (positive : 0 < q) (labels : Label q → Λ) (exit : Option Λ) : + Label q → TM2.Stmt (fun _ : CoreTape => Bool) Λ (CoreState σ q) + | .originalPort l => portInstruction q positive (fun p => labels (.originalPort p)) + (some (labels (.original (.row (.lookup .seed))))) l + | .dummyPort l => portInstruction q positive (fun p => labels (.dummyPort p)) + (some (labels (.dummy (.affine .seed)))) l + | .original l => originalCoreInstruction q (fun s => labels (.original s)) exit l + | .dummy l => dummyCoreInstruction q (fun s => labels (.dummy s)) exit l + +def oldCloud (t : GraphTables.Table) (padding : Fin t.vertices → Nat) (e : Fin t.darts) : + PaddedCloud t padding t.rows[e].tail := paddedOld t padding t.rows[e].tail ⟨e, rfl⟩ + +def originalRowSteps (q : Nat) (t : GraphTables.Table) (e : Fin t.darts) (outputLength : Nat) : Nat := + MachineRegularOriginalClean.steps q t e + (originalMemory (GraphTables.tableBits t) e.val (List.replicate outputLength false)) + +theorem originalRowSteps_eq (q : Nat) (t : GraphTables.Table) (e : Fin t.darts) + (output : List Bool) : + MachineRegularOriginalClean.steps q t e (originalMemory (GraphTables.tableBits t) e.val output) = + originalRowSteps q t e output.length := by + unfold originalRowSteps MachineRegularOriginalClean.steps + rw [MachineRegularOriginalClean.cleanupSteps_eq q t e _ (originalMemory_input t e output), + MachineRegularOriginalClean.cleanupSteps_eq q t e _ + (originalMemory_input t e (List.replicate output.length false))] + simp only [MachineRegularOriginalRow.steps, MachineRegularOriginalRow.rowSteps, + originalMemory, Matrix.cons_val, List.length_replicate] + +theorem encodeWords_flatMap {A : Type*} (xs : List A) (words : A → 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] + +private theorem encodeWords_pair (a b : Nat) (rest : List Nat) : + encodeWords ([a, b] ++ rest) = encodeWord a ++ (encodeWord b ++ encodeWords rest) := rfl + +theorem vertexBits_split (t : GraphTables.Table) (padding : Fin t.vertices → Nat) {q : Nat} + (tables : ∀ v, ExpanderTables.Table (cloudSize t v + padding v) q) + (v : Fin t.vertices) (x : PaddedCloud t padding v) : + PreprocessingRegularWords.vertexBits t padding tables x.val = + (List.ofFn (rowBits t padding tables v x)).flatten ++ + encodeWords (GraphTables.rowWords + (PreprocessingRegularWords.actualRow t padding tables x.val (.inr ()))) := by + unfold PreprocessingRegularWords.vertexBits PreprocessingRegularWords.vertexRows + rw [List.flatMap_append, encodeWords_append] + simp only [List.flatMap_cons, List.flatMap_nil, List.append_nil] + rw [encodeWords_flatMap, List.flatMap_def, List.map_ofFn] + rfl + +def originalSteps (t : GraphTables.Table) (padding : Fin t.vertices → Nat) {q : Nat} + (tables : ∀ v, ExpanderTables.Table (cloudSize t v + padding v) q) + (e : Fin t.darts) (outputLength : Nat) : Nat := + portSteps t padding tables t.rows[e].tail (oldCloud t padding e) outputLength q + + originalRowSteps q t e (outputLength + + (List.ofFn (rowBits t padding tables t.rows[e].tail (oldCloud t padding e))).flatten.length) + +theorem originalTraceAt (q : Nat) (positive : 0 < q) + (labels : Label q → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : CoreTape => Bool) Λ (CoreState σ q)) + (code : ∀ l, program (labels l) = instruction q positive labels exit l) + (t : GraphTables.Table) (padding : Fin t.vertices → Nat) + (tables : ∀ v, ExpanderTables.Table (cloudSize t v + padding v) q) + (e : Fin t.darts) (output : List Bool) (ambient : σ) : + (advance (TM2.step program))^[originalSteps t padding tables e output.length] + (some ⟨some (labels (originalEntry q positive)), coreInitialState q positive ambient, + coreInputTapes t padding tables t.rows[e].tail (oldCloud t padding e) output⟩) = + some ⟨exit, coreInitialState q positive ambient, + coreInputTapes t padding tables t.rows[e].tail (oldCloud t padding e) + (output ++ PreprocessingRegularWords.originalVertexBits t padding tables e)⟩ := by + let x := oldCloud t padding e + let bits := (List.ofFn (rowBits t padding tables t.rows[e].tail x)).flatten + have ports := portTrace q positive (fun l => labels (.originalPort l)) + (some (labels (.original (.row (.lookup .seed))))) program + (fun l => code (.originalPort l)) t padding tables t.rows[e].tail x output ambient + have inherited := originalCoreTrace q positive (fun l => labels (.original l)) exit program + (fun l => code (.original l)) t e t.rows[e].tail.val + (paddedCloudRank t padding t.rows[e].tail x).val (cloudSize t t.rows[e].tail) + (PreprocessingPaddingOffsets.offset padding t.rows[e].tail.val) t.darts + (encodeWords (ExpanderTableWords.rotationWords (tables t.rows[e].tail))) (output ++ bits) ambient + rw [originalRowSteps_eq] at inherited + change (advance (TM2.step program))^[originalRowSteps q t e (output ++ bits).length] + (some ⟨some (labels (.original (.row (.lookup .seed)))), coreInitialState q positive ambient, + coreInputTapes t padding tables t.rows[e].tail x (output ++ bits)⟩) = + some ⟨exit, coreInitialState q positive ambient, + coreInputTapes t padding tables t.rows[e].tail x + ((output ++ bits) ++ encodeWords (MachineRegularOriginalRow.emittedWords q t e))⟩ at inherited + have total := joinTrace ports inherited + have hbits : PreprocessingRegularWords.originalVertexBits t padding tables e = + bits ++ encodeWords (MachineRegularOriginalRow.emittedWords q t e) := by + have h := vertexBits_split t padding tables t.rows[e].tail x + change PreprocessingRegularWords.originalVertexBits t padding tables e = + bits ++ encodeWords (GraphTables.rowWords + (PreprocessingRegularWords.actualRow t padding tables (.inl e) (.inr ()))) at h + rw [PreprocessingRegularWords.inherited_original_words] at h + exact h + rw [hbits] + simpa only [originalSteps, portEntry, dite_eq_left positive, originalEntry, + List.length_append, List.append_assoc, x, bits] using total + +def dummySteps (t : GraphTables.Table) (padding : Fin t.vertices → Nat) {q : Nat} + (tables : ∀ v, ExpanderTables.Table (cloudSize t v + padding v) q) + (v : Fin t.vertices) (j : Fin (padding v)) (outputLength : Nat) : Nat := + portSteps t padding tables v (paddedNew t padding v j) outputLength q + + MachineRegularDummyRow.timeBound q (vertexOrder t padding (.inr ⟨v, j⟩)).val + (outputLength + (List.ofFn (rowBits t padding tables v (paddedNew t padding v j))).flatten.length) + +theorem dummyTraceAt (q : Nat) (positive : 0 < q) + (labels : Label q → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : CoreTape => Bool) Λ (CoreState σ q)) + (code : ∀ l, program (labels l) = instruction q positive labels exit l) + (t : GraphTables.Table) (padding : Fin t.vertices → Nat) + (tables : ∀ v, ExpanderTables.Table (cloudSize t v + padding v) q) + (v : Fin t.vertices) (j : Fin (padding v)) (output : List Bool) (ambient : σ) : + (advance (TM2.step program))^[dummySteps t padding tables v j output.length] + (some ⟨some (labels (dummyEntry q positive)), coreInitialState q positive ambient, + coreInputTapes t padding tables v (paddedNew t padding v j) output⟩) = + some ⟨exit, coreInitialState q positive ambient, + coreInputTapes t padding tables v (paddedNew t padding v j) + (output ++ PreprocessingRegularWords.dummyVertexBits t padding tables v j)⟩ := by + let x := paddedNew t padding v j + let bits := (List.ofFn (rowBits t padding tables v x)).flatten + have ports := portTrace q positive (fun l => labels (.dummyPort l)) + (some (labels (.dummy (.affine .seed)))) program + (fun l => code (.dummyPort l)) t padding tables v x output ambient + have inherited := dummyCoreTrace q positive (fun l => labels (.dummy l)) exit program + (fun l => code (.dummy l)) (GraphTables.tableBits t) (vertexOrder t padding x.val).val v.val + (paddedCloudRank t padding v x).val (cloudSize t v) + (PreprocessingPaddingOffsets.offset padding v.val) t.darts + (encodeWords (ExpanderTableWords.rotationWords (tables v))) (output ++ bits) ambient + have total := joinTrace ports inherited + have hbits : PreprocessingRegularWords.dummyVertexBits t padding tables v j = + bits ++ MachineRegularDummyRow.emittedBits q (vertexOrder t padding x.val).val := by + have h := vertexBits_split t padding tables v x + change PreprocessingRegularWords.dummyVertexBits t padding tables v j = + bits ++ encodeWords (GraphTables.rowWords + (PreprocessingRegularWords.actualRow t padding tables (.inr ⟨v, j⟩) (.inr ()))) at h + rw [PreprocessingRegularWords.inherited_dummy_words] at h + rw [encodeWords_pair] at h + rw [show (vertexOrder t padding x.val).val = + t.darts + PreprocessingPaddingOffsets.offset padding v.val + j.val from + PreprocessingPaddingOffsets.vertexOrder_dummy_val t padding v j] + simpa only [MachineRegularDummyRow.emittedBits, MachineRegularDummyRow.reverseIndex, + MachineDummyRows.rowBits, MachineDummyRows.trueBits, List.append_assoc] using h + rw [hbits] + simp only [dummySteps, portEntry, dite_eq_left positive, dummyEntry, + List.length_append, List.append_assoc, x, bits] at total ⊢ + convert total using 1 <;> rfl + +def rowSizeBound (q vertices : Nat) : Nat := vertices + vertices * (q + 1) + 8192 + +theorem rowBits_length_le (t : GraphTables.Table) (padding : Fin t.vertices → Nat) {q : Nat} + (tables : ∀ v, ExpanderTables.Table (cloudSize t v + padding v) q) + (v : Fin t.vertices) (x : PaddedCloud t padding v) (p : Fin q) : + (rowBits t padding tables v x p).length ≤ rowSizeBound q (vertexCount t padding) := + GraphTables.rowBits_length_le _ + +theorem portBits_length_le {q : Nat} (bits : Fin q → List Bool) (bound : Nat) + (hbits : ∀ p, (bits p).length ≤ bound) (k : Nat) : + (portBits bits k).length ≤ k * bound := by + induction k with + | zero => simp only [portBits, List.length_nil, Nat.zero_mul, le_refl] + | succ k ih => + rw [portBits, List.length_append] + split_ifs with h + · have hp := hbits ⟨k, h⟩ + rw [Nat.succ_mul] + exact Nat.add_le_add ih hp + · simp only [List.length_nil, Nat.add_zero] + exact ih.trans (Nat.mul_le_mul_right bound (by omega)) + +theorem allRowBits_length_le (t : GraphTables.Table) (padding : Fin t.vertices → Nat) {q : Nat} + (tables : ∀ v, ExpanderTables.Table (cloudSize t v + padding v) q) + (v : Fin t.vertices) (x : PaddedCloud t padding v) : + (List.ofFn (rowBits t padding tables v x)).flatten.length ≤ + q * rowSizeBound q (vertexCount t padding) := by + rw [← portBits_all] + exact portBits_length_le _ _ (rowBits_length_le t padding tables v x) q + +def portTimeBound (q graphLength rotorLength x v i k o m outputLength vertices : Nat) : Nat := + q * coreTimeBound q graphLength rotorLength x v i k o m + (outputLength + q * rowSizeBound q vertices) + +theorem portSteps_le (q : Nat) (positive : 0 < q) (t : GraphTables.Table) + (padding : Fin t.vertices → Nat) + (tables : ∀ v, ExpanderTables.Table (cloudSize t v + padding v) q) + (v : Fin t.vertices) (x : PaddedCloud t padding v) (outputLength : Nat) (n : Nat) (hn : n ≤ q) : + portSteps t padding tables v x outputLength n ≤ + n * coreTimeBound q (GraphTables.tableBits t).length + (encodeWords (ExpanderTableWords.rotationWords (tables v))).length + (vertexOrder t padding x.val).val v.val (paddedCloudRank t padding v x).val + (cloudSize t v) (PreprocessingPaddingOffsets.offset padding v.val) t.darts + (outputLength + q * rowSizeBound q (vertexCount t padding)) := by + induction n with + | zero => simp only [portSteps, Nat.zero_mul, le_refl] + | succ n ih => + have h : n < q := by omega + have first := ih (by omega) + have second := coreSteps_le q positive t padding tables v x ⟨n, h⟩ + (outputLength + (portBits (rowBits t padding tables v x) n).length) + have hlen := portBits_length_le (rowBits t padding tables v x) + (rowSizeBound q (vertexCount t padding)) (rowBits_length_le t padding tables v x) n + have hmul := Nat.mul_le_mul_right (rowSizeBound q (vertexCount t padding)) (Nat.le_of_lt h) + have hcost : coreSteps t padding tables v x ⟨n, h⟩ + (outputLength + (portBits (rowBits t padding tables v x) n).length) ≤ + coreTimeBound q (GraphTables.tableBits t).length + (encodeWords (ExpanderTableWords.rotationWords (tables v))).length + (vertexOrder t padding x.val).val v.val (paddedCloudRank t padding v x).val + (cloudSize t v) (PreprocessingPaddingOffsets.offset padding v.val) t.darts + (outputLength + q * rowSizeBound q (vertexCount t padding)) := by + unfold coreTimeBound at second ⊢ + omega + rw [portSteps, dite_eq_left h, Nat.succ_mul] + exact Nat.add_le_add first hcost + +def originalTimeBound (q graphLength rotorLength x v i k o m outputLength vertices : Nat) : Nat := + portTimeBound q graphLength rotorLength x v i k o m outputLength vertices + + MachineRegularOriginalClean.timeBound q graphLength + (outputLength + q * rowSizeBound q vertices) + +def dummyTimeBound (q graphLength rotorLength x v i k o m outputLength vertices : Nat) : Nat := + portTimeBound q graphLength rotorLength x v i k o m outputLength vertices + + MachineRegularDummyRow.timeBound q x (outputLength + q * rowSizeBound q vertices) + +theorem originalSteps_le (q : Nat) (positive : 0 < q) (t : GraphTables.Table) + (padding : Fin t.vertices → Nat) + (tables : ∀ v, ExpanderTables.Table (cloudSize t v + padding v) q) + (e : Fin t.darts) (outputLength : Nat) : + originalSteps t padding tables e outputLength ≤ + originalTimeBound q (GraphTables.tableBits t).length + (encodeWords (ExpanderTableWords.rotationWords (tables t.rows[e].tail))).length + e.val t.rows[e].tail.val (paddedCloudRank t padding t.rows[e].tail (oldCloud t padding e)).val + (cloudSize t t.rows[e].tail) (PreprocessingPaddingOffsets.offset padding t.rows[e].tail.val) + t.darts outputLength (vertexCount t padding) := by + let v := t.rows[e].tail + let x := oldCloud t padding e + let extra := (List.ofFn (rowBits t padding tables v x)).flatten.length + have hp := portSteps_le q positive t padding tables v x outputLength q le_rfl + have hi := MachineRegularOriginalClean.steps_le q t e + (originalMemory (GraphTables.tableBits t) e.val (List.replicate (outputLength + extra) false)) + (originalMemory_input t e (List.replicate (outputLength + extra) false)) + have hl := allRowBits_length_le t padding tables v x + change originalRowSteps q t e (outputLength + extra) ≤ + MachineRegularOriginalClean.timeBound q (GraphTables.tableBits t).length + (List.replicate (outputLength + extra) false).length at hi + rw [List.length_replicate] at hi + change portSteps t padding tables v x outputLength q + + originalRowSteps q t e (outputLength + extra) ≤ _ + unfold originalTimeBound portTimeBound MachineRegularOriginalClean.timeBound at * + have hx : (vertexOrder t padding x.val).val = e.val := rfl + rw [hx] at hp + dsimp only [v, x, extra] at * + omega + +theorem dummySteps_le (q : Nat) (positive : 0 < q) (t : GraphTables.Table) + (padding : Fin t.vertices → Nat) + (tables : ∀ v, ExpanderTables.Table (cloudSize t v + padding v) q) + (v : Fin t.vertices) (j : Fin (padding v)) (outputLength : Nat) : + dummySteps t padding tables v j outputLength ≤ + dummyTimeBound q (GraphTables.tableBits t).length + (encodeWords (ExpanderTableWords.rotationWords (tables v))).length + (vertexOrder t padding (.inr ⟨v, j⟩)).val v.val + (paddedCloudRank t padding v (paddedNew t padding v j)).val + (cloudSize t v) (PreprocessingPaddingOffsets.offset padding v.val) + t.darts outputLength (vertexCount t padding) := by + have hp := portSteps_le q positive t padding tables v (paddedNew t padding v j) outputLength q le_rfl + have hl := allRowBits_length_le t padding tables v (paddedNew t padding v j) + unfold dummySteps dummyTimeBound portTimeBound MachineRegularDummyRow.timeBound + have hx : (paddedNew t padding v j).val = Sum.inr ⟨v, j⟩ := rfl + rw [hx] at hp + omega + +def originalMachine (q : Nat) (positive : 0 < q) : FinTM2 where + K := CoreTape + k₀ := 0 + k₁ := 8 + Γ _ := Bool + Λ := Label q + main := originalEntry q positive + σ := CoreState Unit q + initialState := coreInitialState q positive () + m := instruction q positive id none + +def dummyMachine (q : Nat) (positive : 0 < q) : FinTM2 where + K := CoreTape + k₀ := 0 + k₁ := 8 + Γ _ := Bool + Λ := Label q + main := dummyEntry q positive + σ := CoreState Unit q + initialState := coreInitialState q positive () + m := instruction q positive id none + +def originalMachineInTime (q : Nat) (positive : 0 < q) (t : GraphTables.Table) + (padding : Fin t.vertices → Nat) + (tables : ∀ v, ExpanderTables.Table (cloudSize t v + padding v) q) + (e : Fin t.darts) (output : List Bool) : + StateTransition.EvalsToInTime (originalMachine q positive).step + ⟨some (originalEntry q positive), coreInitialState q positive (), + coreInputTapes t padding tables t.rows[e].tail (oldCloud t padding e) output⟩ + (some ⟨none, coreInitialState q positive (), + coreInputTapes t padding tables t.rows[e].tail (oldCloud t padding e) + (output ++ PreprocessingRegularWords.originalVertexBits t padding tables e)⟩) + (originalTimeBound q (GraphTables.tableBits t).length + (encodeWords (ExpanderTableWords.rotationWords (tables t.rows[e].tail))).length + e.val t.rows[e].tail.val (paddedCloudRank t padding t.rows[e].tail (oldCloud t padding e)).val + (cloudSize t t.rows[e].tail) (PreprocessingPaddingOffsets.offset padding t.rows[e].tail.val) + t.darts output.length (vertexCount t padding)) where + steps := originalSteps t padding tables e output.length + evals_in_steps := originalTraceAt q positive id none (instruction q positive id none) + (fun _ => rfl) t padding tables e output () + steps_le_m := originalSteps_le q positive t padding tables e output.length + +def dummyMachineInTime (q : Nat) (positive : 0 < q) (t : GraphTables.Table) + (padding : Fin t.vertices → Nat) + (tables : ∀ v, ExpanderTables.Table (cloudSize t v + padding v) q) + (v : Fin t.vertices) (j : Fin (padding v)) (output : List Bool) : + StateTransition.EvalsToInTime (dummyMachine q positive).step + ⟨some (dummyEntry q positive), coreInitialState q positive (), + coreInputTapes t padding tables v (paddedNew t padding v j) output⟩ + (some ⟨none, coreInitialState q positive (), + coreInputTapes t padding tables v (paddedNew t padding v j) + (output ++ PreprocessingRegularWords.dummyVertexBits t padding tables v j)⟩) + (dummyTimeBound q (GraphTables.tableBits t).length + (encodeWords (ExpanderTableWords.rotationWords (tables v))).length + (vertexOrder t padding (.inr ⟨v, j⟩)).val v.val + (paddedCloudRank t padding v (paddedNew t padding v j)).val + (cloudSize t v) (PreprocessingPaddingOffsets.offset padding v.val) + t.darts output.length (vertexCount t padding)) where + steps := dummySteps t padding tables v j output.length + evals_in_steps := dummyTraceAt q positive id none (instruction q positive id none) + (fun _ => rfl) t padding tables v j output () + steps_le_m := dummySteps_le q positive t padding tables v j output.length + +end MinUncutGames.Foundations.Complexity.MachineRegularVertexBlock + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineSubroutine.lean b/lean/OAI/Computability/MinUncut/Machines/MachineSubroutine.lean new file mode 100644 index 0000000000000000000000000000000000000000..627f2cb15ccd1cabb6146defc9b59b12c2594d7c --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineSubroutine.lean @@ -0,0 +1,282 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.Runtime + +namespace OAI + +namespace MinUncutGames.Foundations.Complexity.MachineSubroutine + +open Turing + +variable {K Λ Λ' σ : Type} {Γ : K → Type} + +def label (labels : Λ → Λ') (exit : Option Λ') : Option Λ → Option Λ' + | none => exit + | some l => some (labels l) + +def configuration (labels : Λ → Λ') (exit : Option Λ') (c : TM2.Cfg Γ Λ σ) : + TM2.Cfg Γ Λ' σ := ⟨label labels exit c.l, c.var, c.stk⟩ + +def statement (labels : Λ → Λ') (exit : Option Λ') : + TM2.Stmt Γ Λ σ → TM2.Stmt Γ Λ' σ + | .push k f next => .push k f (statement labels exit next) + | .peek k f next => .peek k f (statement labels exit next) + | .pop k f next => .pop k f (statement labels exit next) + | .load f next => .load f (statement labels exit next) + | .branch f yes no => .branch f (statement labels exit yes) (statement labels exit no) + | .goto f => .goto (fun s => labels (f s)) + | .halt => match exit with + | none => .halt + | some l => .goto (fun _ => l) + +variable [DecidableEq K] + +theorem stepAux_simulation (labels : Λ → Λ') (exit : Option Λ') + (q : TM2.Stmt Γ Λ σ) (state : σ) (tapes : ∀ k, List (Γ k)) : + TM2.stepAux (statement labels exit q) state tapes = + configuration labels exit (TM2.stepAux q state tapes) := by + induction q generalizing state tapes with + | push k f next ih => + simpa only [statement, TM2.stepAux] using + ih state (Function.update tapes k (f state :: tapes k)) + | peek k f next ih => + simpa only [statement, TM2.stepAux] using ih (f state (tapes k).head?) tapes + | pop k f next ih => + simpa only [statement, TM2.stepAux] using + ih (f state (tapes k).head?) (Function.update tapes k (tapes k).tail) + | load f next ih => simpa only [statement, TM2.stepAux] using ih (f state) tapes + | branch f yes no ihYes ihNo => + cases h : f state with + | false => simpa only [statement, TM2.stepAux, h, Bool.cond_false] using ihNo state tapes + | true => simpa only [statement, TM2.stepAux, h, Bool.cond_true] using ihYes state tapes + | goto f => rfl + | halt => cases exit <;> rfl + +theorem step_simulation (labels : Λ → Λ') (exit : Option Λ') + (source : Λ → TM2.Stmt Γ Λ σ) (target : Λ' → TM2.Stmt Γ Λ' σ) + (atLabels : ∀ l, target (labels l) = statement labels exit (source l)) + (a b : TM2.Cfg Γ Λ σ) (h : TM2.step source a = some b) : + TM2.step target (configuration labels exit a) = + some (configuration labels exit b) := by + cases a with + | mk l state tapes => + cases l with + | none => simp [TM2.step] at h + | some l => + have hb : TM2.stepAux (source l) state tapes = b := Option.some.inj h + rw [← hb] + change some (TM2.stepAux (target (labels l)) state tapes) = _ + rw [atLabels, stepAux_simulation] + +theorem trace (labels : Λ → Λ') (exit : Option Λ') + (source : Λ → TM2.Stmt Γ Λ σ) (target : Λ' → TM2.Stmt Γ Λ' σ) + (atLabels : ∀ l, target (labels l) = statement labels exit (source l)) + (steps : Nat) (a b : TM2.Cfg Γ Λ σ) + (run : (MachineComposition.advance (TM2.step source))^[steps] (some a) = some b) : + (MachineComposition.advance (TM2.step target))^[steps] + (some (configuration labels exit a)) = some (configuration labels exit b) := + MachineComposition.liftSuccessfulTrace (TM2.step source) (TM2.step target) + (configuration labels exit) (step_simulation labels exit source target atLabels) steps a b run + +def execution (labels : Λ → Λ') (exit : Option Λ') + (source : Λ → TM2.Stmt Γ Λ σ) (target : Λ' → TM2.Stmt Γ Λ' σ) + (atLabels : ∀ l, target (labels l) = statement labels exit (source l)) + {a b : TM2.Cfg Γ Λ σ} {budget : Nat} + (run : StateTransition.EvalsToInTime (TM2.step source) a (some b) budget) : + StateTransition.EvalsToInTime (TM2.step target) + (configuration labels exit a) (some (configuration labels exit b)) budget := + MachineComposition.liftExecutionInTime (TM2.step source) (TM2.step target) + (configuration labels exit) (step_simulation labels exit source target atLabels) run + +end MinUncutGames.Foundations.Complexity.MachineSubroutine + +namespace MinUncutGames.Foundations.Complexity.MachineStateFrame + +open Turing + +variable {K Λ Λ' σ τ : Type} {Γ : K → Type} + +def frameStatement : TM2.Stmt Γ Λ σ → TM2.Stmt Γ Λ (σ × τ) + | .push k f next => .push k (fun state => f state.1) (frameStatement next) + | .peek k f next => .peek k (fun state bit => (f state.1 bit, state.2)) + (frameStatement next) + | .pop k f next => .pop k (fun state bit => (f state.1 bit, state.2)) + (frameStatement next) + | .load f next => .load (fun state => (f state.1, state.2)) (frameStatement next) + | .branch f yes no => .branch (fun state => f state.1) + (frameStatement yes) (frameStatement no) + | .goto f => .goto (fun state => f state.1) + | .halt => .halt + +def frameConfiguration (ambient : τ) (c : TM2.Cfg Γ Λ σ) : TM2.Cfg Γ Λ (σ × τ) := + ⟨c.l, (c.var, ambient), c.stk⟩ + +def frameProgram (source : Λ → TM2.Stmt Γ Λ σ) : Λ → TM2.Stmt Γ Λ (σ × τ) := + fun label => frameStatement (source label) + +@[simp] theorem frameConfiguration_state (ambient : τ) (c : TM2.Cfg Γ Λ σ) : + (frameConfiguration ambient c).var.1 = c.var := rfl + +@[simp] theorem frameConfiguration_metadata (ambient : τ) (c : TM2.Cfg Γ Λ σ) : + (frameConfiguration ambient c).var.2 = ambient := rfl + +@[simp] theorem frameConfiguration_tapes (ambient : τ) (c : TM2.Cfg Γ Λ σ) : + (frameConfiguration ambient c).stk = c.stk := rfl + +theorem frameStatement_pushBound (q : TM2.Stmt Γ Λ σ) : + Runtime.statementPushBound (frameStatement (τ := τ) q) = Runtime.statementPushBound q := by + induction q <;> simp_all only [frameStatement, Runtime.statementPushBound] + +def statement (labels : Λ → Λ') (exit : Option Λ') (q : TM2.Stmt Γ Λ σ) : + TM2.Stmt Γ Λ' (σ × τ) := + MachineSubroutine.statement labels exit (frameStatement q) + +def configuration (labels : Λ → Λ') (exit : Option Λ') (ambient : τ) + (c : TM2.Cfg Γ Λ σ) : TM2.Cfg Γ Λ' (σ × τ) := + MachineSubroutine.configuration labels exit (frameConfiguration ambient c) + +@[simp] theorem configuration_state (labels : Λ → Λ') (exit : Option Λ') + (ambient : τ) (c : TM2.Cfg Γ Λ σ) : + (configuration labels exit ambient c).var.1 = c.var := rfl + +@[simp] theorem configuration_metadata (labels : Λ → Λ') (exit : Option Λ') + (ambient : τ) (c : TM2.Cfg Γ Λ σ) : + (configuration labels exit ambient c).var.2 = ambient := rfl + +@[simp] theorem configuration_tapes (labels : Λ → Λ') (exit : Option Λ') + (ambient : τ) (c : TM2.Cfg Γ Λ σ) : + (configuration labels exit ambient c).stk = c.stk := rfl + +theorem statement_pushBound (labels : Λ → Λ') (exit : Option Λ') + (q : TM2.Stmt Γ Λ σ) : + Runtime.statementPushBound (statement (τ := τ) labels exit q) = + Runtime.statementPushBound q := by + induction q <;> simp_all only [statement, frameStatement, + MachineSubroutine.statement, Runtime.statementPushBound] + cases exit <;> rfl + +variable [DecidableEq K] + +theorem frame_stepAux (q : TM2.Stmt Γ Λ σ) (state : σ) (ambient : τ) + (tapes : ∀ k, List (Γ k)) : + TM2.stepAux (frameStatement q) (state, ambient) tapes = + frameConfiguration ambient (TM2.stepAux q state tapes) := by + induction q generalizing state tapes with + | push k f next ih => + simpa only [frameStatement, TM2.stepAux] using + ih state (Function.update tapes k (f state :: tapes k)) + | peek k f next ih => + simpa only [frameStatement, TM2.stepAux] using ih (f state (tapes k).head?) tapes + | pop k f next ih => + simpa only [frameStatement, TM2.stepAux] using + ih (f state (tapes k).head?) (Function.update tapes k (tapes k).tail) + | load f next ih => simpa only [frameStatement, TM2.stepAux] using ih (f state) tapes + | branch f yes no ihYes ihNo => + cases h : f state with + | false => simpa only [frameStatement, TM2.stepAux, h, Bool.cond_false] using ihNo state tapes + | true => simpa only [frameStatement, TM2.stepAux, h, Bool.cond_true] using ihYes state tapes + | goto f => rfl + | halt => rfl + +theorem frame_step (source : Λ → TM2.Stmt Γ Λ σ) (ambient : τ) + (c : TM2.Cfg Γ Λ σ) : + TM2.step (frameProgram source) (frameConfiguration ambient c) = + (TM2.step source c).map (frameConfiguration ambient) := by + rcases c with ⟨label, state, tapes⟩ + cases label with + | none => rfl + | some label => + change some (TM2.stepAux (frameStatement (source label)) (state, ambient) tapes) = _ + rw [frame_stepAux] + rfl + +theorem frame_advance (source : Λ → TM2.Stmt Γ Λ σ) (ambient : τ) + (c : Option (TM2.Cfg Γ Λ σ)) : + MachineComposition.advance (TM2.step (frameProgram source)) + (c.map (frameConfiguration ambient)) = + (MachineComposition.advance (TM2.step source) c).map (frameConfiguration ambient) := by + cases c with + | none => rfl + | some c => exact frame_step source ambient c + +theorem frame_iterate (source : Λ → TM2.Stmt Γ Λ σ) (ambient : τ) + (steps : ℕ) (c : Option (TM2.Cfg Γ Λ σ)) : + (MachineComposition.advance (TM2.step (frameProgram source)))^[steps] + (c.map (frameConfiguration ambient)) = + ((MachineComposition.advance (TM2.step source))^[steps] c).map + (frameConfiguration ambient) := by + induction steps with + | zero => rfl + | succ steps ih => + rw [Function.iterate_succ_apply', Function.iterate_succ_apply', ih] + exact frame_advance source ambient _ + +def frameExecution (source : Λ → TM2.Stmt Γ Λ σ) (ambient : τ) + {start : TM2.Cfg Γ Λ σ} {finish : Option (TM2.Cfg Γ Λ σ)} {budget : ℕ} + (run : StateTransition.EvalsToInTime (TM2.step source) start finish budget) : + StateTransition.EvalsToInTime (TM2.step (frameProgram source)) + (frameConfiguration ambient start) (finish.map (frameConfiguration ambient)) budget where + steps := run.steps + evals_in_steps := by + have h := run.evals_in_steps + change (MachineComposition.advance (TM2.step source))^[run.steps] (some start) = finish at h + change (MachineComposition.advance (TM2.step (frameProgram source)))^[run.steps] + ((some start).map (frameConfiguration ambient)) = finish.map (frameConfiguration ambient) + rw [frame_iterate, h] + steps_le_m := run.steps_le_m + +@[simp] theorem frameExecution_steps (source : Λ → TM2.Stmt Γ Λ σ) (ambient : τ) + {start : TM2.Cfg Γ Λ σ} {finish : Option (TM2.Cfg Γ Λ σ)} {budget : ℕ} + (run : StateTransition.EvalsToInTime (TM2.step source) start finish budget) : + (frameExecution source ambient run).steps = run.steps := rfl + +theorem stepAux_simulation (labels : Λ → Λ') (exit : Option Λ') + (q : TM2.Stmt Γ Λ σ) (state : σ) (ambient : τ) (tapes : ∀ k, List (Γ k)) : + TM2.stepAux (statement labels exit q) (state, ambient) tapes = + configuration labels exit ambient (TM2.stepAux q state tapes) := by + rw [statement, MachineSubroutine.stepAux_simulation, frame_stepAux] + rfl + +theorem step_simulation (labels : Λ → Λ') (exit : Option Λ') (ambient : τ) + (source : Λ → TM2.Stmt Γ Λ σ) (target : Λ' → TM2.Stmt Γ Λ' (σ × τ)) + (atLabels : ∀ l, target (labels l) = statement labels exit (source l)) + (a b : TM2.Cfg Γ Λ σ) (h : TM2.step source a = some b) : + TM2.step target (configuration labels exit ambient a) = + some (configuration labels exit ambient b) := by + have framed : TM2.step (frameProgram source) (frameConfiguration ambient a) = + some (frameConfiguration ambient b) := by + rw [frame_step, h] + rfl + exact MachineSubroutine.step_simulation labels exit (frameProgram source) target + atLabels _ _ framed + +theorem trace (labels : Λ → Λ') (exit : Option Λ') (ambient : τ) + (source : Λ → TM2.Stmt Γ Λ σ) (target : Λ' → TM2.Stmt Γ Λ' (σ × τ)) + (atLabels : ∀ l, target (labels l) = statement labels exit (source l)) + (steps : ℕ) (a b : TM2.Cfg Γ Λ σ) + (run : (MachineComposition.advance (TM2.step source))^[steps] (some a) = some b) : + (MachineComposition.advance (TM2.step target))^[steps] + (some (configuration labels exit ambient a)) = some (configuration labels exit ambient b) := + MachineComposition.liftSuccessfulTrace (TM2.step source) (TM2.step target) + (configuration labels exit ambient) (step_simulation labels exit ambient source target atLabels) + steps a b run + +def execution (labels : Λ → Λ') (exit : Option Λ') (ambient : τ) + (source : Λ → TM2.Stmt Γ Λ σ) (target : Λ' → TM2.Stmt Γ Λ' (σ × τ)) + (atLabels : ∀ l, target (labels l) = statement labels exit (source l)) + {a b : TM2.Cfg Γ Λ σ} {budget : ℕ} + (run : StateTransition.EvalsToInTime (TM2.step source) a (some b) budget) : + StateTransition.EvalsToInTime (TM2.step target) + (configuration labels exit ambient a) (some (configuration labels exit ambient b)) budget := + MachineComposition.liftExecutionInTime (TM2.step source) (TM2.step target) + (configuration labels exit ambient) (step_simulation labels exit ambient source target atLabels) run + +@[simp] theorem execution_steps (labels : Λ → Λ') (exit : Option Λ') (ambient : τ) + (source : Λ → TM2.Stmt Γ Λ σ) (target : Λ' → TM2.Stmt Γ Λ' (σ × τ)) + (atLabels : ∀ l, target (labels l) = statement labels exit (source l)) + {a b : TM2.Cfg Γ Λ σ} {budget : ℕ} + (run : StateTransition.EvalsToInTime (TM2.step source) a (some b) budget) : + (execution labels exit ambient source target atLabels run).steps = run.steps := rfl + +end MinUncutGames.Foundations.Complexity.MachineStateFrame + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineSubstitution.lean b/lean/OAI/Computability/MinUncut/Machines/MachineSubstitution.lean new file mode 100644 index 0000000000000000000000000000000000000000..3e2dc353836896e21d44a21c0a42ce8735da80e7 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineSubstitution.lean @@ -0,0 +1,871 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineCompare + +namespace OAI + +section +namespace MinUncutGames.Reduction.MachineSubstitution + +open Turing + +open MinUncutGames.Foundations.Complexity + +section PushWord + +variable {K Λ σ : Type} {Γ : K → Type} [DecidableEq K] + +def pushWord (dst : K) : List (Γ dst) → TM2.Stmt Γ Λ σ → TM2.Stmt Γ Λ σ + | [], continuation => continuation + | symbol :: word, continuation => + .push dst (fun _ => symbol) (pushWord dst word continuation) + +theorem stepAux_pushWord (dst : K) (word : List (Γ dst)) + (continuation : TM2.Stmt Γ Λ σ) (state : σ) (tapes : ∀ k, List (Γ k)) : + TM2.stepAux (pushWord dst word continuation) state tapes = + TM2.stepAux continuation state + (Function.update tapes dst (word.reverse ++ tapes dst)) := by + induction word generalizing tapes with + | nil => simp [pushWord] + | cons symbol word ih => + simp only [pushWord, TM2.stepAux] + rw [ih] + simp only [Function.update_self, Function.update_idem, List.reverse_cons, + List.append_assoc, List.singleton_append] + +omit [DecidableEq K] in +theorem statementPushBound_pushWord (dst : K) (word : List (Γ dst)) + (continuation : TM2.Stmt Γ Λ σ) : + Runtime.statementPushBound (pushWord dst word continuation) = + word.length + Runtime.statementPushBound continuation := by + induction word with + | nil => simp [pushWord] + | cons symbol word ih => + simp only [pushWord, Runtime.statementPushBound, ih, List.length_cons] + omega + +end PushWord + +def loop : TM2.Stmt (fun _ : Bool => Bool) (Option Bool) (Option Bool) := + .pop false (fun _ head => head) + (.branch Option.isSome + (.goto fun state => some (state.getD false)) + .halt) + +def program (emit : Bool → List Bool) : + Option Bool → TM2.Stmt (fun _ : Bool => Bool) (Option Bool) (Option Bool) + | none => loop + | some symbol => pushWord true (emit symbol) (.goto fun _ => none) + +def machine (emit : Bool → List Bool) : FinTM2 where + K := Bool + k₀ := false + k₁ := true + Γ _ := Bool + Λ := Option Bool + main := none + σ := Option Bool + initialState := none + m := program emit + +def maxEmission (emit : Bool → List Bool) : Nat := + max (emit false).length (emit true).length + +theorem statementPushBound_le (emit : Bool → List Bool) (label : Option Bool) : + Runtime.statementPushBound (program emit label) ≤ maxEmission emit := by + cases label with + | none => simp [program, loop, Runtime.statementPushBound] + | some symbol => + simp only [program, statementPushBound_pushWord, Runtime.statementPushBound, Nat.add_zero] + cases symbol + · exact Nat.le_max_left _ _ + · exact Nat.le_max_right _ _ + +theorem programPushBound_le (emit : Bool → List Bool) : + Runtime.programPushBound (machine emit) ≤ maxEmission emit := by + have allLabels (labels : List (Option Bool)) : + Runtime.maxLabelPushes (program emit) labels ≤ maxEmission emit := by + induction labels with + | nil => exact Nat.zero_le _ + | cons label rest ih => + exact max_le (statementPushBound_le emit label) ih + exact allLabels (machine emit).ΛFin.elems.toList + +def tapeStacks (input output : List Bool) : Bool → List Bool := + fun side => if side then output else input + +def running (emit : Bool → List Bool) (input output : List Bool) (state : Option Bool) : + (machine emit).Cfg := + ⟨some none, state, tapeStacks input output⟩ + +def emitting (emit : Bool → List Bool) (symbol : Bool) + (input output : List Bool) (state : Option Bool) : (machine emit).Cfg := + ⟨some (some symbol), state, tapeStacks input output⟩ + +def halted (emit : Bool → List Bool) (output : List Bool) : (machine emit).Cfg := + ⟨none, none, tapeStacks [] output⟩ + +theorem update_input (input output replacement : List Bool) : + Function.update (tapeStacks input output) false replacement = tapeStacks replacement output := by + funext side + cases side <;> simp [tapeStacks] + +theorem update_output (input output replacement : List Bool) : + Function.update (tapeStacks input output) true replacement = tapeStacks input replacement := by + funext side + cases side <;> simp [tapeStacks] + +theorem step_empty (emit : Bool → List Bool) (output : List Bool) (state : Option Bool) : + (machine emit).step (running emit [] output state) = some (halted emit output) := by + change some (TM2.stepAux loop state (tapeStacks [] output)) = some (halted emit output) + simp [loop, TM2.stepAux, tapeStacks, halted] + rw [update_input] + rfl + +theorem step_cons (emit : Bool → List Bool) (symbol : Bool) + (input output : List Bool) (state : Option Bool) : + (machine emit).step (running emit (symbol :: input) output state) = + some (emitting emit symbol input output (some symbol)) := by + change some (TM2.stepAux loop state (tapeStacks (symbol :: input) output)) = _ + simp [loop, TM2.stepAux, tapeStacks, emitting] + rw [update_input] + rfl + +theorem step_emit (emit : Bool → List Bool) (symbol : Bool) + (input output : List Bool) (state : Option Bool) : + (machine emit).step (emitting emit symbol input output state) = + some (running emit input ((emit symbol).reverse ++ output) state) := by + change some (TM2.stepAux (pushWord true (emit symbol) (.goto fun _ => none)) + state (tapeStacks input output)) = _ + rw [stepAux_pushWord] + simp only [TM2.stepAux] + change some (⟨some none, state, + Function.update (tapeStacks input output) true ((emit symbol).reverse ++ output)⟩ : + (machine emit).Cfg) = _ + exact congrArg (fun st => (some ⟨some none, state, st⟩ : + Option (TM2.Cfg (fun _ : Bool => Bool) (Option Bool) (Option Bool)))) + (update_output input output ((emit symbol).reverse ++ output)) + +def next (emit : Bool → List Bool) (configuration : Option (machine emit).Cfg) : + Option (machine emit).Cfg := + configuration.bind (machine emit).step + +theorem two_steps_cons (emit : Bool → List Bool) (symbol : Bool) + (input output : List Bool) (state : Option Bool) : + (next emit)^[2] (some (running emit (symbol :: input) output state)) = + some (running emit input ((emit symbol).reverse ++ output) (some symbol)) := by + change (machine emit).step (running emit (symbol :: input) output state) >>= + (machine emit).step = _ + rw [step_cons] + exact step_emit emit symbol input output (some symbol) + +theorem substitution_steps (emit : Bool → List Bool) + (input output : List Bool) (state : Option Bool) : + (next emit)^[2 * input.length + 1] (some (running emit input output state)) = + some (halted emit ((input.flatMap emit).reverse ++ output)) := by + induction input generalizing output state with + | nil => + simpa only [List.length_nil, Nat.mul_zero, Nat.zero_add, Function.iterate_one, next, + Option.bind_some, List.flatMap_nil, List.reverse_nil, List.nil_append] + using step_empty emit output state + | cons symbol input ih => + rw [List.length_cons] + rw [show 2 * (input.length + 1) + 1 = (2 * input.length + 1) + 2 by omega] + rw [Function.iterate_add_apply, two_steps_cons, ih] + simp only [List.flatMap_cons, List.reverse_append, List.append_assoc] + +theorem initList_eq (emit : Bool → List Bool) (input : List Bool) : + initList (machine emit) input = running emit input [] none := by + unfold initList running + congr 1 + funext side + cases side <;> rfl + +theorem haltList_eq (emit : Bool → List Bool) (output : List Bool) : + haltList (machine emit) output = halted emit output := by + unfold haltList halted + congr 1 + +theorem substitution_init_steps (emit : Bool → List Bool) (input : List Bool) : + (next emit)^[2 * input.length + 1] (some (initList (machine emit) input)) = + some (haltList (machine emit) (input.flatMap emit).reverse) := by + rw [initList_eq, haltList_eq] + simpa only [List.append_nil] using substitution_steps emit input [] none + +def outputsInTime (emit : Bool → List Bool) (input : List Bool) : + TM2OutputsInTime (machine emit) input (some (input.flatMap emit).reverse) + (2 * input.length + 1) where + steps := 2 * input.length + 1 + evals_in_steps := substitution_init_steps emit input + steps_le_m := Nat.le_refl _ + +@[simp] theorem outputsInTime_steps (emit : Bool → List Bool) (input : List Bool) : + (outputsInTime emit input).steps = 2 * input.length + 1 := rfl + +noncomputable def computableInPolyTime (emit : Bool → List Bool) : + TM2ComputableInPolyTime (id : List Bool → List Bool) id + (fun input => (input.flatMap emit).reverse) where + tm := machine emit + inputAlphabet := Equiv.refl Bool + outputAlphabet := Equiv.refl Bool + time := 2 * Polynomial.X + 1 + outputsFun input := by + change TM2OutputsInTime (machine emit) (input.map id) + (some ((input.flatMap emit).reverse.map id)) + ((2 * Polynomial.X + 1 : Polynomial Nat).eval input.length) + have hi := @List.map_id ((machine emit).Γ (machine emit).k₀) input + have ho := @List.map_id ((machine emit).Γ (machine emit).k₁) (input.flatMap emit).reverse + rw [hi, ho] + simpa only [Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_X, + Polynomial.eval_ofNat, Polynomial.eval_one] using outputsInTime emit input + +end MinUncutGames.Reduction.MachineSubstitution + +end +section +namespace MinUncutGames.Reduction.MachineReverse + +open Turing + +def loop : TM2.Stmt (fun _ : Bool => Bool) Unit (Option Bool) := + .pop false (fun _ head => head) + (.branch Option.isSome + (.push true (fun state => state.getD false) (.goto fun _ => ())) + .halt) + +def machine : FinTM2 where + K := Bool + k₀ := false + k₁ := true + Γ _ := Bool + Λ := Unit + main := () + σ := Option Bool + initialState := none + m _ := loop + +def tapeStacks (input output : List Bool) : Bool → List Bool := + fun side => if side then output else input + +def running (input output : List Bool) (state : Option Bool) : machine.Cfg := + ⟨some (), state, tapeStacks input output⟩ + +def halted (output : List Bool) : machine.Cfg := + ⟨none, none, tapeStacks [] output⟩ + +theorem update_input (input output replacement : List Bool) : + Function.update (tapeStacks input output) false replacement = tapeStacks replacement output := by + funext side + cases side <;> simp [tapeStacks] + +theorem update_output (input output replacement : List Bool) : + Function.update (tapeStacks input output) true replacement = tapeStacks input replacement := by + funext side + cases side <;> simp [tapeStacks] + +theorem step_empty (output : List Bool) (state : Option Bool) : + machine.step (running [] output state) = some (halted output) := by + change some (TM2.stepAux loop state (tapeStacks [] output)) = some (halted output) + simp [loop, TM2.stepAux, tapeStacks, halted, Function.update] + rw [update_input] + rfl + +theorem step_cons (head : Bool) (input output : List Bool) (state : Option Bool) : + machine.step (running (head :: input) output state) = + some (running input (head :: output) (some head)) := by + change some (TM2.stepAux loop state (tapeStacks (head :: input) output)) = _ + simp [loop, TM2.stepAux, tapeStacks, running, Function.update] + rw [update_input, update_output] + rfl + +def next (configuration : Option machine.Cfg) : Option machine.Cfg := + configuration.bind machine.step + +theorem reverse_steps (input output : List Bool) (state : Option Bool) : + next^[input.length + 1] (some (running input output state)) = + some (halted (input.reverse ++ output)) := by + induction input generalizing output state with + | nil => + simpa only [List.length_nil, Nat.zero_add, Function.iterate_one, next, + Option.bind_some, List.reverse_nil, List.nil_append] using step_empty output state + | cons head input ih => + rw [List.length_cons, Function.iterate_succ_apply] + change next^[input.length + 1] + (machine.step (running (head :: input) output state)) = _ + rw [step_cons, ih] + simp only [List.reverse_cons, List.append_assoc, List.singleton_append] + +theorem initList_eq (input : List Bool) : + initList machine input = running input [] none := by + unfold initList running + congr 1 + funext side + cases side <;> rfl + +theorem haltList_eq (output : List Bool) : haltList machine output = halted output := by + unfold haltList halted + congr 1 + +theorem reverse_init_steps (input : List Bool) : + next^[input.length + 1] (some (initList machine input)) = + some (haltList machine input.reverse) := by + rw [initList_eq, haltList_eq] + simpa only [List.append_nil] using reverse_steps input [] none + +def outputsInTime (input : List Bool) : + TM2OutputsInTime machine input (some input.reverse) (input.length + 1) where + steps := input.length + 1 + evals_in_steps := reverse_init_steps input + steps_le_m := Nat.le_refl _ + +@[simp] theorem outputsInTime_steps (input : List Bool) : + (outputsInTime input).steps = input.length + 1 := rfl + +noncomputable def computableInPolyTime : + TM2ComputableInPolyTime (id : List Bool → List Bool) id List.reverse where + tm := machine + inputAlphabet := Equiv.refl Bool + outputAlphabet := Equiv.refl Bool + time := Polynomial.X + 1 + outputsFun input := by + change TM2OutputsInTime machine (input.map id) (some (input.reverse.map id)) + ((Polynomial.X + 1 : Polynomial Nat).eval input.length) + have hi := @List.map_id (machine.Γ machine.k₀) input + have ho := @List.map_id (machine.Γ machine.k₁) input.reverse + rw [hi, ho] + simpa only [Polynomial.eval_add, Polynomial.eval_X, Polynomial.eval_one] + using outputsInTime input + +end MinUncutGames.Reduction.MachineReverse + +end +section +namespace MinUncutGames.Foundations.Complexity.MachineStackSwap + +open Turing.TM2 + +variable {A B C Λ σ : Type} + {ΓA : A → Type} {ΓB : B → Type} {ΓC : C → Type} + +abbrev Alphabet (ΓA : A → Type) (ΓB : B → Type) (ΓC : C → Type) := + MachineEmbedding.Alphabet ΓA (MachineEmbedding.Alphabet ΓB ΓC) + +def tapes (source : ∀ k, List (Alphabet ΓA ΓB ΓC k)) : + ∀ j, List (Alphabet ΓB ΓA ΓC j) + | .inl b => source (.inr (.inl b)) + | .inr (.inl a) => source (.inl a) + | .inr (.inr c) => source (.inr (.inr c)) + +@[simp] theorem tapes_first (source : ∀ k, List (Alphabet ΓA ΓB ΓC k)) (a : A) : + tapes source (.inr (.inl a)) = source (.inl a) := rfl +@[simp] theorem tapes_second (source : ∀ k, List (Alphabet ΓA ΓB ΓC k)) (b : B) : + tapes source (.inl b) = source (.inr (.inl b)) := rfl +@[simp] theorem tapes_third (source : ∀ k, List (Alphabet ΓA ΓB ΓC k)) (c : C) : + tapes source (.inr (.inr c)) = source (.inr (.inr c)) := rfl + +theorem tapes_involutive (source : ∀ k, List (Alphabet ΓA ΓB ΓC k)) : + tapes (tapes source) = source := by + funext k + rcases k with a | b | c <;> rfl + +def configuration (c : Cfg (Alphabet ΓA ΓB ΓC) Λ σ) : + Cfg (Alphabet ΓB ΓA ΓC) Λ σ where + l := c.l + var := c.var + stk := tapes c.stk + +def statement : Stmt (Alphabet ΓA ΓB ΓC) Λ σ → Stmt (Alphabet ΓB ΓA ΓC) Λ σ + | .push (.inl a) f next => .push (.inr (.inl a)) f (statement next) + | .push (.inr (.inl b)) f next => .push (.inl b) f (statement next) + | .push (.inr (.inr c)) f next => .push (.inr (.inr c)) f (statement next) + | .peek (.inl a) f next => .peek (.inr (.inl a)) f (statement next) + | .peek (.inr (.inl b)) f next => .peek (.inl b) f (statement next) + | .peek (.inr (.inr c)) f next => .peek (.inr (.inr c)) f (statement next) + | .pop (.inl a) f next => .pop (.inr (.inl a)) f (statement next) + | .pop (.inr (.inl b)) f next => .pop (.inl b) f (statement next) + | .pop (.inr (.inr c)) f next => .pop (.inr (.inr c)) f (statement next) + | .load f next => .load f (statement next) + | .branch f yes no => .branch f (statement yes) (statement no) + | .goto f => .goto f + | .halt => .halt + +variable [DecidableEq A] [DecidableEq B] [DecidableEq C] + +theorem tapes_update_first (source : ∀ k, List (Alphabet ΓA ΓB ΓC k)) + (a : A) (value : List (ΓA a)) : + tapes (Function.update source (.inl a) value) = + Function.update (tapes source) (.inr (.inl a)) value := by + funext j + rcases j with b | a' | c + · simp [Function.update] + · by_cases h : a' = a + · subst a'; simp [Function.update] + · simp [Function.update, h] + · simp [Function.update] + +theorem tapes_update_second (source : ∀ k, List (Alphabet ΓA ΓB ΓC k)) + (b : B) (value : List (ΓB b)) : + tapes (Function.update source (.inr (.inl b)) value) = + Function.update (tapes source) (.inl b) value := by + funext j + rcases j with b' | a | c + · by_cases h : b' = b + · subst b'; simp [Function.update] + · simp [Function.update, h] + · simp [Function.update] + · simp [Function.update] + +theorem tapes_update_third (source : ∀ k, List (Alphabet ΓA ΓB ΓC k)) + (c : C) (value : List (ΓC c)) : + tapes (Function.update source (.inr (.inr c)) value) = + Function.update (tapes source) (.inr (.inr c)) value := by + funext j + rcases j with b | a | c' + · simp [Function.update] + · simp [Function.update] + · by_cases h : c' = c + · subst c'; simp [Function.update] + · simp [Function.update, h] + +theorem stepAux_simulation (q : Stmt (Alphabet ΓA ΓB ΓC) Λ σ) + (state : σ) (source : ∀ k, List (Alphabet ΓA ΓB ΓC k)) : + stepAux (statement q) state (tapes source) = + configuration (stepAux q state source) := by + induction q generalizing state source with + | push k f next ih => + rcases k with a | b | c + · simp only [statement, stepAux, tapes_first] + rw [← tapes_update_first] + exact ih state (Function.update source (.inl a) (f state :: source (.inl a))) + · simp only [statement, stepAux, tapes_second] + rw [← tapes_update_second] + exact ih state (Function.update source (.inr (.inl b)) + (f state :: source (.inr (.inl b)))) + · simp only [statement, stepAux, tapes_third] + rw [← tapes_update_third] + exact ih state (Function.update source (.inr (.inr c)) + (f state :: source (.inr (.inr c)))) + | peek k f next ih => + rcases k with a | b | c + · simpa only [statement, stepAux, tapes_first] using + ih (f state (source (.inl a)).head?) source + · simpa only [statement, stepAux, tapes_second] using + ih (f state (source (.inr (.inl b))).head?) source + · simpa only [statement, stepAux, tapes_third] using + ih (f state (source (.inr (.inr c))).head?) source + | pop k f next ih => + rcases k with a | b | c + · simp only [statement, stepAux, tapes_first] + rw [← tapes_update_first] + exact ih (f state (source (.inl a)).head?) + (Function.update source (.inl a) (source (.inl a)).tail) + · simp only [statement, stepAux, tapes_second] + rw [← tapes_update_second] + exact ih (f state (source (.inr (.inl b))).head?) + (Function.update source (.inr (.inl b)) (source (.inr (.inl b))).tail) + · simp only [statement, stepAux, tapes_third] + rw [← tapes_update_third] + exact ih (f state (source (.inr (.inr c))).head?) + (Function.update source (.inr (.inr c)) (source (.inr (.inr c))).tail) + | load f next ih => simpa only [statement, stepAux] using ih (f state) source + | branch f yes no ihYes ihNo => + cases h : f state with + | false => simpa only [statement, stepAux, h, Bool.cond_false] using ihNo state source + | true => simpa only [statement, stepAux, h, Bool.cond_true] using ihYes state source + | goto f => rfl + | halt => rfl + +def program (source : Λ → Stmt (Alphabet ΓA ΓB ΓC) Λ σ) : + Λ → Stmt (Alphabet ΓB ΓA ΓC) Λ σ := fun l => statement (source l) + +theorem step_simulation (source : Λ → Stmt (Alphabet ΓA ΓB ΓC) Λ σ) + (c : Cfg (Alphabet ΓA ΓB ΓC) Λ σ) : + step (program source) (configuration c) = (step source c).map configuration := by + cases c with + | mk l state sourceTapes => + cases l with + | none => rfl + | some l => + change some (stepAux (statement (source l)) state (tapes sourceTapes)) = _ + rw [stepAux_simulation] + rfl + +end MinUncutGames.Foundations.Complexity.MachineStackSwap + +end +section +namespace MinUncutGames.Foundations.Complexity.MachineSequential + +open Turing + +abbrev Tape (first second : FinTM2) := first.K ⊕ (second.K ⊕ Unit) +abbrev Symbols (first second : FinTM2) : Tape first second → Type := + MachineEmbedding.Alphabet first.Γ + (MachineEmbedding.Alphabet second.Γ (fun _ : Unit => second.Γ second.k₀)) +abbrev Label (first second : FinTM2) := first.Λ ⊕ (Bool ⊕ second.Λ) +abbrev Register (second : FinTM2) := Option (second.Γ second.k₀) +abbrev State (first second : FinTM2) := (first.σ × second.σ) × Register second + +def firstStates (first second : FinTM2) : + first.σ × (second.σ × Register second) ≃ State first second where + toFun st := ((st.1, st.2.1), st.2.2) + invFun st := (st.1.1, (st.1.2, st.2)) + left_inv _ := rfl + right_inv _ := rfl + +def secondStates (first second : FinTM2) : + second.σ × (first.σ × Register second) ≃ State first second where + toFun st := ((st.2.1, st.1), st.2.2) + invFun st := (st.1.2, (st.1.1, st.2)) + left_inv _ := rfl + right_inv _ := rfl + +def secondLabels (first second : FinTM2) : + second.Λ ⊕ (Bool ⊕ first.Λ) → Label first second + | .inl label => .inr (.inr label) + | .inr (.inl bit) => .inr (.inl bit) + | .inr (.inr label) => .inl label + +def bridgeLabel (first second : FinTM2) (bit : Bool) : Label first second := + .inr (.inl bit) + +def firstStatement (first second : FinTM2) (q : first.Stmt) : + TM2.Stmt (Symbols first second) (Label first second) (State first second) := + MachineControl.statement id (firstStates first second) + (MachineEmbedding.statement (some (bridgeLabel first second false)) q) + +def secondStatement (first second : FinTM2) (q : second.Stmt) : + TM2.Stmt (Symbols first second) (Label first second) (State first second) := + MachineControl.statement (secondLabels first second) (secondStates first second) + (MachineStackSwap.statement + (MachineEmbedding.statement + (Δ := MachineEmbedding.Alphabet first.Γ (fun _ : Unit => second.Γ second.k₀)) + (Λextra := Bool ⊕ first.Λ) none q)) + +def program (first second : FinTM2) + (relabel : first.Γ first.k₁ → second.Γ second.k₀) + (fallback : second.Γ second.k₀) : + Label first second → TM2.Stmt (Symbols first second) (Label first second) + (State first second) + | .inl label => firstStatement first second (first.m label) + | .inr (.inr label) => secondStatement first second (second.m label) + | .inr (.inl false) => + Reduction.MachineTransfer.loopAt (Γ := Symbols first second) + (.inl first.k₁) (.inr (.inr ())) relabel fallback + (bridgeLabel first second false) (some (bridgeLabel first second true)) + | .inr (.inl true) => + Reduction.MachineTransfer.loopAt (Γ := Symbols first second) + (.inr (.inr ())) (.inr (.inl second.k₀)) id fallback + (bridgeLabel first second true) (some (.inr (.inr second.main))) + +def machine (first second : FinTM2) + (relabel : first.Γ first.k₁ → second.Γ second.k₀) + (fallback : second.Γ second.k₀) : FinTM2 where + K := Tape first second + kFin := by + letI := first.kFin + letI := second.kFin + exact inferInstanceAs (Fintype (first.K ⊕ (second.K ⊕ Unit))) + k₀ := .inl first.k₀ + k₁ := .inr (.inl second.k₁) + Γ := Symbols first second + Λ := Label first second + ΛFin := by + letI := first.ΛFin + letI := second.ΛFin + exact inferInstanceAs (Fintype (first.Λ ⊕ (Bool ⊕ second.Λ))) + main := .inl first.main + σ := State first second + σFin := by + letI := first.σFin + letI := second.σFin + letI := second.Γk₀Fin + exact inferInstanceAs (Fintype ((first.σ × second.σ) × Option (second.Γ second.k₀))) + initialState := ((first.initialState, second.initialState), none) + Γk₀Fin := first.Γk₀Fin + m := program first second relabel fallback + +def firstConfiguration (first second : FinTM2) (c : first.Cfg) : + TM2.Cfg (Symbols first second) (Label first second) (State first second) := + MachineControl.configuration id (firstStates first second) + (MachineEmbedding.configuration (some (bridgeLabel first second false)) + (second.initialState, (none : Register second)) (fun _ => []) c) + +def secondConfiguration (first second : FinTM2) (c : second.Cfg) : + TM2.Cfg (Symbols first second) (Label first second) (State first second) := + MachineControl.configuration (secondLabels first second) (secondStates first second) + (MachineStackSwap.configuration + (MachineEmbedding.configuration + (Δ := MachineEmbedding.Alphabet first.Γ (fun _ : Unit => second.Γ second.k₀)) + (Λextra := Bool ⊕ first.Λ) none + (first.initialState, (none : Register second)) (fun _ => []) c)) + +theorem firstStep (first second : FinTM2) + (relabel : first.Γ first.k₁ → second.Γ second.k₀) + (fallback : second.Γ second.k₀) (a b : first.Cfg) + (transition : first.step a = some b) : + (machine first second relabel fallback).step (firstConfiguration first second a) = + some (firstConfiguration first second b) := by + cases a with + | mk label state tapes => + cases label with + | none => cases transition + | some label => + have hb := Option.some.inj transition + subst b + change some (TM2.stepAux + (MachineControl.statement id (firstStates first second) + (MachineEmbedding.statement (some (bridgeLabel first second false)) (first.m label))) + ((firstStates first second) (state, (second.initialState, none))) + (MachineEmbedding.tapes tapes (fun _ => []))) = _ + have controlled := MachineControl.stepAux_simulation id (firstStates first second) + (MachineEmbedding.statement + (Δ := MachineEmbedding.Alphabet second.Γ (fun _ : Unit => second.Γ second.k₀)) + (some (bridgeLabel first second false)) (first.m label)) + (state, (second.initialState, none)) (MachineEmbedding.tapes tapes (fun _ => [])) + have embedded := MachineEmbedding.stepAux_simulation + (Δ := MachineEmbedding.Alphabet second.Γ (fun _ : Unit => second.Γ second.k₀)) + (some (bridgeLabel first second false)) (second.initialState, (none : Register second)) + (fun _ => []) (first.m label) state tapes + exact congrArg some (controlled.trans + (congrArg (MachineControl.configuration id (firstStates first second)) embedded)) + +theorem secondStep (first second : FinTM2) + (relabel : first.Γ first.k₁ → second.Γ second.k₀) + (fallback : second.Γ second.k₀) (a b : second.Cfg) + (transition : second.step a = some b) : + (machine first second relabel fallback).step (secondConfiguration first second a) = + some (secondConfiguration first second b) := by + cases a with + | mk label state tapes => + cases label with + | none => cases transition + | some label => + have hb := Option.some.inj transition + subst b + change some (TM2.stepAux + (MachineControl.statement (secondLabels first second) (secondStates first second) + (MachineStackSwap.statement + (MachineEmbedding.statement + (Δ := MachineEmbedding.Alphabet first.Γ (fun _ : Unit => second.Γ second.k₀)) + (Λextra := Bool ⊕ first.Λ) none (second.m label)))) + ((secondStates first second) (state, (first.initialState, none))) + (MachineStackSwap.tapes (MachineEmbedding.tapes tapes (fun _ => [])))) = _ + rw [MachineControl.stepAux_simulation, MachineStackSwap.stepAux_simulation, + MachineEmbedding.stepAux_simulation] + rfl + +theorem firstConfiguration_init (first second : FinTM2) + (relabel : first.Γ first.k₁ → second.Γ second.k₀) + (fallback : second.Γ second.k₀) (input : List (first.Γ first.k₀)) : + firstConfiguration first second (initList first input) = + initList (machine first second relabel fallback) input := by + unfold firstConfiguration MachineControl.configuration MachineEmbedding.configuration initList + congr 1 + funext k + rcases k with k | k | k + · by_cases h : k = first.k₀ + · subst k + simp [machine, MachineEmbedding.tapes] + rfl + · simp [machine, MachineEmbedding.tapes, h] + · simp [machine, MachineEmbedding.tapes] + · simp [machine, MachineEmbedding.tapes] + +theorem secondConfiguration_halt (first second : FinTM2) + (relabel : first.Γ first.k₁ → second.Γ second.k₀) + (fallback : second.Γ second.k₀) (output : List (second.Γ second.k₁)) : + secondConfiguration first second (haltList second output) = + haltList (machine first second relabel fallback) output := by + unfold secondConfiguration MachineControl.configuration MachineStackSwap.configuration + MachineEmbedding.configuration haltList + congr 1 + funext k + rcases k with k | k | k + · simp [machine, MachineStackSwap.tapes, MachineEmbedding.tapes] + · by_cases h : k = second.k₁ + · subst k + simp [machine, MachineStackSwap.tapes, MachineEmbedding.tapes] + rfl + · simp [machine, MachineStackSwap.tapes, MachineEmbedding.tapes, h] + · simp [machine, MachineStackSwap.tapes, MachineEmbedding.tapes] + +def temporaryTapes (first second : FinTM2) (word : List (second.Γ second.k₀)) : + ∀ k, List (Symbols first second k) + | .inl _ => [] + | .inr (.inl _) => [] + | .inr (.inr _) => word + +def temporaryConfiguration (first second : FinTM2) (word : List (second.Γ second.k₀)) : + TM2.Cfg (Symbols first second) (Label first second) (State first second) := + ⟨some (bridgeLabel first second true), + ((first.initialState, second.initialState), none), temporaryTapes first second word⟩ + +theorem firstTransfer_tapes (first second : FinTM2) + (relabel : first.Γ first.k₁ → second.Γ second.k₀) + (word : List (first.Γ first.k₁)) : + Reduction.MachineTransfer.tapesAt (.inl first.k₁) (.inr (.inr ())) + (firstConfiguration first second (haltList first word)).stk [] (word.reverse.map relabel) = + temporaryTapes first second (word.reverse.map relabel) := by + funext k + rcases k with k | k | k + · by_cases h : k = first.k₁ + · subst k + simp [Reduction.MachineTransfer.tapesAt, temporaryTapes] + · simp [Reduction.MachineTransfer.tapesAt, temporaryTapes, firstConfiguration, + MachineControl.configuration, MachineEmbedding.configuration, MachineEmbedding.tapes, + haltList, h] + · simp [Reduction.MachineTransfer.tapesAt, temporaryTapes, firstConfiguration, + MachineControl.configuration, MachineEmbedding.configuration, MachineEmbedding.tapes] + · cases k + simp [Reduction.MachineTransfer.tapesAt, temporaryTapes] + +theorem secondTransfer_tapes (first second : FinTM2) (word : List (second.Γ second.k₀)) : + Reduction.MachineTransfer.tapesAt (Γ := Symbols first second) + (.inr (.inr ())) (.inr (.inl second.k₀)) + (temporaryTapes first second word) [] word.reverse = + (secondConfiguration first second (initList second word.reverse)).stk := by + funext k + rcases k with k | k | k + · simp [Reduction.MachineTransfer.tapesAt, temporaryTapes, secondConfiguration, + MachineControl.configuration, MachineStackSwap.configuration, MachineStackSwap.tapes, + MachineEmbedding.configuration, MachineEmbedding.tapes] + · by_cases h : k = second.k₀ + · subst k + simp [Reduction.MachineTransfer.tapesAt, secondConfiguration, + MachineControl.configuration, MachineStackSwap.configuration, MachineStackSwap.tapes, + MachineEmbedding.configuration, MachineEmbedding.tapes, initList] + · simp [Reduction.MachineTransfer.tapesAt, temporaryTapes, secondConfiguration, + MachineControl.configuration, MachineStackSwap.configuration, MachineStackSwap.tapes, + MachineEmbedding.configuration, MachineEmbedding.tapes, initList, h] + · cases k + simp [Reduction.MachineTransfer.tapesAt, secondConfiguration, + MachineControl.configuration, MachineStackSwap.configuration, MachineStackSwap.tapes, + MachineEmbedding.configuration, MachineEmbedding.tapes] + +def firstTransfer (first second : FinTM2) + (relabel : first.Γ first.k₁ → second.Γ second.k₀) + (fallback : second.Γ second.k₀) (word : List (first.Γ first.k₁)) : + StateTransition.EvalsToInTime (machine first second relabel fallback).step + (firstConfiguration first second (haltList first word)) + (some (temporaryConfiguration first second (word.reverse.map relabel))) + (word.length + 1) := by + let run := Reduction.MachineTransfer.transferAtInTime + (.inl first.k₁ : Tape first second) (.inr (.inr ())) (by intro h; cases h) + relabel fallback (bridgeLabel first second false) + (some (bridgeLabel first second true)) (program first second relabel fallback) rfl + (firstConfiguration first second (haltList first word)).stk + (first.initialState, second.initialState) none + have inputTape : (firstConfiguration first second (haltList first word)).stk (.inl first.k₁) = + word := by simp [firstConfiguration, MachineControl.configuration, + MachineEmbedding.configuration, MachineEmbedding.tapes, haltList] + have outputTape : + (firstConfiguration first second (haltList first word)).stk (.inr (.inr ())) = [] := rfl + rw [inputTape, outputTape, List.append_nil, firstTransfer_tapes] at run + exact run + +def secondTransfer (first second : FinTM2) + (relabel : first.Γ first.k₁ → second.Γ second.k₀) + (fallback : second.Γ second.k₀) (word : List (second.Γ second.k₀)) : + StateTransition.EvalsToInTime (machine first second relabel fallback).step + (temporaryConfiguration first second word) + (some (secondConfiguration first second (initList second word.reverse))) + (word.length + 1) := by + let run := Reduction.MachineTransfer.transferAtInTime + (.inr (.inr ()) : Tape first second) (.inr (.inl second.k₀)) (by intro h; cases h) + id fallback (bridgeLabel first second true) (some (.inr (.inr second.main))) + (program first second relabel fallback) rfl (temporaryTapes first second word) + (first.initialState, second.initialState) none + simp only [temporaryTapes, List.map_id, List.append_nil] at run + rw [secondTransfer_tapes] at run + exact run + +def execute (first second : FinTM2) + (relabel : first.Γ first.k₁ → second.Γ second.k₀) + (fallback : second.Γ second.k₀) + (input : List (first.Γ first.k₀)) (middle : List (first.Γ first.k₁)) + (output : List (second.Γ second.k₁)) (firstBudget secondBudget : Nat) + (runFirst : TM2OutputsInTime first input (some middle) firstBudget) + (runSecond : TM2OutputsInTime second (middle.map relabel) (some output) secondBudget) : + TM2OutputsInTime (machine first second relabel fallback) input (some output) + (firstBudget + 2 * (middle.length + 1) + secondBudget) := by + let start := MachineComposition.liftExecutionInTime first.step + (machine first second relabel fallback).step (firstConfiguration first second) + (firstStep first second relabel fallback) runFirst + let bridge₁ := firstTransfer first second relabel fallback middle + have bridge₂ := secondTransfer first second relabel fallback (middle.reverse.map relabel) + have reversal : (middle.reverse.map relabel).reverse = middle.map relabel := by + simp only [List.map_reverse, List.reverse_reverse] + rw [reversal] at bridge₂ + simp only [List.length_map, List.length_reverse] at bridge₂ + let finish := MachineComposition.liftExecutionInTime second.step + (machine first second relabel fallback).step (secondConfiguration first second) + (secondStep first second relabel fallback) runSecond + let phase₁₂ := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ start bridge₁ + let phase₁₂₃ := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ phase₁₂ bridge₂ + have full := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ phase₁₂₃ finish + rw [firstConfiguration_init, secondConfiguration_halt] at full + exact { + toEvalsTo := full.toEvalsTo + steps_le_m := by have h := full.steps_le_m; omega + } + +noncomputable def compose {α β γ αΓ βΓ γΓ : Type} + {ea : α → List αΓ} {eb : β → List βΓ} {ec : γ → List γΓ} + {f : α → β} {g : β → γ} + (first : TM2ComputableInPolyTime ea eb f) + (second : TM2ComputableInPolyTime eb ec g) (fallback : βΓ) : + TM2ComputableInPolyTime ea ec (fun a => g (f a)) := by + let relabel : first.tm.Γ first.tm.k₁ → second.tm.Γ second.tm.k₀ := + fun symbol => second.inputAlphabet.symm (first.outputAlphabet symbol) + let defaultSymbol := second.inputAlphabet.symm fallback + let intermediate : Polynomial Nat := Polynomial.X + + Polynomial.C (Runtime.programPushBound first.tm) * first.time + refine { + tm := machine first.tm second.tm relabel defaultSymbol + inputAlphabet := first.inputAlphabet + outputAlphabet := second.outputAlphabet + time := MachineComposition.compositionPolynomial first.time second.time intermediate + outputsFun := ?_ + } + intro a + let input := (ea a).map first.inputAlphabet.invFun + let middle := (eb (f a)).map first.outputAlphabet.invFun + let output := (ec (g (f a))).map second.outputAlphabet.invFun + have handoff : middle.map relabel = (eb (f a)).map second.inputAlphabet.invFun := by + dsimp only [middle, relabel] + simp only [List.map_map] + apply List.map_congr_left + intro symbol _ + exact congrArg second.inputAlphabet.symm (first.outputAlphabet.apply_symm_apply symbol) + have runSecond : TM2OutputsInTime second.tm (middle.map relabel) (some output) + (second.time.eval (eb (f a)).length) := by + rw [handoff] + exact second.outputsFun (f a) + have full := execute first.tm second.tm relabel defaultSymbol input middle output + (first.time.eval (ea a).length) (second.time.eval (eb (f a)).length) + (first.outputsFun a) runSecond + have intermediateBound : (eb (f a)).length ≤ intermediate.eval (ea a).length := + Runtime.encodedOutputLength first a + have totalBound := MachineComposition.compositionBudget_le first.time second.time + intermediate (ea a).length (eb (f a)).length intermediateBound + have middleLength : middle.length = (eb (f a)).length := by simp only [middle, List.length_map] + exact { + toEvalsTo := full.toEvalsTo + steps_le_m := by + apply Nat.le_trans full.steps_le_m + simpa only [middleLength] using totalBound + } + +noncomputable def composeBits {α β γ : Type} + {ea : α → List Bool} {eb : β → List Bool} {ec : γ → List Bool} + {f : α → β} {g : β → γ} + (first : TM2ComputableInPolyTime ea eb f) + (second : TM2ComputableInPolyTime eb ec g) : + TM2ComputableInPolyTime ea ec (fun a => g (f a)) := + compose first second false + +end MinUncutGames.Foundations.Complexity.MachineSequential + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineTableIteration.lean b/lean/OAI/Computability/MinUncut/Machines/MachineTableIteration.lean new file mode 100644 index 0000000000000000000000000000000000000000..2686405369d52065cb4505bf1facbfaad0c71021 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineTableIteration.lean @@ -0,0 +1,127 @@ +import Mathlib +import OAI.Computability.MinUncut.Games.GraphIterationBounds +import OAI.Computability.MinUncut.Games.FinalCNFOutput + +namespace OAI + +namespace MinUncutGames.Foundations.Complexity.MachineTableIteration + +open Turing PCP RoundTables GraphIterationBounds + +def finalTable (H : BaseTable) (input : Input) : GraphTables.Table := + TableIteration.runTables H (count input) input.val + +noncomputable def counterCertificate : TM2ComputableInPolyTime inputBits countedBits (id : Input → Input) where + toTM2ComputableAux := GraphCounterPrefix.computableInPolyTime.toTM2ComputableAux + time := GraphCounterPrefix.computableInPolyTime.time + outputsFun input := GraphCounterPrefix.computableInPolyTime.outputsFun input.val + +variable (H : BaseTable) + (body : TM2ComputableInPolyTime GraphTables.tableBits GraphTables.tableBits (build H)) + +noncomputable def countedCertificate : + TM2ComputableInPolyTime countedBits GraphTables.tableBits (finalTable H) where + tm := MachineRepeat.machine body.tm body.inputAlphabet body.outputAlphabet + inputAlphabet := body.inputAlphabet + outputAlphabet := body.inputAlphabet + time := runtimePolynomial body.time + outputsFun input := by + let budgets := fun i => body.time.eval (words H input i).length + have runs (i : Nat) (_hi : i < count input) : + TM2OutputsInTime body.tm ((words H input i).map body.inputAlphabet.symm) + (some ((words H input (i + 1)).map body.outputAlphabet.symm)) (budgets i) := by + exact body.outputsFun (TableIteration.runTables H i input.val) + let run := MachineRepeat.executeSequence body.tm body.inputAlphabet body.outputAlphabet + (count input) (words H input) budgets runs + have start : encodeWord (count input) ++ words H input 0 = countedBits input := rfl + have finish : words H input (count input) = GraphTables.tableBits (finalTable H input) := rfl + rw [start, finish] at run + refine { toEvalsTo := run.toEvalsTo, steps_le_m := ?_ } + let N := (countedBits input).length + let L := lengthPolynomial.eval N + let B := body.time.eval L + have hl (i : Nat) (hi : i ≤ count input) : (words H input i).length ≤ L := + intermediate_bits H input i hi + have hb (i : Nat) (hi : i < count input) : budgets i ≤ B := + MachineComposition.natPolynomial_eval_mono body.time (hl i hi.le) + have hloop := MachineRepeat.loopBudget_le (count input) (words H input) budgets B L hb hl + have hc : count input ≤ N + 1 := count_le input + rw [runtimePolynomial_eval] + calc + run.steps ≤ count input + 1 + MachineRepeat.loopBudget (count input) (words H input) budgets := + run.steps_le_m + _ ≤ count input + 1 + (count input * (B + 2 * L + 3) + 2 * L + 3) := + Nat.add_le_add_left hloop _ + _ = count input * (B + 2 * L + 4) + 2 * L + 4 := by ring + _ ≤ (N + 1) * (B + 2 * L + 4) + 2 * L + 4 := + Nat.add_le_add_right (Nat.add_le_add_right (Nat.mul_le_mul_right _ hc) _) _ + +noncomputable def computableInPolyTime : + TM2ComputableInPolyTime inputBits GraphTables.tableBits (finalTable H) := + MachineSequential.composeBits counterCertificate (countedCertificate H body) + +noncomputable def initialCertificate : + TM2ComputableInPolyTime formulaBits inputBits initial where + toTM2ComputableAux := MachineRawInitialTable.computableInPolyTime.toTM2ComputableAux + time := MachineRawInitialTable.computableInPolyTime.time + outputsFun F := MachineRawInitialTable.computableInPolyTime.outputsFun F + +noncomputable def tableCertificate : + TM2ComputableInPolyTime formulaBits GraphTables.tableBits (TableIteration.outputTable H) := by + change TM2ComputableInPolyTime formulaBits GraphTables.tableBits + (fun F => finalTable H (initial F)) + exact MachineSequential.composeBits (f := initial) (g := finalTable H) + initialCertificate (computableInPolyTime H body) + +noncomputable def gapMapCertificate : + TM2ComputableInPolyTime formulaBits formulaBits (TableIteration.gapMap H) := + MachineSequential.composeBits (f := TableIteration.outputTable H) (g := FinalTableFormula.output) + (tableCertificate H body) + FinalCNFMachine.Program.computableInPolyTime + +end MinUncutGames.Foundations.Complexity.MachineTableIteration + +namespace MinUncutGames.Foundations.Complexity.TableIterationFiniteAlphabet + +open PCP MachineFiniteAlphabet + +theorem initial : FiniteAlphabet MachineRawInitialTable.computableInPolyTime.tm := by + intro k + change Finite Bool + infer_instance + +theorem finalCNF : FiniteAlphabet FinalCNFMachine.Program.computableInPolyTime.tm := by + intro k + change Finite Bool + infer_instance + +theorem counter : FiniteAlphabet MachineTableIteration.counterCertificate.tm := by + intro k + change Finite Bool + infer_instance + +variable (H : RoundTables.BaseTable) + (body : Turing.TM2ComputableInPolyTime GraphTables.tableBits GraphTables.tableBits + (RoundTables.build H)) + (finiteBody : FiniteAlphabet body.tm) + +include finiteBody + +theorem counted : FiniteAlphabet (MachineTableIteration.countedCertificate H body).tm := + repeat_machine body.tm body.inputAlphabet body.outputAlphabet finiteBody + +theorem iteration : FiniteAlphabet (MachineTableIteration.computableInPolyTime H body).tm := + composeBits MachineTableIteration.counterCertificate + (MachineTableIteration.countedCertificate H body) counter (counted H body finiteBody) + +theorem table : FiniteAlphabet (MachineTableIteration.tableCertificate H body).tm := + composeBits MachineTableIteration.initialCertificate + (MachineTableIteration.computableInPolyTime H body) initial (iteration H body finiteBody) + +theorem gapMap : FiniteAlphabet (MachineTableIteration.gapMapCertificate H body).tm := + composeBits (MachineTableIteration.tableCertificate H body) + FinalCNFMachine.Program.computableInPolyTime (table H body finiteBody) finalCNF + +end MinUncutGames.Foundations.Complexity.TableIterationFiniteAlphabet + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineTransducer.lean b/lean/OAI/Computability/MinUncut/Machines/MachineTransducer.lean new file mode 100644 index 0000000000000000000000000000000000000000..81106dc2eb208b1e2a5cd4a6822d7f2ab00a89a4 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineTransducer.lean @@ -0,0 +1,834 @@ +import Mathlib +import OAI.Computability.MinUncut.Search.ArithmeticExpression +import OAI.Computability.MinUncut.Machines.MachineSubstitution + +namespace OAI + +section +namespace MinUncutGames.Reduction.MachineTransducer + +open Turing +open MinUncutGames.Foundations.Complexity +open MachineSubstitution (pushWord stepAux_pushWord statementPushBound_pushWord) + +def tapeStacks (input output : List Bool) : Bool → List Bool := + fun side => if side then output else input + +theorem update_input (input output replacement : List Bool) : + Function.update (tapeStacks input output) false replacement = tapeStacks replacement output := by + funext side + cases side <;> simp [tapeStacks] + +theorem update_output (input output replacement : List Bool) : + Function.update (tapeStacks input output) true replacement = tapeStacks input replacement := by + funext side + cases side <;> simp [tapeStacks] + +variable {Q : Type} [Fintype Q] + +def output (transition : Q → Bool → Q) (emit : Q → Bool → List Bool) : + Q → List Bool → List Bool + | _, [] => [] + | state, symbol :: input => + emit state symbol ++ output transition emit (transition state symbol) input + +def loop (initial : Q) : + TM2.Stmt (fun _ : Bool => Bool) (Option (Q × Bool)) (Q × Option Bool) := + .pop false (fun state head => (state.1, head)) + (.branch (fun state => state.2.isSome) + (.goto fun state => some (state.1, state.2.getD false)) + (.load (fun _ => (initial, none)) .halt)) + +def program (initial : Q) (transition : Q → Bool → Q) (emit : Q → Bool → List Bool) : + Option (Q × Bool) → + TM2.Stmt (fun _ : Bool => Bool) (Option (Q × Bool)) (Q × Option Bool) + | none => loop initial + | some (state, symbol) => + .load (fun register => (transition state symbol, register.2)) + (pushWord true (emit state symbol) (.goto fun _ => none)) + +def machine (initial : Q) (transition : Q → Bool → Q) (emit : Q → Bool → List Bool) : + FinTM2 where + K := Bool + k₀ := false + k₁ := true + Γ _ := Bool + Λ := Option (Q × Bool) + main := none + σ := Q × Option Bool + initialState := (initial, none) + m := program initial transition emit + +noncomputable def maxEmission (emit : Q → Bool → List Bool) : Nat := + Finset.univ.sup (fun pair : Q × Bool => (emit pair.1 pair.2).length) + +theorem emission_le (emit : Q → Bool → List Bool) (state : Q) (symbol : Bool) : + (emit state symbol).length ≤ maxEmission emit := by + exact Finset.le_sup (f := fun pair : Q × Bool => (emit pair.1 pair.2).length) + (Finset.mem_univ (state, symbol)) + +theorem statementPushBound_le (initial : Q) (transition : Q → Bool → Q) + (emit : Q → Bool → List Bool) (label : Option (Q × Bool)) : + Runtime.statementPushBound (program initial transition emit label) ≤ maxEmission emit := by + cases label with + | none => simp [program, loop, Runtime.statementPushBound] + | some pair => + simpa only [program, Runtime.statementPushBound, statementPushBound_pushWord, + Nat.add_zero] using emission_le emit pair.1 pair.2 + +theorem programPushBound_le (initial : Q) (transition : Q → Bool → Q) + (emit : Q → Bool → List Bool) : + Runtime.programPushBound (machine initial transition emit) ≤ maxEmission emit := by + have allLabels (labels : List (Option (Q × Bool))) : + Runtime.maxLabelPushes (program initial transition emit) labels ≤ maxEmission emit := by + induction labels with + | nil => exact Nat.zero_le _ + | cons label rest ih => + exact max_le (statementPushBound_le initial transition emit label) ih + exact allLabels (machine initial transition emit).ΛFin.elems.toList + +def running (initial : Q) (transition : Q → Bool → Q) (emit : Q → Bool → List Bool) + (state : Q) (input accumulator : List Bool) (register : Option Bool) : + (machine initial transition emit).Cfg := + ⟨some none, (state, register), tapeStacks input accumulator⟩ + +def emitting (initial : Q) (transition : Q → Bool → Q) (emit : Q → Bool → List Bool) + (oldState : Q) (symbol : Bool) (input accumulator : List Bool) + (state : Q × Option Bool) : (machine initial transition emit).Cfg := + ⟨some (some (oldState, symbol)), state, tapeStacks input accumulator⟩ + +def halted (initial : Q) (transition : Q → Bool → Q) (emit : Q → Bool → List Bool) + (accumulator : List Bool) : (machine initial transition emit).Cfg := + ⟨none, (initial, none), tapeStacks [] accumulator⟩ + +theorem step_empty (initial : Q) (transition : Q → Bool → Q) + (emit : Q → Bool → List Bool) (state : Q) (accumulator : List Bool) + (register : Option Bool) : + (machine initial transition emit).step + (running initial transition emit state [] accumulator register) = + some (halted initial transition emit accumulator) := by + change some (TM2.stepAux (loop initial) (state, register) (tapeStacks [] accumulator)) = _ + simp [loop, TM2.stepAux, tapeStacks, halted] + exact congrArg (fun st => (some ⟨none, (initial, none), st⟩ : + Option (TM2.Cfg (fun _ : Bool => Bool) (Option (Q × Bool)) (Q × Option Bool)))) + (update_input [] accumulator []) + +theorem step_cons (initial : Q) (transition : Q → Bool → Q) + (emit : Q → Bool → List Bool) (state : Q) (symbol : Bool) + (input accumulator : List Bool) (register : Option Bool) : + (machine initial transition emit).step + (running initial transition emit state (symbol :: input) accumulator register) = + some (emitting initial transition emit state symbol input accumulator (state, some symbol)) := by + change some (TM2.stepAux (loop initial) (state, register) + (tapeStacks (symbol :: input) accumulator)) = _ + simp [loop, TM2.stepAux, tapeStacks, emitting] + rw [update_input] + rfl + +theorem step_emit (initial : Q) (transition : Q → Bool → Q) + (emit : Q → Bool → List Bool) (oldState : Q) (symbol : Bool) + (input accumulator : List Bool) (state : Q × Option Bool) : + (machine initial transition emit).step + (emitting initial transition emit oldState symbol input accumulator state) = + some (running initial transition emit (transition oldState symbol) input + ((emit oldState symbol).reverse ++ accumulator) state.2) := by + change some (TM2.stepAux (pushWord true (emit oldState symbol) (.goto fun _ => none)) + (transition oldState symbol, state.2) (tapeStacks input accumulator)) = _ + rw [stepAux_pushWord] + simp only [TM2.stepAux] + change some (⟨some none, (transition oldState symbol, state.2), + Function.update (tapeStacks input accumulator) true + ((emit oldState symbol).reverse ++ accumulator)⟩ : + (machine initial transition emit).Cfg) = _ + exact congrArg (fun st => + (some ⟨some none, (transition oldState symbol, state.2), st⟩ : + Option (TM2.Cfg (fun _ : Bool => Bool) (Option (Q × Bool)) (Q × Option Bool)))) + (update_output input accumulator ((emit oldState symbol).reverse ++ accumulator)) + +def next (initial : Q) (transition : Q → Bool → Q) (emit : Q → Bool → List Bool) + (configuration : Option (machine initial transition emit).Cfg) : + Option (machine initial transition emit).Cfg := + configuration.bind (machine initial transition emit).step + +theorem two_steps_cons (initial : Q) (transition : Q → Bool → Q) + (emit : Q → Bool → List Bool) (state : Q) (symbol : Bool) + (input accumulator : List Bool) (register : Option Bool) : + (next initial transition emit)^[2] + (some (running initial transition emit state (symbol :: input) accumulator register)) = + some (running initial transition emit (transition state symbol) input + ((emit state symbol).reverse ++ accumulator) (some symbol)) := by + change (machine initial transition emit).step + (running initial transition emit state (symbol :: input) accumulator register) >>= + (machine initial transition emit).step = _ + rw [step_cons] + exact step_emit initial transition emit state symbol input accumulator (state, some symbol) + +theorem transduce_steps (initial : Q) (transition : Q → Bool → Q) + (emit : Q → Bool → List Bool) (state : Q) (input accumulator : List Bool) + (register : Option Bool) : + (next initial transition emit)^[2 * input.length + 1] + (some (running initial transition emit state input accumulator register)) = + some (halted initial transition emit ((output transition emit state input).reverse ++ accumulator)) := by + induction input generalizing state accumulator register with + | nil => + simpa only [List.length_nil, Nat.mul_zero, Nat.zero_add, Function.iterate_one, next, + Option.bind_some, output, List.reverse_nil, List.nil_append] + using step_empty initial transition emit state accumulator register + | cons symbol input ih => + rw [List.length_cons] + rw [show 2 * (input.length + 1) + 1 = (2 * input.length + 1) + 2 by omega] + rw [Function.iterate_add_apply, two_steps_cons, ih] + simp only [output, List.reverse_append, List.append_assoc] + +theorem initList_eq (initial : Q) (transition : Q → Bool → Q) + (emit : Q → Bool → List Bool) (input : List Bool) : + initList (machine initial transition emit) input = + running initial transition emit initial input [] none := by + unfold initList running + congr 1 + funext side + cases side <;> rfl + +theorem haltList_eq (initial : Q) (transition : Q → Bool → Q) + (emit : Q → Bool → List Bool) (accumulator : List Bool) : + haltList (machine initial transition emit) accumulator = + halted initial transition emit accumulator := by + unfold haltList halted + congr 1 + +theorem transduce_init_steps (initial : Q) (transition : Q → Bool → Q) + (emit : Q → Bool → List Bool) (input : List Bool) : + (next initial transition emit)^[2 * input.length + 1] + (some (initList (machine initial transition emit) input)) = + some (haltList (machine initial transition emit) (output transition emit initial input).reverse) := by + rw [initList_eq, haltList_eq] + simpa only [List.append_nil] using transduce_steps initial transition emit initial input [] none + +def outputsInTime (initial : Q) (transition : Q → Bool → Q) + (emit : Q → Bool → List Bool) (input : List Bool) : + TM2OutputsInTime (machine initial transition emit) input + (some (output transition emit initial input).reverse) (2 * input.length + 1) where + steps := 2 * input.length + 1 + evals_in_steps := transduce_init_steps initial transition emit input + steps_le_m := Nat.le_refl _ + +@[simp] theorem outputsInTime_steps (initial : Q) (transition : Q → Bool → Q) + (emit : Q → Bool → List Bool) (input : List Bool) : + (outputsInTime initial transition emit input).steps = 2 * input.length + 1 := rfl + +noncomputable def reversedComputableInPolyTime (initial : Q) (transition : Q → Bool → Q) + (emit : Q → Bool → List Bool) : + TM2ComputableInPolyTime (id : List Bool → List Bool) id + (fun input => (output transition emit initial input).reverse) where + tm := machine initial transition emit + inputAlphabet := Equiv.refl Bool + outputAlphabet := Equiv.refl Bool + time := 2 * Polynomial.X + 1 + outputsFun input := by + change TM2OutputsInTime (machine initial transition emit) (input.map id) + (some ((output transition emit initial input).reverse.map id)) + ((2 * Polynomial.X + 1 : Polynomial Nat).eval input.length) + have hi := @List.map_id ((machine initial transition emit).Γ + (machine initial transition emit).k₀) input + have ho := @List.map_id ((machine initial transition emit).Γ + (machine initial transition emit).k₁) (output transition emit initial input).reverse + rw [hi, ho] + simpa only [Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_X, + Polynomial.eval_ofNat, Polynomial.eval_one] using outputsInTime initial transition emit input + +noncomputable def computableInPolyTime (initial : Q) (transition : Q → Bool → Q) + (emit : Q → Bool → List Bool) : + TM2ComputableInPolyTime (id : List Bool → List Bool) id + (output transition emit initial) := by + simpa only [List.reverse_reverse] using + MachineSequential.composeBits (reversedComputableInPolyTime initial transition emit) + MachineReverse.computableInPolyTime + +end MinUncutGames.Reduction.MachineTransducer + +end +section +namespace MinUncutGames.Foundations.Complexity.MachineTransducerCopy + +open Turing +open Reduction.MachineSubstitution (pushWord stepAux_pushWord) + +variable {K Λ σ Q : Type} [DecidableEq K] + +abbrev Alphabet (K : Type) (_ : K) := Bool +abbrev State (σ Q : Type) := (σ × Q) × Option Bool + +def scanLoop (source scratch : K) (initial : Q) + (emitterLabel : Q → Bool → Λ) (restoreLabel : Λ) : + TM2.Stmt (Alphabet K) Λ (State σ Q) := + .pop source (fun state head => (state.1, head)) + (.branch (fun state => state.2.isSome) + (.push scratch (fun state => state.2.getD false) + (.goto fun state => emitterLabel state.1.2 (state.2.getD false))) + (.load (fun state => ((state.1.1, initial), none)) (.goto fun _ => restoreLabel))) + +def emitter (destination : K) (transition : Q → Bool → Q) + (emit : Q → Bool → List Bool) (scanLabel : Λ) (control : Q) (symbol : Bool) : + TM2.Stmt (Alphabet K) Λ (State σ Q) := + .load (fun state => ((state.1.1, transition control symbol), state.2)) + (pushWord destination (emit control symbol) (.goto fun _ => scanLabel)) + +abbrev tapes (source scratch destination : K) (base : K → List Bool) + (input scratchWord outputWord : List Bool) : K → List Bool := + MachineCopy.forkTapes source scratch destination base input scratchWord outputWord + +theorem update_source (source scratch destination : K) + (sourceScratch : source ≠ scratch) (sourceDestination : source ≠ destination) + (scratchDestination : scratch ≠ destination) (base : K → List Bool) + (input scratchWord outputWord replacement : List Bool) : + Function.update (tapes source scratch destination base input scratchWord outputWord) + source replacement = tapes source scratch destination base replacement scratchWord outputWord := by + funext k + by_cases hs : k = source + · subst k; simp [tapes, MachineCopy.forkTapes, sourceScratch, sourceDestination] + · by_cases ht : k = scratch + · subst k; simp [tapes, MachineCopy.forkTapes, Ne.symm sourceScratch, scratchDestination] + · by_cases hd : k = destination + · subst k; simp [tapes, MachineCopy.forkTapes, Ne.symm sourceDestination] + · simp [tapes, MachineCopy.forkTapes, hs, ht, hd] + +theorem update_scratch (source scratch destination : K) + (scratchDestination : scratch ≠ destination) (base : K → List Bool) + (input scratchWord outputWord replacement : List Bool) : + Function.update (tapes source scratch destination base input scratchWord outputWord) + scratch replacement = tapes source scratch destination base input replacement outputWord := by + funext k + by_cases ht : k = scratch + · subst k; simp [tapes, MachineCopy.forkTapes, scratchDestination] + · by_cases hd : k = destination + · subst k; simp [tapes, MachineCopy.forkTapes, Ne.symm scratchDestination] + · simp [tapes, MachineCopy.forkTapes, ht, hd] + +theorem update_output (source scratch destination : K) (base : K → List Bool) + (input scratchWord outputWord replacement : List Bool) : + Function.update (tapes source scratch destination base input scratchWord outputWord) + destination replacement = tapes source scratch destination base input scratchWord replacement := by + simp [tapes, MachineCopy.forkTapes] + +theorem scanStep_empty (source scratch destination : K) + (sourceScratch : source ≠ scratch) (sourceDestination : source ≠ destination) + (scratchDestination : scratch ≠ destination) + (initial : Q) (scanLabel restoreLabel : Λ) (emitterLabel : Q → Bool → Λ) + (program : Λ → TM2.Stmt (Alphabet K) Λ (State σ Q)) + (atScan : program scanLabel = scanLoop source scratch initial emitterLabel restoreLabel) + (base : K → List Bool) (scratchWord outputWord : List Bool) + (ambient : σ) (control : Q) (register : Option Bool) : + TM2.step program ⟨some scanLabel, ((ambient, control), register), + tapes source scratch destination base [] scratchWord outputWord⟩ = + some ⟨some restoreLabel, ((ambient, initial), none), + tapes source scratch destination base [] scratchWord outputWord⟩ := by + change some (TM2.stepAux (program scanLabel) ((ambient, control), register) + (tapes source scratch destination base [] scratchWord outputWord)) = _ + rw [atScan] + simp [scanLoop, TM2.stepAux, sourceScratch, sourceDestination, scratchDestination, + update_source] + +theorem scanStep_cons (source scratch destination : K) + (sourceScratch : source ≠ scratch) (sourceDestination : source ≠ destination) + (scratchDestination : scratch ≠ destination) + (initial : Q) (scanLabel restoreLabel : Λ) (emitterLabel : Q → Bool → Λ) + (program : Λ → TM2.Stmt (Alphabet K) Λ (State σ Q)) + (atScan : program scanLabel = scanLoop source scratch initial emitterLabel restoreLabel) + (base : K → List Bool) (symbol : Bool) (input scratchWord outputWord : List Bool) + (ambient : σ) (control : Q) (register : Option Bool) : + TM2.step program ⟨some scanLabel, ((ambient, control), register), + tapes source scratch destination base (symbol :: input) scratchWord outputWord⟩ = + some ⟨some (emitterLabel control symbol), ((ambient, control), some symbol), + tapes source scratch destination base input (symbol :: scratchWord) outputWord⟩ := by + change some (TM2.stepAux (program scanLabel) ((ambient, control), register) + (tapes source scratch destination base (symbol :: input) scratchWord outputWord)) = _ + rw [atScan] + simp [scanLoop, TM2.stepAux, sourceScratch, sourceDestination, scratchDestination, + update_source, update_scratch] + +theorem emitterStep (source scratch destination : K) + (transition : Q → Bool → Q) (emit : Q → Bool → List Bool) + (scanLabel : Λ) (emitterLabel : Q → Bool → Λ) + (program : Λ → TM2.Stmt (Alphabet K) Λ (State σ Q)) + (atEmitter : ∀ control symbol, program (emitterLabel control symbol) = + emitter destination transition emit scanLabel control symbol) + (base : K → List Bool) (input scratchWord outputWord : List Bool) + (ambient : σ) (control : Q) (symbol : Bool) : + TM2.step program ⟨some (emitterLabel control symbol), ((ambient, control), some symbol), + tapes source scratch destination base input scratchWord outputWord⟩ = + some ⟨some scanLabel, ((ambient, transition control symbol), some symbol), + tapes source scratch destination base input scratchWord + ((emit control symbol).reverse ++ outputWord)⟩ := by + change some (TM2.stepAux (program (emitterLabel control symbol)) ((ambient, control), some symbol) + (tapes source scratch destination base input scratchWord outputWord)) = _ + rw [atEmitter] + simp only [emitter, TM2.stepAux] + rw [stepAux_pushWord] + simp only [TM2.stepAux, MachineCopy.forkTapes_right] + rw [update_output] + +theorem twoSteps_cons (source scratch destination : K) + (sourceScratch : source ≠ scratch) (sourceDestination : source ≠ destination) + (scratchDestination : scratch ≠ destination) + (initial : Q) (transition : Q → Bool → Q) (emit : Q → Bool → List Bool) + (scanLabel restoreLabel : Λ) (emitterLabel : Q → Bool → Λ) + (program : Λ → TM2.Stmt (Alphabet K) Λ (State σ Q)) + (atScan : program scanLabel = scanLoop source scratch initial emitterLabel restoreLabel) + (atEmitter : ∀ control symbol, program (emitterLabel control symbol) = + emitter destination transition emit scanLabel control symbol) + (base : K → List Bool) (symbol : Bool) (input scratchWord outputWord : List Bool) + (ambient : σ) (control : Q) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[2] + (some ⟨some scanLabel, ((ambient, control), register), + tapes source scratch destination base (symbol :: input) scratchWord outputWord⟩) = + some ⟨some scanLabel, ((ambient, transition control symbol), some symbol), + tapes source scratch destination base input (symbol :: scratchWord) + ((emit control symbol).reverse ++ outputWord)⟩ := by + change (TM2.step program ⟨some scanLabel, ((ambient, control), register), + tapes source scratch destination base (symbol :: input) scratchWord outputWord⟩).bind + (TM2.step program) = _ + rw [scanStep_cons source scratch destination sourceScratch sourceDestination scratchDestination + initial scanLabel restoreLabel emitterLabel program atScan base symbol input scratchWord + outputWord ambient control register] + exact emitterStep source scratch destination transition emit scanLabel emitterLabel program + atEmitter base input (symbol :: scratchWord) outputWord ambient control symbol + +theorem scanTrace (source scratch destination : K) + (sourceScratch : source ≠ scratch) (sourceDestination : source ≠ destination) + (scratchDestination : scratch ≠ destination) + (initial : Q) (transition : Q → Bool → Q) (emit : Q → Bool → List Bool) + (scanLabel restoreLabel : Λ) (emitterLabel : Q → Bool → Λ) + (program : Λ → TM2.Stmt (Alphabet K) Λ (State σ Q)) + (atScan : program scanLabel = scanLoop source scratch initial emitterLabel restoreLabel) + (atEmitter : ∀ control symbol, program (emitterLabel control symbol) = + emitter destination transition emit scanLabel control symbol) + (base : K → List Bool) (input scratchWord outputWord : List Bool) + (ambient : σ) (control : Q) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[2 * input.length + 1] + (some ⟨some scanLabel, ((ambient, control), register), + tapes source scratch destination base input scratchWord outputWord⟩) = + some ⟨some restoreLabel, ((ambient, initial), none), + tapes source scratch destination base [] (input.reverse ++ scratchWord) + ((Reduction.MachineTransducer.output transition emit control input).reverse ++ outputWord)⟩ := by + induction input generalizing control scratchWord outputWord register with + | nil => + simpa only [List.length_nil, Nat.mul_zero, Nat.zero_add, Function.iterate_one, + MachineComposition.advance_some, Reduction.MachineTransducer.output, List.reverse_nil, + List.nil_append] using + scanStep_empty source scratch destination sourceScratch sourceDestination scratchDestination + initial scanLabel restoreLabel emitterLabel program atScan base scratchWord outputWord + ambient control register + | cons symbol input ih => + rw [List.length_cons, show 2 * (input.length + 1) + 1 = (2 * input.length + 1) + 2 by omega, + Function.iterate_add_apply] + rw [twoSteps_cons source scratch destination sourceScratch sourceDestination scratchDestination + initial transition emit scanLabel restoreLabel emitterLabel program atScan atEmitter base + symbol input scratchWord outputWord ambient control register, ih] + simp only [Reduction.MachineTransducer.output, List.reverse_append, List.reverse_cons, + List.append_assoc, List.singleton_append] + +theorem restoreTapes (source scratch destination : K) + (sourceScratch : source ≠ scratch) (sourceDestination : source ≠ destination) + (scratchDestination : scratch ≠ destination) + (base : K → List Bool) (scratchEmpty : base scratch = []) (outputWord : List Bool) : + Reduction.MachineTransfer.tapesAt scratch source + (tapes source scratch destination base [] (base source).reverse outputWord) + [] (base source) = Function.update base destination outputWord := by + funext k + by_cases hs : k = source + · subst k; simp [Reduction.MachineTransfer.tapesAt, sourceDestination] + · by_cases ht : k = scratch + · subst k + simp [Reduction.MachineTransfer.tapesAt, Ne.symm sourceScratch, scratchDestination, scratchEmpty] + · by_cases hd : k = destination + · subst k + simp [Reduction.MachineTransfer.tapesAt, tapes, MachineCopy.forkTapes, + Ne.symm sourceDestination, Ne.symm scratchDestination] + · simp [Reduction.MachineTransfer.tapesAt, tapes, MachineCopy.forkTapes, hs, ht, hd] + +theorem transduceCopyTrace (source scratch destination : K) + (sourceScratch : source ≠ scratch) (sourceDestination : source ≠ destination) + (scratchDestination : scratch ≠ destination) + (initial : Q) (transition : Q → Bool → Q) (emit : Q → Bool → List Bool) + (scanLabel restoreLabel : Λ) (emitterLabel : Q → Bool → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet K) Λ (State σ Q)) + (atScan : program scanLabel = scanLoop source scratch initial emitterLabel restoreLabel) + (atEmitter : ∀ control symbol, program (emitterLabel control symbol) = + emitter destination transition emit scanLabel control symbol) + (atRestore : program restoreLabel = + Reduction.MachineTransfer.loopAt scratch source id false restoreLabel exit) + (base : K → List Bool) (scratchEmpty : base scratch = []) + (ambient : σ) (control : Q) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[3 * (base source).length + 2] + (some ⟨some scanLabel, ((ambient, control), register), base⟩) = + some ⟨exit, ((ambient, initial), none), + Function.update base destination + ((Reduction.MachineTransducer.output transition emit control (base source)).reverse ++ + base destination)⟩ := by + have scan := scanTrace source scratch destination sourceScratch sourceDestination scratchDestination + initial transition emit scanLabel restoreLabel emitterLabel program atScan atEmitter base + (base source) (base scratch) (base destination) ambient control register + have tapesSelf : tapes source scratch destination base (base source) (base scratch) + (base destination) = base := MachineCopy.forkTapes_self source scratch destination base + rw [tapesSelf] at scan + simp only [scratchEmpty, List.append_nil] at scan + let outputWord := + (Reduction.MachineTransducer.output transition emit control (base source)).reverse ++ base destination + let scanned := tapes source scratch destination base [] (base source).reverse outputWord + have restore := Reduction.MachineTransfer.transferAt_fromTapes scratch source (Ne.symm sourceScratch) + id false restoreLabel exit program atRestore scanned (ambient, initial) none + change (MachineComposition.advance (TM2.step program))^[(scanned scratch).length + 1] + (some ⟨some restoreLabel, ((ambient, initial), none), scanned⟩) = _ at restore + have scratchWord : scanned scratch = (base source).reverse := by + simp [scanned, scratchDestination] + have sourceWord : scanned source = [] := by + simp [scanned, sourceScratch, sourceDestination] + rw [scratchWord, sourceWord] at restore + simp only [List.map_id, List.reverse_reverse, List.append_nil, List.length_reverse] at restore + rw [restoreTapes source scratch destination sourceScratch sourceDestination scratchDestination + base scratchEmpty outputWord] at restore + rw [show 3 * (base source).length + 2 = + ((base source).length + 1) + (2 * (base source).length + 1) by omega, + Function.iterate_add_apply, scan] + exact restore + +def transduceCopyInTime (source scratch destination : K) + (sourceScratch : source ≠ scratch) (sourceDestination : source ≠ destination) + (scratchDestination : scratch ≠ destination) + (initial : Q) (transition : Q → Bool → Q) (emit : Q → Bool → List Bool) + (scanLabel restoreLabel : Λ) (emitterLabel : Q → Bool → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet K) Λ (State σ Q)) + (atScan : program scanLabel = scanLoop source scratch initial emitterLabel restoreLabel) + (atEmitter : ∀ control symbol, program (emitterLabel control symbol) = + emitter destination transition emit scanLabel control symbol) + (atRestore : program restoreLabel = + Reduction.MachineTransfer.loopAt scratch source id false restoreLabel exit) + (base : K → List Bool) (scratchEmpty : base scratch = []) + (ambient : σ) (control : Q) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some scanLabel, ((ambient, control), register), base⟩ + (some ⟨exit, ((ambient, initial), none), Function.update base destination + ((Reduction.MachineTransducer.output transition emit control (base source)).reverse ++ + base destination)⟩) + (3 * (base source).length + 2) where + steps := 3 * (base source).length + 2 + evals_in_steps := transduceCopyTrace source scratch destination sourceScratch sourceDestination + scratchDestination initial transition emit scanLabel restoreLabel emitterLabel exit program + atScan atEmitter atRestore base scratchEmpty ambient control register + steps_le_m := Nat.le_refl _ + +omit [DecidableEq K] in +theorem scanLoop_pushBound (source scratch : K) (initial : Q) + (emitterLabel : Q → Bool → Λ) (restoreLabel : Λ) : + Runtime.statementPushBound (scanLoop (σ := σ) source scratch initial emitterLabel restoreLabel) = 1 := by + simp [scanLoop, Runtime.statementPushBound] + +omit [DecidableEq K] in +theorem emitter_pushBound (destination : K) (transition : Q → Bool → Q) + (emit : Q → Bool → List Bool) (scanLabel : Λ) (control : Q) (symbol : Bool) : + Runtime.statementPushBound (emitter (σ := σ) destination transition emit scanLabel control symbol) = + (emit control symbol).length := by + simp [emitter, Runtime.statementPushBound, Reduction.MachineSubstitution.statementPushBound_pushWord] + +end MinUncutGames.Foundations.Complexity.MachineTransducerCopy + +end +section +namespace MinUncutGames.Foundations.Complexity.MachineUnaryMultiply + +open Turing +open scoped BigOperators + +inductive Label + | copyDrain | copyFork | seed | guard | scan | emitFalse | emitTrue | restore | finish + deriving DecidableEq + +protected abbrev Label.enumList : List Label := [.copyDrain, .copyFork, .seed, .guard, .scan, + .emitFalse, .emitTrue, .restore, .finish] + +protected theorem Label.enumList_getElem?_ctorIdx_eq (x : Label) : + Label.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem Label.enumList_nodup : Label.enumList.Nodup := by decide + +instance : Fintype Label where + elems := ⟨Label.enumList, Label.enumList_nodup⟩ + complete x := by cases x <;> decide + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool +abbrev State (σ : Type) := (σ × Unit) × Option Bool + +def transition (_ : Unit) (_ : Bool) : Unit := () +def payload (_ : Unit) (bit : Bool) : List Bool := if bit then [true] else [] + +def emitterLabel (labels : Label → Λ) (_ : Unit) (bit : Bool) : Λ := + if bit then labels .emitTrue else labels .emitFalse + +def statement (slots : Fin 5 ↪ K) (labels : Label → Λ) (exit : Option Λ) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (State σ) + | .copyDrain => Reduction.MachineTransfer.loopAt (slots 1) (slots 4) id false + (labels .copyDrain) (some (labels .copyFork)) + | .copyFork => MachineCopy.forkLoop (slots 4) (slots 1) (slots 3) false + (labels .copyFork) (some (labels .seed)) + | .seed => .push (slots 2) (fun _ => false) (.goto fun _ => labels .guard) + | .guard => MachineUnaryCounter.guard (slots 3) (labels .scan) (labels .finish) + | .scan => MachineTransducerCopy.scanLoop (slots 0) (slots 4) () + (emitterLabel labels) (labels .restore) + | .emitFalse => MachineTransducerCopy.emitter (slots 2) transition payload (labels .scan) () false + | .emitTrue => MachineTransducerCopy.emitter (slots 2) transition payload (labels .scan) () true + | .restore => Reduction.MachineTransfer.loopAt (slots 4) (slots 0) id false + (labels .restore) (some (labels .guard)) + | .finish => .pop (slots 3) (fun state _ => (state.1, none)) + (Reduction.MachineTransfer.exitAt (slots 2) exit) + +def program (slots : Fin 5 ↪ K) : Label → TM2.Stmt (Alphabet (K := K)) Label (State σ) := + statement slots id none + +def machine : FinTM2 where + K := Fin 5 + k₀ := 0 + k₁ := 2 + Γ _ := Bool + Λ := Label + main := .copyDrain + σ := State Unit + initialState := (((), ()), none) + m := program (Function.Embedding.refl (Fin 5)) + +def resultTapes (slots : Fin 5 ↪ K) (base : K → List Bool) (product : ℕ) : K → List Bool := + Function.update base (slots 2) (encodeWord product ++ base (slots 2)) + +@[simp] theorem resultTapes_output (slots : Fin 5 ↪ K) (base : K → List Bool) (p : ℕ) : + resultTapes slots base p (slots 2) = encodeWord p ++ base (slots 2) := by + simp [resultTapes] + +theorem resultTapes_other (slots : Fin 5 ↪ K) (base : K → List Bool) (p : ℕ) + (k : K) (hk : k ≠ slots 2) : resultTapes slots base p k = base k := by + simp [resultTapes, hk] + +def bodySteps (a : ℕ) : ℕ := 3 * (a + 1) + 2 +def steps (a b : ℕ) : ℕ := 3 * a * b + 8 * b + 7 + +theorem output_encodeWord (a : ℕ) : + Reduction.MachineTransducer.output transition payload () (encodeWord a) = + List.replicate a true := by + induction a with + | zero => simp [encodeWord, Reduction.MachineTransducer.output, payload] + | succ a ih => + simpa only [encodeWord, List.replicate_succ, List.cons_append, + Reduction.MachineTransducer.output, payload, Bool.cond_true, transition, + ite_true, List.singleton_append, List.nil_append] using congrArg (List.cons true) ih + +private theorem prepend_payload (a p : ℕ) (suffix : List Bool) : + List.replicate a true ++ (encodeWord p ++ suffix) = encodeWord (a + p) ++ suffix := by + simp only [encodeWord, List.replicate_add, List.append_assoc] + +def loopBase (slots : Fin 5 ↪ K) (base : K → List Bool) (a b r : ℕ) : K → List Bool := + resultTapes slots base (a * (b - r)) + +theorem bodyTrace (slots : Fin 5 ↪ K) (labels : Label → Λ) (exit : Option Λ) + (p : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ label, p (labels label) = statement slots labels exit label) + (base : K → List Bool) (a b r : ℕ) (hr : r < b) + (operand : base (slots 0) = encodeWord a) (scratchEmpty : base (slots 4) = []) + (ambient : σ) : + (MachineComposition.advance (TM2.step p))^[bodySteps a] + (some (MachineCountedLoop.bodyConfiguration (slots 3) (labels .scan) [] + (fun _ => (ambient, ())) (loopBase slots base a b) r)) = + some (MachineCountedLoop.guardConfiguration (slots 3) (labels .guard) [] + (fun _ => (ambient, ())) (fun _ => none) (loopBase slots base a b) r) := by + have h04 : slots 0 ≠ slots 4 := slots.injective.ne (by decide) + have h02 : slots 0 ≠ slots 2 := slots.injective.ne (by decide) + have h42 : slots 4 ≠ slots 2 := slots.injective.ne (by decide) + have h03 : slots 0 ≠ slots 3 := slots.injective.ne (by decide) + have h43 : slots 4 ≠ slots 3 := slots.injective.ne (by decide) + have h23 : slots 2 ≠ slots 3 := slots.injective.ne (by decide) + let start := MachineUnaryCounter.counterTapes (slots 3) (loopBase slots base a b (r + 1)) r [] + have hstartA : start (slots 0) = encodeWord a := by + simp [start, MachineUnaryCounter.counterTapes, loopBase, resultTapes, h03, h02, operand] + have hstartScratch : start (slots 4) = [] := by + simp [start, MachineUnaryCounter.counterTapes, loopBase, resultTapes, h43, h42, scratchEmpty] + have hscan : p (labels .scan) = MachineTransducerCopy.scanLoop (slots 0) (slots 4) () + (emitterLabel labels) (labels .restore) := atLabels .scan + have hemit : ∀ control bit, p (emitterLabel labels control bit) = + MachineTransducerCopy.emitter (slots 2) transition payload (labels .scan) control bit := by + intro control bit + cases control + cases bit <;> exact atLabels _ + have hrestore : p (labels .restore) = Reduction.MachineTransfer.loopAt (slots 4) (slots 0) + id false (labels .restore) (some (labels .guard)) := atLabels .restore + have hcopy := MachineTransducerCopy.transduceCopyTrace (slots 0) (slots 4) (slots 2) + h04 h02 h42 () transition payload (labels .scan) (labels .restore) (emitterLabel labels) + (some (labels .guard)) p hscan hemit hrestore start hstartScratch ambient () none + rw [hstartA, output_encodeWord, List.reverse_replicate] at hcopy + have hcount : a + a * (b - (r + 1)) = a * (b - r) := by + have hr' : b - r = b - (r + 1) + 1 := by omega + rw [hr'] + ring + have hfinish : Function.update start (slots 2) + (List.replicate a true ++ start (slots 2)) = + MachineUnaryCounter.counterTapes (slots 3) (loopBase slots base a b r) r [] := by + funext k + by_cases hk2 : k = slots 2 + · subst k + simp only [Function.update_self] + simp only [start, MachineUnaryCounter.counterTapes_other (slots 3) (slots 2) h23, + loopBase, resultTapes_output] + rw [prepend_payload, hcount] + · by_cases hk3 : k = slots 3 + · subst k + simp [start, MachineUnaryCounter.counterTapes, hk2] + · simp [start, MachineUnaryCounter.counterTapes, loopBase, resultTapes, hk2, hk3] + rw [hfinish] at hcopy + simpa only [bodySteps, encodeWord, List.length_append, List.length_replicate, + List.length_singleton, MachineCountedLoop.bodyConfiguration, + MachineCountedLoop.guardConfiguration] using hcopy + +private theorem totalSteps_eq (a b : ℕ) : + MachineCountedLoop.totalSteps (fun _ => bodySteps a) b = b * (bodySteps a + 1) + 1 := by + simp [MachineCountedLoop.totalSteps, Nat.mul_add, Nat.add_assoc] + +theorem multiplyTrace (slots : Fin 5 ↪ K) (labels : Label → Λ) (exit : Option Λ) + (p : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ label, p (labels label) = statement slots labels exit label) + (base : K → List Bool) (a b : ℕ) + (operandA : base (slots 0) = encodeWord a) + (operandB : base (slots 1) = encodeWord b) + (counterEmpty : base (slots 3) = []) (scratchEmpty : base (slots 4) = []) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step p))^[steps a b] + (some ⟨some (labels .copyDrain), ((ambient, ()), register), base⟩) = + some ⟨exit, ((ambient, ()), none), resultTapes slots base (a * b)⟩ := by + have h13 : slots 1 ≠ slots 3 := slots.injective.ne (by decide) + have h14 : slots 1 ≠ slots 4 := slots.injective.ne (by decide) + have h34 : slots 3 ≠ slots 4 := slots.injective.ne (by decide) + have h23 : slots 2 ≠ slots 3 := slots.injective.ne (by decide) + let copied := Function.update base (slots 3) (encodeWord b) + have hcopy : (MachineComposition.advance (TM2.step p))^[2 * (b + 2)] + (some ⟨some (labels .copyDrain), ((ambient, ()), register), base⟩) = + some ⟨some (labels .seed), ((ambient, ()), none), copied⟩ := by + have h := MachineCopy.copyTrace (slots 1) (slots 3) (slots 4) h13 h14 h34 false + (labels .copyDrain) (labels .copyFork) (some (labels .seed)) p + (atLabels .copyDrain) (atLabels .copyFork) base scratchEmpty (ambient, ()) register + simpa only [copied, operandB, counterEmpty, List.append_nil, encodeWord, List.length_append, + List.length_replicate, List.length_singleton, Nat.add_assoc, Nat.reduceAdd] using h + have hseedTapes : Function.update copied (slots 2) (false :: copied (slots 2)) = + MachineUnaryCounter.counterTapes (slots 3) (loopBase slots base a b b) b [] := by + funext k + by_cases hk2 : k = slots 2 + · subst k + simp [copied, MachineUnaryCounter.counterTapes, loopBase, resultTapes, h23, encodeWord] + · by_cases hk3 : k = slots 3 + · subst k + simp [copied, MachineUnaryCounter.counterTapes, hk2] + · simp [copied, MachineUnaryCounter.counterTapes, loopBase, resultTapes, hk2, hk3] + have hseed : (MachineComposition.advance (TM2.step p))^[1] + (some ⟨some (labels .seed), ((ambient, ()), none), copied⟩) = + some (MachineCountedLoop.guardConfiguration (slots 3) (labels .guard) [] + (fun _ => (ambient, ())) (fun _ => none) (loopBase slots base a b) b) := by + change some (TM2.stepAux (p (labels .seed)) ((ambient, ()), none) copied) = _ + rw [atLabels .seed] + change some (⟨some (labels .guard), ((ambient, ()), none), + Function.update copied (slots 2) (false :: copied (slots 2))⟩ : + TM2.Cfg (Alphabet (K := K)) Λ (State σ)) = _ + rw [hseedTapes] + rfl + have hloop := MachineCountedLoop.loopTrace (slots 3) (labels .guard) (labels .scan) + (labels .finish) p (atLabels .guard) [] (fun _ => (ambient, ())) (fun _ => none) + (loopBase slots base a b) (fun _ => bodySteps a) b + (fun r hr => bodyTrace slots labels exit p atLabels base a b r hr operandA scratchEmpty ambient) + let finalCounter := MachineUnaryCounter.counterTapes (slots 3) (loopBase slots base a b 0) 0 [] + have hfinishTapes : Function.update finalCounter (slots 3) ((finalCounter (slots 3)).tail) = + resultTapes slots base (a * b) := by + funext k + by_cases hk3 : k = slots 3 + · subst k + simp [finalCounter, MachineUnaryCounter.counterTapes, encodeWord, resultTapes, + Ne.symm h23, counterEmpty] + · simp [finalCounter, MachineUnaryCounter.counterTapes, loopBase, hk3] + have hfinish : (MachineComposition.advance (TM2.step p))^[1] + (some (MachineCountedLoop.exitConfiguration (slots 3) (labels .finish) [] + (fun _ => (ambient, ())) (loopBase slots base a b))) = + some ⟨exit, ((ambient, ()), none), resultTapes slots base (a * b)⟩ := by + change some (TM2.stepAux (p (labels .finish)) ((ambient, ()), none) finalCounter) = _ + rw [atLabels .finish] + cases exit <;> + simpa only [statement, TM2.stepAux, Reduction.MachineTransfer.exitAt] using + congrArg (fun tapes => some (⟨_, ((ambient, ()), none), tapes⟩ : + TM2.Cfg (Alphabet (K := K)) Λ (State σ))) hfinishTapes + rw [show steps a b = 1 + (MachineCountedLoop.totalSteps (fun _ => bodySteps a) b + + (1 + 2 * (b + 2))) by rw [totalSteps_eq]; unfold steps bodySteps; ring] + rw [Function.iterate_add_apply, Function.iterate_add_apply, Function.iterate_add_apply, + hcopy, hseed, hloop] + exact hfinish + +def multiplyInTime (slots : Fin 5 ↪ K) (labels : Label → Λ) (exit : Option Λ) + (p : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ label, p (labels label) = statement slots labels exit label) + (base : K → List Bool) (a b : ℕ) + (operandA : base (slots 0) = encodeWord a) + (operandB : base (slots 1) = encodeWord b) + (counterEmpty : base (slots 3) = []) (scratchEmpty : base (slots 4) = []) + (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step p) + ⟨some (labels .copyDrain), ((ambient, ()), register), base⟩ + (some ⟨exit, ((ambient, ()), none), resultTapes slots base (a * b)⟩) (steps a b) where + steps := steps a b + evals_in_steps := multiplyTrace slots labels exit p atLabels base a b operandA operandB + counterEmpty scratchEmpty ambient register + steps_le_m := Nat.le_refl _ + +noncomputable def timePolynomial : Polynomial ℕ := + Polynomial.C 3 * Polynomial.X ^ 2 + Polynomial.C 8 * Polynomial.X + Polynomial.C 7 + +theorem steps_le_timePolynomial (a b : ℕ) : + steps a b ≤ timePolynomial.eval (a + b + 2) := by + have ha : a ≤ a + b + 2 := by omega + have hb : b ≤ a + b + 2 := by omega + have hab := Nat.mul_le_mul ha hb + simp only [timePolynomial, Polynomial.eval_add, Polynomial.eval_mul, + Polynomial.eval_C, Polynomial.eval_pow, Polynomial.eval_X] + unfold steps + nlinarith + +theorem multiplyFrame (slots : Fin 5 ↪ K) (base : K → List Bool) (a b : ℕ) + (k : K) (hk : k ≠ slots 2) : + resultTapes slots base (a * b) k = base k := resultTapes_other slots base _ k hk + +theorem programTrace (slots : Fin 5 ↪ K) (base : K → List Bool) (a b : ℕ) + (operandA : base (slots 0) = encodeWord a) + (operandB : base (slots 1) = encodeWord b) + (counterEmpty : base (slots 3) = []) (scratchEmpty : base (slots 4) = []) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step (program (σ := σ) slots)))^[steps a b] + (some ⟨some .copyDrain, ((ambient, ()), register), base⟩) = + some ⟨none, ((ambient, ()), none), resultTapes slots base (a * b)⟩ := + multiplyTrace slots id none (program slots) (fun _ => rfl) base a b + operandA operandB counterEmpty scratchEmpty ambient register + +def programInPolynomialTime (slots : Fin 5 ↪ K) (base : K → List Bool) (a b : ℕ) + (operandA : base (slots 0) = encodeWord a) + (operandB : base (slots 1) = encodeWord b) + (counterEmpty : base (slots 3) = []) (scratchEmpty : base (slots 4) = []) + (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step (program (σ := σ) slots)) + ⟨some .copyDrain, ((ambient, ()), register), base⟩ + (some ⟨none, ((ambient, ()), none), resultTapes slots base (a * b)⟩) + (timePolynomial.eval ((encodeWord a).length + (encodeWord b).length)) where + steps := steps a b + evals_in_steps := programTrace slots base a b operandA operandB counterEmpty scratchEmpty ambient register + steps_le_m := by + have hlength : (encodeWord a).length + (encodeWord b).length = a + b + 2 := by + simp only [encodeWord, List.length_append, List.length_replicate, List.length_singleton] + omega + rw [hlength] + exact steps_le_timePolynomial a b + +end MinUncutGames.Foundations.Complexity.MachineUnaryMultiply + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineTupleOdometer.lean b/lean/OAI/Computability/MinUncut/Machines/MachineTupleOdometer.lean new file mode 100644 index 0000000000000000000000000000000000000000..eb65cc8c49cea214617c79859da33da26d5eefae --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineTupleOdometer.lean @@ -0,0 +1,702 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineUnaryAdd + +namespace OAI + +namespace MinUncutGames.Foundations.Complexity.MachineTupleOdometer + +open Turing +open Reduction.MachineTransfer + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool + +abbrev digitTapes (current remaining : K) (base : K → List Bool) (d r : ℕ) + (currentSuffix remainingSuffix : List Bool) : K → List Bool := + MachineUnaryAddAt.unaryTapes current remaining base d r currentSuffix remainingSuffix + +def increment (current remaining : K) (doneLabel resetLabel : Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) := + .peek remaining (fun state head => (state.1, head)) + (.branch (fun state => state.2.getD false) + (.pop remaining (fun state _ => (state.1, none)) + (.push current (fun _ => true) (.goto fun _ => doneLabel))) + (.load (fun state => (state.1, none)) (.goto fun _ => resetLabel))) + +def reset (current remaining : K) (resetLabel carryLabel : Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) := + MachineUnaryAddAt.loop current remaining resetLabel (some carryLabel) + +omit [DecidableEq K] in +theorem incrementPushBound (current remaining : K) (doneLabel resetLabel : Λ) : + Runtime.statementPushBound (increment (σ := σ) current remaining doneLabel resetLabel) = + 1 := rfl + +omit [DecidableEq K] in +theorem resetPushBound (current remaining : K) (resetLabel carryLabel : Λ) : + Runtime.statementPushBound (reset (σ := σ) current remaining resetLabel carryLabel) = + 1 := rfl + +private theorem update_current (current remaining : K) (distinct : current ≠ remaining) + (base : K → List Bool) (input output replacement : List Bool) : + Function.update (tapesAt current remaining base input output) current replacement = + tapesAt current remaining base replacement output := by + funext k + by_cases hc : k = current + · subst k; simp [tapesAt, distinct] + · by_cases hr : k = remaining + · subst k; simp [tapesAt, Ne.symm distinct] + · simp [tapesAt, hc, hr] + +private theorem update_remaining (current remaining : K) + (base : K → List Bool) (input output replacement : List Bool) : + Function.update (tapesAt current remaining base input output) remaining replacement = + tapesAt current remaining base input replacement := by + simp [tapesAt] + +theorem stepAux_increment_succ (current remaining : K) (distinct : current ≠ remaining) + (doneLabel resetLabel : Λ) (base : K → List Bool) (d r : ℕ) + (currentSuffix remainingSuffix : List Bool) (ambient : σ) (register : Option Bool) : + TM2.stepAux (increment current remaining doneLabel resetLabel) (ambient, register) + (digitTapes current remaining base d (r + 1) currentSuffix remainingSuffix) = + ⟨some doneLabel, (ambient, none), + digitTapes current remaining base (d + 1) r currentSuffix remainingSuffix⟩ := by + simp [increment, TM2.stepAux, digitTapes, MachineUnaryAddAt.unaryTapes, + distinct, encodeWord, List.replicate_succ, update_current, update_remaining] + +theorem stepAux_increment_zero (current remaining : K) (distinct : current ≠ remaining) + (doneLabel resetLabel : Λ) (base : K → List Bool) (d : ℕ) + (currentSuffix remainingSuffix : List Bool) (ambient : σ) (register : Option Bool) : + TM2.stepAux (increment current remaining doneLabel resetLabel) (ambient, register) + (digitTapes current remaining base d 0 currentSuffix remainingSuffix) = + ⟨some resetLabel, (ambient, none), + digitTapes current remaining base d 0 currentSuffix remainingSuffix⟩ := by + simp [increment, TM2.stepAux, digitTapes, MachineUnaryAddAt.unaryTapes, + distinct, encodeWord] + +theorem incrementStep_succ (current remaining : K) (distinct : current ≠ remaining) + (checkLabel doneLabel resetLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atCheck : program checkLabel = increment current remaining doneLabel resetLabel) + (base : K → List Bool) (d r : ℕ) (currentSuffix remainingSuffix : List Bool) + (ambient : σ) (register : Option Bool) : + TM2.step program ⟨some checkLabel, (ambient, register), + digitTapes current remaining base d (r + 1) currentSuffix remainingSuffix⟩ = + some ⟨some doneLabel, (ambient, none), + digitTapes current remaining base (d + 1) r currentSuffix remainingSuffix⟩ := by + change some (TM2.stepAux (program checkLabel) (ambient, register) _) = _ + rw [atCheck, stepAux_increment_succ current remaining distinct] + +theorem incrementStep_zero (current remaining : K) (distinct : current ≠ remaining) + (checkLabel doneLabel resetLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atCheck : program checkLabel = increment current remaining doneLabel resetLabel) + (base : K → List Bool) (d : ℕ) (currentSuffix remainingSuffix : List Bool) + (ambient : σ) (register : Option Bool) : + TM2.step program ⟨some checkLabel, (ambient, register), + digitTapes current remaining base d 0 currentSuffix remainingSuffix⟩ = + some ⟨some resetLabel, (ambient, none), + digitTapes current remaining base d 0 currentSuffix remainingSuffix⟩ := by + change some (TM2.stepAux (program checkLabel) (ambient, register) _) = _ + rw [atCheck, stepAux_increment_zero current remaining distinct] + +theorem resetTrace (current remaining : K) (distinct : current ≠ remaining) + (resetLabel carryLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atReset : program resetLabel = reset current remaining resetLabel carryLabel) + (base : K → List Bool) (d r : ℕ) (currentSuffix remainingSuffix : List Bool) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[d + 1] + (some ⟨some resetLabel, (ambient, register), + digitTapes current remaining base d r currentSuffix remainingSuffix⟩) = + some ⟨some carryLabel, (ambient, none), + digitTapes current remaining base 0 (d + r) currentSuffix remainingSuffix⟩ := + MachineUnaryAddAt.addTrace current remaining distinct resetLabel (some carryLabel) + program atReset base d r currentSuffix remainingSuffix ambient register + +theorem carryTrace (current remaining : K) (distinct : current ≠ remaining) + (checkLabel doneLabel resetLabel carryLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atCheck : program checkLabel = increment current remaining doneLabel resetLabel) + (atReset : program resetLabel = reset current remaining resetLabel carryLabel) + (base : K → List Bool) (d : ℕ) (currentSuffix remainingSuffix : List Bool) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[d + 2] + (some ⟨some checkLabel, (ambient, register), + digitTapes current remaining base d 0 currentSuffix remainingSuffix⟩) = + some ⟨some carryLabel, (ambient, none), + digitTapes current remaining base 0 d currentSuffix remainingSuffix⟩ := by + rw [show d + 2 = (d + 1) + 1 by omega, Function.iterate_succ_apply] + change (MachineComposition.advance (TM2.step program))^[d + 1] + (TM2.step program ⟨some checkLabel, (ambient, register), + digitTapes current remaining base d 0 currentSuffix remainingSuffix⟩) = _ + rw [incrementStep_zero current remaining distinct checkLabel doneLabel resetLabel + program atCheck] + simpa only [Nat.add_zero] using resetTrace current remaining distinct resetLabel carryLabel + program atReset base d 0 currentSuffix remainingSuffix ambient none + +def digitSteps (d r : ℕ) : ℕ := if r = 0 then d + 2 else 1 + +theorem digitTrace (current remaining : K) (distinct : current ≠ remaining) + (checkLabel doneLabel resetLabel carryLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atCheck : program checkLabel = increment current remaining doneLabel resetLabel) + (atReset : program resetLabel = reset current remaining resetLabel carryLabel) + (base : K → List Bool) (d r : ℕ) (currentSuffix remainingSuffix : List Bool) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[digitSteps d r] + (some ⟨some checkLabel, (ambient, register), + digitTapes current remaining base d r currentSuffix remainingSuffix⟩) = + some ⟨some (if r = 0 then carryLabel else doneLabel), (ambient, none), + digitTapes current remaining base (if r = 0 then 0 else d + 1) + (if r = 0 then d else r - 1) currentSuffix remainingSuffix⟩ := by + cases r with + | zero => + simpa only [digitSteps, ↓reduceIte] using carryTrace current remaining distinct + checkLabel doneLabel resetLabel carryLabel program atCheck atReset base d + currentSuffix remainingSuffix ambient register + | succ r => + simpa only [digitSteps, Nat.succ_ne_zero, ↓reduceIte, Nat.add_sub_cancel, + Function.iterate_one, MachineComposition.advance_some] using + incrementStep_succ current remaining distinct checkLabel doneLabel resetLabel + program atCheck base d r currentSuffix remainingSuffix ambient register + +omit [DecidableEq K] in +theorem digitSteps_le (n d r : ℕ) (hn : 0 < n) (budget : d + r = n - 1) : + digitSteps d r ≤ n + 1 := by + unfold digitSteps + split <;> omega + +omit [DecidableEq K] in +theorem digitBudget (n d r : ℕ) (_hn : 0 < n) (budget : d + r = n - 1) : + (if r = 0 then 0 else d + 1) + (if r = 0 then d else r - 1) = n - 1 := by + by_cases hr : r = 0 <;> simp only [hr, ↓reduceIte] <;> omega + +theorem digitFrame (current remaining other : K) + (notCurrent : other ≠ current) (notRemaining : other ≠ remaining) + (base : K → List Bool) (d r : ℕ) (currentSuffix remainingSuffix : List Bool) : + digitTapes current remaining base (if r = 0 then 0 else d + 1) + (if r = 0 then d else r - 1) currentSuffix remainingSuffix other = + digitTapes current remaining base d r currentSuffix remainingSuffix other := by + simp only [digitTapes, MachineUnaryAddAt.unaryTapes_other current remaining other + notCurrent notRemaining] + +def digitInTime (current remaining : K) (distinct : current ≠ remaining) + (checkLabel doneLabel resetLabel carryLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atCheck : program checkLabel = increment current remaining doneLabel resetLabel) + (atReset : program resetLabel = reset current remaining resetLabel carryLabel) + (base : K → List Bool) (n d r : ℕ) (hn : 0 < n) (budget : d + r = n - 1) + (currentSuffix remainingSuffix : List Bool) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some checkLabel, (ambient, register), + digitTapes current remaining base d r currentSuffix remainingSuffix⟩ + (some ⟨some (if r = 0 then carryLabel else doneLabel), (ambient, none), + digitTapes current remaining base (if r = 0 then 0 else d + 1) + (if r = 0 then d else r - 1) currentSuffix remainingSuffix⟩) (n + 1) where + steps := digitSteps d r + evals_in_steps := digitTrace current remaining distinct checkLabel doneLabel resetLabel + carryLabel program atCheck atReset base d r currentSuffix remainingSuffix ambient register + steps_le_m := digitSteps_le n d r hn budget + +section AscendingCycle + +open scoped BigOperators + +def bodyConfiguration (current remaining : K) (bodyLabel : Λ) + (maximum remainder : ℕ) (currentSuffix remainingSuffix : List Bool) + (ambient : ℕ → σ) (base : ℕ → K → List Bool) : + TM2.Cfg (Alphabet (K := K)) Λ (σ × Option Bool) := + ⟨some bodyLabel, (ambient (remainder + 1), none), + digitTapes current remaining (base (remainder + 1)) (maximum - remainder) + remainder currentSuffix remainingSuffix⟩ + +def checkConfiguration (current remaining : K) (checkLabel : Λ) + (maximum remainder : ℕ) (currentSuffix remainingSuffix : List Bool) + (ambient : ℕ → σ) (register : ℕ → Option Bool) (base : ℕ → K → List Bool) : + TM2.Cfg (Alphabet (K := K)) Λ (σ × Option Bool) := + ⟨some checkLabel, (ambient remainder, register remainder), + digitTapes current remaining (base remainder) (maximum - remainder) + remainder currentSuffix remainingSuffix⟩ + +def cycleExit (current remaining : K) (exitLabel : Λ) + (maximum : ℕ) (currentSuffix remainingSuffix : List Bool) + (ambient : ℕ → σ) (base : ℕ → K → List Bool) : + TM2.Cfg (Alphabet (K := K)) Λ (σ × Option Bool) := + ⟨some exitLabel, (ambient 0, none), + digitTapes current remaining (base 0) 0 maximum currentSuffix remainingSuffix⟩ + +def VisitTraces (current remaining : K) (bodyLabel checkLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (maximum count : ℕ) (currentSuffix remainingSuffix : List Bool) + (ambient : ℕ → σ) (register : ℕ → Option Bool) (base : ℕ → K → List Bool) + (cost : ℕ → ℕ) : Prop := + ∀ r, r ≤ count → (MachineComposition.advance (TM2.step program))^[cost r] + (some (bodyConfiguration current remaining bodyLabel maximum r + currentSuffix remainingSuffix ambient base)) = + some (checkConfiguration current remaining checkLabel maximum r + currentSuffix remainingSuffix ambient register base) + +def cycleSteps (cost : ℕ → ℕ) (maximum count : ℕ) : ℕ := + (∑ r ∈ Finset.range (count + 1), cost r) + count + maximum + 2 + +private theorem cycleSteps_zero (cost : ℕ → ℕ) (maximum : ℕ) : + cycleSteps cost maximum 0 = (maximum + 2) + cost 0 := by + simp [cycleSteps, Nat.add_comm, Nat.add_left_comm, Nat.add_assoc] + +private theorem cycleSteps_succ (cost : ℕ → ℕ) (maximum count : ℕ) : + cycleSteps cost maximum (count + 1) = + (cycleSteps cost maximum count + 1) + cost (count + 1) := by + simp only [cycleSteps, Finset.sum_range_succ] + omega + +theorem cycleTrace (current remaining : K) (distinct : current ≠ remaining) + (bodyLabel checkLabel resetLabel exitLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atCheck : program checkLabel = increment current remaining bodyLabel resetLabel) + (atReset : program resetLabel = reset current remaining resetLabel exitLabel) + (maximum count : ℕ) (hcount : count ≤ maximum) + (currentSuffix remainingSuffix : List Bool) (ambient : ℕ → σ) + (register : ℕ → Option Bool) (base : ℕ → K → List Bool) (cost : ℕ → ℕ) + (visits : VisitTraces current remaining bodyLabel checkLabel program maximum count + currentSuffix remainingSuffix ambient register base cost) : + (MachineComposition.advance (TM2.step program))^[cycleSteps cost maximum count] + (some (bodyConfiguration current remaining bodyLabel maximum count + currentSuffix remainingSuffix ambient base)) = + some (cycleExit current remaining exitLabel maximum + currentSuffix remainingSuffix ambient base) := by + induction count with + | zero => + rw [cycleSteps_zero, Function.iterate_add_apply, visits 0 (Nat.le_refl 0)] + simpa only [checkConfiguration, cycleExit, Nat.sub_zero] using + carryTrace current remaining distinct checkLabel bodyLabel resetLabel exitLabel + program atCheck atReset (base 0) maximum currentSuffix remainingSuffix + (ambient 0) (register 0) + | succ count ih => + rw [cycleSteps_succ, Function.iterate_add_apply, visits (count + 1) (Nat.le_refl _), + Function.iterate_succ_apply] + change (MachineComposition.advance (TM2.step program))^[cycleSteps cost maximum count] + (TM2.step program ⟨some checkLabel, (ambient (count + 1), register (count + 1)), + digitTapes current remaining (base (count + 1)) (maximum - (count + 1)) + (count + 1) currentSuffix remainingSuffix⟩) = _ + rw [incrementStep_succ current remaining distinct checkLabel bodyLabel resetLabel + program atCheck] + have hnext : maximum - (count + 1) + 1 = maximum - count := by omega + rw [hnext] + exact ih (by omega) (fun r hr => visits r (by omega)) + +def ascendingCycleInTime (current remaining : K) (distinct : current ≠ remaining) + (bodyLabel checkLabel resetLabel exitLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atCheck : program checkLabel = increment current remaining bodyLabel resetLabel) + (atReset : program resetLabel = reset current remaining resetLabel exitLabel) + (n : ℕ) (hn : 0 < n) (currentSuffix remainingSuffix : List Bool) + (ambient : ℕ → σ) (register : ℕ → Option Bool) (base : ℕ → K → List Bool) + (cost : ℕ → ℕ) (B : ℕ) + (visits : VisitTraces current remaining bodyLabel checkLabel program (n - 1) (n - 1) + currentSuffix remainingSuffix ambient register base cost) + (bodyBound : ∀ r, r < n → cost r ≤ B) : + StateTransition.EvalsToInTime (TM2.step program) + (bodyConfiguration current remaining bodyLabel (n - 1) (n - 1) + currentSuffix remainingSuffix ambient base) + (some (cycleExit current remaining exitLabel (n - 1) + currentSuffix remainingSuffix ambient base)) (n * (B + 2)) where + steps := cycleSteps cost (n - 1) (n - 1) + evals_in_steps := cycleTrace current remaining distinct bodyLabel checkLabel resetLabel exitLabel + program atCheck atReset (n - 1) (n - 1) (Nat.le_refl _) currentSuffix remainingSuffix + ambient register base cost visits + steps_le_m := by + have hsum : (∑ r ∈ Finset.range n, cost r) ≤ n * B := by + calc + _ ≤ ∑ _r ∈ Finset.range n, B := + Finset.sum_le_sum (fun r hr => bodyBound r (Finset.mem_range.mp hr)) + _ = _ := by simp + have hn' : n - 1 + 1 = n := by omega + simp only [cycleSteps, hn', Nat.mul_add] at * + omega + +end AscendingCycle + +section Order + +omit [DecidableEq K] + +open scoped BigOperators + +def tupleOrder (n q : ℕ) : List (Fin q → Fin n) := + List.ofFn (finFunctionFinEquiv (m := n) (n := q)).symm + +theorem tupleOrder_length (n q : ℕ) : (tupleOrder n q).length = n ^ q := by + simp [tupleOrder] + +theorem tupleOrder_dimension_zero (n : ℕ) : + tupleOrder n 0 = [fun i => Fin.elim0 i] := by + simp only [tupleOrder, pow_zero, List.ofFn_succ, List.ofFn_zero, List.cons.injEq, + and_true] + funext i + exact Fin.elim0 i + +theorem tupleOrder_radix_zero {q : ℕ} (hq : 0 < q) : tupleOrder 0 q = [] := by + apply List.length_eq_zero_iff.mp + rw [tupleOrder_length, Nat.zero_pow hq] + +theorem tupleRank_cons {n q : ℕ} (d : Fin n) (tail : Fin q → Fin n) : + (finFunctionFinEquiv (Fin.cons d tail)).val = + d.val + n * (finFunctionFinEquiv tail).val := by + rw [finFunctionFinEquiv_apply, Fin.sum_univ_succ] + simp only [Fin.cons_zero, Fin.cons_succ, Fin.val_zero, Fin.val_succ, pow_zero, mul_one] + congr 1 + rw [finFunctionFinEquiv_apply, Finset.mul_sum] + apply Finset.sum_congr rfl + intro i _ + simp [pow_succ, Nat.mul_comm, Nat.mul_left_comm] + +theorem tupleRank_increment_lowest {n q : ℕ} (d d' : Fin n) + (tail : Fin q → Fin n) (hsucc : d'.val = d.val + 1) : + (finFunctionFinEquiv (Fin.cons d' tail)).val = + (finFunctionFinEquiv (Fin.cons d tail)).val + 1 := by + rw [tupleRank_cons, tupleRank_cons, hsucc] + omega + +theorem tupleRank_carry {n q : ℕ} (hn : 0 < n) (d : Fin n) + (tail tail' : Fin q → Fin n) (hmax : d.val = n - 1) + (htail : (finFunctionFinEquiv tail').val = (finFunctionFinEquiv tail).val + 1) : + (finFunctionFinEquiv (Fin.cons (⟨0, hn⟩ : Fin n) tail')).val = + (finFunctionFinEquiv (Fin.cons d tail)).val + 1 := by + rw [tupleRank_cons, tupleRank_cons, htail, hmax] + simp only [Nat.zero_add, Nat.mul_add, Nat.mul_one] + omega + +theorem tupleRank_snoc {n q : ℕ} (tail : Fin q → Fin n) (d : Fin n) : + (finFunctionFinEquiv (Fin.snoc tail d)).val = + (finFunctionFinEquiv tail).val + d.val * n ^ q := by + rw [finFunctionFinEquiv_apply, Fin.sum_univ_castSucc] + simp only [Fin.snoc_castSucc, Fin.snoc_last, Fin.val_castSucc, Fin.val_last] + rfl + +theorem tupleOrder_snoc (n q : ℕ) : + tupleOrder n (q + 1) = (List.ofFn (fun d : Fin n => d)).flatMap + (fun d => (tupleOrder n q).map (fun tail => Fin.snoc tail d)) := by + change List.ofFn (fun rank : Fin (n ^ q * n) => + (finFunctionFinEquiv (m := n) (n := q + 1)).symm rank) = _ + rw [List.ofFn_mul'] + simp only [tupleOrder, List.flatMap_def, List.map_ofFn] + apply congrArg List.flatten + apply congrArg List.ofFn + funext d + apply congrArg List.ofFn + funext rank + dsimp only [Function.comp_apply] + apply finFunctionFinEquiv.injective + apply Fin.ext + erw [Equiv.apply_symm_apply, tupleRank_snoc, Equiv.apply_symm_apply] + simp [Nat.mul_comm, Nat.add_comm] + +end Order + +section Nested + +open scoped BigOperators + +structure CycleSchedule (K σ : Type) where + currentSuffix : List Bool + remainingSuffix : List Bool + ambient : ℕ → σ + register : ℕ → Option Bool + base : ℕ → K → List Bool + +abbrev Configuration (K Λ σ : Type) := + TM2.Cfg (Alphabet (K := K)) Λ (σ × Option Bool) + +inductive NestedCycle (n : ℕ) (current remaining : ℕ → K) (bodyLabel : Λ) + (checkLabel resetLabel : ℕ → Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) : + ℕ → Λ → Configuration K Λ σ → Configuration K Λ σ → Type where + | leaf (exitLabel : Λ) (start finish : Configuration K Λ σ) (count : ℕ) + (atBody : start.l = some bodyLabel) (atExit : finish.l = some exitLabel) + (run : (MachineComposition.advance (TM2.step program))^[count] (some start) = some finish) : + NestedCycle n current remaining bodyLabel checkLabel resetLabel program + 0 exitLabel start finish + | node (depth : ℕ) (exitLabel : Λ) (positive : 0 < n) + (distinct : current depth ≠ remaining depth) + (atCheck : program (checkLabel depth) = + increment (current depth) (remaining depth) bodyLabel (resetLabel depth)) + (atReset : program (resetLabel depth) = + reset (current depth) (remaining depth) (resetLabel depth) exitLabel) + (s : CycleSchedule K σ) + (children : ∀ r : Fin n, + NestedCycle n current remaining bodyLabel checkLabel resetLabel program + depth (checkLabel depth) + (bodyConfiguration (current depth) (remaining depth) bodyLabel (n - 1) r.val + s.currentSuffix s.remainingSuffix s.ambient s.base) + (checkConfiguration (current depth) (remaining depth) (checkLabel depth) (n - 1) r.val + s.currentSuffix s.remainingSuffix s.ambient s.register s.base)) : + NestedCycle n current remaining bodyLabel checkLabel resetLabel program + (depth + 1) exitLabel + (bodyConfiguration (current depth) (remaining depth) bodyLabel (n - 1) (n - 1) + s.currentSuffix s.remainingSuffix s.ambient s.base) + (cycleExit (current depth) (remaining depth) exitLabel (n - 1) + s.currentSuffix s.remainingSuffix s.ambient s.base) + +omit [DecidableEq K] in + +def counterOverhead (n : ℕ) : ℕ → ℕ + | 0 => 0 + | q + 1 => n * (counterOverhead n q + 2) + +namespace NestedCycle + +variable {n : ℕ} {current remaining : ℕ → K} {bodyLabel : Λ} + {checkLabel resetLabel : ℕ → Λ} + {program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)} + +def steps {depth : ℕ} {exitLabel : Λ} {start finish : Configuration K Λ σ} + (tree : NestedCycle n current remaining bodyLabel checkLabel resetLabel program + depth exitLabel start finish) : ℕ := + match tree with + | .leaf _ _ _ count _ _ _ => count + | .node _ _ _ _ _ _ _ children => + cycleSteps (fun r => if hr : r < n then steps (children ⟨r, hr⟩) else 0) (n - 1) (n - 1) +termination_by depth + +def LeafBound (B : ℕ) {depth : ℕ} {exitLabel : Λ} {start finish : Configuration K Λ σ} + (tree : NestedCycle n current remaining bodyLabel checkLabel resetLabel program + depth exitLabel start finish) : Prop := + match tree with + | .leaf _ _ _ count _ _ _ => count ≤ B + | .node _ _ _ _ _ _ _ children => ∀ r, LeafBound B (children r) +termination_by depth + +def work {depth : ℕ} {exitLabel : Λ} {start finish : Configuration K Λ σ} + (tree : NestedCycle n current remaining bodyLabel checkLabel resetLabel program + depth exitLabel start finish) : ℕ := + match tree with + | .leaf _ _ _ count _ _ _ => count + | .node _ _ _ _ _ _ _ children => ∑ r : Fin n, work (children r) +termination_by depth + +def reverseDigit (d : Fin n) : Fin n := ⟨n - 1 - d.val, by omega⟩ + +theorem reverseDigit_current (d : Fin n) : n - 1 - (reverseDigit d).val = d.val := by + dsimp only [reverseDigit] + omega + +def order {depth : ℕ} {exitLabel : Λ} {start finish : Configuration K Λ σ} + (tree : NestedCycle n current remaining bodyLabel checkLabel resetLabel program + depth exitLabel start finish) : List (Fin depth → Fin n) := + match tree with + | .leaf _ _ _ _ _ _ _ => [fun i => Fin.elim0 i] + | .node _ _ _ _ _ _ _ children => + (List.ofFn (fun d : Fin n => d)).flatMap (fun d => + (order (children (reverseDigit d))).map (fun tail => Fin.snoc tail d)) +termination_by depth + +theorem order_eq_tupleOrder {depth : ℕ} {exitLabel : Λ} {start finish : Configuration K Λ σ} + (tree : NestedCycle n current remaining bodyLabel checkLabel resetLabel program + depth exitLabel start finish) : tree.order = tupleOrder n depth := by + induction tree with + | leaf exitLabel start finish count atBody atExit run => + simpa only [order] using (tupleOrder_dimension_zero n).symm + | node depth exitLabel positive distinct atCheck atReset s children ih => + simp only [order, ih, tupleOrder_snoc] + +theorem order_length {depth : ℕ} {exitLabel : Λ} {start finish : Configuration K Λ σ} + (tree : NestedCycle n current remaining bodyLabel checkLabel resetLabel program + depth exitLabel start finish) : tree.order.length = n ^ depth := by + rw [order_eq_tupleOrder, tupleOrder_length] + +theorem steps_eq_work_add_overhead {depth : ℕ} {exitLabel : Λ} + {start finish : Configuration K Λ σ} + (tree : NestedCycle n current remaining bodyLabel checkLabel resetLabel program + depth exitLabel start finish) : tree.steps = tree.work + counterOverhead n depth := by + induction tree with + | leaf exitLabel start finish count atBody atExit run => + simp only [steps, work, counterOverhead, Nat.add_zero] + | node depth exitLabel positive distinct atCheck atReset s children ih => + have hn : n - 1 + 1 = n := by omega + have hsum : (∑ r ∈ Finset.range n, + if hr : r < n then steps (children ⟨r, hr⟩) else 0) = + (∑ r : Fin n, work (children r)) + n * counterOverhead n depth := by + calc + _ = ∑ r : Fin n, steps (children r) := by + rw [← Fin.sum_univ_eq_sum_range] + simp only [Fin.isLt, ↓reduceDIte] + _ = ∑ r : Fin n, (work (children r) + counterOverhead n depth) := by + apply Finset.sum_congr rfl + intro r _ + exact ih r + _ = _ := by simp [Finset.sum_add_distrib] + simp only [steps, work, cycleSteps, hn, hsum, counterOverhead, Nat.mul_add] + omega + +theorem trace {depth : ℕ} {exitLabel : Λ} {start finish : Configuration K Λ σ} + (tree : NestedCycle n current remaining bodyLabel checkLabel resetLabel program + depth exitLabel start finish) : + (MachineComposition.advance (TM2.step program))^[tree.steps] (some start) = some finish := by + induction tree with + | leaf exitLabel start finish count atBody atExit run => simpa only [steps] using run + | node depth exitLabel positive distinct atCheck atReset s children ih => + simp only [steps] + apply cycleTrace (current depth) (remaining depth) distinct bodyLabel (checkLabel depth) + (resetLabel depth) exitLabel program atCheck atReset (n - 1) (n - 1) + (Nat.le_refl _) s.currentSuffix s.remainingSuffix s.ambient s.register s.base + (fun r => if hr : r < n then steps (children ⟨r, hr⟩) else 0) + intro r hr + have hlt : r < n := by omega + simpa only [dite_eq_left hlt] using ih ⟨r, hlt⟩ + +theorem steps_le {depth : ℕ} {exitLabel : Λ} {start finish : Configuration K Λ σ} + (tree : NestedCycle n current remaining bodyLabel checkLabel resetLabel program + depth exitLabel start finish) (B : ℕ) (bounded : tree.LeafBound B) : + tree.steps ≤ n ^ depth * B + counterOverhead n depth := by + induction tree with + | leaf exitLabel start finish count atBody atExit run => + simpa only [steps, LeafBound, counterOverhead, pow_zero, Nat.one_mul, Nat.add_zero] using bounded + | node depth exitLabel positive distinct atCheck atReset s children ih => + simp only [LeafBound] at bounded + have visits : VisitTraces (current depth) (remaining depth) bodyLabel (checkLabel depth) + program (n - 1) (n - 1) s.currentSuffix s.remainingSuffix s.ambient s.register s.base + (fun r => if hr : r < n then steps (children ⟨r, hr⟩) else 0) := by + intro r hr + have hlt : r < n := by omega + simpa only [dite_eq_left hlt] using (children ⟨r, hlt⟩).trace + have bodyBound : ∀ r, r < n → + (if hr : r < n then steps (children ⟨r, hr⟩) else 0) ≤ + n ^ depth * B + counterOverhead n depth := by + intro r hr + simpa only [dite_eq_left hr] using ih ⟨r, hr⟩ (bounded ⟨r, hr⟩) + have h := (ascendingCycleInTime (current depth) (remaining depth) distinct bodyLabel + (checkLabel depth) (resetLabel depth) exitLabel program atCheck atReset n positive + s.currentSuffix s.remainingSuffix s.ambient s.register s.base + (fun r => if hr : r < n then steps (children ⟨r, hr⟩) else 0) + (n ^ depth * B + counterOverhead n depth) visits bodyBound).steps_le_m + change cycleSteps _ (n - 1) (n - 1) ≤ _ at h + simpa only [steps, counterOverhead, pow_succ, Nat.mul_add, Nat.add_mul, + Nat.mul_assoc, Nat.mul_comm, Nat.mul_left_comm, Nat.add_assoc] using h + +def inTime {depth : ℕ} {exitLabel : Λ} {start finish : Configuration K Λ σ} + (tree : NestedCycle n current remaining bodyLabel checkLabel resetLabel program + depth exitLabel start finish) (B : ℕ) (bounded : tree.LeafBound B) : + StateTransition.EvalsToInTime (TM2.step program) start (some finish) + (n ^ depth * B + counterOverhead n depth) where + steps := tree.steps + evals_in_steps := tree.trace + steps_le_m := tree.steps_le B bounded + +end NestedCycle + +omit [DecidableEq K] in +theorem counterOverhead_le (n q : ℕ) (hn : 0 < n) : + counterOverhead n q ≤ 2 * q * n ^ q := by + induction q with + | zero => simp [counterOverhead] + | succ q ih => + have hp : 1 ≤ n ^ q := by apply Nat.one_le_pow; exact hn + have h := Nat.mul_le_mul_left n (Nat.add_le_add_right ih 2) + have htwo : 2 ≤ 2 * n ^ q := Nat.mul_le_mul_left 2 hp + have hinner : 2 * q * n ^ q + 2 ≤ 2 * (q + 1) * n ^ q := by + rw [Nat.mul_add, Nat.add_mul] + omega + exact h.trans (by + simpa only [counterOverhead, pow_succ, Nat.mul_assoc, Nat.mul_comm, + Nat.mul_left_comm] using Nat.mul_le_mul_left n hinner) + +namespace NestedCycle + +variable {n : ℕ} {current remaining : ℕ → K} {bodyLabel : Λ} + {checkLabel resetLabel : ℕ → Λ} + {program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)} + +theorem steps_le_power {depth : ℕ} {exitLabel : Λ} {start finish : Configuration K Λ σ} + (tree : NestedCycle n current remaining bodyLabel checkLabel resetLabel program + depth exitLabel start finish) (hn : 0 < n) (B : ℕ) (bounded : tree.LeafBound B) : + tree.steps ≤ (B + 2 * depth) * n ^ depth := by + have h := (tree.steps_le B bounded).trans + (Nat.add_le_add_left (counterOverhead_le n depth hn) (n ^ depth * B)) + simpa only [Nat.add_mul, Nat.mul_add, Nat.mul_comm] using h + +end NestedCycle + +end Nested + +def entry (q : ℕ) (radix : K) (bodyLabel exitLabel : Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) := + if q = 0 then + .load (fun state => (state.1, none)) (.goto fun _ => bodyLabel) + else + .peek radix (fun state head => (state.1, head)) + (.branch (fun state => state.2.getD false) + (.load (fun state => (state.1, none)) (.goto fun _ => bodyLabel)) + (.load (fun state => (state.1, none)) (.goto fun _ => exitLabel))) + +theorem entryStep_dimension_zero (radix : K) (startLabel bodyLabel exitLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atStart : program startLabel = entry 0 radix bodyLabel exitLabel) + (base : K → List Bool) (ambient : σ) (register : Option Bool) : + TM2.step program ⟨some startLabel, (ambient, register), base⟩ = + some ⟨some bodyLabel, (ambient, none), base⟩ := by + change some (TM2.stepAux (program startLabel) (ambient, register) base) = _ + rw [atStart] + simp [entry, TM2.stepAux] + +theorem entryStep_radix_zero (q : ℕ) (hq : 0 < q) (radix : K) + (startLabel bodyLabel exitLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atStart : program startLabel = entry q radix bodyLabel exitLabel) + (base : K → List Bool) (suffix : List Bool) (hradix : base radix = encodeWord 0 ++ suffix) + (ambient : σ) (register : Option Bool) : + TM2.step program ⟨some startLabel, (ambient, register), base⟩ = + some ⟨some exitLabel, (ambient, none), base⟩ := by + change some (TM2.stepAux (program startLabel) (ambient, register) base) = _ + rw [atStart] + simp [entry, Nat.ne_of_gt hq, TM2.stepAux, hradix, encodeWord] + +theorem entryStep_radix_positive (q n : ℕ) (hn : 0 < n) (radix : K) + (startLabel bodyLabel exitLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atStart : program startLabel = entry q radix bodyLabel exitLabel) + (base : K → List Bool) (suffix : List Bool) (hradix : base radix = encodeWord n ++ suffix) + (ambient : σ) (register : Option Bool) : + TM2.step program ⟨some startLabel, (ambient, register), base⟩ = + some ⟨some bodyLabel, (ambient, none), base⟩ := by + cases n with + | zero => omega + | succ n => + change some (TM2.stepAux (program startLabel) (ambient, register) base) = _ + rw [atStart] + by_cases hq : q = 0 <;> + simp [entry, hq, TM2.stepAux, hradix, encodeWord, List.replicate_succ] + +namespace Control + +abbrev Label (q : ℕ) := Fin q ⊕ (Fin q ⊕ Option Bool) + +def start (q : ℕ) : Label q := .inr (.inr none) +def body (q : ℕ) : Label q := .inr (.inr (some false)) +def exit (q : ℕ) : Label q := .inr (.inr (some true)) +def check {q : ℕ} (i : Fin q) : Label q := .inl i +def resetLabel {q : ℕ} (i : Fin q) : Label q := .inr (.inl i) + +def carry {q : ℕ} (i : Fin q) : Label q := + if h : i.val + 1 < q then check ⟨i.val + 1, h⟩ else exit q + +def program (q : ℕ) (current remaining : Fin q → K) (radix : K) + (emitter : TM2.Stmt (Alphabet (K := K)) (Label q) (σ × Option Bool)) : + Label q → TM2.Stmt (Alphabet (K := K)) (Label q) (σ × Option Bool) + | .inl i => increment (current i) (remaining i) (body q) (resetLabel i) + | .inr (.inl i) => reset (current i) (remaining i) (resetLabel i) (carry i) + | .inr (.inr none) => entry q radix (body q) (exit q) + | .inr (.inr (some false)) => emitter + | .inr (.inr (some true)) => .halt + +omit [DecidableEq K] in +theorem label_card (q : ℕ) : Fintype.card (Label q) = 2 * q + 3 := by + simp [Label] + omega + +end Control + +end MinUncutGames.Foundations.Complexity.MachineTupleOdometer + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineUnaryAdd.lean b/lean/OAI/Computability/MinUncut/Machines/MachineUnaryAdd.lean new file mode 100644 index 0000000000000000000000000000000000000000..2d4f90995a10c357e04e6fefbc7a73a026a8d4ea --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineUnaryAdd.lean @@ -0,0 +1,962 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineTransducer + +namespace OAI + +namespace MinUncutGames.Foundations.Complexity.MachineUnaryAddAt + +open Turing +open Reduction.MachineTransfer + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool + +def finish (destination : K) (exit : Option Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) := + .load (fun state => (state.1, none)) (exitAt destination exit) + +def loop (source destination : K) (loopLabel : Λ) (exit : Option Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) := + .pop source (fun state head => (state.1, head)) + (.branch (fun state => state.2.getD false) + (.push destination (fun _ => true) (.goto fun _ => loopLabel)) + (.branch (fun state => state.2.isSome) + (.push source (fun _ => false) (finish destination exit)) + (finish destination exit))) + +omit [DecidableEq K] in +theorem loopPushBound (source destination : K) (loopLabel : Λ) (exit : Option Λ) : + Runtime.statementPushBound (loop (σ := σ) source destination loopLabel exit) = 1 := by + cases exit <;> rfl + +def unaryTapes (source destination : K) (base : K → List Bool) (a b : Nat) + (sourceSuffix destinationSuffix : List Bool) : K → List Bool := + tapesAt source destination base (encodeWord a ++ sourceSuffix) + (encodeWord b ++ destinationSuffix) + +@[simp] theorem unaryTapes_source (source destination : K) (distinct : source ≠ destination) + (base : K → List Bool) (a b : Nat) (sourceSuffix destinationSuffix : List Bool) : + unaryTapes source destination base a b sourceSuffix destinationSuffix source = + encodeWord a ++ sourceSuffix := by + simp [unaryTapes, distinct] + +@[simp] theorem unaryTapes_destination (source destination : K) + (base : K → List Bool) (a b : Nat) (sourceSuffix destinationSuffix : List Bool) : + unaryTapes source destination base a b sourceSuffix destinationSuffix destination = + encodeWord b ++ destinationSuffix := by + simp [unaryTapes] + +theorem unaryTapes_other (source destination other : K) + (notSource : other ≠ source) (notDestination : other ≠ destination) + (base : K → List Bool) (a b : Nat) (sourceSuffix destinationSuffix : List Bool) : + unaryTapes source destination base a b sourceSuffix destinationSuffix other = + base other := by + simp [unaryTapes, tapesAt, notSource, notDestination] + +theorem update_source (source destination : K) (distinct : source ≠ destination) + (base : K → List Bool) (input output replacement : List Bool) : + Function.update (tapesAt source destination base input output) source replacement = + tapesAt source destination base replacement output := by + funext k + by_cases hs : k = source + · subst k + simp [tapesAt, distinct] + · by_cases hd : k = destination + · subst k + simp [tapesAt, Ne.symm distinct] + · simp [tapesAt, hs, hd] + +theorem update_destination (source destination : K) + (base : K → List Bool) (input output replacement : List Bool) : + Function.update (tapesAt source destination base input output) destination replacement = + tapesAt source destination base input replacement := by + funext k + by_cases hd : k = destination + · subst k + simp [tapesAt] + · simp [tapesAt, hd] + +theorem stepAux_true (source destination : K) (distinct : source ≠ destination) + (loopLabel : Λ) (exit : Option Λ) (base : K → List Bool) + (input output : List Bool) (ambient : σ) (register : Option Bool) : + TM2.stepAux (loop source destination loopLabel exit) (ambient, register) + (tapesAt source destination base (true :: input) output) = + ⟨some loopLabel, (ambient, some true), + tapesAt source destination base input (true :: output)⟩ := by + simp [loop, TM2.stepAux, distinct, update_source, update_destination] + +theorem stepAux_false (source destination : K) (distinct : source ≠ destination) + (loopLabel : Λ) (exit : Option Λ) (base : K → List Bool) + (input output : List Bool) (ambient : σ) (register : Option Bool) : + TM2.stepAux (loop source destination loopLabel exit) (ambient, register) + (tapesAt source destination base (false :: input) output) = + ⟨exit, (ambient, none), tapesAt source destination base (false :: input) output⟩ := by + cases exit <;> simp [loop, finish, exitAt, TM2.stepAux, distinct, update_source] + +theorem stepAux_succ (source destination : K) (distinct : source ≠ destination) + (loopLabel : Λ) (exit : Option Λ) (base : K → List Bool) (a b : Nat) + (sourceSuffix destinationSuffix : List Bool) (ambient : σ) (register : Option Bool) : + TM2.stepAux (loop source destination loopLabel exit) (ambient, register) + (unaryTapes source destination base (a + 1) b sourceSuffix destinationSuffix) = + ⟨some loopLabel, (ambient, some true), + unaryTapes source destination base a (b + 1) sourceSuffix destinationSuffix⟩ := by + simpa only [unaryTapes, encodeWord, List.replicate_succ, List.cons_append] using + stepAux_true source destination distinct loopLabel exit base + (encodeWord a ++ sourceSuffix) (encodeWord b ++ destinationSuffix) ambient register + +theorem stepAux_zero (source destination : K) (distinct : source ≠ destination) + (loopLabel : Λ) (exit : Option Λ) (base : K → List Bool) (b : Nat) + (sourceSuffix destinationSuffix : List Bool) (ambient : σ) (register : Option Bool) : + TM2.stepAux (loop source destination loopLabel exit) (ambient, register) + (unaryTapes source destination base 0 b sourceSuffix destinationSuffix) = + ⟨exit, (ambient, none), + unaryTapes source destination base 0 b sourceSuffix destinationSuffix⟩ := by + simpa only [unaryTapes, encodeWord, List.replicate_zero, List.nil_append, + List.singleton_append] using + stepAux_false source destination distinct loopLabel exit base sourceSuffix + (encodeWord b ++ destinationSuffix) ambient register + +theorem step_succ (source destination : K) (distinct : source ≠ destination) + (loopLabel : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atLoop : program loopLabel = loop source destination loopLabel exit) + (base : K → List Bool) (a b : Nat) (sourceSuffix destinationSuffix : List Bool) + (ambient : σ) (register : Option Bool) : + TM2.step program ⟨some loopLabel, (ambient, register), + unaryTapes source destination base (a + 1) b sourceSuffix destinationSuffix⟩ = + some ⟨some loopLabel, (ambient, some true), + unaryTapes source destination base a (b + 1) sourceSuffix destinationSuffix⟩ := by + change some (TM2.stepAux (program loopLabel) (ambient, register) + (unaryTapes source destination base (a + 1) b sourceSuffix destinationSuffix)) = _ + rw [atLoop, stepAux_succ source destination distinct] + +theorem step_zero (source destination : K) (distinct : source ≠ destination) + (loopLabel : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atLoop : program loopLabel = loop source destination loopLabel exit) + (base : K → List Bool) (b : Nat) (sourceSuffix destinationSuffix : List Bool) + (ambient : σ) (register : Option Bool) : + TM2.step program ⟨some loopLabel, (ambient, register), + unaryTapes source destination base 0 b sourceSuffix destinationSuffix⟩ = + some ⟨exit, (ambient, none), + unaryTapes source destination base 0 b sourceSuffix destinationSuffix⟩ := by + change some (TM2.stepAux (program loopLabel) (ambient, register) + (unaryTapes source destination base 0 b sourceSuffix destinationSuffix)) = _ + rw [atLoop, stepAux_zero source destination distinct] + +theorem addTrace (source destination : K) (distinct : source ≠ destination) + (loopLabel : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atLoop : program loopLabel = loop source destination loopLabel exit) + (base : K → List Bool) (a b : Nat) (sourceSuffix destinationSuffix : List Bool) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[a + 1] + (some ⟨some loopLabel, (ambient, register), + unaryTapes source destination base a b sourceSuffix destinationSuffix⟩) = + some ⟨exit, (ambient, none), + unaryTapes source destination base 0 (a + b) sourceSuffix destinationSuffix⟩ := by + induction a generalizing b register with + | zero => + simpa only [Nat.zero_add, Function.iterate_one, MachineComposition.advance_some] using + step_zero source destination distinct loopLabel exit program atLoop + base b sourceSuffix destinationSuffix ambient register + | succ a ih => + rw [Function.iterate_succ_apply] + change (MachineComposition.advance (TM2.step program))^[a + 1] + (TM2.step program ⟨some loopLabel, (ambient, register), + unaryTapes source destination base (a + 1) b sourceSuffix destinationSuffix⟩) = _ + rw [step_succ source destination distinct loopLabel exit program atLoop] + simpa only [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using ih (b + 1) (some true) + +theorem addFromTapes (source destination : K) (distinct : source ≠ destination) + (loopLabel : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atLoop : program loopLabel = loop source destination loopLabel exit) + (base : K → List Bool) (a b : Nat) (sourceSuffix destinationSuffix : List Bool) + (sourceInput : base source = encodeWord a ++ sourceSuffix) + (destinationInput : base destination = encodeWord b ++ destinationSuffix) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[a + 1] + (some ⟨some loopLabel, (ambient, register), base⟩) = + some ⟨exit, (ambient, none), + unaryTapes source destination base 0 (a + b) sourceSuffix destinationSuffix⟩ := by + have hbase : unaryTapes source destination base a b sourceSuffix destinationSuffix = + base := by + simp only [unaryTapes, ← sourceInput, ← destinationInput, tapesAt_self] + have h := addTrace source destination distinct loopLabel exit program atLoop + base a b sourceSuffix destinationSuffix ambient register + rw [hbase] at h + exact h + +def addInTime (source destination : K) (distinct : source ≠ destination) + (loopLabel : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atLoop : program loopLabel = loop source destination loopLabel exit) + (base : K → List Bool) (a b : Nat) (sourceSuffix destinationSuffix : List Bool) + (sourceInput : base source = encodeWord a ++ sourceSuffix) + (destinationInput : base destination = encodeWord b ++ destinationSuffix) + (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some loopLabel, (ambient, register), base⟩ + (some ⟨exit, (ambient, none), + unaryTapes source destination base 0 (a + b) sourceSuffix destinationSuffix⟩) + (a + 1) where + steps := a + 1 + evals_in_steps := addFromTapes source destination distinct loopLabel exit program atLoop + base a b sourceSuffix destinationSuffix sourceInput destinationInput ambient register + steps_le_m := Nat.le_refl _ + +@[simp] theorem addInTime_steps (source destination : K) (distinct : source ≠ destination) + (loopLabel : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atLoop : program loopLabel = loop source destination loopLabel exit) + (base : K → List Bool) (a b : Nat) (sourceSuffix destinationSuffix : List Bool) + (sourceInput : base source = encodeWord a ++ sourceSuffix) + (destinationInput : base destination = encodeWord b ++ destinationSuffix) + (ambient : σ) (register : Option Bool) : + (addInTime source destination distinct loopLabel exit program atLoop base a b + sourceSuffix destinationSuffix sourceInput destinationInput ambient register).steps = + a + 1 := rfl + +end MinUncutGames.Foundations.Complexity.MachineUnaryAddAt + +namespace MinUncutGames.Foundations.Complexity.MachineRadixStep + +open Turing + +inductive Label + | multiply (label : MachineUnaryMultiply.Label) + | digitDrain | digitFork | add | finish + deriving DecidableEq, Fintype + +variable {K Λ σ : Type} + +abbrev Alphabet (_ : K) := Bool +abbrev State (σ : Type) := MachineUnaryMultiply.State σ + +def multiplySlots (slots : Fin 6 ↪ K) : Fin 5 ↪ K := + (Fin.succAboveEmb (2 : Fin 6)).trans slots + +@[simp] theorem multiplySlots_zero (slots : Fin 6 ↪ K) : multiplySlots slots 0 = slots 0 := rfl +@[simp] theorem multiplySlots_one (slots : Fin 6 ↪ K) : multiplySlots slots 1 = slots 1 := rfl +@[simp] theorem multiplySlots_two (slots : Fin 6 ↪ K) : multiplySlots slots 2 = slots 3 := rfl +@[simp] theorem multiplySlots_three (slots : Fin 6 ↪ K) : multiplySlots slots 3 = slots 4 := rfl +@[simp] theorem multiplySlots_four (slots : Fin 6 ↪ K) : multiplySlots slots 4 = slots 5 := rfl + +variable [DecidableEq K] + +def statement (slots : Fin 6 ↪ K) (labels : Label → Λ) (exit : Option Λ) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (State σ) + | .multiply label => MachineUnaryMultiply.statement (multiplySlots slots) + (fun l => labels (.multiply l)) (some (labels .digitDrain)) label + | .digitDrain => Reduction.MachineTransfer.loopAt (slots 2) (slots 5) id false + (labels .digitDrain) (some (labels .digitFork)) + | .digitFork => MachineCopy.forkLoop (slots 5) (slots 2) (slots 4) false + (labels .digitFork) (some (labels .add)) + | .add => MachineUnaryAddAt.loop (slots 4) (slots 3) (labels .add) (some (labels .finish)) + | .finish => .pop (slots 4) (fun state _ => (state.1, none)) + (Reduction.MachineTransfer.exitAt (slots 3) exit) + +def program (slots : Fin 6 ↪ K) : Label → TM2.Stmt (Alphabet (K := K)) Label (State σ) := + statement slots id none + +def machine : FinTM2 where + K := Fin 6 + k₀ := 0 + k₁ := 3 + Γ _ := Bool + Λ := Label + main := .multiply .copyDrain + σ := State Unit + initialState := (((), ()), none) + m := program (Function.Embedding.refl (Fin 6)) + +def resultTapes (slots : Fin 6 ↪ K) (base : K → List Bool) (value : ℕ) : K → List Bool := + Function.update base (slots 3) (encodeWord value ++ base (slots 3)) + +@[simp] theorem resultTapes_output (slots : Fin 6 ↪ K) (base : K → List Bool) (value : ℕ) : + resultTapes slots base value (slots 3) = encodeWord value ++ base (slots 3) := by + simp [resultTapes] + +theorem resultTapes_other (slots : Fin 6 ↪ K) (base : K → List Bool) (value : ℕ) + (k : K) (hk : k ≠ slots 3) : resultTapes slots base value k = base k := by + simp [resultTapes, hk] + +def steps (radix acc digit : ℕ) : ℕ := 3 * radix * acc + 8 * acc + 3 * digit + 13 + +theorem radixStepTrace (slots : Fin 6 ↪ K) (labels : Label → Λ) (exit : Option Λ) + (p : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ label, p (labels label) = statement slots labels exit label) + (base : K → List Bool) (radix acc digit : ℕ) + (operandRadix : base (slots 0) = encodeWord radix) + (operandAcc : base (slots 1) = encodeWord acc) + (operandDigit : base (slots 2) = encodeWord digit) + (counterEmpty : base (slots 4) = []) (scratchEmpty : base (slots 5) = []) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step p))^[steps radix acc digit] + (some ⟨some (labels (.multiply .copyDrain)), ((ambient, ()), register), base⟩) = + some ⟨exit, ((ambient, ()), none), resultTapes slots base (radix * acc + digit)⟩ := by + have h23 : slots 2 ≠ slots 3 := slots.injective.ne (by decide) + have h24 : slots 2 ≠ slots 4 := slots.injective.ne (by decide) + have h25 : slots 2 ≠ slots 5 := slots.injective.ne (by decide) + have h34 : slots 3 ≠ slots 4 := slots.injective.ne (by decide) + have h53 : slots 5 ≠ slots 3 := slots.injective.ne (by decide) + have h45 : slots 4 ≠ slots 5 := slots.injective.ne (by decide) + let multiplied := resultTapes slots base (radix * acc) + have hmul : (MachineComposition.advance (TM2.step p))^[MachineUnaryMultiply.steps radix acc] + (some ⟨some (labels (.multiply .copyDrain)), ((ambient, ()), register), base⟩) = + some ⟨some (labels .digitDrain), ((ambient, ()), none), multiplied⟩ := by + have h := MachineUnaryMultiply.multiplyTrace (multiplySlots slots) + (fun l => labels (.multiply l)) (some (labels .digitDrain)) p + (fun l => atLabels (.multiply l)) base radix acc operandRadix operandAcc + counterEmpty scratchEmpty ambient register + simpa only [MachineUnaryMultiply.resultTapes, multiplySlots_two, multiplied, resultTapes] using h + have hmulDigit : multiplied (slots 2) = encodeWord digit := by + simp [multiplied, resultTapes, h23, operandDigit] + have hmulCounter : multiplied (slots 4) = [] := by + simp [multiplied, resultTapes, Ne.symm h34, counterEmpty] + have hmulScratch : multiplied (slots 5) = [] := by + simp [multiplied, resultTapes, h53, scratchEmpty] + let copied := Function.update multiplied (slots 4) (encodeWord digit) + have hcopy : (MachineComposition.advance (TM2.step p))^[2 * (digit + 2)] + (some ⟨some (labels .digitDrain), ((ambient, ()), none), multiplied⟩) = + some ⟨some (labels .add), ((ambient, ()), none), copied⟩ := by + have h := MachineCopy.copyTrace (slots 2) (slots 4) (slots 5) h24 h25 h45 false + (labels .digitDrain) (labels .digitFork) (some (labels .add)) p + (atLabels .digitDrain) (atLabels .digitFork) multiplied hmulScratch (ambient, ()) none + simpa only [copied, hmulDigit, hmulCounter, List.append_nil, encodeWord, + List.length_append, List.length_replicate, List.length_singleton, + Nat.add_assoc, Nat.reduceAdd] using h + have hcopiedCounter : copied (slots 4) = encodeWord digit ++ [] := by simp [copied] + have hcopiedOutput : copied (slots 3) = encodeWord (radix * acc) ++ base (slots 3) := by + simp [copied, multiplied, resultTapes, h34] + let added := MachineUnaryAddAt.unaryTapes (slots 4) (slots 3) copied + 0 (digit + radix * acc) [] (base (slots 3)) + have hadd : (MachineComposition.advance (TM2.step p))^[digit + 1] + (some ⟨some (labels .add), ((ambient, ()), none), copied⟩) = + some ⟨some (labels .finish), ((ambient, ()), none), added⟩ := + MachineUnaryAddAt.addFromTapes (slots 4) (slots 3) (Ne.symm h34) + (labels .add) (some (labels .finish)) p (atLabels .add) copied digit (radix * acc) + [] (base (slots 3)) hcopiedCounter hcopiedOutput (ambient, ()) none + have hfinishTapes : Function.update added (slots 4) ((added (slots 4)).tail) = + resultTapes slots base (radix * acc + digit) := by + funext k + by_cases hk3 : k = slots 3 + · subst k + simp only [Function.update_of_ne h34, added, MachineUnaryAddAt.unaryTapes_destination, + resultTapes_output] + rw [Nat.add_comm digit (radix * acc)] + · by_cases hk4 : k = slots 4 + · subst k + simp [added, MachineUnaryAddAt.unaryTapes, Reduction.MachineTransfer.tapesAt, + resultTapes, encodeWord, Ne.symm h34, counterEmpty] + · simp [added, MachineUnaryAddAt.unaryTapes, Reduction.MachineTransfer.tapesAt, + copied, multiplied, resultTapes, hk3, hk4] + have hfinish : (MachineComposition.advance (TM2.step p))^[1] + (some ⟨some (labels .finish), ((ambient, ()), none), added⟩) = + some ⟨exit, ((ambient, ()), none), resultTapes slots base (radix * acc + digit)⟩ := by + change some (TM2.stepAux (p (labels .finish)) ((ambient, ()), none) added) = _ + rw [atLabels .finish] + have hcfg := congrArg (fun tapes => some (⟨exit, ((ambient, ()), none), tapes⟩ : + TM2.Cfg (Alphabet (K := K)) Λ (State σ))) hfinishTapes + cases exit <;> simpa only [statement, TM2.stepAux, Reduction.MachineTransfer.exitAt] using hcfg + rw [show steps radix acc digit = + 1 + ((digit + 1) + (2 * (digit + 2) + MachineUnaryMultiply.steps radix acc)) by + unfold steps MachineUnaryMultiply.steps; ring] + rw [Function.iterate_add_apply _ 1, + Function.iterate_add_apply _ (digit + 1), + Function.iterate_add_apply _ (2 * (digit + 2)), hmul, hcopy, hadd] + exact hfinish + +def radixStepInTime (slots : Fin 6 ↪ K) (labels : Label → Λ) (exit : Option Λ) + (p : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ label, p (labels label) = statement slots labels exit label) + (base : K → List Bool) (radix acc digit : ℕ) + (operandRadix : base (slots 0) = encodeWord radix) + (operandAcc : base (slots 1) = encodeWord acc) + (operandDigit : base (slots 2) = encodeWord digit) + (counterEmpty : base (slots 4) = []) (scratchEmpty : base (slots 5) = []) + (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step p) + ⟨some (labels (.multiply .copyDrain)), ((ambient, ()), register), base⟩ + (some ⟨exit, ((ambient, ()), none), resultTapes slots base (radix * acc + digit)⟩) + (steps radix acc digit) where + steps := steps radix acc digit + evals_in_steps := radixStepTrace slots labels exit p atLabels base radix acc digit + operandRadix operandAcc operandDigit counterEmpty scratchEmpty ambient register + steps_le_m := Nat.le_refl _ + +noncomputable def timePolynomial : Polynomial ℕ := + Polynomial.C 3 * Polynomial.X ^ 2 + Polynomial.C 11 * Polynomial.X + Polynomial.C 13 + +theorem steps_le_timePolynomial (radix acc digit : ℕ) : + steps radix acc digit ≤ timePolynomial.eval (radix + acc + digit + 3) := by + have hr : radix ≤ radix + acc + digit + 3 := by omega + have ha : acc ≤ radix + acc + digit + 3 := by omega + have hd : digit ≤ radix + acc + digit + 3 := by omega + have hprod := Nat.mul_le_mul hr ha + simp only [timePolynomial, Polynomial.eval_add, Polynomial.eval_mul, + Polynomial.eval_C, Polynomial.eval_pow, Polynomial.eval_X] + unfold steps + nlinarith + +theorem programTrace (slots : Fin 6 ↪ K) (base : K → List Bool) (radix acc digit : ℕ) + (operandRadix : base (slots 0) = encodeWord radix) + (operandAcc : base (slots 1) = encodeWord acc) + (operandDigit : base (slots 2) = encodeWord digit) + (counterEmpty : base (slots 4) = []) (scratchEmpty : base (slots 5) = []) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step (program (σ := σ) slots)))^[steps radix acc digit] + (some ⟨some (.multiply .copyDrain), ((ambient, ()), register), base⟩) = + some ⟨none, ((ambient, ()), none), resultTapes slots base (radix * acc + digit)⟩ := + radixStepTrace slots id none (program slots) (fun _ => rfl) base radix acc digit + operandRadix operandAcc operandDigit counterEmpty scratchEmpty ambient register + +def programInPolynomialTime (slots : Fin 6 ↪ K) (base : K → List Bool) (radix acc digit : ℕ) + (operandRadix : base (slots 0) = encodeWord radix) + (operandAcc : base (slots 1) = encodeWord acc) + (operandDigit : base (slots 2) = encodeWord digit) + (counterEmpty : base (slots 4) = []) (scratchEmpty : base (slots 5) = []) + (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step (program (σ := σ) slots)) + ⟨some (.multiply .copyDrain), ((ambient, ()), register), base⟩ + (some ⟨none, ((ambient, ()), none), resultTapes slots base (radix * acc + digit)⟩) + (timePolynomial.eval + ((encodeWord radix).length + (encodeWord acc).length + (encodeWord digit).length)) where + steps := steps radix acc digit + evals_in_steps := programTrace slots base radix acc digit operandRadix operandAcc operandDigit + counterEmpty scratchEmpty ambient register + steps_le_m := by + have hlength : (encodeWord radix).length + (encodeWord acc).length + (encodeWord digit).length = + radix + acc + digit + 3 := by + simp only [encodeWord, List.length_append, List.length_replicate, List.length_singleton] + omega + rw [hlength] + exact steps_le_timePolynomial radix acc digit + +end MinUncutGames.Foundations.Complexity.MachineRadixStep + +namespace MinUncutGames.Foundations.Complexity.MachineHorner + +open Turing + +variable {K Λ σ : Type} {width : Nat} + +abbrev Layout (width : Nat) := Fin 6 ⊕ Fin width +abbrev Alphabet (_ : K) := Bool +abbrev State (σ : Type) := MachineRadixStep.State σ + +def parity : Nat → Bool + | 0 => false + | n + 1 => !(parity n) + +def accumulator (flip : Bool) : Fin 6 := if flip then 2 else 1 + +@[simp] theorem accumulator_ne (flip : Bool) : accumulator flip ≠ accumulator (!flip) := by + cases flip <;> decide + +def radixLayout (flip : Bool) (i : Fin width) : Fin 6 ↪ Layout width where + toFun + | 0 => .inl 0 + | 1 => .inl (accumulator flip) + | 2 => .inr i + | 3 => .inl (accumulator (!flip)) + | 4 => .inl 4 + | 5 => .inl 5 + inj' := by + intro a b h + cases flip <;> fin_cases a <;> fin_cases b <;> simp [accumulator] at h ⊢ + +def radixSlots (slots : Layout width ↪ K) (i : Fin width) : Fin 6 ↪ K := + (radixLayout (parity i.val) i).trans slots + +@[simp] theorem radixSlots_base (slots : Layout width ↪ K) (i : Fin width) : + radixSlots slots i 0 = slots (.inl 0) := rfl +@[simp] theorem radixSlots_acc (slots : Layout width ↪ K) (i : Fin width) : + radixSlots slots i 1 = slots (.inl (accumulator (parity i.val))) := rfl +@[simp] theorem radixSlots_digit (slots : Layout width ↪ K) (i : Fin width) : + radixSlots slots i 2 = slots (.inr i) := rfl +@[simp] theorem radixSlots_out (slots : Layout width ↪ K) (i : Fin width) : + radixSlots slots i 3 = slots (.inl (accumulator (parity (i.val + 1)))) := rfl +@[simp] theorem radixSlots_counter (slots : Layout width ↪ K) (i : Fin width) : + radixSlots slots i 4 = slots (.inl 4) := rfl +@[simp] theorem radixSlots_scratch (slots : Layout width ↪ K) (i : Fin width) : + radixSlots slots i 5 = slots (.inl 5) := rfl + +inductive Label (width : Nat) + | start + | radix (i : Fin width) (inner : MachineRadixStep.Label) + | clear (i : Fin width) + | finishDrain | finishRestore + deriving DecidableEq, Fintype + +def entryLabel (width n : Nat) : Label width := + if h : n < width then .radix ⟨n, h⟩ (.multiply .copyDrain) else .finishDrain + +def drainLoop (tape : K) (loopLabel : Λ) (exit : Option Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (State σ) := + .pop tape (fun state bit => (state.1, bit)) + (.branch (fun state => state.2.getD false) + (.goto fun _ => loopLabel) + (.load (fun state => (state.1, none)) (Reduction.MachineTransfer.exitAt tape exit))) + +variable [DecidableEq K] + +def statement (slots : Layout width ↪ K) (labels : Label width → Λ) (exit : Option Λ) : + Label width → TM2.Stmt (Alphabet (K := K)) Λ (State σ) + | .start => .push (slots (.inl 1)) (fun _ => false) + (.load (fun state => (state.1, none)) (.goto fun _ => labels (entryLabel width 0))) + | .radix i inner => MachineRadixStep.statement (radixSlots slots i) + (fun l => labels (.radix i l)) (some (labels (.clear i))) inner + | .clear i => drainLoop (slots (.inl (accumulator (parity i.val)))) + (labels (.clear i)) (some (labels (entryLabel width (i.val + 1)))) + | .finishDrain => Reduction.MachineTransfer.loopAt + (slots (.inl (accumulator (parity width)))) (slots (.inl 5)) id false + (labels .finishDrain) (some (labels .finishRestore)) + | .finishRestore => Reduction.MachineTransfer.loopAt (slots (.inl 5)) (slots (.inl 3)) id false + (labels .finishRestore) exit + +def program (slots : Layout width ↪ K) : + Label width → TM2.Stmt (Alphabet (K := K)) (Label width) (State σ) := statement slots id none + +def machine (width : Nat) : FinTM2 where + K := Layout width + k₀ := .inl 0 + k₁ := .inl 3 + Γ _ := Bool + Λ := Label width + main := .start + σ := State Unit + initialState := (((), ()), none) + m := program (Function.Embedding.refl (Layout width)) + +def value (radix : Nat) (digits : Nat → Nat) : Nat → Nat + | 0 => 0 + | n + 1 => radix * value radix digits n + digits n + +def stepCost (radix acc digit : Nat) : Nat := + MachineRadixStep.steps radix acc digit + acc + 1 + +def prefixSteps (radix : Nat) (digits : Nat → Nat) : Nat → Nat + | 0 => 0 + | n + 1 => prefixSteps radix digits n + stepCost radix (value radix digits n) (digits n) + +def stageTapes (slots : Layout width ↪ K) (base : K → List Bool) (n acc : Nat) : K → List Bool := + Function.update base (slots (.inl (accumulator (parity n)))) (encodeWord acc) + +def resultTapes (slots : Layout width ↪ K) (base : K → List Bool) (acc : Nat) : K → List Bool := + Function.update base (slots (.inl 3)) (encodeWord acc ++ base (slots (.inl 3))) + +theorem drainTrace (tape : K) (loopLabel : Λ) (exit : Option Λ) + (p : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLoop : p loopLabel = drainLoop tape loopLabel exit) + (base : K → List Bool) (n : Nat) (suffix : List Bool) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step p))^[n + 1] + (some ⟨some loopLabel, ((ambient, ()), register), + Function.update base tape (encodeWord n ++ suffix)⟩) = + some ⟨exit, ((ambient, ()), none), Function.update base tape suffix⟩ := by + induction n generalizing register with + | zero => + change some (TM2.stepAux (p loopLabel) _ _) = _ + rw [atLoop] + cases exit <;> simp [drainLoop, TM2.stepAux, encodeWord, Reduction.MachineTransfer.exitAt] + | succ n ih => + rw [Function.iterate_succ_apply] + change (MachineComposition.advance (TM2.step p))^[n + 1] + (some (TM2.stepAux (p loopLabel) _ _)) = _ + rw [atLoop] + simp only [drainLoop, TM2.stepAux, Function.update_self, encodeWord, + List.replicate_succ, List.cons_append, List.head?_cons, List.tail_cons, + Option.getD_some, Function.update_idem] + exact ih (some true) + +structure Clean (slots : Layout width ↪ K) (base : K → List Bool) : Prop where + accA : base (slots (.inl 1)) = [] + accB : base (slots (.inl 2)) = [] + counter : base (slots (.inl 4)) = [] + scratch : base (slots (.inl 5)) = [] + +omit [DecidableEq K] in +theorem Clean.acc {slots : Layout width ↪ K} {base : K → List Bool} + (clean : Clean slots base) (flip : Bool) : base (slots (.inl (accumulator flip))) = [] := by + cases flip + · exact clean.accA + · exact clean.accB + +theorem digitTrace (slots : Layout width ↪ K) (labels : Label width → Λ) (exit : Option Λ) + (p : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ label, p (labels label) = statement slots labels exit label) + (base : K → List Bool) (radix acc digit : Nat) (i : Fin width) + (operandRadix : base (slots (.inl 0)) = encodeWord radix) + (operandDigit : base (slots (.inr i)) = encodeWord digit) + (clean : Clean slots base) (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step p))^[stepCost radix acc digit] + (some ⟨some (labels (.radix i (.multiply .copyDrain))), ((ambient, ()), register), + stageTapes slots base i.val acc⟩) = + some ⟨some (labels (entryLabel width (i.val + 1))), ((ambient, ()), none), + stageTapes slots base (i.val + 1) (radix * acc + digit)⟩ := by + let rs := radixSlots slots i + let before := stageTapes slots base i.val acc + let after := MachineRadixStep.resultTapes rs before (radix * acc + digit) + have h01 : rs 0 ≠ rs 1 := rs.injective.ne (by decide) + have h21 : rs 2 ≠ rs 1 := rs.injective.ne (by decide) + have h31 : rs 3 ≠ rs 1 := rs.injective.ne (by decide) + have h41 : rs 4 ≠ rs 1 := rs.injective.ne (by decide) + have h51 : rs 5 ≠ rs 1 := rs.injective.ne (by decide) + have hb : before (rs 0) = encodeWord radix := by + change Function.update base (rs 1) (encodeWord acc) (rs 0) = _ + rw [Function.update_of_ne h01] + exact operandRadix + have ha : before (rs 1) = encodeWord acc := by + exact Function.update_self _ _ _ + have hd : before (rs 2) = encodeWord digit := by + change Function.update base (rs 1) (encodeWord acc) (rs 2) = _ + rw [Function.update_of_ne h21] + exact operandDigit + have hc : before (rs 4) = [] := by + change Function.update base (rs 1) (encodeWord acc) (rs 4) = _ + rw [Function.update_of_ne h41] + exact clean.counter + have hs : before (rs 5) = [] := by + change Function.update base (rs 1) (encodeWord acc) (rs 5) = _ + rw [Function.update_of_ne h51] + exact clean.scratch + have hout : before (rs 3) = [] := by + change Function.update base (rs 1) (encodeWord acc) (rs 3) = _ + rw [Function.update_of_ne h31] + exact clean.acc _ + have hradix := MachineRadixStep.radixStepTrace rs (fun l => labels (.radix i l)) + (some (labels (.clear i))) p (fun l => atLabels (.radix i l)) before radix acc digit + hb ha hd hc hs ambient register + have hold : after (rs 1) = encodeWord acc := by + change Function.update before (rs 3) _ (rs 1) = _ + rw [Function.update_of_ne (Ne.symm h31), ha] + have hstart : Function.update after (rs 1) (encodeWord acc ++ []) = after := by + rw [List.append_nil, ← hold, Function.update_eq_self] + have hfinish : Function.update after (rs 1) [] = + stageTapes slots base (i.val + 1) (radix * acc + digit) := by + have hempty : base (rs 1) = [] := clean.acc _ + change Function.update (Function.update (Function.update base (rs 1) (encodeWord acc)) + (rs 3) (encodeWord (radix * acc + digit) ++ before (rs 3))) (rs 1) [] = + Function.update base (rs 3) (encodeWord (radix * acc + digit)) + rw [hout, List.append_nil] + funext k + by_cases h1 : k = rs 1 + · subst k; simp [Ne.symm h31, hempty] + · by_cases h3 : k = rs 3 + · subst k; simp [h31] + · simp [h1, h3] + have hdrain := drainTrace (rs 1) (labels (.clear i)) + (some (labels (entryLabel width (i.val + 1)))) p (atLabels (.clear i)) + after acc [] ambient none + rw [hstart, hfinish] at hdrain + rw [show stepCost radix acc digit = (acc + 1) + MachineRadixStep.steps radix acc digit by + unfold stepCost; omega, Function.iterate_add_apply, hradix] + exact hdrain + +theorem prefixTrace (slots : Layout width ↪ K) (labels : Label width → Λ) (exit : Option Λ) + (p : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ label, p (labels label) = statement slots labels exit label) + (base : K → List Bool) (radix : Nat) (digits : Nat → Nat) + (operandRadix : base (slots (.inl 0)) = encodeWord radix) + (operandDigits : ∀ i : Fin width, base (slots (.inr i)) = encodeWord (digits i.val)) + (clean : Clean slots base) (ambient : σ) (n : Nat) (hn : n ≤ width) : + (MachineComposition.advance (TM2.step p))^[prefixSteps radix digits n] + (some ⟨some (labels (entryLabel width 0)), ((ambient, ()), none), stageTapes slots base 0 0⟩) = + some ⟨some (labels (entryLabel width n)), ((ambient, ()), none), + stageTapes slots base n (value radix digits n)⟩ := by + induction n with + | zero => rfl + | succ n ih => + have hlt : n < width := by omega + let i : Fin width := ⟨n, hlt⟩ + rw [prefixSteps, Nat.add_comm, Function.iterate_add_apply, ih (by omega)] + have h := digitTrace slots labels exit p atLabels base radix (value radix digits n) + (digits n) i operandRadix (operandDigits i) clean ambient none + simpa only [entryLabel, dite_eq_left hlt, i, value] using h + +theorem finishTrace (slots : Layout width ↪ K) (labels : Label width → Λ) (exit : Option Λ) + (p : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ label, p (labels label) = statement slots labels exit label) + (base : K → List Bool) (acc : Nat) (clean : Clean slots base) (ambient : σ) : + (MachineComposition.advance (TM2.step p))^[2 * acc + 4] + (some ⟨some (labels .finishDrain), ((ambient, ()), none), stageTapes slots base width acc⟩) = + some ⟨exit, ((ambient, ()), none), resultTapes slots base acc⟩ := by + let src := slots (.inl (accumulator (parity width))) + let scratch := slots (.inl 5) + let dst := slots (.inl 3) + have hsrcScratch : src ≠ scratch := by + apply slots.injective.ne + cases parity width <;> simp [accumulator] + have hsrcDst : src ≠ dst := by + apply slots.injective.ne + cases parity width <;> simp [accumulator] + have hscratchDst : scratch ≠ dst := slots.injective.ne (by simp) + have hsrc : base src = [] := clean.acc _ + have hs : base scratch = [] := clean.scratch + let before := stageTapes slots base width acc + let middle := Function.update base scratch (encodeWord acc).reverse + have hinput : before src = encodeWord acc := Function.update_self _ _ _ + have hscratch : before scratch = [] := by + change Function.update base src (encodeWord acc) scratch = [] + rw [Function.update_of_ne (Ne.symm hsrcScratch), hs] + have hfirstTapes : Reduction.MachineTransfer.tapesAt src scratch before [] + ((before src).reverse.map id ++ before scratch) = middle := by + rw [hinput, hscratch, List.append_nil, List.map_id] + funext k + by_cases h1 : k = src + · subst k + simp [Reduction.MachineTransfer.tapesAt, middle, hsrcScratch, hsrc] + · by_cases h2 : k = scratch + · subst k; simp [Reduction.MachineTransfer.tapesAt, middle] + · simp [Reduction.MachineTransfer.tapesAt, middle, before, stageTapes, h1, h2, src] + have first := Reduction.MachineTransfer.transferAt_fromTapes (Γ := fun _ : K => Bool) (σ := σ × Unit) src scratch hsrcScratch id false + (labels .finishDrain) (some (labels .finishRestore)) p (atLabels .finishDrain) + before (ambient, ()) none + rw [hfirstTapes] at first + have hlength : (before src).length + 1 = acc + 2 := by + simp [hinput, encodeWord, Nat.add_assoc] + rw [hlength] at first + change (MachineComposition.advance (TM2.step p))^[acc + 2] + (some ⟨some (labels .finishDrain), ((ambient, ()), none), before⟩) = + some ⟨some (labels .finishRestore), ((ambient, ()), none), middle⟩ at first + have hmSource : middle scratch = (encodeWord acc).reverse := Function.update_self _ _ _ + have hmOutput : middle dst = base dst := by + exact Function.update_of_ne (Ne.symm hscratchDst) _ _ + have hsecondTapes : Reduction.MachineTransfer.tapesAt scratch dst middle [] + ((middle scratch).reverse.map id ++ middle dst) = resultTapes slots base acc := by + rw [hmSource, hmOutput, List.reverse_reverse, List.map_id] + funext k + by_cases h1 : k = dst + · subst k; simp [Reduction.MachineTransfer.tapesAt, resultTapes, dst] + · by_cases h2 : k = scratch + · subst k + simp [Reduction.MachineTransfer.tapesAt, resultTapes, middle, hscratchDst, hs, scratch, dst] + · simp [Reduction.MachineTransfer.tapesAt, resultTapes, middle, h1, h2, dst] + have second := Reduction.MachineTransfer.transferAt_fromTapes (Γ := fun _ : K => Bool) (σ := σ × Unit) scratch dst hscratchDst id false + (labels .finishRestore) exit p (atLabels .finishRestore) middle (ambient, ()) none + rw [hsecondTapes] at second + have hmLength : (middle scratch).length + 1 = acc + 2 := by + simp [hmSource, encodeWord, Nat.add_assoc] + rw [hmLength] at second + change (MachineComposition.advance (TM2.step p))^[acc + 2] + (some ⟨some (labels .finishRestore), ((ambient, ()), none), middle⟩) = + some ⟨exit, ((ambient, ()), none), resultTapes slots base acc⟩ at second + rw [show 2 * acc + 4 = (acc + 2) + (acc + 2) by omega, + Function.iterate_add_apply, first] + exact second + +def steps (radix : Nat) (digits : Nat → Nat) (width : Nat) : Nat := + prefixSteps radix digits width + 2 * value radix digits width + 5 + +theorem hornerTrace (slots : Layout width ↪ K) (labels : Label width → Λ) (exit : Option Λ) + (p : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ label, p (labels label) = statement slots labels exit label) + (base : K → List Bool) (radix : Nat) (digits : Nat → Nat) + (operandRadix : base (slots (.inl 0)) = encodeWord radix) + (operandDigits : ∀ i : Fin width, base (slots (.inr i)) = encodeWord (digits i.val)) + (clean : Clean slots base) (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step p))^[steps radix digits width] + (some ⟨some (labels .start), ((ambient, ()), register), base⟩) = + some ⟨exit, ((ambient, ()), none), resultTapes slots base (value radix digits width)⟩ := by + have start : TM2.step p ⟨some (labels .start), ((ambient, ()), register), base⟩ = + some ⟨some (labels (entryLabel width 0)), ((ambient, ()), none), stageTapes slots base 0 0⟩ := by + change some (TM2.stepAux (p (labels .start)) _ _) = _ + rw [atLabels .start] + simp only [statement, TM2.stepAux, clean.accA, stageTapes, parity, accumulator, + Bool.false_eq_true, ↓reduceIte, encodeWord, List.replicate_zero, List.nil_append] + have prefixRun := prefixTrace slots labels exit p atLabels base radix digits operandRadix + operandDigits clean ambient width (Nat.le_refl _) + have final := finishTrace slots labels exit p atLabels base (value radix digits width) clean ambient + have hend : entryLabel width width = .finishDrain := by simp [entryLabel] + rw [hend] at prefixRun + rw [show steps radix digits width = + ((2 * value radix digits width + 4) + prefixSteps radix digits width) + 1 by + unfold steps; omega, Function.iterate_succ_apply] + change (MachineComposition.advance (TM2.step p))^[ + (2 * value radix digits width + 4) + prefixSteps radix digits width] + (TM2.step p ⟨some (labels .start), ((ambient, ()), register), base⟩) = _ + rw [start, Function.iterate_add_apply, prefixRun] + exact final + +omit [DecidableEq K] in +theorem value_eq_foldl (radix : Nat) (digits : Nat → Nat) (n : Nat) : + value radix digits n = + ((List.range n).map digits).foldl (fun acc digit => radix * acc + digit) 0 := by + induction n with + | zero => rfl + | succ n ih => + rw [value, List.range_succ, List.map_append, List.foldl_append] + simp only [List.map_singleton, List.foldl_cons, List.foldl_nil, ← ih] + +omit [DecidableEq K] in + +theorem value_add_one_le (radix : Nat) (digits : Nat → Nat) (width magnitude : Nat) + (radixBound : radix ≤ magnitude) + (digitBound : ∀ i, i < width → digits i ≤ magnitude) + (n : Nat) (hn : n ≤ width) : value radix digits n + 1 ≤ (magnitude + 1) ^ n := by + induction n with + | zero => simp [value] + | succ n ih => + have hn' : n < width := by omega + have hm := Nat.mul_le_mul_right (value radix digits n) radixBound + calc + value radix digits (n + 1) + 1 ≤ (magnitude + 1) * (value radix digits n + 1) := by + rw [value] + have hd := digitBound n hn' + nlinarith + _ ≤ (magnitude + 1) * (magnitude + 1) ^ n := + Nat.mul_le_mul_left _ (ih (by omega)) + _ = (magnitude + 1) ^ (n + 1) := by rw [pow_succ]; ac_rfl + +omit [DecidableEq K] in +theorem value_le (radix : Nat) (digits : Nat → Nat) (width magnitude : Nat) + (radixBound : radix ≤ magnitude) + (digitBound : ∀ i, i < width → digits i ≤ magnitude) + (n : Nat) (hn : n ≤ width) : value radix digits n ≤ (magnitude + 1) ^ width := by + have h := value_add_one_le radix digits width magnitude radixBound digitBound n hn + exact (Nat.le_trans (Nat.le_add_right _ _) h).trans + (Nat.pow_le_pow_right (Nat.succ_pos _) hn) + +def perDigitBound (width magnitude : Nat) : Nat := + 3 * magnitude * (magnitude + 1) ^ width + 9 * (magnitude + 1) ^ width + 3 * magnitude + 14 + +omit [DecidableEq K] in +theorem stepCost_le (radix acc digit width magnitude : Nat) + (radixBound : radix ≤ magnitude) (accBound : acc ≤ (magnitude + 1) ^ width) + (digitBound : digit ≤ magnitude) : + stepCost radix acc digit ≤ perDigitBound width magnitude := by + have hm := Nat.mul_le_mul (Nat.mul_le_mul_left 3 radixBound) accBound + unfold stepCost MachineRadixStep.steps perDigitBound + omega + +omit [DecidableEq K] in +theorem prefixSteps_le (radix : Nat) (digits : Nat → Nat) (width magnitude : Nat) + (radixBound : radix ≤ magnitude) + (digitBound : ∀ i, i < width → digits i ≤ magnitude) + (n : Nat) (hn : n ≤ width) : + prefixSteps radix digits n ≤ n * perDigitBound width magnitude := by + induction n with + | zero => simp [prefixSteps] + | succ n ih => + have hn' : n < width := by omega + have ha := value_le radix digits width magnitude radixBound digitBound n (by omega) + have hc := stepCost_le radix (value radix digits n) (digits n) width magnitude + radixBound ha (digitBound n hn') + rw [prefixSteps] + calc + prefixSteps radix digits n + stepCost radix (value radix digits n) (digits n) ≤ + n * perDigitBound width magnitude + perDigitBound width magnitude := + Nat.add_le_add (ih (by omega)) hc + _ = (n + 1) * perDigitBound width magnitude := by rw [Nat.add_mul, Nat.one_mul] + +noncomputable def timePolynomial (width : Nat) : Polynomial Nat := + Polynomial.C width * + (3 * Polynomial.X * (Polynomial.X + 1) ^ width + + 9 * (Polynomial.X + 1) ^ width + 3 * Polynomial.X + 14) + + 2 * (Polynomial.X + 1) ^ width + 5 + +omit [DecidableEq K] in +@[simp] theorem timePolynomial_eval (width magnitude : Nat) : + (timePolynomial width).eval magnitude = + width * perDigitBound width magnitude + 2 * (magnitude + 1) ^ width + 5 := by + simp [timePolynomial, perDigitBound] + +omit [DecidableEq K] in +theorem steps_le_timePolynomial (radix : Nat) (digits : Nat → Nat) (width magnitude : Nat) + (radixBound : radix ≤ magnitude) + (digitBound : ∀ i, i < width → digits i ≤ magnitude) : + steps radix digits width ≤ (timePolynomial width).eval magnitude := by + have hp := prefixSteps_le radix digits width magnitude radixBound digitBound width (Nat.le_refl _) + have hv := value_le radix digits width magnitude radixBound digitBound width (Nat.le_refl _) + rw [timePolynomial_eval] + unfold steps + omega + +def hornerInTime (slots : Layout width ↪ K) (labels : Label width → Λ) (exit : Option Λ) + (p : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ label, p (labels label) = statement slots labels exit label) + (base : K → List Bool) (radix : Nat) (digits : Nat → Nat) + (operandRadix : base (slots (.inl 0)) = encodeWord radix) + (operandDigits : ∀ i : Fin width, base (slots (.inr i)) = encodeWord (digits i.val)) + (clean : Clean slots base) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step p) + ⟨some (labels .start), ((ambient, ()), register), base⟩ + (some ⟨exit, ((ambient, ()), none), resultTapes slots base (value radix digits width)⟩) + (steps radix digits width) where + steps := steps radix digits width + evals_in_steps := hornerTrace slots labels exit p atLabels base radix digits + operandRadix operandDigits clean ambient register + steps_le_m := Nat.le_refl _ + +def hornerInPolynomialTime (slots : Layout width ↪ K) (labels : Label width → Λ) (exit : Option Λ) + (p : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ label, p (labels label) = statement slots labels exit label) + (base : K → List Bool) (radix : Nat) (digits : Nat → Nat) + (operandRadix : base (slots (.inl 0)) = encodeWord radix) + (operandDigits : ∀ i : Fin width, base (slots (.inr i)) = encodeWord (digits i.val)) + (clean : Clean slots base) (ambient : σ) (register : Option Bool) (magnitude : Nat) + (radixBound : radix ≤ magnitude) + (digitBound : ∀ i, i < width → digits i ≤ magnitude) : + StateTransition.EvalsToInTime (TM2.step p) + ⟨some (labels .start), ((ambient, ()), register), base⟩ + (some ⟨exit, ((ambient, ()), none), resultTapes slots base (value radix digits width)⟩) + ((timePolynomial width).eval magnitude) where + steps := steps radix digits width + evals_in_steps := hornerTrace slots labels exit p atLabels base radix digits + operandRadix operandDigits clean ambient register + steps_le_m := steps_le_timePolynomial radix digits width magnitude radixBound digitBound + +open scoped BigOperators + +def operandLength (radix : Nat) (digits : Nat → Nat) (width : Nat) : Nat := + (encodeWord radix).length + ∑ i ∈ Finset.range width, (encodeWord (digits i)).length + +omit [DecidableEq K] in +theorem radix_le_operandLength (radix : Nat) (digits : Nat → Nat) (width : Nat) : + radix ≤ operandLength radix digits width := by + unfold operandLength + simp only [encodeWord, List.length_append, List.length_replicate, List.length_singleton] + omega + +omit [DecidableEq K] in +theorem digit_le_operandLength (radix : Nat) (digits : Nat → Nat) (width i : Nat) + (hi : i < width) : digits i ≤ operandLength radix digits width := by + have h : (encodeWord (digits i)).length ≤ + ∑ j ∈ Finset.range width, (encodeWord (digits j)).length := + Finset.single_le_sum (fun j _ => Nat.zero_le ((encodeWord (digits j)).length)) + (Finset.mem_range.mpr hi) + have hlen : digits i + 1 ≤ ∑ j ∈ Finset.range width, (encodeWord (digits j)).length := by + simpa only [encodeWord, List.length_append, List.length_replicate, List.length_singleton] using h + unfold operandLength + omega + +@[simp] theorem resultTapes_output (slots : Layout width ↪ K) (base : K → List Bool) (acc : Nat) : + resultTapes slots base acc (slots (.inl 3)) = encodeWord acc ++ base (slots (.inl 3)) := by + simp [resultTapes] + +theorem resultTapes_other (slots : Layout width ↪ K) (base : K → List Bool) (acc : Nat) + (k : K) (hk : k ≠ slots (.inl 3)) : resultTapes slots base acc k = base k := by + simp [resultTapes, hk] + +def hornerInEncodedPolynomialTime (slots : Layout width ↪ K) (labels : Label width → Λ) + (exit : Option Λ) (p : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ label, p (labels label) = statement slots labels exit label) + (base : K → List Bool) (radix : Nat) (digits : Nat → Nat) + (operandRadix : base (slots (.inl 0)) = encodeWord radix) + (operandDigits : ∀ i : Fin width, base (slots (.inr i)) = encodeWord (digits i.val)) + (clean : Clean slots base) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step p) + ⟨some (labels .start), ((ambient, ()), register), base⟩ + (some ⟨exit, ((ambient, ()), none), resultTapes slots base (value radix digits width)⟩) + ((timePolynomial width).eval (operandLength radix digits width)) := + hornerInPolynomialTime slots labels exit p atLabels base radix digits operandRadix operandDigits + clean ambient register (operandLength radix digits width) + (radix_le_operandLength radix digits width) + (fun i hi => digit_le_operandLength radix digits width i hi) + +end MinUncutGames.Foundations.Complexity.MachineHorner + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/MachineUnaryCounter.lean b/lean/OAI/Computability/MinUncut/Machines/MachineUnaryCounter.lean new file mode 100644 index 0000000000000000000000000000000000000000..a72062bcd7ea1a7cd3135fe09a451c8db9251344 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/MachineUnaryCounter.lean @@ -0,0 +1,766 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.Machine + +namespace OAI + +namespace MinUncutGames.Foundations.Complexity.MachineUnaryCounter + +open Turing + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool + +def guard (counter : K) (bodyLabel exitLabel : Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) := + .peek counter (fun state head => (state.1, head)) + (.branch (fun state => state.2.getD false) + (.pop counter (fun state _ => (state.1, none)) (.goto fun _ => bodyLabel)) + (.load (fun state => (state.1, none)) (.goto fun _ => exitLabel))) + +def counterTapes (counter : K) (base : K → List Bool) (n : Nat) + (suffix : List Bool) : K → List Bool := + Function.update base counter (encodeWord n ++ suffix) + +@[simp] theorem counterTapes_counter (counter : K) (base : K → List Bool) + (n : Nat) (suffix : List Bool) : + counterTapes counter base n suffix counter = encodeWord n ++ suffix := by + simp [counterTapes] + +theorem counterTapes_other (counter other : K) (hne : other ≠ counter) + (base : K → List Bool) (n : Nat) (suffix : List Bool) : + counterTapes counter base n suffix other = base other := by + simp [counterTapes, hne] + +omit [DecidableEq K] in +theorem guardPushBound (counter : K) (bodyLabel exitLabel : Λ) : + Runtime.statementPushBound (guard (σ := σ) counter bodyLabel exitLabel) = 0 := by + rfl + +theorem stepAux_succ (counter : K) (bodyLabel exitLabel : Λ) + (base : K → List Bool) (n : Nat) (suffix : List Bool) + (ambient : σ) (register : Option Bool) : + TM2.stepAux (guard counter bodyLabel exitLabel) (ambient, register) + (counterTapes counter base (n + 1) suffix) = + ⟨some bodyLabel, (ambient, none), counterTapes counter base n suffix⟩ := by + simp [guard, TM2.stepAux, counterTapes, encodeWord, List.replicate_succ] + +theorem stepAux_zero (counter : K) (bodyLabel exitLabel : Λ) + (base : K → List Bool) (suffix : List Bool) + (ambient : σ) (register : Option Bool) : + TM2.stepAux (guard counter bodyLabel exitLabel) (ambient, register) + (counterTapes counter base 0 suffix) = + ⟨some exitLabel, (ambient, none), counterTapes counter base 0 suffix⟩ := by + simp [guard, TM2.stepAux, counterTapes, encodeWord] + +theorem guardStep_succ (counter : K) (guardLabel bodyLabel exitLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atGuard : program guardLabel = guard counter bodyLabel exitLabel) + (base : K → List Bool) (n : Nat) (suffix : List Bool) + (ambient : σ) (register : Option Bool) : + TM2.step program + ⟨some guardLabel, (ambient, register), counterTapes counter base (n + 1) suffix⟩ = + some ⟨some bodyLabel, (ambient, none), counterTapes counter base n suffix⟩ := by + change some (TM2.stepAux (program guardLabel) (ambient, register) + (counterTapes counter base (n + 1) suffix)) = _ + rw [atGuard, stepAux_succ] + +theorem guardStep_zero (counter : K) (guardLabel bodyLabel exitLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atGuard : program guardLabel = guard counter bodyLabel exitLabel) + (base : K → List Bool) (suffix : List Bool) + (ambient : σ) (register : Option Bool) : + TM2.step program + ⟨some guardLabel, (ambient, register), counterTapes counter base 0 suffix⟩ = + some ⟨some exitLabel, (ambient, none), counterTapes counter base 0 suffix⟩ := by + change some (TM2.stepAux (program guardLabel) (ambient, register) + (counterTapes counter base 0 suffix)) = _ + rw [atGuard, stepAux_zero] + +theorem guardTrace_succ (counter : K) (guardLabel bodyLabel exitLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atGuard : program guardLabel = guard counter bodyLabel exitLabel) + (base : K → List Bool) (n : Nat) (suffix : List Bool) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[1] + (some ⟨some guardLabel, (ambient, register), + counterTapes counter base (n + 1) suffix⟩) = + some ⟨some bodyLabel, (ambient, none), counterTapes counter base n suffix⟩ := by + simpa only [Function.iterate_one, MachineComposition.advance_some] using + guardStep_succ counter guardLabel bodyLabel exitLabel program atGuard + base n suffix ambient register + +theorem guardTrace_zero (counter : K) (guardLabel bodyLabel exitLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atGuard : program guardLabel = guard counter bodyLabel exitLabel) + (base : K → List Bool) (suffix : List Bool) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[1] + (some ⟨some guardLabel, (ambient, register), counterTapes counter base 0 suffix⟩) = + some ⟨some exitLabel, (ambient, none), counterTapes counter base 0 suffix⟩ := by + simpa only [Function.iterate_one, MachineComposition.advance_some] using + guardStep_zero counter guardLabel bodyLabel exitLabel program atGuard + base suffix ambient register + +def guardInTime_succ (counter : K) (guardLabel bodyLabel exitLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atGuard : program guardLabel = guard counter bodyLabel exitLabel) + (base : K → List Bool) (n : Nat) (suffix : List Bool) + (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some guardLabel, (ambient, register), counterTapes counter base (n + 1) suffix⟩ + (some ⟨some bodyLabel, (ambient, none), counterTapes counter base n suffix⟩) 1 where + steps := 1 + evals_in_steps := by + change (MachineComposition.advance (TM2.step program))^[1] _ = _ + exact guardTrace_succ counter guardLabel bodyLabel exitLabel program atGuard + base n suffix ambient register + steps_le_m := Nat.le_refl _ + +def guardInTime_zero (counter : K) (guardLabel bodyLabel exitLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atGuard : program guardLabel = guard counter bodyLabel exitLabel) + (base : K → List Bool) (suffix : List Bool) + (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some guardLabel, (ambient, register), counterTapes counter base 0 suffix⟩ + (some ⟨some exitLabel, (ambient, none), counterTapes counter base 0 suffix⟩) 1 where + steps := 1 + evals_in_steps := by + change (MachineComposition.advance (TM2.step program))^[1] _ = _ + exact guardTrace_zero counter guardLabel bodyLabel exitLabel program atGuard + base suffix ambient register + steps_le_m := Nat.le_refl _ + +end MinUncutGames.Foundations.Complexity.MachineUnaryCounter + +namespace MinUncutGames.Foundations.Complexity.MachineLookup + +open Turing + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool + +def discard (source : K) (loopLabel returnLabel : Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) := + .pop source (fun state head => (state.1, head)) + (.branch (fun state => state.2.getD false) + (.goto fun _ => loopLabel) + (.load (fun state => (state.1, none)) (.goto fun _ => returnLabel))) + +def select (source destination : K) (copyLabel rejected : Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) := + .peek source (fun state head => (state.1, head)) + (.branch (fun state => state.2.isSome) + (Hastad.SourceMachine.fieldStart destination copyLabel) + (.load (fun state => (state.1, none)) (.goto fun _ => rejected))) + +inductive Label + | guard | skip | select | copy | accepted | rejected + deriving DecidableEq + +protected abbrev Label.enumList : List Label := [.guard, .skip, .select, .copy, .accepted, + .rejected] + +protected theorem Label.enumList_getElem?_ctorIdx_eq (x : Label) : + Label.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem Label.enumList_nodup : Label.enumList.Nodup := by decide + +instance : Fintype Label where + elems := ⟨Label.enumList, Label.enumList_nodup⟩ + complete x := by cases x <;> decide + +def program (index source destination : K) : + Label → TM2.Stmt (Alphabet (K := K)) Label (σ × Option Bool) + | .guard => MachineUnaryCounter.guard index .skip .select + | .skip => discard source .skip .guard + | .select => select source destination .copy .rejected + | .copy => Hastad.SourceMachine.fieldLoop source destination .copy (some .accepted) + | .accepted => .halt + | .rejected => .halt + +def tapes (index source destination : K) (base : K → List Bool) + (counter input output : List Bool) : K → List Bool := + Function.update (Function.update (Function.update base index counter) source input) + destination output + +@[simp] theorem tapes_index (index source destination : K) + (his : index ≠ source) (hid : index ≠ destination) + (base : K → List Bool) (counter input output : List Bool) : + tapes index source destination base counter input output index = counter := by + simp [tapes, his, hid] + +@[simp] theorem tapes_source (index source destination : K) + (hsd : source ≠ destination) (base : K → List Bool) + (counter input output : List Bool) : + tapes index source destination base counter input output source = input := by + simp [tapes, hsd] + +@[simp] theorem tapes_destination (index source destination : K) + (base : K → List Bool) (counter input output : List Bool) : + tapes index source destination base counter input output destination = output := by + simp [tapes] + +theorem tapes_other (index source destination p : K) + (hi : p ≠ index) (hs : p ≠ source) (hd : p ≠ destination) + (base : K → List Bool) (counter input output : List Bool) : + tapes index source destination base counter input output p = base p := by + simp [tapes, hi, hs, hd] + +theorem update_index (index source destination : K) + (his : index ≠ source) (hid : index ≠ destination) + (base : K → List Bool) (counter input output replacement : List Bool) : + Function.update (tapes index source destination base counter input output) index replacement = + tapes index source destination base replacement input output := by + funext p + by_cases hi : p = index + · subst p; simp [tapes, his, hid] + · by_cases hs : p = source + · subst p; by_cases hs : source = destination <;> simp [tapes, hi, hs, Ne.symm hid] + · by_cases hd : p = destination + · subst p; simp [tapes, hi] + · simp [tapes, hi, hs, hd] + +theorem update_source (index source destination : K) (hsd : source ≠ destination) + (base : K → List Bool) (counter input output replacement : List Bool) : + Function.update (tapes index source destination base counter input output) source replacement = + tapes index source destination base counter replacement output := by + funext p + by_cases hs : p = source + · subst p; simp [tapes, hsd] + · by_cases hd : p = destination + · subst p; simp [tapes, hs] + · simp [tapes, hs, hd] + +theorem update_destination (index source destination : K) + (base : K → List Bool) (counter input output replacement : List Bool) : + Function.update (tapes index source destination base counter input output) + destination replacement = tapes index source destination base counter input replacement := by + simp [tapes] + +theorem fieldTapes_eq (index source destination : K) (hsd : source ≠ destination) + (base : K → List Bool) (counter input output input' output' : List Bool) : + Hastad.SourceMachine.fieldTapes source destination + (tapes index source destination base counter input output) input' output' = + tapes index source destination base counter input' output' := by + rw [Hastad.SourceMachine.fieldTapes, update_source _ _ _ hsd, update_destination] + +def machine : FinTM2 where + K := Fin 3 + k₀ := 1 + k₁ := 2 + Γ _ := Bool + Λ := Label + main := .guard + σ := Unit × Option Bool + initialState := ((), none) + m := program 0 1 2 + +open Turing + +variable {K Λ σ : Type} [DecidableEq K] + +private theorem discard_update_twice (source : K) (base : K → List Bool) + (input replacement : List Bool) : + Function.update (Function.update base source input) source replacement = + Function.update base source replacement := by + funext p + by_cases hp : p = source + · subst p; simp + · simp [hp] + +theorem discardStep_delimiter (source : K) (loopLabel returnLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atLoop : program loopLabel = discard source loopLabel returnLabel) + (base : K → List Bool) (suffix : List Bool) (ambient : σ) + (register : Option Bool) : + TM2.step program + ⟨some loopLabel, (ambient, register), Function.update base source (false :: suffix)⟩ = + some ⟨some returnLabel, (ambient, none), Function.update base source suffix⟩ := by + change some (TM2.stepAux (program loopLabel) (ambient, register) + (Function.update base source (false :: suffix))) = _ + rw [atLoop] + simp [discard, TM2.stepAux] + +theorem discardStep_true (source : K) (loopLabel returnLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atLoop : program loopLabel = discard source loopLabel returnLabel) + (base : K → List Bool) (input : List Bool) (ambient : σ) + (register : Option Bool) : + TM2.step program + ⟨some loopLabel, (ambient, register), Function.update base source (true :: input)⟩ = + some ⟨some loopLabel, (ambient, some true), Function.update base source input⟩ := by + change some (TM2.stepAux (program loopLabel) (ambient, register) + (Function.update base source (true :: input))) = _ + rw [atLoop] + simp [discard, TM2.stepAux] + +theorem discard_empty_step (source : K) (loopLabel returnLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atLoop : program loopLabel = discard source loopLabel returnLabel) + (base : K → List Bool) (hinput : base source = []) + (ambient : σ) (register : Option Bool) : + TM2.step program ⟨some loopLabel, (ambient, register), base⟩ = + some ⟨some returnLabel, (ambient, none), base⟩ := by + have hupdate : Function.update base source [] = base := by + funext p + by_cases hp : p = source + · subst p; simp [hinput] + · simp [hp] + change some (TM2.stepAux (program loopLabel) (ambient, register) base) = _ + rw [atLoop] + simp [discard, TM2.stepAux, hinput, hupdate] + +theorem discardTrace_update (source : K) (loopLabel returnLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atLoop : program loopLabel = discard source loopLabel returnLabel) + (base : K → List Bool) (n : Nat) (suffix : List Bool) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[n + 1] + (some ⟨some loopLabel, (ambient, register), + Function.update base source (encodeWord n ++ suffix)⟩) = + some ⟨some returnLabel, (ambient, none), Function.update base source suffix⟩ := by + induction n generalizing register with + | zero => + simpa only [Nat.zero_add, Function.iterate_one, MachineComposition.advance_some, + encodeWord, List.replicate_zero, List.nil_append, List.singleton_append] using + discardStep_delimiter source loopLabel returnLabel program atLoop + base suffix ambient register + | succ n ih => + rw [Function.iterate_succ_apply] + simp only [encodeWord, List.replicate_succ, List.cons_append] + change (MachineComposition.advance (TM2.step program))^[n + 1] + (TM2.step program ⟨some loopLabel, (ambient, register), + Function.update base source (true :: (encodeWord n ++ suffix))⟩) = _ + rw [discardStep_true source loopLabel returnLabel program atLoop, ih] + +theorem discardTrace (source : K) (loopLabel returnLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atLoop : program loopLabel = discard source loopLabel returnLabel) + (base : K → List Bool) (n : Nat) (suffix : List Bool) + (hinput : base source = encodeWord n ++ suffix) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[n + 1] + (some ⟨some loopLabel, (ambient, register), base⟩) = + some ⟨some returnLabel, (ambient, none), Function.update base source suffix⟩ := by + have hbase : Function.update base source (encodeWord n ++ suffix) = base := by + funext p + by_cases hp : p = source + · subst p; simp [hinput] + · simp [hp] + have h := discardTrace_update source loopLabel returnLabel program atLoop + base n suffix ambient register + rw [hbase] at h + exact h + +def discardInTime (source : K) (loopLabel returnLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atLoop : program loopLabel = discard source loopLabel returnLabel) + (base : K → List Bool) (n : Nat) (suffix : List Bool) + (hinput : base source = encodeWord n ++ suffix) + (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some loopLabel, (ambient, register), base⟩ + (some ⟨some returnLabel, (ambient, none), Function.update base source suffix⟩) + (n + 1) where + steps := n + 1 + evals_in_steps := discardTrace source loopLabel returnLabel program atLoop + base n suffix hinput ambient register + steps_le_m := Nat.le_refl _ + +end MinUncutGames.Foundations.Complexity.MachineLookup + +namespace MinUncutGames.Foundations.Complexity.MachineCopy + +open Turing + +variable {K Λ σ β : Type} [DecidableEq K] + +abbrev Alphabet (β : Type) (_ : K) := β + +def forkLoop (source left right : K) (fallback : β) (loopLabel : Λ) (exit : Option Λ) : + TM2.Stmt (Alphabet (K := K) β) Λ (σ × Option β) := + .pop source (fun state head => (state.1, head)) + (.branch (fun state => state.2.isSome) + (.push left (fun state => state.2.getD fallback) + (.push right (fun state => state.2.getD fallback) (.goto fun _ => loopLabel))) + (Reduction.MachineTransfer.exitAt right exit)) + +def forkTapes (source left right : K) (base : K → List β) + (input leftOutput rightOutput : List β) : K → List β := + Function.update (Function.update (Function.update base source input) left leftOutput) + right rightOutput + +@[simp] theorem forkTapes_source (source left right : K) + (sourceLeft : source ≠ left) (sourceRight : source ≠ right) + (base : K → List β) (input leftOutput rightOutput : List β) : + forkTapes source left right base input leftOutput rightOutput source = input := by + simp [forkTapes, sourceLeft, sourceRight] + +@[simp] theorem forkTapes_left (source left right : K) (leftRight : left ≠ right) + (base : K → List β) (input leftOutput rightOutput : List β) : + forkTapes source left right base input leftOutput rightOutput left = leftOutput := by + simp [forkTapes, leftRight] + +@[simp] theorem forkTapes_right (source left right : K) + (base : K → List β) (input leftOutput rightOutput : List β) : + forkTapes source left right base input leftOutput rightOutput right = rightOutput := by + simp [forkTapes] + +@[simp] theorem forkTapes_self (source left right : K) (base : K → List β) : + forkTapes source left right base (base source) (base left) (base right) = base := by + simp [forkTapes] + +private theorem update_fork_source (source left right : K) + (sourceLeft : source ≠ left) (sourceRight : source ≠ right) (leftRight : left ≠ right) + (base : K → List β) (input leftOutput rightOutput replacement : List β) : + Function.update (forkTapes source left right base input leftOutput rightOutput) + source replacement = forkTapes source left right base replacement leftOutput rightOutput := by + funext k + by_cases hs : k = source + · subst k; simp [forkTapes, sourceLeft, sourceRight] + · by_cases hl : k = left + · subst k; simp [forkTapes, Ne.symm sourceLeft, leftRight] + · by_cases hr : k = right + · subst k; simp [forkTapes, Ne.symm sourceRight] + · simp [forkTapes, hs, hl, hr] + +private theorem update_fork_left (source left right : K) (leftRight : left ≠ right) + (base : K → List β) (input leftOutput rightOutput replacement : List β) : + Function.update (forkTapes source left right base input leftOutput rightOutput) + left replacement = forkTapes source left right base input replacement rightOutput := by + funext k + by_cases hl : k = left + · subst k; simp [forkTapes, leftRight] + · by_cases hr : k = right + · subst k; simp [forkTapes, Ne.symm leftRight] + · simp [forkTapes, hl, hr] + +private theorem update_fork_right (source left right : K) + (base : K → List β) (input leftOutput rightOutput replacement : List β) : + Function.update (forkTapes source left right base input leftOutput rightOutput) + right replacement = forkTapes source left right base input leftOutput replacement := by + simp [forkTapes] + +theorem forkStep_empty (source left right : K) + (sourceLeft : source ≠ left) (sourceRight : source ≠ right) (leftRight : left ≠ right) + (fallback : β) (loopLabel : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K) β) Λ (σ × Option β)) + (atLoop : program loopLabel = forkLoop source left right fallback loopLabel exit) + (base : K → List β) (leftOutput rightOutput : List β) (ambient : σ) (register : Option β) : + TM2.step program + ⟨some loopLabel, (ambient, register), forkTapes source left right base [] leftOutput rightOutput⟩ = + some ⟨exit, (ambient, none), forkTapes source left right base [] leftOutput rightOutput⟩ := by + change some (TM2.stepAux (program loopLabel) (ambient, register) + (forkTapes source left right base [] leftOutput rightOutput)) = _ + rw [atLoop] + cases exit <;> + simp [forkLoop, Reduction.MachineTransfer.exitAt, TM2.stepAux, sourceLeft, sourceRight, + leftRight, update_fork_source] + +theorem forkStep_cons (source left right : K) + (sourceLeft : source ≠ left) (sourceRight : source ≠ right) (leftRight : left ≠ right) + (fallback : β) (loopLabel : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K) β) Λ (σ × Option β)) + (atLoop : program loopLabel = forkLoop source left right fallback loopLabel exit) + (base : K → List β) (head : β) (input leftOutput rightOutput : List β) + (ambient : σ) (register : Option β) : + TM2.step program + ⟨some loopLabel, (ambient, register), + forkTapes source left right base (head :: input) leftOutput rightOutput⟩ = + some ⟨some loopLabel, (ambient, some head), + forkTapes source left right base input (head :: leftOutput) (head :: rightOutput)⟩ := by + change some (TM2.stepAux (program loopLabel) (ambient, register) + (forkTapes source left right base (head :: input) leftOutput rightOutput)) = _ + rw [atLoop] + simp [forkLoop, TM2.stepAux, sourceLeft, sourceRight, leftRight, + update_fork_source, update_fork_left, update_fork_right] + +theorem forkTrace (source left right : K) + (sourceLeft : source ≠ left) (sourceRight : source ≠ right) (leftRight : left ≠ right) + (fallback : β) (loopLabel : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K) β) Λ (σ × Option β)) + (atLoop : program loopLabel = forkLoop source left right fallback loopLabel exit) + (base : K → List β) (input leftOutput rightOutput : List β) + (ambient : σ) (register : Option β) : + (MachineComposition.advance (TM2.step program))^[input.length + 1] + (some ⟨some loopLabel, (ambient, register), + forkTapes source left right base input leftOutput rightOutput⟩) = + some ⟨exit, (ambient, none), forkTapes source left right base [] + (input.reverse ++ leftOutput) (input.reverse ++ rightOutput)⟩ := by + induction input generalizing leftOutput rightOutput register with + | nil => + simpa only [List.length_nil, Nat.zero_add, Function.iterate_one, + MachineComposition.advance_some, List.reverse_nil, List.nil_append] using + forkStep_empty source left right sourceLeft sourceRight leftRight fallback loopLabel exit + program atLoop base leftOutput rightOutput ambient register + | cons head input ih => + rw [List.length_cons, Function.iterate_succ_apply] + change (MachineComposition.advance (TM2.step program))^[input.length + 1] + (TM2.step program ⟨some loopLabel, (ambient, register), + forkTapes source left right base (head :: input) leftOutput rightOutput⟩) = _ + rw [forkStep_cons source left right sourceLeft sourceRight leftRight fallback loopLabel exit + program atLoop base head input leftOutput rightOutput ambient register, ih] + simp only [List.reverse_cons, List.append_assoc, List.singleton_append] + +def forkInTime (source left right : K) + (sourceLeft : source ≠ left) (sourceRight : source ≠ right) (leftRight : left ≠ right) + (fallback : β) (loopLabel : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K) β) Λ (σ × Option β)) + (atLoop : program loopLabel = forkLoop source left right fallback loopLabel exit) + (base : K → List β) (ambient : σ) (register : Option β) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some loopLabel, (ambient, register), base⟩ + (some ⟨exit, (ambient, none), forkTapes source left right base [] + ((base source).reverse ++ base left) ((base source).reverse ++ base right)⟩) + ((base source).length + 1) where + steps := (base source).length + 1 + evals_in_steps := by + change (MachineComposition.advance (TM2.step program))^[(base source).length + 1] + (some ⟨some loopLabel, (ambient, register), base⟩) = _ + simpa only [forkTapes_self] using + forkTrace source left right sourceLeft sourceRight leftRight fallback loopLabel exit + program atLoop base (base source) (base left) (base right) ambient register + steps_le_m := Nat.le_refl _ + +def drainedTapes (source scratch : K) (base : K → List β) : K → List β := + Reduction.MachineTransfer.tapesAt source scratch base [] (base source).reverse + +theorem restoredTapes (source destination scratch : K) + (sourceDestination : source ≠ destination) (sourceScratch : source ≠ scratch) + (destinationScratch : destination ≠ scratch) (base : K → List β) + (scratchEmpty : base scratch = []) : + forkTapes scratch source destination (drainedTapes source scratch base) [] + (base source) (base source ++ base destination) = + Function.update base destination (base source ++ base destination) := by + funext k + by_cases hs : k = source + · subst k + simp [forkTapes, sourceDestination] + · by_cases hd : k = destination + · subst k; simp [forkTapes] + · by_cases ht : k = scratch + · subst k + simp [forkTapes, Ne.symm sourceScratch, Ne.symm destinationScratch, scratchEmpty] + · simp [forkTapes, drainedTapes, Reduction.MachineTransfer.tapesAt, hs, hd, ht] + +theorem copyTrace (source destination scratch : K) + (sourceDestination : source ≠ destination) (sourceScratch : source ≠ scratch) + (destinationScratch : destination ≠ scratch) + (fallback : β) (firstLabel secondLabel : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K) β) Λ (σ × Option β)) + (atFirst : program firstLabel = + Reduction.MachineTransfer.loopAt source scratch id fallback firstLabel (some secondLabel)) + (atSecond : program secondLabel = forkLoop scratch source destination fallback secondLabel exit) + (base : K → List β) (scratchEmpty : base scratch = []) + (ambient : σ) (register : Option β) : + (MachineComposition.advance (TM2.step program))^[2 * ((base source).length + 1)] + (some ⟨some firstLabel, (ambient, register), base⟩) = + some ⟨exit, (ambient, none), + Function.update base destination (base source ++ base destination)⟩ := by + have first := Reduction.MachineTransfer.transferAt_fromTapes source scratch sourceScratch + id fallback firstLabel (some secondLabel) program atFirst base ambient register + change (MachineComposition.advance (TM2.step program))^[(base source).length + 1] + (some ⟨some firstLabel, (ambient, register), base⟩) = _ at first + simp only [List.map_id, scratchEmpty, List.append_nil] at first + have second := forkTrace scratch source destination (Ne.symm sourceScratch) + (Ne.symm destinationScratch) sourceDestination fallback secondLabel exit program atSecond + (drainedTapes source scratch base) + (drainedTapes source scratch base scratch) (drainedTapes source scratch base source) + (drainedTapes source scratch base destination) ambient none + simp only [forkTapes_self] at second + have scratchWord : drainedTapes source scratch base scratch = (base source).reverse := by + simp [drainedTapes] + have sourceWord : drainedTapes source scratch base source = [] := by + simp [drainedTapes, sourceScratch] + have destinationWord : drainedTapes source scratch base destination = base destination := by + simp [drainedTapes, Reduction.MachineTransfer.tapesAt, Ne.symm sourceDestination, + destinationScratch] + rw [scratchWord, sourceWord, destinationWord] at second + simp only [List.reverse_reverse, List.append_nil, List.length_reverse] at second + rw [restoredTapes source destination scratch sourceDestination sourceScratch destinationScratch + base scratchEmpty] at second + rw [show 2 * ((base source).length + 1) = + ((base source).length + 1) + ((base source).length + 1) by omega, + Function.iterate_add_apply, first] + exact second + +def copyInTime (source destination scratch : K) + (sourceDestination : source ≠ destination) (sourceScratch : source ≠ scratch) + (destinationScratch : destination ≠ scratch) + (fallback : β) (firstLabel secondLabel : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K) β) Λ (σ × Option β)) + (atFirst : program firstLabel = + Reduction.MachineTransfer.loopAt source scratch id fallback firstLabel (some secondLabel)) + (atSecond : program secondLabel = forkLoop scratch source destination fallback secondLabel exit) + (base : K → List β) (scratchEmpty : base scratch = []) + (ambient : σ) (register : Option β) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some firstLabel, (ambient, register), base⟩ + (some ⟨exit, (ambient, none), + Function.update base destination (base source ++ base destination)⟩) + (2 * ((base source).length + 1)) where + steps := 2 * ((base source).length + 1) + evals_in_steps := copyTrace source destination scratch sourceDestination sourceScratch + destinationScratch fallback firstLabel secondLabel exit program atFirst atSecond base + scratchEmpty ambient register + steps_le_m := Nat.le_refl _ + +end MinUncutGames.Foundations.Complexity.MachineCopy + +namespace MinUncutGames.Foundations.Complexity.MachineCountedLoop + +open Turing +open scoped BigOperators +open MachineUnaryCounter + +variable {K Λ σ : Type} [DecidableEq K] + +def guardConfiguration (counter : K) (guardLabel : Λ) (suffix : List Bool) + (ambient : Nat → σ) (register : Nat → Option Bool) + (base : Nat → K → List Bool) (n : Nat) : + TM2.Cfg (Alphabet (K := K)) Λ (σ × Option Bool) := + ⟨some guardLabel, (ambient n, register n), counterTapes counter (base n) n suffix⟩ + +def bodyConfiguration (counter : K) (bodyLabel : Λ) (suffix : List Bool) + (ambient : Nat → σ) (base : Nat → K → List Bool) (n : Nat) : + TM2.Cfg (Alphabet (K := K)) Λ (σ × Option Bool) := + ⟨some bodyLabel, (ambient (n + 1), none), counterTapes counter (base (n + 1)) n suffix⟩ + +def exitConfiguration (counter : K) (exitLabel : Λ) (suffix : List Bool) + (ambient : Nat → σ) (base : Nat → K → List Bool) : + TM2.Cfg (Alphabet (K := K)) Λ (σ × Option Bool) := + ⟨some exitLabel, (ambient 0, none), counterTapes counter (base 0) 0 suffix⟩ + +def BodyTraces (counter : K) (guardLabel bodyLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (suffix : List Bool) (ambient : Nat → σ) (register : Nat → Option Bool) + (base : Nat → K → List Bool) (cost : Nat → Nat) (n : Nat) : Prop := + ∀ r, r < n → + (MachineComposition.advance (TM2.step program))^[cost r] + (some (bodyConfiguration counter bodyLabel suffix ambient base r)) = + some (guardConfiguration counter guardLabel suffix ambient register base r) + +def totalSteps (cost : Nat → Nat) (n : Nat) : Nat := + (∑ r ∈ Finset.range n, cost r) + n + 1 + +@[simp] theorem totalSteps_zero (cost : Nat → Nat) : totalSteps cost 0 = 1 := by + simp [totalSteps] + +theorem totalSteps_succ (cost : Nat → Nat) (n : Nat) : + totalSteps cost (n + 1) = (totalSteps cost n + cost n) + 1 := by + simp only [totalSteps, Finset.sum_range_succ] + omega + +theorem loopTrace (counter : K) (guardLabel bodyLabel exitLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atGuard : program guardLabel = guard counter bodyLabel exitLabel) + (suffix : List Bool) (ambient : Nat → σ) (register : Nat → Option Bool) + (base : Nat → K → List Bool) (cost : Nat → Nat) (n : Nat) + (bodyTraces : BodyTraces counter guardLabel bodyLabel program suffix + ambient register base cost n) : + (MachineComposition.advance (TM2.step program))^[totalSteps cost n] + (some (guardConfiguration counter guardLabel suffix ambient register base n)) = + some (exitConfiguration counter exitLabel suffix ambient base) := by + revert bodyTraces + induction n with + | zero => + intro _ + simpa only [totalSteps_zero, guardConfiguration, exitConfiguration] using + guardTrace_zero counter guardLabel bodyLabel exitLabel program atGuard + (base 0) suffix (ambient 0) (register 0) + | succ n ih => + intro bodyTraces + rw [totalSteps_succ, Function.iterate_succ_apply] + change (MachineComposition.advance (TM2.step program))^[totalSteps cost n + cost n] + (TM2.step program + ⟨some guardLabel, (ambient (n + 1), register (n + 1)), + counterTapes counter (base (n + 1)) (n + 1) suffix⟩) = _ + rw [guardStep_succ counter guardLabel bodyLabel exitLabel program atGuard + (base (n + 1)) n suffix (ambient (n + 1)) (register (n + 1)), + Function.iterate_add_apply] + change (MachineComposition.advance (TM2.step program))^[totalSteps cost n] + ((MachineComposition.advance (TM2.step program))^[cost n] + (some (bodyConfiguration counter bodyLabel suffix ambient base n))) = _ + rw [bodyTraces n (Nat.lt_succ_self n)] + exact ih (fun r hr => bodyTraces r (Nat.lt_trans hr (Nat.lt_succ_self n))) + +theorem totalSteps_le (cost : Nat → Nat) (n B : Nat) + (bodyBound : ∀ r, r < n → cost r ≤ B) : + totalSteps cost n ≤ n * (B + 1) + 1 := by + have hsum : (∑ r ∈ Finset.range n, cost r) ≤ n * B := by + calc + (∑ r ∈ Finset.range n, cost r) ≤ ∑ _r ∈ Finset.range n, B := + Finset.sum_le_sum (fun r hr => bodyBound r (Finset.mem_range.mp hr)) + _ = n * B := by simp + simpa only [totalSteps, Nat.mul_add, Nat.mul_one] using + Nat.add_le_add_right (Nat.add_le_add_right hsum n) 1 + +def loopInTime (counter : K) (guardLabel bodyLabel exitLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atGuard : program guardLabel = guard counter bodyLabel exitLabel) + (suffix : List Bool) (ambient : Nat → σ) (register : Nat → Option Bool) + (base : Nat → K → List Bool) (cost : Nat → Nat) (n B : Nat) + (bodyTraces : BodyTraces counter guardLabel bodyLabel program suffix + ambient register base cost n) + (bodyBound : ∀ r, r < n → cost r ≤ B) : + StateTransition.EvalsToInTime (TM2.step program) + (guardConfiguration counter guardLabel suffix ambient register base n) + (some (exitConfiguration counter exitLabel suffix ambient base)) + (n * (B + 1) + 1) where + steps := totalSteps cost n + evals_in_steps := by + change (MachineComposition.advance (TM2.step program))^[totalSteps cost n] _ = _ + exact loopTrace counter guardLabel bodyLabel exitLabel program atGuard suffix + ambient register base cost n bodyTraces + steps_le_m := totalSteps_le cost n B bodyBound + +omit [DecidableEq K] in + +theorem baseFrame (base : Nat → K → List Bool) (frame : K → Prop) (n : Nat) + (bodyFrame : ∀ r, r < n → ∀ k, frame k → base (r + 1) k = base r k) : + ∀ k, frame k → base n k = base 0 k := by + revert bodyFrame + induction n with + | zero => intro _ k _; rfl + | succ n ih => + intro bodyFrame k hk + exact (bodyFrame n (Nat.lt_succ_self n) k hk).trans + (ih (fun r hr => bodyFrame r (Nat.lt_trans hr (Nat.lt_succ_self n))) k hk) + +theorem counterFrame (counter : K) (suffix : List Bool) + (base : Nat → K → List Bool) (frame : K → Prop) (n : Nat) + (counterOutside : ∀ k, frame k → k ≠ counter) + (bodyFrame : ∀ r, r < n → ∀ k, frame k → base (r + 1) k = base r k) : + ∀ k, frame k → + counterTapes counter (base n) n suffix k = counterTapes counter (base 0) 0 suffix k := by + intro k hk + rw [counterTapes_other counter k (counterOutside k hk), + counterTapes_other counter k (counterOutside k hk)] + exact baseFrame base frame n bodyFrame k hk + +theorem loopTrace_framed (counter : K) (guardLabel bodyLabel exitLabel : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atGuard : program guardLabel = guard counter bodyLabel exitLabel) + (suffix : List Bool) (ambient : Nat → σ) (register : Nat → Option Bool) + (base : Nat → K → List Bool) (cost : Nat → Nat) (n : Nat) + (bodyTraces : BodyTraces counter guardLabel bodyLabel program suffix + ambient register base cost n) + (frame : K → Prop) (counterOutside : ∀ k, frame k → k ≠ counter) + (bodyFrame : ∀ r, r < n → ∀ k, frame k → base (r + 1) k = base r k) : + ((MachineComposition.advance (TM2.step program))^[totalSteps cost n] + (some (guardConfiguration counter guardLabel suffix ambient register base n)) = + some (exitConfiguration counter exitLabel suffix ambient base)) ∧ + (∀ k, frame k → + (guardConfiguration counter guardLabel suffix ambient register base n).stk k = + (exitConfiguration counter exitLabel suffix ambient base).stk k) := + ⟨loopTrace counter guardLabel bodyLabel exitLabel program atGuard suffix + ambient register base cost n bodyTraces, + counterFrame counter suffix base frame n counterOutside bodyFrame⟩ + +end MinUncutGames.Foundations.Complexity.MachineCountedLoop + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/OuterAlphabets.lean b/lean/OAI/Computability/MinUncut/Machines/OuterAlphabets.lean new file mode 100644 index 0000000000000000000000000000000000000000..effba505988bd9910c92f6a0d52ac4f209e61793 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/OuterAlphabets.lean @@ -0,0 +1,107 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.F2 + +namespace OAI + +section +noncomputable section +open scoped BigOperators +namespace MinUncut.Outer +open MinUncut.Inner +abbrev Triple := Fin 3 → F₂ + +structure Equation (Name : Type*) where + names : Fin 3 → Name + rhs : F₂ + deriving DecidableEq + +variable {Name : Type*} + +def parity : Triple →ₗ[F₂] F₂ where + toFun a := a 0+a 1+a 2 + map_add' a b := by simp only [Pi.add_apply]; ring + map_smul' c a := by simp only [Pi.smul_apply,smul_eq_mul,RingHom.id_apply]; ring + +@[simp] lemma parity_apply (a : Triple) : parity a = a 0+a 1+a 2 := rfl + +def Valid (E : Equation Name) (a : Triple) : Prop := + parity a = E.rhs ∧ ∀ p p', E.names p=E.names p' → a p=a p' + +def alphabet (E : Equation Name) : AffineSubspace F₂ Triple where + carrier := {a | Valid E a} + smul_vsub_vadd_mem' c a b d ha hb hd := by + change parity (c • (a-b)+d)=E.rhs ∧ _ + constructor + · rw [map_add,map_smul,map_sub,ha.1,hb.1,hd.1,sub_self,smul_zero,zero_add] + · intro p p' he + change c*(a p-b p)+d p=c*(a p'-b p')+d p' + rw [ha.2 p p' he,hb.2 p p' he,hd.2 p p' he] + +@[simp] lemma mem_alphabet (E : Equation Name) (a : Triple) : + a ∈ alphabet E ↔ Valid E a := Iff.rfl + +def origin (E : Equation Name) : alphabet E := + ⟨fun _ => E.rhs, ⟨by simp only [parity_apply,CharTwo.add_self_eq_zero,zero_add], + fun _ _ _ => rfl⟩⟩ + +instance alphabetNonempty (E : Equation Name) : Nonempty (alphabet E) := ⟨origin E⟩ +instance alphabetFintype (E : Equation Name) : Fintype (alphabet E) := Fintype.ofFinite _ +instance directionFintype (E : Equation Name) : Fintype (alphabet E).direction := Fintype.ofFinite _ + +lemma direction_parity (E : Equation Name) (v : (alphabet E).direction) : + parity (v : Triple) = 0 := by + obtain ⟨a,ha,b,hb,he⟩ := + ((alphabet E).mem_direction_iff_eq_vsub ⟨origin E,(origin E).property⟩ v.val).mp v.property + rw [he] + change parity (a-b)=0 + rw [map_sub,ha.1,hb.1,sub_self] + +def firstTwo (E : Equation Name) : (alphabet E).direction →ₗ[F₂] (Fin 2 → F₂) := + LinearMap.pi (fun i => (LinearMap.proj i.castSucc).comp (alphabet E).direction.subtype) + +lemma firstTwo_injective (E : Equation Name) : Function.Injective (firstTwo E) := by + intro v w hvw + have h0 : v.val 0=w.val 0 := congrFun hvw 0 + have h1 : v.val 1=w.val 1 := congrFun hvw 1 + apply Subtype.ext + funext i + fin_cases i + · exact h0 + · exact h1 + · have hv := direction_parity E v + have hw := direction_parity E w + simp only [parity_apply,h0,h1] at hv hw + exact add_left_cancel (hv.trans hw.symm) + +lemma alphabet_dimension_le (E : Equation Name) : + Module.finrank F₂ (alphabet E).direction ≤ 2 := by + have h := (firstTwo E).finrank_le_finrank_of_injective (firstTwo_injective E) + simpa only [Module.finrank_fin_fun] using h + +def coordinates (E : Equation Name) : + (Fin (Module.finrank F₂ (alphabet E).direction) → F₂) ≃ₗ[F₂] (alphabet E).direction := + (Module.finBasis F₂ (alphabet E).direction).equivFun.symm + +def directionEmbedding (E : Equation Name) : + (Fin (Module.finrank F₂ (alphabet E).direction) → F₂) →ₗ[F₂] Triple := + (alphabet E).direction.subtype.comp (coordinates E).toLinearMap + +lemma directionEmbedding_injective (E : Equation Name) : + Function.Injective (directionEmbedding E) := + Subtype.val_injective.comp (coordinates E).injective + +def alphabetCoordinates (E : Equation Name) : + (Fin (Module.finrank F₂ (alphabet E).direction) → F₂) ≃ᵃ[F₂] alphabet E := + (coordinates E).toAffineEquiv.trans (AffineEquiv.vaddConst F₂ (origin E)) + +@[simp] lemma alphabetCoordinates_val (E : Equation Name) + (v : Fin (Module.finrank F₂ (alphabet E).direction) → F₂) : + ((alphabetCoordinates E v : alphabet E) : Triple) = + directionEmbedding E v + (origin E : Triple) := rfl + +end MinUncut.Outer + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/PCPIterationMachine.lean b/lean/OAI/Computability/MinUncut/Machines/PCPIterationMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..d7ccd2a73429c3eb41f97dfdb5525bf7ee448f6a --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/PCPIterationMachine.lean @@ -0,0 +1,192 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineUnaryCounter + +namespace OAI + +section +namespace MinUncutGames.Foundations.Complexity.PCPIterationMachine + +open Turing +open MachineCountedLoop + +def rounds (n : Nat) : Nat := n.log2 + 1 + +theorem rounds_le (n : Nat) : rounds n ≤ n + 1 := + Nat.add_le_add_right (Nat.log2_le_self n) 1 + +theorem two_pow_rounds_le (n : Nat) : 2 ^ rounds n ≤ 2 * (n + 1) := by + by_cases hn : n = 0 + · subst n; decide + · have h := Nat.log2_self_le hn + simp only [rounds, pow_succ] + omega + +theorem growth_pow_rounds_le (growth n : Nat) : + growth ^ rounds n ≤ (2 * (n + 1)) ^ growth := by + calc + growth ^ rounds n ≤ (2 ^ growth) ^ rounds n := + Nat.pow_le_pow_left (Nat.le_of_lt (Nat.lt_two_pow_self (n := growth))) _ + _ = (2 ^ rounds n) ^ growth := by simp only [← pow_mul, Nat.mul_comm] + _ ≤ (2 * (n + 1)) ^ growth := Nat.pow_le_pow_left (two_pow_rounds_le n) growth + +def sizeEnvelope (growth n : Nat) : Nat := (n + 1) * (2 * (n + 1)) ^ growth + +theorem semanticSize_geometric (sizes : Nat → Nat) (growth n : Nat) + (initialBound : sizes 0 ≤ n + 1) + (growthBound : ∀ i, i < rounds n → sizes (i + 1) ≤ growth * sizes i) + (i : Nat) (hi : i ≤ rounds n) : sizes i ≤ (n + 1) * growth ^ i := by + induction i with + | zero => simpa only [pow_zero, Nat.mul_one] using initialBound + | succ i ih => + have ilt : i < rounds n := by omega + calc + sizes (i + 1) ≤ growth * sizes i := growthBound i ilt + _ ≤ growth * ((n + 1) * growth ^ i) := + Nat.mul_le_mul_left growth (ih (by omega)) + _ = (n + 1) * growth ^ (i + 1) := by rw [pow_succ]; ac_rfl + +theorem semanticSize_bound (sizes : Nat → Nat) (growth n : Nat) + (growthPositive : 0 < growth) + (initialBound : sizes 0 ≤ n + 1) + (growthBound : ∀ i, i < rounds n → sizes (i + 1) ≤ growth * sizes i) + (i : Nat) (hi : i ≤ rounds n) : sizes i ≤ sizeEnvelope growth n := by + calc + sizes i ≤ (n + 1) * growth ^ i := + semanticSize_geometric sizes growth n initialBound growthBound i hi + _ ≤ (n + 1) * growth ^ rounds n := + Nat.mul_le_mul_left _ (Nat.pow_le_pow_right growthPositive hi) + _ ≤ sizeEnvelope growth n := + Nat.mul_le_mul_left _ (growth_pow_rounds_le growth n) + +noncomputable def sizePolynomial (growth : Nat) : Polynomial Nat := + (Polynomial.X + 1) * (2 * (Polynomial.X + 1)) ^ growth + +@[simp] theorem sizePolynomial_eval (growth n : Nat) : + (sizePolynomial growth).eval n = sizeEnvelope growth n := by + simp [sizePolynomial, sizeEnvelope] + +noncomputable def timePolynomial (growth : Nat) + (encodingSize bodyTime : Polynomial Nat) : Polynomial Nat := + (Polynomial.X + 1) * + ((bodyTime.comp encodingSize).comp (sizePolynomial growth) + 1) + 2 + +@[simp] theorem timePolynomial_eval (growth n : Nat) + (encodingSize bodyTime : Polynomial Nat) : + (timePolynomial growth encodingSize bodyTime).eval n = + (n + 1) * (bodyTime.eval (encodingSize.eval (sizeEnvelope growth n)) + 1) + 2 := by + simp [timePolynomial] + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool +abbrev State (σ : Type) := σ × Option Bool +abbrev Labels (Λ : Type) := Bool ⊕ Λ + +def program (counter : K) (entry : Λ) + (body : Λ → TM2.Stmt (Alphabet (K := K)) (Labels Λ) (State σ)) : + Labels Λ → TM2.Stmt (Alphabet (K := K)) (Labels Λ) (State σ) + | .inl false => MachineUnaryCounter.guard counter (.inr entry) (.inl true) + | .inl true => .pop counter (fun state _ => (state.1, none)) .halt + | .inr label => body label + +omit [DecidableEq K] in +@[simp] theorem program_guard (counter : K) (entry : Λ) + (body : Λ → TM2.Stmt (Alphabet (K := K)) (Labels Λ) (State σ)) : + program counter entry body (.inl false) = + MachineUnaryCounter.guard counter (.inr entry) (.inl true) := rfl + +def machine [Fintype K] [Fintype Λ] [Fintype σ] + (counter output : K) (entry : Λ) (initial : σ) + (body : Λ → TM2.Stmt (Alphabet (K := K)) (Labels Λ) (State σ)) : FinTM2 where + K := K + k₀ := counter + k₁ := output + Γ := Alphabet + Λ := Labels Λ + main := .inl false + σ := State σ + initialState := (initial, none) + m := program counter entry body + +def haltedConfiguration (counter : K) (suffix : List Bool) + (ambient : Nat → σ) (base : Nat → K → List Bool) : + TM2.Cfg (Alphabet (K := K)) (Labels Λ) (State σ) := + ⟨none, (ambient 0, none), Function.update (base 0) counter suffix⟩ + +theorem haltStep (counter : K) (entry : Λ) + (body : Λ → TM2.Stmt (Alphabet (K := K)) (Labels Λ) (State σ)) + (suffix : List Bool) (ambient : Nat → σ) (base : Nat → K → List Bool) : + TM2.step (program counter entry body) + (exitConfiguration counter (.inl true) suffix ambient base) = + some (haltedConfiguration counter suffix ambient base) := by + change some (TM2.stepAux (.pop counter (fun state _ => (state.1, none)) .halt) + (ambient 0, none) (MachineUnaryCounter.counterTapes counter (base 0) 0 suffix)) = _ + simp [TM2.stepAux, MachineUnaryCounter.counterTapes, encodeWord, haltedConfiguration] + +theorem iterationTrace (counter : K) (entry : Λ) + (body : Λ → TM2.Stmt (Alphabet (K := K)) (Labels Λ) (State σ)) + (suffix : List Bool) (ambient : Nat → σ) (register : Nat → Option Bool) + (base : Nat → K → List Bool) (cost : Nat → Nat) (n : Nat) + (bodyTraces : BodyTraces counter (.inl false) (.inr entry) + (program counter entry body) suffix ambient register base cost (rounds n)) : + (MachineComposition.advance (TM2.step (program counter entry body)))^[ + totalSteps cost (rounds n) + 1] + (some (guardConfiguration counter (.inl false) suffix ambient register base (rounds n))) = + some (haltedConfiguration counter suffix ambient base) := by + rw [Function.iterate_succ_apply'] + rw [loopTrace counter (.inl false) (.inr entry) (.inl true) + (program counter entry body) (program_guard counter entry body) suffix + ambient register base cost (rounds n) bodyTraces] + exact haltStep counter entry body suffix ambient base + +theorem bodyCosts_bound (growth n : Nat) (growthPositive : 0 < growth) + (sizes encodedSizes cost : Nat → Nat) (encodingSize bodyTime : Polynomial Nat) + (initialBound : sizes 0 ≤ n + 1) + (growthBound : ∀ i, i < rounds n → sizes (i + 1) ≤ growth * sizes i) + (encodingBound : ∀ r, r < rounds n → + encodedSizes r ≤ encodingSize.eval (sizes (rounds n - (r + 1)))) + (bodyCost : ∀ r, r < rounds n → cost r ≤ bodyTime.eval (encodedSizes r)) : + ∀ r, r < rounds n → + cost r ≤ bodyTime.eval (encodingSize.eval (sizeEnvelope growth n)) := by + intro r hr + have hs := semanticSize_bound sizes growth n growthPositive initialBound growthBound + (rounds n - (r + 1)) (Nat.sub_le _ _) + exact (bodyCost r hr).trans + (MachineComposition.natPolynomial_eval_mono bodyTime + ((encodingBound r hr).trans + (MachineComposition.natPolynomial_eval_mono encodingSize hs))) + +def iterationInTime (counter : K) (entry : Λ) + (body : Λ → TM2.Stmt (Alphabet (K := K)) (Labels Λ) (State σ)) + (suffix : List Bool) (ambient : Nat → σ) (register : Nat → Option Bool) + (base : Nat → K → List Bool) (cost : Nat → Nat) (growth n : Nat) + (growthPositive : 0 < growth) + (bodyTraces : BodyTraces counter (.inl false) (.inr entry) + (program counter entry body) suffix ambient register base cost (rounds n)) + (sizes encodedSizes : Nat → Nat) (encodingSize bodyTime : Polynomial Nat) + (initialBound : sizes 0 ≤ n + 1) + (growthBound : ∀ i, i < rounds n → sizes (i + 1) ≤ growth * sizes i) + (encodingBound : ∀ r, r < rounds n → + encodedSizes r ≤ encodingSize.eval (sizes (rounds n - (r + 1)))) + (bodyCost : ∀ r, r < rounds n → cost r ≤ bodyTime.eval (encodedSizes r)) : + StateTransition.EvalsToInTime (TM2.step (program counter entry body)) + (guardConfiguration counter (.inl false) suffix ambient register base (rounds n)) + (some (haltedConfiguration counter suffix ambient base)) + ((timePolynomial growth encodingSize bodyTime).eval n) where + steps := totalSteps cost (rounds n) + 1 + evals_in_steps := iterationTrace counter entry body suffix ambient register base cost n bodyTraces + steps_le_m := by + rw [timePolynomial_eval] + have h := totalSteps_le cost (rounds n) + (bodyTime.eval (encodingSize.eval (sizeEnvelope growth n))) + (bodyCosts_bound growth n growthPositive sizes encodedSizes cost encodingSize bodyTime + initialBound growthBound encodingBound bodyCost) + have hm := Nat.mul_le_mul_right + (bodyTime.eval (encodingSize.eval (sizeEnvelope growth n)) + 1) (rounds_le n) + omega + +end MinUncutGames.Foundations.Complexity.PCPIterationMachine + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/PoweringMachineField.lean b/lean/OAI/Computability/MinUncut/Machines/PoweringMachineField.lean new file mode 100644 index 0000000000000000000000000000000000000000..5dedfd7c2b90669e9d51d2fa7e0d80dd9ee84786 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/PoweringMachineField.lean @@ -0,0 +1,276 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.PoweringMachineRelation +import OAI.Computability.MinUncut.PCP.PoweringRowData + +namespace OAI + +namespace MinUncutGames.Foundations.Complexity.PoweringMachineField + +open Turing MachineComposition PCP PoweringFieldPlan + +variable {K Λ A : Type} [DecidableEq K] {n d max : Nat} + +abbrev Tape := PoweringMachineTapes.Tape +abbrev State := MachineUnaryEqualityBit.State + +def Label : Instruction d → Type + | .relation path _ _ _ => PoweringMachineRelationField.Label path + | .equal left right => PoweringMachineEqualityField.Label left.length right.length + +instance labelFintype (op : Instruction d) : Fintype (Label op) := by + cases op <;> dsimp only [Label] <;> infer_instance + +instance labelDecidableEq (op : Instruction d) : DecidableEq (Label op) := by + cases op <;> dsimp only [Label] <;> infer_instance + +def entry : (op : Instruction d) → Label op + | .relation path _ _ _ => .inl (PoweringMachineWord.entry path.length) + | .equal left right => PoweringMachineEqualityField.entry left.length right.length + +def instruction (placement : Tape max → K) : (op : Instruction d) → op.radius ≤ max → + (Label op → Λ) → Option Λ → Label op → TM2.Stmt (fun _ : K => Bool) Λ (State A) + | .relation path port a b, bounded, labels, exit => + PoweringMachineRelationField.instruction placement path bounded port a b labels exit + | .equal left right, bounded, labels, exit => + PoweringMachineEqualityField.instruction + ((le_max_left _ _).trans bounded) ((le_max_right _ _).trans bounded) + placement left.get right.get labels exit + +def finalTapes (graph : PortTables.Table n d) (placement : Tape max → K) + (vertex : Fin n) : (op : Instruction d) → op.radius ≤ max → + (K → List Bool) → K → List Bool + | .relation path port a b, bounded, base => + PoweringMachineRelationField.finalTapes placement path bounded port a b graph vertex base + | .equal left right, bounded, base => + PoweringMachineEqualityField.finalTapes graph + ((le_max_left _ _).trans bounded) ((le_max_right _ _).trans bounded) + placement vertex left.get right.get base + +def steps (graph : PortTables.Table n d) (vertex : Fin n) : Instruction d → Nat + | .relation path port a b => PoweringMachineRelationField.steps path port a b graph vertex + | .equal left right => PoweringMachineEqualityField.steps graph vertex left.get right.get + +structure Ready (graph : PortTables.Table n d) (placement : Tape max → K) + (vertex : Fin n) (suffix : List Bool) (tapes : K → List Bool) : Prop where + table : tapes (placement (.inl 0)) = PortTables.tableBits graph + source : tapes (placement (.inl 1)) = encodeWord vertex.val ++ suffix + scratch : tapes (placement (.inl 5)) = [] + leftCopy : tapes (placement (.inl 8)) = [] + rightCopy : tapes (placement (.inl 9)) = [] + +theorem finalTapes_role (graph : PortTables.Table n d) (placement : Tape max → K) + (distinct : Function.Injective placement) (vertex : Fin n) + (op : Instruction d) (bounded : op.radius ≤ max) (base : K → List Bool) + (j : Fin 11) (role : j = 0 ∨ j = 1 ∨ j = 5 ∨ j = 8 ∨ j = 9) : + finalTapes graph placement vertex op bounded base (placement (.inl j)) = + base (placement (.inl j)) := by + cases op with + | relation path port a b => + apply PoweringMachineRelationField.finalTapes_frame placement distinct path bounded + port a b graph vertex base j + all_goals rcases role with rfl | rfl | rfl | rfl | rfl <;> decide + | equal left right => + exact PoweringMachineEqualityField.finalTapes_role graph _ _ placement distinct + vertex left.get right.get base j role + +theorem ready_finalTapes (graph : PortTables.Table n d) (placement : Tape max → K) + (distinct : Function.Injective placement) (vertex : Fin n) + (op : Instruction d) (bounded : op.radius ≤ max) (base : K → List Bool) + (suffix : List Bool) (ready : Ready graph placement vertex suffix base) : + Ready graph placement vertex suffix (finalTapes graph placement vertex op bounded base) := by + constructor + · rw [finalTapes_role graph placement distinct vertex op bounded base 0 (by simp)] + exact ready.table + · rw [finalTapes_role graph placement distinct vertex op bounded base 1 (by simp)] + exact ready.source + · rw [finalTapes_role graph placement distinct vertex op bounded base 5 (by simp)] + exact ready.scratch + · rw [finalTapes_role graph placement distinct vertex op bounded base 8 (by simp)] + exact ready.leftCopy + · rw [finalTapes_role graph placement distinct vertex op bounded base 9 (by simp)] + exact ready.rightCopy + +theorem finalTapes_other (graph : PortTables.Table n d) (placement : Tape max → K) + (vertex : Fin n) (op : Instruction d) (bounded : op.radius ≤ max) + (base : K → List Bool) (k : K) (outside : ∀ i, k ≠ placement i) : + finalTapes graph placement vertex op bounded base k = base k := by + cases op with + | relation path port a b => + exact PoweringMachineRelationField.finalTapes_other placement path bounded port a b + graph vertex base k outside + | equal left right => + exact PoweringMachineEqualityField.finalTapes_other graph _ _ placement vertex + left.get right.get base k (outside _) (outside _) (outside _) (outside _) + (outside _) (outside _) (fun i => outside _) + +theorem fieldTrace (graph : PortTables.Table n d) (placement : Tape max → K) + (distinct : Function.Injective placement) (vertex : Fin n) + (op : Instruction d) (bounded : op.radius ≤ max) + (labels : Label op → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State A)) + (atLabels : ∀ l, program (labels l) = instruction placement op bounded labels exit l) + (base : K → List Bool) (suffix : List Bool) + (ready : Ready graph placement vertex suffix base) (ambient : A) : + (advance (TM2.step program))^[steps graph vertex op] + (some ⟨some (labels (entry op)), MachineUnaryEqualityBit.clean ambient, base⟩) = + some ⟨exit, MachineUnaryEqualityBit.clean ambient, + finalTapes graph placement vertex op bounded base⟩ := by + cases op with + | relation path port a b => + exact (PoweringMachineRelationField.fieldTrace placement distinct path bounded port a b + labels exit program atLabels graph vertex base ready.table ready.scratch suffix + ready.source ambient).1 + | equal left right => + exact PoweringMachineEqualityField.fieldTrace graph _ _ placement distinct + vertex left.get right.get labels exit program atLabels base ready.table ready.scratch + ready.leftCopy ready.rightCopy suffix ready.source ambient + +theorem finalTapes_output (graph : PortTables.Table n d) (placement : Tape max → K) + (distinct : Function.Injective placement) (vertex : Fin n) + (op : Instruction d) (bounded : op.radius ≤ max) (base : K → List Bool) + (suffix : List Bool) (ready : Ready graph placement vertex suffix base) : + finalTapes graph placement vertex op bounded base (placement (.inl 10)) = + PoweringMachineRow.encodeBit (evaluate graph vertex op) ++ base (placement (.inl 10)) := by + cases op with + | relation path port a b => + have h := (PoweringMachineRelationField.fieldTrace placement distinct path bounded port a b + id none (PoweringMachineRelationField.instruction placement path bounded port a b id none) + (fun _ => rfl) graph vertex base ready.table ready.scratch suffix ready.source ()).2 + have he : ∀ bit : Bool, encodeWord (GraphTables.bitWord bit) = + PoweringMachineRow.encodeBit bit := by intro bit; cases bit <;> rfl + simpa only [finalTapes, PoweringMachineRelationField.bit, PoweringMachineRelationField.endpoint, + evaluate, he] using h + | equal left right => + have h := PoweringMachineEqualityField.finalTapes_output graph + ((le_max_left _ _).trans bounded) ((le_max_right _ _).trans bounded) placement distinct + vertex left.get right.get base + have he : ∀ bit : Bool, MachineUnaryEqualityBit.bitEncoding bit = + PoweringMachineRow.encodeBit bit := by intro bit; cases bit <;> rfl + simpa only [finalTapes, PoweringMachineEqualityField.resultBit, PoweringMachineEqualityField.endpoint, + PoweringReach.wordEnd_eq_walkEnd_ofFn, List.ofFn_get, evaluate, he] using h + +end MinUncutGames.Foundations.Complexity.PoweringMachineField + +namespace MinUncutGames.Foundations.Complexity.PoweringMachinePlan + +open Turing MachineComposition PCP PoweringFieldPlan + +variable {K Λ A : Type} [DecidableEq K] {vertices d max : Nat} + +abbrev Command (d max : Nat) := {op : Instruction d // op.radius ≤ max} +abbrev LocalLabel (op : Command d max) := PoweringMachineField.Label op.val +abbrev Label (commands : List (Command d max)) := MachineFiniteSequence.Label LocalLabel commands + +def entry (commands : List (Command d max)) (labels : Label commands → Λ) (exit : Option Λ) : Option Λ := + MachineFiniteSequence.entry LocalLabel (fun op => PoweringMachineField.entry op.val) + commands labels exit + +def instruction (placement : PoweringMachineTapes.Tape max → K) + (commands : List (Command d max)) (labels : Label commands → Λ) (exit : Option Λ) : + Label commands → TM2.Stmt (fun _ : K => Bool) Λ (MachineUnaryEqualityBit.State A) := + MachineFiniteSequence.instruction LocalLabel (fun op => PoweringMachineField.entry op.val) + (fun op => PoweringMachineField.instruction placement op.val op.property) + commands labels exit + +def result (graph : PortTables.Table vertices d) (placement : PoweringMachineTapes.Tape max → K) + (vertex : Fin vertices) (op : Command d max) (base : K → List Bool) : K → List Bool := + PoweringMachineField.finalTapes graph placement vertex op.val op.property base + +def finalTapes (graph : PortTables.Table vertices d) (placement : PoweringMachineTapes.Tape max → K) + (vertex : Fin vertices) (commands : List (Command d max)) (base : K → List Bool) : K → List Bool := + MachineFiniteSequence.resultOf (result graph placement vertex) commands base + +def steps (graph : PortTables.Table vertices d) (placement : PoweringMachineTapes.Tape max → K) + (vertex : Fin vertices) (commands : List (Command d max)) (base : K → List Bool) : Nat := + MachineFiniteSequence.steps (result graph placement vertex) + (fun op _ => PoweringMachineField.steps graph vertex op.val) commands base + +theorem planTrace (graph : PortTables.Table vertices d) + (placement : PoweringMachineTapes.Tape max → K) (distinct : Function.Injective placement) + (vertex : Fin vertices) (commands : List (Command d max)) + (labels : Label commands → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (MachineUnaryEqualityBit.State A)) + (atLabels : ∀ l, program (labels l) = instruction placement commands labels exit l) + (base : K → List Bool) (suffix : List Bool) + (ready : PoweringMachineField.Ready graph placement vertex suffix base) (ambient : A) : + (advance (TM2.step program))^[steps graph placement vertex commands base] + (some ⟨entry commands labels exit, MachineUnaryEqualityBit.clean ambient, base⟩) = + some ⟨exit, MachineUnaryEqualityBit.clean ambient, + finalTapes graph placement vertex commands base⟩ := by + apply MachineFiniteSequence.trace LocalLabel (fun op => PoweringMachineField.entry op.val) + (fun op => PoweringMachineField.instruction placement op.val op.property) + (result graph placement vertex) (fun op _ => PoweringMachineField.steps graph vertex op.val) + program (PoweringMachineField.Ready graph placement vertex suffix) + (fun _ => MachineUnaryEqualityBit.clean ambient) id commands + · intro op _ tapes good + exact PoweringMachineField.ready_finalTapes graph placement distinct vertex op.val + op.property tapes suffix good + · intro op _ localLabels localExit atLocal tapes good + exact PoweringMachineField.fieldTrace graph placement distinct vertex op.val op.property + localLabels localExit program atLocal tapes suffix good ambient + · exact atLabels + · exact ready + +theorem ready_finalTapes (graph : PortTables.Table vertices d) + (placement : PoweringMachineTapes.Tape max → K) (distinct : Function.Injective placement) + (vertex : Fin vertices) (commands : List (Command d max)) (base : K → List Bool) + (suffix : List Bool) (ready : PoweringMachineField.Ready graph placement vertex suffix base) : + PoweringMachineField.Ready graph placement vertex suffix + (finalTapes graph placement vertex commands base) := by + induction commands generalizing base with + | nil => exact ready + | cons op commands ih => + apply ih + exact PoweringMachineField.ready_finalTapes graph placement distinct vertex op.val + op.property base suffix ready + +theorem finalTapes_output (graph : PortTables.Table vertices d) + (placement : PoweringMachineTapes.Tape max → K) (distinct : Function.Injective placement) + (vertex : Fin vertices) (commands : List (Command d max)) (base : K → List Bool) + (suffix : List Bool) (ready : PoweringMachineField.Ready graph placement vertex suffix base) : + finalTapes graph placement vertex commands base (placement (.inl 10)) = + PoweringMachineRow.encodeBits ((commands.map (fun op => evaluate graph vertex op.val)).reverse) ++ + base (placement (.inl 10)) := by + induction commands generalizing base with + | nil => rfl + | cons op commands ih => + have nextReady := PoweringMachineField.ready_finalTapes graph placement distinct vertex + op.val op.property base suffix ready + change finalTapes graph placement vertex commands + (result graph placement vertex op base) (placement (.inl 10)) = _ + dsimp only [result] + rw [ih _ nextReady, PoweringMachineField.finalTapes_output graph placement distinct vertex + op.val op.property base suffix ready] + simp only [List.map_cons, List.reverse_cons, PoweringMachineRow.encodeBits_append, + PoweringMachineRow.encodeBits, List.append_nil, + List.append_assoc] + +def boundedRowPlan (n : Nat) (ports : Fin (n + 1) → Fin d) (direction : Bool) : + List (Command d (2 * (n + 1))) := + List.ofFn fun i : Fin (PoweringMachineRow.inputSize (n + 1) (PoweringRowData.slotCount d n)) => + let pair := (PoweringMachineRow.inputEquiv (n + 1) (PoweringRowData.slotCount d n)).symm i + ⟨directedFieldPlan n ports direction pair.1 pair.2, + directedFieldPlan_radius n ports direction pair.1 pair.2⟩ + +theorem boundedRowPlan_values (n : Nat) (ports : Fin (n + 1) → Fin d) (direction : Bool) : + (boundedRowPlan n ports direction).map Subtype.val = rowPlan n ports direction := by + rw [boundedRowPlan, rowPlan, List.map_ofFn] + rfl + +theorem rowPlan_output (graph : PortTables.Table vertices d) + (n : Nat) (ports : Fin (n + 1) → Fin d) (direction : Bool) + (placement : PoweringMachineTapes.Tape (2 * (n + 1)) → K) + (distinct : Function.Injective placement) (vertex : Fin vertices) (base : K → List Bool) + (suffix : List Bool) (ready : PoweringMachineField.Ready graph placement vertex suffix base) : + finalTapes graph placement vertex (boundedRowPlan n ports direction).reverse base + (placement (.inl 10)) = + PoweringRowData.dataTape graph n (direction, vertex, ports) ++ base (placement (.inl 10)) := by + rw [finalTapes_output graph placement distinct vertex _ base suffix ready] + rw [List.map_reverse, List.reverse_reverse, PoweringFieldPlan.dataTape_eq_plan] + have h := congrArg (List.map (evaluate graph vertex)) (boundedRowPlan_values n ports direction) + simpa only [List.map_map, Function.comp_def] using + congrArg (fun bits => PoweringMachineRow.encodeBits bits ++ base (placement (.inl 10))) h + +end MinUncutGames.Foundations.Complexity.PoweringMachinePlan + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/PoweringMachineGlobal.lean b/lean/OAI/Computability/MinUncut/Machines/PoweringMachineGlobal.lean new file mode 100644 index 0000000000000000000000000000000000000000..07025ac51fe4d170b16618488c7d785e83f2b1e4 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/PoweringMachineGlobal.lean @@ -0,0 +1,125 @@ +import Mathlib +import OAI.Computability.MinUncut.Games.PoweringGlobalEnumeration +import OAI.Computability.MinUncut.Machines.PoweringMachineVertex + +namespace OAI + +section +namespace MinUncutGames.Foundations.Complexity.PoweringMachineGlobal + +open Turing + +abbrev Tape (n : Nat) := + PoweringMachineInitialize.GlobalTape (PoweringMachineRowBody.capacity n) + +abbrev State (d n : Nat) := + PoweringMasterState.Master (PoweringMachineRowBody.bufferSize d n) + +def placement (n : Nat) : + PoweringMachineTapes.Tape (PoweringMachineRowBody.capacity n) → Tape n := + PoweringMachineInitialize.commonPlacement (PoweringMachineRowBody.capacity n) + +def inputTape (n : Nat) : Tape n := + placement n (PoweringMachineTapes.table (PoweringMachineRowBody.capacity n)) + +def outputTape (n : Nat) : Tape n := + PoweringMachineInitialize.finalOutput (PoweringMachineRowBody.capacity n) + +def headerVertices (n : Nat) : Tape n := .inl PoweringMachineLoop.HeaderTape.vertices +def headerDarts (n : Nat) : Tape n := .inl PoweringMachineLoop.HeaderTape.darts + +def enumeration (n : Nat) : + Fin (4 + (11 + PoweringMachineRowBody.capacity n + 1)) ≃ Tape n := + PoweringGlobalEnumeration.enumeration (PoweringMachineRowBody.capacity n) + +abbrev FinishLabel (n : Nat) := PoweringMachineFinish.Label (enumeration n) (outputTape n) + +abbrev Label (d n : Nat) := PoweringMachineInitialize.Label ⊕ + (Bool ⊕ (PoweringMachineVertex.Label d n ⊕ FinishLabel n)) + +instance labelFintype (d n : Nat) : Fintype (Label d n) := + inferInstanceAs (Fintype (PoweringMachineInitialize.Label ⊕ + (Bool ⊕ (PoweringMachineVertex.Label d n ⊕ FinishLabel n)))) + +def initLabels (d n : Nat) : PoweringMachineInitialize.Label → Label d n := Sum.inl +def guardLabel (d n : Nat) : Label d n := .inr (.inl false) +def bridgeLabel (d n : Nat) : Label d n := .inr (.inl true) + +def vertexLabels (d n : Nat) (label : PoweringMachineVertex.Label d n) : Label d n := + .inr (.inr (.inl label)) + +def finishLabels (d n : Nat) (label : FinishLabel n) : Label d n := + .inr (.inr (.inr label)) + +def finishEntry (d n : Nat) : Label d n := finishLabels d n (.inl .seed) + +def main (d n : Nat) : Label d n := initLabels d n (.inr .seed) + +def program (d n : Nat) : + Label d n → TM2.Stmt (fun _ : Tape n => Bool) (Label d n) (State d n) + | .inl label => PoweringMachineInitialize.instruction + (PoweringMachineRowBody.capacity n) (PoweringMachineRowBody.bufferSize d n) + (PCP.PoweringTableLayout.blockSize d n) (initLabels d n) (some (guardLabel d n)) label + | .inr (.inl false) => MachineUnaryCounter.guard + (placement n (PoweringMachineTapes.start (PoweringMachineRowBody.capacity n))) + (bridgeLabel d n) (finishEntry d n) + | .inr (.inl true) => PoweringMachineOuterLoop.bridge d n (vertexLabels d n) (guardLabel d n) + | .inr (.inr (.inl label)) => PoweringMachineVertex.instruction n (placement n) (outputTape n) + (vertexLabels d n) (some (guardLabel d n)) label + | .inr (.inr (.inr label)) => PoweringMachineFinish.instruction (enumeration n) + (headerVertices n) (headerDarts n) (outputTape n) + (placement n (PoweringMachineTapes.scratch (PoweringMachineRowBody.capacity n))) + (finishLabels d n) label + +@[simp] theorem atInit (d n : Nat) (label : PoweringMachineInitialize.Label) : + program d n (initLabels d n label) = PoweringMachineInitialize.instruction + (PoweringMachineRowBody.capacity n) (PoweringMachineRowBody.bufferSize d n) + (PCP.PoweringTableLayout.blockSize d n) (initLabels d n) (some (guardLabel d n)) label := rfl + +@[simp] theorem atGuard (d n : Nat) : + program d n (guardLabel d n) = MachineUnaryCounter.guard + (placement n (PoweringMachineTapes.start (PoweringMachineRowBody.capacity n))) + (bridgeLabel d n) (finishEntry d n) := rfl + +@[simp] theorem atBridge (d n : Nat) : + program d n (bridgeLabel d n) = + PoweringMachineOuterLoop.bridge d n (vertexLabels d n) (guardLabel d n) := rfl + +@[simp] theorem atVertex (d n : Nat) (label : PoweringMachineVertex.Label d n) : + program d n (vertexLabels d n label) = PoweringMachineVertex.instruction n + (placement n) (outputTape n) (vertexLabels d n) (some (guardLabel d n)) label := rfl + +@[simp] theorem atFinish (d n : Nat) (label : FinishLabel n) : + program d n (finishLabels d n label) = PoweringMachineFinish.instruction (enumeration n) + (headerVertices n) (headerDarts n) (outputTape n) + (placement n (PoweringMachineTapes.scratch (PoweringMachineRowBody.capacity n))) + (finishLabels d n) label := rfl + +def machine (d n : Nat) : FinTM2 where + K := Tape n + k₀ := inputTape n + k₁ := outputTape n + Γ _ := Bool + Λ := Label d n + main := main d n + σ := State d n + initialState := PoweringMasterState.clean (PoweringMachineRowBody.bufferSize d n) + m := program d n + +@[simp] theorem machine_code (d n : Nat) (label : Label d n) : + (machine d n).m label = program d n label := rfl + +@[simp] theorem machine_main (d n : Nat) : (machine d n).main = main d n := rfl + +@[simp] theorem machine_initialState (d n : Nat) : + (machine d n).initialState = PoweringMasterState.clean (PoweringMachineRowBody.bufferSize d n) := rfl + +theorem input_ne_output (n : Nat) : inputTape n ≠ outputTape n := + PoweringMachineInitialize.commonPlacement_ne_finalOutput (PoweringMachineRowBody.capacity n) + (PoweringMachineTapes.table (PoweringMachineRowBody.capacity n)) + +end MinUncutGames.Foundations.Complexity.PoweringMachineGlobal + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/PoweringMachineRelation.lean b/lean/OAI/Computability/MinUncut/Machines/PoweringMachineRelation.lean new file mode 100644 index 0000000000000000000000000000000000000000..edc2229f9d2fd1892f0f2e42b0f4b23075985473 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/PoweringMachineRelation.lean @@ -0,0 +1,575 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.PoweringMachineRotor + +namespace OAI + +namespace MinUncutGames.Foundations.Complexity.PoweringMachineRelation + +open Turing +open MachineComposition +open PCP + +variable {K Λ σ : Type} [DecidableEq K] +variable {n d : Nat} + +abbrev Alphabet (_ : K) := Bool + +def address (vertex : Fin n) (port : Fin d) (position : Fin 4096) : Nat := + (4098 * d) * vertex.val + (4098 * port.val + 4 + position.val) + +def value (table : PortTables.Table n d) (vertex : Fin n) (port : Fin d) + (position : Fin 4096) : Nat := + GraphTables.bitWord table.relations[PortTables.rowIndex n d (vertex, port)][position] + +theorem selected (table : PortTables.Table n d) (vertex : Fin n) (port : Fin d) + (position : Fin 4096) : + (PortTables.tableWords table)[address vertex port position]? = + some (value table vertex port position) := by + have h := PortTableLookup.relation_word table (PortTables.rowIndex n d (vertex, port)) position + have hindex : address vertex port position = + 4 + 4098 * (PortTables.rowIndex n d (vertex, port)).val + position.val := by + simp only [address, PortTables.rowIndex_val, Nat.mul_add, Nat.mul_assoc] + omega + rw [hindex] + exact h + +def instruction (source : K) (tape : Fin 5 → K) (port : Fin d) (position : Fin 4096) + (labels : MachineAffineLookup.Label → Λ) (exit : Option Λ) : + MachineAffineLookup.Label → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) := + MachineAffineLookup.instruction source tape (4098 * d) + (4098 * port.val + 4 + position.val) labels exit + +theorem relationTrace (source : K) (tape : Fin 5 → K) + (distinct : Function.Injective tape) (outside : ∀ i, source ≠ tape i) + (port : Fin d) (position : Fin 4096) + (labels : MachineAffineLookup.Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atLabels : ∀ l, program (labels l) = instruction source tape port position labels exit l) + (table : PortTables.Table n d) (vertex : Fin n) (base : K → List Bool) + (tableWord : base (tape 0) = PortTables.tableBits table) (scratchEmpty : base (tape 4) = []) + (suffix : List Bool) (sourceWord : base source = encodeWord vertex.val ++ suffix) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[MachineAffineLookup.steps (PortTables.tableWords table) + vertex.val (4098 * d) (4098 * port.val + 4 + position.val)] + (some ⟨some (labels .seed), (ambient,register), base⟩) = + some ⟨exit, (ambient,none), MachineAffineLookup.finalTapes tape base + (PortTables.tableWords table) (address vertex port position) (value table vertex port position)⟩ := + MachineAffineLookup.affineLookupTrace source tape distinct outside + (4098 * d) (4098 * port.val + 4 + position.val) labels exit program atLabels + base (PortTables.tableWords table) tableWord scratchEmpty vertex.val suffix sourceWord + (value table vertex port position) (selected table vertex port position) ambient register + +theorem steps_le (table : PortTables.Table n d) (vertex : Fin n) (port : Fin d) + (position : Fin 4096) : + MachineAffineLookup.steps (PortTables.tableWords table) vertex.val + (4098 * d) (4098 * port.val + 4 + position.val) ≤ + 7 * (PortTables.tableBits table).length + 6 := + MachineAffineLookup.steps_le_table (PortTables.tableWords table) vertex.val + (4098 * d) (4098 * port.val + 4 + position.val) (value table vertex port position) + (selected table vertex port position) + (Nat.le_trans (Nat.le_of_lt vertex.isLt) (PortTables.vertices_le_tableBits_length table)) + +theorem value_eq_accepts (table : PortTables.Table n d) (vertex : Fin n) (port : Fin d) + (left right : PortTables.Label) : + value table vertex port (GraphTables.relationIndex (left, right)) = + GraphTables.bitWord (PortTables.accepts table (vertex, port) left right) := rfl + +def machine (degree : Nat) (port : Fin degree) (position : Fin 4096) : FinTM2 := + MachineAffineLookup.machine (4098 * degree) (4098 * port.val + 4 + position.val) + +end MinUncutGames.Foundations.Complexity.PoweringMachineRelation + +namespace MinUncutGames.Foundations.Complexity.PoweringMachineRelationField + +open Turing +open MachineComposition +open PCP + +variable {K Λ A : Type} [DecidableEq K] +variable {n d max : Nat} + +abbrev Alphabet (_ : K) := Bool +abbrev State (A : Type) := MachineUnaryEqualityBit.State A +abbrev Label (path : List (Fin d)) := PoweringMachineWord.Label path.length ⊕ MachineAffineLookup.Label + +def lookupTapes (placement : PoweringMachineTapes.Tape max → K) (i : Fin 5) : K := + placement (PoweringMachineTapes.relationPlacement max i.succ) + +omit [DecidableEq K] in +theorem lookupTapes_injective (placement : PoweringMachineTapes.Tape max → K) + (distinct : Function.Injective placement) : Function.Injective (lookupTapes placement) := by + intro i j h + exact (Fin.succ_injective _) ((PoweringMachineTapes.relationPlacement_injective max) (distinct h)) + +omit [DecidableEq K] in +theorem source_outside_lookup (placement : PoweringMachineTapes.Tape max → K) + (distinct : Function.Injective placement) : + ∀ i, placement (.inl 6) ≠ lookupTapes placement i := by + intro i h + have heq : PoweringMachineTapes.relationPlacement max 0 = PoweringMachineTapes.relationPlacement max i.succ := by + simpa [PoweringMachineTapes.leftEndpoint] using distinct h + have hi := (PoweringMachineTapes.relationPlacement_injective max) heq + have hv := congrArg Fin.val hi + simp at hv + +def endpoint (table : PortTables.Table n d) (vertex : Fin n) (path : List (Fin d)) : Fin n := + PoweringWalks.walkEnd (PortTables.portGraph table) vertex path + +theorem endpoint_eq_wordEnd (table : PortTables.Table n d) (vertex : Fin n) + (path : List (Fin d)) : + endpoint table vertex path = + PoweringWalks.wordEnd (PortTables.portGraph table) path.length vertex path.get := by + rw [PoweringReach.wordEnd_eq_walkEnd_ofFn, List.ofFn_get] + rfl + +def bit (table : PortTables.Table n d) (vertex : Fin n) (path : List (Fin d)) + (port : Fin d) (left right : PortTables.Label) : Nat := + GraphTables.bitWord (PortTables.accepts table (endpoint table vertex path, port) left right) + +def instruction (placement : PoweringMachineTapes.Tape max → K) (path : List (Fin d)) + (lengthBound : path.length ≤ max) (port : Fin d) (left right : PortTables.Label) + (labels : Label path → Λ) (exit : Option Λ) : + Label path → TM2.Stmt (Alphabet (K := K)) Λ (State A) + | .inl q => PoweringMachineWord.instruction path.length (placement ∘ PoweringMachineTapes.wordPlacement lengthBound false) + path.get (fun z => labels (.inl z)) (some (labels (.inr .seed))) q + | .inr q => PoweringMachineRelation.instruction (placement (.inl 6)) (lookupTapes placement) + port (GraphTables.relationIndex (left, right)) (fun z => labels (.inr z)) exit q + +def afterWord (placement : PoweringMachineTapes.Tape max → K) (path : List (Fin d)) + (lengthBound : path.length ≤ max) (table : PortTables.Table n d) + (vertex : Fin n) (base : K → List Bool) : K → List Bool := + PoweringMachineWord.finalTapes table path.length (placement ∘ PoweringMachineTapes.wordPlacement lengthBound false) + vertex path.get base + +def finalTapes (placement : PoweringMachineTapes.Tape max → K) (path : List (Fin d)) + (lengthBound : path.length ≤ max) (port : Fin d) (left right : PortTables.Label) + (table : PortTables.Table n d) (vertex : Fin n) (base : K → List Bool) : K → List Bool := + MachineAffineLookup.finalTapes (lookupTapes placement) + (afterWord placement path lengthBound table vertex base) (PortTables.tableWords table) + (PoweringMachineRelation.address (endpoint table vertex path) port + (GraphTables.relationIndex (left, right))) (bit table vertex path port left right) + +def steps (path : List (Fin d)) (port : Fin d) (left right : PortTables.Label) + (table : PortTables.Table n d) (vertex : Fin n) : Nat := + PoweringMachineWord.steps table path.length vertex path.get + + MachineAffineLookup.steps (PortTables.tableWords table) (endpoint table vertex path).val + (4098 * d) (4098 * port.val + 4 + (GraphTables.relationIndex (left, right)).val) + +theorem afterWord_frame (placement : PoweringMachineTapes.Tape max → K) (distinct : Function.Injective placement) + (path : List (Fin d)) (lengthBound : path.length ≤ max) + (table : PortTables.Table n d) (vertex : Fin n) (base : K → List Bool) + (role : Fin 11) (h₂ : role ≠ 2) (h₃ : role ≠ 3) (h₄ : role ≠ 4) (h₆ : role ≠ 6) : + afterWord placement path lengthBound table vertex base (placement (.inl role)) = + base (placement (.inl role)) := by + apply PoweringMachineWord.finalTapes_other + · intro h; exact h₂ (by simpa [PoweringMachineTapes.query] using distinct h) + · intro h; exact h₃ (by simpa [PoweringMachineTapes.scan] using distinct h) + · intro h; exact h₄ (by simpa [PoweringMachineTapes.reverse] using distinct h) + · intro h; exact h₆ (by simpa [PoweringMachineTapes.leftEndpoint] using distinct h) + · intro i h + have heq := distinct h + simp at heq + +theorem finalTapes_frame (placement : PoweringMachineTapes.Tape max → K) (distinct : Function.Injective placement) + (path : List (Fin d)) (lengthBound : path.length ≤ max) + (port : Fin d) (left right : PortTables.Label) + (table : PortTables.Table n d) (vertex : Fin n) (base : K → List Bool) + (role : Fin 11) (h₂ : role ≠ 2) (h₃ : role ≠ 3) (h₄ : role ≠ 4) + (h₆ : role ≠ 6) (h₁₀ : role ≠ 10) : + finalTapes placement path lengthBound port left right table vertex base (placement (.inl role)) = + base (placement (.inl role)) := by + calc + finalTapes placement path lengthBound port left right table vertex base (placement (.inl role)) = + afterWord placement path lengthBound table vertex base (placement (.inl role)) := by + apply MachineAffineLookup.finalTapes_other + · intro h; exact h₂ (by simpa [lookupTapes, PoweringMachineTapes.query] using distinct h) + · intro h; exact h₃ (by simpa [lookupTapes, PoweringMachineTapes.scan] using distinct h) + · intro h; exact h₁₀ (by simpa [lookupTapes, PoweringMachineTapes.rowOutput] using distinct h) + _ = _ := afterWord_frame placement distinct path lengthBound table vertex base role h₂ h₃ h₄ h₆ + +theorem finalTapes_other (placement : PoweringMachineTapes.Tape max → K) + (path : List (Fin d)) (lengthBound : path.length ≤ max) + (port : Fin d) (left right : PortTables.Label) + (table : PortTables.Table n d) (vertex : Fin n) (base : K → List Bool) + (k : K) (outside : ∀ i, k ≠ placement i) : + finalTapes placement path lengthBound port left right table vertex base k = base k := by + calc + finalTapes placement path lengthBound port left right table vertex base k = + afterWord placement path lengthBound table vertex base k := + MachineAffineLookup.finalTapes_other _ _ _ _ _ _ (outside _) (outside _) (outside _) + _ = base k := PoweringMachineWord.finalTapes_other _ _ _ _ _ _ _ + (outside _) (outside _) (outside _) (outside _) (fun i => outside _) + +theorem fieldTrace (placement : PoweringMachineTapes.Tape max → K) (distinct : Function.Injective placement) + (path : List (Fin d)) (lengthBound : path.length ≤ max) + (port : Fin d) (left right : PortTables.Label) + (labels : Label path → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ l, program (labels l) = instruction placement path lengthBound port left right labels exit l) + (table : PortTables.Table n d) (vertex : Fin n) (base : K → List Bool) + (tableWord : base (placement (.inl 0)) = PortTables.tableBits table) + (scratchEmpty : base (placement (.inl 5)) = []) (suffix : List Bool) + (sourceWord : base (placement (.inl 1)) = encodeWord vertex.val ++ suffix) (ambient : A) : + (advance (TM2.step program))^[steps path port left right table vertex] + (some ⟨some (labels (.inl (PoweringMachineWord.entry path.length))), MachineUnaryEqualityBit.clean ambient, base⟩) = + some ⟨exit, MachineUnaryEqualityBit.clean ambient, + finalTapes placement path lengthBound port left right table vertex base⟩ ∧ + finalTapes placement path lengthBound port left right table vertex base (placement (.inl 10)) = + encodeWord (bit table vertex path port left right) ++ base (placement (.inl 10)) := by + have hword := PoweringMachineWord.wordTrace table path.length (placement ∘ PoweringMachineTapes.wordPlacement lengthBound false) + (distinct.comp (PoweringMachineTapes.wordPlacement_injective lengthBound false)) vertex path.get + (fun q => labels (.inl q)) (some (labels (.inr .seed))) program + (fun q => atLabels (.inl q)) base (by simpa [PoweringMachineTapes.table] using tableWord) + (by simpa [PoweringMachineTapes.scratch] using scratchEmpty) suffix + (by simpa [PoweringMachineTapes.start] using sourceWord) (ambient, false, none) none + let mid := afterWord placement path lengthBound table vertex base + have hmidTable : mid (placement (.inl 0)) = PortTables.tableBits table := by + dsimp only [mid] + rw [afterWord_frame placement distinct path lengthBound table vertex base 0 + (by decide) (by decide) (by decide) (by decide)] + exact tableWord + have hmidScratch : mid (placement (.inl 5)) = [] := by + dsimp only [mid] + rw [afterWord_frame placement distinct path lengthBound table vertex base 5 + (by decide) (by decide) (by decide) (by decide)] + exact scratchEmpty + have hmidOutput : mid (placement (.inl 10)) = base (placement (.inl 10)) := + afterWord_frame placement distinct path lengthBound table vertex base 10 + (by decide) (by decide) (by decide) (by decide) + have hmidEndpoint : mid (placement (.inl 6)) = encodeWord (endpoint table vertex path).val ++ + base (placement (.inl 6)) := by + dsimp only [mid, afterWord] + simpa only [Function.comp_apply, PoweringMachineTapes.wordPlacement_inl_five, PoweringMachineTapes.endpoint_false, + PoweringMachineTapes.leftEndpoint, ← endpoint_eq_wordEnd] using hword.2 + have hrelation := PoweringMachineRelation.relationTrace (placement (.inl 6)) (lookupTapes placement) + (lookupTapes_injective placement distinct) (source_outside_lookup placement distinct) + port (GraphTables.relationIndex (left, right)) (fun q => labels (.inr q)) exit program + (fun q => atLabels (.inr q)) table (endpoint table vertex path) mid + (by simpa [lookupTapes, PoweringMachineTapes.table] using hmidTable) + (by simpa [lookupTapes, PoweringMachineTapes.scratch] using hmidScratch) + (base (placement (.inl 6))) hmidEndpoint (ambient, false, none) none + constructor + · simp only [MachineUnaryEqualityBit.clean] + rw [steps, Nat.add_comm, Function.iterate_add_apply, hword.1] + exact hrelation + · change MachineAffineLookup.finalTapes (lookupTapes placement) _ _ _ _ (lookupTapes placement 3) = _ + rw [MachineAffineLookup.finalTapes_output] + change encodeWord (bit table vertex path port left right) ++ mid (placement (.inl 10)) = _ + rw [hmidOutput] + +theorem steps_le (path : List (Fin d)) (port : Fin d) (left right : PortTables.Label) + (table : PortTables.Table n d) (vertex : Fin n) : + steps path port left right table vertex ≤ + (14 * path.length + 9) * (PortTables.tableBits table).length + 12 * path.length + 9 := by + have hw := PoweringMachineWord.steps_le table path.length vertex path.get + have hr := PoweringMachineRelation.steps_le table (endpoint table vertex path) port + (GraphTables.relationIndex (left, right)) + simp only [steps, Nat.add_mul, Nat.mul_assoc] at hw ⊢ + omega + +end MinUncutGames.Foundations.Complexity.PoweringMachineRelationField + +namespace MinUncutGames.Foundations.Complexity.PoweringMachineEqualityField + +open Turing +open MachineComposition +open PCP + +variable {K Λ A : Type} [DecidableEq K] +variable {max l r n d : Nat} + +abbrev Alphabet (_ : K) := Bool +abbrev Tape := PoweringMachineTapes.Tape +abbrev State := MachineUnaryEqualityBit.State +abbrev Label (l r : Nat) := + PoweringMachineWord.Label l ⊕ PoweringMachineWord.Label r ⊕ MachineUnaryEqualityBit.Label + +def entry (l r : Nat) : Label l r := .inl (PoweringMachineWord.entry l) + +def instruction (hl : l ≤ max) (hr : r ≤ max) (placement : Tape max → K) + (left : Fin l → Fin d) (right : Fin r → Fin d) + (labels : Label l r → Λ) (exit : Option Λ) : + Label l r → TM2.Stmt (Alphabet (K := K)) Λ (State A) + | .inl q => PoweringMachineWord.instruction l + (placement ∘ PoweringMachineTapes.wordPlacement hl false) left + (fun z => labels (.inl z)) + (some (labels (.inr (.inl (PoweringMachineWord.entry r))))) q + | .inr (.inl q) => PoweringMachineWord.instruction r + (placement ∘ PoweringMachineTapes.wordPlacement hr true) right + (fun z => labels (.inr (.inl z))) + (some (labels (.inr (.inr .seedLeft)))) q + | .inr (.inr q) => MachineUnaryEqualityBit.instruction + (placement ∘ PoweringMachineTapes.equalityPlacement max) + (fun z => labels (.inr (.inr z))) exit q + +def endpoint (graph : PortTables.Table n d) {t : Nat} (vertex : Fin n) + (ports : Fin t → Fin d) : Fin n := + PoweringWalks.wordEnd (PortTables.portGraph graph) t vertex ports + +def resultBit (graph : PortTables.Table n d) (vertex : Fin n) + (left : Fin l → Fin d) (right : Fin r → Fin d) : Bool := + decide (endpoint graph vertex left = endpoint graph vertex right) + +def wordTapes (graph : PortTables.Table n d) {t : Nat} (h : t ≤ max) + (placement : Tape max → K) (target : Bool) (vertex : Fin n) + (ports : Fin t → Fin d) (base : K → List Bool) : K → List Bool := + PoweringMachineWord.finalTapes graph t + (placement ∘ PoweringMachineTapes.wordPlacement h target) vertex ports base + +def finalTapes (graph : PortTables.Table n d) (hl : l ≤ max) (hr : r ≤ max) + (placement : Tape max → K) (vertex : Fin n) + (left : Fin l → Fin d) (right : Fin r → Fin d) (base : K → List Bool) : + K → List Bool := + let afterLeft := wordTapes graph hl placement false vertex left base + let afterBoth := wordTapes graph hr placement true vertex right afterLeft + Function.update afterBoth (placement (.inl 10)) + (MachineUnaryEqualityBit.bitEncoding (resultBit graph vertex left right) ++ + afterBoth (placement (.inl 10))) + +def steps (graph : PortTables.Table n d) (vertex : Fin n) + (left : Fin l → Fin d) (right : Fin r → Fin d) : Nat := + PoweringMachineWord.steps graph l vertex left + + PoweringMachineWord.steps graph r vertex right + + MachineUnaryEqualityBit.steps (endpoint graph vertex left).val + (endpoint graph vertex right).val + +theorem steps_le (graph : PortTables.Table n d) (vertex : Fin n) + (left : Fin l → Fin d) (right : Fin r → Fin d) : + steps graph vertex left right ≤ + (14 * (l + r) + 10) * (PortTables.tableBits graph).length + 12 * (l + r) + 15 := by + have hl := PoweringMachineWord.steps_le graph l vertex left + have hr := PoweringMachineWord.steps_le graph r vertex right + have he := MachineUnaryEqualityBit.steps_le + (endpoint graph vertex left).val (endpoint graph vertex right).val + have hleft := Nat.le_trans (Nat.le_of_lt (endpoint graph vertex left).isLt) + (PortTables.vertices_le_tableBits_length graph) + have hright := Nat.le_trans (Nat.le_of_lt (endpoint graph vertex right).isLt) + (PortTables.vertices_le_tableBits_length graph) + unfold steps + simp only [Nat.mul_add, Nat.add_mul, Nat.mul_assoc] at hl hr ⊢ + omega + +theorem wordTapes_other (graph : PortTables.Table n d) {t : Nat} (h : t ≤ max) + (placement : Tape max → K) (target : Bool) (vertex : Fin n) + (ports : Fin t → Fin d) (base : K → List Bool) (k : K) + (hquery : k ≠ placement (.inl 2)) (hscan : k ≠ placement (.inl 3)) + (hreverse : k ≠ placement (.inl 4)) + (houtput : k ≠ placement (PoweringMachineTapes.endpoint max target)) + (hpositions : ∀ i : Fin max, k ≠ placement (.inr i)) : + wordTapes graph h placement target vertex ports base k = base k := by + apply PoweringMachineWord.finalTapes_other + · simpa only [Function.comp_apply, PoweringMachineTapes.wordPlacement_inl_one, + PoweringMachineTapes.query] using hquery + · simpa only [Function.comp_apply, PoweringMachineTapes.wordPlacement_inl_two, + PoweringMachineTapes.scan] using hscan + · simpa only [Function.comp_apply, PoweringMachineTapes.wordPlacement_inl_three, + PoweringMachineTapes.reverse] using hreverse + · simpa only [Function.comp_apply, PoweringMachineTapes.wordPlacement_inl_five] using houtput + · intro i + simpa only [Function.comp_apply, PoweringMachineTapes.wordPlacement_succ] using + hpositions (Fin.castLE h i) + +theorem wordTapes_role (graph : PortTables.Table n d) {t : Nat} (h : t ≤ max) + (placement : Tape max → K) (distinct : Function.Injective placement) + (target : Bool) (vertex : Fin n) (ports : Fin t → Fin d) + (base : K → List Bool) (j : Fin 11) + (hquery : j ≠ 2) (hscan : j ≠ 3) (hreverse : j ≠ 4) + (houtput : j ≠ if target then 7 else 6) : + wordTapes graph h placement target vertex ports base (placement (.inl j)) = + base (placement (.inl j)) := by + apply wordTapes_other + · intro he + exact hquery (Sum.inl.inj (distinct he)) + · intro he + exact hscan (Sum.inl.inj (distinct he)) + · intro he + exact hreverse (Sum.inl.inj (distinct he)) + · intro he + apply houtput + cases target <;> exact Sum.inl.inj (distinct he) + · intro i he + cases distinct he + +theorem finalTapes_other (graph : PortTables.Table n d) (hl : l ≤ max) (hr : r ≤ max) + (placement : Tape max → K) (vertex : Fin n) + (left : Fin l → Fin d) (right : Fin r → Fin d) (base : K → List Bool) (k : K) + (hquery : k ≠ placement (.inl 2)) (hscan : k ≠ placement (.inl 3)) + (hreverse : k ≠ placement (.inl 4)) (hleft : k ≠ placement (.inl 6)) + (hright : k ≠ placement (.inl 7)) (hrow : k ≠ placement (.inl 10)) + (hpositions : ∀ i : Fin max, k ≠ placement (.inr i)) : + finalTapes graph hl hr placement vertex left right base k = base k := by + unfold finalTapes + rw [Function.update_of_ne hrow] + rw [wordTapes_other graph hr placement true vertex right _ k + hquery hscan hreverse hright hpositions] + exact wordTapes_other graph hl placement false vertex left base k + hquery hscan hreverse hleft hpositions + +theorem finalTapes_role (graph : PortTables.Table n d) (hl : l ≤ max) (hr : r ≤ max) + (placement : Tape max → K) (distinct : Function.Injective placement) (vertex : Fin n) + (left : Fin l → Fin d) (right : Fin r → Fin d) (base : K → List Bool) + (j : Fin 11) (hrole : j = 0 ∨ j = 1 ∨ j = 5 ∨ j = 8 ∨ j = 9) : + finalTapes graph hl hr placement vertex left right base (placement (.inl j)) = + base (placement (.inl j)) := by + apply finalTapes_other + all_goals first + | (intro he; have hij := Sum.inl.inj (distinct he); rcases hrole with rfl | rfl | rfl | rfl | rfl <;> simp at hij) + | (intro i he; cases distinct he) + +theorem finalTapes_output (graph : PortTables.Table n d) (hl : l ≤ max) (hr : r ≤ max) + (placement : Tape max → K) (distinct : Function.Injective placement) (vertex : Fin n) + (left : Fin l → Fin d) (right : Fin r → Fin d) (base : K → List Bool) : + finalTapes graph hl hr placement vertex left right base (placement (.inl 10)) = + MachineUnaryEqualityBit.bitEncoding (resultBit graph vertex left right) ++ + base (placement (.inl 10)) := by + unfold finalTapes + rw [Function.update_self, + wordTapes_role graph hr placement distinct true vertex right _ 10 + (by decide) (by decide) (by decide) (by decide), + wordTapes_role graph hl placement distinct false vertex left base 10 + (by decide) (by decide) (by decide) (by decide)] + +theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {u v : Nat} + (first : f^[u] a = b) (second : f^[v] b = c) : f^[u + v] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +theorem fieldTrace (graph : PortTables.Table n d) (hl : l ≤ max) (hr : r ≤ max) + (placement : Tape max → K) (distinct : Function.Injective placement) + (vertex : Fin n) (left : Fin l → Fin d) (right : Fin r → Fin d) + (labels : Label l r → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ q, program (labels q) = instruction hl hr placement left right labels exit q) + (base : K → List Bool) + (tableWord : base (placement (.inl 0)) = PortTables.tableBits graph) + (scratchEmpty : base (placement (.inl 5)) = []) + (leftCopyEmpty : base (placement (.inl 8)) = []) + (rightCopyEmpty : base (placement (.inl 9)) = []) + (suffix : List Bool) (sourceWord : base (placement (.inl 1)) = encodeWord vertex.val ++ suffix) + (ambient : A) : + (advance (TM2.step program))^[steps graph vertex left right] + (some ⟨some (labels (entry l r)), MachineUnaryEqualityBit.clean ambient, base⟩) = + some ⟨exit, MachineUnaryEqualityBit.clean ambient, + finalTapes graph hl hr placement vertex left right base⟩ := by + let afterLeft := wordTapes graph hl placement false vertex left base + let afterBoth := wordTapes graph hr placement true vertex right afterLeft + have leftFrame (j : Fin 11) (h2 : j ≠ 2) (h3 : j ≠ 3) (h4 : j ≠ 4) (h6 : j ≠ 6) : + afterLeft (placement (.inl j)) = base (placement (.inl j)) := + wordTapes_role graph hl placement distinct false vertex left base j h2 h3 h4 h6 + have rightFrame (j : Fin 11) (h2 : j ≠ 2) (h3 : j ≠ 3) (h4 : j ≠ 4) (h7 : j ≠ 7) : + afterBoth (placement (.inl j)) = afterLeft (placement (.inl j)) := + wordTapes_role graph hr placement distinct true vertex right afterLeft j h2 h3 h4 h7 + have bothFrame (j : Fin 11) (h2 : j ≠ 2) (h3 : j ≠ 3) (h4 : j ≠ 4) + (h6 : j ≠ 6) (h7 : j ≠ 7) : + afterBoth (placement (.inl j)) = base (placement (.inl j)) := + (rightFrame j h2 h3 h4 h7).trans (leftFrame j h2 h3 h4 h6) + have leftRun := PoweringMachineWord.wordTrace graph l + (placement ∘ PoweringMachineTapes.wordPlacement hl false) + (distinct.comp (PoweringMachineTapes.wordPlacement_injective hl false)) vertex left + (fun q => labels (.inl q)) + (some (labels (.inr (.inl (PoweringMachineWord.entry r))))) program + (fun q => atLabels (.inl q)) base + (by simpa only [Function.comp_apply, PoweringMachineTapes.wordPlacement_inl_zero, + PoweringMachineTapes.table] using tableWord) + (by simpa only [Function.comp_apply, PoweringMachineTapes.wordPlacement_inl_four, + PoweringMachineTapes.scratch] using scratchEmpty) + suffix (by simpa only [Function.comp_apply, PoweringMachineTapes.wordPlacement_first, + PoweringMachineTapes.start] using sourceWord) + (ambient, false, none) none + have rightTable : afterLeft (placement (.inl 0)) = PortTables.tableBits graph := + (leftFrame 0 (by decide) (by decide) (by decide) (by decide)).trans tableWord + have rightScratch : afterLeft (placement (.inl 5)) = [] := + (leftFrame 5 (by decide) (by decide) (by decide) (by decide)).trans scratchEmpty + have rightSource : afterLeft (placement (.inl 1)) = encodeWord vertex.val ++ suffix := + (leftFrame 1 (by decide) (by decide) (by decide) (by decide)).trans sourceWord + have rightRun := PoweringMachineWord.wordTrace graph r + (placement ∘ PoweringMachineTapes.wordPlacement hr true) + (distinct.comp (PoweringMachineTapes.wordPlacement_injective hr true)) vertex right + (fun q => labels (.inr (.inl q))) (some (labels (.inr (.inr .seedLeft)))) program + (fun q => atLabels (.inr (.inl q))) afterLeft + (by simpa only [Function.comp_apply, PoweringMachineTapes.wordPlacement_inl_zero, + PoweringMachineTapes.table] using rightTable) + (by simpa only [Function.comp_apply, PoweringMachineTapes.wordPlacement_inl_four, + PoweringMachineTapes.scratch] using rightScratch) + suffix (by simpa only [Function.comp_apply, PoweringMachineTapes.wordPlacement_first, + PoweringMachineTapes.start] using rightSource) + (ambient, false, none) none + have leftEndpoint : afterBoth (placement (.inl 6)) = + encodeWord (endpoint graph vertex left).val ++ base (placement (.inl 6)) := by + rw [rightFrame 6 (by decide) (by decide) (by decide) (by decide)] + dsimp only [afterLeft, wordTapes] + simpa only [Function.comp_apply, PoweringMachineTapes.wordPlacement_inl_five, + PoweringMachineTapes.endpoint_false, PoweringMachineTapes.leftEndpoint, + wordTapes, endpoint] using leftRun.2 + have rightEndpoint : afterBoth (placement (.inl 7)) = + encodeWord (endpoint graph vertex right).val ++ afterLeft (placement (.inl 7)) := by + dsimp only [afterBoth, wordTapes] + simpa only [Function.comp_apply, PoweringMachineTapes.wordPlacement_inl_five, + PoweringMachineTapes.endpoint_true, PoweringMachineTapes.rightEndpoint, + wordTapes, endpoint] using rightRun.2 + have copiesLeft : afterBoth (placement (.inl 8)) = [] := + (bothFrame 8 (by decide) (by decide) (by decide) (by decide) (by decide)).trans leftCopyEmpty + have copiesRight : afterBoth (placement (.inl 9)) = [] := + (bothFrame 9 (by decide) (by decide) (by decide) (by decide) (by decide)).trans rightCopyEmpty + have scratchBoth : afterBoth (placement (.inl 5)) = [] := + (bothFrame 5 (by decide) (by decide) (by decide) (by decide) (by decide)).trans scratchEmpty + have equalityRun := MachineUnaryEqualityBit.equalityTrace + (placement ∘ PoweringMachineTapes.equalityPlacement max) + (distinct.comp (PoweringMachineTapes.equalityPlacement_injective max)) + (fun q => labels (.inr (.inr q))) exit program (fun q => atLabels (.inr (.inr q))) + afterBoth (endpoint graph vertex left).val (endpoint graph vertex right).val + (base (placement (.inl 6))) (afterLeft (placement (.inl 7))) + (by simpa only [Function.comp_apply, PoweringMachineTapes.equalityPlacement_zero, + PoweringMachineTapes.leftEndpoint] using leftEndpoint) + (by simpa only [Function.comp_apply, PoweringMachineTapes.equalityPlacement_one, + PoweringMachineTapes.rightEndpoint] using rightEndpoint) + (by simpa only [Function.comp_apply, PoweringMachineTapes.equalityPlacement_two, + PoweringMachineTapes.leftCopy] using copiesLeft) + (by simpa only [Function.comp_apply, PoweringMachineTapes.equalityPlacement_three, + PoweringMachineTapes.rightCopy] using copiesRight) + (by simpa only [Function.comp_apply, PoweringMachineTapes.equalityPlacement_four, + PoweringMachineTapes.scratch] using scratchBoth) + ambient + have joined := joinTrace (joinTrace leftRun.1 rightRun.1) equalityRun + simpa only [steps, entry, MachineUnaryEqualityBit.clean, Function.comp_apply, + PoweringMachineTapes.equalityPlacement_five, PoweringMachineTapes.rowOutput, + finalTapes, resultBit, Fin.ext_iff, + afterLeft, afterBoth, wordTapes] using joined + +def fieldInTime (graph : PortTables.Table n d) (hl : l ≤ max) (hr : r ≤ max) + (placement : Tape max → K) (distinct : Function.Injective placement) + (vertex : Fin n) (left : Fin l → Fin d) (right : Fin r → Fin d) + (labels : Label l r → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ q, program (labels q) = instruction hl hr placement left right labels exit q) + (base : K → List Bool) + (tableWord : base (placement (.inl 0)) = PortTables.tableBits graph) + (scratchEmpty : base (placement (.inl 5)) = []) + (leftCopyEmpty : base (placement (.inl 8)) = []) + (rightCopyEmpty : base (placement (.inl 9)) = []) + (suffix : List Bool) (sourceWord : base (placement (.inl 1)) = encodeWord vertex.val ++ suffix) + (ambient : A) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels (entry l r)), MachineUnaryEqualityBit.clean ambient, base⟩ + (some ⟨exit, MachineUnaryEqualityBit.clean ambient, + finalTapes graph hl hr placement vertex left right base⟩) + ((14 * (l + r) + 10) * (PortTables.tableBits graph).length + 12 * (l + r) + 15) where + steps := steps graph vertex left right + evals_in_steps := fieldTrace graph hl hr placement distinct vertex left right labels exit program + atLabels base tableWord scratchEmpty leftCopyEmpty rightCopyEmpty suffix sourceWord ambient + steps_le_m := steps_le graph vertex left right + +def machine (degree : Nat) (hl : l ≤ max) (hr : r ≤ max) + (left : Fin l → Fin degree) (right : Fin r → Fin degree) : FinTM2 where + K := Tape max + k₀ := .inl 0 + k₁ := .inl 10 + Γ _ := Bool + Λ := Label l r + main := entry l r + σ := State Unit + initialState := MachineUnaryEqualityBit.clean () + m := instruction hl hr id left right id none + +end MinUncutGames.Foundations.Complexity.PoweringMachineEqualityField + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/PoweringMachineRotor.lean b/lean/OAI/Computability/MinUncut/Machines/PoweringMachineRotor.lean new file mode 100644 index 0000000000000000000000000000000000000000..a187ae2c3803216c37e43dd9226736607c968c9a --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/PoweringMachineRotor.lean @@ -0,0 +1,883 @@ +import Mathlib +import OAI.Computability.MinUncut.Games.PoweringMasterState +import OAI.Computability.MinUncut.Machines.MachinePreservingLookup +import OAI.Computability.MinUncut.PCP.PortTableLookup + +namespace OAI + +namespace MinUncutGames.Foundations.Complexity.PoweringMachineRotor + +open Turing +open MachineComposition +open PCP + +variable {K Λ σ : Type} [DecidableEq K] +variable {n d : Nat} + +abbrev Alphabet (_ : K) := Bool + +def reverseRole (i : Fin 5) : Fin 7 := + if i = 0 then 0 else if i = 1 then 2 else if i = 2 then 3 else if i = 3 then 4 else 6 + +def endpointRole (i : Fin 5) : Fin 7 := + if i = 0 then 0 else if i = 1 then 2 else if i = 2 then 3 else if i = 3 then 5 else 6 + +theorem reverseRole_injective : Function.Injective reverseRole := by decide +theorem endpointRole_injective : Function.Injective endpointRole := by decide +theorem source_outside_reverse : ∀ i, (1 : Fin 7) ≠ reverseRole i := by decide +theorem reverse_outside_endpoint : ∀ i, (4 : Fin 7) ≠ endpointRole i := by decide + +def reverseTapes (tape : Fin 7 → K) : Fin 5 → K := tape ∘ reverseRole +def endpointTapes (tape : Fin 7 → K) : Fin 5 → K := tape ∘ endpointRole + +inductive Label + | reverse (l : MachineAffineLookup.Label) + | endpoint (l : MachineAffineLookup.Label) + deriving DecidableEq, Fintype + +def instruction (tape : Fin 7 → K) (degree port : Nat) + (labels : Label → Λ) (exit : Option Λ) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) + | .reverse l => MachineAffineLookup.instruction (tape 1) (reverseTapes tape) + (4098 * degree) (4098 * port + 3) (fun q => labels (.reverse q)) + (some (labels (.endpoint .seed))) l + | .endpoint l => MachineAffineLookup.instruction (tape 4) (endpointTapes tape) + 4098 2 (fun q => labels (.endpoint q)) exit l + +def reverseId (table : PortTables.Table n d) (vertex : Fin n) (port : Fin d) : Nat := + table.reverseIndex[PortTables.rowIndex n d (vertex, port)].val + +def reverseAddress (vertex : Fin n) (port : Fin d) : Nat := + (4098 * d) * vertex.val + (4098 * port.val + 3) + +def endpointAddress (table : PortTables.Table n d) (vertex : Fin n) (port : Fin d) : Nat := + 4098 * reverseId table vertex port + 2 + +theorem reverse_selected (table : PortTables.Table n d) (vertex : Fin n) (port : Fin d) : + (PortTables.tableWords table)[reverseAddress vertex port]? = + some (reverseId table vertex port) := by + have h := PortTableLookup.reverse_word table (PortTables.rowIndex n d (vertex, port)) + have hindex : reverseAddress vertex port = 3 + 4098 * (PortTables.rowIndex n d (vertex, port)).val := by + simp only [reverseAddress, PortTables.rowIndex_val, Nat.mul_add, Nat.mul_assoc] + omega + rw [hindex] + exact h + +theorem endpoint_selected (table : PortTables.Table n d) (vertex : Fin n) (port : Fin d) : + (PortTables.tableWords table)[endpointAddress table vertex port]? = + some ((PortTables.rotation table (vertex, port)).1.val) := by + have h := PortTableLookup.rotation_head_word table (vertex, port) + simpa only [endpointAddress, reverseId, Nat.add_comm] using h + +def afterReverse (tape : Fin 7 → K) (table : PortTables.Table n d) + (vertex : Fin n) (port : Fin d) (base : K → List Bool) : K → List Bool := + MachineAffineLookup.finalTapes (reverseTapes tape) base (PortTables.tableWords table) + (reverseAddress vertex port) (reverseId table vertex port) + +def finalTapes (tape : Fin 7 → K) (table : PortTables.Table n d) + (vertex : Fin n) (port : Fin d) (base : K → List Bool) : K → List Bool := + MachineAffineLookup.finalTapes (endpointTapes tape) + (afterReverse tape table vertex port base) (PortTables.tableWords table) + (endpointAddress table vertex port) ((PortTables.rotation table (vertex, port)).1.val) + +def steps (table : PortTables.Table n d) (vertex : Fin n) (port : Fin d) : Nat := + MachineAffineLookup.steps (PortTables.tableWords table) vertex.val (4098 * d) (4098 * port.val + 3) + + MachineAffineLookup.steps (PortTables.tableWords table) (reverseId table vertex port) 4098 2 + +theorem rotorTrace (tape : Fin 7 → K) (distinct : Function.Injective tape) + (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (port : Fin d) + (atLabels : ∀ l, program (labels l) = instruction tape d port.val labels exit l) + (table : PortTables.Table n d) (vertex : Fin n) (base : K → List Bool) + (tableWord : base (tape 0) = PortTables.tableBits table) + (scratchEmpty : base (tape 6) = []) (suffix : List Bool) + (sourceWord : base (tape 1) = encodeWord vertex.val ++ suffix) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[steps table vertex port] + (some ⟨some (labels (.reverse .seed)), (ambient,register), base⟩) = + some ⟨exit, (ambient,none), finalTapes tape table vertex port base⟩ := by + have hd (i j : Fin 7) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + have hrDistinct : Function.Injective (reverseTapes tape) := distinct.comp reverseRole_injective + have heDistinct : Function.Injective (endpointTapes tape) := distinct.comp endpointRole_injective + have hrOutside : ∀ i, tape 1 ≠ reverseTapes tape i := fun i => + hd 1 (reverseRole i) (source_outside_reverse i) + have heOutside : ∀ i, tape 4 ≠ endpointTapes tape i := fun i => + hd 4 (endpointRole i) (reverse_outside_endpoint i) + have hreverse := MachineAffineLookup.affineLookupTrace (tape 1) (reverseTapes tape) + hrDistinct hrOutside (4098 * d) (4098 * port.val + 3) + (fun q => labels (.reverse q)) (some (labels (.endpoint .seed))) + program (fun q => atLabels (.reverse q)) base (PortTables.tableWords table) + tableWord scratchEmpty vertex.val suffix sourceWord (reverseId table vertex port) + (reverse_selected table vertex port) ambient register + let mid := afterReverse tape table vertex port base + have hmidTable : mid (tape 0) = PortTables.tableBits table := by + calc + mid (tape 0) = base (tape 0) := + MachineAffineLookup.finalTapes_other _ _ _ _ _ _ + (hd 0 2 (by decide)) (hd 0 3 (by decide)) (hd 0 4 (by decide)) + _ = _ := tableWord + have hmidScratch : mid (tape 6) = [] := by + calc + mid (tape 6) = base (tape 6) := + MachineAffineLookup.finalTapes_other _ _ _ _ _ _ + (hd 6 2 (by decide)) (hd 6 3 (by decide)) (hd 6 4 (by decide)) + _ = _ := scratchEmpty + have hmidSource : mid (tape 4) = encodeWord (reverseId table vertex port) ++ base (tape 4) := + MachineAffineLookup.finalTapes_output _ _ _ _ _ + have hendpoint := MachineAffineLookup.affineLookupTrace (tape 4) (endpointTapes tape) + heDistinct heOutside 4098 2 (fun q => labels (.endpoint q)) exit + program (fun q => atLabels (.endpoint q)) mid (PortTables.tableWords table) + hmidTable hmidScratch (reverseId table vertex port) (base (tape 4)) hmidSource + ((PortTables.rotation table (vertex, port)).1.val) + (endpoint_selected table vertex port) ambient none + rw [steps, Nat.add_comm, Function.iterate_add_apply, hreverse] + exact hendpoint + +theorem finalTapes_endpoint (tape : Fin 7 → K) (distinct : Function.Injective tape) + (table : PortTables.Table n d) (vertex : Fin n) (port : Fin d) (base : K → List Bool) : + finalTapes tape table vertex port base (tape 5) = + encodeWord ((PortTables.rotation table (vertex, port)).1.val) ++ base (tape 5) := by + have hd (i j : Fin 7) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + change MachineAffineLookup.finalTapes (endpointTapes tape) _ _ _ _ (endpointTapes tape 3) = _ + rw [MachineAffineLookup.finalTapes_output] + congr 1 + exact MachineAffineLookup.finalTapes_other _ _ _ _ _ _ + (hd 5 2 (by decide)) (hd 5 3 (by decide)) (hd 5 4 (by decide)) + +theorem finalTapes_other (tape : Fin 7 → K) (table : PortTables.Table n d) + (vertex : Fin n) (port : Fin d) (base : K → List Bool) (k : K) + (h₂ : k ≠ tape 2) (h₃ : k ≠ tape 3) (h₄ : k ≠ tape 4) (h₅ : k ≠ tape 5) : + finalTapes tape table vertex port base k = base k := by + calc + finalTapes tape table vertex port base k = afterReverse tape table vertex port base k := + MachineAffineLookup.finalTapes_other _ _ _ _ _ _ h₂ h₃ h₅ + _ = base k := MachineAffineLookup.finalTapes_other _ _ _ _ _ _ h₂ h₃ h₄ + +theorem steps_le (table : PortTables.Table n d) (vertex : Fin n) (port : Fin d) : + steps table vertex port ≤ 14 * (PortTables.tableBits table).length + 12 := by + have hvertex : vertex.val ≤ (encodeWords (PortTables.tableWords table)).length := + Nat.le_trans (Nat.le_of_lt vertex.isLt) (PortTables.vertices_le_tableBits_length table) + have hreverse := MachineLookupSpec.output_length_le (PortTables.tableWords table) + (reverseAddress vertex port) (reverseId table vertex port) (reverse_selected table vertex port) + rw [encodeWord_length] at hreverse + have hr := MachineAffineLookup.steps_le_table (PortTables.tableWords table) + vertex.val (4098 * d) (4098 * port.val + 3) (reverseId table vertex port) + (reverse_selected table vertex port) hvertex + have he := MachineAffineLookup.steps_le_table (PortTables.tableWords table) + (reverseId table vertex port) 4098 2 ((PortTables.rotation table (vertex, port)).1.val) + (endpoint_selected table vertex port) (by omega) + change _ ≤ 14 * (encodeWords (PortTables.tableWords table)).length + 12 + unfold steps + omega + +def machine (degree port : Nat) : FinTM2 where + K := Fin 7 + k₀ := 0 + k₁ := 5 + Γ _ := Bool + Λ := Label + main := .reverse .seed + σ := Unit × Option Bool + initialState := ((),none) + m := instruction id degree port id none + +end MinUncutGames.Foundations.Complexity.PoweringMachineRotor + +namespace MinUncutGames.Foundations.Complexity.PoweringMachineWord + +open Turing +open MachineComposition +open PCP + +variable {K Λ σ : Type} [DecidableEq K] +variable {n d : Nat} + +abbrev Alphabet (_ : K) := Bool +abbrev Tape (t : Nat) := Fin 6 ⊕ Fin (t + 1) + +def first (t : Nat) : Fin (t + 1) := ⟨0, by omega⟩ + +def shift (t : Nat) : Tape t → Tape (t + 1) := Sum.map id Fin.succ + +theorem shift_injective (t : Nat) : Function.Injective (shift t) := by + intro a b h + cases a <;> cases b <;> simp_all [shift] + +def rotorRole (t : Nat) (i : Fin 7) : Tape (t + 1) := + if i = 0 then .inl 0 else if i = 1 then .inr (first (t + 1)) else + if i = 2 then .inl 1 else if i = 3 then .inl 2 else + if i = 4 then .inl 3 else if i = 5 then .inr (first t).succ else .inl 4 + +theorem rotorRole_injective (t : Nat) : Function.Injective (rotorRole t) := by + intro a b h + fin_cases a <;> fin_cases b <;> simp_all [rotorRole, first, Fin.ext_iff] + +def Label : Nat → Type + | 0 => MachineUnaryAffineAt.Label + | t + 1 => PoweringMachineRotor.Label ⊕ Label t + +instance labelFintype (t : Nat) : Fintype (Label t) := by + induction t with + | zero => exact inferInstanceAs (Fintype MachineUnaryAffineAt.Label) + | succ t ih => + letI := ih + exact inferInstanceAs (Fintype (PoweringMachineRotor.Label ⊕ Label t)) + +instance labelDecidableEq (t : Nat) : DecidableEq (Label t) := by + induction t with + | zero => exact inferInstanceAs (DecidableEq MachineUnaryAffineAt.Label) + | succ t ih => + letI := ih + exact inferInstanceAs (DecidableEq (PoweringMachineRotor.Label ⊕ Label t)) + +def entry : (t : Nat) → Label t + | 0 => .seed + | _ + 1 => .inl (.reverse .seed) + +def copyInstruction (source scratch output : K) + (labels : MachineUnaryAffineAt.Label → Λ) (exit : Option Λ) : + MachineUnaryAffineAt.Label → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) + | .seed => MachineUnaryAffineAt.seed output 0 (labels .scan) + | .scan => MachineUnaryAffineAt.scan source scratch output 1 (labels .scan) (labels .restore) + | .restore => Reduction.MachineTransfer.loopAt scratch source id false (labels .restore) exit + +def instruction : (t : Nat) → (Tape t → K) → (Fin t → Fin d) → + (Label t → Λ) → Option Λ → Label t → + TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) + | 0, placement, _, labels, exit => + copyInstruction (placement (.inr (first 0))) (placement (.inl 4)) + (placement (.inl 5)) labels exit + | t + 1, placement, ports, labels, exit => fun l => + match l with + | .inl q => PoweringMachineRotor.instruction (placement ∘ rotorRole t) d (ports 0).val + (fun z => labels (.inl z)) (some (labels (.inr (entry t)))) q + | .inr q => instruction t (placement ∘ shift t) (fun j => ports j.succ) + (fun z => labels (.inr z)) exit q + +def steps (table : PortTables.Table n d) : + (t : Nat) → Fin n → (Fin t → Fin d) → Nat + | 0, vertex, _ => 2 * (vertex.val + 1) + 1 + | t + 1, vertex, ports => PoweringMachineRotor.steps table vertex (ports 0) + + steps table t (PortTables.rotation table (vertex, ports 0)).1 (fun j => ports j.succ) + +def finalTapes (table : PortTables.Table n d) : + (t : Nat) → (Tape t → K) → Fin n → (Fin t → Fin d) → (K → List Bool) → K → List Bool + | 0, placement, vertex, _, base => + Function.update base (placement (.inl 5)) (encodeWord vertex.val ++ base (placement (.inl 5))) + | t + 1, placement, vertex, ports, base => + finalTapes table t (placement ∘ shift t) (PortTables.rotation table (vertex, ports 0)).1 + (fun j => ports j.succ) + (PoweringMachineRotor.finalTapes (placement ∘ rotorRole t) table vertex (ports 0) base) + +theorem finalTapes_other (table : PortTables.Table n d) (t : Nat) + (placement : Tape t → K) (vertex : Fin n) (ports : Fin t → Fin d) + (base : K → List Bool) (k : K) + (hquery : k ≠ placement (.inl 1)) (hscan : k ≠ placement (.inl 2)) + (hreverse : k ≠ placement (.inl 3)) (houtput : k ≠ placement (.inl 5)) + (hpositions : ∀ i : Fin t, k ≠ placement (.inr i.succ)) : + finalTapes table t placement vertex ports base k = base k := by + induction t generalizing vertex base with + | zero => simp only [finalTapes, Function.update_of_ne houtput] + | succ t ih => + let mid := PoweringMachineRotor.finalTapes (placement ∘ rotorRole t) table vertex (ports 0) base + calc + finalTapes table (t + 1) placement vertex ports base k = mid k := + ih (placement ∘ shift t) (PortTables.rotation table (vertex, ports 0)).1 + (fun j => ports j.succ) mid hquery hscan hreverse houtput + (fun i => hpositions i.succ) + _ = base k := PoweringMachineRotor.finalTapes_other _ _ _ _ _ k + hquery hscan hreverse (hpositions (first t)) + +theorem wordTrace (table : PortTables.Table n d) (t : Nat) + (placement : Tape t → K) (distinct : Function.Injective placement) + (vertex : Fin n) (ports : Fin t → Fin d) + (labels : Label t → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atLabels : ∀ l, program (labels l) = instruction t placement ports labels exit l) + (base : K → List Bool) (tableWord : base (placement (.inl 0)) = PortTables.tableBits table) + (scratchEmpty : base (placement (.inl 4)) = []) (suffix : List Bool) + (sourceWord : base (placement (.inr (first t))) = encodeWord vertex.val ++ suffix) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[steps table t vertex ports] + (some ⟨some (labels (entry t)), (ambient,register), base⟩) = + some ⟨exit, (ambient,none), finalTapes table t placement vertex ports base⟩ ∧ + finalTapes table t placement vertex ports base (placement (.inl 5)) = + encodeWord (PoweringWalks.wordEnd (PortTables.portGraph table) t vertex ports).val ++ + base (placement (.inl 5)) := by + induction t generalizing vertex base suffix register with + | zero => + have hd (i j : Tape 0) (hne : i ≠ j) : placement i ≠ placement j := fun h => hne (distinct h) + have hrun := MachineUnaryAffineAt.seededAffineTrace + (placement (.inr (first 0))) (placement (.inl 4)) (placement (.inl 5)) + (hd _ _ (by simp [first])) (hd _ _ (by simp [first])) (hd _ _ (by simp)) + 1 0 (labels .seed) (labels .scan) (labels .restore) exit program + (atLabels .seed) (atLabels .scan) (atLabels .restore) + base vertex.val suffix sourceWord scratchEmpty ambient register + constructor + · simpa only [steps, entry, finalTapes, Nat.one_mul, Nat.add_zero] using hrun + · simp only [finalTapes, Function.update_self, PoweringWalks.wordEnd] + | succ t ih => + have hd (i j : Tape (t + 1)) (hne : i ≠ j) : placement i ≠ placement j := + fun h => hne (distinct h) + have hrotor := PoweringMachineRotor.rotorTrace (placement ∘ rotorRole t) + (distinct.comp (rotorRole_injective t)) (fun q => labels (.inl q)) + (some (labels (.inr (entry t)))) program (ports 0) (fun q => atLabels (.inl q)) + table vertex base tableWord scratchEmpty suffix sourceWord ambient register + let mid := PoweringMachineRotor.finalTapes (placement ∘ rotorRole t) table vertex (ports 0) base + have hmidTable : mid (placement (.inl 0)) = PortTables.tableBits table := by + calc + mid (placement (.inl 0)) = base (placement (.inl 0)) := + PoweringMachineRotor.finalTapes_other _ _ _ _ _ _ + (hd _ _ (by simp [rotorRole])) (hd _ _ (by simp [rotorRole])) + (hd _ _ (by simp [rotorRole])) (hd _ _ (by simp [rotorRole, first])) + _ = _ := tableWord + have hmidScratch : mid (placement (.inl 4)) = [] := by + calc + mid (placement (.inl 4)) = base (placement (.inl 4)) := + PoweringMachineRotor.finalTapes_other _ _ _ _ _ _ + (hd _ _ (by simp [rotorRole])) (hd _ _ (by simp [rotorRole])) + (hd _ _ (by simp [rotorRole])) (hd _ _ (by simp [rotorRole, first])) + _ = _ := scratchEmpty + have hmidOutput : mid (placement (.inl 5)) = base (placement (.inl 5)) := + PoweringMachineRotor.finalTapes_other _ _ _ _ _ _ + (hd _ _ (by simp [rotorRole])) (hd _ _ (by simp [rotorRole])) + (hd _ _ (by simp [rotorRole])) (hd _ _ (by simp [rotorRole, first])) + have hmidSource : mid (placement (.inr (first t).succ)) = + encodeWord (PortTables.rotation table (vertex, ports 0)).1.val ++ + base (placement (.inr (first t).succ)) := + PoweringMachineRotor.finalTapes_endpoint _ (distinct.comp (rotorRole_injective t)) _ _ _ _ + have htail := ih (placement ∘ shift t) (distinct.comp (shift_injective t)) + (PortTables.rotation table (vertex, ports 0)).1 (fun j => ports j.succ) + (fun q => labels (.inr q)) (fun q => atLabels (.inr q)) mid hmidTable hmidScratch + (base (placement (.inr (first t).succ))) hmidSource none + constructor + · rw [steps, Nat.add_comm, Function.iterate_add_apply] + simp only [entry] + rw [hrotor] + exact htail.1 + · change finalTapes table t (placement ∘ shift t) + (PortTables.rotation table (vertex, ports 0)).1 (fun j => ports j.succ) mid + ((placement ∘ shift t) (.inl 5)) = _ + rw [htail.2] + change _ ++ mid (placement (.inl 5)) = _ + rw [hmidOutput] + rfl + +theorem steps_le (table : PortTables.Table n d) (t : Nat) + (vertex : Fin n) (ports : Fin t → Fin d) : + steps table t vertex ports ≤ (14 * t + 2) * (PortTables.tableBits table).length + 12 * t + 3 := by + induction t generalizing vertex with + | zero => + have h := Nat.le_trans (Nat.le_of_lt vertex.isLt) (PortTables.vertices_le_tableBits_length table) + simp only [steps, Nat.mul_zero, Nat.zero_add] + omega + | succ t ih => + have hr := PoweringMachineRotor.steps_le table vertex (ports 0) + have ht := ih (PortTables.rotation table (vertex, ports 0)).1 (fun j => ports j.succ) + simp only [steps, Nat.mul_add, Nat.add_mul, Nat.mul_one, Nat.mul_assoc] at ht ⊢ + omega + +def machine (degree t : Nat) (ports : Fin t → Fin degree) : FinTM2 where + K := Tape t + k₀ := .inl 0 + k₁ := .inl 5 + Γ _ := Bool + Λ := Label t + main := entry t + σ := Unit × Option Bool + initialState := ((),none) + m := instruction t id ports id none + +end MinUncutGames.Foundations.Complexity.PoweringMachineWord + +namespace MinUncutGames.Foundations.Complexity.PoweringMachineTapes + +abbrev Tape (max : Nat) := Fin 11 ⊕ Fin max + +def table (max : Nat) : Tape max := .inl 0 +def start (max : Nat) : Tape max := .inl 1 +def query (max : Nat) : Tape max := .inl 2 +def scan (max : Nat) : Tape max := .inl 3 +def reverse (max : Nat) : Tape max := .inl 4 +def scratch (max : Nat) : Tape max := .inl 5 +def leftEndpoint (max : Nat) : Tape max := .inl 6 +def rightEndpoint (max : Nat) : Tape max := .inl 7 +def leftCopy (max : Nat) : Tape max := .inl 8 +def rightCopy (max : Nat) : Tape max := .inl 9 +def rowOutput (max : Nat) : Tape max := .inl 10 + +def endpoint (max : Nat) (target : Bool) : Tape max := + if target then rightEndpoint max else leftEndpoint max + +@[simp] theorem endpoint_false (max : Nat) : endpoint max false = leftEndpoint max := rfl +@[simp] theorem endpoint_true (max : Nat) : endpoint max true = rightEndpoint max := rfl + +def wordSharedRole (target : Bool) (i : Fin 6) : Fin 11 := + if i = 0 then 0 else if i = 1 then 2 else if i = 2 then 3 else + if i = 3 then 4 else if i = 4 then 5 else if target then 7 else 6 + +def trajectoryPlacement {t max : Nat} (h : t ≤ max) : Fin (t + 1) → Tape max := + Fin.cases (start max) (fun i => .inr (Fin.castLE h i)) + +def wordPlacement {t max : Nat} (h : t ≤ max) (target : Bool) : + PoweringMachineWord.Tape t → Tape max + | .inl i => .inl (wordSharedRole target i) + | .inr i => trajectoryPlacement h i + +@[simp] theorem wordPlacement_inl_zero {t max : Nat} (h : t ≤ max) (target : Bool) : + wordPlacement h target (.inl 0) = table max := rfl +@[simp] theorem wordPlacement_inl_one {t max : Nat} (h : t ≤ max) (target : Bool) : + wordPlacement h target (.inl 1) = query max := rfl +@[simp] theorem wordPlacement_inl_two {t max : Nat} (h : t ≤ max) (target : Bool) : + wordPlacement h target (.inl 2) = scan max := rfl +@[simp] theorem wordPlacement_inl_three {t max : Nat} (h : t ≤ max) (target : Bool) : + wordPlacement h target (.inl 3) = reverse max := rfl +@[simp] theorem wordPlacement_inl_four {t max : Nat} (h : t ≤ max) (target : Bool) : + wordPlacement h target (.inl 4) = scratch max := rfl +@[simp] theorem wordPlacement_inl_five {t max : Nat} (h : t ≤ max) (target : Bool) : + wordPlacement h target (.inl 5) = endpoint max target := by cases target <;> rfl +@[simp] theorem wordPlacement_first {t max : Nat} (h : t ≤ max) (target : Bool) : + wordPlacement h target (.inr (PoweringMachineWord.first t)) = start max := rfl +@[simp] theorem wordPlacement_succ {t max : Nat} (h : t ≤ max) (target : Bool) (i : Fin t) : + wordPlacement h target (.inr i.succ) = .inr (Fin.castLE h i) := rfl + +def relationPlacement (max : Nat) (i : Fin 6) : Tape max := + .inl (if i = 0 then 6 else if i = 1 then 0 else if i = 2 then 2 else + if i = 3 then 3 else if i = 4 then 10 else 5) + +@[simp] theorem relationPlacement_zero (max : Nat) : relationPlacement max 0 = leftEndpoint max := rfl +@[simp] theorem relationPlacement_one (max : Nat) : relationPlacement max 1 = table max := rfl +@[simp] theorem relationPlacement_two (max : Nat) : relationPlacement max 2 = query max := rfl +@[simp] theorem relationPlacement_three (max : Nat) : relationPlacement max 3 = scan max := rfl +@[simp] theorem relationPlacement_four (max : Nat) : relationPlacement max 4 = rowOutput max := rfl +@[simp] theorem relationPlacement_five (max : Nat) : relationPlacement max 5 = scratch max := rfl + +def equalityPlacement (max : Nat) (i : Fin 6) : Tape max := + .inl (if i = 0 then 6 else if i = 1 then 7 else if i = 2 then 8 else + if i = 3 then 9 else if i = 4 then 5 else 10) + +@[simp] theorem equalityPlacement_zero (max : Nat) : equalityPlacement max 0 = leftEndpoint max := rfl +@[simp] theorem equalityPlacement_one (max : Nat) : equalityPlacement max 1 = rightEndpoint max := rfl +@[simp] theorem equalityPlacement_two (max : Nat) : equalityPlacement max 2 = leftCopy max := rfl +@[simp] theorem equalityPlacement_three (max : Nat) : equalityPlacement max 3 = rightCopy max := rfl +@[simp] theorem equalityPlacement_four (max : Nat) : equalityPlacement max 4 = scratch max := rfl +@[simp] theorem equalityPlacement_five (max : Nat) : equalityPlacement max 5 = rowOutput max := rfl + +theorem wordSharedRole_injective (target : Bool) : Function.Injective (wordSharedRole target) := by + cases target <;> decide + +theorem wordSharedRole_ne_start (target : Bool) : + ∀ i : Fin 6, wordSharedRole target i ≠ 1 := by + cases target <;> decide + +theorem wordSharedRole_ne_rowOutput (target : Bool) : + ∀ i : Fin 6, wordSharedRole target i ≠ 10 := by + cases target <;> decide + +theorem trajectoryPlacement_injective {t max : Nat} (ht : t ≤ max) : + Function.Injective (trajectoryPlacement ht) := by + intro a b + refine Fin.cases ?_ (fun i => ?_) a + · refine Fin.cases ?_ (fun j => ?_) b + · intro _ + rfl + · intro h + change (Sum.inl (1 : Fin 11) : Tape max) = .inr (Fin.castLE ht j) at h + cases h + · refine Fin.cases ?_ (fun j => ?_) b + · intro h + change (Sum.inr (Fin.castLE ht i) : Tape max) = .inl (1 : Fin 11) at h + cases h + · intro h + change (Sum.inr (Fin.castLE ht i) : Tape max) = .inr (Fin.castLE ht j) at h + have hc : Fin.castLE ht i = Fin.castLE ht j := Sum.inr.inj h + have hv : i.val = j.val := congrArg (fun x : Fin max => x.val) hc + have hij : i = j := Fin.ext hv + exact congrArg Fin.succ hij + +theorem wordShared_ne_trajectory {t max : Nat} (ht : t ≤ max) (target : Bool) + (i : Fin 6) : + ∀ j : Fin (t + 1), + (Sum.inl (wordSharedRole target i) : Tape max) ≠ trajectoryPlacement ht j := by + intro j + refine Fin.cases ?_ (fun k => ?_) j + · intro h + change (Sum.inl (wordSharedRole target i) : Tape max) = .inl (1 : Fin 11) at h + exact wordSharedRole_ne_start target i (Sum.inl.inj h) + · intro h + change (Sum.inl (wordSharedRole target i) : Tape max) = .inr (Fin.castLE ht k) at h + cases h + +theorem wordPlacement_injective {t max : Nat} (ht : t ≤ max) (target : Bool) : + Function.Injective (wordPlacement ht target) := by + intro a b h + cases a with + | inl i => + cases b with + | inl j => + exact congrArg Sum.inl (wordSharedRole_injective target (Sum.inl.inj h)) + | inr j => + exact False.elim (wordShared_ne_trajectory ht target i j h) + | inr i => + cases b with + | inl j => + exact False.elim (wordShared_ne_trajectory ht target j i h.symm) + | inr j => + exact congrArg Sum.inr (trajectoryPlacement_injective ht h) + +theorem relationPlacement_injective (max : Nat) : Function.Injective (relationPlacement max) := by + intro i j h + fin_cases i <;> fin_cases j <;> simp_all [relationPlacement] + +theorem equalityPlacement_injective (max : Nat) : Function.Injective (equalityPlacement max) := by + intro i j h + fin_cases i <;> fin_cases j <;> simp_all [equalityPlacement] + +theorem wordPlacement_ne_rowOutput {t max : Nat} (ht : t ≤ max) (target : Bool) + (i : PoweringMachineWord.Tape t) : wordPlacement ht target i ≠ rowOutput max := by + cases i with + | inl i => + intro h + exact wordSharedRole_ne_rowOutput target i (Sum.inl.inj h) + | inr j => + refine Fin.cases ?_ (fun i => ?_) j + · intro h + change (Sum.inl (1 : Fin 11) : Tape max) = .inl (10 : Fin 11) at h + have hne : (1 : Fin 11) ≠ 10 := by decide + exact hne (Sum.inl.inj h) + · intro h + change (Sum.inr (Fin.castLE ht i) : Tape max) = .inl (10 : Fin 11) at h + cases h + +theorem shared_ne_wordPlacement_succ {t max : Nat} (ht : t ≤ max) (target : Bool) + (role : Fin 11) (i : Fin t) : + (Sum.inl role : Tape max) ≠ wordPlacement ht target (.inr i.succ) := by + intro h + change (Sum.inl role : Tape max) = .inr (Fin.castLE ht i) at h + cases h + +end MinUncutGames.Foundations.Complexity.PoweringMachineTapes + +namespace MinUncutGames.Foundations.Complexity.PoweringMachineInitialize + +open Turing +open PoweringMachineLoop PoweringMasterState + +abbrev ExtraTape (max : Nat) := PoweringMachineTapes.Tape max ⊕ Unit +abbrev GlobalTape (max : Nat) := HeaderTape ⊕ ExtraTape max +abbrev Label := HeaderLabel ⊕ MachineUnaryAffineAt.Label + +def finalOutput (max : Nat) : GlobalTape max := .inr (.inr ()) + +def commonPlacement (max : Nat) (tape : PoweringMachineTapes.Tape max) : GlobalTape max := + if tape = PoweringMachineTapes.start max then .inl .counter else .inr (.inl tape) + +theorem commonPlacement_injective (max : Nat) : Function.Injective (commonPlacement max) := by + intro a b h + by_cases ha : a = PoweringMachineTapes.start max <;> + by_cases hb : b = PoweringMachineTapes.start max <;> + simp_all [commonPlacement] + +@[simp] theorem commonPlacement_start (max : Nat) : + commonPlacement max (PoweringMachineTapes.start max) = .inl .counter := by + simp [commonPlacement] + +@[simp] theorem commonPlacement_table (max : Nat) : + commonPlacement max (PoweringMachineTapes.table max) = + .inr (.inl (PoweringMachineTapes.table max)) := by + simp [commonPlacement, PoweringMachineTapes.table, PoweringMachineTapes.start] + +@[simp] theorem commonPlacement_scratch (max : Nat) : + commonPlacement max (PoweringMachineTapes.scratch max) = + .inr (.inl (PoweringMachineTapes.scratch max)) := by + simp [commonPlacement, PoweringMachineTapes.scratch, PoweringMachineTapes.start] + +@[simp] theorem commonPlacement_rowOutput (max : Nat) : + commonPlacement max (PoweringMachineTapes.rowOutput max) = + .inr (.inl (PoweringMachineTapes.rowOutput max)) := by + simp [commonPlacement, PoweringMachineTapes.rowOutput, PoweringMachineTapes.start] + +theorem commonPlacement_ne_finalOutput (max : Nat) (tape : PoweringMachineTapes.Tape max) : + commonPlacement max tape ≠ finalOutput max := by + by_cases h : tape = PoweringMachineTapes.start max <;> + simp [commonPlacement, finalOutput, h] + +theorem commonPlacement_ne_header (max : Nat) (tape : PoweringMachineTapes.Tape max) + (field : HeaderTape) (hne : field ≠ .counter) : + commonPlacement max tape ≠ .inl field := by + by_cases h : tape = PoweringMachineTapes.start max <;> + simp [commonPlacement, h, Ne.symm hne] + +def headerPlacement (max : Nat) (tape : PoweringMachineTapes.Tape max) : GlobalTape max := + if tape = PoweringMachineTapes.rowOutput max then finalOutput max + else commonPlacement max tape + +theorem headerPlacement_injective (max : Nat) : Function.Injective (headerPlacement max) := by + intro a b h + by_cases ha : a = PoweringMachineTapes.rowOutput max + · subst a + by_cases hb : b = PoweringMachineTapes.rowOutput max + · exact hb.symm + · simp only [headerPlacement, ite_eq_right hb] at h + exact False.elim (commonPlacement_ne_finalOutput max b h.symm) + · by_cases hb : b = PoweringMachineTapes.rowOutput max + · subst b + simp only [headerPlacement, ite_eq_right ha] at h + exact False.elim (commonPlacement_ne_finalOutput max a h) + · simp only [headerPlacement, ite_eq_right ha, ite_eq_right hb] at h + exact commonPlacement_injective max h + +@[simp] theorem headerPlacement_rowOutput (max : Nat) : + headerPlacement max (PoweringMachineTapes.rowOutput max) = finalOutput max := by + simp [headerPlacement] + +theorem headerPlacement_eq_common (max : Nat) (tape : PoweringMachineTapes.Tape max) + (hne : tape ≠ PoweringMachineTapes.rowOutput max) : + headerPlacement max tape = commonPlacement max tape := by simp [headerPlacement, hne] + +theorem headerPlacement_ne_data (max : Nat) (tape : PoweringMachineTapes.Tape max) : + headerPlacement max tape ≠ commonPlacement max (PoweringMachineTapes.rowOutput max) := by + by_cases h : tape = PoweringMachineTapes.rowOutput max + · simp only [headerPlacement, ite_eq_left h] + exact Ne.symm (commonPlacement_ne_finalOutput max _) + · rw [headerPlacement_eq_common max tape h] + exact fun heq => h (commonPlacement_injective max heq) + +theorem headerPlacement_ne_header (max : Nat) (tape : PoweringMachineTapes.Tape max) + (field : HeaderTape) (hne : field ≠ .counter) : + headerPlacement max tape ≠ .inl field := by + by_cases h : tape = PoweringMachineTapes.rowOutput max + · simp [headerPlacement, h, finalOutput] + · rw [headerPlacement_eq_common max tape h] + exact commonPlacement_ne_header max tape field hne + +private def castTapes {K : Type} {Γ Δ : K → Type} (h : Γ = Δ) + (tapes : ∀ k, List (Γ k)) : ∀ k, List (Δ k) := h ▸ tapes + +def castStatement {K Λ σ : Type} {Γ Δ : K → Type} (h : Γ = Δ) + (q : TM2.Stmt Γ Λ σ) : TM2.Stmt Δ Λ σ := h ▸ q + +def castConfiguration {K Λ σ : Type} {Γ Δ : K → Type} (h : Γ = Δ) + (c : TM2.Cfg Γ Λ σ) : TM2.Cfg Δ Λ σ := h ▸ c + +private theorem castTapes_apply {K : Type} {Γ Δ : K → Type} (h : Γ = Δ) + (tapes : ∀ k, List (Γ k)) (k : K) : + castTapes h tapes k = cast (congrArg (fun alphabet => List (alphabet k)) h) (tapes k) := by + cases h + rfl + +private theorem castConfiguration_mk {K Λ σ : Type} {Γ Δ : K → Type} (h : Γ = Δ) + (label : Option Λ) (state : σ) (tapes : ∀ k, List (Γ k)) : + castConfiguration h ⟨label, state, tapes⟩ = ⟨label, state, castTapes h tapes⟩ := by + cases h + rfl + +private theorem stepAux_cast {K Λ σ : Type} [DecidableEq K] + {Γ Δ : K → Type} (h : Γ = Δ) (q : TM2.Stmt Γ Λ σ) + (state : σ) (tapes : ∀ k, List (Γ k)) : + TM2.stepAux (castStatement h q) state (castTapes h tapes) = + castConfiguration h (TM2.stepAux q state tapes) := by + cases h + rfl + +private theorem boolAlphabet_eq (max : Nat) : + MachineEmbedding.Alphabet HeaderAlphabet (fun _ : ExtraTape max => Bool) = + (fun _ : GlobalTape max => Bool) := by + funext tape + cases tape <;> rfl + +def mergeTapes {max : Nat} (header : HeaderTape → List Bool) + (extra : ExtraTape max → List Bool) : GlobalTape max → List Bool + | .inl k => header k + | .inr e => extra e + +private theorem castTapes_embedding {max : Nat} (header : HeaderTape → List Bool) + (extra : ExtraTape max → List Bool) : + castTapes (boolAlphabet_eq max) (MachineEmbedding.tapes header extra) = + mergeTapes header extra := by + funext tape + rw [castTapes_apply] + cases tape <;> rfl + +private def dropUnit (N : Nat) : (Master N × Unit) ≃ Master N where + toFun := Prod.fst + invFun state := (state, ()) + left_inv := by rintro ⟨state, ⟨⟩⟩; rfl + right_inv := by intro state; rfl + +def headerStatement (max N B : Nat) (label : HeaderLabel) : + TM2.Stmt (fun _ : GlobalTape max => Bool) Label (Master N) := + MachineStateEquiv.statement (dropUnit N) + (castStatement (boolAlphabet_eq max) + (MachineEmbedding.statement (Λextra := MachineUnaryAffineAt.Label) + (τ := Unit) none (headerProgram (σ := OtherRegisters N) B label))) + +def headerConfiguration {max N : Nat} (extra : ExtraTape max → List Bool) + (c : TM2.Cfg HeaderAlphabet HeaderLabel (Master N)) : + TM2.Cfg (fun _ : GlobalTape max => Bool) Label (Master N) := + ⟨c.l.map Sum.inl, c.var, mergeTapes c.stk extra⟩ + +private theorem headerConfiguration_eq {max N : Nat} (extra : ExtraTape max → List Bool) + (c : TM2.Cfg HeaderAlphabet HeaderLabel (Master N)) : + headerConfiguration extra c = + MachineStateEquiv.configuration (dropUnit N) + (castConfiguration (boolAlphabet_eq max) + (MachineEmbedding.configuration (Λextra := MachineUnaryAffineAt.Label) + none () extra c)) := by + cases c with + | mk label state tapes => + simp only [MachineEmbedding.configuration, castConfiguration_mk, + MachineStateEquiv.configuration, castTapes_embedding, dropUnit, + Equiv.coe_fn_mk, headerConfiguration] + cases label <;> rfl + +theorem stepAux_headerStatement (max N B : Nat) (label : HeaderLabel) + (state : Master N) (header : HeaderTape → List Bool) + (extra : ExtraTape max → List Bool) : + TM2.stepAux (headerStatement max N B label) state (mergeTapes header extra) = + headerConfiguration extra (TM2.stepAux (headerProgram B label) state header) := by + rw [headerStatement, MachineStateEquiv.stepAux_transport_symm] + change MachineStateEquiv.configuration (dropUnit N) + (TM2.stepAux (castStatement (boolAlphabet_eq max) + (MachineEmbedding.statement none (headerProgram B label))) (state, ()) + (mergeTapes header extra)) = _ + rw [← castTapes_embedding, stepAux_cast, MachineEmbedding.stepAux_simulation] + exact (headerConfiguration_eq extra _).symm + +def program (max N B : Nat) : Label → + TM2.Stmt (fun _ : GlobalTape max => Bool) Label (Master N) + | .inl label => headerStatement max N B label + | .inr .seed => MachineUnaryAffineAt.seed (.inl .source) 0 (.inr .scan) + | .inr .scan => MachineUnaryAffineAt.scan + (commonPlacement max (PoweringMachineTapes.table max)) + (commonPlacement max (PoweringMachineTapes.scratch max)) + (.inl .source) 1 (.inr .scan) (.inr .restore) + | .inr .restore => Reduction.MachineTransfer.loopAt + (commonPlacement max (PoweringMachineTapes.scratch max)) + (commonPlacement max (PoweringMachineTapes.table max)) + id false (.inr .restore) (some (.inl .initialize)) + +theorem headerStep (max N B : Nat) (extra : ExtraTape max → List Bool) + (a b : TM2.Cfg HeaderAlphabet HeaderLabel (Master N)) + (run : TM2.step (headerProgram B) a = some b) : + TM2.step (program max N B) (headerConfiguration extra a) = + some (headerConfiguration extra b) := by + cases a with + | mk label state tapes => + cases label with + | none => simp [TM2.step] at run + | some label => + have hb : TM2.stepAux (headerProgram B label) state tapes = b := Option.some.inj run + rw [← hb] + change some (TM2.stepAux (headerStatement max N B label) state + (mergeTapes tapes extra)) = _ + rw [stepAux_headerStatement] + +theorem headerTrace (max N B vertices : Nat) (extra : ExtraTape max → List Bool) + (state : Master N) : + (MachineComposition.advance (TM2.step (program max N B)))^[vertices + 2] + (some ⟨some (.inl .initialize), state, + mergeTapes (initialTapes vertices []) extra⟩) = + some ⟨none, (state.1, none), mergeTapes (finalTapes B vertices []) extra⟩ := by + exact MachineComposition.liftSuccessfulTrace (TM2.step (headerProgram B)) + (TM2.step (program max N B)) (headerConfiguration extra) + (headerStep max N B extra) (vertices + 2) _ _ + (PoweringMachineLoop.headerTrace B vertices [] state.1 state.2) + +def initialGlobalTapes {max : Nat} (extra : ExtraTape max → List Bool) : + GlobalTape max → List Bool := mergeTapes (fun _ => []) extra + +theorem copyFirstTrace (max N B vertices : Nat) (extra : ExtraTape max → List Bool) + (suffix : List Bool) + (input : extra (.inl (PoweringMachineTapes.table max)) = encodeWord vertices ++ suffix) + (scratch : extra (.inl (PoweringMachineTapes.scratch max)) = []) + (state : Master N) : + (MachineComposition.advance (TM2.step (program max N B)))^[2 * (vertices + 1) + 1] + (some ⟨some (.inr .seed), state, initialGlobalTapes extra⟩) = + some ⟨some (.inl .initialize), (state.1, none), + mergeTapes (initialTapes vertices []) extra⟩ := by + have copied := MachineUnaryAffineAt.seededAffineTrace + (commonPlacement max (PoweringMachineTapes.table max)) + (commonPlacement max (PoweringMachineTapes.scratch max)) (.inl HeaderTape.source) + (by + intro heq + have hroles := commonPlacement_injective max heq + simp [PoweringMachineTapes.table, PoweringMachineTapes.scratch] at hroles) + (by simp) (by simp) 1 0 (.inr .seed) (.inr .scan) (.inr .restore) + (some (.inl .initialize)) (program max N B) rfl rfl rfl + (initialGlobalTapes extra) vertices suffix + (by simpa [initialGlobalTapes, mergeTapes] using input) + (by simpa [initialGlobalTapes, mergeTapes] using scratch) state.1 state.2 + have handoff : Function.update (initialGlobalTapes extra) (.inl HeaderTape.source) + (encodeWord (1 * vertices + 0) ++ initialGlobalTapes extra (.inl .source)) = + mergeTapes (initialTapes vertices []) extra := by + funext tape + cases tape with + | inl field => cases field <;> simp [initialGlobalTapes, mergeTapes, initialTapes] + | inr field => simp [initialGlobalTapes, mergeTapes] + rw [handoff] at copied + exact copied + +theorem initializeTrace (max N B vertices : Nat) (extra : ExtraTape max → List Bool) + (suffix : List Bool) + (input : extra (.inl (PoweringMachineTapes.table max)) = encodeWord vertices ++ suffix) + (scratch : extra (.inl (PoweringMachineTapes.scratch max)) = []) + (state : Master N) : + (MachineComposition.advance (TM2.step (program max N B)))^[3 * vertices + 5] + (some ⟨some (.inr .seed), state, initialGlobalTapes extra⟩) = + some ⟨none, (state.1, none), mergeTapes (finalTapes B vertices []) extra⟩ := by + rw [show 3 * vertices + 5 = (vertices + 2) + (2 * (vertices + 1) + 1) by omega, + Function.iterate_add_apply, copyFirstTrace max N B vertices extra suffix input scratch state] + exact headerTrace max N B vertices extra (state.1, none) + +def initializeInTime (max N B vertices : Nat) (extra : ExtraTape max → List Bool) + (suffix : List Bool) + (input : extra (.inl (PoweringMachineTapes.table max)) = encodeWord vertices ++ suffix) + (scratch : extra (.inl (PoweringMachineTapes.scratch max)) = []) + (state : Master N) : + StateTransition.EvalsToInTime (TM2.step (program max N B)) + ⟨some (.inr .seed), state, initialGlobalTapes extra⟩ + (some ⟨none, (state.1, none), mergeTapes (finalTapes B vertices []) extra⟩) + (3 * vertices + 5) where + steps := 3 * vertices + 5 + evals_in_steps := initializeTrace max N B vertices extra suffix input scratch state + steps_le_m := Nat.le_refl _ + +def instruction {Λ : Type} (max N B : Nat) (labels : Label → Λ) (exit : Option Λ) + (label : Label) : TM2.Stmt (fun _ : GlobalTape max => Bool) Λ (Master N) := + MachineSubroutine.statement labels exit (program max N B label) + +def initializeAtInTime {Λ : Type} (max N B vertices : Nat) + (labels : Label → Λ) (exit : Option Λ) + (caller : Λ → TM2.Stmt (fun _ : GlobalTape max => Bool) Λ (Master N)) + (atLabels : ∀ label, caller (labels label) = instruction max N B labels exit label) + (extra : ExtraTape max → List Bool) (suffix : List Bool) + (input : extra (.inl (PoweringMachineTapes.table max)) = encodeWord vertices ++ suffix) + (scratch : extra (.inl (PoweringMachineTapes.scratch max)) = []) + (state : Master N) : + StateTransition.EvalsToInTime (TM2.step caller) + ⟨some (labels (.inr .seed)), state, initialGlobalTapes extra⟩ + (some ⟨exit, (state.1, none), mergeTapes (finalTapes B vertices []) extra⟩) + (3 * vertices + 5) := + MachineSubroutine.execution labels exit (program max N B) caller atLabels + (initializeInTime max N B vertices extra suffix input scratch state) + +@[simp] theorem final_counter (max B vertices : Nat) (extra : ExtraTape max → List Bool) : + mergeTapes (finalTapes B vertices []) extra + (commonPlacement max (PoweringMachineTapes.start max)) = encodeWord vertices := by + simp [mergeTapes, finalTapes] + +@[simp] theorem final_vertices (max B vertices : Nat) (extra : ExtraTape max → List Bool) : + mergeTapes (finalTapes B vertices []) extra (.inl .vertices) = encodeWord vertices := rfl + +@[simp] theorem final_darts (max B vertices : Nat) (extra : ExtraTape max → List Bool) : + mergeTapes (finalTapes B vertices []) extra (.inl .darts) = encodeWord (B * vertices) := rfl + +@[simp] theorem final_extra (max B vertices : Nat) (extra : ExtraTape max → List Bool) + (tape : ExtraTape max) : + mergeTapes (finalTapes B vertices []) extra (.inr tape) = extra tape := rfl + +end MinUncutGames.Foundations.Complexity.PoweringMachineInitialize + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/PoweringMachineRow.lean b/lean/OAI/Computability/MinUncut/Machines/PoweringMachineRow.lean new file mode 100644 index 0000000000000000000000000000000000000000..6194dcf1f7c21b6f4fcf7875353c3027a77a722a --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/PoweringMachineRow.lean @@ -0,0 +1,667 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineLookup + +namespace OAI + +section +namespace MinUncutGames.Foundations.Complexity.PoweringMachineRow + +open Turing +open MachineFixedBlockMap +open MinUncutGames.Foundations.PCP + +abbrev Field (S : Nat) := (GraphTables.Label × GraphTables.Label) ⊕ (Fin S ⊕ Fin S) + +def inputSize (t S : Nat) : Nat := t * (4096 + (S + S)) + +def fieldEquiv (S : Nat) : Field S ≃ Fin (4096 + (S + S)) := + (Equiv.sumCongr GraphTables.relationIndex + (finSumFinEquiv : (Fin S ⊕ Fin S) ≃ Fin (S + S))).trans finSumFinEquiv + +def inputEquiv (t S : Nat) : (Fin t × Field S) ≃ Fin (inputSize t S) := + (Equiv.prodCongr (Equiv.refl (Fin t)) (fieldEquiv S)).trans finProdFinEquiv + +def packData {t S : Nat} (data : Fin t → Field S → Bool) : Buffer (inputSize t S) := + fun i => data ((inputEquiv t S).symm i).1 ((inputEquiv t S).symm i).2 + +@[simp] theorem packData_inputEquiv {t S : Nat} + (data : Fin t → Field S → Bool) (k : Fin t) (f : Field S) : + packData data (inputEquiv t S (k, f)) = data k f := by + simp [packData] + +def basePredicate {t S : Nat} (bits : Buffer (inputSize t S)) + (k : Fin t) (a b : GraphTables.Label) : Bool := + bits (inputEquiv t S (k, .inl (a, b))) + +def leftMatches {t S : Nat} (bits : Buffer (inputSize t S)) + (k : Fin t) (i : Fin S) : Bool := + bits (inputEquiv t S (k, .inr (.inl i))) + +def rightMatches {t S : Nat} (bits : Buffer (inputSize t S)) + (k : Fin t) (i : Fin S) : Bool := + bits (inputEquiv t S (k, .inr (.inr i))) + +def firstMatch {S : Nat} (mask : Fin S → Bool) : Option (Fin S) := + (List.ofFn id).find? mask + +theorem firstMatch_spec {S : Nat} (mask : Fin S → Bool) (i : Fin S) : + firstMatch mask = some i ↔ + mask i = true ∧ ∃ before after, + List.ofFn id = before ++ i :: after ∧ ∀ j ∈ before, mask j = false := by + simpa only [firstMatch, Bool.not_eq_eq_eq_not, Bool.not_true] using + (List.find?_eq_some_iff_append (xs := List.ofFn id) (p := mask) (b := i)) + +theorem firstMatch_none {S : Nat} (mask : Fin S → Bool) : + firstMatch mask = none ↔ ∀ i, mask i = false := by + simp [firstMatch, List.find?_eq_none, List.mem_ofFn] + +def edgeAccept {t S q : Nat} (labelAt : Fin q → Fin S → GraphTables.Label) + (bits : Buffer (inputSize t S)) (k : Fin t) (a b : Fin q) : Bool := + match firstMatch (leftMatches bits k), firstMatch (rightMatches bits k) with + | some i, some j => basePredicate bits k (labelAt a i) (labelAt b j) + | _, _ => false + +theorem edgeAccept_of_matches {t S q : Nat} + (labelAt : Fin q → Fin S → GraphTables.Label) + (bits : Buffer (inputSize t S)) (k : Fin t) (a b : Fin q) (i j : Fin S) + (hl : firstMatch (leftMatches bits k) = some i) + (hr : firstMatch (rightMatches bits k) = some j) : + edgeAccept labelAt bits k a b = basePredicate bits k (labelAt a i) (labelAt b j) := by + simp [edgeAccept, hl, hr] + +def rowAccept {t S q : Nat} (labelAt : Fin q → Fin S → GraphTables.Label) + (bits : Buffer (inputSize t S)) (a b : Fin q) : Bool := + (List.ofFn id).all (fun k : Fin t => edgeAccept labelAt bits k a b) + +theorem rowAccept_eq_true {t S q : Nat} + (labelAt : Fin q → Fin S → GraphTables.Label) + (bits : Buffer (inputSize t S)) (a b : Fin q) : + rowAccept labelAt bits a b = true ↔ ∀ k, edgeAccept labelAt bits k a b = true := by + simp [rowAccept, List.all_eq_true, List.mem_ofFn] + +def rowBlock {t S q : Nat} (labelAt : Fin q → Fin S → GraphTables.Label) + (bits : Buffer (inputSize t S)) : Buffer (q * q) := + fun i => rowAccept labelAt bits + ((GenericGraphTables.relationIndex q).symm i).1 + ((GenericGraphTables.relationIndex q).symm i).2 + +@[simp] theorem rowBlock_at {t S q : Nat} + (labelAt : Fin q → Fin S → GraphTables.Label) + (bits : Buffer (inputSize t S)) (a b : Fin q) : + rowBlock labelAt bits (GenericGraphTables.relationIndex q (a, b)) = + rowAccept labelAt bits a b := by + simp [rowBlock] + +def encodeBit (b : Bool) : List Bool := if b then [true, false] else [false] + +def encodeBits : List Bool → List Bool + | [] => [] + | b :: bits => encodeBit b ++ encodeBits bits + +@[simp] theorem encodeBits_append (xs ys : List Bool) : + encodeBits (xs ++ ys) = encodeBits xs ++ encodeBits ys := by + induction xs with + | nil => rfl + | cons b xs ih => simp [encodeBits, ih, List.append_assoc] + +theorem encodeBits_graphWords (bits : List Bool) : + encodeBits bits = encodeWords (bits.map GraphTables.bitWord) := by + induction bits with + | nil => rfl + | cons b bits ih => cases b <;> simp [encodeBits, encodeBit, encodeWords, + GraphTables.bitWord, encodeWord, ih] + +theorem encodeBits_length_le (bits : List Bool) : + (encodeBits bits).length ≤ 2 * bits.length := by + induction bits with + | nil => simp [encodeBits] + | cons b bits ih => + cases b <;> simp only [encodeBits, encodeBit, Bool.false_eq_true, + ite_false, ite_true, List.length_append, List.length_cons, List.length_nil] <;> omega + +section Chains + +variable {K Λ σ : Type} {N : Nat} + +def readEncodedSlots (src : K) : List (Fin N) → + TM2.Stmt (fun _ : K => Bool) Λ (σ × Buffer N) → + TM2.Stmt (fun _ : K => Bool) Λ (σ × Buffer N) + | [], next => next + | i :: slots, next => + .pop src (fun state head => + (state.1, Function.update state.2 i (head.getD false))) + (.branch (fun state => state.2 i) + (.pop src (fun state _ => state) (readEncodedSlots src slots next)) + (readEncodedSlots src slots next)) + +variable [DecidableEq K] + +theorem stepAux_readEncodedSlots (src : K) (slots : List (Fin N)) + (next : TM2.Stmt (fun _ : K => Bool) Λ (σ × Buffer N)) + (ambient : σ) (bits buffer : Buffer N) (tapes : K → List Bool) + (suffix : List Bool) : + TM2.stepAux (readEncodedSlots src slots next) (ambient, buffer) + (Function.update tapes src (encodeBits (slots.map bits) ++ suffix)) = + TM2.stepAux next (ambient, fill slots bits buffer) + (Function.update tapes src suffix) := by + induction slots generalizing buffer tapes with + | nil => simp [readEncodedSlots, encodeBits, fill] + | cons i slots ih => + cases hb : bits i <;> + simpa only [readEncodedSlots, List.map_cons, encodeBits, encodeBit, hb, + Bool.false_eq_true, ite_false, ite_true, List.cons_append, + List.nil_append, TM2.stepAux, Function.update_self, List.head?_cons, + Option.getD_some, List.tail_cons, Function.update_idem, Bool.cond_false, + Bool.cond_true, fill, List.foldl_cons] using + ih (Function.update buffer i (bits i)) tapes + +theorem stepAux_readEncodedAll (src : K) + (next : TM2.Stmt (fun _ : K => Bool) Λ (σ × Buffer N)) + (state : σ × Buffer N) (bits : Buffer N) (tapes : K → List Bool) + (suffix : List Bool) (hinput : tapes src = encodeBits (List.ofFn bits) ++ suffix) : + TM2.stepAux (readEncodedSlots src (List.ofFn id) next) state tapes = + TM2.stepAux next (state.1, bits) (Function.update tapes src suffix) := by + have h := stepAux_readEncodedSlots src (List.ofFn id) next + state.1 bits state.2 tapes suffix + have hin : Function.update tapes src + (encodeBits ((List.ofFn id).map bits) ++ suffix) = tapes := by + simpa only [List.map_ofFn, Function.comp_id, ← hinput] using + Function.update_eq_self src tapes + rw [hin, fill_all] at h + exact h + +omit [DecidableEq K] in +theorem statementPushBound_readEncodedSlots (src : K) (slots : List (Fin N)) + (next : TM2.Stmt (fun _ : K => Bool) Λ (σ × Buffer N)) : + Runtime.statementPushBound (readEncodedSlots src slots next) = + Runtime.statementPushBound next := by + induction slots with + | nil => rfl + | cons i slots ih => simp [readEncodedSlots, Runtime.statementPushBound, ih] + +def writeEncodedSlots {M : Nat} (dst : K) (emit : σ → Buffer M) : List (Fin M) → + TM2.Stmt (fun _ : K => Bool) Λ σ → TM2.Stmt (fun _ : K => Bool) Λ σ + | [], next => next + | i :: slots, next => .push dst (fun _ => false) + (.branch (fun state => emit state i) + (.push dst (fun _ => true) (writeEncodedSlots dst emit slots next)) + (writeEncodedSlots dst emit slots next)) + +theorem stepAux_writeEncodedSlots {M : Nat} (dst : K) (emit : σ → Buffer M) + (slots : List (Fin M)) (next : TM2.Stmt (fun _ : K => Bool) Λ σ) + (state : σ) (tapes : K → List Bool) : + TM2.stepAux (writeEncodedSlots dst emit slots next) state tapes = + TM2.stepAux next state + (Function.update tapes dst + (encodeBits ((slots.map (emit state)).reverse) ++ tapes dst)) := by + induction slots generalizing tapes with + | nil => simp [writeEncodedSlots, encodeBits] + | cons i slots ih => + cases hb : emit state i <;> + simp only [writeEncodedSlots, TM2.stepAux, hb, Bool.cond_false, Bool.cond_true] + all_goals rw [ih] + all_goals simp [Function.update_idem, List.map_cons, List.reverse_cons, + encodeBits_append, encodeBits, encodeBit, hb, List.append_assoc] + +omit [DecidableEq K] in +theorem statementPushBound_writeEncodedSlots {M : Nat} + (dst : K) (emit : σ → Buffer M) (slots : List (Fin M)) + (next : TM2.Stmt (fun _ : K => Bool) Λ σ) : + Runtime.statementPushBound (writeEncodedSlots dst emit slots next) = + 2 * slots.length + Runtime.statementPushBound next := by + induction slots with + | nil => simp [writeEncodedSlots] + | cons i slots ih => + simp only [writeEncodedSlots, Runtime.statementPushBound, ih, List.length_cons] + omega + +end Chains + +section Block + +variable {K Λ σ : Type} {N M : Nat} + +def encodedBlockStmt (src dst : K) (F : Buffer N → Buffer M) + (next : TM2.Stmt (fun _ : K => Bool) Λ (σ × Buffer N)) : + TM2.Stmt (fun _ : K => Bool) Λ (σ × Buffer N) := + readEncodedSlots src (List.ofFn id) + (writeEncodedSlots dst (fun state => F state.2) (List.ofFn id).reverse + (.load (fun state => (state.1, emptyBuffer N)) next)) + +def encodedBlockAt (src dst : K) (F : Buffer N → Buffer M) (exit : Option Λ) : + TM2.Stmt (fun _ : K => Bool) Λ (σ × Buffer N) := + encodedBlockStmt src dst F (finishAt exit) + +theorem statementPushBound_encodedBlockAt (src dst : K) + (F : Buffer N → Buffer M) (exit : Option Λ) : + Runtime.statementPushBound (encodedBlockAt (σ := σ) src dst F exit) = 2 * M := by + cases exit <;> simp [encodedBlockAt, encodedBlockStmt, + statementPushBound_readEncodedSlots, statementPushBound_writeEncodedSlots, + finishAt, Runtime.statementPushBound] + +variable [DecidableEq K] + +theorem stepAux_encodedBlockStmt (src dst : K) (F : Buffer N → Buffer M) + (next : TM2.Stmt (fun _ : K => Bool) Λ (σ × Buffer N)) + (hne : src ≠ dst) (bits : Buffer N) (suffix : List Bool) + (state : σ × Buffer N) (tapes : K → List Bool) + (hinput : tapes src = encodeBits (List.ofFn bits) ++ suffix) : + TM2.stepAux (encodedBlockStmt src dst F next) state tapes = + TM2.stepAux next (state.1, emptyBuffer N) + (Function.update (Function.update tapes src suffix) dst + (encodeBits (List.ofFn (F bits)) ++ tapes dst)) := by + unfold encodedBlockStmt + rw [stepAux_readEncodedAll src _ state bits tapes suffix hinput, + stepAux_writeEncodedSlots] + simp only [List.map_reverse, List.map_ofFn, Function.comp_id, List.reverse_reverse, + Function.update_of_ne (Ne.symm hne), TM2.stepAux] + +theorem stepAux_encodedBlockAt (src dst : K) (F : Buffer N → Buffer M) + (exit : Option Λ) (hne : src ≠ dst) (bits : Buffer N) (suffix : List Bool) + (state : σ × Buffer N) (tapes : K → List Bool) + (hinput : tapes src = encodeBits (List.ofFn bits) ++ suffix) : + TM2.stepAux (encodedBlockAt src dst F exit) state tapes = + { l := exit, var := (state.1, emptyBuffer N), + stk := Function.update (Function.update tapes src suffix) dst + (encodeBits (List.ofFn (F bits)) ++ tapes dst) } := by + rw [encodedBlockAt, stepAux_encodedBlockStmt src dst F _ hne bits suffix state tapes hinput] + cases exit <;> rfl + +theorem step_encodedBlockAt (src dst : K) (F : Buffer N → Buffer M) + (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (σ × Buffer N)) + (label : Λ) (hprogram : program label = encodedBlockAt src dst F exit) + (hne : src ≠ dst) (bits : Buffer N) (suffix : List Bool) + (state : σ × Buffer N) (tapes : K → List Bool) + (hinput : tapes src = encodeBits (List.ofFn bits) ++ suffix) : + TM2.step program { l := some label, var := state, stk := tapes } = + some { l := exit + var := (state.1, emptyBuffer N) + stk := Function.update (Function.update tapes src suffix) dst + (encodeBits (List.ofFn (F bits)) ++ tapes dst) } := by + simp only [TM2.step, hprogram, + stepAux_encodedBlockAt src dst F exit hne bits suffix state tapes hinput] + +end Block + +def rowAt {K Λ σ : Type} {t S q : Nat} (src dst : K) + (labelAt : Fin q → Fin S → GraphTables.Label) (exit : Option Λ) : + TM2.Stmt (fun _ : K => Bool) Λ (σ × Buffer (inputSize t S)) := + encodedBlockAt src dst (rowBlock labelAt) exit + +def machine {t S q : Nat} (labelAt : Fin q → Fin S → GraphTables.Label) : FinTM2 where + K := Bool + k₀ := false + k₁ := true + Γ _ := Bool + Λ := Unit + main := () + σ := Unit × Buffer (inputSize t S) + initialState := ((), emptyBuffer (inputSize t S)) + m _ := rowAt false true labelAt none + +theorem machine_statementPushBound {t S q : Nat} + (labelAt : Fin q → Fin S → GraphTables.Label) : + Runtime.statementPushBound ((machine (t := t) labelAt).m ()) = 2 * (q * q) := + statementPushBound_encodedBlockAt false true (rowBlock labelAt) none + +def machineInTime {t S q : Nat} (labelAt : Fin q → Fin S → GraphTables.Label) + (bits : Buffer (inputSize t S)) (suffix : List Bool) + (register : Buffer (inputSize t S)) (tapes : Bool → List Bool) + (hinput : tapes false = encodeBits (List.ofFn bits) ++ suffix) : + StateTransition.EvalsToInTime (machine (t := t) labelAt).step + ⟨some (), ((), register), tapes⟩ + (some ⟨none, ((), emptyBuffer (inputSize t S)), + Function.update (Function.update tapes false suffix) true + (encodeBits (List.ofFn (rowBlock labelAt bits)) ++ tapes true)⟩) 1 where + steps := 1 + evals_in_steps := by + change TM2.step (fun _ : Unit => rowAt false true labelAt none) + { l := some (), var := ((), register), stk := tapes } = + some { l := none + var := ((), emptyBuffer (inputSize t S)) + stk := Function.update (Function.update tapes false suffix) true + (encodeBits (List.ofFn (rowBlock labelAt bits)) ++ tapes true) } + exact step_encodedBlockAt false true (rowBlock labelAt) (none : Option Unit) + (fun _ => rowAt false true labelAt none) () rfl (by decide) + bits suffix ((), register) tapes hinput + steps_le_m := le_rfl + +end MinUncutGames.Foundations.Complexity.PoweringMachineRow + +end +section +namespace MinUncutGames.Foundations.Complexity.PoweringMachineLoop + +open Turing + +inductive HeaderTape + | source | counter | vertices | darts + deriving DecidableEq + +protected abbrev HeaderTape.enumList : List HeaderTape := [.source, .counter, .vertices, .darts] + +protected theorem HeaderTape.enumList_getElem?_ctorIdx_eq (x : HeaderTape) : + HeaderTape.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem HeaderTape.enumList_nodup : HeaderTape.enumList.Nodup := by decide + +instance : Fintype HeaderTape where + elems := ⟨HeaderTape.enumList, HeaderTape.enumList_nodup⟩ + complete x := by cases x <;> decide + +inductive HeaderLabel + | initialize | scan + deriving DecidableEq + +protected abbrev HeaderLabel.enumList : List HeaderLabel := [.initialize, .scan] + +protected theorem HeaderLabel.enumList_getElem?_ctorIdx_eq (x : HeaderLabel) : + HeaderLabel.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem HeaderLabel.enumList_nodup : HeaderLabel.enumList.Nodup := by decide + +instance : Fintype HeaderLabel where + elems := ⟨HeaderLabel.enumList, HeaderLabel.enumList_nodup⟩ + complete x := by cases x <;> decide + +abbrev HeaderAlphabet (_ : HeaderTape) := Bool +abbrev HeaderState (σ : Type) := σ × Option Bool + +def pushTrue {K Λ σ : Type} (destination : K) : Nat → + TM2.Stmt (fun _ : K => Bool) Λ σ → TM2.Stmt (fun _ : K => Bool) Λ σ + | 0, next => next + | count + 1, next => pushTrue destination count (.push destination (fun _ => true) next) + +theorem stepAux_pushTrue {K Λ σ : Type} [DecidableEq K] + (destination : K) (count : Nat) (next : TM2.Stmt (fun _ : K => Bool) Λ σ) + (state : σ) (tapes : K → List Bool) : + TM2.stepAux (pushTrue destination count next) state tapes = + TM2.stepAux next state + (Function.update tapes destination (List.replicate count true ++ tapes destination)) := by + induction count generalizing next with + | zero => simp [pushTrue] + | succ count ih => + rw [pushTrue, ih] + simp [TM2.stepAux, List.replicate_succ, Function.update_idem] + +theorem pushTrue_pushBound {K Λ σ : Type} (destination : K) (count : Nat) + (next : TM2.Stmt (fun _ : K => Bool) Λ σ) : + Runtime.statementPushBound (pushTrue destination count next) = + count + Runtime.statementPushBound next := by + induction count generalizing next with + | zero => simp [pushTrue] + | succ count ih => simp only [pushTrue, ih, Runtime.statementPushBound]; omega + +def headerProgram {σ : Type} (B : Nat) : + HeaderLabel → TM2.Stmt HeaderAlphabet HeaderLabel (HeaderState σ) + | .initialize => + .push .counter (fun _ => false) + (.push .vertices (fun _ => false) + (.push .darts (fun _ => false) + (.load (fun state => (state.1, none)) (.goto fun _ => .scan)))) + | .scan => + .pop .source (fun state head => (state.1, head)) + (.branch (fun state => state.2.getD false) + (.push .counter (fun _ => true) + (.push .vertices (fun _ => true) + (pushTrue .darts B + (.load (fun state => (state.1, none)) (.goto fun _ => .scan))))) + (.load (fun state => (state.1, none)) .halt)) + +def headerMachine (B : Nat) : FinTM2 where + K := HeaderTape + k₀ := .source + k₁ := .darts + Γ := HeaderAlphabet + Λ := HeaderLabel + main := .initialize + σ := HeaderState Unit + initialState := ((), none) + m := headerProgram B + +def initialTapes (n : Nat) (suffix : List Bool) : HeaderTape → List Bool + | .source => encodeWord n ++ suffix + | _ => [] + +def scanTapes (B remaining processed : Nat) (suffix : List Bool) : HeaderTape → List Bool + | .source => encodeWord remaining ++ suffix + | .counter => encodeWord processed + | .vertices => encodeWord processed + | .darts => encodeWord (B * processed) + +def finalTapes (B n : Nat) (suffix : List Bool) : HeaderTape → List Bool + | .source => suffix + | .counter => encodeWord n + | .vertices => encodeWord n + | .darts => encodeWord (B * n) + +def scanConfiguration {σ : Type} (B remaining processed : Nat) + (suffix : List Bool) (ambient : σ) (register : Option Bool) : + TM2.Cfg HeaderAlphabet HeaderLabel (HeaderState σ) := + ⟨some .scan, (ambient, register), scanTapes B remaining processed suffix⟩ + +def finalConfiguration {σ : Type} (B n : Nat) (suffix : List Bool) (ambient : σ) : + TM2.Cfg HeaderAlphabet HeaderLabel (HeaderState σ) := + ⟨none, (ambient, none), finalTapes B n suffix⟩ + +theorem initializeStep {σ : Type} (B n : Nat) (suffix : List Bool) + (ambient : σ) (register : Option Bool) : + TM2.step (headerProgram B) + ⟨some .initialize, (ambient, register), initialTapes n suffix⟩ = + some (scanConfiguration B n 0 suffix ambient none) := by + simp only [TM2.step, headerProgram, TM2.stepAux] + congr 2 + funext tape + cases tape <;> simp [initialTapes, scanTapes, encodeWord] + +theorem scanStep_zero {σ : Type} (B processed : Nat) (suffix : List Bool) + (ambient : σ) (register : Option Bool) : + TM2.step (headerProgram B) (scanConfiguration B 0 processed suffix ambient register) = + some (finalConfiguration B processed suffix ambient) := by + simp only [TM2.step, scanConfiguration, headerProgram, TM2.stepAux, + scanTapes, encodeWord, List.replicate_zero, List.nil_append, List.singleton_append, + List.head?_cons, List.tail_cons, Option.getD_some, Bool.cond_false] + congr 2 + funext tape + cases tape <;> simp [finalTapes, scanTapes] + +theorem scanStep_succ {σ : Type} (B remaining processed : Nat) (suffix : List Bool) + (ambient : σ) (register : Option Bool) : + TM2.step (headerProgram B) + (scanConfiguration B (remaining + 1) processed suffix ambient register) = + some (scanConfiguration B remaining (processed + 1) suffix ambient none) := by + simp only [TM2.step, scanConfiguration, headerProgram, TM2.stepAux, + scanTapes, encodeWord, List.replicate_succ, List.cons_append, + List.head?_cons, List.tail_cons, Option.getD_some, Bool.cond_true] + rw [stepAux_pushTrue] + simp only [TM2.stepAux] + congr 2 + funext tape + cases tape <;> + simp [scanTapes, encodeWord, Nat.mul_add, List.replicate_add, + List.replicate_succ, List.append_assoc, Nat.add_comm, + -List.replicate_append_replicate] + +theorem scanTrace {σ : Type} (B remaining processed : Nat) (suffix : List Bool) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step (headerProgram B)))^[remaining + 1] + (some (scanConfiguration B remaining processed suffix ambient register)) = + some (finalConfiguration B (processed + remaining) suffix ambient) := by + induction remaining generalizing processed register with + | zero => + simpa only [Nat.add_zero, Nat.zero_add, Function.iterate_one, MachineComposition.advance_some] using + scanStep_zero B processed suffix ambient register + | succ remaining ih => + rw [Function.iterate_succ_apply] + change (MachineComposition.advance (TM2.step (headerProgram B)))^[remaining + 1] + (TM2.step (headerProgram B) + (scanConfiguration B (remaining + 1) processed suffix ambient register)) = _ + rw [scanStep_succ, ih] + simp only [Nat.add_comm, Nat.add_left_comm] + +theorem headerTrace {σ : Type} (B n : Nat) (suffix : List Bool) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step (headerProgram B)))^[n + 2] + (some ⟨some .initialize, (ambient, register), initialTapes n suffix⟩) = + some (finalConfiguration B n suffix ambient) := by + rw [show n + 2 = (n + 1) + 1 by omega, Function.iterate_succ_apply] + change (MachineComposition.advance (TM2.step (headerProgram B)))^[n + 1] + (TM2.step (headerProgram B) + ⟨some .initialize, (ambient, register), initialTapes n suffix⟩) = _ + rw [initializeStep] + simpa only [Nat.zero_add] using scanTrace B n 0 suffix ambient none + +def headerInTime {σ : Type} (B n : Nat) (suffix : List Bool) + (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step (headerProgram B)) + ⟨some .initialize, (ambient, register), initialTapes n suffix⟩ + (some (finalConfiguration B n suffix ambient)) (n + 2) where + steps := n + 2 + evals_in_steps := headerTrace B n suffix ambient register + steps_le_m := Nat.le_refl _ + +def remainingRows (rowBlock : Nat → List Bool) (n r : Nat) : List Bool := + (List.range' r (n - r)).flatMap rowBlock + +@[simp] theorem remainingRows_top (rowBlock : Nat → List Bool) (n : Nat) : + remainingRows rowBlock n n = [] := by simp [remainingRows] + +theorem remainingRows_step (rowBlock : Nat → List Bool) (n r : Nat) (hr : r < n) : + remainingRows rowBlock n r = rowBlock r ++ remainingRows rowBlock n (r + 1) := by + have h : n - r = (n - (r + 1)) + 1 := by omega + simp only [remainingRows, h, List.range'_succ, List.flatMap_cons] + +section Enumeration + +variable {K Λ σ : Type} [DecidableEq K] + +def rowBase (output : K) (base : K → List Bool) + (rowBlock : Nat → List Bool) (n r : Nat) : K → List Bool := + Function.update base output (remainingRows rowBlock n r ++ base output) + +def VertexBodyTraces (counter output : K) (guardLabel bodyLabel : Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (σ × Option Bool)) + (base : K → List Bool) (suffix : List Bool) (ambient : σ) + (rowBlock : Nat → List Bool) (cost : Nat → Nat) (n : Nat) : Prop := + ∀ r, r < n → ∀ accumulator : List Bool, + (MachineComposition.advance (TM2.step program))^[cost r] + (some ⟨some bodyLabel, (ambient, none), + MachineUnaryCounter.counterTapes counter + (Function.update base output accumulator) r suffix⟩) = + some ⟨some guardLabel, (ambient, none), + MachineUnaryCounter.counterTapes counter + (Function.update base output (rowBlock r ++ accumulator)) r suffix⟩ + +theorem vertexBodyTraces_to_counted (counter output : K) (guardLabel bodyLabel : Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (σ × Option Bool)) + (base : K → List Bool) (suffix : List Bool) (ambient : σ) + (rowBlock : Nat → List Bool) (cost : Nat → Nat) (n : Nat) + (bodies : VertexBodyTraces counter output guardLabel bodyLabel program + base suffix ambient rowBlock cost n) : + MachineCountedLoop.BodyTraces counter guardLabel bodyLabel program suffix + (fun _ => ambient) (fun _ => none) (rowBase output base rowBlock n) cost n := by + intro r hr + have h := bodies r hr (remainingRows rowBlock n (r + 1) ++ base output) + simpa only [MachineCountedLoop.bodyConfiguration, MachineCountedLoop.guardConfiguration, + rowBase, remainingRows_step rowBlock n r hr, List.append_assoc] using h + +def vertexLoopInTime (counter output : K) (guardLabel bodyLabel exitLabel : Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (σ × Option Bool)) + (atGuard : program guardLabel = MachineUnaryCounter.guard counter bodyLabel exitLabel) + (base : K → List Bool) (suffix : List Bool) (ambient : σ) + (rowBlock : Nat → List Bool) (cost : Nat → Nat) (n bodyBound : Nat) + (bodies : VertexBodyTraces counter output guardLabel bodyLabel program + base suffix ambient rowBlock cost n) + (bounded : ∀ r, r < n → cost r ≤ bodyBound) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some guardLabel, (ambient, none), + MachineUnaryCounter.counterTapes counter base n suffix⟩ + (some ⟨some exitLabel, (ambient, none), + MachineUnaryCounter.counterTapes counter + (rowBase output base rowBlock n 0) 0 suffix⟩) + (n * (bodyBound + 1) + 1) := by + have h := MachineCountedLoop.loopInTime counter guardLabel bodyLabel exitLabel + program atGuard suffix (fun _ => ambient) (fun _ => none) + (rowBase output base rowBlock n) cost n bodyBound + (vertexBodyTraces_to_counted counter output guardLabel bodyLabel program + base suffix ambient rowBlock cost n bodies) bounded + simpa [MachineCountedLoop.guardConfiguration, MachineCountedLoop.exitConfiguration, + rowBase] using h + +theorem vertexLoop_output (counter output : K) (different : output ≠ counter) + (base : K → List Bool) (suffix : List Bool) (rowBlock : Nat → List Bool) (n : Nat) : + MachineUnaryCounter.counterTapes counter (rowBase output base rowBlock n 0) 0 suffix output = + remainingRows rowBlock n 0 ++ base output := by + simp [MachineUnaryCounter.counterTapes, rowBase, different] + +def varyingRowBase (output : K) (base : Nat → K → List Bool) + (rowBlock : Nat → List Bool) (n r : Nat) : K → List Bool := + Function.update (base r) output (remainingRows rowBlock n r ++ base n output) + +def VaryingVertexBodyTraces (counter output : K) (guardLabel bodyLabel : Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (σ × Option Bool)) + (base : Nat → K → List Bool) (suffix : List Bool) (ambient : Nat → σ) + (rowBlock : Nat → List Bool) (cost : Nat → Nat) (n : Nat) : Prop := + ∀ r, r < n → ∀ accumulator : List Bool, + (MachineComposition.advance (TM2.step program))^[cost r] + (some ⟨some bodyLabel, (ambient (r + 1), none), + MachineUnaryCounter.counterTapes counter + (Function.update (base (r + 1)) output accumulator) r suffix⟩) = + some ⟨some guardLabel, (ambient r, none), + MachineUnaryCounter.counterTapes counter + (Function.update (base r) output (rowBlock r ++ accumulator)) r suffix⟩ + +theorem varyingVertexBodyTraces_to_counted (counter output : K) (guardLabel bodyLabel : Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (σ × Option Bool)) + (base : Nat → K → List Bool) (suffix : List Bool) (ambient : Nat → σ) + (rowBlock : Nat → List Bool) (cost : Nat → Nat) (n : Nat) + (bodies : VaryingVertexBodyTraces counter output guardLabel bodyLabel program + base suffix ambient rowBlock cost n) : + MachineCountedLoop.BodyTraces counter guardLabel bodyLabel program suffix + ambient (fun _ => none) (varyingRowBase output base rowBlock n) cost n := by + intro r hr + have h := bodies r hr (remainingRows rowBlock n (r + 1) ++ base n output) + simpa only [MachineCountedLoop.bodyConfiguration, MachineCountedLoop.guardConfiguration, + varyingRowBase, remainingRows_step rowBlock n r hr, List.append_assoc] using h + +def vertexLoopInTime_varying (counter output : K) (guardLabel bodyLabel exitLabel : Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (σ × Option Bool)) + (atGuard : program guardLabel = MachineUnaryCounter.guard counter bodyLabel exitLabel) + (base : Nat → K → List Bool) (suffix : List Bool) (ambient : Nat → σ) + (rowBlock : Nat → List Bool) (cost : Nat → Nat) (n bodyBound : Nat) + (bodies : VaryingVertexBodyTraces counter output guardLabel bodyLabel program + base suffix ambient rowBlock cost n) + (bounded : ∀ r, r < n → cost r ≤ bodyBound) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some guardLabel, (ambient n, none), + MachineUnaryCounter.counterTapes counter (base n) n suffix⟩ + (some ⟨some exitLabel, (ambient 0, none), + MachineUnaryCounter.counterTapes counter + (varyingRowBase output base rowBlock n 0) 0 suffix⟩) + (n * (bodyBound + 1) + 1) := by + have h := MachineCountedLoop.loopInTime counter guardLabel bodyLabel exitLabel + program atGuard suffix ambient (fun _ => none) + (varyingRowBase output base rowBlock n) cost n bodyBound + (varyingVertexBodyTraces_to_counted counter output guardLabel bodyLabel program + base suffix ambient rowBlock cost n bodies) bounded + simpa [MachineCountedLoop.guardConfiguration, MachineCountedLoop.exitConfiguration, + varyingRowBase] using h + +theorem vertexLoop_varying_output (counter output : K) (different : output ≠ counter) + (base : Nat → K → List Bool) (suffix : List Bool) + (rowBlock : Nat → List Bool) (n : Nat) : + MachineUnaryCounter.counterTapes counter + (varyingRowBase output base rowBlock n 0) 0 suffix output = + remainingRows rowBlock n 0 ++ base n output := by + simp [MachineUnaryCounter.counterTapes, varyingRowBase, different] + +end Enumeration + +end MinUncutGames.Foundations.Complexity.PoweringMachineLoop + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/PoweringMachineRowHeaders.lean b/lean/OAI/Computability/MinUncut/Machines/PoweringMachineRowHeaders.lean new file mode 100644 index 0000000000000000000000000000000000000000..b331c99edca3ee6b8c6b9bf1ab983b13268f1dbb --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/PoweringMachineRowHeaders.lean @@ -0,0 +1,629 @@ +import Mathlib +import OAI.Computability.MinUncut.Games.PoweringPlanBudget +import OAI.Computability.MinUncut.PCP.PoweringRowHeaderSemantics + +namespace OAI + +namespace MinUncutGames.Foundations.Complexity.PoweringMachineRowHeaders + +open Turing MachineComposition +open PCP PoweringRowHeaderSemantics +open PoweringMachineTapes + +variable {K Λ σ : Type} [DecidableEq K] +variable {vertices d max : Nat} + +def headerPlacement {t max : Nat} (h : t ≤ max) : PoweringMachineWord.Tape t → Tape max := + (Equiv.swap (leftEndpoint max) (rowOutput max)) ∘ wordPlacement h false + +theorem headerPlacement_injective {t max : Nat} (h : t ≤ max) : + Function.Injective (headerPlacement h) := + (Equiv.swap (leftEndpoint max) (rowOutput max)).injective.comp (wordPlacement_injective h false) + +@[simp] theorem headerPlacement_table {t max : Nat} (h : t ≤ max) : + headerPlacement h (.inl 0) = table max := by + simp [headerPlacement, table, leftEndpoint, rowOutput, Equiv.swap_apply_def] + +@[simp] theorem headerPlacement_query {t max : Nat} (h : t ≤ max) : + headerPlacement h (.inl 1) = query max := by + simp [headerPlacement, query, leftEndpoint, rowOutput, Equiv.swap_apply_def] + +@[simp] theorem headerPlacement_scan {t max : Nat} (h : t ≤ max) : + headerPlacement h (.inl 2) = scan max := by + simp [headerPlacement, scan, leftEndpoint, rowOutput, Equiv.swap_apply_def] + +@[simp] theorem headerPlacement_reverse {t max : Nat} (h : t ≤ max) : + headerPlacement h (.inl 3) = reverse max := by + simp [headerPlacement, reverse, leftEndpoint, rowOutput, Equiv.swap_apply_def] + +@[simp] theorem headerPlacement_scratch {t max : Nat} (h : t ≤ max) : + headerPlacement h (.inl 4) = scratch max := by + simp [headerPlacement, scratch, leftEndpoint, rowOutput, Equiv.swap_apply_def] + +@[simp] theorem headerPlacement_output {t max : Nat} (h : t ≤ max) : + headerPlacement h (.inl 5) = rowOutput max := by + simp [headerPlacement] + +@[simp] theorem headerPlacement_start {t max : Nat} (h : t ≤ max) : + headerPlacement h (.inr (PoweringMachineWord.first t)) = start max := by + simp [headerPlacement, start, leftEndpoint, rowOutput, Equiv.swap_apply_def] + +@[simp] theorem headerPlacement_succ {t max : Nat} (h : t ≤ max) (i : Fin t) : + headerPlacement h (.inr i.succ) = .inr (Fin.castLE h i) := by + simp [headerPlacement, leftEndpoint, rowOutput, Equiv.swap_apply_def] + +abbrev Label (n : Nat) := MachineUnaryAffineAt.Label ⊕ + (MachineUnaryAffineAt.Label ⊕ PoweringMachineWord.Label (n + 1)) + +def entry (n : Nat) : Label n := .inl .seed + +def tailEntry (n : Nat) (direction : Bool) : Label n := + if direction then .inr (.inr (PoweringMachineWord.entry (n + 1))) else .inr (.inl .seed) + +def affineInstruction (source work output : K) (coefficient offset : Nat) + (labels : MachineUnaryAffineAt.Label → Λ) (exit : Option Λ) : + MachineUnaryAffineAt.Label → TM2.Stmt (fun _ : K => Bool) Λ (σ × Option Bool) + | .seed => MachineUnaryAffineAt.seed output offset (labels .scan) + | .scan => MachineUnaryAffineAt.scan source work output coefficient (labels .scan) (labels .restore) + | .restore => Reduction.MachineTransfer.loopAt work source id false (labels .restore) exit + +def instruction (n : Nat) (h : n + 1 ≤ max) (placement : Tape max → K) + (ports : Fin (n + 1) → Fin d) (direction : Bool) + (labels : Label n → Λ) (exit : Option Λ) : + Label n → TM2.Stmt (fun _ : K => Bool) Λ (σ × Option Bool) + | .inl q => affineInstruction (placement (start max)) (placement (scratch max)) + (placement (rowOutput max)) (blockSize d n) (reverseOffset d n ports direction) + (fun z => labels (.inl z)) (some (labels (tailEntry n direction))) q + | .inr (.inl q) => PoweringMachineWord.copyInstruction + (placement (start max)) (placement (scratch max)) (placement (rowOutput max)) + (fun z => labels (.inr (.inl z))) exit q + | .inr (.inr q) => PoweringMachineWord.instruction (n + 1) + (placement ∘ headerPlacement h) ports (fun z => labels (.inr (.inr z))) exit q + +def afterReverse (n : Nat) (placement : Tape max → K) (vertex : Fin vertices) + (ports : Fin (n + 1) → Fin d) (direction : Bool) (base : K → List Bool) : K → List Bool := + Function.update base (placement (rowOutput max)) + (encodeWord (reverseValue d n vertex ports direction) ++ base (placement (rowOutput max))) + +def finalTapes (input : PortTables.Table vertices d) (n : Nat) (h : n + 1 ≤ max) + (placement : Tape max → K) (vertex : Fin vertices) (ports : Fin (n + 1) → Fin d) + (direction : Bool) (base : K → List Bool) : K → List Bool := + let mid := afterReverse n placement vertex ports direction base + if direction then + PoweringMachineWord.finalTapes input (n + 1) (placement ∘ headerPlacement h) vertex ports mid + else Function.update mid (placement (rowOutput max)) + (encodeWord vertex.val ++ mid (placement (rowOutput max))) + +def steps (input : PortTables.Table vertices d) (n : Nat) (vertex : Fin vertices) + (ports : Fin (n + 1) → Fin d) (direction : Bool) : Nat := + (2 * (vertex.val + 1) + 1) + + if direction then PoweringMachineWord.steps input (n + 1) vertex ports + else 2 * (vertex.val + 1) + 1 + +theorem headerTrace (input : PortTables.Table vertices d) (n : Nat) (h : n + 1 ≤ max) + (placement : Tape max → K) (distinct : Function.Injective placement) + (vertex : Fin vertices) (ports : Fin (n + 1) → Fin d) (direction : Bool) + (labels : Label n → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (σ × Option Bool)) + (atLabels : ∀ l, program (labels l) = instruction n h placement ports direction labels exit l) + (base : K → List Bool) (tableWord : base (placement (table max)) = PortTables.tableBits input) + (scratchEmpty : base (placement (scratch max)) = []) (suffix : List Bool) + (sourceWord : base (placement (start max)) = encodeWord vertex.val ++ suffix) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[steps input n vertex ports direction] + (some ⟨some (labels (entry n)), (ambient, register), base⟩) = + some ⟨exit, (ambient, none), finalTapes input n h placement vertex ports direction base⟩ ∧ + finalTapes input n h placement vertex ports direction base (placement (rowOutput max)) = + encodeWords (headerWords input n vertex ports direction) ++ base (placement (rowOutput max)) := by + have hd (i j : Tape max) (hne : i ≠ j) : placement i ≠ placement j := + fun eq => hne (distinct eq) + have hsourceOut : placement (start max) ≠ placement (rowOutput max) := + hd _ _ (by simp [start, rowOutput]) + have hscratchOut : placement (scratch max) ≠ placement (rowOutput max) := + hd _ _ (by simp [scratch, rowOutput]) + have htableOut : placement (table max) ≠ placement (rowOutput max) := + hd _ _ (by simp [table, rowOutput]) + let mid := afterReverse n placement vertex ports direction base + have hrev := MachineUnaryAffineAt.seededAffineTrace + (placement (start max)) (placement (scratch max)) (placement (rowOutput max)) + (hd _ _ (by simp [start, scratch])) hsourceOut hscratchOut + (blockSize d n) (reverseOffset d n ports direction) + (labels (.inl .seed)) (labels (.inl .scan)) (labels (.inl .restore)) + (some (labels (tailEntry n direction))) program + (atLabels (.inl .seed)) (atLabels (.inl .scan)) (atLabels (.inl .restore)) + base vertex.val suffix sourceWord scratchEmpty ambient register + have hreverseTrace : (advance (TM2.step program))^[2 * (vertex.val + 1) + 1] + (some ⟨some (labels (entry n)), (ambient, register), base⟩) = + some ⟨some (labels (tailEntry n direction)), (ambient, none), mid⟩ := by + simpa only [entry, mid, afterReverse, reverseValue] using hrev + have hmidSource : mid (placement (start max)) = encodeWord vertex.val ++ suffix := by + simpa only [mid, afterReverse, Function.update_of_ne hsourceOut] using sourceWord + have hmidScratch : mid (placement (scratch max)) = [] := by + simpa only [mid, afterReverse, Function.update_of_ne hscratchOut] using scratchEmpty + have hmidTable : mid (placement (table max)) = PortTables.tableBits input := by + simpa only [mid, afterReverse, Function.update_of_ne htableOut] using tableWord + cases direction with + | false => + have hcopy := MachineUnaryAffineAt.seededAffineTrace + (placement (start max)) (placement (scratch max)) (placement (rowOutput max)) + (hd _ _ (by simp [start, scratch])) hsourceOut hscratchOut 1 0 + (labels (.inr (.inl .seed))) (labels (.inr (.inl .scan))) + (labels (.inr (.inl .restore))) exit program + (atLabels (.inr (.inl .seed))) (atLabels (.inr (.inl .scan))) + (atLabels (.inr (.inl .restore))) mid vertex.val suffix hmidSource hmidScratch ambient none + constructor + · rw [steps, ite_eq_right Bool.false_ne_true, Function.iterate_add_apply, hreverseTrace] + simpa only [tailEntry, Bool.false_eq_true, ite_false, finalTapes, Nat.one_mul, + Nat.add_zero] using hcopy + · simp only [finalTapes, Bool.false_eq_true, ite_false, Function.update_self, + afterReverse, headerWords, tailVertex, encodeWords, List.append_nil, List.append_assoc] + | true => + have hword := PoweringMachineWord.wordTrace input (n + 1) + (placement ∘ headerPlacement h) (distinct.comp (headerPlacement_injective h)) vertex ports + (fun z => labels (.inr (.inr z))) exit program (fun z => atLabels (.inr (.inr z))) mid + (by simpa only [Function.comp_apply, headerPlacement_table] using hmidTable) + (by simpa only [Function.comp_apply, headerPlacement_scratch] using hmidScratch) + suffix (by simpa only [Function.comp_apply, headerPlacement_start] using hmidSource) ambient none + constructor + · rw [steps, ite_eq_left rfl, Nat.add_comm, Function.iterate_add_apply, hreverseTrace] + simpa only [tailEntry, ite_true, finalTapes] using hword.1 + · have hout := hword.2 + simp only [Function.comp_apply, headerPlacement_output] at hout + simpa only [finalTapes, ite_true, mid, afterReverse, Function.update_self, + headerWords, tailVertex, encodeWords, List.append_nil, List.append_assoc] using hout + +theorem finalTapes_other (input : PortTables.Table vertices d) (n : Nat) (h : n + 1 ≤ max) + (placement : Tape max → K) (vertex : Fin vertices) (ports : Fin (n + 1) → Fin d) + (direction : Bool) (base : K → List Bool) (k : K) + (hquery : k ≠ placement (query max)) (hscan : k ≠ placement (scan max)) + (hreverse : k ≠ placement (reverse max)) (houtput : k ≠ placement (rowOutput max)) + (hpositions : ∀ i : Fin (n + 1), k ≠ placement (.inr (Fin.castLE h i))) : + finalTapes input n h placement vertex ports direction base k = base k := by + cases direction with + | false => simp only [finalTapes, Bool.false_eq_true, ite_false, + Function.update_of_ne houtput, afterReverse] + | true => + let mid := afterReverse n placement vertex ports true base + have hw := PoweringMachineWord.finalTapes_other input (n + 1) + (placement ∘ headerPlacement h) vertex ports mid k + (by simpa only [Function.comp_apply, headerPlacement_query] using hquery) + (by simpa only [Function.comp_apply, headerPlacement_scan] using hscan) + (by simpa only [Function.comp_apply, headerPlacement_reverse] using hreverse) + (by simpa only [Function.comp_apply, headerPlacement_output] using houtput) + (fun i => by simpa only [Function.comp_apply, headerPlacement_succ] using hpositions i) + calc + _ = mid k := hw + _ = base k := by simp only [mid, afterReverse, Function.update_of_ne houtput] + +theorem finalTapes_shared (input : PortTables.Table vertices d) (n : Nat) (h : n + 1 ≤ max) + (placement : Tape max → K) (distinct : Function.Injective placement) + (vertex : Fin vertices) (ports : Fin (n + 1) → Fin d) + (direction : Bool) (base : K → List Bool) (i : Fin 11) + (hquery : i ≠ 2) (hscan : i ≠ 3) (hreverse : i ≠ 4) (houtput : i ≠ 10) : + finalTapes input n h placement vertex ports direction base (placement (.inl i)) = + base (placement (.inl i)) := by + apply finalTapes_other input n h placement vertex ports direction base + · intro heq; exact hquery (Sum.inl.inj (distinct heq)) + · intro heq; exact hscan (Sum.inl.inj (distinct heq)) + · intro heq; exact hreverse (Sum.inl.inj (distinct heq)) + · intro heq; exact houtput (Sum.inl.inj (distinct heq)) + · intro j heq; cases distinct heq + +theorem steps_le (input : PortTables.Table vertices d) (n : Nat) (vertex : Fin vertices) + (ports : Fin (n + 1) → Fin d) (direction : Bool) : + steps input n vertex ports direction ≤ + (14 * (n + 1) + 4) * (PortTables.tableBits input).length + 12 * (n + 1) + 6 := by + have hv : vertex.val ≤ (PortTables.tableBits input).length := + Nat.le_trans (Nat.le_of_lt vertex.isLt) (PortTables.vertices_le_tableBits_length input) + have hw := PoweringMachineWord.steps_le input (n + 1) vertex ports + cases direction <;> simp only [steps, Bool.false_eq_true, ite_false, ite_true] + · simp only [Nat.add_mul] + omega + · calc + _ ≤ (2 * (PortTables.tableBits input).length + 3) + + ((14 * (n + 1) + 2) * (PortTables.tableBits input).length + 12 * (n + 1) + 3) := + Nat.add_le_add (by omega) hw + _ = _ := by simp only [Nat.add_mul]; omega + +def machine (degree n : Nat) (ports : Fin (n + 1) → Fin degree) (direction : Bool) : FinTM2 where + K := PoweringMachineTapes.Tape (n + 1) + k₀ := table (n + 1) + k₁ := rowOutput (n + 1) + Γ _ := Bool + Λ := Label n + main := entry n + σ := (Unit × Bool × Option Bool) × Option Bool + initialState := (((), false, none), none) + m := instruction n (Nat.le_refl (n + 1)) id ports direction id none + +end MinUncutGames.Foundations.Complexity.PoweringMachineRowHeaders + +namespace MinUncutGames.Foundations.Complexity.PoweringMachineRowBody + +open Turing MachineComposition PCP +open MachineFixedBlockMap + +variable {K Λ : Type} [DecidableEq K] {vertices d : Nat} + +abbrev capacity (n : Nat) := 2 * (n + 1) +abbrev bufferSize (d n : Nat) := PoweringMachineRow.inputSize (n + 1) (PoweringRowData.slotCount d n) +abbrev State (d n : Nat) := PoweringMasterState.Master (bufferSize d n) + +def commands (n : Nat) (ports : Fin (n + 1) → Fin d) (direction : Bool) := + (PoweringMachinePlan.boundedRowPlan n ports direction).reverse + +abbrev Label (n : Nat) (ports : Fin (n + 1) → Fin d) (direction : Bool) := + PoweringMachinePlan.Label (commands n ports direction) ⊕ + (Unit ⊕ PoweringMachineRowHeaders.Label n) + +def planMain {max : Nat} {E : Type} + (ops : List (PoweringMachinePlan.Command d max)) (fallback : E) : + PoweringMachinePlan.Label ops ⊕ E := + match ops with + | [] => .inr fallback + | op :: _ => .inl (.inl (PoweringMachineField.entry op.val)) + +theorem plan_entry_eq {max : Nat} {E : Type} + (ops : List (PoweringMachinePlan.Command d max)) (fallback : E) + (labels : PoweringMachinePlan.Label ops ⊕ E → Λ) : + PoweringMachinePlan.entry ops (fun l => labels (.inl l)) + (some (labels (.inr fallback))) = some (labels (planMain ops fallback)) := by + cases ops <;> rfl + +def entry (n : Nat) (ports : Fin (n + 1) → Fin d) (direction : Bool) : Label n ports direction := + planMain (commands n ports direction) (.inl ()) + +def headerPlacement {max : Nat} (placement : PoweringMachineTapes.Tape max → K) + (output : K) (i : PoweringMachineTapes.Tape max) : K := + if i = .inl 10 then output else placement i + +omit [DecidableEq K] in +@[simp] theorem headerPlacement_output {max : Nat} + (placement : PoweringMachineTapes.Tape max → K) (output : K) : + headerPlacement placement output (.inl 10) = output := by simp [headerPlacement] + +omit [DecidableEq K] in +theorem headerPlacement_other {max : Nat} + (placement : PoweringMachineTapes.Tape max → K) (output : K) + (i : PoweringMachineTapes.Tape max) (hi : i ≠ .inl 10) : + headerPlacement placement output i = placement i := by simp [headerPlacement, hi] + +omit [DecidableEq K] in +theorem headerPlacement_injective {max : Nat} + (placement : PoweringMachineTapes.Tape max → K) (distinct : Function.Injective placement) + (output : K) (outside : ∀ i, output ≠ placement i) : + Function.Injective (headerPlacement placement output) := by + intro i j h + by_cases hi : i = .inl 10 + · subst i + by_cases hj : j = .inl 10 + · exact hj.symm + · exact False.elim (outside j (by simpa [headerPlacement, hj] using h)) + · by_cases hj : j = .inl 10 + · subst j + exact False.elim (outside i (by simpa [headerPlacement, hi] using h.symm)) + · exact distinct (by simpa [headerPlacement, hi, hj] using h) + +omit [DecidableEq K] in +theorem headerPlacement_excludes_data {max : Nat} + (placement : PoweringMachineTapes.Tape max → K) (distinct : Function.Injective placement) + (output : K) (outside : ∀ i, output ≠ placement i) : + ∀ i, placement (.inl 10) ≠ headerPlacement placement output i := by + intro i h + by_cases hi : i = .inl 10 + · subst i + exact outside _ (by simpa only [headerPlacement_output] using h.symm) + · have heq : (.inl 10 : PoweringMachineTapes.Tape max) = i := + distinct (by simpa [headerPlacement, hi] using h) + exact hi heq.symm + +def instruction (n : Nat) (placement : PoweringMachineTapes.Tape (capacity n) → K) + (output : K) (ports : Fin (n + 1) → Fin d) (direction : Bool) + (labels : Label n ports direction → Λ) (exit : Option Λ) : + Label n ports direction → TM2.Stmt (fun _ : K => Bool) Λ (State d n) + | .inl q => PoweringMachinePlan.instruction placement (commands n ports direction) + (fun z => labels (.inl z)) (some (labels (.inr (.inl ())))) q + | .inr (.inl _) => PoweringMasterState.rowAt (t := n + 1) (placement (.inl 10)) output + (PoweringRowData.fixedLabelAt d n) (some (labels (.inr (.inr (PoweringMachineRowHeaders.entry n))))) + | .inr (.inr q) => PoweringMachineRowHeaders.instruction n (by unfold capacity; omega) + (headerPlacement placement output) ports direction (fun z => labels (.inr (.inr z))) exit q + +def afterPlan (graph : PortTables.Table vertices d) (n : Nat) + (placement : PoweringMachineTapes.Tape (capacity n) → K) (vertex : Fin vertices) (ports : Fin (n + 1) → Fin d) (direction : Bool) (base : K → List Bool) : K → List Bool := + PoweringMachinePlan.finalTapes graph placement vertex (commands n ports direction) base + +def rowRelation (graph : PortTables.Table vertices d) (n : Nat) (vertex : Fin vertices) + (ports : Fin (n + 1) → Fin d) (direction : Bool) : List Bool := + encodeWords (GenericGraphTables.relationWords (PoweringTables.table graph n).rows[ + PoweringEnumeration.encodeDart vertices d n (direction, vertex, ports)].relation) + +def rowWords (graph : PortTables.Table vertices d) (n : Nat) (vertex : Fin vertices) + (ports : Fin (n + 1) → Fin d) (direction : Bool) : List Nat := + GenericGraphTables.rowWords (PoweringTables.table graph n).rows[ + PoweringEnumeration.encodeDart vertices d n (direction, vertex, ports)] + +def afterEmit (graph : PortTables.Table vertices d) (n : Nat) + (placement : PoweringMachineTapes.Tape (capacity n) → K) (output : K) (vertex : Fin vertices) + (ports : Fin (n + 1) → Fin d) (direction : Bool) (base : K → List Bool) : K → List Bool := + let mid := afterPlan graph n placement vertex ports direction base + Function.update (Function.update mid (placement (.inl 10)) []) output + (rowRelation graph n vertex ports direction ++ mid output) + +def finalTapes (graph : PortTables.Table vertices d) + (n : Nat) (placement : PoweringMachineTapes.Tape (capacity n) → K) (output : K) + (vertex : Fin vertices) (ports : Fin (n + 1) → Fin d) (direction : Bool) + (base : K → List Bool) : K → List Bool := + PoweringMachineRowHeaders.finalTapes graph n (by unfold capacity; omega) + (headerPlacement placement output) vertex ports direction + (afterEmit graph n placement output vertex ports direction base) + +def planSteps {max : Nat} (graph : PortTables.Table vertices d) (vertex : Fin vertices) : + List (PoweringMachinePlan.Command d max) → Nat + | [] => 0 + | op :: ops => PoweringMachineField.steps graph vertex op.val + planSteps graph vertex ops + +theorem planSteps_eq {max : Nat} (graph : PortTables.Table vertices d) + (placement : PoweringMachineTapes.Tape max → K) (vertex : Fin vertices) + (ops : List (PoweringMachinePlan.Command d max)) (base : K → List Bool) : + PoweringMachinePlan.steps graph placement vertex ops base = planSteps graph vertex ops := by + induction ops generalizing base with + | nil => rfl + | cons op ops ih => + change PoweringMachineField.steps graph vertex op.val + + PoweringMachinePlan.steps graph placement vertex ops + (PoweringMachinePlan.result graph placement vertex op base) = _ + rw [ih] + rfl + +def steps (graph : PortTables.Table vertices d) (vertex : Fin vertices) + (n : Nat) (ports : Fin (n + 1) → Fin d) (direction : Bool) : Nat := + planSteps graph vertex (commands n ports direction) + 1 + + PoweringMachineRowHeaders.steps graph n vertex ports direction + +def Ready (graph : PortTables.Table vertices d) (n : Nat) + (placement : PoweringMachineTapes.Tape (capacity n) → K) (vertex : Fin vertices) + (suffix : List Bool) (base : K → List Bool) : Prop := + PoweringMachineField.Ready graph placement vertex suffix base ∧ base (placement (.inl 10)) = [] + +private theorem plan_other {max : Nat} (graph : PortTables.Table vertices d) + (placement : PoweringMachineTapes.Tape max → K) (vertex : Fin vertices) + (ops : List (PoweringMachinePlan.Command d max)) (base : K → List Bool) + (k : K) (outside : ∀ i, k ≠ placement i) : + PoweringMachinePlan.finalTapes graph placement vertex ops base k = base k := by + induction ops generalizing base with + | nil => rfl + | cons op ops ih => + change PoweringMachinePlan.finalTapes graph placement vertex ops + (PoweringMachinePlan.result graph placement vertex op base) k = _ + rw [ih] + exact PoweringMachineField.finalTapes_other graph placement vertex op.val op.property base k outside + +theorem afterEmit_data (graph : PortTables.Table vertices d) (n : Nat) + (placement : PoweringMachineTapes.Tape (capacity n) → K) (output : K) + (outside : ∀ i, output ≠ placement i) (vertex : Fin vertices) + (ports : Fin (n + 1) → Fin d) (direction : Bool) (base : K → List Bool) : + afterEmit graph n placement output vertex ports direction base (placement (.inl 10)) = [] := by + simp only [afterEmit, Function.update_of_ne (Ne.symm (outside _)), Function.update_self] + +theorem afterEmit_role (graph : PortTables.Table vertices d) (n : Nat) + (placement : PoweringMachineTapes.Tape (capacity n) → K) (distinct : Function.Injective placement) + (output : K) (outside : ∀ i, output ≠ placement i) (vertex : Fin vertices) + (ports : Fin (n + 1) → Fin d) (direction : Bool) (base : K → List Bool) + (j : Fin 11) (hj : j ≠ 10) : + afterEmit graph n placement output vertex ports direction base (placement (.inl j)) = + afterPlan graph n placement vertex ports direction base (placement (.inl j)) := by + have hdata : placement (.inl j) ≠ placement (.inl 10) := fun h => hj (Sum.inl.inj (distinct h)) + simp only [afterEmit, Function.update_of_ne (Ne.symm (outside _)), Function.update_of_ne hdata] + +theorem afterEmit_ready (graph : PortTables.Table vertices d) (n : Nat) + (placement : PoweringMachineTapes.Tape (capacity n) → K) (distinct : Function.Injective placement) + (output : K) (outside : ∀ i, output ≠ placement i) (vertex : Fin vertices) + (ports : Fin (n + 1) → Fin d) (direction : Bool) (base : K → List Bool) + (suffix : List Bool) (ready : Ready graph n placement vertex suffix base) : + Ready graph n placement vertex suffix (afterEmit graph n placement output vertex ports direction base) := by + have hp := PoweringMachinePlan.ready_finalTapes graph placement distinct vertex + (commands n ports direction) base suffix ready.1 + constructor + · constructor + · rw [afterEmit_role graph n placement distinct output outside vertex ports direction base 0 (by decide)] + exact hp.table + · rw [afterEmit_role graph n placement distinct output outside vertex ports direction base 1 (by decide)] + exact hp.source + · rw [afterEmit_role graph n placement distinct output outside vertex ports direction base 5 (by decide)] + exact hp.scratch + · rw [afterEmit_role graph n placement distinct output outside vertex ports direction base 8 (by decide)] + exact hp.leftCopy + · rw [afterEmit_role graph n placement distinct output outside vertex ports direction base 9 (by decide)] + exact hp.rightCopy + · exact afterEmit_data graph n placement output outside vertex ports direction base + +theorem finalTapes_data (graph : PortTables.Table vertices d) (n : Nat) + (placement : PoweringMachineTapes.Tape (capacity n) → K) (distinct : Function.Injective placement) + (output : K) (outside : ∀ i, output ≠ placement i) (vertex : Fin vertices) + (ports : Fin (n + 1) → Fin d) (direction : Bool) (base : K → List Bool) : + finalTapes graph n placement output vertex ports direction base (placement (.inl 10)) = [] := by + have hother := headerPlacement_excludes_data placement distinct output outside + calc + finalTapes graph n placement output vertex ports direction base (placement (.inl 10)) = + afterEmit graph n placement output vertex ports direction base (placement (.inl 10)) := + PoweringMachineRowHeaders.finalTapes_other _ _ _ _ _ _ _ _ _ + (hother _) (hother _) (hother _) (hother _) (fun i => hother _) + _ = [] := afterEmit_data graph n placement output outside vertex ports direction base + +theorem finalTapes_ready (graph : PortTables.Table vertices d) (n : Nat) + (placement : PoweringMachineTapes.Tape (capacity n) → K) (distinct : Function.Injective placement) + (output : K) (outside : ∀ i, output ≠ placement i) (vertex : Fin vertices) + (ports : Fin (n + 1) → Fin d) (direction : Bool) (base : K → List Bool) + (suffix : List Bool) (ready : Ready graph n placement vertex suffix base) : + Ready graph n placement vertex suffix (finalTapes graph n placement output vertex ports direction base) := by + have hm := afterEmit_ready graph n placement distinct output outside vertex ports direction base suffix ready + have hrole (j : Fin 11) (h₂ : j ≠ 2) (h₃ : j ≠ 3) (h₄ : j ≠ 4) (h₁₀ : j ≠ 10) : + finalTapes graph n placement output vertex ports direction base (placement (.inl j)) = + afterEmit graph n placement output vertex ports direction base (placement (.inl j)) := by + have h := PoweringMachineRowHeaders.finalTapes_shared graph n (by unfold capacity; omega) + (headerPlacement placement output) (headerPlacement_injective placement distinct output outside) + vertex ports direction (afterEmit graph n placement output vertex ports direction base) j h₂ h₃ h₄ h₁₀ + dsimp only [finalTapes] + simpa only [headerPlacement, ite_eq_right (show (Sum.inl j : PoweringMachineTapes.Tape (capacity n)) ≠ .inl 10 from + fun heq => h₁₀ (Sum.inl.inj heq))] using h + constructor + · constructor + · rw [hrole 0 (by decide) (by decide) (by decide) (by decide)]; exact hm.1.table + · rw [hrole 1 (by decide) (by decide) (by decide) (by decide)]; exact hm.1.source + · rw [hrole 5 (by decide) (by decide) (by decide) (by decide)]; exact hm.1.scratch + · rw [hrole 8 (by decide) (by decide) (by decide) (by decide)]; exact hm.1.leftCopy + · rw [hrole 9 (by decide) (by decide) (by decide) (by decide)]; exact hm.1.rightCopy + · exact finalTapes_data graph n placement distinct output outside vertex ports direction base + +theorem finalTapes_other (graph : PortTables.Table vertices d) (n : Nat) + (placement : PoweringMachineTapes.Tape (capacity n) → K) (output : K) + (vertex : Fin vertices) (ports : Fin (n + 1) → Fin d) (direction : Bool) + (base : K → List Bool) (k : K) (hout : k ≠ output) (outside : ∀ i, k ≠ placement i) : + finalTapes graph n placement output vertex ports direction base k = base k := by + have hh : ∀ i, k ≠ headerPlacement placement output i := by + intro i + by_cases hi : i = .inl 10 + · simpa [headerPlacement, hi] using hout + · simpa [headerPlacement, hi] using outside i + calc + finalTapes graph n placement output vertex ports direction base k = + afterEmit graph n placement output vertex ports direction base k := + PoweringMachineRowHeaders.finalTapes_other _ _ _ _ _ _ _ _ _ + (hh _) (hh _) (hh _) (hh _) (fun i => hh _) + _ = afterPlan graph n placement vertex ports direction base k := by + simp only [afterEmit, Function.update_of_ne hout, Function.update_of_ne (outside _)] + _ = base k := plan_other graph placement vertex _ base k outside + +theorem rowBlock_eq_rowRelation (graph : PortTables.Table vertices d) (n : Nat) + (vertex : Fin vertices) (ports : Fin (n + 1) → Fin d) (direction : Bool) : + PoweringMachineRow.encodeBits (List.ofFn (PoweringMachineRow.rowBlock + (PoweringRowData.fixedLabelAt d n) (PoweringRowData.rowBits graph n (direction, vertex, ports)))) = + rowRelation graph n vertex ports direction := by + calc + _ = encodeWords (GenericGraphTables.relationWords + (PoweringRowData.emittedRelation graph n (direction, vertex, ports))) := + PoweringRowData.rowBlock_unary graph n (direction, vertex, ports) + _ = _ := by + have h := PoweringRowData.emittedRelation_table graph n + (PoweringEnumeration.encodeDart vertices d n (direction, vertex, ports)) + rw [PoweringEnumeration.decodeDart_encodeDart] at h + exact congrArg (fun relation : GenericGraphTables.RelationTable (PoweringTables.labelCount d n) => + encodeWords (GenericGraphTables.relationWords relation)) h + +theorem finalTapes_output (graph : PortTables.Table vertices d) (n : Nat) + (placement : PoweringMachineTapes.Tape (capacity n) → K) (distinct : Function.Injective placement) + (output : K) (outside : ∀ i, output ≠ placement i) (vertex : Fin vertices) + (ports : Fin (n + 1) → Fin d) (direction : Bool) (base : K → List Bool) + (suffix : List Bool) (ready : Ready graph n placement vertex suffix base) : + finalTapes graph n placement output vertex ports direction base output = + encodeWords (rowWords graph n vertex ports direction) ++ base output := by + have hm := afterEmit_ready graph n placement distinct output outside vertex ports direction base suffix ready + have hh := (PoweringMachineRowHeaders.headerTrace graph n (by unfold capacity; omega) + (headerPlacement placement output) (headerPlacement_injective placement distinct output outside) + vertex ports direction id none + (PoweringMachineRowHeaders.instruction n (by unfold capacity; omega) + (headerPlacement placement output) ports direction id none) (fun _ => rfl) + (afterEmit graph n placement output vertex ports direction base) + (by simpa [headerPlacement, PoweringMachineTapes.table] using hm.1.table) + (by simpa [headerPlacement, PoweringMachineTapes.scratch] using hm.1.scratch) suffix + (by simpa [headerPlacement, PoweringMachineTapes.start] using hm.1.source) () none).2 + simp only [PoweringMachineTapes.rowOutput, headerPlacement_output] at hh + calc + finalTapes graph n placement output vertex ports direction base output = + encodeWords (PoweringRowHeaderSemantics.headerWords graph n vertex ports direction) ++ + afterEmit graph n placement output vertex ports direction base output := hh + _ = encodeWords (PoweringRowHeaderSemantics.headerWords graph n vertex ports direction) ++ + (rowRelation graph n vertex ports direction ++ base output) := by + simp only [afterEmit, Function.update_self] + rw [show afterPlan graph n placement vertex ports direction base output = base output from + plan_other graph placement vertex _ base output outside] + _ = _ := PoweringRowHeaderSemantics.header_relation_bits graph n vertex ports direction (base output) + +theorem rowTrace (graph : PortTables.Table vertices d) (n : Nat) + (placement : PoweringMachineTapes.Tape (capacity n) → K) (distinct : Function.Injective placement) + (output : K) (outside : ∀ i, output ≠ placement i) (vertex : Fin vertices) + (ports : Fin (n + 1) → Fin d) (direction : Bool) + (labels : Label n ports direction → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State d n)) + (atLabels : ∀ l, program (labels l) = instruction n placement output ports direction labels exit l) + (base : K → List Bool) (suffix : List Bool) (ready : Ready graph n placement vertex suffix base) : + (advance (TM2.step program))^[steps graph vertex n ports direction] + (some ⟨some (labels (entry n ports direction)), PoweringMasterState.clean (bufferSize d n), base⟩) = + some ⟨exit, PoweringMasterState.clean (bufferSize d n), + finalTapes graph n placement output vertex ports direction base⟩ := by + have hp := PoweringMachinePlan.planTrace graph placement distinct vertex (commands n ports direction) + (fun q => labels (.inl q)) (some (labels (.inr (.inl ())))) program + (fun q => atLabels (.inl q)) base suffix ready.1 (emptyBuffer (bufferSize d n)) + rw [planSteps_eq, plan_entry_eq] at hp + let mid := afterPlan graph n placement vertex ports direction base + have hinput : mid (placement (.inl 10)) = PoweringMachineRow.encodeBits + (List.ofFn (PoweringRowData.rowBits graph n (direction, vertex, ports))) ++ [] := by + dsimp only [mid, afterPlan, commands] + have h := PoweringMachinePlan.rowPlan_output graph n ports direction placement distinct vertex base suffix ready.1 + simpa only [ready.2, List.append_nil, PoweringRowData.dataTape_eq] using h + have hr := PoweringMasterState.step_rowAt_clean (t := n + 1) (placement (.inl 10)) output + (PoweringRowData.fixedLabelAt d n) + (some (labels (.inr (.inr (PoweringMachineRowHeaders.entry n))))) program (labels (.inr (.inl ()))) + (atLabels (.inr (.inl ()))) (Ne.symm (outside _)) + (PoweringRowData.rowBits graph n (direction, vertex, ports)) + (emptyBuffer (bufferSize d n)) [] mid hinput + rw [rowBlock_eq_rowRelation] at hr + have hm := afterEmit_ready graph n placement distinct output outside vertex ports direction base suffix ready + have hh := (PoweringMachineRowHeaders.headerTrace graph n (by unfold capacity; omega) + (headerPlacement placement output) (headerPlacement_injective placement distinct output outside) + vertex ports direction (fun q => labels (.inr (.inr q))) exit program + (fun q => atLabels (.inr (.inr q))) + (afterEmit graph n placement output vertex ports direction base) + (by simpa [headerPlacement, PoweringMachineTapes.table] using hm.1.table) + (by simpa [headerPlacement, PoweringMachineTapes.scratch] using hm.1.scratch) suffix + (by simpa [headerPlacement, PoweringMachineTapes.start] using hm.1.source) + (emptyBuffer (bufferSize d n), false, none) none).1 + rw [steps, Nat.add_comm, Function.iterate_add_apply, Function.iterate_succ_apply'] + change (advance (TM2.step program))^[PoweringMachineRowHeaders.steps graph n vertex ports direction] + (advance (TM2.step program) ((advance (TM2.step program))^[planSteps graph vertex (commands n ports direction)] + (some ⟨some (labels (planMain (commands n ports direction) (.inl ()))), + MachineUnaryEqualityBit.clean (emptyBuffer (bufferSize d n)), base⟩))) = _ + rw [hp] + simp only [advance_some] + change (advance (TM2.step program))^[PoweringMachineRowHeaders.steps graph n vertex ports direction] + (TM2.step program ⟨some (labels (.inr (.inl ()))), + PoweringMasterState.withBuffer (emptyBuffer (bufferSize d n)), mid⟩) = _ + rw [hr] + exact hh + +def budget (d n inputLength : Nat) : Nat := + PoweringPlanBudget.rowBudget d n inputLength + 1 + + ((14 * (n + 1) + 4) * inputLength + 12 * (n + 1) + 6) + +theorem steps_le (graph : PortTables.Table vertices d) (vertex : Fin vertices) + (n : Nat) (ports : Fin (n + 1) → Fin d) (direction : Bool) : + steps graph vertex n ports direction ≤ budget d n (PortTables.tableBits graph).length := by + have hp := PoweringPlanBudget.rowPlan_steps_le graph n ports direction id vertex (fun _ => []) + rw [planSteps_eq] at hp + have hh := PoweringMachineRowHeaders.steps_le graph n vertex ports direction + change planSteps graph vertex (commands n ports direction) ≤ + PoweringPlanBudget.rowBudget d n (PortTables.tableBits graph).length at hp + unfold steps budget + omega + +def rowInTime (graph : PortTables.Table vertices d) (n : Nat) + (placement : PoweringMachineTapes.Tape (capacity n) → K) (distinct : Function.Injective placement) + (output : K) (outside : ∀ i, output ≠ placement i) (vertex : Fin vertices) + (ports : Fin (n + 1) → Fin d) (direction : Bool) + (labels : Label n ports direction → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State d n)) + (atLabels : ∀ l, program (labels l) = instruction n placement output ports direction labels exit l) + (base : K → List Bool) (suffix : List Bool) (ready : Ready graph n placement vertex suffix base) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels (entry n ports direction)), PoweringMasterState.clean (bufferSize d n), base⟩ + (some ⟨exit, PoweringMasterState.clean (bufferSize d n), + finalTapes graph n placement output vertex ports direction base⟩) + (budget d n (PortTables.tableBits graph).length) where + steps := steps graph vertex n ports direction + evals_in_steps := rowTrace graph n placement distinct output outside vertex ports direction + labels exit program atLabels base suffix ready + steps_le_m := steps_le graph vertex n ports direction + +end MinUncutGames.Foundations.Complexity.PoweringMachineRowBody + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/PoweringMachineRuntime.lean b/lean/OAI/Computability/MinUncut/Machines/PoweringMachineRuntime.lean new file mode 100644 index 0000000000000000000000000000000000000000..5b20752e7ec59ba0179b1fb26e36ebe724c2bd16 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/PoweringMachineRuntime.lean @@ -0,0 +1,190 @@ +import Mathlib +import OAI.Computability.MinUncut.Games.PoweringInitializeFrame +import OAI.Computability.MinUncut.Machines.PoweringRuntimeBudget +import OAI.Computability.MinUncut.Games.PoweringPolynomialBudget + +namespace OAI + +section +namespace MinUncutGames.Foundations.Complexity.PoweringMachineRuntime + +open Turing MachineComposition PCP PoweringMachineGlobal + + +variable {vertices d : Nat} + +def beforeFinish (graph : PortTables.Table vertices d) (n : Nat) : Tape n → List Bool := + PoweringMachineOuterLoop.finalTapes graph n (placement n) (outputTape n) + vertices (Nat.le_refl _) (PoweringInitializeFrame.preparedTapes graph n) + +def finishConfiguration (graph : PortTables.Table vertices d) (n : Nat) : (machine d n).Cfg := + ⟨some (finishEntry d n), PoweringMasterState.clean (PoweringMachineRowBody.bufferSize d n), + beforeFinish graph n⟩ + +def beforeFinishBudget (graph : PortTables.Table vertices d) (n : Nat) : Nat := + (3 * vertices + 5) + (vertices * + (PoweringMachineVertex.budget d n (PortTables.tableBits graph).length + 2) + 1) + +theorem beforeFinish_ready (graph : PortTables.Table vertices d) (n : Nat) : + PoweringMachineOuterLoop.Ready graph n (placement n) (beforeFinish graph n) := + PoweringMachineOuterLoop.finalTapes_ready graph n (placement n) + (PoweringMachineInitialize.commonPlacement_injective _) + (outputTape n) (fun i => Ne.symm (PoweringMachineInitialize.commonPlacement_ne_finalOutput _ i)) + vertices (Nat.le_refl _) (PoweringInitializeFrame.preparedTapes graph n) + (PoweringInitializeFrame.prepared_ready graph n) + +theorem beforeFinish_output (graph : PortTables.Table vertices d) (n : Nat) : + beforeFinish graph n (outputTape n) = + (List.finRange vertices).flatMap (PoweringTableLayout.vertexRowBits graph n) := by + rw [beforeFinish, PoweringMachineOuterLoop.finalTapes_output graph n (placement n) + (PoweringMachineInitialize.commonPlacement_injective _) (outputTape n) + (fun i => Ne.symm (PoweringMachineInitialize.commonPlacement_ne_finalOutput _ i)) + vertices (Nat.le_refl _) (PoweringInitializeFrame.preparedTapes graph n) + (PoweringInitializeFrame.prepared_ready graph n), + PoweringMachineOuterLoop.prefixRows_all, PoweringInitializeFrame.prepared_output, + List.append_nil] + +theorem beforeFinish_vertices (graph : PortTables.Table vertices d) (n : Nat) : + beforeFinish graph n (headerVertices n) = encodeWord vertices := by + rw [beforeFinish, PoweringMachineOuterLoop.finalTapes_other graph n (placement n) + (outputTape n) vertices (Nat.le_refl _) (PoweringInitializeFrame.preparedTapes graph n) + (headerVertices n) (PoweringGlobalConfiguration.headerVertices_ne_output n) + (fun i => Ne.symm (PoweringMachineInitialize.commonPlacement_ne_header _ i .vertices (by decide)))] + exact PoweringInitializeFrame.prepared_vertices graph n + +theorem beforeFinish_darts (graph : PortTables.Table vertices d) (n : Nat) : + beforeFinish graph n (headerDarts n) = + encodeWord (PoweringTableLayout.blockSize d n * vertices) := by + rw [beforeFinish, PoweringMachineOuterLoop.finalTapes_other graph n (placement n) + (outputTape n) vertices (Nat.le_refl _) (PoweringInitializeFrame.preparedTapes graph n) + (headerDarts n) (PoweringGlobalConfiguration.headerDarts_ne_output n) + (fun i => Ne.symm (PoweringMachineInitialize.commonPlacement_ne_header _ i .darts (by decide)))] + exact PoweringInitializeFrame.prepared_darts graph n + +theorem serialized_eq (graph : PortTables.Table vertices d) (n : Nat) : + encodeWords [vertices, PoweringTableLayout.blockSize d n * vertices] ++ + beforeFinish graph n (outputTape n) = PoweringTables.outputBits graph n := by + rw [beforeFinish_output, PoweringTableLayout.outputBits_vertexRows] + congr 2 + rw [PoweringTableLayout.dartCount_eq_vertex_blocks, Nat.mul_comm] + +def beforeFinishExecution (graph : PortTables.Table vertices d) (n : Nat) : + StateTransition.EvalsToInTime (machine d n).step + (initList (machine d n) (PortTables.tableBits graph)) + (some (finishConfiguration graph n)) (beforeFinishBudget graph n) := by + have initialRun := PoweringInitializeFrame.initializeInTime graph n + have loop := PoweringMachineOuterLoop.loopInTime graph n (placement n) + (PoweringMachineInitialize.commonPlacement_injective _) (outputTape n) + (fun i => Ne.symm (PoweringMachineInitialize.commonPlacement_ne_finalOutput _ i)) + (guardLabel d n) (bridgeLabel d n) (finishEntry d n) (vertexLabels d n) + (program d n) (atGuard d n) (atBridge d n) (atVertex d n) + vertices (Nat.le_refl _) (PoweringInitializeFrame.preparedTapes graph n) + (PoweringInitializeFrame.prepared_ready graph n) + rw [PoweringInitializeFrame.prepared_counter] at loop + simpa only [beforeFinishBudget, Nat.add_comm] using + (StateTransition.EvalsToInTime.trans (machine d n).step + (3 * vertices + 5) + (vertices * (PoweringMachineVertex.budget d n (PortTables.tableBits graph).length + 2) + 1) + (initList (machine d n) (PortTables.tableBits graph)) + (PoweringInitializeFrame.preparedCfg graph n) (some (finishConfiguration graph n)) + initialRun loop) + +def finishSteps (graph : PortTables.Table vertices d) (n : Nat) : Nat := + PoweringMachineFinish.steps (enumeration n) (outputTape n) (beforeFinish graph n) + vertices (PoweringTableLayout.blockSize d n * vertices) + +def finishExecution (graph : PortTables.Table vertices d) (n : Nat) : + StateTransition.EvalsToInTime (machine d n).step (finishConfiguration graph n) + (some (haltList (machine d n) (PoweringTables.outputBits graph n))) + (finishSteps graph n) := by + have run := PoweringMachineFinish.traceAt (enumeration n) + (headerVertices n) (headerDarts n) (outputTape n) + (placement n (PoweringMachineTapes.scratch (PoweringMachineRowBody.capacity n))) + (PoweringGlobalConfiguration.headerVertices_ne_scratch n) + (PoweringGlobalConfiguration.headerVertices_ne_output n) + (PoweringGlobalConfiguration.headerDarts_ne_scratch n) + (PoweringGlobalConfiguration.headerDarts_ne_output n) + (PoweringMachineInitialize.commonPlacement_ne_finalOutput _ _) + (finishLabels d n) (program d n) (atFinish d n) + (beforeFinish graph n) vertices (PoweringTableLayout.blockSize d n * vertices) [] [] + (by simpa only [List.append_nil] using beforeFinish_vertices graph n) + (by simpa only [List.append_nil] using beforeFinish_darts graph n) + (beforeFinish_ready graph n).scratch + (PoweringMasterState.clean (PoweringMachineRowBody.bufferSize d n)).1 none + rw [serialized_eq] at run + refine { steps := finishSteps graph n, evals_in_steps := ?_, steps_le_m := Nat.le_refl _ } + change (advance (TM2.step (program d n)))^[finishSteps graph n] + (some (finishConfiguration graph n)) = _ + rw [PoweringGlobalConfiguration.haltList_eq] + simpa only [finishConfiguration, finishEntry, finishSteps, PoweringMasterState.clean, + PoweringMasterState.withBuffer] using! run + +def execution (graph : PortTables.Table vertices d) (n : Nat) : + TM2OutputsInTime (machine d n) (PortTables.tableBits graph) + (some (PoweringTables.outputBits graph n)) + (beforeFinishBudget graph n + finishSteps graph n) := by + simpa only [TM2OutputsInTime, Option.map_some, Nat.add_comm] using! + (StateTransition.EvalsToInTime.trans (machine d n).step + (beforeFinishBudget graph n) (finishSteps graph n) + (initList (machine d n) (PortTables.tableBits graph)) + (finishConfiguration graph n) + (some (haltList (machine d n) (PoweringTables.outputBits graph n))) + (beforeFinishExecution graph n) (finishExecution graph n)) + +theorem finishSteps_le (graph : PortTables.Table vertices d) (n : Nat) : + finishSteps graph n ≤ + 2 * (vertices + PoweringTableLayout.blockSize d n * vertices) + 6 + + PoweringRuntimeBudget.tapeCount n * + ((PortTables.tableBits graph).length + beforeFinishBudget graph n * + Runtime.programPushBound (machine d n) + vertices + + PoweringTableLayout.blockSize d n * vertices + 3) := + PoweringRuntimeBudget.finish_steps_le_of_execution d n (PortTables.tableBits graph) + (finishConfiguration graph n) (beforeFinishBudget graph n) vertices + (PoweringTableLayout.blockSize d n * vertices) (beforeFinishExecution graph n) + +theorem execution_budget_le (graph : PortTables.Table vertices d) (n : Nat) : + beforeFinishBudget graph n + finishSteps graph n ≤ + (PoweringPolynomialBudget.time d n (Runtime.programPushBound (machine d n)) + (PoweringRuntimeBudget.tapeCount n)).eval (PortTables.tableBits graph).length := by + exact PoweringPolynomialBudget.execution_budget_le_time d n + (Runtime.programPushBound (machine d n)) (PoweringRuntimeBudget.tapeCount n) + vertices (PortTables.tableBits graph).length (PortTables.vertices_le_tableBits_length graph) + (Nat.le_refl _) (finishSteps_le graph n) + +noncomputable def computableInPolyTime (d n : Nat) : + TM2ComputableInPolyTime (@PortTables.inputBits d) GenericGraphTables.tableBits + (PoweringTables.transform d n) where + tm := machine d n + inputAlphabet := Equiv.refl Bool + outputAlphabet := Equiv.refl Bool + time := PoweringPolynomialBudget.time d n (Runtime.programPushBound (machine d n)) + (PoweringRuntimeBudget.tapeCount n) + outputsFun input := by + rcases input with ⟨vertices, graph⟩ + have run := execution graph n + let bounded : TM2OutputsInTime (machine d n) (PortTables.tableBits graph) + (some (PoweringTables.outputBits graph n)) + ((PoweringPolynomialBudget.time d n (Runtime.programPushBound (machine d n)) + (PoweringRuntimeBudget.tapeCount n)).eval (PortTables.tableBits graph).length) := + ⟨run.toEvalsTo, run.steps_le_m.trans (execution_budget_le graph n)⟩ + change TM2OutputsInTime (machine d n) ((PortTables.tableBits graph).map id) + (some ((PoweringTables.outputBits graph n).map id)) _ + have input_eq : @List.map ((machine d n).Γ (machine d n).k₀) + ((machine d n).Γ (machine d n).k₀) id (PortTables.tableBits graph) = + PortTables.tableBits graph := List.map_id _ + have output_eq : @List.map ((machine d n).Γ (machine d n).k₁) + ((machine d n).Γ (machine d n).k₁) id (PoweringTables.outputBits graph n) = + PoweringTables.outputBits graph n := List.map_id _ + simpa only [input_eq, output_eq, PortTables.inputBits] using bounded + +theorem computableInPolyTime_finite_alphabet (d n : Nat) : + ∀ k, Finite ((computableInPolyTime d n).tm.Γ k) := by + intro k + change Finite Bool + infer_instance + +end MinUncutGames.Foundations.Complexity.PoweringMachineRuntime + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/PoweringMachineVertex.lean b/lean/OAI/Computability/MinUncut/Machines/PoweringMachineVertex.lean new file mode 100644 index 0000000000000000000000000000000000000000..32bf50109ca406bba45d1efc8c3d565c9cb8b352 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/PoweringMachineVertex.lean @@ -0,0 +1,782 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.PoweringMachineRowHeaders +import OAI.Computability.MinUncut.PCP.PoweringTableLayout + +namespace OAI + +namespace MinUncutGames.Foundations.Complexity.PoweringMachineVertex + +open Turing MachineComposition PCP + +variable {K Λ : Type} [DecidableEq K] {vertices d n : Nat} + +abbrev Command (d n : Nat) := Fin (PoweringTableLayout.blockSize d n) + +def ports {d n : Nat} (j : Command d n) : Fin (n + 1) → Fin d := + ((PoweringEnumeration.dartBlockEquiv d n).symm j).1 + +def direction {d n : Nat} (j : Command d n) : Bool := + ((PoweringEnumeration.dartBlockEquiv d n).symm j).2 + +def commands (d n : Nat) : List (Command d n) := (List.ofFn id).reverse + +@[simp] theorem commands_length (d n : Nat) : + (commands d n).length = PoweringTableLayout.blockSize d n := by + simp only [commands, List.length_reverse, List.length_ofFn] + +abbrev LocalLabel (j : Command d n) := PoweringMachineRowBody.Label n (ports j) (direction j) +abbrev SequenceLabel (ops : List (Command d n)) := MachineFiniteSequence.Label LocalLabel ops +abbrev Label (d n : Nat) := SequenceLabel (commands d n) +abbrev State (d n : Nat) := PoweringMachineRowBody.State d n + +def sequenceEntry (ops : List (Command d n)) (labels : SequenceLabel ops → Λ) + (exit : Option Λ) : Option Λ := + MachineFiniteSequence.entry LocalLabel + (fun j => PoweringMachineRowBody.entry n (ports j) (direction j)) ops labels exit + +def entry (d n : Nat) (labels : Label d n → Λ) (exit : Option Λ) : Option Λ := + sequenceEntry (commands d n) labels exit + +def sequenceInstruction (n : Nat) + (placement : PoweringMachineTapes.Tape (PoweringMachineRowBody.capacity n) → K) + (output : K) (ops : List (Command d n)) (labels : SequenceLabel ops → Λ) + (exit : Option Λ) : SequenceLabel ops → TM2.Stmt (fun _ : K => Bool) Λ (State d n) := + MachineFiniteSequence.instruction LocalLabel + (fun j => PoweringMachineRowBody.entry n (ports j) (direction j)) + (fun j => PoweringMachineRowBody.instruction n placement output (ports j) (direction j)) + ops labels exit + +def instruction (n : Nat) + (placement : PoweringMachineTapes.Tape (PoweringMachineRowBody.capacity n) → K) + (output : K) (labels : Label d n → Λ) (exit : Option Λ) : + Label d n → TM2.Stmt (fun _ : K => Bool) Λ (State d n) := + sequenceInstruction n placement output (commands d n) labels exit + +def result (graph : PortTables.Table vertices d) (n : Nat) + (placement : PoweringMachineTapes.Tape (PoweringMachineRowBody.capacity n) → K) + (output : K) (vertex : Fin vertices) (j : Command d n) (base : K → List Bool) : + K → List Bool := + PoweringMachineRowBody.finalTapes graph n placement output vertex (ports j) (direction j) base + +def sequenceTapes (graph : PortTables.Table vertices d) (n : Nat) + (placement : PoweringMachineTapes.Tape (PoweringMachineRowBody.capacity n) → K) + (output : K) (vertex : Fin vertices) (ops : List (Command d n)) (base : K → List Bool) : + K → List Bool := + MachineFiniteSequence.resultOf (result graph n placement output vertex) ops base + +def finalTapes (graph : PortTables.Table vertices d) (n : Nat) + (placement : PoweringMachineTapes.Tape (PoweringMachineRowBody.capacity n) → K) + (output : K) (vertex : Fin vertices) (base : K → List Bool) : K → List Bool := + sequenceTapes graph n placement output vertex (commands d n) base + +def sequenceSteps (graph : PortTables.Table vertices d) (n : Nat) + (placement : PoweringMachineTapes.Tape (PoweringMachineRowBody.capacity n) → K) + (output : K) (vertex : Fin vertices) (ops : List (Command d n)) (base : K → List Bool) : Nat := + MachineFiniteSequence.steps (result graph n placement output vertex) + (fun j _ => PoweringMachineRowBody.steps graph vertex n (ports j) (direction j)) ops base + +def costSum (graph : PortTables.Table vertices d) (vertex : Fin vertices) (n : Nat) : + List (Command d n) → Nat + | [] => 0 + | j :: ops => PoweringMachineRowBody.steps graph vertex n (ports j) (direction j) + + costSum graph vertex n ops + +theorem sequenceSteps_eq (graph : PortTables.Table vertices d) (n : Nat) + (placement : PoweringMachineTapes.Tape (PoweringMachineRowBody.capacity n) → K) + (output : K) (vertex : Fin vertices) (ops : List (Command d n)) (base : K → List Bool) : + sequenceSteps graph n placement output vertex ops base = costSum graph vertex n ops := by + induction ops generalizing base with + | nil => rfl + | cons j ops ih => + change PoweringMachineRowBody.steps graph vertex n (ports j) (direction j) + + sequenceSteps graph n placement output vertex ops + (result graph n placement output vertex j base) = _ + rw [ih] + rfl + +def steps (graph : PortTables.Table vertices d) (vertex : Fin vertices) (n : Nat) : Nat := + costSum graph vertex n (commands d n) + +def budget (d n inputLength : Nat) : Nat := + PoweringTableLayout.blockSize d n * PoweringMachineRowBody.budget d n inputLength + +theorem costSum_le (graph : PortTables.Table vertices d) (vertex : Fin vertices) + (n : Nat) (ops : List (Command d n)) : + costSum graph vertex n ops ≤ + ops.length * PoweringMachineRowBody.budget d n (PortTables.tableBits graph).length := by + induction ops with + | nil => simp only [costSum, List.length_nil, Nat.zero_mul, Nat.le_refl] + | cons j ops ih => + have hfirst := PoweringMachineRowBody.steps_le graph vertex n (ports j) (direction j) + change PoweringMachineRowBody.steps graph vertex n (ports j) (direction j) + + costSum graph vertex n ops ≤ _ + simpa only [List.length_cons, Nat.add_mul, Nat.one_mul, Nat.add_comm] using + Nat.add_le_add hfirst ih + +theorem steps_le (graph : PortTables.Table vertices d) (vertex : Fin vertices) (n : Nat) : + steps graph vertex n ≤ budget d n (PortTables.tableBits graph).length := by + simpa only [steps, budget, commands_length] using costSum_le graph vertex n (commands d n) + +theorem sequenceTrace (graph : PortTables.Table vertices d) (n : Nat) + (placement : PoweringMachineTapes.Tape (PoweringMachineRowBody.capacity n) → K) + (distinct : Function.Injective placement) (output : K) (outside : ∀ i, output ≠ placement i) + (vertex : Fin vertices) (ops : List (Command d n)) + (labels : SequenceLabel ops → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State d n)) + (atLabels : ∀ l, program (labels l) = sequenceInstruction n placement output ops labels exit l) + (base : K → List Bool) (suffix : List Bool) + (ready : PoweringMachineRowBody.Ready graph n placement vertex suffix base) : + (advance (TM2.step program))^[sequenceSteps graph n placement output vertex ops base] + (some ⟨sequenceEntry ops labels exit, + PoweringMasterState.clean (PoweringMachineRowBody.bufferSize d n), base⟩) = + some ⟨exit, PoweringMasterState.clean (PoweringMachineRowBody.bufferSize d n), + sequenceTapes graph n placement output vertex ops base⟩ := by + apply MachineFiniteSequence.trace LocalLabel + (fun j => PoweringMachineRowBody.entry n (ports j) (direction j)) + (fun j => PoweringMachineRowBody.instruction n placement output (ports j) (direction j)) + (result graph n placement output vertex) + (fun j _ => PoweringMachineRowBody.steps graph vertex n (ports j) (direction j)) + program (PoweringMachineRowBody.Ready graph n placement vertex suffix) + (fun _ => PoweringMasterState.clean (PoweringMachineRowBody.bufferSize d n)) id ops + · intro j _ tapes good + exact PoweringMachineRowBody.finalTapes_ready graph n placement distinct output outside + vertex (ports j) (direction j) tapes suffix good + · intro j _ localLabels localExit atLocal tapes good + exact PoweringMachineRowBody.rowTrace graph n placement distinct output outside vertex + (ports j) (direction j) localLabels localExit program atLocal tapes suffix good + · exact atLabels + · exact ready + +theorem vertexTrace (graph : PortTables.Table vertices d) (n : Nat) + (placement : PoweringMachineTapes.Tape (PoweringMachineRowBody.capacity n) → K) + (distinct : Function.Injective placement) (output : K) (outside : ∀ i, output ≠ placement i) + (vertex : Fin vertices) (labels : Label d n → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State d n)) + (atLabels : ∀ l, program (labels l) = instruction n placement output labels exit l) + (base : K → List Bool) (suffix : List Bool) + (ready : PoweringMachineRowBody.Ready graph n placement vertex suffix base) : + (advance (TM2.step program))^[steps graph vertex n] + (some ⟨entry d n labels exit, + PoweringMasterState.clean (PoweringMachineRowBody.bufferSize d n), base⟩) = + some ⟨exit, PoweringMasterState.clean (PoweringMachineRowBody.bufferSize d n), + finalTapes graph n placement output vertex base⟩ := by + have h := sequenceTrace graph n placement distinct output outside vertex (commands d n) + labels exit program atLabels base suffix ready + rw [sequenceSteps_eq] at h + exact h + +theorem sequenceTapes_ready (graph : PortTables.Table vertices d) (n : Nat) + (placement : PoweringMachineTapes.Tape (PoweringMachineRowBody.capacity n) → K) + (distinct : Function.Injective placement) (output : K) (outside : ∀ i, output ≠ placement i) + (vertex : Fin vertices) (ops : List (Command d n)) (base : K → List Bool) + (suffix : List Bool) (ready : PoweringMachineRowBody.Ready graph n placement vertex suffix base) : + PoweringMachineRowBody.Ready graph n placement vertex suffix + (sequenceTapes graph n placement output vertex ops base) := by + induction ops generalizing base with + | nil => exact ready + | cons j ops ih => + apply ih + exact PoweringMachineRowBody.finalTapes_ready graph n placement distinct output outside + vertex (ports j) (direction j) base suffix ready + +theorem finalTapes_ready (graph : PortTables.Table vertices d) (n : Nat) + (placement : PoweringMachineTapes.Tape (PoweringMachineRowBody.capacity n) → K) + (distinct : Function.Injective placement) (output : K) (outside : ∀ i, output ≠ placement i) + (vertex : Fin vertices) (base : K → List Bool) (suffix : List Bool) + (ready : PoweringMachineRowBody.Ready graph n placement vertex suffix base) : + PoweringMachineRowBody.Ready graph n placement vertex suffix + (finalTapes graph n placement output vertex base) := + sequenceTapes_ready graph n placement distinct output outside vertex (commands d n) base suffix ready + +theorem sequenceTapes_other (graph : PortTables.Table vertices d) (n : Nat) + (placement : PoweringMachineTapes.Tape (PoweringMachineRowBody.capacity n) → K) + (output : K) (vertex : Fin vertices) (ops : List (Command d n)) (base : K → List Bool) + (k : K) (hout : k ≠ output) (outside : ∀ i, k ≠ placement i) : + sequenceTapes graph n placement output vertex ops base k = base k := by + induction ops generalizing base with + | nil => rfl + | cons j ops ih => + change sequenceTapes graph n placement output vertex ops + (result graph n placement output vertex j base) k = _ + rw [ih] + exact PoweringMachineRowBody.finalTapes_other graph n placement output vertex + (ports j) (direction j) base k hout outside + +theorem finalTapes_other (graph : PortTables.Table vertices d) (n : Nat) + (placement : PoweringMachineTapes.Tape (PoweringMachineRowBody.capacity n) → K) + (output : K) (vertex : Fin vertices) (base : K → List Bool) + (k : K) (hout : k ≠ output) (outside : ∀ i, k ≠ placement i) : + finalTapes graph n placement output vertex base k = base k := + sequenceTapes_other graph n placement output vertex (commands d n) base k hout outside + +def rowBits (graph : PortTables.Table vertices d) (n : Nat) (vertex : Fin vertices) + (j : Command d n) : List Bool := + encodeWords (PoweringMachineRowBody.rowWords graph n vertex (ports j) (direction j)) + +theorem blockIndex_eq_encodeDart (n : Nat) (vertex : Fin vertices) (j : Command d n) : + PoweringTableLayout.blockIndex d n vertex j = + PoweringEnumeration.encodeDart vertices d n (direction j, vertex, ports j) := by + have h := PoweringTableLayout.blockIndex_eq_encodeDart d n vertex (ports j) (direction j) + simp only [ports, direction, Prod.mk.eta] at h + erw [Equiv.apply_symm_apply] at h + exact h + +theorem rowBits_eq (graph : PortTables.Table vertices d) (n : Nat) (vertex : Fin vertices) + (j : Command d n) : + rowBits graph n vertex j = encodeWords (GenericGraphTables.rowWords + (PoweringTables.table graph n).rows[PoweringTableLayout.blockIndex d n vertex j]) := by + rw [blockIndex_eq_encodeDart] + rfl + +theorem encodeWords_flatMap {X : Type*} (xs : List X) (f : X → List Nat) : + encodeWords (xs.flatMap f) = xs.flatMap (fun x => encodeWords (f x)) := by + induction xs with + | nil => rfl + | cons x xs ih => simp only [List.flatMap_cons, encodeWords_append, ih] + +theorem rows_eq_vertexRowBits (graph : PortTables.Table vertices d) (n : Nat) + (vertex : Fin vertices) : + (List.ofFn id : List (Command d n)).flatMap (rowBits graph n vertex) = + PoweringTableLayout.vertexRowBits graph n vertex := by + have hrows : (List.ofFn id : List (Command d n)).map + (fun j => (PoweringTables.table graph n).rows[PoweringTableLayout.blockIndex d n vertex j]) = + List.ofFn (fun j : Command d n => + (PoweringTables.table graph n).rows[PoweringTableLayout.blockIndex d n vertex j]) := by + simp only [List.map_ofFn, Function.comp_id] + calc + _ = (List.ofFn id : List (Command d n)).flatMap (fun j => encodeWords + (GenericGraphTables.rowWords + (PoweringTables.table graph n).rows[PoweringTableLayout.blockIndex d n vertex j])) := by + apply congrArg (List.flatMap · (List.ofFn id)) + funext j + exact rowBits_eq graph n vertex j + _ = PoweringTableLayout.vertexRowBits graph n vertex := by + unfold PoweringTableLayout.vertexRowBits PoweringTableLayout.vertexRowWords + PoweringTableLayout.vertexRows + rw [encodeWords_flatMap] + erw [← hrows, List.flatMap_map] + rfl + +theorem sequenceTapes_output (graph : PortTables.Table vertices d) (n : Nat) + (placement : PoweringMachineTapes.Tape (PoweringMachineRowBody.capacity n) → K) + (distinct : Function.Injective placement) (output : K) (outside : ∀ i, output ≠ placement i) + (vertex : Fin vertices) (ops : List (Command d n)) (base : K → List Bool) (suffix : List Bool) + (ready : PoweringMachineRowBody.Ready graph n placement vertex suffix base) : + sequenceTapes graph n placement output vertex ops base output = + ops.reverse.flatMap (rowBits graph n vertex) ++ base output := by + induction ops generalizing base with + | nil => rfl + | cons j ops ih => + have nextReady := PoweringMachineRowBody.finalTapes_ready graph n placement distinct + output outside vertex (ports j) (direction j) base suffix ready + change sequenceTapes graph n placement output vertex ops + (result graph n placement output vertex j base) output = _ + dsimp only [result] + rw [ih _ nextReady, PoweringMachineRowBody.finalTapes_output graph n placement distinct + output outside vertex (ports j) (direction j) base suffix ready] + simp only [List.reverse_cons, List.flatMap_append, List.flatMap_cons, + List.flatMap_nil, List.append_nil, List.append_assoc, rowBits] + +theorem finalTapes_output (graph : PortTables.Table vertices d) (n : Nat) + (placement : PoweringMachineTapes.Tape (PoweringMachineRowBody.capacity n) → K) + (distinct : Function.Injective placement) (output : K) (outside : ∀ i, output ≠ placement i) + (vertex : Fin vertices) (base : K → List Bool) (suffix : List Bool) + (ready : PoweringMachineRowBody.Ready graph n placement vertex suffix base) : + finalTapes graph n placement output vertex base output = + PoweringTableLayout.vertexRowBits graph n vertex ++ base output := by + rw [finalTapes, sequenceTapes_output graph n placement distinct output outside vertex + (commands d n) base suffix ready] + simp only [commands, List.reverse_reverse, rows_eq_vertexRowBits] + +def vertexInTime (graph : PortTables.Table vertices d) (n : Nat) + (placement : PoweringMachineTapes.Tape (PoweringMachineRowBody.capacity n) → K) + (distinct : Function.Injective placement) (output : K) (outside : ∀ i, output ≠ placement i) + (vertex : Fin vertices) (labels : Label d n → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State d n)) + (atLabels : ∀ l, program (labels l) = instruction n placement output labels exit l) + (base : K → List Bool) (suffix : List Bool) + (ready : PoweringMachineRowBody.Ready graph n placement vertex suffix base) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨entry d n labels exit, PoweringMasterState.clean (PoweringMachineRowBody.bufferSize d n), base⟩ + (some ⟨exit, PoweringMasterState.clean (PoweringMachineRowBody.bufferSize d n), + finalTapes graph n placement output vertex base⟩) + (budget d n (PortTables.tableBits graph).length) where + steps := steps graph vertex n + evals_in_steps := vertexTrace graph n placement distinct output outside vertex labels exit + program atLabels base suffix ready + steps_le_m := steps_le graph vertex n + +end MinUncutGames.Foundations.Complexity.PoweringMachineVertex + +namespace MinUncutGames.Foundations.Complexity.PoweringMachineOuterLoop + +open Turing MachineComposition PCP + +variable {K Λ : Type} [DecidableEq K] {vertices d n : Nat} + +abbrev Placement (K : Type) (n : Nat) := PoweringMachineTapes.Tape (PoweringMachineRowBody.capacity n) → K +abbrev State := PoweringMachineVertex.State + +structure Ready (graph : PortTables.Table vertices d) (n : Nat) (placement : Placement K n) + (base : K → List Bool) : Prop where + table : base (placement (.inl 0)) = PortTables.tableBits graph + scratch : base (placement (.inl 5)) = [] + leftCopy : base (placement (.inl 8)) = [] + rightCopy : base (placement (.inl 9)) = [] + data : base (placement (.inl 10)) = [] + +def counter (placement : Placement K n) (base : K → List Bool) (remaining : Nat) : K → List Bool := + MachineUnaryCounter.counterTapes (placement (.inl 1)) base remaining [] + +theorem counter_other (placement : Placement K n) (distinct : Function.Injective placement) + (base : K → List Bool) (remaining : Nat) (j : Fin 11) (hj : j ≠ 1) : + counter placement base remaining (placement (.inl j)) = base (placement (.inl j)) := by + apply MachineUnaryCounter.counterTapes_other + intro h + exact hj (Sum.inl.inj (distinct h)) + +theorem ready_vertex (graph : PortTables.Table vertices d) (n : Nat) + (placement : Placement K n) (distinct : Function.Injective placement) + (base : K → List Bool) (ready : Ready graph n placement base) (vertex : Fin vertices) : + PoweringMachineRowBody.Ready graph n placement vertex [] (counter placement base vertex.val) := by + constructor + · constructor + · rw [counter_other placement distinct base vertex.val 0 (by decide)] + exact ready.table + · simp only [counter, MachineUnaryCounter.counterTapes_counter] + · rw [counter_other placement distinct base vertex.val 5 (by decide)] + exact ready.scratch + · rw [counter_other placement distinct base vertex.val 8 (by decide)] + exact ready.leftCopy + · rw [counter_other placement distinct base vertex.val 9 (by decide)] + exact ready.rightCopy + · rw [counter_other placement distinct base vertex.val 10 (by decide)] + exact ready.data + +omit [DecidableEq K] in +theorem ready_of_vertex (graph : PortTables.Table vertices d) (n : Nat) + (placement : Placement K n) (base : K → List Bool) (vertex : Fin vertices) + (ready : PoweringMachineRowBody.Ready graph n placement vertex [] base) : + Ready graph n placement base := + ⟨ready.1.table, ready.1.scratch, ready.1.leftCopy, ready.1.rightCopy, ready.2⟩ + +def vertexStart (d n : Nat) (labels : PoweringMachineVertex.Label d n → Λ) (guardLabel : Λ) : Λ := + (PoweringMachineVertex.entry d n labels (some guardLabel)).getD guardLabel + +theorem vertexEntry (d n : Nat) (labels : PoweringMachineVertex.Label d n → Λ) (guardLabel : Λ) : + PoweringMachineVertex.entry d n labels (some guardLabel) = + some (vertexStart d n labels guardLabel) := by + unfold vertexStart PoweringMachineVertex.entry PoweringMachineVertex.sequenceEntry + have h : ∀ (commands : List (PoweringMachineVertex.Command d n)) + (labels : MachineFiniteSequence.Label PoweringMachineVertex.LocalLabel commands → Λ), + MachineFiniteSequence.entry PoweringMachineVertex.LocalLabel + (fun j => PoweringMachineRowBody.entry n + (PoweringMachineVertex.ports j) (PoweringMachineVertex.direction j)) + commands labels (some guardLabel) = + some ((MachineFiniteSequence.entry PoweringMachineVertex.LocalLabel + (fun j => PoweringMachineRowBody.entry n + (PoweringMachineVertex.ports j) (PoweringMachineVertex.direction j)) + commands labels (some guardLabel)).getD guardLabel) := by + intro commands labels + cases commands <;> rfl + exact h _ labels + +def bridge (d n : Nat) (labels : PoweringMachineVertex.Label d n → Λ) (guardLabel : Λ) : + TM2.Stmt (fun _ : K => Bool) Λ (State d n) := + .goto (fun _ => vertexStart d n labels guardLabel) + +def finalTapes (graph : PortTables.Table vertices d) (n : Nat) (placement : Placement K n) + (output : K) : (remaining : Nat) → remaining ≤ vertices → (K → List Bool) → K → List Bool + | 0, _, base => counter placement base 0 + | r + 1, bounded, base => + finalTapes graph n placement output r (by omega) + (PoweringMachineVertex.finalTapes graph n placement output ⟨r, by omega⟩ + (counter placement base r)) + +def steps (graph : PortTables.Table vertices d) (n : Nat) : + (remaining : Nat) → remaining ≤ vertices → Nat + | 0, _ => 1 + | r + 1, bounded => + 2 + PoweringMachineVertex.steps graph ⟨r, by omega⟩ n + steps graph n r (by omega) + +theorem steps_le (graph : PortTables.Table vertices d) (n remaining : Nat) + (bounded : remaining ≤ vertices) : + steps graph n remaining bounded ≤ + remaining * (PoweringMachineVertex.budget d n (PortTables.tableBits graph).length + 2) + 1 := by + induction remaining with + | zero => simp [steps] + | succ r ih => + have hv := PoweringMachineVertex.steps_le graph (⟨r, by omega⟩ : Fin vertices) n + have hi := ih (by omega) + simp only [steps, Nat.add_mul, Nat.one_mul] + omega + +theorem finalTapes_ready (graph : PortTables.Table vertices d) (n : Nat) + (placement : Placement K n) (distinct : Function.Injective placement) + (output : K) (outside : ∀ i, output ≠ placement i) + (remaining : Nat) (bounded : remaining ≤ vertices) (base : K → List Bool) + (ready : Ready graph n placement base) : + Ready graph n placement (finalTapes graph n placement output remaining bounded base) := by + induction remaining generalizing base with + | zero => + constructor + · rw [finalTapes, counter_other placement distinct base 0 0 (by decide)] + exact ready.table + · rw [finalTapes, counter_other placement distinct base 0 5 (by decide)] + exact ready.scratch + · rw [finalTapes, counter_other placement distinct base 0 8 (by decide)] + exact ready.leftCopy + · rw [finalTapes, counter_other placement distinct base 0 9 (by decide)] + exact ready.rightCopy + · rw [finalTapes, counter_other placement distinct base 0 10 (by decide)] + exact ready.data + | succ r ih => + apply ih + apply ready_of_vertex graph n placement _ (⟨r, by omega⟩ : Fin vertices) + exact PoweringMachineVertex.finalTapes_ready graph n placement distinct output outside + ⟨r, by omega⟩ _ [] (ready_vertex graph n placement distinct base ready _) + +def prefixRows (graph : PortTables.Table vertices d) (n : Nat) : Nat → List Bool + | 0 => [] + | r + 1 => prefixRows graph n r ++ + if h : r < vertices then PoweringTableLayout.vertexRowBits graph n ⟨r, h⟩ else [] + +theorem prefixRows_ofFn (graph : PortTables.Table vertices d) (n remaining : Nat) + (bounded : remaining ≤ vertices) : + prefixRows graph n remaining = + (List.ofFn (fun i : Fin remaining => + PoweringTableLayout.vertexRowBits graph n (Fin.castLE bounded i))).flatten := by + induction remaining with + | zero => rfl + | succ r ih => + have hr : r < vertices := by omega + rw [prefixRows, dite_eq_left hr, List.ofFn_succ_last, List.flatten_append] + simp only [List.flatten_cons, List.flatten_nil, List.append_nil] + change prefixRows graph n r ++ PoweringTableLayout.vertexRowBits graph n ⟨r, hr⟩ = + (List.ofFn (fun i : Fin r => PoweringTableLayout.vertexRowBits graph n + (Fin.castLE (show r ≤ vertices by omega) i))).flatten ++ + PoweringTableLayout.vertexRowBits graph n ⟨r, hr⟩ + rw [ih] + +theorem prefixRows_all (graph : PortTables.Table vertices d) (n : Nat) : + prefixRows graph n vertices = + (List.finRange vertices).flatMap (PoweringTableLayout.vertexRowBits graph n) := by + rw [prefixRows_ofFn graph n vertices (Nat.le_refl _)] + simp only [List.finRange, List.flatMap_def, List.map_ofFn] + rfl + +theorem finalTapes_output (graph : PortTables.Table vertices d) (n : Nat) + (placement : Placement K n) (distinct : Function.Injective placement) + (output : K) (outside : ∀ i, output ≠ placement i) + (remaining : Nat) (bounded : remaining ≤ vertices) (base : K → List Bool) + (ready : Ready graph n placement base) : + finalTapes graph n placement output remaining bounded base output = + prefixRows graph n remaining ++ base output := by + induction remaining generalizing base with + | zero => + exact MachineUnaryCounter.counterTapes_other (placement (.inl 1)) output (outside _) + base 0 [] + | succ r ih => + let vertex : Fin vertices := ⟨r, by omega⟩ + let current := counter placement base r + have vertexReady := ready_vertex graph n placement distinct base ready vertex + have nextReady := PoweringMachineVertex.finalTapes_ready graph n placement distinct + output outside vertex current [] vertexReady + change finalTapes graph n placement output r (by omega) + (PoweringMachineVertex.finalTapes graph n placement output vertex current) output = _ + rw [ih (by omega) _ (ready_of_vertex graph n placement _ vertex nextReady), + PoweringMachineVertex.finalTapes_output graph n placement distinct output outside + vertex current [] vertexReady] + have hc : current output = base output := + MachineUnaryCounter.counterTapes_other (placement (.inl 1)) output (outside _) base r [] + rw [hc, prefixRows, dite_eq_left vertex.isLt, List.append_assoc] + +theorem finalTapes_other (graph : PortTables.Table vertices d) (n : Nat) + (placement : Placement K n) (output : K) (remaining : Nat) + (bounded : remaining ≤ vertices) (base : K → List Bool) + (k : K) (hout : k ≠ output) (outside : ∀ i, k ≠ placement i) : + finalTapes graph n placement output remaining bounded base k = base k := by + induction remaining generalizing base with + | zero => exact MachineUnaryCounter.counterTapes_other _ _ (outside _) base 0 [] + | succ r ih => + rw [finalTapes, ih, PoweringMachineVertex.finalTapes_other graph n placement output + ⟨r, by omega⟩ _ k hout outside] + exact MachineUnaryCounter.counterTapes_other _ _ (outside _) base r [] + +theorem loopTrace (graph : PortTables.Table vertices d) (n : Nat) + (placement : Placement K n) (distinct : Function.Injective placement) + (output : K) (outside : ∀ i, output ≠ placement i) + (guardLabel bridgeLabel exitLabel : Λ) (labels : PoweringMachineVertex.Label d n → Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State d n)) + (atGuard : program guardLabel = + MachineUnaryCounter.guard (placement (.inl 1)) bridgeLabel exitLabel) + (atBridge : program bridgeLabel = bridge d n labels guardLabel) + (atVertex : ∀ l, program (labels l) = + PoweringMachineVertex.instruction n placement output labels (some guardLabel) l) + (remaining : Nat) (bounded : remaining ≤ vertices) (base : K → List Bool) + (ready : Ready graph n placement base) : + (advance (TM2.step program))^[steps graph n remaining bounded] + (some ⟨some guardLabel, PoweringMasterState.clean (PoweringMachineRowBody.bufferSize d n), + counter placement base remaining⟩) = + some ⟨some exitLabel, PoweringMasterState.clean (PoweringMachineRowBody.bufferSize d n), + finalTapes graph n placement output remaining bounded base⟩ := by + let initial := PoweringMasterState.clean (PoweringMachineRowBody.bufferSize d n) + induction remaining generalizing base with + | zero => + simpa only [steps, finalTapes, counter, initial, PoweringMasterState.clean, + PoweringMasterState.withBuffer] using + MachineUnaryCounter.guardTrace_zero (placement (.inl 1)) guardLabel bridgeLabel exitLabel + program atGuard base [] initial.1 none + | succ r ih => + let vertex : Fin vertices := ⟨r, by omega⟩ + let current := counter placement base r + let next := PoweringMachineVertex.finalTapes graph n placement output vertex current + have vertexReady : PoweringMachineRowBody.Ready graph n placement vertex [] current := + ready_vertex graph n placement distinct base ready vertex + have nextVertexReady := PoweringMachineVertex.finalTapes_ready graph n placement distinct + output outside vertex current [] vertexReady + have nextReady : Ready graph n placement next := + ready_of_vertex graph n placement next vertex nextVertexReady + have sameCounter : counter placement next r = next := by + have hs := nextVertexReady.1.source + change next (placement (.inl 1)) = encodeWord r ++ [] at hs + unfold counter MachineUnaryCounter.counterTapes + rw [← hs] + exact Function.update_eq_self _ _ + have tailRun := ih (by omega) next nextReady + rw [sameCounter] at tailRun + have guardRun : advance (TM2.step program) + (some ⟨some guardLabel, initial, counter placement base (r + 1)⟩) = + some ⟨some bridgeLabel, initial, current⟩ := by + simpa only [advance_some, current, counter, initial, PoweringMasterState.clean, + PoweringMasterState.withBuffer] using + MachineUnaryCounter.guardStep_succ (placement (.inl 1)) guardLabel bridgeLabel exitLabel + program atGuard base r [] initial.1 none + have bridgeRun : advance (TM2.step program) + (some ⟨some bridgeLabel, initial, current⟩) = + some ⟨PoweringMachineVertex.entry d n labels (some guardLabel), initial, current⟩ := by + change some (TM2.stepAux (program bridgeLabel) initial current) = _ + rw [atBridge, vertexEntry] + rfl + have vertexRun := PoweringMachineVertex.vertexTrace graph n placement distinct output outside + vertex labels (some guardLabel) program atVertex current [] vertexReady + change (advance (TM2.step program))^[2 + PoweringMachineVertex.steps graph vertex n + + steps graph n r (by omega)] + (some ⟨some guardLabel, initial, counter placement base (r + 1)⟩) = _ + rw [show 2 + PoweringMachineVertex.steps graph vertex n + steps graph n r (by omega) = + (steps graph n r (by omega) + PoweringMachineVertex.steps graph vertex n) + 1 + 1 by omega, + Function.iterate_succ_apply, guardRun, Function.iterate_succ_apply, bridgeRun, + Function.iterate_add_apply, vertexRun] + exact tailRun + +def loopInTime (graph : PortTables.Table vertices d) (n : Nat) + (placement : Placement K n) (distinct : Function.Injective placement) + (output : K) (outside : ∀ i, output ≠ placement i) + (guardLabel bridgeLabel exitLabel : Λ) (labels : PoweringMachineVertex.Label d n → Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State d n)) + (atGuard : program guardLabel = + MachineUnaryCounter.guard (placement (.inl 1)) bridgeLabel exitLabel) + (atBridge : program bridgeLabel = bridge d n labels guardLabel) + (atVertex : ∀ l, program (labels l) = + PoweringMachineVertex.instruction n placement output labels (some guardLabel) l) + (remaining : Nat) (bounded : remaining ≤ vertices) (base : K → List Bool) + (ready : Ready graph n placement base) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some guardLabel, PoweringMasterState.clean (PoweringMachineRowBody.bufferSize d n), + counter placement base remaining⟩ + (some ⟨some exitLabel, PoweringMasterState.clean (PoweringMachineRowBody.bufferSize d n), + finalTapes graph n placement output remaining bounded base⟩) + (remaining * (PoweringMachineVertex.budget d n (PortTables.tableBits graph).length + 2) + 1) where + steps := steps graph n remaining bounded + evals_in_steps := loopTrace graph n placement distinct output outside guardLabel bridgeLabel + exitLabel labels program atGuard atBridge atVertex remaining bounded base ready + steps_le_m := steps_le graph n remaining bounded + +end MinUncutGames.Foundations.Complexity.PoweringMachineOuterLoop + +namespace MinUncutGames.Foundations.Complexity.PoweringMachineFinish + +open Turing MachineComposition + +variable {K Λ σ : Type} [DecidableEq K] {N : Nat} + +abbrev Alphabet (_ : K) := Bool + +abbrev Label (enumeration : Fin N ≃ K) (output : K) := + MachineUnaryAffineAt.Label ⊕ (MachineUnaryAffineAt.Label ⊕ + MachineDrainMany.Label (MachineDrainMany.workTapes enumeration output)) + +def copyInstruction (source scratch output : K) + (labels : MachineUnaryAffineAt.Label → Λ) (exit : Option Λ) : + MachineUnaryAffineAt.Label → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) + | .seed => MachineUnaryAffineAt.seed output 0 (labels .scan) + | .scan => MachineUnaryAffineAt.scan source scratch output 1 (labels .scan) (labels .restore) + | .restore => Reduction.MachineTransfer.loopAt scratch source id false (labels .restore) exit + +def instruction (enumeration : Fin N ≃ K) (headerV headerD output scratch : K) + (labels : Label enumeration output → Λ) : + Label enumeration output → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) + | .inl l => copyInstruction headerD scratch output (fun q => labels (.inl q)) + (some (labels (.inr (.inl .seed)))) l + | .inr (.inl l) => copyInstruction headerV scratch output + (fun q => labels (.inr (.inl q))) + (MachineDrainMany.entry (MachineDrainMany.workTapes enumeration output) + (fun q => labels (.inr (.inr q))) none) l + | .inr (.inr l) => MachineDrainMany.instruction + (MachineDrainMany.workTapes enumeration output) (fun q => labels (.inr (.inr q))) none l + +def program (enumeration : Fin N ≃ K) (headerV headerD output scratch : K) : + Label enumeration output → + TM2.Stmt (Alphabet (K := K)) (Label enumeration output) (σ × Option Bool) := + instruction enumeration headerV headerD output scratch id + +def afterD (output : K) (base : K → List Bool) (m : Nat) : K → List Bool := + Function.update base output (encodeWord m ++ base output) + +def afterHeaders (output : K) (base : K → List Bool) (n m : Nat) : K → List Bool := + Function.update base output (encodeWords [n, m] ++ base output) + +@[simp] theorem afterHeaders_output (output : K) (base : K → List Bool) (n m : Nat) : + afterHeaders output base n m output = encodeWords [n, m] ++ base output := by + simp only [afterHeaders, Function.update_self] + +theorem afterHeaders_other (output : K) (base : K → List Bool) (n m : Nat) + (k : K) (hk : k ≠ output) : afterHeaders output base n m k = base k := + Function.update_of_ne hk _ _ + +def copySteps (n m : Nat) : Nat := (2 * (m + 1) + 1) + (2 * (n + 1) + 1) + +theorem copySteps_eq (n m : Nat) : copySteps n m = 2 * (n + m) + 6 := by + unfold copySteps + omega + +def steps (enumeration : Fin N ≃ K) (output : K) (base : K → List Bool) (n m : Nat) : Nat := + copySteps n m + MachineDrainMany.steps (MachineDrainMany.workTapes enumeration output) + (afterHeaders output base n m) + +def budget (enumeration : Fin N ≃ K) (output : K) (base : K → List Bool) (n m : Nat) : Nat := + copySteps n m + (MachineDrainMany.lengthSum (MachineDrainMany.workTapes enumeration output) + (afterHeaders output base n m) + (MachineDrainMany.workTapes enumeration output).length) + +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 traceAt (enumeration : Fin N ≃ K) (headerV headerD output scratch : K) + (hvs : headerV ≠ scratch) (hvo : headerV ≠ output) + (hds : headerD ≠ scratch) (hdo : headerD ≠ output) (hso : scratch ≠ output) + (labels : Label enumeration output → Λ) + (target : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atLabels : ∀ l, target (labels l) = + instruction enumeration headerV headerD output scratch labels l) + (base : K → List Bool) (n m : Nat) (suffixV suffixD : List Bool) + (wordV : base headerV = encodeWord n ++ suffixV) + (wordD : base headerD = encodeWord m ++ suffixD) + (scratchEmpty : base scratch = []) (ambient : σ) (register : Option Bool) : + (advance (TM2.step target))^[steps enumeration output base n m] + (some ⟨some (labels (.inl .seed)), (ambient, register), base⟩) = + some ⟨none, (ambient, none), + MachineDrainMany.haltTapes output (encodeWords [n, m] ++ base output)⟩ := by + have hd := MachineUnaryAffineAt.seededAffineTrace headerD scratch output hds hdo hso 1 0 + (labels (.inl .seed)) (labels (.inl .scan)) (labels (.inl .restore)) + (some (labels (.inr (.inl .seed)))) target + (atLabels (.inl .seed)) (atLabels (.inl .scan)) (atLabels (.inl .restore)) + base m suffixD wordD scratchEmpty ambient register + simp only [Nat.one_mul, Nat.add_zero] at hd + change (advance (TM2.step target))^[2 * (m + 1) + 1] + (some ⟨some (labels (.inl .seed)), (ambient, register), base⟩) = + some ⟨some (labels (.inr (.inl .seed))), (ambient, none), afterD output base m⟩ at hd + have wordV' : afterD output base m headerV = encodeWord n ++ suffixV := by + simpa only [afterD, Function.update_of_ne hvo] using wordV + have scratchEmpty' : afterD output base m scratch = [] := by + simpa only [afterD, Function.update_of_ne hso] using scratchEmpty + have hv := MachineUnaryAffineAt.seededAffineTrace headerV scratch output hvs hvo hso 1 0 + (labels (.inr (.inl .seed))) (labels (.inr (.inl .scan))) + (labels (.inr (.inl .restore))) + (MachineDrainMany.entry (MachineDrainMany.workTapes enumeration output) + (fun q => labels (.inr (.inr q))) none) + target (atLabels (.inr (.inl .seed))) (atLabels (.inr (.inl .scan))) + (atLabels (.inr (.inl .restore))) (afterD output base m) n suffixV + wordV' scratchEmpty' ambient none + simp only [Nat.one_mul, Nat.add_zero] at hv + have copied : Function.update (afterD output base m) output + (encodeWord n ++ afterD output base m output) = afterHeaders output base n m := by + simp only [afterD, afterHeaders, Function.update_self, Function.update_idem, + encodeWords, List.append_nil, List.append_assoc] + rw [copied] at hv + have cleaned := MachineDrainMany.cleanupTrace enumeration output + (fun q => labels (.inr (.inr q))) target (fun l => atLabels (.inr (.inr l))) + (afterHeaders output base n m) ambient + rw [afterHeaders_output] at cleaned + have total := trace_trans _ (trace_trans _ hd hv) cleaned + simpa only [steps, copySteps] using total + +theorem trace (enumeration : Fin N ≃ K) (headerV headerD output scratch : K) + (hvs : headerV ≠ scratch) (hvo : headerV ≠ output) + (hds : headerD ≠ scratch) (hdo : headerD ≠ output) (hso : scratch ≠ output) + (base : K → List Bool) (n m : Nat) (suffixV suffixD : List Bool) + (wordV : base headerV = encodeWord n ++ suffixV) + (wordD : base headerD = encodeWord m ++ suffixD) + (scratchEmpty : base scratch = []) (ambient : σ) (register : Option Bool) : + (advance (TM2.step (program enumeration headerV headerD output scratch)))^[ + steps enumeration output base n m] + (some ⟨some (.inl .seed), (ambient, register), base⟩) = + some ⟨none, (ambient, none), + MachineDrainMany.haltTapes output (encodeWords [n, m] ++ base output)⟩ := + traceAt enumeration headerV headerD output scratch hvs hvo hds hdo hso id + (program enumeration headerV headerD output scratch) (fun _ => rfl) + base n m suffixV suffixD wordV wordD scratchEmpty ambient register + +theorem steps_le_budget (enumeration : Fin N ≃ K) (output : K) + (base : K → List Bool) (n m : Nat) : + steps enumeration output base n m ≤ budget enumeration output base n m := + Nat.add_le_add_left (MachineDrainMany.steps_le + (MachineDrainMany.workTapes enumeration output) (afterHeaders output base n m)) _ + +theorem afterHeaders_length_le (output : K) (base : K → List Bool) (n m bound : Nat) + (bounded : ∀ k, (base k).length ≤ bound) (k : K) : + (afterHeaders output base n m k).length ≤ bound + n + m + 2 := by + by_cases hk : k = output + · subst k + rw [afterHeaders_output] + have hb := bounded output + simp only [List.length_append, encodeWords, encodeWord_length, List.length_nil] + omega + · rw [afterHeaders_other output base n m k hk] + have hb := bounded k + omega + +theorem steps_le_uniform (enumeration : Fin N ≃ K) (output : K) + (base : K → List Bool) (n m bound : Nat) + (bounded : ∀ k, (base k).length ≤ bound) : + steps enumeration output base n m ≤ 2 * (n + m) + 6 + N * (bound + n + m + 3) := by + have hc := MachineDrainMany.steps_le_uniform (MachineDrainMany.workTapes enumeration output) + (afterHeaders output base n m) (bound + n + m + 2) + (afterHeaders_length_le output base n m bound bounded) + have hl := MachineDrainMany.workTapes_length_le enumeration output + have hm := Nat.mul_le_mul_right (bound + n + m + 3) hl + rw [show bound + n + m + 2 + 1 = bound + n + m + 3 by omega] at hc + unfold steps + rw [copySteps_eq] + exact Nat.add_le_add_left (hc.trans hm) _ + +def execution (enumeration : Fin N ≃ K) (headerV headerD output scratch : K) + (hvs : headerV ≠ scratch) (hvo : headerV ≠ output) + (hds : headerD ≠ scratch) (hdo : headerD ≠ output) (hso : scratch ≠ output) + (base : K → List Bool) (n m : Nat) (suffixV suffixD : List Bool) + (wordV : base headerV = encodeWord n ++ suffixV) + (wordD : base headerD = encodeWord m ++ suffixD) + (scratchEmpty : base scratch = []) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step (program enumeration headerV headerD output scratch)) + ⟨some (.inl .seed), (ambient, register), base⟩ + (some ⟨none, (ambient, none), + MachineDrainMany.haltTapes output (encodeWords [n, m] ++ base output)⟩) + (budget enumeration output base n m) where + steps := steps enumeration output base n m + evals_in_steps := trace enumeration headerV headerD output scratch hvs hvo hds hdo hso + base n m suffixV suffixD wordV wordD scratchEmpty ambient register + steps_le_m := steps_le_budget enumeration output base n m + +end MinUncutGames.Foundations.Complexity.PoweringMachineFinish + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/PoweringRuntimeBudget.lean b/lean/OAI/Computability/MinUncut/Machines/PoweringRuntimeBudget.lean new file mode 100644 index 0000000000000000000000000000000000000000..97a4ec6b10279d276d9d8af8c3550074039ac6a0 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/PoweringRuntimeBudget.lean @@ -0,0 +1,64 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.PoweringMachineGlobal + +namespace OAI + +section +namespace MinUncutGames.Foundations.Complexity.PoweringRuntimeBudget + +open Turing + +theorem stackLength_le_of_execution (tm : FinTM2) (start finish : tm.Cfg) + (initialBound priorBudget : Nat) + (initial : ∀ k, (start.stk k).length ≤ initialBound) + (prior : StateTransition.EvalsToInTime tm.step start (some finish) priorBudget) + (k : tm.K) : + (finish.stk k).length ≤ initialBound + priorBudget * Runtime.programPushBound tm := by + have grown := Runtime.executionSizeBound tm.step (fun cfg => (cfg.stk k).length) + (Runtime.programPushBound tm) (Runtime.stepStackLength tm k) prior + exact grown.trans (Nat.add_le_add_right (initial k) _) + +theorem stackLength_le_from_input (tm : FinTM2) (input : List (tm.Γ tm.k₀)) + (finish : tm.Cfg) (priorBudget : Nat) + (prior : StateTransition.EvalsToInTime tm.step (initList tm input) + (some finish) priorBudget) (k : tm.K) : + (finish.stk k).length ≤ input.length + priorBudget * Runtime.programPushBound tm := + stackLength_le_of_execution tm (initList tm input) finish input.length priorBudget + (Runtime.initialStackLength tm input) prior k + +abbrev tapeCount (radius : Nat) : Nat := + 4 + (11 + PoweringMachineRowBody.capacity radius + 1) + +theorem finish_steps_le_of_execution (d radius : Nat) (input : List Bool) + (before : (PoweringMachineGlobal.machine d radius).Cfg) + (priorBudget vertices darts : Nat) + (prior : StateTransition.EvalsToInTime (PoweringMachineGlobal.machine d radius).step + (initList (PoweringMachineGlobal.machine d radius) input) (some before) priorBudget) : + PoweringMachineFinish.steps (PoweringMachineGlobal.enumeration radius) + (PoweringMachineGlobal.outputTape radius) before.stk vertices darts ≤ + 2 * (vertices + darts) + 6 + tapeCount radius * + (input.length + priorBudget * Runtime.programPushBound + (PoweringMachineGlobal.machine d radius) + vertices + darts + 3) := by + exact PoweringMachineFinish.steps_le_uniform (PoweringMachineGlobal.enumeration radius) + (PoweringMachineGlobal.outputTape radius) before.stk vertices darts + (input.length + priorBudget * Runtime.programPushBound (PoweringMachineGlobal.machine d radius)) + (stackLength_le_from_input (PoweringMachineGlobal.machine d radius) input before priorBudget prior) + +theorem total_steps_le_of_execution (d radius : Nat) (input : List Bool) + (before : (PoweringMachineGlobal.machine d radius).Cfg) + (priorBudget vertices darts : Nat) + (prior : StateTransition.EvalsToInTime (PoweringMachineGlobal.machine d radius).step + (initList (PoweringMachineGlobal.machine d radius) input) (some before) priorBudget) : + prior.steps + PoweringMachineFinish.steps (PoweringMachineGlobal.enumeration radius) + (PoweringMachineGlobal.outputTape radius) before.stk vertices darts ≤ + priorBudget + (2 * (vertices + darts) + 6 + tapeCount radius * + (input.length + priorBudget * Runtime.programPushBound + (PoweringMachineGlobal.machine d radius) + vertices + darts + 3)) := + Nat.add_le_add prior.steps_le_m + (finish_steps_le_of_execution d radius input before priorBudget vertices darts prior) + +end MinUncutGames.Foundations.Complexity.PoweringRuntimeBudget + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/PreprocessingMachineBounds.lean b/lean/OAI/Computability/MinUncut/Machines/PreprocessingMachineBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..53c4f2591c96ecd3f92d06081cdbc04993500e60 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/PreprocessingMachineBounds.lean @@ -0,0 +1,108 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.PreprocessingPaddingOffsets +import OAI.Computability.MinUncut.PCP.ExpanderRowControl + +namespace OAI + +section +namespace MinUncutGames.Foundations.PCP.PreprocessingMachineBounds +open PreprocessingRegularTables PreprocessingCloudIndex +open MinUncutGames.Foundations.Complexity +open scoped BigOperators + +def inputLength (t : GraphTables.Table) : Nat := (GraphTables.tableBits t).length + +theorem cloudSize_le_input (t : GraphTables.Table) (v : Fin t.vertices) : + cloudSize t v ≤ inputLength t := + (cloudSize_le_darts t v).trans (GraphTables.darts_le_tableBits_length t) + +theorem cloudTotal_le_input (t : GraphTables.Table) (v : Fin t.vertices) : + cloudSize t v + padding t v ≤ ExpanderFamily.growth * inputLength t := by + rw [cloudSize_add_padding] + exact (PreprocessingLevels.cloudPaddedSize_bounds _).2.trans + (Nat.mul_le_mul_left _ (cloudSize_le_input t v)) + +theorem level_le_input (t : GraphTables.Table) (v : Fin t.vertices) : + PreprocessingLevels.boundedLevel (cloudSize t v) ≤ inputLength t := + (PreprocessingLevels.boundedLevel_le_input _).trans (cloudSize_le_input t v) + +theorem regularVertices_le_input (t : GraphTables.Table) : + vertexCount t (padding t) ≤ ExpanderFamily.growth * inputLength t := + (vertexCount_le t).trans + (Nat.mul_le_mul_left _ (GraphTables.darts_le_tableBits_length t)) + +theorem offset_le_sum {n : Nat} (p : Fin n → Nat) (k : Nat) : + PreprocessingPaddingOffsets.offset p k ≤ ∑ v, p v := by + have hfull : (List.finRange n).take n = List.finRange n := by simp + have hsplit : PreprocessingPaddingOffsets.offset p k + + (((List.finRange n).drop k).map p).sum = + PreprocessingPaddingOffsets.offset p n := by + simp only [PreprocessingPaddingOffsets.offset, hfull] + rw [← List.sum_append, ← List.map_append, List.take_append_drop] + rw [PreprocessingPaddingOffsets.offset_all] at hsplit + omega + +theorem prefix_le_input (t : GraphTables.Table) (k : Nat) : + PreprocessingPaddingOffsets.offset (padding t) k ≤ + ExpanderFamily.growth * inputLength t := by + have hsum : (∑ v, padding t v) ≤ vertexCount t (padding t) := by + unfold vertexCount + omega + exact (offset_le_sum (padding t) k).trans (hsum.trans (regularVertices_le_input t)) + +noncomputable def tablePolynomial (a b : Nat) : Polynomial Nat := + Polynomial.C a * Polynomial.X + Polynomial.C b * Polynomial.X + 2 + + (Polynomial.C b * Polynomial.X) * + (Polynomial.C a * Polynomial.X + Polynomial.C b * Polynomial.X + 8192) + +theorem tableBits_le_of_counts (t : GraphTables.Table) (a b L : Nat) + (hv : t.vertices ≤ a * L) (he : t.darts ≤ b * L) : + (GraphTables.tableBits t).length ≤ (tablePolynomial a b).eval L := by + have hsum := Nat.add_le_add hv he + have hprod := Nat.mul_le_mul he (Nat.add_le_add_right hsum 8192) + have h := (GraphTables.tableBits_length_le t).trans + (Nat.add_le_add (Nat.add_le_add_right hsum 2) hprod) + simpa only [tablePolynomial, Polynomial.eval_add, Polynomial.eval_mul, + Polynomial.eval_C, Polynomial.eval_X, Polynomial.eval_ofNat] using h + +noncomputable def regularPolynomial : Polynomial Nat := + tablePolynomial ExpanderFamily.growth (ExpanderFamily.growth * (internalDegree + 1)) + +theorem regularBits_le (H : BaseTable) (t : GraphTables.Table) : + (PortTables.tableBits (regularize H t)).length ≤ + regularPolynomial.eval (inputLength t) := by + have hv : (PortTables.graphTable (regularize H t)).vertices ≤ + ExpanderFamily.growth * inputLength t := regularVertices_le_input t + have he : (PortTables.graphTable (regularize H t)).darts ≤ + (ExpanderFamily.growth * (internalDegree + 1)) * inputLength t := by + change vertexCount t (padding t) * (internalDegree + 1) ≤ _ + calc + _ ≤ (ExpanderFamily.growth * inputLength t) * (internalDegree + 1) := + Nat.mul_le_mul_right _ hv + _ = _ := by ac_rfl + exact tableBits_le_of_counts (PortTables.graphTable (regularize H t)) _ _ _ hv he + +noncomputable def rotorPolynomial (q : Nat) : Polynomial Nat := + (Polynomial.C (ExpanderFamily.growth * q) * Polynomial.X) * + (Polynomial.C (ExpanderFamily.growth * q) * Polynomial.X + 1) + +theorem cloudRotorBits_le (t : GraphTables.Table) (v : Fin t.vertices) {q : Nat} + (table : ExpanderTables.Table (cloudSize t v + padding t v) q) : + (encodeWords (ExpanderTableWords.rotationWords table)).length ≤ + (rotorPolynomial q).eval (inputLength t) := by + have hd : (cloudSize t v + padding t v) * q ≤ + (ExpanderFamily.growth * q) * inputLength t := by + calc + _ ≤ (ExpanderFamily.growth * inputLength t) * q := + Nat.mul_le_mul_right _ (cloudTotal_le_input t v) + _ = _ := by ac_rfl + have h := (ExpanderTableWords.encode_rotationWords_length_le table).trans + (Nat.mul_le_mul hd (Nat.add_le_add_right hd 1)) + simpa only [rotorPolynomial, Polynomial.eval_mul, Polynomial.eval_add, + Polynomial.eval_C, Polynomial.eval_X, Polynomial.eval_one] using h + +end MinUncutGames.Foundations.PCP.PreprocessingMachineBounds + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/RawInitialMachineBudget.lean b/lean/OAI/Computability/MinUncut/Machines/RawInitialMachineBudget.lean new file mode 100644 index 0000000000000000000000000000000000000000..fac8151678ef37478df6667f7a88f22002cc83e8 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/RawInitialMachineBudget.lean @@ -0,0 +1,103 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.GraphTableComplexity + +namespace OAI + +section +namespace MinUncutGames.Foundations.PCP.RawInitialMachineBudget + +open Target Complexity + +def nameSum {n : Nat} (c : Clause n) : Nat := + (c)[0].variableIndex.val + (c)[1].variableIndex.val + (c)[2].variableIndex.val + +def bodyTime {n : Nat} (i : Nat) (c : Clause n) : Nat := + 6 * n + 18 * i + 2 * nameSum c + + 2 * (encodeWords (Complexity.clauseWords c)).length + 63 + +def loopTime {n : Nat} (i : Nat) : List (Clause n) → Nat + | [] => 1 + | c :: cs => bodyTime i c + loopTime (i + 1) cs + +theorem nameSum_le {n : Nat} (c : Clause n) : nameSum c ≤ 3 * n := by + have h0 := (c)[0].variableIndex.isLt + have h1 := (c)[1].variableIndex.isLt + have h2 := (c)[2].variableIndex.isLt + unfold nameSum + omega + +theorem bodyTime_le {n : Nat} (i : Nat) (c : Clause n) : + bodyTime i c ≤ 18 * n + 18 * i + 81 := by + have hn := nameSum_le c + have hb := clauseBits_length_le c + unfold bodyTime + omega + +theorem loopTime_le {n : Nat} (i : Nat) (cs : List (Clause n)) : + loopTime i cs ≤ cs.length * (18 * n + 18 * (i + cs.length) + 81) + 1 := by + induction cs generalizing i with + | nil => simp [loopTime] + | cons c cs ih => + have hc := bodyTime_le i c + have ht := ih (i + 1) + have hbound : bodyTime i c ≤ 18 * n + 18 * (i + (c :: cs).length) + 81 := by + simp only [List.length_cons] + omega + have hsame : 18 * n + 18 * (i + 1 + cs.length) + 81 = + 18 * n + 18 * (i + (c :: cs).length) + 81 := by + simp only [List.length_cons] + omega + rw [hsame] at ht + rw [loopTime] + calc + _ ≤ (18 * n + 18 * (i + (c :: cs).length) + 81) + + (cs.length * (18 * n + 18 * (i + (c :: cs).length) + 81) + 1) := + Nat.add_le_add hbound ht + _ = _ := by rw [List.length_cons]; ring + +theorem input_header_bound (F : Formula) : + F.«variables» + F.clauses.length + 2 ≤ (formulaBits F).length := by + simp only [formulaBits, formulaWords, encodeWords_append, List.length_append, + encodeWords, encodeWord_length, List.length_nil] + omega + +theorem graph_size_bound (F : Formula) : + (RawInitialTables.table F).vertices + (RawInitialTables.table F).darts ≤ + 7 * (formulaBits F).length := by + rw [RawInitialTables.initial_size] + have h := input_header_bound F + omega + +def fullBudget (F : Formula) : Nat := + 6 * F.«variables» + 10 * F.clauses.length + 30 + loopTime 0 F.clauses + + (GraphTables.tableBits (RawInitialTables.table F)).length + +noncomputable def timePolynomial : Polynomial Nat := + Polynomial.C 100 * Polynomial.X ^ 2 + Polynomial.C 60000 * Polynomial.X + + Polynomial.C 100 + +theorem timePolynomial_eval (N : Nat) : + timePolynomial.eval N = 100 * N ^ 2 + 60000 * N + 100 := by + simp [timePolynomial] + +theorem fullBudget_le (F : Formula) : + fullBudget F ≤ timePolynomial.eval (formulaBits F).length := by + have hinput := input_header_bound F + have hloop := loopTime_le 0 F.clauses + have hout := GraphTableComplexity.bits_le_of_size_le (RawInitialTables.table F) + (graph_size_bound F) + rw [GraphTableComplexity.encodingPolynomial_eval] at hout + simp only [Nat.zero_add] at hloop + have hm : F.clauses.length ≤ (formulaBits F).length := by omega + have hcoefficient : 18 * F.«variables» + 18 * F.clauses.length + 81 ≤ + 18 * (formulaBits F).length + 81 := by omega + have hproduct := Nat.mul_le_mul hm hcoefficient + rw [timePolynomial_eval] + unfold fullBudget + nlinarith + +end MinUncutGames.Foundations.PCP.RawInitialMachineBudget + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/RawInitialMachineFinish.lean b/lean/OAI/Computability/MinUncut/Machines/RawInitialMachineFinish.lean new file mode 100644 index 0000000000000000000000000000000000000000..75797d55a206ee77ccd030dd558e249fb01f8ec6 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/RawInitialMachineFinish.lean @@ -0,0 +1,786 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineRegularOwnerProgram +import OAI.Computability.MinUncut.Machines.RawInitialMachinePhases + +namespace OAI + +section +namespace MinUncutGames.Foundations.PCP.RawInitialMachineFinish + +open Turing Complexity RawInitialMachineModel RawInitialMachinePhases + +def tapes (varsWord counter index reversed output : List Bool) : Tape → List Bool + | .«variables» => varsWord + | .counter => counter + | .index => index + | .reversed => reversed + | .output => output + | _ => [] + +def finishTapes (n m : Nat) (rev : List Bool) : Tape → List Bool := + tapes (encodeWord n) [false] (encodeWord m) rev [] + +private 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 trueRelationWords : + GraphTables.relationWords (GraphTables.relationOf (fun _ _ => true)) = + List.replicate 4096 1 := by + unfold GraphTables.relationWords + rw [GraphTables.relationOf, Vector.toList_ofFn, List.map_ofFn] + exact List.ofFn_const 4096 1 + +theorem dummyBits_length (n m : Nat) : + (encodeWords (RawInitialRows.dummyWords n m)).length = n + 7 * m + 8194 := by + rw [encodeWords_length] + simp only [RawInitialRows.dummyWords, List.sum_append, List.sum_cons, + List.sum_nil, List.length_append, List.length_cons, List.length_nil, + List.sum_replicate, List.length_replicate, nsmul_eq_mul, Nat.mul_one] + omega + +private theorem update_reversed (varsWord counter index rev out word : List Bool) : + Function.update (tapes varsWord counter index rev out) .reversed word = + tapes varsWord counter index word out := by + funext k + cases k <;> simp [tapes] + +theorem cleanupTrace (n m : Nat) (rev : List Bool) (state : State) : + (MachineComposition.advance (TM2.step program))^[n + m + 6] + (some ⟨some (.cleanupFinal 0), state, finishTapes n m rev⟩) = + some ⟨some .reset, (state.1, none), tapes [] [] [] rev []⟩ := by + have h0 := (cleanupFinalInTime 0 (finishTapes n m rev) state).evals_in_steps + change (MachineComposition.advance (TM2.step program))^[(encodeWord n).length + 1] + (some ⟨some (.cleanupFinal 0), state, finishTapes n m rev⟩) = _ at h0 + rw [encodeWord_length] at h0 + have f0 : Function.update (finishTapes n m rev) .«variables» [] = + tapes [] [false] (encodeWord m) rev [] := by + funext k + cases k <;> simp [finishTapes, tapes] + change (MachineComposition.advance (TM2.step program))^[n + 2] + (some ⟨some (.cleanupFinal 0), state, finishTapes n m rev⟩) = + some ⟨some (.cleanupFinal 1), (state.1, none), + Function.update (finishTapes n m rev) .«variables» []⟩ at h0 + rw [f0] at h0 + have h1 := (cleanupFinalInTime 1 (tapes [] [false] (encodeWord m) rev []) + (state.1, none)).evals_in_steps + change (MachineComposition.advance (TM2.step program))^[2] + (some ⟨some (.cleanupFinal 1), (state.1, none), + tapes [] [false] (encodeWord m) rev []⟩) = _ at h1 + have f1 : Function.update (tapes [] [false] (encodeWord m) rev []) .counter [] = + tapes [] [] (encodeWord m) rev [] := by + funext k + cases k <;> simp [tapes] + change (MachineComposition.advance (TM2.step program))^[2] + (some ⟨some (.cleanupFinal 1), (state.1, none), tapes [] [false] (encodeWord m) rev []⟩) = + some ⟨some (.cleanupFinal 2), (state.1, none), + Function.update (tapes [] [false] (encodeWord m) rev []) .counter []⟩ at h1 + rw [f1] at h1 + have h2 := (cleanupFinalInTime 2 (tapes [] [] (encodeWord m) rev []) + (state.1, none)).evals_in_steps + change (MachineComposition.advance (TM2.step program))^[(encodeWord m).length + 1] + (some ⟨some (.cleanupFinal 2), (state.1, none), + tapes [] [] (encodeWord m) rev []⟩) = _ at h2 + rw [encodeWord_length] at h2 + have f2 : Function.update (tapes [] [] (encodeWord m) rev []) .index [] = + tapes [] [] [] rev [] := by + funext k + cases k <;> simp [tapes] + change (MachineComposition.advance (TM2.step program))^[m + 2] + (some ⟨some (.cleanupFinal 2), (state.1, none), tapes [] [] (encodeWord m) rev []⟩) = + some ⟨some .reset, (state.1, none), + Function.update (tapes [] [] (encodeWord m) rev []) .index []⟩ at h2 + rw [f2] at h2 + have total := trace_trans _ (trace_trans _ h0 h1) h2 + simpa only [show (n + 2) + 2 + (m + 2) = n + m + 6 by omega] using total + +private theorem resetReverseTrace (rev : List Bool) (state : State) : + (MachineComposition.advance (TM2.step program))^[rev.length + 2] + (some ⟨some .reset, state, tapes [] [] [] rev []⟩) = + some (haltList machine rev.reverse) := by + have reset : (MachineComposition.advance (TM2.step program))^[1] + (some ⟨some .reset, state, tapes [] [] [] rev []⟩) = + some ⟨some .finalReverse, initialState, tapes [] [] [] rev []⟩ := rfl + have transfer := (Reduction.MachineTransfer.transferAtInTime + .reversed .output (by decide) id false .finalReverse none program rfl + (tapes [] [] [] rev []) (false, false, false) none).evals_in_steps + change (MachineComposition.advance (TM2.step program))^[rev.length + 1] + (some ⟨some .finalReverse, initialState, tapes [] [] [] rev []⟩) = _ at transfer + have frame : Reduction.MachineTransfer.tapesAt .reversed .output + (tapes [] [] [] rev []) [] (rev.reverse.map id ++ []) = + (haltList machine rev.reverse).stk := by + funext k + change Tape at k + cases k <;> simp [Reduction.MachineTransfer.tapesAt, tapes, haltList, machine] + rfl + change (MachineComposition.advance (TM2.step program))^[rev.length + 1] + (some ⟨some .finalReverse, initialState, tapes [] [] [] rev []⟩) = + some ⟨none, initialState, Reduction.MachineTransfer.tapesAt .reversed .output + (tapes [] [] [] rev []) [] (rev.reverse.map id ++ [])⟩ at transfer + rw [frame] at transfer + have total := trace_trans _ reset transfer + rw [show 1 + (rev.length + 1) = rev.length + 2 by omega] at total + change (MachineComposition.advance (TM2.step program))^[rev.length + 2] + (some ⟨some .reset, state, tapes [] [] [] rev []⟩) = + some ⟨none, initialState, (haltList machine rev.reverse).stk⟩ + exact total + +private theorem update_finish (n m : Nat) (rev word : List Bool) : + Function.update (finishTapes n m rev) .reversed word = finishTapes n m word := + update_reversed _ _ _ _ _ _ + +private theorem copyFinishTrace (n m r : Nat) (rev : List Bool) (phase : CopyPhase) + (hsource : finishTapes n m rev (copySource phase) = encodeWord r) (state : State) : + (MachineComposition.advance (TM2.step program))^[2 * r + 2] + (some ⟨some (.scan phase), state, finishTapes n m rev⟩) = + some ⟨some (copyNext phase), (state.1, none), + finishTapes n m (List.replicate (copyScale phase * r) true ++ rev)⟩ := by + have h := (copyInTime phase (finishTapes n m rev) r [] + (by simpa only [List.append_nil] using hsource) rfl state).evals_in_steps + change (MachineComposition.advance (TM2.step program))^[2 * r + 2] + (some ⟨some (.scan phase), state, finishTapes n m rev⟩) = + some ⟨some (copyNext phase), (state.1, none), + Function.update (finishTapes n m rev) .reversed + (List.replicate (copyScale phase * r) true ++ rev)⟩ at h + rw [update_finish] at h + exact h + +private theorem closeDummyTailTrace (n m : Nat) (rev : List Bool) (state : State) : + (MachineComposition.advance (TM2.step program))^[1] + (some ⟨some .closeDummyTail, state, finishTapes n m rev⟩) = + some ⟨some (.scan .dummyReverse), state, finishTapes n m (false :: rev)⟩ := by + change some (TM2.stepAux (program .closeDummyTail) state (finishTapes n m rev)) = _ + simp only [program, TM2.stepAux] + congr 2 + exact update_finish _ _ _ _ + +private theorem closeDummyReverseTrace (n m : Nat) (rev : List Bool) (state : State) : + (MachineComposition.advance (TM2.step program))^[1] + (some ⟨some .closeDummyReverse, state, finishTapes n m rev⟩) = + some ⟨some .dummyRelation, state, finishTapes n m (false :: rev)⟩ := by + change some (TM2.stepAux (program .closeDummyReverse) state (finishTapes n m rev)) = _ + simp only [program, TM2.stepAux] + congr 2 + exact update_finish _ _ _ _ + +private theorem dummyRelationTrace (n m : Nat) (rev : List Bool) (state : State) : + (MachineComposition.advance (TM2.step program))^[1] + (some ⟨some .dummyRelation, state, finishTapes n m rev⟩) = + some ⟨some (.cleanupFinal 0), state, + finishTapes n m ((encodeWords (List.replicate 4096 1)).reverse ++ rev)⟩ := by + change some (TM2.stepAux (program .dummyRelation) state (finishTapes n m rev)) = _ + rw [program, Reduction.MachineSubstitution.stepAux_pushWord, trueRelationWords] + simp only [TM2.stepAux] + congr 2 + exact update_finish _ _ _ _ + +theorem dummyTrace (n m : Nat) (rev : List Bool) (state : State) : + (MachineComposition.advance (TM2.step program))^[2 * n + 4 * m + 9] + (some ⟨some (.scan .dummyVariables), state, finishTapes n m rev⟩) = + some ⟨some (.cleanupFinal 0), (state.1, none), + finishTapes n m ((encodeWords (RawInitialRows.dummyWords n m)).reverse ++ rev)⟩ := by + let a := List.replicate n true ++ rev + let b := List.replicate m true ++ a + let c := false :: b + let d := List.replicate (6 * m) true ++ c + let e := false :: d + have h0 := copyFinishTrace n m n rev .dummyVariables rfl state + simp only [copyScale, copyNext, Nat.one_mul] at h0 + have h1 := copyFinishTrace n m m a .dummyIndex rfl (state.1, none) + simp only [copyScale, copyNext, Nat.one_mul] at h1 + have h2 := closeDummyTailTrace n m b (state.1, none) + have h3 := copyFinishTrace n m m c .dummyReverse rfl (state.1, none) + simp only [copyScale, copyNext] at h3 + have h4 := closeDummyReverseTrace n m d (state.1, none) + have h5 := dummyRelationTrace n m e (state.1, none) + have total := trace_trans _ (trace_trans _ (trace_trans _ + (trace_trans _ (trace_trans _ h0 h1) h2) h3) h4) h5 + have output : (encodeWords (List.replicate 4096 1)).reverse ++ e = + (encodeWords (RawInitialRows.dummyWords n m)).reverse ++ rev := by + have rep : List.replicate m true ++ (List.replicate n true ++ rev) = + List.replicate (n + m) true ++ rev := by + rw [← List.append_assoc, ← List.replicate_add, Nat.add_comm m n] + simp only [RawInitialRows.dummyWords, encodeWords_append, encodeWords, + List.append_nil, List.reverse_append, + encodeWord, List.reverse_cons, + List.reverse_replicate, List.append_assoc, List.singleton_append, + a, b, c, d, e] + rw [rep] + simp only [List.reverse_nil, List.nil_append, List.cons_append] + rw [output] at total + simpa only [show (((((2 * n + 2) + (2 * m + 2)) + 1) + (2 * m + 2)) + 1) + 1 = + 2 * n + 4 * m + 9 by omega] using total + +theorem finishTrace (n m : Nat) (rev : List Bool) (state : State) : + (MachineComposition.advance (TM2.step program))^[ + 3 * n + 5 * m + 17 + (encodeWords (RawInitialRows.dummyWords n m)).length + rev.length] + (some ⟨some (.scan .dummyVariables), state, finishTapes n m rev⟩) = + some (haltList machine (rev.reverse ++ encodeWords (RawInitialRows.dummyWords n m))) := by + let emitted := (encodeWords (RawInitialRows.dummyWords n m)).reverse ++ rev + have total := trace_trans _ (trace_trans _ (dummyTrace n m rev state) + (cleanupTrace n m emitted (state.1, none))) + (resetReverseTrace emitted (state.1, none)) + have hout : emitted.reverse = rev.reverse ++ encodeWords (RawInitialRows.dummyWords n m) := by + simp only [emitted, List.reverse_append, List.reverse_reverse] + rw [hout] at total + have htime : (2 * n + 4 * m + 9) + (n + m + 6) + (emitted.length + 2) = + 3 * n + 5 * m + 17 + (encodeWords (RawInitialRows.dummyWords n m)).length + rev.length := by + simp only [emitted, List.length_append, List.length_reverse] + omega + rwa [htime] at total + +def finishInTime (n m : Nat) (rev : List Bool) (state : State) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (.scan .dummyVariables), state, finishTapes n m rev⟩ + (some (haltList machine (rev.reverse ++ encodeWords (RawInitialRows.dummyWords n m)))) + (4 * n + 12 * m + 8211 + rev.length) where + steps := 4 * n + 12 * m + 8211 + rev.length + evals_in_steps := by + have h := finishTrace n m rev state + rw [dummyBits_length] at h + rw [show 3 * n + 5 * m + 17 + (n + 7 * m + 8194) + rev.length = + 4 * n + 12 * m + 8211 + rev.length by omega] at h + exact h + steps_le_m := Nat.le_refl _ + +end MinUncutGames.Foundations.PCP.RawInitialMachineFinish + +end +section +namespace MinUncutGames.Foundations.PCP.RawInitialMachineLoop + +open Turing Target Complexity RawInitialMachineModel RawInitialMachineLoopData +open RawInitialMachineBudget RawInitialMachineBody RawInitialMachineFinish + +def finalSigns {n : Nat} (incoming : RawInitialMachineModel.Signs) : + List (Clause n) → RawInitialMachineModel.Signs + | [] => incoming + | c :: cs => finalSigns (RawInitialRows.clauseSigns c) cs + +private 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 empty_loopTapes (n i : Nat) (rev : List Bool) : + loopTapes n i 0 [] rev = finishTapes n i rev := by + funext tape + cases tape <;> rfl + +theorem loopTrace {n : Nat} (i : Nat) (cs : List (Clause n)) + (rev : List Bool) (state : State) : + (MachineComposition.advance (TM2.step program))^[loopTime i cs] + (some ⟨some .guard, state, loopTapes n i cs.length (clauseInput cs) rev⟩) = + some ⟨some (.scan .dummyVariables), (finalSigns state.1 cs, none), + finishTapes n (i + cs.length) ((encodeWords (clauseOutput n i cs)).reverse ++ rev)⟩ := by + induction cs generalizing i rev state with + | nil => + have h := RawInitialMachineBody.guardTrace_zero n i [] rev state + rw [empty_loopTapes] at h + simpa only [loopTime, List.length_nil, clauseInput_nil, clauseOutput_nil, + finalSigns, encodeWords, List.reverse_nil, List.nil_append, Nat.add_zero, + empty_loopTapes] using h + | cons c cs ih => + have first := bodyTrace i cs.length c (clauseInput cs) rev state + have rest := ih (i + 1) + ((encodeWords (RawInitialRows.clauseWords n i + (RawInitialRows.clauseNames c) (RawInitialRows.clauseSigns c))).reverse ++ rev) + (RawInitialRows.clauseSigns c, none) + have total := trace_trans _ first rest + have hi : i + 1 + cs.length = i + (cs.length + 1) := by omega + simpa only [loopTime, List.length_cons, clauseInput_cons, clauseOutput_cons, + encodeWords_append, List.reverse_append, List.append_assoc, finalSigns, hi] using total + +def loopInTime {n : Nat} (i : Nat) (cs : List (Clause n)) + (rev : List Bool) (state : State) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some .guard, state, loopTapes n i cs.length (clauseInput cs) rev⟩ + (some ⟨some (.scan .dummyVariables), (finalSigns state.1 cs, none), + finishTapes n (i + cs.length) ((encodeWords (clauseOutput n i cs)).reverse ++ rev)⟩) + (loopTime i cs) where + steps := loopTime i cs + evals_in_steps := loopTrace i cs rev state + steps_le_m := Nat.le_refl _ + +end MinUncutGames.Foundations.PCP.RawInitialMachineLoop + +end +section +namespace MinUncutGames.Foundations.PCP.MachineRawInitialTable + +open Turing Target Complexity RawInitialMachineModel RawInitialMachineLoopData +open RawInitialMachineBudget RawInitialMachineLoop + +private 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] + +def prefixBits (F : Formula) : List Bool := + encodeWords ([F.«variables» + F.clauses.length + 1, 6 * F.clauses.length + 1] ++ + clauseOutput F.«variables» 0 F.clauses) + +theorem outputBits (F : Formula) : + GraphTables.tableBits (RawInitialTables.table F) = prefixBits F ++ + encodeWords (RawInitialRows.dummyWords F.«variables» F.clauses.length) := by + change encodeWords (GraphTables.tableWords (RawInitialTables.table F)) = _ + rw [tableWords_decomposition, encodeWords_append] + rfl + +theorem machineTrace (F : Formula) : + (MachineComposition.advance (TM2.step program))^[fullBudget F] + (some (initList machine (formulaBits F))) = + some (haltList machine (GraphTables.tableBits (RawInitialTables.table F))) := by + have startup := RawInitialMachineStart.formulaStartTrace F + rw [startTapes_eq] at startup + have loop := loopTrace 0 F.clauses + (encodeWords [F.«variables» + F.clauses.length + 1, 6 * F.clauses.length + 1]).reverse + initialState + have hprefix : (encodeWords (clauseOutput F.«variables» 0 F.clauses)).reverse ++ + (encodeWords [F.«variables» + F.clauses.length + 1, 6 * F.clauses.length + 1]).reverse = + (prefixBits F).reverse := by + simp only [prefixBits, encodeWords_append, List.reverse_append] + rw [hprefix, Nat.zero_add] at loop + have finish := RawInitialMachineFinish.finishTrace F.«variables» F.clauses.length + (prefixBits F).reverse (finalSigns initialState.1 F.clauses, none) + rw [List.reverse_reverse, ← outputBits F] at finish + have total := trace_trans _ (trace_trans _ startup loop) finish + have time : (3 * F.«variables» + 5 * F.clauses.length + 13 + loopTime 0 F.clauses) + + (3 * F.«variables» + 5 * F.clauses.length + 17 + + (encodeWords (RawInitialRows.dummyWords F.«variables» F.clauses.length)).length + + (prefixBits F).reverse.length) = fullBudget F := by + rw [fullBudget, outputBits, List.length_append, List.length_reverse] + omega + simpa only [time] using total + +def outputsInTime (F : Formula) : + TM2OutputsInTime machine (formulaBits F) + (some (GraphTables.tableBits (RawInitialTables.table F))) + (timePolynomial.eval (formulaBits F).length) where + steps := fullBudget F + evals_in_steps := machineTrace F + steps_le_m := fullBudget_le F + +noncomputable def computableInPolyTime : + TM2ComputableInPolyTime formulaEncoding.encode GraphTables.encoding.encode + RawInitialTables.table where + tm := machine + inputAlphabet := Equiv.refl Bool + outputAlphabet := Equiv.refl Bool + time := timePolynomial + outputsFun F := by + change TM2OutputsInTime machine ((formulaBits F).map id) + (some ((GraphTables.tableBits (RawInitialTables.table F)).map id)) + (timePolynomial.eval (formulaBits F).length) + have hi := @List.map_id (machine.Γ machine.k₀) (formulaBits F) + have ho := @List.map_id (machine.Γ machine.k₁) + (GraphTables.tableBits (RawInitialTables.table F)) + rw [hi, ho] + exact outputsInTime F + +end MinUncutGames.Foundations.PCP.MachineRawInitialTable + +end +section +namespace MinUncutGames.Foundations.Complexity.FinalCNFMachine + +open Turing +open PCP + +abbrev Buffer (N : Nat) := MachineFixedBlockMap.Buffer N + +section RelationReader + +variable {K Λ σ : Type} {N : Nat} + +def readUnarySlots (source : K) : List (Fin N) → + TM2.Stmt (fun _ : K => Bool) Λ (σ × Buffer N) → + TM2.Stmt (fun _ : K => Bool) Λ (σ × Buffer N) + | [], next => next + | i :: slots, next => + .pop source (fun state head => + (state.1, Function.update state.2 i (head.getD false))) + (.branch (fun state => state.2 i) + (.pop source (fun state _ => state) (readUnarySlots source slots next)) + (readUnarySlots source slots next)) + +def unaryBits (slots : List (Fin N)) (bits : Buffer N) : List Bool := + slots.flatMap fun i => encodeWord (GraphTables.bitWord (bits i)) + +theorem unaryBits_eq_encodeWords (slots : List (Fin N)) (bits : Buffer N) : + unaryBits slots bits = encodeWords (slots.map fun i => GraphTables.bitWord (bits i)) := by + induction slots with + | nil => rfl + | cons i slots ih => simpa only [unaryBits, List.flatMap_cons, List.map_cons, + encodeWords] using congrArg (encodeWord (GraphTables.bitWord (bits i)) ++ ·) ih + +theorem unaryBits_length_le (slots : List (Fin N)) (bits : Buffer N) : + (unaryBits slots bits).length ≤ 2 * slots.length := by + induction slots with + | nil => simp [unaryBits] + | cons i slots ih => + have hi : (encodeWord (GraphTables.bitWord (bits i))).length ≤ 2 := by + cases bits i <;> simp [GraphTables.bitWord, encodeWord_length] + simp only [unaryBits, List.flatMap_cons, List.length_append, List.length_cons] at * + omega + +theorem statementPushBound_readUnarySlots (source : K) (slots : List (Fin N)) + (next : TM2.Stmt (fun _ : K => Bool) Λ (σ × Buffer N)) : + Runtime.statementPushBound (readUnarySlots source slots next) = + Runtime.statementPushBound next := by + induction slots with + | nil => rfl + | cons i slots ih => + simp only [readUnarySlots, Runtime.statementPushBound, ih, max_self] + +variable [DecidableEq K] + +theorem stepAux_readUnarySlots (source : K) (slots : List (Fin N)) + (next : TM2.Stmt (fun _ : K => Bool) Λ (σ × Buffer N)) + (ambient : σ) (bits buffer : Buffer N) (tapes : K → List Bool) + (suffix : List Bool) : + TM2.stepAux (readUnarySlots source slots next) (ambient, buffer) + (Function.update tapes source (unaryBits slots bits ++ suffix)) = + TM2.stepAux next (ambient, MachineFixedBlockMap.fill slots bits buffer) + (Function.update tapes source suffix) := by + induction slots generalizing buffer tapes with + | nil => simp [readUnarySlots, unaryBits, MachineFixedBlockMap.fill] + | cons i slots ih => + cases hi : bits i <;> + simp only [readUnarySlots, unaryBits, List.flatMap_cons, hi, + GraphTables.bitWord, Bool.false_eq_true, ite_false, ite_true, encodeWord, + List.replicate_zero, List.replicate_succ, List.nil_append, + List.cons_append, + TM2.stepAux, Function.update_self, List.head?_cons, Option.getD_some, + List.tail_cons, Function.update_idem, MachineFixedBlockMap.fill, + List.foldl_cons] + · simpa [unaryBits, MachineFixedBlockMap.fill, hi, encodeWord, GraphTables.bitWord] using + ih (Function.update buffer i false) tapes + · simpa [unaryBits, MachineFixedBlockMap.fill, hi, encodeWord, GraphTables.bitWord] using + ih (Function.update buffer i true) tapes + +theorem stepAux_readUnaryAll (source : K) + (next : TM2.Stmt (fun _ : K => Bool) Λ (σ × Buffer N)) + (state : σ × Buffer N) (bits : Buffer N) (tapes : K → List Bool) + (suffix : List Bool) + (hinput : tapes source = unaryBits (List.ofFn id) bits ++ suffix) : + TM2.stepAux (readUnarySlots source (List.ofFn id) next) state tapes = + TM2.stepAux next (state.1, bits) (Function.update tapes source suffix) := by + have h := stepAux_readUnarySlots source (List.ofFn id) next state.1 bits state.2 tapes suffix + have hin : Function.update tapes source (unaryBits (List.ofFn id) bits ++ suffix) = tapes := by + simpa only [← hinput] using Function.update_eq_self source tapes + rw [hin, MachineFixedBlockMap.fill_all] at h + exact h + +def unaryBlockMapAt {M : Nat} (source destination : K) (F : Buffer N → Buffer M) + (exit : Option Λ) : TM2.Stmt (fun _ : K => Bool) Λ (σ × Buffer N) := + readUnarySlots source (List.ofFn id) + (MachineFixedBlockMap.writeSlots destination (fun state => F state.2) + (List.ofFn id).reverse + (.load (fun state => (state.1, MachineFixedBlockMap.emptyBuffer N)) + (MachineFixedBlockMap.finishAt exit))) + +theorem stepAux_unaryBlockMapAt {M : Nat} (source destination : K) + (F : Buffer N → Buffer M) (exit : Option Λ) (hne : source ≠ destination) + (state : σ × Buffer N) (bits : Buffer N) (tapes : K → List Bool) (suffix : List Bool) + (hinput : tapes source = unaryBits (List.ofFn id) bits ++ suffix) : + TM2.stepAux (unaryBlockMapAt source destination F exit) state tapes = + { l := exit, var := (state.1, MachineFixedBlockMap.emptyBuffer N), + stk := Function.update (Function.update tapes source suffix) destination + (List.ofFn (F bits) ++ tapes destination) } := by + unfold unaryBlockMapAt + rw [stepAux_readUnaryAll source _ state bits tapes suffix hinput, + MachineFixedBlockMap.stepAux_writeSlots] + simp only [List.map_reverse, List.map_ofFn, Function.comp_id, List.reverse_reverse, + Function.update_of_ne (Ne.symm hne), TM2.stepAux] + cases exit <;> rfl + +theorem step_unaryBlockMapAt {M : Nat} (source destination : K) + (F : Buffer N → Buffer M) (exit : Option Λ) (hne : source ≠ destination) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (σ × Buffer N)) + (label : Λ) (atLabel : program label = unaryBlockMapAt source destination F exit) + (state : σ × Buffer N) (bits : Buffer N) (tapes : K → List Bool) (suffix : List Bool) + (hinput : tapes source = unaryBits (List.ofFn id) bits ++ suffix) : + TM2.step program ⟨some label, state, tapes⟩ = + some ⟨exit, (state.1, MachineFixedBlockMap.emptyBuffer N), + Function.update (Function.update tapes source suffix) destination + (List.ofFn (F bits) ++ tapes destination)⟩ := by + simp only [TM2.step, atLabel, + stepAux_unaryBlockMapAt source destination F exit hne state bits tapes suffix hinput] + +def unaryBlockInTime {M : Nat} (source destination : K) + (F : Buffer N → Buffer M) (exit : Option Λ) (hne : source ≠ destination) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (σ × Buffer N)) + (label : Λ) (atLabel : program label = unaryBlockMapAt source destination F exit) + (state : σ × Buffer N) (bits : Buffer N) (tapes : K → List Bool) (suffix : List Bool) + (hinput : tapes source = unaryBits (List.ofFn id) bits ++ suffix) : + StateTransition.EvalsToInTime (TM2.step program) ⟨some label, state, tapes⟩ + (some ⟨exit, (state.1, MachineFixedBlockMap.emptyBuffer N), + Function.update (Function.update tapes source suffix) destination + (List.ofFn (F bits) ++ tapes destination)⟩) 1 where + steps := 1 + evals_in_steps := step_unaryBlockMapAt source destination F exit hne program label + atLabel state bits tapes suffix hinput + steps_le_m := Nat.le_refl _ + +end RelationReader + +theorem unaryBits_relation (relation : GraphTables.RelationTable) : + unaryBits (List.ofFn id) (fun i => relation[i]) = + encodeWords (GraphTables.relationWords relation) := by + have h : List.ofFn (fun i : Fin 4096 => relation[i]) = relation.toList := by + change List.ofFn (fun i : Fin 4096 => relation[i.val]) = relation.toList + rw [← Vector.toList_ofFn, Vector.ofFn_getElem] + rw [unaryBits_eq_encodeWords] + unfold GraphTables.relationWords + rw [← h] + simp only [List.map_ofFn, Function.comp_def, id_eq] + +def readerStateEquiv (σ : Type) (N : Nat) : + (((σ × Unit) × Option Bool) × Buffer N) ≃ (((σ × Buffer N) × Unit) × Option Bool) where + toFun state := (((state.1.1.1, state.2), state.1.1.2), state.1.2) + invFun state := (((state.1.1.1, state.1.2), state.2), state.1.1.2) + left_inv _ := rfl + right_inv _ := rfl + +section AmbientRelation + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev State (σ : Type) := ((σ × Buffer 4096) × Unit) × Option Bool + +def readRelationAt (source : K) (exit : Λ) : + TM2.Stmt (fun _ : K => Bool) Λ (State σ) := + MachineControl.statement id (readerStateEquiv σ 4096) + (readUnarySlots source (List.ofFn id) (.goto fun _ => exit)) + +theorem stepAux_readRelationAt (source : K) (exit : Λ) (ambient : σ) + (buffer : Buffer 4096) (unitState : Unit) (register : Option Bool) + (relation : GraphTables.RelationTable) (tapes : K → List Bool) (suffix : List Bool) + (hinput : tapes source = encodeWords (GraphTables.relationWords relation) ++ suffix) : + TM2.stepAux (readRelationAt source exit) (((ambient, buffer), unitState), register) tapes = + ⟨some exit, (((ambient, fun i => relation[i]), unitState), register), + Function.update tapes source suffix⟩ := by + change TM2.stepAux (MachineControl.statement id (readerStateEquiv σ 4096) + (readUnarySlots source (List.ofFn id) (.goto fun _ => exit))) + ((readerStateEquiv σ 4096) (((ambient, unitState), register), buffer)) tapes = _ + rw [MachineControl.stepAux_simulation] + rw [stepAux_readUnaryAll source _ _ (fun i => relation[i]) tapes suffix + (by simpa only [unaryBits_relation] using hinput)] + rfl + +end AmbientRelation + +namespace Program + +open PCP.AlphabetTable + +inductive Tape + | input | output | accumulator | scratch | vertices | darts | tail | head | rowIndex + | archive | reverseIndex | scanWork | indexWork + deriving DecidableEq + +protected abbrev Tape.enumList : List Tape := [.input, .output, .accumulator, .scratch, .vertices, + .darts, .tail, .head, .rowIndex, .archive, .reverseIndex, .scanWork, .indexWork] + +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 + +abbrev Ambient := Unit × Buffer 4096 +abbrev Plan := List (Emitter.Command 5 Ambient 36864) + +def values (vertices darts tail head row : Nat) : Fin 5 → Nat := + Fin.cases vertices (Fin.cases darts (Fin.cases tail (Fin.cases head (fun _ => row)))) + +def headerPlan : Plan := + Emitter.affineCommands [(0, 6), (1, 36864)] (fun _ => 0) ++ + Emitter.affineCommands [(1, 40960)] (fun _ => 0) + +theorem headerPlan_length : headerPlan.length = 7 := by + simp [headerPlan] + +theorem headerPlan_bits (vertices darts tail head row : Nat) (ambient : Ambient) : + headerPlan.flatMap (Emitter.commandBits (values vertices darts tail head row) ambient) = + encodeWords [6 * vertices + 36864 * darts, 40960 * darts] := by + rw [headerPlan, List.flatMap_append, Emitter.affineCommands_bits, + Emitter.affineCommands_bits] + simp [Emitter.affineValue, values, encodeWords] + rfl + +def source : Fin 5 → Tape := + Fin.cases .vertices (Fin.cases .darts (Fin.cases .tail (Fin.cases .head (fun _ => .rowIndex)))) + +inductive Label (headerCount rowCount : Nat) + | copyFirst | copySecond | startVertices | readVertices | startDarts | readDarts | seedIndex + | header (label : Emitter.Label headerCount 36864) + | headerClearTail | headerClearHead + | guard | startTail | readTail | startReverse | readReverse + | headTableFirst | headTableSecond | headIndexFirst | headIndexSecond + | headHeaderVertices | headHeaderDarts | headLookup (label : Lookup.Label) + | readRelation + | row (label : Emitter.Label rowCount 36864) + | clearTail | clearHead | clearReverse | nextRow | reverseOutput + deriving DecidableEq, Fintype + +def guard {hc rc : Nat} (again finish : Label hc rc) : + TM2.Stmt (fun _ : Tape => Bool) (Label hc rc) (State Unit) := + .peek .input (fun state head => (state.1, head)) + (.branch (fun state => state.2.isSome) + (.load (fun state => (state.1, none)) (.goto fun _ => again)) + (.load (fun state => (state.1, none)) (.goto fun _ => finish))) + +def program (headerPlan rowPlan : Plan) : + Label headerPlan.length rowPlan.length → + TM2.Stmt (fun _ : Tape => Bool) (Label headerPlan.length rowPlan.length) (State Unit) + | .copyFirst => Reduction.MachineTransfer.loopAt .input .scratch id false .copyFirst + (some .copySecond) + | .copySecond => MachineCopy.forkLoop .scratch .input .archive false .copySecond + (some .startVertices) + | .startVertices => Hastad.SourceMachine.fieldStart .vertices .readVertices + | .readVertices => Hastad.SourceMachine.fieldLoop .input .vertices .readVertices (some .startDarts) + | .startDarts => Hastad.SourceMachine.fieldStart .darts .readDarts + | .readDarts => Hastad.SourceMachine.fieldLoop .input .darts .readDarts (some .seedIndex) + | .seedIndex => .push .rowIndex (fun _ => false) + (.push .tail (fun _ => false) (.push .head (fun _ => false) + (.goto fun _ => .header (Emitter.labelAt headerPlan.length 36864 0 .entry)))) + | .header label => Emitter.statement (Emitter.listCommands headerPlan) + source .scratch .accumulator Label.header (some .headerClearTail) label + | .headerClearTail => MachineLookup.discard .tail .headerClearTail .headerClearHead + | .headerClearHead => MachineLookup.discard .head .headerClearHead .guard + | .guard => guard .startTail .reverseOutput + | .startTail => Hastad.SourceMachine.fieldStart .tail .readTail + | .readTail => Hastad.SourceMachine.fieldLoop .input .tail .readTail (some .startReverse) + | .startReverse => Hastad.SourceMachine.fieldStart .reverseIndex .readReverse + | .readReverse => Hastad.SourceMachine.fieldLoop .input .reverseIndex .readReverse + (some .headTableFirst) + | .headTableFirst => Reduction.MachineTransfer.loopAt .archive .scratch id false + .headTableFirst (some .headTableSecond) + | .headTableSecond => MachineCopy.forkLoop .scratch .archive .scanWork false + .headTableSecond (some .headIndexFirst) + | .headIndexFirst => Reduction.MachineTransfer.loopAt .reverseIndex .scratch id false + .headIndexFirst (some .headIndexSecond) + | .headIndexSecond => MachineCopy.forkLoop .scratch .reverseIndex .indexWork false + .headIndexSecond (some .headHeaderVertices) + | .headHeaderVertices => MachineLookup.discard .scanWork .headHeaderVertices .headHeaderDarts + | .headHeaderDarts => MachineLookup.discard .scanWork .headHeaderDarts (.headLookup .guard) + | .headLookup label => Lookup.statement 64 .indexWork .scanWork .head Label.headLookup + (some .readRelation) label + | .readRelation => readRelationAt .input + (.row (Emitter.labelAt rowPlan.length 36864 0 .entry)) + | .row label => Emitter.statement (Emitter.listCommands rowPlan) + source .scratch .accumulator Label.row (some .clearTail) label + | .clearTail => MachineLookup.discard .tail .clearTail .clearHead + | .clearHead => MachineLookup.discard .head .clearHead .clearReverse + | .clearReverse => MachineLookup.discard .reverseIndex .clearReverse .nextRow + | .nextRow => .push .rowIndex (fun _ => true) (.goto fun _ => .guard) + | .reverseOutput => Reduction.MachineTransfer.loopAt .accumulator .output id false + .reverseOutput none + +def machine (headerPlan rowPlan : Plan) : FinTM2 where + K := Tape + k₀ := .input + k₁ := .output + Γ _ := Bool + Λ := Label headerPlan.length rowPlan.length + main := .copyFirst + σ := State Unit + initialState := ((((), fun _ => false), ()), none) + m := program headerPlan rowPlan + +def headRoles : Fin 6 → Tape := + Fin.cases .archive (Fin.cases .reverseIndex (Fin.cases .scanWork + (Fin.cases .indexWork (Fin.cases .head (fun _ => .scratch))))) + +theorem headRoles_injective : Function.Injective headRoles := by + decide + +def headPhaseInTime (headerPlan rowPlan : Plan) (base : Tape → List Bool) + (table : GenericGraphTables.Table 64) (e : Fin table.darts) + (hTable : base .archive = GenericGraphTables.tableBits table) + (hReverse : base .reverseIndex = encodeWord (Lookup.headIndex table e).val) + (hHead : base .head = []) (hScratch : base .scratch = []) (ambient : Ambient) : + StateTransition.EvalsToInTime (TM2.step (program headerPlan rowPlan)) + ⟨some .headTableFirst, ((ambient, ()), none), base⟩ + (some ⟨some .readRelation, ((ambient, ()), none), + Lookup.headLookupTapes headRoles base table e⟩) + (Lookup.headTimePolynomial.eval (GenericGraphTables.tableBits table).length) := + Lookup.headLookupInTime headRoles headRoles_injective + .headTableFirst .headTableSecond .headIndexFirst .headIndexSecond + .headHeaderVertices .headHeaderDarts Label.headLookup (some .readRelation) + (program headerPlan rowPlan) rfl rfl rfl rfl rfl rfl (fun _ => rfl) + base table e hTable hReverse hHead hScratch (ambient, ()) none + +def workingTapes (vertices darts row : Nat) (input tail head accumulator : List Bool) : + Tape → List Bool + | .input => input + | .output => [] + | .accumulator => accumulator + | .scratch => [] + | .vertices => encodeWord vertices + | .darts => encodeWord darts + | .tail => tail + | .head => head + | .rowIndex => encodeWord row + | .archive | .reverseIndex | .scanWork | .indexWork => [] + +theorem workingTapes_operands (vertices darts row tail head : Nat) + (input accumulator : List Bool) : + ∀ i, workingTapes vertices darts row input (encodeWord tail) (encodeWord head) + accumulator (source i) = encodeWord (values vertices darts tail head row i) := by + intro i + fin_cases i <;> rfl + +theorem update_working_input (vertices darts row : Nat) + (input tail head accumulator replacement : List Bool) : + Function.update (workingTapes vertices darts row input tail head accumulator) Tape.input + replacement = workingTapes vertices darts row replacement tail head accumulator := by + funext tape + cases tape <;> simp [workingTapes, Function.update] + +theorem update_working_tail (vertices darts row : Nat) + (input tail head accumulator replacement : List Bool) : + Function.update (workingTapes vertices darts row input tail head accumulator) Tape.tail + replacement = workingTapes vertices darts row input replacement head accumulator := by + funext tape + cases tape <;> simp [workingTapes, Function.update] + +theorem update_working_head (vertices darts row : Nat) + (input tail head accumulator replacement : List Bool) : + Function.update (workingTapes vertices darts row input tail head accumulator) Tape.head + replacement = workingTapes vertices darts row input tail replacement accumulator := by + funext tape + cases tape <;> simp [workingTapes, Function.update] + +theorem update_working_accumulator (vertices darts row : Nat) + (input tail head accumulator replacement : List Bool) : + Function.update (workingTapes vertices darts row input tail head accumulator) Tape.accumulator + replacement = workingTapes vertices darts row input tail head replacement := by + funext tape + cases tape <;> simp [workingTapes, Function.update] + +theorem update_working_rowIndex (vertices darts row : Nat) + (input tail head accumulator : List Bool) : + Function.update (workingTapes vertices darts row input tail head accumulator) Tape.rowIndex + (true :: encodeWord row) = + workingTapes vertices darts (row + 1) input tail head accumulator := by + funext tape + cases tape <;> simp [workingTapes, Function.update, encodeWord, List.replicate_succ] + +theorem source_ne_scratch (i : Fin 5) : source i ≠ Tape.scratch := by + fin_cases i <;> decide + +theorem source_ne_accumulator (i : Fin 5) : source i ≠ Tape.accumulator := by + fin_cases i <;> decide + +end Program + +end MinUncutGames.Foundations.Complexity.FinalCNFMachine + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/RawInitialMachinePhases.lean b/lean/OAI/Computability/MinUncut/Machines/RawInitialMachinePhases.lean new file mode 100644 index 0000000000000000000000000000000000000000..4ce29c35827feb4189c0adf7172c233126792720 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/RawInitialMachinePhases.lean @@ -0,0 +1,727 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.RawInitialMachineBudget +import OAI.Computability.MinUncut.Machines.MachineInitialHeaders + +namespace OAI + +namespace MinUncutGames.Foundations.PCP.RawInitialMachinePhases + +open Turing Complexity RawInitialMachineModel + +theorem copySource_ne_scratch (phase : CopyPhase) : copySource phase ≠ Tape.scratch := by + cases phase <;> simp [copySource] + +theorem copySource_ne_reversed (phase : CopyPhase) : copySource phase ≠ Tape.reversed := by + cases phase <;> simp [copySource] + +def copyInTime (phase : CopyPhase) (base : Tape → List Bool) + (n : Nat) (suffix : List Bool) + (hsource : base (copySource phase) = encodeWord n ++ suffix) + (hscratch : base .scratch = []) (state : State) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (.scan phase), state, base⟩ + (some ⟨some (copyNext phase), (state.1, none), + Function.update base .reversed + (List.replicate (copyScale phase * n) true ++ base .reversed)⟩) + (2 * n + 2) := + MachineInitialHeaders.prefixInTime (copySource phase) Tape.scratch Tape.reversed + (copySource_ne_scratch phase) (copySource_ne_reversed phase) (by decide) + (copyScale phase) (.scan phase) (.restore phase) (some (copyNext phase)) + program rfl rfl base n suffix hsource hscratch state.1 state.2 + +def relationInTime (slot : Fin 3) (orientation : Bool) + (base : Tape → List Bool) (state : State) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (.relation slot orientation), state, base⟩ + (some ⟨some (relationNext slot orientation), state, + Function.update base .reversed + (relationOutput slot orientation state ++ base .reversed)⟩) 1 := + MachineFiniteTable.emitInTime (K := Tape) (Λ := Label) (σ := State) (Γ := Alphabet) + Tape.reversed + (relationOutput slot orientation) + stateKeys stateKeys_complete program (.relation slot orientation) + (relationNext slot orientation) rfl state base + +private theorem bitWord_head (b : Bool) : + (encodeWord (if b then 1 else 0)).head? = some b := by + cases b <;> rfl + +theorem loadSigns_step (base : Tape → List Bool) (a b c : Bool) + (ha : base (.field 1) = encodeWord (if a then 1 else 0)) + (hb : base (.field 3) = encodeWord (if b then 1 else 0)) + (hc : base (.field 5) = encodeWord (if c then 1 else 0)) (state : State) : + (TM2.step program) ⟨some .loadSigns, state, base⟩ = + some ⟨some (.scan (.tailVariables 0)), ((a, b, c), none), base⟩ := by + change some (TM2.stepAux (program .loadSigns) state base) = _ + simp only [program, TM2.stepAux, ha, hb, hc, bitWord_head, Option.getD_some] + +def loadSignsInTime (base : Tape → List Bool) (a b c : Bool) + (ha : base (.field 1) = encodeWord (if a then 1 else 0)) + (hb : base (.field 3) = encodeWord (if b then 1 else 0)) + (hc : base (.field 5) = encodeWord (if c then 1 else 0)) (state : State) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some .loadSigns, state, base⟩ + (some ⟨some (.scan (.tailVariables 0)), ((a, b, c), none), base⟩) 1 where + steps := 1 + evals_in_steps := loadSigns_step base a b c ha hb hc state + steps_le_m := Nat.le_refl _ + +def cleanupFieldInTime (slot : Fin 6) (base : Tape → List Bool) (state : State) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (.cleanupField slot), state, base⟩ + (some ⟨some (if h : slot.val + 1 < 6 then .cleanupField ⟨slot.val + 1, h⟩ + else .incrementIndex), (state.1, none), Function.update base (.field slot) []⟩) + ((base (.field slot)).length + 1) := + MachineDrain.drainInTime (.field slot) (.cleanupField slot) _ program rfl base state.1 state.2 + +def cleanupFinalInTime (slot : Fin 3) (base : Tape → List Bool) (state : State) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (.cleanupFinal slot), state, base⟩ + (some ⟨some (if h : slot.val + 1 < 3 then .cleanupFinal ⟨slot.val + 1, h⟩ + else .reset), (state.1, none), Function.update base (finalTape slot) []⟩) + ((base (finalTape slot)).length + 1) := + MachineDrain.drainInTime (finalTape slot) (.cleanupFinal slot) _ program rfl base state.1 state.2 + +end MinUncutGames.Foundations.PCP.RawInitialMachinePhases + +namespace MinUncutGames.Foundations.PCP.RawInitialMachineReadClause + +open Turing Complexity Hastad RawInitialMachineModel + +def fieldValue {n : ℕ} (c : Target.Clause n) (j : Fin 6) : ℕ := + (Complexity.clauseWords c)[j.val]'(by + rw [Complexity.clauseWords_length] + exact j.isLt) + +def recordTapes {n : ℕ} (base : Tape → List Bool) (c : Target.Clause n) + (suffix : List Bool) : Tape → List Bool + | .input => suffix + | .field j => encodeWord (fieldValue c j) + | k => base k + +@[simp] theorem recordTapes_input {n : ℕ} (base : Tape → List Bool) + (c : Target.Clause n) (suffix : List Bool) : + recordTapes base c suffix .input = suffix := rfl + +@[simp] theorem recordTapes_field {n : ℕ} (base : Tape → List Bool) + (c : Target.Clause n) (suffix : List Bool) (j : Fin 6) : + recordTapes base c suffix (.field j) = encodeWord (fieldValue c j) := rfl + +theorem recordTapes_other {n : ℕ} (base : Tape → List Bool) + (c : Target.Clause n) (suffix : List Bool) (k : Tape) + (hi : k ≠ .input) (hf : ∀ j, k ≠ .field j) : + recordTapes base c suffix k = base k := by + cases k <;> try rfl + · exact (hi rfl).elim + · exact (hf _ rfl).elim + +@[simp] theorem recordTapes_name {n : ℕ} (base : Tape → List Bool) + (c : Target.Clause n) (suffix : List Bool) (j : Fin 3) : + recordTapes base c suffix (.field (nameField j)) = + encodeWord ((c)[j].variableIndex.val) := by + fin_cases j <;> rfl + +theorem trace_trans {α : Type*} (f : α → α) {a b : ℕ} {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 fieldsTrace {n : ℕ} (base : Tape → List Bool) (c : Target.Clause n) + (suffix : List Bool) + (hinput : base .input = encodeWords (Complexity.clauseWords c) ++ suffix) + (hempty : ∀ j, base (.field j) = []) (state : State) : + (MachineComposition.advance (TM2.step program))^[ + (encodeWords (Complexity.clauseWords c)).length + 6] + (some ⟨some (.fieldStart 0), state, base⟩) = + some ⟨some .loadSigns, (state.1, none), recordTapes base c suffix⟩ := by + let a := fieldValue c 0 + let b := fieldValue c 1 + let d := fieldValue c 2 + let e := fieldValue c 3 + let f := fieldValue c 4 + let g := fieldValue c 5 + have hwords : Complexity.clauseWords c = [a, b, d, e, f, g] := rfl + have hin : base .input = encodeWord a ++ (encodeWords [b, d, e, f, g] ++ suffix) := by + rw [hinput, hwords] + simp only [encodeWords, List.append_assoc] + let t1 := SourceMachine.afterField .input (.field 0) base a + (encodeWords [b, d, e, f, g] ++ suffix) + let t2 := SourceMachine.afterField .input (.field 1) t1 b + (encodeWords [d, e, f, g] ++ suffix) + let t3 := SourceMachine.afterField .input (.field 2) t2 d + (encodeWords [e, f, g] ++ suffix) + let t4 := SourceMachine.afterField .input (.field 3) t3 e + (encodeWords [f, g] ++ suffix) + let t5 := SourceMachine.afterField .input (.field 4) t4 f + (encodeWords [g] ++ suffix) + let t6 := SourceMachine.afterField .input (.field 5) t5 g suffix + have h1 := (SourceMachine.fieldInTime .input (.field 0) (by decide) + (.fieldStart 0) (.fieldLoop 0) (some (.fieldStart 1)) program rfl rfl + base a (encodeWords [b, d, e, f, g] ++ suffix) hin state.1 state.2).evals_in_steps + change (MachineComposition.advance (TM2.step program))^[a + 2] + (some ⟨some (.fieldStart 0), state, base⟩) = + some ⟨some (.fieldStart 1), (state.1, none), t1⟩ at h1 + have h2 := (SourceMachine.fieldInTime .input (.field 1) (by decide) + (.fieldStart 1) (.fieldLoop 1) (some (.fieldStart 2)) program rfl rfl + t1 b (encodeWords [d, e, f, g] ++ suffix) + (by simp [t1, SourceMachine.afterField, encodeWords, List.append_assoc]) + state.1 none).evals_in_steps + change (MachineComposition.advance (TM2.step program))^[b + 2] + (some ⟨some (.fieldStart 1), (state.1, none), t1⟩) = + some ⟨some (.fieldStart 2), (state.1, none), t2⟩ at h2 + have h3 := (SourceMachine.fieldInTime .input (.field 2) (by decide) + (.fieldStart 2) (.fieldLoop 2) (some (.fieldStart 3)) program rfl rfl + t2 d (encodeWords [e, f, g] ++ suffix) + (by simp [t2, SourceMachine.afterField, encodeWords, List.append_assoc]) + state.1 none).evals_in_steps + change (MachineComposition.advance (TM2.step program))^[d + 2] + (some ⟨some (.fieldStart 2), (state.1, none), t2⟩) = + some ⟨some (.fieldStart 3), (state.1, none), t3⟩ at h3 + have h4 := (SourceMachine.fieldInTime .input (.field 3) (by decide) + (.fieldStart 3) (.fieldLoop 3) (some (.fieldStart 4)) program rfl rfl + t3 e (encodeWords [f, g] ++ suffix) + (by simp [t3, SourceMachine.afterField, encodeWords, List.append_assoc]) + state.1 none).evals_in_steps + change (MachineComposition.advance (TM2.step program))^[e + 2] + (some ⟨some (.fieldStart 3), (state.1, none), t3⟩) = + some ⟨some (.fieldStart 4), (state.1, none), t4⟩ at h4 + have h5 := (SourceMachine.fieldInTime .input (.field 4) (by decide) + (.fieldStart 4) (.fieldLoop 4) (some (.fieldStart 5)) program rfl rfl + t4 f (encodeWords [g] ++ suffix) + (by simp [t4, SourceMachine.afterField, encodeWords, List.append_assoc]) + state.1 none).evals_in_steps + change (MachineComposition.advance (TM2.step program))^[f + 2] + (some ⟨some (.fieldStart 4), (state.1, none), t4⟩) = + some ⟨some (.fieldStart 5), (state.1, none), t5⟩ at h5 + have h6 := (SourceMachine.fieldInTime .input (.field 5) (by decide) + (.fieldStart 5) (.fieldLoop 5) (some .loadSigns) program rfl rfl + t5 g suffix + (by simp [t5, SourceMachine.afterField, encodeWords]) + state.1 none).evals_in_steps + change (MachineComposition.advance (TM2.step program))^[g + 2] + (some ⟨some (.fieldStart 5), (state.1, none), t5⟩) = + some ⟨some .loadSigns, (state.1, none), t6⟩ at h6 + have total := trace_trans _ (trace_trans _ (trace_trans _ + (trace_trans _ (trace_trans _ h1 h2) h3) h4) h5) h6 + have htime : (((((a + 2) + (b + 2)) + (d + 2)) + (e + 2)) + (f + 2)) + (g + 2) = + (encodeWords (Complexity.clauseWords c)).length + 6 := by + rw [hwords, encodeWords_length] + simp + omega + rw [htime] at total + have frame : t6 = recordTapes base c suffix := by + funext k + cases k with + | field j => + fin_cases j <;> + simp [t6, t5, t4, t3, t2, t1, SourceMachine.afterField, SourceMachine.fieldTapes, + recordTapes, hempty, a, b, d, e, f, g] + | _ => + simp [t6, t5, t4, t3, t2, t1, SourceMachine.afterField, SourceMachine.fieldTapes, + recordTapes] + rw [frame] at total + exact total + +theorem readClauseTrace {n : ℕ} (base : Tape → List Bool) (c : Target.Clause n) + (suffix : List Bool) + (hinput : base .input = encodeWords (Complexity.clauseWords c) ++ suffix) + (hempty : ∀ j, base (.field j) = []) (state : State) : + (MachineComposition.advance (TM2.step program))^[ + (encodeWords (Complexity.clauseWords c)).length + 7] + (some ⟨some (.fieldStart 0), state, base⟩) = + some ⟨some (.scan (.tailVariables 0)), (RawInitialRows.clauseSigns c, none), + recordTapes base c suffix⟩ := by + have first := fieldsTrace base c suffix hinput hempty state + have last := RawInitialMachinePhases.loadSigns_step (recordTapes base c suffix) + (c)[0].positive (c)[1].positive (c)[2].positive rfl rfl rfl (state.1, none) + have lastTrace : (MachineComposition.advance (TM2.step program))^[1] + (some ⟨some .loadSigns, (state.1, none), recordTapes base c suffix⟩) = + some ⟨some (.scan (.tailVariables 0)), (RawInitialRows.clauseSigns c, none), + recordTapes base c suffix⟩ := last + have total := trace_trans _ first lastTrace + simpa only [show (encodeWords (Complexity.clauseWords c)).length + 6 + 1 = + (encodeWords (Complexity.clauseWords c)).length + 7 by omega] using total + +def readClauseInTime {n : ℕ} (base : Tape → List Bool) (c : Target.Clause n) + (suffix : List Bool) + (hinput : base .input = encodeWords (Complexity.clauseWords c) ++ suffix) + (hempty : ∀ j, base (.field j) = []) (state : State) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (.fieldStart 0), state, base⟩ + (some ⟨some (.scan (.tailVariables 0)), (RawInitialRows.clauseSigns c, none), + recordTapes base c suffix⟩) + ((encodeWords (Complexity.clauseWords c)).length + 7) where + steps := (encodeWords (Complexity.clauseWords c)).length + 7 + evals_in_steps := readClauseTrace base c suffix hinput hempty state + steps_le_m := Nat.le_refl _ + +end MinUncutGames.Foundations.PCP.RawInitialMachineReadClause + +namespace MinUncutGames.Foundations.PCP.RawInitialMachineRows + +open Turing Complexity RawInitialMachineModel RawInitialMachinePhases + +attribute [local irreducible] relationOutput RawInitialRows.relationWordsFor + +abbrev advance := MachineComposition.advance (TM2.step program) + +def outputTapes (base : Tape → List Bool) (bits : List Bool) : Tape → List Bool := + Function.update base .reversed (bits ++ base .reversed) + +@[simp] theorem outputTapes_reversed (base : Tape → List Bool) (bits : List Bool) : + outputTapes base bits .reversed = bits ++ base .reversed := by simp [outputTapes] + +theorem outputTapes_other (base : Tape → List Bool) (bits : List Bool) + (tape : Tape) (h : tape ≠ .reversed) : outputTapes base bits tape = base tape := by + simp [outputTapes, h] + +@[simp] theorem outputTapes_twice (base : Tape → List Bool) (first second : List Bool) : + outputTapes (outputTapes base first) second = outputTapes base (second ++ first) := by + funext tape + by_cases h : tape = .reversed + · subst tape; simp [List.append_assoc] + · simp [outputTapes, h] + +theorem trace_trans {α : Type*} (f : α → α) {a b : ℕ} {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 copyTrace (phase : CopyPhase) (base : Tape → List Bool) + (n : ℕ) (hsource : base (copySource phase) = encodeWord n) + (hscratch : base .scratch = []) (signs : Signs) : + advance^[2 * n + 2] (some ⟨some (.scan phase), (signs, none), base⟩) = + some ⟨some (copyNext phase), (signs, none), + outputTapes base (List.replicate (copyScale phase * n) true)⟩ := + (copyInTime phase base n [] (by simpa using hsource) hscratch (signs, none)).evals_in_steps + +private theorem closeTailTrace (slot : Fin 3) (orientation : Bool) + (base : Tape → List Bool) (signs : Signs) : + advance^[1] (some ⟨some (.closeTail slot orientation), (signs, none), base⟩) = + some ⟨some (.scan (.reverseIndex slot orientation)), (signs, none), + outputTapes base [false]⟩ := by + change some (TM2.stepAux (program (.closeTail slot orientation)) (signs, none) base) = _ + rfl + +private theorem closeReverseTrace (slot : Fin 3) (orientation : Bool) + (base : Tape → List Bool) (signs : Signs) : + advance^[1] (some ⟨some (.closeReverse slot orientation), (signs, none), base⟩) = + some ⟨some (.relation slot orientation), (signs, none), + outputTapes base (encodeWord (2 * slot.val + if orientation then 0 else 1)).reverse⟩ := + MachineInitialHeaders.literalTrace .reversed + (encodeWord (2 * slot.val + if orientation then 0 else 1)) + (.closeReverse slot orientation) (some (.relation slot orientation)) + program rfl base signs none + +private theorem reverse_encodeWord_add (a b : ℕ) : + (encodeWord b).reverse ++ List.replicate a true = (encodeWord (a + b)).reverse := by + simp only [encodeWord, List.reverse_append, List.reverse_replicate, List.reverse_singleton] + rw [Nat.add_comm a b, List.replicate_add] + simp only [List.append_assoc] + +def rowEndBits (slot : Fin 3) (orientation : Bool) (i : ℕ) (signs : Signs) : List Bool := + relationOutput slot orientation (signs, none) ++ + (encodeWord (6 * i + 2 * slot.val + if orientation then 0 else 1)).reverse ++ [false] + +private theorem rowEndTrace (slot : Fin 3) (orientation : Bool) (base : Tape → List Bool) + (i : ℕ) (hindex : base .index = encodeWord i) (hscratch : base .scratch = []) + (signs : Signs) : + advance^[2 * i + 5] (some ⟨some (.closeTail slot orientation), (signs, none), base⟩) = + some ⟨some (relationNext slot orientation), (signs, none), + outputTapes base (rowEndBits slot orientation i signs)⟩ := by + let first := outputTapes base [false] + let second := outputTapes first (List.replicate (6 * i) true) + let third := outputTapes second + (encodeWord (2 * slot.val + if orientation then 0 else 1)).reverse + have h1 := closeTailTrace slot orientation base signs + have h2 := copyTrace (.reverseIndex slot orientation) first i + (by simpa [first, outputTapes, copySource] using hindex) + (by simpa [first, outputTapes] using hscratch) signs + change advance^[2 * i + 2] + (some ⟨some (.scan (.reverseIndex slot orientation)), (signs, none), first⟩) = + some ⟨some (.closeReverse slot orientation), (signs, none), second⟩ at h2 + have h3 := closeReverseTrace slot orientation second signs + have h4 := (relationInTime slot orientation third (signs, none)).evals_in_steps + change advance^[1] (some ⟨some (.relation slot orientation), (signs, none), third⟩) = + some ⟨some (relationNext slot orientation), (signs, none), + outputTapes third (relationOutput slot orientation (signs, none))⟩ at h4 + have total := trace_trans _ (trace_trans _ (trace_trans _ h1 h2) h3) h4 + have hout : outputTapes third (relationOutput slot orientation (signs, none)) = + outputTapes base (rowEndBits slot orientation i signs) := by + simp only [third, second, first, outputTapes_twice] + apply congrArg (outputTapes base) + rw [reverse_encodeWord_add] + simp only [rowEndBits, Nat.add_assoc, List.append_assoc] + rw [hout] at total + simpa only [show 1 + (2 * i + 2) + 1 + 1 = 2 * i + 5 by omega] using total + +private theorem rowEndBits_append (slot : Fin 3) (orientation : Bool) + (tail i : ℕ) (signs : Signs) : + rowEndBits slot orientation i signs ++ List.replicate tail true = + (encodeWords ([tail, 6 * i + 2 * slot.val + if orientation then 0 else 1] ++ + RawInitialRows.relationWordsFor signs (RawInitialTables.slotOrder.symm slot) orientation)).reverse := by + simp only [rowEndBits, relationOutput, encodeWords_append, encodeWords, + List.append_nil, List.reverse_append, encodeWord, + List.reverse_replicate, List.reverse_singleton, List.append_assoc] + +theorem falseRowTrace (slot : Fin 3) (base : Tape → List Bool) (n i : ℕ) + (names : RawInitialRows.Names) (signs : Signs) + (hvariables : base .«variables» = encodeWord n) (hindex : base .index = encodeWord i) + (hscratch : base .scratch = []) : + advance^[2 * n + 4 * i + 9] + (some ⟨some (.scan (.tailVariables slot)), (signs, none), base⟩) = + some ⟨some (.scan (.variableName slot)), (signs, none), + outputTapes base (encodeWords (RawInitialRows.incidenceWords n i names signs + (RawInitialTables.slotOrder.symm slot) false)).reverse⟩ := by + let first := outputTapes base (List.replicate n true) + let second := outputTapes first (List.replicate i true) + have h1 := copyTrace (.tailVariables slot) base n hvariables hscratch signs + have h2 := copyTrace (.tailIndex slot) first i + (by simpa [first, outputTapes, copySource] using hindex) + (by simpa [first, outputTapes] using hscratch) signs + simp only [copyScale, Nat.one_mul, copyNext] at h1 h2 + change advance^[2 * n + 2] + (some ⟨some (.scan (.tailVariables slot)), (signs, none), base⟩) = + some ⟨some (.scan (.tailIndex slot)), (signs, none), first⟩ at h1 + change advance^[2 * i + 2] + (some ⟨some (.scan (.tailIndex slot)), (signs, none), first⟩) = + some ⟨some (.closeTail slot false), (signs, none), second⟩ at h2 + have h3 := rowEndTrace slot false second i + (by simpa [second, first, outputTapes] using hindex) + (by simpa [second, first, outputTapes] using hscratch) signs + have total := trace_trans _ (trace_trans _ h1 h2) h3 + have hout : outputTapes second (rowEndBits slot false i signs) = + outputTapes base (encodeWords (RawInitialRows.incidenceWords n i names signs + (RawInitialTables.slotOrder.symm slot) false)).reverse := by + simp only [second, first, outputTapes_twice] + apply congrArg (outputTapes base) + rw [← List.replicate_add, Nat.add_comm i n, rowEndBits_append] + simp only [RawInitialRows.incidenceWords, Bool.false_eq_true, ↓reduceIte, + Equiv.apply_symm_apply] + rw [hout] at total + simpa only [relationNext, Bool.false_eq_true, ↓reduceIte, + show (2 * n + 2) + (2 * i + 2) + (2 * i + 5) = 2 * n + 4 * i + 9 by omega] using total + +theorem trueRowTrace (slot : Fin 3) (base : Tape → List Bool) (n i : ℕ) + (names : RawInitialRows.Names) (signs : Signs) + (hname : base (.field (nameField slot)) = + encodeWord (RawInitialRows.nameWord names (RawInitialTables.slotOrder.symm slot))) + (hindex : base .index = encodeWord i) (hscratch : base .scratch = []) : + advance^[2 * RawInitialRows.nameWord names (RawInitialTables.slotOrder.symm slot) + 2 * i + 7] + (some ⟨some (.scan (.variableName slot)), (signs, none), base⟩) = + some ⟨some (relationNext slot true), (signs, none), + outputTapes base (encodeWords (RawInitialRows.incidenceWords n i names signs + (RawInitialTables.slotOrder.symm slot) true)).reverse⟩ := by + let value := RawInitialRows.nameWord names (RawInitialTables.slotOrder.symm slot) + let first := outputTapes base (List.replicate value true) + have h1 := copyTrace (.variableName slot) base value hname hscratch signs + simp only [copyScale, Nat.one_mul, copyNext] at h1 + change advance^[2 * value + 2] + (some ⟨some (.scan (.variableName slot)), (signs, none), base⟩) = + some ⟨some (.closeTail slot true), (signs, none), first⟩ at h1 + have h2 := rowEndTrace slot true first i + (by simpa [first, outputTapes] using hindex) + (by simpa [first, outputTapes] using hscratch) signs + have total := trace_trans _ h1 h2 + have hout : outputTapes first (rowEndBits slot true i signs) = + outputTapes base (encodeWords (RawInitialRows.incidenceWords n i names signs + (RawInitialTables.slotOrder.symm slot) true)).reverse := by + simp only [first, outputTapes_twice, rowEndBits_append, value, + RawInitialRows.incidenceWords, ↓reduceIte, Equiv.apply_symm_apply] + rw [hout] at total + simpa only [value, show (2 * value + 2) + (2 * i + 5) = 2 * value + 2 * i + 7 by omega] using total + +def pairWords (slot : Fin 3) (n i : ℕ) (names : RawInitialRows.Names) + (signs : Signs) : List ℕ := + RawInitialRows.incidenceWords n i names signs (RawInitialTables.slotOrder.symm slot) false ++ + RawInitialRows.incidenceWords n i names signs (RawInitialTables.slotOrder.symm slot) true + +theorem pairTrace (slot : Fin 3) (base : Tape → List Bool) (n i : ℕ) + (names : RawInitialRows.Names) (signs : Signs) + (hvariables : base .«variables» = encodeWord n) (hindex : base .index = encodeWord i) + (hname : base (.field (nameField slot)) = + encodeWord (RawInitialRows.nameWord names (RawInitialTables.slotOrder.symm slot))) + (hscratch : base .scratch = []) : + advance^[2 * n + 6 * i + + 2 * RawInitialRows.nameWord names (RawInitialTables.slotOrder.symm slot) + 16] + (some ⟨some (.scan (.tailVariables slot)), (signs, none), base⟩) = + some ⟨some (relationNext slot true), (signs, none), + outputTapes base (encodeWords (pairWords slot n i names signs)).reverse⟩ := by + let first := outputTapes base (encodeWords (RawInitialRows.incidenceWords n i names signs + (RawInitialTables.slotOrder.symm slot) false)).reverse + have h1 := falseRowTrace slot base n i names signs hvariables hindex hscratch + have h2 := trueRowTrace slot first n i names signs + (by simpa [first, outputTapes] using hname) + (by simpa [first, outputTapes] using hindex) + (by simpa [first, outputTapes] using hscratch) + have total := trace_trans _ h1 h2 + simpa only [first, outputTapes_twice, pairWords, encodeWords_append, List.reverse_append, + show (2 * n + 4 * i + 9) + + (2 * RawInitialRows.nameWord names (RawInitialTables.slotOrder.symm slot) + 2 * i + 7) = + 2 * n + 6 * i + + 2 * RawInitialRows.nameWord names (RawInitialTables.slotOrder.symm slot) + 16 by omega] + using total + +theorem rowsTrace (base : Tape → List Bool) (n i : ℕ) + (names : RawInitialRows.Names) (signs : Signs) + (hvariables : base .«variables» = encodeWord n) (hindex : base .index = encodeWord i) + (hname0 : base (.field 0) = encodeWord names.1) + (hname2 : base (.field 2) = encodeWord names.2.1) + (hname4 : base (.field 4) = encodeWord names.2.2) + (hscratch : base .scratch = []) : + advance^[6 * n + 18 * i + 2 * (names.1 + names.2.1 + names.2.2) + 48] + (some ⟨some (.scan (.tailVariables 0)), (signs, none), base⟩) = + some ⟨some (.cleanupField 0), (signs, none), + outputTapes base (encodeWords (RawInitialRows.clauseWords n i names signs)).reverse⟩ := by + let first := outputTapes base (encodeWords (pairWords 0 n i names signs)).reverse + let second := outputTapes first (encodeWords (pairWords 1 n i names signs)).reverse + have h0 := pairTrace 0 base n i names signs hvariables hindex hname0 hscratch + have h1 := pairTrace 1 first n i names signs + (by simpa [first, outputTapes] using hvariables) + (by simpa [first, outputTapes] using hindex) + (by simpa [first, outputTapes, nameField, RawInitialRows.nameWord, + RawInitialTables.slotOrder] using hname2) + (by simpa [first, outputTapes] using hscratch) + have h2 := pairTrace 2 second n i names signs + (by simpa [second, first, outputTapes] using hvariables) + (by simpa [second, first, outputTapes] using hindex) + (by simpa [second, first, outputTapes, nameField, RawInitialRows.nameWord, + RawInitialTables.slotOrder] using hname4) + (by simpa [second, first, outputTapes] using hscratch) + change advance^[2 * n + 6 * i + 2 * names.1 + 16] + (some ⟨some (.scan (.tailVariables 0)), (signs, none), base⟩) = + some ⟨some (.scan (.tailVariables 1)), (signs, none), first⟩ at h0 + change advance^[2 * n + 6 * i + 2 * names.2.1 + 16] + (some ⟨some (.scan (.tailVariables 1)), (signs, none), first⟩) = + some ⟨some (.scan (.tailVariables 2)), (signs, none), second⟩ at h1 + change advance^[2 * n + 6 * i + 2 * names.2.2 + 16] + (some ⟨some (.scan (.tailVariables 2)), (signs, none), second⟩) = + some ⟨some (.cleanupField 0), (signs, none), + outputTapes second (encodeWords (pairWords 2 n i names signs)).reverse⟩ at h2 + have total := trace_trans _ (trace_trans _ h0 h1) h2 + have hout : outputTapes second (encodeWords (pairWords 2 n i names signs)).reverse = + outputTapes base (encodeWords (RawInitialRows.clauseWords n i names signs)).reverse := by + simp only [second, first, outputTapes_twice, RawInitialRows.clauseWords, + encodeWords_append, List.reverse_append, pairWords, List.append_assoc] + rfl + rw [hout] at total + simpa only [show (2 * n + 6 * i + 2 * names.1 + 16) + + (2 * n + 6 * i + 2 * names.2.1 + 16) + (2 * n + 6 * i + 2 * names.2.2 + 16) = + 6 * n + 18 * i + 2 * (names.1 + names.2.1 + names.2.2) + 48 by omega] using total + +def rowsInTime (base : Tape → List Bool) (n i : ℕ) + (names : RawInitialRows.Names) (signs : Signs) + (hvariables : base .«variables» = encodeWord n) (hindex : base .index = encodeWord i) + (hname0 : base (.field 0) = encodeWord names.1) + (hname2 : base (.field 2) = encodeWord names.2.1) + (hname4 : base (.field 4) = encodeWord names.2.2) + (hscratch : base .scratch = []) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (.scan (.tailVariables 0)), (signs, none), base⟩ + (some ⟨some (.cleanupField 0), (signs, none), + outputTapes base (encodeWords (RawInitialRows.clauseWords n i names signs)).reverse⟩) + (6 * n + 18 * i + 2 * (names.1 + names.2.1 + names.2.2) + 48) where + steps := 6 * n + 18 * i + 2 * (names.1 + names.2.1 + names.2.2) + 48 + evals_in_steps := rowsTrace base n i names signs hvariables hindex hname0 hname2 hname4 hscratch + steps_le_m := Nat.le_refl _ + +end MinUncutGames.Foundations.PCP.RawInitialMachineRows + +namespace MinUncutGames.Foundations.PCP.RawInitialMachineCleanup + +open Turing Complexity RawInitialMachineModel RawInitialMachineReadClause + +theorem trace_trans {α : Type*} (f : α → α) {a b : ℕ} {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 incrementIndexTrace (base : Tape → List Bool) (state : State) : + (MachineComposition.advance (TM2.step program))^[1] + (some ⟨some .incrementIndex, state, base⟩) = + some ⟨some .guard, state, Function.update base .index (true :: base .index)⟩ := by + rfl + +theorem cleanupTrace {n : ℕ} (base : Tape → List Bool) (c : Target.Clause n) + (suffix : List Bool) (i : ℕ) + (hempty : ∀ j, base (.field j) = []) (hindex : base .index = encodeWord i) + (incoming : State) : + (MachineComposition.advance (TM2.step program))^[ + (encodeWords (Complexity.clauseWords c)).length + 7] + (some ⟨some (.cleanupField 0), incoming, recordTapes base c suffix⟩) = + some ⟨some .guard, (incoming.1, none), + Function.update (Function.update base .input suffix) .index (encodeWord (i + 1))⟩ := by + let r := recordTapes base c suffix + let t1 := Function.update r (.field 0) [] + let t2 := Function.update t1 (.field 1) [] + let t3 := Function.update t2 (.field 2) [] + let t4 := Function.update t3 (.field 3) [] + let t5 := Function.update t4 (.field 4) [] + let t6 := Function.update t5 (.field 5) [] + have h1 := (RawInitialMachinePhases.cleanupFieldInTime 0 r incoming).evals_in_steps + change (MachineComposition.advance (TM2.step program))^[ + (encodeWord (fieldValue c 0)).length + 1] + (some ⟨some (.cleanupField 0), incoming, r⟩) = + some ⟨some (.cleanupField 1), (incoming.1, none), t1⟩ at h1 + have h2 := (RawInitialMachinePhases.cleanupFieldInTime 1 t1 (incoming.1, none)).evals_in_steps + have hf2 : t1 (.field 1) = encodeWord (fieldValue c 1) := by + simp [t1, r] + change (MachineComposition.advance (TM2.step program))^[(t1 (.field 1)).length + 1] + (some ⟨some (.cleanupField 1), (incoming.1, none), t1⟩) = + some ⟨some (.cleanupField 2), (incoming.1, none), t2⟩ at h2 + rw [hf2] at h2 + have h3 := (RawInitialMachinePhases.cleanupFieldInTime 2 t2 (incoming.1, none)).evals_in_steps + have hf3 : t2 (.field 2) = encodeWord (fieldValue c 2) := by + simp [t2, t1, r] + change (MachineComposition.advance (TM2.step program))^[(t2 (.field 2)).length + 1] + (some ⟨some (.cleanupField 2), (incoming.1, none), t2⟩) = + some ⟨some (.cleanupField 3), (incoming.1, none), t3⟩ at h3 + rw [hf3] at h3 + have h4 := (RawInitialMachinePhases.cleanupFieldInTime 3 t3 (incoming.1, none)).evals_in_steps + have hf4 : t3 (.field 3) = encodeWord (fieldValue c 3) := by + simp [t3, t2, t1, r] + change (MachineComposition.advance (TM2.step program))^[(t3 (.field 3)).length + 1] + (some ⟨some (.cleanupField 3), (incoming.1, none), t3⟩) = + some ⟨some (.cleanupField 4), (incoming.1, none), t4⟩ at h4 + rw [hf4] at h4 + have h5 := (RawInitialMachinePhases.cleanupFieldInTime 4 t4 (incoming.1, none)).evals_in_steps + have hf5 : t4 (.field 4) = encodeWord (fieldValue c 4) := by + simp [t4, t3, t2, t1, r] + change (MachineComposition.advance (TM2.step program))^[(t4 (.field 4)).length + 1] + (some ⟨some (.cleanupField 4), (incoming.1, none), t4⟩) = + some ⟨some (.cleanupField 5), (incoming.1, none), t5⟩ at h5 + rw [hf5] at h5 + have h6 := (RawInitialMachinePhases.cleanupFieldInTime 5 t5 (incoming.1, none)).evals_in_steps + have hf6 : t5 (.field 5) = encodeWord (fieldValue c 5) := by + simp [t5, t4, t3, t2, t1, r] + change (MachineComposition.advance (TM2.step program))^[(t5 (.field 5)).length + 1] + (some ⟨some (.cleanupField 5), (incoming.1, none), t5⟩) = + some ⟨some .incrementIndex, (incoming.1, none), t6⟩ at h6 + rw [hf6] at h6 + have last := incrementIndexTrace t6 (incoming.1, none) + have total := trace_trans _ (trace_trans _ (trace_trans _ (trace_trans _ + (trace_trans _ (trace_trans _ h1 h2) h3) h4) h5) h6) last + have htime : + ((((((encodeWord (fieldValue c 0)).length + 1 + + ((encodeWord (fieldValue c 1)).length + 1)) + + ((encodeWord (fieldValue c 2)).length + 1)) + + ((encodeWord (fieldValue c 3)).length + 1)) + + ((encodeWord (fieldValue c 4)).length + 1)) + + ((encodeWord (fieldValue c 5)).length + 1)) + 1 = + (encodeWords (Complexity.clauseWords c)).length + 7 := by + simp [fieldValue, Complexity.clauseWords, Complexity.literalWords, encodeWords] + omega + rw [htime] at total + have frame : Function.update t6 .index (true :: t6 .index) = + Function.update (Function.update base .input suffix) .index (encodeWord (i + 1)) := by + funext k + cases k with + | field j => + fin_cases j <;> simp [t6, t5, t4, t3, t2, t1, r, recordTapes, hempty] + | index => + simp [t6, t5, t4, t3, t2, t1, r, recordTapes, hindex, + encodeWord, List.replicate_succ] + | _ => simp [t6, t5, t4, t3, t2, t1, r, recordTapes] + rw [frame] at total + exact total + +def cleanupInTime {n : ℕ} (base : Tape → List Bool) (c : Target.Clause n) + (suffix : List Bool) (i : ℕ) + (hempty : ∀ j, base (.field j) = []) (hindex : base .index = encodeWord i) + (incoming : State) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (.cleanupField 0), incoming, recordTapes base c suffix⟩ + (some ⟨some .guard, (incoming.1, none), + Function.update (Function.update base .input suffix) .index (encodeWord (i + 1))⟩) + ((encodeWords (Complexity.clauseWords c)).length + 7) where + steps := (encodeWords (Complexity.clauseWords c)).length + 7 + evals_in_steps := cleanupTrace base c suffix i hempty hindex incoming + steps_le_m := Nat.le_refl _ + +end MinUncutGames.Foundations.PCP.RawInitialMachineCleanup + +namespace MinUncutGames.Foundations.PCP.RawInitialMachineBody + +open Turing Target Complexity RawInitialMachineModel RawInitialMachineLoopData +open RawInitialMachineReadClause RawInitialMachineRows RawInitialMachineBudget + +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 guardTrace_succ (n i remaining : Nat) (input reversed : List Bool) + (state : State) : + (MachineComposition.advance (TM2.step program))^[1] + (some ⟨some .guard, state, loopTapes n i (remaining + 1) input reversed⟩) = + some ⟨some (.fieldStart 0), (state.1, none), + loopTapes n i remaining input reversed⟩ := by + have h := MachineUnaryCounter.guardTrace_succ Tape.counter Label.guard + (.fieldStart 0) (.scan .dummyVariables) program rfl + (loopTapes n i remaining input reversed) remaining [] state.1 state.2 + have heq (r : Nat) : MachineUnaryCounter.counterTapes Tape.counter + (loopTapes n i remaining input reversed) r [] = loopTapes n i r input reversed := by + funext tape + cases tape <;> simp [MachineUnaryCounter.counterTapes, loopTapes] + simpa only [heq, Prod.mk.eta] using h + +theorem guardTrace_zero (n i : Nat) (input reversed : List Bool) (state : State) : + (MachineComposition.advance (TM2.step program))^[1] + (some ⟨some .guard, state, loopTapes n i 0 input reversed⟩) = + some ⟨some (.scan .dummyVariables), (state.1, none), + loopTapes n i 0 input reversed⟩ := by + have h := MachineUnaryCounter.guardTrace_zero Tape.counter Label.guard + (.fieldStart 0) (.scan .dummyVariables) program rfl + (loopTapes n i 0 input reversed) [] state.1 state.2 + have heq : MachineUnaryCounter.counterTapes Tape.counter + (loopTapes n i 0 input reversed) 0 [] = loopTapes n i 0 input reversed := by + funext tape + cases tape <;> simp [MachineUnaryCounter.counterTapes, loopTapes] + simpa only [heq, Prod.mk.eta] using h + +theorem bodyTrace {n : Nat} (i remaining : Nat) (c : Clause n) + (suffix reversed : List Bool) (state : State) : + (MachineComposition.advance (TM2.step program))^[bodyTime i c] + (some ⟨some .guard, state, + loopTapes n i (remaining + 1) + (encodeWords (Complexity.clauseWords c) ++ suffix) reversed⟩) = + some ⟨some .guard, (RawInitialRows.clauseSigns c, none), + loopTapes n (i + 1) remaining suffix + ((encodeWords (RawInitialRows.clauseWords n i + (RawInitialRows.clauseNames c) (RawInitialRows.clauseSigns c))).reverse ++ reversed)⟩ := by + let input := encodeWords (Complexity.clauseWords c) ++ suffix + let base := loopTapes n i remaining input reversed + let chunk := (encodeWords (RawInitialRows.clauseWords n i + (RawInitialRows.clauseNames c) (RawInitialRows.clauseSigns c))).reverse + let emitted := loopTapes n i remaining input (chunk ++ reversed) + have first := guardTrace_succ n i remaining input reversed state + have read := readClauseTrace base c suffix rfl (fun _ => rfl) (state.1, none) + have rows := rowsTrace (recordTapes base c suffix) n i + (RawInitialRows.clauseNames c) (RawInitialRows.clauseSigns c) + rfl rfl rfl rfl rfl rfl + have frame : outputTapes (recordTapes base c suffix) chunk = + recordTapes emitted c suffix := by + funext tape + cases tape <;> simp [outputTapes, recordTapes, emitted, base, loopTapes] + change (MachineComposition.advance (TM2.step program))^[6 * n + 18 * i + + 2 * nameSum c + 48] + (some ⟨some (.scan (.tailVariables 0)), (RawInitialRows.clauseSigns c, none), + recordTapes base c suffix⟩) = + some ⟨some (.cleanupField 0), (RawInitialRows.clauseSigns c, none), + outputTapes (recordTapes base c suffix) chunk⟩ at rows + rw [frame] at rows + have cleanup := RawInitialMachineCleanup.cleanupTrace emitted c suffix i + (fun _ => rfl) rfl (RawInitialRows.clauseSigns c, none) + have finalFrame : Function.update (Function.update emitted .input suffix) + .index (encodeWord (i + 1)) = + loopTapes n (i + 1) remaining suffix (chunk ++ reversed) := by + funext tape + cases tape <;> simp [emitted, loopTapes] + rw [finalFrame] at cleanup + have total := trace_trans _ (trace_trans _ (trace_trans _ first read) rows) cleanup + have time : 1 + ((encodeWords (Complexity.clauseWords c)).length + 7) + + (6 * n + 18 * i + 2 * nameSum c + 48) + + ((encodeWords (Complexity.clauseWords c)).length + 7) = bodyTime i c := by + simp only [bodyTime, nameSum] + omega + simpa only [time] using total + +end MinUncutGames.Foundations.PCP.RawInitialMachineBody + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/Relations.lean b/lean/OAI/Computability/MinUncut/Machines/Relations.lean new file mode 100644 index 0000000000000000000000000000000000000000..49126e952826d6da43cbfd84bb0a612e708ece7b --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/Relations.lean @@ -0,0 +1,652 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.AlphabetGraph + +namespace OAI + +namespace MinUncutGames.Foundations.PCP.AlphabetTable.Relations + +open Hastad +open Queries + +variable {q : Nat} + +def sameAddress (selfLoop : Bool) : RawQuery q → RawQuery q → Bool + | .inl (side, f), .inl (side', g) => ((side == side') || selfLoop) && decide (f = g) + | .inr f, .inr g => decide (f = g) + | _, _ => false + +@[simp] theorem sameAddress_refl (selfLoop : Bool) (x : RawQuery q) : + sameAddress selfLoop x x = true := by + rcases x with ⟨side, f⟩ | f <;> simp [sameAddress] + +theorem globalize_eq_iff {V E : Type*} [DecidableEq V] + (tail head : V) (edge : E) (selfLoop : Bool) + (hloop : selfLoop = decide (tail = head)) (x y : RawQuery q) : + globalize tail head edge x = globalize tail head edge y ↔ + sameAddress selfLoop x y = true := by + rcases x with ⟨side, f⟩ | f <;> rcases y with ⟨side', g⟩ | g + · cases side <;> cases side' + · simp [globalize, sameAddress] + · simp [globalize, sameAddress, hloop] + · simp [globalize, sameAddress, hloop, + show head = tail ↔ tail = head from eq_comm] + · simp [globalize, sameAddress] + · simp [globalize, sameAddress] + · simp [globalize, sameAddress] + · simp [globalize, sameAddress] + +def eqProfile (selfLoop : Bool) (queries : Fin 6 → RawQuery q) + (i j : Fin 6) : Bool := sameAddress selfLoop (queries i) (queries j) + +@[simp] theorem eqProfile_refl (selfLoop : Bool) (queries : Fin 6 → RawQuery q) + (i : Fin 6) : eqProfile selfLoop queries i i = true := sameAddress_refl _ _ + +def canonicalSlot (selfLoop : Bool) (queries : Fin 6 → RawQuery q) (i : Fin 6) : Fin 6 := + Fin.find (fun j => eqProfile selfLoop queries j i = true) ⟨i, eqProfile_refl _ _ _⟩ + +theorem canonicalSlot_profile (selfLoop : Bool) (queries : Fin 6 → RawQuery q) + (i : Fin 6) : eqProfile selfLoop queries (canonicalSlot selfLoop queries i) i = true := by + unfold canonicalSlot + exact Fin.find_spec (p := fun j => eqProfile selfLoop queries j i = true) + ⟨i, eqProfile_refl _ _ _⟩ + +theorem canonicalSlot_le (selfLoop : Bool) (queries : Fin 6 → RawQuery q) + (i j : Fin 6) (h : eqProfile selfLoop queries j i = true) : + canonicalSlot selfLoop queries i ≤ j := + Fin.find_le_of_pos ⟨i, eqProfile_refl _ _ _⟩ h + +def RepeatedConsistent (selfLoop : Bool) (queries : Fin 6 → RawQuery q) + (label : QueryIncidence.Label 6) : Prop := + ∀ i j, eqProfile selfLoop queries i j = true → label i = label j + +instance repeatedConsistentDecidable (selfLoop : Bool) (queries : Fin 6 → RawQuery q) + (label : QueryIncidence.Label 6) : Decidable (RepeatedConsistent selfLoop queries label) := by + unfold RepeatedConsistent + infer_instance + +def incidenceAccept (selfLoop : Bool) (queries : Fin 6 → RawQuery q) + (accept : QueryIncidence.Label 6 → Bool) (slot : Fin 6) + (left right : QueryIncidence.Label 6) : Bool := + decide (accept left = true ∧ RepeatedConsistent selfLoop queries left) && + decide (left (canonicalSlot selfLoop queries slot) = right 0) + +def predicate (selfLoop : Bool) (queries : Fin 6 → RawQuery q) + (accept : QueryIncidence.Label 6 → Bool) (slot : Fin 6) (orientation : Bool) + (a b : QueryIncidence.Label 6) : Bool := + if orientation then incidenceAccept selfLoop queries accept slot b a + else incidenceAccept selfLoop queries accept slot a b + +def relation (P : Fin q → Fin q → Bool) (selfLoop : Bool) + (event : AlphabetGraph.LocalEvent (Fin q)) (slot : Fin 6) (orientation : Bool) : + GraphTables.RelationTable := + GraphTables.relationOf fun a b => + predicate selfLoop (query P event) (AssignmentTester.eventAccepts event.1) + slot orientation (Enumeration.labelEquiv.symm a) (Enumeration.labelEquiv.symm b) + +@[simp] theorem relationAt_relation (P : Fin q → Fin q → Bool) (selfLoop : Bool) + (event : AlphabetGraph.LocalEvent (Fin q)) (slot : Fin 6) (orientation : Bool) + (a b : GraphTables.Label) : + GraphTables.relationAt (relation P selfLoop event slot orientation) a b = + predicate selfLoop (query P event) (AssignmentTester.eventAccepts event.1) + slot orientation (Enumeration.labelEquiv.symm a) (Enumeration.labelEquiv.symm b) := by + exact GraphTables.relationAt_relationOf _ _ _ + +theorem relation_reverse (P : Fin q → Fin q → Bool) (selfLoop : Bool) + (event : AlphabetGraph.LocalEvent (Fin q)) (slot : Fin 6) (orientation : Bool) + (a b : GraphTables.Label) : + GraphTables.relationAt (relation P selfLoop event slot (!orientation)) b a = + GraphTables.relationAt (relation P selfLoop event slot orientation) a b := by + simp only [relationAt_relation] + cases orientation <;> rfl + +def oldPredicate (old : Vector Bool (q * q)) (a b : Fin q) : Bool := + old[(finProdFinEquiv (a, b) : Fin (q * q))] + +def relationFromTable (old : Vector Bool (q * q)) (selfLoop : Bool) + (event : AlphabetGraph.LocalEvent (Fin q)) (slot : Fin 6) (orientation : Bool) : + GraphTables.RelationTable := relation (oldPredicate old) selfLoop event slot orientation + +@[simp] theorem oldPredicate_relationAt (old : GraphTables.RelationTable) + (a b : GraphTables.Label) : oldPredicate old a b = GraphTables.relationAt old a b := rfl + +theorem relationFromTable_eq (old : GraphTables.RelationTable) (selfLoop : Bool) + (event : AlphabetGraph.LocalEvent (Fin 64)) (slot : Fin 6) (orientation : Bool) : + relationFromTable old selfLoop event slot orientation = + relation (GraphTables.relationAt old) selfLoop event slot orientation := rfl + +variable {V E : Type*} [DecidableEq V] [DecidableEq E] + +omit [DecidableEq E] in +theorem eqProfile_query_iff (G : ConstraintGraph V E (Fin q)) (e : E) + (event : AlphabetGraph.LocalEvent (Fin q)) (i j : Fin 6) : + eqProfile (decide (G.tail e = G.head e)) (query (G.accepts e) event) i j = true ↔ + (AlphabetGraph.verifier G).query (e, event) i = + (AlphabetGraph.verifier G).query (e, event) j := by + rw [← globalize_query G e event i, ← globalize_query G e event j] + exact (globalize_eq_iff (G.tail e) (G.head e) e _ rfl _ _).symm + +theorem canonicalSlot_eq (G : ConstraintGraph V E (Fin q)) (e : E) + (event : AlphabetGraph.LocalEvent (Fin q)) (slot : Fin 6) : + canonicalSlot (decide (G.tail e = G.head e)) (query (G.accepts e) event) slot = + QueryIncidence.canonicalSlot (AlphabetGraph.verifier G) (e, event) slot := by + unfold canonicalSlot QueryIncidence.canonicalSlot + apply Fin.find_congr' + exact eqProfile_query_iff G e event _ slot + +omit [DecidableEq E] in +theorem repeatedConsistent_iff (G : ConstraintGraph V E (Fin q)) (e : E) + (event : AlphabetGraph.LocalEvent (Fin q)) (label : QueryIncidence.Label 6) : + RepeatedConsistent (decide (G.tail e = G.head e)) (query (G.accepts e) event) label ↔ + QueryIncidence.RepeatedConsistent (AlphabetGraph.verifier G) (e, event) label := by + constructor + · intro h i j hij + exact h i j ((eqProfile_query_iff G e event i j).mpr hij) + · intro h i j hij + exact h i j ((eqProfile_query_iff G e event i j).mp hij) + +omit [DecidableEq V] [DecidableEq E] in +theorem verifier_accepts (G : ConstraintGraph V E (Fin q)) (e : E) + (event : AlphabetGraph.LocalEvent (Fin q)) (label : QueryIncidence.Label 6) : + (AlphabetGraph.verifier G).accepts (e, event) label = + AssignmentTester.eventAccepts event.1 label := by + rcases event with ⟨kind, k, f, g, r₀, r₁, r₂⟩ + rfl + +theorem incidenceAccept_eq (G : ConstraintGraph V E (Fin q)) (e : E) + (event : AlphabetGraph.LocalEvent (Fin q)) (slot : Fin 6) + (left right : QueryIncidence.Label 6) : + incidenceAccept (decide (G.tail e = G.head e)) (query (G.accepts e) event) + (AssignmentTester.eventAccepts event.1) slot left right = + QueryIncidence.incidenceAccept (AlphabetGraph.verifier G) (by decide) (e, event) slot + left right := by + simp only [incidenceAccept, QueryIncidence.incidenceAccept, QueryIncidence.LeftValid, + verifier_accepts, repeatedConsistent_iff, canonicalSlot_eq, + QueryIncidence.decodeRight, QueryIncidence.zeroSlot] + rfl + +theorem relationAt_relation_graph (G : ConstraintGraph V E (Fin q)) (e : E) + (event : AlphabetGraph.LocalEvent (Fin q)) (slot : Fin 6) (orientation : Bool) + (a b : GraphTables.Label) : + GraphTables.relationAt + (relation (G.accepts e) (decide (G.tail e = G.head e)) event slot orientation) a b = + (AlphabetGraph.graph G).accepts (((e, event), slot), orientation) + (Enumeration.labelEquiv.symm a) (Enumeration.labelEquiv.symm b) := by + rw [relationAt_relation] + cases orientation <;> + exact incidenceAccept_eq G e event slot _ _ + +end MinUncutGames.Foundations.PCP.AlphabetTable.Relations + +namespace MinUncutGames.Foundations.PCP.AlphabetTable.Table + +variable {q : Nat} + +def rowFromDart (input : GenericGraphTables.Table q) + (dart : QueryIncidence.Dart (AlphabetGraph.Event (Fin input.darts) (Fin q)) 6) : + GraphTables.DartRow (Enumeration.vertexCount input.vertices input.darts q) + (Enumeration.dartCount input.darts q) := + let edge := dart.1.1.1 + let event := dart.1.1.2 + let slot := dart.1.2 + let old := input.rows[edge] + let head := input.rows[old.reverseIndex].tail + { tail := Enumeration.vertexEquiv input.vertices input.darts q + (if dart.2 then + .inr (Queries.globalize old.tail head edge + (Queries.query (GenericGraphTables.relationAt old.relation) event slot)) + else .inl (edge, event)) + reverseIndex := Enumeration.dartEquiv input.darts q (dart.1, !dart.2) + relation := Relations.relationFromTable old.relation (decide (old.tail = head)) + event slot dart.2 } + +def rows (input : GenericGraphTables.Table q) : + GraphTables.Rows (Enumeration.vertexCount input.vertices input.darts q) + (Enumeration.dartCount input.darts q) := + Vector.ofFn (fun index => + rowFromDart input ((Enumeration.dartEquiv input.darts q).symm index)) + +@[simp] theorem rows_at (input : GenericGraphTables.Table q) + (index : Fin (Enumeration.dartCount input.darts q)) : + (rows input)[index] = + rowFromDart input ((Enumeration.dartEquiv input.darts q).symm index) := by + simp [rows] + +theorem rows_reverseIndex (input : GenericGraphTables.Table q) + (index : Fin (Enumeration.dartCount input.darts q)) : + (rows input)[index].reverseIndex = + Enumeration.dartEquiv input.darts q + (((Enumeration.dartEquiv input.darts q).symm index).1, + !((Enumeration.dartEquiv input.darts q).symm index).2) := by + simp [rows, rowFromDart] + +private theorem dartRow_ext {n m : Nat} {left right : GraphTables.DartRow n m} + (ht : left.tail = right.tail) (hr : left.reverseIndex = right.reverseIndex) + (hp : left.relation = right.relation) : left = right := by + cases left + cases right + cases ht + cases hr + cases hp + rfl + +theorem relation_ext {left right : GraphTables.RelationTable} + (h : ∀ a b, GraphTables.relationAt left a b = GraphTables.relationAt right a b) : + left = right := by + apply Vector.ext + intro i hi + let labels := GraphTables.relationIndex.symm (⟨i, hi⟩ : Fin 4096) + have index : GraphTables.relationIndex labels = (⟨i, hi⟩ : Fin 4096) := + GraphTables.relationIndex.apply_symm_apply _ + have point := h labels.1 labels.2 + simpa only [GraphTables.relationAt, index, Fin.getElem_fin] using point + +theorem rowFromDart_eq_graphRow (input : GenericGraphTables.Table q) + (dart : QueryIncidence.Dart (AlphabetGraph.Event (Fin input.darts) (Fin q)) 6) : + rowFromDart input dart = + { tail := Enumeration.vertexEquiv input.vertices input.darts q + ((AlphabetGraph.graph (GenericGraphTables.semantics input)).tail dart) + reverseIndex := Enumeration.dartEquiv input.darts q + ((AlphabetGraph.graph (GenericGraphTables.semantics input)).reverse dart) + relation := GraphTables.relationOf (fun a b => + (AlphabetGraph.graph (GenericGraphTables.semantics input)).accepts dart + (Enumeration.labelEquiv.symm a) (Enumeration.labelEquiv.symm b)) } := by + rcases dart with ⟨⟨⟨edge, event⟩, slot⟩, orientation⟩ + apply dartRow_ext + · cases orientation with + | false => rfl + | true => + have query := Queries.globalize_query (GenericGraphTables.semantics input) + edge event slot + have predicate : (GenericGraphTables.semantics input).accepts edge = + GenericGraphTables.relationAt input.rows[edge].relation := rfl + rw [predicate] at query + simpa only [rowFromDart, AlphabetGraph.graph, QueryIncidence.graph, + QueryIncidence.tail, GenericGraphTables.semantics_tail, + ConstraintGraph.head, GenericGraphTables.semantics_reverse, + ite_true] using + congrArg (fun address => Enumeration.vertexEquiv input.vertices input.darts q + (.inr address)) query + · rfl + · apply relation_ext + intro a b + rw [GraphTables.relationAt_relationOf] + have relation := Relations.relationAt_relation_graph (GenericGraphTables.semantics input) + edge event slot orientation a b + have predicate : (GenericGraphTables.semantics input).accepts edge = + Relations.oldPredicate input.rows[edge].relation := rfl + rw [predicate] at relation + simp only [rowFromDart, Relations.relationFromTable, + GenericGraphTables.semantics_tail, ConstraintGraph.head, + GenericGraphTables.semantics_reverse] at relation ⊢ + exact relation + +theorem rows_eq_graphRows (input : GenericGraphTables.Table q) : + rows input = GraphTables.graphRows + (GraphTables.enumeratedGraph (AlphabetGraph.graph (GenericGraphTables.semantics input)) + (Enumeration.vertexEquiv input.vertices input.darts q) + (Enumeration.dartEquiv input.darts q) Enumeration.labelEquiv) := by + apply Vector.ext + intro i hi + simp only [rows, GraphTables.graphRows, Vector.getElem_ofFn] + exact rowFromDart_eq_graphRow input + ((Enumeration.dartEquiv input.darts q).symm ⟨i, hi⟩) + +theorem rows_valid (input : GenericGraphTables.Table q) : GraphTables.Valid (rows input) := by + rw [rows_eq_graphRows] + exact GraphTables.graphRows_valid _ + +def build (input : GenericGraphTables.Table q) : GraphTables.Table where + vertices := Enumeration.vertexCount input.vertices input.darts q + darts := Enumeration.dartCount input.darts q + rows := rows input + valid := rows_valid input + +@[simp] theorem build_vertices (input : GenericGraphTables.Table q) : + (build input).vertices = Enumeration.vertexCount input.vertices input.darts q := rfl + +@[simp] theorem build_darts (input : GenericGraphTables.Table q) : + (build input).darts = Enumeration.dartCount input.darts q := rfl + +private theorem table_rows_congr {n m : Nat} {left right : GraphTables.Rows n m} + (h : left = right) (hl : GraphTables.Valid left) (hr : GraphTables.Valid right) : + (⟨n, m, left, hl⟩ : GraphTables.Table) = ⟨n, m, right, hr⟩ := by + subst right + rfl + +private theorem semantics_rows_congr {n m : Nat} {left right : GraphTables.Rows n m} + (h : left = right) (hl : GraphTables.Valid left) (hr : GraphTables.Valid right) : + GraphTables.semantics (⟨n, m, left, hl⟩ : GraphTables.Table) = + GraphTables.semantics (⟨n, m, right, hr⟩ : GraphTables.Table) := by + subst right + rfl + +theorem build_eq_ofEnumeratedGraph (input : GenericGraphTables.Table q) : + build input = + GraphTables.ofEnumeratedGraph (AlphabetGraph.graph (GenericGraphTables.semantics input)) + (Enumeration.vertexEquiv input.vertices input.darts q) + (Enumeration.dartEquiv input.darts q) Enumeration.labelEquiv := by + exact table_rows_congr (rows_eq_graphRows input) (rows_valid input) + (GraphTables.graphRows_valid _) + +theorem semantics_build (input : GenericGraphTables.Table q) : + GraphTables.semantics (build input) = + GraphTables.enumeratedGraph (AlphabetGraph.graph (GenericGraphTables.semantics input)) + (Enumeration.vertexEquiv input.vertices input.darts q) + (Enumeration.dartEquiv input.darts q) Enumeration.labelEquiv := by + exact (semantics_rows_congr (rows_eq_graphRows input) (rows_valid input) + (GraphTables.graphRows_valid _)).trans (GraphTables.semantics_ofGraph _) + +theorem decode_build (input : GenericGraphTables.Table q) : + GraphTables.decodeTableBits (GraphTables.tableBits (build input)) = + some (GraphTables.ofEnumeratedGraph + (AlphabetGraph.graph (GenericGraphTables.semantics input)) + (Enumeration.vertexEquiv input.vertices input.darts q) + (Enumeration.dartEquiv input.darts q) Enumeration.labelEquiv) := by + rw [GraphTables.decodeTableBits_encoded, build_eq_ofEnumeratedGraph] + +theorem edgeSatisfied_build (input : GenericGraphTables.Table q) + (labeling : QueryIncidence.Vertex (AlphabetGraph.Event (Fin input.darts) (Fin q)) + (AlphabetGraph.Address (Fin input.vertices) (Fin input.darts) (Fin q)) → + QueryIncidence.Label 6) + (dart : QueryIncidence.Dart (AlphabetGraph.Event (Fin input.darts) (Fin q)) 6) : + (GraphTables.semantics (build input)).edgeSatisfied + (fun v => Enumeration.labelEquiv + (labeling ((Enumeration.vertexEquiv input.vertices input.darts q).symm v))) + (Enumeration.dartEquiv input.darts q dart) = + (AlphabetGraph.graph (GenericGraphTables.semantics input)).edgeSatisfied labeling dart := by + rw [semantics_build] + exact GraphTables.enumeratedGraph_edgeSatisfied _ _ _ _ labeling dart + +theorem rejectionCount_build (input : GenericGraphTables.Table q) + (labeling : QueryIncidence.Vertex (AlphabetGraph.Event (Fin input.darts) (Fin q)) + (AlphabetGraph.Address (Fin input.vertices) (Fin input.darts) (Fin q)) → + QueryIncidence.Label 6) : + (GraphTables.semantics (build input)).rejectionCount + (fun v => Enumeration.labelEquiv + (labeling ((Enumeration.vertexEquiv input.vertices input.darts q).symm v))) = + (AlphabetGraph.graph (GenericGraphTables.semantics input)).rejectionCount labeling := by + rw [semantics_build] + exact GraphTables.enumeratedGraph_rejectionCount _ _ _ _ labeling + +theorem perfect_completeness [Nonempty (Fin q)] (input : GenericGraphTables.Table q) + (satisfied : (GenericGraphTables.semantics input).Satisfiable) : + (GraphTables.semantics (build input)).Satisfiable := by + obtain ⟨labeling, accepted⟩ := + AlphabetGraph.perfect_completeness (GenericGraphTables.semantics input) satisfied + refine ⟨fun v => Enumeration.labelEquiv + (labeling ((Enumeration.vertexEquiv input.vertices input.darts q).symm v)), ?_⟩ + intro index + have h := edgeSatisfied_build input labeling + ((Enumeration.dartEquiv input.darts q).symm index) + have index_eq := (Enumeration.dartEquiv input.darts q).apply_symm_apply index + rw [index_eq] at h + exact h.trans (accepted _) + +theorem gap_transfer [Nonempty (Fin q)] (input : GenericGraphTables.Table q) (a b : Nat) + (source : ∀ labeling : Fin input.vertices → Fin q, + a * input.darts ≤ b * (GenericGraphTables.semantics input).rejectionCount labeling) + (labeling : Fin (build input).vertices → GraphTables.Label) : + a * (build input).darts ≤ + (b * 12288) * (GraphTables.semantics (build input)).rejectionCount labeling := by + classical + let lifted := fun vertex => Enumeration.labelEquiv.symm + (labeling (Enumeration.vertexEquiv input.vertices input.darts q vertex)) + have h := AlphabetGraph.gap_transfer (GenericGraphTables.semantics input) a b + (by simpa only [Fintype.card_fin] using source) lifted + rw [Enumeration.card_dart] at h + have counts := rejectionCount_build input lifted + have restored : (fun v : Fin (build input).vertices => Enumeration.labelEquiv + (lifted ((Enumeration.vertexEquiv input.vertices input.darts q).symm v))) = labeling := by + funext v + dsimp only [lifted] + rw [Enumeration.labelEquiv.apply_symm_apply] + exact congrArg labeling + ((Enumeration.vertexEquiv input.vertices input.darts q).apply_symm_apply v) + rw [restored] at counts + rw [← counts] at h + exact h + +theorem rowList_eq_ordered (input : GenericGraphTables.Table q) : + GraphTables.rowList (build input) = + (Enumeration.ordered (Enumeration.dartEquiv input.darts q)).map + (rowFromDart input) := by + change (Vector.ofFn (fun index => rowFromDart input + ((Enumeration.dartEquiv input.darts q).symm index))).toList = + (List.ofFn (Enumeration.dartEquiv input.darts q).symm).map (rowFromDart input) + simp only [Vector.toList_ofFn, List.map_ofFn, Function.comp_def] + +theorem tableWords_eq_ordered (input : GenericGraphTables.Table q) : + GraphTables.tableWords (build input) = + [Enumeration.vertexCount input.vertices input.darts q, + Enumeration.dartCount input.darts q] ++ + (Enumeration.ordered (Enumeration.dartEquiv input.darts q)).flatMap + (fun dart => GraphTables.rowWords (rowFromDart input dart)) := by + simp only [GraphTables.tableWords, rowList_eq_ordered, build_vertices, build_darts, + List.flatMap_map] + +@[simp] theorem rowList_length (input : GenericGraphTables.Table q) : + (GraphTables.rowList (build input)).length = Enumeration.dartCount input.darts q := by + exact GraphTables.rowList_length (build input) + +theorem tableWords_length (input : GenericGraphTables.Table q) : + (GraphTables.tableWords (build input)).length = + 2 + 4098 * Enumeration.dartCount input.darts q := by + exact GraphTables.tableWords_length (build input) + +theorem tableBits_length_le (input : GenericGraphTables.Table q) : + (GraphTables.tableBits (build input)).length ≤ + Enumeration.vertexCount input.vertices input.darts q + + Enumeration.dartCount input.darts q + 2 + Enumeration.dartCount input.darts q * + (Enumeration.vertexCount input.vertices input.darts q + + Enumeration.dartCount input.darts q + 8192) := by + exact GraphTables.tableBits_length_le (build input) + +end MinUncutGames.Foundations.PCP.AlphabetTable.Table + +namespace MinUncutGames.Foundations.PCP.AlphabetGraphBounds + +open scoped BigOperators + +abbrev OutputVertex (V E A : Type*) := + QueryIncidence.Vertex (AlphabetGraph.Event E A) (AlphabetGraph.Address V E A) + +abbrev OutputDart (E A : Type*) := QueryIncidence.Dart (AlphabetGraph.Event E A) 6 + +def localEventFactor (q : Nat) : Nat := + 4 * (2 * 2 ^ q) * (2 ^ (q * q)) ^ 5 + +def vertexFactor (q : Nat) : Nat := localEventFactor q + 2 ^ (q * q) + +def dartFactor (q : Nat) : Nat := 12 * localEventFactor q + +def sizeFactor (q : Nat) : Nat := 2 ^ q + vertexFactor q + dartFactor q + +theorem sizeFactor_positive (q : Nat) : 0 < sizeFactor q := by + have hp : (0 : Nat) < 2 ^ q := pow_pos (by decide) q + unfold sizeFactor + omega + +variable {V E A : Type*} [Fintype A] [DecidableEq A] [Nonempty A] + +theorem gap_transfer_real [Fintype E] [DecidableEq V] [DecidableEq E] + (G : ConstraintGraph V E A) (eps : ℝ) (_eps_nonnegative : 0 ≤ eps) + (source : ∀ labeling : V → A, + eps * (Fintype.card E : ℝ) ≤ (G.rejectionCount labeling : ℝ)) + (labeling : OutputVertex V E A → QueryIncidence.Label 6) : + (eps / 12288) * (Fintype.card (OutputDart E A) : ℝ) ≤ + ((AlphabetGraph.graph G).rejectionCount labeling : ℝ) := by + let assignment := QueryIncidence.decodedAssignment (by decide : 0 < 6) labeling + have htest : + (Fintype.card (AlphabetGraph.LocalEvent A) : ℝ) * + (G.rejectionCount (AlphabetGraph.decodedLabeling assignment) : ℝ) ≤ + 2048 * (QueryIncidence.verifierRejectionCount (AlphabetGraph.verifier G) assignment : ℝ) := by + exact_mod_cast AlphabetGraph.rejection_count_bound G assignment + have hinc : + 2 * (QueryIncidence.verifierRejectionCount (AlphabetGraph.verifier G) assignment : ℝ) ≤ + ((AlphabetGraph.graph G).rejectionCount labeling : ℝ) := by + exact_mod_cast QueryIncidence.rejection_count_bound + (AlphabetGraph.verifier G) (by decide : 0 < 6) labeling + have hscaled : + eps * (Fintype.card E : ℝ) * (Fintype.card (AlphabetGraph.LocalEvent A) : ℝ) ≤ + 2048 * (QueryIncidence.verifierRejectionCount (AlphabetGraph.verifier G) assignment : ℝ) := by + calc + _ = (Fintype.card (AlphabetGraph.LocalEvent A) : ℝ) * + (eps * (Fintype.card E : ℝ)) := by ring + _ ≤ (Fintype.card (AlphabetGraph.LocalEvent A) : ℝ) * + (G.rejectionCount (AlphabetGraph.decodedLabeling assignment) : ℝ) := + mul_le_mul_of_nonneg_left (source (AlphabetGraph.decodedLabeling assignment)) + (Nat.cast_nonneg _) + _ ≤ _ := htest + change (eps / 12288) * + (Fintype.card (QueryIncidence.Dart (AlphabetGraph.Event E A) 6) : ℝ) ≤ _ + rw [QueryIncidence.card_dart, AlphabetGraph.card_event] + push_cast + nlinarith + +omit [Nonempty A] + +variable [Fintype V] [Fintype E] + +theorem card_output_vertex : + Fintype.card (OutputVertex V E A) = + Fintype.card V * 2 ^ Fintype.card A + + Fintype.card E * vertexFactor (Fintype.card A) := by + rw [QueryIncidence.card_vertex, AlphabetGraph.card_event, + AlphabetGraph.card_address, AlphabetGraph.card_localEvent] + unfold vertexFactor localEventFactor + ring + +theorem card_output_dart : + Fintype.card (OutputDart E A) = Fintype.card E * dartFactor (Fintype.card A) := by + rw [QueryIncidence.card_dart, AlphabetGraph.card_event, AlphabetGraph.card_localEvent] + unfold dartFactor localEventFactor + ring + +theorem card_output_total : + Fintype.card (OutputVertex V E A) + Fintype.card (OutputDart E A) = + Fintype.card V * 2 ^ Fintype.card A + + Fintype.card E * (vertexFactor (Fintype.card A) + dartFactor (Fintype.card A)) := by + rw [card_output_vertex, card_output_dart] + ring + +theorem card_output_total_le : + Fintype.card (OutputVertex V E A) + Fintype.card (OutputDart E A) ≤ + sizeFactor (Fintype.card A) * (Fintype.card V + Fintype.card E) := by + rw [card_output_total] + have hv : 2 ^ Fintype.card A ≤ sizeFactor (Fintype.card A) := by + unfold sizeFactor + omega + have he : vertexFactor (Fintype.card A) + dartFactor (Fintype.card A) ≤ + sizeFactor (Fintype.card A) := by + unfold sizeFactor + exact Nat.add_le_add_right (Nat.le_add_left _ _) _ + calc + _ ≤ Fintype.card V * sizeFactor (Fintype.card A) + + Fintype.card E * sizeFactor (Fintype.card A) := + Nat.add_le_add (Nat.mul_le_mul_left _ hv) (Nat.mul_le_mul_left _ he) + _ = _ := by ring + +theorem card_output_vertex_le : + Fintype.card (OutputVertex V E A) ≤ + sizeFactor (Fintype.card A) * (Fintype.card V + Fintype.card E) := + (Nat.le_add_right _ _).trans card_output_total_le + +theorem card_output_dart_le : + Fintype.card (OutputDart E A) ≤ + sizeFactor (Fintype.card A) * (Fintype.card V + Fintype.card E) := + (Nat.le_add_left _ _).trans card_output_total_le + +end MinUncutGames.Foundations.PCP.AlphabetGraphBounds + +namespace MinUncutGames.Foundations.PCP.AlphabetTableBounds + +open AlphabetTable + +variable {q : Nat} + +theorem gap_transfer_real (hq : 0 < q) (input : GenericGraphTables.Table q) + (eps : ℝ) (eps_nonnegative : 0 ≤ eps) + (source : ∀ labeling : Fin input.vertices → Fin q, + eps * (input.darts : ℝ) ≤ + ((GenericGraphTables.semantics input).rejectionCount labeling : ℝ)) + (labeling : Fin (Table.build input).vertices → GraphTables.Label) : + (eps / 12288) * ((Table.build input).darts : ℝ) ≤ + ((GraphTables.semantics (Table.build input)).rejectionCount labeling : ℝ) := by + classical + let : Nonempty (Fin q) := ⟨⟨0, hq⟩⟩ + let lifted := fun vertex => Enumeration.labelEquiv.symm + (labeling (Enumeration.vertexEquiv input.vertices input.darts q vertex)) + have h := AlphabetGraphBounds.gap_transfer_real + (GenericGraphTables.semantics input) eps eps_nonnegative + (by simpa only [Fintype.card_fin] using source) lifted + rw [Enumeration.card_dart] at h + have counts := Table.rejectionCount_build input lifted + have restored : (fun v : Fin (Table.build input).vertices => Enumeration.labelEquiv + (lifted ((Enumeration.vertexEquiv input.vertices input.darts q).symm v))) = labeling := by + funext v + dsimp only [lifted] + rw [Enumeration.labelEquiv.apply_symm_apply] + exact congrArg labeling + ((Enumeration.vertexEquiv input.vertices input.darts q).apply_symm_apply v) + rw [restored] at counts + rw [← counts] at h + exact h + +theorem build_vertices (input : GenericGraphTables.Table q) : + (Table.build input).vertices = input.vertices * 2 ^ q + + input.darts * AlphabetGraphBounds.vertexFactor q := by + rw [Table.build_vertices] + simp only [Enumeration.vertexCount, Enumeration.eventCount, Enumeration.addressCount, + Enumeration.localCount, Enumeration.tapeCount, Enumeration.pairTapeCount, + Enumeration.fiveTapeCount, AlphabetGraphBounds.vertexFactor, + AlphabetGraphBounds.localEventFactor] + ring + +theorem build_darts (input : GenericGraphTables.Table q) : + (Table.build input).darts = input.darts * AlphabetGraphBounds.dartFactor q := by + rw [Table.build_darts] + simp only [Enumeration.dartCount, Enumeration.eventCount, Enumeration.localCount, + Enumeration.tapeCount, Enumeration.pairTapeCount, Enumeration.fiveTapeCount, + AlphabetGraphBounds.dartFactor, AlphabetGraphBounds.localEventFactor] + ring + +theorem build_total (input : GenericGraphTables.Table q) : + (Table.build input).vertices + (Table.build input).darts = + input.vertices * 2 ^ q + input.darts * + (AlphabetGraphBounds.vertexFactor q + AlphabetGraphBounds.dartFactor q) := by + rw [build_vertices, build_darts] + ring + +theorem build_total_le (input : GenericGraphTables.Table q) : + (Table.build input).vertices + (Table.build input).darts ≤ + AlphabetGraphBounds.sizeFactor q * (input.vertices + input.darts) := by + rw [build_total] + have hv : 2 ^ q ≤ AlphabetGraphBounds.sizeFactor q := by + unfold AlphabetGraphBounds.sizeFactor + omega + have he : AlphabetGraphBounds.vertexFactor q + AlphabetGraphBounds.dartFactor q ≤ + AlphabetGraphBounds.sizeFactor q := by + unfold AlphabetGraphBounds.sizeFactor + exact Nat.add_le_add_right (Nat.le_add_left _ _) _ + calc + _ ≤ input.vertices * AlphabetGraphBounds.sizeFactor q + + input.darts * AlphabetGraphBounds.sizeFactor q := + Nat.add_le_add (Nat.mul_le_mul_left _ hv) (Nat.mul_le_mul_left _ he) + _ = _ := by ring + +theorem build_vertices_le (input : GenericGraphTables.Table q) : + (Table.build input).vertices ≤ + AlphabetGraphBounds.sizeFactor q * (input.vertices + input.darts) := + (Nat.le_add_right _ _).trans (build_total_le input) + +theorem build_darts_le (input : GenericGraphTables.Table q) : + (Table.build input).darts ≤ + AlphabetGraphBounds.sizeFactor q * (input.vertices + input.darts) := + (Nat.le_add_left _ _).trans (build_total_le input) + +theorem sizeFactor_positive : 0 < AlphabetGraphBounds.sizeFactor q := + AlphabetGraphBounds.sizeFactor_positive q + +end MinUncutGames.Foundations.PCP.AlphabetTableBounds + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/Runtime.lean b/lean/OAI/Computability/MinUncut/Machines/Runtime.lean new file mode 100644 index 0000000000000000000000000000000000000000..dcb69c027d286c6fb58567cf3b1bc53723ad4d11 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/Runtime.lean @@ -0,0 +1,735 @@ +import Mathlib +import OAI.Computability.MinUncut.Encoding.UniformEncoding +import OAI.Computability.MinUncut.Estimates.PolynomialRecursor + +namespace OAI + +namespace MinUncutGames.Foundations.Complexity.Runtime + +def statementPushBound {K : Type} {Γ : K → Type} {Λ σ : Type} : + Turing.TM2.Stmt Γ Λ σ → Nat + | .push _ _ next => statementPushBound next + 1 + | .peek _ _ next => statementPushBound next + | .pop _ _ next => statementPushBound next + | .load _ next => statementPushBound next + | .branch _ yes no => max (statementPushBound yes) (statementPushBound no) + | .goto _ => 0 + | .halt => 0 + +def maxLabelPushes {K : Type} {Γ : K → Type} {Λ σ : Type} + (program : Λ → Turing.TM2.Stmt Γ Λ σ) : List Λ → Nat + | [] => 0 + | label :: rest => max (statementPushBound (program label)) (maxLabelPushes program rest) + +theorem maxLabelPushes_ge {K : Type} {Γ : K → Type} {Λ σ : Type} + (program : Λ → Turing.TM2.Stmt Γ Λ σ) (labels : List Λ) (label : Λ) + (member : label ∈ labels) : + statementPushBound (program label) ≤ maxLabelPushes program labels := by + induction labels with + | nil => simp at member + | cons first rest ih => + simp only [List.mem_cons] at member + rcases member with rfl | member + · exact Nat.le_max_left _ _ + · exact Nat.le_trans (ih member) (Nat.le_max_right _ _) + +noncomputable def programPushBound (tm : Turing.FinTM2) : Nat := + maxLabelPushes tm.m tm.ΛFin.elems.toList + +theorem statement_le_programPushBound (tm : Turing.FinTM2) (label : tm.Λ) : + statementPushBound (tm.m label) ≤ programPushBound tm := by + apply maxLabelPushes_ge + simpa using tm.ΛFin.complete label + +theorem stepAuxStackLength {K : Type} {Γ : K → Type} {Λ σ : Type} [DecidableEq K] + (stmt : Turing.TM2.Stmt Γ Λ σ) (state : σ) (tapes : ∀ k, List (Γ k)) (k : K) : + ((Turing.TM2.stepAux stmt state tapes).stk k).length ≤ + (tapes k).length + statementPushBound stmt := by + induction stmt generalizing state tapes with + | push j f next ih => + have changed : ((Function.update tapes j (f state :: tapes j)) k).length ≤ + (tapes k).length + 1 := by + by_cases same : k = j + · subst k; simp + · simp [Function.update, same] + have h := ih state (Function.update tapes j (f state :: tapes j)) + simp only [Turing.TM2.stepAux, statementPushBound] + omega + | peek j f next ih => + simpa only [Turing.TM2.stepAux, statementPushBound] using + ih (f state (tapes j).head?) tapes + | pop j f next ih => + have changed : ((Function.update tapes j (tapes j).tail) k).length ≤ + (tapes k).length := by + by_cases same : k = j + · subst k; simp + · simp [Function.update, same] + have h := ih (f state (tapes j).head?) (Function.update tapes j (tapes j).tail) + simp only [Turing.TM2.stepAux, statementPushBound] + omega + | load f next ih => + simpa only [Turing.TM2.stepAux, statementPushBound] using ih (f state) tapes + | branch condition yes no ihYes ihNo => + cases decision : condition state with + | false => + have h := ihNo state tapes + have hm := Nat.le_max_right (statementPushBound yes) (statementPushBound no) + simp only [Turing.TM2.stepAux, statementPushBound, decision, Bool.cond_false] + omega + | true => + have h := ihYes state tapes + have hm := Nat.le_max_left (statementPushBound yes) (statementPushBound no) + simp only [Turing.TM2.stepAux, statementPushBound, decision, Bool.cond_true] + omega + | goto f => simp [Turing.TM2.stepAux, statementPushBound] + | halt => simp [Turing.TM2.stepAux, statementPushBound] + +private theorem iterateSizeBound {α : Type} (f : α → α) (size : α → Nat) (C : Nat) + (oneStep : ∀ x, size (f x) ≤ size x + C) (n : Nat) (x : α) : + size ((f^[n]) x) ≤ size x + n * C := by + induction n with + | zero => simp + | succ n ih => + have hs := oneStep ((f^[n]) x) + have bound : size (f ((f^[n]) x)) ≤ size x + (n + 1) * C := by + rw [Nat.add_mul, Nat.one_mul] + omega + simpa only [Function.iterate_succ_apply'] using bound + +theorem executionSizeBound {σ : Type} (step : σ → Option σ) (size : σ → Nat) (C : Nat) + (oneStep : ∀ a b, step a = some b → size b ≤ size a + C) + {start finish : σ} {budget : Nat} + (execution : StateTransition.EvalsToInTime step start (some finish) budget) : + size finish ≤ size start + budget * C := by + let liftedSize : Option σ → Nat := fun state => (state.map size).getD 0 + have liftedStep : ∀ state : Option σ, + liftedSize (state.bind step) ≤ liftedSize state + C := by + intro state + cases state with + | none => simp [liftedSize] + | some a => + cases transition : step a with + | none => simp [liftedSize, transition] + | some b => simpa [liftedSize, transition] using oneStep a b transition + have bound := iterateSizeBound (fun state : Option σ => state.bind step) + liftedSize C liftedStep execution.steps (some start) + change liftedSize ((flip bind step)^[execution.steps] (some start)) ≤ _ at bound + rw [execution.evals_in_steps] at bound + simp only [liftedSize, Option.map_some, Option.getD_some] at bound + exact Nat.le_trans bound (Nat.add_le_add_left + (Nat.mul_le_mul_right C execution.steps_le_m) _) + +theorem stepStackLength (tm : Turing.FinTM2) (k : tm.K) (a b : tm.Cfg) + (transition : tm.step a = some b) : + (b.stk k).length ≤ (a.stk k).length + programPushBound tm := by + cases a with + | mk label state tapes => + cases label with + | none => simp [Turing.FinTM2.step, Turing.TM2.step] at transition + | some label => + have result := Option.some.inj transition + rw [← result] + exact Nat.le_trans (stepAuxStackLength _ _ _ _) + (Nat.add_le_add_left (statement_le_programPushBound tm label) _) + +theorem initialStackLength (tm : Turing.FinTM2) (input : List (tm.Γ tm.k₀)) (k : tm.K) : + ((Turing.initList tm input).stk k).length ≤ input.length := by + simp only [Turing.initList] + split + next same => subst k; exact Nat.le_refl _ + next _ => simp + +@[simp] theorem haltedOutputLength (tm : Turing.FinTM2) (output : List (tm.Γ tm.k₁)) : + ((Turing.haltList tm output).stk tm.k₁).length = output.length := by + simp [Turing.haltList] + +theorem outputLength_le (tm : Turing.FinTM2) (input : List (tm.Γ tm.k₀)) + (output : List (tm.Γ tm.k₁)) (budget : Nat) + (execution : Turing.TM2OutputsInTime tm input (some output) budget) : + output.length ≤ input.length + budget * programPushBound tm := by + have bound := executionSizeBound tm.step (fun cfg => (cfg.stk tm.k₁).length) + (programPushBound tm) (stepStackLength tm tm.k₁) execution + calc + output.length = ((Turing.haltList tm output).stk tm.k₁).length := (haltedOutputLength tm output).symm + _ ≤ ((Turing.initList tm input).stk tm.k₁).length + budget * programPushBound tm := bound + _ ≤ input.length + budget * programPushBound tm := + Nat.add_le_add_right (initialStackLength tm input tm.k₁) _ + +theorem encodedOutputLength {α β αΓ βΓ : Type} + {ea : α → List αΓ} {eb : β → List βΓ} {f : α → β} + (certificate : Turing.TM2ComputableInPolyTime ea eb f) (a : α) : + (eb (f a)).length ≤ + (Polynomial.X + Polynomial.C (programPushBound certificate.tm) * certificate.time).eval + (ea a).length := by + have bound := outputLength_le certificate.tm _ _ _ (certificate.outputsFun a) + simpa only [List.length_map, Polynomial.eval_add, Polynomial.eval_X, + Polynomial.eval_mul, Polynomial.eval_C, Nat.mul_comm] using bound + +end MinUncutGames.Foundations.Complexity.Runtime + +namespace MinUncutGames.Foundations.Complexity.MachineEmbedding + +open Turing.TM2 + +variable {K E Λ Λextra σ τ : Type} {Γ : K → Type} {Δ : E → Type} + +abbrev Alphabet (Γ : K → Type) (Δ : E → Type) : K ⊕ E → Type + | .inl k => Γ k + | .inr e => Δ e + +def tapes (source : ∀ k, List (Γ k)) (extra : ∀ e, List (Δ e)) : + ∀ j, List (Alphabet Γ Δ j) + | .inl k => source k + | .inr e => extra e + +@[simp] theorem tapes_inl (source : ∀ k, List (Γ k)) (extra : ∀ e, List (Δ e)) + (k : K) : tapes source extra (.inl k) = source k := rfl + +@[simp] theorem tapes_inr (source : ∀ k, List (Γ k)) (extra : ∀ e, List (Δ e)) + (e : E) : tapes source extra (.inr e) = extra e := rfl + +def label (haltTarget : Option (Λ ⊕ Λextra)) : Option Λ → Option (Λ ⊕ Λextra) + | none => haltTarget + | some l => some (.inl l) + +def configuration (haltTarget : Option (Λ ⊕ Λextra)) (extraState : τ) + (extraTapes : ∀ e, List (Δ e)) (c : Cfg Γ Λ σ) : + Cfg (Alphabet Γ Δ) (Λ ⊕ Λextra) (σ × τ) where + l := label haltTarget c.l + var := (c.var, extraState) + stk := tapes c.stk extraTapes + +def statement (haltTarget : Option (Λ ⊕ Λextra)) : + Stmt Γ Λ σ → Stmt (Alphabet Γ Δ) (Λ ⊕ Λextra) (σ × τ) + | .push k f next => .push (.inl k) (fun st => f st.1) (statement haltTarget next) + | .peek k f next => .peek (.inl k) (fun st v => (f st.1 v, st.2)) + (statement haltTarget next) + | .pop k f next => .pop (.inl k) (fun st v => (f st.1 v, st.2)) + (statement haltTarget next) + | .load f next => .load (fun st => (f st.1, st.2)) (statement haltTarget next) + | .branch f yes no => .branch (fun st => f st.1) + (statement haltTarget yes) (statement haltTarget no) + | .goto f => .goto (fun st => .inl (f st.1)) + | .halt => match haltTarget with + | none => .halt + | some l => .goto (fun _ => l) + +variable [DecidableEq K] [DecidableEq E] + +theorem tapes_update (source : ∀ k, List (Γ k)) (extra : ∀ e, List (Δ e)) + (k : K) (value : List (Γ k)) : + tapes (Function.update source k value) extra = + Function.update (tapes source extra) (.inl k) value := by + funext j + cases j with + | inl j => + by_cases h : j = k + · subst j + simp [Function.update] + · simp [Function.update, h] + | inr e => simp [Function.update] + +theorem stepAux_simulation (haltTarget : Option (Λ ⊕ Λextra)) + (extraState : τ) (extraTapes : ∀ e, List (Δ e)) + (q : Stmt Γ Λ σ) (state : σ) (source : ∀ k, List (Γ k)) : + stepAux (statement haltTarget q) (state, extraState) (tapes source extraTapes) = + configuration haltTarget extraState extraTapes (stepAux q state source) := by + induction q generalizing state source with + | push k f next ih => + simp only [statement, stepAux, tapes_inl] + rw [← tapes_update] + exact ih state (Function.update source k (f state :: source k)) + | peek k f next ih => + simpa only [statement, stepAux, tapes_inl] using + ih (f state (source k).head?) source + | pop k f next ih => + simp only [statement, stepAux, tapes_inl] + rw [← tapes_update] + exact ih (f state (source k).head?) (Function.update source k (source k).tail) + | load f next ih => + simpa only [statement, stepAux] using ih (f state) source + | branch f yes no ihYes ihNo => + cases h : f state with + | false => simpa only [statement, stepAux, h, Bool.cond_false] using ihNo state source + | true => simpa only [statement, stepAux, h, Bool.cond_true] using ihYes state source + | goto f => rfl + | halt => cases haltTarget <;> rfl + +theorem stepAux_preserves_extra_state (haltTarget : Option (Λ ⊕ Λextra)) + (extraState : τ) (extraTapes : ∀ e, List (Δ e)) + (q : Stmt Γ Λ σ) (state : σ) (source : ∀ k, List (Γ k)) : + (stepAux (statement haltTarget q) (state, extraState) + (tapes source extraTapes)).var.2 = extraState := by + rw [stepAux_simulation] + rfl + +theorem stepAux_preserves_extra_tape (haltTarget : Option (Λ ⊕ Λextra)) + (extraState : τ) (extraTapes : ∀ e, List (Δ e)) + (q : Stmt Γ Λ σ) (state : σ) (source : ∀ k, List (Γ k)) (e : E) : + (stepAux (statement haltTarget q) (state, extraState) + (tapes source extraTapes)).stk (.inr e) = extraTapes e := by + rw [stepAux_simulation] + rfl + +def program (haltTarget : Option (Λ ⊕ Λextra)) (source : Λ → Stmt Γ Λ σ) + (extra : Λextra → Stmt (Alphabet Γ Δ) (Λ ⊕ Λextra) (σ × τ)) : + Λ ⊕ Λextra → Stmt (Alphabet Γ Δ) (Λ ⊕ Λextra) (σ × τ) + | .inl l => statement haltTarget (source l) + | .inr l => extra l + +theorem step_running (haltTarget : Option (Λ ⊕ Λextra)) + (extraState : τ) (extraTapes : ∀ e, List (Δ e)) + (source : Λ → Stmt Γ Λ σ) + (extra : Λextra → Stmt (Alphabet Γ Δ) (Λ ⊕ Λextra) (σ × τ)) + (l : Λ) (state : σ) (sourceTapes : ∀ k, List (Γ k)) : + step (program haltTarget source extra) + (configuration haltTarget extraState extraTapes ⟨some l, state, sourceTapes⟩) = + some (configuration haltTarget extraState extraTapes + (stepAux (source l) state sourceTapes)) := by + change some (stepAux (statement haltTarget (source l)) (state, extraState) + (tapes sourceTapes extraTapes)) = _ + rw [stepAux_simulation] + +theorem step_simulation (haltTarget : Option (Λ ⊕ Λextra)) + (extraState : τ) (extraTapes : ∀ e, List (Δ e)) + (source : Λ → Stmt Γ Λ σ) + (extra : Λextra → Stmt (Alphabet Γ Δ) (Λ ⊕ Λextra) (σ × τ)) + (a b : Cfg Γ Λ σ) (h : step source a = some b) : + step (program haltTarget source extra) + (configuration haltTarget extraState extraTapes a) = + some (configuration haltTarget extraState extraTapes b) := by + cases a with + | mk l state sourceTapes => + cases l with + | none => simp [step] at h + | some l => + have hb : stepAux (source l) state sourceTapes = b := Option.some.inj h + rw [← hb] + exact step_running haltTarget extraState extraTapes source extra l state sourceTapes + +end MinUncutGames.Foundations.Complexity.MachineEmbedding + +namespace MinUncutGames.Foundations.Complexity.MachineComposition + +def advance {σ : Type} (step : σ → Option σ) (state : Option σ) : Option σ := + state.bind step + +@[simp] theorem advance_none {σ : Type} (step : σ → Option σ) : + advance step none = none := rfl + +@[simp] theorem advance_some {σ : Type} (step : σ → Option σ) (state : σ) : + advance step (some state) = step state := rfl + +@[simp] theorem advance_iterate_none {σ : Type} (step : σ → Option σ) (n : Nat) : + (advance step)^[n] none = none := by + induction n with + | zero => rfl + | succ n ih => rw [Function.iterate_succ_apply', ih, advance_none] + +theorem liftSuccessfulTrace {σ τ : Type} (source : σ → Option σ) + (target : τ → Option τ) (embed : σ → τ) + (simulation : ∀ a b, source a = some b → target (embed a) = some (embed b)) + (n : Nat) (start finish : σ) + (trace : (advance source)^[n] (some start) = some finish) : + (advance target)^[n] (some (embed start)) = some (embed finish) := by + induction n generalizing start with + | zero => + have same := Option.some.inj trace + cases same + rfl + | succ n ih => + rw [Function.iterate_succ_apply] at trace ⊢ + change (advance source)^[n] (source start) = some finish at trace + change (advance target)^[n] (target (embed start)) = some (embed finish) + cases firstStep : source start with + | none => + rw [firstStep, advance_iterate_none] at trace + contradiction + | some intermediate => + rw [firstStep] at trace + rw [simulation start intermediate firstStep] + exact ih intermediate trace + +def liftExecutionInTime {σ τ : Type} (source : σ → Option σ) + (target : τ → Option τ) (embed : σ → τ) + (simulation : ∀ a b, source a = some b → target (embed a) = some (embed b)) + {start finish : σ} {budget : Nat} + (execution : StateTransition.EvalsToInTime source start (some finish) budget) : + StateTransition.EvalsToInTime target (embed start) (some (embed finish)) budget where + steps := execution.steps + evals_in_steps := by + have sourceTrace := execution.evals_in_steps + change (advance source)^[execution.steps] (some start) = some finish at sourceTrace + change (advance target)^[execution.steps] (some (embed start)) = some (embed finish) + exact liftSuccessfulTrace source target embed simulation execution.steps start finish sourceTrace + steps_le_m := execution.steps_le_m + +@[simp] theorem liftExecutionInTime_steps {σ τ : Type} (source : σ → Option σ) + (target : τ → Option τ) (embed : σ → τ) + (simulation : ∀ a b, source a = some b → target (embed a) = some (embed b)) + {start finish : σ} {budget : Nat} + (execution : StateTransition.EvalsToInTime source start (some finish) budget) : + (liftExecutionInTime source target embed simulation execution).steps = execution.steps := rfl + +def embeddedExecution {K E Λ Λextra σ τ : Type} {Γ : K → Type} {Δ : E → Type} + [DecidableEq K] [DecidableEq E] + (haltTarget : Option (Λ ⊕ Λextra)) (extraState : τ) + (extraTapes : ∀ e, List (Δ e)) + (source : Λ → Turing.TM2.Stmt Γ Λ σ) + (extra : Λextra → Turing.TM2.Stmt (MachineEmbedding.Alphabet Γ Δ) + (Λ ⊕ Λextra) (σ × τ)) + {start finish : Turing.TM2.Cfg Γ Λ σ} {budget : Nat} + (execution : StateTransition.EvalsToInTime (Turing.TM2.step source) + start (some finish) budget) : + StateTransition.EvalsToInTime (Turing.TM2.step (MachineEmbedding.program haltTarget source extra)) + (MachineEmbedding.configuration haltTarget extraState extraTapes start) + (some (MachineEmbedding.configuration haltTarget extraState extraTapes finish)) budget := + liftExecutionInTime (Turing.TM2.step source) + (Turing.TM2.step (MachineEmbedding.program haltTarget source extra)) + (MachineEmbedding.configuration haltTarget extraState extraTapes) + (MachineEmbedding.step_simulation haltTarget extraState extraTapes source extra) execution + +theorem natPolynomial_eval_mono (p : Polynomial Nat) {a b : Nat} (h : a ≤ b) : + p.eval a ≤ p.eval b := by + induction p using Polynomial.induction_on' with + | add p q hp hq => + simpa only [Polynomial.eval_add] using Nat.add_le_add hp hq + | monomial degree coefficient => + simp only [Polynomial.eval_monomial] + exact Nat.mul_le_mul_left coefficient (Nat.pow_le_pow_left h degree) + +noncomputable def compositionPolynomial (first second intermediate : Polynomial Nat) : Polynomial Nat := + first + Polynomial.C 2 * (intermediate + 1) + second.comp intermediate + +theorem compositionBudget_le (first second intermediate : Polynomial Nat) + (inputLength intermediateLength : Nat) + (intermediateBound : intermediateLength ≤ intermediate.eval inputLength) : + first.eval inputLength + 2 * (intermediateLength + 1) + second.eval intermediateLength ≤ + (compositionPolynomial first second intermediate).eval inputLength := by + have secondBound := natPolynomial_eval_mono second intermediateBound + have transferBound := Nat.mul_le_mul_left 2 (Nat.add_le_add_right intermediateBound 1) + simp only [compositionPolynomial, Polynomial.eval_add, Polynomial.eval_mul, + Polynomial.eval_C, Polynomial.eval_one, Polynomial.eval_comp] + omega + +def fourPhaseExecution {σ : Type} (step : σ → Option σ) + (start afterFirst afterTransfer₁ afterTransfer₂ : σ) (finish : Option σ) + (first second intermediate : Polynomial Nat) (inputLength intermediateLength : Nat) + (intermediateBound : intermediateLength ≤ intermediate.eval inputLength) + (runFirst : StateTransition.EvalsToInTime step start (some afterFirst) (first.eval inputLength)) + (transfer₁ : StateTransition.EvalsToInTime step afterFirst (some afterTransfer₁) + (intermediateLength + 1)) + (transfer₂ : StateTransition.EvalsToInTime step afterTransfer₁ (some afterTransfer₂) + (intermediateLength + 1)) + (runSecond : StateTransition.EvalsToInTime step afterTransfer₂ finish + (second.eval intermediateLength)) : + StateTransition.EvalsToInTime step start finish + ((compositionPolynomial first second intermediate).eval inputLength) := by + let firstTwo := StateTransition.EvalsToInTime.trans step _ _ start afterFirst + (some afterTransfer₁) runFirst transfer₁ + let firstThree := StateTransition.EvalsToInTime.trans step _ _ start afterTransfer₁ + (some afterTransfer₂) firstTwo transfer₂ + let allFour := StateTransition.EvalsToInTime.trans step _ _ start afterTransfer₂ + finish firstThree runSecond + refine { + toEvalsTo := allFour.toEvalsTo + steps_le_m := Nat.le_trans allFour.steps_le_m ?_ + } + have bounded := compositionBudget_le first second intermediate inputLength intermediateLength + intermediateBound + omega + +end MinUncutGames.Foundations.Complexity.MachineComposition + +namespace MinUncutGames.Reduction.MachineTransfer + +open Turing + +abbrev alphabet (α β : Type) : Bool → Type + | false => α + | true => β + +variable {α β : Type} [Fintype α] [Fintype β] + +def loop (f : α → β) (fallback : β) : + TM2.Stmt (alphabet α β) Unit (Option β) := + .pop false (fun _ head => head.map f) + (.branch Option.isSome + (.push true (fun state => state.getD fallback) (.goto fun _ => ())) + .halt) + +def machine (f : α → β) (fallback : β) : FinTM2 where + K := Bool + k₀ := false + k₁ := true + Γ := alphabet α β + Λ := Unit + main := () + σ := Option β + initialState := none + Γk₀Fin := inferInstanceAs (Fintype α) + m _ := loop f fallback + +def tapeStacks (input : List α) (output : List β) : + (side : Bool) → List (alphabet α β side) + | false => input + | true => output + +def running (f : α → β) (fallback : β) (input : List α) (output : List β) + (state : Option β) : (machine f fallback).Cfg := + ⟨some (), state, tapeStacks input output⟩ + +def halted (f : α → β) (fallback : β) (output : List β) : (machine f fallback).Cfg := + ⟨none, none, tapeStacks (α := α) [] output⟩ + +omit [Fintype α] [Fintype β] in +theorem update_input (input replacement : List α) (output : List β) : + Function.update (tapeStacks input output) false replacement = tapeStacks replacement output := by + funext side + cases side <;> rfl + +omit [Fintype α] [Fintype β] in +theorem update_output (input : List α) (output replacement : List β) : + Function.update (tapeStacks input output) true replacement = tapeStacks input replacement := by + funext side + cases side <;> rfl + +theorem step_empty (f : α → β) (fallback : β) (output : List β) (state : Option β) : + (machine f fallback).step (running f fallback [] output state) = + some (halted f fallback output) := by + change some (TM2.stepAux (loop f fallback) state (tapeStacks (α := α) [] output)) = _ + simp [loop, TM2.stepAux, tapeStacks, halted, Function.update] + rw [update_input] + rfl + +theorem step_cons (f : α → β) (fallback : β) (head : α) (input : List α) + (output : List β) (state : Option β) : + (machine f fallback).step (running f fallback (head :: input) output state) = + some (running f fallback input (f head :: output) (some (f head))) := by + change some (TM2.stepAux (loop f fallback) state (tapeStacks (head :: input) output)) = _ + simp [loop, TM2.stepAux, tapeStacks, running, Function.update] + rw [update_input, update_output] + rfl + +def next (f : α → β) (fallback : β) (configuration : Option (machine f fallback).Cfg) : + Option (machine f fallback).Cfg := configuration.bind (machine f fallback).step + +theorem transfer_steps (f : α → β) (fallback : β) (input : List α) (output : List β) + (state : Option β) : + (next f fallback)^[input.length + 1] (some (running f fallback input output state)) = + some (halted f fallback (input.reverse.map f ++ output)) := by + induction input generalizing output state with + | nil => + simpa only [List.length_nil, Nat.zero_add, Function.iterate_one, next, + Option.bind_some, List.reverse_nil, List.map_nil, List.nil_append] + using step_empty f fallback output state + | cons head input ih => + rw [List.length_cons, Function.iterate_succ_apply] + change (next f fallback)^[input.length + 1] + ((machine f fallback).step (running f fallback (head :: input) output state)) = _ + rw [step_cons, ih] + simp only [List.reverse_cons, List.map_append, List.map_singleton, + List.append_assoc, List.singleton_append] + +theorem initList_eq (f : α → β) (fallback : β) (input : List α) : + initList (machine f fallback) input = running f fallback input [] none := by + unfold initList running + congr 1 + funext side + cases side <;> rfl + +theorem haltList_eq (f : α → β) (fallback : β) (output : List β) : + haltList (machine f fallback) output = halted f fallback output := by + unfold haltList halted + congr 1 + funext side + cases side <;> rfl + +theorem transfer_init_steps (f : α → β) (fallback : β) (input : List α) : + (next f fallback)^[input.length + 1] (some (initList (machine f fallback) input)) = + some (haltList (machine f fallback) (input.reverse.map f)) := by + have ht := transfer_steps f fallback input [] none + simp only [List.append_nil] at ht + exact (congrArg (fun c => (next f fallback)^[input.length + 1] (some c)) + (initList_eq f fallback input)).trans + (ht.trans ((congrArg some (haltList_eq f fallback (input.reverse.map f))).symm)) + +def outputsInTime (f : α → β) (fallback : β) (input : List α) : + TM2OutputsInTime (machine f fallback) input (some (input.reverse.map f)) + (input.length + 1) where + steps := input.length + 1 + evals_in_steps := transfer_init_steps f fallback input + steps_le_m := Nat.le_refl _ + +@[simp] theorem outputsInTime_steps (f : α → β) (fallback : β) (input : List α) : + (outputsInTime f fallback input).steps = input.length + 1 := rfl + +noncomputable def computableInPolyTime (f : α → β) (fallback : β) : + TM2ComputableInPolyTime (id : List α → List α) (id : List β → List β) + (fun input => input.reverse.map f) where + tm := machine f fallback + inputAlphabet := Equiv.refl α + outputAlphabet := Equiv.refl β + time := Polynomial.X + 1 + outputsFun input := by + change TM2OutputsInTime (machine f fallback) (input.map id) + (some ((input.reverse.map f).map id)) + ((Polynomial.X + 1 : Polynomial Nat).eval input.length) + have hi := @List.map_id ((machine f fallback).Γ (machine f fallback).k₀) input + have ho := @List.map_id ((machine f fallback).Γ (machine f fallback).k₁) (input.reverse.map f) + erw [hi, ho] + simpa only [Polynomial.eval_add, Polynomial.eval_X, Polynomial.eval_one] + using outputsInTime f fallback input + +variable {K Λ σ : Type} {Γ : K → Type} [DecidableEq K] + +def exitAt (dst : K) (exit : Option Λ) : TM2.Stmt Γ Λ (σ × Option (Γ dst)) := + match exit with + | none => .halt + | some label => .goto fun _ => label + +def loopAt (src dst : K) (f : Γ src → Γ dst) (fallback : Γ dst) + (loopLabel : Λ) (exit : Option Λ) : TM2.Stmt Γ Λ (σ × Option (Γ dst)) := + .pop src (fun state head => (state.1, head.map f)) + (.branch (fun state => state.2.isSome) + (.push dst (fun state => state.2.getD fallback) (.goto fun _ => loopLabel)) + (exitAt dst exit)) + +def tapesAt (src dst : K) (base : (k : K) → List (Γ k)) + (input : List (Γ src)) (output : List (Γ dst)) : (k : K) → List (Γ k) := + Function.update (Function.update base src input) dst output + +@[simp] theorem tapesAt_src (src dst : K) (distinct : src ≠ dst) + (base : (k : K) → List (Γ k)) (input : List (Γ src)) (output : List (Γ dst)) : + tapesAt src dst base input output src = input := by + simp [tapesAt, distinct] + +@[simp] theorem tapesAt_dst (src dst : K) + (base : (k : K) → List (Γ k)) (input : List (Γ src)) (output : List (Γ dst)) : + tapesAt src dst base input output dst = output := by + simp [tapesAt] + +theorem tapesAt_other (src dst k : K) (notSrc : k ≠ src) (notDst : k ≠ dst) + (base : (k : K) → List (Γ k)) (input : List (Γ src)) (output : List (Γ dst)) : + tapesAt src dst base input output k = base k := by + simp [tapesAt, notSrc, notDst] + +@[simp] theorem tapesAt_self (src dst : K) (base : (k : K) → List (Γ k)) : + tapesAt src dst base (base src) (base dst) = base := by + simp [tapesAt] + +private theorem update_tapesAt_src (src dst : K) (distinct : src ≠ dst) + (base : (k : K) → List (Γ k)) (input replacement : List (Γ src)) + (output : List (Γ dst)) : + Function.update (tapesAt src dst base input output) src replacement = + tapesAt src dst base replacement output := by + funext k + by_cases hs : k = src + · subst k + simp [tapesAt, distinct] + · by_cases hd : k = dst + · subst k + simp [tapesAt, Ne.symm distinct] + · simp [tapesAt, hs, hd] + +private theorem update_tapesAt_dst (src dst : K) + (base : (k : K) → List (Γ k)) (input : List (Γ src)) + (output replacement : List (Γ dst)) : + Function.update (tapesAt src dst base input output) dst replacement = + tapesAt src dst base input replacement := by + funext k + by_cases hd : k = dst + · subst k + simp [tapesAt] + · simp [tapesAt, hd] + +def nextAt (dst : K) (program : Λ → TM2.Stmt Γ Λ (σ × Option (Γ dst))) + (configuration : Option (TM2.Cfg Γ Λ (σ × Option (Γ dst)))) : + Option (TM2.Cfg Γ Λ (σ × Option (Γ dst))) := + configuration.bind (TM2.step program) + +theorem stepAt_empty (src dst : K) (distinct : src ≠ dst) + (f : Γ src → Γ dst) (fallback : Γ dst) (loopLabel : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt Γ Λ (σ × Option (Γ dst))) + (atLoop : program loopLabel = loopAt src dst f fallback loopLabel exit) + (base : (k : K) → List (Γ k)) (output : List (Γ dst)) + (ambient : σ) (register : Option (Γ dst)) : + TM2.step program ⟨some loopLabel, (ambient, register), tapesAt src dst base [] output⟩ = + some ⟨exit, (ambient, none), tapesAt src dst base [] output⟩ := by + change some (TM2.stepAux (program loopLabel) (ambient, register) + (tapesAt src dst base [] output)) = _ + rw [atLoop] + cases exit <;> + simp [loopAt, exitAt, TM2.stepAux, tapesAt_src, distinct, update_tapesAt_src] + +theorem stepAt_cons (src dst : K) (distinct : src ≠ dst) + (f : Γ src → Γ dst) (fallback : Γ dst) (loopLabel : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt Γ Λ (σ × Option (Γ dst))) + (atLoop : program loopLabel = loopAt src dst f fallback loopLabel exit) + (base : (k : K) → List (Γ k)) (head : Γ src) (input : List (Γ src)) + (output : List (Γ dst)) (ambient : σ) (register : Option (Γ dst)) : + TM2.step program + ⟨some loopLabel, (ambient, register), tapesAt src dst base (head :: input) output⟩ = + some ⟨some loopLabel, (ambient, some (f head)), + tapesAt src dst base input (f head :: output)⟩ := by + change some (TM2.stepAux (program loopLabel) (ambient, register) + (tapesAt src dst base (head :: input) output)) = _ + rw [atLoop] + simp [loopAt, TM2.stepAux, tapesAt_src, tapesAt_dst, distinct, + update_tapesAt_src, update_tapesAt_dst] + +theorem transferAt_steps (src dst : K) (distinct : src ≠ dst) + (f : Γ src → Γ dst) (fallback : Γ dst) (loopLabel : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt Γ Λ (σ × Option (Γ dst))) + (atLoop : program loopLabel = loopAt src dst f fallback loopLabel exit) + (base : (k : K) → List (Γ k)) (input : List (Γ src)) (output : List (Γ dst)) + (ambient : σ) (register : Option (Γ dst)) : + (nextAt dst program)^[input.length + 1] + (some ⟨some loopLabel, (ambient, register), tapesAt src dst base input output⟩) = + some ⟨exit, (ambient, none), tapesAt src dst base [] (input.reverse.map f ++ output)⟩ := by + induction input generalizing output register with + | nil => + simpa only [List.length_nil, Nat.zero_add, Function.iterate_one, nextAt, + Option.bind_some, List.reverse_nil, List.map_nil, List.nil_append] + using stepAt_empty src dst distinct f fallback loopLabel exit program atLoop base output + ambient register + | cons head input ih => + rw [List.length_cons, Function.iterate_succ_apply] + change (nextAt dst program)^[input.length + 1] + (TM2.step program + ⟨some loopLabel, (ambient, register), tapesAt src dst base (head :: input) output⟩) = _ + rw [stepAt_cons src dst distinct f fallback loopLabel exit program atLoop, ih] + simp only [List.reverse_cons, List.map_append, List.map_singleton, + List.append_assoc, List.singleton_append] + +theorem transferAt_fromTapes (src dst : K) (distinct : src ≠ dst) + (f : Γ src → Γ dst) (fallback : Γ dst) (loopLabel : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt Γ Λ (σ × Option (Γ dst))) + (atLoop : program loopLabel = loopAt src dst f fallback loopLabel exit) + (base : (k : K) → List (Γ k)) (ambient : σ) (register : Option (Γ dst)) : + (nextAt dst program)^[(base src).length + 1] + (some ⟨some loopLabel, (ambient, register), base⟩) = + some ⟨exit, (ambient, none), + tapesAt src dst base [] ((base src).reverse.map f ++ base dst)⟩ := by + simpa only [tapesAt_self] using + transferAt_steps src dst distinct f fallback loopLabel exit program atLoop base + (base src) (base dst) ambient register + +def transferAtInTime (src dst : K) (distinct : src ≠ dst) + (f : Γ src → Γ dst) (fallback : Γ dst) (loopLabel : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt Γ Λ (σ × Option (Γ dst))) + (atLoop : program loopLabel = loopAt src dst f fallback loopLabel exit) + (base : (k : K) → List (Γ k)) (ambient : σ) (register : Option (Γ dst)) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some loopLabel, (ambient, register), base⟩ + (some ⟨exit, (ambient, none), + tapesAt src dst base [] ((base src).reverse.map f ++ base dst)⟩) + ((base src).length + 1) where + steps := (base src).length + 1 + evals_in_steps := transferAt_fromTapes src dst distinct f fallback loopLabel exit + program atLoop base ambient register + steps_le_m := Nat.le_refl _ + +end MinUncutGames.Reduction.MachineTransfer + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/RuntimeFinish.lean b/lean/OAI/Computability/MinUncut/Machines/RuntimeFinish.lean new file mode 100644 index 0000000000000000000000000000000000000000..09e08378ecb0176b18809d38bc5075f9677272ce --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/RuntimeFinish.lean @@ -0,0 +1,183 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.MachineFiniteSequence + +namespace OAI + +namespace MinUncutGames.Foundations.Hastad.SourceRuntimeFinish + +open Turing Complexity + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev Label (clearKeys : List K) := MachineDrainMany.Label clearKeys ⊕ Bool +abbrev Tapes (K : Type) := K → List Bool + +def entry (clearKeys : List K) (labels : Label clearKeys → Λ) : Option Λ := + MachineDrainMany.entry clearKeys (fun l => labels (.inl l)) (some (labels (.inr false))) + +def statement (clearKeys : List K) (accumulator output : K) (canonical : σ) + (labels : Label clearKeys → Λ) (exit : Option Λ) : + Label clearKeys → TM2.Stmt (fun _ : K => Bool) Λ (σ × Option Bool) + | .inl label => MachineDrainMany.instruction clearKeys (fun l => labels (.inl l)) + (some (labels (.inr false))) label + | .inr false => Reduction.MachineTransfer.loopAt accumulator output id false + (labels (.inr false)) (some (labels (.inr true))) + | .inr true => .load (fun _ => (canonical, none)) (Reduction.MachineTransfer.exitAt output exit) + +def canonicalTapes (output : K) (word : List Bool) : Tapes K := + Function.update (fun _ => []) output word + +def finishCost (clearKeys : List K) (accumulator : K) (base : Tapes K) : Nat := + MachineDrainMany.steps clearKeys base + (base accumulator).length + 2 + +theorem cleared_frame (clearKeys : List K) (base : Tapes K) (tape : K) + (h : tape ∉ clearKeys) : MachineDrainMany.finalTapes clearKeys base tape = base tape := + MachineDrainMany.finalTapes_not_mem clearKeys base tape h + +theorem reversed_tapes (clearKeys : List K) (accumulator output : K) + (distinct : accumulator ≠ output) + (covers : ∀ k, k ≠ accumulator → k ≠ output → k ∈ clearKeys) + (base : Tapes K) : + Reduction.MachineTransfer.tapesAt accumulator output + (MachineDrainMany.finalTapes clearKeys base) [] (base accumulator).reverse = + canonicalTapes output (base accumulator).reverse := by + funext k + by_cases hout : k = output + · subst k + simp [Reduction.MachineTransfer.tapesAt, canonicalTapes] + · by_cases hacc : k = accumulator + · subst k + simp [Reduction.MachineTransfer.tapesAt, canonicalTapes, distinct] + · have hclear := MachineDrainMany.finalTapes_mem clearKeys base k (covers k hacc hout) + simp [Reduction.MachineTransfer.tapesAt, canonicalTapes, hout, hacc, hclear] + +def finishInTime (clearKeys : List K) (accumulator output : K) + (distinct : accumulator ≠ output) + (keepAccumulator : accumulator ∉ clearKeys) (keepOutput : output ∉ clearKeys) + (covers : ∀ k, k ≠ accumulator → k ≠ output → k ∈ clearKeys) + (canonical : σ) (labels : Label clearKeys → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (σ × Option Bool)) + (atLabels : ∀ label, + program (labels label) = statement clearKeys accumulator output canonical labels exit label) + (base : Tapes K) (outputEmpty : base output = []) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨entry clearKeys labels, (ambient, register), base⟩ + (some ⟨exit, (canonical, none), canonicalTapes output (base accumulator).reverse⟩) + (finishCost clearKeys accumulator base) := by + let cleared := MachineDrainMany.finalTapes clearKeys base + let afterRegister := MachineDrainMany.finalRegister clearKeys register + let drain : StateTransition.EvalsToInTime (TM2.step program) + ⟨entry clearKeys labels, (ambient, register), base⟩ + (some ⟨some (labels (.inr false)), (ambient, afterRegister), cleared⟩) + (MachineDrainMany.steps clearKeys base) := { + steps := MachineDrainMany.steps clearKeys base + evals_in_steps := MachineDrainMany.trace clearKeys (fun l => labels (.inl l)) + (some (labels (.inr false))) program (fun l => atLabels (.inl l)) base ambient register + steps_le_m := Nat.le_refl _ } + have acc : cleared accumulator = base accumulator := cleared_frame _ _ _ keepAccumulator + have out : cleared output = [] := (cleared_frame _ _ _ keepOutput).trans outputEmpty + let reverse : StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels (.inr false)), (ambient, afterRegister), cleared⟩ + (some ⟨some (labels (.inr true)), (ambient, none), + canonicalTapes output (base accumulator).reverse⟩) ((base accumulator).length + 1) := { + steps := (base accumulator).length + 1 + evals_in_steps := by + change (Reduction.MachineTransfer.nextAt output program)^[(base accumulator).length + 1] + (some ⟨some (labels (.inr false)), (ambient, afterRegister), cleared⟩) = _ + have run := Reduction.MachineTransfer.transferAt_fromTapes (Γ := fun _ : K => Bool) + accumulator output distinct id false (labels (.inr false)) + (some (labels (.inr true))) program + (by simpa only [statement] using atLabels (.inr false)) cleared ambient afterRegister + simpa only [acc, out, List.map_id, List.append_nil, + cleared, reversed_tapes clearKeys accumulator output distinct covers base] using run + steps_le_m := Nat.le_refl _ } + let reset : StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels (.inr true)), (ambient, none), canonicalTapes output (base accumulator).reverse⟩ + (some ⟨exit, (canonical, none), canonicalTapes output (base accumulator).reverse⟩) 1 := { + steps := 1 + evals_in_steps := by + change some (TM2.stepAux (program (labels (.inr true))) _ _) = _ + rw [atLabels] + cases exit <;> rfl + steps_le_m := Nat.le_refl _ } + let first := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ drain reverse + let run := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ first reset + have hsteps : run.steps = finishCost clearKeys accumulator base := by + change 1 + ((base accumulator).length + 1 + MachineDrainMany.steps clearKeys base) = _ + unfold finishCost + omega + exact { + steps := finishCost clearKeys accumulator base + evals_in_steps := by simpa only [hsteps] using run.evals_in_steps + steps_le_m := Nat.le_refl _ } + +theorem finishCost_le_list (clearKeys : List K) (accumulator : K) (base : Tapes K) : + finishCost clearKeys accumulator base ≤ MachineDrainMany.lengthSum clearKeys base + + clearKeys.length + (base accumulator).length + 2 := by + have h := MachineDrainMany.steps_le clearKeys base + unfold finishCost + omega + +variable [Fintype K] +open scoped BigOperators + +def totalLength (base : Tapes K) : Nat := ∑ k, (base k).length + +theorem totalLength_erase (base : Tapes K) (source : K) : + totalLength (Function.update base source []) + (base source).length = totalLength base := by + calc + _ = ∑ k, (((Function.update base source []) k).length + + if k = source then (base source).length else 0) := by + simp [totalLength, Finset.sum_add_distrib] + _ = _ := by + apply Finset.sum_congr rfl + intro k hk + by_cases h : k = source + · subst k + simp + · simp [h] + +theorem drain_conservation (clearKeys : List K) (base : Tapes K) : + MachineDrainMany.steps clearKeys base + + totalLength (MachineDrainMany.finalTapes clearKeys base) = + totalLength base + clearKeys.length := by + induction clearKeys generalizing base with + | nil => simp [MachineDrainMany.steps, MachineDrainMany.finalTapes] + | cons source rest ih => + have h := ih (Function.update base source []) + have erase := totalLength_erase base source + simp only [MachineDrainMany.steps, MachineDrainMany.finalTapes, List.length_cons] + omega + +theorem cleared_totalLength (clearKeys : List K) (accumulator output : K) + (keepAccumulator : accumulator ∉ clearKeys) (keepOutput : output ∉ clearKeys) + (covers : ∀ k, k ≠ accumulator → k ≠ output → k ∈ clearKeys) + (base : Tapes K) (outputEmpty : base output = []) : + totalLength (MachineDrainMany.finalTapes clearKeys base) = (base accumulator).length := by + have point (k : K) : (MachineDrainMany.finalTapes clearKeys base k).length = + if k = accumulator then (base accumulator).length else 0 := by + by_cases ha : k = accumulator + · subst k + simp [cleared_frame clearKeys base accumulator keepAccumulator] + · by_cases ho : k = output + · subst k + simp [ha, cleared_frame clearKeys base output keepOutput, outputEmpty] + · rw [MachineDrainMany.finalTapes_mem clearKeys base k (covers k ha ho)] + simp [ha] + simp only [totalLength, point] + simp + +theorem finishCost_eq_totalLength (clearKeys : List K) (accumulator output : K) + (keepAccumulator : accumulator ∉ clearKeys) (keepOutput : output ∉ clearKeys) + (covers : ∀ k, k ≠ accumulator → k ≠ output → k ∈ clearKeys) + (base : Tapes K) (outputEmpty : base output = []) : + finishCost clearKeys accumulator base = totalLength base + clearKeys.length + 2 := by + have h := drain_conservation clearKeys base + rw [cleared_totalLength clearKeys accumulator output keepAccumulator keepOutput covers + base outputEmpty] at h + unfold finishCost + omega + +end MinUncutGames.Foundations.Hastad.SourceRuntimeFinish + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/RuntimeModel.lean b/lean/OAI/Computability/MinUncut/Machines/RuntimeModel.lean new file mode 100644 index 0000000000000000000000000000000000000000..43a2018169dfb959359896b2bd60781c57c7df73 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/RuntimeModel.lean @@ -0,0 +1,517 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.ContextPrepare +import OAI.Computability.MinUncut.PCP.DescriptorEmission + +namespace OAI + +section +namespace MinUncutGames.Foundations.Hastad.SourceRuntimeModel + +open Turing Complexity SourceContexts SourceOccurrences SourceLocalSignature SourceProfileBridge + +inductive BodyWork (Extra : Type) + | leftBlock | dummy | bitCount | occurrenceCount + | zero | rank | rightBase | leftBase + | accA | accB | counter | arithScratch | coefficient + | queryTemporary | queryScratch | accumulator + | extra (value : Extra) + deriving DecidableEq, Fintype + +abbrev BodyExtra (Extra : Type) := SourceLoopInit.HeaderTape ⊕ BodyWork Extra +abbrev Arena (u : Nat) (Extra : Type) := SourceContextLoad.Tape u (BodyExtra Extra) +abbrev QueryState (u D : Nat) := SourceQueryLoop.State u D +abbrev ArithmeticState := MachineHorner.State Unit +abbrev State (u D : Nat) := SourceContextPrepare.State u (QueryState u D × ArithmeticState) +abbrev QueryMetadata (u : Nat) := SourceContextPrepare.LoadState × + (SourceSignaturePrepare.ProfileState u × (Signature u × ArithmeticState)) +abbrev ArithmeticMetadata (u D : Nat) := SourceContextPrepare.LoadState × + (SourceSignaturePrepare.ProfileState u × (Signature u × QueryState u D)) + +variable {u D : Nat} {Extra : Type} + +def workTape (role : BodyWork Extra) : Arena u Extra := .extra (.inr role) +def variableHeader : Arena u Extra := SourceLoopInit.variableHeader +def clauseHeader : Arena u Extra := SourceLoopInit.clauseHeader + +def canonicalSignature (u : Nat) : Signature u := + ⟨fun _ => false, fun _ _ => false, fun _ => .first⟩ + +def canonicalState (initialQuery : SourceQueryLoop.Query u D) : State u D := + SourceContextPrepare.initialState (fun _ _ => false) (canonicalSignature u) + (((canonicalSignature u, initialQuery), none), (((), ()), none)) + +def queryStateEquiv (u D : Nat) : QueryState u D × QueryMetadata u ≃ State u D where + toFun x := (x.2.1, (x.2.2.1, (x.2.2.2.1, (x.1, x.2.2.2.2)))) + invFun x := (x.2.2.2.1, (x.1, (x.2.1, (x.2.2.1, x.2.2.2.2)))) + left_inv _ := rfl + right_inv _ := rfl + +def arithmeticStateEquiv (u D : Nat) : ArithmeticState × ArithmeticMetadata u D ≃ State u D where + toFun x := (x.2.1, (x.2.2.1, (x.2.2.2.1, (x.2.2.2.2, x.1)))) + invFun x := (x.2.2.2.2, (x.1, (x.2.1, (x.2.2.1, x.2.2.2.1)))) + left_inv _ := rfl + right_inv _ := rfl + +def rankControls (header : SourceLoopInit.HeaderTape) : Fin 6 ↪ BodyExtra Extra where + toFun + | 0 => .inl header + | 1 => .inr .accA + | 2 => .inr .accB + | 3 => .inr .rank + | 4 => .inr .counter + | 5 => .inr .arithScratch + inj' := by intro a b h; fin_cases a <;> fin_cases b <;> simp_all + +def clauseRankSlots : MachineHorner.Layout u ↪ Arena u Extra := + SourceRankPhase.clauseSlots (rankControls .clauseCount) + +def variableRankSlots (selected : SlotContext u) : MachineHorner.Layout u ↪ Arena u Extra := + SourceRankPhase.variableSlots (rankControls .variableCount) selected + +def baseSlots (right : Bool) : MachineHorner.Layout 2 ↪ Arena u Extra where + toFun + | .inl 0 => workTape .rank + | .inl 1 => workTape .accA + | .inl 2 => workTape .accB + | .inl 3 => workTape (if right then .rightBase else .leftBase) + | .inl 4 => workTape .counter + | .inl 5 => workTape .arithScratch + | .inr 0 => workTape .coefficient + | .inr 1 => workTape (if right then .leftBlock else .zero) + inj' := by + intro a b h + cases a with + | inl a => + cases b with + | inl b => cases right <;> fin_cases a <;> fin_cases b <;> simp_all [workTape] + | inr b => cases right <;> fin_cases a <;> fin_cases b <;> simp_all [workTape] + | inr a => + cases b with + | inl b => cases right <;> fin_cases a <;> fin_cases b <;> simp_all [workTape] + | inr b => cases right <;> fin_cases a <;> fin_cases b <;> simp_all [workTape] + +def querySources : Fin 3 → Arena u Extra + | 0 => workTape .leftBase + | 1 => workTape .rightBase + | 2 => workTape .dummy + +def queryLayout : SourceTestAppend.Layout (Arena u Extra) where + sources := querySources + temporary := workTape .queryTemporary + scratch := workTape .queryScratch + accumulator := workTape .accumulator + sourceTemporary side := by fin_cases side <;> simp [querySources, workTape] + sourceScratch side := by fin_cases side <;> simp [querySources, workTape] + sourceAccumulator side := by fin_cases side <;> simp [querySources, workTape] + temporaryScratch := by simp [workTape] + temporaryAccumulator := by simp [workTape] + scratchAccumulator := by simp [workTape] + +def perSlotCleanup : List (Arena u Extra) := [workTape .rank, workTape .leftBase] +def finalBaseCleanup : List (Arena u Extra) := [workTape .rank, workTape .rightBase, workTape .zero] + +@[simp] theorem initializer_arena : + SourceLoopInit.Tape u (BodyWork Extra) = Arena u Extra := rfl + +end MinUncutGames.Foundations.Hastad.SourceRuntimeModel + +end +section +namespace MinUncutGames.Foundations.Complexity.CookLevin.PolynomialMachine + +noncomputable def coefficientPolynomial : List Nat → Polynomial Nat + | [] => 0 + | a :: rest => coefficientPolynomial rest * Polynomial.X + Polynomial.C a + +theorem coefficientPolynomial_eval (cs : List Nat) (n : Nat) : + (coefficientPolynomial cs).eval n = cs.foldr (fun digit value => value * n + digit) 0 := by + induction cs with + | nil => simp [coefficientPolynomial] + | cons a rest ih => simp [coefficientPolynomial, ih] + +theorem coefficientPolynomial_eval_reverse (cs : List Nat) (n : Nat) : + (coefficientPolynomial cs).eval n = + cs.reverse.foldl (fun value digit => value * n + digit) 0 := by + rw [coefficientPolynomial_eval, List.foldr_eq_foldl_reverse] + +noncomputable def coefficients (p : Polynomial Nat) : + {cs : List Nat // coefficientPolynomial cs = p} := by + refine Polynomial.recOnHorner p ?_ ?_ ?_ + · exact ⟨[], rfl⟩ + · intro q a hq ha ih + rcases ih with ⟨cs, hcs⟩ + cases cs with + | nil => + refine ⟨[a], ?_⟩ + rw [← hcs] + simp [coefficientPolynomial] + | cons b rest => + refine ⟨(b + a) :: rest, ?_⟩ + rw [← hcs] + simp only [coefficientPolynomial, Polynomial.C_add, add_assoc] + · intro q hq ih + rcases ih with ⟨cs, hcs⟩ + refine ⟨0 :: cs, ?_⟩ + simp only [coefficientPolynomial, Polynomial.C_0, add_zero, hcs] + +noncomputable def highCoefficients (p : Polynomial Nat) : List Nat := + (coefficients p).val.reverse + +noncomputable def width (p : Polynomial Nat) : Nat := (highCoefficients p).length + +noncomputable def digit (p : Polynomial Nat) (i : Nat) : Nat := + if hi : i < width p then (highCoefficients p)[i] else 0 + +noncomputable def digitBound (p : Polynomial Nat) : Nat := (highCoefficients p).sum + +theorem le_sum_of_mem {n : Nat} {xs : List Nat} (h : n ∈ xs) : n ≤ xs.sum := by + induction xs with + | nil => simp at h + | cons a rest ih => + rcases List.mem_cons.mp h with rfl | hm + · simp + · have hrest := ih hm + simp only [List.sum_cons] + omega + +theorem digit_le_bound (p : Polynomial Nat) (i : Nat) : digit p i ≤ digitBound p := by + unfold digit + split + · exact le_sum_of_mem (List.getElem_mem _) + · exact Nat.zero_le _ + +theorem highCoefficients_foldl (p : Polynomial Nat) (n : Nat) : + (highCoefficients p).foldl (fun value digit => value * n + digit) 0 = p.eval n := by + calc + _ = (coefficientPolynomial (coefficients p).val).eval n := + (coefficientPolynomial_eval_reverse (coefficients p).val n).symm + _ = p.eval n := congrArg (fun q : Polynomial Nat => q.eval n) (coefficients p).property + +theorem range_map_digit (p : Polynomial Nat) : + (List.range (width p)).map (digit p) = highCoefficients p := by + apply List.ext_getElem + · simp [width] + · intro i hi hj + simp [digit, width, hj] + +section LiteralFields + +open Turing +open MinUncutGames.Reduction.MachineSubstitution + +variable {K Λ σ : Type} [DecidableEq K] + +def prependFields (word : K → List Bool) : List K → + TM2.Stmt (fun _ : K => Bool) Λ σ → TM2.Stmt (fun _ : K => Bool) Λ σ + | [], continuation => continuation + | k :: rest, continuation => + pushWord k (word k).reverse (prependFields word rest continuation) + +def prependFieldsTapes (word : K → List Bool) : List K → + (K → List Bool) → K → List Bool + | [], tapes => tapes + | k :: rest, tapes => + prependFieldsTapes word rest (Function.update tapes k (word k ++ tapes k)) + +theorem stepAux_prependFields (word : K → List Bool) (indices : List K) + (continuation : TM2.Stmt (fun _ : K => Bool) Λ σ) (state : σ) (tapes : K → List Bool) : + TM2.stepAux (prependFields word indices continuation) state tapes = + TM2.stepAux continuation state (prependFieldsTapes word indices tapes) := by + induction indices generalizing tapes with + | nil => rfl + | cons k rest ih => + simp only [prependFields, stepAux_pushWord, List.reverse_reverse, prependFieldsTapes] + exact ih _ + +theorem prependFieldsTapes_apply (word : K → List Bool) (indices : List K) + (hn : indices.Nodup) (tapes : K → List Bool) (k : K) : + prependFieldsTapes word indices tapes k = + if k ∈ indices then word k ++ tapes k else tapes k := by + induction indices generalizing tapes with + | nil => simp [prependFieldsTapes] + | cons j rest ih => + have hnodup := List.nodup_cons.mp hn + rw [prependFieldsTapes, ih hnodup.2] + by_cases hkj : k = j + · subst k + simp [hnodup.1] + · simp [hkj] + +def popN (k : K) : Nat → TM2.Stmt (fun _ : K => Bool) Λ σ → + TM2.Stmt (fun _ : K => Bool) Λ σ + | 0, continuation => continuation + | n + 1, continuation => .pop k (fun state _ => state) (popN k n continuation) + +theorem stepAux_popN (k : K) (n : Nat) + (continuation : TM2.Stmt (fun _ : K => Bool) Λ σ) (state : σ) (tapes : K → List Bool) : + TM2.stepAux (popN k n continuation) state tapes = + TM2.stepAux continuation state (Function.update tapes k ((tapes k).drop n)) := by + induction n generalizing tapes with + | zero => simp [popN] + | succ n ih => + simp only [popN, TM2.stepAux] + rw [ih] + simp only [Function.update_self, Function.update_idem, List.drop_tail] + +def clearFields (count : K → Nat) : List K → + TM2.Stmt (fun _ : K => Bool) Λ σ → TM2.Stmt (fun _ : K => Bool) Λ σ + | [], continuation => continuation + | k :: rest, continuation => popN k (count k) (clearFields count rest continuation) + +def clearFieldsTapes (count : K → Nat) : List K → (K → List Bool) → K → List Bool + | [], tapes => tapes + | k :: rest, tapes => clearFieldsTapes count rest + (Function.update tapes k ((tapes k).drop (count k))) + +theorem stepAux_clearFields (count : K → Nat) (indices : List K) + (continuation : TM2.Stmt (fun _ : K => Bool) Λ σ) (state : σ) (tapes : K → List Bool) : + TM2.stepAux (clearFields count indices continuation) state tapes = + TM2.stepAux continuation state (clearFieldsTapes count indices tapes) := by + induction indices generalizing tapes with + | nil => rfl + | cons k rest ih => + simp only [clearFields, stepAux_popN, clearFieldsTapes] + exact ih _ + +theorem clearFieldsTapes_apply (count : K → Nat) (indices : List K) + (hn : indices.Nodup) (tapes : K → List Bool) (k : K) : + clearFieldsTapes count indices tapes k = + if k ∈ indices then (tapes k).drop (count k) else tapes k := by + induction indices generalizing tapes with + | nil => simp [clearFieldsTapes] + | cons j rest ih => + have hnodup := List.nodup_cons.mp hn + rw [clearFieldsTapes, ih hnodup.2] + by_cases hkj : k = j + · subst k + simp [hnodup.1] + · simp [hkj] + +end LiteralFields + +noncomputable section + +abbrev Layout (p : Polynomial Nat) := MachineHorner.Layout (width p) +abbrev Label (p : Polynomial Nat) := Unit ⊕ (MachineHorner.Label (width p) ⊕ Bool) +abbrev State := MachineHorner.State Unit + +def fieldWord (p : Polynomial Nat) : Layout p → List Bool + | .inl _ => [] + | .inr i => encodeWord (digit p i.val) + +def fieldIndices (p : Polynomial Nat) : List (Layout p) := + (List.finRange (width p)).map Sum.inr + +theorem fieldIndices_nodup (p : Polynomial Nat) : (fieldIndices p).Nodup := + (List.nodup_finRange _).map Sum.inr_injective + +@[simp] theorem inl_not_mem_fields (p : Polynomial Nat) (i : Fin 6) : + Sum.inl i ∉ fieldIndices p := by simp [fieldIndices] + +@[simp] theorem inr_mem_fields (p : Polynomial Nat) (i : Fin (width p)) : + Sum.inr i ∈ fieldIndices p := by simp [fieldIndices] + +def initialTapes (p : Polynomial Nat) (n : Nat) (k : Layout p) : List Bool := + if k = .inl 0 then encodeWord n else [] + +def preparedTapes (p : Polynomial Nat) (n : Nat) : Layout p → List Bool := + prependFieldsTapes (fieldWord p) (fieldIndices p) (initialTapes p n) + +@[simp] theorem preparedTapes_inl (p : Polynomial Nat) (n : Nat) (i : Fin 6) : + preparedTapes p n (.inl i) = if i = 0 then encodeWord n else [] := by + rw [preparedTapes, prependFieldsTapes_apply _ _ (fieldIndices_nodup p)] + simp [initialTapes] + +@[simp] theorem preparedTapes_inr (p : Polynomial Nat) (n : Nat) (i : Fin (width p)) : + preparedTapes p n (.inr i) = encodeWord (digit p i.val) := by + rw [preparedTapes, prependFieldsTapes_apply _ _ (fieldIndices_nodup p)] + simp [initialTapes, fieldWord] + +def slots (p : Polynomial Nat) : Layout p ↪ Layout p := Function.Embedding.refl _ + +theorem preparedTapes_clean (p : Polynomial Nat) (n : Nat) : + MachineHorner.Clean (slots p) (preparedTapes p n) := by + constructor <;> simp [slots] + +def innerLabels (p : Polynomial Nat) (l : MachineHorner.Label (width p)) : Label p := + .inr (.inl l) + +def program (p : Polynomial Nat) : Label p → + Turing.TM2.Stmt (fun _ : Layout p => Bool) (Label p) State + | .inl _ => prependFields (fieldWord p) (fieldIndices p) + (.goto fun _ => innerLabels p .start) + | .inr (.inl l) => MachineHorner.statement (slots p) (innerLabels p) + (some (.inr (.inr false))) l + | .inr (.inr false) => MachineLookup.discard (.inl 0) + (.inr (.inr false)) (.inr (.inr true)) + | .inr (.inr true) => clearFields (fun k => (fieldWord p k).length) (fieldIndices p) .halt + +abbrev machine (p : Polynomial Nat) : Turing.FinTM2 where + K := Layout p + k₀ := .inl 0 + k₁ := .inl 3 + Γ _ := Bool + Λ := Label p + main := .inl () + σ := State + initialState := (((), ()), none) + m := program p + +def afterHornerTapes (p : Polynomial Nat) (n result : Nat) : Layout p → List Bool := + Function.update (preparedTapes p n) (.inl 3) (encodeWord result) + +def afterInputTapes (p : Polynomial Nat) (n result : Nat) : Layout p → List Bool := + Function.update (afterHornerTapes p n result) (.inl 0) [] + +def finalTapes (p : Polynomial Nat) (result : Nat) (k : Layout p) : List Bool := + if k = .inl 3 then encodeWord result else [] + +theorem clearFields_final (p : Polynomial Nat) (n result : Nat) : + clearFieldsTapes (fun k => (fieldWord p k).length) (fieldIndices p) + (afterInputTapes p n result) = finalTapes p result := by + funext k + rw [clearFieldsTapes_apply _ _ (fieldIndices_nodup p)] + cases k with + | inl i => + fin_cases i <;> simp [afterInputTapes, afterHornerTapes, finalTapes] + | inr i => + simp [afterInputTapes, afterHornerTapes, fieldWord, finalTapes] + +theorem initList_eq (p : Polynomial Nat) (n : Nat) : + Turing.initList (machine p) (encodeWord n) = + ⟨some (.inl ()), (((), ()), none), initialTapes p n⟩ := by + unfold Turing.initList + congr 1 + +theorem haltList_eq (p : Polynomial Nat) (result : Nat) : + Turing.haltList (machine p) (encodeWord result) = + ⟨none, (((), ()), none), finalTapes p result⟩ := by + unfold Turing.haltList + congr 1 + +theorem initializationTrace (p : Polynomial Nat) (n : Nat) : + (MachineComposition.advance (machine p).step)^[1] + (some (Turing.initList (machine p) (encodeWord n))) = + some ⟨some (innerLabels p .start), (((), ()), none), preparedTapes p n⟩ := by + rw [initList_eq] + change some (Turing.TM2.stepAux (program p (.inl ())) + (((), ()), none) (initialTapes p n)) = _ + rw [program, stepAux_prependFields] + rfl + +theorem cleanupTrace (p : Polynomial Nat) (n result : Nat) : + (MachineComposition.advance (machine p).step)^[n + 2] + (some ⟨some (.inr (.inr false)), (((), ()), none), afterHornerTapes p n result⟩) = + some (Turing.haltList (machine p) (encodeWord result)) := by + have hd := MachineLookup.discardTrace (Sum.inl (0 : Fin 6)) + (Sum.inr (Sum.inr false)) (Sum.inr (Sum.inr true)) (program p) rfl + (afterHornerTapes p n result) n [] (by simp [afterHornerTapes]) ((), ()) none + have hc : (MachineComposition.advance (machine p).step)^[1] + (some ⟨some (.inr (.inr true)), (((), ()), none), afterInputTapes p n result⟩) = + some (Turing.haltList (machine p) (encodeWord result)) := by + change some (Turing.TM2.stepAux (program p (.inr (.inr true))) + (((), ()), none) (afterInputTapes p n result)) = _ + rw [program, stepAux_clearFields, clearFields_final, haltList_eq] + rfl + rw [show n + 2 = 1 + (n + 1) by omega, Function.iterate_add_apply] + exact (congrArg ((MachineComposition.advance (Turing.TM2.step (program p)))^[1]) hd).trans hc + +def prefixValuePolynomial (digits : Nat → Nat) : Nat → Polynomial Nat + | 0 => 0 + | i + 1 => Polynomial.X * prefixValuePolynomial digits i + Polynomial.C (digits i) + +def prefixCostPolynomial (digits : Nat → Nat) : Nat → Polynomial Nat + | 0 => 0 + | i + 1 => prefixCostPolynomial digits i + + Polynomial.C 3 * Polynomial.X * prefixValuePolynomial digits i + + Polynomial.C 9 * prefixValuePolynomial digits i + Polynomial.C (3 * digits i + 14) + +theorem prefixValuePolynomial_eval (digits : Nat → Nat) (i n : Nat) : + (prefixValuePolynomial digits i).eval n = MachineHorner.value n digits i := by + induction i with + | zero => simp [prefixValuePolynomial, MachineHorner.value] + | succ i ih => simp [prefixValuePolynomial, MachineHorner.value, ih] + +theorem prefixCostPolynomial_eval (digits : Nat → Nat) (i n : Nat) : + (prefixCostPolynomial digits i).eval n = MachineHorner.prefixSteps n digits i := by + induction i with + | zero => simp [prefixCostPolynomial, MachineHorner.prefixSteps] + | succ i ih => + simp only [prefixCostPolynomial, Polynomial.eval_add, Polynomial.eval_mul, + Polynomial.eval_C, Polynomial.eval_X, prefixValuePolynomial_eval, ih, + MachineHorner.prefixSteps, MachineHorner.stepCost, MachineRadixStep.steps] + ring + +def timePolynomial (p : Polynomial Nat) : Polynomial Nat := + prefixCostPolynomial (digit p) (width p) + + Polynomial.C 2 * prefixValuePolynomial (digit p) (width p) + Polynomial.X + Polynomial.C 8 + +theorem timePolynomial_eval (p : Polynomial Nat) (n : Nat) : + (timePolynomial p).eval n = MachineHorner.steps n (digit p) (width p) + n + 3 := by + simp only [timePolynomial, Polynomial.eval_add, Polynomial.eval_mul, + Polynomial.eval_C, Polynomial.eval_X, prefixValuePolynomial_eval, + prefixCostPolynomial_eval, MachineHorner.steps] + omega + +theorem hornerValue_eq_eval (p : Polynomial Nat) (n : Nat) : + MachineHorner.value n (digit p) (width p) = p.eval n := by + rw [MachineHorner.value_eq_foldl, range_map_digit] + have hh := highCoefficients_foldl p n + simpa only [Nat.mul_comm] using hh + +theorem hornerStageTrace (p : Polynomial Nat) (n : Nat) : + (MachineComposition.advance (machine p).step)^[MachineHorner.steps n (digit p) (width p)] + (some ⟨some (innerLabels p .start), (((), ()), none), preparedTapes p n⟩) = + some ⟨some (.inr (.inr false)), (((), ()), none), afterHornerTapes p n (p.eval n)⟩ := by + have h := MachineHorner.hornerTrace (slots p) (innerLabels p) + (some (.inr (.inr false))) (program p) (fun _ => rfl) (preparedTapes p n) n (digit p) + (by simp [slots]) (fun i => by simp [slots]) (preparedTapes_clean p n) () none + rw [hornerValue_eq_eval] at h + have ht : MachineHorner.resultTapes (slots p) (preparedTapes p n) (p.eval n) = + afterHornerTapes p n (p.eval n) := by + simp [MachineHorner.resultTapes, afterHornerTapes, slots] + rw [ht] at h + exact h + +def outputsInTime (p : Polynomial Nat) (n : Nat) : + Turing.TM2OutputsInTime (machine p) (encodeWord n) (some (encodeWord (p.eval n))) + ((timePolynomial p).eval n) where + steps := MachineHorner.steps n (digit p) (width p) + n + 3 + evals_in_steps := by + change (MachineComposition.advance (machine p).step)^[MachineHorner.steps n (digit p) (width p) + n + 3] + (some (Turing.initList (machine p) (encodeWord n))) = + some (Turing.haltList (machine p) (encodeWord (p.eval n))) + have h01 : (MachineComposition.advance (machine p).step)^[ + MachineHorner.steps n (digit p) (width p) + 1] + (some (Turing.initList (machine p) (encodeWord n))) = + some ⟨some (.inr (.inr false)), (((), ()), none), + afterHornerTapes p n (p.eval n)⟩ := by + rw [Function.iterate_add_apply, initializationTrace, hornerStageTrace] + rw [show MachineHorner.steps n (digit p) (width p) + n + 3 = + (n + 2) + (MachineHorner.steps n (digit p) (width p) + 1) by omega, + Function.iterate_add_apply, h01, cleanupTrace] + steps_le_m := by rw [timePolynomial_eval] + +def computableInPolyTime (p : Polynomial Nat) : + Turing.TM2ComputableInPolyTime encodeWord encodeWord p.eval where + tm := machine p + inputAlphabet := Equiv.refl Bool + outputAlphabet := Equiv.refl Bool + time := timePolynomial p + outputsFun n := by + change Turing.TM2OutputsInTime (machine p) ((encodeWord n).map id) + (some ((encodeWord (p.eval n)).map id)) ((timePolynomial p).eval (encodeWord n).length) + rw [List.map_id, List.map_id, encodeWord_length] + let h := outputsInTime p n + exact { + toEvalsTo := h.toEvalsTo + steps_le_m := h.steps_le_m.trans + (MachineComposition.natPolynomial_eval_mono (timePolynomial p) (by omega : n ≤ n + 1)) } + +end + +end MinUncutGames.Foundations.Complexity.CookLevin.PolynomialMachine + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/RuntimeModel2.lean b/lean/OAI/Computability/MinUncut/Machines/RuntimeModel2.lean new file mode 100644 index 0000000000000000000000000000000000000000..a918af32e816aa37995df456ad932e031521dfd2 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/RuntimeModel2.lean @@ -0,0 +1,822 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.Relations + +namespace OAI + +section +namespace MinUncutGames.Foundations.PCP.AlphabetTable.RuntimeModel + +open Turing +open MinUncutGames.Foundations.Complexity + +inductive Tape + | original | cursor | scan | vertices | darts | counter | edge + | tail | reverseIndex | head | scratch | indexScan + | compareLeft | compareRight | reversed | output + deriving DecidableEq + +protected abbrev Tape.enumList : List Tape := [.original, .cursor, .scan, .vertices, .darts, + .counter, .edge, .tail, .reverseIndex, .head, .scratch, .indexScan, .compareLeft, .compareRight, + .reversed, .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 + +abbrev Alphabet (_ : Tape) := Bool + +abbrev Flags := Bool × Bool × Option Bool +abbrev Ambient (q : Nat) := Flags × GenericGraphTables.RelationTable q +abbrev State (q : Nat) := Ambient q × Option Bool + +def normal {q : Nat} (relation : GenericGraphTables.RelationTable q) (selfLoop : Bool) : State q := + (((selfLoop, false, none), relation), none) + +def initial (q : Nat) : State q := normal (Vector.replicate (q * q) false) false + +def context {q : Nat} (ambient : Ambient q) : GenericGraphTables.RelationTable q × Bool := + (ambient.2, ambient.1.1) + +def compareEquiv (q : Nat) : State q ≃ + MachineCompare.State (GenericGraphTables.RelationTable q × Bool) where + toFun s := ((s.1.2, s.1.1.1), s.1.1.2.1, s.1.1.2.2, s.2) + invFun s := (((s.1.2, s.2.1, s.2.2.1), s.1.1), s.2.2.2) + left_inv _ := rfl + right_inv _ := rfl + +@[simp] theorem compareEquiv_normal {q : Nat} + (relation : GenericGraphTables.RelationTable q) (selfLoop : Bool) : + compareEquiv q (normal relation selfLoop) = + ((relation, selfLoop), false, none, none) := rfl + +def emitterEquiv (q : Nat) : ((Ambient q × Unit) × Option Bool) ≃ State q where + toFun s := (s.1.1, s.2) + invFun s := ((s.1, ()), s.2) + left_inv s := by rcases s with ⟨⟨s, u⟩, r⟩; cases u; rfl + right_inv _ := rfl + +def setupPorts : Fin 7 → Tape := + ![.original, .cursor, .vertices, .darts, .counter, .scratch, .edge] + +theorem setupPorts_injective : Function.Injective setupPorts := by + intro i j h + fin_cases i <;> fin_cases j <;> simp_all [setupPorts] + +def headPorts : Fin 6 → Tape := + ![.original, .reverseIndex, .scan, .indexScan, .head, .scratch] + +theorem headPorts_injective : Function.Injective headPorts := by + intro i j h + fin_cases i <;> fin_cases j <;> simp_all [headPorts] + +def rowSources : Fin 5 → Tape := ![.vertices, .darts, .edge, .tail, .head] +def headerSources : Fin 2 → Tape := ![.vertices, .darts] +def fieldPorts : Fin 3 → Tape := ![.tail, .reverseIndex, .head] + +def cleanupPorts : Fin 15 → Tape := + ![.original, .cursor, .scan, .vertices, .darts, .counter, .edge, + .tail, .reverseIndex, .head, .scratch, .indexScan, .compareLeft, .compareRight, .reversed] + +theorem cleanupPorts_ne_output (i : Fin 15) : cleanupPorts i ≠ .output := by + fin_cases i <;> simp [cleanupPorts] + +theorem cleanupPorts_cover (tape : Tape) (h : tape ≠ .output) : + ∃ i, cleanupPorts i = tape := by + cases tape + · exact ⟨0, rfl⟩ + · exact ⟨1, rfl⟩ + · exact ⟨2, rfl⟩ + · exact ⟨3, rfl⟩ + · exact ⟨4, rfl⟩ + · exact ⟨5, rfl⟩ + · exact ⟨6, rfl⟩ + · exact ⟨7, rfl⟩ + · exact ⟨8, rfl⟩ + · exact ⟨9, rfl⟩ + · exact ⟨10, rfl⟩ + · exact ⟨11, rfl⟩ + · exact ⟨12, rfl⟩ + · exact ⟨13, rfl⟩ + · exact ⟨14, rfl⟩ + · exact (h rfl).elim + +variable {Λ : Type} {q : Nat} + +def compareStatement (stmt : TM2.Stmt Alphabet Λ + (MachineCompare.State (GenericGraphTables.RelationTable q × Bool))) : + TM2.Stmt Alphabet Λ (State q) := + MachineControl.statement id (compareEquiv q).symm stmt + +def emitterStatement (stmt : TM2.Stmt Alphabet Λ ((Ambient q × Unit) × Option Bool)) : + TM2.Stmt Alphabet Λ (State q) := + MachineControl.statement id (emitterEquiv q) stmt + +def storeLoop (value : Bool) (next : Λ) : TM2.Stmt Alphabet Λ (State q) := + .load (fun state => (((value, false, none), state.1.2), none)) (.goto fun _ => next) + +theorem stepAux_storeLoop (value : Bool) (next : Λ) (state : State q) + (base : Tape → List Bool) : + TM2.stepAux (storeLoop value next) state base = + ⟨some next, normal state.1.2 value, base⟩ := rfl + +def nextRow (next : Λ) : TM2.Stmt Alphabet Λ (State q) := + .push .edge (fun _ => true) + (.load (fun state => (state.1, none)) (.goto fun _ => next)) + +theorem stepAux_nextRow (next : Λ) (state : State q) + (base : Tape → List Bool) (edge : Nat) (suffix : List Bool) + (he : base .edge = encodeWord edge ++ suffix) : + TM2.stepAux (nextRow next) state base = + ⟨some next, (state.1, none), + Function.update base .edge (encodeWord (edge + 1) ++ suffix)⟩ := by + simp [nextRow, TM2.stepAux, he, encodeWord, List.replicate_succ] + +def transportInTime {K τ υ : Type} [DecidableEq K] {Γ : K → Type} + (e : τ ≃ υ) (p : Λ → TM2.Stmt Γ Λ τ) + {start finish : TM2.Cfg Γ Λ τ} {budget : Nat} + (run : StateTransition.EvalsToInTime (TM2.step p) start (some finish) budget) : + StateTransition.EvalsToInTime (TM2.step (MachineControl.program (Equiv.refl Λ) e p)) + (MachineControl.configuration id e start) + (some (MachineControl.configuration id e finish)) budget := by + apply MachineComposition.liftExecutionInTime _ _ (MachineControl.configuration id e) _ run + intro a b hab + have h := MachineControl.step_simulation (Equiv.refl Λ) e p a + rw [hab] at h + exact h + +end MinUncutGames.Foundations.PCP.AlphabetTable.RuntimeModel + +end +section +namespace MinUncutGames.Foundations.PCP.AlphabetTable.CompareLoop + +open Turing +open MinUncutGames.Foundations.Complexity +open RuntimeModel + +inductive Label + | leftFirst | leftSecond | rightFirst | rightSecond | compare + | equalStore | differentStore + deriving DecidableEq + +protected abbrev Label.enumList : List Label := [.leftFirst, .leftSecond, .rightFirst, + .rightSecond, .compare, .equalStore, .differentStore] + +protected theorem Label.enumList_getElem?_ctorIdx_eq (x : Label) : + Label.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem Label.enumList_nodup : Label.enumList.Nodup := by decide + +instance : Fintype Label where + elems := ⟨Label.enumList, Label.enumList_nodup⟩ + complete x := by cases x <;> decide + +variable {q : Nat} {Λ : Type} + +def statement (labels : Label → Λ) (next : Λ) : + Label → TM2.Stmt Alphabet Λ (State q) + | .leftFirst => compareStatement (MachineFieldProfile.copyStatement + (Reduction.MachineTransfer.loopAt .tail .scratch id false + (labels .leftFirst) (some (labels .leftSecond)))) + | .leftSecond => compareStatement (MachineFieldProfile.copyStatement + (MachineCopy.forkLoop .scratch .tail .compareLeft false + (labels .leftSecond) (some (labels .rightFirst)))) + | .rightFirst => compareStatement (MachineFieldProfile.copyStatement + (Reduction.MachineTransfer.loopAt .head .scratch id false + (labels .rightFirst) (some (labels .rightSecond)))) + | .rightSecond => compareStatement (MachineFieldProfile.copyStatement + (MachineCopy.forkLoop .scratch .head .compareRight false + (labels .rightSecond) (some (labels .compare)))) + | .compare => compareStatement (MachineCompare.loop .compareLeft .compareRight + (labels .compare) (some (labels .equalStore)) (some (labels .differentStore))) + | .equalStore => storeLoop true next + | .differentStore => storeLoop false next + +private theorem compareProgram_at + (program : Λ → TM2.Stmt Alphabet Λ (State q)) (label : Λ) + (stmt : TM2.Stmt Alphabet Λ + (MachineCompare.State (GenericGraphTables.RelationTable q × Bool))) + (atLabel : program label = compareStatement stmt) : + (MachineControl.program (Equiv.refl Λ) (compareEquiv q) program) label = stmt := by + change MachineControl.statement id (compareEquiv q) (program label) = stmt + rw [atLabel] + exact MachineFieldProfile.statement_roundtrip (compareEquiv q) stmt + +def compareWordsInTime (labels : Label → Λ) (next : Λ) + (program : Λ → TM2.Stmt Alphabet Λ (State q)) + (atLabel : ∀ label, program (labels label) = statement labels next label) + (base : Tape → List Bool) + (hLeft : base .compareLeft = []) (hRight : base .compareRight = []) + (hScratch : base .scratch = []) + (relation : GenericGraphTables.RelationTable q) (oldLoop : Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .leftFirst), normal relation oldLoop, base⟩ + (some ⟨some next, normal relation (decide (base .tail = base .head)), base⟩) + (2 * ((base .tail).length + 1) + 2 * ((base .head).length + 1) + + max (base .tail).length (base .head).length + 2) := by + let view := MachineControl.program (Equiv.refl Λ) (compareEquiv q) program + have compared := MachineFieldProfile.nonDestructiveCompareInTime + Tape.tail Tape.head Tape.compareLeft Tape.compareRight Tape.scratch + (by decide) (by decide) (by decide) + (labels .leftFirst) (labels .leftSecond) (labels .rightFirst) + (labels .rightSecond) (labels .compare) + (some (labels .equalStore)) (some (labels .differentStore)) view + (compareProgram_at program _ _ (atLabel .leftFirst)) + (compareProgram_at program _ _ (atLabel .leftSecond)) + (compareProgram_at program _ _ (atLabel .rightFirst)) + (compareProgram_at program _ _ (atLabel .rightSecond)) + (compareProgram_at program _ _ (atLabel .compare)) + base hLeft hRight hScratch (relation, oldLoop) + have restoredProgram : + MachineControl.program (Equiv.refl Λ) (compareEquiv q).symm view = program := by + funext label + exact MachineFieldProfile.statement_roundtrip (compareEquiv q).symm (program label) + have transported := transportInTime (compareEquiv q).symm view compared + rw [restoredProgram] at transported + have copied : StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .leftFirst), normal relation oldLoop, base⟩ + (some ⟨if base .tail = base .head then some (labels .equalStore) + else some (labels .differentStore), normal relation oldLoop, base⟩) + (2 * ((base .tail).length + 1) + 2 * ((base .head).length + 1) + + max (base .tail).length (base .head).length + 1) := by + simpa [MachineControl.configuration, compareEquiv, MachineFieldProfile.normalState, + normal] using transported + have stored : StateTransition.EvalsToInTime (TM2.step program) + ⟨if base .tail = base .head then some (labels .equalStore) + else some (labels .differentStore), normal relation oldLoop, base⟩ + (some ⟨some next, normal relation (decide (base .tail = base .head)), base⟩) 1 := { + steps := 1 + evals_in_steps := by + change TM2.step program + ⟨if base .tail = base .head then some (labels .equalStore) + else some (labels .differentStore), normal relation oldLoop, base⟩ = _ + by_cases heq : base .tail = base .head + · simp [heq, TM2.step, atLabel, statement, stepAux_storeLoop, normal] + · simp [heq, TM2.step, atLabel, statement, stepAux_storeLoop, normal] + steps_le_m := Nat.le_refl _ + } + let run := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ copied stored + exact { toEvalsTo := run.toEvalsTo, steps_le_m := by have h := run.steps_le_m; omega } + +def comparisonTime (tailName headName : Nat) : Nat := + 2 * (tailName + 2) + 2 * (headName + 2) + max (tailName + 1) (headName + 1) + 2 + +theorem encodeWord_eq_iff (left right : Nat) : + encodeWord left = encodeWord right ↔ left = right := by + constructor + · intro h + have hh := congrArg List.length h + simpa only [encodeWord_length, Nat.add_right_cancel_iff] using hh + · rintro rfl + rfl + +def compareInTime (labels : Label → Λ) (next : Λ) + (program : Λ → TM2.Stmt Alphabet Λ (State q)) + (atLabel : ∀ label, program (labels label) = statement labels next label) + (base : Tape → List Bool) (tailName headName : Nat) + (hTail : base .tail = encodeWord tailName) (hHead : base .head = encodeWord headName) + (hLeft : base .compareLeft = []) (hRight : base .compareRight = []) + (hScratch : base .scratch = []) + (relation : GenericGraphTables.RelationTable q) (oldLoop : Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .leftFirst), normal relation oldLoop, base⟩ + (some ⟨some next, normal relation (decide (tailName = headName)), base⟩) + (comparisonTime tailName headName) := by + have run := compareWordsInTime labels next program atLabel base hLeft hRight hScratch + relation oldLoop + simpa only [hTail, hHead, encodeWord_eq_iff, encodeWord_length, comparisonTime, + Nat.add_assoc] using run + +theorem comparisonTime_le (tailName headName N : Nat) + (hTail : tailName ≤ N) (hHead : headName ≤ N) : + comparisonTime tailName headName ≤ 5 * N + 11 := by + have hm : max (tailName + 1) (headName + 1) ≤ N + 1 := max_le (by omega) (by omega) + unfold comparisonTime + omega + +theorem comparisonTime_le_of_lt (tailName headName N : Nat) + (hTail : tailName < N) (hHead : headName < N) : + comparisonTime tailName headName ≤ 5 * N + 6 := by + have hm : max (tailName + 1) (headName + 1) ≤ N := max_le (by omega) (by omega) + unfold comparisonTime + omega + +def compareWordsInTime_bounded (labels : Label → Λ) (next : Λ) + (program : Λ → TM2.Stmt Alphabet Λ (State q)) + (atLabel : ∀ label, program (labels label) = statement labels next label) + (base : Tape → List Bool) + (hLeft : base .compareLeft = []) (hRight : base .compareRight = []) + (hScratch : base .scratch = []) + (relation : GenericGraphTables.RelationTable q) (oldLoop : Bool) + (N : Nat) (hTail : (base .tail).length ≤ N) (hHead : (base .head).length ≤ N) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .leftFirst), normal relation oldLoop, base⟩ + (some ⟨some next, normal relation (decide (base .tail = base .head)), base⟩) + (5 * N + 6) := by + let run := compareWordsInTime labels next program atLabel base hLeft hRight hScratch + relation oldLoop + refine { toEvalsTo := run.toEvalsTo, steps_le_m := ?_ } + have hm := max_le hTail hHead + have h := run.steps_le_m + omega + +def rowLoop (table : GenericGraphTables.Table q) (e : Fin table.darts) : Bool := + decide (table.rows[e].tail.val = table.rows[table.rows[e].reverseIndex].tail.val) + +def rowState (table : GenericGraphTables.Table q) (e : Fin table.darts) : State q := + normal table.rows[e].relation (rowLoop table e) + +theorem rowLoop_eq_graph (table : GenericGraphTables.Table q) (e : Fin table.darts) : + rowLoop table e = decide ((GenericGraphTables.semantics table).tail e = + (GenericGraphTables.semantics table).head e) := by + simp only [rowLoop, ConstraintGraph.head, GenericGraphTables.semantics_tail, + GenericGraphTables.semantics_reverse, Fin.val_inj] + rfl + +theorem rowContext_eq (table : GenericGraphTables.Table q) (e : Fin table.darts) : + context (rowState table e).1 = + (table.rows[e].relation, decide ((GenericGraphTables.semantics table).tail e = + (GenericGraphTables.semantics table).head e)) := by + change (table.rows[e].relation, rowLoop table e) = _ + rw [rowLoop_eq_graph] + +def compareRowInTime (labels : Label → Λ) (next : Λ) + (program : Λ → TM2.Stmt Alphabet Λ (State q)) + (atLabel : ∀ label, program (labels label) = statement labels next label) + (table : GenericGraphTables.Table q) (e : Fin table.darts) + (base : Tape → List Bool) + (hTail : base .tail = encodeWord table.rows[e].tail.val) + (hHead : base .head = encodeWord table.rows[table.rows[e].reverseIndex].tail.val) + (hLeft : base .compareLeft = []) (hRight : base .compareRight = []) + (hScratch : base .scratch = []) (oldLoop : Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .leftFirst), normal table.rows[e].relation oldLoop, base⟩ + (some ⟨some next, rowState table e, base⟩) (5 * table.vertices + 6) := by + let run := compareInTime labels next program atLabel base _ _ hTail hHead + hLeft hRight hScratch table.rows[e].relation oldLoop + refine { toEvalsTo := run.toEvalsTo, steps_le_m := ?_ } + exact run.steps_le_m.trans (comparisonTime_le_of_lt _ _ _ + table.rows[e].tail.isLt table.rows[table.rows[e].reverseIndex].tail.isLt) + +theorem relationFromRowState (table : GenericGraphTables.Table q) (e : Fin table.darts) + (event : AlphabetGraph.LocalEvent (Fin q)) (slot : Fin 6) (orientation : Bool) + (a b : GraphTables.Label) : + GraphTables.relationAt + (Relations.relationFromTable (context (rowState table e).1).1 + (context (rowState table e).1).2 event slot orientation) a b = + (AlphabetGraph.graph (GenericGraphTables.semantics table)).accepts + (((e, event), slot), orientation) + (Enumeration.labelEquiv.symm a) (Enumeration.labelEquiv.symm b) := by + rw [rowContext_eq] + exact Relations.relationAt_relation_graph (GenericGraphTables.semantics table) + e event slot orientation a b + +end MinUncutGames.Foundations.PCP.AlphabetTable.CompareLoop + +end +section +namespace MinUncutGames.Foundations.PCP.AlphabetTable.Emitter + +open Turing +open MinUncutGames.Foundations.Complexity +open Reduction.MachineSubstitution (pushWord stepAux_pushWord) + +inductive Command (h : Nat) (σ : Type) (bound : Nat) + | literal (word : List Bool) + | bit (value : σ → Bool) + | bounded (value : σ → Fin bound) + | scaled (source : Fin h) (coefficient : Nat) + | scaledIf (source : Fin h) (coefficient : Nat) (active : σ → Bool) + +inductive Phase (bound : Nat) + | entry | emit (symbol : Bool) | restore | offset (value : Fin bound) + | scanIf (active : Bool) | emitIf (active symbol : Bool) + deriving DecidableEq, Fintype + +variable {K : Type} + +abbrev Alphabet (_ : K) := Bool +abbrev State (σ : Type) := (σ × Unit) × Option Bool + +def transition (_ : Unit) (_ : Bool) : Unit := () +def payload (coefficient : Nat) (_ : Unit) (symbol : Bool) : List Bool := + if symbol then List.replicate coefficient true else [] + +def commandBits {h bound : Nat} {σ : Type} (values : Fin h → Nat) (ambient : σ) : + Command h σ bound → List Bool + | .literal word => word + | .bit value => encodeWord (if value ambient then 1 else 0) + | .bounded value => List.replicate (value ambient).val true + | .scaled source coefficient => List.replicate (coefficient * values source) true + | .scaledIf source coefficient active => + List.replicate ((if active ambient then coefficient else 0) * values source) true + +def commandSteps {h bound : Nat} {σ : Type} (values : Fin h → Nat) : + Command h σ bound → Nat + | .literal _ | .bit _ => 1 + | .bounded _ => 2 + | .scaled source _ => 3 * (values source + 1) + 2 + | .scaledIf source _ _ => 3 * (values source + 1) + 3 + +variable {Λ σ : Type} {h bound : Nat} [DecidableEq K] + +def commandStatement (sources : Fin h → K) (scratch output : K) + (labels : Phase bound → Λ) (next : Λ) (command : Command h σ bound) : + Phase bound → TM2.Stmt (Alphabet (K := K)) Λ (State σ) + | .entry => match command with + | .literal word => pushWord output word + (.load (fun state => (state.1, none)) (.goto fun _ => next)) + | .bit value => .branch (fun state => value state.1.1) + (pushWord output [true, false] + (.load (fun state => (state.1, none)) (.goto fun _ => next))) + (pushWord output [false] + (.load (fun state => (state.1, none)) (.goto fun _ => next))) + | .bounded value => .goto fun state => labels (.offset (value state.1.1)) + | .scaled source _ => MachineTransducerCopy.scanLoop (sources source) scratch () + (fun _ symbol => labels (.emit symbol)) (labels .restore) + | .scaledIf _ _ active => .goto fun state => labels (.scanIf (active state.1.1)) + | .emit symbol => match command with + | .scaled _ coefficient => MachineTransducerCopy.emitter output transition + (payload coefficient) (labels .entry) () symbol + | _ => .goto fun _ => next + | .restore => match command with + | .scaled source _ | .scaledIf source _ _ => Reduction.MachineTransfer.loopAt scratch (sources source) + id false (labels .restore) (some next) + | _ => .goto fun _ => next + | .offset value => pushWord output (List.replicate value.val true) + (.load (fun state => (state.1, none)) (.goto fun _ => next)) + | .scanIf active => match command with + | .scaledIf source _ _ => MachineTransducerCopy.scanLoop (sources source) scratch () + (fun _ symbol => labels (.emitIf active symbol)) (labels .restore) + | _ => .goto fun _ => next + | .emitIf active symbol => match command with + | .scaledIf _ coefficient _ => MachineTransducerCopy.emitter output transition + (payload (if active then coefficient else 0)) (labels (.scanIf active)) () symbol + | _ => .goto fun _ => next + +private theorem output_encodeWord (coefficient n : Nat) : + Reduction.MachineTransducer.output transition (payload coefficient) () (encodeWord n) = + List.replicate (coefficient * n) true := by + induction n with + | zero => simp [encodeWord, Reduction.MachineTransducer.output, payload] + | succ n ih => + simp only [encodeWord, List.replicate_succ, List.cons_append, + Reduction.MachineTransducer.output, payload, ite_true, transition] + change List.replicate coefficient true ++ + Reduction.MachineTransducer.output transition (payload coefficient) () (encodeWord n) = _ + rw [ih, ← List.replicate_add] + congr 1 + simp [Nat.mul_succ, Nat.add_comm] + +theorem commandTrace (sources : Fin h → K) (scratch output : K) + (sourceScratch : ∀ i, sources i ≠ scratch) + (sourceOutput : ∀ i, sources i ≠ output) (scratchOutput : scratch ≠ output) + (labels : Phase bound → Λ) (next : Λ) (command : Command h σ bound) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ phase, + program (labels phase) = commandStatement sources scratch output labels next command phase) + (values : Fin h → Nat) (base : K → List Bool) + (operands : ∀ i, base (sources i) = encodeWord (values i)) + (scratchEmpty : base scratch = []) (ambient : σ) : + (MachineComposition.advance (TM2.step program))^[commandSteps values command] + (some ⟨some (labels .entry), ((ambient, ()), none), base⟩) = + some ⟨some next, ((ambient, ()), none), + Function.update base output ((commandBits values ambient command).reverse ++ base output)⟩ := by + cases command with + | literal word => + change some (TM2.stepAux (program (labels .entry)) ((ambient, ()), none) base) = _ + rw [atLabels] + simp only [commandStatement, stepAux_pushWord, TM2.stepAux, commandBits] + | bit value => + change some (TM2.stepAux (program (labels .entry)) ((ambient, ()), none) base) = _ + rw [atLabels] + cases hb : value ambient <;> + simp [commandStatement, TM2.stepAux, pushWord, commandBits, hb, encodeWord] + | bounded value => + change (TM2.step program ⟨some (labels .entry), ((ambient, ()), none), base⟩).bind + (TM2.step program) = _ + have first : TM2.step program ⟨some (labels .entry), ((ambient, ()), none), base⟩ = + some ⟨some (labels (.offset (value ambient))), ((ambient, ()), none), base⟩ := by + change some (TM2.stepAux (program (labels .entry)) _ _) = _ + rw [atLabels] + rfl + rw [first] + change some (TM2.stepAux (program (labels (.offset (value ambient)))) _ _) = _ + rw [atLabels] + simp only [commandStatement, stepAux_pushWord, TM2.stepAux, commandBits] + | scaled source coefficient => + have emitAt : ∀ control symbol, program (labels (.emit symbol)) = + MachineTransducerCopy.emitter output transition (payload coefficient) + (labels .entry) control symbol := by + intro control symbol + cases control + exact atLabels (.emit symbol) + have run := MachineTransducerCopy.transduceCopyTrace (sources source) scratch output + (sourceScratch source) (sourceOutput source) scratchOutput () transition (payload coefficient) + (labels .entry) (labels .restore) (fun _ symbol => labels (.emit symbol)) (some next) + program (atLabels .entry) emitAt (atLabels .restore) base scratchEmpty ambient () none + rw [operands source, encodeWord_length, output_encodeWord] at run + exact run + | scaledIf source coefficient active => + have first : TM2.step program ⟨some (labels .entry), ((ambient, ()), none), base⟩ = + some ⟨some (labels (.scanIf (active ambient))), ((ambient, ()), none), base⟩ := by + change some (TM2.stepAux (program (labels .entry)) _ _) = _ + rw [atLabels] + rfl + have emitAt : ∀ control symbol, program (labels (.emitIf (active ambient) symbol)) = + MachineTransducerCopy.emitter output transition + (payload (if active ambient then coefficient else 0)) + (labels (.scanIf (active ambient))) control symbol := by + intro control symbol + cases control + exact atLabels (.emitIf (active ambient) symbol) + have run := MachineTransducerCopy.transduceCopyTrace (sources source) scratch output + (sourceScratch source) (sourceOutput source) scratchOutput () transition + (payload (if active ambient then coefficient else 0)) + (labels (.scanIf (active ambient))) (labels .restore) + (fun _ symbol => labels (.emitIf (active ambient) symbol)) (some next) + program (atLabels (.scanIf (active ambient))) emitAt (atLabels .restore) + base scratchEmpty ambient () none + rw [operands source, encodeWord_length, output_encodeWord] at run + change (MachineComposition.advance (TM2.step program))^[ + (3 * (values source + 1) + 2) + 1] _ = _ + rw [Function.iterate_succ_apply] + simp only [MachineComposition.advance_some] + rw [first] + exact run + +abbrev Label (count bound : Nat) := Fin (count + 1) × Phase bound + +def labelAt (count bound r : Nat) (phase : Phase bound) : Label count bound := + (⟨min r count, by omega⟩, phase) + +def commandAt {count : Nat} (commands : Fin count → Command h σ bound) (r : Nat) : + Command h σ bound := + if hr : r < count then commands ⟨r, hr⟩ else .literal [] + +def statement {count : Nat} (commands : Fin count → Command h σ bound) + (sources : Fin h → K) (scratch output : K) + (labels : Label count bound → Λ) (exit : Option Λ) (label : Label count bound) : + TM2.Stmt (Alphabet (K := K)) Λ (State σ) := + if label.1.val < count then + commandStatement sources scratch output (fun phase => labels (labelAt count bound label.1.val phase)) + (labels (labelAt count bound (label.1.val + 1) .entry)) + (commandAt commands label.1.val) label.2 + else Reduction.MachineTransfer.exitAt output exit + +def program {count : Nat} (commands : Fin count → Command h σ bound) + (sources : Fin h → K) (scratch output : K) : + Label count bound → TM2.Stmt (Alphabet (K := K)) (Label count bound) (State σ) := + statement commands sources scratch output id none + +def machine [Fintype K] [Fintype σ] {count : Nat} + (commands : Fin count → Command h σ bound) (sources : Fin h → K) + (scratch output input : K) (ambient : σ) : FinTM2 where + K := K + k₀ := input + k₁ := output + Γ _ := Bool + Λ := Label count bound + main := labelAt count bound 0 .entry + σ := State σ + initialState := ((ambient, ()), none) + m := program commands sources scratch output + +def prefixBits {count : Nat} (commands : Fin count → Command h σ bound) + (values : Fin h → Nat) (ambient : σ) : Nat → List Bool + | 0 => [] + | r + 1 => prefixBits commands values ambient r ++ + commandBits values ambient (commandAt commands r) + +def prefixSteps {count : Nat} (commands : Fin count → Command h σ bound) + (values : Fin h → Nat) : Nat → Nat + | 0 => 0 + | r + 1 => prefixSteps commands values r + commandSteps values (commandAt commands r) + +def resultTapes (output : K) (base : K → List Bool) (bits : List Bool) : K → List Bool := + Function.update base output (bits.reverse ++ base output) + +@[simp] theorem resultTapes_output (output : K) (base : K → List Bool) (bits : List Bool) : + resultTapes output base bits output = bits.reverse ++ base output := by + simp [resultTapes] + +theorem resultTapes_other (output : K) (base : K → List Bool) (bits : List Bool) + (k : K) (hk : k ≠ output) : resultTapes output base bits k = base k := by + simp [resultTapes, hk] + +theorem prefixTrace {count : Nat} (commands : Fin count → Command h σ bound) + (sources : Fin h → K) (scratch output : K) + (sourceScratch : ∀ i, sources i ≠ scratch) + (sourceOutput : ∀ i, sources i ≠ output) (scratchOutput : scratch ≠ output) + (labels : Label count bound → Λ) (exit : Option Λ) + (p : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ label, p (labels label) = statement commands sources scratch output labels exit label) + (values : Fin h → Nat) (base : K → List Bool) + (operands : ∀ i, base (sources i) = encodeWord (values i)) + (scratchEmpty : base scratch = []) (ambient : σ) (r : Nat) (hr : r ≤ count) : + (MachineComposition.advance (TM2.step p))^[prefixSteps commands values r] + (some ⟨some (labels (labelAt count bound 0 .entry)), ((ambient, ()), none), base⟩) = + some ⟨some (labels (labelAt count bound r .entry)), ((ambient, ()), none), + resultTapes output base (prefixBits commands values ambient r)⟩ := by + induction r with + | zero => simp [prefixSteps, prefixBits, resultTapes] + | succ r ih => + have hrc : r < count := by omega + let prior := resultTapes output base (prefixBits commands values ambient r) + have priorOperands : ∀ i, prior (sources i) = encodeWord (values i) := by + intro i + simpa [prior, resultTapes, sourceOutput i] using operands i + have priorScratch : prior scratch = [] := by + simpa [prior, resultTapes, scratchOutput] using scratchEmpty + have commandAtLabels : ∀ phase, p (labels (labelAt count bound r phase)) = + commandStatement sources scratch output (fun phase => labels (labelAt count bound r phase)) + (labels (labelAt count bound (r + 1) .entry)) (commandAt commands r) phase := by + intro phase + rw [atLabels] + simp only [statement, labelAt, Nat.min_eq_left (Nat.le_of_lt hrc), hrc, ite_true] + have one := commandTrace sources scratch output sourceScratch sourceOutput scratchOutput + (fun phase => labels (labelAt count bound r phase)) + (labels (labelAt count bound (r + 1) .entry)) (commandAt commands r) + p commandAtLabels values prior priorOperands priorScratch ambient + rw [prefixSteps, Nat.add_comm, Function.iterate_add_apply, ih (by omega)] + rw [one] + congr 2 + simp [prior, prefixBits, resultTapes, List.reverse_append, List.append_assoc] + +theorem planTrace {count : Nat} (commands : Fin count → Command h σ bound) + (sources : Fin h → K) (scratch output : K) + (sourceScratch : ∀ i, sources i ≠ scratch) + (sourceOutput : ∀ i, sources i ≠ output) (scratchOutput : scratch ≠ output) + (labels : Label count bound → Λ) (exit : Option Λ) + (p : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ label, p (labels label) = statement commands sources scratch output labels exit label) + (values : Fin h → Nat) (base : K → List Bool) + (operands : ∀ i, base (sources i) = encodeWord (values i)) + (scratchEmpty : base scratch = []) (ambient : σ) : + (MachineComposition.advance (TM2.step p))^[prefixSteps commands values count + 1] + (some ⟨some (labels (labelAt count bound 0 .entry)), ((ambient, ()), none), base⟩) = + some ⟨exit, ((ambient, ()), none), + resultTapes output base (prefixBits commands values ambient count)⟩ := by + rw [Function.iterate_succ_apply', prefixTrace commands sources scratch output sourceScratch + sourceOutput scratchOutput labels exit p atLabels values base operands scratchEmpty ambient count + (Nat.le_refl _)] + change some (TM2.stepAux (p (labels (labelAt count bound count .entry))) _ _) = _ + rw [atLabels] + cases exit <;> simp [statement, labelAt, Reduction.MachineTransfer.exitAt, TM2.stepAux] + +theorem prefixSteps_le {count : Nat} (commands : Fin count → Command h σ bound) + (values : Fin h → Nat) (N : Nat) (bounded : ∀ i, values i ≤ N) + (r : Nat) : prefixSteps commands values r ≤ r * (3 * (N + 1) + 3) := by + induction r with + | zero => simp [prefixSteps] + | succ r ih => + have one : commandSteps values (commandAt commands r) ≤ 3 * (N + 1) + 3 := by + cases commandAt commands r with + | literal _ => simp only [commandSteps]; omega + | bit _ => simp only [commandSteps]; omega + | bounded _ => simp only [commandSteps]; omega + | scaled source _ => have hs := bounded source; simp only [commandSteps]; omega + | scaledIf source _ _ => have hs := bounded source; simp only [commandSteps]; omega + calc + prefixSteps commands values (r + 1) = + prefixSteps commands values r + commandSteps values (commandAt commands r) := rfl + _ ≤ r * (3 * (N + 1) + 3) + (3 * (N + 1) + 3) := Nat.add_le_add ih one + _ = (r + 1) * (3 * (N + 1) + 3) := (Nat.succ_mul r _).symm + +def planInTime {count : Nat} (commands : Fin count → Command h σ bound) + (sources : Fin h → K) (scratch output : K) + (sourceScratch : ∀ i, sources i ≠ scratch) + (sourceOutput : ∀ i, sources i ≠ output) (scratchOutput : scratch ≠ output) + (labels : Label count bound → Λ) (exit : Option Λ) + (p : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ label, p (labels label) = statement commands sources scratch output labels exit label) + (values : Fin h → Nat) (base : K → List Bool) + (operands : ∀ i, base (sources i) = encodeWord (values i)) + (scratchEmpty : base scratch = []) (ambient : σ) + (N : Nat) (bounded : ∀ i, values i ≤ N) : + StateTransition.EvalsToInTime (TM2.step p) + ⟨some (labels (labelAt count bound 0 .entry)), ((ambient, ()), none), base⟩ + (some ⟨exit, ((ambient, ()), none), + resultTapes output base (prefixBits commands values ambient count)⟩) + (count * (3 * (N + 1) + 3) + 1) where + steps := prefixSteps commands values count + 1 + evals_in_steps := planTrace commands sources scratch output sourceScratch sourceOutput + scratchOutput labels exit p atLabels values base operands scratchEmpty ambient + steps_le_m := Nat.add_le_add_right (prefixSteps_le commands values N bounded count) 1 + +def listCommands (commands : List (Command h σ bound)) : + Fin commands.length → Command h σ bound := fun i => commands[i] + +theorem prefixBits_listCommands (commands : List (Command h σ bound)) + (values : Fin h → Nat) (ambient : σ) (r : Nat) (hr : r ≤ commands.length) : + prefixBits (listCommands commands) values ambient r = + (commands.take r).flatMap (commandBits values ambient) := by + induction r with + | zero => simp [prefixBits] + | succ r ih => + have hrc : r < commands.length := by omega + rw [prefixBits, ih (by omega), List.take_succ_eq_append_getElem hrc, + List.flatMap_append] + simp [commandAt, hrc, listCommands] + +theorem bits_listCommands (commands : List (Command h σ bound)) + (values : Fin h → Nat) (ambient : σ) : + prefixBits (listCommands commands) values ambient commands.length = + commands.flatMap (commandBits values ambient) := by + simpa using prefixBits_listCommands commands values ambient commands.length (Nat.le_refl _) + +def affineCommands (terms : List (Fin h × Nat)) (offset : σ → Fin bound) : + List (Command h σ bound) := + terms.map (fun term => .scaled term.1 term.2) ++ [.bounded offset, .literal [false]] + +def affineValue (terms : List (Fin h × Nat)) (values : Fin h → Nat) (offset : Nat) : Nat := + (terms.map (fun term => term.2 * values term.1)).sum + offset + +private theorem scaleBits (terms : List (Fin h × Nat)) (values : Fin h → Nat) (ambient : σ) : + (terms.map (fun term => (Command.scaled term.1 term.2 : Command h σ bound))).flatMap + (commandBits values ambient) = + List.replicate ((terms.map (fun term => term.2 * values term.1)).sum) true := by + induction terms with + | nil => rfl + | cons term terms ih => + simp only [List.map_cons, List.flatMap_cons, commandBits, List.sum_cons] + rw [ih, List.replicate_add] + +theorem affineCommands_bits (terms : List (Fin h × Nat)) (offset : σ → Fin bound) + (values : Fin h → Nat) (ambient : σ) : + (affineCommands terms offset).flatMap (commandBits values ambient) = + encodeWord (affineValue terms values (offset ambient).val) := by + simp only [affineCommands, List.flatMap_append, scaleBits, List.flatMap_cons, + List.flatMap_nil, commandBits, List.append_nil, affineValue, encodeWord, + List.replicate_add, List.append_assoc] + +@[simp] theorem affineCommands_length (terms : List (Fin h × Nat)) (offset : σ → Fin bound) : + (affineCommands terms offset).length = terms.length + 2 := by + simp [affineCommands] + +def bitCommands (bits : List (σ → Bool)) : List (Command h σ bound) := bits.map .bit + +theorem bitCommands_bits (bits : List (σ → Bool)) (values : Fin h → Nat) (ambient : σ) : + (bitCommands (h := h) (bound := bound) bits).flatMap (commandBits values ambient) = + encodeWords (bits.map (fun bit => if bit ambient then 1 else 0)) := by + induction bits with + | nil => rfl + | cons bit bits ih => + simpa only [bitCommands, List.map_cons, List.flatMap_cons, commandBits, encodeWords] + using congrArg (encodeWord (if bit ambient then 1 else 0) ++ ·) ih + +def affineInTime (terms : List (Fin h × Nat)) (offset : σ → Fin bound) + (sources : Fin h → K) (scratch output : K) + (sourceScratch : ∀ i, sources i ≠ scratch) + (sourceOutput : ∀ i, sources i ≠ output) (scratchOutput : scratch ≠ output) + (labels : Label (affineCommands terms offset).length bound → Λ) (exit : Option Λ) + (p : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ label, p (labels label) = + statement (listCommands (affineCommands terms offset)) sources scratch output labels exit label) + (values : Fin h → Nat) (base : K → List Bool) + (operands : ∀ i, base (sources i) = encodeWord (values i)) + (scratchEmpty : base scratch = []) (ambient : σ) + (N : Nat) (bounded : ∀ i, values i ≤ N) : + StateTransition.EvalsToInTime (TM2.step p) + ⟨some (labels (labelAt (affineCommands terms offset).length bound 0 .entry)), + ((ambient, ()), none), base⟩ + (some ⟨exit, ((ambient, ()), none), + resultTapes output base (encodeWord (affineValue terms values (offset ambient).val))⟩) + ((terms.length + 2) * (3 * (N + 1) + 3) + 1) := by + have run := planInTime (listCommands (affineCommands terms offset)) sources scratch output + sourceScratch sourceOutput scratchOutput labels exit p atLabels values base operands + scratchEmpty ambient N bounded + rw [bits_listCommands, affineCommands_bits] at run + simpa only [affineCommands_length] using run + +def Command.mapAmbient {τ : Type} (view : σ → τ) : + Command h τ bound → Command h σ bound + | .literal word => .literal word + | .bit value => .bit (value ∘ view) + | .bounded value => .bounded (value ∘ view) + | .scaled source coefficient => .scaled source coefficient + | .scaledIf source coefficient active => .scaledIf source coefficient (active ∘ view) + +@[simp] theorem commandBits_mapAmbient {τ : Type} (view : σ → τ) + (command : Command h τ bound) (values : Fin h → Nat) (ambient : σ) : + commandBits values ambient (command.mapAmbient view) = + commandBits values (view ambient) command := by + cases command <;> rfl + +@[simp] theorem commandSteps_mapAmbient {τ : Type} (view : σ → τ) + (command : Command h τ bound) (values : Fin h → Nat) : + commandSteps values (command.mapAmbient view) = commandSteps values command := by + cases command <;> rfl + +end MinUncutGames.Foundations.PCP.AlphabetTable.Emitter + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/RuntimeSpace.lean b/lean/OAI/Computability/MinUncut/Machines/RuntimeSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..371149fbb9ccb846666543658ecada7000cad33a --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/RuntimeSpace.lean @@ -0,0 +1,125 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.RuntimeFinish + +namespace OAI + +section +namespace MinUncutGames.Foundations.Hastad.SourceRuntimeSpace + +open Turing Complexity +open scoped BigOperators + +attribute [local instance] FinTM2.kFin + +def configurationLength (tm : FinTM2) (cfg : tm.Cfg) : Nat := + ∑ k : tm.K, (cfg.stk k).length + +theorem initial_configurationLength (tm : FinTM2) (input : List (tm.Γ tm.k₀)) : + configurationLength tm (initList tm input) = input.length := by + have point (k : tm.K) : ((initList tm input).stk k).length = + if k = tm.k₀ then input.length else 0 := by + by_cases h : k = tm.k₀ + · subst k + simp [initList] + · simp [initList, h] + simp [configurationLength, point] + +theorem step_configurationLength (tm : FinTM2) (a b : tm.Cfg) + (transition : tm.step a = some b) : + configurationLength tm b ≤ configurationLength tm a + + Fintype.card tm.K * Runtime.programPushBound tm := by + calc + _ ≤ ∑ k : tm.K, ((a.stk k).length + Runtime.programPushBound tm) := + Finset.sum_le_sum (fun k _ => Runtime.stepStackLength tm k a b transition) + _ = _ := by simp [configurationLength, Finset.sum_add_distrib] + +theorem execution_configurationLength (tm : FinTM2) {start finish : tm.Cfg} + {budget : Nat} + (run : StateTransition.EvalsToInTime tm.step start (some finish) budget) : + configurationLength tm finish ≤ configurationLength tm start + + budget * (Fintype.card tm.K * Runtime.programPushBound tm) := + Runtime.executionSizeBound tm.step (configurationLength tm) + (Fintype.card tm.K * Runtime.programPushBound tm) (step_configurationLength tm) run + +theorem prefix_configurationLength (tm : FinTM2) (input : List (tm.Γ tm.k₀)) + {finish : tm.Cfg} {budget : Nat} + (run : StateTransition.EvalsToInTime tm.step (initList tm input) (some finish) budget) : + configurationLength tm finish ≤ input.length + + budget * (Fintype.card tm.K * Runtime.programPushBound tm) := by + simpa only [initial_configurationLength] using execution_configurationLength tm run + +noncomputable def spacePolynomial (tm : FinTM2) (time : Polynomial Nat) : Polynomial Nat := + Polynomial.X + time * Polynomial.C (Fintype.card tm.K * Runtime.programPushBound tm) + +theorem spacePolynomial_eval (tm : FinTM2) (time : Polynomial Nat) (N : Nat) : + (spacePolynomial tm time).eval N = N + + time.eval N * (Fintype.card tm.K * Runtime.programPushBound tm) := by + simp [spacePolynomial] + +theorem prefix_length_polynomial (tm : FinTM2) (input : List (tm.Γ tm.k₀)) + (time : Polynomial Nat) {finish : tm.Cfg} + (run : StateTransition.EvalsToInTime tm.step (initList tm input) (some finish) + (time.eval input.length)) : + configurationLength tm finish ≤ (spacePolynomial tm time).eval input.length := by + rw [spacePolynomial_eval] + exact prefix_configurationLength tm input run + +theorem totalLength_eq_configurationLength (tm : FinTM2) (finish : tm.Cfg) + (base : tm.K → List Bool) + (sameLengths : ∀ k, (base k).length = (finish.stk k).length) : + SourceRuntimeFinish.totalLength base = configurationLength tm finish := by + exact Finset.sum_congr rfl (fun k _ => sameLengths k) + +theorem finishCost_le_of_prefix (tm : FinTM2) (input : List (tm.Γ tm.k₀)) + {finish : tm.Cfg} {budget : Nat} + (run : StateTransition.EvalsToInTime tm.step (initList tm input) (some finish) budget) + (clearKeys : List tm.K) (accumulator output : tm.K) + (keepAccumulator : accumulator ∉ clearKeys) (keepOutput : output ∉ clearKeys) + (covers : ∀ k, k ≠ accumulator → k ≠ output → k ∈ clearKeys) + (base : tm.K → List Bool) (outputEmpty : base output = []) + (sameLengths : ∀ k, (base k).length = (finish.stk k).length) : + SourceRuntimeFinish.finishCost clearKeys accumulator base ≤ input.length + + budget * (Fintype.card tm.K * Runtime.programPushBound tm) + clearKeys.length + 2 := by + rw [SourceRuntimeFinish.finishCost_eq_totalLength clearKeys accumulator output + keepAccumulator keepOutput covers base outputEmpty, + totalLength_eq_configurationLength tm finish base sameLengths] + exact Nat.add_le_add_right (Nat.add_le_add_right + (prefix_configurationLength tm input run) clearKeys.length) 2 + +noncomputable def completedTime (tm : FinTM2) (clearKeyCount : Nat) + (time : Polynomial Nat) : Polynomial Nat := + time + spacePolynomial tm time + Polynomial.C (clearKeyCount + 2) + +theorem completedTime_eval (tm : FinTM2) (clearKeyCount : Nat) + (time : Polynomial Nat) (N : Nat) : + (completedTime tm clearKeyCount time).eval N = time.eval N + + (N + time.eval N * (Fintype.card tm.K * Runtime.programPushBound tm)) + + (clearKeyCount + 2) := by + simp [completedTime, spacePolynomial_eval] + +def prefixAndFinishInTime (tm : FinTM2) (input : List (tm.Γ tm.k₀)) + (time : Polynomial Nat) {middle finish : tm.Cfg} + (prefixRun : StateTransition.EvalsToInTime tm.step (initList tm input) + (some middle) (time.eval input.length)) + (clearKeys : List tm.K) (accumulator output : tm.K) + (keepAccumulator : accumulator ∉ clearKeys) (keepOutput : output ∉ clearKeys) + (covers : ∀ k, k ≠ accumulator → k ≠ output → k ∈ clearKeys) + (base : tm.K → List Bool) (outputEmpty : base output = []) + (sameLengths : ∀ k, (base k).length = (middle.stk k).length) + (finishRun : StateTransition.EvalsToInTime tm.step middle (some finish) + (SourceRuntimeFinish.finishCost clearKeys accumulator base)) : + StateTransition.EvalsToInTime tm.step (initList tm input) (some finish) + ((completedTime tm clearKeys.length time).eval input.length) := by + have joined := StateTransition.EvalsToInTime.trans tm.step _ _ _ _ _ prefixRun finishRun + have hc := finishCost_le_of_prefix tm input prefixRun clearKeys accumulator output + keepAccumulator keepOutput covers base outputEmpty sameLengths + refine { steps := joined.steps, evals_in_steps := joined.evals_in_steps, steps_le_m := ?_ } + apply Nat.le_trans joined.steps_le_m + rw [completedTime_eval] + omega + +end MinUncutGames.Foundations.Hastad.SourceRuntimeSpace + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/SelectorMachine.lean b/lean/OAI/Computability/MinUncut/Machines/SelectorMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..b6b03af2d6180a7ad70149e981f9d7db0d1474ee --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/SelectorMachine.lean @@ -0,0 +1,837 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.Alphabet + +namespace OAI + +section +namespace MinUncutGames.Foundations.Complexity.MachineRegularInternalRow +open Turing MachineComposition +open PCP +open Reduction.MachineSubstitution (pushWord stepAux_pushWord) +variable {K Λ σ : Type} [DecidableEq K] + +theorem selectionSteps_le (t : GraphTables.Table) (padding : Fin t.vertices → Nat) + (v : Fin t.vertices) (i : Fin (PreprocessingCloudIndex.cloudSize t v + padding v)) : + selectionSteps t padding v i ≤ + 10 * (GraphTables.tableBits t).length + 16 * i.val + 13 * v.val + + 5 * PreprocessingCloudIndex.cloudSize t v + + 2 * PreprocessingPaddingOffsets.offset padding v.val + 2 * t.darts + 57 := by + unfold selectionSteps + split + · rename_i hi + have hb := MachineCloudSelect.cloudSelectSteps_le t v ⟨i.val, hi⟩ [] + have hmin : min i.val (PreprocessingCloudIndex.cloudSize t v) = i.val := Nat.min_eq_left hi.le + simp only [oldSelectSteps, MachineUnaryLessAt.steps, hmin] + simp only [MachineCloudSelect.queryWord, MachineCloudRank.queryWord, + List.length_append, encodeWord_length, List.length_nil] at hb + omega + · rename_i hi + rw [dummySelectSteps_eq _ _ _ _ (Nat.le_of_not_gt hi)] + have hmin := Nat.min_le_right i.val (PreprocessingCloudIndex.cloudSize t v) + unfold MachineUnaryLessAt.steps + omega + +def selectorMachine : FinTM2 where + K := SelectTape + k₀ := .inl (.inl .original) + k₁ := selectOutput + Γ := SelectAlphabet + Λ := SelectLabel + main := .inr (.compare .scan) + σ := SelectState Unit + initialState := selectCleanState () none + m := selectProgram + +def selectionInTime (t : GraphTables.Table) (padding : Fin t.vertices → Nat) + (v : Fin t.vertices) (i : Fin (PreprocessingCloudIndex.cloudSize t v + padding v)) + (register : Option Bool) : + StateTransition.EvalsToInTime selectorMachine.step + ⟨some (.inr (.compare .scan)), selectCleanState () register, + selectMemory (GraphTables.tableBits t) i.val v.val + (PreprocessingCloudIndex.cloudSize t v) + (PreprocessingPaddingOffsets.offset padding v.val) t.darts [] [] [] [] [] []⟩ + (some ⟨none, selectCleanState () none, + selectMemory (GraphTables.tableBits t) i.val v.val + (PreprocessingCloudIndex.cloudSize t v) + (PreprocessingPaddingOffsets.offset padding v.val) t.darts [] + (encodeWord (PreprocessingInternalRows.selectedIndex t padding v i)) [] [] [] []⟩) + (10 * (GraphTables.tableBits t).length + 16 * i.val + 13 * v.val + + 5 * PreprocessingCloudIndex.cloudSize t v + + 2 * PreprocessingPaddingOffsets.offset padding v.val + 2 * t.darts + 57) where + steps := selectionSteps t padding v i + evals_in_steps := selectionTrace t padding v i () register + steps_le_m := selectionSteps_le t padding v i + +def coreRotorTapes : Fin 8 → CoreTape := ![3, 7, 10, 11, 12, 9, 13, 14] + +def coreFinishTapes : Fin 8 → CoreTape := ![1, 15, 14, 9, 24, 25, 26, 8] + +def coreSelectTape : SelectTape → CoreTape + | .inl (.inl .original) => 0 + | .inl (.inl .work) => 17 + | .inl (.inl .target) => 16 + | .inl (.inl .scratch) => 9 + | .inl (.inl .count) => 18 + | .inl (.inl .spare) => 19 + | .inl (.inr ()) => 15 + | .inr .localIndex => 13 + | .inr .owner => 2 + | .inr .cloudSize => 4 + | .inr .prefixOffset => 5 + | .inr .darts => 6 + | .inr .savedLeft => 20 + | .inr .savedRight => 21 + | .inr .localWork => 22 + | .inr .sizeWork => 23 + +def coreSelectView : CoreTape → Option SelectTape := + ![some (.inl (.inl .original)), none, some (.inr .owner), none, + some (.inr .cloudSize), some (.inr .prefixOffset), some (.inr .darts), none, none, + some (.inl (.inl .scratch)), none, none, none, some (.inr .localIndex), none, + some (.inl (.inr ())), some (.inl (.inl .target)), some (.inl (.inl .work)), + some (.inl (.inl .count)), some (.inl (.inl .spare)), + some (.inr .savedLeft), some (.inr .savedRight), + some (.inr .localWork), some (.inr .sizeWork), none, none, none] + +theorem coreSelectView_left (k : SelectTape) : coreSelectView (coreSelectTape k) = some k := by + cases k with + | inl k => + cases k with + | inl k => cases k <;> rfl + | inr k => cases k; rfl + | inr k => cases k <;> rfl + +theorem coreSelectView_right (j : CoreTape) (k : SelectTape) + (h : coreSelectView j = some k) : coreSelectTape k = j := by + fin_cases j <;> simp [coreSelectView] at h + all_goals subst k; rfl + +def coreCleanupTape : Fin 10 → CoreTape := ![10, 11, 12, 13, 14, 15, 9, 16, 17, 18] + +def coreRotorStateEquiv (σ : Type) (q : Nat) : + MachineFixedDivMod.State + ((σ × MachineFixedBlockMap.Buffer 4096) × (Bool × MachineCloudSelect.Phase)) q ≃ + CoreState σ q where + toFun s := ((s.1.1.1.1, (s.1.1.1.2, (s.1.2, s.1.1.2))), s.2) + invFun s := ((((s.1.1, s.1.2.1), s.1.2.2.2), s.1.2.2.1), s.2) + left_inv s := by rcases s with ⟨⟨⟨⟨a,b⟩,⟨c,d⟩⟩,e⟩,f⟩; rfl + right_inv s := by rcases s with ⟨⟨a,⟨b,⟨c,⟨d,e⟩⟩⟩⟩,f⟩; rfl + +def coreSelectStateEquiv (σ : Type) (q : Nat) : + SelectState (σ × (MachineFixedBlockMap.Buffer 4096 × Fin q)) ≃ CoreState σ q where + toFun s := ((s.1.1.1.1, (s.1.1.1.2.1, (s.1.1.1.2.2, (s.1.2, s.1.1.2)))), s.2) + invFun s := ((((s.1.1, (s.1.2.1, s.1.2.2.1)), s.1.2.2.2.2), s.1.2.2.2.1), s.2) + left_inv s := by rcases s with ⟨⟨⟨⟨a,⟨b,c⟩⟩,d⟩,e⟩,f⟩; rfl + right_inv s := by rcases s with ⟨⟨a,⟨b,⟨c,⟨d,e⟩⟩⟩⟩,f⟩; rfl + +def coreAfterCleanup {q : Nat} (labels : CoreLabel q → Λ) (exit : Option Λ) (i : Fin 10) : + Option Λ := + if h : i.val + 1 < 10 then some (labels (.cleanup ⟨i.val + 1,h⟩)) else exit + +def coreInstruction (q : Nat) (positive : 0 < q) (p : Fin q) + (labels : CoreLabel q → Λ) (exit : Option Λ) : + CoreLabel q → TM2.Stmt (fun _ : CoreTape => Bool) Λ (CoreState σ q) + | .rotor stage => MachineStateEquiv.statement (coreRotorStateEquiv σ q) + (rotorInstruction q positive p coreRotorTapes + (fun l => labels (.rotor l)) (some (labels (.select (.inr (.compare .scan))))) stage) + | .select stage => MachineCloudPadding.Placement.statement coreSelectTape + (fun l => labels (.select l)) (some (labels (.finish .seedReturn))) + (MachineStateEquiv.statement (coreSelectStateEquiv σ q) (selectProgram stage)) + | .finish stage => finishInstruction q coreFinishTapes + (fun l => labels (.finish l)) (some (labels (.cleanup 0))) stage + | .cleanup i => MachineDrain.drain (coreCleanupTape i) (labels (.cleanup i)) + (coreAfterCleanup labels exit i) + +def coreInitialState (q : Nat) (positive : 0 < q) (ambient : σ) : CoreState σ q := + ((ambient, (MachineFixedBlockMap.emptyBuffer 4096, + (MachineFixedDivMod.residue q positive 0, (false, MachineCloudSelect.Phase.checking)))), none) + +def coreMachine (q : Nat) (positive : 0 < q) (p : Fin q) : FinTM2 where + K := CoreTape + k₀ := 0 + k₁ := 8 + Γ _ := Bool + Λ := CoreLabel q + main := coreEntry q + σ := CoreState Unit q + initialState := coreInitialState q positive () + m := coreInstruction q positive p id none + +def coreMemory (graph : List Bool) (x v i k o m : Nat) (rotor output : List Bool) + (query scan flat localIndex returnPort selected : List Bool) : CoreTape → List Bool := + ![graph, encodeWord x, encodeWord v, encodeWord i, encodeWord k, encodeWord o, + encodeWord m, rotor, output, [], query, scan, flat, localIndex, returnPort, selected, + [], [], [], [], [], [], [], [], [], [], []] + +@[simp] theorem coreMemory_update_output (graph : List Bool) (x v i k o m : Nat) + (rotor output query scan flat localIndex returnPort selected newOutput : List Bool) : + Function.update (coreMemory graph x v i k o m rotor output query scan flat + localIndex returnPort selected) (8 : CoreTape) newOutput = + coreMemory graph x v i k o m rotor newOutput query scan flat localIndex returnPort selected := by + funext z + fin_cases z <;> rfl + +theorem coreRotorTapes_injective : Function.Injective coreRotorTapes := by + intro i j h + fin_cases i <;> fin_cases j <;> simp_all [coreRotorTapes] + +theorem coreFinishTapes_injective : Function.Injective coreFinishTapes := by + intro i j h + fin_cases i <;> fin_cases j <;> simp_all [coreFinishTapes] + +def coreCleaned (base : CoreTape → List Bool) : CoreTape → List Bool := + Function.update (Function.update (Function.update (Function.update (Function.update + (Function.update (Function.update (Function.update (Function.update + (Function.update base 10 []) 11 []) 12 []) 13 []) 14 []) 15 []) 9 []) 16 []) 17 []) 18 [] + +def coreCleanupSteps (base : CoreTape → List Bool) : Nat := + (base 10).length + (base 11).length + (base 12).length + (base 13).length + + (base 14).length + (base 15).length + (base 9).length + (base 16).length + + (base 17).length + (base 18).length + 10 + +theorem coreCleanupTrace (q : Nat) (positive : 0 < q) (p : Fin q) + (labels : CoreLabel q → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : CoreTape => Bool) Λ (CoreState σ q)) + (code : ∀ l, program (labels l) = coreInstruction q positive p labels exit l) + (base : CoreTape → List Bool) + (ambient : σ × (MachineFixedBlockMap.Buffer 4096 × + (Fin q × (Bool × MachineCloudSelect.Phase)))) : + (advance (TM2.step program))^[coreCleanupSteps base] + (some ⟨some (labels (.cleanup 0)), (ambient, none), base⟩) = + some ⟨exit, (ambient, none), coreCleaned base⟩ := by + let b1 := Function.update base (10 : CoreTape) [] + have h0 := MachineDrain.drainTrace (10 : CoreTape) (labels (.cleanup 0)) + (some (labels (.cleanup 1))) program (code (.cleanup 0)) base (base 10) ambient none + rw [Function.update_eq_self] at h0 + let b2 := Function.update b1 (11 : CoreTape) [] + have h1 := MachineDrain.drainTrace (11 : CoreTape) (labels (.cleanup 1)) + (some (labels (.cleanup 2))) program (code (.cleanup 1)) b1 (b1 11) ambient none + rw [Function.update_eq_self] at h1 + have hw1 : b1 11 = base 11 := by simp [b1] + rw [hw1] at h1 + let b3 := Function.update b2 (12 : CoreTape) [] + have h2 := MachineDrain.drainTrace (12 : CoreTape) (labels (.cleanup 2)) + (some (labels (.cleanup 3))) program (code (.cleanup 2)) b2 (b2 12) ambient none + rw [Function.update_eq_self] at h2 + have hw2 : b2 12 = base 12 := by simp [b1, b2] + rw [hw2] at h2 + let b4 := Function.update b3 (13 : CoreTape) [] + have h3 := MachineDrain.drainTrace (13 : CoreTape) (labels (.cleanup 3)) + (some (labels (.cleanup 4))) program (code (.cleanup 3)) b3 (b3 13) ambient none + rw [Function.update_eq_self] at h3 + have hw3 : b3 13 = base 13 := by simp [b1, b2, b3] + rw [hw3] at h3 + let b5 := Function.update b4 (14 : CoreTape) [] + have h4 := MachineDrain.drainTrace (14 : CoreTape) (labels (.cleanup 4)) + (some (labels (.cleanup 5))) program (code (.cleanup 4)) b4 (b4 14) ambient none + rw [Function.update_eq_self] at h4 + have hw4 : b4 14 = base 14 := by simp [b1, b2, b3, b4] + rw [hw4] at h4 + let b6 := Function.update b5 (15 : CoreTape) [] + have h5 := MachineDrain.drainTrace (15 : CoreTape) (labels (.cleanup 5)) + (some (labels (.cleanup 6))) program (code (.cleanup 5)) b5 (b5 15) ambient none + rw [Function.update_eq_self] at h5 + have hw5 : b5 15 = base 15 := by simp [b1, b2, b3, b4, b5] + rw [hw5] at h5 + let b7 := Function.update b6 (9 : CoreTape) [] + have h6 := MachineDrain.drainTrace (9 : CoreTape) (labels (.cleanup 6)) + (some (labels (.cleanup 7))) program (code (.cleanup 6)) b6 (b6 9) ambient none + rw [Function.update_eq_self] at h6 + have hw6 : b6 9 = base 9 := by simp [b1, b2, b3, b4, b5, b6] + rw [hw6] at h6 + let b8 := Function.update b7 (16 : CoreTape) [] + have h7 := MachineDrain.drainTrace (16 : CoreTape) (labels (.cleanup 7)) + (some (labels (.cleanup 8))) program (code (.cleanup 7)) b7 (b7 16) ambient none + rw [Function.update_eq_self] at h7 + have hw7 : b7 16 = base 16 := by simp [b1, b2, b3, b4, b5, b6, b7] + rw [hw7] at h7 + let b9 := Function.update b8 (17 : CoreTape) [] + have h8 := MachineDrain.drainTrace (17 : CoreTape) (labels (.cleanup 8)) + (some (labels (.cleanup 9))) program (code (.cleanup 8)) b8 (b8 17) ambient none + rw [Function.update_eq_self] at h8 + have hw8 : b8 17 = base 17 := by simp [b1, b2, b3, b4, b5, b6, b7, b8] + rw [hw8] at h8 + let b10 := Function.update b9 (18 : CoreTape) [] + have h9 := MachineDrain.drainTrace (18 : CoreTape) (labels (.cleanup 9)) + exit program (code (.cleanup 9)) b9 (b9 18) ambient none + rw [Function.update_eq_self] at h9 + have hw9 : b9 18 = base 18 := by simp [b1, b2, b3, b4, b5, b6, b7, b8, b9] + rw [hw9] at h9 + have total := (joinTrace (joinTrace (joinTrace (joinTrace (joinTrace (joinTrace (joinTrace (joinTrace (joinTrace h0 h1) h2) h3) h4) h5) h6) h7) h8) h9) + have hn : coreCleanupSteps base = + (base 10).length + 1 + ((base 11).length + 1) + ((base 12).length + 1) + + ((base 13).length + 1) + ((base 14).length + 1) + ((base 15).length + 1) + + ((base 9).length + 1) + ((base 16).length + 1) + ((base 17).length + 1) + + ((base 18).length + 1) := by unfold coreCleanupSteps; omega + rw [hn] + exact total + +theorem coreCleaned_memory (graph : List Bool) (x v i k o m : Nat) + (rotor output query scan flat localIndex returnPort selected : List Bool) : + coreCleaned (coreMemory graph x v i k o m rotor output query scan flat + localIndex returnPort selected) = + coreMemory graph x v i k o m rotor output [] [] [] [] [] [] := by + funext z + fin_cases z <;> rfl + +theorem coreCleanupSteps_memory (graph : List Bool) (x v i k o m : Nat) + (rotor output scan : List Bool) (j r z : Nat) : + coreCleanupSteps (coreMemory graph x v i k o m rotor output + (encodeWord 0) scan (encodeWord 0) (encodeWord j) (encodeWord r) (encodeWord z)) = + scan.length + j + r + z + 15 := by + change (encodeWord 0).length + scan.length + (encodeWord 0).length + + (encodeWord j).length + (encodeWord r).length + (encodeWord z).length + + ([] : List Bool).length + ([] : List Bool).length + ([] : List Bool).length + + ([] : List Bool).length + 10 = _ + simp only [encodeWord_length, List.length_nil] + omega + +theorem coreRotorFinalFrame {n q : Nat} (table : ExpanderTables.Table n q) (i : Fin n) (p : Fin q) + (graph : List Bool) (x v k o m : Nat) (output : List Bool) : + rotorFinalTapes table i p coreRotorTapes + (coreMemory graph x v i.val k o m + (encodeWords (ExpanderTableWords.rotationWords table)) output [] [] [] [] [] []) = + coreMemory graph x v i.val k o m + (encodeWords (ExpanderTableWords.rotationWords table)) output (encodeWord 0) + (encodeWords ((ExpanderTableWords.rotationWords table).drop (q * i.val + p.val + 1))) + (encodeWord 0) (encodeWord (ExpanderTables.lookup table (i, p)).1.val) + (encodeWord (ExpanderTables.lookup table (i, p)).2.val) [] := by + funext z + fin_cases z <;> + simp [rotorFinalTapes, coreRotorTapes, rotorLookupTapes, coreMemory, + MachineFixedDivMod.unaryTapes, MachineFixedDivMod.tapes, MachineCopy.forkTapes, + MachineAffineLookup.finalTapes, MachinePreservingLookup.finalTapes, MachineLookup.tapes] + +theorem coreRotorTrace {n q : Nat} (positive : 0 < q) (table : ExpanderTables.Table n q) + (i : Fin n) (p : Fin q) (labels : CoreLabel q → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : CoreTape => Bool) Λ (CoreState σ q)) + (code : ∀ l, program (labels l) = coreInstruction q positive p labels exit l) + (graph : List Bool) (x v k o m : Nat) (output : List Bool) (ambient : σ) : + (advance (TM2.step program))^[rotorSteps table i p] + (some ⟨some (labels (coreEntry q)), coreInitialState q positive ambient, + coreMemory graph x v i.val k o m + (encodeWords (ExpanderTableWords.rotationWords table)) output [] [] [] [] [] []⟩) = + some ⟨some (labels (.select (.inr (.compare .scan)))), coreInitialState q positive ambient, + coreMemory graph x v i.val k o m + (encodeWords (ExpanderTableWords.rotationWords table)) output (encodeWord 0) + (encodeWords ((ExpanderTableWords.rotationWords table).drop (q * i.val + p.val + 1))) + (encodeWord 0) (encodeWord (ExpanderTables.lookup table (i, p)).1.val) + (encodeWord (ExpanderTables.lookup table (i, p)).2.val) []⟩ := by + let e := coreRotorStateEquiv σ q + let backwards := MachineStateEquiv.program e.symm program + have atRotor (l : RotorLabel q) : + backwards (labels (.rotor l)) = rotorInstruction q positive p coreRotorTapes + (fun l => labels (.rotor l)) (some (labels (.select (.inr (.compare .scan))))) l := by + change MachineStateEquiv.statement e.symm (program (labels (.rotor l))) = _ + rw [code] + exact MachineStateEquiv.statement_symm_statement e _ + have run := rotorTrace positive table i p coreRotorTapes coreRotorTapes_injective + (fun l => labels (.rotor l)) (some (labels (.select (.inr (.compare .scan))))) + backwards atRotor + (coreMemory graph x v i.val k o m + (encodeWords (ExpanderTableWords.rotationWords table)) output [] [] [] [] [] []) + rfl rfl rfl rfl rfl rfl + ((ambient, MachineFixedBlockMap.emptyBuffer 4096), (false, MachineCloudSelect.Phase.checking)) none + have h := MachineStateEquiv.trace e backwards _ _ _ run + have backForward : MachineStateEquiv.program e backwards = program := by + have hp := MachineStateEquiv.program_symm_program e.symm program + simpa only [Equiv.symm_symm, backwards] using hp + rw [backForward] at h + change (advance (TM2.step program))^[rotorSteps table i p] + (some ⟨some (labels (coreEntry q)), coreInitialState q positive ambient, + coreMemory graph x v i.val k o m + (encodeWords (ExpanderTableWords.rotationWords table)) output [] [] [] [] [] []⟩) = + some ⟨some (labels (.select (.inr (.compare .scan)))), coreInitialState q positive ambient, + rotorFinalTapes table i p coreRotorTapes + (coreMemory graph x v i.val k o m + (encodeWords (ExpanderTableWords.rotationWords table)) output [] [] [] [] [] [])⟩ at h + rw [coreRotorFinalFrame] at h + exact h + +theorem coreSelectFrame (graph : List Bool) (x v i k o m j : Nat) + (rotor output query scan flat returnPort selected : List Bool) : + MachineCloudPadding.Placement.tapes coreSelectView + (selectMemory graph j v k o m [] selected [] [] [] []) + (coreMemory graph x v i k o m rotor output query scan flat (encodeWord j) returnPort []) = + coreMemory graph x v i k o m rotor output query scan flat (encodeWord j) returnPort selected := by + funext z + fin_cases z <;> rfl + +theorem coreSelectionTrace (q : Nat) (positive : 0 < q) (p : Fin q) + (labels : CoreLabel q → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : CoreTape => Bool) Λ (CoreState σ q)) + (code : ∀ l, program (labels l) = coreInstruction q positive p labels exit l) + (t : GraphTables.Table) (padding : Fin t.vertices → Nat) (v : Fin t.vertices) + (j : Fin (PreprocessingCloudIndex.cloudSize t v + padding v)) + (x i : Nat) (rotor output query scan flat returnPort : List Bool) (ambient : σ) : + (advance (TM2.step program))^[selectionSteps t padding v j] + (some ⟨some (labels (.select (.inr (.compare .scan)))), coreInitialState q positive ambient, + coreMemory (GraphTables.tableBits t) x v.val i (PreprocessingCloudIndex.cloudSize t v) + (PreprocessingPaddingOffsets.offset padding v.val) t.darts rotor output query scan flat + (encodeWord j.val) returnPort []⟩) = + some ⟨some (labels (.finish .seedReturn)), coreInitialState q positive ambient, + coreMemory (GraphTables.tableBits t) x v.val i (PreprocessingCloudIndex.cloudSize t v) + (PreprocessingPaddingOffsets.offset padding v.val) t.darts rotor output query scan flat + (encodeWord j.val) returnPort + (encodeWord (PreprocessingInternalRows.selectedIndex t padding v j))⟩ := by + let e := coreSelectStateEquiv σ q + let state := (ambient, (MachineFixedBlockMap.emptyBuffer 4096, + MachineFixedDivMod.residue q positive 0)) + have sourceRun := selectionTrace t padding v j state none + have moved := MachineStateEquiv.trace e selectProgram _ _ _ sourceRun + let base := coreMemory (GraphTables.tableBits t) x v.val i + (PreprocessingCloudIndex.cloudSize t v) + (PreprocessingPaddingOffsets.offset padding v.val) t.darts rotor output query scan flat + (encodeWord j.val) returnPort [] + have placed := MachineCloudPadding.Placement.trace coreSelectTape coreSelectView + coreSelectView_left coreSelectView_right (fun l => labels (.select l)) + (some (labels (.finish .seedReturn))) base + (MachineStateEquiv.program e selectProgram) program (fun l => code (.select l)) + _ _ _ moved + simp only [MachineCloudPadding.Placement.configuration, MachineCloudPadding.Placement.label, + MachineStateEquiv.configuration, base, coreSelectFrame] at placed + convert placed using 1 <;> rfl + +theorem coreFinishTrace (q : Nat) (positive : 0 < q) (p : Fin q) + (labels : CoreLabel q → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : CoreTape => Bool) Λ (CoreState σ q)) + (code : ∀ l, program (labels l) = coreInstruction q positive p labels exit l) + (graph : List Bool) (x v i k o m j r z : Nat) + (rotor output query scan flat : List Bool) (ambient : σ) : + (advance (TM2.step program))^[finishSteps q x z r output.length] + (some ⟨some (labels (.finish .seedReturn)), coreInitialState q positive ambient, + coreMemory graph x v i k o m rotor output query scan flat + (encodeWord j) (encodeWord r) (encodeWord z)⟩) = + some ⟨some (labels (.cleanup 0)), coreInitialState q positive ambient, + coreMemory graph x v i k o m rotor (output ++ emittedBits q x z r) query scan flat + (encodeWord j) (encodeWord r) (encodeWord z)⟩ := by + have h := finishTrace q coreFinishTapes coreFinishTapes_injective + (fun l => labels (.finish l)) (some (labels (.cleanup 0))) program + (fun l => code (.finish l)) + (coreMemory graph x v i k o m rotor output query scan flat + (encodeWord j) (encodeWord r) (encodeWord z)) + x z r rfl rfl rfl rfl rfl rfl rfl + (ambient, (MachineFixedBlockMap.emptyBuffer 4096, + (MachineFixedDivMod.residue q positive 0, (false, MachineCloudSelect.Phase.checking)))) none + change (advance (TM2.step program))^[finishSteps q x z r output.length] + (some ⟨some (labels (.finish .seedReturn)), coreInitialState q positive ambient, + coreMemory graph x v i k o m rotor output query scan flat + (encodeWord j) (encodeWord r) (encodeWord z)⟩) = + some ⟨some (labels (.cleanup 0)), coreInitialState q positive ambient, + Function.update (coreMemory graph x v i k o m rotor output query scan flat + (encodeWord j) (encodeWord r) (encodeWord z)) (8 : CoreTape) + (output ++ emittedBits q x z r)⟩ at h + rw [coreMemory_update_output] at h + exact h + +def coreInputTapes (t : GraphTables.Table) (padding : Fin t.vertices → Nat) {q : Nat} + (tables : ∀ v, ExpanderTables.Table (PreprocessingCloudIndex.cloudSize t v + padding v) q) + (v : Fin t.vertices) (x : PreprocessingCloudIndex.PaddedCloud t padding v) + (output : List Bool) : CoreTape → List Bool := + coreMemory (GraphTables.tableBits t) + (PreprocessingRegularTables.vertexOrder t padding x.val).val v.val + (PreprocessingCloudIndex.paddedCloudRank t padding v x).val + (PreprocessingCloudIndex.cloudSize t v) (PreprocessingPaddingOffsets.offset padding v.val) t.darts + (encodeWords (ExpanderTableWords.rotationWords (tables v))) output [] [] [] [] [] [] + +def coreSteps (t : GraphTables.Table) (padding : Fin t.vertices → Nat) {q : Nat} + (tables : ∀ v, ExpanderTables.Table (PreprocessingCloudIndex.cloudSize t v + padding v) q) + (v : Fin t.vertices) (x : PreprocessingCloudIndex.PaddedCloud t padding v) + (p : Fin q) (outputLength : Nat) : Nat := + let rank := PreprocessingCloudIndex.paddedCloudRank t padding v x + let step := ExpanderTables.lookup (tables v) (rank, p) + let selected := PreprocessingInternalRows.selectedIndex t padding v step.1 + let suffixBits := encodeWords ((ExpanderTableWords.rotationWords (tables v)).drop + (q * rank.val + p.val + 1)) + rotorSteps (tables v) rank p + selectionSteps t padding v step.1 + + finishSteps q (PreprocessingRegularTables.vertexOrder t padding x.val).val + selected step.2.val outputLength + + (suffixBits.length + step.1.val + step.2.val + selected + 15) + +theorem coreTrace (q : Nat) (positive : 0 < q) (p : Fin q) + (labels : CoreLabel q → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : CoreTape => Bool) Λ (CoreState σ q)) + (code : ∀ l, program (labels l) = coreInstruction q positive p labels exit l) + (t : GraphTables.Table) (padding : Fin t.vertices → Nat) + (tables : ∀ v, ExpanderTables.Table (PreprocessingCloudIndex.cloudSize t v + padding v) q) + (v : Fin t.vertices) (x : PreprocessingCloudIndex.PaddedCloud t padding v) + (output : List Bool) (ambient : σ) : + (advance (TM2.step program))^[coreSteps t padding tables v x p output.length] + (some ⟨some (labels (coreEntry q)), coreInitialState q positive ambient, + coreInputTapes t padding tables v x output⟩) = + some ⟨exit, coreInitialState q positive ambient, + coreInputTapes t padding tables v x + (output ++ encodeWords (GraphTables.rowWords + (PreprocessingInternalRows.row t padding tables v x p)))⟩ := by + let rank := PreprocessingCloudIndex.paddedCloudRank t padding v x + let step := ExpanderTables.lookup (tables v) (rank, p) + let z := PreprocessingInternalRows.selectedIndex t padding v step.1 + let X := (PreprocessingRegularTables.vertexOrder t padding x.val).val + let o := PreprocessingPaddingOffsets.offset padding v.val + let bits := encodeWords (ExpanderTableWords.rotationWords (tables v)) + let tailBits := encodeWords ((ExpanderTableWords.rotationWords (tables v)).drop + (q * rank.val + p.val + 1)) + let graph := GraphTables.tableBits t + let k := PreprocessingCloudIndex.cloudSize t v + have hr := coreRotorTrace positive (tables v) rank p labels exit program code + graph X v.val k o t.darts output ambient + have hs := coreSelectionTrace q positive p labels exit program code t padding v step.1 + X rank.val bits output (encodeWord 0) tailBits (encodeWord 0) (encodeWord step.2.val) ambient + have hf := coreFinishTrace q positive p labels exit program code + graph X v.val rank.val k o t.darts step.1.val step.2.val z bits output + (encodeWord 0) tailBits (encodeWord 0) ambient + have hc := coreCleanupTrace q positive p labels exit program code + (coreMemory graph X v.val rank.val k o t.darts bits + (output ++ emittedBits q X z step.2.val) + (encodeWord 0) tailBits (encodeWord 0) (encodeWord step.1.val) + (encodeWord step.2.val) (encodeWord z)) + (ambient, (MachineFixedBlockMap.emptyBuffer 4096, + (MachineFixedDivMod.residue q positive 0, (false, MachineCloudSelect.Phase.checking)))) + rw [coreCleanupSteps_memory, coreCleaned_memory] at hc + have h := joinTrace (joinTrace (joinTrace hr hs) hf) hc + have hbits : emittedBits q X z step.2.val = + encodeWords (GraphTables.rowWords (PreprocessingInternalRows.row t padding tables v x p)) := + emittedBits_eq_row t padding tables v x p + rw [hbits] at h + exact h + +theorem selectedIndex_le (t : GraphTables.Table) (padding : Fin t.vertices → Nat) + (v : Fin t.vertices) (i : Fin (PreprocessingCloudIndex.cloudSize t v + padding v)) : + PreprocessingInternalRows.selectedIndex t padding v i ≤ + t.darts + PreprocessingPaddingOffsets.offset padding v.val + i.val := by + unfold PreprocessingInternalRows.selectedIndex + split + · rename_i hi + have h := (PreprocessingCloudIndex.cloudSelect t v ⟨i.val, hi⟩).val.isLt + omega + · omega + +theorem encodedDrop_length_le (values : List Nat) (n : Nat) : + (encodeWords (values.drop n)).length ≤ (encodeWords values).length := by + have h : (encodeWords (values.take n)).length + (encodeWords (values.drop n)).length = + (encodeWords values).length := by + rw [← List.length_append, ← encodeWords_append, List.take_append_drop] + omega + +theorem rotorSize_le_encodedLength {n q : Nat} (positive : 0 < q) + (table : ExpanderTables.Table n q) : + n ≤ (encodeWords (ExpanderTableWords.rotationWords table)).length := by + have h : n * q ≤ (encodeWords (ExpanderTableWords.rotationWords table)).length := by + rw [encodeWords_length, ExpanderTableWords.rotationWords_length] + omega + exact (Nat.le_mul_of_pos_right n positive).trans h + +def coreTimeBound (q graphLength rotorLength x v i k o m outputLength : Nat) : Nat := + (5 * q + 32) * rotorLength + 10 * graphLength + 2 * i + 13 * v + 5 * k + + (5 * q + 10) * (m + o) + 4 * x + 2 * outputLength + 8 * q + 41066 + +theorem coreSteps_le (q : Nat) (positive : 0 < q) (t : GraphTables.Table) + (padding : Fin t.vertices → Nat) + (tables : ∀ v, ExpanderTables.Table (PreprocessingCloudIndex.cloudSize t v + padding v) q) + (v : Fin t.vertices) (x : PreprocessingCloudIndex.PaddedCloud t padding v) + (p : Fin q) (outputLength : Nat) : + coreSteps t padding tables v x p outputLength ≤ + coreTimeBound q (GraphTables.tableBits t).length + (encodeWords (ExpanderTableWords.rotationWords (tables v))).length + (PreprocessingRegularTables.vertexOrder t padding x.val).val v.val + (PreprocessingCloudIndex.paddedCloudRank t padding v x).val + (PreprocessingCloudIndex.cloudSize t v) + (PreprocessingPaddingOffsets.offset padding v.val) t.darts outputLength := by + let rank := PreprocessingCloudIndex.paddedCloudRank t padding v x + let step := ExpanderTables.lookup (tables v) (rank, p) + let z := PreprocessingInternalRows.selectedIndex t padding v step.1 + let X := (PreprocessingRegularTables.vertexOrder t padding x.val).val + let o := PreprocessingPaddingOffsets.offset padding v.val + let L := (GraphTables.tableBits t).length + let R := (encodeWords (ExpanderTableWords.rotationWords (tables v))).length + let k := PreprocessingCloudIndex.cloudSize t v + let tailBits := encodeWords ((ExpanderTableWords.rotationWords (tables v)).drop + (q * rank.val + p.val + 1)) + have hN : k + padding v ≤ R := rotorSize_le_encodedLength positive (tables v) + have hj : step.1.val ≤ R := step.1.isLt.le.trans hN + have hr : step.2.val ≤ q := step.2.isLt.le + have hz : z ≤ t.darts + o + R := by + have h := selectedIndex_le t padding v step.1 + change z ≤ t.darts + o + step.1.val at h + omega + have hsize : (k + padding v) * q ≤ R := by + dsimp only [R, k] + rw [encodeWords_length, ExpanderTableWords.rotationWords_length] + omega + have hrotor : rotorSteps (tables v) rank p ≤ 2 * rank.val + 6 * R + 8 := by + have h := rotorSteps_le (tables v) rank p + change rotorSteps (tables v) rank p ≤ 2 * rank.val + 5 * R + (k + padding v) * q + 8 at h + omega + have hselect : selectionSteps t padding v step.1 ≤ + 10 * L + 16 * R + 13 * v.val + 5 * k + 2 * o + 2 * t.darts + 57 := by + have h := selectionSteps_le t padding v step.1 + change selectionSteps t padding v step.1 ≤ + 10 * L + 16 * step.1.val + 13 * v.val + 5 * k + 2 * o + 2 * t.darts + 57 at h + omega + have hfinish : finishSteps q X z step.2.val outputLength ≤ + (5 * q + 7) * (t.darts + o + R) + 7 * q + 4 * X + 2 * outputLength + 40986 := by + have h := finishSteps_le q X z step.2.val outputLength + have hm := Nat.mul_le_mul_left (5 * q + 7) hz + omega + have htail : tailBits.length ≤ R := encodedDrop_length_le + (ExpanderTableWords.rotationWords (tables v)) (q * rank.val + p.val + 1) + have hcleanup : tailBits.length + step.1.val + step.2.val + z + 15 ≤ + R + R + q + (t.darts + o + R) + 15 := by omega + calc + coreSteps t padding tables v x p outputLength + ≤ (2 * rank.val + 6 * R + 8) + + (10 * L + 16 * R + 13 * v.val + 5 * k + 2 * o + 2 * t.darts + 57) + + ((5 * q + 7) * (t.darts + o + R) + 7 * q + 4 * X + 2 * outputLength + 40986) + + (R + R + q + (t.darts + o + R) + 15) := + Nat.add_le_add (Nat.add_le_add (Nat.add_le_add hrotor hselect) hfinish) hcleanup + _ = _ := by + change _ = coreTimeBound q L R X v.val rank.val k o t.darts outputLength + unfold coreTimeBound + ring + +def coreMachineInTime (q : Nat) (positive : 0 < q) (t : GraphTables.Table) + (padding : Fin t.vertices → Nat) + (tables : ∀ v, ExpanderTables.Table (PreprocessingCloudIndex.cloudSize t v + padding v) q) + (v : Fin t.vertices) (x : PreprocessingCloudIndex.PaddedCloud t padding v) + (p : Fin q) (output : List Bool) : + StateTransition.EvalsToInTime (coreMachine q positive p).step + ⟨some (coreEntry q), coreInitialState q positive (), coreInputTapes t padding tables v x output⟩ + (some ⟨none, coreInitialState q positive (), coreInputTapes t padding tables v x + (output ++ encodeWords (GraphTables.rowWords (PreprocessingInternalRows.row t padding tables v x p)))⟩) + (coreTimeBound q (GraphTables.tableBits t).length + (encodeWords (ExpanderTableWords.rotationWords (tables v))).length + (PreprocessingRegularTables.vertexOrder t padding x.val).val v.val + (PreprocessingCloudIndex.paddedCloudRank t padding v x).val + (PreprocessingCloudIndex.cloudSize t v) + (PreprocessingPaddingOffsets.offset padding v.val) t.darts output.length) where + steps := coreSteps t padding tables v x p output.length + evals_in_steps := coreTrace q positive p id none (coreMachine q positive p).m + (fun _ => rfl) t padding tables v x output () + steps_le_m := coreSteps_le q positive t padding tables v x p output.length + +end MinUncutGames.Foundations.Complexity.MachineRegularInternalRow + +end +section +namespace MinUncutGames.Foundations.Complexity.MachineRegularOriginalClean + +open Turing MachineComposition PCP PCP.GraphTables PCP.PreprocessingRegularTables + +abbrev Tape := MachineRegularOriginalRow.Tape +abbrev Alphabet := MachineRegularOriginalRow.Alphabet +abbrev State := MachineRegularOriginalRow.State + +inductive Label + | row (label : MachineRegularOriginalRow.Label) + | query | scan | rawReverse | computedReverse | relation + deriving DecidableEq, Fintype + +def instruction {σ Λ : Type} (q : Nat) (labels : Label → Λ) (exit : Option Λ) : + Label → TM2.Stmt Alphabet Λ (State σ) + | .row l => MachineRegularOriginalRow.instruction q (fun l => labels (.row l)) + (some (labels .query)) l + | .query => MachineDrain.drain 2 (labels .query) (some (labels .scan)) + | .scan => MachineDrain.drain 3 (labels .scan) (some (labels .rawReverse)) + | .rawReverse => MachineDrain.drain 4 (labels .rawReverse) (some (labels .computedReverse)) + | .computedReverse => MachineDrain.drain 6 (labels .computedReverse) (some (labels .relation)) + | .relation => MachineDrain.drain 7 (labels .relation) exit + +def cleanupTapes (base : Tape → List Bool) : Tape → List Bool := + Function.update (Function.update (Function.update (Function.update + (Function.update base 2 []) 3 []) 4 []) 6 []) 7 [] + +def cleanupSteps (base : Tape → List Bool) : Nat := + ((base 2).length + 1) + ((base 3).length + 1) + ((base 4).length + 1) + + ((base 6).length + 1) + ((base 7).length + 1) + +theorem join_trace {A : Type*} {f : A → A} {m n : Nat} {a b c : A} + (first : f^[m] a = b) (second : f^[n] b = c) : f^[m + n] a = c := by + rw [Nat.add_comm m n, Function.iterate_add_apply, first, second] + +theorem cleanupTraceAt {σ Λ : Type} (q : Nat) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt Alphabet Λ (State σ)) + (code : ∀ l, program (labels l) = instruction q labels exit l) + (base : Tape → List Bool) (state : State σ) : + (advance (TM2.step program))^[cleanupSteps base] + (some ⟨some (labels .query), state, base⟩) = + some ⟨exit, (state.1, none), cleanupTapes base⟩ := by + let t1 := Function.update base (2 : Tape) [] + let t2 := Function.update t1 (3 : Tape) [] + let t3 := Function.update t2 (4 : Tape) [] + let t4 := Function.update t3 (6 : Tape) [] + have h0 := MachineDrain.drainTrace (2 : Tape) (labels .query) (some (labels .scan)) + program (code .query) base (base 2) state.1 state.2 + have h1 := MachineDrain.drainTrace (3 : Tape) (labels .scan) (some (labels .rawReverse)) + program (code .scan) t1 (t1 3) state.1 none + have h2 := MachineDrain.drainTrace (4 : Tape) (labels .rawReverse) (some (labels .computedReverse)) + program (code .rawReverse) t2 (t2 4) state.1 none + have h3 := MachineDrain.drainTrace (6 : Tape) (labels .computedReverse) (some (labels .relation)) + program (code .computedReverse) t3 (t3 6) state.1 none + have h4 := MachineDrain.drainTrace (7 : Tape) (labels .relation) exit + program (code .relation) t4 (t4 7) state.1 none + simp only [Function.update_eq_self] at h0 h1 h2 h3 h4 + simp only [t1, t2, t3, t4, Function.update_of_ne (by decide : (3 : Tape) ≠ 2), + Function.update_of_ne (by decide : (4 : Tape) ≠ 3), + Function.update_of_ne (by decide : (4 : Tape) ≠ 2), + Function.update_of_ne (by decide : (6 : Tape) ≠ 4), + Function.update_of_ne (by decide : (6 : Tape) ≠ 3), + Function.update_of_ne (by decide : (6 : Tape) ≠ 2), + Function.update_of_ne (by decide : (7 : Tape) ≠ 6), + Function.update_of_ne (by decide : (7 : Tape) ≠ 4), + Function.update_of_ne (by decide : (7 : Tape) ≠ 3), + Function.update_of_ne (by decide : (7 : Tape) ≠ 2)] at h1 h2 h3 h4 + exact join_trace (join_trace (join_trace (join_trace h0 h1) h2) h3) h4 + +structure Input (t : Table) (e : Fin t.darts) (base : Tape → List Bool) : Prop + extends MachineRegularOriginalRow.Input t e base where + queryEmpty : base 2 = [] + scanEmpty : base 3 = [] + +theorem cleanup_frame (q : Nat) (t : Table) (e : Fin t.darts) + (base : Tape → List Bool) (input : Input t e base) : + cleanupTapes (MachineRegularOriginalRow.finalTapes q t e base) = + Function.update base 9 + (base 9 ++ encodeWords (MachineRegularOriginalRow.emittedWords q t e)) := by + funext k + fin_cases k <;> + simp [cleanupTapes, MachineRegularOriginalRow.finalTapes, + MachineRegularOriginalRow.affined, MachineRegularOriginalRow.copied, + MachineRegularOriginalRow.looked, MachineAffineLookup.finalTapes, + MachinePreservingLookup.finalTapes, MachineLookup.tapes, + MachineRegularOriginalRow.lookupTape, input.queryEmpty, input.scanEmpty, + input.reverseEmpty, input.computedEmpty, input.relationEmpty] + +theorem suffix_length_le (t : Table) (e : Fin t.darts) : + (encodeWords (MachineRegularOriginalRow.suffixWords t e)).length ≤ (tableBits t).length := by + have hlength : (tableBits t).length = + (encodeWords (MachineRegularOriginalRow.prefixWords t e)).length + + ((encodeWords (rowWords t.rows[e])).length + + (encodeWords (MachineRegularOriginalRow.suffixWords t e)).length) := by + rw [tableBits, MachineRegularOriginalRow.tableWords_at_row, + encodeWords_append, encodeWords_append, List.length_append, List.length_append] + omega + +theorem cleanupSteps_eq (q : Nat) (t : Table) (e : Fin t.darts) + (base : Tape → List Bool) (input : Input t e base) : + cleanupSteps (MachineRegularOriginalRow.finalTapes q t e base) = + (encodeWords (MachineRegularOriginalRow.suffixWords t e)).length + + (q + 2) * t.rows[e].reverseIndex.val + q + + (encodeWords (relationWords t.rows[e].relation)).length + 8 := by + have hquery : MachineRegularOriginalRow.finalTapes q t e base 2 = encodeWord 0 := by + simp only [MachineRegularOriginalRow.finalTapes, + Function.update_of_ne (by decide : (2 : Tape) ≠ 9), MachineRegularOriginalRow.affined, + Function.update_of_ne (by decide : (2 : Tape) ≠ 6), MachineRegularOriginalRow.copied, + Function.update_of_ne (by decide : (2 : Tape) ≠ 7), + Function.update_of_ne (by decide : (2 : Tape) ≠ 3)] + change MachineLookup.tapes (2 : Tape) 3 4 base + (encodeWord 0 ++ base 2) + (encodeWords ((GraphTables.tableWords t).drop (4098 * e.val + 3 + 1)) ++ base 3) + (encodeWord t.rows[e].reverseIndex.val ++ base 4) 2 = _ + rw [MachineLookup.tapes_index _ _ _ (by decide) (by decide), input.queryEmpty, + List.append_nil] + have hscan : MachineRegularOriginalRow.finalTapes q t e base 3 = + encodeWords (MachineRegularOriginalRow.suffixWords t e) := by + simp only [MachineRegularOriginalRow.finalTapes, + Function.update_of_ne (by decide : (3 : Tape) ≠ 9), MachineRegularOriginalRow.affined, + Function.update_of_ne (by decide : (3 : Tape) ≠ 6), MachineRegularOriginalRow.copied, + Function.update_of_ne (by decide : (3 : Tape) ≠ 7), Function.update_self, + input.scanEmpty, List.append_nil] + have hraw : MachineRegularOriginalRow.finalTapes q t e base 4 = + encodeWord t.rows[e].reverseIndex.val := by + simp only [MachineRegularOriginalRow.finalTapes, + Function.update_of_ne (by decide : (4 : Tape) ≠ 9), MachineRegularOriginalRow.affined, + Function.update_of_ne (by decide : (4 : Tape) ≠ 6), MachineRegularOriginalRow.copied_reverse, + input.reverseEmpty, List.append_nil] + have hcomputed : MachineRegularOriginalRow.finalTapes q t e base 6 = + encodeWord ((q + 1) * t.rows[e].reverseIndex.val + q) := by + simp only [MachineRegularOriginalRow.finalTapes, + Function.update_of_ne (by decide : (6 : Tape) ≠ 9), MachineRegularOriginalRow.affined_reverse, + input.computedEmpty, List.append_nil] + have hrelation : MachineRegularOriginalRow.finalTapes q t e base 7 = + encodeWords (relationWords t.rows[e].relation) := by + simp only [MachineRegularOriginalRow.finalTapes, + Function.update_of_ne (by decide : (7 : Tape) ≠ 9), MachineRegularOriginalRow.affined_relation, + input.relationEmpty, List.append_nil] + simp only [cleanupSteps, hquery, hscan, hraw, hcomputed, hrelation, encodeWord_length] + ring + +theorem cleanupSteps_le (q : Nat) (t : Table) (e : Fin t.darts) + (base : Tape → List Bool) (input : Input t e base) : + cleanupSteps (MachineRegularOriginalRow.finalTapes q t e base) ≤ + (q + 3) * (tableBits t).length + q + 8200 := by + rw [cleanupSteps_eq q t e base input] + have hsuffix := suffix_length_le t e + have htable := tableWords_length_le_bits t + have hr : t.rows[e].reverseIndex.val ≤ (tableBits t).length := by + have hrlt := t.rows[e].reverseIndex.isLt + omega + have hmul := Nat.mul_le_mul_left (q + 2) hr + have hrel := relationBits_length_le t.rows[e].relation + nlinarith + +def steps (q : Nat) (t : Table) (e : Fin t.darts) (base : Tape → List Bool) : Nat := + MachineRegularOriginalRow.steps q t e base + + cleanupSteps (MachineRegularOriginalRow.finalTapes q t e base) + +def timeBound (q inputLength outputLength : Nat) : Nat := + (5 * q + 20) * inputLength + 2 * outputLength + 5 * q + 40995 + +theorem steps_le (q : Nat) (t : Table) (e : Fin t.darts) + (base : Tape → List Bool) (input : Input t e base) : + steps q t e base ≤ timeBound q (tableBits t).length (base 9).length := by + have hrow := MachineRegularOriginalRow.steps_le q t e base + have hclean := cleanupSteps_le q t e base input + unfold steps timeBound MachineRegularOriginalRow.timeBound at * + nlinarith + +theorem traceAt {σ Λ : Type} (q : Nat) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt Alphabet Λ (State σ)) + (code : ∀ l, program (labels l) = instruction q labels exit l) + (t : Table) (e : Fin t.darts) (base : Tape → List Bool) (input : Input t e base) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[steps q t e base] + (some ⟨some (labels (.row (.lookup .seed))), + ((ambient, MachineRegularOriginalRow.zeroBuffer), register), base⟩) = + some ⟨exit, ((ambient, MachineRegularOriginalRow.zeroBuffer), none), + Function.update base 9 + (base 9 ++ encodeWords (MachineRegularOriginalRow.emittedWords q t e))⟩ := by + have row := MachineRegularOriginalRow.traceAt q (fun l => labels (.row l)) + (some (labels .query)) program (fun l => code (.row l)) t e base input.toInput ambient register + have clean := cleanupTraceAt q labels exit program code + (MachineRegularOriginalRow.finalTapes q t e base) + ((ambient, MachineRegularOriginalRow.zeroBuffer), none) + rw [cleanup_frame q t e base input] at clean + exact join_trace row clean + +def machine (q : Nat) : FinTM2 where + K := Tape + k₀ := 1 + k₁ := 9 + Γ := Alphabet + Λ := Label + main := .row (.lookup .seed) + σ := State Unit + initialState := (((), MachineRegularOriginalRow.zeroBuffer), none) + m := instruction q id none + +def machineInTime (H : BaseTable) (t : Table) (e : Fin t.darts) + (base : Tape → List Bool) (input : Input t e base) (register : Option Bool) : + StateTransition.EvalsToInTime (machine internalDegree).step + ⟨some (.row (.lookup .seed)), (((), MachineRegularOriginalRow.zeroBuffer), register), base⟩ + (some ⟨none, (((), MachineRegularOriginalRow.zeroBuffer), none), + Function.update base (9 : Tape) + (base (9 : Tape) ++ encodeWords (rowWords (MachineRegularOriginalRow.inheritedRow H t e)))⟩) + (timeBound internalDegree (tableBits t).length (base (9 : Tape)).length) where + steps := steps internalDegree t e base + evals_in_steps := by + change (advance (TM2.step (instruction internalDegree id none)))^[_] _ = _ + rw [MachineRegularOriginalRow.inheritedRow_words] + exact traceAt internalDegree id none (instruction internalDegree id none) + (fun _ => rfl) t e base input () register + steps_le_m := steps_le internalDegree t e base input + +end MinUncutGames.Foundations.Complexity.MachineRegularOriginalClean + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/UnboundedGraphMachine.lean b/lean/OAI/Computability/MinUncut/Machines/UnboundedGraphMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..442be215d4c37beedcef75aa3d9a323bc70da6b3 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/UnboundedGraphMachine.lean @@ -0,0 +1,68 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.GraphRenderMachine +import OAI.Computability.MinUncut.Estimates.CountedWordParser + +namespace OAI + +section +namespace MinUncut.Costed.Arena +open _root_.Turing _root_.OAI.Turing _root_.Turing.PartrecToTM2 _root_.OAI.Turing.PartrecToTM2 Turing.ToPartrec Polynomial +open MinUncutGames.Foundations.Complexity +noncomputable section + +def unboundedGraphMachine : FinTM2 := + MachineSequential.machine (codeMachine unboundedWordsCode) GraphCodec.machine id .cons + +lemma unboundedGraphMachine_finiteAlphabet (k : unboundedGraphMachine.K) : + Finite (unboundedGraphMachine.Γ k) := + sequential_finiteAlphabet _ _ _ _ (codeMachine_finiteAlphabet _) GraphCodec.finiteAlphabet k + +def unboundedGraphTime : Polynomial ℕ := C 10*unboundedWordsBound+10 + +def unboundedGraphPacked (c : Code) (v : List ℕ) : List ℕ := (initialState c v []).encode + +def unboundedGraphMachine_outputs {c : Code} {v : List ℕ} {B n k : ℕ} + {table : List Bool} {rest : List ℕ} + (hc : Runs c v (n::(table.map Bool.toNat++2::k::rest)) B) + (hl : (n::(table.map Bool.toNat++2::k::rest)).length≤B) : + TM2OutputsInTime unboundedGraphMachine (trList (unboundedGraphPacked c v)) + (some (MinUncutGames.BinaryEncoding.nameBits n++table++MinUncutGames.BinaryEncoding.nameBits k)) + (unboundedGraphTime.eval (magnitude (B::unboundedGraphPacked c v))) := by + apply Classical.choice + obtain ⟨h,hr,hm⟩ := unboundedWords_run hc hl [] + let junk := rest++(n::(table.map Bool.toNat++2::k::rest)).reverse++2::words h + have he' : (n::(table.map Bool.toNat++2::k::rest))++ + (n::(table.map Bool.toNat++2::k::rest)).reverse++2::words h= + n::(table.map Bool.toNat++2::k::junk) := by + simp only [List.cons_append,List.append_assoc,junk] + rw [he'] at hr hm + obtain ⟨t,ht,hr⟩ := hr + have h1 := hr.finiteMachine + have h2 := GraphCodec.outputsInTime n k table junk + have h2' : TM2OutputsInTime GraphCodec.machine + ((trList (n::(table.map Bool.toNat++2::k::junk))).map id) + (some (MinUncutGames.BinaryEncoding.nameBits n++table++MinUncutGames.BinaryEncoding.nameBits k)) + (2*bitsize (n::(table.map Bool.toNat++2::k::junk))+ + (MinUncutGames.BinaryEncoding.nameBits n++table++MinUncutGames.BinaryEncoding.nameBits k).length+2) := by + have input_eq : @List.map (GraphCodec.machine.Γ GraphCodec.machine.k₀) + (GraphCodec.machine.Γ GraphCodec.machine.k₀) id + (trList (n::(table.map Bool.toNat++2::k::junk))) = + trList (n::(table.map Bool.toNat++2::k::junk)) := List.map_id _ + simpa only [input_eq] using h2 + have hh := MachineSequential.execute (codeMachine unboundedWordsCode) GraphCodec.machine id Γ'.cons + _ _ _ _ _ h1 h2' + have hb := bitsize_le_magnitude (n::(table.map Bool.toNat++2::k::junk)) + have ho := GraphRegisters.codec_length_le n k table junk + refine ⟨⟨hh.toEvalsTo,hh.steps_le_m.trans ?_⟩⟩ + change t+1+2*((trList (n::(table.map Bool.toNat++2::k::junk))).length+1)+ + (2*bitsize (n::(table.map Bool.toNat++2::k::junk))+ + (MinUncutGames.BinaryEncoding.nameBits n++table++MinUncutGames.BinaryEncoding.nameBits k).length+2)≤_ + simp only [unboundedGraphPacked,unboundedGraphTime,eval_add,eval_mul,eval_C,eval_ofNat] + simp only [bitsize] at hb ⊢ + omega +end +end MinUncut.Costed.Arena + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/UniformAlphabet.lean b/lean/OAI/Computability/MinUncut/Machines/UniformAlphabet.lean new file mode 100644 index 0000000000000000000000000000000000000000..878d8fdaad69cb25eabe8370b2963f973936c830 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/UniformAlphabet.lean @@ -0,0 +1,102 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.UniformAlgebra +import OAI.Computability.MinUncut.Estimates.Bridge +import OAI.Computability.MinUncut.Search.UniformQuantifier + +namespace OAI + +section +noncomputable section +namespace MinUncut.Preprocess.Alphabet +open MinUncut.Inner MinUncut.Outer MinUncut.Outer.LocalTemplate +open MinUncutGames.Foundations.Hastad.SourceOccurrences +open UEncoding +open scoped BigOperators +variable {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)) +abbrev Slot (p : P) := Σj:Fin (t p),Fin (width (h p j)) +def axes := fin t ht +def positions : UEncoding P (fun _=>Fin 3) := fixed (Encoding.fin 3) +def slotPairs := (axes t ht).prod (positions (P:=P)) +def slotGood (p : P) (x : Fin (t p) × Fin 3) : Bool := !h p x.1 || decide (x.2=0) +omit [Primcodable P] in +lemma slotGood_iff (p : P) (x : Fin (t p) × Fin 3) : + slotGood t h p x=true ↔ x.2.valh p) := map_const hc + exact map_or (map_not (map_apply hh (map_fst _ _))) + (map_bool_eq (map_snd _ _) (map_const (Computable.const 0))) + +def slotEquiv (p : P) : Slot t h p ≃ {x:Fin (t p) × Fin 3 // slotGood t h p x=true} where + toFun x := ⟨(x.1,⟨x.2.val,by + have hx:=x.2.isLt + have hw:width (h p x.1)≤3 := by cases h p x.1 <;> decide + omega⟩),(slotGood_iff t h p _).mpr x.2.isLt⟩ + invFun x := ⟨x.val.1,⟨x.val.2.val,(slotGood_iff t h p x.val).mp x.property⟩⟩ + left_inv _ := rfl + right_inv _ := rfl + +def slots : UEncoding P (Slot t h) := + ((slotPairs t ht).restrict (slotGood t h) (map_slotGood t ht h hc)).ofEquiv (slotEquiv t h) +def labelEquiv (p : P) : LocalTemplate.Alphabet (h p) ≃ (Slot t h p → F₂) where + toFun x := fun j=>x j.1 j.2 + invFun x := fun j k=>x ⟨j,k⟩ + left_inv _ := rfl + right_inv _ := rfl + +def labels : UEncoding P (fun p=>LocalTemplate.Alphabet (h p)) := + ((slots t ht h hc).function (field P)).ofEquiv (labelEquiv t h) +def formsEquiv (p : P) : Forms (LocalTemplate.Alphabet (h p)) ≃ F₂ × (Slot t h p → F₂) := + (SampleEnumeration.formsCurryEquiv (Fin (t p)) (fun j=>Fin (width (h p j)))).trans + (SampleEnumeration.formsPiEquiv (Slot t h p)) +def forms : UEncoding P (fun p=>Forms (LocalTemplate.Alphabet (h p))) := + ((field P).prod ((slots t ht h hc).function (field P))).ofEquiv (formsEquiv t h) + +omit [Primcodable P] in +lemma forms_apply (p : P) (f : Forms (LocalTemplate.Alphabet (h p))) (x : LocalTemplate.Alphabet (h p)) : + f x=(formsEquiv t h p f).1+∑j:Slot t h p,(formsEquiv t h p f).2 j*labelEquiv t h p x j := by + let e:=SampleEnumeration.formsCurryEquiv (Fin (t p)) (fun j=>Fin (width (h p j))) + let f':=e f + have he : f x=f' (labelEquiv t h p x) := rfl + rw [he] + change f' (labelEquiv t h p x)=f' 0+∑j:Slot t h p, + (LinearEquiv.piRing F₂ F₂ (Slot t h p) F₂ f'.linear) j*labelEquiv t h p x j + have hl := congrArg (fun L : (Slot t h p → F₂) →ₗ[F₂] F₂=>L (labelEquiv t h p x)) + ((LinearEquiv.piRing F₂ F₂ (Slot t h p) F₂).symm_apply_apply f'.linear) + rw [LinearEquiv.piRing_symm_apply] at hl + have hd:=congrFun f'.decomp (labelEquiv t h p x) + change f' (labelEquiv t h p x)=f'.linear (labelEquiv t h p x)+f' 0 at hd + rw [hd,←hl] + simp only [smul_eq_mul,mul_comm] + exact add_comm _ _ + +lemma map_forms_apply : ((forms t ht h hc).prod (labels t ht h hc)).Map (field P) + (fun _ x=>x.1 x.2) := by + let s:=slots t ht h hc + let f:=forms t ht h hc + let a:=labels t ht h hc + let c:=f.prod a + have hf : c.Map ((field P).prod (s.function (field P))) (fun p x=>formsEquiv t h p x.1) := + (map_to _ (formsEquiv t h)).first + have ha : c.Map (s.function (field P)) (fun p x=>labelEquiv t h p x.2) := + (map_to _ (labelEquiv t h)).second + have hcoef:=map_comp hf (map_snd _ _) + have hv:=map_snd c s + have hs:=map_field_sum (map_field_mul (map_apply hcoef.first hv) (map_apply ha.first hv)) + apply (map_field_add (map_comp hf (map_fst _ _)) hs).ofEq + intro p x + exact (forms_apply t h p x.1 x.2).symm +end MinUncut.Preprocess.Alphabet + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Machines/UniformDemandAlphabet.lean b/lean/OAI/Computability/MinUncut/Machines/UniformDemandAlphabet.lean new file mode 100644 index 0000000000000000000000000000000000000000..e8ab0ecb0e0160d9b017a91e3ec2a8a8face3e06 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Machines/UniformDemandAlphabet.lean @@ -0,0 +1,137 @@ +import Mathlib +import OAI.Computability.MinUncut.Search.UniformQuantifier +import OAI.Computability.MinUncut.Encoding.SignatureEncoding +import OAI.Computability.MinUncut.Machines.UniformAlphabet + +namespace OAI + +section +noncomputable section +namespace MinUncut.Preprocess.Alphabet +open MinUncut.Inner MinUncut.Outer MinUncut.Outer.LocalTemplate MinUncut.FiniteProof +open MinUncutGames.Foundations.Hastad.SourceOccurrences UEncoding +attribute [local instance] Classical.propDecidable +variable {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)) +def triples : UEncoding P (fun _=>Triple) := (positions (P:=P)).function (field P) +def ambient := (axes t ht).function (triples (P:=P)) +def positionsList := (axes t ht).function (positions (P:=P)) +def rhs := (axes t ht).function (field P) +def equalities := (axes t ht).function ((positions (P:=P)).function ((positions (P:=P)).function bool)) +def signatures : UEncoding P (fun p=>Signature (Fin (t p))) := + ((rhs t ht).prod (equalities t ht)).ofEquiv (fun p=>signatureEquiv (t p)) +lemma signatures_encoding (p : P) : (signatures t ht).enc p=signatureEncoding (t p) := rfl +lemma ambient_encoding (p : P) : (ambient t ht).enc p=ambientEncoding (t p) := rfl +lemma map_rhs : (signatures t ht).Map (rhs t ht) (fun _ s=>s.rhs) := by + have hh := map_comp (map_to ((rhs t ht).prod (equalities t ht)) (fun p=>signatureEquiv (t p))) + (map_fst (rhs t ht) (equalities t ht)) + exact hh +lemma map_same : (signatures t ht).Map (equalities t ht) (fun _ s=>s.same) := by + have hh := map_comp (map_to ((rhs t ht).prod (equalities t ht)) (fun p=>signatureEquiv (t p))) + (map_snd (rhs t ht) (equalities t ht)) + exact hh +lemma map_origin : (signatures t ht).Map (ambient t ht) (fun _ s=>s.origin) := by + let c:=signatures t ht + let ax:=axes t ht + let po:=positions (P:=P) + have hh : ((c.prod ax).prod po).Map (field P) (fun _ x=>x.1.1.rhs x.1.2) := + map_apply (map_rhs t ht).first.first (map_snd c ax).first + exact map_lambda (map_lambda hh) +lemma map_zeroLabel : (fixed (P:=P) Encoding.unit).Map (labels t ht h hc) (fun _ _=>0) := by + let s:=slots t ht h hc + have hf : (fixed (P:=P) Encoding.unit).Map (s.function (field P)) (fun _ _ _=>0) := + map_lambda (map_const (Computable.const 0)) + have hh := map_comp hf (map_from (s.function (field P)) (labelEquiv t h)) + exact hh +lemma map_slotCoords : (slots t ht h hc).Map (slotPairs t ht) + (fun _ x=>((slotEquiv t h _ x).val)) := + map_comp (map_to _ (slotEquiv t h)) (map_restrict_val _ _ (map_slotGood t ht h hc)) +lemma projectSlot_apply (b : Bool) (pos : Fin 3) (x : Triple) (k : Fin (width b)) + (hk : k.val<3) : projectSlot b pos x k = if b then x pos else x ⟨k.val,hk⟩ := by + cases b <;> rfl +lemma map_slotAxis : (slots t ht h hc).Map (axes t ht) (fun _ x=>x.1) := by + have hh := map_comp (map_slotCoords t ht h hc) (map_fst (axes t ht) (positions (P:=P))) + exact hh +lemma map_slotPosition : (slots t ht h hc).Map (positions (P:=P)) + (fun p x=>(slotEquiv t h p x).val.2) := by + have hh := map_comp (map_slotCoords t ht h hc) (map_snd (axes t ht) (positions (P:=P))) + exact hh +lemma map_projectEval : (((positionsList t ht).prod (ambient t ht)).prod (slots t ht h hc)).Map + (field P) (fun p x=>project (h p) x.1.1 x.1.2 x.2.1 x.2.2) := by + let c:=(positionsList t ht).prod (ambient t ht) + let sl:=slots t ht h hc + let ax:=axes t ht + let po:=positions (P:=P) + have hi : (c.prod sl).Map ax (fun _ x=>x.2.1) := (map_slotAxis t ht h hc).second + have hk : (c.prod sl).Map po (fun p x=>(slotEquiv t h p x.2).val.2) := (map_slotPosition t ht h hc).second + have hpos : (c.prod sl).Map po (fun _ x=>x.1.1 x.2.1) := + map_apply (map_fst _ _).first hi + have hm : (c.prod sl).Map (ax.function bool) (fun p _=>h p) := map_const hc + have hh : (c.prod sl).Map bool (fun p x=>h p x.2.1) := map_apply hm hi + have hx : (c.prod sl).Map (triples (P:=P)) (fun _ x=>x.1.2 x.2.1) := + map_apply (map_snd _ _).first hi + apply (map_cond hh (map_apply hx hpos) (map_apply hx hk)).ofEq + intro p x + exact (projectSlot_apply _ _ _ _ _).symm +lemma map_project : ((positionsList t ht).prod (ambient t ht)).Map (labels t ht h hc) + (fun p x=>project (h p) x.1 x.2) := by + let c:=(positionsList t ht).prod (ambient t ht) + let sl:=slots t ht h hc + have hl : c.Map (sl.function (field P)) (fun p x y=>project (h p) x.1 x.2 y.1 y.2) := + map_lambda (map_projectEval t ht h hc) + have hout := map_comp hl (map_from (sl.function (field P)) (labelEquiv t h)) + exact hout.ofEq (by intro p x; rfl) +lemma map_decode : (ambient t ht).Map (labels t ht h hc) (fun p x=>decode (h p) x) := by + have hz : (ambient t ht).Map (positionsList t ht) (fun _ _ _=>0) := + map_lambda (map_const (Computable.const 0)) + have hh := map_comp (map_pair hz (map_id _)) (map_project t ht h hc) + exact hh +lemma map_valid : ((signatures t ht).prod (ambient t ht)).Map bool + (fun _ x=>decide (x.1.Valid x.2)) := by + classical + let c:=(signatures t ht).prod (ambient t ht) + let ax:=axes t ht + let po:=positions (P:=P) + let tr:=triples (P:=P) + have hx : (c.prod ax).Map tr (fun _ x=>x.1.2 x.2) := + map_apply (map_snd _ _).first (map_snd c ax) + have hr : (c.prod ax).Map (field P) (fun _ x=>x.1.1.rhs x.2) := + map_apply (map_rhs t ht).first.first (map_snd c ax) + have hpar : (c.prod ax).Map (field P) (fun _ x=>parity (x.1.2 x.2)) := + map_fixed_apply ((Encoding.fin 3).function fieldEncoding) fieldEncoding parity hx + have hsame : (((c.prod ax).prod po).prod po).Map bool + (fun _ x=>x.1.1.1.1.same x.1.1.2 x.1.2 x.2) := + map_apply (map_apply (map_apply (map_same t ht).first.first.first.first + (map_snd c ax).first.first) (map_snd (c.prod ax) po).first) (map_snd _ _) + have hp : (((c.prod ax).prod po).prod po).Map (field P) + (fun _ x=>x.1.1.1.2 x.1.1.2 x.1.2) := + map_apply hx.first.first (map_snd (c.prod ax) po).first + have hq : (((c.prod ax).prod po).prod po).Map (field P) + (fun _ x=>x.1.1.1.2 x.1.1.2 x.2) := + map_apply hx.first.first (map_snd _ _) + have he:=map_forall (map_forall (map_or (map_not hsame) (map_bool_eq hp hq))) + apply (map_forall (map_and (map_bool_eq hpar hr) he)).ofEq + intro p x + simp only [Signature.Valid,decide_eq_true_eq] + apply decide_eq_decide.mpr + simp only [Bool.and_eq_true, Bool.not_eq_true',Bool.or_eq_true,decide_eq_true_eq] + constructor + · intro H i + refine ⟨(H i).1,?_⟩ + intro j k hj + rcases (H i).2 j k with h|h + · simp [hj] at h + · exact h + · intro H i + refine ⟨(H i).1,?_⟩ + intro j k + by_cases hj:x.1.same i j k=true + · exact Or.inr ((H i).2 j k hj) + · exact Or.inl (Bool.eq_false_iff.mpr hj) +end MinUncut.Preprocess.Alphabet + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Main.lean b/lean/OAI/Computability/MinUncut/Main.lean new file mode 100644 index 0000000000000000000000000000000000000000..93eb304eb102be38880f3e94e57dfbcbc5ad9feb --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Main.lean @@ -0,0 +1,112 @@ +import Mathlib +import OAI.Computability.MinUncut.Encoding.PortTableEncoding +import OAI.Computability.MinUncut.Search.UniformRational +import OAI.Computability.MinUncut.Machines.GraphCoreMachine +import OAI.Computability.MinUncut.Encoding.BitOutputBound + +namespace OAI + +section +noncomputable section +namespace MinUncut.Uniform +open MinUncut.Costed MinUncut.Costed.Arena +open _root_.Turing _root_.OAI.Turing Turing.ToPartrec _root_.Turing.PartrecToTM2 _root_.OAI.Turing.PartrecToTM2 Polynomial +open MinUncutGames MinUncutGames.Foundations.Complexity +open MinUncutGames.BinaryEncoding +attribute [local irreducible] MinUncut.Preprocess.selectedInner MinUncut.Preprocess.selectedOuter +attribute [local irreducible] frontend frontendMachine program output initializerCode + +def framedFrontend : FinTM2 := + Framed.machine frontendMachine.tm frontendMachine.inputAlphabet frontendMachine.outputAlphabet + +def fullMachine : FinTM2 := + MachineSequential.machine framedFrontend coreMachine frontendMachine.outputAlphabet false +lemma full_finite (k : fullMachine.K) : Finite (fullMachine.Γ k) := + sequential_finiteAlphabet _ _ _ _ + (Framed.finiteAlphabet _ _ _ frontend_finite) core_finite k + +def frontSize : Polynomial ℕ := + X+C (Runtime.programPushBound frontendMachine.tm)*frontendMachine.time +lemma frontSize_bound (F : BinaryFormula.Formula) : + (MinUncutGames.Foundations.Complexity.formulaBits (frontend F).val).length≤ + frontSize.eval (formulaBits F).length := + Runtime.encodedOutputLength frontendMachine F + +def fullTime (K : ℕ) : Polynomial ℕ := + frontendMachine.time+C (4*(nameBits K).length+3)+C 2*frontSize+(coreTime K).comp frontSize + +def full_outputs (K : ℕ) (F : BinaryFormula.Formula) : + TM2OutputsInTime fullMachine + ((inputBits (K,F)).map frontendMachine.inputAlphabet.symm) + (some (output K F).bits) ((fullTime K).eval (formulaBits F).length) := by + let v:=formulaBits F + let w:=MinUncutGames.Foundations.Complexity.formulaBits (frontend F).val + let mid:=(nameBits K++w).map frontendMachine.outputAlphabet.symm + let h1:=Framed.execute frontendMachine.tm frontendMachine.inputAlphabet frontendMachine.outputAlphabet + K v w _ (frontendMachine.outputsFun F) + have handoff:mid.map frontendMachine.outputAlphabet=nameBits K++w:=by + simp only [mid,List.map_map,Function.comp_def,Equiv.apply_symm_apply] + exact List.map_id _ + let h2: TM2OutputsInTime coreMachine (mid.map frontendMachine.outputAlphabet) + (some (output K F).bits) ((coreTime K).eval w.length):=by + erw [handoff] + exact core_outputs K F + let hh:=MachineSequential.execute framedFrontend coreMachine frontendMachine.outputAlphabet false + _ _ _ _ _ h1 h2 + have hs:=frontSize_bound F + have hc:=evalNat_mono (coreTime K) hs + refine ⟨hh.toEvalsTo,hh.steps_le_m.trans ?_⟩ + change frontendMachine.time.eval v.length+2*(nameBits K).length+1+ + 2*(mid.length+1)+(coreTime K).eval w.length≤(fullTime K).eval v.length + simp only [mid,List.length_map,List.length_append,fullTime,eval_add,eval_C,eval_mul,eval_comp] + dsimp only [v,w] at * + omega + +def computation : TM2Computable inputBits Output.bits (fun p=>output p.1 p.2) where + tm := fullMachine + inputAlphabet := frontendMachine.inputAlphabet + outputAlphabet := Equiv.refl Bool + outputsFun p := by + change TM2Outputs fullMachine + ((inputBits (p.1,p.2)).map frontendMachine.inputAlphabet.symm) + (some ((output p.1 p.2).bits.map id)) + erw [List.map_id] + exact (full_outputs p.1 p.2).toEvalsTo + +def outputSize (K : ℕ) : Polynomial ℕ := + C 2*(C (nameBits K).length+X+fullTime K*C (Runtime.programPushBound fullMachine)) +lemma outputSize_bound (K : ℕ) (F : BinaryFormula.Formula) : + (output K F).vertices+(output K F).bits.length≤ + (outputSize K).eval (formulaBits F).length := by + have h:=graph_size_of_runtime fullMachine (output K F) + ((inputBits (K,F)).map frontendMachine.inputAlphabet.symm) + (output K F).bits ((fullTime K).eval (formulaBits F).length) rfl (full_outputs K F) + erw [List.length_map] at h + simpa only [inputBits,List.length_append,outputSize, + eval_mul,eval_add,eval_C,eval_X] using h + +def reduction : Reduction where + reduce := output + machine := computation + finiteAlphabet := full_finite + time := fullTime + runtime K F := by + change TM2OutputsInTime fullMachine + ((inputBits (K,F)).map frontendMachine.inputAlphabet.symm) + (some ((output K F).bits.map id)) ((fullTime K).eval (formulaBits F).length) + erw [List.map_id] + exact full_outputs K F + size := outputSize + output_size := outputSize_bound + yes K _ F hf := output_yes K F hf + no := output_no +end MinUncut.Uniform +namespace MinUncut + +theorem main : Nonempty Reduction := ⟨Uniform.reduction⟩ +end MinUncut + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Model.lean b/lean/OAI/Computability/MinUncut/Model.lean new file mode 100644 index 0000000000000000000000000000000000000000..408e6bb859e427b2cc7333047990e32a4910983d --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Model.lean @@ -0,0 +1,123 @@ +import Mathlib + +namespace OAI + + + + + + + + + + +namespace MinUncutGames.BinaryFormula + +structure Literal where + name : Nat + positive : Bool + deriving DecidableEq + +def Literal.eval (literal : Literal) (assignment : Nat → Bool) : Bool := + if literal.positive then assignment literal.name else !(assignment literal.name) + +abbrev Clause := Vector Literal 3 + +def Clause.eval (clause : Clause) (assignment : Nat → Bool) : Bool := + (clause[0].eval assignment || clause[1].eval assignment) || clause[2].eval assignment + +structure Formula where + clauses : List Clause + +def Formula.Satisfiable (F : Formula) : Prop := + ∃ assignment : Nat → Bool, ∀ clause ∈ F.clauses, clause.eval assignment = true + +end MinUncutGames.BinaryFormula + +namespace MinUncutGames.BinaryEncoding +open BinaryFormula + +def frame : List Bool → List Bool + | [] => [false] + | b :: bits => true :: b :: frame bits + +def nameBits (name : Nat) : List Bool := frame name.bits + +def literalBits (literal : Literal) : List Bool := + literal.positive :: nameBits literal.name + +def clauseBits (clause : Clause) : List Bool := + literalBits clause[0] ++ literalBits clause[1] ++ literalBits clause[2] + +def clausesBits : List Clause → List Bool + | [] => [false] + | clause :: clauses => true :: (clauseBits clause ++ clausesBits clauses) + +def formulaBits (formula : Formula) : List Bool := clausesBits formula.clauses + +end MinUncutGames.BinaryEncoding + +namespace MinUncut +open MinUncutGames.BinaryFormula MinUncutGames.BinaryEncoding + + + +structure Output where + vertices : ℕ + adjacent : Fin vertices → Fin vertices → Bool + symmetric : ∀ u v, adjacent u v = adjacent v u + loopless : ∀ u, adjacent u u = false + threshold : ℕ + threshold_pos : 1 ≤ threshold + + + +def Output.uncut (G : Output) (cut : Fin G.vertices → Bool) : ℕ := + (Finset.univ.filter fun uv : Fin G.vertices × Fin G.vertices => + uv.1 < uv.2 ∧ G.adjacent uv.1 uv.2 = true ∧ cut uv.1 = cut uv.2).card + + + +noncomputable def Output.opt (G : Output) : ℕ := + (Finset.univ.image G.uncut).min' (by + exact Finset.image_nonempty.mpr Finset.univ_nonempty) + + + +def Output.bits (G : Output) : List Bool := + nameBits G.vertices ++ + ((List.finRange G.vertices).flatMap fun u => + (List.finRange G.vertices).map fun v => G.adjacent u v) ++ + nameBits G.threshold + + + +def inputBits (input : ℕ × Formula) : List Bool := + nameBits input.1 ++ formulaBits input.2 + + + + + +structure Reduction where + reduce : ℕ → Formula → Output + machine : Turing.TM2Computable inputBits Output.bits (fun p => reduce p.1 p.2) + finiteAlphabet : ∀ k : machine.tm.K, Finite (machine.tm.Γ k) + time : ℕ → Polynomial ℕ + runtime : ∀ K φ, + Turing.TM2OutputsInTime machine.tm + ((inputBits (K, φ)).map machine.inputAlphabet.symm) + (some (((reduce K φ).bits).map machine.outputAlphabet.symm)) + ((time K).eval (formulaBits φ).length) + size : ℕ → Polynomial ℕ + output_size : ∀ K φ, + (reduce K φ).vertices + (reduce K φ).bits.length ≤ + (size K).eval (formulaBits φ).length + yes : ∀ K, 2 ≤ K → ∀ φ, φ.Satisfiable → + (reduce K φ).opt ≤ (reduce K φ).threshold + no : ∀ K, 2 ≤ K → ∀ φ, ¬ φ.Satisfiable → + K * (reduce K φ).threshold < (reduce K φ).opt + +end MinUncut + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/AddressArithmetic.lean b/lean/OAI/Computability/MinUncut/PCP/AddressArithmetic.lean new file mode 100644 index 0000000000000000000000000000000000000000..8ad31a30462798a7e11fc7609b273468198236cb --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/AddressArithmetic.lean @@ -0,0 +1,435 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.ContextLoad +import OAI.Computability.MinUncut.Machines.MachineUnaryAdd + +namespace OAI + +namespace MinUncutGames.Foundations.Hastad.SourceAddressArithmetic + +open scoped BigOperators +open Target SourceContexts SourceOccurrences + +theorem variable_rank (F : Formula) (u : ℕ) (v : VariableContext F u) : + ((variableEncoding F u).code v).val = + ∑ t : Fin u, (v t).val * F.«variables» ^ t.val := rfl + +theorem clause_rank (F : Formula) (u : ℕ) (c : ClauseContext F u) : + ((clauseEncoding F u).code c).val = + ∑ t : Fin u, (c t).val * F.clauses.length ^ t.val := rfl + +theorem left_address (F : Formula) (u : ℕ) (v : VariableContext F u) (f : Cube (I u)) : + ((proofEncoding F u).code (.inl (v, f))).val = + (((iEncoding u).function Encoding.bool).code f).val + + 2 ^ (2 ^ u) * ((variableEncoding F u).code v).val := rfl + +theorem right_address (F : Formula) (u : ℕ) (c : ClauseContext F u) (g : Cube (J u)) : + ((proofEncoding F u).code (.inr (.inl (c, g)))).val = + F.«variables» ^ u * 2 ^ (2 ^ u) + + ((((jEncoding u).function Encoding.bool).code g).val + + 2 ^ (8 ^ u) * ((clauseEncoding F u).code c).val) := rfl + +theorem dummy_address (F : Formula) (u : ℕ) : + (dummyIndex F u).val = + F.«variables» ^ u * 2 ^ (2 ^ u) + F.clauses.length ^ u * 2 ^ (8 ^ u) := by + change F.«variables» ^ u * 2 ^ (2 ^ u) + + (F.clauses.length ^ u * 2 ^ (8 ^ u) + 0) = _ + omega + +theorem left_address_radix (F : Formula) (u : ℕ) + (v : VariableContext F u) (f : Cube (I u)) : + ((proofEncoding F u).code (.inl (v, f))).val = + (((iEncoding u).function Encoding.bool).code f).val + + 2 ^ (2 ^ u) * ∑ t : Fin u, (v t).val * F.«variables» ^ t.val := by + rw [left_address, variable_rank] + +theorem right_address_radix (F : Formula) (u : ℕ) + (c : ClauseContext F u) (g : Cube (J u)) : + ((proofEncoding F u).code (.inr (.inl (c, g)))).val = + F.«variables» ^ u * 2 ^ (2 ^ u) + + ((((jEncoding u).function Encoding.bool).code g).val + + 2 ^ (8 ^ u) * ∑ t : Fin u, (c t).val * F.clauses.length ^ t.val) := by + rw [right_address, clause_rank] + +theorem nBits_eq_dummy_succ (F : Formula) (u : ℕ) : + nBits F u = (dummyIndex F u).val + 1 := by + rw [dummy_address, nBits_eq] + omega + +end MinUncutGames.Foundations.Hastad.SourceAddressArithmetic + +namespace MinUncutGames.Foundations.Hastad.SourceRankPhase + +open Turing Complexity +open scoped BigOperators +open Target SourceContexts SourceOccurrences SourceAddressArithmetic + +def rank {width : Nat} (radix : Nat) (digits : Fin width → Nat) : Nat := + ∑ i : Fin width, digits i * radix ^ i.val + +def reverseDigits {width : Nat} (digits : Fin width → Nat) (i : Nat) : Nat := + if h : i < width then digits (Fin.rev ⟨i, h⟩) else 0 + +@[simp] theorem reverseDigits_apply {width : Nat} (digits : Fin width → Nat) (i : Fin width) : + reverseDigits digits i.val = digits i.rev := by + simp [reverseDigits, i.isLt] + +theorem horner_value_sum (radix : Nat) (digits : Nat → Nat) (n : Nat) : + MachineHorner.value radix digits n = + ∑ i ∈ Finset.range n, digits i * radix ^ (n - 1 - i) := by + induction n with + | zero => simp [MachineHorner.value] + | succ n ih => + rw [MachineHorner.value, ih, Finset.sum_range_succ, Finset.mul_sum] + simp only [Nat.add_sub_cancel, Nat.sub_self, pow_zero, Nat.mul_one] + congr 1 + apply Finset.sum_congr rfl + intro i hi + have hi' := Finset.mem_range.mp hi + rw [show n - i = (n - 1 - i) + 1 by omega, pow_succ] + ac_rfl + +theorem horner_reverse_eq_rank {width : Nat} (radix : Nat) (digits : Fin width → Nat) : + MachineHorner.value radix (reverseDigits digits) width = rank radix digits := by + rw [horner_value_sum, Finset.sum_range] + calc + (∑ i : Fin width, reverseDigits digits i.val * radix ^ (width - 1 - i.val)) = + ∑ i : Fin width, digits i.rev * radix ^ i.rev.val := by + apply Finset.sum_congr rfl + intro i _ + rw [reverseDigits_apply] + have he : width - 1 - i.val = i.rev.val := by + simp only [Fin.rev] + omega + rw [he] + _ = rank radix digits := by + simpa only [rank, Fin.revPerm_apply] using + Equiv.sum_comp (Fin.revPerm (n := width)) (fun i => digits i * radix ^ i.val) + +variable {K Λ σ : Type} {width : Nat} + +def reverseSlots (slots : MachineHorner.Layout width ↪ K) : MachineHorner.Layout width ↪ K := + (Equiv.sumCongr (Equiv.refl (Fin 6)) (Fin.revPerm (n := width))).toEmbedding.trans slots + +@[simp] theorem reverseSlots_control (slots : MachineHorner.Layout width ↪ K) (i : Fin 6) : + reverseSlots slots (.inl i) = slots (.inl i) := rfl + +@[simp] theorem reverseSlots_digit (slots : MachineHorner.Layout width ↪ K) (i : Fin width) : + reverseSlots slots (.inr i) = slots (.inr i.rev) := rfl + +variable [DecidableEq K] + +omit [DecidableEq K] in +theorem clean_reverseSlots (slots : MachineHorner.Layout width ↪ K) (base : K → List Bool) + (clean : MachineHorner.Clean slots base) : MachineHorner.Clean (reverseSlots slots) base where + accA := by simpa only [reverseSlots_control] using clean.accA + accB := by simpa only [reverseSlots_control] using clean.accB + counter := by simpa only [reverseSlots_control] using clean.counter + scratch := by simpa only [reverseSlots_control] using clean.scratch + +def statement (slots : MachineHorner.Layout width ↪ K) + (labels : MachineHorner.Label width → Λ) (exit : Option Λ) : + MachineHorner.Label width → TM2.Stmt (fun _ : K => Bool) Λ (MachineHorner.State σ) := + MachineHorner.statement (reverseSlots slots) labels exit + +def program (slots : MachineHorner.Layout width ↪ K) : + MachineHorner.Label width → TM2.Stmt (fun _ : K => Bool) + (MachineHorner.Label width) (MachineHorner.State σ) := + statement slots id none + +theorem rankTrace (slots : MachineHorner.Layout width ↪ K) + (labels : MachineHorner.Label width → Λ) (exit : Option Λ) + (p : Λ → TM2.Stmt (fun _ : K => Bool) Λ (MachineHorner.State σ)) + (atLabels : ∀ label, p (labels label) = statement slots labels exit label) + (base : K → List Bool) (radix : Nat) (digits : Fin width → Nat) + (operandRadix : base (slots (.inl 0)) = encodeWord radix) + (operandDigits : ∀ i, base (slots (.inr i)) = encodeWord (digits i)) + (clean : MachineHorner.Clean slots base) (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step p))^[ + MachineHorner.steps radix (reverseDigits digits) width] + (some ⟨some (labels .start), ((ambient, ()), register), base⟩) = + some ⟨exit, ((ambient, ()), none), MachineHorner.resultTapes slots base (rank radix digits)⟩ := by + have h := MachineHorner.hornerTrace (reverseSlots slots) labels exit p atLabels base radix + (reverseDigits digits) operandRadix + (fun i => by simpa only [reverseSlots_digit, reverseDigits_apply] using operandDigits i.rev) + (clean_reverseSlots slots base clean) ambient register + rw [horner_reverse_eq_rank] at h + simpa only [MachineHorner.resultTapes, reverseSlots_control] using h + +def rankInTime (slots : MachineHorner.Layout width ↪ K) + (labels : MachineHorner.Label width → Λ) (exit : Option Λ) + (p : Λ → TM2.Stmt (fun _ : K => Bool) Λ (MachineHorner.State σ)) + (atLabels : ∀ label, p (labels label) = statement slots labels exit label) + (base : K → List Bool) (radix : Nat) (digits : Fin width → Nat) + (operandRadix : base (slots (.inl 0)) = encodeWord radix) + (operandDigits : ∀ i, base (slots (.inr i)) = encodeWord (digits i)) + (clean : MachineHorner.Clean slots base) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step p) + ⟨some (labels .start), ((ambient, ()), register), base⟩ + (some ⟨exit, ((ambient, ()), none), MachineHorner.resultTapes slots base (rank radix digits)⟩) + (MachineHorner.steps radix (reverseDigits digits) width) where + steps := MachineHorner.steps radix (reverseDigits digits) width + evals_in_steps := rankTrace slots labels exit p atLabels base radix digits operandRadix + operandDigits clean ambient register + steps_le_m := Nat.le_refl _ + +def rankInPolynomialTime (slots : MachineHorner.Layout width ↪ K) + (labels : MachineHorner.Label width → Λ) (exit : Option Λ) + (p : Λ → TM2.Stmt (fun _ : K => Bool) Λ (MachineHorner.State σ)) + (atLabels : ∀ label, p (labels label) = statement slots labels exit label) + (base : K → List Bool) (radix : Nat) (digits : Fin width → Nat) + (operandRadix : base (slots (.inl 0)) = encodeWord radix) + (operandDigits : ∀ i, base (slots (.inr i)) = encodeWord (digits i)) + (clean : MachineHorner.Clean slots base) (ambient : σ) (register : Option Bool) + (magnitude : Nat) (radixBound : radix ≤ magnitude) (digitBound : ∀ i, digits i ≤ magnitude) : + StateTransition.EvalsToInTime (TM2.step p) + ⟨some (labels .start), ((ambient, ()), register), base⟩ + (some ⟨exit, ((ambient, ()), none), MachineHorner.resultTapes slots base (rank radix digits)⟩) + ((MachineHorner.timePolynomial width).eval magnitude) where + steps := MachineHorner.steps radix (reverseDigits digits) width + evals_in_steps := rankTrace slots labels exit p atLabels base radix digits operandRadix + operandDigits clean ambient register + steps_le_m := MachineHorner.steps_le_timePolynomial radix (reverseDigits digits) width magnitude + radixBound (fun i hi => by simpa only [reverseDigits, dite_eq_left hi] using digitBound (Fin.rev ⟨i, hi⟩)) + +def variableRankInTime (F : Formula) (u : Nat) (v : VariableContext F u) + (slots : MachineHorner.Layout u ↪ K) (labels : MachineHorner.Label u → Λ) (exit : Option Λ) + (p : Λ → TM2.Stmt (fun _ : K => Bool) Λ (MachineHorner.State σ)) + (atLabels : ∀ label, p (labels label) = statement slots labels exit label) + (base : K → List Bool) (operandRadix : base (slots (.inl 0)) = encodeWord F.«variables») + (operandDigits : ∀ i, base (slots (.inr i)) = encodeWord (v i).val) + (clean : MachineHorner.Clean slots base) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step p) + ⟨some (labels .start), ((ambient, ()), register), base⟩ + (some ⟨exit, ((ambient, ()), none), + MachineHorner.resultTapes slots base (((variableEncoding F u).code v).val)⟩) + ((MachineHorner.timePolynomial u).eval F.«variables») := by + have h := rankInPolynomialTime slots labels exit p atLabels base F.«variables» (fun i => (v i).val) + operandRadix operandDigits clean ambient register F.«variables» (Nat.le_refl _) (fun i => (v i).isLt.le) + simpa only [rank, ← variable_rank F u v] using h + +def clauseRankInTime (F : Formula) (u : Nat) (c : ClauseContext F u) + (slots : MachineHorner.Layout u ↪ K) (labels : MachineHorner.Label u → Λ) (exit : Option Λ) + (p : Λ → TM2.Stmt (fun _ : K => Bool) Λ (MachineHorner.State σ)) + (atLabels : ∀ label, p (labels label) = statement slots labels exit label) + (base : K → List Bool) (operandRadix : base (slots (.inl 0)) = encodeWord F.clauses.length) + (operandDigits : ∀ i, base (slots (.inr i)) = encodeWord (c i).val) + (clean : MachineHorner.Clean slots base) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step p) + ⟨some (labels .start), ((ambient, ()), register), base⟩ + (some ⟨exit, ((ambient, ()), none), + MachineHorner.resultTapes slots base (((clauseEncoding F u).code c).val)⟩) + ((MachineHorner.timePolynomial u).eval F.clauses.length) := by + have h := rankInPolynomialTime slots labels exit p atLabels base F.clauses.length (fun i => (c i).val) + operandRadix operandDigits clean ambient register F.clauses.length (Nat.le_refl _) (fun i => (c i).isLt.le) + simpa only [rank, ← clause_rank F u c] using h + +def programInTime (slots : MachineHorner.Layout width ↪ K) + (base : K → List Bool) (radix : Nat) (digits : Fin width → Nat) + (operandRadix : base (slots (.inl 0)) = encodeWord radix) + (operandDigits : ∀ i, base (slots (.inr i)) = encodeWord (digits i)) + (clean : MachineHorner.Clean slots base) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step (program (σ := σ) slots)) + ⟨some .start, ((ambient, ()), register), base⟩ + (some ⟨none, ((ambient, ()), none), MachineHorner.resultTapes slots base (rank radix digits)⟩) + (MachineHorner.steps radix (reverseDigits digits) width) := + rankInTime slots id none (program slots) (fun _ => rfl) base radix digits operandRadix + operandDigits clean ambient register + +def machine (width : Nat) : FinTM2 where + K := MachineHorner.Layout width + k₀ := .inl 0 + k₁ := .inl 3 + Γ _ := Bool + Λ := MachineHorner.Label width + main := .start + σ := MachineHorner.State Unit + initialState := (((), ()), none) + m := program (Function.Embedding.refl (MachineHorner.Layout width)) + +def machineInTime (width radix : Nat) (digits : Fin width → Nat) + (base : MachineHorner.Layout width → List Bool) + (operandRadix : base (.inl 0) = encodeWord radix) + (operandDigits : ∀ i, base (.inr i) = encodeWord (digits i)) + (clean : MachineHorner.Clean (Function.Embedding.refl _) base) (register : Option Bool) : + StateTransition.EvalsToInTime (machine width).step + ⟨some (MachineHorner.Label.start), (((), ()), register), base⟩ + (some ⟨none, (((), ()), none), + MachineHorner.resultTapes (Function.Embedding.refl _) base (rank radix digits)⟩) + (MachineHorner.steps radix (reverseDigits digits) width) := + programInTime (Function.Embedding.refl _) base radix digits operandRadix operandDigits clean () register + +variable {u : Nat} {Extra : Type} + +def clauseSlots (controls : Fin 6 ↪ Extra) : + MachineHorner.Layout u ↪ SourceContextLoad.Tape u Extra where + toFun + | .inl i => .extra (controls i) + | .inr i => .current i + inj' := by + intro a b h + cases a with + | inl a => + cases b with + | inl b => exact congrArg Sum.inl (controls.injective (SourceContextLoad.Tape.extra.inj h)) + | inr b => cases h + | inr a => + cases b with + | inl b => cases h + | inr b => exact congrArg Sum.inr (SourceContextLoad.Tape.current.inj h) + +def variableSlots (controls : Fin 6 ↪ Extra) (selected : SlotContext u) : + MachineHorner.Layout u ↪ SourceContextLoad.Tape u Extra where + toFun + | .inl i => .extra (controls i) + | .inr i => SourceContextLoad.variableField i (slotEncoding.code (selected i)) + inj' := by + intro a b h + cases a with + | inl a => + cases b with + | inl b => exact congrArg Sum.inl (controls.injective (SourceContextLoad.Tape.extra.inj h)) + | inr b => cases h + | inr a => + cases b with + | inl b => cases h + | inr b => exact congrArg Sum.inr (SourceContextLoad.Tape.field.inj h).1 + +@[simp] theorem clauseSlots_control (controls : Fin 6 ↪ Extra) (i : Fin 6) : + clauseSlots (u := u) controls (.inl i) = .extra (controls i) := rfl + +@[simp] theorem clauseSlots_digit (controls : Fin 6 ↪ Extra) (i : Fin u) : + clauseSlots controls (.inr i) = .current i := rfl + +@[simp] theorem variableSlots_control (controls : Fin 6 ↪ Extra) (selected : SlotContext u) (i : Fin 6) : + variableSlots controls selected (.inl i) = .extra (controls i) := rfl + +@[simp] theorem variableSlots_digit (controls : Fin 6 ↪ Extra) (selected : SlotContext u) (i : Fin u) : + variableSlots controls selected (.inr i) = + SourceContextLoad.variableField i (slotEncoding.code (selected i)) := rfl + +theorem selectedDigits_loaded (F : Formula) (c : ClauseContext F u) (selected : SlotContext u) + (controls : Fin 6 ↪ Extra) (base : SourceContextLoad.Tape u Extra → List Bool) + (empty : ∀ i, base (SourceContextLoad.variableField i (slotEncoding.code (selected i))) = []) + (i : Fin u) : + SourceContextLoad.stageTapes F c base u (variableSlots controls selected (.inr i)) = + encodeWord (sampledVariables F c selected i).val := by + rw [variableSlots_digit] + erw [SourceContextLoad.output_variable, empty i, List.append_nil] + congr 1 + cases hs : selected i <;> simp [sampledVariables, PCP.nameAt, PCP.clauseAt, slotEncoding, hs] <;> rfl + +end MinUncutGames.Foundations.Hastad.SourceRankPhase + +namespace MinUncutGames.Foundations.Hastad.SourceAddressDescriptors + +open Target SourceContexts SourceOccurrences SourceLocalEquation SourceLocalSignature +open SourceAddressArithmetic +open MinUncutGames.Reduction.CloneGap + +abbrev Descriptor := Fin 3 × ℕ + +def descriptor (u : ℕ) : LocalKey u → Descriptor + | .inl f => (0, (((iEncoding u).function Encoding.bool).code f).val) + | .inr (.inl g) => (1, (((jEncoding u).function Encoding.bool).code g).val) + | .inr (.inr _) => (2, 0) + +def baseValue (F : Formula) (u : ℕ) (c : ClauseContext F u) + (v : VariableContext F u) (side : Fin 3) : ℕ := + if side = 0 then 2 ^ (2 ^ u) * ((variableEncoding F u).code v).val + else if side = 1 then F.«variables» ^ u * 2 ^ (2 ^ u) + + 2 ^ (8 ^ u) * ((clauseEncoding F u).code c).val + else F.«variables» ^ u * 2 ^ (2 ^ u) + F.clauses.length ^ u * 2 ^ (8 ^ u) + +def realize (base : Fin 3 → ℕ) (d : Descriptor) : ℕ := d.2 + base d.1 + +def words (base : Fin 3 → ℕ) (e : Equation Descriptor) : List ℕ := + [realize base e.first, realize base e.second, realize base e.third, + if e.rhs then 1 else 0] + +theorem realize_descriptor (F : Formula) (u : ℕ) (c : ClauseContext F u) + (v : VariableContext F u) (key : LocalKey u) : + realize (baseValue F u c v) (descriptor u key) = (addressMap F u c v key).val := by + cases key with + | inl f => + simpa [realize, descriptor, baseValue, addressMap] using + (left_address F u v f).symm + | inr key => + cases key with + | inl g => + simp [realize, descriptor, baseValue, addressMap, right_address] + omega + | inr _dummy => + simp only [realize, descriptor, baseValue, show (2 : Fin 3) ≠ 0 by decide, + show (2 : Fin 3) ≠ 1 by decide, ite_false, Nat.zero_add, addressMap, + dummy_address] + +theorem descriptor_offset_bound (u : ℕ) (key : LocalKey u) : + (descriptor u key).2 < 2 ^ (2 ^ u) + 2 ^ (8 ^ u) + 1 := by + cases key with + | inl f => + have h := (((iEncoding u).function Encoding.bool).code f).isLt + change _ < 2 ^ (2 ^ u) at h + change (((iEncoding u).function Encoding.bool).code f).val < _ + calc + _ < (2 ^ (2 ^ u) : ℕ) := h + _ ≤ 2 ^ (2 ^ u) + 2 ^ (8 ^ u) := Nat.le_add_right _ _ + _ ≤ _ := Nat.le_add_right _ _ + | inr key => + cases key with + | inl g => + have h := (((jEncoding u).function Encoding.bool).code g).isLt + change _ < 2 ^ (8 ^ u) at h + change (((jEncoding u).function Encoding.bool).code g).val < _ + calc + _ < (2 ^ (8 ^ u) : ℕ) := h + _ ≤ 2 ^ (2 ^ u) + 2 ^ (8 ^ u) := Nat.le_add_left _ _ + _ ≤ _ := Nat.le_add_right _ _ + | inr _dummy => simp [descriptor] + +theorem sourceEquation_numeric (F : Formula) (u D : ℕ) (p : SourceIndex F u D) : + mapEquation Fin.val (sourceEquation F u D p) = + mapEquation (realize (baseValue F u p.1.1 (sampledVariables F p.1.1 p.1.2))) + (mapEquation (descriptor u) (emit u D (ofContext F p.1.1 p.1.2, p.2))) := by + rw [sourceEquation_eq_map_emit, mapEquation_comp, mapEquation_comp] + congr 1 + funext key + exact (realize_descriptor F u p.1.1 (sampledVariables F p.1.1 p.1.2) key).symm + +theorem sourceEquation_words (F : Formula) (u D : ℕ) (p : SourceIndex F u D) : + MinUncutGames.Reduction.SourceEncoding.equationWords (sourceEquation F u D p) = + words (baseValue F u p.1.1 (sampledVariables F p.1.1 p.1.2)) + (mapEquation (descriptor u) (emit u D (ofContext F p.1.1 p.1.2, p.2))) := by + rw [sourceEquation_eq_map_emit] + simp only [MinUncutGames.Reduction.SourceEncoding.equationWords, words, mapEquation] + rw [realize_descriptor, realize_descriptor, realize_descriptor] + rfl + +theorem baseValue_lt (F : Formula) (u : ℕ) (c : ClauseContext F u) + (v : VariableContext F u) (side : Fin 3) : + baseValue F u c v side < nBits F u := by + have hside : side = 0 ∨ side = 1 ∨ side = 2 := by omega + rcases hside with rfl | rfl | rfl + · have h := (addressMap F u c v (.inl (fun _ => false))).isLt + rw [← realize_descriptor] at h + change _ + baseValue F u c v 0 < _ at h + exact (Nat.le_add_left _ _).trans_lt h + · have h := (addressMap F u c v (.inr (.inl (fun _ => false)))).isLt + rw [← realize_descriptor] at h + change _ + baseValue F u c v 1 < _ at h + exact (Nat.le_add_left _ _).trans_lt h + · have h := (addressMap F u c v (.inr (.inr ()))).isLt + rw [← realize_descriptor] at h + simpa only [realize, descriptor, Nat.zero_add] using h + +theorem equation_emit_steps_le (F : Formula) (u : ℕ) (c : ClauseContext F u) + (v : VariableContext F u) (e : Equation Descriptor) : + 2 * (baseValue F u c v e.first.1 + baseValue F u c v e.second.1 + + baseValue F u c v e.third.1) + 16 ≤ 6 * nBits F u + 16 := by + have h₁ := (baseValue_lt F u c v e.first.1).le + have h₂ := (baseValue_lt F u c v e.second.1).le + have h₃ := (baseValue_lt F u c v e.third.1).le + omega + +end MinUncutGames.Foundations.Hastad.SourceAddressDescriptors + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/Bounds.lean b/lean/OAI/Computability/MinUncut/PCP/Bounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..f04c248240bf5b6647c219c04da653d80fcef00d --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/Bounds.lean @@ -0,0 +1,172 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.Occurrences + +namespace OAI + +section +namespace MinUncutGames.Foundations.Hastad.SourceBounds + +open Target +open MinUncutGames.Reduction + +theorem formulaBits_length (F : Formula) : + (Complexity.formulaBits F).length = F.«variables» + F.clauses.length + 2 + + (Complexity.encodeWords (F.clauses.flatMap Complexity.clauseWords)).length := by + simp only [Complexity.formulaBits, Complexity.formulaWords, + Complexity.encodeWords_append, List.length_append, Complexity.encodeWords, + Complexity.encodeWord_length, List.length_nil] + omega + +theorem formulaBits_length_ge_variables (F : Formula) : + F.«variables» ≤ (Complexity.formulaBits F).length := by + rw [formulaBits_length] + omega + +theorem formulaBits_length_ge_clauses (F : Formula) : + F.clauses.length ≤ (Complexity.formulaBits F).length := by + rw [formulaBits_length] + omega + +theorem formulaBits_length_ge_two (F : Formula) : + 2 ≤ (Complexity.formulaBits F).length := by + rw [formulaBits_length] + omega + +def bitCountFormula (n m u : ℕ) : ℕ := + n ^ u * 2 ^ (2 ^ u) + m ^ u * 2 ^ (8 ^ u) + 1 + +def bitCoefficient (u : ℕ) : ℕ := 2 ^ (2 ^ u) + 2 ^ (8 ^ u) + 1 + +def testCoefficient (u D : ℕ) : ℕ := + 3 ^ u * 2 ^ (2 ^ u) * D ^ (8 ^ u) * 2 ^ (8 ^ u) + +def occurrenceCoefficient (u D : ℕ) : ℕ := testCoefficient u D + 1 + +theorem one_le_input_power (F : Formula) (u : ℕ) : + 1 ≤ (Complexity.formulaBits F).length ^ u := by + apply Nat.one_le_pow + have h := formulaBits_length_ge_two F + omega + +theorem bitCountFormula_le_input (F : Formula) (u : ℕ) : + bitCountFormula F.«variables» F.clauses.length u ≤ + bitCoefficient u * (Complexity.formulaBits F).length ^ u := by + have hn := Nat.pow_le_pow_left (formulaBits_length_ge_variables F) u + have hm := Nat.pow_le_pow_left (formulaBits_length_ge_clauses F) u + have hpos := one_le_input_power F u + unfold bitCountFormula bitCoefficient + calc + _ ≤ (Complexity.formulaBits F).length ^ u * 2 ^ (2 ^ u) + + (Complexity.formulaBits F).length ^ u * 2 ^ (8 ^ u) + + (Complexity.formulaBits F).length ^ u := + Nat.add_le_add + (Nat.add_le_add (Nat.mul_le_mul_right _ hn) (Nat.mul_le_mul_right _ hm)) hpos + _ = _ := by ring + +theorem testCountFormula_le_input (F : Formula) (u D : ℕ) : + (F.clauses.length * 3) ^ u * 2 ^ (2 ^ u) * D ^ (8 ^ u) * 2 ^ (8 ^ u) ≤ + testCoefficient u D * (Complexity.formulaBits F).length ^ u := by + have hm := Nat.pow_le_pow_left (formulaBits_length_ge_clauses F) u + calc + _ = testCoefficient u D * F.clauses.length ^ u := by + simp only [testCoefficient, Nat.mul_pow] + ring + _ ≤ _ := Nat.mul_le_mul_left _ hm + +theorem testCountFormula_add_one_le_input (F : Formula) (u D : ℕ) : + (F.clauses.length * 3) ^ u * 2 ^ (2 ^ u) * D ^ (8 ^ u) * 2 ^ (8 ^ u) + 1 ≤ + occurrenceCoefficient u D * (Complexity.formulaBits F).length ^ u := by + calc + _ ≤ testCoefficient u D * (Complexity.formulaBits F).length ^ u + + (Complexity.formulaBits F).length ^ u := + Nat.add_le_add (testCountFormula_le_input F u D) (one_le_input_power F u) + _ = _ := by simp only [occurrenceCoefficient, Nat.add_mul, Nat.one_mul] + +def sourceSizeBound (V E u L : ℕ) : ℕ := + V * L ^ u + E * L ^ u + 2 + E * L ^ u * (3 * (V * L ^ u) + 2) + +theorem sourceBits_length_le (input : SourceEncoding.Input) (V E u L : ℕ) + (hv : input.«variables» ≤ V * L ^ u) + (he : input.equations.length ≤ E * L ^ u) : + (SourceEncoding.inputBits input).length ≤ sourceSizeBound V E u L := by + apply (SourceEncoding.inputBits_length_le input).trans + unfold sourceSizeBound + exact Nat.add_le_add + (Nat.add_le_add_right (Nat.add_le_add hv he) 2) + (Nat.mul_le_mul he (Nat.add_le_add_right (Nat.mul_le_mul_left 3 hv) 2)) + +noncomputable def sourcePolynomial (u D : ℕ) : Polynomial ℕ := + let V := Polynomial.C (bitCoefficient u) * Polynomial.X ^ u + let E := Polynomial.C (occurrenceCoefficient u D) * Polynomial.X ^ u + V + E + Polynomial.C 2 + E * (Polynomial.C 3 * V + Polynomial.C 2) + +theorem sourcePolynomial_eval (u D L : ℕ) : + (sourcePolynomial u D).eval L = + sourceSizeBound (bitCoefficient u) (occurrenceCoefficient u D) u L := by + simp [sourcePolynomial, sourceSizeBound] + +open SourceOccurrences SourceContexts + +theorem card_testTape (u D : ℕ) : + Fintype.card (SourceTape.TestTape (I u) (J u) D) = + 2 ^ (2 ^ u) * (D ^ (8 ^ u) * 2 ^ (8 ^ u)) := by + rw [SourceTape.card_testTape, card_I, card_J] + +theorem testTapeEncoding_size (u D : ℕ) : + (SourceOccurrences.testTapeEncoding u D).size = + 2 ^ (2 ^ u) * (D ^ (8 ^ u) * 2 ^ (8 ^ u)) := rfl + +theorem card_sourceIndex (F : Formula) (u D : ℕ) : + Fintype.card (SourceIndex F u D) = + (F.clauses.length ^ u * 3 ^ u) * + (2 ^ (2 ^ u) * (D ^ (8 ^ u) * 2 ^ (8 ^ u))) := by + rw [(sourceIndexEncoding F u D).card_eq_size] + rfl + +theorem nBits_le_input (F : Formula) (u : ℕ) : + nBits F u ≤ bitCoefficient u * (Complexity.formulaBits F).length ^ u := by + have h := bitCountFormula_le_input F u + simpa only [nBits_eq, bitCountFormula, Nat.add_assoc] using h + +theorem rawSourceList_length_eq (F : Formula) (u D : ℕ) : + (rawSourceList F u D).length = testCoefficient u D * F.clauses.length ^ u := by + rw [rawSourceList_length] + unfold testCoefficient + ac_rfl + +theorem rawSourceList_length_le_input (F : Formula) (u D : ℕ) : + (rawSourceList F u D).length ≤ + testCoefficient u D * (Complexity.formulaBits F).length ^ u := by + rw [rawSourceList_length_eq] + exact Nat.mul_le_mul_left _ + (Nat.pow_le_pow_left (formulaBits_length_ge_clauses F) u) + +theorem sourceList_length_le_input (F : Formula) (u D : ℕ) : + (sourceList F u D).length ≤ + occurrenceCoefficient u D * (Complexity.formulaBits F).length ^ u := by + calc + _ ≤ (rawSourceList F u D).length + 1 := sourceList_length_le_raw_add_one F u D + _ ≤ testCoefficient u D * (Complexity.formulaBits F).length ^ u + + (Complexity.formulaBits F).length ^ u := + Nat.add_le_add (rawSourceList_length_le_input F u D) (one_le_input_power F u) + _ = _ := by simp only [occurrenceCoefficient, Nat.add_mul, Nat.one_mul] + +theorem sourceInput_bits_polynomial (F : Formula) (u D : ℕ) (hD : 0 < D) : + (SourceEncoding.inputBits (sourceInput F u D hD)).length ≤ + (sourcePolynomial u D).eval (Complexity.formulaBits F).length := by + rw [sourcePolynomial_eval] + exact sourceBits_length_le (sourceInput F u D hD) + (bitCoefficient u) (occurrenceCoefficient u D) u (Complexity.formulaBits F).length + (nBits_le_input F u) (sourceList_length_le_input F u D) + +theorem fixed_parameters_source_size (u D : ℕ) (hD : 0 < D) : + ∃ p : Polynomial ℕ, ∀ F : Formula, + (SourceEncoding.inputBits (sourceInput F u D hD)).length ≤ + p.eval (Complexity.formulaBits F).length := + ⟨sourcePolynomial u D, fun F => sourceInput_bits_polynomial F u D hD⟩ + +end MinUncutGames.Foundations.Hastad.SourceBounds + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/CayleySampling.lean b/lean/OAI/Computability/MinUncut/PCP/CayleySampling.lean new file mode 100644 index 0000000000000000000000000000000000000000..2130c24650be187289f1a79715a3a1a5e5f15835 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/CayleySampling.lean @@ -0,0 +1,746 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.DegreeReplacement + +namespace OAI + +section +noncomputable section + +namespace MinUncutGames.Foundations.PCP.CayleySampling + +open scoped BigOperators +open Finset +open MinUncutGames.Foundations.Hastad + +variable {V D : Type*} + +abbrev FalseFiber (χ : V → Bool) := {x : V // χ x = false} + +def falseRepresentative (χ : V → Bool) (flip : V → V) + (hχ : ∀ x, χ (flip x) = !(χ x)) (x : V) : FalseFiber χ := + if h : χ x = false then ⟨x, h⟩ + else ⟨flip x, by cases hx : χ x <;> simp_all⟩ + +def booleanSplitEquiv (χ : V → Bool) (flip : V → V) + (hflip : Function.Involutive flip) (hχ : ∀ x, χ (flip x) = !(χ x)) : + V ≃ Bool × FalseFiber χ where + toFun x := (χ x, falseRepresentative χ flip hχ x) + invFun p := if p.1 then flip p.2.val else p.2.val + left_inv x := by + cases hx : χ x <;> simp [falseRepresentative, hx] + exact hflip x + right_inv p := by + rcases p with ⟨b, x⟩ + apply Prod.ext + · cases b <;> simp [hχ, x.property] + · cases b <;> apply Subtype.ext <;> + simp [falseRepresentative, hχ, x.property] + exact hflip x.val + +@[simp] theorem booleanSplitEquiv_fst (χ : V → Bool) (flip : V → V) + (hflip : Function.Involutive flip) (hχ : ∀ x, χ (flip x) = !(χ x)) (x : V) : + (booleanSplitEquiv χ flip hflip hχ x).1 = χ x := rfl + +def sampleSplitEquiv (χ : V → Bool) (flip : V → V) + (hflip : Function.Involutive flip) (hχ : ∀ x, χ (flip x) = !(χ x)) : + (D → V) ≃ (D → Bool) × (D → FalseFiber χ) := + (Equiv.piCongrRight fun _ : D => booleanSplitEquiv χ flip hflip hχ).trans + (Equiv.arrowProdEquivProdArrow D (fun _ => Bool) (fun _ => FalseFiber χ)) + +@[simp] theorem sampleSplitEquiv_fst (χ : V → Bool) (flip : V → V) + (hflip : Function.Involutive flip) (hχ : ∀ x, χ (flip x) = !(χ x)) (g : D → V) : + (sampleSplitEquiv χ flip hflip hχ g).1 = fun d => χ (g d) := rfl + +theorem card_boolean_split [Fintype V] (χ : V → Bool) (flip : V → V) + (hflip : Function.Involutive flip) (hχ : ∀ x, χ (flip x) = !(χ x)) : + Fintype.card V = 2 * Fintype.card (FalseFiber χ) := by + simpa using Fintype.card_congr (booleanSplitEquiv χ flip hflip hχ) + +theorem expect_boolean_samples [Fintype V] [Nonempty V] [Fintype D] [DecidableEq D] + (χ : V → Bool) (flip : V → V) (hflip : Function.Involutive flip) + (hχ : ∀ x, χ (flip x) = !(χ x)) (F : (D → Bool) → ℝ) : + (𝔼 g : D → V, F (fun d => χ (g d))) = 𝔼 b : D → Bool, F b := by + classical + have : Nonempty (FalseFiber χ) := + ⟨falseRepresentative χ flip hχ (Classical.choice ‹Nonempty V›)⟩ + calc + (𝔼 g : D → V, F (fun d => χ (g d))) = + 𝔼 p : (D → Bool) × (D → FalseFiber χ), F p.1 := by + apply Fintype.expect_equiv (sampleSplitEquiv χ flip hflip hχ) + intro g + rfl + _ = 𝔼 b : D → Bool, F b := by + rw [← Finset.univ_product_univ, Finset.expect_product] + simp only [Fintype.expect_const] + +section Walsh + +variable {I : Type*} [Fintype I] [DecidableEq I] [Fintype D] [DecidableEq D] + +omit [DecidableEq I] in +theorem exists_true_of_ne_zero (s : Cube I) (hs : s ≠ fun _ => false) : + ∃ i, s i = true := by + by_contra h + apply hs + funext i + cases hi : s i + · rfl + · exact False.elim (h ⟨i, hi⟩) + +theorem expect_parity_samples (s : Cube I) (hs : s ≠ fun _ => false) + (F : (D → Bool) → ℝ) : + (𝔼 g : D → Cube I, F (fun d => AssignmentTester.parity s (g d))) = + 𝔼 b : D → Bool, F b := by + obtain ⟨i, hi⟩ := exists_true_of_ne_zero s hs + exact expect_boolean_samples (AssignmentTester.parity s) (AssignmentTester.flipAt i) + (AssignmentTester.flipAt_twice i) + (fun x => AssignmentTester.parity_flipAt s i x hi) F + +theorem expect_walsh_samples (s : Cube I) (hs : s ≠ fun _ => false) + (F : (D → ℝ) → ℝ) : + (𝔼 g : D → Cube I, F (fun d => walsh s (g d))) = + 𝔼 b : D → Bool, F (fun d => bitSign (b d)) := by + simpa only [AssignmentTester.bitSign_parity] using + expect_parity_samples s hs (fun b => F (fun d => bitSign (b d))) + +theorem expect_walsh_mean (s : Cube I) (hs : s ≠ fun _ => false) (F : ℝ → ℝ) : + (𝔼 g : D → Cube I, F (𝔼 d, walsh s (g d))) = + 𝔼 b : D → Bool, F (𝔼 d, bitSign (b d)) := + expect_walsh_samples s hs (fun z => F (𝔼 d, z d)) + +end Walsh + +end MinUncutGames.Foundations.PCP.CayleySampling + +end +end +section +namespace MinUncutGames.Foundations.PCP.CayleyTailCount + +open scoped BigOperators +open MinUncutGames.Foundations.Hastad (bitSign) + +variable {α : Type*} [DecidableEq α] + +def upperMasks (s : Finset α) (m : ℕ) : Finset (Finset α) := + s.powerset.filter fun t => 3 * m ≤ t.card + +def lowerMasks (s : Finset α) (m : ℕ) : Finset (Finset α) := + s.powerset.filter fun t => t.card ≤ m + +def badMasks (s : Finset α) (m : ℕ) : Finset (Finset α) := + lowerMasks s m ∪ upperMasks s m + +omit [DecidableEq α] in + +theorem upperMasks_weight (s : Finset α) (m : ℕ) (hcard : s.card = 4 * m) : + (upperMasks s m).card * 3 ^ (3 * m) ≤ 4 ^ (4 * m) := by + calc + _ = ∑ _t ∈ upperMasks s m, 3 ^ (3 * m) := by simp + _ ≤ ∑ t ∈ upperMasks s m, 3 ^ t.card := by + apply Finset.sum_le_sum + intro t ht + exact Nat.pow_le_pow_right (by decide) (Finset.mem_filter.mp ht).2 + _ ≤ ∑ t ∈ s.powerset, 3 ^ t.card := by + apply Finset.sum_le_sum_of_subset_of_nonneg + · exact Finset.filter_subset _ _ + · intro t _ _ + exact Nat.zero_le _ + _ = 4 ^ s.card := by + simpa using Finset.sum_pow_mul_eq_add_pow (3 : ℕ) 1 s + _ = 4 ^ (4 * m) := by rw [hcard] + +theorem lowerMasks_complement_image (s : Finset α) (m : ℕ) + (hcard : s.card = 4 * m) : + (lowerMasks s m).image (fun t => s \ t) = upperMasks s m := by + ext u + constructor + · intro hu + obtain ⟨t, ht, rfl⟩ := Finset.mem_image.mp hu + obtain ⟨hts, htlo⟩ := Finset.mem_filter.mp ht + have hsub := Finset.mem_powerset.mp hts + apply Finset.mem_filter.mpr + refine ⟨Finset.mem_powerset.mpr Finset.sdiff_subset, ?_⟩ + rw [Finset.card_sdiff_of_subset hsub, hcard] + omega + · intro hu + obtain ⟨hus, huhi⟩ := Finset.mem_filter.mp hu + have hsub := Finset.mem_powerset.mp hus + apply Finset.mem_image.mpr + refine ⟨s \ u, ?_, Finset.sdiff_sdiff_eq_self hsub⟩ + apply Finset.mem_filter.mpr + refine ⟨Finset.mem_powerset.mpr Finset.sdiff_subset, ?_⟩ + rw [Finset.card_sdiff_of_subset hsub, hcard] + omega + +theorem lowerMasks_card_eq_upperMasks (s : Finset α) (m : ℕ) + (hcard : s.card = 4 * m) : + (lowerMasks s m).card = (upperMasks s m).card := by + have hinj : Set.InjOn (fun t : Finset α => s \ t) (lowerMasks s m) := by + intro a ha b hb hab + have has := Finset.mem_powerset.mp (Finset.mem_filter.mp ha).1 + have hbs := Finset.mem_powerset.mp (Finset.mem_filter.mp hb).1 + have h := congrArg (fun t : Finset α => s \ t) hab + simpa only [Finset.sdiff_sdiff_eq_self has, Finset.sdiff_sdiff_eq_self hbs] using h + calc + _ = ((lowerMasks s m).image (fun t => s \ t)).card := + (Finset.card_image_of_injOn hinj).symm + _ = _ := congrArg Finset.card (lowerMasks_complement_image s m hcard) + +private theorem ratio_le_of_weight (c m : ℕ) + (h : c * 3 ^ (3 * m) ≤ 4 ^ (4 * m)) : + (c : ℝ) / 2 ^ (4 * m) ≤ (16 / 27 : ℝ) ^ m := by + have hc : (c : ℝ) * 3 ^ (3 * m) ≤ 4 ^ (4 * m) := by exact_mod_cast h + have h3 : 0 < (3 : ℝ) ^ (3 * m) := by positivity + have h2 : 0 < (2 : ℝ) ^ (4 * m) := by positivity + calc + _ ≤ ((4 : ℝ) ^ (4 * m) / 3 ^ (3 * m)) / 2 ^ (4 * m) := + div_le_div_of_nonneg_right ((le_div_iff₀ h3).mpr hc) h2.le + _ = _ := by + rw [pow_mul, pow_mul, pow_mul, ← div_pow, ← div_pow] + norm_num + +omit [DecidableEq α] in +theorem upperMasks_ratio_le (s : Finset α) (m : ℕ) (hcard : s.card = 4 * m) : + ((upperMasks s m).card : ℝ) / 2 ^ s.card ≤ (16 / 27 : ℝ) ^ m := by + rw [hcard] + exact ratio_le_of_weight _ m (upperMasks_weight s m hcard) + +theorem lowerMasks_ratio_le (s : Finset α) (m : ℕ) (hcard : s.card = 4 * m) : + ((lowerMasks s m).card : ℝ) / 2 ^ s.card ≤ (16 / 27 : ℝ) ^ m := by + rw [lowerMasks_card_eq_upperMasks s m hcard] + exact upperMasks_ratio_le s m hcard + +theorem badMasks_ratio_le_sharp (s : Finset α) (m : ℕ) (hcard : s.card = 4 * m) : + ((badMasks s m).card : ℝ) / 2 ^ s.card ≤ 2 * (16 / 27 : ℝ) ^ m := by + have hc : ((badMasks s m).card : ℝ) ≤ + (lowerMasks s m).card + (upperMasks s m).card := by + exact_mod_cast (Finset.card_union_le (lowerMasks s m) (upperMasks s m)) + have hpos : 0 < (2 : ℝ) ^ s.card := by positivity + calc + _ ≤ ((lowerMasks s m).card + (upperMasks s m).card : ℝ) / 2 ^ s.card := + div_le_div_of_nonneg_right hc hpos.le + _ = ((lowerMasks s m).card : ℝ) / 2 ^ s.card + + ((upperMasks s m).card : ℝ) / 2 ^ s.card := add_div _ _ _ + _ ≤ (16 / 27 : ℝ) ^ m + (16 / 27 : ℝ) ^ m := + add_le_add (lowerMasks_ratio_le s m hcard) (upperMasks_ratio_le s m hcard) + _ = _ := by ring + +theorem badMasks_ratio_le (s : Finset α) (m : ℕ) (hcard : s.card = 4 * m) : + ((badMasks s m).card : ℝ) / 2 ^ s.card ≤ 2 * (2 / 3 : ℝ) ^ m := by + apply (badMasks_ratio_le_sharp s m hcard).trans + exact mul_le_mul_of_nonneg_left + (pow_le_pow_left₀ (by norm_num) (by norm_num) m) (by norm_num) + +section Words + +variable {D : Type*} [Fintype D] + +def trueMask (word : D → Bool) : Finset D := + Finset.univ.filter fun i => word i = true + +def countTrue (word : D → Bool) : ℕ := (trueMask word).card + +def badWord (m : ℕ) (word : D → Bool) : Prop := + countTrue word ≤ m ∨ 3 * m ≤ countTrue word + +instance (m : ℕ) (word : D → Bool) : Decidable (badWord m word) := + inferInstanceAs (Decidable (countTrue word ≤ m ∨ 3 * m ≤ countTrue word)) + +theorem bitSign_mean_eq [Nonempty D] (word : D → Bool) : + (𝔼 i, bitSign (word i)) = + 1 - 2 * ((countTrue word : ℝ) / Fintype.card D) := by + have hsign (b : Bool) : bitSign b = 1 - 2 * (if b = true then (1 : ℝ) else 0) := by + cases b <;> norm_num [bitSign] + calc + _ = (𝔼 i : D, (1 - 2 * (if word i = true then (1 : ℝ) else 0))) := by + apply Finset.expect_congr rfl + intro i _ + exact hsign (word i) + _ = 1 - 2 * (𝔼 i, if word i = true then (1 : ℝ) else 0) := by + rw [Finset.expect_sub_distrib, ← Finset.mul_expect, Fintype.expect_const] + _ = _ := by + rw [Fintype.expect_eq_sum_div_card, Finset.sum_boole] + rfl + +theorem not_badWord_bias (m : ℕ) (hcard : Fintype.card D = 4 * m) (hm : 0 < m) + (word : D → Bool) (hword : ¬ badWord m word) : + |𝔼 i, bitSign (word i)| ≤ (1 / 2 : ℝ) := by + have hD : 0 < Fintype.card D := by rw [hcard]; omega + let : Nonempty D := Fintype.card_pos_iff.mp hD + have hlo : m < countTrue word := lt_of_not_ge (not_or.mp hword).1 + have hhi : countTrue word < 3 * m := lt_of_not_ge (not_or.mp hword).2 + have hmr : 0 < (m : ℝ) := by exact_mod_cast hm + have hlor : (m : ℝ) ≤ countTrue word := by exact_mod_cast hlo.le + have hhir : (countTrue word : ℝ) ≤ 3 * m := by exact_mod_cast hhi.le + have hden : 0 < 4 * (m : ℝ) := by positivity + have hratioLo : (1 / 4 : ℝ) ≤ (countTrue word : ℝ) / (4 * m) := + (le_div_iff₀ hden).mpr (by nlinarith) + have hratioHi : (countTrue word : ℝ) / (4 * m) ≤ (3 / 4 : ℝ) := + (div_le_iff₀ hden).mpr (by nlinarith) + rw [bitSign_mean_eq word, hcard] + simp only [Nat.cast_mul, Nat.cast_ofNat] + apply abs_le.mpr + constructor <;> linarith + +def wordMaskEquiv [DecidableEq D] : (D → Bool) ≃ Finset D where + toFun := trueMask + invFun s i := decide (i ∈ s) + left_inv word := by + funext i + cases h : word i <;> simp [trueMask, h] + right_inv s := by + ext i + simp [trueMask] + +theorem twoTail_probability [DecidableEq D] (m : ℕ) (hcard : Fintype.card D = 4 * m) : + (𝔼 word : D → Bool, if badWord m word then (1 : ℝ) else 0) ≤ + 2 * (2 / 3 : ℝ) ^ m := by + classical + have he : (𝔼 word : D → Bool, if badWord m word then (1 : ℝ) else 0) = + (𝔼 s : Finset D, if s.card ≤ m ∨ 3 * m ≤ s.card then (1 : ℝ) else 0) := by + apply Finset.expect_equiv (wordMaskEquiv (D := D)) + · intro word + simp + · intro word _ + rfl + have hs : (Finset.univ.filter fun s : Finset D => s.card ≤ m ∨ 3 * m ≤ s.card) = + badMasks (Finset.univ : Finset D) m := by + ext s + simp [badMasks, lowerMasks, upperMasks] + rw [he, Fintype.expect_eq_sum_div_card, Finset.sum_boole, hs, Fintype.card_finset] + simpa only [Nat.cast_pow, Nat.cast_ofNat, Finset.card_univ] using + badMasks_ratio_le (Finset.univ : Finset D) m (by simpa using hcard) + +end Words + +theorem union_bound_le_half (n m : ℕ) (hm : 3 * (n + 2) ≤ m) : + (2 : ℝ) ^ n * (2 * (2 / 3 : ℝ) ^ m) ≤ 1 / 2 := by + have hpow : (2 / 3 : ℝ) ^ m ≤ (2 / 3 : ℝ) ^ (3 * (n + 2)) := + pow_le_pow_of_le_one (by norm_num) (by norm_num) hm + have hbase : (2 / 3 : ℝ) ^ (3 * (n + 2)) ≤ (1 / 2 : ℝ) ^ (n + 2) := by + rw [pow_mul] + exact pow_le_pow_left₀ (by positivity) (by norm_num) (n + 2) + calc + _ ≤ (2 : ℝ) ^ n * (2 * (1 / 2 : ℝ) ^ (n + 2)) := by + exact mul_le_mul_of_nonneg_left + (mul_le_mul_of_nonneg_left (hpow.trans hbase) (by norm_num)) (by positivity) + _ = 1 / 2 := by + rw [pow_add, div_pow] + norm_num + field_simp + norm_num + +theorem fixed_parameters : 3 * (448 + 2) ≤ 16384 ∧ 4 * 16384 = 2 ^ 16 := by + norm_num + +theorem fixed_union_bound : + (2 : ℝ) ^ 448 * (2 * (2 / 3 : ℝ) ^ 16384) ≤ 1 / 2 := + union_bound_le_half 448 16384 fixed_parameters.1 + +theorem seventh_power_size : (2 : ℕ) ^ 448 = (((2 : ℕ) ^ 16) ^ 7) ^ 4 := by + rw [← pow_mul, ← pow_mul] + +theorem seventh_power_abs_le {a : ℝ} (ha : |a| ≤ 1 / 2) : |a ^ 7| ≤ 1 / 128 := by + rw [abs_pow] + calc + |a| ^ 7 ≤ (1 / 2 : ℝ) ^ 7 := pow_le_pow_left₀ (abs_nonneg a) ha 7 + _ = 1 / 128 := by norm_num + +end MinUncutGames.Foundations.PCP.CayleyTailCount + +end +section +namespace MinUncutGames.Foundations.PCP.SpectralReturn + +open PoweringWalks +open scoped BigOperators + +noncomputable section + +def mean {A : Type*} [Fintype A] (f : A → ℝ) : ℝ := Finset.univ.expect f + +def energy {A : Type*} [Fintype A] (f : A → ℝ) : ℝ := mean (fun x => (f x) ^ 2) + +def correlation {A : Type*} [Fintype A] (f g : A → ℝ) : ℝ := + mean (fun x => f x * g x) + +def averagingOperator {V D : Type*} [Fintype D] (G : PortGraph V D) + (f : V → ℝ) (v : V) : ℝ := Finset.univ.expect (fun d => f (G.rot (v, d)).1) + +def iterateOperator {V D : Type*} [Fintype D] (G : PortGraph V D) : + Nat → (V → ℝ) → (V → ℝ) + | 0, f => f + | n + 1, f => averagingOperator G (iterateOperator G n f) + +def edgeProfile {V D : Type*} [Fintype D] (bad : V × D → Bool) (v : V) : ℝ := + Finset.univ.expect (fun d => if bad (v, d) then 1 else 0) + +def edgeDensity {V D : Type*} [Fintype V] [Fintype D] (bad : V × D → Bool) : ℝ := + mean (edgeProfile bad) + +def markedStep {V D : Type*} [Fintype D] (G : PortGraph V D) + (bad : V × D → Bool) (f : V → ℝ) (v : V) : ℝ := + Finset.univ.expect (fun d => if bad (v, d) then f (G.rot (v, d)).1 else 0) + +def returnMass {V D : Type*} [Fintype V] [Fintype D] + (G : PortGraph V D) (bad : V × D → Bool) (gap : Nat) : ℝ := + mean (markedStep G bad (iterateOperator G gap (edgeProfile bad))) + +structure SpectralCertificate {V D : Type*} [Fintype V] [Fintype D] + (G : PortGraph V D) (lambda : ℝ) : Prop where + nonnegative : 0 ≤ lambda + lt_one : lambda < 1 + contraction : ∀ f : V → ℝ, mean f = 0 → + energy (averagingOperator G f) ≤ lambda ^ 2 * energy f + +section Averages + +variable {A B : Type*} [Fintype A] [Fintype B] + +theorem mean_eq_sum_div_card (f : A → ℝ) : + mean f = (∑ x, f x) / (Fintype.card A : ℝ) := + Fintype.expect_eq_sum_div_card f + +theorem mean_equiv (e : A ≃ B) (f : B → ℝ) : + mean (fun x => f (e x)) = mean f := + Fintype.expect_equiv e _ _ (fun _ => rfl) + +theorem mean_prod (f : A × B → ℝ) : + mean f = mean (fun a => mean (fun b => f (a, b))) := by + simpa only [mean, Finset.univ_product_univ] using + Finset.expect_product (Finset.univ : Finset A) (Finset.univ : Finset B) f + +@[simp] theorem mean_const [Nonempty A] (c : ℝ) : mean (fun _ : A => c) = c := + Fintype.expect_const c + +theorem mean_add (f g : A → ℝ) : + mean (fun x => f x + g x) = mean f + mean g := + Finset.expect_add_distrib _ f g + +theorem mean_sub (f g : A → ℝ) : + mean (fun x => f x - g x) = mean f - mean g := + Finset.expect_sub_distrib _ f g + +theorem mean_mul_left (c : ℝ) (f : A → ℝ) : + mean (fun x => c * f x) = c * mean f := + (Finset.mul_expect _ f c).symm + +theorem mean_mul_right (f : A → ℝ) (c : ℝ) : + mean (fun x => f x * c) = mean f * c := + (Finset.expect_mul _ f c).symm + +theorem mean_nonnegative (f : A → ℝ) (hf : ∀ x, 0 ≤ f x) : 0 ≤ mean f := + Finset.expect_nonneg (fun x _ => hf x) + +theorem mean_mono {f g : A → ℝ} (h : ∀ x, f x ≤ g x) : mean f ≤ mean g := + Finset.expect_le_expect (fun x _ => h x) + +theorem energy_nonnegative (f : A → ℝ) : 0 ≤ energy f := + mean_nonnegative _ (fun x => sq_nonneg (f x)) + +theorem correlation_sq_le (f g : A → ℝ) : + correlation f g ^ 2 ≤ energy f * energy g := + Finset.expect_mul_sq_le_sq_mul_sq Finset.univ f g + +theorem energy_sub_const [Nonempty A] (f : A → ℝ) (c : ℝ) : + energy (fun x => f x - c) = energy f - 2 * c * mean f + c ^ 2 := by + have h : (fun x => (f x - c) ^ 2) = + (fun x => (f x) ^ 2 - (2 * c) * f x + c ^ 2) := by + funext x + ring + unfold energy + rw [h, mean_add, mean_sub, mean_mul_left, mean_const] + +theorem correlation_sub_const [Nonempty A] (f g : A → ℝ) (c d : ℝ) : + correlation (fun x => f x - c) (fun x => g x - d) = + correlation f g - d * mean f - c * mean g + c * d := by + have h : (fun x => (f x - c) * (g x - d)) = + (fun x => f x * g x - d * f x - c * g x + c * d) := by + funext x + ring + unfold correlation + rw [h, mean_add, mean_sub, mean_sub, mean_mul_left, mean_mul_left, mean_const] + +end Averages + +section Graph + +variable {V D : Type*} [Fintype V] [Fintype D] [Nonempty V] [Nonempty D] + (G : PortGraph V D) + +omit [Nonempty V] in +theorem mean_operator (f : V → ℝ) : mean (averagingOperator G f) = mean f := by + calc + mean (averagingOperator G f) = mean (fun e : V × D => f (G.rot e).1) := + (mean_prod (fun e : V × D => f (G.rot e).1)).symm + _ = mean (fun e : V × D => f e.1) := mean_equiv G.rot (fun e => f e.1) + _ = mean (fun v : V => mean (fun _ : D => f v)) := + mean_prod (fun e : V × D => f e.1) + _ = mean f := by simp only [mean_const] + +omit [Fintype V] [Nonempty V] in +theorem operator_sub_const (f : V → ℝ) (c : ℝ) : + averagingOperator G (fun v => f v - c) = fun v => averagingOperator G f v - c := by + funext v + change mean (fun d => f (G.rot (v, d)).1 - c) = _ + rw [mean_sub, mean_const] + rfl + +omit [Nonempty V] in +theorem mean_iterate (n : Nat) (f : V → ℝ) : mean (iterateOperator G n f) = mean f := by + induction n with + | zero => rfl + | succ n ih => rw [iterateOperator, mean_operator, ih] + +omit [Fintype V] [Nonempty V] in +theorem iterate_sub_const (n : Nat) (f : V → ℝ) (c : ℝ) : + iterateOperator G n (fun v => f v - c) = fun v => iterateOperator G n f v - c := by + induction n with + | zero => rfl + | succ n ih => rw [iterateOperator, ih, operator_sub_const]; rfl + +omit [Nonempty V] [Nonempty D] in +theorem mean_markedStep (bad : V × D → Bool) + (reversal : ∀ e, bad (G.rot e) = bad e) (f : V → ℝ) : + mean (markedStep G bad f) = correlation (edgeProfile bad) f := by + calc + mean (markedStep G bad f) = + mean (fun e : V × D => if bad e then f (G.rot e).1 else 0) := by + exact (mean_prod (fun e : V × D => if bad e then f (G.rot e).1 else 0)).symm + _ = mean (fun e : V × D => if bad (G.rot e) + then f (G.rot (G.rot e)).1 else 0) := + (mean_equiv G.rot (fun e : V × D => if bad e then f (G.rot e).1 else 0)).symm + _ = mean (fun e : V × D => if bad e then f e.1 else 0) := by + congr 1 + funext e + rw [reversal e, G.rot_involutive e] + _ = mean (fun v => mean (fun d => if bad (v, d) then f v else 0)) := + mean_prod (fun e : V × D => if bad e then f e.1 else 0) + _ = correlation (edgeProfile bad) f := by + unfold correlation + congr 1 + funext v + have h : (fun d => if bad (v, d) then f v else 0) = + (fun d => (if bad (v, d) then (1 : ℝ) else 0) * f v) := by + funext d + cases bad (v, d) <;> simp + rw [h, mean_mul_right] + rfl + +omit [Nonempty V] [Nonempty D] in +theorem returnMass_eq_correlation (bad : V × D → Bool) + (reversal : ∀ e, bad (G.rot e) = bad e) (gap : Nat) : + returnMass G bad gap = correlation (edgeProfile bad) + (iterateOperator G gap (edgeProfile bad)) := + mean_markedStep G bad reversal _ + +omit [Nonempty V] in +theorem iterate_energy_bound (lambda : ℝ) (certificate : SpectralCertificate G lambda) + (f : V → ℝ) (hf : mean f = 0) (n : Nat) : + energy (iterateOperator G n f) ≤ (lambda ^ n) ^ 2 * energy f := by + induction n with + | zero => simp [iterateOperator] + | succ n ih => + calc + energy (iterateOperator G (n + 1) f) ≤ + lambda ^ 2 * energy (iterateOperator G n f) := + certificate.contraction _ ((mean_iterate G n f).trans hf) + _ ≤ lambda ^ 2 * ((lambda ^ n) ^ 2 * energy f) := + mul_le_mul_of_nonneg_left ih (sq_nonneg lambda) + _ = (lambda ^ (n + 1)) ^ 2 * energy f := by rw [pow_succ]; ring + +omit [Nonempty V] in +theorem zero_mean_correlation_bound (lambda : ℝ) + (certificate : SpectralCertificate G lambda) (f : V → ℝ) + (hf : mean f = 0) (n : Nat) : + correlation f (iterateOperator G n f) ≤ lambda ^ n * energy f := by + have hsq : correlation f (iterateOperator G n f) ^ 2 ≤ + (lambda ^ n * energy f) ^ 2 := by + calc + _ ≤ energy f * energy (iterateOperator G n f) := correlation_sq_le _ _ + _ ≤ energy f * ((lambda ^ n) ^ 2 * energy f) := + mul_le_mul_of_nonneg_left (iterate_energy_bound G lambda certificate f hf n) + (energy_nonnegative f) + _ = _ := by ring + exact le_of_sq_le_sq hsq + (mul_nonneg (pow_nonneg certificate.nonnegative n) (energy_nonnegative f)) + +theorem correlation_centered (f : V → ℝ) (n : Nat) : + correlation f (iterateOperator G n f) = mean f ^ 2 + + correlation (fun v => f v - mean f) + (iterateOperator G n (fun v => f v - mean f)) := by + rw [iterate_sub_const, correlation_sub_const, mean_iterate] + ring + +end Graph + +section Profiles + +variable {V D : Type*} [Fintype V] [Fintype D] [Nonempty V] [Nonempty D] + +omit [Nonempty V] [Nonempty D] in +theorem edgeDensity_eq_edge_mean (bad : V × D → Bool) : + edgeDensity bad = mean (fun e => if bad e then (1 : ℝ) else 0) := + (mean_prod (fun e : V × D => if bad e then (1 : ℝ) else 0)).symm + +omit [Nonempty V] [Nonempty D] in +theorem edgeDensity_eq_card (bad : V × D → Bool) : + edgeDensity bad = + ((Finset.univ.filter (fun e => bad e = true)).card : ℝ) / + (Fintype.card (V × D) : ℝ) := by + rw [edgeDensity_eq_edge_mean, mean_eq_sum_div_card] + simp only [Finset.sum_boole] + +omit [Fintype V] [Nonempty V] [Nonempty D] in +theorem edgeProfile_nonnegative (bad : V × D → Bool) (v : V) : 0 ≤ edgeProfile bad v := + mean_nonnegative _ (fun d => by cases bad (v, d) <;> norm_num) + +omit [Fintype V] [Nonempty V] in +theorem edgeProfile_le_one (bad : V × D → Bool) (v : V) : edgeProfile bad v ≤ 1 := by + change mean (fun d => if bad (v, d) then (1 : ℝ) else 0) ≤ 1 + calc + _ ≤ mean (fun _ : D => (1 : ℝ)) := mean_mono (fun d => by + cases bad (v, d) <;> norm_num) + _ = 1 := mean_const _ + +omit [Nonempty V] [Nonempty D] in +theorem edgeDensity_nonnegative (bad : V × D → Bool) : 0 ≤ edgeDensity bad := + mean_nonnegative _ (edgeProfile_nonnegative bad) + +theorem edgeDensity_le_one (bad : V × D → Bool) : edgeDensity bad ≤ 1 := by + calc + _ ≤ mean (fun _ : V => (1 : ℝ)) := mean_mono (edgeProfile_le_one bad) + _ = 1 := mean_const _ + +omit [Nonempty V] in +theorem edgeProfile_energy_le_density (bad : V × D → Bool) : + energy (edgeProfile bad) ≤ edgeDensity bad := + mean_mono (fun v => by + have h0 := edgeProfile_nonnegative bad v + have h1 := edgeProfile_le_one bad v + nlinarith) + +theorem edgeProfile_centered_energy (bad : V × D → Bool) : + energy (fun v => edgeProfile bad v - edgeDensity bad) ≤ + edgeDensity bad * (1 - edgeDensity bad) := by + rw [energy_sub_const] + have h := edgeProfile_energy_le_density bad + change energy (edgeProfile bad) - 2 * edgeDensity bad * edgeDensity bad + + edgeDensity bad ^ 2 ≤ _ + nlinarith + +theorem returnMass_le_sharp (G : PortGraph V D) (lambda : ℝ) + (certificate : SpectralCertificate G lambda) (bad : V × D → Bool) + (reversal : ∀ e, bad (G.rot e) = bad e) (gap : Nat) : + returnMass G bad gap ≤ edgeDensity bad ^ 2 + + lambda ^ gap * (edgeDensity bad * (1 - edgeDensity bad)) := by + rw [returnMass_eq_correlation G bad reversal, correlation_centered] + have hzero : mean (fun v => edgeProfile bad v - edgeDensity bad) = 0 := by + rw [mean_sub, mean_const] + simp only [edgeDensity, sub_self] + have hc := zero_mean_correlation_bound G lambda certificate + (fun v => edgeProfile bad v - edgeDensity bad) hzero gap + have hv := mul_le_mul_of_nonneg_left (edgeProfile_centered_energy bad) + (pow_nonneg certificate.nonnegative gap) + change edgeDensity bad ^ 2 + _ ≤ _ + exact add_le_add (le_refl _) (hc.trans hv) + +theorem returnMass_le (G : PortGraph V D) (lambda : ℝ) + (certificate : SpectralCertificate G lambda) (bad : V × D → Bool) + (reversal : ∀ e, bad (G.rot e) = bad e) (gap : Nat) : + returnMass G bad gap ≤ edgeDensity bad ^ 2 + edgeDensity bad * lambda ^ gap := by + have h := returnMass_le_sharp G lambda certificate bad reversal gap + have hvar : edgeDensity bad * (1 - edgeDensity bad) ≤ edgeDensity bad := by + nlinarith [sq_nonneg (edgeDensity bad)] + have hm := mul_le_mul_of_nonneg_left hvar (pow_nonneg certificate.nonnegative gap) + nlinarith + +theorem adjacent_returnMass_le (G : PortGraph V D) (lambda : ℝ) + (certificate : SpectralCertificate G lambda) (bad : V × D → Bool) + (reversal : ∀ e, bad (G.rot e) = bad e) : + returnMass G bad 0 ≤ edgeDensity bad := by + have h := returnMass_le_sharp G lambda certificate bad reversal 0 + norm_num at h + nlinarith + +end Profiles + +theorem geometric_sum_le (lambda : ℝ) (h0 : 0 ≤ lambda) (h1 : lambda < 1) (n : Nat) : + (∑ k ∈ Finset.range n, lambda ^ k) ≤ 1 / (1 - lambda) := by + have hsum : (∑ k ∈ Finset.range n, lambda ^ k) * (1 - lambda) = 1 - lambda ^ n := by + induction n with + | zero => simp + | succ n ih => rw [Finset.sum_range_succ, pow_succ]; nlinarith + have hden : 0 < 1 - lambda := by linarith + apply (le_div_iff₀ hden).2 + rw [hsum] + linarith [pow_nonneg h0 n] + +section ReturnSums + +variable {V D : Type*} [Fintype V] [Fintype D] [Nonempty V] [Nonempty D] + +theorem sum_returnMass_le (G : PortGraph V D) (lambda : ℝ) + (certificate : SpectralCertificate G lambda) (bad : V × D → Bool) + (reversal : ∀ e, bad (G.rot e) = bad e) (n : Nat) : + (∑ gap ∈ Finset.range n, returnMass G bad gap) ≤ + (n : ℝ) * edgeDensity bad ^ 2 + edgeDensity bad / (1 - lambda) := by + calc + _ ≤ ∑ gap ∈ Finset.range n, + (edgeDensity bad ^ 2 + edgeDensity bad * lambda ^ gap) := + Finset.sum_le_sum (fun gap _ => returnMass_le G lambda certificate bad reversal gap) + _ = (n : ℝ) * edgeDensity bad ^ 2 + + edgeDensity bad * (∑ gap ∈ Finset.range n, lambda ^ gap) := by + rw [Finset.sum_add_distrib, ← Finset.mul_sum] + simp only [Finset.sum_const, Finset.card_range, nsmul_eq_mul] + _ ≤ (n : ℝ) * edgeDensity bad ^ 2 + edgeDensity bad * (1 / (1 - lambda)) := + add_le_add (le_refl _) + (mul_le_mul_of_nonneg_left + (geometric_sum_le lambda certificate.nonnegative certificate.lt_one n) + (edgeDensity_nonnegative bad)) + _ = _ := by ring + +theorem triangular_returnMass_sum_le (G : PortGraph V D) (lambda : ℝ) + (certificate : SpectralCertificate G lambda) (bad : V × D → Bool) + (reversal : ∀ e, bad (G.rot e) = bad e) (n : Nat) : + (∑ j ∈ Finset.range n, ∑ gap ∈ Finset.range j, returnMass G bad gap) ≤ + ((n : ℝ) * ((n : ℝ) - 1) / 2) * edgeDensity bad ^ 2 + + (n : ℝ) * (edgeDensity bad / (1 - lambda)) := by + induction n with + | zero => simp + | succ n ih => + rw [Finset.sum_range_succ] + have hrow := sum_returnMass_le G lambda certificate bad reversal n + have h := add_le_add ih hrow + calc + _ ≤ ((n : ℝ) * ((n : ℝ) - 1) / 2) * edgeDensity bad ^ 2 + + (n : ℝ) * (edgeDensity bad / (1 - lambda)) + + ((n : ℝ) * edgeDensity bad ^ 2 + edgeDensity bad / (1 - lambda)) := h + _ = _ := by simp only [Nat.cast_add, Nat.cast_one]; ring + +theorem secondMoment_return_envelope (G : PortGraph V D) (lambda : ℝ) + (certificate : SpectralCertificate G lambda) (bad : V × D → Bool) + (reversal : ∀ e, bad (G.rot e) = bad e) (n : Nat) : + (n : ℝ) * edgeDensity bad + + 2 * (∑ j ∈ Finset.range n, ∑ gap ∈ Finset.range j, returnMass G bad gap) ≤ + (n : ℝ) * edgeDensity bad * + (1 + 2 / (1 - lambda) + ((n : ℝ) - 1) * edgeDensity bad) := by + calc + _ ≤ (n : ℝ) * edgeDensity bad + + 2 * (((n : ℝ) * ((n : ℝ) - 1) / 2) * edgeDensity bad ^ 2 + + (n : ℝ) * (edgeDensity bad / (1 - lambda))) := + add_le_add (le_refl _) + (mul_le_mul_of_nonneg_left + (triangular_returnMass_sum_le G lambda certificate bad reversal n) (by norm_num)) + _ = _ := by ring + +end ReturnSums + +end + +end MinUncutGames.Foundations.PCP.SpectralReturn + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/CayleySpectral.lean b/lean/OAI/Computability/MinUncut/PCP/CayleySpectral.lean new file mode 100644 index 0000000000000000000000000000000000000000..001b5d9e0389e31969d85d5dcffb0df6c51ed6c1 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/CayleySpectral.lean @@ -0,0 +1,839 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.CayleySampling + +namespace OAI + +noncomputable section + +namespace MinUncutGames.Foundations.PCP.CayleySpectral + +open scoped BigOperators +open Finset +open MinUncutGames.Foundations.Hastad +open PoweringWalks + +variable {I D : Type*} + +def zeroFrequency : Cube I := fun _ => false + +theorem cubeXor_cancel_right (x y : Cube I) : + cubeXor (cubeXor x y) y = x := by + funext i + cases hx : x i <;> cases hy : y i <;> simp [cubeXor, hx, hy] + +theorem cubeXor_assoc (x y z : Cube I) : + cubeXor (cubeXor x y) z = cubeXor x (cubeXor y z) := by + funext i + cases hx : x i <;> cases hy : y i <;> cases hz : z i <;> + simp [cubeXor, hx, hy, hz] + +@[simp] theorem cubeXor_zeroFrequency (x : Cube I) : + cubeXor x zeroFrequency = x := by + funext i + cases hx : x i <;> simp [cubeXor, zeroFrequency, hx] + +def xorTranslation (y : Cube I) : Cube I ≃ Cube I where + toFun x := cubeXor x y + invFun x := cubeXor x y + left_inv x := cubeXor_cancel_right x y + right_inv x := cubeXor_cancel_right x y + +def rotate (g : D → Cube I) (p : Cube I × D) : Cube I × D := + (cubeXor p.1 (g p.2), p.2) + +theorem rotate_involutive (g : D → Cube I) : Function.Involutive (rotate g) := by + rintro ⟨x, d⟩ + change (cubeXor (cubeXor x (g d)) (g d), d) = (x, d) + rw [cubeXor_cancel_right] + +def cayleyGraph (g : D → Cube I) : PortGraph (Cube I) D where + rot := + { toFun := rotate g + invFun := rotate g + left_inv := rotate_involutive g + right_inv := rotate_involutive g } + rot_involutive := rotate_involutive g + +@[simp] theorem cayleyGraph_rot (g : D → Cube I) (x : Cube I) (d : D) : + (cayleyGraph g).rot (x, d) = (cubeXor x (g d), d) := rfl + +def splitPortWord (n : Nat) : (Fin (n + 1) → D) ≃ D × (Fin n → D) where + toFun p := (p 0, fun j => p j.succ) + invFun z := Fin.cases z.1 z.2 + left_inv p := by + funext j + exact Fin.cases rfl (fun _ => rfl) j + right_inv z := rfl + +def powerGenerators (g : D → Cube I) : (n : Nat) → (Fin n → D) → Cube I + | 0, _ => zeroFrequency + | n + 1, p => cubeXor (g (p 0)) (powerGenerators g n (fun j => p j.succ)) + +theorem wordEnd_eq_powerGenerators (g : D → Cube I) (n : Nat) + (x : Cube I) (p : Fin n → D) : + wordEnd (cayleyGraph g) n x p = cubeXor x (powerGenerators g n p) := by + induction n generalizing x with + | zero => simp [wordEnd, powerGenerators] + | succ n ih => + change wordEnd (cayleyGraph g) n (cubeXor x (g (p 0))) (fun j => p j.succ) = + cubeXor x (cubeXor (g (p 0)) (powerGenerators g n (fun j => p j.succ))) + rw [ih, cubeXor_assoc] + + +variable [Fintype I] [DecidableEq I] [Fintype D] + +def cayleyAverage (g : D → Cube I) (f : Cube I → ℝ) (x : Cube I) : ℝ := + 𝔼 d, f ((cayleyGraph g).rot (x, d)).1 + +def eigenvalue (g : D → Cube I) (s : Cube I) : ℝ := + 𝔼 d, walsh s (g d) + +omit [Fintype I] [DecidableEq I] in +@[simp] theorem averagingOperator_cayleyGraph (g : D → Cube I) (f : Cube I → ℝ) : + SpectralReturn.averagingOperator (cayleyGraph g) f = cayleyAverage g f := rfl + +@[simp] theorem coefficient_zeroFrequency (f : Cube I → ℝ) : + coefficient f zeroFrequency = 𝔼 x, f x := by + simp [coefficient, zeroFrequency, walsh, bitSign] + +theorem coefficient_xorTranslation (f : Cube I → ℝ) (s v : Cube I) : + coefficient (fun x => f (cubeXor x v)) s = walsh s v * coefficient f s := by + calc + coefficient (fun x => f (cubeXor x v)) s = + 𝔼 x, f x * walsh s (cubeXor x v) := by + unfold coefficient + apply Fintype.expect_equiv (xorTranslation v) + intro x + change f (cubeXor x v) * walsh s x = + f (cubeXor x v) * walsh s (cubeXor (cubeXor x v) v) + rw [cubeXor_cancel_right] + _ = 𝔼 x, (f x * walsh s x) * walsh s v := by + apply Finset.expect_congr rfl + intro x _ + rw [walsh_xor] + ring + _ = coefficient f s * walsh s v := by + rw [← Finset.expect_mul] + rfl + _ = walsh s v * coefficient f s := mul_comm _ _ + +theorem cayleyAverage_walsh (g : D → Cube I) (s x : Cube I) : + cayleyAverage g (walsh s) x = eigenvalue g s * walsh s x := by + unfold cayleyAverage + simp only [cayleyGraph_rot, walsh_xor] + rw [← Finset.mul_expect] + rw [mul_comm] + rfl + +theorem coefficient_cayleyAverage (g : D → Cube I) (f : Cube I → ℝ) (s : Cube I) : + coefficient (cayleyAverage g f) s = eigenvalue g s * coefficient f s := by + calc + coefficient (cayleyAverage g f) s = + 𝔼 x, 𝔼 d, f (cubeXor x (g d)) * walsh s x := by + unfold coefficient cayleyAverage + simp only [cayleyGraph_rot, Finset.expect_mul] + _ = 𝔼 d, 𝔼 x, f (cubeXor x (g d)) * walsh s x := by + rw [Finset.expect_comm] + _ = 𝔼 d, walsh s (g d) * coefficient f s := by + apply Finset.expect_congr rfl + intro d _ + exact coefficient_xorTranslation f s (g d) + _ = eigenvalue g s * coefficient f s := by + rw [← Finset.expect_mul] + rfl + +theorem eigenvalue_powerGenerators (g : D → Cube I) (n : Nat) (s : Cube I) : + eigenvalue (powerGenerators g n) s = eigenvalue g s ^ n := by + induction n with + | zero => + let : Nonempty (Fin 0 → D) := ⟨fun i => Fin.elim0 i⟩ + simp [eigenvalue, powerGenerators, zeroFrequency, walsh, bitSign] + | succ n ih => + calc + eigenvalue (powerGenerators g (n + 1)) s = + 𝔼 z : D × (Fin n → D), + walsh s (cubeXor (g z.1) (powerGenerators g n z.2)) := by + unfold eigenvalue + apply Fintype.expect_equiv (splitPortWord n) + intro p + rfl + _ = 𝔼 d, 𝔼 p : Fin n → D, + walsh s (cubeXor (g d) (powerGenerators g n p)) := by + exact SpectralReturn.mean_prod _ + _ = eigenvalue g s * eigenvalue (powerGenerators g n) s := by + simp_rw [walsh_xor, ← Finset.mul_expect] + rw [← Finset.expect_mul] + rfl + _ = eigenvalue g s ^ (n + 1) := by + rw [ih, pow_succ, mul_comm] + +theorem power_port_card (n : Nat) : + Fintype.card (Fin n → D) = Fintype.card D ^ n := by + simp only [Fintype.card_fun, Fintype.card_fin] + +theorem seven_power_port_card : + Fintype.card (Fin 7 → Fin (2 ^ 16)) = (2 ^ 16) ^ 7 := by + simp only [Fintype.card_fun, Fintype.card_fin] + +theorem cayley_energy_contraction (g : D → Cube I) (lambda : ℝ) (_hlambda : 0 ≤ lambda) + (hbias : ∀ s : Cube I, s ≠ zeroFrequency → |eigenvalue g s| ≤ lambda) + (f : Cube I → ℝ) (hmean : (𝔼 x, f x) = 0) : + (𝔼 x, cayleyAverage g f x ^ 2) ≤ lambda ^ 2 * (𝔼 x, f x ^ 2) := by + classical + have hzero : coefficient f zeroFrequency = 0 := by + rw [coefficient_zeroFrequency] + exact hmean + calc + (𝔼 x, cayleyAverage g f x ^ 2) = + ∑ s, coefficient (cayleyAverage g f) s ^ 2 := (walsh_parseval _).symm + _ = ∑ s, (eigenvalue g s * coefficient f s) ^ 2 := by + simp only [coefficient_cayleyAverage] + _ ≤ ∑ s, lambda ^ 2 * coefficient f s ^ 2 := by + apply Finset.sum_le_sum + intro s _ + by_cases hs : s = zeroFrequency + · subst s + simp [hzero] + · have hb := hbias s hs + have hlo : -lambda ≤ eigenvalue g s := (abs_le.mp hb).1 + have hhi : eigenvalue g s ≤ lambda := (abs_le.mp hb).2 + have hprod : 0 ≤ (lambda - eigenvalue g s) * (lambda + eigenvalue g s) := + mul_nonneg (sub_nonneg.mpr hhi) (by linarith) + have hsq : eigenvalue g s ^ 2 ≤ lambda ^ 2 := by nlinarith + calc + (eigenvalue g s * coefficient f s) ^ 2 = + eigenvalue g s ^ 2 * coefficient f s ^ 2 := by rw [mul_pow] + _ ≤ lambda ^ 2 * coefficient f s ^ 2 := + mul_le_mul_of_nonneg_right hsq (sq_nonneg _) + _ = lambda ^ 2 * (𝔼 x, f x ^ 2) := by + rw [← Finset.mul_sum, walsh_parseval] + +theorem cayley_spectralCertificate (g : D → Cube I) (lambda : ℝ) + (hlambda : 0 ≤ lambda) (hlambdaone : lambda < 1) + (hbias : ∀ s : Cube I, s ≠ zeroFrequency → |eigenvalue g s| ≤ lambda) : + SpectralReturn.SpectralCertificate (cayleyGraph g) lambda where + nonnegative := hlambda + lt_one := hlambdaone + contraction := by + intro f hf + change (𝔼 x, cayleyAverage g f x ^ 2) ≤ lambda ^ 2 * (𝔼 x, f x ^ 2) + exact cayley_energy_contraction g lambda hlambda hbias f hf + +theorem power_eigenvalue_bound (g : D → Cube I) (lambda : ℝ) (hlambda : 0 ≤ lambda) + (hbias : ∀ s : Cube I, s ≠ zeroFrequency → |eigenvalue g s| ≤ lambda) + (n : Nat) (s : Cube I) (hs : s ≠ zeroFrequency) : + |eigenvalue (powerGenerators g n) s| ≤ lambda ^ n := by + rw [eigenvalue_powerGenerators, abs_pow] + induction n with + | zero => simp + | succ n ih => + rw [pow_succ, pow_succ] + exact mul_le_mul ih (hbias s hs) (abs_nonneg _) (pow_nonneg hlambda _) + +theorem sevenStep_halfCertificate (g : D → Cube I) + (hbias : ∀ s : Cube I, s ≠ zeroFrequency → |eigenvalue g s| ≤ (1 / 2 : ℝ)) : + SpectralReturn.SpectralCertificate (cayleyGraph (powerGenerators g 7)) + ((1 / 2 : ℝ) ^ 7) := by + apply cayley_spectralCertificate + · norm_num + · norm_num + · intro s hs + exact power_eigenvalue_bound g (1 / 2) (by norm_num) hbias 7 s hs + + +end MinUncutGames.Foundations.PCP.CayleySpectral + + +namespace MinUncutGames.Foundations.PCP.Expanders + +open scoped BigOperators +open MinUncutGames.Foundations.Hastad +open CayleySpectral + +abbrev Generators (n m : Nat) := Fin (4 * m) → Cube (Fin n) + +def badFrequency {n m : Nat} (g : Generators n m) (s : Cube (Fin n)) : ℝ := + if s = zeroFrequency then 0 else + if CayleyTailCount.badWord m (fun d => AssignmentTester.parity s (g d)) then 1 else 0 + +def badMass {n m : Nat} (g : Generators n m) : ℝ := + ∑ s : Cube (Fin n), badFrequency g s + +theorem badFrequency_nonnegative {n m : Nat} + (g : Generators n m) (s : Cube (Fin n)) : 0 ≤ badFrequency g s := by + unfold badFrequency + split_ifs <;> norm_num + +theorem mean_badFrequency_le {n m : Nat} (s : Cube (Fin n)) : + (𝔼 g : Generators n m, badFrequency g s) ≤ 2 * (2 / 3 : ℝ) ^ m := by + classical + by_cases hs : s = zeroFrequency + · simp only [badFrequency, ite_eq_left hs, Finset.expect_const_zero] + positivity + · have hs' : s ≠ (fun _ => false) := hs + simp only [badFrequency, ite_eq_right hs] + rw [CayleySampling.expect_parity_samples s hs' + (fun w : Fin (4 * m) → Bool => if CayleyTailCount.badWord m w then (1 : ℝ) else 0)] + exact CayleyTailCount.twoTail_probability m (by simp) + +theorem mean_badMass_le (n m : Nat) (hm : 3 * (n + 2) ≤ m) : + (𝔼 g : Generators n m, badMass g) ≤ 1 / 2 := by + calc + _ = ∑ s : Cube (Fin n), 𝔼 g : Generators n m, badFrequency g s := by + unfold badMass + rw [Finset.expect_sum_comm] + _ ≤ ∑ _s : Cube (Fin n), 2 * (2 / 3 : ℝ) ^ m := + Finset.sum_le_sum (fun s _ => mean_badFrequency_le s) + _ = (2 : ℝ) ^ n * (2 * (2 / 3 : ℝ) ^ m) := by + simp [Cube] + _ ≤ 1 / 2 := CayleyTailCount.union_bound_le_half n m hm + +theorem exists_generators (n m : Nat) (hm : 3 * (n + 2) ≤ m) : + ∃ g : Generators n m, ∀ s : Cube (Fin n), + s ≠ zeroFrequency → |eigenvalue g s| ≤ (1 / 2 : ℝ) := by + classical + have hmpos : 0 < m := by omega + let : Nonempty (Fin (4 * m)) := ⟨⟨0, by omega⟩⟩ + have havg : (𝔼 g : Generators n m, badMass g) < (1 : ℝ) := + lt_of_le_of_lt (mean_badMass_le n m hm) (by norm_num) + obtain ⟨g, _, hg⟩ := Finset.exists_lt_of_expect_lt Finset.univ_nonempty havg + refine ⟨g, fun s hs => ?_⟩ + have hgood : ¬ CayleyTailCount.badWord m + (fun d => AssignmentTester.parity s (g d)) := by + intro hbad + have hsingle : badFrequency g s ≤ badMass g := + Finset.single_le_sum (fun t _ => badFrequency_nonnegative g t) (Finset.mem_univ s) + simp only [badFrequency, ite_eq_right hs, ite_eq_left hbad] at hsingle + exact (not_le_of_gt hg) hsingle + unfold eigenvalue + simp_rw [← AssignmentTester.bitSign_parity] + exact CayleyTailCount.not_badWord_bias m (by simp) hmpos _ hgood + +def baseDimension : Nat := 448 +def initialDegree : Nat := 2 ^ 16 +def initialQuarterDegree : Nat := 2 ^ 14 +def basePower : Nat := 7 + +theorem base_arithmetic : + 4 * initialQuarterDegree = initialDegree ∧ + 3 * (baseDimension + 2) ≤ initialQuarterDegree ∧ + (2 : Nat) ^ baseDimension = (initialDegree ^ basePower) ^ 4 ∧ + (1 / 2 : ℝ) ^ basePower ≤ 1 / 100 := by + refine ⟨?_, ?_, ?_, ?_⟩ + · norm_num [initialDegree, initialQuarterDegree] + · norm_num [baseDimension, initialQuarterDegree] + · simpa only [baseDimension, initialDegree, basePower] using + CayleyTailCount.seventh_power_size + · norm_num [basePower] + +theorem exists_initial_generators : + ∃ g : Generators baseDimension initialQuarterDegree, + ∀ s : Cube (Fin baseDimension), s ≠ zeroFrequency → + |eigenvalue g s| ≤ (1 / 2 : ℝ) := + exists_generators _ _ base_arithmetic.2.1 + +abbrev BaseVertex := Cube (Fin baseDimension) +abbrev BasePort := Fin basePower → Fin (4 * initialQuarterDegree) +def baseDegree : Nat := initialDegree ^ basePower + +theorem card_basePort : Fintype.card BasePort = baseDegree := by + simp only [BasePort, Fintype.card_fun, Fintype.card_fin] + rw [base_arithmetic.1] + rfl + +theorem card_baseVertex : Fintype.card BaseVertex = baseDegree ^ 4 := by + simpa only [BaseVertex, Cube, Fintype.card_fun, Fintype.card_bool, + Fintype.card_fin, baseDegree] using base_arithmetic.2.2.1 + +theorem exists_baseGraph : + ∃ H : PoweringWalks.PortGraph BaseVertex BasePort, + SpectralReturn.SpectralCertificate H (1 / 100 : ℝ) := by + obtain ⟨g, hg⟩ := exists_initial_generators + refine ⟨cayleyGraph (powerGenerators g basePower), ?_⟩ + apply cayley_spectralCertificate + · norm_num + · norm_num + · intro s hs + exact (power_eigenvalue_bound g (1 / 2) (by norm_num) hg basePower s hs).trans + base_arithmetic.2.2.2 + +end MinUncutGames.Foundations.PCP.Expanders + +end +namespace MinUncutGames.Foundations.PCP.GraphTransport + +open PoweringWalks SpectralReturn + +variable {V W D E : Type*} + +def reindex (G : PortGraph V D) (vertices : V ≃ W) (ports : D ≃ E) : + PortGraph W E where + rot := (Equiv.prodCongr vertices ports).symm.trans + (G.rot.trans (Equiv.prodCongr vertices ports)) + rot_involutive := by + intro x + change (Equiv.prodCongr vertices ports) + (G.rot ((Equiv.prodCongr vertices ports).symm + ((Equiv.prodCongr vertices ports) + (G.rot ((Equiv.prodCongr vertices ports).symm x))))) = x + rw [Equiv.symm_apply_apply, G.rot_involutive, Equiv.apply_symm_apply] + +@[simp] theorem reindex_rot (G : PortGraph V D) (vertices : V ≃ W) + (ports : D ≃ E) (v : V) (d : D) : + (reindex G vertices ports).rot (vertices v, ports d) = + (vertices (G.rot (v, d)).1, ports (G.rot (v, d)).2) := by + simp [reindex, Equiv.trans_apply, Prod.map] + + +variable [Fintype V] [Fintype W] [Fintype D] [Fintype E] + +omit [Fintype V] [Fintype W] in +theorem operator_reindex (G : PortGraph V D) (vertices : V ≃ W) + (ports : D ≃ E) (f : W → ℝ) (w : W) : + averagingOperator (reindex G vertices ports) f w = + averagingOperator G (fun v => f (vertices v)) (vertices.symm w) := by + unfold averagingOperator + apply Fintype.expect_equiv ports.symm + intro e + rfl + +theorem energy_reindex (vertices : V ≃ W) (f : W → ℝ) : + energy (fun v => f (vertices v)) = energy f := + mean_equiv vertices (fun w => f w ^ 2) + +theorem reindex_spectralCertificate (G : PortGraph V D) (vertices : V ≃ W) + (ports : D ≃ E) (lambda : ℝ) (certificate : SpectralCertificate G lambda) : + SpectralCertificate (reindex G vertices ports) lambda where + nonnegative := certificate.nonnegative + lt_one := certificate.lt_one + contraction := by + intro f hf + have hf' : mean (fun v => f (vertices v)) = 0 := + (mean_equiv vertices f).trans hf + have h := certificate.contraction (fun v => f (vertices v)) hf' + have hout : energy (averagingOperator (reindex G vertices ports) f) = + energy (averagingOperator G (fun v => f (vertices v))) := by + rw [← energy_reindex vertices] + congr 1 + funext v + rw [operator_reindex, vertices.symm_apply_apply] + rw [hout, ← energy_reindex vertices f] + exact h + + +end MinUncutGames.Foundations.PCP.GraphTransport + +namespace MinUncutGames.Foundations.PCP.ZigzagGraphs + +open PoweringWalks + +variable {V D E : Type*} + +def involutionEquiv {A : Type*} (f : A → A) (hf : Function.Involutive f) : A ≃ A where + toFun := f + invFun := f + left_inv := hf + right_inv := hf + +theorem palindrome_involutive {A : Type*} (B P : A ≃ A) + (hB : Function.Involutive B) (hP : Function.Involutive P) : + Function.Involutive (B.trans (P.trans B)) := by + intro x + change B (P (B (B (P (B x))))) = x + rw [hB, hP, hB] + +def squareFirst (G : PortGraph V D) (s : V × (D × D)) : V × (D × D) := + let step := G.rot (s.1, s.2.1) + (step.1, (step.2, s.2.2)) + +theorem squareFirst_involutive (G : PortGraph V D) : Function.Involutive (squareFirst G) := by + rintro ⟨v, d₁, d₂⟩ + change ((G.rot (G.rot (v, d₁))).1, ((G.rot (G.rot (v, d₁))).2, d₂)) = + (v, (d₁, d₂)) + rw [G.rot_involutive] + +def squareSwap (s : V × (D × D)) : V × (D × D) := (s.1, (s.2.2, s.2.1)) + +theorem squareSwap_involutive : Function.Involutive (squareSwap (V := V) (D := D)) := by + rintro ⟨v, d₁, d₂⟩ + rfl + +def square (G : PortGraph V D) : PortGraph V (D × D) := by + let B := involutionEquiv (squareFirst G) (squareFirst_involutive G) + let P := involutionEquiv (squareSwap (V := V) (D := D)) squareSwap_involutive + exact + { rot := B.trans (P.trans B) + rot_involutive := palindrome_involutive B P + (squareFirst_involutive G) squareSwap_involutive } + +@[simp] theorem square_rot_apply (G : PortGraph V D) (v : V) (d₁ d₂ : D) : + (square G).rot (v, (d₁, d₂)) = + let first := G.rot (v, d₁) + let second := G.rot (first.1, d₂) + (second.1, (second.2, first.2)) := rfl + +@[simp] theorem square_next (G : PortGraph V D) (v : V) (d₁ d₂ : D) : + next (square G) v (d₁, d₂) = next G (next G v d₁) d₂ := rfl + +def cloudFirst (H : PortGraph D E) (s : (V × D) × (E × E)) : + (V × D) × (E × E) := + let step := H.rot (s.1.2, s.2.1) + ((s.1.1, step.1), (step.2, s.2.2)) + +theorem cloudFirst_involutive (H : PortGraph D E) : + Function.Involutive (cloudFirst (V := V) H) := by + rintro ⟨⟨v, d⟩, ⟨e₁, e₂⟩⟩ + change ((v, (H.rot (H.rot (d, e₁))).1), ((H.rot (H.rot (d, e₁))).2, e₂)) = + ((v, d), (e₁, e₂)) + rw [H.rot_involutive] + +def crossCloud (G : PortGraph V D) (s : (V × D) × (E × E)) : + (V × D) × (E × E) := (G.rot s.1, (s.2.2, s.2.1)) + +theorem crossCloud_involutive (G : PortGraph V D) : + Function.Involutive (crossCloud (E := E) G) := by + rintro ⟨x, e₁, e₂⟩ + change (G.rot (G.rot x), (e₁, e₂)) = (x, (e₁, e₂)) + rw [G.rot_involutive] + +def zigzag (G : PortGraph V D) (H : PortGraph D E) : PortGraph (V × D) (E × E) := by + let B := involutionEquiv (cloudFirst (V := V) H) (cloudFirst_involutive H) + let P := involutionEquiv (crossCloud (E := E) G) (crossCloud_involutive G) + exact + { rot := B.trans (P.trans B) + rot_involutive := palindrome_involutive B P + (cloudFirst_involutive H) (crossCloud_involutive G) } + +@[simp] theorem zigzag_rot_apply (G : PortGraph V D) (H : PortGraph D E) + (v : V) (d : D) (e₁ e₂ : E) : + (zigzag G H).rot ((v, d), (e₁, e₂)) = + let first := H.rot (d, e₁) + let middle := G.rot (v, first.1) + let last := H.rot (middle.2, e₂) + ((middle.1, last.1), (last.2, first.2)) := rfl + +theorem natCard_square_ports : Nat.card (D × D) = Nat.card D ^ 2 := by + simp [Nat.card_prod, pow_two] + +theorem natCard_square_edges : + Nat.card (Edge V (D × D)) = Nat.card V * Nat.card D ^ 2 := by + simp [Edge, Nat.card_prod, pow_two] + +theorem natCard_zigzag_vertices : + Nat.card (V × D) = Nat.card V * Nat.card D := Nat.card_prod V D + +theorem natCard_zigzag_ports : Nat.card (E × E) = Nat.card E ^ 2 := by + simp [Nat.card_prod, pow_two] + +theorem natCard_zigzag_edges : + Nat.card (Edge (V × D) (E × E)) = + Nat.card V * Nat.card D * Nat.card E ^ 2 := by + simp [Edge, Nat.card_prod, pow_two] + +noncomputable section + +def cloudOperator [Fintype E] (H : PortGraph D E) (f : V × D → ℝ) (x : V × D) : ℝ := + SpectralReturn.mean (fun e => f (x.1, (H.rot (x.2, e)).1)) + +def graphPermutation (G : PortGraph V D) (f : V × D → ℝ) (x : V × D) : ℝ := + f (G.rot x) + +theorem averagingOperator_square [Fintype D] (G : PortGraph V D) (f : V → ℝ) : + SpectralReturn.averagingOperator (square G) f = + SpectralReturn.averagingOperator G (SpectralReturn.averagingOperator G f) := by + funext v + let w : D × D → ℝ := fun ds => f (G.rot ((G.rot (v, ds.1)).1, ds.2)).1 + change SpectralReturn.mean w = + SpectralReturn.mean (fun d₁ => SpectralReturn.mean (fun d₂ => w (d₁, d₂))) + exact SpectralReturn.mean_prod w + +theorem averagingOperator_zigzag [Fintype E] (G : PortGraph V D) + (H : PortGraph D E) (f : V × D → ℝ) : + SpectralReturn.averagingOperator (zigzag G H) f = + cloudOperator H (graphPermutation G (cloudOperator H f)) := by + funext x + rcases x with ⟨v, d⟩ + let w : E × E → ℝ := fun es => + let first := H.rot (d, es.1) + let middle := G.rot (v, first.1) + let last := H.rot (middle.2, es.2) + f (middle.1, last.1) + change SpectralReturn.mean w = + SpectralReturn.mean (fun e₁ => SpectralReturn.mean (fun e₂ => w (e₁, e₂))) + exact SpectralReturn.mean_prod w + +end + +end MinUncutGames.Foundations.PCP.ZigzagGraphs + +namespace MinUncutGames.Foundations.PCP.ZigzagSpectral + +open PoweringWalks SpectralReturn ZigzagGraphs + +noncomputable section + +variable {V D E : Type*} + +def cloudMean [Fintype D] (f : V × D → ℝ) (v : V) : ℝ := + mean (fun d => f (v, d)) + +def liftCloud (f : V → ℝ) (x : V × D) : ℝ := f x.1 + +def projection [Fintype D] (f : V × D → ℝ) : V × D → ℝ := + liftCloud (cloudMean f) + +def centered [Fintype D] (f : V × D → ℝ) : V × D → ℝ := f - projection f + +theorem mean_liftCloud [Fintype V] [Fintype D] [Nonempty D] (f : V → ℝ) : + mean (liftCloud (D := D) f) = mean f := by + change mean (fun x : V × D => f x.1) = mean f + rw [mean_prod] + simp only [mean_const] + +theorem energy_liftCloud [Fintype V] [Fintype D] [Nonempty D] (f : V → ℝ) : + energy (liftCloud (D := D) f) = energy f := + mean_liftCloud (D := D) (fun v => f v ^ 2) + +theorem mean_cloudMean [Fintype V] [Fintype D] (f : V × D → ℝ) : + mean (cloudMean f) = mean f := (mean_prod f).symm + +theorem energy_prod [Fintype V] [Fintype D] (f : V × D → ℝ) : + energy f = mean (fun v => energy (fun d => f (v, d))) := + mean_prod (fun x => f x ^ 2) + +theorem cloudMean_centered_zero [Fintype D] [Nonempty D] + (f : V × D → ℝ) (v : V) : cloudMean (centered f) v = 0 := by + change mean (fun d => f (v, d) - cloudMean f v) = 0 + rw [mean_sub, mean_const] + exact sub_self _ + +theorem energy_centered_eq_sub [Fintype V] [Fintype D] [Nonempty D] + (f : V × D → ℝ) : energy (centered f) = energy f - energy (projection f) := by + have hpoint (v : V) : energy (fun d => centered f (v, d)) = + energy (fun d => f (v, d)) - (cloudMean f v) ^ 2 := by + change energy (fun d => f (v, d) - cloudMean f v) = _ + rw [energy_sub_const] + change energy (fun d => f (v, d)) - 2 * cloudMean f v * cloudMean f v + + (cloudMean f v) ^ 2 = _ + ring + have hproj : energy (projection f) = energy (cloudMean f) := energy_liftCloud _ + calc + energy (centered f) = mean (fun v => energy (fun d => centered f (v, d))) := + energy_prod _ + _ = mean (fun v => energy (fun d => f (v, d)) - (cloudMean f v) ^ 2) := by + congr 1 + funext v + exact hpoint v + _ = mean (fun v => energy (fun d => f (v, d))) - + mean (fun v => (cloudMean f v) ^ 2) := mean_sub _ _ + _ = energy f - energy (projection f) := by + rw [← energy_prod f, hproj] + rfl + +theorem projection_energy_decomposition [Fintype V] [Fintype D] [Nonempty D] + (f : V × D → ℝ) : energy f = energy (projection f) + energy (centered f) := by + rw [energy_centered_eq_sub] + ring + +theorem energy_projection_le [Fintype V] [Fintype D] [Nonempty D] + (f : V × D → ℝ) : energy (projection f) ≤ energy f := by + have h := projection_energy_decomposition f + have hn := energy_nonnegative (centered f) + linarith + +theorem energy_centered_le [Fintype V] [Fintype D] [Nonempty D] + (f : V × D → ℝ) : energy (centered f) ≤ energy f := by + rw [energy_centered_eq_sub] + exact sub_le_self _ (energy_nonnegative _) + +theorem mean_sq_le_energy {A : Type*} [Fintype A] [Nonempty A] (f : A → ℝ) : + mean f ^ 2 ≤ energy f := by + have h := correlation_sq_le f (fun _ => 1) + simpa [correlation, energy] using h + +theorem averaging_energy_le [Fintype V] [Fintype D] [Nonempty V] [Nonempty D] + (G : PortGraph V D) (f : V → ℝ) : energy (averagingOperator G f) ≤ energy f := by + calc + energy (averagingOperator G f) ≤ mean (averagingOperator G (fun v => f v ^ 2)) := by + apply mean_mono + intro v + exact mean_sq_le_energy (fun d => f (G.rot (v, d)).1) + _ = energy f := mean_operator G _ + +theorem cloudOperator_add [Fintype E] (H : PortGraph D E) (f g : V × D → ℝ) : + cloudOperator H (f + g) = cloudOperator H f + cloudOperator H g := by + funext x + exact mean_add _ _ + +theorem cloudOperator_sub [Fintype E] (H : PortGraph D E) (f g : V × D → ℝ) : + cloudOperator H (f - g) = cloudOperator H f - cloudOperator H g := by + funext x + exact mean_sub _ _ + +theorem cloudOperator_projection [Fintype D] [Fintype E] [Nonempty E] + (H : PortGraph D E) (f : V × D → ℝ) : cloudOperator H (projection f) = projection f := by + funext x + change mean (fun _ : E => cloudMean f x.1) = cloudMean f x.1 + exact mean_const _ + +theorem cloudOperator_centered [Fintype D] [Fintype E] [Nonempty E] + (H : PortGraph D E) (f : V × D → ℝ) : + cloudOperator H (centered f) = cloudOperator H f - projection f := by + unfold centered + rw [cloudOperator_sub, cloudOperator_projection] + +theorem graphPermutation_energy [Fintype V] [Fintype D] (G : PortGraph V D) + (f : V × D → ℝ) : energy (graphPermutation G f) = energy f := + mean_equiv G.rot (fun x => f x ^ 2) + +theorem cloud_energy_le [Fintype V] [Fintype D] [Fintype E] + [Nonempty D] [Nonempty E] (H : PortGraph D E) (f : V × D → ℝ) : + energy (cloudOperator H f) ≤ energy f := by + calc + energy (cloudOperator H f) = + mean (fun v => energy (averagingOperator H (fun d => f (v, d)))) := energy_prod _ + _ ≤ mean (fun v => energy (fun d => f (v, d))) := + mean_mono (fun v => averaging_energy_le H _) + _ = energy f := (energy_prod f).symm + +theorem cloud_centered_contraction [Fintype V] [Fintype D] [Fintype E] + (H : PortGraph D E) (lambda : ℝ) (hH : SpectralCertificate H lambda) + (f : V × D → ℝ) (hzero : ∀ v, cloudMean f v = 0) : + energy (cloudOperator H f) ≤ lambda ^ 2 * energy f := by + calc + energy (cloudOperator H f) = + mean (fun v => energy (averagingOperator H (fun d => f (v, d)))) := energy_prod _ + _ ≤ mean (fun v => lambda ^ 2 * energy (fun d => f (v, d))) := + mean_mono (fun v => hH.contraction _ (hzero v)) + _ = lambda ^ 2 * mean (fun v => energy (fun d => f (v, d))) := mean_mul_left _ _ + _ = lambda ^ 2 * energy f := by rw [← energy_prod f] + +theorem cloud_residual_bound [Fintype V] [Fintype D] [Fintype E] + [Nonempty D] [Nonempty E] (H : PortGraph D E) (lambda : ℝ) + (hH : SpectralCertificate H lambda) (f : V × D → ℝ) : + energy (cloudOperator H f - projection f) ≤ lambda ^ 2 * energy f := by + rw [← cloudOperator_centered H f] + exact (cloud_centered_contraction H lambda hH (centered f) + (cloudMean_centered_zero f)).trans + (mul_le_mul_of_nonneg_left (energy_centered_le f) (sq_nonneg lambda)) + +theorem projection_graphPermutation_projection [Fintype D] (G : PortGraph V D) + (f : V × D → ℝ) : + projection (graphPermutation G (projection f)) = + liftCloud (averagingOperator G (cloudMean f)) := rfl + +theorem projected_outer_bound [Fintype V] [Fintype D] [Nonempty D] + (G : PortGraph V D) (lambda : ℝ) (hG : SpectralCertificate G lambda) + (f : V × D → ℝ) (hf : mean f = 0) : + energy (projection (graphPermutation G (projection f))) ≤ + lambda ^ 2 * energy (projection f) := by + have hzero : mean (cloudMean f) = 0 := (mean_cloudMean f).trans hf + have hleft : energy (projection (graphPermutation G (projection f))) = + energy (averagingOperator G (cloudMean f)) := by + rw [projection_graphPermutation_projection] + exact energy_liftCloud _ + have hright : energy (projection f) = energy (cloudMean f) := energy_liftCloud _ + rw [hleft, hright] + exact hG.contraction _ hzero + +theorem energy_add_three_le {A : Type*} [Fintype A] (a b c : A → ℝ) : + energy (a + b + c) ≤ 3 * (energy a + energy b + energy c) := by + calc + energy (a + b + c) ≤ mean (fun x => 3 * (a x ^ 2 + b x ^ 2 + c x ^ 2)) := by + apply mean_mono + intro x + change (a x + b x + c x) ^ 2 ≤ 3 * (a x ^ 2 + b x ^ 2 + c x ^ 2) + nlinarith [sq_nonneg (a x - b x), sq_nonneg (a x - c x), sq_nonneg (b x - c x)] + _ = 3 * (energy a + energy b + energy c) := by + rw [mean_mul_left, mean_add, mean_add] + rfl + +theorem zigzag_energy_bound [Fintype V] [Fintype D] [Fintype E] + [Nonempty D] [Nonempty E] + (G : PortGraph V D) (H : PortGraph D E) (lambdaG lambdaH : ℝ) + (hG : SpectralCertificate G lambdaG) (hH : SpectralCertificate H lambdaH) + (f : V × D → ℝ) (hf : mean f = 0) : + energy (averagingOperator (zigzag G H) f) ≤ + 3 * (lambdaG ^ 2 + lambdaH ^ 2) * energy f := by + let u := projection f + let v := centered f + let a := projection (graphPermutation G u) + let b := cloudOperator H (graphPermutation G u) - a + let c := cloudOperator H (graphPermutation G (cloudOperator H v)) + have hfactor : averagingOperator (zigzag G H) f = a + b + c := by + rw [averagingOperator_zigzag] + have hf' : f = u + v := by + funext x + change f x = projection f x + (f x - projection f x) + ring + have hbu : cloudOperator H u = u := cloudOperator_projection H f + have hbf : cloudOperator H f = u + cloudOperator H v := by + rw [hf', cloudOperator_add, hbu] + rw [hbf] + have hp : graphPermutation G (u + cloudOperator H v) = + graphPermutation G u + graphPermutation G (cloudOperator H v) := rfl + rw [hp, cloudOperator_add] + change cloudOperator H (graphPermutation G u) + c = + a + (cloudOperator H (graphPermutation G u) - a) + c + funext x + change cloudOperator H (graphPermutation G u) x + c x = + a x + (cloudOperator H (graphPermutation G u) x - a x) + c x + ring + have ha : energy a ≤ lambdaG ^ 2 * energy u := projected_outer_bound G lambdaG hG f hf + have hb : energy b ≤ lambdaH ^ 2 * energy u := by + have h := cloud_residual_bound H lambdaH hH (graphPermutation G u) + simpa only [graphPermutation_energy] using h + have hc : energy c ≤ lambdaH ^ 2 * energy v := by + calc + energy c ≤ energy (graphPermutation G (cloudOperator H v)) := cloud_energy_le H _ + _ = energy (cloudOperator H v) := graphPermutation_energy G _ + _ ≤ lambdaH ^ 2 * energy v := + cloud_centered_contraction H lambdaH hH v (cloudMean_centered_zero f) + rw [hfactor] + calc + energy (a + b + c) ≤ 3 * (energy a + energy b + energy c) := energy_add_three_le _ _ _ + _ ≤ 3 * (lambdaG ^ 2 * energy u + lambdaH ^ 2 * energy u + lambdaH ^ 2 * energy v) := + mul_le_mul_of_nonneg_left (add_le_add (add_le_add ha hb) hc) (by norm_num) + _ ≤ 3 * (lambdaG ^ 2 + lambdaH ^ 2) * energy f := by + have hdecomp : energy f = energy u + energy v := projection_energy_decomposition f + rw [hdecomp] + have hn := mul_nonneg (sq_nonneg lambdaG) (energy_nonnegative v) + nlinarith + +theorem square_certificate [Fintype V] [Fintype D] [Nonempty V] [Nonempty D] + (G : PortGraph V D) (lambda : ℝ) (hG : SpectralCertificate G lambda) : + SpectralCertificate (square G) (lambda ^ 2) where + nonnegative := sq_nonneg lambda + lt_one := by + have hprod := mul_pos (sub_pos.mpr hG.lt_one) + (show 0 < 1 + lambda by linarith [hG.nonnegative]) + nlinarith + contraction f hf := by + rw [averagingOperator_square] + calc + energy (averagingOperator G (averagingOperator G f)) ≤ + lambda ^ 2 * energy (averagingOperator G f) := + hG.contraction _ ((mean_operator G f).trans hf) + _ ≤ lambda ^ 2 * (lambda ^ 2 * energy f) := + mul_le_mul_of_nonneg_left (hG.contraction f hf) (sq_nonneg lambda) + _ = (lambda ^ 2) ^ 2 * energy f := by ring + +theorem square_zigzag_halfCertificate [Fintype V] [Fintype D] [Fintype E] + [Nonempty V] [Nonempty D] [Nonempty E] + (G : PortGraph V D) (H : PortGraph (D × D) E) + (hG : SpectralCertificate G (1 / 2)) (hH : SpectralCertificate H (1 / 100)) : + SpectralCertificate (zigzag (square G) H) (1 / 2) where + nonnegative := by norm_num + lt_one := by norm_num + contraction f hf := by + have h := zigzag_energy_bound (square G) H ((1 / 2 : ℝ) ^ 2) (1 / 100) + (square_certificate G (1 / 2) hG) hH f hf + have hcoef : 3 * (((1 / 2 : ℝ) ^ 2) ^ 2 + (1 / 100) ^ 2) ≤ (1 / 2 : ℝ) ^ 2 := by + norm_num + exact h.trans (mul_le_mul_of_nonneg_right hcoef (energy_nonnegative f)) + +end + +end MinUncutGames.Foundations.PCP.ZigzagSpectral + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/ClauseLookup.lean b/lean/OAI/Computability/MinUncut/PCP/ClauseLookup.lean new file mode 100644 index 0000000000000000000000000000000000000000..2acc9ee0fe24c19be85c0db59feb87697b4a6b16 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/ClauseLookup.lean @@ -0,0 +1,475 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.FieldArray +import OAI.Computability.MinUncut.Machines.MachineUnaryCounter + +namespace OAI + +section +namespace MinUncutGames.Foundations.Hastad.SourceClauseLookup + +open Turing +open MinUncutGames.Foundations.Complexity +open MachineComposition SourceMachine + +section Discard + +variable {K Λ σ : Type} [DecidableEq K] + +theorem discardFieldsTrace (source : K) (label : Nat → Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (base : K → List Bool) (offset : Nat) (values : List Nat) (suffix : List Bool) + (atLoop : ∀ r, r < values.length → program (label (offset + r)) = + MachineLookup.discard source (label (offset + r)) (label (offset + r + 1))) + (hinput : base source = encodeWords values ++ suffix) (ambient : σ) : + (advance (TM2.step program))^[(encodeWords values).length] + (some ⟨some (label offset), (ambient, none), base⟩) = + some ⟨some (label (offset + values.length)), (ambient, none), + Function.update base source suffix⟩ := by + induction values generalizing base offset with + | nil => + have hbase : Function.update base source suffix = base := by + have hs : base source = suffix := by simpa only [encodeWords, List.nil_append] using hinput + funext p + by_cases hp : p = source + · subst p; simp [hs] + · simp [hp] + simp only [encodeWords, List.length_nil, Nat.add_zero, Function.iterate_zero_apply, hbase] + | cons n rest ih => + have hs : program (label offset) = + MachineLookup.discard source (label offset) (label (offset + 1)) := by + simpa only [Nat.add_zero] using atLoop 0 (by simp) + have hin : base source = encodeWord n ++ (encodeWords rest ++ suffix) := by + simpa only [encodeWords, List.append_assoc] using hinput + have first := MachineLookup.discardTrace source (label offset) (label (offset + 1)) + program hs base n (encodeWords rest ++ suffix) hin ambient none + have htail : ∀ r, r < rest.length → program (label (offset + 1 + r)) = + MachineLookup.discard source (label (offset + 1 + r)) + (label (offset + 1 + r + 1)) := by + intro r hr + simpa [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using + atLoop (r + 1) (by simp; omega) + have second := ih (Function.update base source (encodeWords rest ++ suffix)) + (offset + 1) htail (by simp) + rw [show (encodeWords (n :: rest)).length = (encodeWords rest).length + (n + 1) by + simp only [encodeWords, List.length_append, encodeWord_length] + omega] + rw [Function.iterate_add_apply, first] + simpa [Function.update_idem, Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using second + +end Discard + +inductive Tape + | formula | index | work | scratch | field (slot : Fin 6) + deriving DecidableEq, Fintype + +inductive Label + | copyOut | copyBack | headerFirst | headerSecond | guard + | skip (slot : Fin 6) + | read (slot : Fin 7 × Bool) + deriving DecidableEq, Fintype + +def fieldDestination (r : Nat) : Tape := .field ⟨min r 5, by omega⟩ +def readStart (r : Nat) : Label := .read (SourceFieldArray.boundedIndex 6 r, false) +def readLoop (r : Nat) : Label := .read (SourceFieldArray.boundedIndex 6 r, true) +def skipLabel (r : Nat) : Label := if h : r < 6 then .skip ⟨r, h⟩ else .guard +def headerLabel (r : Nat) : Label := + if r = 0 then .headerFirst else if r = 1 then .headerSecond else .guard + +def program : Label → TM2.Stmt (fun _ : Tape => Bool) Label (Unit × Option Bool) + | .copyOut => Reduction.MachineTransfer.loopAt .formula .scratch id false + .copyOut (some .copyBack) + | .copyBack => MachineCopy.forkLoop .scratch .formula .work false + .copyBack (some .headerFirst) + | .headerFirst => MachineLookup.discard .work .headerFirst .headerSecond + | .headerSecond => MachineLookup.discard .work .headerSecond .guard + | .guard => MachineUnaryCounter.guard .index (skipLabel 0) (readStart 0) + | .skip slot => MachineLookup.discard .work (.skip slot) (skipLabel (slot.val + 1)) + | .read slot => + if slot.1.val < 6 then + if slot.2 then + fieldLoop .work (fieldDestination slot.1.val) (.read (slot.1, true)) + (some (readStart (slot.1.val + 1))) + else fieldStart (fieldDestination slot.1.val) (.read (slot.1, true)) + else SourceFieldArray.finish .work none + +def machine : FinTM2 where + K := Tape + k₀ := .formula + k₁ := .field 0 + Γ _ := Bool + Λ := Label + main := .copyOut + σ := Unit × Option Bool + initialState := ((), none) + m := program + +theorem atSkip (r : Nat) (hr : r < 6) : + program (skipLabel r) = MachineLookup.discard .work (skipLabel r) (skipLabel (r + 1)) := by + simp [skipLabel, hr, program] + +theorem atReadStart (r : Nat) (hr : r < 6) : + program (readStart r) = fieldStart (fieldDestination r) (readLoop r) := by + simp [program, readStart, readLoop, SourceFieldArray.boundedIndex_val hr.le, hr] + +theorem atReadLoop (r : Nat) (hr : r < 6) : + program (readLoop r) = fieldLoop .work (fieldDestination r) (readLoop r) + (some (readStart (r + 1))) := by + simp [program, readStart, readLoop, SourceFieldArray.boundedIndex_val hr.le, hr] + +theorem atReadDone : program (readStart 6) = SourceFieldArray.finish .work none := by + simp [program, readStart, SourceFieldArray.boundedIndex] + +theorem discardHeadersTrace (base : Tape → List Bool) (variableCount clauses : Nat) + (suffix : List Bool) (hinput : base .work = encodeWords [variableCount, clauses] ++ suffix) : + (advance (TM2.step program))^[variableCount + clauses + 2] + (some ⟨some .headerFirst, ((), none), base⟩) = + some ⟨some .guard, ((), none), Function.update base .work suffix⟩ := by + have ht := discardFieldsTrace .work headerLabel program base 0 [variableCount, clauses] + suffix (by + intro r hr + have he : r = 0 ∨ r = 1 := by simp at hr; omega + rcases he with rfl | rfl <;> rfl) hinput () + simpa [encodeWords_length, headerLabel] using ht + +theorem discardSixTrace (base : Tape → List Bool) (values : List Nat) + (hlen : values.length = 6) (suffix : List Bool) + (hinput : base .work = encodeWords values ++ suffix) : + (advance (TM2.step program))^[(encodeWords values).length] + (some ⟨some (skipLabel 0), ((), none), base⟩) = + some ⟨some .guard, ((), none), Function.update base .work suffix⟩ := by + have ht := discardFieldsTrace .work skipLabel program base 0 values suffix + (by intro r hr; simpa only [Nat.zero_add] using atSkip r (by omega)) hinput () + simpa [hlen, skipLabel] using ht + +theorem readSixTrace (base : Tape → List Bool) (values : List Nat) + (hlen : values.length = 6) (suffix : List Bool) + (hinput : base .work = encodeWords values ++ suffix) : + (advance (TM2.step program))^[(encodeWords values).length + 7] + (some ⟨some (readStart 0), ((), none), base⟩) = + some ⟨none, ((), none), + SourceFieldArray.sequenceTapes .work fieldDestination base 0 values suffix⟩ := by + have ht := SourceFieldArray.sequenceTrace .work fieldDestination readStart readLoop none + program base 0 values suffix (by intro r hr; simp [fieldDestination]) + (by intro r hr; simpa only [Nat.zero_add] using atReadStart r (by omega)) + (by intro r hr; simpa only [Nat.zero_add] using atReadLoop r (by omega)) + (by simpa [hlen] using atReadDone) hinput () none + have htime : values.sum + 2 * values.length + 1 = (encodeWords values).length + 7 := by + rw [encodeWords_length, hlen] + simpa only [Nat.zero_add, htime] using ht + +def scanTapes (base : Tape → List Bool) (index : Nat) + (indexSuffix input : List Bool) : Tape → List Bool := + MachineUnaryCounter.counterTapes .index (Function.update base .work input) index indexSuffix + +@[simp] theorem scanTapes_work (base : Tape → List Bool) (i : Nat) + (indexSuffix input : List Bool) : scanTapes base i indexSuffix input .work = input := by + simp [scanTapes, MachineUnaryCounter.counterTapes] + +@[simp] theorem scanTapes_index (base : Tape → List Bool) (i : Nat) + (indexSuffix input : List Bool) : + scanTapes base i indexSuffix input .index = encodeWord i ++ indexSuffix := by + simp [scanTapes, MachineUnaryCounter.counterTapes] + +theorem scanTapes_other (base : Tape → List Bool) (i : Nat) + (indexSuffix input : List Bool) (p : Tape) (hi : p ≠ .index) (hw : p ≠ .work) : + scanTapes base i indexSuffix input p = base p := by + simp [scanTapes, MachineUnaryCounter.counterTapes, hi, hw] + +theorem update_scanTapes_work (base : Tape → List Bool) (i : Nat) + (indexSuffix input replacement : List Bool) : + Function.update (scanTapes base i indexSuffix input) .work replacement = + scanTapes base i indexSuffix replacement := by + funext p + cases p <;> simp [scanTapes, MachineUnaryCounter.counterTapes] + +theorem skipClausesTrace {n : Nat} (base : Tape → List Bool) + (prior : List (Target.Clause n)) (indexSuffix suffix : List Bool) + (register : Option Bool) : + (advance (TM2.step program))^[(encodeWords (prior.flatMap clauseWords)).length + prior.length + 1] + (some ⟨some .guard, ((), register), scanTapes base prior.length indexSuffix + (encodeWords (prior.flatMap clauseWords) ++ suffix)⟩) = + some ⟨some (readStart 0), ((), none), scanTapes base 0 indexSuffix suffix⟩ := by + induction prior generalizing register with + | nil => + simpa only [List.flatMap_nil, List.length_nil, encodeWords, List.nil_append, + Nat.zero_add, Function.iterate_one, advance_some, scanTapes] using + MachineUnaryCounter.guardStep_zero .index .guard (skipLabel 0) (readStart 0) + program rfl (Function.update base .work suffix) indexSuffix () register + | cons clause prior ih => + have hencoding : encodeWords ((clause :: prior).flatMap clauseWords) ++ suffix = + encodeWords (clauseWords clause) ++ (encodeWords (prior.flatMap clauseWords) ++ suffix) := by + simp only [List.flatMap_cons, encodeWords_append, List.append_assoc] + have htime : (encodeWords ((clause :: prior).flatMap clauseWords)).length + + (clause :: prior).length + 1 = + ((encodeWords (prior.flatMap clauseWords)).length + prior.length + 1 + + (encodeWords (clauseWords clause)).length) + 1 := by + simp only [List.flatMap_cons, encodeWords_append, List.length_append, List.length_cons] + omega + rw [htime, Function.iterate_succ_apply] + change (advance (TM2.step program))^[ + (encodeWords (prior.flatMap clauseWords)).length + prior.length + 1 + + (encodeWords (clauseWords clause)).length] + (TM2.step program ⟨some .guard, ((), register), + MachineUnaryCounter.counterTapes .index + (Function.update base .work (encodeWords ((clause :: prior).flatMap clauseWords) ++ suffix)) + (prior.length + 1) indexSuffix⟩) = _ + rw [MachineUnaryCounter.guardStep_succ .index .guard (skipLabel 0) (readStart 0) + program rfl] + rw [Function.iterate_add_apply] + have hd := discardSixTrace + (scanTapes base prior.length indexSuffix + (encodeWords ((clause :: prior).flatMap clauseWords) ++ suffix)) + (clauseWords clause) (clauseWords_length clause) + (encodeWords (prior.flatMap clauseWords) ++ suffix) (by + rw [scanTapes_work, hencoding]) + change (advance (TM2.step program))^[ + (encodeWords (prior.flatMap clauseWords)).length + prior.length + 1] + ((advance (TM2.step program))^[(encodeWords (clauseWords clause)).length] + (some ⟨some (skipLabel 0), ((), none), scanTapes base prior.length indexSuffix + (encodeWords ((clause :: prior).flatMap clauseWords) ++ suffix)⟩)) = _ + rw [hd, update_scanTapes_work] + exact ih none + +theorem fieldDestination_eq (j : Fin 6) : fieldDestination j.val = .field j := by + unfold fieldDestination + congr 1 + apply Fin.ext + exact Nat.min_eq_left (by omega) + +theorem fieldDestination_injective_below (r s : Nat) (hr : r < 6) (hs : s < 6) + (he : fieldDestination r = fieldDestination s) : r = s := by + have hv := congrArg (fun t : Tape => match t with | .field j => j.val | _ => 6) he + simpa [fieldDestination, Nat.min_eq_left (show r ≤ 5 by omega), + Nat.min_eq_left (show s ≤ 5 by omega)] using hv + +theorem readSix_output_field (base : Tape → List Bool) (values : List Nat) + (hlen : values.length = 6) (suffix : List Bool) (j : Fin 6) : + SourceFieldArray.sequenceTapes .work fieldDestination base 0 values suffix (.field j) = + encodeWord (values[j.val]'(by omega)) ++ base (.field j) := by + have ht := SourceFieldArray.sequenceTapes_selected .work fieldDestination base 0 values + suffix j.val (by omega) (by intro r hr; simp [fieldDestination]) + (by + intro r s hr hs he + apply fieldDestination_injective_below r s (by omega) (by omega) + simpa only [Nat.zero_add] using he) + simpa only [Nat.zero_add, fieldDestination_eq] using ht + +theorem readSix_output_work (base : Tape → List Bool) (values : List Nat) + (_hlen : values.length = 6) (suffix : List Bool) + (hinput : base .work = encodeWords values ++ suffix) : + SourceFieldArray.sequenceTapes .work fieldDestination base 0 values suffix .work = suffix := by + apply SourceFieldArray.sequenceTapes_source _ _ _ _ _ _ _ hinput + intro r hr + simp [fieldDestination] + +theorem readSix_output_frame (base : Tape → List Bool) (values : List Nat) + (suffix : List Bool) (p : Tape) (hwork : p ≠ .work) + (hfield : ∀ j : Fin 6, p ≠ .field j) : + SourceFieldArray.sequenceTapes .work fieldDestination base 0 values suffix p = base p := by + apply SourceFieldArray.sequenceTapes_other _ _ _ hwork + intro r hr + exact hfield _ + +def outputTapes {n : Nat} (base : Tape → List Bool) (clause : Target.Clause n) + (indexSuffix suffix : List Bool) : Tape → List Bool := + SourceFieldArray.sequenceTapes .work fieldDestination + (scanTapes base 0 indexSuffix (encodeWords (clauseWords clause) ++ suffix)) + 0 (clauseWords clause) suffix + +def scanSteps {n : Nat} (variableCount declaredClauses : Nat) + (prior : List (Target.Clause n)) (clause : Target.Clause n) : Nat := + variableCount + declaredClauses + 2 + + (encodeWords (prior.flatMap clauseWords)).length + prior.length + 1 + + (encodeWords (clauseWords clause)).length + 7 + +theorem scanReadTrace {n : Nat} (base : Tape → List Bool) (variableCount declaredClauses : Nat) + (prior : List (Target.Clause n)) (clause : Target.Clause n) + (indexSuffix suffix : List Bool) : + (advance (TM2.step program))^[scanSteps variableCount declaredClauses prior clause] + (some ⟨some .headerFirst, ((), none), scanTapes base prior.length indexSuffix + (encodeWords [variableCount, declaredClauses] ++ + (encodeWords (prior.flatMap clauseWords) ++ + (encodeWords (clauseWords clause) ++ suffix)))⟩) = + some ⟨none, ((), none), outputTapes base clause indexSuffix suffix⟩ := by + have hh := discardHeadersTrace + (scanTapes base prior.length indexSuffix + (encodeWords [variableCount, declaredClauses] ++ + (encodeWords (prior.flatMap clauseWords) ++ (encodeWords (clauseWords clause) ++ suffix)))) + variableCount declaredClauses + (encodeWords (prior.flatMap clauseWords) ++ (encodeWords (clauseWords clause) ++ suffix)) + (by simp) + have hs := skipClausesTrace base prior indexSuffix (encodeWords (clauseWords clause) ++ suffix) none + have hr := readSixTrace + (scanTapes base 0 indexSuffix (encodeWords (clauseWords clause) ++ suffix)) + (clauseWords clause) (clauseWords_length clause) suffix (by simp) + rw [show scanSteps variableCount declaredClauses prior clause = + ((encodeWords (clauseWords clause)).length + 7 + + ((encodeWords (prior.flatMap clauseWords)).length + prior.length + 1)) + + (variableCount + declaredClauses + 2) by unfold scanSteps; omega] + rw [Function.iterate_add_apply, hh, update_scanTapes_work, + Function.iterate_add_apply, hs] + exact hr + +def lookupSteps {n : Nat} (F : Target.Formula) (prior : List (Target.Clause n)) + (clause : Target.Clause n) : Nat := + 2 * ((formulaBits F).length + 1) + scanSteps F.«variables» F.clauses.length prior clause + +theorem lookupWithSplitTrace (F : Target.Formula) (prior : List (Target.Clause F.«variables»)) + (clause : Target.Clause F.«variables») (after : List (Target.Clause F.«variables»)) + (hsplit : F.clauses = prior ++ clause :: after) + (base : Tape → List Bool) (indexSuffix : List Bool) + (hformula : base .formula = formulaBits F) + (hindex : base .index = encodeWord prior.length ++ indexSuffix) + (hwork : base .work = []) (hscratch : base .scratch = []) + (register : Option Bool) : + (advance (TM2.step program))^[lookupSteps F prior clause] + (some ⟨some .copyOut, ((), register), base⟩) = + some ⟨none, ((), none), + outputTapes base clause indexSuffix (encodeWords (after.flatMap clauseWords))⟩ := by + have hbits : formulaBits F = encodeWords [F.«variables», F.clauses.length] ++ + (encodeWords (prior.flatMap clauseWords) ++ + (encodeWords (clauseWords clause) ++ encodeWords (after.flatMap clauseWords))) := by + simp only [formulaBits, formulaWords, encodeWords_append] + rw [hsplit] + simp only [List.flatMap_append, List.flatMap_cons, encodeWords_append] + have hc := MachineCopy.copyTrace .formula .work .scratch (by decide) (by decide) + (by decide) false .copyOut .copyBack (some .headerFirst) program rfl rfl + base hscratch () register + have htapes : Function.update base .work (base .formula ++ base .work) = + scanTapes base prior.length indexSuffix (formulaBits F) := by + funext p + cases p <;> simp [scanTapes, MachineUnaryCounter.counterTapes, hformula, hindex, hwork] + rw [htapes, hformula] at hc + rw [lookupSteps, Nat.add_comm, Function.iterate_add_apply, hc, hbits] + exact scanReadTrace base F.«variables» F.clauses.length prior clause indexSuffix + (encodeWords (after.flatMap clauseWords)) + +theorem output_formula {n : Nat} (base : Tape → List Bool) (clause : Target.Clause n) + (indexSuffix suffix : List Bool) : + outputTapes base clause indexSuffix suffix .formula = base .formula := by + rw [outputTapes, readSix_output_frame _ _ _ .formula (by decide) (by intro j; simp)] + exact scanTapes_other _ _ _ _ _ (by decide) (by decide) + +theorem output_index {n : Nat} (base : Tape → List Bool) (clause : Target.Clause n) + (indexSuffix suffix : List Bool) : + outputTapes base clause indexSuffix suffix .index = encodeWord 0 ++ indexSuffix := by + rw [outputTapes, readSix_output_frame _ _ _ .index (by decide) (by intro j; simp), + scanTapes_index] + +theorem output_work {n : Nat} (base : Tape → List Bool) (clause : Target.Clause n) + (indexSuffix suffix : List Bool) : + outputTapes base clause indexSuffix suffix .work = suffix := by + apply readSix_output_work _ _ (clauseWords_length clause) _ + simp + +theorem output_field {n : Nat} (base : Tape → List Bool) (clause : Target.Clause n) + (indexSuffix suffix : List Bool) (j : Fin 6) : + outputTapes base clause indexSuffix suffix (.field j) = + encodeWord ((clauseWords clause)[j.val]'(by simp)) ++ base (.field j) := by + rw [outputTapes, readSix_output_field _ _ (clauseWords_length clause)] + rw [scanTapes_other _ _ _ _ (.field j) (by simp) (by simp)] + +theorem output_frame {n : Nat} (base : Tape → List Bool) (clause : Target.Clause n) + (indexSuffix suffix : List Bool) (p : Tape) (hindex : p ≠ .index) (hwork : p ≠ .work) + (hfield : ∀ j : Fin 6, p ≠ .field j) : + outputTapes base clause indexSuffix suffix p = base p := by + rw [outputTapes, readSix_output_frame _ _ _ p hwork hfield] + exact scanTapes_other _ _ _ _ p hindex hwork + +theorem clauseWords_six {n : Nat} (clause : Target.Clause n) : + clauseWords clause = + [clause[0].variableIndex.val, if clause[0].positive then 1 else 0, + clause[1].variableIndex.val, if clause[1].positive then 1 else 0, + clause[2].variableIndex.val, if clause[2].positive then 1 else 0] := rfl + +def fieldWords (tapes : Tape → List Bool) : List (List Bool) := + [tapes (.field 0), tapes (.field 1), tapes (.field 2), + tapes (.field 3), tapes (.field 4), tapes (.field 5)] + +theorem output_fieldWords {n : Nat} (base : Tape → List Bool) (clause : Target.Clause n) + (indexSuffix suffix : List Bool) (hempty : ∀ j : Fin 6, base (.field j) = []) : + fieldWords (outputTapes base clause indexSuffix suffix) = + (clauseWords clause).map encodeWord := by + simp [fieldWords, output_field, hempty, clauseWords_six] + +theorem lookupSteps_le_input (F : Target.Formula) (prior : List (Target.Clause F.«variables»)) + (clause : Target.Clause F.«variables») (after : List (Target.Clause F.«variables»)) + (hsplit : F.clauses = prior ++ clause :: after) : + lookupSteps F prior clause ≤ 4 * (formulaBits F).length + 10 := by + have hlength : (formulaBits F).length = F.«variables» + F.clauses.length + 2 + + (encodeWords (prior.flatMap clauseWords)).length + + (encodeWords (clauseWords clause)).length + + (encodeWords (after.flatMap clauseWords)).length := by + simp only [formulaBits, formulaWords, encodeWords_append, List.length_append, + encodeWords, encodeWord_length, List.length_nil] + rw [hsplit] + simp only [List.flatMap_append, List.flatMap_cons, encodeWords_append, List.length_append] + omega + have hp : prior.length ≤ F.clauses.length := by + rw [hsplit, List.length_append, List.length_cons] + omega + unfold lookupSteps scanSteps + omega + +noncomputable def timePolynomial : Polynomial Nat := Polynomial.C 4 * Polynomial.X + Polynomial.C 10 + +theorem timePolynomial_eval (L : Nat) : timePolynomial.eval L = 4 * L + 10 := by + simp [timePolynomial] + +def lookupWithSplitInTime (F : Target.Formula) (prior : List (Target.Clause F.«variables»)) + (clause : Target.Clause F.«variables») (after : List (Target.Clause F.«variables»)) + (hsplit : F.clauses = prior ++ clause :: after) + (base : Tape → List Bool) (indexSuffix : List Bool) + (hformula : base .formula = formulaBits F) + (hindex : base .index = encodeWord prior.length ++ indexSuffix) + (hwork : base .work = []) (hscratch : base .scratch = []) + (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some .copyOut, ((), register), base⟩ + (some ⟨none, ((), none), + outputTapes base clause indexSuffix (encodeWords (after.flatMap clauseWords))⟩) + (timePolynomial.eval (formulaBits F).length) where + steps := lookupSteps F prior clause + evals_in_steps := lookupWithSplitTrace F prior clause after hsplit base indexSuffix + hformula hindex hwork hscratch register + steps_le_m := by + rw [timePolynomial_eval] + exact lookupSteps_le_input F prior clause after hsplit + +def lookupInTime (F : Target.Formula) (i : Fin F.clauses.length) + (base : Tape → List Bool) (indexSuffix : List Bool) + (hformula : base .formula = formulaBits F) + (hindex : base .index = encodeWord i.val ++ indexSuffix) + (hwork : base .work = []) (hscratch : base .scratch = []) + (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some .copyOut, ((), register), base⟩ + (some ⟨none, ((), none), outputTapes base F.clauses[i.val] indexSuffix + (encodeWords ((F.clauses.drop (i.val + 1)).flatMap clauseWords))⟩) + (timePolynomial.eval (formulaBits F).length) := by + have hp : (F.clauses.take i.val).length = i.val := by + rw [List.length_take, Nat.min_eq_left i.isLt.le] + have hs : F.clauses = F.clauses.take i.val ++ F.clauses[i.val] :: F.clauses.drop (i.val + 1) := by + rw [List.getElem_cons_drop i.isLt, List.take_append_drop] + apply lookupWithSplitInTime F (F.clauses.take i.val) F.clauses[i.val] + (F.clauses.drop (i.val + 1)) hs base indexSuffix hformula + (by simpa only [hp] using hindex) hwork hscratch register + +def machineInTime (F : Target.Formula) (i : Fin F.clauses.length) + (base : Tape → List Bool) (indexSuffix : List Bool) + (hformula : base .formula = formulaBits F) + (hindex : base .index = encodeWord i.val ++ indexSuffix) + (hwork : base .work = []) (hscratch : base .scratch = []) + (register : Option Bool) : + StateTransition.EvalsToInTime machine.step + ⟨some .copyOut, ((), register), base⟩ + (some ⟨none, ((), none), outputTapes base F.clauses[i.val] indexSuffix + (encodeWords ((F.clauses.drop (i.val + 1)).flatMap clauseWords))⟩) + (timePolynomial.eval (formulaBits F).length) := by + exact lookupInTime F i base indexSuffix hformula hindex hwork hscratch register + +end MinUncutGames.Foundations.Hastad.SourceClauseLookup + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/ClauseVerifier.lean b/lean/OAI/Computability/MinUncut/PCP/ClauseVerifier.lean new file mode 100644 index 0000000000000000000000000000000000000000..1c7d29d86030a5c9115d63645551504e97cb583c --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/ClauseVerifier.lean @@ -0,0 +1,496 @@ +import Mathlib +import OAI.Computability.MinUncut.Games.Target + +namespace OAI + +section +namespace MinUncutGames.Foundations.PCP + +open Target + +structure ClauseAnswer where + first : Bool + second : Bool + third : Bool + deriving DecidableEq + +inductive Slot where + | first + | second + | third + deriving DecidableEq + +def answerAt (answer : ClauseAnswer) : Slot → Bool + | .first => answer.first + | .second => answer.second + | .third => answer.third + +def nameAt {n : Nat} (clause : Clause n) : Slot → Fin n + | .first => clause[0].variableIndex + | .second => clause[1].variableIndex + | .third => clause[2].variableIndex + +def literalValue (positive value : Bool) : Bool := + if positive then value else !value + +def localSatisfies {n : Nat} (clause : Clause n) (answer : ClauseAnswer) : Bool := + (literalValue clause[0].positive answer.first || + literalValue clause[1].positive answer.second) || + literalValue clause[2].positive answer.third + +def honestAnswer {n : Nat} (clause : Clause n) (assignment : Fin n → Bool) : ClauseAnswer := + ⟨assignment clause[0].variableIndex, assignment clause[1].variableIndex, + assignment clause[2].variableIndex⟩ + +theorem honest_satisfies {n : Nat} (clause : Clause n) (assignment : Fin n → Bool) : + localSatisfies clause (honestAnswer clause assignment) = clause.eval assignment := rfl + +theorem honest_answerAt {n : Nat} (clause : Clause n) (assignment : Fin n → Bool) + (slot : Slot) : answerAt (honestAnswer clause assignment) slot = + assignment (nameAt clause slot) := by + cases slot <;> rfl + +def matchingSlots (a b : ClauseAnswer) : 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) + +theorem matchingSlots_le (a b : ClauseAnswer) : matchingSlots a b ≤ 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₃ <;> decide + +theorem matchingSlots_eq_three (a b : ClauseAnswer) : matchingSlots a b = 3 ↔ a = b := 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₃ <;> decide + +def acceptedSlots {n : Nat} (clause : Clause n) (alice bob : ClauseAnswer) : Nat := + if localSatisfies clause alice then matchingSlots alice bob else 0 + +def clauseFailure {n : Nat} (clause : Clause n) (assignment : Fin n → Bool) : Nat := + if clause.eval assignment then 0 else 1 + +theorem local_rejection_bound {n : Nat} (clause : Clause n) (alice : ClauseAnswer) + (bob : Fin n → Bool) : + acceptedSlots clause alice (honestAnswer clause bob) + clauseFailure clause bob ≤ 3 := by + have hle := matchingSlots_le alice (honestAnswer clause bob) + by_cases hb : clause.eval bob = true + · simp only [clauseFailure, hb, ↓reduceIte, Nat.add_zero] + unfold acceptedSlots + split <;> omega + · have hfailure : clauseFailure clause bob = 1 := by simp [clauseFailure, hb] + rw [hfailure] + by_cases ha : localSatisfies clause alice = true + · have hne : alice ≠ honestAnswer clause bob := by + intro h + subst alice + exact hb ((honest_satisfies clause bob).symm.trans ha) + have hlt : matchingSlots alice (honestAnswer clause bob) ≠ 3 := by + intro h + exact hne ((matchingSlots_eq_three _ _).mp h) + simp only [acceptedSlots, ha, ↓reduceIte] + omega + · simp [acceptedSlots, ha] + +def clauseAt (formula : Formula) (index : Fin formula.clauses.length) : + Clause formula.«variables» := formula.clauses[index.val] + +abbrev RandomEvent (formula : Formula) := Fin formula.clauses.length × Slot +abbrev AliceStrategy (formula : Formula) := Fin formula.clauses.length → ClauseAnswer +abbrev BobStrategy (formula : Formula) := Fin formula.«variables» → Bool + +def accepts (formula : Formula) (alice : AliceStrategy formula) (bob : BobStrategy formula) + (event : RandomEvent formula) : Bool := + localSatisfies (clauseAt formula event.1) (alice event.1) && + decide (answerAt (alice event.1) event.2 = bob (nameAt (clauseAt formula event.1) event.2)) + +def acceptedCount (formula : Formula) (alice : AliceStrategy formula) + (bob : BobStrategy formula) : List (Fin formula.clauses.length) → Nat + | [] => 0 + | i :: rest => acceptedSlots (clauseAt formula i) (alice i) + (honestAnswer (clauseAt formula i) bob) + acceptedCount formula alice bob rest + +def failureCount (formula : Formula) (bob : BobStrategy formula) : + List (Fin formula.clauses.length) → Nat + | [] => 0 + | i :: rest => clauseFailure (clauseAt formula i) bob + failureCount formula bob rest + +theorem total_rejection_bound (formula : Formula) (alice : AliceStrategy formula) + (bob : BobStrategy formula) (indices : List (Fin formula.clauses.length)) : + acceptedCount formula alice bob indices + failureCount formula bob indices ≤ + 3 * indices.length := by + induction indices with + | nil => simp [acceptedCount, failureCount] + | cons i rest ih => + have h := local_rejection_bound (clauseAt formula i) (alice i) bob + simp only [acceptedCount, failureCount, List.length_cons] + omega + +def allIndices (formula : Formula) : List (Fin formula.clauses.length) := + List.finRange formula.clauses.length + +theorem hastad_basic_verifier_soundness (formula : Formula) (a b : Nat) + (sourceGap : ∀ bob : BobStrategy formula, + a * formula.clauses.length ≤ b * failureCount formula bob (allIndices formula)) + (alice : AliceStrategy formula) (bob : BobStrategy formula) : + b * acceptedCount formula alice bob (allIndices formula) + a * formula.clauses.length ≤ + b * (3 * formula.clauses.length) := by + have ht := Nat.mul_le_mul_left b (total_rejection_bound formula alice bob (allIndices formula)) + have hg := sourceGap bob + simp only [allIndices, List.length_finRange, Nat.mul_add] at * + omega + +theorem honest_accepts (formula : Formula) (assignment : BobStrategy formula) + (satisfies : ∀ clause ∈ formula.clauses, clause.eval assignment = true) + (event : RandomEvent formula) : + accepts formula (fun i => honestAnswer (clauseAt formula i) assignment) assignment event = true := by + have hc : (clauseAt formula event.1).eval assignment = true := + satisfies _ (List.getElem_mem _) + simp [accepts, honest_satisfies, honest_answerAt, hc] + +theorem verifier_completeness (formula : Formula) (sat : formula.Satisfiable) : + ∃ (alice : AliceStrategy formula) (bob : BobStrategy formula), + ∀ event : RandomEvent formula, accepts formula alice bob event = true := by + rcases sat with ⟨assignment, hs⟩ + exact ⟨fun i => honestAnswer (clauseAt formula i) assignment, assignment, + honest_accepts formula assignment hs⟩ + +abbrev LeftLabel (formula : Formula) (i : Fin formula.clauses.length) := + { answer : ClauseAnswer // localSatisfies (clauseAt formula i) answer = true } + +def edgeProjection (formula : Formula) (event : RandomEvent formula) + (label : LeftLabel formula event.1) : Bool := answerAt label.val event.2 + +theorem verifier_eq_projection (formula : Formula) + (alice : ∀ i, LeftLabel formula i) (bob : BobStrategy formula) (event : RandomEvent formula) : + accepts formula (fun i => (alice i).val) bob event = + decide (edgeProjection formula event (alice event.1) = + bob (nameAt (clauseAt formula event.1) event.2)) := by + simp [accepts, (alice event.1).property, edgeProjection] + rfl + +def eventsAt (formula : Formula) (i : Fin formula.clauses.length) : List (RandomEvent formula) := + [(i, .first), (i, .second), (i, .third)] + +def enumerateEvents (formula : Formula) : List (Fin formula.clauses.length) → + List (RandomEvent formula) + | [] => [] + | i :: rest => eventsAt formula i ++ enumerateEvents formula rest + +theorem length_enumerateEvents (formula : Formula) (indices : List (Fin formula.clauses.length)) : + (enumerateEvents formula indices).length = 3 * indices.length := by + induction indices with + | nil => simp [enumerateEvents] + | cons i rest ih => + simp only [enumerateEvents, eventsAt, List.length_append, List.length_cons, + List.length_nil, ih] + omega + +theorem accepted_eventsAt (formula : Formula) (alice : AliceStrategy formula) + (bob : BobStrategy formula) (i : Fin formula.clauses.length) : + ((eventsAt formula i).filter (accepts formula alice bob)).length = + acceptedSlots (clauseAt formula i) (alice i) (honestAnswer (clauseAt formula i) bob) := by + by_cases hs : localSatisfies (clauseAt formula i) (alice i) = true + · by_cases h₁ : (alice i).first = bob (clauseAt formula i)[0].variableIndex <;> + by_cases h₂ : (alice i).second = bob (clauseAt formula i)[1].variableIndex <;> + by_cases h₃ : (alice i).third = bob (clauseAt formula i)[2].variableIndex <;> + simp [eventsAt, accepts, acceptedSlots, matchingSlots, honestAnswer, + answerAt, nameAt, hs, h₁, h₂, h₃] + · simp [eventsAt, accepts, acceptedSlots, hs] + +theorem accepted_enumerateEvents (formula : Formula) (alice : AliceStrategy formula) + (bob : BobStrategy formula) (indices : List (Fin formula.clauses.length)) : + ((enumerateEvents formula indices).filter (accepts formula alice bob)).length = + acceptedCount formula alice bob indices := by + induction indices with + | nil => simp [enumerateEvents, acceptedCount] + | cons i rest ih => + simp only [enumerateEvents, List.filter_append, List.length_append, + accepted_eventsAt, ih, acceptedCount] + +def allEvents (formula : Formula) : List (RandomEvent formula) := + enumerateEvents formula (allIndices formula) + +theorem length_allEvents (formula : Formula) : + (allEvents formula).length = 3 * formula.clauses.length := by + simp [allEvents, length_enumerateEvents, allIndices] + +theorem allEvents_nonempty (formula : Formula) (hne : formula.clauses ≠ []) : + allEvents formula ≠ [] := by + intro he + have hl := length_allEvents formula + rw [he] at hl + have hpos : 0 < formula.clauses.length := List.length_pos_iff.mpr hne + simp only [List.length_nil] at hl + omega + +theorem verifier_event_soundness (formula : Formula) (a b : Nat) + (sourceGap : ∀ bob : BobStrategy formula, + a * formula.clauses.length ≤ b * failureCount formula bob (allIndices formula)) + (alice : AliceStrategy formula) (bob : BobStrategy formula) : + b * ((allEvents formula).filter (accepts formula alice bob)).length + + a * formula.clauses.length ≤ b * (allEvents formula).length := by + rw [length_allEvents] + simp only [allEvents, accepted_enumerateEvents] + exact hastad_basic_verifier_soundness formula a b sourceGap alice bob + +def occurrencesAt {n : Nat} (clause : Clause n) (v : Fin n) : Nat := + (if clause[0].variableIndex = v then 1 else 0) + + (if clause[1].variableIndex = v then 1 else 0) + + (if clause[2].variableIndex = v then 1 else 0) + +def occurrenceCount (formula : Formula) (v : Fin formula.«variables») : + List (Fin formula.clauses.length) → Nat + | [] => 0 + | i :: rest => occurrencesAt (clauseAt formula i) v + occurrenceCount formula v rest + +theorem variable_eventsAt (formula : Formula) (v : Fin formula.«variables») + (i : Fin formula.clauses.length) : + ((eventsAt formula i).filter (fun event => + decide (nameAt (clauseAt formula event.1) event.2 = v))).length = + occurrencesAt (clauseAt formula i) v := by + by_cases h₁ : (clauseAt formula i)[0].variableIndex = v <;> + by_cases h₂ : (clauseAt formula i)[1].variableIndex = v <;> + by_cases h₃ : (clauseAt formula i)[2].variableIndex = v <;> + simp [eventsAt, nameAt, occurrencesAt, h₁, h₂, h₃] + +theorem variable_enumerateEvents (formula : Formula) (v : Fin formula.«variables») + (indices : List (Fin formula.clauses.length)) : + ((enumerateEvents formula indices).filter (fun event => + decide (nameAt (clauseAt formula event.1) event.2 = v))).length = + occurrenceCount formula v indices := by + induction indices with + | nil => simp [enumerateEvents, occurrenceCount] + | cons i rest ih => + simp only [enumerateEvents, List.filter_append, List.length_append, + variable_eventsAt, ih, occurrenceCount] + +theorem regular_bob_marginal (formula : Formula) (degree : Nat) + (regular : ∀ v : Fin formula.«variables», + occurrenceCount formula v (allIndices formula) = degree) + (v : Fin formula.«variables») : + ((allEvents formula).filter (fun event => + decide (nameAt (clauseAt formula event.1) event.2 = v))).length = degree := by + rw [allEvents, variable_enumerateEvents] + exact regular v + +end MinUncutGames.Foundations.PCP + +end +section +namespace MinUncutGames.Foundations.Hastad.SourceContexts + +open Target PCP + +def clauseAnswerEquiv : ClauseAnswer ≃ Bool × Bool × Bool where + toFun a := (a.first, a.second, a.third) + invFun a := ⟨a.1, a.2.1, a.2.2⟩ + left_inv a := by cases a; rfl + right_inv a := by rcases a with ⟨a, b, c⟩; rfl + +def clauseAnswerFinEquiv : ClauseAnswer ≃ Fin 8 := + clauseAnswerEquiv.trans + ((Equiv.prodCongr finTwoEquiv.symm + (Equiv.prodCongr finTwoEquiv.symm finTwoEquiv.symm)).trans + ((Equiv.prodCongr (Equiv.refl (Fin 2)) finProdFinEquiv).trans finProdFinEquiv)) + +instance clauseAnswerFintype : Fintype ClauseAnswer := + Fintype.ofEquiv (Bool × Bool × Bool) clauseAnswerEquiv.symm + +instance clauseAnswerInhabited : Inhabited ClauseAnswer := ⟨⟨false, false, false⟩⟩ + +instance slotFintype : Fintype Slot where + elems := {.first, .second, .third} + complete s := by cases s <;> simp + +instance slotInhabited : Inhabited Slot := ⟨.first⟩ + +@[simp] theorem card_clauseAnswer : Fintype.card ClauseAnswer = 8 := by + rw [Fintype.card_congr clauseAnswerFinEquiv] + rfl + +@[simp] theorem card_slot : Fintype.card Slot = 3 := by decide + +abbrev I (u : ℕ) := Fin u → Bool +abbrev J (u : ℕ) := Fin u → ClauseAnswer +abbrev ClauseContext (F : Formula) (u : ℕ) := Fin u → Fin F.clauses.length +abbrev VariableContext (F : Formula) (u : ℕ) := Fin u → Fin F.«variables» +abbrev SlotContext (u : ℕ) := Fin u → Slot + +@[simp] theorem card_I (u : ℕ) : Fintype.card (I u) = 2 ^ u := by simp [I] +@[simp] theorem card_J (u : ℕ) : Fintype.card (J u) = 8 ^ u := by simp [J] +@[simp] theorem card_ClauseContext (F : Formula) (u : ℕ) : + Fintype.card (ClauseContext F u) = F.clauses.length ^ u := by simp [ClauseContext] +@[simp] theorem card_VariableContext (F : Formula) (u : ℕ) : + Fintype.card (VariableContext F u) = F.«variables» ^ u := by simp [VariableContext] +@[simp] theorem card_SlotContext (u : ℕ) : + Fintype.card (SlotContext u) = 3 ^ u := by simp [SlotContext] + +def localConsistent {n : ℕ} (clause : Clause n) (answer : ClauseAnswer) : Bool := + decide (∀ s s' : Slot, nameAt clause s = nameAt clause s' → + answerAt answer s = answerAt answer s') + +@[simp] theorem localConsistent_eq_true_iff {n : ℕ} + (clause : Clause n) (answer : ClauseAnswer) : + localConsistent clause answer = true ↔ + ∀ s s' : Slot, nameAt clause s = nameAt clause s' → + answerAt answer s = answerAt answer s' := by + simp [localConsistent] + +def validJ (F : Formula) {u : ℕ} (c : ClauseContext F u) (j : J u) : Bool := + decide ((∀ t, localSatisfies (clauseAt F (c t)) (j t) = true) ∧ + ∀ t t' s s', nameAt (clauseAt F (c t)) s = nameAt (clauseAt F (c t')) s' → + answerAt (j t) s = answerAt (j t') s') + +@[simp] theorem validJ_eq_true_iff (F : Formula) {u : ℕ} + (c : ClauseContext F u) (j : J u) : + validJ F c j = true ↔ + (∀ t, localSatisfies (clauseAt F (c t)) (j t) = true) ∧ + ∀ t t' s s', nameAt (clauseAt F (c t)) s = nameAt (clauseAt F (c t')) s' → + answerAt (j t) s = answerAt (j t') s' := by + simp [validJ] + +theorem validJ_satisfies (F : Formula) {u : ℕ} (c : ClauseContext F u) + (j : J u) (hj : validJ F c j = true) (t : Fin u) : + localSatisfies (clauseAt F (c t)) (j t) = true := + ((validJ_eq_true_iff F c j).mp hj).1 t + +theorem validJ_consistent (F : Formula) {u : ℕ} (c : ClauseContext F u) + (j : J u) (hj : validJ F c j = true) (t : Fin u) (s : Slot) + (t' : Fin u) (s' : Slot) + (hname : nameAt (clauseAt F (c t)) s = nameAt (clauseAt F (c t')) s') : + answerAt (j t) s = answerAt (j t') s' := + ((validJ_eq_true_iff F c j).mp hj).2 t t' s s' hname + +theorem validJ_localConsistent (F : Formula) {u : ℕ} (c : ClauseContext F u) + (j : J u) (hj : validJ F c j = true) (t : Fin u) : + localConsistent (clauseAt F (c t)) (j t) = true := by + apply (localConsistent_eq_true_iff _ _).mpr + intro s s' hs + exact validJ_consistent F c j hj t s t s' hs + +def canonicalSlot {n : ℕ} (clause : Clause n) (v : Fin n) : Slot := + if nameAt clause .first = v then .first + else if nameAt clause .second = v then .second else .third + +theorem canonicalSlot_name {n : ℕ} (clause : Clause n) (v : Fin n) + (hv : ∃ s, nameAt clause s = v) : nameAt clause (canonicalSlot clause v) = v := by + by_cases hfirst : nameAt clause .first = v + · simp [canonicalSlot, hfirst] + by_cases hsecond : nameAt clause .second = v + · simp [canonicalSlot, hfirst, hsecond] + obtain ⟨s, hs⟩ := hv + cases s with + | first => exact False.elim (hfirst hs) + | second => exact False.elim (hsecond hs) + | third => simpa [canonicalSlot, hfirst, hsecond] using hs + +def pi (F : Formula) {u : ℕ} (c : ClauseContext F u) (v : VariableContext F u) + (j : J u) : I u := + fun t => answerAt (j t) (canonicalSlot (clauseAt F (c t)) (v t)) + +def sampledVariables (F : Formula) {u : ℕ} (c : ClauseContext F u) + (s : SlotContext u) : VariableContext F u := + fun t => nameAt (clauseAt F (c t)) (s t) + +theorem sampledVariables_supported (F : Formula) {u : ℕ} + (c : ClauseContext F u) (s : SlotContext u) : + ∀ t, ∃ slot, nameAt (clauseAt F (c t)) slot = sampledVariables F c s t := + fun t => ⟨s t, rfl⟩ + +theorem sampled_eq_pi (F : Formula) {u : ℕ} (c : ClauseContext F u) + (v : VariableContext F u) (j : J u) (hj : validJ F c j = true) + (t : Fin u) (s : Slot) (hs : nameAt (clauseAt F (c t)) s = v t) : + answerAt (j t) s = pi F c v j t := by + exact validJ_consistent F c j hj t s t + (canonicalSlot (clauseAt F (c t)) (v t)) + (hs.trans (canonicalSlot_name _ _ ⟨s, hs⟩).symm) + +theorem sampled_answers_eq_of_visible_eq (F : Formula) {u : ℕ} + (c : ClauseContext F u) (s s' : SlotContext u) (j : J u) + (hj : validJ F c j = true) + (hvisible : sampledVariables F c s = sampledVariables F c s') : + (fun t => answerAt (j t) (s t)) = fun t => answerAt (j t) (s' t) := by + funext t + exact validJ_consistent F c j hj t (s t) t (s' t) (congrFun hvisible t) + +def honestJ (F : Formula) {u : ℕ} (c : ClauseContext F u) + (assignment : Fin F.«variables» → Bool) : J u := + fun t => honestAnswer (clauseAt F (c t)) assignment + +def honestI (F : Formula) {u : ℕ} (v : VariableContext F u) + (assignment : Fin F.«variables» → Bool) : I u := + fun t => assignment (v t) + +theorem honestJ_valid (F : Formula) {u : ℕ} (c : ClauseContext F u) + (assignment : Fin F.«variables» → Bool) + (hs : ∀ clause ∈ F.clauses, clause.eval assignment = true) : + validJ F c (honestJ F c assignment) = true := by + apply (validJ_eq_true_iff F c _).mpr + constructor + · intro t + exact (honest_satisfies _ assignment).trans (hs _ (List.getElem_mem _)) + · intro t t' s s' hname + simp only [honestJ, honest_answerAt] + exact congrArg assignment hname + +theorem pi_honest (F : Formula) {u : ℕ} (c : ClauseContext F u) + (v : VariableContext F u) (assignment : Fin F.«variables» → Bool) + (hsupport : ∀ t, ∃ s, nameAt (clauseAt F (c t)) s = v t) : + pi F c v (honestJ F c assignment) = honestI F v assignment := by + funext t + exact (honest_answerAt _ assignment _).trans + (congrArg assignment (canonicalSlot_name _ _ (hsupport t))) + +theorem pi_honest_sampled (F : Formula) {u : ℕ} (c : ClauseContext F u) + (s : SlotContext u) (assignment : Fin F.«variables» → Bool) : + pi F c (sampledVariables F c s) (honestJ F c assignment) = + honestI F (sampledVariables F c s) assignment := + pi_honest F c _ assignment (sampledVariables_supported F c s) + +def baseAccepts (F : Formula) (v : Fin F.«variables») (c : Fin F.clauses.length) + (i : Bool) (j : ClauseAnswer) : Bool := + decide (localSatisfies (clauseAt F c) j = true ∧ + localConsistent (clauseAt F c) j = true ∧ + answerAt j (canonicalSlot (clauseAt F c) v) = i) + +@[simp] theorem baseAccepts_eq_true_iff (F : Formula) (v : Fin F.«variables») + (c : Fin F.clauses.length) (i : Bool) (j : ClauseAnswer) : + baseAccepts F v c i j = true ↔ + localSatisfies (clauseAt F c) j = true ∧ + localConsistent (clauseAt F c) j = true ∧ + answerAt j (canonicalSlot (clauseAt F c) v) = i := by + simp [baseAccepts] + +theorem projection_implies_coordinate_accepts (F : Formula) {u : ℕ} + (c : ClauseContext F u) (v : VariableContext F u) (i : I u) (j : J u) + (hj : validJ F c j = true) (hpi : pi F c v j = i) (t : Fin u) : + baseAccepts F (v t) (c t) (i t) (j t) = true := by + exact (baseAccepts_eq_true_iff F _ _ _ _).mpr + ⟨validJ_satisfies F c j hj t, validJ_localConsistent F c j hj t, congrFun hpi t⟩ + +theorem baseAccepts_implies_sampled (F : Formula) (c : Fin F.clauses.length) + (s : Slot) (i : Bool) (j : ClauseAnswer) + (h : baseAccepts F (nameAt (clauseAt F c) s) c i j = true) : + (localSatisfies (clauseAt F c) j && decide (answerAt j s = i)) = true := by + obtain ⟨hsat, hcons, heq⟩ := (baseAccepts_eq_true_iff F _ _ _ _).mp h + have hname := canonicalSlot_name (clauseAt F c) (nameAt (clauseAt F c) s) ⟨s, rfl⟩ + have hans := (localConsistent_eq_true_iff _ _).mp hcons s + (canonicalSlot (clauseAt F c) (nameAt (clauseAt F c) s)) hname.symm + simp [hsat, hans.trans heq] + +theorem projection_implies_sampled_accepts (F : Formula) {u : ℕ} + (c : ClauseContext F u) (s : SlotContext u) (i : I u) (j : J u) + (hj : validJ F c j = true) (hpi : pi F c (sampledVariables F c s) j = i) : + ∀ t, (localSatisfies (clauseAt F (c t)) (j t) && + decide (answerAt (j t) (s t) = i t)) = true := by + intro t + exact baseAccepts_implies_sampled F (c t) (s t) (i t) (j t) + (projection_implies_coordinate_accepts F c _ i j hj hpi t) + +end MinUncutGames.Foundations.Hastad.SourceContexts + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/CompletedSampling.lean b/lean/OAI/Computability/MinUncut/PCP/CompletedSampling.lean new file mode 100644 index 0000000000000000000000000000000000000000..a0a321900ce0722051f2149aae7461cf2e886acc --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/CompletedSampling.lean @@ -0,0 +1,636 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.Overlap + +namespace OAI + +namespace MinUncutGames.Foundations.Repetition.CompletedSampling + +open scoped BigOperators +open Games + +noncomputable section + +section DistributionIdentities + +variable {A B C D : Type*} [Fintype A] [Fintype B] [Fintype C] [Fintype D] + +theorem mixture_pushforward_base (μ : FiniteDistribution A) (f : A → B) + (K : B → FiniteDistribution C) : + (μ.pushforward f).mixture K = μ.mixture (fun a => K (f a)) := by + apply FiniteDistribution.eq_of_weight_eq + intro c + exact FiniteDistribution.expectation_pushforward μ f (fun b => (K b).weight c) + +theorem product_pushforward_eq_mixture_right (μ : FiniteDistribution A) + (ν : FiniteDistribution B) (f : A × B → C) : + (μ.product ν).pushforward f = + ν.mixture (fun b => μ.pushforward (fun a => f (a, b))) := by + classical + apply FiniteDistribution.eq_of_weight_eq + intro c + simp only [FiniteDistribution.pushforward, FiniteDistribution.product, + FiniteDistribution.mixture, Fintype.sum_prod_type] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro b _ + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro a _ + by_cases h : f (a, b) = c <;> simp [h, mul_comm] + +theorem product_product_pushforward_eq_mixture (μ : FiniteDistribution A) + (ν : FiniteDistribution B) (κ : FiniteDistribution C) (f : A → B → C → D) : + (μ.product (ν.product κ)).pushforward (fun z => f z.1 z.2.1 z.2.2) = + (μ.product ν).mixture + (fun z => κ.pushforward (fun c => f z.1 z.2 c)) := by + classical + apply FiniteDistribution.eq_of_weight_eq + intro d + simp only [FiniteDistribution.pushforward, FiniteDistribution.product, + FiniteDistribution.mixture, Fintype.sum_prod_type] + simp only [Finset.mul_sum, mul_ite, mul_zero, mul_assoc] + +theorem mixture_totalVariation_le (μ ν : FiniteDistribution A) + (K : A → FiniteDistribution B) : + (μ.mixture K).totalVariation (ν.mixture K) ≤ μ.totalVariation ν := by + simpa only [FiniteDistribution.totalVariation, FiniteDistribution.mixture, + Information.totalVariation, kernelPushforward] using + totalVariation_kernelPushforward_le μ.weight ν.weight + (fun a => (K a).weight) (fun a => Information.gameLaw_isProbability (K a)) + +end DistributionIdentities + +section Diagonal + +variable {Z S : Type*} [Fintype Z] [Fintype S] + +def diagonalLaw (σ : FiniteDistribution (Z × S)) : FiniteDistribution (Z × S × S) := + Information.toGameLaw (diagonalWeights σ.weight) + (diagonalWeights_isProbability _ (Information.gameLaw_isProbability σ)) + +theorem diagonalLaw_eq_pushforward (σ : FiniteDistribution (Z × S)) : + diagonalLaw σ = σ.pushforward (fun z => (z.1, z.2, z.2)) := by + classical + apply FiniteDistribution.eq_of_weight_eq + rintro ⟨z, a, b⟩ + change diagonalWeights σ.weight (z, a, b) = + (σ.pushforward (fun t => (t.1, t.2, t.2))).weight (z, a, b) + simp only [diagonalWeights, FiniteDistribution.pushforward, + Fintype.sum_prod_type, Prod.mk.injEq] + by_cases hab : a = b + · subst b + simp [ite_and] + · simp [hab, ite_and] + +theorem diagonalLaw_mixture {T : Type*} [Fintype T] + (σ : FiniteDistribution (Z × S)) (K : Z × S × S → FiniteDistribution T) : + (diagonalLaw σ).mixture K = σ.mixture (fun z => K (z.1, z.2, z.2)) := by + rw [diagonalLaw_eq_pushforward, mixture_pushforward_base] + +end Diagonal + +section Completion + +variable {X Y S Γ U V : Type*} + [Fintype X] [Fintype Y] [Fintype S] [Fintype Γ] [Fintype U] [Fintype V] + [DecidableEq X] [DecidableEq Y] [DecidableEq S] + +abbrev Seed (Γ X Y S U V : Type*) := + Γ × KernelSampling.Seed (X × S) (Y × S) U V + +def seedLaw (γ : FiniteDistribution Γ) + (L : X × S → FiniteDistribution U) (R : Y × S → FiniteDistribution V) : + FiniteDistribution (Seed Γ X Y S U V) := + γ.product (KernelSampling.seedLaw L R) + +def left (sL : Γ → X → S) (seed : Seed Γ X Y S U V) (x : X) : U := + KernelSampling.readLeft seed.2 (x, sL seed.1 x) + +def right (sR : Γ → Y → S) (seed : Seed Γ X Y S U V) (y : Y) : V := + KernelSampling.readRight seed.2 (y, sR seed.1 y) + +def completionKernel (L : X × S → FiniteDistribution U) + (R : Y × S → FiniteDistribution V) (z : (X × Y) × S × S) : + FiniteDistribution (U × V) := + (L (z.1.1, z.2.1)).product (R (z.1.2, z.2.2)) + +def outputLaw (μ : FiniteDistribution (X × Y)) (γ : FiniteDistribution Γ) + (sL : Γ → X → S) (sR : Γ → Y → S) + (L : X × S → FiniteDistribution U) (R : Y × S → FiniteDistribution V) : + FiniteDistribution (U × V) := + (seedLaw γ L R).mixture (fun seed => + μ.pushforward (fun q => (left sL seed q.1, right sR seed q.2))) + +theorem outputLaw_eq_product_pushforward + (μ : FiniteDistribution (X × Y)) (γ : FiniteDistribution Γ) + (sL : Γ → X → S) (sR : Γ → Y → S) + (L : X × S → FiniteDistribution U) (R : Y × S → FiniteDistribution V) : + outputLaw μ γ sL sR L R = + (μ.product (seedLaw γ L R)).pushforward + (fun z => (left sL z.2 z.1.1, right sR z.2 z.1.2)) := by + exact (product_pushforward_eq_mixture_right μ (seedLaw γ L R) + (fun z : (X × Y) × Seed Γ X Y S U V => + (left sL z.2 z.1.1, right sR z.2 z.1.2))).symm + +theorem outputLaw_eq_mixture + (μ : FiniteDistribution (X × Y)) (γ : FiniteDistribution Γ) + (sL : Γ → X → S) (sR : Γ → Y → S) + (L : X × S → FiniteDistribution U) (R : Y × S → FiniteDistribution V) : + outputLaw μ γ sL sR L R = + (sharedOutputLaw μ γ sL sR).mixture (completionKernel L R) := by + calc + outputLaw μ γ sL sR L R = + (μ.product γ).mixture (fun z => + (KernelSampling.seedLaw L R).pushforward (fun table => + (KernelSampling.readLeft table (z.1.1, sL z.2 z.1.1), + KernelSampling.readRight table (z.1.2, sR z.2 z.1.2)))) := by + rw [outputLaw_eq_product_pushforward] + exact product_product_pushforward_eq_mixture μ γ (KernelSampling.seedLaw L R) + (fun q seed table => + (KernelSampling.readLeft table (q.1, sL seed q.1), + KernelSampling.readRight table (q.2, sR seed q.2))) + _ = (μ.product γ).mixture (fun z => + completionKernel L R (z.1, sL z.2 z.1.1, sR z.2 z.1.2)) := by + apply congrArg ((μ.product γ).mixture) + funext z + exact KernelSampling.read_joint_pushforward L R + (z.1.1, sL z.2 z.1.1) (z.1.2, sR z.2 z.1.2) + _ = (sharedOutputLaw μ γ sL sR).mixture (completionKernel L R) := by + exact (mixture_pushforward_base (μ.product γ) + (fun z => (z.1, sL z.2 z.1.1, sR z.2 z.1.2)) (completionKernel L R)).symm + +omit [DecidableEq X] [DecidableEq Y] [DecidableEq S] in + +theorem diagonalLaw_completion_mixture + (σ : FiniteDistribution ((X × Y) × S)) + (L : X × S → FiniteDistribution U) (R : Y × S → FiniteDistribution V) : + (diagonalLaw σ).mixture (completionKernel L R) = + σ.mixture (fun z => (L (z.1.1, z.2)).product (R (z.1.2, z.2))) := by + exact diagonalLaw_mixture σ (completionKernel L R) + +theorem outputLaw_totalVariation_le + (μ : FiniteDistribution (X × Y)) (γ : FiniteDistribution Γ) + (sL : Γ → X → S) (sR : Γ → Y → S) + (L : X × S → FiniteDistribution U) (R : Y × S → FiniteDistribution V) + (σ : FiniteDistribution ((X × Y) × S)) : + (outputLaw μ γ sL sR L R).totalVariation + (σ.mixture (fun z => (L (z.1.1, z.2)).product (R (z.1.2, z.2)))) ≤ + (sharedOutputLaw μ γ sL sR).totalVariation (diagonalLaw σ) := by + rw [outputLaw_eq_mixture, ← diagonalLaw_completion_mixture σ L R] + exact mixture_totalVariation_le _ _ (completionKernel L R) + +end Completion + +variable {I X Y S Γ : Type*} + [Fintype I] [Fintype X] [Fintype Y] [Fintype S] [Fintype Γ] + [DecidableEq I] [DecidableEq X] [DecidableEq Y] [DecidableEq S] + +def coordinateLeft (j : I) (sL : Γ → X → S) + (seed : Seed Γ X Y S (I → X) (I → Y)) (x : X) : I → X := + KernelSampling.completedLeft j seed.2 (x, sL seed.1 x) + +def coordinateRight (j : I) (sR : Γ → Y → S) + (seed : Seed Γ X Y S (I → X) (I → Y)) (y : Y) : I → Y := + KernelSampling.completedRight j seed.2 (y, sR seed.1 y) + +omit [Fintype I] [Fintype X] [Fintype Y] [Fintype S] [Fintype Γ] + [DecidableEq X] [DecidableEq Y] [DecidableEq S] in +@[simp] theorem coordinateLeft_preserves (j : I) (sL : Γ → X → S) + (seed : Seed Γ X Y S (I → X) (I → Y)) (x : X) : + coordinateLeft j sL seed x j = x := by + simp [coordinateLeft] + +omit [Fintype I] [Fintype X] [Fintype Y] [Fintype S] [Fintype Γ] + [DecidableEq X] [DecidableEq Y] [DecidableEq S] in +@[simp] theorem coordinateRight_preserves (j : I) (sR : Γ → Y → S) + (seed : Seed Γ X Y S (I → X) (I → Y)) (y : Y) : + coordinateRight j sR seed y j = y := by + simp [coordinateRight] + +def coordinateOutputLaw (μ : FiniteDistribution (X × Y)) (γ : FiniteDistribution Γ) + (j : I) (sL : Γ → X → S) (sR : Γ → Y → S) + (L : X × S → FiniteDistribution (I → X)) + (R : Y × S → FiniteDistribution (I → Y)) : + FiniteDistribution ((I → X) × (I → Y)) := + (seedLaw γ L R).mixture (fun seed => μ.pushforward + (fun q => (coordinateLeft j sL seed q.1, coordinateRight j sR seed q.2))) + +theorem coordinateOutputLaw_eq_mixture + (μ : FiniteDistribution (X × Y)) (γ : FiniteDistribution Γ) + (j : I) (sL : Γ → X → S) (sR : Γ → Y → S) + (L : X × S → FiniteDistribution (I → X)) + (R : Y × S → FiniteDistribution (I → Y)) + (hL : ∀ q xs, (L q).weight xs ≠ 0 → xs j = q.1) + (hR : ∀ q ys, (R q).weight ys ≠ 0 → ys j = q.1) : + coordinateOutputLaw μ γ j sL sR L R = + (sharedOutputLaw μ γ sL sR).mixture (completionKernel L R) := by + calc + coordinateOutputLaw μ γ j sL sR L R = + (μ.product (seedLaw γ L R)).pushforward + (fun z => (coordinateLeft j sL z.2 z.1.1, + coordinateRight j sR z.2 z.1.2)) := by + exact (product_pushforward_eq_mixture_right μ (seedLaw γ L R) + (fun z : (X × Y) × Seed Γ X Y S (I → X) (I → Y) => + (coordinateLeft j sL z.2 z.1.1, coordinateRight j sR z.2 z.1.2))).symm + _ = (μ.product γ).mixture (fun z => + (KernelSampling.seedLaw L R).pushforward (fun table => + (KernelSampling.completedLeft j table (z.1.1, sL z.2 z.1.1), + KernelSampling.completedRight j table (z.1.2, sR z.2 z.1.2)))) := by + exact product_product_pushforward_eq_mixture μ γ (KernelSampling.seedLaw L R) + (fun q seed table => + (KernelSampling.completedLeft j table (q.1, sL seed q.1), + KernelSampling.completedRight j table (q.2, sR seed q.2))) + _ = (μ.product γ).mixture (fun z => + completionKernel L R (z.1, sL z.2 z.1.1, sR z.2 z.1.2)) := by + apply congrArg ((μ.product γ).mixture) + funext z + exact KernelSampling.completed_joint_pushforward L R j hL hR + (z.1.1, sL z.2 z.1.1) (z.1.2, sR z.2 z.1.2) + _ = (sharedOutputLaw μ γ sL sR).mixture (completionKernel L R) := by + exact (mixture_pushforward_base (μ.product γ) + (fun z => (z.1, sL z.2 z.1.1, sR z.2 z.1.2)) (completionKernel L R)).symm + +theorem coordinateOutputLaw_eq_outputLaw + (μ : FiniteDistribution (X × Y)) (γ : FiniteDistribution Γ) + (j : I) (sL : Γ → X → S) (sR : Γ → Y → S) + (L : X × S → FiniteDistribution (I → X)) + (R : Y × S → FiniteDistribution (I → Y)) + (hL : ∀ q xs, (L q).weight xs ≠ 0 → xs j = q.1) + (hR : ∀ q ys, (R q).weight ys ≠ 0 → ys j = q.1) : + coordinateOutputLaw μ γ j sL sR L R = outputLaw μ γ sL sR L R := by + rw [coordinateOutputLaw_eq_mixture μ γ j sL sR L R hL hR, outputLaw_eq_mixture] + +theorem coordinateOutputLaw_totalVariation_le + (μ : FiniteDistribution (X × Y)) (γ : FiniteDistribution Γ) + (j : I) (sL : Γ → X → S) (sR : Γ → Y → S) + (L : X × S → FiniteDistribution (I → X)) + (R : Y × S → FiniteDistribution (I → Y)) + (hL : ∀ q xs, (L q).weight xs ≠ 0 → xs j = q.1) + (hR : ∀ q ys, (R q).weight ys ≠ 0 → ys j = q.1) + (σ : FiniteDistribution ((X × Y) × S)) : + (coordinateOutputLaw μ γ j sL sR L R).totalVariation + (σ.mixture (fun z => (L (z.1.1, z.2)).product (R (z.1.2, z.2)))) ≤ + (sharedOutputLaw μ γ sL sR).totalVariation (diagonalLaw σ) := by + rw [coordinateOutputLaw_eq_outputLaw μ γ j sL sR L R hL hR] + exact outputLaw_totalVariation_le μ γ sL sR L R σ + +end + +end MinUncutGames.Foundations.Repetition.CompletedSampling + +namespace MinUncutGames.Foundations.Games.Game + +noncomputable section + +variable {Q₁ Q₂ A₁ A₂ R₁ R₂ B₁ B₂ Seed : Type*} + [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂] + [Fintype R₁] [Fintype R₂] [Fintype B₁] [Fintype B₂] [Fintype Seed] + [Nonempty A₁] [Nonempty A₂] + +def localEmbeddingLaw (G : Game Q₁ Q₂ A₁ A₂) + (seedLaw : FiniteDistribution Seed) + (left : Seed → Q₁ → R₁) (right : Seed → Q₂ → R₂) : + FiniteDistribution (R₁ × R₂) := + seedLaw.mixture fun seed => + G.questions.pushforward fun q => (left seed q.1, right seed q.2) + +theorem success_le_value_add_embedding_distance + (G : Game Q₁ Q₂ A₁ A₂) (H : Game R₁ R₂ B₁ B₂) + (seedLaw : FiniteDistribution Seed) + (left : Seed → Q₁ → R₁) (right : Seed → Q₂ → R₂) + (answerLeft : Seed → Q₁ → B₁ → A₁) + (answerRight : Seed → Q₂ → B₂ → A₂) + (acceptance : ∀ seed x y a b, + H.accepts (left seed x) (right seed y) a b = true → + G.accepts x y (answerLeft seed x a) (answerRight seed y b) = true) + (strategy : Strategy R₁ R₂ B₁ B₂) : + H.success strategy ≤ G.value + + H.questions.totalVariation (G.localEmbeddingLaw seedLaw left right) := by + have localBound (seed : Seed) : + (G.questions.pushforward (fun q => (left seed q.1, right seed q.2))).probability + (H.wins strategy) ≤ G.value := by + let embedded : Game R₁ R₂ B₁ B₂ := + { questions := G.questions.pushforward fun q => (left seed q.1, right seed q.2) + accepts := H.accepts } + change embedded.success strategy ≤ G.value + exact (G.success_le_of_localSimulation embedded (left seed) (right seed) + (answerLeft seed) (answerRight seed) rfl (acceptance seed) strategy).trans + (G.success_le_value _) + have mixtureBound : + (G.localEmbeddingLaw seedLaw left right).probability (H.wins strategy) ≤ G.value := + seedLaw.probability_mixture_le _ _ _ localBound + exact (H.questions.probability_le_add_totalVariation + (G.localEmbeddingLaw seedLaw left right) (H.wins strategy)).trans + (add_le_add mixtureBound (le_refl _)) + +def coordinateGame (G : Game Q₁ Q₂ A₁ A₂) {n : Nat} (coordinate : Fin n) + (law : FiniteDistribution ((Fin n → Q₁) × (Fin n → Q₂))) : + Game (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂) where + questions := law + accepts x y a b := G.accepts (x coordinate) (y coordinate) (a coordinate) (b coordinate) + +theorem coordinate_probability_le_value_add_embedding_distance + (G : Game Q₁ Q₂ A₁ A₂) {n : Nat} (coordinate : Fin n) + (law : FiniteDistribution ((Fin n → Q₁) × (Fin n → Q₂))) + (seedLaw : FiniteDistribution Seed) + (left : Seed → Q₁ → Fin n → Q₁) (right : Seed → Q₂ → Fin n → Q₂) + (left_preserves : ∀ seed x, left seed x coordinate = x) + (right_preserves : ∀ seed y, right seed y coordinate = y) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) : + law.probability (G.coordinateWin strategy coordinate) ≤ G.value + + law.totalVariation (G.localEmbeddingLaw seedLaw left right) := by + apply G.success_le_value_add_embedding_distance (G.coordinateGame coordinate law) + seedLaw left right (fun _ _ a => a coordinate) (fun _ _ b => b coordinate) + intro seed x y a b h + simpa only [coordinateGame, left_preserves, right_preserves] using h + +theorem coordinate_probability_le_value_of_approximate_embeddings + {SeedFamily : Nat → Type*} [∀ t, Fintype (SeedFamily t)] + (G : Game Q₁ Q₂ A₁ A₂) {n : Nat} (coordinate : Fin n) + (law : FiniteDistribution ((Fin n → Q₁) × (Fin n → Q₂))) + (seedLaw : (t : Nat) → FiniteDistribution (SeedFamily t)) + (left : (t : Nat) → SeedFamily t → Q₁ → Fin n → Q₁) + (right : (t : Nat) → SeedFamily t → Q₂ → Fin n → Q₂) + (left_preserves : ∀ t seed x, left t seed x coordinate = x) + (right_preserves : ∀ t seed y, right t seed y coordinate = y) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (distance : ℝ) + (close : ∀ η : ℝ, 0 < η → ∃ t, + law.totalVariation (G.localEmbeddingLaw (seedLaw t) (left t) (right t)) ≤ + distance + η) : + law.probability (G.coordinateWin strategy coordinate) ≤ G.value + distance := by + by_contra h + have gap : 0 < law.probability (G.coordinateWin strategy coordinate) - + (G.value + distance) := sub_pos.mpr (lt_of_not_ge h) + obtain ⟨t, ht⟩ := close + ((law.probability (G.coordinateWin strategy coordinate) - (G.value + distance)) / 2) + (by linarith) + have bound := G.coordinate_probability_le_value_add_embedding_distance coordinate law + (seedLaw t) (left t) (right t) (left_preserves t) (right_preserves t) strategy + linarith + +end +end MinUncutGames.Foundations.Games.Game + +namespace MinUncutGames.Foundations.Repetition +open scoped BigOperators +open Games CorrelatedSampling +noncomputable section +variable {Q₁ Q₂ A₁ A₂ S : Type*} + [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂] [Fintype S] + [Nonempty A₁] [Nonempty A₂] [Nonempty S] + [DecidableEq Q₁] [DecidableEq Q₂] [DecidableEq S] {n : Nat} + +theorem coordinate_probability_le_value_of_local_completion + (G : Game Q₁ Q₂ A₁ A₂) (j : Fin n) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (σ : FiniteDistribution ((Q₁ × Q₂) × S)) + (profileL : Q₁ → FiniteDistribution S) (profileR : Q₂ → FiniteDistribution S) + (completionL : Q₁ × S → FiniteDistribution (Fin n → Q₁)) + (completionR : Q₂ × S → FiniteDistribution (Fin n → Q₂)) + (supportL : ∀ q xs, (completionL q).weight xs ≠ 0 → xs j = q.1) + (supportR : ∀ q ys, (completionR q).weight ys ≠ 0 → ys j = q.1) + (fallback : S) : + (σ.mixture (fun z => (completionL (z.1.1,z.2)).product + (completionR (z.1.2,z.2)))).probability (G.coordinateWin strategy j) ≤ + G.value + + (2 * Information.totalVariation σ.weight + (fun z => G.questions.weight z.1 * (profileL z.1.1).weight z.2) + + 2 * Information.totalVariation σ.weight + (fun z => G.questions.weight z.1 * (profileR z.1.2).weight z.2)) := by + let targetLaw := σ.mixture (fun z => (completionL (z.1.1,z.2)).product (completionR (z.1.2,z.2))) + let δ := 2 * Information.totalVariation σ.weight + (fun z => G.questions.weight z.1 * (profileL z.1.1).weight z.2) + + 2 * Information.totalVariation σ.weight + (fun z => G.questions.weight z.1 * (profileR z.1.2).weight z.2) + change targetLaw.probability (G.coordinateWin strategy j) ≤ G.value + δ + by_contra h + have gap : 0 < targetLaw.probability (G.coordinateWin strategy j) - (G.value + δ) := + sub_pos.mpr (lt_of_not_ge h) + let η := (targetLaw.probability (G.coordinateWin strategy j) - (G.value + δ)) / 2 + have hη : 0 < η := by dsimp [η]; linarith + obtain ⟨N,hN⟩ := samplerOutputLaw_arbitrarily_close σ G.questions profileL profileR fallback η hη + let thresholds := sharedProfileThresholds profileL profileR + let γ := traceSeedLaw (rectangleDistribution (α := S) thresholds) N + let sL := samplerLocal thresholds profileL fallback N + let sR := samplerLocal thresholds profileR fallback N + have hvariation := CompletedSampling.coordinateOutputLaw_totalVariation_le + G.questions γ j sL sR completionL completionR supportL supportR σ + have hclose : (CompletedSampling.coordinateOutputLaw G.questions γ j sL sR completionL completionR).totalVariation targetLaw ≤ δ + η := + hvariation.trans hN + have hsuccess := G.coordinate_probability_le_value_add_embedding_distance j targetLaw + (CompletedSampling.seedLaw γ completionL completionR) + (CompletedSampling.coordinateLeft j sL) (CompletedSampling.coordinateRight j sR) + (CompletedSampling.coordinateLeft_preserves j sL) + (CompletedSampling.coordinateRight_preserves j sR) strategy + have hsym : targetLaw.totalVariation + (G.localEmbeddingLaw (CompletedSampling.seedLaw γ completionL completionR) + (CompletedSampling.coordinateLeft j sL) (CompletedSampling.coordinateRight j sR)) = + (CompletedSampling.coordinateOutputLaw G.questions γ j sL sR completionL completionR).totalVariation targetLaw := by + unfold FiniteDistribution.totalVariation + congr 1 + apply Finset.sum_congr rfl + intro q _ + exact abs_sub_comm _ _ + rw [hsym] at hsuccess + dsimp [η] at hclose + linarith + +end + +noncomputable def logTwo (x : ℝ) : ℝ := Real.log x / Real.log 2 + +@[simp] theorem logTwo_one : logTwo 1 = 0 := by simp [logTwo] + +theorem logTwo_inv_le_of_half_pow_le {p : ℝ} (m : ℕ) + (h : (1 / 2 : ℝ) ^ m ≤ p) : logTwo (1 / p) ≤ m := by + have hp : 0 < p := (pow_pos (by norm_num : (0 : ℝ) < 1 / 2) m).trans_le h + have hlog := Real.log_le_log (pow_pos (by norm_num : (0 : ℝ) < 1 / 2) m) h + have hhalf : Real.log (1 / 2 : ℝ) = -Real.log 2 := by + rw [one_div, Real.log_inv] + rw [Real.log_pow, hhalf] at hlog + unfold logTwo + rw [one_div, Real.log_inv] + apply (div_le_iff₀ (Real.log_pos (by norm_num : (1 : ℝ) < 2))).2 + nlinarith + +theorem contraction_step {v ell : ℝ} {n m : ℕ} {p next : ℝ} + (hv0 : 0 ≤ v) (hv1 : v < 1) (hell : 1 ≤ ell) + (hm : 1 ≤ m) (hmn : m < n) (hp : 0 ≤ p) + (hmono : next ≤ p) + (hprev : p ≤ ((1 + v) / 2) ^ m) + (hcut : 2700 * (m : ℝ) * ell ≤ (1 - v) ^ 2 * ((n : ℝ) - m)) + (hstep : next ≤ p * (v + 15 * Real.sqrt + (((m : ℝ) * ell + logTwo (1 / p)) / ((n : ℝ) - m)))) : + next ≤ ((1 + v) / 2) ^ (m + 1) := by + by_cases hsmall : p ≤ ((1 + v) / 2) ^ (m + 1) + · exact hmono.trans hsmall + have hq : (1 / 2 : ℝ) ≤ (1 + v) / 2 := by linarith + have hhalf : (1 / 2 : ℝ) ^ (m + 1) ≤ p := + (pow_le_pow_left₀ (by norm_num) hq (m + 1)).trans (le_of_not_ge hsmall) + have hlog := logTwo_inv_le_of_half_pow_le (m + 1) hhalf + have hmreal : (1 : ℝ) ≤ m := by exact_mod_cast hm + have hden : 0 < (n : ℝ) - m := by + have hmnreal : (m : ℝ) < n := by exact_mod_cast hmn + linarith + have hmell : (m : ℝ) ≤ (m : ℝ) * ell := by nlinarith + have hbudget : (m : ℝ) * ell + logTwo (1 / p) ≤ 3 * (m : ℝ) * ell := by + simp only [Nat.cast_add, Nat.cast_one] at hlog + nlinarith + have hsqrt : Real.sqrt + (((m : ℝ) * ell + logTwo (1 / p)) / ((n : ℝ) - m)) ≤ (1 - v) / 30 := by + apply (Real.sqrt_le_left (by linarith : 0 ≤ (1 - v) / 30)).2 + apply (div_le_iff₀ hden).2 + nlinarith + have hfactor : v + 15 * Real.sqrt + (((m : ℝ) * ell + logTwo (1 / p)) / ((n : ℝ) - m)) ≤ (1 + v) / 2 := by + linarith + calc + next ≤ p * (v + 15 * Real.sqrt + (((m : ℝ) * ell + logTwo (1 / p)) / ((n : ℝ) - m))) := hstep + _ ≤ p * ((1 + v) / 2) := mul_le_mul_of_nonneg_left hfactor hp + _ ≤ ((1 + v) / 2) ^ m * ((1 + v) / 2) := + mul_le_mul_of_nonneg_right hprev (by linarith) + _ = ((1 + v) / 2) ^ (m + 1) := (pow_succ _ _).symm + +theorem initial_step {v ell next : ℝ} {n : ℕ} + (hstep : next ≤ 1 * (v + 15 * Real.sqrt + (((0 : ℝ) * ell + logTwo (1 / 1)) / ((n : ℝ) - 0)))) : + next ≤ v := by simpa using hstep + +theorem cutoff_step {v ell : ℝ} {n m : ℕ} + (hv0 : 0 ≤ v) (hv1 : v < 1) (hell : 1 ≤ ell) + (hm : (m : ℝ) < (n : ℝ) * (1 - v) ^ 2 / (2925 * ell)) : + 2700 * (m : ℝ) * ell ≤ (1 - v) ^ 2 * ((n : ℝ) - m) := by + have hell0 : 0 < ell := by linarith + have hd : (1 - v) ^ 2 ≤ 1 := by nlinarith + have hmul : (m : ℝ) * (2925 * ell) < (n : ℝ) * (1 - v) ^ 2 := + (lt_div_iff₀ (by positivity : 0 < 2925 * ell)).1 hm + have hdell : (1 - v) ^ 2 ≤ 225 * ell := by linarith + have hprod := mul_le_mul_of_nonneg_left hdell (Nat.cast_nonneg m : (0 : ℝ) ≤ m) + nlinarith + +theorem cutoff_le_length {v ell : ℝ} (n : ℕ) + (hv0 : 0 ≤ v) (hv1 : v < 1) (hell : 1 ≤ ell) : + (n : ℝ) * (1 - v) ^ 2 / (2925 * ell) ≤ n := by + have hell0 : 0 < ell := by linarith + apply (div_le_iff₀ (by positivity : 0 < 2925 * ell)).2 + have hd : (1 - v) ^ 2 ≤ 2925 * ell := by nlinarith + nlinarith [mul_le_mul_of_nonneg_left hd (Nat.cast_nonneg n : (0 : ℝ) ≤ n)] + +def ScalarRecurrence (p : ℕ → ℝ) (n : ℕ) (v ell : ℝ) : Prop := + ∀ m, m < n → p (m + 1) ≤ p m * (v + 15 * Real.sqrt + (((m : ℝ) * ell + logTwo (1 / p m)) / ((n : ℝ) - m))) + +theorem decay_to_cutoff (p : ℕ → ℝ) (n : ℕ) {v ell : ℝ} + (hv0 : 0 ≤ v) (hv1 : v < 1) (hell : 1 ≤ ell) + (hp0 : p 0 = 1) (hpnonneg : ∀ m, 0 ≤ p m) + (hpmono : Antitone p) (hrec : ScalarRecurrence p n v ell) : + p n ≤ ((1 + v) / 2) ^ + ((n : ℝ) * (1 - v) ^ 2 / (2925 * ell)) := by + let T : ℝ := (n : ℝ) * (1 - v) ^ 2 / (2925 * ell) + let M : ℕ := Nat.ceil T + have hMn : M ≤ n := Nat.ceil_le.mpr (cutoff_le_length n hv0 hv1 hell) + have hind : ∀ m, m ≤ M → p m ≤ ((1 + v) / 2) ^ m := by + intro m + induction m with + | zero => intro _; simp [hp0] + | succ m ih => + intro hmM + have hmM' : m < M := Nat.lt_of_succ_le hmM + have hmn : m < n := hmM'.trans_le hMn + have hprev := ih (Nat.le_of_lt hmM') + by_cases hm0 : m = 0 + · subst m + have hinit : p 1 ≤ v := by + have hs := hrec 0 hmn + simpa [hp0] using hs + simpa using hinit.trans (by linarith : v ≤ (1 + v) / 2) + · have hmT : (m : ℝ) < T := Nat.lt_ceil.mp hmM' + exact contraction_step hv0 hv1 hell (Nat.one_le_iff_ne_zero.mpr hm0) + hmn (hpnonneg m) (hpmono (Nat.le_succ m)) hprev + (cutoff_step hv0 hv1 hell hmT) (hrec m hmn) + have hq0 : 0 < (1 + v) / 2 := by linarith + have hq1 : (1 + v) / 2 ≤ 1 := by linarith + calc + p n ≤ p M := hpmono hMn + _ ≤ ((1 + v) / 2) ^ M := hind M le_rfl + _ = ((1 + v) / 2) ^ (M : ℝ) := (Real.rpow_natCast _ _).symm + _ ≤ ((1 + v) / 2) ^ T := + Real.rpow_le_rpow_of_exponent_ge hq0 hq1 (Nat.le_ceil T) + +theorem block_contraction {v : ℝ} (hv0 : 0 ≤ v) (hv1 : v < 1) : + ((1 + v) / 2) ^ ((1 - v) ^ 2 / 2925 : ℝ) ≤ + 1 - (1 - v) ^ 3 / 5850 := by + have hd : (1 - v) ^ 2 ≤ 1 := by nlinarith + have hb := rpow_one_add_le_one_add_mul_self + (s := -(1 - v) / 2) (p := (1 - v) ^ 2 / 2925) + (by linarith) (by positivity) (by nlinarith) + have hbase : 1 + -(1 - v) / 2 = (1 + v) / 2 := by ring + have hrhs : 1 + (1 - v) ^ 2 / 2925 * (-(1 - v) / 2) = + 1 - (1 - v) ^ 3 / 5850 := by ring + rwa [hbase, hrhs] at hb + +theorem scalar_bound_6000 (p : ℕ → ℝ) (n : ℕ) {v ell : ℝ} + (hv0 : 0 ≤ v) (hv1 : v < 1) (hell : 1 ≤ ell) + (hp0 : p 0 = 1) (hpnonneg : ∀ m, 0 ≤ p m) + (hpmono : Antitone p) (hrec : ScalarRecurrence p n v ell) : + p n ≤ (1 - (1 - v) ^ 3 / 6000) ^ ((n : ℝ) / ell) := by + have hell0 : 0 < ell := by linarith + have hq0 : 0 ≤ (1 + v) / 2 := by linarith + have hexp : 0 ≤ (n : ℝ) / ell := by positivity + have hblock := block_contraction hv0 hv1 + have hweak : 1 - (1 - v) ^ 3 / 5850 ≤ 1 - (1 - v) ^ 3 / 6000 := by + have : 0 ≤ (1 - v) ^ 3 := by positivity + nlinarith + calc + p n ≤ ((1 + v) / 2) ^ + ((n : ℝ) * (1 - v) ^ 2 / (2925 * ell)) := + decay_to_cutoff p n hv0 hv1 hell hp0 hpnonneg hpmono hrec + _ = (((1 + v) / 2) ^ ((1 - v) ^ 2 / 2925 : ℝ)) ^ ((n : ℝ) / ell) := by + rw [← Real.rpow_mul hq0] + congr 1 + ring + _ ≤ (1 - (1 - v) ^ 3 / 6000) ^ ((n : ℝ) / ell) := + Real.rpow_le_rpow (Real.rpow_nonneg hq0 _) (hblock.trans hweak) hexp + +noncomputable def incidenceRate : ℝ := 1 - 1 / (100000 * 192 ^ 3) + +theorem incidenceRate_pos : 0 < incidenceRate := by norm_num [incidenceRate] + +theorem incidenceRate_lt_one : incidenceRate < 1 := by norm_num [incidenceRate] + +theorem incidenceRate_fourth : + 1 - (1 / 192 : ℝ) ^ 3 / 6000 ≤ incidenceRate ^ 4 := by + norm_num [incidenceRate] + +theorem incidence_rate_comparison (n : ℕ) : + (1 - (1 / 192 : ℝ) ^ 3 / 6000) ^ ((n : ℝ) / 4) ≤ incidenceRate ^ n := by + calc + (1 - (1 / 192 : ℝ) ^ 3 / 6000) ^ ((n : ℝ) / 4) + ≤ (incidenceRate ^ 4) ^ ((n : ℝ) / 4) := + Real.rpow_le_rpow (by norm_num) incidenceRate_fourth (by positivity) + _ = incidenceRate ^ ((4 : ℝ) * ((n : ℝ) / 4)) := + (Real.rpow_natCast_mul incidenceRate_pos.le 4 ((n : ℝ) / 4)).symm + _ = incidenceRate ^ (n : ℝ) := by congr 1; ring + _ = incidenceRate ^ n := Real.rpow_natCast _ _ + +theorem scalar_incidence_bound (p : ℕ → ℝ) (n : ℕ) {v : ℝ} + (hv : v ≤ 1 - (1 / 192 : ℝ)) + (hp0 : p 0 = 1) (hpnonneg : ∀ m, 0 ≤ p m) + (hpmono : Antitone p) (hrec : ScalarRecurrence p n v 4) : + p n ≤ incidenceRate ^ n := by + have hrec' : ScalarRecurrence p n (1 - (1 / 192 : ℝ)) 4 := by + intro m hm + exact (hrec m hm).trans (mul_le_mul_of_nonneg_left (by linarith) (hpnonneg m)) + have hbound := scalar_bound_6000 p n + (v := 1 - (1 / 192 : ℝ)) (ell := 4) + (by norm_num) (by norm_num) (by norm_num) hp0 hpnonneg hpmono hrec' + norm_num only [sub_sub_cancel] at hbound + have hcomparison := incidence_rate_comparison n + norm_num at hcomparison + exact hbound.trans hcomparison + +end MinUncutGames.Foundations.Repetition + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/Completion.lean b/lean/OAI/Computability/MinUncut/PCP/Completion.lean new file mode 100644 index 0000000000000000000000000000000000000000..7d1748867bfc6dbfb7f26b806acf7de71bffe999 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/Completion.lean @@ -0,0 +1,293 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.ProfileCorrection +import OAI.Computability.MinUncut.Games.TotalVariation + +namespace OAI + +namespace MinUncutGames.Foundations.Repetition + +open scoped BigOperators +open Games +noncomputable section + +variable {X Y : Type*} [Fintype X] [Fintype Y] + +def normalizeOr (w : X → ℝ) (hw : ∀ x, 0 ≤ w x) + (fallback : FiniteDistribution X) : FiniteDistribution X := + if h : 0 < ∑ x, w x then + { weight := normalizedWeight w + nonnegative := (normalizedWeight_isProbability w hw h).1 + normalized := (normalizedWeight_isProbability w hw h).2 } + else fallback + +theorem sum_mul_normalizeOr (w : X → ℝ) (hw : ∀ x, 0 ≤ w x) + (fallback : FiniteDistribution X) (x : X) : + (∑ z, w z) * (normalizeOr w hw fallback).weight x = w x := by + classical + have hs : 0 ≤ ∑ z, w z := Finset.sum_nonneg (fun z _ => hw z) + by_cases h : 0 < ∑ z, w z + · simp only [normalizeOr, dite_eq_left h, normalizedWeight] + field_simp + · have hz : ∑ z, w z = 0 := le_antisymm (le_of_not_gt h) hs + have hx : w x = 0 := by + apply le_antisymm _ (hw x) + have hl := Finset.single_le_sum (fun z _ => hw z) (Finset.mem_univ x) + simpa only [hz] using hl + simp [normalizeOr, hz, hx] + +theorem local_completion_recombination + (left : X → ℝ) (right : Y → ℝ) + (hl : ∀ x, 0 ≤ left x) (hr : ∀ y, 0 ≤ right y) + (defaultLeft : FiniteDistribution X) (defaultRight : FiniteDistribution Y) + (c : ℝ) (x : X) (y : Y) : + (c * (∑ z, left z) * (∑ z, right z)) * + ((normalizeOr left hl defaultLeft).weight x * + (normalizeOr right hr defaultRight).weight y) = c * left x * right y := by + calc + _ = c * ((∑ z, left z) * (normalizeOr left hl defaultLeft).weight x) * + ((∑ z, right z) * (normalizeOr right hr defaultRight).weight y) := by ring + _ = _ := by rw [sum_mul_normalizeOr, sum_mul_normalizeOr] + +theorem factorized_completion_row + (left : X → ℝ) (right : Y → ℝ) + (hl : ∀ x, 0 ≤ left x) (hr : ∀ y, 0 ≤ right y) + (defaultLeft : FiniteDistribution X) (defaultRight : FiniteDistribution Y) + (c : ℝ) (xy : X × Y) : + (∑ z : X × Y, c * left z.1 * right z.2) * + ((normalizeOr left hl defaultLeft).product + (normalizeOr right hr defaultRight)).weight xy = c * left xy.1 * right xy.2 := by + have hm : (∑ z : X × Y, c * left z.1 * right z.2) = + c * (∑ z, left z) * (∑ z, right z) := by + simp_rw [mul_assoc, ← Finset.mul_sum] + rw [productWeight_mass] + rw [hm] + exact local_completion_recombination left right hl hr defaultLeft defaultRight c xy.1 xy.2 + +end +end MinUncutGames.Foundations.Repetition + +namespace MinUncutGames.Foundations.Repetition +open scoped BigOperators +open Games Information +noncomputable section + +variable {X Y : Type*} [Fintype X] [Fintype Y] [DecidableEq X] [DecidableEq Y] + +def revealEndpoint (q : X × Y) (side : Bool) : X ⊕ Y := + if side then Sum.inr q.2 else Sum.inl q.1 + +def revealLaw (μ : FiniteDistribution (X × Y)) : + FiniteDistribution ((X × Y) × (X ⊕ Y)) := + (μ.product (FiniteDistribution.uniform Bool)).pushforward + (fun z => (z.1, revealEndpoint z.1 z.2)) + +theorem revealLaw_weight (μ : FiniteDistribution (X × Y)) (q : X × Y) (r : X ⊕ Y) : + (revealLaw μ).weight (q,r) = + (if r = Sum.inl q.1 then μ.weight q / 2 else 0) + + (if r = Sum.inr q.2 then μ.weight q / 2 else 0) := by + classical + rcases q with ⟨x,y⟩ + simp only [revealLaw, FiniteDistribution.pushforward, FiniteDistribution.product, + Fintype.sum_prod_type, Prod.mk.injEq, ite_and] + simp [revealEndpoint, FiniteDistribution.uniform, div_eq_mul_inv, add_comm, eq_comm] + +def revealFirstLaw (μ : FiniteDistribution (X × Y)) : + FiniteDistribution ((X ⊕ Y) × (X × Y)) := + (revealLaw μ).transport (Equiv.prodComm _ _) + +omit [DecidableEq X] [DecidableEq Y] in +@[simp] theorem revealFirstLaw_weight (μ : FiniteDistribution (X × Y)) + (r : X ⊕ Y) (q : X × Y) : + (revealFirstLaw μ).weight (r,q) = (revealLaw μ).weight (q,r) := rfl + +def revealFallback (μ : FiniteDistribution (X × Y)) (r : X ⊕ Y) : + FiniteDistribution (X × Y) := + match r with + | Sum.inl x => μ.pushforward (fun q => (x,q.2)) + | Sum.inr y => μ.pushforward (fun q => (q.1,y)) + +def revealProfile (μ : FiniteDistribution (X × Y)) (r : X ⊕ Y) : + FiniteDistribution (X × Y) := + gameConditionalKernel (revealFirstLaw μ) (revealFallback μ r) r + +theorem revealProfile_inl_support (μ : FiniteDistribution (X × Y)) + (x : X) (q : X × Y) (h : q.1 ≠ x) : + (revealProfile μ (Sum.inl x)).weight q = 0 := by + classical + rcases q with ⟨x',y⟩ + dsimp at h + simp only [revealProfile, gameConditionalKernel, toGameLaw, conditionalKernel] + split + · simp [revealFallback, FiniteDistribution.pushforward, Fintype.sum_prod_type, + Prod.mk.injEq, Ne.symm h] + · simp [revealLaw_weight, Ne.symm h] + +theorem revealProfile_inr_support (μ : FiniteDistribution (X × Y)) + (y : Y) (q : X × Y) (h : q.2 ≠ y) : + (revealProfile μ (Sum.inr y)).weight q = 0 := by + classical + rcases q with ⟨x,y'⟩ + dsimp at h + simp only [revealProfile, gameConditionalKernel, toGameLaw, conditionalKernel] + split + · simp [revealFallback, FiniteDistribution.pushforward, Fintype.sum_prod_type, + Prod.mk.injEq, Ne.symm h] + · simp [revealLaw_weight, Ne.symm h] + +def revealInputLaw (μ : FiniteDistribution (X × Y)) : FiniteDistribution (X ⊕ Y) := + (revealLaw μ).pushforward Prod.snd + +theorem revealInputLaw_weight (μ : FiniteDistribution (X × Y)) (r : X ⊕ Y) : + (revealInputLaw μ).weight r = firstMarginal (revealFirstLaw μ).weight r := by + classical + cases r <;> + simp [revealInputLaw, FiniteDistribution.pushforward, firstMarginal, Fintype.sum_prod_type] + +theorem reveal_profile_recombination (μ : FiniteDistribution (X × Y)) + (r : X ⊕ Y) (q : X × Y) : + (revealInputLaw μ).weight r * (revealProfile μ r).weight q = + (revealLaw μ).weight (q,r) := by + rw [revealInputLaw_weight] + exact gameConditionalKernel_recombine (revealFirstLaw μ) (revealFallback μ r) r q + +theorem reveal_profile_inl_recombination (μ : FiniteDistribution (X × Y)) + (x : X) (q : X × Y) : + (revealInputLaw μ).weight (Sum.inl x) * (revealProfile μ (Sum.inl x)).weight q = + if x = q.1 then μ.weight q / 2 else 0 := by + rw [reveal_profile_recombination, revealLaw_weight] + simp + +theorem reveal_profile_inr_recombination (μ : FiniteDistribution (X × Y)) + (y : Y) (q : X × Y) : + (revealInputLaw μ).weight (Sum.inr y) * (revealProfile μ (Sum.inr y)).weight q = + if y = q.2 then μ.weight q / 2 else 0 := by + rw [reveal_profile_recombination, revealLaw_weight] + simp + +theorem revealInputLaw_inl (μ : FiniteDistribution (X × Y)) (x : X) : + (revealInputLaw μ).weight (Sum.inl x) = (∑ y, μ.weight (x,y)) / 2 := by + classical + rw [revealInputLaw_weight] + simp [firstMarginal, Fintype.sum_prod_type, revealLaw_weight, div_eq_mul_inv] + rw [Finset.sum_comm] + simp [← Finset.sum_mul] + +theorem revealInputLaw_inr (μ : FiniteDistribution (X × Y)) (y : Y) : + (revealInputLaw μ).weight (Sum.inr y) = (∑ x, μ.weight (x,y)) / 2 := by + classical + rw [revealInputLaw_weight] + simp [firstMarginal, Fintype.sum_prod_type, revealLaw_weight, + div_eq_mul_inv, ← Finset.sum_mul] + +theorem revealProfile_inl_diagonal (μ : FiniteDistribution (X × Y)) (x : X) (y : Y) : + (revealProfile μ (Sum.inl x)).weight (x,y) = + conditionalKernel μ.weight (μ.pushforward Prod.snd).weight x y := by + classical + have hm : firstMarginal (revealFirstLaw μ).weight (Sum.inl x) = + firstMarginal μ.weight x / 2 := by + rw [← revealInputLaw_weight, revealInputLaw_inl] + rfl + have hf : (revealFallback μ (Sum.inl x)).weight (x,y) = + (μ.pushforward Prod.snd).weight y := by + simp [revealFallback, FiniteDistribution.pushforward, Prod.mk.injEq] + apply Finset.sum_congr rfl + intro q _ + by_cases hq : q.2 = y <;> simp [hq] + simp only [revealProfile, gameConditionalKernel, toGameLaw, conditionalKernel, hm] + by_cases h : firstMarginal μ.weight x = 0 + · simpa [h] using hf + · have hh : firstMarginal μ.weight x / 2 ≠ 0 := div_ne_zero h (by norm_num) + simp only [ite_eq_right h, ite_eq_right hh, revealFirstLaw_weight, revealLaw_weight, + ite_true, Sum.inl_ne_inr, ite_false, add_zero] + field_simp + +theorem revealProfile_inr_diagonal (μ : FiniteDistribution (X × Y)) (x : X) (y : Y) : + (revealProfile μ (Sum.inr y)).weight (x,y) = + conditionalKernel (μ.transport (Equiv.prodComm X Y)).weight + (μ.pushforward Prod.fst).weight y x := by + classical + have hm : firstMarginal (revealFirstLaw μ).weight (Sum.inr y) = + firstMarginal (μ.transport (Equiv.prodComm X Y)).weight y / 2 := by + rw [← revealInputLaw_weight, revealInputLaw_inr] + rfl + have hf : (revealFallback μ (Sum.inr y)).weight (x,y) = + (μ.pushforward Prod.fst).weight x := by + simp [revealFallback, FiniteDistribution.pushforward, Prod.mk.injEq] + apply Finset.sum_congr rfl + intro q _ + by_cases hq : q.1 = x <;> simp [hq] + simp only [revealProfile, gameConditionalKernel, toGameLaw, conditionalKernel, hm] + by_cases h : firstMarginal (μ.transport (Equiv.prodComm X Y)).weight y = 0 + · simpa [h] using hf + · have hh : firstMarginal (μ.transport (Equiv.prodComm X Y)).weight y / 2 ≠ 0 := + div_ne_zero h (by norm_num) + simp only [ite_eq_right h, ite_eq_right hh, revealFirstLaw_weight, revealLaw_weight, + ite_true, Sum.inr_ne_inl, ite_false, zero_add] + change (μ.weight (x,y) / 2) / (firstMarginal (μ.transport (Equiv.prodComm X Y)).weight y / 2) = + μ.weight (x,y) / firstMarginal (μ.transport (Equiv.prodComm X Y)).weight y + field_simp + +theorem revealLaw_sum_left (μ : FiniteDistribution (X × Y)) (q : X × Y) : + (∑ x, (revealLaw μ).weight (q, Sum.inl x)) = μ.weight q / 2 := by + classical + simp [revealLaw_weight] + +theorem revealLaw_sum_right (μ : FiniteDistribution (X × Y)) (q : X × Y) : + (∑ y, (revealLaw μ).weight (q, Sum.inr y)) = μ.weight q / 2 := by + classical + simp [revealLaw_weight] + +theorem revealLaw_forget (μ : FiniteDistribution (X × Y)) : + (revealLaw μ).pushforward Prod.fst = μ := by + classical + apply FiniteDistribution.eq_of_weight_eq + intro q + rcases q with ⟨x,y⟩ + simp [FiniteDistribution.pushforward, Fintype.sum_prod_type, + Finset.sum_ite_irrel, revealLaw_weight] + +theorem reveal_product_factorization {ι : Type*} [Fintype ι] + (μ : FiniteDistribution (X × Y)) (r : ι → X ⊕ Y) (q : ι → X × Y) : + (∏ i, (revealInputLaw μ).weight (r i)) * + (∏ i, (revealProfile μ (r i)).weight (q i)) = + ∏ i, (revealLaw μ).weight (q i,r i) := by + rw [← Finset.prod_mul_distrib] + apply Finset.prod_congr rfl + intro i _ + exact reveal_profile_recombination μ (r i) (q i) + +theorem reveal_product_forget {ι : Type*} [Fintype ι] [DecidableEq ι] + (μ : FiniteDistribution (X × Y)) (q : ι → X × Y) : + (∑ r : ι → X ⊕ Y, + (∏ i, (revealInputLaw μ).weight (r i)) * + (∏ i, (revealProfile μ (r i)).weight (q i))) = + ∏ i, μ.weight (q i) := by + classical + simp_rw [reveal_product_factorization] + calc + _ = ∏ i, ∑ r : X ⊕ Y, (revealLaw μ).weight (q i,r) := + (Fintype.prod_sum (fun (i : ι) (r : X ⊕ Y) => (revealLaw μ).weight (q i,r))).symm + _ = _ := by + apply Finset.prod_congr rfl + intro i _ + rw [Fintype.sum_sum_type, revealLaw_sum_left, revealLaw_sum_right] + ring + +theorem reveal_product_expectation {ι : Type*} [Fintype ι] [DecidableEq ι] + (μ : FiniteDistribution (X × Y)) (f : (ι → X × Y) → ℝ) : + (∑ r : ι → X ⊕ Y, + (∏ i, (revealInputLaw μ).weight (r i)) * + ∑ q : ι → X × Y, (∏ i, (revealProfile μ (r i)).weight (q i)) * f q) = + ∑ q : ι → X × Y, (∏ i, μ.weight (q i)) * f q := by + classical + simp_rw [Finset.mul_sum] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro q _ + simp_rw [← mul_assoc, ← Finset.sum_mul] + rw [reveal_product_forget] + +end +end MinUncutGames.Foundations.Repetition + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/ContextClear.lean b/lean/OAI/Computability/MinUncut/PCP/ContextClear.lean new file mode 100644 index 0000000000000000000000000000000000000000..303ea66008b2add4cfdc4748cc5d0faa96f84ed1 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/ContextClear.lean @@ -0,0 +1,352 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.ContextLoad +import OAI.Computability.MinUncut.Machines.MachineFiniteSequence + +namespace OAI + +namespace MinUncutGames.Foundations.Hastad.SourceContextClear + +open Turing Complexity MachineComposition + +abbrev Tape := SourceContextLoad.Tape + +variable {u : Nat} {Extra : Type} + +def fieldAt (i : Fin (u * 6)) : Tape u Extra := + .field (finProdFinEquiv.symm i).1 (finProdFinEquiv.symm i).2 + +def fields : List (Tape u Extra) := List.ofFn fieldAt + +theorem fieldAt_injective : Function.Injective (fieldAt (u := u) (Extra := Extra)) := by + intro i j h + have hpair := SourceContextLoad.Tape.field.inj h + have hp : finProdFinEquiv.symm i = finProdFinEquiv.symm j := + Prod.ext hpair.1 hpair.2 + exact finProdFinEquiv.symm.injective hp + +@[simp] theorem fields_length : (fields (u := u) (Extra := Extra)).length = 6 * u := by + simp [fields, Nat.mul_comm] + +theorem fields_nodup : (fields (u := u) (Extra := Extra)).Nodup := by + exact List.nodup_ofFn.mpr fieldAt_injective + +theorem field_mem (j : Fin u) (s : Fin 6) : + (SourceContextLoad.Tape.field j s : Tape u Extra) ∈ fields := by + apply List.mem_ofFn.mpr + exact ⟨finProdFinEquiv (j, s), by simp [fieldAt]⟩ + +theorem mem_fields_iff (p : Tape u Extra) : p ∈ fields ↔ ∃ j s, p = .field j s := by + constructor + · intro h + obtain ⟨i, hi⟩ := List.mem_ofFn.mp h + exact ⟨(finProdFinEquiv.symm i).1, (finProdFinEquiv.symm i).2, hi.symm⟩ + · rintro ⟨j, s, rfl⟩ + exact field_mem j s + +def outputTapes (base : Tape u Extra → List Bool) : Tape u Extra → List Bool + | .field _ _ => [] + | p => base p + +@[simp] theorem output_field (base : Tape u Extra → List Bool) (j : Fin u) (s : Fin 6) : + outputTapes base (.field j s) = [] := rfl + +theorem output_frame (base : Tape u Extra → List Bool) (p : Tape u Extra) + (hp : ∀ j s, p ≠ .field j s) : outputTapes base p = base p := by + cases p <;> simp_all [outputTapes] + +abbrev Label (u : Nat) (Extra : Type) := + MachineDrainMany.Label (fields (u := u) (Extra := Extra)) ⊕ Unit + +private def entryLabel {K : Type} : (chosen : List K) → MachineDrainMany.Label chosen ⊕ Unit + | [] => .inr () + | _ :: _ => .inl (.inl ()) + +def main : Label u Extra := entryLabel fields + +variable [DecidableEq Extra] + +def program : Label u Extra → TM2.Stmt (fun _ : Tape u Extra => Bool) + (Label u Extra) (Unit × Option Bool) + | .inl l => MachineDrainMany.instruction fields Sum.inl (some (.inr ())) l + | .inr _ => .load (fun _ => ((), none)) .halt + +private theorem entryLabel_eq {K : Type} (chosen : List K) : + MachineDrainMany.entry chosen + (Sum.inl : MachineDrainMany.Label chosen → MachineDrainMany.Label chosen ⊕ Unit) + (some (.inr ())) = some (entryLabel chosen) := by + cases chosen <;> rfl + +omit [DecidableEq Extra] in +private theorem entry_eq : + MachineDrainMany.entry (fields (u := u) (Extra := Extra)) Sum.inl (some (.inr ())) = + some (main (u := u) (Extra := Extra)) := entryLabel_eq fields + +theorem finalTapes_eq (base : Tape u Extra → List Bool) : + MachineDrainMany.finalTapes fields base = outputTapes base := by + funext p + rw [MachineDrainMany.finalTapes_apply] + cases p <;> simp [mem_fields_iff, outputTapes] + +private theorem lengthSum_update {K : Type} [DecidableEq K] (chosen : List K) + (base : K → List Bool) (source : K) (h : source ∉ chosen) : + MachineDrainMany.lengthSum chosen (Function.update base source []) = + MachineDrainMany.lengthSum chosen base := by + unfold MachineDrainMany.lengthSum + congr 1 + apply List.map_congr_left + intro k hk + rw [Function.update_of_ne (by intro he; subst k; exact h hk)] + +private theorem steps_eq_of_nodup {K : Type} [DecidableEq K] (chosen : List K) + (h : chosen.Nodup) (base : K → List Bool) : + MachineDrainMany.steps chosen base = + MachineDrainMany.lengthSum chosen base + chosen.length := by + induction chosen generalizing base with + | nil => rfl + | cons source chosen ih => + obtain ⟨hn, hd⟩ := List.nodup_cons.mp h + rw [MachineDrainMany.steps, ih hd, lengthSum_update chosen base source hn] + simp only [MachineDrainMany.lengthSum, List.map_cons, List.sum_cons, List.length_cons] + omega + +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 clearTrace (base : Tape u Extra → List Bool) (register : Option Bool) : + (advance (TM2.step program))^[MachineDrainMany.lengthSum fields base + 6 * u + 1] + (some ⟨some main, ((), register), base⟩) = + some ⟨none, ((), none), outputTapes base⟩ := by + have drain := MachineDrainMany.trace fields Sum.inl (some (.inr ())) + program (fun _ => rfl) base () register + rw [entry_eq, finalTapes_eq, steps_eq_of_nodup fields fields_nodup, fields_length] at drain + have last : (advance (TM2.step program))^[1] + (some ⟨some (.inr ()), ((), MachineDrainMany.finalRegister (fields (u := u) (Extra := Extra)) register), outputTapes base⟩) = + some ⟨none, ((), none), outputTapes base⟩ := rfl + exact trace_trans _ drain last + +def clearInTime (base : Tape u Extra → List Bool) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some main, ((), register), base⟩ (some ⟨none, ((), none), outputTapes base⟩) + (MachineDrainMany.lengthSum fields base + 6 * u + 1) where + steps := MachineDrainMany.lengthSum fields base + 6 * u + 1 + evals_in_steps := clearTrace base register + steps_le_m := Nat.le_refl _ + +private theorem lengthSum_le_selected {K : Type} (chosen : List K) + (base : K → List Bool) (B : Nat) (h : ∀ k ∈ chosen, (base k).length ≤ B) : + MachineDrainMany.lengthSum chosen base ≤ chosen.length * B := by + induction chosen with + | nil => simp [MachineDrainMany.lengthSum] + | cons source chosen ih => + have hs := h source (by simp) + have ht := ih (by intro k hk; exact h k (by simp [hk])) + simp only [MachineDrainMany.lengthSum, List.map_cons, List.sum_cons, + List.length_cons, Nat.add_mul, Nat.one_mul] at ht ⊢ + omega + +theorem clauseField_length_le {n : Nat} (c : Target.Clause n) (s : Fin 6) : + (encodeWord ((clauseWords c)[s.val]'(by simp))).length ≤ n + 2 := by + have h0 := (c)[0].variableIndex.isLt + have h1 := (c)[1].variableIndex.isLt + have h2 := (c)[2].variableIndex.isLt + fin_cases s <;> simp [clauseWords, literalWords, encodeWord_length] + all_goals first | omega | (split <;> omega) + +theorem variables_add_two_le_input (F : Target.Formula) : + F.«variables» + 2 ≤ (formulaBits F).length := by + simp only [formulaBits, formulaWords, encodeWords_append, List.length_append, + encodeWords, encodeWord_length, List.length_nil] + omega + +omit [DecidableEq Extra] in +theorem loaded_field_length_le (F : Target.Formula) + (tuple : Fin u → Fin F.clauses.length) (base : Tape u Extra → List Bool) + (hfields : ∀ j s, base (.field j s) = []) (j : Fin u) (s : Fin 6) : + (SourceContextLoad.stageTapes F tuple base u (.field j s)).length ≤ + (formulaBits F).length := by + rw [SourceContextLoad.stageTapes_field, ite_eq_left j.isLt, hfields, List.append_nil] + exact (clauseField_length_le _ s).trans (variables_add_two_le_input F) + +omit [DecidableEq Extra] in +theorem loaded_cost_le (F : Target.Formula) (tuple : Fin u → Fin F.clauses.length) + (base : Tape u Extra → List Bool) (hfields : ∀ j s, base (.field j s) = []) : + MachineDrainMany.lengthSum fields (SourceContextLoad.stageTapes F tuple base u) + 6 * u + 1 ≤ + 6 * u * ((formulaBits F).length + 1) + 1 := by + have h := lengthSum_le_selected fields (SourceContextLoad.stageTapes F tuple base u) + (formulaBits F).length (by + intro p hp + obtain ⟨j, s, rfl⟩ := (mem_fields_iff p).mp hp + exact loaded_field_length_le F tuple base hfields j s) + rw [fields_length] at h + rw [Nat.mul_add, Nat.mul_one] + omega + +def clearLoadedInTime (F : Target.Formula) (tuple : Fin u → Fin F.clauses.length) + (base : Tape u Extra → List Bool) (hfields : ∀ j s, base (.field j s) = []) + (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some main, ((), register), SourceContextLoad.stageTapes F tuple base u⟩ + (some ⟨none, ((), none), outputTapes (SourceContextLoad.stageTapes F tuple base u)⟩) + (6 * u * ((formulaBits F).length + 1) + 1) where + steps := MachineDrainMany.lengthSum fields (SourceContextLoad.stageTapes F tuple base u) + 6 * u + 1 + evals_in_steps := clearTrace _ register + steps_le_m := loaded_cost_le F tuple base hfields + +omit [DecidableEq Extra] in +theorem output_loaded_eq_base (F : Target.Formula) (tuple : Fin u → Fin F.clauses.length) + (base : Tape u Extra → List Bool) (hfields : ∀ j s, base (.field j s) = []) + (hindex : base .index = []) (hwork : base .work = []) : + outputTapes (SourceContextLoad.stageTapes F tuple base u) = base := by + funext p + cases p with + | field j s => exact (hfields j s).symm + | index => exact (SourceContextLoad.stageTapes_clean F tuple base u hindex hwork).1.trans hindex.symm + | work => exact (SourceContextLoad.stageTapes_clean F tuple base u hindex hwork).2.trans hwork.symm + | _ => exact SourceContextLoad.stageTapes_frame F tuple base u _ (by simp) (by simp) (by simp) + +def clearLoadedToBaseInTime (F : Target.Formula) (tuple : Fin u → Fin F.clauses.length) + (base : Tape u Extra → List Bool) (hfields : ∀ j s, base (.field j s) = []) + (hindex : base .index = []) (hwork : base .work = []) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some main, ((), register), SourceContextLoad.stageTapes F tuple base u⟩ + (some ⟨none, ((), none), base⟩) + (6 * u * ((formulaBits F).length + 1) + 1) := by + simpa only [output_loaded_eq_base F tuple base hfields hindex hwork] using + clearLoadedInTime F tuple base hfields register + +def machine (u : Nat) (Extra : Type) [DecidableEq Extra] [Fintype Extra] : FinTM2 where + K := Tape u Extra + k₀ := .formula + k₁ := .formula + Γ _ := Bool + Λ := Label u Extra + main := main + σ := Unit × Option Bool + initialState := ((), none) + m := program + +end MinUncutGames.Foundations.Hastad.SourceContextClear + +namespace MinUncutGames.Foundations.Hastad.SourceOccurrences.Encoding + +variable {α β γ : Type} + +theorem prod_decode_pair (a : Encoding α) (b : Encoding β) + (i : Fin a.size) (j : Fin b.size) : + (a.prod b).code.symm (finProdFinEquiv (i, j)) = + (a.code.symm i, b.code.symm j) := by + change (a.code.symm (finProdFinEquiv.symm (finProdFinEquiv (i, j))).1, + b.code.symm (finProdFinEquiv.symm (finProdFinEquiv (i, j))).2) = _ + rw [Equiv.symm_apply_apply] + +theorem prod_decode_mk (a : Encoding α) (b : Encoding β) + (i : Fin a.size) (j : Fin b.size) + (h : i.val * b.size + j.val < a.size * b.size) : + (a.prod b).code.symm ⟨i.val * b.size + j.val, h⟩ = + (a.code.symm i, b.code.symm j) := by + have he : (⟨i.val * b.size + j.val, h⟩ : Fin (a.size * b.size)) = + finProdFinEquiv (i, j) := by + apply Fin.ext + simp [finProdFinEquiv, Nat.mul_comm, Nat.add_comm] + change (a.code.symm (finProdFinEquiv.symm (⟨i.val * b.size + j.val, h⟩ : + Fin (a.size * b.size))).1, + b.code.symm (finProdFinEquiv.symm (⟨i.val * b.size + j.val, h⟩ : + Fin (a.size * b.size))).2) = _ + rw [he] + exact prod_decode_pair a b i j + +theorem enumerate_prod (a : Encoding α) (b : Encoding β) : + (a.prod b).enumerate = + a.enumerate.flatMap (fun x => b.enumerate.map (fun y => (x, y))) := by + change List.ofFn (fun q : Fin (a.size * b.size) => + (a.code.symm (finProdFinEquiv.symm q).1, + b.code.symm (finProdFinEquiv.symm q).2)) = _ + rw [List.ofFn_mul] + simp only [enumerate, List.flatMap_def, List.map_ofFn] + apply congrArg List.flatten + apply congrArg List.ofFn + funext i + apply congrArg List.ofFn + funext j + exact prod_decode_mk a b i j _ + +theorem map_enumerate_prod (a : Encoding α) (b : Encoding β) (emit : α × β → γ) : + (a.prod b).enumerate.map emit = + a.enumerate.flatMap (fun x => b.enumerate.map (fun y => emit (x, y))) := by + rw [enumerate_prod] + simp only [List.map_flatMap, List.map_map, Function.comp_def] + +end MinUncutGames.Foundations.Hastad.SourceOccurrences.Encoding + +namespace MinUncutGames.Foundations.Hastad.SourceEnumeration + +open Target SourceContexts SourceOccurrences + +theorem testTapeEncoding_enumerate (u D : ℕ) : + (testTapeEncoding u D).enumerate = + ((iEncoding u).function Encoding.bool).enumerate.flatMap (fun f => + ((jEncoding u).function (Encoding.fin D)).enumerate.flatMap (fun z => + ((jEncoding u).function Encoding.bool).enumerate.map (fun g => (f, z, g)))) := by + simp only [testTapeEncoding, Encoding.enumerate_prod, List.map_flatMap, + List.map_map, Function.comp_def] + +theorem sourceIndexEncoding_enumerate (F : Formula) (u D : ℕ) : + (sourceIndexEncoding F u D).enumerate = + (clauseEncoding F u).enumerate.flatMap (fun c => + (slotContextEncoding u).enumerate.flatMap (fun s => + ((iEncoding u).function Encoding.bool).enumerate.flatMap (fun f => + ((jEncoding u).function (Encoding.fin D)).enumerate.flatMap (fun z => + ((jEncoding u).function Encoding.bool).enumerate.map + (fun g => ((c, s), (f, z, g))))))) := by + simp only [sourceIndexEncoding, Encoding.enumerate_prod, testTapeEncoding_enumerate, + List.flatMap_assoc, List.flatMap_map, List.map_flatMap, List.map_map, Function.comp_def] + +theorem sourceIndexEncoding_map {α : Type} (F : Formula) (u D : ℕ) + (emit : SourceIndex F u D → α) : + (sourceIndexEncoding F u D).enumerate.map emit = + (clauseEncoding F u).enumerate.flatMap (fun c => + (slotContextEncoding u).enumerate.flatMap (fun s => + ((iEncoding u).function Encoding.bool).enumerate.flatMap (fun f => + ((jEncoding u).function (Encoding.fin D)).enumerate.flatMap (fun z => + ((jEncoding u).function Encoding.bool).enumerate.map + (fun g => emit ((c, s), (f, z, g))))))) := by + rw [sourceIndexEncoding_enumerate] + simp only [List.map_flatMap, List.map_map, Function.comp_def] + +theorem rawSourceList_eq_nestedLoops (F : Formula) (u D : ℕ) : + rawSourceList F u D = + (clauseEncoding F u).enumerate.flatMap (fun c => + (slotContextEncoding u).enumerate.flatMap (fun s => + ((iEncoding u).function Encoding.bool).enumerate.flatMap (fun f => + ((jEncoding u).function (Encoding.fin D)).enumerate.flatMap (fun z => + ((jEncoding u).function Encoding.bool).enumerate.map + (fun g => contextEquation F u D c (sampledVariables F c s) (f, z, g)))))) := by + exact sourceIndexEncoding_map F u D (sourceEquation F u D) + +theorem sourceList_eq_nestedLoops (F : Formula) (u D : ℕ) (hne : F.clauses ≠ []) : + sourceList F u D = + (clauseEncoding F u).enumerate.flatMap (fun c => + (slotContextEncoding u).enumerate.flatMap (fun s => + ((iEncoding u).function Encoding.bool).enumerate.flatMap (fun f => + ((jEncoding u).function (Encoding.fin D)).enumerate.flatMap (fun z => + ((jEncoding u).function Encoding.bool).enumerate.map + (fun g => contextEquation F u D c (sampledVariables F c s) (f, z, g)))))) := by + rw [sourceList_nonempty F u D hne] + exact rawSourceList_eq_nestedLoops F u D + +theorem rawSourceList_flatMap {α : Type} (F : Formula) (u D : ℕ) + (emit : MinUncutGames.Reduction.CloneGap.Equation (Fin (nBits F u)) → List α) : + (rawSourceList F u D).flatMap emit = + (clauseEncoding F u).enumerate.flatMap (fun c => + (slotContextEncoding u).enumerate.flatMap (fun s => + ((iEncoding u).function Encoding.bool).enumerate.flatMap (fun f => + ((jEncoding u).function (Encoding.fin D)).enumerate.flatMap (fun z => + ((jEncoding u).function Encoding.bool).enumerate.flatMap + (fun g => emit (contextEquation F u D c (sampledVariables F c s) (f, z, g))))))) := by + rw [rawSourceList_eq_nestedLoops] + simp only [List.flatMap_assoc, List.flatMap_map] + +end MinUncutGames.Foundations.Hastad.SourceEnumeration + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/ContextLoad.lean b/lean/OAI/Computability/MinUncut/PCP/ContextLoad.lean new file mode 100644 index 0000000000000000000000000000000000000000..921a7b23292309eb16813d3b6b3b29717012030d --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/ContextLoad.lean @@ -0,0 +1,777 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.ClauseLookup +import OAI.Computability.MinUncut.Machines.MachineDrain + +namespace OAI + +namespace MinUncutGames.Foundations.Hastad.SourceContextLoad + +open Turing MinUncutGames.Foundations.Complexity +open MachineComposition + +inductive Tape (u : Nat) (Extra : Type) + | formula | index | work | scratch | copyScratch + | current (coordinate : Fin u) | remaining (coordinate : Fin u) + | field (coordinate : Fin u) (slot : Fin 6) + | extra (value : Extra) + deriving DecidableEq, Fintype + +inductive Label (u : Nat) + | copyOut (coordinate : Fin u) | copyBack (coordinate : Fin u) + | lookup (coordinate : Fin u) (localLabel : SourceClauseLookup.Label) + | clearWork (coordinate : Fin u) | clearIndex (coordinate : Fin u) + | done + deriving DecidableEq, Fintype + +variable {u : Nat} {Extra : Type} + +def place (j : Fin u) : SourceClauseLookup.Tape → Tape u Extra + | .formula => .formula | .index => .index | .work => .work | .scratch => .scratch + | .field s => .field j s + +def fill (j : Fin u) (base : Tape u Extra → List Bool) + (localTapes : SourceClauseLookup.Tape → List Bool) : Tape u Extra → List Bool + | .formula => localTapes .formula | .index => localTapes .index + | .work => localTapes .work | .scratch => localTapes .scratch + | .field i s => if i = j then localTapes (.field s) else base (.field i s) + | p => base p + +@[simp] theorem fill_place (j : Fin u) (base : Tape u Extra → List Bool) + (localTapes : SourceClauseLookup.Tape → List Bool) (p : SourceClauseLookup.Tape) : + fill j base localTapes (place j p) = localTapes p := by + cases p <;> simp [fill, place] + +@[simp] theorem fill_self (j : Fin u) (base : Tape u Extra → List Bool) : + fill j base (base ∘ place j) = base := by + funext p + cases p <;> simp [fill, place] + intro h + subst h + rfl + +variable [DecidableEq Extra] + +theorem fill_update (j : Fin u) (base : Tape u Extra → List Bool) + (localTapes : SourceClauseLookup.Tape → List Bool) (p : SourceClauseLookup.Tape) + (value : List Bool) : + fill j base (Function.update localTapes p value) = + Function.update (fill j base localTapes) (place j p) value := by + funext k + cases k <;> cases p <;> simp [fill, place, Function.update_apply] + all_goals split <;> simp_all + +def placedLabel (j : Fin u) : Option SourceClauseLookup.Label → Option (Label u) + | none => some (.clearWork j) + | some l => some (.lookup j l) + +def placedConfiguration (j : Fin u) (base : Tape u Extra → List Bool) + (c : TM2.Cfg (fun _ : SourceClauseLookup.Tape => Bool) + SourceClauseLookup.Label (Unit × Option Bool)) : + TM2.Cfg (fun _ : Tape u Extra => Bool) (Label u) (Unit × Option Bool) := + ⟨placedLabel j c.l, c.var, fill j base c.stk⟩ + +def placedStatement (j : Fin u) : + TM2.Stmt (fun _ : SourceClauseLookup.Tape => Bool) + SourceClauseLookup.Label (Unit × Option Bool) → + TM2.Stmt (fun _ : Tape u Extra => Bool) (Label u) (Unit × Option Bool) + | .push k f next => .push (place j k) f (placedStatement j next) + | .peek k f next => .peek (place j k) f (placedStatement j next) + | .pop k f next => .pop (place j k) f (placedStatement j next) + | .load f next => .load f (placedStatement j next) + | .branch f yes no => .branch f (placedStatement j yes) (placedStatement j no) + | .goto f => .goto (fun state => .lookup j (f state)) + | .halt => .goto (fun _ => .clearWork j) + +theorem placed_stepAux (j : Fin u) (base : Tape u Extra → List Bool) + (q : TM2.Stmt (fun _ : SourceClauseLookup.Tape => Bool) + SourceClauseLookup.Label (Unit × Option Bool)) + (state : Unit × Option Bool) (localTapes : SourceClauseLookup.Tape → List Bool) : + TM2.stepAux (placedStatement j q) state (fill j base localTapes) = + placedConfiguration j base (TM2.stepAux q state localTapes) := by + induction q generalizing state localTapes with + | push k f next ih => + simp only [placedStatement, TM2.stepAux, fill_place] + rw [← fill_update] + exact ih state _ + | peek k f next ih => + simpa only [placedStatement, TM2.stepAux, fill_place] using ih (f state _) localTapes + | pop k f next ih => + simp only [placedStatement, TM2.stepAux, fill_place] + rw [← fill_update] + exact ih (f state _) _ + | load f next ih => simpa only [placedStatement, TM2.stepAux] using ih (f state) localTapes + | branch f yes no ihYes ihNo => + cases h : f state + · simpa only [placedStatement, TM2.stepAux, h, Bool.cond_false] using ihNo state localTapes + · simpa only [placedStatement, TM2.stepAux, h, Bool.cond_true] using ihYes state localTapes + | goto f => rfl + | halt => rfl + +def nextLabel (j : Fin u) : Label u := + if h : j.val + 1 < u then .copyOut ⟨j.val + 1, h⟩ else .done + +def program : Label u → TM2.Stmt (fun _ : Tape u Extra => Bool) + (Label u) (Unit × Option Bool) + | .copyOut j => Reduction.MachineTransfer.loopAt (.current j) .copyScratch id false + (.copyOut j) (some (.copyBack j)) + | .copyBack j => MachineCopy.forkLoop .copyScratch (.current j) .index false + (.copyBack j) (some (.lookup j .copyOut)) + | .lookup j l => placedStatement j (SourceClauseLookup.program l) + | .clearWork j => MachineDrain.drain .work (.clearWork j) (some (.clearIndex j)) + | .clearIndex j => MachineDrain.drain .index (.clearIndex j) (some (nextLabel j)) + | .done => .halt + +theorem placed_step (j : Fin u) (base : Tape u Extra → List Bool) + (a b : TM2.Cfg (fun _ : SourceClauseLookup.Tape => Bool) + SourceClauseLookup.Label (Unit × Option Bool)) + (h : TM2.step SourceClauseLookup.program a = some b) : + TM2.step program (placedConfiguration j base a) = + some (placedConfiguration j base b) := by + cases a with + | mk l state localTapes => + cases l with + | none => contradiction + | some l => + change some (TM2.stepAux (SourceClauseLookup.program l) state localTapes) = some b at h + cases Option.some.inj h + change some (TM2.stepAux (placedStatement j (SourceClauseLookup.program l)) + state (fill j base localTapes)) = _ + rw [placed_stepAux] + +def lookupOutput (j : Fin u) (F : Target.Formula) (i : Fin F.clauses.length) + (base : Tape u Extra → List Bool) (suffix : List Bool) : Tape u Extra → List Bool := + fill j base (SourceClauseLookup.outputTapes (base ∘ place j) F.clauses[i.val] suffix + (encodeWords ((F.clauses.drop (i.val + 1)).flatMap clauseWords))) + +noncomputable def placedLookupInTime (j : Fin u) (F : Target.Formula) (i : Fin F.clauses.length) + (base : Tape u Extra → List Bool) (suffix : List Bool) + (hformula : base .formula = formulaBits F) + (hindex : base .index = encodeWord i.val ++ suffix) + (hwork : base .work = []) (hscratch : base .scratch = []) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (.lookup j .copyOut), ((), register), base⟩ + (some ⟨some (.clearWork j), ((), none), lookupOutput j F i base suffix⟩) + (4 * (formulaBits F).length + 10) := by + have h := SourceClauseLookup.lookupInTime F i (base ∘ place j) suffix + hformula hindex hwork hscratch register + have lifted := liftExecutionInTime (TM2.step SourceClauseLookup.program) (TM2.step program) + (placedConfiguration j base) (placed_step j base) h + simpa only [placedConfiguration, placedLabel, fill_self, + SourceClauseLookup.timePolynomial_eval, lookupOutput] using lifted + +def copiedTapes (j : Fin u) (base : Tape u Extra → List Bool) : Tape u Extra → List Bool := + Function.update base .index (base (.current j)) + +def coordinateOutput {n : Nat} (j : Fin u) (clause : Target.Clause n) + (base : Tape u Extra → List Bool) : Tape u Extra → List Bool + | .index | .work => [] + | .field k s => if k = j then + encodeWord ((clauseWords clause)[s.val]'(by simp)) ++ base (.field k s) + else base (.field k s) + | p => base p + +theorem cleanup_lookupOutput (j : Fin u) (F : Target.Formula) (i : Fin F.clauses.length) + (base : Tape u Extra → List Bool) (suffix : List Bool) : + Function.update (Function.update + (lookupOutput j F i (copiedTapes j base) suffix) .work []) .index [] = + coordinateOutput j F.clauses[i.val] base := by + funext p + cases p with + | formula => simp [lookupOutput, fill, coordinateOutput, SourceClauseLookup.output_formula, + copiedTapes, place] + | index => simp [coordinateOutput] + | work => simp [coordinateOutput] + | scratch => + simp only [Function.update_of_ne (by simp : (Tape.scratch : Tape u Extra) ≠ .index), + Function.update_of_ne (by simp : (Tape.scratch : Tape u Extra) ≠ .work), lookupOutput, fill, + coordinateOutput] + rw [SourceClauseLookup.output_frame _ _ _ _ .scratch (by simp) (by simp) (by intro s; simp)] + simp [copiedTapes, place] + | field k s => + by_cases hk : k = j + · subst k + simp [lookupOutput, fill, coordinateOutput, SourceClauseLookup.output_field, + copiedTapes, place] + · simp [lookupOutput, fill, coordinateOutput, hk, copiedTapes] + | copyScratch => simp [lookupOutput, fill, coordinateOutput, copiedTapes] + | current k => simp [lookupOutput, fill, coordinateOutput, copiedTapes] + | remaining k => simp [lookupOutput, fill, coordinateOutput, copiedTapes] + | extra k => simp [lookupOutput, fill, coordinateOutput, copiedTapes] + +omit [DecidableEq Extra] in +@[simp] theorem coordinateOutput_current {n : Nat} (j k : Fin u) (clause : Target.Clause n) + (base : Tape u Extra → List Bool) : + coordinateOutput j clause base (.current k) = base (.current k) := rfl + +omit [DecidableEq Extra] in +@[simp] theorem coordinateOutput_remaining {n : Nat} (j k : Fin u) (clause : Target.Clause n) + (base : Tape u Extra → List Bool) : + coordinateOutput j clause base (.remaining k) = base (.remaining k) := rfl + +omit [DecidableEq Extra] in +@[simp] theorem coordinateOutput_field {n : Nat} (j : Fin u) (s : Fin 6) + (clause : Target.Clause n) (base : Tape u Extra → List Bool) : + coordinateOutput j clause base (.field j s) = + encodeWord ((clauseWords clause)[s.val]'(by simp)) ++ base (.field j s) := by + simp [coordinateOutput] + +omit [DecidableEq Extra] in +theorem coordinateOutput_other_field {n : Nat} (j k : Fin u) (s : Fin 6) + (clause : Target.Clause n) (base : Tape u Extra → List Bool) (h : k ≠ j) : + coordinateOutput j clause base (.field k s) = base (.field k s) := by + simp [coordinateOutput, h] + +theorem suffix_length_le_input (F : Target.Formula) (i : Nat) : + (encodeWords ((F.clauses.drop i).flatMap clauseWords)).length ≤ (formulaBits F).length := by + have hs := List.take_append_drop i F.clauses + have he : formulaBits F = encodeWords [F.«variables», F.clauses.length] ++ + encodeWords ((F.clauses.take i).flatMap clauseWords) ++ + encodeWords ((F.clauses.drop i).flatMap clauseWords) := by + conv_lhs => rw [formulaBits, formulaWords, ← hs] + simp only [List.flatMap_append, encodeWords_append, List.append_assoc] + rw [hs] + rw [he, List.length_append, List.length_append] + omega + +noncomputable def coordinateInTime (j : Fin u) (F : Target.Formula) (i : Fin F.clauses.length) + (base : Tape u Extra → List Bool) (suffix : List Bool) + (hformula : base .formula = formulaBits F) + (hcurrent : base (.current j) = encodeWord i.val ++ suffix) + (hindex : base .index = []) (hwork : base .work = []) + (hscratch : base .scratch = []) (hcopy : base .copyScratch = []) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (.copyOut j), ((), register), base⟩ + (some ⟨some (nextLabel j), ((), none), coordinateOutput j F.clauses[i.val] base⟩) + (6 * (formulaBits F).length + 4 * (base (.current j)).length + 20) := by + let copied := copiedTapes j base + let loaded := lookupOutput j F i copied suffix + have copyRun := MachineCopy.copyInTime (.current j) .index .copyScratch + (by simp) (by simp) (by simp) false (.copyOut j) (.copyBack j) + (some (.lookup j .copyOut)) program rfl rfl base hcopy () register + have copied_eq : Function.update base .index (base (.current j) ++ base .index) = copied := by + simp [copied, copiedTapes, hindex] + rw [copied_eq] at copyRun + have lookupRun := placedLookupInTime j F i copied suffix + (by simpa [copied, copiedTapes] using hformula) + (by simpa [copied, copiedTapes] using hcurrent) + (by simpa [copied, copiedTapes] using hwork) + (by simpa [copied, copiedTapes] using hscratch) none + have workRun := MachineDrain.drainInTime .work (.clearWork j) (some (.clearIndex j)) + program rfl loaded () none + have indexRun := MachineDrain.drainInTime .index (.clearIndex j) (some (nextLabel j)) + program rfl (Function.update loaded .work []) () none + have hrun := StateTransition.EvalsToInTime.trans (TM2.step program) _ _ _ _ _ + (StateTransition.EvalsToInTime.trans (TM2.step program) _ _ _ _ _ + (StateTransition.EvalsToInTime.trans (TM2.step program) _ _ _ _ _ copyRun lookupRun) + workRun) indexRun + have hw : loaded .work = encodeWords ((F.clauses.drop (i.val + 1)).flatMap clauseWords) := by + simp [loaded, lookupOutput, fill, SourceClauseLookup.output_work] + have hi : (Function.update loaded .work []) .index = encodeWord 0 ++ suffix := by + simp [loaded, lookupOutput, fill, SourceClauseLookup.output_index] + have hc : suffix.length ≤ (base (.current j)).length := by + rw [hcurrent, List.length_append] + omega + refine { steps := hrun.steps, evals_in_steps := ?_, steps_le_m := ?_ } + · simpa only [loaded, copied, cleanup_lookupOutput] using hrun.evals_in_steps + · apply Nat.le_trans hrun.steps_le_m + rw [hw, hi, List.length_append, encodeWord_length] + have hs := suffix_length_le_input F (i.val + 1) + omega + +def labelAt (r : Nat) : Label u := + if h : r < u then .copyOut ⟨r, h⟩ else .done + +theorem nextLabel_eq (j : Fin u) : nextLabel j = labelAt (j.val + 1) := rfl + +def stageTapes (F : Target.Formula) (tuple : Fin u → Fin F.clauses.length) + (base : Tape u Extra → List Bool) : Nat → Tape u Extra → List Bool + | 0 => base + | r + 1 => if h : r < u then + coordinateOutput ⟨r, h⟩ F.clauses[(tuple ⟨r, h⟩).val] (stageTapes F tuple base r) + else stageTapes F tuple base r + +omit [DecidableEq Extra] in +theorem stageTapes_frame (F : Target.Formula) (tuple : Fin u → Fin F.clauses.length) + (base : Tape u Extra → List Bool) (r : Nat) (p : Tape u Extra) + (hi : p ≠ .index) (hw : p ≠ .work) (hf : ∀ j s, p ≠ .field j s) : + stageTapes F tuple base r p = base p := by + induction r with + | zero => rfl + | succ r ih => + simp only [stageTapes] + split + · cases p <;> simp_all [coordinateOutput] + · exact ih + +omit [DecidableEq Extra] in +theorem stageTapes_clean (F : Target.Formula) (tuple : Fin u → Fin F.clauses.length) + (base : Tape u Extra → List Bool) (r : Nat) (hi : base .index = []) (hw : base .work = []) : + stageTapes F tuple base r .index = [] ∧ stageTapes F tuple base r .work = [] := by + induction r with + | zero => exact ⟨hi, hw⟩ + | succ r ih => + simp only [stageTapes] + split + · exact ⟨rfl, rfl⟩ + · exact ih + +omit [DecidableEq Extra] in +theorem stageTapes_field (F : Target.Formula) (tuple : Fin u → Fin F.clauses.length) + (base : Tape u Extra → List Bool) (r : Nat) (j : Fin u) (s : Fin 6) : + stageTapes F tuple base r (.field j s) = if j.val < r then + encodeWord ((clauseWords F.clauses[(tuple j).val])[s.val]'(by simp)) ++ base (.field j s) + else base (.field j s) := by + induction r with + | zero => simp [stageTapes] + | succ r ih => + simp only [stageTapes] + split + next hr => + by_cases hj : j = (⟨r, hr⟩ : Fin u) + · subst j + simp only [coordinateOutput_field, ih] + simp + · rw [coordinateOutput_other_field _ _ _ _ _ hj, ih] + have hval : j.val ≠ r := by intro h; apply hj; exact Fin.ext h + have he : j.val < r + 1 ↔ j.val < r := by omega + simp only [he] + next hr => + rw [ih] + have hjr : j.val < r := by omega + have hjr' : j.val < r + 1 := by omega + simp only [hjr, hjr', ite_true] + +noncomputable def prefixInTime (F : Target.Formula) (tuple : Fin u → Fin F.clauses.length) + (base : Tape u Extra → List Bool) (suffix : Fin u → List Bool) (C : Nat) + (hformula : base .formula = formulaBits F) + (hcurrent : ∀ j, base (.current j) = encodeWord (tuple j).val ++ suffix j) + (hsize : ∀ j, (base (.current j)).length ≤ C) + (hindex : base .index = []) (hwork : base .work = []) + (hscratch : base .scratch = []) (hcopy : base .copyScratch = []) + (r : Nat) (hr : r ≤ u) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labelAt 0), ((), none), base⟩ + (some ⟨some (labelAt r), ((), none), stageTapes F tuple base r⟩) + (r * (6 * (formulaBits F).length + 4 * C + 20)) := by + induction r with + | zero => exact { steps := 0, evals_in_steps := rfl, steps_le_m := by omega } + | succ r ih => + have hru : r < u := by omega + let j : Fin u := ⟨r, hru⟩ + let before := stageTapes F tuple base r + have hf (p : Tape u Extra) (hi : p ≠ .index) (hw : p ≠ .work) + (hh : ∀ j s, p ≠ .field j s) : before p = base p := + stageTapes_frame F tuple base r p hi hw hh + have hd := stageTapes_clean F tuple base r hindex hwork + have hc : before (.current j) = base (.current j) := hf _ (by simp) (by simp) (by simp) + have one := coordinateInTime j F (tuple j) before (suffix j) + (by rw [hf _ (by simp) (by simp) (by simp)]; exact hformula) + (by rw [hc]; exact hcurrent j) hd.1 hd.2 + (by rw [hf _ (by simp) (by simp) (by simp)]; exact hscratch) + (by rw [hf _ (by simp) (by simp) (by simp)]; exact hcopy) none + have one' : StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labelAt r), ((), none), before⟩ + (some ⟨some (labelAt (r + 1)), ((), none), stageTapes F tuple base (r + 1)⟩) + (6 * (formulaBits F).length + 4 * C + 20) := by + refine { steps := one.steps, evals_in_steps := ?_, steps_le_m := ?_ } + · simpa only [labelAt, dite_eq_left hru, nextLabel_eq, j, stageTapes, before] using + one.evals_in_steps + · apply Nat.le_trans one.steps_le_m + rw [hc] + have hs := hsize j + omega + have joined := StateTransition.EvalsToInTime.trans (TM2.step program) _ _ _ _ _ + (ih (by omega)) one' + simpa only [Nat.add_mul, Nat.one_mul, Nat.add_comm] using joined + +noncomputable def loadInTime (F : Target.Formula) (tuple : Fin u → Fin F.clauses.length) + (base : Tape u Extra → List Bool) (suffix : Fin u → List Bool) (C : Nat) + (hformula : base .formula = formulaBits F) + (hcurrent : ∀ j, base (.current j) = encodeWord (tuple j).val ++ suffix j) + (hsize : ∀ j, (base (.current j)).length ≤ C) + (hindex : base .index = []) (hwork : base .work = []) + (hscratch : base .scratch = []) (hcopy : base .copyScratch = []) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labelAt 0), ((), none), base⟩ + (some ⟨none, ((), none), stageTapes F tuple base u⟩) + (u * (6 * (formulaBits F).length + 4 * C + 20) + 1) := by + have prefixRun := prefixInTime F tuple base suffix C hformula hcurrent hsize + hindex hwork hscratch hcopy u (Nat.le_refl _) + have doneRun : StateTransition.EvalsToInTime (TM2.step (program (Extra := Extra))) + ⟨some (labelAt u), ((), none), stageTapes F tuple base u⟩ + (some ⟨none, ((), none), stageTapes F tuple base u⟩) 1 := by + refine { steps := 1, evals_in_steps := ?_, steps_le_m := Nat.le_refl _ } + change TM2.step program ⟨some (labelAt u), ((), none), stageTapes F tuple base u⟩ = _ + simp only [labelAt, Nat.lt_irrefl, ↓reduceDIte] + rfl + simpa only [Nat.add_comm] using + StateTransition.EvalsToInTime.trans (TM2.step program) _ _ _ _ _ prefixRun doneRun + +theorem clauses_length_le_input (F : Target.Formula) : + F.clauses.length ≤ (formulaBits F).length := by + simp only [formulaBits, encodeWords_length, formulaWords_length] + omega + +noncomputable def loadUnaryInTime (F : Target.Formula) (tuple : Fin u → Fin F.clauses.length) + (base : Tape u Extra → List Bool) + (hformula : base .formula = formulaBits F) + (hcurrent : ∀ j, base (.current j) = encodeWord (tuple j).val) + (hindex : base .index = []) (hwork : base .work = []) + (hscratch : base .scratch = []) (hcopy : base .copyScratch = []) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labelAt 0), ((), none), base⟩ + (some ⟨none, ((), none), stageTapes F tuple base u⟩) + (u * (10 * (formulaBits F).length + 20) + 1) := by + have run := loadInTime F tuple base (fun _ => []) (formulaBits F).length hformula + (by simpa only [List.append_nil] using hcurrent) + (by + intro j + rw [hcurrent j, encodeWord_length] + have h := (tuple j).isLt + have hm := clauses_length_le_input F + omega) + hindex hwork hscratch hcopy + have he : 6 * (formulaBits F).length + 4 * (formulaBits F).length + 20 = + 10 * (formulaBits F).length + 20 := by omega + simpa only [he] using run + +noncomputable def timePolynomial (u : Nat) : Polynomial Nat := + Polynomial.C (10 * u) * Polynomial.X + Polynomial.C (20 * u + 1) + +theorem timePolynomial_eval (u L : Nat) : + (timePolynomial u).eval L = u * (10 * L + 20) + 1 := by + simp only [timePolynomial, Polynomial.eval_add, Polynomial.eval_mul, + Polynomial.eval_C, Polynomial.eval_X] + simp [Nat.mul_add, Nat.mul_comm, Nat.mul_left_comm, Nat.add_assoc] + +def variableSlot (s : Fin 3) : Fin 6 := ⟨2 * s.val, by omega⟩ +def polaritySlot (s : Fin 3) : Fin 6 := ⟨2 * s.val + 1, by omega⟩ +def variableField (j : Fin u) (s : Fin 3) : Tape u Extra := .field j (variableSlot s) +def polarityField (j : Fin u) (s : Fin 3) : Tape u Extra := .field j (polaritySlot s) + +theorem clauseWords_variable {n : Nat} (clause : Target.Clause n) (s : Fin 3) : + (clauseWords clause)[(variableSlot s).val]'(by simp) = clause[s.val].variableIndex.val := by + obtain ⟨s, hs⟩ := s + have h : s = 0 ∨ s = 1 ∨ s = 2 := by omega + rcases h with rfl | rfl | rfl <;> rfl + +theorem clauseWords_polarity {n : Nat} (clause : Target.Clause n) (s : Fin 3) : + (clauseWords clause)[(polaritySlot s).val]'(by simp) = + if clause[s.val].positive then 1 else 0 := by + obtain ⟨s, hs⟩ := s + have h : s = 0 ∨ s = 1 ∨ s = 2 := by omega + rcases h with rfl | rfl | rfl <;> rfl + +omit [DecidableEq Extra] in +theorem output_variable (F : Target.Formula) (tuple : Fin u → Fin F.clauses.length) + (base : Tape u Extra → List Bool) (j : Fin u) (s : Fin 3) : + stageTapes F tuple base u (variableField j s) = + encodeWord (F.clauses[(tuple j).val][s.val].variableIndex.val) ++ base (variableField j s) := by + rw [variableField, stageTapes_field, ite_eq_left j.isLt, clauseWords_variable] + +omit [DecidableEq Extra] in +theorem output_polarity (F : Target.Formula) (tuple : Fin u → Fin F.clauses.length) + (base : Tape u Extra → List Bool) (j : Fin u) (s : Fin 3) : + stageTapes F tuple base u (polarityField j s) = + encodeWord (if F.clauses[(tuple j).val][s.val].positive then 1 else 0) ++ + base (polarityField j s) := by + rw [polarityField, stageTapes_field, ite_eq_left j.isLt, clauseWords_polarity] + +variable [Fintype Extra] + +def machine (u : Nat) (Extra : Type) [DecidableEq Extra] [Fintype Extra] : FinTM2 where + K := Tape u Extra + k₀ := .formula + k₁ := .formula + Γ _ := Bool + Λ := Label u + main := labelAt 0 + σ := Unit × Option Bool + initialState := ((), none) + m := program + +end MinUncutGames.Foundations.Hastad.SourceContextLoad + +namespace MinUncutGames.Foundations.Hastad.SourceLocalSignature + +open Target PCP SourceContexts + +abbrev Position (u : ℕ) := Fin u × Slot +abbrev NameProfile (u : ℕ) := Position u → Position u → Bool + +structure Signature (u : ℕ) where + signs : Position u → Bool + sameName : NameProfile u + selected : SlotContext u + deriving DecidableEq + +def signatureEquiv (u : ℕ) : + Signature u ≃ (Position u → Bool) × NameProfile u × SlotContext u where + toFun σ := (σ.signs, σ.sameName, σ.selected) + invFun p := ⟨p.1, p.2.1, p.2.2⟩ + left_inv σ := by cases σ; rfl + right_inv p := by rcases p with ⟨a, b, c⟩; rfl + +instance signatureFintype (u : ℕ) : Fintype (Signature u) := + Fintype.ofEquiv ((Position u → Bool) × NameProfile u × SlotContext u) + (signatureEquiv u).symm + +@[simp] theorem card_position (u : ℕ) : Fintype.card (Position u) = 3 * u := by + simp [Position, Nat.mul_comm] + +theorem card_signature (u : ℕ) : + Fintype.card (Signature u) = + 2 ^ (3 * u) * ((2 ^ (3 * u)) ^ (3 * u) * 3 ^ u) := by + rw [Fintype.card_congr (signatureEquiv u)] + simp [NameProfile, Nat.mul_comm] + +def positiveAt {n : ℕ} (clause : Clause n) : Slot → Bool + | .first => clause[0].positive + | .second => clause[1].positive + | .third => clause[2].positive + +def occurrenceName (F : Formula) {u : ℕ} (c : ClauseContext F u) + (p : Position u) : Fin F.«variables» := + nameAt (clauseAt F (c p.1)) p.2 + +def contextNameProfile (F : Formula) {u : ℕ} (c : ClauseContext F u) : NameProfile u := + fun p q => decide (occurrenceName F c p = occurrenceName F c q) + +def ofContext (F : Formula) {u : ℕ} (c : ClauseContext F u) + (selected : SlotContext u) : Signature u where + signs p := positiveAt (clauseAt F (c p.1)) p.2 + sameName := contextNameProfile F c + selected := selected + +@[simp] theorem ofContext_signs (F : Formula) {u : ℕ} (c : ClauseContext F u) + (s : SlotContext u) (p : Position u) : + (ofContext F c s).signs p = positiveAt (clauseAt F (c p.1)) p.2 := rfl + +@[simp] theorem ofContext_sameName (F : Formula) {u : ℕ} (c : ClauseContext F u) + (s : SlotContext u) (p q : Position u) : + (ofContext F c s).sameName p q = + decide (occurrenceName F c p = occurrenceName F c q) := rfl + +@[simp] theorem ofContext_selected (F : Formula) {u : ℕ} (c : ClauseContext F u) + (s : SlotContext u) : (ofContext F c s).selected = s := rfl + +def signatureSatisfies {u : ℕ} (σ : Signature u) (j : J u) (t : Fin u) : Bool := + (literalValue (σ.signs (t, .first)) (j t).first || + literalValue (σ.signs (t, .second)) (j t).second) || + literalValue (σ.signs (t, .third)) (j t).third + +def signatureValid {u : ℕ} (σ : Signature u) (j : J u) : Bool := + decide ((∀ t, signatureSatisfies σ j t = true) ∧ + ∀ t t' s s', σ.sameName (t, s) (t', s') = true → + answerAt (j t) s = answerAt (j t') s') + +@[simp] theorem signatureSatisfies_ofContext (F : Formula) {u : ℕ} + (c : ClauseContext F u) (s : SlotContext u) (j : J u) (t : Fin u) : + signatureSatisfies (ofContext F c s) j t = + localSatisfies (clauseAt F (c t)) (j t) := rfl + +theorem signature_validJ (F : Formula) {u : ℕ} (c : ClauseContext F u) + (s : SlotContext u) (j : J u) : + signatureValid (ofContext F c s) j = validJ F c j := by + apply Bool.eq_iff_iff.mpr + constructor + · intro h + have hs := of_decide_eq_true h + apply (validJ_eq_true_iff F c j).mpr + constructor + · intro t + exact (signatureSatisfies_ofContext F c s j t).symm.trans (hs.1 t) + · intro t t' a a' hname + apply hs.2 t t' a a' + exact decide_eq_true hname + · intro h + have hs := (validJ_eq_true_iff F c j).mp h + apply decide_eq_true + constructor + · intro t + exact (signatureSatisfies_ofContext F c s j t).trans (hs.1 t) + · intro t t' a a' heq + exact hs.2 t t' a a' (of_decide_eq_true heq) + +def signatureCanonicalSlot {u : ℕ} (σ : Signature u) (t : Fin u) : Slot := + if σ.sameName (t, .first) (t, σ.selected t) then .first + else if σ.sameName (t, .second) (t, σ.selected t) then .second else .third + +def signatureProjection {u : ℕ} (σ : Signature u) (j : J u) : I u := + fun t => answerAt (j t) (signatureCanonicalSlot σ t) + +theorem signatureCanonicalSlot_ofContext (F : Formula) {u : ℕ} + (c : ClauseContext F u) (s : SlotContext u) (t : Fin u) : + signatureCanonicalSlot (ofContext F c s) t = + canonicalSlot (clauseAt F (c t)) (sampledVariables F c s t) := by + by_cases hfirst : nameAt (clauseAt F (c t)) .first = + nameAt (clauseAt F (c t)) (s t) + · simp [signatureCanonicalSlot, canonicalSlot, ofContext, contextNameProfile, + occurrenceName, sampledVariables, hfirst] + · by_cases hsecond : nameAt (clauseAt F (c t)) .second = + nameAt (clauseAt F (c t)) (s t) + · simp [signatureCanonicalSlot, canonicalSlot, ofContext, contextNameProfile, + occurrenceName, sampledVariables, hfirst, hsecond] + · simp [signatureCanonicalSlot, canonicalSlot, ofContext, contextNameProfile, + occurrenceName, sampledVariables, hfirst, hsecond] + +theorem signature_pi (F : Formula) {u : ℕ} (c : ClauseContext F u) + (s : SlotContext u) (j : J u) : + signatureProjection (ofContext F c s) j = pi F c (sampledVariables F c s) j := by + funext t + simp only [signatureProjection, signatureCanonicalSlot_ofContext, pi] + +theorem signature_projection_selected (F : Formula) {u : ℕ} + (c : ClauseContext F u) (s : SlotContext u) (j : J u) + (hj : signatureValid (ofContext F c s) j = true) : + signatureProjection (ofContext F c s) j = fun t => answerAt (j t) (s t) := by + rw [signature_pi] + have hv : validJ F c j = true := by simpa only [signature_validJ] using hj + funext t + exact (sampled_eq_pi F c (sampledVariables F c s) j hv t (s t) rfl).symm + +theorem validJ_eq_of_signature_eq (F G : Formula) {u : ℕ} + (c : ClauseContext F u) (d : ClauseContext G u) (s s' : SlotContext u) + (h : ofContext F c s = ofContext G d s') (j : J u) : + validJ F c j = validJ G d j := by + rw [← signature_validJ F c s, h, signature_validJ] + +theorem pi_eq_of_signature_eq (F G : Formula) {u : ℕ} + (c : ClauseContext F u) (d : ClauseContext G u) (s s' : SlotContext u) + (h : ofContext F c s = ofContext G d s') (j : J u) : + pi F c (sampledVariables F c s) j = pi G d (sampledVariables G d s') j := by + rw [← signature_pi F c s, h, signature_pi] + +end MinUncutGames.Foundations.Hastad.SourceLocalSignature + +namespace MinUncutGames.Foundations.Hastad.SourceLocalEquation + +open Target SourceContexts SourceOccurrences SourceLocalSignature +open MinUncutGames.Reduction.CloneGap +open MinUncutGames.Reduction.FiniteNoise + +abbrev LocalKey (u : ℕ) := Cube (I u) ⊕ (Cube (J u) ⊕ Unit) +abbrev LocalInput (u D : ℕ) := Signature u × SourceTape.TestTape (I u) (J u) D + +def signatureEncoding (u : ℕ) : Encoding (Signature u) := + let position := (Encoding.fin u).prod slotEncoding + let fields := (position.function Encoding.bool).prod + ((position.function (position.function Encoding.bool)).prod (slotContextEncoding u)) + ⟨fields.size, (signatureEquiv u).trans fields.code⟩ + +def signatureList (u : ℕ) : List (Signature u) := (signatureEncoding u).enumerate + +theorem mem_signatureList (u : ℕ) (σ : Signature u) : σ ∈ signatureList u := + (signatureEncoding u).mem_enumerate σ + +theorem signatureList_nodup (u : ℕ) : (signatureList u).Nodup := + (signatureEncoding u).nodup_enumerate + +theorem signatureList_length (u : ℕ) : + (signatureList u).length = (signatureEncoding u).size := + (signatureEncoding u).length_enumerate + +def localInputEncoding (u D : ℕ) : Encoding (LocalInput u D) := + (signatureEncoding u).prod (testTapeEncoding u D) + +def localInputs (u D : ℕ) : List (LocalInput u D) := (localInputEncoding u D).enumerate + +theorem mem_localInputs (u D : ℕ) (p : LocalInput u D) : p ∈ localInputs u D := + (localInputEncoding u D).mem_enumerate p + +theorem localInputs_nodup (u D : ℕ) : (localInputs u D).Nodup := + (localInputEncoding u D).nodup_enumerate + +theorem localInputs_length (u D : ℕ) : + (localInputs u D).length = (localInputEncoding u D).size := + (localInputEncoding u D).length_enumerate + +def localKeyEncoding (u : ℕ) : Encoding (LocalKey u) := + ((iEncoding u).function Encoding.bool).sum + (((jEncoding u).function Encoding.bool).sum Encoding.unit) + +def emptyLocalAddress (u : ℕ) : EmptyContext.Address (leftAnchor u) → LocalKey u + | .inl f => .inl f.val + | .inr _ => .inr (.inr ()) + +def foldedLocalAddress (u : ℕ) (valid : J u → Bool) + (j₀ : {j : J u // valid j = true}) : + FoldedEquation.Address (leftAnchor u) j₀ → LocalKey u + | .inl f => .inl f.val + | .inr g => .inr (.inl (extendRestricted valid g.val)) + +def equationFor (u D : ℕ) (valid : J u → Bool) (π : J u → I u) + (t : SourceTape.TestTape (I u) (J u) D) : Equation (LocalKey u) := + match firstValid (jEncoding u) valid with + | none => mapEquation (emptyLocalAddress u) (EmptyContext.equation (leftAnchor u) t.1) + | some j₀ => mapEquation (foldedLocalAddress u valid j₀) + (FoldedEquation.conditionedEquation valid π (leftAnchor u) j₀ + t.1 t.2.2 (realizedNoise t.2.1)) + +def equation (u D : ℕ) (σ : Signature u) + (t : SourceTape.TestTape (I u) (J u) D) : Equation (LocalKey u) := + equationFor u D (signatureValid σ) (signatureProjection σ) t + +def emit (u D : ℕ) (p : LocalInput u D) : Equation (LocalKey u) := + equation u D p.1 p.2 + +def addressMap (F : Formula) (u : ℕ) (c : ClauseContext F u) + (v : VariableContext F u) : LocalKey u → Fin (nBits F u) + | .inl f => (proofEncoding F u).code (.inl (v, f)) + | .inr (.inl g) => (proofEncoding F u).code (.inr (.inl (c, g))) + | .inr (.inr _) => dummyIndex F u + +theorem mapEquation_comp {A B C : Type} (g : B → C) (f : A → B) (e : Equation A) : + mapEquation g (mapEquation f e) = mapEquation (g ∘ f) e := rfl + +theorem addressMap_emptyLocalAddress (F : Formula) (u : ℕ) + (c : ClauseContext F u) (v : VariableContext F u) : + addressMap F u c v ∘ emptyLocalAddress u = emptyAddress F u v := by + funext a + cases a <;> rfl + +theorem addressMap_foldedLocalAddress (F : Formula) (u : ℕ) + (c : ClauseContext F u) (v : VariableContext F u) (valid : J u → Bool) + (j₀ : {j : J u // valid j = true}) : + addressMap F u c v ∘ foldedLocalAddress u valid j₀ = + localAddress (variableEncoding F u) (clauseEncoding F u) (iEncoding u) (jEncoding u) + v c valid (leftAnchor u) j₀ := by + funext a + cases a <;> rfl + +theorem contextEquation_eq_map_equationFor (F : Formula) (u D : ℕ) + (c : ClauseContext F u) (v : VariableContext F u) + (t : SourceTape.TestTape (I u) (J u) D) : + contextEquation F u D c v t = + mapEquation (addressMap F u c v) (equationFor u D (validJ F c) (pi F c v) t) := by + unfold contextEquation equationFor rightAnchor + cases h : firstValid (jEncoding u) (validJ F c) with + | none => + rw [mapEquation_comp, addressMap_emptyLocalAddress] + | some j₀ => + rw [mapEquation_comp, addressMap_foldedLocalAddress] + rfl + +theorem contextEquation_eq_map (F : Formula) (u D : ℕ) + (c : ClauseContext F u) (s : SlotContext u) + (t : SourceTape.TestTape (I u) (J u) D) : + contextEquation F u D c (sampledVariables F c s) t = + mapEquation (addressMap F u c (sampledVariables F c s)) + (equation u D (ofContext F c s) t) := by + have hv : signatureValid (ofContext F c s) = validJ F c := + funext (signature_validJ F c s) + have hp : signatureProjection (ofContext F c s) = pi F c (sampledVariables F c s) := + funext (signature_pi F c s) + rw [equation, hv, hp] + exact contextEquation_eq_map_equationFor F u D c (sampledVariables F c s) t + +theorem sourceEquation_eq_map_emit (F : Formula) (u D : ℕ) + (p : SourceIndex F u D) : + sourceEquation F u D p = + mapEquation (addressMap F u p.1.1 (sampledVariables F p.1.1 p.1.2)) + (emit u D (ofContext F p.1.1 p.1.2, p.2)) := + contextEquation_eq_map F u D p.1.1 p.1.2 p.2 + +end MinUncutGames.Foundations.Hastad.SourceLocalEquation + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/ContextPrepare.lean b/lean/OAI/Computability/MinUncut/PCP/ContextPrepare.lean new file mode 100644 index 0000000000000000000000000000000000000000..3d21fa2f31050a7dc9fc8085bfdd5f8cf3e0be90 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/ContextPrepare.lean @@ -0,0 +1,544 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.ProfileBridge +import OAI.Computability.MinUncut.Machines.MachineSubroutine + +namespace OAI + +section +namespace MinUncutGames.Foundations.Hastad.SourceContextPrepare + +open Turing MinUncutGames.Foundations.Complexity +open Target PCP SourceContexts SourceOccurrences SourceLocalSignature SourceProfileBridge + +abbrev Arena (u : Nat) (Extra : Type) := SourceContextLoad.Tape u Extra +abbrev LoadState := Unit × Option Bool +abbrev PrepareState (u : Nat) (τ : Type) := SourceSignaturePrepare.State u τ +abbrev State (u : Nat) (τ : Type) := LoadState × PrepareState u τ +abbrev Label (u : Nat) := SourceContextLoad.Label u ⊕ SourceSignaturePrepare.Label u + +variable {u : Nat} {Extra τ : Type} + +def prepareEntry (u : Nat) : SourceSignaturePrepare.Label u := + .profile (MachineFieldProfile.labelAt + (MachineFieldProfile.allPairs (SourceSignaturePrepare.Width u)) 0 0) + +def stateSwap (u : Nat) (τ : Type) : PrepareState u τ × LoadState ≃ State u τ := + Equiv.prodComm _ _ + +def program : Label u → TM2.Stmt (fun _ : Arena u Extra => Bool) (Label u) (State u τ) + | .inl l => MachineStateFrame.statement Sum.inl (some (.inr (prepareEntry u))) + (SourceContextLoad.program l) + | .inr l => MachineControl.statement id (stateSwap u τ) + (MachineStateFrame.statement Sum.inr none (SourceSignaturePrepare.program l)) + +def preparationConfiguration (loaderState : LoadState) + (c : TM2.Cfg (fun _ : Arena u Extra => Bool) (SourceSignaturePrepare.Label u) (PrepareState u τ)) : + TM2.Cfg (fun _ : Arena u Extra => Bool) (Label u) (State u τ) := + MachineControl.configuration id (stateSwap u τ) + (MachineStateFrame.configuration Sum.inr none loaderState c) + +variable [DecidableEq Extra] + +theorem preparation_step (loaderState : LoadState) + (a b : TM2.Cfg (fun _ : Arena u Extra => Bool) + (SourceSignaturePrepare.Label u) (PrepareState u τ)) + (h : TM2.step SourceSignaturePrepare.program a = some b) : + TM2.step program (preparationConfiguration loaderState a) = + some (preparationConfiguration loaderState b) := by + rcases a with ⟨label, state, tapes⟩ + cases label with + | none => cases h + | some l => + change some (TM2.stepAux (SourceSignaturePrepare.program l) state tapes) = some b at h + cases Option.some.inj h + change some (TM2.stepAux + (MachineControl.statement id (stateSwap u τ) + (MachineStateFrame.statement Sum.inr none (SourceSignaturePrepare.program l))) + ((stateSwap u τ) (state, loaderState)) tapes) = _ + rw [MachineControl.stepAux_simulation, MachineStateFrame.stepAux_simulation] + rfl + +def initialState (initialProfile : MachineFieldProfile.Profile (SourceSignaturePrepare.Width u)) + (initial : Signature u) (ambient : τ) : State u τ := + (((), none), (MachineFieldProfile.normalState initialProfile, (initial, ambient))) + +def finalState (F : Formula) (c : ClauseContext F u) (selected : SlotContext u) + (ambient : τ) : State u τ := + (((), none), (MachineFieldProfile.normalState (MachineFieldProfile.equalityProfile (nameWords F c)), + (ofContext F c selected, ambient))) + +noncomputable def loadInTime (F : Formula) (c : ClauseContext F u) + (base : Arena u Extra → List Bool) + (hformula : base .formula = formulaBits F) + (hcurrent : ∀ j, base (.current j) = encodeWord (c j).val) + (hindex : base .index = []) (hwork : base .work = []) + (hscratch : base .scratch = []) (hcopy : base .copyScratch = []) + (initialProfile : MachineFieldProfile.Profile (SourceSignaturePrepare.Width u)) + (initial : Signature u) (ambient : τ) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (.inl (SourceContextLoad.labelAt 0)), initialState initialProfile initial ambient, base⟩ + (some ⟨some (.inr (prepareEntry u)), initialState initialProfile initial ambient, + SourceContextLoad.stageTapes F c base u⟩) + (u * (10 * (formulaBits F).length + 20) + 1) := by + have run := SourceContextLoad.loadUnaryInTime F c base hformula hcurrent + hindex hwork hscratch hcopy + have lifted := MachineStateFrame.execution Sum.inl (some (.inr (prepareEntry u))) + (MachineFieldProfile.normalState initialProfile, (initial, ambient)) + SourceContextLoad.program program (fun _ => rfl) run + simpa only [MachineStateFrame.configuration, MachineStateFrame.frameConfiguration, + MachineSubroutine.configuration, MachineSubroutine.label, initialState] using lifted + +def signatureInTime (F : Formula) (c : ClauseContext F u) (selected : SlotContext u) + (base : Arena u Extra → List Bool) + (hindex : base .index = []) (hwork : base .work = []) (hscratch : base .scratch = []) + (hfields : ∀ p : Position u, base (SourceSignaturePrepare.variableField p) = []) + (initialProfile : MachineFieldProfile.Profile (SourceSignaturePrepare.Width u)) + (initial : Signature u) (hselected : initial.selected = selected) (ambient : τ) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (.inr (prepareEntry u)), initialState initialProfile initial ambient, + SourceContextLoad.stageTapes F c base u⟩ + (some ⟨none, finalState F c selected ambient, SourceContextLoad.stageTapes F c base u⟩) + (SourceSignaturePrepare.Width u * SourceSignaturePrepare.Width u * + (5 * (formulaBits F).length + 6) + 2) := by + have run := SourceSignaturePrepare.loadedPrepareInTime F c selected base + hindex hwork hscratch hfields initialProfile initial hselected ambient + have lifted := MachineComposition.liftExecutionInTime + (TM2.step SourceSignaturePrepare.program) (TM2.step program) + (preparationConfiguration ((), none)) (preparation_step ((), none)) run + simpa only [preparationConfiguration, MachineControl.configuration, MachineStateFrame.configuration, + MachineStateFrame.frameConfiguration, MachineSubroutine.configuration, + MachineSubroutine.label, Option.map_some, Option.map_none, id_eq, stateSwap, + Equiv.prodComm_apply, Prod.swap, initialState, finalState, prepareEntry] using lifted + +noncomputable def prepareInTime (F : Formula) (c : ClauseContext F u) (selected : SlotContext u) + (base : Arena u Extra → List Bool) + (hformula : base .formula = formulaBits F) + (hcurrent : ∀ j, base (.current j) = encodeWord (c j).val) + (hindex : base .index = []) (hwork : base .work = []) + (hscratch : base .scratch = []) (hcopy : base .copyScratch = []) + (hfields : ∀ p : Position u, base (SourceSignaturePrepare.variableField p) = []) + (initialProfile : MachineFieldProfile.Profile (SourceSignaturePrepare.Width u)) + (initial : Signature u) (hselected : initial.selected = selected) (ambient : τ) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (.inl (SourceContextLoad.labelAt 0)), initialState initialProfile initial ambient, base⟩ + (some ⟨none, finalState F c selected ambient, SourceContextLoad.stageTapes F c base u⟩) + ((u * (10 * (formulaBits F).length + 20) + 1) + + (SourceSignaturePrepare.Width u * SourceSignaturePrepare.Width u * + (5 * (formulaBits F).length + 6) + 2)) := by + have firstRun := loadInTime F c base hformula hcurrent hindex hwork hscratch hcopy + initialProfile initial ambient + have secondRun := signatureInTime F c selected base hindex hwork hscratch hfields + initialProfile initial hselected ambient + simpa only [Nat.add_comm] using + StateTransition.EvalsToInTime.trans (TM2.step program) _ _ _ _ _ firstRun secondRun + +def machine (u : Nat) (Extra τ : Type) [DecidableEq Extra] [Fintype Extra] [Fintype τ] + (initialProfile : MachineFieldProfile.Profile (SourceSignaturePrepare.Width u)) + (initial : Signature u) (ambient : τ) : FinTM2 where + K := Arena u Extra + k₀ := .formula + k₁ := .formula + Γ _ := Bool + Λ := Label u + main := .inl (SourceContextLoad.labelAt 0) + σ := State u τ + initialState := initialState initialProfile initial ambient + m := program + +end MinUncutGames.Foundations.Hastad.SourceContextPrepare + +end +section + +namespace MinUncutGames.Foundations.Hastad.SourceLoopInit + +open Turing MinUncutGames.Foundations.Complexity +open MachineComposition SourceMachine + +inductive HeaderTape + | variableCount | clauseCount + deriving DecidableEq + +protected abbrev HeaderTape.enumList : List HeaderTape := [.variableCount, .clauseCount] + +protected theorem HeaderTape.enumList_getElem?_ctorIdx_eq (x : HeaderTape) : + HeaderTape.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem HeaderTape.enumList_nodup : HeaderTape.enumList.Nodup := by decide + +instance : Fintype HeaderTape where + elems := ⟨HeaderTape.enumList, HeaderTape.enumList_nodup⟩ + complete x := by cases x <;> decide + +abbrev Tape (u : Nat) (Extra : Type) := SourceContextLoad.Tape u (HeaderTape ⊕ Extra) + +inductive Label (u : Nat) + | inputCopyOut | inputCopyBack | read (slot : Fin 3 × Bool) | clearWork + | seed (j : Fin u) | digitCopyOut (j : Fin u) | digitCopyBack (j : Fin u) + | trim (j : Fin u) | done + deriving DecidableEq, Fintype + +variable {u : Nat} {Extra : Type} + +def variableHeader : Tape u Extra := .extra (.inl .variableCount) +def clauseHeader : Tape u Extra := .extra (.inl .clauseCount) +def headerDestination (r : Nat) : Tape u Extra := if r = 0 then variableHeader else clauseHeader +def readStart (r : Nat) : Label u := .read (SourceFieldArray.boundedIndex 2 r, false) +def readLoop (r : Nat) : Label u := .read (SourceFieldArray.boundedIndex 2 r, true) +def labelAt (r : Nat) : Label u := if h : r < u then .seed ⟨r, h⟩ else .done + +def program : Label u → TM2.Stmt (fun _ : Tape u Extra => Bool) (Label u) (Unit × Option Bool) + | .inputCopyOut => Reduction.MachineTransfer.loopAt .formula .scratch id false + .inputCopyOut (some .inputCopyBack) + | .inputCopyBack => MachineCopy.forkLoop .scratch .formula .work false + .inputCopyBack (some (readStart 0)) + | .read slot => if slot.1.val < 2 then + if slot.2 then fieldLoop .work (headerDestination slot.1.val) (.read (slot.1, true)) + (some (readStart (slot.1.val + 1))) + else fieldStart (headerDestination slot.1.val) (.read (slot.1, true)) + else SourceFieldArray.finish .work (some .clearWork) + | .clearWork => MachineDrain.drain .work .clearWork (some (labelAt 0)) + | .seed j => .push (.current j) (fun _ => false) (.goto fun _ => .digitCopyOut j) + | .digitCopyOut j => Reduction.MachineTransfer.loopAt clauseHeader .copyScratch id false + (.digitCopyOut j) (some (.digitCopyBack j)) + | .digitCopyBack j => MachineCopy.forkLoop .copyScratch clauseHeader (.remaining j) false + (.digitCopyBack j) (some (.trim j)) + | .trim j => .pop (.remaining j) (fun state _ => state) (.goto fun _ => labelAt (j.val + 1)) + | .done => .halt + +theorem atReadStart (r : Nat) (hr : r < 2) : + program (u := u) (Extra := Extra) (readStart r) = + fieldStart (headerDestination r) (readLoop r) := by + simp [program, readStart, readLoop, SourceFieldArray.boundedIndex_val hr.le, hr] + +theorem atReadLoop (r : Nat) (hr : r < 2) : + program (u := u) (Extra := Extra) (readLoop r) = fieldLoop .work (headerDestination r) + (readLoop r) (some (readStart (r + 1))) := by + simp [program, readStart, readLoop, SourceFieldArray.boundedIndex_val hr.le, hr] + +theorem atReadDone : program (u := u) (Extra := Extra) (readStart 2) = + SourceFieldArray.finish .work (some .clearWork) := by + simp [program, readStart] + +variable [DecidableEq Extra] + +def copiedInput (base : Tape u Extra → List Bool) : Tape u Extra → List Bool := + Function.update base .work (base .formula) + +def readOutput (F : Target.Formula) (base : Tape u Extra → List Bool) : Tape u Extra → List Bool := + SourceFieldArray.sequenceTapes .work headerDestination (copiedInput base) 0 + [F.«variables», F.clauses.length] (encodeWords (F.clauses.flatMap clauseWords)) + +def headerOutput (F : Target.Formula) (base : Tape u Extra → List Bool) : Tape u Extra → List Bool := + Function.update (Function.update (Function.update base .work []) variableHeader + (encodeWord F.«variables» ++ base variableHeader)) clauseHeader + (encodeWord F.clauses.length ++ base clauseHeader) + +theorem clear_readOutput (F : Target.Formula) (base : Tape u Extra → List Bool) : + Function.update (readOutput F base) .work [] = headerOutput F base := by + funext p + cases p <;> simp [readOutput, headerOutput, SourceFieldArray.sequenceTapes, + afterField, fieldTapes, copiedInput, headerDestination, variableHeader, clauseHeader] + rename_i e + cases e with + | inl h => cases h <;> simp + | inr e => simp + +theorem readOutput_work (F : Target.Formula) (base : Tape u Extra → List Bool) : + readOutput F base .work = encodeWords (F.clauses.flatMap clauseWords) := by + simp [readOutput, SourceFieldArray.sequenceTapes, afterField, fieldTapes, + headerDestination, variableHeader, clauseHeader, encodeWords] + +theorem headerOutput_frame (F : Target.Formula) (base : Tape u Extra → List Bool) + (p : Tape u Extra) (hw : p ≠ .work) (hn : p ≠ variableHeader) (hm : p ≠ clauseHeader) : + headerOutput F base p = base p := by simp [headerOutput, hw, hn, hm] + +def headerInTime (F : Target.Formula) (base : Tape u Extra → List Bool) + (hformula : base .formula = formulaBits F) (hwork : base .work = []) + (hscratch : base .scratch = []) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some .inputCopyOut, ((), register), base⟩ + (some ⟨some (labelAt 0), ((), none), headerOutput F base⟩) + (3 * (formulaBits F).length + 6) := by + have copying := MachineCopy.copyInTime .formula .work .scratch + (by simp) (by simp) (by simp) false .inputCopyOut .inputCopyBack (some (readStart 0)) + program rfl rfl base hscratch () register + have hc : Function.update base .work (base .formula ++ base .work) = copiedInput base := by + simp [copiedInput, hwork] + rw [hc] at copying + have reading := SourceFieldArray.sequenceInTime .work headerDestination readStart readLoop + (some .clearWork) program (copiedInput base) 0 [F.«variables», F.clauses.length] + (encodeWords (F.clauses.flatMap clauseWords)) + (by intro r hr; simp [headerDestination, variableHeader, clauseHeader]; split <;> simp) + (by intro r hr; simpa only [Nat.zero_add] using atReadStart (u := u) (Extra := Extra) r (by simpa using hr)) + (by intro r hr; simpa only [Nat.zero_add] using atReadLoop (u := u) (Extra := Extra) r (by simpa using hr)) + (by simpa using (atReadDone (u := u) (Extra := Extra))) + (by simp [copiedInput, hformula, formulaBits, formulaWords, encodeWords, List.append_assoc]) () none + have draining := MachineDrain.drainInTime .work .clearWork (some (labelAt 0)) + program rfl (readOutput F base) () none + have joined := StateTransition.EvalsToInTime.trans (TM2.step program) _ _ _ _ _ + (StateTransition.EvalsToInTime.trans (TM2.step program) _ _ _ _ _ copying reading) draining + refine { steps := joined.steps, evals_in_steps := ?_, steps_le_m := ?_ } + · simpa only [clear_readOutput] using joined.evals_in_steps + · apply Nat.le_trans joined.steps_le_m + rw [readOutput_work, hformula] + have he : (formulaBits F).length = F.«variables» + F.clauses.length + 2 + + (encodeWords (F.clauses.flatMap clauseWords)).length := by + simp [formulaBits, formulaWords, encodeWords, Nat.add_assoc] + omega + simp only [List.sum_cons, List.sum_nil, List.length_cons, List.length_nil] + omega + +def digitOutput (j : Fin u) (m : Nat) (base : Tape u Extra → List Bool) : Tape u Extra → List Bool := + Function.update (Function.update base (.current j) (encodeWord 0)) (.remaining j) (encodeWord (m - 1)) + +theorem digitOutput_frame (j : Fin u) (m : Nat) (base : Tape u Extra → List Bool) + (p : Tape u Extra) (hc : p ≠ .current j) (hr : p ≠ .remaining j) : + digitOutput j m base p = base p := by simp [digitOutput, hc, hr] + +def digitInTime (j : Fin u) (m : Nat) (hm : 0 < m) (base : Tape u Extra → List Bool) + (hcount : base clauseHeader = encodeWord m) + (hcurrent : base (.current j) = []) (hremaining : base (.remaining j) = []) + (hscratch : base .copyScratch = []) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (.seed j), ((), none), base⟩ + (some ⟨some (labelAt (j.val + 1)), ((), none), digitOutput j m base⟩) + (2 * m + 6) := by + let seeded := Function.update base (.current j) (encodeWord 0) + have seedRun : StateTransition.EvalsToInTime (TM2.step program) + ⟨some (.seed j), ((), none), base⟩ + (some ⟨some (.digitCopyOut j), ((), none), seeded⟩) 1 := by + refine { steps := 1, evals_in_steps := ?_, steps_le_m := Nat.le_refl _ } + change TM2.step program ⟨some (.seed j), ((), none), base⟩ = _ + simp [program, TM2.step, TM2.stepAux, seeded, hcurrent, encodeWord] + have copying := MachineCopy.copyInTime clauseHeader (.remaining j) .copyScratch + (by simp [clauseHeader]) (by simp [clauseHeader]) (by simp) + false (.digitCopyOut j) (.digitCopyBack j) (some (.trim j)) program rfl rfl seeded + (by simpa [seeded] using hscratch) () none + let copied := Function.update seeded (.remaining j) (encodeWord m) + have he : Function.update seeded (.remaining j) + (seeded clauseHeader ++ seeded (.remaining j)) = copied := by + have hcount' : base (.extra (.inl .clauseCount)) = encodeWord m := hcount + simp [copied, seeded, clauseHeader, hremaining, hcount'] + rw [he] at copying + have trimRun : StateTransition.EvalsToInTime (TM2.step program) + ⟨some (.trim j), ((), none), copied⟩ + (some ⟨some (labelAt (j.val + 1)), ((), none), digitOutput j m base⟩) 1 := by + refine { steps := 1, evals_in_steps := ?_, steps_le_m := Nat.le_refl _ } + change TM2.step program ⟨some (.trim j), ((), none), copied⟩ = _ + have hn : m = (m - 1) + 1 := by omega + have htail : (encodeWord m).tail = encodeWord (m - 1) := by + conv_lhs => rw [hn] + simp [encodeWord, List.replicate_succ] + simp [program, TM2.step, TM2.stepAux, copied, seeded, digitOutput, htail] + have joined := StateTransition.EvalsToInTime.trans (TM2.step program) _ _ _ _ _ + (StateTransition.EvalsToInTime.trans (TM2.step program) _ _ _ _ _ seedRun copying) trimRun + refine { steps := joined.steps, evals_in_steps := joined.evals_in_steps, steps_le_m := ?_ } + apply Nat.le_trans joined.steps_le_m + have hs : seeded clauseHeader = encodeWord m := by simpa [seeded, clauseHeader] using hcount + rw [hs, encodeWord_length] + omega + +def stageTapes (m : Nat) (base : Tape u Extra → List Bool) : Nat → Tape u Extra → List Bool + | 0 => base + | r + 1 => if h : r < u then digitOutput ⟨r, h⟩ m (stageTapes m base r) + else stageTapes m base r + +theorem stageTapes_frame (m : Nat) (base : Tape u Extra → List Bool) (r : Nat) + (p : Tape u Extra) (hc : ∀ j, p ≠ .current j) (hr : ∀ j, p ≠ .remaining j) : + stageTapes m base r p = base p := by + induction r with + | zero => rfl + | succ r ih => + simp only [stageTapes] + split + · rw [digitOutput_frame _ _ _ _ (hc _) (hr _), ih] + · exact ih + +theorem stageTapes_current (m : Nat) (base : Tape u Extra → List Bool) (r : Nat) (j : Fin u) : + stageTapes m base r (.current j) = if j.val < r then encodeWord 0 else base (.current j) := by + induction r with + | zero => simp [stageTapes] + | succ r ih => + simp only [stageTapes] + split + next hr => + by_cases hj : j = (⟨r, hr⟩ : Fin u) + · subst j; simp [digitOutput] + · rw [digitOutput_frame _ _ _ _ (by simpa using hj) (by simp), ih] + have hval : j.val ≠ r := by intro h; apply hj; exact Fin.ext h + have he : j.val < r + 1 ↔ j.val < r := by omega + simp only [he] + next hr => + rw [ih] + have hjr : j.val < r := by omega + have hjr' : j.val < r + 1 := by omega + simp only [hjr, hjr', ite_true] + +theorem stageTapes_remaining (m : Nat) (base : Tape u Extra → List Bool) (r : Nat) (j : Fin u) : + stageTapes m base r (.remaining j) = + if j.val < r then encodeWord (m - 1) else base (.remaining j) := by + induction r with + | zero => simp [stageTapes] + | succ r ih => + simp only [stageTapes] + split + next hr => + by_cases hj : j = (⟨r, hr⟩ : Fin u) + · subst j; simp [digitOutput] + · rw [digitOutput_frame _ _ _ _ (by simp) (by simpa using hj), ih] + have hval : j.val ≠ r := by intro h; apply hj; exact Fin.ext h + have he : j.val < r + 1 ↔ j.val < r := by omega + simp only [he] + next hr => + rw [ih] + have hjr : j.val < r := by omega + have hjr' : j.val < r + 1 := by omega + simp only [hjr, hjr', ite_true] + +def prefixInTime (m : Nat) (hm : 0 < m) (base : Tape u Extra → List Bool) + (hcount : base clauseHeader = encodeWord m) + (hcurrent : ∀ j, base (.current j) = []) (hremaining : ∀ j, base (.remaining j) = []) + (hscratch : base .copyScratch = []) (r : Nat) (hr : r ≤ u) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labelAt 0), ((), none), base⟩ + (some ⟨some (labelAt r), ((), none), stageTapes m base r⟩) + (r * (2 * m + 6)) := by + induction r with + | zero => exact { steps := 0, evals_in_steps := rfl, steps_le_m := by omega } + | succ r ih => + have hru : r < u := by omega + let j : Fin u := ⟨r, hru⟩ + let before := stageTapes m base r + have one := digitInTime j m hm before + (by dsimp only [before]; rw [stageTapes_frame _ _ _ _ (by simp [clauseHeader]) (by simp [clauseHeader])]; exact hcount) + (by simp [before, stageTapes_current, j, hcurrent]) + (by simp [before, stageTapes_remaining, j, hremaining]) + (by dsimp only [before]; rw [stageTapes_frame _ _ _ _ (by simp) (by simp)]; exact hscratch) + have one' : StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labelAt r), ((), none), before⟩ + (some ⟨some (labelAt (r + 1)), ((), none), stageTapes m base (r + 1)⟩) + (2 * m + 6) := by + simpa only [labelAt, dite_eq_left hru, j, stageTapes, before] using one + have joined := StateTransition.EvalsToInTime.trans (TM2.step program) _ _ _ _ _ + (ih (by omega)) one' + simpa only [Nat.add_mul, Nat.one_mul, Nat.add_comm] using joined + +def digitsInTime (m : Nat) (hm : 0 < m) (base : Tape u Extra → List Bool) + (hcount : base clauseHeader = encodeWord m) + (hcurrent : ∀ j, base (.current j) = []) (hremaining : ∀ j, base (.remaining j) = []) + (hscratch : base .copyScratch = []) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labelAt 0), ((), none), base⟩ + (some ⟨none, ((), none), stageTapes m base u⟩) + (u * (2 * m + 6) + 1) := by + have initialRun := prefixInTime m hm base hcount hcurrent hremaining hscratch u (Nat.le_refl _) + have doneRun : StateTransition.EvalsToInTime (TM2.step (program (Extra := Extra))) + ⟨some (labelAt u), ((), none), stageTapes m base u⟩ + (some ⟨none, ((), none), stageTapes m base u⟩) 1 := by + refine { steps := 1, evals_in_steps := ?_, steps_le_m := Nat.le_refl _ } + change TM2.step program ⟨some (labelAt u), ((), none), stageTapes m base u⟩ = _ + simp only [labelAt, Nat.lt_irrefl, ↓reduceDIte] + rfl + simpa only [Nat.add_comm] using + StateTransition.EvalsToInTime.trans (TM2.step program) _ _ _ _ _ initialRun doneRun + +def outputTapes (F : Target.Formula) (base : Tape u Extra → List Bool) : Tape u Extra → List Bool := + stageTapes F.clauses.length (headerOutput F base) u + +def initializeInTime (F : Target.Formula) (hm : 0 < F.clauses.length) + (base : Tape u Extra → List Bool) (hformula : base .formula = formulaBits F) + (hwork : base .work = []) (hscratch : base .scratch = []) (hcopy : base .copyScratch = []) + (hclauseHeader : base clauseHeader = []) + (hcurrent : ∀ j, base (.current j) = []) (hremaining : ∀ j, base (.remaining j) = []) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some .inputCopyOut, ((), none), base⟩ + (some ⟨none, ((), none), outputTapes F base⟩) + ((2 * u + 3) * (formulaBits F).length + 6 * u + 7) := by + have firstRun := headerInTime F base hformula hwork hscratch none + have hcount : headerOutput F base clauseHeader = encodeWord F.clauses.length := by + simp [headerOutput, hclauseHeader] + have secondRun := digitsInTime F.clauses.length hm (headerOutput F base) hcount + (by intro j; rw [headerOutput_frame _ _ _ (by simp) (by simp [variableHeader]) + (by simp [clauseHeader])]; exact hcurrent j) + (by intro j; rw [headerOutput_frame _ _ _ (by simp) (by simp [variableHeader]) + (by simp [clauseHeader])]; exact hremaining j) + (by rw [headerOutput_frame _ _ _ (by simp) (by simp [variableHeader]) + (by simp [clauseHeader])]; exact hcopy) + have joined := StateTransition.EvalsToInTime.trans (TM2.step program) _ _ _ _ _ firstRun secondRun + refine { steps := joined.steps, evals_in_steps := joined.evals_in_steps, steps_le_m := ?_ } + apply Nat.le_trans joined.steps_le_m + have hL := SourceContextLoad.clauses_length_le_input F + have hb : u * (2 * F.clauses.length + 6) ≤ u * (2 * (formulaBits F).length + 6) := + Nat.mul_le_mul_left u (by omega) + have he : (2 * u + 3) * (formulaBits F).length + 6 * u + 7 = + u * (2 * (formulaBits F).length + 6) + 3 * (formulaBits F).length + 7 := by + simp [Nat.add_mul, Nat.mul_add, Nat.mul_comm, Nat.mul_assoc, + Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] + rw [he] + omega + +@[simp] theorem output_current (F : Target.Formula) (base : Tape u Extra → List Bool) (j : Fin u) : + outputTapes F base (.current j) = encodeWord 0 := by + simp only [outputTapes, stageTapes_current, j.isLt, ite_true] + +@[simp] theorem output_remaining (F : Target.Formula) (base : Tape u Extra → List Bool) (j : Fin u) : + outputTapes F base (.remaining j) = encodeWord (F.clauses.length - 1) := by + simp only [outputTapes, stageTapes_remaining, j.isLt, ite_true] + +theorem output_frame (F : Target.Formula) (base : Tape u Extra → List Bool) (p : Tape u Extra) + (hw : p ≠ .work) (hn : p ≠ variableHeader) (hm : p ≠ clauseHeader) + (hc : ∀ j, p ≠ .current j) (hr : ∀ j, p ≠ .remaining j) : + outputTapes F base p = base p := by + rw [outputTapes, stageTapes_frame _ _ _ _ hc hr, headerOutput_frame _ _ _ hw hn hm] + +@[simp] theorem output_work (F : Target.Formula) (base : Tape u Extra → List Bool) : + outputTapes F base .work = [] := by + rw [outputTapes, stageTapes_frame _ _ _ _ (by simp) (by simp)] + simp [headerOutput, variableHeader, clauseHeader] + +@[simp] theorem output_variableHeader (F : Target.Formula) (base : Tape u Extra → List Bool) : + outputTapes F base variableHeader = encodeWord F.«variables» ++ base variableHeader := by + rw [outputTapes, stageTapes_frame _ _ _ _ (by simp [variableHeader]) (by simp [variableHeader])] + simp [headerOutput, variableHeader, clauseHeader] + +@[simp] theorem output_clauseHeader (F : Target.Formula) (base : Tape u Extra → List Bool) : + outputTapes F base clauseHeader = encodeWord F.clauses.length ++ base clauseHeader := by + rw [outputTapes, stageTapes_frame _ _ _ _ (by simp [clauseHeader]) (by simp [clauseHeader])] + simp [headerOutput] + +theorem output_headers (F : Target.Formula) (base : Tape u Extra → List Bool) + (hn : base variableHeader = []) (hm : base clauseHeader = []) : + outputTapes F base variableHeader = encodeWord F.«variables» ∧ + outputTapes F base clauseHeader = encodeWord F.clauses.length := by + simp only [output_variableHeader, output_clauseHeader, hn, hm, List.append_nil, and_self] + +@[simp] theorem output_formula (F : Target.Formula) (base : Tape u Extra → List Bool) : + outputTapes F base .formula = base .formula := + output_frame F base .formula (by simp) (by simp [variableHeader]) + (by simp [clauseHeader]) (by simp) (by simp) + +noncomputable def timePolynomial (u : Nat) : Polynomial Nat := + Polynomial.C (2 * u + 3) * Polynomial.X + Polynomial.C (6 * u + 7) + +theorem timePolynomial_eval (u L : Nat) : + (timePolynomial u).eval L = (2 * u + 3) * L + 6 * u + 7 := by + simp [timePolynomial, Nat.add_assoc] + +def machine (u : Nat) (Extra : Type) [DecidableEq Extra] [Fintype Extra] : FinTM2 where + K := Tape u Extra + k₀ := .formula + k₁ := clauseHeader + Γ _ := Bool + Λ := Label u + main := .inputCopyOut + σ := Unit × Option Bool + initialState := ((), none) + m := program + +end MinUncutGames.Foundations.Hastad.SourceLoopInit + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/DegreeReplacement.lean b/lean/OAI/Computability/MinUncut/PCP/DegreeReplacement.lean new file mode 100644 index 0000000000000000000000000000000000000000..15c131e989473bdf8059c6d251bd741aa929a573 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/DegreeReplacement.lean @@ -0,0 +1,832 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.GraphTables + +namespace OAI + +section +open scoped BigOperators + +namespace MinUncutGames.Foundations.PCP.DegreeReplacement + +open PoweringWalks + +variable {V E A D : Type*} + +abbrev Cloud (G : ConstraintGraph V E A) (v : V) := {e : E // G.tail e = v} + +def cloudIndexEquiv (G : ConstraintGraph V E A) : + (E × D) ≃ (Σ v : V, Cloud G v × D) where + toFun p := ⟨G.tail p.1, (⟨p.1, rfl⟩, p.2)⟩ + invFun p := (p.2.1.val, p.2.2) + left_inv _ := rfl + right_inv := by + rintro ⟨v, ⟨⟨e, he⟩, d⟩⟩ + cases he + rfl + +def cloudRotation (G : ConstraintGraph V E A) + (H : ∀ v, PortGraph (Cloud G v) D) : + (Σ v : V, Cloud G v × D) ≃ (Σ v : V, Cloud G v × D) := + Equiv.sigmaCongrRight (fun v => (H v).rot) + +theorem cloudRotation_involutive (G : ConstraintGraph V E A) + (H : ∀ v, PortGraph (Cloud G v) D) : + Function.Involutive (cloudRotation G H) := by + rintro ⟨v, p⟩ + change (⟨v, (H v).rot ((H v).rot p)⟩ : Σ v : V, Cloud G v × D) = ⟨v, p⟩ + rw [(H v).rot_involutive p] + +def innerRotation (G : ConstraintGraph V E A) + (H : ∀ v, PortGraph (Cloud G v) D) : (E × D) ≃ (E × D) := + ((cloudIndexEquiv G).trans (cloudRotation G H)).trans (cloudIndexEquiv G).symm + +theorem innerRotation_involutive (G : ConstraintGraph V E A) + (H : ∀ v, PortGraph (Cloud G v) D) : + Function.Involutive (innerRotation G H) := by + intro p + apply (cloudIndexEquiv G).injective + simp only [innerRotation, Equiv.trans_apply, Equiv.apply_symm_apply] + exact cloudRotation_involutive G H _ + +theorem innerRotation_tail (G : ConstraintGraph V E A) + (H : ∀ v, PortGraph (Cloud G v) D) (e : E) (d : D) : + G.tail (innerRotation G H (e, d)).1 = G.tail e := by + change G.tail (((H (G.tail e)).rot (⟨e, rfl⟩, d)).1.val) = G.tail e + exact ((H (G.tail e)).rot (⟨e, rfl⟩, d)).1.property + +def replacementStep (G : ConstraintGraph V E A) + (H : ∀ v, PortGraph (Cloud G v) D) : E × (D ⊕ Unit) → E × (D ⊕ Unit) + | (e, Sum.inl d) => + let p := innerRotation G H (e, d) + (p.1, Sum.inl p.2) + | (e, Sum.inr u) => (G.reverse e, Sum.inr u) + +theorem replacementStep_involutive (G : ConstraintGraph V E A) + (H : ∀ v, PortGraph (Cloud G v) D) : + Function.Involutive (replacementStep G H) := by + rintro ⟨e, p⟩ + rcases p with d | u + · change ((innerRotation G H (innerRotation G H (e, d))).1, + (Sum.inl ((innerRotation G H (innerRotation G H (e, d))).2) : D ⊕ Unit)) = + (e, Sum.inl d) + rw [innerRotation_involutive G H (e, d)] + · change (G.reverse (G.reverse e), (Sum.inr u : D ⊕ Unit)) = (e, Sum.inr u) + rw [G.reverse_involutive e] + +def replacementPortGraph (G : ConstraintGraph V E A) + (H : ∀ v, PortGraph (Cloud G v) D) : PortGraph E (D ⊕ Unit) where + rot := + { toFun := replacementStep G H + invFun := replacementStep G H + left_inv := replacementStep_involutive G H + right_inv := replacementStep_involutive G H } + rot_involutive := replacementStep_involutive G H + +def replacementGraph [DecidableEq A] (G : ConstraintGraph V E A) + (H : ∀ v, PortGraph (Cloud G v) D) : + ConstraintGraph E (E × (D ⊕ Unit)) A where + reverse := (replacementPortGraph G H).rot + reverse_involutive := (replacementPortGraph G H).rot_involutive + tail := Prod.fst + accepts p a b := match p.2 with + | Sum.inl _ => decide (a = b) + | Sum.inr _ => G.accepts p.1 a b + reverse_accepts := by + rintro ⟨e, p⟩ a b + rcases p with d | u + · change decide (b = a) = decide (a = b) + simp [eq_comm] + · exact G.reverse_accepts e a b + +def liftLabel (G : ConstraintGraph V E A) (labeling : V → A) : E → A := + fun e => labeling (G.tail e) + +@[simp] theorem replacement_satisfied_inl [DecidableEq A] + (G : ConstraintGraph V E A) (H : ∀ v, PortGraph (Cloud G v) D) + (labeling : V → A) (e : E) (d : D) : + (replacementGraph G H).edgeSatisfied (liftLabel G labeling) (e, Sum.inl d) = + true := by + change decide (labeling (G.tail e) = + labeling (G.tail (innerRotation G H (e, d)).1)) = true + rw [innerRotation_tail G H e d] + simp + +@[simp] theorem replacement_satisfied_inr [DecidableEq A] + (G : ConstraintGraph V E A) (H : ∀ v, PortGraph (Cloud G v) D) + (labeling : V → A) (e : E) (u : Unit) : + (replacementGraph G H).edgeSatisfied (liftLabel G labeling) (e, Sum.inr u) = + G.edgeSatisfied labeling e := rfl + +theorem replacement_complete [DecidableEq A] + (G : ConstraintGraph V E A) (H : ∀ v, PortGraph (Cloud G v) D) + (labeling : V → A) (h : ∀ e, G.edgeSatisfied labeling e = true) : + ∀ p, (replacementGraph G H).edgeSatisfied (liftLabel G labeling) p = true := by + rintro ⟨e, p⟩ + rcases p with d | u + · exact replacement_satisfied_inl G H labeling e d + · rw [replacement_satisfied_inr] + exact h e + +theorem replacement_satisfiable [DecidableEq A] + (G : ConstraintGraph V E A) (H : ∀ v, PortGraph (Cloud G v) D) + (h : G.Satisfiable) : (replacementGraph G H).Satisfiable := by + obtain ⟨labeling, hlabeling⟩ := h + exact ⟨liftLabel G labeling, replacement_complete G H labeling hlabeling⟩ + +theorem rejectionCount_eq_sum [Fintype E] (G : ConstraintGraph V E A) + (labeling : V → A) : + G.rejectionCount labeling = + ∑ e, if G.edgeSatisfied labeling e = false then 1 else 0 := by + classical + simp only [ConstraintGraph.rejectionCount, ConstraintGraph.rejectedDarts, + Finset.card_eq_sum_ones, Finset.sum_filter] + +theorem replacement_rejectionCount [Fintype E] [Fintype D] [DecidableEq A] + (G : ConstraintGraph V E A) (H : ∀ v, PortGraph (Cloud G v) D) + (labeling : V → A) : + (replacementGraph G H).rejectionCount (liftLabel G labeling) = + G.rejectionCount labeling := by + classical + simp only [rejectionCount_eq_sum, Fintype.sum_prod_type, Fintype.sum_sum_type, + replacement_satisfied_inl, replacement_satisfied_inr, Bool.true_eq_false, + ite_false, Finset.sum_const_zero, Fintype.sum_unique, Nat.zero_add] + rfl + +abbrev PaddedDart (_G : ConstraintGraph V E A) (dummy : V → Type*) := + E ⊕ (Σ v : V, dummy v) + +def paddedOwner (G : ConstraintGraph V E A) (dummy : V → Type*) : + PaddedDart G dummy → V + | Sum.inl e => G.tail e + | Sum.inr z => z.1 + +def paddedReverse (G : ConstraintGraph V E A) (dummy : V → Type*) : + PaddedDart G dummy ≃ PaddedDart G dummy := + Equiv.sumCongr G.reverse (Equiv.refl (Σ v : V, dummy v)) + +theorem paddedReverse_involutive (G : ConstraintGraph V E A) (dummy : V → Type*) : + Function.Involutive (paddedReverse G dummy) := by + intro z + cases z with + | inl e => + change (Sum.inl (G.reverse (G.reverse e)) : PaddedDart G dummy) = Sum.inl e + rw [G.reverse_involutive e] + | inr z => rfl + +def paddedGraph (G : ConstraintGraph V E A) (dummy : V → Type*) : + ConstraintGraph V (PaddedDart G dummy) A where + reverse := paddedReverse G dummy + reverse_involutive := paddedReverse_involutive G dummy + tail := paddedOwner G dummy + accepts e a b := match e with + | Sum.inl e => G.accepts e a b + | Sum.inr _ => true + reverse_accepts := by + intro e a b + cases e with + | inl e => exact G.reverse_accepts e a b + | inr z => rfl + +@[simp] theorem padded_satisfied_inl (G : ConstraintGraph V E A) + (dummy : V → Type*) (labeling : V → A) (e : E) : + (paddedGraph G dummy).edgeSatisfied labeling (Sum.inl e) = + G.edgeSatisfied labeling e := rfl + +@[simp] theorem padded_satisfied_inr (G : ConstraintGraph V E A) + (dummy : V → Type*) (labeling : V → A) (z : Σ v : V, dummy v) : + (paddedGraph G dummy).edgeSatisfied labeling (Sum.inr z) = true := rfl + +theorem padded_complete (G : ConstraintGraph V E A) (dummy : V → Type*) + (labeling : V → A) (h : ∀ e, G.edgeSatisfied labeling e = true) : + ∀ c, (paddedGraph G dummy).edgeSatisfied labeling c = true := by + intro c + cases c with + | inl e => exact h e + | inr z => rfl + +theorem padded_satisfiable (G : ConstraintGraph V E A) (dummy : V → Type*) + (h : G.Satisfiable) : (paddedGraph G dummy).Satisfiable := by + obtain ⟨labeling, hlabeling⟩ := h + exact ⟨labeling, padded_complete G dummy labeling hlabeling⟩ + +theorem card_paddedDart [Fintype V] [Fintype E] (G : ConstraintGraph V E A) + (dummy : V → Type*) [∀ v, Fintype (dummy v)] : + Fintype.card (PaddedDart G dummy) = + Fintype.card E + ∑ v, Fintype.card (dummy v) := by + rw [Fintype.card_sum, Fintype.card_sigma] + +theorem padded_rejectionCount [Fintype V] [Fintype E] + (G : ConstraintGraph V E A) (dummy : V → Type*) [∀ v, Fintype (dummy v)] + (labeling : V → A) : + (paddedGraph G dummy).rejectionCount labeling = G.rejectionCount labeling := by + classical + simp only [rejectionCount_eq_sum, Fintype.sum_sum_type, + padded_satisfied_inl, padded_satisfied_inr, Bool.true_eq_false, + ite_false, Finset.sum_const_zero, Nat.add_zero] + rfl + +def paddedReplacementPortGraph (G : ConstraintGraph V E A) (dummy : V → Type*) + (H : ∀ v, PortGraph (Cloud (paddedGraph G dummy) v) D) : + PortGraph (PaddedDart G dummy) (D ⊕ Unit) := + replacementPortGraph (paddedGraph G dummy) H + +def paddedReplacementGraph [DecidableEq A] + (G : ConstraintGraph V E A) (dummy : V → Type*) + (H : ∀ v, PortGraph (Cloud (paddedGraph G dummy) v) D) : + ConstraintGraph (PaddedDart G dummy) (PaddedDart G dummy × (D ⊕ Unit)) A := + replacementGraph (paddedGraph G dummy) H + +theorem paddedReplacement_rejectionCount + [Fintype V] [Fintype E] [Fintype D] [DecidableEq A] + (G : ConstraintGraph V E A) (dummy : V → Type*) [∀ v, Fintype (dummy v)] + (H : ∀ v, PortGraph (Cloud (paddedGraph G dummy) v) D) (labeling : V → A) : + (paddedReplacementGraph G dummy H).rejectionCount + (liftLabel (paddedGraph G dummy) labeling) = G.rejectionCount labeling := + (replacement_rejectionCount (paddedGraph G dummy) H labeling).trans + (padded_rejectionCount G dummy labeling) + +def noDummyEquiv (G : ConstraintGraph V E A) : + PaddedDart G (fun _ : V => Empty) ≃ E where + toFun z := match z with + | Sum.inl e => e + | Sum.inr z => Empty.elim z.2 + invFun := Sum.inl + left_inv := by + intro z + cases z with + | inl e => rfl + | inr z => exact Empty.elim z.2 + right_inv _ := rfl + +end MinUncutGames.Foundations.PCP.DegreeReplacement + +end +section +noncomputable section + +namespace MinUncutGames.Foundations.PCP.AssignmentTester + +open MinUncutGames.Foundations.Hastad +open scoped BigOperators +open Finset + +variable {A : Type*} [Fintype A] [DecidableEq A] + +def truth (b : Bool) : ℝ := if b then 1 else 0 + +def disagree (a b : Bool) : ℝ := if a = b then 0 else 1 + +theorem truth_nonneg (b : Bool) : 0 ≤ truth b := by cases b <;> norm_num [truth] + +theorem disagree_nonneg (a b : Bool) : 0 ≤ disagree a b := by + cases a <;> cases b <;> norm_num [disagree] + +theorem disagree_eq (a b : Bool) : + disagree a b = (1 - bitSign a * bitSign b) / 2 := by + cases a <;> cases b <;> norm_num [disagree, bitSign] + +theorem disagree_xor_le (a b c d : Bool) : + disagree (a ^^ b) (c ^^ d) ≤ disagree a c + disagree b d := by + cases a <;> cases b <;> cases c <;> cases d <;> norm_num [disagree] + +def parity (s f : Cube A) : Bool := + decide (Odd ((Finset.univ.filter fun a => s a && f a = true).card)) + +theorem bitSign_parity (s f : Cube A) : bitSign (parity s f) = walsh s f := by + have hw : walsh s f = (-1 : ℝ) ^ + (Finset.univ.filter fun a => s a && f a = true).card := by + simp [walsh, bitSign, Finset.prod_ite] + rw [hw] + simpa [parity, bitSign] using + (sign_power_parity true (Finset.univ.filter fun a => s a && f a = true).card).symm + +theorem bitSign_injective : Function.Injective bitSign := by + intro a b h + cases a <;> cases b <;> simp_all [bitSign] <;> linarith + +theorem parity_xor (s f g : Cube A) : + parity s (cubeXor f g) = (parity s f ^^ parity s g) := by + apply bitSign_injective + rw [bitSign_parity, bitSign_xor, bitSign_parity, bitSign_parity, walsh_xor] + +omit [Fintype A] [DecidableEq A] in +theorem cubeXor_comm (f g : Cube A) : cubeXor f g = cubeXor g f := by + funext a + simp [cubeXor, Bool.xor_comm] + +omit [Fintype A] [DecidableEq A] in +@[simp] theorem cubeXor_right_twice (f g : Cube A) : + cubeXor (cubeXor f g) g = f := by + funext a + change ((f a ^^ g a) ^^ g a) = f a + cases f a <;> cases g a <;> rfl + +theorem expect_cubeXor (F : Cube A → ℝ) (g : Cube A) : + (𝔼 f, F (cubeXor f g)) = 𝔼 f, F f := by + rw [Fintype.expect_eq_sum_div_card, Fintype.expect_eq_sum_div_card] + congr 1 + refine Finset.sum_bij (fun f _ => cubeXor f g) ?_ ?_ ?_ ?_ + · intro f _ + exact Finset.mem_univ _ + · intro f _ h _ heq + have hh := congrArg (fun x => cubeXor x g) heq + simpa only [cubeXor_right_twice] using hh + · intro f _ + exact ⟨cubeXor f g, Finset.mem_univ _, cubeXor_right_twice f g⟩ + · intro f _ + rfl + +def distance {K : Type*} [Fintype K] (f g : K → Bool) : ℝ := + 𝔼 k, disagree (f k) (g k) + +theorem distance_nonneg {K : Type*} [Fintype K] (f g : K → Bool) : + 0 ≤ distance f g := by + apply Finset.expect_nonneg + intro k _ + exact disagree_nonneg _ _ + +theorem distance_parity (F : Cube A → Bool) (s : Cube A) : + distance F (parity s) = (1 - coefficient (fun f => bitSign (F f)) s) / 2 := by + unfold distance + simp_rw [disagree_eq, bitSign_parity, div_eq_mul_inv, + ← Finset.expect_mul, Finset.expect_sub_distrib] + simp only [Fintype.expect_const] + rfl + +def blrReject (F : Cube A → Bool) : ℝ := + 𝔼 f, 𝔼 g, disagree (F f ^^ F g) (F (cubeXor f g)) + +theorem blrReject_nonneg (F : Cube A → Bool) : 0 ≤ blrReject F := by + apply Finset.expect_nonneg + intro f _ + apply Finset.expect_nonneg + intro g _ + exact disagree_nonneg _ _ + +theorem blr_correlation (F : Cube A → Bool) : + (𝔼 f, 𝔼 g, bitSign (F f) * bitSign (F g) * bitSign (F (cubeXor f g))) = + ∑ s, coefficient (fun f => bitSign (F f)) s ^ 3 := by + simp_rw [mul_assoc, ← Finset.mul_expect] + conv_lhs => + enter [2, f, 2, 2, g, 2, 1] + rw [cubeXor_comm] + simp_rw [walsh_autocorrelation, Finset.mul_sum] + rw [Finset.expect_sum_comm] + apply Finset.sum_congr rfl + intro s _ + have heq (f : Cube A) : bitSign (F f) * + (coefficient (fun f => bitSign (F f)) s ^ 2 * walsh s f) = + coefficient (fun f => bitSign (F f)) s ^ 2 * (bitSign (F f) * walsh s f) := by ring + simp_rw [heq, ← Finset.mul_expect] + change coefficient (fun f => bitSign (F f)) s ^ 2 * + coefficient (fun f => bitSign (F f)) s = _ + ring + +theorem blrReject_fourier (F : Cube A → Bool) : + blrReject F = (1 - ∑ s, coefficient (fun f => bitSign (F f)) s ^ 3) / 2 := by + unfold blrReject + simp_rw [disagree_eq, bitSign_xor, div_eq_mul_inv, + ← Finset.expect_mul, Finset.expect_sub_distrib] + simp only [Fintype.expect_const] + rw [blr_correlation] + +theorem blr_near_parity (F : Cube A → Bool) : + ∃ s : Cube A, distance F (parity s) ≤ blrReject F := by + classical + let c := coefficient (fun f => bitSign (F f)) + have hmass : (∑ s, c s ^ 2) = 1 := sign_parseval F + have hlarge : ∃ s, (∑ t, c t ^ 3) ≤ c s := by + by_contra hn + push Not at hn + have hpos : ∃ s, 0 < c s ^ 2 := by + by_contra hh + push Not at hh + have hz := Finset.sum_nonpos (s := Finset.univ) (fun s _ => hh s) + linarith + obtain ⟨s₀, hs₀⟩ := hpos + have hle (s : Cube A) (_ : s ∈ Finset.univ) : + c s ^ 3 ≤ (∑ t, c t ^ 3) * c s ^ 2 := by + have h := mul_le_mul_of_nonneg_right (hn s).le (sq_nonneg (c s)) + nlinarith + have hlt : c s₀ ^ 3 < (∑ t, c t ^ 3) * c s₀ ^ 2 := by + have h := mul_lt_mul_of_pos_right (hn s₀) hs₀ + nlinarith + have hsum := Finset.sum_lt_sum hle ⟨s₀, Finset.mem_univ _, hlt⟩ + rw [← Finset.mul_sum, hmass, mul_one] at hsum + exact (lt_irrefl _ hsum) + obtain ⟨s, hs⟩ := hlarge + refine ⟨s, ?_⟩ + rw [distance_parity, blrReject_fourier] + dsimp [c] at hs + linarith + +def selfCorrect (F : Cube A → Bool) (x r : Cube A) : Bool := + F r ^^ F (cubeXor r x) + +theorem parity_selfCorrect (s x r : Cube A) : + (parity s r ^^ parity s (cubeXor r x)) = parity s x := by + rw [parity_xor] + cases parity s r <;> cases parity s x <;> rfl + +theorem selfCorrect_error (F : Cube A → Bool) (s x : Cube A) : + (𝔼 r, disagree (selfCorrect F x r) (parity s x)) ≤ 2 * distance F (parity s) := by + have hle (r : Cube A) : + disagree (selfCorrect F x r) (parity s x) ≤ + disagree (F r) (parity s r) + + disagree (F (cubeXor r x)) (parity s (cubeXor r x)) := by + rw [← parity_selfCorrect s x r] + exact disagree_xor_le _ _ _ _ + have h := Finset.expect_le_expect (s := Finset.univ) (fun r _ => hle r) + rw [Finset.expect_add_distrib, + expect_cubeXor (fun r => disagree (F r) (parity s r)) x] at h + change _ ≤ distance F (parity s) + distance F (parity s) at h + linarith + +def singleMask (i : A) : Cube A := fun j => decide (j = i) + +def flipAt (i : A) (f : Cube A) : Cube A := + fun j => if j = i then !(f j) else f j + +omit [Fintype A] in +@[simp] theorem flipAt_twice (i : A) (f : Cube A) : flipAt i (flipAt i f) = f := by + funext j + by_cases h : j = i <;> simp [flipAt, h] + +omit [Fintype A] in +theorem flipAt_eq_xor (i : A) (f : Cube A) : flipAt i f = cubeXor f (singleMask i) := by + funext j + by_cases h : j = i <;> simp [flipAt, cubeXor, singleMask, h] + +theorem expect_flipAt (F : Cube A → ℝ) (i : A) : + (𝔼 f, F (flipAt i f)) = 𝔼 f, F f := by + simp_rw [flipAt_eq_xor] + exact expect_cubeXor F _ + +theorem walsh_singleMask (s : Cube A) (i : A) : + walsh s (singleMask i) = bitSign (s i) := by + unfold walsh + rw [Finset.prod_eq_single i] + · simp [singleMask] + · intro j _ hj + simp [singleMask, hj, bitSign] + · intro h + exact False.elim (h (Finset.mem_univ _)) + +theorem parity_singleMask (s : Cube A) (i : A) : parity s (singleMask i) = s i := by + apply bitSign_injective + rw [bitSign_parity, walsh_singleMask] + +theorem parity_flipAt (s : Cube A) (i : A) (f : Cube A) (hs : s i = true) : + parity s (flipAt i f) = !(parity s f) := by + rw [flipAt_eq_xor, parity_xor, parity_singleMask, hs] + cases parity s f <;> rfl + +def cubeAnd (f g : Cube A) : Cube A := fun a => f a && g a + +def andLawFailure (s f g : Cube A) : Bool := + parity s (cubeAnd f g) ^^ (parity s f && parity s g) + +theorem andLawFailure_flipAt_second (s : Cube A) (i : A) (f g : Cube A) + (hi : s i = true) : + andLawFailure s f (flipAt i g) = + (andLawFailure s f g ^^ (parity s f ^^ f i)) := by + have hAnd : cubeAnd f (flipAt i g) = + (if f i then flipAt i (cubeAnd f g) else cubeAnd f g) := by + funext a + by_cases ha : a = i + · subst a + cases hfi : f i <;> simp [cubeAnd, flipAt, hfi] + · cases f i <;> simp [cubeAnd, flipAt, ha] + have hg := parity_flipAt s i g hi + have hfg := parity_flipAt s i (cubeAnd f g) hi + cases hfi : f i <;> cases hf : parity s f <;> + cases hg₀ : parity s g <;> cases ha : parity s (cubeAnd f g) <;> + simp [andLawFailure, hAnd, hg, hfg, hfi, hf, hg₀, ha] + +private theorem four_truth_lower (e₀ e₁ d : Bool) : + (1 : ℝ) ≤ truth e₀ + truth (e₀ ^^ d) + truth e₁ + truth (e₁ ^^ (!d)) := by + cases e₀ <;> cases e₁ <;> cases d <;> norm_num [truth] + +theorem parity_and_rejection (s : Cube A) (i j : A) + (hi : s i = true) (hj : s j = true) (hij : i ≠ j) : + (1 : ℝ) / 4 ≤ 𝔼 f, 𝔼 g, truth (andLawFailure s f g) := by + have hpoint (f g : Cube A) : (1 : ℝ) ≤ + truth (andLawFailure s f g) + truth (andLawFailure s f (flipAt i g)) + + truth (andLawFailure s (flipAt j f) g) + + truth (andLawFailure s (flipAt j f) (flipAt i g)) := by + rw [andLawFailure_flipAt_second s i f g hi, + andLawFailure_flipAt_second s i (flipAt j f) g hi] + have hD : (parity s (flipAt j f) ^^ (flipAt j f) i) = + !(parity s f ^^ f i) := by + rw [parity_flipAt s j f hj] + simp only [flipAt, ite_eq_right hij] + cases parity s f <;> cases f i <;> rfl + rw [hD] + exact four_truth_lower _ _ _ + have havg := Finset.expect_le_expect (s := Finset.univ) (fun f _ => + Finset.expect_le_expect (s := Finset.univ) (fun g _ => hpoint f g)) + simp only [Finset.expect_add_distrib, Fintype.expect_const] at havg + have hinner (f : Cube A) : + (𝔼 g, truth (andLawFailure s f (flipAt i g))) = + 𝔼 g, truth (andLawFailure s f g) := + expect_flipAt (fun g => truth (andLawFailure s f g)) i + have houter : (𝔼 f, 𝔼 g, truth (andLawFailure s (flipAt j f) g)) = + 𝔼 f, 𝔼 g, truth (andLawFailure s f g) := + expect_flipAt (fun f => 𝔼 g, truth (andLawFailure s f g)) j + simp only [hinner, houter] at havg + linarith + +theorem truth_xor (a b : Bool) : truth (a ^^ b) = disagree a b := by + cases a <;> cases b <;> norm_num [truth, disagree] + +theorem disagree_triangle (a b c : Bool) : + disagree a c ≤ disagree a b + disagree b c := by + cases a <;> cases b <;> cases c <;> norm_num [disagree] + +theorem and_disagree_transfer (p₀ p₁ p₂ q₀ q₁ q₂ : Bool) : + disagree p₀ (p₁ && p₂) ≤ disagree q₀ (q₁ && q₂) + + disagree q₀ p₀ + disagree q₁ p₁ + disagree q₂ p₂ := by + cases p₀ <;> cases p₁ <;> cases p₂ <;> + cases q₀ <;> cases q₁ <;> cases q₂ <;> norm_num [disagree] + +def andReject (F : Cube A → Bool) : ℝ := + 𝔼 f, 𝔼 g, 𝔼 r₀, 𝔼 r₁, 𝔼 r₂, + disagree (selfCorrect F (cubeAnd f g) r₀) + (selfCorrect F f r₁ && selfCorrect F g r₂) + +def unitReject (F : Cube A → Bool) : ℝ := + 𝔼 r, disagree (selfCorrect F (fun _ => true) r) true + +variable {K : Type*} [Fintype K] [Nonempty K] + +def inputReject (label : A → K → Bool) (σ : K → Bool) (F : Cube A → Bool) : ℝ := + 𝔼 k, 𝔼 r, disagree (σ k) (selfCorrect F (fun a => label a k) r) + +def testerReject (label : A → K → Bool) (σ : K → Bool) (F : Cube A → Bool) : ℝ := + (blrReject F + andReject F + unitReject F + inputReject label σ F) / 4 + +theorem andReject_nonneg (F : Cube A → Bool) : 0 ≤ andReject F := by + apply Finset.expect_nonneg + intro f _ + apply Finset.expect_nonneg + intro g _ + apply Finset.expect_nonneg + intro r₀ _ + apply Finset.expect_nonneg + intro r₁ _ + apply Finset.expect_nonneg + intro r₂ _ + exact disagree_nonneg _ _ + +theorem unitReject_nonneg (F : Cube A → Bool) : 0 ≤ unitReject F := by + apply Finset.expect_nonneg + intro r _ + exact disagree_nonneg _ _ + +omit [Nonempty K] in +theorem inputReject_nonneg (label : A → K → Bool) (σ : K → Bool) (F : Cube A → Bool) : + 0 ≤ inputReject label σ F := by + apply Finset.expect_nonneg + intro k _ + apply Finset.expect_nonneg + intro r _ + exact disagree_nonneg _ _ + +theorem andReject_transfer (F : Cube A → Bool) (s : Cube A) : + (𝔼 f, 𝔼 g, truth (andLawFailure s f g)) ≤ + andReject F + 6 * distance F (parity s) := by + have hlocal (f g : Cube A) : truth (andLawFailure s f g) ≤ + (𝔼 r₀, 𝔼 r₁, 𝔼 r₂, + disagree (selfCorrect F (cubeAnd f g) r₀) + (selfCorrect F f r₁ && selfCorrect F g r₂)) + + 6 * distance F (parity s) := by + have hp (r₀ r₁ r₂ : Cube A) := and_disagree_transfer + (parity s (cubeAnd f g)) (parity s f) (parity s g) + (selfCorrect F (cubeAnd f g) r₀) (selfCorrect F f r₁) (selfCorrect F g r₂) + have havg := Finset.expect_le_expect (s := Finset.univ) (fun r₀ _ => + Finset.expect_le_expect (s := Finset.univ) (fun r₁ _ => + Finset.expect_le_expect (s := Finset.univ) (fun r₂ _ => hp r₀ r₁ r₂))) + simp only [Finset.expect_add_distrib, Fintype.expect_const] at havg + have h₀ := selfCorrect_error F s (cubeAnd f g) + have h₁ := selfCorrect_error F s f + have h₂ := selfCorrect_error F s g + rw [andLawFailure, truth_xor] + linarith + have h := Finset.expect_le_expect (s := Finset.univ) (fun f _ => + Finset.expect_le_expect (s := Finset.univ) (fun g _ => hlocal f g)) + simpa only [Finset.expect_add_distrib, Fintype.expect_const, andReject] using h + +theorem parity_zero (f : Cube A) : parity (fun _ => false) f = false := by + apply bitSign_injective + rw [bitSign_parity] + simp [walsh, bitSign] + +theorem unitReject_zero_parity (F : Cube A → Bool) : + 1 - 2 * distance F (parity (fun _ => false)) ≤ unitReject F := by + have herr := selfCorrect_error F (fun _ => false) (fun _ => true) + simp only [parity_zero] at herr + have heq : unitReject F + + (𝔼 r, disagree (selfCorrect F (fun _ => true) r) false) = 1 := by + unfold unitReject + rw [← Finset.expect_add_distrib] + have hp (b : Bool) : disagree b true + disagree b false = 1 := by + cases b <;> norm_num [disagree] + simp only [hp, Fintype.expect_const] + linarith + +theorem parity_singleMask_eval (a : A) (f : Cube A) : + parity (singleMask a) f = f a := by + apply bitSign_injective + rw [bitSign_parity, walsh_symm, walsh_singleMask] + +theorem inputReject_transfer (label : A → K → Bool) (σ : K → Bool) + (F : Cube A → Bool) (a : A) : + distance σ (label a) ≤ inputReject label σ F + + 2 * distance F (parity (singleMask a)) := by + have hlocal (k : K) : disagree (σ k) (label a k) ≤ + (𝔼 r, disagree (σ k) (selfCorrect F (fun a => label a k) r)) + + 2 * distance F (parity (singleMask a)) := by + have hp (r : Cube A) := disagree_triangle (σ k) + (selfCorrect F (fun a => label a k) r) (label a k) + have havg := Finset.expect_le_expect (s := Finset.univ) (fun r _ => hp r) + simp only [Fintype.expect_const, Finset.expect_add_distrib] at havg + have herr := selfCorrect_error F (singleMask a) (fun a => label a k) + simp only [parity_singleMask_eval] at herr + linarith + have h := Finset.expect_le_expect (s := Finset.univ) (fun k _ => hlocal k) + simpa only [Finset.expect_add_distrib, Fintype.expect_const, inputReject, distance] using h + +theorem tester_proximity_soundness (label : A → K → Bool) (σ : K → Bool) + (F : Cube A → Bool) {δ : ℝ} (hδ : 0 < δ) (hδ' : δ ≤ 1 / 4) + (hfar : ∀ a, δ ≤ distance σ (label a)) : + δ / 256 ≤ testerReject label σ F := by + have hblr := blrReject_nonneg F + have hand := andReject_nonneg F + have hunit := unitReject_nonneg F + have hin := inputReject_nonneg label σ F + by_cases hb : δ / 64 ≤ blrReject F + · unfold testerReject + linarith + obtain ⟨s, hs⟩ := blr_near_parity F + by_cases hz : s = fun _ => false + · subst s + have hu := unitReject_zero_parity F + unfold testerReject + linarith + have hsome : ∃ i, s i = true := by + by_contra hh + push Not at hh + apply hz + funext i + have h := hh i + cases hi : s i <;> simp_all + obtain ⟨i, hi⟩ := hsome + by_cases htwo : ∃ j, i ≠ j ∧ s j = true + · obtain ⟨j, hij, hj⟩ := htwo + have ha := parity_and_rejection s i j hi hj hij + have ht := andReject_transfer F s + unfold testerReject + linarith + · have heq : s = singleMask i := by + funext j + by_cases hji : j = i + · subst j + simp [singleMask, hi] + · have hj : s j = false := by + cases hv : s j + · rfl + · exact False.elim (htwo ⟨j, Ne.symm hji, hv⟩) + simp [singleMask, hji, hj] + subst s + have ht := inputReject_transfer label σ F i + have hf := hfar i + unfold testerReject + linarith + +omit [Fintype A] [DecidableEq A] in +theorem selfCorrect_dictator (a : A) (x r : Cube A) : + selfCorrect (fun f => f a) x r = x a := by + change (r a ^^ (r a ^^ x a)) = x a + cases r a <;> cases x a <;> rfl + +omit [Nonempty K] in +theorem tester_perfect_completeness (label : A → K → Bool) (a : A) : + testerReject label (label a) (fun f => f a) = 0 := by + have hb : blrReject (fun f : Cube A => f a) = 0 := by + simp [blrReject, cubeXor, disagree] + have ha : andReject (fun f : Cube A => f a) = 0 := by + simp [andReject, selfCorrect_dictator, cubeAnd, disagree] + have hu : unitReject (fun f : Cube A => f a) = 0 := by + simp [unitReject, selfCorrect_dictator, disagree] + have hi : inputReject label (label a) (fun f => f a) = 0 := by + simp [inputReject, selfCorrect_dictator, disagree] + simp [testerReject, hb, ha, hu, hi] + +def eventQueries (label : A → K → Bool) (kind : Fin 4) (k : K) + (f g r₀ r₁ r₂ : Cube A) (slot : Fin 6) : K ⊕ Cube A := + if kind = 0 then + if slot = 0 then .inr f else if slot = 1 then .inr g else .inr (cubeXor f g) + else if kind = 1 then + if slot = 0 then .inr r₀ else + if slot = 1 then .inr (cubeXor r₀ (cubeAnd f g)) else + if slot = 2 then .inr r₁ else + if slot = 3 then .inr (cubeXor r₁ f) else + if slot = 4 then .inr r₂ else .inr (cubeXor r₂ g) + else if kind = 2 then + if slot = 0 then .inr r₀ else .inr (cubeXor r₀ (fun _ => true)) + else + if slot = 0 then .inl k else + if slot = 1 then .inr r₀ else .inr (cubeXor r₀ (fun a => label a k)) + +def eventAccepts (kind : Fin 4) (b : Fin 6 → Bool) : Bool := + if kind = 0 then decide ((b 0 ^^ b 1) = b 2) + else if kind = 1 then decide ((b 0 ^^ b 1) = ((b 2 ^^ b 3) && (b 4 ^^ b 5))) + else if kind = 2 then (b 0 ^^ b 1) + else decide (b 0 = (b 1 ^^ b 2)) + +def oracleAnswer (σ : K → Bool) (F : Cube A → Bool) : K ⊕ Cube A → Bool := + Sum.elim σ F + +def eventReject (label : A → K → Bool) (σ : K → Bool) (F : Cube A → Bool) + (kind : Fin 4) (k : K) (f g r₀ r₁ r₂ : Cube A) : ℝ := + truth (!(eventAccepts kind (fun slot => + oracleAnswer σ F (eventQueries label kind k f g r₀ r₁ r₂ slot)))) + +theorem truth_not_decide_eq (a b : Bool) : truth (!(decide (a = b))) = disagree a b := by + cases a <;> cases b <;> norm_num [truth, disagree] + +omit [Fintype A] [DecidableEq A] [Fintype K] [Nonempty K] in +theorem eventReject_blr (label : A → K → Bool) (σ : K → Bool) (F : Cube A → Bool) + (k : K) (f g r₀ r₁ r₂ : Cube A) : + eventReject label σ F 0 k f g r₀ r₁ r₂ = + disagree (F f ^^ F g) (F (cubeXor f g)) := by + simp [eventReject, eventAccepts, eventQueries, oracleAnswer, truth_not_decide_eq] + +omit [Fintype A] [DecidableEq A] [Fintype K] [Nonempty K] in +theorem eventReject_and (label : A → K → Bool) (σ : K → Bool) (F : Cube A → Bool) + (k : K) (f g r₀ r₁ r₂ : Cube A) : + eventReject label σ F 1 k f g r₀ r₁ r₂ = + disagree (selfCorrect F (cubeAnd f g) r₀) + (selfCorrect F f r₁ && selfCorrect F g r₂) := by + simp [eventReject, eventAccepts, eventQueries, oracleAnswer, + truth_not_decide_eq, selfCorrect] + +omit [Fintype A] [DecidableEq A] [Fintype K] [Nonempty K] in +theorem eventReject_unit (label : A → K → Bool) (σ : K → Bool) (F : Cube A → Bool) + (k : K) (f g r₀ r₁ r₂ : Cube A) : + eventReject label σ F 2 k f g r₀ r₁ r₂ = + disagree (selfCorrect F (fun _ => true) r₀) true := by + simp only [eventReject, eventAccepts, eventQueries, oracleAnswer] + norm_num + change truth (!(selfCorrect F (fun _ => true) r₀)) = + disagree (selfCorrect F (fun _ => true) r₀) true + cases selfCorrect F (fun _ => true) r₀ <;> norm_num [truth, disagree] + +omit [Fintype A] [DecidableEq A] [Fintype K] [Nonempty K] in +theorem eventReject_input (label : A → K → Bool) (σ : K → Bool) (F : Cube A → Bool) + (k : K) (f g r₀ r₁ r₂ : Cube A) : + eventReject label σ F 3 k f g r₀ r₁ r₂ = + disagree (σ k) (selfCorrect F (fun a => label a k) r₀) := by + simp [eventReject, eventAccepts, eventQueries, oracleAnswer, + truth_not_decide_eq, selfCorrect] + +omit [Fintype A] [DecidableEq A] [Fintype K] [Nonempty K] in +theorem event_perfect_completeness (label : A → K → Bool) (a : A) + (kind : Fin 4) (k : K) (f g r₀ r₁ r₂ : Cube A) : + eventAccepts kind (fun slot => oracleAnswer (label a) (fun x => x a) + (eventQueries label kind k f g r₀ r₁ r₂ slot)) = true := by + have hkind : kind = 0 ∨ kind = 1 ∨ kind = 2 ∨ kind = 3 := by omega + have hreject : eventReject label (label a) (fun x => x a) kind k f g r₀ r₁ r₂ = 0 := by + rcases hkind with h | h | h | h <;> subst kind + · simp [eventReject_blr, cubeXor, disagree] + · simp [eventReject_and, selfCorrect_dictator, cubeAnd, disagree] + · simp [eventReject_unit, selfCorrect_dictator, disagree] + · simp [eventReject_input, selfCorrect_dictator, disagree] + unfold eventReject at hreject + cases h : eventAccepts kind (fun slot => oracleAnswer (label a) (fun x => x a) + (eventQueries label kind k f g r₀ r₁ r₂ slot)) <;> simp_all [truth] + +def explicitTesterReject (label : A → K → Bool) (σ : K → Bool) (F : Cube A → Bool) : ℝ := + 𝔼 kind : Fin 4, 𝔼 k, 𝔼 f, 𝔼 g, 𝔼 r₀, 𝔼 r₁, 𝔼 r₂, + eventReject label σ F kind k f g r₀ r₁ r₂ + +theorem explicitTesterReject_eq (label : A → K → Bool) (σ : K → Bool) + (F : Cube A → Bool) : explicitTesterReject label σ F = testerReject label σ F := by + unfold explicitTesterReject + rw [Fintype.expect_eq_sum_div_card] + simp [Fin.sum_univ_succ, eventReject_blr, eventReject_and, eventReject_unit, + eventReject_input, testerReject, blrReject, andReject, unitReject, inputReject, add_assoc] + +theorem explicit_proximity_soundness (label : A → K → Bool) (σ : K → Bool) + (F : Cube A → Bool) {δ : ℝ} (hδ : 0 < δ) (hδ' : δ ≤ 1 / 4) + (hfar : ∀ a, δ ≤ distance σ (label a)) : + δ / 256 ≤ explicitTesterReject label σ F := by + rw [explicitTesterReject_eq] + exact tester_proximity_soundness label σ F hδ hδ' hfar + +end MinUncutGames.Foundations.PCP.AssignmentTester + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/DescriptorEmission.lean b/lean/OAI/Computability/MinUncut/PCP/DescriptorEmission.lean new file mode 100644 index 0000000000000000000000000000000000000000..efd41063516040eab803b833bede4e5aab1a8c13 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/DescriptorEmission.lean @@ -0,0 +1,625 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.EquationEmit +import OAI.Computability.MinUncut.Machines.MachineFiniteTable + +namespace OAI + +namespace MinUncutGames.Foundations.Hastad.SourceDescriptorEmission + +open Turing +open Target SourceContexts SourceOccurrences SourceLocalSignature SourceLocalEquation +open MinUncutGames.Reduction.CloneGap +open MinUncutGames.Foundations.Complexity + +def codedEquation (u D : ℕ) (state : LocalInput u D) : + Equation (Fin (localKeyEncoding u).size) := + mapEquation (localKeyEncoding u).code (SourceLocalEquation.emit u D state) + +def descriptorWords (u D : ℕ) (state : LocalInput u D) : List ℕ := + MinUncutGames.Reduction.SourceEncoding.equationWords (codedEquation u D state) + +def descriptorBits (u D : ℕ) (state : LocalInput u D) : List Bool := + encodeWords (descriptorWords u D state) + +@[simp] theorem descriptorWords_length (u D : ℕ) (state : LocalInput u D) : + (descriptorWords u D state).length = 4 := + MinUncutGames.Reduction.SourceEncoding.equationWords_length _ + +theorem descriptorBits_length_le (u D : ℕ) (state : LocalInput u D) : + (descriptorBits u D state).length ≤ 3 * (localKeyEncoding u).size + 2 := + MinUncutGames.Reduction.SourceEncoding.equationBits_length_le _ + +@[simp] theorem decode_descriptorBits (u D : ℕ) (state : LocalInput u D) : + decodeWords (descriptorBits u D state) = some (descriptorWords u D state) := + decodeWords_encodeWords _ + +@[simp] theorem parse_descriptorWords (u D : ℕ) (state : LocalInput u D) : + MinUncutGames.Reduction.SourceEncoding.parseEquation (localKeyEncoding u).size + (descriptorWords u D state) = some (codedEquation u D state, []) := by + simpa only [List.append_nil, descriptorWords] using + MinUncutGames.Reduction.SourceEncoding.parseEquation_encoded (codedEquation u D state) [] + +theorem decode_codedEquation (u D : ℕ) (state : LocalInput u D) : + mapEquation (localKeyEncoding u).code.symm (codedEquation u D state) = + SourceLocalEquation.emit u D state := by + unfold codedEquation + rw [SourceLocalEquation.mapEquation_comp] + have h : (localKeyEncoding u).code.symm ∘ (localKeyEncoding u).code = id := by + funext key + exact (localKeyEncoding u).code.symm_apply_apply key + rw [h] + rfl + +theorem codedEquation_global (F : Formula) (u D : ℕ) (p : SourceIndex F u D) : + mapEquation + (addressMap F u p.1.1 (sampledVariables F p.1.1 p.1.2) ∘ + (localKeyEncoding u).code.symm) + (codedEquation u D (ofContext F p.1.1 p.1.2, p.2)) = + sourceEquation F u D p := by + rw [← SourceLocalEquation.mapEquation_comp, decode_codedEquation] + exact (sourceEquation_eq_map_emit F u D p).symm + +def descriptorPushBound (u D : ℕ) : ℕ := + ((localInputs u D).map (fun state => (descriptorBits u D state).length)).sum + +theorem descriptorPushBound_le (u D : ℕ) : + descriptorPushBound u D ≤ + (localInputs u D).length * (3 * (localKeyEncoding u).size + 2) := by + have hlist (states : List (LocalInput u D)) : + (states.map (fun state => (descriptorBits u D state).length)).sum ≤ + states.length * (3 * (localKeyEncoding u).size + 2) := by + induction states with + | nil => simp + | cons state states ih => + simp only [List.map_cons, List.sum_cons, List.length_cons, Nat.add_mul, Nat.one_mul] + have hstate := descriptorBits_length_le u D state + omega + exact hlist (localInputs u D) + +variable {K Λ : Type} [DecidableEq K] + +instance localInputDecidableEq (u D : ℕ) : DecidableEq (LocalInput u D) := + fun x y => + if h : (localInputEncoding u D).code x = (localInputEncoding u D).code y then + isTrue ((localInputEncoding u D).code.injective h) + else isFalse (fun hxy => h (congrArg (localInputEncoding u D).code hxy)) + +def emitDescriptor (u D : ℕ) (dst : K) + (next : TM2.Stmt (fun _ : K => Bool) Λ (LocalInput u D)) : + TM2.Stmt (fun _ : K => Bool) Λ (LocalInput u D) := + MachineFiniteTable.emit (Γ := fun _ : K => Bool) dst + (descriptorBits u D) (localInputs u D) next + +theorem stepAux_emitDescriptor (u D : ℕ) (dst : K) + (next : TM2.Stmt (fun _ : K => Bool) Λ (LocalInput u D)) + (state : LocalInput u D) (tapes : K → List Bool) : + TM2.stepAux (emitDescriptor u D dst next) state tapes = + TM2.stepAux next state + (Function.update tapes dst (descriptorBits u D state ++ tapes dst)) := + MachineFiniteTable.stepAux_emit (Γ := fun _ : K => Bool) dst + (descriptorBits u D) (localInputs u D) + (mem_localInputs u D) next state tapes + +omit [DecidableEq K] in +theorem emitDescriptor_push_bound (u D : ℕ) (dst : K) + (next : TM2.Stmt (fun _ : K => Bool) Λ (LocalInput u D)) : + Runtime.statementPushBound (emitDescriptor u D dst next) ≤ + descriptorPushBound u D + Runtime.statementPushBound next := + MachineFiniteTable.emit_push_bound (Γ := fun _ : K => Bool) dst + (descriptorBits u D) (localInputs u D) next + +def emitDescriptorInTime (u D : ℕ) (dst : K) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (LocalInput u D)) + (label exitLabel : Λ) + (atLabel : program label = emitDescriptor u D dst (.goto (fun _ => exitLabel))) + (state : LocalInput u D) (tapes : K → List Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some label, state, tapes⟩ + (some ⟨some exitLabel, state, + Function.update tapes dst (descriptorBits u D state ++ tapes dst)⟩) 1 := + MachineFiniteTable.emitInTime (Γ := fun _ : K => Bool) dst + (descriptorBits u D) (localInputs u D) + (mem_localInputs u D) program label exitLabel atLabel state tapes + +theorem descriptor_output_frame (u D : ℕ) (dst : K) + (state : LocalInput u D) (tapes : K → List Bool) (k : K) (h : k ≠ dst) : + (Function.update tapes dst (descriptorBits u D state ++ tapes dst)) k = tapes k := + MachineFiniteTable.output_frame (Γ := fun _ : K => Bool) dst + (descriptorBits u D) state tapes k h + +end MinUncutGames.Foundations.Hastad.SourceDescriptorEmission + +namespace MinUncutGames.Foundations.Hastad.SourceTestEmit + +open Turing +open Target SourceContexts SourceOccurrences SourceLocalSignature SourceLocalEquation +open SourceAddressDescriptors SourceEquationEmit +open MinUncutGames.Reduction.CloneGap +open Complexity + +abbrev Label (u D : ℕ) := Unit ⊕ (LocalInput u D × SourceEquationEmit.Label) +abbrev State (u D : ℕ) := LocalInput u D × Option Bool + +def localEquation (u D : ℕ) (state : LocalInput u D) : Equation Descriptor := + mapEquation (descriptor u) (SourceLocalEquation.emit u D state) + +def bodyLabel (u D : ℕ) (state : LocalInput u D) (label : SourceEquationEmit.Label) : + Label u D := .inr (state, label) + +variable {K : Type} [DecidableEq K] + +def program (u D : ℕ) (sources : Fin 3 → K) (destination scratch : K) + (exit : Option (Label u D)) : + Label u D → TM2.Stmt (fun _ : K => Bool) (Label u D) (State u D) + | .inl _ => .goto (fun state => bodyLabel u D state.1 .seed) + | .inr (state, label) => + SourceEquationEmit.statement sources destination scratch (localEquation u D state) + (bodyLabel u D state) exit label + +theorem testTrace (u D : ℕ) (sources : Fin 3 → K) (destination scratch : K) + (sourceDestination : ∀ side, sources side ≠ destination) + (sourceScratch : ∀ side, sources side ≠ scratch) + (destinationScratch : destination ≠ scratch) (exit : Option (Label u D)) + (state : LocalInput u D) (base : K → List Bool) (values : Fin 3 → ℕ) + (sourceWords : ∀ side, base (sources side) = encodeWord (values side)) + (scratchEmpty : base scratch = []) (register : Option Bool) : + (MachineComposition.advance (TM2.step (program u D sources destination scratch exit)))^[ + SourceEquationEmit.steps values (localEquation u D state) + 1] + (some ⟨some (.inl ()), (state, register), base⟩) = + some ⟨exit, (state, none), + prefixTapes destination base (words values (localEquation u D state))⟩ := by + rw [Function.iterate_succ_apply] + change (MachineComposition.advance (TM2.step (program u D sources destination scratch exit)))^[ + SourceEquationEmit.steps values (localEquation u D state)] + (some ⟨some (bodyLabel u D state .seed), (state, register), base⟩) = _ + exact SourceEquationEmit.equationTrace sources destination scratch sourceDestination + sourceScratch destinationScratch (localEquation u D state) (bodyLabel u D state) exit + (program u D sources destination scratch exit) (fun _ => rfl) + base values sourceWords scratchEmpty state register + +def testInTime (u D : ℕ) (sources : Fin 3 → K) (destination scratch : K) + (sourceDestination : ∀ side, sources side ≠ destination) + (sourceScratch : ∀ side, sources side ≠ scratch) + (destinationScratch : destination ≠ scratch) (exit : Option (Label u D)) + (state : LocalInput u D) (base : K → List Bool) (values : Fin 3 → ℕ) + (sourceWords : ∀ side, base (sources side) = encodeWord (values side)) + (scratchEmpty : base scratch = []) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step (program u D sources destination scratch exit)) + ⟨some (.inl ()), (state, register), base⟩ + (some ⟨exit, (state, none), + prefixTapes destination base (words values (localEquation u D state))⟩) + (SourceEquationEmit.steps values (localEquation u D state) + 1) where + steps := SourceEquationEmit.steps values (localEquation u D state) + 1 + evals_in_steps := testTrace u D sources destination scratch sourceDestination sourceScratch + destinationScratch exit state base values sourceWords scratchEmpty register + steps_le_m := Nat.le_refl _ + +def sourceTestInTime (F : Formula) (u D : ℕ) (p : SourceIndex F u D) + (sources : Fin 3 → K) (destination scratch : K) + (sourceDestination : ∀ side, sources side ≠ destination) + (sourceScratch : ∀ side, sources side ≠ scratch) + (destinationScratch : destination ≠ scratch) (exit : Option (Label u D)) + (base : K → List Bool) + (sourceWords : ∀ side, base (sources side) = encodeWord + (baseValue F u p.1.1 (sampledVariables F p.1.1 p.1.2) side)) + (scratchEmpty : base scratch = []) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step (program u D sources destination scratch exit)) + ⟨some (.inl ()), ((ofContext F p.1.1 p.1.2, p.2), register), base⟩ + (some ⟨exit, ((ofContext F p.1.1 p.1.2, p.2), none), + prefixTapes destination base + (MinUncutGames.Reduction.SourceEncoding.equationWords (sourceEquation F u D p))⟩) + (6 * nBits F u + 17) where + steps := SourceEquationEmit.steps + (baseValue F u p.1.1 (sampledVariables F p.1.1 p.1.2)) + (localEquation u D (ofContext F p.1.1 p.1.2, p.2)) + 1 + evals_in_steps := by + rw [sourceEquation_words] + exact testTrace u D sources destination scratch sourceDestination sourceScratch + destinationScratch exit (ofContext F p.1.1 p.1.2, p.2) base + (baseValue F u p.1.1 (sampledVariables F p.1.1 p.1.2)) sourceWords scratchEmpty register + steps_le_m := by + have h := equation_emit_steps_le F u p.1.1 (sampledVariables F p.1.1 p.1.2) + (localEquation u D (ofContext F p.1.1 p.1.2, p.2)) + change _ + 1 ≤ _ + unfold SourceEquationEmit.steps + omega + +end MinUncutGames.Foundations.Hastad.SourceTestEmit + +namespace MinUncutGames.Foundations.Hastad.SourceTestAppend + +open Turing Complexity +open Target SourceContexts SourceOccurrences SourceLocalSignature SourceLocalEquation +open SourceAddressDescriptors SourceEquationEmit SourceTestEmit + +inductive Label (u D : Nat) + | test (label : SourceTestEmit.Label u D) + | append + deriving DecidableEq, Fintype + +abbrev State (u D : Nat) := SourceTestEmit.State u D + +structure Layout (K : Type) where + sources : Fin 3 → K + temporary : K + scratch : K + accumulator : K + sourceTemporary : ∀ side, sources side ≠ temporary + sourceScratch : ∀ side, sources side ≠ scratch + sourceAccumulator : ∀ side, sources side ≠ accumulator + temporaryScratch : temporary ≠ scratch + temporaryAccumulator : temporary ≠ accumulator + scratchAccumulator : scratch ≠ accumulator + +def equationBits (u D : Nat) (values : Fin 3 → Nat) (state : LocalInput u D) : List Bool := + encodeWords (words values (localEquation u D state)) + +def steps (u D : Nat) (values : Fin 3 → Nat) (state : LocalInput u D) : Nat := + SourceEquationEmit.steps values (localEquation u D state) + 1 + + (equationBits u D values state).length + 1 + +variable {K Λ : Type} [DecidableEq K] + +def bodyLabel (u D : Nat) (labels : Label u D → Λ) (state : LocalInput u D) + (label : SourceEquationEmit.Label) : Λ := + labels (.test (SourceTestEmit.bodyLabel u D state label)) + +def statement (u D : Nat) (layout : Layout K) (labels : Label u D → Λ) (exit : Option Λ) : + Label u D → TM2.Stmt (fun _ : K => Bool) Λ (State u D) + | .test (.inl _) => .goto (fun state => bodyLabel u D labels state.1 .seed) + | .test (.inr (state, label)) => + SourceEquationEmit.statement layout.sources layout.temporary layout.scratch + (localEquation u D state) (bodyLabel u D labels state) (some (labels .append)) label + | .append => Reduction.MachineTransfer.loopAt layout.temporary layout.accumulator id false + (labels .append) exit + +def program (u D : Nat) (layout : Layout K) (exit : Option (Label u D)) : + Label u D → TM2.Stmt (fun _ : K => Bool) (Label u D) (State u D) := + statement u D layout id exit + +def resultTapes (layout : Layout K) (base : K → List Bool) (bits : List Bool) : K → List Bool := + Function.update base layout.accumulator (bits.reverse ++ base layout.accumulator) + +theorem resultTapes_other (layout : Layout K) (base : K → List Bool) (bits : List Bool) + (k : K) (hk : k ≠ layout.accumulator) : resultTapes layout base bits k = base k := by + simp [resultTapes, hk] + +theorem resultTapes_source (layout : Layout K) (base : K → List Bool) (bits : List Bool) + (side : Fin 3) : resultTapes layout base bits (layout.sources side) = base (layout.sources side) := + resultTapes_other layout base bits _ (layout.sourceAccumulator side) + +theorem resultTapes_temporary (layout : Layout K) (base : K → List Bool) (bits : List Bool) : + resultTapes layout base bits layout.temporary = base layout.temporary := + resultTapes_other layout base bits _ layout.temporaryAccumulator + +theorem resultTapes_scratch (layout : Layout K) (base : K → List Bool) (bits : List Bool) : + resultTapes layout base bits layout.scratch = base layout.scratch := + resultTapes_other layout base bits _ layout.scratchAccumulator + +theorem emitTrace (u D : Nat) (layout : Layout K) (labels : Label u D → Λ) (exit : Option Λ) + (p : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State u D)) + (atLabels : ∀ label, p (labels label) = statement u D layout labels exit label) + (state : LocalInput u D) (base : K → List Bool) (values : Fin 3 → Nat) + (sourceWords : ∀ side, base (layout.sources side) = encodeWord (values side)) + (scratchEmpty : base layout.scratch = []) (register : Option Bool) : + (MachineComposition.advance (TM2.step p))^[ + SourceEquationEmit.steps values (localEquation u D state) + 1] + (some ⟨some (labels (.test (.inl ()))), (state, register), base⟩) = + some ⟨some (labels .append), (state, none), + prefixTapes layout.temporary base (words values (localEquation u D state))⟩ := by + have select : TM2.step p + ⟨some (labels (.test (.inl ()))), (state, register), base⟩ = + some ⟨some (bodyLabel u D labels state .seed), (state, register), base⟩ := by + change some (TM2.stepAux (p (labels (.test (.inl ())))) (state, register) base) = _ + rw [atLabels] + rfl + rw [Function.iterate_succ_apply] + change (MachineComposition.advance (TM2.step p))^[ + SourceEquationEmit.steps values (localEquation u D state)] + (TM2.step p ⟨some (labels (.test (.inl ()))), (state, register), base⟩) = _ + rw [select] + exact SourceEquationEmit.equationTrace layout.sources layout.temporary layout.scratch + layout.sourceTemporary layout.sourceScratch layout.temporaryScratch (localEquation u D state) + (bodyLabel u D labels state) (some (labels .append)) p + (fun label => atLabels (.test (SourceTestEmit.bodyLabel u D state label))) + base values sourceWords scratchEmpty state register + +theorem appendTrace (u D : Nat) (layout : Layout K) (labels : Label u D → Λ) (exit : Option Λ) + (p : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State u D)) + (atLabels : ∀ label, p (labels label) = statement u D layout labels exit label) + (state : LocalInput u D) (base : K → List Bool) (values : Fin 3 → Nat) + (sourceWords : ∀ side, base (layout.sources side) = encodeWord (values side)) + (scratchEmpty : base layout.scratch = []) (temporaryEmpty : base layout.temporary = []) + (register : Option Bool) : + (MachineComposition.advance (TM2.step p))^[steps u D values state] + (some ⟨some (labels (.test (.inl ()))), (state, register), base⟩) = + some ⟨exit, (state, none), resultTapes layout base (equationBits u D values state)⟩ := by + let emitted := prefixTapes layout.temporary base (words values (localEquation u D state)) + have hemit := emitTrace u D layout labels exit p atLabels state base values sourceWords + scratchEmpty register + have htemp : emitted layout.temporary = equationBits u D values state := by + simp [emitted, prefixTapes, equationBits, temporaryEmpty] + have hacc : emitted layout.accumulator = base layout.accumulator := + prefixTapes_other _ _ _ _ (Ne.symm layout.temporaryAccumulator) + have hfinal : Reduction.MachineTransfer.tapesAt layout.temporary layout.accumulator emitted [] + ((equationBits u D values state).reverse ++ base layout.accumulator) = + resultTapes layout base (equationBits u D values state) := by + funext k + by_cases hka : k = layout.accumulator + · subst k + simp [Reduction.MachineTransfer.tapesAt, resultTapes] + · by_cases hkt : k = layout.temporary + · subst k + simp [Reduction.MachineTransfer.tapesAt, resultTapes, layout.temporaryAccumulator, + temporaryEmpty] + · simp [Reduction.MachineTransfer.tapesAt, resultTapes, emitted, prefixTapes, hka, hkt] + have transferred := Reduction.MachineTransfer.transferAt_fromTapes + (Γ := fun _ : K => Bool) (σ := LocalInput u D) + layout.temporary layout.accumulator layout.temporaryAccumulator id false (labels .append) + exit p (by simpa only [statement] using atLabels .append) emitted state none + change (MachineComposition.advance (TM2.step p))^[(emitted layout.temporary).length + 1] + (some ⟨some (labels .append), (state, none), emitted⟩) = _ at transferred + rw [htemp, hacc] at transferred + simp only [List.map_id] at transferred + rw [hfinal] at transferred + rw [show steps u D values state = ((equationBits u D values state).length + 1) + + (SourceEquationEmit.steps values (localEquation u D state) + 1) by unfold steps; omega, + Function.iterate_add_apply, hemit] + exact transferred + +def appendInTime (u D : Nat) (layout : Layout K) (labels : Label u D → Λ) (exit : Option Λ) + (p : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State u D)) + (atLabels : ∀ label, p (labels label) = statement u D layout labels exit label) + (state : LocalInput u D) (base : K → List Bool) (values : Fin 3 → Nat) + (sourceWords : ∀ side, base (layout.sources side) = encodeWord (values side)) + (scratchEmpty : base layout.scratch = []) (temporaryEmpty : base layout.temporary = []) + (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step p) + ⟨some (labels (.test (.inl ()))), (state, register), base⟩ + (some ⟨exit, (state, none), resultTapes layout base (equationBits u D values state)⟩) + (steps u D values state) where + steps := steps u D values state + evals_in_steps := appendTrace u D layout labels exit p atLabels state base values + sourceWords scratchEmpty temporaryEmpty register + steps_le_m := Nat.le_refl _ + +def programInTime (u D : Nat) (layout : Layout K) (exit : Option (Label u D)) + (state : LocalInput u D) (base : K → List Bool) (values : Fin 3 → Nat) + (sourceWords : ∀ side, base (layout.sources side) = encodeWord (values side)) + (scratchEmpty : base layout.scratch = []) (temporaryEmpty : base layout.temporary = []) + (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step (program u D layout exit)) + ⟨some (.test (.inl ())), (state, register), base⟩ + (some ⟨exit, (state, none), resultTapes layout base (equationBits u D values state)⟩) + (steps u D values state) := + appendInTime u D layout id exit (program u D layout exit) (fun _ => rfl) state base values + sourceWords scratchEmpty temporaryEmpty register + +def sourceAppendInTime (F : Formula) (u D : Nat) (occurrence : SourceIndex F u D) + (layout : Layout K) (labels : Label u D → Λ) (exit : Option Λ) + (p : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State u D)) + (atLabels : ∀ label, p (labels label) = statement u D layout labels exit label) + (base : K → List Bool) + (sourceWords : ∀ side, base (layout.sources side) = encodeWord + (baseValue F u occurrence.1.1 (sampledVariables F occurrence.1.1 occurrence.1.2) side)) + (scratchEmpty : base layout.scratch = []) (temporaryEmpty : base layout.temporary = []) + (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step p) + ⟨some (labels (.test (.inl ()))), + ((ofContext F occurrence.1.1 occurrence.1.2, occurrence.2), register), base⟩ + (some ⟨exit, ((ofContext F occurrence.1.1 occurrence.1.2, occurrence.2), none), + resultTapes layout base (encodeWords + (MinUncutGames.Reduction.SourceEncoding.equationWords (sourceEquation F u D occurrence)))⟩) + (9 * nBits F u + 20) where + steps := steps u D + (baseValue F u occurrence.1.1 (sampledVariables F occurrence.1.1 occurrence.1.2)) + (ofContext F occurrence.1.1 occurrence.1.2, occurrence.2) + evals_in_steps := by + rw [sourceEquation_words] + exact appendTrace u D layout labels exit p atLabels + (ofContext F occurrence.1.1 occurrence.1.2, occurrence.2) base + (baseValue F u occurrence.1.1 (sampledVariables F occurrence.1.1 occurrence.1.2)) + sourceWords scratchEmpty temporaryEmpty register + steps_le_m := by + have he := equation_emit_steps_le F u occurrence.1.1 + (sampledVariables F occurrence.1.1 occurrence.1.2) + (localEquation u D (ofContext F occurrence.1.1 occurrence.1.2, occurrence.2)) + have hl := MinUncutGames.Reduction.SourceEncoding.equationBits_length_le + (sourceEquation F u D occurrence) + rw [sourceEquation_words] at hl + unfold steps SourceEquationEmit.steps equationBits + dsimp only [localEquation] at he hl ⊢ + omega + +abbrev Tape := Fin 3 ⊕ Fin 3 + +def standardLayout : Layout Tape where + sources := Sum.inl + temporary := .inr 0 + scratch := .inr 1 + accumulator := .inr 2 + sourceTemporary _ := Sum.inl_ne_inr + sourceScratch _ := Sum.inl_ne_inr + sourceAccumulator _ := Sum.inl_ne_inr + temporaryScratch := by decide + temporaryAccumulator := by decide + scratchAccumulator := by decide + +def machine (u D : Nat) (initial : LocalInput u D) : FinTM2 where + K := Tape + k₀ := .inl 0 + k₁ := .inr 2 + Γ _ := Bool + Λ := Label u D + main := .test (.inl ()) + σ := State u D + initialState := (initial, none) + m := program u D standardLayout none + +def machineInTime (u D : Nat) (initial state : LocalInput u D) + (base : Tape → List Bool) (values : Fin 3 → Nat) + (sourceWords : ∀ side, base (.inl side) = encodeWord (values side)) + (scratchEmpty : base (.inr 1) = []) (temporaryEmpty : base (.inr 0) = []) + (register : Option Bool) : + StateTransition.EvalsToInTime (machine u D initial).step + ⟨some (Label.test (.inl ())), (state, register), base⟩ + (some ⟨none, (state, none), resultTapes standardLayout base (equationBits u D values state)⟩) + (steps u D values state) := + programInTime u D standardLayout none state base values sourceWords scratchEmpty temporaryEmpty register + +end MinUncutGames.Foundations.Hastad.SourceTestAppend + +namespace MinUncutGames.Foundations.Hastad.SourceQueryLoop + +open Turing Complexity Target SourceContexts SourceOccurrences +open SourceLocalSignature SourceLocalEquation + +abbrev Query (u D : Nat) := SourceTape.TestTape (I u) (J u) D +abbrev State (u D : Nat) := SourceTestAppend.State u D + +inductive Label (u D n : Nat) + | load (index : Fin (n + 1)) + | emit (index : Fin n) (label : SourceTestAppend.Label u D) + deriving DecidableEq, Fintype + +variable {K Λ : Type} [DecidableEq K] + +def finish (u D : Nat) (exit : Option Λ) : + TM2.Stmt (fun _ : K => Bool) Λ (State u D) := + match exit with + | none => .halt + | some label => .goto fun _ => label + +def statement (u D n : Nat) (queries : Nat → Query u D) + (layout : SourceTestAppend.Layout K) (labels : Label u D n → Λ) (exit : Option Λ) : + Label u D n → TM2.Stmt (fun _ : K => Bool) Λ (State u D) + | .load index => + if h : index.val < n then + .load (fun state => ((state.1.1, queries index.val), none)) + (.goto fun _ => labels (.emit ⟨index.val, h⟩ (.test (.inl ())))) + else finish u D exit + | .emit index label => + SourceTestAppend.statement u D layout (fun l => labels (.emit index l)) + (some (labels (.load ⟨index.val + 1, by omega⟩))) label + +def prefixBits (u D : Nat) (queries : Nat → Query u D) + (values : Fin 3 → Nat) (signature : Signature u) : Nat → List Bool + | 0 => [] + | n + 1 => prefixBits u D queries values signature n ++ + SourceTestAppend.equationBits u D values (signature, queries n) + +def prefixSteps (u D : Nat) (queries : Nat → Query u D) + (values : Fin 3 → Nat) (signature : Signature u) : Nat → Nat + | 0 => 0 + | n + 1 => prefixSteps u D queries values signature n + + (SourceTestAppend.steps u D values (signature, queries n) + 1) + +theorem resultTapes_append (layout : SourceTestAppend.Layout K) (base : K → List Bool) + (first second : List Bool) : + SourceTestAppend.resultTapes layout + (SourceTestAppend.resultTapes layout base first) second = + SourceTestAppend.resultTapes layout base (first ++ second) := by + funext k + by_cases hk : k = layout.accumulator + · subst k + simp [SourceTestAppend.resultTapes, List.reverse_append, List.append_assoc] + · simp [SourceTestAppend.resultTapes, hk] + +theorem prefixTrace (u D n : Nat) (queries : Nat → Query u D) + (layout : SourceTestAppend.Layout K) (labels : Label u D n → Λ) (exit : Option Λ) + (p : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State u D)) + (atLabels : ∀ l, p (labels l) = statement u D n queries layout labels exit l) + (signature : Signature u) (initialQuery : Query u D) + (base : K → List Bool) (values : Fin 3 → Nat) + (sourceWords : ∀ side, base (layout.sources side) = encodeWord (values side)) + (scratchEmpty : base layout.scratch = []) (temporaryEmpty : base layout.temporary = []) + (r : Nat) (hr : r ≤ n) : + ∃ lastQuery : Query u D, + (MachineComposition.advance (TM2.step p))^[prefixSteps u D queries values signature r] + (some ⟨some (labels (.load ⟨0, by omega⟩)), ((signature, initialQuery), none), base⟩) = + some ⟨some (labels (.load ⟨r, by omega⟩)), ((signature, lastQuery), none), + SourceTestAppend.resultTapes layout base (prefixBits u D queries values signature r)⟩ := by + induction r with + | zero => + refine ⟨initialQuery, ?_⟩ + simp [prefixSteps, prefixBits, SourceTestAppend.resultTapes] + | succ r ih => + obtain ⟨lastQuery, hprevious⟩ := ih (by omega) + have hlt : r < n := by omega + let current := SourceTestAppend.resultTapes layout base + (prefixBits u D queries values signature r) + have hselect : TM2.step p + ⟨some (labels (.load ⟨r, by omega⟩)), ((signature, lastQuery), none), current⟩ = + some ⟨some (labels (.emit ⟨r, hlt⟩ (.test (.inl ())))), + ((signature, queries r), none), current⟩ := by + change some (TM2.stepAux (p (labels (.load ⟨r, by omega⟩))) _ _) = _ + rw [atLabels] + simp only [statement, hlt, ↓reduceDIte, TM2.stepAux] + have hbody := SourceTestAppend.appendTrace u D layout + (fun l => labels (.emit ⟨r, hlt⟩ l)) + (some (labels (.load ⟨r + 1, by omega⟩))) p + (fun l => atLabels (.emit ⟨r, hlt⟩ l)) (signature, queries r) current values + (fun side => (SourceTestAppend.resultTapes_source layout base _ side).trans + (sourceWords side)) + ((SourceTestAppend.resultTapes_scratch layout base _).trans scratchEmpty) + ((SourceTestAppend.resultTapes_temporary layout base _).trans temporaryEmpty) none + refine ⟨queries r, ?_⟩ + rw [show prefixSteps u D queries values signature (r + 1) = + (SourceTestAppend.steps u D values (signature, queries r) + 1) + + prefixSteps u D queries values signature r by rw [prefixSteps]; omega, + Function.iterate_add_apply, hprevious, Function.iterate_succ_apply] + change (MachineComposition.advance (TM2.step p))^[ + SourceTestAppend.steps u D values (signature, queries r)] + (TM2.step p ⟨some (labels (.load ⟨r, by omega⟩)), + ((signature, lastQuery), none), current⟩) = _ + rw [hselect, hbody] + rw [show current = SourceTestAppend.resultTapes layout base + (prefixBits u D queries values signature r) from rfl, resultTapes_append] + rfl + +theorem prefixSteps_le (u D n B : Nat) (queries : Nat → Query u D) + (values : Fin 3 → Nat) (signature : Signature u) + (hbound : ∀ i, i < n → SourceTestAppend.steps u D values (signature, queries i) ≤ B) : + prefixSteps u D queries values signature n ≤ n * (B + 1) := by + induction n with + | zero => simp [prefixSteps] + | succ n ih => + have hp := ih (fun i hi => hbound i (by omega)) + have hb := hbound n (by omega) + rw [prefixSteps, Nat.succ_mul] + omega + +theorem loopInTime (u D n B : Nat) (queries : Nat → Query u D) + (layout : SourceTestAppend.Layout K) (labels : Label u D n → Λ) (exit : Option Λ) + (p : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State u D)) + (atLabels : ∀ l, p (labels l) = statement u D n queries layout labels exit l) + (signature : Signature u) (initialQuery : Query u D) + (base : K → List Bool) (values : Fin 3 → Nat) + (sourceWords : ∀ side, base (layout.sources side) = encodeWord (values side)) + (scratchEmpty : base layout.scratch = []) (temporaryEmpty : base layout.temporary = []) + (hbound : ∀ i, i < n → SourceTestAppend.steps u D values (signature, queries i) ≤ B) : + ∃ lastQuery : Query u D, + Nonempty (StateTransition.EvalsToInTime (TM2.step p) + ⟨some (labels (.load ⟨0, by omega⟩)), ((signature, initialQuery), none), base⟩ + (some ⟨exit, ((signature, lastQuery), none), + SourceTestAppend.resultTapes layout base (prefixBits u D queries values signature n)⟩) + (n * (B + 1) + 1)) := by + obtain ⟨lastQuery, hprefix⟩ := prefixTrace u D n queries layout labels exit p atLabels + signature initialQuery base values sourceWords scratchEmpty temporaryEmpty n (Nat.le_refl n) + refine ⟨lastQuery, ⟨{ + steps := prefixSteps u D queries values signature n + 1 + evals_in_steps := ?_ + steps_le_m := ?_ }⟩⟩ + · change (MachineComposition.advance (TM2.step p))^[ + prefixSteps u D queries values signature n + 1] _ = _ + rw [Function.iterate_succ_apply', hprefix] + rw [MachineComposition.advance_some] + change some (TM2.stepAux (p (labels (.load ⟨n, by omega⟩))) _ _) = _ + rw [atLabels] + simp only [statement, Nat.lt_irrefl, ↓reduceDIte] + cases exit <;> rfl + · exact Nat.add_le_add_right (prefixSteps_le u D n B queries values signature hbound) 1 + +end MinUncutGames.Foundations.Hastad.SourceQueryLoop + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/DistributionMaps.lean b/lean/OAI/Computability/MinUncut/PCP/DistributionMaps.lean new file mode 100644 index 0000000000000000000000000000000000000000..792e1fe75400c888fe3f0e6b9209a43763cfe3b4 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/DistributionMaps.lean @@ -0,0 +1,256 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.SelectedMarginal +import OAI.Computability.MinUncut.Games.KernelSampling + +namespace OAI + +namespace MinUncutGames.Foundations.Games.FiniteDistribution +open scoped BigOperators +noncomputable section +variable {A B C : Type*} [Fintype A] [Fintype B] [Fintype C] + +theorem weight_eq_probability_singleton [DecidableEq A] (μ : FiniteDistribution A) (a : A) : + μ.weight a = μ.probability (fun x => decide (x = a)) := by + classical + simp [probability] + +theorem pushforward_comp (μ : FiniteDistribution A) (f : A → B) (g : B → C) : + (μ.pushforward f).pushforward g = μ.pushforward (fun a => g (f a)) := by + classical + apply eq_of_weight_eq + intro c + rw [weight_eq_probability_singleton, weight_eq_probability_singleton] + simp only [probability_pushforward] + +theorem transport_eq_pushforward (μ : FiniteDistribution A) (e : A ≃ B) : + μ.transport e = μ.pushforward e := by + classical + apply eq_of_weight_eq + intro b + rw [weight_eq_probability_singleton, weight_eq_probability_singleton, + probability_transport, probability_pushforward] + +theorem expectation_pushforward (μ : FiniteDistribution A) (f : A → B) (h : B → ℝ) : + (μ.pushforward f).expectation h = μ.expectation (fun a => h (f a)) := by + classical + simp only [expectation, pushforward, Finset.sum_mul] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro a _ + simp [ite_mul] + +theorem pushforward_mixture (μ : FiniteDistribution A) (ν : A → FiniteDistribution B) + (f : B → C) : + (μ.mixture ν).pushforward f = μ.mixture (fun a => (ν a).pushforward f) := by + classical + apply eq_of_weight_eq + intro c + rw [weight_eq_probability_singleton, weight_eq_probability_singleton] + simp only [probability_pushforward, probability_mixture] + +end +end MinUncutGames.Foundations.Games.FiniteDistribution + +namespace MinUncutGames.Foundations.Repetition +open scoped BigOperators +open Games Information +noncomputable section + +theorem isProbability_comp_equiv {A B : Type*} [Fintype A] [Fintype B] + (e : A ≃ B) (p : B → ℝ) (hp : IsProbability p) : + IsProbability (fun a => p (e a)) := by + constructor + · intro a + exact hp.1 _ + · rw [e.sum_comp] + exact hp.2 + +theorem partialRevealMarginal_isProbability + {I T X Y : Type*} [Fintype I] [DecidableEq I] [Fintype T] + [Fintype X] [Fintype Y] [DecidableEq X] [DecidableEq Y] + (μ : FiniteDistribution (X × Y)) (j : I) + (likelihood : T → (I → X × Y) → ℝ) + (hp : IsProbability (fullRevealMarginal μ j likelihood)) : + IsProbability (partialRevealMarginal μ j likelihood) := by + apply (maskedJoint_isProbability_iff _).mp + have h := isProbability_comp_equiv (revealSplitEquiv (T := T) j).symm _ hp + have he : (fun z => fullRevealMarginal μ j likelihood + ((revealSplitEquiv (T := T) j).symm z)) = + maskedJoint (partialRevealMarginal μ j likelihood) := by + funext z + exact fullRevealMarginal_merge μ j likelihood z.1.1.1 z.1.1.2 z.1.2 z.2 + rw [he] at h + exact h + +variable {Q₁ Q₂ A₁ A₂ : Type*} + [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂] + [DecidableEq Q₁] [DecidableEq Q₂] {n : Nat} + +abbrev SelectedCommonData (selected : Finset (Fin n)) + (j : {i : Fin n // i ∉ selected}) := + ((selected → Q₁ × Q₂) × SelectedLabels (A₁ := A₁) (A₂ := A₂) selected) × + ({i : {i : Fin n // i ∉ selected} // i ≠ j} → Q₁ ⊕ Q₂) + +theorem selected_fullReveal_isProbability (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) + (j : {i : Fin n // i ∉ selected}) : + IsProbability (fullRevealMarginal G.questions j + (selectedOutsideLikelihood G strategy selected)) := by + have h := isProbability_comp_equiv + (selectedObservationEquiv (Q₁ := Q₁) (Q₂ := Q₂) (A₁ := A₁) (A₂ := A₂) selected).symm + _ (selectedRawMarginal_isProbability G strategy selected positive j) + have he : (fun z => selectedRawMarginal G strategy selected j + ((selectedObservationEquiv (Q₁ := Q₁) (Q₂ := Q₂) (A₁ := A₁) (A₂ := A₂) selected).symm z)) = + fullRevealMarginal G.questions j (selectedOutsideLikelihood G strategy selected) := by + funext z + exact selectedRawMarginal_fullReveal G strategy selected j z + rw [he] at h + exact h + +def selectedCommonLaw (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) + (j : {i : Fin n // i ∉ selected}) : + FiniteDistribution (SelectedCommonData (Q₁ := Q₁) (Q₂ := Q₂) + (A₁ := A₁) (A₂ := A₂) selected j × (Q₁ × Q₂)) := + toGameLaw (partialRevealMarginal G.questions j (selectedOutsideLikelihood G strategy selected)) + (partialRevealMarginal_isProbability G.questions j _ + (selected_fullReveal_isProbability G strategy selected positive j)) + +variable {S X Y : Type*} [Fintype S] [Fintype X] [Fintype Y] + +theorem firstMarginal_totalVariation_le (r t : X × Y → ℝ) : + totalVariation (firstMarginal r) (firstMarginal t) ≤ totalVariation r t := by + unfold totalVariation firstMarginal + simp_rw [← Finset.sum_sub_distrib] + have h := Finset.sum_le_sum (s := Finset.univ) + (fun x _ => Finset.abs_sum_le_sum_abs (fun y : Y => r (x,y)-t (x,y)) Finset.univ) + rw [Fintype.sum_prod_type] + linarith + +def leftCommonMarginal (p : S × (X × Y) → ℝ) : X × S → ℝ := + fun z => ∑ y, p (z.2,(z.1,y)) + +def leftCommonProfile (p : S × (X × Y) → ℝ) (fallback : S → ℝ) : X → S → ℝ := + conditionalKernel (leftCommonMarginal p) fallback + +def swapSeedLeft : (X × (S × Y)) ≃ (S × (X × Y)) where + toFun z := (z.2.1,(z.1,z.2.2)) + invFun z := (z.2.1,(z.1,z.2.2)) + left_inv _ := rfl + right_inv _ := rfl + +theorem leftCommonMarginal_isProbability (p : S × (X × Y) → ℝ) + (hp : IsProbability p) : IsProbability (leftCommonMarginal p) := by + exact ProfileCorrection.seedQuestionMarginal_isProbability + (fun z => p (swapSeedLeft z)) (isProbability_comp_equiv swapSeedLeft p hp) + +theorem leftCommonProfile_isProbability (p : S × (X × Y) → ℝ) (fallback : S → ℝ) + (hp : IsProbability p) (hf : IsProbability fallback) (x : X) : + IsProbability (leftCommonProfile p fallback x) := + conditionalKernel_isProbability _ _ (leftCommonMarginal_isProbability p hp) hf x + +theorem leftCommonProfile_error [DecidableEq X] [DecidableEq Y] + (p : S × (X × Y) → ℝ) (μ : FiniteDistribution (X × Y)) (fallback : S → ℝ) + (hp : IsProbability p) (hf : IsProbability fallback) : + totalVariation p (fun z => μ.weight z.2 * leftCommonProfile p fallback z.2.1 z.1) ≤ + totalVariation p (leftRevealModel μ p) + totalVariation (secondMarginal p) μ.weight := by + let e := swapSeedLeft (S := S) (X := X) (Y := Y) + let p' : X × (S × Y) → ℝ := fun z => p (e z) + have h := ProfileCorrection.left_profile_correction p' μ.weight fallback + (μ.pushforward Prod.snd).weight + (isProbability_comp_equiv e p hp) (gameLaw_isProbability μ) hf + (gameLaw_isProbability (μ.pushforward Prod.snd)) + have hs : ProfileCorrection.seedQuestionMarginal p' = leftCommonMarginal p := rfl + have hc : (fun z : X × (S × Y) => ProfileCorrection.seedQuestionMarginal p' (z.1,z.2.1) * + conditionalKernel μ.weight (μ.pushforward Prod.snd).weight z.1 z.2.2) = + fun z => leftRevealModel μ p (e z) := by + funext z + change (∑ y, p (z.2.1,(z.1,y))) * + conditionalKernel μ.weight (μ.pushforward Prod.snd).weight z.1 z.2.2 = + (∑ y, p (z.2.1,(z.1,y))) * + (revealProfile μ (Sum.inl z.1)).weight (z.1,z.2.2) + rw [revealProfile_inl_diagonal] + have hd : (fun z : X × (S × Y) => μ.weight (z.1,z.2.2) * + conditionalKernel (ProfileCorrection.seedQuestionMarginal p') fallback z.1 z.2.1) = + fun z => μ.weight (e z).2 * leftCommonProfile p fallback (e z).2.1 (e z).1 := rfl + rw [hc, hd] at h + change totalVariation (fun z => p (e z)) _ ≤ + totalVariation (fun z => p (e z)) _ + _ at h + rw [totalVariation_comp_equiv e p (leftRevealModel μ p)] at h + rw [totalVariation_comp_equiv e p + (fun z => μ.weight z.2 * leftCommonProfile p fallback z.2.1 z.1)] at h + have hm : firstMarginal p' = firstMarginal (secondMarginal p) := by + funext x + simp only [firstMarginal, secondMarginal, Fintype.sum_prod_type, p', e, swapSeedLeft] + exact Finset.sum_comm + rw [hm] at h + exact h.trans (add_le_add le_rfl (firstMarginal_totalVariation_le (secondMarginal p) μ.weight)) + +def swapQuestionEndpoints : (S × (Y × X)) ≃ (S × (X × Y)) where + toFun z := (z.1,(z.2.2,z.2.1)) + invFun z := (z.1,(z.2.2,z.2.1)) + left_inv _ := rfl + right_inv _ := rfl + +def rightCommonMarginal (p : S × (X × Y) → ℝ) : Y × S → ℝ := + fun z => ∑ x, p (z.2,(x,z.1)) + +def rightCommonProfile (p : S × (X × Y) → ℝ) (fallback : S → ℝ) : Y → S → ℝ := + conditionalKernel (rightCommonMarginal p) fallback + +theorem rightCommonProfile_isProbability (p : S × (X × Y) → ℝ) (fallback : S → ℝ) + (hp : IsProbability p) (hf : IsProbability fallback) (y : Y) : + IsProbability (rightCommonProfile p fallback y) := + leftCommonProfile_isProbability (fun z => p (swapQuestionEndpoints z)) fallback + (isProbability_comp_equiv swapQuestionEndpoints p hp) hf y + +theorem swap_question_pushforward_snd (μ : FiniteDistribution (X × Y)) : + ((μ.transport (Equiv.prodComm X Y)).pushforward Prod.snd) = μ.pushforward Prod.fst := by + rw [FiniteDistribution.transport_eq_pushforward, FiniteDistribution.pushforward_comp] + rfl + +omit [Fintype S] in +theorem leftRevealModel_swap [DecidableEq X] [DecidableEq Y] + (p : S × (X × Y) → ℝ) (μ : FiniteDistribution (X × Y)) (z : S × (Y × X)) : + leftRevealModel (μ.transport (Equiv.prodComm X Y)) + (fun z => p (swapQuestionEndpoints z)) z = rightRevealModel μ p (swapQuestionEndpoints z) := by + rcases z with ⟨s,y,x⟩ + change (∑ x', p (s,(x',y))) * + (revealProfile (μ.transport (Equiv.prodComm X Y)) (Sum.inl y)).weight (y,x) = + (∑ x', p (s,(x',y))) * (revealProfile μ (Sum.inr y)).weight (x,y) + rw [revealProfile_inl_diagonal, revealProfile_inr_diagonal, swap_question_pushforward_snd] + +theorem rightCommonProfile_error [DecidableEq X] [DecidableEq Y] + (p : S × (X × Y) → ℝ) (μ : FiniteDistribution (X × Y)) (fallback : S → ℝ) + (hp : IsProbability p) (hf : IsProbability fallback) : + totalVariation p (fun z => μ.weight z.2 * rightCommonProfile p fallback z.2.2 z.1) ≤ + totalVariation p (rightRevealModel μ p) + totalVariation (secondMarginal p) μ.weight := by + let e := swapQuestionEndpoints (S := S) (X := X) (Y := Y) + let p' : S × (Y × X) → ℝ := fun z => p (e z) + let μ' := μ.transport (Equiv.prodComm X Y) + have h := leftCommonProfile_error p' μ' fallback (isProbability_comp_equiv e p hp) hf + have hc : leftRevealModel μ' p' = fun z => rightRevealModel μ p (e z) := by + funext z + exact leftRevealModel_swap p μ z + have hd : (fun z : S × (Y × X) => μ'.weight z.2 * leftCommonProfile p' fallback z.2.1 z.1) = + fun z => μ.weight (e z).2 * rightCommonProfile p fallback (e z).2.2 (e z).1 := rfl + rw [hc, hd] at h + change totalVariation (fun z => p (e z)) _ ≤ + totalVariation (fun z => p (e z)) _ + _ at h + rw [totalVariation_comp_equiv e p (rightRevealModel μ p)] at h + rw [totalVariation_comp_equiv e p + (fun z => μ.weight z.2 * rightCommonProfile p fallback z.2.2 z.1)] at h + have hm : totalVariation (secondMarginal p') μ'.weight = + totalVariation (secondMarginal p) μ.weight := by + change totalVariation (fun yx => secondMarginal p ((Equiv.prodComm Y X) yx)) + (fun yx => μ.weight ((Equiv.prodComm Y X) yx)) = _ + exact totalVariation_comp_equiv (Equiv.prodComm Y X) _ _ + rw [hm] at h + exact h + +end +end MinUncutGames.Foundations.Repetition + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/EquationEmit.lean b/lean/OAI/Computability/MinUncut/PCP/EquationEmit.lean new file mode 100644 index 0000000000000000000000000000000000000000..ab7669b725dbf9322b474d83610deed12bb0d7b2 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/EquationEmit.lean @@ -0,0 +1,210 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.AddressArithmetic +import OAI.Computability.MinUncut.Machines.MachineRegisterEmit + +namespace OAI + +section +namespace MinUncutGames.Foundations.Hastad.SourceEquationEmit + +open Turing Complexity +open SourceAddressDescriptors +open MinUncutGames.Reduction.CloneGap +open MinUncutGames.Reduction.MachineSubstitution + +inductive Label + | seed | thirdDrain | thirdFork | thirdEmit + | secondDrain | secondFork | secondEmit | firstDrain | firstFork | firstEmit + deriving DecidableEq + +protected abbrev Label.enumList : List Label := [.seed, .thirdDrain, .thirdFork, .thirdEmit, + .secondDrain, .secondFork, .secondEmit, .firstDrain, .firstFork, .firstEmit] + +protected theorem Label.enumList_getElem?_ctorIdx_eq (x : Label) : + Label.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem Label.enumList_nodup : Label.enumList.Nodup := by decide + +instance : Fintype Label where + elems := ⟨Label.enumList, Label.enumList_nodup⟩ + complete x := by cases x <;> decide + +abbrev Alphabet {K : Type} (_ : K) := Bool +abbrev State (σ : Type) := σ × Option Bool + +def rhsBit (e : Equation Descriptor) : Nat := if e.rhs then 1 else 0 + +def steps (values : Fin 3 → Nat) (e : Equation Descriptor) : Nat := + 2 * (values e.first.1 + values e.second.1 + values e.third.1) + 16 + +variable {K Λ σ : Type} [DecidableEq K] + +def statement (sources : Fin 3 → K) (destination scratch : K) + (e : Equation Descriptor) (labels : Label → Λ) (exit : Option Λ) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (State σ) + | .seed => pushWord destination (encodeWord (rhsBit e)).reverse + (.goto fun _ => labels .thirdDrain) + | .thirdDrain => Reduction.MachineTransfer.loopAt (sources e.third.1) scratch id false + (labels .thirdDrain) (some (labels .thirdFork)) + | .thirdFork => MachineCopy.forkLoop scratch (sources e.third.1) destination false + (labels .thirdFork) (some (labels .thirdEmit)) + | .thirdEmit => MachineRegisterEmit.emitStatement destination e.third.2 + (some (labels .secondDrain)) + | .secondDrain => Reduction.MachineTransfer.loopAt (sources e.second.1) scratch id false + (labels .secondDrain) (some (labels .secondFork)) + | .secondFork => MachineCopy.forkLoop scratch (sources e.second.1) destination false + (labels .secondFork) (some (labels .secondEmit)) + | .secondEmit => MachineRegisterEmit.emitStatement destination e.second.2 + (some (labels .firstDrain)) + | .firstDrain => Reduction.MachineTransfer.loopAt (sources e.first.1) scratch id false + (labels .firstDrain) (some (labels .firstFork)) + | .firstFork => MachineCopy.forkLoop scratch (sources e.first.1) destination false + (labels .firstFork) (some (labels .firstEmit)) + | .firstEmit => MachineRegisterEmit.emitStatement destination e.first.2 exit + +def program (sources : Fin 3 → K) (destination scratch : K) (e : Equation Descriptor) : + Label → TM2.Stmt (Alphabet (K := K)) Label (State σ) := + statement sources destination scratch e id none + +def prefixTapes (destination : K) (base : K → List Bool) (written : List Nat) : + K → List Bool := Function.update base destination (encodeWords written ++ base destination) + +theorem prefixTapes_other (destination : K) (base : K → List Bool) (written : List Nat) + (k : K) (hk : k ≠ destination) : prefixTapes destination base written k = base k := by + simp [prefixTapes, hk] + +theorem equationTrace (sources : Fin 3 → K) (destination scratch : K) + (sourceDestination : ∀ side, sources side ≠ destination) + (sourceScratch : ∀ side, sources side ≠ scratch) + (destinationScratch : destination ≠ scratch) (e : Equation Descriptor) + (labels : Label → Λ) (exit : Option Λ) + (p : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ label, p (labels label) = statement sources destination scratch e labels exit label) + (base : K → List Bool) (values : Fin 3 → Nat) + (sourceWords : ∀ side, base (sources side) = encodeWord (values side)) + (scratchEmpty : base scratch = []) (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step p))^[steps values e] + (some ⟨some (labels .seed), (ambient, register), base⟩) = + some ⟨exit, (ambient, none), prefixTapes destination base (words values e)⟩ := by + have hw (written : List Nat) (side : Fin 3) : + prefixTapes destination base written (sources side) = encodeWord (values side) := by + rw [prefixTapes_other _ _ _ _ (sourceDestination side), sourceWords side] + have hs (written : List Nat) : prefixTapes destination base written scratch = [] := by + rw [prefixTapes_other _ _ _ _ (Ne.symm destinationScratch), scratchEmpty] + have hseed : (MachineComposition.advance (TM2.step p))^[1] + (some ⟨some (labels .seed), (ambient, register), base⟩) = + some ⟨some (labels .thirdDrain), (ambient, register), + prefixTapes destination base [rhsBit e]⟩ := by + change some (TM2.stepAux (p (labels .seed)) (ambient, register) base) = _ + rw [atLabels .seed] + simp only [statement, stepAux_pushWord, List.reverse_reverse, TM2.stepAux, + prefixTapes, encodeWords, List.append_nil] + have hthird : (MachineComposition.advance (TM2.step p))^[2 * values e.third.1 + 5] + (some ⟨some (labels .thirdDrain), (ambient, register), + prefixTapes destination base [rhsBit e]⟩) = + some ⟨some (labels .secondDrain), (ambient, none), + prefixTapes destination base [realize values e.third, rhsBit e]⟩ := by + have h := MachineRegisterEmit.registerEmitTrace (sources e.third.1) destination scratch + (sourceDestination _) (sourceScratch _) destinationScratch e.third.2 + (labels .thirdDrain) (labels .thirdFork) (labels .thirdEmit) (some (labels .secondDrain)) + p (atLabels .thirdDrain) (atLabels .thirdFork) (atLabels .thirdEmit) + (prefixTapes destination base [rhsBit e]) (values e.third.1) + (hw _ _) (hs _) ambient register + simpa only [prefixTapes, Function.update_self, Function.update_idem, realize, + encodeWords, List.append_nil, List.append_assoc] using h + have hsecond : (MachineComposition.advance (TM2.step p))^[2 * values e.second.1 + 5] + (some ⟨some (labels .secondDrain), (ambient, none), + prefixTapes destination base [realize values e.third, rhsBit e]⟩) = + some ⟨some (labels .firstDrain), (ambient, none), + prefixTapes destination base [realize values e.second, realize values e.third, rhsBit e]⟩ := by + have h := MachineRegisterEmit.registerEmitTrace (sources e.second.1) destination scratch + (sourceDestination _) (sourceScratch _) destinationScratch e.second.2 + (labels .secondDrain) (labels .secondFork) (labels .secondEmit) (some (labels .firstDrain)) + p (atLabels .secondDrain) (atLabels .secondFork) (atLabels .secondEmit) + (prefixTapes destination base [realize values e.third, rhsBit e]) (values e.second.1) + (hw _ _) (hs _) ambient none + simpa only [prefixTapes, Function.update_self, Function.update_idem, realize, + encodeWords, List.append_nil, List.append_assoc] using h + have hfirst : (MachineComposition.advance (TM2.step p))^[2 * values e.first.1 + 5] + (some ⟨some (labels .firstDrain), (ambient, none), + prefixTapes destination base [realize values e.second, realize values e.third, rhsBit e]⟩) = + some ⟨exit, (ambient, none), prefixTapes destination base (words values e)⟩ := by + have h := MachineRegisterEmit.registerEmitTrace (sources e.first.1) destination scratch + (sourceDestination _) (sourceScratch _) destinationScratch e.first.2 + (labels .firstDrain) (labels .firstFork) (labels .firstEmit) exit + p (atLabels .firstDrain) (atLabels .firstFork) (atLabels .firstEmit) + (prefixTapes destination base [realize values e.second, realize values e.third, rhsBit e]) + (values e.first.1) (hw _ _) (hs _) ambient none + simpa only [prefixTapes, Function.update_self, Function.update_idem, words, rhsBit, realize, + encodeWords, List.append_nil, List.append_assoc] using h + rw [show steps values e = (2 * values e.first.1 + 5) + + ((2 * values e.second.1 + 5) + ((2 * values e.third.1 + 5) + 1)) by + unfold steps; omega] + rw [Function.iterate_add_apply _ (2 * values e.first.1 + 5), + Function.iterate_add_apply _ (2 * values e.second.1 + 5), + Function.iterate_add_apply _ (2 * values e.third.1 + 5), hseed, hthird, hsecond, hfirst] + +def equationInTime (sources : Fin 3 → K) (destination scratch : K) + (sourceDestination : ∀ side, sources side ≠ destination) + (sourceScratch : ∀ side, sources side ≠ scratch) + (destinationScratch : destination ≠ scratch) (e : Equation Descriptor) + (labels : Label → Λ) (exit : Option Λ) + (p : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ label, p (labels label) = statement sources destination scratch e labels exit label) + (base : K → List Bool) (values : Fin 3 → Nat) + (sourceWords : ∀ side, base (sources side) = encodeWord (values side)) + (scratchEmpty : base scratch = []) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step p) + ⟨some (labels .seed), (ambient, register), base⟩ + (some ⟨exit, (ambient, none), prefixTapes destination base (words values e)⟩) + (steps values e) where + steps := steps values e + evals_in_steps := equationTrace sources destination scratch sourceDestination sourceScratch + destinationScratch e labels exit p atLabels base values sourceWords scratchEmpty ambient register + steps_le_m := Nat.le_refl _ + +def programInTime (sources : Fin 3 → K) (destination scratch : K) + (sourceDestination : ∀ side, sources side ≠ destination) + (sourceScratch : ∀ side, sources side ≠ scratch) + (destinationScratch : destination ≠ scratch) (e : Equation Descriptor) + (base : K → List Bool) (values : Fin 3 → Nat) + (sourceWords : ∀ side, base (sources side) = encodeWord (values side)) + (scratchEmpty : base scratch = []) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step (program (σ := σ) sources destination scratch e)) + ⟨some .seed, (ambient, register), base⟩ + (some ⟨none, (ambient, none), prefixTapes destination base (words values e)⟩) + (steps values e) := + equationInTime sources destination scratch sourceDestination sourceScratch destinationScratch + e id none (program sources destination scratch e) (fun _ => rfl) + base values sourceWords scratchEmpty ambient register + +abbrev Tape := Fin 3 ⊕ Bool + +def machine (e : Equation Descriptor) : FinTM2 where + K := Tape + k₀ := .inl 0 + k₁ := .inr false + Γ _ := Bool + Λ := Label + main := .seed + σ := State Unit + initialState := ((), none) + m := program Sum.inl (.inr false) (.inr true) e + +def machineInTime (e : Equation Descriptor) (base : Tape → List Bool) (values : Fin 3 → Nat) + (sourceWords : ∀ side, base (.inl side) = encodeWord (values side)) + (scratchEmpty : base (.inr true) = []) (register : Option Bool) : + StateTransition.EvalsToInTime (machine e).step + ⟨some Label.seed, ((), register), base⟩ + (some ⟨none, ((), none), prefixTapes (.inr false : Tape) base (words values e)⟩) + (steps values e) := + programInTime Sum.inl (.inr false : Tape) (.inr true) + (fun _ => Sum.inl_ne_inr) (fun _ => Sum.inl_ne_inr) (by decide) + e base values sourceWords scratchEmpty () register + +end MinUncutGames.Foundations.Hastad.SourceEquationEmit + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/ExpanderFamily.lean b/lean/OAI/Computability/MinUncut/PCP/ExpanderFamily.lean new file mode 100644 index 0000000000000000000000000000000000000000..286b641f5a9a8afc57b9135ddb5957310ba842f7 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/ExpanderFamily.lean @@ -0,0 +1,775 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.CayleySpectral + +namespace OAI + +namespace MinUncutGames.Foundations.PCP.ExpanderFamily + +open PoweringWalks SpectralReturn Expanders + +abbrev Port := BasePort × BasePort +abbrev CloudPort := Port × Port +def growth : Nat := baseDegree ^ 4 + +theorem card_port : Fintype.card Port = baseDegree ^ 2 := by + change Fintype.card (BasePort × BasePort) = baseDegree ^ 2 + rw [Fintype.card_prod, card_basePort, pow_two] + +theorem card_cloudPort : Fintype.card CloudPort = growth := by + change Fintype.card (Port × Port) = growth + rw [Fintype.card_prod, card_port] + unfold growth + ring + +theorem growth_gt_one : 1 < growth := by + norm_num [growth, baseDegree, initialDegree, basePower] + +theorem port_degree_ge_eight : 8 ≤ Fintype.card Port := by + rw [card_port] + norm_num [baseDegree, initialDegree, basePower] + +noncomputable def baseVertexEquiv : BaseVertex ≃ CloudPort := + Fintype.equivOfCardEq (card_baseVertex.trans card_cloudPort.symm) + +noncomputable def baseOnCloud : PortGraph CloudPort BasePort := + GraphTransport.reindex (Classical.choose exists_baseGraph) baseVertexEquiv (Equiv.refl _) + +theorem baseOnCloud_certificate : SpectralCertificate baseOnCloud (1 / 100 : ℝ) := + GraphTransport.reindex_spectralCertificate _ _ _ _ (Classical.choose_spec exists_baseGraph) + +def Vertex : Nat → Type + | 0 => Unit + | n + 1 => Vertex n × CloudPort + +instance vertexFintype (n : Nat) : Fintype (Vertex n) := by + induction n with + | zero => exact inferInstanceAs (Fintype Unit) + | succ n ih => + letI : Fintype (Vertex n) := ih + change Fintype (Vertex n × CloudPort) + infer_instance + +instance basePortNonempty : Nonempty BasePort := + ⟨fun _ => ⟨0, by norm_num [initialQuarterDegree]⟩⟩ + +instance vertexNonempty (n : Nat) : Nonempty (Vertex n) := by + induction n with + | zero => exact inferInstanceAs (Nonempty Unit) + | succ n ih => + let : Nonempty (Vertex n) := ih + change Nonempty (Vertex n × CloudPort) + infer_instance + +def graph (H : PortGraph CloudPort BasePort) : (n : Nat) → PortGraph (Vertex n) Port + | 0 => { rot := Equiv.refl _, rot_involutive := fun _ => rfl } + | n + 1 => ZigzagGraphs.zigzag (ZigzagGraphs.square (graph H n)) H + +theorem graph_certificate (H : PortGraph CloudPort BasePort) + (hH : SpectralCertificate H (1 / 100 : ℝ)) (n : Nat) : + SpectralCertificate (graph H n) (1 / 2 : ℝ) := by + induction n with + | zero => + refine ⟨by norm_num, by norm_num, ?_⟩ + intro f hf + have hm : mean f = f () := by + change mean (fun x : Unit => f x) = f () + have hfun : (fun x : Unit => f x) = fun _ : Unit => f () := by + funext x + cases x + rfl + rw [hfun, mean_const] + have hz : f = fun _ => 0 := by + funext x + cases x + exact hm.symm.trans hf + rw [hz] + simp [energy, mean, averagingOperator] + | succ n ih => + exact ZigzagSpectral.square_zigzag_halfCertificate (graph H n) H ih hH + +noncomputable def family (n : Nat) : PortGraph (Vertex n) Port := graph baseOnCloud n + +theorem family_certificate (n : Nat) : SpectralCertificate (family n) (1 / 2 : ℝ) := + graph_certificate baseOnCloud baseOnCloud_certificate n + +theorem card_vertex (n : Nat) : Fintype.card (Vertex n) = growth ^ n := by + induction n with + | zero => rfl + | succ n ih => + change Fintype.card (Vertex n × CloudPort) = growth ^ (n + 1) + rw [Fintype.card_prod, ih, card_cloudPort, pow_succ] + +def level (k : Nat) : Nat := Nat.clog growth k + +def size (k : Nat) : Nat := growth ^ level k + +theorem le_size (k : Nat) : k ≤ size k := Nat.le_pow_clog growth_gt_one k + +theorem size_le_mul {k : Nat} (hk : 0 < k) : size k ≤ growth * k := by + by_cases hk1 : k = 1 + · subst k + simpa [size, level] using growth_gt_one.le + · have hk2 : 1 < k := by omega + have hl : 0 < level k := Nat.clog_pos growth_gt_one hk2 + have hp : growth ^ (level k).pred < k := + Nat.pow_pred_clog_lt_self growth_gt_one hk2 + have he : (level k).pred + 1 = level k := Nat.succ_pred_eq_of_pos hl + calc + size k = growth ^ ((level k).pred + 1) := by rw [he]; rfl + _ = growth * growth ^ (level k).pred := by rw [pow_succ, Nat.mul_comm] + _ ≤ growth * k := Nat.mul_le_mul_left growth hp.le + +theorem padded_family_size {k : Nat} (hk : 0 < k) : + k ≤ Fintype.card (Vertex (level k)) ∧ + Fintype.card (Vertex (level k)) ≤ growth * k := by + rw [card_vertex] + exact ⟨le_size k, size_le_mul hk⟩ + +end MinUncutGames.Foundations.PCP.ExpanderFamily + +namespace MinUncutGames.Foundations.PCP.CloudPadding + +open scoped BigOperators +open DegreeReplacement + +variable {V E A : Type*} + +def paddedSize (k : Nat) : Nat := if k = 0 then 0 else ExpanderFamily.size k + +@[simp] theorem paddedSize_zero : paddedSize 0 = 0 := rfl + +theorem paddedSize_of_pos {k : Nat} (hk : 0 < k) : + paddedSize k = ExpanderFamily.size k := by + simp only [paddedSize, ite_eq_right (Nat.ne_of_gt hk)] + +theorem le_paddedSize (k : Nat) : k ≤ paddedSize k := by + by_cases hk : k = 0 + · subst k + simp + · rw [paddedSize, ite_eq_right hk] + exact ExpanderFamily.le_size k + +theorem paddedSize_le_mul (k : Nat) : paddedSize k ≤ ExpanderFamily.growth * k := by + by_cases hk : k = 0 + · subst k + simp + · rw [paddedSize, ite_eq_right hk] + exact ExpanderFamily.size_le_mul (Nat.pos_of_ne_zero hk) + +def paddedCloudEquiv (G : ConstraintGraph V E A) (dummy : V → Type*) (v : V) : + Cloud (paddedGraph G dummy) v ≃ Cloud G v ⊕ dummy v where + toFun := by + rintro ⟨e, he⟩ + rcases e with e | ⟨w, d⟩ + · exact Sum.inl ⟨e, he⟩ + · change w = v at he + cases he + exact Sum.inr d + invFun := fun z => match z with + | Sum.inl e => ⟨Sum.inl e.val, e.property⟩ + | Sum.inr d => ⟨Sum.inr ⟨v, d⟩, rfl⟩ + left_inv := by + rintro ⟨e, he⟩ + rcases e with e | ⟨w, d⟩ + · rfl + · change w = v at he + cases he + rfl + right_inv := by + intro z + cases z <;> rfl + +def dartCloudEquiv (G : ConstraintGraph V E A) : E ≃ Σ v : V, Cloud G v where + toFun e := ⟨G.tail e, ⟨e, rfl⟩⟩ + invFun z := z.2.val + left_inv _ := rfl + right_inv := by + rintro ⟨v, ⟨e, he⟩⟩ + cases he + rfl + +variable [Fintype V] [DecidableEq V] [Fintype E] + +theorem sum_card_cloud (G : ConstraintGraph V E A) : + (∑ v, Fintype.card (Cloud G v)) = Fintype.card E := by + simpa only [Fintype.card_sigma] using (Fintype.card_congr (dartCloudEquiv G)).symm + +theorem card_padded_cloud (G : ConstraintGraph V E A) (dummy : V → Type*) + [∀ v, Fintype (dummy v)] (v : V) : + Fintype.card (Cloud (paddedGraph G dummy) v) = + Fintype.card (Cloud G v) + Fintype.card (dummy v) := by + simpa only [Fintype.card_sum] using Fintype.card_congr (paddedCloudEquiv G dummy v) + +abbrev dummy (G : ConstraintGraph V E A) (v : V) := + Fin (paddedSize (Fintype.card (Cloud G v)) - Fintype.card (Cloud G v)) + +theorem card_cloud (G : ConstraintGraph V E A) (v : V) : + Fintype.card (Cloud (paddedGraph G (dummy G)) v) = + paddedSize (Fintype.card (Cloud G v)) := by + rw [card_padded_cloud] + simp only [dummy, Fintype.card_fin] + exact Nat.add_sub_of_le (le_paddedSize _) + +omit [Fintype V] in +theorem card_dummy_of_empty (G : ConstraintGraph V E A) (v : V) + (hk : Fintype.card (Cloud G v) = 0) : Fintype.card (dummy G v) = 0 := by + simp [dummy, hk] + +theorem card_cloud_of_empty (G : ConstraintGraph V E A) (v : V) + (hk : Fintype.card (Cloud G v) = 0) : + Fintype.card (Cloud (paddedGraph G (dummy G)) v) = 0 := by + rw [card_cloud, hk, paddedSize_zero] + +theorem card_cloud_eq_family (G : ConstraintGraph V E A) (v : V) + (hk : 0 < Fintype.card (Cloud G v)) : + Fintype.card (Cloud (paddedGraph G (dummy G)) v) = + Fintype.card (ExpanderFamily.Vertex + (ExpanderFamily.level (Fintype.card (Cloud G v)))) := by + rw [card_cloud, paddedSize_of_pos hk, ExpanderFamily.card_vertex] + rfl + +theorem card_paddedDart_eq_sum (G : ConstraintGraph V E A) : + Fintype.card (PaddedDart G (dummy G)) = + ∑ v, paddedSize (Fintype.card (Cloud G v)) := by + calc + Fintype.card (PaddedDart G (dummy G)) = + ∑ v, Fintype.card (Cloud (paddedGraph G (dummy G)) v) := + (sum_card_cloud (paddedGraph G (dummy G))).symm + _ = ∑ v, paddedSize (Fintype.card (Cloud G v)) := by + apply Finset.sum_congr rfl + intro v _ + exact card_cloud G v + +theorem card_paddedDart_le (G : ConstraintGraph V E A) : + Fintype.card (PaddedDart G (dummy G)) ≤ ExpanderFamily.growth * Fintype.card E := by + rw [card_paddedDart_eq_sum] + calc + (∑ v, paddedSize (Fintype.card (Cloud G v))) ≤ + ∑ v, ExpanderFamily.growth * Fintype.card (Cloud G v) := by + apply Finset.sum_le_sum + intro v _ + exact paddedSize_le_mul _ + _ = ExpanderFamily.growth * Fintype.card E := by + rw [← Finset.mul_sum, sum_card_cloud] + +end MinUncutGames.Foundations.PCP.CloudPadding + +namespace MinUncutGames.Foundations.PCP.PreprocessingCloudIndex + +open scoped BigOperators +open GraphTables DegreeReplacement + +def listEquiv {α : Type*} [BEq α] [LawfulBEq α] (xs : List α) + (nodup : xs.Nodup) (complete : ∀ a, a ∈ xs) : α ≃ Fin xs.length where + toFun a := ⟨xs.idxOf a, List.idxOf_lt_length_of_mem (complete a)⟩ + invFun i := xs.get i + left_inv a := List.idxOf_get _ + right_inv i := by + apply Fin.ext + exact List.get_idxOf nodup i + +@[simp] theorem listEquiv_val {α : Type*} [BEq α] [LawfulBEq α] + (xs : List α) (nodup : xs.Nodup) (complete : ∀ a, a ∈ xs) (a : α) : + (listEquiv xs nodup complete a).val = xs.idxOf a := rfl + +@[simp] theorem listEquiv_symm_apply {α : Type*} [BEq α] [LawfulBEq α] + (xs : List α) (nodup : xs.Nodup) (complete : ∀ a, a ∈ xs) + (i : Fin xs.length) : (listEquiv xs nodup complete).symm i = xs.get i := rfl + +def cloudDarts (t : Table) (v : Fin t.vertices) : List (Fin t.darts) := + (List.finRange t.darts).filter (fun e => decide (t.rows[e].tail = v)) + +@[simp] theorem mem_cloudDarts (t : Table) (v : Fin t.vertices) (e : Fin t.darts) : + e ∈ cloudDarts t v ↔ t.rows[e].tail = v := by + simp [cloudDarts] + +theorem cloudDarts_nodup (t : Table) (v : Fin t.vertices) : + (cloudDarts t v).Nodup := + List.Nodup.filter _ (List.nodup_finRange t.darts) + +theorem cloudDarts_sublist (t : Table) (v : Fin t.vertices) : + (cloudDarts t v).Sublist (List.finRange t.darts) := List.filter_sublist + +def cloudSize (t : Table) (v : Fin t.vertices) : Nat := (cloudDarts t v).length + +theorem cloudSize_le_darts (t : Table) (v : Fin t.vertices) : + cloudSize t v ≤ t.darts := by + simpa only [cloudSize, List.length_finRange] using (cloudDarts_sublist t v).length_le + +def cloudSelect (t : Table) (v : Fin t.vertices) (i : Fin (cloudSize t v)) : + Cloud (semantics t) v := + ⟨(cloudDarts t v).get i, + (mem_cloudDarts t v _).1 (List.get_mem (cloudDarts t v) i)⟩ + +def cloudRank (t : Table) (v : Fin t.vertices) (e : Cloud (semantics t) v) : + Fin (cloudSize t v) := + ⟨(cloudDarts t v).idxOf e.val, + List.idxOf_lt_length_of_mem ((mem_cloudDarts t v e.val).2 e.property)⟩ + +@[simp] theorem cloudSelect_val (t : Table) (v : Fin t.vertices) + (i : Fin (cloudSize t v)) : + (cloudSelect t v i).val = (cloudDarts t v).get i := rfl + +@[simp] theorem cloudRank_val (t : Table) (v : Fin t.vertices) + (e : Cloud (semantics t) v) : + (cloudRank t v e).val = (cloudDarts t v).idxOf e.val := rfl + +@[simp] theorem cloudSelect_cloudRank (t : Table) (v : Fin t.vertices) + (e : Cloud (semantics t) v) : cloudSelect t v (cloudRank t v e) = e := by + apply Subtype.ext + exact List.idxOf_get (cloudRank t v e).isLt + +@[simp] theorem cloudRank_cloudSelect (t : Table) (v : Fin t.vertices) + (i : Fin (cloudSize t v)) : cloudRank t v (cloudSelect t v i) = i := by + apply Fin.ext + exact List.get_idxOf (cloudDarts_nodup t v) i + +def cloudEquiv (t : Table) (v : Fin t.vertices) : + Cloud (semantics t) v ≃ Fin (cloudSize t v) where + toFun := cloudRank t v + invFun := cloudSelect t v + left_inv := cloudSelect_cloudRank t v + right_inv := cloudRank_cloudSelect t v + +theorem cloudSize_eq_card_cloud (t : Table) (v : Fin t.vertices) : + cloudSize t v = Fintype.card (Cloud (semantics t) v) := by + simpa only [Fintype.card_fin] using (Fintype.card_congr (cloudEquiv t v)).symm + +theorem cloudDarts_eq_nil_iff (t : Table) (v : Fin t.vertices) : + cloudDarts t v = [] ↔ ∀ e : Fin t.darts, t.rows[e].tail ≠ v := by + simp only [List.eq_nil_iff_forall_not_mem, mem_cloudDarts] + +theorem cloudSize_eq_zero_iff (t : Table) (v : Fin t.vertices) : + cloudSize t v = 0 ↔ ∀ e : Fin t.darts, t.rows[e].tail ≠ v := by + rw [cloudSize, List.length_eq_zero_iff, cloudDarts_eq_nil_iff] + +theorem sum_cloudSize (t : Table) : (∑ v, cloudSize t v) = t.darts := by + calc + _ = ∑ v, Fintype.card (Cloud (semantics t) v) := by + apply Finset.sum_congr rfl + intro v _ + exact cloudSize_eq_card_cloud t v + _ = Fintype.card (Fin t.darts) := CloudPadding.sum_card_cloud (semantics t) + _ = t.darts := Fintype.card_fin t.darts + +def oldCloudIndex (t : Table) (e : Fin t.darts) : + Fin (cloudSize t t.rows[e].tail) := cloudRank t t.rows[e].tail ⟨e, rfl⟩ + +@[simp] theorem cloudSelect_oldCloudIndex (t : Table) (e : Fin t.darts) : + (cloudSelect t t.rows[e].tail (oldCloudIndex t e)).val = e := + congrArg Subtype.val (cloudSelect_cloudRank t t.rows[e].tail ⟨e, rfl⟩) + +abbrev PaddedCloud (t : Table) (padding : Fin t.vertices → Nat) + (v : Fin t.vertices) := + Cloud (paddedGraph (semantics t) (fun u => Fin (padding u))) v + +def paddedOld (t : Table) (padding : Fin t.vertices → Nat) (v : Fin t.vertices) + (e : Cloud (semantics t) v) : PaddedCloud t padding v := + ⟨Sum.inl e.val, e.property⟩ + +def paddedNew (t : Table) (padding : Fin t.vertices → Nat) (v : Fin t.vertices) + (i : Fin (padding v)) : PaddedCloud t padding v := + ⟨Sum.inr ⟨v, i⟩, rfl⟩ + +def paddedCloudEquiv (t : Table) (padding : Fin t.vertices → Nat) + (v : Fin t.vertices) : PaddedCloud t padding v ≃ Fin (cloudSize t v + padding v) := + (CloudPadding.paddedCloudEquiv (semantics t) (fun u => Fin (padding u)) v).trans + ((Equiv.sumCongr (cloudEquiv t v) (Equiv.refl (Fin (padding v)))).trans + finSumFinEquiv) + +def paddedCloudRank (t : Table) (padding : Fin t.vertices → Nat) (v : Fin t.vertices) : + PaddedCloud t padding v → Fin (cloudSize t v + padding v) := + paddedCloudEquiv t padding v + +def paddedCloudSelect (t : Table) (padding : Fin t.vertices → Nat) (v : Fin t.vertices) : + Fin (cloudSize t v + padding v) → PaddedCloud t padding v := + (paddedCloudEquiv t padding v).symm + +@[simp] theorem paddedCloudSelect_rank (t : Table) (padding : Fin t.vertices → Nat) + (v : Fin t.vertices) (e : PaddedCloud t padding v) : + paddedCloudSelect t padding v (paddedCloudRank t padding v e) = e := + (paddedCloudEquiv t padding v).symm_apply_apply e + +@[simp] theorem paddedCloudRank_select (t : Table) (padding : Fin t.vertices → Nat) + (v : Fin t.vertices) (i : Fin (cloudSize t v + padding v)) : + paddedCloudRank t padding v (paddedCloudSelect t padding v i) = i := + (paddedCloudEquiv t padding v).apply_symm_apply i + +@[simp] theorem paddedCloudRank_old (t : Table) (padding : Fin t.vertices → Nat) + (v : Fin t.vertices) (e : Cloud (semantics t) v) : + paddedCloudRank t padding v (paddedOld t padding v e) = + Fin.castAdd (padding v) (cloudRank t v e) := rfl + +@[simp] theorem paddedCloudRank_new (t : Table) (padding : Fin t.vertices → Nat) + (v : Fin t.vertices) (i : Fin (padding v)) : + paddedCloudRank t padding v (paddedNew t padding v i) = + Fin.natAdd (cloudSize t v) i := rfl + +@[simp] theorem paddedCloudRank_old_val (t : Table) (padding : Fin t.vertices → Nat) + (v : Fin t.vertices) (e : Cloud (semantics t) v) : + (paddedCloudRank t padding v (paddedOld t padding v e)).val = + (cloudRank t v e).val := rfl + +@[simp] theorem paddedCloudRank_new_val (t : Table) (padding : Fin t.vertices → Nat) + (v : Fin t.vertices) (i : Fin (padding v)) : + (paddedCloudRank t padding v (paddedNew t padding v i)).val = + cloudSize t v + i.val := rfl + +@[simp] theorem paddedCloudSelect_castAdd (t : Table) (padding : Fin t.vertices → Nat) + (v : Fin t.vertices) (i : Fin (cloudSize t v)) : + paddedCloudSelect t padding v (Fin.castAdd (padding v) i) = + paddedOld t padding v (cloudSelect t v i) := by + apply (paddedCloudEquiv t padding v).injective + change (paddedCloudEquiv t padding v) + ((paddedCloudEquiv t padding v).symm (Fin.castAdd (padding v) i)) = _ + rw [Equiv.apply_symm_apply] + change Fin.castAdd (padding v) i = + Fin.castAdd (padding v) (cloudRank t v (cloudSelect t v i)) + rw [cloudRank_cloudSelect] + +@[simp] theorem paddedCloudSelect_natAdd (t : Table) (padding : Fin t.vertices → Nat) + (v : Fin t.vertices) (i : Fin (padding v)) : + paddedCloudSelect t padding v (Fin.natAdd (cloudSize t v) i) = + paddedNew t padding v i := + (paddedCloudEquiv t padding v).symm_apply_apply (paddedNew t padding v i) + +theorem card_paddedCloud (t : Table) (padding : Fin t.vertices → Nat) + (v : Fin t.vertices) : + Fintype.card (PaddedCloud t padding v) = cloudSize t v + padding v := by + simpa only [Fintype.card_fin] using Fintype.card_congr (paddedCloudEquiv t padding v) + +end MinUncutGames.Foundations.PCP.PreprocessingCloudIndex + +namespace MinUncutGames.Foundations.PCP.ExpanderTables + +open PoweringWalks SpectralReturn + +def rowIndex (v d : Nat) : Fin v × Fin d ≃ Fin (v * d) := finProdFinEquiv + +theorem rowIndex_val (v d : Nat) (x : Fin v × Fin d) : + (rowIndex v d x).val = x.2.val + d * x.1.val := rfl + +structure Table (v d : Nat) where + rows : Vector (Fin (v * d)) (v * d) + involutive : Function.Involutive (fun i : Fin (v * d) => rows[i]) + +def reverseIndex {v d : Nat} (table : Table v d) (i : Fin (v * d)) : Fin (v * d) := + table.rows[i] + +def lookup {v d : Nat} (table : Table v d) (x : Fin v × Fin d) : Fin v × Fin d := + (rowIndex v d).symm (reverseIndex table (rowIndex v d x)) + +theorem lookup_involutive {v d : Nat} (table : Table v d) : + Function.Involutive (lookup table) := by + intro x + simp only [lookup, Equiv.apply_symm_apply] + exact (congrArg (rowIndex v d).symm (table.involutive (rowIndex v d x))).trans + ((rowIndex v d).symm_apply_apply x) + +def graph {v d : Nat} (table : Table v d) : PortGraph (Fin v) (Fin d) where + rot := ZigzagGraphs.involutionEquiv (lookup table) (lookup_involutive table) + rot_involutive := lookup_involutive table + +@[simp] theorem graph_rot {v d : Nat} (table : Table v d) (x : Fin v × Fin d) : + (graph table).rot x = lookup table x := rfl + +def ofGraph {v d : Nat} (G : PortGraph (Fin v) (Fin d)) : Table v d where + rows := Vector.ofFn (fun i => rowIndex v d (G.rot ((rowIndex v d).symm i))) + involutive := by + intro i + simp only [Fin.getElem_fin, Vector.getElem_ofFn, Fin.eta, Equiv.symm_apply_apply] + exact (congrArg (rowIndex v d) (G.rot_involutive ((rowIndex v d).symm i))).trans + ((rowIndex v d).apply_symm_apply i) + +@[simp] theorem lookup_ofGraph {v d : Nat} (G : PortGraph (Fin v) (Fin d)) + (x : Fin v × Fin d) : lookup (ofGraph G) x = G.rot x := by + simp only [lookup, reverseIndex, ofGraph, Fin.getElem_fin, Vector.getElem_ofFn, Fin.eta, + Equiv.symm_apply_apply] + +private theorem graph_ext {V D : Type*} {G H : PortGraph V D} + (h : ∀ x, G.rot x = H.rot x) : G = H := by + have hr : G.rot = H.rot := Equiv.ext h + cases G + cases H + cases hr + rfl + +@[simp] theorem graph_ofGraph {v d : Nat} (G : PortGraph (Fin v) (Fin d)) : + graph (ofGraph G) = G := graph_ext (lookup_ofGraph G) + +theorem row_count {v d : Nat} (table : Table v d) : table.rows.toList.length = v * d := by + simp + +def vertexIndex (v q : Nat) : Fin v × (Fin q × Fin q) ≃ Fin (v * (q * q)) := + (Equiv.prodCongr (Equiv.refl _) (rowIndex q q)).trans (rowIndex v (q * q)) + +def stepGraph {v d : Nat} (G : Table v (d * d)) + (H : Table ((d * d) * (d * d)) d) : + PortGraph (Fin (v * ((d * d) * (d * d)))) (Fin (d * d)) := + GraphTransport.reindex + (ZigzagGraphs.zigzag (ZigzagGraphs.square (graph G)) + (GraphTransport.reindex (graph H) (rowIndex (d * d) (d * d)).symm (Equiv.refl _))) + (vertexIndex v (d * d)) (rowIndex d d) + +def step {v d : Nat} (G : Table v (d * d)) + (H : Table ((d * d) * (d * d)) d) : + Table (v * ((d * d) * (d * d))) (d * d) := ofGraph (stepGraph G H) + +def stepLookup {v d : Nat} (G : Table v (d * d)) + (H : Table ((d * d) * (d * d)) d) + (x : Fin (v * ((d * d) * (d * d))) × Fin (d * d)) : + Fin (v * ((d * d) * (d * d))) × Fin (d * d) := + let vc := (rowIndex v ((d * d) * (d * d))).symm x.1 + let ports := (rowIndex d d).symm x.2 + let first := lookup H (vc.2, ports.1) + let squarePorts := (rowIndex (d * d) (d * d)).symm first.1 + let outerFirst := lookup G (vc.1, squarePorts.1) + let outerSecond := lookup G (outerFirst.1, squarePorts.2) + let last := lookup H (rowIndex (d * d) (d * d) (outerSecond.2, outerFirst.2), ports.2) + (rowIndex v ((d * d) * (d * d)) (outerSecond.1, last.1), + rowIndex d d (last.2, first.2)) + +theorem lookup_step {v d : Nat} (G : Table v (d * d)) + (H : Table ((d * d) * (d * d)) d) + (x : Fin (v * ((d * d) * (d * d))) × Fin (d * d)) : + lookup (step G H) x = stepLookup G H x := by + simp [step, stepGraph, GraphTransport.reindex, + Equiv.trans_apply, Equiv.prodCongr_apply, + Equiv.prodCongr_symm, Equiv.refl_apply, vertexIndex, Equiv.apply_symm_apply, + ZigzagGraphs.zigzag, ZigzagGraphs.square, ZigzagGraphs.involutionEquiv, + ZigzagGraphs.cloudFirst, ZigzagGraphs.crossCloud, graph_rot, + stepLookup, Prod.map, Equiv.symm_symm] + all_goals repeat' constructor + +theorem step_certificate {v d : Nat} [NeZero v] [NeZero d] + (G : Table v (d * d)) (H : Table ((d * d) * (d * d)) d) + (hG : SpectralCertificate (graph G) (1 / 2 : ℝ)) + (hH : SpectralCertificate (graph H) (1 / 100 : ℝ)) : + SpectralCertificate (graph (step G H)) (1 / 2 : ℝ) := by + rw [step, graph_ofGraph] + apply GraphTransport.reindex_spectralCertificate + apply ZigzagSpectral.square_zigzag_halfCertificate + · exact hG + · exact GraphTransport.reindex_spectralCertificate _ _ _ _ hH + +def initial (d : Nat) : Table 1 (d * d) := + ofGraph { rot := Equiv.refl _, rot_involutive := fun _ => rfl } + +theorem initial_certificate (d : Nat) : + SpectralCertificate (graph (initial d)) (1 / 2 : ℝ) := by + refine ⟨by norm_num, by norm_num, ?_⟩ + intro f hf + have hfun : f = fun _ => f 0 := funext (fun x => congrArg f (Subsingleton.elim x 0)) + have hm : mean f = f 0 := (congrArg mean hfun).trans (mean_const _) + have hz : f 0 = 0 := hm.symm.trans hf + rw [hfun, hz] + simp [energy, mean, averagingOperator] + +def vertexCount (q : Nat) : Nat → Nat + | 0 => 1 + | n + 1 => vertexCount q n * (q * q) + +theorem vertexCount_eq (q n : Nat) : vertexCount q n = (q * q) ^ n := by + induction n with + | zero => rfl + | succ n ih => simp only [vertexCount, ih, pow_succ] + +theorem vertexCount_positive {q : Nat} (hq : 0 < q) (n : Nat) : + 0 < vertexCount q n := by + rw [vertexCount_eq] + exact Nat.pow_pos (Nat.mul_pos hq hq) + +def family {d : Nat} (H : Table ((d * d) * (d * d)) d) : + (n : Nat) → Table (vertexCount (d * d) n) (d * d) + | 0 => initial d + | n + 1 => step (family H n) H + +theorem family_certificate {d : Nat} [NeZero d] + (H : Table ((d * d) * (d * d)) d) + (hH : SpectralCertificate (graph H) (1 / 100 : ℝ)) (n : Nat) : + SpectralCertificate (graph (family H n)) (1 / 2 : ℝ) := by + induction n with + | zero => exact initial_certificate d + | succ n ih => + let : NeZero (vertexCount (d * d) n) := + ⟨Nat.ne_of_gt (vertexCount_positive (Nat.mul_pos (NeZero.pos d) (NeZero.pos d)) n)⟩ + exact step_certificate _ _ ih hH + +theorem family_row_count {d : Nat} (H : Table ((d * d) * (d * d)) d) (n : Nat) : + (family H n).rows.toList.length = ((d * d) * (d * d)) ^ n * (d * d) := by + rw [row_count, vertexCount_eq] + +theorem exists_base_table : ∃ H : Table + ((Expanders.baseDegree * Expanders.baseDegree) * + (Expanders.baseDegree * Expanders.baseDegree)) Expanders.baseDegree, + SpectralCertificate (graph H) (1 / 100 : ℝ) := by + classical + have hv : Fintype.card ExpanderFamily.CloudPort = + (Expanders.baseDegree * Expanders.baseDegree) * + (Expanders.baseDegree * Expanders.baseDegree) := by + rw [ExpanderFamily.card_cloudPort] + unfold ExpanderFamily.growth + ring + let vertices := Fintype.equivFinOfCardEq hv + let ports := Fintype.equivFinOfCardEq Expanders.card_basePort + let G := GraphTransport.reindex ExpanderFamily.baseOnCloud vertices ports + refine ⟨ofGraph G, ?_⟩ + rw [graph_ofGraph] + exact GraphTransport.reindex_spectralCertificate _ _ _ _ + ExpanderFamily.baseOnCloud_certificate + +end MinUncutGames.Foundations.PCP.ExpanderTables + +namespace MinUncutGames.Foundations.PCP.PreprocessingLevels + +def levelLoop (g k : Nat) : Nat → Nat → Nat → Nat × Nat + | 0, e, s => (e, s) + | fuel + 1, e, s => + if k ≤ s then (e, s) + else levelLoop g k fuel (e + 1) (s * g) + +theorem levelLoop_level_le (g k fuel e s : Nat) : + (levelLoop g k fuel e s).1 ≤ e + fuel := by + induction fuel generalizing e s with + | zero => simp only [levelLoop, Nat.add_zero, le_refl] + | succ fuel ih => + simp only [levelLoop] + split + · omega + · have h := ih (e + 1) (s * g) + omega + +theorem levelLoop_power (g k fuel e : Nat) : + (levelLoop g k fuel e (g ^ e)).2 = + g ^ (levelLoop g k fuel e (g ^ e)).1 := by + induction fuel generalizing e with + | zero => rfl + | succ fuel ih => + simp only [levelLoop] + split + · rfl + · simpa only [pow_succ] using ih (e + 1) + +theorem levelLoop_covers (g k fuel e s : Nat) (hg : 1 < g) + (hs : 0 < s) (hbudget : k ≤ s + fuel) : + k ≤ (levelLoop g k fuel e s).2 := by + induction fuel generalizing e s with + | zero => simpa only [levelLoop, Nat.add_zero] using hbudget + | succ fuel ih => + simp only [levelLoop] + split + · assumption + · apply ih + · exact Nat.mul_pos hs (by omega) + · have htwo : 2 ≤ g := by omega + have hmul : s * 2 ≤ s * g := Nat.mul_le_mul_left s htwo + omega + +theorem levelLoop_le_of_covering_power (g k fuel e j : Nat) + (he : e ≤ j) (hj : k ≤ g ^ j) : + (levelLoop g k fuel e (g ^ e)).1 ≤ j := by + induction fuel generalizing e with + | zero => exact he + | succ fuel ih => + simp only [levelLoop] + split + · exact he + · rename_i hnot + have hne : e ≠ j := by + intro h + subst e + exact hnot hj + have hnext : e + 1 ≤ j := by omega + simpa only [pow_succ] using ih (e + 1) hnext + +def searchResult (k : Nat) : Nat × Nat := + levelLoop ExpanderFamily.growth k k 0 1 + +def boundedLevel (k : Nat) : Nat := (searchResult k).1 + +def paddedSize (k : Nat) : Nat := (searchResult k).2 + +@[simp] theorem boundedLevel_zero : boundedLevel 0 = 0 := rfl + +@[simp] theorem paddedSize_zero : paddedSize 0 = 1 := rfl + +theorem boundedLevel_le_input (k : Nat) : boundedLevel k ≤ k := by + simpa only [boundedLevel, searchResult, Nat.zero_add] using + levelLoop_level_le ExpanderFamily.growth k k 0 1 + +theorem paddedSize_power (k : Nat) : + paddedSize k = ExpanderFamily.growth ^ boundedLevel k := by + simpa only [paddedSize, boundedLevel, searchResult, pow_zero] using + levelLoop_power ExpanderFamily.growth k k 0 + +theorem le_paddedSize (k : Nat) : k ≤ paddedSize k := by + exact levelLoop_covers ExpanderFamily.growth k k 0 1 + ExpanderFamily.growth_gt_one (by omega) (by omega) + +theorem boundedLevel_eq_level (k : Nat) : + boundedLevel k = ExpanderFamily.level k := by + apply Nat.le_antisymm + · simpa only [boundedLevel, searchResult, pow_zero] using + levelLoop_le_of_covering_power ExpanderFamily.growth k k 0 + (ExpanderFamily.level k) (Nat.zero_le _) (ExpanderFamily.le_size k) + · apply (Nat.clog_le_iff_le_pow ExpanderFamily.growth_gt_one).2 + rw [← paddedSize_power] + exact le_paddedSize k + +theorem paddedSize_eq_size (k : Nat) : paddedSize k = ExpanderFamily.size k := by + rw [paddedSize_power, boundedLevel_eq_level] + rfl + +theorem boundedLevel_le_of_le_power {k j : Nat} + (h : k ≤ ExpanderFamily.growth ^ j) : boundedLevel k ≤ j := by + rw [boundedLevel_eq_level] + exact (Nat.clog_le_iff_le_pow ExpanderFamily.growth_gt_one).2 h + +theorem paddedSize_positive (k : Nat) : 0 < paddedSize k := by + rw [paddedSize_power] + exact Nat.pow_pos (by have h := ExpanderFamily.growth_gt_one; omega) + +theorem paddedSize_bounds {k : Nat} (hk : 0 < k) : + k ≤ paddedSize k ∧ paddedSize k ≤ ExpanderFamily.growth * k := by + rw [paddedSize_eq_size] + exact ⟨ExpanderFamily.le_size k, ExpanderFamily.size_le_mul hk⟩ + +def cloudPaddedSize (k : Nat) : Nat := if k = 0 then 0 else paddedSize k + +@[simp] theorem cloudPaddedSize_zero : cloudPaddedSize 0 = 0 := rfl + +theorem cloudPaddedSize_of_pos {k : Nat} (hk : 0 < k) : + cloudPaddedSize k = paddedSize k := by + simp only [cloudPaddedSize, Nat.ne_of_gt hk, ite_false] + +theorem cloudPaddedSize_bounds (k : Nat) : + k ≤ cloudPaddedSize k ∧ cloudPaddedSize k ≤ ExpanderFamily.growth * k := by + by_cases hk : k = 0 + · subst k + simp only [cloudPaddedSize_zero, Nat.mul_zero, le_refl, and_self] + · rw [cloudPaddedSize_of_pos (Nat.pos_of_ne_zero hk)] + exact paddedSize_bounds (Nat.pos_of_ne_zero hk) + +theorem table_vertexCount_eq_paddedSize (k : Nat) : + ExpanderTables.vertexCount (Expanders.baseDegree * Expanders.baseDegree) + (boundedLevel k) = paddedSize k := by + rw [ExpanderTables.vertexCount_eq] + have hg : (Expanders.baseDegree * Expanders.baseDegree) * + (Expanders.baseDegree * Expanders.baseDegree) = ExpanderFamily.growth := by + unfold ExpanderFamily.growth + ring + rw [hg] + exact (paddedSize_power k).symm + +theorem family_row_count_at_size + (H : ExpanderTables.Table + ((Expanders.baseDegree * Expanders.baseDegree) * + (Expanders.baseDegree * Expanders.baseDegree)) Expanders.baseDegree) + (k : Nat) : + (ExpanderTables.family H (boundedLevel k)).rows.toList.length = + paddedSize k * (Expanders.baseDegree * Expanders.baseDegree) := by + rw [ExpanderTables.row_count, table_vertexCount_eq_paddedSize] + +end MinUncutGames.Foundations.PCP.PreprocessingLevels + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/ExpanderRowControl.lean b/lean/OAI/Computability/MinUncut/PCP/ExpanderRowControl.lean new file mode 100644 index 0000000000000000000000000000000000000000..c016e0bacf3f2d12a84e3b79b6dce8524edcb461 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/ExpanderRowControl.lean @@ -0,0 +1,250 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.ExpanderFamily + +namespace OAI + +section +namespace MinUncutGames.Foundations.PCP.ExpanderRowControl + +open ExpanderTables + +abbrev degree (d : Nat) : Nat := d * d +abbrev cloudSize (d : Nat) : Nat := degree d * degree d +abbrev rowFactor (d : Nat) : Nat := cloudSize d * degree d + +structure Control (d : Nat) where + firstH : Fin (cloudSize d) × Fin d + lastInput : Fin d + firstG : Fin (degree d) + secondG : Fin (degree d) + lastH : Fin (cloudSize d) × Fin d + deriving DecidableEq, Fintype + +def squarePorts {d : Nat} (s : Control d) : Fin (degree d) × Fin (degree d) := + (rowIndex (degree d) (degree d)).symm s.firstH.1 + +def start {d : Nat} (H : Table (cloudSize d) d) + (cloud : Fin (cloudSize d)) (port : Fin (degree d)) : Control d := + let ports := (rowIndex d d).symm port + let first := lookup H (cloud, ports.1) + let square := (rowIndex (degree d) (degree d)).symm first.1 + { firstH := first + lastInput := ports.2 + firstG := square.1 + secondG := square.2 + lastH := first } + +def receiveFirst {d : Nat} (s : Control d) (returnedPort : Fin (degree d)) : Control d := + { s with firstG := returnedPort } + +def receiveSecond {d : Nat} (H : Table (cloudSize d) d) + (s : Control d) (returnedPort : Fin (degree d)) : Control d := + { s with + secondG := returnedPort + lastH := lookup H + (rowIndex (degree d) (degree d) (returnedPort,s.firstG),s.lastInput) } + +def firstOffset {d : Nat} (s : Control d) : Fin (degree d) := (squarePorts s).1 +def secondOffset {d : Nat} (s : Control d) : Fin (degree d) := (squarePorts s).2 + +def outputPort {d : Nat} (s : Control d) : Fin (degree d) := + rowIndex d d (s.lastH.2,s.firstH.2) + +def outputOffset {d : Nat} (s : Control d) : Fin (rowFactor d) := + rowIndex (cloudSize d) (degree d) (s.lastH.1,outputPort s) + +def firstAddress {d : Nat} (vertex : Nat) (s : Control d) : Nat := + degree d * vertex + (firstOffset s).val + +def secondAddress {d : Nat} (vertex : Nat) (s : Control d) : Nat := + degree d * vertex + (secondOffset s).val + +def outputAddress {d : Nat} (vertex : Nat) (s : Control d) : Nat := + rowFactor d * vertex + (outputOffset s).val + +@[simp] theorem firstOffset_receiveFirst {d : Nat} (s : Control d) (r : Fin (degree d)) : + firstOffset (receiveFirst s r) = firstOffset s := rfl + +@[simp] theorem secondOffset_receiveFirst {d : Nat} (s : Control d) (r : Fin (degree d)) : + secondOffset (receiveFirst s r) = secondOffset s := rfl + +@[simp] theorem receiveFirst_port {d : Nat} (s : Control d) (r : Fin (degree d)) : + (receiveFirst s r).firstG = r := rfl + +@[simp] theorem receiveSecond_port {d : Nat} (H : Table (cloudSize d) d) + (s : Control d) (r : Fin (degree d)) : (receiveSecond H s r).secondG = r := rfl + +theorem firstAddress_eq_rowIndex {v d : Nat} (vertex : Fin v) (s : Control d) : + firstAddress vertex.val s = + (rowIndex v (degree d) (vertex,firstOffset s)).val := by + rw [rowIndex_val] + exact Nat.add_comm _ _ + +theorem secondAddress_eq_rowIndex {v d : Nat} (vertex : Fin v) (s : Control d) : + secondAddress vertex.val s = + (rowIndex v (degree d) (vertex,secondOffset s)).val := by + rw [rowIndex_val] + exact Nat.add_comm _ _ + +theorem firstAddress_lt {v d : Nat} (vertex : Fin v) (s : Control d) : + firstAddress vertex.val s < v * degree d := by + rw [firstAddress_eq_rowIndex] + exact (rowIndex v (degree d) (vertex,firstOffset s)).isLt + +theorem secondAddress_lt {v d : Nat} (vertex : Fin v) (s : Control d) : + secondAddress vertex.val s < v * degree d := by + rw [secondAddress_eq_rowIndex] + exact (rowIndex v (degree d) (vertex,secondOffset s)).isLt + +theorem lookup_vertex_div {v q : Nat} (G : Table v q) (x : Fin v × Fin q) : + (lookup G x).1.val = (reverseIndex G (rowIndex v q x)).val / q := rfl + +theorem lookup_port_mod {v q : Nat} (G : Table v q) (x : Fin v × Fin q) : + (lookup G x).2.val = (reverseIndex G (rowIndex v q x)).val % q := rfl + +theorem lookup_port_eq_remainder {v q : Nat} (G : Table v q) (x : Fin v × Fin q) + (r : Fin q) (hr : r.val = (reverseIndex G (rowIndex v q x)).val % q) : + (lookup G x).2 = r := Fin.ext ((lookup_port_mod G x).trans hr.symm) + +theorem rowIndex_lookup {v q : Nat} (G : Table v q) (x : Fin v × Fin q) : + rowIndex v q (lookup G x) = reverseIndex G (rowIndex v q x) := by + simp only [lookup, Equiv.apply_symm_apply] + +def outputPair {v d : Nat} (vertex : Fin v) (s : Control d) : + Fin (v * cloudSize d) × Fin (degree d) := + (rowIndex v (cloudSize d) (vertex,s.lastH.1),outputPort s) + +theorem outputAddress_eq_rowIndex {v d : Nat} (vertex : Fin v) (s : Control d) : + outputAddress vertex.val s = + (rowIndex (v * cloudSize d) (degree d) (outputPair vertex s)).val := by + simp only [outputAddress, outputOffset, outputPair, rowIndex_val, rowFactor] + ring + +theorem outputAddress_lt {v d : Nat} (vertex : Fin v) (s : Control d) : + outputAddress vertex.val s < (v * cloudSize d) * degree d := by + rw [outputAddress_eq_rowIndex] + exact (rowIndex (v * cloudSize d) (degree d) (outputPair vertex s)).isLt + +def evaluateRow {v d : Nat} (G : Table v (degree d)) (H : Table (cloudSize d) d) + (vertex : Fin v) (cloud : Fin (cloudSize d)) (port : Fin (degree d)) : + Fin v × Control d := + let s₀ := start H cloud port + let g₁ := lookup G (vertex,firstOffset s₀) + let s₁ := receiveFirst s₀ g₁.2 + let g₂ := lookup G (g₁.1,secondOffset s₁) + (g₂.1, receiveSecond H s₁ g₂.2) + +theorem evaluateRow_eq_lookup_step {v d : Nat} + (G : Table v (degree d)) (H : Table (cloudSize d) d) + (vertex : Fin v) (cloud : Fin (cloudSize d)) (port : Fin (degree d)) : + outputPair (evaluateRow G H vertex cloud port).1 (evaluateRow G H vertex cloud port).2 = + lookup (step G H) (rowIndex v (cloudSize d) (vertex,cloud),port) := by + rw [lookup_step] + simp only [evaluateRow, start, receiveFirst, receiveSecond, firstOffset, secondOffset, + squarePorts, outputPair, outputPort, stepLookup, Equiv.symm_apply_apply] + +theorem outputAddress_eq_step_row {v d : Nat} + (G : Table v (degree d)) (H : Table (cloudSize d) d) + (vertex : Fin v) (cloud : Fin (cloudSize d)) (port : Fin (degree d)) : + outputAddress (evaluateRow G H vertex cloud port).1.val (evaluateRow G H vertex cloud port).2 = + (rowIndex (v * cloudSize d) (degree d) + (lookup (step G H) (rowIndex v (cloudSize d) (vertex,cloud),port))).val := by + rw [outputAddress_eq_rowIndex, evaluateRow_eq_lookup_step] + +theorem outputAddress_eq_step_reverseIndex {v d : Nat} + (G : Table v (degree d)) (H : Table (cloudSize d) d) + (vertex : Fin v) (cloud : Fin (cloudSize d)) (port : Fin (degree d)) : + outputAddress (evaluateRow G H vertex cloud port).1.val (evaluateRow G H vertex cloud port).2 = + (reverseIndex (step G H) (rowIndex (v * cloudSize d) (degree d) + (rowIndex v (cloudSize d) (vertex,cloud),port))).val := by + rw [outputAddress_eq_step_row, rowIndex_lookup] + +end MinUncutGames.Foundations.PCP.ExpanderRowControl + +end +section +namespace MinUncutGames.Foundations.PCP.ExpanderTableWords + +open ExpanderTables +open MinUncutGames.Foundations.Complexity (encodeWords decodeWords) + +variable {v d : ℕ} + +def rotationWords (table : Table v d) : List Nat := table.rows.toList.map Fin.val + +@[simp] theorem rotationWords_length (table : Table v d) : + (rotationWords table).length = v * d := by + simp [rotationWords] + +theorem rotationWords_getElem (table : Table v d) (i : ℕ) (hi : i < v * d) : + (rotationWords table)[i]'(by simpa only [rotationWords_length] using hi) = + (reverseIndex table ⟨i, hi⟩).val := by + simp only [rotationWords, List.getElem_map, Vector.getElem_toList, + reverseIndex, Fin.getElem_fin] + +theorem rotationWords_get (table : Table v d) (i : Fin (v * d)) : + (rotationWords table).get + ⟨i.val, by simpa only [rotationWords_length] using i.isLt⟩ = + (reverseIndex table i).val := by + simpa only [List.get_eq_getElem] using rotationWords_getElem table i.val i.isLt + +theorem rotationWords_getElem? (table : Table v d) (i : Fin (v * d)) : + (rotationWords table)[i.val]? = some (reverseIndex table i).val := by + apply List.getElem?_eq_some_iff.mpr + exact ⟨by simpa only [rotationWords_length] using i.isLt, + rotationWords_getElem table i.val i.isLt⟩ + +theorem rotationWords_getElem?_none (table : Table v d) (i : ℕ) (hi : v * d ≤ i) : + (rotationWords table)[i]? = none := + List.getElem?_eq_none (by simpa only [rotationWords_length] using hi) + +theorem rotationWords_entry_lt (table : Table v d) (n : ℕ) + (hn : n ∈ rotationWords table) : n < v * d := by + obtain ⟨a, _, rfl⟩ := List.mem_map.mp hn + exact a.isLt + +theorem rotationWords_lookup (table : Table v d) (x : Fin v × Fin d) : + (rotationWords table)[(rowIndex v d x).val]? = + some (rowIndex v d (lookup table x)).val := by + simpa only [lookup, Equiv.apply_symm_apply] using + rotationWords_getElem? table (rowIndex v d x) + +theorem rotationWords_row_order (table : Table v d) (x : Fin v × Fin d) : + (rotationWords table)[x.2.val + d * x.1.val]? = + some ((lookup table x).2.val + d * (lookup table x).1.val) := by + simpa only [rowIndex_val] using rotationWords_lookup table x + +@[simp] theorem decode_rotationWords (table : Table v d) : + decodeWords (encodeWords (rotationWords table)) = some (rotationWords table) := + Complexity.decodeWords_encodeWords _ + +theorem decoded_lookup (table : Table v d) (i : Fin (v * d)) : + (decodeWords (encodeWords (rotationWords table))).bind (fun words => words[i.val]?) = + some (reverseIndex table i).val := by + rw [decode_rotationWords] + exact rotationWords_getElem? table i + +theorem decoded_coordinate_lookup (table : Table v d) (x : Fin v × Fin d) : + (decodeWords (encodeWords (rotationWords table))).bind + (fun words => words[x.2.val + d * x.1.val]?) = + some ((lookup table x).2.val + d * (lookup table x).1.val) := by + rw [decode_rotationWords] + exact rotationWords_row_order table x + +theorem encode_rotationWords_length_eq (table : Table v d) : + (encodeWords (rotationWords table)).length = (rotationWords table).sum + v * d := by + rw [Complexity.encodeWords_length, rotationWords_length] + +theorem encode_rotationWords_length_le (table : Table v d) : + (encodeWords (rotationWords table)).length ≤ (v * d) * (v * d + 1) := by + calc + _ ≤ (rotationWords table).length * (v * d + 1) := + Complexity.encodeWords_length_le _ _ + (fun n hn => (rotationWords_entry_lt table n hn).le) + _ = _ := by rw [rotationWords_length] + +end MinUncutGames.Foundations.PCP.ExpanderTableWords + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/ExpanderTableEnumeration.lean b/lean/OAI/Computability/MinUncut/PCP/ExpanderTableEnumeration.lean new file mode 100644 index 0000000000000000000000000000000000000000..2347ee7ad4057555048d61b5cbe7b0f9538bec6e --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/ExpanderTableEnumeration.lean @@ -0,0 +1,206 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.ExpanderRowControl + +namespace OAI + +section +namespace MinUncutGames.Foundations.PCP.ExpanderTableEnumeration + +open ExpanderTables ExpanderRowControl ExpanderTableWords +open MinUncutGames.Foundations.Complexity + +variable {v d : Nat} + +def globalIndex (vertex : Fin v) (position : Fin (rowFactor d)) : + Fin ((v * cloudSize d) * degree d) := + let pair := (rowIndex (cloudSize d) (degree d)).symm position + rowIndex (v * cloudSize d) (degree d) + (rowIndex v (cloudSize d) (vertex, pair.1), pair.2) + +theorem globalIndex_val (vertex : Fin v) (position : Fin (rowFactor d)) : + (globalIndex vertex position).val = position.val + rowFactor d * vertex.val := by + let pair := (rowIndex (cloudSize d) (degree d)).symm position + have hp := congrArg Fin.val + ((rowIndex (cloudSize d) (degree d)).apply_symm_apply position) + change pair.2.val + degree d * pair.1.val = position.val at hp + change pair.2.val + degree d * (pair.1.val + cloudSize d * vertex.val) = _ + calc + _ = (pair.2.val + degree d * pair.1.val) + rowFactor d * vertex.val := by + dsimp only [rowFactor] + ring + _ = position.val + rowFactor d * vertex.val := by rw [hp] + +def rowValue (G : Table v (degree d)) (H : Table (cloudSize d) d) + (vertex : Fin v) (position : Fin (rowFactor d)) : Nat := + let pair := (rowIndex (cloudSize d) (degree d)).symm position + let result := evaluateRow G H vertex pair.1 pair.2 + outputAddress result.1.val result.2 + +theorem rowValue_eq_reverseIndex (G : Table v (degree d)) (H : Table (cloudSize d) d) + (vertex : Fin v) (position : Fin (rowFactor d)) : + rowValue G H vertex position = (reverseIndex (step G H) (globalIndex vertex position)).val := by + exact outputAddress_eq_step_reverseIndex G H vertex + ((rowIndex (cloudSize d) (degree d)).symm position).1 + ((rowIndex (cloudSize d) (degree d)).symm position).2 + +def vertexWords (G : Table v (degree d)) (H : Table (cloudSize d) d) (vertex : Fin v) : + List Nat := List.ofFn (rowValue G H vertex) + +def generatedWords (G : Table v (degree d)) (H : Table (cloudSize d) d) : List Nat := + (List.ofFn (vertexWords G H)).flatten + +@[simp] theorem vertexWords_length (G : Table v (degree d)) (H : Table (cloudSize d) d) + (vertex : Fin v) : (vertexWords G H vertex).length = rowFactor d := by + simp [vertexWords] + +theorem vertexWords_drop_succ (G : Table v (degree d)) (H : Table (cloudSize d) d) + (vertex : Fin v) (position : Fin (rowFactor d)) : + (vertexWords G H vertex).drop position.val = + rowValue G H vertex position :: (vertexWords G H vertex).drop (position.val + 1) := by + rw [List.drop_eq_getElem_cons (by simp)] + simp [vertexWords] + +@[simp] theorem vertexWords_drop_full (G : Table v (degree d)) (H : Table (cloudSize d) d) + (vertex : Fin v) : (vertexWords G H vertex).drop (rowFactor d) = [] := by + apply List.drop_eq_nil_of_le + simp + +theorem vertexWords_drop_last (G : Table v (degree d)) (H : Table (cloudSize d) d) + (vertex : Fin v) (position : Fin (rowFactor d)) + (last : position.val + 1 = rowFactor d) : + (vertexWords G H vertex).drop position.val = [rowValue G H vertex position] := by + rw [vertexWords_drop_succ, last, vertexWords_drop_full] + +private theorem ofFn_cast {α : Type*} {n m : Nat} (h : n = m) (f : Fin m → α) : + List.ofFn (fun i : Fin n => f (Fin.cast h i)) = List.ofFn f := by + cases h + rfl + +theorem rotationWords_eq_ofFn {n q : Nat} (G : Table n q) : + rotationWords G = List.ofFn (fun i : Fin (n * q) => (reverseIndex G i).val) := by + apply List.ext_getElem + · simp + · intro i hi hj + rw [List.getElem_ofFn] + exact rotationWords_getElem G i (by simpa only [rotationWords_length] using hi) + +theorem rowCount_eq : v * rowFactor d = (v * cloudSize d) * degree d := + (Nat.mul_assoc v (cloudSize d) (degree d)).symm + +theorem generatedWords_eq_flat_ofFn (G : Table v (degree d)) (H : Table (cloudSize d) d) : + generatedWords G H = List.ofFn (fun i : Fin (v * rowFactor d) => + (reverseIndex (step G H) (Fin.cast rowCount_eq i)).val) := by + rw [List.ofFn_mul] + unfold generatedWords vertexWords + apply congrArg List.flatten + apply congrArg List.ofFn + funext vertex + apply congrArg List.ofFn + funext position + rw [rowValue_eq_reverseIndex] + apply congrArg (fun i : Fin ((v * cloudSize d) * degree d) => + (reverseIndex (step G H) i).val) + apply Fin.ext + rw [globalIndex_val] + change position.val + rowFactor d * vertex.val = vertex.val * rowFactor d + position.val + ac_rfl + +theorem generatedWords_eq_rotationWords (G : Table v (degree d)) (H : Table (cloudSize d) d) : + generatedWords G H = rotationWords (step G H) := by + rw [generatedWords_eq_flat_ofFn] + exact (ofFn_cast (rowCount_eq (v := v) (d := d)) + (fun i => (reverseIndex (step G H) i).val)).trans + (rotationWords_eq_ofFn (step G H)).symm + +@[simp] theorem generatedWords_length (G : Table v (degree d)) (H : Table (cloudSize d) d) : + (generatedWords G H).length = v * rowFactor d := by + rw [generatedWords_eq_rotationWords, rotationWords_length] + exact rowCount_eq.symm + +def priorVertices (G : Table v (degree d)) (H : Table (cloudSize d) d) (count : Nat) : + List Nat := ((List.ofFn (vertexWords G H)).take count).flatten + +def prefixRows (G : Table v (degree d)) (H : Table (cloudSize d) d) + (vertex : Fin v) (completedPositions : Nat) : List Nat := + priorVertices G H vertex.val ++ (vertexWords G H vertex).take completedPositions + +@[simp] theorem priorVertices_zero (G : Table v (degree d)) (H : Table (cloudSize d) d) : + priorVertices G H 0 = [] := by simp [priorVertices] + +@[simp] theorem priorVertices_full (G : Table v (degree d)) (H : Table (cloudSize d) d) : + priorVertices G H v = generatedWords G H := by + unfold priorVertices generatedWords + rw [List.take_of_length_le (by simp)] + +theorem priorVertices_succ (G : Table v (degree d)) (H : Table (cloudSize d) d) + (k : Nat) (hk : k < v) : + priorVertices G H (k + 1) = priorVertices G H k ++ vertexWords G H ⟨k, hk⟩ := by + unfold priorVertices + rw [List.take_succ_eq_append_getElem (by simpa using hk), List.flatten_append] + simp + +@[simp] theorem prefixRows_zero (G : Table v (degree d)) (H : Table (cloudSize d) d) + (vertex : Fin v) : prefixRows G H vertex 0 = priorVertices G H vertex.val := by + simp [prefixRows] + +theorem prefixRows_succ (G : Table v (degree d)) (H : Table (cloudSize d) d) + (vertex : Fin v) (r : Nat) (hr : r < rowFactor d) : + prefixRows G H vertex (r + 1) = + prefixRows G H vertex r ++ [rowValue G H vertex ⟨r, hr⟩] := by + unfold prefixRows + rw [List.take_succ_eq_append_getElem (by simpa using hr)] + simp [vertexWords, List.append_assoc] + +theorem prefixRows_complete (G : Table v (degree d)) (H : Table (cloudSize d) d) + (vertex : Fin v) : + prefixRows G H vertex (rowFactor d) = priorVertices G H (vertex.val + 1) := by + rw [prefixRows, List.take_of_length_le (by simp)] + simpa using (priorVertices_succ G H vertex.val vertex.isLt).symm + +def accumulate (values : List Nat) (initial : List Bool) : List Bool := + values.foldl (fun accumulator value => (encodeWord value).reverse ++ accumulator) initial + +theorem accumulate_eq (values : List Nat) (initial : List Bool) : + accumulate values initial = (encodeWords values).reverse ++ initial := by + induction values generalizing initial with + | nil => simp [accumulate, encodeWords] + | cons value values ih => + simpa only [accumulate, List.foldl_cons, encodeWords, List.reverse_append, + List.append_assoc] using ih ((encodeWord value).reverse ++ initial) + +theorem accumulate_append (first second : List Nat) (initial : List Bool) : + accumulate (first ++ second) initial = accumulate second (accumulate first initial) := by + simp only [accumulate, List.foldl_append] + +theorem accumulate_prefixRows_succ (G : Table v (degree d)) (H : Table (cloudSize d) d) + (vertex : Fin v) (r : Nat) (hr : r < rowFactor d) (initial : List Bool) : + accumulate (prefixRows G H vertex (r + 1)) initial = + (encodeWord (rowValue G H vertex ⟨r, hr⟩)).reverse ++ + accumulate (prefixRows G H vertex r) initial := by + rw [prefixRows_succ G H vertex r hr, accumulate_append] + rfl + +theorem accumulate_generatedWords (G : Table v (degree d)) (H : Table (cloudSize d) d) + (initial : List Bool) : + accumulate (generatedWords G H) initial = + (encodeWords (rotationWords (step G H))).reverse ++ initial := by + rw [accumulate_eq, generatedWords_eq_rotationWords] + +theorem encode_generatedWords_length_le (G : Table v (degree d)) (H : Table (cloudSize d) d) : + (encodeWords (generatedWords G H)).length ≤ + (v * rowFactor d) * (v * rowFactor d + 1) := by + rw [generatedWords_eq_rotationWords, rowCount_eq] + exact encode_rotationWords_length_le (step G H) + +theorem accumulate_generatedWords_length_le (G : Table v (degree d)) + (H : Table (cloudSize d) d) (initial : List Bool) : + (accumulate (generatedWords G H) initial).length ≤ + (v * rowFactor d) * (v * rowFactor d + 1) + initial.length := by + rw [accumulate_eq, List.length_append, List.length_reverse] + exact Nat.add_le_add_right (encode_generatedWords_length_le G H) initial.length + +end MinUncutGames.Foundations.PCP.ExpanderTableEnumeration + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/FieldArray.lean b/lean/OAI/Computability/MinUncut/PCP/FieldArray.lean new file mode 100644 index 0000000000000000000000000000000000000000..df813118fffda911ed8bbffcc10063fe5af3a4ea --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/FieldArray.lean @@ -0,0 +1,339 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.Machine + +namespace OAI + +section +namespace MinUncutGames.Foundations.Hastad.SourceFieldArray + +open Turing +open MinUncutGames.Foundations.Complexity SourceMachine + +variable {K Λ σ : Type} [DecidableEq K] + +def finish (source : K) (exit : Option Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) := + .load (fun state => (state.1, none)) (Reduction.MachineTransfer.exitAt source exit) + +theorem finishStep (source : K) (label : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atFinish : program label = finish source exit) + (base : K → List Bool) (ambient : σ) (register : Option Bool) : + TM2.step program ⟨some label, (ambient, register), base⟩ = + some ⟨exit, (ambient, none), base⟩ := by + change some (TM2.stepAux (program label) (ambient, register) base) = _ + rw [atFinish] + cases exit <;> simp [finish, Reduction.MachineTransfer.exitAt, TM2.stepAux] + +def sequenceTapes (source : K) (destination : Nat → K) (base : K → List Bool) + (offset : Nat) (values : List Nat) (suffix : List Bool) : K → List Bool := + match values with + | [] => base + | n :: rest => sequenceTapes source destination + (afterField source (destination offset) base n (encodeWords rest ++ suffix)) + (offset + 1) rest suffix + +theorem sequenceTrace (source : K) (destination : Nat → K) + (start loopLabel : Nat → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (base : K → List Bool) (offset : Nat) (values : List Nat) (suffix : List Bool) + (hsep : ∀ r, r < values.length → source ≠ destination (offset + r)) + (atStart : ∀ r, r < values.length → + program (start (offset + r)) = fieldStart (destination (offset + r)) (loopLabel (offset + r))) + (atLoop : ∀ r, r < values.length → program (loopLabel (offset + r)) = + fieldLoop source (destination (offset + r)) (loopLabel (offset + r)) + (some (start (offset + r + 1)))) + (atDone : program (start (offset + values.length)) = finish source exit) + (hinput : base source = encodeWords values ++ suffix) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[values.sum + 2 * values.length + 1] + (some ⟨some (start offset), (ambient, register), base⟩) = + some ⟨exit, (ambient, none), sequenceTapes source destination base offset values suffix⟩ := by + induction values generalizing offset base register with + | nil => + simpa only [List.sum_nil, List.length_nil, Nat.mul_zero, Nat.zero_add, + Nat.add_zero, Function.iterate_one, MachineComposition.advance_some, sequenceTapes] + using finishStep source (start offset) exit program atDone base ambient register + | cons n rest ih => + have hr0 : 0 < (n :: rest).length := by simp + have hsep0 : source ≠ destination offset := by simpa using hsep 0 hr0 + have hs0 : program (start offset) = fieldStart (destination offset) (loopLabel offset) := by + simpa using atStart 0 hr0 + have hl0 : program (loopLabel offset) = fieldLoop source (destination offset) + (loopLabel offset) (some (start (offset + 1))) := by simpa using atLoop 0 hr0 + have hin : base source = encodeWord n ++ (encodeWords rest ++ suffix) := by + simpa only [encodeWords, List.append_assoc] using hinput + let nextBase := afterField source (destination offset) base n (encodeWords rest ++ suffix) + have hfirst := (fieldInTime source (destination offset) hsep0 (start offset) + (loopLabel offset) (some (start (offset + 1))) program hs0 hl0 base n + (encodeWords rest ++ suffix) hin ambient register).evals_in_steps + change (MachineComposition.advance (TM2.step program))^[n + 2] + (some ⟨some (start offset), (ambient, register), base⟩) = + some ⟨some (start (offset + 1)), (ambient, none), nextBase⟩ at hfirst + have hsep' : ∀ r, r < rest.length → source ≠ destination (offset + 1 + r) := by + intro r hr + simpa [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using hsep (r + 1) (by simp; omega) + have hs' : ∀ r, r < rest.length → program (start (offset + 1 + r)) = + fieldStart (destination (offset + 1 + r)) (loopLabel (offset + 1 + r)) := by + intro r hr + simpa [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using atStart (r + 1) (by simp; omega) + have hl' : ∀ r, r < rest.length → program (loopLabel (offset + 1 + r)) = + fieldLoop source (destination (offset + 1 + r)) (loopLabel (offset + 1 + r)) + (some (start (offset + 1 + r + 1))) := by + intro r hr + simpa [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using atLoop (r + 1) (by simp; omega) + have hd' : program (start (offset + 1 + rest.length)) = finish source exit := by + simpa [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using atDone + have hin' : nextBase source = encodeWords rest ++ suffix := by + simp [nextBase, afterField, hsep0] + rw [show (n :: rest).sum + 2 * (n :: rest).length + 1 = + (rest.sum + 2 * rest.length + 1) + (n + 2) by simp; omega] + rw [Function.iterate_add_apply, hfirst, + ih nextBase (offset + 1) hsep' hs' hl' hd' hin' none] + rfl + +def sequenceInTime (source : K) (destination : Nat → K) + (start loopLabel : Nat → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (base : K → List Bool) (offset : Nat) (values : List Nat) (suffix : List Bool) + (hsep : ∀ r, r < values.length → source ≠ destination (offset + r)) + (atStart : ∀ r, r < values.length → + program (start (offset + r)) = fieldStart (destination (offset + r)) (loopLabel (offset + r))) + (atLoop : ∀ r, r < values.length → program (loopLabel (offset + r)) = + fieldLoop source (destination (offset + r)) (loopLabel (offset + r)) + (some (start (offset + r + 1)))) + (atDone : program (start (offset + values.length)) = finish source exit) + (hinput : base source = encodeWords values ++ suffix) + (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (start offset), (ambient, register), base⟩ + (some ⟨exit, (ambient, none), sequenceTapes source destination base offset values suffix⟩) + (values.sum + 2 * values.length + 1) where + steps := values.sum + 2 * values.length + 1 + evals_in_steps := sequenceTrace source destination start loopLabel exit program base offset + values suffix hsep atStart atLoop atDone hinput ambient register + steps_le_m := Nat.le_refl _ + +theorem sequence_time_eq_length (values : List Nat) : + values.sum + 2 * values.length + 1 = (encodeWords values).length + values.length + 1 := by + rw [encodeWords_length] + omega + +theorem sequenceTapes_other (source : K) (destination : Nat → K) + (p : K) (hpS : p ≠ source) (base : K → List Bool) (offset : Nat) + (values : List Nat) (suffix : List Bool) + (hpD : ∀ r, r < values.length → p ≠ destination (offset + r)) : + sequenceTapes source destination base offset values suffix p = base p := by + induction values generalizing base offset with + | nil => rfl + | cons n rest ih => + have hp0 : p ≠ destination offset := by simpa using hpD 0 (by simp) + have htail : ∀ r, r < rest.length → p ≠ destination (offset + 1 + r) := by + intro r hr + simpa [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using hpD (r + 1) (by simp; omega) + rw [sequenceTapes, ih _ (offset + 1) htail] + exact fieldTapes_other source (destination offset) p hpS hp0 _ _ _ + +theorem sequenceTapes_source (source : K) (destination : Nat → K) + (base : K → List Bool) (offset : Nat) (values : List Nat) (suffix : List Bool) + (hsep : ∀ r, r < values.length → source ≠ destination (offset + r)) + (hinput : base source = encodeWords values ++ suffix) : + sequenceTapes source destination base offset values suffix source = suffix := by + induction values generalizing base offset with + | nil => simpa [sequenceTapes, encodeWords] using hinput + | cons n rest ih => + have hsep0 : source ≠ destination offset := by simpa using hsep 0 (by simp) + have htail : ∀ r, r < rest.length → source ≠ destination (offset + 1 + r) := by + intro r hr + simpa [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using hsep (r + 1) (by simp; omega) + apply ih _ (offset + 1) htail + simp [afterField, hsep0] + +theorem sequenceTapes_selected (source : K) (destination : Nat → K) + (base : K → List Bool) (offset : Nat) (values : List Nat) (suffix : List Bool) + (j : Nat) (hj : j < values.length) + (hsep : ∀ r, r < values.length → source ≠ destination (offset + r)) + (hdist : ∀ r s, r < values.length → s < values.length → + destination (offset + r) = destination (offset + s) → r = s) : + sequenceTapes source destination base offset values suffix (destination (offset + j)) = + encodeWord (values[j]'hj) ++ base (destination (offset + j)) := by + induction values generalizing base offset j with + | nil => simp at hj + | cons n rest ih => + have hsep0 : source ≠ destination offset := by simpa using hsep 0 (by simp) + let nextBase := afterField source (destination offset) base n (encodeWords rest ++ suffix) + cases j with + | zero => + have hframe : ∀ r, r < rest.length → destination offset ≠ destination (offset + 1 + r) := by + intro r hr heq + have hh := hdist 0 (r + 1) (by simp) (by simp; omega) + (by simpa [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using heq) + omega + simp only [sequenceTapes, Nat.add_zero, List.getElem_cons_zero] + rw [sequenceTapes_other source destination (destination offset) hsep0.symm _ + (offset + 1) rest suffix hframe] + simp [afterField] + | succ j => + have hj' : j < rest.length := by simpa using hj + have hsep' : ∀ r, r < rest.length → source ≠ destination (offset + 1 + r) := by + intro r hr + simpa [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using hsep (r + 1) (by simp; omega) + have hdist' : ∀ r s, r < rest.length → s < rest.length → + destination (offset + 1 + r) = destination (offset + 1 + s) → r = s := by + intro r s hr hs heq + have hh := hdist (r + 1) (s + 1) (by simp; omega) (by simp; omega) + (by simpa [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using heq) + omega + have hsrc : destination (offset + 1 + j) ≠ source := (hsep' j hj').symm + have hdst : destination (offset + 1 + j) ≠ destination offset := by + intro heq + have hh := hdist (j + 1) 0 hj (by simp) + (by simpa [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using heq) + omega + have hkeep : nextBase (destination (offset + 1 + j)) = base (destination (offset + 1 + j)) := + fieldTapes_other source (destination offset) _ hsrc hdst _ _ _ + simp only [sequenceTapes, List.getElem_cons_succ] + rw [show offset + (j + 1) = offset + 1 + j by omega] + rw [ih _ (offset + 1) j hj' hsep' hdist'] + exact congrArg (encodeWord rest[j] ++ ·) hkeep + +def boundedIndex (q j : Nat) : Fin (q + 1) := ⟨min j q, by omega⟩ + +@[simp] theorem boundedIndex_val {q j : Nat} (hj : j ≤ q) : + (boundedIndex q j).val = j := Nat.min_eq_left hj + +def destination (q j : Nat) : Fin (q + 1) := boundedIndex q (j + 1) +def startLabel (q j : Nat) : Fin (q + 1) × Bool := (boundedIndex q j, false) +def loopLabel (q j : Nat) : Fin (q + 1) × Bool := (boundedIndex q j, true) + +theorem destination_ne_source (q r : Nat) (hr : r < q) : + (0 : Fin (q + 1)) ≠ destination q r := by + intro heq + have hh := congrArg Fin.val heq + simp only [destination, boundedIndex_val (Nat.succ_le_iff.mpr hr)] at hh + change 0 = r + 1 at hh + omega + +theorem destination_injective_below (q r s : Nat) (hr : r < q) (hs : s < q) + (heq : destination q r = destination q s) : r = s := by + have hh := congrArg Fin.val heq + simp only [destination, boundedIndex_val (Nat.succ_le_iff.mpr hr), + boundedIndex_val (Nat.succ_le_iff.mpr hs)] at hh + omega + +@[simp] theorem destination_eq_succ {q : Nat} (j : Fin q) : destination q j.val = j.succ := by + apply Fin.ext + exact boundedIndex_val (Nat.succ_le_iff.mpr j.isLt) + +theorem output_source (q : Nat) (values : List Nat) (hlen : values.length = q) + (base : Fin (q + 1) → List Bool) (suffix : List Bool) + (hinput : base 0 = encodeWords values ++ suffix) : + sequenceTapes (0 : Fin (q + 1)) (destination q) base 0 values suffix 0 = suffix := by + apply sequenceTapes_source _ _ _ _ _ _ _ hinput + intro r hr + simpa using destination_ne_source q r (by omega) + +theorem output_field (q : Nat) (values : List Nat) (hlen : values.length = q) + (base : Fin (q + 1) → List Bool) (suffix : List Bool) (j : Fin q) : + sequenceTapes (0 : Fin (q + 1)) (destination q) base 0 values suffix j.succ = + encodeWord (values[j.val]'(by omega)) ++ base j.succ := by + have h := sequenceTapes_selected (0 : Fin (q + 1)) (destination q) base 0 values suffix + j.val (by omega) + (by intro r hr; simpa using destination_ne_source q r (by omega)) + (by + intro r s hr hs heq + exact destination_injective_below q r s (by omega) (by omega) + (by simpa only [Nat.zero_add] using heq)) + simpa only [Nat.zero_add, destination_eq_succ] using h + +def program (q : Nat) (label : Fin (q + 1) × Bool) : + TM2.Stmt (fun _ : Fin (q + 1) => Bool) (Fin (q + 1) × Bool) (Unit × Option Bool) := + if label.1.val < q then + if label.2 then + fieldLoop 0 (destination q label.1.val) (label.1, true) + (some (startLabel q (label.1.val + 1))) + else fieldStart (destination q label.1.val) (label.1, true) + else finish 0 none + +def machine (q : Nat) : FinTM2 where + K := Fin (q + 1) + k₀ := 0 + k₁ := 0 + Γ _ := Bool + Λ := Fin (q + 1) × Bool + main := startLabel q 0 + σ := Unit × Option Bool + initialState := ((), none) + m := program q + +theorem atStart (q r : Nat) (hr : r < q) : + program q (startLabel q r) = fieldStart (destination q r) (loopLabel q r) := by + simp [program, startLabel, loopLabel, boundedIndex_val hr.le, hr] + +theorem atLoop (q r : Nat) (hr : r < q) : + program q (loopLabel q r) = fieldLoop (0 : Fin (q + 1)) (destination q r) + (loopLabel q r) (some (startLabel q (r + 1))) := by + simp [program, startLabel, loopLabel, boundedIndex_val hr.le, hr] + +theorem atDone (q : Nat) : program q (startLabel q q) = finish (0 : Fin (q + 1)) none := by + simp [program, startLabel] + +def machineInTime (q : Nat) (values : List Nat) (hlen : values.length = q) + (base : Fin (q + 1) → List Bool) (suffix : List Bool) + (hinput : base 0 = encodeWords values ++ suffix) (register : Option Bool) : + StateTransition.EvalsToInTime (machine q).step + ⟨some (startLabel q 0), ((), register), base⟩ + (some ⟨none, ((), none), sequenceTapes (0 : Fin (q + 1)) (destination q) base 0 values suffix⟩) + (values.sum + 2 * q + 1) := by + have hsep : ∀ r, r < values.length → (0 : Fin (q + 1)) ≠ destination q (0 + r) := by + intro r hr heq + have hr' : r + 1 ≤ q := by omega + have hh := congrArg Fin.val heq + simp only [Nat.zero_add, destination, boundedIndex_val hr'] at hh + change 0 = r + 1 at hh + omega + have hs : ∀ r, r < values.length → program q (startLabel q (0 + r)) = + fieldStart (destination q (0 + r)) (loopLabel q (0 + r)) := by + intro r hr + simpa only [Nat.zero_add] using atStart q r (by omega) + have hl : ∀ r, r < values.length → program q (loopLabel q (0 + r)) = + fieldLoop (0 : Fin (q + 1)) (destination q (0 + r)) (loopLabel q (0 + r)) + (some (startLabel q (0 + r + 1))) := by + intro r hr + simpa only [Nat.zero_add] using atLoop q r (by omega) + have hd : program q (startLabel q (0 + values.length)) = finish (0 : Fin (q + 1)) none := by + simpa [hlen] using atDone q + simpa only [machine, FinTM2.Cfg, FinTM2.step, hlen] using! sequenceInTime (0 : Fin (q + 1)) (destination q) + (startLabel q) (loopLabel q) none (program q) base 0 values suffix hsep hs hl hd hinput () register + +def machineInTime_inputBound (q : Nat) (values : List Nat) (hlen : values.length = q) + (base : Fin (q + 1) → List Bool) (suffix : List Bool) + (hinput : base 0 = encodeWords values ++ suffix) (register : Option Bool) : + StateTransition.EvalsToInTime (machine q).step + ⟨some (startLabel q 0), ((), register), base⟩ + (some ⟨none, ((), none), sequenceTapes (0 : Fin (q + 1)) (destination q) base 0 values suffix⟩) + ((base 0).length + q + 1) := by + let run := machineInTime q values hlen base suffix hinput register + refine { toEvalsTo := run.toEvalsTo, steps_le_m := ?_ } + have hb := run.steps_le_m + have hi : (base 0).length = values.sum + q + suffix.length := by + rw [hinput, List.length_append, encodeWords_length, hlen] + omega + +def sixFieldsInTime (base : Fin 7 → List Bool) (a b c d e f : Nat) (suffix : List Bool) + (hinput : base 0 = encodeWords [a, b, c, d, e, f] ++ suffix) (register : Option Bool) : + StateTransition.EvalsToInTime (machine 6).step + ⟨some (startLabel 6 0), ((), register), base⟩ + (some ⟨none, ((), none), + sequenceTapes (0 : Fin 7) (destination 6) base 0 [a, b, c, d, e, f] suffix⟩) + (a + b + c + d + e + f + 13) := by + have h := machineInTime 6 [a, b, c, d, e, f] rfl base suffix hinput register + convert h using 1 + simp + omega + +end MinUncutGames.Foundations.Hastad.SourceFieldArray + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/FinalBooleanVerifier.lean b/lean/OAI/Computability/MinUncut/PCP/FinalBooleanVerifier.lean new file mode 100644 index 0000000000000000000000000000000000000000..a17e475eaf727aa4ba7cfef55599c77338f3d2f0 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/FinalBooleanVerifier.lean @@ -0,0 +1,246 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.RawInitialTables + +namespace OAI + +section +namespace MinUncutGames.Foundations.PCP.FinalBooleanVerifier + +open Target + +abbrev Label := Fin 6 → Bool + +variable {V E : Type*} {n m : Nat} + +def bitIndex (vertices : V ≃ Fin n) (v : V) (j : Fin 6) : Fin (n * 6) := + finProdFinEquiv (vertices v, j) + +def labelsOfBits (vertices : V ≃ Fin n) (assignment : Fin (n * 6) → Bool) : V → Label := + fun v j => assignment (bitIndex vertices v j) + +def bitsOfLabels (vertices : V ≃ Fin n) (labeling : V → Label) : Fin (n * 6) → Bool := + fun k => + let pair : Fin n × Fin 6 := finProdFinEquiv.symm k + labeling (vertices.symm pair.1) pair.2 + +@[simp] theorem labelsOfBits_bitsOfLabels (vertices : V ≃ Fin n) (labeling : V → Label) : + labelsOfBits vertices (bitsOfLabels vertices labeling) = labeling := by + funext v j + simp only [labelsOfBits, bitsOfLabels, bitIndex, Equiv.symm_apply_apply] + +@[simp] theorem bitsOfLabels_labelsOfBits (vertices : V ≃ Fin n) + (assignment : Fin (n * 6) → Bool) : bitsOfLabels vertices (labelsOfBits vertices assignment) = assignment := by + funext k + simp only [bitsOfLabels, labelsOfBits, bitIndex, Equiv.apply_symm_apply, Prod.eta] + +abbrev verifier (G : ConstraintGraph V E Label) (vertices : V ≃ Fin n) (edges : E ≃ Fin m) : + VerifierToCNF.FiniteVerifier 12 where + «variables» := n * 6 + events := m + query := fun e i => Fin.addCases (motive := fun _ : Fin (6 + 6) => Fin (n * 6)) + (fun j : Fin 6 => bitIndex vertices (G.tail (edges.symm e)) j) + (fun j : Fin 6 => bitIndex vertices (G.head (edges.symm e)) j) i + accepts := fun e bits => G.accepts (edges.symm e) + (fun j => bits (Fin.castAdd 6 j)) (fun j => bits (Fin.natAdd 6 j)) + +theorem query_tail (G : ConstraintGraph V E Label) (vertices : V ≃ Fin n) + (edges : E ≃ Fin m) (e : Fin m) (j : Fin 6) : + (verifier G vertices edges).query e (Fin.castAdd 6 j) = + bitIndex vertices (G.tail (edges.symm e)) j := by + simp only [verifier, Fin.addCases_left] + +theorem query_head (G : ConstraintGraph V E Label) (vertices : V ≃ Fin n) + (edges : E ≃ Fin m) (e : Fin m) (j : Fin 6) : + (verifier G vertices edges).query e (Fin.natAdd 6 j) = + bitIndex vertices (G.head (edges.symm e)) j := by + simp only [verifier, Fin.addCases_right] + +theorem eventValue_eq (G : ConstraintGraph V E Label) (vertices : V ≃ Fin n) + (edges : E ≃ Fin m) (assignment : Fin (n * 6) → Bool) (e : Fin m) : + VerifierToCNF.eventValue (verifier G vertices edges) assignment e = + G.edgeSatisfied (labelsOfBits vertices assignment) (edges.symm e) := by + simp only [VerifierToCNF.eventValue, Fin.addCases_left, Fin.addCases_right, + ConstraintGraph.edgeSatisfied] + rfl + +theorem count_false_map_filter {α : Type*} (xs : List α) (f : α → Bool) : + (xs.map f).count false = (xs.filter (fun x => decide (f x = false))).length := by + induction xs with + | nil => rfl + | cons x xs ih => cases h : f x <;> simp [h, ih, Nat.add_comm] + +theorem count_false_finRange (f : Fin m → Bool) : + ((List.finRange m).map f).count false = + (Finset.univ.filter (fun e : Fin m => f e = false)).card := by + classical + calc + _ = ((List.finRange m).filter (fun e => decide (f e = false))).length := + count_false_map_filter _ _ + _ = (((List.finRange m).filter (fun e => decide (f e = false))).toFinset).card := + (List.toFinset_card_of_nodup ((List.nodup_finRange m).filter _)).symm + _ = _ := by + congr 1 + ext e + simp + +theorem rejection_count_eq [Fintype E] (G : ConstraintGraph V E Label) + (vertices : V ≃ Fin n) (edges : E ≃ Fin m) (assignment : Fin (n * 6) → Bool) : + VerifierToCNF.rejectedEventCount (verifier G vertices edges) assignment = + G.rejectionCount (labelsOfBits vertices assignment) := by + classical + change ((List.finRange m).map + (VerifierToCNF.eventValue (verifier G vertices edges) assignment)).count false = _ + rw [count_false_finRange] + change (Finset.univ.filter (fun e : Fin m => + VerifierToCNF.eventValue (verifier G vertices edges) assignment e = false)).card = + (G.rejectedDarts (labelsOfBits vertices assignment)).card + apply Finset.card_equiv edges.symm + intro e + simp only [Finset.mem_filter, Finset.mem_univ, true_and, + ConstraintGraph.rejectedDarts, eventValue_eq] + +theorem verifier_completeness (G : ConstraintGraph V E Label) (vertices : V ≃ Fin n) + (edges : E ≃ Fin m) (labeling : V → Label) + (satisfied : ∀ e, G.edgeSatisfied labeling e = true) : + ∀ e, VerifierToCNF.eventValue (verifier G vertices edges) + (bitsOfLabels vertices labeling) e = true := by + intro e + rw [eventValue_eq, labelsOfBits_bitsOfLabels] + exact satisfied (edges.symm e) + +theorem verifier_reflects (G : ConstraintGraph V E Label) (vertices : V ≃ Fin n) + (edges : E ≃ Fin m) (assignment : Fin (n * 6) → Bool) + (accepted : ∀ e, VerifierToCNF.eventValue (verifier G vertices edges) assignment e = true) : + ∀ e, G.edgeSatisfied (labelsOfBits vertices assignment) e = true := by + intro e + have h := accepted (edges e) + simpa only [eventValue_eq, Equiv.symm_apply_apply] using h + +def cnf (G : ConstraintGraph V E Label) (vertices : V ≃ Fin n) (edges : E ≃ Fin m) : Formula := + VerifierToCNF.convert (verifier G vertices edges) (by decide) + +abbrev OutputAssignment (G : ConstraintGraph V E Label) (vertices : V ≃ Fin n) + (edges : E ≃ Fin m) := + Fin (VerifierToCNF.outputVariables (verifier G vertices edges)) → Bool + +def extractLabeling (G : ConstraintGraph V E Label) (vertices : V ≃ Fin n) + (edges : E ≃ Fin m) (assignment : OutputAssignment G vertices edges) : V → Label := + labelsOfBits vertices (VerifierToCNF.restrictAssignment (verifier G vertices edges) assignment) + +theorem cnf_completeness (G : ConstraintGraph V E Label) (vertices : V ≃ Fin n) + (edges : E ≃ Fin m) (sat : G.Satisfiable) : (cnf G vertices edges).Satisfiable := by + obtain ⟨labeling, satisfied⟩ := sat + exact VerifierToCNF.convert_completeness (verifier G vertices edges) (by decide) + (bitsOfLabels vertices labeling) (verifier_completeness G vertices edges labeling satisfied) + +theorem cnf_count_bridge [Fintype E] (G : ConstraintGraph V E Label) + (vertices : V ≃ Fin n) (edges : E ≃ Fin m) (assignment : OutputAssignment G vertices edges) : + G.rejectionCount (extractLabeling G vertices edges assignment) ≤ + NameCompaction.failedCount (cnf G vertices edges) assignment := by + have h := VerifierToCNF.convert_count_bridge (verifier G vertices edges) (by decide) assignment + rw [rejection_count_eq] at h + exact h + +theorem failedCount_zero_of_satisfied (F : Formula) (assignment : Fin F.«variables» → Bool) + (satisfied : ∀ c ∈ F.clauses, c.eval assignment = true) : + NameCompaction.failedCount F assignment = 0 := by + apply (VerifierToCNF.zero_false_count_iff_all _).mpr + have h := List.all_eq_true.mpr satisfied + simpa only [NameCompaction.evaluationList, List.all_map, Function.comp_def, id_eq] using h + +theorem all_satisfied_of_rejectionCount_zero [Fintype E] (G : ConstraintGraph V E Label) + (labeling : V → Label) (zero : G.rejectionCount labeling = 0) : + ∀ e, G.edgeSatisfied labeling e = true := by + intro e + cases h : G.edgeSatisfied labeling e with + | true => rfl + | false => + have member : e ∈ G.rejectedDarts labeling := (G.mem_rejectedDarts labeling e).mpr h + have positive : 0 < G.rejectionCount labeling := Finset.card_pos.mpr ⟨e, member⟩ + omega + +theorem cnf_reflects [Fintype E] (G : ConstraintGraph V E Label) + (vertices : V ≃ Fin n) (edges : E ≃ Fin m) (sat : (cnf G vertices edges).Satisfiable) : + G.Satisfiable := by + obtain ⟨assignment, satisfied⟩ := sat + have zero := failedCount_zero_of_satisfied (cnf G vertices edges) assignment satisfied + have bound := cnf_count_bridge G vertices edges assignment + have graphZero : G.rejectionCount (extractLabeling G vertices edges assignment) = 0 := by omega + exact ⟨extractLabeling G vertices edges assignment, + all_satisfied_of_rejectionCount_zero G _ graphZero⟩ + +theorem cnf_satisfiable_iff [Fintype E] (G : ConstraintGraph V E Label) + (vertices : V ≃ Fin n) (edges : E ≃ Fin m) : + (cnf G vertices edges).Satisfiable ↔ G.Satisfiable := + ⟨cnf_reflects G vertices edges, cnf_completeness G vertices edges⟩ + +theorem cnf_clause_count (G : ConstraintGraph V E Label) (vertices : V ≃ Fin n) + (edges : E ≃ Fin m) : (cnf G vertices edges).clauses.length = m * 40960 := + VerifierToCNF.twelve_query_clause_count (verifier G vertices edges) + +theorem twelve_query_auxiliary_factor : 2 ^ 12 * (12 - 3) = 36864 := by decide + +theorem cnf_variable_count (G : ConstraintGraph V E Label) (vertices : V ≃ Fin n) + (edges : E ≃ Fin m) : (cnf G vertices edges).«variables» = n * 6 + m * 36864 := by + change n * 6 + m * (VerifierToCNF.patterns 12).length * (12 - 3) = _ + rw [VerifierToCNF.patterns_length, Nat.mul_assoc, twelve_query_auxiliary_factor] + +theorem cnf_nonempty (G : ConstraintGraph V E Label) (vertices : V ≃ Fin n) + (edges : E ≃ Fin m) (nonempty : 0 < m) : (cnf G vertices edges).clauses ≠ [] := + VerifierToCNF.convert_nonempty (verifier G vertices edges) (by decide) nonempty + +theorem cnf_gap [Fintype E] (G : ConstraintGraph V E Label) + (vertices : V ≃ Fin n) (edges : E ≃ Fin m) (a b : Nat) + (source : ∀ labeling : V → Label, a * Fintype.card E ≤ b * G.rejectionCount labeling) + (assignment : OutputAssignment G vertices edges) : + a * (cnf G vertices edges).clauses.length ≤ + (b * 40960) * NameCompaction.failedCount (cnf G vertices edges) assignment := by + have cardEdges : Fintype.card E = m := by simpa using Fintype.card_congr edges + have testGap (bits : Fin (n * 6) → Bool) : + a * m ≤ b * VerifierToCNF.rejectedEventCount (verifier G vertices edges) bits := by + rw [rejection_count_eq] + simpa only [cardEdges] using source (labelsOfBits vertices bits) + simpa only [cnf, VerifierToCNF.twelve_query_factor] using + VerifierToCNF.convert_gap (verifier G vertices edges) (by decide) a b testGap assignment + +abbrev ReducedVertex (V E A : Type*) := + QueryIncidence.Vertex (AlphabetGraph.Event E A) (AlphabetGraph.Address V E A) + +abbrev ReducedDart (E A : Type*) := QueryIncidence.Dart (AlphabetGraph.Event E A) 6 + +variable {A : Type*} [Fintype A] [DecidableEq A] [Nonempty A] + [DecidableEq V] [DecidableEq E] + +noncomputable def alphabetCNF (G : ConstraintGraph V E A) + (vertices : ReducedVertex V E A ≃ Fin n) (edges : ReducedDart E A ≃ Fin m) : Formula := + cnf (AlphabetGraph.graph G) vertices edges + +omit [DecidableEq A] [Nonempty A] in +theorem alphabetCNF_completeness (G : ConstraintGraph V E A) + (vertices : ReducedVertex V E A ≃ Fin n) (edges : ReducedDart E A ≃ Fin m) + (sat : G.Satisfiable) : (alphabetCNF G vertices edges).Satisfiable := + cnf_completeness (AlphabetGraph.graph G) vertices edges (AlphabetGraph.perfect_completeness G sat) + +omit [DecidableEq A] [Nonempty A] in +theorem alphabetCNF_clause_count (G : ConstraintGraph V E A) + (vertices : ReducedVertex V E A ≃ Fin n) (edges : ReducedDart E A ≃ Fin m) : + (alphabetCNF G vertices edges).clauses.length = m * 40960 := + cnf_clause_count (AlphabetGraph.graph G) vertices edges + +theorem alphabetCNF_gap [Fintype E] (G : ConstraintGraph V E A) + (vertices : ReducedVertex V E A ≃ Fin n) (edges : ReducedDart E A ≃ Fin m) + (a b : Nat) + (source : ∀ labeling : V → A, a * Fintype.card E ≤ b * G.rejectionCount labeling) + (assignment : OutputAssignment (AlphabetGraph.graph G) vertices edges) : + a * (alphabetCNF G vertices edges).clauses.length ≤ + (b * 503316480) * NameCompaction.failedCount (alphabetCNF G vertices edges) assignment := by + have h := cnf_gap (AlphabetGraph.graph G) vertices edges a (b * 12288) + (AlphabetGraph.gap_transfer G a b source) assignment + have factor : (b * 12288) * 40960 = b * 503316480 := by omega + simpa only [alphabetCNF, factor] using h + +end MinUncutGames.Foundations.PCP.FinalBooleanVerifier + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/Folding.lean b/lean/OAI/Computability/MinUncut/PCP/Folding.lean new file mode 100644 index 0000000000000000000000000000000000000000..eaed0bebe2cc5841d0c092e0c583081decb91ded --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/Folding.lean @@ -0,0 +1,794 @@ +import Mathlib +import OAI.Computability.MinUncut.Encoding.ThreeBitTest + +namespace OAI + +noncomputable section + +namespace MinUncutGames.Foundations.Hastad + +open scoped BigOperators +open Finset + +variable {I : Type*} [Fintype I] [DecidableEq I] + +def cubeFlip (f : Cube I) : Cube I := fun i => !(f i) + +omit [Fintype I] [DecidableEq I] in +@[simp] theorem cubeFlip_cubeFlip (f : Cube I) : cubeFlip (cubeFlip f) = f := by + funext i + simp [cubeFlip] + +@[simp] theorem bitSign_not (b : Bool) : bitSign (!b) = -bitSign b := by + cases b <;> norm_num [bitSign] + +theorem sum_cubeFlip (F : Cube I → ℝ) : (∑ f, F (cubeFlip f)) = ∑ f, F f := by + refine Finset.sum_bij (fun f _ => cubeFlip f) ?_ ?_ ?_ ?_ + · intro f _ + exact Finset.mem_univ _ + · intro f _ g _ h + have h' := congrArg cubeFlip h + simpa only [cubeFlip_cubeFlip] using h' + · intro g _ + exact ⟨cubeFlip g, Finset.mem_univ _, cubeFlip_cubeFlip g⟩ + · intro f _ + rfl + +theorem coefficient_zero_of_odd (F : Cube I → ℝ) + (hF : ∀ f, F (cubeFlip f) = -F f) : + coefficient F (fun _ => false) = 0 := by + have hs : (∑ f, F f) = 0 := by + have h := sum_cubeFlip F + simp_rw [hF, Finset.sum_neg_distrib] at h + linarith + simp [coefficient, walsh, bitSign, Fintype.expect_eq_sum_div_card, hs] + +theorem coefficient_sign_zero_of_folded (A : Cube I → Bool) + (hA : ∀ f, A (cubeFlip f) = !(A f)) : + coefficient (fun f => bitSign (A f)) (fun _ => false) = 0 := by + apply coefficient_zero_of_odd + intro f + rw [hA, bitSign_not] + +def representative (i₀ : I) (f : Cube I) : Cube I := + if f i₀ then cubeFlip f else f + +omit [Fintype I] [DecidableEq I] in +theorem representative_at (i₀ : I) (f : Cube I) : + representative i₀ f i₀ = false := by + cases hf : f i₀ <;> simp [representative, cubeFlip, hf] + +omit [Fintype I] [DecidableEq I] in +theorem representative_flip (i₀ : I) (f : Cube I) : + representative i₀ (cubeFlip f) = representative i₀ f := by + cases hf : f i₀ <;> simp [representative, cubeFlip, hf] + +abbrev HalfCube (i₀ : I) := {f : Cube I // f i₀ = false} + +def canonicalInput (i₀ : I) (f : Cube I) : HalfCube i₀ := + ⟨representative i₀ f, representative_at i₀ f⟩ + +omit [Fintype I] [DecidableEq I] in +theorem canonicalInput_flip (i₀ : I) (f : Cube I) : + canonicalInput i₀ (cubeFlip f) = canonicalInput i₀ f := by + apply Subtype.ext + exact representative_flip i₀ f + +def foldedAnswer (i₀ : I) (table : HalfCube i₀ → Bool) (f : Cube I) : Bool := + table (canonicalInput i₀ f) ^^ f i₀ + +omit [Fintype I] [DecidableEq I] in +theorem foldedAnswer_flip (i₀ : I) (table : HalfCube i₀ → Bool) (f : Cube I) : + foldedAnswer i₀ table (cubeFlip f) = !(foldedAnswer i₀ table f) := by + unfold foldedAnswer + rw [canonicalInput_flip] + change (table (canonicalInput i₀ f) ^^ !(f i₀)) = + !(table (canonicalInput i₀ f) ^^ f i₀) + cases table (canonicalInput i₀ f) <;> cases f i₀ <;> rfl + +theorem foldedAnswer_zero_coefficient (i₀ : I) (table : HalfCube i₀ → Bool) : + coefficient (fun f => bitSign (foldedAnswer i₀ table f)) (fun _ => false) = 0 := + coefficient_sign_zero_of_folded _ (foldedAnswer_flip i₀ table) + +omit [Fintype I] [DecidableEq I] in +theorem foldedAnswer_dictator (i₀ i : I) (f : Cube I) : + foldedAnswer i₀ (fun h => h.val i) f = f i := by + cases hf : f i₀ <;> cases hi : f i <;> + simp [foldedAnswer, canonicalInput, representative, cubeFlip, hf, hi] + +def coordinateMask (i : I) : Cube I := fun j => decide (j = i) + +def cubeToggle (i : I) (f : Cube I) : Cube I := + cubeXor f (coordinateMask i) + +omit [Fintype I] in +@[simp] theorem cubeToggle_twice (i : I) (f : Cube I) : + cubeToggle i (cubeToggle i f) = f := by + funext j + change ((f j ^^ coordinateMask i j) ^^ coordinateMask i j) = f j + cases f j <;> cases coordinateMask i j <;> rfl + +theorem walsh_coordinateMask (s : Cube I) (i : I) : + walsh s (coordinateMask i) = bitSign (s i) := by + unfold walsh + rw [Finset.prod_eq_single i] + · simp [coordinateMask] + · intro j _ hj + simp [coordinateMask, hj, bitSign] + · intro h + exact False.elim (h (Finset.mem_univ _)) + +theorem walsh_cubeToggle (s : Cube I) (i : I) (f : Cube I) (hs : s i = true) : + walsh s (cubeToggle i f) = -walsh s f := by + rw [cubeToggle, walsh_xor, walsh_coordinateMask, hs] + simp [bitSign] + +theorem sum_cubeToggle (i : I) (F : Cube I → ℝ) : + (∑ f, F (cubeToggle i f)) = ∑ f, F f := by + refine Finset.sum_bij (fun f _ => cubeToggle i f) ?_ ?_ ?_ ?_ + · intro f _ + exact Finset.mem_univ _ + · intro f _ g _ h + have h' := congrArg (cubeToggle i) h + simpa only [cubeToggle_twice] using h' + · intro g _ + exact ⟨cubeToggle i g, Finset.mem_univ _, cubeToggle_twice i g⟩ + · intro f _ + rfl + +def restrictQuery (valid : I → Bool) (f : Cube I) : + Cube {i : I // valid i = true} := fun i => f i.val + +omit [Fintype I] in +theorem restrictQuery_cubeToggle (valid : I → Bool) (i : I) + (hi : valid i = false) (f : Cube I) : + restrictQuery valid (cubeToggle i f) = restrictQuery valid f := by + funext j + have hj : j.val ≠ i := by + intro heq + have hp := j.property + rw [heq, hi] at hp + contradiction + simp [restrictQuery, cubeToggle, cubeXor, coordinateMask, hj] + +theorem conditioned_coefficient_zero_invalid (valid : I → Bool) + (B : Cube {i : I // valid i = true} → ℝ) (s : Cube I) (i : I) + (hi : valid i = false) (hs : s i = true) : + coefficient (fun f => B (restrictQuery valid f)) s = 0 := by + have hsum := sum_cubeToggle i (fun f => B (restrictQuery valid f) * walsh s f) + simp_rw [restrictQuery_cubeToggle valid i hi, walsh_cubeToggle s i _ hs, + mul_neg, Finset.sum_neg_distrib] at hsum + have hz : (∑ f, B (restrictQuery valid f) * walsh s f) = 0 := by linarith + simp [coefficient, Fintype.expect_eq_sum_div_card, hz] + +theorem conditioned_coefficient_support (valid : I → Bool) + (B : Cube {i : I // valid i = true} → ℝ) (s : Cube I) + (hne : coefficient (fun f => B (restrictQuery valid f)) s ≠ 0) : + ∀ i ∈ support s, valid i = true := by + intro i hi + have hs := (Finset.mem_filter.mp hi).2 + cases hv : valid i + · exact False.elim (hne (conditioned_coefficient_zero_invalid valid B s i hv hs)) + · rfl + +def conditionedFoldedAnswer (valid : I → Bool) (i₀ : {i : I // valid i = true}) + (table : HalfCube i₀ → Bool) (f : Cube I) : Bool := + foldedAnswer i₀ table (restrictQuery valid f) + +omit [Fintype I] [DecidableEq I] in +theorem conditionedFoldedAnswer_flip (valid : I → Bool) + (i₀ : {i : I // valid i = true}) (table : HalfCube i₀ → Bool) (f : Cube I) : + conditionedFoldedAnswer valid i₀ table (cubeFlip f) = + !(conditionedFoldedAnswer valid i₀ table f) := by + change foldedAnswer i₀ table (cubeFlip (restrictQuery valid f)) = _ + exact foldedAnswer_flip i₀ table (restrictQuery valid f) + +theorem conditionedFoldedAnswer_zero_coefficient (valid : I → Bool) + (i₀ : {i : I // valid i = true}) (table : HalfCube i₀ → Bool) : + coefficient (fun f => bitSign (conditionedFoldedAnswer valid i₀ table f)) + (fun _ => false) = 0 := + coefficient_sign_zero_of_folded _ (conditionedFoldedAnswer_flip valid i₀ table) + +omit [Fintype I] [DecidableEq I] in +theorem conditionedFoldedAnswer_dictator (valid : I → Bool) + (i₀ i : {i : I // valid i = true}) (f : Cube I) : + conditionedFoldedAnswer valid i₀ (fun h => h.val i) f = f i.val := by + exact foldedAnswer_dictator i₀ i (restrictQuery valid f) + +end MinUncutGames.Foundations.Hastad + +end +namespace MinUncutGames.Reduction.CloneGap + +variable {α β : Type*} {Name : Type} + +def cart (xs : List α) (ys : List β) : List (α × β) := + xs.flatMap fun x => ys.map fun y => (x, y) + +theorem count_const (xs : List α) (b : Bool) : + xs.countP (fun _ => b) = if b then xs.length else 0 := by + cases b <;> simp + +theorem count_cart (xs : List α) (ys : List β) (p : α → Bool) (q : β → Bool) : + (cart xs ys).countP (fun z => p z.1 && q z.2) = + xs.countP p * ys.countP q := by + induction xs with + | nil => simp [cart] + | cons x xs ih => + simp only [cart, List.flatMap_cons, List.countP_append] at * + rw [ih] + cases h : p x <;> + simp [List.countP_map, Function.comp_def, h, Nat.add_mul, Nat.add_comm] + +theorem length_cart (xs : List α) (ys : List β) : + (cart xs ys).length = xs.length * ys.length := by + have := count_cart xs ys (fun _ => true) (fun _ => true) + simpa using this + +theorem count_cart_left (xs : List α) (ys : List β) (p : α → Bool) : + (cart xs ys).countP (fun z => p z.1) = xs.countP p * ys.length := by + simpa using count_cart xs ys p (fun _ => true) + +theorem count_cart_right (xs : List α) (ys : List β) (p : β → Bool) : + (cart xs ys).countP (fun z => p z.2) = xs.length * ys.countP p := by + simpa using count_cart xs ys (fun _ => true) p + +theorem count_cart_le (xs : List α) (ys : List β) (p : α × β → Bool) + (bound : Nat) (h : ∀ x ∈ xs, ys.countP (fun y => p (x, y)) ≤ bound) : + (cart xs ys).countP p ≤ xs.length * bound := by + induction xs with + | nil => simp [cart] + | cons x xs ih => + have hx := h x (by simp) + have ht := ih (fun y hy => h y (by simp [hy])) + simp only [cart, List.flatMap_cons, List.countP_append, List.countP_map, + Function.comp_def] at * + simp only [List.length_cons, Nat.add_mul] + omega + +theorem count_union_le (xs : List α) (p q : α → Bool) : + xs.countP (fun x => p x || q x) ≤ xs.countP p + xs.countP q := by + induction xs with + | nil => simp + | cons x xs ih => + cases hp : p x <;> cases hq : q x <;> + simp [hp, hq] at * <;> omega + +theorem count_remove (xs : List α) (p q : α → Bool) : + xs.countP p ≤ xs.countP (fun x => p x && !q x) + xs.countP q := by + induction xs with + | nil => simp + | cons x xs ih => + cases hp : p x <;> cases hq : q x <;> + simp [hp, hq] at * <;> omega + +abbrev Index := Nat +def indices : List Index := List.range 48 +def triples : List (Index × Index × Index) := cart indices (cart indices indices) +def collision (t : Index × Index × Index) : Bool := + (t.1 == t.2.1) || (t.1 == t.2.2) || (t.2.1 == t.2.2) +def distinctTriples : List (Index × Index × Index) := triples.filter (fun t => !collision t) + +theorem length_indices : indices.length = 48 := by simp [indices] +theorem length_triples : triples.length = 110592 := by + simp [triples, length_cart, length_indices] + +theorem count_index_eq_le (i : Index) : indices.countP (fun j => i == j) ≤ 1 := by + have h := List.count_range (a := i) (n := 48) + have heq : (fun j => i == j) = (fun j => j == i) := by + funext j + exact Bool.beq_comm + rw [heq] + change (List.range 48).count i ≤ 1 + rw [h] + split <;> omega + +theorem count_collision_le : triples.countP collision ≤ 6912 := by + have h12 : triples.countP (fun t => t.1 == t.2.1) ≤ 2304 := by + apply count_cart_le indices (cart indices indices) _ 48 + intro i _ + change (cart indices indices).countP (fun y => i == y.1) ≤ 48 + rw [count_cart_left indices indices (fun j => i == j), length_indices] + have := count_index_eq_le i + omega + have h13 : triples.countP (fun t => t.1 == t.2.2) ≤ 2304 := by + apply count_cart_le indices (cart indices indices) _ 48 + intro i _ + change (cart indices indices).countP (fun y => i == y.2) ≤ 48 + rw [count_cart_right indices indices (fun j => i == j), length_indices] + have := count_index_eq_le i + omega + have h23 : triples.countP (fun t => t.2.1 == t.2.2) ≤ 2304 := by + change (cart indices (cart indices indices)).countP (fun t => t.2.1 == t.2.2) ≤ 2304 + rw [count_cart_right indices (cart indices indices) (fun t => t.1 == t.2), length_indices] + have h : (cart indices indices).countP (fun t => t.1 == t.2) ≤ 48 := by + apply count_cart_le indices indices _ 1 + intro i _ + exact count_index_eq_le i + omega + have hA := count_union_le triples (fun t => t.1 == t.2.1) (fun t => t.1 == t.2.2) + have hB := count_union_le triples + (fun t => (t.1 == t.2.1) || (t.1 == t.2.2)) (fun t => t.2.1 == t.2.2) + unfold collision + omega + +theorem majority_exists (g : Index → Bool) : + ∃ b : Bool, 24 ≤ indices.countP (fun i => g i == b) := by + have h := List.length_eq_countP_add_countP g (l := indices) + have hn : (fun i => decide (¬g i = true)) = (fun i => !g i) := by + funext i + cases g i <;> rfl + rw [hn] at h + rw [length_indices] at h + by_cases ht : 24 ≤ indices.countP g + · exact ⟨true, by simpa using ht⟩ + · refine ⟨false, ?_⟩ + have : 24 ≤ indices.countP (fun i => !g i) := by omega + simpa using this + +def allAgree (p q r : Index → Bool) (t : Index × Index × Index) : Bool := + p t.1 && (q t.2.1 && r t.2.2) + +theorem count_agree_distinct (p q r : Index → Bool) + (hp : 24 ≤ indices.countP p) (hq : 24 ≤ indices.countP q) + (hr : 24 ≤ indices.countP r) : + 6912 ≤ distinctTriples.countP (allAgree p q r) := by + have hprod := count_cart indices (cart indices indices) p + (fun t => q t.1 && r t.2) + rw [count_cart] at hprod + have h1 : 24 * 24 ≤ indices.countP q * indices.countP r := Nat.mul_le_mul hq hr + have h2 : 24 * (24 * 24) ≤ indices.countP p * + (indices.countP q * indices.countP r) := Nat.mul_le_mul hp h1 + have hremove := count_remove triples (allAgree p q r) collision + have hcollision := count_collision_le + change triples.countP (allAgree p q r) = _ at hprod + unfold distinctTriples + rw [List.countP_filter] + omega + +structure Equation (Name : Type) where + first : Name + second : Name + third : Name + rhs : Bool + +def satisfied (e : Equation Name) (g : Name → Bool) : Bool := + (xor (xor (g e.first) (g e.second)) (g e.third)) == e.rhs + +def clone (e : Equation Name) (t : Index × Index × Index) : Equation (Name × Index) := + ⟨(e.first, t.1), (e.second, t.2.1), (e.third, t.2.2), e.rhs⟩ + +theorem lift_preserves (e : Equation Name) (t : Index × Index × Index) (g : Name → Bool) : + satisfied (clone e t) (fun z => g z.1) = satisfied e g := rfl + +theorem clone_names_distinct (e : Equation Name) (t : Index × Index × Index) + (h : collision t = false) : + (clone e t).first ≠ (clone e t).second ∧ + (clone e t).first ≠ (clone e t).third ∧ + (clone e t).second ≠ (clone e t).third := by + simp only [collision, Bool.or_eq_false_iff, beq_eq_false_iff_ne] at h + dsimp [clone] + exact ⟨fun he => h.1.1 (congrArg Prod.snd he), + fun he => h.1.2 (congrArg Prod.snd he), + fun he => h.2 (congrArg Prod.snd he)⟩ + +theorem agree_failure (e : Equation Name) (g : Name × Index → Bool) + (majority : Name → Bool) (t : Index × Index × Index) + (hfail : satisfied e majority = false) + (h : allAgree (fun i => g (e.first, i) == majority e.first) + (fun i => g (e.second, i) == majority e.second) + (fun i => g (e.third, i) == majority e.third) t = true) : + satisfied (clone e t) g = false := by + simp only [allAgree, Bool.and_eq_true, beq_iff_eq] at h + simpa [satisfied, clone, h.1, h.2.1, h.2.2] using hfail + +theorem failed_occurrence_clones (e : Equation Name) (g : Name × Index → Bool) + (majority : Name → Bool) + (hmaj : ∀ v, 24 ≤ indices.countP (fun i => g (v, i) == majority v)) + (hfail : satisfied e majority = false) : + 6912 ≤ distinctTriples.countP (fun t => !satisfied (clone e t) g) := by + have h := count_agree_distinct + (fun i => g (e.first, i) == majority e.first) + (fun i => g (e.second, i) == majority e.second) + (fun i => g (e.third, i) == majority e.third) + (hmaj _) (hmaj _) (hmaj _) + apply Nat.le_trans h + apply List.countP_mono_left + intro t _ ht + have hf := agree_failure e g majority t hfail ht + simp [hf] + +def majorityBit (g : Index → Bool) : Bool := decide (24 ≤ indices.countP g) + +theorem majorityBit_count (g : Index → Bool) : + 24 ≤ indices.countP (fun i => g i == majorityBit g) := by + have h := List.length_eq_countP_add_countP g (l := indices) + have hn : (fun i => decide (¬g i = true)) = (fun i => !g i) := by + funext i + cases g i <;> rfl + rw [hn, length_indices] at h + by_cases ht : 24 ≤ indices.countP g + · simp [majorityBit, ht] + · have hn : 24 ≤ indices.countP (fun i => !g i) := by omega + simpa [majorityBit, ht] using hn + +def cloneList (source : List (Equation Name)) : List (Equation (Name × Index)) := + source.flatMap fun e => distinctTriples.map (clone e) + +theorem length_cloneList (source : List (Equation Name)) : + (cloneList source).length = source.length * distinctTriples.length := by + induction source with + | nil => simp [cloneList] + | cons e es ih => + simp only [cloneList, List.flatMap_cons, List.length_append, List.length_map] at * + rw [ih] + simp [Nat.add_mul, Nat.add_comm] + +theorem cloneList_failure_lower (source : List (Equation Name)) + (g : Name × Index → Bool) (majority : Name → Bool) + (hmaj : ∀ v, 24 ≤ indices.countP (fun i => g (v, i) == majority v)) : + 6912 * source.countP (fun e => !satisfied e majority) ≤ + (cloneList source).countP (fun e => !satisfied e g) := by + induction source with + | nil => simp [cloneList] + | cons e es ih => + simp only [cloneList, List.flatMap_cons, List.countP_append, + List.countP_map, Function.comp_def] at * + cases hf : satisfied e majority with + | false => + have he := failed_occurrence_clones e g majority hmaj hf + simp [hf, Nat.mul_add] at * + omega + | true => + simp [hf] + omega + +theorem clone_gap (source : List (Equation Name)) + (source_gap : ∀ A : Name → Bool, + source.length ≤ 4 * source.countP (fun e => !satisfied e A)) + (g : Name × Index → Bool) : + (cloneList source).length ≤ + 64 * (cloneList source).countP (fun e => !satisfied e g) := by + let majority : Name → Bool := fun v => majorityBit (fun i => g (v, i)) + have hmaj : ∀ v, 24 ≤ indices.countP (fun i => g (v, i) == majority v) := + fun v => majorityBit_count (fun i => g (v, i)) + have hlocal := cloneList_failure_lower source g majority hmaj + have hsource := source_gap majority + have hd : distinctTriples.length ≤ 110592 := by + exact Nat.le_trans (List.length_filter_le _ triples) (by simp [length_triples]) + rw [length_cloneList] + have hlength := Nat.mul_le_mul_left source.length hd + have hs := Nat.mul_le_mul_right 27648 hsource + have hc := Nat.mul_le_mul_left 64 hlocal + omega + +theorem clone_completeness_count (source : List (Equation Name)) (A : Name → Bool) : + (cloneList source).countP (fun e => satisfied e (fun z => A z.1)) = + source.countP (fun e => satisfied e A) * distinctTriples.length := by + induction source with + | nil => simp [cloneList] + | cons e es ih => + simp only [cloneList, List.flatMap_cons, List.countP_append, + List.countP_map, Function.comp_def] at * + rw [ih] + have he : (fun t => satisfied (clone e t) (fun z => A z.1)) = + (fun _ => satisfied e A) := by + funext t + exact lift_preserves e t A + rw [he, count_const] + cases h : satisfied e A <;> simp [h, Nat.add_mul, Nat.add_comm] + +end MinUncutGames.Reduction.CloneGap + +namespace MinUncutGames.Foundations.Hastad.FoldedEquation + +open MinUncutGames.Reduction.CloneGap +open scoped BigOperators + +variable {I J : Type} + +abbrev Address (i₀ : I) (j₀ : J) := HalfCube i₀ ⊕ HalfCube j₀ + +def storedAssignment {i₀ : I} {j₀ : J} + (tableA : HalfCube i₀ → Bool) (tableB : HalfCube j₀ → Bool) : + Address i₀ j₀ → Bool := Sum.elim tableA tableB + +def rhsCorrection (π : J → I) (i₀ : I) (j₀ : J) + (f : Cube I) (μ : Cube J) : Bool := f i₀ ^^ f (π j₀) ^^ μ j₀ + +theorem correction_eq (π : J → I) (i₀ : I) (j₀ : J) + (f : Cube I) (g μ : Cube J) : + (f i₀ ^^ g j₀ ^^ thirdQuery π f g μ j₀) = rhsCorrection π i₀ j₀ f μ := by + change (f i₀ ^^ g j₀ ^^ (g j₀ ^^ (f (π j₀) ^^ μ j₀))) = + (f i₀ ^^ f (π j₀) ^^ μ j₀) + cases f i₀ <;> cases g j₀ <;> cases f (π j₀) <;> cases μ j₀ <;> rfl + +def equation (π : J → I) (i₀ : I) (j₀ : J) + (f : Cube I) (g μ : Cube J) : Equation (Address i₀ j₀) where + first := .inl (canonicalInput i₀ f) + second := .inr (canonicalInput j₀ g) + third := .inr (canonicalInput j₀ (thirdQuery π f g μ)) + rhs := rhsCorrection π i₀ j₀ f μ + +theorem xor_corrections (a b c u v w : Bool) : + ((a ^^ b ^^ c) == (u ^^ v ^^ w)) = + !((a ^^ u) ^^ (b ^^ v) ^^ (c ^^ w)) := by + cases a <;> cases b <;> cases c <;> cases u <;> cases v <;> cases w <;> rfl + +theorem equation_satisfied (π : J → I) (i₀ : I) (j₀ : J) + (tableA : HalfCube i₀ → Bool) (tableB : HalfCube j₀ → Bool) + (f : Cube I) (g μ : Cube J) : + satisfied (equation π i₀ j₀ f g μ) (storedAssignment tableA tableB) = + !(foldedAnswer i₀ tableA f ^^ foldedAnswer j₀ tableB g ^^ + foldedAnswer j₀ tableB (thirdQuery π f g μ)) := by + change ((tableA (canonicalInput i₀ f) ^^ tableB (canonicalInput j₀ g) ^^ + tableB (canonicalInput j₀ (thirdQuery π f g μ))) == rhsCorrection π i₀ j₀ f μ) = _ + rw [← correction_eq π i₀ j₀ f g μ] + exact xor_corrections _ _ _ _ _ _ + +theorem equation_satisfied_iff (π : J → I) (i₀ : I) (j₀ : J) + (tableA : HalfCube i₀ → Bool) (tableB : HalfCube j₀ → Bool) + (f : Cube I) (g μ : Cube J) : + satisfied (equation π i₀ j₀ f g μ) (storedAssignment tableA tableB) = true ↔ + (foldedAnswer i₀ tableA f ^^ foldedAnswer j₀ tableB g ^^ + foldedAnswer j₀ tableB (thirdQuery π f g μ)) = false := by + rw [equation_satisfied] + simp + +theorem equation_indicator (π : J → I) (i₀ : I) (j₀ : J) + (tableA : HalfCube i₀ → Bool) (tableB : HalfCube j₀ → Bool) + (f : Cube I) (g μ : Cube J) : + (if satisfied (equation π i₀ j₀ f g μ) (storedAssignment tableA tableB) + then (1 : ℝ) else 0) = + (if foldedAnswer i₀ tableA f ^^ foldedAnswer j₀ tableB g ^^ + foldedAnswer j₀ tableB (thirdQuery π f g μ) then 0 else 1) := by + rw [equation_satisfied] + cases foldedAnswer i₀ tableA f ^^ foldedAnswer j₀ tableB g ^^ + foldedAnswer j₀ tableB (thirdQuery π f g μ) <;> rfl + +theorem satisfied_repeated_right {Name : Type} (e : Equation Name) + (assignment : Name → Bool) (h : e.second = e.third) : + satisfied e assignment = (assignment e.first == e.rhs) := by + unfold satisfied + rw [← h] + cases assignment e.first <;> cases assignment e.second <;> cases e.rhs <;> rfl + +theorem equation_repeated_right (π : J → I) (i₀ : I) (j₀ : J) + (tableA : HalfCube i₀ → Bool) (tableB : HalfCube j₀ → Bool) + (f : Cube I) (g μ : Cube J) + (h : canonicalInput j₀ g = canonicalInput j₀ (thirdQuery π f g μ)) : + satisfied (equation π i₀ j₀ f g μ) (storedAssignment tableA tableB) = + (tableA (canonicalInput i₀ f) == rhsCorrection π i₀ j₀ f μ) := by + apply satisfied_repeated_right + exact congrArg Sum.inr h + +theorem restrict_thirdQuery (valid : J → Bool) (π : J → I) + (f : Cube I) (g μ : Cube J) : + restrictQuery valid (thirdQuery π f g μ) = + thirdQuery (fun j : {j : J // valid j = true} => π j.val) f + (restrictQuery valid g) (restrictQuery valid μ) := rfl + +def conditionedEquation (valid : J → Bool) (π : J → I) + (i₀ : I) (j₀ : {j : J // valid j = true}) + (f : Cube I) (g μ : Cube J) : Equation (Address i₀ j₀) := + equation (fun j => π j.val) i₀ j₀ f (restrictQuery valid g) (restrictQuery valid μ) + +theorem conditionedEquation_rhs (valid : J → Bool) (π : J → I) + (i₀ : I) (j₀ : {j : J // valid j = true}) (f : Cube I) (g μ : Cube J) : + (conditionedEquation valid π i₀ j₀ f g μ).rhs = + (f i₀ ^^ f (π j₀.val) ^^ μ j₀.val) := rfl + +theorem conditionedEquation_satisfied (valid : J → Bool) (π : J → I) + (i₀ : I) (j₀ : {j : J // valid j = true}) + (tableA : HalfCube i₀ → Bool) (tableB : HalfCube j₀ → Bool) + (f : Cube I) (g μ : Cube J) : + satisfied (conditionedEquation valid π i₀ j₀ f g μ) (storedAssignment tableA tableB) = + !(foldedAnswer i₀ tableA f ^^ conditionedFoldedAnswer valid j₀ tableB g ^^ + conditionedFoldedAnswer valid j₀ tableB (thirdQuery π f g μ)) := by + unfold conditionedEquation + rw [equation_satisfied] + simp only [conditionedFoldedAnswer, restrict_thirdQuery] + +theorem conditionedEquation_satisfied_iff (valid : J → Bool) (π : J → I) + (i₀ : I) (j₀ : {j : J // valid j = true}) + (tableA : HalfCube i₀ → Bool) (tableB : HalfCube j₀ → Bool) + (f : Cube I) (g μ : Cube J) : + satisfied (conditionedEquation valid π i₀ j₀ f g μ) (storedAssignment tableA tableB) = true ↔ + (foldedAnswer i₀ tableA f ^^ conditionedFoldedAnswer valid j₀ tableB g ^^ + conditionedFoldedAnswer valid j₀ tableB (thirdQuery π f g μ)) = false := by + rw [conditionedEquation_satisfied] + simp + +theorem conditionedEquation_indicator (valid : J → Bool) (π : J → I) + (i₀ : I) (j₀ : {j : J // valid j = true}) + (tableA : HalfCube i₀ → Bool) (tableB : HalfCube j₀ → Bool) + (f : Cube I) (g μ : Cube J) : + (if satisfied (conditionedEquation valid π i₀ j₀ f g μ) (storedAssignment tableA tableB) + then (1 : ℝ) else 0) = + (if foldedAnswer i₀ tableA f ^^ conditionedFoldedAnswer valid j₀ tableB g ^^ + conditionedFoldedAnswer valid j₀ tableB (thirdQuery π f g μ) then 0 else 1) := by + rw [conditionedEquation_satisfied] + cases foldedAnswer i₀ tableA f ^^ conditionedFoldedAnswer valid j₀ tableB g ^^ + conditionedFoldedAnswer valid j₀ tableB (thirdQuery π f g μ) <;> rfl + +theorem conditionedEquation_repeated_right (valid : J → Bool) (π : J → I) + (i₀ : I) (j₀ : {j : J // valid j = true}) + (tableA : HalfCube i₀ → Bool) (tableB : HalfCube j₀ → Bool) + (f : Cube I) (g μ : Cube J) + (h : canonicalInput j₀ (restrictQuery valid g) = + canonicalInput j₀ (restrictQuery valid (thirdQuery π f g μ))) : + satisfied (conditionedEquation valid π i₀ j₀ f g μ) (storedAssignment tableA tableB) = + (tableA (canonicalInput i₀ f) == (f i₀ ^^ f (π j₀.val) ^^ μ j₀.val)) := by + apply satisfied_repeated_right + exact congrArg Sum.inr h + +noncomputable section + +variable [Fintype I] [DecidableEq I] [Fintype J] [DecidableEq J] + +def equationAcceptance (ε : ℝ) (π : J → I) (i₀ : I) (j₀ : J) + (tableA : HalfCube i₀ → Bool) (tableB : HalfCube j₀ → Bool) : ℝ := + 𝔼 f, ∑ μ, noiseWeight ε μ * + (𝔼 g, if satisfied (equation π i₀ j₀ f g μ) (storedAssignment tableA tableB) + then (1 : ℝ) else 0) + +theorem equationAcceptance_eq (ε : ℝ) (π : J → I) (i₀ : I) (j₀ : J) + (tableA : HalfCube i₀ → Bool) (tableB : HalfCube j₀ → Bool) : + equationAcceptance ε π i₀ j₀ tableA tableB = + testAcceptance ε π (foldedAnswer i₀ tableA) (foldedAnswer j₀ tableB) := by + unfold equationAcceptance testAcceptance + simp_rw [equation_indicator] + +def conditionedEquationAcceptance (ε : ℝ) (valid : J → Bool) (π : J → I) + (i₀ : I) (j₀ : {j : J // valid j = true}) + (tableA : HalfCube i₀ → Bool) (tableB : HalfCube j₀ → Bool) : ℝ := + 𝔼 f, ∑ μ, noiseWeight ε μ * + (𝔼 g, if satisfied (conditionedEquation valid π i₀ j₀ f g μ) + (storedAssignment tableA tableB) then (1 : ℝ) else 0) + +theorem conditionedEquationAcceptance_eq (ε : ℝ) (valid : J → Bool) (π : J → I) + (i₀ : I) (j₀ : {j : J // valid j = true}) + (tableA : HalfCube i₀ → Bool) (tableB : HalfCube j₀ → Bool) : + conditionedEquationAcceptance ε valid π i₀ j₀ tableA tableB = + testAcceptance ε π (foldedAnswer i₀ tableA) + (conditionedFoldedAnswer valid j₀ tableB) := by + unfold conditionedEquationAcceptance testAcceptance + simp_rw [conditionedEquation_indicator] + +end + +end MinUncutGames.Foundations.Hastad.FoldedEquation + +namespace MinUncutGames.Foundations.Hastad + +open MinUncutGames.Reduction.CloneGap +open scoped BigOperators + +def mapEquation {Name Name' : Type} (rename : Name → Name') + (e : Equation Name) : Equation Name' where + first := rename e.first + second := rename e.second + third := rename e.third + rhs := e.rhs + +theorem satisfied_mapEquation {Name Name' : Type} (rename : Name → Name') + (e : Equation Name) (assignment : Name' → Bool) : + satisfied (mapEquation rename e) assignment = satisfied e (assignment ∘ rename) := rfl + +namespace EmptyContext + +variable {I : Type} + +abbrev Address (i₀ : I) := HalfCube i₀ ⊕ Unit + +def storedAssignment {i₀ : I} (table : HalfCube i₀ → Bool) (dummy : Bool) : + Address i₀ → Bool := Sum.elim table (fun _ => dummy) + +def equation (i₀ : I) (f : Cube I) : Equation (Address i₀) where + first := .inl (canonicalInput i₀ f) + second := .inr () + third := .inr () + rhs := f i₀ + +@[simp] theorem equation_second_eq_third (i₀ : I) (f : Cube I) : + (equation i₀ f).second = (equation i₀ f).third := rfl + +theorem equation_satisfied (i₀ : I) (assignment : Address i₀ → Bool) (f : Cube I) : + satisfied (equation i₀ f) assignment = + !(foldedAnswer i₀ (fun h => assignment (.inl h)) f) := by + rw [FoldedEquation.satisfied_repeated_right (equation i₀ f) assignment rfl] + change (assignment (.inl (canonicalInput i₀ f)) == f i₀) = + !(assignment (.inl (canonicalInput i₀ f)) ^^ f i₀) + cases assignment (.inl (canonicalInput i₀ f)) <;> cases f i₀ <;> rfl + +theorem equation_storedAssignment_satisfied (i₀ : I) (table : HalfCube i₀ → Bool) + (dummy : Bool) (f : Cube I) : + satisfied (equation i₀ f) (storedAssignment table dummy) = + !(foldedAnswer i₀ table f) := equation_satisfied i₀ _ f + +theorem equation_flip_first (i₀ : I) (f : Cube I) : + (equation i₀ (cubeFlip f)).first = (equation i₀ f).first := by + change Sum.inl (canonicalInput i₀ (cubeFlip f)) = Sum.inl (canonicalInput i₀ f) + rw [canonicalInput_flip] + +theorem equation_flip_rhs (i₀ : I) (f : Cube I) : + (equation i₀ (cubeFlip f)).rhs = !(equation i₀ f).rhs := rfl + +theorem equation_satisfied_flip (i₀ : I) (assignment : Address i₀ → Bool) + (f : Cube I) : + satisfied (equation i₀ (cubeFlip f)) assignment = + !(satisfied (equation i₀ f) assignment) := by + rw [equation_satisfied, foldedAnswer_flip, equation_satisfied] + +def pairedEquations (i₀ : I) (f : Cube I) : List (Equation (Address i₀)) := + [equation i₀ f, equation i₀ (cubeFlip f)] + +@[simp] theorem pairedEquations_length (i₀ : I) (f : Cube I) : + (pairedEquations i₀ f).length = 2 := rfl + +theorem pairedEquations_ne_nil (i₀ : I) (f : Cube I) : + pairedEquations i₀ f ≠ [] := by simp [pairedEquations] + +theorem pairedEquations_acceptedCount (i₀ : I) (assignment : Address i₀ → Bool) + (f : Cube I) : + (pairedEquations i₀ f).countP (fun e => satisfied e assignment) = 1 := by + simp only [pairedEquations, List.countP_cons, List.countP_nil, equation_satisfied_flip] + cases satisfied (equation i₀ f) assignment <;> rfl + +theorem pairedEquations_failureCount (i₀ : I) (assignment : Address i₀ → Bool) + (f : Cube I) : + (pairedEquations i₀ f).countP (fun e => !(satisfied e assignment)) = 1 := by + simp only [pairedEquations, List.countP_cons, List.countP_nil, equation_satisfied_flip] + cases satisfied (equation i₀ f) assignment <;> rfl + +noncomputable section + +variable [Fintype I] [DecidableEq I] + +def equationAcceptance (i₀ : I) (assignment : Address i₀ → Bool) : ℝ := + 𝔼 f : Cube I, if satisfied (equation i₀ f) assignment then (1 : ℝ) else 0 + +def equationBias (i₀ : I) (assignment : Address i₀ → Bool) : ℝ := + 𝔼 f : Cube I, if satisfied (equation i₀ f) assignment then (1 : ℝ) else -1 + +theorem foldedMean_eq_zero (i₀ : I) (table : HalfCube i₀ → Bool) : + (𝔼 f : Cube I, bitSign (foldedAnswer i₀ table f)) = 0 := by + simpa [coefficient, walsh, bitSign] using foldedAnswer_zero_coefficient i₀ table + +omit [Fintype I] [DecidableEq I] in +theorem equation_indicator (i₀ : I) (assignment : Address i₀ → Bool) (f : Cube I) : + (if satisfied (equation i₀ f) assignment then (1 : ℝ) else 0) = + (1 + bitSign (foldedAnswer i₀ (fun h => assignment (.inl h)) f)) / 2 := by + rw [equation_satisfied] + cases foldedAnswer i₀ (fun h => assignment (.inl h)) f <;> norm_num [bitSign] + +theorem equationAcceptance_eq_half (i₀ : I) (assignment : Address i₀ → Bool) : + equationAcceptance i₀ assignment = 1 / 2 := by + unfold equationAcceptance + simp_rw [equation_indicator, div_eq_mul_inv, ← Finset.expect_mul, + Finset.expect_add_distrib, Fintype.expect_const, foldedMean_eq_zero] + norm_num + +theorem equationBias_eq_zero (i₀ : I) (assignment : Address i₀ → Bool) : + equationBias i₀ assignment = 0 := by + unfold equationBias + have hi (f : Cube I) : + (if satisfied (equation i₀ f) assignment then (1 : ℝ) else -1) = + bitSign (foldedAnswer i₀ (fun h => assignment (.inl h)) f) := by + rw [equation_satisfied] + cases foldedAnswer i₀ (fun h => assignment (.inl h)) f <;> norm_num [bitSign] + simp_rw [hi] + exact foldedMean_eq_zero i₀ _ + +theorem mapped_equationAcceptance_eq_half {Name : Type} (i₀ : I) + (rename : Address i₀ → Name) (assignment : Name → Bool) : + (𝔼 f : Cube I, if satisfied (mapEquation rename (equation i₀ f)) assignment + then (1 : ℝ) else 0) = 1 / 2 := by + simp only [satisfied_mapEquation] + exact equationAcceptance_eq_half i₀ (assignment ∘ rename) + +end +end EmptyContext +end MinUncutGames.Foundations.Hastad + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/FourierResponse.lean b/lean/OAI/Computability/MinUncut/PCP/FourierResponse.lean new file mode 100644 index 0000000000000000000000000000000000000000..e2b41cef01efb990809575d64be2bf9b73f304ff --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/FourierResponse.lean @@ -0,0 +1,158 @@ +import Mathlib +import OAI.Computability.MinUncut.Games.OuterQuestions +import OAI.Computability.MinUncut.Encoding.Decoder + +namespace OAI + +section +noncomputable section + +namespace MinUncutGames.Foundations.Hastad + +open scoped BigOperators +open Finset +open MinUncutGames.Foundations.Games + +variable {I J : Type*} [Fintype I] [DecidableEq I] + [Fintype J] [DecidableEq J] + +def supportResponse (fallback : I) (s : Cube I) : FiniteDistribution I where + weight i := if (support s).Nonempty then + if i ∈ support s then 1 / ((support s).card : ℝ) else 0 + else if i = fallback then 1 else 0 + nonnegative i := by + split_ifs <;> positivity + normalized := by + by_cases hs : (support s).Nonempty + · have hc : ((support s).card : ℝ) ≠ 0 := + ne_of_gt (Nat.cast_pos.mpr (Finset.card_pos.mpr hs)) + simp [hs, hc] + · simp [hs] + +theorem supportResponse_expectation (fallback : I) (s : Cube I) (H : I → ℝ) + (hs : (support s).Nonempty) : + (supportResponse fallback s).expectation H = + (∑ i ∈ support s, H i) / ((support s).card : ℝ) := by + simp only [FiniteDistribution.expectation, supportResponse, hs, ite_true] + simp_rw [ite_mul, zero_mul] + rw [Finset.sum_ite_mem] + simp only [div_eq_mul_inv, one_mul, Finset.univ_inter] + rw [← Finset.mul_sum] + ring + +def fourierResponse (fallback : I) (F : Cube I → Bool) : FiniteDistribution I where + weight i := ∑ s, coefficient (fun f => bitSign (F f)) s ^ 2 * + (supportResponse fallback s).weight i + nonnegative i := Finset.sum_nonneg fun s _ => + mul_nonneg (sq_nonneg _) ((supportResponse fallback s).nonnegative i) + normalized := by + rw [Finset.sum_comm] + simp_rw [← Finset.mul_sum, FiniteDistribution.normalized, mul_one] + exact sign_parseval F + +theorem fourierResponse_expectation (fallback : I) (F : Cube I → Bool) + (H : I → ℝ) : + (fourierResponse fallback F).expectation H = + ∑ s, coefficient (fun f => bitSign (F f)) s ^ 2 * + (supportResponse fallback s).expectation H := by + unfold FiniteDistribution.expectation fourierResponse + simp_rw [Finset.sum_mul] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro s _ + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro i _ + ring + +theorem response_expectation_nonnegative {K : Type*} [Fintype K] + (law : FiniteDistribution K) (H : K → ℝ) (hH : ∀ k, 0 ≤ H k) : + 0 ≤ law.expectation H := + Finset.sum_nonneg fun k _ => mul_nonneg (law.nonnegative k) (hH k) + +def responseAgreement (π : J → I) (fallbackI : I) (fallbackJ : J) + (A : Cube I → Bool) (B : Cube J → Bool) : ℝ := + (fourierResponse fallbackI A).expectation fun i => + (fourierResponse fallbackJ B).expectation fun j => if π j = i then 1 else 0 + +def validResponseAgreement (valid : J → Bool) (π : J → I) + (fallbackI : I) (fallbackJ : J) + (A : Cube I → Bool) (B : Cube J → Bool) : ℝ := + (fourierResponse fallbackI A).expectation fun i => + (fourierResponse fallbackJ B).expectation fun j => + if π j = i ∧ valid j = true then 1 else 0 + +theorem supportResponse_validAgreement (valid : J → Bool) (π : J → I) + (fallbackI : I) (fallbackJ : J) (a : Cube I) (b : Cube J) + (ha : (support a).Nonempty) (hb : (support b).Nonempty) : + (supportResponse fallbackI a).expectation (fun i => + (supportResponse fallbackJ b).expectation (fun j => + if π j = i ∧ valid j = true then 1 else 0)) = + validAgreementProbability valid π a b := by + rw [supportResponse_expectation fallbackI a _ ha] + simp_rw [supportResponse_expectation fallbackJ b _ hb, Finset.sum_boole] + unfold validAgreementProbability + simp only [div_eq_mul_inv] + rw [← Finset.sum_mul] + ring + +theorem validAgreement_le_supportResponses (valid : J → Bool) (π : J → I) + (fallbackI : I) (fallbackJ : J) (a : Cube I) (b : Cube J) : + validAgreementProbability valid π a b ≤ + (supportResponse fallbackI a).expectation (fun i => + (supportResponse fallbackJ b).expectation (fun j => + if π j = i ∧ valid j = true then 1 else 0)) := by + by_cases ha : (support a).Nonempty + · by_cases hb : (support b).Nonempty + · exact le_of_eq (supportResponse_validAgreement valid π fallbackI fallbackJ a b ha hb).symm + · have he : support b = ∅ := Finset.not_nonempty_iff_eq_empty.mp hb + simp only [validAgreementProbability, he, Finset.card_empty, Nat.cast_zero, + mul_zero, div_zero] + apply response_expectation_nonnegative + intro i + apply response_expectation_nonnegative + intro j + split_ifs <;> norm_num + · have he : support a = ∅ := Finset.not_nonempty_iff_eq_empty.mp ha + simp only [validAgreementProbability, he, Finset.sum_empty, Finset.card_empty, + Nat.cast_zero, zero_mul, div_zero] + apply response_expectation_nonnegative + intro i + apply response_expectation_nonnegative + intro j + split_ifs <;> norm_num + +theorem validDecoderSuccess_le_response (valid : J → Bool) (π : J → I) + (fallbackI : I) (fallbackJ : J) (A : Cube I → Bool) (B : Cube J → Bool) : + validDecoderSuccess valid π A B ≤ + validResponseAgreement valid π fallbackI fallbackJ A B := by + unfold validDecoderSuccess validResponseAgreement + rw [FiniteDistribution.expectation_comm] + rw [fourierResponse_expectation fallbackJ B] + apply Finset.sum_le_sum + intro b _ + apply mul_le_mul_of_nonneg_left _ (sq_nonneg _) + rw [FiniteDistribution.expectation_comm] + rw [fourierResponse_expectation fallbackI A] + apply Finset.sum_le_sum + intro a _ + apply mul_le_mul_of_nonneg_left _ (sq_nonneg _) + exact validAgreement_le_supportResponses valid π fallbackI fallbackJ a b + +theorem conditioned_folded_response_bound (ε : ℝ) (π : J → I) (valid : J → Bool) + (i₀ : I) (tableA : HalfCube i₀ → Bool) + (j₀ : {j : J // valid j = true}) (tableB : HalfCube j₀ → Bool) + (hε : 0 < ε) (hε' : ε ≤ 1 / 2) : + 4 * ε * testBias ε π (fun f => bitSign (foldedAnswer i₀ tableA f)) + (fun g => bitSign (conditionedFoldedAnswer valid j₀ tableB g)) ^ 2 ≤ + validResponseAgreement valid π i₀ j₀.val (foldedAnswer i₀ tableA) + (conditionedFoldedAnswer valid j₀ tableB) := + (conditioned_folded_decoder_bound ε π valid i₀ tableA j₀ tableB hε hε').trans + (validDecoderSuccess_le_response valid π i₀ j₀.val _ _) + +end MinUncutGames.Foundations.Hastad + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/Game.lean b/lean/OAI/Computability/MinUncut/PCP/Game.lean new file mode 100644 index 0000000000000000000000000000000000000000..a0f632201d12eb13fae2f583986f44bbbea04ceb --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/Game.lean @@ -0,0 +1,869 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.Occurrences +import OAI.Computability.MinUncut.Encoding.GameDecoder +import OAI.Computability.MinUncut.Games.Reindexing + +namespace OAI + +noncomputable section +namespace MinUncutGames.Foundations.Hastad.SourceGame + +open scoped BigOperators +open Target PCP Games SourceContexts + +theorem event_nonempty (F : Formula) (hne : F.clauses ≠ []) : + Nonempty (RandomEvent F) := + ⟨(⟨0, List.length_pos_iff.mpr hne⟩, .first)⟩ + +def eventLaw (F : Formula) (hne : F.clauses ≠ []) : + FiniteDistribution (RandomEvent F) := by + let : Nonempty (RandomEvent F) := event_nonempty F hne + exact FiniteDistribution.uniform _ + +def visibleQuestion (F : Formula) (e : RandomEvent F) : + Fin F.«variables» × Fin F.clauses.length := + (nameAt (clauseAt F e.1) e.2, e.1) + +def baseGame (F : Formula) (hne : F.clauses ≠ []) : + Game (Fin F.«variables») (Fin F.clauses.length) Bool ClauseAnswer where + questions := (eventLaw F hne).pushforward (visibleQuestion F) + accepts := baseAccepts F + +@[simp] theorem baseGame_accepts (F : Formula) (hne : F.clauses ≠ []) + (v : Fin F.«variables») (c : Fin F.clauses.length) (i : Bool) (j : ClauseAnswer) : + (baseGame F hne).accepts v c i j = baseAccepts F v c i j := rfl + +theorem eventLaw_probability (F : Formula) (hne : F.clauses ≠ []) + (P : RandomEvent F → Bool) : + (eventLaw F hne).probability P = + (∑ e : RandomEvent F, if P e then (1 : ℝ) else 0) / + (3 * F.clauses.length : ℕ) := by + classical + simp only [eventLaw, FiniteDistribution.uniform, FiniteDistribution.probability] + simp_rw [div_eq_mul_inv] + rw [Finset.sum_mul] + apply Finset.sum_congr rfl + intro e _ + cases P e <;> simp [RandomEvent, Fintype.card_prod, card_slot, Nat.mul_comm] + +theorem sum_slots (H : Slot → ℝ) : + (∑ s : Slot, H s) = H .first + H .second + H .third := by + have hu : (Finset.univ : Finset Slot) = {.first, .second, .third} := by + ext s + cases s <;> simp + rw [hu] + simp only [Finset.sum_insert, Finset.mem_insert, Finset.mem_singleton, + reduceCtorEq, or_self, not_false_eq_true, Finset.sum_singleton] + ring + +theorem sum_slot_accepts (F : Formula) (alice : AliceStrategy F) + (bob : BobStrategy F) (c : Fin F.clauses.length) : + (∑ s : Slot, if accepts F alice bob (c,s) then (1 : ℝ) else 0) = + (acceptedSlots (clauseAt F c) (alice c) + (honestAnswer (clauseAt F c) bob) : ℕ) := by + rw [sum_slots] + by_cases hs : localSatisfies (clauseAt F c) (alice c) = true + · by_cases h₁ : (alice c).first = bob (clauseAt F c)[0].variableIndex <;> + by_cases h₂ : (alice c).second = bob (clauseAt F c)[1].variableIndex <;> + by_cases h₃ : (alice c).third = bob (clauseAt F c)[2].variableIndex <;> + norm_num [accepts, hs, acceptedSlots, matchingSlots, honestAnswer, answerAt, nameAt, + h₁, h₂, h₃] + · simp [accepts, acceptedSlots, hs] + +theorem failureCount_eq_sum_map (F : Formula) (bob : BobStrategy F) + (cs : List (Fin F.clauses.length)) : + failureCount F bob cs = + (cs.map (fun c => clauseFailure (clauseAt F c) bob)).sum := by + induction cs with + | nil => rfl + | cons c cs ih => simp only [failureCount, List.map_cons, List.sum_cons, ih] + +theorem failureCount_allIndices (F : Formula) (bob : BobStrategy F) : + failureCount F bob (allIndices F) = + ∑ c : Fin F.clauses.length, clauseFailure (clauseAt F c) bob := by + rw [failureCount_eq_sum_map] + unfold allIndices + rw [← List.sum_toFinset _ (List.nodup_finRange _), List.toFinset_finRange] + +theorem verifier_probability_plus_failure (F : Formula) (hne : F.clauses ≠ []) + (alice : AliceStrategy F) (bob : BobStrategy F) : + (eventLaw F hne).probability (accepts F alice bob) + + (failureCount F bob (allIndices F) : ℝ) / (3 * F.clauses.length : ℕ) ≤ 1 := by + have hm : (0 : ℝ) < (3 * F.clauses.length : ℕ) := by + exact_mod_cast Nat.mul_pos (by decide : 0 < 3) (List.length_pos_iff.mpr hne) + have hlocal (c : Fin F.clauses.length) : + (∑ s : Slot, if accepts F alice bob (c,s) then (1 : ℝ) else 0) + + (clauseFailure (clauseAt F c) bob : ℝ) ≤ 3 := by + rw [sum_slot_accepts] + exact_mod_cast local_rejection_bound (clauseAt F c) (alice c) bob + have hsum := Finset.sum_le_sum (fun c (_ : c ∈ (Finset.univ : Finset _)) => hlocal c) + simp only [Finset.sum_add_distrib, Finset.sum_const, Finset.card_univ, + Fintype.card_fin, nsmul_eq_mul] at hsum + rw [eventLaw_probability, failureCount_allIndices] + push_cast + push_cast at hm + rw [Fintype.sum_prod_type, ← add_div] + apply (div_le_one hm).mpr + simpa only [Nat.cast_mul, Nat.cast_ofNat, mul_comm] using hsum + +theorem base_success_le_verifier (F : Formula) (hne : F.clauses ≠ []) + (strategy : Strategy (Fin F.«variables») (Fin F.clauses.length) Bool ClauseAnswer) : + (baseGame F hne).success strategy ≤ + (eventLaw F hne).probability (accepts F strategy.2 strategy.1) := by + unfold Game.success baseGame + rw [FiniteDistribution.probability_pushforward] + apply FiniteDistribution.probability_mono + intro e he + exact baseAccepts_implies_sampled F e.1 e.2 _ _ he + +theorem base_value_le_of_clause_gap (F : Formula) (hne : F.clauses ≠ []) + (δ : ℝ) (hgap : ∀ bob : BobStrategy F, + δ * F.clauses.length ≤ (failureCount F bob (allIndices F) : ℝ)) : + (baseGame F hne).value ≤ 1 - δ / 3 := by + apply (Game.value_le_iff _ _).mpr + intro strategy + have hbase := base_success_le_verifier F hne strategy + have hprob := verifier_probability_plus_failure F hne strategy.2 strategy.1 + have hm : (0 : ℝ) < F.clauses.length := + Nat.cast_pos.mpr (List.length_pos_iff.mpr hne) + have hg : δ / 3 ≤ (failureCount F strategy.1 (allIndices F) : ℝ) / + (3 * F.clauses.length : ℕ) := by + have hden : (0 : ℝ) < (3 * F.clauses.length : ℕ) := by + exact_mod_cast Nat.mul_pos (by decide : 0 < 3) (List.length_pos_iff.mpr hne) + apply (le_div_iff₀ hden).mpr + calc + δ / 3 * (3 * F.clauses.length : ℕ) = δ * F.clauses.length := by push_cast; ring + _ ≤ _ := hgap strategy.1 + linarith + +theorem pushforward_comp {X Y Z : Type*} [Fintype X] [Fintype Y] [Fintype Z] + (μ : FiniteDistribution X) (f : X → Y) (g : Y → Z) : + (μ.pushforward f).pushforward g = μ.pushforward (g ∘ f) := by + classical + apply FiniteDistribution.eq_of_weight_eq + intro z + simp only [FiniteDistribution.pushforward] + calc + _ = ∑ y : Y, ∑ x : X, if f x = y then + (if g y = z then μ.weight x else 0) else 0 := by + apply Finset.sum_congr rfl + intro y _ + by_cases h : g y = z <;> simp [h] + _ = _ := by rw [Finset.sum_comm]; simp + +theorem expectation_pushforward {X Y : Type*} [Fintype X] [Fintype Y] + (μ : FiniteDistribution X) (f : X → Y) (H : Y → ℝ) : + (μ.pushforward f).expectation H = μ.expectation (H ∘ f) := by + classical + simp only [FiniteDistribution.expectation, FiniteDistribution.pushforward, + Finset.sum_mul] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro x _ + simp [ite_mul] + +def repeatedVisible (F : Formula) (u : ℕ) (events : Fin u → RandomEvent F) : + VariableContext F u × ClauseContext F u := + (fun t => nameAt (clauseAt F (events t).1) (events t).2, + fun t => (events t).1) + +theorem repeated_questions (F : Formula) (hne : F.clauses ≠ []) (u : ℕ) : + ((baseGame F hne).repetition u).questions = + ((eventLaw F hne).iid u).pushforward (repeatedVisible F u) := by + change (((eventLaw F hne).pushforward (visibleQuestion F)).iid u).transport + (Game.tupleQuestionEquiv u) = _ + rw [FiniteDistribution.iid_pushforward, ← FiniteDistribution.pushforward_equiv, + pushforward_comp] + rfl + +theorem repeated_expectation (F : Formula) (hne : F.clauses ≠ []) (u : ℕ) + (H : VariableContext F u × ClauseContext F u → ℝ) : + ((baseGame F hne).repetition u).questions.expectation H = + 𝔼 events : Fin u → RandomEvent F, H (repeatedVisible F u events) := by + let : Nonempty (RandomEvent F) := event_nonempty F hne + rw [repeated_questions, expectation_pushforward] + change ((FiniteDistribution.uniform (RandomEvent F)).iid u).expectation _ = _ + rw [FiniteDistribution.iid_uniform, FiniteDistribution.expectation_uniform, + Fintype.expect_eq_sum_div_card] + rfl + +theorem repeated_expectation_split (F : Formula) (hne : F.clauses ≠ []) (u : ℕ) + (H : VariableContext F u × ClauseContext F u → ℝ) : + ((baseGame F hne).repetition u).questions.expectation H = + 𝔼 c : ClauseContext F u, 𝔼 s : SlotContext u, + H (sampledVariables F c s, c) := by + rw [repeated_expectation] + calc + _ = 𝔼 p : ClauseContext F u × SlotContext u, + H (sampledVariables F p.1 p.2, p.1) := + Fintype.expect_equiv + (Game.tupleQuestionEquiv (Q₁ := Fin F.clauses.length) (Q₂ := Slot) u) + _ _ (fun _ => rfl) + _ = _ := SourceTape.expect_prod _ + +def sourceProjectionGame (F : Formula) (hne : F.clauses ≠ []) (u : ℕ) : + Game (VariableContext F u) (ClauseContext F u) (I u) (J u) := + projectionGame ((baseGame F hne).repetition u).questions + (fun v c => pi F c v) (validJ F) + +theorem projection_value_le_repetition (F : Formula) (hne : F.clauses ≠ []) + (u : ℕ) : + (sourceProjectionGame F hne u).value ≤ ((baseGame F hne).repetition u).value := by + apply (Game.value_le_iff _ _).mpr + intro strategy + have h : (sourceProjectionGame F hne u).success strategy ≤ + ((baseGame F hne).repetition u).success strategy := by + apply FiniteDistribution.probability_mono + intro q hq + have hlegal : pi F q.2 q.1 (strategy.2 q.2) = strategy.1 q.1 ∧ + validJ F q.2 (strategy.2 q.2) = true := by + simpa only [Game.wins, sourceProjectionGame, projectionGame, + decide_eq_true_eq] using hq + apply (Game.repetition_accepts_iff _ _ _ _ _ _).mpr + intro t + exact projection_implies_coordinate_accepts F q.2 q.1 + (strategy.1 q.1) (strategy.2 q.2) hlegal.2 hlegal.1 t + exact h.trans (Game.success_le_value _ strategy) + +theorem source_acceptance_le (F : Formula) (hne : F.clauses ≠ []) (u : ℕ) + (ε δ : ℝ) (i₀ : VariableContext F u → I u) + (tableA : ∀ v, HalfCube (i₀ v) → Bool) + (right : ∀ c : ClauseContext F u, ConditionedOracle (validJ F c)) + (hε : 0 < ε) (hε' : ε ≤ 1 / 2) (hδ : 0 ≤ δ) + (hvalue : ((baseGame F hne).repetition u).value ≤ 4 * ε * δ ^ 2) : + (𝔼 events : Fin u → RandomEvent F, + questionAcceptance ε (fun v c => pi F c v) + (fun v => foldedAnswer (i₀ v) (tableA v)) (fun c => (right c).answer) + (repeatedVisible F u events)) ≤ (1 + δ) / 2 := by + rw [← repeated_expectation F hne u] + exact conditionedOracle_acceptance_bound _ ε δ _ (validJ F) i₀ tableA + (fun _ => default) right hε hε' hδ + ((projection_value_le_repetition F hne u).trans hvalue) + +theorem source_acceptance_le_split (F : Formula) (hne : F.clauses ≠ []) (u : ℕ) + (ε δ : ℝ) (i₀ : VariableContext F u → I u) + (tableA : ∀ v, HalfCube (i₀ v) → Bool) + (right : ∀ c : ClauseContext F u, ConditionedOracle (validJ F c)) + (hε : 0 < ε) (hε' : ε ≤ 1 / 2) (hδ : 0 ≤ δ) + (hvalue : ((baseGame F hne).repetition u).value ≤ 4 * ε * δ ^ 2) : + (𝔼 c : ClauseContext F u, 𝔼 s : SlotContext u, + testAcceptance ε (pi F c (sampledVariables F c s)) + (foldedAnswer (i₀ (sampledVariables F c s)) (tableA (sampledVariables F c s))) + (right c).answer) ≤ (1 + δ) / 2 := by + have h := conditionedOracle_acceptance_bound + ((baseGame F hne).repetition u).questions ε δ (fun v c => pi F c v) + (validJ F) i₀ tableA (fun _ => default) right hε hε' hδ + ((projection_value_le_repetition F hne u).trans hvalue) + rw [repeated_expectation_split] at h + exact h + +end MinUncutGames.Foundations.Hastad.SourceGame + +namespace MinUncutGames.Foundations.Hastad.SourceSoundness + +open scoped BigOperators +open Target SourceContexts SourceOccurrences SourceGame + +def leftTable (F : Formula) (u : ℕ) (bits : Fin (nBits F u) → Bool) + (v : VariableContext F u) : HalfCube (leftAnchor u) → Bool := + fun h => bits ((proofEncoding F u).code (.inl (v, h.val))) + +def rightOracle (F : Formula) (u : ℕ) (bits : Fin (nBits F u) → Bool) + (c : ClauseContext F u) : ConditionedOracle (validJ F c) := + match h : rightAnchor F c with + | none => .empty ((rightAnchor_none_iff F c).mp h) + | some j₀ => .stored j₀ + (fun h => bits ((proofEncoding F u).code + (.inr (.inl (c, extendRestricted (validJ F c) h.val))))) + +@[simp] theorem rightOracle_answer (F : Formula) (u : ℕ) + (bits : Fin (nBits F u) → Bool) (c : ClauseContext F u) : + (rightOracle F u bits c).answer = rightResponse F u bits c := by + unfold rightOracle + split <;> simp_all [rightResponse, ConditionedOracle.answer] + +@[simp] theorem leftTable_answer (F : Formula) (u : ℕ) + (bits : Fin (nBits F u) → Bool) (v : VariableContext F u) : + foldedAnswer (leftAnchor u) (leftTable F u bits v) = leftResponse F u bits v := rfl + +theorem sourceList_sound (F : Formula) (hne : F.clauses ≠ []) (u D : ℕ) + (hD : 0 < D) (hDtwo : 2 ≤ D) (δ : ℝ) (hδ : 0 ≤ δ) + (hvalue : ((baseGame F hne).repetition u).value ≤ + 4 * (D : ℝ)⁻¹ * δ ^ 2) + (bits : Fin (nBits F u) → Bool) : + ((sourceList F u D).countP (fun e => MinUncutGames.Reduction.CloneGap.satisfied e bits) : ℝ) / + (sourceList F u D).length ≤ (1 + δ) / 2 := by + rw [sourceList_nonempty F u D hne, rawSourceList_acceptance F u D hD] + have hε : (0 : ℝ) < (D : ℝ)⁻¹ := inv_pos.mpr (Nat.cast_pos.mpr hD) + have hε' : (D : ℝ)⁻¹ ≤ (1 : ℝ) / 2 := by + have hd : (2 : ℝ) ≤ D := by exact_mod_cast hDtwo + simpa only [one_div] using + (inv_le_inv₀ (Nat.cast_pos.mpr hD) (by norm_num : (0 : ℝ) < 2)).mpr hd + have h := source_acceptance_le_split F hne u ((D : ℝ)⁻¹) δ + (fun _ => leftAnchor u) (leftTable F u bits) (rightOracle F u bits) + hε hε' hδ hvalue + simpa only [leftTable_answer, rightOracle_answer] using h + +theorem sourceList_sound_rat (F : Formula) (hne : F.clauses ≠ []) (u D : ℕ) + (hD : 0 < D) (hDtwo : 2 ≤ D) (δ : ℚ) (hδ : 0 ≤ δ) + (hvalue : ((baseGame F hne).repetition u).value ≤ + 4 * (D : ℝ)⁻¹ * (δ : ℝ) ^ 2) + (bits : Fin (nBits F u) → Bool) : + ((sourceList F u D).countP (fun e => MinUncutGames.Reduction.CloneGap.satisfied e bits) : ℚ) / + (sourceList F u D).length ≤ (1 + δ) / 2 := by + have h := sourceList_sound F hne u D hD hDtwo (δ : ℝ) + (by exact_mod_cast hδ) hvalue bits + apply (Rat.cast_le (K := ℝ)).mp + push_cast + exact h + +end MinUncutGames.Foundations.Hastad.SourceSoundness + +end +namespace MinUncutGames.Foundations.Hastad.SourceHonest + +open MinUncutGames.Reduction.CloneGap +open MinUncutGames.Reduction.FiniteNoise +open scoped BigOperators + +def taggedAssignment {V C I J : Type} (left : V → I) (right : C → J) : + (V × Cube I) ⊕ ((C × Cube J) ⊕ Unit) → Bool + | .inl (v, f) => f (left v) + | .inr (.inl (c, g)) => g (right c) + | .inr (.inr _) => false + +@[simp] theorem taggedAssignment_left {V C I J : Type} + (left : V → I) (right : C → J) (v : V) (f : Cube I) : + taggedAssignment left right (.inl (v, f)) = f (left v) := rfl + +@[simp] theorem taggedAssignment_right {V C I J : Type} + (left : V → I) (right : C → J) (c : C) (g : Cube J) : + taggedAssignment left right (.inr (.inl (c, g))) = g (right c) := rfl + +theorem taggedAssignment_right_restriction {V C I J : Type} + (left : V → I) (right : C → J) (c : C) (valid : J → Bool) + (honest : {j : J // valid j = true}) (hright : right c = honest.val) + (extend : Cube {j : J // valid j = true} → Cube J) + (hextend : ∀ (g : Cube {j : J // valid j = true}) + (j : {j : J // valid j = true}), extend g j.val = g j) + (j₀ : {j : J // valid j = true}) (h : HalfCube j₀) : + taggedAssignment left right (.inr (.inl (c, extend h.val))) = h.val honest := by + change extend h.val (right c) = h.val honest + rw [hright] + exact hextend h.val honest + +section Local + +variable {I J : Type} [Fintype I] [DecidableEq I] [Fintype J] [DecidableEq J] + +omit [Fintype I] [DecidableEq I] [Fintype J] [DecidableEq J] in +theorem conditioned_equation_honest_satisfied + (valid : J → Bool) (π : J → I) (i₀ i : I) + (j₀ j : {j : J // valid j = true}) (hπ : π j.val = i) + (f : Cube I) (g μ : Cube J) : + satisfied (FoldedEquation.conditionedEquation valid π i₀ j₀ f g μ) + (FoldedEquation.storedAssignment (fun h => h.val i) (fun h => h.val j)) = + !(μ j.val) := by + rw [FoldedEquation.conditionedEquation_satisfied, foldedAnswer_dictator, + conditionedFoldedAnswer_dictator, conditionedFoldedAnswer_dictator, + dictator_test_parity π i j.val hπ] + +omit [Fintype I] [DecidableEq I] [Fintype J] [DecidableEq J] in +theorem mapped_conditioned_equation_honest_satisfied {Name : Type} + (valid : J → Bool) (π : J → I) (i₀ i : I) + (j₀ j : {j : J // valid j = true}) (hπ : π j.val = i) + (rename : FoldedEquation.Address i₀ j₀ → Name) (assignment : Name → Bool) + (hleft : ∀ h, assignment (rename (.inl h)) = h.val i) + (hright : ∀ h, assignment (rename (.inr h)) = h.val j) + (f : Cube I) (g μ : Cube J) : + satisfied (mapEquation rename + (FoldedEquation.conditionedEquation valid π i₀ j₀ f g μ)) assignment = + !(μ j.val) := by + have hlocal : assignment ∘ rename = + FoldedEquation.storedAssignment (fun h => h.val i) (fun h => h.val j) := by + funext a + cases a with + | inl h => exact hleft h + | inr h => exact hright h + rw [satisfied_mapEquation, hlocal] + exact conditioned_equation_honest_satisfied valid π i₀ i j₀ j hπ f g μ + +theorem tapeAcceptance_conditioned_dictators {D : ℕ} (positive : 0 < D) + (valid : J → Bool) (π : J → I) (i₀ i : I) + (j₀ j : {j : J // valid j = true}) (hπ : π j.val = i) : + SourceTape.tapeAcceptance D π + (foldedAnswer i₀ (fun h => h.val i)) + (conditionedFoldedAnswer valid j₀ (fun h => h.val j)) = + 1 - (D : ℝ)⁻¹ := by + rw [SourceTape.tapeAcceptance_eq_realizedTestAcceptance] + exact realizedTestAcceptance_folded_conditioned_dictators positive π i₀ i valid j₀ j hπ + +end Local + +section NumberedStorage + +open SourceOccurrences + +variable {V C I J : Type} + +theorem numbered_assignment_restriction + (vE : Encoding V) (cE : Encoding C) (iE : Encoding I) (jE : Encoding J) + (left : V → I) (right : C → J) (v : V) (c : C) + (valid : J → Bool) (i₀ : I) (j₀ j : {j : J // valid j = true}) + (hright : right c = j.val) : + assignmentOfKey vE cE iE jE (taggedAssignment left right) ∘ + localAddress vE cE iE jE v c valid i₀ j₀ = + FoldedEquation.storedAssignment (fun h => h.val (left v)) (fun h => h.val j) := by + funext a + cases a with + | inl h => + simp only [Function.comp_apply, localAddress, assignmentOfKey_code, + taggedAssignment_left, FoldedEquation.storedAssignment, Sum.elim_inl] + | inr h => + simp only [Function.comp_apply, localAddress, assignmentOfKey_code, + taggedAssignment_right, hright, extendRestricted_valid, + FoldedEquation.storedAssignment, Sum.elim_inr] + +variable [Fintype I] [DecidableEq I] [Fintype J] [DecidableEq J] + +omit [Fintype I] [DecidableEq I] [Fintype J] [DecidableEq J] in +theorem conditionedOccurrence_honest_satisfied + (vE : Encoding V) (cE : Encoding C) (iE : Encoding I) (jE : Encoding J) + (left : V → I) (right : C → J) (v : V) (c : C) + (valid : J → Bool) (π : J → I) (i₀ : I) + (j₀ j : {j : J // valid j = true}) + (hright : right c = j.val) (hπ : π j.val = left v) + (f : Cube I) (g μ : Cube J) : + satisfied (conditionedOccurrence vE cE iE jE v c valid π i₀ j₀ f g μ) + (assignmentOfKey vE cE iE jE (taggedAssignment left right)) = !(μ j.val) := by + rw [conditionedOccurrence, satisfied_mapEquation, + numbered_assignment_restriction vE cE iE jE left right v c valid i₀ j₀ j hright] + exact conditioned_equation_honest_satisfied valid π i₀ (left v) j₀ j hπ f g μ + +theorem conditionedOccurrenceList_honest_acceptance {D : ℕ} (positive : 0 < D) + (vE : Encoding V) (cE : Encoding C) (iE : Encoding I) (jE : Encoding J) + (left : V → I) (right : C → J) (v : V) (c : C) + (valid : J → Bool) (π : J → I) (i₀ : I) + (j₀ j : {j : J // valid j = true}) + (hright : right c = j.val) (hπ : π j.val = left v) + (tape : Encoding (SourceTape.TestTape I J D)) : + let equations := occurrenceList tape (fun t => + conditionedOccurrence vE cE iE jE v c valid π i₀ j₀ + t.1 t.2.2 (realizedNoise t.2.1)) + ((equations.countP (fun e => satisfied e + (assignmentOfKey vE cE iE jE (taggedAssignment left right)))) : ℝ) / + equations.length = 1 - (D : ℝ)⁻¹ := by + dsimp only + rw [occurrenceList_acceptance] + calc + _ = SourceTape.tapeAcceptance D π (fun f => f (left v)) (fun g => g j.val) := by + unfold SourceTape.tapeAcceptance + apply Finset.expect_congr rfl + intro t _ + rw [conditionedOccurrence_honest_satisfied vE cE iE jE left right v c + valid π i₀ j₀ j hright hπ, dictator_test_parity π (left v) j.val hπ] + cases realizedNoise t.2.1 j.val <;> rfl + _ = _ := by + rw [SourceTape.tapeAcceptance_eq_realizedTestAcceptance] + exact realizedTestAcceptance_dictator positive π (left v) j.val hπ + +end NumberedStorage + + +open SourceContexts +open SourceOccurrences + +def honestGlobal (F : Target.Formula) (u : ℕ) + (assignment : Fin F.«variables» → Bool) : + (VariableContext F u × Cube (I u)) ⊕ + ((ClauseContext F u × Cube (J u)) ⊕ Unit) → Bool := + taggedAssignment (fun v => honestI F v assignment) (fun c => honestJ F c assignment) + +def honestBits (F : Target.Formula) (u : ℕ) + (assignment : Fin F.«variables» → Bool) : Fin (nBits F u) → Bool := + assignmentOfKey (variableEncoding F u) (clauseEncoding F u) (iEncoding u) + (jEncoding u) (honestGlobal F u assignment) + +@[simp] theorem honestBits_code (F : Target.Formula) (u : ℕ) + (assignment : Fin F.«variables» → Bool) + (key : GlobalKey (VariableContext F u) (ClauseContext F u) (I u) (J u)) : + honestBits F u assignment ((proofEncoding F u).code key) = + honestGlobal F u assignment key := + assignmentOfKey_code (variableEncoding F u) (clauseEncoding F u) + (iEncoding u) (jEncoding u) (honestGlobal F u assignment) key + +@[simp] theorem honestBits_dummy (F : Target.Formula) (u : ℕ) + (assignment : Fin F.«variables» → Bool) : + honestBits F u assignment (dummyIndex F u) = false := by + rw [dummyIndex, honestBits_code] + rfl + +def honestValidJ (F : Target.Formula) {u : ℕ} (c : ClauseContext F u) + (assignment : Fin F.«variables» → Bool) + (hs : ∀ clause ∈ F.clauses, clause.eval assignment = true) : + {j : J u // validJ F c j = true} := + ⟨honestJ F c assignment, honestJ_valid F c assignment hs⟩ + +theorem validJ_nonempty_of_satisfying (F : Target.Formula) {u : ℕ} + (c : ClauseContext F u) (assignment : Fin F.«variables» → Bool) + (hs : ∀ clause ∈ F.clauses, clause.eval assignment = true) : + Nonempty {j : J u // validJ F c j = true} := + ⟨honestValidJ F c assignment hs⟩ + +theorem leftResponse_honest (F : Target.Formula) (u : ℕ) + (assignment : Fin F.«variables» → Bool) (v : VariableContext F u) : + leftResponse F u (honestBits F u assignment) v = + fun f => f (honestI F v assignment) := by + funext f + simp only [leftResponse, honestBits_code, honestGlobal, taggedAssignment, + foldedAnswer_dictator] + +theorem rightResponse_honest (F : Target.Formula) (u : ℕ) + (assignment : Fin F.«variables» → Bool) + (hs : ∀ clause ∈ F.clauses, clause.eval assignment = true) + (c : ClauseContext F u) : + rightResponse F u (honestBits F u assignment) c = + fun g => g (honestJ F c assignment) := by + funext g + cases ha : rightAnchor F c with + | none => + have hf := (rightAnchor_none_iff F c).mp ha (honestJ F c assignment) + rw [honestJ_valid F c assignment hs] at hf + cases hf + | some j₀ => + simp only [rightResponse, ha, honestBits_code, honestGlobal, taggedAssignment] + have ht : (fun h : HalfCube j₀ => + extendRestricted (validJ F c) h.val (honestJ F c assignment)) = + fun h => h.val (honestValidJ F c assignment hs) := by + funext h + exact extendRestricted_valid (validJ F c) h.val (honestValidJ F c assignment hs) + rw [ht] + exact conditionedFoldedAnswer_dictator (validJ F c) j₀ + (honestValidJ F c assignment hs) g + +theorem context_tapeAcceptance {D : ℕ} (positive : 0 < D) + (F : Target.Formula) {u : ℕ} (c : ClauseContext F u) (s : SlotContext u) + (assignment : Fin F.«variables» → Bool) + (hs : ∀ clause ∈ F.clauses, clause.eval assignment = true) + (i₀ : I u) (j₀ : {j : J u // validJ F c j = true}) : + SourceTape.tapeAcceptance D (pi F c (sampledVariables F c s)) + (foldedAnswer i₀ (fun h => h.val (honestI F (sampledVariables F c s) assignment))) + (conditionedFoldedAnswer (validJ F c) j₀ + (fun h => h.val (honestValidJ F c assignment hs))) = + 1 - (D : ℝ)⁻¹ := by + exact tapeAcceptance_conditioned_dictators positive (validJ F c) + (pi F c (sampledVariables F c s)) i₀ _ j₀ _ + (pi_honest_sampled F c s assignment) + +theorem sourceEquation_honest_satisfied (F : Target.Formula) (u D : ℕ) + (assignment : Fin F.«variables» → Bool) + (hs : ∀ clause ∈ F.clauses, clause.eval assignment = true) + (p : SourceIndex F u D) : + satisfied (sourceEquation F u D p) (honestBits F u assignment) = + !(realizedNoise p.2.2.1 (honestJ F p.1.1 assignment)) := by + simp only [sourceEquation, contextEquation_satisfied, leftResponse_honest, + rightResponse_honest F u assignment hs] + rw [dictator_test_parity _ _ _ (pi_honest_sampled F p.1.1 p.1.2 assignment)] + +theorem rawSourceList_honest_acceptance (F : Target.Formula) (u D : ℕ) + (hD : 0 < D) (hF : F.clauses ≠ []) + (assignment : Fin F.«variables» → Bool) + (hs : ∀ clause ∈ F.clauses, clause.eval assignment = true) : + ((rawSourceList F u D).countP + (fun e => satisfied e (honestBits F u assignment)) : ℝ) / + (rawSourceList F u D).length = 1 - (D : ℝ)⁻¹ := by + have hc : 0 < F.clauses.length := List.length_pos_iff.mpr hF + let : Nonempty (Fin F.clauses.length) := ⟨⟨0, hc⟩⟩ + rw [rawSourceList_acceptance F u D hD] + have heq (c : ClauseContext F u) (s : SlotContext u) : + testAcceptance ((D : ℝ)⁻¹) (pi F c (sampledVariables F c s)) + (leftResponse F u (honestBits F u assignment) (sampledVariables F c s)) + (rightResponse F u (honestBits F u assignment) c) = 1 - (D : ℝ)⁻¹ := by + rw [leftResponse_honest, rightResponse_honest F u assignment hs] + exact testAcceptance_dictator _ _ _ _ (pi_honest_sampled F c s assignment) + simp_rw [heq] + simp only [Fintype.expect_const] + +theorem sourceList_honest_acceptance_nonempty (F : Target.Formula) (u D : ℕ) + (hD : 0 < D) (hF : F.clauses ≠ []) + (assignment : Fin F.«variables» → Bool) + (hs : ∀ clause ∈ F.clauses, clause.eval assignment = true) : + ((sourceList F u D).countP + (fun e => satisfied e (honestBits F u assignment)) : ℝ) / + (sourceList F u D).length = 1 - (D : ℝ)⁻¹ := by + rw [sourceList_nonempty F u D hF] + exact rawSourceList_honest_acceptance F u D hD hF assignment hs + +theorem sourceList_honest_acceptance (F : Target.Formula) (u D : ℕ) + (hD : 0 < D) (assignment : Fin F.«variables» → Bool) + (hs : ∀ clause ∈ F.clauses, clause.eval assignment = true) : + 1 - (D : ℝ)⁻¹ ≤ ((sourceList F u D).countP + (fun e => satisfied e (honestBits F u assignment)) : ℝ) / + (sourceList F u D).length := by + by_cases hF : F.clauses = [] + · rw [sourceList_empty F u D hF] + simp only [List.countP_cons, List.countP_nil, emptyFormulaEquation_satisfied, + honestBits_dummy, Bool.not_false, ↓reduceIte, + Nat.zero_add, Nat.cast_one, List.length_cons, List.length_nil, div_one] + exact sub_le_self _ (inv_nonneg.mpr (Nat.cast_nonneg D)) + · exact (sourceList_honest_acceptance_nonempty F u D hD hF assignment hs).ge + +theorem sourceList_honest_acceptance_rat (F : Target.Formula) (u D : ℕ) + (hD : 0 < D) (assignment : Fin F.«variables» → Bool) + (hs : ∀ clause ∈ F.clauses, clause.eval assignment = true) : + 1 - (D : ℚ)⁻¹ ≤ ((sourceList F u D).countP + (fun e => satisfied e (honestBits F u assignment)) : ℚ) / + (sourceList F u D).length := by + apply (Rat.cast_le (K := ℝ)).mp + simpa only [Rat.cast_sub, Rat.cast_one, Rat.cast_inv, Rat.cast_natCast, Rat.cast_div] using + sourceList_honest_acceptance F u D hD assignment hs + +theorem sourceList_honest_acceptance_nonempty_rat (F : Target.Formula) (u D : ℕ) + (hD : 0 < D) (hF : F.clauses ≠ []) + (assignment : Fin F.«variables» → Bool) + (hs : ∀ clause ∈ F.clauses, clause.eval assignment = true) : + ((sourceList F u D).countP + (fun e => satisfied e (honestBits F u assignment)) : ℚ) / + (sourceList F u D).length = 1 - (D : ℚ)⁻¹ := by + apply Rat.cast_injective (α := ℝ) + simpa only [Rat.cast_sub, Rat.cast_one, Rat.cast_inv, Rat.cast_natCast, Rat.cast_div] using + sourceList_honest_acceptance_nonempty F u D hD hF assignment hs + + +end MinUncutGames.Foundations.Hastad.SourceHonest + +namespace MinUncutGames.Soundness.RepetitionUpper + +def bernoulliAverage (p : Rat) : Nat → (Nat → Rat) → Rat + | 0, f => f 0 + | n + 1, f => + (1 - p) * bernoulliAverage p n f + + p * bernoulliAverage p n (fun k => f (k + 1)) + +theorem bernoulliAverage_scale (p c : Rat) (n : Nat) (f : Nat → Rat) : + bernoulliAverage p n (fun k => c * f k) = c * bernoulliAverage p n f := by + induction n generalizing f with + | zero => rfl + | succ n ih => + simp only [bernoulliAverage, ih] + grind + +theorem bernoulliAverage_geometric (p a : Rat) (n : Nat) : + bernoulliAverage p n (fun k => a ^ k) = (1 - p * (1 - a)) ^ n := by + induction n with + | zero => simp [bernoulliAverage] + | succ n ih => + simp only [bernoulliAverage] + have hs : (fun k : Nat => a ^ (k + 1)) = fun k => a * a ^ k := by + funext k + rw [Rat.pow_succ, Rat.mul_comm] + rw [hs, bernoulliAverage_scale, ih, Rat.pow_succ] + grind + +theorem bernoulliAverage_mono (p : Rat) (hp : 0 ≤ p) (hp' : p ≤ 1) + (n : Nat) (f g : Nat → Rat) (h : ∀ k, f k ≤ g k) : + bernoulliAverage p n f ≤ bernoulliAverage p n g := by + induction n generalizing f g with + | zero => exact h 0 + | succ n ih => + have hleft := ih f g h + have hright := ih (fun k => f (k + 1)) (fun k => g (k + 1)) + (fun k => h (k + 1)) + have hnp : 0 ≤ 1 - p := by grind + have hl := Rat.mul_le_mul_of_nonneg_left hleft hnp + have hr := Rat.mul_le_mul_of_nonneg_left hright hp + simp only [bernoulliAverage] + grind + +theorem success_le_geometric + (p a success : Rat) (n : Nat) (conditionalSuccess : Nat → Rat) + (hp : 0 ≤ p) (hp' : p ≤ 1) + (conditional : ∀ k, conditionalSuccess k ≤ a ^ k) + (averaged : success ≤ bernoulliAverage p n conditionalSuccess) : + success ≤ (1 - p * (1 - a)) ^ n := by + have h := bernoulliAverage_mono p hp hp' n conditionalSuccess + (fun k => a ^ k) conditional + rw [bernoulliAverage_geometric] at h + exact Rat.le_trans averaged h + +theorem pow_mono_nonneg (x y : Rat) (hx : 0 ≤ x) (hxy : x ≤ y) (n : Nat) : + x ^ n ≤ y ^ n := by + induction n with + | zero => simp + | succ n ih => + have hy : 0 ≤ y := Rat.le_trans hx hxy + have hp : 0 ≤ x ^ n := Rat.pow_nonneg hx + have h₁ := Rat.mul_le_mul_of_nonneg_left hxy hp + have h₂ := Rat.mul_le_mul_of_nonneg_right ih hy + simp only [Rat.pow_succ] + exact Rat.le_trans h₁ h₂ + +def zeroProbability (d : Nat) : Rat := (1 / 2 : Rat) ^ d + +theorem zeroProbability_nonneg (d : Nat) : 0 ≤ zeroProbability d := by + exact Rat.pow_nonneg (by grind) + +theorem zeroProbability_le_one (d : Nat) : zeroProbability d ≤ 1 := by + induction d with + | zero => simp [zeroProbability] + | succ d ih => + have hp := zeroProbability_nonneg d + simp only [zeroProbability, Rat.pow_succ] at * + grind + +theorem zeroProbability_antitone (d L : Nat) (hd : d ≤ L) : + zeroProbability L ≤ zeroProbability d := by + induction L with + | zero => + have : d = 0 := by omega + subst d + exact Rat.le_refl + | succ L ih => + by_cases heq : d = L + 1 + · subst d + exact Rat.le_refl + · have hdL : d ≤ L := by omega + have h := ih hdL + have hp := zeroProbability_nonneg L + have hs : zeroProbability (L + 1) ≤ zeroProbability L := by + simp only [zeroProbability, Rat.pow_succ] at * + grind + exact Rat.le_trans hs h + +theorem geometric_le_dimension_bound (d L n : Nat) (hd : d ≤ L) + (a : Rat) (ha : 0 ≤ a) (ha' : a ≤ 1) : + (1 - zeroProbability d * (1 - a)) ^ n ≤ + (1 - zeroProbability L * (1 - a)) ^ n := by + have hp := zeroProbability_nonneg d + have hp' := zeroProbability_le_one d + have hdL := zeroProbability_antitone d L hd + have hna : 0 ≤ 1 - a := by grind + have hprod := Rat.mul_le_mul_of_nonneg_right hdL hna + have hnprod := Rat.mul_le_mul_of_nonneg_right hp' hna + apply pow_mono_nonneg + · grind + · grind + +theorem projection_upper_bound + (d L n : Nat) (hd : d ≤ L) (a success : Rat) + (ha : 0 ≤ a) (ha' : a ≤ 1) (conditionalSuccess : Nat → Rat) + (conditional : ∀ k, conditionalSuccess k ≤ a ^ k) + (averaged : success ≤ bernoulliAverage (zeroProbability d) n conditionalSuccess) : + success ≤ (1 - zeroProbability L * (1 - a)) ^ n := by + have hs := success_le_geometric (zeroProbability d) a success n + conditionalSuccess (zeroProbability_nonneg d) (zeroProbability_le_one d) + conditional averaged + exact Rat.le_trans hs (geometric_le_dimension_bound d L n hd a ha ha') + +def decoderThreshold (theta : Rat) (q : Nat) : Rat := theta ^ 3 / (64 * (q : Rat)) + +theorem decoderThreshold_pos (theta : Rat) (q : Nat) + (htheta : 0 < theta) (hq : 0 < q) : 0 < decoderThreshold theta q := by + have hq' : (0 : Rat) < (q : Rat) := Rat.natCast_pos.mpr hq + have ht := Rat.pow_pos (n := 3) htheta + have hd : (0 : Rat) < 64 * (q : Rat) := by grind + unfold decoderThreshold + apply (Rat.lt_div_iff hd).mpr + simpa using ht + +theorem exists_pos_nat_gt (x : Rat) : ∃ n : Nat, 0 < n ∧ x < (n : Rat) := by + refine ⟨x.ceil.toNat + 1, by omega, ?_⟩ + have hceil := Rat.le_ceil (x := x) + have hint : x.ceil ≤ (x.ceil.toNat : Int) := by omega + have hcast := Rat.intCast_le_intCast.mpr hint + simp only [Rat.intCast_natCast] at hcast + rw [Rat.natCast_add, Rat.natCast_ofNat] + grind + +theorem power_mul_growth_le_one (b : Rat) (hb : 0 ≤ b) (hb' : b ≤ 1) + (n : Nat) : b ^ n * (1 + (n : Rat) * (1 - b)) ≤ 1 := by + induction n with + | zero => + simp only [Rat.pow_zero, Rat.natCast_ofNat, Rat.zero_mul, Rat.add_zero, Rat.one_mul] + exact Rat.le_refl + | succ n ih => + have hn := Rat.natCast_nonneg (a := n) + have hc : 0 ≤ 1 - b := by grind + have hnc : 0 ≤ ((n : Rat) + 1) * (1 - b) := + Rat.mul_nonneg (by grind) hc + have hscaled := Rat.mul_le_mul_of_nonneg_right hb' hnc + have hstep : b * (1 + ((n : Rat) + 1) * (1 - b)) ≤ + 1 + (n : Rat) * (1 - b) := by grind + have hprod := Rat.mul_le_mul_of_nonneg_left hstep (Rat.pow_nonneg (n := n) hb) + simp only [Rat.pow_succ, Rat.natCast_add, Rat.natCast_ofNat] + grind + +theorem exists_power_lt (b threshold : Rat) (hb : 0 ≤ b) (hb' : b < 1) + (ht : 0 < threshold) : ∃ n : Nat, 0 < n ∧ b ^ n < threshold := by + have hc : 0 < 1 - b := by grind + have hden : 0 < threshold * (1 - b) := Rat.mul_pos ht hc + obtain ⟨n, hn, hlarge⟩ := exists_pos_nat_gt (1 / (threshold * (1 - b))) + refine ⟨n, hn, ?_⟩ + have hlarge' := (Rat.div_lt_iff hden).mp hlarge + have hn' := Rat.natCast_nonneg (a := n) + have hg : 0 ≤ 1 + (n : Rat) * (1 - b) := by + have h := Rat.mul_nonneg hn' (Rat.le_of_lt hc) + grind + have hbnd := power_mul_growth_le_one b hb (Rat.le_of_lt hb') n + apply Rat.not_le.mp + intro hbad + have hmul := Rat.mul_le_mul_of_nonneg_right hbad hg + grind + +theorem zeroProbability_pos (d : Nat) : 0 < zeroProbability d := by + exact Rat.pow_pos (by grind) + +theorem exists_repetition_length (L q : Nat) (a theta : Rat) + (ha : 0 ≤ a) (ha' : a < 1) (htheta : 0 < theta) (hq : 0 < q) : + ∃ t : Nat, 0 < t ∧ + (1 - zeroProbability L * (1 - a)) ^ t < decoderThreshold theta q := by + have hp := zeroProbability_pos L + have hp' := zeroProbability_le_one L + have hc : 0 < 1 - a := by grind + have hmul := Rat.mul_le_mul_of_nonneg_right hp' (Rat.le_of_lt hc) + have hpos := Rat.mul_pos hp hc + apply exists_power_lt + · grind + · grind + · exact decoderThreshold_pos theta q htheta hq + +theorem soundness_of_bounds + {Labeling Strategy : Type} (acceptance : Labeling → Rat) + (success : Strategy → Rat) (delta lower upperBound : Rat) + (extraction : ∀ labeling, delta < acceptance labeling → + ∃ strategy, lower ≤ success strategy) + (upper : ∀ strategy, success strategy ≤ upperBound) + (gap : upperBound < lower) : + ∀ labeling, acceptance labeling ≤ delta := by + intro labeling + apply Rat.not_lt.mp + intro hbad + obtain ⟨strategy, hlow⟩ := extraction labeling hbad + have h : lower ≤ upperBound := Rat.le_trans hlow (upper strategy) + exact (Rat.not_lt.mpr h) gap + +theorem soundness_from_repetition + {Labeling Strategy : Type} (acceptance : Labeling → Rat) + (success : Strategy → Rat) (dimension : Strategy → Nat) + (conditionalSuccess : Strategy → Nat → Rat) + (delta a theta : Rat) (q L t : Nat) (ha : 0 ≤ a) (ha' : a ≤ 1) + (dimension_le : ∀ strategy, dimension strategy ≤ L) + (conditional : ∀ strategy k, conditionalSuccess strategy k ≤ a ^ k) + (averaged : ∀ strategy, success strategy ≤ + bernoulliAverage (zeroProbability (dimension strategy)) t + (conditionalSuccess strategy)) + (extraction : ∀ labeling, delta < acceptance labeling → + ∃ strategy, decoderThreshold theta q ≤ success strategy) + (gap : (1 - zeroProbability L * (1 - a)) ^ t < decoderThreshold theta q) : + ∀ labeling, acceptance labeling ≤ delta := by + apply soundness_of_bounds acceptance success delta (decoderThreshold theta q) + ((1 - zeroProbability L * (1 - a)) ^ t) extraction + · intro strategy + exact projection_upper_bound (dimension strategy) L t (dimension_le strategy) + a (success strategy) ha ha' (conditionalSuccess strategy) + (conditional strategy) (averaged strategy) + · exact gap + +end MinUncutGames.Soundness.RepetitionUpper + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/Gap.lean b/lean/OAI/Computability/MinUncut/PCP/Gap.lean new file mode 100644 index 0000000000000000000000000000000000000000..e7027b454b0a1b5bda7f2e9fd1c50a87e0e7880b --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/Gap.lean @@ -0,0 +1,681 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.TupleBody +import OAI.Computability.MinUncut.Machines.RuntimeFinish +import OAI.Computability.MinUncut.Games.Parameters + +namespace OAI + +namespace MinUncutGames.Foundations.Hastad.SourceGap + +open Target SourceContexts SourceOccurrences SourceGame +open MinUncutGames.Integration.SourceParameters +open MinUncutGames.Reduction + +def ClauseGap (F : Formula) (η : ℚ) : Prop := + F.clauses ≠ [] ∧ ∀ assignment : Fin F.«variables» → Bool, + (η : ℝ) * F.clauses.length ≤ + (PCP.failureCount F assignment (PCP.allIndices F) : ℝ) + +theorem third_pos {η : ℚ} (hη : 0 < η) : 0 < η / 3 := by positivity + +theorem third_le_one {η : ℚ} (hη : η ≤ 1) : η / 3 ≤ 1 := by linarith + +def repetitionCount (η ξ : ℚ) (hη : 0 < η) (hη1 : η ≤ 1) (hξ : 0 < ξ) + (D : ℕ) (hD : 0 < D) : ℕ := + repetitionLength (η / 3) ξ (third_pos hη) (third_le_one hη1) hξ D hD + +theorem repetitionCount_pos (η ξ : ℚ) (hη : 0 < η) (hη1 : η ≤ 1) + (hξ : 0 < ξ) (D : ℕ) (hD : 0 < D) : + 0 < repetitionCount η ξ hη hη1 hξ D hD := + (repetitionLength_spec (η / 3) ξ (third_pos hη) (third_le_one hη1) hξ D hD).1 + +theorem repeated_game_bound (F : Formula) (η ξ : ℚ) + (hη : 0 < η) (hη1 : η ≤ 1) (hξ : 0 < ξ) (D : ℕ) (hD : 0 < D) + (hgap : ClauseGap F η) : + ((baseGame F hgap.1).repetition + (repetitionCount η ξ hη hη1 hξ D hD)).value ≤ + 4 * (D : ℝ)⁻¹ * (ξ : ℝ)^2 := by + have hb : (baseGame F hgap.1).value ≤ 1 - ((η / 3 : ℚ) : ℝ) := by + simpa only [Rat.cast_div, Rat.cast_ofNat] using + base_value_le_of_clause_gap F hgap.1 (η : ℝ) hgap.2 + have hc : Fintype.card Bool * Fintype.card PCP.ClauseAnswer = 16 := by + simp + exact (game_repetition_rate (baseGame F hgap.1) (third_pos hη) + (third_le_one hη1) hc hb _).trans + (repetitionLength_real_bound (η / 3) ξ (third_pos hη) + (third_le_one hη1) hξ D hD) + +def source (η ξ : ℚ) (hη : 0 < η) (hη1 : η ≤ 1) (hξ : 0 < ξ) + (D : ℕ) (hD : 0 < D) (F : Formula) : SourceEncoding.Input := + sourceInput F (repetitionCount η ξ hη hη1 hξ D hD) D hD + +theorem source_complete (η ξ : ℚ) (hη : 0 < η) (hη1 : η ≤ 1) (hξ : 0 < ξ) + (D : ℕ) (hD : 0 < D) (hnoise : (D : ℚ)⁻¹ ≤ ξ) + (F : Formula) (hF : F.Satisfiable) : + ∃ bits : Fin (source η ξ hη hη1 hξ D hD F).«variables» → Bool, + 1 - ξ ≤ (((source η ξ hη hη1 hξ D hD F).equations.countP + (fun e => CloneGap.satisfied e bits) : ℚ) / + (source η ξ hη hη1 hξ D hD F).equations.length) := by + obtain ⟨assignment, hs⟩ := hF + refine ⟨SourceHonest.honestBits F _ assignment, ?_⟩ + have h := SourceHonest.sourceList_honest_acceptance_rat F + (repetitionCount η ξ hη hη1 hξ D hD) D hD assignment hs + exact (sub_le_sub_left hnoise 1).trans h + +theorem source_sound (η ξ : ℚ) (hη : 0 < η) (hη1 : η ≤ 1) (hξ : 0 < ξ) + (D : ℕ) (hD : 0 < D) (hDtwo : 2 ≤ D) + (F : Formula) (hgap : ClauseGap F η) + (bits : Fin (source η ξ hη hη1 hξ D hD F).«variables» → Bool) : + ((source η ξ hη hη1 hξ D hD F).equations.countP + (fun e => CloneGap.satisfied e bits) : ℚ) / + (source η ξ hη hη1 hξ D hD F).equations.length ≤ (1 + ξ) / 2 := + SourceSoundness.sourceList_sound_rat F hgap.1 + (repetitionCount η ξ hη hη1 hξ D hD) D hD hDtwo ξ hξ.le + (repeated_game_bound F η ξ hη hη1 hξ D hD hgap) bits + +theorem source_size (η ξ : ℚ) (hη : 0 < η) (hη1 : η ≤ 1) (hξ : 0 < ξ) + (D : ℕ) (hD : 0 < D) : + ∃ p : Polynomial ℕ, ∀ F : Formula, + (SourceEncoding.inputBits (source η ξ hη hη1 hξ D hD F)).length ≤ + p.eval (Complexity.formulaBits F).length := + SourceBounds.fixed_parameters_source_size (repetitionCount η ξ hη hη1 hξ D hD) D hD + +end MinUncutGames.Foundations.Hastad.SourceGap + +namespace MinUncutGames.Foundations.Hastad.SourceNoiseParameter + +def noiseDenominator (ξ : ℚ) : ℕ := ξ.den + 2 + +theorem noiseDenominator_ge_two (ξ : ℚ) : 2 ≤ noiseDenominator ξ := by + unfold noiseDenominator + omega + +theorem noiseDenominator_pos (ξ : ℚ) : 0 < noiseDenominator ξ := + lt_of_lt_of_le (by decide) (noiseDenominator_ge_two ξ) + +theorem noiseDenominator_inv_pos (ξ : ℚ) : + 0 < (noiseDenominator ξ : ℚ)⁻¹ := by + apply inv_pos.mpr + exact_mod_cast noiseDenominator_pos ξ + +theorem noiseDenominator_inv_le_half (ξ : ℚ) : + (noiseDenominator ξ : ℚ)⁻¹ ≤ (1 / 2 : ℚ) := by + rw [inv_eq_one_div] + apply one_div_le_one_div_of_le (by norm_num) + exact_mod_cast noiseDenominator_ge_two ξ + +theorem noiseDenominator_inv_le {ξ : ℚ} (hξ : 0 < ξ) : + (noiseDenominator ξ : ℚ)⁻¹ ≤ ξ := by + have hn : (1 : ℤ) ≤ ξ.num := by + have h := Rat.num_pos.mpr hξ + omega + have hnq : (1 : ℚ) ≤ (ξ.num : ℚ) := by exact_mod_cast hn + have hd : (0 : ℚ) < (ξ.den : ℚ) := by exact_mod_cast ξ.den_pos + calc + (noiseDenominator ξ : ℚ)⁻¹ = 1 / (noiseDenominator ξ : ℚ) := inv_eq_one_div _ + _ ≤ 1 / (ξ.den : ℚ) := by + apply one_div_le_one_div_of_le hd + exact_mod_cast (show ξ.den ≤ noiseDenominator ξ by + unfold noiseDenominator + omega) + _ ≤ (ξ.num : ℚ) / (ξ.den : ℚ) := div_le_div_of_nonneg_right hnq hd.le + _ = ξ := ξ.num_div_den + +end MinUncutGames.Foundations.Hastad.SourceNoiseParameter + +namespace MinUncutGames.Foundations.Hastad.SourceGap + +open Target SourceNoiseParameter MinUncutGames.Reduction + +def forError (η ξ : ℚ) (hη : 0 < η) (hη1 : η ≤ 1) (hξ : 0 < ξ) : + Formula → SourceEncoding.Input := + source η ξ hη hη1 hξ (noiseDenominator ξ) (noiseDenominator_pos ξ) + +theorem forError_complete (η ξ : ℚ) (hη : 0 < η) (hη1 : η ≤ 1) (hξ : 0 < ξ) + (F : Formula) (hF : F.Satisfiable) : + ∃ bits : Fin (forError η ξ hη hη1 hξ F).«variables» → Bool, + 1 - ξ ≤ ((forError η ξ hη hη1 hξ F).equations.countP + (fun e => CloneGap.satisfied e bits) : ℚ) / + (forError η ξ hη hη1 hξ F).equations.length := + source_complete η ξ hη hη1 hξ (noiseDenominator ξ) (noiseDenominator_pos ξ) + (noiseDenominator_inv_le hξ) F hF + +theorem forError_sound (η ξ : ℚ) (hη : 0 < η) (hη1 : η ≤ 1) (hξ : 0 < ξ) + (F : Formula) (hgap : ClauseGap F η) + (bits : Fin (forError η ξ hη hη1 hξ F).«variables» → Bool) : + ((forError η ξ hη hη1 hξ F).equations.countP + (fun e => CloneGap.satisfied e bits) : ℚ) / + (forError η ξ hη hη1 hξ F).equations.length ≤ (1 + ξ) / 2 := + source_sound η ξ hη hη1 hξ (noiseDenominator ξ) (noiseDenominator_pos ξ) + (noiseDenominator_ge_two ξ) F hgap bits + +theorem forError_size (η ξ : ℚ) (hη : 0 < η) (hη1 : η ≤ 1) (hξ : 0 < ξ) : + ∃ p : Polynomial ℕ, ∀ F : Formula, + (SourceEncoding.inputBits (forError η ξ hη hη1 hξ F)).length ≤ + p.eval (Complexity.formulaBits F).length := + source_size η ξ hη hη1 hξ (noiseDenominator ξ) (noiseDenominator_pos ξ) + +end MinUncutGames.Foundations.Hastad.SourceGap + +namespace MinUncutGames.Foundations.Hastad.SourceGeneratorContract + +open Target Complexity + +abbrev NonemptyFormula := { F : Formula // F.clauses ≠ [] } + +def inputEncoding (F : NonemptyFormula) : List Bool := formulaBits F.val + +def sourceMap (u D : Nat) (hD : 0 < D) (F : NonemptyFormula) : + MinUncutGames.Reduction.SourceEncoding.Input := + SourceOccurrences.sourceInput F.val u D hD + +def errorMap (η ξ : ℚ) (hη : 0 < η) (hη1 : η ≤ 1) (hξ : 0 < ξ) + (F : NonemptyFormula) : MinUncutGames.Reduction.SourceEncoding.Input := + SourceGap.forError η ξ hη hη1 hξ F.val + +theorem inputEncoding_mk (F : Formula) (hne : F.clauses ≠ []) : + inputEncoding ⟨F, hne⟩ = formulaBits F := rfl + +end MinUncutGames.Foundations.Hastad.SourceGeneratorContract + +namespace MinUncutGames.Foundations.Hastad.SourceOdometerSchedule + +open Turing Complexity MachineTupleOdometer +open Reduction.MachineTransfer + +abbrev Tape := SourceContextLoad.Tape + +variable {u m : ℕ} {Extra Λ σ : Type} [DecidableEq Extra] + +def currentAt (accumulator : Extra) (i : ℕ) : Tape u Extra := + if h : i < u then .current ⟨i, h⟩ else .extra accumulator + +def remainingAt (accumulator : Extra) (i : ℕ) : Tape u Extra := + if h : i < u then .remaining ⟨i, h⟩ else .extra accumulator + +def setDigits (m : ℕ) {q : ℕ} (digits : Fin q → ℕ) + (base : Tape u Extra → List Bool) : Tape u Extra → List Bool + | .current i => if h : i.val < q then encodeWord (digits ⟨i.val, h⟩) + else base (.current i) + | .remaining i => if h : i.val < q then encodeWord (m - 1 - digits ⟨i.val, h⟩) + else base (.remaining i) + | k => base k + +def setAcc (accumulator : Extra) (base : Tape u Extra → List Bool) (bits : List Bool) : + Tape u Extra → List Bool := Function.update base (.extra accumulator) bits + +def putDigit (i : Fin u) (base : Tape u Extra → List Bool) (d r : ℕ) : + Tape u Extra → List Bool := digitTapes (.current i) (.remaining i) base d r [] [] + +omit [DecidableEq Extra] in +@[simp] theorem setDigits_zero (m : ℕ) (digits : Fin 0 → ℕ) + (base : Tape u Extra → List Bool) : setDigits m digits base = base := by + funext k + cases k <;> simp [setDigits] + +omit [DecidableEq Extra] in +@[simp] theorem setDigits_extra (m : ℕ) {q : ℕ} (digits : Fin q → ℕ) + (base : Tape u Extra → List Bool) (a : Extra) : + setDigits m digits base (.extra a) = base (.extra a) := rfl + +@[simp] theorem setAcc_self (a : Extra) (base : Tape u Extra → List Bool) : + setAcc a base (base (.extra a)) = base := by + simp [setAcc] + +@[simp] theorem setAcc_setAcc (a : Extra) (base : Tape u Extra → List Bool) + (first second : List Bool) : setAcc a (setAcc a base first) second = setAcc a base second := by + simp [setAcc] + +@[simp] theorem setAcc_apply (a : Extra) (base : Tape u Extra → List Bool) (bits : List Bool) : + setAcc a base bits (.extra a) = bits := by simp [setAcc] + +theorem setDigits_setAcc (m : ℕ) {q : ℕ} (digits : Fin q → ℕ) + (a : Extra) (base : Tape u Extra → List Bool) (bits : List Bool) : + setDigits m digits (setAcc a base bits) = setAcc a (setDigits m digits base) bits := by + funext k + cases k <;> simp [setDigits, setAcc, Function.update_apply] + +@[simp] theorem putDigit_extra (i : Fin u) (base : Tape u Extra → List Bool) + (d r : ℕ) (a : Extra) : putDigit i base d r (.extra a) = base (.extra a) := by + simp [putDigit, digitTapes, MachineUnaryAddAt.unaryTapes, tapesAt] + +theorem putDigit_setAcc (i : Fin u) (base : Tape u Extra → List Bool) + (d r : ℕ) (a : Extra) (bits : List Bool) : + putDigit i (setAcc a base bits) d r = setAcc a (putDigit i base d r) bits := by + funext k + cases k <;> simp [putDigit, digitTapes, MachineUnaryAddAt.unaryTapes, tapesAt, + setAcc, Function.update_apply] + +theorem setDigits_putDigit (m q : ℕ) (hq : q < u) (digits : Fin q → ℕ) + (base : Tape u Extra → List Bool) (d r : ℕ) : + setDigits m digits (putDigit ⟨q, hq⟩ base d r) = + putDigit ⟨q, hq⟩ (setDigits m digits base) d r := by + funext k + cases k with + | current i => + by_cases hi : i.val < q + · have hne : i ≠ ⟨q, hq⟩ := by intro h; have := congrArg Fin.val h; simp at this; omega + simp [setDigits, putDigit, digitTapes, MachineUnaryAddAt.unaryTapes, tapesAt, hi, hne] + · simp [setDigits, putDigit, digitTapes, MachineUnaryAddAt.unaryTapes, tapesAt, hi, + Function.update_apply] + | remaining i => + by_cases hi : i.val < q + · have hne : i ≠ ⟨q, hq⟩ := by intro h; have := congrArg Fin.val h; simp at this; omega + simp [setDigits, putDigit, digitTapes, MachineUnaryAddAt.unaryTapes, tapesAt, hi, hne] + · simp [setDigits, putDigit, digitTapes, MachineUnaryAddAt.unaryTapes, tapesAt, hi, + Function.update_apply] + | _ => simp [setDigits, putDigit, digitTapes, MachineUnaryAddAt.unaryTapes, tapesAt] + +theorem setDigits_snoc (m q : ℕ) (hq : q < u) (digits : Fin q → ℕ) + (d : ℕ) (base : Tape u Extra → List Bool) : + setDigits m (Fin.snoc digits d) base = + putDigit ⟨q, hq⟩ (setDigits m digits base) d (m - 1 - d) := by + funext k + cases k with + | current i => + by_cases hi : i.val < q + · have hi' : i.val < q + 1 := by omega + have hne : i ≠ ⟨q, hq⟩ := by intro h; have := congrArg Fin.val h; simp at this; omega + simp [setDigits, putDigit, digitTapes, MachineUnaryAddAt.unaryTapes, tapesAt, + hi, hi', hne, Fin.snoc] + · by_cases he : i.val = q + · have hie : i = ⟨q, hq⟩ := Fin.ext he + subst i + simp [setDigits, putDigit, digitTapes, MachineUnaryAddAt.unaryTapes, tapesAt, Fin.snoc] + · have hi' : ¬ i.val < q + 1 := by omega + have hne : i ≠ ⟨q, hq⟩ := by intro h; exact he (congrArg Fin.val h) + simp [setDigits, putDigit, digitTapes, MachineUnaryAddAt.unaryTapes, tapesAt, + hi, hi', hne] + | remaining i => + by_cases hi : i.val < q + · have hi' : i.val < q + 1 := by omega + have hne : i ≠ ⟨q, hq⟩ := by intro h; have := congrArg Fin.val h; simp at this; omega + simp [setDigits, putDigit, digitTapes, MachineUnaryAddAt.unaryTapes, tapesAt, + hi, hi', hne, Fin.snoc] + · by_cases he : i.val = q + · have hie : i = ⟨q, hq⟩ := Fin.ext he + subst i + simp [setDigits, putDigit, digitTapes, MachineUnaryAddAt.unaryTapes, tapesAt, Fin.snoc] + · have hi' : ¬ i.val < q + 1 := by omega + have hne : i ≠ ⟨q, hq⟩ := by intro h; exact he (congrArg Fin.val h) + simp [setDigits, putDigit, digitTapes, MachineUnaryAddAt.unaryTapes, tapesAt, + hi, hi', hne] + | _ => simp [setDigits, putDigit, digitTapes, MachineUnaryAddAt.unaryTapes, tapesAt] + +theorem setDigits_snoc_base (m q : ℕ) (hq : q < u) (digits : Fin q → ℕ) + (d : ℕ) (base : Tape u Extra → List Bool) : + setDigits m digits (putDigit ⟨q, hq⟩ base d (m - 1 - d)) = + setDigits m (Fin.snoc digits d) base := by + rw [setDigits_putDigit, setDigits_snoc] + +def allBits {q : ℕ} (bits : (Fin q → Fin m) → List Bool) : List Bool := + (tupleOrder m q).flatMap bits + +def blockPrefix (blocks : ℕ → List Bool) : ℕ → List Bool + | 0 => [] + | n + 1 => blockPrefix blocks n ++ blocks n + +theorem blockPrefix_eq_ofFn (blocks : ℕ → List Bool) (n : ℕ) : + blockPrefix blocks n = (List.ofFn (fun i : Fin n => blocks i.val)).flatten := by + induction n with + | zero => simp [blockPrefix] + | succ n ih => + rw [blockPrefix, List.ofFn_succ', List.concat_eq_append, List.flatten_append] + simpa only [Fin.val_castSucc, Fin.val_last, List.flatten_cons, + List.flatten_nil, List.append_nil] using congrArg (fun xs => xs ++ blocks n) ih + +def blocks {q : ℕ} (bits : (Fin (q + 1) → Fin m) → List Bool) (d : ℕ) : List Bool := + if h : d < m then allBits (fun c => bits (Fin.snoc c ⟨d, h⟩)) else [] + +theorem blockPrefix_all {q : ℕ} (bits : (Fin (q + 1) → Fin m) → List Bool) : + blockPrefix (blocks bits) m = allBits bits := by + rw [blockPrefix_eq_ofFn] + simp only [blocks, Fin.isLt, ↓reduceDIte, allBits, tupleOrder_snoc] + simp only [List.flatMap_assoc, List.flatMap_map] + simp only [List.flatMap_def, List.map_ofFn, Function.comp_def] + +def configuration (label : Λ) (canonical : σ) (tapes : Tape u Extra → List Bool) : + Configuration (Tape u Extra) Λ σ := ⟨some label, (canonical, none), tapes⟩ + +def BodyTrace (program : Λ → TM2.Stmt (fun _ : Tape u Extra => Bool) Λ (σ × Option Bool)) + (bodyLabel returnLabel : Λ) (canonical : σ) (accumulator : Extra) + {q : ℕ} (base : Tape u Extra → List Bool) + (bits : (Fin q → Fin m) → List Bool) (B : ℕ) : Prop := + ∀ c output, ∃ count, count ≤ B ∧ (MachineComposition.advance (TM2.step program))^[count] + (some (configuration bodyLabel canonical + (setDigits m (fun i => (c i).val) (setAcc accumulator base output)))) = + some (configuration returnLabel canonical + (setDigits m (fun i => (c i).val) + (setAcc accumulator base ((bits c).reverse ++ output)))) + +theorem val_snoc {q : ℕ} (c : Fin q → Fin m) (d : Fin m) : + (fun i : Fin (q + 1) => (Fin.snoc (α := fun _ => Fin m) c d i).val) = + Fin.snoc (fun i => (c i).val) d.val := by + funext i + refine Fin.lastCases ?_ (fun j => ?_) i <;> simp + +theorem zeros_snoc (q : ℕ) : + Fin.snoc (fun _ : Fin q => (0 : ℕ)) 0 = fun _ : Fin (q + 1) => 0 := by + funext i + refine Fin.lastCases ?_ (fun j => ?_) i <;> simp + +def initialConfiguration (q : ℕ) (bodyLabel : Λ) (canonical : σ) + (base : Tape u Extra → List Bool) : Configuration (Tape u Extra) Λ σ := + configuration bodyLabel canonical (setDigits m (fun _ : Fin q => 0) base) + +def finalConfiguration {q : ℕ} (exitLabel : Λ) (canonical : σ) (accumulator : Extra) + (base : Tape u Extra → List Bool) (bits : (Fin q → Fin m) → List Bool) : + Configuration (Tape u Extra) Λ σ := + configuration exitLabel canonical (setDigits m (fun _ : Fin q => 0) + (setAcc accumulator base ((allBits bits).reverse ++ base (.extra accumulator)))) + +theorem exists_schedule + (program : Λ → TM2.Stmt (fun _ : Tape u Extra => Bool) Λ (σ × Option Bool)) + (bodyLabel : Λ) (next resetLabel : ℕ → Λ) (canonical : σ) (accumulator : Extra) + (positive : 0 < m) (B q : ℕ) (hq : q ≤ u) + (base : Tape u Extra → List Bool) (bits : (Fin q → Fin m) → List Bool) + (atCheck : ∀ i, i < q → program (next i) = + increment (currentAt accumulator i) (remainingAt accumulator i) bodyLabel (resetLabel i)) + (atReset : ∀ i, i < q → program (resetLabel i) = + reset (currentAt accumulator i) (remainingAt accumulator i) (resetLabel i) (next (i + 1))) + (bodies : BodyTrace program bodyLabel (next 0) canonical accumulator base bits B) : + ∃ tree : NestedCycle m (currentAt accumulator) (remainingAt accumulator) bodyLabel + next resetLabel program q (next q) + (initialConfiguration (m := m) q bodyLabel canonical base) + (finalConfiguration (next q) canonical accumulator base bits), tree.LeafBound B := by + classical + induction q generalizing base with + | zero => + let empty : Fin 0 → Fin m := fun i => Fin.elim0 i + obtain ⟨count, hcount, run⟩ := bodies empty (base (.extra accumulator)) + have hrun : (MachineComposition.advance (TM2.step program))^[count] + (some (initialConfiguration (m := m) 0 bodyLabel canonical base)) = + some (finalConfiguration (next 0) canonical accumulator base bits) := by + simpa only [initialConfiguration, finalConfiguration, allBits, + tupleOrder_dimension_zero, List.flatMap_cons, List.flatMap_nil, List.append_nil, + setDigits_zero, setAcc_self] using run + let tree := NestedCycle.leaf (n := m) (current := currentAt accumulator) + (remaining := remainingAt accumulator) (bodyLabel := bodyLabel) + (checkLabel := next) (resetLabel := resetLabel) (program := program) + (next 0) (initialConfiguration (m := m) 0 bodyLabel canonical base) + (finalConfiguration (next 0) canonical accumulator base bits) count rfl rfl hrun + refine ⟨tree, ?_⟩ + dsimp only [tree] + erw [NestedCycle.LeafBound] + exact hcount + | succ q ih => + have hqu : q < u := by omega + let s : CycleSchedule (Tape u Extra) σ := { + currentSuffix := [] + remainingSuffix := [] + ambient := fun _ => canonical + register := fun _ => none + base := fun r => setDigits m (fun _ : Fin q => 0) + (setAcc accumulator base + ((blockPrefix (blocks bits) (m - r)).reverse ++ base (.extra accumulator))) } + have childrenExist (r : Fin m) : + ∃ tree : NestedCycle m (currentAt accumulator) (remainingAt accumulator) bodyLabel + next resetLabel program q (next q) + (bodyConfiguration (currentAt accumulator q) (remainingAt accumulator q) + bodyLabel (m - 1) r.val s.currentSuffix s.remainingSuffix s.ambient s.base) + (checkConfiguration (currentAt accumulator q) (remainingAt accumulator q) + (next q) (m - 1) r.val s.currentSuffix s.remainingSuffix + s.ambient s.register s.base), tree.LeafBound B := by + let d : Fin m := NestedCycle.reverseDigit r + let childBits : (Fin q → Fin m) → List Bool := fun c => bits (Fin.snoc c d) + let childBase := putDigit ⟨q, hqu⟩ + (setAcc accumulator base + ((blockPrefix (blocks bits) (m - (r.val + 1))).reverse ++ base (.extra accumulator))) + d.val (m - 1 - d.val) + have hrem : m - 1 - d.val = r.val := by + dsimp [d, NestedCycle.reverseDigit] + omega + have hbefore : m - (r.val + 1) = d.val := by + dsimp [d, NestedCycle.reverseDigit] + omega + have hafter : m - r.val = d.val + 1 := by + dsimp [d, NestedCycle.reverseDigit] + omega + have hprefix : blockPrefix (blocks bits) (m - r.val) = + blockPrefix (blocks bits) (m - (r.val + 1)) ++ allBits childBits := by + rw [hafter, hbefore, blockPrefix] + simp only [blocks, d.isLt, ↓reduceDIte, childBits] + have childBodies : BodyTrace program bodyLabel (next 0) canonical accumulator + childBase childBits B := by + intro c output + obtain ⟨count, hcount, h⟩ := bodies (Fin.snoc c d) output + refine ⟨count, hcount, ?_⟩ + simpa only [childBase, childBits, ← putDigit_setAcc, + setAcc_setAcc, setDigits_snoc_base, ← val_snoc] using h + have lower := ih (by omega) childBase childBits + (fun i hi => atCheck i (by omega)) (fun i hi => atReset i (by omega)) + childBodies + have hstart : initialConfiguration (m := m) q bodyLabel canonical childBase = + bodyConfiguration (currentAt accumulator q) (remainingAt accumulator q) + bodyLabel (m - 1) r.val s.currentSuffix s.remainingSuffix s.ambient s.base := by + simp only [initialConfiguration, configuration, bodyConfiguration, s, childBase, + currentAt, remainingAt, hqu, ↓reduceDIte, setDigits_putDigit, hrem] + rfl + have hfinish : finalConfiguration (next q) canonical accumulator childBase childBits = + checkConfiguration (currentAt accumulator q) (remainingAt accumulator q) + (next q) (m - 1) r.val s.currentSuffix s.remainingSuffix + s.ambient s.register s.base := by + simp only [finalConfiguration, configuration, checkConfiguration, s, childBase, + currentAt, remainingAt, hqu, ↓reduceDIte, putDigit_extra, setAcc_apply, + ← putDigit_setAcc, setAcc_setAcc, setDigits_putDigit, hrem, hprefix, + List.reverse_append, List.append_assoc] + rfl + rw [hstart, hfinish] at lower + exact lower + let children := fun r : Fin m => Classical.choose (childrenExist r) + let tree := NestedCycle.node q (next (q + 1)) positive + (by simp [currentAt, remainingAt, hqu]) + (atCheck q (by omega)) (atReset q (by omega)) s children + have hbounded : tree.LeafBound B := by + simp only [tree, NestedCycle.LeafBound] + intro r + exact Classical.choose_spec (childrenExist r) + have hstart : bodyConfiguration (currentAt accumulator q) (remainingAt accumulator q) + bodyLabel (m - 1) (m - 1) s.currentSuffix s.remainingSuffix s.ambient s.base = + initialConfiguration (m := m) (q + 1) bodyLabel canonical base := by + have hm : m - 1 + 1 = m := by omega + simp only [bodyConfiguration, initialConfiguration, configuration, s, + currentAt, remainingAt, hqu, ↓reduceDIte, Nat.sub_self, hm, + blockPrefix, List.reverse_nil, List.nil_append, setAcc_self] + rw [← zeros_snoc q, setDigits_snoc m q hqu] + rfl + have hfinish : cycleExit (currentAt accumulator q) (remainingAt accumulator q) + (next (q + 1)) (m - 1) s.currentSuffix s.remainingSuffix s.ambient s.base = + finalConfiguration (next (q + 1)) canonical accumulator base bits := by + simp only [cycleExit, finalConfiguration, configuration, s, currentAt, remainingAt, + hqu, ↓reduceDIte, Nat.sub_zero, blockPrefix_all] + rw [← zeros_snoc q, setDigits_snoc m q hqu] + rfl + have result := (show ∃ t : NestedCycle m (currentAt accumulator) (remainingAt accumulator) + bodyLabel next resetLabel program (q + 1) (next (q + 1)) + (bodyConfiguration (currentAt accumulator q) (remainingAt accumulator q) + bodyLabel (m - 1) (m - 1) s.currentSuffix s.remainingSuffix s.ambient s.base) + (cycleExit (currentAt accumulator q) (remainingAt accumulator q) + (next (q + 1)) (m - 1) s.currentSuffix s.remainingSuffix s.ambient s.base), + t.LeafBound B from ⟨tree, hbounded⟩) + rw [hstart, hfinish] at result + exact result + +theorem traversalInTime + (program : Λ → TM2.Stmt (fun _ : Tape u Extra => Bool) Λ (σ × Option Bool)) + (bodyLabel : Λ) (next resetLabel : ℕ → Λ) (canonical : σ) (accumulator : Extra) + (positive : 0 < m) (B : ℕ) (base : Tape u Extra → List Bool) + (bits : (Fin u → Fin m) → List Bool) + (atCheck : ∀ i, i < u → program (next i) = + increment (currentAt accumulator i) (remainingAt accumulator i) bodyLabel (resetLabel i)) + (atReset : ∀ i, i < u → program (resetLabel i) = + reset (currentAt accumulator i) (remainingAt accumulator i) (resetLabel i) (next (i + 1))) + (bodies : BodyTrace program bodyLabel (next 0) canonical accumulator base bits B) : + Nonempty (StateTransition.EvalsToInTime (TM2.step program) + (initialConfiguration (m := m) u bodyLabel canonical base) + (some (finalConfiguration (next u) canonical accumulator base bits)) + ((B + 2 * u) * m ^ u)) := by + obtain ⟨tree, ht⟩ := exists_schedule program bodyLabel next resetLabel canonical accumulator + positive B u (Nat.le_refl _) base bits atCheck atReset bodies + exact ⟨{ + steps := tree.steps + evals_in_steps := tree.trace + steps_le_m := tree.steps_le_power positive B ht }⟩ + +omit [DecidableEq Extra] in +@[simp] theorem initial_current (base : Tape u Extra → List Bool) + (bodyLabel : Λ) (canonical : σ) (i : Fin u) : + (initialConfiguration (m := m) u bodyLabel canonical base).stk (.current i) = + encodeWord 0 := by simp [initialConfiguration, configuration, setDigits] + +omit [DecidableEq Extra] in +@[simp] theorem initial_remaining (base : Tape u Extra → List Bool) + (bodyLabel : Λ) (canonical : σ) (i : Fin u) : + (initialConfiguration (m := m) u bodyLabel canonical base).stk (.remaining i) = + encodeWord (m - 1) := by simp [initialConfiguration, configuration, setDigits] + +@[simp] theorem final_current (base : Tape u Extra → List Bool) + (exitLabel : Λ) (canonical : σ) (accumulator : Extra) + (bits : (Fin u → Fin m) → List Bool) (i : Fin u) : + (finalConfiguration exitLabel canonical accumulator base bits).stk (.current i) = + encodeWord 0 := by simp [finalConfiguration, configuration, setDigits] + +@[simp] theorem final_remaining (base : Tape u Extra → List Bool) + (exitLabel : Λ) (canonical : σ) (accumulator : Extra) + (bits : (Fin u → Fin m) → List Bool) (i : Fin u) : + (finalConfiguration exitLabel canonical accumulator base bits).stk (.remaining i) = + encodeWord (m - 1) := by simp [finalConfiguration, configuration, setDigits] + +@[simp] theorem final_accumulator (base : Tape u Extra → List Bool) + (exitLabel : Λ) (canonical : σ) (accumulator : Extra) + (bits : (Fin u → Fin m) → List Bool) : + (finalConfiguration exitLabel canonical accumulator base bits).stk (.extra accumulator) = + ((tupleOrder m u).flatMap bits).reverse ++ base (.extra accumulator) := by + simp [finalConfiguration, configuration, allBits] + +end MinUncutGames.Foundations.Hastad.SourceOdometerSchedule + +namespace MinUncutGames.Foundations.Hastad.SourceGeneratorProgram + +open Turing Complexity SourceGeneratorModel + +noncomputable section + +abbrev Tape (u D : Nat) := SourceGeneratorModel.Tape u D +abbrev Ambient (u D : Nat) := SourceGeneratorModel.ControlAmbient u D +abbrev State (u D : Nat) := Ambient u D × Option Bool + +local instance sourceGeneratorProgramExtraDecidableEq (u D : Nat) : + DecidableEq (Extra u D) := Classical.decEq _ + +inductive Label (u D : Nat) + | startup (label : SourceStartup.Label u D) + | body (label : SourceTupleBody.Label u D (Extra u D)) + | check (coordinate : Fin u) + | reset (coordinate : Fin u) + | finishEnter + | finish (label : SourceRuntimeFinish.Label (clearKeys u D)) + deriving DecidableEq, Fintype + +def bodyEntry (u D : Nat) : Label u D := .body SourceTupleBody.main + +def next (u D : Nat) (i : Nat) : Label u D := + if h : i < u then .check ⟨i, h⟩ else .finishEnter + +def sourceStateEquiv (u D : Nat) : SourceRuntimeModel.State u D × Unit ≃ State u D where + toFun x := (controlStateEquiv u D).symm x.1 + invFun x := (controlStateEquiv u D x, ()) + left_inv x := by cases x with | mk x y => cases y; simp + right_inv x := by simp + +def program (u D : Nat) (hD : 0 < D) : + Label u D → TM2.Stmt (fun _ : Tape u D => Bool) (Label u D) (State u D) + | .startup l => SourceTupleBody.framed (sourceStateEquiv u D) Label.startup + (some (bodyEntry u D)) (SourceStartup.program l) + | .body l => SourceTupleBody.framed (sourceStateEquiv u D) Label.body + (some (next u D 0)) + (SourceTupleBody.program (initialQuery u D hD) none l) + | .check i => MachineTupleOdometer.increment + (.current i) (.remaining i) (bodyEntry u D) (.reset i) + | .reset i => MachineTupleOdometer.reset + (.current i) (.remaining i) (.reset i) (next u D (i.val + 1)) + | .finishEnter => Reduction.MachineTransfer.exitAt (accumulatorTape u D) + (SourceRuntimeFinish.entry (clearKeys u D) Label.finish) + | .finish l => SourceRuntimeFinish.statement (clearKeys u D) + (accumulatorTape u D) (outputTape u D) (initialAmbient u D hD) + Label.finish none l + +def main (u D : Nat) : Label u D := .startup (.inl .inputCopyOut) + +def machine (u D : Nat) (hD : 0 < D) : FinTM2 where + K := Tape u D + k₀ := .formula + k₁ := outputTape u D + Γ _ := Bool + Λ := Label u D + main := main u D + σ := State u D + initialState := (initialAmbient u D hD, none) + m := program u D hD + +theorem finite_work_alphabets (u D : Nat) (hD : 0 < D) + (k : (machine u D hD).K) : Finite ((machine u D hD).Γ k) := by + change Finite Bool + infer_instance + +theorem atCheck (u D : Nat) (hD : 0 < D) (i : Fin u) : + program u D hD (.check i) = MachineTupleOdometer.increment + (.current i) (.remaining i) (bodyEntry u D) (.reset i) := rfl + +theorem atReset (u D : Nat) (hD : 0 < D) (i : Fin u) : + program u D hD (.reset i) = MachineTupleOdometer.reset + (.current i) (.remaining i) (.reset i) (next u D (i.val + 1)) := rfl + +end + +end MinUncutGames.Foundations.Hastad.SourceGeneratorProgram + +namespace MinUncutGames.Foundations.Hastad.SourceGenerator +open Turing Complexity Target +open SourceGeneratorModel SourceGeneratorProgram SourceGeneratorContract +noncomputable section +variable {u D : Nat} +local instance sourceGeneratorExtraDecidableEq : DecidableEq (Extra u D) := Classical.decEq _ + +theorem source_initial (u D : Nat) (hD : 0 < D) : + sourceStateEquiv u D (SourceGeneratorModel.initialState u D hD, ()) = + (initialAmbient u D hD, none) := rfl + +theorem initial_configuration (F : Formula) (hD : 0 < D) : + initList (SourceGeneratorProgram.machine u D hD) (formulaBits F) = + (⟨some (SourceGeneratorProgram.main u D), (initialAmbient u D hD, none), + SourceStartup.initialTapes F⟩ : (SourceGeneratorProgram.machine u D hD).Cfg) := by + simp only [initList, SourceGeneratorProgram.machine] + congr 1 + funext k + by_cases hk : k = SourceContextLoad.Tape.formula + · subst k + simp [SourceStartup.initialTapes] + rfl + · simp [SourceStartup.initialTapes, hk] + +def startupInTime (F : Formula) (hm : 0 < F.clauses.length) (hD : 0 < D) : + StateTransition.EvalsToInTime (SourceGeneratorProgram.machine u D hD).step + (initList (SourceGeneratorProgram.machine u D hD) (formulaBits F)) + (some ⟨some (bodyEntry u D), (initialAmbient u D hD, none), SourceStartup.readyTapes F⟩) + ((SourceStartup.timePolynomial u D).eval (formulaBits F).length) := by + have run := SourceTupleBody.framedExecution (sourceStateEquiv u D) + SourceGeneratorProgram.Label.startup (some (bodyEntry u D)) () + SourceStartup.program (SourceGeneratorProgram.program u D hD) (fun _ => rfl) + (SourceStartup.startupInPolynomialTime (u := u) F hm hD) + rw [initial_configuration F hD] + simpa only [SourceTupleBody.framedConfiguration, MachineStateFrame.configuration, + MachineControl.configuration, MachineSubroutine.configuration, + MachineStateFrame.frameConfiguration, MachineSubroutine.label, source_initial, + Option.map_some, Option.map_none, id_eq, SourceGeneratorProgram.main, + FinTM2.step, FinTM2.Cfg, SourceGeneratorProgram.machine] using! run + +end +end MinUncutGames.Foundations.Hastad.SourceGenerator + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/Generator.lean b/lean/OAI/Computability/MinUncut/PCP/Generator.lean new file mode 100644 index 0000000000000000000000000000000000000000..9fbc818678f1d72070cee0388c436239e0cdfac2 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/Generator.lean @@ -0,0 +1,223 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.TupleBound +import OAI.Computability.MinUncut.Machines.RuntimeSpace + +namespace OAI + +namespace MinUncutGames.Foundations.Hastad.SourceGenerator + +open Turing Complexity Target +open SourceGeneratorModel SourceGeneratorProgram SourceGeneratorContract + +noncomputable section + +variable {u D : Nat} +local instance generatorExtraDecidableEq : DecidableEq (Extra u D) := Classical.decEq _ + +def prefixPolynomial (u D : Nat) : Polynomial Nat := + SourceStartup.timePolynomial u D + SourceGeneratorTraversal.timePolynomial u D + 1 + +def timePolynomial (u D : Nat) (hD : 0 < D) : Polynomial Nat := + SourceRuntimeSpace.completedTime (SourceGeneratorProgram.machine u D hD) + (clearKeys u D).length (prefixPolynomial u D) + +def beforeFinish (F : Formula) (hD : 0 < D) : (SourceGeneratorProgram.machine u D hD).Cfg := + ⟨SourceRuntimeFinish.entry (clearKeys u D) SourceGeneratorProgram.Label.finish, + (initialAmbient u D hD, none), SourceGeneratorTraversal.traversalOutput F hD⟩ + +def enterFinishInTime (F : Formula) (hD : 0 < D) : + StateTransition.EvalsToInTime (SourceGeneratorProgram.machine u D hD).step + ⟨some .finishEnter, (initialAmbient u D hD, none), + SourceGeneratorTraversal.traversalOutput F hD⟩ + (some (beforeFinish F hD)) 1 where + steps := 1 + evals_in_steps := by + change some (TM2.stepAux + (Reduction.MachineTransfer.exitAt (accumulatorTape u D) + (SourceRuntimeFinish.entry (clearKeys u D) SourceGeneratorProgram.Label.finish)) + _ _) = _ + cases h : SourceRuntimeFinish.entry (clearKeys u D) SourceGeneratorProgram.Label.finish <;> + simp only [Reduction.MachineTransfer.exitAt, beforeFinish, TM2.stepAux] <;> + erw [h] <;> rfl + steps_le_m := Nat.le_refl _ + +def prefixInTime (F : Formula) (hm : 0 < F.clauses.length) (hD : 0 < D) : + StateTransition.EvalsToInTime (SourceGeneratorProgram.machine u D hD).step + (initList (SourceGeneratorProgram.machine u D hD) (formulaBits F)) + (some (beforeFinish F hD)) ((prefixPolynomial u D).eval (formulaBits F).length) := by + have start := startupInTime (u := u) F hm hD + let traversal := Classical.choice (SourceGeneratorTraversal.traversalInPolynomialTime + (u := u) F hm hD) + have first := StateTransition.EvalsToInTime.trans + (SourceGeneratorProgram.machine u D hD).step _ _ _ _ _ start traversal + have joined := StateTransition.EvalsToInTime.trans + (SourceGeneratorProgram.machine u D hD).step _ _ _ _ _ first (enterFinishInTime F hD) + refine { steps := joined.steps, evals_in_steps := joined.evals_in_steps, steps_le_m := ?_ } + apply joined.steps_le_m.trans + simp only [prefixPolynomial, Polynomial.eval_add, Polynomial.eval_one] + omega + +theorem output_empty (F : Formula) (hD : 0 < D) : + SourceGeneratorTraversal.traversalOutput F hD (outputTape u D) = [] := by + rw [SourceGeneratorTraversal.traversalOutput_frame F hD _ + (Ne.symm (accumulator_ne_output u D))] + exact SourceStartup.ready_work_blank F (.extra (.inr ())) + (by simp) (by simp) (by simp) + +theorem halted_configuration (F : Formula) (hD : 0 < D) : + (⟨none, (initialAmbient u D hD, none), + SourceRuntimeFinish.canonicalTapes (outputTape u D) + (SourceGeneratorTraversal.traversalOutput F hD (accumulatorTape u D)).reverse⟩ : + (SourceGeneratorProgram.machine u D hD).Cfg) = + haltList (SourceGeneratorProgram.machine u D hD) + (MinUncutGames.Reduction.SourceEncoding.inputBits (SourceOccurrences.sourceInput F u D hD)) := by + rw [SourceGeneratorTraversal.traversalOutput_accumulator, List.reverse_reverse] + simp only [haltList, SourceGeneratorProgram.machine] + congr 1 + funext k + by_cases hk : k = outputTape u D + · subst k + simp [SourceRuntimeFinish.canonicalTapes] + erw [Function.update_self] + rfl + · simp [SourceRuntimeFinish.canonicalTapes, hk] + erw [Function.update_of_ne hk] + +def outputInTime (F : NonemptyFormula) (hD : 0 < D) : + TM2OutputsInTime (SourceGeneratorProgram.machine u D hD) (inputEncoding F) + (some (MinUncutGames.Reduction.SourceEncoding.inputBits (sourceMap u D hD F))) + ((timePolynomial u D hD).eval (inputEncoding F).length) := by + have hm : 0 < F.val.clauses.length := List.length_pos_iff.mpr F.property + have prefixRun := prefixInTime (u := u) F.val hm hD + have keepAcc : accumulatorTape u D ∉ clearKeys u D := by + simp [mem_clearKeys] + have keepOut : outputTape u D ∉ clearKeys u D := by + simp [mem_clearKeys] + have covers : ∀ k, k ≠ accumulatorTape u D → k ≠ outputTape u D → k ∈ clearKeys u D := + fun k ha ho => (mem_clearKeys u D k).mpr ⟨ha, ho⟩ + have finish := SourceRuntimeFinish.finishInTime (clearKeys u D) + (accumulatorTape u D) (outputTape u D) (accumulator_ne_output u D) + keepAcc keepOut covers (initialAmbient u D hD) SourceGeneratorProgram.Label.finish none + (SourceGeneratorProgram.program u D hD) (fun _ => rfl) + (SourceGeneratorTraversal.traversalOutput F.val hD) (output_empty F.val hD) + (initialAmbient u D hD) none + erw [halted_configuration F.val hD] at finish + have joined := SourceRuntimeSpace.prefixAndFinishInTime + (SourceGeneratorProgram.machine u D hD) (formulaBits F.val) (prefixPolynomial u D) + prefixRun (clearKeys u D) (accumulatorTape u D) (outputTape u D) + keepAcc keepOut covers (SourceGeneratorTraversal.traversalOutput F.val hD) + (output_empty F.val hD) (fun _ => rfl) finish + exact joined + +def computableInPolyTime (u D : Nat) (hD : 0 < D) : + TM2ComputableInPolyTime inputEncoding MinUncutGames.Reduction.SourceEncoding.inputBits + (sourceMap u D hD) where + tm := SourceGeneratorProgram.machine u D hD + inputAlphabet := Equiv.refl Bool + outputAlphabet := Equiv.refl Bool + time := timePolynomial u D hD + outputsFun F := by + change TM2OutputsInTime (machine u D hD) ((inputEncoding F).map id) + (some ((MinUncutGames.Reduction.SourceEncoding.inputBits (sourceMap u D hD F)).map id)) _ + have input_eq : @List.map ((machine u D hD).Γ (machine u D hD).k₀) + ((machine u D hD).Γ (machine u D hD).k₀) id (inputEncoding F) = + inputEncoding F := List.map_id _ + have output_eq : @List.map ((machine u D hD).Γ (machine u D hD).k₁) + ((machine u D hD).Γ (machine u D hD).k₁) id + (MinUncutGames.Reduction.SourceEncoding.inputBits (sourceMap u D hD F)) = + MinUncutGames.Reduction.SourceEncoding.inputBits (sourceMap u D hD F) := List.map_id _ + simpa only [input_eq, output_eq] using outputInTime (u := u) F hD + +theorem finite_work_alphabets (u D : Nat) (hD : 0 < D) + (k : (computableInPolyTime u D hD).tm.K) : + Finite ((computableInPolyTime u D hD).tm.Γ k) := by + change Finite Bool + infer_instance + +def forErrorComputableInPolyTime (η ξ : ℚ) (hη : 0 < η) (hη1 : η ≤ 1) (hξ : 0 < ξ) : + TM2ComputableInPolyTime inputEncoding MinUncutGames.Reduction.SourceEncoding.inputBits + (errorMap η ξ hη hη1 hξ) := by + let D := SourceNoiseParameter.noiseDenominator ξ + let hD := SourceNoiseParameter.noiseDenominator_pos ξ + let u := SourceGap.repetitionCount η ξ hη hη1 hξ D hD + exact computableInPolyTime u D hD + +theorem forError_finite_work_alphabets (η ξ : ℚ) (hη : 0 < η) (hη1 : η ≤ 1) (hξ : 0 < ξ) + (k : (forErrorComputableInPolyTime η ξ hη hη1 hξ).tm.K) : + Finite ((forErrorComputableInPolyTime η ξ hη hη1 hξ).tm.Γ k) := by + change Finite Bool + infer_instance + +end + +end MinUncutGames.Foundations.Hastad.SourceGenerator + +namespace MinUncutGames.Foundations.PCP + +structure ConstraintGraph (V E A : Type*) where + reverse : E ≃ E + reverse_involutive : Function.Involutive reverse + tail : E → V + accepts : E → A → A → Bool + reverse_accepts : ∀ e a b, accepts (reverse e) b a = accepts e a b + +namespace ConstraintGraph + +variable {V E A : Type*} + +def head (G : ConstraintGraph V E A) (e : E) : V := G.tail (G.reverse e) + +@[simp] theorem head_reverse (G : ConstraintGraph V E A) (e : E) : + G.head (G.reverse e) = G.tail e := by + simp only [head, G.reverse_involutive e] + +def edgeSatisfied (G : ConstraintGraph V E A) (labeling : V → A) (e : E) : Bool := + G.accepts e (labeling (G.tail e)) (labeling (G.head e)) + +@[simp] theorem edgeSatisfied_reverse (G : ConstraintGraph V E A) + (labeling : V → A) (e : E) : + G.edgeSatisfied labeling (G.reverse e) = G.edgeSatisfied labeling e := by + simpa only [edgeSatisfied, head, G.reverse_involutive e] using + G.reverse_accepts e (labeling (G.tail e)) (labeling (G.tail (G.reverse e))) + +def Satisfiable (G : ConstraintGraph V E A) : Prop := + ∃ labeling : V → A, ∀ e, G.edgeSatisfied labeling e = true + +def rejectedDarts [Fintype E] (G : ConstraintGraph V E A) (labeling : V → A) : + Finset E := Finset.univ.filter (fun e => G.edgeSatisfied labeling e = false) + +def rejectionCount [Fintype E] (G : ConstraintGraph V E A) (labeling : V → A) : Nat := + (G.rejectedDarts labeling).card + +theorem mem_rejectedDarts [Fintype E] (G : ConstraintGraph V E A) + (labeling : V → A) (e : E) : + e ∈ G.rejectedDarts labeling ↔ G.edgeSatisfied labeling e = false := by + simp [rejectedDarts] + +theorem rejectionCount_le [Fintype E] (G : ConstraintGraph V E A) + (labeling : V → A) : G.rejectionCount labeling ≤ Fintype.card E := by + exact Finset.card_le_card (Finset.filter_subset _ _) + +theorem rejected_exists_of_not_satisfiable (G : ConstraintGraph V E A) + (unsat : ¬ G.Satisfiable) (labeling : V → A) : + ∃ e, G.edgeSatisfied labeling e = false := by + classical + by_contra none + apply unsat + refine ⟨labeling, fun e => ?_⟩ + have notFalse : G.edgeSatisfied labeling e ≠ false := by + intro h + exact none ⟨e, h⟩ + cases h : G.edgeSatisfied labeling e <;> simp_all + +theorem rejectionCount_positive [Fintype E] (G : ConstraintGraph V E A) + (unsat : ¬ G.Satisfiable) (labeling : V → A) : + 1 ≤ G.rejectionCount labeling := by + obtain ⟨e, he⟩ := G.rejected_exists_of_not_satisfiable unsat labeling + exact Finset.one_le_card.mpr ⟨e, (G.mem_rejectedDarts labeling e).mpr he⟩ + +end ConstraintGraph + +end MinUncutGames.Foundations.PCP + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/GraphGap.lean b/lean/OAI/Computability/MinUncut/PCP/GraphGap.lean new file mode 100644 index 0000000000000000000000000000000000000000..09e39bc9e2b7c8ca38fd53f7b9f4daec423a00dd --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/GraphGap.lean @@ -0,0 +1,743 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.ExpanderFamily +import OAI.Computability.MinUncut.PCP.Overlay + +namespace OAI + +noncomputable section + +namespace MinUncutGames.Foundations.PCP.ConstraintGraph + +variable {V E A : Type*} + +section Minimum + +variable [Fintype V] [Fintype E] [Fintype A] [Nonempty A] + +def rejectionCounts (G : ConstraintGraph V E A) : Finset Nat := by + classical + exact Finset.univ.image G.rejectionCount + +theorem rejectionCounts_nonempty (G : ConstraintGraph V E A) : + G.rejectionCounts.Nonempty := by + classical + exact Finset.univ_nonempty.image G.rejectionCount + +def minimumRejections (G : ConstraintGraph V E A) : Nat := + G.rejectionCounts.min' G.rejectionCounts_nonempty + +theorem minimumRejections_le (G : ConstraintGraph V E A) (labeling : V → A) : + G.minimumRejections ≤ G.rejectionCount labeling := by + classical + exact Finset.min'_le _ _ (Finset.mem_image.mpr ⟨labeling, Finset.mem_univ _, rfl⟩) + +theorem exists_minimizer (G : ConstraintGraph V E A) : + ∃ labeling : V → A, G.rejectionCount labeling = G.minimumRejections := by + classical + have h := Finset.min'_mem G.rejectionCounts G.rejectionCounts_nonempty + obtain ⟨labeling, _, heq⟩ := Finset.mem_image.mp h + exact ⟨labeling, heq⟩ + +theorem le_minimumRejections_iff (G : ConstraintGraph V E A) (bound : Nat) : + bound ≤ G.minimumRejections ↔ ∀ labeling : V → A, bound ≤ G.rejectionCount labeling := by + constructor + · intro h labeling + exact h.trans (G.minimumRejections_le labeling) + · intro h + obtain ⟨labeling, heq⟩ := G.exists_minimizer + rw [← heq] + exact h labeling + +theorem minimumRejections_le_card (G : ConstraintGraph V E A) : + G.minimumRejections ≤ Fintype.card E := by + obtain ⟨labeling, heq⟩ := G.exists_minimizer + rw [← heq] + exact G.rejectionCount_le labeling + +omit [Fintype V] [Fintype A] [Nonempty A] in +theorem rejectionCount_eq_zero_iff (G : ConstraintGraph V E A) (labeling : V → A) : + G.rejectionCount labeling = 0 ↔ ∀ e, G.edgeSatisfied labeling e = true := by + classical + constructor + · intro h e + have hempty : G.rejectedDarts labeling = ∅ := Finset.card_eq_zero.mp h + cases he : G.edgeSatisfied labeling e with + | false => + have hm := (G.mem_rejectedDarts labeling e).mpr he + rw [hempty] at hm + simp at hm + | true => rfl + · intro h + simp [rejectionCount, rejectedDarts, h] + +theorem minimumRejections_eq_zero_iff (G : ConstraintGraph V E A) : + G.minimumRejections = 0 ↔ G.Satisfiable := by + constructor + · intro h + obtain ⟨labeling, heq⟩ := G.exists_minimizer + exact ⟨labeling, (G.rejectionCount_eq_zero_iff labeling).mp (heq.trans h)⟩ + · rintro ⟨labeling, h⟩ + have hc := (G.rejectionCount_eq_zero_iff labeling).mpr h + exact Nat.eq_zero_of_le_zero (hc ▸ G.minimumRejections_le labeling) + +def gap (G : ConstraintGraph V E A) : ℝ := + (G.minimumRejections : ℝ) / Fintype.card E + +theorem gap_nonnegative (G : ConstraintGraph V E A) : 0 ≤ G.gap := + div_nonneg (Nat.cast_nonneg _) (Nat.cast_nonneg _) + +theorem gap_le_one [Nonempty E] (G : ConstraintGraph V E A) : G.gap ≤ 1 := by + have he : (0 : ℝ) < Fintype.card E := by exact_mod_cast Fintype.card_pos + apply (div_le_iff₀ he).mpr + simpa only [one_mul] using (Nat.cast_le.mpr G.minimumRejections_le_card : + (G.minimumRejections : ℝ) ≤ (Fintype.card E : ℝ)) + +theorem gap_eq_zero_iff [Nonempty E] (G : ConstraintGraph V E A) : + G.gap = 0 ↔ G.Satisfiable := by + have he : (Fintype.card E : ℝ) ≠ 0 := by exact_mod_cast Fintype.card_ne_zero + simp only [gap, div_eq_zero_iff, he, or_false, Nat.cast_eq_zero] + exact G.minimumRejections_eq_zero_iff + +theorem le_gap_iff [Nonempty E] (G : ConstraintGraph V E A) (ε : ℝ) : + ε ≤ G.gap ↔ ∀ labeling : V → A, + ε * Fintype.card E ≤ (G.rejectionCount labeling : ℝ) := by + have he : (0 : ℝ) < Fintype.card E := by exact_mod_cast Fintype.card_pos + change ε ≤ (G.minimumRejections : ℝ) / Fintype.card E ↔ _ + rw [le_div_iff₀ he] + constructor + · intro h labeling + exact h.trans (Nat.cast_le.mpr (G.minimumRejections_le labeling)) + · intro h + obtain ⟨labeling, heq⟩ := G.exists_minimizer + simpa only [heq] using h labeling + +theorem inverse_card_le_gap_of_unsatisfiable [Nonempty E] + (G : ConstraintGraph V E A) (unsat : ¬ G.Satisfiable) : + 1 / (Fintype.card E : ℝ) ≤ G.gap := by + apply (G.le_gap_iff _).mpr + intro labeling + have he : (Fintype.card E : ℝ) ≠ 0 := by exact_mod_cast Fintype.card_ne_zero + have hc : (1 : ℝ) ≤ (G.rejectionCount labeling : ℝ) := by + exact_mod_cast G.rejectionCount_positive unsat labeling + simpa only [div_mul_cancel₀ _ he] using hc + +end Minimum + +variable {W D B : Type*} + +def reindex (G : ConstraintGraph V E A) (vertices : V ≃ W) (darts : E ≃ D) + (labels : A ≃ B) : ConstraintGraph W D B where + reverse := darts.symm.trans (G.reverse.trans darts) + reverse_involutive := by + intro d + change darts (G.reverse (darts.symm (darts (G.reverse (darts.symm d))))) = d + rw [darts.symm_apply_apply, G.reverse_involutive, darts.apply_symm_apply] + tail := fun d => vertices (G.tail (darts.symm d)) + accepts := fun d a b => G.accepts (darts.symm d) (labels.symm a) (labels.symm b) + reverse_accepts := by + intro d a b + simpa only [Equiv.trans_apply, darts.symm_apply_apply] using + G.reverse_accepts (darts.symm d) (labels.symm a) (labels.symm b) + +def labelingEquiv (vertices : V ≃ W) (labels : A ≃ B) : (V → A) ≃ (W → B) where + toFun := fun labeling w => labels (labeling (vertices.symm w)) + invFun := fun labeling v => labels.symm (labeling (vertices v)) + left_inv := by intro labeling; funext v; simp + right_inv := by intro labeling; funext w; simp + +theorem reindex_edgeSatisfied (G : ConstraintGraph V E A) + (vertices : V ≃ W) (darts : E ≃ D) (labels : A ≃ B) + (labeling : V → A) (e : E) : + (G.reindex vertices darts labels).edgeSatisfied (labelingEquiv vertices labels labeling) + (darts e) = G.edgeSatisfied labeling e := by + simp [reindex, labelingEquiv, edgeSatisfied, head, Equiv.trans_apply] + +theorem reindex_rejectionCount [Fintype E] [Fintype D] (G : ConstraintGraph V E A) + (vertices : V ≃ W) (darts : E ≃ D) (labels : A ≃ B) (labeling : V → A) : + (G.reindex vertices darts labels).rejectionCount (labelingEquiv vertices labels labeling) = + G.rejectionCount labeling := by + classical + unfold rejectionCount + symm + apply Finset.card_bij (fun e _ => darts e) + · intro e he + rw [mem_rejectedDarts, reindex_edgeSatisfied] + exact (G.mem_rejectedDarts labeling e).mp he + · intro e _ f _ h + exact darts.injective h + · intro d hd + refine ⟨darts.symm d, ?_, darts.apply_symm_apply d⟩ + rw [mem_rejectedDarts] + rw [← reindex_edgeSatisfied G vertices darts labels labeling (darts.symm d)] + rw [darts.apply_symm_apply] + exact (mem_rejectedDarts _ _ _).mp hd + +variable [Fintype V] [Fintype E] [Fintype A] [Nonempty A] + [Fintype W] [Fintype D] [Fintype B] [Nonempty B] + +omit [Nonempty A] [Nonempty B] in +theorem rejectionCounts_reindex (G : ConstraintGraph V E A) + (vertices : V ≃ W) (darts : E ≃ D) (labels : A ≃ B) : + (G.reindex vertices darts labels).rejectionCounts = G.rejectionCounts := by + classical + ext n + simp only [rejectionCounts, Finset.mem_image, Finset.mem_univ, true_and] + constructor + · rintro ⟨labeling, hn⟩ + refine ⟨(labelingEquiv vertices labels).symm labeling, ?_⟩ + rw [← reindex_rejectionCount G vertices darts labels, + Equiv.apply_symm_apply] + exact hn + · rintro ⟨labeling, hn⟩ + refine ⟨labelingEquiv vertices labels labeling, ?_⟩ + rw [reindex_rejectionCount] + exact hn + +theorem minimumRejections_reindex (G : ConstraintGraph V E A) + (vertices : V ≃ W) (darts : E ≃ D) (labels : A ≃ B) : + (G.reindex vertices darts labels).minimumRejections = G.minimumRejections := by + unfold minimumRejections + simp only [rejectionCounts_reindex] + +theorem gap_reindex (G : ConstraintGraph V E A) + (vertices : V ≃ W) (darts : E ≃ D) (labels : A ≃ B) : + (G.reindex vertices darts labels).gap = G.gap := by + unfold gap + rw [minimumRejections_reindex, Fintype.card_congr darts] + +theorem satisfiable_reindex (G : ConstraintGraph V E A) + (vertices : V ≃ W) (darts : E ≃ D) (labels : A ≃ B) : + (G.reindex vertices darts labels).Satisfiable ↔ G.Satisfiable := by + rw [← minimumRejections_eq_zero_iff, minimumRejections_reindex, + minimumRejections_eq_zero_iff] + +end MinUncutGames.Foundations.PCP.ConstraintGraph + +end +namespace MinUncutGames.Foundations.PCP.PreprocessingOverlayTables + +open PoweringWalks + +def overlayPorts (d e : Nat) : (Fin d ⊕ Fin e) ≃ Fin (d + e) := finSumFinEquiv + +@[simp] theorem overlayPorts_inl_val (d e : Nat) (i : Fin d) : + (overlayPorts d e (Sum.inl i)).val = i.val := rfl + +@[simp] theorem overlayPorts_inr_val (d e : Nat) (i : Fin e) : + (overlayPorts d e (Sum.inr i)).val = d + i.val := rfl + +def lazyPorts (d : Nat) : (Bool × Fin d) ≃ Fin (2 * d) := + (Equiv.prodCongr finTwoEquiv.symm (Equiv.refl (Fin d))).trans finProdFinEquiv + +@[simp] theorem lazyPorts_false_val (d : Nat) (i : Fin d) : + (lazyPorts d (false, i)).val = i.val := by + simp [lazyPorts, finTwoEquiv, finProdFinEquiv] + +@[simp] theorem lazyPorts_true_val (d : Nat) (i : Fin d) : + (lazyPorts d (true, i)).val = i.val + d := by + simp [lazyPorts, finTwoEquiv, finProdFinEquiv] + +def materialize {n d : Nat} {D : Type*} + (G : ConstraintGraph (Fin n) (Fin n × D) PortTables.Label) + (ports : D ≃ Fin d) : PortTables.Table n d := + PortTables.ofPortGraph + (GraphTransport.reindex (Overlay.originalPortGraph G) (Equiv.refl _) ports) + (fun x a b => G.accepts (x.1, ports.symm x.2) a b) + (by + intro x a b + simp only [GraphTransport.reindex, Overlay.originalPortGraph, + Equiv.trans_apply, Equiv.prodCongr_apply, Equiv.prodCongr_symm, + Equiv.refl_apply, Equiv.symm_apply_apply, Prod.map] + convert G.reverse_accepts (x.1, ports.symm x.2) a b using 1 + rfl) + +theorem rotation_materialize {n d : Nat} {D : Type*} + (G : ConstraintGraph (Fin n) (Fin n × D) PortTables.Label) + (ports : D ≃ Fin d) (x : Fin n × Fin d) : + PortTables.rotation (materialize G ports) x = + ((G.reverse (x.1, ports.symm x.2)).1, + ports (G.reverse (x.1, ports.symm x.2)).2) := by + simp only [materialize, PortTables.rotation_ofPortGraph, GraphTransport.reindex, + Overlay.originalPortGraph, Equiv.trans_apply, Equiv.prodCongr_apply, + Equiv.prodCongr_symm, Equiv.refl_apply, Prod.map] + rfl + +theorem rotation_materialize_image {n d : Nat} {D : Type*} + (G : ConstraintGraph (Fin n) (Fin n × D) PortTables.Label) + (ports : D ≃ Fin d) (v : Fin n) (i : D) : + PortTables.rotation (materialize G ports) (v, ports i) = + ((G.reverse (v, i)).1, ports (G.reverse (v, i)).2) := by + rw [rotation_materialize, Equiv.symm_apply_apply] + +@[simp] theorem accepts_materialize {n d : Nat} {D : Type*} + (G : ConstraintGraph (Fin n) (Fin n × D) PortTables.Label) + (ports : D ≃ Fin d) (x : Fin n × Fin d) (a b : PortTables.Label) : + PortTables.accepts (materialize G ports) x a b = + G.accepts (x.1, ports.symm x.2) a b := by + exact PortTables.accepts_ofPortGraph _ _ _ x a b + +theorem constraintGraph_ext {V E A : Type*} {G H : ConstraintGraph V E A} + (hreverse : ∀ e, G.reverse e = H.reverse e) + (htail : ∀ e, G.tail e = H.tail e) + (haccepts : ∀ e a b, G.accepts e a b = H.accepts e a b) : G = H := by + rcases G with ⟨r, hi, t, p, hp⟩ + rcases H with ⟨r', hi', t', p', hp'⟩ + have hr : r = r' := Equiv.ext hreverse + cases hr + have ht : t = t' := funext htail + cases ht + have ha : p = p' := funext fun e => funext fun a => funext fun b => haccepts e a b + cases ha + rfl + +theorem baseGraph_materialize {n d : Nat} {D : Type*} + (G : ConstraintGraph (Fin n) (Fin n × D) PortTables.Label) + (ports : D ≃ Fin d) (htail : G.tail = Prod.fst) : + PortTables.baseGraph (materialize G ports) = + G.reindex (Equiv.refl _) (Equiv.prodCongr (Equiv.refl _) ports) (Equiv.refl _) := by + apply constraintGraph_ext + · intro x + rw [PortTables.baseGraph_reverse, rotation_materialize] + rfl + · intro x + change x.1 = G.tail (x.1, ports.symm x.2) + rw [htail] + · intro x a b + rw [PortTables.baseGraph_accepts, accepts_materialize] + rfl + +def overlay {n d e : Nat} (G : PortTables.Table n d) (H : ExpanderTables.Table n e) : + PortTables.Table n (d + e) := + materialize (Overlay.constraintGraph (PortTables.baseGraph G) (ExpanderTables.graph H)) + (overlayPorts d e) + +theorem overlay_rotation_old {n d e : Nat} (G : PortTables.Table n d) + (H : ExpanderTables.Table n e) (v : Fin n) (i : Fin d) : + PortTables.rotation (overlay G H) (v, overlayPorts d e (Sum.inl i)) = + ((PortTables.rotation G (v, i)).1, + overlayPorts d e (Sum.inl (PortTables.rotation G (v, i)).2)) := by + exact rotation_materialize_image _ _ v (Sum.inl i) + +theorem overlay_rotation_expander {n d e : Nat} (G : PortTables.Table n d) + (H : ExpanderTables.Table n e) (v : Fin n) (i : Fin e) : + PortTables.rotation (overlay G H) (v, overlayPorts d e (Sum.inr i)) = + ((ExpanderTables.lookup H (v, i)).1, + overlayPorts d e (Sum.inr (ExpanderTables.lookup H (v, i)).2)) := by + exact rotation_materialize_image _ _ v (Sum.inr i) + +@[simp] theorem overlay_accepts_old {n d e : Nat} (G : PortTables.Table n d) + (H : ExpanderTables.Table n e) (v : Fin n) (i : Fin d) (a b : PortTables.Label) : + PortTables.accepts (overlay G H) (v, overlayPorts d e (Sum.inl i)) a b = + PortTables.accepts G (v, i) a b := by + simp only [overlay, accepts_materialize, Equiv.symm_apply_apply] + rfl + +@[simp] theorem overlay_accepts_expander {n d e : Nat} (G : PortTables.Table n d) + (H : ExpanderTables.Table n e) (v : Fin n) (i : Fin e) (a b : PortTables.Label) : + PortTables.accepts (overlay G H) (v, overlayPorts d e (Sum.inr i)) a b = true := by + simp only [overlay, accepts_materialize, Equiv.symm_apply_apply] + rfl + +theorem overlay_semantics {n d e : Nat} (G : PortTables.Table n d) + (H : ExpanderTables.Table n e) : + PortTables.baseGraph (overlay G H) = + (Overlay.constraintGraph (PortTables.baseGraph G) (ExpanderTables.graph H)).reindex + (Equiv.refl _) (Equiv.prodCongr (Equiv.refl _) (overlayPorts d e)) + (Equiv.refl _) := + baseGraph_materialize _ _ rfl + +def lazy {n d : Nat} (G : PortTables.Table n d) : PortTables.Table n (2 * d) := + materialize (LazyConstraint.constraintGraph (PortTables.baseGraph G)) (lazyPorts d) + +theorem lazy_rotation_false {n d : Nat} (G : PortTables.Table n d) + (v : Fin n) (i : Fin d) : + PortTables.rotation (lazy G) (v, lazyPorts d (false, i)) = + (v, lazyPorts d (false, i)) := by + exact rotation_materialize_image _ _ v (false, i) + +theorem lazy_rotation_true {n d : Nat} (G : PortTables.Table n d) + (v : Fin n) (i : Fin d) : + PortTables.rotation (lazy G) (v, lazyPorts d (true, i)) = + ((PortTables.rotation G (v, i)).1, + lazyPorts d (true, (PortTables.rotation G (v, i)).2)) := by + exact rotation_materialize_image _ _ v (true, i) + +@[simp] theorem lazy_accepts_false {n d : Nat} (G : PortTables.Table n d) + (v : Fin n) (i : Fin d) (a b : PortTables.Label) : + PortTables.accepts (lazy G) (v, lazyPorts d (false, i)) a b = true := by + simp only [lazy, accepts_materialize, Equiv.symm_apply_apply] + rfl + +@[simp] theorem lazy_accepts_true {n d : Nat} (G : PortTables.Table n d) + (v : Fin n) (i : Fin d) (a b : PortTables.Label) : + PortTables.accepts (lazy G) (v, lazyPorts d (true, i)) a b = + PortTables.accepts G (v, i) a b := by + simp only [lazy, accepts_materialize, Equiv.symm_apply_apply] + rfl + +theorem lazy_semantics {n d : Nat} (G : PortTables.Table n d) : + PortTables.baseGraph (lazy G) = + (LazyConstraint.constraintGraph (PortTables.baseGraph G)).reindex + (Equiv.refl _) (Equiv.prodCongr (Equiv.refl _) (lazyPorts d)) (Equiv.refl _) := + baseGraph_materialize _ _ rfl + +end MinUncutGames.Foundations.PCP.PreprocessingOverlayTables + +namespace MinUncutGames.Foundations.PCP.CloudRounding + +open scoped BigOperators + +theorem dart_rejection_count_le + {E V A : Type*} [Fintype E] [DecidableEq A] + (tail : E → V) (reverse : E ≃ E) (accepts : E → A → A → Bool) + (ell : E → A) (rounded : V → A) : + (Finset.univ.filter (fun e => + accepts e (rounded (tail e)) (rounded (tail (reverse e))) = false)).card ≤ + (Finset.univ.filter (fun e => accepts e (ell e) (ell (reverse e)) = false)).card + + 2 * (Finset.univ.filter (fun e => ell e ≠ rounded (tail e))).card := by + classical + let R : Finset E := Finset.univ.filter (fun e => + accepts e (rounded (tail e)) (rounded (tail (reverse e))) = false) + let B : Finset E := Finset.univ.filter (fun e => + accepts e (ell e) (ell (reverse e)) = false) + let M : Finset E := Finset.univ.filter (fun e => ell e ≠ rounded (tail e)) + let MR : Finset E := Finset.univ.filter (fun e => + ell (reverse e) ≠ rounded (tail (reverse e))) + have hrev : MR.card = M.card := by + have hsets : MR = M.map reverse.symm.toEmbedding := by + ext e + constructor + · intro he + apply Finset.mem_map.mpr + refine ⟨reverse e, ?_, reverse.symm_apply_apply e⟩ + simpa [MR, M] using he + · intro he + obtain ⟨d, hd, rfl⟩ := Finset.mem_map.mp he + simpa [MR, M] using hd + rw [hsets, Finset.card_map] + have hsub : R ⊆ (B ∪ M) ∪ MR := by + intro e he + by_cases hl : ell e = rounded (tail e) + · by_cases hr : ell (reverse e) = rounded (tail (reverse e)) + · have hb : e ∈ B := by simpa [B, R, hl, hr] using he + exact Finset.mem_union_left _ (Finset.mem_union_left _ hb) + · exact Finset.mem_union_right _ (by simp [MR, hr]) + · exact Finset.mem_union_left _ (Finset.mem_union_right _ (by simp [M, hl])) + change R.card ≤ B.card + 2 * M.card + calc + R.card ≤ ((B ∪ M) ∪ MR).card := Finset.card_le_card hsub + _ ≤ (B ∪ M).card + MR.card := Finset.card_union_le _ _ + _ ≤ (B.card + M.card) + MR.card := + Nat.add_le_add_right (Finset.card_union_le B M) _ + _ = B.card + 2 * M.card := by rw [hrev]; omega + +section CloudCounts + +variable {X A D : Type*} [Fintype X] [Fintype A] [Fintype D] +variable [DecidableEq X] [DecidableEq A] + +def colorSet (ell : X → A) (a : A) : Finset X := + Finset.univ.filter (fun x => ell x = a) + +def minoritySet (ell : X → A) (m : A) : Finset X := + Finset.univ.filter (fun x => ell x ≠ m) + +def directedCut (next : X × D → X) (S : Finset X) : Finset (X × D) := + Finset.univ.filter (fun xd => xd.1 ∈ S ∧ next xd ∉ S) + +def disagreementSet (ell : X → A) (next : X × D → X) : Finset (X × D) := + Finset.univ.filter (fun xd => ell xd.1 ≠ ell (next xd)) + +abbrev Nonmajor (m : A) := {a : A // a ≠ m} + +omit [DecidableEq X] in +theorem exists_max_color (ell : X → A) [Nonempty A] : + ∃ m : A, ∀ a, (colorSet ell a).card ≤ (colorSet ell m).card := by + classical + obtain ⟨m, _, hm⟩ := Finset.exists_max_image Finset.univ + (fun a : A => (colorSet ell a).card) Finset.univ_nonempty + exact ⟨m, fun a => hm a (Finset.mem_univ a)⟩ + +noncomputable def majority (ell : X → A) [Nonempty A] : A := + Classical.choose (exists_max_color ell) + +omit [DecidableEq X] in +theorem majority_maximal (ell : X → A) [Nonempty A] (a : A) : + (colorSet ell a).card ≤ (colorSet ell (majority ell)).card := + Classical.choose_spec (exists_max_color ell) a + +omit [Fintype A] in +theorem nonchosen_color_twice_le (ell : X → A) (m : A) + (maximal : ∀ a, (colorSet ell a).card ≤ (colorSet ell m).card) + (a : A) (ha : a ≠ m) : + 2 * (colorSet ell a).card ≤ Fintype.card X := by + have hd : Disjoint (colorSet ell a) (colorSet ell m) := by + apply Finset.disjoint_left.mpr + intro x hx hm + have hxa : ell x = a := by simpa [colorSet] using hx + have hxm : ell x = m := by simpa [colorSet] using hm + exact ha (hxa.symm.trans hxm) + have hu : (colorSet ell a).card + (colorSet ell m).card ≤ Fintype.card X := by + calc + _ = (colorSet ell a ∪ colorSet ell m).card := + (Finset.card_union_of_disjoint hd).symm + _ ≤ Finset.univ.card := Finset.card_le_card (Finset.subset_univ _) + _ = Fintype.card X := Finset.card_univ + have hm := maximal a + omega + +def minorityEquiv (ell : X → A) (m : A) : + (Σ a : Nonmajor m, ↥(colorSet ell a.val)) ≃ ↥(minoritySet ell m) where + toFun t := ⟨t.2.val, by + have hc : ell t.2.val = t.1.val := (Finset.mem_filter.mp t.2.property).2 + have hn : ell t.2.val ≠ m := fun h => t.1.property (hc.symm.trans h) + simpa [minoritySet] using hn⟩ + invFun x := + ⟨⟨ell x.val, by simpa [minoritySet] using x.property⟩, + ⟨x.val, by simp [colorSet]⟩⟩ + left_inv t := by + rcases t with ⟨⟨a, ha⟩, ⟨x, hx⟩⟩ + have hxa : ell x = a := by simpa [colorSet] using hx + cases hxa + rfl + right_inv x := by apply Subtype.ext; rfl + +omit [DecidableEq X] in +theorem minority_card_eq_sum (ell : X → A) (m : A) : + (minoritySet ell m).card = ∑ a : Nonmajor m, (colorSet ell a.val).card := by + have h := Fintype.card_congr (minorityEquiv ell m) + simpa only [Fintype.card_sigma, Fintype.card_coe] using h.symm + +def minorityCutEmbedding (ell : X → A) (next : X × D → X) (m : A) : + (Σ a : Nonmajor m, ↥(directedCut next (colorSet ell a.val))) ↪ + ↥(disagreementSet ell next) where + toFun t := ⟨t.2.val, by + have hc : ell t.2.val.1 = t.1.val ∧ ell (next t.2.val) ≠ t.1.val := by + simpa [directedCut, colorSet] using t.2.property + have hn : ell t.2.val.1 ≠ ell (next t.2.val) := + fun h => hc.2 (h.symm.trans hc.1) + simpa [disagreementSet] using hn⟩ + inj' p q h := by + rcases p with ⟨⟨a, ha⟩, ⟨x, hx⟩⟩ + rcases q with ⟨⟨b, hb⟩, ⟨y, hy⟩⟩ + have hxy : x = y := congrArg Subtype.val h + cases hxy + have hxa : ell x.1 = a := by + have hc : ell x.1 = a ∧ ell (next x) ≠ a := by + simpa [directedCut, colorSet] using hx + exact hc.1 + have hxb : ell x.1 = b := by + have hc : ell x.1 = b ∧ ell (next x) ≠ b := by + simpa [directedCut, colorSet] using hy + exact hc.1 + have hab : a = b := hxa.symm.trans hxb + cases hab + rfl + +theorem minority_cut_sum_le (ell : X → A) (next : X × D → X) (m : A) : + (∑ a : Nonmajor m, (directedCut next (colorSet ell a.val)).card) ≤ + (disagreementSet ell next).card := by + have h := Fintype.card_le_of_injective + (minorityCutEmbedding ell next m) (minorityCutEmbedding ell next m).injective + simpa only [Fintype.card_sigma, Fintype.card_coe] using h + +theorem minority_expansion_bound (ell : X → A) (next : X × D → X) (m : A) + (h : ℚ) + (maximal : ∀ a, (colorSet ell a).card ≤ (colorSet ell m).card) + (expansion : ∀ S : Finset X, S.card ≤ Fintype.card X / 2 → + h * (S.card : ℚ) ≤ ((directedCut next S).card : ℚ)) : + h * ((minoritySet ell m).card : ℚ) ≤ ((disagreementSet ell next).card : ℚ) := by + have each (a : Nonmajor m) : + h * ((colorSet ell a.val).card : ℚ) ≤ + ((directedCut next (colorSet ell a.val)).card : ℚ) := by + apply expansion + have ha := nonchosen_color_twice_le ell m maximal a.val a.property + omega + calc + h * ((minoritySet ell m).card : ℚ) = + ∑ a : Nonmajor m, h * ((colorSet ell a.val).card : ℚ) := by + rw [minority_card_eq_sum, Nat.cast_sum, Finset.mul_sum] + _ ≤ ∑ a : Nonmajor m, ((directedCut next (colorSet ell a.val)).card : ℚ) := + Finset.sum_le_sum (fun a _ => each a) + _ ≤ ((disagreementSet ell next).card : ℚ) := by + exact_mod_cast minority_cut_sum_le ell next m + +end CloudCounts + +section GraphRounding + +open DegreeReplacement PoweringWalks + +variable {V E A D : Type*} [Fintype V] [Fintype E] [Fintype A] [Fintype D] +variable [DecidableEq V] [DecidableEq E] [DecidableEq A] + +def mismatchSet (G : ConstraintGraph V E A) (ell : E → A) (rounded : V → A) : + Finset E := + Finset.univ.filter (fun e => ell e ≠ rounded (G.tail e)) + +def copiedRejectionCount (G : ConstraintGraph V E A) (ell : E → A) : Nat := + (Finset.univ.filter (fun e => G.accepts e (ell e) (ell (G.reverse e)) = false)).card + +def innerDisagreementSet (G : ConstraintGraph V E A) + (H : ∀ v, PortGraph (Cloud G v) D) (ell : E → A) : Finset (E × D) := + Finset.univ.filter (fun ed => ell ed.1 ≠ ell (innerRotation G H ed).1) + +noncomputable def roundLabels [Nonempty A] + (G : ConstraintGraph V E A) (ell : E → A) : V → A := + fun v => majority (fun e : Cloud G v => ell e.val) + +def mismatchFiberEquiv (G : ConstraintGraph V E A) (ell : E → A) + (rounded : V → A) : + (Σ v, ↥(minoritySet (fun e : Cloud G v => ell e.val) (rounded v))) ≃ + ↥(mismatchSet G ell rounded) where + toFun := by + rintro ⟨v, ⟨⟨e, he⟩, hbad⟩⟩ + cases he + exact ⟨e, by simpa [mismatchSet, minoritySet] using hbad⟩ + invFun e := + ⟨G.tail e.val, ⟨⟨e.val, rfl⟩, by + simpa [mismatchSet, minoritySet] using e.property⟩⟩ + left_inv := by + rintro ⟨v, ⟨⟨e, he⟩, hbad⟩⟩ + cases he + rfl + right_inv := by intro e; apply Subtype.ext; rfl + +omit [Fintype A] [DecidableEq E] in +theorem mismatch_card_eq_sum (G : ConstraintGraph V E A) (ell : E → A) + (rounded : V → A) : + (mismatchSet G ell rounded).card = + ∑ v, (minoritySet (fun e : Cloud G v => ell e.val) (rounded v)).card := by + have h := Fintype.card_congr (mismatchFiberEquiv G ell rounded) + simpa only [Fintype.card_sigma, Fintype.card_coe] using h.symm + +def disagreementFiberEquiv (G : ConstraintGraph V E A) + (H : ∀ v, PortGraph (Cloud G v) D) (ell : E → A) : + (Σ v, ↥(disagreementSet (fun e : Cloud G v => ell e.val) + (fun ed => ((H v).rot ed).1))) ≃ ↥(innerDisagreementSet G H ell) where + toFun := by + rintro ⟨v, ⟨⟨⟨e, he⟩, d⟩, hbad⟩⟩ + cases he + refine ⟨(e, d), ?_⟩ + simpa [disagreementSet, innerDisagreementSet, innerRotation, + cloudIndexEquiv, cloudRotation] using hbad + invFun := by + rintro ⟨⟨e, d⟩, hbad⟩ + refine ⟨G.tail e, ⟨(⟨e, rfl⟩, d), ?_⟩⟩ + simpa [disagreementSet, innerDisagreementSet, innerRotation, + cloudIndexEquiv, cloudRotation] using hbad + left_inv := by + rintro ⟨v, ⟨⟨⟨e, he⟩, d⟩, hbad⟩⟩ + cases he + rfl + right_inv := by intro ed; apply Subtype.ext; rfl + +omit [Fintype A] [DecidableEq E] in +theorem disagreement_card_eq_sum (G : ConstraintGraph V E A) + (H : ∀ v, PortGraph (Cloud G v) D) (ell : E → A) : + (innerDisagreementSet G H ell).card = + ∑ v, (disagreementSet (fun e : Cloud G v => ell e.val) + (fun ed => ((H v).rot ed).1)).card := by + have h := Fintype.card_congr (disagreementFiberEquiv G H ell) + simpa only [Fintype.card_sigma, Fintype.card_coe] using h.symm + +theorem rounded_mismatch_expansion [Nonempty A] + (G : ConstraintGraph V E A) (H : ∀ v, PortGraph (Cloud G v) D) + (ell : E → A) (h : ℚ) + (expansion : ∀ v (S : Finset (Cloud G v)), + S.card ≤ Fintype.card (Cloud G v) / 2 → + h * (S.card : ℚ) ≤ ((directedCut (fun ed => ((H v).rot ed).1) S).card : ℚ)) : + h * ((mismatchSet G ell (roundLabels G ell)).card : ℚ) ≤ + ((innerDisagreementSet G H ell).card : ℚ) := by + rw [mismatch_card_eq_sum, disagreement_card_eq_sum, Nat.cast_sum, Nat.cast_sum, + Finset.mul_sum] + apply Finset.sum_le_sum + intro v _ + exact minority_expansion_bound (fun e : Cloud G v => ell e.val) + (fun ed => ((H v).rot ed).1) (roundLabels G ell v) h + (majority_maximal (fun e : Cloud G v => ell e.val)) (expansion v) + +omit [Fintype V] [Fintype A] [DecidableEq V] [DecidableEq E] in +theorem rounded_endpoint_bound (G : ConstraintGraph V E A) + (ell : E → A) (rounded : V → A) : + G.rejectionCount rounded ≤ copiedRejectionCount G ell + + 2 * (mismatchSet G ell rounded).card := + dart_rejection_count_le G.tail G.reverse G.accepts ell rounded + +omit [Fintype V] [Fintype E] [Fintype A] [Fintype D] [DecidableEq V] [DecidableEq E] in +@[simp] theorem copied_satisfied_inl (G : ConstraintGraph V E A) + (H : ∀ v, PortGraph (Cloud G v) D) (ell : E → A) (e : E) (d : D) : + (replacementGraph G H).edgeSatisfied ell (e, Sum.inl d) = + decide (ell e = ell (innerRotation G H (e, d)).1) := rfl + +omit [Fintype V] [Fintype E] [Fintype A] [Fintype D] [DecidableEq V] [DecidableEq E] in +@[simp] theorem copied_satisfied_inr (G : ConstraintGraph V E A) + (H : ∀ v, PortGraph (Cloud G v) D) (ell : E → A) (e : E) (u : Unit) : + (replacementGraph G H).edgeSatisfied ell (e, Sum.inr u) = + G.accepts e (ell e) (ell (G.reverse e)) := rfl + +omit [Fintype V] [Fintype A] [DecidableEq V] [DecidableEq E] in +theorem replacement_rejection_split (G : ConstraintGraph V E A) + (H : ∀ v, PortGraph (Cloud G v) D) (ell : E → A) : + (replacementGraph G H).rejectionCount ell = + copiedRejectionCount G ell + (innerDisagreementSet G H ell).card := by + classical + simp only [rejectionCount_eq_sum, Fintype.sum_prod_type, Fintype.sum_sum_type, + copied_satisfied_inl, copied_satisfied_inr, decide_eq_false_iff_not, + Fintype.sum_unique, Finset.sum_add_distrib] + simp only [copiedRejectionCount, innerDisagreementSet, Finset.card_eq_sum_ones, + Finset.sum_filter, Fintype.sum_prod_type] + exact Nat.add_comm _ _ + +theorem replacement_soundness [Nonempty A] + (G : ConstraintGraph V E A) (H : ∀ v, PortGraph (Cloud G v) D) + (expansion : ∀ v (S : Finset (Cloud G v)), + S.card ≤ Fintype.card (Cloud G v) / 2 → + 2 * S.card ≤ (directedCut (fun ed => ((H v).rot ed).1) S).card) + (ell : E → A) : + G.rejectionCount (roundLabels G ell) ≤ (replacementGraph G H).rejectionCount ell := by + have hc := rounded_mismatch_expansion G H ell 2 (by + intro v S hS + exact_mod_cast expansion v S hS) + have hcNat : 2 * (mismatchSet G ell (roundLabels G ell)).card ≤ + (innerDisagreementSet G H ell).card := by exact_mod_cast hc + rw [replacement_rejection_split] + exact (rounded_endpoint_bound G ell (roundLabels G ell)).trans + (Nat.add_le_add_left hcNat _) + +theorem padded_replacement_soundness [Nonempty A] + (G : ConstraintGraph V E A) (dummy : V → Type*) [∀ v, Fintype (dummy v)] + [∀ v, DecidableEq (dummy v)] + (H : ∀ v, PortGraph (Cloud (paddedGraph G dummy) v) D) + (expansion : ∀ v (S : Finset (Cloud (paddedGraph G dummy) v)), + S.card ≤ Fintype.card (Cloud (paddedGraph G dummy) v) / 2 → + 2 * S.card ≤ (directedCut (fun ed => ((H v).rot ed).1) S).card) + (ell : PaddedDart G dummy → A) : + G.rejectionCount (roundLabels (paddedGraph G dummy) ell) ≤ + (paddedReplacementGraph G dummy H).rejectionCount ell := by + simpa only [paddedReplacementGraph, padded_rejectionCount] using + replacement_soundness (paddedGraph G dummy) H expansion ell + +end GraphRounding + +theorem combine_counts (R b M c : Nat) (h : ℚ) (hh : 0 < h) + (endpoint : R ≤ b + 2 * M) (cloud : h * (M : ℚ) ≤ (c : ℚ)) : + (R : ℚ) ≤ max 1 (2 / h) * ((b : ℚ) + (c : ℚ)) := by + let K : ℚ := max 1 (2 / h) + have hK : 1 ≤ K := le_max_left _ _ + have hK0 : 0 ≤ K := le_trans zero_le_one hK + have hcoef : 2 ≤ K * h := (div_le_iff₀ hh).mp (le_max_right _ _) + have hm : (2 : ℚ) * M ≤ K * c := by + calc + (2 : ℚ) * M ≤ (K * h) * M := + mul_le_mul_of_nonneg_right hcoef (Nat.cast_nonneg M) + _ = K * (h * M) := mul_assoc _ _ _ + _ ≤ K * c := mul_le_mul_of_nonneg_left cloud hK0 + have hb : (b : ℚ) ≤ K * b := by + simpa only [one_mul] using mul_le_mul_of_nonneg_right hK (Nat.cast_nonneg b) + have hr : (R : ℚ) ≤ (b : ℚ) + 2 * (M : ℚ) := by exact_mod_cast endpoint + exact hr.trans ((add_le_add hb hm).trans_eq (mul_add K (b : ℚ) (c : ℚ)).symm) + +end MinUncutGames.Foundations.PCP.CloudRounding + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/GraphTableComplexity.lean b/lean/OAI/Computability/MinUncut/PCP/GraphTableComplexity.lean new file mode 100644 index 0000000000000000000000000000000000000000..c1df5cc38c0aa4664cdfb58a5c286356c8004396 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/GraphTableComplexity.lean @@ -0,0 +1,672 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.RawInitialTables + +namespace OAI + +section +namespace MinUncutGames.Foundations.PCP.GraphTableComplexity + +open MinUncutGames.Foundations.Complexity +open Polynomial + +noncomputable def encodingPolynomial (q : Nat) : Polynomial Nat := + X ^ 2 + C (2 * (q * q) + 1) * X + C 2 + +theorem encodingPolynomial_eval (q n : Nat) : + (encodingPolynomial q).eval n = n ^ 2 + (2 * (q * q) + 1) * n + 2 := by + simp [encodingPolynomial] + +theorem encodingPolynomial_mono (q : Nat) {n m : Nat} (hnm : n ≤ m) : + (encodingPolynomial q).eval n ≤ (encodingPolynomial q).eval m := by + rw [encodingPolynomial_eval, encodingPolynomial_eval] + exact Nat.add_le_add_right + (Nat.add_le_add (Nat.pow_le_pow_left hnm 2) (Nat.mul_le_mul_left _ hnm)) 2 + +theorem rowBound_le_polynomial (q vertices darts : Nat) : + vertices + darts + 2 + darts * (vertices + darts + 2 * (q * q)) ≤ + (encodingPolynomial q).eval (vertices + darts) := by + have hd : darts ≤ vertices + darts := Nat.le_add_left darts vertices + calc + _ ≤ vertices + darts + 2 + + (vertices + darts) * (vertices + darts + 2 * (q * q)) := + Nat.add_le_add_left (Nat.mul_le_mul_right _ hd) _ + _ = _ := by rw [encodingPolynomial_eval]; ring + +theorem generic_size_add_two_le_bits {q : Nat} (table : GenericGraphTables.Table q) : + table.vertices + table.darts + 2 ≤ (GenericGraphTables.tableBits table).length := by + simp only [GenericGraphTables.tableBits, GenericGraphTables.tableWords, + encodeWords_append, List.length_append, encodeWords, encodeWord_length, List.length_nil] + omega + +theorem generic_bits_le_polynomial {q : Nat} (table : GenericGraphTables.Table q) : + (GenericGraphTables.tableBits table).length ≤ + (encodingPolynomial q).eval (table.vertices + table.darts) := + (GenericGraphTables.tableBits_length_le table).trans + (rowBound_le_polynomial q table.vertices table.darts) + +theorem generic_bits_le_of_size_le {q N : Nat} (table : GenericGraphTables.Table q) + (hsize : table.vertices + table.darts ≤ N) : + (GenericGraphTables.tableBits table).length ≤ (encodingPolynomial q).eval N := + (generic_bits_le_polynomial table).trans (encodingPolynomial_mono q hsize) + +theorem size_add_two_le_bits (table : GraphTables.Table) : + table.vertices + table.darts + 2 ≤ (GraphTables.tableBits table).length := by + simp only [GraphTables.tableBits, GraphTables.tableWords, + encodeWords_append, List.length_append, encodeWords, encodeWord_length, List.length_nil] + omega + +theorem bits_le_polynomial (table : GraphTables.Table) : + (GraphTables.tableBits table).length ≤ + (encodingPolynomial 64).eval (table.vertices + table.darts) := + (GraphTables.tableBits_length_le table).trans + (rowBound_le_polynomial 64 table.vertices table.darts) + +theorem bits_le_of_size_le {N : Nat} (table : GraphTables.Table) + (hsize : table.vertices + table.darts ≤ N) : + (GraphTables.tableBits table).length ≤ (encodingPolynomial 64).eval N := + (bits_le_polynomial table).trans (encodingPolynomial_mono 64 hsize) + +end MinUncutGames.Foundations.PCP.GraphTableComplexity + +end +section +noncomputable section + +namespace MinUncutGames.Foundations.PCP.AmplificationRound + +abbrev Label := QueryIncidence.Label 6 +abbrev Addresses := PoweringLabels.PortWords Preprocessing.Port FinalConstants.walkLength +abbrev PoweredAlphabet := + PoweringLabels.PaddedLabel Preprocessing.Port FinalConstants.walkLength Label + +instance : Fintype PoweredAlphabet := Fintype.ofFinite _ +instance : DecidableEq PoweredAlphabet := Classical.decEq _ + +variable {V E : Type*} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + [Nonempty E] + +abbrev PoweredDart (G : ConstraintGraph V E Label) := + PoweringTest.Dart (Preprocessing.Vertex G) Preprocessing.Port + (2 * FinalConstants.endpointLength) + +instance (G : ConstraintGraph V E Label) : DecidableEq (PoweredDart G) := Classical.decEq _ + +def selectors (addresses : List Addresses) (complete : ∀ w, w ∈ addresses) + (G : ConstraintGraph V E Label) (v : Preprocessing.Vertex G) : + PoweringLabels.AddressSelector (Preprocessing.portGraph G) + FinalConstants.walkLength v := + PoweringLabels.listSelector (Preprocessing.portGraph G) FinalConstants.walkLength + v addresses complete + +def powered (addresses : List Addresses) (complete : ∀ w, w ∈ addresses) + (G : ConstraintGraph V E Label) : + ConstraintGraph (Preprocessing.Vertex G) (PoweredDart G) PoweredAlphabet := + PoweringTest.poweredGraph (Preprocessing.portGraph G) (Preprocessing.graph G).accepts + (2 * FinalConstants.endpointLength) (selectors addresses complete G) + +abbrev Vertex (G : ConstraintGraph V E Label) := + QueryIncidence.Vertex + (AlphabetGraph.Event (PoweredDart G) PoweredAlphabet) + (AlphabetGraph.Address (Preprocessing.Vertex G) (PoweredDart G) PoweredAlphabet) + +abbrev Dart (G : ConstraintGraph V E Label) := + QueryIncidence.Dart (AlphabetGraph.Event (PoweredDart G) PoweredAlphabet) 6 + +instance (G : ConstraintGraph V E Label) : Fintype (Vertex G) := by + letI : Fintype (AlphabetGraph.Event (PoweredDart G) PoweredAlphabet) := inferInstance + letI : Fintype + (AlphabetGraph.Address (Preprocessing.Vertex G) (PoweredDart G) PoweredAlphabet) := + inferInstance + change Fintype + (AlphabetGraph.Event (PoweredDart G) PoweredAlphabet ⊕ + AlphabetGraph.Address (Preprocessing.Vertex G) (PoweredDart G) PoweredAlphabet) + infer_instance +instance (G : ConstraintGraph V E Label) : Fintype (Dart G) := by + change Fintype ((AlphabetGraph.Event (PoweredDart G) PoweredAlphabet × Fin 6) × Bool) + infer_instance +instance (G : ConstraintGraph V E Label) : DecidableEq (Vertex G) := Classical.decEq _ + +def graph (addresses : List Addresses) (complete : ∀ w, w ∈ addresses) + (G : ConstraintGraph V E Label) : ConstraintGraph (Vertex G) (Dart G) Label := + AlphabetGraph.graph (powered addresses complete G) + +omit [Nonempty E] in +theorem powered_completeness (addresses : List Addresses) + (complete : ∀ w, w ∈ addresses) (G : ConstraintGraph V E Label) + (satisfied : G.Satisfiable) : (powered addresses complete G).Satisfiable := by + obtain ⟨assignment, hassignment⟩ := Preprocessing.completeness G satisfied + refine ⟨PoweringOpinions.honestLabels (Preprocessing.portGraph G) + FinalConstants.walkLength assignment, ?_⟩ + apply PoweringTest.perfect_completeness (Preprocessing.portGraph G) + (Preprocessing.graph G).accepts (2 * FinalConstants.endpointLength) + (selectors addresses complete G) assignment + intro e + exact hassignment e + +omit [Nonempty E] in +theorem completeness (addresses : List Addresses) + (complete : ∀ w, w ∈ addresses) (G : ConstraintGraph V E Label) + (satisfied : G.Satisfiable) : (graph addresses complete G).Satisfiable := + AlphabetGraph.perfect_completeness _ + (powered_completeness addresses complete G satisfied) + +end MinUncutGames.Foundations.PCP.AmplificationRound + +end +end +section +namespace MinUncutGames.Foundations.PCP.PoweringWitness + +open PoweringWalks SpectralReturn PoweringReturn PoweringLazy +open PoweringMoment (bit) + +variable {V D : Type*} + +theorem iterate_mul_const [Fintype D] (G : PortGraph V D) + (n : Nat) (c : ℝ) (h : V → ℝ) : + iterateOperator G n (fun x => c * h x) = + fun x => c * iterateOperator G n h x := by + induction n with + | zero => rfl + | succ n ih => + change averagingOperator G (iterateOperator G n (fun x => c * h x)) = + fun x => c * averagingOperator G (iterateOperator G n h) x + rw [ih] + funext v + exact mean_mul_left c (fun d => iterateOperator G n h (G.rot (v, d)).1) + +noncomputable def endpointWitness (G : PortGraph V D) (bad : Edge V D → Bool) + (φ ψ : Edge V D → V → ℝ) (n : Nat) (k : Fin (n + 1)) + (w : Walk V D (n + 1)) : ℝ := + bit (bad (edgeAt G n w k) = true) * + φ (edgeAt G n w k) w.1 * ψ (edgeAt G n w k) (endpoint G w) + +noncomputable def vertexWitness (G : PortGraph V D) (bad : Edge V D → Bool) + (f : V → V → ℝ) (n : Nat) (k : Fin (n + 1)) : + Walk V D (n + 1) → ℝ := + endpointWitness G bad (fun e => f e.1) (fun e => f (next G e.1 e.2)) n k + +theorem endpoint_lower_bound [Fintype V] [Fintype D] [Nonempty D] + (G : PortGraph V D) (n : Nat) (k : Fin (n + 1)) (bad : Edge V D → Bool) + (φ ψ : Edge V D → V → ℝ) (a : ℝ) (ha : 0 ≤ a) + (hL : ∀ e, bad e = true → a ≤ iterateOperator G k.val (φ e) e.1) + (hR : ∀ e, bad e = true → + a ≤ iterateOperator G (n - k.val) (ψ e) (next G e.1 e.2)) : + edgeDensity bad * a ^ 2 ≤ mean (endpointWitness G bad φ ψ n k) := by + have hfactor : mean (endpointWitness G bad φ ψ n k) = + mean (fun e : Edge V D => + (bit (bad e = true) * iterateOperator G k.val (φ e) e.1) * + iterateOperator G (n - k.val) (ψ e) (next G e.1 e.2)) := by + unfold endpointWitness + rw [mean_edge_endpoints G n k (fun e x => bit (bad e = true) * φ e x) ψ] + simp_rw [iterate_mul_const] + have hbitMean : mean (fun e : Edge V D => bit (bad e = true)) = edgeDensity bad := by + calc + _ = mean (fun v : V => mean (fun d : D => bit (bad (v, d) = true))) := + mean_prod (A := V) (B := D) (fun e => bit (bad e = true)) + _ = edgeDensity bad := by simp only [mean_edge_bit, edgeDensity] + calc + edgeDensity bad * a ^ 2 = + mean (fun e : Edge V D => bit (bad e = true) * a ^ 2) := by + rw [mean_mul_right, hbitMean] + _ ≤ mean (fun e : Edge V D => + (bit (bad e = true) * iterateOperator G k.val (φ e) e.1) * + iterateOperator G (n - k.val) (ψ e) (next G e.1 e.2)) := by + apply mean_mono + intro e + cases hb : bad e with + | false => simp [bit] + | true => + have hprod := mul_le_mul (hL e hb) (hR e hb) ha (ha.trans (hL e hb)) + simpa [bit, hb, pow_two] using hprod + _ = mean (endpointWitness G bad φ ψ n k) := hfactor.symm + +theorem lazy_middle_witness_mean [Fintype V] [Fintype D] [Nonempty D] + (G : PortGraph V D) (q M : Nat) (hq : 1 ≤ q) (hM : 1 ≤ M) + (k : Fin (2 * (4 * q * M) ^ 2 + 1)) + (hlo : (4 * q * M) ^ 2 - M ≤ k.val) + (hhi : k.val ≤ (4 * q * M) ^ 2 + M) + (bad : Edge V (Bool × D) → Bool) (f : V → V → ℝ) + (hf : ∀ u w, f u w ∈ Set.Icc (0 : ℝ) 1) + (hmodal : ∀ u, 1 / (q : ℝ) ≤ + iterateOperator (lazyGraph G) ((4 * q * M) ^ 2) (f u) u) : + edgeDensity bad / (4 * (q : ℝ) ^ 2) ≤ + mean (vertexWitness (lazyGraph G) bad f (2 * (4 * q * M) ^ 2) k) := by + have hk : k.val ≤ 2 * (4 * q * M) ^ 2 := Nat.le_of_lt_succ k.isLt + have hslo : (4 * q * M) ^ 2 - M ≤ 2 * (4 * q * M) ^ 2 - k.val := by omega + have hshi : 2 * (4 * q * M) ^ 2 - k.val ≤ (4 * q * M) ^ 2 + M := by omega + have ha : (0 : ℝ) ≤ 1 / (2 * (q : ℝ)) := by positivity + have hbound := endpoint_lower_bound (lazyGraph G) (2 * (4 * q * M) ^ 2) k bad + (fun e => f e.1) (fun e => f (next (lazyGraph G) e.1 e.2)) + (1 / (2 * (q : ℝ))) ha + (by + intro e _ + exact lazy_endpoint_modal_transfer G q M k.val hq hM hlo hhi + (f e.1) (hf e.1) e.1 (hmodal e.1)) + (by + intro e _ + exact lazy_endpoint_modal_transfer G q M (2 * (4 * q * M) ^ 2 - k.val) + hq hM hslo hshi (f (next (lazyGraph G) e.1 e.2)) + (hf (next (lazyGraph G) e.1 e.2)) (next (lazyGraph G) e.1 e.2) + (hmodal (next (lazyGraph G) e.1 e.2))) + have hscale : edgeDensity bad * (1 / (2 * (q : ℝ))) ^ 2 = + edgeDensity bad / (4 * (q : ℝ) ^ 2) := by ring + simpa only [vertexWitness, hscale] using hbound + +end MinUncutGames.Foundations.PCP.PoweringWitness + +end +section +namespace MinUncutGames.Foundations.PCP.PoweringMomentBound + +open scoped BigOperators +open PoweringWalks SpectralReturn PoweringReturn +open PoweringMoment (bit hits) + +theorem symmetric_gap_matrix_sum (ε : ℝ) (r : Nat → ℝ) : + ∀ (m : Nat) (f : Fin m → Fin m → ℝ), + (∀ i j, f i j = f j i) → (∀ i, f i i = ε) → + (∀ i j, i.val < j.val → f i j = r (j.val - i.val - 1)) → + (∑ i, ∑ j, f i j) = (m : ℝ) * ε + + 2 * ∑ j ∈ Finset.range m, ∑ gap ∈ Finset.range j, r gap := by + intro m + induction m with + | zero => intro f _hSym _hDiag _hUpper; simp + | succ m ih => + intro f hSym hDiag hUpper + have hOld : (∑ i : Fin m, ∑ j : Fin m, f i.castSucc j.castSucc) = + (m : ℝ) * ε + 2 * ∑ j ∈ Finset.range m, ∑ gap ∈ Finset.range j, r gap := by + apply ih (fun i j => f i.castSucc j.castSucc) + · intro i j; exact hSym i.castSucc j.castSucc + · intro i; exact hDiag i.castSucc + · intro i j hij; exact hUpper i.castSucc j.castSucc hij + have hLast : (∑ i : Fin m, f i.castSucc (Fin.last m)) = + ∑ gap ∈ Finset.range m, r gap := by + calc + _ = ∑ i : Fin m, r (m - 1 - i.val) := by + apply Finset.sum_congr rfl + intro i _ + rw [hUpper i.castSucc (Fin.last m) i.isLt] + simp only [Fin.val_last, Fin.val_castSucc] + congr 1 + omega + _ = ∑ i ∈ Finset.range m, r (m - 1 - i) := + Fin.sum_univ_eq_sum_range (fun i => r (m - 1 - i)) m + _ = _ := Finset.sum_range_reflect r m + have hLastRow : (∑ j : Fin m, f (Fin.last m) j.castSucc) = + ∑ gap ∈ Finset.range m, r gap := by + calc + _ = ∑ j : Fin m, f j.castSucc (Fin.last m) := by + apply Finset.sum_congr rfl + intro j _ + exact hSym (Fin.last m) j.castSucc + _ = _ := hLast + calc + (∑ i, ∑ j, f i j) = + (∑ i : Fin m, ∑ j : Fin m, f i.castSucc j.castSucc) + + (∑ i : Fin m, f i.castSucc (Fin.last m)) + + (∑ j : Fin m, f (Fin.last m) j.castSucc) + f (Fin.last m) (Fin.last m) := by + simp only [Fin.sum_univ_castSucc, Finset.sum_add_distrib] + ring + _ = (m : ℝ) * ε + + 2 * (∑ j ∈ Finset.range m, ∑ gap ∈ Finset.range j, r gap) + + (∑ gap ∈ Finset.range m, r gap) + (∑ gap ∈ Finset.range m, r gap) + ε := by + rw [hOld, hLast, hLastRow, hDiag] + _ = ((m + 1 : Nat) : ℝ) * ε + + 2 * ∑ j ∈ Finset.range (m + 1), ∑ gap ∈ Finset.range j, r gap := by + rw [Finset.sum_range_succ] + simp only [Nat.cast_add, Nat.cast_one] + ring + +def windowIndex (n start m : Nat) (h : start + m ≤ n + 1) (i : Fin m) : Fin (n + 1) := + ⟨start + i.val, (Nat.add_lt_add_left i.isLt start).trans_le h⟩ + +variable {V D : Type*} [Fintype V] [Fintype D] [Nonempty V] [Nonempty D] + +def windowEvent (G : PortGraph V D) (bad : V × D → Bool) + (n start m : Nat) (h : start + m ≤ n + 1) (i : Fin m) (w : Walk V D (n + 1)) : Prop := + bad (edgeAt G n w (windowIndex n start m h i)) = true + +theorem window_second_moment_eq (G : PortGraph V D) (bad : V × D → Bool) + (n start m : Nat) (h : start + m ≤ n + 1) : + mean (fun w => hits (windowEvent G bad n start m h) w ^ 2) = + (m : ℝ) * edgeDensity bad + + 2 * ∑ j ∈ Finset.range m, ∑ gap ∈ Finset.range j, returnMass G bad gap := by + rw [show mean (fun w => hits (windowEvent G bad n start m h) w ^ 2) = + ∑ i, ∑ j, mean (fun w => bit (windowEvent G bad n start m h i w ∧ + windowEvent G bad n start m h j w)) from + PoweringMoment.second_moment_eq (windowEvent G bad n start m h)] + apply symmetric_gap_matrix_sum + · intro i j + congr 1 + funext w + simp only [and_comm] + · intro i + simp only [and_self] + exact hit_mean G bad n (windowIndex n start m h i) + · intro i j hij + have hwin : windowIndex n start m h i < windowIndex n start m h j := + Nat.add_lt_add_left hij start + have hp := pair_event_mean G bad n (windowIndex n start m h i) + (windowIndex n start m h j) hwin + simpa only [windowEvent, windowIndex, Nat.add_sub_add_left] using hp + +theorem window_second_moment_le (G : PortGraph V D) (lambda : ℝ) + (certificate : SpectralCertificate G lambda) (bad : V × D → Bool) + (reversal : ∀ e, bad (G.rot e) = bad e) + (n start m : Nat) (h : start + m ≤ n + 1) : + mean (fun w => hits (windowEvent G bad n start m h) w ^ 2) ≤ + (m : ℝ) * edgeDensity bad * + (1 + 2 / (1 - lambda) + ((m : ℝ) - 1) * edgeDensity bad) := by + rw [window_second_moment_eq] + exact secondMoment_return_envelope G lambda certificate bad reversal m + +end MinUncutGames.Foundations.PCP.PoweringMomentBound + +end +section +namespace MinUncutGames.Foundations.PCP.PoweringNumeric + +theorem min_density_ratio (ε C k t : ℝ) + (hε : 0 < ε) (hC : 0 < C) (hk : 0 ≤ k) + (ht : 0 < t) (hkt : k ≤ t) : + min ε (1 / t) / (C + 1) ≤ ε / (C + k * ε) := by + have hx : 0 ≤ min ε (1 / t) := + le_min hε.le (one_div_nonneg.mpr ht.le) + have hxt : min ε (1 / t) * t ≤ 1 := + (le_div_iff₀ ht).mp (min_le_right ε (1 / t)) + have hkx : k * min ε (1 / t) ≤ 1 := by + calc + k * min ε (1 / t) ≤ t * min ε (1 / t) := + mul_le_mul_of_nonneg_right hkt hx + _ ≤ 1 := by simpa only [mul_comm] using hxt + have hC1 : 0 < C + 1 := by positivity + have hden : 0 < C + k * ε := + add_pos_of_pos_of_nonneg hC (mul_nonneg hk hε.le) + apply (div_le_div_iff₀ hC1 hden).2 + calc + min ε (1 / t) * (C + k * ε) = + C * min ε (1 / t) + ε * (k * min ε (1 / t)) := by ring + _ ≤ C * ε + ε * 1 := + add_le_add + (mul_le_mul_of_nonneg_left (min_le_left ε (1 / t)) hC.le) + (mul_le_mul_of_nonneg_left hkx hε.le) + _ = ε * (C + 1) := by ring + +theorem count_moment_ratio_lower (α ε C t : ℝ) (m : ℕ) + (hm : 0 < m) (hε : 0 < ε) (hC : 0 < C) (ht : 0 < t) + (hmt : (m : ℝ) - 1 ≤ t) : + (α ^ 4 * (m : ℝ) / (C + 1)) * min ε (1 / t) ≤ + (α ^ 2 * (m : ℝ) * ε) ^ 2 / + ((m : ℝ) * ε * (C + ((m : ℝ) - 1) * ε)) := by + have hm0 : (0 : ℝ) < (m : ℝ) := Nat.cast_pos.mpr hm + have hm1 : (1 : ℝ) ≤ (m : ℝ) := by + exact_mod_cast (Nat.succ_le_iff.mpr hm) + have hk : 0 ≤ (m : ℝ) - 1 := sub_nonneg.mpr hm1 + have hden : 0 < C + ((m : ℝ) - 1) * ε := + add_pos_of_pos_of_nonneg hC (mul_nonneg hk hε.le) + have hαm : 0 ≤ α ^ 4 * (m : ℝ) := by positivity + have hratio := min_density_ratio ε C ((m : ℝ) - 1) t hε hC hk ht hmt + calc + (α ^ 4 * (m : ℝ) / (C + 1)) * min ε (1 / t) = + (α ^ 4 * (m : ℝ)) * (min ε (1 / t) / (C + 1)) := by ring + _ ≤ (α ^ 4 * (m : ℝ)) * (ε / (C + ((m : ℝ) - 1) * ε)) := + mul_le_mul_of_nonneg_left hratio hαm + _ = (α ^ 2 * (m : ℝ) * ε) ^ 2 / + ((m : ℝ) * ε * (C + ((m : ℝ) - 1) * ε)) := by + field_simp [ne_of_gt hm0, ne_of_gt hε, ne_of_gt hden] + +end MinUncutGames.Foundations.PCP.PoweringNumeric + +end +section +noncomputable section + +namespace MinUncutGames.Foundations.PCP.PoweringSoundness + +open scoped BigOperators +open PoweringWalks PoweringLabels PoweringOpinions PoweringTest +open SpectralReturn PoweringWitness PoweringMomentBound +open PoweringMoment (bit hits) + +variable {V D A : Type*} + +def center (q M : Nat) : Nat := (4 * q * M) ^ 2 + +theorem le_center (q M : Nat) (hq : 1 ≤ q) (hM : 1 ≤ M) : M ≤ center q M := by + have hfour : 1 ≤ 4 * q := by omega + have hx : M ≤ 4 * q * M := by simpa only [Nat.one_mul] using Nat.mul_le_mul_right M hfour + have hone : 1 ≤ 4 * q * M := hM.trans hx + have hsquare : 4 * q * M ≤ (4 * q * M) * (4 * q * M) := by + simpa only [Nat.mul_one] using Nat.mul_le_mul_left (4 * q * M) hone + exact hx.trans (by simpa only [center, pow_two] using hsquare) + +def gain (q M : Nat) (lambda : ℝ) : ℝ := + (1 / (2 * (q : ℝ))) ^ 4 * ((2 * M + 1 : Nat) : ℝ) / + ((1 + 2 / (1 - lambda)) + 1) + +variable [Fintype V] [Fintype D] [Nonempty V] [Nonempty D] + [Fintype A] [Nonempty A] + +def decodedError (G : PortGraph V D) (accepts : Edge V D → A → A → Bool) + (n N : Nat) (selectors : ∀ v, AddressSelector G (n + 1) v) + (labels : V → PaddedLabel D (n + 1) A) (fallback : A) : ℝ := + edgeDensity (decodedBad G accepts (decoded G (n + 1) N selectors labels fallback)) + +def poweredRejection (G : PortGraph V D) (accepts : Edge V D → A → A → Bool) + (n : Nat) (selectors : ∀ v, AddressSelector G (n + 1) v) + (labels : V → PaddedLabel D (n + 1) A) : ℝ := + mean (fun d : Dart V D n => bit ((poweredGraph G accepts n selectors).edgeSatisfied labels d = false)) + +omit [Fintype V] [Nonempty V] [Nonempty D] in +theorem witness_bit_eq (G : PortGraph V D) (accepts : Edge V D → A → A → Bool) + (n N : Nat) (selectors : ∀ v, AddressSelector G (n + 1) v) + (labels : V → PaddedLabel D (n + 1) A) (fallback : A) + (w : Walk V D (n + 1)) (k : Fin (n + 1)) : + bit (witness G accepts n selectors labels fallback + (decoded G (n + 1) N selectors labels fallback) w k) = + vertexWitness G + (decodedBad G accepts (decoded G (n + 1) N selectors labels fallback)) + (matchFn G (n + 1) N selectors labels fallback) n k w := by + simp only [witness, vertexWitness, endpointWitness, matchFn, + PoweringMoment.bit_mul, next, and_assoc] + +omit [Nonempty V] in +theorem modal_witness_mean (G : PortGraph V D) (M : Nat) (hM : 1 ≤ M) + (accepts : Edge V (Bool × D) → A → A → Bool) + (selectors : ∀ v, AddressSelector (lazyGraph G) (2 * center (Fintype.card A) M + 1) v) + (labels : V → PaddedLabel (Bool × D) (2 * center (Fintype.card A) M + 1) A) + (fallback : A) (k : Fin (2 * center (Fintype.card A) M + 1)) + (hlo : center (Fintype.card A) M - M ≤ k.val) + (hhi : k.val ≤ center (Fintype.card A) M + M) : + decodedError (lazyGraph G) accepts (2 * center (Fintype.card A) M) + (center (Fintype.card A) M) selectors labels fallback / (4 * (Fintype.card A : ℝ) ^ 2) ≤ + mean (fun w => bit (witness (lazyGraph G) accepts (2 * center (Fintype.card A) M) + selectors labels fallback (decoded (lazyGraph G) (2 * center (Fintype.card A) M + 1) + (center (Fintype.card A) M) selectors labels fallback) w k)) := by + have h := lazy_middle_witness_mean G (Fintype.card A) M Fintype.card_pos hM k hlo hhi + (decodedBad (lazyGraph G) accepts + (decoded (lazyGraph G) (2 * center (Fintype.card A) M + 1) + (center (Fintype.card A) M) selectors labels fallback)) + (matchFn (lazyGraph G) (2 * center (Fintype.card A) M + 1) + (center (Fintype.card A) M) selectors labels fallback) + (matchFn_mem_Icc (lazyGraph G) (2 * center (Fintype.card A) M + 1) + (center (Fintype.card A) M) selectors labels fallback) + (decoded_modal_baseline (lazyGraph G) (2 * center (Fintype.card A) M + 1) + (center (Fintype.card A) M) selectors labels fallback) + simp_rw [witness_bit_eq] + convert h using 1 <;> rfl + +theorem rejection_lower_bound (G : PortGraph V D) (lambda : ℝ) + (certificate : SpectralCertificate (lazyGraph G) lambda) + (accepts : Edge V (Bool × D) → A → A → Bool) + (reverse_accepts : ∀ e a b, accepts ((lazyGraph G).rot e) b a = accepts e a b) + (M : Nat) (hM : 1 ≤ M) + (selectors : ∀ v, AddressSelector (lazyGraph G) (2 * center (Fintype.card A) M + 1) v) + (labels : V → PaddedLabel (Bool × D) (2 * center (Fintype.card A) M + 1) A) + (fallback : A) + (hε : 0 < decodedError (lazyGraph G) accepts (2 * center (Fintype.card A) M) + (center (Fintype.card A) M) selectors labels fallback) : + gain (Fintype.card A) M lambda * + min (decodedError (lazyGraph G) accepts (2 * center (Fintype.card A) M) + (center (Fintype.card A) M) selectors labels fallback) + (1 / ((2 * center (Fintype.card A) M + 1 : Nat) : ℝ)) ≤ + poweredRejection (lazyGraph G) accepts (2 * center (Fintype.card A) M) selectors labels := by + let q := Fintype.card A + let N := center q M + let n := 2 * N + let m := 2 * M + 1 + let start := N - M + let L := lazyGraph G + let assignment := decoded L (n + 1) N selectors labels fallback + let bad := decodedBad L accepts assignment + let ε := edgeDensity bad + let α : ℝ := 1 / (2 * (q : ℝ)) + let C : ℝ := 1 + 2 / (1 - lambda) + have hNM : M ≤ N := le_center q M Fintype.card_pos hM + have hw : start + m ≤ n + 1 := by dsimp [start, m, n]; omega + let E := windowEvent L bad n start m hw + let W : Fin m → Walk V (Bool × D) (n + 1) → Prop := fun i w => + witness L accepts n selectors labels fallback assignment w (windowIndex n start m hw i) + let R : Walk V (Bool × D) (n + 1) → Prop := fun w => + pathAccepts L accepts n selectors w (labels w.1) (labels (endpoint L w)) = false + have hWE : ∀ i w, W i w → E i w := by + intro i w h + exact h.1 + have hWR : ∀ i w, W i w → R w := by + intro i w h + exact witness_implies_path_rejection L accepts n selectors labels fallback assignment w + (windowIndex n start m hw i) h + have hpoint (i : Fin m) : ε / (4 * (q : ℝ) ^ 2) ≤ mean (fun w => bit (W i w)) := by + have hlo : N - M ≤ (windowIndex n start m hw i).val := by + dsimp [windowIndex, start] + omega + have hhi : (windowIndex n start m hw i).val ≤ N + M := by + have hi := i.isLt + dsimp [windowIndex, start] + dsimp [m] at hi + omega + exact modal_witness_mean G M hM accepts selectors labels fallback + (windowIndex n start m hw i) hlo hhi + have hfirst : α ^ 2 * (m : ℝ) * ε ≤ mean (hits W) := by + change α ^ 2 * (m : ℝ) * ε ≤ PoweringMoment.mean (hits W) + rw [PoweringMoment.mean_hits] + calc + _ = ∑ _i : Fin m, ε / (4 * (q : ℝ) ^ 2) := by + simp only [Finset.sum_const, Finset.card_univ, Fintype.card_fin, nsmul_eq_mul] + dsimp [α] + ring + _ ≤ _ := Finset.sum_le_sum (fun i _ => hpoint i) + have hsecond : mean (fun w => hits E w ^ 2) ≤ + (m : ℝ) * ε * (C + ((m : ℝ) - 1) * ε) := + window_second_moment_le L lambda certificate bad + (decodedBad_rot L accepts reverse_accepts assignment) n start m hw + have hε' : 0 < ε := hε + have hm : 0 < m := by dsimp [m]; omega + have hmReal : (0 : ℝ) < m := Nat.cast_pos.mpr hm + have hqReal : (0 : ℝ) < q := Nat.cast_pos.mpr Fintype.card_pos + have hden : 0 < 1 - lambda := sub_pos.mpr certificate.lt_one + have hC : 0 < C := by dsimp [C]; positivity + have hmOne : (1 : ℝ) ≤ m := by exact_mod_cast hm + have hα : 0 < α := by dsimp [α]; positivity + have ha : 0 < α ^ 2 * (m : ℝ) * ε := by positivity + have hb : 0 < (m : ℝ) * ε * (C + ((m : ℝ) - 1) * ε) := by + have hdiff : 0 ≤ (m : ℝ) - 1 := sub_nonneg.mpr hmOne + positivity + have hCS := PoweringMoment.rejection_lower_bound E W R hWE hWR + (α ^ 2 * (m : ℝ) * ε) ((m : ℝ) * ε * (C + ((m : ℝ) - 1) * ε)) + ha hb hfirst hsecond + have ht : (0 : ℝ) < ((n + 1 : Nat) : ℝ) := Nat.cast_pos.mpr (Nat.succ_pos n) + have hmn : m ≤ n + 1 := by dsimp [m, n]; omega + have hmt : (m : ℝ) - 1 ≤ ((n + 1 : Nat) : ℝ) := by + have hmnReal : (m : ℝ) ≤ ((n + 1 : Nat) : ℝ) := by exact_mod_cast hmn + linarith + have hratio := PoweringNumeric.count_moment_ratio_lower α ε C ((n + 1 : Nat) : ℝ) + m hm hε' hC ht hmt + change (α ^ 4 * (m : ℝ) / (C + 1)) * min ε (1 / ((n + 1 : Nat) : ℝ)) ≤ _ + change _ ≤ mean (fun d : Dart V (Bool × D) n => + bit ((poweredGraph L accepts n selectors).edgeSatisfied labels d = false)) + rw [rejection_mean_eq_path_mean] + exact hratio.trans hCS + +end MinUncutGames.Foundations.PCP.PoweringSoundness + +end +end +section +namespace MinUncutGames.Foundations.PCP.PoweringGap + +open PoweringWalks PoweringLabels PoweringOpinions PoweringTest +open SpectralReturn PoweringSoundness PoweringCounting + +variable {V D A : Type*} + +theorem gain_nonneg (q M : Nat) (lambda : ℝ) (hlambda : lambda < 1) : + 0 ≤ gain q M lambda := by + have hden : 0 < 1 - lambda := sub_pos.mpr hlambda + unfold gain + positivity + +variable [Fintype V] [Fintype D] [Nonempty V] [Nonempty D] + [Fintype A] [Nonempty A] + +theorem uniform_count_gap (G : PortGraph V D) (lambda : ℝ) + (certificate : SpectralCertificate (lazyGraph G) lambda) + (accepts : Edge V (Bool × D) → A → A → Bool) + (reverse_accepts : ∀ e a b, accepts ((lazyGraph G).rot e) b a = accepts e a b) + (M : Nat) (hM : 1 ≤ M) + (selectors : ∀ v, AddressSelector (lazyGraph G) + (2 * center (Fintype.card A) M + 1) v) + (epsilon : ℝ) (hepsilon : 0 ≤ epsilon) + (hgap : ∀ assignment : V → A, + epsilon * (Fintype.card (Edge V (Bool × D)) : ℝ) ≤ + ((baseGraph (lazyGraph G) accepts reverse_accepts).rejectionCount assignment : ℝ)) + (labels : V → PaddedLabel (Bool × D) (2 * center (Fintype.card A) M + 1) A) : + (gain (Fintype.card A) M lambda * + min epsilon (1 / ((2 * center (Fintype.card A) M + 1 : Nat) : ℝ))) * + (Fintype.card (Dart V (Bool × D) (2 * center (Fintype.card A) M)) : ℝ) ≤ + ((poweredGraph (lazyGraph G) accepts (2 * center (Fintype.card A) M) + selectors).rejectionCount labels : ℝ) := by + classical + let L := lazyGraph G + let N := center (Fintype.card A) M + let n := 2 * N + let H := poweredGraph L accepts n selectors + change (gain (Fintype.card A) M lambda * + min epsilon (1 / ((n + 1 : Nat) : ℝ))) * + (Fintype.card (Dart V (Bool × D) n) : ℝ) ≤ + (H.rejectionCount labels : ℝ) + rcases eq_or_lt_of_le hepsilon with hzero | hpositive + · rw [← hzero] + have hcap : (0 : ℝ) ≤ 1 / ((n + 1 : Nat) : ℝ) := by positivity + rw [min_eq_left hcap, mul_zero, zero_mul] + exact Nat.cast_nonneg _ + · let fallback : A := Classical.choice (inferInstance : Nonempty A) + let assignment := decoded L (n + 1) N selectors labels fallback + have hdecoded : epsilon ≤ decodedError L accepts n N selectors labels fallback := by + change epsilon ≤ edgeDensity (decodedBad L accepts assignment) + exact base_count_lower_to_density L accepts reverse_accepts assignment + Fintype.card_pos epsilon (hgap assignment) + have herror : 0 < decodedError L accepts n N selectors labels fallback := + hpositive.trans_le hdecoded + have hsound := PoweringSoundness.rejection_lower_bound G lambda certificate + accepts reverse_accepts M hM selectors labels fallback herror + have hgain : 0 ≤ gain (Fintype.card A) M lambda := + gain_nonneg (Fintype.card A) M lambda certificate.lt_one + have hmin : min epsilon (1 / ((n + 1 : Nat) : ℝ)) ≤ + min (decodedError L accepts n N selectors labels fallback) + (1 / ((n + 1 : Nat) : ℝ)) := + min_le_min hdecoded (le_refl _) + have hlower : gain (Fintype.card A) M lambda * + min epsilon (1 / ((n + 1 : Nat) : ℝ)) ≤ + poweredRejection L accepts n selectors labels := + (mul_le_mul_of_nonneg_left hmin hgain).trans hsound + exact (constraint_rejection_lower_iff H labels Fintype.card_pos + (gain (Fintype.card A) M lambda * + min epsilon (1 / ((n + 1 : Nat) : ℝ)))).mp hlower + +end MinUncutGames.Foundations.PCP.PoweringGap + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/GraphTables.lean b/lean/OAI/Computability/MinUncut/PCP/GraphTables.lean new file mode 100644 index 0000000000000000000000000000000000000000..3d7b5e47994433ab5505324a812aca3bcdc657a5 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/GraphTables.lean @@ -0,0 +1,784 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.Generator +import OAI.Computability.MinUncut.Encoding.GameEncoding + +namespace OAI + +section +namespace MinUncutGames.Foundations.PCP.GraphTables + +open MinUncutGames.Foundations.Complexity + +abbrev Label := Fin 64 +abbrev RelationTable := Vector Bool 4096 + +def relationIndex : Label × Label ≃ Fin 4096 := finProdFinEquiv + +theorem relationIndex_val (a b : Label) : + (relationIndex (a, b)).val = b.val + 64 * a.val := rfl + +def relationAt (table : RelationTable) (a b : Label) : Bool := + table[relationIndex (a, b)] + +def relationOf (predicate : Label → Label → Bool) : RelationTable := + Vector.ofFn (fun i => predicate (relationIndex.symm i).1 (relationIndex.symm i).2) + +@[simp] theorem relationAt_relationOf (predicate : Label → Label → Bool) (a b : Label) : + relationAt (relationOf predicate) a b = predicate a b := by + simp [relationAt, relationOf] + +structure DartRow (vertices darts : Nat) where + tail : Fin vertices + reverseIndex : Fin darts + relation : RelationTable + +abbrev Rows (vertices darts : Nat) := Vector (DartRow vertices darts) darts + +def reverseAt {n m : Nat} (rows : Rows n m) (e : Fin m) : Fin m := + rows[e].reverseIndex + +def acceptsAt {n m : Nat} (rows : Rows n m) (e : Fin m) (a b : Label) : Bool := + relationAt rows[e].relation a b + +def Valid {n m : Nat} (rows : Rows n m) : Prop := + (∀ e, reverseAt rows (reverseAt rows e) = e) ∧ + (∀ e a b, acceptsAt rows (reverseAt rows e) b a = acceptsAt rows e a b) + +instance {n m : Nat} (rows : Rows n m) : Decidable (Valid rows) := by + unfold Valid + infer_instance + +structure Table where + vertices : Nat + darts : Nat + rows : Rows vertices darts + valid : Valid rows + +def rowList (table : Table) : List (DartRow table.vertices table.darts) := table.rows.toList + +@[simp] theorem rowList_length (table : Table) : (rowList table).length = table.darts := by + simp [rowList] + +def semantics (table : Table) : ConstraintGraph (Fin table.vertices) (Fin table.darts) Label where + reverse := + { toFun := reverseAt table.rows + invFun := reverseAt table.rows + left_inv := table.valid.1 + right_inv := table.valid.1 } + reverse_involutive := table.valid.1 + tail e := table.rows[e].tail + accepts := acceptsAt table.rows + reverse_accepts := table.valid.2 + +@[simp] theorem semantics_reverse (table : Table) (e : Fin table.darts) : + (semantics table).reverse e = table.rows[e].reverseIndex := rfl + +@[simp] theorem semantics_tail (table : Table) (e : Fin table.darts) : + (semantics table).tail e = table.rows[e].tail := rfl + +@[simp] theorem semantics_accepts (table : Table) (e : Fin table.darts) (a b : Label) : + (semantics table).accepts e a b = relationAt table.rows[e].relation a b := rfl + +def graphRows {n m : Nat} (G : ConstraintGraph (Fin n) (Fin m) Label) : Rows n m := + Vector.ofFn (fun e => ⟨G.tail e, G.reverse e, relationOf (G.accepts e)⟩) + +@[simp] theorem reverseAt_graphRows {n m : Nat} + (G : ConstraintGraph (Fin n) (Fin m) Label) (e : Fin m) : + reverseAt (graphRows G) e = G.reverse e := by + simp [reverseAt, graphRows] + +@[simp] theorem acceptsAt_graphRows {n m : Nat} + (G : ConstraintGraph (Fin n) (Fin m) Label) (e : Fin m) (a b : Label) : + acceptsAt (graphRows G) e a b = G.accepts e a b := by + simp [acceptsAt, graphRows] + +theorem graphRows_valid {n m : Nat} (G : ConstraintGraph (Fin n) (Fin m) Label) : + Valid (graphRows G) := by + constructor + · intro e + simpa using G.reverse_involutive e + · intro e a b + simpa using G.reverse_accepts e a b + +def ofGraph {n m : Nat} (G : ConstraintGraph (Fin n) (Fin m) Label) : Table := + ⟨n, m, graphRows G, graphRows_valid G⟩ + +@[simp] theorem semantics_ofGraph_reverse {n m : Nat} + (G : ConstraintGraph (Fin n) (Fin m) Label) (e : Fin m) : + (semantics (ofGraph G)).reverse e = G.reverse e := by + exact reverseAt_graphRows G e + +@[simp] theorem semantics_ofGraph_tail {n m : Nat} + (G : ConstraintGraph (Fin n) (Fin m) Label) (e : Fin m) : + (semantics (ofGraph G)).tail e = G.tail e := by + change (graphRows G)[e.val].tail = G.tail e + simp only [graphRows, Vector.getElem_ofFn] + +@[simp] theorem semantics_ofGraph_accepts {n m : Nat} + (G : ConstraintGraph (Fin n) (Fin m) Label) (e : Fin m) (a b : Label) : + (semantics (ofGraph G)).accepts e a b = G.accepts e a b := by + exact acceptsAt_graphRows G e a b + +@[simp] theorem semantics_ofGraph_edgeSatisfied {n m : Nat} + (G : ConstraintGraph (Fin n) (Fin m) Label) (labeling : Fin n → Label) (e : Fin m) : + (semantics (ofGraph G)).edgeSatisfied labeling e = G.edgeSatisfied labeling e := by + simp [ConstraintGraph.edgeSatisfied, ConstraintGraph.head] + +theorem constraintGraph_ext {V E A : Type*} {G H : ConstraintGraph V E A} + (hr : ∀ e, G.reverse e = H.reverse e) (ht : G.tail = H.tail) + (hp : G.accepts = H.accepts) : G = H := by + cases G with + | mk reverse hinv tail accepts htranspose => + cases H with + | mk reverse' hinv' tail' accepts' htranspose' => + dsimp only at hr ht hp + have he : reverse = reverse' := Equiv.ext hr + cases he + cases ht + cases hp + rfl + +@[simp] theorem semantics_ofGraph {n m : Nat} + (G : ConstraintGraph (Fin n) (Fin m) Label) : semantics (ofGraph G) = G := by + apply constraintGraph_ext + · exact semantics_ofGraph_reverse G + · funext e + exact semantics_ofGraph_tail G e + · funext e a b + exact semantics_ofGraph_accepts G e a b + +@[simp] theorem semantics_ofGraph_rejectionCount {n m : Nat} + (G : ConstraintGraph (Fin n) (Fin m) Label) (labeling : Fin n → Label) : + (semantics (ofGraph G)).rejectionCount labeling = G.rejectionCount labeling := by + rw [semantics_ofGraph] + rfl + +def enumeratedGraph {V E A : Type*} {n m : Nat} (G : ConstraintGraph V E A) + (vertexOrder : V ≃ Fin n) (dartOrder : E ≃ Fin m) (labelOrder : A ≃ Label) : + ConstraintGraph (Fin n) (Fin m) Label where + reverse := (dartOrder.symm.trans G.reverse).trans dartOrder + reverse_involutive e := by + change dartOrder (G.reverse (dartOrder.symm + (dartOrder (G.reverse (dartOrder.symm e))))) = e + rw [dartOrder.symm_apply_apply, G.reverse_involutive, dartOrder.apply_symm_apply] + tail e := vertexOrder (G.tail (dartOrder.symm e)) + accepts e a b := G.accepts (dartOrder.symm e) (labelOrder.symm a) (labelOrder.symm b) + reverse_accepts e a b := by + change G.accepts (dartOrder.symm (dartOrder (G.reverse (dartOrder.symm e)))) + (labelOrder.symm b) (labelOrder.symm a) = _ + rw [dartOrder.symm_apply_apply] + exact G.reverse_accepts _ _ _ + +theorem enumeratedGraph_edgeSatisfied {V E A : Type*} {n m : Nat} + (G : ConstraintGraph V E A) (vertexOrder : V ≃ Fin n) (dartOrder : E ≃ Fin m) + (labelOrder : A ≃ Label) (labeling : V → A) (e : E) : + (enumeratedGraph G vertexOrder dartOrder labelOrder).edgeSatisfied + (fun v => labelOrder (labeling (vertexOrder.symm v))) (dartOrder e) = + G.edgeSatisfied labeling e := by + simp [ConstraintGraph.edgeSatisfied, ConstraintGraph.head, enumeratedGraph] + +theorem enumeratedGraph_rejectionCount {V E A : Type*} [Fintype E] {n m : Nat} + (G : ConstraintGraph V E A) (vertexOrder : V ≃ Fin n) (dartOrder : E ≃ Fin m) + (labelOrder : A ≃ Label) (labeling : V → A) : + (enumeratedGraph G vertexOrder dartOrder labelOrder).rejectionCount + (fun v => labelOrder (labeling (vertexOrder.symm v))) = G.rejectionCount labeling := by + classical + unfold ConstraintGraph.rejectionCount + symm + apply Finset.card_equiv dartOrder + intro e + simp only [ConstraintGraph.mem_rejectedDarts, enumeratedGraph_edgeSatisfied] + +def ofEnumeratedGraph {V E A : Type*} {n m : Nat} (G : ConstraintGraph V E A) + (vertexOrder : V ≃ Fin n) (dartOrder : E ≃ Fin m) (labelOrder : A ≃ Label) : Table := + ofGraph (enumeratedGraph G vertexOrder dartOrder labelOrder) + +def bitWord (b : Bool) : Nat := if b then 1 else 0 + +def parseBit : Nat → Option Bool + | 0 => some false + | 1 => some true + | _ => none + +@[simp] theorem parseBit_bitWord (b : Bool) : parseBit (bitWord b) = some b := by + cases b <;> rfl + +@[simp] theorem parseBits_bitWords (bits : List Bool) : + (bits.map bitWord).mapM parseBit = some bits := by + induction bits with + | nil => rfl + | cons bit bits ih => simp [ih] + +def relationWords (relation : RelationTable) : List Nat := relation.toList.map bitWord + +@[simp] theorem relationWords_length (relation : RelationTable) : + (relationWords relation).length = 4096 := by simp [relationWords] + +def parseRelation (words : List Nat) : Option RelationTable := do + let bits ← words.mapM parseBit + if length_ok : bits.length = 4096 then + some ⟨bits.toArray, by simpa using length_ok⟩ + else none + +@[simp] theorem parseRelation_encoded (relation : RelationTable) : + parseRelation (relationWords relation) = some relation := by + unfold parseRelation relationWords + rw [parseBits_bitWords] + simp + exact Vector.toArray_toList + +def rowWords {n m : Nat} (row : DartRow n m) : List Nat := + [row.tail.val, row.reverseIndex.val] ++ relationWords row.relation + +def parseRow (vertices darts : Nat) : List Nat → Option (DartRow vertices darts × List Nat) + | tail :: reverseIndex :: words => do + let tail ← parseLabel vertices tail + let reverseIndex ← parseLabel darts reverseIndex + let relation ← parseRelation (words.take 4096) + return (⟨tail, reverseIndex, relation⟩, words.drop 4096) + | _ => none + +@[simp] theorem parseRow_encoded {n m : Nat} (row : DartRow n m) (rest : List Nat) : + parseRow n m (rowWords row ++ rest) = some (row, rest) := by + cases row with + | mk tail reverseIndex relation => + have taken := List.take_left' (l₂ := rest) (relationWords_length relation) + have dropped := List.drop_left' (l₂ := rest) (relationWords_length relation) + simp [rowWords, parseRow, taken, dropped] + +def parseRows (vertices darts : Nat) : + Nat → List Nat → Option (List (DartRow vertices darts) × List Nat) + | 0, words => some ([], words) + | count + 1, words => do + let (row, words) ← parseRow vertices darts words + let (rows, words) ← parseRows vertices darts count words + return (row :: rows, words) + +@[simp] theorem parseRows_encoded {n m : Nat} (rows : List (DartRow n m)) (rest : List Nat) : + parseRows n m rows.length (rows.flatMap rowWords ++ rest) = some (rows, rest) := by + induction rows with + | nil => rfl + | cons row rows ih => simp [parseRows, List.append_assoc, ih] + +def tableWords (table : Table) : List Nat := + [table.vertices, table.darts] ++ (rowList table).flatMap rowWords + +def tableBits (table : Table) : List Bool := encodeWords (tableWords table) + +def decodeTableWords : List Nat → Option Table + | vertices :: darts :: words => do + let (parsed, trailing) ← parseRows vertices darts darts words + if trailing = [] then + if length_ok : parsed.length = darts then + let rows : Rows vertices darts := ⟨parsed.toArray, by simpa using length_ok⟩ + if valid : Valid rows then some ⟨vertices, darts, rows, valid⟩ else none + else none + else none + | _ => none + +@[simp] theorem decodeTableWords_encoded (table : Table) : + decodeTableWords (tableWords table) = some table := by + cases table with + | mk vertices darts rows valid => + have parsed := parseRows_encoded rows.toList [] + simp only [Vector.length_toList, List.append_nil] at parsed + simp [tableWords, rowList, decodeTableWords, parsed, valid, Vector.toArray_toList] + +def decodeTableBits (bits : List Bool) : Option Table := + decodeWords bits >>= decodeTableWords + +@[simp] theorem decodeTableBits_encoded (table : Table) : + decodeTableBits (tableBits table) = some table := by + simp [decodeTableBits, tableBits] + +def encoding : Computability.Encoding Table Bool where + encode := tableBits + decode := decodeTableBits + decode_encode := decodeTableBits_encoded + +theorem tableBits_injective : Function.Injective tableBits := encoding.encode_injective + +@[simp] theorem rowWords_length {n m : Nat} (row : DartRow n m) : + (rowWords row).length = 4098 := by simp [rowWords] + +theorem rowsWords_length {n m : Nat} (rows : List (DartRow n m)) : + (rows.flatMap rowWords).length = 4098 * rows.length := by + induction rows with + | nil => rfl + | cons row rows ih => simp [ih, Nat.mul_add, Nat.add_comm] + +@[simp] theorem tableWords_length (table : Table) : + (tableWords table).length = 2 + 4098 * table.darts := by + simp only [tableWords, List.length_append, List.length_cons, List.length_nil, + rowsWords_length, rowList_length] + +theorem tableWords_length_le_bits (table : Table) : + 2 + 4098 * table.darts ≤ (tableBits table).length := by + rw [tableBits, encodeWords_length, ← tableWords_length] + omega + +theorem relationBits_length_le (relation : RelationTable) : + (encodeWords (relationWords relation)).length ≤ 8192 := by + have h := encodeWords_length_le (relationWords relation) 1 (by + intro word hword + obtain ⟨bit, _, rfl⟩ := List.mem_map.mp hword + cases bit <;> decide) + simpa only [relationWords_length] using h + +theorem rowBits_length_le {n m : Nat} (row : DartRow n m) : + (encodeWords (rowWords row)).length ≤ n + m + 8192 := by + have ht := row.tail.isLt + have hr := row.reverseIndex.isLt + have hp := relationBits_length_le row.relation + simp only [rowWords, encodeWords_append, List.length_append, encodeWords, + encodeWord_length, List.length_nil] at ⊢ + omega + +theorem rowsBits_length_le {n m : Nat} (rows : List (DartRow n m)) : + (encodeWords (rows.flatMap rowWords)).length ≤ rows.length * (n + m + 8192) := by + induction rows with + | nil => simp [encodeWords] + | cons row rows ih => + have hrow := rowBits_length_le row + simp only [List.flatMap_cons, encodeWords_append, List.length_append, + List.length_cons, Nat.add_mul, Nat.one_mul] + omega + +theorem tableBits_length_le (table : Table) : + (tableBits table).length ≤ table.vertices + table.darts + 2 + + table.darts * (table.vertices + table.darts + 8192) := by + have hrows := rowsBits_length_le (rowList table) + rw [rowList_length] at hrows + simp only [tableBits, tableWords, encodeWords_append, List.length_append, + encodeWords, encodeWord_length, List.length_nil] + omega + +theorem vertices_le_tableBits_length (table : Table) : + table.vertices ≤ (tableBits table).length := by + simp only [tableBits, tableWords, encodeWords_append, List.length_append, + encodeWords, encodeWord_length, List.length_nil] + omega + +theorem darts_le_tableBits_length (table : Table) : + table.darts ≤ (tableBits table).length := by + simp only [tableBits, tableWords, encodeWords_append, List.length_append, + encodeWords, encodeWord_length, List.length_nil] + omega + +end MinUncutGames.Foundations.PCP.GraphTables + +end +section +namespace MinUncutGames.Foundations.PCP.PoweringWalks + +structure PortGraph (V D : Type*) where + rot : (V × D) ≃ (V × D) + rot_involutive : Function.Involutive rot + +abbrev Edge (V D : Type*) := V × D +abbrev Walk (V D : Type*) (t : Nat) := V × (Fin t → D) + +variable {V D : Type*} + +def next (G : PortGraph V D) (v : V) (d : D) : V := (G.rot (v, d)).1 + +@[simp] theorem rot_rot (G : PortGraph V D) (e : Edge V D) : + G.rot (G.rot e) = e := G.rot_involutive e + +def walkEnd (G : PortGraph V D) : V → List D → V + | v, [] => v + | v, d :: ds => walkEnd G (next G v d) ds + +@[simp] theorem walkEnd_nil (G : PortGraph V D) (v : V) : walkEnd G v [] = v := rfl + +@[simp] theorem walkEnd_cons (G : PortGraph V D) (v : V) (d : D) (ds : List D) : + walkEnd G v (d :: ds) = walkEnd G (next G v d) ds := rfl + +theorem walkEnd_append (G : PortGraph V D) (v : V) (as bs : List D) : + walkEnd G v (as ++ bs) = walkEnd G (walkEnd G v as) bs := by + induction as generalizing v with + | nil => rfl + | cons d ds ih => exact ih (next G v d) + +def splitHead (V D : Type*) (n : Nat) : + Walk V D (n + 1) ≃ ((V × D) × (Fin n → D)) where + toFun w := ((w.1, w.2 0), fun j => w.2 j.succ) + invFun z := (z.1.1, Fin.cases z.1.2 z.2) + left_inv w := by + apply Prod.ext + · rfl + funext j + exact Fin.cases rfl (fun _ => rfl) j + right_inv z := rfl + +def rotateHead (G : PortGraph V D) (n : Nat) : Walk V D (n + 1) ≃ Walk V D (n + 1) := + (splitHead V D n).trans + ((Equiv.prodCongr G.rot (Equiv.refl (Fin n → D))).trans (splitHead V D n).symm) + +@[simp] theorem rotateHead_vertex (G : PortGraph V D) (n : Nat) (w : Walk V D (n + 1)) : + (rotateHead G n w).1 = next G w.1 (w.2 0) := rfl + +@[simp] theorem rotateHead_zero (G : PortGraph V D) (n : Nat) (w : Walk V D (n + 1)) : + (rotateHead G n w).2 0 = (G.rot (w.1, w.2 0)).2 := rfl + +@[simp] theorem rotateHead_succ (G : PortGraph V D) (n : Nat) + (w : Walk V D (n + 1)) (j : Fin n) : + (rotateHead G n w).2 j.succ = w.2 j.succ := rfl + +def permutePorts {t : Nat} (σ : Fin t ≃ Fin t) : Walk V D t ≃ Walk V D t where + toFun w := (w.1, fun j => w.2 (σ j)) + invFun w := (w.1, fun j => w.2 (σ.symm j)) + left_inv w := by + apply Prod.ext + · rfl + funext j + exact congrArg w.2 (σ.apply_symm_apply j) + right_inv w := by + apply Prod.ext + · rfl + funext j + exact congrArg w.2 (σ.symm_apply_apply j) + +def wordEnd (G : PortGraph V D) : (n : Nat) → V → (Fin n → D) → V + | 0, v, _ => v + | n + 1, v, p => wordEnd G n (next G v (p 0)) (fun j => p j.succ) + +def endpoint (G : PortGraph V D) {n : Nat} (w : Walk V D n) : V := + wordEnd G n w.1 w.2 + +theorem natCard_walk [Finite V] [Finite D] (n : Nat) : + Nat.card (Walk V D n) = Nat.card V * Nat.card D ^ n := by + simp [Walk, Nat.card_prod, Nat.card_fun] + +def headTailEquiv (V D : Type*) (n : Nat) : + Walk V D (n + 1) ≃ (Walk V D n × D) where + toFun w := ((w.1, fun j => w.2 j.succ), w.2 0) + invFun z := (z.1.1, Fin.cases z.2 z.1.2) + left_inv w := by + apply Prod.ext + · rfl + · funext j + exact Fin.cases rfl (fun _ => rfl) j + right_inv z := rfl + +def advanceTail {n : Nat} (G : PortGraph V D) (w : Walk V D (n + 1)) : Walk V D n := + ((G.rot (w.1, w.2 0)).1, fun j => w.2 j.succ) + +def edgeAt (G : PortGraph V D) : + (n : Nat) → Walk V D (n + 1) → Fin (n + 1) → Edge V D + | 0, w, _ => (w.1, w.2 0) + | n + 1, w, k => Fin.cases (w.1, w.2 0) + (fun j => edgeAt G n (advanceTail G w) j) k + +def pivotEquiv (G : PortGraph V D) : + (n : Nat) → Fin (n + 1) → + (Walk V D (n + 1) ≃ (Edge V D × (Fin n → D))) + | 0, _ => splitHead V D 0 + | n + 1, k => Fin.cases (splitHead V D (n + 1)) + (fun j => (rotateHead G (n + 1)).trans + ((headTailEquiv V D (n + 1)).trans + ((Equiv.prodCongr (pivotEquiv G n j) (Equiv.refl D)).trans + (headTailEquiv (Edge V D) D n).symm))) k + +theorem pivotEquiv_fst (G : PortGraph V D) : + ∀ (n : Nat) (k : Fin (n + 1)) (w : Walk V D (n + 1)), + (pivotEquiv G n k w).1 = edgeAt G n w k := by + intro n + induction n with + | zero => intro k w; rfl + | succ n ih => + intro k w + refine Fin.cases ?_ (fun j => ?_) k + · rfl + · change (pivotEquiv G n j (advanceTail G w)).1 = + edgeAt G n (advanceTail G w) j + exact ih j (advanceTail G w) + +theorem edgeAt_port (G : PortGraph V D) : + ∀ (n : Nat) (w : Walk V D (n + 1)) (k : Fin (n + 1)), + (edgeAt G n w k).2 = w.2 k := by + intro n + induction n with + | zero => + intro w k + have hk : k = 0 := Fin.eq_zero k + subst k + rfl + | succ n ih => + intro w k + refine Fin.cases ?_ (fun j => ?_) k + · rfl + · exact ih (advanceTail G w) j + +theorem pivotEquiv_zero_apply (G : PortGraph V D) (n : Nat) (w : Walk V D (n + 1)) : + pivotEquiv G n 0 w = ((w.1, w.2 0), fun j => w.2 j.succ) := by + cases n <;> rfl + +theorem pivotEquiv_succ_apply (G : PortGraph V D) + (n : Nat) (k : Fin (n + 1)) (w : Walk V D (n + 2)) : + pivotEquiv G (n + 1) k.succ w = + ((pivotEquiv G n k (advanceTail G w)).1, + Fin.cases (G.rot (w.1, w.2 0)).2 + (pivotEquiv G n k (advanceTail G w)).2) := rfl + +def projectedFiberEquiv {X E R : Type*} (e : X ≃ E × R) (f : X → E) + (he : ∀ x, (e x).1 = f x) (a : E) : {x // f x = a} ≃ R where + toFun x := (e x.val).2 + invFun r := ⟨e.symm (a, r), by + exact (he _).symm.trans (congrArg Prod.fst (e.apply_symm_apply (a, r)))⟩ + left_inv x := by + apply Subtype.ext + apply e.injective + rw [e.apply_symm_apply] + exact Prod.ext ((he x.val).trans x.property).symm rfl + right_inv r := congrArg Prod.snd (e.apply_symm_apply (a, r)) + +def projectedEventEquiv {X E R : Type*} (e : X ≃ E × R) (f : X → E) + (he : ∀ x, (e x).1 = f x) (P : E → Prop) : + {x // P (f x)} ≃ ({a // P a} × R) where + toFun x := (⟨(e x.val).1, by rw [he]; exact x.property⟩, (e x.val).2) + invFun ar := ⟨e.symm (ar.1.val, ar.2), by + have h : f (e.symm (ar.1.val, ar.2)) = ar.1.val := + (he _).symm.trans (congrArg Prod.fst (e.apply_symm_apply (ar.1.val, ar.2))) + simpa only [h] using ar.1.property⟩ + left_inv x := by + apply Subtype.ext + exact e.symm_apply_apply x.val + right_inv ar := by + apply Prod.ext + · apply Subtype.ext + exact congrArg Prod.fst (e.apply_symm_apply (ar.1.val, ar.2)) + · change (e (e.symm (ar.1.val, ar.2))).2 = ar.2 + exact congrArg Prod.snd (e.apply_symm_apply (ar.1.val, ar.2)) + +theorem natCard_edgeAt_fiber (G : PortGraph V D) (n : Nat) (k : Fin (n + 1)) + (a : Edge V D) : + Nat.card {w : Walk V D (n + 1) // edgeAt G n w k = a} = Nat.card D ^ n := by + calc + _ = Nat.card (Fin n → D) := Nat.card_congr + (projectedFiberEquiv (pivotEquiv G n k) (fun w => edgeAt G n w k) + (pivotEquiv_fst G n k) a) + _ = _ := by simp [Nat.card_fun] + +theorem natCard_edgeAt_event (G : PortGraph V D) (n : Nat) (k : Fin (n + 1)) + (P : Edge V D → Prop) : + Nat.card {w : Walk V D (n + 1) // P (edgeAt G n w k)} = + Nat.card {a : Edge V D // P a} * Nat.card D ^ n := by + calc + _ = Nat.card ({a : Edge V D // P a} × (Fin n → D)) := Nat.card_congr + (projectedEventEquiv (pivotEquiv G n k) (fun w => edgeAt G n w k) + (pivotEquiv_fst G n k) P) + _ = _ := by simp [Nat.card_prod, Nat.card_fun] + +def leftFromPivot (G : PortGraph V D) : + (n : Nat) → Fin (n + 1) → V → (Fin n → D) → V + | 0, _, v, _ => v + | n + 1, k, v, r => Fin.cases v + (fun j => next G (leftFromPivot G n j v (fun m => r m.succ)) (r 0)) k + +def rightFromPivot (G : PortGraph V D) : + (n : Nat) → Fin (n + 1) → Edge V D → (Fin n → D) → V + | 0, _, e, _ => next G e.1 e.2 + | n + 1, k, e, r => Fin.cases + (wordEnd G (n + 1) (next G e.1 e.2) r) + (fun j => rightFromPivot G n j e (fun m => r m.succ)) k + +theorem leftFromPivot_zero (G : PortGraph V D) (n : Nat) + (v : V) (r : Fin n → D) : leftFromPivot G n 0 v r = v := by + cases n <;> rfl + +theorem rightFromPivot_zero (G : PortGraph V D) (n : Nat) + (e : Edge V D) (r : Fin n → D) : + rightFromPivot G n 0 e r = wordEnd G n (next G e.1 e.2) r := by + cases n <;> rfl + +theorem leftFromPivot_actual (G : PortGraph V D) : + ∀ (n : Nat) (k : Fin (n + 1)) (w : Walk V D (n + 1)), + leftFromPivot G n k (pivotEquiv G n k w).1.1 (pivotEquiv G n k w).2 = w.1 := by + intro n + induction n with + | zero => intro k w; rfl + | succ n ih => + intro k w + refine Fin.cases ?_ (fun j => ?_) k + · rfl + · rw [pivotEquiv_succ_apply] + change next G + (leftFromPivot G n j (pivotEquiv G n j (advanceTail G w)).1.1 + (pivotEquiv G n j (advanceTail G w)).2) + (G.rot (w.1, w.2 0)).2 = w.1 + rw [ih j (advanceTail G w)] + change (G.rot ((G.rot (w.1, w.2 0)).1, (G.rot (w.1, w.2 0)).2)).1 = w.1 + exact congrArg Prod.fst (rot_rot G (w.1, w.2 0)) + +theorem rightFromPivot_actual (G : PortGraph V D) : + ∀ (n : Nat) (k : Fin (n + 1)) (w : Walk V D (n + 1)), + rightFromPivot G n k (pivotEquiv G n k w).1 (pivotEquiv G n k w).2 = + endpoint G w := by + intro n + induction n with + | zero => intro k w; rfl + | succ n ih => + intro k w + refine Fin.cases ?_ (fun j => ?_) k + · rfl + · rw [pivotEquiv_succ_apply] + change rightFromPivot G n j (pivotEquiv G n j (advanceTail G w)).1 + (pivotEquiv G n j (advanceTail G w)).2 = endpoint G w + rw [ih j (advanceTail G w)] + rfl + +end MinUncutGames.Foundations.PCP.PoweringWalks + +end +section +namespace MinUncutGames.Foundations.PCP.PortTables + +open PoweringWalks + +abbrev Label := GraphTables.Label + +def rowIndex (vertices ports : Nat) : + Fin vertices × Fin ports ≃ Fin (vertices * ports) := finProdFinEquiv + +@[simp] theorem rowIndex_val (n d : Nat) (e : Fin n × Fin d) : + (rowIndex n d e).val = e.2.val + d * e.1.val := rfl + +structure Table (vertices ports : Nat) where + reverseIndex : Vector (Fin (vertices * ports)) (vertices * ports) + relations : Vector GraphTables.RelationTable (vertices * ports) + involutive : Function.Involutive + (fun i : Fin (vertices * ports) => reverseIndex[i]) + transpose : ∀ (i : Fin (vertices * ports)) (a b : Label), + GraphTables.relationAt relations[reverseIndex[i]] b a = + GraphTables.relationAt relations[i] a b + +variable {n d : Nat} + +def rotation (table : Table n d) (e : Fin n × Fin d) : Fin n × Fin d := + (rowIndex n d).symm table.reverseIndex[rowIndex n d e] + +def accepts (table : Table n d) (e : Fin n × Fin d) (a b : Label) : Bool := + GraphTables.relationAt table.relations[rowIndex n d e] a b + +@[simp] theorem rowIndex_rotation (table : Table n d) (e : Fin n × Fin d) : + rowIndex n d (rotation table e) = table.reverseIndex[rowIndex n d e] := by + exact (rowIndex n d).apply_symm_apply _ + +theorem rotation_involutive (table : Table n d) : Function.Involutive (rotation table) := by + intro e + simp only [rotation, Equiv.apply_symm_apply] + exact (congrArg (rowIndex n d).symm (table.involutive (rowIndex n d e))).trans + ((rowIndex n d).symm_apply_apply e) + +theorem accepts_rotation (table : Table n d) (e : Fin n × Fin d) (a b : Label) : + accepts table (rotation table e) b a = accepts table e a b := by + simpa only [accepts, rowIndex_rotation] using table.transpose (rowIndex n d e) a b + +def portGraph (table : Table n d) : PortGraph (Fin n) (Fin d) where + rot := + { toFun := rotation table + invFun := rotation table + left_inv := rotation_involutive table + right_inv := rotation_involutive table } + rot_involutive := rotation_involutive table + +@[simp] theorem portGraph_rot (table : Table n d) (e : Fin n × Fin d) : + (portGraph table).rot e = rotation table e := rfl + +def baseGraph (table : Table n d) : ConstraintGraph (Fin n) (Fin n × Fin d) Label where + reverse := (portGraph table).rot + reverse_involutive := rotation_involutive table + tail := Prod.fst + accepts := accepts table + reverse_accepts := accepts_rotation table + +@[simp] theorem baseGraph_reverse (table : Table n d) (e : Fin n × Fin d) : + (baseGraph table).reverse e = rotation table e := rfl + +@[simp] theorem baseGraph_tail (table : Table n d) (e : Fin n × Fin d) : + (baseGraph table).tail e = e.1 := rfl + +@[simp] theorem baseGraph_head (table : Table n d) (e : Fin n × Fin d) : + (baseGraph table).head e = (rotation table e).1 := rfl + +@[simp] theorem baseGraph_accepts (table : Table n d) (e : Fin n × Fin d) (a b : Label) : + (baseGraph table).accepts e a b = accepts table e a b := rfl + +def ofPortGraph (G : PortGraph (Fin n) (Fin d)) + (predicate : (Fin n × Fin d) → Label → Label → Bool) + (htranspose : ∀ e a b, predicate (G.rot e) b a = predicate e a b) : Table n d where + reverseIndex := Vector.ofFn (fun i => rowIndex n d (G.rot ((rowIndex n d).symm i))) + relations := Vector.ofFn (fun i => GraphTables.relationOf (predicate ((rowIndex n d).symm i))) + involutive := by + intro i + simp only [Fin.getElem_fin, Vector.getElem_ofFn, Fin.eta, + Equiv.symm_apply_apply] + exact (congrArg (rowIndex n d) (G.rot_involutive ((rowIndex n d).symm i))).trans + ((rowIndex n d).apply_symm_apply i) + transpose := by + intro i a b + simp only [Fin.getElem_fin, Vector.getElem_ofFn, Fin.eta, + Equiv.symm_apply_apply, GraphTables.relationAt_relationOf] + exact htranspose ((rowIndex n d).symm i) a b + +@[simp] theorem rotation_ofPortGraph (G : PortGraph (Fin n) (Fin d)) + (predicate : (Fin n × Fin d) → Label → Label → Bool) + (htranspose : ∀ e a b, predicate (G.rot e) b a = predicate e a b) + (e : Fin n × Fin d) : rotation (ofPortGraph G predicate htranspose) e = G.rot e := by + simp only [rotation, ofPortGraph, Fin.getElem_fin, Vector.getElem_ofFn, Fin.eta, + Equiv.symm_apply_apply] + +@[simp] theorem accepts_ofPortGraph (G : PortGraph (Fin n) (Fin d)) + (predicate : (Fin n × Fin d) → Label → Label → Bool) + (htranspose : ∀ e a b, predicate (G.rot e) b a = predicate e a b) + (e : Fin n × Fin d) (a b : Label) : + accepts (ofPortGraph G predicate htranspose) e a b = predicate e a b := by + simp only [accepts, ofPortGraph, Fin.getElem_fin, Vector.getElem_ofFn, Fin.eta, + Equiv.symm_apply_apply, GraphTables.relationAt_relationOf] + +def flatRows (table : Table n d) : GraphTables.Rows n (n * d) := + Vector.ofFn (fun i => + ⟨((rowIndex n d).symm i).1, table.reverseIndex[i], table.relations[i]⟩) + +@[simp] theorem reverseAt_flatRows (table : Table n d) (i : Fin (n * d)) : + GraphTables.reverseAt (flatRows table) i = table.reverseIndex[i] := by + simp [GraphTables.reverseAt, flatRows] + +@[simp] theorem acceptsAt_flatRows (table : Table n d) (i : Fin (n * d)) (a b : Label) : + GraphTables.acceptsAt (flatRows table) i a b = GraphTables.relationAt table.relations[i] a b := by + simp [GraphTables.acceptsAt, flatRows] + +theorem flatRows_valid (table : Table n d) : GraphTables.Valid (flatRows table) := by + constructor + · intro i + simpa only [reverseAt_flatRows] using table.involutive i + · intro i a b + simpa only [reverseAt_flatRows, acceptsAt_flatRows] using table.transpose i a b + +def graphTable (table : Table n d) : GraphTables.Table := + ⟨n, n * d, flatRows table, flatRows_valid table⟩ + +def tableWords (table : Table n d) : List Nat := GraphTables.tableWords (graphTable table) + +def tableBits (table : Table n d) : List Bool := GraphTables.tableBits (graphTable table) + +abbrev Input (ports : Nat) := (vertices : Nat) × Table vertices ports + +def inputBits {ports : Nat} (input : Input ports) : List Bool := tableBits input.2 + +theorem tableWords_eq (table : Table n d) : + tableWords table = [n, n * d] ++ (flatRows table).toList.flatMap GraphTables.rowWords := rfl + +theorem tableWords_length (table : Table n d) : + (tableWords table).length = 2 + 4098 * (n * d) := + GraphTables.tableWords_length (graphTable table) + +theorem vertices_le_tableBits_length (table : Table n d) : n ≤ (tableBits table).length := + GraphTables.vertices_le_tableBits_length (graphTable table) + +end MinUncutGames.Foundations.PCP.PortTables + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/Hastad.lean b/lean/OAI/Computability/MinUncut/PCP/Hastad.lean new file mode 100644 index 0000000000000000000000000000000000000000..aa6015090de76cd72383c3c001e5857653f1e230 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/Hastad.lean @@ -0,0 +1,111 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.TableIteration +import OAI.Computability.MinUncut.PCP.RoundComputation +import OAI.Computability.MinUncut.Games.IncidenceProbability +import OAI.Computability.MinUncut.Machines.MachineLazyTableRuntime +import OAI.Computability.MinUncut.Machines.MachineTableIteration + +namespace OAI + +section +namespace MinUncutGames.Outer.HastadSource + +open MinUncutGames.Foundations Target Complexity PCP +open MinUncutGames.Reduction ActualSource +open MachineFiniteAlphabet + + +def success (input : SourceEncoding.Input) (bits : Fin input.«variables» → Bool) : ℚ := + (input.equations.countP (fun e => CloneGap.satisfied e bits) : ℚ) / + input.equations.length + +def asSource (input : SourceEncoding.Input) : Source := + Source.ofList input.equations input.nonempty + +theorem failure_add_success (input : SourceEncoding.Input) + (bits : Fin input.«variables» → Bool) : + (asSource input).failure bits + success input bits = 1 := by + have h := SourceProbability.failure_add_satisfaction (asSource input) bits + rw [show (asSource input).sourceList = input.equations from + Source.sourceList_ofList input.equations input.nonempty] at h + exact h + +def gapInput (H : RoundTables.BaseTable) (F : Formula) : + Hastad.SourceGeneratorContract.NonemptyFormula := + ⟨TableIteration.gapMap H F, TableIteration.gapMap_nonempty H F⟩ + +def sourceMap (ξ : ℚ) (hξ : 0 < ξ) := + Hastad.SourceGeneratorContract.errorMap PCPIteration.finalClauseGap ξ + PCPIteration.finalClauseGap_positive TableGapReduction.finalClauseGap_le_one hξ + +def output (H : RoundTables.BaseTable) (ξ : ℚ) (hξ : 0 < ξ) + (F : Formula) : SourceEncoding.Input := + sourceMap ξ hξ (gapInput H F) + +theorem complete (H : RoundTables.BaseTable) (ξ : ℚ) (hξ : 0 < ξ) + (F : Formula) (hF : F.Satisfiable) : + ∃ bits, 1 - ξ ≤ success (output H ξ hξ F) bits := by + exact Hastad.SourceGap.forError_complete PCPIteration.finalClauseGap ξ + PCPIteration.finalClauseGap_positive TableGapReduction.finalClauseGap_le_one hξ + (TableIteration.gapMap H F) (TableIteration.gapMap_completeness H F hF) + +theorem sound (H : RoundTables.BaseTable) + (certificate : SpectralReturn.SpectralCertificate (ExpanderTables.graph H) (1 / 100 : ℝ)) + (ξ : ℚ) (hξ : 0 < ξ) (F : Formula) (hF : ¬ F.Satisfiable) + (bits : Fin (output H ξ hξ F).«variables» → Bool) : + success (output H ξ hξ F) bits ≤ (1 + ξ) / 2 := by + exact Hastad.SourceGap.forError_sound PCPIteration.finalClauseGap ξ + PCPIteration.finalClauseGap_positive TableGapReduction.finalClauseGap_le_one hξ + (TableIteration.gapMap H F) (TableGapReduction.gapMap_clauseGap H certificate F hF) bits + +noncomputable def roundMachine (H : RoundTables.BaseTable) := + RoundComputation.tablePolynomialTime H (PreprocessingRuntime.tablePolynomialTime H) + +theorem roundMachine_finite (H : RoundTables.BaseTable) : + FiniteAlphabet (roundMachine H).tm := + RoundComputation.tablePolynomialTime_finite_alphabet H + (PreprocessingRuntime.tablePolynomialTime H) (PreprocessingRuntime.finiteAlphabet H) + +noncomputable def gapMachine (H : RoundTables.BaseTable) : + Turing.TM2ComputableInPolyTime formulaBits Hastad.SourceGeneratorContract.inputEncoding + (gapInput H) where + toTM2ComputableAux := + (MachineTableIteration.gapMapCertificate H (roundMachine H)).toTM2ComputableAux + time := (MachineTableIteration.gapMapCertificate H (roundMachine H)).time + outputsFun F := (MachineTableIteration.gapMapCertificate H (roundMachine H)).outputsFun F + +noncomputable def sourceMachine (ξ : ℚ) (hξ : 0 < ξ) : + Turing.TM2ComputableInPolyTime Hastad.SourceGeneratorContract.inputEncoding + SourceEncoding.inputBits (sourceMap ξ hξ) := + Hastad.SourceGenerator.forErrorComputableInPolyTime PCPIteration.finalClauseGap ξ + PCPIteration.finalClauseGap_positive TableGapReduction.finalClauseGap_le_one hξ + +noncomputable def computation (H : RoundTables.BaseTable) (ξ : ℚ) (hξ : 0 < ξ) : + Turing.TM2ComputableInPolyTime formulaBits SourceEncoding.inputBits (output H ξ hξ) := + MachineSequential.composeBits (f := gapInput H) (g := sourceMap ξ hξ) + (gapMachine H) (sourceMachine ξ hξ) + +theorem finiteAlphabet (H : RoundTables.BaseTable) (ξ : ℚ) (hξ : 0 < ξ) : + FiniteAlphabet (computation H ξ hξ).tm := + MachineFiniteAlphabet.composeBits (gapMachine H) (sourceMachine ξ hξ) + (TableIterationFiniteAlphabet.gapMap H (roundMachine H) (roundMachine_finite H)) + (Hastad.SourceGenerator.forError_finite_work_alphabets PCPIteration.finalClauseGap ξ + PCPIteration.finalClauseGap_positive TableGapReduction.finalClauseGap_le_one hξ) + +structure Reduction (ξ : ℚ) where + reduce : Formula → SourceEncoding.Input + completeness : ∀ F, F.Satisfiable → ∃ bits, 1 - ξ ≤ success (reduce F) bits + soundness : ∀ F, ¬ F.Satisfiable → ∀ bits, success (reduce F) bits ≤ (1 + ξ) / 2 + computation : Turing.TM2ComputableInPolyTime formulaBits SourceEncoding.inputBits reduce + finiteAlphabet : FiniteAlphabet computation.tm + +theorem exists_reduction (ξ : ℚ) (hξ : 0 < ξ) : Nonempty (Reduction ξ) := by + obtain ⟨H, certificate⟩ := ExpanderTables.exists_base_table + exact ⟨⟨output H ξ hξ, complete H ξ hξ, sound H certificate ξ hξ, + computation H ξ hξ, finiteAlphabet H ξ hξ⟩⟩ + +end MinUncutGames.Outer.HastadSource + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/HeaderAccumulate.lean b/lean/OAI/Computability/MinUncut/PCP/HeaderAccumulate.lean new file mode 100644 index 0000000000000000000000000000000000000000..f0e5ca6ba813383c44b2ea377f193d1298cac4a7 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/HeaderAccumulate.lean @@ -0,0 +1,743 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.HeaderCounts + +namespace OAI + +section +namespace MinUncutGames.Foundations.Hastad.SourceHeaderAccumulate + +open Turing MinUncutGames.Foundations.Complexity +open MachineComposition +open MinUncutGames.Reduction.MachineTransfer + +structure Layout (K : Type) where + bits : K + count : K + accumulator : K + bits_count : bits ≠ count + bits_accumulator : bits ≠ accumulator + count_accumulator : count ≠ accumulator + +variable {K Λ σ : Type} [DecidableEq K] + +def statement (layout : Layout K) (labels : Bool → Λ) (exit : Option Λ) : + Bool → TM2.Stmt (fun _ : K => Bool) Λ (σ × Option Bool) + | false => loopAt layout.bits layout.accumulator id false (labels false) (some (labels true)) + | true => loopAt layout.count layout.accumulator id false (labels true) exit + +def resultTapes (layout : Layout K) (base : K → List Bool) (nBits count : Nat) : K → List Bool := + Function.update (Function.update (Function.update base layout.bits []) layout.count []) + layout.accumulator ((encodeWords [nBits, count]).reverse ++ base layout.accumulator) + +@[simp] theorem result_bits (layout : Layout K) (base : K → List Bool) (nBits count : Nat) : + resultTapes layout base nBits count layout.bits = [] := by + simp [resultTapes, layout.bits_count, layout.bits_accumulator] + +@[simp] theorem result_count (layout : Layout K) (base : K → List Bool) (nBits count : Nat) : + resultTapes layout base nBits count layout.count = [] := by + simp [resultTapes, layout.count_accumulator] + +@[simp] theorem result_accumulator (layout : Layout K) (base : K → List Bool) (nBits count : Nat) : + resultTapes layout base nBits count layout.accumulator = + (encodeWords [nBits, count]).reverse ++ base layout.accumulator := by + simp [resultTapes] + +theorem result_frame (layout : Layout K) (base : K → List Bool) (nBits count : Nat) + (k : K) (hb : k ≠ layout.bits) (hc : k ≠ layout.count) (ha : k ≠ layout.accumulator) : + resultTapes layout base nBits count k = base k := by + simp [resultTapes, hb, hc, ha] + +theorem trace (layout : Layout K) (labels : Bool → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (σ × Option Bool)) + (atLabels : ∀ l, program (labels l) = statement layout labels exit l) + (base : K → List Bool) (nBits count : Nat) + (hbits : base layout.bits = encodeWord nBits) + (hcount : base layout.count = encodeWord count) (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[nBits + count + 4] + (some ⟨some (labels false), (ambient, register), base⟩) = + some ⟨exit, (ambient, none), resultTapes layout base nBits count⟩ := by + let middle := tapesAt layout.bits layout.accumulator base [] + ((encodeWord nBits).reverse ++ base layout.accumulator) + have firstRun := transferAt_fromTapes layout.bits layout.accumulator layout.bits_accumulator + id false (labels false) (some (labels true)) program (by simpa only [statement] using atLabels false) base ambient register + change (advance (TM2.step program))^[(base layout.bits).length + 1] + (some ⟨some (labels false), (ambient, register), base⟩) = _ at firstRun + simp only [hbits, List.map_id, encodeWord_length] at firstRun + have hc : middle layout.count = encodeWord count := by + dsimp only [middle] + rw [tapesAt_other _ _ _ layout.bits_count.symm layout.count_accumulator] + exact hcount + have ha : middle layout.accumulator = + (encodeWord nBits).reverse ++ base layout.accumulator := by + exact tapesAt_dst _ _ _ _ _ + have secondRun := transferAt_fromTapes layout.count layout.accumulator layout.count_accumulator + id false (labels true) exit program (by simpa only [statement] using atLabels true) middle ambient none + change (advance (TM2.step program))^[(middle layout.count).length + 1] + (some ⟨some (labels true), (ambient, none), middle⟩) = _ at secondRun + simp only [hc, ha, List.map_id, encodeWord_length] at secondRun + have he : tapesAt layout.count layout.accumulator middle [] + ((encodeWord count).reverse ++ ((encodeWord nBits).reverse ++ base layout.accumulator)) = + resultTapes layout base nBits count := by + funext k + by_cases hk : k = layout.accumulator + · subst k + simp [resultTapes, tapesAt, encodeWords, List.reverse_append, List.append_assoc] + · by_cases hc : k = layout.count + · subst k; simp [tapesAt, resultTapes, layout.count_accumulator] + · by_cases hb : k = layout.bits + · subst k + simp [middle, tapesAt, resultTapes, layout.bits_count, layout.bits_accumulator] + · simp [middle, tapesAt, resultTapes, hk, hc, hb] + rw [he] at secondRun + rw [show nBits + count + 4 = (count + 1 + 1) + (nBits + 1 + 1) by omega, + Function.iterate_add_apply, firstRun] + exact secondRun + +def inTime (layout : Layout K) (labels : Bool → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (σ × Option Bool)) + (atLabels : ∀ l, program (labels l) = statement layout labels exit l) + (base : K → List Bool) (nBits count : Nat) + (hbits : base layout.bits = encodeWord nBits) + (hcount : base layout.count = encodeWord count) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels false), (ambient, register), base⟩ + (some ⟨exit, (ambient, none), resultTapes layout base nBits count⟩) + (nBits + count + 4) where + steps := nBits + count + 4 + evals_in_steps := trace layout labels exit program atLabels base nBits count hbits hcount ambient register + steps_le_m := Nat.le_refl _ + +@[simp] theorem inTime_steps (layout : Layout K) (labels : Bool → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (σ × Option Bool)) + (atLabels : ∀ l, program (labels l) = statement layout labels exit l) + (base : K → List Bool) (nBits count : Nat) + (hbits : base layout.bits = encodeWord nBits) + (hcount : base layout.count = encodeWord count) (ambient : σ) (register : Option Bool) : + (inTime layout labels exit program atLabels base nBits count hbits hcount ambient register).steps = + nBits + count + 4 := rfl + +def machine [Fintype K] [Fintype σ] (layout : Layout K) (ambient : σ) : FinTM2 where + K := K + k₀ := layout.bits + k₁ := layout.accumulator + Γ _ := Bool + Λ := Bool + main := false + σ := σ × Option Bool + initialState := (ambient, none) + m := statement layout id none + +theorem source_inputBits_header (input : MinUncutGames.Reduction.SourceEncoding.Input) : + MinUncutGames.Reduction.SourceEncoding.inputBits input = + encodeWords [input.«variables», input.equations.length] ++ + encodeWords (input.equations.flatMap MinUncutGames.Reduction.SourceEncoding.equationWords) := by + simp only [MinUncutGames.Reduction.SourceEncoding.inputBits, + MinUncutGames.Reduction.SourceEncoding.inputWords, encodeWords_append] + +end MinUncutGames.Foundations.Hastad.SourceHeaderAccumulate + +end +section +namespace MinUncutGames.Foundations.Hastad.SourceStartup + +open Turing Complexity SourceRuntimeModel SourceGeneratorModel +open MachineComposition + +noncomputable section + +variable {u D : Nat} + +abbrev Tape (u D : Nat) := SourceGeneratorModel.Tape u D +abbrev State (u D : Nat) := SourceRuntimeModel.State u D +abbrev ArithmeticLabel (u D : Nat) := SourceHeaderCounts.Label u D ⊕ Bool +abbrev Label (u D : Nat) := SourceLoopInit.Label u ⊕ ArithmeticLabel u D + +local instance (u D : Nat) : DecidableEq (SourceGeneratorModel.Extra u D) := Classical.decEq _ + +def headerLayout (u D : Nat) : SourceHeaderAccumulate.Layout (Tape u D) where + bits := workTape .bitCount + count := workTape .occurrenceCount + accumulator := workTape .accumulator + bits_count := by simp [workTape] + bits_accumulator := by simp [workTape] + count_accumulator := by simp [workTape] + +def arithmeticEntry (u D : Nat) : ArithmeticLabel u D := + .inl (SourceHeaderCounts.evalStart .left) + +def arithmeticProgram : ArithmeticLabel u D → + TM2.Stmt (fun _ : Tape u D => Bool) (ArithmeticLabel u D) ArithmeticState + | .inl l => SourceHeaderCounts.statement (headerSlots u D) Sum.inl (some (.inr false)) l + | .inr l => SourceHeaderAccumulate.statement (headerLayout u D) Sum.inr none l + +def program : Label u D → TM2.Stmt (fun _ : Tape u D => Bool) (Label u D) (State u D) + | .inl l => MachineStateFrame.statement Sum.inl (some (.inr (arithmeticEntry u D))) + (SourceLoopInit.program l) + | .inr l => MachineControl.statement id (arithmeticStateEquiv u D) + (MachineStateFrame.statement Sum.inr none (arithmeticProgram l)) + +def initialTapes (F : Target.Formula) : Tape u D → List Bool := + Function.update (fun _ => []) .formula (formulaBits F) + +def initializedTapes (F : Target.Formula) : Tape u D → List Bool := + SourceLoopInit.outputTapes F (initialTapes F) + +def countedTapes (F : Target.Formula) : Tape u D → List Bool := + SourceHeaderCounts.resultTapes (headerSlots u D) (initializedTapes F) + F.«variables» F.clauses.length + +def outputTapes (F : Target.Formula) : Tape u D → List Bool := + SourceHeaderAccumulate.resultTapes (headerLayout u D) (countedTapes F) + (SourceHeaderCounts.bitValue u F.«variables» F.clauses.length) + (SourceHeaderCounts.occurrenceValue u D F.clauses.length) + +def readyTapes (F : Target.Formula) : Tape u D → List Bool + | .extra (.inr .leftBlock) => encodeWord (SourceHeaderCounts.leftValue u F.«variables») + | .extra (.inr .dummy) => encodeWord (SourceHeaderCounts.dummyValue u F.«variables» F.clauses.length) + | .extra (.inr .accumulator) => + (encodeWords [SourceOccurrences.nBits F u, (SourceOccurrences.sourceList F u D).length]).reverse + | p => initializedTapes F p + +@[simp] theorem initialized_formula (F : Target.Formula) : + initializedTapes (u := u) (D := D) F .formula = formulaBits F := by + simp [initializedTapes, initialTapes] + +@[simp] theorem initialized_current (F : Target.Formula) (j : Fin u) : + initializedTapes (D := D) F (.current j) = encodeWord 0 := by + simp [initializedTapes] + +@[simp] theorem initialized_remaining (F : Target.Formula) (j : Fin u) : + initializedTapes (D := D) F (.remaining j) = encodeWord (F.clauses.length - 1) := by + simp [initializedTapes] + +@[simp] theorem initialized_variableHeader (F : Target.Formula) : + initializedTapes (u := u) (D := D) F variableHeader = encodeWord F.«variables» := by + change SourceLoopInit.outputTapes F (initialTapes F) SourceLoopInit.variableHeader = _ + rw [SourceLoopInit.output_variableHeader] + simp [initialTapes, SourceLoopInit.variableHeader] + +@[simp] theorem initialized_clauseHeader (F : Target.Formula) : + initializedTapes (u := u) (D := D) F clauseHeader = encodeWord F.clauses.length := by + change SourceLoopInit.outputTapes F (initialTapes F) SourceLoopInit.clauseHeader = _ + rw [SourceLoopInit.output_clauseHeader] + simp [initialTapes, SourceLoopInit.clauseHeader] + +@[simp] theorem initialized_work (F : Target.Formula) (role : BodyWork (SourceGeneratorModel.Extra u D)) : + initializedTapes F (workTape role) = [] := by + rw [initializedTapes, SourceLoopInit.output_frame F (initialTapes F) (workTape role) + (by simp [workTape]) (by simp [workTape, SourceLoopInit.variableHeader]) + (by simp [workTape, SourceLoopInit.clauseHeader]) (by simp [workTape]) (by simp [workTape])] + simp [initialTapes, workTape] + +@[simp] theorem initialized_work_raw (F : Target.Formula) + (role : BodyWork (SourceGeneratorModel.Extra u D)) : + initializedTapes F (.extra (.inr role)) = [] := initialized_work F role + +@[simp] theorem initialized_field (F : Target.Formula) (j : Fin u) (s : Fin 6) : + initializedTapes (D := D) F (.field j s) = [] := by + rw [initializedTapes, SourceLoopInit.output_frame F (initialTapes F) (.field j s) + (by simp) (by simp [SourceLoopInit.variableHeader]) (by simp [SourceLoopInit.clauseHeader]) + (by simp) (by simp)] + simp [initialTapes] + +theorem initialized_clean (F : Target.Formula) : + SourceHeaderCounts.Clean (headerSlots u D) (initializedTapes F) := by + constructor + · exact initialized_work F .leftBlock + · exact initialized_work F .rank + · exact initialized_work F .dummy + · exact initialized_work F .bitCount + · exact initialized_work F .occurrenceCount + · exact initialized_work F .accA + · exact initialized_work F .accB + · exact initialized_work F .counter + · exact initialized_work F .arithScratch + · intro i; exact initialized_work F (.extra (.inl i)) + +def initialArithmeticMetadata (u D : Nat) (hD : 0 < D) : ArithmeticMetadata u D := + ((arithmeticStateEquiv u D).symm (SourceGeneratorModel.initialState u D hD)).2 + +theorem initial_arithmetic (hD : 0 < D) : + arithmeticStateEquiv u D ((((), ()), none), initialArithmeticMetadata u D hD) = + SourceGeneratorModel.initialState u D hD := rfl + +theorem initial_loader (hD : 0 < D) : + (((), none), (SourceGeneratorModel.initialState u D hD).2) = + SourceGeneratorModel.initialState u D hD := rfl + +def initializeInTime (F : Target.Formula) (hm : 0 < F.clauses.length) (hD : 0 < D) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (.inl .inputCopyOut), SourceGeneratorModel.initialState u D hD, initialTapes F⟩ + (some ⟨some (.inr (arithmeticEntry u D)), SourceGeneratorModel.initialState u D hD, + initializedTapes F⟩) + ((2 * u + 3) * (formulaBits F).length + 6 * u + 7) := by + have run := SourceLoopInit.initializeInTime F hm (initialTapes (u := u) (D := D) F) + (by simp [initialTapes]) (by simp [initialTapes]) (by simp [initialTapes]) + (by simp [initialTapes]) (by simp [initialTapes, SourceLoopInit.clauseHeader]) + (by intro j; simp [initialTapes]) (by intro j; simp [initialTapes]) + have lifted := MachineStateFrame.execution Sum.inl (some (.inr (arithmeticEntry u D))) + (SourceGeneratorModel.initialState u D hD).2 SourceLoopInit.program program (fun _ => rfl) run + simpa only [MachineStateFrame.configuration, MachineSubroutine.configuration, + MachineStateFrame.frameConfiguration, MachineSubroutine.label, initial_loader, + initializedTapes] using lifted + +def arithmeticInTime (F : Target.Formula) : + StateTransition.EvalsToInTime (TM2.step arithmeticProgram) + ⟨some (arithmeticEntry u D), (((), ()), none), initializedTapes F⟩ + (some ⟨none, (((), ()), none), outputTapes F⟩) + (SourceHeaderCounts.steps u D F.«variables» F.clauses.length + + SourceHeaderCounts.bitValue u F.«variables» F.clauses.length + + SourceHeaderCounts.occurrenceValue u D F.clauses.length + 4) := by + have countRun := SourceHeaderCounts.inTime (headerSlots u D) Sum.inl (some (.inr false)) + arithmeticProgram (fun _ => rfl) (initializedTapes F) F.«variables» F.clauses.length + (initialized_variableHeader F) (initialized_clauseHeader F) (initialized_clean F) () none + have appendRun := SourceHeaderAccumulate.inTime (headerLayout u D) Sum.inr none + arithmeticProgram (fun _ => rfl) (countedTapes F) + (SourceHeaderCounts.bitValue u F.«variables» F.clauses.length) + (SourceHeaderCounts.occurrenceValue u D F.clauses.length) + (SourceHeaderCounts.result_bits (headerSlots u D) (initializedTapes F) _ _) + (SourceHeaderCounts.result_occurrences (headerSlots u D) (initializedTapes F) _ _) ((), ()) none + have joined := StateTransition.EvalsToInTime.trans (TM2.step arithmeticProgram) _ _ _ _ _ + countRun appendRun + refine { steps := joined.steps, evals_in_steps := joined.evals_in_steps, steps_le_m := ?_ } + have ht := joined.steps_le_m + omega + +def arithmeticConfiguration (metadata : ArithmeticMetadata u D) + (c : TM2.Cfg (fun _ : Tape u D => Bool) (ArithmeticLabel u D) ArithmeticState) : + TM2.Cfg (fun _ : Tape u D => Bool) (Label u D) (State u D) := + MachineControl.configuration id (arithmeticStateEquiv u D) + (MachineStateFrame.configuration Sum.inr none metadata c) + +theorem arithmetic_step (metadata : ArithmeticMetadata u D) + (a b : TM2.Cfg (fun _ : Tape u D => Bool) (ArithmeticLabel u D) ArithmeticState) + (h : TM2.step arithmeticProgram a = some b) : + TM2.step program (arithmeticConfiguration metadata a) = + some (arithmeticConfiguration metadata b) := by + rcases a with ⟨label, state, tapes⟩ + cases label with + | none => cases h + | some l => + change some (TM2.stepAux (arithmeticProgram l) state tapes) = some b at h + cases Option.some.inj h + change some (TM2.stepAux + (MachineControl.statement id (arithmeticStateEquiv u D) + (MachineStateFrame.statement Sum.inr none (arithmeticProgram l))) + ((arithmeticStateEquiv u D) (state, metadata)) tapes) = _ + rw [MachineControl.stepAux_simulation, MachineStateFrame.stepAux_simulation] + rfl + +def arithmeticPlacedInTime (F : Target.Formula) (hD : 0 < D) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (.inr (arithmeticEntry u D)), SourceGeneratorModel.initialState u D hD, initializedTapes F⟩ + (some ⟨none, SourceGeneratorModel.initialState u D hD, outputTapes F⟩) + (SourceHeaderCounts.steps u D F.«variables» F.clauses.length + + SourceHeaderCounts.bitValue u F.«variables» F.clauses.length + + SourceHeaderCounts.occurrenceValue u D F.clauses.length + 4) := by + have lifted := liftExecutionInTime (TM2.step arithmeticProgram) (TM2.step program) + (arithmeticConfiguration (initialArithmeticMetadata u D hD)) + (arithmetic_step (initialArithmeticMetadata u D hD)) (arithmeticInTime F) + simpa only [arithmeticConfiguration, MachineControl.configuration, + MachineStateFrame.configuration, MachineStateFrame.frameConfiguration, + MachineSubroutine.configuration, MachineSubroutine.label, Option.map_some, Option.map_none, + id_eq, initial_arithmetic] using lifted + +def phaseBound (F : Target.Formula) (u D : Nat) : Nat := + ((2 * u + 3) * (formulaBits F).length + 6 * u + 7) + + (SourceHeaderCounts.steps u D F.«variables» F.clauses.length + + SourceHeaderCounts.bitValue u F.«variables» F.clauses.length + + SourceHeaderCounts.occurrenceValue u D F.clauses.length + 4) + +def phasesInTime (F : Target.Formula) (hm : 0 < F.clauses.length) (hD : 0 < D) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (.inl .inputCopyOut), SourceGeneratorModel.initialState u D hD, initialTapes F⟩ + (some ⟨none, SourceGeneratorModel.initialState u D hD, outputTapes F⟩) + (phaseBound F u D) := by + have run := StateTransition.EvalsToInTime.trans (TM2.step program) _ _ _ _ _ + (initializeInTime (u := u) F hm hD) (arithmeticPlacedInTime (u := u) F hD) + simpa only [phaseBound, Nat.add_comm] using run + +theorem output_eq_ready (F : Target.Formula) (hm : 0 < F.clauses.length) : + outputTapes (u := u) (D := D) F = readyTapes F := by + funext k + cases k <;> try simp [outputTapes, SourceHeaderAccumulate.resultTapes, headerLayout, + countedTapes, SourceHeaderCounts.resultTapes, SourceHeaderCounts.control, + headerSlots, headerControl, workTape, readyTapes] + rename_i e + cases e with + | inl h => + cases h <;> simp + | inr role => + cases role <;> simp [SourceHeaderCounts.bitValue_eq_nBits, + SourceHeaderCounts.occurrenceValue_eq_length F u D hm] + change Function.update (_ : Tape u D → List Bool) + (SourceContextLoad.Tape.extra (.inr BodyWork.bitCount)) _ + (SourceContextLoad.Tape.extra (.inr BodyWork.accumulator)) = [] + simp + +@[simp] theorem ready_formula (F : Target.Formula) : + readyTapes (u := u) (D := D) F .formula = formulaBits F := initialized_formula F + +@[simp] theorem ready_current (F : Target.Formula) (j : Fin u) : + readyTapes (D := D) F (.current j) = encodeWord 0 := initialized_current F j + +@[simp] theorem ready_remaining (F : Target.Formula) (j : Fin u) : + readyTapes (D := D) F (.remaining j) = encodeWord (F.clauses.length - 1) := initialized_remaining F j + +@[simp] theorem ready_variableHeader (F : Target.Formula) : + readyTapes (u := u) (D := D) F variableHeader = encodeWord F.«variables» := initialized_variableHeader F + +@[simp] theorem ready_clauseHeader (F : Target.Formula) : + readyTapes (u := u) (D := D) F clauseHeader = encodeWord F.clauses.length := initialized_clauseHeader F + +@[simp] theorem ready_leftBlock (F : Target.Formula) : + readyTapes (u := u) (D := D) F (workTape .leftBlock) = + encodeWord (SourceHeaderCounts.leftValue u F.«variables») := rfl + +@[simp] theorem ready_dummy (F : Target.Formula) : + readyTapes (u := u) (D := D) F (workTape .dummy) = + encodeWord (SourceHeaderCounts.dummyValue u F.«variables» F.clauses.length) := rfl + +@[simp] theorem ready_accumulator (F : Target.Formula) : + readyTapes (u := u) (D := D) F (accumulatorTape u D) = + (encodeWords [SourceOccurrences.nBits F u, (SourceOccurrences.sourceList F u D).length]).reverse := rfl + +@[simp] theorem ready_field (F : Target.Formula) (j : Fin u) (s : Fin 6) : + readyTapes (D := D) F (.field j s) = [] := initialized_field F j s + +theorem ready_work_blank (F : Target.Formula) (role : BodyWork (SourceGeneratorModel.Extra u D)) + (hl : role ≠ .leftBlock) (hd : role ≠ .dummy) (ha : role ≠ .accumulator) : + readyTapes F (workTape role) = [] := by + cases role <;> try contradiction + all_goals exact initialized_work F _ + +@[simp] theorem ready_sharedWork (F : Target.Formula) : + readyTapes (u := u) (D := D) F .work = [] := by + simp [readyTapes, initializedTapes] + +theorem ready_sharedFrame (F : Target.Formula) (k : Tape u D) + (hk : k = .index ∨ k = .scratch ∨ k = .copyScratch) : readyTapes F k = [] := by + rcases hk with rfl | rfl | rfl <;> + simp only [readyTapes, initializedTapes] + all_goals + rw [SourceLoopInit.output_frame F (initialTapes F) _ + (by simp) (by simp [SourceLoopInit.variableHeader]) (by simp [SourceLoopInit.clauseHeader]) + (by simp) (by simp)] + simp [initialTapes] + +def startupInTime (F : Target.Formula) (hm : 0 < F.clauses.length) (hD : 0 < D) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (.inl .inputCopyOut), SourceGeneratorModel.initialState u D hD, initialTapes F⟩ + (some ⟨none, SourceGeneratorModel.initialState u D hD, readyTapes F⟩) + (phaseBound F u D) := by + have run := phasesInTime (u := u) F hm hD + simpa only [output_eq_ready F hm] using run + +def timePolynomial (u D : Nat) : Polynomial Nat := + SourceLoopInit.timePolynomial u + SourceHeaderCounts.timePolynomial u D + + SourceHeaderCounts.polynomial u D .left + SourceHeaderCounts.polynomial u D .right + + SourceHeaderCounts.polynomial u D .occurrences + Polynomial.C 5 + +theorem phaseBound_le_polynomial (F : Target.Formula) (u D : Nat) : + phaseBound F u D ≤ (timePolynomial u D).eval (formulaBits F).length := by + have hn := SourceBounds.formulaBits_length_ge_variables F + have hm := SourceBounds.formulaBits_length_ge_clauses F + have hc := SourceHeaderCounts.steps_le_timePolynomial u D F.«variables» F.clauses.length + (formulaBits F).length hn hm + have hl : SourceHeaderCounts.leftValue u F.«variables» ≤ + SourceHeaderCounts.leftValue u (formulaBits F).length := + Nat.mul_le_mul_left _ (Nat.pow_le_pow_left hn u) + have hr : SourceHeaderCounts.rightValue u F.clauses.length ≤ + SourceHeaderCounts.rightValue u (formulaBits F).length := + Nat.mul_le_mul_left _ (Nat.pow_le_pow_left hm u) + have ho : SourceHeaderCounts.occurrenceValue u D F.clauses.length ≤ + SourceHeaderCounts.occurrenceValue u D (formulaBits F).length := + Nat.mul_le_mul_left _ (Nat.pow_le_pow_left hm u) + simp only [phaseBound, timePolynomial, Polynomial.eval_add, Polynomial.eval_C, + SourceLoopInit.timePolynomial_eval, SourceHeaderCounts.polynomial_left_eval, + SourceHeaderCounts.polynomial_right_eval, SourceHeaderCounts.polynomial_occurrences_eval, + SourceHeaderCounts.bitValue, SourceHeaderCounts.dummyValue] + omega + +def startupInPolynomialTime (F : Target.Formula) (hm : 0 < F.clauses.length) (hD : 0 < D) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (.inl .inputCopyOut), SourceGeneratorModel.initialState u D hD, initialTapes F⟩ + (some ⟨none, SourceGeneratorModel.initialState u D hD, readyTapes F⟩) + ((timePolynomial u D).eval (formulaBits F).length) := by + have run := startupInTime (u := u) F hm hD + refine { steps := run.steps, evals_in_steps := run.evals_in_steps, steps_le_m := ?_ } + exact Nat.le_trans run.steps_le_m (phaseBound_le_polynomial F u D) + +def machine (u D : Nat) (hD : 0 < D) : FinTM2 where + K := Tape u D + k₀ := .formula + k₁ := accumulatorTape u D + Γ _ := Bool + Λ := Label u D + main := .inl .inputCopyOut + σ := State u D + initialState := SourceGeneratorModel.initialState u D hD + m := program + +end + +end MinUncutGames.Foundations.Hastad.SourceStartup + +end +section +namespace MinUncutGames.Foundations.Hastad.SourceBasePhase + +open Turing Complexity +open Target SourceContexts SourceOccurrences SourceAddressDescriptors +open MinUncutGames.Reduction.MachineSubstitution + +inductive Label + | seed + | horner (label : MachineHorner.Label 2) + | clear + deriving DecidableEq, Fintype + +abbrev Layout := MachineHorner.Layout 2 + +def digits (coefficient offset : Nat) (i : Nat) : Nat := + if i = 0 then coefficient else offset + +theorem horner_value (coefficient rank offset : Nat) : + MachineHorner.value rank (digits coefficient offset) 2 = coefficient * rank + offset := by + simp [MachineHorner.value, digits, Nat.mul_comm] + +def steps (coefficient rank offset : Nat) : Nat := + MachineHorner.steps rank (digits coefficient offset) 2 + coefficient + 2 + +def operandLength (rank offset : Nat) : Nat := + (encodeWord rank).length + (encodeWord offset).length + +noncomputable def timePolynomial (coefficient : Nat) : Polynomial Nat := + (MachineHorner.timePolynomial 2).comp (Polynomial.X + Polynomial.C coefficient) + + Polynomial.C (coefficient + 2) + +theorem timePolynomial_eval (coefficient n : Nat) : + (timePolynomial coefficient).eval n = + (MachineHorner.timePolynomial 2).eval (n + coefficient) + coefficient + 2 := by + simp [timePolynomial, Polynomial.eval_comp, Nat.add_assoc] + +theorem steps_le_timePolynomial (coefficient rank offset : Nat) : + steps coefficient rank offset ≤ (timePolynomial coefficient).eval (operandLength rank offset) := by + have hr : rank ≤ operandLength rank offset + coefficient := by + simp only [operandLength, encodeWord_length] + omega + have hd : ∀ i, i < 2 → digits coefficient offset i ≤ operandLength rank offset + coefficient := by + intro i _ + simp only [digits, operandLength, encodeWord_length] + split <;> omega + have h := MachineHorner.steps_le_timePolynomial rank (digits coefficient offset) 2 + (operandLength rank offset + coefficient) hr hd + rw [timePolynomial_eval] + unfold steps + omega + +variable {K Λ σ : Type} [DecidableEq K] + +def statement (slots : Layout ↪ K) (coefficient : Nat) (labels : Label → Λ) (exit : Option Λ) : + Label → TM2.Stmt (fun _ : K => Bool) Λ (MachineHorner.State σ) + | .seed => pushWord (slots (.inr 0)) (encodeWord coefficient).reverse + (.goto fun _ => labels (.horner .start)) + | .horner label => MachineHorner.statement slots (fun l => labels (.horner l)) + (some (labels .clear)) label + | .clear => MachineHorner.drainLoop (slots (.inr 0)) (labels .clear) exit + +def program (slots : Layout ↪ K) (coefficient : Nat) : + Label → TM2.Stmt (fun _ : K => Bool) Label (MachineHorner.State σ) := + statement slots coefficient id none + +def coefficientTapes (slots : Layout ↪ K) (base : K → List Bool) (coefficient : Nat) : K → List Bool := + Function.update base (slots (.inr 0)) (encodeWord coefficient) + +theorem affineTrace (slots : Layout ↪ K) (coefficient : Nat) (labels : Label → Λ) (exit : Option Λ) + (p : Λ → TM2.Stmt (fun _ : K => Bool) Λ (MachineHorner.State σ)) + (atLabels : ∀ label, p (labels label) = statement slots coefficient labels exit label) + (base : K → List Bool) (rank offset : Nat) + (rankWord : base (slots (.inl 0)) = encodeWord rank) + (offsetWord : base (slots (.inr 1)) = encodeWord offset) + (coefficientEmpty : base (slots (.inr 0)) = []) + (clean : MachineHorner.Clean slots base) (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step p))^[steps coefficient rank offset] + (some ⟨some (labels .seed), ((ambient, ()), register), base⟩) = + some ⟨exit, ((ambient, ()), none), + MachineHorner.resultTapes slots base (coefficient * rank + offset)⟩ := by + have hc (i : Fin 6) : slots (.inl i) ≠ slots (.inr 0) := slots.injective.ne (by simp) + have hd : slots (.inr 1) ≠ slots (.inr 0) := slots.injective.ne (by decide) + let seeded := coefficientTapes slots base coefficient + have hseed : (MachineComposition.advance (TM2.step p))^[1] + (some ⟨some (labels .seed), ((ambient, ()), register), base⟩) = + some ⟨some (labels (.horner .start)), ((ambient, ()), register), seeded⟩ := by + change some (TM2.stepAux (p (labels .seed)) ((ambient, ()), register) base) = _ + rw [atLabels .seed] + simp only [statement, stepAux_pushWord, List.reverse_reverse, TM2.stepAux, + coefficientEmpty, List.append_nil, seeded, coefficientTapes] + have hradix : seeded (slots (.inl 0)) = encodeWord rank := by + simp [seeded, coefficientTapes, hc, rankWord] + have hdigits : ∀ i : Fin 2, seeded (slots (.inr i)) = encodeWord (digits coefficient offset i.val) := by + intro i + have hi : i = 0 ∨ i = 1 := by omega + rcases hi with rfl | rfl + · simp [seeded, coefficientTapes, digits] + · simp [seeded, coefficientTapes, digits, hd, offsetWord] + have hclean : MachineHorner.Clean slots seeded := { + accA := by simpa only [seeded, coefficientTapes, Function.update_of_ne (hc 1)] using clean.accA + accB := by simpa only [seeded, coefficientTapes, Function.update_of_ne (hc 2)] using clean.accB + counter := by simpa only [seeded, coefficientTapes, Function.update_of_ne (hc 4)] using clean.counter + scratch := by simpa only [seeded, coefficientTapes, Function.update_of_ne (hc 5)] using clean.scratch + } + have hhorner := MachineHorner.hornerTrace slots (fun l => labels (.horner l)) + (some (labels .clear)) p (fun l => atLabels (.horner l)) seeded rank + (digits coefficient offset) hradix hdigits hclean ambient register + rw [horner_value] at hhorner + let after := MachineHorner.resultTapes slots seeded (coefficient * rank + offset) + have hafter : after (slots (.inr 0)) = encodeWord coefficient := by + simp [after, MachineHorner.resultTapes, Ne.symm (hc 3), seeded, coefficientTapes] + have hstart : Function.update after (slots (.inr 0)) (encodeWord coefficient ++ []) = after := by + rw [List.append_nil, ← hafter, Function.update_eq_self] + have hfinish : Function.update after (slots (.inr 0)) [] = + MachineHorner.resultTapes slots base (coefficient * rank + offset) := by + funext k + by_cases ho : k = slots (.inl 3) + · subst k + simp [after, MachineHorner.resultTapes, seeded, coefficientTapes, hc 3] + · by_cases hk : k = slots (.inr 0) + · subst k + simp [MachineHorner.resultTapes, Ne.symm (hc 3), coefficientEmpty] + · simp [after, MachineHorner.resultTapes, seeded, coefficientTapes, ho, hk] + have hclear := MachineHorner.drainTrace (slots (.inr 0)) (labels .clear) exit p + (atLabels .clear) after coefficient [] ambient none + rw [hstart, hfinish] at hclear + rw [show steps coefficient rank offset = (coefficient + 1) + + (MachineHorner.steps rank (digits coefficient offset) 2 + 1) by unfold steps; omega, + Function.iterate_add_apply, Function.iterate_succ_apply] + change (MachineComposition.advance (TM2.step p))^[coefficient + 1] + ((MachineComposition.advance (TM2.step p))^[MachineHorner.steps rank (digits coefficient offset) 2] + ((MachineComposition.advance (TM2.step p))^[1] + (some ⟨some (labels .seed), ((ambient, ()), register), base⟩))) = _ + rw [hseed, hhorner] + exact hclear + +def affineInTime (slots : Layout ↪ K) (coefficient : Nat) (labels : Label → Λ) (exit : Option Λ) + (p : Λ → TM2.Stmt (fun _ : K => Bool) Λ (MachineHorner.State σ)) + (atLabels : ∀ label, p (labels label) = statement slots coefficient labels exit label) + (base : K → List Bool) (rank offset : Nat) + (rankWord : base (slots (.inl 0)) = encodeWord rank) + (offsetWord : base (slots (.inr 1)) = encodeWord offset) + (coefficientEmpty : base (slots (.inr 0)) = []) + (clean : MachineHorner.Clean slots base) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step p) + ⟨some (labels .seed), ((ambient, ()), register), base⟩ + (some ⟨exit, ((ambient, ()), none), MachineHorner.resultTapes slots base (coefficient * rank + offset)⟩) + (steps coefficient rank offset) where + steps := steps coefficient rank offset + evals_in_steps := affineTrace slots coefficient labels exit p atLabels base rank offset + rankWord offsetWord coefficientEmpty clean ambient register + steps_le_m := Nat.le_refl _ + +def affineInPolynomialTime (slots : Layout ↪ K) (coefficient : Nat) (labels : Label → Λ) (exit : Option Λ) + (p : Λ → TM2.Stmt (fun _ : K => Bool) Λ (MachineHorner.State σ)) + (atLabels : ∀ label, p (labels label) = statement slots coefficient labels exit label) + (base : K → List Bool) (rank offset : Nat) + (rankWord : base (slots (.inl 0)) = encodeWord rank) + (offsetWord : base (slots (.inr 1)) = encodeWord offset) + (coefficientEmpty : base (slots (.inr 0)) = []) + (clean : MachineHorner.Clean slots base) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step p) + ⟨some (labels .seed), ((ambient, ()), register), base⟩ + (some ⟨exit, ((ambient, ()), none), MachineHorner.resultTapes slots base (coefficient * rank + offset)⟩) + ((timePolynomial coefficient).eval (operandLength rank offset)) where + steps := steps coefficient rank offset + evals_in_steps := affineTrace slots coefficient labels exit p atLabels base rank offset + rankWord offsetWord coefficientEmpty clean ambient register + steps_le_m := steps_le_timePolynomial coefficient rank offset + +def programInTime (slots : Layout ↪ K) (coefficient : Nat) (base : K → List Bool) (rank offset : Nat) + (rankWord : base (slots (.inl 0)) = encodeWord rank) + (offsetWord : base (slots (.inr 1)) = encodeWord offset) + (coefficientEmpty : base (slots (.inr 0)) = []) + (clean : MachineHorner.Clean slots base) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step (program (σ := σ) slots coefficient)) + ⟨some .seed, ((ambient, ()), register), base⟩ + (some ⟨none, ((ambient, ()), none), MachineHorner.resultTapes slots base (coefficient * rank + offset)⟩) + ((timePolynomial coefficient).eval (operandLength rank offset)) := + affineInPolynomialTime slots coefficient id none (program slots coefficient) (fun _ => rfl) + base rank offset rankWord offsetWord coefficientEmpty clean ambient register + +def leftBaseInTime (F : Formula) (u : Nat) (c : ClauseContext F u) (v : VariableContext F u) + (slots : Layout ↪ K) (labels : Label → Λ) (exit : Option Λ) + (p : Λ → TM2.Stmt (fun _ : K => Bool) Λ (MachineHorner.State σ)) + (atLabels : ∀ label, p (labels label) = statement slots (2 ^ (2 ^ u)) labels exit label) + (base : K → List Bool) + (rankWord : base (slots (.inl 0)) = encodeWord (((variableEncoding F u).code v).val)) + (zeroWord : base (slots (.inr 1)) = encodeWord 0) + (coefficientEmpty : base (slots (.inr 0)) = []) + (clean : MachineHorner.Clean slots base) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step p) + ⟨some (labels .seed), ((ambient, ()), register), base⟩ + (some ⟨exit, ((ambient, ()), none), MachineHorner.resultTapes slots base (baseValue F u c v 0)⟩) + ((timePolynomial (2 ^ (2 ^ u))).eval (operandLength (((variableEncoding F u).code v).val) 0)) := by + have h := affineInPolynomialTime slots (2 ^ (2 ^ u)) labels exit p atLabels base + (((variableEncoding F u).code v).val) 0 rankWord zeroWord coefficientEmpty clean ambient register + have hv : 2 ^ (2 ^ u) * (((variableEncoding F u).code v).val) + 0 = baseValue F u c v 0 := by + simp [baseValue] + simpa only [hv] using h + +def rightBaseInTime (F : Formula) (u : Nat) (c : ClauseContext F u) (v : VariableContext F u) + (slots : Layout ↪ K) (labels : Label → Λ) (exit : Option Λ) + (p : Λ → TM2.Stmt (fun _ : K => Bool) Λ (MachineHorner.State σ)) + (atLabels : ∀ label, p (labels label) = statement slots (2 ^ (8 ^ u)) labels exit label) + (base : K → List Bool) + (rankWord : base (slots (.inl 0)) = encodeWord (((clauseEncoding F u).code c).val)) + (leftBlockWord : base (slots (.inr 1)) = encodeWord (2 ^ (2 ^ u) * F.«variables» ^ u)) + (coefficientEmpty : base (slots (.inr 0)) = []) + (clean : MachineHorner.Clean slots base) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step p) + ⟨some (labels .seed), ((ambient, ()), register), base⟩ + (some ⟨exit, ((ambient, ()), none), MachineHorner.resultTapes slots base (baseValue F u c v 1)⟩) + ((timePolynomial (2 ^ (8 ^ u))).eval + (operandLength (((clauseEncoding F u).code c).val) (2 ^ (2 ^ u) * F.«variables» ^ u))) := by + have h := affineInPolynomialTime slots (2 ^ (8 ^ u)) labels exit p atLabels base + (((clauseEncoding F u).code c).val) (2 ^ (2 ^ u) * F.«variables» ^ u) + rankWord leftBlockWord coefficientEmpty clean ambient register + have hv : 2 ^ (8 ^ u) * (((clauseEncoding F u).code c).val) + 2 ^ (2 ^ u) * F.«variables» ^ u = + baseValue F u c v 1 := by + simp [baseValue, Nat.mul_comm, Nat.add_comm] + simpa only [hv] using h + +theorem resultTapes_dummy (slots : Layout ↪ K) (base : K → List Bool) (value : Nat) + (dummy : K) (distinct : dummy ≠ slots (.inl 3)) : + MachineHorner.resultTapes slots base value dummy = base dummy := + MachineHorner.resultTapes_other slots base value dummy distinct + +def machine (coefficient : Nat) : FinTM2 where + K := Layout + k₀ := .inl 0 + k₁ := .inl 3 + Γ _ := Bool + Λ := Label + main := .seed + σ := MachineHorner.State Unit + initialState := (((), ()), none) + m := program (Function.Embedding.refl Layout) coefficient + +def machineInTime (coefficient rank offset : Nat) (base : Layout → List Bool) + (rankWord : base (.inl 0) = encodeWord rank) (offsetWord : base (.inr 1) = encodeWord offset) + (coefficientEmpty : base (.inr 0) = []) + (clean : MachineHorner.Clean (Function.Embedding.refl _) base) (register : Option Bool) : + StateTransition.EvalsToInTime (machine coefficient).step + ⟨some Label.seed, (((), ()), register), base⟩ + (some ⟨none, (((), ()), none), + MachineHorner.resultTapes (Function.Embedding.refl _) base (coefficient * rank + offset)⟩) + ((timePolynomial coefficient).eval (operandLength rank offset)) := + programInTime (Function.Embedding.refl _) coefficient base rank offset rankWord offsetWord + coefficientEmpty clean () register + +end MinUncutGames.Foundations.Hastad.SourceBasePhase + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/HeaderCounts.lean b/lean/OAI/Computability/MinUncut/PCP/HeaderCounts.lean new file mode 100644 index 0000000000000000000000000000000000000000..fd8523794e75f485fece1d54178640ab001fc5b4 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/HeaderCounts.lean @@ -0,0 +1,812 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.RuntimeModel + +namespace OAI + +section + +namespace MinUncutGames.Foundations.Hastad.SourceHeaderCounts + +open Turing Complexity +open MachineComposition + +noncomputable section + +namespace Eval + +open CookLevin.PolynomialMachine + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev Label (p : Polynomial Nat) := Unit ⊕ (MachineHorner.Label (width p) ⊕ Unit) + +def start (p : Polynomial Nat) : Label p := .inl () +def inner (p : Polynomial Nat) (l : MachineHorner.Label (width p)) : Label p := .inr (.inl l) +def finish (p : Polynomial Nat) : Label p := .inr (.inr ()) + +def word (p : Polynomial Nat) (slots : MachineHorner.Layout (width p) ↪ K) : K → List Bool := + Function.extend slots (fieldWord p) (fun _ => []) + +def indices (p : Polynomial Nat) (slots : MachineHorner.Layout (width p) ↪ K) : List K := + (fieldIndices p).map slots + +omit [DecidableEq K] in +theorem indices_nodup (p : Polynomial Nat) (slots : MachineHorner.Layout (width p) ↪ K) : + (indices p slots).Nodup := (fieldIndices_nodup p).map slots.injective + +omit [DecidableEq K] in +@[simp] theorem word_slot (p : Polynomial Nat) (slots : MachineHorner.Layout (width p) ↪ K) + (i : MachineHorner.Layout (width p)) : word p slots (slots i) = fieldWord p i := + slots.injective.extend_apply _ _ i + +omit [DecidableEq K] in +@[simp] theorem control_not_mem (p : Polynomial Nat) + (slots : MachineHorner.Layout (width p) ↪ K) (i : Fin 6) : + slots (.inl i) ∉ indices p slots := by + simp [indices, slots.injective.eq_iff] + +omit [DecidableEq K] in +@[simp] theorem digit_mem (p : Polynomial Nat) + (slots : MachineHorner.Layout (width p) ↪ K) (i : Fin (width p)) : + slots (.inr i) ∈ indices p slots := by + simp [indices, slots.injective.eq_iff] + +def prepared (p : Polynomial Nat) (slots : MachineHorner.Layout (width p) ↪ K) + (base : K → List Bool) : K → List Bool := + prependFieldsTapes (word p slots) (indices p slots) base + +@[simp] theorem prepared_control (p : Polynomial Nat) + (slots : MachineHorner.Layout (width p) ↪ K) (base : K → List Bool) (i : Fin 6) : + prepared p slots base (slots (.inl i)) = base (slots (.inl i)) := by + rw [prepared, prependFieldsTapes_apply _ _ (indices_nodup p slots)] + simp + +@[simp] theorem prepared_digit (p : Polynomial Nat) + (slots : MachineHorner.Layout (width p) ↪ K) (base : K → List Bool) + (i : Fin (width p)) (hi : base (slots (.inr i)) = []) : + prepared p slots base (slots (.inr i)) = encodeWord (digit p i.val) := by + rw [prepared, prependFieldsTapes_apply _ _ (indices_nodup p slots)] + simp [fieldWord, hi] + +theorem clear_result (p : Polynomial Nat) (slots : MachineHorner.Layout (width p) ↪ K) + (base : K → List Bool) (result : Nat) + (hcoeff : ∀ i : Fin (width p), base (slots (.inr i)) = []) : + clearFieldsTapes (fun k => (word p slots k).length) (indices p slots) + (MachineHorner.resultTapes slots (prepared p slots base) result) = + MachineHorner.resultTapes slots base result := by + funext k + rw [clearFieldsTapes_apply _ _ (indices_nodup p slots)] + by_cases h : k ∈ indices p slots + · obtain ⟨q, hq, rfl⟩ := List.mem_map.mp h + obtain ⟨i, hi, rfl⟩ := List.mem_map.mp hq + simp [MachineHorner.resultTapes, slots.injective.eq_iff, prepared_digit, + fieldWord, hcoeff] + · by_cases hd : k = slots (.inl 3) + · subst k + simp [MachineHorner.resultTapes] + · simp [h, MachineHorner.resultTapes, hd, prepared, + prependFieldsTapes_apply _ _ (indices_nodup p slots)] + +def statement (p : Polynomial Nat) (slots : MachineHorner.Layout (width p) ↪ K) + (labels : Label p → Λ) (exit : Option Λ) : + Label p → TM2.Stmt (fun _ : K => Bool) Λ (MachineHorner.State σ) + | .inl _ => prependFields (word p slots) (indices p slots) + (.goto fun _ => labels (inner p .start)) + | .inr (.inl l) => MachineHorner.statement slots (fun l => labels (inner p l)) + (some (labels (finish p))) l + | .inr (.inr _) => clearFields (fun k => (word p slots k).length) (indices p slots) + (Reduction.MachineTransfer.exitAt (slots (.inl 3)) exit) + +def steps (p : Polynomial Nat) (n : Nat) : Nat := + MachineHorner.steps n (digit p) (width p) + 2 + +theorem trace (p : Polynomial Nat) (slots : MachineHorner.Layout (width p) ↪ K) + (labels : Label p → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (MachineHorner.State σ)) + (atLabels : ∀ l, program (labels l) = statement p slots labels exit l) + (base : K → List Bool) (n : Nat) + (hinput : base (slots (.inl 0)) = encodeWord n) + (hcoeff : ∀ i : Fin (width p), base (slots (.inr i)) = []) + (clean : MachineHorner.Clean slots base) (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[steps p n] + (some ⟨some (labels (start p)), ((ambient, ()), register), base⟩) = + some ⟨exit, ((ambient, ()), none), MachineHorner.resultTapes slots base (p.eval n)⟩ := by + have hp : (advance (TM2.step program))^[1] + (some ⟨some (labels (start p)), ((ambient, ()), register), base⟩) = + some ⟨some (labels (inner p .start)), ((ambient, ()), register), prepared p slots base⟩ := by + change some (TM2.stepAux (program (labels (start p))) _ _) = _ + rw [atLabels] + change some (TM2.stepAux (prependFields _ _ _) _ _) = _ + rw [stepAux_prependFields] + rfl + have hh := MachineHorner.hornerTrace slots (fun l => labels (inner p l)) + (some (labels (finish p))) program (fun l => atLabels (inner p l)) + (prepared p slots base) n (digit p) (by simpa using hinput) + (fun i => prepared_digit p slots base i (hcoeff i)) + (by + constructor + · simpa using clean.accA + · simpa using clean.accB + · simpa using clean.counter + · simpa using clean.scratch) ambient register + rw [hornerValue_eq_eval] at hh + have hc : (advance (TM2.step program))^[1] + (some ⟨some (labels (finish p)), ((ambient, ()), none), + MachineHorner.resultTapes slots (prepared p slots base) (p.eval n)⟩) = + some ⟨exit, ((ambient, ()), none), MachineHorner.resultTapes slots base (p.eval n)⟩ := by + change some (TM2.stepAux (program (labels (finish p))) _ _) = _ + rw [atLabels] + change some (TM2.stepAux (clearFields _ _ _) _ _) = _ + rw [stepAux_clearFields, clear_result p slots base _ hcoeff] + cases exit <;> rfl + rw [show steps p n = 1 + (MachineHorner.steps n (digit p) (width p) + 1) by + unfold steps; omega, Function.iterate_add_apply, Function.iterate_add_apply, hp, hh, hc] + +def inTime (p : Polynomial Nat) (slots : MachineHorner.Layout (width p) ↪ K) + (labels : Label p → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (MachineHorner.State σ)) + (atLabels : ∀ l, program (labels l) = statement p slots labels exit l) + (base : K → List Bool) (n : Nat) + (hinput : base (slots (.inl 0)) = encodeWord n) + (hcoeff : ∀ i : Fin (width p), base (slots (.inr i)) = []) + (clean : MachineHorner.Clean slots base) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels (start p)), ((ambient, ()), register), base⟩ + (some ⟨exit, ((ambient, ()), none), MachineHorner.resultTapes slots base (p.eval n)⟩) + ((timePolynomial p).eval n) where + steps := steps p n + evals_in_steps := trace p slots labels exit program atLabels base n hinput hcoeff clean ambient register + steps_le_m := by rw [timePolynomial_eval]; unfold steps; omega + +end Eval + +def leftValue (u n : Nat) : Nat := 2 ^ (2 ^ u) * n ^ u +def rightValue (u m : Nat) : Nat := 2 ^ (8 ^ u) * m ^ u +def dummyValue (u n m : Nat) : Nat := leftValue u n + rightValue u m +def bitValue (u n m : Nat) : Nat := dummyValue u n m + 1 +def occurrenceValue (u D m : Nat) : Nat := + 3 ^ u * (SourceOccurrences.testTapeEncoding u D).size * m ^ u + +inductive Kind + | left | right | occurrences + deriving DecidableEq + +protected abbrev Kind.enumList : List Kind := [.left, .right, .occurrences] + +protected theorem Kind.enumList_getElem?_ctorIdx_eq (x : Kind) : + Kind.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem Kind.enumList_nodup : Kind.enumList.Nodup := by decide + +instance : Fintype Kind where + elems := ⟨Kind.enumList, Kind.enumList_nodup⟩ + complete x := by cases x <;> decide + +def polynomial (u D : Nat) : Kind → Polynomial Nat + | .left => Polynomial.C (2 ^ (2 ^ u)) * Polynomial.X ^ u + | .right => Polynomial.C (2 ^ (8 ^ u)) * Polynomial.X ^ u + | .occurrences => Polynomial.C (3 ^ u * (SourceOccurrences.testTapeEncoding u D).size) * + Polynomial.X ^ u + +@[simp] theorem polynomial_left_eval (u D n : Nat) : + (polynomial u D .left).eval n = leftValue u n := by simp [polynomial, leftValue] +@[simp] theorem polynomial_right_eval (u D m : Nat) : + (polynomial u D .right).eval m = rightValue u m := by simp [polynomial, rightValue] +@[simp] theorem polynomial_occurrences_eval (u D m : Nat) : + (polynomial u D .occurrences).eval m = occurrenceValue u D m := by + simp [polynomial, occurrenceValue] + +theorem bitValue_eq_nBits (F : Target.Formula) (u : Nat) : + bitValue u F.«variables» F.clauses.length = SourceOccurrences.nBits F u := by + rw [SourceOccurrences.nBits_eq] + simp [bitValue, dummyValue, leftValue, rightValue, Nat.mul_comm, Nat.add_assoc] + +theorem occurrenceValue_eq_length (F : Target.Formula) (u D : Nat) + (hm : 0 < F.clauses.length) : + occurrenceValue u D F.clauses.length = (SourceOccurrences.sourceList F u D).length := by + have hne : F.clauses ≠ [] := by intro h; simp [h] at hm + have hfalse : ¬ F.clauses.isEmpty = true := by simpa using hne + simp only [SourceOccurrences.sourceList, ite_eq_right hfalse] + rw [SourceOccurrences.rawSourceList_length] + unfold occurrenceValue + rw [SourceBounds.testTapeEncoding_size] + ac_rfl + +inductive Control + | variableCount | clauseCount | leftBlockSize | rightTemporary | dummyIndex + | bitCount | occurrenceCount | accA | accB | counter | scratch + deriving DecidableEq + +protected abbrev Control.enumList : List Control := [.variableCount, .clauseCount, .leftBlockSize, + .rightTemporary, .dummyIndex, .bitCount, .occurrenceCount, .accA, .accB, .counter, .scratch] + +protected theorem Control.enumList_getElem?_ctorIdx_eq (x : Control) : + Control.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem Control.enumList_nodup : Control.enumList.Nodup := by decide + +instance : Fintype Control where + elems := ⟨Control.enumList, Control.enumList_nodup⟩ + complete x := by cases x <;> decide + +abbrev Coefficients (u D : Nat) := + Fin (CookLevin.PolynomialMachine.width (polynomial u D .left)) ⊕ + (Fin (CookLevin.PolynomialMachine.width (polynomial u D .right)) ⊕ + Fin (CookLevin.PolynomialMachine.width (polynomial u D .occurrences))) + +abbrev Layout (u D : Nat) := Control ⊕ Coefficients u D + +def coefficientBlock (u D : Nat) (kind : Kind) : + Fin (CookLevin.PolynomialMachine.width (polynomial u D kind)) ↪ Coefficients u D := + match kind with + | .left => ⟨Sum.inl, Sum.inl_injective⟩ + | .right => ⟨fun i => .inr (.inl i), Sum.inr_injective.comp Sum.inl_injective⟩ + | .occurrences => ⟨fun i => .inr (.inr i), Sum.inr_injective.comp Sum.inr_injective⟩ + +def inputControl : Kind → Control + | .left => .variableCount | _ => .clauseCount + +def outputControl : Kind → Control + | .left => .leftBlockSize | .right => .rightTemporary | .occurrences => .occurrenceCount + +def controlSlots (kind : Kind) : Fin 6 ↪ Control where + toFun i := match i.val with + | 0 => inputControl kind | 1 => .accA | 2 => .accB + | 3 => outputControl kind | 4 => .counter | _ => .scratch + inj' := by + intro i j h + cases kind <;> fin_cases i <;> fin_cases j <;> cases h <;> rfl + +def localSlots (u D : Nat) (kind : Kind) : + MachineHorner.Layout (CookLevin.PolynomialMachine.width (polynomial u D kind)) ↪ Layout u D where + toFun + | .inl i => .inl (controlSlots kind i) + | .inr i => .inr (coefficientBlock u D kind i) + inj' := by + intro a b h + cases a with + | inl a => + cases b with + | inl b => exact congrArg Sum.inl ((controlSlots kind).injective (Sum.inl.inj h)) + | inr b => cases h + | inr a => + cases b with + | inl b => cases h + | inr b => exact congrArg Sum.inr ((coefficientBlock u D kind).injective (Sum.inr.inj h)) + +variable {u D : Nat} {K Λ σ : Type} + +def control (slots : Layout u D ↪ K) (c : Control) : K := slots (.inl c) + +def evalSlots (slots : Layout u D ↪ K) (kind : Kind) : + MachineHorner.Layout (CookLevin.PolynomialMachine.width (polynomial u D kind)) ↪ K := + (localSlots u D kind).trans slots + +@[simp] theorem evalSlots_radix (slots : Layout u D ↪ K) (kind : Kind) : + evalSlots slots kind (.inl 0) = control slots (inputControl kind) := rfl +@[simp] theorem evalSlots_accA (slots : Layout u D ↪ K) (kind : Kind) : + evalSlots slots kind (.inl 1) = control slots .accA := rfl +@[simp] theorem evalSlots_accB (slots : Layout u D ↪ K) (kind : Kind) : + evalSlots slots kind (.inl 2) = control slots .accB := rfl +@[simp] theorem evalSlots_destination (slots : Layout u D ↪ K) (kind : Kind) : + evalSlots slots kind (.inl 3) = control slots (outputControl kind) := rfl +@[simp] theorem evalSlots_counter (slots : Layout u D ↪ K) (kind : Kind) : + evalSlots slots kind (.inl 4) = control slots .counter := rfl +@[simp] theorem evalSlots_scratch (slots : Layout u D ↪ K) (kind : Kind) : + evalSlots slots kind (.inl 5) = control slots .scratch := rfl +@[simp] theorem evalSlots_digit (slots : Layout u D ↪ K) (kind : Kind) + (i : Fin (CookLevin.PolynomialMachine.width (polynomial u D kind))) : + evalSlots slots kind (.inr i) = slots (.inr (coefficientBlock u D kind i)) := rfl + +@[simp] theorem control_eq_iff (slots : Layout u D ↪ K) (a b : Control) : + control slots a = control slots b ↔ a = b := by + simp [control, slots.injective.eq_iff] + +structure Clean (slots : Layout u D ↪ K) (base : K → List Bool) : Prop where + left : base (control slots .leftBlockSize) = [] + right : base (control slots .rightTemporary) = [] + dummy : base (control slots .dummyIndex) = [] + bits : base (control slots .bitCount) = [] + occurrences : base (control slots .occurrenceCount) = [] + accA : base (control slots .accA) = [] + accB : base (control slots .accB) = [] + counter : base (control slots .counter) = [] + scratch : base (control slots .scratch) = [] + coefficients : ∀ i : Coefficients u D, base (slots (.inr i)) = [] + +inductive Label (u D : Nat) + | evaluate (kind : Kind) (localLabel : Eval.Label (polynomial u D kind)) + | copyLeftOut | copyLeftBack | addRight | clearTemporary + | copyDummyOut | copyDummyBack | incrementBits + deriving DecidableEq, Fintype + +def evalStart (kind : Kind) : Label u D := .evaluate kind (Eval.start (polynomial u D kind)) + +def afterEval : Kind → Label u D + | .left => evalStart .right | .right => evalStart .occurrences | .occurrences => .copyLeftOut + +variable [DecidableEq K] + +def statement (slots : Layout u D ↪ K) (labels : Label u D → Λ) (exit : Option Λ) : + Label u D → TM2.Stmt (fun _ : K => Bool) Λ (MachineHorner.State σ) + | .evaluate kind l => Eval.statement (polynomial u D kind) (evalSlots slots kind) + (fun l => labels (.evaluate kind l)) (some (labels (afterEval kind))) l + | .copyLeftOut => Reduction.MachineTransfer.loopAt (control slots .leftBlockSize) + (control slots .scratch) id false (labels .copyLeftOut) (some (labels .copyLeftBack)) + | .copyLeftBack => MachineCopy.forkLoop (control slots .scratch) + (control slots .leftBlockSize) (control slots .dummyIndex) false + (labels .copyLeftBack) (some (labels .addRight)) + | .addRight => MachineUnaryAddAt.loop (control slots .rightTemporary) + (control slots .dummyIndex) (labels .addRight) (some (labels .clearTemporary)) + | .clearTemporary => .pop (control slots .rightTemporary) (fun state _ => state) + (.goto fun _ => labels .copyDummyOut) + | .copyDummyOut => Reduction.MachineTransfer.loopAt (control slots .dummyIndex) + (control slots .scratch) id false (labels .copyDummyOut) (some (labels .copyDummyBack)) + | .copyDummyBack => MachineCopy.forkLoop (control slots .scratch) + (control slots .dummyIndex) (control slots .bitCount) false + (labels .copyDummyBack) (some (labels .incrementBits)) + | .incrementBits => .push (control slots .bitCount) (fun _ => true) + (Reduction.MachineTransfer.exitAt (control slots .bitCount) exit) + +def resultTapes (slots : Layout u D ↪ K) (base : K → List Bool) (n m : Nat) : K → List Bool := + Function.update (Function.update (Function.update (Function.update base + (control slots .leftBlockSize) (encodeWord (leftValue u n))) + (control slots .occurrenceCount) (encodeWord (occurrenceValue u D m))) + (control slots .dummyIndex) (encodeWord (dummyValue u n m))) + (control slots .bitCount) (encodeWord (bitValue u n m)) + +def steps (u D n m : Nat) : Nat := + Eval.steps (polynomial u D .left) n + Eval.steps (polynomial u D .right) m + + Eval.steps (polynomial u D .occurrences) m + + 2 * leftValue u n + rightValue u m + 2 * dummyValue u n m + 11 + +structure WorkClean (slots : Layout u D ↪ K) (base : K → List Bool) : Prop where + accA : base (control slots .accA) = [] + accB : base (control slots .accB) = [] + counter : base (control slots .counter) = [] + scratch : base (control slots .scratch) = [] + coefficients : ∀ i : Coefficients u D, base (slots (.inr i)) = [] + +omit [DecidableEq K] in +theorem Clean.work {slots : Layout u D ↪ K} {base : K → List Bool} (clean : Clean slots base) : + WorkClean slots base := + ⟨clean.accA, clean.accB, clean.counter, clean.scratch, clean.coefficients⟩ + +theorem WorkClean.update_output {slots : Layout u D ↪ K} {base : K → List Bool} + (clean : WorkClean slots base) (kind : Kind) (value : List Bool) : + WorkClean slots (Function.update base (control slots (outputControl kind)) value) := by + cases kind <;> constructor + all_goals try { simpa [outputControl] using clean.accA } + all_goals try { simpa [outputControl] using clean.accB } + all_goals try { simpa [outputControl] using clean.counter } + all_goals try { simpa [outputControl] using clean.scratch } + all_goals intro i; simpa [control, slots.injective.eq_iff] using clean.coefficients i + +theorem evalPhaseTrace (slots : Layout u D ↪ K) (labels : Label u D → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (MachineHorner.State σ)) + (atLabels : ∀ l, program (labels l) = statement slots labels exit l) + (kind : Kind) (base : K → List Bool) (n : Nat) + (hinput : base (control slots (inputControl kind)) = encodeWord n) + (hdest : base (control slots (outputControl kind)) = []) + (clean : WorkClean slots base) (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[Eval.steps (polynomial u D kind) n] + (some ⟨some (labels (evalStart kind)), ((ambient, ()), register), base⟩) = + some ⟨some (labels (afterEval kind)), ((ambient, ()), none), + Function.update base (control slots (outputControl kind)) + (encodeWord ((polynomial u D kind).eval n))⟩ := by + have h := Eval.trace (polynomial u D kind) (evalSlots slots kind) + (fun l => labels (.evaluate kind l)) (some (labels (afterEval kind))) program + (fun l => atLabels (.evaluate kind l)) base n (by simpa using hinput) + (fun i => by simpa using clean.coefficients (coefficientBlock u D kind i)) + ⟨by simpa using clean.accA, by simpa using clean.accB, + by simpa using clean.counter, by simpa using clean.scratch⟩ ambient register + simpa only [evalStart, MachineHorner.resultTapes, evalSlots_destination, + hdest, List.append_nil] using h + +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 trace (slots : Layout u D ↪ K) (labels : Label u D → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (MachineHorner.State σ)) + (atLabels : ∀ l, program (labels l) = statement slots labels exit l) + (base : K → List Bool) (n m : Nat) + (hn : base (control slots .variableCount) = encodeWord n) + (hm : base (control slots .clauseCount) = encodeWord m) + (clean : Clean slots base) (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[steps u D n m] + (some ⟨some (labels (evalStart .left)), ((ambient, ()), register), base⟩) = + some ⟨exit, ((ambient, ()), none), resultTapes slots base n m⟩ := by + let t1 := Function.update base (control slots .leftBlockSize) (encodeWord (leftValue u n)) + let t2 := Function.update t1 (control slots .rightTemporary) (encodeWord (rightValue u m)) + let t3 := Function.update t2 (control slots .occurrenceCount) (encodeWord (occurrenceValue u D m)) + let t4 := Function.update t3 (control slots .dummyIndex) (encodeWord (leftValue u n)) + let t5 := Function.update (Function.update t4 (control slots .rightTemporary) [false]) + (control slots .dummyIndex) (encodeWord (dummyValue u n m)) + let t6 := Function.update t5 (control slots .rightTemporary) [] + let t7 := Function.update t6 (control slots .bitCount) (encodeWord (dummyValue u n m)) + have h1 := evalPhaseTrace slots labels exit program atLabels .left base n hn clean.left + clean.work ambient register + change (advance (TM2.step program))^[Eval.steps (polynomial u D .left) n] + (some ⟨some (labels (evalStart .left)), ((ambient, ()), register), base⟩) = + some ⟨some (labels (evalStart .right)), ((ambient, ()), none), _⟩ at h1 + simp only [polynomial_left_eval] at h1 + have cw1 : WorkClean slots t1 := clean.work.update_output .left _ + have h2 := evalPhaseTrace slots labels exit program atLabels .right t1 m + (by simpa [t1, inputControl] using hm) + (by simpa [t1, outputControl] using clean.right) cw1 ambient none + change (advance (TM2.step program))^[Eval.steps (polynomial u D .right) m] + (some ⟨some (labels (evalStart .right)), ((ambient, ()), none), t1⟩) = + some ⟨some (labels (evalStart .occurrences)), ((ambient, ()), none), _⟩ at h2 + simp only [polynomial_right_eval] at h2 + have cw2 : WorkClean slots t2 := cw1.update_output .right _ + have h3 := evalPhaseTrace slots labels exit program atLabels .occurrences t2 m + (by simpa [t2, t1, inputControl] using hm) + (by simpa [t2, t1, outputControl] using clean.occurrences) cw2 ambient none + change (advance (TM2.step program))^[Eval.steps (polynomial u D .occurrences) m] + (some ⟨some (labels (evalStart .occurrences)), ((ambient, ()), none), t2⟩) = + some ⟨some (labels .copyLeftOut), ((ambient, ()), none), _⟩ at h3 + simp only [polynomial_occurrences_eval] at h3 + have cw3 : WorkClean slots t3 := cw2.update_output .occurrences _ + have copyingLeft := MachineCopy.copyTrace (control slots .leftBlockSize) + (control slots .dummyIndex) (control slots .scratch) + (by simp) (by simp) (by simp) false (labels .copyLeftOut) (labels .copyLeftBack) + (some (labels .addRight)) program (atLabels .copyLeftOut) (atLabels .copyLeftBack) + t3 cw3.scratch (ambient, ()) none + have hleft : t3 (control slots .leftBlockSize) = encodeWord (leftValue u n) := by + simp [t3, t2, t1] + have hdummy : t3 (control slots .dummyIndex) = [] := by + simpa [t3, t2, t1] using clean.dummy + rw [hleft, hdummy, List.append_nil, encodeWord_length] at copyingLeft + have adding := MachineUnaryAddAt.addFromTapes (control slots .rightTemporary) + (control slots .dummyIndex) (by simp) (labels .addRight) (some (labels .clearTemporary)) + program (atLabels .addRight) t4 (rightValue u m) (leftValue u n) [] [] + (by simp [t4, t3, t2]) (by simp [t4]) (ambient, ()) none + have ha : MachineUnaryAddAt.unaryTapes (control slots .rightTemporary) + (control slots .dummyIndex) t4 0 (rightValue u m + leftValue u n) [] [] = t5 := by + simp [MachineUnaryAddAt.unaryTapes, Reduction.MachineTransfer.tapesAt, t5, + encodeWord, dummyValue, Nat.add_comm] + rw [ha] at adding + have clearing : (advance (TM2.step program))^[1] + (some ⟨some (labels .clearTemporary), ((ambient, ()), none), t5⟩) = + some ⟨some (labels .copyDummyOut), ((ambient, ()), none), t6⟩ := by + change some (TM2.stepAux (program (labels .clearTemporary)) _ _) = _ + rw [atLabels] + simp [statement, TM2.stepAux, t6, t5] + have copyingDummy := MachineCopy.copyTrace (control slots .dummyIndex) + (control slots .bitCount) (control slots .scratch) + (by simp) (by simp) (by simp) false (labels .copyDummyOut) (labels .copyDummyBack) + (some (labels .incrementBits)) program (atLabels .copyDummyOut) (atLabels .copyDummyBack) + t6 (by simpa [t6, t5, t4] using cw3.scratch) (ambient, ()) none + have hdi : t6 (control slots .dummyIndex) = encodeWord (dummyValue u n m) := by + simp [t6, t5] + have hbi : t6 (control slots .bitCount) = [] := by + simpa [t6, t5, t4, t3, t2, t1] using clean.bits + rw [hdi, hbi, List.append_nil, encodeWord_length] at copyingDummy + have increment : (advance (TM2.step program))^[1] + (some ⟨some (labels .incrementBits), ((ambient, ()), none), t7⟩) = + some ⟨exit, ((ambient, ()), none), + Function.update t7 (control slots .bitCount) (encodeWord (bitValue u n m))⟩ := by + change some (TM2.stepAux (program (labels .incrementBits)) _ _) = _ + rw [atLabels] + cases exit <;> simp [statement, TM2.stepAux, Reduction.MachineTransfer.exitAt, + t7, bitValue, encodeWord, List.replicate_succ] + have total := trace_trans _ (trace_trans _ (trace_trans _ (trace_trans _ + (trace_trans _ (trace_trans _ (trace_trans _ h1 h2) h3) copyingLeft) adding) clearing) + copyingDummy) increment + have htime : + Eval.steps (polynomial u D .left) n + Eval.steps (polynomial u D .right) m + + Eval.steps (polynomial u D .occurrences) m + 2 * (leftValue u n + 1 + 1) + + (rightValue u m + 1) + 1 + 2 * (dummyValue u n m + 1 + 1) + 1 = + steps u D n m := by unfold steps; omega + rw [htime] at total + have frame : Function.update t7 (control slots .bitCount) (encodeWord (bitValue u n m)) = + resultTapes slots base n m := by + funext k + by_cases hr : k = control slots .rightTemporary + · subst k + simp [t7, t6, t5, t4, t3, t2, t1, resultTapes, clean.right] + · simp [t7, t6, t5, t4, t3, t2, t1, resultTapes, Function.update_apply, hr] + split_ifs <;> rfl + rw [frame] at total + exact total + +def timePolynomial (u D : Nat) : Polynomial Nat := + CookLevin.PolynomialMachine.timePolynomial (polynomial u D .left) + + CookLevin.PolynomialMachine.timePolynomial (polynomial u D .right) + + CookLevin.PolynomialMachine.timePolynomial (polynomial u D .occurrences) + + Polynomial.C 2 * polynomial u D .left + polynomial u D .right + + Polynomial.C 2 * (polynomial u D .left + polynomial u D .right) + Polynomial.C 11 + +theorem steps_le_timePolynomial (u D n m L : Nat) (hn : n ≤ L) (hm : m ≤ L) : + steps u D n m ≤ (timePolynomial u D).eval L := by + have hEval (p : Polynomial Nat) (a : Nat) (ha : a ≤ L) : + Eval.steps p a ≤ (CookLevin.PolynomialMachine.timePolynomial p).eval L := by + apply Nat.le_trans (m := (CookLevin.PolynomialMachine.timePolynomial p).eval a) + · rw [CookLevin.PolynomialMachine.timePolynomial_eval] + unfold Eval.steps + omega + · exact natPolynomial_eval_mono _ ha + have h1 := hEval (polynomial u D .left) n hn + have h2 := hEval (polynomial u D .right) m hm + have h3 := hEval (polynomial u D .occurrences) m hm + have hl : leftValue u n ≤ leftValue u L := + Nat.mul_le_mul_left _ (Nat.pow_le_pow_left hn u) + have hr : rightValue u m ≤ rightValue u L := + Nat.mul_le_mul_left _ (Nat.pow_le_pow_left hm u) + simp only [timePolynomial, Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_C, + polynomial_left_eval, polynomial_right_eval] + unfold steps dummyValue + omega + +def inTime (slots : Layout u D ↪ K) (labels : Label u D → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (MachineHorner.State σ)) + (atLabels : ∀ l, program (labels l) = statement slots labels exit l) + (base : K → List Bool) (n m : Nat) + (hn : base (control slots .variableCount) = encodeWord n) + (hm : base (control slots .clauseCount) = encodeWord m) + (clean : Clean slots base) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels (evalStart .left)), ((ambient, ()), register), base⟩ + (some ⟨exit, ((ambient, ()), none), resultTapes slots base n m⟩) + (steps u D n m) where + steps := steps u D n m + evals_in_steps := trace slots labels exit program atLabels base n m hn hm clean ambient register + steps_le_m := Nat.le_refl _ + +def inPolynomialTime (slots : Layout u D ↪ K) (labels : Label u D → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (MachineHorner.State σ)) + (atLabels : ∀ l, program (labels l) = statement slots labels exit l) + (base : K → List Bool) (n m L : Nat) + (hn : base (control slots .variableCount) = encodeWord n) + (hm : base (control slots .clauseCount) = encodeWord m) + (clean : Clean slots base) (hnL : n ≤ L) (hmL : m ≤ L) + (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels (evalStart .left)), ((ambient, ()), register), base⟩ + (some ⟨exit, ((ambient, ()), none), resultTapes slots base n m⟩) + ((timePolynomial u D).eval L) where + steps := steps u D n m + evals_in_steps := trace slots labels exit program atLabels base n m hn hm clean ambient register + steps_le_m := steps_le_timePolynomial u D n m L hnL hmL + +def formulaInTime (slots : Layout u D ↪ K) (labels : Label u D → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (MachineHorner.State σ)) + (atLabels : ∀ l, program (labels l) = statement slots labels exit l) + (base : K → List Bool) (F : Target.Formula) + (hn : base (control slots .variableCount) = encodeWord F.«variables») + (hm : base (control slots .clauseCount) = encodeWord F.clauses.length) + (clean : Clean slots base) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels (evalStart .left)), ((ambient, ()), register), base⟩ + (some ⟨exit, ((ambient, ()), none), resultTapes slots base F.«variables» F.clauses.length⟩) + ((timePolynomial u D).eval (formulaBits F).length) := + inPolynomialTime slots labels exit program atLabels base F.«variables» F.clauses.length + (formulaBits F).length hn hm clean (SourceBounds.formulaBits_length_ge_variables F) + (SourceBounds.formulaBits_length_ge_clauses F) ambient register + +theorem result_frame (slots : Layout u D ↪ K) (base : K → List Bool) (n m : Nat) (k : K) + (hl : k ≠ control slots .leftBlockSize) (ho : k ≠ control slots .occurrenceCount) + (hd : k ≠ control slots .dummyIndex) (hb : k ≠ control slots .bitCount) : + resultTapes slots base n m k = base k := by + simp [resultTapes, hl, ho, hd, hb] + +@[simp] theorem result_left (slots : Layout u D ↪ K) (base : K → List Bool) (n m : Nat) : + resultTapes slots base n m (control slots .leftBlockSize) = encodeWord (leftValue u n) := by + simp [resultTapes] +@[simp] theorem result_occurrences (slots : Layout u D ↪ K) (base : K → List Bool) (n m : Nat) : + resultTapes slots base n m (control slots .occurrenceCount) = encodeWord (occurrenceValue u D m) := by + simp [resultTapes] +@[simp] theorem result_dummy (slots : Layout u D ↪ K) (base : K → List Bool) (n m : Nat) : + resultTapes slots base n m (control slots .dummyIndex) = encodeWord (dummyValue u n m) := by + simp [resultTapes] +@[simp] theorem result_bits (slots : Layout u D ↪ K) (base : K → List Bool) (n m : Nat) : + resultTapes slots base n m (control slots .bitCount) = encodeWord (bitValue u n m) := by + simp [resultTapes] +@[simp] theorem result_variableCount (slots : Layout u D ↪ K) (base : K → List Bool) (n m : Nat) : + resultTapes slots base n m (control slots .variableCount) = base (control slots .variableCount) := by + simp [resultTapes] +@[simp] theorem result_clauseCount (slots : Layout u D ↪ K) (base : K → List Bool) (n m : Nat) : + resultTapes slots base n m (control slots .clauseCount) = base (control slots .clauseCount) := by + simp [resultTapes] + +theorem result_source_headers (slots : Layout u D ↪ K) (base : K → List Bool) + (F : Target.Formula) (hm : 0 < F.clauses.length) : + resultTapes slots base F.«variables» F.clauses.length (control slots .bitCount) = + encodeWord (SourceOccurrences.nBits F u) ∧ + resultTapes slots base F.«variables» F.clauses.length (control slots .occurrenceCount) = + encodeWord (SourceOccurrences.sourceList F u D).length := by + simp only [result_bits, result_occurrences, bitValue_eq_nBits, + occurrenceValue_eq_length F u D hm, and_self] + +def program (slots : Layout u D ↪ K) : Label u D → + TM2.Stmt (fun _ : K => Bool) (Label u D) (MachineHorner.State σ) := + statement slots id none + +def machine (u D : Nat) : FinTM2 where + K := Layout u D + k₀ := .inl .variableCount + k₁ := .inl .bitCount + Γ _ := Bool + Λ := Label u D + main := evalStart .left + σ := MachineHorner.State Unit + initialState := (((), ()), none) + m := program (Function.Embedding.refl _) + +def afterInitializationInTime {Extra : Type} [DecidableEq Extra] + (slots : Layout u D ↪ SourceLoopInit.Tape u Extra) + (hnslot : control slots .variableCount = SourceLoopInit.variableHeader) + (hmslot : control slots .clauseCount = SourceLoopInit.clauseHeader) + (labels : Label u D → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : SourceLoopInit.Tape u Extra => Bool) Λ + (MachineHorner.State σ)) + (atLabels : ∀ l, program (labels l) = statement slots labels exit l) + (base : SourceLoopInit.Tape u Extra → List Bool) (F : Target.Formula) + (hn : base SourceLoopInit.variableHeader = []) + (hm : base SourceLoopInit.clauseHeader = []) + (clean : Clean slots (SourceLoopInit.outputTapes F base)) + (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels (evalStart .left)), ((ambient, ()), register), + SourceLoopInit.outputTapes F base⟩ + (some ⟨exit, ((ambient, ()), none), + resultTapes slots (SourceLoopInit.outputTapes F base) F.«variables» F.clauses.length⟩) + ((timePolynomial u D).eval (formulaBits F).length) := + formulaInTime slots labels exit program atLabels (SourceLoopInit.outputTapes F base) F + (by rw [hnslot, SourceLoopInit.output_variableHeader, hn, List.append_nil]) + (by rw [hmslot, SourceLoopInit.output_clauseHeader, hm, List.append_nil]) + clean ambient register + +end + +end MinUncutGames.Foundations.Hastad.SourceHeaderCounts + +end +section +namespace MinUncutGames.Foundations.Hastad.SourceGeneratorModel + +open Turing Complexity SourceRuntimeModel + +abbrev Extra (u D : Nat) := SourceHeaderCounts.Coefficients u D ⊕ Unit +abbrev Tape (u D : Nat) := SourceRuntimeModel.Arena u (Extra u D) +abbrev State (u D : Nat) := SourceRuntimeModel.State u D + +def outputTape (u D : Nat) : Tape u D := workTape (.extra (.inr ())) +def accumulatorTape (u D : Nat) : Tape u D := workTape .accumulator + +def headerControl (u D : Nat) : SourceHeaderCounts.Control ↪ Tape u D where + toFun + | .variableCount => variableHeader + | .clauseCount => clauseHeader + | .leftBlockSize => workTape .leftBlock + | .rightTemporary => workTape .rank + | .dummyIndex => workTape .dummy + | .bitCount => workTape .bitCount + | .occurrenceCount => workTape .occurrenceCount + | .accA => workTape .accA + | .accB => workTape .accB + | .counter => workTape .counter + | .scratch => workTape .arithScratch + inj' := by + intro a b h + cases a <;> cases b <;> simp_all [variableHeader, clauseHeader, + SourceLoopInit.variableHeader, SourceLoopInit.clauseHeader, workTape] + +def headerSlots (u D : Nat) : SourceHeaderCounts.Layout u D ↪ Tape u D where + toFun + | .inl c => headerControl u D c + | .inr i => workTape (.extra (.inl i)) + inj' := by + intro a b h + cases a with + | inl a => + cases b with + | inl b => exact congrArg Sum.inl ((headerControl u D).injective h) + | inr b => cases a <;> cases h + | inr a => + cases b with + | inl b => cases b <;> cases h + | inr b => simpa [workTape] using h + +abbrev ControlAmbient (u D : Nat) := (Unit × Unit) × ArithmeticMetadata u D + +def controlStateEquiv (u D : Nat) : + ControlAmbient u D × Option Bool ≃ State u D where + toFun x := arithmeticStateEquiv u D ((x.1.1, x.2), x.1.2) + invFun x := + let y := (arithmeticStateEquiv u D).symm x + ((y.1.1, y.2), y.1.2) + left_inv _ := rfl + right_inv _ := rfl + +def initialQuery (u D : Nat) (hD : 0 < D) : SourceQueryLoop.Query u D := + (fun _ => false, fun _ => ⟨0, hD⟩, fun _ => false) + +def initialState (u D : Nat) (hD : 0 < D) : State u D := + canonicalState (initialQuery u D hD) + +def initialAmbient (u D : Nat) (hD : 0 < D) : ControlAmbient u D := + ((controlStateEquiv u D).symm (initialState u D hD)).1 + +theorem control_initial (u D : Nat) (hD : 0 < D) : + controlStateEquiv u D (initialAmbient u D hD, none) = initialState u D hD := rfl + +noncomputable def coefficientKeys (u D : Nat) : List (SourceHeaderCounts.Coefficients u D) := + (List.finRange (CookLevin.PolynomialMachine.width + (SourceHeaderCounts.polynomial u D .left))).map Sum.inl ++ + (List.finRange (CookLevin.PolynomialMachine.width + (SourceHeaderCounts.polynomial u D .right))).map (fun i => Sum.inr (Sum.inl i)) ++ + (List.finRange (CookLevin.PolynomialMachine.width + (SourceHeaderCounts.polynomial u D .occurrences))).map (fun i => Sum.inr (Sum.inr i)) + +theorem mem_coefficientKeys (u D : Nat) (i : SourceHeaderCounts.Coefficients u D) : + i ∈ coefficientKeys u D := by + cases i with + | inl i => simp [coefficientKeys] + | inr i => cases i <;> simp [coefficientKeys] + +noncomputable def workKeys (u D : Nat) : List (BodyWork (Extra u D)) := + [.leftBlock, .dummy, .bitCount, .occurrenceCount, .zero, .rank, .rightBase, .leftBase, + .accA, .accB, .counter, .arithScratch, .coefficient, .queryTemporary, + .queryScratch, .accumulator] ++ + (coefficientKeys u D).map (fun i => .extra (.inl i)) ++ [.extra (.inr ())] + +theorem mem_workKeys (u D : Nat) (i : BodyWork (Extra u D)) : i ∈ workKeys u D := by + cases i + case extra e => + cases e with + | inl i => + exact List.mem_append_left _ (List.mem_append_right _ + (List.mem_map.mpr ⟨i, mem_coefficientKeys u D i, rfl⟩)) + | inr i => cases i; simp [workKeys] + all_goals simp [workKeys] + +noncomputable def allTapes (u D : Nat) : List (Tape u D) := + [.formula, .index, .work, .scratch, .copyScratch] ++ + (List.finRange u).map SourceContextLoad.Tape.current ++ + (List.finRange u).map SourceContextLoad.Tape.remaining ++ + (List.finRange u).flatMap (fun i => + (List.finRange 6).map (SourceContextLoad.Tape.field i)) ++ + [variableHeader, clauseHeader] ++ (workKeys u D).map workTape + +theorem mem_allTapes (u D : Nat) (k : Tape u D) : k ∈ allTapes u D := by + cases k with + | formula => simp [allTapes] + | index => simp [allTapes] + | work => simp [allTapes] + | scratch => simp [allTapes] + | copyScratch => simp [allTapes] + | current i => simp [allTapes] + | remaining i => simp [allTapes] + | field i j => simp [allTapes] + | extra e => + cases e with + | inl h => cases h <;> simp [allTapes, variableHeader, clauseHeader, + SourceLoopInit.variableHeader, SourceLoopInit.clauseHeader] + | inr w => + have h : workTape (u := u) w ∈ (workKeys u D).map (workTape (u := u)) := + List.mem_map.mpr ⟨w, mem_workKeys u D w, rfl⟩ + simp only [allTapes, List.mem_append] + tauto + +noncomputable def clearKeys (u D : Nat) : List (Tape u D) := by + classical + exact (allTapes u D).filter + (fun k => decide (k ≠ accumulatorTape u D ∧ k ≠ outputTape u D)) + +theorem mem_clearKeys (u D : Nat) (k : Tape u D) : + k ∈ clearKeys u D ↔ k ≠ accumulatorTape u D ∧ k ≠ outputTape u D := by + classical + simp [clearKeys, mem_allTapes] + +theorem accumulator_ne_output (u D : Nat) : accumulatorTape u D ≠ outputTape u D := by + simp [accumulatorTape, outputTape, workTape] + +end MinUncutGames.Foundations.Hastad.SourceGeneratorModel + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/HonestTest.lean b/lean/OAI/Computability/MinUncut/PCP/HonestTest.lean new file mode 100644 index 0000000000000000000000000000000000000000..4db11506b66f2d9715dd3a2a233d528ff4d71df6 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/HonestTest.lean @@ -0,0 +1,371 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.Folding +import OAI.Computability.MinUncut.Games.FiniteNoise + +namespace OAI + +noncomputable section + +namespace MinUncutGames.Foundations.Hastad + +open scoped BigOperators +open MinUncutGames.Reduction.FiniteNoise + +variable {I J : Type*} [Fintype I] [DecidableEq I] [Fintype J] [DecidableEq J] + +omit [Fintype I] [DecidableEq I] [Fintype J] [DecidableEq J] in + +theorem dictator_test_parity (π : J → I) (i : I) (j : J) (hπ : π j = i) + (f : Cube I) (g μ : Cube J) : + (f i ^^ g j ^^ (thirdQuery π f g μ) j) = μ j := by + simp only [thirdQuery, cubeXor, hπ] + cases f i <;> cases g j <;> cases μ j <;> rfl + +theorem noise_coordinate_sign (ε : ℝ) (j : J) : + (∑ μ : Cube J, noiseWeight ε μ * bitSign (μ j)) = 1 - 2 * ε := by + have hs : support (coordinateMask j) = {j} := by + ext k + simp [support, coordinateMask] + have h := noise_walsh ε (coordinateMask j) + simp_rw [walsh_symm (coordinateMask j), walsh_coordinateMask] at h + simpa only [hs, Finset.card_singleton, pow_one] using h + +theorem noise_coordinate_false (ε : ℝ) (j : J) : + (∑ μ : Cube J, noiseWeight ε μ * if μ j then (0 : ℝ) else 1) = 1 - ε := by + have hind (b : Bool) : (if b then (0 : ℝ) else 1) = + (1 + bitSign b) * (2 : ℝ)⁻¹ := by + cases b <;> norm_num [bitSign] + have ht (μ : Cube J) : noiseWeight ε μ * (if μ j then (0 : ℝ) else 1) = + (noiseWeight ε μ + noiseWeight ε μ * bitSign (μ j)) * (2 : ℝ)⁻¹ := by + rw [hind] + ring + simp_rw [ht] + rw [← Finset.sum_mul, Finset.sum_add_distrib, noiseWeight_sum, noise_coordinate_sign] + ring + +theorem testAcceptance_dictator (ε : ℝ) (π : J → I) + (i : I) (j : J) (hπ : π j = i) : + testAcceptance ε π (fun f => f i) (fun g => g j) = 1 - ε := by + have hg (f : Cube I) (μ : Cube J) : + (𝔼 g : Cube J, if f i ^^ g j ^^ (thirdQuery π f g μ) j then (0 : ℝ) else 1) = + if μ j then 0 else 1 := by + calc + _ = 𝔼 _g : Cube J, if μ j then (0 : ℝ) else 1 := by + apply Finset.expect_congr rfl + intro g _ + rw [dictator_test_parity π i j hπ f g μ] + _ = _ := Fintype.expect_const _ + change (𝔼 f : Cube I, ∑ μ : Cube J, noiseWeight ε μ * + (𝔼 g : Cube J, if f i ^^ g j ^^ (thirdQuery π f g μ) j then (0 : ℝ) else 1)) = _ + simp_rw [hg] + rw [Fintype.expect_const] + exact noise_coordinate_false ε j + +theorem testAcceptance_folded_dictators (ε : ℝ) (π : J → I) + (i₀ i : I) (j₀ j : J) (hπ : π j = i) : + testAcceptance ε π (foldedAnswer i₀ (fun h => h.val i)) + (foldedAnswer j₀ (fun h => h.val j)) = 1 - ε := by + have hA : foldedAnswer i₀ (fun h => h.val i) = (fun f : Cube I => f i) := + funext (foldedAnswer_dictator i₀ i) + have hB : foldedAnswer j₀ (fun h => h.val j) = (fun g : Cube J => g j) := + funext (foldedAnswer_dictator j₀ j) + rw [hA, hB] + exact testAcceptance_dictator ε π i j hπ + +theorem testAcceptance_conditioned_dictators (ε : ℝ) (π : J → I) + (validI : I → Bool) (validJ : J → Bool) + (i₀ i : {i : I // validI i = true}) (j₀ j : {j : J // validJ j = true}) + (hπ : π j.val = i.val) : + testAcceptance ε π + (conditionedFoldedAnswer validI i₀ (fun h => h.val i)) + (conditionedFoldedAnswer validJ j₀ (fun h => h.val j)) = 1 - ε := by + have hA : conditionedFoldedAnswer validI i₀ (fun h => h.val i) = + (fun f : Cube I => f i.val) := + funext (conditionedFoldedAnswer_dictator validI i₀ i) + have hB : conditionedFoldedAnswer validJ j₀ (fun h => h.val j) = + (fun g : Cube J => g j.val) := + funext (conditionedFoldedAnswer_dictator validJ j₀ j) + rw [hA, hB] + exact testAcceptance_dictator ε π i.val j.val hπ + +theorem testAcceptance_folded_conditioned_dictators (ε : ℝ) (π : J → I) + (i₀ i : I) (valid : J → Bool) + (j₀ j : {j : J // valid j = true}) (hπ : π j.val = i) : + testAcceptance ε π (foldedAnswer i₀ (fun h => h.val i)) + (conditionedFoldedAnswer valid j₀ (fun h => h.val j)) = 1 - ε := by + have hA : foldedAnswer i₀ (fun h => h.val i) = (fun f : Cube I => f i) := + funext (foldedAnswer_dictator i₀ i) + have hB : conditionedFoldedAnswer valid j₀ (fun h => h.val j) = + (fun g : Cube J => g j.val) := + funext (conditionedFoldedAnswer_dictator valid j₀ j) + rw [hA, hB] + exact testAcceptance_dictator ε π i j.val hπ + +def realizedTestAcceptance (D : Nat) (π : J → I) + (A : Cube I → Bool) (B : Cube J → Bool) : ℝ := + 𝔼 f : Cube I, 𝔼 z : J → Fin D, 𝔼 g : Cube J, + if A f ^^ B g ^^ B (thirdQuery π f g (realizedNoise z)) then 0 else 1 + +theorem realizedTestAcceptance_eq_testAcceptance {D : Nat} (positive : 0 < D) + (π : J → I) (A : Cube I → Bool) (B : Cube J → Bool) : + realizedTestAcceptance D π A B = testAcceptance ((D : ℝ)⁻¹) π A B := by + unfold realizedTestAcceptance testAcceptance + apply Finset.expect_congr rfl + intro f _ + exact expect_realizedNoise positive + (fun μ => 𝔼 g : Cube J, if A f ^^ B g ^^ B (thirdQuery π f g μ) then 0 else 1) + +theorem realizedTestAcceptance_dictator {D : Nat} (positive : 0 < D) + (π : J → I) (i : I) (j : J) (hπ : π j = i) : + realizedTestAcceptance D π (fun f => f i) (fun g => g j) = 1 - (D : ℝ)⁻¹ := by + rw [realizedTestAcceptance_eq_testAcceptance positive] + exact testAcceptance_dictator _ π i j hπ + +theorem realizedTestAcceptance_folded_dictators {D : Nat} (positive : 0 < D) + (π : J → I) (i₀ i : I) (j₀ j : J) (hπ : π j = i) : + realizedTestAcceptance D π (foldedAnswer i₀ (fun h => h.val i)) + (foldedAnswer j₀ (fun h => h.val j)) = 1 - (D : ℝ)⁻¹ := by + rw [realizedTestAcceptance_eq_testAcceptance positive] + exact testAcceptance_folded_dictators _ π i₀ i j₀ j hπ + +theorem realizedTestAcceptance_conditioned_dictators {D : Nat} (positive : 0 < D) + (π : J → I) (validI : I → Bool) (validJ : J → Bool) + (i₀ i : {i : I // validI i = true}) (j₀ j : {j : J // validJ j = true}) + (hπ : π j.val = i.val) : + realizedTestAcceptance D π + (conditionedFoldedAnswer validI i₀ (fun h => h.val i)) + (conditionedFoldedAnswer validJ j₀ (fun h => h.val j)) = 1 - (D : ℝ)⁻¹ := by + rw [realizedTestAcceptance_eq_testAcceptance positive] + exact testAcceptance_conditioned_dictators _ π validI validJ i₀ i j₀ j hπ + +theorem realizedTestAcceptance_folded_conditioned_dictators {D : Nat} (positive : 0 < D) + (π : J → I) (i₀ i : I) (valid : J → Bool) + (j₀ j : {j : J // valid j = true}) (hπ : π j.val = i) : + realizedTestAcceptance D π (foldedAnswer i₀ (fun h => h.val i)) + (conditionedFoldedAnswer valid j₀ (fun h => h.val j)) = 1 - (D : ℝ)⁻¹ := by + rw [realizedTestAcceptance_eq_testAcceptance positive] + exact testAcceptance_folded_conditioned_dictators _ π i₀ i valid j₀ j hπ + +end MinUncutGames.Foundations.Hastad + +namespace MinUncutGames.Foundations.Hastad.SourceTape + +open scoped BigOperators +open MinUncutGames.Reduction.FiniteNoise + +abbrev TestTape (I J : Type*) (D : ℕ) := + Cube I × ((J → Fin D) × Cube J) + +abbrev FairTestTape (I J : Type*) (D : ℕ) := TestTape I J D × Bool + +section Expectations + +variable {X Y : Type*} [Fintype X] [Fintype Y] + +theorem expect_prod (H : X × Y → ℝ) : + (𝔼 p : X × Y, H p) = 𝔼 x : X, 𝔼 y : Y, H (x, y) := by + simpa only [Finset.univ_product_univ] using + (Finset.expect_product (Finset.univ : Finset X) (Finset.univ : Finset Y) H) + +end Expectations + +section Tape + +variable {I J : Type*} [Fintype I] [DecidableEq I] [Fintype J] [DecidableEq J] {D : ℕ} + +theorem card_testTape : + Fintype.card (TestTape I J D) = + 2 ^ Fintype.card I * (D ^ Fintype.card J * 2 ^ Fintype.card J) := by + simp [TestTape, Cube] + +theorem card_fairTestTape : + Fintype.card (FairTestTape I J D) = + (2 ^ Fintype.card I * (D ^ Fintype.card J * 2 ^ Fintype.card J)) * 2 := by + rw [Fintype.card_prod, card_testTape] + rfl + +theorem expect_testTape (H : TestTape I J D → ℝ) : + (𝔼 t : TestTape I J D, H t) = + 𝔼 f : Cube I, 𝔼 z : J → Fin D, 𝔼 g : Cube J, H (f, z, g) := by + rw [expect_prod] + apply Finset.expect_congr rfl + intro f _ + exact expect_prod _ + +theorem expect_equivTape {E : Type*} [Fintype E] + (e : E ≃ TestTape I J D) (H : TestTape I J D → ℝ) : + (𝔼 s : E, H (e s)) = 𝔼 t : TestTape I J D, H t := + Fintype.expect_equiv e _ _ (fun _ => rfl) + +theorem expect_fairTestTape (H : FairTestTape I J D → ℝ) : + (𝔼 t : FairTestTape I J D, H t) = + 𝔼 t : TestTape I J D, (H (t, false) + H (t, true)) / 2 := by + rw [expect_prod] + apply Finset.expect_congr rfl + intro t _ + rw [Fintype.expect_eq_sum_div_card] + simp [add_comm] + +theorem expect_fairTestTape_ignore (H : TestTape I J D → ℝ) : + (𝔼 t : FairTestTape I J D, H t.1) = 𝔼 t : TestTape I J D, H t := by + rw [expect_prod] + simp only [Fintype.expect_const] + +def tapeQueries (π : J → I) (t : TestTape I J D) : Cube I × Cube J × Cube J := + (t.1, t.2.2, thirdQuery π t.1 t.2.2 (realizedNoise t.2.1)) + +theorem expect_tapeQueries (positive : 0 < D) (π : J → I) + (H : Cube I × Cube J × Cube J → ℝ) : + (𝔼 t : TestTape I J D, H (tapeQueries π t)) = + 𝔼 f : Cube I, ∑ μ : Cube J, noiseWeight ((D : ℝ)⁻¹) μ * + (𝔼 g : Cube J, H (f, g, thirdQuery π f g μ)) := by + rw [expect_testTape] + apply Finset.expect_congr rfl + intro f _ + exact expect_realizedNoise positive + (fun μ => 𝔼 g : Cube J, H (f, g, thirdQuery π f g μ)) + +def tapeAcceptance (D : ℕ) (π : J → I) + (A : Cube I → Bool) (B : Cube J → Bool) : ℝ := + 𝔼 t : TestTape I J D, + if A t.1 ^^ B t.2.2 ^^ B (thirdQuery π t.1 t.2.2 (realizedNoise t.2.1)) + then 0 else 1 + +theorem tapeAcceptance_eq_realizedTestAcceptance (D : ℕ) (π : J → I) + (A : Cube I → Bool) (B : Cube J → Bool) : + tapeAcceptance D π A B = realizedTestAcceptance D π A B := + expect_testTape _ + +theorem tapeAcceptance_eq_testAcceptance (positive : 0 < D) (π : J → I) + (A : Cube I → Bool) (B : Cube J → Bool) : + tapeAcceptance D π A B = testAcceptance ((D : ℝ)⁻¹) π A B := by + rw [tapeAcceptance_eq_realizedTestAcceptance, + realizedTestAcceptance_eq_testAcceptance positive] + +theorem tapeAcceptance_eq_sum_div_card (D : ℕ) (π : J → I) + (A : Cube I → Bool) (B : Cube J → Bool) : + tapeAcceptance D π A B = + (∑ t : TestTape I J D, + if A t.1 ^^ B t.2.2 ^^ B (thirdQuery π t.1 t.2.2 (realizedNoise t.2.1)) + then (0 : ℝ) else 1) / Fintype.card (TestTape I J D) := + Fintype.expect_eq_sum_div_card _ + +end Tape + +variable {X Λ : Type*} + +def restrictFunction (P : X → Prop) (f : X → Λ) : {x : X // P x} → Λ := + fun x => f x.val + +theorem expect_restrictFunction [Fintype X] [DecidableEq X] [Fintype Λ] [Nonempty Λ] + (P : X → Prop) [DecidablePred P] (H : ({x : X // P x} → Λ) → ℝ) : + (𝔼 f : X → Λ, H (restrictFunction P f)) = + 𝔼 g : {x : X // P x} → Λ, H g := by + classical + calc + _ = 𝔼 p : ({x : X // P x} → Λ) × ({x : X // ¬ P x} → Λ), H p.1 := + Fintype.expect_equiv (Equiv.piEquivPiSubtypeProd P (fun _ => Λ)) _ _ + (fun _ => rfl) + _ = _ := by + rw [expect_prod] + simp only [Fintype.expect_const] + +variable {I J : Type*} + +def restrictTape (P : I → Prop) (Q : J → Prop) {D : ℕ} + (t : TestTape I J D) : TestTape {i : I // P i} {j : J // Q j} D := + (restrictFunction P t.1, restrictFunction Q t.2.1, restrictFunction Q t.2.2) + +theorem expect_restrictTape [Fintype I] [DecidableEq I] [Fintype J] [DecidableEq J] + (P : I → Prop) (Q : J → Prop) [DecidablePred P] [DecidablePred Q] + {D : ℕ} (positive : 0 < D) + (H : TestTape {i : I // P i} {j : J // Q j} D → ℝ) : + (𝔼 t : TestTape I J D, H (restrictTape P Q t)) = + 𝔼 t : TestTape {i : I // P i} {j : J // Q j} D, H t := by + let : Nonempty (Fin D) := ⟨⟨0, positive⟩⟩ + rw [expect_testTape, expect_testTape] + change (𝔼 f : Cube I, 𝔼 z : J → Fin D, 𝔼 g : Cube J, + H (restrictFunction P f, restrictFunction Q z, restrictFunction Q g)) = _ + have hg (f : Cube I) (z : J → Fin D) : + (𝔼 g : Cube J, + H (restrictFunction P f, restrictFunction Q z, restrictFunction Q g)) = + 𝔼 g : Cube {j : J // Q j}, H (restrictFunction P f, restrictFunction Q z, g) := + expect_restrictFunction (Λ := Bool) Q + (fun g => H (restrictFunction P f, restrictFunction Q z, g)) + simp_rw [hg] + have hz (f : Cube I) : + (𝔼 z : J → Fin D, 𝔼 g : Cube {j : J // Q j}, + H (restrictFunction P f, restrictFunction Q z, g)) = + 𝔼 z : {j : J // Q j} → Fin D, 𝔼 g : Cube {j : J // Q j}, + H (restrictFunction P f, z, g) := + expect_restrictFunction (Λ := Fin D) Q + (fun z => 𝔼 g : Cube {j : J // Q j}, H (restrictFunction P f, z, g)) + simp_rw [hz] + exact expect_restrictFunction (Λ := Bool) P + (fun f => 𝔼 z : {j : J // Q j} → Fin D, 𝔼 g : Cube {j : J // Q j}, H (f, z, g)) + +def restrictedProjection (P : I → Prop) (Q : J → Prop) (π : J → I) + (hπ : ∀ j, Q j → P (π j)) : {j : J // Q j} → {i : I // P i} := + fun j => ⟨π j.val, hπ j.val j.property⟩ + +theorem restrict_realizedNoise (Q : J → Prop) {D : ℕ} (z : J → Fin D) : + restrictFunction Q (realizedNoise z) = realizedNoise (restrictFunction Q z) := rfl + +theorem restrict_thirdQuery (P : I → Prop) (Q : J → Prop) (π : J → I) + (hπ : ∀ j, Q j → P (π j)) (f : Cube I) (g μ : Cube J) : + restrictFunction Q (thirdQuery π f g μ) = + thirdQuery (restrictedProjection P Q π hπ) + (restrictFunction P f) (restrictFunction Q g) (restrictFunction Q μ) := rfl + +theorem expect_restricted_queries [Fintype I] [DecidableEq I] [Fintype J] [DecidableEq J] + (P : I → Prop) (Q : J → Prop) [DecidablePred P] [DecidablePred Q] + (π : J → I) (hπ : ∀ j, Q j → P (π j)) {D : ℕ} (positive : 0 < D) + (H : Cube {i : I // P i} × Cube {j : J // Q j} × Cube {j : J // Q j} → ℝ) : + (𝔼 t : TestTape I J D, + H (restrictFunction P t.1, restrictFunction Q t.2.2, + restrictFunction Q (thirdQuery π t.1 t.2.2 (realizedNoise t.2.1)))) = + 𝔼 t : TestTape {i : I // P i} {j : J // Q j} D, + H (tapeQueries (restrictedProjection P Q π hπ) t) := by + exact expect_restrictTape P Q positive + (fun t => H (tapeQueries (restrictedProjection P Q π hπ) t)) + +def restrictRightTape (Q : J → Prop) {D : ℕ} (t : TestTape I J D) : + TestTape I {j : J // Q j} D := + (t.1, restrictFunction Q t.2.1, restrictFunction Q t.2.2) + +theorem expect_restrictRightTape [Fintype I] [DecidableEq I] + [Fintype J] [DecidableEq J] (Q : J → Prop) [DecidablePred Q] + {D : ℕ} (positive : 0 < D) (H : TestTape I {j : J // Q j} D → ℝ) : + (𝔼 t : TestTape I J D, H (restrictRightTape Q t)) = + 𝔼 t : TestTape I {j : J // Q j} D, H t := by + let : Nonempty (Fin D) := ⟨⟨0, positive⟩⟩ + rw [expect_testTape, expect_testTape] + apply Finset.expect_congr rfl + intro f _ + change (𝔼 z : J → Fin D, 𝔼 g : Cube J, + H (f, restrictFunction Q z, restrictFunction Q g)) = _ + have hg (z : J → Fin D) : + (𝔼 g : Cube J, H (f, restrictFunction Q z, restrictFunction Q g)) = + 𝔼 g : Cube {j : J // Q j}, H (f, restrictFunction Q z, g) := + expect_restrictFunction (Λ := Bool) Q (fun g => H (f, restrictFunction Q z, g)) + simp_rw [hg] + exact expect_restrictFunction (Λ := Fin D) Q + (fun z => 𝔼 g : Cube {j : J // Q j}, H (f, z, g)) + +theorem expect_rightRestricted_queries [Fintype I] [DecidableEq I] + [Fintype J] [DecidableEq J] (Q : J → Prop) [DecidablePred Q] + (π : J → I) {D : ℕ} (positive : 0 < D) + (H : Cube I × Cube {j : J // Q j} × Cube {j : J // Q j} → ℝ) : + (𝔼 t : TestTape I J D, + H (t.1, restrictFunction Q t.2.2, + restrictFunction Q (thirdQuery π t.1 t.2.2 (realizedNoise t.2.1)))) = + 𝔼 t : TestTape I {j : J // Q j} D, + H (tapeQueries (fun j => π j.val) t) := by + exact expect_restrictRightTape Q positive + (fun t => H (tapeQueries (fun j => π j.val) t)) + +end MinUncutGames.Foundations.Hastad.SourceTape + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/InitialGraph.lean b/lean/OAI/Computability/MinUncut/PCP/InitialGraph.lean new file mode 100644 index 0000000000000000000000000000000000000000..817f81fe83ba86dcbf084675dc0d82157dd18f9a --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/InitialGraph.lean @@ -0,0 +1,198 @@ +import Mathlib +import OAI.Computability.MinUncut.Encoding.FormulaEncoding +import OAI.Computability.MinUncut.PCP.Generator + +namespace OAI + +section +namespace MinUncutGames.Foundations.PCP.InitialGraph + +open Target + +abbrev Label := Bool × Bool × Bool +abbrev Vertex (F : Formula) := (Fin F.«variables» ⊕ Fin F.clauses.length) ⊕ Unit +abbrev Dart (F : Formula) := (RandomEvent F × Bool) ⊕ Unit + +instance slotFintype : Fintype Slot where + elems := {Slot.first, Slot.second, Slot.third} + complete := by intro s; cases s <;> simp + +@[simp] theorem card_slot : Fintype.card Slot = 3 := by decide +@[simp] theorem card_label : Fintype.card Label = 8 := by + simp [Label, Fintype.card_prod] + +def variableVertex (F : Formula) (v : Fin F.«variables») : Vertex F := .inl (.inl v) +def clauseVertex (F : Formula) (i : Fin F.clauses.length) : Vertex F := .inl (.inr i) +def dummyVertex (F : Formula) : Vertex F := .inr () +def dummyDart (F : Formula) : Dart F := .inr () + +instance vertexNonempty (F : Formula) : Nonempty (Vertex F) := ⟨dummyVertex F⟩ +instance dartNonempty (F : Formula) : Nonempty (Dart F) := ⟨dummyDart F⟩ + +def reverse (F : Formula) : Dart F → Dart F + | .inl (event, orientation) => .inl (event, !orientation) + | .inr _ => .inr () + +theorem reverse_involutive (F : Formula) : Function.Involutive (reverse F) := by + intro d + cases d with + | inl pair => rcases pair with ⟨e, b⟩; cases b <;> rfl + | inr u => cases u; rfl + +def reverseEquiv (F : Formula) : Dart F ≃ Dart F where + toFun := reverse F + invFun := reverse F + left_inv := reverse_involutive F + right_inv := reverse_involutive F + +def tail (F : Formula) : Dart F → Vertex F + | .inl (event, false) => clauseVertex F event.1 + | .inl (event, true) => variableVertex F (nameAt (clauseAt F event.1) event.2) + | .inr _ => dummyVertex F + +def toClauseAnswer (label : Label) : ClauseAnswer := ⟨label.1, label.2.1, label.2.2⟩ +def fromClauseAnswer (answer : ClauseAnswer) : Label := (answer.first, answer.second, answer.third) +def variableLabel (value : Bool) : Label := (value, false, false) + +@[simp] theorem to_fromClauseAnswer (answer : ClauseAnswer) : + toClauseAnswer (fromClauseAnswer answer) = answer := by + cases answer; rfl + +def variableValid (label : Label) : Bool := + decide (label.2.1 = false ∧ label.2.2 = false) + +def incidenceAccept (F : Formula) (event : RandomEvent F) + (clauseLabel variableAnswer : Label) : Bool := + variableValid variableAnswer && + (localSatisfies (clauseAt F event.1) (toClauseAnswer clauseLabel) && + decide (answerAt (toClauseAnswer clauseLabel) event.2 = variableAnswer.1)) + +def predicate (F : Formula) : Dart F → Label → Label → Bool + | .inl (event, false), a, b => incidenceAccept F event a b + | .inl (event, true), a, b => incidenceAccept F event b a + | .inr _, _, _ => true + +def raw (F : Formula) : ConstraintGraph (Vertex F) (Dart F) Label where + reverse := reverseEquiv F + reverse_involutive := reverse_involutive F + tail := tail F + accepts := predicate F + reverse_accepts := by + intro d a b + cases d with + | inl pair => rcases pair with ⟨event, orientation⟩; cases orientation <;> rfl + | inr u => rfl + +theorem raw_forward (F : Formula) (labeling : Vertex F → Label) (event : RandomEvent F) : + (raw F).edgeSatisfied labeling (.inl (event, false)) = + incidenceAccept F event (labeling (clauseVertex F event.1)) + (labeling (variableVertex F (nameAt (clauseAt F event.1) event.2))) := rfl + +theorem incidenceAccept_true (F : Formula) (event : RandomEvent F) (a b : Label) + (h : incidenceAccept F event a b = true) : + localSatisfies (clauseAt F event.1) (toClauseAnswer a) = true ∧ + answerAt (toClauseAnswer a) event.2 = b.1 := by + simp only [incidenceAccept, Bool.and_eq_true, decide_eq_true_eq] at h + exact h.2 + +def honestLabeling (F : Formula) (A : Fin F.«variables» → Bool) : Vertex F → Label + | .inl (.inl v) => variableLabel (A v) + | .inl (.inr i) => fromClauseAnswer (honestAnswer (clauseAt F i) A) + | .inr _ => variableLabel false + +theorem incidence_honest (F : Formula) (A : Fin F.«variables» → Bool) + (sat : ∀ c ∈ F.clauses, c.eval A = true) (event : RandomEvent F) : + incidenceAccept F event (honestLabeling F A (clauseVertex F event.1)) + (honestLabeling F A (variableVertex F (nameAt (clauseAt F event.1) event.2))) = true := by + have hc : (clauseAt F event.1).eval A = true := sat _ (List.getElem_mem _) + simp [incidenceAccept, honestLabeling, clauseVertex, variableVertex, variableLabel, + variableValid, honest_satisfies, honest_answerAt, hc] + +theorem raw_completeness (F : Formula) (sat : F.Satisfiable) : (raw F).Satisfiable := by + rcases sat with ⟨A, hA⟩ + refine ⟨honestLabeling F A, fun d => ?_⟩ + cases d with + | inl pair => + rcases pair with ⟨event, orientation⟩ + cases orientation <;> exact incidence_honest F A hA event + | inr u => rfl + +theorem clauseAnswer_eq_of_slots (a b : ClauseAnswer) + (h : ∀ s, answerAt a s = answerAt b s) : a = b := by + rcases a with ⟨a₀, a₁, a₂⟩ + rcases b with ⟨b₀, b₁, b₂⟩ + have h₀ : a₀ = b₀ := h .first + have h₁ : a₁ = b₁ := h .second + have h₂ : a₂ = b₂ := h .third + cases h₀; cases h₁; cases h₂; rfl + +theorem raw_reflects (F : Formula) (sat : (raw F).Satisfiable) : F.Satisfiable := by + rcases sat with ⟨labeling, hlabeling⟩ + let A : Fin F.«variables» → Bool := fun v => (labeling (variableVertex F v)).1 + have slot_correct (i : Fin F.clauses.length) (s : Slot) : + localSatisfies (clauseAt F i) (toClauseAnswer (labeling (clauseVertex F i))) = true ∧ + answerAt (toClauseAnswer (labeling (clauseVertex F i))) s = + A (nameAt (clauseAt F i) s) := by + exact incidenceAccept_true F (i, s) _ _ (hlabeling (.inl ((i, s), false))) + have clause_correct (i : Fin F.clauses.length) : (clauseAt F i).eval A = true := by + have equal : toClauseAnswer (labeling (clauseVertex F i)) = honestAnswer (clauseAt F i) A := + clauseAnswer_eq_of_slots _ _ (fun s => by + simpa only [honest_answerAt] using (slot_correct i s).2) + have satisfied := (slot_correct i .first).1 + rw [equal, honest_satisfies] at satisfied + exact satisfied + refine ⟨A, fun c hc => ?_⟩ + obtain ⟨i, hi, heq⟩ := List.getElem_of_mem hc + simpa only [clauseAt, heq] using clause_correct ⟨i, hi⟩ + +theorem raw_satisfiable_iff (F : Formula) : (raw F).Satisfiable ↔ F.Satisfiable := + ⟨raw_reflects F, raw_completeness F⟩ + +@[simp] theorem card_vertex (F : Formula) : + Fintype.card (Vertex F) = F.«variables» + F.clauses.length + 1 := by + simp [Vertex, Fintype.card_sum] + +@[simp] theorem card_dart (F : Formula) : + Fintype.card (Dart F) = 6 * F.clauses.length + 1 := by + simp [Dart, RandomEvent, Fintype.card_sum, Fintype.card_prod] + omega + +abbrev CompactVertex (F : Formula) := Vertex (NameCompaction.compact F) +abbrev CompactDart (F : Formula) := Dart (NameCompaction.compact F) + +def build (F : Formula) : ConstraintGraph (CompactVertex F) (CompactDart F) Label := + raw (NameCompaction.compact F) + +theorem build_satisfiable_iff (F : Formula) : (build F).Satisfiable ↔ F.Satisfiable := by + exact (raw_satisfiable_iff (NameCompaction.compact F)).trans + (NameCompaction.compact_satisfiable_iff F) + +theorem build_vertex_bound (F : Formula) : + Fintype.card (CompactVertex F) ≤ 4 * F.clauses.length + 1 := by + have h := NameCompaction.compact_active_bound F + simp only [CompactVertex, card_vertex, NameCompaction.compact_clause_count] + omega + +theorem build_dart_count (F : Formula) : + Fintype.card (CompactDart F) = 6 * F.clauses.length + 1 := by + simp only [CompactDart, card_dart, NameCompaction.compact_clause_count] + +theorem build_initial_gap (F : Formula) (unsat : ¬ F.Satisfiable) + (labeling : CompactVertex F → Label) : 1 ≤ (build F).rejectionCount labeling := by + apply ConstraintGraph.rejectionCount_positive + intro h + exact unsat ((build_satisfiable_iff F).mp h) + +theorem build_inverse_size_gap (F : Formula) (unsat : ¬ F.Satisfiable) + (labeling : CompactVertex F → Label) : + Fintype.card (CompactDart F) ≤ + (6 * F.clauses.length + 1) * (build F).rejectionCount labeling := by + rw [build_dart_count] + simpa only [Nat.mul_one] using + Nat.mul_le_mul_left (6 * F.clauses.length + 1) (build_initial_gap F unsat labeling) + +end MinUncutGames.Foundations.PCP.InitialGraph + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/LoopOrder.lean b/lean/OAI/Computability/MinUncut/PCP/LoopOrder.lean new file mode 100644 index 0000000000000000000000000000000000000000..3b410041cad9a6e6768e0cb6a7d920b9c30bbe44 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/LoopOrder.lean @@ -0,0 +1,557 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.RuntimeModel +import OAI.Computability.MinUncut.PCP.ContextClear +import OAI.Computability.MinUncut.Machines.MachineTupleOdometer + +namespace OAI + +section +namespace MinUncutGames.Foundations.Hastad.SourceOccurrences.Encoding + +open MinUncutGames.Foundations.Complexity.MachineTupleOdometer + +def decodeTuple {α β : Type} (a : Encoding α) (b : Encoding β) + (digits : Fin a.size → Fin b.size) : α → β := + fun x => b.code.symm (digits (a.code x)) + +theorem enumerate_function {α β : Type} (a : Encoding α) (b : Encoding β) : + (a.function b).enumerate = + (tupleOrder b.size a.size).map (decodeTuple a b) := by + simp only [tupleOrder, List.map_ofFn] + rfl + +theorem enumerate_fin_function (n u : ℕ) : + ((Encoding.fin u).function (Encoding.fin n)).enumerate = tupleOrder n u := by + rfl + +end MinUncutGames.Foundations.Hastad.SourceOccurrences.Encoding + +namespace MinUncutGames.Foundations.Hastad.SourceLoopOrder + +open Complexity Complexity.MachineTupleOdometer +open Target SourceContexts SourceOccurrences +open MinUncutGames.Reduction + +def tupleTapeOrder (u D : ℕ) : List (SourceTape.TestTape (I u) (J u) D) := + (tupleOrder 2 (2 ^ u)).flatMap (fun f => + (tupleOrder D (8 ^ u)).flatMap (fun z => + (tupleOrder 2 (8 ^ u)).map (fun g => + (Encoding.decodeTuple (iEncoding u) Encoding.bool f, + Encoding.decodeTuple (jEncoding u) (Encoding.fin D) z, + Encoding.decodeTuple (jEncoding u) Encoding.bool g)))) + +theorem testTapeEncoding_eq_tupleTapeOrder (u D : ℕ) : + (testTapeEncoding u D).enumerate = tupleTapeOrder u D := by + rw [SourceEnumeration.testTapeEncoding_enumerate] + simp only [tupleTapeOrder, Encoding.enumerate_function, + List.flatMap_map, List.map_map, Function.comp_def] + rfl + +theorem testTapeEncoding_flatMap_tupleTapeOrder {α : Type} (u D : ℕ) + (emit : SourceTape.TestTape (I u) (J u) D → List α) : + (testTapeEncoding u D).enumerate.flatMap emit = + (tupleTapeOrder u D).flatMap emit := by + rw [testTapeEncoding_eq_tupleTapeOrder] + +def rankedQuery (u D : ℕ) (fallback : SourceQueryLoop.Query u D) + (i : ℕ) : SourceQueryLoop.Query u D := + if h : i < (testTapeEncoding u D).size then + (testTapeEncoding u D).code.symm ⟨i, h⟩ + else fallback + +theorem rankedQuery_at (u D : ℕ) (fallback : SourceQueryLoop.Query u D) + (i : Fin (testTapeEncoding u D).size) : + rankedQuery u D fallback i.val = (testTapeEncoding u D).code.symm i := by + simp only [rankedQuery, i.isLt, ↓reduceDIte] + +theorem query_prefixBits_eq_ofFn (u D n : ℕ) (queries : ℕ → SourceQueryLoop.Query u D) + (values : Fin 3 → ℕ) (signature : SourceLocalSignature.Signature u) : + SourceQueryLoop.prefixBits u D queries values signature n = + (List.ofFn (fun i : Fin n => queries i.val)).flatMap + (fun query => SourceTestAppend.equationBits u D values (signature, query)) := by + induction n with + | zero => simp [SourceQueryLoop.prefixBits] + | succ n ih => + rw [SourceQueryLoop.prefixBits, List.ofFn_succ', List.concat_eq_append, + List.flatMap_append] + simpa only [List.flatMap_cons, List.flatMap_nil, List.append_nil, + Fin.val_castSucc, Fin.val_last] using + congrArg (fun bits => bits ++ + SourceTestAppend.equationBits u D values (signature, queries n)) ih + +theorem query_prefixBits_eq_enumerate (u D : ℕ) (fallback : SourceQueryLoop.Query u D) + (values : Fin 3 → ℕ) (signature : SourceLocalSignature.Signature u) : + SourceQueryLoop.prefixBits u D (rankedQuery u D fallback) values signature + (testTapeEncoding u D).size = + (testTapeEncoding u D).enumerate.flatMap + (fun query => SourceTestAppend.equationBits u D values (signature, query)) := by + rw [query_prefixBits_eq_ofFn] + have hlist : List.ofFn (fun i : Fin (testTapeEncoding u D).size => + rankedQuery u D fallback i.val) = (testTapeEncoding u D).enumerate := by + apply congrArg List.ofFn + funext i + exact rankedQuery_at u D fallback i + rw [hlist] + +theorem query_prefixBits_eq_tupleTapeOrder (u D : ℕ) + (fallback : SourceQueryLoop.Query u D) (values : Fin 3 → ℕ) + (signature : SourceLocalSignature.Signature u) : + SourceQueryLoop.prefixBits u D (rankedQuery u D fallback) values signature + (testTapeEncoding u D).size = + (tupleTapeOrder u D).flatMap + (fun query => SourceTestAppend.equationBits u D values (signature, query)) := by + rw [query_prefixBits_eq_enumerate, testTapeEncoding_eq_tupleTapeOrder] + +def tupleSourceOrder (F : Formula) (u D : ℕ) : List (SourceIndex F u D) := + (tupleOrder F.clauses.length u).flatMap (fun c => + (tupleOrder 3 u).flatMap (fun s => + (tupleTapeOrder u D).map (fun t => + ((c, Encoding.decodeTuple (Encoding.fin u) slotEncoding s), t)))) + +theorem sourceIndexEncoding_eq_tupleSourceOrder (F : Formula) (u D : ℕ) : + (sourceIndexEncoding F u D).enumerate = tupleSourceOrder F u D := by + rw [SourceEnumeration.sourceIndexEncoding_enumerate] + simp only [tupleSourceOrder, tupleTapeOrder, clauseEncoding, slotContextEncoding, + Encoding.enumerate_function, List.flatMap_map, List.map_map, Function.comp_def] + apply List.flatMap_congr + intro c hc + apply List.flatMap_congr + intro slots hslots + erw [List.map_flatMap] + apply List.flatMap_congr + intro first hfirst + erw [List.map_flatMap] + apply List.flatMap_congr + intro second hsecond + erw [List.map_map] + rfl + +theorem rawSourceList_eq_tupleOrder (F : Formula) (u D : ℕ) : + rawSourceList F u D = (tupleSourceOrder F u D).map (sourceEquation F u D) := by + unfold rawSourceList occurrenceList + rw [sourceIndexEncoding_eq_tupleSourceOrder] + +theorem sourceList_eq_tupleOrder (F : Formula) (u D : ℕ) (hne : F.clauses ≠ []) : + sourceList F u D = (tupleSourceOrder F u D).map (sourceEquation F u D) := by + rw [sourceList_nonempty F u D hne, rawSourceList_eq_tupleOrder] + +theorem rawSourceList_flatMap_tupleOrder {α : Type} (F : Formula) (u D : ℕ) + (emit : CloneGap.Equation (Fin (nBits F u)) → List α) : + (rawSourceList F u D).flatMap emit = + (tupleSourceOrder F u D).flatMap (fun p => emit (sourceEquation F u D p)) := by + rw [rawSourceList_eq_tupleOrder] + simp only [List.flatMap_map] + +def reverseAppend {α β : Type} (encode : α → List β) + (accumulator : List β) (record : α) : List β := + (encode record).reverse ++ accumulator + +theorem foldl_reverseAppend {α β : Type} (encode : α → List β) + (records : List α) (accumulator : List β) : + records.foldl (reverseAppend encode) accumulator = + (records.flatMap encode).reverse ++ accumulator := by + induction records generalizing accumulator with + | nil => simp + | cons record records ih => + simp only [List.foldl_cons, ih, reverseAppend, List.flatMap_cons, + List.reverse_append, List.append_assoc] + +theorem foldl_reverseAppend_header {α β : Type} (encode : α → List β) + (records : List α) (header : List β) : + records.foldl (reverseAppend encode) header.reverse = + (header ++ records.flatMap encode).reverse := by + rw [foldl_reverseAppend, List.reverse_append] + +theorem foldl_reverseAppend_prefix {α β : Type} (encode : α → List β) + (emitted remaining : List α) (header : List β) : + (emitted ++ remaining).foldl (reverseAppend encode) header.reverse = + remaining.foldl (reverseAppend encode) + (header ++ emitted.flatMap encode).reverse := by + rw [List.foldl_append, foldl_reverseAppend_header] + +theorem foldl_resultTapes {α K : Type} [DecidableEq K] + (layout : SourceTestAppend.Layout K) (encode : α → List Bool) + (records : List α) (base : K → List Bool) : + records.foldl (fun tapes record => + SourceTestAppend.resultTapes layout tapes (encode record)) base = + Function.update base layout.accumulator + ((records.flatMap encode).reverse ++ base layout.accumulator) := by + induction records generalizing base with + | nil => + funext k + by_cases hk : k = layout.accumulator <;> simp [hk] + | cons record records ih => + simp only [List.foldl_cons, ih] + funext k + by_cases hk : k = layout.accumulator <;> + simp [SourceTestAppend.resultTapes, hk, List.flatMap_cons, + List.reverse_append, List.append_assoc] + +theorem inputBits_eq_header_records (input : SourceEncoding.Input) : + SourceEncoding.inputBits input = + encodeWords [input.«variables», input.equations.length] ++ + input.equations.flatMap (fun e => encodeWords (SourceEncoding.equationWords e)) := by + unfold SourceEncoding.inputBits SourceEncoding.inputWords + rw [encodeWords_append] + congr 1 + induction input.equations with + | nil => rfl + | cons e es ih => + simp only [List.flatMap_cons, encodeWords_append, ih] + +theorem input_reverse_accumulator (input : SourceEncoding.Input) : + input.equations.foldl + (reverseAppend (fun e => encodeWords (SourceEncoding.equationWords e))) + (encodeWords [input.«variables», input.equations.length]).reverse = + (SourceEncoding.inputBits input).reverse := by + rw [foldl_reverseAppend_header, inputBits_eq_header_records] + +theorem sourceInput_tuple_reverse_accumulator (F : Formula) (u D : ℕ) + (hD : 0 < D) (hne : F.clauses ≠ []) : + (tupleSourceOrder F u D).foldl + (reverseAppend (fun p => encodeWords + (SourceEncoding.equationWords (sourceEquation F u D p)))) + (encodeWords [nBits F u, (sourceList F u D).length]).reverse = + (SourceEncoding.inputBits (sourceInput F u D hD)).reverse := by + rw [← input_reverse_accumulator (sourceInput F u D hD)] + change _ = (sourceList F u D).foldl + (reverseAppend (fun e => encodeWords (SourceEncoding.equationWords e))) + (encodeWords [nBits F u, (sourceList F u D).length]).reverse + rw [sourceList_eq_tupleOrder F u D hne, List.foldl_map] + rfl + +theorem finalReverse_steps (input : SourceEncoding.Input) (register : Option Bool) : + MachineReverse.next^[(SourceEncoding.inputBits input).length + 1] + (some (MachineReverse.running + (input.equations.foldl + (reverseAppend (fun e => encodeWords (SourceEncoding.equationWords e))) + (encodeWords [input.«variables», input.equations.length]).reverse) + [] register)) = + some (MachineReverse.halted (SourceEncoding.inputBits input)) := by + rw [input_reverse_accumulator] + simpa only [List.length_reverse, List.reverse_reverse, List.append_nil] using + MachineReverse.reverse_steps (SourceEncoding.inputBits input).reverse [] register + +end MinUncutGames.Foundations.Hastad.SourceLoopOrder + +end +section +namespace MinUncutGames.Foundations.Hastad.SourceQueryOrder + +open Turing Complexity Target SourceContexts SourceOccurrences +open SourceLocalSignature SourceAddressDescriptors SourceLoopOrder + +def occurrenceBits (F : Formula) (u D : Nat) (p : SourceIndex F u D) : List Bool := + encodeWords (MinUncutGames.Reduction.SourceEncoding.equationWords (sourceEquation F u D p)) + +def slotBits (F : Formula) (u D : Nat) (c : ClauseContext F u) (s : SlotContext u) : + List Bool := + (testTapeEncoding u D).enumerate.flatMap (fun t => occurrenceBits F u D ((c, s), t)) + +def tupleBits (F : Formula) (u D : Nat) (c : ClauseContext F u) : List Bool := + (slotContextEncoding u).enumerate.flatMap (slotBits F u D c) + +theorem equationBits_eq (F : Formula) (u D : Nat) (c : ClauseContext F u) + (s : SlotContext u) (t : SourceQueryLoop.Query u D) : + SourceTestAppend.equationBits u D (baseValue F u c (sampledVariables F c s)) + (ofContext F c s, t) = occurrenceBits F u D ((c, s), t) := by + rw [occurrenceBits, sourceEquation_words] + rfl + +theorem prefixBits_eq_slotBits (F : Formula) (u D : Nat) (c : ClauseContext F u) + (s : SlotContext u) (fallback : SourceQueryLoop.Query u D) : + SourceQueryLoop.prefixBits u D (rankedQuery u D fallback) + (baseValue F u c (sampledVariables F c s)) (ofContext F c s) + (testTapeEncoding u D).size = slotBits F u D c s := by + rw [query_prefixBits_eq_enumerate] + unfold slotBits + congr 1 + funext t + exact equationBits_eq F u D c s t + +variable {K Λ : Type} [DecidableEq K] + +theorem sourceLoopInTime (F : Formula) (u D : Nat) (c : ClauseContext F u) + (s : SlotContext u) (fallback initialQuery : SourceQueryLoop.Query u D) + (layout : SourceTestAppend.Layout K) + (labels : SourceQueryLoop.Label u D (testTapeEncoding u D).size → Λ) + (exit : Option Λ) + (p : Λ → TM2.Stmt (fun _ : K => Bool) Λ (SourceQueryLoop.State u D)) + (atLabels : ∀ l, p (labels l) = SourceQueryLoop.statement u D + (testTapeEncoding u D).size (rankedQuery u D fallback) layout labels exit l) + (base : K → List Bool) + (sourceWords : ∀ side, base (layout.sources side) = + encodeWord (baseValue F u c (sampledVariables F c s) side)) + (scratchEmpty : base layout.scratch = []) + (temporaryEmpty : base layout.temporary = []) : + ∃ lastQuery : SourceQueryLoop.Query u D, + Nonempty (StateTransition.EvalsToInTime (TM2.step p) + ⟨some (labels (.load ⟨0, Nat.zero_lt_succ _⟩)), + ((ofContext F c s, initialQuery), none), base⟩ + (some ⟨exit, ((ofContext F c s, lastQuery), none), + SourceTestAppend.resultTapes layout base (slotBits F u D c s)⟩) + ((testTapeEncoding u D).size * (9 * nBits F u + 21) + 1)) := by + have hbound : ∀ i, i < (testTapeEncoding u D).size → + SourceTestAppend.steps u D (baseValue F u c (sampledVariables F c s)) + (ofContext F c s, rankedQuery u D fallback i) ≤ 9 * nBits F u + 20 := by + intro i hi + let run := SourceTestAppend.sourceAppendInTime F u D + ((c, s), rankedQuery u D fallback i) layout + (fun l => labels (.emit ⟨i, hi⟩ l)) + (some (labels (.load ⟨i + 1, by omega⟩))) p + (fun l => atLabels (.emit ⟨i, hi⟩ l)) base sourceWords + scratchEmpty temporaryEmpty none + exact run.steps_le_m + have h := SourceQueryLoop.loopInTime u D (testTapeEncoding u D).size + (9 * nBits F u + 20) (rankedQuery u D fallback) layout labels exit p atLabels + (ofContext F c s) initialQuery base (baseValue F u c (sampledVariables F c s)) + sourceWords scratchEmpty temporaryEmpty hbound + rw [prefixBits_eq_slotBits] at h + exact h + +end MinUncutGames.Foundations.Hastad.SourceQueryOrder + +end +section +namespace MinUncutGames.Foundations.Hastad.SourceTupleTape + +open Turing Complexity SourceContexts SourceRuntimeModel + +structure Snapshot where + rank : List Bool := [] + rightBase : List Bool := [] + leftBase : List Bool := [] + zero : List Bool := [] + emitted : List Bool := [] + deriving DecidableEq, Inhabited + +variable {u : Nat} {Extra : Type} + +def tapes (base : Arena u Extra → List Bool) (s : Snapshot) : Arena u Extra → List Bool + | .extra (.inr .rank) => s.rank + | .extra (.inr .rightBase) => s.rightBase + | .extra (.inr .leftBase) => s.leftBase + | .extra (.inr .zero) => s.zero + | .extra (.inr .accumulator) => s.emitted.reverse ++ base (workTape .accumulator) + | k => base k + +@[simp] theorem tapes_rank (base : Arena u Extra → List Bool) (s : Snapshot) : + tapes base s (workTape .rank) = s.rank := rfl +@[simp] theorem tapes_rightBase (base : Arena u Extra → List Bool) (s : Snapshot) : + tapes base s (workTape .rightBase) = s.rightBase := rfl +@[simp] theorem tapes_leftBase (base : Arena u Extra → List Bool) (s : Snapshot) : + tapes base s (workTape .leftBase) = s.leftBase := rfl +@[simp] theorem tapes_zero (base : Arena u Extra → List Bool) (s : Snapshot) : + tapes base s (workTape .zero) = s.zero := rfl +@[simp] theorem tapes_accumulator (base : Arena u Extra → List Bool) (s : Snapshot) : + tapes base s (workTape .accumulator) = s.emitted.reverse ++ base (workTape .accumulator) := rfl +@[simp] theorem tapes_coefficient (base : Arena u Extra → List Bool) (s : Snapshot) : + tapes base s (workTape .coefficient) = base (workTape .coefficient) := rfl +@[simp] theorem tapes_dummy (base : Arena u Extra → List Bool) (s : Snapshot) : + tapes base s (workTape .dummy) = base (workTape .dummy) := rfl +@[simp] theorem tapes_leftBlock (base : Arena u Extra → List Bool) (s : Snapshot) : + tapes base s (workTape .leftBlock) = base (workTape .leftBlock) := rfl +@[simp] theorem tapes_queryTemporary (base : Arena u Extra → List Bool) (s : Snapshot) : + tapes base s (workTape .queryTemporary) = base (workTape .queryTemporary) := rfl +@[simp] theorem tapes_queryScratch (base : Arena u Extra → List Bool) (s : Snapshot) : + tapes base s (workTape .queryScratch) = base (workTape .queryScratch) := rfl +@[simp] theorem tapes_field (base : Arena u Extra → List Bool) (s : Snapshot) (j : Fin u) (k : Fin 6) : + tapes base s (.field j k) = base (.field j k) := rfl +@[simp] theorem tapes_current (base : Arena u Extra → List Bool) (s : Snapshot) (j : Fin u) : + tapes base s (.current j) = base (.current j) := rfl +@[simp] theorem tapes_formula (base : Arena u Extra → List Bool) (s : Snapshot) : + tapes base s .formula = base .formula := rfl +@[simp] theorem tapes_index (base : Arena u Extra → List Bool) (s : Snapshot) : + tapes base s .index = base .index := rfl +@[simp] theorem tapes_work (base : Arena u Extra → List Bool) (s : Snapshot) : + tapes base s .work = base .work := rfl +@[simp] theorem tapes_variableHeader (base : Arena u Extra → List Bool) (s : Snapshot) : + tapes base s variableHeader = base variableHeader := rfl +@[simp] theorem tapes_clauseHeader (base : Arena u Extra → List Bool) (s : Snapshot) : + tapes base s clauseHeader = base clauseHeader := rfl + +variable [DecidableEq Extra] + +theorem update_rank (base : Arena u Extra → List Bool) (s : Snapshot) (value : List Bool) : + Function.update (tapes base s) (workTape .rank) value = tapes base {s with rank := value} := by + funext k + cases k <;> try rfl + rename_i extra + cases extra with + | inl header => simp [tapes, workTape] + | inr role => cases role <;> simp [tapes, workTape] + +theorem update_rightBase (base : Arena u Extra → List Bool) (s : Snapshot) (value : List Bool) : + Function.update (tapes base s) (workTape .rightBase) value = tapes base {s with rightBase := value} := by + funext k + cases k <;> try rfl + rename_i extra + cases extra with + | inl header => simp [tapes, workTape] + | inr role => cases role <;> simp [tapes, workTape] + +theorem update_leftBase (base : Arena u Extra → List Bool) (s : Snapshot) (value : List Bool) : + Function.update (tapes base s) (workTape .leftBase) value = tapes base {s with leftBase := value} := by + funext k + cases k <;> try rfl + rename_i extra + cases extra with + | inl header => simp [tapes, workTape] + | inr role => cases role <;> simp [tapes, workTape] + +theorem update_zero (base : Arena u Extra → List Bool) (s : Snapshot) (value : List Bool) : + Function.update (tapes base s) (workTape .zero) value = tapes base {s with zero := value} := by + funext k + cases k <;> try rfl + rename_i extra + cases extra with + | inl header => simp [tapes, workTape] + | inr role => cases role <;> simp [tapes, workTape] + +theorem update_emitted (base : Arena u Extra → List Bool) (s : Snapshot) (value : List Bool) : + Function.update (tapes base s) (workTape .accumulator) + (value.reverse ++ base (workTape .accumulator)) = tapes base {s with emitted := value} := by + funext k + cases k <;> try rfl + rename_i extra + cases extra with + | inl header => simp [tapes, workTape] + | inr role => cases role <;> simp [tapes, workTape] + +theorem query_result (base : Arena u Extra → List Bool) (s : Snapshot) (bits : List Bool) : + SourceTestAppend.resultTapes queryLayout (tapes base s) bits = + tapes base {s with emitted := s.emitted ++ bits} := by + change Function.update (tapes base s) (workTape .accumulator) + (bits.reverse ++ tapes base s (workTape .accumulator)) = _ + rw [tapes_accumulator] + have h := update_emitted base s (s.emitted ++ bits) + simpa only [List.reverse_append, List.append_assoc] using h + +theorem horner_clause_result (base : Arena u Extra → List Bool) (s : Snapshot) (value : Nat) : + MachineHorner.resultTapes clauseRankSlots (tapes base s) value = + tapes base {s with rank := encodeWord value ++ s.rank} := by + change Function.update (tapes base s) (workTape .rank) + (encodeWord value ++ tapes base s (workTape .rank)) = _ + rw [tapes_rank, update_rank] + +theorem horner_variable_result (base : Arena u Extra → List Bool) (s : Snapshot) + (selected : SlotContext u) (value : Nat) : + MachineHorner.resultTapes (variableRankSlots selected) (tapes base s) value = + tapes base {s with rank := encodeWord value ++ s.rank} := by + change Function.update (tapes base s) (workTape .rank) + (encodeWord value ++ tapes base s (workTape .rank)) = _ + rw [tapes_rank, update_rank] + +theorem horner_right_result (base : Arena u Extra → List Bool) (s : Snapshot) (value : Nat) : + MachineHorner.resultTapes (baseSlots true) (tapes base s) value = + tapes base {s with rightBase := encodeWord value ++ s.rightBase} := by + change Function.update (tapes base s) (workTape .rightBase) + (encodeWord value ++ tapes base s (workTape .rightBase)) = _ + rw [tapes_rightBase, update_rightBase] + +theorem horner_left_result (base : Arena u Extra → List Bool) (s : Snapshot) (value : Nat) : + MachineHorner.resultTapes (baseSlots false) (tapes base s) value = + tapes base {s with leftBase := encodeWord value ++ s.leftBase} := by + change Function.update (tapes base s) (workTape .leftBase) + (encodeWord value ++ tapes base s (workTape .leftBase)) = _ + rw [tapes_leftBase, update_leftBase] + +structure WorkClean (base : Arena u Extra → List Bool) : Prop where + accA : base (workTape .accA) = [] + accB : base (workTape .accB) = [] + counter : base (workTape .counter) = [] + scratch : base (workTape .arithScratch) = [] + +omit [DecidableEq Extra] in +theorem clean_clause (base : Arena u Extra → List Bool) (s : Snapshot) (clean : WorkClean base) : + MachineHorner.Clean clauseRankSlots (tapes base s) where + accA := clean.accA + accB := clean.accB + counter := clean.counter + scratch := clean.scratch + +omit [DecidableEq Extra] in +theorem clean_variable (base : Arena u Extra → List Bool) (s : Snapshot) (selected : SlotContext u) + (clean : WorkClean base) : MachineHorner.Clean (variableRankSlots selected) (tapes base s) where + accA := clean.accA + accB := clean.accB + counter := clean.counter + scratch := clean.scratch + +omit [DecidableEq Extra] in +theorem clean_base (base : Arena u Extra → List Bool) (s : Snapshot) (right : Bool) + (clean : WorkClean base) : MachineHorner.Clean (baseSlots right) (tapes base s) where + accA := clean.accA + accB := clean.accB + counter := clean.counter + scratch := clean.scratch + +omit [DecidableEq Extra] in +theorem tapes_coordinateOutput {numVariables : ℕ} (j : Fin u) (clause : Target.Clause numVariables) + (base : Arena u Extra → List Bool) (s : Snapshot) : + tapes (SourceContextLoad.coordinateOutput j clause base) s = + SourceContextLoad.coordinateOutput j clause (tapes base s) := by + funext k + cases k <;> simp [tapes, SourceContextLoad.coordinateOutput, workTape] + rename_i extra + cases extra with + | inl header => rfl + | inr role => cases role <;> rfl + +omit [DecidableEq Extra] in + +theorem tapes_stageTapes (F : Target.Formula) (c : ClauseContext F u) + (base : Arena u Extra → List Bool) (s : Snapshot) (r : Nat) : + tapes (SourceContextLoad.stageTapes F c base r) s = + SourceContextLoad.stageTapes F c (tapes base s) r := by + induction r with + | zero => rfl + | succ r ih => + simp only [SourceContextLoad.stageTapes] + split + · rw [tapes_coordinateOutput, ih] + · exact ih + +theorem final_tapes (base : Arena u Extra → List Bool) (emitted : List Bool) + (hrank : base (workTape .rank) = []) (hright : base (workTape .rightBase) = []) + (hleft : base (workTape .leftBase) = []) (hzero : base (workTape .zero) = []) : + tapes base {emitted := emitted} = + Function.update base (workTape .accumulator) (emitted.reverse ++ base (workTape .accumulator)) := by + funext k + cases k <;> try rfl + rename_i extra + cases extra with + | inl header => simp [tapes, workTape] + | inr role => + cases role <;> simp_all [tapes, workTape] + +theorem empty_tapes (base : Arena u Extra → List Bool) + (hrank : base (workTape .rank) = []) (hright : base (workTape .rightBase) = []) + (hleft : base (workTape .leftBase) = []) (hzero : base (workTape .zero) = []) : + tapes base {} = base := by + simpa using final_tapes base [] hrank hright hleft hzero + +omit [DecidableEq Extra] in +theorem clear_loaded (F : Target.Formula) (c : ClauseContext F u) + (base : Arena u Extra → List Bool) (s : Snapshot) + (hfields : ∀ j k, base (.field j k) = []) (hindex : base .index = []) (hwork : base .work = []) : + SourceContextClear.outputTapes (tapes (SourceContextLoad.stageTapes F c base u) s) = tapes base s := by + rw [tapes_stageTapes] + exact SourceContextClear.output_loaded_eq_base F c (tapes base s) hfields hindex hwork + +def clearLoadedSnapshotInTime (F : Target.Formula) (c : ClauseContext F u) + (base : Arena u Extra → List Bool) (s : Snapshot) + (hfields : ∀ j k, base (.field j k) = []) (hindex : base .index = []) (hwork : base .work = []) + (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step SourceContextClear.program) + ⟨some SourceContextClear.main, ((), register), tapes (SourceContextLoad.stageTapes F c base u) s⟩ + (some ⟨none, ((), none), tapes base s⟩) + (6 * u * ((formulaBits F).length + 1) + 1) := by + rw [tapes_stageTapes] + exact SourceContextClear.clearLoadedToBaseInTime F c (tapes base s) hfields hindex hwork register + +end MinUncutGames.Foundations.Hastad.SourceTupleTape + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/Occurrences.lean b/lean/OAI/Computability/MinUncut/PCP/Occurrences.lean new file mode 100644 index 0000000000000000000000000000000000000000..b1582594368bf678ac13c7a90464dbb3b6489db3 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/Occurrences.lean @@ -0,0 +1,472 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.HonestTest +import OAI.Computability.MinUncut.PCP.ClauseVerifier +import OAI.Computability.MinUncut.Encoding.Serialization + +namespace OAI + +section +namespace MinUncutGames.Foundations.Hastad.SourceOccurrences + +open MinUncutGames.Reduction.CloneGap +open scoped BigOperators + +structure Encoding (α : Type) where + size : ℕ + code : α ≃ Fin size + +namespace Encoding + +def fin (n : ℕ) : Encoding (Fin n) := ⟨n, Equiv.refl _⟩ +def bool : Encoding Bool := ⟨2, finTwoEquiv.symm⟩ +def unit : Encoding Unit := ⟨1, finOneEquiv.symm⟩ + +def prod {α β : Type} (a : Encoding α) (b : Encoding β) : Encoding (α × β) := + ⟨a.size * b.size, (Equiv.prodCongr a.code b.code).trans finProdFinEquiv⟩ + +def sum {α β : Type} (a : Encoding α) (b : Encoding β) : Encoding (α ⊕ β) := + ⟨a.size + b.size, (Equiv.sumCongr a.code b.code).trans finSumFinEquiv⟩ + +def function {α β : Type} (a : Encoding α) (b : Encoding β) : Encoding (α → β) where + size := b.size ^ a.size + code := (show (α → β) ≃ (Fin a.size → Fin b.size) from + { toFun := fun f i => b.code (f (a.code.symm i)) + invFun := fun f x => b.code.symm (f (a.code x)) + left_inv := by intro f; funext x; simp + right_inv := by intro f; funext i; simp }).trans finFunctionFinEquiv + +def enumerate {α : Type} (a : Encoding α) : List α := List.ofFn a.code.symm + +@[simp] theorem length_enumerate {α : Type} (a : Encoding α) : + a.enumerate.length = a.size := by simp [enumerate] + +theorem mem_enumerate {α : Type} (a : Encoding α) (x : α) : x ∈ a.enumerate := by + rw [enumerate, List.mem_ofFn'] + exact ⟨a.code x, a.code.symm_apply_apply x⟩ + +theorem nodup_enumerate {α : Type} (a : Encoding α) : a.enumerate.Nodup := + List.nodup_ofFn_ofInjective a.code.symm.injective + +theorem card_eq_size {α : Type} [Fintype α] (a : Encoding α) : + Fintype.card α = a.size := by + simpa only [Fintype.card_fin] using Fintype.card_congr a.code + +end Encoding + +abbrev GlobalKey (V C I J : Type) := (V × Cube I) ⊕ ((C × Cube J) ⊕ Unit) + +def globalEncoding {V C I J : Type} + (v : Encoding V) (c : Encoding C) (i : Encoding I) (j : Encoding J) : + Encoding (GlobalKey V C I J) := + (v.prod (i.function Encoding.bool)).sum + ((c.prod (j.function Encoding.bool)).sum Encoding.unit) + +@[simp] theorem globalEncoding_size {V C I J : Type} + (v : Encoding V) (c : Encoding C) (i : Encoding I) (j : Encoding J) : + (globalEncoding v c i j).size = + v.size * 2 ^ i.size + (c.size * 2 ^ j.size + 1) := rfl + +def extendRestricted {J : Type} (valid : J → Bool) + (f : Cube {j : J // valid j = true}) : Cube J := + fun j => if h : valid j = true then f ⟨j, h⟩ else false + +@[simp] theorem extendRestricted_valid {J : Type} (valid : J → Bool) + (f : Cube {j : J // valid j = true}) (j : {j : J // valid j = true}) : + extendRestricted valid f j.val = f j := by simp [extendRestricted, j.property] + +theorem extendRestricted_injective {J : Type} (valid : J → Bool) : + Function.Injective (extendRestricted valid) := by + intro f g h + funext j + have := congrFun h j.val + simpa only [extendRestricted_valid] using this + +@[simp] theorem restrictQuery_extendRestricted {J : Type} (valid : J → Bool) + (f : Cube {j : J // valid j = true}) : + restrictQuery valid (extendRestricted valid f) = f := by + funext j + exact extendRestricted_valid valid f j + +@[simp] theorem canonicalInput_half {I : Type} [Fintype I] [DecidableEq I] + (i₀ : I) (f : HalfCube i₀) : + canonicalInput i₀ f.val = f := by + apply Subtype.ext + simp [canonicalInput, representative, f.property] + +def assignmentOfKey {V C I J : Type} + (v : Encoding V) (c : Encoding C) (i : Encoding I) (j : Encoding J) + (bits : GlobalKey V C I J → Bool) : Fin (globalEncoding v c i j).size → Bool := + fun q => bits ((globalEncoding v c i j).code.symm q) + +@[simp] theorem assignmentOfKey_code {V C I J : Type} + (v : Encoding V) (c : Encoding C) (i : Encoding I) (j : Encoding J) + (bits : GlobalKey V C I J → Bool) (key : GlobalKey V C I J) : + assignmentOfKey v c i j bits ((globalEncoding v c i j).code key) = bits key := by + exact congrArg bits ((globalEncoding v c i j).code.symm_apply_apply key) + +theorem assignmentOfKey_surjective {V C I J : Type} + (v : Encoding V) (c : Encoding C) (i : Encoding I) (j : Encoding J) : + Function.Surjective (assignmentOfKey v c i j) := by + intro bits + refine ⟨fun key => bits ((globalEncoding v c i j).code key), ?_⟩ + funext q + exact congrArg bits ((globalEncoding v c i j).code.apply_symm_apply q) + +section LocalEquations + +variable {V C I J : Type} [Fintype I] [DecidableEq I] [Fintype J] [DecidableEq J] + +def localAddress (vE : Encoding V) (cE : Encoding C) (iE : Encoding I) (jE : Encoding J) + (v : V) (c : C) (valid : J → Bool) (i₀ : I) (j₀ : {j : J // valid j = true}) : + FoldedEquation.Address i₀ j₀ → Fin (globalEncoding vE cE iE jE).size + | .inl f => (globalEncoding vE cE iE jE).code (.inl (v, f.val)) + | .inr g => (globalEncoding vE cE iE jE).code (.inr (.inl (c, extendRestricted valid g.val))) + +omit [Fintype I] [DecidableEq I] [Fintype J] [DecidableEq J] in +theorem localAddress_injective + (vE : Encoding V) (cE : Encoding C) (iE : Encoding I) (jE : Encoding J) + (v : V) (c : C) (valid : J → Bool) (i₀ : I) (j₀ : {j : J // valid j = true}) : + Function.Injective (localAddress vE cE iE jE v c valid i₀ j₀) := by + intro a b h + cases a with + | inl a => + cases b with + | inl b => + have h' := (globalEncoding vE cE iE jE).code.injective h + have hval : a.val = b.val := congrArg Prod.snd (Sum.inl.inj h') + exact congrArg Sum.inl (Subtype.ext hval) + | inr b => + have h' := (globalEncoding vE cE iE jE).code.injective h + cases h' + | inr a => + cases b with + | inl b => + have h' := (globalEncoding vE cE iE jE).code.injective h + cases h' + | inr b => + have h' := (globalEncoding vE cE iE jE).code.injective h + have hext := congrArg Prod.snd (Sum.inl.inj (Sum.inr.inj h')) + exact congrArg Sum.inr (Subtype.ext (extendRestricted_injective valid hext)) + +def conditionedOccurrence + (vE : Encoding V) (cE : Encoding C) (iE : Encoding I) (jE : Encoding J) + (v : V) (c : C) (valid : J → Bool) (π : J → I) + (i₀ : I) (j₀ : {j : J // valid j = true}) (f : Cube I) (g μ : Cube J) : + Equation (Fin (globalEncoding vE cE iE jE).size) := + mapEquation (localAddress vE cE iE jE v c valid i₀ j₀) + (FoldedEquation.conditionedEquation valid π i₀ j₀ f g μ) + +omit [Fintype I] [DecidableEq I] [Fintype J] [DecidableEq J] in +theorem conditionedOccurrence_satisfied + (vE : Encoding V) (cE : Encoding C) (iE : Encoding I) (jE : Encoding J) + (v : V) (c : C) (valid : J → Bool) (π : J → I) + (i₀ : I) (j₀ : {j : J // valid j = true}) + (bits : Fin (globalEncoding vE cE iE jE).size → Bool) + (f : Cube I) (g μ : Cube J) : + satisfied (conditionedOccurrence vE cE iE jE v c valid π i₀ j₀ f g μ) bits = + !(foldedAnswer i₀ (fun h => bits ((globalEncoding vE cE iE jE).code (.inl (v, h.val)))) f ^^ + conditionedFoldedAnswer valid j₀ + (fun h => bits ((globalEncoding vE cE iE jE).code + (.inr (.inl (c, extendRestricted valid h.val))))) g ^^ + conditionedFoldedAnswer valid j₀ + (fun h => bits ((globalEncoding vE cE iE jE).code + (.inr (.inl (c, extendRestricted valid h.val))))) (thirdQuery π f g μ)) := by + rw [conditionedOccurrence, satisfied_mapEquation] + let tableA : HalfCube i₀ → Bool := + fun h => bits ((globalEncoding vE cE iE jE).code (.inl (v, h.val))) + let tableB : HalfCube j₀ → Bool := + fun h => bits ((globalEncoding vE cE iE jE).code + (.inr (.inl (c, extendRestricted valid h.val)))) + have hbits : bits ∘ localAddress vE cE iE jE v c valid i₀ j₀ = + FoldedEquation.storedAssignment tableA tableB := by + funext a + cases a <;> rfl + rw [hbits] + exact FoldedEquation.conditionedEquation_satisfied valid π i₀ j₀ tableA tableB f g μ + +end LocalEquations + +def findValid {J : Type} (valid : J → Bool) : List J → Option {j : J // valid j = true} + | [] => none + | j :: rest => if h : valid j = true then some ⟨j, h⟩ else findValid valid rest + +theorem findValid_none_iff {J : Type} (valid : J → Bool) (xs : List J) : + findValid valid xs = none ↔ ∀ j ∈ xs, valid j = false := by + induction xs with + | nil => simp [findValid] + | cons j xs ih => + by_cases hj : valid j = true + · simp [findValid, hj] + · simp [findValid, hj, ih] + +def firstValid {J : Type} (e : Encoding J) (valid : J → Bool) : + Option {j : J // valid j = true} := findValid valid e.enumerate + +theorem firstValid_none_iff {J : Type} (e : Encoding J) (valid : J → Bool) : + firstValid e valid = none ↔ ∀ j, valid j = false := by + rw [firstValid, findValid_none_iff] + exact ⟨fun h j => h j (e.mem_enumerate j), fun h j _ => h j⟩ + +def occurrenceList {Tape Name : Type} (tape : Encoding Tape) + (emit : Tape → Equation Name) : List (Equation Name) := tape.enumerate.map emit + +@[simp] theorem occurrenceList_length {Tape Name : Type} (tape : Encoding Tape) + (emit : Tape → Equation Name) : (occurrenceList tape emit).length = tape.size := by + simp [occurrenceList] + +private theorem countP_cast_eq_sum {α : Type} (xs : List α) (p : α → Bool) : + (xs.countP p : ℝ) = (xs.map (fun x => if p x then (1 : ℝ) else 0)).sum := by + induction xs with + | nil => simp + | cons x xs ih => cases hp : p x <;> simp [hp, ih, add_comm] + +theorem countP_enumerate {Tape : Type} [Fintype Tape] + (tape : Encoding Tape) (p : Tape → Bool) : + (tape.enumerate.countP p : ℝ) = ∑ x, if p x then (1 : ℝ) else 0 := by + rw [countP_cast_eq_sum] + simp only [Encoding.enumerate, List.map_ofFn, List.sum_ofFn] + exact Fintype.sum_equiv tape.code.symm _ _ (fun _ => rfl) + +theorem occurrenceList_acceptance {Tape Name : Type} [Fintype Tape] + (tape : Encoding Tape) (emit : Tape → Equation Name) (bits : Name → Bool) : + ((occurrenceList tape emit).countP (fun e => satisfied e bits) : ℝ) / + (occurrenceList tape emit).length = + 𝔼 x, if satisfied (emit x) bits then (1 : ℝ) else 0 := by + rw [occurrenceList_length, Fintype.expect_eq_sum_div_card, tape.card_eq_size] + congr 1 + simpa only [occurrenceList, List.countP_map, Function.comp_def] using + countP_enumerate tape (fun x => satisfied (emit x) bits) + +section ConcreteSource + +open SourceContexts +open MinUncutGames.Reduction.FiniteNoise + +def clauseAnswerEncoding : Encoding PCP.ClauseAnswer := ⟨8, clauseAnswerFinEquiv⟩ + +def slotEncoding : Encoding PCP.Slot where + size := 3 + code := + { toFun := fun s => match s with | .first => 0 | .second => 1 | .third => 2 + invFun := fun i => if i.val = 0 then .first else if i.val = 1 then .second else .third + left_inv := by intro s; cases s <;> rfl + right_inv := by decide } + +def iEncoding (u : ℕ) : Encoding (I u) := (Encoding.fin u).function Encoding.bool +def jEncoding (u : ℕ) : Encoding (J u) := (Encoding.fin u).function clauseAnswerEncoding +def variableEncoding (F : Target.Formula) (u : ℕ) : Encoding (VariableContext F u) := + (Encoding.fin u).function (Encoding.fin F.«variables») +def clauseEncoding (F : Target.Formula) (u : ℕ) : Encoding (ClauseContext F u) := + (Encoding.fin u).function (Encoding.fin F.clauses.length) +def slotContextEncoding (u : ℕ) : Encoding (SlotContext u) := + (Encoding.fin u).function slotEncoding + +def proofEncoding (F : Target.Formula) (u : ℕ) : + Encoding (GlobalKey (VariableContext F u) (ClauseContext F u) (I u) (J u)) := + globalEncoding (variableEncoding F u) (clauseEncoding F u) (iEncoding u) (jEncoding u) + +def nBits (F : Target.Formula) (u : ℕ) : ℕ := (proofEncoding F u).size + +@[simp] theorem nBits_eq (F : Target.Formula) (u : ℕ) : + nBits F u = F.«variables» ^ u * 2 ^ (2 ^ u) + + (F.clauses.length ^ u * 2 ^ (8 ^ u) + 1) := rfl + +def dummyIndex (F : Target.Formula) (u : ℕ) : Fin (nBits F u) := + (proofEncoding F u).code (.inr (.inr ())) + +def leftAnchor (u : ℕ) : I u := fun _ => false + +def rightAnchor (F : Target.Formula) {u : ℕ} (c : ClauseContext F u) : + Option {j : J u // validJ F c j = true} := firstValid (jEncoding u) (validJ F c) + +theorem rightAnchor_none_iff (F : Target.Formula) {u : ℕ} (c : ClauseContext F u) : + rightAnchor F c = none ↔ ∀ j : J u, validJ F c j = false := + firstValid_none_iff _ _ + +def halfTableKeyAssignment (F : Target.Formula) (u : ℕ) + (a : VariableContext F u → HalfCube (leftAnchor u) → Bool) + (b : ∀ c : ClauseContext F u, ∀ j₀ : {j : J u // validJ F c j = true}, + HalfCube j₀ → Bool) : + GlobalKey (VariableContext F u) (ClauseContext F u) (I u) (J u) → Bool + | .inl (v, f) => a v (canonicalInput (leftAnchor u) f) + | .inr (.inl (c, g)) => + match rightAnchor F c with + | none => false + | some j₀ => b c j₀ (canonicalInput j₀ (restrictQuery (validJ F c) g)) + | .inr (.inr _) => false + +def extendHalfTables (F : Target.Formula) (u : ℕ) + (a : VariableContext F u → HalfCube (leftAnchor u) → Bool) + (b : ∀ c : ClauseContext F u, ∀ j₀ : {j : J u // validJ F c j = true}, + HalfCube j₀ → Bool) : Fin (nBits F u) → Bool := + assignmentOfKey (variableEncoding F u) (clauseEncoding F u) (iEncoding u) (jEncoding u) + (halfTableKeyAssignment F u a b) + +@[simp] theorem extendHalfTables_left (F : Target.Formula) (u : ℕ) + (a : VariableContext F u → HalfCube (leftAnchor u) → Bool) + (b : ∀ c : ClauseContext F u, ∀ j₀ : {j : J u // validJ F c j = true}, + HalfCube j₀ → Bool) (v : VariableContext F u) (h : HalfCube (leftAnchor u)) : + extendHalfTables F u a b ((proofEncoding F u).code (.inl (v, h.val))) = a v h := by + calc + _ = halfTableKeyAssignment F u a b (.inl (v, h.val)) := + assignmentOfKey_code (variableEncoding F u) (clauseEncoding F u) (iEncoding u) + (jEncoding u) (halfTableKeyAssignment F u a b) (.inl (v, h.val)) + _ = a v h := congrArg (a v) (canonicalInput_half (leftAnchor u) h) + +theorem extendHalfTables_right (F : Target.Formula) (u : ℕ) + (a : VariableContext F u → HalfCube (leftAnchor u) → Bool) + (b : ∀ c : ClauseContext F u, ∀ j₀ : {j : J u // validJ F c j = true}, + HalfCube j₀ → Bool) (c : ClauseContext F u) + (j₀ : {j : J u // validJ F c j = true}) (hanchor : rightAnchor F c = some j₀) + (h : HalfCube j₀) : + extendHalfTables F u a b ((proofEncoding F u).code + (.inr (.inl (c, extendRestricted (validJ F c) h.val)))) = b c j₀ h := by + calc + _ = halfTableKeyAssignment F u a b + (.inr (.inl (c, extendRestricted (validJ F c) h.val))) := + assignmentOfKey_code (variableEncoding F u) (clauseEncoding F u) (iEncoding u) + (jEncoding u) (halfTableKeyAssignment F u a b) _ + _ = b c j₀ h := by + simp only [halfTableKeyAssignment, hanchor] + rw [restrictQuery_extendRestricted, canonicalInput_half] + +def emptyAddress (F : Target.Formula) (u : ℕ) (v : VariableContext F u) : + EmptyContext.Address (leftAnchor u) → Fin (nBits F u) + | .inl h => (proofEncoding F u).code (.inl (v, h.val)) + | .inr _ => dummyIndex F u + +def contextEquation (F : Target.Formula) (u D : ℕ) + (c : ClauseContext F u) (v : VariableContext F u) + (t : SourceTape.TestTape (I u) (J u) D) : Equation (Fin (nBits F u)) := + match rightAnchor F c with + | none => mapEquation (emptyAddress F u v) (EmptyContext.equation (leftAnchor u) t.1) + | some j₀ => conditionedOccurrence (variableEncoding F u) (clauseEncoding F u) + (iEncoding u) (jEncoding u) v c (validJ F c) (pi F c v) (leftAnchor u) j₀ + t.1 t.2.2 (realizedNoise t.2.1) + +def leftResponse (F : Target.Formula) (u : ℕ) (bits : Fin (nBits F u) → Bool) + (v : VariableContext F u) : Cube (I u) → Bool := + foldedAnswer (leftAnchor u) (fun h => bits ((proofEncoding F u).code (.inl (v, h.val)))) + +def rightResponse (F : Target.Formula) (u : ℕ) (bits : Fin (nBits F u) → Bool) + (c : ClauseContext F u) : Cube (J u) → Bool := + match rightAnchor F c with + | none => fun _ => false + | some j₀ => conditionedFoldedAnswer (validJ F c) j₀ + (fun h => bits ((proofEncoding F u).code (.inr (.inl (c, extendRestricted (validJ F c) h.val))))) + +theorem contextEquation_satisfied (F : Target.Formula) (u D : ℕ) + (c : ClauseContext F u) (v : VariableContext F u) + (t : SourceTape.TestTape (I u) (J u) D) (bits : Fin (nBits F u) → Bool) : + satisfied (contextEquation F u D c v t) bits = + !(leftResponse F u bits v t.1 ^^ rightResponse F u bits c t.2.2 ^^ + rightResponse F u bits c (thirdQuery (pi F c v) t.1 t.2.2 (realizedNoise t.2.1))) := by + cases ha : rightAnchor F c with + | none => + simp only [contextEquation, ha, satisfied_mapEquation, EmptyContext.equation_satisfied, + rightResponse, Bool.xor_false] + rfl + | some j₀ => + simp only [contextEquation, ha, rightResponse] + exact conditionedOccurrence_satisfied (variableEncoding F u) (clauseEncoding F u) + (iEncoding u) (jEncoding u) v c (validJ F c) (pi F c v) (leftAnchor u) j₀ + bits t.1 t.2.2 (realizedNoise t.2.1) + +def testTapeEncoding (u D : ℕ) : Encoding (SourceTape.TestTape (I u) (J u) D) := + ((iEncoding u).function Encoding.bool).prod + (((jEncoding u).function (Encoding.fin D)).prod ((jEncoding u).function Encoding.bool)) + +abbrev SourceIndex (F : Target.Formula) (u D : ℕ) := + (ClauseContext F u × SlotContext u) × SourceTape.TestTape (I u) (J u) D + +def sourceIndexEncoding (F : Target.Formula) (u D : ℕ) : Encoding (SourceIndex F u D) := + ((clauseEncoding F u).prod (slotContextEncoding u)).prod (testTapeEncoding u D) + +def sourceEquation (F : Target.Formula) (u D : ℕ) (p : SourceIndex F u D) : + Equation (Fin (nBits F u)) := + contextEquation F u D p.1.1 (sampledVariables F p.1.1 p.1.2) p.2 + +def rawSourceList (F : Target.Formula) (u D : ℕ) : List (Equation (Fin (nBits F u))) := + occurrenceList (sourceIndexEncoding F u D) (sourceEquation F u D) + +@[simp] theorem rawSourceList_length (F : Target.Formula) (u D : ℕ) : + (rawSourceList F u D).length = + (F.clauses.length ^ u * 3 ^ u) * + (2 ^ (2 ^ u) * (D ^ (8 ^ u) * 2 ^ (8 ^ u))) := by + rw [rawSourceList, occurrenceList_length] + rfl + +theorem rawSourceList_acceptance (F : Target.Formula) (u D : ℕ) + (hD : 0 < D) (bits : Fin (nBits F u) → Bool) : + ((rawSourceList F u D).countP (fun e => satisfied e bits) : ℝ) / + (rawSourceList F u D).length = + 𝔼 c : ClauseContext F u, 𝔼 s : SlotContext u, + testAcceptance ((D : ℝ)⁻¹) (pi F c (sampledVariables F c s)) + (leftResponse F u bits (sampledVariables F c s)) (rightResponse F u bits c) := by + rw [rawSourceList, occurrenceList_acceptance, SourceTape.expect_prod] + rw [SourceTape.expect_prod] + apply Finset.expect_congr rfl + intro c _ + apply Finset.expect_congr rfl + intro s _ + rw [← SourceTape.tapeAcceptance_eq_testAcceptance hD] + unfold SourceTape.tapeAcceptance + apply Finset.expect_congr rfl + intro t _ + rw [sourceEquation, contextEquation_satisfied] + cases h : leftResponse F u bits (sampledVariables F c s) t.1 ^^ + rightResponse F u bits c t.2.2 ^^ + rightResponse F u bits c + (thirdQuery (pi F c (sampledVariables F c s)) t.1 t.2.2 (realizedNoise t.2.1)) <;> rfl + +def emptyFormulaEquation (F : Target.Formula) (u : ℕ) : Equation (Fin (nBits F u)) := + ⟨dummyIndex F u, dummyIndex F u, dummyIndex F u, false⟩ + +def sourceList (F : Target.Formula) (u D : ℕ) : List (Equation (Fin (nBits F u))) := + if F.clauses.isEmpty then [emptyFormulaEquation F u] else rawSourceList F u D + +theorem sourceList_empty (F : Target.Formula) (u D : ℕ) (h : F.clauses = []) : + sourceList F u D = [emptyFormulaEquation F u] := by simp [sourceList, h] + +theorem sourceList_nonempty (F : Target.Formula) (u D : ℕ) (h : F.clauses ≠ []) : + sourceList F u D = rawSourceList F u D := by + unfold sourceList + rw [List.isEmpty_eq_false_iff.mpr h] + rfl + +theorem sourceList_length_le_raw_add_one (F : Target.Formula) (u D : ℕ) : + (sourceList F u D).length ≤ (rawSourceList F u D).length + 1 := by + by_cases h : F.clauses = [] + · rw [sourceList_empty F u D h] + rw [List.length_singleton] + omega + · rw [sourceList_nonempty F u D h] + omega + +theorem sourceList_ne_nil (F : Target.Formula) (u D : ℕ) (hD : 0 < D) : + sourceList F u D ≠ [] := by + by_cases h : F.clauses = [] + · rw [sourceList_empty F u D h] + simp + · rw [sourceList_nonempty F u D h] + apply List.length_pos_iff.mp + rw [rawSourceList_length] + have hc : 0 < F.clauses.length := List.length_pos_iff.mpr h + positivity + +def sourceInput (F : Target.Formula) (u D : ℕ) (hD : 0 < D) : + MinUncutGames.Reduction.SourceEncoding.Input := + ⟨nBits F u, sourceList F u D, sourceList_ne_nil F u D hD⟩ + +theorem emptyFormulaEquation_satisfied (F : Target.Formula) (u : ℕ) + (bits : Fin (nBits F u) → Bool) : + satisfied (emptyFormulaEquation F u) bits = !(bits (dummyIndex F u)) := by + cases h : bits (dummyIndex F u) <;> simp [emptyFormulaEquation, satisfied, h] + +end ConcreteSource + +end MinUncutGames.Foundations.Hastad.SourceOccurrences + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/Overlap.lean b/lean/OAI/Computability/MinUncut/PCP/Overlap.lean new file mode 100644 index 0000000000000000000000000000000000000000..3632d872ce234aed4d5a1c864c06f3110a200b4c --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/Overlap.lean @@ -0,0 +1,721 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.DistributionMaps +import OAI.Computability.MinUncut.Games.LabelBound + +namespace OAI + +namespace MinUncutGames.Foundations.Repetition + +open scoped BigOperators +open Information + +private theorem min_half_formula (x y : ℝ) : + min x y = (x + y - |x - y|) / 2 := 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 + +theorem sum_min_one_sub_tv {Ω : Type*} [Fintype Ω] + (p q : Ω → ℝ) (hp : IsProbability p) (hq : IsProbability q) : + (∑ z, min (p z) (q z)) = 1 - totalVariation p q := by + classical + simp_rw [min_half_formula] + simp only [div_eq_mul_inv, ← Finset.sum_mul, Finset.sum_sub_distrib, + Finset.sum_add_distrib, hp.2, hq.2, totalVariation] + ring + +private theorem discount_le_self {c t : ℝ} (hc : 0 ≤ c) (ht : 0 ≤ t) : + c / (1 + t) ≤ c := by + apply (div_le_iff₀ (by linarith : 0 < 1 + t)).2 + nlinarith [mul_nonneg hc ht] + +private theorem discount_loss_le_mul {c t : ℝ} (hc : 0 ≤ c) (ht : 0 ≤ t) : + c - c / (1 + t) ≤ c * t := by + have hd : 0 < 1 + t := by linarith + have hid : c - c / (1 + t) = c * t / (1 + t) := by + field_simp [hd.ne'] + ring + rw [hid] + apply (div_le_iff₀ hd).2 + nlinarith [mul_nonneg (mul_nonneg hc ht) ht] + +noncomputable def discountedCommonMass {X S : Type*} [Fintype X] [Fintype S] + (p a b : X × S → ℝ) (t : X → ℝ) : ℝ := + ∑ z, min (p z) (min (a z) (b z)) / (1 + t z.1) + +theorem discounted_common_mass_bounds {X S : Type*} [Fintype X] [Fintype S] + (p a b : X × S → ℝ) (μ t : X → ℝ) + (hp : IsProbability p) (ha : IsProbability a) (hb : IsProbability b) + (ht : ∀ x, 0 ≤ t x) + (hrow : ∀ x, (∑ s, a (x, s)) = μ x) + (htv : (∑ x, μ x * t x) = totalVariation a b) : + 1 - 2 * totalVariation p a - 2 * totalVariation p b ≤ discountedCommonMass p a b t ∧ + discountedCommonMass p a b t ≤ 1 := by + classical + let C : X × S → ℝ := fun z => min (p z) (min (a z) (b z)) + have hC0 : ∀ z, 0 ≤ C z := by + intro z + exact le_min (hp.1 z) (le_min (ha.1 z) (hb.1 z)) + have hCp : ∀ z, C z ≤ p z := by + intro z + exact min_le_left _ _ + have hCa : ∀ z, C z ≤ a z := by + intro z + exact (min_le_right _ _).trans (min_le_left _ _) + have hmass : 1 - totalVariation p a - totalVariation p b ≤ ∑ z, C z := by + have hpoint : ∀ z, min (p z) (a z) + min (p z) (b z) - p z ≤ C z := by + intro z + dsimp [C] + refine le_min ?_ (le_min ?_ ?_) + · linarith [min_le_left (p z) (a z), min_le_left (p z) (b z)] + · linarith [min_le_right (p z) (a z), min_le_left (p z) (b z)] + · linarith [min_le_right (p z) (b z), min_le_left (p z) (a z)] + have hsum := Finset.sum_le_sum + (fun z (_ : z ∈ (Finset.univ : Finset (X × S))) => hpoint z) + simp only [Finset.sum_sub_distrib, Finset.sum_add_distrib] at hsum + rw [sum_min_one_sub_tv p a hp ha, sum_min_one_sub_tv p b hp hb, hp.2] at hsum + linarith + have hrowC : ∀ x, (∑ s, C (x, s)) ≤ μ x := by + intro x + calc + (∑ s, C (x, s)) ≤ ∑ s, a (x, s) := Finset.sum_le_sum (fun s _ => hCa (x, s)) + _ = μ x := hrow x + have hweighted : (∑ z, C z * t z.1) ≤ totalVariation a b := by + rw [← htv, Fintype.sum_prod_type] + apply Finset.sum_le_sum + intro x _ + change (∑ s, C (x, s) * t x) ≤ μ x * t x + rw [← Finset.sum_mul] + exact mul_le_mul_of_nonneg_right (hrowC x) (ht x) + have hloss : (∑ z, C z) - discountedCommonMass p a b t ≤ ∑ z, C z * t z.1 := by + change (∑ z, C z) - (∑ z, C z / (1 + t z.1)) ≤ ∑ z, C z * t z.1 + rw [← Finset.sum_sub_distrib] + exact Finset.sum_le_sum (fun z _ => discount_loss_le_mul (hC0 z) (ht z.1)) + have htriangle : totalVariation a b ≤ totalVariation p a + totalVariation p b := by + have h := totalVariation_triangle a p b + rw [totalVariation_symm a p] at h + exact h + have hupper : discountedCommonMass p a b t ≤ 1 := by + change (∑ z, C z / (1 + t z.1)) ≤ 1 + calc + _ ≤ ∑ z, p z := Finset.sum_le_sum + (fun z _ => (discount_le_self (hC0 z) (ht z.1)).trans (hCp z)) + _ = 1 := hp.2 + exact ⟨by linarith, hupper⟩ + +noncomputable def diagonalWeights {X S : Type*} [Fintype X] [Fintype S] + (p : X × S → ℝ) : X × S × S → ℝ := by + classical + exact fun z => if z.2.1 = z.2.2 then p (z.1, z.2.1) else 0 + +theorem diagonalWeights_isProbability {X S : Type*} [Fintype X] [Fintype S] + (p : X × S → ℝ) (hp : IsProbability p) : IsProbability (diagonalWeights p) := by + classical + constructor + · intro z + dsimp [diagonalWeights] + split + · exact hp.1 _ + · exact le_rfl + · simpa [diagonalWeights, Fintype.sum_prod_type] using hp.2 + +theorem diagonal_overlap_identity {X S : Type*} [Fintype X] [Fintype S] + (p : X × S → ℝ) (sim : X × S × S → ℝ) + (hp : IsProbability p) (hsim : IsProbability sim) : + totalVariation sim (diagonalWeights p) = + 1 - ∑ z : X × S, min (p z) (sim (z.1, z.2, z.2)) := by + classical + have h := sum_min_one_sub_tv sim (diagonalWeights p) hsim (diagonalWeights_isProbability p hp) + have heq : (∑ z, min (sim z) (diagonalWeights p z)) = + ∑ z : X × S, min (p z) (sim (z.1, z.2, z.2)) := by + simp only [Fintype.sum_prod_type, diagonalWeights] + apply Finset.sum_congr rfl + intro x _ + apply Finset.sum_congr rfl + intro s _ + have hpoint : ∀ s', min (sim (x, s, s')) (if s = s' then p (x, s) else 0) = + if s = s' then min (p (x, s)) (sim (x, s, s')) else 0 := by + intro s' + by_cases he : s = s' + · simp [he, min_comm] + · simp [he, min_eq_right (hsim.1 (x, s, s'))] + simp only [hpoint] + simp + rw [heq] at h + linarith + +theorem diagonal_sampler_totalVariation_le {X S : Type*} [Fintype X] [Fintype S] + (p : X × S → ℝ) (μ : X → ℝ) (L R : X → S → ℝ) + (sim : X × S × S → ℝ) (hp : IsProbability p) (hμ : IsProbability μ) + (hL : ∀ x, IsProbability (L x)) (hR : ∀ x, IsProbability (R x)) + (hsim : IsProbability sim) {τ : ℝ} (hτ0 : 0 ≤ τ) (hτ1 : τ ≤ 1) + (hdiag : ∀ x s, μ x * min (L x s) (R x s) / + (1 + totalVariation (L x) (R x)) * (1 - τ) ≤ sim (x, s, s)) : + totalVariation sim (diagonalWeights p) ≤ + 2 * totalVariation p (fun z => μ z.1 * L z.1 z.2) + + 2 * totalVariation p (fun z => μ z.1 * R z.1 z.2) + τ := by + classical + let a : X × S → ℝ := fun z => μ z.1 * L z.1 z.2 + let b : X × S → ℝ := fun z => μ z.1 * R z.1 z.2 + let t : X → ℝ := fun x => totalVariation (L x) (R x) + let C : X × S → ℝ := fun z => min (p z) (min (a z) (b z)) + have ha : IsProbability a := kernelProduct_isProbability μ L hμ hL + have hb : IsProbability b := kernelProduct_isProbability μ R hμ hR + have ht : ∀ x, 0 ≤ t x := fun x => totalVariation_nonneg (L x) (R x) + have hrow : ∀ x, (∑ s, a (x, s)) = μ x := by + intro x + simp only [a, ← Finset.mul_sum, (hL x).2, mul_one] + have htv : (∑ x, μ x * t x) = totalVariation a b := + (totalVariation_joint_common_weights μ L R hμ.1).symm + obtain ⟨hBlower, hBupper⟩ := discounted_common_mass_bounds p a b μ t hp ha hb ht hrow htv + have hpoint : ∀ z : X × S, + (1 - τ) * (C z / (1 + t z.1)) ≤ min (p z) (sim (z.1, z.2, z.2)) := by + intro z + have hden : 0 < 1 + t z.1 := by linarith [ht z.1] + have hC0 : 0 ≤ C z := le_min (hp.1 z) (le_min (ha.1 z) (hb.1 z)) + have hCp : C z ≤ p z := min_le_left _ _ + have hdisc0 : 0 ≤ C z / (1 + t z.1) := div_nonneg hC0 hden.le + have hmin : min (a z) (b z) = μ z.1 * min (L z.1 z.2) (R z.1 z.2) := by + dsimp [a, b] + rcases le_total (L z.1 z.2) (R z.1 z.2) with h | h + · rw [min_eq_left h, min_eq_left (mul_le_mul_of_nonneg_left h (hμ.1 z.1))] + · rw [min_eq_right h, min_eq_right (mul_le_mul_of_nonneg_left h (hμ.1 z.1))] + have hCmin : C z ≤ μ z.1 * min (L z.1 z.2) (R z.1 z.2) := by + rw [← hmin] + exact min_le_right _ _ + apply le_min + · calc + _ ≤ 1 * (C z / (1 + t z.1)) := + mul_le_mul_of_nonneg_right (by linarith) hdisc0 + _ ≤ C z := by simpa using discount_le_self hC0 (ht z.1) + _ ≤ p z := hCp + · have hd := mul_le_mul_of_nonneg_left + (div_le_div_of_nonneg_right hCmin hden.le) (by linarith : 0 ≤ 1 - τ) + calc + _ ≤ (1 - τ) * (μ z.1 * min (L z.1 z.2) (R z.1 z.2) / (1 + t z.1)) := hd + _ ≤ sim (z.1, z.2, z.2) := by + simpa only [t, mul_comm] using hdiag z.1 z.2 + have hsum := Finset.sum_le_sum (fun z (_ : z ∈ (Finset.univ : Finset (X × S))) => hpoint z) + rw [← Finset.mul_sum] at hsum + change (1 - τ) * discountedCommonMass p a b t ≤ _ at hsum + rw [diagonal_overlap_identity p sim hp hsim] + have hτB := mul_le_mul_of_nonneg_left hBupper hτ0 + change 1 - _ ≤ 2 * totalVariation p a + 2 * totalVariation p b + τ + nlinarith + +open scoped BigOperators +open Games +noncomputable section + +universe u + +def TraceSeed (σ : Type u) : Nat → Type u + | 0 => PUnit + | n + 1 => σ × TraceSeed σ n + +instance traceSeedFintype {σ : Type*} [Fintype σ] (n : Nat) : Fintype (TraceSeed σ n) := by + induction n with + | zero => exact inferInstanceAs (Fintype PUnit) + | succ n ih => exact inferInstanceAs (Fintype (σ × TraceSeed σ n)) + +instance traceSeedUniqueZero {σ : Type*} : Unique (TraceSeed σ 0) := + inferInstanceAs (Unique PUnit) + +def traceList {σ : Type*} : (n : Nat) → TraceSeed σ n → List σ + | 0, _ => [] + | n + 1, seed => seed.1 :: traceList n seed.2 + +def traceSeedLaw {σ : Type*} [Fintype σ] (μ : FiniteDistribution σ) : + (n : Nat) → FiniteDistribution (TraceSeed σ n) + | 0 => { weight := fun _ => 1, nonnegative := by intro; norm_num, + normalized := by simp } + | n + 1 => μ.product (traceSeedLaw μ n) + +theorem traceSeedLaw_expectation {σ : Type*} [Fintype σ] + (μ : FiniteDistribution σ) (n : Nat) (f : List σ → ℝ) : + (traceSeedLaw μ n).expectation (fun seed => f (traceList n seed)) = + CorrelatedSampling.traceAverage μ.weight n f := by + induction n generalizing f with + | zero => simp [traceSeedLaw, traceList, FiniteDistribution.expectation, + CorrelatedSampling.traceAverage] + | succ n ih => + change (μ.product (traceSeedLaw μ n)).expectation + (fun seed => f (seed.1 :: traceList n seed.2)) = _ + rw [FiniteDistribution.expectation_product] + simp only [CorrelatedSampling.traceAverage, FiniteDistribution.expectation] + apply Finset.sum_congr rfl + intro s _ + congr 1 + exact ih (fun xs => f (s :: xs)) + +def sharedOutputLaw {X Y S Seed : Type*} + [Fintype X] [Fintype Y] [Fintype S] [Fintype Seed] [DecidableEq S] + (μ : FiniteDistribution (X × Y)) (seedLaw : FiniteDistribution Seed) + (left : Seed → X → S) (right : Seed → Y → S) : + FiniteDistribution ((X × Y) × S × S) := + (μ.product seedLaw).pushforward + (fun z => (z.1, left z.2 z.1.1, right z.2 z.1.2)) + +theorem sharedOutputLaw_weight {X Y S Seed : Type*} + [Fintype X] [Fintype Y] [Fintype S] [Fintype Seed] [DecidableEq S] + (μ : FiniteDistribution (X × Y)) (seedLaw : FiniteDistribution Seed) + (left : Seed → X → S) (right : Seed → Y → S) (x : X) (y : Y) (a b : S) : + (sharedOutputLaw μ seedLaw left right).weight ((x,y),a,b) = + μ.weight (x,y) * seedLaw.expectation + (fun seed => if left seed x = a ∧ right seed y = b then 1 else 0) := by + classical + simp only [sharedOutputLaw, FiniteDistribution.pushforward, + FiniteDistribution.product, Fintype.sum_prod_type, Prod.mk.injEq] + simp only [and_assoc, ite_and] + simp [FiniteDistribution.expectation, Finset.mul_sum, mul_ite] + +open CorrelatedSampling + +variable {X Y S : Type*} [Fintype X] [Fintype Y] [Fintype S] + [Nonempty S] [DecidableEq S] + +def samplerLocal (thresholds : List ℝ) (profile : X → FiniteDistribution S) + (fallback : S) (n : Nat) (seed : TraceSeed (RectangleSeed thresholds S) n) + (x : X) : S := + localSample (rectangleAccept thresholds (profile x).weight) Prod.fst fallback + (traceList n seed) + +def samplerOutputLaw (thresholds : List ℝ) (μ : FiniteDistribution (X × Y)) + (L : X → FiniteDistribution S) (R : Y → FiniteDistribution S) + (fallback : S) (n : Nat) : FiniteDistribution ((X × Y) × S × S) := + sharedOutputLaw μ (traceSeedLaw (rectangleDistribution thresholds) n) + (samplerLocal thresholds L fallback n) (samplerLocal thresholds R fallback n) + +omit [Nonempty S] [DecidableEq S] in +theorem probability_weight_le_one (μ : 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 + +theorem samplerOutputLaw_diagonal (thresholds : List ℝ) + (μ : FiniteDistribution (X × Y)) + (L : X → FiniteDistribution S) (R : Y → FiniteDistribution S) + (hL : ∀ x s, (L x).weight s ∈ thresholds) + (hR : ∀ y s, (R y).weight s ∈ thresholds) + (fallback : S) (n : Nat) (x : X) (y : Y) (a : S) : + μ.weight (x,y) * min ((L x).weight a) ((R y).weight a) / + (1 + Information.totalVariation (L x).weight (R y).weight) * + (1 - eventMass (rectangleWeight thresholds) + (fun s => !(rectangleAccept thresholds (L x).weight s || + rectangleAccept thresholds (R y).weight s)) ^ n) ≤ + (samplerOutputLaw thresholds μ L R fallback n).weight ((x,y),a,a) := by + have h := rectangle_label_diagonal_bound thresholds (L x).weight (R y).weight + fallback a (hL x) (hR y) (L x).nonnegative (R y).nonnegative + (probability_weight_le_one (L x)) (probability_weight_le_one (R y)) + (L x).normalized (R y).normalized n + rw [samplerOutputLaw, sharedOutputLaw_weight] + have he : (traceSeedLaw (rectangleDistribution (α := S) thresholds) n).expectation + (fun seed => if samplerLocal thresholds L fallback n seed x = a ∧ + samplerLocal thresholds R fallback n seed y = a then 1 else 0) = + traceAverage (rectangleWeight thresholds) n + (localDiagonal (rectangleAccept thresholds (L x).weight) + (rectangleAccept thresholds (R y).weight) Prod.fst fallback a) := by + exact traceSeedLaw_expectation (rectangleDistribution (α := S) thresholds) n + (localDiagonal (rectangleAccept thresholds (L x).weight) + (rectangleAccept thresholds (R y).weight) Prod.fst fallback a) + rw [he] + simp only [Information.totalVariation, CorrelatedSampling.totalVariation] at h ⊢ + simpa only [mul_div_assoc, mul_assoc] using + mul_le_mul_of_nonneg_left h (μ.nonnegative (x,y)) + +theorem samplerOutputLaw_uniform_diagonal + (μ : FiniteDistribution (X × Y)) + (L : X → FiniteDistribution S) (R : Y → FiniteDistribution S) + (fallback : S) (n : Nat) (x : X) (y : Y) (a : S) : + μ.weight (x,y) * min ((L x).weight a) ((R y).weight a) / + (1 + Information.totalVariation (L x).weight (R y).weight) * + (1 - uniformRejectionRate S ^ n) ≤ + (samplerOutputLaw (sharedProfileThresholds L R) μ L R fallback n).weight ((x,y),a,a) := by + have hp := pow_le_pow_left₀ (sharedProfileReject_nonnegative L R x y) + (sharedProfile_reject_le_rate L R x y) n + have hco : 0 ≤ μ.weight (x,y) * min ((L x).weight a) ((R y).weight a) / + (1 + Information.totalVariation (L x).weight (R y).weight) := + div_nonneg (mul_nonneg (μ.nonnegative (x,y)) + (le_min ((L x).nonnegative a) ((R y).nonnegative a))) + (by linarith [Information.totalVariation_nonneg (L x).weight (R y).weight]) + have h := samplerOutputLaw_diagonal (sharedProfileThresholds L R) μ L R + (left_mem_sharedProfileThresholds L R) (right_mem_sharedProfileThresholds L R) + fallback n x y a + exact (mul_le_mul_of_nonneg_left (sub_le_sub_left hp 1) hco).trans h + +theorem samplerOutputLaw_totalVariation + (p : FiniteDistribution ((X × Y) × S)) (μ : FiniteDistribution (X × Y)) + (L : X → FiniteDistribution S) (R : Y → FiniteDistribution S) + (fallback : S) (n : Nat) : + Information.totalVariation + (samplerOutputLaw (sharedProfileThresholds L R) μ L R fallback n).weight + (diagonalWeights p.weight) ≤ + 2 * Information.totalVariation p.weight (fun z => μ.weight z.1 * (L z.1.1).weight z.2) + + 2 * Information.totalVariation p.weight (fun z => μ.weight z.1 * (R z.1.2).weight z.2) + + uniformRejectionRate S ^ n := by + apply diagonal_sampler_totalVariation_le p.weight μ.weight + (fun xy => (L xy.1).weight) (fun xy => (R xy.2).weight) _ + (Information.gameLaw_isProbability p) (Information.gameLaw_isProbability μ) + (fun xy => Information.gameLaw_isProbability (L xy.1)) + (fun xy => Information.gameLaw_isProbability (R xy.2)) + (Information.gameLaw_isProbability _) + (pow_nonneg (uniformRejectionRate_nonnegative S) n) + · exact pow_le_one₀ (uniformRejectionRate_nonnegative S) + (uniformRejectionRate_lt_one S).le + · intro xy a + exact samplerOutputLaw_uniform_diagonal μ L R fallback n xy.1 xy.2 a + +theorem samplerOutputLaw_arbitrarily_close + (p : FiniteDistribution ((X × Y) × S)) (μ : FiniteDistribution (X × Y)) + (L : X → FiniteDistribution S) (R : Y → FiniteDistribution S) + (fallback : S) (η : ℝ) (hη : 0 < η) : ∃ n : Nat, + Information.totalVariation + (samplerOutputLaw (sharedProfileThresholds L R) μ L R fallback n).weight + (diagonalWeights p.weight) ≤ + 2 * Information.totalVariation p.weight (fun z => μ.weight z.1 * (L z.1.1).weight z.2) + + 2 * Information.totalVariation p.weight (fun z => μ.weight z.1 * (R z.1.2).weight z.2) + η := by + obtain ⟨n,hn⟩ := exists_uniformRejectionRate_pow_lt S η hη + exact ⟨n, (samplerOutputLaw_totalVariation p μ L R fallback n).trans + (by linarith)⟩ + +open scoped BigOperators +open Games Information + +theorem finiteDistribution_nonempty {A : Type*} [Fintype A] (μ : FiniteDistribution A) : + Nonempty A := by + have hsum : (∑ a, μ.weight a) ≠ 0 := by rw [μ.normalized]; norm_num + obtain ⟨a, _, _⟩ := Finset.exists_ne_zero_of_sum_ne_zero hsum + exact ⟨a⟩ + +variable {Q₁ Q₂ A₁ A₂ : Type*} + [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂] + [DecidableEq Q₁] [DecidableEq Q₂] {n : Nat} + +def selectedProfileFallback (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) + (j : {i : Fin n // i ∉ selected}) : + FiniteDistribution (SelectedCommonData (Q₁ := Q₁) (Q₂ := Q₂) + (A₁ := A₁) (A₂ := A₂) selected j) := + (selectedCommonLaw G strategy selected positive j).pushforward Prod.fst + +def selectedLeftProfile (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) + (j : {i : Fin n // i ∉ selected}) (x : Q₁) : + FiniteDistribution (SelectedCommonData (Q₁ := Q₁) (Q₂ := Q₂) + (A₁ := A₁) (A₂ := A₂) selected j) := + toGameLaw + (leftCommonProfile (selectedCommonLaw G strategy selected positive j).weight + (selectedProfileFallback G strategy selected positive j).weight x) + (leftCommonProfile_isProbability _ _ + (gameLaw_isProbability (selectedCommonLaw G strategy selected positive j)) + (gameLaw_isProbability (selectedProfileFallback G strategy selected positive j)) x) + +def selectedRightProfile (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) + (j : {i : Fin n // i ∉ selected}) (y : Q₂) : + FiniteDistribution (SelectedCommonData (Q₁ := Q₁) (Q₂ := Q₂) + (A₁ := A₁) (A₂ := A₂) selected j) := + toGameLaw + (rightCommonProfile (selectedCommonLaw G strategy selected positive j).weight + (selectedProfileFallback G strategy selected positive j).weight y) + (rightCommonProfile_isProbability _ _ + (gameLaw_isProbability (selectedCommonLaw G strategy selected positive j)) + (gameLaw_isProbability (selectedProfileFallback G strategy selected positive j)) y) + +def selectedLeftProfileError (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) + (j : {i : Fin n // i ∉ selected}) : ℝ := + Information.totalVariation (selectedCommonLaw G strategy selected positive j).weight + (fun z => G.questions.weight z.2 * (selectedLeftProfile G strategy selected positive j z.2.1).weight z.1) + +def selectedRightProfileError (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) + (j : {i : Fin n // i ∉ selected}) : ℝ := + Information.totalVariation (selectedCommonLaw G strategy selected positive j).weight + (fun z => G.questions.weight z.2 * (selectedRightProfile G strategy selected positive j z.2.2).weight z.1) + +theorem selectedLeftProfileError_le (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) + (j : {i : Fin n // i ∉ selected}) : + selectedLeftProfileError G strategy selected positive j ≤ + Information.totalVariation (partialRevealMarginal G.questions j (selectedOutsideLikelihood G strategy selected)) + (leftRevealModel G.questions + (partialRevealMarginal G.questions j (selectedOutsideLikelihood G strategy selected))) + + Information.totalVariation (secondMarginal (selectedCommonLaw G strategy selected positive j).weight) + G.questions.weight := + leftCommonProfile_error _ G.questions _ + (gameLaw_isProbability (selectedCommonLaw G strategy selected positive j)) + (gameLaw_isProbability (selectedProfileFallback G strategy selected positive j)) + +theorem selectedRightProfileError_le (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) + (j : {i : Fin n // i ∉ selected}) : + selectedRightProfileError G strategy selected positive j ≤ + Information.totalVariation (partialRevealMarginal G.questions j (selectedOutsideLikelihood G strategy selected)) + (rightRevealModel G.questions + (partialRevealMarginal G.questions j (selectedOutsideLikelihood G strategy selected))) + + Information.totalVariation (secondMarginal (selectedCommonLaw G strategy selected positive j).weight) + G.questions.weight := + rightCommonProfile_error _ G.questions _ + (gameLaw_isProbability (selectedCommonLaw G strategy selected positive j)) + (gameLaw_isProbability (selectedProfileFallback G strategy selected positive j)) + +def selectedSamplingTarget (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) + (j : {i : Fin n // i ∉ selected}) : + FiniteDistribution ((Q₁ × Q₂) × SelectedCommonData (Q₁ := Q₁) (Q₂ := Q₂) + (A₁ := A₁) (A₂ := A₂) selected j) := + (selectedCommonLaw G strategy selected positive j).transport (Equiv.prodComm _ _) + +theorem selectedSamplingTarget_left_error (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) + (j : {i : Fin n // i ∉ selected}) : + Information.totalVariation (selectedSamplingTarget G strategy selected positive j).weight + (fun z => G.questions.weight z.1 * (selectedLeftProfile G strategy selected positive j z.1.1).weight z.2) = + selectedLeftProfileError G strategy selected positive j := by + exact totalVariation_comp_equiv + (Equiv.prodComm (Q₁ × Q₂) (SelectedCommonData (Q₁ := Q₁) (Q₂ := Q₂) + (A₁ := A₁) (A₂ := A₂) selected j)) + (selectedCommonLaw G strategy selected positive j).weight + (fun z => G.questions.weight z.2 * (selectedLeftProfile G strategy selected positive j z.2.1).weight z.1) + +theorem selectedSamplingTarget_right_error (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) + (j : {i : Fin n // i ∉ selected}) : + Information.totalVariation (selectedSamplingTarget G strategy selected positive j).weight + (fun z => G.questions.weight z.1 * (selectedRightProfile G strategy selected positive j z.1.2).weight z.2) = + selectedRightProfileError G strategy selected positive j := by + exact totalVariation_comp_equiv + (Equiv.prodComm (Q₁ × Q₂) (SelectedCommonData (Q₁ := Q₁) (Q₂ := Q₂) + (A₁ := A₁) (A₂ := A₂) selected j)) + (selectedCommonLaw G strategy selected positive j).weight + (fun z => G.questions.weight z.2 * (selectedRightProfile G strategy selected positive j z.2.2).weight z.1) + +theorem pushforward_snd_weight_eq_secondMarginal {A B : Type*} + [Fintype A] [Fintype B] (μ : FiniteDistribution (A × B)) : + (μ.pushforward Prod.snd).weight = secondMarginal μ.weight := by + classical + funext b + simp [FiniteDistribution.pushforward, secondMarginal, Fintype.sum_prod_type] + +variable {I T X Y : Type*} [Fintype I] [DecidableEq I] [Fintype T] + [Fintype X] [Fintype Y] [DecidableEq X] [DecidableEq Y] + +def revealDataSplitEquiv (j : I) : + (T × (I → X ⊕ Y)) ≃ ((T × ({i : I // i ≠ j} → X ⊕ Y)) × (X ⊕ Y)) where + toFun z := ((z.1, fun i => z.2 i.1), z.2 j) + invFun z := (z.1.1, mergeAt j z.2 z.1.2) + left_inv z := by + apply Prod.ext + · rfl + · funext i + by_cases h : i = j <;> simp [mergeAt, h] + right_inv z := by + apply Prod.ext + · apply Prod.ext + · rfl + · funext i + exact mergeAt_other j z.2 z.1.2 i + · exact mergeAt_self j z.2 z.1.2 + +theorem partialRevealMarginal_secondMarginal + (μ : FiniteDistribution (X × Y)) (j : I) + (likelihood : T → (I → X × Y) → ℝ) : + secondMarginal (partialRevealMarginal μ j likelihood) = + secondMarginal (fullRevealMarginal μ j likelihood) := by + classical + funext q + calc + _ = ∑ z : (T × ({i : I // i ≠ j} → X ⊕ Y)) × (X ⊕ Y), + maskedJoint (partialRevealMarginal μ j likelihood) (z,q) := by + simp [secondMarginal, Fintype.sum_prod_type, maskedJoint] + _ = _ := by + apply Fintype.sum_equiv (revealDataSplitEquiv (T := T) j).symm + intro z + exact (fullRevealMarginal_merge μ j likelihood z.1.1 z.1.2 z.2 q).symm + +variable {Q₁ Q₂ A₁ A₂ : Type*} + [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂] + [DecidableEq Q₁] [DecidableEq Q₂] {n : Nat} + +def selectedObservationDataEquiv (selected : Finset (Fin n)) : + (SelectedInput Q₁ Q₂ selected × SelectedLabels (A₁ := A₁) (A₂ := A₂) selected) ≃ + (((selected → Q₁ × Q₂) × SelectedLabels (A₁ := A₁) (A₂ := A₂) selected) × + ({i : Fin n // i ∉ selected} → Q₁ ⊕ Q₂)) where + toFun z := ((z.1.1,z.2),z.1.2) + invFun z := ((z.1.1,z.2),z.1.2) + left_inv _ := rfl + right_inv _ := rfl + +theorem selectedFullReveal_secondMarginal (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (j : {i : Fin n // i ∉ selected}) : + secondMarginal (fullRevealMarginal G.questions j + (selectedOutsideLikelihood G strategy selected)) = + secondMarginal (selectedRawMarginal G strategy selected j) := by + classical + funext q + apply Fintype.sum_equiv + (selectedObservationDataEquiv (Q₁ := Q₁) (Q₂ := Q₂) + (A₁ := A₁) (A₂ := A₂) selected).symm + intro z + exact (selectedRawMarginal_fullReveal G strategy selected j (z,q)).symm + +theorem selectedRawMarginal_secondMarginal (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) + (j : {i : Fin n // i ∉ selected}) : + secondMarginal (selectedRawMarginal G strategy selected j) = + (selectedQuestionMarginal G strategy selected positive j.1).weight := by + classical + funext q + calc + _ = (selectedJointLaw G strategy selected positive).probability + (fun z => decide (z.2 j = q)) := by + simp only [secondMarginal, selectedRawMarginal, FiniteDistribution.probability, + selectedJointLaw, toGameLaw, Fintype.sum_prod_type, decide_eq_true_eq] + _ = ((G.repetition n).questions.condition (G.selectedWins strategy selected) positive).probability + (fun questions => decide ((questions.1 j.1,questions.2 j.1) = q)) := by + have h := selectedJointLaw_question_probability G strategy selected positive + (fun questions => decide ((questions.1 j.1,questions.2 j.1) = q)) + simpa [selectedQuestionTuple, mergeCoordinates, j.property] using h + _ = _ := by + rw [FiniteDistribution.weight_eq_probability_singleton, selectedQuestionMarginal, + FiniteDistribution.probability_pushforward] + +theorem selectedCommonLaw_secondMarginal (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) + (j : {i : Fin n // i ∉ selected}) : + secondMarginal (selectedCommonLaw G strategy selected positive j).weight = + (selectedQuestionMarginal G strategy selected positive j.1).weight := by + change secondMarginal (partialRevealMarginal G.questions j + (selectedOutsideLikelihood G strategy selected)) = _ + rw [partialRevealMarginal_secondMarginal, selectedFullReveal_secondMarginal] + exact selectedRawMarginal_secondMarginal G strategy selected positive j + +theorem selectedCommonLaw_questions_pushforward (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) + (j : {i : Fin n // i ∉ selected}) : + (selectedCommonLaw G strategy selected positive j).pushforward Prod.snd = + selectedQuestionMarginal G strategy selected positive j.1 := by + classical + apply FiniteDistribution.eq_of_weight_eq + intro q + exact (congrFun (pushforward_snd_weight_eq_secondMarginal + (selectedCommonLaw G strategy selected positive j)) q).trans + (congrFun (selectedCommonLaw_secondMarginal G strategy selected positive j) q) + +variable {Q₁ Q₂ A₁ A₂ : Type*} + [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂] + [DecidableEq Q₁] [DecidableEq Q₂] {n : Nat} + +omit [DecidableEq Q₁] [DecidableEq Q₂] in +theorem selectedQuestionRadius_le_informationRadius [Nonempty A₁] [Nonempty A₂] + (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) : + Real.sqrt ((Fintype.card {i : Fin n // i ∉ selected} : ℝ) * + Real.log (1 / G.selectedSuccess strategy selected)) ≤ + selectedInformationRadius G strategy selected := by + have hcard : (1 : ℝ) ≤ Fintype.card (SelectedLabels (A₁ := A₁) (A₂ := A₂) selected) := by + exact_mod_cast (Nat.succ_le_of_lt + (Fintype.card_pos : 0 < Fintype.card (SelectedLabels (A₁ := A₁) (A₂ := A₂) selected))) + have hlog := Real.log_nonneg hcard + have hnonneg : 0 ≤ (Fintype.card {i : Fin n // i ∉ selected} : ℝ) := Nat.cast_nonneg _ + unfold selectedInformationRadius + apply Real.sqrt_le_sqrt + nlinarith + +theorem selectedQuestionMarginal_error_sum [Nonempty A₁] [Nonempty A₂] + (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) : + (∑ j : {i : Fin n // i ∉ selected}, + (selectedQuestionMarginal G strategy selected positive j.1).totalVariation G.questions) ≤ + selectedInformationRadius G strategy selected := + (unselectedQuestionMarginal_totalVariation_sum_le_sqrt G strategy selected positive).trans + (selectedQuestionRadius_le_informationRadius G strategy selected) + +def selectedEmbeddingError (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) + (j : {i : Fin n // i ∉ selected}) : ℝ := + 2 * selectedLeftProfileError G strategy selected positive j + + 2 * selectedRightProfileError G strategy selected positive j + +theorem selectedEmbeddingError_nonnegative (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) + (j : {i : Fin n // i ∉ selected}) : + 0 ≤ selectedEmbeddingError G strategy selected positive j := by + exact add_nonneg + (mul_nonneg (by norm_num) (Information.totalVariation_nonneg _ _)) + (mul_nonneg (by norm_num) (Information.totalVariation_nonneg _ _)) + +theorem selectedLeftProfileError_sum [Nonempty A₁] [Nonempty A₂] + (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) : + (∑ j : {i : Fin n // i ∉ selected}, selectedLeftProfileError G strategy selected positive j) ≤ + 3 * selectedInformationRadius G strategy selected := by + have hsum := Finset.sum_le_sum + (fun j (_ : j ∈ (Finset.univ : Finset {i : Fin n // i ∉ selected})) => + selectedLeftProfileError_le G strategy selected positive j) + simp_rw [selectedCommonLaw_secondMarginal] at hsum + rw [Finset.sum_add_distrib] at hsum + have hleft := selected_leftReveal_error_sum G strategy selected positive + have hquestion := selectedQuestionMarginal_error_sum G strategy selected positive + change (∑ j : {i : Fin n // i ∉ selected}, + Information.totalVariation (selectedQuestionMarginal G strategy selected positive j.1).weight + G.questions.weight) ≤ _ at hquestion + linarith + +theorem selectedRightProfileError_sum [Nonempty A₁] [Nonempty A₂] + (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) : + (∑ j : {i : Fin n // i ∉ selected}, selectedRightProfileError G strategy selected positive j) ≤ + 3 * selectedInformationRadius G strategy selected := by + have hsum := Finset.sum_le_sum + (fun j (_ : j ∈ (Finset.univ : Finset {i : Fin n // i ∉ selected})) => + selectedRightProfileError_le G strategy selected positive j) + simp_rw [selectedCommonLaw_secondMarginal] at hsum + rw [Finset.sum_add_distrib] at hsum + have hright := selected_rightReveal_error_sum G strategy selected positive + have hquestion := selectedQuestionMarginal_error_sum G strategy selected positive + change (∑ j : {i : Fin n // i ∉ selected}, + Information.totalVariation (selectedQuestionMarginal G strategy selected positive j.1).weight + G.questions.weight) ≤ _ at hquestion + linarith + +theorem selectedEmbeddingError_sum_le_fifteen [Nonempty A₁] [Nonempty A₂] + (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) : + (∑ j : {i : Fin n // i ∉ selected}, selectedEmbeddingError G strategy selected positive j) ≤ + 15 * selectedInformationRadius G strategy selected := by + have hl := selectedLeftProfileError_sum G strategy selected positive + have hr := selectedRightProfileError_sum G strategy selected positive + have hn : 0 ≤ selectedInformationRadius G strategy selected := Real.sqrt_nonneg _ + simp only [selectedEmbeddingError, Finset.sum_add_distrib, ← Finset.mul_sum] + linarith + +end +end MinUncutGames.Foundations.Repetition + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/Overlay.lean b/lean/OAI/Computability/MinUncut/PCP/Overlay.lean new file mode 100644 index 0000000000000000000000000000000000000000..9324f8baf0ad22792ba8b5afb76b328186109c5a --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/Overlay.lean @@ -0,0 +1,718 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.CayleySpectral + +namespace OAI + +section +open scoped BigOperators + +namespace MinUncutGames.Foundations.PCP.Overlay + +open PoweringWalks SpectralReturn + +variable {V D E A : Type*} + +def originalPortGraph (G : ConstraintGraph V (V × D) A) : PortGraph V D where + rot := G.reverse + rot_involutive := G.reverse_involutive + +def rotate (G : PortGraph V D) (H : PortGraph V E) : + V × (D ⊕ E) → V × (D ⊕ E) + | (v, Sum.inl d) => ((G.rot (v, d)).1, Sum.inl (G.rot (v, d)).2) + | (v, Sum.inr e) => ((H.rot (v, e)).1, Sum.inr (H.rot (v, e)).2) + +theorem rotate_involutive (G : PortGraph V D) (H : PortGraph V E) : + Function.Involutive (rotate G H) := by + rintro ⟨v, p⟩ + rcases p with d | e + · exact congrArg (fun a : V × D => (a.1, (Sum.inl a.2 : D ⊕ E))) + (G.rot_involutive (v, d)) + · exact congrArg (fun a : V × E => (a.1, (Sum.inr a.2 : D ⊕ E))) + (H.rot_involutive (v, e)) + +def portGraph (G : PortGraph V D) (H : PortGraph V E) : PortGraph V (D ⊕ E) where + rot := + { toFun := rotate G H + invFun := rotate G H + left_inv := rotate_involutive G H + right_inv := rotate_involutive G H } + rot_involutive := rotate_involutive G H + +@[simp] theorem portGraph_rot_inl (G : PortGraph V D) (H : PortGraph V E) + (v : V) (d : D) : + (portGraph G H).rot (v, Sum.inl d) = + ((G.rot (v, d)).1, Sum.inl (G.rot (v, d)).2) := rfl + +@[simp] theorem portGraph_rot_inr (G : PortGraph V D) (H : PortGraph V E) + (v : V) (e : E) : + (portGraph G H).rot (v, Sum.inr e) = + ((H.rot (v, e)).1, Sum.inr (H.rot (v, e)).2) := rfl + +def constraintGraph (G : ConstraintGraph V (V × D) A) (H : PortGraph V E) : + ConstraintGraph V (V × (D ⊕ E)) A where + reverse := (portGraph (originalPortGraph G) H).rot + reverse_involutive := (portGraph (originalPortGraph G) H).rot_involutive + tail := Prod.fst + accepts p a b := match p.2 with + | Sum.inl d => G.accepts (p.1, d) a b + | Sum.inr _ => true + reverse_accepts := by + rintro ⟨v, p⟩ a b + rcases p with d | e + · exact G.reverse_accepts (v, d) a b + · rfl + +@[simp] theorem constraintGraph_tail (G : ConstraintGraph V (V × D) A) + (H : PortGraph V E) : (constraintGraph G H).tail = Prod.fst := rfl + +@[simp] theorem constraintGraph_portGraph (G : ConstraintGraph V (V × D) A) + (H : PortGraph V E) : + originalPortGraph (constraintGraph G H) = portGraph (originalPortGraph G) H := rfl + +@[simp] theorem edgeSatisfied_inl (G : ConstraintGraph V (V × D) A) + (H : PortGraph V E) (htail : G.tail = Prod.fst) + (labeling : V → A) (v : V) (d : D) : + (constraintGraph G H).edgeSatisfied labeling (v, Sum.inl d) = + G.edgeSatisfied labeling (v, d) := by + change G.accepts (v, d) (labeling v) (labeling (G.reverse (v, d)).1) = + G.accepts (v, d) (labeling (G.tail (v, d))) + (labeling (G.tail (G.reverse (v, d)))) + rw [htail] + +@[simp] theorem edgeSatisfied_inr (G : ConstraintGraph V (V × D) A) + (H : PortGraph V E) (labeling : V → A) (v : V) (e : E) : + (constraintGraph G H).edgeSatisfied labeling (v, Sum.inr e) = true := rfl + +theorem complete (G : ConstraintGraph V (V × D) A) (H : PortGraph V E) + (htail : G.tail = Prod.fst) (labeling : V → A) + (h : ∀ a, G.edgeSatisfied labeling a = true) : + ∀ a, (constraintGraph G H).edgeSatisfied labeling a = true := by + rintro ⟨v, p⟩ + rcases p with d | e + · rw [edgeSatisfied_inl G H htail] + exact h (v, d) + · rfl + +theorem satisfiable_iff (G : ConstraintGraph V (V × D) A) (H : PortGraph V E) + (htail : G.tail = Prod.fst) : + (constraintGraph G H).Satisfiable ↔ G.Satisfiable := by + constructor + · rintro ⟨labeling, h⟩ + refine ⟨labeling, ?_⟩ + rintro ⟨v, d⟩ + rw [← edgeSatisfied_inl G H htail] + exact h (v, Sum.inl d) + · rintro ⟨labeling, h⟩ + exact ⟨labeling, complete G H htail labeling h⟩ + +theorem rejectionCount_eq [Fintype V] [Fintype D] [Fintype E] + (G : ConstraintGraph V (V × D) A) (H : PortGraph V E) + (htail : G.tail = Prod.fst) (labeling : V → A) : + (constraintGraph G H).rejectionCount labeling = G.rejectionCount labeling := by + classical + simp only [DegreeReplacement.rejectionCount_eq_sum, Fintype.sum_prod_type, + Fintype.sum_sum_type] + simp [edgeSatisfied_inl G H htail] + +theorem card_ports [Fintype D] [Fintype E] : + Fintype.card (D ⊕ E) = Fintype.card D + Fintype.card E := Fintype.card_sum + +theorem card_darts [Fintype V] [Fintype D] [Fintype E] : + Fintype.card (V × (D ⊕ E)) = + Fintype.card (V × D) + Fintype.card (V × E) := by + simp only [Fintype.card_prod, Fintype.card_sum, Nat.mul_add] + +section Averages + +variable [Fintype V] [Fintype D] [Fintype E] + +omit [Fintype V] in + +theorem operator_mix [Nonempty D] [Nonempty E] + (G : PortGraph V D) (H : PortGraph V E) (f : V → ℝ) (v : V) : + averagingOperator (portGraph G H) f v = + (Fintype.card D : ℝ) / ((Fintype.card D : ℝ) + Fintype.card E) * + averagingOperator G f v + + (Fintype.card E : ℝ) / ((Fintype.card D : ℝ) + Fintype.card E) * + averagingOperator H f v := by + have hd : (0 : ℝ) < Fintype.card D := by + exact_mod_cast (Fintype.card_pos : 0 < Fintype.card D) + have he : (0 : ℝ) < Fintype.card E := by + exact_mod_cast (Fintype.card_pos : 0 < Fintype.card E) + change mean (fun p : D ⊕ E => f ((portGraph G H).rot (v, p)).1) = _ + rw [mean_eq_sum_div_card] + simp only [Fintype.sum_sum_type, Fintype.card_sum, Nat.cast_add, + portGraph_rot_inl, portGraph_rot_inr] + unfold averagingOperator + rw [Fintype.expect_eq_sum_div_card, Fintype.expect_eq_sum_div_card] + field_simp [hd.ne', he.ne', (add_pos hd he).ne'] + +theorem energy_convex_mix (a b : ℝ) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) + (f g : V → ℝ) : + energy (fun v => a * f v + b * g v) ≤ a * energy f + b * energy g := by + calc + energy (fun v => a * f v + b * g v) ≤ + mean (fun v => a * (f v) ^ 2 + b * (g v) ^ 2) := by + apply mean_mono + intro v + have hnormalize := congrArg (fun t : ℝ => t * (a * (f v) ^ 2 + b * (g v) ^ 2)) hab + have hnonneg := mul_nonneg (mul_nonneg ha hb) (sq_nonneg (f v - g v)) + nlinarith + _ = a * energy f + b * energy g := by + rw [mean_add, mean_mul_left, mean_mul_left] + rfl + +theorem energy_bound [Nonempty V] [Nonempty D] [Nonempty E] + (G : PortGraph V D) (H : PortGraph V E) (lambda : ℝ) + (certificate : SpectralCertificate H lambda) (f : V → ℝ) (hf : mean f = 0) : + energy (averagingOperator (portGraph G H) f) ≤ + ((Fintype.card D : ℝ) + (Fintype.card E : ℝ) * lambda ^ 2) / + ((Fintype.card D : ℝ) + Fintype.card E) * energy f := by + let a : ℝ := (Fintype.card D : ℝ) / ((Fintype.card D : ℝ) + Fintype.card E) + let b : ℝ := (Fintype.card E : ℝ) / ((Fintype.card D : ℝ) + Fintype.card E) + have hd : (0 : ℝ) < Fintype.card D := by + exact_mod_cast (Fintype.card_pos : 0 < Fintype.card D) + have he : (0 : ℝ) < Fintype.card E := by + exact_mod_cast (Fintype.card_pos : 0 < Fintype.card E) + have hden : (0 : ℝ) < (Fintype.card D : ℝ) + Fintype.card E := add_pos hd he + have ha : 0 ≤ a := div_nonneg hd.le hden.le + have hb : 0 ≤ b := div_nonneg he.le hden.le + have hab : a + b = 1 := by + dsimp [a, b] + rw [← add_div, div_self hden.ne'] + have hop : averagingOperator (portGraph G H) f = + fun v => a * averagingOperator G f v + b * averagingOperator H f v := by + funext v + exact operator_mix G H f v + calc + energy (averagingOperator (portGraph G H) f) ≤ + a * energy (averagingOperator G f) + b * energy (averagingOperator H f) := by + rw [hop] + exact energy_convex_mix a b ha hb hab _ _ + _ ≤ a * energy f + b * (lambda ^ 2 * energy f) := + add_le_add + (mul_le_mul_of_nonneg_left (ZigzagSpectral.averaging_energy_le G f) ha) + (mul_le_mul_of_nonneg_left (certificate.contraction f hf) hb) + _ = _ := by + dsimp [a, b] + ring + +theorem energy_bound_three_quarters [Nonempty V] + (G : PortGraph V D) (H : PortGraph V E) + (hdegree : Fintype.card D = Fintype.card E + 1) (hpositive : 1 ≤ Fintype.card E) + (certificate : SpectralCertificate H (1 / 2 : ℝ)) + (f : V → ℝ) (hf : mean f = 0) : + energy (averagingOperator (portGraph G H) f) ≤ (3 / 4 : ℝ) * energy f := by + let _ : Nonempty E := Fintype.card_pos_iff.mp (lt_of_lt_of_le Nat.zero_lt_one hpositive) + let _ : Nonempty D := Fintype.card_pos_iff.mp (by omega) + have he : (1 : ℝ) ≤ Fintype.card E := by exact_mod_cast hpositive + have hd : (Fintype.card D : ℝ) = (Fintype.card E : ℝ) + 1 := by exact_mod_cast hdegree + have hden : (0 : ℝ) < (Fintype.card D : ℝ) + Fintype.card E := by linarith + have hcoefficient : + ((Fintype.card D : ℝ) + (Fintype.card E : ℝ) * (1 / 2 : ℝ) ^ 2) / + ((Fintype.card D : ℝ) + Fintype.card E) ≤ (3 / 4 : ℝ) := by + apply (div_le_iff₀ hden).mpr + nlinarith + exact (energy_bound G H (1 / 2) certificate f hf).trans + (mul_le_mul_of_nonneg_right hcoefficient (energy_nonnegative f)) + +theorem spectralCertificate_seven_eighths [Nonempty V] + (G : PortGraph V D) (H : PortGraph V E) + (hdegree : Fintype.card D = Fintype.card E + 1) (hpositive : 1 ≤ Fintype.card E) + (certificate : SpectralCertificate H (1 / 2 : ℝ)) : + SpectralCertificate (portGraph G H) (7 / 8 : ℝ) where + nonnegative := by norm_num + lt_one := by norm_num + contraction := by + intro f hf + exact (energy_bound_three_quarters G H hdegree hpositive certificate f hf).trans + (mul_le_mul_of_nonneg_right (by norm_num : (3 / 4 : ℝ) ≤ (7 / 8 : ℝ) ^ 2) + (energy_nonnegative f)) + +theorem constraintGraph_spectralCertificate [Nonempty V] + (G : ConstraintGraph V (V × D) A) (H : PortGraph V E) + (hdegree : Fintype.card D = Fintype.card E + 1) (hpositive : 1 ≤ Fintype.card E) + (certificate : SpectralCertificate H (1 / 2 : ℝ)) : + SpectralCertificate (originalPortGraph (constraintGraph G H)) (7 / 8 : ℝ) := by + rw [constraintGraph_portGraph] + exact spectralCertificate_seven_eighths (originalPortGraph G) H + hdegree hpositive certificate + +end Averages + +end MinUncutGames.Foundations.PCP.Overlay + +end +section +namespace MinUncutGames.Foundations.PCP.LazySmoothing + +open scoped BigOperators + +def bitCount {n : ℕ} (tape : Fin n → Bool) : ℕ := + ∑ i, if tape i then 1 else 0 + +noncomputable def binomialMean (n : ℕ) (g : ℕ → ℝ) : ℝ := + Finset.univ.expect (fun tape : Fin n → Bool => g (bitCount tape)) + +def splitTape (n : ℕ) : (Fin (n + 1) → Bool) ≃ (Bool × (Fin n → Bool)) where + toFun x := (x 0, fun i => x i.succ) + invFun x := Fin.cases x.1 x.2 + left_inv x := by + funext i + exact Fin.cases rfl (fun _ => rfl) i + right_inv _ := rfl + +theorem bitCount_succ {n : ℕ} (x : Fin (n + 1) → Bool) : + bitCount x = (if x 0 then 1 else 0) + bitCount (fun i => x i.succ) := by + exact Fin.sum_univ_succ _ + +theorem mean_congr {n : ℕ} {f g : ℕ → ℝ} (h : ∀ k, f k = g k) : + binomialMean n f = binomialMean n g := by + unfold binomialMean + exact Finset.expect_congr rfl (fun x _ => h (bitCount x)) + +@[simp] theorem mean_const (n : ℕ) (c : ℝ) : + binomialMean n (fun _ => c) = c := Fintype.expect_const c + +theorem mean_add (n : ℕ) (f g : ℕ → ℝ) : + binomialMean n (fun k => f k + g k) = binomialMean n f + binomialMean n g := + Finset.expect_add_distrib _ _ _ + +theorem mean_sub (n : ℕ) (f g : ℕ → ℝ) : + binomialMean n (fun k => f k - g k) = binomialMean n f - binomialMean n g := + Finset.expect_sub_distrib _ _ _ + +theorem mean_mul (n : ℕ) (c : ℝ) (f : ℕ → ℝ) : + binomialMean n (fun k => c * f k) = c * binomialMean n f := by + exact (Finset.mul_expect Finset.univ (fun x : Fin n → Bool => f (bitCount x)) c).symm + +@[simp] theorem mean_zero (g : ℕ → ℝ) : binomialMean 0 g = g 0 := by + simp [binomialMean, bitCount] + +theorem expect_bool (f : Bool → ℝ) : Finset.univ.expect f = (f false + f true) / 2 := by + rw [Finset.expect_eq_sum_div_card] + simp [Fintype.univ_bool, add_comm] + +theorem mean_succ (n : ℕ) (g : ℕ → ℝ) : + binomialMean (n + 1) g = + (binomialMean n g + binomialMean n (fun k => g (k + 1))) / 2 := by + unfold binomialMean + rw [Fintype.expect_equiv (splitTape n) + (fun x => g (bitCount x)) + (fun x => g ((if x.1 then 1 else 0) + bitCount x.2)) + (fun x => congrArg g (bitCount_succ x))] + rw [← Finset.univ_product_univ, Finset.expect_product, expect_bool] + simp [Nat.add_comm] + +def score (n k : ℕ) : ℝ := (n : ℝ) - 2 * (k : ℝ) + +noncomputable def scoreMean (n : ℕ) (g : ℕ → ℝ) : ℝ := + binomialMean n (fun k => score n k * g k) + +@[simp] theorem scoreMean_zero (g : ℕ → ℝ) : scoreMean 0 g = 0 := by + simp [scoreMean, score] + +theorem scoreMean_succ (n : ℕ) (g : ℕ → ℝ) : + scoreMean (n + 1) g = + ((scoreMean n g + binomialMean n g) + + (scoreMean n (fun k => g (k + 1)) - + binomialMean n (fun k => g (k + 1)))) / 2 := by + unfold scoreMean + rw [mean_succ] + have h₁ : (fun k => score (n + 1) k * g k) = + (fun k => score n k * g k + g k) := by + funext k + simp only [score, Nat.cast_add, Nat.cast_one] + ring + have h₂ : (fun k => score (n + 1) (k + 1) * g (k + 1)) = + (fun k => score n k * g (k + 1) - g (k + 1)) := by + funext k + simp only [score, Nat.cast_add, Nat.cast_one] + ring + rw [h₁, h₂, mean_add, mean_sub] + +theorem score_identity (n : ℕ) (g : ℕ → ℝ) : + scoreMean (n + 1) g = ((n : ℝ) + 1) / 2 * + (binomialMean n g - binomialMean n (fun k => g (k + 1))) := by + induction n generalizing g with + | zero => simp [scoreMean_succ]; ring + | succ n ih => + rw [scoreMean_succ, ih g, ih (fun k => g (k + 1))] + simp only [mean_succ, Nat.cast_add, Nat.cast_one] + ring + +theorem score_mean_zero (n : ℕ) : binomialMean n (score n) = 0 := by + cases n with + | zero => simp [score] + | succ n => + have h := score_identity n (fun _ => 1) + simpa [scoreMean] using h + +theorem score_second_moment (n : ℕ) : + binomialMean n (fun k => score n k ^ 2) = (n : ℝ) := by + cases n with + | zero => simp [score] + | succ n => + have h := score_identity n (score (n + 1)) + have hd : binomialMean n (score (n + 1)) - + binomialMean n (fun k => score (n + 1) (k + 1)) = 2 := by + rw [← mean_sub] + calc + _ = binomialMean n (fun _ => 2) := by + apply mean_congr + intro k + simp only [score, Nat.cast_add, Nat.cast_one] + ring + _ = 2 := mean_const _ _ + rw [hd] at h + simpa [scoreMean, pow_two] using h + +theorem score_difference (n : ℕ) (g : ℕ → ℝ) : + scoreMean (n + 1) g = ((n : ℝ) + 1) * + (binomialMean n g - binomialMean (n + 1) g) := by + rw [score_identity, mean_succ] + ring + +theorem adjacent_difference_sq (n : ℕ) (g : ℕ → ℝ) + (hg : ∀ k, 0 ≤ g k ∧ g k ≤ 1) : + 4 * ((n : ℝ) + 1) * + (binomialMean n g - binomialMean (n + 1) g) ^ 2 ≤ 1 := by + have hc : binomialMean (n + 1) + (fun k => score (n + 1) k * (g k - 1 / 2)) = scoreMean (n + 1) g := by + calc + _ = binomialMean (n + 1) (fun k => + score (n + 1) k * g k - (1 / 2) * score (n + 1) k) := by + apply mean_congr + intro k + ring + _ = scoreMean (n + 1) g := by + rw [mean_sub, mean_mul, score_mean_zero] + simp [scoreMean] + have hv : binomialMean (n + 1) (fun k => (g k - 1 / 2) ^ 2) ≤ 1 / 4 := by + apply Finset.expect_le Finset.univ_nonempty + intro tape _ + have h₀ := (hg (bitCount tape)).1 + have h₁ := (hg (bitCount tape)).2 + have hp := mul_nonneg h₀ (sub_nonneg.mpr h₁) + nlinarith + have hcs : (binomialMean (n + 1) + (fun k => score (n + 1) k * (g k - 1 / 2))) ^ 2 ≤ + binomialMean (n + 1) (fun k => score (n + 1) k ^ 2) * + binomialMean (n + 1) (fun k => (g k - 1 / 2) ^ 2) := + Finset.expect_mul_sq_le_sq_mul_sq Finset.univ _ _ + rw [hc, score_difference, score_second_moment] at hcs + have hn : 0 < (n : ℝ) + 1 := by positivity + have hm := mul_le_mul_of_nonneg_left hv (le_of_lt hn) + simp only [Nat.cast_add, Nat.cast_one] at hcs + apply (mul_le_mul_iff_left₀ hn).mp + nlinarith + +theorem adjacent_difference_le (n : ℕ) (g : ℕ → ℝ) + (hg : ∀ k, 0 ≤ g k ∧ g k ≤ 1) (r : ℝ) (hr : 0 < r) + (hrn : r ^ 2 ≤ 4 * ((n : ℝ) + 1)) : + |binomialMean n g - binomialMean (n + 1) g| ≤ 1 / r := by + have hs := adjacent_difference_sq n g hg + have hd := sq_nonneg (binomialMean n g - binomialMean (n + 1) g) + have hh := mul_le_mul_of_nonneg_right hrn hd + rw [le_div_iff₀ hr] + have ha := sq_abs (binomialMean n g - binomialMean (n + 1) g) + have hp : 0 ≤ |binomialMean n g - binomialMean (n + 1) g| * r := + mul_nonneg (abs_nonneg _) (le_of_lt hr) + nlinarith [sq_nonneg (|binomialMean n g - binomialMean (n + 1) g| * r - 1)] + +theorem mean_shift_le (n d : ℕ) (g : ℕ → ℝ) + (hg : ∀ k, 0 ≤ g k ∧ g k ≤ 1) (r : ℝ) (hr : 0 < r) + (hrn : r ^ 2 ≤ 4 * ((n : ℝ) + 1)) : + |binomialMean (n + d) g - binomialMean n g| ≤ (d : ℝ) / r := by + induction d with + | zero => simp + | succ d ih => + have hrnd : r ^ 2 ≤ 4 * ((n + d : ℕ) + 1 : ℝ) := by + push_cast + have : (0 : ℝ) ≤ d := Nat.cast_nonneg _ + linarith + have ha := adjacent_difference_le (n + d) g hg r hr hrnd + rw [abs_sub_comm] at ha + calc + _ ≤ |binomialMean (n + d + 1) g - binomialMean (n + d) g| + + |binomialMean (n + d) g - binomialMean n g| := abs_sub_le _ _ _ + _ ≤ 1 / r + (d : ℝ) / r := add_le_add ha ih + _ = ((d + 1 : ℕ) : ℝ) / r := by push_cast; ring + +theorem mean_ordered_difference_le (m n : ℕ) (hmn : m ≤ n) (g : ℕ → ℝ) + (hg : ∀ k, 0 ≤ g k ∧ g k ≤ 1) (r : ℝ) (hr : 0 < r) + (hrm : r ^ 2 ≤ 4 * ((m : ℝ) + 1)) : + |binomialMean n g - binomialMean m g| ≤ ((n - m : ℕ) : ℝ) / r := by + simpa [Nat.add_sub_of_le hmn] using mean_shift_le m (n - m) g hg r hr hrm + +theorem mean_window_le (N M m : ℕ) (hlo : N - M ≤ m) (hhi : m ≤ N + M) + (g : ℕ → ℝ) (hg : ∀ k, 0 ≤ g k ∧ g k ≤ 1) + (r : ℝ) (hr : 0 < r) (hbase : r ^ 2 ≤ 4 * (((N - M : ℕ) : ℝ) + 1)) : + |binomialMean m g - binomialMean N g| ≤ (M : ℝ) / r := by + by_cases hmN : m ≤ N + · have hrm : r ^ 2 ≤ 4 * ((m : ℝ) + 1) := by + have : ((N - M : ℕ) : ℝ) ≤ (m : ℝ) := by exact_mod_cast hlo + linarith + have h := mean_ordered_difference_le m N hmN g hg r hr hrm + rw [abs_sub_comm] at h + refine h.trans (div_le_div_of_nonneg_right ?_ (le_of_lt hr)) + have : N - m ≤ M := by omega + exact_mod_cast this + · have hNm : N ≤ m := Nat.le_of_lt (Nat.lt_of_not_ge hmN) + have hrN : r ^ 2 ≤ 4 * ((N : ℝ) + 1) := by + have : ((N - M : ℕ) : ℝ) ≤ (N : ℝ) := by exact_mod_cast Nat.sub_le N M + linarith + have h := mean_ordered_difference_le N m hNm g hg r hr hrN + refine h.trans (div_le_div_of_nonneg_right ?_ (le_of_lt hr)) + have : m - N ≤ M := by omega + exact_mod_cast this + +theorem square_window_le (q M m : ℕ) (hq : 1 ≤ q) (hM : 1 ≤ M) + (hlo : (4 * q * M) ^ 2 - M ≤ m) (hhi : m ≤ (4 * q * M) ^ 2 + M) + (g : ℕ → ℝ) (hg : ∀ k, 0 ≤ g k ∧ g k ≤ 1) : + |binomialMean m g - binomialMean ((4 * q * M) ^ 2) g| ≤ 1 / (4 * (q : ℝ)) := by + have hqR : (1 : ℝ) ≤ q := by exact_mod_cast hq + have hMR : (1 : ℝ) ≤ M := by exact_mod_cast hM + have hR : (4 : ℝ) * M ≤ ((4 * q * M : ℕ) : ℝ) := by + push_cast + nlinarith + have hRM : (M : ℝ) ≤ (((4 * q * M : ℕ) : ℝ)) ^ 2 := by nlinarith + have hMN : M ≤ (4 * q * M) ^ 2 := by exact_mod_cast hRM + have hr : (0 : ℝ) < ((4 * q * M : ℕ) : ℝ) := by linarith + have hb : (((4 * q * M : ℕ) : ℝ)) ^ 2 ≤ + 4 * (((((4 * q * M) ^ 2 - M : ℕ)) : ℝ) + 1) := by + rw [Nat.cast_sub hMN, Nat.cast_pow] + nlinarith + have h := mean_window_le ((4 * q * M) ^ 2) M m hlo hhi g hg + ((4 * q * M : ℕ) : ℝ) hr hb + have he : (M : ℝ) / ((4 * q * M : ℕ) : ℝ) = 1 / (4 * (q : ℝ)) := by + push_cast + have hq0 : (q : ℝ) ≠ 0 := by linarith + have hM0 : (M : ℝ) ≠ 0 := by linarith + field_simp + rw [he] at h + exact h + +theorem modal_transfer (q M m : ℕ) (hq : 1 ≤ q) (hM : 1 ≤ M) + (hlo : (4 * q * M) ^ 2 - M ≤ m) (hhi : m ≤ (4 * q * M) ^ 2 + M) + (g : ℕ → ℝ) (hg : ∀ k, 0 ≤ g k ∧ g k ≤ 1) + (hmodal : 1 / (q : ℝ) ≤ binomialMean ((4 * q * M) ^ 2) g) : + 1 / (2 * (q : ℝ)) ≤ binomialMean m g := by + have h := square_window_le q M m hq hM hlo hhi g hg + have hqR : (0 : ℝ) < q := by exact_mod_cast (Nat.zero_lt_of_lt hq) + have hrec : 0 < 1 / (q : ℝ) := one_div_pos.mpr hqR + have he₁ : 1 / (4 * (q : ℝ)) = (1 / (q : ℝ)) / 4 := by ring + have he₂ : 1 / (2 * (q : ℝ)) = (1 / (q : ℝ)) / 2 := by ring + rw [he₁] at h + rw [he₂] + have hl := (abs_le.mp h).1 + linarith + +end MinUncutGames.Foundations.PCP.LazySmoothing + +end +section +namespace MinUncutGames.Foundations.PCP.PoweringWalks + +variable {V D : Type*} + +def lazyRotate (G : PortGraph V D) : Edge V (Bool × D) → Edge V (Bool × D) + | (v, (false, d)) => (v, (false, d)) + | (v, (true, d)) => ((G.rot (v, d)).1, (true, (G.rot (v, d)).2)) + +theorem lazyRotate_involutive (G : PortGraph V D) : + Function.Involutive (lazyRotate G) := by + rintro ⟨v, b, d⟩ + cases b with + | false => rfl + | true => + exact congrArg (fun e : V × D => (e.1, (true, e.2))) (rot_rot G (v, d)) + +def lazyGraph (G : PortGraph V D) : PortGraph V (Bool × D) where + rot := { + toFun := lazyRotate G + invFun := lazyRotate G + left_inv := lazyRotate_involutive G + right_inv := lazyRotate_involutive G } + rot_involutive := lazyRotate_involutive G + +@[simp] theorem lazyGraph_rot_false (G : PortGraph V D) (v : V) (d : D) : + (lazyGraph G).rot (v, (false, d)) = (v, (false, d)) := rfl + +@[simp] theorem lazyGraph_rot_true (G : PortGraph V D) (v : V) (d : D) : + (lazyGraph G).rot (v, (true, d)) = ((G.rot (v, d)).1, (true, (G.rot (v, d)).2)) := rfl + +end MinUncutGames.Foundations.PCP.PoweringWalks + +namespace MinUncutGames.Foundations.PCP.PoweringLazy + +open PoweringWalks SpectralReturn + +variable {V D : Type*} + +theorem operator_binomialMean [Fintype D] (G : PortGraph V D) + (n : Nat) (g : Nat → V → ℝ) (v : V) : + averagingOperator G (fun w => LazySmoothing.binomialMean n (fun k => g k w)) v = + LazySmoothing.binomialMean n (fun k => averagingOperator G (g k) v) := by + unfold averagingOperator LazySmoothing.binomialMean + exact Finset.expect_comm Finset.univ Finset.univ + (fun d tape => g (LazySmoothing.bitCount tape) (G.rot (v, d)).1) + +theorem averagingOperator_lazy [Fintype D] [Nonempty D] + (G : PortGraph V D) (f : V → ℝ) (v : V) : + averagingOperator (lazyGraph G) f v = (f v + averagingOperator G f v) / 2 := by + change mean (fun bd : Bool × D => f ((lazyGraph G).rot (v, bd)).1) = _ + rw [mean_prod] + change Finset.univ.expect (fun b : Bool => + mean (fun d : D => f ((lazyGraph G).rot (v, (b, d))).1)) = _ + rw [LazySmoothing.expect_bool] + simp only [lazyGraph_rot_false, lazyGraph_rot_true] + rw [mean_const] + rfl + +theorem iterate_lazy_eq_binomialMean [Fintype D] [Nonempty D] + (G : PortGraph V D) (n : Nat) (f : V → ℝ) : + iterateOperator (lazyGraph G) n f = + fun v => LazySmoothing.binomialMean n (fun k => iterateOperator G k f v) := by + induction n with + | zero => + funext v + simp [iterateOperator] + | succ n ih => + funext v + change averagingOperator (lazyGraph G) (iterateOperator (lazyGraph G) n f) v = _ + rw [ih, averagingOperator_lazy, operator_binomialMean, LazySmoothing.mean_succ] + rfl + +theorem iterate_mem_Icc [Fintype D] [Nonempty D] + (G : PortGraph V D) (f : V → ℝ) (hf : ∀ w, f w ∈ Set.Icc (0 : ℝ) 1) + (n : Nat) (v : V) : iterateOperator G n f v ∈ Set.Icc (0 : ℝ) 1 := by + induction n generalizing v with + | zero => exact hf v + | succ n ih => + change mean (fun d : D => iterateOperator G n f (G.rot (v, d)).1) ∈ Set.Icc (0 : ℝ) 1 + constructor + · exact mean_nonnegative _ (fun d => (ih ((G.rot (v, d)).1)).1) + · calc + mean (fun d : D => iterateOperator G n f (G.rot (v, d)).1) ≤ + mean (fun _ : D => (1 : ℝ)) := + mean_mono (fun d => (ih ((G.rot (v, d)).1)).2) + _ = 1 := mean_const _ + +theorem lazy_endpoint_modal_transfer [Fintype D] [Nonempty D] + (G : PortGraph V D) (q M m : Nat) (hq : 1 ≤ q) (hM : 1 ≤ M) + (hlo : (4 * q * M) ^ 2 - M ≤ m) (hhi : m ≤ (4 * q * M) ^ 2 + M) + (f : V → ℝ) (hf : ∀ w, f w ∈ Set.Icc (0 : ℝ) 1) (v : V) + (hmodal : 1 / (q : ℝ) ≤ iterateOperator (lazyGraph G) ((4 * q * M) ^ 2) f v) : + 1 / (2 * (q : ℝ)) ≤ iterateOperator (lazyGraph G) m f v := by + rw [iterate_lazy_eq_binomialMean] at hmodal ⊢ + exact LazySmoothing.modal_transfer q M m hq hM hlo hhi + (fun k => iterateOperator G k f v) (fun k => iterate_mem_Icc G f hf k v) hmodal + +end MinUncutGames.Foundations.PCP.PoweringLazy + +end +section +namespace MinUncutGames.Foundations.PCP.LazyConstraint + +open scoped BigOperators +open PoweringWalks + +variable {V D A : Type*} + +def constraintGraph (G : ConstraintGraph V (V × D) A) : + ConstraintGraph V (V × (Bool × D)) A where + reverse := (lazyGraph (Overlay.originalPortGraph G)).rot + reverse_involutive := (lazyGraph (Overlay.originalPortGraph G)).rot_involutive + tail := Prod.fst + accepts e a b := if e.2.1 then G.accepts (e.1,e.2.2) a b else true + reverse_accepts := by + rintro ⟨v,b,d⟩ a c + cases b with + | false => rfl + | true => exact G.reverse_accepts (v,d) a c + +@[simp] theorem constraintGraph_tail (G : ConstraintGraph V (V × D) A) : + (constraintGraph G).tail = Prod.fst := rfl + +@[simp] theorem constraintGraph_reverse (G : ConstraintGraph V (V × D) A) : + (constraintGraph G).reverse = (lazyGraph (Overlay.originalPortGraph G)).rot := rfl + +@[simp] theorem constraintGraph_portGraph (G : ConstraintGraph V (V × D) A) : + Overlay.originalPortGraph (constraintGraph G) = + lazyGraph (Overlay.originalPortGraph G) := rfl + +@[simp] theorem edgeSatisfied_false (G : ConstraintGraph V (V × D) A) + (labeling : V → A) (v : V) (d : D) : + (constraintGraph G).edgeSatisfied labeling (v,(false,d)) = true := rfl + +@[simp] theorem edgeSatisfied_true (G : ConstraintGraph V (V × D) A) + (htail : G.tail = Prod.fst) (labeling : V → A) (v : V) (d : D) : + (constraintGraph G).edgeSatisfied labeling (v,(true,d)) = + G.edgeSatisfied labeling (v,d) := by + change G.accepts (v,d) (labeling v) (labeling (G.reverse (v,d)).1) = + G.accepts (v,d) (labeling (G.tail (v,d))) + (labeling (G.tail (G.reverse (v,d)))) + rw [htail] + +theorem complete (G : ConstraintGraph V (V × D) A) (htail : G.tail = Prod.fst) + (labeling : V → A) (h : ∀ e, G.edgeSatisfied labeling e = true) : + ∀ e, (constraintGraph G).edgeSatisfied labeling e = true := by + rintro ⟨v,b,d⟩ + cases b with + | false => rfl + | true => + rw [edgeSatisfied_true G htail] + exact h (v,d) + +theorem complete_iff (G : ConstraintGraph V (V × D) A) (htail : G.tail = Prod.fst) + (labeling : V → A) : + (∀ e, (constraintGraph G).edgeSatisfied labeling e = true) ↔ + ∀ e, G.edgeSatisfied labeling e = true := by + constructor + · intro h + rintro ⟨v,d⟩ + rw [← edgeSatisfied_true G htail] + exact h (v,(true,d)) + · exact complete G htail labeling + +theorem satisfiable_iff (G : ConstraintGraph V (V × D) A) (htail : G.tail = Prod.fst) : + (constraintGraph G).Satisfiable ↔ G.Satisfiable := by + constructor + · rintro ⟨labeling,h⟩ + exact ⟨labeling, (complete_iff G htail labeling).mp h⟩ + · rintro ⟨labeling,h⟩ + exact ⟨labeling, complete G htail labeling h⟩ + +theorem rejectionCount_eq [Fintype V] [Fintype D] + (G : ConstraintGraph V (V × D) A) (htail : G.tail = Prod.fst) + (labeling : V → A) : + (constraintGraph G).rejectionCount labeling = G.rejectionCount labeling := by + classical + simp only [DegreeReplacement.rejectionCount_eq_sum, Fintype.sum_prod_type, + Fintype.sum_bool] + simp [edgeSatisfied_true G htail] + +theorem card_ports [Fintype D] : + Fintype.card (Bool × D) = 2 * Fintype.card D := by + simp + +theorem card_darts [Fintype V] [Fintype D] : + Fintype.card (V × (Bool × D)) = 2 * Fintype.card (V × D) := by + simp [Fintype.card_prod, Nat.mul_left_comm] + +theorem rejection_density_eq_half [Fintype V] [Fintype D] + (G : ConstraintGraph V (V × D) A) (htail : G.tail = Prod.fst) + (labeling : V → A) : + ((constraintGraph G).rejectionCount labeling : ℝ) / + (Fintype.card (V × (Bool × D)) : ℝ) = + ((G.rejectionCount labeling : ℝ) / (Fintype.card (V × D) : ℝ)) / 2 := by + rw [rejectionCount_eq G htail, card_darts] + simp only [Nat.cast_mul, Nat.cast_ofNat, div_eq_mul_inv, mul_inv_rev] + ring + +end MinUncutGames.Foundations.PCP.LazyConstraint + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/Parity.lean b/lean/OAI/Computability/MinUncut/PCP/Parity.lean new file mode 100644 index 0000000000000000000000000000000000000000..9b64197a5f5e4bfa1698113a68b3d707d6f6e1dd --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/Parity.lean @@ -0,0 +1,57 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.Convolution +import OAI.Computability.MinUncut.Estimates.ArraySum + +namespace OAI + +noncomputable section +open scoped BigOperators +open MeasureTheory ProbabilityTheory Filter +open scoped Topology NNReal +open scoped BigOperators +open MeasureTheory ProbabilityTheory Polynomial Filter +open scoped BigOperators Topology +open MeasureTheory ProbabilityTheory WithLp +open scoped BigOperators RealInnerProductSpace +namespace MinUncut.GaussianHermite +open MeasureTheory ProbabilityTheory +open scoped BigOperators + +lemma H_neg (d : ℕ) (x : ℝ) : H d (-x) = (-1 : ℝ)^d * H d x := by + have hh := H_noise (-1) 0 x (by norm_num) d + simpa [γ] using hh + +lemma H_sign (d : ℕ) (k : BinaryFourier.F₂) (x : ℝ) : + H d (BinaryFourier.sign k*x) = BinaryFourier.sign (k*(d : BinaryFourier.F₂))*H d x := by + have hs : BinaryFourier.sign (d : BinaryFourier.F₂) = (-1 : ℝ)^d := by + induction d with + | zero => simp + | succ d ih => simp [Nat.cast_add, BinaryFourier.sign_add, ih, pow_succ] + by_cases hk : k = 0 + · simp [hk] + · have hk1 : k = 1 := by + have h : ∀ a : BinaryFourier.F₂, a = 0 ∨ a=1 := by decide + exact (h k).resolve_left hk + simp only [hk1, BinaryFourier.sign_one, neg_one_mul, one_mul, H_neg, hs] + +variable {ι : Type*} [Fintype ι] + +def parity (k : ι → BinaryFourier.F₂) (a : ι → ℕ) : BinaryFourier.F₂ := ∑ i, k i * (a i : BinaryFourier.F₂) + +lemma psi_diagonal (k : ι → BinaryFourier.F₂) (a : ι → ℕ) (c : ι → ℝ) : + psi a (Inner.diagonal k c) = BinaryFourier.sign (parity k a) * psi a c := by + simp only [psi, Inner.diagonal, H_sign, Finset.prod_mul_distrib, parity, RowNoise.sign_sum] + +lemma coeff_diagonal (k : ι → BinaryFourier.F₂) (f : (ι → ℝ) → ℝ) (a : ι → ℕ) : + coeff (fun c => f (Inner.diagonal k c)) a = BinaryFourier.sign (parity k a)*coeff f a := by + unfold coeff + change (∫ c, psi a c * f (Inner.diagonal k c) ∂Inner.gauss ι) = + BinaryFourier.sign (parity k a)*(∫ c, psi a c*f c ∂Inner.gauss ι) + rw [← Inner.integral_diagonal k (fun c => psi a c * f (Inner.diagonal k c))] + simp only [Inner.diagonal_involutive k _, psi_diagonal, mul_assoc, integral_const_mul] + +end MinUncut.GaussianHermite + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/PortTableLookup.lean b/lean/OAI/Computability/MinUncut/PCP/PortTableLookup.lean new file mode 100644 index 0000000000000000000000000000000000000000..76644b0e2c1b57e25de6e85f9d05f92a5b556e2d --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/PortTableLookup.lean @@ -0,0 +1,115 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.GraphTables + +namespace OAI + +section +namespace MinUncutGames.Foundations.PCP.PortTableLookup + +theorem flatMap_word {α β : Type*} (f : α → List β) + (width j : Nat) (hj : j < width) : + ∀ (rows : List α), (∀ a ∈ rows, (f a).length = width) → + ∀ (i : Nat) (row : α), rows[i]? = some row → + (rows.flatMap f)[width * i + j]? = (f row)[j]? := by + intro rows + induction rows with + | nil => + intro _ i row selected + simp at selected + | cons a rows ih => + intro hwidth i row selected + have ha : (f a).length = width := hwidth a (by simp) + cases i with + | zero => + have heq : a = row := by simpa using selected + subst row + simp only [Nat.mul_zero, Nat.zero_add, List.flatMap_cons] + exact List.getElem?_append_left (by omega) + | succ i => + have selected' : rows[i]? = some row := by simpa using selected + have hskip : (f a).length ≤ width * (i + 1) + j := by + rw [ha, Nat.mul_add, Nat.mul_one] + omega + have hoff : width * (i + 1) + j - (f a).length = width * i + j := by + rw [ha, Nat.mul_add, Nat.mul_one] + omega + rw [List.flatMap_cons, List.getElem?_append_right hskip, hoff] + exact ih (fun b hb => hwidth b (by simp [hb])) i row selected' + +variable {n d : Nat} + +theorem vertices_word (table : PortTables.Table n d) : + (PortTables.tableWords table)[0]? = some n := rfl + +theorem darts_word (table : PortTables.Table n d) : + (PortTables.tableWords table)[1]? = some (n * d) := rfl + +private theorem row_word (table : PortTables.Table n d) (i : Fin (n * d)) + (j : Nat) (hj : j < 4098) : + (PortTables.tableWords table)[2 + 4098 * i.val + j]? = + (GraphTables.rowWords (PortTables.flatRows table)[i])[j]? := by + rw [PortTables.tableWords_eq] + change (n :: n * d :: (PortTables.flatRows table).toList.flatMap + GraphTables.rowWords)[2 + 4098 * i.val + j]? = _ + rw [show 2 + 4098 * i.val + j = (4098 * i.val + j + 1) + 1 by omega, + List.getElem?_cons_succ, List.getElem?_cons_succ] + apply flatMap_word GraphTables.rowWords 4098 j hj + (PortTables.flatRows table).toList + (fun row _ => GraphTables.rowWords_length row) i.val + ((PortTables.flatRows table)[i]) + simp only [Vector.getElem?_toList, Vector.getElem?_eq_getElem i.isLt, + Fin.getElem_fin] + +theorem tail_word (table : PortTables.Table n d) (i : Fin (n * d)) : + (PortTables.tableWords table)[2 + 4098 * i.val]? = + some (((PortTables.rowIndex n d).symm i).1.val) := by + have h := row_word table i 0 (by decide) + simpa only [Nat.add_zero, GraphTables.rowWords, PortTables.flatRows, + Fin.getElem_fin, Vector.getElem_ofFn, Fin.eta, List.cons_append, + List.nil_append, List.getElem?_cons_zero] using h + +theorem reverse_word (table : PortTables.Table n d) (i : Fin (n * d)) : + (PortTables.tableWords table)[3 + 4098 * i.val]? = + some (table.reverseIndex[i].val) := by + have h := row_word table i 1 (by decide) + rw [show 2 + 4098 * i.val + 1 = 3 + 4098 * i.val by omega] at h + simpa only [GraphTables.rowWords, PortTables.flatRows, Fin.getElem_fin, + Vector.getElem_ofFn, Fin.eta, List.cons_append, List.nil_append, + List.getElem?_cons_succ, List.getElem?_cons_zero] using h + +theorem relation_word (table : PortTables.Table n d) (i : Fin (n * d)) + (j : Fin 4096) : + (PortTables.tableWords table)[4 + 4098 * i.val + j.val]? = + some (GraphTables.bitWord table.relations[i][j]) := by + have h := row_word table i (j.val + 2) (by omega) + rw [show 2 + 4098 * i.val + (j.val + 2) = 4 + 4098 * i.val + j.val by omega] at h + simpa only [GraphTables.rowWords, GraphTables.relationWords, + PortTables.flatRows, Fin.getElem_fin, Vector.getElem_ofFn, Fin.eta, + List.cons_append, List.nil_append, List.getElem?_cons_succ, + List.getElem?_map, Vector.getElem?_toList, + Vector.getElem?_eq_getElem j.isLt, Option.map_some] using h + +theorem accepts_word (table : PortTables.Table n d) (e : Fin n × Fin d) + (a b : PortTables.Label) : + (PortTables.tableWords table)[4 + 4098 * (PortTables.rowIndex n d e).val + + (GraphTables.relationIndex (a, b)).val]? = + some (GraphTables.bitWord (PortTables.accepts table e a b)) := + relation_word table (PortTables.rowIndex n d e) (GraphTables.relationIndex (a, b)) + +theorem rotation_head_word (table : PortTables.Table n d) (e : Fin n × Fin d) : + (PortTables.tableWords table)[2 + 4098 * (table.reverseIndex[PortTables.rowIndex n d e]).val]? = + some ((PortTables.rotation table e).1.val) := + tail_word table (table.reverseIndex[PortTables.rowIndex n d e]) + +theorem rotor_lookups (table : PortTables.Table n d) (e : Fin n × Fin d) : + (PortTables.tableWords table)[3 + 4098 * (PortTables.rowIndex n d e).val]? = + some (table.reverseIndex[PortTables.rowIndex n d e].val) ∧ + (PortTables.tableWords table)[2 + 4098 * (table.reverseIndex[PortTables.rowIndex n d e]).val]? = + some ((PortTables.rotation table e).1.val) := + ⟨reverse_word table (PortTables.rowIndex n d e), rotation_head_word table e⟩ + +end MinUncutGames.Foundations.PCP.PortTableLookup + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/PoweringFinalConstants.lean b/lean/OAI/Computability/MinUncut/PCP/PoweringFinalConstants.lean new file mode 100644 index 0000000000000000000000000000000000000000..04d79fa0379ce13fe6731afad126dd88e3c9bc83 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/PoweringFinalConstants.lean @@ -0,0 +1,695 @@ +import Mathlib +import OAI.Computability.MinUncut.Games.FinalCNFPattern +import OAI.Computability.MinUncut.PCP.GraphTableComplexity + +namespace OAI + +section +namespace MinUncutGames.Foundations.PCP.PoweringFinalConstants + +abbrev Alphabet := Fin 6 → Bool + +@[simp] theorem card_alphabet : Fintype.card Alphabet = 64 := by + norm_num [Alphabet, Fintype.card_fun] + +theorem card_alphabet_eq_final : Fintype.card Alphabet = FinalConstants.alphabet := by + exact card_alphabet + +theorem center_eq : + PoweringSoundness.center (Fintype.card Alphabet) FinalConstants.windowHalf = + FinalConstants.endpointLength := by + rw [card_alphabet] + rfl + +theorem walkLength_eq : + 2 * PoweringSoundness.center (Fintype.card Alphabet) FinalConstants.windowHalf + 1 = + FinalConstants.walkLength := by + rw [center_eq] + rfl + +theorem spectral_denominator_eq : + (1 + 2 / (1 - (31 / 32 : ℝ))) + 1 = 66 := by + norm_num + +theorem gain_eq : + PoweringSoundness.gain 64 FinalConstants.windowHalf (31 / 32) / 12288 = + FinalConstants.gain := by + change + (1 / (2 * (FinalConstants.alphabet : ℝ))) ^ 4 * + (FinalConstants.windowSize : ℝ) / + ((1 + 2 / (1 - (31 / 32 : ℝ))) + 1) / + (FinalConstants.compositionLoss : ℝ) = + (FinalConstants.windowSize : ℝ) / (FinalConstants.denominator : ℝ) + rw [spectral_denominator_eq] + have hden : (FinalConstants.denominator : ℝ) = + 16 * (FinalConstants.alphabet : ℝ) ^ 4 * 66 * + (FinalConstants.compositionLoss : ℝ) := by + simp only [FinalConstants.denominator, Nat.cast_mul, Nat.cast_pow, Nat.cast_ofNat] + rw [hden] + simp only [div_eq_mul_inv, mul_inv_rev] + ring + +theorem gain_card_eq : + PoweringSoundness.gain (Fintype.card Alphabet) FinalConstants.windowHalf (31 / 32) / + 12288 = FinalConstants.gain := by + rw [card_alphabet] + exact gain_eq + +theorem scaled_bound_eq (ε : ℝ) : + (PoweringSoundness.gain (Fintype.card Alphabet) FinalConstants.windowHalf (31 / 32) * + min ε + (1 / ((2 * PoweringSoundness.center (Fintype.card Alphabet) + FinalConstants.windowHalf + 1 : Nat) : ℝ))) / 12288 = + FinalConstants.gain * min ε FinalConstants.cap := by + rw [walkLength_eq] + rw [mul_div_right_comm, gain_card_eq] + rfl + +theorem composed_scaled_gap (ε : ℝ) (hε : 0 ≤ ε) : + min (2 * ε) FinalConstants.cap ≤ + (PoweringSoundness.gain (Fintype.card Alphabet) FinalConstants.windowHalf (31 / 32) * + min (ε / (Preprocessing.sizeFactor : ℝ)) + (1 / ((2 * PoweringSoundness.center (Fintype.card Alphabet) + FinalConstants.windowHalf + 1 : Nat) : ℝ))) / 12288 := by + rw [scaled_bound_eq] + exact FinalConstants.composed_gap ε hε + +end MinUncutGames.Foundations.PCP.PoweringFinalConstants + +end +section +noncomputable section + +namespace MinUncutGames.Foundations.PCP.RoundGap + +open AmplificationRound + +variable {V E : Type*} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + [Nonempty E] + +def poweredLower (epsilon : ℝ) : ℝ := + PoweringSoundness.gain (Fintype.card Label) FinalConstants.windowHalf (31 / 32) * + min (epsilon / (Preprocessing.sizeFactor : ℝ)) FinalConstants.cap + +theorem poweredLower_nonnegative (epsilon : ℝ) (he : 0 ≤ epsilon) : + 0 ≤ poweredLower epsilon := by + have hg := PoweringGap.gain_nonneg (Fintype.card Label) + FinalConstants.windowHalf (31 / 32) (by norm_num) + have hs : (0 : ℝ) < Preprocessing.sizeFactor := by + exact_mod_cast Preprocessing.sizeFactor_positive + exact mul_nonneg hg (le_min (div_nonneg he hs.le) FinalConstants.cap_positive.le) + +theorem powered_count_gap (addresses : List Addresses) (complete : ∀ w, w ∈ addresses) + (G : ConstraintGraph V E Label) + (labeling : Preprocessing.Vertex G → PoweredAlphabet) : + poweredLower G.gap * (Fintype.card (PoweredDart G) : ℝ) ≤ + ((powered addresses complete G).rejectionCount labeling : ℝ) := by + let H := Overlay.originalPortGraph (Preprocessing.overlayGraph G) + have certificate : SpectralReturn.SpectralCertificate + (PoweringWalks.lazyGraph H) (31 / 32 : ℝ) := + Preprocessing.spectral_certificate G + have lower : ∀ assignment : Preprocessing.Vertex G → Label, + (G.gap / (Preprocessing.sizeFactor : ℝ)) * + (Fintype.card (Preprocessing.Vertex G × Preprocessing.Port) : ℝ) ≤ + ((Preprocessing.graph G).rejectionCount assignment : ℝ) := + Preprocessing.gap_transfer_real G G.gap G.gap_nonnegative + ((G.le_gap_iff G.gap).mp le_rfl) + have hs : (0 : ℝ) < Preprocessing.sizeFactor := by + exact_mod_cast Preprocessing.sizeFactor_positive + have h := PoweringGap.uniform_count_gap H (31 / 32) certificate + (Preprocessing.graph G).accepts (Preprocessing.accepts_reverse G) + FinalConstants.windowHalf FinalConstants.windowHalf_positive + (selectors addresses complete G) + (G.gap / (Preprocessing.sizeFactor : ℝ)) (div_nonneg G.gap_nonnegative hs.le) + lower labeling + convert h using 1 <;> + simp only [poweredLower, powered, FinalConstants.cap, FinalConstants.walkLength, + PoweringFinalConstants.center_eq] + rfl + +theorem amplifies (addresses : List Addresses) (complete : ∀ w, w ∈ addresses) + (G : ConstraintGraph V E Label) : + min (2 * G.gap) FinalConstants.cap ≤ (graph addresses complete G).gap := by + apply ((graph addresses complete G).le_gap_iff _).mpr + intro labeling + have hcount := AlphabetGraphBounds.gap_transfer_real (powered addresses complete G) + (poweredLower G.gap) (poweredLower_nonnegative G.gap G.gap_nonnegative) + (powered_count_gap addresses complete G) labeling + have hscalar : min (2 * G.gap) FinalConstants.cap ≤ poweredLower G.gap / 12288 := by + simpa only [poweredLower, FinalConstants.cap, FinalConstants.walkLength, + PoweringFinalConstants.center_eq] using + PoweringFinalConstants.composed_scaled_gap G.gap G.gap_nonnegative + exact (mul_le_mul_of_nonneg_right hscalar (Nat.cast_nonneg _)).trans hcount + +end MinUncutGames.Foundations.PCP.RoundGap + +end +end +section +namespace MinUncutGames.Foundations.PCP.RoundSize + +open scoped BigOperators + +noncomputable section + +theorem card_padded_alphabet {D A : Type*} [Fintype D] [DecidableEq D] + [Fintype A] (t : Nat) : + Fintype.card (PoweringLabels.PaddedLabel D t A) = + Fintype.card A ^ (∑ k : Fin (t + 1), Fintype.card D ^ k.val) := by + simpa only [Nat.card_eq_fintype_card] using + PoweringLabels.card_paddedLabel (D := D) (A := A) t + +theorem card_powered_dart {V D : Type*} [Fintype V] [Fintype D] + (n : Nat) : Fintype.card (PoweringTest.Dart V D n) = + Fintype.card V * (2 * Fintype.card D ^ (n + 1)) := by + simp only [PoweringTest.Dart, PoweringWalks.Walk, Fintype.card_prod, + Fintype.card_bool, Fintype.card_fun, Fintype.card_fin] + ring + +private opaque lockedNat (n : Nat) : {m : Nat // m = n} := ⟨n, rfl⟩ + +def poweredAlphabetSize : Nat := + (lockedNat (64 ^ (∑ k : Fin (FinalConstants.walkLength + 1), + Preprocessing.degree ^ k.val))).val + +def poweredDartFactor : Nat := + (lockedNat (2 * Preprocessing.degree ^ (2 * FinalConstants.endpointLength + 1))).val + +def sizeFactor : Nat := + (lockedNat (AlphabetGraphBounds.sizeFactor poweredAlphabetSize * + (1 + poweredDartFactor) * ExpanderFamily.growth ^ 2)).val + +theorem poweredAlphabetSize_eq : poweredAlphabetSize = + 64 ^ (∑ k : Fin (FinalConstants.walkLength + 1), Preprocessing.degree ^ k.val) := + (lockedNat _).property + +theorem poweredDartFactor_eq : poweredDartFactor = + 2 * Preprocessing.degree ^ (2 * FinalConstants.endpointLength + 1) := + (lockedNat _).property + +theorem sizeFactor_eq : sizeFactor = AlphabetGraphBounds.sizeFactor poweredAlphabetSize * + (1 + poweredDartFactor) * ExpanderFamily.growth ^ 2 := + (lockedNat _).property + +private theorem coefficient_positive (q d g : Nat) (hg : 0 < g) : + 0 < AlphabetGraphBounds.sizeFactor q * (1 + d) * g ^ 2 := by + exact Nat.mul_pos (Nat.mul_pos (AlphabetGraphBounds.sizeFactor_positive q) + (Nat.zero_lt_one.trans_le (Nat.le_add_right 1 d))) (pow_pos hg 2) + +theorem poweredAlphabet_card : Fintype.card AmplificationRound.PoweredAlphabet = + poweredAlphabetSize := by + have h := PoweringLabels.card_paddedLabel (D := Preprocessing.Port) + (A := QueryIncidence.Label 6) FinalConstants.walkLength + change Nat.card AmplificationRound.PoweredAlphabet = _ at h + simp only [Nat.card_eq_fintype_card, ← Preprocessing.degree_eq_card, + QueryIncidence.six_query_alphabet] at h + exact h.trans poweredAlphabetSize_eq.symm + +theorem sizeFactor_positive : 0 < sizeFactor := by + have hG : 0 < ExpanderFamily.growth := + Nat.zero_lt_one.trans ExpanderFamily.growth_gt_one + rw [sizeFactor_eq] + exact coefficient_positive _ _ _ hG + +private theorem factor_total (c v d : Nat) : c * (v + v * d) = c * (1 + d) * v := by + ring + +private theorem nat_card_output_vertex {V E A : Type*} + [Fintype V] [Fintype E] [Fintype A] [DecidableEq A] [Nonempty A] : + Nat.card (AlphabetGraphBounds.OutputVertex V E A) = + Nat.card V * 2 ^ Nat.card A + + Nat.card E * AlphabetGraphBounds.vertexFactor (Nat.card A) := by + simpa only [← Nat.card_eq_fintype_card] using + AlphabetGraphBounds.card_output_vertex (V := V) (E := E) (A := A) + +private theorem nat_card_output_dart {E A : Type*} + [Fintype E] [Fintype A] [DecidableEq A] [Nonempty A] : + Nat.card (AlphabetGraphBounds.OutputDart E A) = + Nat.card E * AlphabetGraphBounds.dartFactor (Nat.card A) := by + simpa only [← Nat.card_eq_fintype_card] using + AlphabetGraphBounds.card_output_dart (E := E) (A := A) + +private theorem nat_card_output_total_le {V E A : Type*} + [Fintype V] [Fintype E] [Fintype A] [DecidableEq A] [Nonempty A] : + Nat.card (AlphabetGraphBounds.OutputVertex V E A) + + Nat.card (AlphabetGraphBounds.OutputDart E A) ≤ + AlphabetGraphBounds.sizeFactor (Nat.card A) * (Nat.card V + Nat.card E) := by + simpa only [← Nat.card_eq_fintype_card] using + AlphabetGraphBounds.card_output_total_le (V := V) (E := E) (A := A) + +variable {V E : Type*} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + [Nonempty E] + +omit [DecidableEq E] [Nonempty E] in +theorem poweredDart_card (G : ConstraintGraph V E AmplificationRound.Label) : + Fintype.card (AmplificationRound.PoweredDart G) = + Fintype.card (Preprocessing.Vertex G) * poweredDartFactor := by + have h := card_powered_dart (V := Preprocessing.Vertex G) (D := Preprocessing.Port) + (2 * FinalConstants.endpointLength) + rw [← Preprocessing.degree_eq_card] at h + exact h.trans (congrArg (fun d => Fintype.card (Preprocessing.Vertex G) * d) + poweredDartFactor_eq.symm) + +omit [DecidableEq E] [Nonempty E] in + +theorem output_vertex_card (G : ConstraintGraph V E AmplificationRound.Label) : + Fintype.card (AmplificationRound.Vertex G) = + Fintype.card (Preprocessing.Vertex G) * 2 ^ poweredAlphabetSize + + (Fintype.card (Preprocessing.Vertex G) * poweredDartFactor) * + AlphabetGraphBounds.vertexFactor poweredAlphabetSize := by + have h := nat_card_output_vertex (V := Preprocessing.Vertex G) + (E := AmplificationRound.PoweredDart G) (A := AmplificationRound.PoweredAlphabet) + change Nat.card (AmplificationRound.Vertex G) = + Nat.card (Preprocessing.Vertex G) * 2 ^ Nat.card AmplificationRound.PoweredAlphabet + + Nat.card (AmplificationRound.PoweredDart G) * + AlphabetGraphBounds.vertexFactor (Nat.card AmplificationRound.PoweredAlphabet) at h + simpa only [Nat.card_eq_fintype_card, poweredAlphabet_card, poweredDart_card] using h + +omit [DecidableEq E] [Nonempty E] in + +theorem output_dart_card (G : ConstraintGraph V E AmplificationRound.Label) : + Fintype.card (AmplificationRound.Dart G) = + (Fintype.card (Preprocessing.Vertex G) * poweredDartFactor) * + AlphabetGraphBounds.dartFactor poweredAlphabetSize := by + have h := nat_card_output_dart (E := AmplificationRound.PoweredDart G) + (A := AmplificationRound.PoweredAlphabet) + change Nat.card (AmplificationRound.Dart G) = Nat.card (AmplificationRound.PoweredDart G) * + AlphabetGraphBounds.dartFactor (Nat.card AmplificationRound.PoweredAlphabet) at h + simpa only [Nat.card_eq_fintype_card, poweredAlphabet_card, poweredDart_card] using h + +omit [DecidableEq E] in +theorem output_total_le_darts (G : ConstraintGraph V E AmplificationRound.Label) : + Fintype.card (AmplificationRound.Vertex G) + Fintype.card (AmplificationRound.Dart G) ≤ + sizeFactor * Fintype.card E := by + have h := nat_card_output_total_le + (V := Preprocessing.Vertex G) (E := AmplificationRound.PoweredDart G) + (A := AmplificationRound.PoweredAlphabet) + change Nat.card (AmplificationRound.Vertex G) + Nat.card (AmplificationRound.Dart G) ≤ + AlphabetGraphBounds.sizeFactor (Nat.card AmplificationRound.PoweredAlphabet) * + (Nat.card (Preprocessing.Vertex G) + Nat.card (AmplificationRound.PoweredDart G)) at h + simp only [Nat.card_eq_fintype_card] at h + rw [poweredAlphabet_card, poweredDart_card] at h + calc + _ ≤ AlphabetGraphBounds.sizeFactor poweredAlphabetSize * + (Fintype.card (Preprocessing.Vertex G) + + Fintype.card (Preprocessing.Vertex G) * poweredDartFactor) := h + _ = (AlphabetGraphBounds.sizeFactor poweredAlphabetSize * + (1 + poweredDartFactor)) * Fintype.card (Preprocessing.Vertex G) := + factor_total _ _ _ + _ ≤ (AlphabetGraphBounds.sizeFactor poweredAlphabetSize * + (1 + poweredDartFactor)) * (ExpanderFamily.growth ^ 2 * Fintype.card E) := + Nat.mul_le_mul_left _ (Preprocessing.vertex_count_le G) + _ = sizeFactor * Fintype.card E := by + rw [sizeFactor_eq] + exact (Nat.mul_assoc _ _ _).symm + +omit [DecidableEq E] in +theorem output_total_le (G : ConstraintGraph V E AmplificationRound.Label) : + Fintype.card (AmplificationRound.Vertex G) + Fintype.card (AmplificationRound.Dart G) ≤ + sizeFactor * (Fintype.card V + Fintype.card E) := + (output_total_le_darts G).trans (Nat.mul_le_mul_left _ (Nat.le_add_left _ _)) + +end + +end MinUncutGames.Foundations.PCP.RoundSize + +end +section +namespace MinUncutGames.Foundations.Hastad.SourceNonempty + +open Target PCP + +theorem real_clause_gap_of_count (F : Formula) (a b : ℕ) (hb : 0 < b) + (hgap : ∀ assignment : Fin F.«variables» → Bool, + a * F.clauses.length ≤ b * NameCompaction.failedCount F assignment) + (assignment : Fin F.«variables» → Bool) : + (a : ℝ) / (b : ℝ) * F.clauses.length ≤ + (failureCount F assignment (allIndices F) : ℝ) := by + rw [NameCompaction.verifier_failureCount] + have hreal : (a : ℝ) * F.clauses.length ≤ + (b : ℝ) * (NameCompaction.failedCount F assignment : ℝ) := by + exact_mod_cast hgap assignment + rw [div_mul_eq_mul_div] + apply (div_le_iff₀ (Nat.cast_pos.mpr hb)).mpr + simpa only [mul_comm] using hreal + +theorem clauseGap_of_count (F : Formula) (a b : ℕ) (hne : F.clauses ≠ []) + (hb : 0 < b) + (hgap : ∀ assignment : Fin F.«variables» → Bool, + a * F.clauses.length ≤ b * NameCompaction.failedCount F assignment) : + SourceGap.ClauseGap F ((a : ℚ) / (b : ℚ)) := by + refine ⟨hne, fun assignment => ?_⟩ + simpa only [Rat.cast_div, Rat.cast_natCast] using + real_clause_gap_of_count F a b hb hgap assignment + +variable {V E : Type*} {n m : ℕ} + +theorem cnf_nonempty_of_nonempty_darts [Fintype E] [Nonempty E] + (G : ConstraintGraph V E FinalBooleanVerifier.Label) + (vertices : V ≃ Fin n) (edges : E ≃ Fin m) : + (FinalBooleanVerifier.cnf G vertices edges).clauses ≠ [] := by + have hcard : Fintype.card E = m := by + simpa only [Fintype.card_fin] using Fintype.card_congr edges + have hm : 0 < m := hcard ▸ Fintype.card_pos + exact FinalBooleanVerifier.cnf_nonempty G vertices edges hm + +theorem cnf_clauseGap [Fintype E] [Nonempty E] + (G : ConstraintGraph V E FinalBooleanVerifier.Label) + (vertices : V ≃ Fin n) (edges : E ≃ Fin m) (a b : ℕ) (hb : 0 < b) + (hgap : ∀ labeling : V → FinalBooleanVerifier.Label, + a * Fintype.card E ≤ b * G.rejectionCount labeling) : + SourceGap.ClauseGap (FinalBooleanVerifier.cnf G vertices edges) + ((a : ℚ) / ((b : ℚ) * 40960)) := by + have h := clauseGap_of_count (FinalBooleanVerifier.cnf G vertices edges) a (b * 40960) + (cnf_nonempty_of_nonempty_darts G vertices edges) + (Nat.mul_pos hb (by decide)) (FinalBooleanVerifier.cnf_gap G vertices edges a b hgap) + simpa only [Nat.cast_mul, Nat.cast_ofNat] using h + +theorem cnf_clauseGap_unit [Fintype E] [Nonempty E] + (G : ConstraintGraph V E FinalBooleanVerifier.Label) + (vertices : V ≃ Fin n) (edges : E ≃ Fin m) (walkLength : ℕ) + (hwalk : 0 < walkLength) + (hgap : ∀ labeling : V → FinalBooleanVerifier.Label, + Fintype.card E ≤ walkLength * G.rejectionCount labeling) : + SourceGap.ClauseGap (FinalBooleanVerifier.cnf G vertices edges) + (1 / (40960 * (walkLength : ℚ))) := by + have h := cnf_clauseGap G vertices edges 1 walkLength hwalk + (by simpa only [one_mul] using hgap) + simpa only [Nat.cast_one, mul_comm] using h + +end MinUncutGames.Foundations.Hastad.SourceNonempty + +end +section +noncomputable section + +namespace MinUncutGames.Foundations.PCP.PCPIteration + +open FiniteGraph + +abbrev Label := AlphabetRetraction.Label64 +abbrev Graph := Bundle Label +abbrev Addresses := AmplificationRound.Addresses + +def step (addresses : List Addresses) (complete : ∀ w, w ∈ addresses) (G : Graph) : Graph := by + classical + exact Bundle.ofGraph (AmplificationRound.graph addresses complete G.graph) + +def run (addresses : List Addresses) (complete : ∀ w, w ∈ addresses) : Nat → Graph → Graph := + AmplificationIteration.run (step addresses complete) + +def initial (F : Target.Formula) : Graph := Bundle.ofGraph (AlphabetRetraction.initial64 F) + +def iterationCount (F : Target.Formula) : Nat := AmplificationIteration.rounds (initial F).size + +def output (addresses : List Addresses) (complete : ∀ w, w ∈ addresses) + (F : Target.Formula) : Graph := run addresses complete (iterationCount F) (initial F) + +def polynomialDegree : Nat := AmplificationIteration.rounds RoundSize.sizeFactor + +def finalClauseGap : ℚ := 1 / (40960 * (FinalConstants.walkLength : ℚ)) + +theorem finalClauseGap_positive : 0 < finalClauseGap := by + apply one_div_pos.mpr + exact mul_pos (by norm_num) (by exact_mod_cast FinalConstants.walkLength_positive) + +theorem sizeFactor_le_power : RoundSize.sizeFactor ≤ 2 ^ polynomialDegree := + (AmplificationIteration.rounds_large RoundSize.sizeFactor).le + +theorem initial_satisfiable_iff (F : Target.Formula) : + (initial F).Satisfiable ↔ F.Satisfiable := + AlphabetRetraction.initial64_satisfiable_iff F + +theorem initial_size_positive (F : Target.Formula) : 0 < (initial F).size := + (initial F).size_positive + +theorem initial_size_bound (F : Target.Formula) : + (initial F).size ≤ 10 * F.clauses.length + 2 := by + change Fintype.card (InitialGraph.CompactVertex F) + + Fintype.card (InitialGraph.CompactDart F) ≤ _ + rw [InitialGraph.build_dart_count] + have h := InitialGraph.build_vertex_bound F + omega + +theorem step_completeness (addresses : List Addresses) (complete : ∀ w, w ∈ addresses) + (G : Graph) (satisfied : G.Satisfiable) : (step addresses complete G).Satisfiable := + AmplificationRound.completeness addresses complete G.graph satisfied + +theorem step_gap (addresses : List Addresses) (complete : ∀ w, w ∈ addresses) (G : Graph) : + min (2 * G.gap) FinalConstants.cap ≤ (step addresses complete G).gap := + RoundGap.amplifies addresses complete G.graph + +theorem step_size (addresses : List Addresses) (complete : ∀ w, w ∈ addresses) (G : Graph) : + (step addresses complete G).size ≤ RoundSize.sizeFactor * G.size := + RoundSize.output_total_le G.graph + +theorem run_completeness (addresses : List Addresses) (complete : ∀ w, w ∈ addresses) + (n : Nat) (G : Graph) (satisfied : G.Satisfiable) : + (run addresses complete n G).Satisfiable := + AmplificationIteration.run_preserves (step addresses complete) Bundle.Satisfiable + (step_completeness addresses complete) n G satisfied + +theorem run_gap (addresses : List Addresses) (complete : ∀ w, w ∈ addresses) + (n : Nat) (G : Graph) : + min (2 ^ n * G.gap) FinalConstants.cap ≤ (run addresses complete n G).gap := + AmplificationIteration.run_gap (step addresses complete) Bundle.gap + FinalConstants.cap FinalConstants.cap_positive.le (step_gap addresses complete) n G + +theorem run_size (addresses : List Addresses) (complete : ∀ w, w ∈ addresses) + (n : Nat) (G : Graph) : + (run addresses complete n G).size ≤ RoundSize.sizeFactor ^ n * G.size := + AmplificationIteration.run_size (step addresses complete) Bundle.size RoundSize.sizeFactor + (step_size addresses complete) n G + +theorem output_completeness (addresses : List Addresses) (complete : ∀ w, w ∈ addresses) + (F : Target.Formula) (satisfied : F.Satisfiable) : + (output addresses complete F).Satisfiable := + run_completeness addresses complete (iterationCount F) (initial F) + ((initial_satisfiable_iff F).mpr satisfied) + +theorem output_gap (addresses : List Addresses) (complete : ∀ w, w ∈ addresses) + (F : Target.Formula) (unsat : ¬ F.Satisfiable) : + FinalConstants.cap ≤ (output addresses complete F).gap := by + have hinitial : ¬ (initial F).Satisfiable := + fun h => unsat ((initial_satisfiable_iff F).mp h) + exact AmplificationIteration.run_reaches_cap (step addresses complete) Bundle.gap + FinalConstants.cap FinalConstants.cap_positive.le FinalConstants.cap_le_one + (step_gap addresses complete) (initial F).size (initial F) + (initial F).gap_nonnegative ((initial F).one_le_size_mul_gap hinitial) + +theorem output_satisfiable_iff (addresses : List Addresses) (complete : ∀ w, w ∈ addresses) + (F : Target.Formula) : (output addresses complete F).Satisfiable ↔ F.Satisfiable := by + constructor + · intro satisfied + by_contra unsat + have hgap := output_gap addresses complete F unsat + rw [(output addresses complete F).gap_eq_zero_iff.mpr satisfied] at hgap + exact (not_le_of_gt FinalConstants.cap_positive) hgap + · exact output_completeness addresses complete F + +theorem output_size_polynomial (addresses : List Addresses) (complete : ∀ w, w ∈ addresses) + (F : Target.Formula) : + (output addresses complete F).size ≤ + (2 * (initial F).size) ^ polynomialDegree * (initial F).size := + AmplificationIteration.run_size_polynomial (step addresses complete) Bundle.size + (initial_size_positive F) sizeFactor_le_power (step_size addresses complete) (initial F) + +theorem output_size_clause_bound (addresses : List Addresses) (complete : ∀ w, w ∈ addresses) + (F : Target.Formula) : + (output addresses complete F).size ≤ + (2 * (10 * F.clauses.length + 2)) ^ polynomialDegree * (10 * F.clauses.length + 2) := by + have h := initial_size_bound F + exact (output_size_polynomial addresses complete F).trans + (Nat.mul_le_mul (Nat.pow_le_pow_left (Nat.mul_le_mul_left 2 h) _) h) + +theorem output_count_gap (addresses : List Addresses) (complete : ∀ w, w ∈ addresses) + (F : Target.Formula) (unsat : ¬ F.Satisfiable) + (labeling : (output addresses complete F).Vertex → Label) : + Fintype.card (output addresses complete F).Dart ≤ + FinalConstants.walkLength * (output addresses complete F).rejectionCount labeling := by + have h := ((output addresses complete F).le_gap_iff FinalConstants.cap).mp + (output_gap addresses complete F unsat) labeling + have ht : (0 : ℝ) < FinalConstants.walkLength := by + exact_mod_cast FinalConstants.walkLength_positive + have h' : (Fintype.card (output addresses complete F).Dart : ℝ) / + FinalConstants.walkLength ≤ + ((output addresses complete F).rejectionCount labeling : ℝ) := by + simpa only [FinalConstants.cap, one_div_mul_eq_div] using h + have h'' := (div_le_iff₀ ht).mp h' + exact_mod_cast (show (Fintype.card (output addresses complete F).Dart : ℝ) ≤ + (FinalConstants.walkLength : ℝ) * + ((output addresses complete F).rejectionCount labeling : ℝ) by + simpa only [mul_comm] using h'') + +section FinalCNF + +variable (addresses : List Addresses) (complete : ∀ w, w ∈ addresses) + (F : Target.Formula) {n m : Nat} + (vertices : (output addresses complete F).Vertex ≃ Fin n) + (darts : (output addresses complete F).Dart ≃ Fin m) + +def finalCNF : Target.Formula := + FinalBooleanVerifier.cnf (output addresses complete F).graph vertices darts + +theorem finalCNF_satisfiable_iff : + (finalCNF addresses complete F vertices darts).Satisfiable ↔ F.Satisfiable := + (FinalBooleanVerifier.cnf_satisfiable_iff _ vertices darts).trans + (output_satisfiable_iff addresses complete F) + +theorem finalCNF_clause_count : + (finalCNF addresses complete F vertices darts).clauses.length = m * 40960 := + FinalBooleanVerifier.cnf_clause_count _ vertices darts + +theorem finalCNF_variable_count : + (finalCNF addresses complete F vertices darts).«variables» = n * 6 + m * 36864 := + FinalBooleanVerifier.cnf_variable_count _ vertices darts + +theorem finalCNF_nonempty : (finalCNF addresses complete F vertices darts).clauses ≠ [] := by + have hm : Fintype.card (output addresses complete F).Dart = m := by + simpa only [Fintype.card_fin] using Fintype.card_congr darts + have hpositive : 0 < m := hm ▸ (Fintype.card_pos : + 0 < Fintype.card (output addresses complete F).Dart) + exact FinalBooleanVerifier.cnf_nonempty _ vertices darts hpositive + +theorem finalCNF_gap (unsat : ¬ F.Satisfiable) + (assignment : Fin (finalCNF addresses complete F vertices darts).«variables» → Bool) : + (finalCNF addresses complete F vertices darts).clauses.length ≤ + (FinalConstants.walkLength * 40960) * + NameCompaction.failedCount (finalCNF addresses complete F vertices darts) assignment := by + have source (labeling : (output addresses complete F).Vertex → Label) : + 1 * Fintype.card (output addresses complete F).Dart ≤ + FinalConstants.walkLength * (output addresses complete F).graph.rejectionCount labeling := by + simpa only [one_mul, Bundle.rejectionCount] using output_count_gap addresses complete F unsat labeling + simpa only [one_mul, finalCNF] using FinalBooleanVerifier.cnf_gap + (output addresses complete F).graph vertices darts 1 FinalConstants.walkLength source assignment + +theorem finalCNF_clauseGap (unsat : ¬ F.Satisfiable) : + Hastad.SourceGap.ClauseGap (finalCNF addresses complete F vertices darts) finalClauseGap := + Hastad.SourceNonempty.cnf_clauseGap_unit (output addresses complete F).graph + vertices darts FinalConstants.walkLength FinalConstants.walkLength_positive + (output_count_gap addresses complete F unsat) + +theorem finalCNF_total_size : + (finalCNF addresses complete F vertices darts).«variables» + + (finalCNF addresses complete F vertices darts).clauses.length ≤ + 77824 * (output addresses complete F).size := by + have hn : Fintype.card (output addresses complete F).Vertex = n := by + simpa only [Fintype.card_fin] using Fintype.card_congr vertices + have hm : Fintype.card (output addresses complete F).Dart = m := by + simpa only [Fintype.card_fin] using Fintype.card_congr darts + have hsize : (output addresses complete F).size = n + m := congrArg₂ Nat.add hn hm + calc + _ = n * 6 + m * 36864 + m * 40960 := + congrArg₂ Nat.add (finalCNF_variable_count addresses complete F vertices darts) + (finalCNF_clause_count addresses complete F vertices darts) + _ ≤ 77824 * (n + m) := by omega + _ = 77824 * (output addresses complete F).size := + congrArg (fun k => 77824 * k) hsize.symm + +theorem finalCNF_polynomial_size : + (finalCNF addresses complete F vertices darts).«variables» + + (finalCNF addresses complete F vertices darts).clauses.length ≤ + 77824 * ((2 * (10 * F.clauses.length + 2)) ^ polynomialDegree * + (10 * F.clauses.length + 2)) := + (finalCNF_total_size addresses complete F vertices darts).trans + (Nat.mul_le_mul_left _ (output_size_clause_bound addresses complete F)) + +end FinalCNF + +end MinUncutGames.Foundations.PCP.PCPIteration + +end +end +section +namespace MinUncutGames.Foundations.PCP.FinalTableFormula + +open Target Complexity + +def output (table : GraphTables.Table) : Formula := + FinalBooleanVerifier.cnf (FinalCNFPattern.tableGraph table) (Equiv.refl _) (Equiv.refl _) + +theorem satisfiable_iff (table : GraphTables.Table) : + (output table).Satisfiable ↔ (GraphTables.semantics table).Satisfiable := + (FinalBooleanVerifier.cnf_satisfiable_iff (FinalCNFPattern.tableGraph table) + (Equiv.refl _) (Equiv.refl _)).trans + ((GraphTables.semantics table).satisfiable_reindex (Equiv.refl _) (Equiv.refl _) + FinalCNFPattern.labelEquiv.symm) + +@[simp] theorem variable_count (table : GraphTables.Table) : + (output table).«variables» = table.vertices * 6 + table.darts * 36864 := + FinalBooleanVerifier.cnf_variable_count _ (Equiv.refl _) (Equiv.refl _) + +@[simp] theorem clause_count (table : GraphTables.Table) : + (output table).clauses.length = table.darts * 40960 := + FinalBooleanVerifier.cnf_clause_count _ (Equiv.refl _) (Equiv.refl _) + +theorem nonempty (table : GraphTables.Table) (hd : 0 < table.darts) : + (output table).clauses ≠ [] := + FinalBooleanVerifier.cnf_nonempty _ (Equiv.refl _) (Equiv.refl _) hd + +theorem tableGraph_rejectionCount (table : GraphTables.Table) + (labeling : Fin table.vertices → FinalBooleanVerifier.Label) : + (FinalCNFPattern.tableGraph table).rejectionCount labeling = + (GraphTables.semantics table).rejectionCount + (fun v => FinalCNFPattern.labelEquiv (labeling v)) := by + have h := (GraphTables.semantics table).reindex_rejectionCount + (Equiv.refl _) (Equiv.refl _) FinalCNFPattern.labelEquiv.symm + (fun v => FinalCNFPattern.labelEquiv (labeling v)) + simpa [FinalCNFPattern.tableGraph, ConstraintGraph.labelingEquiv] using h + +theorem tableGraph_count_lower (table : GraphTables.Table) (walkLength : Nat) + (hgap : ∀ labeling : Fin table.vertices → GraphTables.Label, + table.darts ≤ walkLength * (GraphTables.semantics table).rejectionCount labeling) + (labeling : Fin table.vertices → FinalBooleanVerifier.Label) : + Fintype.card (Fin table.darts) ≤ + walkLength * (FinalCNFPattern.tableGraph table).rejectionCount labeling := by + rw [Fintype.card_fin, tableGraph_rejectionCount] + exact hgap _ + +theorem clauseGap (table : GraphTables.Table) (hd : 0 < table.darts) + (hgap : ∀ labeling : Fin table.vertices → GraphTables.Label, + table.darts ≤ FinalConstants.walkLength * + (GraphTables.semantics table).rejectionCount labeling) : + Hastad.SourceGap.ClauseGap (output table) PCPIteration.finalClauseGap := by + let : Nonempty (Fin table.darts) := ⟨⟨0, hd⟩⟩ + exact Hastad.SourceNonempty.cnf_clauseGap_unit (FinalCNFPattern.tableGraph table) + (Equiv.refl _) (Equiv.refl _) FinalConstants.walkLength + FinalConstants.walkLength_positive (tableGraph_count_lower table _ hgap) + +theorem total_size_le (table : GraphTables.Table) : + (output table).«variables» + (output table).clauses.length ≤ + 77824 * (table.vertices + table.darts) := by + have hv := variable_count table + have hc := clause_count table + omega + +noncomputable def sizePolynomial : Polynomial Nat := + Polynomial.C 77824 * Polynomial.X + Polynomial.C 2 + + (Polynomial.C 40960 * Polynomial.X) * + (Polynomial.C 3 * (Polynomial.C 36864 * Polynomial.X + Polynomial.C 2)) + +theorem sizePolynomial_eval (N : Nat) : + sizePolynomial.eval N = 77824 * N + 2 + (40960 * N) * (3 * (36864 * N + 2)) := by + simp [sizePolynomial] + +theorem formulaBits_length_le_polynomial (table : GraphTables.Table) : + (formulaBits (output table)).length ≤ + sizePolynomial.eval (GraphTables.tableBits table).length := by + have hinput := GraphTableComplexity.size_add_two_le_bits table + have hv : (output table).«variables» ≤ 36864 * (GraphTables.tableBits table).length := by + rw [variable_count] + omega + have hc : (output table).clauses.length ≤ 40960 * (GraphTables.tableBits table).length := by + rw [clause_count] + omega + have hsum : (output table).«variables» + (output table).clauses.length + 2 ≤ + 77824 * (GraphTables.tableBits table).length + 2 := by omega + have hproduct := Nat.mul_le_mul hc (Nat.mul_le_mul_left 3 (Nat.add_le_add_right hv 2)) + rw [sizePolynomial_eval] + exact (formulaBits_length_le (output table)).trans (Nat.add_le_add hsum hproduct) + +end MinUncutGames.Foundations.PCP.FinalTableFormula + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/PoweringOpinionTables.lean b/lean/OAI/Computability/MinUncut/PCP/PoweringOpinionTables.lean new file mode 100644 index 0000000000000000000000000000000000000000..af33452023da4021426aaa8220c14a6a9e73a71c --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/PoweringOpinionTables.lean @@ -0,0 +1,755 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.PoweringReturn + +namespace OAI + +section +namespace MinUncutGames.Foundations.PCP.PoweringOpinionTables + +open PoweringWalks PoweringLabels PoweringAddresses PoweringReach +open scoped BigOperators + +variable {X A : Type*} + +private theorem match_in_tail (p : X → Prop) {a : X} {xs : List X} + (h : ∃ b ∈ a :: xs, p b) (ha : ¬p a) : ∃ b ∈ xs, p b := by + obtain ⟨b, hb, hp⟩ := h + rcases List.mem_cons.mp hb with he | hm + · exact False.elim (ha (he ▸ hp)) + · exact ⟨b, hm, hp⟩ + +def firstIndex (p : X → Prop) [DecidablePred p] : + (xs : List X) → (∃ a ∈ xs, p a) → Fin xs.length + | [], h => False.elim (by simp at h) + | a :: xs, h => + if ha : p a then ⟨0, Nat.zero_lt_succ xs.length⟩ else + (firstIndex p xs (match_in_tail p h ha)).succ + +theorem get_firstIndex (p : X → Prop) [DecidablePred p] : + ∀ (xs : List X) (h : ∃ a ∈ xs, p a), + xs.get (firstIndex p xs h) = (scanWitness p xs h).val := by + intro xs + induction xs with + | nil => intro h; simp at h + | cons a xs ih => + intro h + by_cases ha : p a + · simp [firstIndex, scanWitness, ha] + · simpa only [firstIndex, scanWitness, ha, dite_false, List.get_cons_succ'] using + ih (match_in_tail p h ha) + +theorem firstIndex_matches (p : X → Prop) [DecidablePred p] + (xs : List X) (h : ∃ a ∈ xs, p a) : p (xs.get (firstIndex p xs h)) := by + rw [get_firstIndex] + exact (scanWitness p xs h).property + +theorem firstIndex_is_first (p : X → Prop) [DecidablePred p] : + ∀ (xs : List X) (h : ∃ a ∈ xs, p a) (j : Fin xs.length), + j.val < (firstIndex p xs h).val → ¬p (xs.get j) := by + intro xs + induction xs with + | nil => intro h; simp at h + | cons a xs ih => + intro h j + by_cases ha : p a + · simp [firstIndex, ha] + · refine Fin.cases (by intro _; exact ha) (fun i => ?_) j + intro hi + apply ih (match_in_tail p h ha) i + exact Nat.lt_of_succ_lt_succ (by + simpa only [firstIndex, ha, dite_false, Fin.val_succ] using hi) + +abbrev AddressIndex (d t : Nat) := Fin (allAddresses d t).length + +variable {vertices d : Nat} + +def addressIndex (G : PortGraph (Fin vertices) (Fin d)) (t : Nat) + (center : Fin vertices) (u : Ball G t center) : AddressIndex d t := + firstIndex (fun w => (wordToBall G t center w).val = u.val) + (allAddresses d t) (by + obtain ⟨w, hw⟩ := wordToBall_surjective G t center u + exact ⟨w, mem_allAddresses d t w, congrArg Subtype.val hw⟩) + +theorem addressIndex_get (G : PortGraph (Fin vertices) (Fin d)) (t : Nat) + (center : Fin vertices) (u : Ball G t center) : + (allAddresses d t).get (addressIndex G t center u) = + (finitePortSelector G t center).address u := by + change (allAddresses d t).get (firstIndex + (fun w => (wordToBall G t center w).val = u.val) (allAddresses d t) _) = + (scanWitness _ _ _).val + exact get_firstIndex _ _ _ + +theorem addressIndex_matches (G : PortGraph (Fin vertices) (Fin d)) (t : Nat) + (center : Fin vertices) (u : Ball G t center) : + wordToBall G t center ((allAddresses d t).get (addressIndex G t center u)) = u := by + rw [addressIndex_get] + exact (finitePortSelector G t center).correct u + +theorem addressIndex_is_first (G : PortGraph (Fin vertices) (Fin d)) (t : Nat) + (center : Fin vertices) (u : Ball G t center) (j : AddressIndex d t) + (hj : j.val < (addressIndex G t center u).val) : + (wordToBall G t center ((allAddresses d t).get j)).val ≠ u.val := by + exact firstIndex_is_first _ _ _ j hj + +theorem addressIndex_lt (G : PortGraph (Fin vertices) (Fin d)) (t : Nat) + (center : Fin vertices) (u : Ball G t center) : + (addressIndex G t center u).val < ∑ n : Fin (t + 1), d ^ n.val := by + rw [← length_allAddresses] + exact (addressIndex G t center u).isLt + +abbrev LabelTable (d t : Nat) (A : Type*) := Vector A (allAddresses d t).length + +def labelTable {t : Nat} (a : PaddedLabel (Fin d) t A) : LabelTable d t A := + Vector.ofFn fun i => a ((allAddresses d t).get i) + +@[simp] theorem labelTable_get {t : Nat} (a : PaddedLabel (Fin d) t A) + (i : AddressIndex d t) : + (labelTable a)[i] = a ((allAddresses d t).get i) := by + simp [labelTable] + +theorem labelTable_addressIndex (G : PortGraph (Fin vertices) (Fin d)) (t : Nat) + (center : Fin vertices) (u : Ball G t center) (a : PaddedLabel (Fin d) t A) : + (labelTable a)[addressIndex G t center u] = + decode (finitePortSelector G t center) a u := by + rw [labelTable_get, addressIndex_get] + rfl + +structure WalkOpinionRow (vertices d t : Nat) where + edge : Edge (Fin vertices) (Fin d) + tailIndex : AddressIndex d t + headIndex : AddressIndex d t + +abbrev WalkRows (vertices d n : Nat) := Vector (WalkOpinionRow vertices d (n + 1)) (n + 1) + +def walkRows (G : PortGraph (Fin vertices) (Fin d)) (n : Nat) + (w : Walk (Fin vertices) (Fin d) (n + 1)) : WalkRows vertices d n := + Vector.ofFn fun k => + { edge := edgeAt G n w k + tailIndex := addressIndex G (n + 1) w.1 (tailFromStart G n w k) + headIndex := addressIndex G (n + 1) (endpoint G w) (headFromEnd G n w k) } + +@[simp] theorem walkRows_edge (G : PortGraph (Fin vertices) (Fin d)) (n : Nat) + (w : Walk (Fin vertices) (Fin d) (n + 1)) (k : Fin (n + 1)) : + (walkRows G n w)[k].edge = edgeAt G n w k := by + simp [walkRows] + +@[simp] theorem walkRows_tail_value (G : PortGraph (Fin vertices) (Fin d)) (n : Nat) + (w : Walk (Fin vertices) (Fin d) (n + 1)) (k : Fin (n + 1)) + (a : PaddedLabel (Fin d) (n + 1) A) : + (labelTable a)[(walkRows G n w)[k].tailIndex] = + decode (finitePortSelector G (n + 1) w.1) a (tailFromStart G n w k) := by + simpa only [walkRows, Fin.getElem_fin, Vector.getElem_ofFn] using + labelTable_addressIndex G (n + 1) w.1 (tailFromStart G n w k) a + +@[simp] theorem walkRows_head_value (G : PortGraph (Fin vertices) (Fin d)) (n : Nat) + (w : Walk (Fin vertices) (Fin d) (n + 1)) (k : Fin (n + 1)) + (b : PaddedLabel (Fin d) (n + 1) A) : + (labelTable b)[(walkRows G n w)[k].headIndex] = + decode (finitePortSelector G (n + 1) (endpoint G w)) b (headFromEnd G n w k) := by + simpa only [walkRows, Fin.getElem_fin, Vector.getElem_ofFn] using + labelTable_addressIndex G (n + 1) (endpoint G w) (headFromEnd G n w k) b + +theorem walkRows_length (G : PortGraph (Fin vertices) (Fin d)) (n : Nat) + (w : Walk (Fin vertices) (Fin d) (n + 1)) : + (walkRows G n w).toList.length = n + 1 := by + simp + +def rowsAccepts {n : Nat} (accepts : Edge (Fin vertices) (Fin d) → A → A → Bool) + (rows : WalkRows vertices d n) (a b : LabelTable d (n + 1) A) : Bool := + decide (∀ k : Fin (n + 1), accepts rows[k].edge a[rows[k].tailIndex] + b[rows[k].headIndex] = true) + +theorem rowsAccepts_walkRows (G : PortGraph (Fin vertices) (Fin d)) + (accepts : Edge (Fin vertices) (Fin d) → A → A → Bool) (n : Nat) + (w : Walk (Fin vertices) (Fin d) (n + 1)) + (a b : PaddedLabel (Fin d) (n + 1) A) : + rowsAccepts accepts (walkRows G n w) (labelTable a) (labelTable b) = + PoweringTest.pathAccepts G accepts n (finitePortSelector G (n + 1)) w a b := by + apply Bool.eq_iff_iff.mpr + simp only [rowsAccepts, decide_eq_true_iff, PoweringTest.pathAccepts_eq_true_iff, + walkRows_edge, walkRows_tail_value, walkRows_head_value] + +end MinUncutGames.Foundations.PCP.PoweringOpinionTables + +end +section +namespace MinUncutGames.Foundations.PCP.GenericGraphTables + +open MinUncutGames.Foundations.Complexity + +abbrev Label (q : Nat) := Fin q +abbrev RelationTable (q : Nat) := Vector Bool (q * q) + +variable {q : Nat} + +def relationIndex (q : Nat) : (Label q) × (Label q) ≃ Fin (q * q) := finProdFinEquiv + +theorem relationIndex_val (a b : (Label q)) : + ((relationIndex q) (a, b)).val = b.val + q * a.val := rfl + +def relationAt (table : (RelationTable q)) (a b : (Label q)) : Bool := + table[(relationIndex q) (a, b)] + +def relationOf (predicate : (Label q) → (Label q) → Bool) : (RelationTable q) := + Vector.ofFn (fun i => predicate ((relationIndex q).symm i).1 ((relationIndex q).symm i).2) + +@[simp] theorem relationAt_relationOf (predicate : (Label q) → (Label q) → Bool) (a b : (Label q)) : + relationAt (relationOf predicate) a b = predicate a b := by + simp [relationAt, relationOf] + +structure DartRow (q vertices darts : Nat) where + tail : Fin vertices + reverseIndex : Fin darts + relation : (RelationTable q) + +abbrev Rows (q vertices darts : Nat) := Vector (DartRow q vertices darts) darts + +def reverseAt {n m : Nat} (rows : Rows q n m) (e : Fin m) : Fin m := + rows[e].reverseIndex + +def acceptsAt {n m : Nat} (rows : Rows q n m) (e : Fin m) (a b : (Label q)) : Bool := + relationAt rows[e].relation a b + +def Valid {n m : Nat} (rows : Rows q n m) : Prop := + (∀ e, reverseAt rows (reverseAt rows e) = e) ∧ + (∀ e a b, acceptsAt rows (reverseAt rows e) b a = acceptsAt rows e a b) + +instance {n m : Nat} (rows : Rows q n m) : Decidable (Valid rows) := by + unfold Valid + infer_instance + +structure Table (q : Nat) where + vertices : Nat + darts : Nat + rows : Rows q vertices darts + valid : Valid rows + +def rowList (table : (Table q)) : List (DartRow q table.vertices table.darts) := table.rows.toList + +@[simp] theorem rowList_length (table : (Table q)) : (rowList table).length = table.darts := by + simp [rowList] + +def semantics (table : (Table q)) : ConstraintGraph (Fin table.vertices) (Fin table.darts) (Label q) where + reverse := + { toFun := reverseAt table.rows + invFun := reverseAt table.rows + left_inv := table.valid.1 + right_inv := table.valid.1 } + reverse_involutive := table.valid.1 + tail e := table.rows[e].tail + accepts := acceptsAt table.rows + reverse_accepts := table.valid.2 + +@[simp] theorem semantics_reverse (table : (Table q)) (e : Fin table.darts) : + (semantics table).reverse e = table.rows[e].reverseIndex := rfl + +@[simp] theorem semantics_tail (table : (Table q)) (e : Fin table.darts) : + (semantics table).tail e = table.rows[e].tail := rfl + +@[simp] theorem semantics_accepts (table : (Table q)) (e : Fin table.darts) (a b : (Label q)) : + (semantics table).accepts e a b = relationAt table.rows[e].relation a b := rfl + +def graphRows {n m : Nat} (G : ConstraintGraph (Fin n) (Fin m) (Label q)) : Rows q n m := + Vector.ofFn (fun e => ⟨G.tail e, G.reverse e, relationOf (G.accepts e)⟩) + +@[simp] theorem reverseAt_graphRows {n m : Nat} + (G : ConstraintGraph (Fin n) (Fin m) (Label q)) (e : Fin m) : + reverseAt (graphRows G) e = G.reverse e := by + simp [reverseAt, graphRows] + +@[simp] theorem acceptsAt_graphRows {n m : Nat} + (G : ConstraintGraph (Fin n) (Fin m) (Label q)) (e : Fin m) (a b : (Label q)) : + acceptsAt (graphRows G) e a b = G.accepts e a b := by + simp [acceptsAt, graphRows] + +theorem graphRows_valid {n m : Nat} (G : ConstraintGraph (Fin n) (Fin m) (Label q)) : + Valid (graphRows G) := by + constructor + · intro e + simpa using G.reverse_involutive e + · intro e a b + simpa using G.reverse_accepts e a b + +def ofGraph {n m : Nat} (G : ConstraintGraph (Fin n) (Fin m) (Label q)) : (Table q) := + ⟨n, m, graphRows G, graphRows_valid G⟩ + +@[simp] theorem semantics_ofGraph_reverse {n m : Nat} + (G : ConstraintGraph (Fin n) (Fin m) (Label q)) (e : Fin m) : + (semantics (ofGraph G)).reverse e = G.reverse e := by + exact reverseAt_graphRows G e + +@[simp] theorem semantics_ofGraph_tail {n m : Nat} + (G : ConstraintGraph (Fin n) (Fin m) (Label q)) (e : Fin m) : + (semantics (ofGraph G)).tail e = G.tail e := by + change (graphRows G)[e.val].tail = G.tail e + simp only [graphRows, Vector.getElem_ofFn] + +@[simp] theorem semantics_ofGraph_accepts {n m : Nat} + (G : ConstraintGraph (Fin n) (Fin m) (Label q)) (e : Fin m) (a b : (Label q)) : + (semantics (ofGraph G)).accepts e a b = G.accepts e a b := by + exact acceptsAt_graphRows G e a b + +@[simp] theorem semantics_ofGraph_edgeSatisfied {n m : Nat} + (G : ConstraintGraph (Fin n) (Fin m) (Label q)) (labeling : Fin n → (Label q)) (e : Fin m) : + (semantics (ofGraph G)).edgeSatisfied labeling e = G.edgeSatisfied labeling e := by + simp [ConstraintGraph.edgeSatisfied, ConstraintGraph.head] + +private theorem constraintGraph_ext {V E A : Type*} {G H : ConstraintGraph V E A} + (hr : ∀ e, G.reverse e = H.reverse e) (ht : G.tail = H.tail) + (hp : G.accepts = H.accepts) : G = H := by + cases G with + | mk reverse hinv tail accepts htranspose => + cases H with + | mk reverse' hinv' tail' accepts' htranspose' => + dsimp only at hr ht hp + have he : reverse = reverse' := Equiv.ext hr + cases he + cases ht + cases hp + rfl + +@[simp] theorem semantics_ofGraph {n m : Nat} + (G : ConstraintGraph (Fin n) (Fin m) (Label q)) : semantics (ofGraph G) = G := by + apply constraintGraph_ext + · exact semantics_ofGraph_reverse G + · funext e + exact semantics_ofGraph_tail G e + · funext e a b + exact semantics_ofGraph_accepts G e a b + +@[simp] theorem semantics_ofGraph_rejectionCount {n m : Nat} + (G : ConstraintGraph (Fin n) (Fin m) (Label q)) (labeling : Fin n → (Label q)) : + (semantics (ofGraph G)).rejectionCount labeling = G.rejectionCount labeling := by + rw [semantics_ofGraph] + rfl + +def enumeratedGraph {V E A : Type*} {n m : Nat} (G : ConstraintGraph V E A) + (vertexOrder : V ≃ Fin n) (dartOrder : E ≃ Fin m) (labelOrder : A ≃ (Label q)) : + ConstraintGraph (Fin n) (Fin m) (Label q) where + reverse := (dartOrder.symm.trans G.reverse).trans dartOrder + reverse_involutive e := by + change dartOrder (G.reverse (dartOrder.symm + (dartOrder (G.reverse (dartOrder.symm e))))) = e + rw [dartOrder.symm_apply_apply, G.reverse_involutive, dartOrder.apply_symm_apply] + tail e := vertexOrder (G.tail (dartOrder.symm e)) + accepts e a b := G.accepts (dartOrder.symm e) (labelOrder.symm a) (labelOrder.symm b) + reverse_accepts e a b := by + change G.accepts (dartOrder.symm (dartOrder (G.reverse (dartOrder.symm e)))) + (labelOrder.symm b) (labelOrder.symm a) = _ + rw [dartOrder.symm_apply_apply] + exact G.reverse_accepts _ _ _ + +theorem enumeratedGraph_edgeSatisfied {V E A : Type*} {n m : Nat} + (G : ConstraintGraph V E A) (vertexOrder : V ≃ Fin n) (dartOrder : E ≃ Fin m) + (labelOrder : A ≃ (Label q)) (labeling : V → A) (e : E) : + (enumeratedGraph G vertexOrder dartOrder labelOrder).edgeSatisfied + (fun v => labelOrder (labeling (vertexOrder.symm v))) (dartOrder e) = + G.edgeSatisfied labeling e := by + simp [ConstraintGraph.edgeSatisfied, ConstraintGraph.head, enumeratedGraph] + +theorem enumeratedGraph_rejectionCount {V E A : Type*} [Fintype E] {n m : Nat} + (G : ConstraintGraph V E A) (vertexOrder : V ≃ Fin n) (dartOrder : E ≃ Fin m) + (labelOrder : A ≃ (Label q)) (labeling : V → A) : + (enumeratedGraph G vertexOrder dartOrder labelOrder).rejectionCount + (fun v => labelOrder (labeling (vertexOrder.symm v))) = G.rejectionCount labeling := by + classical + unfold ConstraintGraph.rejectionCount + symm + apply Finset.card_equiv dartOrder + intro e + simp only [ConstraintGraph.mem_rejectedDarts, enumeratedGraph_edgeSatisfied] + +def ofEnumeratedGraph {V E A : Type*} {n m : Nat} (G : ConstraintGraph V E A) + (vertexOrder : V ≃ Fin n) (dartOrder : E ≃ Fin m) (labelOrder : A ≃ (Label q)) : (Table q) := + ofGraph (enumeratedGraph G vertexOrder dartOrder labelOrder) + +def bitWord (b : Bool) : Nat := if b then 1 else 0 + +def parseBit : Nat → Option Bool + | 0 => some false + | 1 => some true + | _ => none + +@[simp] theorem parseBit_bitWord (b : Bool) : parseBit (bitWord b) = some b := by + cases b <;> rfl + +@[simp] theorem parseBits_bitWords (bits : List Bool) : + (bits.map bitWord).mapM parseBit = some bits := by + induction bits with + | nil => rfl + | cons bit bits ih => simp [ih] + +def relationWords (relation : (RelationTable q)) : List Nat := relation.toList.map bitWord + +@[simp] theorem relationWords_length (relation : (RelationTable q)) : + (relationWords relation).length = (q * q) := by simp [relationWords] + +def parseRelation (q : Nat) (words : List Nat) : Option (RelationTable q) := do + let bits ← words.mapM parseBit + if length_ok : bits.length = (q * q) then + some ⟨bits.toArray, by simpa using length_ok⟩ + else none + +@[simp] theorem parseRelation_encoded (relation : (RelationTable q)) : + (parseRelation q) (relationWords relation) = some relation := by + unfold parseRelation relationWords + rw [parseBits_bitWords] + simp + exact Vector.toArray_toList + +def rowWords {n m : Nat} (row : DartRow q n m) : List Nat := + [row.tail.val, row.reverseIndex.val] ++ relationWords row.relation + +def parseRow (q : Nat) (vertices darts : Nat) : List Nat → Option (DartRow q vertices darts × List Nat) + | tail :: reverseIndex :: words => do + let tail ← parseLabel vertices tail + let reverseIndex ← parseLabel darts reverseIndex + let relation ← (parseRelation q) (words.take (q * q)) + return (⟨tail, reverseIndex, relation⟩, words.drop (q * q)) + | _ => none + +@[simp] theorem parseRow_encoded {n m : Nat} (row : DartRow q n m) (rest : List Nat) : + (parseRow q) n m (rowWords row ++ rest) = some (row, rest) := by + cases row with + | mk tail reverseIndex relation => + have taken := List.take_left' (l₂ := rest) (relationWords_length relation) + have dropped := List.drop_left' (l₂ := rest) (relationWords_length relation) + simp [rowWords, parseRow, taken, dropped] + +def parseRows (q : Nat) (vertices darts : Nat) : + Nat → List Nat → Option (List (DartRow q vertices darts) × List Nat) + | 0, words => some ([], words) + | count + 1, words => do + let (row, words) ← (parseRow q) vertices darts words + let (rows, words) ← (parseRows q) vertices darts count words + return (row :: rows, words) + +@[simp] theorem parseRows_encoded {n m : Nat} (rows : List (DartRow q n m)) (rest : List Nat) : + (parseRows q) n m rows.length (rows.flatMap rowWords ++ rest) = some (rows, rest) := by + induction rows with + | nil => rfl + | cons row rows ih => simp [parseRows, List.append_assoc, ih] + +def tableWords (table : (Table q)) : List Nat := + [table.vertices, table.darts] ++ (rowList table).flatMap rowWords + +def tableBits (table : (Table q)) : List Bool := encodeWords (tableWords table) + +def decodeTableWords (q : Nat) : List Nat → Option (Table q) + | vertices :: darts :: words => do + let (parsed, trailing) ← (parseRows q) vertices darts darts words + if trailing = [] then + if length_ok : parsed.length = darts then + let rows : Rows q vertices darts := ⟨parsed.toArray, by simpa using length_ok⟩ + if valid : Valid rows then some ⟨vertices, darts, rows, valid⟩ else none + else none + else none + | _ => none + +@[simp] theorem decodeTableWords_encoded (table : (Table q)) : + (decodeTableWords q) (tableWords table) = some table := by + cases table with + | mk vertices darts rows valid => + have parsed := parseRows_encoded rows.toList [] + simp only [Vector.length_toList, List.append_nil] at parsed + simp [tableWords, rowList, decodeTableWords, parsed, valid, Vector.toArray_toList] + +def decodeTableBits (q : Nat) (bits : List Bool) : Option (Table q) := + decodeWords bits >>= (decodeTableWords q) + +@[simp] theorem decodeTableBits_encoded (table : (Table q)) : + (decodeTableBits q) (tableBits table) = some table := by + simp [decodeTableBits, tableBits] + +def encoding (q : Nat) : Computability.Encoding (Table q) Bool where + encode := tableBits + decode := (decodeTableBits q) + decode_encode := decodeTableBits_encoded + +theorem tableBits_injective : Function.Injective (tableBits (q := q)) := (encoding q).encode_injective + +@[simp] theorem rowWords_length {n m : Nat} (row : DartRow q n m) : + (rowWords row).length = (q * q + 2) := by + simp only [rowWords, List.length_append, List.length_cons, List.length_nil, + relationWords_length] + omega + +theorem rowsWords_length {n m : Nat} (rows : List (DartRow q n m)) : + (rows.flatMap rowWords).length = (q * q + 2) * rows.length := by + induction rows with + | nil => rfl + | cons row rows ih => simp [ih, Nat.mul_add, Nat.add_comm] + +@[simp] theorem tableWords_length (table : (Table q)) : + (tableWords table).length = 2 + (q * q + 2) * table.darts := by + simp only [tableWords, List.length_append, List.length_cons, List.length_nil, + rowsWords_length, rowList_length] + +theorem tableWords_length_le_bits (table : (Table q)) : + 2 + (q * q + 2) * table.darts ≤ (tableBits table).length := by + rw [tableBits, encodeWords_length, ← tableWords_length] + omega + +theorem relationBits_length_le (relation : (RelationTable q)) : + (encodeWords (relationWords relation)).length ≤ (2 * (q * q)) := by + have h := encodeWords_length_le (relationWords relation) 1 (by + intro word hword + obtain ⟨bit, _, rfl⟩ := List.mem_map.mp hword + cases bit <;> decide) + simpa only [relationWords_length, Nat.mul_comm] using h + +theorem rowBits_length_le {n m : Nat} (row : DartRow q n m) : + (encodeWords (rowWords row)).length ≤ n + m + (2 * (q * q)) := by + have ht := row.tail.isLt + have hr := row.reverseIndex.isLt + have hp := relationBits_length_le row.relation + simp only [rowWords, encodeWords_append, List.length_append, encodeWords, + encodeWord_length, List.length_nil] at ⊢ + omega + +theorem rowsBits_length_le {n m : Nat} (rows : List (DartRow q n m)) : + (encodeWords (rows.flatMap rowWords)).length ≤ rows.length * (n + m + (2 * (q * q))) := by + induction rows with + | nil => simp [encodeWords] + | cons row rows ih => + have hrow := rowBits_length_le row + simp only [List.flatMap_cons, encodeWords_append, List.length_append, + List.length_cons, Nat.add_mul, Nat.one_mul] + omega + +theorem tableBits_length_le (table : (Table q)) : + (tableBits table).length ≤ table.vertices + table.darts + 2 + + table.darts * (table.vertices + table.darts + (2 * (q * q))) := by + have hrows := rowsBits_length_le (rowList table) + rw [rowList_length] at hrows + simp only [tableBits, tableWords, encodeWords_append, List.length_append, + encodeWords, encodeWord_length, List.length_nil] + omega + +theorem vertices_le_tableBits_length (table : (Table q)) : + table.vertices ≤ (tableBits table).length := by + simp only [tableBits, tableWords, encodeWords_append, List.length_append, + encodeWords, encodeWord_length, List.length_nil] + omega + +theorem darts_le_tableBits_length (table : (Table q)) : + table.darts ≤ (tableBits table).length := by + simp only [tableBits, tableWords, encodeWords_append, List.length_append, + encodeWords, encodeWord_length, List.length_nil] + omega + +end MinUncutGames.Foundations.PCP.GenericGraphTables + +end +section +namespace MinUncutGames.Foundations.PCP.PoweringTables + +open PoweringWalks PoweringLabels PoweringAddresses PoweringEnumeration + +def labelCount (d n : Nat) : Nat := 64 ^ addressCount d (n + 1) + +def dartCount (vertices d n : Nat) : Nat := 2 * vertices * d ^ (n + 1) + +def mathematicalGraph {vertices d : Nat} (input : PortTables.Table vertices d) (n : Nat) : + ConstraintGraph (Fin vertices) (PoweringTest.Dart (Fin vertices) (Fin d) n) + (PaddedLabel (Fin d) (n + 1) (Fin 64)) := + PoweringTest.poweredGraph (PortTables.portGraph input) (PortTables.accepts input) n + (finitePortSelector (PortTables.portGraph input) (n + 1)) + +def rowAccepts {vertices d : Nat} (input : PortTables.Table vertices d) (n : Nat) + (e : PoweringTest.Dart (Fin vertices) (Fin d) n) + (a b : Fin (labelCount d n)) : Bool := + let rows := PoweringOpinionTables.walkRows (PortTables.portGraph input) n e.2 + let left := PoweringOpinionTables.labelTable (decodeLabel d (n + 1) 64 a) + let right := PoweringOpinionTables.labelTable (decodeLabel d (n + 1) 64 b) + if e.1 then PoweringOpinionTables.rowsAccepts (PortTables.accepts input) rows right left + else PoweringOpinionTables.rowsAccepts (PortTables.accepts input) rows left right + +theorem rowAccepts_eq {vertices d : Nat} (input : PortTables.Table vertices d) (n : Nat) + (e : PoweringTest.Dart (Fin vertices) (Fin d) n) + (a b : Fin (labelCount d n)) : + rowAccepts input n e a b = (mathematicalGraph input n).accepts e + (decodeLabel d (n + 1) 64 a) (decodeLabel d (n + 1) 64 b) := by + rcases e with ⟨direction, w⟩ + cases direction <;> + simp only [rowAccepts, mathematicalGraph, PoweringTest.poweredGraph, Bool.false_eq_true, + ite_false, ite_true, PoweringOpinionTables.rowsAccepts_walkRows] + +def table {vertices d : Nat} (input : PortTables.Table vertices d) (n : Nat) : + GenericGraphTables.Table (labelCount d n) := + GenericGraphTables.ofEnumeratedGraph (mathematicalGraph input n) (Equiv.refl _) + (dartEquiv vertices d n) (paddedLabelEquiv d (n + 1) 64) + +@[simp] theorem table_vertices {vertices d : Nat} (input : PortTables.Table vertices d) + (n : Nat) : (table input n).vertices = vertices := rfl + +@[simp] theorem table_darts {vertices d : Nat} (input : PortTables.Table vertices d) + (n : Nat) : (table input n).darts = dartCount vertices d n := rfl + +theorem semantics_table {vertices d : Nat} (input : PortTables.Table vertices d) (n : Nat) : + GenericGraphTables.semantics (table input n) = + GenericGraphTables.enumeratedGraph (mathematicalGraph input n) (Equiv.refl _) + (dartEquiv vertices d n) (paddedLabelEquiv d (n + 1) 64) := + GenericGraphTables.semantics_ofGraph _ + +theorem table_accepts {vertices d : Nat} (input : PortTables.Table vertices d) (n : Nat) + (i : Fin (dartCount vertices d n)) (a b : Fin (labelCount d n)) : + GenericGraphTables.acceptsAt (table input n).rows i a b = + rowAccepts input n (decodeDart vertices d n i) a b := by + change (GenericGraphTables.semantics (table input n)).accepts i a b = _ + rw [semantics_table] + exact (rowAccepts_eq input n (decodeDart vertices d n i) a b).symm + +theorem table_reverse {vertices d : Nat} (input : PortTables.Table vertices d) (n : Nat) + (direction : Bool) (w : Walk (Fin vertices) (Fin d) (n + 1)) : + GenericGraphTables.reverseAt (table input n).rows (encodeDart vertices d n (direction, w)) = + encodeDart vertices d n (!direction, w) := by + change (GenericGraphTables.semantics (table input n)).reverse _ = _ + rw [semantics_table] + change dartEquiv vertices d n ((mathematicalGraph input n).reverse + ((dartEquiv vertices d n).symm (dartEquiv vertices d n (direction, w)))) = + dartEquiv vertices d n (!direction, w) + rw [(dartEquiv vertices d n).symm_apply_apply] + rfl + +def outputBits {vertices d : Nat} (input : PortTables.Table vertices d) (n : Nat) : List Bool := + GenericGraphTables.tableBits (table input n) + +def transform (d n : Nat) (input : PortTables.Input d) : GenericGraphTables.Table (labelCount d n) := + table input.2 n + +end MinUncutGames.Foundations.PCP.PoweringTables + +end +section +namespace MinUncutGames.Foundations.PCP.PoweringCounting + +open PoweringWalks PoweringLabels PoweringTest +open scoped BigOperators + +variable {V D A E : Type*} + +theorem constraint_rejection_mean_eq_count [Fintype E] + (H : ConstraintGraph V E A) (labels : V → A) : + SpectralReturn.mean (fun e : E => PoweringMoment.bit + (H.edgeSatisfied labels e = false)) = + (H.rejectionCount labels : ℝ) / (Fintype.card E : ℝ) := by + classical + rw [SpectralReturn.mean_eq_sum_div_card] + simp only [PoweringMoment.bit, ConstraintGraph.rejectionCount, ConstraintGraph.rejectedDarts] + apply congrArg (fun x : ℝ => x / (Fintype.card E : ℝ)) + convert (Finset.sum_boole (R := ℝ) + (fun e => H.edgeSatisfied labels e = false) Finset.univ) using 1 + apply Finset.sum_congr rfl + intro e _ + by_cases h : H.edgeSatisfied labels e = false <;> simp [h] + +theorem constraint_rejection_lower_iff [Fintype E] + (H : ConstraintGraph V E A) (labels : V → A) + (hcard : 0 < Fintype.card E) (ε : ℝ) : + ε ≤ SpectralReturn.mean (fun e : E => PoweringMoment.bit + (H.edgeSatisfied labels e = false)) ↔ + ε * (Fintype.card E : ℝ) ≤ (H.rejectionCount labels : ℝ) := by + rw [constraint_rejection_mean_eq_count] + exact le_div_iff₀ (Nat.cast_pos.mpr hcard) + +theorem edgeDensity_eq_bit_mean [Fintype V] [Fintype D] + (bad : Edge V D → Bool) : + SpectralReturn.edgeDensity bad = + SpectralReturn.mean (fun e : Edge V D => PoweringMoment.bit (bad e = true)) := by + convert (SpectralReturn.mean_prod + (fun e : Edge V D => PoweringMoment.bit (bad e = true))).symm using 1 + change SpectralReturn.mean (fun v => SpectralReturn.mean + (fun d => if bad (v, d) then (1 : ℝ) else 0)) = _ + apply congrArg SpectralReturn.mean + funext v + apply congrArg SpectralReturn.mean + funext d + cases bad (v, d) <;> simp [PoweringMoment.bit] + +theorem base_edgeDensity_eq_rejection_count [Fintype V] [Fintype D] + (G : PortGraph V D) (accepts : Edge V D → A → A → Bool) + (reverse_accepts : ∀ e a b, accepts (G.rot e) b a = accepts e a b) + (assignment : V → A) : + SpectralReturn.edgeDensity (decodedBad G accepts assignment) = + ((baseGraph G accepts reverse_accepts).rejectionCount assignment : ℝ) / + (Fintype.card (Edge V D) : ℝ) := by + calc + _ = SpectralReturn.mean (fun e : Edge V D => PoweringMoment.bit + (decodedBad G accepts assignment e = true)) := edgeDensity_eq_bit_mean _ + _ = SpectralReturn.mean (fun e : Edge V D => PoweringMoment.bit + ((baseGraph G accepts reverse_accepts).edgeSatisfied assignment e = false)) := by + apply congrArg SpectralReturn.mean + funext e + exact congrArg PoweringMoment.bit + (propext (decodedBad_eq_true_iff G accepts assignment e)) + _ = _ := constraint_rejection_mean_eq_count _ _ + +theorem base_count_lower_to_density [Fintype V] [Fintype D] + (G : PortGraph V D) (accepts : Edge V D → A → A → Bool) + (reverse_accepts : ∀ e a b, accepts (G.rot e) b a = accepts e a b) + (assignment : V → A) (hcard : 0 < Fintype.card (Edge V D)) (ε : ℝ) + (hcount : ε * (Fintype.card (Edge V D) : ℝ) ≤ + ((baseGraph G accepts reverse_accepts).rejectionCount assignment : ℝ)) : + ε ≤ SpectralReturn.edgeDensity (decodedBad G accepts assignment) := by + rw [base_edgeDensity_eq_rejection_count G accepts reverse_accepts assignment] + exact (le_div_iff₀ (Nat.cast_pos.mpr hcard)).2 hcount + +theorem powered_rejection_mean_eq_count [Fintype V] [Fintype D] + (G : PortGraph V D) (accepts : Edge V D → A → A → Bool) (n : Nat) + (selectors : ∀ v, AddressSelector G (n + 1) v) + (labels : V → PaddedLabel D (n + 1) A) : + SpectralReturn.mean (fun d : Dart V D n => PoweringMoment.bit + ((poweredGraph G accepts n selectors).edgeSatisfied labels d = false)) = + ((poweredGraph G accepts n selectors).rejectionCount labels : ℝ) / + (Fintype.card (Dart V D n) : ℝ) := + constraint_rejection_mean_eq_count _ _ + +theorem path_rejection_mean_eq_count [Fintype V] [Fintype D] + (G : PortGraph V D) (accepts : Edge V D → A → A → Bool) (n : Nat) + (selectors : ∀ v, AddressSelector G (n + 1) v) + (labels : V → PaddedLabel D (n + 1) A) : + SpectralReturn.mean (fun w : Walk V D (n + 1) => PoweringMoment.bit + (pathAccepts G accepts n selectors w (labels w.1) (labels (endpoint G w)) = false)) = + ((poweredGraph G accepts n selectors).rejectionCount labels : ℝ) / + (Fintype.card (Dart V D n) : ℝ) := by + rw [← rejection_mean_eq_path_mean G accepts n selectors labels] + exact powered_rejection_mean_eq_count G accepts n selectors labels + +theorem powered_density_lower_to_count [Fintype V] [Fintype D] + (G : PortGraph V D) (accepts : Edge V D → A → A → Bool) (n : Nat) + (selectors : ∀ v, AddressSelector G (n + 1) v) + (labels : V → PaddedLabel D (n + 1) A) + (hcard : 0 < Fintype.card (Dart V D n)) (ε : ℝ) + (hlower : ε ≤ SpectralReturn.mean (fun w : Walk V D (n + 1) => PoweringMoment.bit + (pathAccepts G accepts n selectors w (labels w.1) (labels (endpoint G w)) = false))) : + ε * (Fintype.card (Dart V D n) : ℝ) ≤ + ((poweredGraph G accepts n selectors).rejectionCount labels : ℝ) := by + rw [path_rejection_mean_eq_count G accepts n selectors labels] at hlower + exact (le_div_iff₀ (Nat.cast_pos.mpr hcard)).1 hlower + +theorem natCard_dart [Finite V] [Finite D] (n : Nat) : + Nat.card (Dart V D n) = 2 * Nat.card V * Nat.card D ^ (n + 1) := by + simp [Dart, Walk, Nat.card_prod, Nat.card_fun, Nat.mul_assoc] + +theorem fintypeCard_dart [Fintype V] [Fintype D] (n : Nat) : + Fintype.card (Dart V D n) = + 2 * Fintype.card V * Fintype.card D ^ (n + 1) := by + simpa only [Nat.card_eq_fintype_card] using (natCard_dart (V := V) (D := D) n) + +theorem natCard_poweredAlphabet [Finite D] [Finite A] (n : Nat) : + Nat.card (PaddedLabel D (n + 1) A) = + Nat.card A ^ (∑ j : Fin (n + 2), Nat.card D ^ j.val) := + PoweringLabels.card_paddedLabel (n + 1) + +theorem natCard_finitePortAlphabet [Finite A] (d n : Nat) : + Nat.card (PaddedLabel (Fin d) (n + 1) A) = + Nat.card A ^ (PoweringAddresses.allAddresses d (n + 1)).length := by + rw [PoweringLabels.card_paddedLabel, PoweringAddresses.length_allAddresses] + simp only [Nat.card_fin] + +end MinUncutGames.Foundations.PCP.PoweringCounting + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/PoweringReturn.lean b/lean/OAI/Computability/MinUncut/PCP/PoweringReturn.lean new file mode 100644 index 0000000000000000000000000000000000000000..a9249c8f443651a2163e55277a7ca33147f0164a --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/PoweringReturn.lean @@ -0,0 +1,724 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.PreprocessingTableSpectral + +namespace OAI + +section +namespace MinUncutGames.Foundations.PCP.PoweringReturn + +open PoweringWalks SpectralReturn +open PoweringMoment (bit) + +variable {V D : Type*} + +def portConsEquiv (D : Type*) (n : Nat) : + (D × (Fin n → D)) ≃ (Fin (n + 1) → D) where + toFun z := Fin.cases z.1 z.2 + invFun r := (r 0, fun j => r j.succ) + left_inv z := by + apply Prod.ext + · rfl + · funext j + rfl + right_inv r := by + funext j + exact Fin.cases rfl (fun _ => rfl) j + +theorem mean_word_cons_head [Fintype D] (n : Nat) + (F : (Fin (n + 1) → D) → ℝ) : + mean F = mean (fun d : D => mean (fun r : Fin n → D => F (Fin.cases d r))) := by + calc + mean F = mean (fun z : D × (Fin n → D) => F (Fin.cases z.1 z.2)) := + (mean_equiv (portConsEquiv D n) F).symm + _ = _ := mean_prod _ + +theorem mean_word_cons_tail [Fintype D] (n : Nat) + (F : (Fin (n + 1) → D) → ℝ) : + mean F = mean (fun r : Fin n → D => mean (fun d : D => F (Fin.cases d r))) := by + calc + mean F = mean (fun z : (Fin n → D) × D => F (Fin.cases z.2 z.1)) := + (mean_equiv ((Equiv.prodComm (Fin n → D) D).trans (portConsEquiv D n)) F).symm + _ = _ := mean_prod _ + +theorem iterateOperator_succ_right [Fintype D] (G : PortGraph V D) + (n : Nat) (f : V → ℝ) : + iterateOperator G n (averagingOperator G f) = iterateOperator G (n + 1) f := by + induction n with + | zero => rfl + | succ n ih => exact congrArg (averagingOperator G) ih + +theorem mean_wordEnd [Fintype D] [Nonempty D] (G : PortGraph V D) : + ∀ (n : Nat) (v : V) (f : V → ℝ), + mean (fun r : Fin n → D => f (wordEnd G n v r)) = iterateOperator G n f v := by + intro n + induction n with + | zero => + intro v f + change mean (fun _ : Fin 0 → D => f v) = f v + exact mean_const _ + | succ n ih => + intro v f + rw [mean_word_cons_head] + change mean (fun d : D => mean (fun r : Fin n → D => + f (wordEnd G n (next G v d) r))) = _ + calc + _ = mean (fun d : D => iterateOperator G n f (next G v d)) := by + congr 1 + funext d + exact ih (next G v d) f + _ = iterateOperator G (n + 1) f v := rfl + +theorem mean_pivot_endpoints [Fintype D] [Nonempty D] (G : PortGraph V D) : + ∀ (n : Nat) (k : Fin (n + 1)) (e : Edge V D) (φ ψ : V → ℝ), + mean (fun r : Fin n → D => + φ (leftFromPivot G n k e.1 r) * ψ (rightFromPivot G n k e r)) = + iterateOperator G k.val φ e.1 * + iterateOperator G (n - k.val) ψ (next G e.1 e.2) := by + intro n + induction n with + | zero => + intro k e φ ψ + have hk : k = 0 := Fin.eq_zero k + subst k + change mean (fun _ : Fin 0 → D => φ e.1 * ψ (next G e.1 e.2)) = + φ e.1 * ψ (next G e.1 e.2) + exact mean_const _ + | succ n ih => + intro k e φ ψ + refine Fin.cases ?_ (fun j => ?_) k + · change mean (fun r : Fin (n + 1) → D => + φ e.1 * ψ (wordEnd G (n + 1) (next G e.1 e.2) r)) = + φ e.1 * iterateOperator G (n + 1) ψ (next G e.1 e.2) + rw [mean_mul_left, mean_wordEnd] + · simp only [Fin.val_succ, Nat.add_sub_add_right] + rw [mean_word_cons_tail] + change mean (fun r : Fin n → D => mean (fun d : D => + φ (next G (leftFromPivot G n j e.1 r) d) * + ψ (rightFromPivot G n j e r))) = + iterateOperator G (j.val + 1) φ e.1 * + iterateOperator G (n - j.val) ψ (next G e.1 e.2) + calc + _ = mean (fun r : Fin n → D => + averagingOperator G φ (leftFromPivot G n j e.1 r) * + ψ (rightFromPivot G n j e r)) := by + congr 1 + funext r + rw [mean_mul_right] + rfl + _ = iterateOperator G j.val (averagingOperator G φ) e.1 * + iterateOperator G (n - j.val) ψ (next G e.1 e.2) := + ih j e (averagingOperator G φ) ψ + _ = _ := by rw [iterateOperator_succ_right] + +theorem mean_edge_endpoints [Fintype V] [Fintype D] [Nonempty D] + (G : PortGraph V D) (n : Nat) (k : Fin (n + 1)) (φ ψ : Edge V D → V → ℝ) : + mean (fun w : Walk V D (n + 1) => + φ (edgeAt G n w k) w.1 * ψ (edgeAt G n w k) (endpoint G w)) = + mean (fun e : Edge V D => + iterateOperator G k.val (φ e) e.1 * + iterateOperator G (n - k.val) (ψ e) (next G e.1 e.2)) := by + let F : Edge V D × (Fin n → D) → ℝ := fun z => + φ z.1 (leftFromPivot G n k z.1.1 z.2) * + ψ z.1 (rightFromPivot G n k z.1 z.2) + calc + _ = mean (fun w => F (pivotEquiv G n k w)) := by + congr 1 + funext w + dsimp [F] + rw [leftFromPivot_actual, rightFromPivot_actual, pivotEquiv_fst] + _ = mean F := mean_equiv (pivotEquiv G n k) F + _ = mean (fun e : Edge V D => mean (fun r : Fin n → D => + φ e (leftFromPivot G n k e.1 r) * ψ e (rightFromPivot G n k e r))) := mean_prod F + _ = _ := by + congr 1 + funext e + exact mean_pivot_endpoints G n k e (φ e) (ψ e) + +theorem bit_bool (b : Bool) : bit (b = true) = (if b then 1 else 0 : ℝ) := by + cases b <;> simp [bit] + +theorem mean_edge_bit [Fintype D] (bad : V × D → Bool) (v : V) : + mean (fun d : D => bit (bad (v, d) = true)) = edgeProfile bad v := by + simp only [bit_bool, mean, edgeProfile] + +theorem mean_marked_bit [Fintype D] (G : PortGraph V D) + (bad : V × D → Bool) (f : V → ℝ) (v : V) : + mean (fun d : D => bit (bad (v, d) = true) * f (next G v d)) = + markedStep G bad f v := by + change mean (fun d : D => bit (bad (v, d) = true) * f (next G v d)) = + mean (fun d : D => if bad (v, d) then f (next G v d) else 0) + congr 1 + funext d + cases bad (v, d) <;> simp [bit] + +theorem edgeAt_zero (G : PortGraph V D) (n : Nat) (w : Walk V D (n + 1)) : + edgeAt G n w 0 = (w.1, w.2 0) := by + cases n <;> rfl + +theorem word_first_hit_mean [Fintype D] [Nonempty D] + (G : PortGraph V D) (bad : V × D → Bool) (n : Nat) (v : V) : + mean (fun p : Fin (n + 1) → D => bit (bad (edgeAt G n (v, p) 0) = true)) = + edgeProfile bad v := by + rw [mean_word_cons_head] + simp_rw [edgeAt_zero] + change mean (fun d : D => mean (fun _ : Fin n → D => bit (bad (v, d) = true))) = _ + calc + _ = mean (fun d : D => bit (bad (v, d) = true)) := by simp only [mean_const] + _ = edgeProfile bad v := mean_edge_bit bad v + +theorem word_hit_mean [Fintype D] [Nonempty D] + (G : PortGraph V D) (bad : V × D → Bool) : + ∀ (n : Nat) (v : V) (k : Fin (n + 1)), + mean (fun p : Fin (n + 1) → D => bit (bad (edgeAt G n (v, p) k) = true)) = + iterateOperator G k.val (edgeProfile bad) v := by + intro n + induction n with + | zero => + intro v k + have hk : k = 0 := Fin.eq_zero k + subst k + exact word_first_hit_mean G bad 0 v + | succ n ih => + intro v k + refine Fin.cases ?_ (fun j => ?_) k + · exact word_first_hit_mean G bad (n + 1) v + · rw [mean_word_cons_head] + change mean (fun d : D => mean (fun p : Fin (n + 1) → D => + bit (bad (edgeAt G n (next G v d, p) j) = true))) = + averagingOperator G (iterateOperator G j.val (edgeProfile bad)) v + calc + _ = mean (fun d : D => iterateOperator G j.val (edgeProfile bad) (next G v d)) := by + congr 1 + funext d + exact ih (next G v d) j + _ = _ := rfl + +theorem word_pair_hit_mean [Fintype D] [Nonempty D] + (G : PortGraph V D) (bad : V × D → Bool) : + ∀ (n : Nat) (v : V) (i j : Fin (n + 1)), i < j → + mean (fun p : Fin (n + 1) → D => + bit (bad (edgeAt G n (v, p) i) = true) * + bit (bad (edgeAt G n (v, p) j) = true)) = + iterateOperator G i.val (markedStep G bad + (iterateOperator G (j.val - i.val - 1) (edgeProfile bad))) v := by + intro n + induction n with + | zero => + intro v i j hij + have hi : i = 0 := Fin.eq_zero i + have hj : j = 0 := Fin.eq_zero j + subst i + subst j + exact ((lt_irrefl _) hij).elim + | succ n ih => + intro v i + refine Fin.cases ?_ (fun a => ?_) i + · intro j + refine Fin.cases ?_ (fun b => ?_) j + · intro hij + exact ((lt_irrefl _) hij).elim + · intro _hij + simp only [Fin.val_zero, Fin.val_succ, Nat.sub_zero, Nat.add_sub_cancel] + rw [mean_word_cons_head] + change mean (fun d : D => mean (fun p : Fin (n + 1) → D => + bit (bad (v, d) = true) * bit (bad (edgeAt G n (next G v d, p) b) = true))) = + markedStep G bad (iterateOperator G b.val (edgeProfile bad)) v + calc + _ = mean (fun d : D => bit (bad (v, d) = true) * + iterateOperator G b.val (edgeProfile bad) (next G v d)) := by + congr 1 + funext d + rw [mean_mul_left, word_hit_mean] + _ = _ := mean_marked_bit G bad _ v + · intro j + refine Fin.cases ?_ (fun b => ?_) j + · intro hij + exact (Nat.not_lt_zero _ hij).elim + · intro hij + have hab : a < b := Nat.lt_of_succ_lt_succ hij + simp only [Fin.val_succ, Nat.add_sub_add_right] + rw [mean_word_cons_head] + change mean (fun d : D => mean (fun p : Fin (n + 1) → D => + bit (bad (edgeAt G n (next G v d, p) a) = true) * + bit (bad (edgeAt G n (next G v d, p) b) = true))) = + averagingOperator G (iterateOperator G a.val (markedStep G bad + (iterateOperator G (b.val - a.val - 1) (edgeProfile bad)))) v + calc + _ = mean (fun d : D => iterateOperator G a.val (markedStep G bad + (iterateOperator G (b.val - a.val - 1) (edgeProfile bad))) (next G v d)) := by + congr 1 + funext d + exact ih (next G v d) a b hab + _ = _ := rfl + +theorem hit_mean [Fintype V] [Fintype D] [Nonempty V] [Nonempty D] + (G : PortGraph V D) (bad : V × D → Bool) (n : Nat) (k : Fin (n + 1)) : + mean (fun w : Walk V D (n + 1) => bit (bad (edgeAt G n w k) = true)) = + edgeDensity bad := by + calc + _ = mean (fun v : V => mean (fun p : Fin (n + 1) → D => + bit (bad (edgeAt G n (v, p) k) = true))) := + mean_prod (A := V) (B := Fin (n + 1) → D) + (fun w => bit (bad (edgeAt G n w k) = true)) + _ = mean (iterateOperator G k.val (edgeProfile bad)) := by + congr 1 + funext v + exact word_hit_mean G bad n v k + _ = mean (edgeProfile bad) := mean_iterate G k.val _ + _ = _ := rfl + +theorem pair_hit_mean [Fintype V] [Fintype D] [Nonempty V] [Nonempty D] + (G : PortGraph V D) (bad : V × D → Bool) (n : Nat) + (i j : Fin (n + 1)) (hij : i < j) : + mean (fun w : Walk V D (n + 1) => bit (bad (edgeAt G n w i) = true) * + bit (bad (edgeAt G n w j) = true)) = returnMass G bad (j.val - i.val - 1) := by + calc + _ = mean (fun v : V => mean (fun p : Fin (n + 1) → D => + bit (bad (edgeAt G n (v, p) i) = true) * + bit (bad (edgeAt G n (v, p) j) = true))) := + mean_prod (A := V) (B := Fin (n + 1) → D) + (fun w => bit (bad (edgeAt G n w i) = true) * + bit (bad (edgeAt G n w j) = true)) + _ = mean (iterateOperator G i.val (markedStep G bad + (iterateOperator G (j.val - i.val - 1) (edgeProfile bad)))) := by + congr 1 + funext v + exact word_pair_hit_mean G bad n v i j hij + _ = mean (markedStep G bad + (iterateOperator G (j.val - i.val - 1) (edgeProfile bad))) := mean_iterate G i.val _ + _ = _ := rfl + +theorem pair_event_mean [Fintype V] [Fintype D] [Nonempty V] [Nonempty D] + (G : PortGraph V D) (bad : V × D → Bool) (n : Nat) + (i j : Fin (n + 1)) (hij : i < j) : + mean (fun w : Walk V D (n + 1) => + bit (bad (edgeAt G n w i) = true ∧ bad (edgeAt G n w j) = true)) = + returnMass G bad (j.val - i.val - 1) := by + simpa only [PoweringMoment.bit_mul] using pair_hit_mean G bad n i j hij + +end MinUncutGames.Foundations.PCP.PoweringReturn + +end +section +noncomputable section + +namespace MinUncutGames.Foundations.PCP.PoweringOpinions + +open PoweringWalks PoweringLabels SpectralReturn +open PoweringMoment (bit) + +variable {V D A : Type*} + +def opinionAt (G : PortGraph V D) (t : Nat) + (selectors : ∀ v, AddressSelector G t v) (labels : V → PaddedLabel D t A) + (fallback : A) (u v : V) : A := by + classical + exact if h : ∃ n, n ≤ t ∧ ∃ p : Fin n → D, wordEnd G n v p = u then + decode (selectors v) (labels v) ⟨u, h⟩ else fallback + +theorem opinionAt_eq_decode (G : PortGraph V D) (t : Nat) + (selectors : ∀ v, AddressSelector G t v) (labels : V → PaddedLabel D t A) + (fallback : A) (v : V) (u : Ball G t v) : + opinionAt G t selectors labels fallback u.val v = decode (selectors v) (labels v) u := by + classical + simp [opinionAt, u.property] + rfl + +def honestLabels (G : PortGraph V D) (t : Nat) (assignment : V → A) : + V → PaddedLabel D t A := fun v => encode G t v (fun u => assignment u.val) + +theorem opinionAt_honest (G : PortGraph V D) (t : Nat) + (selectors : ∀ v, AddressSelector G t v) (assignment : V → A) + (fallback : A) (v : V) (u : Ball G t v) : + opinionAt G t selectors (honestLabels G t assignment) fallback u.val v = + assignment u.val := by + rw [opinionAt_eq_decode] + exact congrFun (decode_encode (selectors v) (fun u => assignment u.val)) u + +variable [Fintype D] [Nonempty D] [Fintype A] [Nonempty A] + +def sampleOpinion (G : PortGraph V D) (t N : Nat) + (selectors : ∀ v, AddressSelector G t v) (labels : V → PaddedLabel D t A) + (fallback : A) (u : V) (p : Fin N → D) : A := + opinionAt G t selectors labels fallback u (wordEnd G N u p) + +def decoded (G : PortGraph V D) (t N : Nat) + (selectors : ∀ v, AddressSelector G t v) (labels : V → PaddedLabel D t A) + (fallback : A) (u : V) : A := + PoweringDecoding.mode (sampleOpinion G t N selectors labels fallback u) + +def matchFn (G : PortGraph V D) (t N : Nat) + (selectors : ∀ v, AddressSelector G t v) (labels : V → PaddedLabel D t A) + (fallback : A) (u v : V) : ℝ := + bit (opinionAt G t selectors labels fallback u v = decoded G t N selectors labels fallback u) + +omit [Nonempty D] in +theorem matchFn_mem_Icc (G : PortGraph V D) (t N : Nat) + (selectors : ∀ v, AddressSelector G t v) (labels : V → PaddedLabel D t A) + (fallback : A) (u v : V) : + matchFn G t N selectors labels fallback u v ∈ Set.Icc (0 : ℝ) 1 := by + classical + constructor + · exact PoweringMoment.bit_nonneg _ + · unfold matchFn bit + split <;> simp + +theorem decoded_modal_baseline (G : PortGraph V D) (t N : Nat) + (selectors : ∀ v, AddressSelector G t v) (labels : V → PaddedLabel D t A) + (fallback : A) (u : V) : + 1 / (Fintype.card A : ℝ) ≤ + iterateOperator G N (matchFn G t N selectors labels fallback u) u := by + have h := PoweringDecoding.mode_mass_lower (sampleOpinion G t N selectors labels fallback u) + change 1 / (Fintype.card A : ℝ) ≤ mean (fun p : Fin N → D => + matchFn G t N selectors labels fallback u (wordEnd G N u p)) at h + rwa [PoweringReturn.mean_wordEnd] at h + +theorem decoded_modal_near (G : PortGraph V D) (t M m : Nat) + (selectors : ∀ v, AddressSelector (lazyGraph G) t v) + (labels : V → PaddedLabel (Bool × D) t A) (fallback : A) + (hM : 1 ≤ M) + (hlo : (4 * Fintype.card A * M) ^ 2 - M ≤ m) + (hhi : m ≤ (4 * Fintype.card A * M) ^ 2 + M) (u : V) : + 1 / (2 * (Fintype.card A : ℝ)) ≤ + iterateOperator (lazyGraph G) m + (matchFn (lazyGraph G) t ((4 * Fintype.card A * M) ^ 2) + selectors labels fallback u) u := by + exact PoweringLazy.lazy_endpoint_modal_transfer G (Fintype.card A) M m + Fintype.card_pos hM hlo hhi _ + (matchFn_mem_Icc (lazyGraph G) t ((4 * Fintype.card A * M) ^ 2) + selectors labels fallback u) u + (decoded_modal_baseline (lazyGraph G) t ((4 * Fintype.card A * M) ^ 2) + selectors labels fallback u) + +end MinUncutGames.Foundations.PCP.PoweringOpinions + +end +end +section +namespace MinUncutGames.Foundations.PCP.PoweringReach + +open PoweringWalks PoweringLabels + +variable {V D : Type*} + +def ReachLE (G : PortGraph V D) (t : Nat) (u v : V) : Prop := + ∃ l, l ≤ t ∧ ∃ p : Fin l → D, wordEnd G l u p = v + +theorem reach_refl (G : PortGraph V D) (t : Nat) (u : V) : ReachLE G t u u := + ⟨0, Nat.zero_le t, Fin.elim0, rfl⟩ + +theorem reach_mono {G : PortGraph V D} {s t : Nat} {u v : V} + (hst : s ≤ t) (h : ReachLE G s u v) : ReachLE G t u v := by + obtain ⟨l, hl, p, hp⟩ := h + exact ⟨l, hl.trans hst, p, hp⟩ + +theorem reach_prepend (G : PortGraph V D) {t : Nat} (u : V) (d : D) {v : V} + (h : ReachLE G t (next G u d) v) : ReachLE G (t + 1) u v := by + obtain ⟨l, hl, p, hp⟩ := h + refine ⟨l + 1, Nat.succ_le_succ hl, + (fun i : Fin (l + 1) => Fin.cases d p i), ?_⟩ + simpa only [wordEnd, Fin.cases_zero, Fin.cases_succ] using hp + +def reversePorts (G : PortGraph V D) : V → List D → List D + | _, [] => [] + | v, d :: ds => reversePorts G (next G v d) ds ++ [(G.rot (v, d)).2] + +theorem reversePorts_length (G : PortGraph V D) (v : V) (ds : List D) : + (reversePorts G v ds).length = ds.length := by + induction ds generalizing v with + | nil => rfl + | cons d ds ih => simp [reversePorts, ih] + +theorem walkEnd_reversePorts (G : PortGraph V D) (v : V) (ds : List D) : + walkEnd G (walkEnd G v ds) (reversePorts G v ds) = v := by + induction ds generalizing v with + | nil => rfl + | cons d ds ih => + change walkEnd G (walkEnd G (next G v d) ds) + (reversePorts G (next G v d) ds ++ [(G.rot (v, d)).2]) = v + rw [walkEnd_append, ih] + change (G.rot (G.rot (v, d))).1 = v + exact congrArg Prod.fst (G.rot_involutive (v, d)) + +theorem wordEnd_eq_walkEnd_ofFn (G : PortGraph V D) : + ∀ n v (p : Fin n → D), wordEnd G n v p = walkEnd G v (List.ofFn p) := by + intro n + induction n with + | zero => intro v p; rfl + | succ n ih => + intro v p + rw [List.ofFn_succ, walkEnd_cons] + exact ih (next G v (p 0)) (fun j => p j.succ) + +theorem reach_reverse {G : PortGraph V D} {t : Nat} {u v : V} + (h : ReachLE G t u v) : ReachLE G t v u := by + obtain ⟨l, hl, p, hp⟩ := h + refine ⟨(reversePorts G u (List.ofFn p)).length, ?_, + (reversePorts G u (List.ofFn p)).get, ?_⟩ + · simpa only [reversePorts_length, List.length_ofFn] using hl + · rw [wordEnd_eq_walkEnd_ofFn, List.ofFn_get] + have hlist : walkEnd G u (List.ofFn p) = v := by + rw [← wordEnd_eq_walkEnd_ofFn] + exact hp + rw [← hlist, walkEnd_reversePorts] + +theorem tail_reach (G : PortGraph V D) : + ∀ (n : Nat) (w : Walk V D (n + 1)) (k : Fin (n + 1)), + ReachLE G (n + 1) w.1 (edgeAt G n w k).1 := by + intro n + induction n with + | zero => + intro w k + exact reach_refl G 1 w.1 + | succ n ih => + intro w k + refine Fin.cases ?_ (fun j => ?_) k + · exact reach_refl G (n + 2) w.1 + · exact reach_prepend G w.1 (w.2 0) (ih (advanceTail G w) j) + +theorem head_reach_endpoint (G : PortGraph V D) : + ∀ (n : Nat) (w : Walk V D (n + 1)) (k : Fin (n + 1)), + ReachLE G (n + 1) (G.rot (edgeAt G n w k)).1 (endpoint G w) := by + intro n + induction n with + | zero => + intro w k + exact reach_refl G 1 (G.rot (w.1, w.2 0)).1 + | succ n ih => + intro w k + refine Fin.cases ?_ (fun j => ?_) k + · exact ⟨n + 1, Nat.le_succ (n + 1), (fun j => w.2 j.succ), rfl⟩ + · exact reach_mono (Nat.le_succ (n + 1)) (ih (advanceTail G w) j) + +def tailFromStart (G : PortGraph V D) (n : Nat) (w : Walk V D (n + 1)) + (k : Fin (n + 1)) : Ball G (n + 1) w.1 := + ⟨(edgeAt G n w k).1, tail_reach G n w k⟩ + +def headFromEnd (G : PortGraph V D) (n : Nat) (w : Walk V D (n + 1)) + (k : Fin (n + 1)) : Ball G (n + 1) (endpoint G w) := + ⟨(G.rot (edgeAt G n w k)).1, reach_reverse (head_reach_endpoint G n w k)⟩ + +@[simp] theorem tailFromStart_val (G : PortGraph V D) (n : Nat) + (w : Walk V D (n + 1)) (k : Fin (n + 1)) : + (tailFromStart G n w k).val = (edgeAt G n w k).1 := rfl + +@[simp] theorem headFromEnd_val (G : PortGraph V D) (n : Nat) + (w : Walk V D (n + 1)) (k : Fin (n + 1)) : + (headFromEnd G n w k).val = (G.rot (edgeAt G n w k)).1 := rfl + +end MinUncutGames.Foundations.PCP.PoweringReach + +end +section +namespace MinUncutGames.Foundations.PCP.PoweringTest + +open PoweringWalks PoweringLabels PoweringReach PoweringOpinions + +variable {V D A : Type*} + +def baseGraph (G : PortGraph V D) (accepts : Edge V D → A → A → Bool) + (reverse_accepts : ∀ e a b, accepts (G.rot e) b a = accepts e a b) : + ConstraintGraph V (Edge V D) A where + reverse := G.rot + reverse_involutive := G.rot_involutive + tail := Prod.fst + accepts := accepts + reverse_accepts := reverse_accepts + +def pathAccepts (G : PortGraph V D) (accepts : Edge V D → A → A → Bool) + (n : Nat) (selectors : ∀ v, AddressSelector G (n + 1) v) + (w : Walk V D (n + 1)) (a b : PaddedLabel D (n + 1) A) : Bool := + decide (∀ k : Fin (n + 1), + accepts (edgeAt G n w k) + (decode (selectors w.1) a (tailFromStart G n w k)) + (decode (selectors (endpoint G w)) b (headFromEnd G n w k)) = true) + +theorem pathAccepts_eq_true_iff (G : PortGraph V D) + (accepts : Edge V D → A → A → Bool) + (n : Nat) (selectors : ∀ v, AddressSelector G (n + 1) v) + (w : Walk V D (n + 1)) (a b : PaddedLabel D (n + 1) A) : + pathAccepts G accepts n selectors w a b = true ↔ + ∀ k : Fin (n + 1), + accepts (edgeAt G n w k) + (decode (selectors w.1) a (tailFromStart G n w k)) + (decode (selectors (endpoint G w)) b (headFromEnd G n w k)) = true := by + simp [pathAccepts] + +abbrev Dart (V D : Type*) (n : Nat) := Bool × Walk V D (n + 1) + +def reverseDart (V D : Type*) (n : Nat) : Dart V D n ≃ Dart V D n where + toFun d := (!d.1, d.2) + invFun d := (!d.1, d.2) + left_inv := by + rintro ⟨b, w⟩ + cases b <;> rfl + right_inv := by + rintro ⟨b, w⟩ + cases b <;> rfl + +theorem reverseDart_involutive (V D : Type*) (n : Nat) : + Function.Involutive (reverseDart V D n) := by + rintro ⟨b, w⟩ + cases b <;> rfl + +def poweredGraph (G : PortGraph V D) (accepts : Edge V D → A → A → Bool) + (n : Nat) (selectors : ∀ v, AddressSelector G (n + 1) v) : + ConstraintGraph V (Dart V D n) (PaddedLabel D (n + 1) A) where + reverse := reverseDart V D n + reverse_involutive := reverseDart_involutive V D n + tail d := if d.1 then endpoint G d.2 else d.2.1 + accepts d a b := if d.1 then pathAccepts G accepts n selectors d.2 b a + else pathAccepts G accepts n selectors d.2 a b + reverse_accepts := by + rintro ⟨direction, w⟩ a b + cases direction <;> rfl + +@[simp] theorem poweredGraph_tail_false (G : PortGraph V D) + (accepts : Edge V D → A → A → Bool) (n : Nat) + (selectors : ∀ v, AddressSelector G (n + 1) v) (w : Walk V D (n + 1)) : + (poweredGraph G accepts n selectors).tail (false, w) = w.1 := rfl + +@[simp] theorem poweredGraph_tail_true (G : PortGraph V D) + (accepts : Edge V D → A → A → Bool) (n : Nat) + (selectors : ∀ v, AddressSelector G (n + 1) v) (w : Walk V D (n + 1)) : + (poweredGraph G accepts n selectors).tail (true, w) = endpoint G w := rfl + +theorem poweredGraph_edgeSatisfied (G : PortGraph V D) + (accepts : Edge V D → A → A → Bool) (n : Nat) + (selectors : ∀ v, AddressSelector G (n + 1) v) + (labels : V → PaddedLabel D (n + 1) A) + (direction : Bool) (w : Walk V D (n + 1)) : + (poweredGraph G accepts n selectors).edgeSatisfied labels (direction, w) = + pathAccepts G accepts n selectors w (labels w.1) (labels (endpoint G w)) := by + cases direction <;> rfl + +theorem rejection_mean_eq_path_mean [Fintype V] [Fintype D] + (G : PortGraph V D) (accepts : Edge V D → A → A → Bool) (n : Nat) + (selectors : ∀ v, AddressSelector G (n + 1) v) + (labels : V → PaddedLabel D (n + 1) A) : + SpectralReturn.mean (fun d : Dart V D n => PoweringMoment.bit + ((poweredGraph G accepts n selectors).edgeSatisfied labels d = false)) = + SpectralReturn.mean (fun w : Walk V D (n + 1) => PoweringMoment.bit + (pathAccepts G accepts n selectors w (labels w.1) (labels (endpoint G w)) = false)) := by + rw [SpectralReturn.mean_prod] + simp only [poweredGraph_edgeSatisfied, SpectralReturn.mean_const] + +theorem pathAccepts_honest (G : PortGraph V D) + (accepts : Edge V D → A → A → Bool) (n : Nat) + (selectors : ∀ v, AddressSelector G (n + 1) v) + (assignment : V → A) + (satisfies : ∀ e, accepts e (assignment e.1) (assignment (G.rot e).1) = true) + (w : Walk V D (n + 1)) : + pathAccepts G accepts n selectors w + (honestLabels G (n + 1) assignment w.1) + (honestLabels G (n + 1) assignment (endpoint G w)) = true := by + apply (pathAccepts_eq_true_iff G accepts n selectors w _ _).2 + intro k + simpa only [honestLabels, decode_encode, tailFromStart_val, headFromEnd_val] using + satisfies (edgeAt G n w k) + +theorem perfect_completeness (G : PortGraph V D) + (accepts : Edge V D → A → A → Bool) (n : Nat) + (selectors : ∀ v, AddressSelector G (n + 1) v) + (assignment : V → A) + (satisfies : ∀ e, accepts e (assignment e.1) (assignment (G.rot e).1) = true) : + ∀ d, (poweredGraph G accepts n selectors).edgeSatisfied + (honestLabels G (n + 1) assignment) d = true := by + rintro ⟨direction, w⟩ + rw [poweredGraph_edgeSatisfied] + exact pathAccepts_honest G accepts n selectors assignment satisfies w + +theorem preserves_satisfiability (G : PortGraph V D) + (accepts : Edge V D → A → A → Bool) + (reverse_accepts : ∀ e a b, accepts (G.rot e) b a = accepts e a b) + (n : Nat) (selectors : ∀ v, AddressSelector G (n + 1) v) + (h : (baseGraph G accepts reverse_accepts).Satisfiable) : + (poweredGraph G accepts n selectors).Satisfiable := by + obtain ⟨assignment, satisfies⟩ := h + refine ⟨honestLabels G (n + 1) assignment, ?_⟩ + apply perfect_completeness G accepts n selectors assignment + intro e + exact satisfies e + +def decodedBad (G : PortGraph V D) (accepts : Edge V D → A → A → Bool) + (assignment : V → A) (e : Edge V D) : Bool := + !(accepts e (assignment e.1) (assignment (G.rot e).1)) + +theorem decodedBad_eq_true_iff (G : PortGraph V D) + (accepts : Edge V D → A → A → Bool) (assignment : V → A) (e : Edge V D) : + decodedBad G accepts assignment e = true ↔ + accepts e (assignment e.1) (assignment (G.rot e).1) = false := by + simp [decodedBad] + +theorem decodedBad_rot (G : PortGraph V D) + (accepts : Edge V D → A → A → Bool) + (reverse_accepts : ∀ e a b, accepts (G.rot e) b a = accepts e a b) + (assignment : V → A) (e : Edge V D) : + decodedBad G accepts assignment (G.rot e) = decodedBad G accepts assignment e := by + have h := congrArg Bool.not + (reverse_accepts e (assignment e.1) (assignment (G.rot e).1)) + simpa only [decodedBad, G.rot_involutive e] using h + +noncomputable def witness (G : PortGraph V D) + (accepts : Edge V D → A → A → Bool) (n : Nat) + (selectors : ∀ v, AddressSelector G (n + 1) v) + (labels : V → PaddedLabel D (n + 1) A) (fallback : A) + (assignment : V → A) (w : Walk V D (n + 1)) (k : Fin (n + 1)) : Prop := + decodedBad G accepts assignment (edgeAt G n w k) = true ∧ + opinionAt G (n + 1) selectors labels fallback (edgeAt G n w k).1 w.1 = + assignment (edgeAt G n w k).1 ∧ + opinionAt G (n + 1) selectors labels fallback + (G.rot (edgeAt G n w k)).1 (endpoint G w) = + assignment (G.rot (edgeAt G n w k)).1 + +theorem witness_bad (G : PortGraph V D) + (accepts : Edge V D → A → A → Bool) (n : Nat) + (selectors : ∀ v, AddressSelector G (n + 1) v) + (labels : V → PaddedLabel D (n + 1) A) (fallback : A) + (assignment : V → A) (w : Walk V D (n + 1)) (k : Fin (n + 1)) + (h : witness G accepts n selectors labels fallback assignment w k) : + decodedBad G accepts assignment (edgeAt G n w k) = true := h.1 + +theorem witness_implies_path_rejection (G : PortGraph V D) + (accepts : Edge V D → A → A → Bool) (n : Nat) + (selectors : ∀ v, AddressSelector G (n + 1) v) + (labels : V → PaddedLabel D (n + 1) A) (fallback : A) + (assignment : V → A) (w : Walk V D (n + 1)) (k : Fin (n + 1)) + (h : witness G accepts n selectors labels fallback assignment w k) : + pathAccepts G accepts n selectors w (labels w.1) (labels (endpoint G w)) = false := by + obtain ⟨hBad, hTail, hHead⟩ := h + have hTailDecode : + decode (selectors w.1) (labels w.1) (tailFromStart G n w k) = + assignment (edgeAt G n w k).1 := + (opinionAt_eq_decode G (n + 1) selectors labels fallback w.1 + (tailFromStart G n w k)).symm.trans hTail + have hHeadDecode : + decode (selectors (endpoint G w)) (labels (endpoint G w)) + (headFromEnd G n w k) = assignment (G.rot (edgeAt G n w k)).1 := + (opinionAt_eq_decode G (n + 1) selectors labels fallback (endpoint G w) + (headFromEnd G n w k)).symm.trans hHead + have hFalse := (decodedBad_eq_true_iff G accepts assignment (edgeAt G n w k)).1 hBad + cases hPath : pathAccepts G accepts n selectors w + (labels w.1) (labels (endpoint G w)) with + | false => rfl + | true => + have hChecked := (pathAccepts_eq_true_iff G accepts n selectors w _ _).1 hPath k + rw [hTailDecode, hHeadDecode, hFalse] at hChecked + exact False.elim (Bool.noConfusion hChecked) + +theorem witness_implies_rejection (G : PortGraph V D) + (accepts : Edge V D → A → A → Bool) (n : Nat) + (selectors : ∀ v, AddressSelector G (n + 1) v) + (labels : V → PaddedLabel D (n + 1) A) (fallback : A) + (assignment : V → A) (w : Walk V D (n + 1)) (k : Fin (n + 1)) + (h : witness G accepts n selectors labels fallback assignment w k) + (direction : Bool) : + (poweredGraph G accepts n selectors).edgeSatisfied labels (direction, w) = false := by + rw [poweredGraph_edgeSatisfied] + exact witness_implies_path_rejection G accepts n selectors labels fallback assignment w k h + +end MinUncutGames.Foundations.PCP.PoweringTest + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/PoweringRowData.lean b/lean/OAI/Computability/MinUncut/PCP/PoweringRowData.lean new file mode 100644 index 0000000000000000000000000000000000000000..bbc30c1004b3a13cebe87c4e74f7936b53dcf83b --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/PoweringRowData.lean @@ -0,0 +1,490 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.PoweringMachineRow + +namespace OAI + +section +namespace MinUncutGames.Foundations.PCP.PoweringRowData + +open MinUncutGames.Foundations.Complexity +open Turing +open PoweringMachineRow MachineFixedBlockMap +open PoweringWalks PoweringLabels PoweringAddresses PoweringReach +open PoweringOpinionTables PoweringEnumeration + +variable {vertices d : Nat} + +theorem firstMatch_of_first {S : Nat} (mask : Fin S → Bool) (i : Fin S) + (hi : mask i = true) (hfirst : ∀ j : Fin S, j.val < i.val → mask j = false) : + firstMatch mask = some i := by + unfold firstMatch + apply List.find?_ofFn_eq_some.mpr + refine ⟨hi, i, rfl, ?_⟩ + intro j hj + change ¬mask j = true + simp [hfirst j hj] + +theorem firstMatch_firstIndex {X : Type*} (p : X → Prop) [DecidablePred p] + (xs : List X) (h : ∃ a ∈ xs, p a) : + firstMatch (fun i : Fin xs.length => decide (p (xs.get i))) = + some (firstIndex p xs h) := by + apply firstMatch_of_first + · exact decide_eq_true (firstIndex_matches p xs h) + · intro j hj + exact decide_eq_false (firstIndex_is_first p xs h j hj) + +def endpointMask (G : PortGraph (Fin vertices) (Fin d)) (t : Nat) + (center target : Fin vertices) (i : AddressIndex d t) : Bool := + decide ((wordToBall G t center ((allAddresses d t).get i)).val = target) + +theorem firstMatch_endpointMask (G : PortGraph (Fin vertices) (Fin d)) (t : Nat) + (center : Fin vertices) (u : Ball G t center) : + firstMatch (endpointMask G t center u.val) = some (addressIndex G t center u) := by + unfold endpointMask addressIndex + exact firstMatch_firstIndex + (fun w : PortWords (Fin d) t => (wordToBall G t center w).val = u.val) + (allAddresses d t) (by + obtain ⟨w, hw⟩ := wordToBall_surjective G t center u + exact ⟨w, mem_allAddresses d t w, congrArg Subtype.val hw⟩) + +def slotCount (d n : Nat) : Nat := (allAddresses d (n + 1)).length + +abbrev RowBuffer (d n : Nat) := Buffer (inputSize (n + 1) (slotCount d n)) + +def fixedLabelAt (d n : Nat) (a : Fin (PoweringTables.labelCount d n)) + (i : Fin (slotCount d n)) : GraphTables.Label := + decodeLabel d (n + 1) 64 a ((allAddresses d (n + 1)).get i) + +theorem fixedLabelAt_addressIndex (G : PortGraph (Fin vertices) (Fin d)) (n : Nat) + (center : Fin vertices) (u : Ball G (n + 1) center) + (a : Fin (PoweringTables.labelCount d n)) : + fixedLabelAt d n a (addressIndex G (n + 1) center u) = + decode (finitePortSelector G (n + 1) center) (decodeLabel d (n + 1) 64 a) u := by + simpa only [fixedLabelAt, labelTable_get] using + labelTable_addressIndex G (n + 1) center u (decodeLabel d (n + 1) 64 a) + +def walkData (input : PortTables.Table vertices d) (n : Nat) + (w : Walk (Fin vertices) (Fin d) (n + 1)) + (k : Fin (n + 1)) : Field (slotCount d n) → Bool + | .inl (a, b) => PortTables.accepts input (edgeAt (PortTables.portGraph input) n w k) a b + | .inr (.inl i) => endpointMask (PortTables.portGraph input) (n + 1) w.1 + (edgeAt (PortTables.portGraph input) n w k).1 i + | .inr (.inr i) => endpointMask (PortTables.portGraph input) (n + 1) + (endpoint (PortTables.portGraph input) w) + ((PortTables.portGraph input).rot (edgeAt (PortTables.portGraph input) n w k)).1 i + +def walkBits (input : PortTables.Table vertices d) (n : Nat) + (w : Walk (Fin vertices) (Fin d) (n + 1)) : RowBuffer d n := + packData (walkData input n w) + +@[simp] theorem basePredicate_walkBits (input : PortTables.Table vertices d) (n : Nat) + (w : Walk (Fin vertices) (Fin d) (n + 1)) (k : Fin (n + 1)) + (a b : GraphTables.Label) : + basePredicate (walkBits input n w) k a b = + PortTables.accepts input (edgeAt (PortTables.portGraph input) n w k) a b := by + simp [basePredicate, walkBits, walkData] + +@[simp] theorem leftMatches_walkBits (input : PortTables.Table vertices d) (n : Nat) + (w : Walk (Fin vertices) (Fin d) (n + 1)) (k : Fin (n + 1)) : + leftMatches (walkBits input n w) k = endpointMask (PortTables.portGraph input) + (n + 1) w.1 (edgeAt (PortTables.portGraph input) n w k).1 := by + funext i + simp [leftMatches, walkBits, walkData] + +@[simp] theorem rightMatches_walkBits (input : PortTables.Table vertices d) (n : Nat) + (w : Walk (Fin vertices) (Fin d) (n + 1)) (k : Fin (n + 1)) : + rightMatches (walkBits input n w) k = endpointMask (PortTables.portGraph input) + (n + 1) (endpoint (PortTables.portGraph input) w) + ((PortTables.portGraph input).rot (edgeAt (PortTables.portGraph input) n w k)).1 := by + funext i + simp [rightMatches, walkBits, walkData] + +theorem firstMatch_walkBits_left (input : PortTables.Table vertices d) (n : Nat) + (w : Walk (Fin vertices) (Fin d) (n + 1)) (k : Fin (n + 1)) : + firstMatch (leftMatches (walkBits input n w) k) = some + (addressIndex (PortTables.portGraph input) (n + 1) w.1 + (tailFromStart (PortTables.portGraph input) n w k)) := by + rw [leftMatches_walkBits] + simpa only [tailFromStart_val, slotCount] using + firstMatch_endpointMask (PortTables.portGraph input) (n + 1) w.1 + (tailFromStart (PortTables.portGraph input) n w k) + +theorem firstMatch_walkBits_right (input : PortTables.Table vertices d) (n : Nat) + (w : Walk (Fin vertices) (Fin d) (n + 1)) (k : Fin (n + 1)) : + firstMatch (rightMatches (walkBits input n w) k) = some + (addressIndex (PortTables.portGraph input) (n + 1) + (endpoint (PortTables.portGraph input) w) + (headFromEnd (PortTables.portGraph input) n w k)) := by + rw [rightMatches_walkBits] + simpa only [headFromEnd_val, slotCount] using + firstMatch_endpointMask (PortTables.portGraph input) (n + 1) + (endpoint (PortTables.portGraph input) w) (headFromEnd (PortTables.portGraph input) n w k) + +theorem edgeAccept_walkBits (input : PortTables.Table vertices d) (n : Nat) + (w : Walk (Fin vertices) (Fin d) (n + 1)) (k : Fin (n + 1)) + (a b : Fin (PoweringTables.labelCount d n)) : + edgeAccept (fixedLabelAt d n) (walkBits input n w) k a b = + PortTables.accepts input (edgeAt (PortTables.portGraph input) n w k) + (decode (finitePortSelector (PortTables.portGraph input) (n + 1) w.1) + (decodeLabel d (n + 1) 64 a) (tailFromStart (PortTables.portGraph input) n w k)) + (decode (finitePortSelector (PortTables.portGraph input) (n + 1) + (endpoint (PortTables.portGraph input) w)) + (decodeLabel d (n + 1) 64 b) (headFromEnd (PortTables.portGraph input) n w k)) := by + simp only [edgeAccept, firstMatch_walkBits_left, firstMatch_walkBits_right, + basePredicate_walkBits, fixedLabelAt_addressIndex] + +theorem rowAccept_walkBits (input : PortTables.Table vertices d) (n : Nat) + (w : Walk (Fin vertices) (Fin d) (n + 1)) + (a b : Fin (PoweringTables.labelCount d n)) : + rowAccept (fixedLabelAt d n) (walkBits input n w) a b = + rowsAccepts (PortTables.accepts input) (walkRows (PortTables.portGraph input) n w) + (labelTable (decodeLabel d (n + 1) 64 a)) + (labelTable (decodeLabel d (n + 1) 64 b)) := by + rw [rowsAccepts_walkRows] + apply Bool.eq_iff_iff.mpr + simp only [rowAccept_eq_true, PoweringTest.pathAccepts_eq_true_iff, edgeAccept_walkBits] + +def transposeField {S : Nat} : Field S → Field S + | .inl (a, b) => .inl (b, a) + | .inr (.inl i) => .inr (.inr i) + | .inr (.inr i) => .inr (.inl i) + +def transposeBits {t S : Nat} (bits : Buffer (inputSize t S)) : Buffer (inputSize t S) := + packData fun k field => bits (inputEquiv t S (k, transposeField field)) + +@[simp] theorem basePredicate_transposeBits {t S : Nat} + (bits : Buffer (inputSize t S)) (k : Fin t) (a b : GraphTables.Label) : + basePredicate (transposeBits bits) k a b = basePredicate bits k b a := by + simp [basePredicate, transposeBits, transposeField] + +@[simp] theorem leftMatches_transposeBits {t S : Nat} + (bits : Buffer (inputSize t S)) (k : Fin t) : + leftMatches (transposeBits bits) k = rightMatches bits k := by + funext i + simp [leftMatches, rightMatches, transposeBits, transposeField] + +@[simp] theorem rightMatches_transposeBits {t S : Nat} + (bits : Buffer (inputSize t S)) (k : Fin t) : + rightMatches (transposeBits bits) k = leftMatches bits k := by + funext i + simp [leftMatches, rightMatches, transposeBits, transposeField] + +theorem edgeAccept_transposeBits {t S q : Nat} + (labelAt : Fin q → Fin S → GraphTables.Label) + (bits : Buffer (inputSize t S)) (k : Fin t) (a b : Fin q) : + edgeAccept labelAt (transposeBits bits) k a b = edgeAccept labelAt bits k b a := by + simp only [edgeAccept, leftMatches_transposeBits, rightMatches_transposeBits] + cases firstMatch (leftMatches bits k) <;> + cases firstMatch (rightMatches bits k) <;> + simp + +theorem rowAccept_transposeBits {t S q : Nat} + (labelAt : Fin q → Fin S → GraphTables.Label) + (bits : Buffer (inputSize t S)) (a b : Fin q) : + rowAccept labelAt (transposeBits bits) a b = rowAccept labelAt bits b a := by + apply Bool.eq_iff_iff.mpr + simp only [rowAccept_eq_true, edgeAccept_transposeBits] + +def rowBits (input : PortTables.Table vertices d) (n : Nat) + (e : PoweringTest.Dart (Fin vertices) (Fin d) n) : RowBuffer d n := + if e.1 then transposeBits (walkBits input n e.2) else walkBits input n e.2 + +def rowData (input : PortTables.Table vertices d) (n : Nat) + (e : PoweringTest.Dart (Fin vertices) (Fin d) n) + (k : Fin (n + 1)) (field : Field (slotCount d n)) : Bool := + walkData input n e.2 k (if e.1 then transposeField field else field) + +theorem rowBits_packData (input : PortTables.Table vertices d) (n : Nat) + (e : PoweringTest.Dart (Fin vertices) (Fin d) n) : + rowBits input n e = packData (rowData input n e) := by + rcases e with ⟨direction, w⟩ + cases direction <;> funext i <;> + simp [rowBits, rowData, transposeBits, walkBits, packData] + +@[simp] theorem rowBits_field (input : PortTables.Table vertices d) (n : Nat) + (e : PoweringTest.Dart (Fin vertices) (Fin d) n) + (k : Fin (n + 1)) (field : Field (slotCount d n)) : + rowBits input n e (inputEquiv (n + 1) (slotCount d n) (k, field)) = + rowData input n e k field := by + rw [rowBits_packData, packData_inputEquiv] + +theorem rowAccept_rowBits (input : PortTables.Table vertices d) (n : Nat) + (e : PoweringTest.Dart (Fin vertices) (Fin d) n) + (a b : Fin (PoweringTables.labelCount d n)) : + rowAccept (fixedLabelAt d n) (rowBits input n e) a b = + PoweringTables.rowAccepts input n e a b := by + rcases e with ⟨direction, w⟩ + cases direction <;> + simp only [rowBits, Bool.false_eq_true, ite_false, ite_true, + rowAccept_transposeBits, rowAccept_walkBits, PoweringTables.rowAccepts] + +theorem rowBlock_at_rowBits (input : PortTables.Table vertices d) (n : Nat) + (e : PoweringTest.Dart (Fin vertices) (Fin d) n) + (a b : Fin (PoweringTables.labelCount d n)) : + rowBlock (fixedLabelAt d n) (rowBits input n e) + (GenericGraphTables.relationIndex (PoweringTables.labelCount d n) (a, b)) = + PoweringTables.rowAccepts input n e a b := by + rw [rowBlock_at, rowAccept_rowBits] + +def dataWords (input : PortTables.Table vertices d) (n : Nat) + (e : PoweringTest.Dart (Fin vertices) (Fin d) n) : List Nat := + (List.ofFn (rowBits input n e)).map GraphTables.bitWord + +def dataTape (input : PortTables.Table vertices d) (n : Nat) + (e : PoweringTest.Dart (Fin vertices) (Fin d) n) : List Bool := + encodeWords (dataWords input n e) + +theorem dataTape_eq (input : PortTables.Table vertices d) (n : Nat) + (e : PoweringTest.Dart (Fin vertices) (Fin d) n) : + dataTape input n e = encodeBits (List.ofFn (rowBits input n e)) := + (encodeBits_graphWords _).symm + +theorem dataWords_length (input : PortTables.Table vertices d) (n : Nat) + (e : PoweringTest.Dart (Fin vertices) (Fin d) n) : + (dataWords input n e).length = (n + 1) * (4096 + (slotCount d n + slotCount d n)) := by + rw [dataWords, List.length_map] + simpa only [inputSize] using (List.length_ofFn (f := rowBits input n e)) + +theorem dataTape_length_le (input : PortTables.Table vertices d) (n : Nat) + (e : PoweringTest.Dart (Fin vertices) (Fin d) n) : + (dataTape input n e).length ≤ 2 * inputSize (n + 1) (slotCount d n) := by + rw [dataTape_eq] + simpa only [List.length_ofFn] using encodeBits_length_le (List.ofFn (rowBits input n e)) + +def emittedRelation (input : PortTables.Table vertices d) (n : Nat) + (e : PoweringTest.Dart (Fin vertices) (Fin d) n) : + GenericGraphTables.RelationTable (PoweringTables.labelCount d n) := + Vector.ofFn (rowBlock (fixedLabelAt d n) (rowBits input n e)) + +theorem emittedRelation_eq (input : PortTables.Table vertices d) (n : Nat) + (e : PoweringTest.Dart (Fin vertices) (Fin d) n) : + emittedRelation input n e = GenericGraphTables.relationOf (PoweringTables.rowAccepts input n e) := by + unfold emittedRelation GenericGraphTables.relationOf + apply congrArg Vector.ofFn + funext i + exact rowAccept_rowBits input n e _ _ + +theorem rowBlock_unary (input : PortTables.Table vertices d) (n : Nat) + (e : PoweringTest.Dart (Fin vertices) (Fin d) n) : + encodeBits (List.ofFn (rowBlock (fixedLabelAt d n) (rowBits input n e))) = + encodeWords (GenericGraphTables.relationWords (emittedRelation input n e)) := by + have hbit : GraphTables.bitWord = GenericGraphTables.bitWord := by + funext b + cases b <;> rfl + have h := encodeBits_graphWords + (List.ofFn (rowBlock (fixedLabelAt d n) (rowBits input n e))) + rw [hbit] at h + simpa only [emittedRelation, GenericGraphTables.relationWords, Vector.toList_ofFn] using h + +theorem emittedRelation_table (input : PortTables.Table vertices d) (n : Nat) + (i : Fin (PoweringTables.dartCount vertices d n)) : + emittedRelation input n (decodeDart vertices d n i) = + (PoweringTables.table input n).rows[i].relation := by + apply Vector.ext + intro j hj + have h := PoweringTables.table_accepts input n i + ((GenericGraphTables.relationIndex (PoweringTables.labelCount d n)).symm ⟨j, hj⟩).1 + ((GenericGraphTables.relationIndex (PoweringTables.labelCount d n)).symm ⟨j, hj⟩).2 + have hindex : GenericGraphTables.relationIndex (PoweringTables.labelCount d n) + (((GenericGraphTables.relationIndex (PoweringTables.labelCount d n)).symm ⟨j, hj⟩).1, + ((GenericGraphTables.relationIndex (PoweringTables.labelCount d n)).symm ⟨j, hj⟩).2) = + ⟨j, hj⟩ := by + change GenericGraphTables.relationIndex (PoweringTables.labelCount d n) + ((GenericGraphTables.relationIndex (PoweringTables.labelCount d n)).symm ⟨j, hj⟩) = _ + exact Equiv.apply_symm_apply _ _ + simp only [GenericGraphTables.acceptsAt, GenericGraphTables.relationAt, hindex, + Fin.getElem_fin] at h + simp only [emittedRelation, Vector.getElem_ofFn] + change rowBlock (fixedLabelAt d n) (rowBits input n (decodeDart vertices d n i)) ⟨j, hj⟩ = + (PoweringTables.table input n).rows[i].relation[j] + change rowAccept (fixedLabelAt d n) (rowBits input n (decodeDart vertices d n i)) + ((GenericGraphTables.relationIndex (PoweringTables.labelCount d n)).symm ⟨j, hj⟩).1 + ((GenericGraphTables.relationIndex (PoweringTables.labelCount d n)).symm ⟨j, hj⟩).2 = _ + rw [rowAccept_rowBits] + exact h.symm + +theorem rowBlock_unary_table (input : PortTables.Table vertices d) (n : Nat) + (i : Fin (PoweringTables.dartCount vertices d n)) : + encodeBits (List.ofFn (rowBlock (fixedLabelAt d n) + (rowBits input n (decodeDart vertices d n i)))) = + encodeWords (GenericGraphTables.relationWords (PoweringTables.table input n).rows[i].relation) := by + rw [rowBlock_unary, emittedRelation_table] + +def tableRowMachineInTime (input : PortTables.Table vertices d) (n : Nat) + (i : Fin (PoweringTables.dartCount vertices d n)) (suffix : List Bool) + (register : RowBuffer d n) (tapes : Bool → List Bool) + (hinput : tapes false = dataTape input n (decodeDart vertices d n i) ++ suffix) : + StateTransition.EvalsToInTime (PoweringMachineRow.machine (t := n + 1) (fixedLabelAt d n)).step + ⟨some (), ((), register), tapes⟩ + (some ⟨none, ((), emptyBuffer (inputSize (n + 1) (slotCount d n))), + Function.update (Function.update tapes false suffix) true + (encodeWords (GenericGraphTables.relationWords + (PoweringTables.table input n).rows[i].relation) ++ tapes true)⟩) 1 := by + have hinput' : tapes false = + encodeBits (List.ofFn (rowBits input n (decodeDart vertices d n i))) ++ suffix := by + simpa only [dataTape_eq] using hinput + have h := PoweringMachineRow.machineInTime (fixedLabelAt d n) + (rowBits input n (decodeDart vertices d n i)) suffix register tapes hinput' + simpa only [rowBlock_unary_table] using h + +end MinUncutGames.Foundations.PCP.PoweringRowData + +end +section +namespace MinUncutGames.Foundations.PCP.PoweringFieldPlan + +open PoweringWalks PoweringLabels PoweringAddresses PoweringReach PoweringRowData +open MinUncutGames.Foundations.Complexity PoweringMachineRow + +variable {V D : Type*} + +def tailPorts : (n : Nat) → (Fin (n + 1) → D) → Fin (n + 1) → List D + | 0, _, _ => [] + | n + 1, p, k => Fin.cases [] (fun j => p 0 :: tailPorts n (fun i => p i.succ) j) k + +theorem tailPorts_length : ∀ (n : Nat) (p : Fin (n + 1) → D) (k : Fin (n + 1)), + (tailPorts n p k).length = k.val := by + intro n + induction n with + | zero => intro p k; have hk := Fin.eq_zero k; subst k; rfl + | succ n ih => + intro p k + refine Fin.cases rfl (fun j => ?_) k + simp only [tailPorts, Fin.cases_succ, List.length_cons, ih, Fin.val_succ] + +theorem walkEnd_tailPorts (G : PortGraph V D) : + ∀ (n : Nat) (v : V) (p : Fin (n + 1) → D) (k : Fin (n + 1)), + walkEnd G v (tailPorts n p k) = (edgeAt G n (v, p) k).1 := by + intro n + induction n with + | zero => intro v p k; rfl + | succ n ih => + intro v p k + refine Fin.cases rfl (fun j => ?_) k + exact ih (next G v (p 0)) (fun i => p i.succ) j + +def headPorts (n : Nat) (p : Fin (n + 1) → D) (k : Fin (n + 1)) : List D := + tailPorts n p k ++ [p k] + +theorem walkEnd_headPorts (G : PortGraph V D) (n : Nat) (v : V) + (p : Fin (n + 1) → D) (k : Fin (n + 1)) : + walkEnd G v (headPorts n p k) = (G.rot (edgeAt G n (v, p) k)).1 := by + rw [headPorts, walkEnd_append, walkEnd_tailPorts] + change (G.rot ((edgeAt G n (v, p) k).1, p k)).1 = _ + have hp : (edgeAt G n (v, p) k).2 = p k := edgeAt_port G n (v, p) k + rw [← hp] + +def addressPorts {d t : Nat} (i : PoweringOpinionTables.AddressIndex d t) : List (Fin d) := + List.ofFn ((allAddresses d t).get i).2 + +theorem walkEnd_addressPorts {d t : Nat} (G : PortGraph V (Fin d)) (v : V) + (i : PoweringOpinionTables.AddressIndex d t) : + walkEnd G v (addressPorts i) = (wordToBall G t v ((allAddresses d t).get i)).val := + (wordEnd_eq_walkEnd_ofFn G _ _ _).symm + +inductive Instruction (d : Nat) where + | relation (ports : List (Fin d)) (port : Fin d) (left right : Fin 64) + | equal (left right : List (Fin d)) + +def Instruction.radius {d : Nat} : Instruction d → Nat + | .relation ports _ _ _ => ports.length + | .equal left right => max left.length right.length + +theorem addressPorts_length_le {d t : Nat} (i : PoweringOpinionTables.AddressIndex d t) : + (addressPorts i).length ≤ t := by + simp only [addressPorts, List.length_ofFn] + exact Nat.le_of_lt_succ ((allAddresses d t).get i).1.isLt + +def evaluate {vertices d : Nat} (input : PortTables.Table vertices d) + (start : Fin vertices) : Instruction d → Bool + | .relation ports port a b => PortTables.accepts input + (walkEnd (PortTables.portGraph input) start ports, port) a b + | .equal left right => decide + (walkEnd (PortTables.portGraph input) start left = + walkEnd (PortTables.portGraph input) start right) + +def fieldPlan {d : Nat} (n : Nat) (ports : Fin (n + 1) → Fin d) + (k : Fin (n + 1)) : Field (slotCount d n) → Instruction d + | .inl (a, b) => .relation (tailPorts n ports k) (ports k) a b + | .inr (.inl i) => .equal (addressPorts i) (tailPorts n ports k) + | .inr (.inr i) => .equal (List.ofFn ports ++ addressPorts i) (headPorts n ports k) + +theorem evaluate_fieldPlan {vertices d : Nat} (input : PortTables.Table vertices d) + (n : Nat) (start : Fin vertices) (ports : Fin (n + 1) → Fin d) + (k : Fin (n + 1)) (field : Field (slotCount d n)) : + evaluate input start (fieldPlan n ports k field) = walkData input n (start, ports) k field := by + rcases field with ⟨a,b⟩ | i | i + · simp only [evaluate, fieldPlan, walkData, walkEnd_tailPorts] + have hp : (edgeAt (PortTables.portGraph input) n (start, ports) k).2 = ports k := + edgeAt_port (PortTables.portGraph input) n (start, ports) k + rw [← hp] + · simp only [evaluate, fieldPlan, walkData, endpointMask, walkEnd_tailPorts] + have ha := walkEnd_addressPorts (t := n + 1) (PortTables.portGraph input) start i + rw [ha] + · simp only [evaluate, fieldPlan, walkData, endpointMask, walkEnd_append, + walkEnd_headPorts] + rw [← wordEnd_eq_walkEnd_ofFn] + have ha := walkEnd_addressPorts (t := n + 1) (PortTables.portGraph input) + (wordEnd (PortTables.portGraph input) (n + 1) start ports) i + rw [ha] + rfl + +def directedFieldPlan {d : Nat} (n : Nat) (ports : Fin (n + 1) → Fin d) + (direction : Bool) (k : Fin (n + 1)) (field : Field (slotCount d n)) : Instruction d := + fieldPlan n ports k (if direction then transposeField field else field) + +theorem fieldPlan_radius {d : Nat} (n : Nat) (ports : Fin (n + 1) → Fin d) + (k : Fin (n + 1)) (field : Field (slotCount d n)) : + (fieldPlan n ports k field).radius ≤ 2 * (n + 1) := by + have hk := k.isLt + rcases field with ⟨a,b⟩ | i | i + · simp only [fieldPlan, Instruction.radius, tailPorts_length] + omega + · have hi := addressPorts_length_le i + simp only [fieldPlan, Instruction.radius, tailPorts_length] + exact max_le (by omega) (by omega) + · have hi := addressPorts_length_le i + simp only [fieldPlan, Instruction.radius, headPorts, List.length_append, + List.length_ofFn, List.length_singleton, tailPorts_length] + exact max_le (by omega) (by omega) + +theorem directedFieldPlan_radius {d : Nat} (n : Nat) (ports : Fin (n + 1) → Fin d) + (direction : Bool) (k : Fin (n + 1)) (field : Field (slotCount d n)) : + (directedFieldPlan n ports direction k field).radius ≤ 2 * (n + 1) := + fieldPlan_radius n ports k _ + +theorem evaluate_directedFieldPlan {vertices d : Nat} (input : PortTables.Table vertices d) + (n : Nat) (start : Fin vertices) (ports : Fin (n + 1) → Fin d) + (direction : Bool) (k : Fin (n + 1)) (field : Field (slotCount d n)) : + evaluate input start (directedFieldPlan n ports direction k field) = + rowData input n (direction, start, ports) k field := + evaluate_fieldPlan input n start ports k _ + +def rowPlan {d : Nat} (n : Nat) (ports : Fin (n + 1) → Fin d) (direction : Bool) : + List (Instruction d) := + List.ofFn fun i : Fin (inputSize (n + 1) (slotCount d n)) => + let pair := (inputEquiv (n + 1) (slotCount d n)).symm i + directedFieldPlan n ports direction pair.1 pair.2 + +theorem evaluate_rowPlan {vertices d : Nat} (input : PortTables.Table vertices d) + (n : Nat) (start : Fin vertices) (ports : Fin (n + 1) → Fin d) (direction : Bool) : + (rowPlan n ports direction).map (evaluate input start) = + List.ofFn (rowBits input n (direction, start, ports)) := by + rw [rowPlan, List.map_ofFn] + apply congrArg List.ofFn + funext i + dsimp only [Function.comp_apply] + rw [evaluate_directedFieldPlan, rowBits_packData] + rfl + +theorem dataTape_eq_plan {vertices d : Nat} (input : PortTables.Table vertices d) + (n : Nat) (start : Fin vertices) (ports : Fin (n + 1) → Fin d) (direction : Bool) : + dataTape input n (direction, start, ports) = + encodeBits ((rowPlan n ports direction).map (evaluate input start)) := by + rw [evaluate_rowPlan, dataTape_eq] + +end MinUncutGames.Foundations.PCP.PoweringFieldPlan + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/PoweringRowHeaderSemantics.lean b/lean/OAI/Computability/MinUncut/PCP/PoweringRowHeaderSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..4d1b85e7e4c825826c07f0e1c7c6e94164eda4f0 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/PoweringRowHeaderSemantics.lean @@ -0,0 +1,80 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.PoweringOpinionTables + +namespace OAI + +section +namespace MinUncutGames.Foundations.PCP.PoweringRowHeaderSemantics + +open PoweringWalks PoweringEnumeration +open MinUncutGames.Foundations.Complexity + +variable {vertices d : Nat} + +def blockSize (d n : Nat) : Nat := 2 * d ^ (n + 1) + +def reverseOffset (d n : Nat) (ports : Fin (n + 1) → Fin d) (direction : Bool) : Nat := + 2 * (wordEquiv d (n + 1) ports).val + (if direction then 0 else 1) + +def reverseValue (d n : Nat) (vertex : Fin vertices) + (ports : Fin (n + 1) → Fin d) (direction : Bool) : Nat := + blockSize d n * vertex.val + reverseOffset d n ports direction + +def tailVertex (input : PortTables.Table vertices d) (n : Nat) (vertex : Fin vertices) + (ports : Fin (n + 1) → Fin d) (direction : Bool) : Fin vertices := + if direction then wordEnd (PortTables.portGraph input) (n + 1) vertex ports else vertex + +def headerWords (input : PortTables.Table vertices d) (n : Nat) (vertex : Fin vertices) + (ports : Fin (n + 1) → Fin d) (direction : Bool) : List Nat := + [(tailVertex input n vertex ports direction).val, reverseValue d n vertex ports direction] + +theorem table_tail (input : PortTables.Table vertices d) (n : Nat) (vertex : Fin vertices) + (ports : Fin (n + 1) → Fin d) (direction : Bool) : + (PoweringTables.table input n).rows[encodeDart vertices d n (direction, vertex, ports)].tail = + tailVertex input n vertex ports direction := by + change (GenericGraphTables.semantics (PoweringTables.table input n)).tail + (encodeDart vertices d n (direction, vertex, ports)) = _ + rw [PoweringTables.semantics_table] + change (PoweringTables.mathematicalGraph input n).tail + ((dartEquiv vertices d n).symm (dartEquiv vertices d n (direction, vertex, ports))) = _ + rw [Equiv.symm_apply_apply] + rfl + +theorem table_reverseValue (input : PortTables.Table vertices d) (n : Nat) + (vertex : Fin vertices) (ports : Fin (n + 1) → Fin d) (direction : Bool) : + (PoweringTables.table input n).rows[encodeDart vertices d n + (direction, vertex, ports)].reverseIndex.val = reverseValue d n vertex ports direction := by + change (GenericGraphTables.reverseAt (PoweringTables.table input n).rows + (encodeDart vertices d n (direction, vertex, ports))).val = _ + rw [PoweringTables.table_reverse, encodeDart, dartEquiv_val] + cases direction <;> + simp [reverseValue, blockSize, reverseOffset, orientationEquiv, Nat.add_assoc] <;> decide + +theorem headerWords_eq (input : PortTables.Table vertices d) (n : Nat) (vertex : Fin vertices) + (ports : Fin (n + 1) → Fin d) (direction : Bool) : + headerWords input n vertex ports direction = + [(PoweringTables.table input n).rows[encodeDart vertices d n + (direction, vertex, ports)].tail.val, + (PoweringTables.table input n).rows[encodeDart vertices d n + (direction, vertex, ports)].reverseIndex.val] := by + rw [table_tail, table_reverseValue] + rfl + +theorem header_relation_bits (input : PortTables.Table vertices d) (n : Nat) + (vertex : Fin vertices) (ports : Fin (n + 1) → Fin d) (direction : Bool) + (suffix : List Bool) : + encodeWords (headerWords input n vertex ports direction) ++ + (encodeWords (GenericGraphTables.relationWords + (PoweringTables.table input n).rows[encodeDart vertices d n + (direction, vertex, ports)].relation) ++ suffix) = + encodeWords (GenericGraphTables.rowWords + (PoweringTables.table input n).rows[encodeDart vertices d n + (direction, vertex, ports)]) ++ suffix := by + rw [headerWords_eq, ← List.append_assoc, ← encodeWords_append] + rfl + +end MinUncutGames.Foundations.PCP.PoweringRowHeaderSemantics + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/PoweringTableLayout.lean b/lean/OAI/Computability/MinUncut/PCP/PoweringTableLayout.lean new file mode 100644 index 0000000000000000000000000000000000000000..6cf0561c6c6318ac67a0707014704690744c1347 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/PoweringTableLayout.lean @@ -0,0 +1,147 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.PoweringOpinionTables + +namespace OAI + +section +namespace MinUncutGames.Foundations.PCP.PoweringTableLayout + +open MinUncutGames.Foundations.Complexity +open PoweringTables PoweringEnumeration + +def blockSize (d n : Nat) : Nat := 2 * d ^ (n + 1) + +theorem dartCount_eq_vertex_blocks (vertices d n : Nat) : + dartCount vertices d n = vertices * blockSize d n := by + simp only [blockSize] + unfold dartCount + ac_rfl + +def blockIndex {vertices : Nat} (d n : Nat) (v : Fin vertices) + (j : Fin (blockSize d n)) : Fin (dartCount vertices d n) := + Fin.cast (dartCount_eq_vertex_blocks vertices d n).symm + (finProdFinEquiv (v, j)) + +@[simp] theorem blockIndex_val {vertices : Nat} (d n : Nat) (v : Fin vertices) + (j : Fin (blockSize d n)) : + (blockIndex d n v j).val = blockSize d n * v.val + j.val := by + change j.val + blockSize d n * v.val = blockSize d n * v.val + j.val + exact Nat.add_comm _ _ + +theorem blockIndex_eq_encodeDart {vertices : Nat} (d n : Nat) (v : Fin vertices) + (p : Fin (n + 1) → Fin d) (direction : Bool) : + blockIndex d n v (dartBlockEquiv d n (p, direction)) = + encodeDart vertices d n (direction, (v, p)) := by + apply Fin.ext + erw [blockIndex_val] + +def vertexRows {vertices d : Nat} (input : PortTables.Table vertices d) (n : Nat) + (v : Fin vertices) : + List (GenericGraphTables.DartRow (labelCount d n) vertices (dartCount vertices d n)) := + List.ofFn (fun j : Fin (blockSize d n) => (table input n).rows[blockIndex d n v j]) + +def vertexRowWords {vertices d : Nat} (input : PortTables.Table vertices d) (n : Nat) + (v : Fin vertices) : List Nat := + (vertexRows input n v).flatMap GenericGraphTables.rowWords + +def vertexRowBits {vertices d : Nat} (input : PortTables.Table vertices d) (n : Nat) + (v : Fin vertices) : List Bool := + encodeWords (vertexRowWords input n v) + +@[simp] theorem vertexRows_length {vertices d : Nat} + (input : PortTables.Table vertices d) (n : Nat) (v : Fin vertices) : + (vertexRows input n v).length = blockSize d n := by + simp only [vertexRows] + exact List.length_ofFn + +private theorem vector_toList_ofFn {α : Type*} {m : Nat} (rows : Vector α m) : + rows.toList = List.ofFn (fun i : Fin m => rows[i]) := by + apply List.ext_getElem + · simp + · intro i hi₁ hi₂ + simp + +private theorem vector_blocks {α : Type*} {m vertices width : Nat} + (sameCount : m = vertices * width) (rows : Vector α m) : + rows.toList = (List.finRange vertices).flatMap (fun v => + List.ofFn (fun j : Fin width => + rows[Fin.cast sameCount.symm (finProdFinEquiv (v, j))])) := by + have atIndex (v : Fin vertices) (j : Fin width) + (h : v.val * width + j.val < vertices * width) : + (⟨v.val * width + j.val, h⟩ : Fin (vertices * width)) = + finProdFinEquiv (v, j) := by + apply Fin.ext + simp [finProdFinEquiv, Nat.add_comm, Nat.mul_comm] + rw [vector_toList_ofFn rows, + List.ofFn_congr sameCount (fun i : Fin m => rows[i]), List.ofFn_mul] + simp only [atIndex, List.finRange, List.flatMap_def, List.map_ofFn] + rfl + +theorem rowList_eq_vertexRows {vertices d : Nat} (input : PortTables.Table vertices d) + (n : Nat) : + GenericGraphTables.rowList (table input n) = + (List.finRange vertices).flatMap (vertexRows input n) := by + exact vector_blocks (dartCount_eq_vertex_blocks vertices d n) (table input n).rows + +theorem outputWords_vertexRows {vertices d : Nat} (input : PortTables.Table vertices d) + (n : Nat) : + GenericGraphTables.tableWords (table input n) = + [vertices, dartCount vertices d n] ++ + (List.finRange vertices).flatMap (vertexRowWords input n) := by + change [vertices, dartCount vertices d n] ++ + (GenericGraphTables.rowList (table input n)).flatMap GenericGraphTables.rowWords = _ + rw [rowList_eq_vertexRows] + erw [List.flatMap_assoc] + rfl + +theorem encodeWords_flatMap {α : Type*} (items : List α) + (words : α → List Nat) : + encodeWords (items.flatMap words) = + items.flatMap (fun item => encodeWords (words item)) := by + induction items with + | nil => rfl + | cons item rest ih => simp only [List.flatMap_cons, encodeWords_append, ih] + +theorem outputBits_vertexRows {vertices d : Nat} (input : PortTables.Table vertices d) + (n : Nat) : + outputBits input n = encodeWords [vertices, dartCount vertices d n] ++ + (List.finRange vertices).flatMap (vertexRowBits input n) := by + unfold outputBits GenericGraphTables.tableBits + rw [outputWords_vertexRows, encodeWords_append, encodeWords_flatMap] + rfl + +theorem vertexRowWords_length {vertices d : Nat} (input : PortTables.Table vertices d) + (n : Nat) (v : Fin vertices) : + (vertexRowWords input n v).length = + (labelCount d n * labelCount d n + 2) * blockSize d n := by + unfold vertexRowWords + rw [GenericGraphTables.rowsWords_length, vertexRows_length] + +theorem vertexRowBits_length_ge {vertices d : Nat} (input : PortTables.Table vertices d) + (n : Nat) (v : Fin vertices) : + (labelCount d n * labelCount d n + 2) * blockSize d n ≤ + (vertexRowBits input n v).length := by + unfold vertexRowBits + rw [encodeWords_length, vertexRowWords_length] + omega + +theorem vertexRowBits_length_le {vertices d : Nat} (input : PortTables.Table vertices d) + (n : Nat) (v : Fin vertices) : + (vertexRowBits input n v).length ≤ + blockSize d n * + (vertices + dartCount vertices d n + 2 * (labelCount d n * labelCount d n)) := by + have h := GenericGraphTables.rowsBits_length_le (vertexRows input n v) + rw [vertexRows_length] at h + exact h + +theorem outputHeader_length (vertices d n : Nat) : + (encodeWords [vertices, dartCount vertices d n]).length = + vertices + dartCount vertices d n + 2 := by + simp only [encodeWords, List.length_append, encodeWord_length, List.length_nil] + omega + +end MinUncutGames.Foundations.PCP.PoweringTableLayout + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/PoweringTableSemantics.lean b/lean/OAI/Computability/MinUncut/PCP/PoweringTableSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..4a5fe33fdf359c768d5b872d4656ac2eddd324a0 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/PoweringTableSemantics.lean @@ -0,0 +1,559 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.PoweringOpinionTables + +namespace OAI + +namespace MinUncutGames.Foundations.PCP.PoweringTableSemantics + +open PoweringWalks PoweringLabels PoweringAddresses PoweringEnumeration PoweringTables + +abbrev RawLabeling (vertices d n : Nat) := + Fin vertices → PaddedLabel (Fin d) (n + 1) (Fin 64) + +abbrev EncodedLabeling (vertices d n : Nat) := + Fin vertices → Fin (labelCount d n) + +def encodeLabeling {vertices : Nat} (d n : Nat) (labels : RawLabeling vertices d n) : + EncodedLabeling vertices d n := + fun v => encodeLabel d (n + 1) 64 (labels v) + +def decodeLabeling {vertices : Nat} (d n : Nat) (labels : EncodedLabeling vertices d n) : + RawLabeling vertices d n := + fun v => decodeLabel d (n + 1) 64 (labels v) + +@[simp] theorem decodeLabeling_encodeLabeling {vertices : Nat} (d n : Nat) + (labels : RawLabeling vertices d n) : + decodeLabeling d n (encodeLabeling d n labels) = labels := by + funext v + exact decodeLabel_encodeLabel d (n + 1) 64 (labels v) + +@[simp] theorem encodeLabeling_decodeLabeling {vertices : Nat} (d n : Nat) + (labels : EncodedLabeling vertices d n) : + encodeLabeling d n (decodeLabeling d n labels) = labels := by + funext v + exact encodeLabel_decodeLabel d (n + 1) 64 (labels v) + +theorem edgeSatisfied_encoded {vertices d : Nat} (input : PortTables.Table vertices d) + (n : Nat) (labels : RawLabeling vertices d n) + (e : PoweringTest.Dart (Fin vertices) (Fin d) n) : + (GenericGraphTables.semantics (table input n)).edgeSatisfied + (encodeLabeling d n labels) (encodeDart vertices d n e) = + (mathematicalGraph input n).edgeSatisfied labels e := by + rw [semantics_table] + unfold encodeLabeling encodeLabel encodeDart + simpa using! + GenericGraphTables.enumeratedGraph_edgeSatisfied (mathematicalGraph input n) + (Equiv.refl _) (dartEquiv vertices d n) (paddedLabelEquiv d (n + 1) 64) labels e + +theorem edgeSatisfied_decoded {vertices d : Nat} (input : PortTables.Table vertices d) + (n : Nat) (labels : EncodedLabeling vertices d n) (i : Fin (dartCount vertices d n)) : + (GenericGraphTables.semantics (table input n)).edgeSatisfied labels i = + (mathematicalGraph input n).edgeSatisfied (decodeLabeling d n labels) + (decodeDart vertices d n i) := by + have h := edgeSatisfied_encoded input n (decodeLabeling d n labels) (decodeDart vertices d n i) + erw [encodeLabeling_decodeLabeling d n labels, + encodeDart_decodeDart vertices d n i] at h + exact h + +theorem edgeSatisfied_eq_path {vertices d : Nat} (input : PortTables.Table vertices d) + (n : Nat) (labels : EncodedLabeling vertices d n) (direction : Bool) + (w : Walk (Fin vertices) (Fin d) (n + 1)) : + (GenericGraphTables.semantics (table input n)).edgeSatisfied labels + (encodeDart vertices d n (direction, w)) = + PoweringTest.pathAccepts (PortTables.portGraph input) (PortTables.accepts input) n + (finitePortSelector (PortTables.portGraph input) (n + 1)) w + (decodeLabeling d n labels w.1) + (decodeLabeling d n labels (endpoint (PortTables.portGraph input) w)) := by + rw [edgeSatisfied_decoded input n labels (encodeDart vertices d n (direction, w)), + decodeDart_encodeDart vertices d n (direction, w)] + exact PoweringTest.poweredGraph_edgeSatisfied (PortTables.portGraph input) + (PortTables.accepts input) n (finitePortSelector (PortTables.portGraph input) (n + 1)) + (decodeLabeling d n labels) direction w + +theorem rejectionCount_encoded {vertices d : Nat} (input : PortTables.Table vertices d) + (n : Nat) (labels : RawLabeling vertices d n) : + (GenericGraphTables.semantics (table input n)).rejectionCount + (encodeLabeling d n labels) = (mathematicalGraph input n).rejectionCount labels := by + rw [semantics_table] + unfold encodeLabeling encodeLabel + simpa using! + GenericGraphTables.enumeratedGraph_rejectionCount (mathematicalGraph input n) + (Equiv.refl _) (dartEquiv vertices d n) (paddedLabelEquiv d (n + 1) 64) labels + +theorem rejectionCount_decoded {vertices d : Nat} (input : PortTables.Table vertices d) + (n : Nat) (labels : EncodedLabeling vertices d n) : + (GenericGraphTables.semantics (table input n)).rejectionCount labels = + (mathematicalGraph input n).rejectionCount (decodeLabeling d n labels) := by + have h := rejectionCount_encoded input n (decodeLabeling d n labels) + erw [encodeLabeling_decodeLabeling d n labels] at h + exact h + +theorem card_darts_eq_table {vertices d : Nat} (input : PortTables.Table vertices d) + (n : Nat) : + Fintype.card (PoweringTest.Dart (Fin vertices) (Fin d) n) = (table input n).darts := by + change Fintype.card (PoweringTest.Dart (Fin vertices) (Fin d) n) = + 2 * vertices * d ^ (n + 1) + simpa only [Fintype.card_fin] using Fintype.card_congr (dartEquiv vertices d n) + +theorem satisfiable_iff {vertices d : Nat} (input : PortTables.Table vertices d) (n : Nat) : + (GenericGraphTables.semantics (table input n)).Satisfiable ↔ + (mathematicalGraph input n).Satisfiable := by + constructor + · rintro ⟨labels, satisfies⟩ + refine ⟨decodeLabeling d n labels, ?_⟩ + intro e + have h := edgeSatisfied_encoded input n (decodeLabeling d n labels) e + erw [encodeLabeling_decodeLabeling d n labels] at h + exact h.symm.trans (satisfies (encodeDart vertices d n e)) + · rintro ⟨labels, satisfies⟩ + refine ⟨encodeLabeling d n labels, ?_⟩ + intro i + have h := edgeSatisfied_encoded input n labels (decodeDart vertices d n i) + rw [encodeDart_decodeDart vertices d n i] at h + exact h.trans (satisfies (decodeDart vertices d n i)) + +theorem preserves_satisfiability {vertices d : Nat} (input : PortTables.Table vertices d) + (n : Nat) (h : (PortTables.baseGraph input).Satisfiable) : + (GenericGraphTables.semantics (table input n)).Satisfiable := by + apply (satisfiable_iff input n).mpr + exact PoweringTest.preserves_satisfiability (PortTables.portGraph input) + (PortTables.accepts input) (PortTables.accepts_rotation input) n + (finitePortSelector (PortTables.portGraph input) (n + 1)) h + +theorem path_rejection_mean_eq_table_fraction {vertices d : Nat} + (input : PortTables.Table vertices d) (n : Nat) (labels : EncodedLabeling vertices d n) : + SpectralReturn.mean (fun w : Walk (Fin vertices) (Fin d) (n + 1) => + PoweringMoment.bit + (PoweringTest.pathAccepts (PortTables.portGraph input) (PortTables.accepts input) n + (finitePortSelector (PortTables.portGraph input) (n + 1)) w + (decodeLabeling d n labels w.1) + (decodeLabeling d n labels (endpoint (PortTables.portGraph input) w)) = false)) = + ((GenericGraphTables.semantics (table input n)).rejectionCount labels : ℝ) / + ((table input n).darts : ℝ) := by + rw [rejectionCount_decoded input n labels, ← card_darts_eq_table input n] + exact PoweringCounting.path_rejection_mean_eq_count (PortTables.portGraph input) + (PortTables.accepts input) n (finitePortSelector (PortTables.portGraph input) (n + 1)) + (decodeLabeling d n labels) + +theorem uniform_count_gap_iff {vertices d : Nat} (input : PortTables.Table vertices d) + (n : Nat) (epsilon : ℝ) : + (∀ labels : EncodedLabeling vertices d n, + epsilon * ((table input n).darts : ℝ) ≤ + ((GenericGraphTables.semantics (table input n)).rejectionCount labels : ℝ)) ↔ + (∀ labels : RawLabeling vertices d n, + epsilon * (Fintype.card (PoweringTest.Dart (Fin vertices) (Fin d) n) : ℝ) ≤ + ((mathematicalGraph input n).rejectionCount labels : ℝ)) := by + constructor + · intro h labels + have hlabels := h (encodeLabeling d n labels) + erw [rejectionCount_encoded input n labels, ← card_darts_eq_table input n] at hlabels + exact hlabels + · intro h labels + rw [rejectionCount_decoded input n labels] + have hlabels := h (decodeLabeling d n labels) + rw [card_darts_eq_table input n] at hlabels + exact hlabels + +theorem uniform_count_gap {vertices d : Nat} (input : PortTables.Table vertices d) + (n : Nat) (epsilon : ℝ) + (hgap : ∀ labels : RawLabeling vertices d n, + epsilon * (Fintype.card (PoweringTest.Dart (Fin vertices) (Fin d) n) : ℝ) ≤ + ((mathematicalGraph input n).rejectionCount labels : ℝ)) : + ∀ labels : EncodedLabeling vertices d n, + epsilon * ((table input n).darts : ℝ) ≤ + ((GenericGraphTables.semantics (table input n)).rejectionCount labels : ℝ) := + (uniform_count_gap_iff input n epsilon).mpr hgap + +end MinUncutGames.Foundations.PCP.PoweringTableSemantics + +namespace MinUncutGames.Foundations.PCP.QueryIncidence + +structure Verifier (E X : Type*) (q : Nat) where + query : E → Fin q → X + accepts : E → (Fin q → Bool) → Bool + +abbrev Label (q : Nat) := Fin q → Bool +abbrev Vertex (E X : Type*) := E ⊕ X +abbrev Dart (E : Type*) (q : Nat) := (E × Fin q) × Bool + +variable {E X : Type*} {q : Nat} + +def response (T : Verifier E X q) (assignment : X → Bool) (event : E) : Label q := + fun i => assignment (T.query event i) + +def zeroSlot (positive : 0 < q) : Fin q := ⟨0, positive⟩ + +def decodeRight (positive : 0 < q) (label : Label q) : Bool := label (zeroSlot positive) + +def encodeRight (bit : Bool) : Label q := fun _ => bit + +@[simp] theorem decode_encodeRight (positive : 0 < q) (bit : Bool) : + decodeRight positive (encodeRight bit) = bit := rfl + +def canonicalSlot [DecidableEq X] (T : Verifier E X q) (event : E) (i : Fin q) : Fin q := + Fin.find (fun j => T.query event j = T.query event i) ⟨i, rfl⟩ + +theorem canonicalSlot_query [DecidableEq X] (T : Verifier E X q) (event : E) (i : Fin q) : + T.query event (canonicalSlot T event i) = T.query event i := + Fin.find_spec (p := fun j => T.query event j = T.query event i) ⟨i, rfl⟩ + +def RepeatedConsistent (T : Verifier E X q) (event : E) (label : Label q) : Prop := + ∀ i j, T.query event i = T.query event j → label i = label j + +instance repeatedConsistentDecidable [DecidableEq X] + (T : Verifier E X q) (event : E) (label : Label q) : + Decidable (RepeatedConsistent T event label) := by + unfold RepeatedConsistent + infer_instance + +def LeftValid (T : Verifier E X q) (event : E) (label : Label q) : Prop := + T.accepts event label = true ∧ RepeatedConsistent T event label + +instance leftValidDecidable [DecidableEq X] + (T : Verifier E X q) (event : E) (label : Label q) : + Decidable (LeftValid T event label) := by + unfold LeftValid + infer_instance + +def incidenceAccept [DecidableEq X] (T : Verifier E X q) (positive : 0 < q) + (event : E) (slot : Fin q) (left right : Label q) : Bool := + decide (LeftValid T event left) && + decide (left (canonicalSlot T event slot) = decodeRight positive right) + +def reverse : Dart E q → Dart E q := fun d => (d.1, !d.2) + +theorem reverse_involutive : Function.Involutive (reverse : Dart E q → Dart E q) := by + rintro ⟨⟨event, slot⟩, orientation⟩ + cases orientation <;> rfl + +def reverseEquiv : Dart E q ≃ Dart E q where + toFun := reverse + invFun := reverse + left_inv := reverse_involutive + right_inv := reverse_involutive + +def tail (T : Verifier E X q) : Dart E q → Vertex E X + | ((event, _), false) => .inl event + | ((event, slot), true) => .inr (T.query event slot) + +def predicate [DecidableEq X] (T : Verifier E X q) (positive : 0 < q) : + Dart E q → Label q → Label q → Bool + | ((event, slot), false), a, b => incidenceAccept T positive event slot a b + | ((event, slot), true), a, b => incidenceAccept T positive event slot b a + +def graph [DecidableEq X] (T : Verifier E X q) (positive : 0 < q) : + ConstraintGraph (Vertex E X) (Dart E q) (Label q) where + reverse := reverseEquiv + reverse_involutive := reverse_involutive + tail := tail T + accepts := predicate T positive + reverse_accepts := by + rintro ⟨⟨event, slot⟩, orientation⟩ a b + cases orientation <;> rfl + +theorem edgeSatisfied_eq_incidence [DecidableEq X] (T : Verifier E X q) + (positive : 0 < q) (labeling : Vertex E X → Label q) + (event : E) (slot : Fin q) (orientation : Bool) : + (graph T positive).edgeSatisfied labeling ((event, slot), orientation) = + incidenceAccept T positive event slot (labeling (.inl event)) + (labeling (.inr (T.query event slot))) := by + cases orientation <;> rfl + +def honestLabeling (T : Verifier E X q) (assignment : X → Bool) : Vertex E X → Label q + | .inl event => response T assignment event + | .inr address => encodeRight (assignment address) + +theorem honest_leftValid (T : Verifier E X q) (assignment : X → Bool) (event : E) + (accepted : T.accepts event (response T assignment event) = true) : + LeftValid T event (response T assignment event) := by + refine ⟨accepted, ?_⟩ + intro i j hij + exact congrArg assignment hij + +theorem honest_incidence [DecidableEq X] (T : Verifier E X q) (positive : 0 < q) + (assignment : X → Bool) (event : E) + (accepted : T.accepts event (response T assignment event) = true) (slot : Fin q) : + incidenceAccept T positive event slot + (honestLabeling T assignment (.inl event)) + (honestLabeling T assignment (.inr (T.query event slot))) = true := by + simp only [incidenceAccept, Bool.and_eq_true, honestLabeling, + decode_encodeRight] + refine ⟨_root_.decide_eq_true (honest_leftValid T assignment event accepted), ?_⟩ + exact _root_.decide_eq_true (congrArg assignment (canonicalSlot_query T event slot)) + +theorem perfect_completeness [DecidableEq X] (T : Verifier E X q) (positive : 0 < q) + (assignment : X → Bool) + (accepted : ∀ event, T.accepts event (response T assignment event) = true) : + ∀ dart, (graph T positive).edgeSatisfied (honestLabeling T assignment) dart = true := by + rintro ⟨⟨event, slot⟩, orientation⟩ + rw [edgeSatisfied_eq_incidence] + exact honest_incidence T positive assignment event (accepted event) slot + +theorem satisfiable_of_verifier_satisfiable [DecidableEq X] (T : Verifier E X q) + (positive : 0 < q) + (sat : ∃ assignment : X → Bool, + ∀ event, T.accepts event (response T assignment event) = true) : + (graph T positive).Satisfiable := by + obtain ⟨assignment, h⟩ := sat + exact ⟨honestLabeling T assignment, perfect_completeness T positive assignment h⟩ + +def decodedAssignment (positive : 0 < q) (labeling : Vertex E X → Label q) : X → Bool := + fun address => decodeRight positive (labeling (.inr address)) + +theorem incidenceAccept_true [DecidableEq X] (T : Verifier E X q) (positive : 0 < q) + (event : E) (slot : Fin q) (left right : Label q) + (accepted : incidenceAccept T positive event slot left right = true) : + T.accepts event left = true ∧ RepeatedConsistent T event left ∧ + left (canonicalSlot T event slot) = decodeRight positive right := by + simp only [incidenceAccept, Bool.and_eq_true] at accepted + have hvalid : LeftValid T event left := _root_.of_decide_eq_true accepted.1 + exact ⟨hvalid.1, hvalid.2, _root_.of_decide_eq_true accepted.2⟩ + +theorem all_incidences_imply_event [DecidableEq X] (T : Verifier E X q) + (positive : 0 < q) (labeling : Vertex E X → Label q) (event : E) + (accepted : ∀ slot, incidenceAccept T positive event slot (labeling (.inl event)) + (labeling (.inr (T.query event slot))) = true) : + T.accepts event (response T (decodedAssignment positive labeling) event) = true := by + have first := incidenceAccept_true T positive event (zeroSlot positive) _ _ + (accepted (zeroSlot positive)) + have labels_equal : labeling (.inl event) = response T (decodedAssignment positive labeling) event := by + funext slot + have info := incidenceAccept_true T positive event slot _ _ (accepted slot) + exact (first.2.1 slot (canonicalSlot T event slot) + (canonicalSlot_query T event slot).symm).trans info.2.2 + rw [← labels_equal] + exact first.1 + +theorem rejected_event_forces_slot [DecidableEq X] (T : Verifier E X q) + (positive : 0 < q) (labeling : Vertex E X → Label q) (event : E) + (rejected : T.accepts event (response T (decodedAssignment positive labeling) event) = false) : + ∃ slot, incidenceAccept T positive event slot (labeling (.inl event)) + (labeling (.inr (T.query event slot))) = false := by + classical + by_contra none + have all : ∀ slot, incidenceAccept T positive event slot (labeling (.inl event)) + (labeling (.inr (T.query event slot))) = true := by + intro slot + cases h : incidenceAccept T positive event slot (labeling (.inl event)) + (labeling (.inr (T.query event slot))) with + | false => exact False.elim (none ⟨slot, h⟩) + | true => rfl + have h := all_incidences_imply_event T positive labeling event all + rw [rejected] at h + cases h + +def rejectedEvents [Fintype E] (T : Verifier E X q) (assignment : X → Bool) : Finset E := + Finset.univ.filter (fun event => T.accepts event (response T assignment event) = false) + +def verifierRejectionCount [Fintype E] (T : Verifier E X q) (assignment : X → Bool) : Nat := + (rejectedEvents T assignment).card + +theorem rejection_count_bound [Fintype E] [DecidableEq X] + (T : Verifier E X q) (positive : 0 < q) (labeling : Vertex E X → Label q) : + 2 * verifierRejectionCount T (decodedAssignment positive labeling) ≤ + (graph T positive).rejectionCount labeling := by + classical + let failed := rejectedEvents T (decodedAssignment positive labeling) + have witnesses : ∀ event, event ∈ failed → + ∃ slot, incidenceAccept T positive event slot (labeling (.inl event)) + (labeling (.inr (T.query event slot))) = false := by + intro event he + apply rejected_event_forces_slot T positive labeling event + simpa [failed, rejectedEvents] using he + let chosen := fun event he => Classical.choose (witnesses event he) + let inject : (failed.product (Finset.univ : Finset Bool)) → + (graph T positive).rejectedDarts labeling := fun p => + ⟨((p.val.1, chosen p.val.1 (Finset.mem_product.mp p.property).1), p.val.2), by + apply (ConstraintGraph.mem_rejectedDarts _ _ _).mpr + rw [edgeSatisfied_eq_incidence] + exact Classical.choose_spec (witnesses p.val.1 (Finset.mem_product.mp p.property).1)⟩ + have injective : Function.Injective inject := by + intro a b h + apply Subtype.ext + apply Prod.ext + · exact congrArg (fun d => d.val.1.1) h + · exact congrArg (fun d => d.val.2) h + have bound := Finset.card_le_card_of_injective injective + simpa [failed, verifierRejectionCount, ConstraintGraph.rejectionCount, + Finset.card_product, Nat.mul_comm] using bound + +@[simp] theorem card_label (q : Nat) : Fintype.card (Label q) = 2 ^ q := by + simp [Label] + +@[simp] theorem card_vertex [Fintype E] [Fintype X] : + Fintype.card (Vertex E X) = Fintype.card E + Fintype.card X := by + simp [Vertex, Fintype.card_sum] + +@[simp] theorem card_dart [Fintype E] : + Fintype.card (Dart E q) = 2 * q * Fintype.card E := by + simp [Dart, Fintype.card_prod, Nat.mul_comm, Nat.mul_left_comm, Nat.mul_assoc] + +theorem gap_transfer [Fintype E] [DecidableEq X] (T : Verifier E X q) + (positive : 0 < q) (a b : Nat) + (sourceGap : ∀ assignment : X → Bool, + a * Fintype.card E ≤ b * verifierRejectionCount T assignment) + (labeling : Vertex E X → Label q) : + a * Fintype.card (Dart E q) ≤ (b * q) * (graph T positive).rejectionCount labeling := by + have source := Nat.mul_le_mul_left (2 * q) (sourceGap (decodedAssignment positive labeling)) + have incidences := Nat.mul_le_mul_left (b * q) (rejection_count_bound T positive labeling) + rw [card_dart] + calc + a * (2 * q * Fintype.card E) = (2 * q) * (a * Fintype.card E) := by ac_rfl + _ ≤ (2 * q) * (b * verifierRejectionCount T (decodedAssignment positive labeling)) := source + _ = (b * q) * (2 * verifierRejectionCount T (decodedAssignment positive labeling)) := by ac_rfl + _ ≤ (b * q) * (graph T positive).rejectionCount labeling := incidences + +theorem six_query_alphabet : Fintype.card (Label 6) = 64 := by + simp + +end MinUncutGames.Foundations.PCP.QueryIncidence + +noncomputable section + +namespace MinUncutGames.Foundations.PCP.CodeComposition + +open scoped BigOperators +open MinUncutGames.Foundations.Hastad + +def disagreement (a b : Bool) : ℝ := if a = b then 0 else 1 + +@[simp] theorem disagreement_self (a : Bool) : disagreement a a = 0 := by + simp [disagreement] + +theorem disagreement_nonnegative (a b : Bool) : 0 ≤ disagreement a b := by + cases a <;> cases b <;> norm_num [disagreement] + +theorem disagreement_le_one (a b : Bool) : disagreement a b ≤ 1 := by + cases a <;> cases b <;> norm_num [disagreement] + +theorem disagreement_comm (a b : Bool) : disagreement a b = disagreement b a := by + simp [disagreement, eq_comm] + +theorem disagreement_triangle (a b c : Bool) : + disagreement a c ≤ disagreement a b + disagreement b c := by + cases a <;> cases b <;> cases c <;> norm_num [disagreement] + +theorem disagreement_eq_sign (a b : Bool) : + disagreement a b = (1 - bitSign a * bitSign b) / 2 := by + cases a <;> cases b <;> norm_num [disagreement, bitSign] + +def relativeDistance {X : Type*} [Fintype X] (f g : X → Bool) : ℝ := + 𝔼 x, disagreement (f x) (g x) + +@[simp] theorem relativeDistance_self {X : Type*} [Fintype X] (f : X → Bool) : + relativeDistance f f = 0 := by + simp [relativeDistance] + +theorem relativeDistance_nonnegative {X : Type*} [Fintype X] (f g : X → Bool) : + 0 ≤ relativeDistance f g := + Finset.expect_nonneg (fun _ _ => disagreement_nonnegative _ _) + +theorem relativeDistance_comm {X : Type*} [Fintype X] (f g : X → Bool) : + relativeDistance f g = relativeDistance g f := by + simp only [relativeDistance, disagreement_comm] + +theorem relativeDistance_triangle {X : Type*} [Fintype X] (f g h : X → Bool) : + relativeDistance f h ≤ relativeDistance f g + relativeDistance g h := by + rw [relativeDistance, relativeDistance, relativeDistance, + ← Finset.expect_add_distrib] + exact Finset.expect_le_expect (fun _ _ => disagreement_triangle _ _ _) + +theorem relativeDistance_eq_sign {X : Type*} [Fintype X] [Nonempty X] + (f g : X → Bool) : + relativeDistance f g = (1 - 𝔼 x, bitSign (f x) * bitSign (g x)) / 2 := by + simp only [relativeDistance, disagreement_eq_sign] + rw [← Finset.expect_div, Finset.expect_sub_distrib] + simp + +def codeword {A : Type*} (a : A) : Cube A → Bool := fun x => x a + +private def singletonMask {A : Type*} [DecidableEq A] (a : A) : Cube A := + fun i => decide (i = a) + +private theorem walsh_singletonMask {A : Type*} [Fintype A] [DecidableEq A] + (a : A) (x : Cube A) : walsh (singletonMask a) x = bitSign (x a) := by + classical + unfold walsh singletonMask + rw [Finset.prod_eq_single a] + · simp + · intro b _ hba + simp [hba, bitSign] + · simp + +private theorem singletonMask_ne {A : Type*} [DecidableEq A] {a b : A} (hab : a ≠ b) : + singletonMask a ≠ singletonMask b := by + intro h + have he := congrFun h a + simp [singletonMask, hab] at he + +theorem codeword_distance {A : Type*} [Fintype A] [DecidableEq A] + {a b : A} (hab : a ≠ b) : + relativeDistance (codeword a) (codeword b) = 1 / 2 := by + rw [relativeDistance_eq_sign] + have horth := walsh_orthogonality (singletonMask a) (singletonMask b) + rw [ite_eq_right (singletonMask_ne hab)] at horth + simp_rw [walsh_singletonMask] at horth + change (1 - 𝔼 x : Cube A, bitSign (x a) * bitSign (x b)) / 2 = 1 / 2 + rw [horth] + norm_num + +theorem exists_nearest {A : Type*} [Fintype A] [DecidableEq A] [Nonempty A] + (f : Cube A → Bool) : + ∃ a : A, ∀ b : A, relativeDistance f (codeword a) ≤ relativeDistance f (codeword b) := by + classical + obtain ⟨a, _, ha⟩ := Finset.exists_min_image Finset.univ + (fun a : A => relativeDistance f (codeword a)) Finset.univ_nonempty + exact ⟨a, fun b => ha b (Finset.mem_univ b)⟩ + +def nearest {A : Type*} [Fintype A] [DecidableEq A] [Nonempty A] (f : Cube A → Bool) : A := + Classical.choose (exists_nearest f) + +theorem nearest_minimal {A : Type*} [Fintype A] [DecidableEq A] [Nonempty A] + (f : Cube A → Bool) (a : A) : + relativeDistance f (codeword (nearest f)) ≤ relativeDistance f (codeword a) := + Classical.choose_spec (exists_nearest f) a + +theorem distance_from_other_codeword {A : Type*} [Fintype A] [DecidableEq A] + [Nonempty A] (f : Cube A → Bool) {a : A} (ha : a ≠ nearest f) : + 1 / 4 ≤ relativeDistance f (codeword a) := by + have htri := relativeDistance_triangle (codeword (nearest f)) f (codeword a) + rw [codeword_distance (Ne.symm ha), relativeDistance_comm (codeword (nearest f)) f] at htri + have hmin := nearest_minimal f a + linarith + +def pairWord {X : Type*} (left right : X → Bool) : Bool × X → Bool := + fun p => if p.1 then right p.2 else left p.2 + +theorem pairWord_distance {X : Type*} [Fintype X] [Nonempty X] + (left right left' right' : X → Bool) : + relativeDistance (pairWord left right) (pairWord left' right') = + (relativeDistance left left' + relativeDistance right right') / 2 := by + classical + simp [relativeDistance, Fintype.expect_eq_sum_div_card, Fintype.card_prod, + Fintype.sum_prod_type, pairWord] + ring + +theorem rejected_pair_far {A : Type*} [Fintype A] [DecidableEq A] [Nonempty A] + (accepts : A → A → Bool) (left right : Cube A → Bool) + (hbad : accepts (nearest left) (nearest right) = false) + (a b : A) (hgood : accepts a b = true) : + 1 / 8 ≤ relativeDistance (pairWord left right) + (pairWord (codeword a) (codeword b)) := by + rw [pairWord_distance] + have hleft := relativeDistance_nonnegative left (codeword a) + have hright := relativeDistance_nonnegative right (codeword b) + by_cases ha : a = nearest left + · have hb : b ≠ nearest right := by + intro hb + rw [ha, hb, hbad] at hgood + cases hgood + have hsep := distance_from_other_codeword right hb + linarith + · have hsep := distance_from_other_codeword left ha + linarith + +end MinUncutGames.Foundations.PCP.CodeComposition + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/PreprocessingFamilyBridge.lean b/lean/OAI/Computability/MinUncut/PCP/PreprocessingFamilyBridge.lean new file mode 100644 index 0000000000000000000000000000000000000000..b11a1862394403a95eeeaab48b95403643063f18 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/PreprocessingFamilyBridge.lean @@ -0,0 +1,67 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.PreprocessingRegularTables +import OAI.Computability.MinUncut.PCP.ExpanderRowControl + +namespace OAI + +section +namespace MinUncutGames.Foundations.PCP.PreprocessingFamilyBridge + +open PreprocessingCloudIndex PreprocessingRegularTables ExpanderTableWords +open MinUncutGames.Foundations.Complexity (encodeWords) + +theorem rotationWords_resizeTable {n m q : Nat} (h : n = m) + (table : ExpanderTables.Table n q) : + rotationWords (resizeTable h table) = rotationWords table := by + cases h + rfl + +theorem familyRotor_eq_familyCloudTable (H : BaseTable) (t : GraphTables.Table) + (v : Fin t.vertices) (hk : 0 < cloudSize t v) : + encodeWords (rotationWords (ExpanderTables.family H + (PreprocessingLevels.boundedLevel (cloudSize t v)))) = + encodeWords (rotationWords (familyCloudTable H t v)) := by + unfold familyCloudTable + rw [dite_eq_right (Nat.ne_of_gt hk)] + erw [rotationWords_resizeTable] + rfl + +theorem cloudSize_pos_of_dart (t : GraphTables.Table) (e : Fin t.darts) : + 0 < cloudSize t t.rows[e].tail := by + have h := (oldCloudIndex t e).isLt + omega + +theorem padding_zero_of_cloudSize_zero (t : GraphTables.Table) (v : Fin t.vertices) + (hk : cloudSize t v = 0) : padding t v = 0 := by + simp only [padding, hk, PreprocessingLevels.cloudPaddedSize_zero, Nat.sub_zero] + +theorem cloudSize_pos_of_dummy (t : GraphTables.Table) (v : Fin t.vertices) + (j : Fin (padding t v)) : 0 < cloudSize t v := by + by_contra h + have hk := Nat.eq_zero_of_not_pos h + have hp := padding_zero_of_cloudSize_zero t v hk + have hj := j.isLt + omega + +theorem cloudSize_pos_of_paddedCloud (t : GraphTables.Table) (v : Fin t.vertices) + (x : PaddedCloud t (padding t) v) : 0 < cloudSize t v := by + by_contra h + have hk := Nat.eq_zero_of_not_pos h + have hp := padding_zero_of_cloudSize_zero t v hk + have hx := (paddedCloudRank t (padding t) v x).isLt + omega + +theorem familyCloudWords_of_zero (H : BaseTable) (t : GraphTables.Table) + (v : Fin t.vertices) (hk : cloudSize t v = 0) : + encodeWords (rotationWords (familyCloudTable H t v)) = [] := by + have hl : (rotationWords (familyCloudTable H t v)).length = 0 := by + rw [rotationWords_length, cloudSize_add_padding, hk, + PreprocessingLevels.cloudPaddedSize_zero, Nat.zero_mul] + rw [List.length_eq_zero_iff.mp hl] + rfl + +end MinUncutGames.Foundations.PCP.PreprocessingFamilyBridge + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/PreprocessingInternalRows.lean b/lean/OAI/Computability/MinUncut/PCP/PreprocessingInternalRows.lean new file mode 100644 index 0000000000000000000000000000000000000000..cb6551c542c9ebbec892f99fef24d5c9173744b7 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/PreprocessingInternalRows.lean @@ -0,0 +1,191 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.PreprocessingPaddingOffsets + +namespace OAI + +section +namespace MinUncutGames.Foundations.PCP.PreprocessingInternalRows + +open DegreeReplacement PreprocessingCloudIndex PreprocessingRegularTables + +variable (t : GraphTables.Table) (padding : Fin t.vertices → Nat) {q : Nat} +variable (tables : ∀ v, ExpanderTables.Table (cloudSize t v + padding v) q) + +def localStep (v : Fin t.vertices) (x : PaddedCloud t padding v) (p : Fin q) : + Fin (cloudSize t v + padding v) × Fin q := + ExpanderTables.lookup (tables v) (paddedCloudRank t padding v x, p) + +def destination (v : Fin t.vertices) (x : PaddedCloud t padding v) (p : Fin q) : + PaddedCloud t padding v := + paddedCloudSelect t padding v (localStep t padding tables v x p).1 + +def rowIndex (v : Fin t.vertices) (x : PaddedCloud t padding v) (p : Fin q) : + Fin (vertexCount t padding * (q + 1)) := + PortTables.rowIndex (vertexCount t padding) (q + 1) + (vertexOrder t padding x.val, portOrder q (.inl p)) + +def row (v : Fin t.vertices) (x : PaddedCloud t padding v) (p : Fin q) : + GraphTables.DartRow (vertexCount t padding) (vertexCount t padding * (q + 1)) := + (PortTables.flatRows (ofCloudTables t padding tables))[rowIndex t padding v x p] + +def equalityRelation : GraphTables.RelationTable := + GraphTables.relationOf (fun a b => decide (a = b)) + +@[simp] theorem equalityRelation_apply (a b : GraphTables.Label) : + GraphTables.relationAt equalityRelation a b = decide (a = b) := + GraphTables.relationAt_relationOf _ a b + +theorem cloud_rotation (v : Fin t.vertices) (x : PaddedCloud t padding v) (p : Fin q) : + (cloudGraphs t padding tables v).rot (x, p) = + (destination t padding tables v x p, (localStep t padding tables v x p).2) := by + have h := GraphTransport.reindex_rot (ExpanderTables.graph (tables v)) + (paddedCloudEquiv t padding v).symm (Equiv.refl _) + (paddedCloudRank t padding v x) p + simpa only [cloudGraphs, ExpanderTables.graph_rot, Equiv.refl_apply, + paddedCloudRank, paddedCloudSelect, Equiv.symm_apply_apply, destination, localStep] using h + +theorem source_rotation (v : Fin t.vertices) (x : PaddedCloud t padding v) (p : Fin q) : + (sourcePortGraph t padding tables).rot (x.val, .inl p) = + ((destination t padding tables v x p).val, + .inl (localStep t padding tables v x p).2) := by + rcases x with ⟨x, hx⟩ + subst v + exact congrArg + (fun z : PaddedCloud t padding + ((paddedGraph (GraphTables.semantics t) (fun v => Fin (padding v))).tail x) × Fin q => + (z.1.val, (Sum.inl z.2 : Fin q ⊕ Unit))) + (cloud_rotation t padding tables _ ⟨x, rfl⟩ p) + +theorem rotation_internal (v : Fin t.vertices) (x : PaddedCloud t padding v) (p : Fin q) : + PortTables.rotation (ofCloudTables t padding tables) + (vertexOrder t padding x.val, portOrder q (.inl p)) = + (vertexOrder t padding (destination t padding tables v x p).val, + portOrder q (.inl (localStep t padding tables v x p).2)) := by + rw [rotation_ofCloudTables, source_rotation t padding tables v x p] + +theorem reverseIndex_internal (v : Fin t.vertices) (x : PaddedCloud t padding v) (p : Fin q) : + ((ofCloudTables t padding tables).reverseIndex[rowIndex t padding v x p]).val = + (q + 1) * (vertexOrder t padding (destination t padding tables v x p).val).val + + (localStep t padding tables v x p).2.val := by + unfold rowIndex + rw [← PortTables.rowIndex_rotation, rotation_internal t padding tables v x p, + PortTables.rowIndex_val, portOrder_internal] + dsimp only + omega + +theorem relation_ext {r s : GraphTables.RelationTable} + (h : ∀ a b, GraphTables.relationAt r a b = GraphTables.relationAt s a b) : r = s := by + apply Vector.ext + intro i hi + simpa only [GraphTables.relationAt, Prod.eta, Equiv.apply_symm_apply, + Fin.getElem_fin] using + h (GraphTables.relationIndex.symm ⟨i, hi⟩).1 + (GraphTables.relationIndex.symm ⟨i, hi⟩).2 + +theorem relations_internal (v : Fin t.vertices) (x : PaddedCloud t padding v) (p : Fin q) : + (ofCloudTables t padding tables).relations[rowIndex t padding v x p] = equalityRelation := by + apply relation_ext + intro a b + rw [equalityRelation_apply] + exact accepts_internal t padding tables x.val p a b + +@[simp] theorem row_tail (v : Fin t.vertices) (x : PaddedCloud t padding v) (p : Fin q) : + (row t padding tables v x p).tail.val = (vertexOrder t padding x.val).val := by + simp only [row, rowIndex, PortTables.flatRows, Vector.getElem_ofFn, + Fin.getElem_fin, Fin.eta, Equiv.symm_apply_apply] + +theorem row_reverse (v : Fin t.vertices) (x : PaddedCloud t padding v) (p : Fin q) : + (row t padding tables v x p).reverseIndex.val = + (q + 1) * (vertexOrder t padding (destination t padding tables v x p).val).val + + (localStep t padding tables v x p).2.val := by + simpa only [row, PortTables.flatRows, Vector.getElem_ofFn, Fin.getElem_fin] using + reverseIndex_internal t padding tables v x p + +@[simp] theorem row_relation (v : Fin t.vertices) (x : PaddedCloud t padding v) (p : Fin q) : + (row t padding tables v x p).relation = equalityRelation := by + simpa only [row, PortTables.flatRows, Vector.getElem_ofFn, Fin.getElem_fin] using + relations_internal t padding tables v x p + +@[simp] theorem localStep_original (v : Fin t.vertices) (x : Cloud (GraphTables.semantics t) v) + (p : Fin q) : + localStep t padding tables v (paddedOld t padding v x) p = + ExpanderTables.lookup (tables v) (Fin.castAdd (padding v) (cloudRank t v x), p) := rfl + +@[simp] theorem localStep_dummy (v : Fin t.vertices) (j : Fin (padding v)) (p : Fin q) : + localStep t padding tables v (paddedNew t padding v j) p = + ExpanderTables.lookup (tables v) (Fin.natAdd (cloudSize t v) j, p) := rfl + +@[simp] theorem row_tail_original (v : Fin t.vertices) (x : Cloud (GraphTables.semantics t) v) + (p : Fin q) : + (row t padding tables v (paddedOld t padding v x) p).tail.val = x.val.val := by + rw [row_tail] + rfl + +@[simp] theorem row_tail_dummy (v : Fin t.vertices) (j : Fin (padding v)) (p : Fin q) : + (row t padding tables v (paddedNew t padding v j) p).tail.val = + t.darts + PreprocessingPaddingOffsets.offset padding v.val + j.val := by + rw [row_tail] + exact PreprocessingPaddingOffsets.vertexOrder_dummy_val t padding v j + +def selectedIndex (v : Fin t.vertices) (i : Fin (cloudSize t v + padding v)) : Nat := + if hi : i.val < cloudSize t v then + (cloudSelect t v ⟨i.val, hi⟩).val.val + else t.darts + PreprocessingPaddingOffsets.offset padding v.val + (i.val - cloudSize t v) + +theorem selectedIndex_eq (v : Fin t.vertices) (i : Fin (cloudSize t v + padding v)) : + (vertexOrder t padding (paddedCloudSelect t padding v i).val).val = + selectedIndex t padding v i := by + unfold selectedIndex + split + · rename_i hi + have he : i = Fin.castAdd (padding v) (⟨i.val, hi⟩ : Fin (cloudSize t v)) := Fin.ext rfl + refine (congrArg (fun j => + (vertexOrder t padding (paddedCloudSelect t padding v j).val).val) he).trans ?_ + rw [paddedCloudSelect_castAdd] + rfl + · rename_i hi + have hj : i.val - cloudSize t v < padding v := by have h := i.isLt; omega + have he : i = Fin.natAdd (cloudSize t v) (⟨i.val - cloudSize t v, hj⟩ : Fin (padding v)) := by + apply Fin.ext + dsimp only [Fin.val_natAdd] + omega + refine (congrArg (fun j => + (vertexOrder t padding (paddedCloudSelect t padding v j).val).val) he).trans ?_ + rw [paddedCloudSelect_natAdd] + change (vertexOrder t padding + (Sum.inr ⟨v, (⟨i.val - cloudSize t v, hj⟩ : Fin (padding v))⟩)).val = _ + exact PreprocessingPaddingOffsets.vertexOrder_dummy_val t padding v _ + +theorem selectedIndex_old (v : Fin t.vertices) (i : Fin (cloudSize t v + padding v)) + (hi : i.val < cloudSize t v) : + selectedIndex t padding v i = (cloudSelect t v ⟨i.val, hi⟩).val.val := by + simp only [selectedIndex, dite_eq_left hi] + +theorem selectedIndex_dummy (v : Fin t.vertices) (i : Fin (cloudSize t v + padding v)) + (hi : cloudSize t v ≤ i.val) : + selectedIndex t padding v i = + t.darts + PreprocessingPaddingOffsets.offset padding v.val + (i.val - cloudSize t v) := by + simp only [selectedIndex, dite_eq_right (Nat.not_lt_of_ge hi)] + +theorem row_reverse_selectedIndex (v : Fin t.vertices) (x : PaddedCloud t padding v) (p : Fin q) : + (row t padding tables v x p).reverseIndex.val = + (q + 1) * selectedIndex t padding v (localStep t padding tables v x p).1 + + (localStep t padding tables v x p).2.val := by + rw [row_reverse] + unfold destination + rw [selectedIndex_eq] + +theorem rowWords_eq (v : Fin t.vertices) (x : PaddedCloud t padding v) (p : Fin q) : + GraphTables.rowWords (row t padding tables v x p) = + [(vertexOrder t padding x.val).val, + (q + 1) * selectedIndex t padding v (localStep t padding tables v x p).1 + + (localStep t padding tables v x p).2.val] ++ + GraphTables.relationWords equalityRelation := by + unfold GraphTables.rowWords + rw [row_tail, row_reverse_selectedIndex, row_relation] + +end MinUncutGames.Foundations.PCP.PreprocessingInternalRows + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/PreprocessingLazyWords.lean b/lean/OAI/Computability/MinUncut/PCP/PreprocessingLazyWords.lean new file mode 100644 index 0000000000000000000000000000000000000000..58384b3f33d5c41ba1282a1dcb0f951cefc8b350 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/PreprocessingLazyWords.lean @@ -0,0 +1,183 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.GraphGap + +namespace OAI + +section +namespace MinUncutGames.Foundations.PCP.PreprocessingLazyWords + +open PortTables GraphTables PreprocessingOverlayTables +open MinUncutGames.Foundations.Complexity + +variable {n d : Nat} + +def row (table : PortTables.Table n d) (v : Fin n) (p : Fin d) : + DartRow n (n * d) := + ⟨v, table.reverseIndex[rowIndex n d (v, p)], table.relations[rowIndex n d (v, p)]⟩ + +def trueRelation : RelationTable := Vector.replicate 4096 true + +def stayRow (d : Nat) (v : Fin n) (p : Fin d) : DartRow n (n * (2 * d)) := + ⟨v, rowIndex n (2 * d) (v, lazyPorts d (false, p)), trueRelation⟩ + +def moveRow (table : PortTables.Table n d) (v : Fin n) (p : Fin d) : + DartRow n (n * (2 * d)) := + ⟨v, rowIndex n (2 * d) ((rotation table (v, p)).1, + lazyPorts d (true, (rotation table (v, p)).2)), + table.relations[rowIndex n d (v, p)]⟩ + +def reverseMap (d j : Nat) : Nat := 2 * d * (j / d) + d + j % d + +theorem relation_ext {r s : RelationTable} + (h : ∀ a b, relationAt r a b = relationAt s a b) : r = s := by + apply Vector.ext + intro i hi + simpa only [relationAt, Prod.eta, Equiv.apply_symm_apply, Fin.getElem_fin] using + h (relationIndex.symm ⟨i, hi⟩).1 (relationIndex.symm ⟨i, hi⟩).2 + +theorem row_lazy_stay (table : PortTables.Table n d) (v : Fin n) (p : Fin d) : + row (lazy table) v (lazyPorts d (false, p)) = stayRow d v p := by + have hr : (lazy table).reverseIndex[rowIndex n (2 * d) (v, lazyPorts d (false, p))] = + rowIndex n (2 * d) (v, lazyPorts d (false, p)) := by + rw [← rowIndex_rotation, lazy_rotation_false] + have hp : (lazy table).relations[rowIndex n (2 * d) (v, lazyPorts d (false, p))] = + trueRelation := by + apply relation_ext + intro a b + simpa only [PortTables.accepts, relationAt, trueRelation, Fin.getElem_fin, + Vector.getElem_replicate] using lazy_accepts_false table v p a b + exact congrArg₂ (DartRow.mk v) hr hp + +theorem row_lazy_move (table : PortTables.Table n d) (v : Fin n) (p : Fin d) : + row (lazy table) v (lazyPorts d (true, p)) = moveRow table v p := by + have hr : (lazy table).reverseIndex[rowIndex n (2 * d) (v, lazyPorts d (true, p))] = + rowIndex n (2 * d) ((rotation table (v, p)).1, + lazyPorts d (true, (rotation table (v, p)).2)) := by + rw [← rowIndex_rotation, lazy_rotation_true] + have hp : (lazy table).relations[rowIndex n (2 * d) (v, lazyPorts d (true, p))] = + table.relations[rowIndex n d (v, p)] := by + apply relation_ext + intro a b + exact lazy_accepts_true table v p a b + exact congrArg₂ (DartRow.mk v) hr hp + +theorem stayRow_reverse_val (v : Fin n) (p : Fin d) : + (stayRow d v p).reverseIndex.val = 2 * d * v.val + p.val := by + simp only [stayRow, rowIndex_val, lazyPorts_false_val] + omega + +theorem moveRow_reverse_val (table : PortTables.Table n d) (v : Fin n) (p : Fin d) : + (moveRow table v p).reverseIndex.val = + reverseMap d (row table v p).reverseIndex.val := by + simp only [moveRow, rowIndex_val, lazyPorts_true_val, reverseMap, row] + change (table.reverseIndex[rowIndex n d (v, p)]).val % d + d + + (2 * d) * ((table.reverseIndex[rowIndex n d (v, p)]).val / d) = _ + omega + +theorem relationWords_true : relationWords trueRelation = List.replicate 4096 1 := by + simp only [relationWords, trueRelation, Vector.toList_replicate, + List.map_replicate, bitWord, ite_true] + +theorem stayRow_words (v : Fin n) (p : Fin d) : + rowWords (stayRow d v p) = + [v.val, 2 * d * v.val + p.val] ++ List.replicate 4096 1 := by + rw [rowWords, stayRow_reverse_val] + exact congrArg (fun words => [v.val, 2 * d * v.val + p.val] ++ words) relationWords_true + +theorem moveRow_words (table : PortTables.Table n d) (v : Fin n) (p : Fin d) : + rowWords (moveRow table v p) = + [v.val, reverseMap d (row table v p).reverseIndex.val] ++ + relationWords (row table v p).relation := by + rw [rowWords, moveRow_reverse_val] + rfl + +theorem ofFn_rowIndex {α : Type*} (f : Fin (n * d) → α) : + List.ofFn f = (List.ofFn fun v : Fin n => + List.ofFn fun p : Fin d => f (rowIndex n d (v, p))).flatten := by + rw [List.ofFn_mul] + apply congrArg List.flatten + congr 1 + funext v + congr 1 + funext p + apply congrArg f + apply Fin.ext + simp only [rowIndex_val] + ac_rfl + +theorem flatRows_list (table : PortTables.Table n d) : + (flatRows table).toList = + (List.ofFn fun v : Fin n => List.ofFn (row table v)).flatten := by + rw [flatRows, Vector.toList_ofFn, ofFn_rowIndex] + simp only [Equiv.symm_apply_apply] + rfl + +theorem ofFn_lazyPorts {α : Type*} (f : Fin (2 * d) → α) : + List.ofFn f = List.ofFn (fun p => f (lazyPorts d (false, p))) ++ + List.ofFn (fun p => f (lazyPorts d (true, p))) := by + have hf (p : Fin d) : rowIndex 2 d (0, p) = lazyPorts d (false, p) := by + apply Fin.ext + simp only [rowIndex_val, Fin.val_zero, Nat.mul_zero, Nat.add_zero, lazyPorts_false_val] + have ht (p : Fin d) : rowIndex 2 d ((0 : Fin 1).succ, p) = lazyPorts d (true, p) := by + apply Fin.ext + simp only [rowIndex_val, Fin.val_succ, Fin.val_zero, Nat.zero_add, + Nat.mul_one, lazyPorts_true_val] + simpa only [List.ofFn_succ, List.ofFn_zero, List.flatten_cons, List.flatten_nil, + List.append_nil, hf, ht] using (ofFn_rowIndex (n := 2) (d := d) f) + +def vertexRows (table : PortTables.Table n d) (v : Fin n) : + List (DartRow n (n * (2 * d))) := + List.ofFn (stayRow d v) ++ List.ofFn (moveRow table v) + +theorem vertexRows_length (table : PortTables.Table n d) (v : Fin n) : + (vertexRows table v).length = 2 * d := by + simp only [vertexRows, List.length_append, List.length_ofFn] + omega + +theorem flatRows_lazy (table : PortTables.Table n d) : + (flatRows (lazy table)).toList = (List.ofFn (vertexRows table)).flatten := by + rw [flatRows_list] + apply congrArg List.flatten + congr 1 + funext v + rw [ofFn_lazyPorts] + simp only [row_lazy_stay, row_lazy_move] + rfl + +theorem vertexRows_words (table : PortTables.Table n d) (v : Fin n) : + (vertexRows table v).flatMap rowWords = + (List.ofFn fun p : Fin d => + [v.val, 2 * d * v.val + p.val] ++ List.replicate 4096 1).flatten ++ + (List.ofFn fun p : Fin d => + [v.val, reverseMap d (row table v p).reverseIndex.val] ++ + relationWords (row table v p).relation).flatten := by + have hs : rowWords ∘ stayRow d v = fun p : Fin d => + [v.val, 2 * d * v.val + p.val] ++ List.replicate 4096 1 := by + funext p + exact stayRow_words v p + have hm : rowWords ∘ moveRow table v = fun p : Fin d => + [v.val, reverseMap d (row table v p).reverseIndex.val] ++ + relationWords (row table v p).relation := by + funext p + exact moveRow_words table v p + simp only [vertexRows, List.flatMap_def, List.map_append, List.map_ofFn, + List.flatten_append] + rw [hs, hm] + +theorem tableWords_lazy (table : PortTables.Table n d) : + PortTables.tableWords (lazy table) = + [n, n * (2 * d)] ++ (List.ofFn (vertexRows table)).flatten.flatMap rowWords := by + rw [PortTables.tableWords_eq, flatRows_lazy] + +theorem tableBits_lazy (table : PortTables.Table n d) : + PortTables.tableBits (lazy table) = + encodeWords ([n, n * (2 * d)] ++ + (List.ofFn (vertexRows table)).flatten.flatMap rowWords) := by + change encodeWords (PortTables.tableWords (lazy table)) = _ + rw [tableWords_lazy] + +end MinUncutGames.Foundations.PCP.PreprocessingLazyWords + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/PreprocessingOverlayWords.lean b/lean/OAI/Computability/MinUncut/PCP/PreprocessingOverlayWords.lean new file mode 100644 index 0000000000000000000000000000000000000000..e929627a72590ff401b569e0d51b5bd331f71b1f --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/PreprocessingOverlayWords.lean @@ -0,0 +1,177 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.ExpanderRowControl +import OAI.Computability.MinUncut.PCP.PreprocessingLazyWords + +namespace OAI + +section +namespace MinUncutGames.Foundations.PCP.PreprocessingOverlayWords + +open PortTables GraphTables PreprocessingOverlayTables +open Complexity + +variable {n d e : Nat} + +abbrev row := @PreprocessingLazyWords.row +abbrev trueRelation := PreprocessingLazyWords.trueRelation + +def oldReverseMap (d e j : Nat) : Nat := (d + e) * (j / d) + j % d +def expanderReverseMap (d e j : Nat) : Nat := (d + e) * (j / e) + d + j % e + +def oldRow (G : PortTables.Table n d) (e : Nat) (v : Fin n) (p : Fin d) : + DartRow n (n * (d + e)) := + ⟨v, rowIndex n (d + e) ((rotation G (v, p)).1, + overlayPorts d e (.inl (rotation G (v, p)).2)), + G.relations[rowIndex n d (v, p)]⟩ + +def expanderRow (d : Nat) (H : ExpanderTables.Table n e) (v : Fin n) (p : Fin e) : + DartRow n (n * (d + e)) := + ⟨v, rowIndex n (d + e) ((ExpanderTables.lookup H (v, p)).1, + overlayPorts d e (.inr (ExpanderTables.lookup H (v, p)).2)), trueRelation⟩ + +private theorem relation_ext {r s : RelationTable} + (h : ∀ a b, relationAt r a b = relationAt s a b) : r = s := by + apply Vector.ext + intro i hi + simpa only [relationAt, Prod.eta, Equiv.apply_symm_apply, Fin.getElem_fin] using + h (relationIndex.symm ⟨i, hi⟩).1 (relationIndex.symm ⟨i, hi⟩).2 + +theorem row_overlay_old (G : PortTables.Table n d) (H : ExpanderTables.Table n e) + (v : Fin n) (p : Fin d) : + row (overlay G H) v (overlayPorts d e (.inl p)) = oldRow G e v p := by + have hr : (overlay G H).reverseIndex[rowIndex n (d + e) (v, overlayPorts d e (.inl p))] = + rowIndex n (d + e) ((rotation G (v, p)).1, + overlayPorts d e (.inl (rotation G (v, p)).2)) := by + rw [← rowIndex_rotation, overlay_rotation_old] + have hp : (overlay G H).relations[rowIndex n (d + e) (v, overlayPorts d e (.inl p))] = + G.relations[rowIndex n d (v, p)] := by + apply relation_ext + exact overlay_accepts_old G H v p + exact congrArg₂ (DartRow.mk v) hr hp + +theorem row_overlay_expander (G : PortTables.Table n d) (H : ExpanderTables.Table n e) + (v : Fin n) (p : Fin e) : + row (overlay G H) v (overlayPorts d e (.inr p)) = expanderRow d H v p := by + have hr : (overlay G H).reverseIndex[rowIndex n (d + e) (v, overlayPorts d e (.inr p))] = + rowIndex n (d + e) ((ExpanderTables.lookup H (v, p)).1, + overlayPorts d e (.inr (ExpanderTables.lookup H (v, p)).2)) := by + rw [← rowIndex_rotation, overlay_rotation_expander] + have hp : (overlay G H).relations[rowIndex n (d + e) (v, overlayPorts d e (.inr p))] = + trueRelation := by + apply relation_ext + intro a b + simpa only [PortTables.accepts, relationAt, trueRelation, + PreprocessingLazyWords.trueRelation, Fin.getElem_fin, Vector.getElem_replicate] using + overlay_accepts_expander G H v p a b + exact congrArg₂ (DartRow.mk v) hr hp + +theorem oldRow_reverse_val (G : PortTables.Table n d) (v : Fin n) (p : Fin d) : + (oldRow G e v p).reverseIndex.val = oldReverseMap d e (row G v p).reverseIndex.val := by + simp only [oldRow, rowIndex_val, overlayPorts_inl_val, oldReverseMap, row, + PreprocessingLazyWords.row] + change (G.reverseIndex[rowIndex n d (v, p)]).val % d + + (d + e) * ((G.reverseIndex[rowIndex n d (v, p)]).val / d) = _ + omega + +theorem expanderRow_reverse_val (H : ExpanderTables.Table n e) (v : Fin n) (p : Fin e) : + (expanderRow d H v p).reverseIndex.val = + expanderReverseMap d e (ExpanderTables.reverseIndex H (ExpanderTables.rowIndex n e (v, p))).val := by + simp only [expanderRow, rowIndex_val, overlayPorts_inr_val, expanderReverseMap] + change d + (ExpanderTables.reverseIndex H (ExpanderTables.rowIndex n e (v, p))).val % e + + (d + e) * ((ExpanderTables.reverseIndex H (ExpanderTables.rowIndex n e (v, p))).val / e) = _ + omega + +theorem oldRow_words (G : PortTables.Table n d) (v : Fin n) (p : Fin d) : + rowWords (oldRow G e v p) = + [v.val, oldReverseMap d e (row G v p).reverseIndex.val] ++ + relationWords (row G v p).relation := by + rw [rowWords, oldRow_reverse_val] + rfl + +theorem expanderRow_words (H : ExpanderTables.Table n e) (v : Fin n) (p : Fin e) : + rowWords (expanderRow d H v p) = + [v.val, expanderReverseMap d e + (ExpanderTables.reverseIndex H (ExpanderTables.rowIndex n e (v, p))).val] ++ + List.replicate 4096 1 := by + rw [rowWords, expanderRow_reverse_val] + exact congrArg (fun rs => [v.val, expanderReverseMap d e + (ExpanderTables.reverseIndex H (ExpanderTables.rowIndex n e (v, p))).val] ++ rs) + PreprocessingLazyWords.relationWords_true + +theorem ofFn_overlayPorts {α : Type*} (f : Fin (d + e) → α) : + List.ofFn f = List.ofFn (fun p => f (overlayPorts d e (.inl p))) ++ + List.ofFn (fun p => f (overlayPorts d e (.inr p))) := by + rw [List.ofFn_add] + rfl + +def vertexRows (G : PortTables.Table n d) (H : ExpanderTables.Table n e) (v : Fin n) : + List (DartRow n (n * (d + e))) := + List.ofFn (oldRow G e v) ++ List.ofFn (expanderRow d H v) + +theorem vertexRows_length (G : PortTables.Table n d) (H : ExpanderTables.Table n e) (v : Fin n) : + (vertexRows G H v).length = d + e := by + simp only [vertexRows, List.length_append, List.length_ofFn] + +theorem flatRows_overlay (G : PortTables.Table n d) (H : ExpanderTables.Table n e) : + (flatRows (overlay G H)).toList = (List.ofFn (vertexRows G H)).flatten := by + rw [PreprocessingLazyWords.flatRows_list] + apply congrArg List.flatten + congr 1 + funext v + rw [ofFn_overlayPorts] + simp only [row_overlay_old, row_overlay_expander] + rfl + +theorem vertexRows_words (G : PortTables.Table n d) (H : ExpanderTables.Table n e) (v : Fin n) : + (vertexRows G H v).flatMap rowWords = + (List.ofFn fun p : Fin d => + [v.val, oldReverseMap d e (row G v p).reverseIndex.val] ++ + relationWords (row G v p).relation).flatten ++ + (List.ofFn fun p : Fin e => + [v.val, expanderReverseMap d e + (ExpanderTables.reverseIndex H (ExpanderTables.rowIndex n e (v, p))).val] ++ + List.replicate 4096 1).flatten := by + have ho : rowWords ∘ oldRow G e v = fun p : Fin d => + [v.val, oldReverseMap d e (row G v p).reverseIndex.val] ++ + relationWords (row G v p).relation := by + funext p + exact oldRow_words G v p + have he : rowWords ∘ expanderRow d H v = fun p : Fin e => + [v.val, expanderReverseMap d e + (ExpanderTables.reverseIndex H (ExpanderTables.rowIndex n e (v, p))).val] ++ + List.replicate 4096 1 := by + funext p + exact expanderRow_words H v p + simp only [vertexRows, List.flatMap_def, List.map_append, List.map_ofFn, List.flatten_append] + rw [ho, he] + +theorem tableWords_overlay (G : PortTables.Table n d) (H : ExpanderTables.Table n e) : + PortTables.tableWords (overlay G H) = + [n, n * (d + e)] ++ (List.ofFn (vertexRows G H)).flatten.flatMap rowWords := by + rw [PortTables.tableWords_eq, flatRows_overlay] + +theorem tableBits_overlay (G : PortTables.Table n d) (H : ExpanderTables.Table n e) : + PortTables.tableBits (overlay G H) = encodeWords + ([n, n * (d + e)] ++ (List.ofFn (vertexRows G H)).flatten.flatMap rowWords) := by + change encodeWords (PortTables.tableWords (overlay G H)) = _ + rw [tableWords_overlay] + +theorem rotationWords_vertices (H : ExpanderTables.Table n e) : + ExpanderTableWords.rotationWords H = + (List.ofFn fun v : Fin n => List.ofFn fun p : Fin e => + (ExpanderTables.reverseIndex H (ExpanderTables.rowIndex n e (v, p))).val).flatten := by + have hflat : ExpanderTableWords.rotationWords H = + List.ofFn (fun i : Fin (n * e) => (ExpanderTables.reverseIndex H i).val) := by + apply List.ext_getElem + · simp [ExpanderTableWords.rotationWords_length] + · intro i hi hj + rw [ExpanderTableWords.rotationWords_getElem H i (by simpa using hi)] + simp only [List.getElem_ofFn] + rw [hflat, PreprocessingLazyWords.ofFn_rowIndex] + rfl + +end MinUncutGames.Foundations.PCP.PreprocessingOverlayWords + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/PreprocessingPaddingOffsets.lean b/lean/OAI/Computability/MinUncut/PCP/PreprocessingPaddingOffsets.lean new file mode 100644 index 0000000000000000000000000000000000000000..16a7ac73adab86bbb8f266a3f22917e45071e68a --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/PreprocessingPaddingOffsets.lean @@ -0,0 +1,87 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.PreprocessingRegularTables + +namespace OAI + +section +namespace MinUncutGames.Foundations.PCP.PreprocessingPaddingOffsets + +open PreprocessingRegularTables +open scoped BigOperators + +private theorem idxOf_map_injective {A B : Type*} [DecidableEq A] [DecidableEq B] + (f : A → B) (hf : Function.Injective f) (xs : List A) (a : A) : + (xs.map f).idxOf (f a) = xs.idxOf a := by + induction xs with + | nil => rfl + | cons x xs ih => + by_cases h : x = a + · subst x; simp + · simp [List.idxOf_cons_ne, h, hf.ne h, ih] + +theorem sigma_idxOf {A : Type*} [DecidableEq A] (sizes : A → Nat) + (xs : List A) (a : A) (ha : a ∈ xs) (j : Fin (sizes a)) : + (xs.sigma (fun x => List.finRange (sizes x))).idxOf ⟨a, j⟩ = + ((xs.take (xs.idxOf a)).map sizes).sum + j.val := by + induction xs with + | nil => simp at ha + | cons x xs ih => + rw [List.sigma_cons] + by_cases h : x = a + · subst x + have hm : (⟨a, j⟩ : Σ x, Fin (sizes x)) ∈ + (List.finRange (sizes a)).map (Sigma.mk a) := by + exact List.mem_map.mpr ⟨j, List.mem_finRange j, rfl⟩ + rw [List.idxOf_append_of_mem hm, + idxOf_map_injective (Sigma.mk a) (fun x y h => by cases h; rfl), + List.idxOf_finRange] + simp + · have hm : (⟨a, j⟩ : Σ x, Fin (sizes x)) ∉ + (List.finRange (sizes x)).map (Sigma.mk x) := by + intro hm + rcases List.mem_map.mp hm with ⟨k, _, hk⟩ + exact h (congrArg Sigma.fst hk) + rw [List.idxOf_append_of_notMem hm, List.length_map, List.length_finRange, + ih (List.mem_of_ne_of_mem (Ne.symm h) ha), List.idxOf_cons_ne xs h] + simp only [List.take_succ_cons, List.map_cons, List.sum_cons] + omega + +def offset {n : Nat} (padding : Fin n → Nat) (k : Nat) : Nat := + (((List.finRange n).take k).map padding).sum + +theorem sigma_length {A : Type*} (sizes : A → Nat) (xs : List A) : + (xs.sigma (fun x => List.finRange (sizes x))).length = (xs.map sizes).sum := by + induction xs with + | nil => rfl + | cons x xs ih => simp [List.sigma_cons, ih] + +theorem paddingOrder_val {n : Nat} (padding : Fin n → Nat) + (v : Fin n) (j : Fin (padding v)) : + (PreprocessingRegularTables.paddingOrder padding ⟨v, j⟩).val = + offset padding v.val + j.val := by + change (paddingList padding).idxOf ⟨v, j⟩ = _ + have h := sigma_idxOf padding (List.finRange n) v (List.mem_finRange v) j + simpa only [List.idxOf_finRange, paddingList, offset] using h + +theorem vertexOrder_dummy_val (t : GraphTables.Table) + (padding : Fin t.vertices → Nat) (v : Fin t.vertices) (j : Fin (padding v)) : + (vertexOrder t padding (Sum.inr ⟨v, j⟩)).val = + t.darts + offset padding v.val + j.val := by + rw [vertexOrder_dummy, paddingOrder_val] + omega + +@[simp] theorem offset_zero {n : Nat} (padding : Fin n → Nat) : offset padding 0 = 0 := by + simp [offset] + +theorem offset_all {n : Nat} (padding : Fin n → Nat) : + offset padding n = ∑ v, padding v := by + have ht : (List.finRange n).take n = List.finRange n := by simp + unfold offset + rw [ht, ← sigma_length padding (List.finRange n)] + exact paddingList_length padding + +end MinUncutGames.Foundations.PCP.PreprocessingPaddingOffsets + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/PreprocessingPaddingWords.lean b/lean/OAI/Computability/MinUncut/PCP/PreprocessingPaddingWords.lean new file mode 100644 index 0000000000000000000000000000000000000000..fd6ac30c1780e003a9ccad9ffe218ac6d5685586 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/PreprocessingPaddingWords.lean @@ -0,0 +1,389 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.PreprocessingInternalRows +import OAI.Computability.MinUncut.Machines.MachineDummyRows + +namespace OAI + +section +namespace MinUncutGames.Foundations.PCP.PreprocessingPaddingWords + +open Complexity PortTables + +variable {n m d : Nat} + +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 ofFn_split {α : Type*} (h : n ≤ m) (f : Fin m → α) : + List.ofFn f = + List.ofFn (fun v : Fin n => f (v.castLE h)) ++ + List.ofFn (fun v : Fin (m - n) => f (PreprocessingPaddingTables.vertexEquiv h (.inr v))) := by + calc + List.ofFn f = List.ofFn + (fun v : Fin (n + (m - n)) => f (Fin.cast (Nat.add_sub_of_le h) v)) := + List.ofFn_congr (Nat.add_sub_of_le h).symm f + _ = _ := by rw [List.ofFn_add]; rfl + +theorem flatten_ofFn_rowIndex {α : Type*} (f : Fin (n * d) → List α) : + (List.ofFn f).flatten = + (List.ofFn (fun v : Fin n => + (List.ofFn (fun p : Fin d => f (rowIndex n d (v, p)))).flatten)).flatten := by + rw [List.ofFn_mul, List.flatten_flatten, List.map_ofFn] + apply congrArg List.flatten + apply congrArg List.ofFn + funext v + apply congrArg List.flatten + apply congrArg List.ofFn + funext p + apply congrArg f + apply Fin.ext + simp only [rowIndex_val, Nat.mul_comm, Nat.add_comm] + +def rowBits (table : Table n d) (v : Fin n) (p : Fin d) : List Bool := + encodeWord v.val ++ encodeWord (table.reverseIndex[rowIndex n d (v, p)]).val ++ + encodeWords (GraphTables.relationWords table.relations[rowIndex n d (v, p)]) + +def vertexBits (table : Table n d) (v : Fin n) : List Bool := + (List.ofFn (fun p : Fin d => rowBits table v p)).flatten + +def rowsBits (table : Table n d) : List Bool := + encodeWords ((flatRows table).toList.flatMap GraphTables.rowWords) + +theorem rowBits_flat (table : Table n d) (i : Fin (n * d)) : + encodeWords (GraphTables.rowWords ((flatRows table)[i])) = + rowBits table ((rowIndex n d).symm i).1 ((rowIndex n d).symm i).2 := by + simp only [flatRows, Vector.getElem_ofFn, Fin.getElem_fin, + MachineTableRows.rowBits_eq, rowBits, Prod.eta, Equiv.apply_symm_apply] + +theorem rowsBits_eq_vertices (table : Table n d) : + rowsBits table = (List.ofFn (fun v : Fin n => vertexBits table v)).flatten := by + have hflat : (flatRows table).toList = + List.ofFn (fun i : Fin (n * d) => (flatRows table)[i]) := by + simp only [flatRows, Vector.toList_ofFn, Vector.getElem_ofFn, Fin.getElem_fin] + unfold rowsBits + rw [hflat, encodeWords_flatMap, List.flatMap_def, List.map_ofFn] + change (List.ofFn (fun i : Fin (n * d) => + encodeWords (GraphTables.rowWords ((flatRows table)[i])))).flatten = _ + simp_rw [rowBits_flat] + simpa only [Equiv.symm_apply_apply, vertexBits] using + flatten_ofFn_rowIndex (fun i : Fin (n * d) => + rowBits table ((rowIndex n d).symm i).1 ((rowIndex n d).symm i).2) + +theorem rowBits_pad_old (table : Table n d) (h : n ≤ m) (v : Fin n) (p : Fin d) : + rowBits (PreprocessingPaddingTables.pad table h) (v.castLE h) p = rowBits table v p := by + unfold rowBits + rw [PreprocessingPaddingTables.reverseIndex_pad_old, + PreprocessingPaddingTables.relations_pad_old] + have he : (rowIndex m d ((rotation table (v, p)).1.castLE h, + (rotation table (v, p)).2)).val = (table.reverseIndex[rowIndex n d (v, p)]).val := by + rw [← rowIndex_rotation] + rfl + rw [he] + rfl + +theorem rowBits_pad_new (table : Table n d) (h : n ≤ m) + (v : Fin (m - n)) (p : Fin d) : + rowBits (PreprocessingPaddingTables.pad table h) + (PreprocessingPaddingTables.vertexEquiv h (.inr v)) p = + MachineDummyRows.rowBits (n + v.val) (p.val + d * (n + v.val)) := by + unfold rowBits + rw [PreprocessingPaddingTables.reverseIndex_pad_new, + PreprocessingPaddingTables.relations_pad_new] + rfl + +theorem dummy_rowsBits_eq_ofFn (v e count : Nat) : + MachineDummyRows.rowsBits v e count = + (List.ofFn (fun p : Fin count => MachineDummyRows.rowBits v (e + p.val))).flatten := by + induction count generalizing e with + | zero => rfl + | succ count ih => + rw [MachineDummyRows.rowsBits, List.ofFn_succ, List.flatten_cons, ih] + simp only [Fin.val_zero, Nat.add_zero, Fin.val_succ] + congr 1 + apply congrArg (fun f : Fin count → List Bool => (List.ofFn f).flatten) + funext p + congr 1 + omega + +theorem paddingBits_eq_ofFn (d v e count : Nat) : + MachinePaddingRows.paddingBits d v e count = + (List.ofFn (fun k : Fin count => + MachineDummyRows.rowsBits (v + k.val) (e + k.val * d) d)).flatten := by + induction count generalizing v e with + | zero => rfl + | succ count ih => + rw [MachinePaddingRows.paddingBits, List.ofFn_succ, List.flatten_cons, ih] + simp only [Fin.val_zero, Nat.zero_mul, Nat.add_zero, Fin.val_succ, Nat.add_mul, Nat.one_mul] + congr 1 + apply congrArg (fun f : Fin count → List Bool => (List.ofFn f).flatten) + funext k + congr 1 <;> omega + +@[simp] theorem vertexBits_pad_old (table : Table n d) (h : n ≤ m) (v : Fin n) : + vertexBits (PreprocessingPaddingTables.pad table h) (v.castLE h) = vertexBits table v := by + simp only [vertexBits, rowBits_pad_old] + +theorem vertexBits_pad_new (table : Table n d) (h : n ≤ m) (v : Fin (m - n)) : + vertexBits (PreprocessingPaddingTables.pad table h) + (PreprocessingPaddingTables.vertexEquiv h (.inr v)) = + MachineDummyRows.rowsBits (n + v.val) (n * d + v.val * d) d := by + unfold vertexBits + simp_rw [rowBits_pad_new] + rw [dummy_rowsBits_eq_ofFn] + apply congrArg (fun f : Fin d → List Bool => (List.ofFn f).flatten) + funext p + congr 1 + ring + +theorem rowsBits_pad (table : Table n d) (h : n ≤ m) : + rowsBits (PreprocessingPaddingTables.pad table h) = + rowsBits table ++ MachinePaddingRows.paddingBits d n (n * d) (m - n) := by + rw [rowsBits_eq_vertices, ofFn_split h, List.flatten_append] + simp_rw [vertexBits_pad_old, vertexBits_pad_new] + rw [← rowsBits_eq_vertices, ← paddingBits_eq_ofFn] + +theorem tableBits_pad (table : Table n d) (h : n ≤ m) : + tableBits (PreprocessingPaddingTables.pad table h) = + encodeWords [m, m * d] ++ rowsBits table ++ + MachinePaddingRows.paddingBits d n (n * d) (m - n) := by + change encodeWords (PortTables.tableWords (PreprocessingPaddingTables.pad table h)) = _ + rw [tableWords_eq, encodeWords_append] + change encodeWords [m, m * d] ++ rowsBits (PreprocessingPaddingTables.pad table h) = _ + rw [rowsBits_pad, List.append_assoc] + +end MinUncutGames.Foundations.PCP.PreprocessingPaddingWords + +end +section +namespace MinUncutGames.Foundations.PCP.PreprocessingRegularWords + +open DegreeReplacement PreprocessingCloudIndex PreprocessingRegularTables Complexity +open scoped BigOperators + +variable (t : GraphTables.Table) (padding : Fin t.vertices → Nat) {q : Nat} +variable (tables : ∀ v, ExpanderTables.Table (cloudSize t v + padding v) q) + +def actualRow (x : Vertex t padding) (p : Fin q ⊕ Unit) : + GraphTables.DartRow (vertexCount t padding) (vertexCount t padding * (q + 1)) := + (PortTables.flatRows (ofCloudTables t padding tables))[ + PortTables.rowIndex _ _ (vertexOrder t padding x, portOrder q p)] + +def vertexRows (x : Vertex t padding) : + List (GraphTables.DartRow (vertexCount t padding) (vertexCount t padding * (q + 1))) := + List.ofFn (fun p : Fin q => actualRow t padding tables x (.inl p)) ++ + [actualRow t padding tables x (.inr ())] + +def originalVertexRows (e : Fin t.darts) := vertexRows t padding tables (.inl e) +def dummyVertexRows (v : Fin t.vertices) (j : Fin (padding v)) := + vertexRows t padding tables (.inr ⟨v, j⟩) + +def vertexBits (x : Vertex t padding) : List Bool := + encodeWords ((vertexRows t padding tables x).flatMap GraphTables.rowWords) + +def originalVertexBits (e : Fin t.darts) : List Bool := vertexBits t padding tables (.inl e) +def dummyVertexBits (v : Fin t.vertices) (j : Fin (padding v)) : List Bool := + vertexBits t padding tables (.inr ⟨v, j⟩) + +theorem actualRow_internal (v : Fin t.vertices) (x : PaddedCloud t padding v) (p : Fin q) : + actualRow t padding tables x.val (.inl p) = + PreprocessingInternalRows.row t padding tables v x p := rfl + +theorem actualRow_eq (x : Vertex t padding) (p : Fin q ⊕ Unit) : + actualRow t padding tables x p = + ⟨vertexOrder t padding x, + (ofCloudTables t padding tables).reverseIndex[ + PortTables.rowIndex _ _ (vertexOrder t padding x, portOrder q p)], + (ofCloudTables t padding tables).relations[ + PortTables.rowIndex _ _ (vertexOrder t padding x, portOrder q p)]⟩ := by + simp only [actualRow, PortTables.flatRows, Vector.getElem_ofFn, + Fin.getElem_fin, Fin.eta, Equiv.symm_apply_apply] + +@[simp] theorem actualRow_tail (x : Vertex t padding) (p : Fin q ⊕ Unit) : + (actualRow t padding tables x p).tail.val = (vertexOrder t padding x).val := by + rw [actualRow_eq] + +@[simp] theorem inherited_original_reverse (e : Fin t.darts) : + (actualRow t padding tables (.inl e) (.inr ())).reverseIndex.val = + (q + 1) * t.rows[e].reverseIndex.val + q := by + rw [actualRow_eq] + change ((ofCloudTables t padding tables).reverseIndex[PortTables.rowIndex _ _ + (vertexOrder t padding (.inl e), portOrder q (.inr ()))]).val = _ + rw [← PortTables.rowIndex_rotation, rotation_ofCloudTables] + change (PortTables.rowIndex _ _ + (vertexOrder t padding (.inl (GraphTables.reverseAt t.rows e)), portOrder q (.inr ()))).val = _ + rw [PortTables.rowIndex_val, vertexOrder_original, portOrder_inherited] + exact Nat.add_comm _ _ + +@[simp] theorem inherited_dummy_reverse (v : Fin t.vertices) (j : Fin (padding v)) : + (actualRow t padding tables (.inr ⟨v, j⟩) (.inr ())).reverseIndex.val = + (q + 1) * (t.darts + PreprocessingPaddingOffsets.offset padding v.val + j.val) + q := by + rw [actualRow_eq] + change ((ofCloudTables t padding tables).reverseIndex[PortTables.rowIndex _ _ + (vertexOrder t padding (.inr ⟨v, j⟩), portOrder q (.inr ()))]).val = _ + rw [← PortTables.rowIndex_rotation, rotation_ofCloudTables] + change (PortTables.rowIndex _ _ + (vertexOrder t padding (.inr ⟨v, j⟩), portOrder q (.inr ()))).val = _ + rw [PortTables.rowIndex_val, PreprocessingPaddingOffsets.vertexOrder_dummy_val, + portOrder_inherited] + exact Nat.add_comm _ _ + +theorem relation_ext {r s : GraphTables.RelationTable} + (h : ∀ a b, GraphTables.relationAt r a b = GraphTables.relationAt s a b) : r = s := by + apply Vector.ext + intro i hi + simpa only [GraphTables.relationAt, Prod.eta, Equiv.apply_symm_apply, + Fin.getElem_fin] using h (GraphTables.relationIndex.symm ⟨i, hi⟩).1 + (GraphTables.relationIndex.symm ⟨i, hi⟩).2 + +@[simp] theorem inherited_original_relation (e : Fin t.darts) : + (actualRow t padding tables (.inl e) (.inr ())).relation = t.rows[e].relation := by + rw [actualRow_eq] + apply relation_ext + intro a b + exact accepts_original t padding tables e a b + +@[simp] theorem inherited_dummy_relation (v : Fin t.vertices) (j : Fin (padding v)) : + (actualRow t padding tables (.inr ⟨v, j⟩) (.inr ())).relation = + MachineDummyRows.trueRelation := by + rw [actualRow_eq] + apply relation_ext + intro a b + have h := accepts_dummy t padding tables ⟨v, j⟩ a b + simpa only [PortTables.accepts, MachineDummyRows.trueRelation, + GraphTables.relationAt, Fin.getElem_fin, Vector.getElem_replicate] using h + +theorem inherited_original_words (e : Fin t.darts) : + GraphTables.rowWords (actualRow t padding tables (.inl e) (.inr ())) = + [e.val, (q + 1) * t.rows[e].reverseIndex.val + q] ++ + GraphTables.relationWords t.rows[e].relation := by + simp only [GraphTables.rowWords, actualRow_tail, vertexOrder_original, + inherited_original_reverse, inherited_original_relation] + +theorem inherited_dummy_words (v : Fin t.vertices) (j : Fin (padding v)) : + GraphTables.rowWords (actualRow t padding tables (.inr ⟨v, j⟩) (.inr ())) = + [t.darts + PreprocessingPaddingOffsets.offset padding v.val + j.val, + (q + 1) * (t.darts + PreprocessingPaddingOffsets.offset padding v.val + j.val) + q] ++ + GraphTables.relationWords MachineDummyRows.trueRelation := by + simp only [GraphTables.rowWords, actualRow_tail, + PreprocessingPaddingOffsets.vertexOrder_dummy_val, + inherited_dummy_reverse, inherited_dummy_relation] + +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 actualRow_bits (x : Vertex t padding) (p : Fin q ⊕ Unit) : + encodeWords (GraphTables.rowWords (actualRow t padding tables x p)) = + PreprocessingPaddingWords.rowBits (ofCloudTables t padding tables) + (vertexOrder t padding x) (portOrder q p) := by + simpa only [actualRow, Equiv.symm_apply_apply] using + PreprocessingPaddingWords.rowBits_flat (ofCloudTables t padding tables) + (PortTables.rowIndex _ _ (vertexOrder t padding x, portOrder q p)) + +theorem vertexBits_eq (x : Vertex t padding) : + vertexBits t padding tables x = + PreprocessingPaddingWords.vertexBits (ofCloudTables t padding tables) + (vertexOrder t padding x) := by + unfold vertexBits vertexRows + rw [List.flatMap_append, encodeWords_append] + simp only [List.flatMap_cons, List.flatMap_nil, List.append_nil] + rw [encodeWords_flatMap, List.flatMap_def, List.map_ofFn] + change (List.ofFn (fun p : Fin q => + encodeWords (GraphTables.rowWords (actualRow t padding tables x (.inl p))))).flatten ++ + encodeWords (GraphTables.rowWords (actualRow t padding tables x (.inr ()))) = _ + simp_rw [actualRow_bits] + unfold PreprocessingPaddingWords.vertexBits + rw [List.ofFn_succ_last, List.flatten_append] + simp only [List.flatten_cons, List.flatten_nil, List.append_nil] + rfl + +theorem paddingOrder_ofFn : + List.ofFn (paddingOrder padding).symm = paddingList padding := by + calc + List.ofFn (paddingOrder padding).symm = + List.ofFn (fun i : Fin (paddingList padding).length => + (paddingOrder padding).symm (Fin.cast (paddingList_length padding) i)) := + List.ofFn_congr (paddingList_length padding).symm (paddingOrder padding).symm + _ = paddingList padding := by + change List.ofFn (fun i => (paddingList padding).get i) = _ + exact List.ofFn_get _ + + +theorem vertexOrder_ofFn {α : Type*} (f : Vertex t padding → α) : + List.ofFn (fun i : Fin (vertexCount t padding) => f ((vertexOrder t padding).symm i)) = + List.ofFn (fun e : Fin t.darts => f (.inl e)) ++ + (paddingList padding).map (fun z => f (.inr z)) := by + change List.ofFn (fun i : Fin (t.darts + ∑ v, padding v) => + f ((vertexOrder t padding).symm i)) = _ + rw [List.ofFn_add] + have hold (e : Fin t.darts) : + (vertexOrder t padding).symm (e.castLE (Nat.le_add_right t.darts (∑ v, padding v))) = + Sum.inl e := (vertexOrder t padding).symm_apply_apply (Sum.inl e) + have hnew (i : Fin (∑ v, padding v)) : + (vertexOrder t padding).symm (i.natAdd t.darts) = + Sum.inr ((paddingOrder padding).symm i) := by + apply (vertexOrder t padding).injective + erw [Equiv.apply_symm_apply] + change i.natAdd t.darts = Fin.natAdd t.darts + ((paddingOrder padding) ((paddingOrder padding).symm i)) + rw [Equiv.apply_symm_apply] + apply congrArg₂ (· ++ ·) + · exact congrArg List.ofFn (funext (fun i => congrArg f (hold i))) + · calc + List.ofFn (fun i : Fin (∑ v, padding v) => + f ((vertexOrder t padding).symm (i.natAdd t.darts))) = + List.ofFn (fun i => f (.inr ((paddingOrder padding).symm i))) := + congrArg List.ofFn (funext (fun i => congrArg f (hnew i))) + _ = (List.ofFn (paddingOrder padding).symm).map (fun z => f (.inr z)) := + (List.map_ofFn (f := (paddingOrder padding).symm) (g := fun z => f (.inr z))).symm + _ = _ := by rw [paddingOrder_ofFn] + + +theorem paddingList_flatMap {α : Type*} (f : (Σ v : Fin t.vertices, Fin (padding v)) → List α) : + (paddingList padding).flatMap f = + (List.ofFn (fun v : Fin t.vertices => + (List.ofFn (fun j : Fin (padding v) => f ⟨v, j⟩)).flatten)).flatten := by + simp only [paddingList, List.sigma, List.finRange, List.flatMap_def, + List.map_flatten, List.flatten_flatten, List.map_ofFn, Function.comp_def] + +theorem rowsBits_ofCloudTables : + PreprocessingPaddingWords.rowsBits (ofCloudTables t padding tables) = + (List.ofFn (originalVertexBits t padding tables)).flatten ++ + (List.ofFn (fun v : Fin t.vertices => + (List.ofFn (dummyVertexBits t padding tables v)).flatten)).flatten := by + rw [PreprocessingPaddingWords.rowsBits_eq_vertices] + have hblocks : + List.ofFn (fun i : Fin (vertexCount t padding) => + PreprocessingPaddingWords.vertexBits (ofCloudTables t padding tables) i) = + List.ofFn (fun i : Fin (vertexCount t padding) => + vertexBits t padding tables ((vertexOrder t padding).symm i)) := by + apply congrArg List.ofFn + funext i + rw [vertexBits_eq, Equiv.apply_symm_apply] + rw [hblocks, vertexOrder_ofFn, List.flatten_append] + change (List.ofFn (originalVertexBits t padding tables)).flatten ++ + ((paddingList padding).map (fun z => dummyVertexBits t padding tables z.1 z.2)).flatten = _ + rw [← List.flatMap_def, paddingList_flatMap] + +theorem tableBits_ofCloudTables : + PortTables.tableBits (ofCloudTables t padding tables) = + encodeWords [vertexCount t padding, vertexCount t padding * (q + 1)] ++ + (List.ofFn (originalVertexBits t padding tables)).flatten ++ + (List.ofFn (fun v : Fin t.vertices => + (List.ofFn (dummyVertexBits t padding tables v)).flatten)).flatten := by + change encodeWords (PortTables.tableWords (ofCloudTables t padding tables)) = _ + rw [PortTables.tableWords_eq, encodeWords_append] + change encodeWords [vertexCount t padding, vertexCount t padding * (q + 1)] ++ + PreprocessingPaddingWords.rowsBits (ofCloudTables t padding tables) = _ + rw [rowsBits_ofCloudTables, List.append_assoc] + +end MinUncutGames.Foundations.PCP.PreprocessingRegularWords + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/PreprocessingRegularBounds.lean b/lean/OAI/Computability/MinUncut/PCP/PreprocessingRegularBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..8de58cf8d3a91e4c131efd5a384f0be07664d4c5 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/PreprocessingRegularBounds.lean @@ -0,0 +1,147 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.PreprocessingPaddingWords +import OAI.Computability.MinUncut.PCP.PreprocessingRegularLoopWords +import OAI.Computability.MinUncut.Machines.PreprocessingMachineBounds + +namespace OAI + +section +namespace MinUncutGames.Foundations.PCP.PreprocessingRegularBounds + +open PreprocessingRegularTables PreprocessingRegularWords PreprocessingRegularLoopWords +open MinUncutGames.Foundations.Complexity +open scoped BigOperators + +theorem offset_succ {n : Nat} (p : Fin n → Nat) (k : Nat) (h : k < n) : + PreprocessingPaddingOffsets.offset p (k + 1) = + PreprocessingPaddingOffsets.offset p k + p ⟨k, h⟩ := by + unfold PreprocessingPaddingOffsets.offset + rw [List.take_succ_eq_append_getElem (show k < (List.finRange n).length by simpa using h)] + simp only [List.map_append, List.sum_append, List.map_cons, List.map_nil, + List.sum_cons, List.sum_nil, Nat.add_zero, List.finRange, List.getElem_ofFn] + +theorem blocksPrefix_length_le {n : Nat} (f : Fin n → List Bool) (k : Nat) : + (blocksPrefix f k).length ≤ (List.ofFn f).flatten.length := by + have h := congrArg List.length (blocksPrefix_append_suffix f k) + simp only [List.length_append] at h + omega + +def header (t : GraphTables.Table) (p : Fin t.vertices → Nat) (q : Nat) : List Bool := + encodeWords [vertexCount t p, vertexCount t p * (q + 1)] + +def ownerBits (t : GraphTables.Table) (p : Fin t.vertices → Nat) {q : Nat} + (tables : ∀ v, ExpanderTables.Table (PreprocessingCloudIndex.cloudSize t v + p v) q) + (v : Fin t.vertices) : List Bool := + (List.ofFn (dummyVertexBits t p tables v)).flatten + +def originalPrefix (t : GraphTables.Table) (p : Fin t.vertices → Nat) {q : Nat} + (tables : ∀ v, ExpanderTables.Table (PreprocessingCloudIndex.cloudSize t v + p v) q) + (k : Nat) : List Bool := + header t p q ++ blocksPrefix (originalVertexBits t p tables) k + +def ownerPrefix (t : GraphTables.Table) (p : Fin t.vertices → Nat) {q : Nat} + (tables : ∀ v, ExpanderTables.Table (PreprocessingCloudIndex.cloudSize t v + p v) q) + (k : Nat) : List Bool := + header t p q ++ (List.ofFn (originalVertexBits t p tables)).flatten ++ + blocksPrefix (ownerBits t p tables) k + +def dummyPrefix (t : GraphTables.Table) (p : Fin t.vertices → Nat) {q : Nat} + (tables : ∀ v, ExpanderTables.Table (PreprocessingCloudIndex.cloudSize t v + p v) q) + (v : Fin t.vertices) (k : Nat) : List Bool := + ownerPrefix t p tables v.val ++ blocksPrefix (dummyVertexBits t p tables v) k + +variable (t : GraphTables.Table) (p : Fin t.vertices → Nat) {q : Nat} +variable (tables : ∀ v, ExpanderTables.Table (PreprocessingCloudIndex.cloudSize t v + p v) q) + +theorem originalPrefix_length_le (k : Nat) : + (originalPrefix t p tables k).length ≤ + (PortTables.tableBits (ofCloudTables t p tables)).length := by + have h := blocksPrefix_length_le (originalVertexBits t p tables) k + rw [tableBits_ofCloudTables] + simp only [originalPrefix, header, List.length_append] + omega + +theorem ownerPrefix_length_le (k : Nat) : + (ownerPrefix t p tables k).length ≤ + (PortTables.tableBits (ofCloudTables t p tables)).length := by + have h := blocksPrefix_length_le (ownerBits t p tables) k + have he : ownerBits t p tables = + (fun v => (List.ofFn (dummyVertexBits t p tables v)).flatten) := rfl + rw [tableBits_ofCloudTables] + simp only [ownerPrefix, header, List.length_append] at * + simp only [he] at * + omega + +theorem dummyPrefix_length_le (v : Fin t.vertices) (k : Nat) : + (dummyPrefix t p tables v k).length ≤ + (PortTables.tableBits (ofCloudTables t p tables)).length := by + have hi := blocksPrefix_length_le (dummyVertexBits t p tables v) k + have ho := blocksPrefix_length_le (ownerBits t p tables) (v.val + 1) + rw [blocksPrefix_succ _ _ v.isLt] at ho + have he : ownerBits t p tables = + (fun v => (List.ofFn (dummyVertexBits t p tables v)).flatten) := rfl + simp only [Fin.eta] at ho + rw [tableBits_ofCloudTables] + simp only [dummyPrefix, ownerPrefix, header, ownerBits, List.length_append] at * + simp only [he] at * + omega + +theorem regular_originalPrefix_le (H : BaseTable) (k : Nat) : + (originalPrefix t (padding t) (familyCloudTable H t) k).length ≤ + PreprocessingMachineBounds.regularPolynomial.eval + (PreprocessingMachineBounds.inputLength t) := + (originalPrefix_length_le t (padding t) (familyCloudTable H t) k).trans + (PreprocessingMachineBounds.regularBits_le H t) + +theorem regular_ownerPrefix_le (H : BaseTable) (k : Nat) : + (ownerPrefix t (padding t) (familyCloudTable H t) k).length ≤ + PreprocessingMachineBounds.regularPolynomial.eval + (PreprocessingMachineBounds.inputLength t) := + (ownerPrefix_length_le t (padding t) (familyCloudTable H t) k).trans + (PreprocessingMachineBounds.regularBits_le H t) + +theorem regular_dummyPrefix_le (H : BaseTable) (v : Fin t.vertices) (k : Nat) : + (dummyPrefix t (padding t) (familyCloudTable H t) v k).length ≤ + PreprocessingMachineBounds.regularPolynomial.eval + (PreprocessingMachineBounds.inputLength t) := + (dummyPrefix_length_le t (padding t) (familyCloudTable H t) v k).trans + (PreprocessingMachineBounds.regularBits_le H t) + +theorem visits_le_input : + t.darts + t.vertices + (∑ v, padding t v) + 1 ≤ + (ExpanderFamily.growth + 1) * PreprocessingMachineBounds.inputLength t + 1 := by + have hv := PreprocessingMachineBounds.regularVertices_le_input t + have hn := GraphTables.vertices_le_tableBits_length t + change t.vertices ≤ PreprocessingMachineBounds.inputLength t at hn + unfold vertexCount at hv + rw [Nat.add_mul, one_mul] + omega + +theorem sum_body_costs_le (old : Fin t.darts → Nat) (owners : Fin t.vertices → Nat) + (dummy : ∀ v : Fin t.vertices, Fin (padding t v) → Nat) (setup cap : Nat) + (hs : setup ≤ cap) (ho : ∀ e, old e ≤ cap) (hv : ∀ v, owners v ≤ cap) + (hd : ∀ v j, dummy v j ≤ cap) : + setup + (∑ e, old e) + (∑ v, owners v) + (∑ v, ∑ j, dummy v j) ≤ + ((ExpanderFamily.growth + 1) * PreprocessingMachineBounds.inputLength t + 1) * cap := by + have hOld : (∑ e, old e) ≤ t.darts * cap := by + simpa using Finset.sum_le_sum (fun e (_ : e ∈ Finset.univ) => ho e) + have hOwners : (∑ v, owners v) ≤ t.vertices * cap := by + simpa using Finset.sum_le_sum (fun v (_ : v ∈ Finset.univ) => hv v) + have hDummy : (∑ v, ∑ j, dummy v j) ≤ (∑ v, padding t v) * cap := by + calc + _ ≤ ∑ v, padding t v * cap := by + apply Finset.sum_le_sum + intro v _ + simpa using Finset.sum_le_sum (fun j (_ : j ∈ Finset.univ) => hd v j) + _ = _ := (Finset.sum_mul ..).symm + calc + _ ≤ (t.darts + t.vertices + (∑ v, padding t v) + 1) * cap := by + rw [Nat.add_mul, Nat.add_mul, Nat.add_mul, one_mul] + omega + _ ≤ _ := Nat.mul_le_mul_right cap (visits_le_input t) + +end MinUncutGames.Foundations.PCP.PreprocessingRegularBounds + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/PreprocessingRegularLoopWords.lean b/lean/OAI/Computability/MinUncut/PCP/PreprocessingRegularLoopWords.lean new file mode 100644 index 0000000000000000000000000000000000000000..c5601e728fb3bbbb612eb5d834242c134c042b01 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/PreprocessingRegularLoopWords.lean @@ -0,0 +1,59 @@ +import Mathlib +import OAI.Computability.MinUncut.Model + +namespace OAI + +section +namespace MinUncutGames.Foundations.PCP.PreprocessingRegularLoopWords + +def blocksPrefix {n : Nat} (f : Fin n → List Bool) (k : Nat) : List Bool := + ((List.ofFn f).take k).flatten + +def blocksSuffix {n : Nat} (f : Fin n → List Bool) (k : Nat) : List Bool := + ((List.ofFn f).drop k).flatten + +@[simp] theorem blocksPrefix_zero {n : Nat} (f : Fin n → List Bool) : + blocksPrefix f 0 = [] := by + simp only [blocksPrefix, List.take_zero, List.flatten_nil] + +@[simp] theorem blocksPrefix_all {n : Nat} (f : Fin n → List Bool) : + blocksPrefix f n = (List.ofFn f).flatten := by + have h : (List.ofFn f).take n = List.ofFn f := by + simpa only [List.length_ofFn] using (List.take_length (l := List.ofFn f)) + exact congrArg List.flatten h + +theorem blocksPrefix_succ {n : Nat} (f : Fin n → List Bool) (k : Nat) (h : k < n) : + blocksPrefix f (k + 1) = blocksPrefix f k ++ f ⟨k, h⟩ := by + unfold blocksPrefix + rw [List.take_succ_eq_append_getElem + (show k < (List.ofFn f).length by simpa only [List.length_ofFn] using h)] + simp only [List.flatten_append, List.flatten_cons, List.flatten_nil, + List.append_nil, List.getElem_ofFn] + +@[simp] theorem blocksSuffix_zero {n : Nat} (f : Fin n → List Bool) : + blocksSuffix f 0 = (List.ofFn f).flatten := by + simp only [blocksSuffix, List.drop_zero] + +@[simp] theorem blocksSuffix_all {n : Nat} (f : Fin n → List Bool) : + blocksSuffix f n = [] := by + have h : (List.ofFn f).drop n = [] := by + simpa only [List.length_ofFn] using (List.drop_length (l := List.ofFn f)) + exact congrArg List.flatten h + +theorem blocksSuffix_succ {n : Nat} (f : Fin n → List Bool) (k : Nat) (h : k < n) : + blocksSuffix f k = f ⟨k, h⟩ ++ blocksSuffix f (k + 1) := by + unfold blocksSuffix + rw [List.drop_eq_getElem_cons + (show k < (List.ofFn f).length by simpa only [List.length_ofFn] using h)] + simp only [List.flatten_cons, List.getElem_ofFn] + +theorem blocksPrefix_append_suffix {n : Nat} (f : Fin n → List Bool) (k : Nat) : + blocksPrefix f k ++ blocksSuffix f k = (List.ofFn f).flatten := by + unfold blocksPrefix blocksSuffix + rw [← List.flatten_append, List.take_append_drop] + +end MinUncutGames.Foundations.PCP.PreprocessingRegularLoopWords + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/PreprocessingRegularTables.lean b/lean/OAI/Computability/MinUncut/PCP/PreprocessingRegularTables.lean new file mode 100644 index 0000000000000000000000000000000000000000..77ad0d7ff0508a73037ae0015b2e604e5cba53cc --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/PreprocessingRegularTables.lean @@ -0,0 +1,746 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.ExpanderFamily + +namespace OAI + +namespace MinUncutGames.Foundations.PCP.PreprocessingRegularTables + +open scoped BigOperators +open PoweringWalks DegreeReplacement + +def paddingList {n : Nat} (padding : Fin n → Nat) : + List (Σ v : Fin n, Fin (padding v)) := + (List.finRange n).sigma (fun v => List.finRange (padding v)) + +theorem paddingList_nodup {n : Nat} (padding : Fin n → Nat) : + (paddingList padding).Nodup := + (List.nodup_finRange n).sigma (fun v => List.nodup_finRange (padding v)) + +theorem mem_paddingList {n : Nat} (padding : Fin n → Nat) + (z : Σ v : Fin n, Fin (padding v)) : z ∈ paddingList padding := by + rcases z with ⟨v, k⟩ + simp only [paddingList, List.mem_sigma, List.mem_finRange, and_self] + +def paddingListOrder {n : Nat} (padding : Fin n → Nat) : + (Σ v : Fin n, Fin (padding v)) ≃ Fin (paddingList padding).length := + PreprocessingCloudIndex.listEquiv (paddingList padding) + (paddingList_nodup padding) (mem_paddingList padding) + +theorem paddingList_length {n : Nat} (padding : Fin n → Nat) : + (paddingList padding).length = ∑ v, padding v := by + simpa only [Fintype.card_sigma, Fintype.card_fin] using + (Fintype.card_congr (paddingListOrder padding)).symm + +def paddingOrder {n : Nat} (padding : Fin n → Nat) : + (Σ v : Fin n, Fin (padding v)) ≃ Fin (∑ v, padding v) := + (paddingListOrder padding).trans (finCongr (paddingList_length padding)) + +abbrev Vertex (t : GraphTables.Table) (padding : Fin t.vertices → Nat) := + PaddedDart (GraphTables.semantics t) (fun v => Fin (padding v)) + +def vertexCount (t : GraphTables.Table) (padding : Fin t.vertices → Nat) : Nat := + t.darts + ∑ v, padding v + +def vertexOrder (t : GraphTables.Table) (padding : Fin t.vertices → Nat) : + Vertex t padding ≃ Fin (vertexCount t padding) := + (Equiv.sumCongr (Equiv.refl _) (paddingOrder padding)).trans finSumFinEquiv + +@[simp] theorem vertexOrder_original (t : GraphTables.Table) + (padding : Fin t.vertices → Nat) (e : Fin t.darts) : + (vertexOrder t padding (Sum.inl e)).val = e.val := rfl + +@[simp] theorem vertexOrder_dummy (t : GraphTables.Table) + (padding : Fin t.vertices → Nat) (z : Σ v, Fin (padding v)) : + (vertexOrder t padding (Sum.inr z)).val = + t.darts + (paddingOrder padding z).val := rfl + +def unitOrder : Unit ≃ Fin 1 where + toFun _ := ⟨0, Nat.zero_lt_one⟩ + invFun _ := () + left_inv u := by cases u; rfl + right_inv k := Subsingleton.elim _ _ + +def portOrder (q : Nat) : (Fin q ⊕ Unit) ≃ Fin (q + 1) := + (Equiv.sumCongr (Equiv.refl _) unitOrder).trans finSumFinEquiv + +@[simp] theorem portOrder_internal (q : Nat) (p : Fin q) : + (portOrder q (Sum.inl p)).val = p.val := rfl + +@[simp] theorem portOrder_inherited (q : Nat) : + (portOrder q (Sum.inr ())).val = q := rfl + +def cloudGraphs (t : GraphTables.Table) (padding : Fin t.vertices → Nat) + {q : Nat} (tables : ∀ v, ExpanderTables.Table + (PreprocessingCloudIndex.cloudSize t v + padding v) q) (v : Fin t.vertices) : + PortGraph (Cloud (paddedGraph (GraphTables.semantics t) + (fun w => Fin (padding w))) v) (Fin q) := + GraphTransport.reindex (ExpanderTables.graph (tables v)) + (PreprocessingCloudIndex.paddedCloudEquiv t padding v).symm (Equiv.refl _) + +def sourcePortGraph (t : GraphTables.Table) (padding : Fin t.vertices → Nat) + {q : Nat} (tables : ∀ v, ExpanderTables.Table + (PreprocessingCloudIndex.cloudSize t v + padding v) q) : + PortGraph (Vertex t padding) (Fin q ⊕ Unit) := + paddedReplacementPortGraph (GraphTables.semantics t) (fun v => Fin (padding v)) + (cloudGraphs t padding tables) + +def sourceGraph (t : GraphTables.Table) (padding : Fin t.vertices → Nat) + {q : Nat} (tables : ∀ v, ExpanderTables.Table + (PreprocessingCloudIndex.cloudSize t v + padding v) q) : + ConstraintGraph (Vertex t padding) (Vertex t padding × (Fin q ⊕ Unit)) + GraphTables.Label := + paddedReplacementGraph (GraphTables.semantics t) (fun v => Fin (padding v)) + (cloudGraphs t padding tables) + +def numberedPortGraph (t : GraphTables.Table) (padding : Fin t.vertices → Nat) + {q : Nat} (tables : ∀ v, ExpanderTables.Table + (PreprocessingCloudIndex.cloudSize t v + padding v) q) : + PortGraph (Fin (vertexCount t padding)) (Fin (q + 1)) := + GraphTransport.reindex (sourcePortGraph t padding tables) + (vertexOrder t padding) (portOrder q) + +def numberedAccepts (t : GraphTables.Table) (padding : Fin t.vertices → Nat) + {q : Nat} (tables : ∀ v, ExpanderTables.Table + (PreprocessingCloudIndex.cloudSize t v + padding v) q) + (e : Fin (vertexCount t padding) × Fin (q + 1)) + (a b : GraphTables.Label) : Bool := + (sourceGraph t padding tables).accepts + ((vertexOrder t padding).symm e.1, (portOrder q).symm e.2) a b + +theorem numberedAccepts_transpose (t : GraphTables.Table) + (padding : Fin t.vertices → Nat) {q : Nat} + (tables : ∀ v, ExpanderTables.Table + (PreprocessingCloudIndex.cloudSize t v + padding v) q) + (e : Fin (vertexCount t padding) × Fin (q + 1)) (a b : GraphTables.Label) : + numberedAccepts t padding tables ((numberedPortGraph t padding tables).rot e) b a = + numberedAccepts t padding tables e a b := by + obtain ⟨z, rfl⟩ := (Equiv.prodCongr (vertexOrder t padding) (portOrder q)).surjective e + rcases z with ⟨v, p⟩ + simp only [numberedPortGraph, Equiv.prodCongr_apply, Prod.map_apply, + GraphTransport.reindex_rot, numberedAccepts, Equiv.symm_apply_apply] + exact (sourceGraph t padding tables).reverse_accepts (v, p) a b + +def ofCloudTables (t : GraphTables.Table) (padding : Fin t.vertices → Nat) + {q : Nat} (tables : ∀ v, ExpanderTables.Table + (PreprocessingCloudIndex.cloudSize t v + padding v) q) : + PortTables.Table (vertexCount t padding) (q + 1) := + PortTables.ofPortGraph (numberedPortGraph t padding tables) + (numberedAccepts t padding tables) (numberedAccepts_transpose t padding tables) + +@[simp] theorem rotation_ofCloudTables (t : GraphTables.Table) + (padding : Fin t.vertices → Nat) {q : Nat} + (tables : ∀ v, ExpanderTables.Table + (PreprocessingCloudIndex.cloudSize t v + padding v) q) + (v : Vertex t padding) (p : Fin q ⊕ Unit) : + PortTables.rotation (ofCloudTables t padding tables) + (vertexOrder t padding v, portOrder q p) = + (vertexOrder t padding ((sourcePortGraph t padding tables).rot (v, p)).1, + portOrder q ((sourcePortGraph t padding tables).rot (v, p)).2) := by + rw [ofCloudTables, PortTables.rotation_ofPortGraph] + exact GraphTransport.reindex_rot _ _ _ _ _ + +@[simp] theorem accepts_ofCloudTables (t : GraphTables.Table) + (padding : Fin t.vertices → Nat) {q : Nat} + (tables : ∀ v, ExpanderTables.Table + (PreprocessingCloudIndex.cloudSize t v + padding v) q) + (v : Vertex t padding) (p : Fin q ⊕ Unit) (a b : GraphTables.Label) : + PortTables.accepts (ofCloudTables t padding tables) + (vertexOrder t padding v, portOrder q p) a b = + (sourceGraph t padding tables).accepts (v, p) a b := by + simp only [ofCloudTables, PortTables.accepts_ofPortGraph, + numberedAccepts, Equiv.symm_apply_apply] + +@[simp] theorem accepts_internal (t : GraphTables.Table) + (padding : Fin t.vertices → Nat) {q : Nat} + (tables : ∀ v, ExpanderTables.Table + (PreprocessingCloudIndex.cloudSize t v + padding v) q) + (v : Vertex t padding) (p : Fin q) (a b : GraphTables.Label) : + PortTables.accepts (ofCloudTables t padding tables) + (vertexOrder t padding v, portOrder q (Sum.inl p)) a b = decide (a = b) := by + rw [accepts_ofCloudTables] + rfl + +@[simp] theorem accepts_original (t : GraphTables.Table) + (padding : Fin t.vertices → Nat) {q : Nat} + (tables : ∀ v, ExpanderTables.Table + (PreprocessingCloudIndex.cloudSize t v + padding v) q) + (e : Fin t.darts) (a b : GraphTables.Label) : + PortTables.accepts (ofCloudTables t padding tables) + (vertexOrder t padding (Sum.inl e), portOrder q (Sum.inr ())) a b = + GraphTables.acceptsAt t.rows e a b := by + rw [accepts_ofCloudTables] + rfl + +@[simp] theorem accepts_dummy (t : GraphTables.Table) + (padding : Fin t.vertices → Nat) {q : Nat} + (tables : ∀ v, ExpanderTables.Table + (PreprocessingCloudIndex.cloudSize t v + padding v) q) + (z : Σ v, Fin (padding v)) (a b : GraphTables.Label) : + PortTables.accepts (ofCloudTables t padding tables) + (vertexOrder t padding (Sum.inr z), portOrder q (Sum.inr ())) a b = true := by + rw [accepts_ofCloudTables] + rfl + +theorem edgeSatisfied_ofCloudTables (t : GraphTables.Table) + (padding : Fin t.vertices → Nat) {q : Nat} + (tables : ∀ v, ExpanderTables.Table + (PreprocessingCloudIndex.cloudSize t v + padding v) q) + (labels : Fin (vertexCount t padding) → GraphTables.Label) + (v : Vertex t padding) (p : Fin q ⊕ Unit) : + (PortTables.baseGraph (ofCloudTables t padding tables)).edgeSatisfied labels + (vertexOrder t padding v, portOrder q p) = + (sourceGraph t padding tables).edgeSatisfied + (fun z => labels (vertexOrder t padding z)) (v, p) := by + change PortTables.accepts (ofCloudTables t padding tables) + (vertexOrder t padding v, portOrder q p) (labels (vertexOrder t padding v)) + (labels (PortTables.rotation (ofCloudTables t padding tables) + (vertexOrder t padding v, portOrder q p)).1) = _ + rw [rotation_ofCloudTables, accepts_ofCloudTables] + rfl + +theorem rejectionCount_ofCloudTables (t : GraphTables.Table) + (padding : Fin t.vertices → Nat) {q : Nat} + (tables : ∀ v, ExpanderTables.Table + (PreprocessingCloudIndex.cloudSize t v + padding v) q) + (labels : Fin (vertexCount t padding) → GraphTables.Label) : + (PortTables.baseGraph (ofCloudTables t padding tables)).rejectionCount labels = + (sourceGraph t padding tables).rejectionCount + (fun z => labels (vertexOrder t padding z)) := by + classical + unfold ConstraintGraph.rejectionCount + symm + apply Finset.card_equiv (Equiv.prodCongr (vertexOrder t padding) (portOrder q)) + rintro ⟨v, p⟩ + simp only [ConstraintGraph.mem_rejectedDarts, Equiv.prodCongr_apply, + Prod.map_apply, edgeSatisfied_ofCloudTables] + +def liftedLabel (t : GraphTables.Table) (padding : Fin t.vertices → Nat) + (labels : Fin t.vertices → GraphTables.Label) : + Fin (vertexCount t padding) → GraphTables.Label := + fun z => labels (paddedOwner (GraphTables.semantics t) (fun v => Fin (padding v)) + ((vertexOrder t padding).symm z)) + +theorem rejectionCount_liftedLabel (t : GraphTables.Table) + (padding : Fin t.vertices → Nat) {q : Nat} + (tables : ∀ v, ExpanderTables.Table + (PreprocessingCloudIndex.cloudSize t v + padding v) q) + (labels : Fin t.vertices → GraphTables.Label) : + (PortTables.baseGraph (ofCloudTables t padding tables)).rejectionCount + (liftedLabel t padding labels) = (GraphTables.semantics t).rejectionCount labels := by + rw [rejectionCount_ofCloudTables] + simp only [liftedLabel, Equiv.symm_apply_apply] + convert paddedReplacement_rejectionCount (GraphTables.semantics t) + (fun v => Fin (padding v)) (cloudGraphs t padding tables) labels using 1 + rfl + +def emptyTable (q : Nat) : ExpanderTables.Table 0 q := + ExpanderTables.ofGraph { rot := Equiv.refl _, rot_involutive := fun _ => rfl } + +def resizeTable {n m q : Nat} (h : n = m) (table : ExpanderTables.Table n q) : + ExpanderTables.Table m q := h ▸ table + +abbrev BaseTable := ExpanderTables.Table + ((Expanders.baseDegree * Expanders.baseDegree) * + (Expanders.baseDegree * Expanders.baseDegree)) Expanders.baseDegree + +def internalDegree : Nat := Expanders.baseDegree * Expanders.baseDegree + +def padding (t : GraphTables.Table) (v : Fin t.vertices) : Nat := + PreprocessingLevels.cloudPaddedSize (PreprocessingCloudIndex.cloudSize t v) - + PreprocessingCloudIndex.cloudSize t v + +theorem cloudSize_add_padding (t : GraphTables.Table) (v : Fin t.vertices) : + PreprocessingCloudIndex.cloudSize t v + padding t v = + PreprocessingLevels.cloudPaddedSize (PreprocessingCloudIndex.cloudSize t v) := + Nat.add_sub_of_le (PreprocessingLevels.cloudPaddedSize_bounds _).1 + +theorem vertexCount_eq_sum_cloudPaddedSize (t : GraphTables.Table) : + vertexCount t (padding t) = ∑ v, + PreprocessingLevels.cloudPaddedSize (PreprocessingCloudIndex.cloudSize t v) := by + unfold vertexCount + rw [← PreprocessingCloudIndex.sum_cloudSize t, ← Finset.sum_add_distrib] + exact Finset.sum_congr rfl (fun v _ => cloudSize_add_padding t v) + +theorem vertexCount_le (t : GraphTables.Table) : + vertexCount t (padding t) ≤ ExpanderFamily.growth * t.darts := by + rw [vertexCount_eq_sum_cloudPaddedSize, ← PreprocessingCloudIndex.sum_cloudSize t, + Finset.mul_sum] + exact Finset.sum_le_sum (fun v _ => (PreprocessingLevels.cloudPaddedSize_bounds _).2) + +theorem vertexCount_eq_zero_of_no_darts (t : GraphTables.Table) (h : t.darts = 0) : + vertexCount t (padding t) = 0 := by + have hle := vertexCount_le t + rw [h, Nat.mul_zero] at hle + exact Nat.eq_zero_of_le_zero hle + +def familyCloudTable (H : BaseTable) (t : GraphTables.Table) (v : Fin t.vertices) : + ExpanderTables.Table (PreprocessingCloudIndex.cloudSize t v + padding t v) + internalDegree := + if hk : PreprocessingCloudIndex.cloudSize t v = 0 then + resizeTable (by rw [cloudSize_add_padding, hk]; rfl) (emptyTable internalDegree) + else + resizeTable (by + rw [cloudSize_add_padding, + PreprocessingLevels.cloudPaddedSize_of_pos (Nat.pos_of_ne_zero hk)] + exact PreprocessingLevels.table_vertexCount_eq_paddedSize _) + (ExpanderTables.family H + (PreprocessingLevels.boundedLevel (PreprocessingCloudIndex.cloudSize t v))) + +def regularize (H : BaseTable) (t : GraphTables.Table) : + PortTables.Table (vertexCount t (padding t)) (internalDegree + 1) := + ofCloudTables t (padding t) (familyCloudTable H t) + +def regularizeInput (H : BaseTable) (t : GraphTables.Table) : + PortTables.Input (internalDegree + 1) := + ⟨vertexCount t (padding t), regularize H t⟩ + +end MinUncutGames.Foundations.PCP.PreprocessingRegularTables + +namespace MinUncutGames.Foundations.PCP.VertexPadding + +open scoped BigOperators + +variable {V D A : Type*} + +def reverseFunction (G : ConstraintGraph V (V × D) A) (extra : ℕ) : + (V ⊕ Fin extra) × D → (V ⊕ Fin extra) × D + | (Sum.inl v, d) => (Sum.inl (G.reverse (v, d)).1, (G.reverse (v, d)).2) + | (Sum.inr w, d) => (Sum.inr w, d) + +theorem reverseFunction_involutive (G : ConstraintGraph V (V × D) A) (extra : ℕ) : + Function.Involutive (reverseFunction G extra) := by + rintro ⟨v | w, d⟩ + · change (Sum.inl (G.reverse (G.reverse (v, d))).1, + (G.reverse (G.reverse (v, d))).2) = (Sum.inl v, d) + rw [G.reverse_involutive] + · rfl + +def pad (G : ConstraintGraph V (V × D) A) (extra : ℕ) : + ConstraintGraph (V ⊕ Fin extra) ((V ⊕ Fin extra) × D) A where + reverse := { + toFun := reverseFunction G extra + invFun := reverseFunction G extra + left_inv := reverseFunction_involutive G extra + right_inv := reverseFunction_involutive G extra } + reverse_involutive := reverseFunction_involutive G extra + tail := Prod.fst + accepts := fun e a b => match e.1 with + | Sum.inl v => G.accepts (v, e.2) a b + | Sum.inr _ => true + reverse_accepts := by + rintro ⟨v | w, d⟩ a b + · change G.accepts (G.reverse (v, d)) b a = G.accepts (v, d) a b + exact G.reverse_accepts (v, d) a b + · rfl + +@[simp] theorem pad_tail (G : ConstraintGraph V (V × D) A) (extra : ℕ) : + (pad G extra).tail = Prod.fst := rfl + +@[simp] theorem pad_reverse_inl (G : ConstraintGraph V (V × D) A) (extra : ℕ) + (v : V) (d : D) : + (pad G extra).reverse (Sum.inl v, d) = + (Sum.inl (G.reverse (v, d)).1, (G.reverse (v, d)).2) := rfl + +@[simp] theorem pad_reverse_inr (G : ConstraintGraph V (V × D) A) (extra : ℕ) + (w : Fin extra) (d : D) : + (pad G extra).reverse (Sum.inr w, d) = (Sum.inr w, d) := rfl + +@[simp] theorem edgeSatisfied_inl (G : ConstraintGraph V (V × D) A) + (htail : G.tail = Prod.fst) (extra : ℕ) (labeling : V ⊕ Fin extra → A) + (v : V) (d : D) : + (pad G extra).edgeSatisfied labeling (Sum.inl v, d) = + G.edgeSatisfied (fun v => labeling (Sum.inl v)) (v, d) := by + change G.accepts (v, d) (labeling (Sum.inl v)) + (labeling (Sum.inl (G.reverse (v, d)).1)) = + G.accepts (v, d) (labeling (Sum.inl (G.tail (v, d)))) + (labeling (Sum.inl (G.tail (G.reverse (v, d))))) + rw [htail] + +@[simp] theorem edgeSatisfied_inr (G : ConstraintGraph V (V × D) A) (extra : ℕ) + (labeling : V ⊕ Fin extra → A) (w : Fin extra) (d : D) : + (pad G extra).edgeSatisfied labeling (Sum.inr w, d) = true := rfl + +def extendLabeling (extra : ℕ) (defaultA : A) (labeling : V → A) : V ⊕ Fin extra → A := + Sum.elim labeling (fun _ => defaultA) + +@[simp] theorem extendLabeling_inl (extra : ℕ) (defaultA : A) (labeling : V → A) + (v : V) : extendLabeling extra defaultA labeling (Sum.inl v) = labeling v := rfl + +@[simp] theorem extendLabeling_inr (extra : ℕ) (defaultA : A) (labeling : V → A) + (w : Fin extra) : extendLabeling extra defaultA labeling (Sum.inr w) = defaultA := rfl + +theorem pad_satisfiable (G : ConstraintGraph V (V × D) A) (htail : G.tail = Prod.fst) + (extra : ℕ) (defaultA : A) (hG : G.Satisfiable) : (pad G extra).Satisfiable := by + obtain ⟨labeling, hlabeling⟩ := hG + refine ⟨extendLabeling extra defaultA labeling, ?_⟩ + rintro ⟨v | w, d⟩ + · simpa only [edgeSatisfied_inl G htail, extendLabeling_inl] using hlabeling (v, d) + · rfl + +theorem satisfiable_of_pad (G : ConstraintGraph V (V × D) A) (htail : G.tail = Prod.fst) + (extra : ℕ) (hG : (pad G extra).Satisfiable) : G.Satisfiable := by + obtain ⟨labeling, hlabeling⟩ := hG + refine ⟨fun v => labeling (Sum.inl v), ?_⟩ + rintro ⟨v, d⟩ + simpa only [edgeSatisfied_inl G htail] using hlabeling (Sum.inl v, d) + +theorem rejectionCount_eq_sum {U E : Type*} [Fintype E] + (G : ConstraintGraph U E A) (labeling : U → A) : + G.rejectionCount labeling = ∑ e, if G.edgeSatisfied labeling e = false then 1 else 0 := by + simp [ConstraintGraph.rejectionCount, ConstraintGraph.rejectedDarts] + +theorem pad_rejectionCount [Fintype V] [Fintype D] + (G : ConstraintGraph V (V × D) A) (htail : G.tail = Prod.fst) (extra : ℕ) + (labeling : V ⊕ Fin extra → A) : + (pad G extra).rejectionCount labeling = + G.rejectionCount (fun v => labeling (Sum.inl v)) := by + classical + simp only [rejectionCount_eq_sum, Fintype.sum_prod_type, Fintype.sum_sum_type] + simp only [edgeSatisfied_inl G htail, edgeSatisfied_inr] + simp + +variable (V : Type*) [Fintype V] + +def extraVertices : ℕ := ExpanderFamily.size (Fintype.card V) - Fintype.card V + +abbrev Vertex := V ⊕ Fin (extraVertices V) + +theorem card_vertex : Fintype.card (Vertex V) = ExpanderFamily.size (Fintype.card V) := by + rw [Fintype.card_sum, Fintype.card_fin] + exact Nat.add_sub_of_le (ExpanderFamily.le_size _) + +theorem le_card_vertex : Fintype.card V ≤ Fintype.card (Vertex V) := by + rw [card_vertex] + exact ExpanderFamily.le_size _ + +theorem card_vertex_le [Nonempty V] : + Fintype.card (Vertex V) ≤ ExpanderFamily.growth * Fintype.card V := by + rw [card_vertex] + exact ExpanderFamily.size_le_mul Fintype.card_pos + +noncomputable def familyVertexEquiv : + Vertex V ≃ ExpanderFamily.Vertex (ExpanderFamily.level (Fintype.card V)) := + Fintype.equivOfCardEq (by + rw [card_vertex, ExpanderFamily.card_vertex] + rfl) + +variable {V} + +def paddedG (G : ConstraintGraph V (V × D) A) : ConstraintGraph (Vertex V) (Vertex V × D) A := + pad G (extraVertices V) + +@[simp] theorem paddedG_tail (G : ConstraintGraph V (V × D) A) : + (paddedG G).tail = Prod.fst := rfl + +theorem paddedG_rejectionCount [Fintype D] + (G : ConstraintGraph V (V × D) A) (htail : G.tail = Prod.fst) + (labeling : Vertex V → A) : + (paddedG G).rejectionCount labeling = + G.rejectionCount (fun v => labeling (Sum.inl v)) := + pad_rejectionCount G htail (extraVertices V) labeling + +theorem rejectionCount_eq [Fintype D] + (G : ConstraintGraph V (V × D) A) (htail : G.tail = Prod.fst) + (labeling : Vertex V → A) : + (paddedG G).rejectionCount labeling = + G.rejectionCount (fun v => labeling (Sum.inl v)) := + paddedG_rejectionCount G htail labeling + +def liftLabel (defaultA : A) (labeling : V → A) : Vertex V → A := + extendLabeling (extraVertices V) defaultA labeling + +@[simp] theorem liftLabel_inl (defaultA : A) (labeling : V → A) (v : V) : + liftLabel defaultA labeling (Sum.inl v) = labeling v := rfl + +@[simp] theorem liftLabel_inr (defaultA : A) (labeling : V → A) + (w : Fin (extraVertices V)) : + liftLabel defaultA labeling (Sum.inr w) = defaultA := rfl + +theorem rejectionCount_liftLabel [Fintype D] + (G : ConstraintGraph V (V × D) A) (htail : G.tail = Prod.fst) + (defaultA : A) (labeling : V → A) : + (paddedG G).rejectionCount (liftLabel defaultA labeling) = G.rejectionCount labeling := by + simpa only [liftLabel_inl] using + paddedG_rejectionCount G htail (liftLabel defaultA labeling) + +theorem paddedG_satisfiable (G : ConstraintGraph V (V × D) A) (htail : G.tail = Prod.fst) + (defaultA : A) (hG : G.Satisfiable) : (paddedG G).Satisfiable := + pad_satisfiable G htail (extraVertices V) defaultA hG + +theorem card_padded_darts [Fintype D] : + Fintype.card (Vertex V × D) = ExpanderFamily.size (Fintype.card V) * Fintype.card D := by + rw [Fintype.card_prod, card_vertex] + +theorem card_padded_darts_le [Fintype D] [Nonempty V] : + Fintype.card (Vertex V × D) ≤ ExpanderFamily.growth * Fintype.card (V × D) := by + rw [Fintype.card_prod, Fintype.card_prod, ← Nat.mul_assoc] + exact Nat.mul_le_mul_right (Fintype.card D) (card_vertex_le V) + +end MinUncutGames.Foundations.PCP.VertexPadding + +namespace MinUncutGames.Foundations.PCP.PreprocessingPaddingTables + +open PoweringWalks PortTables + +variable {n m d : Nat} + +def vertexEquiv (h : n ≤ m) : Fin n ⊕ Fin (m - n) ≃ Fin m := + finSumFinEquiv.trans (finCongr (Nat.add_sub_of_le h)) + +@[simp] theorem vertexEquiv_inl (h : n ≤ m) (v : Fin n) : + vertexEquiv h (Sum.inl v) = v.castLE h := rfl + +@[simp] theorem vertexEquiv_inr_val (h : n ≤ m) (v : Fin (m - n)) : + (vertexEquiv h (Sum.inr v)).val = n + v.val := rfl + +@[simp] theorem vertexEquiv_symm_old (h : n ≤ m) (v : Fin n) : + (vertexEquiv h).symm (v.castLE h) = Sum.inl v := + (vertexEquiv h).symm_apply_apply (Sum.inl v) + +def dartEquiv (h : n ≤ m) : + (Fin n ⊕ Fin (m - n)) × Fin d ≃ Fin m × Fin d := + Equiv.prodCongr (vertexEquiv h) (Equiv.refl _) + +@[simp] theorem dartEquiv_apply (h : n ≤ m) + (v : Fin n ⊕ Fin (m - n)) (p : Fin d) : + dartEquiv h (v, p) = (vertexEquiv h v, p) := rfl + +def sumGraph (table : Table n d) (m : Nat) : + ConstraintGraph (Fin n ⊕ Fin (m - n)) + ((Fin n ⊕ Fin (m - n)) × Fin d) Label := + VertexPadding.pad (baseGraph table) (m - n) + +def paddedGraph (table : Table n d) (h : n ≤ m) : + ConstraintGraph (Fin m) (Fin m × Fin d) Label where + reverse := ((dartEquiv h).symm.trans (sumGraph table m).reverse).trans (dartEquiv h) + reverse_involutive e := by + change dartEquiv h ((sumGraph table m).reverse + ((dartEquiv h).symm (dartEquiv h ((sumGraph table m).reverse + ((dartEquiv h).symm e))))) = e + rw [Equiv.symm_apply_apply, (sumGraph table m).reverse_involutive, + Equiv.apply_symm_apply] + tail := Prod.fst + accepts e a b := (sumGraph table m).accepts ((dartEquiv h).symm e) a b + reverse_accepts e a b := by + change (sumGraph table m).accepts ((dartEquiv h).symm + (dartEquiv h ((sumGraph table m).reverse ((dartEquiv h).symm e)))) b a = _ + rw [Equiv.symm_apply_apply] + exact (sumGraph table m).reverse_accepts _ _ _ + +theorem paddedGraph_reverse_equiv (table : Table n d) (h : n ≤ m) + (e : (Fin n ⊕ Fin (m - n)) × Fin d) : + (paddedGraph table h).reverse (dartEquiv h e) = + dartEquiv h ((sumGraph table m).reverse e) := by + change dartEquiv h ((sumGraph table m).reverse + ((dartEquiv h).symm (dartEquiv h e))) = _ + rw [Equiv.symm_apply_apply] + +theorem paddedGraph_accepts_equiv (table : Table n d) (h : n ≤ m) + (e : (Fin n ⊕ Fin (m - n)) × Fin d) (a b : Label) : + (paddedGraph table h).accepts (dartEquiv h e) a b = + (sumGraph table m).accepts e a b := by + change (sumGraph table m).accepts ((dartEquiv h).symm (dartEquiv h e)) a b = _ + rw [Equiv.symm_apply_apply] + +def pad (table : Table n d) (h : n ≤ m) : Table m d := + ofPortGraph + { rot := (paddedGraph table h).reverse + rot_involutive := (paddedGraph table h).reverse_involutive } + (paddedGraph table h).accepts (paddedGraph table h).reverse_accepts + +@[simp] theorem rotation_pad (table : Table n d) (h : n ≤ m) (e : Fin m × Fin d) : + rotation (pad table h) e = (paddedGraph table h).reverse e := by + exact rotation_ofPortGraph _ _ _ e + +@[simp] theorem accepts_pad (table : Table n d) (h : n ≤ m) + (e : Fin m × Fin d) (a b : Label) : + PortTables.accepts (pad table h) e a b = (paddedGraph table h).accepts e a b := by + exact accepts_ofPortGraph _ _ _ e a b + +theorem pad_valid (table : Table n d) (h : n ≤ m) : + Function.Involutive (rotation (pad table h)) ∧ + ∀ e a b, PortTables.accepts (pad table h) (rotation (pad table h) e) b a = + PortTables.accepts (pad table h) e a b := + ⟨rotation_involutive (pad table h), accepts_rotation (pad table h)⟩ + +theorem constraintGraph_ext {V E A : Type*} {G H : ConstraintGraph V E A} + (hr : ∀ e, G.reverse e = H.reverse e) (ht : G.tail = H.tail) + (hp : G.accepts = H.accepts) : G = H := by + cases G with + | mk reverse hinv tail accepts htranspose => + cases H with + | mk reverse' hinv' tail' accepts' htranspose' => + dsimp only at hr ht hp + have he : reverse = reverse' := Equiv.ext hr + cases he + cases ht + cases hp + rfl + +@[simp] theorem baseGraph_pad (table : Table n d) (h : n ≤ m) : + baseGraph (pad table h) = paddedGraph table h := by + apply constraintGraph_ext + · exact rotation_pad table h + · rfl + · funext e a b + exact accepts_pad table h e a b + +theorem rotation_pad_equiv (table : Table n d) (h : n ≤ m) + (v : Fin n ⊕ Fin (m - n)) (p : Fin d) : + rotation (pad table h) (vertexEquiv h v, p) = + (vertexEquiv h ((sumGraph table m).reverse (v, p)).1, + ((sumGraph table m).reverse (v, p)).2) := by + rw [rotation_pad] + exact paddedGraph_reverse_equiv table h (v, p) + +@[simp] theorem rotation_pad_old (table : Table n d) (h : n ≤ m) + (v : Fin n) (p : Fin d) : + rotation (pad table h) (v.castLE h, p) = + ((rotation table (v, p)).1.castLE h, (rotation table (v, p)).2) := by + simpa only [sumGraph, VertexPadding.pad_reverse_inl, baseGraph_reverse, + vertexEquiv_inl] using rotation_pad_equiv table h (Sum.inl v) p + +@[simp] theorem rotation_pad_new (table : Table n d) (h : n ≤ m) + (v : Fin (m - n)) (p : Fin d) : + rotation (pad table h) (vertexEquiv h (Sum.inr v), p) = + (vertexEquiv h (Sum.inr v), p) := by + simpa only [sumGraph, VertexPadding.pad_reverse_inr] using + rotation_pad_equiv table h (Sum.inr v) p + +@[simp] theorem accepts_pad_old (table : Table n d) (h : n ≤ m) + (v : Fin n) (p : Fin d) (a b : Label) : + PortTables.accepts (pad table h) (v.castLE h, p) a b = PortTables.accepts table (v, p) a b := by + rw [accepts_pad] + exact paddedGraph_accepts_equiv table h (Sum.inl v, p) a b + +@[simp] theorem accepts_pad_new (table : Table n d) (h : n ≤ m) + (v : Fin (m - n)) (p : Fin d) (a b : Label) : + PortTables.accepts (pad table h) (vertexEquiv h (Sum.inr v), p) a b = true := by + rw [accepts_pad] + exact paddedGraph_accepts_equiv table h (Sum.inr v, p) a b + +theorem reverseIndex_pad_old (table : Table n d) (h : n ≤ m) + (v : Fin n) (p : Fin d) : + (pad table h).reverseIndex[rowIndex m d (v.castLE h, p)] = + rowIndex m d ((rotation table (v, p)).1.castLE h, (rotation table (v, p)).2) := by + rw [← rowIndex_rotation, rotation_pad_old] + +theorem reverseIndex_pad_new (table : Table n d) (h : n ≤ m) + (v : Fin (m - n)) (p : Fin d) : + (pad table h).reverseIndex[rowIndex m d (vertexEquiv h (Sum.inr v), p)] = + rowIndex m d (vertexEquiv h (Sum.inr v), p) := by + rw [← rowIndex_rotation, rotation_pad_new] + +theorem relation_ext {r s : GraphTables.RelationTable} + (h : ∀ a b, GraphTables.relationAt r a b = GraphTables.relationAt s a b) : r = s := by + apply Vector.ext + intro i hi + simpa only [GraphTables.relationAt, Prod.eta, Equiv.apply_symm_apply, + Fin.getElem_fin] using + h (GraphTables.relationIndex.symm ⟨i, hi⟩).1 + (GraphTables.relationIndex.symm ⟨i, hi⟩).2 + +theorem relations_pad_old (table : Table n d) (h : n ≤ m) + (v : Fin n) (p : Fin d) : + (pad table h).relations[rowIndex m d (v.castLE h, p)] = + table.relations[rowIndex n d (v, p)] := by + apply relation_ext + intro a b + exact accepts_pad_old table h v p a b + +theorem relations_pad_new (table : Table n d) (h : n ≤ m) + (v : Fin (m - n)) (p : Fin d) : + (pad table h).relations[rowIndex m d (vertexEquiv h (Sum.inr v), p)] = + Vector.replicate 4096 true := by + apply relation_ext + intro a b + simpa only [PortTables.accepts, GraphTables.relationAt, Fin.getElem_fin, + Vector.getElem_replicate] using + accepts_pad_new table h v p a b + +theorem paddedGraph_edgeSatisfied_equiv (table : Table n d) (h : n ≤ m) + (labeling : Fin m → Label) (e : (Fin n ⊕ Fin (m - n)) × Fin d) : + (paddedGraph table h).edgeSatisfied labeling (dartEquiv h e) = + (sumGraph table m).edgeSatisfied (fun v => labeling (vertexEquiv h v)) e := by + change (sumGraph table m).accepts ((dartEquiv h).symm (dartEquiv h e)) + (labeling (dartEquiv h e).1) + (labeling (dartEquiv h ((sumGraph table m).reverse + ((dartEquiv h).symm (dartEquiv h e)))).1) = + (sumGraph table m).accepts e (labeling (vertexEquiv h e.1)) + (labeling (vertexEquiv h ((sumGraph table m).reverse e).1)) + simp only [Equiv.symm_apply_apply] + rfl + +theorem edgeSatisfied_pad_equiv (table : Table n d) (h : n ≤ m) + (labeling : Fin m → Label) (e : (Fin n ⊕ Fin (m - n)) × Fin d) : + (baseGraph (pad table h)).edgeSatisfied labeling (dartEquiv h e) = + (sumGraph table m).edgeSatisfied (fun v => labeling (vertexEquiv h v)) e := by + rw [baseGraph_pad] + exact paddedGraph_edgeSatisfied_equiv table h labeling e + +@[simp] theorem edgeSatisfied_pad_old (table : Table n d) (h : n ≤ m) + (labeling : Fin m → Label) (v : Fin n) (p : Fin d) : + (baseGraph (pad table h)).edgeSatisfied labeling (v.castLE h, p) = + (baseGraph table).edgeSatisfied (fun v => labeling (v.castLE h)) (v, p) := by + simpa only [dartEquiv_apply, vertexEquiv_inl, sumGraph, + VertexPadding.edgeSatisfied_inl (baseGraph table) rfl] using + edgeSatisfied_pad_equiv table h labeling (Sum.inl v, p) + +@[simp] theorem edgeSatisfied_pad_new (table : Table n d) (h : n ≤ m) + (labeling : Fin m → Label) (v : Fin (m - n)) (p : Fin d) : + (baseGraph (pad table h)).edgeSatisfied labeling (vertexEquiv h (Sum.inr v), p) = true := by + simpa only [dartEquiv_apply, sumGraph, VertexPadding.edgeSatisfied_inr] using + edgeSatisfied_pad_equiv table h labeling (Sum.inr v, p) + +theorem pad_rejectionCount (table : Table n d) (h : n ≤ m) + (labeling : Fin m → Label) : + (baseGraph (pad table h)).rejectionCount labeling = + (baseGraph table).rejectionCount (fun v => labeling (v.castLE h)) := by + classical + calc + (baseGraph (pad table h)).rejectionCount labeling = + (sumGraph table m).rejectionCount (fun v => labeling (vertexEquiv h v)) := by + unfold ConstraintGraph.rejectionCount + symm + apply Finset.card_equiv (dartEquiv h) + intro e + simp only [ConstraintGraph.mem_rejectedDarts, edgeSatisfied_pad_equiv] + _ = (baseGraph table).rejectionCount (fun v => labeling (v.castLE h)) := by + simpa only [sumGraph, vertexEquiv_inl] using + VertexPadding.pad_rejectionCount (baseGraph table) rfl (m - n) + (fun v => labeling (vertexEquiv h v)) + +theorem pad_labeling_satisfies_iff (table : Table n d) (h : n ≤ m) + (labeling : Fin m → Label) : + (∀ e, (baseGraph (pad table h)).edgeSatisfied labeling e = true) ↔ + ∀ e, (baseGraph table).edgeSatisfied (fun v => labeling (v.castLE h)) e = true := by + constructor + · intro hs e + simpa only [edgeSatisfied_pad_old] using hs (e.1.castLE h, e.2) + · intro hs e + obtain ⟨v, hv⟩ := (vertexEquiv h).surjective e.1 + have he : e = (vertexEquiv h v, e.2) := Prod.ext hv.symm rfl + rw [he] + cases v with + | inl v => simpa only [vertexEquiv_inl, edgeSatisfied_pad_old] using hs (v, e.2) + | inr v => exact edgeSatisfied_pad_new table h labeling v e.2 + +def extendLabeling (h : n ≤ m) (labeling : Fin n → Label) : Fin m → Label := + fun v => Sum.elim labeling (fun _ => 0) ((vertexEquiv h).symm v) + +@[simp] theorem extendLabeling_old (h : n ≤ m) (labeling : Fin n → Label) (v : Fin n) : + extendLabeling h labeling (v.castLE h) = labeling v := by + simp only [extendLabeling, vertexEquiv_symm_old, Sum.elim_inl] + +theorem pad_satisfiable_iff (table : Table n d) (h : n ≤ m) : + (baseGraph (pad table h)).Satisfiable ↔ (baseGraph table).Satisfiable := by + constructor + · rintro ⟨labeling, hs⟩ + exact ⟨fun v => labeling (v.castLE h), (pad_labeling_satisfies_iff table h labeling).1 hs⟩ + · rintro ⟨labeling, hs⟩ + refine ⟨extendLabeling h labeling, (pad_labeling_satisfies_iff table h _).2 ?_⟩ + simpa only [extendLabeling_old] using hs + +end MinUncutGames.Foundations.PCP.PreprocessingPaddingTables + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/PreprocessingStageMaps.lean b/lean/OAI/Computability/MinUncut/PCP/PreprocessingStageMaps.lean new file mode 100644 index 0000000000000000000000000000000000000000..59da3ba332aeb5b19ea27deb382f00c7f6d6c3e5 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/PreprocessingStageMaps.lean @@ -0,0 +1,41 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.SpectralCut + +namespace OAI + +section +namespace MinUncutGames.Foundations.PCP.PreprocessingStageMaps +open PreprocessingRegularTables + +abbrev BaseTable := PreprocessingTables.BaseTable + +def regular (H : BaseTable) (t : GraphTables.Table) : PortTables.Input (internalDegree + 1) := + ⟨vertexCount t (PreprocessingRegularTables.padding t), regularize H t⟩ + +def padding (d : Nat) (input : PortTables.Input d) : PortTables.Input d := + ⟨PreprocessingLevels.paddedSize input.1, + PreprocessingPaddingTables.pad input.2 (PreprocessingLevels.le_paddedSize input.1)⟩ + +def familyAt (H : BaseTable) (n : Nat) : + ExpanderTables.Table (PreprocessingLevels.paddedSize n) internalDegree := + resizeTable (PreprocessingLevels.table_vertexCount_eq_paddedSize n) + (ExpanderTables.family H (PreprocessingLevels.boundedLevel n)) + +def paddedOverlay (H : BaseTable) (d : Nat) (input : PortTables.Input d) : + PortTables.Input (d + internalDegree) := + ⟨PreprocessingLevels.paddedSize input.1, + PreprocessingOverlayTables.overlay (padding d input).2 (familyAt H input.1)⟩ + +def lazy (d : Nat) (input : PortTables.Input d) : PortTables.Input (2 * d) := + ⟨input.1, PreprocessingOverlayTables.lazy input.2⟩ + +theorem output_eq (H : BaseTable) (t : GraphTables.Table) : + PreprocessingTables.output H t = + lazy ((internalDegree + 1) + internalDegree) + (paddedOverlay H (internalDegree + 1) (regular H t)) := rfl + +end MinUncutGames.Foundations.PCP.PreprocessingStageMaps + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/PreprocessingTableSpectral.lean b/lean/OAI/Computability/MinUncut/PCP/PreprocessingTableSpectral.lean new file mode 100644 index 0000000000000000000000000000000000000000..4bbfd16f9bfa8da50e992567dcb17b6b20d2d8cf --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/PreprocessingTableSpectral.lean @@ -0,0 +1,739 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.SpectralCut + +namespace OAI + +section +namespace MinUncutGames.Foundations.PCP.PreprocessingTableSpectral + +open PoweringWalks SpectralReturn + +private theorem portGraph_ext {V D : Type*} {G H : PortGraph V D} + (h : ∀ x, G.rot x = H.rot x) : G = H := by + have hr : G.rot = H.rot := Equiv.ext h + cases G + cases H + cases hr + rfl + +theorem materialize_portGraph {n d : Nat} {D : Type*} + (G : ConstraintGraph (Fin n) (Fin n × D) PortTables.Label) + (ports : D ≃ Fin d) : + PortTables.portGraph (PreprocessingOverlayTables.materialize G ports) = + GraphTransport.reindex (Overlay.originalPortGraph G) (Equiv.refl _) ports := by + apply portGraph_ext + intro x + rw [PortTables.portGraph_rot, PreprocessingOverlayTables.rotation_materialize] + rfl + +theorem overlay_portGraph {n d e : Nat} (G : PortTables.Table n d) + (H : ExpanderTables.Table n e) : + PortTables.portGraph (PreprocessingOverlayTables.overlay G H) = + GraphTransport.reindex + (Overlay.portGraph (PortTables.portGraph G) (ExpanderTables.graph H)) + (Equiv.refl _) (PreprocessingOverlayTables.overlayPorts d e) := by + unfold PreprocessingOverlayTables.overlay + rw [materialize_portGraph] + rfl + +theorem overlay_rotation_eq {n d e : Nat} (G : PortTables.Table n d) + (H : ExpanderTables.Table n e) (x : Fin n × Fin (d + e)) : + PortTables.rotation (PreprocessingOverlayTables.overlay G H) x = + (GraphTransport.reindex + (Overlay.portGraph (PortTables.portGraph G) (ExpanderTables.graph H)) + (Equiv.refl _) (PreprocessingOverlayTables.overlayPorts d e)).rot x := by + change (PortTables.portGraph (PreprocessingOverlayTables.overlay G H)).rot x = _ + rw [overlay_portGraph] + +theorem lazy_portGraph {n d : Nat} (G : PortTables.Table n d) : + PortTables.portGraph (PreprocessingOverlayTables.lazy G) = + GraphTransport.reindex (lazyGraph (PortTables.portGraph G)) + (Equiv.refl _) (PreprocessingOverlayTables.lazyPorts d) := by + unfold PreprocessingOverlayTables.lazy + rw [materialize_portGraph] + rfl + +theorem lazy_rotation_eq {n d : Nat} (G : PortTables.Table n d) + (x : Fin n × Fin (2 * d)) : + PortTables.rotation (PreprocessingOverlayTables.lazy G) x = + (GraphTransport.reindex (lazyGraph (PortTables.portGraph G)) + (Equiv.refl _) (PreprocessingOverlayTables.lazyPorts d)).rot x := by + change (PortTables.portGraph (PreprocessingOverlayTables.lazy G)).rot x = _ + rw [lazy_portGraph] + +theorem overlay_certificate_seven_eighths {n d e : Nat} + (G : PortTables.Table n d) (H : ExpanderTables.Table n e) + (hn : 0 < n) (hdegree : d = e + 1) (he : 8 ≤ e) + (hH : SpectralCertificate (ExpanderTables.graph H) (1 / 2 : ℝ)) : + SpectralCertificate (PortTables.portGraph (PreprocessingOverlayTables.overlay G H)) + (7 / 8 : ℝ) := by + let : Nonempty (Fin n) := ⟨⟨0, hn⟩⟩ + rw [overlay_portGraph] + apply GraphTransport.reindex_spectralCertificate + apply Overlay.spectralCertificate_seven_eighths + (PortTables.portGraph G) (ExpanderTables.graph H) + · simpa only [Fintype.card_fin] using hdegree + · simp only [Fintype.card_fin] + omega + · exact hH + +theorem lazy_certificate_31_32 {n d : Nat} (G : PortTables.Table n d) + (hd : 0 < d) (hG : SpectralCertificate (PortTables.portGraph G) (7 / 8 : ℝ)) : + SpectralCertificate (PortTables.portGraph (PreprocessingOverlayTables.lazy G)) + (31 / 32 : ℝ) := by + let : Nonempty (Fin d) := ⟨⟨0, hd⟩⟩ + rw [lazy_portGraph] + exact GraphTransport.reindex_spectralCertificate _ _ _ _ + (LazySpectral.lazy_certificate_31_32 (PortTables.portGraph G) hG) + +end MinUncutGames.Foundations.PCP.PreprocessingTableSpectral + +end +section +noncomputable section + +namespace MinUncutGames.Foundations.PCP.PreprocessingGuarantees + +open PoweringWalks SpectralReturn PreprocessingTables +open PreprocessingRegularTables (internalDegree regularize) + +variable {n d e : Nat} + +theorem overlay_rejectionCount (G : PortTables.Table n d) (H : ExpanderTables.Table n e) + (labels : Fin n → GraphTables.Label) : + (PortTables.baseGraph (PreprocessingOverlayTables.overlay G H)).rejectionCount labels = + (PortTables.baseGraph G).rejectionCount labels := by + rw [PreprocessingOverlayTables.overlay_semantics] + calc + _ = (Overlay.constraintGraph (PortTables.baseGraph G) (ExpanderTables.graph H)).rejectionCount labels := by + convert ConstraintGraph.reindex_rejectionCount + (Overlay.constraintGraph (PortTables.baseGraph G) (ExpanderTables.graph H)) + (Equiv.refl _) (Equiv.prodCongr (Equiv.refl _) + (PreprocessingOverlayTables.overlayPorts d e)) (Equiv.refl _) labels using 1 + rfl + _ = _ := Overlay.rejectionCount_eq _ _ rfl labels + +theorem lazy_rejectionCount (G : PortTables.Table n d) + (labels : Fin n → GraphTables.Label) : + (PortTables.baseGraph (PreprocessingOverlayTables.lazy G)).rejectionCount labels = + (PortTables.baseGraph G).rejectionCount labels := by + rw [PreprocessingOverlayTables.lazy_semantics] + calc + _ = (LazyConstraint.constraintGraph (PortTables.baseGraph G)).rejectionCount labels := by + convert ConstraintGraph.reindex_rejectionCount + (LazyConstraint.constraintGraph (PortTables.baseGraph G)) + (Equiv.refl _) (Equiv.prodCongr (Equiv.refl _) + (PreprocessingOverlayTables.lazyPorts d)) (Equiv.refl _) labels using 1 + rfl + _ = _ := LazyConstraint.rejectionCount_eq _ rfl labels + +theorem overlayFamily_certificate (H : BaseTable) + (certificate : SpectralCertificate (ExpanderTables.graph H) (1 / 100 : ℝ)) + (t : GraphTables.Table) : + SpectralCertificate (ExpanderTables.graph (overlayFamily H t)) (1 / 2 : ℝ) := by + let : NeZero Expanders.baseDegree := ⟨PreprocessingRegularSoundness.baseDegree_ne_zero⟩ + apply PreprocessingRegularSoundness.resizeTable_certificate + exact ExpanderTables.family_certificate H certificate _ + +theorem overlay_certificate (H : BaseTable) + (certificate : SpectralCertificate (ExpanderTables.graph H) (1 / 100 : ℝ)) + (t : GraphTables.Table) : + SpectralCertificate (PortTables.portGraph + (PreprocessingOverlayTables.overlay (padded H t) (overlayFamily H t))) (7 / 8 : ℝ) := + PreprocessingTableSpectral.overlay_certificate_seven_eighths _ _ + (vertices_positive t) rfl PreprocessingRegularSoundness.internalDegree_ge_eight + (overlayFamily_certificate H certificate t) + +theorem spectral_certificate (H : BaseTable) + (certificate : SpectralCertificate (ExpanderTables.graph H) (1 / 100 : ℝ)) + (t : GraphTables.Table) : + SpectralCertificate (PortTables.portGraph (preprocess H t)) (31 / 32 : ℝ) := by + apply PreprocessingTableSpectral.lazy_certificate_31_32 + · omega + · exact overlay_certificate H certificate t + +def restrictedLabel (t : GraphTables.Table) + (labels : Fin (vertices t) → GraphTables.Label) : + Fin (regularVertices t) → GraphTables.Label := + fun v => labels (v.castLE (PreprocessingLevels.le_paddedSize (regularVertices t))) + +theorem rejectionCount_eq_regularized (H : BaseTable) (t : GraphTables.Table) + (labels : Fin (vertices t) → GraphTables.Label) : + (PortTables.baseGraph (preprocess H t)).rejectionCount labels = + (PortTables.baseGraph (regularize H t)).rejectionCount (restrictedLabel t labels) := by + unfold preprocess PreprocessingTables.degree + rw [lazy_rejectionCount, overlay_rejectionCount] + exact PreprocessingPaddingTables.pad_rejectionCount _ _ labels + +def roundLabels (t : GraphTables.Table) + (labels : Fin (vertices t) → GraphTables.Label) : Fin t.vertices → GraphTables.Label := + PreprocessingRegularSoundness.roundLabels t (restrictedLabel t labels) + +theorem soundness (H : BaseTable) + (certificate : SpectralCertificate (ExpanderTables.graph H) (1 / 100 : ℝ)) + (t : GraphTables.Table) (labels : Fin (vertices t) → GraphTables.Label) : + (GraphTables.semantics t).rejectionCount (roundLabels t labels) ≤ + (PortTables.baseGraph (preprocess H t)).rejectionCount labels := by + rw [rejectionCount_eq_regularized] + exact PreprocessingRegularSoundness.soundness H certificate t (restrictedLabel t labels) + +theorem completeness (H : BaseTable) (t : GraphTables.Table) + (h : (GraphTables.semantics t).Satisfiable) : + (PortTables.baseGraph (preprocess H t)).Satisfiable := by + have hp : (PortTables.baseGraph (padded H t)).Satisfiable := + (PreprocessingPaddingTables.pad_satisfiable_iff _ _).mpr + (PreprocessingRegularSoundness.completeness H t h) + obtain ⟨labels, hlabels⟩ := hp + refine ⟨labels, ?_⟩ + apply (ConstraintGraph.rejectionCount_eq_zero_iff _ labels).mp + unfold preprocess PreprocessingTables.degree + rw [lazy_rejectionCount, overlay_rejectionCount] + exact (ConstraintGraph.rejectionCount_eq_zero_iff _ labels).mpr hlabels + +theorem gap_transfer_real (H : BaseTable) + (certificate : SpectralCertificate (ExpanderTables.graph H) (1 / 100 : ℝ)) + (t : GraphTables.Table) (ht : 0 < t.darts) + (epsilon : ℝ) (he : 0 ≤ epsilon) + (lower : ∀ labels : Fin t.vertices → GraphTables.Label, + epsilon * t.darts ≤ ((GraphTables.semantics t).rejectionCount labels : ℝ)) + (labels : Fin (vertices t) → GraphTables.Label) : + (epsilon / Preprocessing.sizeFactor) * + Fintype.card (Fin (vertices t) × Fin PreprocessingTables.degree) ≤ + ((PortTables.baseGraph (preprocess H t)).rejectionCount labels : ℝ) := by + have hs : (0 : ℝ) < Preprocessing.sizeFactor := + Nat.cast_pos.mpr Preprocessing.sizeFactor_positive + have hcount : Fintype.card (Fin (vertices t) × Fin PreprocessingTables.degree) ≤ + Preprocessing.sizeFactor * t.darts := by + simp only [Fintype.card_prod, Fintype.card_fin] + calc + _ ≤ (ExpanderFamily.growth ^ 2 * t.darts) * PreprocessingTables.degree := + Nat.mul_le_mul_right _ (vertices_le_of_positive t ht) + _ = _ := by rw [PreprocessingTables.degree_eq]; unfold Preprocessing.sizeFactor; ring + have hcountR : (Fintype.card (Fin (vertices t) × Fin PreprocessingTables.degree) : ℝ) ≤ + (Preprocessing.sizeFactor : ℝ) * t.darts := by exact_mod_cast hcount + calc + _ ≤ (epsilon / Preprocessing.sizeFactor) * + ((Preprocessing.sizeFactor : ℝ) * t.darts) := + mul_le_mul_of_nonneg_left hcountR (div_nonneg he hs.le) + _ = epsilon * t.darts := by field_simp + _ ≤ ((GraphTables.semantics t).rejectionCount (roundLabels t labels) : ℝ) := lower _ + _ ≤ _ := Nat.cast_le.mpr (soundness H certificate t labels) + +end MinUncutGames.Foundations.PCP.PreprocessingGuarantees + +end +end +section +namespace MinUncutGames.Foundations.PCP.PoweringLabels + +open PoweringWalks +open scoped BigOperators + +variable {V D A : Type*} + +abbrev PortWords (D : Type*) (t : Nat) := (n : Fin (t + 1)) × (Fin n.val → D) + +instance finitePortWords [Finite D] (t : Nat) : Finite (PortWords D t) := by + let := Fintype.ofFinite D + exact Finite.of_fintype _ + +def Ball (G : PortGraph V D) (t : Nat) (v : V) := + {u : V // ∃ n, n ≤ t ∧ ∃ p : Fin n → D, wordEnd G n v p = u} + +def wordToBall (G : PortGraph V D) (t : Nat) (v : V) (w : PortWords D t) : Ball G t v := + ⟨wordEnd G w.1.val v w.2, w.1.val, Nat.le_of_lt_succ w.1.isLt, w.2, rfl⟩ + +theorem wordToBall_surjective (G : PortGraph V D) (t : Nat) (v : V) : + Function.Surjective (wordToBall G t v) := by + intro u + obtain ⟨n, hn, p, hp⟩ := u.property + refine ⟨⟨⟨n, Nat.lt_succ_of_le hn⟩, p⟩, ?_⟩ + exact Subtype.ext hp + +instance finiteBall [Finite D] (G : PortGraph V D) (t : Nat) (v : V) : + Finite (Ball G t v) := + Finite.of_surjective (wordToBall G t v) (wordToBall_surjective G t v) + +theorem card_portWords [Finite D] (t : Nat) : + Nat.card (PortWords D t) = ∑ n : Fin (t + 1), Nat.card D ^ n.val := by + simp [PortWords, Nat.card_sigma, Nat.card_fun] + +theorem card_ball_le [Finite D] (G : PortGraph V D) (t : Nat) (v : V) : + Nat.card (Ball G t v) ≤ ∑ n : Fin (t + 1), Nat.card D ^ n.val := by + calc + _ ≤ Nat.card (PortWords D t) := Nat.card_le_card_of_surjective + (wordToBall G t v) (wordToBall_surjective G t v) + _ = _ := card_portWords t + +structure AddressSelector (G : PortGraph V D) (t : Nat) (v : V) where + address : Ball G t v → PortWords D t + correct : ∀ u, wordToBall G t v (address u) = u + +noncomputable def classicalSelector (G : PortGraph V D) (t : Nat) (v : V) : + AddressSelector G t v where + address u := Classical.choose (wordToBall_surjective G t v u) + correct u := Classical.choose_spec (wordToBall_surjective G t v u) + +def scanWitness {A : Type*} (p : A → Prop) [DecidablePred p] : + (xs : List A) → (∃ a ∈ xs, p a) → {a // p a} + | [], h => False.elim (by simp at h) + | a :: xs, h => + if ha : p a then ⟨a, ha⟩ else + scanWitness p xs (by + obtain ⟨b, hb, hp⟩ := h + rcases List.mem_cons.mp hb with he | hm + · exact False.elim (ha (he ▸ hp)) + · exact ⟨b, hm, hp⟩) + +def listSelector [DecidableEq V] (G : PortGraph V D) (t : Nat) (v : V) + (addresses : List (PortWords D t)) (complete : ∀ w, w ∈ addresses) : + AddressSelector G t v where + address u := (scanWitness (fun w => (wordToBall G t v w).val = u.val) addresses (by + obtain ⟨w, hw⟩ := wordToBall_surjective G t v u + exact ⟨w, complete w, congrArg Subtype.val hw⟩)).val + correct u := Subtype.ext (scanWitness + (fun w => (wordToBall G t v w).val = u.val) addresses (by + obtain ⟨w, hw⟩ := wordToBall_surjective G t v u + exact ⟨w, complete w, congrArg Subtype.val hw⟩)).property + +abbrev PaddedLabel (D : Type*) (t : Nat) (A : Type*) := PortWords D t → A + +def encode (G : PortGraph V D) (t : Nat) (v : V) (ℓ : Ball G t v → A) : + PaddedLabel D t A := fun w => ℓ (wordToBall G t v w) + +def decode {G : PortGraph V D} {t : Nat} {v : V} (S : AddressSelector G t v) + (a : PaddedLabel D t A) : Ball G t v → A := fun u => a (S.address u) + +theorem decode_encode {G : PortGraph V D} {t : Nat} {v : V} + (S : AddressSelector G t v) (ℓ : Ball G t v → A) : + decode S (encode G t v ℓ) = ℓ := by + funext u + change ℓ (wordToBall G t v (S.address u)) = ℓ u + rw [S.correct] + +theorem decode_surjective {G : PortGraph V D} {t : Nat} {v : V} + (S : AddressSelector G t v) : Function.Surjective (decode (A := A) S) := + fun ℓ => ⟨encode G t v ℓ, decode_encode S ℓ⟩ + +theorem encode_injective (G : PortGraph V D) (t : Nat) (v : V) : + Function.Injective (encode (A := A) G t v) := by + intro a b h + funext u + obtain ⟨w, rfl⟩ := wordToBall_surjective G t v u + exact congrFun h w + +theorem decoded_word_collision {G : PortGraph V D} {t : Nat} {v : V} + (S : AddressSelector G t v) (a : PaddedLabel D t A) (w z : PortWords D t) + (h : (wordToBall G t v w).val = (wordToBall G t v z).val) : + decode S a (wordToBall G t v w) = decode S a (wordToBall G t v z) := + congrArg (decode S a) (Subtype.ext h) + +theorem card_paddedLabel [Finite D] [Finite A] (t : Nat) : + Nat.card (PaddedLabel D t A) = + Nat.card A ^ (∑ n : Fin (t + 1), Nat.card D ^ n.val) := by + rw [Nat.card_fun, card_portWords] + +end MinUncutGames.Foundations.PCP.PoweringLabels + +end +section +namespace MinUncutGames.Foundations.PCP.PoweringAddresses + +open PoweringWalks PoweringLabels +open scoped BigOperators + +variable {V : Type*} + +def allWords (d : Nat) : (n : Nat) → List (Fin n → Fin d) + | 0 => [Fin.elim0] + | n + 1 => (List.finRange d).flatMap fun a => + (allWords d n).map fun p => Fin.cases a p + +theorem mem_allWords (d : Nat) : + ∀ n (p : Fin n → Fin d), p ∈ allWords d n := by + intro n + induction n with + | zero => + intro p + simp only [allWords, List.mem_singleton] + funext i + exact Fin.elim0 i + | succ n ih => + intro p + simp only [allWords, List.mem_flatMap, List.mem_map] + refine ⟨p 0, List.mem_finRange (p 0), (fun j => p j.succ), ih _, ?_⟩ + funext j + exact Fin.cases rfl (fun _ => rfl) j + +def allAddresses (d t : Nat) : List (PortWords (Fin d) t) := + (List.finRange (t + 1)).flatMap fun n => + (allWords d n.val).map fun p => Sigma.mk n p + +theorem mem_allAddresses (d t : Nat) (w : PortWords (Fin d) t) : + w ∈ allAddresses d t := by + rcases w with ⟨n, p⟩ + unfold allAddresses + apply List.mem_flatMap.mpr + refine ⟨n, List.mem_finRange n, ?_⟩ + exact List.mem_map.mpr ⟨p, mem_allWords d n.val p, rfl⟩ + +theorem length_allWords (d : Nat) : + ∀ n, (allWords d n).length = d ^ n := by + intro n + induction n with + | zero => rfl + | succ n ih => + simp only [allWords, List.length_flatMap, List.length_map, ih, + List.map_const', List.length_finRange, List.sum_replicate_nat] + exact (Nat.mul_comm d (d ^ n)).trans (Nat.pow_succ d n).symm + +theorem length_allAddresses (d t : Nat) : + (allAddresses d t).length = ∑ n : Fin (t + 1), d ^ n.val := by + unfold allAddresses + simp only [List.length_flatMap, List.length_map, length_allWords] + exact (Fin.sum_univ_def (fun n : Fin (t + 1) => d ^ n.val)).symm + +def finitePortSelector {d : Nat} [DecidableEq V] (G : PortGraph V (Fin d)) + (t : Nat) (v : V) : AddressSelector G t v := + listSelector G t v (allAddresses d t) (mem_allAddresses d t) + +end MinUncutGames.Foundations.PCP.PoweringAddresses + +end +section +namespace MinUncutGames.Foundations.PCP.PoweringEnumeration + +open PoweringLabels +open scoped BigOperators + +def addressCount (d t : Nat) : Nat := ∑ i : Fin (t + 1), d ^ i.val + +def reverseWordEquiv (d n : Nat) : (Fin n → Fin d) ≃ (Fin n → Fin d) where + toFun p i := p i.rev + invFun p i := p i.rev + left_inv p := by funext i; simp only [Fin.rev_rev] + right_inv p := by funext i; simp only [Fin.rev_rev] + +def wordEquiv (d n : Nat) : (Fin n → Fin d) ≃ Fin (d ^ n) := + (reverseWordEquiv d n).trans finFunctionFinEquiv + +theorem wordEquiv_val (d n : Nat) (p : Fin n → Fin d) : + (wordEquiv d n p).val = ∑ i : Fin n, (p i.rev).val * d ^ i.val := rfl + +def addressEquiv (d t : Nat) : PortWords (Fin d) t ≃ Fin (addressCount d t) := + (Equiv.sigmaCongrRight (fun i : Fin (t + 1) => wordEquiv d i.val)).trans + finSigmaFinEquiv + +theorem addressEquiv_val (d t : Nat) (w : PortWords (Fin d) t) : + (addressEquiv d t w).val = + (∑ i : Fin w.1.val, d ^ i.val) + (wordEquiv d w.1.val w.2).val := by + change (finSigmaFinEquiv + (⟨w.1, wordEquiv d w.1.val w.2⟩ : (i : Fin (t + 1)) × Fin (d ^ i.val))).val = _ + rw [finSigmaFinEquiv_apply] + rfl + +def paddedLabelEquiv (d t q : Nat) : + PaddedLabel (Fin d) t (Fin q) ≃ Fin (q ^ addressCount d t) := + ((addressEquiv d t).arrowCongr (Equiv.refl (Fin q))).trans + (wordEquiv q (addressCount d t)) + +theorem paddedLabelEquiv_val (d t q : Nat) (a : PaddedLabel (Fin d) t (Fin q)) : + (paddedLabelEquiv d t q a).val = + ∑ i : Fin (addressCount d t), + (a ((addressEquiv d t).symm i.rev)).val * q ^ i.val := rfl + +def orientationEquiv : Bool ≃ Fin 2 := finTwoEquiv.symm + +@[simp] theorem orientationEquiv_false : orientationEquiv false = 0 := rfl +@[simp] theorem orientationEquiv_true : orientationEquiv true = 1 := rfl + +def dartBlockEquiv (d n : Nat) : + ((Fin (n + 1) → Fin d) × Bool) ≃ Fin (2 * d ^ (n + 1)) := + ((wordEquiv d (n + 1)).prodCongr orientationEquiv).trans + (finProdFinEquiv.trans (finCongr (Nat.mul_comm (d ^ (n + 1)) 2))) + +theorem dartBlockEquiv_val (d n : Nat) (p : Fin (n + 1) → Fin d) (b : Bool) : + (dartBlockEquiv d n (p, b)).val = + 2 * (wordEquiv d (n + 1) p).val + (orientationEquiv b).val := by + change (orientationEquiv b).val + 2 * (wordEquiv d (n + 1) p).val = _ + exact Nat.add_comm _ _ + +def dartVertexEquiv (vertices d n : Nat) : + (Bool × (Fin vertices × (Fin (n + 1) → Fin d))) ≃ + (Fin vertices × ((Fin (n + 1) → Fin d) × Bool)) where + toFun x := (x.2.1, (x.2.2, x.1)) + invFun x := (x.2.2, (x.1, x.2.1)) + left_inv x := by rcases x with ⟨b, v, p⟩; rfl + right_inv x := by rcases x with ⟨v, p, b⟩; rfl + +def dartEquiv (vertices d n : Nat) : + (Bool × (Fin vertices × (Fin (n + 1) → Fin d))) ≃ + Fin (2 * vertices * d ^ (n + 1)) := + (dartVertexEquiv vertices d n).trans + (((Equiv.refl (Fin vertices)).prodCongr (dartBlockEquiv d n)).trans + (finProdFinEquiv.trans + (finCongr (show vertices * (2 * d ^ (n + 1)) = + 2 * vertices * d ^ (n + 1) by ac_rfl)))) + +theorem dartEquiv_val (vertices d n : Nat) (b : Bool) (v : Fin vertices) + (p : Fin (n + 1) → Fin d) : + (dartEquiv vertices d n (b, (v, p))).val = + (2 * d ^ (n + 1)) * v.val + + 2 * (wordEquiv d (n + 1) p).val + (orientationEquiv b).val := by + change (dartBlockEquiv d n (p, b)).val + (2 * d ^ (n + 1)) * v.val = _ + rw [dartBlockEquiv_val] + omega + +theorem dartEquiv_true_eq_false_add_one (vertices d n : Nat) (v : Fin vertices) + (p : Fin (n + 1) → Fin d) : + (dartEquiv vertices d n (true, (v, p))).val = + (dartEquiv vertices d n (false, (v, p))).val + 1 := by + rw [dartEquiv_val, dartEquiv_val, orientationEquiv_true, orientationEquiv_false] + rfl + +def encodeWord (d n : Nat) : (Fin n → Fin d) → Fin (d ^ n) := wordEquiv d n +def decodeWord (d n : Nat) : Fin (d ^ n) → (Fin n → Fin d) := (wordEquiv d n).symm + +@[simp] theorem decodeWord_encodeWord (d n : Nat) (p : Fin n → Fin d) : + decodeWord d n (encodeWord d n p) = p := (wordEquiv d n).symm_apply_apply p + +@[simp] theorem encodeWord_decodeWord (d n : Nat) (i : Fin (d ^ n)) : + encodeWord d n (decodeWord d n i) = i := (wordEquiv d n).apply_symm_apply i + +def encodeAddress (d t : Nat) : PortWords (Fin d) t → Fin (addressCount d t) := + addressEquiv d t + +def decodeAddress (d t : Nat) : Fin (addressCount d t) → PortWords (Fin d) t := + (addressEquiv d t).symm + +@[simp] theorem decodeAddress_encodeAddress (d t : Nat) (w : PortWords (Fin d) t) : + decodeAddress d t (encodeAddress d t w) = w := (addressEquiv d t).symm_apply_apply w + +@[simp] theorem encodeAddress_decodeAddress (d t : Nat) (i : Fin (addressCount d t)) : + encodeAddress d t (decodeAddress d t i) = i := (addressEquiv d t).apply_symm_apply i + +def encodeLabel (d t q : Nat) : + PaddedLabel (Fin d) t (Fin q) → Fin (q ^ addressCount d t) := paddedLabelEquiv d t q + +def decodeLabel (d t q : Nat) : + Fin (q ^ addressCount d t) → PaddedLabel (Fin d) t (Fin q) := + (paddedLabelEquiv d t q).symm + +@[simp] theorem decodeLabel_encodeLabel (d t q : Nat) (a : PaddedLabel (Fin d) t (Fin q)) : + decodeLabel d t q (encodeLabel d t q a) = a := (paddedLabelEquiv d t q).symm_apply_apply a + +@[simp] theorem encodeLabel_decodeLabel (d t q : Nat) (i : Fin (q ^ addressCount d t)) : + encodeLabel d t q (decodeLabel d t q i) = i := (paddedLabelEquiv d t q).apply_symm_apply i + +@[simp] theorem decodeLabel_apply (d t q : Nat) (i : Fin (q ^ addressCount d t)) + (w : PortWords (Fin d) t) : + decodeLabel d t q i w = decodeWord q (addressCount d t) i (encodeAddress d t w) := rfl + +def encodeDart (vertices d n : Nat) : + (Bool × (Fin vertices × (Fin (n + 1) → Fin d))) → + Fin (2 * vertices * d ^ (n + 1)) := dartEquiv vertices d n + +def decodeDart (vertices d n : Nat) : + Fin (2 * vertices * d ^ (n + 1)) → + (Bool × (Fin vertices × (Fin (n + 1) → Fin d))) := (dartEquiv vertices d n).symm + +@[simp] theorem decodeDart_encodeDart (vertices d n : Nat) + (e : Bool × (Fin vertices × (Fin (n + 1) → Fin d))) : + decodeDart vertices d n (encodeDart vertices d n e) = e := + (dartEquiv vertices d n).symm_apply_apply e + +@[simp] theorem encodeDart_decodeDart (vertices d n : Nat) + (i : Fin (2 * vertices * d ^ (n + 1))) : + encodeDart vertices d n (decodeDart vertices d n i) = i := + (dartEquiv vertices d n).apply_symm_apply i + +theorem card_words (d n : Nat) : Nat.card (Fin n → Fin d) = d ^ n := by + simpa only [Nat.card_fin] using Nat.card_congr (wordEquiv d n) + +theorem card_addresses (d t : Nat) : + Nat.card (PortWords (Fin d) t) = addressCount d t := by + simpa only [Nat.card_fin] using Nat.card_congr (addressEquiv d t) + +theorem card_labels (d t q : Nat) : + Nat.card (PaddedLabel (Fin d) t (Fin q)) = q ^ addressCount d t := by + simpa only [Nat.card_fin] using Nat.card_congr (paddedLabelEquiv d t q) + +theorem card_darts (vertices d n : Nat) : + Nat.card (Bool × (Fin vertices × (Fin (n + 1) → Fin d))) = + 2 * vertices * d ^ (n + 1) := by + simpa only [Nat.card_fin] using Nat.card_congr (dartEquiv vertices d n) + +theorem length_allAddresses (d t : Nat) : + (PoweringAddresses.allAddresses d t).length = addressCount d t := + PoweringAddresses.length_allAddresses d t + +end MinUncutGames.Foundations.PCP.PoweringEnumeration + +end +section +namespace MinUncutGames.Foundations.PCP.PoweringDecoding + +open scoped BigOperators + +variable {Ω A : Type*} [Fintype Ω] [Nonempty Ω] [Fintype A] [Nonempty A] + +noncomputable def mass (opinion : Ω → A) (a : A) : ℝ := by + classical + exact Finset.univ.expect (fun ω => if opinion ω = a then 1 else 0) + +omit [Nonempty A] in +theorem mass_sum (opinion : Ω → A) : (∑ a, mass opinion a) = 1 := by + classical + calc + (∑ a, mass opinion a) = + (Finset.univ : Finset Ω).expect + (fun ω => ∑ a : A, if opinion ω = a then (1 : ℝ) else 0) := + (Finset.expect_sum_comm (Finset.univ : Finset Ω) (Finset.univ : Finset A) + (fun ω a => if opinion ω = a then (1 : ℝ) else 0)).symm + _ = (Finset.univ : Finset Ω).expect (fun _ => (1 : ℝ)) := by + apply Finset.expect_congr rfl + intro ω _ + simp + _ = 1 := Finset.expect_const Finset.univ_nonempty 1 + +omit [Nonempty Ω] in +theorem exists_mode (opinion : Ω → A) : + ∃ a : A, ∀ b : A, mass opinion b ≤ mass opinion a := by + obtain ⟨a, _, ha⟩ := Finset.exists_max_image (Finset.univ : Finset A) + (mass opinion) Finset.univ_nonempty + exact ⟨a, fun b => ha b (Finset.mem_univ b)⟩ + +noncomputable def mode (opinion : Ω → A) : A := Classical.choose (exists_mode opinion) + +omit [Nonempty Ω] in +theorem mode_max (opinion : Ω → A) (b : A) : + mass opinion b ≤ mass opinion (mode opinion) := + Classical.choose_spec (exists_mode opinion) b + +theorem mode_mass_lower (opinion : Ω → A) : + 1 / (Fintype.card A : ℝ) ≤ mass opinion (mode opinion) := by + have hk : 0 < (Fintype.card A : ℝ) := Nat.cast_pos.mpr Fintype.card_pos + have hsum : (1 : ℝ) ≤ mass opinion (mode opinion) * (Fintype.card A : ℝ) := by + calc + (1 : ℝ) = ∑ a : A, mass opinion a := (mass_sum opinion).symm + _ ≤ ∑ _a : A, mass opinion (mode opinion) := + Finset.sum_le_sum (fun a _ => mode_max opinion a) + _ = mass opinion (mode opinion) * (Fintype.card A : ℝ) := by simp [mul_comm] + exact (div_le_iff₀ hk).2 hsum + +theorem exists_letter_mass_lower (opinion : Ω → A) : + ∃ a : A, 1 / (Fintype.card A : ℝ) ≤ mass opinion a := + ⟨mode opinion, mode_mass_lower opinion⟩ + +end MinUncutGames.Foundations.PCP.PoweringDecoding + +end +section +noncomputable section + +namespace MinUncutGames.Foundations.PCP.PoweringMoment + +open scoped BigOperators + +def bit (p : Prop) : ℝ := by + classical + exact if p then 1 else 0 + +def hits {I Ω : Type*} [Fintype I] (E : I → Ω → Prop) (ω : Ω) : ℝ := + ∑ i, bit (E i ω) + +def mean {Ω : Type*} [Fintype Ω] (f : Ω → ℝ) : ℝ := Finset.univ.expect f + +theorem bit_nonneg (p : Prop) : 0 ≤ bit p := by + classical + by_cases hp : p <;> simp [bit, hp] + +theorem bit_sq (p : Prop) : bit p ^ 2 = bit p := by + classical + by_cases hp : p <;> simp [bit, hp] + +theorem bit_mul (p q : Prop) : bit p * bit q = bit (p ∧ q) := by + classical + by_cases hp : p <;> by_cases hq : q <;> simp [bit, hp, hq] + +theorem bit_mono {p q : Prop} (hpq : p → q) : bit p ≤ bit q := by + classical + by_cases hp : p + · simp [bit, hp, hpq hp] + · have hz : bit p = 0 := by simp [bit, hp] + rw [hz] + exact bit_nonneg q + +theorem hits_nonneg {I Ω : Type*} [Fintype I] (E : I → Ω → Prop) (ω : Ω) : + 0 ≤ hits E ω := Finset.sum_nonneg (fun i _ => bit_nonneg (E i ω)) + +theorem mean_nonneg {Ω : Type*} [Fintype Ω] (f : Ω → ℝ) (hf : ∀ ω, 0 ≤ f ω) : + 0 ≤ mean f := Finset.expect_nonneg (fun ω _ => hf ω) + +theorem mean_hits {I Ω : Type*} [Fintype I] [Fintype Ω] (E : I → Ω → Prop) : + mean (hits E) = ∑ i, mean (fun ω => bit (E i ω)) := by + exact Finset.expect_sum_comm _ _ _ + +theorem second_moment_eq {I Ω : Type*} [Fintype I] [Fintype Ω] + (E : I → Ω → Prop) : + mean (fun ω => hits E ω ^ 2) = + ∑ i, ∑ j, mean (fun ω => bit (E i ω ∧ E j ω)) := by + simp only [hits, pow_two, Finset.sum_mul, Finset.mul_sum, bit_mul, + mean, Finset.expect_sum_comm] + exact Finset.sum_comm + +theorem mean_witness_sq_le {I Ω : Type*} [Fintype I] [Fintype Ω] + (E W : I → Ω → Prop) (reject : Ω → Prop) + (hWE : ∀ i ω, W i ω → E i ω) + (hWR : ∀ i ω, W i ω → reject ω) : + mean (hits W) ^ 2 ≤ + mean (fun ω => bit (reject ω)) * mean (fun ω => hits E ω ^ 2) := by + classical + have hNH (ω : Ω) : hits W ω ≤ hits E ω := + Finset.sum_le_sum (fun i _ => bit_mono (hWE i ω)) + have hzero (ω : Ω) (hr : ¬ reject ω) : hits W ω = 0 := by + apply Finset.sum_eq_zero + intro i _ + have hw : ¬ W i ω := fun h => hr (hWR i ω h) + simp [bit, hw] + have hsupport (ω : Ω) : bit (reject ω) * hits W ω = hits W ω := by + by_cases hr : reject ω + · simp [bit, hr] + · rw [hzero ω hr] + simp + have hCS := Finset.expect_mul_sq_le_sq_mul_sq Finset.univ + (fun ω => bit (reject ω)) (hits W) + have hsquares : mean (fun ω => hits W ω ^ 2) ≤ mean (fun ω => hits E ω ^ 2) := by + apply Finset.expect_le_expect + intro ω _ + simpa only [pow_two] using + (mul_le_mul (hNH ω) (hNH ω) (hits_nonneg W ω) (hits_nonneg E ω)) + calc + _ ≤ mean (fun ω => bit (reject ω)) * mean (fun ω => hits W ω ^ 2) := by + simpa only [mean, hsupport, bit_sq] using hCS + _ ≤ _ := mul_le_mul_of_nonneg_left hsquares + (mean_nonneg _ (fun ω => bit_nonneg (reject ω))) + +theorem rejection_lower_bound {I Ω : Type*} [Fintype I] [Fintype Ω] + (E W : I → Ω → Prop) (reject : Ω → Prop) + (hWE : ∀ i ω, W i ω → E i ω) + (hWR : ∀ i ω, W i ω → reject ω) + (a b : ℝ) (ha : 0 < a) (hb : 0 < b) + (hfirst : a ≤ mean (hits W)) + (hsecond : mean (fun ω => hits E ω ^ 2) ≤ b) : + a ^ 2 / b ≤ mean (fun ω => bit (reject ω)) := by + have hN : 0 ≤ mean (hits W) := mean_nonneg _ (hits_nonneg W) + have hρ : 0 ≤ mean (fun ω => bit (reject ω)) := + mean_nonneg _ (fun ω => bit_nonneg (reject ω)) + have haSq : a ^ 2 ≤ mean (hits W) ^ 2 := by + simpa only [pow_two] using mul_le_mul hfirst hfirst ha.le hN + have hCS := mean_witness_sq_le E W reject hWE hWR + apply (div_le_iff₀ hb).2 + exact haSq.trans (hCS.trans (mul_le_mul_of_nonneg_left hsecond hρ)) + +end MinUncutGames.Foundations.PCP.PoweringMoment + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/ProfileBridge.lean b/lean/OAI/Computability/MinUncut/PCP/ProfileBridge.lean new file mode 100644 index 0000000000000000000000000000000000000000..8e2fba640066d872749667e0219e5bea65f938da --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/ProfileBridge.lean @@ -0,0 +1,602 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.ContextLoad +import OAI.Computability.MinUncut.PCP.Bounds +import OAI.Computability.MinUncut.Machines.MachineCompare + +namespace OAI + +namespace MinUncutGames.Foundations.Hastad.SourceProfileBridge + +open Target SourceContexts SourceOccurrences SourceLocalSignature +open Complexity + +def positionEncoding (u : ℕ) : Encoding (Position u) := + (Encoding.fin u).prod slotEncoding + +def names (F : Formula) {u : ℕ} (c : ClauseContext F u) : + Fin (positionEncoding u).size → ℕ := + fun i => (occurrenceName F c ((positionEncoding u).code.symm i)).val + +def nameWords (F : Formula) {u : ℕ} (c : ClauseContext F u) : + Fin (positionEncoding u).size → List Bool := + fun i => encodeWord (names F c i) + +def reindexProfile (u : ℕ) (profile : MachineFieldProfile.Profile (positionEncoding u).size) : + NameProfile u := + fun p q => profile ((positionEncoding u).code p) ((positionEncoding u).code q) + +theorem computed_profile_eq (F : Formula) {u : ℕ} (c : ClauseContext F u) : + reindexProfile u (MachineFieldProfile.equalityProfile (nameWords F c)) = + contextNameProfile F c := by + funext p q + unfold reindexProfile nameWords + rw [MachineFieldProfile.equalityProfile_encodeWord] + simp only [names, Equiv.symm_apply_apply, contextNameProfile, Fin.ext_iff] + +theorem prepared_signature_eq (F : Formula) {u : ℕ} (c : ClauseContext F u) + (s : SlotContext u) : + (⟨fun p => positiveAt (PCP.clauseAt F (c p.1)) p.2, + reindexProfile u (MachineFieldProfile.equalityProfile (nameWords F c)), s⟩ : + Signature u) = ofContext F c s := by + rw [computed_profile_eq] + rfl + +theorem nameWords_length_le_input (F : Formula) {u : ℕ} (c : ClauseContext F u) + (i : Fin (positionEncoding u).size) : + (nameWords F c i).length ≤ (formulaBits F).length := by + rw [nameWords, encodeWord_length] + exact (Nat.succ_le_of_lt + (occurrenceName F c ((positionEncoding u).code.symm i)).isLt).trans + (SourceBounds.formulaBits_length_ge_variables F) + +end MinUncutGames.Foundations.Hastad.SourceProfileBridge + +namespace MinUncutGames.Foundations.Hastad.SourceSignLoad + +open Turing +open SourceLocalSignature +open MinUncutGames.Foundations.Complexity + +def positions (u : ℕ) : List (Position u) := + ((SourceOccurrences.Encoding.fin u).prod SourceOccurrences.slotEncoding).enumerate + +theorem mem_positions {u : ℕ} (p : Position u) : p ∈ positions u := + SourceOccurrences.Encoding.mem_enumerate _ p + +def fillSigns {u : ℕ} (values initial : Position u → Bool) + (cells : List (Position u)) : Position u → Bool := + cells.foldl (fun signs p => Function.update signs p (values p)) initial + +theorem fillSigns_apply {u : ℕ} (values initial : Position u → Bool) + (cells : List (Position u)) (p : Position u) : + fillSigns values initial cells p = if p ∈ cells then values p else initial p := by + induction cells generalizing initial with + | nil => simp [fillSigns] + | cons q cells ih => + change fillSigns values (Function.update initial q (values q)) cells p = _ + rw [ih] + by_cases hp : p ∈ cells + · simp [hp] + · by_cases hpq : p = q + · subst q; simp [hp] + · simp [hp, hpq] + +theorem fillSigns_positions {u : ℕ} (values initial : Position u → Bool) : + fillSigns values initial (positions u) = values := by + funext p + rw [fillSigns_apply] + simp only [mem_positions, ↓reduceIte] + +variable {u : ℕ} {K Λ τ : Type} [DecidableEq K] + +abbrev State (u : ℕ) (τ : Type) := Signature u × τ +abbrev Alphabet (_ : K) := Bool + +def finish (exit : Option Λ) : TM2.Stmt (Alphabet (K := K)) Λ (State u τ) := + match exit with + | none => .halt + | some label => .goto fun _ => label + +def peekChain (field : Position u → K) (exit : Option Λ) : + List (Position u) → TM2.Stmt (Alphabet (K := K)) Λ (State u τ) + | [] => finish exit + | p :: rest => + .peek (field p) (fun state head => + ({state.1 with signs := Function.update state.1.signs p (head.getD false)}, state.2)) + (peekChain field exit rest) + +def statement (field : Position u → K) (exit : Option Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (State u τ) := + peekChain field exit (positions u) + +def readSigns (field : Position u → K) (tapes : K → List Bool) : Position u → Bool := + fun p => (tapes (field p)).head?.getD false + +theorem stepAux_peekChain (field : Position u → K) (exit : Option Λ) + (cells : List (Position u)) (initial : Signature u) (ambient : τ) + (tapes : K → List Bool) : + TM2.stepAux (peekChain field exit cells) (initial, ambient) tapes = + ⟨exit, ({initial with signs := fillSigns (readSigns field tapes) initial.signs cells}, + ambient), tapes⟩ := by + induction cells generalizing initial with + | nil => cases exit <;> rfl + | cons p rest ih => + simp only [peekChain, TM2.stepAux] + rw [ih] + rfl + +theorem stepAux_statement (field : Position u → K) (exit : Option Λ) + (initial : Signature u) (ambient : τ) (tapes : K → List Bool) : + TM2.stepAux (statement field exit) (initial, ambient) tapes = + ⟨exit, ({initial with signs := readSigns field tapes}, ambient), tapes⟩ := by + rw [statement, stepAux_peekChain, fillSigns_positions] + +omit [DecidableEq K] in +theorem peekChain_pushBound (field : Position u → K) (exit : Option Λ) + (cells : List (Position u)) : + Runtime.statementPushBound (peekChain (τ := τ) field exit cells) = 0 := by + induction cells with + | nil => cases exit <;> rfl + | cons p rest ih => exact ih + +omit [DecidableEq K] in +theorem statement_pushBound (field : Position u → K) (exit : Option Λ) : + Runtime.statementPushBound (statement (τ := τ) field exit) = 0 := + peekChain_pushBound field exit (positions u) + +omit [DecidableEq K] in +theorem readSigns_of_unary (field : Position u → K) (tapes : K → List Bool) + (values : Position u → Bool) (suffix : Position u → List Bool) + (hfields : ∀ p, tapes (field p) = encodeWord (if values p then 1 else 0) ++ suffix p) : + readSigns field tapes = values := by + funext p + rw [readSigns, hfields] + cases values p <;> rfl + +theorem loadStep (field : Position u → K) (entryLabel : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State u τ)) + (atEntry : program entryLabel = statement field exit) + (initial : Signature u) (ambient : τ) (tapes : K → List Bool) + (values : Position u → Bool) (suffix : Position u → List Bool) + (hfields : ∀ p, tapes (field p) = encodeWord (if values p then 1 else 0) ++ suffix p) : + TM2.step program ⟨some entryLabel, (initial, ambient), tapes⟩ = + some ⟨exit, ({initial with signs := values}, ambient), tapes⟩ := by + change some (TM2.stepAux (program entryLabel) (initial, ambient) tapes) = _ + rw [atEntry, stepAux_statement, readSigns_of_unary field tapes values suffix hfields] + +def loadInTime (field : Position u → K) (entryLabel : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State u τ)) + (atEntry : program entryLabel = statement field exit) + (initial : Signature u) (ambient : τ) (tapes : K → List Bool) + (values : Position u → Bool) (suffix : Position u → List Bool) + (hfields : ∀ p, tapes (field p) = encodeWord (if values p then 1 else 0) ++ suffix p) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some entryLabel, (initial, ambient), tapes⟩ + (some ⟨exit, ({initial with signs := values}, ambient), tapes⟩) 1 where + steps := 1 + evals_in_steps := by + change (MachineComposition.advance (TM2.step program))^[1] _ = _ + simpa only [Function.iterate_one, MachineComposition.advance_some] using + loadStep field entryLabel exit program atEntry initial ambient tapes values suffix hfields + steps_le_m := Nat.le_refl _ + +omit [DecidableEq K] in + +theorem loaded_ofContext (F : Target.Formula) (c : SourceContexts.ClauseContext F u) + (selected : SourceContexts.SlotContext u) (initial : Signature u) + (hnames : initial.sameName = contextNameProfile F c) + (hselected : initial.selected = selected) : + {initial with signs := (ofContext F c selected).signs} = ofContext F c selected := by + cases initial with + | mk signs sameName chosen => + dsimp only at hnames hselected + cases hnames + cases hselected + rfl + +def loadContextInTime (F : Target.Formula) (c : SourceContexts.ClauseContext F u) + (selected : SourceContexts.SlotContext u) (field : Position u → K) + (entryLabel : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State u τ)) + (atEntry : program entryLabel = statement field exit) + (initial : Signature u) (hnames : initial.sameName = contextNameProfile F c) + (hselected : initial.selected = selected) (ambient : τ) (tapes : K → List Bool) + (suffix : Position u → List Bool) + (hfields : ∀ p, tapes (field p) = + encodeWord (if positiveAt (PCP.clauseAt F (c p.1)) p.2 then 1 else 0) ++ suffix p) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some entryLabel, (initial, ambient), tapes⟩ + (some ⟨exit, (ofContext F c selected, ambient), tapes⟩) 1 := by + have h := loadInTime field entryLabel exit program atEntry initial ambient tapes + (ofContext F c selected).signs suffix hfields + rw [loaded_ofContext F c selected initial hnames hselected] at h + exact h + +end MinUncutGames.Foundations.Hastad.SourceSignLoad + +namespace MinUncutGames.Foundations.Hastad.SourceSignaturePrepare + +open Turing +open Target PCP SourceContexts SourceOccurrences SourceLocalSignature SourceProfileBridge +open MinUncutGames.Foundations.Complexity + +abbrev Width (u : ℕ) := (positionEncoding u).size +abbrev Arena (u : ℕ) (Extra : Type) := SourceContextLoad.Tape u Extra +abbrev ProfileState (u : ℕ) := MachineCompare.State (MachineFieldProfile.Profile (Width u)) +abbrev State (u : ℕ) (τ : Type) := ProfileState u × (Signature u × τ) +abbrev ProfileLabel (u : ℕ) := MachineFieldProfile.Label (MachineFieldProfile.allPairs (Width u)) + +inductive Label (u : ℕ) + | profile (label : ProfileLabel u) + | commit + deriving DecidableEq, Fintype + +variable {u : ℕ} {Extra τ : Type} + +def variableField (p : Position u) : Arena u Extra := + SourceContextLoad.variableField p.1 (slotEncoding.code p.2) + +def polarityField (p : Position u) : Arena u Extra := + SourceContextLoad.polarityField p.1 (slotEncoding.code p.2) + +def place : MachineFieldProfile.Tape (Width u) → Arena u Extra + | .inl i => variableField ((positionEncoding u).code.symm i) + | .inr w => if w = 0 then .index else if w = 1 then .work else .scratch + +def unplace : Arena u Extra → Option (MachineFieldProfile.Tape (Width u)) + | .index => some (.inr 0) + | .work => some (.inr 1) + | .scratch => some (.inr 2) + | .field t s => + if s = 0 then some (.inl ((positionEncoding u).code (t, .first))) + else if s = 2 then some (.inl ((positionEncoding u).code (t, .second))) + else if s = 4 then some (.inl ((positionEncoding u).code (t, .third))) else none + | _ => none + +@[simp] theorem unplace_place (k : MachineFieldProfile.Tape (Width u)) : + unplace (place (Extra := Extra) k) = some k := by + cases k with + | inl i => + obtain ⟨p, rfl⟩ := (positionEncoding u).code.surjective i + rcases p with ⟨t, s⟩ + simp only [place, Equiv.symm_apply_apply] + cases s <;> rfl + | inr w => + obtain ⟨w, hw⟩ := w + have h : w = 0 ∨ w = 1 ∨ w = 2 := by omega + rcases h with rfl | rfl | rfl <;> rfl + +theorem place_injective : Function.Injective (place (u := u) (Extra := Extra)) := by + intro a b h + have h' := congrArg unplace h + simpa only [unplace_place, Option.some.injEq] using h' + +theorem place_unplace (a : Arena u Extra) (k : MachineFieldProfile.Tape (Width u)) + (h : unplace a = some k) : place k = a := by + cases a with + | formula => simp [unplace] at h + | index => cases Option.some.inj h; rfl + | work => cases Option.some.inj h; rfl + | scratch => cases Option.some.inj h; rfl + | copyScratch => simp [unplace] at h + | current t => simp [unplace] at h + | remaining t => simp [unplace] at h + | extra e => simp [unplace] at h + | field t s => + by_cases h0 : s = 0 + · subst s + simp only [unplace, ↓reduceIte] at h + cases Option.some.inj h + simp only [place, Equiv.symm_apply_apply] + rfl + · by_cases h2 : s = 2 + · subst s + simp only [unplace, ↓reduceIte] at h + cases Option.some.inj h + simp only [place, Equiv.symm_apply_apply] + rfl + · by_cases h4 : s = 4 + · subst s + simp only [unplace, ↓reduceIte] at h + cases Option.some.inj h + simp only [place, Equiv.symm_apply_apply] + rfl + · simp [unplace, h0, h2, h4] at h + +def fill (base : Arena u Extra → List Bool) + (localTapes : MachineFieldProfile.Tape (Width u) → List Bool) : Arena u Extra → List Bool := + fun a => match unplace a with + | some k => localTapes k + | none => base a + +@[simp] theorem fill_place (base : Arena u Extra → List Bool) + (localTapes : MachineFieldProfile.Tape (Width u) → List Bool) + (k : MachineFieldProfile.Tape (Width u)) : fill base localTapes (place k) = localTapes k := by + simp only [fill, unplace_place] + +@[simp] theorem fill_self (base : Arena u Extra → List Bool) : + fill base (base ∘ place) = base := by + funext a + cases h : unplace a with + | none => simp only [fill, h] + | some k => + simp only [fill, h, Function.comp_apply, place_unplace a k h] + +theorem fill_frame (base : Arena u Extra → List Bool) + (localTapes : MachineFieldProfile.Tape (Width u) → List Bool) + (a : Arena u Extra) (h : unplace a = none) : fill base localTapes a = base a := by + simp only [fill, h] + +variable [DecidableEq Extra] + +theorem fill_update (base : Arena u Extra → List Bool) + (localTapes : MachineFieldProfile.Tape (Width u) → List Bool) + (k : MachineFieldProfile.Tape (Width u)) (value : List Bool) : + fill base (Function.update localTapes k value) = + Function.update (fill base localTapes) (place k) value := by + funext a + cases hu : unplace a with + | none => + have hne : a ≠ place k := by + intro h + rw [h, unplace_place] at hu + contradiction + simp only [fill, hu, Function.update_of_ne hne] + | some j => + have ha := place_unplace a j hu + rw [← ha] + by_cases h : j = k + · subst j + simp only [fill_place] + simp [Function.update] + · have hne : place (Extra := Extra) j ≠ place k := fun h' => h (place_injective h') + simp only [fill_place, Function.update_of_ne h, Function.update_of_ne hne] + +def placedLabel : Option (ProfileLabel u) → Option (Label u) + | none => some .commit + | some l => some (.profile l) + +def placedConfiguration (base : Arena u Extra → List Bool) (metadata : Signature u × τ) + (c : TM2.Cfg (fun _ : MachineFieldProfile.Tape (Width u) => Bool) + (ProfileLabel u) (ProfileState u)) : + TM2.Cfg (fun _ : Arena u Extra => Bool) (Label u) (State u τ) := + ⟨placedLabel c.l, (c.var, metadata), fill base c.stk⟩ + +def placedStatement : + TM2.Stmt (fun _ : MachineFieldProfile.Tape (Width u) => Bool) + (ProfileLabel u) (ProfileState u) → + TM2.Stmt (fun _ : Arena u Extra => Bool) (Label u) (State u τ) + | .push k f next => .push (place k) (fun state => f state.1) (placedStatement next) + | .peek k f next => .peek (place k) (fun state bit => (f state.1 bit, state.2)) + (placedStatement next) + | .pop k f next => .pop (place k) (fun state bit => (f state.1 bit, state.2)) + (placedStatement next) + | .load f next => .load (fun state => (f state.1, state.2)) (placedStatement next) + | .branch f yes no => .branch (fun state => f state.1) + (placedStatement yes) (placedStatement no) + | .goto f => .goto (fun state => .profile (f state.1)) + | .halt => .goto (fun _ => .commit) + +theorem placed_stepAux (base : Arena u Extra → List Bool) (metadata : Signature u × τ) + (q : TM2.Stmt (fun _ : MachineFieldProfile.Tape (Width u) => Bool) + (ProfileLabel u) (ProfileState u)) + (state : ProfileState u) (localTapes : MachineFieldProfile.Tape (Width u) → List Bool) : + TM2.stepAux (placedStatement q) (state, metadata) (fill base localTapes) = + placedConfiguration base metadata (TM2.stepAux q state localTapes) := by + induction q generalizing state localTapes with + | push k f next ih => + simp only [placedStatement, TM2.stepAux, fill_place] + rw [← fill_update] + exact ih state _ + | peek k f next ih => + simpa only [placedStatement, TM2.stepAux, fill_place] using + ih (f state (localTapes k).head?) localTapes + | pop k f next ih => + simp only [placedStatement, TM2.stepAux, fill_place] + rw [← fill_update] + exact ih (f state (localTapes k).head?) _ + | load f next ih => + simpa only [placedStatement, TM2.stepAux] using ih (f state) localTapes + | branch f yes no ihYes ihNo => + cases h : f state + · simpa only [placedStatement, TM2.stepAux, h, Bool.cond_false] using ihNo state localTapes + · simpa only [placedStatement, TM2.stepAux, h, Bool.cond_true] using ihYes state localTapes + | goto f => rfl + | halt => rfl + +def signStateEquiv (u : ℕ) (τ : Type) : + SourceSignLoad.State u (ProfileState u × τ) ≃ State u τ where + toFun x := (x.2.1, (x.1, x.2.2)) + invFun x := (x.2.1, (x.1, x.2.2)) + left_inv _ := rfl + right_inv _ := rfl + +def commitStatement : TM2.Stmt (fun _ : Arena u Extra => Bool) (Label u) (State u τ) := + .load (fun state => + (state.1, ({state.2.1 with sameName := reindexProfile u state.1.1}, state.2.2))) + (MachineControl.statement id (signStateEquiv u τ) + (SourceSignLoad.statement polarityField none)) + +def program : Label u → TM2.Stmt (fun _ : Arena u Extra => Bool) (Label u) (State u τ) + | .profile label => placedStatement + (MachineFieldProfile.profileProgram (MachineFieldProfile.allPairs (Width u)) label) + | .commit => commitStatement + +theorem placed_step (base : Arena u Extra → List Bool) (metadata : Signature u × τ) + (a b : TM2.Cfg (fun _ : MachineFieldProfile.Tape (Width u) => Bool) + (ProfileLabel u) (ProfileState u)) + (h : (MachineFieldProfile.profileMachine (Width u)).step a = some b) : + TM2.step program (placedConfiguration base metadata a) = + some (placedConfiguration base metadata b) := by + rcases a with ⟨label, state, tapes⟩ + cases label with + | none => cases h + | some label => + change some (TM2.stepAux + (MachineFieldProfile.profileProgram (MachineFieldProfile.allPairs (Width u)) label) + state tapes) = some b at h + cases Option.some.inj h + change some (TM2.stepAux (placedStatement _) (state, metadata) (fill base tapes)) = _ + rw [placed_stepAux] + +theorem stepAux_commit (work : ProfileState u) (initial : Signature u) (ambient : τ) + (tapes : Arena u Extra → List Bool) : + TM2.stepAux commitStatement (work, (initial, ambient)) tapes = + ⟨none, (work, (⟨SourceSignLoad.readSigns polarityField tapes, + reindexProfile u work.1, initial.selected⟩, ambient)), tapes⟩ := by + change TM2.stepAux (MachineControl.statement id (signStateEquiv u τ) + (SourceSignLoad.statement polarityField none)) + ((signStateEquiv u τ) + ({initial with sameName := reindexProfile u work.1}, (work, ambient))) tapes = _ + rw [MachineControl.stepAux_simulation, SourceSignLoad.stepAux_statement] + rfl + +def profileInTime (tapes : Arena u Extra → List Bool) + (hwork : ∀ w : Fin 3, tapes (place (.inr w)) = []) + (initialProfile : MachineFieldProfile.Profile (Width u)) + (initial : Signature u) (ambient : τ) (L : ℕ) + (hL : ∀ i, (tapes (place (.inl i))).length ≤ L) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (.profile (MachineFieldProfile.labelAt (MachineFieldProfile.allPairs (Width u)) 0 0)), + (MachineFieldProfile.normalState initialProfile, (initial, ambient)), tapes⟩ + (some ⟨some .commit, + (MachineFieldProfile.normalState + (MachineFieldProfile.equalityProfile (fun i => tapes (place (.inl i)))), + (initial, ambient)), tapes⟩) + (Width u * Width u * (5 * L + 6) + 1) := by + let run := MachineFieldProfile.profileInTime_bounded (Width u) (tapes ∘ place) + hwork initialProfile L hL + have lifted := MachineComposition.liftExecutionInTime _ _ + (placedConfiguration tapes (initial, ambient)) + (placed_step tapes (initial, ambient)) run + simpa only [placedConfiguration, placedLabel, fill_self, Function.comp_apply] using lifted + +def commitInTime (work : ProfileState u) (initial : Signature u) (ambient : τ) + (tapes : Arena u Extra → List Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some .commit, (work, (initial, ambient)), tapes⟩ + (some ⟨none, (work, (⟨SourceSignLoad.readSigns polarityField tapes, + reindexProfile u work.1, initial.selected⟩, ambient)), tapes⟩) 1 where + steps := 1 + evals_in_steps := by + change TM2.step program ⟨some .commit, (work, (initial, ambient)), tapes⟩ = _ + change some (TM2.stepAux commitStatement (work, (initial, ambient)) tapes) = _ + rw [stepAux_commit] + steps_le_m := Nat.le_refl _ + +def prepareInTime (F : Formula) (c : ClauseContext F u) (selected : SlotContext u) + (tapes : Arena u Extra → List Bool) + (hwork : ∀ w : Fin 3, tapes (place (.inr w)) = []) + (hnames : ∀ i, tapes (place (.inl i)) = nameWords F c i) + (suffix : Position u → List Bool) + (hsigns : ∀ p, tapes (polarityField p) = + encodeWord (if positiveAt (clauseAt F (c p.1)) p.2 then 1 else 0) ++ suffix p) + (initialProfile : MachineFieldProfile.Profile (Width u)) + (initial : Signature u) (hselected : initial.selected = selected) (ambient : τ) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (.profile (MachineFieldProfile.labelAt (MachineFieldProfile.allPairs (Width u)) 0 0)), + (MachineFieldProfile.normalState initialProfile, (initial, ambient)), tapes⟩ + (some ⟨none, + (MachineFieldProfile.normalState (MachineFieldProfile.equalityProfile (nameWords F c)), + (ofContext F c selected, ambient)), tapes⟩) + (Width u * Width u * (5 * (formulaBits F).length + 6) + 2) := by + have hfields : (fun i => tapes (place (.inl i))) = nameWords F c := funext hnames + have hsign : SourceSignLoad.readSigns polarityField tapes = + fun p => positiveAt (clauseAt F (c p.1)) p.2 := + SourceSignLoad.readSigns_of_unary polarityField tapes _ suffix hsigns + have hL : ∀ i, (tapes (place (.inl i))).length ≤ (formulaBits F).length := by + intro i + rw [hnames] + exact nameWords_length_le_input F c i + have first := profileInTime tapes hwork initialProfile initial ambient + (formulaBits F).length hL + rw [hfields] at first + have last := commitInTime + (MachineFieldProfile.normalState (MachineFieldProfile.equalityProfile (nameWords F c))) + initial ambient tapes + dsimp only [MachineFieldProfile.normalState] at last + rw [hsign, hselected, prepared_signature_eq F c selected] at last + let run := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ first last + refine { toEvalsTo := run.toEvalsTo, steps_le_m := ?_ } + have h := run.steps_le_m + omega + +omit [DecidableEq Extra] in + +theorem loaded_name_field (F : Formula) (c : ClauseContext F u) + (base : Arena u Extra → List Bool) + (hbase : ∀ p : Position u, base (variableField p) = []) + (i : Fin (Width u)) : + SourceContextLoad.stageTapes F c base u (place (.inl i)) = nameWords F c i := by + obtain ⟨p, rfl⟩ := (positionEncoding u).code.surjective i + simp only [place, Equiv.symm_apply_apply] + have ho := SourceContextLoad.output_variable F c base p.1 (slotEncoding.code p.2) + change SourceContextLoad.stageTapes F c base u (variableField p) = + encodeWord (F.clauses[(c p.1).val][(slotEncoding.code p.2).val].variableIndex.val) ++ + base (variableField p) at ho + rw [ho, hbase p, List.append_nil] + simp only [nameWords, names, Equiv.symm_apply_apply] + rcases p with ⟨t, s⟩ + cases s <;> rfl + +omit [DecidableEq Extra] in + +theorem loaded_sign_field (F : Formula) (c : ClauseContext F u) + (base : Arena u Extra → List Bool) (p : Position u) : + SourceContextLoad.stageTapes F c base u (polarityField p) = + encodeWord (if positiveAt (clauseAt F (c p.1)) p.2 then 1 else 0) ++ + base (polarityField p) := by + have ho := SourceContextLoad.output_polarity F c base p.1 (slotEncoding.code p.2) + change SourceContextLoad.stageTapes F c base u (polarityField p) = + encodeWord (if F.clauses[(c p.1).val][(slotEncoding.code p.2).val].positive then 1 else 0) ++ + base (polarityField p) at ho + rw [ho] + rcases p with ⟨t, s⟩ + cases s <;> rfl + +def loadedPrepareInTime (F : Formula) (c : ClauseContext F u) (selected : SlotContext u) + (base : Arena u Extra → List Bool) + (hindex : base .index = []) (hwork : base .work = []) (hscratch : base .scratch = []) + (hbase : ∀ p : Position u, base (variableField p) = []) + (initialProfile : MachineFieldProfile.Profile (Width u)) + (initial : Signature u) (hselected : initial.selected = selected) (ambient : τ) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (.profile (MachineFieldProfile.labelAt (MachineFieldProfile.allPairs (Width u)) 0 0)), + (MachineFieldProfile.normalState initialProfile, (initial, ambient)), + SourceContextLoad.stageTapes F c base u⟩ + (some ⟨none, + (MachineFieldProfile.normalState (MachineFieldProfile.equalityProfile (nameWords F c)), + (ofContext F c selected, ambient)), SourceContextLoad.stageTapes F c base u⟩) + (Width u * Width u * (5 * (formulaBits F).length + 6) + 2) := by + apply prepareInTime F c selected (SourceContextLoad.stageTapes F c base u) _ + (loaded_name_field F c base hbase) (fun p => base (polarityField p)) + (loaded_sign_field F c base) initialProfile initial hselected ambient + intro w + have hc := SourceContextLoad.stageTapes_clean F c base u hindex hwork + have hs : SourceContextLoad.stageTapes F c base u .scratch = [] := by + rw [SourceContextLoad.stageTapes_frame F c base u .scratch + (by simp) (by simp) (by intros; simp)] + exact hscratch + obtain ⟨w, hw⟩ := w + have h : w = 0 ∨ w = 1 ∨ w = 2 := by omega + rcases h with rfl | rfl | rfl + · exact hc.1 + · exact hc.2 + · exact hs + +def machine (u : ℕ) (Extra τ : Type) [DecidableEq Extra] [Fintype Extra] [Fintype τ] + (initialProfile : MachineFieldProfile.Profile (Width u)) + (initial : Signature u) (ambient : τ) : FinTM2 where + K := Arena u Extra + k₀ := .formula + k₁ := .formula + Γ _ := Bool + Λ := Label u + main := .profile (MachineFieldProfile.labelAt (MachineFieldProfile.allPairs (Width u)) 0 0) + σ := State u τ + initialState := (MachineFieldProfile.normalState initialProfile, (initial, ambient)) + m := program + +end MinUncutGames.Foundations.Hastad.SourceSignaturePrepare + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/ProfileCorrection.lean b/lean/OAI/Computability/MinUncut/PCP/ProfileCorrection.lean new file mode 100644 index 0000000000000000000000000000000000000000..ead2ae7cf856ff8d7bd1998e9b842a27cbae9a04 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/ProfileCorrection.lean @@ -0,0 +1,186 @@ +import Mathlib +import OAI.Computability.MinUncut.Games.Sampling + +namespace OAI + +section +namespace MinUncutGames.Foundations.Repetition.ProfileCorrection +open scoped BigOperators +open MinUncutGames.Foundations.Information +noncomputable section +variable {S X Y : Type*} [Fintype S] [Fintype X] [Fintype Y] + +def seedQuestionMarginal (p : X × (S × Y) → ℝ) : X × S → ℝ := + firstMarginal (fun z : (X × S) × Y => p (z.1.1, (z.1.2, z.2))) + +theorem seedQuestionMarginal_isProbability (p : X × (S × Y) → ℝ) + (hp : IsProbability p) : IsProbability (seedQuestionMarginal p) := by + apply firstMarginal_isProbability + constructor + · intro z + exact hp.1 _ + · have h := hp.2 + simp only [Fintype.sum_prod_type] at h ⊢ + exact h + +omit [Fintype X] in +theorem seedQuestionMarginal_first (p : X × (S × Y) → ℝ) : + firstMarginal (seedQuestionMarginal p) = firstMarginal p := by + funext x + simp only [seedQuestionMarginal, firstMarginal, Fintype.sum_prod_type] + +theorem totalVariation_triangle {Ω : Type*} [Fintype Ω] + (p c d : Ω → ℝ) : + totalVariation p d ≤ totalVariation p c + totalVariation c d := by + unfold totalVariation + have h := Finset.sum_le_sum (s := Finset.univ) + (fun x _ => abs_sub_le (p x) (c x) (d x)) + rw [Finset.sum_add_distrib] at h + linarith + +theorem left_profile_correction + (p : X × (S × Y) → ℝ) (μ : X × Y → ℝ) + (fallbackS : S → ℝ) (fallbackY : Y → ℝ) + (hp : IsProbability p) (hμ : IsProbability μ) + (hS : IsProbability fallbackS) (hY : IsProbability fallbackY) : + totalVariation p (fun z => μ (z.1, z.2.2) * + conditionalKernel (seedQuestionMarginal p) fallbackS z.1 z.2.1) ≤ + totalVariation p (fun z => seedQuestionMarginal p (z.1, z.2.1) * + conditionalKernel μ fallbackY z.1 z.2.2) + + totalVariation (firstMarginal p) (firstMarginal μ) := by + let σ := seedQuestionMarginal p + let L := conditionalKernel σ fallbackS + let M := conditionalKernel μ fallbackY + let k : X → S × Y → ℝ := fun x sy => L x sy.1 * M x sy.2 + let c : X × (S × Y) → ℝ := fun z => σ (z.1,z.2.1) * M z.1 z.2.2 + let d : X × (S × Y) → ℝ := fun z => μ (z.1,z.2.2) * L z.1 z.2.1 + have hσ : IsProbability σ := seedQuestionMarginal_isProbability p hp + have hk : ∀ x, IsProbability (k x) := by + intro x + exact kernelProduct_isProbability (L x) (fun _ : S => M x) + (conditionalKernel_isProbability σ fallbackS hσ hS x) + (fun _ => conditionalKernel_isProbability μ fallbackY hμ hY x) + have hc : c = fun z => firstMarginal σ z.1 * k z.1 z.2 := by + funext z + change σ (z.1,z.2.1) * M z.1 z.2.2 = + firstMarginal σ z.1 * (L z.1 z.2.1 * M z.1 z.2.2) + rw [← mul_assoc, marginal_mul_conditionalKernel σ fallbackS hσ] + have hd : d = fun z => firstMarginal μ z.1 * k z.1 z.2 := by + funext z + change μ (z.1,z.2.2) * L z.1 z.2.1 = + firstMarginal μ z.1 * (L z.1 z.2.1 * M z.1 z.2.2) + calc + _ = (firstMarginal μ z.1 * M z.1 z.2.2) * L z.1 z.2.1 := by + rw [marginal_mul_conditionalKernel μ fallbackY hμ] + _ = _ := by ring + have hmiddle : totalVariation c d = + totalVariation (firstMarginal σ) (firstMarginal μ) := by + rw [hc, hd] + exact totalVariation_joint_common_kernel _ _ k hk + have result := totalVariation_triangle p c d + rw [hmiddle] at result + have hmarg : firstMarginal σ = firstMarginal p := seedQuestionMarginal_first p + rw [hmarg] at result + exact result +end +end MinUncutGames.Foundations.Repetition.ProfileCorrection + +end +section +namespace MinUncutGames.Foundations.Repetition + +open scoped BigOperators + +noncomputable section + +variable {ι α β : Type*} [Fintype ι] [DecidableEq α] [DecidableEq β] + +def revealedProductWeight (weight : ι → α → β → ℝ) (mask : ι → Bool) + (fixedLeft : ι → α) (fixedRight : ι → β) (x : ι → α) (y : ι → β) : ℝ := + ∏ i, weight i (x i) (y i) * + (if mask i then (if y i = fixedRight i then 1 else 0) + else (if x i = fixedLeft i then 1 else 0)) + +def revealedLeftWeight (weight : ι → α → β → ℝ) (mask : ι → Bool) + (fixedLeft : ι → α) (fixedRight : ι → β) (x : ι → α) : ℝ := + ∏ i, if mask i then weight i (x i) (fixedRight i) + else (if x i = fixedLeft i then 1 else 0) + +def revealedRightWeight (weight : ι → α → β → ℝ) (mask : ι → Bool) + (fixedLeft : ι → α) (fixedRight : ι → β) (y : ι → β) : ℝ := + ∏ i, if mask i then (if y i = fixedRight i then 1 else 0) + else weight i (fixedLeft i) (y i) + +theorem revealedProductWeight_factorizes (weight : ι → α → β → ℝ) (mask : ι → Bool) + (fixedLeft : ι → α) (fixedRight : ι → β) (x : ι → α) (y : ι → β) : + revealedProductWeight weight mask fixedLeft fixedRight x y = + revealedLeftWeight weight mask fixedLeft fixedRight x * + revealedRightWeight weight mask fixedLeft fixedRight y := by + unfold revealedProductWeight revealedLeftWeight revealedRightWeight + rw [← Finset.prod_mul_distrib] + apply Finset.prod_congr rfl + intro i _ + by_cases hm : mask i = true + · by_cases hy : y i = fixedRight i <;> simp [hm, hy] + · by_cases hx : x i = fixedLeft i <;> simp [hm, hx] + +theorem revealedProductWeight_local_restrictions + (weight : ι → α → β → ℝ) (mask : ι → Bool) + (fixedLeft : ι → α) (fixedRight : ι → β) + (leftTest : (ι → α) → ℝ) (rightTest : (ι → β) → ℝ) + (x : ι → α) (y : ι → β) : + revealedProductWeight weight mask fixedLeft fixedRight x y * leftTest x * rightTest y = + (revealedLeftWeight weight mask fixedLeft fixedRight x * leftTest x) * + (revealedRightWeight weight mask fixedLeft fixedRight y * rightTest y) := by + rw [revealedProductWeight_factorizes] + ring + +variable {X Y : Type*} [Fintype X] [Fintype Y] + +theorem productWeight_mass (left : X → ℝ) (right : Y → ℝ) : + (∑ xy : X × Y, left xy.1 * right xy.2) = + (∑ x, left x) * (∑ y, right y) := by + rw [Fintype.sum_prod_type] + simp only [← Finset.mul_sum, ← Finset.sum_mul] + +def normalizedWeight (weight : X → ℝ) : X → ℝ := + fun x => weight x / ∑ x', weight x' + +theorem normalizedWeight_isProbability (weight : X → ℝ) + (hweight : ∀ x, 0 ≤ weight x) (hmass : 0 < ∑ x, weight x) : + (∀ x, 0 ≤ normalizedWeight weight x) ∧ (∑ x, normalizedWeight weight x) = 1 := by + constructor + · intro x + exact div_nonneg (hweight x) hmass.le + · simp only [normalizedWeight, div_eq_mul_inv, ← Finset.sum_mul, mul_inv_cancel₀ hmass.ne'] + +theorem normalized_productWeight (left : X → ℝ) (right : Y → ℝ) + (hleft : 0 < ∑ x, left x) (hright : 0 < ∑ y, right y) (xy : X × Y) : + normalizedWeight (fun z : X × Y => left z.1 * right z.2) xy = + normalizedWeight left xy.1 * normalizedWeight right xy.2 := by + unfold normalizedWeight + rw [productWeight_mass] + field_simp + +theorem normalized_rectangle_restriction + (left : X → ℝ) (right : Y → ℝ) (leftTest : X → ℝ) (rightTest : Y → ℝ) + (hleft : 0 < ∑ x, left x * leftTest x) + (hright : 0 < ∑ y, right y * rightTest y) (xy : X × Y) : + normalizedWeight + (fun z : X × Y => left z.1 * right z.2 * leftTest z.1 * rightTest z.2) xy = + normalizedWeight (fun x => left x * leftTest x) xy.1 * + normalizedWeight (fun y => right y * rightTest y) xy.2 := by + have hfun : (fun z : X × Y => left z.1 * right z.2 * leftTest z.1 * rightTest z.2) = + (fun z : X × Y => (left z.1 * leftTest z.1) * (right z.2 * rightTest z.2)) := by + funext z + ring + rw [hfun] + exact normalized_productWeight _ _ hleft hright xy + +end + +end MinUncutGames.Foundations.Repetition + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/RawInitialPredicate.lean b/lean/OAI/Computability/MinUncut/PCP/RawInitialPredicate.lean new file mode 100644 index 0000000000000000000000000000000000000000..8552199da1576e3c4572f960a32b14200926125c --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/RawInitialPredicate.lean @@ -0,0 +1,191 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.RawInitialTables + +namespace OAI + +namespace MinUncutGames.Foundations.PCP.RawInitialRows + +open Target GraphTables RawInitialTables + +abbrev Signs := Bool × Bool × Bool +abbrev Names := Nat × Nat × Nat + +def clauseSigns {n : Nat} (c : Clause n) : Signs := + ((c)[0].positive, (c)[1].positive, (c)[2].positive) + +def clauseNames {n : Nat} (c : Clause n) : Names := + ((c)[0].variableIndex.val, (c)[1].variableIndex.val, (c)[2].variableIndex.val) + +def nameWord (names : Names) : Slot → Nat + | .first => names.1 + | .second => names.2.1 + | .third => names.2.2 + +def decodedLabel (a : GraphTables.Label) : InitialGraph.Label := + AlphabetRetraction.decode64 (labelOrder.symm a) + +def incidencePredicate (signs : Signs) (slot : Slot) + (clauseLabel variableLabel : InitialGraph.Label) : Bool := + InitialGraph.variableValid variableLabel && + (((literalValue signs.1 clauseLabel.1 || + literalValue signs.2.1 clauseLabel.2.1) || + literalValue signs.2.2 clauseLabel.2.2) && + decide (answerAt (InitialGraph.toClauseAnswer clauseLabel) slot = variableLabel.1)) + +def relationPredicate (signs : Signs) (slot : Slot) : + Bool → GraphTables.Label → GraphTables.Label → Bool + | false, a, b => incidencePredicate signs slot (decodedLabel a) (decodedLabel b) + | true, a, b => incidencePredicate signs slot (decodedLabel b) (decodedLabel a) + +def relationWordsFor (signs : Signs) (slot : Slot) (orientation : Bool) : List Nat := + relationWords (relationOf (relationPredicate signs slot orientation)) + +@[simp] theorem relationWordsFor_length (signs : Signs) (slot : Slot) (orientation : Bool) : + (relationWordsFor signs slot orientation).length = 4096 := by + exact relationWords_length _ + +def incidenceWords (n i : Nat) (names : Names) (signs : Signs) + (slot : Slot) (orientation : Bool) : List Nat := + [if orientation then nameWord names slot else n + i, + 6 * i + 2 * (slotOrder slot).val + (if orientation then 0 else 1)] ++ + relationWordsFor signs slot orientation + +def clauseWords (n i : Nat) (names : Names) (signs : Signs) : List Nat := + incidenceWords n i names signs .first false ++ + incidenceWords n i names signs .first true ++ + incidenceWords n i names signs .second false ++ + incidenceWords n i names signs .second true ++ + incidenceWords n i names signs .third false ++ + incidenceWords n i names signs .third true + +def dummyWords (n m : Nat) : List Nat := + [n + m, 6 * m] ++ List.replicate 4096 1 + +def orderedList {α : Type*} {n : Nat} (e : α ≃ Fin n) : List α := + List.ofFn e.symm + +theorem orderedList_cast {α : Type*} {m n : Nat} (e : α ≃ Fin m) (h : m = n) : + orderedList (e.trans (finCongr h)) = orderedList e := by + subst n + rfl + +theorem orderedList_prod {α β : Type*} {m n : Nat} + (e : α ≃ Fin m) (f : β ≃ Fin n) : + orderedList ((e.prodCongr f).trans finProdFinEquiv) = + (orderedList e).flatMap (fun a => (orderedList f).map (fun b => (a, b))) := by + change List.ofFn (fun q : Fin (m * n) => + (e.symm (finProdFinEquiv.symm q).1, f.symm (finProdFinEquiv.symm q).2)) = _ + rw [List.ofFn_mul] + simp only [orderedList, List.flatMap_def, List.map_ofFn] + apply congrArg List.flatten + apply congrArg List.ofFn + funext i + apply congrArg List.ofFn + funext j + have h : (⟨i.val * n + j.val, by + calc + i.val * n + j.val < (i.val + 1) * n := + (Nat.add_lt_add_left j.isLt _).trans_eq (by rw [Nat.add_mul, Nat.one_mul]) + _ ≤ m * n := Nat.mul_le_mul_right _ i.isLt⟩ : Fin (m * n)) = + finProdFinEquiv (i, j) := by + apply Fin.ext + simp [finProdFinEquiv, Nat.add_comm, Nat.mul_comm] + rw [h, Equiv.symm_apply_apply] + rfl + +theorem orderedList_sum {α β : Type*} {m n : Nat} + (e : α ≃ Fin m) (f : β ≃ Fin n) : + orderedList ((e.sumCongr f).trans finSumFinEquiv) = + (orderedList e).map Sum.inl ++ (orderedList f).map Sum.inr := by + change List.ofFn (fun q : Fin (m + n) => + (e.sumCongr f).symm (finSumFinEquiv.symm q)) = _ + rw [List.ofFn_add] + change (List.ofFn (fun i : Fin m => + (e.sumCongr f).symm (finSumFinEquiv.symm (i.castAdd n)))) ++ + (List.ofFn (fun i : Fin n => + (e.sumCongr f).symm (finSumFinEquiv.symm (i.natAdd m)))) = _ + simp [orderedList, List.map_ofFn] + rfl + +def clauseDarts (F : Formula) (i : Fin F.clauses.length) : List (InitialGraph.Dart F) := + [.inl ((i, .first), false), .inl ((i, .first), true), + .inl ((i, .second), false), .inl ((i, .second), true), + .inl ((i, .third), false), .inl ((i, .third), true)] + +theorem orderedList_dartOrder (F : Formula) : + orderedList (dartOrder F) = + (List.finRange F.clauses.length).flatMap (clauseDarts F) ++ [.inr ()] := by + rw [dartOrder, orderedList_cast, orderedList_sum, orderedList_prod] + rw [eventOrder, orderedList_prod] + have hs : orderedList slotOrder = [.first, .second, .third] := rfl + have hb : orderedList finTwoEquiv.symm = [false, true] := rfl + have hu : orderedList unitOrder = [()] := rfl + rw [hs, hb, hu] + simp [orderedList, List.finRange, List.flatMap_assoc, List.map_flatMap, + ] + rfl + +def rowFor (F : Formula) (d : InitialGraph.Dart F) : + DartRow (F.«variables» + F.clauses.length + 1) (6 * F.clauses.length + 1) where + tail := vertexOrder F (InitialGraph.tail F d) + reverseIndex := dartOrder F (InitialGraph.reverse F d) + relation := relationOf (fun a b => InitialGraph.predicate F d (decodedLabel a) (decodedLabel b)) + +theorem rowList_table (F : Formula) : + rowList (table F) = (orderedList (dartOrder F)).map (rowFor F) := by + simp only [rowList, table, ofEnumeratedGraph, ofGraph, graphRows, Vector.toList_ofFn, + orderedList, List.map_ofFn] + rfl + +theorem rowWords_incidence (F : Formula) (i : Fin F.clauses.length) + (slot : Slot) (orientation : Bool) : + rowWords (rowFor F (.inl ((i, slot), orientation))) = + incidenceWords F.«variables» i.val (clauseNames (clauseAt F i)) + (clauseSigns (clauseAt F i)) slot orientation := by + have ht : (rowFor F (.inl ((i, slot), orientation))).tail.val = + if orientation then nameWord (clauseNames (clauseAt F i)) slot else F.«variables» + i.val := by + cases orientation <;> cases slot <;> rfl + have hr : (rowFor F (.inl ((i, slot), orientation))).reverseIndex.val = + 6 * i.val + 2 * (slotOrder slot).val + (if orientation then 0 else 1) := by + cases orientation <;> cases slot <;> + simp [rowFor, InitialGraph.reverse, dartOrder, eventOrder, slotOrder, unitOrder, + finProdFinEquiv, finSumFinEquiv, finTwoEquiv, Nat.mul_add, + Nat.mul_comm, Nat.mul_left_comm, Nat.add_comm] + have hp : (rowFor F (.inl ((i, slot), orientation))).relation = + relationOf (relationPredicate (clauseSigns (clauseAt F i)) slot orientation) := by + cases orientation <;> rfl + unfold rowWords incidenceWords relationWordsFor + rw [ht, hr, hp] + +theorem rowWords_dummy (F : Formula) : + rowWords (rowFor F (.inr ())) = dummyWords F.«variables» F.clauses.length := by + have ht : (rowFor F (.inr ())).tail.val = F.«variables» + F.clauses.length := rfl + have hr : (rowFor F (.inr ())).reverseIndex.val = 6 * F.clauses.length := by + simp [rowFor, InitialGraph.reverse, dartOrder, unitOrder, finSumFinEquiv] + have hp : (rowFor F (.inr ())).relation = relationOf (fun _ _ => true) := rfl + have hw : relationWords (relationOf (fun _ _ => true)) = List.replicate 4096 1 := by + unfold relationWords + rw [relationOf, Vector.toList_ofFn, List.map_ofFn] + exact List.ofFn_const 4096 1 + unfold rowWords dummyWords + rw [ht, hr, hp, hw] + +theorem clauseDarts_rowWords (F : Formula) (i : Fin F.clauses.length) : + (clauseDarts F i).flatMap (fun d => rowWords (rowFor F d)) = + clauseWords F.«variables» i.val (clauseNames (clauseAt F i)) + (clauseSigns (clauseAt F i)) := by + simp [clauseDarts, rowWords_incidence, clauseWords, List.append_assoc] + +theorem tableWords_eq (F : Formula) : + tableWords (table F) = + [F.«variables» + F.clauses.length + 1, 6 * F.clauses.length + 1] ++ + (List.finRange F.clauses.length).flatMap (fun i => + clauseWords F.«variables» i.val (clauseNames (clauseAt F i)) + (clauseSigns (clauseAt F i))) ++ dummyWords F.«variables» F.clauses.length := by + rw [tableWords, rowList_table, orderedList_dartOrder] + simp [List.flatMap_map, List.flatMap_append, List.flatMap_assoc, clauseDarts_rowWords, + rowWords_dummy] + +end MinUncutGames.Foundations.PCP.RawInitialRows + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/RawInitialTables.lean b/lean/OAI/Computability/MinUncut/PCP/RawInitialTables.lean new file mode 100644 index 0000000000000000000000000000000000000000..a5a18f92094e4a32f32e9ec483e4fe7c9357a710 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/RawInitialTables.lean @@ -0,0 +1,1156 @@ +import Mathlib +import OAI.Computability.MinUncut.Machines.Relations +import OAI.Computability.MinUncut.Machines.AlphabetRetraction +import OAI.Computability.MinUncut.Encoding.BinaryCoordinates + +namespace OAI + +section +namespace MinUncutGames.Foundations.PCP.RawInitialTables + +open Target GraphTables + +def unitOrder : Unit ≃ Fin 1 where + toFun _ := 0 + invFun _ := () + left_inv _ := rfl + right_inv i := by fin_cases i; rfl + +def slotOrder : Slot ≃ Fin 3 where + toFun + | .first => 0 + | .second => 1 + | .third => 2 + invFun i := if i = 0 then .first else if i = 1 then .second else .third + left_inv s := by cases s <;> rfl + right_inv i := by fin_cases i <;> rfl + +def binaryOrder (n : Nat) : (Fin n → Bool) ≃ Fin (2 ^ n) where + toFun bits := (MinUncutGames.Integration.BinaryCoordinates.pack bits).toFin + invFun index := MinUncutGames.Integration.BinaryCoordinates.unpack (BitVec.ofFin index) + left_inv bits := MinUncutGames.Integration.BinaryCoordinates.unpack_pack bits + right_inv index := by + change (MinUncutGames.Integration.BinaryCoordinates.pack + (MinUncutGames.Integration.BinaryCoordinates.unpack (BitVec.ofFin index))).toFin = index + rw [MinUncutGames.Integration.BinaryCoordinates.pack_unpack] + +def labelOrder : AlphabetRetraction.Label64 ≃ GraphTables.Label := binaryOrder 6 + +def vertexOrder (F : Formula) : + InitialGraph.Vertex F ≃ Fin (F.«variables» + F.clauses.length + 1) := + ((finSumFinEquiv.sumCongr unitOrder).trans finSumFinEquiv) + +def eventOrder (F : Formula) : RandomEvent F ≃ Fin (F.clauses.length * 3) := + ((Equiv.refl (Fin F.clauses.length)).prodCongr slotOrder).trans finProdFinEquiv + +def dartOrder (F : Formula) : InitialGraph.Dart F ≃ Fin (6 * F.clauses.length + 1) := + (((((eventOrder F).prodCongr finTwoEquiv.symm).trans finProdFinEquiv).sumCongr + unitOrder).trans finSumFinEquiv).trans (finCongr (by omega)) + +def raw64 (F : Formula) : ConstraintGraph (InitialGraph.Vertex F) + (InitialGraph.Dart F) AlphabetRetraction.Label64 := + AlphabetRetraction.pullback (InitialGraph.raw F) AlphabetRetraction.decode64 + +def table (F : Formula) : GraphTables.Table := + GraphTables.ofEnumeratedGraph (raw64 F) (vertexOrder F) (dartOrder F) labelOrder + +@[simp] theorem table_vertices (F : Formula) : + (table F).vertices = F.«variables» + F.clauses.length + 1 := rfl + +@[simp] theorem table_darts (F : Formula) : (table F).darts = 6 * F.clauses.length + 1 := rfl + +theorem table_vertices_positive (F : Formula) : 0 < (table F).vertices := by + rw [table_vertices]; omega + +theorem table_darts_positive (F : Formula) : 0 < (table F).darts := by + rw [table_darts]; omega + +theorem raw64_satisfiable_iff (F : Formula) : (raw64 F).Satisfiable ↔ F.Satisfiable := + (AlphabetRetraction.satisfiable_pullback_iff (InitialGraph.raw F) + AlphabetRetraction.decode64 AlphabetRetraction.encode64 + AlphabetRetraction.decode_encode64).trans (InitialGraph.raw_satisfiable_iff F) + +theorem table_semantics (F : Formula) : + GraphTables.semantics (table F) = + (raw64 F).reindex (vertexOrder F) (dartOrder F) labelOrder := by + change GraphTables.semantics (GraphTables.ofGraph + (GraphTables.enumeratedGraph (raw64 F) (vertexOrder F) (dartOrder F) labelOrder)) = _ + rw [GraphTables.semantics_ofGraph] + rfl + +theorem table_satisfiable_iff (F : Formula) : + (GraphTables.semantics (table F)).Satisfiable ↔ F.Satisfiable := by + rw [table_semantics] + exact ((raw64 F).satisfiable_reindex (vertexOrder F) (dartOrder F) labelOrder).trans + (raw64_satisfiable_iff F) + +theorem initial_rejection (F : Formula) (unsat : ¬ F.Satisfiable) + (labeling : Fin (table F).vertices → GraphTables.Label) : + 1 ≤ (GraphTables.semantics (table F)).rejectionCount labeling := + ConstraintGraph.rejectionCount_positive _ + (fun h => unsat ((table_satisfiable_iff F).mp h)) labeling + +theorem initial_size (F : Formula) : + (table F).vertices + (table F).darts = F.«variables» + 7 * F.clauses.length + 2 := by + rw [table_vertices, table_darts] + omega + +end MinUncutGames.Foundations.PCP.RawInitialTables + +end +section +noncomputable section + +namespace MinUncutGames.Foundations.PCP.FiniteGraph + +structure Bundle (A : Type) where + Vertex : Type + Dart : Type + vertexFintype : Fintype Vertex + dartFintype : Fintype Dart + vertexDecidableEq : DecidableEq Vertex + dartDecidableEq : DecidableEq Dart + dartNonempty : Nonempty Dart + graph : ConstraintGraph Vertex Dart A + +namespace Bundle + +variable {A : Type} + +instance instFintypeVertex (G : Bundle A) : Fintype G.Vertex := G.vertexFintype +instance instFintypeDart (G : Bundle A) : Fintype G.Dart := G.dartFintype +instance instDecidableEqVertex (G : Bundle A) : DecidableEq G.Vertex := G.vertexDecidableEq +instance instDecidableEqDart (G : Bundle A) : DecidableEq G.Dart := G.dartDecidableEq +instance instNonemptyDart (G : Bundle A) : Nonempty G.Dart := G.dartNonempty + +instance instNonemptyVertex (G : Bundle A) : Nonempty G.Vertex := by + obtain ⟨d⟩ := G.dartNonempty + exact ⟨G.graph.tail d⟩ + +def ofGraph {V E : Type} [Fintype V] [Fintype E] + [DecidableEq V] [DecidableEq E] [Nonempty E] + (G : ConstraintGraph V E A) : Bundle A where + Vertex := V + Dart := E + vertexFintype := inferInstance + dartFintype := inferInstance + vertexDecidableEq := inferInstance + dartDecidableEq := inferInstance + dartNonempty := inferInstance + graph := G + +def size (G : Bundle A) : Nat := Fintype.card G.Vertex + Fintype.card G.Dart + +def Satisfiable (G : Bundle A) : Prop := G.graph.Satisfiable + +def rejectionCount (G : Bundle A) (labeling : G.Vertex → A) : Nat := + G.graph.rejectionCount labeling + +theorem size_positive (G : Bundle A) : 0 < G.size := + lt_of_lt_of_le (Fintype.card_pos : 0 < Fintype.card G.Dart) (Nat.le_add_left _ _) + +theorem dartCard_le_size (G : Bundle A) : Fintype.card G.Dart ≤ G.size := + Nat.le_add_left _ _ + +@[simp] theorem ofGraph_graph {V E : Type} [Fintype V] [Fintype E] + [DecidableEq V] [DecidableEq E] [Nonempty E] (G : ConstraintGraph V E A) : + (ofGraph G).graph = G := rfl + +@[simp] theorem ofGraph_size {V E : Type} [Fintype V] [Fintype E] + [DecidableEq V] [DecidableEq E] [Nonempty E] (G : ConstraintGraph V E A) : + (ofGraph G).size = Fintype.card V + Fintype.card E := rfl + +@[simp] theorem ofGraph_satisfiable {V E : Type} [Fintype V] [Fintype E] + [DecidableEq V] [DecidableEq E] [Nonempty E] (G : ConstraintGraph V E A) : + (ofGraph G).Satisfiable ↔ G.Satisfiable := Iff.rfl + +@[simp] theorem ofGraph_rejectionCount {V E : Type} [Fintype V] [Fintype E] + [DecidableEq V] [DecidableEq E] [Nonempty E] + (G : ConstraintGraph V E A) (labeling : V → A) : + (ofGraph G).rejectionCount labeling = G.rejectionCount labeling := rfl + +section Gap + +variable [Fintype A] [Nonempty A] + +def minimumRejections (G : Bundle A) : Nat := G.graph.minimumRejections + +def gap (G : Bundle A) : ℝ := G.graph.gap + +theorem exists_minimizer (G : Bundle A) : + ∃ labeling : G.Vertex → A, G.rejectionCount labeling = G.minimumRejections := + G.graph.exists_minimizer + +theorem gap_nonnegative (G : Bundle A) : 0 ≤ G.gap := G.graph.gap_nonnegative + +theorem gap_le_one (G : Bundle A) : G.gap ≤ 1 := G.graph.gap_le_one + +theorem gap_eq_zero_iff (G : Bundle A) : G.gap = 0 ↔ G.Satisfiable := + G.graph.gap_eq_zero_iff + +theorem le_gap_iff (G : Bundle A) (ε : ℝ) : + ε ≤ G.gap ↔ ∀ labeling : G.Vertex → A, + ε * Fintype.card G.Dart ≤ (G.rejectionCount labeling : ℝ) := + G.graph.le_gap_iff ε + +theorem inverse_card_le_gap_of_unsatisfiable (G : Bundle A) (unsat : ¬ G.Satisfiable) : + 1 / (Fintype.card G.Dart : ℝ) ≤ G.gap := + G.graph.inverse_card_le_gap_of_unsatisfiable unsat + +theorem one_le_dartCard_mul_gap (G : Bundle A) (unsat : ¬ G.Satisfiable) : + 1 ≤ (Fintype.card G.Dart : ℝ) * G.gap := by + have he : (0 : ℝ) < Fintype.card G.Dart := by exact_mod_cast Fintype.card_pos + have h := (div_le_iff₀ he).mp (G.inverse_card_le_gap_of_unsatisfiable unsat) + simpa only [mul_comm] using h + +theorem one_le_size_mul_gap (G : Bundle A) (unsat : ¬ G.Satisfiable) : + 1 ≤ (G.size : ℝ) * G.gap := by + have hsize : (Fintype.card G.Dart : ℝ) ≤ (G.size : ℝ) := by + exact_mod_cast G.dartCard_le_size + exact (G.one_le_dartCard_mul_gap unsat).trans + (mul_le_mul_of_nonneg_right hsize G.gap_nonnegative) + +@[simp] theorem ofGraph_minimumRejections {V E : Type} [Fintype V] [Fintype E] + [DecidableEq V] [DecidableEq E] [Nonempty E] (G : ConstraintGraph V E A) : + (ofGraph G).minimumRejections = G.minimumRejections := rfl + +@[simp] theorem ofGraph_gap {V E : Type} [Fintype V] [Fintype E] + [DecidableEq V] [DecidableEq E] [Nonempty E] (G : ConstraintGraph V E A) : + (ofGraph G).gap = G.gap := rfl + +end Gap + +end Bundle + +end MinUncutGames.Foundations.PCP.FiniteGraph + +end +end +section +namespace MinUncutGames.Foundations.PCP.FinalConstants + +def alphabet : Nat := 64 +def compositionLoss : Nat := 12288 +def denominator : Nat := 16 * alphabet ^ 4 * 66 * compositionLoss +def windowHalf : Nat := denominator * Preprocessing.sizeFactor +def windowSize : Nat := 2 * windowHalf + 1 +def smoothingScale : Nat := 4 * alphabet * windowHalf +def endpointLength : Nat := smoothingScale ^ 2 +def walkLength : Nat := 2 * endpointLength + 1 + +noncomputable def gain : ℝ := (windowSize : ℝ) / denominator +noncomputable def cap : ℝ := 1 / (walkLength : ℝ) + +theorem denominator_positive : 0 < denominator := by + norm_num [denominator, alphabet, compositionLoss] + +theorem windowHalf_positive : 0 < windowHalf := + Nat.mul_pos denominator_positive Preprocessing.sizeFactor_positive + +theorem walkLength_positive : 0 < walkLength := by + simp [walkLength] + +theorem gain_large : 2 * (Preprocessing.sizeFactor : ℝ) ≤ gain := by + have hd : (0 : ℝ) < denominator := by exact_mod_cast denominator_positive + apply (le_div_iff₀ hd).2 + simp only [windowSize, windowHalf, Nat.cast_add, Nat.cast_mul, + Nat.cast_ofNat] + nlinarith + +theorem cap_positive : 0 < cap := by + exact one_div_pos.mpr (by exact_mod_cast walkLength_positive) + +theorem cap_le_one : cap ≤ 1 := by + apply (div_le_one (by exact_mod_cast walkLength_positive)).2 + exact_mod_cast walkLength_positive + +theorem composed_gap (epsilon : ℝ) (he : 0 ≤ epsilon) : + min (2 * epsilon) cap ≤ + gain * min (epsilon / (Preprocessing.sizeFactor : ℝ)) + (1 / (walkLength : ℝ)) := by + have hs : (0 : ℝ) < Preprocessing.sizeFactor := by + exact_mod_cast Preprocessing.sizeFactor_positive + have hs1 : (1 : ℝ) ≤ Preprocessing.sizeFactor := by + exact_mod_cast Preprocessing.sizeFactor_positive + have hg : 0 ≤ gain := le_trans (by positivity) gain_large + rw [mul_min_of_nonneg _ _ hg] + apply min_le_min + · calc + 2 * epsilon = (2 * (Preprocessing.sizeFactor : ℝ)) * + (epsilon / (Preprocessing.sizeFactor : ℝ)) := by field_simp + _ ≤ gain * (epsilon / (Preprocessing.sizeFactor : ℝ)) := + mul_le_mul_of_nonneg_right gain_large (div_nonneg he hs.le) + · change cap ≤ gain * cap + have hgain : 1 ≤ gain := by linarith [gain_large] + simpa only [one_mul] using mul_le_mul_of_nonneg_right hgain cap_positive.le + +end MinUncutGames.Foundations.PCP.FinalConstants + +end +section +namespace MinUncutGames.Foundations.PCP.RoundTables + +abbrev BaseTable := PreprocessingTables.BaseTable + +opaque fixedWalkParameter : {n : Nat // n = 2 * FinalConstants.endpointLength} := + ⟨2 * FinalConstants.endpointLength, rfl⟩ + +def walkParameter : Nat := fixedWalkParameter.val + +theorem walkParameter_eq : walkParameter = 2 * FinalConstants.endpointLength := + fixedWalkParameter.property + +def alphabet : Nat := PoweringTables.labelCount PreprocessingTables.degree walkParameter + +theorem alphabet_positive : 0 < alphabet := by + unfold alphabet PoweringTables.labelCount + exact Nat.pow_pos (by decide) + +def powered (H : BaseTable) (table : GraphTables.Table) : GenericGraphTables.Table alphabet := + PoweringTables.table (PreprocessingTables.preprocess H table) walkParameter + +def build (H : BaseTable) (table : GraphTables.Table) : GraphTables.Table := + AlphabetTable.Table.build (powered H table) + +def sizeFactor : Nat := AlphabetGraphBounds.sizeFactor alphabet * + (ExpanderFamily.growth ^ 2 * (1 + 2 * PreprocessingTables.degree ^ (walkParameter + 1))) + +theorem degree_positive : 0 < PreprocessingTables.degree := by + unfold PreprocessingTables.degree + omega + +theorem dartFactor_positive (q : Nat) : 0 < AlphabetGraphBounds.dartFactor q := by + unfold AlphabetGraphBounds.dartFactor AlphabetGraphBounds.localEventFactor + positivity + +theorem sizeFactor_positive : 0 < sizeFactor := by + unfold sizeFactor + apply Nat.mul_pos (AlphabetGraphBounds.sizeFactor_positive alphabet) + apply Nat.mul_pos + · exact Nat.pow_pos (Nat.zero_lt_one.trans ExpanderFamily.growth_gt_one) + · omega + +theorem powered_vertices (H : BaseTable) (table : GraphTables.Table) : + (powered H table).vertices = PreprocessingTables.vertices table := rfl + +theorem powered_darts (H : BaseTable) (table : GraphTables.Table) : + (powered H table).darts = 2 * PreprocessingTables.vertices table * + PreprocessingTables.degree ^ (walkParameter + 1) := rfl + +theorem build_darts_positive (H : BaseTable) (table : GraphTables.Table) : + 0 < (build H table).darts := by + change 0 < (AlphabetTable.Table.build (powered H table)).darts + rw [AlphabetTableBounds.build_darts, powered_darts] + exact Nat.mul_pos (Nat.mul_pos + (Nat.mul_pos (by decide) (PreprocessingTables.vertices_positive table)) + (Nat.pow_pos degree_positive)) (dartFactor_positive alphabet) + +theorem build_size_le (H : BaseTable) (table : GraphTables.Table) + (ht : 0 < table.darts) : + (build H table).vertices + (build H table).darts ≤ + sizeFactor * (table.vertices + table.darts) := by + have hv := PreprocessingTables.vertices_le_of_positive table ht + have he : (powered H table).vertices + (powered H table).darts = + PreprocessingTables.vertices table * + (1 + 2 * PreprocessingTables.degree ^ (walkParameter + 1)) := by + rw [powered_vertices, powered_darts] + ring + have hp := Nat.mul_le_mul_right + (1 + 2 * PreprocessingTables.degree ^ (walkParameter + 1)) hv + calc + _ ≤ AlphabetGraphBounds.sizeFactor alphabet * + ((powered H table).vertices + (powered H table).darts) := + AlphabetTableBounds.build_total_le (powered H table) + _ = AlphabetGraphBounds.sizeFactor alphabet * + (PreprocessingTables.vertices table * + (1 + 2 * PreprocessingTables.degree ^ (walkParameter + 1))) := by rw [he] + _ ≤ AlphabetGraphBounds.sizeFactor alphabet * + ((ExpanderFamily.growth ^ 2 * table.darts) * + (1 + 2 * PreprocessingTables.degree ^ (walkParameter + 1))) := + Nat.mul_le_mul_left _ hp + _ = sizeFactor * table.darts := by unfold sizeFactor; ring + _ ≤ sizeFactor * (table.vertices + table.darts) := + Nat.mul_le_mul_left _ (Nat.le_add_left _ _) + +theorem build_completeness (H : BaseTable) (table : GraphTables.Table) + (sat : (GraphTables.semantics table).Satisfiable) : + (GraphTables.semantics (build H table)).Satisfiable := by + let : Nonempty (Fin alphabet) := ⟨⟨0, alphabet_positive⟩⟩ + exact AlphabetTable.Table.perfect_completeness (powered H table) + (PoweringTableSemantics.preserves_satisfiability + (PreprocessingTables.preprocess H table) walkParameter + (PreprocessingGuarantees.completeness H table sat)) + +abbrev Input := {table : GraphTables.Table // 0 < table.darts} + +instance (input : Input) : Nonempty (Fin input.val.darts) := ⟨⟨0, input.property⟩⟩ + +def step (H : BaseTable) (input : Input) : Input := + ⟨build H input.val, build_darts_positive H input.val⟩ + +def initial (F : Target.Formula) : Input := + ⟨RawInitialTables.table F, RawInitialTables.table_darts_positive F⟩ + +def size (input : Input) : Nat := input.val.vertices + input.val.darts + +def Satisfiable (input : Input) : Prop := (GraphTables.semantics input.val).Satisfiable + +noncomputable def gap (input : Input) : ℝ := (GraphTables.semantics input.val).gap + +theorem size_positive (input : Input) : 0 < size input := + input.property.trans_le (Nat.le_add_left _ _) + +theorem gap_nonnegative (input : Input) : 0 ≤ gap input := + (GraphTables.semantics input.val).gap_nonnegative + +theorem gap_eq_zero_iff (input : Input) : gap input = 0 ↔ Satisfiable input := + (GraphTables.semantics input.val).gap_eq_zero_iff + +theorem one_le_size_mul_gap (input : Input) (unsat : ¬ Satisfiable input) : + 1 ≤ (size input : ℝ) * gap input := by + have h := (GraphTables.semantics input.val).inverse_card_le_gap_of_unsatisfiable unsat + have hp : (0 : ℝ) < input.val.darts := Nat.cast_pos.mpr input.property + simp only [Fintype.card_fin] at h + have hd := (div_le_iff₀ hp).mp h + have hsize : (input.val.darts : ℝ) ≤ (size input : ℝ) := by + exact_mod_cast (Nat.le_add_left input.val.darts input.val.vertices) + exact (show 1 ≤ (input.val.darts : ℝ) * gap input by + simpa only [gap, mul_comm] using hd).trans + (mul_le_mul_of_nonneg_right hsize (gap_nonnegative input)) + +theorem initial_satisfiable_iff (F : Target.Formula) : Satisfiable (initial F) ↔ F.Satisfiable := + RawInitialTables.table_satisfiable_iff F + +theorem step_completeness (H : BaseTable) (input : Input) : + Satisfiable input → Satisfiable (step H input) := build_completeness H input.val + +theorem step_size (H : BaseTable) (input : Input) : + size (step H input) ≤ sizeFactor * size input := build_size_le H input.val input.property + +end MinUncutGames.Foundations.PCP.RoundTables + +end +section +namespace MinUncutGames.Foundations.PCP.AmplificationIteration + +def run {X : Type*} (step : X → X) : Nat → X → X + | 0, x => x + | n + 1, x => step (run step n x) + +private theorem min_double_min (u cap : ℝ) (hc : 0 ≤ cap) : + min (2 * min u cap) cap = min (2 * u) cap := by + by_cases hu : u ≤ cap + · rw [min_eq_left hu] + · have hcu : cap ≤ u := le_of_not_ge hu + rw [min_eq_right hcu, min_eq_right (by linarith : cap ≤ 2 * cap), + min_eq_right (by linarith : cap ≤ 2 * u)] + +theorem run_gap {X : Type*} (step : X → X) (gap : X → ℝ) + (cap : ℝ) (hc : 0 ≤ cap) + (amplifies : ∀ x, min (2 * gap x) cap ≤ gap (step x)) + (n : Nat) (x : X) : + min (2 ^ n * gap x) cap ≤ gap (run step n x) := by + induction n with + | zero => simp [run] + | succ n ih => + have hm : min (2 * min (2 ^ n * gap x) cap) cap ≤ + min (2 * gap (run step n x)) cap := + min_le_min (mul_le_mul_of_nonneg_left ih (by norm_num)) le_rfl + rw [min_double_min _ _ hc] at hm + have h := hm.trans (amplifies (run step n x)) + simpa [run, pow_succ, mul_assoc, mul_left_comm, mul_comm] using h + +theorem run_preserves {X : Type*} (step : X → X) (P : X → Prop) + (preserves : ∀ x, P x → P (step x)) (n : Nat) (x : X) (hx : P x) : + P (run step n x) := by + induction n with + | zero => exact hx + | succ n ih => exact preserves _ ih + +theorem run_size {X : Type*} (step : X → X) (size : X → Nat) (C : Nat) + (blowup : ∀ x, size (step x) ≤ C * size x) (n : Nat) (x : X) : + size (run step n x) ≤ C ^ n * size x := by + induction n with + | zero => simp [run] + | succ n ih => + have h := (blowup (run step n x)).trans (Nat.mul_le_mul_left C ih) + simpa [run, pow_succ, Nat.mul_assoc, Nat.mul_left_comm, Nat.mul_comm] using h + +def rounds (n : Nat) : Nat := Nat.log2 n + 1 + +theorem rounds_large (n : Nat) : n < 2 ^ rounds n := by + simpa [rounds, Nat.log2_eq_log_two] using + (Nat.lt_pow_succ_log_self (by decide : 1 < 2) n) + +theorem rounds_power_le {n : Nat} (hn : 0 < n) : 2 ^ rounds n ≤ 2 * n := by + have h := Nat.pow_log_le_self 2 (Nat.ne_of_gt hn) + simpa [rounds, Nat.log2_eq_log_two, pow_succ, Nat.mul_comm] using + (Nat.mul_le_mul_right 2 h) + +theorem blowup_rounds_le {C degree n : Nat} (hn : 0 < n) (hC : C ≤ 2 ^ degree) : + C ^ rounds n ≤ (2 * n) ^ degree := by + calc + C ^ rounds n ≤ (2 ^ degree) ^ rounds n := Nat.pow_le_pow_left hC _ + _ = (2 ^ rounds n) ^ degree := by + rw [← pow_mul, ← pow_mul, Nat.mul_comm degree (rounds n)] + _ ≤ (2 * n) ^ degree := Nat.pow_le_pow_left (rounds_power_le hn) _ + +theorem run_size_polynomial {X : Type*} (step : X → X) (size : X → Nat) + {C degree n : Nat} (hn : 0 < n) (hC : C ≤ 2 ^ degree) + (blowup : ∀ x, size (step x) ≤ C * size x) (x : X) : + size (run step (rounds n) x) ≤ (2 * n) ^ degree * size x := + (run_size step size C blowup (rounds n) x).trans + (Nat.mul_le_mul_right _ (blowup_rounds_le hn hC)) + +theorem run_reaches_cap {X : Type*} (step : X → X) (gap : X → ℝ) + (cap : ℝ) (hc : 0 ≤ cap) (hc1 : cap ≤ 1) + (amplifies : ∀ x, min (2 * gap x) cap ≤ gap (step x)) + (n : Nat) (x : X) (hg : 0 ≤ gap x) (hstart : 1 ≤ (n : ℝ) * gap x) : + cap ≤ gap (run step (rounds n) x) := by + have hp : (n : ℝ) ≤ (2 : ℝ) ^ rounds n := by + exact_mod_cast (Nat.le_of_lt (rounds_large n)) + have hcap : cap ≤ (2 : ℝ) ^ rounds n * gap x := + hc1.trans (hstart.trans (mul_le_mul_of_nonneg_right hp hg)) + have h := run_gap step gap cap hc amplifies (rounds n) x + rwa [min_eq_right hcap] at h + +end MinUncutGames.Foundations.PCP.AmplificationIteration + +end +section +namespace MinUncutGames.Foundations.PCP.VerifierToCNF + +open Target + +abbrev BoolTriple := Bool × Bool × Bool + +def tripleValue (t : BoolTriple) : Bool := (t.1 || t.2.1) || t.2.2 + +def chainView : List Bool → List Bool → List BoolTriple + | [a, b, c], [] => [(a, b, c)] + | a :: b :: rest, y :: ys => (a, b, y) :: chainView ((!y) :: rest) ys + | _, _ => [] + +def fillBits (bits : List Bool) : List Bool := + match bits with + | a :: b :: c :: d :: rest => + (!(a || b)) :: fillBits ((a || b) :: c :: d :: rest) + | _ => [] +termination_by bits.length +decreasing_by simp_wf + +theorem chainView_length (bits ys : List Bool) + (size : bits.length = ys.length + 3) : + (chainView bits ys).length = ys.length + 1 := by + induction ys generalizing bits with + | nil => + match bits with + | [a, b, c] => rfl + | [] => simp at size + | [_] => simp at size + | [_, _] => simp at size + | _ :: _ :: _ :: _ :: rest => + simp only [List.length_cons, List.length_nil] at size + omega + | cons y ys ih => + match bits with + | [] => simp at size + | [_] => simp only [List.length_cons, List.length_nil] at size; omega + | a :: b :: rest => + have smaller : ((!y) :: rest).length = ys.length + 3 := by + simp only [List.length_cons] at * + omega + have h := ih ((!y) :: rest) smaller + simpa only [chainView, List.length_cons] using congrArg (fun n => n + 1) h + +theorem chainView_sound (bits ys : List Bool) + (size : bits.length = ys.length + 3) + (accepted : (chainView bits ys).all tripleValue = true) : bits.any id = true := by + induction ys generalizing bits with + | nil => + match bits with + | [a, b, c] => simpa [chainView, tripleValue, Bool.or_assoc] using accepted + | [] => simp at size + | [_] => simp at size + | [_, _] => simp at size + | _ :: _ :: _ :: _ :: rest => + simp only [List.length_cons, List.length_nil] at size + omega + | cons y ys ih => + match bits with + | [] => simp at size + | [_] => simp only [List.length_cons, List.length_nil] at size; omega + | a :: b :: rest => + have smaller : ((!y) :: rest).length = ys.length + 3 := by + simp only [List.length_cons] at * + omega + have accepted' : tripleValue (a, b, y) = true ∧ + (chainView ((!y) :: rest) ys).all tripleValue = true := by + simpa only [chainView, List.all_cons, Bool.and_eq_true] using accepted + have tailAccepted := ih ((!y) :: rest) smaller accepted'.2 + cases a <;> cases b <;> cases y <;> simp_all [tripleValue] + +theorem fillBits_length (bits : List Bool) (size : 3 ≤ bits.length) : + (fillBits bits).length + 3 = bits.length := by + match bits with + | [] => simp at size + | [_] => simp at size + | [_, _] => simp at size + | [a, b, c] => simp [fillBits] + | a :: b :: c :: d :: rest => + have ih := fillBits_length ((a || b) :: c :: d :: rest) (by simp) + rw [fillBits] + change (fillBits ((a || b) :: c :: d :: rest)).length + 1 + 3 = rest.length + 4 + simp only [List.length_cons] at ih + omega +termination_by bits.length +decreasing_by simp_wf + +theorem fillBits_correct (bits : List Bool) (size : 3 ≤ bits.length) : + (chainView bits (fillBits bits)).all tripleValue = true ↔ bits.any id = true := by + match bits with + | [] => simp at size + | [_] => simp at size + | [_, _] => simp at size + | [a, b, c] => simp [fillBits, chainView, tripleValue, Bool.or_assoc] + | a :: b :: c :: d :: rest => + have ih := fillBits_correct ((a || b) :: c :: d :: rest) (by simp) + have tautology : tripleValue (a, b, !(a || b)) = true := by + cases a <;> cases b <;> rfl + rw [fillBits] + simp only [chainView, List.all_cons, Bool.not_not] + rw [tautology] + simp only [Bool.true_and] + simpa [Bool.or_assoc] using ih +termination_by bits.length +decreasing_by simp_wf + +theorem zero_false_count_iff_all (bits : List Bool) : + bits.count false = 0 ↔ bits.all id = true := by + induction bits with + | nil => simp + | cons b bits ih => cases b <;> simp [ih] + +theorem chainView_failed (bits ys : List Bool) + (size : bits.length = ys.length + 3) (failed : bits.any id = false) : + 1 ≤ ((chainView bits ys).map tripleValue).count false := by + by_contra none + have zero : ((chainView bits ys).map tripleValue).count false = 0 := by omega + have all := (zero_false_count_iff_all _).mp zero + have accepted : (chainView bits ys).all tripleValue = true := by + simpa only [List.all_map, Function.comp_def, id_eq] using all + have impossible := chainView_sound bits ys size accepted + rw [failed] at impossible + contradiction + +abbrev Pattern (q : Nat) := Fin q → Bool + +def patterns : (q : Nat) → List (Pattern q) + | 0 => [Fin.elim0] + | q + 1 => (patterns q).flatMap (fun p => [Fin.cases false p, Fin.cases true p]) + +theorem flatMap_pair_length {α β : Type*} (xs : List α) (f g : α → β) : + (xs.flatMap (fun x => [f x, g x])).length = 2 * xs.length := by + induction xs with + | nil => rfl + | cons x xs ih => + simp only [List.flatMap_cons, List.length_append, List.length_cons, + List.length_nil, ih] + omega + +theorem patterns_length (q : Nat) : (patterns q).length = 2 ^ q := by + induction q with + | zero => rfl + | succ q ih => + rw [patterns, flatMap_pair_length, ih, Nat.pow_succ] + exact Nat.mul_comm _ _ + +theorem mem_patterns (q : Nat) (p : Pattern q) : p ∈ patterns q := by + induction q with + | zero => + have h : p = Fin.elim0 := by funext i; exact Fin.elim0 i + simp [patterns, h] + | succ q ih => + let tail : Pattern q := fun i => p i.succ + have htail : tail ∈ patterns q := ih tail + have prefixEquality : Fin.cases (p 0) tail = p := by + funext i + exact Fin.cases rfl (fun _ => rfl) i + apply List.mem_flatMap.mpr + refine ⟨tail, htail, ?_⟩ + cases h : p 0 with + | false => + have hp : Fin.cases false tail = p := by simpa only [h] using prefixEquality + exact List.mem_cons.mpr (Or.inl hp.symm) + | true => + have hp : Fin.cases true tail = p := by simpa only [h] using prefixEquality + exact List.mem_cons.mpr (Or.inr (List.mem_cons.mpr (Or.inl hp.symm))) + +abbrev PatternIndex (q : Nat) := Fin (patterns q).length +def patternAt (q : Nat) (p : PatternIndex q) : Pattern q := (patterns q)[p.val] + +theorem patternAt_surjective (q : Nat) (bits : Pattern q) : + ∃ p : PatternIndex q, patternAt q p = bits := by + obtain ⟨i, hi, h⟩ := List.getElem_of_mem (mem_patterns q bits) + exact ⟨⟨i, hi⟩, h⟩ + +structure FiniteVerifier (q : Nat) where + «variables» : Nat + events : Nat + query : Fin events → Fin q → Fin «variables» + accepts : Fin events → Pattern q → Bool + +def eventValue {q : Nat} (V : FiniteVerifier q) (A : Fin V.«variables» → Bool) + (e : Fin V.events) : Bool := V.accepts e (fun i => A (V.query e i)) + +def rejectedEventCount {q : Nat} (V : FiniteVerifier q) (A : Fin V.«variables» → Bool) : Nat := + ((List.finRange V.events).map (eventValue V A)).count false + +def auxiliaryCount {q : Nat} (V : FiniteVerifier q) : Nat := + V.events * (patterns q).length * (q - 3) + +def outputVariables {q : Nat} (V : FiniteVerifier q) : Nat := V.«variables» + auxiliaryCount V + +def oldIndex {q : Nat} (V : FiniteVerifier q) (v : Fin V.«variables») : Fin (outputVariables V) := + Fin.castAdd (auxiliaryCount V) v + +def freshIndex {q : Nat} (V : FiniteVerifier q) (e : Fin V.events) + (p : PatternIndex q) (j : Fin (q - 3)) : Fin (outputVariables V) := + Fin.natAdd V.«variables» (finProdFinEquiv (finProdFinEquiv (e, p), j)) + +theorem freshIndex_value {q : Nat} (V : FiniteVerifier q) (e : Fin V.events) + (p : PatternIndex q) (j : Fin (q - 3)) : + (freshIndex V e p j).val = + V.«variables» + ((e.val * (patterns q).length + p.val) * (q - 3) + j.val) := by + simp [freshIndex, Fin.natAdd, finProdFinEquiv, Nat.mul_comm, Nat.add_comm] + +def liftLiteral {q : Nat} (V : FiniteVerifier q) (l : Literal V.«variables») : + Literal (outputVariables V) := ⟨oldIndex V l.variableIndex, l.positive⟩ + +def forbiddenLiteral {q : Nat} (V : FiniteVerifier q) (e : Fin V.events) + (p : PatternIndex q) (i : Fin q) : Literal V.«variables» := + ⟨V.query e i, !(patternAt q p i)⟩ + +def forbiddenClause {q : Nat} (V : FiniteVerifier q) (e : Fin V.events) + (p : PatternIndex q) : List (Literal (outputVariables V)) := + List.ofFn (fun i => liftLiteral V (forbiddenLiteral V e p i)) + +def auxiliaryNames {q : Nat} (V : FiniteVerifier q) (e : Fin V.events) + (p : PatternIndex q) : List (Fin (outputVariables V)) := + List.ofFn (freshIndex V e p) + +def splitLong {n : Nat} : List (Literal n) → List (Fin n) → List (Clause n) + | [a, b, c], [] => [#v[a, b, c]] + | a :: b :: rest, y :: ys => + #v[a, b, ⟨y, true⟩] :: splitLong (⟨y, false⟩ :: rest) ys + | _, _ => [] + +def tautology {q : Nat} (V : FiniteVerifier q) (hq : 3 ≤ q) (e : Fin V.events) : + Clause (outputVariables V) := + let v := oldIndex V (V.query e ⟨0, by omega⟩) + #v[⟨v, true⟩, ⟨v, false⟩, ⟨v, true⟩] + +def block {q : Nat} (V : FiniteVerifier q) (hq : 3 ≤ q) (e : Fin V.events) + (p : PatternIndex q) : List (Clause (outputVariables V)) := + if V.accepts e (patternAt q p) then List.replicate (q - 2) (tautology V hq e) + else splitLong (forbiddenClause V e p) (auxiliaryNames V e p) + +def eventBlock {q : Nat} (V : FiniteVerifier q) (hq : 3 ≤ q) (e : Fin V.events) : + List (Clause (outputVariables V)) := + (List.finRange (patterns q).length).flatMap (block V hq e) + +def convert {q : Nat} (V : FiniteVerifier q) (hq : 3 ≤ q) : Formula where + «variables» := outputVariables V + clauses := (List.finRange V.events).flatMap (eventBlock V hq) + +def clauseFailures {n : Nat} (clauses : List (Clause n)) (A : Fin n → Bool) : Nat := + (clauses.map (fun c => c.eval A)).count false + +theorem splitLong_values {n : Nat} (ls : List (Literal n)) (ys : List (Fin n)) + (A : Fin n → Bool) : + (splitLong ls ys).map (fun c => c.eval A) = + (chainView (ls.map (fun l => l.eval A)) (ys.map A)).map tripleValue := by + induction ys generalizing ls with + | nil => + match ls with + | [] => rfl + | [_] => rfl + | [_, _] => rfl + | [a, b, c] => rfl + | _ :: _ :: _ :: _ :: _ => rfl + | cons y ys ih => + match ls with + | [] => rfl + | [_] => rfl + | a :: b :: rest => + have h := ih (⟨y, false⟩ :: rest) + simp only [splitLong, List.map_cons, chainView] + apply congrArg₂ List.cons + · rfl + · simpa only [List.map_cons, Literal.eval, Bool.false_eq_true, ↓reduceIte] using h + +theorem splitLong_length {n : Nat} (ls : List (Literal n)) (ys : List (Fin n)) + (size : ls.length = ys.length + 3) : (splitLong ls ys).length = ys.length + 1 := by + have values := congrArg List.length (splitLong_values ls ys (fun _ => false)) + simp only [List.length_map] at values + rw [values] + have h := chainView_length (ls.map (fun l => l.eval (fun _ => false))) + (ys.map (fun _ => false)) (by simpa only [List.length_map] using size) + simpa only [List.length_map] using h + +def restrictAssignment {q : Nat} (V : FiniteVerifier q) + (B : Fin (outputVariables V) → Bool) : Fin V.«variables» → Bool := + fun v => B (oldIndex V v) + +def mismatchBits {q : Nat} (V : FiniteVerifier q) (A : Fin V.«variables» → Bool) + (e : Fin V.events) (p : PatternIndex q) : List Bool := + List.ofFn (fun i => (forbiddenLiteral V e p i).eval A) + +@[simp] theorem mismatchBits_length {q : Nat} (V : FiniteVerifier q) + (A : Fin V.«variables» → Bool) (e : Fin V.events) (p : PatternIndex q) : + (mismatchBits V A e p).length = q := by simp [mismatchBits] + +theorem forbiddenLiteral_false {q : Nat} (V : FiniteVerifier q) (A : Fin V.«variables» → Bool) + (e : Fin V.events) (p : PatternIndex q) (i : Fin q) : + (forbiddenLiteral V e p i).eval A = false ↔ A (V.query e i) = patternAt q p i := by + cases hp : patternAt q p i <;> cases ha : A (V.query e i) <;> + simp [forbiddenLiteral, Literal.eval, hp, ha] + +theorem forbiddenClause_values {q : Nat} (V : FiniteVerifier q) + (B : Fin (outputVariables V) → Bool) (e : Fin V.events) (p : PatternIndex q) : + (forbiddenClause V e p).map (fun l => l.eval B) = + mismatchBits V (restrictAssignment V B) e p := by + simp [forbiddenClause, mismatchBits, List.map_ofFn, Function.comp_def, liftLiteral, Literal.eval, + restrictAssignment] + +theorem mismatchBits_false {q : Nat} (V : FiniteVerifier q) (A : Fin V.«variables» → Bool) + (e : Fin V.events) (p : PatternIndex q) + (actual : ∀ i, A (V.query e i) = patternAt q p i) : + (mismatchBits V A e p).any id = false := by + apply List.any_eq_false.mpr + intro b hb + obtain ⟨i, rfl⟩ := List.mem_ofFn.mp hb + have h := (forbiddenLiteral_false V A e p i).mpr (actual i) + simp [h] + +theorem mismatchBits_true {q : Nat} (V : FiniteVerifier q) (A : Fin V.«variables» → Bool) + (e : Fin V.events) (p : PatternIndex q) (honest : eventValue V A e = true) + (rejected : V.accepts e (patternAt q p) = false) : + (mismatchBits V A e p).any id = true := by + cases h : (mismatchBits V A e p).any id with + | true => rfl + | false => + have none := List.any_eq_false.mp h + have equal : (fun i => A (V.query e i)) = patternAt q p := by + funext i + apply (forbiddenLiteral_false V A e p i).mp + have hi := none ((forbiddenLiteral V e p i).eval A) + (List.mem_ofFn.mpr ⟨i, rfl⟩) + cases hv : (forbiddenLiteral V e p i).eval A <;> simp_all + have impossible : V.accepts e (patternAt q p) = true := by + simpa only [eventValue, equal] using honest + rw [rejected] at impossible + contradiction + +theorem mismatchFill_length {q : Nat} (V : FiniteVerifier q) (hq : 3 ≤ q) + (A : Fin V.«variables» → Bool) (e : Fin V.events) (p : PatternIndex q) : + (fillBits (mismatchBits V A e p)).length = q - 3 := by + have h := fillBits_length (mismatchBits V A e p) (by simpa using hq) + rw [mismatchBits_length] at h + omega + +def mismatchFill {q : Nat} (V : FiniteVerifier q) (hq : 3 ≤ q) + (A : Fin V.«variables» → Bool) (e : Fin V.events) (p : PatternIndex q) + (j : Fin (q - 3)) : Bool := + (fillBits (mismatchBits V A e p))[j.val]'(by + rw [mismatchFill_length V hq A e p] + exact j.isLt) + +def extendAssignment {q : Nat} (V : FiniteVerifier q) (hq : 3 ≤ q) + (A : Fin V.«variables» → Bool) : Fin (outputVariables V) → Bool := + Fin.addCases A (fun k : Fin (auxiliaryCount V) => + let pair : Fin (V.events * (patterns q).length) × Fin (q - 3) := finProdFinEquiv.symm k + let ep : Fin V.events × PatternIndex q := finProdFinEquiv.symm pair.1 + mismatchFill V hq A ep.1 ep.2 pair.2) + +@[simp] theorem extend_old {q : Nat} (V : FiniteVerifier q) (hq : 3 ≤ q) + (A : Fin V.«variables» → Bool) (v : Fin V.«variables») : + extendAssignment V hq A (oldIndex V v) = A v := by + simp [extendAssignment, oldIndex] + +@[simp] theorem extend_fresh {q : Nat} (V : FiniteVerifier q) (hq : 3 ≤ q) + (A : Fin V.«variables» → Bool) (e : Fin V.events) (p : PatternIndex q) + (j : Fin (q - 3)) : + extendAssignment V hq A (freshIndex V e p j) = mismatchFill V hq A e p j := by + unfold extendAssignment freshIndex auxiliaryCount + rw [Fin.addCases_right] + simp only [Equiv.symm_apply_apply] + +@[simp] theorem restrict_extend {q : Nat} (V : FiniteVerifier q) (hq : 3 ≤ q) + (A : Fin V.«variables» → Bool) : restrictAssignment V (extendAssignment V hq A) = A := by + funext v + exact extend_old V hq A v + +theorem ofFn_getElem_of_length {α : Type*} (xs : List α) (n : Nat) (h : xs.length = n) : + List.ofFn (fun i : Fin n => xs[i.val]'(by rw [h]; exact i.isLt)) = xs := by + subst n + exact List.ofFn_getElem + +theorem extended_auxiliary_values {q : Nat} (V : FiniteVerifier q) (hq : 3 ≤ q) + (A : Fin V.«variables» → Bool) (e : Fin V.events) (p : PatternIndex q) : + (auxiliaryNames V e p).map (extendAssignment V hq A) = fillBits (mismatchBits V A e p) := by + simp only [auxiliaryNames, List.map_ofFn, Function.comp_def, extend_fresh, mismatchFill] + exact ofFn_getElem_of_length _ _ (mismatchFill_length V hq A e p) + +theorem tautology_satisfied {q : Nat} (V : FiniteVerifier q) (hq : 3 ≤ q) + (e : Fin V.events) (B : Fin (outputVariables V) → Bool) : + (tautology V hq e).eval B = true := by + simp [tautology, Clause.eval, Literal.eval] + +theorem block_length {q : Nat} (V : FiniteVerifier q) (hq : 3 ≤ q) + (e : Fin V.events) (p : PatternIndex q) : (block V hq e p).length = q - 2 := by + by_cases accepted : V.accepts e (patternAt q p) = true + · simp [block, accepted] + · simp only [block, accepted, Bool.false_eq_true, ↓reduceIte] + have size : (forbiddenClause V e p).length = (auxiliaryNames V e p).length + 3 := by + simp only [forbiddenClause, auxiliaryNames, List.length_ofFn] + omega + have h := splitLong_length (forbiddenClause V e p) (auxiliaryNames V e p) size + have auxLength : (auxiliaryNames V e p).length = q - 3 := by simp [auxiliaryNames] + rw [auxLength] at h + omega + +theorem block_honest {q : Nat} (V : FiniteVerifier q) (hq : 3 ≤ q) + (A : Fin V.«variables» → Bool) (e : Fin V.events) (p : PatternIndex q) + (honest : eventValue V A e = true) : + (block V hq e p).all (fun c => c.eval (extendAssignment V hq A)) = true := by + cases accepted : V.accepts e (patternAt q p) with + | true => simp [block, accepted, tautology_satisfied] + | false => + have good := (fillBits_correct (mismatchBits V A e p) (by simpa using hq)).mpr + (mismatchBits_true V A e p honest accepted) + have values := splitLong_values (forbiddenClause V e p) (auxiliaryNames V e p) + (extendAssignment V hq A) + rw [forbiddenClause_values, restrict_extend, extended_auxiliary_values] at values + have all := congrArg (fun bs : List Bool => bs.all id) values + simp only [List.all_map, Function.comp_def, id_eq] at all + simpa only [block, accepted, Bool.false_eq_true, ↓reduceIte] using all.trans good + +theorem length_flatMap_constant {α β : Type*} (xs : List α) (f : α → List β) (k : Nat) + (lengths : ∀ x ∈ xs, (f x).length = k) : (xs.flatMap f).length = xs.length * k := by + induction xs with + | nil => simp + | cons x xs ih => + have hx := lengths x (by simp) + have ht := ih (fun y hy => lengths y (by simp [hy])) + simp only [List.flatMap_cons, List.length_append, List.length_cons, hx, ht, + Nat.add_mul, Nat.one_mul] + omega + +theorem eventBlock_length {q : Nat} (V : FiniteVerifier q) (hq : 3 ≤ q) + (e : Fin V.events) : (eventBlock V hq e).length = 2 ^ q * (q - 2) := by + rw [eventBlock, length_flatMap_constant _ _ (q - 2) (fun p _ => block_length V hq e p)] + simp only [List.length_finRange, patterns_length] + +theorem convert_clause_count {q : Nat} (V : FiniteVerifier q) (hq : 3 ≤ q) : + (convert V hq).clauses.length = V.events * (2 ^ q * (q - 2)) := by + change ((List.finRange V.events).flatMap (eventBlock V hq)).length = _ + rw [length_flatMap_constant _ _ _ (fun e _ => eventBlock_length V hq e)] + rw [List.length_finRange] + +theorem convert_nonempty {q : Nat} (V : FiniteVerifier q) (hq : 3 ≤ q) + (eventsPositive : 0 < V.events) : (convert V hq).clauses ≠ [] := by + have p : 0 < (convert V hq).clauses.length := by + rw [convert_clause_count] + exact Nat.mul_pos eventsPositive (Nat.mul_pos (Nat.pow_pos (by decide)) (by omega)) + intro empty + simp only [empty, List.length_nil] at p + omega + +theorem convert_completeness {q : Nat} (V : FiniteVerifier q) (hq : 3 ≤ q) + (A : Fin V.«variables» → Bool) (honest : ∀ e, eventValue V A e = true) : + (convert V hq).Satisfiable := by + refine ⟨extendAssignment V hq A, fun c hc => ?_⟩ + obtain ⟨e, _, hc⟩ := List.mem_flatMap.mp hc + obtain ⟨p, _, hc⟩ := List.mem_flatMap.mp hc + exact List.all_eq_true.mp (block_honest V hq A e p (honest e)) c hc + +theorem clauseFailures_append {n : Nat} (xs ys : List (Clause n)) (A : Fin n → Bool) : + clauseFailures (xs ++ ys) A = clauseFailures xs A + clauseFailures ys A := by + simp [clauseFailures, List.map_append, List.count_append] + +theorem clauseFailures_le_flatMap {α : Type*} {n : Nat} (xs : List α) + (f : α → List (Clause n)) (A : Fin n → Bool) (x : α) (hx : x ∈ xs) : + clauseFailures (f x) A ≤ clauseFailures (xs.flatMap f) A := by + induction xs with + | nil => simp at hx + | cons y ys ih => + simp only [List.mem_cons] at hx + rcases hx with rfl | hx + · simp only [List.flatMap_cons, clauseFailures_append] + omega + · have h := ih hx + simp only [List.flatMap_cons, clauseFailures_append] + omega + +theorem block_failed {q : Nat} (V : FiniteVerifier q) (hq : 3 ≤ q) + (B : Fin (outputVariables V) → Bool) (e : Fin V.events) (p : PatternIndex q) + (rejected : V.accepts e (patternAt q p) = false) + (actual : ∀ i, restrictAssignment V B (V.query e i) = patternAt q p i) : + 1 ≤ clauseFailures (block V hq e p) B := by + have bitsFalse := mismatchBits_false V (restrictAssignment V B) e p actual + have size : ((forbiddenClause V e p).map (fun l => l.eval B)).length = + ((auxiliaryNames V e p).map B).length + 3 := by + simp only [List.length_map, forbiddenClause, auxiliaryNames, List.length_ofFn] + omega + have failed := chainView_failed ((forbiddenClause V e p).map (fun l => l.eval B)) + ((auxiliaryNames V e p).map B) size (by + rw [forbiddenClause_values] + exact bitsFalse) + simpa only [block, rejected, Bool.false_eq_true, ↓reduceIte, clauseFailures, + splitLong_values] using failed + +theorem eventBlock_failed {q : Nat} (V : FiniteVerifier q) (hq : 3 ≤ q) + (B : Fin (outputVariables V) → Bool) (e : Fin V.events) + (rejected : eventValue V (restrictAssignment V B) e = false) : + 1 ≤ clauseFailures (eventBlock V hq e) B := by + obtain ⟨p, hp⟩ := patternAt_surjective q (fun i => restrictAssignment V B (V.query e i)) + have rejectedPattern : V.accepts e (patternAt q p) = false := by + rw [hp] + exact rejected + have failed := block_failed V hq B e p rejectedPattern (fun i => (congrFun hp i).symm) + exact failed.trans (clauseFailures_le_flatMap (List.finRange (patterns q).length) + (block V hq e) B p (by simp)) + +theorem count_false_map_sum {α : Type*} (xs : List α) (f : α → Bool) : + (xs.map f).count false = (xs.map (fun x => if f x then 0 else 1)).sum := by + induction xs with + | nil => simp + | cons x xs ih => cases h : f x <;> simp [h, ih, Nat.add_comm] + +theorem clauseFailures_flatMap {α : Type*} {n : Nat} (xs : List α) + (f : α → List (Clause n)) (A : Fin n → Bool) : + clauseFailures (xs.flatMap f) A = (xs.map (fun x => clauseFailures (f x) A)).sum := by + induction xs with + | nil => rfl + | cons x xs ih => + simp only [List.flatMap_cons, clauseFailures_append, List.map_cons, List.sum_cons, ih] + +theorem nat_sum_map_le {α : Type*} (xs : List α) (f g : α → Nat) + (bound : ∀ x ∈ xs, f x ≤ g x) : (xs.map f).sum ≤ (xs.map g).sum := by + induction xs with + | nil => exact Nat.le_refl 0 + | cons x xs ih => + simp only [List.map_cons, List.sum_cons] + exact Nat.add_le_add (bound x (by simp)) (ih (fun y hy => bound y (by simp [hy]))) + +theorem convert_count_bridge {q : Nat} (V : FiniteVerifier q) (hq : 3 ≤ q) + (B : Fin (outputVariables V) → Bool) : + rejectedEventCount V (restrictAssignment V B) ≤ NameCompaction.failedCount (convert V hq) B := by + change ((List.finRange V.events).map (eventValue V (restrictAssignment V B))).count false ≤ + clauseFailures ((List.finRange V.events).flatMap (eventBlock V hq)) B + rw [count_false_map_sum, clauseFailures_flatMap] + apply nat_sum_map_le + intro e _ + cases rejected : eventValue V (restrictAssignment V B) e with + | false => simpa only [rejected, Bool.false_eq_true, ↓reduceIte] using + eventBlock_failed V hq B e rejected + | true => simp only [↓reduceIte, Nat.zero_le] + +theorem convert_gap {q : Nat} (V : FiniteVerifier q) (hq : 3 ≤ q) (a b : Nat) + (gap : ∀ A, a * V.events ≤ b * rejectedEventCount V A) + (B : Fin (outputVariables V) → Bool) : + a * (convert V hq).clauses.length ≤ + (b * (2 ^ q * (q - 2))) * NameCompaction.failedCount (convert V hq) B := by + have eventGap := gap (restrictAssignment V B) + have countBound := Nat.mul_le_mul_left b (convert_count_bridge V hq B) + rw [convert_clause_count] + calc + a * (V.events * (2 ^ q * (q - 2))) = (a * V.events) * (2 ^ q * (q - 2)) := by + rw [Nat.mul_assoc] + _ ≤ (b * NameCompaction.failedCount (convert V hq) B) * (2 ^ q * (q - 2)) := + Nat.mul_le_mul_right _ (eventGap.trans countBound) + _ = (b * (2 ^ q * (q - 2))) * NameCompaction.failedCount (convert V hq) B := by ac_rfl + +theorem twelve_query_factor : 2 ^ 12 * (12 - 2) = 40960 := by decide + +theorem twelve_query_clause_count (V : FiniteVerifier 12) : + (convert V (by decide)).clauses.length = V.events * 40960 := by + simpa only [twelve_query_factor] using convert_clause_count V (by decide) + +def padLiteral {n : Nat} (l : Literal n) : Literal (n + 1) := + ⟨Fin.castAdd 1 l.variableIndex, l.positive⟩ + +def padClause {n : Nat} (c : Clause n) : Clause (n + 1) := + #v[padLiteral (c)[0], padLiteral (c)[1], padLiteral (c)[2]] + +def padTautology (n : Nat) : Clause (n + 1) := + let v := Fin.natAdd n (0 : Fin 1) + #v[⟨v, true⟩, ⟨v, false⟩, ⟨v, true⟩] + +def padInput (F : Formula) : Formula where + «variables» := F.«variables» + 1 + clauses := F.clauses.map padClause ++ [padTautology F.«variables»] + +theorem padClause_eval {n : Nat} (c : Clause n) (B : Fin (n + 1) → Bool) : + (padClause c).eval B = c.eval (fun v => B (Fin.castAdd 1 v)) := rfl + +theorem padTautology_satisfied (n : Nat) (B : Fin (n + 1) → Bool) : + (padTautology n).eval B = true := by + simp [padTautology, Clause.eval, Literal.eval] + +theorem padInput_satisfiable_iff (F : Formula) : (padInput F).Satisfiable ↔ F.Satisfiable := by + change (∃ B : Fin (F.«variables» + 1) → Bool, + ∀ c ∈ F.clauses.map padClause ++ [padTautology F.«variables»], c.eval B = true) ↔ _ + constructor + · rintro ⟨B, hB⟩ + refine ⟨fun v => B (Fin.castAdd 1 v), fun c hc => ?_⟩ + have hmem : padClause c ∈ (padInput F).clauses := by + apply List.mem_append.mpr + exact Or.inl (List.mem_map.mpr ⟨c, hc, rfl⟩) + exact (padClause_eval c B).symm.trans (hB _ hmem) + · rintro ⟨A, hA⟩ + let B : Fin (F.«variables» + 1) → Bool := Fin.addCases A (fun _ => false) + refine ⟨B, fun c hc => ?_⟩ + rcases List.mem_append.mp hc with original | padding + · obtain ⟨d, hd, rfl⟩ := List.mem_map.mp original + have h := hA d hd + simpa only [padClause_eval, B, Fin.addCases_left] using h + · have hc : c = padTautology F.«variables» := by simpa using padding + subst c + exact padTautology_satisfied F.«variables» B + +@[simp] theorem padInput_clause_count (F : Formula) : + (padInput F).clauses.length = F.clauses.length + 1 := by simp [padInput] + +theorem padInput_nonempty (F : Formula) : (padInput F).clauses ≠ [] := by + intro empty + have size := padInput_clause_count F + rw [empty, List.length_nil] at size + omega + +def prepareInput (F : Formula) : Formula := NameCompaction.compact (padInput F) + +theorem prepareInput_satisfiable_iff (F : Formula) : + (prepareInput F).Satisfiable ↔ F.Satisfiable := + (NameCompaction.compact_satisfiable_iff (padInput F)).trans (padInput_satisfiable_iff F) + +theorem prepareInput_clause_count (F : Formula) : + (prepareInput F).clauses.length = F.clauses.length + 1 := by + simp only [prepareInput, NameCompaction.compact_clause_count, padInput_clause_count] + +theorem prepareInput_nonempty (F : Formula) : (prepareInput F).clauses ≠ [] := by + intro empty + have h := prepareInput_clause_count F + rw [empty, List.length_nil] at h + omega + +theorem prepareInput_variable_bound (F : Formula) : + (prepareInput F).«variables» ≤ 3 * (F.clauses.length + 1) := by + simpa only [prepareInput, padInput_clause_count] using NameCompaction.compact_active_bound (padInput F) + +end MinUncutGames.Foundations.PCP.VerifierToCNF + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/RoundComputation.lean b/lean/OAI/Computability/MinUncut/PCP/RoundComputation.lean new file mode 100644 index 0000000000000000000000000000000000000000..329424a9feb12781fdabb13063f0f36bccbc2c65 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/RoundComputation.lean @@ -0,0 +1,93 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.RawInitialTables +import OAI.Computability.MinUncut.Machines.PoweringMachineRuntime + +namespace OAI + +section +namespace MinUncutGames.Foundations.PCP.RoundComputation + +open Turing +open MinUncutGames.Foundations.Complexity + + +abbrev PreprocessingCertificate (H : RoundTables.BaseTable) := + TM2ComputableInPolyTime GraphTables.tableBits + (PortTables.inputBits (ports := PreprocessingTables.degree)) + (PreprocessingTables.output H) + +abbrev PoweringCertificate := + TM2ComputableInPolyTime + (PortTables.inputBits (ports := PreprocessingTables.degree)) + (GenericGraphTables.tableBits (q := RoundTables.alphabet)) + (PoweringTables.transform PreprocessingTables.degree RoundTables.walkParameter) + +theorem powered_eq_transform (H : RoundTables.BaseTable) (table : GraphTables.Table) : + RoundTables.powered H table = + PoweringTables.transform PreprocessingTables.degree RoundTables.walkParameter + (PreprocessingTables.output H table) := rfl + +noncomputable def poweredPolynomialTimeOfCertificates (H : RoundTables.BaseTable) + (preprocessing : PreprocessingCertificate H) (powering : PoweringCertificate) : + TM2ComputableInPolyTime GraphTables.tableBits + (GenericGraphTables.tableBits (q := RoundTables.alphabet)) + (RoundTables.powered H) := by + change TM2ComputableInPolyTime GraphTables.tableBits _ + (fun table => PoweringTables.transform PreprocessingTables.degree + RoundTables.walkParameter (PreprocessingTables.output H table)) + exact MachineSequential.composeBits preprocessing powering + +noncomputable def tablePolynomialTimeOfCertificates (H : RoundTables.BaseTable) + (preprocessing : PreprocessingCertificate H) (powering : PoweringCertificate) : + TM2ComputableInPolyTime GraphTables.tableBits GraphTables.tableBits + (RoundTables.build H) := by + change TM2ComputableInPolyTime GraphTables.tableBits GraphTables.tableBits + (fun table => AlphabetTable.Table.build (RoundTables.powered H table)) + exact MachineSequential.composeBits + (poweredPolynomialTimeOfCertificates H preprocessing powering) + (AlphabetTable.Runtime.tablePolynomialTime RoundTables.alphabet) + +theorem powered_finiteAlphabet (H : RoundTables.BaseTable) + (preprocessing : PreprocessingCertificate H) (powering : PoweringCertificate) + (hpreprocessing : MachineFiniteAlphabet.FiniteAlphabet preprocessing.tm) + (hpowering : MachineFiniteAlphabet.FiniteAlphabet powering.tm) : + MachineFiniteAlphabet.FiniteAlphabet + (poweredPolynomialTimeOfCertificates H preprocessing powering).tm := + MachineFiniteAlphabet.composeBits preprocessing powering hpreprocessing hpowering + +theorem finiteAlphabet (H : RoundTables.BaseTable) + (preprocessing : PreprocessingCertificate H) (powering : PoweringCertificate) + (hpreprocessing : MachineFiniteAlphabet.FiniteAlphabet preprocessing.tm) + (hpowering : MachineFiniteAlphabet.FiniteAlphabet powering.tm) : + MachineFiniteAlphabet.FiniteAlphabet + (tablePolynomialTimeOfCertificates H preprocessing powering).tm := + MachineFiniteAlphabet.composeBits + (poweredPolynomialTimeOfCertificates H preprocessing powering) + (AlphabetTable.Runtime.tablePolynomialTime RoundTables.alphabet) + (powered_finiteAlphabet H preprocessing powering hpreprocessing hpowering) + (AlphabetTable.Runtime.finiteAlphabet RoundTables.alphabet) + +noncomputable def tablePolynomialTime (H : RoundTables.BaseTable) + (preprocessing : PreprocessingCertificate H) : + TM2ComputableInPolyTime GraphTables.tableBits GraphTables.tableBits + (RoundTables.build H) := + tablePolynomialTimeOfCertificates H preprocessing + (PoweringMachineRuntime.computableInPolyTime PreprocessingTables.degree + RoundTables.walkParameter) + +theorem tablePolynomialTime_finite_alphabet (H : RoundTables.BaseTable) + (preprocessing : PreprocessingCertificate H) + (hpreprocessing : MachineFiniteAlphabet.FiniteAlphabet preprocessing.tm) : + MachineFiniteAlphabet.FiniteAlphabet + (tablePolynomialTime H preprocessing).tm := + finiteAlphabet H preprocessing + (PoweringMachineRuntime.computableInPolyTime PreprocessingTables.degree + RoundTables.walkParameter) hpreprocessing + (PoweringMachineRuntime.computableInPolyTime_finite_alphabet + PreprocessingTables.degree RoundTables.walkParameter) + +end MinUncutGames.Foundations.PCP.RoundComputation + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/SelectedInformation.lean b/lean/OAI/Computability/MinUncut/PCP/SelectedInformation.lean new file mode 100644 index 0000000000000000000000000000000000000000..c29105e7ed2d675c52ffdc9b8f052d059680cf58 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/SelectedInformation.lean @@ -0,0 +1,699 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.Completion +import OAI.Computability.MinUncut.Games.Pinsker + +namespace OAI + +namespace MinUncutGames.Foundations.Repetition +open scoped BigOperators +open Games Information +noncomputable section + +def mergeCoordinates {Ω : Type*} {n : Nat} (selected : Finset (Fin n)) + (fixed : selected → Ω) (remaining : {i : Fin n // i ∉ selected} → Ω) : Fin n → Ω := + fun i => if h : i ∈ selected then fixed ⟨i,h⟩ else remaining ⟨i,h⟩ + +def coordinateSplitEquiv {Ω : Type*} {n : Nat} (selected : Finset (Fin n)) : + (Fin n → Ω) ≃ ((selected → Ω) × ({i : Fin n // i ∉ selected} → Ω)) where + toFun x := (fun i => x i.1, fun i => x i.1) + invFun x := mergeCoordinates selected x.1 x.2 + left_inv x := by funext i; simp [mergeCoordinates] + right_inv x := by + apply Prod.ext <;> funext i <;> simp [mergeCoordinates, i.property] + +theorem iid_coordinate_split {Ω : Type*} [Fintype Ω] {n : Nat} + (μ : FiniteDistribution Ω) (selected : Finset (Fin n)) : + (μ.iid n).transport (coordinateSplitEquiv selected) = + (FiniteDistribution.table (fun _ : selected => μ)).product + (FiniteDistribution.table (fun _ : {i : Fin n // i ∉ selected} => μ)) := by + classical + apply FiniteDistribution.eq_of_weight_eq + intro x + change (∏ i, μ.weight (mergeCoordinates selected x.1 x.2 i)) = + (∏ i : selected, μ.weight (x.1 i)) * + ∏ i : {i : Fin n // i ∉ selected}, μ.weight (x.2 i) + have h := Fintype.prod_subtype_mul_prod_subtype (fun i : Fin n => i ∈ selected) + (fun i => μ.weight (mergeCoordinates selected x.1 x.2 i)) + have hi : Subtype.fintype (fun i : Fin n => i ∈ selected) = + Finset.Subtype.fintype selected := Subsingleton.elim _ _ + rw [hi] at h + calc + _ = (∏ i : {i : Fin n // i ∈ selected}, + μ.weight (mergeCoordinates selected x.1 x.2 i.1)) * + ∏ i : {i : Fin n // i ∉ selected}, + μ.weight (mergeCoordinates selected x.1 x.2 i.1) := h.symm + _ = _ := by + congr 1 <;> apply Finset.prod_congr rfl <;> intro i _ <;> + simp [mergeCoordinates, i.property] + +variable {Q₁ Q₂ A₁ A₂ : Type*} + [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂] + [DecidableEq Q₁] [DecidableEq Q₂] + {n : Nat} + +abbrev SelectedLabels (selected : Finset (Fin n)) := + (selected → A₁) × (selected → A₂) + +def selectedQuestionTuple (selected : Finset (Fin n)) + (fixed : selected → Q₁ × Q₂) + (remaining : {i : Fin n // i ∉ selected} → Q₁ × Q₂) : + (Fin n → Q₁) × (Fin n → Q₂) := + (fun i => (mergeCoordinates selected fixed remaining i).1, + fun i => (mergeCoordinates selected fixed remaining i).2) + +def selectedAnswerLabel + (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₂)) : + SelectedLabels (A₁ := A₁) (A₂ := A₂) selected := + (fun i => strategy.1 questions.1 i.1, fun i => strategy.2 questions.2 i.1) + +def selectedLikelihood (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (fixed : selected → Q₁ × Q₂) + (label : SelectedLabels (A₁ := A₁) (A₂ := A₂) selected) + (remaining : {i : Fin n // i ∉ selected} → Q₁ × Q₂) : ℝ := by + classical + let questions := selectedQuestionTuple selected fixed remaining + exact if selectedAnswerLabel strategy selected questions = label then + (if G.selectedWins strategy selected questions then 1 else 0) else 0 + +omit [DecidableEq Q₁] [DecidableEq Q₂] in +theorem selectedLikelihood_nonnegative (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (fixed : selected → Q₁ × Q₂) + (label : SelectedLabels (A₁ := A₁) (A₂ := A₂) selected) + (remaining : {i : Fin n // i ∉ selected} → Q₁ × Q₂) : + 0 ≤ selectedLikelihood G strategy selected fixed label remaining := by + classical + dsimp only [selectedLikelihood] + split_ifs <;> norm_num + +omit [DecidableEq Q₁] [DecidableEq Q₂] in +theorem selectedLikelihood_sum (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (fixed : selected → Q₁ × Q₂) + (remaining : {i : Fin n // i ∉ selected} → Q₁ × Q₂) : + (∑ label, selectedLikelihood G strategy selected fixed label remaining) = + if G.selectedWins strategy selected (selectedQuestionTuple selected fixed remaining) + then 1 else 0 := by + classical + simp [selectedLikelihood] + +omit [DecidableEq Q₁] [DecidableEq Q₂] in +theorem selectedLikelihood_sum_le_one (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (fixed : selected → Q₁ × Q₂) + (remaining : {i : Fin n // i ∉ selected} → Q₁ × Q₂) : + (∑ label, selectedLikelihood G strategy selected fixed label remaining) ≤ 1 := by + rw [selectedLikelihood_sum] + split <;> norm_num + +def selectedSplitLaw (G : Game Q₁ Q₂ A₁ A₂) (selected : Finset (Fin n)) : + FiniteDistribution ((selected → Q₁ × Q₂) × + ({i : Fin n // i ∉ selected} → Q₁ × Q₂)) := + (FiniteDistribution.table (fun _ : selected => G.questions)).product + (FiniteDistribution.table (fun _ : {i : Fin n // i ∉ selected} => G.questions)) + +omit [DecidableEq Q₁] [DecidableEq Q₂] in +theorem selectedSplit_probability (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) : + (selectedSplitLaw G selected).probability + (fun q => G.selectedWins strategy selected (selectedQuestionTuple selected q.1 q.2)) = + G.selectedSuccess strategy selected := by + rw [selectedSplitLaw, ← iid_coordinate_split, FiniteDistribution.probability_transport] + change (G.questions.iid n).probability _ = + ((G.questions.iid n).transport (Game.tupleQuestionEquiv n)).probability _ + rw [FiniteDistribution.probability_transport] + apply congrArg (G.questions.iid n).probability + funext q + congr 1 + apply Prod.ext <;> funext i <;> + simp [selectedQuestionTuple, coordinateSplitEquiv, mergeCoordinates, Game.tupleQuestionEquiv] + +abbrev SelectedInput (Q₁ Q₂ : Type*) {n : Nat} (selected : Finset (Fin n)) := + (selected → Q₁ × Q₂) × ({i : Fin n // i ∉ selected} → Q₁ ⊕ Q₂) + +def selectedInputLaw (G : Game Q₁ Q₂ A₁ A₂) (selected : Finset (Fin n)) : + FiniteDistribution (SelectedInput Q₁ Q₂ selected) := + (FiniteDistribution.table (fun _ : selected => G.questions)).product + (FiniteDistribution.table (fun _ : {i : Fin n // i ∉ selected} => revealInputLaw G.questions)) + +def selectedInputProfile (G : Game Q₁ Q₂ A₁ A₂) (selected : Finset (Fin n)) + (t : SelectedInput Q₁ Q₂ selected) (i : {i : Fin n // i ∉ selected}) : + FiniteDistribution (Q₁ × Q₂) := revealProfile G.questions (t.2 i) + +def selectedSideMass (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) + (tv : SelectedInput Q₁ Q₂ selected × SelectedLabels (A₁ := A₁) (A₂ := A₂) selected) : ℝ := + ∑ u, independentProduct (fun i => (selectedInputProfile G selected tv.1 i).weight) u * + selectedLikelihood G strategy selected tv.1.1 tv.2 u + +omit [DecidableEq Q₁] [DecidableEq Q₂] in +theorem selectedSideMass_sum (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (t : SelectedInput Q₁ Q₂ selected) : + (∑ v, selectedSideMass G strategy selected (t,v)) = + ∑ u, independentProduct (fun i => (selectedInputProfile G selected t i).weight) u * + (if G.selectedWins strategy selected (selectedQuestionTuple selected t.1 u) + then 1 else 0) := by + classical + simp only [selectedSideMass] + rw [Finset.sum_comm] + simp_rw [← Finset.mul_sum, selectedLikelihood_sum] + +theorem selectedSideMass_total (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) : + (∑ tv, (selectedInputLaw G selected).weight tv.1 * + selectedSideMass G strategy selected tv) = G.selectedSuccess strategy selected := by + classical + rw [Fintype.sum_prod_type] + simp_rw [← Finset.mul_sum, selectedSideMass_sum] + rw [Fintype.sum_prod_type] + simp only [selectedInputLaw, FiniteDistribution.product, FiniteDistribution.table, + selectedInputProfile, independentProduct] + simp_rw [mul_assoc, ← Finset.mul_sum] + have hforget (fixed : selected → Q₁ × Q₂) := + reveal_product_expectation G.questions + (fun u : {i : Fin n // i ∉ selected} → Q₁ × Q₂ => + if G.selectedWins strategy selected (selectedQuestionTuple selected fixed u) + then (1 : ℝ) else 0) + simp_rw [hforget] + have h := selectedSplit_probability G strategy selected + simpa [selectedSplitLaw, FiniteDistribution.probability, FiniteDistribution.product, + FiniteDistribution.table, Fintype.sum_prod_type, Finset.mul_sum, mul_ite, mul_assoc] using h + +def selectedSideWeight (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) + (tv : SelectedInput Q₁ Q₂ selected × SelectedLabels (A₁ := A₁) (A₂ := A₂) selected) : ℝ := + (selectedInputLaw G selected).weight tv.1 * selectedSideMass G strategy selected tv / + G.selectedSuccess strategy selected + +theorem selected_information_bound [Nonempty A₁] [Nonempty A₂] + (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) : + (∑ i : {i : Fin n // i ∉ selected}, totalVariation + (fun tva : (SelectedInput Q₁ Q₂ selected × + SelectedLabels (A₁ := A₁) (A₂ := A₂) selected) × (Q₁ × Q₂) => + selectedSideWeight G strategy selected tva.1 * coordinateMarginal + (posteriorOrOriginal + (independentProduct (fun j => (selectedInputProfile G selected tva.1.1 j).weight)) + (selectedLikelihood G strategy selected tva.1.1.1 tva.1.2) + (selectedSideMass G strategy selected tva.1)) i tva.2) + (fun tva => selectedSideWeight G strategy selected tva.1 * + (selectedInputProfile G selected tva.1.1 i).weight tva.2)) ≤ + Real.sqrt ((Fintype.card {i : Fin n // i ∉ selected} : ℝ) * + (Real.log (Fintype.card (SelectedLabels (A₁ := A₁) (A₂ := A₂) selected) : ℝ) + + Real.log (1 / G.selectedSuccess strategy selected))) := by + exact finite_side_information_bound (selectedInputLaw G selected).weight + (fun t i => (selectedInputProfile G selected t i).weight) + (fun tv => selectedLikelihood G strategy selected tv.1.1 tv.2) + (selectedSideMass G strategy selected) (selectedSideWeight G strategy selected) + (gameLaw_isProbability _) (fun t i => gameLaw_isProbability _) + (fun tv => selectedLikelihood_nonnegative G strategy selected tv.1.1 tv.2) + (fun t => selectedLikelihood_sum_le_one G strategy selected t.1) + (fun _ => rfl) positive (selectedSideMass_total G strategy selected) (fun _ => rfl) + +variable {Q₁ Q₂ A₁ A₂ : Type*} + [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂] + [DecidableEq Q₁] [DecidableEq Q₂] {n : Nat} + +def selectedJointWeight (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) + (z : (SelectedInput Q₁ Q₂ selected × SelectedLabels (A₁ := A₁) (A₂ := A₂) selected) × + ({i : Fin n // i ∉ selected} → Q₁ × Q₂)) : ℝ := + (selectedInputLaw G selected).weight z.1.1 * + independentProduct (fun i => (selectedInputProfile G selected z.1.1 i).weight) z.2 * + selectedLikelihood G strategy selected z.1.1.1 z.1.2 z.2 / + G.selectedSuccess strategy selected + +omit [DecidableEq Q₁] [DecidableEq Q₂] in +theorem selectedJointWeight_nonnegative (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (z) : 0 ≤ selectedJointWeight G strategy selected z := by + apply div_nonneg + · exact mul_nonneg + (mul_nonneg ((selectedInputLaw G selected).nonnegative _) + ((independentProduct_isProbability _ + (fun i => gameLaw_isProbability (selectedInputProfile G selected z.1.1 i))).1 z.2)) + (selectedLikelihood_nonnegative G strategy selected z.1.1.1 z.1.2 z.2) + · exact G.selectedSuccess_nonnegative strategy selected + +omit [DecidableEq Q₁] [DecidableEq Q₂] in +theorem selectedJointWeight_firstMarginal (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (tv) : + firstMarginal (selectedJointWeight G strategy selected) tv = + selectedSideWeight G strategy selected tv := by + simp only [firstMarginal, selectedJointWeight, selectedSideWeight, selectedSideMass, + div_eq_mul_inv, Finset.mul_sum, Finset.sum_mul] + apply Finset.sum_congr rfl + intro i _ + ring + +theorem selectedJointWeight_isProbability (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) : + IsProbability (selectedJointWeight G strategy selected) := by + constructor + · exact selectedJointWeight_nonnegative G strategy selected + · rw [Fintype.sum_prod_type] + change (∑ tv, firstMarginal (selectedJointWeight G strategy selected) tv) = 1 + simp_rw [selectedJointWeight_firstMarginal, selectedSideWeight, div_eq_mul_inv] + rw [← Finset.sum_mul, selectedSideMass_total, mul_inv_cancel₀ positive.ne'] + +def selectedJointLaw (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) := + toGameLaw (selectedJointWeight G strategy selected) + (selectedJointWeight_isProbability G strategy selected positive) + +theorem selectedJointWeight_factorization (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (tv) (u) : + selectedJointWeight G strategy selected (tv,u) = + (∏ i : selected, G.questions.weight (tv.1.1 i)) * + (∏ i : {i : Fin n // i ∉ selected}, (revealLaw G.questions).weight (u i,tv.1.2 i)) * + selectedLikelihood G strategy selected tv.1.1 tv.2 u / + G.selectedSuccess strategy selected := by + unfold selectedJointWeight + simp only [selectedInputLaw, FiniteDistribution.product, FiniteDistribution.table, + independentProduct, selectedInputProfile] + rw [mul_assoc (∏ i : selected, G.questions.weight (tv.1.1 i)), reveal_product_factorization] + +open scoped BigOperators +open Information + +variable {α β : Type*} [Fintype α] [Fintype β] + +theorem totalVariation_triangle (p q r : α → ℝ) : + totalVariation p r ≤ totalVariation p q + totalVariation q r := by + have hpoint : ∀ a, |p a - r a| ≤ |p a - q a| + |q a - r a| := by + intro a + have := abs_add_le (p a - q a) (q a - r a) + simpa only [sub_add_sub_cancel] using this + have hsum := Finset.sum_le_sum (fun a (_ : a ∈ (Finset.univ : Finset α)) => hpoint a) + simp only [Finset.sum_add_distrib] at hsum + unfold totalVariation + linarith + +noncomputable def conditionWeights (p : α → ℝ) (event : α → Bool) (z : ℝ) : α → ℝ := + fun a => if event a then p a / z else 0 + +theorem conditionWeights_isProbability (p : α → ℝ) (hp : IsProbability p) + (event : α → Bool) {z : ℝ} (hz : 0 < z) + (hmass : ∑ a, (if event a then p a else 0) = z) : + IsProbability (conditionWeights p event z) := by + constructor + · intro a + dsimp [conditionWeights] + split + · exact div_nonneg (hp.1 a) hz.le + · exact le_rfl + · have hpoint : ∀ a, conditionWeights p event z a = + (if event a then p a else 0) / z := by + intro a + simp only [conditionWeights] + split <;> simp + simp only [hpoint, div_eq_mul_inv, ← Finset.sum_mul, hmass, mul_inv_cancel₀ hz.ne'] + +theorem totalVariation_condition_le (p q : α → ℝ) (event : α → Bool) + {z : ℝ} (hz : 0 < z) : + totalVariation (conditionWeights p event z) (conditionWeights q event z) ≤ + totalVariation p q / z := by + have hpoint : ∀ a, + |conditionWeights p event z a - conditionWeights q event z a| ≤ + |p a - q a| / z := by + intro a + dsimp [conditionWeights] + split + · rw [← sub_div, abs_div, abs_of_pos hz] + · simp only [sub_self, abs_zero] + positivity + have hsum := Finset.sum_le_sum (fun a (_ : a ∈ (Finset.univ : Finset α)) => hpoint a) + simp only [div_eq_mul_inv, ← Finset.sum_mul] at hsum + have hsum' : (∑ a, |conditionWeights p event z a - conditionWeights q event z a|) ≤ + (∑ a, |p a - q a|) / z := by + simpa only [div_eq_mul_inv] using hsum + unfold totalVariation + calc + _ ≤ (∑ a, |p a - q a|) / z / 2 := div_le_div_of_nonneg_right hsum' (by norm_num) + _ = _ := by ring + +theorem totalVariation_condition_half_le (p q : α → ℝ) (event : α → Bool) : + totalVariation (conditionWeights p event (1 / 2)) + (conditionWeights q event (1 / 2)) ≤ 2 * totalVariation p q := by + have h := totalVariation_condition_le p q event (z := 1 / 2) (by norm_num) + convert h using 1; ring + +theorem totalVariation_append_kernel (p q : α → ℝ) (kernel : α → β → ℝ) + (hk : ∀ a, IsProbability (kernel a)) : + totalVariation (fun ab : α × β => p ab.1 * kernel ab.1 ab.2) + (fun ab : α × β => q ab.1 * kernel ab.1 ab.2) = totalVariation p q := by + unfold totalVariation + congr 1 + rw [Fintype.sum_prod_type] + apply Finset.sum_congr rfl + intro a _ + have habs : ∀ b, |kernel a b| = kernel a b := fun b => abs_of_nonneg ((hk a).1 b) + simp only [← sub_mul, abs_mul, habs, ← Finset.mul_sum, (hk a).2, + mul_one] + +noncomputable def kernelPushforward (p : α → ℝ) (kernel : α → β → ℝ) : β → ℝ := + fun b => ∑ a, p a * kernel a b + +theorem totalVariation_kernelPushforward_le (p q : α → ℝ) (kernel : α → β → ℝ) + (hk : ∀ a, IsProbability (kernel a)) : + totalVariation (kernelPushforward p kernel) (kernelPushforward q kernel) ≤ + totalVariation p q := by + have hpoint : ∀ b, + |kernelPushforward p kernel b - kernelPushforward q kernel b| ≤ + ∑ a, |p a - q a| * kernel a b := by + intro b + simp only [kernelPushforward, ← Finset.sum_sub_distrib, ← sub_mul] + have h := Finset.abs_sum_le_sum_abs (fun a => (p a - q a) * kernel a b) Finset.univ + have habs : ∀ a, |kernel a b| = kernel a b := fun a => abs_of_nonneg ((hk a).1 b) + simpa only [abs_mul, habs] using h + have hsum := Finset.sum_le_sum (fun b (_ : b ∈ (Finset.univ : Finset β)) => hpoint b) + rw [Finset.sum_comm] at hsum + simp only [← Finset.mul_sum, (hk _).2, mul_one] at hsum + exact div_le_div_of_nonneg_right hsum (by norm_num : (0 : ℝ) ≤ 2) + +open scoped BigOperators +variable {S X Y : Type*} [Fintype S] [Fintype X] [Fintype Y] + [DecidableEq X] [DecidableEq Y] + +def maskedJoint (p : S × (X × Y) → ℝ) : (S × (X ⊕ Y)) × (X × Y) → ℝ := fun z => + (if z.1.2 = Sum.inl z.2.1 then p (z.1.1, z.2) / 2 else 0) + + (if z.1.2 = Sum.inr z.2.2 then p (z.1.1, z.2) / 2 else 0) + +def maskedModel (μ : Games.FiniteDistribution (X × Y)) (p : S × (X × Y) → ℝ) : + (S × (X ⊕ Y)) × (X × Y) → ℝ := fun z => + Information.firstMarginal (maskedJoint p) z.1 * (revealProfile μ z.1.2).weight z.2 + +def leftRevealModel (μ : Games.FiniteDistribution (X × Y)) (p : S × (X × Y) → ℝ) : + S × (X × Y) → ℝ := fun z => + (∑ y, p (z.1, (z.2.1, y))) * (revealProfile μ (Sum.inl z.2.1)).weight z.2 + +def rightRevealModel (μ : Games.FiniteDistribution (X × Y)) (p : S × (X × Y) → ℝ) : + S × (X × Y) → ℝ := fun z => + (∑ x, p (z.1, (x, z.2.2))) * (revealProfile μ (Sum.inr z.2.2)).weight z.2 + +theorem sum_maskedJoint (p : S × (X × Y) → ℝ) : + (∑ z, maskedJoint p z) = ∑ z, p z := by + classical + have hrow (s : S) (q : X × Y) : + (∑ r : X ⊕ Y, maskedJoint p ((s,r),q)) = p (s,q) := by + simp [maskedJoint] + calc + _ = ∑ s : S, ∑ r : X ⊕ Y, ∑ q : X × Y, maskedJoint p ((s,r),q) := by + simp only [Fintype.sum_prod_type] + _ = ∑ s : S, ∑ q : X × Y, p (s,q) := by + apply Finset.sum_congr rfl + intro s _ + rw [Finset.sum_comm] + simp_rw [hrow] + _ = _ := (Fintype.sum_prod_type _).symm + +theorem maskedJoint_isProbability_iff (p : S × (X × Y) → ℝ) : + Information.IsProbability (maskedJoint p) ↔ Information.IsProbability p := by + classical + constructor + · intro h + constructor + · intro z + have hp := h.1 ((z.1,Sum.inl z.2.1),z.2) + simp [maskedJoint] at hp + linarith + · rw [← sum_maskedJoint] + exact h.2 + · intro h + constructor + · intro z + have hp : 0 ≤ p (z.1.1,z.2) / 2 := div_nonneg (h.1 _) (by norm_num) + dsimp [maskedJoint] + split_ifs <;> linarith + · rw [sum_maskedJoint] + exact h.2 + +omit [Fintype S] in +theorem maskedJoint_firstMarginal_inl (p : S × (X × Y) → ℝ) (s : S) (x : X) : + Information.firstMarginal (maskedJoint p) (s, Sum.inl x) = + (∑ y, p (s, (x, y))) / 2 := by + simp [Information.firstMarginal, maskedJoint, Fintype.sum_prod_type, + div_eq_mul_inv, Finset.sum_mul] + rw [Finset.sum_comm] + simp + +omit [Fintype S] in +theorem maskedJoint_firstMarginal_inr (p : S × (X × Y) → ℝ) (s : S) (y : Y) : + Information.firstMarginal (maskedJoint p) (s, Sum.inr y) = + (∑ x, p (s, (x, y))) / 2 := by + simp [Information.firstMarginal, maskedJoint, Fintype.sum_prod_type, + div_eq_mul_inv, Finset.sum_mul] + +private theorem abs_half_sub_half_mul (a b c : ℝ) : + |a / 2 - b / 2 * c| = |a - b * c| / 2 := by + rw [show a / 2 - b / 2 * c = (a - b * c) / 2 by ring, abs_div] + norm_num + +omit [Fintype S] in +theorem abs_masked_inl (μ : Games.FiniteDistribution (X × Y)) + (p : S × (X × Y) → ℝ) (s : S) (u x : X) (y : Y) : + |maskedJoint p ((s, Sum.inl u), (x, y)) - maskedModel μ p ((s, Sum.inl u), (x, y))| = + if x = u then |p (s, (x, y)) - leftRevealModel μ p (s, (x, y))| / 2 else 0 := by + by_cases hx : x = u + · subst x + simp only [maskedModel, maskedJoint_firstMarginal_inl] + simpa [maskedJoint, leftRevealModel] using + abs_half_sub_half_mul (p (s, (u, y))) (∑ v, p (s, (u, v))) + ((revealProfile μ (Sum.inl u)).weight (u, y)) + · have hs := revealProfile_inl_support μ u (x, y) hx + simp [maskedJoint, maskedModel, hs, hx, Ne.symm hx] + +omit [Fintype S] in +theorem abs_masked_inr (μ : Games.FiniteDistribution (X × Y)) + (p : S × (X × Y) → ℝ) (s : S) (v : Y) (x : X) (y : Y) : + |maskedJoint p ((s, Sum.inr v), (x, y)) - maskedModel μ p ((s, Sum.inr v), (x, y))| = + if y = v then |p (s, (x, y)) - rightRevealModel μ p (s, (x, y))| / 2 else 0 := by + by_cases hy : y = v + · subst y + simp only [maskedModel, maskedJoint_firstMarginal_inr] + simpa [maskedJoint, rightRevealModel] using + abs_half_sub_half_mul (p (s, (x, v))) (∑ u, p (s, (u, v))) + ((revealProfile μ (Sum.inr v)).weight (x, v)) + · have hs := revealProfile_inr_support μ v (x, y) hy + simp [maskedJoint, maskedModel, hs, hy, Ne.symm hy] + +theorem masked_totalVariation_identity (μ : Games.FiniteDistribution (X × Y)) + (p : S × (X × Y) → ℝ) : + 2 * Information.totalVariation (maskedJoint p) (maskedModel μ p) = + Information.totalVariation p (leftRevealModel μ p) + + Information.totalVariation p (rightRevealModel μ p) := by + have hleft (s : S) : + (∑ u : X, ∑ q : X × Y, + |maskedJoint p ((s, Sum.inl u), q) - maskedModel μ p ((s, Sum.inl u), q)|) = + (∑ q : X × Y, |p (s, q) - leftRevealModel μ p (s, q)|) / 2 := by + simp_rw [Fintype.sum_prod_type, abs_masked_inl] + simp [Finset.sum_ite_irrel, div_eq_mul_inv, Finset.sum_mul] + have hright (s : S) : + (∑ v : Y, ∑ q : X × Y, + |maskedJoint p ((s, Sum.inr v), q) - maskedModel μ p ((s, Sum.inr v), q)|) = + (∑ q : X × Y, |p (s, q) - rightRevealModel μ p (s, q)|) / 2 := by + have hcollapse : + (∑ v : Y, ∑ q : X × Y, + |maskedJoint p ((s, Sum.inr v), q) - maskedModel μ p ((s, Sum.inr v), q)|) = + ∑ v : Y, ∑ x : X, |p (s, (x, v)) - rightRevealModel μ p (s, (x, v))| / 2 := by + simp [Fintype.sum_prod_type, abs_masked_inr] + rw [hcollapse, Finset.sum_comm] + simp [Fintype.sum_prod_type, div_eq_mul_inv, Finset.sum_mul] + have hmass : + (∑ z : (S × (X ⊕ Y)) × (X × Y), |maskedJoint p z - maskedModel μ p z|) = + ((∑ z : S × (X × Y), |p z - leftRevealModel μ p z|) + + (∑ z : S × (X × Y), |p z - rightRevealModel μ p z|)) / 2 := by + calc + _ = ∑ s : S, + ((∑ u : X, ∑ q : X × Y, |maskedJoint p ((s, Sum.inl u), q) - maskedModel μ p ((s, Sum.inl u), q)|) + + (∑ v : Y, ∑ q : X × Y, |maskedJoint p ((s, Sum.inr v), q) - maskedModel μ p ((s, Sum.inr v), q)|)) := by + simp only [Fintype.sum_prod_type, Fintype.sum_sum_type] + _ = ∑ s : S, + ((∑ q : X × Y, |p (s, q) - leftRevealModel μ p (s, q)|) / 2 + + (∑ q : X × Y, |p (s, q) - rightRevealModel μ p (s, q)|) / 2) := by + simp_rw [hleft, hright] + _ = _ := by + simp [Fintype.sum_prod_type, div_eq_mul_inv, Finset.sum_add_distrib, Finset.sum_mul, add_mul] + unfold Information.totalVariation + rw [hmass] + ring + +theorem leftRevealModel_totalVariation_le (μ : Games.FiniteDistribution (X × Y)) + (p : S × (X × Y) → ℝ) : + Information.totalVariation p (leftRevealModel μ p) ≤ + 2 * Information.totalVariation (maskedJoint p) (maskedModel μ p) := by + rw [masked_totalVariation_identity] + linarith [Information.totalVariation_nonneg p (rightRevealModel μ p)] + +theorem rightRevealModel_totalVariation_le (μ : Games.FiniteDistribution (X × Y)) + (p : S × (X × Y) → ℝ) : + Information.totalVariation p (rightRevealModel μ p) ≤ + 2 * Information.totalVariation (maskedJoint p) (maskedModel μ p) := by + rw [masked_totalVariation_identity] + linarith [Information.totalVariation_nonneg p (leftRevealModel μ p)] + +variable {I T X Y : Type*} [Fintype I] [DecidableEq I] [Fintype T] + [Fintype X] [Fintype Y] [DecidableEq X] [DecidableEq Y] + +def mergeAt {R : Type*} (j : I) (a : R) (rest : {i : I // i ≠ j} → R) : I → R := + fun i => if h : i = j then a else rest ⟨i,h⟩ + +omit [Fintype I] in +@[simp] theorem mergeAt_self {R : Type*} (j : I) (a : R) (rest : {i : I // i ≠ j} → R) : + mergeAt j a rest j = a := by simp [mergeAt] + +omit [Fintype I] in +@[simp] theorem mergeAt_other {R : Type*} (j : I) (a : R) + (rest : {i : I // i ≠ j} → R) (i : {i : I // i ≠ j}) : + mergeAt j a rest i.1 = rest i := by simp [mergeAt, i.property] + +def partialRevealWeight (μ : Games.FiniteDistribution (X × Y)) (j : I) + (rest : {i : I // i ≠ j} → X ⊕ Y) (u : I → X × Y) : ℝ := + μ.weight (u j) * ∏ i : {i : I // i ≠ j}, (revealLaw μ).weight (u i.1,rest i) + +theorem product_reveal_at (μ : Games.FiniteDistribution (X × Y)) (j : I) + (r : X ⊕ Y) (rest : {i : I // i ≠ j} → X ⊕ Y) (u : I → X × Y) : + (∏ i, (revealLaw μ).weight (u i,mergeAt j r rest i)) = + (if r = Sum.inl (u j).1 then partialRevealWeight μ j rest u / 2 else 0) + + (if r = Sum.inr (u j).2 then partialRevealWeight μ j rest u / 2 else 0) := by + rw [Fintype.prod_eq_mul_prod_subtype_ne _ j] + simp only [mergeAt_self, mergeAt_other, revealLaw_weight] + by_cases hl : r = Sum.inl (u j).1 <;> by_cases hr : r = Sum.inr (u j).2 <;> + simp [hl, hr, partialRevealWeight, revealLaw_weight] <;> ring + +def partialRevealMarginal (μ : Games.FiniteDistribution (X × Y)) (j : I) + (likelihood : T → (I → X × Y) → ℝ) : + (T × ({i : I // i ≠ j} → X ⊕ Y)) × (X × Y) → ℝ := by + classical + exact fun z => ∑ u, if u j = z.2 then + partialRevealWeight μ j z.1.2 u * likelihood z.1.1 u else 0 + +def fullRevealMarginal (μ : Games.FiniteDistribution (X × Y)) (j : I) + (likelihood : T → (I → X × Y) → ℝ) : + (T × (I → X ⊕ Y)) × (X × Y) → ℝ := by + classical + exact fun z => ∑ u, if u j = z.2 then + (∏ i, (revealLaw μ).weight (u i,z.1.2 i)) * likelihood z.1.1 u else 0 + +omit [Fintype T] in +theorem fullRevealMarginal_merge (μ : Games.FiniteDistribution (X × Y)) (j : I) + (likelihood : T → (I → X × Y) → ℝ) (t : T) + (rest : {i : I // i ≠ j} → X ⊕ Y) (r : X ⊕ Y) (q : X × Y) : + fullRevealMarginal μ j likelihood ((t,mergeAt j r rest),q) = + maskedJoint (partialRevealMarginal μ j likelihood) (((t,rest),r),q) := by + classical + unfold fullRevealMarginal + simp_rw [product_reveal_at] + have hpoint (u : I → X × Y) : + (if u j = q then + ((if r = Sum.inl (u j).1 then partialRevealWeight μ j rest u / 2 else 0) + + (if r = Sum.inr (u j).2 then partialRevealWeight μ j rest u / 2 else 0)) * + likelihood t u else 0) = + (if r = Sum.inl q.1 then + (if u j = q then partialRevealWeight μ j rest u * likelihood t u else 0) / 2 else 0) + + (if r = Sum.inr q.2 then + (if u j = q then partialRevealWeight μ j rest u * likelihood t u else 0) / 2 else 0) := by + by_cases hu : u j = q + · rw [hu] + by_cases hl : r = Sum.inl q.1 <;> by_cases hr : r = Sum.inr q.2 <;> + simp [hl, hr] <;> ring + · simp [hu] + simp_rw [hpoint] + simp [maskedJoint, partialRevealMarginal, Finset.sum_add_distrib, + Finset.sum_ite_irrel, div_eq_mul_inv, Finset.sum_mul] + +def fullRevealModel (μ : Games.FiniteDistribution (X × Y)) (j : I) + (likelihood : T → (I → X × Y) → ℝ) : + (T × (I → X ⊕ Y)) × (X × Y) → ℝ := fun z => + Information.firstMarginal (fullRevealMarginal μ j likelihood) z.1 * + (revealProfile μ (z.1.2 j)).weight z.2 + +omit [Fintype T] in +theorem fullRevealModel_merge (μ : Games.FiniteDistribution (X × Y)) (j : I) + (likelihood : T → (I → X × Y) → ℝ) (t : T) + (rest : {i : I // i ≠ j} → X ⊕ Y) (r : X ⊕ Y) (q : X × Y) : + fullRevealModel μ j likelihood ((t,mergeAt j r rest),q) = + maskedModel μ (partialRevealMarginal μ j likelihood) (((t,rest),r),q) := by + simp only [fullRevealModel, Information.firstMarginal, fullRevealMarginal_merge, + mergeAt_self, maskedModel] + +def revealSplitEquiv (j : I) : + ((T × (I → X ⊕ Y)) × (X × Y)) ≃ + (((T × ({i : I // i ≠ j} → X ⊕ Y)) × (X ⊕ Y)) × (X × Y)) where + toFun z := (((z.1.1, fun i => z.1.2 i.1), z.1.2 j), z.2) + invFun z := ((z.1.1.1, mergeAt j z.1.2 z.1.1.2), z.2) + left_inv z := by + apply Prod.ext + · apply Prod.ext + · rfl + · funext i + by_cases h : i = j <;> simp [mergeAt, h] + · rfl + right_inv z := by + apply Prod.ext + · apply Prod.ext + · apply Prod.ext + · rfl + · funext i + exact mergeAt_other j z.1.2 z.1.1.2 i + · exact mergeAt_self j z.1.2 z.1.1.2 + · rfl + +theorem totalVariation_comp_equiv {A B : Type*} [Fintype A] [Fintype B] + (e : A ≃ B) (p q : B → ℝ) : + Information.totalVariation (fun a => p (e a)) (fun a => q (e a)) = + Information.totalVariation p q := by + unfold Information.totalVariation + congr 1 + exact e.sum_comp (fun b => |p b - q b|) + +theorem fullReveal_totalVariation (μ : Games.FiniteDistribution (X × Y)) (j : I) + (likelihood : T → (I → X × Y) → ℝ) : + Information.totalVariation (fullRevealMarginal μ j likelihood) (fullRevealModel μ j likelihood) = + Information.totalVariation (maskedJoint (partialRevealMarginal μ j likelihood)) + (maskedModel μ (partialRevealMarginal μ j likelihood)) := by + calc + _ = Information.totalVariation + (fun z => fullRevealMarginal μ j likelihood ((revealSplitEquiv (T := T) j).symm z)) + (fun z => fullRevealModel μ j likelihood ((revealSplitEquiv (T := T) j).symm z)) := + (totalVariation_comp_equiv (revealSplitEquiv (T := T) j).symm _ _).symm + _ = _ := by + congr 1 <;> funext z + · exact fullRevealMarginal_merge μ j likelihood z.1.1.1 z.1.1.2 z.1.2 z.2 + · exact fullRevealModel_merge μ j likelihood z.1.1.1 z.1.1.2 z.1.2 z.2 + +theorem leftReveal_full_error (μ : Games.FiniteDistribution (X × Y)) (j : I) + (likelihood : T → (I → X × Y) → ℝ) : + Information.totalVariation (partialRevealMarginal μ j likelihood) + (leftRevealModel μ (partialRevealMarginal μ j likelihood)) ≤ + 2 * Information.totalVariation (fullRevealMarginal μ j likelihood) + (fullRevealModel μ j likelihood) := by + rw [fullReveal_totalVariation] + exact leftRevealModel_totalVariation_le μ _ + +theorem rightReveal_full_error (μ : Games.FiniteDistribution (X × Y)) (j : I) + (likelihood : T → (I → X × Y) → ℝ) : + Information.totalVariation (partialRevealMarginal μ j likelihood) + (rightRevealModel μ (partialRevealMarginal μ j likelihood)) ≤ + 2 * Information.totalVariation (fullRevealMarginal μ j likelihood) + (fullRevealModel μ j likelihood) := by + rw [fullReveal_totalVariation] + exact rightRevealModel_totalVariation_le μ _ + +end +end MinUncutGames.Foundations.Repetition + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/SelectedLikelihood.lean b/lean/OAI/Computability/MinUncut/PCP/SelectedLikelihood.lean new file mode 100644 index 0000000000000000000000000000000000000000..dfa507840111b0091c38222985bfc1429bf9c521 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/SelectedLikelihood.lean @@ -0,0 +1,703 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.DistributionMaps + +namespace OAI + +namespace MinUncutGames.Foundations.Repetition +open Games +noncomputable section +variable {Q₁ Q₂ A₁ A₂ : Type*} + [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂] + [DecidableEq Q₁] [DecidableEq Q₂] {n : Nat} + +def selectedLabelAccepts (G : Game Q₁ Q₂ A₁ A₂) (selected : Finset (Fin n)) + (fixed : selected → Q₁ × Q₂) + (label : SelectedLabels (A₁ := A₁) (A₂ := A₂) selected) : Bool := by + classical + exact decide (∀ i : selected, G.accepts (fixed i).1 (fixed i).2 (label.1 i) (label.2 i) = true) + +def selectedLocalAnswers {Q A : Type*} (strategy : (Fin n → Q) → (Fin n → A)) + (selected : Finset (Fin n)) (fixed : selected → Q) + (remaining : {i : Fin n // i ∉ selected} → Q) : selected → A := + fun i => strategy (mergeCoordinates selected fixed remaining) i.1 + +def selectedLocalTest {Q A : Type*} (strategy : (Fin n → Q) → (Fin n → A)) + (selected : Finset (Fin n)) (fixed : selected → Q) (label : selected → A) + (remaining : {i : Fin n // i ∉ selected} → Q) : ℝ := by + classical + exact if selectedLocalAnswers strategy selected fixed remaining = label then 1 else 0 + +theorem selectedLocalTest_nonnegative {Q A : Type*} (strategy : (Fin n → Q) → (Fin n → A)) + (selected : Finset (Fin n)) (fixed : selected → Q) (label : selected → A) + (remaining : {i : Fin n // i ∉ selected} → Q) : + 0 ≤ selectedLocalTest strategy selected fixed label remaining := by + classical + unfold selectedLocalTest + split <;> norm_num + +omit [Fintype Q₁] [Fintype Q₂] [DecidableEq Q₁] [DecidableEq Q₂] in +theorem selectedQuestionTuple_left (selected : Finset (Fin n)) + (fixed : selected → Q₁ × Q₂) (remaining : {i : Fin n // i ∉ selected} → Q₁ × Q₂) : + (selectedQuestionTuple selected fixed remaining).1 = + mergeCoordinates selected (fun i => (fixed i).1) (fun i => (remaining i).1) := by + funext i + simp only [selectedQuestionTuple, mergeCoordinates] + split <;> rfl + +omit [Fintype Q₁] [Fintype Q₂] [DecidableEq Q₁] [DecidableEq Q₂] in +theorem selectedQuestionTuple_right (selected : Finset (Fin n)) + (fixed : selected → Q₁ × Q₂) (remaining : {i : Fin n // i ∉ selected} → Q₁ × Q₂) : + (selectedQuestionTuple selected fixed remaining).2 = + mergeCoordinates selected (fun i => (fixed i).2) (fun i => (remaining i).2) := by + funext i + simp only [selectedQuestionTuple, mergeCoordinates] + split <;> rfl + +omit [DecidableEq Q₁] [DecidableEq Q₂] in +theorem selectedWins_of_answerLabel (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (fixed : selected → Q₁ × Q₂) + (label : SelectedLabels (A₁ := A₁) (A₂ := A₂) selected) + (remaining : {i : Fin n // i ∉ selected} → Q₁ × Q₂) + (hlabel : selectedAnswerLabel strategy selected (selectedQuestionTuple selected fixed remaining) = label) : + G.selectedWins strategy selected (selectedQuestionTuple selected fixed remaining) = + selectedLabelAccepts G selected fixed label := by + classical + have hleft (i : selected) := congrArg (fun l => l.1 i) hlabel + have hright (i : selected) := congrArg (fun l => l.2 i) hlabel + apply Bool.eq_iff_iff.mpr + simp only [Game.selectedWins, selectedLabelAccepts, decide_eq_true_eq] + constructor + · intro h i + have hi := h i.1 i.property + simpa [Game.coordinateWin, selectedQuestionTuple, mergeCoordinates, i.property, + ← hleft i, ← hright i, selectedAnswerLabel] using hi + · intro h i hi + have hv := h ⟨i,hi⟩ + simpa [Game.coordinateWin, selectedQuestionTuple, mergeCoordinates, hi, + ← hleft ⟨i,hi⟩, ← hright ⟨i,hi⟩, selectedAnswerLabel] using hv + +omit [DecidableEq Q₁] [DecidableEq Q₂] in +theorem selectedLikelihood_factorization (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (fixed : selected → Q₁ × Q₂) + (label : SelectedLabels (A₁ := A₁) (A₂ := A₂) selected) + (remaining : {i : Fin n // i ∉ selected} → Q₁ × Q₂) : + selectedLikelihood G strategy selected fixed label remaining = + (if selectedLabelAccepts G selected fixed label then 1 else 0) * + selectedLocalTest strategy.1 selected (fun i => (fixed i).1) label.1 (fun i => (remaining i).1) * + selectedLocalTest strategy.2 selected (fun i => (fixed i).2) label.2 (fun i => (remaining i).2) := by + classical + have he : selectedAnswerLabel strategy selected (selectedQuestionTuple selected fixed remaining) = + (selectedLocalAnswers strategy.1 selected (fun i => (fixed i).1) (fun i => (remaining i).1), + selectedLocalAnswers strategy.2 selected (fun i => (fixed i).2) (fun i => (remaining i).2)) := by + simp only [selectedAnswerLabel, + selectedQuestionTuple_left, selectedQuestionTuple_right] + rfl + by_cases hl : selectedLocalAnswers strategy.1 selected (fun i => (fixed i).1) + (fun i => (remaining i).1) = label.1 + · by_cases hr : selectedLocalAnswers strategy.2 selected (fun i => (fixed i).2) + (fun i => (remaining i).2) = label.2 + · have hlabel : selectedAnswerLabel strategy selected (selectedQuestionTuple selected fixed remaining) = label := by + rw [he, hl, hr] + simp only [selectedLikelihood, ite_eq_left hlabel, + selectedWins_of_answerLabel G strategy selected fixed label remaining hlabel, + selectedLocalTest, ite_eq_left hl, ite_eq_left hr, mul_one] + · have hn : selectedAnswerLabel strategy selected (selectedQuestionTuple selected fixed remaining) ≠ label := by + intro h + rw [he] at h + exact hr (congrArg Prod.snd h) + simp [selectedLikelihood, hn, selectedLocalTest, hl, hr] + · have hn : selectedAnswerLabel strategy selected (selectedQuestionTuple selected fixed remaining) ≠ label := by + intro h + rw [he] at h + exact hl (congrArg Prod.fst h) + simp [selectedLikelihood, hn, selectedLocalTest, hl] + +open scoped BigOperators +open Games +variable {I X Y : Type*} [Fintype I] [DecidableEq I] + [Fintype X] [Fintype Y] [DecidableEq X] [DecidableEq Y] + +def revealLeftFactor (μ : FiniteDistribution (X × Y)) (r : X ⊕ Y) (x : X) : ℝ := + match r with + | Sum.inl u => if x = u then 1 else 0 + | Sum.inr v => μ.weight (x,v) / 2 + +def revealRightFactor (μ : FiniteDistribution (X × Y)) (r : X ⊕ Y) (y : Y) : ℝ := + match r with + | Sum.inl u => μ.weight (u,y) / 2 + | Sum.inr v => if y = v then 1 else 0 + +omit [DecidableEq Y] in +theorem revealLeftFactor_nonnegative (μ : FiniteDistribution (X × Y)) + (r : X ⊕ Y) (x : X) : 0 ≤ revealLeftFactor μ r x := by + cases r with + | inl u => simp only [revealLeftFactor]; split <;> norm_num + | inr v => exact div_nonneg (μ.nonnegative _) (by norm_num) + +omit [DecidableEq X] in +theorem revealRightFactor_nonnegative (μ : FiniteDistribution (X × Y)) + (r : X ⊕ Y) (y : Y) : 0 ≤ revealRightFactor μ r y := by + cases r with + | inl u => exact div_nonneg (μ.nonnegative _) (by norm_num) + | inr v => simp only [revealRightFactor]; split <;> norm_num + +theorem revealLaw_factorization (μ : FiniteDistribution (X × Y)) + (r : X ⊕ Y) (x : X) (y : Y) : + (revealLaw μ).weight ((x,y),r) = + revealLeftFactor μ r x * revealRightFactor μ r y := by + rw [revealLaw_weight] + cases r with + | inl u => + by_cases h : x = u + · subst x; simp [revealLeftFactor, revealRightFactor] + · simp [revealLeftFactor, revealRightFactor, h, Ne.symm h] + | inr v => + by_cases h : y = v + · subst y; simp [revealLeftFactor, revealRightFactor] + · simp [revealLeftFactor, revealRightFactor, h, Ne.symm h] + +def partialLeftFactor (μ : FiniteDistribution (X × Y)) (j : I) + (rest : {i : I // i ≠ j} → X ⊕ Y) (x : I → X) : ℝ := + ∏ i, revealLeftFactor μ (rest i) (x i.1) + +def partialRightFactor (μ : FiniteDistribution (X × Y)) (j : I) + (rest : {i : I // i ≠ j} → X ⊕ Y) (y : I → Y) : ℝ := + ∏ i, revealRightFactor μ (rest i) (y i.1) + +theorem partialRevealWeight_factorization (μ : FiniteDistribution (X × Y)) (j : I) + (rest : {i : I // i ≠ j} → X ⊕ Y) (u : I → X × Y) : + partialRevealWeight μ j rest u = + μ.weight (u j) * partialLeftFactor μ j rest (fun i => (u i).1) * + partialRightFactor μ j rest (fun i => (u i).2) := by + have hpoint (i : {i : I // i ≠ j}) : + (revealLaw μ).weight (u i.1,rest i) = + revealLeftFactor μ (rest i) (u i.1).1 * revealRightFactor μ (rest i) (u i.1).2 := + revealLaw_factorization μ (rest i) (u i.1).1 (u i.1).2 + simp only [partialRevealWeight, partialLeftFactor, partialRightFactor, + hpoint, Finset.prod_mul_distrib] + ring + +section LocalNormalization + +variable {I X Y : Type*} [Fintype I] [DecidableEq I] + [Fintype X] [Fintype Y] + +def completionTupleEquiv : (I → X × Y) ≃ ((I → X) × (I → Y)) where + toFun u := (fun i => (u i).1, fun i => (u i).2) + invFun z := fun i => (z.1 i, z.2 i) + left_inv u := by funext i; rfl + right_inv z := by cases z; rfl + +def updatedTableFallback (μ : FiniteDistribution X) (j : I) (x : X) : + FiniteDistribution (I → X) := + (FiniteDistribution.table (fun _ : I => μ)).pushforward + (fun l => Function.update l j x) + +theorem updatedTableFallback_zero (μ : FiniteDistribution X) (j : I) (x : X) + (l : I → X) (hne : l j ≠ x) : + (updatedTableFallback μ j x).weight l = 0 := by + classical + simp only [updatedTableFallback, FiniteDistribution.pushforward] + apply Finset.sum_eq_zero + intro t _ + apply ite_eq_right + intro h + have he := congrFun h j + exact hne (by simpa only [Function.update_self] using he.symm) + +theorem normalizeOr_weight_eq_zero_of_zero + (w : X → ℝ) (hw : ∀ x, 0 ≤ w x) (fallback : FiniteDistribution X) + (x : X) (hraw : w x = 0) (hdefault : fallback.weight x = 0) : + (normalizeOr w hw fallback).weight x = 0 := by + classical + unfold normalizeOr + split + · change normalizedWeight w x = 0 + simp only [normalizedWeight, hraw, zero_div] + · exact hdefault + +end LocalNormalization + +variable {Q₁ Q₂ A₁ A₂ : Type*} + [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂] + [DecidableEq Q₁] [DecidableEq Q₂] {n : Nat} + +def selectedLeftRaw (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (j : {i : Fin n // i ∉ selected}) + (s : SelectedCommonData (Q₁ := Q₁) (Q₂ := Q₂) (A₁ := A₁) (A₂ := A₂) selected j) + (x : Q₁) (l : {i : Fin n // i ∉ selected} → Q₁) : ℝ := + (if l j = x then 1 else 0) * partialLeftFactor G.questions j s.2 l * + selectedLocalTest strategy.1 selected (fun i => (s.1.1 i).1) s.1.2.1 l + +def selectedRightRaw (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (j : {i : Fin n // i ∉ selected}) + (s : SelectedCommonData (Q₁ := Q₁) (Q₂ := Q₂) (A₁ := A₁) (A₂ := A₂) selected j) + (y : Q₂) (r : {i : Fin n // i ∉ selected} → Q₂) : ℝ := + (if r j = y then 1 else 0) * partialRightFactor G.questions j s.2 r * + selectedLocalTest strategy.2 selected (fun i => (s.1.1 i).2) s.1.2.2 r + +omit [DecidableEq Q₂] in +theorem selectedLeftRaw_nonnegative (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (j : {i : Fin n // i ∉ selected}) + (s : SelectedCommonData (Q₁ := Q₁) (Q₂ := Q₂) (A₁ := A₁) (A₂ := A₂) selected j) + (x : Q₁) (l : {i : Fin n // i ∉ selected} → Q₁) : + 0 ≤ selectedLeftRaw G strategy selected j s x l := by + apply mul_nonneg + · apply mul_nonneg + · split <;> norm_num + · exact Finset.prod_nonneg (fun i _ => revealLeftFactor_nonnegative G.questions (s.2 i) (l i.1)) + · exact selectedLocalTest_nonnegative _ _ _ _ _ + +omit [DecidableEq Q₁] in +theorem selectedRightRaw_nonnegative (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (j : {i : Fin n // i ∉ selected}) + (s : SelectedCommonData (Q₁ := Q₁) (Q₂ := Q₂) (A₁ := A₁) (A₂ := A₂) selected j) + (y : Q₂) (r : {i : Fin n // i ∉ selected} → Q₂) : + 0 ≤ selectedRightRaw G strategy selected j s y r := by + apply mul_nonneg + · apply mul_nonneg + · split <;> norm_num + · exact Finset.prod_nonneg (fun i _ => revealRightFactor_nonnegative G.questions (s.2 i) (r i.1)) + · exact selectedLocalTest_nonnegative _ _ _ _ _ + +def selectedLeftCompletion (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (j : {i : Fin n // i ∉ selected}) + (s : SelectedCommonData (Q₁ := Q₁) (Q₂ := Q₂) (A₁ := A₁) (A₂ := A₂) selected j) + (x : Q₁) : FiniteDistribution ({i : Fin n // i ∉ selected} → Q₁) := + normalizeOr (selectedLeftRaw G strategy selected j s x) + (selectedLeftRaw_nonnegative G strategy selected j s x) + (updatedTableFallback (G.questions.pushforward Prod.fst) j x) + +def selectedRightCompletion (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (j : {i : Fin n // i ∉ selected}) + (s : SelectedCommonData (Q₁ := Q₁) (Q₂ := Q₂) (A₁ := A₁) (A₂ := A₂) selected j) + (y : Q₂) : FiniteDistribution ({i : Fin n // i ∉ selected} → Q₂) := + normalizeOr (selectedRightRaw G strategy selected j s y) + (selectedRightRaw_nonnegative G strategy selected j s y) + (updatedTableFallback (G.questions.pushforward Prod.snd) j y) + +omit [DecidableEq Q₂] in +theorem selectedLeftCompletion_zero (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (j : {i : Fin n // i ∉ selected}) + (s : SelectedCommonData (Q₁ := Q₁) (Q₂ := Q₂) (A₁ := A₁) (A₂ := A₂) selected j) + (x : Q₁) (l : {i : Fin n // i ∉ selected} → Q₁) (hne : l j ≠ x) : + (selectedLeftCompletion G strategy selected j s x).weight l = 0 := by + apply normalizeOr_weight_eq_zero_of_zero + · simp only [selectedLeftRaw, ite_eq_right hne, zero_mul] + · exact updatedTableFallback_zero _ j x l hne + +omit [DecidableEq Q₁] in +theorem selectedRightCompletion_zero (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (j : {i : Fin n // i ∉ selected}) + (s : SelectedCommonData (Q₁ := Q₁) (Q₂ := Q₂) (A₁ := A₁) (A₂ := A₂) selected j) + (y : Q₂) (r : {i : Fin n // i ∉ selected} → Q₂) (hne : r j ≠ y) : + (selectedRightCompletion G strategy selected j s y).weight r = 0 := by + apply normalizeOr_weight_eq_zero_of_zero + · simp only [selectedRightRaw, ite_eq_right hne, zero_mul] + · exact updatedTableFallback_zero _ j y r hne + +omit [DecidableEq Q₂] in +theorem selectedLeftCompletion_support (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (j : {i : Fin n // i ∉ selected}) + (s : SelectedCommonData (Q₁ := Q₁) (Q₂ := Q₂) (A₁ := A₁) (A₂ := A₂) selected j) + (x : Q₁) (l : {i : Fin n // i ∉ selected} → Q₁) + (h : (selectedLeftCompletion G strategy selected j s x).weight l ≠ 0) : l j = x := by + by_contra hne + exact h (selectedLeftCompletion_zero G strategy selected j s x l hne) + +omit [DecidableEq Q₁] in +theorem selectedRightCompletion_support (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (j : {i : Fin n // i ∉ selected}) + (s : SelectedCommonData (Q₁ := Q₁) (Q₂ := Q₂) (A₁ := A₁) (A₂ := A₂) selected j) + (y : Q₂) (r : {i : Fin n // i ∉ selected} → Q₂) + (h : (selectedRightCompletion G strategy selected j s y).weight r ≠ 0) : r j = y := by + by_contra hne + exact h (selectedRightCompletion_zero G strategy selected j s y r hne) + +def selectedCompletionScale (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (j : {i : Fin n // i ∉ selected}) + (s : SelectedCommonData (Q₁ := Q₁) (Q₂ := Q₂) (A₁ := A₁) (A₂ := A₂) selected j) + (xy : Q₁ × Q₂) : ℝ := + G.questions.weight xy * (∏ i : selected, G.questions.weight (s.1.1 i)) * + (if selectedLabelAccepts G selected s.1.1 s.1.2 then 1 else 0) / + G.selectedSuccess strategy selected + +theorem selected_completion_factorization (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (j : {i : Fin n // i ∉ selected}) + (s : SelectedCommonData (Q₁ := Q₁) (Q₂ := Q₂) (A₁ := A₁) (A₂ := A₂) selected j) + (xy : Q₁ × Q₂) + (l : {i : Fin n // i ∉ selected} → Q₁) + (r : {i : Fin n // i ∉ selected} → Q₂) : + selectedCompletionScale G strategy selected j s xy * + selectedLeftRaw G strategy selected j s xy.1 l * + selectedRightRaw G strategy selected j s xy.2 r = + if (l j, r j) = xy then + partialRevealWeight G.questions j s.2 (fun i => (l i,r i)) * + selectedOutsideLikelihood G strategy selected s.1 (fun i => (l i,r i)) + else 0 := by + rcases xy with ⟨x,y⟩ + by_cases hl : l j = x <;> by_cases hr : r j = y + · rw [ite_eq_left (Prod.ext hl hr), partialRevealWeight_factorization] + cases hacc : selectedLabelAccepts G selected s.1.1 s.1.2 <;> + simp [selectedOutsideLikelihood, selectedLikelihood_factorization, + selectedCompletionScale, selectedLeftRaw, selectedRightRaw, hl, hr, hacc]; ring + · simp [selectedLeftRaw, selectedRightRaw, hl, hr, Prod.mk.injEq] + · simp [selectedLeftRaw, selectedRightRaw, hl, hr, Prod.mk.injEq] + · simp [selectedLeftRaw, selectedRightRaw, hl, hr, Prod.mk.injEq] + +theorem selectedCommonLaw_completion_row_mass (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) + (j : {i : Fin n // i ∉ selected}) + (s : SelectedCommonData (Q₁ := Q₁) (Q₂ := Q₂) (A₁ := A₁) (A₂ := A₂) selected j) + (xy : Q₁ × Q₂) : + (selectedCommonLaw G strategy selected positive j).weight (s,xy) = + ∑ lr : ({i : Fin n // i ∉ selected} → Q₁) × + ({i : Fin n // i ∉ selected} → Q₂), + selectedCompletionScale G strategy selected j s xy * + selectedLeftRaw G strategy selected j s xy.1 lr.1 * + selectedRightRaw G strategy selected j s xy.2 lr.2 := by + classical + change (∑ u, if u j = xy then partialRevealWeight G.questions j s.2 u * + selectedOutsideLikelihood G strategy selected s.1 u else 0) = _ + rw [← (completionTupleEquiv (I := {i : Fin n // i ∉ selected}) + (X := Q₁) (Y := Q₂)).sum_comp] + apply Finset.sum_congr rfl + intro u _ + exact (selected_completion_factorization G strategy selected j s xy + (fun i => (u i).1) (fun i => (u i).2)).symm + +theorem selected_completion_row_recombine (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) + (j : {i : Fin n // i ∉ selected}) + (s : SelectedCommonData (Q₁ := Q₁) (Q₂ := Q₂) (A₁ := A₁) (A₂ := A₂) selected j) + (xy : Q₁ × Q₂) + (l : {i : Fin n // i ∉ selected} → Q₁) + (r : {i : Fin n // i ∉ selected} → Q₂) : + (selectedCommonLaw G strategy selected positive j).weight (s,xy) * + ((selectedLeftCompletion G strategy selected j s xy.1).product + (selectedRightCompletion G strategy selected j s xy.2)).weight (l,r) = + if (l j,r j) = xy then + partialRevealWeight G.questions j s.2 (fun i => (l i,r i)) * + selectedOutsideLikelihood G strategy selected s.1 (fun i => (l i,r i)) + else 0 := by + rw [selectedCommonLaw_completion_row_mass] + calc + _ = selectedCompletionScale G strategy selected j s xy * + selectedLeftRaw G strategy selected j s xy.1 l * + selectedRightRaw G strategy selected j s xy.2 r := + factorized_completion_row + (selectedLeftRaw G strategy selected j s xy.1) + (selectedRightRaw G strategy selected j s xy.2) + (selectedLeftRaw_nonnegative G strategy selected j s xy.1) + (selectedRightRaw_nonnegative G strategy selected j s xy.2) + (updatedTableFallback (G.questions.pushforward Prod.fst) j xy.1) + (updatedTableFallback (G.questions.pushforward Prod.snd) j xy.2) + (selectedCompletionScale G strategy selected j s xy) (l,r) + _ = _ := selected_completion_factorization G strategy selected j s xy l r + +theorem partialRevealWeight_forget + {I X Y : Type*} [Fintype I] [DecidableEq I] + [Fintype X] [Fintype Y] [DecidableEq X] [DecidableEq Y] + (μ : FiniteDistribution (X × Y)) (j : I) (u : I → X × Y) : + (∑ rest : {i : I // i ≠ j} → X ⊕ Y, partialRevealWeight μ j rest u) = + ∏ i, μ.weight (u i) := by + have h := reveal_product_forget μ (fun i : {i : I // i ≠ j} => u i.1) + simp_rw [reveal_product_factorization] at h + simp only [partialRevealWeight, ← Finset.mul_sum] + rw [h] + exact (Fintype.prod_eq_mul_prod_subtype_ne (fun i => μ.weight (u i)) j).symm + +theorem partialReveal_event_forget + {I X Y : Type*} [Fintype I] [DecidableEq I] + [Fintype X] [Fintype Y] [DecidableEq X] [DecidableEq Y] + (μ : FiniteDistribution (X × Y)) (j : I) (f : (I → X × Y) → ℝ) : + (∑ rest : {i : I // i ≠ j} → X ⊕ Y, + ∑ u : I → X × Y, partialRevealWeight μ j rest u * f u) = + ∑ u, (∏ i, μ.weight (u i)) * f u := by + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro u _ + rw [← Finset.sum_mul, partialRevealWeight_forget] + +variable {Q₁ Q₂ A₁ A₂ : Type*} + [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂] + [DecidableEq Q₁] [DecidableEq Q₂] {n : Nat} + +omit [DecidableEq Q₁] [DecidableEq Q₂] in +theorem selectedOutsideLikelihood_event_sum (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) + (event : ((Fin n → Q₁) × (Fin n → Q₂)) → Bool) : + (∑ t : (selected → Q₁ × Q₂) × SelectedLabels (A₁ := A₁) (A₂ := A₂) selected, + ∑ u : {i : Fin n // i ∉ selected} → Q₁ × Q₂, + (∏ i, G.questions.weight (u i)) * selectedOutsideLikelihood G strategy selected t u * + (if event (selectedQuestionTuple selected t.1 u) then 1 else 0)) = + (G.repetition n).questions.probability + (fun q => G.selectedWins strategy selected q && event q) / + G.selectedSuccess strategy selected := by + classical + have hlabel (fixed : selected → Q₁ × Q₂) + (u : {i : Fin n // i ∉ selected} → Q₁ × Q₂) : + (∑ label : SelectedLabels (A₁ := A₁) (A₂ := A₂) selected, + (∏ i, G.questions.weight (u i)) * + selectedOutsideLikelihood G strategy selected (fixed,label) u * + (if event (selectedQuestionTuple selected fixed u) then 1 else 0)) = + ((∏ i : selected, G.questions.weight (fixed i)) * (∏ i, G.questions.weight (u i)) * + (if G.selectedWins strategy selected (selectedQuestionTuple selected fixed u) && + event (selectedQuestionTuple selected fixed u) then 1 else 0)) / + G.selectedSuccess strategy selected := by + calc + _ = (∏ i, G.questions.weight (u i)) * + (∏ i : selected, G.questions.weight (fixed i)) * + (∑ label, selectedLikelihood G strategy selected fixed label u) * + (if event (selectedQuestionTuple selected fixed u) then 1 else 0) / + G.selectedSuccess strategy selected := by + simp only [selectedOutsideLikelihood, div_eq_mul_inv, Finset.mul_sum, Finset.sum_mul] + apply Finset.sum_congr rfl + intro label _ + ring + _ = _ := by + rw [selectedLikelihood_sum] + cases G.selectedWins strategy selected (selectedQuestionTuple selected fixed u) <;> + cases event (selectedQuestionTuple selected fixed u) <;> simp; ring + calc + _ = ∑ fixed : selected → Q₁ × Q₂, + ∑ u : {i : Fin n // i ∉ selected} → Q₁ × Q₂, + ∑ label : SelectedLabels (A₁ := A₁) (A₂ := A₂) selected, + (∏ i, G.questions.weight (u i)) * + selectedOutsideLikelihood G strategy selected (fixed,label) u * + (if event (selectedQuestionTuple selected fixed u) then 1 else 0) := by + rw [Fintype.sum_prod_type] + apply Finset.sum_congr rfl + intro fixed _ + rw [Finset.sum_comm] + _ = (∑ fixed : selected → Q₁ × Q₂, + ∑ u : {i : Fin n // i ∉ selected} → Q₁ × Q₂, + (∏ i : selected, G.questions.weight (fixed i)) * (∏ i, G.questions.weight (u i)) * + (if G.selectedWins strategy selected (selectedQuestionTuple selected fixed u) && + event (selectedQuestionTuple selected fixed u) then 1 else 0)) / + G.selectedSuccess strategy selected := by + simp_rw [hlabel] + simp only [div_eq_mul_inv, Finset.sum_mul] + _ = _ := by + congr 1 + have h := selectedSplit_question_probability G selected + (fun q => G.selectedWins strategy selected q && event q) + simpa [selectedSplitLaw, FiniteDistribution.probability, FiniteDistribution.product, + FiniteDistribution.table, Fintype.sum_prod_type, mul_ite] using h + +theorem selected_partial_event_total (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (j : {i : Fin n // i ∉ selected}) + (event : ((Fin n → Q₁) × (Fin n → Q₂)) → Bool) : + (∑ s : SelectedCommonData (Q₁ := Q₁) (Q₂ := Q₂) (A₁ := A₁) (A₂ := A₂) selected j, + ∑ u : {i : Fin n // i ∉ selected} → Q₁ × Q₂, + partialRevealWeight G.questions j s.2 u * + selectedOutsideLikelihood G strategy selected s.1 u * + (if event (selectedQuestionTuple selected s.1.1 u) then 1 else 0)) = + (G.repetition n).questions.probability + (fun q => G.selectedWins strategy selected q && event q) / + G.selectedSuccess strategy selected := by + have hrest (t : (selected → Q₁ × Q₂) × SelectedLabels (A₁ := A₁) (A₂ := A₂) selected) := + partialReveal_event_forget G.questions j + (fun u => selectedOutsideLikelihood G strategy selected t u * + (if event (selectedQuestionTuple selected t.1 u) then 1 else 0)) + simp only [← mul_assoc] at hrest + rw [Fintype.sum_prod_type] + simp_rw [hrest] + exact selectedOutsideLikelihood_event_sum G strategy selected event + +def selectedFullLeftCompletion (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (j : {i : Fin n // i ∉ selected}) + (q : Q₁ × SelectedCommonData (Q₁ := Q₁) (Q₂ := Q₂) (A₁ := A₁) (A₂ := A₂) selected j) : + FiniteDistribution (Fin n → Q₁) := + (selectedLeftCompletion G strategy selected j q.2 q.1).pushforward + (mergeCoordinates selected (fun i => (q.2.1.1 i).1)) + +def selectedFullRightCompletion (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (j : {i : Fin n // i ∉ selected}) + (q : Q₂ × SelectedCommonData (Q₁ := Q₁) (Q₂ := Q₂) (A₁ := A₁) (A₂ := A₂) selected j) : + FiniteDistribution (Fin n → Q₂) := + (selectedRightCompletion G strategy selected j q.2 q.1).pushforward + (mergeCoordinates selected (fun i => (q.2.1.1 i).2)) + +omit [DecidableEq Q₂] in +theorem selectedFullLeftCompletion_support (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (j : {i : Fin n // i ∉ selected}) + (q : Q₁ × SelectedCommonData (Q₁ := Q₁) (Q₂ := Q₂) (A₁ := A₁) (A₂ := A₂) selected j) + (l : Fin n → Q₁) (h : (selectedFullLeftCompletion G strategy selected j q).weight l ≠ 0) : + l j.1 = q.1 := by + classical + by_contra hne + apply h + simp only [selectedFullLeftCompletion, FiniteDistribution.pushforward] + apply Finset.sum_eq_zero + intro t _ + split + · rename_i he + apply selectedLeftCompletion_zero + intro ht + apply hne + have hcoord := congrFun he j.1 + simpa [mergeCoordinates, j.property, ht] using hcoord.symm + · rfl + +omit [DecidableEq Q₁] in +theorem selectedFullRightCompletion_support (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (j : {i : Fin n // i ∉ selected}) + (q : Q₂ × SelectedCommonData (Q₁ := Q₁) (Q₂ := Q₂) (A₁ := A₁) (A₂ := A₂) selected j) + (r : Fin n → Q₂) (h : (selectedFullRightCompletion G strategy selected j q).weight r ≠ 0) : + r j.1 = q.1 := by + classical + by_contra hne + apply h + simp only [selectedFullRightCompletion, FiniteDistribution.pushforward] + apply Finset.sum_eq_zero + intro t _ + split + · rename_i he + apply selectedRightCompletion_zero + intro ht + apply hne + have hcoord := congrFun he j.1 + simpa [mergeCoordinates, j.property, ht] using hcoord.symm + · rfl + +theorem selected_full_completion_probability (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (j : {i : Fin n // i ∉ selected}) + (s : SelectedCommonData (Q₁ := Q₁) (Q₂ := Q₂) (A₁ := A₁) (A₂ := A₂) selected j) + (xy : Q₁ × Q₂) (event : ((Fin n → Q₁) × (Fin n → Q₂)) → Bool) : + ((selectedFullLeftCompletion G strategy selected j (xy.1,s)).product + (selectedFullRightCompletion G strategy selected j (xy.2,s))).probability event = + ∑ lr : ({i : Fin n // i ∉ selected} → Q₁) × ({i : Fin n // i ∉ selected} → Q₂), + ((selectedLeftCompletion G strategy selected j s xy.1).product + (selectedRightCompletion G strategy selected j s xy.2)).weight lr * + (if event (selectedQuestionTuple selected s.1.1 (fun i => (lr.1 i,lr.2 i))) + then 1 else 0) := by + rw [selectedFullLeftCompletion, selectedFullRightCompletion, + ← FiniteDistribution.product_pushforward, FiniteDistribution.probability_pushforward] + unfold FiniteDistribution.probability + apply Finset.sum_congr rfl + intro lr _ + have he : selectedQuestionTuple selected s.1.1 (fun i => (lr.1 i,lr.2 i)) = + (mergeCoordinates selected (fun i => (s.1.1 i).1) lr.1, + mergeCoordinates selected (fun i => (s.1.1 i).2) lr.2) := + Prod.ext (selectedQuestionTuple_left selected s.1.1 _) + (selectedQuestionTuple_right selected s.1.1 _) + rw [he] + cases hevent : event (mergeCoordinates selected (fun i => (s.1.1 i).1) lr.1, + mergeCoordinates selected (fun i => (s.1.1 i).2) lr.2) <;> simp [hevent] + +theorem selected_completion_event_row (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) + (j : {i : Fin n // i ∉ selected}) + (s : SelectedCommonData (Q₁ := Q₁) (Q₂ := Q₂) (A₁ := A₁) (A₂ := A₂) selected j) + (event : ((Fin n → Q₁) × (Fin n → Q₂)) → Bool) : + (∑ xy : Q₁ × Q₂, (selectedCommonLaw G strategy selected positive j).weight (s,xy) * + ((selectedFullLeftCompletion G strategy selected j (xy.1,s)).product + (selectedFullRightCompletion G strategy selected j (xy.2,s))).probability event) = + ∑ u : {i : Fin n // i ∉ selected} → Q₁ × Q₂, + partialRevealWeight G.questions j s.2 u * + selectedOutsideLikelihood G strategy selected s.1 u * + (if event (selectedQuestionTuple selected s.1.1 u) then 1 else 0) := by + classical + have hpoint (xy : Q₁ × Q₂) + (lr : ({i : Fin n // i ∉ selected} → Q₁) × ({i : Fin n // i ∉ selected} → Q₂)) : + (selectedCommonLaw G strategy selected positive j).weight (s,xy) * + ((selectedLeftCompletion G strategy selected j s xy.1).product + (selectedRightCompletion G strategy selected j s xy.2)).weight lr = + if (lr.1 j,lr.2 j) = xy then + partialRevealWeight G.questions j s.2 (fun i => (lr.1 i,lr.2 i)) * + selectedOutsideLikelihood G strategy selected s.1 (fun i => (lr.1 i,lr.2 i)) else 0 := + selected_completion_row_recombine G strategy selected positive j s xy lr.1 lr.2 + simp_rw [selected_full_completion_probability, Finset.mul_sum, ← mul_assoc, + hpoint] + have hsum (xy : Q₁ × Q₂) : + (∑ lr : ({i : Fin n // i ∉ selected} → Q₁) × ({i : Fin n // i ∉ selected} → Q₂), + (if (lr.1 j,lr.2 j) = xy then + partialRevealWeight G.questions j s.2 (fun i => (lr.1 i,lr.2 i)) * + selectedOutsideLikelihood G strategy selected s.1 (fun i => (lr.1 i,lr.2 i)) else 0) * + (if event (selectedQuestionTuple selected s.1.1 (fun i => (lr.1 i,lr.2 i))) then 1 else 0)) = + ∑ u : {i : Fin n // i ∉ selected} → Q₁ × Q₂, + (if u j = xy then partialRevealWeight G.questions j s.2 u * + selectedOutsideLikelihood G strategy selected s.1 u else 0) * + (if event (selectedQuestionTuple selected s.1.1 u) then 1 else 0) := by + exact ((completionTupleEquiv (I := {i : Fin n // i ∉ selected}) + (X := Q₁) (Y := Q₂)).sum_comp _).symm + simp_rw [hsum] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro u _ + rw [← Finset.sum_mul] + simp + +def selectedFullCompletionMixture (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) + (j : {i : Fin n // i ∉ selected}) : + FiniteDistribution ((Fin n → Q₁) × (Fin n → Q₂)) := + ((selectedCommonLaw G strategy selected positive j).transport (Equiv.prodComm _ _)).mixture + (fun z => (selectedFullLeftCompletion G strategy selected j (z.1.1,z.2)).product + (selectedFullRightCompletion G strategy selected j (z.1.2,z.2))) + +theorem selectedFullCompletionMixture_probability (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) + (j : {i : Fin n // i ∉ selected}) + (event : ((Fin n → Q₁) × (Fin n → Q₂)) → Bool) : + (selectedFullCompletionMixture G strategy selected positive j).probability event = + ((G.repetition n).questions.condition (G.selectedWins strategy selected) positive).probability event := by + erw [FiniteDistribution.probability_condition] + rw [selectedFullCompletionMixture, FiniteDistribution.probability_mixture] + simp only [FiniteDistribution.transport] + rw [Fintype.sum_prod_type, Finset.sum_comm] + calc + _ = ∑ s : SelectedCommonData (Q₁ := Q₁) (Q₂ := Q₂) (A₁ := A₁) (A₂ := A₂) selected j, + ∑ u : {i : Fin n // i ∉ selected} → Q₁ × Q₂, + partialRevealWeight G.questions j s.2 u * + selectedOutsideLikelihood G strategy selected s.1 u * + (if event (selectedQuestionTuple selected s.1.1 u) then 1 else 0) := by + apply Finset.sum_congr rfl + intro s _ + exact selected_completion_event_row G strategy selected positive j s event + _ = _ := selected_partial_event_total G strategy selected j event + +theorem selectedFullCompletionMixture_eq_conditionedQuestions (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) + (j : {i : Fin n // i ∉ selected}) : + selectedFullCompletionMixture G strategy selected positive j = + (G.repetition n).questions.condition (G.selectedWins strategy selected) positive := by + classical + apply FiniteDistribution.eq_of_weight_eq + intro q + rw [FiniteDistribution.weight_eq_probability_singleton, + FiniteDistribution.weight_eq_probability_singleton] + exact selectedFullCompletionMixture_probability G strategy selected positive j _ + +end +end MinUncutGames.Foundations.Repetition + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/SelectedMarginal.lean b/lean/OAI/Computability/MinUncut/PCP/SelectedMarginal.lean new file mode 100644 index 0000000000000000000000000000000000000000..f62ca7e957759cc4ae550f56b000d51ebb9a47cd --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/SelectedMarginal.lean @@ -0,0 +1,495 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.SelectedInformation + +namespace OAI + +namespace MinUncutGames.Foundations.Repetition +open scoped BigOperators +open Games Information +noncomputable section +variable {Q₁ Q₂ A₁ A₂ : Type*} + [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂] + [DecidableEq Q₁] [DecidableEq Q₂] {n : Nat} + +def selectedRawMarginal (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (j : {i : Fin n // i ∉ selected}) : + (SelectedInput Q₁ Q₂ selected × SelectedLabels (A₁ := A₁) (A₂ := A₂) selected) × + (Q₁ × Q₂) → ℝ := by + classical + exact fun z => ∑ u, if u j = z.2 then selectedJointWeight G strategy selected (z.1,u) else 0 + +theorem selectedPosterior_eq_raw (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (j : {i : Fin n // i ∉ selected}) (tv) (q) : + selectedSideWeight G strategy selected tv * coordinateMarginal + (posteriorOrOriginal + (independentProduct (fun i => (selectedInputProfile G selected tv.1 i).weight)) + (selectedLikelihood G strategy selected tv.1.1 tv.2) + (selectedSideMass G strategy selected tv)) j q = + selectedRawMarginal G strategy selected j (tv,q) := by + classical + rw [selectedSideWeight] + have h := weighted_coordinate_posterior_recombine + (independentProduct (fun i => (selectedInputProfile G selected tv.1 i).weight)) + (selectedLikelihood G strategy selected tv.1.1 tv.2) + (independentProduct_isProbability _ + (fun i => gameLaw_isProbability (selectedInputProfile G selected tv.1 i))) + (selectedLikelihood_nonnegative G strategy selected tv.1.1 tv.2) + (c := selectedSideMass G strategy selected tv) rfl + ((selectedInputLaw G selected).weight tv.1) (G.selectedSuccess strategy selected) j q + rw [h] + simp only [Finset.mul_sum, selectedRawMarginal, selectedJointWeight] + apply Finset.sum_congr rfl + intro u _ + by_cases hu : u j = q + · simp only [ite_eq_left hu] + ring + · simp [hu] + +theorem selectedRawMarginal_firstMarginal (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (j : {i : Fin n // i ∉ selected}) (tv) : + firstMarginal (selectedRawMarginal G strategy selected j) tv = + selectedSideWeight G strategy selected tv := by + classical + simp only [firstMarginal, selectedRawMarginal] + rw [Finset.sum_comm] + simp only [Finset.sum_ite_eq, Finset.mem_univ, ite_true] + exact selectedJointWeight_firstMarginal G strategy selected tv + +theorem selectedRawMarginal_isProbability (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) + (j : {i : Fin n // i ∉ selected}) : + IsProbability (selectedRawMarginal G strategy selected j) := by + classical + constructor + · intro z + apply Finset.sum_nonneg + intro u _ + split + · exact selectedJointWeight_nonnegative G strategy selected (z.1,u) + · exact le_rfl + · rw [Fintype.sum_prod_type] + change (∑ tv, firstMarginal (selectedRawMarginal G strategy selected j) tv) = 1 + simp_rw [selectedRawMarginal_firstMarginal, selectedSideWeight, div_eq_mul_inv] + rw [← Finset.sum_mul, selectedSideMass_total, mul_inv_cancel₀ positive.ne'] + +theorem selected_raw_information_bound [Nonempty A₁] [Nonempty A₂] + (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) : + (∑ j : {i : Fin n // i ∉ selected}, totalVariation + (selectedRawMarginal G strategy selected j) + (fun z => selectedSideWeight G strategy selected z.1 * + (selectedInputProfile G selected z.1.1 j).weight z.2)) ≤ + Real.sqrt ((Fintype.card {i : Fin n // i ∉ selected} : ℝ) * + (Real.log (Fintype.card (SelectedLabels (A₁ := A₁) (A₂ := A₂) selected) : ℝ) + + Real.log (1 / G.selectedSuccess strategy selected))) := by + have h := selected_information_bound G strategy selected positive + simp_rw [selectedPosterior_eq_raw] at h + exact h + +def selectedOutsideLikelihood (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) + (t : (selected → Q₁ × Q₂) × SelectedLabels (A₁ := A₁) (A₂ := A₂) selected) + (u : {i : Fin n // i ∉ selected} → Q₁ × Q₂) : ℝ := + (∏ i : selected, G.questions.weight (t.1 i)) * + selectedLikelihood G strategy selected t.1 t.2 u / G.selectedSuccess strategy selected + +def selectedObservationEquiv (selected : Finset (Fin n)) : + ((SelectedInput Q₁ Q₂ selected × SelectedLabels (A₁ := A₁) (A₂ := A₂) selected) × + (Q₁ × Q₂)) ≃ + ((((selected → Q₁ × Q₂) × SelectedLabels (A₁ := A₁) (A₂ := A₂) selected) × + ({i : Fin n // i ∉ selected} → Q₁ ⊕ Q₂)) × (Q₁ × Q₂)) where + toFun z := (((z.1.1.1,z.1.2),z.1.1.2),z.2) + invFun z := (((z.1.1.1,z.1.2),z.1.1.2),z.2) + left_inv _ := rfl + right_inv _ := rfl + +theorem selectedRawMarginal_fullReveal (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (j : {i : Fin n // i ∉ selected}) (z) : + selectedRawMarginal G strategy selected j + ((selectedObservationEquiv (Q₁ := Q₁) (Q₂ := Q₂) (A₁ := A₁) (A₂ := A₂) selected).symm z) = + fullRevealMarginal G.questions j (selectedOutsideLikelihood G strategy selected) z := by + classical + change selectedRawMarginal G strategy selected j + (((z.1.1.1,z.1.2),z.1.1.2),z.2) = _ + simp only [selectedRawMarginal, fullRevealMarginal] + apply Finset.sum_congr rfl + intro u _ + by_cases hu : u j = z.2 + · simp only [ite_eq_left hu, selectedJointWeight_factorization, selectedOutsideLikelihood] + ring + · simp [hu] + +theorem selectedRawReference_fullReveal (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (j : {i : Fin n // i ∉ selected}) (z) : + (fun w => selectedSideWeight G strategy selected w.1 * + (selectedInputProfile G selected w.1.1 j).weight w.2) + ((selectedObservationEquiv (Q₁ := Q₁) (Q₂ := Q₂) (A₁ := A₁) (A₂ := A₂) selected).symm z) = + fullRevealModel G.questions j (selectedOutsideLikelihood G strategy selected) z := by + change selectedSideWeight G strategy selected ((z.1.1.1,z.1.2),z.1.1.2) * + (revealProfile G.questions (z.1.2 j)).weight z.2 = _ + rw [← selectedRawMarginal_firstMarginal G strategy selected j] + unfold firstMarginal fullRevealModel + congr 1 + apply Finset.sum_congr rfl + intro q _ + exact selectedRawMarginal_fullReveal G strategy selected j (z.1,q) + +theorem selected_raw_error_eq_fullReveal (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (j : {i : Fin n // i ∉ selected}) : + totalVariation (selectedRawMarginal G strategy selected j) + (fun z => selectedSideWeight G strategy selected z.1 * + (selectedInputProfile G selected z.1.1 j).weight z.2) = + totalVariation (fullRevealMarginal G.questions j (selectedOutsideLikelihood G strategy selected)) + (fullRevealModel G.questions j (selectedOutsideLikelihood G strategy selected)) := by + rw [← totalVariation_comp_equiv + (selectedObservationEquiv (Q₁ := Q₁) (Q₂ := Q₂) (A₁ := A₁) (A₂ := A₂) selected).symm] + congr 1 <;> funext z + · exact selectedRawMarginal_fullReveal G strategy selected j z + · exact selectedRawReference_fullReveal G strategy selected j z + +theorem selected_fullReveal_information_bound [Nonempty A₁] [Nonempty A₂] + (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) : + (∑ j : {i : Fin n // i ∉ selected}, + totalVariation (fullRevealMarginal G.questions j (selectedOutsideLikelihood G strategy selected)) + (fullRevealModel G.questions j (selectedOutsideLikelihood G strategy selected))) ≤ + Real.sqrt ((Fintype.card {i : Fin n // i ∉ selected} : ℝ) * + (Real.log (Fintype.card (SelectedLabels (A₁ := A₁) (A₂ := A₂) selected) : ℝ) + + Real.log (1 / G.selectedSuccess strategy selected))) := by + have h := selected_raw_information_bound G strategy selected positive + simp_rw [selected_raw_error_eq_fullReveal] at h + exact h + +def selectedInformationRadius (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) : ℝ := + Real.sqrt ((Fintype.card {i : Fin n // i ∉ selected} : ℝ) * + (Real.log (Fintype.card (SelectedLabels (A₁ := A₁) (A₂ := A₂) selected) : ℝ) + + Real.log (1 / G.selectedSuccess strategy selected))) + +theorem selected_leftReveal_error_sum [Nonempty A₁] [Nonempty A₂] + (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) : + (∑ j : {i : Fin n // i ∉ selected}, + totalVariation (partialRevealMarginal G.questions j (selectedOutsideLikelihood G strategy selected)) + (leftRevealModel G.questions + (partialRevealMarginal G.questions j (selectedOutsideLikelihood G strategy selected)))) ≤ + 2 * selectedInformationRadius G strategy selected := by + calc + _ ≤ ∑ j : {i : Fin n // i ∉ selected}, + 2 * totalVariation (fullRevealMarginal G.questions j (selectedOutsideLikelihood G strategy selected)) + (fullRevealModel G.questions j (selectedOutsideLikelihood G strategy selected)) := by + apply Finset.sum_le_sum + intro j _ + exact leftReveal_full_error G.questions j _ + _ = 2 * ∑ j : {i : Fin n // i ∉ selected}, + totalVariation (fullRevealMarginal G.questions j (selectedOutsideLikelihood G strategy selected)) + (fullRevealModel G.questions j (selectedOutsideLikelihood G strategy selected)) := + (Finset.mul_sum _ _ _).symm + _ ≤ _ := mul_le_mul_of_nonneg_left + (selected_fullReveal_information_bound G strategy selected positive) (by norm_num) + +theorem selected_rightReveal_error_sum [Nonempty A₁] [Nonempty A₂] + (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) : + (∑ j : {i : Fin n // i ∉ selected}, + totalVariation (partialRevealMarginal G.questions j (selectedOutsideLikelihood G strategy selected)) + (rightRevealModel G.questions + (partialRevealMarginal G.questions j (selectedOutsideLikelihood G strategy selected)))) ≤ + 2 * selectedInformationRadius G strategy selected := by + calc + _ ≤ ∑ j : {i : Fin n // i ∉ selected}, + 2 * totalVariation (fullRevealMarginal G.questions j (selectedOutsideLikelihood G strategy selected)) + (fullRevealModel G.questions j (selectedOutsideLikelihood G strategy selected)) := by + apply Finset.sum_le_sum + intro j _ + exact rightReveal_full_error G.questions j _ + _ = 2 * ∑ j : {i : Fin n // i ∉ selected}, + totalVariation (fullRevealMarginal G.questions j (selectedOutsideLikelihood G strategy selected)) + (fullRevealModel G.questions j (selectedOutsideLikelihood G strategy selected)) := + (Finset.mul_sum _ _ _).symm + _ ≤ _ := mul_le_mul_of_nonneg_left + (selected_fullReveal_information_bound G strategy selected positive) (by norm_num) + + +omit [DecidableEq Q₁] [DecidableEq Q₂] in +theorem selectedSplit_question_probability (G : Game Q₁ Q₂ A₁ A₂) + (selected : Finset (Fin n)) + (event : ((Fin n → Q₁) × (Fin n → Q₂)) → Bool) : + (selectedSplitLaw G selected).probability + (fun q => event (selectedQuestionTuple selected q.1 q.2)) = + (G.repetition n).questions.probability event := by + rw [selectedSplitLaw, ← iid_coordinate_split, FiniteDistribution.probability_transport] + change (G.questions.iid n).probability _ = + ((G.questions.iid n).transport (Game.tupleQuestionEquiv n)).probability event + rw [FiniteDistribution.probability_transport] + apply congrArg (G.questions.iid n).probability + funext q + congr 1 + apply Prod.ext <;> funext i <;> + simp [selectedQuestionTuple, coordinateSplitEquiv, mergeCoordinates, Game.tupleQuestionEquiv] + +theorem selectedJoint_eventMass (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) + (event : ((Fin n → Q₁) × (Fin n → Q₂)) → Bool) : + (∑ tv : SelectedInput Q₁ Q₂ selected × + SelectedLabels (A₁ := A₁) (A₂ := A₂) selected, + (selectedInputLaw G selected).weight tv.1 * + ∑ u, independentProduct + (fun i => (selectedInputProfile G selected tv.1 i).weight) u * + selectedLikelihood G strategy selected tv.1.1 tv.2 u * + (if event (selectedQuestionTuple selected tv.1.1 u) then 1 else 0)) = + (G.repetition n).questions.probability + (fun q => G.selectedWins strategy selected q && event q) := by + classical + have hlabel (t : SelectedInput Q₁ Q₂ selected) : + (∑ v, ∑ u, independentProduct + (fun i => (selectedInputProfile G selected t i).weight) u * + selectedLikelihood G strategy selected t.1 v u * + (if event (selectedQuestionTuple selected t.1 u) then 1 else 0)) = + ∑ u, independentProduct + (fun i => (selectedInputProfile G selected t i).weight) u * + (if G.selectedWins strategy selected (selectedQuestionTuple selected t.1 u) && + event (selectedQuestionTuple selected t.1 u) then 1 else 0) := by + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro u _ + rw [← Finset.sum_mul, ← Finset.mul_sum, selectedLikelihood_sum] + cases G.selectedWins strategy selected (selectedQuestionTuple selected t.1 u) <;> + cases event (selectedQuestionTuple selected t.1 u) <;> simp + rw [Fintype.sum_prod_type] + simp_rw [← Finset.mul_sum, hlabel] + rw [Fintype.sum_prod_type] + simp only [selectedInputLaw, FiniteDistribution.product, FiniteDistribution.table, + selectedInputProfile, independentProduct] + simp_rw [mul_assoc, ← Finset.mul_sum] + have hforget (fixed : selected → Q₁ × Q₂) := + reveal_product_expectation G.questions + (fun u : {i : Fin n // i ∉ selected} → Q₁ × Q₂ => + if G.selectedWins strategy selected (selectedQuestionTuple selected fixed u) && + event (selectedQuestionTuple selected fixed u) then (1 : ℝ) else 0) + simp_rw [hforget] + have h := selectedSplit_question_probability G selected + (fun q => G.selectedWins strategy selected q && event q) + simpa [selectedSplitLaw, FiniteDistribution.probability, FiniteDistribution.product, + FiniteDistribution.table, Fintype.sum_prod_type, Finset.mul_sum, mul_ite, mul_assoc] using h + +theorem selectedJointLaw_question_probability (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) + (event : ((Fin n → Q₁) × (Fin n → Q₂)) → Bool) : + (selectedJointLaw G strategy selected positive).probability + (fun z => event (selectedQuestionTuple selected z.1.1.1 z.2)) = + ((G.repetition n).questions.condition (G.selectedWins strategy selected) positive).probability + event := by + classical + erw [FiniteDistribution.probability_condition] + change + (∑ z : (SelectedInput Q₁ Q₂ selected × + SelectedLabels (A₁ := A₁) (A₂ := A₂) selected) × + ({i : Fin n // i ∉ selected} → Q₁ × Q₂), + if event (selectedQuestionTuple selected z.1.1.1 z.2) + then selectedJointWeight G strategy selected z else 0) = + (G.repetition n).questions.probability + (fun q => G.selectedWins strategy selected q && event q) / + G.selectedSuccess strategy selected + calc + _ = (∑ tv : SelectedInput Q₁ Q₂ selected × + SelectedLabels (A₁ := A₁) (A₂ := A₂) selected, + (selectedInputLaw G selected).weight tv.1 * + ∑ u, independentProduct + (fun i => (selectedInputProfile G selected tv.1 i).weight) u * + selectedLikelihood G strategy selected tv.1.1 tv.2 u * + (if event (selectedQuestionTuple selected tv.1.1 u) then 1 else 0)) / + G.selectedSuccess strategy selected := by + conv_lhs => rw [Fintype.sum_prod_type] + simp only [div_eq_mul_inv, Finset.sum_mul, Finset.mul_sum] + apply Finset.sum_congr rfl + intro tv _ + apply Finset.sum_congr rfl + intro u _ + cases event (selectedQuestionTuple selected tv.1.1 u) <;> + simp [selectedJointWeight, div_eq_mul_inv, mul_assoc] + _ = _ := by rw [selectedJoint_eventMass] + +theorem selectedJointLaw_questions_pushforward (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) : + (selectedJointLaw G strategy selected positive).pushforward + (fun z => selectedQuestionTuple selected z.1.1.1 z.2) = + (G.repetition n).questions.condition (G.selectedWins strategy selected) positive := by + classical + apply FiniteDistribution.eq_of_weight_eq + intro questions + have h : + ((selectedJointLaw G strategy selected positive).pushforward + (fun z => selectedQuestionTuple selected z.1.1.1 z.2)).probability + (fun q => decide (q = questions)) = + ((G.repetition n).questions.condition (G.selectedWins strategy selected) positive).probability + (fun q => decide (q = questions)) := by + rw [FiniteDistribution.probability_pushforward] + exact selectedJointLaw_question_probability G strategy selected positive + (fun q => decide (q = questions)) + simpa [FiniteDistribution.probability] using h + + +def selectedTupleLikelihood (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (questions : Fin n → Q₁ × Q₂) : ℝ := + if G.selectedWins strategy selected (Game.tupleQuestionEquiv n questions) then 1 else 0 + +omit [DecidableEq Q₁] [DecidableEq Q₂] in +theorem selectedTupleLikelihood_nonnegative (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (questions : Fin n → Q₁ × Q₂) : + 0 ≤ selectedTupleLikelihood G strategy selected questions := by + unfold selectedTupleLikelihood + split <;> norm_num + +omit [DecidableEq Q₁] [DecidableEq Q₂] in +theorem selectedTupleLikelihood_le_one (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (questions : Fin n → Q₁ × Q₂) : + selectedTupleLikelihood G strategy selected questions ≤ 1 := by + unfold selectedTupleLikelihood + split <;> norm_num + +omit [DecidableEq Q₁] [DecidableEq Q₂] in +theorem selectedTupleLikelihood_mass (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) : + (∑ questions, independentProduct (fun _ : Fin n => G.questions.weight) questions * + selectedTupleLikelihood G strategy selected questions) = + G.selectedSuccess strategy selected := by + classical + change _ = ((G.questions.iid n).transport (Game.tupleQuestionEquiv n)).probability + (G.selectedWins strategy selected) + rw [FiniteDistribution.probability_transport] + simp only [FiniteDistribution.probability, FiniteDistribution.iid, independentProduct, + selectedTupleLikelihood, mul_ite, mul_one, mul_zero] + +def selectedQuestionMarginal (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) + (i : Fin n) : FiniteDistribution (Q₁ × Q₂) := + ((G.repetition n).questions.condition (G.selectedWins strategy selected) positive).pushforward + (fun questions => (questions.1 i, questions.2 i)) + +theorem selectedQuestionMarginal_weight (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) + (i : Fin n) : + (selectedQuestionMarginal G strategy selected positive i).weight = + coordinateMarginal + (posterior (independentProduct (fun _ : Fin n => G.questions.weight)) + (selectedTupleLikelihood G strategy selected) (G.selectedSuccess strategy selected)) i := by + classical + funext a + simp only [selectedQuestionMarginal, FiniteDistribution.pushforward, + FiniteDistribution.condition, coordinateMarginal] + refine Fintype.sum_equiv (Game.tupleQuestionEquiv (Q₁ := Q₁) (Q₂ := Q₂) n).symm _ _ ?_ + intro questions + cases he : G.selectedWins strategy selected questions <;> + simp [Game.repetition_question_weight, Game.tupleQuestionEquiv, + posterior, independentProduct, selectedTupleLikelihood, Game.selectedSuccess, he] + +theorem selectedQuestionMarginal_totalVariation_sq_sum_le_log + (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) : + (∑ i : Fin n, + (selectedQuestionMarginal G strategy selected positive i).totalVariation G.questions ^ 2) ≤ + Real.log (1 / G.selectedSuccess strategy selected) := by + classical + change (∑ i : Fin n, Information.totalVariation + (selectedQuestionMarginal G strategy selected positive i).weight G.questions.weight ^ 2) ≤ _ + simp_rw [selectedQuestionMarginal_weight] + exact posterior_coordinate_totalVariation_sq_sum_le_log + (fun _ : Fin n => G.questions.weight) (fun _ => gameLaw_isProbability G.questions) + (selectedTupleLikelihood G strategy selected) + (selectedTupleLikelihood_nonnegative G strategy selected) + (selectedTupleLikelihood_le_one G strategy selected) + positive (selectedTupleLikelihood_mass G strategy selected) + +theorem unselectedQuestionMarginal_totalVariation_sq_sum_le_log + (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) : + (∑ i : {i : Fin n // i ∉ selected}, + (selectedQuestionMarginal G strategy selected positive i.1).totalVariation G.questions ^ 2) ≤ + Real.log (1 / G.selectedSuccess strategy selected) := by + classical + let d : Fin n → ℝ := fun i => + (selectedQuestionMarginal G strategy selected positive i).totalVariation G.questions + have hfull := selectedQuestionMarginal_totalVariation_sq_sum_le_log G strategy selected positive + have hsplit := Fintype.sum_subtype_add_sum_subtype (fun i : Fin n => i ∈ selected) + (fun i => d i ^ 2) + have hinst : Subtype.fintype (fun i : Fin n => i ∈ selected) = + Finset.Subtype.fintype selected := Subsingleton.elim _ _ + rw [hinst] at hsplit + have hselected : 0 ≤ ∑ i : {i : Fin n // i ∈ selected}, d i.1 ^ 2 := + Finset.sum_nonneg (fun _ _ => sq_nonneg _) + change (∑ i : {i : Fin n // i ∉ selected}, d i.1 ^ 2) ≤ _ + change (∑ i : Fin n, d i ^ 2) ≤ _ at hfull + linarith + +theorem unselectedQuestionMarginal_totalVariation_sum_le_sqrt + (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) : + (∑ i : {i : Fin n // i ∉ selected}, + (selectedQuestionMarginal G strategy selected positive i.1).totalVariation G.questions) ≤ + Real.sqrt ((Fintype.card {i : Fin n // i ∉ selected} : ℝ) * + Real.log (1 / G.selectedSuccess strategy selected)) := by + classical + let d : {i : Fin n // i ∉ selected} → ℝ := fun i => + (selectedQuestionMarginal G strategy selected positive i.1).totalVariation G.questions + have hsq := unselectedQuestionMarginal_totalVariation_sq_sum_le_log G strategy selected positive + have hcs := Finset.sum_mul_sq_le_sq_mul_sq + (Finset.univ : Finset {i : Fin n // i ∉ selected}) 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 / G.selectedSuccess strategy selected) := + (Finset.sum_nonneg (fun _ _ => sq_nonneg _)).trans hsq + have hcard : 0 ≤ (Fintype.card {i : Fin n // i ∉ selected} : ℝ) := 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 {i : Fin n // i ∉ selected} : ℝ) * + Real.log (1 / G.selectedSuccess strategy selected)) + change (∑ i, d i) ≤ _ + change (∑ i, d i ^ 2) ≤ _ at hsq + change (Fintype.card {i : Fin n // i ∉ selected} : ℝ) * (∑ i, d i ^ 2) ≤ _ at hmul + nlinarith + +theorem unselectedQuestionMarginal_totalVariation_sum_le_sqrt_sub_card + (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) : + (∑ i : {i : Fin n // i ∉ selected}, + (selectedQuestionMarginal G strategy selected positive i.1).totalVariation G.questions) ≤ + Real.sqrt (((n - selected.card : Nat) : ℝ) * + Real.log (1 / G.selectedSuccess strategy selected)) := by + classical + have hcard : Fintype.card {i : Fin n // i ∉ selected} = n - selected.card := by + simp [Fintype.card_subtype_compl] + simpa only [hcard] using + unselectedQuestionMarginal_totalVariation_sum_le_sqrt G strategy selected positive + +end + +end MinUncutGames.Foundations.Repetition + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/SelectionSequence.lean b/lean/OAI/Computability/MinUncut/PCP/SelectionSequence.lean new file mode 100644 index 0000000000000000000000000000000000000000..5c303dd50c8ad495c5fa5c8b43482b12bcd787d0 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/SelectionSequence.lean @@ -0,0 +1,313 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.SelectedLikelihood +import OAI.Computability.MinUncut.Machines.AlphabetBudget + +namespace OAI + +namespace MinUncutGames.Foundations.Repetition.SelectionSequence + +private theorem exists_unused {n : Nat} (S : Finset (Fin n)) (hcard : S.card < n) : + ∃ j : Fin n, j ∉ S := by + classical + apply Classical.byContradiction + intro h + have hall : ∀ j : Fin n, j ∈ S := by + intro j + apply Classical.byContradiction + intro hj + exact h ⟨j, hj⟩ + have hfull : S = Finset.univ := + Finset.ext (fun j => iff_of_true (hall j) (Finset.mem_univ j)) + have hbad : n < n := by + simpa only [hfull, Finset.card_univ, Fintype.card_fin] using hcard + exact Nat.lt_irrefl n hbad + +noncomputable def nextSet {n : Nat} + (Step : Finset (Fin n) → Fin n → Prop) + (witness : ∀ S, S.card < n → ∃ j, j ∉ S ∧ Step S j) + (S : Finset (Fin n)) : Finset (Fin n) := + if hs : S.card < n then insert (Classical.choose (witness S hs)) S else S + +noncomputable def selectedSet {n : Nat} + (Step : Finset (Fin n) → Fin n → Prop) + (witness : ∀ S, S.card < n → ∃ j, j ∉ S ∧ Step S j) : Nat → Finset (Fin n) + | 0 => ∅ + | m + 1 => nextSet Step witness (selectedSet Step witness m) + +theorem selectedSet_card {n : Nat} + (Step : Finset (Fin n) → Fin n → Prop) + (witness : ∀ S, S.card < n → ∃ j, j ∉ S ∧ Step S j) (m : Nat) : + (selectedSet Step witness m).card = min m n := by + induction m with + | zero => simp [selectedSet] + | succ m ih => + by_cases hm : m < n + · have hc : (selectedSet Step witness m).card = m := by + simpa only [Nat.min_eq_left (Nat.le_of_lt hm)] using ih + have hs : (selectedSet Step witness m).card < n := by + simpa only [hc] using hm + rw [selectedSet, nextSet, dite_eq_left hs, + Finset.card_insert_of_notMem ((Classical.choose_spec (witness _ hs)).1), + hc, Nat.min_eq_left (Nat.succ_le_of_lt hm)] + · have hc : (selectedSet Step witness m).card = n := by + simpa only [Nat.min_eq_right (Nat.le_of_not_gt hm)] using ih + have hs : ¬(selectedSet Step witness m).card < n := by + rw [hc] + exact Nat.not_lt.mpr (Nat.le_refl n) + rw [selectedSet, nextSet, dite_eq_right hs, hc, + Nat.min_eq_right (Nat.le_trans (Nat.le_of_not_gt hm) (Nat.le_succ m))] + +theorem selectedSet_subset_succ {n : Nat} + (Step : Finset (Fin n) → Fin n → Prop) + (witness : ∀ S, S.card < n → ∃ j, j ∉ S ∧ Step S j) (m : Nat) : + selectedSet Step witness m ⊆ selectedSet Step witness (m + 1) := by + change selectedSet Step witness m ⊆ nextSet Step witness (selectedSet Step witness m) + unfold nextSet + split + · exact Finset.subset_insert _ _ + · exact le_rfl + +theorem selectedSet_monotone {n : Nat} + (Step : Finset (Fin n) → Fin n → Prop) + (witness : ∀ S, S.card < n → ∃ j, j ∉ S ∧ Step S j) : + Monotone (selectedSet Step witness) := + monotone_nat_of_le_succ (selectedSet_subset_succ Step witness) + +theorem selectedSet_univ {n : Nat} + (Step : Finset (Fin n) → Fin n → Prop) + (witness : ∀ S, S.card < n → ∃ j, j ∉ S ∧ Step S j) : + selectedSet Step witness n = Finset.univ := by + apply Finset.eq_of_subset_of_card_le (Finset.subset_univ _) + simp [selectedSet_card] + +theorem selectedSet_step {n : Nat} + (Step : Finset (Fin n) → Fin n → Prop) + (witness : ∀ S, S.card < n → ∃ j, j ∉ S ∧ Step S j) + (m : Nat) (hm : m < n) : + ∃ j, j ∉ selectedSet Step witness m ∧ + selectedSet Step witness (m + 1) = insert j (selectedSet Step witness m) ∧ + Step (selectedSet Step witness m) j := by + have hc : (selectedSet Step witness m).card = m := by + rw [selectedSet_card, Nat.min_eq_left (Nat.le_of_lt hm)] + have hs : (selectedSet Step witness m).card < n := by simpa only [hc] using hm + let j := Classical.choose (witness (selectedSet Step witness m) hs) + have hj := Classical.choose_spec (witness (selectedSet Step witness m) hs) + refine ⟨j, hj.1, ?_, hj.2⟩ + simp only [selectedSet, nextSet, dite_eq_left hs, j] + +def SetStep {n : Nat} (P : Finset (Fin n) → ℝ) (v ell : ℝ) + (S : Finset (Fin n)) (j : Fin n) : Prop := + P (insert j S) ≤ P S * + (v + 15 * Real.sqrt (((S.card : ℝ) * ell + logTwo (1 / P S)) / + ((n : ℝ) - S.card))) + +theorem totalSetStep {n : Nat} (P : Finset (Fin n) → ℝ) (v ell : ℝ) + (hnonneg : ∀ S, 0 ≤ P S) (hanti : Antitone P) + (hpositive : ∀ S, S.card < n → 0 < P S → + ∃ j, j ∉ S ∧ SetStep P v ell S j) : + ∀ S, S.card < n → ∃ j, j ∉ S ∧ SetStep P v ell S j := by + intro S hcard + by_cases hp : 0 < P S + · exact hpositive S hcard hp + · obtain ⟨j, hj⟩ := exists_unused S hcard + have hz : P S = 0 := le_antisymm (le_of_not_gt hp) (hnonneg S) + have hnext : P (insert j S) = 0 := le_antisymm + ((hanti (Finset.subset_insert j S)).trans (le_of_eq hz)) (hnonneg (insert j S)) + refine ⟨j, hj, ?_⟩ + simpa only [SetStep, hnext, hz, zero_mul] using (le_refl (0 : ℝ)) + +theorem exists_scalar_sequence {n : Nat} (P : Finset (Fin n) → ℝ) (v ell : ℝ) + (hempty : P ∅ = 1) (hnonneg : ∀ S, 0 ≤ P S) (hanti : Antitone P) + (hpositive : ∀ S, S.card < n → 0 < P S → + ∃ j, j ∉ S ∧ SetStep P v ell S j) : + ∃ p : Nat → ℝ, p 0 = 1 ∧ (∀ m, 0 ≤ p m) ∧ Antitone p ∧ + ScalarRecurrence p n v ell ∧ p n = P Finset.univ := by + let witness := totalSetStep P v ell hnonneg hanti hpositive + let sets := selectedSet (SetStep P v ell) witness + let p := fun m => P (sets m) + refine ⟨p, ?_, ?_, ?_, ?_, ?_⟩ + · change P (selectedSet (SetStep P v ell) witness 0) = 1 + simpa only [selectedSet] using hempty + · intro m + exact hnonneg (sets m) + · intro i j hij + exact hanti (selectedSet_monotone (SetStep P v ell) witness hij) + · intro m hm + obtain ⟨j, _, hnext, hbound⟩ := + selectedSet_step (SetStep P v ell) witness m hm + have hc : (selectedSet (SetStep P v ell) witness m).card = m := by + rw [selectedSet_card, Nat.min_eq_left (Nat.le_of_lt hm)] + change P (selectedSet (SetStep P v ell) witness (m + 1)) ≤ _ + rw [hnext] + simpa only [SetStep, hc] using hbound + · change P (selectedSet (SetStep P v ell) witness n) = P Finset.univ + rw [selectedSet_univ] + +open MinUncutGames.Foundations.Games + +variable {Q₁ Q₂ A₁ A₂ : Type*} +variable [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂] +variable [Nonempty A₁] [Nonempty A₂] + +def ConditionalCoordinateBound (G : Game Q₁ Q₂ A₁ A₂) (n : Nat) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (ell : ℝ) : Prop := + ∀ (S : Finset (Fin n)) (_hcard : S.card < n) + (hp : 0 < G.selectedSuccess strategy S), + ∃ j, j ∉ S ∧ + (((G.repetition n).questions.condition (G.selectedWins strategy S) hp).probability + (G.coordinateWin strategy j)) ≤ + G.value + 15 * Real.sqrt + (((S.card : ℝ) * ell + logTwo (1 / G.selectedSuccess strategy S)) / + ((n : ℝ) - S.card)) + +theorem repetition_success_le_of_conditionalCoordinateBound + (G : Game Q₁ Q₂ A₁ A₂) (n : Nat) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + {v ell : ℝ} (hvalue : G.value ≤ v) (hv1 : v < 1) (hell : 1 ≤ ell) + (hcoordinate : ConditionalCoordinateBound G n strategy ell) : + (G.repetition n).success strategy ≤ + (1 - (1 - v)^3 / 6000)^((n : ℝ) / ell) := by + have hpositive : ∀ S : Finset (Fin n), S.card < n → + 0 < G.selectedSuccess strategy S → + ∃ j, j ∉ S ∧ SetStep (G.selectedSuccess strategy) v ell S j := by + intro S hcard hp + obtain ⟨j, hj, hbound⟩ := hcoordinate S hcard hp + refine ⟨j, hj, ?_⟩ + change G.selectedSuccess strategy (insert j S) ≤ _ + rw [G.selectedSuccess_insert strategy S j hp] + exact mul_le_mul_of_nonneg_left + (hbound.trans (add_le_add hvalue (le_refl _))) (le_of_lt hp) + obtain ⟨p, hp0, hpnonneg, hpmono, hrec, hpn⟩ := + exists_scalar_sequence (G.selectedSuccess strategy) v ell + (G.selectedSuccess_empty strategy) (G.selectedSuccess_nonnegative strategy) + (G.selectedSuccess_antitone strategy) hpositive + have hbound := scalar_bound_6000 p n + (G.value_nonnegative.trans hvalue) hv1 hell hp0 hpnonneg hpmono hrec + rw [hpn, G.selectedSuccess_univ strategy] at hbound + exact hbound + +end MinUncutGames.Foundations.Repetition.SelectionSequence + +namespace MinUncutGames.Foundations.Repetition +open scoped BigOperators +open Games +noncomputable section +variable {Q₁ Q₂ A₁ A₂ : Type*} + [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂] + [Nonempty A₁] [Nonempty A₂] + [DecidableEq Q₁] [DecidableEq Q₂] {n : Nat} + +theorem selected_coordinate_probability_le_value_add_error + (G : Game Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (selected : Finset (Fin n)) (positive : 0 < G.selectedSuccess strategy selected) + (j : {i : Fin n // i ∉ selected}) : + ((G.repetition n).questions.condition (G.selectedWins strategy selected) positive).probability + (G.coordinateWin strategy j.1) ≤ + G.value + selectedEmbeddingError G strategy selected positive j := by + classical + let : Nonempty (SelectedCommonData (Q₁ := Q₁) (Q₂ := Q₂) + (A₁ := A₁) (A₂ := A₂) selected j) := + finiteDistribution_nonempty (selectedProfileFallback G strategy selected positive j) + have h := coordinate_probability_le_value_of_local_completion G j.1 strategy + (selectedSamplingTarget G strategy selected positive j) + (selectedLeftProfile G strategy selected positive j) + (selectedRightProfile G strategy selected positive j) + (selectedFullLeftCompletion G strategy selected j) + (selectedFullRightCompletion G strategy selected j) + (selectedFullLeftCompletion_support G strategy selected j) + (selectedFullRightCompletion_support G strategy selected j) + (Classical.choice inferInstance) + have htarget : (selectedSamplingTarget G strategy selected positive j).mixture + (fun z => (selectedFullLeftCompletion G strategy selected j (z.1.1,z.2)).product + (selectedFullRightCompletion G strategy selected j (z.1.2,z.2))) = + (G.repetition n).questions.condition (G.selectedWins strategy selected) positive := + selectedFullCompletionMixture_eq_conditionedQuestions G strategy selected positive j + rw [htarget, selectedSamplingTarget_left_error, selectedSamplingTarget_right_error] at h + exact h + +theorem holenstein_conditionalCoordinateBound + (G : Game Q₁ Q₂ A₁ A₂) (n : Nat) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + (ell : ℝ) + (halphabet : logTwo ((Fintype.card A₁ : ℝ) * (Fintype.card A₂ : ℝ)) ≤ ell) : + SelectionSequence.ConditionalCoordinateBound G n strategy ell := by + intro selected hcard positive + obtain ⟨j,hj⟩ := exists_coordinate_le_information_budget G strategy selected positive ell + halphabet hcard (selectedEmbeddingError G strategy selected positive) + (selectedEmbeddingError_sum_le_fifteen G strategy selected positive) + exact ⟨j.1,j.property, + (selected_coordinate_probability_le_value_add_error G strategy selected positive j).trans + (add_le_add le_rfl hj)⟩ + +theorem holenstein_repetition_success + (G : Game Q₁ Q₂ A₁ A₂) (n : Nat) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) + {v ell : ℝ} (hvalue : G.value ≤ v) (hv : v < 1) (hell : 1 ≤ ell) + (halphabet : logTwo ((Fintype.card A₁ : ℝ) * (Fintype.card A₂ : ℝ)) ≤ ell) : + (G.repetition n).success strategy ≤ + (1 - (1 - v)^3 / 6000)^((n : ℝ) / ell) := + SelectionSequence.repetition_success_le_of_conditionalCoordinateBound G n strategy + hvalue hv hell (holenstein_conditionalCoordinateBound G n strategy ell halphabet) + +theorem holenstein_repetition_value + (G : Game Q₁ Q₂ A₁ A₂) (n : Nat) + {v ell : ℝ} (hvalue : G.value ≤ v) (hv : v < 1) (hell : 1 ≤ ell) + (halphabet : logTwo ((Fintype.card A₁ : ℝ) * (Fintype.card A₂ : ℝ)) ≤ ell) : + (G.repetition n).value ≤ + (1 - (1 - v)^3 / 6000)^((n : ℝ) / ell) := by + apply ((G.repetition n).value_le_iff _).2 + intro strategy + exact holenstein_repetition_success G n strategy hvalue hv hell halphabet + +end +end MinUncutGames.Foundations.Repetition + +noncomputable section +namespace MinUncut.Outer +open MinUncut.Inner MinUncutGames.Foundations.Games MinUncutGames.Foundations.Repetition + +def repetitionRate : ℝ := 99999999/100000000 +lemma repetitionRate_pos : 0 v ∈ S) = S := by + ext v + simp + rw [mean_eq_sum_div_card] + simp only [indicator, Finset.sum_boole, hf] + +theorem energy_indicator (S : Finset V) : energy (indicator S) = mean (indicator S) := by + unfold energy + congr 1 + funext v + unfold indicator + split_ifs <;> norm_num + +omit [Fintype V] in +theorem indicator_nonnegative (S : Finset V) (v : V) : 0 ≤ indicator S v := by + unfold indicator + split_ifs <;> norm_num +end Indicators + +variable {V D : Type*} [Fintype V] [Fintype D] [DecidableEq V] + +def cut (G : PortGraph V D) (S : Finset V) : Finset (V × D) := + Finset.univ.filter (fun e => e.1 ∈ S ∧ (G.rot e).1 ∉ S) + +section Nonempty +variable [Nonempty V] [Nonempty D] (G : PortGraph V D) + +omit [Nonempty V] in +theorem cut_density_eq (S : Finset V) : + ((cut G S).card : ℝ) / (Fintype.card (V × D) : ℝ) = + mean (indicator S) - correlation (indicator S) (averagingOperator G (indicator S)) := by + classical + calc + _ = mean (indicator (cut G S)) := (mean_indicator (cut G S)).symm + _ = mean (fun e : V × D => indicator S e.1 - + indicator S e.1 * indicator S (G.rot e).1) := by + congr 1 + funext e + by_cases hv : e.1 ∈ S <;> by_cases hw : (G.rot e).1 ∈ S <;> + simp [indicator, cut, hv, hw] + _ = mean (fun v => mean (fun d : D => indicator S v - + indicator S v * indicator S (G.rot (v,d)).1)) := mean_prod _ + _ = mean (fun v => indicator S v - + indicator S v * averagingOperator G (indicator S) v) := by + congr 1 + funext v + rw [mean_sub, mean_const, mean_mul_left] + rfl + _ = _ := mean_sub _ _ + +theorem cut_density_ge_variance + (certificate : SpectralCertificate G (1/2)) (S : Finset V) : + (1/2:ℝ) * mean (indicator S) * (1 - mean (indicator S)) ≤ + ((cut G S).card : ℝ) / (Fintype.card (V × D) : ℝ) := by + let f := indicator S + have hz : mean (fun v => f v - mean f) = 0 := by + rw [mean_sub, mean_const, sub_self] + have he : energy (fun v => f v - mean f) = mean f - mean f ^ 2 := by + rw [energy_sub_const, energy_indicator] + ring + have hb := zero_mean_correlation_bound G (1/2) certificate + (fun v => f v - mean f) hz 1 + have hc := correlation_centered G f 1 + simp only [iterateOperator, pow_one, he] at hb hc + rw [cut_density_eq] + change (1/2:ℝ) * mean f * (1 - mean f) ≤ + mean f - correlation f (averagingOperator G f) + nlinarith + +theorem cut_density_ge_quarter + (certificate : SpectralCertificate G (1/2)) (S : Finset V) + (hsmall : 2 * S.card ≤ Fintype.card V) : + mean (indicator S) / 4 ≤ + ((cut G S).card : ℝ) / (Fintype.card (V × D) : ℝ) := by + have hN : (0:ℝ) < Fintype.card V := by exact_mod_cast Fintype.card_pos + have hp0 : 0 ≤ mean (indicator S) := mean_nonnegative _ (indicator_nonnegative S) + have hp : mean (indicator S) ≤ (1/2:ℝ) := by + rw [mean_indicator] + apply (div_le_iff₀ hN).mpr + have hs : (2:ℝ) * (S.card : ℝ) ≤ (Fintype.card V : ℝ) := by exact_mod_cast hsmall + nlinarith + have hv := cut_density_ge_variance G certificate S + have hprod := mul_nonneg hp0 (sub_nonneg.mpr hp) + nlinarith + +theorem cut_card_ge_quarter_degree + (certificate : SpectralCertificate G (1/2)) (S : Finset V) + (hsmall : 2 * S.card ≤ Fintype.card V) : + (Fintype.card D : ℝ) * (S.card : ℝ) / 4 ≤ ((cut G S).card : ℝ) := by + have hN : (0:ℝ) < Fintype.card V := by exact_mod_cast Fintype.card_pos + have hD : (0:ℝ) < Fintype.card D := by exact_mod_cast Fintype.card_pos + have h := cut_density_ge_quarter G certificate S hsmall + rw [Fintype.card_prod, Nat.cast_mul] at h + have hh := (le_div_iff₀ (mul_pos hN hD)).mp h + have he : mean (indicator S) / 4 * + ((Fintype.card V : ℝ) * (Fintype.card D : ℝ)) = + (Fintype.card D : ℝ) * (S.card : ℝ) / 4 := by + rw [mean_indicator] + field_simp [ne_of_gt hN] + rw [he] at hh + exact hh + +theorem degree_mul_card_le_four_cut + (certificate : SpectralCertificate G (1/2)) (S : Finset V) + (hsmall : 2 * S.card ≤ Fintype.card V) : + Fintype.card D * S.card ≤ 4 * (cut G S).card := by + have h := cut_card_ge_quarter_degree G certificate S hsmall + have hr : (Fintype.card D : ℝ) * (S.card : ℝ) ≤ 4 * ((cut G S).card : ℝ) := by + linarith + exact_mod_cast hr + +theorem cut_card_ge_quarter_degree_of_card_le_half + (certificate : SpectralCertificate G (1/2)) (S : Finset V) + (hsmall : S.card ≤ Fintype.card V / 2) : + (Fintype.card D : ℝ) * (S.card : ℝ) / 4 ≤ ((cut G S).card : ℝ) := + cut_card_ge_quarter_degree G certificate S (by omega) +end Nonempty + +theorem cut_card_ge_twice (G : PortGraph V D) + (certificate : SpectralCertificate G (1/2)) (hdegree : 8 ≤ Fintype.card D) + (S : Finset V) (hsmall : 2 * S.card ≤ Fintype.card V) : + 2 * S.card ≤ (cut G S).card := by + let : Nonempty D := Fintype.card_pos_iff.mp (by omega) + rcases isEmpty_or_nonempty V with hV | hV + · let := hV + have hzero : Fintype.card V = 0 := Fintype.card_eq_zero + have hs : S.card = 0 := by omega + simp only [hs, mul_zero, Nat.zero_le] + · let := hV + have h := degree_mul_card_le_four_cut G certificate S hsmall + have hdeg := Nat.mul_le_mul_right S.card hdegree + omega + +end MinUncutGames.Foundations.PCP.SpectralCut + + +namespace MinUncutGames.Foundations.PCP.Regularization + +open PoweringWalks DegreeReplacement + +variable {V E A : Type*} [Fintype V] [Fintype E] [Fintype A] +variable [DecidableEq V] [DecidableEq E] [DecidableEq A] + +abbrev Vertex (G : ConstraintGraph V E A) := PaddedDart G (CloudPadding.dummy G) +abbrev Port := ExpanderFamily.Port ⊕ Unit + +def degree : Nat := Fintype.card Port + +theorem degree_eq : degree = Fintype.card ExpanderFamily.Port + 1 := by + simp [degree, Port] + +theorem degree_positive : 0 < degree := by rw [degree_eq]; omega + +def cloudEquiv (G : ConstraintGraph V E A) (v : V) + (hk : 0 < Fintype.card (Cloud G v)) : + ExpanderFamily.Vertex (ExpanderFamily.level (Fintype.card (Cloud G v))) ≃ + Cloud (paddedGraph G (CloudPadding.dummy G)) v := + Fintype.equivOfCardEq (CloudPadding.card_cloud_eq_family G v hk).symm + +def cloudGraph (G : ConstraintGraph V E A) (v : V) : + PortGraph (Cloud (paddedGraph G (CloudPadding.dummy G)) v) ExpanderFamily.Port := + if hk : Fintype.card (Cloud G v) = 0 then + { rot := Equiv.refl _ + rot_involutive := fun _ => rfl } + else + GraphTransport.reindex + (ExpanderFamily.family (ExpanderFamily.level (Fintype.card (Cloud G v)))) + (cloudEquiv G v (Nat.pos_of_ne_zero hk)) (Equiv.refl _) + +omit [Fintype A] [DecidableEq E] [DecidableEq A] in +theorem cloudGraph_of_pos (G : ConstraintGraph V E A) (v : V) + (hk : 0 < Fintype.card (Cloud G v)) : + cloudGraph G v = GraphTransport.reindex + (ExpanderFamily.family (ExpanderFamily.level (Fintype.card (Cloud G v)))) + (cloudEquiv G v hk) (Equiv.refl _) := by + simp only [cloudGraph, dite_eq_right (Nat.ne_of_gt hk)] + +omit [Fintype A] [DecidableEq E] [DecidableEq A] in +theorem cloudGraph_certificate_of_pos (G : ConstraintGraph V E A) (v : V) + (hk : 0 < Fintype.card (Cloud G v)) : + SpectralReturn.SpectralCertificate (cloudGraph G v) (1 / 2 : ℝ) := by + rw [cloudGraph_of_pos G v hk] + exact GraphTransport.reindex_spectralCertificate _ _ _ _ + (ExpanderFamily.family_certificate _) + +omit [Fintype A] [DecidableEq A] in +theorem cloud_expansion (G : ConstraintGraph V E A) (v : V) + (S : Finset (Cloud (paddedGraph G (CloudPadding.dummy G)) v)) + (hsmall : S.card ≤ + Fintype.card (Cloud (paddedGraph G (CloudPadding.dummy G)) v) / 2) : + 2 * S.card ≤ + (CloudRounding.directedCut (fun ed => ((cloudGraph G v).rot ed).1) S).card := by + by_cases hk : Fintype.card (Cloud G v) = 0 + · have hzero : Fintype.card (Cloud (paddedGraph G (CloudPadding.dummy G)) v) = 0 := by + rw [CloudPadding.card_cloud, hk, CloudPadding.paddedSize_zero] + have hs : S.card = 0 := by omega + simp only [hs, mul_zero, Nat.zero_le] + · exact SpectralCut.cut_card_ge_twice (cloudGraph G v) + (cloudGraph_certificate_of_pos G v (Nat.pos_of_ne_zero hk)) + ExpanderFamily.port_degree_ge_eight S (by omega) + +def portGraph (G : ConstraintGraph V E A) : PortGraph (Vertex G) Port := + paddedReplacementPortGraph G (CloudPadding.dummy G) (cloudGraph G) + +def graph (G : ConstraintGraph V E A) : + ConstraintGraph (Vertex G) (Vertex G × Port) A := + paddedReplacementGraph G (CloudPadding.dummy G) (cloudGraph G) + +omit [Fintype A] [DecidableEq E] in +@[simp] theorem graph_tail (G : ConstraintGraph V E A) (e : Vertex G × Port) : + (graph G).tail e = e.1 := rfl + +omit [Fintype A] [DecidableEq E] in +theorem graph_reverse (G : ConstraintGraph V E A) : + (graph G).reverse = (portGraph G).rot := rfl + +def degreeEquiv (G : ConstraintGraph V E A) (v : Vertex G) : + Cloud (graph G) v ≃ Port where + toFun e := e.val.2 + invFun d := ⟨(v, d), rfl⟩ + left_inv := by + rintro ⟨⟨w, d⟩, hw⟩ + change w = v at hw + cases hw + rfl + right_inv _ := rfl + +omit [Fintype A] in +theorem fixed_degree (G : ConstraintGraph V E A) (v : Vertex G) : + Fintype.card (Cloud (graph G) v) = degree := + Fintype.card_congr (degreeEquiv G v) + +omit [Fintype A] [DecidableEq E] [DecidableEq A] in +theorem vertex_count_le (G : ConstraintGraph V E A) : + Fintype.card (Vertex G) ≤ ExpanderFamily.growth * Fintype.card E := + CloudPadding.card_paddedDart_le G + +omit [Fintype A] [DecidableEq E] [DecidableEq A] in +theorem dart_count (G : ConstraintGraph V E A) : + Fintype.card (Vertex G × Port) = Fintype.card (Vertex G) * degree := + Fintype.card_prod _ _ + +omit [Fintype A] [DecidableEq E] [DecidableEq A] in +theorem dart_count_le (G : ConstraintGraph V E A) : + Fintype.card (Vertex G × Port) ≤ + (ExpanderFamily.growth * degree) * Fintype.card E := by + rw [dart_count] + calc + Fintype.card (Vertex G) * degree ≤ + (ExpanderFamily.growth * Fintype.card E) * degree := + Nat.mul_le_mul_right degree (vertex_count_le G) + _ = (ExpanderFamily.growth * degree) * Fintype.card E := Nat.mul_right_comm _ _ _ + +def liftLabel (G : ConstraintGraph V E A) (labeling : V → A) : Vertex G → A := + DegreeReplacement.liftLabel (paddedGraph G (CloudPadding.dummy G)) labeling + +omit [Fintype A] [DecidableEq E] in +theorem lift_rejectionCount (G : ConstraintGraph V E A) (labeling : V → A) : + (graph G).rejectionCount (liftLabel G labeling) = G.rejectionCount labeling := + paddedReplacement_rejectionCount G (CloudPadding.dummy G) (cloudGraph G) labeling + +omit [Fintype A] [DecidableEq E] in +theorem completeness (G : ConstraintGraph V E A) (h : G.Satisfiable) : + (graph G).Satisfiable := + replacement_satisfiable (paddedGraph G (CloudPadding.dummy G)) (cloudGraph G) + (padded_satisfiable G (CloudPadding.dummy G) h) + +def roundLabels [Nonempty A] (G : ConstraintGraph V E A) (ell : Vertex G → A) : V → A := + CloudRounding.roundLabels (paddedGraph G (CloudPadding.dummy G)) ell + +theorem soundness [Nonempty A] (G : ConstraintGraph V E A) (ell : Vertex G → A) : + G.rejectionCount (roundLabels G ell) ≤ (graph G).rejectionCount ell := + CloudRounding.padded_replacement_soundness G (CloudPadding.dummy G) + (cloudGraph G) (cloud_expansion G) ell + +theorem exists_rounding [Nonempty A] (G : ConstraintGraph V E A) (ell : Vertex G → A) : + ∃ labeling : V → A, G.rejectionCount labeling ≤ (graph G).rejectionCount ell := + ⟨roundLabels G ell, soundness G ell⟩ + +theorem soundness_of_uniform_lower_bound [Nonempty A] (G : ConstraintGraph V E A) + (k : Nat) (lower : ∀ labeling : V → A, k ≤ G.rejectionCount labeling) + (ell : Vertex G → A) : k ≤ (graph G).rejectionCount ell := + (lower (roundLabels G ell)).trans (soundness G ell) + +end MinUncutGames.Foundations.PCP.Regularization + +end +namespace MinUncutGames.Foundations.PCP.LazySpectral + +open PoweringWalks SpectralReturn + +noncomputable section + +variable {V D : Type*} + +theorem half_sum_sq_le (a b : ℝ) : ((a + b) / 2) ^ 2 ≤ (a ^ 2 + b ^ 2) / 2 := by + nlinarith [sq_nonneg (a - b)] + +theorem lazy_energy_le_average [Fintype V] [Fintype D] [Nonempty D] + (G : PortGraph V D) (f : V → ℝ) : + energy (averagingOperator (lazyGraph G) f) ≤ + (energy f + energy (averagingOperator G f)) / 2 := by + calc + energy (averagingOperator (lazyGraph G) f) = + mean (fun v => ((f v + averagingOperator G f v) / 2) ^ 2) := by + unfold energy + congr 1 + funext v + rw [PoweringLazy.averagingOperator_lazy] + _ ≤ mean (fun v => (f v ^ 2 + averagingOperator G f v ^ 2) / 2) := + mean_mono (fun v => half_sum_sq_le _ _) + _ = mean (fun v => (1 / 2 : ℝ) * (f v ^ 2 + averagingOperator G f v ^ 2)) := by + congr 1 + funext v + ring + _ = (1 / 2 : ℝ) * (energy f + energy (averagingOperator G f)) := by + rw [mean_mul_left, mean_add] + rfl + _ = (energy f + energy (averagingOperator G f)) / 2 := by ring + +theorem lazy_energy_bound [Fintype V] [Fintype D] [Nonempty D] + (G : PortGraph V D) (lambda : ℝ) (hG : SpectralCertificate G lambda) + (f : V → ℝ) (hf : mean f = 0) : + energy (averagingOperator (lazyGraph G) f) ≤ + ((1 + lambda ^ 2) / 2) * energy f := by + calc + energy (averagingOperator (lazyGraph G) f) ≤ + (energy f + energy (averagingOperator G f)) / 2 := lazy_energy_le_average G f + _ ≤ (energy f + lambda ^ 2 * energy f) / 2 := by + have h := hG.contraction f hf + linarith + _ = ((1 + lambda ^ 2) / 2) * energy f := by ring + +theorem lazy_certificate_31_32 [Fintype V] [Fintype D] [Nonempty D] + (G : PortGraph V D) (hG : SpectralCertificate G (7 / 8)) : + SpectralCertificate (lazyGraph G) (31 / 32) where + nonnegative := by norm_num + lt_one := by norm_num + contraction f hf := by + have h := lazy_energy_bound G (7 / 8) hG f hf + have hcoef : ((1 + (7 / 8 : ℝ) ^ 2) / 2) ≤ (31 / 32 : ℝ) ^ 2 := by norm_num + exact h.trans (mul_le_mul_of_nonneg_right hcoef (energy_nonnegative f)) + +end + +end MinUncutGames.Foundations.PCP.LazySpectral + +noncomputable section + +namespace MinUncutGames.Foundations.PCP.Preprocessing + +open PoweringWalks SpectralReturn + +variable {V E A : Type*} [Fintype V] [Fintype E] [Fintype A] + [DecidableEq V] [DecidableEq E] [DecidableEq A] [Nonempty E] [Nonempty A] + +abbrev Vertex (G : ConstraintGraph V E A) := VertexPadding.Vertex (Regularization.Vertex G) +abbrev OverlayPort := Regularization.Port ⊕ ExpanderFamily.Port +abbrev Port := Bool × OverlayPort + +def degree : Nat := 2 * (2 * Expanders.baseDegree ^ 2 + 1) +def sizeFactor : Nat := ExpanderFamily.growth ^ 2 * degree + +private theorem card_lazy_sum {X Y : Type*} [Fintype X] [Fintype Y] + (a b : Nat) (hX : Fintype.card X = a) (hY : Fintype.card Y = b) : + Fintype.card (Bool × (X ⊕ Y)) = 2 * (a + b) := by + rw [Fintype.card_prod, Fintype.card_bool, Fintype.card_sum, hX, hY] + +private theorem doubled_add (a : Nat) : 2 * (2 * a + 1) = 2 * ((a + 1) + a) := by omega + +theorem degree_eq_card : degree = Fintype.card Port := by + have hr : Fintype.card Regularization.Port = Expanders.baseDegree ^ 2 + 1 := + Regularization.degree_eq.trans + (congrArg (fun n : Nat => n + 1) ExpanderFamily.card_port) + have hp : Fintype.card Port = + 2 * ((Expanders.baseDegree ^ 2 + 1) + Expanders.baseDegree ^ 2) := + card_lazy_sum _ _ hr ExpanderFamily.card_port + exact (doubled_add _).trans hp.symm + +theorem degree_positive : 0 < degree := by + unfold degree + omega + +theorem sizeFactor_positive : 0 < sizeFactor := by + have hg : 0 < ExpanderFamily.growth := + Nat.zero_lt_one.trans ExpanderFamily.growth_gt_one + exact Nat.mul_pos (Nat.pow_pos hg) degree_positive + +def paddedGraph (G : ConstraintGraph V E A) : + ConstraintGraph (Vertex G) (Vertex G × Regularization.Port) A := + VertexPadding.paddedG (Regularization.graph G) + +def overlayExpander (G : ConstraintGraph V E A) : + PortGraph (Vertex G) ExpanderFamily.Port := + GraphTransport.reindex + (ExpanderFamily.family (ExpanderFamily.level (Fintype.card (Regularization.Vertex G)))) + (VertexPadding.familyVertexEquiv (Regularization.Vertex G)).symm (Equiv.refl _) + +omit [Fintype A] [DecidableEq E] [DecidableEq A] [Nonempty E] [Nonempty A] in +theorem overlayExpander_certificate (G : ConstraintGraph V E A) : + SpectralCertificate (overlayExpander G) (1 / 2 : ℝ) := + GraphTransport.reindex_spectralCertificate _ _ _ _ (ExpanderFamily.family_certificate _) + +def overlayGraph (G : ConstraintGraph V E A) : + ConstraintGraph (Vertex G) (Vertex G × OverlayPort) A := + Overlay.constraintGraph (paddedGraph G) (overlayExpander G) + +def graph (G : ConstraintGraph V E A) : + ConstraintGraph (Vertex G) (Vertex G × Port) A := + LazyConstraint.constraintGraph (overlayGraph G) + +def portGraph (G : ConstraintGraph V E A) : PortGraph (Vertex G) Port := + Overlay.originalPortGraph (graph G) + +omit [Fintype A] [DecidableEq E] [Nonempty E] [Nonempty A] in +@[simp] theorem graph_tail (G : ConstraintGraph V E A) : (graph G).tail = Prod.fst := rfl + +omit [Fintype A] [DecidableEq E] [Nonempty E] [Nonempty A] in +@[simp] theorem graph_reverse (G : ConstraintGraph V E A) : + (graph G).reverse = (portGraph G).rot := rfl + +omit [Fintype A] [DecidableEq E] [Nonempty E] [Nonempty A] in +theorem accepts_reverse (G : ConstraintGraph V E A) (e : Vertex G × Port) (a b : A) : + (graph G).accepts ((portGraph G).rot e) b a = (graph G).accepts e a b := + (graph G).reverse_accepts e a b + +omit [Fintype A] [DecidableEq E] [Nonempty E] [Nonempty A] in +theorem portGraph_eq_lazyGraph (G : ConstraintGraph V E A) : + portGraph G = lazyGraph (Overlay.originalPortGraph (overlayGraph G)) := rfl + +omit [Fintype A] [DecidableEq E] [Nonempty A] in +theorem overlayGraph_certificate (G : ConstraintGraph V E A) : + SpectralCertificate (Overlay.originalPortGraph (overlayGraph G)) (7 / 8 : ℝ) := by + apply Overlay.constraintGraph_spectralCertificate + · exact Regularization.degree_eq + · have h := ExpanderFamily.port_degree_ge_eight + omega + · exact overlayExpander_certificate G + +omit [Fintype A] [DecidableEq E] [Nonempty A] in +theorem spectral_certificate (G : ConstraintGraph V E A) : + SpectralCertificate (portGraph G) (31 / 32 : ℝ) := by + rw [portGraph_eq_lazyGraph] + exact LazySpectral.lazy_certificate_31_32 _ (overlayGraph_certificate G) + +omit [Fintype A] [DecidableEq E] [DecidableEq A] [Nonempty A] in +theorem vertex_count_le (G : ConstraintGraph V E A) : + Fintype.card (Vertex G) ≤ ExpanderFamily.growth ^ 2 * Fintype.card E := by + calc + _ ≤ ExpanderFamily.growth * Fintype.card (Regularization.Vertex G) := + VertexPadding.card_vertex_le _ + _ ≤ ExpanderFamily.growth * (ExpanderFamily.growth * Fintype.card E) := + Nat.mul_le_mul_left _ (Regularization.vertex_count_le G) + _ = _ := by ring + +omit [Fintype A] [DecidableEq E] [DecidableEq A] [Nonempty E] [Nonempty A] in +theorem dart_count (G : ConstraintGraph V E A) : + Fintype.card (Vertex G × Port) = Fintype.card (Vertex G) * degree := by + rw [Fintype.card_prod, ← degree_eq_card] + +omit [Fintype A] [DecidableEq E] [DecidableEq A] [Nonempty A] in +theorem dart_count_le (G : ConstraintGraph V E A) : + Fintype.card (Vertex G × Port) ≤ sizeFactor * Fintype.card E := by + rw [dart_count] + calc + _ ≤ (ExpanderFamily.growth ^ 2 * Fintype.card E) * degree := + Nat.mul_le_mul_right degree (vertex_count_le G) + _ = _ := Nat.mul_right_comm _ _ _ + +def liftLabel (G : ConstraintGraph V E A) (labeling : V → A) : Vertex G → A := + VertexPadding.liftLabel (Classical.choice ‹Nonempty A›) (Regularization.liftLabel G labeling) + +omit [Fintype A] [DecidableEq E] [Nonempty E] in +theorem lift_rejectionCount (G : ConstraintGraph V E A) (labeling : V → A) : + (graph G).rejectionCount (liftLabel G labeling) = G.rejectionCount labeling := by + unfold graph + rw [LazyConstraint.rejectionCount_eq _ rfl] + unfold overlayGraph + rw [Overlay.rejectionCount_eq _ _ rfl] + unfold paddedGraph liftLabel + rw [VertexPadding.rejectionCount_liftLabel _ rfl] + exact Regularization.lift_rejectionCount G labeling + +omit [Fintype A] [DecidableEq E] [Nonempty E] in +theorem completeness (G : ConstraintGraph V E A) (hG : G.Satisfiable) : + (graph G).Satisfiable := by + apply (LazyConstraint.satisfiable_iff _ rfl).mpr + apply (Overlay.satisfiable_iff _ _ rfl).mpr + exact VertexPadding.paddedG_satisfiable (Regularization.graph G) rfl + (Classical.choice ‹Nonempty A›) (Regularization.completeness G hG) + +def roundLabels (G : ConstraintGraph V E A) (labeling : Vertex G → A) : V → A := + Regularization.roundLabels G (fun v => labeling (Sum.inl v)) + +omit [Nonempty E] in +theorem soundness (G : ConstraintGraph V E A) (labeling : Vertex G → A) : + G.rejectionCount (roundLabels G labeling) ≤ (graph G).rejectionCount labeling := by + calc + _ ≤ (Regularization.graph G).rejectionCount (fun v => labeling (Sum.inl v)) := + Regularization.soundness G _ + _ = (paddedGraph G).rejectionCount labeling := + (VertexPadding.paddedG_rejectionCount (Regularization.graph G) rfl labeling).symm + _ = (overlayGraph G).rejectionCount labeling := + (Overlay.rejectionCount_eq (paddedGraph G) (overlayExpander G) rfl labeling).symm + _ = (graph G).rejectionCount labeling := + (LazyConstraint.rejectionCount_eq (overlayGraph G) rfl labeling).symm + +omit [Nonempty E] in +theorem satisfiable_iff (G : ConstraintGraph V E A) : + (graph G).Satisfiable ↔ G.Satisfiable := by + constructor + · rintro ⟨labeling, hlabel⟩ + by_contra hG + have hpositive := G.rejectionCount_positive hG (roundLabels G labeling) + have hzero : (graph G).rejectionCount labeling = 0 := by + simp [ConstraintGraph.rejectionCount, ConstraintGraph.rejectedDarts, hlabel] + have hsound := soundness G labeling + omega + · exact completeness G + +theorem gap_transfer (G : ConstraintGraph V E A) (epsilon : ℚ) (he : 0 ≤ epsilon) + (lower : ∀ labeling : V → A, + epsilon * Fintype.card E ≤ (G.rejectionCount labeling : ℚ)) + (labeling : Vertex G → A) : + (epsilon / sizeFactor) * Fintype.card (Vertex G × Port) ≤ + ((graph G).rejectionCount labeling : ℚ) := by + have hfactor : (0 : ℚ) < sizeFactor := by exact_mod_cast sizeFactor_positive + have hcard : (Fintype.card (Vertex G × Port) : ℚ) ≤ + sizeFactor * Fintype.card E := by exact_mod_cast dart_count_le G + calc + _ ≤ (epsilon / sizeFactor) * (sizeFactor * Fintype.card E) := + mul_le_mul_of_nonneg_left hcard (div_nonneg he hfactor.le) + _ = epsilon * Fintype.card E := by field_simp + _ ≤ (G.rejectionCount (roundLabels G labeling) : ℚ) := lower _ + _ ≤ ((graph G).rejectionCount labeling : ℚ) := by exact_mod_cast soundness G labeling + +theorem gap_transfer_real (G : ConstraintGraph V E A) (epsilon : ℝ) (he : 0 ≤ epsilon) + (lower : ∀ labeling : V → A, + epsilon * Fintype.card E ≤ (G.rejectionCount labeling : ℝ)) + (labeling : Vertex G → A) : + (epsilon / sizeFactor) * Fintype.card (Vertex G × Port) ≤ + ((graph G).rejectionCount labeling : ℝ) := by + have hfactor : (0 : ℝ) < sizeFactor := by exact_mod_cast sizeFactor_positive + have hcard : (Fintype.card (Vertex G × Port) : ℝ) ≤ + sizeFactor * Fintype.card E := by exact_mod_cast dart_count_le G + calc + _ ≤ (epsilon / sizeFactor) * (sizeFactor * Fintype.card E) := + mul_le_mul_of_nonneg_left hcard (div_nonneg he hfactor.le) + _ = epsilon * Fintype.card E := by field_simp + _ ≤ (G.rejectionCount (roundLabels G labeling) : ℝ) := lower _ + _ ≤ ((graph G).rejectionCount labeling : ℝ) := by exact_mod_cast soundness G labeling + +end MinUncutGames.Foundations.PCP.Preprocessing + +end +namespace MinUncutGames.Foundations.PCP.PreprocessingTables + +open PreprocessingRegularTables + +abbrev BaseTable := PreprocessingRegularTables.BaseTable + +def degree : Nat := 2 * ((internalDegree + 1) + internalDegree) + +theorem degree_eq : degree = Preprocessing.degree := by + unfold degree internalDegree Preprocessing.degree + rw [pow_two] + omega + +def regularVertices (t : GraphTables.Table) : Nat := vertexCount t (padding t) +def vertices (t : GraphTables.Table) : Nat := PreprocessingLevels.paddedSize (regularVertices t) + +def padded (H : BaseTable) (t : GraphTables.Table) : + PortTables.Table (vertices t) (internalDegree + 1) := + PreprocessingPaddingTables.pad (regularize H t) + (PreprocessingLevels.le_paddedSize (regularVertices t)) + +def overlayFamily (H : BaseTable) (t : GraphTables.Table) : + ExpanderTables.Table (vertices t) internalDegree := + resizeTable (PreprocessingLevels.table_vertexCount_eq_paddedSize (regularVertices t)) + (ExpanderTables.family H (PreprocessingLevels.boundedLevel (regularVertices t))) + +def preprocess (H : BaseTable) (t : GraphTables.Table) : + PortTables.Table (vertices t) degree := + PreprocessingOverlayTables.lazy + (PreprocessingOverlayTables.overlay (padded H t) (overlayFamily H t)) + +def output (H : BaseTable) (t : GraphTables.Table) : PortTables.Input degree := + ⟨vertices t, preprocess H t⟩ + +def graphTable (H : BaseTable) (t : GraphTables.Table) : GraphTables.Table := + PortTables.graphTable (preprocess H t) + +def outputBits (H : BaseTable) (t : GraphTables.Table) : List Bool := + PortTables.tableBits (preprocess H t) + +theorem regularVertices_ge_darts (t : GraphTables.Table) : t.darts ≤ regularVertices t := by + change t.darts ≤ t.darts + _ + omega + +theorem regularVertices_le (t : GraphTables.Table) : + regularVertices t ≤ ExpanderFamily.growth * t.darts := vertexCount_le t + +theorem vertices_positive (t : GraphTables.Table) : 0 < vertices t := + PreprocessingLevels.paddedSize_positive _ + +theorem vertices_le_of_positive (t : GraphTables.Table) (ht : 0 < t.darts) : + vertices t ≤ ExpanderFamily.growth ^ 2 * t.darts := by + have hr : 0 < regularVertices t := ht.trans_le (regularVertices_ge_darts t) + calc + _ ≤ ExpanderFamily.growth * regularVertices t := + (PreprocessingLevels.paddedSize_bounds hr).2 + _ ≤ ExpanderFamily.growth * (ExpanderFamily.growth * t.darts) := + Nat.mul_le_mul_left _ (regularVertices_le t) + _ = _ := by ring + +theorem vertices_eq_one_of_no_darts (t : GraphTables.Table) (ht : t.darts = 0) : + vertices t = 1 := by + unfold vertices regularVertices + rw [vertexCount_eq_zero_of_no_darts t ht, PreprocessingLevels.paddedSize_zero] + +theorem vertices_le (t : GraphTables.Table) : + vertices t ≤ ExpanderFamily.growth ^ 2 * (t.darts + 1) := by + by_cases ht : t.darts = 0 + · rw [vertices_eq_one_of_no_darts t ht, ht] + have hg : 0 < ExpanderFamily.growth := Nat.zero_lt_one.trans ExpanderFamily.growth_gt_one + have hp : 0 < ExpanderFamily.growth ^ 2 := Nat.pow_pos hg + simpa using Nat.succ_le_of_lt hp + · exact (vertices_le_of_positive t (Nat.pos_of_ne_zero ht)).trans + (Nat.mul_le_mul_left _ (Nat.le_succ _)) + +theorem darts_eq (H : BaseTable) (t : GraphTables.Table) : + (graphTable H t).darts = vertices t * degree := rfl + +theorem darts_le (H : BaseTable) (t : GraphTables.Table) : + (graphTable H t).darts ≤ Preprocessing.sizeFactor * (t.darts + 1) := by + rw [darts_eq] + calc + _ ≤ (ExpanderFamily.growth ^ 2 * (t.darts + 1)) * degree := + Nat.mul_le_mul_right _ (vertices_le t) + _ = _ := by rw [degree_eq]; unfold Preprocessing.sizeFactor; ring + +theorem vertices_le_inputBits (t : GraphTables.Table) : + vertices t ≤ ExpanderFamily.growth ^ 2 * ((GraphTables.tableBits t).length + 1) := + (vertices_le t).trans (Nat.mul_le_mul_left _ + (Nat.add_le_add_right (GraphTables.darts_le_tableBits_length t) 1)) + +theorem darts_le_inputBits (H : BaseTable) (t : GraphTables.Table) : + (graphTable H t).darts ≤ + Preprocessing.sizeFactor * ((GraphTables.tableBits t).length + 1) := + (darts_le H t).trans (Nat.mul_le_mul_left _ + (Nat.add_le_add_right (GraphTables.darts_le_tableBits_length t) 1)) + +end MinUncutGames.Foundations.PCP.PreprocessingTables + +namespace MinUncutGames.Foundations.PCP.PreprocessingRegularSoundness + +open PoweringWalks DegreeReplacement SpectralReturn PreprocessingRegularTables + +theorem internalDegree_ge_eight : 8 ≤ internalDegree := by + simpa only [ExpanderFamily.card_port, internalDegree, pow_two] using + ExpanderFamily.port_degree_ge_eight + +theorem baseDegree_ne_zero : Expanders.baseDegree ≠ 0 := by + intro h + have hdegree := internalDegree_ge_eight + simp only [internalDegree, h, Nat.zero_mul] at hdegree + omega + +theorem resizeTable_certificate {n m q : Nat} (h : n = m) + (table : ExpanderTables.Table n q) (lambda : ℝ) + (certificate : SpectralCertificate (ExpanderTables.graph table) lambda) : + SpectralCertificate (ExpanderTables.graph (resizeTable h table)) lambda := by + cases h + exact certificate + +theorem familyCloudTable_certificate_of_pos (H : BaseTable) + (certificate : SpectralCertificate (ExpanderTables.graph H) (1 / 100 : ℝ)) + (t : GraphTables.Table) (v : Fin t.vertices) + (hk : 0 < PreprocessingCloudIndex.cloudSize t v) : + SpectralCertificate (ExpanderTables.graph (familyCloudTable H t v)) (1 / 2 : ℝ) := by + let : NeZero Expanders.baseDegree := ⟨baseDegree_ne_zero⟩ + unfold familyCloudTable + rw [dite_eq_right (Nat.ne_of_gt hk)] + apply resizeTable_certificate + exact ExpanderTables.family_certificate H certificate _ + +theorem cloudGraphs_certificate_of_pos (H : BaseTable) + (certificate : SpectralCertificate (ExpanderTables.graph H) (1 / 100 : ℝ)) + (t : GraphTables.Table) (v : Fin t.vertices) + (hk : 0 < PreprocessingCloudIndex.cloudSize t v) : + SpectralCertificate (cloudGraphs t (padding t) (familyCloudTable H t) v) + (1 / 2 : ℝ) := by + exact GraphTransport.reindex_spectralCertificate _ _ _ _ + (familyCloudTable_certificate_of_pos H certificate t v hk) + +theorem cloud_expansion (H : BaseTable) + (certificate : SpectralCertificate (ExpanderTables.graph H) (1 / 100 : ℝ)) + (t : GraphTables.Table) (v : Fin t.vertices) + (S : Finset (PreprocessingCloudIndex.PaddedCloud t (padding t) v)) + (hsmall : S.card ≤ + Fintype.card (PreprocessingCloudIndex.PaddedCloud t (padding t) v) / 2) : + 2 * S.card ≤ (CloudRounding.directedCut + (fun ed => ((cloudGraphs t (padding t) (familyCloudTable H t) v).rot ed).1) S).card := by + by_cases hk : PreprocessingCloudIndex.cloudSize t v = 0 + · have hzero : Fintype.card (PreprocessingCloudIndex.PaddedCloud t (padding t) v) = 0 := by + rw [PreprocessingCloudIndex.card_paddedCloud, cloudSize_add_padding, hk] + rfl + have hs : S.card = 0 := by omega + simp only [hs, mul_zero, Nat.zero_le] + · exact SpectralCut.cut_card_ge_twice + (cloudGraphs t (padding t) (familyCloudTable H t) v) + (cloudGraphs_certificate_of_pos H certificate t v (Nat.pos_of_ne_zero hk)) + (by simpa only [Fintype.card_fin] using internalDegree_ge_eight) S (by + change 2 * S.card ≤ + Fintype.card (PreprocessingCloudIndex.PaddedCloud t (padding t) v) + omega) + +noncomputable def roundLabels (t : GraphTables.Table) + (labels : Fin (vertexCount t (padding t)) → GraphTables.Label) : + Fin t.vertices → GraphTables.Label := + CloudRounding.roundLabels + (paddedGraph (GraphTables.semantics t) (fun v => Fin (padding t v))) + (fun z => labels (vertexOrder t (padding t) z)) + +theorem soundness (H : BaseTable) + (certificate : SpectralCertificate (ExpanderTables.graph H) (1 / 100 : ℝ)) + (t : GraphTables.Table) + (labels : Fin (vertexCount t (padding t)) → GraphTables.Label) : + (GraphTables.semantics t).rejectionCount (roundLabels t labels) ≤ + (PortTables.baseGraph (regularize H t)).rejectionCount labels := by + rw [regularize, rejectionCount_ofCloudTables] + exact CloudRounding.padded_replacement_soundness (GraphTables.semantics t) + (fun v => Fin (padding t v)) (cloudGraphs t (padding t) (familyCloudTable H t)) + (cloud_expansion H certificate t) (fun z => labels (vertexOrder t (padding t) z)) + +theorem exists_rounding (H : BaseTable) + (certificate : SpectralCertificate (ExpanderTables.graph H) (1 / 100 : ℝ)) + (t : GraphTables.Table) + (labels : Fin (vertexCount t (padding t)) → GraphTables.Label) : + ∃ original : Fin t.vertices → GraphTables.Label, + (GraphTables.semantics t).rejectionCount original ≤ + (PortTables.baseGraph (regularize H t)).rejectionCount labels := + ⟨roundLabels t labels, soundness H certificate t labels⟩ + +theorem lift_rejectionCount (H : BaseTable) (t : GraphTables.Table) + (labels : Fin t.vertices → GraphTables.Label) : + (PortTables.baseGraph (regularize H t)).rejectionCount + (liftedLabel t (padding t) labels) = (GraphTables.semantics t).rejectionCount labels := + rejectionCount_liftedLabel t (padding t) (familyCloudTable H t) labels + +theorem completeness (H : BaseTable) (t : GraphTables.Table) + (h : (GraphTables.semantics t).Satisfiable) : + (PortTables.baseGraph (regularize H t)).Satisfiable := by + obtain ⟨labels, hlabels⟩ := h + refine ⟨liftedLabel t (padding t) labels, ?_⟩ + intro e + obtain ⟨z, rfl⟩ := + (Equiv.prodCongr (vertexOrder t (padding t)) (portOrder internalDegree)).surjective e + rcases z with ⟨v, p⟩ + change (PortTables.baseGraph (regularize H t)).edgeSatisfied + (liftedLabel t (padding t) labels) + (vertexOrder t (padding t) v, portOrder internalDegree p) = true + rw [regularize, edgeSatisfied_ofCloudTables] + simp only [liftedLabel, Equiv.symm_apply_apply] + have hcomplete := replacement_complete + (paddedGraph (GraphTables.semantics t) (fun v => Fin (padding t v))) + (cloudGraphs t (padding t) (familyCloudTable H t)) labels + (padded_complete (GraphTables.semantics t) (fun v => Fin (padding t v)) labels hlabels) + (v, p) + convert hcomplete using 1 + rfl + +theorem soundness_of_uniform_lower_bound (H : BaseTable) + (certificate : SpectralCertificate (ExpanderTables.graph H) (1 / 100 : ℝ)) + (t : GraphTables.Table) (k : Nat) + (lower : ∀ original : Fin t.vertices → GraphTables.Label, + k ≤ (GraphTables.semantics t).rejectionCount original) + (labels : Fin (vertexCount t (padding t)) → GraphTables.Label) : + k ≤ (PortTables.baseGraph (regularize H t)).rejectionCount labels := + (lower (roundLabels t labels)).trans (soundness H certificate t labels) + +theorem soundness_of_uniform_real_lower_bound (H : BaseTable) + (certificate : SpectralCertificate (ExpanderTables.graph H) (1 / 100 : ℝ)) + (t : GraphTables.Table) (k : ℝ) + (lower : ∀ original : Fin t.vertices → GraphTables.Label, + k ≤ ((GraphTables.semantics t).rejectionCount original : ℝ)) + (labels : Fin (vertexCount t (padding t)) → GraphTables.Label) : + k ≤ ((PortTables.baseGraph (regularize H t)).rejectionCount labels : ℝ) := + (lower (roundLabels t labels)).trans (Nat.cast_le.mpr (soundness H certificate t labels)) + +end MinUncutGames.Foundations.PCP.PreprocessingRegularSoundness + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/TableIteration.lean b/lean/OAI/Computability/MinUncut/PCP/TableIteration.lean new file mode 100644 index 0000000000000000000000000000000000000000..76781eaaa6d6bdfd84c74755116dfeda28dd6f84 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/TableIteration.lean @@ -0,0 +1,610 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.PoweringFinalConstants +import OAI.Computability.MinUncut.Machines.RawInitialMachineBudget + +namespace OAI + +namespace MinUncutGames.Foundations.PCP.TableIteration + +open RoundTables +open Target Complexity + +def run (H : BaseTable) : Nat → Input → Input := AmplificationIteration.run (step H) + +def runTables (H : BaseTable) : Nat → GraphTables.Table → GraphTables.Table := + AmplificationIteration.run (build H) + +theorem run_val (H : BaseTable) (n : Nat) (input : Input) : + (run H n input).val = runTables H n input.val := by + induction n with + | zero => rfl + | succ n ih => + change build H (run H n input).val = build H (runTables H n input.val) + rw [ih] + +def iterationCount (F : Formula) : Nat := AmplificationIteration.rounds (size (initial F)) + +def output (H : BaseTable) (F : Formula) : Input := run H (iterationCount F) (initial F) + +def outputTable (H : BaseTable) (F : Formula) : GraphTables.Table := + runTables H (iterationCount F) (RawInitialTables.table F) + +theorem output_val (H : BaseTable) (F : Formula) : (output H F).val = outputTable H F := + run_val H (iterationCount F) (initial F) + +def gapMap (H : BaseTable) (F : Formula) : Formula := FinalTableFormula.output (outputTable H F) + +opaque degreeData : {n : Nat // sizeFactor ≤ 2 ^ n} := + ⟨AmplificationIteration.rounds sizeFactor, (AmplificationIteration.rounds_large sizeFactor).le⟩ + +def polynomialDegree : Nat := degreeData.val + +theorem sizeFactor_le_power : sizeFactor ≤ 2 ^ polynomialDegree := + degreeData.property + +theorem run_completeness (H : BaseTable) (n : Nat) (input : Input) + (sat : Satisfiable input) : Satisfiable (run H n input) := + AmplificationIteration.run_preserves (step H) Satisfiable (step_completeness H) n input sat + +theorem output_completeness (H : BaseTable) (F : Formula) (sat : F.Satisfiable) : + Satisfiable (output H F) := + run_completeness H _ _ ((initial_satisfiable_iff F).mpr sat) + +theorem gapMap_completeness (H : BaseTable) (F : Formula) (sat : F.Satisfiable) : + (gapMap H F).Satisfiable := by + apply (FinalTableFormula.satisfiable_iff (outputTable H F)).mpr + rw [← output_val] + exact output_completeness H F sat + +theorem output_darts_positive (H : BaseTable) (F : Formula) : 0 < (outputTable H F).darts := by + rw [← output_val] + exact (output H F).property + +theorem gapMap_nonempty (H : BaseTable) (F : Formula) : (gapMap H F).clauses ≠ [] := + FinalTableFormula.nonempty (outputTable H F) (output_darts_positive H F) + +theorem run_size (H : BaseTable) (n : Nat) (input : Input) : + size (run H n input) ≤ sizeFactor ^ n * size input := + AmplificationIteration.run_size (step H) size sizeFactor (step_size H) n input + +theorem output_size (H : BaseTable) (F : Formula) : + size (output H F) ≤ (2 * size (initial F)) ^ polynomialDegree * size (initial F) := + AmplificationIteration.run_size_polynomial (step H) size (size_positive (initial F)) + sizeFactor_le_power (step_size H) (initial F) + +theorem initial_size_le (F : Formula) : size (initial F) ≤ 7 * (formulaBits F).length := + RawInitialMachineBudget.graph_size_bound F + +theorem output_size_le_input (H : BaseTable) (F : Formula) : + (outputTable H F).vertices + (outputTable H F).darts ≤ + (14 * (formulaBits F).length) ^ polynomialDegree * (7 * (formulaBits F).length) := by + rw [← output_val] + have h := initial_size_le F + exact (output_size H F).trans + (Nat.mul_le_mul (Nat.pow_le_pow_left (by omega) _) h) + +noncomputable def tableSizePolynomial : Polynomial Nat := + (Polynomial.C 14 * Polynomial.X) ^ polynomialDegree * (Polynomial.C 7 * Polynomial.X) + +theorem tableSizePolynomial_eval (N : Nat) : + tableSizePolynomial.eval N = (14 * N) ^ polynomialDegree * (7 * N) := by + simp only [tableSizePolynomial, Polynomial.eval_mul, Polynomial.eval_pow, + Polynomial.eval_C, Polynomial.eval_X] + +noncomputable def tableBitsPolynomial : Polynomial Nat := + (GraphTableComplexity.encodingPolynomial 64).comp tableSizePolynomial + +theorem output_bits_le (H : BaseTable) (F : Formula) : + (GraphTables.tableBits (outputTable H F)).length ≤ tableBitsPolynomial.eval (formulaBits F).length := by + rw [tableBitsPolynomial, Polynomial.eval_comp, tableSizePolynomial_eval] + exact GraphTableComplexity.bits_le_of_size_le _ (output_size_le_input H F) + +noncomputable def formulaBitsPolynomial : Polynomial Nat := + FinalTableFormula.sizePolynomial.comp tableBitsPolynomial + +theorem gapMap_bits_le (H : BaseTable) (F : Formula) : + (formulaBits (gapMap H F)).length ≤ formulaBitsPolynomial.eval (formulaBits F).length := by + rw [formulaBitsPolynomial, Polynomial.eval_comp] + exact (FinalTableFormula.formulaBits_length_le_polynomial (outputTable H F)).trans + (MachineComposition.natPolynomial_eval_mono _ (output_bits_le H F)) + +end MinUncutGames.Foundations.PCP.TableIteration + +noncomputable section +namespace MinUncutGames.Foundations.PCP.PoweringPortReindex +open PoweringWalks PoweringLabels PoweringReach PoweringTest +open SpectralReturn PoweringSoundness + +variable {V D E A : Type*} + +def wordEquiv (ports : D ≃ E) (n : Nat) : (Fin n → D) ≃ (Fin n → E) where + toFun p := fun i => ports (p i) + invFun p := fun i => ports.symm (p i) + left_inv p := by funext i; exact ports.symm_apply_apply (p i) + right_inv p := by funext i; exact ports.apply_symm_apply (p i) + +def walkEquiv (ports : D ≃ E) (n : Nat) : Walk V D n ≃ Walk V E n := + Equiv.prodCongr (Equiv.refl V) (wordEquiv ports n) + +def addressEquiv (ports : D ≃ E) (t : Nat) : PortWords D t ≃ PortWords E t where + toFun w := ⟨w.1, wordEquiv ports w.1.val w.2⟩ + invFun w := ⟨w.1, (wordEquiv ports w.1.val).symm w.2⟩ + left_inv w := by rcases w with ⟨n,p⟩; simp + right_inv w := by rcases w with ⟨n,p⟩; simp + +def labelEquiv (ports : D ≃ E) (t : Nat) : PaddedLabel E t A ≃ PaddedLabel D t A where + toFun a := fun w => a (addressEquiv ports t w) + invFun a := fun w => a ((addressEquiv ports t).symm w) + left_inv a := by funext w; simp + right_inv a := by funext w; simp + +variable (G : PortGraph V D) (H : PortGraph V E) (ports : D ≃ E) +variable (rotation : ∀ v d, H.rot (v, ports d) = + ((G.rot (v,d)).1, ports (G.rot (v,d)).2)) + +include rotation + +theorem wordEnd_map (n : Nat) (v : V) (p : Fin n → D) : + wordEnd H n v (wordEquiv ports n p) = wordEnd G n v p := by + induction n generalizing v with + | zero => rfl + | succ n ih => + simp only [wordEnd, next, wordEquiv, Equiv.coe_fn_mk, rotation] + exact ih _ _ + +theorem endpoint_map (n : Nat) (w : Walk V D n) : + endpoint H (walkEquiv ports n w) = endpoint G w := + wordEnd_map G H ports rotation n w.1 w.2 + +theorem reach_iff (t : Nat) (v u : V) : + (∃ n, n ≤ t ∧ ∃ p : Fin n → D, wordEnd G n v p = u) ↔ + (∃ n, n ≤ t ∧ ∃ p : Fin n → E, wordEnd H n v p = u) := by + constructor + · rintro ⟨n,hn,p,hp⟩ + exact ⟨n,hn,wordEquiv ports n p,(wordEnd_map G H ports rotation n v p).trans hp⟩ + · rintro ⟨n,hn,p,hp⟩ + refine ⟨n,hn,(wordEquiv ports n).symm p,?_⟩ + rw [← wordEnd_map G H ports rotation, Equiv.apply_symm_apply] + exact hp + +def ballEquiv (t : Nat) (v : V) : Ball G t v ≃ Ball H t v where + toFun u := ⟨u.val,(reach_iff G H ports rotation t v u.val).mp u.property⟩ + invFun u := ⟨u.val,(reach_iff G H ports rotation t v u.val).mpr u.property⟩ + left_inv _ := rfl + right_inv _ := rfl + +theorem wordToBall_map (t : Nat) (v : V) (w : PortWords D t) : + wordToBall H t v (addressEquiv ports t w) = + ballEquiv G H ports rotation t v (wordToBall G t v w) := by + apply Subtype.ext + exact wordEnd_map G H ports rotation w.1.val v w.2 + +def pullSelector {t : Nat} {v : V} (S : AddressSelector H t v) : + AddressSelector G t v where + address u := (addressEquiv ports t).symm + (S.address (ballEquiv G H ports rotation t v u)) + correct u := by + apply (ballEquiv G H ports rotation t v).injective + rw [← wordToBall_map, Equiv.apply_symm_apply, S.correct] + +theorem decode_pullSelector {t : Nat} {v : V} (S : AddressSelector H t v) + (a : PaddedLabel E t A) (u : Ball G t v) : + decode (pullSelector G H ports rotation S) (labelEquiv ports t a) u = + decode S a (ballEquiv G H ports rotation t v u) := by + simp [decode, pullSelector, labelEquiv] + +theorem decode_transport {t : Nat} (selectors : ∀v, AddressSelector H t v) + (a : PaddedLabel E t A) {v w : V} (hvw : v = w) + (u : Ball G t v) (u' : Ball H t w) (hu : u.val = u'.val) : + decode (pullSelector G H ports rotation (selectors v)) (labelEquiv ports t a) u = + decode (selectors w) a u' := by + subst w + rw [decode_pullSelector] + congr 1 + exact Subtype.ext hu + +theorem opinionAt_pullSelector (t : Nat) (selectors : ∀v, AddressSelector H t v) + (labels : V → PaddedLabel E t A) (fallback : A) (u v : V) : + PoweringOpinions.opinionAt G t (fun v => pullSelector G H ports rotation (selectors v)) + (fun v => labelEquiv ports t (labels v)) fallback u v = + PoweringOpinions.opinionAt H t selectors labels fallback u v := by + classical + unfold PoweringOpinions.opinionAt + split_ifs with hG hH hH + · exact decode_pullSelector G H ports rotation (selectors v) (labels v) ⟨u,hG⟩ + · exact False.elim (hH ((reach_iff G H ports rotation t v u).mp hG)) + · exact False.elim (hG ((reach_iff G H ports rotation t v u).mpr hH)) + · rfl + +theorem advanceTail_map (n : Nat) (w : Walk V D (n+1)) : + advanceTail H (walkEquiv ports (n+1) w) = + walkEquiv ports n (advanceTail G w) := by + apply Prod.ext + · change (H.rot (w.1, ports (w.2 0))).1 = (G.rot (w.1,w.2 0)).1 + rw [rotation] + · rfl + +theorem edgeAt_map (n : Nat) (w : Walk V D (n+1)) (k : Fin (n+1)) : + edgeAt H n (walkEquiv ports (n+1) w) k = + ((edgeAt G n w k).1, ports (edgeAt G n w k).2) := by + induction n with + | zero => rfl + | succ n ih => + induction k using Fin.cases with + | zero => rfl + | succ k => + simp only [edgeAt, Fin.cases_succ] + rw [advanceTail_map G H ports rotation] + exact ih _ _ + +variable (accepts : Edge V E → A → A → Bool) + +def pullAccepts : Edge V D → A → A → Bool := + fun e => accepts (e.1, ports e.2) + +theorem pathAccepts_map (n : Nat) (selectors : ∀v, AddressSelector H (n+1) v) + (w : Walk V D (n+1)) (a b : PaddedLabel E (n+1) A) : + pathAccepts G (pullAccepts ports accepts) n + (fun v => pullSelector G H ports rotation (selectors v)) w + (labelEquiv ports (n+1) a) (labelEquiv ports (n+1) b) = + pathAccepts H accepts n selectors (walkEquiv ports (n+1) w) a b := by + classical + unfold pathAccepts + congr 1 + apply propext + apply forall_congr' + intro k + have ht := decode_transport G H ports rotation selectors a rfl + (tailFromStart G n w k) (tailFromStart H n (walkEquiv ports (n+1) w) k) + (congrArg Prod.fst (edgeAt_map G H ports rotation n w k)).symm + have hh := decode_transport G H ports rotation selectors b + (endpoint_map G H ports rotation (n+1) w).symm + (headFromEnd G n w k) (headFromEnd H n (walkEquiv ports (n+1) w) k) + (by + change (G.rot (edgeAt G n w k)).1 = + (H.rot (edgeAt H n (walkEquiv ports (n+1) w) k)).1 + rw [edgeAt_map G H ports rotation, rotation]) + rw [ht, hh] + simp only [pullAccepts, edgeAt_map G H ports rotation] + rfl + +def dartEquiv (n : Nat) : Dart V D n ≃ Dart V E n := + Equiv.prodCongr (Equiv.refl Bool) (walkEquiv ports (n+1)) + +theorem edgeSatisfied_map (n : Nat) (selectors : ∀v, AddressSelector H (n+1) v) + (labels : V → PaddedLabel E (n+1) A) (e : Dart V D n) : + (poweredGraph G (pullAccepts ports accepts) n + (fun v => pullSelector G H ports rotation (selectors v))).edgeSatisfied + (fun v => labelEquiv ports (n+1) (labels v)) e = + (poweredGraph H accepts n selectors).edgeSatisfied labels (dartEquiv ports n e) := by + rcases e with ⟨direction,w⟩ + rw [poweredGraph_edgeSatisfied] + change _ = (poweredGraph H accepts n selectors).edgeSatisfied labels + (direction, walkEquiv ports (n+1) w) + rw [poweredGraph_edgeSatisfied, endpoint_map G H ports rotation] + exact pathAccepts_map G H ports rotation accepts n selectors w _ _ + +theorem rejectionCount_map [Fintype V] [Fintype D] [Fintype E] + (n : Nat) (selectors : ∀v, AddressSelector H (n+1) v) + (labels : V → PaddedLabel E (n+1) A) : + (poweredGraph G (pullAccepts ports accepts) n + (fun v => pullSelector G H ports rotation (selectors v))).rejectionCount + (fun v => labelEquiv ports (n+1) (labels v)) = + (poweredGraph H accepts n selectors).rejectionCount labels := by + classical + unfold ConstraintGraph.rejectionCount + apply Finset.card_bij (fun e _ => dartEquiv ports n e) + · intro e he + rw [ConstraintGraph.mem_rejectedDarts, ← edgeSatisfied_map G H ports rotation] + exact (ConstraintGraph.mem_rejectedDarts _ _ _).mp he + · intro e _ f _ h + exact (dartEquiv ports n).injective h + · intro e he + refine ⟨(dartEquiv ports n).symm e, ?_, (dartEquiv ports n).apply_symm_apply e⟩ + rw [ConstraintGraph.mem_rejectedDarts, edgeSatisfied_map G H ports rotation, + Equiv.apply_symm_apply] + exact (ConstraintGraph.mem_rejectedDarts _ _ _).mp he + +theorem satisfiable_iff (n : Nat) (selectors : ∀v, AddressSelector H (n+1) v) : + (poweredGraph G (pullAccepts ports accepts) n + (fun v => pullSelector G H ports rotation (selectors v))).Satisfiable ↔ + (poweredGraph H accepts n selectors).Satisfiable := by + constructor + · rintro ⟨labels,hlabels⟩ + refine ⟨fun v => (labelEquiv ports (n+1)).symm (labels v), ?_⟩ + intro e + obtain ⟨e,rfl⟩ := (dartEquiv ports n).surjective e + rw [← edgeSatisfied_map G H ports rotation] + simpa only [Equiv.apply_symm_apply] using hlabels e + · rintro ⟨labels,hlabels⟩ + refine ⟨fun v => labelEquiv ports (n+1) (labels v), ?_⟩ + intro e + rw [edgeSatisfied_map G H ports rotation] + exact hlabels _ + +theorem pullReverse + (reverse_accepts : ∀ e a b, accepts (H.rot e) b a = accepts e a b) + (e : Edge V D) (a b : A) : + pullAccepts ports accepts (G.rot e) b a = pullAccepts ports accepts e a b := by + simpa only [pullAccepts, rotation] using reverse_accepts (e.1,ports e.2) a b + +theorem base_edgeSatisfied_map + (reverse_accepts : ∀ e a b, accepts (H.rot e) b a = accepts e a b) + (assignment : V → A) (e : Edge V D) : + (baseGraph G (pullAccepts ports accepts) + (pullReverse G H ports rotation accepts reverse_accepts)).edgeSatisfied assignment e = + (baseGraph H accepts reverse_accepts).edgeSatisfied assignment (e.1,ports e.2) := by + change accepts (e.1,ports e.2) (assignment e.1) (assignment (G.rot e).1) = + accepts (e.1,ports e.2) (assignment e.1) (assignment (H.rot (e.1,ports e.2)).1) + rw [rotation] + +theorem base_rejectionCount_map [Fintype V] [Fintype D] [Fintype E] + (reverse_accepts : ∀ e a b, accepts (H.rot e) b a = accepts e a b) + (assignment : V → A) : + (baseGraph G (pullAccepts ports accepts) + (pullReverse G H ports rotation accepts reverse_accepts)).rejectionCount assignment = + (baseGraph H accepts reverse_accepts).rejectionCount assignment := by + classical + let e : Edge V D ≃ Edge V E := Equiv.prodCongr (Equiv.refl V) ports + have edgeEq (x : Edge V D) := + base_edgeSatisfied_map G H ports rotation accepts reverse_accepts assignment x + unfold ConstraintGraph.rejectionCount + apply Finset.card_bij (fun x _ => e x) + · intro x hx + rw [ConstraintGraph.mem_rejectedDarts] + change (baseGraph H accepts reverse_accepts).edgeSatisfied assignment (x.1,ports x.2) = false + rw [← edgeEq] + exact (ConstraintGraph.mem_rejectedDarts _ _ _).mp hx + · intro x _ y _ h + exact e.injective h + · intro y hy + refine ⟨e.symm y, ?_, e.apply_symm_apply y⟩ + rw [ConstraintGraph.mem_rejectedDarts, edgeEq] + change (baseGraph H accepts reverse_accepts).edgeSatisfied assignment (e (e.symm y)) = false + rw [e.apply_symm_apply] + exact (ConstraintGraph.mem_rejectedDarts _ _ _).mp hy + +omit rotation in + +theorem uniform_count_gap + [Fintype V] [Fintype D] [Fintype E] [Nonempty V] [Nonempty D] + [Fintype A] [Nonempty A] + (G : PortGraph V D) (H : PortGraph V E) (ports : (Bool × D) ≃ E) + (rotation : ∀ v d, H.rot (v, ports d) = + (((lazyGraph G).rot (v,d)).1, ports ((lazyGraph G).rot (v,d)).2)) + (lambda : ℝ) (certificate : SpectralCertificate (lazyGraph G) lambda) + (accepts : Edge V E → A → A → Bool) + (reverse_accepts : ∀ e a b, accepts (H.rot e) b a = accepts e a b) + (M : Nat) (hM : 1 ≤ M) + (selectors : ∀v, AddressSelector H (2*center (Fintype.card A) M+1) v) + (epsilon : ℝ) (hepsilon : 0 ≤ epsilon) + (hgap : ∀ assignment : V → A, + epsilon * (Fintype.card (Edge V E) : ℝ) ≤ + ((baseGraph H accepts reverse_accepts).rejectionCount assignment : ℝ)) + (labels : V → PaddedLabel E (2*center (Fintype.card A) M+1) A) : + (gain (Fintype.card A) M lambda * + min epsilon (1 / ((2*center (Fintype.card A) M+1 : Nat) : ℝ))) * + (Fintype.card (Dart V E (2*center (Fintype.card A) M)) : ℝ) ≤ + ((poweredGraph H accepts (2*center (Fintype.card A) M) selectors).rejectionCount labels : ℝ) := by + have hbase : ∀ assignment : V → A, + epsilon * (Fintype.card (Edge V (Bool × D)) : ℝ) ≤ + ((baseGraph (lazyGraph G) (pullAccepts ports accepts) + (pullReverse (lazyGraph G) H ports rotation accepts reverse_accepts)).rejectionCount assignment : ℝ) := by + intro assignment + rw [base_rejectionCount_map (lazyGraph G) H ports rotation, + Fintype.card_congr (Equiv.prodCongr (Equiv.refl V) ports)] + exact hgap assignment + have bound := PoweringGap.uniform_count_gap G lambda certificate + (pullAccepts ports accepts) + (pullReverse (lazyGraph G) H ports rotation accepts reverse_accepts) M hM + (fun v => pullSelector (lazyGraph G) H ports rotation (selectors v)) + epsilon hepsilon hbase (fun v => labelEquiv ports _ (labels v)) + rw [rejectionCount_map (lazyGraph G) H ports rotation, + Fintype.card_congr (dartEquiv (V := V) ports (2*center (Fintype.card A) M))] at bound + exact bound + +omit rotation in + +theorem lazy_table_uniform_count_gap {vertices d : Nat} + (input : PortTables.Table vertices d) (hv : 0 < vertices) (hd : 0 < d) + (lambda : ℝ) + (certificate : SpectralCertificate (lazyGraph (PortTables.portGraph input)) lambda) + (M : Nat) (hM : 1 ≤ M) (epsilon : ℝ) (hepsilon : 0 ≤ epsilon) + (hgap : ∀ assignment : Fin vertices → Fin 64, + epsilon * (Fintype.card (Fin vertices × Fin (2*d)) : ℝ) ≤ + ((PortTables.baseGraph (PreprocessingOverlayTables.lazy input)).rejectionCount assignment : ℝ)) : + ∀ labels : PoweringTableSemantics.EncodedLabeling vertices (2*d) (2*center 64 M), + (gain 64 M lambda * min epsilon (1 / ((2*center 64 M+1 : Nat) : ℝ))) * + ((PoweringTables.table (PreprocessingOverlayTables.lazy input) (2*center 64 M)).darts : ℝ) ≤ + ((GenericGraphTables.semantics + (PoweringTables.table (PreprocessingOverlayTables.lazy input) (2*center 64 M))).rejectionCount labels : ℝ) := by + let : Nonempty (Fin vertices) := ⟨⟨0,hv⟩⟩ + let : Nonempty (Fin d) := ⟨⟨0,hd⟩⟩ + apply PoweringTableSemantics.uniform_count_gap + intro labels + have hrot : ∀ v p, + (PortTables.portGraph (PreprocessingOverlayTables.lazy input)).rot + (v, PreprocessingOverlayTables.lazyPorts d p) = + (((lazyGraph (PortTables.portGraph input)).rot (v,p)).1, + PreprocessingOverlayTables.lazyPorts d + ((lazyGraph (PortTables.portGraph input)).rot (v,p)).2) := by + intro v p + rw [PreprocessingTableSpectral.lazy_portGraph] + exact GraphTransport.reindex_rot _ (Equiv.refl _) _ v p + have bound := uniform_count_gap (PortTables.portGraph input) + (PortTables.portGraph (PreprocessingOverlayTables.lazy input)) + (PreprocessingOverlayTables.lazyPorts d) hrot lambda certificate + (PortTables.accepts (PreprocessingOverlayTables.lazy input)) + (PortTables.accepts_rotation (PreprocessingOverlayTables.lazy input)) M hM + (PoweringAddresses.finitePortSelector + (PortTables.portGraph (PreprocessingOverlayTables.lazy input)) _) epsilon hepsilon + hgap + simp only [PortTables.Label, GraphTables.Label, Fintype.card_fin] at bound + exact bound labels + +omit rotation in + +theorem lazy_table_uniform_count_gap_at {vertices d : Nat} + (input : PortTables.Table vertices d) (hv : 0 < vertices) (hd : 0 < d) + (lambda : ℝ) + (certificate : SpectralCertificate (lazyGraph (PortTables.portGraph input)) lambda) + (M : Nat) (hM : 1 ≤ M) (n : Nat) (hn : n = 2*center 64 M) + (epsilon : ℝ) (hepsilon : 0 ≤ epsilon) + (hgap : ∀ assignment : Fin vertices → Fin 64, + epsilon * (Fintype.card (Fin vertices × Fin (2*d)) : ℝ) ≤ + ((PortTables.baseGraph (PreprocessingOverlayTables.lazy input)).rejectionCount + assignment : ℝ)) : + ∀ labels : PoweringTableSemantics.EncodedLabeling vertices (2*d) n, + (gain 64 M lambda * min epsilon (1 / ((n+1 : Nat) : ℝ))) * + ((PoweringTables.table (PreprocessingOverlayTables.lazy input) n).darts : ℝ) ≤ + ((GenericGraphTables.semantics + (PoweringTables.table (PreprocessingOverlayTables.lazy input) n)).rejectionCount + labels : ℝ) := by + subst n + exact lazy_table_uniform_count_gap input hv hd lambda certificate M hM + epsilon hepsilon hgap + +end MinUncutGames.Foundations.PCP.PoweringPortReindex + +end +namespace MinUncutGames.Foundations.PCP.RoundTableGap + +open RoundTables +open PoweringWalks SpectralReturn + +variable (H : BaseTable) + (certificate : SpectralCertificate (ExpanderTables.graph H) (1 / 100 : ℝ)) + +include certificate + +theorem powered_count_gap (input : Input) + (labeling : Fin (powered H input.val).vertices → Fin alphabet) : + RoundGap.poweredLower (gap input) * ((powered H input.val).darts : ℝ) ≤ + ((GenericGraphTables.semantics (powered H input.val)).rejectionCount labeling : ℝ) := by + let old := PreprocessingOverlayTables.overlay + (PreprocessingTables.padded H input.val) (PreprocessingTables.overlayFamily H input.val) + have hd : 0 < (PreprocessingRegularTables.internalDegree + 1) + + PreprocessingRegularTables.internalDegree := by omega + let : Nonempty (Fin ((PreprocessingRegularTables.internalDegree + 1) + + PreprocessingRegularTables.internalDegree)) := ⟨⟨0, hd⟩⟩ + have spectral : SpectralCertificate (lazyGraph (PortTables.portGraph old)) (31 / 32 : ℝ) := + LazySpectral.lazy_certificate_31_32 (PortTables.portGraph old) + (PreprocessingGuarantees.overlay_certificate H certificate input.val) + have lower := PreprocessingGuarantees.gap_transfer_real H certificate input.val input.property + (gap input) (gap_nonnegative input) + (by simpa only [Fintype.card_fin] using + ((GraphTables.semantics input.val).le_gap_iff (gap input)).mp le_rfl) + have hs : (0 : ℝ) < Preprocessing.sizeFactor := Nat.cast_pos.mpr Preprocessing.sizeFactor_positive + have hn : walkParameter = 2 * PoweringSoundness.center 64 FinalConstants.windowHalf := + walkParameter_eq + have bound := PoweringPortReindex.lazy_table_uniform_count_gap_at old + (PreprocessingTables.vertices_positive input.val) hd (31 / 32) spectral + FinalConstants.windowHalf FinalConstants.windowHalf_positive walkParameter hn + (gap input / Preprocessing.sizeFactor) (div_nonneg (gap_nonnegative input) hs.le) + lower labeling + have hw : walkParameter + 1 = FinalConstants.walkLength := by + rw [walkParameter_eq] + rfl + simpa only [RoundGap.poweredLower, PoweringFinalConstants.card_alphabet, + hw, FinalConstants.cap, powered, PreprocessingTables.preprocess, old] using! bound + +theorem build_count_gap (input : Input) + (labeling : Fin (build H input.val).vertices → GraphTables.Label) : + min (2 * gap input) FinalConstants.cap * ((build H input.val).darts : ℝ) ≤ + ((GraphTables.semantics (build H input.val)).rejectionCount labeling : ℝ) := by + have h := AlphabetTableBounds.gap_transfer_real alphabet_positive (powered H input.val) + (RoundGap.poweredLower (gap input)) + (RoundGap.poweredLower_nonnegative (gap input) (gap_nonnegative input)) + (powered_count_gap H certificate input) labeling + have scalar : min (2 * gap input) FinalConstants.cap ≤ + RoundGap.poweredLower (gap input) / 12288 := by + simpa only [RoundGap.poweredLower, FinalConstants.cap, FinalConstants.walkLength, + PoweringFinalConstants.center_eq] using + PoweringFinalConstants.composed_scaled_gap (gap input) (gap_nonnegative input) + exact (mul_le_mul_of_nonneg_right scalar (Nat.cast_nonneg _)).trans h + +theorem step_gap (input : Input) : + min (2 * gap input) FinalConstants.cap ≤ gap (step H input) := by + apply ((GraphTables.semantics (step H input).val).le_gap_iff _).mpr + simp only [step] + intro labeling + change min (2 * gap input) FinalConstants.cap * + (Fintype.card (Fin (build H input.val).darts) : ℝ) ≤ + ((GraphTables.semantics (build H input.val)).rejectionCount labeling : ℝ) + rw [Fintype.card_fin] + exact build_count_gap H certificate input labeling + +end MinUncutGames.Foundations.PCP.RoundTableGap + +namespace MinUncutGames.Foundations.PCP.TableGapReduction + +open RoundTables TableIteration SpectralReturn Target + +variable (H : BaseTable) + (certificate : SpectralCertificate (ExpanderTables.graph H) (1 / 100 : ℝ)) + +include certificate + +theorem run_gap (n : Nat) (input : Input) : + min (2 ^ n * gap input) FinalConstants.cap ≤ gap (TableIteration.run H n input) := + AmplificationIteration.run_gap (step H) gap FinalConstants.cap FinalConstants.cap_positive.le + (RoundTableGap.step_gap H certificate) n input + +theorem output_gap (F : Formula) (unsat : ¬ F.Satisfiable) : + FinalConstants.cap ≤ gap (TableIteration.output H F) := by + have hu : ¬ Satisfiable (initial F) := fun sat => unsat ((initial_satisfiable_iff F).mp sat) + exact AmplificationIteration.run_reaches_cap (step H) gap FinalConstants.cap + FinalConstants.cap_positive.le FinalConstants.cap_le_one (RoundTableGap.step_gap H certificate) + (size (initial F)) (initial F) (gap_nonnegative (initial F)) + (one_le_size_mul_gap (initial F) hu) + +theorem output_satisfiable_iff (F : Formula) : + Satisfiable (TableIteration.output H F) ↔ F.Satisfiable := by + constructor + · intro sat + by_contra unsat + have bound := output_gap H certificate F unsat + rw [(gap_eq_zero_iff (TableIteration.output H F)).mpr sat] at bound + exact (not_le_of_gt FinalConstants.cap_positive) bound + · exact TableIteration.output_completeness H F + +theorem gapMap_satisfiable_iff (F : Formula) : (gapMap H F).Satisfiable ↔ F.Satisfiable := by + rw [gapMap, FinalTableFormula.satisfiable_iff, ← output_val] + exact output_satisfiable_iff H certificate F + +theorem output_count_gap (F : Formula) (unsat : ¬ F.Satisfiable) + (labeling : Fin (outputTable H F).vertices → GraphTables.Label) : + (outputTable H F).darts ≤ FinalConstants.walkLength * + (GraphTables.semantics (outputTable H F)).rejectionCount labeling := by + have hp := output_darts_positive H F + let : Nonempty (Fin (outputTable H F).darts) := ⟨⟨0, hp⟩⟩ + have bound := output_gap H certificate F unsat + change FinalConstants.cap ≤ (GraphTables.semantics (TableIteration.output H F).val).gap at bound + rw [output_val] at bound + have count := ((GraphTables.semantics (outputTable H F)).le_gap_iff FinalConstants.cap).mp bound labeling + simp only [Fintype.card_fin] at count + have ht : (0 : ℝ) < FinalConstants.walkLength := Nat.cast_pos.mpr FinalConstants.walkLength_positive + have divided : ((outputTable H F).darts : ℝ) / FinalConstants.walkLength ≤ + ((GraphTables.semantics (outputTable H F)).rejectionCount labeling : ℝ) := by + simpa only [FinalConstants.cap, one_div_mul_eq_div] using count + have multiplied := (div_le_iff₀ ht).mp divided + exact_mod_cast (show ((outputTable H F).darts : ℝ) ≤ (FinalConstants.walkLength : ℝ) * + ((GraphTables.semantics (outputTable H F)).rejectionCount labeling : ℝ) by + simpa only [mul_comm] using multiplied) + +theorem gapMap_clauseGap (F : Formula) (unsat : ¬ F.Satisfiable) : + Hastad.SourceGap.ClauseGap (gapMap H F) PCPIteration.finalClauseGap := + FinalTableFormula.clauseGap (outputTable H F) (output_darts_positive H F) + (output_count_gap H certificate F unsat) + +omit certificate in +theorem finalClauseGap_le_one : PCPIteration.finalClauseGap ≤ 1 := by + have hw : (1 : ℚ) ≤ (FinalConstants.walkLength : ℚ) := by + exact_mod_cast FinalConstants.walkLength_positive + have hd : (0 : ℚ) < 40960 * (FinalConstants.walkLength : ℚ) := by positivity + rw [PCPIteration.finalClauseGap, div_le_one hd] + linarith + +end MinUncutGames.Foundations.PCP.TableGapReduction + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/TupleBody.lean b/lean/OAI/Computability/MinUncut/PCP/TupleBody.lean new file mode 100644 index 0000000000000000000000000000000000000000..8dfa792a2185b7f0530c2d285d9fd829bad12546 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/TupleBody.lean @@ -0,0 +1,785 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.HeaderAccumulate +import OAI.Computability.MinUncut.PCP.LoopOrder + +namespace OAI + +section +namespace MinUncutGames.Foundations.Hastad.SourceTupleBody + +open Turing Complexity SourceContexts SourceOccurrences SourceLocalSignature +open SourceRuntimeModel SourceTupleTape + +abbrev SlotCount (u : Nat) := (slotContextEncoding u).size +abbrev QueryCount (u D : Nat) := (testTapeEncoding u D).size +abbrev Query (u D : Nat) := SourceQueryLoop.Query u D + +inductive Label (u D : Nat) (Extra : Type) + | prepare (label : SourceContextPrepare.Label u) + | seedZero + | clauseRank (label : MachineHorner.Label u) + | rightBase (label : SourceBasePhase.Label) + | clearClauseRank + | select (index : Fin (SlotCount u + 1)) + | variableRank (index : Fin (SlotCount u)) (label : MachineHorner.Label u) + | leftBase (index : Fin (SlotCount u)) (label : SourceBasePhase.Label) + | query (index : Fin (SlotCount u)) (label : SourceQueryLoop.Label u D (QueryCount u D)) + | clearSlotRank (index : Fin (SlotCount u)) + | clearLeft (index : Fin (SlotCount u)) + | clearRight | clearZero + | clearContext (label : SourceContextClear.Label u (BodyExtra Extra)) + | reset + deriving DecidableEq, Fintype + +variable {u D : Nat} {Extra : Type} + +def selected (index : Fin (SlotCount u)) : SlotContext u := + (slotContextEncoding u).code.symm index + +def main : Label u D Extra := .prepare (.inl (SourceContextLoad.labelAt 0)) + +def framed {K Λ Λ' σ τ S : Type} {Γ : K → Type} + (e : σ × τ ≃ S) (labels : Λ → Λ') (exit : Option Λ') (q : TM2.Stmt Γ Λ σ) : + TM2.Stmt Γ Λ' S := + MachineControl.statement id e (MachineStateFrame.statement labels exit q) + +def framedConfiguration {K Λ Λ' σ τ S : Type} {Γ : K → Type} + (e : σ × τ ≃ S) (labels : Λ → Λ') (exit : Option Λ') (ambient : τ) + (c : TM2.Cfg Γ Λ σ) : TM2.Cfg Γ Λ' S := + MachineControl.configuration id e (MachineStateFrame.configuration labels exit ambient c) + +section Frame + +variable {K Λ Λ' σ τ S : Type} {Γ : K → Type} [DecidableEq K] + +theorem framed_stepAux (e : σ × τ ≃ S) (labels : Λ → Λ') (exit : Option Λ') + (q : TM2.Stmt Γ Λ σ) (state : σ) (ambient : τ) (tapes : ∀ k, List (Γ k)) : + TM2.stepAux (framed e labels exit q) (e (state, ambient)) tapes = + framedConfiguration e labels exit ambient (TM2.stepAux q state tapes) := by + rw [framed, MachineControl.stepAux_simulation, MachineStateFrame.stepAux_simulation] + rfl + +theorem framed_step (e : σ × τ ≃ S) (labels : Λ → Λ') (exit : Option Λ') (ambient : τ) + (source : Λ → TM2.Stmt Γ Λ σ) (target : Λ' → TM2.Stmt Γ Λ' S) + (atLabels : ∀ l, target (labels l) = framed e labels exit (source l)) + (a b : TM2.Cfg Γ Λ σ) (h : TM2.step source a = some b) : + TM2.step target (framedConfiguration e labels exit ambient a) = + some (framedConfiguration e labels exit ambient b) := by + rcases a with ⟨label, state, tapes⟩ + cases label with + | none => cases h + | some l => + change some (TM2.stepAux (source l) state tapes) = some b at h + cases Option.some.inj h + change some (TM2.stepAux (target (labels l)) (e (state, ambient)) tapes) = _ + rw [atLabels, framed_stepAux] + +def framedExecution (e : σ × τ ≃ S) (labels : Λ → Λ') (exit : Option Λ') (ambient : τ) + (source : Λ → TM2.Stmt Γ Λ σ) (target : Λ' → TM2.Stmt Γ Λ' S) + (atLabels : ∀ l, target (labels l) = framed e labels exit (source l)) + {a b : TM2.Cfg Γ Λ σ} {budget : Nat} + (run : StateTransition.EvalsToInTime (TM2.step source) a (some b) budget) : + StateTransition.EvalsToInTime (TM2.step target) + (framedConfiguration e labels exit ambient a) + (some (framedConfiguration e labels exit ambient b)) budget := + MachineComposition.liftExecutionInTime _ _ (framedConfiguration e labels exit ambient) + (framed_step e labels exit ambient source target atLabels) run + +end Frame + +variable [DecidableEq Extra] + +def finish (exit : Option (Label u D Extra)) : + TM2.Stmt (fun _ : Arena u Extra => Bool) (Label u D Extra) (State u D) := + match exit with + | none => .halt + | some label => .goto fun _ => label + +def drainProgram (source : Arena u Extra) : + Unit → TM2.Stmt (fun _ : Arena u Extra => Bool) Unit SourceContextPrepare.LoadState := + fun _ => MachineDrain.drain source () none + +def drainStatement (source : Arena u Extra) (label : Label u D Extra) + (exit : Option (Label u D Extra)) : + TM2.Stmt (fun _ : Arena u Extra => Bool) (Label u D Extra) (State u D) := + MachineStateFrame.statement (fun _ : Unit => label) exit (drainProgram source ()) + +def selectState (initialQuery : Query u D) (index : Fin (SlotCount u)) + (state : State u D) : State u D := + (state.1, (state.2.1, (state.2.2.1, + ((({state.2.2.1 with selected := selected index}, initialQuery), none), state.2.2.2.2)))) + +def program (initialQuery : Query u D) (exit : Option (Label u D Extra)) : + Label u D Extra → TM2.Stmt (fun _ : Arena u Extra => Bool) (Label u D Extra) (State u D) + | .prepare label => MachineSubroutine.statement .prepare (some .seedZero) + (SourceContextPrepare.program label) + | .seedZero => .push (workTape .zero) (fun _ => false) (.goto fun _ => .clauseRank .start) + | .clauseRank label => framed (arithmeticStateEquiv u D) .clauseRank + (some (.rightBase .seed)) (SourceRankPhase.program clauseRankSlots label) + | .rightBase label => framed (arithmeticStateEquiv u D) .rightBase + (some .clearClauseRank) (SourceBasePhase.program (baseSlots true) (2 ^ (8 ^ u)) label) + | .clearClauseRank => drainStatement (workTape .rank) .clearClauseRank + (some (.select ⟨0, by omega⟩)) + | .select index => + if h : index.val < SlotCount u then + .load (selectState initialQuery ⟨index.val, h⟩) + (.goto fun _ => .variableRank ⟨index.val, h⟩ .start) + else .goto fun _ => .clearRight + | .variableRank index label => framed (arithmeticStateEquiv u D) (.variableRank index) + (some (.leftBase index .seed)) + (SourceRankPhase.program (variableRankSlots (selected index)) label) + | .leftBase index label => framed (arithmeticStateEquiv u D) (.leftBase index) + (some (.query index (.load ⟨0, by omega⟩))) + (SourceBasePhase.program (baseSlots false) (2 ^ (2 ^ u)) label) + | .query index label => framed (queryStateEquiv u D) (.query index) + (some (.clearSlotRank index)) + (SourceQueryLoop.statement u D (QueryCount u D) + (SourceLoopOrder.rankedQuery u D initialQuery) queryLayout id none label) + | .clearSlotRank index => drainStatement (workTape .rank) (.clearSlotRank index) + (some (.clearLeft index)) + | .clearLeft index => drainStatement (workTape .leftBase) (.clearLeft index) + (some (.select ⟨index.val + 1, by omega⟩)) + | .clearRight => drainStatement (workTape .rightBase) .clearRight (some .clearZero) + | .clearZero => drainStatement (workTape .zero) .clearZero + (some (.clearContext SourceContextClear.main)) + | .clearContext label => MachineStateFrame.statement .clearContext (some .reset) + (SourceContextClear.program label) + | .reset => .load (fun _ => canonicalState initialQuery) (finish exit) + +theorem reset_step (initialQuery : Query u D) (exit : Option (Label u D Extra)) + (state : State u D) (tapes : Arena u Extra → List Bool) : + TM2.step (program initialQuery exit) ⟨some .reset, state, tapes⟩ = + some ⟨exit, canonicalState initialQuery, tapes⟩ := by + cases exit <;> rfl + +def resetInTime (initialQuery : Query u D) (exit : Option (Label u D Extra)) + (state : State u D) (tapes : Arena u Extra → List Bool) : + StateTransition.EvalsToInTime (TM2.step (program initialQuery exit)) + ⟨some .reset, state, tapes⟩ (some ⟨exit, canonicalState initialQuery, tapes⟩) 1 where + steps := 1 + evals_in_steps := reset_step initialQuery exit state tapes + steps_le_m := Nat.le_refl _ + +structure Ready (F : Target.Formula) (c : ClauseContext F u) + (base : Arena u Extra → List Bool) : Prop where + formula : base .formula = formulaBits F + current : ∀ j, base (.current j) = encodeWord (c j).val + index : base .index = [] + work : base .work = [] + scratch : base .scratch = [] + copyScratch : base .copyScratch = [] + fields : ∀ j s, base (.field j s) = [] + variableCount : base variableHeader = encodeWord F.«variables» + clauseCount : base clauseHeader = encodeWord F.clauses.length + leftBlock : base (workTape .leftBlock) = encodeWord (2 ^ (2 ^ u) * F.«variables» ^ u) + dummy : base (workTape .dummy) = + encodeWord (F.«variables» ^ u * 2 ^ (2 ^ u) + F.clauses.length ^ u * 2 ^ (8 ^ u)) + rank : base (workTape .rank) = [] + rightBase : base (workTape .rightBase) = [] + leftBase : base (workTape .leftBase) = [] + zero : base (workTape .zero) = [] + accA : base (workTape .accA) = [] + accB : base (workTape .accB) = [] + counter : base (workTape .counter) = [] + arithScratch : base (workTape .arithScratch) = [] + coefficient : base (workTape .coefficient) = [] + queryTemporary : base (workTape .queryTemporary) = [] + queryScratch : base (workTape .queryScratch) = [] + +def contextSignature (F : Target.Formula) (c : ClauseContext F u) : Signature u := + ofContext F c (fun _ => .first) + +def workingState (F : Target.Formula) (c : ClauseContext F u) + (signature : Signature u) (query : Query u D) : State u D := + SourceContextPrepare.finalState F c (fun _ => .first) + (((signature, query), none), (((), ()), none)) + +@[simp] theorem workingState_loader (F : Target.Formula) (c : ClauseContext F u) + (signature : Signature u) (query : Query u D) : + (((), none), (workingState F c signature query).2) = workingState F c signature query := rfl + +def arithmeticMetadata (F : Target.Formula) (c : ClauseContext F u) + (signature : Signature u) (query : Query u D) : ArithmeticMetadata u D := + (((), none), (MachineFieldProfile.normalState + (MachineFieldProfile.equalityProfile (SourceProfileBridge.nameWords F c)), + (contextSignature F c, ((signature, query), none)))) + +def queryMetadata (F : Target.Formula) (c : ClauseContext F u) : QueryMetadata u := + (((), none), (MachineFieldProfile.normalState + (MachineFieldProfile.equalityProfile (SourceProfileBridge.nameWords F c)), + (contextSignature F c, (((), ()), none)))) + +@[simp] theorem arithmeticState_working (F : Target.Formula) (c : ClauseContext F u) + (signature : Signature u) (query : Query u D) : + arithmeticStateEquiv u D ((((), ()), none), arithmeticMetadata F c signature query) = + workingState F c signature query := rfl + +@[simp] theorem queryState_working (F : Target.Formula) (c : ClauseContext F u) + (signature : Signature u) (query : Query u D) : + queryStateEquiv u D (((signature, query), none), queryMetadata F c) = + workingState F c signature query := rfl + +@[simp] theorem select_workingState (F : Target.Formula) (c : ClauseContext F u) + (index : Fin (SlotCount u)) (initialQuery query : Query u D) (signature : Signature u) : + selectState initialQuery index (workingState F c signature query) = + workingState F c (ofContext F c (selected index)) initialQuery := rfl + +def rightValue (F : Target.Formula) (c : ClauseContext F u) : Nat := + SourceAddressDescriptors.baseValue F u c (sampledVariables F c (fun _ => .first)) 1 + +def variableRank (F : Target.Formula) (c : ClauseContext F u) (index : Fin (SlotCount u)) : Nat := + ((variableEncoding F u).code (sampledVariables F c (selected index))).val + +def leftValue (F : Target.Formula) (c : ClauseContext F u) (index : Fin (SlotCount u)) : Nat := + SourceAddressDescriptors.baseValue F u c (sampledVariables F c (selected index)) 0 + +noncomputable def slotBudget (F : Target.Formula) (c : ClauseContext F u) + (index : Fin (SlotCount u)) : Nat := + 1 + (MachineHorner.timePolynomial u).eval F.«variables» + + (SourceBasePhase.timePolynomial (2 ^ (2 ^ u))).eval + (SourceBasePhase.operandLength (variableRank F c index) 0) + + (QueryCount u D * (9 * nBits F u + 21) + 1) + + (variableRank F c index + 2) + (leftValue F c index + 2) + +noncomputable def preparePhase (F : Target.Formula) (c : ClauseContext F u) + (initialQuery : Query u D) (exit : Option (Label u D Extra)) + (base : Arena u Extra → List Bool) + (hformula : base .formula = formulaBits F) + (hcurrent : ∀ j, base (.current j) = encodeWord (c j).val) + (hindex : base .index = []) (hwork : base .work = []) + (hscratch : base .scratch = []) (hcopy : base .copyScratch = []) + (hfields : ∀ p : Position u, base (SourceSignaturePrepare.variableField p) = []) : + StateTransition.EvalsToInTime (TM2.step (program initialQuery exit)) + ⟨some main, canonicalState initialQuery, base⟩ + (some ⟨some .seedZero, + SourceContextPrepare.finalState F c (fun _ => .first) + ((((canonicalSignature u, initialQuery), none), (((), ()), none))), + SourceContextLoad.stageTapes F c base u⟩) + ((u * (10 * (formulaBits F).length + 20) + 1) + + (SourceSignaturePrepare.Width u * SourceSignaturePrepare.Width u * + (5 * (formulaBits F).length + 6) + 2)) := by + let run := SourceContextPrepare.prepareInTime (τ := QueryState u D × ArithmeticState) F c (fun _ => .first) base hformula hcurrent + hindex hwork hscratch hcopy hfields (fun _ _ => false) (canonicalSignature u) rfl + ((((canonicalSignature u, initialQuery), none), (((), ()), none))) + exact MachineSubroutine.execution .prepare (some .seedZero) SourceContextPrepare.program + (program initialQuery exit) (fun _ => rfl) run + +def seedZeroPhase (initialQuery : Query u D) (exit : Option (Label u D Extra)) + (state : State u D) (base : Arena u Extra → List Bool) (hzero : base (workTape .zero) = []) : + StateTransition.EvalsToInTime (TM2.step (program initialQuery exit)) + ⟨some .seedZero, state, base⟩ + (some ⟨some (.clauseRank .start), state, + Function.update base (workTape .zero) (encodeWord 0)⟩) 1 where + steps := 1 + evals_in_steps := by + change some (TM2.stepAux (program initialQuery exit .seedZero) state base) = _ + simp only [program, TM2.stepAux, hzero] + rfl + steps_le_m := Nat.le_refl _ + +def drainPhase (initialQuery : Query u D) (exit : Option (Label u D Extra)) + (source : Arena u Extra) (entry : Label u D Extra) (next : Option (Label u D Extra)) + (atEntry : program initialQuery exit entry = drainStatement source entry next) + (base : Arena u Extra → List Bool) + (metadata : SourceSignaturePrepare.State u (QueryState u D × ArithmeticState)) + (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step (program initialQuery exit)) + ⟨some entry, (((), register), metadata), base⟩ + (some ⟨next, (((), none), metadata), Function.update base source []⟩) + ((base source).length + 1) := by + let run := MachineDrain.drainInTime source () none (drainProgram source) rfl base () register + exact MachineStateFrame.execution (fun _ : Unit => entry) next metadata (drainProgram source) + (program initialQuery exit) (fun _ => atEntry) run + +noncomputable def clauseRankPhase (F : Target.Formula) (c : ClauseContext F u) + (initialQuery : Query u D) (exit : Option (Label u D Extra)) + (base : Arena u Extra → List Bool) + (hradix : base (clauseRankSlots (.inl 0)) = encodeWord F.clauses.length) + (hdigits : ∀ i, base (clauseRankSlots (.inr i)) = encodeWord (c i).val) + (hclean : MachineHorner.Clean clauseRankSlots base) (metadata : ArithmeticMetadata u D) : + StateTransition.EvalsToInTime (TM2.step (program initialQuery exit)) + ⟨some (.clauseRank .start), arithmeticStateEquiv u D ((((), ()), none), metadata), base⟩ + (some ⟨some (.rightBase .seed), arithmeticStateEquiv u D ((((), ()), none), metadata), + MachineHorner.resultTapes clauseRankSlots base (((clauseEncoding F u).code c).val)⟩) + ((MachineHorner.timePolynomial u).eval F.clauses.length) := by + let run := SourceRankPhase.clauseRankInTime F u c clauseRankSlots id none + (SourceRankPhase.program clauseRankSlots) (fun _ => rfl) base hradix hdigits hclean () none + exact framedExecution (arithmeticStateEquiv u D) .clauseRank (some (.rightBase .seed)) + metadata (SourceRankPhase.program clauseRankSlots) (program initialQuery exit) + (fun _ => rfl) run + +noncomputable def variableRankPhase (F : Target.Formula) (c : ClauseContext F u) + (index : Fin (SlotCount u)) (initialQuery : Query u D) (exit : Option (Label u D Extra)) + (base : Arena u Extra → List Bool) + (hradix : base (variableRankSlots (selected index) (.inl 0)) = encodeWord F.«variables») + (hdigits : ∀ i, base (variableRankSlots (selected index) (.inr i)) = + encodeWord (sampledVariables F c (selected index) i).val) + (hclean : MachineHorner.Clean (variableRankSlots (selected index)) base) + (metadata : ArithmeticMetadata u D) : + StateTransition.EvalsToInTime (TM2.step (program initialQuery exit)) + ⟨some (.variableRank index .start), arithmeticStateEquiv u D ((((), ()), none), metadata), base⟩ + (some ⟨some (.leftBase index .seed), arithmeticStateEquiv u D ((((), ()), none), metadata), + MachineHorner.resultTapes (variableRankSlots (selected index)) base + (((variableEncoding F u).code (sampledVariables F c (selected index))).val)⟩) + ((MachineHorner.timePolynomial u).eval F.«variables») := by + let slots := variableRankSlots (u := u) (Extra := Extra) (selected index) + let run := SourceRankPhase.variableRankInTime F u (sampledVariables F c (selected index)) + slots id none (SourceRankPhase.program slots) (fun _ => rfl) base hradix hdigits hclean () none + exact framedExecution (arithmeticStateEquiv u D) (.variableRank index) + (some (.leftBase index .seed)) metadata (SourceRankPhase.program slots) + (program initialQuery exit) (fun _ => rfl) run + +noncomputable def rightBasePhase (F : Target.Formula) (c : ClauseContext F u) + (initialQuery : Query u D) (exit : Option (Label u D Extra)) + (base : Arena u Extra → List Bool) + (hrank : base (baseSlots true (.inl 0)) = encodeWord (((clauseEncoding F u).code c).val)) + (hleftBlock : base (baseSlots true (.inr 1)) = encodeWord (2 ^ (2 ^ u) * F.«variables» ^ u)) + (hcoefficient : base (baseSlots true (.inr 0)) = []) + (hclean : MachineHorner.Clean (baseSlots true) base) (metadata : ArithmeticMetadata u D) : + StateTransition.EvalsToInTime (TM2.step (program initialQuery exit)) + ⟨some (.rightBase .seed), arithmeticStateEquiv u D ((((), ()), none), metadata), base⟩ + (some ⟨some .clearClauseRank, arithmeticStateEquiv u D ((((), ()), none), metadata), + MachineHorner.resultTapes (baseSlots true) base + (SourceAddressDescriptors.baseValue F u c (sampledVariables F c (fun _ => .first)) 1)⟩) + ((SourceBasePhase.timePolynomial (2 ^ (8 ^ u))).eval + (SourceBasePhase.operandLength (((clauseEncoding F u).code c).val) + (2 ^ (2 ^ u) * F.«variables» ^ u))) := by + let run := SourceBasePhase.rightBaseInTime F u c (sampledVariables F c (fun _ => .first)) + (baseSlots true) id none (SourceBasePhase.program (baseSlots true) (2 ^ (8 ^ u))) + (fun _ => rfl) base hrank hleftBlock hcoefficient hclean () none + exact framedExecution (arithmeticStateEquiv u D) .rightBase (some .clearClauseRank) metadata + (SourceBasePhase.program (baseSlots true) (2 ^ (8 ^ u))) + (program initialQuery exit) (fun _ => rfl) run + +noncomputable def leftBasePhase (F : Target.Formula) (c : ClauseContext F u) + (index : Fin (SlotCount u)) (initialQuery : Query u D) (exit : Option (Label u D Extra)) + (base : Arena u Extra → List Bool) + (hrank : base (baseSlots false (.inl 0)) = + encodeWord (((variableEncoding F u).code (sampledVariables F c (selected index))).val)) + (hzero : base (baseSlots false (.inr 1)) = encodeWord 0) + (hcoefficient : base (baseSlots false (.inr 0)) = []) + (hclean : MachineHorner.Clean (baseSlots false) base) (metadata : ArithmeticMetadata u D) : + StateTransition.EvalsToInTime (TM2.step (program initialQuery exit)) + ⟨some (.leftBase index .seed), arithmeticStateEquiv u D ((((), ()), none), metadata), base⟩ + (some ⟨some (.query index (.load ⟨0, by omega⟩)), + arithmeticStateEquiv u D ((((), ()), none), metadata), + MachineHorner.resultTapes (baseSlots false) base + (SourceAddressDescriptors.baseValue F u c (sampledVariables F c (selected index)) 0)⟩) + ((SourceBasePhase.timePolynomial (2 ^ (2 ^ u))).eval + (SourceBasePhase.operandLength + (((variableEncoding F u).code (sampledVariables F c (selected index))).val) 0)) := by + let run := SourceBasePhase.leftBaseInTime F u c (sampledVariables F c (selected index)) + (baseSlots false) id none (SourceBasePhase.program (baseSlots false) (2 ^ (2 ^ u))) + (fun _ => rfl) base hrank hzero hcoefficient hclean () none + exact framedExecution (arithmeticStateEquiv u D) (.leftBase index) + (some (.query index (.load ⟨0, by omega⟩))) metadata + (SourceBasePhase.program (baseSlots false) (2 ^ (2 ^ u))) + (program initialQuery exit) (fun _ => rfl) run + +theorem queryPhase (F : Target.Formula) (c : ClauseContext F u) + (index : Fin (SlotCount u)) (initialQuery beforeQuery : Query u D) + (exit : Option (Label u D Extra)) (base : Arena u Extra → List Bool) + (metadata : QueryMetadata u) + (hsource : ∀ side, base (queryLayout.sources side) = encodeWord + (SourceAddressDescriptors.baseValue F u c (sampledVariables F c (selected index)) side)) + (hscratch : base queryLayout.scratch = []) (htemporary : base queryLayout.temporary = []) : + ∃ afterQuery : Query u D, + Nonempty (StateTransition.EvalsToInTime (TM2.step (program initialQuery exit)) + ⟨some (.query index (.load ⟨0, by omega⟩)), + queryStateEquiv u D (((ofContext F c (selected index), beforeQuery), none), metadata), base⟩ + (some ⟨some (.clearSlotRank index), + queryStateEquiv u D (((ofContext F c (selected index), afterQuery), none), metadata), + SourceTestAppend.resultTapes queryLayout base + (SourceQueryOrder.slotBits F u D c (selected index))⟩) + (QueryCount u D * (9 * nBits F u + 21) + 1)) := by + let localProgram := SourceQueryLoop.statement u D (QueryCount u D) + (SourceLoopOrder.rankedQuery u D initialQuery) (queryLayout (u := u) (Extra := Extra)) id none + obtain ⟨lastQuery, ⟨run⟩⟩ := SourceQueryOrder.sourceLoopInTime F u D c (selected index) + initialQuery beforeQuery queryLayout id none localProgram (fun _ => rfl) base + hsource hscratch htemporary + refine ⟨lastQuery, ⟨?_⟩⟩ + exact framedExecution (queryStateEquiv u D) (.query index) (some (.clearSlotRank index)) + metadata localProgram (program initialQuery exit) (fun _ => rfl) run + +def selectPhase (initialQuery : Query u D) (exit : Option (Label u D Extra)) + (index : Fin (SlotCount u)) (state : State u D) (base : Arena u Extra → List Bool) : + StateTransition.EvalsToInTime (TM2.step (program initialQuery exit)) + ⟨some (.select index.castSucc), state, base⟩ + (some ⟨some (.variableRank index .start), selectState initialQuery index state, base⟩) 1 where + steps := 1 + evals_in_steps := by + change some (TM2.stepAux (program initialQuery exit (.select index.castSucc)) state base) = _ + simp only [program, Fin.val_castSucc, index.isLt, ↓reduceDIte, TM2.stepAux] + steps_le_m := Nat.le_refl _ + +omit [DecidableEq Extra] in +@[simp] theorem loaded_extra (F : Target.Formula) (c : ClauseContext F u) + (base : Arena u Extra → List Bool) (extra : BodyExtra Extra) : + SourceContextLoad.stageTapes F c base u (.extra extra) = base (.extra extra) := + SourceContextLoad.stageTapes_frame F c base u _ (by simp) (by simp) (by simp) + +omit [DecidableEq Extra] in +theorem Ready.loadedClean {F : Target.Formula} {c : ClauseContext F u} + {base : Arena u Extra → List Bool} (h : Ready F c base) : + WorkClean (SourceContextLoad.stageTapes F c base u) where + accA := (loaded_extra F c base _).trans h.accA + accB := (loaded_extra F c base _).trans h.accB + counter := (loaded_extra F c base _).trans h.counter + scratch := (loaded_extra F c base _).trans h.arithScratch + +def loopSnapshot (F : Target.Formula) (c : ClauseContext F u) (bits : List Bool) : Snapshot := + { rightBase := encodeWord (rightValue F c), zero := encodeWord 0, emitted := bits } + +def rankSnapshot (F : Target.Formula) (c : ClauseContext F u) + (index : Fin (SlotCount u)) (bits : List Bool) : Snapshot := + { loopSnapshot F c bits with rank := encodeWord (variableRank F c index) } + +def baseSnapshot (F : Target.Formula) (c : ClauseContext F u) + (index : Fin (SlotCount u)) (bits : List Bool) : Snapshot := + { rankSnapshot F c index bits with leftBase := encodeWord (leftValue F c index) } + +theorem slotInTime (F : Target.Formula) (c : ClauseContext F u) + (initialQuery beforeQuery : Query u D) (beforeSignature : Signature u) + (exit : Option (Label u D Extra)) (base : Arena u Extra → List Bool) (h : Ready F c base) + (index : Fin (SlotCount u)) (bits : List Bool) : + ∃ afterQuery : Query u D, + Nonempty (StateTransition.EvalsToInTime (TM2.step (program initialQuery exit)) + ⟨some (.select index.castSucc), workingState F c beforeSignature beforeQuery, + tapes (SourceContextLoad.stageTapes F c base u) (loopSnapshot F c bits)⟩ + (some ⟨some (.select ⟨index.val + 1, by omega⟩), + workingState F c (ofContext F c (selected index)) afterQuery, + tapes (SourceContextLoad.stageTapes F c base u) + (loopSnapshot F c (bits ++ SourceQueryOrder.slotBits F u D c (selected index)))⟩) + (slotBudget (D := D) F c index)) := by + let loaded := SourceContextLoad.stageTapes F c base u + let sig := ofContext F c (selected index) + let startTapes := tapes loaded (loopSnapshot F c bits) + let rankedTapes := tapes loaded (rankSnapshot F c index bits) + let basedTapes := tapes loaded (baseSnapshot F c index bits) + have hs := selectPhase initialQuery exit index (workingState F c beforeSignature beforeQuery) startTapes + rw [select_workingState] at hs + have hr := variableRankPhase F c index initialQuery exit startTapes + (by change loaded variableHeader = encodeWord F.«variables» + exact (loaded_extra F c base _).trans h.variableCount) + (by intro i + exact SourceRankPhase.selectedDigits_loaded F c (selected index) + (rankControls .variableCount) base (fun j => h.fields j _) i) + (clean_variable loaded (loopSnapshot F c bits) (selected index) h.loadedClean) + (arithmeticMetadata F c sig initialQuery) + have hr' : StateTransition.EvalsToInTime (TM2.step (program initialQuery exit)) + ⟨some (.variableRank index .start), workingState F c sig initialQuery, startTapes⟩ + (some ⟨some (.leftBase index .seed), workingState F c sig initialQuery, rankedTapes⟩) + ((MachineHorner.timePolynomial u).eval F.«variables») := by + simpa only [arithmeticState_working, startTapes, rankedTapes, rankSnapshot, + horner_variable_result, loopSnapshot, List.append_nil, variableRank] using hr + have hb := leftBasePhase F c index initialQuery exit rankedTapes + (by rfl) (by rfl) + (by change loaded (workTape .coefficient) = [] + exact (loaded_extra F c base _).trans h.coefficient) + (clean_base loaded (rankSnapshot F c index bits) false h.loadedClean) + (arithmeticMetadata F c sig initialQuery) + have hb' : StateTransition.EvalsToInTime (TM2.step (program initialQuery exit)) + ⟨some (.leftBase index .seed), workingState F c sig initialQuery, rankedTapes⟩ + (some ⟨some (.query index (.load ⟨0, by omega⟩)), workingState F c sig initialQuery, basedTapes⟩) + ((SourceBasePhase.timePolynomial (2 ^ (2 ^ u))).eval + (SourceBasePhase.operandLength (variableRank F c index) 0)) := by + simpa only [arithmeticState_working, rankedTapes, basedTapes, baseSnapshot, + horner_left_result, rankSnapshot, loopSnapshot, List.append_nil, leftValue, variableRank] using hb + obtain ⟨lastQuery, ⟨hq⟩⟩ := queryPhase F c index initialQuery initialQuery exit basedTapes + (queryMetadata F c) + (by intro side + fin_cases side + · rfl + · rfl + · change loaded (workTape .dummy) = _ + exact (loaded_extra F c base _).trans h.dummy) + (by change loaded (workTape .queryScratch) = [] + exact (loaded_extra F c base _).trans h.queryScratch) + (by change loaded (workTape .queryTemporary) = [] + exact (loaded_extra F c base _).trans h.queryTemporary) + let emitted := bits ++ SourceQueryOrder.slotBits F u D c (selected index) + let emittedSnapshot := {baseSnapshot F c index bits with emitted := emitted} + let emittedTapes := tapes loaded emittedSnapshot + have hq' : StateTransition.EvalsToInTime (TM2.step (program initialQuery exit)) + ⟨some (.query index (.load ⟨0, by omega⟩)), workingState F c sig initialQuery, basedTapes⟩ + (some ⟨some (.clearSlotRank index), workingState F c sig lastQuery, emittedTapes⟩) + (QueryCount u D * (9 * nBits F u + 21) + 1) := by + simpa only [queryState_working, basedTapes, emittedTapes, emittedSnapshot, query_result, + baseSnapshot, rankSnapshot, loopSnapshot, emitted, sig] using hq + let afterRank := tapes loaded {emittedSnapshot with rank := []} + have hdRank := drainPhase initialQuery exit (workTape .rank) (.clearSlotRank index) + (some (.clearLeft index)) rfl emittedTapes (workingState F c sig lastQuery).2 none + have hdRank' : StateTransition.EvalsToInTime (TM2.step (program initialQuery exit)) + ⟨some (.clearSlotRank index), workingState F c sig lastQuery, emittedTapes⟩ + (some ⟨some (.clearLeft index), workingState F c sig lastQuery, afterRank⟩) + (variableRank F c index + 2) := by + simpa only [workingState_loader, emittedTapes, afterRank, update_rank, tapes_rank, emittedSnapshot, + baseSnapshot, rankSnapshot, encodeWord_length, Nat.add_assoc, show (1 : Nat) + 1 = 2 from rfl] using hdRank + have hdLeft := drainPhase initialQuery exit (workTape .leftBase) (.clearLeft index) + (some (.select ⟨index.val + 1, by omega⟩)) rfl afterRank + (workingState F c sig lastQuery).2 none + have hdLeft' : StateTransition.EvalsToInTime (TM2.step (program initialQuery exit)) + ⟨some (.clearLeft index), workingState F c sig lastQuery, afterRank⟩ + (some ⟨some (.select ⟨index.val + 1, by omega⟩), workingState F c sig lastQuery, + tapes loaded (loopSnapshot F c emitted)⟩) + (leftValue F c index + 2) := by + simpa only [workingState_loader, afterRank, update_leftBase, tapes_leftBase, emittedSnapshot, + baseSnapshot, rankSnapshot, loopSnapshot, encodeWord_length, Nat.add_assoc, show (1 : Nat) + 1 = 2 from rfl] using hdLeft + let joined := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ + (StateTransition.EvalsToInTime.trans _ _ _ _ _ _ + (StateTransition.EvalsToInTime.trans _ _ _ _ _ _ + (StateTransition.EvalsToInTime.trans _ _ _ _ _ _ + (StateTransition.EvalsToInTime.trans _ _ _ _ _ _ hs hr') hb') hq') hdRank') hdLeft' + refine ⟨lastQuery, ⟨{ toEvalsTo := joined.toEvalsTo, steps_le_m := ?_ }⟩⟩ + have hj := joined.steps_le_m + dsimp only [slotBudget] + omega + +def slotAt (u : Nat) (i : Nat) : SlotContext u := + if h : i < SlotCount u then selected ⟨i, h⟩ else fun _ => .first + +def prefixBits (F : Target.Formula) (c : ClauseContext F u) : Nat → List Bool + | 0 => [] + | r + 1 => prefixBits F c r ++ SourceQueryOrder.slotBits F u D c (slotAt u r) + +noncomputable def prefixBudget (F : Target.Formula) (c : ClauseContext F u) : Nat → Nat + | 0 => 0 + | r + 1 => prefixBudget F c r + if h : r < SlotCount u then slotBudget (D := D) F c ⟨r, h⟩ else 0 + +theorem prefixInTime (F : Target.Formula) (c : ClauseContext F u) + (initialQuery beforeQuery : Query u D) (beforeSignature : Signature u) + (exit : Option (Label u D Extra)) (base : Arena u Extra → List Bool) (h : Ready F c base) + (r : Nat) (hr : r ≤ SlotCount u) : + ∃ afterSignature : Signature u, ∃ afterQuery : Query u D, + Nonempty (StateTransition.EvalsToInTime (TM2.step (program initialQuery exit)) + ⟨some (.select ⟨0, by omega⟩), workingState F c beforeSignature beforeQuery, + tapes (SourceContextLoad.stageTapes F c base u) (loopSnapshot F c [])⟩ + (some ⟨some (.select ⟨r, by omega⟩), workingState F c afterSignature afterQuery, + tapes (SourceContextLoad.stageTapes F c base u) + (loopSnapshot F c (prefixBits (D := D) F c r))⟩) + (prefixBudget (D := D) F c r)) := by + induction r with + | zero => + refine ⟨beforeSignature, beforeQuery, ⟨{ + steps := 0 + evals_in_steps := rfl + steps_le_m := Nat.le_refl _ }⟩⟩ + | succ r ih => + obtain ⟨previousSignature, previousQuery, ⟨previous⟩⟩ := ih (by omega) + have hlt : r < SlotCount u := by omega + let index : Fin (SlotCount u) := ⟨r, hlt⟩ + obtain ⟨lastQuery, ⟨one⟩⟩ := slotInTime F c initialQuery previousQuery previousSignature + exit base h index (prefixBits (D := D) F c r) + let joined := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ previous one + refine ⟨ofContext F c (selected index), lastQuery, + ⟨{ steps := joined.steps, evals_in_steps := ?_, steps_le_m := ?_ }⟩⟩ + · simpa only [prefixBits, slotAt, dite_eq_left hlt, index] using joined.evals_in_steps + · have hj := joined.steps_le_m + simp only [prefixBudget, dite_eq_left hlt] + dsimp only [index] at hj + omega + +theorem prefixBits_eq_ofFn (F : Target.Formula) (c : ClauseContext F u) (n : Nat) : + prefixBits (D := D) F c n = + (List.ofFn (fun i : Fin n => slotAt u i.val)).flatMap (SourceQueryOrder.slotBits F u D c) := by + induction n with + | zero => simp [prefixBits] + | succ n ih => + rw [prefixBits, List.ofFn_succ', List.concat_eq_append, List.flatMap_append] + simpa only [List.flatMap_cons, List.flatMap_nil, List.append_nil, + Fin.val_castSucc, Fin.val_last] using congrArg + (fun bits => bits ++ SourceQueryOrder.slotBits F u D c (slotAt u n)) ih + +theorem prefixBits_eq_tupleBits (F : Target.Formula) (c : ClauseContext F u) : + prefixBits (D := D) F c (SlotCount u) = SourceQueryOrder.tupleBits F u D c := by + rw [prefixBits_eq_ofFn] + have hlist : List.ofFn (fun i : Fin (SlotCount u) => slotAt u i.val) = + (slotContextEncoding u).enumerate := by + apply congrArg List.ofFn + funext i + simp only [slotAt, i.isLt, ↓reduceDIte, selected] + rw [hlist] + rfl + +noncomputable def setupBudget (F : Target.Formula) (c : ClauseContext F u) : Nat := + ((u * (10 * (formulaBits F).length + 20) + 1) + + (SourceSignaturePrepare.Width u * SourceSignaturePrepare.Width u * + (5 * (formulaBits F).length + 6) + 2)) + 1 + + (MachineHorner.timePolynomial u).eval F.clauses.length + + (SourceBasePhase.timePolynomial (2 ^ (8 ^ u))).eval + (SourceBasePhase.operandLength (((clauseEncoding F u).code c).val) + (2 ^ (2 ^ u) * F.«variables» ^ u)) + + (((clauseEncoding F u).code c).val + 2) + +def finishBudget (F : Target.Formula) (c : ClauseContext F u) : Nat := + 1 + (rightValue F c + 2) + 2 + (6 * u * ((formulaBits F).length + 1) + 1) + 1 + +noncomputable def bodyBudget (F : Target.Formula) (c : ClauseContext F u) : Nat := + setupBudget F c + prefixBudget (D := D) F c (SlotCount u) + finishBudget F c + +noncomputable def setupInTime (F : Target.Formula) (c : ClauseContext F u) + (initialQuery : Query u D) (exit : Option (Label u D Extra)) + (base : Arena u Extra → List Bool) (h : Ready F c base) : + StateTransition.EvalsToInTime (TM2.step (program initialQuery exit)) + ⟨some main, canonicalState initialQuery, base⟩ + (some ⟨some (.select ⟨0, by omega⟩), + workingState F c (canonicalSignature u) initialQuery, + tapes (SourceContextLoad.stageTapes F c base u) (loopSnapshot F c [])⟩) + (setupBudget F c) := by + let loaded := SourceContextLoad.stageTapes F c base u + let state := workingState F c (canonicalSignature u) initialQuery + let s0 : Snapshot := {zero := encodeWord 0} + let s1 : Snapshot := {s0 with rank := encodeWord (((clauseEncoding F u).code c).val)} + let s2 : Snapshot := {s1 with rightBase := encodeWord (rightValue F c)} + have hp := preparePhase F c initialQuery exit base h.formula h.current h.index h.work + h.scratch h.copyScratch (fun p => h.fields p.1 _) + have he : tapes loaded {} = loaded := empty_tapes loaded + ((loaded_extra F c base _).trans h.rank) ((loaded_extra F c base _).trans h.rightBase) + ((loaded_extra F c base _).trans h.leftBase) ((loaded_extra F c base _).trans h.zero) + have hz := seedZeroPhase initialQuery exit state loaded ((loaded_extra F c base _).trans h.zero) + have hupdate := update_zero loaded {} (encodeWord 0) + rw [he] at hupdate + rw [hupdate] at hz + have hr := clauseRankPhase F c initialQuery exit (tapes loaded s0) + (by change loaded clauseHeader = encodeWord F.clauses.length + exact (loaded_extra F c base _).trans h.clauseCount) + (by intro i + change loaded (.current i) = encodeWord (c i).val + exact (SourceContextLoad.stageTapes_frame F c base u (.current i) + (by simp) (by simp) (by simp)).trans (h.current i)) + (clean_clause loaded s0 h.loadedClean) + (arithmeticMetadata F c (canonicalSignature u) initialQuery) + have hr' : StateTransition.EvalsToInTime (TM2.step (program initialQuery exit)) + ⟨some (.clauseRank .start), state, tapes loaded s0⟩ + (some ⟨some (.rightBase .seed), state, tapes loaded s1⟩) + ((MachineHorner.timePolynomial u).eval F.clauses.length) := by + simpa only [arithmeticState_working, horner_clause_result, state, s1, s0, List.append_nil] using hr + have hb := rightBasePhase F c initialQuery exit (tapes loaded s1) (by rfl) + (by change loaded (workTape .leftBlock) = encodeWord (2 ^ (2 ^ u) * F.«variables» ^ u) + exact (loaded_extra F c base _).trans h.leftBlock) + (by change loaded (workTape .coefficient) = [] + exact (loaded_extra F c base _).trans h.coefficient) + (clean_base loaded s1 true h.loadedClean) + (arithmeticMetadata F c (canonicalSignature u) initialQuery) + have hb' : StateTransition.EvalsToInTime (TM2.step (program initialQuery exit)) + ⟨some (.rightBase .seed), state, tapes loaded s1⟩ + (some ⟨some .clearClauseRank, state, tapes loaded s2⟩) + ((SourceBasePhase.timePolynomial (2 ^ (8 ^ u))).eval + (SourceBasePhase.operandLength (((clauseEncoding F u).code c).val) + (2 ^ (2 ^ u) * F.«variables» ^ u))) := by + simpa only [arithmeticState_working, horner_right_result, state, s2, s1, s0, + List.append_nil, rightValue] using hb + have hd := drainPhase initialQuery exit (workTape .rank) .clearClauseRank + (some (.select ⟨0, by omega⟩)) rfl (tapes loaded s2) state.2 none + have hd' : StateTransition.EvalsToInTime (TM2.step (program initialQuery exit)) + ⟨some .clearClauseRank, state, tapes loaded s2⟩ + (some ⟨some (.select ⟨0, by omega⟩), state, tapes loaded (loopSnapshot F c [])⟩) + (((clauseEncoding F u).code c).val + 2) := by + simpa only [state, workingState_loader, update_rank, tapes_rank, s2, s1, s0, + loopSnapshot, encodeWord_length, Nat.add_assoc, show (1 : Nat) + 1 = 2 from rfl] using hd + let joined := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ + (StateTransition.EvalsToInTime.trans _ _ _ _ _ _ + (StateTransition.EvalsToInTime.trans _ _ _ _ _ _ + (StateTransition.EvalsToInTime.trans _ _ _ _ _ _ hp hz) hr') hb') hd' + refine { toEvalsTo := joined.toEvalsTo, steps_le_m := ?_ } + have hj := joined.steps_le_m + dsimp only [setupBudget] + omega + +def finishInTime (F : Target.Formula) (c : ClauseContext F u) + (initialQuery query : Query u D) (signature : Signature u) + (exit : Option (Label u D Extra)) (base : Arena u Extra → List Bool) (h : Ready F c base) + (bits : List Bool) : + StateTransition.EvalsToInTime (TM2.step (program initialQuery exit)) + ⟨some (.select ⟨SlotCount u, by omega⟩), workingState F c signature query, + tapes (SourceContextLoad.stageTapes F c base u) (loopSnapshot F c bits)⟩ + (some ⟨exit, canonicalState initialQuery, SourceTestAppend.resultTapes queryLayout base bits⟩) + (finishBudget F c) := by + let loaded := SourceContextLoad.stageTapes F c base u + let state := workingState F c signature query + let s0 := loopSnapshot F c bits + let s1 : Snapshot := {s0 with rightBase := []} + let s2 : Snapshot := {emitted := bits} + have hd : StateTransition.EvalsToInTime (TM2.step (program initialQuery exit)) + ⟨some (.select ⟨SlotCount u, by omega⟩), state, tapes loaded s0⟩ + (some ⟨some .clearRight, state, tapes loaded s0⟩) 1 := { + steps := 1 + evals_in_steps := by + change some (TM2.stepAux (program initialQuery exit (.select ⟨SlotCount u, by omega⟩)) + state (tapes loaded s0)) = _ + simp only [program, Nat.lt_irrefl, ↓reduceDIte, TM2.stepAux] + steps_le_m := Nat.le_refl _ } + have hr := drainPhase initialQuery exit (workTape .rightBase) .clearRight (some .clearZero) + rfl (tapes loaded s0) state.2 none + have hr' : StateTransition.EvalsToInTime (TM2.step (program initialQuery exit)) + ⟨some .clearRight, state, tapes loaded s0⟩ + (some ⟨some .clearZero, state, tapes loaded s1⟩) (rightValue F c + 2) := by + simpa only [state, workingState_loader, update_rightBase, tapes_rightBase, s1, s0, + loopSnapshot, encodeWord_length, Nat.add_assoc, show (1 : Nat) + 1 = 2 from rfl] using hr + have hz := drainPhase initialQuery exit (workTape .zero) .clearZero + (some (.clearContext SourceContextClear.main)) rfl (tapes loaded s1) state.2 none + have hz' : StateTransition.EvalsToInTime (TM2.step (program initialQuery exit)) + ⟨some .clearZero, state, tapes loaded s1⟩ + (some ⟨some (.clearContext SourceContextClear.main), state, tapes loaded s2⟩) 2 := by + simpa only [state, workingState_loader, update_zero, tapes_zero, s2, s1, s0, + loopSnapshot, encodeWord_length, Nat.zero_add, show (1 : Nat) + 1 = 2 from rfl] using hz + have cleanup := clearLoadedSnapshotInTime F c base s2 h.fields h.index h.work none + have hc := MachineStateFrame.execution .clearContext (some .reset) state.2 + SourceContextClear.program (program initialQuery exit) (fun _ => rfl) cleanup + have hc' : StateTransition.EvalsToInTime (TM2.step (program initialQuery exit)) + ⟨some (.clearContext SourceContextClear.main), state, tapes loaded s2⟩ + (some ⟨some .reset, state, tapes base s2⟩) + (6 * u * ((formulaBits F).length + 1) + 1) := by + simpa only [MachineStateFrame.configuration, MachineStateFrame.frameConfiguration, + MachineSubroutine.configuration, MachineSubroutine.label, state, workingState_loader] using hc + have reset := resetInTime initialQuery exit state (tapes base s2) + let joined := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ + (StateTransition.EvalsToInTime.trans _ _ _ _ _ _ + (StateTransition.EvalsToInTime.trans _ _ _ _ _ _ + (StateTransition.EvalsToInTime.trans _ _ _ _ _ _ hd hr') hz') hc') reset + refine { steps := joined.steps, evals_in_steps := ?_, steps_le_m := ?_ } + · have hend : tapes base s2 = SourceTestAppend.resultTapes queryLayout base bits := + final_tapes base bits h.rank h.rightBase h.leftBase h.zero + simpa only [hend] using joined.evals_in_steps + · have hj := joined.steps_le_m + dsimp only [finishBudget] + omega + +theorem bodyInTime (F : Target.Formula) (c : ClauseContext F u) + (initialQuery : Query u D) (exit : Option (Label u D Extra)) + (base : Arena u Extra → List Bool) (h : Ready F c base) : + Nonempty (StateTransition.EvalsToInTime (TM2.step (program initialQuery exit)) + ⟨some main, canonicalState initialQuery, base⟩ + (some ⟨exit, canonicalState initialQuery, + SourceTestAppend.resultTapes queryLayout base (SourceQueryOrder.tupleBits F u D c)⟩) + (bodyBudget (D := D) F c)) := by + have setup := setupInTime F c initialQuery exit base h + obtain ⟨signature, lastQuery, ⟨loopRun⟩⟩ := prefixInTime F c initialQuery initialQuery + (canonicalSignature u) exit base h (SlotCount u) (Nat.le_refl _) + rw [prefixBits_eq_tupleBits] at loopRun + have finishRun := finishInTime F c initialQuery lastQuery signature exit base h + (SourceQueryOrder.tupleBits F u D c) + let joined := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ + (StateTransition.EvalsToInTime.trans _ _ _ _ _ _ setup loopRun) finishRun + refine ⟨{ toEvalsTo := joined.toEvalsTo, steps_le_m := ?_ }⟩ + have hj := joined.steps_le_m + dsimp only [bodyBudget] + omega + +def machine (u D : Nat) (Extra : Type) [DecidableEq Extra] [Fintype Extra] + (initialQuery : Query u D) : FinTM2 where + K := Arena u Extra + k₀ := .formula + k₁ := workTape .accumulator + Γ _ := Bool + Λ := Label u D Extra + main := main + σ := State u D + initialState := canonicalState initialQuery + m := program initialQuery none + +end MinUncutGames.Foundations.Hastad.SourceTupleBody + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/TupleBound.lean b/lean/OAI/Computability/MinUncut/PCP/TupleBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..c928eff364b9de6444cb87de478005327402f533 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/TupleBound.lean @@ -0,0 +1,412 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.Gap + +namespace OAI + +section +namespace MinUncutGames.Foundations.Hastad.SourceTupleBound + +open Complexity SourceContexts SourceOccurrences SourceTupleBody +open Complexity.MachineComposition + +variable {u D : Nat} + +theorem clauseRank_le_power (F : Target.Formula) (c : ClauseContext F u) : + ((clauseEncoding F u).code c).val ≤ (formulaBits F).length ^ u := by + have hr := ((clauseEncoding F u).code c).isLt + change _ < F.clauses.length ^ u at hr + exact hr.le.trans (Nat.pow_le_pow_left (SourceBounds.formulaBits_length_ge_clauses F) u) + +theorem variableRank_le_power (F : Target.Formula) (c : ClauseContext F u) + (index : Fin (SlotCount u)) : + variableRank F c index ≤ (formulaBits F).length ^ u := by + have hr := ((variableEncoding F u).code (sampledVariables F c (selected index))).isLt + change variableRank F c index < F.«variables» ^ u at hr + exact hr.le.trans (Nat.pow_le_pow_left (SourceBounds.formulaBits_length_ge_variables F) u) + +theorem leftValue_le_numberBound (F : Target.Formula) (c : ClauseContext F u) + (index : Fin (SlotCount u)) : + leftValue F c index ≤ SourceBounds.bitCoefficient u * (formulaBits F).length ^ u := + (SourceAddressDescriptors.baseValue_lt F u c (sampledVariables F c (selected index)) 0).le.trans + (SourceBounds.nBits_le_input F u) + +theorem rightValue_le_numberBound (F : Target.Formula) (c : ClauseContext F u) : + rightValue F c ≤ SourceBounds.bitCoefficient u * (formulaBits F).length ^ u := + (SourceAddressDescriptors.baseValue_lt F u c (sampledVariables F c (fun _ => .first)) 1).le.trans + (SourceBounds.nBits_le_input F u) + +theorem leftBlock_le_numberBound (F : Target.Formula) : + 2 ^ (2 ^ u) * F.«variables» ^ u ≤ + SourceBounds.bitCoefficient u * (formulaBits F).length ^ u := by + apply Nat.le_trans (m := nBits F u) + · rw [Nat.mul_comm (2 ^ (2 ^ u)) (F.«variables» ^ u), nBits_eq] + omega + · exact SourceBounds.nBits_le_input F u + +noncomputable def rankPolynomial (u : Nat) : Polynomial Nat := Polynomial.X ^ u +noncomputable def numberPolynomial (u : Nat) : Polynomial Nat := + Polynomial.C (SourceBounds.bitCoefficient u) * Polynomial.X ^ u + +@[simp] theorem rankPolynomial_eval (u L : Nat) : (rankPolynomial u).eval L = L ^ u := by + simp [rankPolynomial] +@[simp] theorem numberPolynomial_eval (u L : Nat) : + (numberPolynomial u).eval L = SourceBounds.bitCoefficient u * L ^ u := by + simp [numberPolynomial] + +noncomputable def slotPolynomial (u D : Nat) : Polynomial Nat := + Polynomial.C 1 + MachineHorner.timePolynomial u + + (SourceBasePhase.timePolynomial (2 ^ (2 ^ u))).comp (rankPolynomial u + Polynomial.C 2) + + (Polynomial.C (QueryCount u D) * (Polynomial.C 9 * numberPolynomial u + Polynomial.C 21) + + Polynomial.C 1) + + (rankPolynomial u + Polynomial.C 2) + (numberPolynomial u + Polynomial.C 2) + +theorem slotPolynomial_eval (u D L : Nat) : + (slotPolynomial u D).eval L = + 1 + (MachineHorner.timePolynomial u).eval L + + (SourceBasePhase.timePolynomial (2 ^ (2 ^ u))).eval (L ^ u + 2) + + (QueryCount u D * (9 * (SourceBounds.bitCoefficient u * L ^ u) + 21) + 1) + + (L ^ u + 2) + (SourceBounds.bitCoefficient u * L ^ u + 2) := by + simp only [slotPolynomial, Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_C, + Polynomial.eval_comp, rankPolynomial_eval, numberPolynomial_eval] + +theorem slotBudget_le (F : Target.Formula) (c : ClauseContext F u) + (index : Fin (SlotCount u)) : + slotBudget (D := D) F c index ≤ (slotPolynomial u D).eval (formulaBits F).length := by + have hr := variableRank_le_power F c index + have hl := leftValue_le_numberBound F c index + have hb := SourceBounds.nBits_le_input F u + have hn := natPolynomial_eval_mono (MachineHorner.timePolynomial u) + (SourceBounds.formulaBits_length_ge_variables F) + have ho : SourceBasePhase.operandLength (variableRank F c index) 0 ≤ + (formulaBits F).length ^ u + 2 := by + simp only [SourceBasePhase.operandLength, encodeWord_length] + omega + have ha := natPolynomial_eval_mono (SourceBasePhase.timePolynomial (2 ^ (2 ^ u))) ho + have hq := Nat.mul_le_mul_left (QueryCount u D) + (Nat.add_le_add_right (Nat.mul_le_mul_left 9 hb) 21) + rw [slotPolynomial_eval] + unfold slotBudget + omega + +theorem prefixBudget_le (F : Target.Formula) (c : ClauseContext F u) (r : Nat) : + prefixBudget (D := D) F c r ≤ r * (slotPolynomial u D).eval (formulaBits F).length := by + induction r with + | zero => simp [prefixBudget] + | succ r ih => + rw [prefixBudget] + split + next h => + have hs := slotBudget_le (D := D) F c ⟨r, h⟩ + simpa only [Nat.succ_mul] using Nat.add_le_add ih hs + next _ => + simpa only [Nat.add_zero] using ih.trans + (Nat.mul_le_mul_right ((slotPolynomial u D).eval (formulaBits F).length) (Nat.le_succ r)) + +noncomputable def preparePolynomial (u : Nat) : Polynomial Nat := + Polynomial.C u * (Polynomial.C 10 * Polynomial.X + Polynomial.C 20) + Polynomial.C 1 + + (Polynomial.C (SourceSignaturePrepare.Width u * SourceSignaturePrepare.Width u) * + (Polynomial.C 5 * Polynomial.X + Polynomial.C 6) + Polynomial.C 2) + +theorem preparePolynomial_eval (u L : Nat) : + (preparePolynomial u).eval L = + (u * (10 * L + 20) + 1) + + (SourceSignaturePrepare.Width u * SourceSignaturePrepare.Width u * (5 * L + 6) + 2) := by + simp only [preparePolynomial, Polynomial.eval_add, Polynomial.eval_mul, + Polynomial.eval_C, Polynomial.eval_X] + +noncomputable def setupPolynomial (u : Nat) : Polynomial Nat := + preparePolynomial u + Polynomial.C 1 + MachineHorner.timePolynomial u + + (SourceBasePhase.timePolynomial (2 ^ (8 ^ u))).comp + (rankPolynomial u + numberPolynomial u + Polynomial.C 2) + + (rankPolynomial u + Polynomial.C 2) + +theorem setupPolynomial_eval (u L : Nat) : + (setupPolynomial u).eval L = + (preparePolynomial u).eval L + 1 + (MachineHorner.timePolynomial u).eval L + + (SourceBasePhase.timePolynomial (2 ^ (8 ^ u))).eval + (L ^ u + SourceBounds.bitCoefficient u * L ^ u + 2) + (L ^ u + 2) := by + simp only [setupPolynomial, Polynomial.eval_add, Polynomial.eval_C, + Polynomial.eval_comp, rankPolynomial_eval, numberPolynomial_eval] + +noncomputable def finishPolynomial (u : Nat) : Polynomial Nat := + Polynomial.C 1 + (numberPolynomial u + Polynomial.C 2) + Polynomial.C 2 + + (Polynomial.C (6 * u) * (Polynomial.X + Polynomial.C 1) + Polynomial.C 1) + Polynomial.C 1 + +theorem finishPolynomial_eval (u L : Nat) : + (finishPolynomial u).eval L = + 1 + (SourceBounds.bitCoefficient u * L ^ u + 2) + 2 + (6 * u * (L + 1) + 1) + 1 := by + simp only [finishPolynomial, Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_C, + Polynomial.eval_X, numberPolynomial_eval] + +noncomputable def bodyPolynomial (u D : Nat) : Polynomial Nat := + setupPolynomial u + Polynomial.C (SlotCount u) * slotPolynomial u D + finishPolynomial u + +theorem setupBudget_le (F : Target.Formula) (c : ClauseContext F u) : + setupBudget F c ≤ (setupPolynomial u).eval (formulaBits F).length := by + have hr := clauseRank_le_power F c + have hl := leftBlock_le_numberBound (u := u) F + have hm := natPolynomial_eval_mono (MachineHorner.timePolynomial u) + (SourceBounds.formulaBits_length_ge_clauses F) + have ho : SourceBasePhase.operandLength (((clauseEncoding F u).code c).val) + (2 ^ (2 ^ u) * F.«variables» ^ u) ≤ + (formulaBits F).length ^ u + + SourceBounds.bitCoefficient u * (formulaBits F).length ^ u + 2 := by + simp only [SourceBasePhase.operandLength, encodeWord_length] + omega + have ha := natPolynomial_eval_mono (SourceBasePhase.timePolynomial (2 ^ (8 ^ u))) ho + rw [setupPolynomial_eval, preparePolynomial_eval] + unfold setupBudget + omega + +theorem finishBudget_le (F : Target.Formula) (c : ClauseContext F u) : + finishBudget F c ≤ (finishPolynomial u).eval (formulaBits F).length := by + have hr := rightValue_le_numberBound F c + rw [finishPolynomial_eval] + unfold finishBudget + omega + +theorem bodyBudget_le (F : Target.Formula) (c : ClauseContext F u) : + bodyBudget (D := D) F c ≤ (bodyPolynomial u D).eval (formulaBits F).length := by + have hs := setupBudget_le F c + have hp := prefixBudget_le (D := D) F c (SlotCount u) + have hf := finishBudget_le F c + simp only [bodyPolynomial, Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_C] + unfold bodyBudget + omega + +theorem fixed_parameters_body_bound (u D : Nat) : + ∃ p : Polynomial Nat, ∀ (F : Target.Formula) (c : ClauseContext F u), + bodyBudget (D := D) F c ≤ p.eval (formulaBits F).length := + ⟨bodyPolynomial u D, fun F c => bodyBudget_le F c⟩ + +theorem bodyInPolynomialTime {Extra : Type} [DecidableEq Extra] + (F : Target.Formula) (c : ClauseContext F u) + (initialQuery : Query u D) (exit : Option (Label u D Extra)) + (base : SourceRuntimeModel.Arena u Extra → List Bool) (h : Ready F c base) : + Nonempty (StateTransition.EvalsToInTime (Turing.TM2.step (program initialQuery exit)) + ⟨some main, SourceRuntimeModel.canonicalState initialQuery, base⟩ + (some ⟨exit, SourceRuntimeModel.canonicalState initialQuery, + SourceTestAppend.resultTapes SourceRuntimeModel.queryLayout base + (SourceQueryOrder.tupleBits F u D c)⟩) + ((bodyPolynomial u D).eval (formulaBits F).length)) := by + obtain ⟨run⟩ := bodyInTime F c initialQuery exit base h + exact ⟨{ + toEvalsTo := run.toEvalsTo + steps_le_m := run.steps_le_m.trans (bodyBudget_le F c) + }⟩ + +end MinUncutGames.Foundations.Hastad.SourceTupleBound + +end +section +namespace MinUncutGames.Foundations.Hastad.SourceGeneratorTraversal + +open Turing Complexity SourceContexts SourceOccurrences SourceRuntimeModel +open SourceGeneratorModel SourceGeneratorProgram SourceOdometerSchedule + +noncomputable section + +variable {u D : Nat} + +local instance tupleBoundExtraDecidableEq (u D : Nat) : + DecidableEq (SourceGeneratorModel.Extra u D) := Classical.decEq _ + +def accumulatorRole (u D : Nat) : BodyExtra (SourceGeneratorModel.Extra u D) := + .inr .accumulator + +def leafTapes (F : Target.Formula) (c : ClauseContext F u) (output : List Bool) : + SourceGeneratorModel.Tape u D → List Bool := + setDigits F.clauses.length (fun i => (c i).val) + (setAcc (accumulatorRole u D) (SourceStartup.readyTapes F) output) + +@[simp] theorem leaf_accumulator (F : Target.Formula) (c : ClauseContext F u) (output : List Bool) : + leafTapes (D := D) F c output (accumulatorTape u D) = output := by + exact setAcc_apply (accumulatorRole u D) (SourceStartup.readyTapes F) output + +theorem leaf_work_blank (F : Target.Formula) (c : ClauseContext F u) (output : List Bool) + (role : BodyWork (SourceGeneratorModel.Extra u D)) + (hl : role ≠ .leftBlock) (hd : role ≠ .dummy) (ha : role ≠ .accumulator) : + leafTapes F c output (workTape role) = [] := by + change (Function.update (SourceStartup.readyTapes F) (accumulatorTape u D) output) + (workTape role) = [] + rw [Function.update_of_ne (by simpa [workTape, accumulatorTape] using ha)] + exact SourceStartup.ready_work_blank F role hl hd ha + +theorem leaf_ready (F : Target.Formula) (c : ClauseContext F u) (output : List Bool) : + SourceTupleBody.Ready F c (leafTapes (D := D) F c output) := by + constructor + · simp [leafTapes, setDigits, setAcc, accumulatorRole] + · intro i + simp [leafTapes, setDigits] + · change (SourceStartup.readyTapes (u := u) (D := D) F) .index = [] + exact SourceStartup.ready_sharedFrame F _ (Or.inl rfl) + · change (SourceStartup.readyTapes (u := u) (D := D) F) .work = [] + exact SourceStartup.ready_sharedWork F + · change (SourceStartup.readyTapes (u := u) (D := D) F) .scratch = [] + exact SourceStartup.ready_sharedFrame F _ (Or.inr (Or.inl rfl)) + · change (SourceStartup.readyTapes (u := u) (D := D) F) .copyScratch = [] + exact SourceStartup.ready_sharedFrame F _ (Or.inr (Or.inr rfl)) + · intro i s + simp [leafTapes, setDigits, setAcc, accumulatorRole] + · change (SourceStartup.readyTapes (u := u) (D := D) F) variableHeader = encodeWord F.«variables» + exact SourceStartup.ready_variableHeader F + · change (SourceStartup.readyTapes (u := u) (D := D) F) clauseHeader = encodeWord F.clauses.length + exact SourceStartup.ready_clauseHeader F + · change (SourceStartup.readyTapes (u := u) (D := D) F) (workTape .leftBlock) = _ + exact SourceStartup.ready_leftBlock F + · change (SourceStartup.readyTapes (u := u) (D := D) F) (workTape .dummy) = _ + simpa only [SourceHeaderCounts.dummyValue, SourceHeaderCounts.leftValue, + SourceHeaderCounts.rightValue, Nat.mul_comm] using SourceStartup.ready_dummy (u := u) (D := D) F + all_goals apply leaf_work_blank F c output _ <;> simp + +theorem body_result_leaf (F : Target.Formula) (c : ClauseContext F u) + (output bits : List Bool) : + SourceTestAppend.resultTapes queryLayout (leafTapes (D := D) F c output) bits = + leafTapes F c (bits.reverse ++ output) := by + change setAcc (accumulatorRole u D) (leafTapes F c output) + (bits.reverse ++ leafTapes F c output (accumulatorTape u D)) = _ + rw [leaf_accumulator] + unfold leafTapes + rw [setDigits_setAcc, setAcc_setAcc, ← setDigits_setAcc] + +@[simp] theorem source_initial (hD : 0 < D) : + sourceStateEquiv u D (canonicalState (initialQuery u D hD), ()) = + (initialAmbient u D hD, none) := rfl + +theorem actual_bodies (F : Target.Formula) (hD : 0 < D) : + BodyTrace (SourceGeneratorProgram.program u D hD) (bodyEntry u D) (next u D 0) + (initialAmbient u D hD) (accumulatorRole u D) (SourceStartup.readyTapes F) + (SourceQueryOrder.tupleBits F u D) + ((SourceTupleBound.bodyPolynomial u D).eval (formulaBits F).length) := by + intro c output + obtain ⟨run⟩ := SourceTupleBound.bodyInPolynomialTime F c (initialQuery u D hD) none + (leafTapes (D := D) F c output) (leaf_ready F c output) + have lifted := SourceTupleBody.framedExecution (sourceStateEquiv u D) + SourceGeneratorProgram.Label.body (some (next u D 0)) () + (SourceTupleBody.program (initialQuery u D hD) none) + (SourceGeneratorProgram.program u D hD) (fun _ => rfl) run + refine ⟨lifted.steps, lifted.steps_le_m, ?_⟩ + have ht := lifted.evals_in_steps + change (MachineComposition.advance (TM2.step (SourceGeneratorProgram.program u D hD)))^[lifted.steps] + _ = _ at ht + simp only [body_result_leaf] at ht + simpa only [SourceTupleBody.framedConfiguration, MachineControl.configuration, + MachineStateFrame.configuration, MachineStateFrame.frameConfiguration, + MachineSubroutine.configuration, MachineSubroutine.label, Option.map_some, + Option.map_none, id_eq, source_initial, configuration, + bodyEntry, leafTapes] using ht + +theorem resetDigits_ready (F : Target.Formula) : + setDigits F.clauses.length (fun _ : Fin u => 0) + (SourceStartup.readyTapes (u := u) (D := D) F) = SourceStartup.readyTapes F := by + funext k + cases k <;> simp [setDigits] + +theorem allBits_eq_records (F : Target.Formula) (hne : F.clauses ≠ []) : + allBits (SourceQueryOrder.tupleBits F u D) = + (sourceList F u D).flatMap (fun e => + encodeWords (MinUncutGames.Reduction.SourceEncoding.equationWords e)) := by + rw [sourceList_nonempty F u D hne] + unfold allBits SourceQueryOrder.tupleBits SourceQueryOrder.slotBits + SourceQueryOrder.occurrenceBits + simp only [rawSourceList, occurrenceList, + sourceIndexEncoding, Encoding.enumerate_prod, List.flatMap_map, List.flatMap_assoc, + clauseEncoding, Encoding.enumerate_fin_function] + +theorem accumulated_eq_input (F : Target.Formula) (hD : 0 < D) (hne : F.clauses ≠ []) : + (allBits (SourceQueryOrder.tupleBits F u D)).reverse ++ + SourceStartup.readyTapes F (accumulatorTape u D) = + (MinUncutGames.Reduction.SourceEncoding.inputBits (sourceInput F u D hD)).reverse := by + rw [allBits_eq_records F hne, SourceStartup.ready_accumulator] + have hi := SourceLoopOrder.inputBits_eq_header_records (sourceInput F u D hD) + change MinUncutGames.Reduction.SourceEncoding.inputBits (sourceInput F u D hD) = + encodeWords [nBits F u, (sourceList F u D).length] ++ + (sourceList F u D).flatMap (fun e => + encodeWords (MinUncutGames.Reduction.SourceEncoding.equationWords e)) at hi + rw [hi, List.reverse_append] + +def traversalOutput (F : Target.Formula) (hD : 0 < D) : SourceGeneratorModel.Tape u D → List Bool := + Function.update (SourceStartup.readyTapes F) (accumulatorTape u D) + (MinUncutGames.Reduction.SourceEncoding.inputBits (sourceInput F u D hD)).reverse + +@[simp] theorem traversalOutput_accumulator (F : Target.Formula) (hD : 0 < D) : + traversalOutput F hD (accumulatorTape u D) = + (MinUncutGames.Reduction.SourceEncoding.inputBits (sourceInput F u D hD)).reverse := by + simp [traversalOutput] + +theorem traversalOutput_frame (F : Target.Formula) (hD : 0 < D) + (k : SourceGeneratorModel.Tape u D) (hk : k ≠ accumulatorTape u D) : + traversalOutput F hD k = SourceStartup.readyTapes F k := by + simp [traversalOutput, hk] + +def resetLabel (u D : Nat) (i : Nat) : SourceGeneratorProgram.Label u D := + if h : i < u then .reset ⟨i, h⟩ else .finishEnter + +theorem traversalInTime (F : Target.Formula) (hm : 0 < F.clauses.length) (hD : 0 < D) : + Nonempty (StateTransition.EvalsToInTime (TM2.step (SourceGeneratorProgram.program u D hD)) + ⟨some (bodyEntry u D), (initialAmbient u D hD, none), SourceStartup.readyTapes F⟩ + (some ⟨some .finishEnter, (initialAmbient u D hD, none), traversalOutput F hD⟩) + (((SourceTupleBound.bodyPolynomial u D).eval (formulaBits F).length + 2 * u) * + F.clauses.length ^ u)) := by + have hne : F.clauses ≠ [] := List.length_pos_iff.mp hm + obtain ⟨run⟩ := SourceOdometerSchedule.traversalInTime + (SourceGeneratorProgram.program u D hD) (bodyEntry u D) (next u D) (resetLabel u D) + (initialAmbient u D hD) (accumulatorRole u D) hm + ((SourceTupleBound.bodyPolynomial u D).eval (formulaBits F).length) + (SourceStartup.readyTapes F) (SourceQueryOrder.tupleBits F u D) + (by intro i hi + simp only [next, resetLabel, currentAt, remainingAt, hi, ↓reduceDIte] + rfl) + (by intro i hi + simp only [resetLabel, currentAt, remainingAt, hi, ↓reduceDIte] + rfl) + (actual_bodies F hD) + refine ⟨?_⟩ + have hs : initialConfiguration (m := F.clauses.length) u (bodyEntry u D) + (initialAmbient u D hD) (SourceStartup.readyTapes F) = + (⟨some (bodyEntry u D), (initialAmbient u D hD, none), SourceStartup.readyTapes F⟩ : + TM2.Cfg (fun _ : SourceGeneratorModel.Tape u D => Bool) + (SourceGeneratorProgram.Label u D) (SourceGeneratorProgram.State u D)) := by + rw [initialConfiguration, configuration, resetDigits_ready] + have hf : finalConfiguration (next u D u) (initialAmbient u D hD) (accumulatorRole u D) + (SourceStartup.readyTapes F) (SourceQueryOrder.tupleBits F u D) = + (⟨some .finishEnter, (initialAmbient u D hD, none), traversalOutput F hD⟩ : + TM2.Cfg (fun _ : SourceGeneratorModel.Tape u D => Bool) + (SourceGeneratorProgram.Label u D) (SourceGeneratorProgram.State u D)) := by + unfold finalConfiguration configuration + rw [setDigits_setAcc, resetDigits_ready] + change (⟨some (next u D u), (initialAmbient u D hD, none), + setAcc (accumulatorRole u D) (SourceStartup.readyTapes F) + ((allBits (SourceQueryOrder.tupleBits F u D)).reverse ++ + SourceStartup.readyTapes F (accumulatorTape u D))⟩ : + TM2.Cfg (fun _ : SourceGeneratorModel.Tape u D => Bool) + (SourceGeneratorProgram.Label u D) (SourceGeneratorProgram.State u D)) = _ + rw [accumulated_eq_input F hD hne] + simp only [next, Nat.lt_irrefl, ↓reduceDIte] + rfl + simpa only [hs, hf] using run + +def timePolynomial (u D : Nat) : Polynomial Nat := + (SourceTupleBound.bodyPolynomial u D + Polynomial.C (2 * u)) * Polynomial.X ^ u + +theorem traversalInPolynomialTime (F : Target.Formula) + (hm : 0 < F.clauses.length) (hD : 0 < D) : + Nonempty (StateTransition.EvalsToInTime (TM2.step (SourceGeneratorProgram.program u D hD)) + ⟨some (bodyEntry u D), (initialAmbient u D hD, none), SourceStartup.readyTapes F⟩ + (some ⟨some .finishEnter, (initialAmbient u D hD, none), traversalOutput F hD⟩) + ((timePolynomial u D).eval (formulaBits F).length)) := by + obtain ⟨run⟩ := traversalInTime F hm hD + refine ⟨{ toEvalsTo := run.toEvalsTo, steps_le_m := ?_ }⟩ + apply run.steps_le_m.trans + simp only [timePolynomial, Polynomial.eval_mul, Polynomial.eval_add, Polynomial.eval_C, + Polynomial.eval_pow, Polynomial.eval_X] + exact Nat.mul_le_mul_left _ + (Nat.pow_le_pow_left (SourceBounds.formulaBits_length_ge_clauses F) u) + +end + +end MinUncutGames.Foundations.Hastad.SourceGeneratorTraversal + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/UniformRestriction.lean b/lean/OAI/Computability/MinUncut/PCP/UniformRestriction.lean new file mode 100644 index 0000000000000000000000000000000000000000..00be9466270fcc645f93ba1ec6c65eccd7b7bf3d --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/UniformRestriction.lean @@ -0,0 +1,104 @@ +import Mathlib +import OAI.Computability.MinUncut.Model + +namespace OAI + +section +namespace MinUncutGames.Foundations.PCP.UniformRestriction + +open scoped BigOperators + +variable {B : Type*} (p : B → Prop) + +def restrict (f : B → Bool) : {b // p b} → Bool := fun b => f b.1 + +variable [DecidablePred p] + +def extend (g : {b // p b} → Bool) : B → Bool := + fun b => if hb : p b then g ⟨b, hb⟩ else false + +def canonicalize (f : B → Bool) : B → Bool := extend p (restrict p f) + +omit [DecidablePred p] in +@[simp] theorem restrict_apply (f : B → Bool) (b : {b // p b}) : + restrict p f b = f b.1 := rfl + +@[simp] theorem extend_apply_of_mem (g : {b // p b} → Bool) (b : B) (hb : p b) : + extend p g b = g ⟨b, hb⟩ := by + simp [extend, hb] + +@[simp] theorem extend_apply_of_not_mem (g : {b // p b} → Bool) (b : B) + (hb : ¬ p b) : extend p g b = false := by + simp [extend, hb] + +@[simp] theorem restrict_extend (g : {b // p b} → Bool) : + restrict p (extend p g) = g := by + funext b + simp [restrict, extend, b.property] + +@[simp] theorem canonicalize_apply_of_mem (f : B → Bool) (b : B) (hb : p b) : + canonicalize p f b = f b := by + simp [canonicalize, hb] + +@[simp] theorem canonicalize_apply_of_not_mem (f : B → Bool) (b : B) + (hb : ¬ p b) : canonicalize p f b = false := by + simp [canonicalize, hb] + +@[simp] theorem restrict_canonicalize (f : B → Bool) : + restrict p (canonicalize p f) = restrict p f := by + exact restrict_extend p (restrict p f) + +@[simp] theorem canonicalize_idempotent (f : B → Bool) : + canonicalize p (canonicalize p f) = canonicalize p f := by + simp only [canonicalize, restrict_extend] + +theorem canonicalize_eq_iff (f g : B → Bool) : + canonicalize p f = canonicalize p g ↔ restrict p f = restrict p g := by + constructor + · intro h + simpa only [restrict_canonicalize] using congrArg (restrict p) h + · intro h + exact congrArg (extend p) h + +section Finite + +variable [Fintype B] [DecidableEq B] + +theorem expect_restrict (h : ({b // p b} → Bool) → ℝ) : + (𝔼 f : B → Bool, h (restrict p f)) = 𝔼 g : {b // p b} → Bool, h g := by + calc + (𝔼 f : B → Bool, h (restrict p f)) = + 𝔼 g : ({b // p b} → Bool) × ({b // ¬ p b} → Bool), h g.1 := + Fintype.expect_equiv (Equiv.piEquivPiSubtypeProd p (fun _ => Bool)) + _ _ (fun _ => rfl) + _ = 𝔼 g : {b // p b} → Bool, 𝔼 _k : {b // ¬ p b} → Bool, h g := by + simpa only [Finset.univ_product_univ] using + Finset.expect_product + (Finset.univ : Finset ({b // p b} → Bool)) + (Finset.univ : Finset ({b // ¬ p b} → Bool)) + (fun g : ({b // p b} → Bool) × ({b // ¬ p b} → Bool) => h g.1) + _ = 𝔼 g : {b // p b} → Bool, h g := by + simp only [Fintype.expect_const] + +theorem expect_canonicalize (h : (B → Bool) → ℝ) : + (𝔼 f : B → Bool, h (canonicalize p f)) = + 𝔼 g : {b // p b} → Bool, h (extend p g) := + expect_restrict p (fun g => h (extend p g)) + +theorem expect_restrict_pair (h : ({b // p b} → Bool) → ({b // p b} → Bool) → ℝ) : + (𝔼 f : B → Bool, 𝔼 g : B → Bool, h (restrict p f) (restrict p g)) = + 𝔼 f : {b // p b} → Bool, 𝔼 g : {b // p b} → Bool, h f g := by + calc + _ = 𝔼 f : B → Bool, 𝔼 g : {b // p b} → Bool, h (restrict p f) g := by + apply Finset.expect_congr rfl + intro f _ + exact expect_restrict p (h (restrict p f)) + _ = _ := expect_restrict p (fun f => 𝔼 g : {b // p b} → Bool, h f g) + +end Finite + +end MinUncutGames.Foundations.PCP.UniformRestriction + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/PCP/Walsh.lean b/lean/OAI/Computability/MinUncut/PCP/Walsh.lean new file mode 100644 index 0000000000000000000000000000000000000000..016fe3a3a55b8d86fe33a0f8f3cde12efc1ad82b --- /dev/null +++ b/lean/OAI/Computability/MinUncut/PCP/Walsh.lean @@ -0,0 +1,126 @@ +import Mathlib +import OAI.Computability.MinUncut.Model + +namespace OAI + +section +noncomputable section + +namespace MinUncutGames.Foundations.Hastad + +open scoped BigOperators +open Finset + +abbrev Cube (I : Type*) := I → Bool + +def bitSign (b : Bool) : ℝ := if b then -1 else 1 + +@[simp] theorem bitSign_sq (b : Bool) : bitSign b ^ 2 = 1 := by + cases b <;> norm_num [bitSign] + +theorem bitSign_xor (b c : Bool) : + bitSign (b ^^ c) = bitSign b * bitSign c := by + cases b <;> cases c <;> norm_num [bitSign] + +def cubeXor {I : Type*} (x y : Cube I) : Cube I := fun i => x i ^^ y i + +def walsh {I : Type*} [Fintype I] [DecidableEq I] (s x : Cube I) : ℝ := + ∏ i, bitSign (s i && x i) + +theorem walsh_symm {I : Type*} [Fintype I] [DecidableEq I] (s x : Cube I) : + walsh s x = walsh x s := by + simp [walsh, Bool.and_comm] + +@[simp] theorem walsh_sq {I : Type*} [Fintype I] [DecidableEq I] (s x : Cube I) : + walsh s x ^ 2 = 1 := by + simp [walsh, ← Finset.prod_pow] + +theorem walsh_xor {I : Type*} [Fintype I] [DecidableEq I] (s x y : Cube I) : + walsh s (cubeXor x y) = walsh s x * walsh s y := by + simp only [walsh, ← Finset.prod_mul_distrib] + apply Finset.prod_congr rfl + intro i _ + simp only [cubeXor] + cases s i <;> cases x i <;> cases y i <;> norm_num [bitSign] + +theorem coordinate_orthogonality (s t : Bool) : + (∑ x : Bool, bitSign (s && x) * bitSign (t && x)) = + if s = t then 2 else 0 := by + cases s <;> cases t <;> norm_num [bitSign, Fintype.sum_bool] + +theorem walsh_sum_orthogonality {I : Type*} [Fintype I] [DecidableEq I] + (s t : Cube I) : + (∑ x, walsh s x * walsh t x) = + if s = t then (Fintype.card (Cube I) : ℝ) else 0 := by + classical + simp only [walsh, ← Finset.prod_mul_distrib] + rw [← Fintype.prod_sum (fun (i : I) (b : Bool) => + bitSign (s i && b) * bitSign (t i && b))] + simp only [coordinate_orthogonality] + by_cases h : s = t + · subst t + simp + · rw [ite_eq_right h] + obtain ⟨i, hi⟩ := Function.ne_iff.mp h + apply Finset.prod_eq_zero (Finset.mem_univ i) + exact ite_eq_right hi + +theorem walsh_orthogonality {I : Type*} [Fintype I] [DecidableEq I] + (s t : Cube I) : + (𝔼 x, walsh s x * walsh t x) = if s = t then 1 else 0 := by + classical + rw [Fintype.expect_eq_sum_div_card, walsh_sum_orthogonality] + split_ifs <;> simp + +def coefficient {I : Type*} [Fintype I] [DecidableEq I] (f : Cube I → ℝ) (s : Cube I) : ℝ := + 𝔼 x, f x * walsh s x + +theorem walsh_inversion {I : Type*} [Fintype I] [DecidableEq I] (f : Cube I → ℝ) (x : Cube I) : + (∑ s, coefficient f s * walsh s x) = f x := by + classical + unfold coefficient + simp_rw [Finset.expect_mul] + rw [← Finset.expect_sum_comm] + have h (y : Cube I) : + (∑ s, (f y * walsh s y) * walsh s x) = + f y * (if y = x then (Fintype.card (Cube I) : ℝ) else 0) := by + simp only [mul_assoc, ← Finset.mul_sum] + congr 1 + simp_rw [walsh_symm (x := y), walsh_symm (x := x)] + exact walsh_sum_orthogonality y x + simp_rw [h] + rw [Fintype.expect_eq_sum_div_card] + simp + +theorem walsh_inner {I : Type*} [Fintype I] [DecidableEq I] (f g : Cube I → ℝ) : + (∑ s, coefficient f s * coefficient g s) = 𝔼 x, f x * g x := by + classical + unfold coefficient + simp_rw [Finset.mul_expect] + rw [← Finset.expect_sum_comm] + apply Finset.expect_congr rfl + intro x _ + have h : (∑ s, (𝔼 y, f y * walsh s y) * (g x * walsh s x)) = + g x * (∑ s, coefficient f s * walsh s x) := by + simp only [Finset.mul_sum, coefficient] + apply Finset.sum_congr rfl + intro s _ + ring + rw [h, walsh_inversion] + ring + +theorem walsh_parseval {I : Type*} [Fintype I] [DecidableEq I] (f : Cube I → ℝ) : + (∑ s, coefficient f s ^ 2) = 𝔼 x, f x ^ 2 := by + simpa [pow_two] using walsh_inner f f + +theorem sign_parseval {I : Type*} [Fintype I] [DecidableEq I] (f : Cube I → Bool) : + (∑ s, coefficient (fun x => bitSign (f x)) s ^ 2) = 1 := by + rw [walsh_parseval] + simp + +end MinUncutGames.Foundations.Hastad + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Search/ArithmeticExpression.lean b/lean/OAI/Computability/MinUncut/Search/ArithmeticExpression.lean new file mode 100644 index 0000000000000000000000000000000000000000..d7b68728198eb6d1cf79a61c55132c2a5c21936b --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Search/ArithmeticExpression.lean @@ -0,0 +1,85 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.IterationMagnitude + +namespace OAI + +section +namespace MinUncut.Costed +inductive AExpr where + | const (n : ℕ) + | reg (i : ℕ) + | add (a b : AExpr) + | sub (a b : AExpr) + | mul (a b : AExpr) + | div (a b : AExpr) + | mod (a b : AExpr) + | eq (a b : AExpr) + | le (a b : AExpr) + | at (a : AExpr) + | cond (e a b : AExpr) + +def AExpr.eval : AExpr → List ℕ → ℕ + | .const n,_ => n + | .reg i,v => (v.drop i).headI + | .add a b,v => a.eval v+b.eval v + | .sub a b,v => a.eval v-b.eval v + | .mul a b,v => a.eval v*b.eval v + | .div a b,v => a.eval v/b.eval v + | .mod a b,v => a.eval v%b.eval v + | .eq a b,v => if a.eval v=b.eval v then 1 else 0 + | .le a b,v => if a.eval v≤b.eval v then 1 else 0 + | .at a,v => (v.drop (a.eval v)).headI + | .cond e a b,v => if e.eval v=0 then a.eval v else b.eval v + +noncomputable def AExpr.program : (a : AExpr) → PolyProgram (fun v=>[a.eval v]) + | .const n => PolyProgram.const n + | .reg i => PolyProgram.projection i + | .add a b => PolyProgram.addOf a.program b.program + | .sub a b => PolyProgram.subOf a.program b.program + | .mul a b => PolyProgram.mulOf a.program b.program + | .div a b => Division.quotient.comp (a.program.cons (b.program.cons PolyProgram.nil)) + | .mod a b => Division.remainder.comp (a.program.cons (b.program.cons PolyProgram.nil)) + | .eq a b => PolyProgram.eqOf a.program b.program + | .le a b => PolyProgram.leOf a.program b.program + | .at a => PolyProgram.dynamic.comp (a.program.cons PolyProgram.id) + | .cond e a b => (PolyProgram.branch e.program a.program b.program).ofEq (by + intro v + change (if e.eval v=0 then [a.eval v] else [b.eval v])=[if e.eval v=0 then a.eval v else b.eval v] + split_ifs <;> rfl) + +def AExpr.pow (a : AExpr) : ℕ → AExpr + | 0 => .const 1 + | n+1 => .mul (a.pow n) a +lemma AExpr.eval_pow (a : AExpr) (n : ℕ) (v : List ℕ) : (a.pow n).eval v=a.eval v^n := by + induction n with + | zero => rfl + | succ n ih => simp only [pow,eval,ih,pow_succ] + +def AExpr.sum : List AExpr → AExpr + | [] => .const 0 + | a::as => .add a (sum as) +lemma AExpr.eval_sum (as : List AExpr) (v : List ℕ) : (sum as).eval v=(as.map (fun a=>a.eval v)).sum := by + induction as with + | nil => rfl + | cons a as ih => simp only [sum,eval,List.map_cons,List.sum_cons,ih] + +def AExpr.lookup (a : AExpr) : List (ℕ × ℕ) → AExpr + | [] => .const 0 + | (i,x)::xs => .cond (.eq a (.const i)) (a.lookup xs) (.const x) +def AExpr.lookupValue (n : ℕ) : List (ℕ × ℕ) → ℕ + | [] => 0 + | (i,x)::xs => if n=i then x else lookupValue n xs +lemma AExpr.eval_lookup (a : AExpr) (xs : List (ℕ × ℕ)) (v : List ℕ) : + (a.lookup xs).eval v=lookupValue (a.eval v) xs := by + induction xs with + | nil => rfl + | cons p xs ih => + rcases p with ⟨i,x⟩ + by_cases h : a.eval v=i <;> simp only [lookup,eval,lookupValue,h,ite_true,ite_false, + Nat.one_ne_zero,ih] + +end MinUncut.Costed + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Search/ArithmeticTactic.lean b/lean/OAI/Computability/MinUncut/Search/ArithmeticTactic.lean new file mode 100644 index 0000000000000000000000000000000000000000..5ed85c942ea361cdf3d2fabadfdbe84d4400ad68 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Search/ArithmeticTactic.lean @@ -0,0 +1,344 @@ +import Mathlib +import OAI.Computability.MinUncut.Search.UniformFiniteSum +import OAI.Computability.MinUncut.Estimates.SamplerAssembly +import OAI.Computability.MinUncut.Search.ParameterFields +import OAI.Computability.MinUncut.Encoding.DerivedResolver + +namespace OAI + +section +syntax "comp_arith" : tactic +open Lean Elab Tactic Meta in +elab_rules : tactic +| `(tactic| comp_arith) => do + let target ← getMainTarget + let fn := target.getAppArgs.back! + let head ← lambdaTelescope fn fun args body => do + let body ← instantiateMVars body + if !args.isEmpty && !(args.any fun a => body.containsFVar a.fvarId!) then return `constant + let name := body.getAppFn.constName? + let ty ← inferType body + let rat := (← whnf ty).isConstOf ``Rat + let n ← match name with + | some ``HAdd.hAdd => pure (if rat then ``MinUncut.Preprocess.ca_ratAdd else ``MinUncut.Preprocess.ca_add) + | some ``HMul.hMul => pure (if rat then ``MinUncut.Preprocess.ca_ratMul else ``MinUncut.Preprocess.ca_mul) + | some ``HSub.hSub => pure (if rat then ``MinUncut.Preprocess.ca_ratSub else ``MinUncut.Preprocess.ca_sub) + | some ``HDiv.hDiv => pure (if rat then ``MinUncut.Preprocess.ca_ratDiv else ``MinUncut.Preprocess.ca_div) + | some ``HMod.hMod => pure ``MinUncut.Preprocess.ca_mod + | some ``HPow.hPow => pure (if rat then ``MinUncut.Preprocess.ca_ratPow else ``MinUncut.Preprocess.ca_pow) + | some ``Inv.inv => pure ``MinUncut.Preprocess.ca_ratInv + | some ``Nat.choose => pure ``MinUncut.Preprocess.ca_choose + | some ``Nat.factorial => pure ``MinUncut.Preprocess.ca_factorial + | some ``Nat.cast => pure ``MinUncut.Preprocess.ca_ratCast + | some ``Nat.ceil => pure ``MinUncut.Preprocess.ca_ratCeil + | some ``And => pure ``MinUncut.Preprocess.ca_and + | some ``LE.le => pure (if body.getAppArgs[0]!.isConstOf ``Rat then ``MinUncut.Preprocess.ca_ratLe else ``MinUncut.Preprocess.ca_natLe) + | some ``LT.lt => pure (if body.getAppArgs[0]!.isConstOf ``Rat then ``MinUncut.Preprocess.ca_ratLt else ``MinUncut.Preprocess.ca_natLt) + | _ => pure `fallback + return n + if head == `constant then evalTactic (← `(tactic| exact MinUncut.Preprocess.ca_const _)) + else if head == `fallback then evalTactic (← `(tactic| fun_prop)) + else + evalTactic (← `(tactic| apply $(mkIdent head))) + evalTactic (← `(tactic| all_goals comp_arith)) + +end +section +namespace MinUncut.Preprocess +open MinUncut.Inner MinUncut.Outer MinUncut.FiniteGaussian +@[fun_prop] lemma c_epsilon : Computable (fun p : ℕ × ℕ=>InnerData.epsilon p.1 p.2) := by + unfold InnerData.epsilon + exact ca_ratDiv (ca_const 1) (ca_ratMul + (ca_ratMul (ca_const 40) (ca_ratCast (c_T.comp Computable.fst))) + (ca_ratAdd (ca_ratCast (ca_pow Computable.snd (ca_const 2))) (ca_const 1))) +@[fun_prop] lemma c_atomConstant : Computable (fun p : ℕ × ℕ × ℕ=>InnerData.atomConstant p.1 p.2.1 p.2.2) := by + unfold InnerData.atomConstant + apply ca_mul + · apply ca_pow <;> fun_prop + · apply ca_choose + · apply ca_add + · apply ca_pow <;> fun_prop + · fun_prop + · fun_prop + +lemma inner_check_0 : ComputablePred (fun p : ℕ × InnerData => + 2 ≤ p.2.m) := by comp_arith + +lemma inner_check_1 : ComputablePred (fun p : ℕ × InnerData => + p.2.k+2 ≤ p.2.n) := by comp_arith + +lemma inner_check_2 : ComputablePred (fun p : ℕ × InnerData => + 1 ≤ p.2.k) := by comp_arith + +lemma inner_check_3 : ComputablePred (fun p : ℕ × InnerData => + 0 < p.2.H) := by comp_arith + +lemma inner_check_4 : ComputablePred (fun p : ℕ × InnerData => + 0 < p.2.A) := by comp_arith + +lemma inner_check_5 : ComputablePred (fun p : ℕ × InnerData => + 0 < p.2.γ) := by comp_arith + +lemma inner_check_6 : ComputablePred (fun p : ℕ × InnerData => + 0 < p.2.p) := by comp_arith + +lemma inner_check_7 : ComputablePred (fun p : ℕ × InnerData => + p.2.p < 1) := by comp_arith + +lemma inner_check_8 : ComputablePred (fun p : ℕ × InnerData => + 0 < p.2.θ) := by comp_arith + +lemma inner_check_9 : ComputablePred (fun p : ℕ × InnerData => + p.2.θ < 1) := by comp_arith + +lemma inner_check_10 : ComputablePred (fun p : ℕ × InnerData => + ((p.2.s:ℚ)+3)*(1+rationalSigma p.1^2)⁻¹ ≤ (p.2.s:ℚ)+2) := by comp_arith + +lemma inner_check_11 : ComputablePred (fun p : ℕ × InnerData => + ((p.2.s:ℚ)+2)*((1+rationalSigma p.1^2)⁻¹)^(p.2.s+2) ≤ 1/16) := by comp_arith + +lemma inner_check_12 : ComputablePred (fun p : ℕ × InnerData => + rationalR p.1*p.2.m < (p.2.m-p.2.s).choose 2) := by comp_arith + +lemma inner_check_13 : ComputablePred (fun p : ℕ × InnerData => + ((p.2.s+rationalR p.1*p.2.m:ℕ):ℚ)*(p.2.k:ℚ)/((p.2.n:ℚ)-1) < (InnerData.epsilon p.1 p.2.m*rationalSigma p.1)^2) := by comp_arith + +lemma inner_check_14 : ComputablePred (fun p : ℕ × InnerData => + (rationalSigma p.1)⁻¹^2/(p.2.H:ℚ) < InnerData.epsilon p.1 p.2.m) := by comp_arith + +lemma inner_check_15 : ComputablePred (fun p : ℕ × InnerData => + 2*(rationalSigma p.1)⁻¹^2/(p.2.A:ℚ) < InnerData.epsilon p.1 p.2.m) := by comp_arith + +lemma inner_check_16 : ComputablePred (fun p : ℕ × InnerData => + (p.2.m:ℚ)/((p.2.k:ℚ)+1) < (InnerData.epsilon p.1 p.2.m/(2*(p.2.A:ℚ)))^(2^p.2.m)) := by comp_arith + +lemma inner_check_17 : ComputablePred (fun p : ℕ × InnerData => + (p.2.H:ℚ)*(p.2.γ+(p.2.H:ℚ)^2/(p.2.A:ℚ)) < InnerData.epsilon p.1 p.2.m^2) := by comp_arith + +lemma inner_check_18 : ComputablePred (fun p : ℕ × InnerData => + p.2.θ^2+(p.2.m:ℚ)*p.2.p*(p.2.n^p.2.m:ℕ)/(rationalSigma p.1)^2 < + (InnerData.epsilon p.1 p.2.m^2*(rationalSigma p.1)^2*p.2.γ/(InnerData.atomConstant p.2.s p.2.m p.2.n:ℚ))^2) := by comp_arith + +lemma inner_check_computable : ComputablePred (fun p : ℕ × InnerData=>p.2.Check p.1) := + ca_and inner_check_0 (ca_and inner_check_1 (ca_and inner_check_2 (ca_and inner_check_3 (ca_and inner_check_4 (ca_and inner_check_5 (ca_and inner_check_6 (ca_and inner_check_7 (ca_and inner_check_8 (ca_and inner_check_9 (ca_and inner_check_10 (ca_and inner_check_11 (ca_and inner_check_12 (ca_and inner_check_13 (ca_and inner_check_14 (ca_and inner_check_15 (ca_and inner_check_16 (ca_and inner_check_17 (inner_check_18)))))))))))))))))) + +@[fun_prop] lemma c_amplitude : Computable (fun p : ℕ × InnerData=>OuterData.amplitude p.1 p.2) := by + unfold OuterData.amplitude; comp_arith +@[fun_prop] lemma c_hints : Computable OuterData.hints := by + unfold OuterData.hints + apply ca_sub + · apply ca_mul + · exact c_innerData_m + · apply ca_pow + · exact c_innerData_n + · apply ca_sub + · exact c_innerData_m + · exact ca_const 1 + · exact ca_const 1 +@[fun_prop] lemma c_rate : Computable OuterData.rate := by unfold OuterData.rate; fun_prop +lemma c_listBound : Computable (fun p : ℕ × InnerData × OuterData=>OuterData.listBound p.1 p.2.1 p.2.2) := by + unfold OuterData.listBound; comp_arith +lemma c_radicand : Computable (fun p : InnerData × ℕ × ℕ=>OuterData.radicand p.1 p.2.1 p.2.2) := by + unfold OuterData.radicand; comp_arith +attribute [fun_prop] c_listBound c_radicand +@[fun_prop] lemma c_oTheta : Computable (fun p : ℕ × InnerData × OuterData=>p.2.1.θ) := + c_innerData_θ.comp (Computable.fst.comp Computable.snd) +@[fun_prop] lemma c_oP : Computable (fun p : ℕ × InnerData × OuterData=>p.2.1.p) := + c_innerData_p.comp (Computable.fst.comp Computable.snd) +@[fun_prop] lemma c_oB4 : Computable (fun p : ℕ × InnerData × OuterData=>p.2.2.b4) := + c_outerData_b4.comp (Computable.snd.comp Computable.snd) +lemma outer_check_0 : ComputablePred (fun p : ℕ × InnerData × OuterData=>0 < p.2.2.u) := by comp_arith +lemma outer_check_1 : ComputablePred (fun p : ℕ × InnerData × OuterData=>0 < p.2.2.b4) := by comp_arith +lemma outer_check_2 : ComputablePred (fun p : ℕ × InnerData × OuterData=>0 < p.2.2.v) := by comp_arith +lemma outer_check_3 : ComputablePred (fun p : ℕ × InnerData × OuterData=>1 ≤ p.2.2.t) := by comp_arith +lemma outer_check_4 : ComputablePred (fun p : ℕ × InnerData × OuterData=>p.2.2.k ≤ p.2.2.t) := by comp_arith +lemma outer_check_5 : ComputablePred (fun p : ℕ × InnerData × OuterData=>OuterData.listBound p.1 p.2.1 p.2.2 < p.2.1.p/4) := by comp_arith +lemma outer_check_6 : ComputablePred (fun p : ℕ × InnerData × OuterData=>(64/(p.2.1.θ^2*rationalSigma p.1^2))*(p.1:ℚ)*p.2.2.b4 < p.2.1.p/4) := by comp_arith +lemma outer_check_7 : ComputablePred (fun p : ℕ × InnerData × OuterData=>OuterData.radicand p.2.1 p.2.2.k p.2.2.t < p.2.2.v^2) := by comp_arith +lemma outer_check_8 : ComputablePred (fun p : ℕ × InnerData × OuterData=>(256/p.2.1.θ^4)*(p.2.2.u^2*OuterData.amplitude p.1 p.2.1^2+p.2.2.v*(OuterData.amplitude p.1 p.2.1+OuterData.amplitude p.1 p.2.1^2/p.2.2.u)^4) < p.2.1.p/2) := by comp_arith +lemma outer_check_computable : ComputablePred (fun p : ℕ × InnerData × OuterData=>p.2.2.Check p.1 p.2.1) := + ca_and outer_check_0 (ca_and outer_check_1 (ca_and outer_check_2 (ca_and outer_check_3 (ca_and outer_check_4 (ca_and outer_check_5 (ca_and outer_check_6 (ca_and outer_check_7 (outer_check_8)))))))) +lemma c_qError : Computable (fun p : ℕ × ℚ=>qError p.1 p.2) := by unfold qError; comp_arith +attribute [fun_prop] c_qError +@[fun_prop] lemma c_gT : Computable (fun p : ℕ × ℕ × ℚ × ℚ × GridData=>p.2.2.2.2.T) := + c_gridData_T.comp (Computable.snd.comp (Computable.snd.comp (Computable.snd.comp Computable.snd))) +@[fun_prop] lemma c_gL : Computable (fun p : ℕ × ℕ × ℚ × ℚ × GridData=>p.2.2.2.2.L) := + c_gridData_L.comp (Computable.snd.comp (Computable.snd.comp (Computable.snd.comp Computable.snd))) +@[fun_prop] lemma c_gr : Computable (fun p : ℕ × ℕ × ℚ × ℚ × GridData=>p.2.2.2.2.r) := + c_gridData_r.comp (Computable.snd.comp (Computable.snd.comp (Computable.snd.comp Computable.snd))) +@[fun_prop] lemma c_gE : Computable (fun p : ℕ × ℕ × ℚ × ℚ × GridData=>p.2.2.2.1) := + Computable.fst.comp (Computable.snd.comp (Computable.snd.comp Computable.snd)) +lemma grid_check_0 : ComputablePred (fun p : ℕ × ℕ × ℚ × ℚ × GridData=>1 ≤ p.2.2.2.2.T) := by comp_arith +lemma grid_check_1 : ComputablePred (fun p : ℕ × ℕ × ℚ × ℚ × GridData=>1 ≤ p.2.2.2.2.L) := by comp_arith +lemma grid_check_2 : ComputablePred (fun p : ℕ × ℕ × ℚ × ℚ × GridData=>(p.1:ℚ)/(p.2.2.2.2.T:ℚ)^2 < p.2.2.2.1/4) := + ca_ratLt (ca_ratDiv (ca_ratCast Computable.fst) (ca_ratPow (ca_ratCast c_gT) (ca_const 2))) + (ca_ratDiv c_gE (ca_const 4)) +lemma grid_check_3 : ComputablePred (fun p : ℕ × ℕ × ℚ × ℚ × GridData=>2*(p.2.1:ℚ)*p.2.2.1*p.2.2.2.2.T/p.2.2.2.2.L < p.2.2.2.1/4) := + ca_ratLt (ca_ratDiv (ca_ratMul (ca_ratMul + (ca_ratMul (ca_const 2) (ca_ratCast (Computable.fst.comp Computable.snd))) + (Computable.fst.comp (Computable.snd.comp Computable.snd))) (ca_ratCast c_gT)) (ca_ratCast c_gL)) + (ca_ratDiv c_gE (ca_const 4)) +lemma c_gErrorArg : Computable (fun p : ℕ × ℕ × ℚ × ℚ × GridData=>((p.2.2.2.2.T:ℚ)^2/2)) := + ca_ratDiv (ca_ratPow (ca_ratCast c_gT) (ca_const 2)) (ca_const 2) +lemma c_gError : Computable (fun p : ℕ × ℕ × ℚ × ℚ × GridData=>qError p.2.2.2.2.r ((p.2.2.2.2.T:ℚ)^2/2)) := + (c_qError.comp (c_gr.pair c_gErrorArg)).of_eq (by intro p; rfl) +lemma c_gCoef : Computable (fun p : ℕ × ℕ × ℚ × ℚ × GridData=>2*(p.1:ℚ)*p.2.2.2.2.T) := + ca_ratMul (ca_ratMul (ca_const 2) (ca_ratCast Computable.fst)) (ca_ratCast c_gT) +lemma grid_check_4 : ComputablePred (fun p : ℕ × ℕ × ℚ × ℚ × GridData=>2*(p.1:ℚ)*p.2.2.2.2.T*qError p.2.2.2.2.r ((p.2.2.2.2.T:ℚ)^2/2) < p.2.2.2.1/4) := + ca_ratLt (ca_ratMul c_gCoef c_gError) (ca_ratDiv c_gE (ca_const 4)) +lemma grid_check_computable : ComputablePred (fun p : ℕ × ℕ × ℚ × ℚ × GridData=>p.2.2.2.2.Check p.1 p.2.1 p.2.2.1 p.2.2.2.1) := + ca_and grid_check_0 (ca_and grid_check_1 (ca_and grid_check_2 (ca_and grid_check_3 (grid_check_4)))) +end MinUncut.Preprocess + +end +section +namespace MinUncut.Preprocess +open MinUncut.FiniteGaussian + +def gridTail (n : ℕ) : ℕ := n.unpair.2 +def gridField (n : ℕ) : ℕ := (n.unpair.1-1).unpair.2 +def gridExtract (n : ℕ) : GridData := + ⟨gridField (gridTail n),gridField (gridTail (gridTail n)), + gridField (gridTail (gridTail (gridTail n)))⟩ +lemma gridExtract_encode (g : GridData) : gridExtract (oldGridEncode g)=g := by + simp only [oldGridEncode_eq,gridExtract,gridTail,gridField,Nat.unpair_pair,Nat.add_sub_cancel_right] +lemma gridDecode_eq (n : ℕ) : oldGridDecode n = + if oldGridEncode (gridExtract n)=n then some (gridExtract n) else none := by + cases h : oldGridDecode n with + | none => + split + · next he => + have hk := @Encodable.encodek GridData instEncodableGridData (gridExtract n) + change oldGridDecode (oldGridEncode (gridExtract n))=some (gridExtract n) at hk + rw [he,h] at hk + cases hk + · rfl + | some g => + have he := oldGridDecode_canonical n g h + have hx : gridExtract n=g := by rw [←he,gridExtract_encode] + simp only [hx,he,ite_true] + +@[fun_prop] lemma c_gridTail : Computable gridTail := Computable.snd.comp Computable.unpair +@[fun_prop] lemma c_gridField : Computable gridField := + Computable.snd.comp (Computable.unpair.comp + (ca_sub (Computable.fst.comp Computable.unpair) (ca_const 1))) +lemma c_gridMk : Computable gridDataEquiv.symm := + (Primrec.of_equiv_symm (e:=gridDataEquiv)).to_comp +lemma gridExtract_eq : gridExtract = fun n => gridDataEquiv.symm + (gridField (gridTail n),gridField (gridTail (gridTail n)), + gridField (gridTail (gridTail (gridTail n)))) := by + funext n + simp only [gridExtract,gridDataEquiv,Equiv.coe_fn_symm_mk] +lemma c_gridExtract₁ : Computable (fun n=>gridField (gridTail n)) := + c_gridField.comp c_gridTail +lemma c_gridExtract₂ : Computable (fun n=>gridField (gridTail (gridTail n))) := + c_gridExtract₁.comp c_gridTail +lemma c_gridExtract₃ : Computable (fun n=>gridField (gridTail (gridTail (gridTail n)))) := + c_gridExtract₂.comp c_gridTail +lemma c_gridExtractPair : Computable (fun n=>(gridField (gridTail n), + gridField (gridTail (gridTail n)),gridField (gridTail (gridTail (gridTail n))))) := + c_gridExtract₁.pair (c_gridExtract₂.pair c_gridExtract₃) +lemma c_gridExtract : Computable gridExtract := by + rw [gridExtract_eq] + exact c_gridMk.comp c_gridExtractPair +lemma c_oldGridEncode : Computable oldGridEncode := by + have hp : Computable₂ Nat.pair := Primrec₂.natPair.to_comp + rw [show oldGridEncode=(fun g : GridData=>Nat.pair (Nat.pair 0 0+1) + (Nat.pair (Nat.pair 0 g.T+1) (Nat.pair (Nat.pair 0 g.L+1) + (Nat.pair (Nat.pair 0 g.r+1) (Nat.pair 0 0))))) from funext oldGridEncode_eq] + exact hp.comp (ca_const _) (hp.comp (ca_add (hp.comp (ca_const 0) c_gridData_T) (ca_const 1)) + (hp.comp (ca_add (hp.comp (ca_const 0) c_gridData_L) (ca_const 1)) + (hp.comp (ca_add (hp.comp (ca_const 0) c_gridData_r) (ca_const 1)) (ca_const _)))) +lemma c_oldGridDecode : Computable oldGridDecode := by + have he : ComputablePred (fun n=>oldGridEncode (gridExtract n)=n) := + (Primrec.eq.computablePred.decide.comp ((c_oldGridEncode.comp c_gridExtract).pair Computable.id)).computablePred + exact (Computable.cond he.decide (Computable.option_some.comp c_gridExtract) (ca_const none)).of_eq + (by intro n; simp only [Bool.cond_decide]; exact (gridDecode_eq n).symm) +end MinUncut.Preprocess + +end +section +namespace MinUncut.Preprocess +open MinUncut.Inner MinUncut.Outer MinUncut.FiniteGaussian + +def parameterJ (K : ℕ) : ℕ := 10*(max K 2) +lemma parameterJ_pos (K : ℕ) : 1≤parameterJ K := by unfold parameterJ; omega +lemma parameterJ_eq (K : ℕ) (hK : 2≤K) : parameterJ K=10*K := by + unfold parameterJ + rw [max_eq_left hK] +@[fun_prop] lemma c_parameterJ : Computable parameterJ := by + have h : Computable (fun K : ℕ=>10*(K+(2-K))) := by fun_prop + exact h.of_eq (by intro K; unfold parameterJ; congr 1; omega) +lemma inner_exists (K : ℕ) : ∃d : InnerData,d.Check (parameterJ K) := + InnerData.check_exists (parameterJ_pos K) +noncomputable def selectedInner (K : ℕ) : InnerData := search inner_exists K +lemma selectedInner_check (K : ℕ) : (selectedInner K).Check (parameterJ K) := + search_spec inner_exists K +lemma c_inner_pred : ComputablePred (fun p : ℕ × InnerData=>p.2.Check (parameterJ p.1)) := + (inner_check_computable.decide.comp ((c_parameterJ.comp Computable.fst).pair Computable.snd)).computablePred +@[fun_prop] lemma c_selectedInner : Computable selectedInner := + computable_search c_inner_pred inner_exists ⟨0,0,0,0,0,0,0,0,0⟩ + +attribute [local irreducible] selectedInner + +lemma outer_exists (K : ℕ) : ∃o : OuterData,o.Check (parameterJ K) (selectedInner K) := + OuterData.check_exists (parameterJ_pos K) _ (selectedInner_check K) +noncomputable def selectedOuter (K : ℕ) : OuterData := search outer_exists K +lemma selectedOuter_check (K : ℕ) : (selectedOuter K).Check (parameterJ K) (selectedInner K) := + search_spec outer_exists K +lemma c_outer_arguments : Computable (fun p : ℕ × OuterData => + (parameterJ p.1,selectedInner p.1,p.2)) := by + exact (c_parameterJ.comp Computable.fst).pair + ((c_selectedInner.comp Computable.fst).pair Computable.snd) +lemma c_outer_decide : Computable (fun p : ℕ × OuterData => + decide (p.2.Check (parameterJ p.1) (selectedInner p.1))) := by + have hh : Computable (fun p : ℕ × InnerData × OuterData=>decide (p.2.2.Check p.1 p.2.1)) := + outer_check_computable.decide + exact @Computable.comp (ℕ × OuterData) (ℕ × InnerData × OuterData) Bool _ _ _ + (fun p=>decide (p.2.2.Check p.1 p.2.1)) (fun p=>(parameterJ p.1,selectedInner p.1,p.2)) hh c_outer_arguments +lemma c_outer_pred : ComputablePred (fun p : ℕ × OuterData=>p.2.Check (parameterJ p.1) (selectedInner p.1)) := + c_outer_decide.computablePred +@[fun_prop] lemma c_selectedOuter : Computable selectedOuter := + computable_search c_outer_pred outer_exists ⟨0,0,0,0,0⟩ +noncomputable def selectedParameters (K : ℕ) : Parameters (parameterJ K) := + ⟨parameterJ_pos K,selectedInner K,selectedInner_check K,selectedOuter K,selectedOuter_check K⟩ + +def gridPredicate (x : ℕ × ℕ × ℚ × ℚ) (g : GridData) : Prop := + if 0≤x.2.2.1 ∧ 0by unfold gridPredicate; infer_instance +lemma grid_exists (x : ℕ × ℕ × ℚ × ℚ) : ∃g,gridPredicate x g := by + unfold gridPredicate + split_ifs with h + · exact GridData.exists_check x.1 x.2.1 h.1 h.2 + · exact ⟨_,rfl⟩ +noncomputable def selectedGrid (x : ℕ × ℕ × ℚ × ℚ) : GridData := + searchWith instEncodableGridData grid_exists x +lemma selectedGrid_eq (d S : ℕ) (A ε : ℚ) (hA : 0≤A) (hε : 0<ε) : + selectedGrid (d,S,A,ε)=GridData.select d S A ε hA hε := by + unfold selectedGrid searchWith GridData.select + congr 1 + funext g + simp only [gridPredicate,hA,hε,and_self,ite_true] +lemma c_grid_valid : ComputablePred (fun x : ℕ × ℕ × ℚ × ℚ=>0≤x.2.2.1 ∧ 0gridPredicate p.1 p.2) := by + have hc := grid_check_computable.decide.comp (Computable.fst.comp Computable.fst |>.pair + ((Computable.fst.comp (Computable.snd.comp Computable.fst)).pair + ((Computable.fst.comp (Computable.snd.comp (Computable.snd.comp Computable.fst))).pair + ((Computable.snd.comp (Computable.snd.comp (Computable.snd.comp Computable.fst))).pair Computable.snd)))) + have he : Computable (fun p : (ℕ × ℕ × ℚ × ℚ) × GridData=>decide (p.2=⟨0,0,0⟩)) := + ComputablePred.decide ((Primrec.eq.computablePred.decide.comp + (Computable.snd.pair (ca_const (⟨0,0,0⟩ : GridData)))).computablePred) + have hh := Computable.cond (c_grid_valid.decide.comp Computable.fst) hc he + exact ⟨inferInstance,hh.of_eq (by + intro p + simp only [gridPredicate,Bool.cond_decide] + split_ifs <;> rfl)⟩ +lemma c_selectedGrid : Computable selectedGrid := + computable_searchWith instEncodableGridData c_oldGridDecode c_grid_pred grid_exists ⟨0,0,0⟩ +end MinUncut.Preprocess + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Search/BlockEnumeration.lean b/lean/OAI/Computability/MinUncut/Search/BlockEnumeration.lean new file mode 100644 index 0000000000000000000000000000000000000000..0afae115ba2764914b5675289ae53ebdd17c5dc0 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Search/BlockEnumeration.lean @@ -0,0 +1,169 @@ +import Mathlib +import OAI.Computability.MinUncut.Search.ArithmeticExpression + +namespace OAI + +section +noncomputable section +namespace MinUncut.Costed +open Turing.ToPartrec Polynomial + +namespace PolyProgram + +def variableDrop : PolyProgram (fun v=>v.tail.drop v.headI) where + code := dynamicDrop + bound := C 3000*(X+1)^2 + run v := by + cases v with + | nil => + obtain ⟨t,ht,hc⟩ := run_caseZero (g:=.cons (.comp .succ .zero) + (.cons .head (.comp .tail .tail))) (v:=[]) rfl (run_zero []) + exact ⟨_,by norm_num [magnitude] at ht ⊢; omega,CodeRun.fixDone (u := [0]) hc rfl⟩ + | cons n v => + apply (run_dynamicDrop n v).mono + simp only [eval_mul,eval_C,eval_pow,eval_add,eval_X,eval_one] + have hn : n+1≤ magnitude (n::v)+1 := by simp only [magnitude_cons]; omega + nlinarith + size v := by + have h := (magnitude_drop v.headI v.tail).trans (magnitude_tail v) + simp only [eval_mul,eval_C,eval_pow,eval_add,eval_X,eval_one] + nlinarith + +def expressions {g : List ℕ → List ℕ} (G : PolyProgram g) : + (es : List AExpr) → PolyProgram (fun v=>es.map (fun e=>e.eval v)++g v) + | [] => G + | e::es => e.program.cons (expressions G es) + +end PolyProgram + +namespace Blocks + +def block (es : List AExpr) (i : ℕ) (v : List ℕ) : List ℕ := es.map (fun e=>e.eval (i::v)) +def source (v : List ℕ) : List ℕ := v.drop (v.tail.headI+2) +def step (es : List AExpr) (v : List ℕ) : List ℕ := + (v.headI+1)::(v.tail.headI+es.length)::(block es v.headI (source v)++v.drop 2) + +def extractor : PolyProgram (fun v=>v.headI::source v) := + PolyProgram.head.cons ((PolyProgram.variableDrop.comp + ((PolyProgram.addOf (PolyProgram.projection 1) (PolyProgram.const 2)).cons PolyProgram.id)).ofEq + (by intro v; simp only [Function.comp_def,List.headI_cons,List.tail_cons,List.drop_one,source])) + +def stepProgram (es : List AExpr) : PolyProgram (step es) := + + let pref : PolyProgram (fun v=>block es v.headI (source v)++v.drop 2) := by + let rec go (l : List AExpr) : PolyProgram (fun v=> l.map (fun e=>e.eval (v.headI::source v))++v.drop 2) := + match l with + | [] => PolyProgram.drop 2 + | e::l => (e.program.comp extractor).cons (go l) + exact go es + (PolyProgram.succ.cons + ((PolyProgram.addOf (PolyProgram.projection 1) (PolyProgram.const es.length)).cons pref)).ofEq + (by intro v; simp only [List.headI_cons,List.drop_one,step]) + +@[simp] lemma length_block (es : List AExpr) (i : ℕ) (v : List ℕ) : + (block es i v).length=es.length := by simp [block] + +lemma source_step (es : List AExpr) (v : List ℕ) : source (step es v)=source v := by + simp only [source,step,List.drop_succ_cons,List.headI_cons,List.tail_cons] + rw [show v.tail.headI+es.length=es.length+v.tail.headI by omega,← List.drop_drop] + rw [← length_block es v.headI (v.drop (v.tail.headI+2)),List.drop_left] + rw [List.drop_drop] + congr 1 + omega + +@[simp] lemma head_step (es : List AExpr) (v : List ℕ) : (step es v).headI=v.headI+1 := rfl +@[simp] lemma second_step (es : List AExpr) (v : List ℕ) : (step es v).tail.headI=v.tail.headI+es.length := rfl + +lemma iterate_head (es : List AExpr) (v : List ℕ) (i : ℕ) : + ((step es)^[i] v).headI=v.headI+i := by + induction i with + | zero => simp + | succ i ih => rw [Function.iterate_succ_apply',head_step,ih]; omega +lemma iterate_source (es : List AExpr) (v : List ℕ) (i : ℕ) : + source ((step es)^[i] v)=source v := by + induction i with + | zero => rfl + | succ i ih => rw [Function.iterate_succ_apply',source_step,ih] + +lemma magnitude_append (v w : List ℕ) : magnitude (v++w)=magnitude v+magnitude w := by + induction v with + | nil => simp only [List.nil_append,magnitude_nil,Nat.zero_add] + | cons a v ih => simp only [List.cons_append,magnitude_cons,ih]; omega + +lemma magnitude_step (es : List AExpr) (v : List ℕ) : + magnitude (step es v)≤ magnitude v+es.length+3+magnitude (block es v.headI (source v)) := by + simp only [step,magnitude_cons,magnitude_append] + cases v with + | nil => simp [magnitude]; omega + | cons a v => + cases v with + | nil => simp [magnitude]; omega + | cons b v => simp only [List.headI_cons,List.tail_cons,List.drop_succ_cons,List.drop_zero,magnitude_cons]; omega + +lemma iterate_size (es : List AExpr) (v : List ℕ) (n i : ℕ) (hi : i≤n) : + magnitude ((step es)^[i] v)≤ magnitude v+ + i*(es.length+3+((PolyProgram.expressions PolyProgram.nil es).bound).eval + (n+1+2*magnitude v)) := by + induction i with + | zero => simp + | succ i ih => + have hh := ih (by omega) + have hs := magnitude_step es ((step es)^[i] v) + have hb := (PolyProgram.expressions PolyProgram.nil es).size + (((step es)^[i] v).headI::source ((step es)^[i] v)) + change magnitude (block es _ _++[])≤_ at hb + rw [List.append_nil,iterate_head,iterate_source] at hb + have hm : magnitude ((v.headI+i)::source v)≤n+1+2*magnitude v := by + have h1 := magnitude_head v + have h2 := magnitude_drop (v.tail.headI+2) v + simp only [magnitude_cons,source] + omega + have hb' := hb.trans (evalNat_mono _ hm) + rw [iterate_head,iterate_source] at hs + rw [Function.iterate_succ_apply'] + nlinarith + +def iterationProgram (es : List AExpr) : + PolyProgram (fun v=>(step es)^[v.headI] v.tail) := + PolyProgram.iterate (stepProgram es) + (X+X*(C (es.length+3)+(PolyProgram.expressions PolyProgram.nil es).bound.comp (C 3*X+1))) (by + intro n v i hi + have h := iterate_size es v n i hi + have hv : magnitude v≤ magnitude (n::v) := by simp only [magnitude_cons]; omega + have hi' : i≤ magnitude (n::v) := by simp only [magnitude_cons]; omega + have hn : n+1+2*magnitude v≤3*magnitude (n::v)+1 := by simp only [magnitude_cons]; omega + have hb := evalNat_mono (PolyProgram.expressions PolyProgram.nil es).bound hn + simp only [eval_add,eval_mul,eval_C,eval_comp,eval_X,eval_one] + exact h.trans (Nat.add_le_add hv (Nat.mul_le_mul hi' (Nat.add_le_add_left hb _)))) + +lemma iterate_accumulator (es : List AExpr) (v : List ℕ) (n : ℕ) : + (step es)^[n] (0::0::v)=n::(n*es.length):: + ((List.range n).reverse.flatMap (fun i=>block es i v)++v) := by + induction n with + | zero => simp + | succ n ih => + rw [Function.iterate_succ_apply',ih] + have hs : source (n::(n*es.length)::((List.range n).reverse.flatMap (fun i=>block es i v)++v))=v := by + rw [← ih,iterate_source] + rfl + simp only [step,List.headI_cons,List.tail_cons,hs,List.drop_succ_cons,List.drop_zero, + List.range_succ,List.reverse_append,List.reverse_singleton,List.flatMap_append, + List.flatMap_cons,List.flatMap_nil,List.append_nil,List.append_assoc] + simp only [Nat.add_mul,Nat.one_mul] + +def enumerate (es : List AExpr) (N : AExpr) : PolyProgram (fun v=> + N.eval v::(N.eval v*es.length):: + ((List.range (N.eval v)).reverse.flatMap (fun i=>block es i v)++v)) := + ((iterationProgram es).comp (N.program.cons ((PolyProgram.const 0).cons + ((PolyProgram.const 0).cons PolyProgram.id)))).ofEq (by + intro v + change (step es)^[N.eval v] (0::0::v)=_ + exact iterate_accumulator es v (N.eval v)) + +end Blocks +end MinUncut.Costed + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Search/CodeArithmetic.lean b/lean/OAI/Computability/MinUncut/Search/CodeArithmetic.lean new file mode 100644 index 0000000000000000000000000000000000000000..526e05e0645900d310df5fb4587a7ef2de1177d4 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Search/CodeArithmetic.lean @@ -0,0 +1,100 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.CodeComputability + +namespace OAI + +section +namespace MinUncut.Costed +open Turing.ToPartrec + +def addCode : Code := .prec .head (.comp .succ .tail) +def subCode : Code := .prec .head (.comp .pred .tail) + +lemma run_add (n a : ℕ) (v : List ℕ) : + Runs addCode (n::a::v) [a+n] (100000*(magnitude (n::a::v)+2)^2) := by + let M := magnitude (n::a::v) + have hn : n≤M := by dsimp [M]; omega + have ha : a≤M := by dsimp [M]; omega + have hv : magnitude (a::v)≤M := by dsimp [M]; omega + have hr : ∀i≤n,a+i≤M := by intro i hi; dsimp [M]; omega + have hg : ∀ia+i) (a::v) M + (300*(M+1)) (200*(M+1)) hn hr hv ((run_head (a::v)).mono (by gcongr)) hg + apply hh.mono + dsimp [M] at * + nlinarith + +lemma run_sub (n a : ℕ) (v : List ℕ) : + Runs subCode (n::a::v) [a-n] (100000*(magnitude (n::a::v)+2)^2) := by + let M := magnitude (n::a::v) + have hn : n≤M := by dsimp [M]; omega + have ha : a≤M := by dsimp [M]; omega + have hv : magnitude (a::v)≤M := by dsimp [M]; omega + have hr : ∀i≤n,a-i≤M := by intro i _; omega + have hg : ∀ia-i) (a::v) M + (300*(M+1)) (1000*(M+1)) hn hr hv ((run_head (a::v)).mono (by gcongr)) hg + apply hh.mono + dsimp [M] at * + nlinarith + +def mulCode : Code := .prec .zero (.comp addCode .tail) + +lemma run_mul (n a : ℕ) (v : List ℕ) : + Runs mulCode (n::a::v) [a*n] (10000000*(magnitude (n::a::v)+2)^6) := by + let S := magnitude (n::a::v) + let M := (S+2)^2 + have hnS : n≤S := by dsimp [S]; omega + have haS : a≤S := by dsimp [S]; omega + have hvS : magnitude (a::v)≤S := by dsimp [S]; omega + have hSM : S≤M := by dsimp [M]; nlinarith + have hr : ∀i≤n,a*i≤M := by + intro i hi + have hh : a*i≤S*S := Nat.mul_le_mul haS (hi.trans hnS) + dsimp [M]; nlinarith + have hg : ∀ia*i) (a::v) M + (210*(M+1)) (1000000*(M+2)^2) (hnS.trans hSM) hr (hvS.trans hSM) + ((run_const_zero (a::v)).mono (by gcongr; exact hvS.trans hSM)) hg + apply hh.mono + change 210*(M+1)+(n+2)*(1000000*(M+2)^2+50000*(M+1))≤10000000*(S+2)^6 + calc + _ ≤ 210*(M+1)+(S+2)*(1000000*(M+2)^2+50000*(M+1)) := by gcongr + _ ≤ _ := by dsimp [M]; ring_nf; omega + +end MinUncut.Costed + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Search/CodeFoldComputable.lean b/lean/OAI/Computability/MinUncut/Search/CodeFoldComputable.lean new file mode 100644 index 0000000000000000000000000000000000000000..c6833b3954ebb840080fcb6bc23afe4f6f4794ee --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Search/CodeFoldComputable.lean @@ -0,0 +1,41 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.CodeComputability + +namespace OAI + +section +namespace MinUncut.CodeEffective +open Turing.ToPartrec +variable {σ : Type*} [Primcodable σ] +def fold (z s t : σ) (b3 b4 b5 : σ → σ → σ) (f6 : σ → σ) : Code → σ + | .zero' => z + | .succ => s + | .tail => t + | .cons f g => b3 (fold z s t b3 b4 b5 f6 f) (fold z s t b3 b4 b5 f6 g) + | .comp f g => b4 (fold z s t b3 b4 b5 f6 f) (fold z s t b3 b4 b5 f6 g) + | .case f g => b5 (fold z s t b3 b4 b5 f6 f) (fold z s t b3 b4 b5 f6 g) + | .fix f => f6 (fold z s t b3 b4 b5 f6 f) +lemma primrec_fold (z s t : σ) {b3 b4 b5 : σ → σ → σ} {f6 : σ → σ} + (h3 : Primrec₂ b3) (h4 : Primrec₂ b4) (h5 : Primrec₂ b5) (h6 : Primrec f6) : + Primrec (fold z s t b3 b4 b5 f6) := by + have h := Nat.Partrec.Code.primrec_recOn (α:=Code) (σ:=σ) primrec_embed + (z:=fun _=>z) (Primrec.const _) (s:=fun _=>s) (Primrec.const _) + (l:=fun _=>t) (Primrec.const _) (r:=fun _=>t) (Primrec.const _) + (pr:=fun _ _ _ x y=>b3 x y) + (h3.comp (Primrec.fst.comp (Primrec.snd.comp (Primrec.snd.comp Primrec.snd))) + (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp Primrec.snd)))) + (co:=fun _ _ _ x y=>b4 x y) + (h4.comp (Primrec.fst.comp (Primrec.snd.comp (Primrec.snd.comp Primrec.snd))) + (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp Primrec.snd)))) + (pc:=fun _ _ _ x y=>b5 x y) + (h5.comp (Primrec.fst.comp (Primrec.snd.comp (Primrec.snd.comp Primrec.snd))) + (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp Primrec.snd)))) + (rf:=fun _ _ x=>f6 x) (h6.comp (Primrec.snd.comp Primrec.snd)) + apply h.of_eq + intro c + induction c <;> simp_all [fold,embed] +end MinUncut.CodeEffective + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Search/CodeLayoutComputable.lean b/lean/OAI/Computability/MinUncut/Search/CodeLayoutComputable.lean new file mode 100644 index 0000000000000000000000000000000000000000..d03e7249db39d0a37bd299906cd174d3ff3b5132 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Search/CodeLayoutComputable.lean @@ -0,0 +1,76 @@ +import Mathlib +import OAI.Computability.MinUncut.Search.CodeFoldComputable +import OAI.Computability.MinUncut.Estimates.HeapInitializationMath + +namespace OAI + +section +namespace MinUncut.CodeEffective.Layout +open Turing.ToPartrec MinUncut.Costed.Arena +abbrev Cell := ℕ × ℕ × ℕ × ℕ +def shift (b : ℕ) (x : Cell) : Cell := + (x.1,rebasePointer b x.2.1,rebasePointer b x.2.2.1,x.2.2.2) +lemma p_pointer : Primrec₂ rebasePointer := + Primrec.ite (Primrec.eq.comp Primrec.snd (Primrec.const 0)) (Primrec.const 0) + (Primrec.nat_add.comp Primrec.fst Primrec.snd) +lemma p_shift : Primrec₂ shift := + (Primrec.fst.comp Primrec.snd).pair + ((p_pointer.comp Primrec.fst (Primrec.fst.comp (Primrec.snd.comp Primrec.snd))).pair + ((p_pointer.comp Primrec.fst (Primrec.fst.comp (Primrec.snd.comp (Primrec.snd.comp Primrec.snd)))).pair + (Primrec.snd.comp (Primrec.snd.comp (Primrec.snd.comp Primrec.snd))))) +def binary (tag : ℕ) (l r : List Cell) : List Cell := + (tag,l.length,l.length+r.length,0)::(r.map (shift l.length)++l) +def unary (l : List Cell) : List Cell := (6,l.length,0,0)::l +lemma p_binary (tag : ℕ) : Primrec₂ (binary tag) := by + have hl : Primrec (fun p : List Cell × List Cell=>p.1.length) := Primrec.list_length.comp Primrec.fst + have hr : Primrec (fun p : List Cell × List Cell=>p.2.length) := Primrec.list_length.comp Primrec.snd + have hm : Primrec (fun p : List Cell × List Cell=>p.2.map (shift p.1.length)) := + Primrec.list_map Primrec.snd (p_shift.comp (hl.comp Primrec.fst) Primrec.snd).to₂ + exact Primrec.list_cons.comp + ((Primrec.const tag).pair (hl.pair ((Primrec.nat_add.comp hl hr).pair (Primrec.const 0)))) + (Primrec.list_append.comp hm Primrec.fst) +lemma p_unary : Primrec unary := + Primrec.list_cons.comp + ((Primrec.const 6).pair (Primrec.list_length.pair ((Primrec.const 0).pair (Primrec.const 0)))) Primrec.id + +def cells : Code → List Cell := fold [(0,0,0,0)] [(1,0,0,0)] [(2,0,0,0)] (binary 3) (binary 4) (binary 5) unary +lemma p_cells : Primrec cells := primrec_fold _ _ _ (p_binary 3) (p_binary 4) (p_binary 5) p_unary + +def pack (n : Node) : Cell := (n 0,n 1,n 2,n 3) +lemma pack_rebase (d : ℕ) (h : Heap) : + (h.map (rebaseNode d)).map pack=(h.map pack).map (shift d) := by + simp only [List.map_map] + rfl +lemma cells_eq (c : Code) : cells c=(codeCells c 0).map pack := by + induction c with + | zero' | succ | tail => rfl + | cons f g ih ih' | comp f g ih ih' | case f g ih ih' => + have hg:=codeCells_rebase g 0 (codeCells f 0).length + simp only [Nat.zero_add] at hg + change binary _ (cells f) (cells g)=_ + rw [binary,ih,ih'] + simp only [codeCells,Nat.zero_add,List.length_map,hg,List.map_cons,List.map_append, + pack_rebase,pack,node_zero,node_one,node_two,node_three] + | fix f ih => + change unary (cells f)=_ + rw [unary,ih] + simp only [codeCells,Nat.zero_add,List.length_map,List.map_cons,pack,node_zero,node_one,node_two,node_three] + +def flattenCell (x : Cell) : List ℕ := [x.1,x.2.1,x.2.2.1,x.2.2.2] +lemma p_flattenCell : Primrec flattenCell := + Primrec.list_cons.comp Primrec.fst (Primrec.list_cons.comp (Primrec.fst.comp Primrec.snd) + (Primrec.list_cons.comp (Primrec.fst.comp (Primrec.snd.comp Primrec.snd)) + (Primrec.list_cons.comp (Primrec.snd.comp (Primrec.snd.comp Primrec.snd)) (Primrec.const [])))) +lemma p_words : Primrec (fun c=>words (codeCells c 0)) := by + have hh : Primrec (fun c=>(cells c).flatMap flattenCell) := + Primrec.list_flatMap p_cells (p_flattenCell.comp Primrec.snd).to₂ + exact hh.of_eq (by intro c; simp only [cells_eq,List.flatMap_map,words]; congr 1) +lemma p_count : Primrec (fun c=>(codeCells c 0).length) := + (Primrec.list_length.comp p_cells).of_eq (by intro c; simp only [cells_eq,List.length_map]) +lemma c_prefix : Computable (fun c=>(codeCells c 0).length::words (codeCells c 0)) := + (Primrec.list_cons.comp p_count p_words).to_comp +end MinUncut.CodeEffective.Layout + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Search/EnumerationPlain.lean b/lean/OAI/Computability/MinUncut/Search/EnumerationPlain.lean new file mode 100644 index 0000000000000000000000000000000000000000..f76d23bd878462bcf9c5914aa0f6fa0ae464f9ac --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Search/EnumerationPlain.lean @@ -0,0 +1,56 @@ +import Mathlib +import OAI.Computability.MinUncut.Search.FiniteEnumeration + +namespace OAI + +section +namespace MinUncut.Enumeration +variable {A B C : Type} +def mapEquiv (E : Enumeration A) (e : A ≃ B) : Enumeration B where + values := E.values.map e + nodup := E.nodup.map e.injective + complete b := List.mem_map.mpr ⟨e.symm b,E.complete _,e.apply_symm_apply b⟩ +def bind (E : Enumeration A) {B : A → Type} (F : ∀a,Enumeration (B a)) : Enumeration (Σa,B a) where + values := E.values.flatMap (fun a=>(F a).values.map (Sigma.mk a)) + nodup := by + rw [List.nodup_flatMap] + constructor + · intro a _ + exact (F a).nodup.map (by intro x y h; exact eq_of_heq (Sigma.mk.inj h).2) + · apply E.nodup.pairwise_of_forall_ne + intro a _ b _ hab + dsimp only [Function.onFun] + rw [List.disjoint_left] + intro x hx hy + obtain ⟨u,_,rfl⟩:=List.mem_map.mp hx + obtain ⟨v,_,he⟩:=List.mem_map.mp hy + exact hab (Sigma.mk.inj he).1.symm + complete x := by + rcases x with ⟨a,b⟩ + exact List.mem_flatMap.mpr ⟨a,E.complete a,List.mem_map.mpr ⟨b,(F a).complete b,rfl⟩⟩ +def filterSubtype (E : Enumeration A) (p : A → Prop) [DecidablePred p] : Enumeration {a // p a} where + values := (E.values.filter p).attach.map (fun a=>(⟨a.val,by simpa only [decide_eq_true_eq] using (List.mem_filter.mp a.property).2⟩ : {a // p a})) + nodup := (List.nodup_attach.mpr (E.nodup.filter _)).map (by intro a b h; apply Subtype.ext; exact congrArg (fun x : {a // p a}=>x.val) h) + complete a := by + apply List.mem_map.mpr + exact ⟨⟨a.val,List.mem_filter.mpr ⟨E.complete a.val,by simpa only [decide_eq_true_eq] using a.property⟩⟩,List.mem_attach _ _,rfl⟩ +lemma filterSubtype_flatMap (E : Enumeration A) (p : A → Prop) [DecidablePred p] + (f : A → List B) : + (E.filterSubtype p).values.flatMap (fun a=>f a.val)= + E.values.flatMap (fun a=>if p a then f a else []) := by + unfold filterSubtype + simp only [List.flatMap_map] + rw [show List.flatMap (fun a : {a // a∈E.values.filter p}=>f a.val) (E.values.filter p).attach = + (E.values.filter p).flatMap f by + rw [←List.flatMap_map (g:=f) (f:=Subtype.val),List.attach_map_subtype_val]] + generalize E.values = xs + induction xs with + | nil => rfl + | cons x xs ih => + simp only [List.filter_cons,List.flatMap_cons] + by_cases hx:p x <;> simp [hx,ih] +end MinUncut.Enumeration + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Search/FiniteAverageBounds.lean b/lean/OAI/Computability/MinUncut/Search/FiniteAverageBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..3474eaa1137fbe3b43a7e104eda491850dfe7170 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Search/FiniteAverageBounds.lean @@ -0,0 +1,118 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.FirstError +import OAI.Computability.MinUncut.Analysis.FreshCorrelation +import OAI.Computability.MinUncut.Analysis.FiniteGaussianLaw +import OAI.Computability.MinUncut.Estimates.TableTestFunctions + +namespace OAI + +section +noncomputable section +open scoped BigOperators +namespace MinUncut.FiniteGaussian +variable {A : Type*} [Fintype A] [Nonempty A] + +lemma expect_abs_difference (f g : A → ℝ) {ε : ℝ} (h : ∀ a, |f a-g a|≤ε) : + |(𝔼 a,f a)-(𝔼 a,g a)|≤ε := by + rw [← Finset.expect_sub_distrib] + exact (OuterSmoothness.Density.abs_expect_le _).trans + ((Finset.expect_le_expect (fun a _ => h a)).trans_eq (Fintype.expect_const _)) + +omit [Nonempty A] in +lemma weighted_expect_abs_difference (w f g : A → ℝ) (hw : ∀ a, 0≤w a) + (hs : (𝔼 a,w a)=1) {ε : ℝ} (h : ∀ a, |f a-g a|≤ε) : + |(𝔼 a,w a*f a)-(𝔼 a,w a*g a)|≤ε := by + rw [← Finset.expect_sub_distrib] + simp only [← mul_sub] + calc + _ ≤ 𝔼 a, |w a*(f a-g a)| := OuterSmoothness.Density.abs_expect_le _ + _ ≤ 𝔼 a, w a*ε := Finset.expect_le_expect (fun a _ => by + rw [abs_mul,abs_of_nonneg (hw a)] + exact mul_le_mul_of_nonneg_left (h a) (hw a)) + _ = ε := by rw [← Finset.expect_mul,hs,one_mul] +end MinUncut.FiniteGaussian + +end +end +section +noncomputable section +open scoped BigOperators +open MeasureTheory ProbabilityTheory +namespace MinUncut.FiniteGaussian +open GaussianBudget MinUncut.Inner +attribute [local instance] Classical.propDecidable +attribute [local instance] coordsDecEq +variable {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 tableAverage (g : GridData) (σ η : ℚ) (F : (ScoreIndex m n → Bool) → ℝ) : ℝ := + ∑ j : TestCoordinates m n → Fin g.L, + (gridWeight g j:ℝ)*F (rationalScoreTable σ η (fun i => midpoint g.T g.L (j i))) + +def finiteFirst (g : GridData) (f : FoldedProof A) (σ η : ℚ) : ℝ := + 𝔼 B : FaceArray A m n, tableAverage g σ η (firstTable f B) + +def finiteSecond (g : GridData) (f : FoldedProof A) (a : ℝ) (σ η : ℚ) : ℝ := + 𝔼 B : FaceArray A m n, 𝔼 C : FaceArray A m n, + RowNoise.density a B C*tableAverage g σ η (secondTable f B C) + +def finiteThird (g : GridData) (f : FoldedProof A) (σ η : ℚ) : ℝ := + 𝔼 B : FaceArray A m n, 𝔼 z : Code m n, tableAverage g σ η (thirdTable f B z) + +def finiteFourth (g : GridData) (π : A →ᵃ[F₂] A') (f : FoldedProof A) (f' : FoldedProof A') + (σ η : ℚ) : ℝ := + 𝔼 C : FaceArray A' m n, tableAverage g σ η (fourthTable f f' (pullbackFaces π C) C) + +lemma tableAverage_difference (hn : 0 disagreement_range _ _) + +lemma finiteSecond_difference (f : FoldedProof A) (hn : 0 RowNoise.density_nonneg ha ha1 B C) + (RowNoise.density_mean a B) + intro C + rw [secondTable_integral] + exact tableAverage_difference hn hσ hσ1 hη hη1 hε _ (fun _ => disagreement_range _ _) + +lemma finiteThird_difference (f : FoldedProof A) (hn : 0 disagreement_range _ _) + +omit [Fintype A] in +lemma finiteFourth_difference (π : A →ᵃ[F₂] A') (f : FoldedProof A) (f' : FoldedProof A') + (hn : 0 disagreement_range _ _) +end MinUncut.FiniteGaussian + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Search/FiniteEnumeration.lean b/lean/OAI/Computability/MinUncut/Search/FiniteEnumeration.lean new file mode 100644 index 0000000000000000000000000000000000000000..ba598ce6ac02d5a8e2c8a7aba20c6004d2b4bd75 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Search/FiniteEnumeration.lean @@ -0,0 +1,78 @@ +import Mathlib +import OAI.Computability.MinUncut.PCP.Occurrences + +namespace OAI + +section +namespace MinUncut +open MinUncutGames.Foundations.Hastad.SourceOccurrences + +structure Enumeration (A : Type) where + values : List A + nodup : values.Nodup + complete : ∀ a, a∈values + +namespace Enumeration +variable {A B : Type} + +def ofList [DecidableEq A] (l : List A) (h : ∀a, a∈l) : Enumeration A where + values := l.dedup + nodup := List.nodup_dedup l + complete a := List.mem_dedup.mpr (h a) + +def encoding [DecidableEq A] (E : Enumeration A) : Encoding A where + size := E.values.length + code := (List.Nodup.getEquivOfForallMemList E.values E.nodup E.complete).symm + +def ofEncoding (e : Encoding A) : Enumeration A where + values := e.enumerate + nodup := e.nodup_enumerate + complete := e.mem_enumerate + +def image [DecidableEq B] (E : Enumeration A) (f : A → B) (h : Function.Surjective f) : Enumeration B := + ofList (E.values.map f) (by intro b; obtain ⟨a,rfl⟩ := h b; exact List.mem_map.mpr ⟨a,E.complete a,rfl⟩) + +def subtype [DecidableEq A] (E : Enumeration A) (p : A → Prop) [DecidablePred p] : Enumeration {a // p a} := + ofList ((E.values.filter (fun a => decide (p a))).attach.map (fun a => + (⟨a.val, by + have hm : a.val ∈ E.values ∧ decide (p a.val) = true := List.mem_filter.mp a.property + exact of_decide_eq_true hm.2⟩ : {a // p a}))) (by + intro a + apply List.mem_map.mpr + exact ⟨⟨a.val,List.mem_filter.mpr ⟨E.complete a.val,by simpa only [decide_eq_true_eq] using a.property⟩⟩,List.mem_attach _ _,rfl⟩) + +def sigma [DecidableEq A] (E : Enumeration A) {B : A → Type} [∀a, DecidableEq (B a)] + (F : ∀a, Enumeration (B a)) : Enumeration (Σa, B a) := + ofList (E.values.flatMap (fun a => (F a).values.map (fun b => Sigma.mk a b))) (by + rintro ⟨a,b⟩ + exact List.mem_flatMap.mpr ⟨a,E.complete a,List.mem_map.mpr ⟨b,(F a).complete b,rfl⟩⟩) + +def pair [DecidableEq A] [DecidableEq B] (E : Enumeration A) (F : Enumeration B) : Enumeration (A × B) := + ofEncoding (E.encoding.prod F.encoding) + +def function [DecidableEq A] [DecidableEq B] (E : Enumeration A) (F : Enumeration B) : Enumeration (A → B) := + ofEncoding (E.encoding.function F.encoding) + +lemma length_values [Fintype A] (E : Enumeration A) : E.values.length=Fintype.card A := by + classical + have he : E.values.toFinset=Finset.univ := by ext a; simp [E.complete] + rw [← List.toFinset_card_of_nodup E.nodup,he,Finset.card_univ] + +lemma prod_values {M : Type*} [CommMonoid M] [Fintype A] (E : Enumeration A) (f : A → M) : + (E.values.map f).prod=∏a, f a := by + classical + have he : E.values.toFinset=Finset.univ := by ext a; simp [E.complete] + rw [← List.prod_toFinset f E.nodup,he] + +lemma sum_values [Fintype A] (E : Enumeration A) (f : A → ℕ) : + (E.values.map f).sum=∑a, f a := by + classical + have he : E.values.toFinset=Finset.univ := by ext a; simp [E.complete] + rw [← List.sum_toFinset f E.nodup] + rw [he] +end Enumeration +end MinUncut + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Search/FiniteQueryFamily.lean b/lean/OAI/Computability/MinUncut/Search/FiniteQueryFamily.lean new file mode 100644 index 0000000000000000000000000000000000000000..1202c7d783cffe178b5fceb87e830fdee8b0e142 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Search/FiniteQueryFamily.lean @@ -0,0 +1,83 @@ +import Mathlib +import OAI.Computability.MinUncut.Graphs.SignedGraph +import OAI.Computability.MinUncut.Analysis.GaussianRows + +namespace OAI + +section +noncomputable section +namespace MinUncut.Outer +open MinUncut.Inner MinUncut.FiniteProof +attribute [local instance] Classical.propDecidable +variable {Name I : Type*} [Fintype I] + +abbrev FamilyQuestion (Name I : Type*) := (I → Equation Name) ⊕ (I → SecondQuestion Name) + +def FamilyAlphabet : FamilyQuestion Name I → Type _ + | .inl U => FirstAlphabet U + | .inr Q => SecondAlphabet Q + +instance familyAlphabetFintype (q : FamilyQuestion Name I) : Fintype (FamilyAlphabet q) := by + cases q <;> unfold FamilyAlphabet <;> infer_instance + +def familyBase : (q : FamilyQuestion Name I) → FamilyAlphabet q + | .inl U => fun j => origin (U j) + | .inr _ => fun _ _ => 0 + +abbrev FamilyVariable (Name I : Type*) [Fintype I] := Variable (familyBase (Name := Name) (I := I)) + +def variableProof (y : FamilyVariable Name I → Bool) : ProofFamily Name I where + first U := ⟨answer familyBase y (.inl U),answer_folded familyBase y (.inl U)⟩ + second Q := ⟨answer familyBase y (.inr Q),answer_folded familyBase y (.inr Q)⟩ + +def ProofFamily.queryAnswer (f : ProofFamily Name I) : + (q : FamilyQuestion Name I) → (FamilyAlphabet q → Bool) → Bool + | .inl U => (f.first U).answer + | .inr Q => (f.second Q).answer + +lemma ProofFamily.queryAnswer_folded (f : ProofFamily Name I) : Folded f.queryAnswer := by + intro q P + cases q with + | inl U => exact (f.first U).folded P + | inr Q => exact (f.second Q).folded P + +def ProofFamily.assignment (f : ProofFamily Name I) : FamilyVariable Name I → Bool := + fun p => f.queryAnswer p.1 p.2.val + +lemma ProofFamily.answer_assignment (f : ProofFamily Name I) : + answer familyBase f.assignment=f.queryAnswer := + answer_of_folded familyBase f.queryAnswer f.queryAnswer_folded + +lemma foldedProof_ext {A : Type*} {f g : FoldedProof A} (h : f.answer=g.answer) : f=g := by + cases f + cases g + cases h + rfl + +lemma proofFamily_ext {f g : ProofFamily Name I} + (hf : f.first=g.first) (hg : f.second=g.second) : f=g := by + cases f + cases g + cases hf + cases hg + rfl + +lemma ProofFamily.variableProof_assignment (f : ProofFamily Name I) : variableProof f.assignment=f := by + apply proofFamily_ext + · funext U + apply foldedProof_ext + exact (congrFun f.answer_assignment (.inl U)) + · funext Q + apply foldedProof_ext + exact (congrFun f.answer_assignment (.inr Q)) + +lemma variableProof_queryAnswer (y : FamilyVariable Name I → Bool) : + (variableProof y).queryAnswer=answer familyBase y := by + funext q + cases q <;> rfl +end MinUncut.Outer + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Search/InnerParameters.lean b/lean/OAI/Computability/MinUncut/Search/InnerParameters.lean new file mode 100644 index 0000000000000000000000000000000000000000..66e7f9ade239f92a16720d48653970f2c42114c0 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Search/InnerParameters.lean @@ -0,0 +1,97 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.Assembly + +namespace OAI + +section +noncomputable section +open scoped BigOperators +namespace MinUncut.Inner +open MeasureTheory ProbabilityTheory BinaryFourier RowNoise GaussianHermite Subbox + +structure InnerParameters (J : ℝ) where + s : ℕ + m : ℕ + k : ℕ + n : ℕ + H : ℕ + A₀ : ℕ + γ : ℚ + p : ℚ + θ : ℚ + hm : 2 ≤ m + hn : k+2 ≤ n + hk : 1 ≤ k + hs : ∀ t : ℕ, s+2 ≤ t → (t:ℝ)*(smoothingRho (sourceSigma J))^(2*t) ≤ 1/16 + hroom : sourceR J*m < (m-s).choose 2 + hH : 0 < H + hA : 0 < A₀ + hγ : 0 < (γ:ℝ) + hp : 0 < (p:ℝ) + hp1 : (p:ℝ) < 1 + hθ : 0 < (θ:ℝ) + hθ1 : (θ:ℝ) < 1 + hloc : (sourceSigma J)⁻¹*Real.sqrt (((s+sourceR J*m:ℕ):ℝ)*((k:ℝ)/((n:ℝ)-1))) < + classTarget (sourceT J) m/10 + henergy : (sourceSigma J)⁻¹^2/(H:ℝ) < classTarget (sourceT J) m/10 + hclip : 2*((sourceSigma J)⁻¹^2)/(A₀:ℝ) < classTarget (sourceT J) m/10 + hcollision : 2*(A₀:ℝ)*((m:ℝ)/((k:ℝ)+1))^(((2^m:ℕ):ℝ)⁻¹) < classTarget (sourceT J) m/10 + hfourth : Real.sqrt ((H:ℝ)*((γ:ℝ)+(H:ℝ)^2/(A₀:ℝ))) < classTarget (sourceT J) m/10 + hatom : Real.sqrt ((sourceSigma J)⁻¹^2)*Real.sqrt + (((4:ℝ)^Fintype.card (Row m n)*((Fintype.card (Point m n)+s).choose s:ℝ)* + Real.sqrt ((θ:ℝ)^2+(m:ℝ)*(p:ℝ)*(n^m:ℕ)/(sourceSigma J)^2))/(γ:ℝ)) < + classTarget (sourceT J) m/10 + +lemma exists_innerParameters {J : ℝ} (hJ : 1 ≤ J) : Nonempty (InnerParameters J) := by + have hσ := sourceSigma_pos hJ + have hT : (0:ℝ) < sourceT J := by exact_mod_cast sourceT_pos hJ + obtain ⟨s,hs⟩ := exists_cutoff (smoothingRho_lt_one hσ.ne') (by norm_num : (0:ℝ) < 1/16) + obtain ⟨m,hm,_,hroom⟩ := exists_dimension (sourceR J) s + let e := classTarget (sourceT J) m/10 + have he : 0 < e := div_pos (classTarget_pos hT m) (by norm_num) + obtain ⟨H,A₀,γ,hH,hA,hγ,_,henergy,hclip,hfourth⟩ := + exists_reciprocal_processing (E := (sourceSigma J)⁻¹^2) he + have hAr : (0:ℝ) < A₀ := by exact_mod_cast hA + obtain ⟨k,hk,hcollision⟩ := exists_box_scale m hAr he + obtain ⟨n,hn,hloc⟩ := exists_ambient_scale s (sourceR J*m) k hσ he + let C := (4:ℝ)^Fintype.card (Row m n)*((Fintype.card (Point m n)+s).choose s:ℝ) + have hchoose : 0 < (Fintype.card (Point m n)+s).choose s := Nat.choose_pos (by omega) + have hC : 0 < C := by dsimp [C]; positivity + let L := (m:ℝ)*(n^m:ℕ)/(sourceSigma J)^2 + have hnpos : 0 < n := by omega + have hmpos : 0 < m := by omega + have hL : 0 < L := by dsimp [L]; positivity + obtain ⟨p,θ,hp,hp1,hθ,hθ1,hQ⟩ := exists_small_rational_atoms hL + (show 0 < (e^2*(sourceSigma J)^2*(γ:ℝ)/C)^2 by positivity) + have hQ' : (θ:ℝ)^2+(m:ℝ)*(p:ℝ)*(n^m:ℕ)/(sourceSigma J)^2 < + (e^2*(sourceSigma J)^2*(γ:ℝ)/C)^2 := by + convert hQ using 1 + dsimp [L] + ring + have hatom := nested_atom_lt hσ he hγ hC hQ' + exact ⟨⟨s,m,k,n,H,A₀,γ,p,θ,hm,hn,hk,hs,hroom,hH,hA,hγ,hp,hp1,hθ,hθ1, + hloc,henergy,hclip,hcollision,hfourth,hatom⟩⟩ + +theorem InnerParameters.decode {J : ℝ} (hJ : 1 ≤ J) (P : InnerParameters J) + {Ξ : Type*} [Fintype Ξ] (V A : Ξ → Type*) + [∀ ξ, AddCommGroup (V ξ)] [∀ ξ, Module F₂ (V ξ)] [∀ ξ, AddTorsor (V ξ) (A ξ)] + [∀ ξ, Fintype (A ξ)] (w : Ξ → ℝ) (hw : ∀ ξ, 0 ≤ w ξ) (hw1 : ∑ ξ, w ξ=1) + (f : ∀ ξ, FoldedProof (A ξ)) + (h1 : (∑ ξ, w ξ*firstError (m := P.m) (n := P.n) (f ξ) (sourceSigma J) (sourceEta J)) ≤ + J*(10*sourceSigma J)) + (h2 : (∑ ξ, w ξ*secondError (m := P.m) (n := P.n) (f ξ) + ((sourceEta J)^2/(P.m:ℝ)) (sourceSigma J) (sourceEta J)) ≤ J*(10*(sourceEta J+sourceEta J))) + (h3 : (∑ ξ, w ξ*thirdError (m := P.m) (n := P.n) (f ξ) (sourceSigma J) (sourceEta J)) ≤ + J/(Fintype.card (Code P.m P.n):ℝ)) : + (P.p:ℝ) ≤ ∑ ξ, w ξ*atomProbability (m := P.m) (n := P.n) (f ξ) + (sourceSigma J) (sourceEta J) (P.θ:ℝ) := by + apply inner_atom_of_errors V A w hw hw1 f hJ P.hm (by have := P.hn; omega) + (by have := P.hn; omega) P.hs P.hroom (by exact_mod_cast P.hH) P.hγ + (by exact_mod_cast P.hA) P.hθ.le P.hloc P.henergy P.hclip P.hcollision P.hfourth P.hatom + h1 h2 h3 +end MinUncut.Inner + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Search/OuterParameters.lean b/lean/OAI/Computability/MinUncut/Search/OuterParameters.lean new file mode 100644 index 0000000000000000000000000000000000000000..958036839a0b8c9478940f10316993d94ea11d3c --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Search/OuterParameters.lean @@ -0,0 +1,99 @@ +import Mathlib +import OAI.Computability.MinUncut.Search.InnerParameters + +namespace OAI + +section +noncomputable section +open scoped BigOperators +namespace MinUncut.Outer +open MinUncut.Inner + +lemma exists_list_scale (M u θ : ℝ) (q : ℕ) {ε : ℝ} (hε : 0<ε) : + ∃ k : ℕ, listTerm M u θ q k < ε := by + let C : ℝ := (⌈M^2/u^2⌉₊ : ℝ)*(⌈M^2/θ^2⌉₊ : ℝ) + have hC : 0≤C := by dsimp [C]; positivity + obtain ⟨k,hk⟩ := shared_hint_rate_vanishes q (show 0<ε/(C+1) by positivity) + refine ⟨k,?_⟩ + have hr := pow_nonneg (hintRate_nonnegative q) k + have hx := (lt_div_iff₀ (show 0.trans_eq (by unfold sourceT; ring) + +lemma source_row_rate {J : ℝ} (hJ : 1 ≤ J) {m : ℕ} (hm : 0 < m) : + 0 ≤ (sourceEta J)^2/(m:ℝ) ∧ (sourceEta J)^2/(m:ℝ) ≤ 1 ∧ + ∀ k : ℕ, sourceR J*m < k → 1 ≤ (k:ℝ)*((sourceEta J)^2/(m:ℝ)) := by + have hm' : (0:ℝ) < m := by exact_mod_cast hm + have hm1 : (1:ℝ) ≤ m := by exact_mod_cast hm + have hetapos := sourceEta_pos hJ + have heta1 : sourceEta J ≤ 1 := (sourceEta_le_sigma hJ).trans (sourceSigma_le_one hJ) + refine ⟨by positivity,?_,?_⟩ + · apply (div_le_iff₀ hm').mpr + nlinarith + · intro k hk + have hk' : (sourceR J:ℝ)*(m:ℝ) ≤ k := by exact_mod_cast hk.le + have hh := mul_le_mul_of_nonneg_right hk' (show 0 ≤ (sourceEta J)^2/(m:ℝ) by positivity) + have he : (sourceR J:ℝ)*(m:ℝ)*((sourceEta J)^2/(m:ℝ)) = + (sourceR J:ℝ)*(sourceEta J)^2 := by field_simp + rw [he] at hh + exact (sourceR_bound hJ).trans hh +end MinUncut.Inner + +namespace MinUncut.Inner +open MeasureTheory ProbabilityTheory GaussianHermite RowNoise +open scoped BigOperators +attribute [local instance] Classical.propDecidable +variable {Ξ : Type*} [Fintype Ξ] (V A : Ξ → Type*) + [∀ ξ, AddCommGroup (V ξ)] [∀ ξ, Module F₂ (V ξ)] [∀ ξ, AddTorsor (V ξ) (A ξ)] + [∀ ξ, Fintype (A ξ)] {m n : ℕ} + +theorem source_lowGradient_energy (w : Ξ → ℝ) (hw : ∀ ξ, 0 ≤ w ξ) + (hw1 : ∑ ξ, w ξ=1) (f : ∀ ξ, FoldedProof (A ξ)) {J : ℝ} (hJ : 1 ≤ J) + (hm : 2 ≤ m) (hn : 2 ≤ n) (s : ℕ) + (hs : ∀ k : ℕ, s+2 ≤ k → (k:ℝ)*(smoothingRho (sourceSigma J))^(2*k) ≤ 1/16) + (h1 : (∑ ξ, w ξ*firstError (m := m) (n := n) (f ξ) (sourceSigma J) (sourceEta J)) ≤ + J*(10*sourceSigma J)) + (h2 : (∑ ξ, w ξ*secondError (m := m) (n := n) (f ξ) + ((sourceEta J)^2/(m:ℝ)) (sourceSigma J) (sourceEta J)) ≤ J*(10*(sourceEta J+sourceEta J))) : + 1/2 ≤ (∑ ξ, w ξ*averagedEnergy + (lowGradient (m := m) (n := n) (sourceR J*m) s (f ξ) (sourceSigma J) (sourceEta J))) ∧ + (∑ ξ, w ξ*averagedEnergy + (lowGradient (m := m) (n := n) (sourceR J*m) s (f ξ) (sourceSigma J) (sourceEta J))) ≤ + (sourceSigma J)⁻¹^2 := by + have hm0 : 0 < m := by omega + have hn0 : 0 < n := by omega + have hσ := sourceSigma_pos hJ + have hη := sourceEta_pos hJ + obtain ⟨ha,ha1,hD⟩ := source_row_rate hJ hm0 + have hL := lowGradient_energy_lower_weighted (m := m) (n := n) V A w hw hw1 f hn0 hσ.ne' hη.ne' ha ha1 + (by norm_num : (0:ℝ) ≤ 1/16) (sourceR J*m) s hD hs + have hJ0 : J≠0 := ne_of_gt (by linarith) + have hc1 : 4*(J*(10*sourceSigma J))=1/64 := by + unfold sourceSigma + field_simp + ring + have hc2 : 8*(sourceSigma J)⁻¹^2*(J*(10*(sourceEta J+sourceEta J)))=1/16 := by + unfold sourceEta sourceSigma + field_simp + ring + have hf1 := mul_le_mul_of_nonneg_left h1 (by norm_num : (0:ℝ) ≤ 4) + have hf2 := mul_le_mul_of_nonneg_left h2 (show 0 ≤ 8*(sourceSigma J)⁻¹^2 by positivity) + rw [hc1] at hf1 + rw [hc2] at hf2 + constructor + · linarith + · calc + _ ≤ ∑ ξ, w ξ*(sourceSigma J)⁻¹^2 := Finset.sum_le_sum + (fun ξ _ => mul_le_mul_of_nonneg_left + (averagedEnergy_lowGradient_le (m := m) (sourceR J*m) s (f ξ) hn0 hσ.ne' (sourceEta J)) (hw ξ)) + _ = _ := by rw [← Finset.sum_mul,hw1,one_mul] + +theorem source_lowGradient_correlation (w : Ξ → ℝ) (hw : ∀ ξ, 0 ≤ w ξ) + (hw1 : ∑ ξ, w ξ=1) (f : ∀ ξ, FoldedProof (A ξ)) {J : ℝ} (hJ : 1 ≤ J) + (hm : 2 ≤ m) (hn : 2 ≤ n) (s : ℕ) + (hs : ∀ k : ℕ, s+2 ≤ k → (k:ℝ)*(smoothingRho (sourceSigma J))^(2*k) ≤ 1/16) + (h1 : (∑ ξ, w ξ*firstError (m := m) (n := n) (f ξ) (sourceSigma J) (sourceEta J)) ≤ + J*(10*sourceSigma J)) + (h2 : (∑ ξ, w ξ*secondError (m := m) (n := n) (f ξ) + ((sourceEta J)^2/(m:ℝ)) (sourceSigma J) (sourceEta J)) ≤ J*(10*(sourceEta J+sourceEta J))) + (h3 : (∑ ξ, w ξ*thirdError (m := m) (n := n) (f ξ) (sourceSigma J) (sourceEta J)) ≤ + J/(Fintype.card (Code m n):ℝ)) : + 1/(4*(sourceT J:ℝ)) ≤ ∑ ξ, w ξ*averagedCorrelation + (lowGradient (m := m) (n := n) (sourceR J*m) s (f ξ) (sourceSigma J) (sourceEta J)) := by + have hn0 : 0 < n := by omega + have hσ := sourceSigma_pos hJ + have hη := sourceEta_pos hJ + have hT : (0:ℝ) < sourceT J := by exact_mod_cast sourceT_pos hJ + obtain ⟨hE,hE'⟩ := source_lowGradient_energy V A w hw hw1 f hJ hm hn s hs h1 h2 + have hU := lowGradient_correlation_truncated_weighted (m := m) (n := n) V A (sourceR J*m) s w hw f hn0 hσ.ne' hη hT + (show 0 < (sourceSigma J)^2/8 by positivity) + have he := mul_le_mul_of_nonneg_left hE' + (show 0 ≤ (sourceSigma J)^2/8 by positivity) + have hea : ((sourceSigma J)^2/8)*(sourceSigma J)⁻¹^2=1/8 := by field_simp + rw [hea] at he + have hc : (0:ℝ) < Fintype.card (Code m n) := by positivity + have hz := mul_le_mul_of_nonneg_left h3 + (show 0 ≤ ((sourceSigma J)⁻¹^2/(4*((sourceSigma J)^2/8)*(sourceT J:ℝ)))* + ((Fintype.card (Code m n):ℝ)/sourceEta J) by positivity) + have hzb : ((sourceSigma J)⁻¹^2/(4*((sourceSigma J)^2/8)*(sourceT J:ℝ)))* + ((Fintype.card (Code m n):ℝ)/sourceEta J)*(J/(Fintype.card (Code m n):ℝ)) = + 2*J/(sourceEta J*(sourceSigma J)^4*(sourceT J:ℝ)) := by + field_simp + ring + rw [hzb] at hz + have hzt : 2*J/(sourceEta J*(sourceSigma J)^4*(sourceT J:ℝ)) ≤ 1/16 := by + apply (div_le_iff₀ (by positivity)).mpr + nlinarith [sourceT_bound hJ] + apply (div_le_iff₀ (by positivity : (0:ℝ) < 4*(sourceT J:ℝ))).mpr + nlinarith +end MinUncut.Inner + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Search/PolynomialArithmetic.lean b/lean/OAI/Computability/MinUncut/Search/PolynomialArithmetic.lean new file mode 100644 index 0000000000000000000000000000000000000000..7730e24fce848c32078626558bce136e39027d34 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Search/PolynomialArithmetic.lean @@ -0,0 +1,88 @@ +import Mathlib +import OAI.Computability.MinUncut.Search.CodeArithmetic + +namespace OAI + +section +noncomputable section +namespace MinUncut.Costed.PolyProgram +open Turing.ToPartrec Polynomial + +def pairPack : PolyProgram (fun v=>[v.headI,v.tail.headI]) := + head.cons ((head.comp tail).cons nil) + +def binary (c : Code) (f : ℕ → ℕ → ℕ) (p : Polynomial ℕ) + (hr : ∀a b,Runs c [a,b] [f a b] (p.eval (magnitude [a,b]))) + (hs : ∀a b,magnitude [f a b]≤p.eval (magnitude [a,b])) : + PolyProgram (fun v=>[f v.headI v.tail.headI]) where + code := .comp c pairPack.code + bound := pairPack.bound+p.comp pairPack.bound+1 + run v := by + have h := run_comp (pairPack.run v) (hr v.headI v.tail.headI) + apply h.mono + simp only [eval_add,eval_comp,eval_one] + have h' := evalNat_mono p (pairPack.size v) + omega + size v := by + have h := (hs v.headI v.tail.headI).trans (evalNat_mono p (pairPack.size v)) + simp only [eval_add,eval_comp,eval_one] + omega + +def add : PolyProgram (fun v=>[v.headI+v.tail.headI]) := + binary addCode (fun a b=>a+b) (C 100000*(X+2)^2) + (by intro a b; simpa [Nat.add_comm] using run_add a b []) + (by intro a b; simp only [magnitude_cons,magnitude_nil,eval_mul,eval_C,eval_pow, + eval_add,eval_X,eval_ofNat]; nlinarith) + +def sub : PolyProgram (fun v=>[v.headI-v.tail.headI]) := + (binary subCode (fun a b=>b-a) (C 100000*(X+2)^2) + (by intro a b; simpa using run_sub a b []) + (by intro a b; simp only [magnitude_cons,magnitude_nil,eval_mul,eval_C,eval_pow, + eval_add,eval_X,eval_ofNat]; + have h : b-a≤b := Nat.sub_le .. + have hp : b+1≤(a+1+(b+1+0)+2)^2 := + (by omega : b+1≤a+1+(b+1+0)+2).trans (Nat.le_self_pow (by omega) _) + omega)).comp + ((head.comp tail).cons (head.cons nil)) + +def mul : PolyProgram (fun v=>[v.headI*v.tail.headI]) := + binary mulCode (fun a b=>a*b) (C 10000000*(X+2)^6) + (by intro a b; simpa [Nat.mul_comm] using run_mul a b []) + (by intro a b + simp only [magnitude_cons,magnitude_nil,eval_mul,eval_C,eval_pow, + eval_add,eval_X,eval_ofNat] + have h₁ : a*b+1≤(a+1+(b+1+0)+2)^2 := by nlinarith + have h₂ : (a+1+(b+1+0)+2)^2≤(a+1+(b+1+0)+2)^6 := + Nat.pow_le_pow_right (by omega) (by omega) + omega) + +def addOf {f g : List ℕ → List ℕ} (F : PolyProgram f) (G : PolyProgram g) : + PolyProgram (fun v=>[(f v).headI+(g v).headI]) := add.comp (F.cons (G.cons nil)) +def subOf {f g : List ℕ → List ℕ} (F : PolyProgram f) (G : PolyProgram g) : + PolyProgram (fun v=>[(f v).headI-(g v).headI]) := sub.comp (F.cons (G.cons nil)) +def mulOf {f g : List ℕ → List ℕ} (F : PolyProgram f) (G : PolyProgram g) : + PolyProgram (fun v=>[(f v).headI*(g v).headI]) := mul.comp (F.cons (G.cons nil)) + +def eqOf {f g : List ℕ → List ℕ} (F : PolyProgram f) (G : PolyProgram g) : + PolyProgram (fun v=>[if (f v).headI=(g v).headI then 1 else 0]) := + (branch (addOf (subOf F G) (subOf G F)) (const 1) (const 0)).ofEq (by + intro v + simp only [List.headI_cons] + have h : (f v).headI-(g v).headI+((g v).headI-(f v).headI)=0 ↔ + (f v).headI=(g v).headI := by omega + simp only [h] + split_ifs <;> rfl) + +def leOf {f g : List ℕ → List ℕ} (F : PolyProgram f) (G : PolyProgram g) : + PolyProgram (fun v=>[if (f v).headI≤(g v).headI then 1 else 0]) := + (branch (subOf F G) (const 1) (const 0)).ofEq (by + intro v + simp only [List.headI_cons,Nat.sub_eq_zero_iff_le] + split_ifs <;> rfl) + +end MinUncut.Costed.PolyProgram + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Search/RationalBasics.lean b/lean/OAI/Computability/MinUncut/Search/RationalBasics.lean new file mode 100644 index 0000000000000000000000000000000000000000..5aef49088717ff08f46d762e394ad47674fdf283 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Search/RationalBasics.lean @@ -0,0 +1,179 @@ +import Mathlib +import OAI.Computability.MinUncut.Search.FiniteAverageBounds +import OAI.Computability.MinUncut.Estimates.ComparisonSoundness + +namespace OAI + +section +namespace MinUncut.Inner +open scoped BigOperators +open GaussianHermite RowNoise + +def rationalSigma (J : ℕ) : ℚ := 1/(2560*(J:ℚ)) +def rationalEta (J : ℕ) : ℚ := rationalSigma J^2/(2560*(J:ℚ)) +def rationalR (J : ℕ) : ℕ := ⌈(rationalEta J)⁻¹^2⌉₊ +def rationalT (J : ℕ) : ℕ := ⌈32*(J:ℚ)/(rationalEta J*rationalSigma J^4)⌉₊ + +lemma ceil_rat_real (q : ℚ) : ⌈(q:ℝ)⌉₊=⌈q⌉₊ := by + apply Nat.le_antisymm + · exact Nat.ceil_le.mpr (by exact_mod_cast Nat.le_ceil q) + · exact Nat.ceil_le.mpr (by exact_mod_cast Nat.le_ceil (q:ℝ)) + +@[simp] lemma rationalSigma_cast (J : ℕ) : (rationalSigma J:ℝ)=sourceSigma J := by + simp [rationalSigma,sourceSigma] +@[simp] lemma rationalEta_cast (J : ℕ) : (rationalEta J:ℝ)=sourceEta J := by + simp [rationalEta,sourceEta] +@[simp] lemma rationalR_eq (J : ℕ) : rationalR J=sourceR J := by + simp only [rationalR,sourceR,← rationalEta_cast J,← Rat.cast_inv,← Rat.cast_pow,ceil_rat_real] +@[simp] lemma rationalT_eq (J : ℕ) : rationalT J=sourceT J := by + rw [rationalT,sourceT,← ceil_rat_real] + congr 1 + simp + +lemma rho_even (σ : ℝ) (t : ℕ) : (smoothingRho σ)^(2*t)=((1+σ^2)⁻¹)^t := by + rw [pow_mul] + congr 1 + unfold smoothingRho + rw [inv_pow,Real.sq_sqrt (by positivity)] + +lemma cutoff_tail {r : ℝ} (hr : 0 ≤ r) {s : ℕ} + (hstep : ((s:ℝ)+3)*r ≤ (s:ℝ)+2) (hbase : ((s:ℝ)+2)*r^(s+2) ≤ 1/16) : + ∀ t : ℕ, s+2 ≤ t → (t:ℝ)*r^t ≤ 1/16 := by + have hr1 : r ≤ 1 := by nlinarith [Nat.cast_nonneg (α := ℝ) s] + intro t ht + induction t,ht using Nat.le_induction with + | base => simpa only [Nat.cast_add,Nat.cast_ofNat] using hbase + | succ t ht ih => + have ht' : (s:ℝ)+2 ≤ t := by exact_mod_cast ht + have hd : ((t:ℝ)+1)*r ≤ t := by nlinarith + calc + ((t+1:ℕ):ℝ)*r^(t+1) = (((t:ℝ)+1)*r)*r^t := by push_cast; rw [pow_succ]; ring + _ ≤ (t:ℝ)*r^t := mul_le_mul_of_nonneg_right hd (pow_nonneg hr _) + _ ≤ _ := ih + +lemma exists_finite_cutoff {σ : ℝ} (hσ : 0 < σ) : + ∃ s : ℕ, ((s:ℝ)+3)*(1+σ^2)⁻¹ ≤ (s:ℝ)+2 ∧ + ((s:ℝ)+2)*((1+σ^2)⁻¹)^(s+2) ≤ 1/16 := by + obtain ⟨s,hs⟩ := exists_cutoff (smoothingRho_lt_one hσ.ne') (by norm_num : (0:ℝ) < 1/16) + obtain ⟨a,ha⟩ := exists_nat_gt ((σ^2)⁻¹) + refine ⟨max s a,?_,?_⟩ + · have hb : (a:ℝ)*σ^2 > 1 := by + have := (div_lt_iff₀ (show 0 < σ^2 by positivity)).mp (show 1/σ^2 < a by simpa using ha) + linarith + have hc : (a:ℝ) ≤ max s a := by exact_mod_cast le_max_right s a + apply (mul_inv_le_iff₀ (show 0 < 1+σ^2 by positivity)).mpr + nlinarith [sq_nonneg σ] + · have hh := hs (max s a+2) (by omega) + rw [rho_even] at hh + simpa only [Nat.cast_add,Nat.cast_ofNat] using hh + +lemma pairClass_card_le (m : ℕ) : Fintype.card (Option (PairClass m)) ≤ m^2+1 := by + have h := Fintype.card_le_of_injective (fun p : PairClass m => p.val) Subtype.val_injective + simpa only [Fintype.card_option,Fintype.card_prod,Fintype.card_fin,pow_two] using Nat.add_le_add_right h 1 + +lemma row_card (m n : ℕ) : Fintype.card (Row m n)=m*n^(m-1) := by + classical + simp only [Row,Fintype.card_sigma,Fintype.card_fun,Fintype.card_fin] + have he (i : Fin m) : Fintype.card {j : Fin m // j ≠ i}=m-1 := by + rw [Fintype.card_subtype_compl] + simp + simp only [he,Finset.sum_const,Finset.card_univ,Fintype.card_fin,nsmul_eq_mul,Nat.cast_id] +end MinUncut.Inner + +end +section +noncomputable section +open scoped BigOperators +namespace MinUncut.Outer +open MinUncut.Inner MinUncut.FiniteGaussian OuterSmoothness +attribute [local instance] Classical.propDecidable BinaryFourier.dualFintype +variable {Name I S : Type*} [Fintype I] [Fintype S] [Nonempty S] + +lemma edgeMean_abs_difference (equations : S → Equation Name) {k : ℕ} + (hk : k≤Fintype.card I) (F G : EdgeStatistic Name I) {ε : ℝ} + (h : ∀ U hidden pos, |F U hidden pos-G U hidden pos|≤ε) : + |edgeMean equations k F-edgeMean equations k G|≤ε := by + let : Nonempty (FixedSets I k) := fixedSets_nonempty hk + apply expect_abs_difference + intro H + apply expect_abs_difference + intro a + apply expect_abs_difference + intro pos + exact h _ _ _ + +def ProofFamily.finiteErrors {J : ℕ} (P : InnerParameters J) (O : OuterParameters J P) + (g : GridData) (f : ProofFamily Name I) (equations : S → Equation Name) : Test → ℝ + | .first => edgeMean equations O.k (fun U h pos => finiteFirst (m := P.m) (n := P.n) g + (f.second (secondQuestion U h pos)) (rationalSigma J) (rationalEta J)) + | .second => edgeMean equations O.k (fun U h pos => finiteSecond (m := P.m) (n := P.n) g + (f.second (secondQuestion U h pos)) ((sourceEta J)^2/P.m) (rationalSigma J) (rationalEta J)) + | .third => edgeMean equations O.k (fun U h pos => finiteThird (m := P.m) (n := P.n) g + (f.second (secondQuestion U h pos)) (rationalSigma J) (rationalEta J)) + | .fourth => edgeMean equations O.k (fun U h pos => finiteFourth (m := P.m) (n := P.n) g + (projection U h pos) (f.first U) (f.second (secondQuestion U h pos)) (rationalSigma J) (rationalEta J)) + +def ProofFamily.finiteCost {J : ℕ} (P : InnerParameters J) (O : OuterParameters J P) + (g : GridData) (f : ProofFamily Name I) (equations : S → Equation Name) : ℝ := + ∑ j, f.finiteErrors P O g equations j / budgets P O j + +def budgetWeight {J : ℝ} (P : InnerParameters J) (O : OuterParameters J P) : ℝ := + ∑ j, (budgets P O j)⁻¹ + +lemma rational_source_bounds {J : ℕ} (hJ : 1≤J) : + 0≤rationalSigma J ∧ rationalSigma J≤1 ∧ 0≤rationalEta J ∧ rationalEta J≤1 := by + have hJ' : (1:ℝ)≤J := by exact_mod_cast hJ + have hs := sourceSigma_pos hJ' + have hs1 := sourceSigma_le_one hJ' + have he := sourceEta_pos hJ' + have he1 := (sourceEta_le_sigma hJ').trans hs1 + rw [← rationalSigma_cast] at hs hs1 + rw [← rationalEta_cast] at he he1 + exact ⟨by exact_mod_cast hs.le,by exact_mod_cast hs1,by exact_mod_cast he.le,by exact_mod_cast he1⟩ + +attribute [local irreducible] edgeMean +lemma ProofFamily.finiteErrors_difference {J : ℕ} (hJ : 1≤J) (P : InnerParameters J) + (O : OuterParameters J P) (f : ProofFamily Name I) (equations : S → Equation Name) + (hk : O.k≤Fintype.card I) {ε : ℚ} (hε : 0<ε) (j : Test) : + |f.testErrors P O equations j- + f.finiteErrors P O (tableGrid P.m P.n ε hε) equations j|≤ε := by + have hn : 0 rw [ProofFamily.testErrors,ProofFamily.finiteErrors] <;> + apply edgeMean_abs_difference equations hk <;> intro U hidden pos + · simpa only [rationalSigma_cast,rationalEta_cast] using + finiteFirst_difference (f.second (secondQuestion U hidden pos)) hn hs hs1 he he1 hε + · simpa only [rationalSigma_cast,rationalEta_cast] using + finiteSecond_difference (f.second (secondQuestion U hidden pos)) hn hs hs1 he he1 hε ha.1 ha.2.1 + · simpa only [rationalSigma_cast,rationalEta_cast] using + finiteThird_difference (f.second (secondQuestion U hidden pos)) hn hs hs1 he he1 hε + · simpa only [rationalSigma_cast,rationalEta_cast,ProofFamily.fourthTotal] using + finiteFourth_difference (projection U hidden pos) (f.first U) + (f.second (secondQuestion U hidden pos)) hn hs hs1 he he1 hε + +lemma ProofFamily.finiteCost_difference {J : ℕ} (hJ : 1≤J) (P : InnerParameters J) + (O : OuterParameters J P) (f : ProofFamily Name I) (equations : S → Equation Name) + (hk : O.k≤Fintype.card I) {ε : ℚ} (hε : 0<ε) : + |f.cost P O equations-f.finiteCost P O (tableGrid P.m P.n ε hε) equations|≤ + (ε:ℝ)*budgetWeight P O := by + have hJ' : (1:ℝ)≤J := by exact_mod_cast hJ + unfold ProofFamily.cost ProofFamily.finiteCost + rw [← Finset.sum_sub_distrib] + calc + _ ≤ ∑ j, |f.testErrors P O equations j / budgets P O j- + f.finiteErrors P O (tableGrid P.m P.n ε hε) equations j / budgets P O j| := + Finset.abs_sum_le_sum_abs _ _ + _ ≤ ∑ j, (ε:ℝ) / budgets P O j := Finset.sum_le_sum (fun j _ => by + rw [← sub_div,abs_div,abs_of_pos (budgets_pos hJ' P O j)] + exact div_le_div_of_nonneg_right (f.finiteErrors_difference hJ P O equations hk hε j) + (budgets_pos hJ' P O j).le) + _ = _ := by simp only [budgetWeight,Finset.mul_sum,div_eq_mul_inv] +end MinUncut.Outer + +end +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Search/RationalDenominatorArithmetic.lean b/lean/OAI/Computability/MinUncut/Search/RationalDenominatorArithmetic.lean new file mode 100644 index 0000000000000000000000000000000000000000..93e612086d358c3096fb800cad1a256933633790 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Search/RationalDenominatorArithmetic.lean @@ -0,0 +1,131 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.WeightedTestLaw +import OAI.Computability.MinUncut.Machines.FiniteAlphabetBounds + +namespace OAI + +section +open scoped BigOperators +namespace MinUncut.RationalDenominator +lemma mul_dvd {a b : ℚ} {A B : ℕ} (ha : a.den∣A) (hb : b.den∣B) : (a*b).den∣A*B := + (Rat.mul_den_dvd a b).trans (Nat.mul_dvd_mul ha hb) + +lemma add_dvd {a b : ℚ} {D : ℕ} (ha : a.den∣D) (hb : b.den∣D) : (a+b).den∣D := + (Rat.add_den_dvd_lcm a b).trans (Nat.lcm_dvd ha hb) + +lemma sub_dvd {a b : ℚ} {D : ℕ} (ha : a.den∣D) (hb : b.den∣D) : (a-b).den∣D := + (Rat.sub_den_dvd_lcm a b).trans (Nat.lcm_dvd ha hb) + +lemma prod_dvd {X : Type*} (s : Finset X) (f : X → ℚ) (D : X → ℕ) + (h : ∀ x∈s, (f x).den∣D x) : (∏ x∈s, f x).den∣∏ x∈s, D x := by + classical + induction s using Finset.induction_on with + | empty => simp + | @insert x s hx ih => + rw [Finset.prod_insert hx,Finset.prod_insert hx] + exact mul_dvd (h x (by simp)) (ih (fun y hy => h y (by simp [hy]))) + +lemma inv_nat {N : ℕ} (hN : 0 Rat.den_pos (f x)) + +lemma denominator_dvd_product {X : Type*} [Fintype X] (f : X → ℚ) (x : X) : + (f x).den∣∏ x, (f x).den := Finset.dvd_prod_of_mem _ (Finset.mem_univ x) +end MinUncut.RationalDenominator + +end +section +noncomputable section +open scoped BigOperators +namespace MinUncut.Outer +open MinUncut.Inner MinUncut.FiniteGaussian MinUncut.FiniteProof RationalDenominator OuterSmoothness +attribute [local instance] Classical.propDecidable coordsDecEq +variable {Name I S : Type*} [Fintype I] [Fintype S] {m n k : ℕ} + +lemma rationalRowDensity_den {W : Type*} [Fintype W] [DecidableEq W] (a : ℚ) (b c : W) : + (RowNoise.rationalRowDensity a b c).den∣a.den := by + unfold RowNoise.rationalRowDensity + apply add_dvd _ (dvd_refl _) + split_ifs + · exact (mul_nat_dvd (1-a) _).trans (sub_dvd (by simp) (dvd_refl _)) + · simp + +lemma rationalDensity_den {R W : Type*} [Fintype R] [Fintype W] [DecidableEq W] + (a : ℚ) (B C : R → W) : (RowNoise.rationalDensity a B C).den∣a.den^Fintype.card R := by + have hh := prod_dvd (Finset.univ : Finset R) (fun r => RowNoise.rationalRowDensity a (B r) (C r)) + (fun _ => a.den) (fun r _ => rationalRowDensity_den a (B r) (C r)) + simpa only [RowNoise.rationalDensity,Finset.prod_const,Finset.card_univ] using hh + +lemma noiseWeight_den {V A : Type*} [AddCommGroup V] [Module F₂ V] [AddTorsor V A] [Fintype A] + (a : ℚ) (B C : FaceArray A m n) (j : Test) : + (noiseWeight a B C j).den∣a.den^Fintype.card (Row m n) := by + cases j with + | second => exact rationalDensity_den a B C + | first => exact one_dvd _ + | third => exact one_dvd _ + | fourth => exact one_dvd _ + +def gridDenominator (m n : ℕ) (g : GridData) : ℕ := + ∏ q : TestCoordinates m n → Fin g.L, (gridWeight g q).den + +def budgetDenominator (b : Test → ℚ) : ℕ := ∏ j, (b j)⁻¹.den + +def innerDenominator (t m n : ℕ) (g : GridData) (a : ℚ) (b : Test → ℚ) : ℕ := + (faceCardBound t m n).factorial*(faceCardBound t m n).factorial* + Fintype.card (Code m n)*gridDenominator m n g*a.den^Fintype.card (Row m n)*budgetDenominator b + +def samplerDenominator (I S : Type*) [Fintype I] [Fintype S] (k m n : ℕ) + (g : GridData) (a : ℚ) (b : Test → ℚ) : ℕ := + Fintype.card (OuterSample I S k)*innerDenominator (Fintype.card I) m n g a b + +lemma innerDenominator_pos (t m n : ℕ) (g : GridData) (a : ℚ) (b : Test → ℚ) : + 0 < innerDenominator t m n g a b := by + have hC := Fintype.card_pos (α := Code m n) + have hg : 0.mpr hM' + have h1 : ⌈M^2/u^2⌉₊ ≤ ⌈M'^2/u^2⌉₊ := Nat.ceil_mono (div_le_div_of_nonneg_right hsq (sq_nonneg u)) + have h2 : ⌈M^2/θ^2⌉₊ ≤ ⌈M'^2/θ^2⌉₊ := Nat.ceil_mono (div_le_div_of_nonneg_right hsq (sq_nonneg θ)) + unfold listTerm + apply mul_le_mul_of_nonneg_right _ (pow_nonneg (hintRate_nonnegative q) k) + exact mul_le_mul (by exact_mod_cast h1) (by exact_mod_cast h2) (by positivity) (by positivity) + +lemma remainderTerm_mono {M M' u θ : ℝ} (hM : 0 ≤ M) (hM' : M ≤ M') (hu : 0 < u) (q k t : ℕ) : + remainderTerm M u θ q k t ≤ remainderTerm M' u θ q k t := by + have hsq : M^2 ≤ M'^2 := sq_le_sq₀ hM (hM.trans hM') |>.mpr hM' + unfold remainderTerm + apply mul_le_mul_of_nonneg_left _ (by positivity) + apply add_le_add (mul_le_mul_of_nonneg_left hsq (sq_nonneg u)) + apply mul_le_mul_of_nonneg_left _ (Real.sqrt_nonneg _) + gcongr + +structure OuterData where + u : ℚ + b4 : ℚ + v : ℚ + k : ℕ + t : ℕ + deriving DecidableEq, Encodable + +namespace OuterData + +def amplitude (J : ℕ) (d : InnerData) : ℚ := (d.n^d.m+1)/(rationalSigma J) +def hints (d : InnerData) : ℕ := d.m*d.n^(d.m-1)-1 +def rate (q : ℕ) : ℚ := 1-1/(2:ℚ)^q*(1-99999999/100000000) +def listBound (J : ℕ) (d : InnerData) (o : OuterData) : ℚ := + (⌈amplitude J d^2/o.u^2⌉₊:ℚ)*(⌈amplitude J d^2/d.θ^2⌉₊:ℚ)*rate (hints d)^o.k +def radicand (d : InnerData) (k t : ℕ) : ℚ := + ((2:ℚ)^(4*(hints d+3)*k)-1)*(k:ℚ)^2/(t:ℚ) + +def Check (J : ℕ) (d : InnerData) (o : OuterData) : Prop := + 0 < o.u ∧ 0 < o.b4 ∧ 0 < o.v ∧ 1 ≤ o.t ∧ o.k ≤ o.t ∧ + listBound J d o < d.p/4 ∧ + (64/(d.θ^2*rationalSigma J^2))*(J:ℚ)*o.b4 < d.p/4 ∧ + radicand d o.k o.t < o.v^2 ∧ + (256/d.θ^4)*(o.u^2*amplitude J d^2+o.v*(amplitude J d+amplitude J d^2/o.u)^4) < d.p/2 + +instance (J : ℕ) (d : InnerData) (o : OuterData) : Decidable (Check J d o) := by + unfold Check; infer_instance + +@[simp] lemma rate_cast (q : ℕ) : (rate q:ℝ)=hintRate q := by simp [rate,hintRate,repetitionRate] +@[simp] lemma hints_eq (d : InnerData) : hints d=Fintype.card (Row d.m d.n)-1 := by rw [hints,row_card] + +lemma amplitude_nonneg {J : ℕ} (hJ : 1 ≤ J) (d : InnerData) : 0 ≤ (amplitude J d:ℝ) := by + have hσ := sourceSigma_pos (by exact_mod_cast hJ : (1:ℝ) ≤ J) + unfold amplitude + push_cast + rw [rationalSigma_cast] + positivity + +lemma amplitude_ge {J : ℕ} (hJ : 1 ≤ J) (d : InnerData) : + Real.sqrt (d.n^d.m:ℕ)/sourceSigma J ≤ (amplitude J d:ℝ) := by + have hσ := sourceSigma_pos (by exact_mod_cast hJ : (1:ℝ) ≤ J) + have hroot : Real.sqrt (d.n^d.m:ℕ) ≤ (d.n^d.m:ℕ)+1 := by + apply (Real.sqrt_le_iff).mpr + constructor + · positivity + · have hN := Nat.cast_nonneg (α := ℝ) (d.n^d.m) + nlinarith + unfold amplitude + push_cast + rw [rationalSigma_cast] + apply div_le_div_of_nonneg_right _ hσ.le + simpa only [Nat.cast_pow] using hroot + +lemma listBound_cast (J : ℕ) (d : InnerData) (o : OuterData) : + (listBound J d o:ℝ)=listTerm (amplitude J d) o.u d.θ (hints d) o.k := by + unfold listBound listTerm + push_cast + rw [rate_cast] + rw [← ceil_rat_real (amplitude J d^2/o.u^2),← ceil_rat_real (amplitude J d^2/d.θ^2)] + push_cast + rfl + +def realize {J : ℕ} (hJ : 1 ≤ J) (d : InnerData) (hd : d.Check J) + (o : OuterData) (ho : o.Check J d) : OuterParameters J (d.realize hJ hd) := by + have hu := ho.1 + have hb := ho.2.1 + have hv := ho.2.2.1 + have ht := ho.2.2.2.1 + have hk := ho.2.2.2.2.1 + have hl := ho.2.2.2.2.2.1 + have hbud := ho.2.2.2.2.2.2.1 + have hrad := ho.2.2.2.2.2.2.2.1 + have hrem := ho.2.2.2.2.2.2.2.2 + have hu' : (0:ℝ) < o.u := by exact_mod_cast hu + have hb' : (0:ℝ) < o.b4 := by exact_mod_cast hb + have hv' : (0:ℝ) < o.v := by exact_mod_cast hv + let P := d.realize hJ hd + have hθ := P.hθ + have hM : (0:ℝ) ≤ Real.sqrt (d.n^d.m:ℕ)/sourceSigma J := by + have := sourceSigma_pos (by exact_mod_cast hJ : (1:ℝ) ≤ J) + positivity + have hm := amplitude_ge hJ d + have hL : listTerm (amplitude J d) o.u d.θ (hints d) o.k < (d.p:ℝ)/4 := by + rw [← listBound_cast] + exact_mod_cast hl + have hB : (64/((d.θ:ℝ)^2*(sourceSigma J)^2))*(J:ℝ)*(o.b4:ℝ) < (d.p:ℝ)/4 := by + have h := (Rat.cast_lt.mpr hbud : (_:ℝ) < _) + push_cast at h + simpa only [rationalSigma_cast] using h + have hRad : Real.sqrt (((2:ℝ)^(4*(hints d+3)*o.k)-1)*(o.k:ℝ)^2/(o.t:ℝ)) < (o.v:ℝ) := by + apply (Real.sqrt_lt' hv').mpr + have h := (Rat.cast_lt.mpr hrad : (_:ℝ) < _) + simpa only [radicand,Rat.cast_div,Rat.cast_mul,Rat.cast_sub,Rat.cast_pow, + Rat.cast_natCast,Rat.cast_ofNat,Rat.cast_one] using h + have hR : remainderTerm (amplitude J d) o.u d.θ (hints d) o.k o.t < (d.p:ℝ)/2 := by + have h := (Rat.cast_lt.mpr hrem : (_:ℝ) < _) + push_cast at h + apply lt_of_le_of_lt _ h + unfold remainderTerm + apply mul_le_mul_of_nonneg_left _ (by positivity) + apply add_le_add le_rfl + exact mul_le_mul_of_nonneg_right hRad.le (by positivity) + have hL' := (listTerm_mono hM hm (hints d) o.k).trans_lt hL + have hR' := (remainderTerm_mono hM hm hu' (hints d) o.k o.t).trans_lt hR + refine ⟨o.u,o.b4,o.k,o.t,hu',hb',ht,hk,?_⟩ + change listTerm (Real.sqrt (d.n^d.m:ℕ)/sourceSigma J) o.u d.θ + (Fintype.card (Row d.m d.n)-1) o.k + + (64/((d.θ:ℝ)^2*(sourceSigma J)^2))*(J:ℝ)*o.b4 + + remainderTerm (Real.sqrt (d.n^d.m:ℕ)/sourceSigma J) o.u d.θ + (Fintype.card (Row d.m d.n)-1) o.k o.t < d.p + rw [← hints_eq] + linarith +end OuterData +end MinUncut.Outer + +end +section +namespace MinUncut.Outer.OuterData +open MinUncut.Inner + +lemma check_exists {J : ℕ} (hJ : 1 ≤ J) (d : InnerData) (hd : d.Check J) : + ∃ o : OuterData, o.Check J d := by + have hJq : (1:ℚ) ≤ J := by exact_mod_cast hJ + have hJ0 : (0:ℚ) < J := by linarith + have hσ : 0 < rationalSigma J := by unfold rationalSigma; positivity + have hp : 0 < d.p := by + have hh : (0:ℝ) < d.p := (d.realize hJ hd).hp + exact_mod_cast hh + have hθ : 0 < d.θ := by + have hh : (0:ℝ) < d.θ := (d.realize hJ hd).hθ + exact_mod_cast hh + let M : ℚ := amplitude J d + let C : ℚ := 256/d.θ^4 + have hC : 0 < C := by dsimp [C]; positivity + obtain ⟨u,hu,hub⟩ := exists_between (show (0:ℚ) < min 1 (d.p/(8*C*(M^2+1))) by positivity) + obtain ⟨hu1,huB⟩ := lt_min_iff.mp hub + have hsmall : C*u^2*M^2 < d.p/8 := by + have hb := (lt_div_iff₀ (show (0:ℚ) < 8*C*(M^2+1) by positivity)).mp huB + have hs : u^2 ≤ u := by nlinarith + have h1 := mul_le_mul_of_nonneg_right hs (show 0 ≤ C*M^2 by positivity) + nlinarith + let R : ℚ := (M+M^2/u)^4 + have hR : 0 ≤ R := by dsimp [R]; positivity + obtain ⟨v,hv,hvB⟩ := exists_between (show (0:ℚ) < d.p/(8*C*(R+1)) by positivity) + have hlarge : C*v*R < d.p/8 := by + have hx := (lt_div_iff₀ (show 0 < 8*C*(R+1) by positivity)).mp hvB + nlinarith + obtain ⟨b,hb,hbB⟩ := exists_between (show (0:ℚ) < d.p*d.θ^2*(rationalSigma J)^2/(256*J) by positivity) + have hbudget : (64/(d.θ^2*(rationalSigma J)^2))*(J:ℚ)*b < d.p/4 := by + have hx := (lt_div_iff₀ (show (0:ℚ) < 256*J by positivity)).mp hbB + have he : (64/(d.θ^2*(rationalSigma J)^2))*(J:ℚ)*b = (64*J*b)/(d.θ^2*(rationalSigma J)^2) := by ring + rw [he] + apply (div_lt_iff₀ (show 0 < d.θ^2*(rationalSigma J)^2 by positivity)).mpr + nlinarith + obtain ⟨k,hk⟩ := exists_list_scale (M:ℝ) u d.θ (hints d) + (show (0:ℝ) < (d.p:ℝ)/4 by exact_mod_cast (show (0:ℚ) < d.p/4 by positivity)) + let B : ℚ := ((2:ℚ)^(4*(hints d+3)*k)-1)*(k:ℚ)^2 + obtain ⟨t,ht⟩ := exists_nat_gt (max (k+1:ℚ) (B/v^2)) + have htk : (k:ℚ)+1 < t := lt_of_le_of_lt (le_max_left _ _) ht + have ht0 : (0:ℚ) < t := by have := Nat.cast_nonneg (α := ℚ) k; linarith + have hrad : B/(t:ℚ) < v^2 := by + apply (div_lt_iff₀ ht0).mpr + have hx := (div_lt_iff₀ (show 0 < v^2 by positivity)).mp (lt_of_le_of_lt (le_max_right _ _) ht) + nlinarith + let o : OuterData := ⟨u,b,v,k,t⟩ + refine ⟨o,hu,hb,hv,by exact_mod_cast (show (1:ℚ) ≤ t by have := Nat.cast_nonneg (α := ℚ) k; linarith), + by exact_mod_cast (show (k:ℚ) ≤ t by linarith),?_,hbudget,hrad,?_⟩ + · apply (Rat.cast_lt (K := ℝ)).mp + rw [listBound_cast] + simpa only [Rat.cast_div,Rat.cast_ofNat] using hk + · change C*(u^2*M^2+v*R) < d.p/2 + nlinarith + +def search (J : ℕ) (hJ : 1 ≤ J) (d : InnerData) (hd : d.Check J) : OuterData := + Encodable.choose (check_exists hJ d hd) + +lemma search_check (J : ℕ) (hJ : 1 ≤ J) (d : InnerData) (hd : d.Check J) : + (search J hJ d hd).Check J d := Encodable.choose_spec (check_exists hJ d hd) + +end MinUncut.Outer.OuterData + +end +section +noncomputable section +open scoped BigOperators +namespace MinUncut.Outer +open MinUncut.Inner MinUncut.FiniteGaussian + +def rationalBudgets (J : ℕ) (d : InnerData) (o : OuterData) : Test → ℚ + | .first => 10*rationalSigma J + | .second => 10*(rationalEta J+rationalEta J) + | .third => (Fintype.card (Code d.m d.n):ℚ)⁻¹ + | .fourth => o.b4 + +lemma rationalBudgets_cast {J : ℕ} (hJ : 1≤J) (d : InnerData) (hd : d.Check J) + (o : OuterData) (ho : o.Check J d) (j : Test) : + (rationalBudgets J d o j:ℝ)=budgets (d.realize hJ hd) (o.realize hJ d hd ho) j := by + cases j <;> simp only [rationalBudgets,budgets,Rat.cast_mul,Rat.cast_ofNat, + Rat.cast_add,Rat.cast_inv,Rat.cast_natCast,rationalSigma_cast,rationalEta_cast] <;> rfl + +lemma rationalBudgets_pos {J : ℕ} (hJ : 1≤J) (d : InnerData) (hd : d.Check J) + (o : OuterData) (ho : o.Check J d) (j : Test) : 0 inv_nonneg.mpr (rationalBudgets_pos hJ d hd o ho j).le) + +lemma rationalWeight_cast {J : ℕ} (hJ : 1≤J) (d : InnerData) (hd : d.Check J) + (o : OuterData) (ho : o.Check J d) : + (rationalWeight J d o:ℝ)=budgetWeight (d.realize hJ hd) (o.realize hJ d hd ho) := by + simp only [rationalWeight,budgetWeight,Rat.cast_sum,Rat.cast_inv, + rationalBudgets_cast hJ d hd o ho] + +lemma tableAccuracy_pos {J : ℕ} (hJ : 1≤J) (d : InnerData) (hd : d.Check J) + (o : OuterData) (ho : o.Check J d) : 0 intro h <;> nlinarith +lemma lt_iff (q r : RawRat) : lt q r ↔ q.value intro h <;> nlinarith + +end RawRat + +lemma primrec_pow : Primrec₂ (fun a n : ℕ=>a^n) := by + have h : Primrec₂ (fun a n : ℕ=> Nat.rec (motive := fun _ => ℕ) 1 (fun _ r=>r*a) n) := + Primrec.nat_rec (Primrec.const 1) ((Primrec.nat_mul.comp (Primrec.snd.comp Primrec.snd) Primrec.fst).to₂) + apply h.of_eq + intro a n + induction n with + | zero => rfl + | succ n ih => simp only [ih,pow_succ] + +lemma primrec_factorial : Primrec Nat.factorial := by + have h : Primrec (Nat.rec 1 (fun n r=> (n+1)*r)) := + Primrec.nat_rec₁ 1 ((Primrec.nat_mul.comp (Primrec.succ.comp Primrec.fst) Primrec.snd).to₂) + apply h.of_eq + intro n + induction n with + | zero => rfl + | succ n ih => simp only [ih,Nat.factorial_succ] + +lemma choose_factorial (n k : ℕ) : n.choose k = + if k≤n then n.factorial/(k.factorial*(n-k).factorial) else 0 := by + by_cases h : k≤n + · rw [ite_eq_left h] + exact Nat.choose_eq_factorial_div_factorial h + · rw [ite_eq_right h,Nat.choose_eq_zero_of_lt (by omega : nif p.2≤p.1 then + p.1.factorial/(p.2.factorial*(p.1-p.2).factorial) else 0) := + Primrec.ite (Primrec.nat_le.comp Primrec.snd Primrec.fst) + (Primrec.nat_div.comp (primrec_factorial.comp Primrec.fst) + (Primrec.nat_mul.comp (primrec_factorial.comp Primrec.snd) + (primrec_factorial.comp Primrec.nat_sub))) (Primrec.const 0) + exact h.to₂.of_eq (fun n k=>(choose_factorial n k).symm) + +namespace RawRat + +lemma primrec_ofNat : Primrec ofNat := Primrec.id.pair ((Primrec.const 0).pair (Primrec.const 0)) +lemma primrec_neg : Primrec neg := + (Primrec.fst.comp Primrec.snd).pair (Primrec.fst.pair (Primrec.snd.comp Primrec.snd)) + +lemma primrec_add : Primrec₂ add := by + let p : Primrec (fun q : RawRat × RawRat => q.1.1) := Primrec.fst.comp Primrec.fst + let n : Primrec (fun q : RawRat × RawRat => q.1.2.1) := Primrec.fst.comp (Primrec.snd.comp Primrec.fst) + let d : Primrec (fun q : RawRat × RawRat => q.1.2.2+1) := Primrec.succ.comp (Primrec.snd.comp (Primrec.snd.comp Primrec.fst)) + let p' : Primrec (fun q : RawRat × RawRat => q.2.1) := Primrec.fst.comp Primrec.snd + let n' : Primrec (fun q : RawRat × RawRat => q.2.2.1) := Primrec.fst.comp (Primrec.snd.comp Primrec.snd) + let d' : Primrec (fun q : RawRat × RawRat => q.2.2.2+1) := Primrec.succ.comp (Primrec.snd.comp (Primrec.snd.comp Primrec.snd)) + exact ((Primrec.nat_add.comp (Primrec.nat_mul.comp p d') (Primrec.nat_mul.comp p' d)).pair + ((Primrec.nat_add.comp (Primrec.nat_mul.comp n d') (Primrec.nat_mul.comp n' d)).pair + (Primrec.nat_sub.comp (Primrec.nat_mul.comp d d') (Primrec.const 1)))).to₂ + +lemma primrec_mul : Primrec₂ mul := by + let p : Primrec (fun q : RawRat × RawRat => q.1.1) := Primrec.fst.comp Primrec.fst + let n : Primrec (fun q : RawRat × RawRat => q.1.2.1) := Primrec.fst.comp (Primrec.snd.comp Primrec.fst) + let d : Primrec (fun q : RawRat × RawRat => q.1.2.2+1) := Primrec.succ.comp (Primrec.snd.comp (Primrec.snd.comp Primrec.fst)) + let p' : Primrec (fun q : RawRat × RawRat => q.2.1) := Primrec.fst.comp Primrec.snd + let n' : Primrec (fun q : RawRat × RawRat => q.2.2.1) := Primrec.fst.comp (Primrec.snd.comp Primrec.snd) + let d' : Primrec (fun q : RawRat × RawRat => q.2.2.2+1) := Primrec.succ.comp (Primrec.snd.comp (Primrec.snd.comp Primrec.snd)) + exact ((Primrec.nat_add.comp (Primrec.nat_mul.comp p p') (Primrec.nat_mul.comp n n')).pair + ((Primrec.nat_add.comp (Primrec.nat_mul.comp p n') (Primrec.nat_mul.comp n p')).pair + (Primrec.nat_sub.comp (Primrec.nat_mul.comp d d') (Primrec.const 1)))).to₂ + +lemma primrec_inv : Primrec inv := by + let p : Primrec (fun q : RawRat => q.1) := Primrec.fst + let n : Primrec (fun q : RawRat => q.2.1) := Primrec.fst.comp Primrec.snd + let d : Primrec (fun q : RawRat => q.2.2+1) := Primrec.succ.comp (Primrec.snd.comp Primrec.snd) + exact Primrec.ite (Primrec.eq.comp p n) (Primrec.const (ofNat 0)) + (Primrec.ite (Primrec.nat_lt.comp n p) + (d.pair ((Primrec.const 0).pair (Primrec.nat_sub.comp (Primrec.nat_sub.comp p n) (Primrec.const 1)))) + ((Primrec.const 0).pair (d.pair (Primrec.nat_sub.comp (Primrec.nat_sub.comp n p) (Primrec.const 1))))) + +lemma primrec_le : PrimrecRel le := by + + let p : Primrec (fun q : RawRat × RawRat => q.1.1) := Primrec.fst.comp Primrec.fst + let n : Primrec (fun q : RawRat × RawRat => q.1.2.1) := Primrec.fst.comp (Primrec.snd.comp Primrec.fst) + let d : Primrec (fun q : RawRat × RawRat => q.1.2.2+1) := Primrec.succ.comp (Primrec.snd.comp (Primrec.snd.comp Primrec.fst)) + let p' : Primrec (fun q : RawRat × RawRat => q.2.1) := Primrec.fst.comp Primrec.snd + let n' : Primrec (fun q : RawRat × RawRat => q.2.2.1) := Primrec.fst.comp (Primrec.snd.comp Primrec.snd) + let d' : Primrec (fun q : RawRat × RawRat => q.2.2.2+1) := Primrec.succ.comp (Primrec.snd.comp (Primrec.snd.comp Primrec.snd)) + exact Primrec.nat_le.comp + (Primrec.nat_add.comp (Primrec.nat_mul.comp p d') (Primrec.nat_mul.comp n' d)) + (Primrec.nat_add.comp (Primrec.nat_mul.comp p' d) (Primrec.nat_mul.comp n d')) + +lemma primrec_lt : PrimrecRel lt := by + let p : Primrec (fun q : RawRat × RawRat => q.1.1) := Primrec.fst.comp Primrec.fst + let n : Primrec (fun q : RawRat × RawRat => q.1.2.1) := Primrec.fst.comp (Primrec.snd.comp Primrec.fst) + let d : Primrec (fun q : RawRat × RawRat => q.1.2.2+1) := Primrec.succ.comp (Primrec.snd.comp (Primrec.snd.comp Primrec.fst)) + let p' : Primrec (fun q : RawRat × RawRat => q.2.1) := Primrec.fst.comp Primrec.snd + let n' : Primrec (fun q : RawRat × RawRat => q.2.2.1) := Primrec.fst.comp (Primrec.snd.comp Primrec.snd) + let d' : Primrec (fun q : RawRat × RawRat => q.2.2.2+1) := Primrec.succ.comp (Primrec.snd.comp (Primrec.snd.comp Primrec.snd)) + exact Primrec.nat_lt.comp + (Primrec.nat_add.comp (Primrec.nat_mul.comp p d') (Primrec.nat_mul.comp n' d)) + (Primrec.nat_add.comp (Primrec.nat_mul.comp p' d) (Primrec.nat_mul.comp n d')) + +def pow (q : RawRat) : ℕ → RawRat + | 0 => ofNat 1 + | n+1 => mul (pow q n) q +@[simp] lemma value_pow (q : RawRat) (n : ℕ) : (pow q n).value=q.value^n := by + induction n with + | zero => simp [pow] + | succ n ih => simp only [pow,value_mul,ih,pow_succ] +lemma primrec_pow : Primrec₂ pow := by + have h : Primrec₂ (fun q n => Nat.rec (motive:=fun _=>RawRat) (ofNat 1) (fun _ r=>mul r q) n) := + Primrec.nat_rec (Primrec.const (ofNat 1)) ((primrec_mul.comp (Primrec.snd.comp Primrec.snd) Primrec.fst).to₂) + apply h.of_eq + intro q n + induction n with + | zero => rfl + | succ n ih => simp only [ih,pow] + +def ceil (q : RawRat) : ℕ := (q.1-q.2.1+q.2.2)/(q.2.2+1) +lemma primrec_ceil : Primrec ceil := + Primrec.nat_div.comp + (Primrec.nat_add.comp (Primrec.nat_sub.comp Primrec.fst (Primrec.fst.comp Primrec.snd)) (Primrec.snd.comp Primrec.snd)) + (Primrec.succ.comp (Primrec.snd.comp Primrec.snd)) + +end RawRat +end MinUncut.Preprocess + +namespace MinUncut.Preprocess.RawRat +lemma ceil_eq (q : RawRat) : q.ceil=⌈q.value⌉₊ := by + apply Nat.le_antisymm + · unfold ceil + rw [Nat.div_le_iff_le_mul_add_pred (by omega : 0a ∣ b) := + (Primrec.eq.comp (Primrec.nat_mod.comp Primrec.snd Primrec.fst) (Primrec.const 0)).of_eq + (by intro p; exact Nat.dvd_iff_mod_eq_zero.symm) + have hf : Primrec (fun p : ℕ × ℕ => Nat.findGreatest (fun k=>k∣p.1 ∧ k∣p.2) p.2) := + Primrec.nat_findGreatest Primrec.snd + ((hd.comp Primrec.snd (Primrec.fst.comp Primrec.fst)).and + (hd.comp Primrec.snd (Primrec.snd.comp Primrec.fst))) + apply (Primrec.ite (Primrec.eq.comp Primrec.snd (Primrec.const 0)) Primrec.fst hf).to₂.of_eq + intro m n + by_cases hn : n=0 + · simp [hn] + · simp only [hn,ite_false] + have hgn : m.gcd n≤n := Nat.gcd_le_right m (by omega) + have hdvd : (Nat.findGreatest (fun k=>k∣m ∧ k∣n) n) ∣ m.gcd n := by + have hh := Nat.findGreatest_spec (P:=fun k=>k∣m ∧ k∣n) hgn ⟨Nat.gcd_dvd_left m n,Nat.gcd_dvd_right m n⟩ + exact Nat.dvd_gcd hh.1 hh.2 + apply Nat.le_antisymm + · exact Nat.le_of_dvd (Nat.gcd_pos_of_pos_right m (by omega)) hdvd + · exact Nat.le_findGreatest hgn ⟨Nat.gcd_dvd_left m n,Nat.gcd_dvd_right m n⟩ + +lemma primrec_intCode : Primrec (Equiv.intEquivNat : ℤ → ℕ) := Primrec.encode + +lemma intCode_nat (n : ℕ) : Equiv.intEquivNat (Int.ofNat n)=2*n := by + rfl +lemma intCode_negSucc (n : ℕ) : Equiv.intEquivNat (Int.negSucc n)=2*n+1 := by + simp [Equiv.intEquivNat,Equiv.intEquivNatSumNat] + +lemma primrec_intAbs : Primrec Int.natAbs := by + apply (Primrec.nat_div.comp (Primrec.succ.comp primrec_intCode) (Primrec.const 2)).of_eq + intro z + cases z with + | ofNat n => rw [intCode_nat]; change (2*n).succ/2=n; omega + | negSucc n => rw [intCode_negSucc]; simp only [Int.natAbs_negSucc]; omega + +lemma primrec_intToNat : Primrec Int.toNat := by + apply (Primrec.ite (Primrec.eq.comp + (Primrec.nat_mod.comp primrec_intCode (Primrec.const 2)) (Primrec.const 0)) + (Primrec.nat_div.comp primrec_intCode (Primrec.const 2)) (Primrec.const 0)).of_eq + intro z + cases z with + | ofNat n => rw [intCode_nat]; simp + | negSucc n => rw [intCode_negSucc]; simp + +lemma primrec_intNegToNat : Primrec (fun z : ℤ=>(-z).toNat) := by + apply (Primrec.ite (Primrec.eq.comp + (Primrec.nat_mod.comp primrec_intCode (Primrec.const 2)) (Primrec.const 0)) + (Primrec.const 0) + (Primrec.succ.comp (Primrec.nat_div.comp primrec_intCode (Primrec.const 2)))).of_eq + intro z + cases z with + | ofNat n => rw [intCode_nat]; simp + | negSucc n => rw [intCode_negSucc]; simp; omega + +abbrev RationalPair := {p : ℤ × ℕ // 00decide (RawRat.le q (RawRat.represent r) ∧ RawRat.le (RawRat.represent r) q)) + +lemma candidate_eq {q : RawRat} {n : ℕ} {r : ℚ} (h : r ∈ candidate q n) : r=q.value := by + have hh : RawRat.le q (RawRat.represent r) ∧ RawRat.le (RawRat.represent r) q := by + cases hn : decode (α:=ℚ) n with + | none => simp [candidate,hn] at h + | some s => + have ht : s=r ∧ RawRat.le q (RawRat.represent r) ∧ RawRat.le (RawRat.represent r) q := by + simpa [candidate,hn] using h + exact ht.2 + have h₁ := (RawRat.le_iff q (RawRat.represent r)).mp hh.1 + have h₂ := (RawRat.le_iff (RawRat.represent r) q).mp hh.2 + simpa only [RawRat.value_represent] using le_antisymm h₂ h₁ + +lemma candidate_exists (q : RawRat) : ∃ n, q.value ∈ candidate q n := by + refine ⟨encode q.value,?_⟩ + simp only [candidate,encodek,Option.filter_some,Option.mem_def] + have h₁ : RawRat.le q (RawRat.represent q.value) := by + rw [RawRat.le_iff,RawRat.value_represent] + have h₂ : RawRat.le (RawRat.represent q.value) q := by + rw [RawRat.le_iff,RawRat.value_represent] + simp [h₁,h₂] + +lemma candidate_primrec : Primrec₂ candidate := by + have hc : PrimrecPred (fun p : RawRat × ℚ=> RawRat.le p.1 (RawRat.represent p.2) ∧ + RawRat.le (RawRat.represent p.2) p.1) := + (RawRat.primrec_le.comp Primrec.fst (primrec_represent.comp Primrec.snd)).and + (RawRat.primrec_le.comp (primrec_represent.comp Primrec.snd) Primrec.fst) + apply (Primrec.option_bind (Primrec.decode.comp Primrec.snd) + (Primrec.ite (hc.comp ((Primrec.fst.comp Primrec.fst).pair Primrec.snd)) + (Primrec.option_some.comp Primrec.snd) (Primrec.const none)).to₂).to₂.of_eq + intro q n + unfold candidate + cases decode (α:=ℚ) n <;> simp [Option.filter] + +lemma computable_value : Computable RawRat.value := by + apply (Partrec.rfindOpt candidate_primrec.to_comp).of_eq + intro q + apply Part.eq_some_iff.mpr + obtain ⟨n,hn⟩ := candidate_exists q + have hd := Nat.rfindOpt_dom.mpr ⟨n,q.value,hn⟩ + obtain ⟨r,hr⟩ := Part.dom_iff_mem.mp hd + obtain ⟨m,hm⟩ := Nat.rfindOpt_spec hr + rw [candidate_eq hm] at hr + exact hr + +lemma computable_ratAdd : Computable₂ (fun q r : ℚ=>q+r) := by + have h : Computable (fun p : ℚ × ℚ=>RawRat.add (RawRat.represent p.1) (RawRat.represent p.2)) := + RawRat.primrec_add.to_comp.comp (primrec_represent.to_comp.comp Computable.fst) + (primrec_represent.to_comp.comp Computable.snd) + exact (computable_value.comp h).of_eq (by intro p; simp only [RawRat.value_add,RawRat.value_represent]) +lemma computable_ratMul : Computable₂ (fun q r : ℚ=>q*r) := by + have h : Computable (fun p : ℚ × ℚ=>RawRat.mul (RawRat.represent p.1) (RawRat.represent p.2)) := + RawRat.primrec_mul.to_comp.comp (primrec_represent.to_comp.comp Computable.fst) + (primrec_represent.to_comp.comp Computable.snd) + exact (computable_value.comp h).of_eq (by intro p; simp only [RawRat.value_mul,RawRat.value_represent]) +lemma computable_ratNeg : Computable (fun q : ℚ=>-q) := by + exact (computable_value.comp (RawRat.primrec_neg.to_comp.comp primrec_represent.to_comp)).of_eq + (by intro q; simp only [RawRat.value_neg,RawRat.value_represent]) +lemma computable_ratInv : Computable (fun q : ℚ=>q⁻¹) := by + exact (computable_value.comp (RawRat.primrec_inv.to_comp.comp primrec_represent.to_comp)).of_eq + (by intro q; simp only [RawRat.value_inv,RawRat.value_represent]) +lemma computable_ratSub : Computable₂ (fun q r : ℚ=>q-r) := + (computable_ratAdd.comp Computable.fst (computable_ratNeg.comp Computable.snd)).of_eq + (by intro p; exact (sub_eq_add_neg p.1 p.2).symm) +lemma computable_ratDiv : Computable₂ (fun q r : ℚ=>q/r) := + (computable_ratMul.comp Computable.fst (computable_ratInv.comp Computable.snd)).of_eq + (by intro p; exact (div_eq_mul_inv p.1 p.2).symm) +lemma computable_ratPow : Computable₂ (fun (q : ℚ) (n : ℕ)=>q^n) := by + have h : Computable (fun p : ℚ × ℕ=>RawRat.pow (RawRat.represent p.1) p.2) := + RawRat.primrec_pow.to_comp.comp (primrec_represent.to_comp.comp Computable.fst) Computable.snd + exact (computable_value.comp h).of_eq (by intro p; simp only [RawRat.value_pow,RawRat.value_represent]) +lemma computable_ratNat : Computable (fun n : ℕ=>(n:ℚ)) := + (computable_value.comp RawRat.primrec_ofNat.to_comp).of_eq (by intro n; simp only [RawRat.value_nat]) +lemma primrec_ratLe : PrimrecRel (fun q r : ℚ=>q≤r) := + (RawRat.primrec_le.comp (primrec_represent.comp Primrec.fst) + (primrec_represent.comp Primrec.snd)).of_eq (by intro p; simp [RawRat.le_iff]) +lemma primrec_ratLt : PrimrecRel (fun q r : ℚ=>q⌈q⌉₊) := + (RawRat.primrec_ceil.comp primrec_represent).of_eq (by intro q; rw [RawRat.ceil_eq,RawRat.value_represent]) + +end MinUncut.Preprocess + +section +attribute [fun_prop] Computable ComputablePred + +namespace MinUncut.Preprocess +variable {α : Type} [Primcodable α] + +@[fun_prop] lemma ca_id : Computable (fun a : α=>a) := Computable.id +@[fun_prop] lemma ca_const {β : Type} [Primcodable β] (b : β) : Computable (fun _ : α=>b) := Computable.const b +@[fun_prop] lemma ca_fst {β : Type} [Primcodable β] : Computable (Prod.fst : α × β → α) := Computable.fst +@[fun_prop] lemma ca_snd {β : Type} [Primcodable β] : Computable (Prod.snd : α × β → β) := Computable.snd +@[fun_prop] lemma ca_comp {β γ : Type} [Primcodable β] [Primcodable γ] {g : β → γ} {f : α → β} + (hg : Computable g) (hf : Computable f) : Computable (fun x=>g (f x)) := hg.comp hf +@[fun_prop] lemma ca_pair {β γ : Type} [Primcodable β] [Primcodable γ] {f : α → β} {g : α → γ} + (hf : Computable f) (hg : Computable g) : Computable (fun x=>(f x,g x)) := hf.pair hg +@[fun_prop] lemma ca_add {f g : α → ℕ} (hf : Computable f) (hg : Computable g) : Computable (fun x=>f x+g x) := + Primrec.nat_add.to_comp.comp hf hg +@[fun_prop] lemma ca_sub {f g : α → ℕ} (hf : Computable f) (hg : Computable g) : Computable (fun x=>f x-g x) := + Primrec.nat_sub.to_comp.comp hf hg +@[fun_prop] lemma ca_mul {f g : α → ℕ} (hf : Computable f) (hg : Computable g) : Computable (fun x=>f x*g x) := + Primrec.nat_mul.to_comp.comp hf hg +@[fun_prop] lemma ca_pow {f g : α → ℕ} (hf : Computable f) (hg : Computable g) : Computable (fun x=>f x^g x) := + primrec_pow.to_comp.comp hf hg +@[fun_prop] lemma ca_div {f g : α → ℕ} (hf : Computable f) (hg : Computable g) : Computable (fun x=>f x/g x) := + Primrec.nat_div.to_comp.comp hf hg +@[fun_prop] lemma ca_mod {f g : α → ℕ} (hf : Computable f) (hg : Computable g) : Computable (fun x=>f x%g x) := + Primrec.nat_mod.to_comp.comp hf hg +@[fun_prop] lemma ca_choose {f g : α → ℕ} (hf : Computable f) (hg : Computable g) : Computable (fun x=>(f x).choose (g x)) := + primrec_choose.to_comp.comp hf hg +@[fun_prop] lemma ca_factorial {f : α → ℕ} (hf : Computable f) : Computable (fun x=>(f x).factorial) := + primrec_factorial.to_comp.comp hf +@[fun_prop] lemma ca_ratCast {f : α → ℕ} (hf : Computable f) : Computable (fun x=>(f x:ℚ)) := + computable_ratNat.comp hf +@[fun_prop] lemma ca_ratAdd {f g : α → ℚ} (hf : Computable f) (hg : Computable g) : Computable (fun x=>f x+g x) := computable_ratAdd.comp hf hg +@[fun_prop] lemma ca_ratSub {f g : α → ℚ} (hf : Computable f) (hg : Computable g) : Computable (fun x=>f x-g x) := computable_ratSub.comp hf hg +@[fun_prop] lemma ca_ratMul {f g : α → ℚ} (hf : Computable f) (hg : Computable g) : Computable (fun x=>f x*g x) := computable_ratMul.comp hf hg +@[fun_prop] lemma ca_ratDiv {f g : α → ℚ} (hf : Computable f) (hg : Computable g) : Computable (fun x=>f x/g x) := computable_ratDiv.comp hf hg +@[fun_prop] lemma ca_ratInv {f : α → ℚ} (hf : Computable f) : Computable (fun x=>(f x)⁻¹) := computable_ratInv.comp hf +@[fun_prop] lemma ca_ratPow {f : α → ℚ} {g : α → ℕ} (hf : Computable f) (hg : Computable g) : Computable (fun x=>f x^g x) := computable_ratPow.comp hf hg +@[fun_prop] lemma ca_ratCeil {f : α → ℚ} (hf : Computable f) : Computable (fun x=>⌈f x⌉₊) := primrec_ratCeil.to_comp.comp hf + +@[fun_prop] lemma ca_and {p q : α → Prop} (hp : ComputablePred p) (hq : ComputablePred q) : + ComputablePred (fun x=>p x ∧ q x) := by + rcases hp with ⟨dp,hp⟩ + rcases hq with ⟨dq,hq⟩ + apply Computable.computablePred + exact (Primrec.and.to_comp.comp hp hq).of_eq (by intro x; simp) +@[fun_prop] lemma ca_natLe {f g : α → ℕ} (hf : Computable f) (hg : Computable g) : + ComputablePred (fun x=>f x≤g x) := + (Primrec.nat_le.computablePred.decide.comp (hf.pair hg)).computablePred +@[fun_prop] lemma ca_natLt {f g : α → ℕ} (hf : Computable f) (hg : Computable g) : + ComputablePred (fun x=>f xf x≤g x) := + (primrec_ratLe.computablePred.decide.comp (hf.pair hg)).computablePred +@[fun_prop] lemma ca_ratLt {f g : α → ℚ} (hf : Computable f) (hg : Computable g) : + ComputablePred (fun x=>f x (p.1:ℚ) * (p.2+1)^p.1) := by fun_prop +example : ComputablePred (fun p : ℕ × ℚ=> p.1<2 ∧ (p.1:ℚ)*p.2<4) := by fun_prop +end MinUncut.Preprocess + +end +namespace MinUncut.Preprocess +variable {α β : Type} [Primcodable α] [Primcodable β] + +lemma c_rangeMap {f : α → ℕ → β} (hf : Computable₂ f) : + Computable₂ (fun a n => (List.range n).map (f a)) := by + have hh := Computable.nat_rec (α:=α × ℕ) (σ:=List β) Computable.snd + (Computable.const []) + (Computable.list_concat.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,ih]) + +@[fun_prop] lemma ca_range {f : α → ℕ} (hf : Computable f) : + Computable (fun a=>List.range (f a)) := Primrec.list_range.to_comp.comp hf +@[fun_prop] lemma ca_sum {f : α → List ℕ} (hf : Computable f) : + Computable (fun a=>(f a).sum) := by + exact (Primrec.list_foldr Primrec.id (Primrec.const 0) + (Primrec.nat_add.comp (Primrec.fst.comp Primrec.snd) (Primrec.snd.comp Primrec.snd)).to₂).to_comp.comp hf + +lemma c_boundedSum {f : α → ℕ → ℕ} {n : α → ℕ} + (hf : Computable₂ f) (hn : Computable n) : + Computable (fun a=>((List.range (n a)).map (f a)).sum) := + ca_sum ((c_rangeMap hf).comp Computable.id hn) + +end MinUncut.Preprocess + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Search/SampleEnumeration.lean b/lean/OAI/Computability/MinUncut/Search/SampleEnumeration.lean new file mode 100644 index 0000000000000000000000000000000000000000..3702f010e728766c0f67b25857762b8c1239bbfb --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Search/SampleEnumeration.lean @@ -0,0 +1,132 @@ +import Mathlib +import OAI.Computability.MinUncut.Search.FiniteEnumeration +import OAI.Computability.MinUncut.Estimates.WeightedTestLaw +import OAI.Computability.MinUncut.Encoding.QuestionEncoding + +namespace OAI + +section +namespace MinUncut.Outer +open MinUncut.Inner MinUncut.FiniteGaussian MinUncut.FiniteProof OuterSmoothness +open MinUncutGames.Foundations.Hastad.SourceOccurrences + +namespace SampleEnumeration + +def fin (n : ℕ) : Enumeration (Fin n) := Enumeration.ofEncoding (Encoding.fin n) +def field : Enumeration F₂ := Enumeration.ofEncoding fieldEncoding + +def point (m n : ℕ) : Enumeration (Point m n) := (fin m).function (fin n) +def row (m n : ℕ) : Enumeration (Row m n) := + (fin m).sigma (fun i => ((fin m).subtype (fun j => j≠i)).function (fin n)) + +local instance codeEq (m n : ℕ) : DecidableEq (Code m n) := + Subtype.instDecidableEq + +def code (m n : ℕ) : Enumeration (Code m n) := + ((row m n).function field).image (faceSum m n).rangeRestrict (by + intro z + obtain ⟨f,hf⟩ := z.property + exact ⟨f,Subtype.ext hf⟩) + +local instance codeType (m n : ℕ) : Fintype (Code m n) := + Fintype.ofList (code m n).values (code m n).complete + +abbrev Slots {N t : ℕ} (Q : Fin t → SecondQuestion (Fin N)) := + Σ j, Fin (secondSlotCount (Q j)) + +def slots {N t : ℕ} (Q : Fin t → SecondQuestion (Fin N)) : Enumeration (Slots Q) := + (fin t).sigma (fun j => fin (secondSlotCount (Q j))) + +def formsPiEquiv (A : Type) [Fintype A] [DecidableEq A] : + Forms (A → F₂) ≃ F₂ × (A → F₂) := + (AffineMap.toConstProdLinearMap F₂).toEquiv.trans + (Equiv.prodCongr (Equiv.refl F₂) (LinearEquiv.piRing F₂ F₂ A F₂).toEquiv) + +def formsCurryEquiv (A : Type) (B : A → Type) : + Forms (∀a, B a → F₂) ≃ Forms ((Σa, B a) → F₂) := + AffineEquiv.arrowCongrEquiv + (LinearEquiv.piCurry F₂ (fun (_ : A) (_ : B _) => F₂)).symm.toAffineEquiv + (AffineEquiv.refl F₂ F₂) + +def formsEquiv {N t : ℕ} (Q : Fin t → SecondQuestion (Fin N)) : + Forms (SecondAlphabet Q) ≃ F₂ × (Slots Q → F₂) := + (formsCurryEquiv (Fin t) (fun j => Fin (secondSlotCount (Q j)))).trans (formsPiEquiv (Slots Q)) + +local instance formEq {N t : ℕ} (Q : Fin t → SecondQuestion (Fin N)) : + DecidableEq (Forms (SecondAlphabet Q)) := + fun f g => decidable_of_iff (formsEquiv Q f=formsEquiv Q g) (formsEquiv Q).injective.eq_iff + +def forms {N t : ℕ} (Q : Fin t → SecondQuestion (Fin N)) : Enumeration (Forms (SecondAlphabet Q)) := + (field.pair ((slots Q).function field)).image (formsEquiv Q).symm (formsEquiv Q).symm.surjective + +def arrays {N t : ℕ} (Q : Fin t → SecondQuestion (Fin N)) (m n : ℕ) : + Enumeration (FaceArray (SecondAlphabet Q) m n) := (row m n).function (forms Q) + +def coordinates (m n : ℕ) : Enumeration (TestCoordinates m n) := + Enumeration.ofEncoding ((point m n).encoding.sum ((point m n).encoding.sum (code m n).encoding)) + +def localSample {N t : ℕ} (Q : Fin t → SecondQuestion (Fin N)) (m n : ℕ) (g : GridData) : + Enumeration (LocalSample (SecondAlphabet Q) m n g) := by + letI : DecidableEq (Forms (SecondAlphabet Q)) := formEq Q + letI : DecidableEq (FaceArray (SecondAlphabet Q) m n) := inferInstanceAs (DecidableEq (Row m n → Forms (SecondAlphabet Q))) + exact (arrays Q m n).pair ((arrays Q m n).pair ((code m n).pair ((coordinates m n).function (fin g.L)))) + +def finsets (t : ℕ) : Enumeration (Finset (Fin t)) := + ((fin t).function (Enumeration.ofEncoding Encoding.bool)).image + (fun f => Finset.univ.filter (fun j => f j=true)) (by + intro S + refine ⟨fun j => decide (j∈S),?_⟩ + ext j + simp) + +def fixedSets (t k : ℕ) : Enumeration (FixedSets (Fin t) k) := + (finsets t).subtype (fun H => H.card=k) + +def outerSample (t s k : ℕ) : Enumeration (OuterSample (Fin t) (Fin s) k) := + (fixedSets t k).pair (((fin t).function (fin s)).pair ((fin t).function (fin 3))) + +local instance localEq {N t : ℕ} (Q : Fin t → SecondQuestion (Fin N)) (m n : ℕ) (g : GridData) : + DecidableEq (LocalSample (SecondAlphabet Q) m n g) := by + letI : DecidableEq (Forms (SecondAlphabet Q)) := formEq Q + letI : DecidableEq (FaceArray (SecondAlphabet Q) m n) := + inferInstanceAs (DecidableEq (Row m n → Forms (SecondAlphabet Q))) + exact fun f h => decidable_of_iff + (f.1=h.1 ∧ f.2.1=h.2.1 ∧ f.2.2.1=h.2.2.1 ∧ f.2.2.2=h.2.2.2) + (by constructor <;> intro he <;> aesop) + +def second {N s t : ℕ} (eqs : Fin s → Equation (Fin N)) {k : ℕ} + (o : OuterSample (Fin t) (Fin s) k) : Fin t → SecondQuestion (Fin N) := + fun j => if j∈o.1.val then Sum.inl ((eqs (o.2.1 j)).names (o.2.2 j)) else Sum.inr (eqs (o.2.1 j)) + +lemma second_eq {N s t : ℕ} (eqs : Fin s → Equation (Fin N)) {k : ℕ} + (o : OuterSample (Fin t) (Fin s) k) : second eqs o=sampleSecond eqs o := by + funext j + simp [second,sampleSecond,secondQuestion,sampleFirst,sampleHidden,hiddenSet,slotQuestion] + +def semanticLocal {N s t : ℕ} (eqs : Fin s → Equation (Fin N)) {k : ℕ} + (o : OuterSample (Fin t) (Fin s) k) (m n : ℕ) (g : GridData) : + Enumeration (LocalSample (SecondAlphabet (sampleSecond eqs o)) m n g) := + (second_eq eqs o) ▸ localSample (second eqs o) m n g + +local instance semanticLocalEq {N s t : ℕ} (eqs : Fin s → Equation (Fin N)) {k : ℕ} + (o : OuterSample (Fin t) (Fin s) k) (m n : ℕ) (g : GridData) : + DecidableEq (LocalSample (SecondAlphabet (sampleSecond eqs o)) m n g) := + (second_eq eqs o) ▸ localEq (second eqs o) m n g + +def elementary {N s t : ℕ} (eqs : Fin s → Equation (Fin N)) (k m n : ℕ) (g : GridData) : + Enumeration (Elementary (I := Fin t) eqs k m n g) := + (outerSample t s k).sigma (fun o => semanticLocal eqs o m n g) + +def tests : Enumeration Test := + Enumeration.ofList [.first,.second,.third,.fourth] (by intro j; cases j <;> simp) + +def all {N s t : ℕ} (eqs : Fin s → Equation (Fin N)) (k m n : ℕ) (g : GridData) : + Enumeration (Test × Elementary (I := Fin t) eqs k m n g) := + tests.pair (elementary eqs k m n g) + +end SampleEnumeration +end MinUncut.Outer + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Search/TemplateArithmetic.lean b/lean/OAI/Computability/MinUncut/Search/TemplateArithmetic.lean new file mode 100644 index 0000000000000000000000000000000000000000..bb2955f1ea7871a7c5858fd5cdf7a394da2b26e7 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Search/TemplateArithmetic.lean @@ -0,0 +1,149 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.ExpressionOutput + +namespace OAI + +section +namespace MinUncut.SourceTemplate +open MinUncutGames.Foundations MinUncutGames.Foundations.Target +open PCP Hastad Hastad.SourceContexts Hastad.SourceOccurrences +open MinUncutGames.Reduction.CloneGap +open MinUncut.Costed +open scoped BigOperators + +def keyTag {u : ℕ} : LocalKey u → ℕ + | .inl _ => 0 + | .inr (.inl _) => 1 + | .inr (.inr _) => 2 + +def keyTable {u : ℕ} : LocalKey u → ℕ + | .inl f => (((iEncoding u).function Encoding.bool).code f).val + | .inr (.inl g) => (((jEncoding u).function Encoding.bool).code g).val + | .inr (.inr _) => 0 + +def keyNumber {u : ℕ} (N M c v : ℕ) (x : LocalKey u) : ℕ := + if keyTag x=0 then keyTable x+2^(2^u)*v else + if keyTag x=1 then N^u*2^(2^u)+(keyTable x+2^(8^u)*c) else + N^u*2^(2^u)+M^u*2^(8^u) + +lemma keyAddress_number (F : Formula) {u : ℕ} (c : ClauseContext F u) + (v : VariableContext F u) (x : LocalKey u) : + (keyAddress F c v x).val=keyNumber F.«variables» F.clauses.length + ((clauseEncoding F u).code c).val ((variableEncoding F u).code v).val x := by + cases x with + | inl f => rfl + | inr x => + cases x with + | inl g => rfl + | inr z => cases z; rfl + +def signatureEquiv (u : ℕ) : Signature u ≃ + (Fin u → Slot → Bool) × ((Fin u × Slot) → (Fin u × Slot) → Bool) where + toFun s := (s.positive,s.same) + invFun p := ⟨p.1,p.2⟩ + left_inv _ := rfl + right_inv _ := rfl + +def coordinateEncoding (u : ℕ) : Encoding (Fin u × Slot) := (Encoding.fin u).prod slotEncoding + +def signatureEncoding (u : ℕ) : Encoding (Signature u) := + let p := (Encoding.fin u).function (slotEncoding.function Encoding.bool) + let s := (coordinateEncoding u).function ((coordinateEncoding u).function Encoding.bool) + ⟨(p.prod s).size,(signatureEquiv u).trans (p.prod s).code⟩ + +def inputTuple (F : Formula) {u : ℕ} (c : ClauseContext F u) : List ℕ := + ((clauseEncoding F u).code c).val::Complexity.formulaWords F + +def tupleDigit (i : ℕ) : AExpr := .mod (.div (.reg 0) ((AExpr.reg 2).pow i)) (.reg 2) +def slotWord (i : ℕ) (s : Slot) (p : ℕ) : AExpr := + .at (.add (.add (.const 3) (.mul (.const 6) (tupleDigit i))) + (.const (2*(slotEncoding.code s).val+p))) + +lemma tupleDigit_eval (F : Formula) {u : ℕ} (c : ClauseContext F u) (i : Fin u) : + (tupleDigit i.val).eval (inputTuple F c)=(c i).val := by + have h := congrArg Fin.val (congrFun (finFunctionFinEquiv.symm_apply_apply c) i) + have he : (clauseEncoding F u).code c=finFunctionFinEquiv c := by + apply congrArg finFunctionFinEquiv + funext j + rfl + simp only [tupleDigit,AExpr.eval,AExpr.eval_pow,inputTuple,Complexity.formulaWords, + List.cons_append,List.nil_append,List.drop_succ_cons,List.drop_zero,List.headI_cons,he] + exact h + +lemma formula_name_word (F : Formula) (i : Fin F.clauses.length) (s : Slot) : + ((Complexity.formulaWords F).drop (2+6*i.val+2*(slotEncoding.code s).val)).headI= + (nameAt (clauseAt F i) s).val := by + have h : ∀ (xs : List (Clause F.«variables»)) (j : ℕ) (hj : j intro j hj; simp at hj + | cons e es ih => + intro j hj + cases j with + | zero => cases s <;> rfl + | succ j => + have he : 6*(j+1)+2*(slotEncoding.code s).val= + ((((((6*j+2*(slotEncoding.code s).val)+1)+1)+1)+1)+1)+1 := by omega + rw [he] + simpa only [List.flatMap_cons,Complexity.clauseWords,Complexity.literalWords, + List.cons_append,List.nil_append,List.drop_succ_cons,List.getElem_cons_succ] using + ih j (by simpa using hj) + have he : 2+6*i.val+2*(slotEncoding.code s).val=(6*i.val+2*(slotEncoding.code s).val)+1+1 := by omega + rw [he] + exact h F.clauses i.val i.isLt + +lemma formula_positive_word (F : Formula) (i : Fin F.clauses.length) (s : Slot) : + ((Complexity.formulaWords F).drop (2+6*i.val+(2*(slotEncoding.code s).val+1))).headI= + (positiveAt (clauseAt F i) s).toNat := by + have h : ∀ (xs : List (Clause F.«variables»)) (j : ℕ) (hj : j intro j hj; simp at hj + | cons e es ih => + intro j hj + cases j with + | zero => + cases s with + | first => change (if e[0].positive then 1 else 0)=e[0].positive.toNat + cases e[0].positive <;> rfl + | second => change (if e[1].positive then 1 else 0)=e[1].positive.toNat + cases e[1].positive <;> rfl + | third => change (if e[2].positive then 1 else 0)=e[2].positive.toNat + cases e[2].positive <;> rfl + | succ j => + have he : 6*(j+1)+(2*(slotEncoding.code s).val+1)= + ((((((6*j+(2*(slotEncoding.code s).val+1))+1)+1)+1)+1)+1)+1 := by omega + rw [he] + simpa only [List.flatMap_cons,Complexity.clauseWords,Complexity.literalWords, + List.cons_append,List.nil_append,List.drop_succ_cons,List.getElem_cons_succ] using + ih j (by simpa using hj) + have he : 2+6*i.val+(2*(slotEncoding.code s).val+1)= + (6*i.val+(2*(slotEncoding.code s).val+1))+1+1 := by omega + rw [he] + exact h F.clauses i.val i.isLt + +lemma slotWord_name (F : Formula) {u : ℕ} (c : ClauseContext F u) (i : Fin u) (s : Slot) : + (slotWord i.val s 0).eval (inputTuple F c)=(nameAt (clauseAt F (c i)) s).val := by + simp only [slotWord,AExpr.eval,tupleDigit_eval,Nat.add_zero] + have he : 3+6*(c i).val+2*(slotEncoding.code s).val= + (2+6*(c i).val+2*(slotEncoding.code s).val)+1 := by omega + rw [he] + exact formula_name_word F (c i) s + +lemma slotWord_positive (F : Formula) {u : ℕ} (c : ClauseContext F u) (i : Fin u) (s : Slot) : + (slotWord i.val s 1).eval (inputTuple F c)=(positiveAt (clauseAt F (c i)) s).toNat := by + simp only [slotWord,AExpr.eval,tupleDigit_eval] + have he : 3+6*(c i).val+(2*(slotEncoding.code s).val+1)= + (2+6*(c i).val+(2*(slotEncoding.code s).val+1))+1 := by omega + rw [he] + exact formula_positive_word F (c i) s + +end MinUncut.SourceTemplate + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Search/UniformFind.lean b/lean/OAI/Computability/MinUncut/Search/UniformFind.lean new file mode 100644 index 0000000000000000000000000000000000000000..32e87bfab5286f8650fdec1a32acd8e05a350c6e --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Search/UniformFind.lean @@ -0,0 +1,91 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.UniformBoolean +import OAI.Computability.MinUncut.Estimates.UniformTransport + +namespace OAI + +section +namespace MinUncut.Preprocess +open MinUncutGames.Foundations.Hastad.SourceOccurrences +namespace UEncoding +variable {P : Type} [Primcodable P] {A B Γ : P → Type} + +def optionEquiv (X : Type) : Option X ≃ X ⊕ Unit where + toFun x := match x with | some a => .inl a | none => .inr () + invFun x := match x with | .inl a => some a | .inr _ => none + left_inv := by intro x; cases x <;> rfl + right_inv := by intro x; cases x with | inl a => rfl | inr a => cases a; rfl + +def option (a : UEncoding P A) : UEncoding P (fun p=>Option (A p)) := + (a.sum (fixed Encoding.unit)).ofEquiv (fun p=>optionEquiv (A p)) +lemma option_code_some (a : UEncoding P A) (p : P) (x : A p) : + ((a.option.enc p).code (some x)).val=((a.enc p).code x).val := rfl +lemma option_code_none (a : UEncoding P A) (p : P) : + ((a.option.enc p).code none).val=(a.enc p).size := by + change (a.enc p).size+0=_ + omega + +lemma enumeration_codes {X : Type} (a : Encoding X) : + a.enumerate.map (fun x=>(a.code x).val)=List.range a.size := by + simp only [Encoding.enumerate,List.map_ofFn] + rw [List.ofFn_eq_map] + simpa only [Function.comp_def,Equiv.apply_symm_apply] using finRange_values a.size + +lemma map_find (a : UEncoding P A) : + (a.function bool).Map a.option (fun p f=>(a.enc p).enumerate.find? f) := by + let search : ℕ × ℕ → ℕ := fun q=>(List.range q.1).findIdx (fun i=>decide ((q.2/2^i)%2=1)) + have hs : Primrec search := by + exact Primrec.list_findIdx (Primrec.list_range.comp Primrec.fst) + (Primrec.eq.decide.comp₂ + (Primrec.nat_mod.comp₂ + (Primrec.nat_div.comp₂ (Primrec.snd.comp Primrec.fst).to₂ + (primrec_pow.comp₂ (Primrec.const 2).to₂ Primrec.snd.to₂)) + (Primrec.const 2).to₂) (Primrec.const 1).to₂) + refine ⟨fun q=>search ((a.enc q.1).size,q.2),hs.to_comp.comp + ((a.computableSize.comp Computable.fst).pair Computable.snd),?_⟩ + intro p f + have he : search ((a.enc p).size,((a.function bool).enc p).code f|>.val)= + (a.enc p).enumerate.findIdx f := by + unfold search + rw [←enumeration_codes (a.enc p),List.findIdx_map] + congr 1 + funext x + have hd:=function_digit (a.enc p) Encoding.bool f x + change decide ((((a.enc p).function Encoding.bool).code f|>.val)/Encoding.bool.size^((a.enc p).code x|>.val)%Encoding.bool.size=1)=f x + rw [hd,bool_code] + cases f x <;> rfl + dsimp only + rw [he,List.find?_eq_getElem?_findIdx] + by_cases h:(a.enc p).enumerate.findIdx f < (a.enc p).size + · rw [show (a.enc p).enumerate=((List.ofFn (a.enc p).code.symm)) from rfl] + dsimp only [Encoding.enumerate] at h + rw [List.getElem?_ofFn,dite_eq_left h] + simp only [option_code_some,Equiv.apply_symm_apply] + · have hn : (a.enc p).enumerate.findIdx f=(a.enc p).size := + le_antisymm (by simpa using List.findIdx_le_length (p:=f) (xs:=(a.enc p).enumerate)) (by omega) + rw [hn,List.getElem?_eq_none (by simp),option_code_none] + +lemma map_find_apply {g : UEncoding P Γ} {a : UEncoding P A} + {f : ∀p,Γ p → A p → Bool} (hf : g.Map (a.function bool) f) : + g.Map a.option (fun p x=>(a.enc p).enumerate.find? (f p x)) := map_comp hf (map_find a) + +lemma map_option_elim {g : UEncoding P Γ} {a : UEncoding P A} {b : UEncoding P B} + {f : ∀p,Γ p → B p} {h : ∀p,Γ p × A p → B p} + (hf : g.Map b f) (hh : (g.prod a).Map b h) : + (g.prod a.option).Map b (fun p x=>x.2.elim (f p x.1) (fun y=>h p (x.1,y))) := by + have hc:=map_case hh (hf.first (c:=fixed Encoding.unit)) + have ht : (g.prod a.option).Map (g.prod (a.sum (fixed Encoding.unit))) + (fun p x=>(x.1,optionEquiv (A p) x.2)) := + map_pair (map_fst g a.option) + (map_comp (map_snd g a.option) (map_to (a.sum (fixed Encoding.unit)) (fun p=>optionEquiv (A p)))) + obtain ⟨raw, hraw, hraw_spec⟩ := map_comp ht hc + refine ⟨raw, hraw, ?_⟩ + rintro parameter ⟨context, value⟩ + cases value <;> exact hraw_spec parameter _ + +end UEncoding +end MinUncut.Preprocess + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Search/UniformFiniteSum.lean b/lean/OAI/Computability/MinUncut/Search/UniformFiniteSum.lean new file mode 100644 index 0000000000000000000000000000000000000000..02a02ff78036cb350ba4648dd921b732127763ef --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Search/UniformFiniteSum.lean @@ -0,0 +1,126 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.UniformAlgebra + +namespace OAI + +section +namespace MinUncut.Preprocess.UEncoding +open MinUncutGames.Foundations.Hastad.SourceOccurrences +open scoped BigOperators +variable {P X : Type} [Primcodable P] [Primcodable X] [AddCommMonoid X] + {A : P → Type} [∀p,Fintype (A p)] +lemma computable_sum {a : UEncoding P A} {f : ∀p,A p → X} (hf : a.Out f) + (hadd : Computable₂ (fun x y : X=>x+y)) : Computable (fun p=>∑x,f p x) := by + have hh:=out_sum (g:=fixed Encoding.unit) hf.second hadd + obtain ⟨h,hr,he⟩:=hh + exact (hr.comp (Computable.id.pair (Computable.const 0))).of_eq (fun p=>he p ()) +end MinUncut.Preprocess.UEncoding + +end +section +namespace MinUncut.Preprocess + +variable {α β : Type} [Primcodable α] [Primcodable β] + +def decodeGood (dec : ℕ → Option β) (p : α → β → Prop) (x : α) (n : ℕ) : Prop := + (dec n).elim False (p x) + +instance {dec : ℕ → Option β} {p : α → β → Prop} [DecidableRel p] (x : α) (n : ℕ) : + Decidable (decodeGood dec p x n) := by + unfold decodeGood + cases dec n <;> simp only [Option.elim] <;> infer_instance + +lemma c_searchProj : Computable (fun q : (α × ℕ) × β=>(q.1.1,q.2)) := + (Computable.fst.comp Computable.fst).pair Computable.snd +lemma c_searchEval {p : α → β → Prop} [DecidableRel p] + (hp : ComputablePred (fun q : α × β=>p q.1 q.2)) : + Computable (fun q : (α × ℕ) × β=>decide (p q.1.1 q.2)) := + by + have hh : Computable (fun q : α × β=>decide (p q.1 q.2)) := hp.decide + exact @Computable.comp ((α × ℕ) × β) (α × β) Bool _ _ _ + (fun q=>decide (p q.1 q.2)) (fun q=>(q.1.1,q.2)) hh c_searchProj +lemma c_searchDecode {dec : ℕ → Option β} (hd : Computable dec) : + Computable (fun q : α × ℕ=>dec q.2) := hd.comp Computable.snd +lemma c_searchBool {dec : ℕ → Option β} {p : α → β → Prop} [DecidableRel p] + (hd : Computable dec) (hp : ComputablePred (fun q : α × β=>p q.1 q.2)) : + Computable (fun q : α × ℕ=>(dec q.2).elim false (fun b=>decide (p q.1 b))) := + (Computable.option_casesOn (c_searchDecode hd) (ca_const false) ((c_searchEval hp).to₂)).of_eq + (fun q=>by cases dec q.2 <;> rfl) +omit [Primcodable α] [Primcodable β] in +lemma searchBool_eq {dec : ℕ → Option β} {p : α → β → Prop} [DecidableRel p] (q : α × ℕ) : + (dec q.2).elim false (fun b=>decide (p q.1 b))=decide (decodeGood dec p q.1 q.2) := by + cases he : dec q.2 <;> simp only [decodeGood,he,Option.elim,decide_false] +lemma computable_decodeGood {dec : ℕ → Option β} {p : α → β → Prop} + [DecidableRel p] (hd : Computable dec) + (hp : ComputablePred (fun q : α × β=>p q.1 q.2)) : + ComputablePred (fun q : α × ℕ=>decodeGood dec p q.1 q.2) := + ⟨inferInstance,(c_searchBool hd hp).of_eq searchBool_eq⟩ + +instance option_elim_decidable {p : β → Prop} [DecidablePred p] (o : Option β) : + Decidable (o.elim False p) := by + cases o <;> simp only [Option.elim] <;> infer_instance + +lemma choose_getD {γ : Type} [Encodable γ] {p : γ → Prop} [DecidablePred p] (h : ∃b,p b) (d : γ) : + Encodable.choose h = + ((Encodable.decode (α:=γ) (Nat.find (show ∃n,(Encodable.decode (α:=γ) n).elim False p from by + obtain ⟨b,hb⟩:=h + exact ⟨Encodable.encode b,by simp [hb]⟩)))).getD d := by + unfold Encodable.choose + conv_lhs => arg 1; whnf + split + next oldPredicate decoded valid value validValue equation compatibility => + have decodedValue : (Encodable.decode (α := γ) (Nat.find (show + ∃ index, (Encodable.decode (α := γ) index).elim False p from by + obtain ⟨witness, validWitness⟩ := h + exact ⟨Encodable.encode witness, by simp [validWitness]⟩))) = some value := by + convert equation using 2 + congr 1 + funext index + cases Encodable.decode (α := γ) index <;> rfl + rw [decodedValue] + rfl + +noncomputable def search {p : α → β → Prop} [DecidableRel p] + (h : ∀a,∃b,p a b) (a : α) : β := Encodable.choose (h a) + +omit [Primcodable α] in +lemma search_spec {p : α → β → Prop} [DecidableRel p] + (h : ∀a,∃b,p a b) (a : α) : p a (search h a) := + Encodable.choose_spec (h a) + +lemma computable_search {p : α → β → Prop} [DecidableRel p] + (hp : ComputablePred (fun q : α × β=>p q.1 q.2)) + (h : ∀a,∃b,p a b) (d : β) : Computable (search h) := by + have hn : ∀a,∃n,decodeGood (Encodable.decode (α:=β)) p a n := by + intro a + obtain ⟨b,hb⟩:=h a + exact ⟨Encodable.encode b,by simp [decodeGood,hb]⟩ + have hc : Computable (fun a=>Nat.find (hn a)) := + Computable.find (computable_decodeGood Computable.decode hp) hn + exact (Computable.option_getD (Computable.decode.comp hc) (ca_const d)).of_eq (by + intro a + convert (choose_getD (h a) d).symm using 3 + all_goals congr 1) +noncomputable def searchWith (e : Encodable β) {p : α → β → Prop} [DecidableRel p] + (h : ∀a,∃b,p a b) (a : α) : β := @Encodable.choose β (p a) e _ (h a) + +lemma computable_searchWith (e : Encodable β) {p : α → β → Prop} [DecidableRel p] + (hd : Computable (@Encodable.decode β e)) + (hp : ComputablePred (fun q : α × β=>p q.1 q.2)) + (h : ∀a,∃b,p a b) (d : β) : Computable (searchWith e h) := by + have hn : ∀a,∃n,decodeGood (@Encodable.decode β e) p a n := by + intro a + obtain ⟨b,hb⟩:=h a + refine ⟨@Encodable.encode β e b,?_⟩ + simp only [decodeGood,Encodable.encodek,Option.elim_some,hb] + have hc : Computable (fun a=>Nat.find (hn a)) := + Computable.find (computable_decodeGood hd hp) hn + exact (Computable.option_getD (hd.comp hc) (ca_const d)).of_eq (by + intro a + convert (@choose_getD β e (p a) _ (h a) d).symm using 3 + all_goals congr 1) +end MinUncut.Preprocess + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Search/UniformQuantifier.lean b/lean/OAI/Computability/MinUncut/Search/UniformQuantifier.lean new file mode 100644 index 0000000000000000000000000000000000000000..7d3e6d8ccda71a5e3850a0ad65e2297262f11acd --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Search/UniformQuantifier.lean @@ -0,0 +1,100 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.UniformBoolean + +namespace OAI + +section +namespace MinUncut.Preprocess +open MinUncutGames.Foundations.Hastad.SourceOccurrences +namespace UEncoding +variable {P : Type} [Primcodable P] {A B Γ : P → Type} + +lemma Map.ofEq {a : UEncoding P A} {b : UEncoding P B} + {f g : ∀p,A p → B p} (hf : a.Map b f) (h : ∀p x,f p x=g p x) : a.Map b g := by + obtain ⟨f',hr,hf⟩:=hf + exact ⟨f',hr,by intro p x; rw [hf,h]⟩ + +lemma map_true (a : UEncoding P A) : a.Map bool (fun _ _=>true) := + map_const (Computable.const 1) +lemma map_false (a : UEncoding P A) : a.Map bool (fun _ _=>false) := + map_const (Computable.const 0) + +lemma map_forall {g : UEncoding P Γ} {a : UEncoding P A} + {f : ∀p,Γ p × A p → Bool} [∀p s,Decidable (∀x,f p (s,x)=true)] + (hf : (g.prod a).Map bool f) : + g.Map bool (fun p s=>decide (∀x,f p (s,x)=true)) := by + classical + have hh := map_bool_eq (map_lambda hf) (map_lambda (map_true (g.prod a))) + apply hh.ofEq + intro p s + apply decide_eq_decide.mpr + exact ⟨fun h x=>congrFun h x,fun h=>funext h⟩ + +lemma map_exists {g : UEncoding P Γ} {a : UEncoding P A} + {f : ∀p,Γ p × A p → Bool} [∀p s,Decidable (∃x,f p (s,x)=true)] + (hf : (g.prod a).Map bool f) : + g.Map bool (fun p s=>decide (∃x,f p (s,x)=true)) := by + classical + have hh := map_not (map_forall (map_not hf)) + apply hh.ofEq + intro p s + rw [←decide_not] + apply decide_eq_decide.mpr + simp + +def Value (a : UEncoding P A) (f : ∀p,A p → ℕ) : Prop := + ∃g : P × ℕ → ℕ, Computable g ∧ ∀p x,g (p,((a.enc p).code x).val)=f p x + +lemma value_code (a : UEncoding P A) : a.Value (fun p x=>((a.enc p).code x).val) := + ⟨Prod.snd,Computable.snd,by intros; rfl⟩ +lemma value_const (a : UEncoding P A) {f : P → ℕ} (hf : Computable f) : + a.Value (fun p _=>f p) := ⟨_,hf.comp Computable.fst,by intros; rfl⟩ +lemma Value.comp {a : UEncoding P A} {b : UEncoding P B} + {f : ∀p,A p → B p} {g : ∀p,B p → ℕ} (hg : b.Value g) (hf : a.Map b f) : + a.Value (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 Value.map {a : UEncoding P A} {f : ∀p,A p → ℕ} (hf : a.Value f) + {g : ℕ → ℕ} (hg : Computable g) : a.Value (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 Value.map₂ {a : UEncoding P A} {f g : ∀p,A p → ℕ} + (hf : a.Value f) (hg : a.Value g) {op : ℕ → ℕ → ℕ} (hop : Computable₂ op) : + a.Value (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 value_sum {g : UEncoding P Γ} {a : UEncoding P A} + {f : ∀p,Γ p × A p → ℕ} (hf : (g.prod a).Value f) : + g.Value (fun p s=>((a.enc p).enumerate.map (fun x=>f p (s,x))).sum) := by + obtain ⟨f',hf',hf⟩:=hf + let raw : (P × ℕ) → ℕ → ℕ := 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_boundedSum hr (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 congrArg List.sum + apply List.map_congr_left + intro i hi + have hh : f' (p, (((g.enc p).prod (a.enc p)).code (s, (a.enc p).code.symm i)).val) = + f p (s, (a.enc p).code.symm i) := + hf p (s, (a.enc p).code.symm i) + rw [prod_code,Equiv.apply_symm_apply] at hh + exact hh + +end UEncoding +end MinUncut.Preprocess + +end + +end OAI diff --git a/lean/OAI/Computability/MinUncut/Search/UniformRational.lean b/lean/OAI/Computability/MinUncut/Search/UniformRational.lean new file mode 100644 index 0000000000000000000000000000000000000000..f844108550d926f4f1e62aaaeeea027aa6c02598 --- /dev/null +++ b/lean/OAI/Computability/MinUncut/Search/UniformRational.lean @@ -0,0 +1,55 @@ +import Mathlib +import OAI.Computability.MinUncut.Estimates.UniformRestrict +import OAI.Computability.MinUncut.Estimates.AlgebraicSigns + +namespace OAI + +section +namespace MinUncut.Preprocess +open MinUncut.FiniteGaussian +lemma c_algebraicNonneg : Computable (fun p : ℚ × ℚ × ℕ=>algebraicNonneg p.1 p.2.1 p.2.2) := by + have ha : Computable (fun p : ℚ × ℚ × ℕ=>p.1) := Computable.fst + have hb : Computable (fun p : ℚ × ℚ × ℕ=>p.2.1) := Computable.fst.comp Computable.snd + have hn : Computable (fun p : ℚ × ℚ × ℕ=>p.2.2) := Computable.snd.comp Computable.snd + exact (Computable.cond (ca_ratLe (ca_const 0) hb).decide + (Computable.cond (ca_ratLe (ca_const 0) ha).decide (ca_const true) + (ca_ratLe (ca_ratPow ha (ca_const 2)) (ca_ratMul (ca_ratCast hn) (ca_ratPow hb (ca_const 2)))).decide) + (Computable.cond (ca_ratLt ha (ca_const 0)).decide (ca_const false) + (ca_ratLe (ca_ratMul (ca_ratCast hn) (ca_ratPow hb (ca_const 2))) (ca_ratPow ha (ca_const 2))).decide)).of_eq + (by intro p; simp only [algebraicNonneg,Bool.cond_decide]) +namespace UEncoding +variable {P : Type} [Primcodable P] {A : P → Type} {a : UEncoding P A} +variable {f g : ∀p,A p → ℚ} +lemma Out.ratAdd (hf : a.Out f) (hg : a.Out g) : a.Out (fun p x=>f p x+g p x) := + hf.map₂ hg computable_ratAdd +lemma Out.ratSub (hf : a.Out f) (hg : a.Out g) : a.Out (fun p x=>f p x-g p x) := + hf.map₂ hg computable_ratSub +lemma Out.ratMul (hf : a.Out f) (hg : a.Out g) : a.Out (fun p x=>f p x*g p x) := + hf.map₂ hg computable_ratMul +lemma Out.ratDiv (hf : a.Out f) (hg : a.Out g) : a.Out (fun p x=>f p x/g p x) := + hf.map₂ hg computable_ratDiv +lemma Out.ratInv (hf : a.Out f) : a.Out (fun p x=>(f p x)⁻¹) := hf.map computable_ratInv +lemma Out.ratNeg (hf : a.Out f) : a.Out (fun p x=>-f p x) := hf.map computable_ratNeg +lemma Out.ratNat {f : ∀p,A p → ℕ} (hf : a.Out f) : a.Out (fun p x=>(f p x:ℚ)) := + hf.map computable_ratNat +lemma Out.ratPow (hf : a.Out f) {g : ∀p,A p → ℕ} (hg : a.Out g) : + a.Out (fun p x=>f p x^g p x) := hf.map₂ hg computable_ratPow +lemma Out.algebraicNonneg (hf : a.Out f) (hg : a.Out g) {n : ∀p,A p → ℕ} (hn : a.Out n) : + a.Map bool (fun p x=>algebraicNonneg (f p x) (g p x) (n p x)) := + ((hf.pair (hg.pair hn)).map c_algebraicNonneg).toBool +lemma Out.eqBool {X : Type} [Primcodable X] [DecidableEq X] + {f g : ∀p,A p → X} (hf : a.Out f) (hg : a.Out g) : + a.Map bool (fun p x=>decide (f p x=g p x)) := + (hf.map₂ hg Primrec.eq.computablePred.decide.to₂).toBool +lemma Out.natAdd {f g : ∀p,A p → ℕ} (hf : a.Out f) (hg : a.Out g) : + a.Out (fun p x=>f p x+g p x) := hf.map₂ hg Primrec.nat_add.to_comp +lemma Out.natMul {f g : ∀p,A p → ℕ} (hf : a.Out f) (hg : a.Out g) : + a.Out (fun p x=>f p x*g p x) := hf.map₂ hg Primrec.nat_mul.to_comp +lemma Out.natPow {f g : ∀p,A p → ℕ} (hf : a.Out f) (hg : a.Out g) : + a.Out (fun p x=>f p x^g p x) := hf.map₂ hg primrec_pow.to_comp +end UEncoding +end MinUncut.Preprocess + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Algebra/AffineDecoderMeeting.lean b/lean/OAI/Computability/PerfectCompleteness/Algebra/AffineDecoderMeeting.lean new file mode 100644 index 0000000000000000000000000000000000000000..2f43c39c9dd92a94dc3fb50c8d00a8b118a5cbc7 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Algebra/AffineDecoderMeeting.lean @@ -0,0 +1,127 @@ +import OAI.Computability.PerfectCompleteness.Decoding.LeftDecoder +import OAI.Computability.PerfectCompleteness.Foundations.TupleIndexEmitterLemmas + +namespace OAI + + +namespace PerfectCompleteness.AffineDecoderMeeting + +noncomputable section + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Integration.BinaryLinear (F2) + +section Product + +variable {L R : Type*} [Fintype L] [Fintype R] + +theorem product_probability_lower + (left : FiniteDistribution L) (right : FiniteDistribution R) + (event : L × R → Bool) (good : R → Bool) (p : ℝ) + (hpoint : ∀ y, good y = true → + p ≤ left.probability (fun x => event (x, y))) : + p * right.probability good ≤ (left.product right).probability event := by + rw [UsefulAdvice.product_probability_advice_first] + change p * (∑ y, if good y then right.weight y else 0) ≤ + ∑ y, right.weight y * left.probability (fun x => event (x, y)) + rw [Finset.mul_sum] + apply Finset.sum_le_sum + intro y _ + by_cases hy : good y = true + · rw [ite_eq_left hy, mul_comm p] + exact mul_le_mul_of_nonneg_left (hpoint y hy) (right.nonnegative y) + · rw [ite_eq_right hy, mul_zero] + exact mul_nonneg (right.nonnegative y) (left.probability_nonnegative _) + +end Product + +section Algebra + +variable {H H' : Type*} [AddCommGroup H] [Module F2 H] + [AddCommGroup H'] [Module F2 H'] + (i : H' →ₗ[F2] H) (B : Submodule F2 H) + (C : Submodule F2 (Module.Dual F2 (H ⧸ B))) + (center : Module.Dual F2 H) + +def nativeQ : Submodule F2 (Module.Dual F2 H') := + (PulledColumnSpace.pulled B C).map i.dualMap + +def nativeCenter : Module.Dual F2 H' := i.dualMap center + +theorem candidate_mem_nativeCoset (q : PulledColumnSpace.Candidates B C center) : + i.dualMap q.val - nativeCenter i center ∈ nativeQ i B C := by + change i.dualMap q.val - i.dualMap center ∈ + (PulledColumnSpace.pulled B C).map i.dualMap + rw [← map_sub] + exact Submodule.mem_map_of_mem q.property + +theorem exists_candidate_of_mem_nativeCoset (decoded : Module.Dual F2 H') + (hdecoded : decoded - nativeCenter i center ∈ nativeQ i B C) : + ∃ q : PulledColumnSpace.Candidates B C center, i.dualMap q.val = decoded := by + obtain ⟨q, hq, heq⟩ := Submodule.mem_map.mp hdecoded + refine ⟨PulledColumnSpace.candidateEquiv B C center ⟨q, hq⟩, ?_⟩ + change i.dualMap (center + q) = decoded + rw [map_add, heq] + change i.dualMap center + (decoded - i.dualMap center) = decoded + abel + +theorem nativeCoset_iff_exists_candidate (decoded : Module.Dual F2 H') : + decoded - nativeCenter i center ∈ nativeQ i B C ↔ + ∃ q : PulledColumnSpace.Candidates B C center, i.dualMap q.val = decoded := by + constructor + · exact exists_candidate_of_mem_nativeCoset i B C center decoded + · rintro ⟨q, rfl⟩ + exact candidate_mem_nativeCoset i B C center q + +theorem finrank_nativeQ_le [FiniteDimensional F2 H] : + Module.finrank F2 (nativeQ i B C) ≤ Module.finrank F2 C := by + calc + Module.finrank F2 (nativeQ i B C) ≤ + Module.finrank F2 (PulledColumnSpace.pulled B C) := + Submodule.finrank_map_le i.dualMap (PulledColumnSpace.pulled B C) + _ = Module.finrank F2 C := PulledColumnSpace.finrank_pulled B C + +end Algebra + + +variable {H H' : Type*} [AddCommGroup H] [Module F2 H] + [AddCommGroup H'] [Module F2 H'] + [FiniteDimensional F2 H] [FiniteDimensional F2 H'] + +local instance leftDualFintype : Fintype (Module.Dual F2 H) := + LeftDecoder.dualFintype (V := H) + +local instance nativeDualFintype : Fintype (Module.Dual F2 H') := + LeftDecoder.dualFintype (V := H') + +variable (i : H' →ₗ[F2] H) (B : Submodule F2 H) + (C : Submodule F2 (Module.Dual F2 (H ⧸ B))) + (center : Module.Dual F2 H) + +omit [FiniteDimensional F2 H'] in +theorem native_point_probability_lower {r : Nat} + (hC : Module.finrank F2 C ≤ r) (decoded : Module.Dual F2 H') + (hdecoded : decoded - nativeCenter i center ∈ nativeQ i B C) : + 1 / (2 : ℝ) ^ r ≤ (LeftDecoder.affineLaw B C center).probability + (fun q => decide (i.dualMap q = decoded)) := by + apply LeftDecoder.affineLaw_success_lower B C center hC + obtain ⟨q, hq⟩ := exists_candidate_of_mem_nativeCoset i B C center decoded hdecoded + exact ⟨q, decide_eq_true hq⟩ + +theorem meeting_probability_lower {r : Nat} + (hC : Module.finrank F2 C ≤ r) + (right : FiniteDistribution (Module.Dual F2 H')) : + (1 / (2 : ℝ) ^ r) * right.probability + (fun decoded => decide (decoded - nativeCenter i center ∈ nativeQ i B C)) ≤ + ((LeftDecoder.affineLaw B C center).product right).probability + (fun pair => decide (i.dualMap pair.1 = pair.2)) := by + apply product_probability_lower + intro decoded hdecoded + exact native_point_probability_lower i B C center hC decoded (of_decide_eq_true hdecoded) + + +end +end PerfectCompleteness.AffineDecoderMeeting + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Algebra/AffineFunctionalDependence.lean b/lean/OAI/Computability/PerfectCompleteness/Algebra/AffineFunctionalDependence.lean new file mode 100644 index 0000000000000000000000000000000000000000..d134222ab56101f975c48a916c111ee8fd6816e1 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Algebra/AffineFunctionalDependence.lean @@ -0,0 +1,165 @@ +import Mathlib.Algebra.Field.ZMod +import Mathlib.FieldTheory.Finiteness +import Mathlib.LinearAlgebra.LinearIndependent.Defs +import Mathlib.Tactic.Positivity +import OAI.Computability.PerfectCompleteness.Algebra.UniformLinearImage +import OAI.Computability.PerfectCompleteness.Sampling.UniformLatent +import OAI.Computability.UniqueGames.Reduction.BinaryLinear + +namespace OAI + +section + +namespace PerfectCompleteness.AffineFunctionalDependence + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Integration.BinaryLinear (F2) + +noncomputable section + +private theorem probability_cover_le_sum {Ω I : Type*} [Fintype Ω] [Fintype I] + (μ : FiniteDistribution Ω) (event : Ω → Bool) (cover : I → Ω → Bool) + (hcover : ∀ x, event x = true → ∃ i, cover i x = true) : + μ.probability event ≤ ∑ i, μ.probability (cover i) := by + unfold FiniteDistribution.probability + rw [Finset.sum_comm] + apply Finset.sum_le_sum + intro x _ + by_cases hx : event x = true + · obtain ⟨i, hi⟩ := hcover x hx + have h := Finset.single_le_sum (s := Finset.univ) + (f := fun j => if cover j x then μ.weight x else 0) (a := i) + (fun j _ => by split <;> first | exact μ.nonnegative x | exact le_rfl) + (Finset.mem_univ i) + simpa only [hx, hi, ite_true] using h + · simp only [hx] + apply Finset.sum_nonneg + intro i _ + split + · exact μ.nonnegative x + · exact le_rfl + +variable {N V : Type*} [AddCommGroup N] [Module F2 N] + [AddCommGroup V] [Module F2 V] [Fintype N] [Fintype V] + +theorem affine_zero_probability_le (f : N →ₗ[F2] V) (b : V) : + (FiniteDistribution.uniform N).probability (fun x => decide (b + f x = 0)) ≤ + 1 / (Fintype.card (LinearMap.range f) : ℝ) := by + have hlaw := UniformLinearImage.uniform_pushforward_linearMap + f.rangeRestrict f.surjective_rangeRestrict + have hp := congrArg (fun μ : FiniteDistribution (LinearMap.range f) => + μ.probability (fun y => decide (b + (y : V) = 0))) hlaw + rw [FiniteDistribution.probability_pushforward] at hp + change (FiniteDistribution.uniform N).probability + (fun x => decide (b + f x = 0)) = _ at hp + rw [hp] + by_cases hzero : ∃ y : LinearMap.range f, b + (y : V) = 0 + · obtain ⟨z, hz⟩ := hzero + have hevent : (fun y : LinearMap.range f => decide (b + (y : V) = 0)) = + (fun y => decide (y = z)) := by + funext y + apply Bool.eq_iff_iff.mpr + simp only [decide_eq_true_eq] + constructor + · intro hy + apply Subtype.ext + exact add_left_cancel (hy.trans hz.symm) + · rintro rfl + exact hz + rw [hevent, UniformLatent.probability_uniform_singleton] + · have hz : ∀ y : LinearMap.range f, b + (y : V) ≠ 0 := by + simpa only [not_exists] using hzero + simp [FiniteDistribution.probability, hz] + +variable {m : Nat} + +def coefficientSum (c : Fin m → F2) : (Fin m → N) →ₗ[F2] N where + toFun x := ∑ i, c i • x i + map_add' x y := by simp only [Pi.add_apply, smul_add, Finset.sum_add_distrib] + map_smul' a x := by + simp only [Pi.smul_apply, Finset.smul_sum, smul_smul, mul_comm, RingHom.id_apply] + +@[simp] theorem coefficientSum_apply (c : Fin m → F2) (x : Fin m → N) : + coefficientSum c x = ∑ i, c i • x i := rfl + +theorem coefficientSum_surjective (c : Fin m → F2) (hc : c ≠ 0) : + Function.Surjective (coefficientSum (N := N) c) := by + have hcoord : ∃ i, c i ≠ 0 := by + by_contra h + push Not at h + exact hc (funext h) + obtain ⟨i, hi⟩ := hcoord + have hi1 : c i = 1 := + (UniqueGamesTheorem.Integration.BinaryLinear.scalar_cases (c i)).resolve_left hi + intro n + refine ⟨Function.update 0 i n, ?_⟩ + rw [coefficientSum_apply, Finset.sum_eq_single i] + · simp [hi1] + · intro j _ hji + simp [Function.update_of_ne hji] + · intro h + exact (h (Finset.mem_univ i)).elim + +theorem relation_probability_le (f : N →ₗ[F2] V) (offsets : Fin m → V) + (c : Fin m → F2) (hc : c ≠ 0) : + (FiniteDistribution.uniform (Fin m → N)).probability + (fun x => decide ((∑ i, c i • (offsets i + f (x i))) = 0)) ≤ + 1 / (Fintype.card (LinearMap.range f) : ℝ) := by + have hlaw := UniformLinearImage.uniform_pushforward_linearMap + (coefficientSum (N := N) c) (coefficientSum_surjective c hc) + have hp := congrArg (fun μ : FiniteDistribution N => + μ.probability (fun n => decide ((∑ i, c i • offsets i) + f n = 0))) hlaw + rw [FiniteDistribution.probability_pushforward] at hp + have hevent : + (fun x : Fin m → N => decide ((∑ i, c i • (offsets i + f (x i))) = 0)) = + (fun x => decide ((∑ i, c i • offsets i) + f (coefficientSum c x) = 0)) := by + funext x + simp only [coefficientSum_apply, smul_add, Finset.sum_add_distrib, + map_sum, map_smul] + rw [hevent, hp] + exact affine_zero_probability_le f (∑ i, c i • offsets i) + +theorem dependence_probability_le (f : N →ₗ[F2] V) (offsets : Fin m → V) : + (FiniteDistribution.uniform (Fin m → N)).probability + (fun x => decide (¬ LinearIndependent F2 (fun i => offsets i + f (x i)))) ≤ + (2 : ℝ) ^ m / (2 : ℝ) ^ Module.finrank F2 (LinearMap.range f) := by + let μ := FiniteDistribution.uniform (Fin m → N) + let event := fun x : Fin m → N => + decide (¬ LinearIndependent F2 (fun i => offsets i + f (x i))) + let cover := fun (c : Fin m → F2) (x : Fin m → N) => + decide (c ≠ 0 ∧ (∑ i, c i • (offsets i + f (x i))) = 0) + have hcover : ∀ x, event x = true → ∃ c, cover c x = true := by + intro x hx + have hdep : ¬ LinearIndependent F2 (fun i => offsets i + f (x i)) := + of_decide_eq_true hx + obtain ⟨c, hc, i, hi⟩ := Fintype.not_linearIndependent_iff.mp hdep + have hc0 : c ≠ 0 := by + intro hz + exact hi (congrFun hz i) + refine ⟨c, ?_⟩ + exact decide_eq_true_eq.mpr ⟨hc0, hc⟩ + have hbound (c : Fin m → F2) : + μ.probability (cover c) ≤ 1 / (Fintype.card (LinearMap.range f) : ℝ) := by + by_cases hc : c = 0 + · subst c + simp [cover, FiniteDistribution.probability] + · simpa [μ, cover, hc] using relation_probability_le f offsets c hc + calc + μ.probability event ≤ ∑ c, μ.probability (cover c) := + probability_cover_le_sum μ event cover hcover + _ ≤ ∑ _c : Fin m → F2, 1 / (Fintype.card (LinearMap.range f) : ℝ) := + Finset.sum_le_sum (fun c _ => hbound c) + _ = (2 : ℝ) ^ m / (2 : ℝ) ^ Module.finrank F2 (LinearMap.range f) := by + simp only [Finset.sum_const, Finset.card_univ, nsmul_eq_mul, + Fintype.card_fun, Fintype.card_fin, + Module.card_eq_pow_finrank (K := F2) (V := LinearMap.range f), + show Fintype.card F2 = 2 by decide, Nat.cast_pow, Nat.cast_ofNat, + mul_one_div] + +end +end PerfectCompleteness.AffineFunctionalDependence + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Algebra/AffineLinearHeavyWitness.lean b/lean/OAI/Computability/PerfectCompleteness/Algebra/AffineLinearHeavyWitness.lean new file mode 100644 index 0000000000000000000000000000000000000000..835e8c3f57e77f7aad4ad38d77f0986f4bc1d010 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Algebra/AffineLinearHeavyWitness.lean @@ -0,0 +1,116 @@ +import OAI.Computability.PerfectCompleteness.Machines.BinaryDualCoordinates + +namespace OAI + +section + +namespace PerfectCompleteness.AffineLinearHeavyWitness + +open scoped BigOperators +open QuarterBalance (F2) +open BinaryDualCoordinates +open UniqueGamesTheorem.Foundations.Games + +noncomputable section + +variable {U V K I J : Type*} + [AddCommGroup U] [Module F2 U] [Fintype U] + [AddCommGroup V] [Module F2 V] + [AddCommGroup K] [Module F2 K] + [Fintype I] [DecidableEq I] [Fintype J] [DecidableEq J] + +def conditionalMatch (μ : FiniteDistribution U) (R : U →ₗ[F2] V) (target : V) + (G : U → K) (T : U →ₗ[F2] K) (offset : K) : ℝ := by + classical + exact μ.expectation (fun x => if R x = target then + (if G x = offset + T x then 1 else 0) else 0) / + μ.expectation (fun x => if R x = target then 1 else 0) + +omit [DecidableEq I] [DecidableEq J] in +theorem conditionalEquality_coordinates (μ : FiniteDistribution U) + (b : Module.Basis I F2 V) (c : Module.Basis J F2 K) + (R : U →ₗ[F2] V) (target : V) (G : U → K) + (T : U →ₗ[F2] K) (offset : K) : + OutputCharacters.conditionalEquality μ (equations b R) (coordinates b target) + (fun x => coordinates c (G x)) (fun x => coordinates c (offset + T x)) = + conditionalMatch μ R target G T offset := by + classical + simp only [OutputCharacters.conditionalEquality, OutputCharacters.sliceCorrelation, + SmallBiasSlice.sliceNumerator, SmallBiasSlice.sliceMass, conditionalMatch, + equations_eq_iff, (coordinates_injective c).eq_iff] + +def badMasks (c : Module.Basis J F2 K) (bad : Finset (Module.Dual F2 K)) : + Finset (J → Bool) := + bad.map (frequencyEquiv c).symm.toEmbedding + +omit [DecidableEq J] in +@[simp] theorem mem_badMasks (c : Module.Basis J F2 K) + (bad : Finset (Module.Dual F2 K)) (s : J → Bool) : + s ∈ badMasks c bad ↔ frequency c s ∈ bad := by + classical + constructor + · rintro h + obtain ⟨f, hf, heq⟩ := Finset.mem_map.mp h + have heq' : frequency c s = f := by + change (frequencyEquiv c) s = f + rw [← heq] + exact (frequencyEquiv c).apply_symm_apply f + simpa only [heq'] using hf + · intro h + apply Finset.mem_map.mpr + refine ⟨frequency c s, h, ?_⟩ + exact (frequencyEquiv c).symm_apply_apply s + +omit [DecidableEq J] in +@[simp] theorem card_badMasks (c : Module.Basis J F2 K) + (bad : Finset (Module.Dual F2 K)) : + (badMasks c bad).card = bad.card := Finset.card_map _ + +theorem exists_heavy_in_dual_coset [Fintype (Module.Dual F2 U)] + [Fintype (Module.Dual F2 K)] + (μ : FiniteDistribution U) + (b : Module.Basis I F2 V) (c : Module.Basis J F2 K) + (R : U →ₗ[F2] V) (hR : Function.Surjective R) (target : V) + (G : U → K) (T : U →ₗ[F2] K) (offset : K) + (bad : Finset (Module.Dual F2 K)) (rho h0 biasBound : ℝ) + (hrho : 0 < rho) (hh0 : 0 < h0) + (hsize : h0 ≤ 1 / (Fintype.card (I → Bool) : ℝ)) + (hb : 0 ≤ biasBound) (hbsmall : biasBound ≤ h0 / 2) + (hbias : ∀ f : Module.Dual F2 U, f ≠ 0 → + |μ.expectation (character f)| ≤ biasBound) + (hbad : (bad.card : ℝ) / (Fintype.card (Module.Dual F2 K) : ℝ) < rho / 8) + (hmatch : rho ≤ conditionalMatch μ R target G T offset) : + ∃ σ : Module.Dual F2 K, σ ∉ bad ∧ + ∃ ψ ∈ LinearMap.range R.dualMap, + σ.comp T + ψ ∈ SmallBias.heavySet μ character + (fun x => character σ (G x)) (rho * h0 / 4) := by + classical + have hcard : Fintype.card (J → Bool) = Fintype.card (Module.Dual F2 K) := + Fintype.card_congr (frequencyEquiv c) + have hbad' : ((badMasks c bad).card : ℝ) / + (Fintype.card (J → Bool) : ℝ) < rho / 8 := by + simpa only [card_badMasks, hcard] using hbad + have hmatch' : rho ≤ OutputCharacters.conditionalEquality μ (equations b R) + (coordinates b target) (fun x => coordinates c (G x)) + (fun x => coordinates c (offset + T x)) := by + rwa [conditionalEquality_coordinates] + obtain ⟨s, hs, mask, hmask⟩ := + OutputCharacters.equality_implies_affine_heavy_witness μ + character character_zero character_add (equationRows b R) (equations b R) + (character_equationRows b R) (equationRows_independent b R hR) + (coordinates b target) (fun x => coordinates c (G x)) + (fun x => coordinates c (offset + T x)) + (fun s => (frequency c s).comp T) (fun s => character (frequency c s) offset) + (fun s => abs_character _ _) (character_affine_target c T offset) + (badMasks c bad) rho h0 biasBound hrho hh0 hsize hb hbsmall hbias hbad' hmatch' + refine ⟨frequency c s, (mem_badMasks c bad s).not.mp hs, + SmallBiasSlice.rowCombination (equationRows b R) mask, + rowCombination_mem_dualRange b R mask, ?_⟩ + simpa only [← character_frequency] using hmask + +end +end PerfectCompleteness.AffineLinearHeavyWitness + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Algebra/BilinearGramCompressionLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Algebra/BilinearGramCompressionLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..c8a17c18a3254efa86f83364901f8284d1bbbe77 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Algebra/BilinearGramCompressionLemmas.lean @@ -0,0 +1,840 @@ +import Lean.Elab.Tactic.Omega +import Mathlib.Algebra.Field.ZMod +import Mathlib.Algebra.Module.Projective +import Mathlib.FieldTheory.Finiteness +import Mathlib.LinearAlgebra.Basis.VectorSpace +import Mathlib.LinearAlgebra.Contraction +import Mathlib.LinearAlgebra.Dual.Defs +import Mathlib.LinearAlgebra.Dual.Lemmas +import Mathlib.LinearAlgebra.FiniteDimensional.Basic +import Mathlib.LinearAlgebra.FreeModule.Finite.Matrix +import Mathlib.LinearAlgebra.Matrix.Rank +import Mathlib.LinearAlgebra.Quotient.Basic +import Mathlib.LinearAlgebra.TensorProduct.Basic +import OAI.Computability.UniqueGames.Analysis.MatrixRestrictions +import OAI.Computability.UniqueGames.Reduction.BinaryLinear + +namespace OAI + +section + +namespace PerfectCompleteness.BilinearGramCompression + +open scoped BigOperators + +noncomputable section + +variable {K H R I J : Type*} [Field K] [AddCommGroup H] [Module K H] + [Fintype R] [Fintype I] [Fintype J] + +def combinations (rows : R → H) (T : Matrix I R K) : I → H := + fun i => ∑ r, T i r • rows r + +def crossGram (F : H →ₗ[K] Module.Dual K H) (left : I → H) (right : J → H) : + Matrix I J K := + fun i j => F (left i) (right j) + +def gram (F : H →ₗ[K] Module.Dual K H) (rows : R → H) : Matrix R R K := + crossGram F rows rows + +omit [Fintype I] [Fintype J] in +theorem crossGram_combinations (F : H →ₗ[K] Module.Dual K H) (rows : R → H) + (T : Matrix I R K) (S : Matrix J R K) : + crossGram F (combinations rows T) (combinations rows S) = + T * gram F rows * S.transpose := by + classical + ext i j + simp only [crossGram, combinations, gram, map_sum, map_smul, + LinearMap.sum_apply, LinearMap.smul_apply, smul_eq_mul, + Matrix.mul_apply, Matrix.transpose_apply, Finset.sum_mul, Finset.mul_sum] + apply Finset.sum_congr rfl + intro s _ + apply Finset.sum_congr rfl + intro r _ + ac_rfl + +omit [Fintype I] in +theorem gram_combinations (F : H →ₗ[K] Module.Dual K H) (rows : R → H) + (T : Matrix I R K) : + gram F (combinations rows T) = T * gram F rows * T.transpose := + crossGram_combinations F rows T T + +omit [Fintype I] in +theorem cross_rank_le (F : H →ₗ[K] Module.Dual K H) (rows : R → H) + (T : Matrix I R K) (S : Matrix J R K) : + (crossGram F (combinations rows T) (combinations rows S)).rank ≤ + (gram F rows).rank := by + rw [crossGram_combinations] + exact (Matrix.rank_mul_le_left (T * gram F rows) S.transpose).trans + (Matrix.rank_mul_le_right T (gram F rows)) + +theorem gram_rank_le (F : H →ₗ[K] Module.Dual K H) (rows : R → H) + (T : Matrix I R K) : + (gram F (combinations rows T)).rank ≤ (gram F rows).rank := + cross_rank_le F rows T T + +omit [Fintype I] in +theorem cross_rank_le_one (F : H →ₗ[K] Module.Dual K H) (rows : R → H) + (T : Matrix I R K) (S : Matrix J R K) (tested : (gram F rows).rank ≤ 1) : + (crossGram F (combinations rows T) (combinations rows S)).rank ≤ 1 := + (cross_rank_le F rows T S).trans tested + +end +end PerfectCompleteness.BilinearGramCompression + +end + +section + +namespace PerfectCompleteness.BilinearRestrictionRank + +noncomputable section + +open Module + +variable {𝕜 H V U : Type*} [Field 𝕜] + [AddCommGroup H] [Module 𝕜 H] + [AddCommGroup V] [Module 𝕜 V] + [AddCommGroup U] [Module 𝕜 U] + +def restrictForm (F : H →ₗ[𝕜] Module.Dual 𝕜 H) (N : Submodule 𝕜 H) : + N →ₗ[𝕜] Module.Dual 𝕜 N := + N.dualRestrict.comp (F.domRestrict N) + +@[simp] +theorem restrictForm_apply (F : H →ₗ[𝕜] Module.Dual 𝕜 H) + (N : Submodule 𝕜 H) (x y : N) : + restrictForm F N x y = F (x : H) (y : H) := rfl + +theorem ker_domRestrict_finrank_le [FiniteDimensional 𝕜 H] + (f : H →ₗ[𝕜] V) (N : Submodule 𝕜 H) : + finrank 𝕜 (LinearMap.ker (f.domRestrict N)) ≤ finrank 𝕜 (LinearMap.ker f) := by + let inclusion : LinearMap.ker (f.domRestrict N) →ₗ[𝕜] LinearMap.ker f := + { toFun := fun x => ⟨x.val.val, x.property⟩ + map_add' := by intros; rfl + map_smul' := by intros; rfl } + apply LinearMap.finrank_le_finrank_of_injective (f := inclusion) + intro x y h + apply Subtype.ext + apply Subtype.ext + exact congrArg (fun z : LinearMap.ker f => (z : H)) h + +theorem rank_domRestrict_add_codim [FiniteDimensional 𝕜 H] + (f : H →ₗ[𝕜] V) (N : Submodule 𝕜 H) : + finrank 𝕜 (LinearMap.range f) ≤ + finrank 𝕜 (LinearMap.range (f.domRestrict N)) + finrank 𝕜 (H ⧸ N) := by + have hwhole := f.finrank_range_add_finrank_ker + have hrestricted := (f.domRestrict N).finrank_range_add_finrank_ker + have hquotient := N.finrank_quotient_add_finrank + have hkernel := ker_domRestrict_finrank_le f N + omega + +theorem rank_le_rank_comp_add_ker [FiniteDimensional 𝕜 V] + (g : H →ₗ[𝕜] V) (f : V →ₗ[𝕜] U) : + finrank 𝕜 (LinearMap.range g) ≤ + finrank 𝕜 (LinearMap.range (f.comp g)) + finrank 𝕜 (LinearMap.ker f) := by + have hrange : LinearMap.range (f.domRestrict (LinearMap.range g)) = + LinearMap.range (f.comp g) := by + rw [LinearMap.range_domRestrict, LinearMap.range_comp] + have hrank := (f.domRestrict (LinearMap.range g)).finrank_range_add_finrank_ker + rw [hrange] at hrank + have hkernel := ker_domRestrict_finrank_le f (LinearMap.range g) + omega + +theorem dualRestrict_ker_finrank [FiniteDimensional 𝕜 H] (N : Submodule 𝕜 H) : + finrank 𝕜 (LinearMap.ker N.dualRestrict) = finrank 𝕜 (H ⧸ N) := by + rw [N.dualRestrict_ker_eq_dualAnnihilator] + exact (Subspace.quotEquivAnnihilator N).finrank_eq.symm + +theorem rank_restrict_add_codim [FiniteDimensional 𝕜 H] + (F : H →ₗ[𝕜] Module.Dual 𝕜 H) (N : Submodule 𝕜 H) : + finrank 𝕜 (LinearMap.range F) ≤ + finrank 𝕜 (LinearMap.range (restrictForm F N)) + 2 * finrank 𝕜 (H ⧸ N) := by + have hdomain := rank_domRestrict_add_codim F N + have hcodomain := rank_le_rank_comp_add_ker (F.domRestrict N) N.dualRestrict + rw [dualRestrict_ker_finrank] at hcodomain + change finrank 𝕜 (LinearMap.range (F.domRestrict N)) ≤ + finrank 𝕜 (LinearMap.range (restrictForm F N)) + finrank 𝕜 (H ⧸ N) at hcodomain + omega + +theorem rank_sub_two_codim_le [FiniteDimensional 𝕜 H] + (F : H →ₗ[𝕜] Module.Dual 𝕜 H) (N : Submodule 𝕜 H) : + finrank 𝕜 (LinearMap.range F) - 2 * finrank 𝕜 (H ⧸ N) ≤ + finrank 𝕜 (LinearMap.range (restrictForm F N)) := by + have h := rank_restrict_add_codim F N + omega + +end +end PerfectCompleteness.BilinearRestrictionRank + +end + +section + +namespace PerfectCompleteness.MatrixRowQuotient + +noncomputable section + +variable {𝕜 H K : Type*} [Field 𝕜] + [AddCommGroup H] [Module 𝕜 H] [AddCommGroup K] [Module 𝕜 K] + +theorem exists_section (W : Submodule 𝕜 H) : + ∃ s : (H ⧸ W) →ₗ[𝕜] H, W.mkQ.comp s = LinearMap.id := + W.mkQ.exists_rightInverse_of_surjective W.range_mkQ + +def projectMatrix (W : Submodule 𝕜 H) (X : Module.Dual 𝕜 H →ₗ[𝕜] K) : + Module.Dual 𝕜 (H ⧸ W) →ₗ[𝕜] K := + X.comp W.mkQ.dualMap + +def liftMatrix (W : Submodule 𝕜 H) (s : (H ⧸ W) →ₗ[𝕜] H) + (X : Module.Dual 𝕜 (H ⧸ W) →ₗ[𝕜] K) : Module.Dual 𝕜 H →ₗ[𝕜] K := + X.comp s.dualMap + +@[simp] theorem projectMatrix_apply (W : Submodule 𝕜 H) + (X : Module.Dual 𝕜 H →ₗ[𝕜] K) (q : Module.Dual 𝕜 (H ⧸ W)) : + projectMatrix W X q = X (q.comp W.mkQ) := rfl + +@[simp] theorem liftMatrix_apply (W : Submodule 𝕜 H) (s : (H ⧸ W) →ₗ[𝕜] H) + (X : Module.Dual 𝕜 (H ⧸ W) →ₗ[𝕜] K) (q : Module.Dual 𝕜 H) : + liftMatrix W s X q = X (q.comp s) := rfl + +theorem project_lift (W : Submodule 𝕜 H) (s : (H ⧸ W) →ₗ[𝕜] H) + (hs : W.mkQ.comp s = LinearMap.id) + (X : Module.Dual 𝕜 (H ⧸ W) →ₗ[𝕜] K) : + projectMatrix W (liftMatrix W s X) = X := by + apply LinearMap.ext + intro q + change X (s.dualMap (W.mkQ.dualMap q)) = X q + apply congrArg X + apply LinearMap.ext + intro h + change q (W.mkQ (s h)) = q h + have hh := LinearMap.congr_fun hs h + change W.mkQ (s h) = h at hh + rw [hh] + +theorem projectMatrix_surjective (W : Submodule 𝕜 H) : + Function.Surjective (projectMatrix (K := K) W) := by + obtain ⟨s, hs⟩ := exists_section W + intro X + exact ⟨liftMatrix W s X, project_lift W s hs X⟩ + +theorem liftMatrix_injective (W : Submodule 𝕜 H) (s : (H ⧸ W) →ₗ[𝕜] H) + (hs : W.mkQ.comp s = LinearMap.id) : + Function.Injective (liftMatrix (K := K) W s) := by + intro X Y h + have h' := congrArg (projectMatrix W) h + simpa only [project_lift W s hs] using h' + +def residualVector (W : Submodule 𝕜 H) (s : (H ⧸ W) →ₗ[𝕜] H) + (hs : W.mkQ.comp s = LinearMap.id) : H →ₗ[𝕜] W := + (LinearMap.id - s.comp W.mkQ).codRestrict W (by + intro h + apply (Submodule.Quotient.mk_eq_zero W).mp + change W.mkQ (h - s (W.mkQ h)) = 0 + rw [map_sub] + have hh := LinearMap.congr_fun hs (W.mkQ h) + change W.mkQ (s (W.mkQ h)) = W.mkQ h at hh + rw [hh, sub_self]) + +@[simp] theorem residualVector_val (W : Submodule 𝕜 H) + (s : (H ⧸ W) →ₗ[𝕜] H) (hs : W.mkQ.comp s = LinearMap.id) (h : H) : + (residualVector W s hs h : H) = h - s (W.mkQ h) := rfl + +theorem subtype_comp_residualVector (W : Submodule 𝕜 H) + (s : (H ⧸ W) →ₗ[𝕜] H) (hs : W.mkQ.comp s = LinearMap.id) : + W.subtype.comp (residualVector W s hs) = LinearMap.id - s.comp W.mkQ := rfl + +theorem residual_factorization (W : Submodule 𝕜 H) + (s : (H ⧸ W) →ₗ[𝕜] H) (hs : W.mkQ.comp s = LinearMap.id) + (X : Module.Dual 𝕜 H →ₗ[𝕜] K) : + X - liftMatrix W s (projectMatrix W X) = + (X.comp (residualVector W s hs).dualMap).comp W.subtype.dualMap := by + apply LinearMap.ext + intro q + change X q - X (W.mkQ.dualMap (s.dualMap q)) = + X ((residualVector W s hs).dualMap (W.subtype.dualMap q)) + rw [← map_sub] + apply congrArg X + apply LinearMap.ext + intro h + change q h - q (s (W.mkQ h)) = q (h - s (W.mkQ h)) + rw [map_sub] + +theorem project_rankOne (W : Submodule 𝕜 H) (X : Module.Dual 𝕜 H →ₗ[𝕜] K) + (a : K) (h : H) : + projectMatrix W (X + (Module.Dual.eval 𝕜 H h).smulRight a) = + projectMatrix W X + (Module.Dual.eval 𝕜 (H ⧸ W) (W.mkQ h)).smulRight a := by + apply LinearMap.ext + intro q + rfl + +theorem lift_rankOne (W : Submodule 𝕜 H) (s : (H ⧸ W) →ₗ[𝕜] H) + (X : Module.Dual 𝕜 (H ⧸ W) →ₗ[𝕜] K) (a : K) (h : H ⧸ W) : + liftMatrix W s (X + (Module.Dual.eval 𝕜 (H ⧸ W) h).smulRight a) = + liftMatrix W s X + (Module.Dual.eval 𝕜 H (s h)).smulRight a := by + apply LinearMap.ext + intro q + rfl + +theorem project_rankOne_of_mem (W : Submodule 𝕜 H) + (X : Module.Dual 𝕜 H →ₗ[𝕜] K) (a : K) (h : H) (hh : h ∈ W) : + projectMatrix W (X + (Module.Dual.eval 𝕜 H h).smulRight a) = projectMatrix W X := by + apply LinearMap.ext + intro q + change X (W.mkQ.dualMap q) + q (W.mkQ h) • a = X (W.mkQ.dualMap q) + have hzero : W.mkQ h = 0 := (Submodule.Quotient.mk_eq_zero W).mpr hh + rw [hzero, map_zero, zero_smul, add_zero] + +end +end PerfectCompleteness.MatrixRowQuotient + +end + +section + +namespace PerfectCompleteness.MatrixSlice + +noncomputable section + +open scoped BigOperators +open UniqueGamesTheorem.Integration.BinaryLinear (F2) +open UniqueGamesTheorem.Fourier.MatrixRestrictions + +variable {E C : Type*} [AddCommGroup E] [Module F2 E] + [AddCommGroup C] [Module F2 C] + +def Slice (W : Submodule F2 E) (C' : Submodule F2 C) (T : E →ₗ[F2] C) := + {X : E →ₗ[F2] C // + X.domRestrict W = T.domRestrict W ∧ C'.mkQ.comp X = C'.mkQ.comp T} + +theorem domRestrict_translate (W : Submodule F2 E) (C' : Submodule F2 C) + (T : E →ₗ[F2] C) (A : Parameter W C') : + (translate W C' T A).domRestrict W = T.domRestrict W := by + apply LinearMap.ext + intro w + change T w + embed W C' A w = T w + have hw : embed W C' A w = 0 := embed_vanishes W C' A w.property + rw [hw, add_zero] + +theorem exists_translate_iff (W : Submodule F2 E) (C' : Submodule F2 C) + (T X : E →ₗ[F2] C) : + (∃ A : Parameter W C', translate W C' T A = X) ↔ + X.domRestrict W = T.domRestrict W ∧ C'.mkQ.comp X = C'.mkQ.comp T := by + constructor + · rintro ⟨A, rfl⟩ + exact ⟨domRestrict_translate W C' T A, quotient_translate W C' T A⟩ + · rintro ⟨hW, hC⟩ + have hker : W ≤ LinearMap.ker (X - T) := by + intro w hw + change X w - T w = 0 + exact sub_eq_zero.mpr (LinearMap.congr_fun hW ⟨w, hw⟩) + have hrange : LinearMap.range (X - T) ≤ C' := by + rintro y ⟨x, rfl⟩ + apply (Submodule.Quotient.mk_eq_zero C').mp + change C'.mkQ (X x - T x) = 0 + rw [map_sub] + exact sub_eq_zero.mpr (LinearMap.congr_fun hC x) + obtain ⟨A, hA⟩ := (exists_embed_iff W C' (X - T)).mpr ⟨hker, hrange⟩ + refine ⟨A, ?_⟩ + change T + embed W C' A = X + rw [hA, add_comm T, sub_add_cancel] + +def parameterEquivSlice (W : Submodule F2 E) (C' : Submodule F2 C) + (T : E →ₗ[F2] C) : Parameter W C' ≃ Slice W C' T := + Equiv.ofBijective + (fun A => ⟨translate W C' T A, + domRestrict_translate W C' T A, quotient_translate W C' T A⟩) + ⟨by + intro A B h + exact translate_injective W C' T (congrArg Subtype.val h), by + intro X + obtain ⟨A, hA⟩ := (exists_translate_iff W C' T X.val).mpr X.property + exact ⟨A, Subtype.ext hA⟩⟩ + +@[simp] theorem parameterEquivSlice_val (W : Submodule F2 E) + (C' : Submodule F2 C) (T : E →ₗ[F2] C) (A : Parameter W C') : + (parameterEquivSlice W C' T A).val = translate W C' T A := rfl + +instance sliceFintype [Finite E] [Finite C] (W : Submodule F2 E) + (C' : Submodule F2 C) (T : E →ₗ[F2] C) : Fintype (Slice W C' T) := + Fintype.ofEquiv (Parameter W C') (parameterEquivSlice W C' T) + +instance sliceNonempty (W : Submodule F2 E) (C' : Submodule F2 C) + (T : E →ₗ[F2] C) : Nonempty (Slice W C' T) := ⟨⟨T, rfl, rfl⟩⟩ + +theorem expect_translate_eq_slice [Finite E] [Finite C] + (W : Submodule F2 E) (C' : Submodule F2 C) (T : E →ₗ[F2] C) + (f : (E →ₗ[F2] C) → ℝ) : + (𝔼 A : Parameter W C', f (translate W C' T A)) = + 𝔼 X : Slice W C' T, f X.val := + Fintype.expect_equiv (parameterEquivSlice W C' T) _ _ (fun _ => rfl) + +theorem expect_restrict_eq_slice [Finite E] [Finite C] + (W : Submodule F2 E) (C' : Submodule F2 C) (T : E →ₗ[F2] C) + (f : (E →ₗ[F2] C) → ℝ) : + (𝔼 A : Parameter W C', restrict f W C' T A) = + 𝔼 X : Slice W C' T, f X.val := + expect_translate_eq_slice W C' T f + +theorem domRestrict_eq_iff_basis [FiniteDimensional F2 E] + (W : Submodule F2 E) (X T : E →ₗ[F2] C) : + X.domRestrict W = T.domRestrict W ↔ + ∀ i : Fin (Module.finrank F2 W), + X (Module.finBasis F2 W i) = T (Module.finBasis F2 W i) := by + constructor + · intro h i + exact LinearMap.congr_fun h (Module.finBasis F2 W i) + · intro h + exact (Module.finBasis F2 W).ext h + +def rowMap [FiniteDimensional F2 C] (C' : Submodule F2 C) : + C →ₗ[F2] (Fin (Module.finrank F2 (C ⧸ C')) → F2) := + (Module.finBasis F2 (C ⧸ C')).equivFun.toLinearMap.comp C'.mkQ + +theorem rowMap_comp_eq_iff [FiniteDimensional F2 C] + (C' : Submodule F2 C) (X T : E →ₗ[F2] C) : + (rowMap C').comp X = (rowMap C').comp T ↔ + C'.mkQ.comp X = C'.mkQ.comp T := by + constructor + · intro h + apply LinearMap.ext + intro x + apply (Module.finBasis F2 (C ⧸ C')).equivFun.injective + exact LinearMap.congr_fun h x + · intro h + apply LinearMap.ext + intro x + exact congrArg (Module.finBasis F2 (C ⧸ C')).equivFun + (LinearMap.congr_fun h x) + +theorem rowMap_surjective [FiniteDimensional F2 C] (C' : Submodule F2 C) : + Function.Surjective (rowMap C') := + (Module.finBasis F2 (C ⧸ C')).equivFun.surjective.comp C'.mkQ_surjective + +theorem exists_translate_iff_equations [FiniteDimensional F2 E] + [FiniteDimensional F2 C] (W : Submodule F2 E) (C' : Submodule F2 C) + (T X : E →ₗ[F2] C) : + (∃ A : Parameter W C', translate W C' T A = X) ↔ + (∀ i : Fin (Module.finrank F2 W), + X (Module.finBasis F2 W i) = T (Module.finBasis F2 W i)) ∧ + (rowMap C').comp X = (rowMap C').comp T := by + rw [exists_translate_iff, domRestrict_eq_iff_basis, rowMap_comp_eq_iff] + +theorem equation_count_eq_order (W : Submodule F2 E) (C' : Submodule F2 C) : + Fintype.card (Fin (Module.finrank F2 W)) + + Fintype.card (Fin (Module.finrank F2 (C ⧸ C'))) = order W C' := by + simp only [Fintype.card_fin, order] + +theorem column_count_le_order (W : Submodule F2 E) (C' : Submodule F2 C) : + Module.finrank F2 W ≤ order W C' := Nat.le_add_right _ _ + +theorem row_count_le_order (W : Submodule F2 E) (C' : Submodule F2 C) : + Module.finrank F2 (C ⧸ C') ≤ order W C' := Nat.le_add_left _ _ + +end +end PerfectCompleteness.MatrixSlice + +end + +section + +namespace PerfectCompleteness.TensorCosetEvaluation + +noncomputable section + +open scoped TensorProduct + +section GeneralField + +variable {𝕜 U H : Type*} [Field 𝕜] + [AddCommGroup U] [Module 𝕜 U] [AddCommGroup H] [Module 𝕜 H] + +def pureFrequency (a : Module.Dual 𝕜 U) (q : Module.Dual 𝕜 H) : + Module.Dual 𝕜 (U ⊗[𝕜] H) := + TensorProduct.lift (a.smulRight q) + +@[simp] theorem pureFrequency_tmul (a : Module.Dual 𝕜 U) + (q : Module.Dual 𝕜 H) (u : U) (h : H) : + pureFrequency a q (u ⊗ₜ[𝕜] h) = a u * q h := by + simp only [pureFrequency, TensorProduct.lift.tmul, LinearMap.smulRight_apply, + LinearMap.smul_apply, smul_eq_mul] + +def scalarRestriction (Φ : Module.Dual 𝕜 (U ⊗[𝕜] H)) (u : U) : + Module.Dual 𝕜 H := + Φ.comp (TensorProduct.mk 𝕜 U H u) + +@[simp] theorem scalarRestriction_apply (Φ : Module.Dual 𝕜 (U ⊗[𝕜] H)) + (u : U) (h : H) : scalarRestriction Φ u h = Φ (u ⊗ₜ[𝕜] h) := rfl + +@[simp] theorem scalarRestriction_zero (u : U) : + scalarRestriction (0 : Module.Dual 𝕜 (U ⊗[𝕜] H)) u = 0 := by + apply LinearMap.ext + intro h + rfl + +@[simp] theorem scalarRestriction_add (Φ Ψ : Module.Dual 𝕜 (U ⊗[𝕜] H)) + (u : U) : scalarRestriction (Φ + Ψ) u = scalarRestriction Φ u + scalarRestriction Ψ u := by + apply LinearMap.ext + intro h + rfl + +@[simp] theorem scalarRestriction_sub (Φ Ψ : Module.Dual 𝕜 (U ⊗[𝕜] H)) + (u : U) : scalarRestriction (Φ - Ψ) u = scalarRestriction Φ u - scalarRestriction Ψ u := by + apply LinearMap.ext + intro h + rfl + +@[simp] theorem scalarRestriction_smul (c : 𝕜) (Φ : Module.Dual 𝕜 (U ⊗[𝕜] H)) + (u : U) : scalarRestriction (c • Φ) u = c • scalarRestriction Φ u := by + apply LinearMap.ext + intro h + rfl + +@[simp] theorem scalarRestriction_pure (a : Module.Dual 𝕜 U) + (q : Module.Dual 𝕜 H) (u : U) : + scalarRestriction (pureFrequency a q) u = a u • q := by + apply LinearMap.ext + intro h + simp only [scalarRestriction_apply, pureFrequency_tmul, + LinearMap.smul_apply, smul_eq_mul] + +def equationSpace (Q : Submodule 𝕜 (Module.Dual 𝕜 H)) : + Submodule 𝕜 (Module.Dual 𝕜 (U ⊗[𝕜] H)) := + Submodule.span 𝕜 + (Set.range (fun p : Module.Dual 𝕜 U × Q => pureFrequency p.1 p.2)) + +theorem scalarRestriction_mem (Q : Submodule 𝕜 (Module.Dual 𝕜 H)) + (Ψ : Module.Dual 𝕜 (U ⊗[𝕜] H)) (hΨ : Ψ ∈ equationSpace (U := U) Q) (u : U) : + scalarRestriction Ψ u ∈ Q := by + unfold equationSpace at hΨ + refine Submodule.span_induction + (p := fun Ψ _ => scalarRestriction Ψ u ∈ Q) ?_ ?_ ?_ ?_ hΨ + · rintro Ψ ⟨⟨a, q⟩, rfl⟩ + rw [scalarRestriction_pure] + exact Q.smul_mem (a u) q.property + · rw [scalarRestriction_zero] + exact Q.zero_mem + · intro Ψ₁ Ψ₂ _ _ h₁ h₂ + rw [scalarRestriction_add] + exact Q.add_mem h₁ h₂ + · intro c Ψ _ h + rw [scalarRestriction_smul] + exact Q.smul_mem c h + +theorem scalarRestriction_sub_base_mem (Q : Submodule 𝕜 (Module.Dual 𝕜 H)) + (Φ : Module.Dual 𝕜 (U ⊗[𝕜] H)) (a : Module.Dual 𝕜 U) + (z : Module.Dual 𝕜 H) (u : U) (hu : a u = 1) + (hΦ : Φ - pureFrequency a z ∈ equationSpace (U := U) Q) : + scalarRestriction Φ u - z ∈ Q := by + have h := scalarRestriction_mem Q _ hΦ u + simpa only [scalarRestriction_sub, scalarRestriction_pure, hu, one_smul] using h + +theorem scalarRestriction_mem_coset_of_eq (Q : Submodule 𝕜 (Module.Dual 𝕜 H)) + (Φ Ψ : Module.Dual 𝕜 (U ⊗[𝕜] H)) (a : Module.Dual 𝕜 U) + (z : Module.Dual 𝕜 H) (u : U) (hu : a u = 1) + (hΨ : Ψ ∈ equationSpace (U := U) Q) (hΦ : Φ = pureFrequency a z + Ψ) : + scalarRestriction Φ u - z ∈ Q := by + apply scalarRestriction_sub_base_mem Q Φ a z u hu + rw [hΦ, add_sub_cancel_left] + exact hΨ + +theorem scalarRestriction_mem_of_vanishes + (Q : Submodule 𝕜 (Module.Dual 𝕜 H)) [FiniteDimensional 𝕜 Q] + (Ψ : Module.Dual 𝕜 (U ⊗[𝕜] H)) + (hΨ : ∀ u h, h ∈ Q.dualCoannihilator → Ψ (u ⊗ₜ[𝕜] h) = 0) (u : U) : + scalarRestriction Ψ u ∈ Q := by + rw [← Subspace.dualCoannihilator_dualAnnihilator_eq (W := Q)] + apply (Submodule.mem_dualAnnihilator _).mpr + intro h hh + exact hΨ u h hh + +theorem scalarRestriction_factor_mem + {L : Type*} [AddCommGroup L] [Module 𝕜 L] + (Q : Submodule 𝕜 (Module.Dual 𝕜 H)) [FiniteDimensional 𝕜 Q] + (R : (U ⊗[𝕜] H) →ₗ[𝕜] L) + (hR : ∀ u h, h ∈ Q.dualCoannihilator → R (u ⊗ₜ[𝕜] h) = 0) + (ψ : Module.Dual 𝕜 L) (u : U) : scalarRestriction (ψ.comp R) u ∈ Q := by + refine scalarRestriction_mem_of_vanishes Q (ψ.comp R) ?_ u + intro v h hh + change ψ (R (v ⊗ₜ[𝕜] h)) = 0 + rw [hR v h hh, map_zero] + +theorem scalarRestriction_mem_coset_of_factor + {L : Type*} [AddCommGroup L] [Module 𝕜 L] + (Q : Submodule 𝕜 (Module.Dual 𝕜 H)) [FiniteDimensional 𝕜 Q] + (R : (U ⊗[𝕜] H) →ₗ[𝕜] L) + (hR : ∀ u h, h ∈ Q.dualCoannihilator → R (u ⊗ₜ[𝕜] h) = 0) + (ψ : Module.Dual 𝕜 L) (Φ : Module.Dual 𝕜 (U ⊗[𝕜] H)) + (a : Module.Dual 𝕜 U) (z : Module.Dual 𝕜 H) (u : U) (hu : a u = 1) + (hΦ : Φ = pureFrequency a z + ψ.comp R) : scalarRestriction Φ u - z ∈ Q := by + rw [hΦ, scalarRestriction_add, scalarRestriction_pure, hu, one_smul, + add_sub_cancel_left] + exact scalarRestriction_factor_mem Q R hR ψ u + +end GeneralField + +section Binary + +open UniqueGamesTheorem.Integration.BinaryLinear (F2) + +variable {K H : Type*} [AddCommGroup K] [Module F2 K] + [AddCommGroup H] [Module F2 H] + +theorem exists_value_one (a : Module.Dual F2 K) (ha : a ≠ 0) : + ∃ w : K, a w = 1 := by + by_contra hnone + apply ha + apply LinearMap.ext + intro w + change a w = 0 + rcases UniqueGamesTheorem.Integration.BinaryLinear.scalar_cases (a w) with hw | hw + · exact hw + · exact (hnone ⟨w, hw⟩).elim + +theorem exists_candidate_restriction (W : Submodule F2 K) + (Q : Submodule F2 (Module.Dual F2 H)) (σ : Module.Dual F2 K) + (hσ : σ.comp W.subtype ≠ 0) (z : Module.Dual F2 H) + (Φ : Module.Dual F2 (W ⊗[F2] H)) + (hΦ : Φ - pureFrequency (σ.comp W.subtype) z ∈ equationSpace (U := W) Q) : + ∃ w : W, σ w = 1 ∧ scalarRestriction Φ w - z ∈ Q := by + obtain ⟨w, hw⟩ := exists_value_one (σ.comp W.subtype) hσ + exact ⟨w, hw, scalarRestriction_sub_base_mem Q Φ (σ.comp W.subtype) z w hw hΦ⟩ + +theorem annihilator_iff_restriction_zero (W : Submodule F2 K) (σ : Module.Dual F2 K) : + σ ∈ W.dualAnnihilator ↔ σ.comp W.subtype = 0 := Iff.rfl + +theorem card_annihilatingCharacters [FiniteDimensional F2 K] (W : Submodule F2 K) : + Nat.card W.dualAnnihilator = + 2 ^ (Module.finrank F2 K - Module.finrank F2 W) := by + have hdim : Module.finrank F2 W.dualAnnihilator = + Module.finrank F2 K - Module.finrank F2 W := + Nat.eq_sub_of_add_eq' (Subspace.finrank_add_finrank_dualAnnihilator_eq W) + rw [Module.natCard_eq_pow_finrank (K := F2), hdim] + rw [show Nat.card F2 = 2 from Nat.card_zmod 2] + +end Binary +end +end PerfectCompleteness.TensorCosetEvaluation + +end + +section + +namespace PerfectCompleteness.TensorRestriction + +noncomputable section + +open scoped TensorProduct +open UniqueGamesTheorem.Integration.BinaryLinear (F2) + +variable {W H : Type*} [AddCommGroup W] [Module F2 W] + [AddCommGroup H] [Module F2 H] [FiniteDimensional F2 H] + +def tensorEquivHom : (W ⊗[F2] H) ≃ₗ[F2] (Module.Dual F2 H →ₗ[F2] W) := + (TensorProduct.comm F2 W H).trans + ((TensorProduct.congr (Module.evalEquiv F2 H) (LinearEquiv.refl F2 W)).trans + (dualTensorHomEquiv F2 (Module.Dual F2 H) W)) + +@[simp] theorem tensorEquivHom_tmul (w : W) (h : H) (q : Module.Dual F2 H) : + tensorEquivHom (w ⊗ₜ[F2] h) q = q h • w := rfl + +def restrictionMap (Q : Submodule F2 (Module.Dual F2 H)) : + (W ⊗[F2] H) →ₗ[F2] (Q →ₗ[F2] W) := + (LinearMap.domRestrict' Q).comp tensorEquivHom.toLinearMap + +@[simp] theorem restrictionMap_apply (Q : Submodule F2 (Module.Dual F2 H)) + (X : W ⊗[F2] H) (q : Q) : + restrictionMap Q X q = tensorEquivHom X q.val := rfl + +@[simp] theorem restrictionMap_tmul (Q : Submodule F2 (Module.Dual F2 H)) + (w : W) (h : H) (q : Q) : + restrictionMap Q (w ⊗ₜ[F2] h) q = q.val h • w := rfl + +theorem restrictionMap_surjective (Q : Submodule F2 (Module.Dual F2 H)) : + Function.Surjective (restrictionMap (W := W) Q) := by + intro f + obtain ⟨g, hg⟩ := f.exists_extend + refine ⟨tensorEquivHom.symm g, ?_⟩ + change (tensorEquivHom (tensorEquivHom.symm g)).comp Q.subtype = f + rw [LinearEquiv.apply_symm_apply] + exact hg + +theorem fiber_nonempty (Q : Submodule F2 (Module.Dual F2 H)) (t : Q →ₗ[F2] W) : + Nonempty {X : W ⊗[F2] H // restrictionMap Q X = t} := by + obtain ⟨X, hX⟩ := restrictionMap_surjective Q t + exact ⟨⟨X, hX⟩⟩ + +theorem dualMap_injective (Q : Submodule F2 (Module.Dual F2 H)) : + Function.Injective (restrictionMap (W := W) Q).dualMap := + LinearMap.dualMap_injective_of_surjective (restrictionMap_surjective Q) + +theorem dualMap_ne_zero (Q : Submodule F2 (Module.Dual F2 H)) + (f : Module.Dual F2 (Q →ₗ[F2] W)) (hf : f ≠ 0) : + (restrictionMap Q).dualMap f ≠ 0 := by + intro h + apply hf + apply dualMap_injective Q + simpa only [map_zero] using h + +def dualImage (Q : Submodule F2 (Module.Dual F2 H)) : + Submodule F2 (Module.Dual F2 (W ⊗[F2] H)) := + LinearMap.range (restrictionMap (W := W) Q).dualMap + +theorem restrictionMap_tmul_eq_zero (Q : Submodule F2 (Module.Dual F2 H)) + (w : W) (h : H) (hh : h ∈ Q.dualCoannihilator) : + restrictionMap Q (w ⊗ₜ[F2] h) = 0 := by + apply LinearMap.ext + intro q + rw [restrictionMap_tmul] + have hq : q.val h = 0 := (Submodule.mem_dualCoannihilator h).mp hh q.val q.property + rw [hq, zero_smul, LinearMap.zero_apply] + +theorem dualImage_vanishes (Q : Submodule F2 (Module.Dual F2 H)) + (Φ : Module.Dual F2 (W ⊗[F2] H)) (hΦ : Φ ∈ dualImage (W := W) Q) + (w : W) (h : H) (hh : h ∈ Q.dualCoannihilator) : + Φ (w ⊗ₜ[F2] h) = 0 := by + obtain ⟨f, rfl⟩ := hΦ + change f (restrictionMap Q (w ⊗ₜ[F2] h)) = 0 + rw [restrictionMap_tmul_eq_zero Q w h hh, map_zero] + +variable [FiniteDimensional F2 W] + +theorem finrank_range (Q : Submodule F2 (Module.Dual F2 H)) : + Module.finrank F2 (LinearMap.range (restrictionMap (W := W) Q)) = + Module.finrank F2 W * Module.finrank F2 Q := by + let : Module.Free F2 Q := Module.Free.of_divisionRing F2 Q + rw [LinearMap.range_eq_top.mpr (restrictionMap_surjective Q), finrank_top, + Module.finrank_linearMap F2 F2 Q W, Nat.mul_comm] + +theorem finrank_dualImage (Q : Submodule F2 (Module.Dual F2 H)) : + Module.finrank F2 (dualImage (W := W) Q) = + Module.finrank F2 W * Module.finrank F2 Q := by + let : Module.Free F2 Q := Module.Free.of_divisionRing F2 Q + rw [dualImage, LinearMap.finrank_range_of_inj (dualMap_injective Q), + Subspace.dual_finrank_eq, Module.finrank_linearMap F2 F2 Q W, Nat.mul_comm] + +theorem finrank_range_le (Q : Submodule F2 (Module.Dual F2 H)) {ℓ r : Nat} + (hW : Module.finrank F2 W ≤ ℓ) (hQ : Module.finrank F2 Q ≤ r) : + Module.finrank F2 (LinearMap.range (restrictionMap (W := W) Q)) ≤ ℓ * r := by + rw [finrank_range] + exact Nat.mul_le_mul hW hQ + +end +end PerfectCompleteness.TensorRestriction + +end + +section + +namespace PerfectCompleteness.TensorEquationSpace + +noncomputable section + +open scoped BigOperators TensorProduct +open TensorCosetEvaluation + +section GeneralField + +variable {𝕜 U H : Type*} [Field 𝕜] + [AddCommGroup U] [Module 𝕜 U] [AddCommGroup H] [Module 𝕜 H] + +theorem basis_expansion {I : Type*} [Fintype I] (b : Module.Basis I 𝕜 U) + (Φ : Module.Dual 𝕜 (U ⊗[𝕜] H)) : + Φ = ∑ i, pureFrequency (b.coord i) (scalarRestriction Φ (b i)) := by + apply TensorProduct.ext' + intro u h + simp only [LinearMap.sum_apply, pureFrequency_tmul, scalarRestriction_apply, + Module.Basis.coord_apply] + have hb := congrArg (fun v : U => Φ (v ⊗ₜ[𝕜] h)) (b.sum_repr u) + simpa only [TensorProduct.sum_tmul, ← TensorProduct.smul_tmul', + map_sum, map_smul, smul_eq_mul] using hb.symm + +variable [FiniteDimensional 𝕜 U] + +theorem mem_equationSpace_of_scalarRestriction_mem + (Q : Submodule 𝕜 (Module.Dual 𝕜 H)) + (Φ : Module.Dual 𝕜 (U ⊗[𝕜] H)) + (hΦ : ∀ u, scalarRestriction Φ u ∈ Q) : + Φ ∈ equationSpace (U := U) Q := by + rw [basis_expansion (Module.finBasis 𝕜 U) Φ] + apply Submodule.sum_mem + intro i _ + apply Submodule.subset_span + exact ⟨⟨(Module.finBasis 𝕜 U).coord i, + ⟨scalarRestriction Φ ((Module.finBasis 𝕜 U) i), hΦ _⟩⟩, rfl⟩ + +theorem mem_equationSpace_iff (Q : Submodule 𝕜 (Module.Dual 𝕜 H)) + (Φ : Module.Dual 𝕜 (U ⊗[𝕜] H)) : + Φ ∈ equationSpace (U := U) Q ↔ ∀ u, scalarRestriction Φ u ∈ Q := + ⟨fun hΦ u => scalarRestriction_mem Q Φ hΦ u, + mem_equationSpace_of_scalarRestriction_mem Q Φ⟩ + +end GeneralField + +section Binary + +open UniqueGamesTheorem.Integration.BinaryLinear (F2) + +variable {W H : Type*} [AddCommGroup W] [Module F2 W] + [AddCommGroup H] [Module F2 H] [FiniteDimensional F2 H] + +def pureFactor (Q : Submodule F2 (Module.Dual F2 H)) + (a : Module.Dual F2 W) (q : Q) : Module.Dual F2 (Q →ₗ[F2] W) where + toFun T := a (T q) + map_add' T S := by simp only [LinearMap.add_apply, map_add] + map_smul' c T := by simp only [LinearMap.smul_apply, map_smul, RingHom.id_apply] + +omit [FiniteDimensional F2 H] in +@[simp] theorem pureFactor_apply (Q : Submodule F2 (Module.Dual F2 H)) + (a : Module.Dual F2 W) (q : Q) (T : Q →ₗ[F2] W) : + pureFactor Q a q T = a (T q) := rfl + +theorem dualMap_pureFactor (Q : Submodule F2 (Module.Dual F2 H)) + (a : Module.Dual F2 W) (q : Q) : + (TensorRestriction.restrictionMap Q).dualMap (pureFactor Q a q) = + pureFrequency a q.val := by + apply TensorProduct.ext' + intro w h + change a (TensorRestriction.restrictionMap Q (w ⊗ₜ[F2] h) q) = + pureFrequency a q.val (w ⊗ₜ[F2] h) + simp only [TensorRestriction.restrictionMap_tmul, pureFrequency_tmul, + map_smul, smul_eq_mul, mul_comm] + +theorem pureFrequency_mem_dualImage (Q : Submodule F2 (Module.Dual F2 H)) + (a : Module.Dual F2 W) (q : Q) : + pureFrequency a q.val ∈ TensorRestriction.dualImage (W := W) Q := + ⟨pureFactor Q a q, dualMap_pureFactor Q a q⟩ + +theorem equationSpace_le_dualImage (Q : Submodule F2 (Module.Dual F2 H)) : + equationSpace (U := W) Q ≤ TensorRestriction.dualImage (W := W) Q := by + apply Submodule.span_le.mpr + rintro Φ ⟨⟨a, q⟩, rfl⟩ + exact pureFrequency_mem_dualImage Q a q + +variable [FiniteDimensional F2 W] + +theorem dualImage_le_equationSpace (Q : Submodule F2 (Module.Dual F2 H)) : + TensorRestriction.dualImage (W := W) Q ≤ equationSpace (U := W) Q := by + intro Φ hΦ + apply mem_equationSpace_of_scalarRestriction_mem Q Φ + intro w + exact scalarRestriction_mem_of_vanishes Q Φ + (TensorRestriction.dualImage_vanishes Q Φ hΦ) w + +theorem dualImage_eq_equationSpace (Q : Submodule F2 (Module.Dual F2 H)) : + TensorRestriction.dualImage (W := W) Q = equationSpace (U := W) Q := + le_antisymm (dualImage_le_equationSpace Q) (equationSpace_le_dualImage Q) + +theorem finrank_equationSpace (Q : Submodule F2 (Module.Dual F2 H)) : + Module.finrank F2 (equationSpace (U := W) Q) = + Module.finrank F2 W * Module.finrank F2 Q := by + rw [← dualImage_eq_equationSpace, TensorRestriction.finrank_dualImage] + +end Binary +end +end PerfectCompleteness.TensorEquationSpace + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Algebra/BilinearWitnessLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Algebra/BilinearWitnessLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..7f3abe583f31885f70c2f9e7dcfb9cbafa5a3abd --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Algebra/BilinearWitnessLemmas.lean @@ -0,0 +1,237 @@ +import Mathlib.Algebra.Field.ZMod +import Mathlib.LinearAlgebra.Pi +import OAI.Computability.PerfectCompleteness.Decoding.CollisionAveragingLemmas +import OAI.Computability.PerfectCompleteness.Sampling.DensityVariation + +namespace OAI + + +namespace PerfectCompleteness.BilinearWitness + +open scoped BigOperators + +noncomputable section + +variable {𝕜 I H : Type*} [Field 𝕜] [Fintype I] [DecidableEq I] + [AddCommGroup H] [Module 𝕜 H] + {V : I → Type*} [∀ i, AddCommGroup (V i)] [∀ i, Module 𝕜 (V i)] + +def assemble (f : (i : I) → V i →ₗ[𝕜] H) (x : (i : I) → V i) : H := + ∑ i, f i (x i) + +omit [DecidableEq I] in +theorem exists_child_pair (f : (i : I) → V i →ₗ[𝕜] H) + (spans : Function.Surjective (assemble f)) (B : H →ₗ[𝕜] H →ₗ[𝕜] 𝕜) + (nonzero : B ≠ 0) : ∃ i j, ∃ (x : V i) (y : V j), B (f i x) (f j y) ≠ 0 := by + classical + by_contra h + push Not at h + apply nonzero + ext u v + obtain ⟨x, rfl⟩ := spans u + obtain ⟨y, rfl⟩ := spans v + simp only [assemble, map_sum, LinearMap.sum_apply] + simp only [h, Finset.sum_const_zero, LinearMap.zero_apply] + +def Witness (f : (i : I) → V i →ₗ[𝕜] H) (B : H →ₗ[𝕜] H →ₗ[𝕜] 𝕜) := + { w : (Σ i : I, Σ j : I, V i × V j) // B (f w.1 w.2.2.1) (f w.2.1 w.2.2.2) ≠ 0 } + +def chooseWitness (f : (i : I) → V i →ₗ[𝕜] H) + (spans : Function.Surjective (assemble f)) (B : H →ₗ[𝕜] H →ₗ[𝕜] 𝕜) + (nonzero : B ≠ 0) : Witness f B := by + classical + apply Classical.choice + obtain ⟨i, j, x, y, h⟩ := exists_child_pair f spans B nonzero + exact ⟨⟨⟨i, j, x, y⟩, h⟩⟩ + +def selected (f : (i : I) → V i →ₗ[𝕜] H) + (spans : Function.Surjective (assemble f)) (B : H →ₗ[𝕜] H →ₗ[𝕜] 𝕜) : Finset I := by + classical + exact if h : B = 0 then ∅ else + { (chooseWitness f spans B h).val.1, (chooseWitness f spans B h).val.2.1 } + +theorem selected_card_le (f : (i : I) → V i →ₗ[𝕜] H) + (spans : Function.Surjective (assemble f)) (B : H →ₗ[𝕜] H →ₗ[𝕜] 𝕜) : + (selected f spans B).card ≤ 2 := by + classical + unfold selected + split + · simp + · exact (Finset.card_insert_le _ _).trans (by simp) + +theorem marked_of_restriction_zero (f : (i : I) → V i →ₗ[𝕜] H) + (spans : Function.Surjective (assemble f)) (B : H →ₗ[𝕜] H →ₗ[𝕜] 𝕜) + (nonzero : B ≠ 0) (mask : I → Bool) (U : Submodule 𝕜 H) + (unchanged : ∀ i, mask i = false → ∀ x, f i x ∈ U) + (vanishes : ∀ x ∈ U, ∀ y ∈ U, B x y = 0) : + ∃ i ∈ selected f spans B, mask i = true := by + classical + let w := chooseWitness f spans B nonzero + have hselect : selected f spans B = {w.val.1, w.val.2.1} := by + simp only [selected, dite_eq_right nonzero, w] + rw [hselect] + by_cases hi : mask w.val.1 = true + · exact ⟨w.val.1, by simp, hi⟩ + by_cases hj : mask w.val.2.1 = true + · exact ⟨w.val.2.1, by simp, hj⟩ + have hif : mask w.val.1 = false := Bool.eq_false_of_not_eq_true hi + have hjf : mask w.val.2.1 = false := Bool.eq_false_of_not_eq_true hj + exact False.elim (w.property (vanishes _ (unchanged _ hif _) _ (unchanged _ hjf _))) + +end +end PerfectCompleteness.BilinearWitness + + +namespace PerfectCompleteness.BilinearProjection + +open scoped BigOperators +open scoped Classical +open UniqueGamesTheorem.Foundations.Games +open PerfectCompleteness ProjectionPosterior AdaptiveProjection BilinearWitness + +noncomputable section + +variable {𝕜 I H : Type*} [Field 𝕜] [Fintype I] [DecidableEq I] + [AddCommGroup H] [Module 𝕜 H] + {V : I → Type*} [∀ i, AddCommGroup (V i)] [∀ i, Module 𝕜 (V i)] + {Ω : I → Type*} [∀ i, Fintype (Ω i)] + +theorem disagreement_probability (f : (i : I) → V i →ₗ[𝕜] H) + (spans : Function.Surjective (assemble f)) + (F₀ F₁ : ((i : I) → Ω i) → (H →ₗ[𝕜] H →ₗ[𝕜] 𝕜)) + (U : ((i : I) → Ω i) → (I → Bool) → Submodule 𝕜 H) + (unchanged : ∀ x mask i, mask i = false → ∀ v, f i v ∈ U x mask) + (P : (i : I) → FiniteDistribution (Ω i)) + (q : (i : I) → Ω i → ℝ) (nonnegative : ∀ i x, 0 ≤ q i x) + (mean : ∀ i, (P i).expectation (q i) = 1) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β < 1) + (L : ℝ) (hL : 0 ≤ L) (bound : ∀ i x, q i x ≤ L) : + (forward P q nonnegative mean β hβ hβ').probability + (fun z => decide (F₀ z.2 ≠ F₁ z.2 ∧ + ∀ v ∈ U z.2 z.1, ∀ w ∈ U z.2 z.1, F₀ z.2 v w = F₁ z.2 v w)) ≤ + 2 * (β * L / (1 - β)) := by + classical + let select := fun x => selected f spans (F₀ x - F₁ x) + have inclusion : ∀ z : (I → Bool) × ((i : I) → Ω i), + decide (F₀ z.2 ≠ F₁ z.2 ∧ + ∀ v ∈ U z.2 z.1, ∀ w ∈ U z.2 z.1, F₀ z.2 v w = F₁ z.2 v w) = true → + decide (∃ i ∈ select z.2, z.1 i = true) = true := by + intro z hz + have h := of_decide_eq_true hz + apply decide_eq_true + apply marked_of_restriction_zero f spans (F₀ z.2 - F₁ z.2) + (sub_ne_zero.mpr h.1) z.1 (U z.2 z.1) (unchanged z.2 z.1) + intro v hv w hw + simpa only [LinearMap.sub_apply, sub_eq_zero] using h.2 v hv w hw + exact ((forward P q nonnegative mean β hβ hβ').probability_mono inclusion).trans + (by simpa only [Nat.cast_ofNat] using + (adaptive_selection P q nonnegative mean β hβ hβ' L hL bound select 2 + (fun x => selected_card_le f spans (F₀ x - F₁ x)))) + +end +end PerfectCompleteness.BilinearProjection + + +namespace PerfectCompleteness.BilinearCollisionTransfer + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games +open PerfectCompleteness ProjectionPosterior BilinearWitness + +noncomputable section + +theorem probability_le_add_of_imp {X : Type*} [Fintype X] + (μ : FiniteDistribution X) (p q r : X → Bool) + (h : ∀ x, p x = true → q x = true ∨ r x = true) : + μ.probability p ≤ μ.probability q + μ.probability r := by + simp only [FiniteDistribution.probability, ← Finset.sum_add_distrib] + apply Finset.sum_le_sum + intro x _ + cases hp : p x <;> cases hq : q x <;> cases hr : r x <;> + simp only [Bool.false_eq_true, ite_false, ite_true, zero_add, add_zero] + all_goals first | exact μ.nonnegative x | linarith [μ.nonnegative x] | + exact False.elim (by simpa [hq, hr] using h x hp) + +variable {𝕜 I H : Type*} [Field 𝕜] [Fintype I] [DecidableEq I] + [AddCommGroup H] [Module 𝕜 H] + {V : I → Type*} [∀ i, AddCommGroup (V i)] [∀ i, Module 𝕜 (V i)] + {Ω : I → Type*} [∀ i, Fintype (Ω i)] + +abbrev Form := H →ₗ[𝕜] H →ₗ[𝕜] 𝕜 + +def fullCollision (a b : Option (Form (𝕜 := 𝕜) (H := H))) : Bool := + decide (∃ F, a = some F ∧ b = some F) + +def restrictedCollision (a b : Option (Form (𝕜 := 𝕜) (H := H))) + (U : Submodule 𝕜 H) : Bool := + decide (∃ F G, a = some F ∧ b = some G ∧ + ∀ v ∈ U, ∀ w ∈ U, F v w = G v w) + +theorem collision_split (a b : Option (Form (𝕜 := 𝕜) (H := H))) + (U : Submodule 𝕜 H) (h : restrictedCollision a b U = true) : + fullCollision a b = true ∨ + decide (a.getD 0 ≠ b.getD 0 ∧ + ∀ v ∈ U, ∀ w ∈ U, a.getD 0 v w = b.getD 0 v w) = true := by + obtain ⟨F, G, ha, hb, heq⟩ := of_decide_eq_true h + subst a b + by_cases hFG : F = G + · left + apply decide_eq_true + exact ⟨F, rfl, congrArg some hFG.symm⟩ + · right + simpa only [Option.getD_some, decide_eq_true_eq] using And.intro hFG heq + +theorem restricted_le_full_add (f : (i : I) → V i →ₗ[𝕜] H) + (spans : Function.Surjective (assemble f)) + (F₀ F₁ : ((i : I) → Ω i) → Option (Form (𝕜 := 𝕜) (H := H))) + (U : ((i : I) → Ω i) → (I → Bool) → Submodule 𝕜 H) + (unchanged : ∀ x mask i, mask i = false → ∀ v, f i v ∈ U x mask) + (P : (i : I) → FiniteDistribution (Ω i)) + (q : (i : I) → Ω i → ℝ) (nonnegative : ∀ i x, 0 ≤ q i x) + (mean : ∀ i, (P i).expectation (q i) = 1) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β < 1) + (L : ℝ) (hL : 0 ≤ L) (bound : ∀ i x, q i x ≤ L) : + (forward P q nonnegative mean β hβ hβ').probability + (fun z => restrictedCollision (F₀ z.2) (F₁ z.2) (U z.2 z.1)) ≤ + ((forward P q nonnegative mean β hβ hβ').pushforward Prod.snd).probability + (fun x => fullCollision (F₀ x) (F₁ x)) + 2 * (β * L / (1 - β)) := by + have hsplit := probability_le_add_of_imp (forward P q nonnegative mean β hβ hβ') + (fun z => restrictedCollision (F₀ z.2) (F₁ z.2) (U z.2 z.1)) + (fun z => fullCollision (F₀ z.2) (F₁ z.2)) + (fun z => decide ((F₀ z.2).getD 0 ≠ (F₁ z.2).getD 0 ∧ + ∀ v ∈ U z.2 z.1, ∀ w ∈ U z.2 z.1, + (F₀ z.2).getD 0 v w = (F₁ z.2).getD 0 v w)) + (fun z => collision_split (F₀ z.2) (F₁ z.2) (U z.2 z.1)) + have hbad := BilinearProjection.disagreement_probability f spans + (fun x => (F₀ x).getD 0) (fun x => (F₁ x).getD 0) U unchanged + P q nonnegative mean β hβ hβ' L hL bound + rw [FiniteDistribution.probability_pushforward] + exact hsplit.trans (add_le_add (le_refl _) hbad) + +theorem full_collision_transfer (f : (i : I) → V i →ₗ[𝕜] H) + (spans : Function.Surjective (assemble f)) + (F₀ F₁ : ((i : I) → Ω i) → Option (Form (𝕜 := 𝕜) (H := H))) + (U : ((i : I) → Ω i) → (I → Bool) → Submodule 𝕜 H) + (unchanged : ∀ x mask i, mask i = false → ∀ v, f i v ∈ U x mask) + (P : (i : I) → FiniteDistribution (Ω i)) + (q : (i : I) → Ω i → ℝ) (nonnegative : ∀ i x, 0 ≤ q i x) + (mean : ∀ i, (P i).expectation (q i) = 1) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β < 1) + (L : ℝ) (hL : 0 ≤ L) (bound : ∀ i x, q i x ≤ L) + (ν : FiniteDistribution ((i : I) → Ω i)) : + (forward P q nonnegative mean β hβ hβ').probability + (fun z => restrictedCollision (F₀ z.2) (F₁ z.2) (U z.2 z.1)) - + 2 * (β * L / (1 - β)) - + ((forward P q nonnegative mean β hβ hβ').pushforward Prod.snd).totalVariation ν ≤ + ν.probability (fun x => fullCollision (F₀ x) (F₁ x)) := by + have h := restricted_le_full_add f spans F₀ F₁ U unchanged + P q nonnegative mean β hβ hβ' L hL bound + have htv := FiniteDistribution.probability_le_add_totalVariation + ((forward P q nonnegative mean β hβ hβ').pushforward Prod.snd) ν + (fun x => fullCollision (F₀ x) (F₁ x)) + linarith + +end +end PerfectCompleteness.BilinearCollisionTransfer + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Algebra/BucketMatrixResampling.lean b/lean/OAI/Computability/PerfectCompleteness/Algebra/BucketMatrixResampling.lean new file mode 100644 index 0000000000000000000000000000000000000000..8821f547f791d6ba6f71d2c1ec8fc7cae230b626 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Algebra/BucketMatrixResampling.lean @@ -0,0 +1,111 @@ +import OAI.Computability.PerfectCompleteness.Sampling.BucketResamplingLaw +import OAI.Computability.PerfectCompleteness.Sampling.BucketUniformLemmas + +namespace OAI + + +namespace PerfectCompleteness.BucketMatrixResampling + +noncomputable section + +open scoped Classical +open UniqueGamesTheorem.Foundations.Games +open BucketSampler (F2 Direction Tape) + +variable {Ω : Type*} (V : Submodule F2 (Ω → F2)) + +abbrev Matrix (ℓ : Nat) := Module.Dual F2 V →ₗ[F2] (Fin ℓ → F2) + +def assembledMatrix (ℓ : Nat) (t : Tape ℓ V) : Matrix V ℓ := + EvaluationMatrix.ofRows V (BucketSampler.evaluate ℓ (id : V → V) t) + +theorem assembledMatrix_update (ℓ : Nat) (t : Tape ℓ V) + (a : Direction ℓ) (new : V) : + assembledMatrix V ℓ (Function.update t a new) = + EvaluationMatrix.shift V (assembledMatrix V ℓ t) a.val (new - t a) := by + unfold assembledMatrix + rw [BucketSampler.evaluate_update] + apply LinearMap.ext + intro q + funext i + change q (BucketSampler.evaluate ℓ (id : V → V) t i + a.val i • (new - t a)) = + q (BucketSampler.evaluate ℓ (id : V → V) t i) + q (new - t a) * a.val i + simp only [map_add, map_smul, smul_eq_mul, mul_comm] + +private theorem pushforward_id {A : Type*} [Fintype A] (μ : FiniteDistribution A) : + μ.pushforward (fun a => a) = μ := by + apply FiniteDistribution.eq_of_weight_eq + intro a + simp [FiniteDistribution.pushforward] + + +variable (ℓ : Nat) [Fintype V] [Fintype (Matrix V ℓ)] + +theorem matrix_difference_law (μ : FiniteDistribution (Tape ℓ V)) (a : Direction ℓ) : + (μ.product (FiniteDistribution.uniform V)).pushforward + (fun p => (assembledMatrix V ℓ p.1, p.2 - p.1 a)) = + (μ.pushforward (assembledMatrix V ℓ)).product (FiniteDistribution.uniform V) := by + rw [UniformDifference.observed_difference_law μ (fun t => t a) + (assembledMatrix V ℓ)] + have hp := FiniteDistribution.product_pushforward μ + (FiniteDistribution.uniform V) (assembledMatrix V ℓ) (id : V → V) + have hi : (FiniteDistribution.uniform V).pushforward (id : V → V) = + FiniteDistribution.uniform V := + pushforward_id (FiniteDistribution.uniform V) + rw [hi] at hp + simpa only [id_eq] using hp + +theorem resampled_matrix_pair_law (μ : FiniteDistribution (Tape ℓ V)) (a : Direction ℓ) : + (μ.product (FiniteDistribution.uniform V)).pushforward + (fun p => (assembledMatrix V ℓ p.1, + assembledMatrix V ℓ (Function.update p.1 a p.2))) = + ((μ.pushforward (assembledMatrix V ℓ)).product (FiniteDistribution.uniform V)).pushforward + (fun p => (p.1, EvaluationMatrix.shift V p.1 a.val p.2)) := by + have h := congrArg + (fun ν : FiniteDistribution (Matrix V ℓ × V) => ν.pushforward + (fun p => (p.1, EvaluationMatrix.shift V p.1 a.val p.2))) + (matrix_difference_law V ℓ μ a) + rw [FiniteDistribution.pushforward_comp] at h + simpa only [assembledMatrix_update] using h + +variable [FiniteDimensional F2 V] + +theorem uniform_assembledMatrix_law : + (BucketSampler.tapeLaw ℓ (FiniteDistribution.uniform V)).pushforward + (assembledMatrix V ℓ) = FiniteDistribution.uniform (Matrix V ℓ) := + BucketUniform.uniform_matrix_law V ℓ + +theorem uniform_matrix_difference_law (a : Direction ℓ) : + ((BucketSampler.tapeLaw ℓ (FiniteDistribution.uniform V)).product + (FiniteDistribution.uniform V)).pushforward + (fun p => (assembledMatrix V ℓ p.1, p.2 - p.1 a)) = + (FiniteDistribution.uniform (Matrix V ℓ)).product (FiniteDistribution.uniform V) := by + rw [matrix_difference_law, uniform_assembledMatrix_law] + +theorem uniform_resampled_matrix_pair_law (a : Direction ℓ) : + ((BucketSampler.tapeLaw ℓ (FiniteDistribution.uniform V)).product + (FiniteDistribution.uniform V)).pushforward + (fun p => (assembledMatrix V ℓ p.1, + assembledMatrix V ℓ (Function.update p.1 a p.2))) = + ((FiniteDistribution.uniform (Matrix V ℓ)).product + (FiniteDistribution.uniform V)).pushforward + (fun p => (p.1, EvaluationMatrix.shift V p.1 a.val p.2)) := by + rw [resampled_matrix_pair_law, uniform_assembledMatrix_law] + +theorem uniform_resampled_event_probability (a : Direction ℓ) + (event : Matrix V ℓ × Matrix V ℓ → Bool) : + ((BucketSampler.tapeLaw ℓ (FiniteDistribution.uniform V)).product + (FiniteDistribution.uniform V)).probability + (fun p => event (assembledMatrix V ℓ p.1, + assembledMatrix V ℓ (Function.update p.1 a p.2))) = + ((FiniteDistribution.uniform (Matrix V ℓ)).product + (FiniteDistribution.uniform V)).probability + (fun p => event (p.1, EvaluationMatrix.shift V p.1 a.val p.2)) := by + have h := congrArg (fun ν => FiniteDistribution.probability ν event) + (uniform_resampled_matrix_pair_law V ℓ a) + simpa only [FiniteDistribution.probability_pushforward] using h + +end +end PerfectCompleteness.BucketMatrixResampling + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Algebra/CanonicalMatrixTable.lean b/lean/OAI/Computability/PerfectCompleteness/Algebra/CanonicalMatrixTable.lean new file mode 100644 index 0000000000000000000000000000000000000000..a2077a1817fe19536e26b193d2d8c159e18819f9 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Algebra/CanonicalMatrixTable.lean @@ -0,0 +1,110 @@ +import OAI.Computability.PerfectCompleteness.Algebra.EvaluationMatrix +import OAI.Computability.PerfectCompleteness.Foundations.LinearEvaluationLemmas +import OAI.Computability.PerfectCompleteness.Foundations.QuotientTableAgreementLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.CanonicalMatrixTable + +noncomputable section + +open scoped Classical +open ClauseSupport MixedSupport CanonicalKeys +open DirectionQuotient (F2) + +variable {n : Nat} {K Z : Type*} [AddCommGroup K] [Module F2 K] + (slots : Fin n → Slot) (H : Submodule F2 (Assignment slots → F2)) + (other : Assignment slots → Z) (σ : KeyStrategy.Strategy n) + +abbrev Matrix := Module.Dual F2 H →ₗ[F2] K + +def query (X : Matrix (K := K) slots H) : Assignment slots → K × Z := + EvaluationMatrix.joint H other X + +def response (X : Matrix (K := K) slots H) : K × Z := + KeyStrategy.response σ .left slots (query slots H other X) + +def partialTable (useful : Matrix (K := K) slots H → Prop) (X : Matrix (K := K) slots H) : Option (K × Z) := + if useful X then some (response slots H other σ X) else none + +theorem response_realized (X : Matrix (K := K) slots H) : + ∃ x : Assignment slots, + EvaluationMatrix.evaluate H X x = (response slots H other σ X).1 ∧ + other x = (response slots H other σ X).2 := by + obtain ⟨x, hx⟩ := KeyStrategy.response_mem_range σ .left slots (query slots H other X) + exact ⟨x, congrArg Prod.fst hx, congrArg Prod.snd hx⟩ + +def rightQuery (a : K) (X : Matrix (K := K) slots H) : Assignment slots → DirectionQuotient.Space a × Z := + DirectionQuotient.projectWithSide a ∘ query slots H other X + +theorem rightQuery_shift (a : K) (X : Matrix (K := K) slots H) (h : H) : + rightQuery slots H other a (EvaluationMatrix.shift H X a h) = + rightQuery slots H other a X := by + funext x + apply Prod.ext + · change DirectionQuotient.proj a + (EvaluationMatrix.evaluate H X x + h.val x • a) = + DirectionQuotient.proj a (EvaluationMatrix.evaluate H X x) + rw [map_add, map_smul] + have ha : DirectionQuotient.proj a a = 0 := + (DirectionQuotient.proj_eq_zero_iff a a).mpr (Or.inr rfl) + simp [ha] + · rfl + +theorem rightResponse_shift (a : K) (X : Matrix (K := K) slots H) (h : H) : + KeyStrategy.response σ .right slots + (rightQuery slots H other a (EvaluationMatrix.shift H X a h)) = + KeyStrategy.response σ .right slots (rightQuery slots H other a X) := by + rw [rightQuery_shift] + +def Accepts (a : K) (X : Matrix (K := K) slots H) : Prop := + CanonicalEdges.coarsen slots (query slots H other X) (DirectionQuotient.projectWithSide a) + (KeyStrategy.label σ .left slots (query slots H other X)) = + KeyStrategy.label σ .right slots (rightQuery slots H other a X) + +theorem accepts_iff (a : K) (X : Matrix (K := K) slots H) : + Accepts slots H other σ a X ↔ + DirectionQuotient.projectWithSide a (response slots H other σ X) = + KeyStrategy.response σ .right slots (rightQuery slots H other a X) := + CanonicalEdges.coarsen_eq_iff slots (query slots H other X) + (DirectionQuotient.projectWithSide a) _ _ + +theorem accepted_response_in_fiber (a : K) (X : Matrix (K := K) slots H) (h : H) + (hacc : Accepts slots H other σ a (EvaluationMatrix.shift H X a h)) : + DirectionQuotient.projectWithSide a + (response slots H other σ (EvaluationMatrix.shift H X a h)) = + KeyStrategy.response σ .right slots (rightQuery slots H other a X) := by + have h := (accepts_iff slots H other σ a (EvaluationMatrix.shift H X a h)).mp hacc + rwa [rightResponse_shift] at h + +theorem card_accepted_responses_le_two [Finite K] [Finite Z] + (a : K) (ha : a ≠ 0) (X : Matrix (K := K) slots H) : + Nat.card {y : K × Z // ∃ h : H, + Accepts slots H other σ a (EvaluationMatrix.shift H X a h) ∧ + response slots H other σ (EvaluationMatrix.shift H X a h) = y} ≤ 2 := by + let z := KeyStrategy.response σ .right slots (rightQuery slots H other a X) + let intoFiber : + {y : K × Z // ∃ h : H, + Accepts slots H other σ a (EvaluationMatrix.shift H X a h) ∧ + response slots H other σ (EvaluationMatrix.shift H X a h) = y} → + {y : K × Z // DirectionQuotient.projectWithSide a y = z} := fun y => + ⟨y.val, by + obtain ⟨h, hacc, hy⟩ := y.property + rw [← hy] + exact accepted_response_in_fiber slots H other σ a X h hacc⟩ + calc + _ ≤ Nat.card {y : K × Z // DirectionQuotient.projectWithSide a y = z} := + Nat.card_le_card_of_injective intoFiber (by + intro y y' he + exact Subtype.ext (congrArg + (fun v : {y : K × Z // DirectionQuotient.projectWithSide a y = z} => v.val) he)) + _ = 2 := DirectionQuotient.card_projectWithSide_fiber a ha z + +end +end PerfectCompleteness.CanonicalMatrixTable + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Algebra/ChildBilinearCollisionTransfer.lean b/lean/OAI/Computability/PerfectCompleteness/Algebra/ChildBilinearCollisionTransfer.lean new file mode 100644 index 0000000000000000000000000000000000000000..a19672e2371b18d6574cabb4e30d0a094e5d4d23 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Algebra/ChildBilinearCollisionTransfer.lean @@ -0,0 +1,96 @@ +import OAI.Computability.PerfectCompleteness.Algebra.BilinearWitnessLemmas +import OAI.Computability.PerfectCompleteness.Construction.ChildUnmarkedSpace +import OAI.Computability.PerfectCompleteness.Decoding.ChildBlockProjection +import OAI.Computability.PerfectCompleteness.Sampling.RationalFiniteLawLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.ChildBilinearCollisionTransfer + +noncomputable section + +open scoped Classical +open RecursiveSpaces TreeSourceSpaces PointwiseSpaces +open UniqueGamesTheorem.Foundations.Games + +variable {branch : Nat → Nat} {n t : Nat} + +abbrev ParentForm (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) := + H slots →ₗ[F2] H slots →ₗ[F2] F2 + +abbrev Raw (calls : Nat) (rows : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) := + (i : Fin (branch n)) → ChildBlockCardinality.Raw calls rows (childSlots slots i) + +variable {Z : Fin (branch n) → Type*} [∀ i, Fintype (Z i)] + +theorem marked_restricted_le_uniform_full + (calls : Nat) (rows : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (projected : (i : Fin (branch n)) → Z i → Slots branch n → Fin t → MixedSupport.Slot) + (p : ∀ i z s k, MixedSupport.Projection + (childSlots slots i s k) (projected i z s k)) + (choiceLaw : (i : Fin (branch n)) → FiniteDistribution (Z i)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β < 1) + (F₀ F₁ : Raw calls rows slots → Option (ParentForm slots)) : + (SparseReplacement.markedLaw + (fun i => FiniteDistribution.uniform + (ChildBlockCardinality.Raw calls rows (childSlots slots i))) + (ChildBlockProjection.replacementLaws calls rows (childSlots slots) + projected p choiceLaw) β hβ hβ'.le).probability + (fun z => BilinearCollisionTransfer.restrictedCollision + (F₀ z.2) (F₁ z.2) (ChildUnmarkedSpace.space slots z.1)) ≤ + (FiniteProduct.law (fun i => FiniteDistribution.uniform + (ChildBlockCardinality.Raw calls rows (childSlots slots i)))).probability + (fun x => BilinearCollisionTransfer.fullCollision (F₀ x) (F₁ x)) + + 2 * (β * (ChildBlockCardinality.bound branch n t calls rows : ℝ) / (1 - β)) + + Real.sqrt ((1 + β ^ 2 * + ((ChildBlockCardinality.bound branch n t calls rows : ℝ) - 1)) ^ + branch n - 1) / 2 := by + let P : (i : Fin (branch n)) → FiniteDistribution + (ChildBlockCardinality.Raw calls rows (childSlots slots i)) := + fun i => FiniteDistribution.uniform + (ChildBlockCardinality.Raw calls rows (childSlots slots i)) + let Q := ChildBlockProjection.replacementLaws calls rows (childSlots slots) + projected p choiceLaw + let L : ℝ := ChildBlockCardinality.bound branch n t calls rows + have hL : 0 ≤ L := Nat.cast_nonneg _ + have hcard : ∀ i : Fin (branch n), + (Fintype.card (ChildBlockCardinality.Raw calls rows (childSlots slots i)) : ℝ) ≤ L := by + intro i + dsimp only [L] + exact_mod_cast ChildBlockCardinality.fintype_card_le calls rows (childSlots slots i) + have hdom : ∀ i x, (Q i).weight x ≤ L * (P i).weight x := + CoordinateReplacement.uniform_domination Q L hcard + have hsupport := CoordinateReplacement.support_of_domination P Q L hdom + have hbound : ∀ i x, CoordinateReplacement.ratio P Q i x ≤ L := + fun i x => (CoordinateReplacement.ratio_bounds_of_domination P Q L hL hdom i x).2 + have htransfer := BilinearCollisionTransfer.full_collision_transfer + (ChildUnmarkedSpace.childMap slots) (ChildUnmarkedSpace.assemble_surjective slots) + F₀ F₁ (fun _ mask => ChildUnmarkedSpace.space slots mask) + (fun _ mask i hi v => ChildUnmarkedSpace.childMap_mem_space slots mask i hi v) + P (CoordinateReplacement.ratio P Q) (CoordinateReplacement.ratio_nonnegative P Q) + (CoordinateReplacement.ratio_mean_one_of_support P Q hsupport) + β hβ hβ' L hL hbound (FiniteProduct.law P) + rw [SparseReplacement.forward_eq P Q hsupport β hβ hβ', + SparseReplacement.markedLaw_marginal] at htransfer + have hvariation := SparseReplacement.observed_variation P Q β hβ hβ'.le L hL hdom + (id : Raw calls rows slots → Raw calls rows slots) + simp only [FiniteDistribution.pushforward_id, Fintype.card_fin] at hvariation + change (SparseReplacement.markedLaw P Q β hβ hβ'.le).probability + (fun z => BilinearCollisionTransfer.restrictedCollision + (F₀ z.2) (F₁ z.2) (ChildUnmarkedSpace.space slots z.1)) ≤ + (FiniteProduct.law P).probability + (fun x => BilinearCollisionTransfer.fullCollision (F₀ x) (F₁ x)) + + 2 * (β * L / (1 - β)) + + Real.sqrt ((1 + β ^ 2 * (L - 1)) ^ branch n - 1) / 2 + linarith + +end +end PerfectCompleteness.ChildBilinearCollisionTransfer + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Algebra/DecoderRankSplit.lean b/lean/OAI/Computability/PerfectCompleteness/Algebra/DecoderRankSplit.lean new file mode 100644 index 0000000000000000000000000000000000000000..491ecd25e9c01d60495d556525b0749af0298605 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Algebra/DecoderRankSplit.lean @@ -0,0 +1,99 @@ +import OAI.Computability.PerfectCompleteness.Algebra.FixedRankContradiction +import OAI.Computability.PerfectCompleteness.Decoding.FixedDecoderCleanRateLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.DecoderRankSplit + +noncomputable section + +open scoped BigOperators Classical +open TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +abbrev F2 := ZMod 2 + +variable {branch rows repeats : Nat → Nat} {n h t v m : Nat} [NeZero m] + {upper : Nodes branch n} {d : HierarchicalFrozenTables.LowerNodes upper (h + 1)} + (S : CleanDecoderRate.Setup branch rows repeats n h t v m upper d) + +def meeting (x : CleanDecoderRate.Sample S) (answer : CleanDecoderPairLaw.Pair S x) : Bool := + decide (answer.2 = DecoderSourcePullback.upperTarget + (CleanDecoderOddLists.fullProjection (CleanDecoderPairLaw.context S x) + (CleanDecoderPairLaw.occurrences S x)) upper answer.1) + +variable (hbranch : ∀ k < n, 0 < branch k) + +def nativeRank (x : CleanDecoderRate.Sample S) + (answer : CleanDecoderPairLaw.Pair S x) : Nat := + OddListExtraction.formRank + (H (CleanDecoderOddLists.leftNative (CleanDecoderPairLaw.context S x) + (CleanDecoderPairLaw.leftOwn S x))) + (CleanLeftDecoder.form + (CleanDecoderContext.leftExposed (CleanDecoderPairLaw.context S x)) upper (h + 1) + hbranch d (CleanDecoderPairLaw.leftOwn S x) answer.1) + +def low (s : Nat) (x : CleanDecoderRate.Sample S) + (answer : CleanDecoderPairLaw.Pair S x) : Bool := + decide (nativeRank S hbranch x answer ≤ s) + +def highAgrees (s : Nat) (x : CleanDecoderRate.Sample S) + (answer : CleanDecoderPairLaw.Pair S x) : Bool := + meeting S x answer && !(low S hbranch s x answer) + +@[simp] theorem highAgrees_eq_true (s : Nat) (x : CleanDecoderRate.Sample S) + (answer : CleanDecoderPairLaw.Pair S x) : + highAgrees S hbranch s x answer = true ↔ + s < nativeRank S hbranch x answer ∧ meeting S x answer = true := by + simp [highAgrees, low, and_comm] + +private theorem decide_and_comm (P Q : Prop) [Decidable P] [Decidable Q] : + (decide P && decide Q) = decide (Q ∧ P) := by + by_cases hP : P <;> by_cases hQ : Q <;> simp [hP, hQ] + +theorem meeting_low (s : Nat) (x : CleanDecoderRate.Sample S) + (answer : CleanDecoderPairLaw.Pair S x) : + (meeting S x answer && low S hbranch s x answer) = + CleanDecoderPairLaw.pairAgrees S hbranch s x answer := + decide_and_comm + (answer.2 = DecoderSourcePullback.upperTarget + (CleanDecoderOddLists.fullProjection (CleanDecoderPairLaw.context S x) + (CleanDecoderPairLaw.occurrences S x)) upper answer.1) + (nativeRank S hbranch x answer ≤ s) + +theorem probability_split + (μ : FiniteDistribution (Σ x : CleanDecoderRate.Sample S, CleanDecoderPairLaw.Pair S x)) + (s : Nat) : + μ.probability (fun z => meeting S z.1 z.2) = + μ.probability (fun z => CleanDecoderPairLaw.pairAgrees S hbranch s z.1 z.2) + + μ.probability (fun z => highAgrees S hbranch s z.1 z.2) := by + have hsplit := FixedRankContradiction.probability_split μ + (fun z => meeting S z.1 z.2) (fun z => low S hbranch s z.1 z.2) + simpa only [meeting_low, highAgrees] using hsplit + +variable (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (useful : (record : CleanDecoderRate.Record S) → + CleanLeftDecoder.Useful (CleanDecoderContext.leftExposed (CleanDecoderRate.context S record)) + upper (h + 1)) + (r : Nat) (ρ : ℝ) (A : ManyGoodRows.RowMap (Block rows upper) r) + (W : Submodule F2 (OwnInputReference.UpperVector rows upper)) + (a : OwnInputReference.LowerVector rows (HierarchicalLeftDecoder.LowerNode upper (h + 1) d)) + (threshold : ℝ) + +theorem pair_probability_split (s cube : Nat) (hcube : 0 < cube) : + (CleanDecoderPairLaw.pairLaw S σ useful r ρ A W a threshold cube hcube).probability + (fun z => meeting S z.1 z.2) = + (CleanDecoderPairLaw.pairLaw S σ useful r ρ A W a threshold cube hcube).probability + (fun z => CleanDecoderPairLaw.pairAgrees S hbranch s z.1 z.2) + + (CleanDecoderPairLaw.pairLaw S σ useful r ρ A W a threshold cube hcube).probability + (fun z => highAgrees S hbranch s z.1 z.2) := + probability_split S hbranch _ s + +end +end PerfectCompleteness.DecoderRankSplit + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Algebra/EvaluationMatrix.lean b/lean/OAI/Computability/PerfectCompleteness/Algebra/EvaluationMatrix.lean new file mode 100644 index 0000000000000000000000000000000000000000..d46fdadcb0608e0ecc3909e0397ebfb5009cdb57 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Algebra/EvaluationMatrix.lean @@ -0,0 +1,95 @@ +import Mathlib.LinearAlgebra.Pi +import OAI.Computability.PerfectCompleteness.Foundations.FiniteRangeInverse + +namespace OAI + +section + +namespace PerfectCompleteness.EvaluationMatrix + +noncomputable section + +variable {𝕜 Ω K : Type*} [Field 𝕜] [AddCommGroup K] [Module 𝕜 K] + +def evaluation (H : Submodule 𝕜 (Ω → 𝕜)) (x : Ω) : Module.Dual 𝕜 H where + toFun h := h.val x + map_add' _ _ := rfl + map_smul' _ _ := rfl + +@[simp] theorem evaluation_apply (H : Submodule 𝕜 (Ω → 𝕜)) (x : Ω) (h : H) : + evaluation H x h = h.val x := rfl + +def evaluate (H : Submodule 𝕜 (Ω → 𝕜)) (X : Module.Dual 𝕜 H →ₗ[𝕜] K) (x : Ω) : K := + X (evaluation H x) + +def shift (H : Submodule 𝕜 (Ω → 𝕜)) (X : Module.Dual 𝕜 H →ₗ[𝕜] K) + (a : K) (h : H) : Module.Dual 𝕜 H →ₗ[𝕜] K := + X + (Module.Dual.eval 𝕜 H h).smulRight a + +@[simp] theorem evaluate_shift (H : Submodule 𝕜 (Ω → 𝕜)) + (X : Module.Dual 𝕜 H →ₗ[𝕜] K) (a : K) (h : H) (x : Ω) : + evaluate H (shift H X a h) x = evaluate H X x + h.val x • a := rfl + +def joint {Z : Type*} (H : Submodule 𝕜 (Ω → 𝕜)) (other : Ω → Z) + (X : Module.Dual 𝕜 H →ₗ[𝕜] K) (x : Ω) : K × Z := + (evaluate H X x, other x) + +@[simp] theorem joint_shift {Z : Type*} (H : Submodule 𝕜 (Ω → 𝕜)) + (other : Ω → Z) (X : Module.Dual 𝕜 H →ₗ[𝕜] K) (a : K) (h : H) (x : Ω) : + joint H other (shift H X a h) x = (evaluate H X x + h.val x • a, other x) := rfl + +section Rows + +variable (H : Submodule 𝕜 (Ω → 𝕜)) [FiniteDimensional 𝕜 H] {ℓ : Nat} + +def rows (X : Module.Dual 𝕜 H →ₗ[𝕜] (Fin ℓ → 𝕜)) : Fin ℓ → H := + fun i => (Module.evalEquiv 𝕜 H).symm ((LinearMap.proj i).comp X) + +def ofRows (v : Fin ℓ → H) : Module.Dual 𝕜 H →ₗ[𝕜] (Fin ℓ → 𝕜) := + LinearMap.pi (fun i => Module.Dual.eval 𝕜 H (v i)) + +omit [FiniteDimensional 𝕜 H] in +@[simp] theorem ofRows_apply (v : Fin ℓ → H) (q : Module.Dual 𝕜 H) (i : Fin ℓ) : + ofRows H v q i = q (v i) := rfl + +@[simp] theorem ofRows_rows (X : Module.Dual 𝕜 H →ₗ[𝕜] (Fin ℓ → 𝕜)) : + ofRows H (rows H X) = X := by + ext q i + exact Module.apply_evalEquiv_symm_apply 𝕜 H q ((LinearMap.proj i).comp X) + +@[simp] theorem rows_ofRows (v : Fin ℓ → H) : rows H (ofRows H v) = v := by + funext i + exact (Module.evalEquiv 𝕜 H).symm_apply_apply (v i) + +def rowsEquiv : (Module.Dual 𝕜 H →ₗ[𝕜] (Fin ℓ → 𝕜)) ≃ (Fin ℓ → H) where + toFun := rows H + invFun := ofRows H + left_inv := ofRows_rows H + right_inv := rows_ofRows H + +omit [FiniteDimensional 𝕜 H] in +@[simp] theorem evaluate_ofRows (v : Fin ℓ → H) (x : Ω) : + evaluate H (ofRows H v) x = fun i => (v i).val x := rfl + +theorem rows_apply (X : Module.Dual 𝕜 H →ₗ[𝕜] (Fin ℓ → 𝕜)) (i : Fin ℓ) (x : Ω) : + (rows H X i).val x = evaluate H X x i := + Module.apply_evalEquiv_symm_apply 𝕜 H (evaluation H x) ((LinearMap.proj i).comp X) + +theorem evaluate_injective : + Function.Injective (evaluate H : (Module.Dual 𝕜 H →ₗ[𝕜] (Fin ℓ → 𝕜)) → (Ω → Fin ℓ → 𝕜)) := by + intro X X' h + apply (rowsEquiv H).injective + funext i + apply Subtype.ext + funext x + change (rows H X i).val x = (rows H X' i).val x + rw [rows_apply, rows_apply] + exact congrFun (congrFun h x) i + +end Rows +end +end PerfectCompleteness.EvaluationMatrix + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Algebra/FixedRankContradiction.lean b/lean/OAI/Computability/PerfectCompleteness/Algebra/FixedRankContradiction.lean new file mode 100644 index 0000000000000000000000000000000000000000..df0f14c996d94c90a58ece4d5fe45866ae5d527c --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Algebra/FixedRankContradiction.lean @@ -0,0 +1,59 @@ +import OAI.Computability.PerfectCompleteness.Decoding.TwoResponseCollisionLemmas +import OAI.Computability.PerfectCompleteness.Reduction.FixedCallBudgetLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.FixedRankContradiction + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games + +noncomputable section + +theorem probability_split {Ω : Type*} [Fintype Ω] + (μ : FiniteDistribution Ω) (event low : Ω → Bool) : + μ.probability event = μ.probability (fun x => event x && low x) + + μ.probability (fun x => event x && !(low x)) := by + unfold FiniteDistribution.probability + rw [← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro x _ + cases he : event x <;> cases hl : low x <;> simp [he, hl] + +variable {δ : ℚ} {hδ : 0 < δ} (p : FixedParameters.Parameters δ hδ) + +def gamma (height : Nat) : ℝ := + UpperParameterScalars.gamma (InitialParameters.useful δ) p.plan.density + (InitialParameters.inverse δ) p.plan.order (FixedRows.rows p.plan height) + +theorem impossible {Ω : Type*} [Fintype Ω] (μ : FiniteDistribution Ω) + (event low : Ω → Bool) (height : Nat) (hheight : height ≤ p.plan.depth) + (hupper : gamma p height ≤ μ.probability event) + (hhigh : μ.probability (fun x => event x && !(low x)) ^ 2 ≤ + gamma p height ^ 2 / 8 + 2 * p.accuracy) + (hlow : μ.probability (fun x => event x && low x) < p.accuracy) : False := by + have hgamma : 0 < gamma p height := + UpperParameterScalars.gamma_pos (InitialParameters.useful_pos hδ) + p.plan.density_pos (InitialParameters.inverse_pos hδ) + p.plan.order (FixedRows.rows p.plan height) + have hsmall := p.accuracy_small height hheight + simp only [CommonAccuracy.tolerance, lt_min_iff] at hsmall + have hsquare : p.accuracy < gamma p height ^ 2 / 640 := hsmall.2.2.2.1 + have hlinear : p.accuracy < gamma p height / 40 := hsmall.2.2.2.2 + have hhalf : μ.probability (fun x => event x && !(low x)) < gamma p height / 2 := by + by_contra hn + have hge := le_of_not_gt hn + have hnonneg := μ.probability_nonnegative (fun x => event x && !(low x)) + have hsq := (sq_le_sq₀ (by positivity : 0 ≤ gamma p height / 2) hnonneg).mpr hge + nlinarith + have hsplit := probability_split μ event low + linarith + +end +end PerfectCompleteness.FixedRankContradiction + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Algebra/FunctionSpaceLowerRank.lean b/lean/OAI/Computability/PerfectCompleteness/Algebra/FunctionSpaceLowerRank.lean new file mode 100644 index 0000000000000000000000000000000000000000..8589219d1484466d9f52d184cf0bbae2efaa371d --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Algebra/FunctionSpaceLowerRank.lean @@ -0,0 +1,147 @@ +import OAI.Computability.PerfectCompleteness.Algebra.EvaluationMatrix +import OAI.Computability.PerfectCompleteness.Algebra.LowerAffineSliceRank +import OAI.Computability.PerfectCompleteness.Algebra.ProductEvaluationRank +import OAI.Computability.PerfectCompleteness.Foundations.OddListExtraction + +namespace OAI + + +namespace PerfectCompleteness.FunctionSpaceLowerRank + +noncomputable section + +open scoped BigOperators Classical +open UniqueGamesTheorem.Integration.BinaryLinear (F2) +open UniqueGamesTheorem.Fourier.MatrixLevelBridge +open UniqueGamesTheorem.Appendix.RankLevelFilter +open PointwiseSpaces + +section Transport + +variable {K H V : Type*} [Field K] + [AddCommGroup H] [Module K H] [AddCommGroup V] [Module K V] + +def transportForm (e : H ≃ₗ[K] V) (F : H →ₗ[K] Module.Dual K H) : + V →ₗ[K] Module.Dual K V := + e.symm.toLinearMap.dualMap.comp (F.comp e.symm.toLinearMap) + +@[simp] theorem transportForm_apply (e : H ≃ₗ[K] V) + (F : H →ₗ[K] Module.Dual K H) (u v : V) : + transportForm e F u v = F (e.symm u) (e.symm v) := rfl + +theorem transportForm_rank (e : H ≃ₗ[K] V) (F : H →ₗ[K] Module.Dual K H) : + Module.finrank K (LinearMap.range (transportForm e F)) = + Module.finrank K (LinearMap.range F) := by + unfold transportForm + rw [LinearMap.range_comp, + LinearMap.range_comp_of_range_eq_top F e.symm.range] + exact e.symm.dualMap.finrank_map_eq (LinearMap.range F) + +end Transport + +section FunctionSpace + +variable {Ω : Type*} (H : Submodule F2 (Ω → F2)) [FiniteDimensional F2 H] + {ℓ m : Nat} + +def matrixForm (F : H →ₗ[F2] Module.Dual F2 H) : + Module.Dual F2 (Module.Dual F2 H) →ₗ[F2] + Module.Dual F2 (Module.Dual F2 (Module.Dual F2 H)) := + transportForm (Module.evalEquiv F2 H) F + +@[simp] theorem matrixForm_rank (F : H →ₗ[F2] Module.Dual F2 H) : + Module.finrank F2 (LinearMap.range (matrixForm H F)) = + Module.finrank F2 (LinearMap.range F) := + transportForm_rank (Module.evalEquiv F2 H) F + +theorem testedGram_matrixForm (F : H →ₗ[F2] Module.Dual F2 H) + (X : Module.Dual F2 H →ₗ[F2] (Fin ℓ → F2)) : + LowerAffineSliceRank.testedGram (matrixForm H F) X = + (fun i j => F (EvaluationMatrix.rows H X i) (EvaluationMatrix.rows H X j)) := rfl + +theorem testedGram_multiplicationForm (z : Module.Dual F2 (squareSpace H)) + (X : Module.Dual F2 H →ₗ[F2] (Fin ℓ → F2)) : + LowerAffineSliceRank.testedGram + (matrixForm H (OddListExtraction.multiplicationForm H z)) X = + (fun i j => z (OddListExtraction.productElement H + (EvaluationMatrix.rows H X i) (EvaluationMatrix.rows H X j))) := rfl + +end FunctionSpace + + +open MixedSupport CanonicalKeys +open ProductEvaluation (productSpan displayedJoint labelFunctional) + +variable {n ℓ m : Nat} {Z Y : Type*} [Fintype Y] + (slots : Fin n → Slot) (H : Submodule F2 (Assignment slots → F2)) + [FiniteDimensional F2 H] + (other : Assignment slots → Z) + (hone : (1 : Assignment slots → F2) ∈ squareSpace H) + +def displayedRows (X : Module.Dual F2 H →ₗ[F2] (Fin ℓ → F2)) + (_ : Unit) (i : Fin ℓ) : Assignment slots → F2 := + (EvaluationMatrix.rows H X i).val + +theorem displayedRows_products + (X : Module.Dual F2 H →ₗ[F2] (Fin ℓ → F2)) + (c : Unit) (i j : Fin ℓ) : + displayedRows slots H X c i * displayedRows slots H X c j ∈ squareSpace H := + mul_mem_squareSpace H (EvaluationMatrix.rows H X i).property + (EvaluationMatrix.rows H X j).property + +def testedProductSpan (X : Module.Dual F2 H →ₗ[F2] (Fin ℓ → F2)) : + Submodule F2 (squareSpace H) := + productSpan (squareSpace H) (displayedRows slots H X) hone + (displayedRows_products slots H X) + +def IsLegalExtension (X : Module.Dual F2 H →ₗ[F2] (Fin ℓ → F2)) + (z : Module.Dual F2 (squareSpace H)) : Prop := + ∃ P : Label slots (displayedJoint (displayedRows slots H X) other), + z.comp (testedProductSpan slots H hone X).subtype = + labelFunctional slots (squareSpace H) (displayedRows slots H X) other hone + (displayedRows_products slots H X) P + +theorem legal_extension_tested_rank_le_one + (X : Module.Dual F2 H →ₗ[F2] (Fin ℓ → F2)) + (z : Module.Dual F2 (squareSpace H)) + (hz : IsLegalExtension slots H other hone X z) : + (LowerAffineSliceRank.testedGram + (matrixForm H (OddListExtraction.multiplicationForm H z)) X).rank ≤ 1 := by + obtain ⟨P, hP⟩ := hz + rw [testedGram_multiplicationForm] + exact ProductEvaluationRank.extension_productMatrix_rank_le_one slots + (squareSpace H) (displayedRows slots H X) other hone + (displayedRows_products slots H X) P z hP () + +variable [Fintype (Module.Dual F2 H)] + [Fintype (Module.Dual F2 (Module.Dual F2 H))] + [Fintype (Module.Dual F2 H →ₗ[F2] (Fin ℓ → F2))] + [Fintype ((Fin ℓ → F2) →ₗ[F2] Module.Dual F2 H)] + +theorem high_rank_agreement_lt_of_legal_extensions + (f : (Module.Dual F2 H →ₗ[F2] (Fin ℓ → F2)) → Option Y) + (output : Y → Module.Dual F2 (squareSpace H)) + (legal : ∀ X y, f X = some y → IsLegalExtension slots H other hone X (output y)) + (r s : Nat) (ρ η : ℝ) (hm : 0 < m) + (hρ : 0 < ρ) (hρ1 : ρ < 1) + (hconstants : levelCutoffConstant r ρ + node (r + 1) < η) + (hrows : 2 * m + r ≤ ℓ) + (herror : (2 : ℝ) ^ m / (2 : ℝ) ^ (s - 2 * r) + + (2 : ℝ) ^ (2 * m) / (2 : ℝ) ^ (m * m) ≤ ρ) : + PartialTableInverse.nonzeroAgreement + (MatrixErasure.erase f (fun X => ∃ y, f X = some y ∧ + OddListExtraction.formRank H (OddListExtraction.multiplicationForm H (output y)) ≤ s)) < η := by + have tested : ∀ X y, f X = some y → + (LowerAffineSliceRank.testedGram + (matrixForm H (OddListExtraction.multiplicationForm H (output y))) X).rank ≤ 1 := by + intro X y h + exact legal_extension_tested_rank_le_one slots H other hone X (output y) (legal X y h) + have h := LowerAffineSliceRank.high_rank_agreement_lt f + (fun y => matrixForm H (OddListExtraction.multiplicationForm H (output y))) + tested r s ρ η hm hρ hρ1 hconstants hrows herror + simpa only [matrixForm_rank, OddListExtraction.formRank] using h + +end +end PerfectCompleteness.FunctionSpaceLowerRank + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Algebra/HierarchicalMatrixTable.lean b/lean/OAI/Computability/PerfectCompleteness/Algebra/HierarchicalMatrixTable.lean new file mode 100644 index 0000000000000000000000000000000000000000..6bb1f0aa0c89b946b94733fcbe33ba1bc600ce10 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Algebra/HierarchicalMatrixTable.lean @@ -0,0 +1,170 @@ +import OAI.Computability.PerfectCompleteness.Algebra.CanonicalMatrixTable +import OAI.Computability.PerfectCompleteness.Construction.NodeEmbedding + +namespace OAI + +section + +namespace PerfectCompleteness.HierarchicalMatrixTable + +noncomputable section + +open scoped Classical +open TreeSourceSpaces HierarchicalArrays + +variable {branch rows : Nat → Nat} {n t : Nat} + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (node : Nodes branch n) + +abbrev Background := (j : {j : Nodes branch n // j ≠ node}) → + Fin (rows (Nodes.height j.val)) → NodeEmbedding.NodeH slots j.val + +abbrev SideOutput : Type := + BlockQuotient.OtherBlocks (fun j : Nodes branch n => Block rows j) node × PUnit.{1} + +abbrev Matrix := Module.Dual F2 (NodeEmbedding.RowSpace slots node) →ₗ[F2] Block rows node + +def backgroundOf (arrays : Arrays slots rows) : Background (rows := rows) slots node := + fun j => arrays j.val + +def nativeRows (X : Matrix (rows := rows) slots node) : + Fin (rows (Nodes.height node)) → NodeEmbedding.NodeH slots node := + fun i => (NodeEmbedding.equiv slots node).symm + (EvaluationMatrix.rows (NodeEmbedding.RowSpace slots node) X i) + +def assemble (background : Background (rows := rows) slots node) + (X : Matrix (rows := rows) slots node) : Arrays slots rows := + fun j => if h : j = node then h.symm ▸ nativeRows slots node X else background ⟨j, h⟩ + +@[simp] theorem assemble_selected (background : Background (rows := rows) slots node) + (X : Matrix (rows := rows) slots node) : + assemble slots node background X node = nativeRows slots node X := by + simp [assemble] + +@[simp] theorem assemble_other (background : Background (rows := rows) slots node) + (X : Matrix (rows := rows) slots node) (j : {j : Nodes branch n // j ≠ node}) : + assemble slots node background X j.val = background j := by + simp only [assemble, dite_eq_right j.property] + +theorem embedded_assembled_rows (background : Background (rows := rows) slots node) + (X : Matrix (rows := rows) slots node) : + NodeEmbedding.embeddedRows (assemble slots node background X) node = + EvaluationMatrix.rows (NodeEmbedding.RowSpace slots node) X := by + funext i + change NodeEmbedding.embed slots node ((assemble slots node background X) node i) = _ + rw [assemble_selected] + exact (NodeEmbedding.equiv slots node).apply_symm_apply _ + +theorem matrix_assemble (background : Background (rows := rows) slots node) + (X : Matrix (rows := rows) slots node) : + NodeEmbedding.matrix (assemble slots node background X) node = X := by + unfold NodeEmbedding.matrix + rw [embedded_assembled_rows, EvaluationMatrix.ofRows_rows] + +theorem nativeRows_matrix (arrays : Arrays slots rows) : + nativeRows slots node (NodeEmbedding.matrix arrays node) = arrays node := by + funext i + change (NodeEmbedding.equiv slots node).symm + (EvaluationMatrix.rows (NodeEmbedding.RowSpace slots node) + (EvaluationMatrix.ofRows (NodeEmbedding.RowSpace slots node) + (NodeEmbedding.embeddedRows arrays node)) i) = arrays node i + rw [EvaluationMatrix.rows_ofRows] + exact (NodeEmbedding.equiv slots node).symm_apply_apply _ + +theorem assemble_original (arrays : Arrays slots rows) : + assemble slots node (backgroundOf slots node arrays) (NodeEmbedding.matrix arrays node) = arrays := by + funext j + by_cases hj : j = node + · subst j + rw [assemble_selected, nativeRows_matrix] + · simp only [assemble, dite_eq_right hj, backgroundOf] + +def other (background : Background (rows := rows) slots node) + (x : NodeEmbedding.NumberedDomain slots) : SideOutput (rows := rows) node := + (fun j i => (background j i).val (NodeEmbedding.numberedRestriction slots j.val x), PUnit.unit) + +def displayed (background : Background (rows := rows) slots node) + (X : Matrix (rows := rows) slots node) : + NodeEmbedding.NumberedDomain slots → (Output branch n rows : Type) := + TreeCanonical.numberedFunction slots (fullJoint (assemble slots node background X)) + +theorem displayed_original (arrays : Arrays slots rows) : + displayed slots node (backgroundOf slots node arrays) (NodeEmbedding.matrix arrays node) = + TreeCanonical.numberedFunction slots (fullJoint arrays) := by + unfold displayed + rw [assemble_original] + +theorem query_eq_split_displayed (background : Background (rows := rows) slots node) + (X : Matrix (rows := rows) slots node) : + CanonicalMatrixTable.query (TreeCanonical.numberedSlots slots) + (NodeEmbedding.RowSpace slots node) (other slots node background) X = + BlockQuotient.splitOutput (fun j : Nodes branch n => Block rows j) PUnit.{1} node ∘ + displayed slots node background X := by + funext x + apply Prod.ext + · change EvaluationMatrix.evaluate (NodeEmbedding.RowSpace slots node) X x = + (displayed slots node background X x).1 node + have he := NodeEmbedding.matrix_evaluate (assemble slots node background X) node x + rw [matrix_assemble] at he + exact he + · apply Prod.ext + · funext j i + change (background j i).val (NodeEmbedding.numberedRestriction slots j.val x) = + ((assemble slots node background X) j.val i).val + (NodeEmbedding.numberedRestriction slots j.val x) + rw [assemble_other] + · rfl + +variable (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + +theorem response_eq_split_response (background : Background (rows := rows) slots node) + (X : Matrix (rows := rows) slots node) : + CanonicalMatrixTable.response (TreeCanonical.numberedSlots slots) + (NodeEmbedding.RowSpace slots node) (other slots node background) σ X = + BlockQuotient.splitOutput (fun j : Nodes branch n => Block rows j) PUnit.{1} node + (KeyStrategy.response σ .left (TreeCanonical.numberedSlots slots) + (displayed slots node background X)) := by + unfold CanonicalMatrixTable.response + rw [query_eq_split_displayed] + exact KeyStrategy.response_postcomp_injective σ .left (TreeCanonical.numberedSlots slots) + (displayed slots node background X) + (BlockQuotient.splitOutput (fun j : Nodes branch n => Block rows j) PUnit.{1} node) + (BlockQuotient.splitOutput (fun j : Nodes branch n => Block rows j) PUnit.{1} node).injective + +theorem rightQuery_eq (background : Background (rows := rows) slots node) + (X : Matrix (rows := rows) slots node) (a : Block rows node) : + CanonicalMatrixTable.rightQuery (TreeCanonical.numberedSlots slots) + (NodeEmbedding.RowSpace slots node) (other slots node background) a X = + BlockQuotient.projectBlock node a ∘ displayed slots node background X := by + unfold CanonicalMatrixTable.rightQuery + rw [query_eq_split_displayed] + rfl + +theorem accepts_iff_canonical (background : Background (rows := rows) slots node) + (X : Matrix (rows := rows) slots node) (a : Block rows node) : + CanonicalMatrixTable.Accepts (TreeCanonical.numberedSlots slots) + (NodeEmbedding.RowSpace slots node) (other slots node background) σ a X ↔ + CanonicalEdges.coarsen (TreeCanonical.numberedSlots slots) + (displayed slots node background X) (BlockQuotient.projectBlock node a) + (KeyStrategy.label σ .left (TreeCanonical.numberedSlots slots) + (displayed slots node background X)) = + KeyStrategy.label σ .right (TreeCanonical.numberedSlots slots) + (BlockQuotient.projectBlock node a ∘ displayed slots node background X) := by + have hresponse := congrArg (DirectionQuotient.projectWithSide a) + (response_eq_split_response slots node σ background X) + have hright := congrArg + (KeyStrategy.response σ .right (TreeCanonical.numberedSlots slots)) + (rightQuery_eq slots node background X a) + rw [CanonicalMatrixTable.accepts_iff, CanonicalEdges.coarsen_eq_iff] + constructor + · intro h + exact hresponse.symm.trans (h.trans hright) + · intro h + exact hresponse.trans (h.trans hright.symm) + +end +end PerfectCompleteness.HierarchicalMatrixTable + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Algebra/LowerAffineSliceRank.lean b/lean/OAI/Computability/PerfectCompleteness/Algebra/LowerAffineSliceRank.lean new file mode 100644 index 0000000000000000000000000000000000000000..80901fcb4bcd88337deb0f0a01174f3c016efaef --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Algebra/LowerAffineSliceRank.lean @@ -0,0 +1,246 @@ +import Mathlib.Algebra.BigOperators.Pi +import Mathlib.Data.Fintype.EquivFin +import OAI.Computability.PerfectCompleteness.Algebra.BilinearGramCompressionLemmas +import OAI.Computability.PerfectCompleteness.Algebra.LowerCrossRank +import OAI.Computability.PerfectCompleteness.Algebra.MatrixErasure +import OAI.Computability.PerfectCompleteness.Foundations.PartialTableInverse +import OAI.Computability.PerfectCompleteness.Sampling.RestrictionCrossLaw + +namespace OAI + + +namespace PerfectCompleteness.LowerAffineSliceRank + +noncomputable section + +open scoped BigOperators Classical +open UniqueGamesTheorem.Integration.BinaryLinear (F2) +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Fourier.MatrixRestrictions +open UniqueGamesTheorem.Fourier.MatrixLevelBridge +open UniqueGamesTheorem.Appendix.RankLevelFilter +open BilinearGramCompression + +variable {E : Type*} [AddCommGroup E] [Module F2 E] + [Fintype E] [FiniteDimensional F2 E] + {ℓ m : Nat} + [Fintype (Module.Dual F2 E)] + +def matrixRows (X : E →ₗ[F2] (Fin ℓ → F2)) : Fin ℓ → Module.Dual F2 E := + fun i => (LinearMap.proj i).comp X + +def testedGram (F : Module.Dual F2 E →ₗ[F2] Module.Dual F2 (Module.Dual F2 E)) + (X : E →ₗ[F2] (Fin ℓ → F2)) : Matrix (Fin ℓ) (Fin ℓ) F2 := + gram F (matrixRows X) + +omit [Fintype E] [FiniteDimensional F2 E] [Fintype (Module.Dual F2 E)] in +theorem coordinate_eq_sum (X : E →ₗ[F2] (Fin ℓ → F2)) + (q : Module.Dual F2 (Fin ℓ → F2)) : + q.comp X = ∑ k, q (Pi.single k 1) • matrixRows X k := by + apply LinearMap.ext + intro e + simp only [LinearMap.sum_apply, LinearMap.smul_apply, LinearMap.comp_apply, + matrixRows, LinearMap.proj_apply, smul_eq_mul] + change q (X e) = ∑ k, q (Pi.single k 1) * X e k + have hrows := pi_eq_sum_univ' (X e) + calc + q (X e) = q (∑ k : Fin ℓ, (X e k) • Pi.single k (1 : F2)) := + congrArg q hrows + _ = ∑ k : Fin ℓ, (X e k) * q (Pi.single k 1) := by + simp only [map_sum, map_smul, smul_eq_mul] + _ = _ := Finset.sum_congr rfl (fun k _ => mul_comm _ _) + +omit [Fintype E] [FiniteDimensional F2 E] [Fintype (Module.Dual F2 E)] in +theorem coordinate_cross_rank_le + (F : Module.Dual F2 E →ₗ[F2] Module.Dual F2 (Module.Dual F2 E)) + (X : E →ₗ[F2] (Fin ℓ → F2)) + (left right : Fin m → Module.Dual F2 (Fin ℓ → F2)) : + Matrix.rank ((fun i j => F ((left i).comp X) ((right j).comp X)) : + Matrix (Fin m) (Fin m) F2) ≤ + (testedGram F X).rank := by + have hleft : combinations (matrixRows X) + (fun i k => left i (Pi.single k 1)) = fun i => (left i).comp X := by + funext i + exact (coordinate_eq_sum X (left i)).symm + have hright : combinations (matrixRows X) + (fun j k => right j (Pi.single k 1)) = fun j => (right j).comp X := by + funext j + exact (coordinate_eq_sum X (right j)).symm + have h := cross_rank_le F (matrixRows X) + (fun i k => left i (Pi.single k 1)) + (fun j k => right j (Pi.single k 1)) + rw [hleft, hright] at h + exact h + +section Coordinates + +variable {I : Type*} [Fintype I] + (W : Submodule F2 E) (C' : Submodule F2 (Fin ℓ → F2)) + (b : Module.Basis I F2 C') (sel : (Fin m ⊕ Fin m) → I) + +theorem slice_probability_le_of_coordinates (hsel : Function.Injective sel) + (coordinates : I → Module.Dual F2 (Fin ℓ → F2)) + (hcoordinates : ∀ i, (coordinates i).comp C'.subtype = b.coord i) + (X : E →ₗ[F2] (Fin ℓ → F2)) + (F : Module.Dual F2 E →ₗ[F2] Module.Dual F2 (Module.Dual F2 E)) + (r s : Nat) (hW : Module.finrank F2 W ≤ r) + (hrank : s < Module.finrank F2 (LinearMap.range F)) : + (FiniteDistribution.uniform (Parameter W C')).probability + (fun A => decide ((testedGram F (translate W C' X A)).rank ≤ 1)) ≤ + (2 : ℝ) ^ m / (2 : ℝ) ^ (s - 2 * r) + + (2 : ℝ) ^ (2 * m) / (2 : ℝ) ^ (m * m) := by + have hlaw := RestrictionCrossLaw.crossMatrix_law W C' b sel hsel + coordinates hcoordinates X F + have hp := congrArg + (fun μ : FiniteDistribution (Matrix (Fin m) (Fin m) F2) => + μ.probability (fun M => decide (M.rank ≤ 1))) hlaw + simp only [FiniteDistribution.probability_pushforward] at hp + have hsource := FiniteDistribution.probability_pushforward + (Γ := Matrix (Fin m) (Fin m) F2) + (FiniteDistribution.uniform (Parameter W C')) + (fun A i j => + F ((coordinates (sel (Sum.inl i))).comp (translate W C' X A)) + ((coordinates (sel (Sum.inr j))).comp (translate W C' X A))) + (fun M => decide (M.rank ≤ 1)) + have hp' := hsource.symm.trans hp + have hcodim : Module.finrank F2 + (Module.Dual F2 E ⧸ W.dualAnnihilator) ≤ r := by + rw [DualQuotientRows.codim_dualAnnihilator_eq] + exact hW + calc + _ ≤ (FiniteDistribution.uniform (Parameter W C')).probability + (fun A => decide (Matrix.rank ((fun i j => + F ((coordinates (sel (Sum.inl i))).comp (translate W C' X A)) + ((coordinates (sel (Sum.inr j))).comp (translate W C' X A))) : + Matrix (Fin m) (Fin m) F2) ≤ 1)) := by + apply FiniteDistribution.probability_mono + intro A hA + apply decide_eq_true + exact (coordinate_cross_rank_le F (translate W C' X A) + (fun i => coordinates (sel (Sum.inl i))) + (fun j => coordinates (sel (Sum.inr j)))).trans (of_decide_eq_true hA) + _ = _ := hp' + _ ≤ _ := LowerCrossRank.cross_rank_probability_le_of_rank_gt F W.dualAnnihilator + (fun i => (coordinates (sel (Sum.inl i))).comp X) + (fun j => (coordinates (sel (Sum.inr j))).comp X) r s hcodim hrank + +end Coordinates + +theorem slice_rank_probability_le_of_rank_gt + (W : Submodule F2 E) (C' : Submodule F2 (Fin ℓ → F2)) + (X : E →ₗ[F2] (Fin ℓ → F2)) + (F : Module.Dual F2 E →ₗ[F2] Module.Dual F2 (Module.Dual F2 E)) + (r s : Nat) (horder : order W C' ≤ r) (hrows : 2 * m + r ≤ ℓ) + (hrank : s < Module.finrank F2 (LinearMap.range F)) : + (FiniteDistribution.uniform (Parameter W C')).probability + (fun A => decide ((testedGram F (translate W C' X A)).rank ≤ 1)) ≤ + (2 : ℝ) ^ m / (2 : ℝ) ^ (s - 2 * r) + + (2 : ℝ) ^ (2 * m) / (2 : ℝ) ^ (m * m) := by + let b := Module.finBasis F2 C' + have hW : Module.finrank F2 W ≤ r := (Nat.le_add_right _ _).trans horder + have hdim : 2 * m ≤ Module.finrank F2 C' := by + have htotal := C'.finrank_quotient_add_finrank + have hfull : Module.finrank F2 (Fin ℓ → F2) = ℓ := by + simp [Module.finrank_fintype_fun_eq_card] + rw [hfull] at htotal + unfold order at horder + omega + obtain ⟨sel⟩ := Function.Embedding.nonempty_of_card_le + (show Fintype.card (Fin m ⊕ Fin m) ≤ + Fintype.card (Fin (Module.finrank F2 C')) by + simpa only [Fintype.card_sum, Fintype.card_fin, two_mul] using hdim) + let coordinates : Fin (Module.finrank F2 C') → Module.Dual F2 (Fin ℓ → F2) := + fun i => Subspace.dualLift C' (b.coord i) + have hcoordinates : ∀ i, (coordinates i).comp C'.subtype = b.coord i := by + intro i + apply LinearMap.ext + intro x + change Subspace.dualLift C' (b.coord i) (x : Fin ℓ → F2) = b.coord i x + exact Subspace.dualLift_of_subtype (φ := b.coord i) x + exact slice_probability_le_of_coordinates W C' b sel sel.injective + coordinates hcoordinates X F r s hW hrank + + +variable {Y : Type*} [Fintype Y] + (f : (E →ₗ[F2] (Fin ℓ → F2)) → Option Y) + (form : Y → Module.Dual F2 E →ₗ[F2] Module.Dual F2 (Module.Dual F2 E)) + +private theorem probability_eq_expect_indicator {A : Type*} [Fintype A] [Nonempty A] + (event : A → Bool) : + (FiniteDistribution.uniform A).probability event = + 𝔼 a : A, if event a then (1 : ℝ) else 0 := by + have h : (FiniteDistribution.uniform A).probability event = + (FiniteDistribution.uniform A).expectation (fun a => if event a then (1 : ℝ) else 0) := by + simp [FiniteDistribution.probability, FiniteDistribution.expectation, mul_ite] + rw [h, FiniteDistribution.expectation_uniform, Fintype.expect_eq_sum_div_card] + +omit [Fintype Y] in +theorem dense_value_rank_le + (tested : ∀ X y, f X = some y → (testedGram (form y) X).rank ≤ 1) + (W : Submodule F2 E) (C' : Submodule F2 (Fin ℓ → F2)) + (X : E →ₗ[F2] (Fin ℓ → F2)) (y : Y) + (r s : Nat) (ρ : ℝ) (horder : order W C' ≤ r) (hrows : 2 * m + r ≤ ℓ) + (herror : (2 : ℝ) ^ m / (2 : ℝ) ^ (s - 2 * r) + + (2 : ℝ) ^ (2 * m) / (2 : ℝ) ^ (m * m) ≤ ρ) + (hdense : ρ < 𝔼 A : Parameter W C', + restrict (PartialTableInverse.indicator f y) W C' X A) : + Module.finrank F2 (LinearMap.range (form y)) ≤ s := by + by_contra h + have hbound := slice_rank_probability_le_of_rank_gt W C' X (form y) r s + horder hrows (Nat.lt_of_not_ge h) + have hdom : (𝔼 A : Parameter W C', + restrict (PartialTableInverse.indicator f y) W C' X A) ≤ + (FiniteDistribution.uniform (Parameter W C')).probability + (fun A => decide ((testedGram (form y) (translate W C' X A)).rank ≤ 1)) := by + rw [probability_eq_expect_indicator] + apply Finset.expect_le_expect + intro A _ + by_cases hf : f (translate W C' X A) = some y + · simp [restrict, PartialTableInverse.indicator, hf, tested _ _ hf] + · simp only [restrict, PartialTableInverse.indicator, ite_eq_right hf] + split_ifs <;> norm_num + exact (not_le_of_gt hdense) (hdom.trans (hbound.trans herror)) + +theorem high_rank_agreement_lt + [Fintype (E →ₗ[F2] (Fin ℓ → F2))] + [Fintype ((Fin ℓ → F2) →ₗ[F2] E)] + (tested : ∀ X y, f X = some y → (testedGram (form y) X).rank ≤ 1) + (r s : Nat) (ρ η : ℝ) (hm : 0 < m) + (hρ : 0 < ρ) (hρ1 : ρ < 1) + (hconstants : levelCutoffConstant r ρ + node (r + 1) < η) + (hrows : 2 * m + r ≤ ℓ) + (herror : (2 : ℝ) ^ m / (2 : ℝ) ^ (s - 2 * r) + + (2 : ℝ) ^ (2 * m) / (2 : ℝ) ^ (m * m) ≤ ρ) : + PartialTableInverse.nonzeroAgreement + (MatrixErasure.erase f (fun X => ∃ y, f X = some y ∧ + Module.finrank F2 (LinearMap.range (form y)) ≤ s)) < η := by + have hℓ : 0 < ℓ := by omega + let : Nonempty (Fin ℓ) := ⟨⟨0, hℓ⟩⟩ + let T := fun X => ∃ y, f X = some y ∧ + Module.finrank F2 (LinearMap.range (form y)) ≤ s + let g := MatrixErasure.erase f T + have htested : ∀ X y, g X = some y → (testedGram (form y) X).rank ≤ 1 := by + intro X y h + exact tested X y ((MatrixErasure.erase_eq_some_iff f T X y).mp h).2 + by_contra h + have hagreement : η ≤ PartialTableInverse.nonzeroAgreement g := le_of_not_gt h + obtain ⟨y, W, C', X, horder, hdense⟩ := + PartialTableInverse.exists_dense_slice_nonzero r ρ η hρ hρ1 hconstants g hagreement + have hrank := dense_value_rank_le g form htested W C' X y r s ρ horder hrows herror hdense + have hnone (A : Parameter W C') : g (translate W C' X A) ≠ some y := by + intro h + have he := (MatrixErasure.erase_eq_some_iff f T _ y).mp h + exact he.1 ⟨y, he.2, hrank⟩ + have hzero : (𝔼 A : Parameter W C', + restrict (PartialTableInverse.indicator g y) W C' X A) = 0 := by + apply Finset.expect_eq_zero + intro A _ + simp [restrict, PartialTableInverse.indicator, hnone A] + rw [hzero] at hdense + exact (not_lt_of_ge hρ.le) hdense + + +end +end PerfectCompleteness.LowerAffineSliceRank + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Algebra/LowerCrossRank.lean b/lean/OAI/Computability/PerfectCompleteness/Algebra/LowerCrossRank.lean new file mode 100644 index 0000000000000000000000000000000000000000..c65dcc2a93519d81550568e9c44fcd3bc2805245 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Algebra/LowerCrossRank.lean @@ -0,0 +1,252 @@ +import Mathlib.LinearAlgebra.Dual.Lemmas +import Mathlib.LinearAlgebra.Matrix.Rank +import OAI.Computability.PerfectCompleteness.Algebra.AffineFunctionalDependence +import OAI.Computability.PerfectCompleteness.Algebra.BilinearGramCompressionLemmas +import OAI.Computability.PerfectCompleteness.Algebra.UniformLinearImage +import OAI.Computability.PerfectCompleteness.Machines.BinaryRankOneCount +import OAI.Computability.UniqueGames.Games.FinishBoundsLemmas + +namespace OAI + + +namespace PerfectCompleteness.LowerCrossRank + +noncomputable section + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Integration.BinaryLinear (F2) + +section Evaluation + +variable {K I N : Type*} [Field K] [Fintype I] + [AddCommGroup N] [Module K N] + +theorem evaluation_surjective (forms : I → Module.Dual K N) + (hforms : LinearIndependent K forms) : Function.Surjective (LinearMap.pi forms) := by + have hfun : LinearIndependent K (fun i => (forms i : N → K)) := by + exact hforms.map' (LinearMap.ltoFun K N K K) + (LinearMap.ker_eq_bot.mpr DFunLike.coe_injective) + have hspan : Submodule.span K + (Set.range (fun n : N => fun i : I => forms i n)) = ⊤ := + span_flip_eq_top_iff_linearIndependent.mpr hfun + apply LinearMap.range_eq_top.mp + apply top_unique + rw [← hspan] + apply Submodule.span_le.mpr + rintro _ ⟨n, rfl⟩ + exact ⟨n, rfl⟩ + +variable {J : Type*} [Fintype J] + +def crossLinear (forms : I → Module.Dual K N) : + (J → N) →ₗ[K] Matrix I J K where + toFun y i j := forms i (y j) + map_add' y z := by ext i j; exact map_add (forms i) (y j) (z j) + map_smul' a y := by ext i j; exact map_smul (forms i) a (y j) + +omit [Fintype J] in +theorem crossLinear_surjective (forms : I → Module.Dual K N) + (hforms : LinearIndependent K forms) : + Function.Surjective (crossLinear (J := J) forms) := by + intro M + have h := evaluation_surjective forms hforms + choose y hy using (fun j : J => h (fun i => M i j)) + refine ⟨y, ?_⟩ + ext i j + exact congrFun (hy j) i + +end Evaluation + +private theorem uniform_pushforward_perm {A : Type*} [Fintype A] [Nonempty A] + (e : A ≃ A) : + (FiniteDistribution.uniform A).pushforward e = FiniteDistribution.uniform A := by + apply FiniteDistribution.eq_of_weight_eq + intro y + change (∑ x : A, if e x = y then (1 / (Fintype.card A : ℝ)) else 0) = + 1 / (Fintype.card A : ℝ) + simp_rw [← e.eq_symm_apply] + simp + +section UniformCross + +variable {I J N : Type*} [Fintype I] [Fintype J] + [AddCommGroup N] [Module F2 N] [Fintype N] + [Fintype (J → N)] [Fintype (Matrix I J F2)] + +omit [Fintype N] [Fintype J] in +theorem affine_cross_uniform (forms : I → Module.Dual F2 N) + (hforms : LinearIndependent F2 forms) (offset : Matrix I J F2) : + (FiniteDistribution.uniform (J → N)).pushforward (Γ := Matrix I J F2) + (fun y i j => offset i j + forms i (y j)) = + FiniteDistribution.uniform (Matrix I J F2) := by + calc + _ = ((FiniteDistribution.uniform (J → N)).pushforward (Γ := Matrix I J F2) + (crossLinear forms)).pushforward (Γ := Matrix I J F2) + (fun M => offset + M) := + (FiniteDistribution.pushforward_comp _ _ _).symm + _ = (FiniteDistribution.uniform (Matrix I J F2)).pushforward (Γ := Matrix I J F2) + (fun M => offset + M) := by + rw [UniformLinearImage.uniform_pushforward_linearMap + (crossLinear forms) (crossLinear_surjective forms hforms)] + _ = _ := uniform_pushforward_perm (Equiv.addLeft offset) + +end UniformCross + + +variable {H : Type*} [AddCommGroup H] [Module F2 H] + [Fintype H] [FiniteDimensional F2 H] + (F : H →ₗ[F2] Module.Dual F2 H) (N : Submodule F2 H) + {m : Nat} (u v : Fin m → H) + +def firstFunctionals (x : Fin m → N) (i : Fin m) : Module.Dual F2 N := + N.dualRestrict (F (u i + (x i : H))) + +def crossMatrix (x y : Fin m → N) : Matrix (Fin m) (Fin m) F2 := + fun i j => F (u i + (x i : H)) (v j + (y j : H)) + +omit [FiniteDimensional F2 H] in +theorem crossMatrix_uniform_of_independent (x : Fin m → N) + (hx : LinearIndependent F2 (firstFunctionals F N u x)) : + (FiniteDistribution.uniform (Fin m → N)).pushforward + (crossMatrix F N u v x) = + FiniteDistribution.uniform (Matrix (Fin m) (Fin m) F2) := by + have h := affine_cross_uniform (firstFunctionals F N u x) hx + (fun i j => F (u i + (x i : H)) (v j)) + have heq : crossMatrix F N u v x = + fun y i j => F (u i + (x i : H)) (v j) + + firstFunctionals F N u x i (y j) := by + funext y i j + exact map_add (F (u i + (x i : H))) (v j) (y j : H) + rw [heq] + exact h + +omit [FiniteDimensional F2 H] in +theorem conditional_rank_probability_le (x : Fin m → N) + (hx : LinearIndependent F2 (firstFunctionals F N u x)) : + (FiniteDistribution.uniform (Fin m → N)).probability + (fun y => decide ((crossMatrix F N u v x y).rank ≤ 1)) ≤ + (2 : ℝ) ^ (2 * m) / (2 : ℝ) ^ (m * m) := by + have h := congrArg (fun μ : FiniteDistribution (Matrix (Fin m) (Fin m) F2) => + μ.probability (fun M => decide (M.rank ≤ 1))) + (crossMatrix_uniform_of_independent F N u v x hx) + rw [FiniteDistribution.probability_pushforward] at h + rw [h] + exact BinaryRankOneCount.uniform_rank_le_one_probability_le m + +private theorem probability_product {A B : Type*} [Fintype A] [Fintype B] + (μ : FiniteDistribution A) (ν : FiniteDistribution B) (event : A × B → Bool) : + (μ.product ν).probability event = + μ.expectation (fun a => ν.probability (fun b => event (a, b))) := by + simp only [FiniteDistribution.probability, FiniteDistribution.expectation, + FiniteDistribution.product, Fintype.sum_prod_type, Finset.mul_sum, mul_ite, mul_zero] + +omit [FiniteDimensional F2 H] in +theorem cross_rank_probability_le : + ((FiniteDistribution.uniform (Fin m → N)).product + (FiniteDistribution.uniform (Fin m → N))).probability + (fun p => decide ((crossMatrix F N u v p.1 p.2).rank ≤ 1)) ≤ + (2 : ℝ) ^ m / + (2 : ℝ) ^ Module.finrank F2 + (LinearMap.range (BilinearRestrictionRank.restrictForm F N)) + + (2 : ℝ) ^ (2 * m) / (2 : ℝ) ^ (m * m) := by + let : Fintype (Module.Dual F2 N) := + Fintype.ofInjective (fun f : Module.Dual F2 N => (f : N → F2)) + DFunLike.coe_injective + let q : ℝ := (2 : ℝ) ^ (2 * m) / (2 : ℝ) ^ (m * m) + have hq : 0 ≤ q := by positivity + have hdep := AffineFunctionalDependence.dependence_probability_le + (BilinearRestrictionRank.restrictForm F N) + (fun i => N.dualRestrict (F (u i))) + have hforms (x : Fin m → N) : firstFunctionals F N u x = + fun i => N.dualRestrict (F (u i)) + + BilinearRestrictionRank.restrictForm F N (x i) := by + funext i + simp [firstFunctionals, BilinearRestrictionRank.restrictForm, map_add] + have hdep' : (FiniteDistribution.uniform (Fin m → N)).probability + (fun x => decide (¬ LinearIndependent F2 (firstFunctionals F N u x))) ≤ + (2 : ℝ) ^ m / + (2 : ℝ) ^ Module.finrank F2 + (LinearMap.range (BilinearRestrictionRank.restrictForm F N)) := by + simpa only [hforms] using hdep + rw [probability_product] + calc + _ ≤ (FiniteDistribution.uniform (Fin m → N)).expectation + (fun x => (if ¬ LinearIndependent F2 (firstFunctionals F N u x) + then (1 : ℝ) else 0) + q) := by + apply SmallBias.expectation_mono + intro x + by_cases hx : LinearIndependent F2 (firstFunctionals F N u x) + · simpa only [hx, not_true_eq_false, ite_false, zero_add] using + conditional_rank_probability_le F N u v x hx + · simpa only [hx, not_false_eq_true, ite_true] using + ((FiniteDistribution.uniform (Fin m → N)).probability_le_one + (fun y => decide ((crossMatrix F N u v x y).rank ≤ 1))).trans + (le_add_of_nonneg_right hq) + _ = (FiniteDistribution.uniform (Fin m → N)).probability + (fun x => decide (¬ LinearIndependent F2 (firstFunctionals F N u x))) + q := by + simp [FiniteDistribution.expectation, FiniteDistribution.probability, + mul_add, mul_ite, mul_one, mul_zero, Finset.sum_add_distrib, + ← Finset.sum_mul, FiniteDistribution.normalized, one_mul] + _ ≤ _ := add_le_add hdep' (le_refl q) + +def gramMatrix (x y : Fin m → N) : + Matrix (Fin m ⊕ Fin m) (Fin m ⊕ Fin m) F2 := + let rows : Fin m ⊕ Fin m → H := + Sum.elim (fun i => u i + (x i : H)) (fun j => v j + (y j : H)) + fun i j => F (rows i) (rows j) + +omit [Fintype H] [FiniteDimensional F2 H] in +theorem cross_rank_le_gram_rank (x y : Fin m → N) : + (crossMatrix F N u v x y).rank ≤ (gramMatrix F N u v x y).rank := + Matrix.rank_submatrix_le (gramMatrix F N u v x y) Sum.inl Sum.inr + +omit [FiniteDimensional F2 H] in +theorem gram_rank_probability_le : + ((FiniteDistribution.uniform (Fin m → N)).product + (FiniteDistribution.uniform (Fin m → N))).probability + (fun p => decide ((gramMatrix F N u v p.1 p.2).rank ≤ 1)) ≤ + (2 : ℝ) ^ m / + (2 : ℝ) ^ Module.finrank F2 + (LinearMap.range (BilinearRestrictionRank.restrictForm F N)) + + (2 : ℝ) ^ (2 * m) / (2 : ℝ) ^ (m * m) := by + apply le_trans _ (cross_rank_probability_le F N u v) + apply FiniteDistribution.probability_mono + intro p hp + apply decide_eq_true + exact (cross_rank_le_gram_rank F N u v p.1 p.2).trans (of_decide_eq_true hp) + +theorem cross_rank_probability_le_of_rank_gt (r s : Nat) + (hcodim : Module.finrank F2 (H ⧸ N) ≤ r) + (hrank : s < Module.finrank F2 (LinearMap.range F)) : + ((FiniteDistribution.uniform (Fin m → N)).product + (FiniteDistribution.uniform (Fin m → N))).probability + (fun p => decide ((crossMatrix F N u v p.1 p.2).rank ≤ 1)) ≤ + (2 : ℝ) ^ m / (2 : ℝ) ^ (s - 2 * r) + + (2 : ℝ) ^ (2 * m) / (2 : ℝ) ^ (m * m) := by + have hloss := BilinearRestrictionRank.rank_restrict_add_codim F N + have hexp : s - 2 * r ≤ Module.finrank F2 + (LinearMap.range (BilinearRestrictionRank.restrictForm F N)) := by omega + apply (cross_rank_probability_le F N u v).trans + apply add_le_add _ (le_refl _) + exact div_le_div_of_nonneg_left (by positivity) (by positivity) + (pow_le_pow_right₀ (by norm_num) hexp) + +theorem rank_le_of_cross_probability (r s : Nat) (α : ℝ) + (hcodim : Module.finrank F2 (H ⧸ N) ≤ r) + (herror : (2 : ℝ) ^ m / (2 : ℝ) ^ (s - 2 * r) + + (2 : ℝ) ^ (2 * m) / (2 : ℝ) ^ (m * m) < α) + (hdensity : α ≤ + ((FiniteDistribution.uniform (Fin m → N)).product + (FiniteDistribution.uniform (Fin m → N))).probability + (fun p => decide ((crossMatrix F N u v p.1 p.2).rank ≤ 1))) : + Module.finrank F2 (LinearMap.range F) ≤ s := by + by_contra h + have hbound := cross_rank_probability_le_of_rank_gt F N u v r s hcodim + (Nat.lt_of_not_ge h) + exact (not_le_of_gt herror) (hdensity.trans hbound) + +end +end PerfectCompleteness.LowerCrossRank + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Algebra/LowerCutNodeMatrix.lean b/lean/OAI/Computability/PerfectCompleteness/Algebra/LowerCutNodeMatrix.lean new file mode 100644 index 0000000000000000000000000000000000000000..b2fc0c14d3153d4a7444836181f7bdad7c2df504 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Algebra/LowerCutNodeMatrix.lean @@ -0,0 +1,149 @@ +import OAI.Computability.PerfectCompleteness.Decoding.LowerCutNodeCoordinates + +namespace OAI + +section + +namespace PerfectCompleteness.LowerCutNodeMatrix + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open WholeArraySubtreeSplit WholeArrayInteriorExterior LowerCutNodeCoordinates +open scoped Classical + +noncomputable section + +variable {branch : Nat → Nat} {n m t : Nat} + +abbrev NativeMatrix (rows : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) := + Module.Dual F2 (H (subtreeSlots p slots)) →ₗ[F2] (Fin (rows (m + 1)) → F2) + +abbrev NodeMatrix (rows : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) := + Module.Dual F2 (H (nodeSlots slots (upperNode p))) →ₗ[F2] Block rows (upperNode p) + +def matrixEquiv (rows : Nat → Nat) : {n m : Nat} → + (p : Path branch n (m + 1)) → + (slots : Slots branch n → Fin t → MixedSupport.Slot) → + NativeMatrix rows p slots ≃ₗ[F2] NodeMatrix rows p slots + | _, _, .refl _, _ => LinearEquiv.refl F2 _ + | _, _, .step i p, slots => matrixEquiv rows p (childSlots slots i) + +theorem ofRows_transport (rows : Nat → Nat) : {n m : Nat} → + (p : Path branch n (m + 1)) → + (slots : Slots branch n → Fin t → MixedSupport.Slot) → + (S : Fin (rows (m + 1)) → H (subtreeSlots p slots)) → + matrixEquiv rows p slots (EvaluationMatrix.ofRows (H (subtreeSlots p slots)) S) = + EvaluationMatrix.ofRows (H (nodeSlots slots (upperNode p))) (rowEquiv rows p slots S) + | _, _, .refl _, _, _ => rfl + | _, _, .step i p, slots, S => ofRows_transport rows p (childSlots slots i) S + +theorem rows_transport (rows : Nat → Nat) : {n m : Nat} → + (p : Path branch n (m + 1)) → + (slots : Slots branch n → Fin t → MixedSupport.Slot) → + (X : NativeMatrix rows p slots) → + EvaluationMatrix.rows (H (nodeSlots slots (upperNode p))) (matrixEquiv rows p slots X) = + rowEquiv rows p slots (EvaluationMatrix.rows (H (subtreeSlots p slots)) X) + | _, _, .refl _, _, _ => rfl + | _, _, .step i p, slots, X => rows_transport rows p (childSlots slots i) X + +theorem selectedRows_matrix (rows : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) (arrays : Arrays slots rows) : + matrixEquiv rows p slots + (EvaluationMatrix.ofRows (H (subtreeSlots p slots)) + (SelectedArrayReplacement.selectedRows rows p slots arrays)) = + EvaluationMatrix.ofRows (H (nodeSlots slots (upperNode p))) (arrays (upperNode p)) := by + rw [ofRows_transport, rowEquiv_selectedRows] + +theorem shift_transport (rows : Nat → Nat) : {n m : Nat} → + (p : Path branch n (m + 1)) → + (slots : Slots branch n → Fin t → MixedSupport.Slot) → + (X : NativeMatrix rows p slots) → + (a : BucketSampler.Direction (rows (m + 1))) → + (h : H (subtreeSlots p slots)) → + matrixEquiv rows p slots (EvaluationMatrix.shift (H (subtreeSlots p slots)) X a.val h) = + EvaluationMatrix.shift (H (nodeSlots slots (upperNode p))) (matrixEquiv rows p slots X) + (directionEquiv rows p a).val (scalarEquiv p slots h) + | _, _, .refl _, _, _, _, _ => rfl + | _, _, .step i p, slots, X, a, h => + shift_transport rows p (childSlots slots i) X a h + +theorem replace_matrix_transport (rows : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (a : BucketSampler.Direction (rows (m + 1))) + (S : Fin (rows (m + 1)) → H (subtreeSlots p slots)) + (fresh : H (subtreeSlots p slots)) : + matrixEquiv rows p slots + (EvaluationMatrix.ofRows (H (subtreeSlots p slots)) + (LowerDirectionFiber.replace a S fresh)) = + EvaluationMatrix.ofRows (H (nodeSlots slots (upperNode p))) + (LowerDirectionFiber.replace (directionEquiv rows p a) + (rowEquiv rows p slots S) (scalarEquiv p slots fresh)) := by + rw [ofRows_transport, rowEquiv_replace] + +section Laws + +open UniqueGamesTheorem.Foundations.Games + +variable (rows : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + +local instance nativeMatrixFintype : Fintype (NativeMatrix rows p slots) := + Fintype.ofEquiv (Fin (rows (m + 1)) → H (subtreeSlots p slots)) + (EvaluationMatrix.rowsEquiv (H (subtreeSlots p slots))).symm + +local instance nodeMatrixFintype : Fintype (NodeMatrix rows p slots) := + Fintype.ofEquiv (Fin (rows (Nodes.height (upperNode p))) → H (nodeSlots slots (upperNode p))) + (EvaluationMatrix.rowsEquiv (H (nodeSlots slots (upperNode p)))).symm + +theorem uniform_matrixEquiv : + (FiniteDistribution.uniform (NativeMatrix rows p slots)).pushforward + (matrixEquiv rows p slots) = + FiniteDistribution.uniform (NodeMatrix rows p slots) := by + have h := UniformConditioning.uniform_transport (matrixEquiv rows p slots).toEquiv + rw [FiniteDistribution.transport_eq_pushforward] at h + exact h + +theorem uniform_matrix_scalarEquiv : + ((FiniteDistribution.uniform (NativeMatrix rows p slots)).product + (FiniteDistribution.uniform (H (subtreeSlots p slots)))).pushforward + (fun z => (matrixEquiv rows p slots z.1, scalarEquiv p slots z.2)) = + (FiniteDistribution.uniform (NodeMatrix rows p slots)).product + (FiniteDistribution.uniform (H (nodeSlots slots (upperNode p)))) := by + have hscalar : + (FiniteDistribution.uniform (H (subtreeSlots p slots))).pushforward + (scalarEquiv p slots) = + FiniteDistribution.uniform (H (nodeSlots slots (upperNode p))) := by + have h := UniformConditioning.uniform_transport (scalarEquiv p slots).toEquiv + rw [FiniteDistribution.transport_eq_pushforward] at h + exact h + rw [FiniteDistribution.product_pushforward, uniform_matrixEquiv rows p slots, hscalar] + +theorem uniform_stepPair_transport (a : BucketSampler.Direction (rows (m + 1))) : + (((FiniteDistribution.uniform (NativeMatrix rows p slots)).product + (FiniteDistribution.uniform (H (subtreeSlots p slots)))).pushforward + (fun z => (z.1, EvaluationMatrix.shift (H (subtreeSlots p slots)) z.1 a.val z.2))).pushforward + (fun z => (matrixEquiv rows p slots z.1, matrixEquiv rows p slots z.2)) = + ((FiniteDistribution.uniform (NodeMatrix rows p slots)).product + (FiniteDistribution.uniform (H (nodeSlots slots (upperNode p))))).pushforward + (fun z => (z.1, EvaluationMatrix.shift (H (nodeSlots slots (upperNode p))) z.1 + (directionEquiv rows p a).val z.2)) := by + have h := congrArg + (fun μ : FiniteDistribution + (NodeMatrix rows p slots × H (nodeSlots slots (upperNode p))) => + μ.pushforward (fun z => + (z.1, EvaluationMatrix.shift (H (nodeSlots slots (upperNode p))) z.1 + (directionEquiv rows p a).val z.2))) + (uniform_matrix_scalarEquiv rows p slots) + rw [FiniteDistribution.pushforward_comp] at h + rw [FiniteDistribution.pushforward_comp] + simpa only [shift_transport] using h + +end Laws + +end +end PerfectCompleteness.LowerCutNodeMatrix + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Algebra/MatrixErasure.lean b/lean/OAI/Computability/PerfectCompleteness/Algebra/MatrixErasure.lean new file mode 100644 index 0000000000000000000000000000000000000000..d5f85e69d4f0921c30e2b23d289e7869d2812776 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Algebra/MatrixErasure.lean @@ -0,0 +1,140 @@ +import OAI.Computability.PerfectCompleteness.Foundations.PartialTableInverse + +namespace OAI + +section + +namespace PerfectCompleteness.MatrixErasure + +noncomputable section + +open scoped BigOperators Classical +open UniqueGamesTheorem.Fourier.MatrixCharacters +open PerfectCompleteness.PartialTableInverse + +variable {Ω Y : Type*} + +def erase (f : Ω → Option Y) (T : Ω → Prop) (X : Ω) : Option Y := + if T X then none else f X + +def uniformMass [Fintype Ω] (T : Ω → Prop) : ℝ := + 𝔼 X, if T X then (1 : ℝ) else 0 + +@[simp] theorem erase_eq_none_of (f : Ω → Option Y) (T : Ω → Prop) + {X : Ω} (hX : T X) : erase f T X = none := by + simp [erase, hX] + +theorem erase_eq_of_not (f : Ω → Option Y) (T : Ω → Prop) + {X : Ω} (hX : ¬T X) : erase f T X = f X := by + simp [erase, hX] + +theorem erase_eq_some_iff (f : Ω → Option Y) (T : Ω → Prop) (X : Ω) (y : Y) : + erase f T X = some y ↔ ¬T X ∧ f X = some y := by + by_cases hX : T X <;> simp [erase, hX] + +theorem indicator_erase_le (f : Ω → Option Y) (T : Ω → Prop) (y : Y) (X : Ω) : + indicator (erase f T) y X ≤ indicator f y X := by + by_cases hX : T X + · simp only [indicator, erase, ite_eq_left hX, reduceCtorEq, ite_false] + split_ifs <;> norm_num + · simp [indicator, erase, hX] + +theorem definedEquality_erase (f : Ω → Option Y) (T : Ω → Prop) (X X' : Ω) : + definedEquality (erase f T) X X' = + if T X ∨ T X' then 0 else definedEquality f X X' := by + by_cases hX : T X <;> by_cases hX' : T X' <;> + simp [definedEquality, erase, hX, hX'] + +theorem definedEquality_le_one (f : Ω → Option Y) (X X' : Ω) : + definedEquality f X X' ≤ 1 := by + unfold definedEquality + split_ifs <;> norm_num + +theorem definedEquality_nonneg (f : Ω → Option Y) (X X' : Ω) : + 0 ≤ definedEquality f X X' := by + unfold definedEquality + split_ifs <;> norm_num + +theorem definedEquality_erase_le (f : Ω → Option Y) (T : Ω → Prop) (X X' : Ω) : + definedEquality (erase f T) X X' ≤ definedEquality f X X' := by + rw [definedEquality_erase] + split_ifs + · exact definedEquality_nonneg f X X' + · exact le_rfl + +theorem definedEquality_le_erase_add (f : Ω → Option Y) (T : Ω → Prop) (X X' : Ω) : + definedEquality f X X' ≤ definedEquality (erase f T) X X' + + (if T X then (1 : ℝ) else 0) + (if T X' then (1 : ℝ) else 0) := by + have hbound := definedEquality_le_one f X X' + by_cases hX : T X <;> by_cases hX' : T X' <;> + simp [definedEquality_erase, hX, hX'] <;> linarith + +theorem uniformMass_nonneg [Fintype Ω] (T : Ω → Prop) : 0 ≤ uniformMass T := by + apply Finset.expect_nonneg + intro X _ + split_ifs <;> norm_num + +theorem expect_add_right [AddGroup Ω] [Fintype Ω] (g : Ω → ℝ) (v : Ω) : + (𝔼 X, g (X + v)) = (𝔼 X, g X) := + Fintype.expect_equiv (Equiv.addRight v) _ _ (fun _ => rfl) + +variable {E F : Type*} + [AddCommGroup E] [Module F2 E] [AddCommGroup F] [Module F2 F] + [Fintype F] [Fintype (E →ₗ[F2] F2)] [Fintype (E →ₗ[F2] F)] + +omit [Fintype F] in +theorem step_second_marginal (g : (E →ₗ[F2] F) → ℝ) (a : F) : + (𝔼 X, 𝔼 h : E →ₗ[F2] F2, g (X + h.smulRight a)) = (𝔼 X, g X) := by + rw [Finset.expect_comm] + simp_rw [expect_add_right] + exact Fintype.expect_const _ + +theorem nonzero_second_marginal [Nontrivial F] (g : (E →ₗ[F2] F) → ℝ) : + (𝔼 a : {a : F // a ≠ 0}, + 𝔼 X, 𝔼 h : E →ₗ[F2] F2, g (X + h.smulRight a.val)) = (𝔼 X, g X) := by + obtain ⟨a, ha⟩ := exists_ne (0 : F) + let : Nonempty {a : F // a ≠ 0} := ⟨⟨a, ha⟩⟩ + simp_rw [step_second_marginal] + exact Fintype.expect_const _ + +omit [Fintype F] in +theorem stepAgreement_erase_bound (f : (E →ₗ[F2] F) → Option Y) + (T : (E →ₗ[F2] F) → Prop) (a : F) : + stepAgreement f a ≤ stepAgreement (erase f T) a + 2 * uniformMass T := by + have havg : stepAgreement f a ≤ + 𝔼 X, 𝔼 h : E →ₗ[F2] F2, + (definedEquality (erase f T) X (X + h.smulRight a) + + (if T X then (1 : ℝ) else 0) + + (if T (X + h.smulRight a) then (1 : ℝ) else 0)) := by + apply Finset.expect_le_expect + intro X _ + apply Finset.expect_le_expect + intro h _ + exact definedEquality_le_erase_add f T X (X + h.smulRight a) + simp_rw [Finset.expect_add_distrib, Fintype.expect_const] at havg + rw [step_second_marginal (fun X => if T X then (1 : ℝ) else 0) a] at havg + change stepAgreement f a ≤ + stepAgreement (erase f T) a + uniformMass T + uniformMass T at havg + linarith + +theorem nonzeroAgreement_erase [Nontrivial F] (f : (E →ₗ[F2] F) → Option Y) + (T : (E →ₗ[F2] F) → Prop) : + nonzeroAgreement f - 2 * uniformMass T ≤ nonzeroAgreement (erase f T) := by + obtain ⟨a, ha⟩ := exists_ne (0 : F) + let : Nonempty {a : F // a ≠ 0} := ⟨⟨a, ha⟩⟩ + have havg : nonzeroAgreement f ≤ + 𝔼 a : {a : F // a ≠ 0}, (stepAgreement (erase f T) a.val + 2 * uniformMass T) := by + unfold nonzeroAgreement + apply Finset.expect_le_expect + intro a _ + exact stepAgreement_erase_bound f T a.val + simp only [Finset.expect_add_distrib, Fintype.expect_const] at havg + change nonzeroAgreement f ≤ nonzeroAgreement (erase f T) + 2 * uniformMass T at havg + linarith + +end +end PerfectCompleteness.MatrixErasure + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Algebra/MatrixInverse.lean b/lean/OAI/Computability/PerfectCompleteness/Algebra/MatrixInverse.lean new file mode 100644 index 0000000000000000000000000000000000000000..0fb41ad806786727f98f6f80a789df61d68333ff --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Algebra/MatrixInverse.lean @@ -0,0 +1,120 @@ +import OAI.Computability.PerfectCompleteness.Foundations.GlobalityLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.MatrixInverse + +noncomputable section + +open scoped BigOperators Classical +open UniqueGamesTheorem.Fourier.MatrixCharacters UniqueGamesTheorem.Fourier.MatrixFourier +open UniqueGamesTheorem.Fourier.MatrixNoise UniqueGamesTheorem.Fourier.MatrixRestrictions +open UniqueGamesTheorem.Fourier.MatrixLevelBridge +open UniqueGamesTheorem.Appendix.LevelInequality UniqueGamesTheorem.Appendix.RankLevelFilter + +variable {E F : Type*} + [AddCommGroup E] [Module F2 E] [AddCommGroup F] [Module F2 F] + [FiniteDimensional F2 E] [FiniteDimensional F2 F] + [Finite E] [Fintype F] [Fintype (E →ₗ[F2] F2)] + [Fintype (E →ₗ[F2] F)] [Fintype (F →ₗ[F2] E)] + +def noiseEnergy (f : (E →ₗ[F2] F) → ℝ) : ℝ := + 𝔼 X, f X * linearRealNoiseOperator (fun _ : F => (Fintype.card F : ℝ)⁻¹) f X + +omit [Finite E] in +theorem noiseEnergy_eq (f : (E →ₗ[F2] F) → ℝ) : + noiseEnergy f = ∑ S : F →ₗ[F2] E, node (frequencyRank S) * linearCoeff f S ^ 2 := by + unfold noiseEnergy + rw [linearRealNoiseOperator_energy] + apply Finset.sum_congr rfl + intro S _ + rw [linearNoiseEigenvalue_uniform, node_eq_inv_pow] + rfl + +omit [Finite E] in +theorem noiseEnergy_le_cutoff (r : Nat) (f : (E →ₗ[F2] F) → ℝ) : + noiseEnergy f ≤ rankCutoffEnergy r f + node (r + 1) * (𝔼 X, f X ^ 2) := by + rw [noiseEnergy_eq] + calc + _ ≤ ∑ S : F →ₗ[F2] E, + ((if frequencyRank S ≤ r then linearCoeff f S ^ 2 else 0) + + node (r + 1) * linearCoeff f S ^ 2) := by + apply Finset.sum_le_sum + intro S _ + by_cases h : frequencyRank S ≤ r + · rw [ite_eq_left h] + have h₁ := mul_le_mul_of_nonneg_right (node_le_one (frequencyRank S)) + (sq_nonneg (linearCoeff f S)) + have h₂ := mul_nonneg (node_pos (r + 1)).le (sq_nonneg (linearCoeff f S)) + linarith + · rw [ite_eq_right h, zero_add] + exact mul_le_mul_of_nonneg_right + (node_antitone (Nat.succ_le_of_lt (Nat.lt_of_not_ge h))) (sq_nonneg _) + _ = rankCutoffEnergy r f + node (r + 1) * (𝔼 X, f X ^ 2) := by + rw [Finset.sum_add_distrib, ← Finset.mul_sum, linear_parseval] + simp only [rankCutoffEnergy, Finset.sum_filter] + +theorem noiseEnergy_le_of_global (r : Nat) (ρ : ℝ) (hρ : 0 < ρ) (hρ1 : ρ < 1) + (f : (E →ₗ[F2] F) → ℝ) (hf : IsBoolean f) + (hg : IsRestrictionGlobal f r ρ) : + noiseEnergy f ≤ (levelCutoffConstant r ρ + node (r + 1)) * (𝔼 X, f X ^ 2) := by + have hcut := rankCutoffEnergy_le_of_theorem23 + (UniqueGamesTheorem.Appendix.LevelTheorem.theorem23 (E := E) (F := F)) f r ρ hρ hρ1 hf hg + calc + noiseEnergy f ≤ rankCutoffEnergy r f + node (r + 1) * (𝔼 X, f X ^ 2) := + noiseEnergy_le_cutoff r f + _ ≤ levelCutoffConstant r ρ * (𝔼 X, f X ^ 2) + + node (r + 1) * (𝔼 X, f X ^ 2) := add_le_add hcut (le_refl _) + _ = _ := (add_mul _ _ _).symm + +theorem exists_dense_restriction (r : Nat) (ρ η : ℝ) (hρ : 0 < ρ) (hρ1 : ρ < 1) + (hconstants : levelCutoffConstant r ρ + node (r + 1) < η) + (f : (E →ₗ[F2] F) → ℝ) (hf : IsBoolean f) + (hpositive : 0 < 𝔼 X, f X ^ 2) + (hretention : η * (𝔼 X, f X ^ 2) ≤ noiseEnergy f) : + ∃ (W : Submodule F2 E) (C' : Submodule F2 F) (T : E →ₗ[F2] F), + order W C' ≤ r ∧ ρ < (𝔼 N, restrict f W C' T N) := by + by_contra hnone + have hg : IsRestrictionGlobal f r ρ := by + apply (boolean_global_iff_density f hf r ρ).mpr + intro W C' T horder + apply le_of_not_gt + intro hdense + exact hnone ⟨W, C', T, horder, hdense⟩ + have hbound := noiseEnergy_le_of_global r ρ hρ hρ1 f hf hg + have hstrict := mul_lt_mul_of_pos_right hconstants hpositive + exact (not_lt_of_ge (hretention.trans hbound)) hstrict + +theorem exists_dense_restriction_of_family {Y : Type*} [Fintype Y] + (r : Nat) (ρ η : ℝ) (hρ : 0 < ρ) (hρ1 : ρ < 1) + (hconstants : levelCutoffConstant r ρ + node (r + 1) < η) + (f : Y → (E →ₗ[F2] F) → ℝ) (hf : ∀ y, IsBoolean (f y)) + (hmass : (∑ y, 𝔼 X, f y X ^ 2) ≤ 1) + (hretention : η ≤ ∑ y, noiseEnergy (f y)) : + ∃ (y : Y) (W : Submodule F2 E) (C' : Submodule F2 F) (T : E →ₗ[F2] F), + order W C' ≤ r ∧ ρ < (𝔼 N, restrict (f y) W C' T N) := by + by_contra hnone + have hg (y : Y) : IsRestrictionGlobal (f y) r ρ := by + apply (boolean_global_iff_density (f y) (hf y) r ρ).mpr + intro W C' T horder + apply le_of_not_gt + intro hdense + exact hnone ⟨y, W, C', T, horder, hdense⟩ + have hbound : (∑ y, noiseEnergy (f y)) ≤ + (levelCutoffConstant r ρ + node (r + 1)) * (∑ y, 𝔼 X, f y X ^ 2) := by + rw [Finset.mul_sum] + exact Finset.sum_le_sum fun y _ => noiseEnergy_le_of_global r ρ hρ hρ1 (f y) (hf y) (hg y) + have hnonneg : 0 ≤ levelCutoffConstant r ρ + node (r + 1) := + add_nonneg (levelCutoffConstant_nonneg r ρ hρ.le) (node_pos _).le + have hbound' := hbound.trans (mul_le_mul_of_nonneg_left hmass hnonneg) + simp only [mul_one] at hbound' + exact (not_lt_of_ge (hretention.trans hbound')) hconstants + +end +end PerfectCompleteness.MatrixInverse + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Algebra/MatrixInverseConstantsLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Algebra/MatrixInverseConstantsLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..a7635ea6907f0a782db01c2e02d76caaad2bb74a --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Algebra/MatrixInverseConstantsLemmas.lean @@ -0,0 +1,85 @@ +import Mathlib.Algebra.Order.Archimedean.Basic +import OAI.Computability.PerfectCompleteness.Foundations.GlobalityLemmas +import OAI.Computability.PerfectCompleteness.Foundations.LinearEvaluationLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.MatrixInverseConstants + +open UniqueGamesTheorem.Appendix UniqueGamesTheorem.Fourier UniqueGamesTheorem.Integration + +theorem exists_cutoff_density {η : ℝ} (hη : 0 < η) : + ∃ r : ℕ, 1 ≤ r ∧ ∃ ρ : ℝ, 0 < ρ ∧ ρ < 1 ∧ + MatrixLevelBridge.levelCutoffConstant r ρ + + RankLevelFilter.node (r + 1) < η := by + obtain ⟨q, hq, hqη⟩ := exists_pos_rat_lt hη + obtain ⟨n, hn⟩ := exists_pow_lt_of_lt_one + (show 0 < η / 2 by positivity) + (by norm_num : (1 / 2 : ℝ) < 1) + let r : ℕ := n + 1 + have hn' : RankLevelFilter.node n < η / 2 := by + simpa only [RankLevelFilter.node_eq_inv_pow, one_div, inv_pow] using hn + have htail : RankLevelFilter.node (r + 1) < η / 2 := + (RankLevelFilter.node_antitone (show n ≤ r + 1 by dsimp [r]; omega)).trans_lt hn' + obtain ⟨s, hs, hcut⟩ := CutoffBudget.exists_symbol_dimension_cutoff r hq + have hρ := CutoffBudget.rho_real_bounds hs + refine ⟨r, by dsimp [r]; omega, (FinalParameters.rho r s : ℝ), hρ.1, hρ.2, ?_⟩ + have hcut' : + MatrixLevelBridge.levelCutoffConstant r (FinalParameters.rho r s : ℝ) ≤ + (q : ℝ) / 8 := by + simpa only [MatrixLevelBridge.levelCutoffConstant, CutoffBudget.cutoffSum] using hcut + linarith + +end PerfectCompleteness.MatrixInverseConstants + +end + +section + +namespace PerfectCompleteness.LowerRankParameters + +open UniqueGamesTheorem.Appendix UniqueGamesTheorem.Fourier + +theorem power_ratio_le {a b k : Nat} (h : a + k ≤ b) : + (2 : ℝ) ^ a / (2 : ℝ) ^ b ≤ (1 / 2 : ℝ) ^ k := by + rw [div_pow, one_pow] + apply (div_le_div_iff₀ (by positivity) (by positivity)).2 + simpa only [one_mul, ← pow_add] using + (pow_le_pow_right₀ (by norm_num : (1 : ℝ) ≤ 2) h) + +theorem exists_cross_parameters (r : Nat) {ρ : ℝ} (hρ : 0 < ρ) : + ∃ m s : Nat, 0 < m ∧ 1 ≤ s ∧ ∀ s' : Nat, s ≤ s' → + (2 : ℝ) ^ m / (2 : ℝ) ^ (s' - 2 * r) + + (2 : ℝ) ^ (2 * m) / (2 : ℝ) ^ (m * m) < ρ := by + obtain ⟨k, hk⟩ := exists_pow_lt_of_lt_one + (show 0 < ρ / 2 by positivity) (by norm_num : (1 / 2 : ℝ) < 1) + let m := k + 3 + let s := 2 * r + m + k + 1 + refine ⟨m, s, by dsimp [m]; omega, by dsimp [s]; omega, ?_⟩ + intro s' hs' + have hfirst : m + k ≤ s' - 2 * r := by dsimp [s] at hs'; omega + have hsecond : 2 * m + k ≤ m * m := by dsimp [m]; nlinarith + have h₁ := power_ratio_le hfirst + have h₂ := power_ratio_le hsecond + linarith + +theorem exists_lower_parameters {η : ℝ} (hη : 0 < η) : + ∃ r m s rowMinimum : Nat, 1 ≤ r ∧ 0 < m ∧ 1 ≤ s ∧ + ∃ ρ : ℝ, 0 < ρ ∧ ρ < 1 ∧ + MatrixLevelBridge.levelCutoffConstant r ρ + RankLevelFilter.node (r + 1) < η ∧ + (∀ ℓ, rowMinimum ≤ ℓ → 2 * m + r ≤ ℓ) ∧ + ∀ s', s ≤ s' → + (2 : ℝ) ^ m / (2 : ℝ) ^ (s' - 2 * r) + + (2 : ℝ) ^ (2 * m) / (2 : ℝ) ^ (m * m) < ρ := by + obtain ⟨r, hr, ρ, hρ, hρ', hcut⟩ := MatrixInverseConstants.exists_cutoff_density hη + obtain ⟨m, s, hm, hs, herror⟩ := exists_cross_parameters r hρ + exact ⟨r, m, s, 2 * m + r, hr, hm, hs, ρ, hρ, hρ', hcut, + fun _ h => h, herror⟩ + +end PerfectCompleteness.LowerRankParameters + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Algebra/MatrixRowQuotientLaw.lean b/lean/OAI/Computability/PerfectCompleteness/Algebra/MatrixRowQuotientLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..e7ced4b623096ac76791618dde9f6d43ff768df3 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Algebra/MatrixRowQuotientLaw.lean @@ -0,0 +1,139 @@ +import Mathlib.Algebra.BigOperators.Expect +import Mathlib.LinearAlgebra.Prod +import OAI.Computability.PerfectCompleteness.Algebra.BilinearGramCompressionLemmas +import OAI.Computability.PerfectCompleteness.Algebra.UniformLinearImage +import OAI.Computability.UniqueGames.Games.FinishBoundsLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.MatrixRowQuotientLaw + +noncomputable section + +open scoped BigOperators +open UniqueGamesTheorem.Foundations.Games +open MatrixRowQuotient + +variable {𝕜 H K : Type*} [Field 𝕜] + [AddCommGroup H] [Module 𝕜 H] [AddCommGroup K] [Module 𝕜 K] + +def projectMatrixLinear (W : Submodule 𝕜 H) : + (Module.Dual 𝕜 H →ₗ[𝕜] K) →ₗ[𝕜] (Module.Dual 𝕜 (H ⧸ W) →ₗ[𝕜] K) where + toFun := projectMatrix W + map_add' X Y := by + apply LinearMap.ext + intro q + rfl + map_smul' a X := by + apply LinearMap.ext + intro q + rfl + +@[simp] theorem projectMatrixLinear_apply (W : Submodule 𝕜 H) + (X : Module.Dual 𝕜 H →ₗ[𝕜] K) : + projectMatrixLinear W X = projectMatrix W X := rfl + +def jointProjection (W : Submodule 𝕜 H) : + ((Module.Dual 𝕜 H →ₗ[𝕜] K) × H) →ₗ[𝕜] + ((Module.Dual 𝕜 (H ⧸ W) →ₗ[𝕜] K) × (H ⧸ W)) := + (projectMatrixLinear W).prodMap W.mkQ + +@[simp] theorem jointProjection_apply (W : Submodule 𝕜 H) + (p : (Module.Dual 𝕜 H →ₗ[𝕜] K) × H) : + jointProjection W p = (projectMatrix W p.1, W.mkQ p.2) := rfl + +theorem jointProjection_surjective (W : Submodule 𝕜 H) : + Function.Surjective (jointProjection (K := K) W) := by + rintro ⟨X, h⟩ + obtain ⟨Y, hY⟩ := projectMatrix_surjective W X + obtain ⟨g, hg⟩ := W.mkQ_surjective h + exact ⟨(Y, g), Prod.ext hY hg⟩ + +theorem uniform_product {A B : Type*} [Fintype A] [Fintype B] + [Nonempty A] [Nonempty B] : + (FiniteDistribution.uniform A).product (FiniteDistribution.uniform B) = + FiniteDistribution.uniform (A × B) := by + apply FiniteDistribution.eq_of_weight_eq + intro p + change (1 / (Fintype.card A : ℝ)) * (1 / (Fintype.card B : ℝ)) = + 1 / (Fintype.card (A × B) : ℝ) + simp only [Fintype.card_prod, Nat.cast_mul, one_div, mul_inv] + +variable (W : Submodule 𝕜 H) + [Fintype H] [Fintype (H ⧸ W)] + [Fintype (Module.Dual 𝕜 H →ₗ[𝕜] K)] + [Fintype (Module.Dual 𝕜 (H ⧸ W) →ₗ[𝕜] K)] + +theorem uniform_jointProjection : + (FiniteDistribution.uniform ((Module.Dual 𝕜 H →ₗ[𝕜] K) × H)).pushforward + (jointProjection W) = + FiniteDistribution.uniform ((Module.Dual 𝕜 (H ⧸ W) →ₗ[𝕜] K) × (H ⧸ W)) := + UniformLinearImage.uniform_pushforward_linearMap + (jointProjection W) (jointProjection_surjective W) + +theorem independent_uniform_jointProjection : + ((FiniteDistribution.uniform (Module.Dual 𝕜 H →ₗ[𝕜] K)).product + (FiniteDistribution.uniform H)).pushforward (jointProjection W) = + (FiniteDistribution.uniform (Module.Dual 𝕜 (H ⧸ W) →ₗ[𝕜] K)).product + (FiniteDistribution.uniform (H ⧸ W)) := by + rw [uniform_product, uniform_product] + exact uniform_jointProjection W + +private theorem expect_prod {A B : Type*} [Fintype A] [Fintype B] + (f : A × B → ℝ) : + (𝔼 p : A × B, f p) = 𝔼 a : A, 𝔼 b : B, f (a, b) := by + simpa only [Finset.univ_product_univ] using + Finset.expect_product (Finset.univ : Finset A) (Finset.univ : Finset B) f + +theorem expect_project_matrix_increment + (f : (Module.Dual 𝕜 (H ⧸ W) →ₗ[𝕜] K) → (H ⧸ W) → ℝ) : + (𝔼 X : Module.Dual 𝕜 H →ₗ[𝕜] K, 𝔼 h : H, + f (projectMatrix W X) (W.mkQ h)) = + 𝔼 X : Module.Dual 𝕜 (H ⧸ W) →ₗ[𝕜] K, 𝔼 h : H ⧸ W, f X h := by + have he := congrArg + (fun μ : FiniteDistribution ((Module.Dual 𝕜 (H ⧸ W) →ₗ[𝕜] K) × (H ⧸ W)) => + μ.expectation (fun p => f p.1 p.2)) (uniform_jointProjection W) + rw [FiniteDistribution.expectation_pushforward, + FiniteDistribution.expectation_uniform, FiniteDistribution.expectation_uniform] at he + have he' : + (𝔼 p : (Module.Dual 𝕜 H →ₗ[𝕜] K) × H, + f (projectMatrix W p.1) (W.mkQ p.2)) = + 𝔼 p : (Module.Dual 𝕜 (H ⧸ W) →ₗ[𝕜] K) × (H ⧸ W), f p.1 p.2 := by + simpa only [Fintype.expect_eq_sum_div_card, jointProjection_apply] using he + simpa only [expect_prod] using he' + +theorem rankOne_pair_law (a : K) : + ((FiniteDistribution.uniform (Module.Dual 𝕜 H →ₗ[𝕜] K)).product + (FiniteDistribution.uniform H)).pushforward + (fun p => (projectMatrix W p.1, + projectMatrix W (p.1 + (Module.Dual.eval 𝕜 H p.2).smulRight a))) = + ((FiniteDistribution.uniform (Module.Dual 𝕜 (H ⧸ W) →ₗ[𝕜] K)).product + (FiniteDistribution.uniform (H ⧸ W))).pushforward + (fun p => (p.1, p.1 + (Module.Dual.eval 𝕜 (H ⧸ W) p.2).smulRight a)) := by + have he := congrArg + (fun μ : FiniteDistribution ((Module.Dual 𝕜 (H ⧸ W) →ₗ[𝕜] K) × (H ⧸ W)) => + μ.pushforward (fun p => + (p.1, p.1 + (Module.Dual.eval 𝕜 (H ⧸ W) p.2).smulRight a))) + (independent_uniform_jointProjection W) + rw [FiniteDistribution.pushforward_comp] at he + simpa only [jointProjection_apply, project_rankOne] using he + +theorem expect_project_rankOne_pair (a : K) + (f : (Module.Dual 𝕜 (H ⧸ W) →ₗ[𝕜] K) → + (Module.Dual 𝕜 (H ⧸ W) →ₗ[𝕜] K) → ℝ) : + (𝔼 X : Module.Dual 𝕜 H →ₗ[𝕜] K, 𝔼 h : H, + f (projectMatrix W X) + (projectMatrix W (X + (Module.Dual.eval 𝕜 H h).smulRight a))) = + 𝔼 X : Module.Dual 𝕜 (H ⧸ W) →ₗ[𝕜] K, 𝔼 h : H ⧸ W, + f X (X + (Module.Dual.eval 𝕜 (H ⧸ W) h).smulRight a) := by + simpa only [project_rankOne] using expect_project_matrix_increment W + (fun X h => f X (X + (Module.Dual.eval 𝕜 (H ⧸ W) h).smulRight a)) + +end +end PerfectCompleteness.MatrixRowQuotientLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Algebra/MatrixTriangularFoldingLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Algebra/MatrixTriangularFoldingLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..4f7ac3986d48003cd122808d5f660680f033517d --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Algebra/MatrixTriangularFoldingLemmas.lean @@ -0,0 +1,261 @@ +import Mathlib.Tactic.Abel +import OAI.Computability.PerfectCompleteness.Algebra.BilinearGramCompressionLemmas +import OAI.Computability.PerfectCompleteness.Algebra.CanonicalMatrixTable +import OAI.Computability.PerfectCompleteness.Construction.FactoredFunctionsLemmas +import OAI.Computability.PerfectCompleteness.Foundations.TriangularFolding + +namespace OAI + + +namespace PerfectCompleteness.MatrixTriangularFolding + +noncomputable section + +open scoped Classical +open ClauseSupport MixedSupport CanonicalKeys +open DirectionQuotient (F2) + +variable {n : Nat} {K Z : Type*} [AddCommGroup K] [Module F2 K] + (slots : Fin n → Slot) (H : Submodule F2 (Assignment slots → F2)) + (other : Assignment slots → Z) (σ : KeyStrategy.Strategy n) + +theorem query_add (X Δ : CanonicalMatrixTable.Matrix (K := K) slots H) (d : Z → K) + (hΔ : ∀ x, EvaluationMatrix.evaluate H Δ x = d (other x)) : + CanonicalMatrixTable.query slots H other (X + Δ) = + TriangularFolding.translate d ∘ CanonicalMatrixTable.query slots H other X := by + funext x + apply Prod.ext + · change X (EvaluationMatrix.evaluation H x) + Δ (EvaluationMatrix.evaluation H x) = + X (EvaluationMatrix.evaluation H x) + d (other x) + rw [← hΔ x] + rfl + · rfl + +theorem response_add (X Δ : CanonicalMatrixTable.Matrix (K := K) slots H) (d : Z → K) + (hΔ : ∀ x, EvaluationMatrix.evaluate H Δ x = d (other x)) : + CanonicalMatrixTable.response slots H other σ (X + Δ) = + TriangularFolding.translate d (CanonicalMatrixTable.response slots H other σ X) := by + unfold CanonicalMatrixTable.response + rw [query_add slots H other X Δ d hΔ] + exact KeyStrategy.response_postcomp_injective σ .left slots + (CanonicalMatrixTable.query slots H other X) (TriangularFolding.translate d) + (TriangularFolding.translate d).injective + +theorem response_add_side (X Δ : CanonicalMatrixTable.Matrix (K := K) slots H) (d : Z → K) + (hΔ : ∀ x, EvaluationMatrix.evaluate H Δ x = d (other x)) : + (CanonicalMatrixTable.response slots H other σ (X + Δ)).2 = + (CanonicalMatrixTable.response slots H other σ X).2 := by + rw [response_add slots H other σ X Δ d hΔ] + rfl + +theorem response_add_selected (X Δ : CanonicalMatrixTable.Matrix (K := K) slots H) (d : Z → K) + (hΔ : ∀ x, EvaluationMatrix.evaluate H Δ x = d (other x)) : + (CanonicalMatrixTable.response slots H other σ (X + Δ)).1 = + (CanonicalMatrixTable.response slots H other σ X).1 + + d (CanonicalMatrixTable.response slots H other σ X).2 := by + rw [response_add slots H other σ X Δ d hΔ] + rfl + +def sideFunctional (B : Submodule F2 (Assignment slots → F2)) + (hB : B ≤ FactoredFunctions.factoringSpace other) (z : Z) : Module.Dual F2 B := + if hz : z ∈ Set.range other then FactoredFunctions.evaluation hB ⟨z, hz⟩ else 0 + +theorem sideFunctional_at_image (B : Submodule F2 (Assignment slots → F2)) + (hB : B ≤ FactoredFunctions.factoringSpace other) (x : Assignment slots) : + sideFunctional slots other B hB (other x) = EvaluationMatrix.evaluation B x := by + have hx : other x ∈ Set.range other := ⟨x, rfl⟩ + rw [sideFunctional, dite_eq_left hx] + ext b + exact FactoredFunctions.evaluation_apply_of_eq hB ⟨other x, hx⟩ x rfl b + +def liftCorrection (B : Submodule F2 (Assignment slots → F2)) (hBH : B ≤ H) + (Δ : Module.Dual F2 B →ₗ[F2] K) : CanonicalMatrixTable.Matrix (K := K) slots H := + Δ.comp (Submodule.inclusion hBH).dualMap + +def correction (B : Submodule F2 (Assignment slots → F2)) + (hB : B ≤ FactoredFunctions.factoringSpace other) + (Δ : Module.Dual F2 B →ₗ[F2] K) (z : Z) : K := + Δ (sideFunctional slots other B hB z) + +theorem evaluate_liftCorrection (B : Submodule F2 (Assignment slots → F2)) + (hBH : B ≤ H) (hB : B ≤ FactoredFunctions.factoringSpace other) + (Δ : Module.Dual F2 B →ₗ[F2] K) (x : Assignment slots) : + EvaluationMatrix.evaluate H (liftCorrection slots H B hBH Δ) x = + correction slots other B hB Δ (other x) := by + unfold correction + rw [sideFunctional_at_image] + rfl + +theorem response_add_correction (B : Submodule F2 (Assignment slots → F2)) + (hBH : B ≤ H) (hB : B ≤ FactoredFunctions.factoringSpace other) + (X : CanonicalMatrixTable.Matrix (K := K) slots H) (Δ : Module.Dual F2 B →ₗ[F2] K) : + CanonicalMatrixTable.response slots H other σ (X + liftCorrection slots H B hBH Δ) = + TriangularFolding.translate (correction slots other B hB Δ) + (CanonicalMatrixTable.response slots H other σ X) := + response_add slots H other σ X _ _ + (evaluate_liftCorrection slots H other B hBH hB Δ) + +theorem correction_rankOne (B : Submodule F2 (Assignment slots → F2)) + (hB : B ≤ FactoredFunctions.factoringSpace other) (a : K) (b : B) (z : Z) : + correction slots other B hB ((Module.Dual.eval F2 B b).smulRight a) z = + sideFunctional slots other B hB z b • a := rfl + +end +end PerfectCompleteness.MatrixTriangularFolding + + + +namespace PerfectCompleteness.RepresentativeMatrixTable + +noncomputable section + +open scoped Classical +open ClauseSupport MixedSupport CanonicalKeys +open DirectionQuotient (F2) + +variable {n : Nat} {K Z : Type*} [AddCommGroup K] [Module F2 K] + (slots : Fin n → Slot) (H : Submodule F2 (Assignment slots → F2)) + (other : Assignment slots → Z) (σ : KeyStrategy.Strategy n) + (W : Submodule F2 H) (s : (H ⧸ W) →ₗ[F2] H) + (hs : W.mkQ.comp s = LinearMap.id) + +def Determined : Prop := ∀ b : W, ∀ x y : Assignment slots, + other x = other y → b.val.val x = b.val.val y + +theorem determined_comap (B : Submodule F2 (Assignment slots → F2)) + (hB : B ≤ FactoredFunctions.factoringSpace other) : + Determined slots H other (B.comap H.subtype) := by + intro b x y h + exact hB b.property x y h + +def sideEvaluation (z : Z) : Module.Dual F2 W := + if hz : z ∈ Set.range other then + (EvaluationMatrix.evaluation H (Classical.choose hz)).comp W.subtype + else 0 + +theorem sideEvaluation_at_image (hW : Determined slots H other W) + (x : Assignment slots) : + sideEvaluation slots H other W (other x) = + (EvaluationMatrix.evaluation H x).comp W.subtype := by + have hx : other x ∈ Set.range other := ⟨x, rfl⟩ + rw [sideEvaluation, dite_eq_left hx] + ext b + exact hW b _ x (Classical.choose_spec hx) + +def correctionFunctional (z : Z) : Module.Dual F2 H := + (sideEvaluation slots H other W z).comp (MatrixRowQuotient.residualVector W s hs) + +def representative (X : CanonicalMatrixTable.Matrix (K := K) slots H) : + CanonicalMatrixTable.Matrix (K := K) slots H := + MatrixRowQuotient.liftMatrix W s (MatrixRowQuotient.projectMatrix W X) + +def response (X : CanonicalMatrixTable.Matrix (K := K) slots H) : K × Z := + CanonicalMatrixTable.response slots H other σ (representative slots H W s X) + +def partialTable (useful : (Module.Dual F2 (H ⧸ W) →ₗ[F2] K) → Prop) + (X : Module.Dual F2 (H ⧸ W) →ₗ[F2] K) : Option (K × Z) := + if useful X then + some (CanonicalMatrixTable.response slots H other σ (MatrixRowQuotient.liftMatrix W s X)) + else none + +theorem raw_response (hW : Determined slots H other W) + (X : CanonicalMatrixTable.Matrix (K := K) slots H) : + CanonicalMatrixTable.response slots H other σ X = + TriangularFolding.translate (fun z => X (correctionFunctional slots H other W s hs z)) + (response slots H other σ W s X) := by + let Δ := (X.comp (MatrixRowQuotient.residualVector W s hs).dualMap).comp W.subtype.dualMap + have hΔ : ∀ x, EvaluationMatrix.evaluate H Δ x = + X (correctionFunctional slots H other W s hs (other x)) := by + intro x + unfold correctionFunctional + rw [sideEvaluation_at_image slots H other W hW x] + rfl + have hsum : representative slots H W s X + Δ = X := by + have he := MatrixRowQuotient.residual_factorization W s hs X + change X - representative slots H W s X = Δ at he + rw [← he] + abel + have hr := MatrixTriangularFolding.response_add slots H other σ + (representative slots H W s X) Δ + (fun z => X (correctionFunctional slots H other W s hs z)) hΔ + rw [hsum] at hr + exact hr + +def normalizeOutput (X : CanonicalMatrixTable.Matrix (K := K) slots H) (y : K × Z) : K × Z := + (y.1 - X (correctionFunctional slots H other W s hs y.2), y.2) + +theorem response_eq_normalize (hW : Determined slots H other W) + (X : CanonicalMatrixTable.Matrix (K := K) slots H) : + response slots H other σ W s X = + normalizeOutput slots H other W s hs X (CanonicalMatrixTable.response slots H other σ X) := by + rw [raw_response slots H other σ W s hs hW X] + apply Prod.ext + · change (response slots H other σ W s X).1 = + (response slots H other σ W s X).1 + + X (correctionFunctional slots H other W s hs (response slots H other σ W s X).2) - + X (correctionFunctional slots H other W s hs (response slots H other σ W s X).2) + abel + · rfl + +def normalizeQuotient (a : K) (X : CanonicalMatrixTable.Matrix (K := K) slots H) + (y : DirectionQuotient.Space a × Z) : DirectionQuotient.Space a × Z := + (y.1 - DirectionQuotient.proj a + (X (correctionFunctional slots H other W s hs y.2)), y.2) + +theorem project_normalize_shift (a : K) (X : CanonicalMatrixTable.Matrix (K := K) slots H) + (h : H) (y : K × Z) : + DirectionQuotient.projectWithSide a + (normalizeOutput slots H other W s hs (EvaluationMatrix.shift H X a h) y) = + normalizeQuotient slots H other W s hs a X (DirectionQuotient.projectWithSide a y) := by + apply Prod.ext + · change DirectionQuotient.proj a + (y.1 - (X (correctionFunctional slots H other W s hs y.2) + + correctionFunctional slots H other W s hs y.2 h • a)) = + DirectionQuotient.proj a y.1 - DirectionQuotient.proj a + (X (correctionFunctional slots H other W s hs y.2)) + have ha : DirectionQuotient.proj a a = 0 := + (DirectionQuotient.proj_eq_zero_iff a a).mpr (Or.inr rfl) + simp only [map_sub, map_add, map_smul, ha, smul_zero, add_zero] + · rfl + +theorem accepted_response_in_fiber (hW : Determined slots H other W) + (a : K) (X : CanonicalMatrixTable.Matrix (K := K) slots H) (h : H) + (hacc : CanonicalMatrixTable.Accepts slots H other σ a (EvaluationMatrix.shift H X a h)) : + DirectionQuotient.projectWithSide a + (response slots H other σ W s (EvaluationMatrix.shift H X a h)) = + normalizeQuotient slots H other W s hs a X + (KeyStrategy.response σ .right slots (CanonicalMatrixTable.rightQuery slots H other a X)) := by + rw [response_eq_normalize slots H other σ W s hs hW] + rw [project_normalize_shift] + rw [CanonicalMatrixTable.accepted_response_in_fiber slots H other σ a X h hacc] + +include hs in +theorem card_accepted_responses_le_two [Finite K] [Finite Z] + (hW : Determined slots H other W) (a : K) (ha : a ≠ 0) + (X : CanonicalMatrixTable.Matrix (K := K) slots H) : + Nat.card {y : K × Z // ∃ h : H, + CanonicalMatrixTable.Accepts slots H other σ a (EvaluationMatrix.shift H X a h) ∧ + response slots H other σ W s (EvaluationMatrix.shift H X a h) = y} ≤ 2 := by + let z := normalizeQuotient slots H other W s hs a X + (KeyStrategy.response σ .right slots (CanonicalMatrixTable.rightQuery slots H other a X)) + let intoFiber : + {y : K × Z // ∃ h : H, + CanonicalMatrixTable.Accepts slots H other σ a (EvaluationMatrix.shift H X a h) ∧ + response slots H other σ W s (EvaluationMatrix.shift H X a h) = y} → + {y : K × Z // DirectionQuotient.projectWithSide a y = z} := fun y => + ⟨y.val, by + obtain ⟨h, hacc, hy⟩ := y.property + rw [← hy] + exact accepted_response_in_fiber slots H other σ W s hs hW a X h hacc⟩ + calc + _ ≤ Nat.card {y : K × Z // DirectionQuotient.projectWithSide a y = z} := + Nat.card_le_card_of_injective intoFiber (by + intro y y' he + exact Subtype.ext (congrArg + (fun v : {y : K × Z // DirectionQuotient.projectWithSide a y = z} => v.val) he)) + _ = 2 := DirectionQuotient.card_projectWithSide_fiber a ha z + +end +end PerfectCompleteness.RepresentativeMatrixTable + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Algebra/OutputCharacters.lean b/lean/OAI/Computability/PerfectCompleteness/Algebra/OutputCharacters.lean new file mode 100644 index 0000000000000000000000000000000000000000..b95e8f31a5fe5fdd0043879072ccf7df52ce4807 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Algebra/OutputCharacters.lean @@ -0,0 +1,227 @@ +import Mathlib.Algebra.BigOperators.Field +import OAI.Computability.PerfectCompleteness.Foundations.DualQuotientRowsLemmas + +namespace OAI + + +namespace PerfectCompleteness.OutputCharacters + +open scoped BigOperators +open UniqueGamesTheorem.Foundations.Games +open PerfectCompleteness.SmallBias +open PerfectCompleteness.SmallBiasSlice + +noncomputable section + +variable {Ω I J : Type*} [Fintype Ω] [Fintype I] [DecidableEq I] + [Fintype J] [DecidableEq J] + +omit [DecidableEq I] in +theorem sliceNumerator_const_mul (μ : FiniteDistribution Ω) + (A : Ω → I → Bool) (t : I → Bool) (c : ℝ) (g : Ω → ℝ) : + sliceNumerator μ A t (fun x => c * g x) = c * sliceNumerator μ A t g := by + unfold sliceNumerator + calc + _ = μ.expectation (fun x => c * (if A x = t then g x else 0)) := by + congr 1 + funext x + by_cases hx : A x = t <;> simp [hx] + _ = _ := expectation_const_mul μ c _ + +omit [DecidableEq I] in +theorem abs_sliceNumerator_le_mass (μ : FiniteDistribution Ω) + (A : Ω → I → Bool) (t : I → Bool) (g : Ω → ℝ) + (hg : ∀ x, |g x| ≤ 1) : + |sliceNumerator μ A t g| ≤ sliceMass μ A t := by + classical + apply abs_le.mpr + constructor + · have h := expectation_mono μ + (a := fun x => -(if A x = t then (1 : ℝ) else 0)) + (b := fun x => if A x = t then g x else 0) (by + intro x + by_cases hx : A x = t + · simpa only [ite_eq_left hx] using (abs_le.mp (hg x)).1 + · simp only [ite_eq_right hx, neg_zero, le_refl]) + simpa only [expectation_neg, sliceMass, sliceNumerator] using h + · change μ.expectation (fun x => if A x = t then g x else 0) ≤ + μ.expectation (fun x => if A x = t then (1 : ℝ) else 0) + apply expectation_mono μ + intro x + by_cases hx : A x = t + · simpa only [ite_eq_left hx] using (abs_le.mp (hg x)).2 + · simp only [ite_eq_right hx, le_refl] + +def sliceCorrelation (μ : FiniteDistribution Ω) (A : Ω → I → Bool) + (t : I → Bool) (g : Ω → ℝ) : ℝ := + sliceNumerator μ A t g / sliceMass μ A t + +def conditionalEquality (μ : FiniteDistribution Ω) (A : Ω → I → Bool) + (t : I → Bool) (G T : Ω → J → Bool) : ℝ := + sliceCorrelation μ A t (fun x => if G x = T x then 1 else 0) + +omit [DecidableEq I] in +theorem abs_sliceCorrelation_le_one (μ : FiniteDistribution Ω) + (A : Ω → I → Bool) (t : I → Bool) (g : Ω → ℝ) + (hmass : 0 < sliceMass μ A t) (hg : ∀ x, |g x| ≤ 1) : + |sliceCorrelation μ A t g| ≤ 1 := by + unfold sliceCorrelation + rw [abs_div, abs_of_pos hmass] + exact (div_le_one hmass).2 (abs_sliceNumerator_le_mass μ A t g hg) + +omit [DecidableEq I] in +theorem sliced_output_kernel (μ : FiniteDistribution Ω) + (A : Ω → I → Bool) (t : I → Bool) (G T : Ω → J → Bool) : + (∑ s : J → Bool, sliceNumerator μ A t + (fun x => maskChar s (G x) * maskChar s (T x))) = + (Fintype.card (J → Bool) : ℝ) * sliceNumerator μ A t + (fun x => if G x = T x then (1 : ℝ) else 0) := by + classical + have hpoint : ∀ x, + (∑ s : J → Bool, if A x = t then + maskChar s (G x) * maskChar s (T x) else 0) = + (Fintype.card (J → Bool) : ℝ) * + (if A x = t then (if G x = T x then (1 : ℝ) else 0) else 0) := by + intro x + by_cases hx : A x = t + · simp only [ite_eq_left hx] + rw [maskChar_kernel] + by_cases heq : G x = T x <;> simp [heq] + · simp [hx] + calc + _ = μ.expectation (fun x => ∑ s : J → Bool, if A x = t then + maskChar s (G x) * maskChar s (T x) else 0) := + (expectation_sum μ (fun s x => if A x = t then + maskChar s (G x) * maskChar s (T x) else 0)).symm + _ = μ.expectation (fun x => (Fintype.card (J → Bool) : ℝ) * + (if A x = t then (if G x = T x then (1 : ℝ) else 0) else 0)) := by + simp only [hpoint] + _ = _ := expectation_const_mul μ _ _ + +omit [DecidableEq I] in +theorem sum_output_correlations (μ : FiniteDistribution Ω) + (A : Ω → I → Bool) (t : I → Bool) (G T : Ω → J → Bool) : + (∑ s : J → Bool, sliceCorrelation μ A t + (fun x => maskChar s (G x) * maskChar s (T x))) = + (Fintype.card (J → Bool) : ℝ) * conditionalEquality μ A t G T := by + simp only [sliceCorrelation, conditionalEquality] + rw [← Finset.sum_div, sliced_output_kernel] + ring + +theorem exists_large_outside {K : Type*} [Fintype K] [Nonempty K] + (bad : Finset K) (c : K → ℝ) (rho : ℝ) (hrho : 0 < rho) + (hc : ∀ j, |c j| ≤ 1) + (hbad : (bad.card : ℝ) < (Fintype.card K : ℝ) * rho / 8) + (htotal : (Fintype.card K : ℝ) * rho ≤ ∑ j, c j) : + ∃ j, j ∉ bad ∧ rho / 2 ≤ |c j| := by + classical + by_contra h + have hsmall : ∀ j, j ∉ bad → |c j| < rho / 2 := by + intro j hj + exact lt_of_not_ge (fun hh => h ⟨j, hj, hh⟩) + have hterm : ∀ j, c j ≤ (if j ∈ bad then (1 : ℝ) else 0) + rho / 2 := by + intro j + by_cases hj : j ∈ bad + · have hb := (abs_le.mp (hc j)).2 + simp only [ite_eq_left hj] + linarith + · have hs := (le_abs_self (c j)).trans (hsmall j hj).le + simpa only [ite_eq_right hj, zero_add] using hs + have hsum := Finset.sum_le_sum + (fun j (_ : j ∈ (Finset.univ : Finset K)) => hterm j) + have hsum' : (∑ j, c j) ≤ + (bad.card : ℝ) + (Fintype.card K : ℝ) * (rho / 2) := by + simpa [Finset.sum_add_distrib] using hsum + have hN : (0 : ℝ) < Fintype.card K := Nat.cast_pos.mpr Fintype.card_pos + have hNrho : 0 < (Fintype.card K : ℝ) * rho := mul_pos hN hrho + nlinarith + +omit [DecidableEq I] in +theorem equality_implies_nonbad_correlation (μ : FiniteDistribution Ω) + (A : Ω → I → Bool) (t : I → Bool) (G T : Ω → J → Bool) + (bad : Finset (J → Bool)) (rho : ℝ) (hrho : 0 < rho) + (hmass : 0 < sliceMass μ A t) + (hbad : (bad.card : ℝ) / (Fintype.card (J → Bool) : ℝ) < rho / 8) + (hequality : rho ≤ conditionalEquality μ A t G T) : + ∃ s : J → Bool, s ∉ bad ∧ rho / 2 ≤ + |sliceCorrelation μ A t (fun x => maskChar s (G x) * maskChar s (T x))| := by + have hN : (0 : ℝ) < Fintype.card (J → Bool) := Nat.cast_pos.mpr Fintype.card_pos + apply exists_large_outside bad _ rho hrho + · intro s + apply abs_sliceCorrelation_le_one μ A t _ hmass + intro x + simp only [abs_mul, abs_maskChar, one_mul, le_refl] + · have h := (div_lt_iff₀ hN).1 hbad + nlinarith + · rw [sum_output_correlations] + exact mul_le_mul_of_nonneg_left hequality hN.le + +omit [DecidableEq I] [DecidableEq J] in +theorem abs_conditional_sign_transport (μ : FiniteDistribution Ω) + (A : Ω → I → Bool) (t : I → Bool) + (G T : Ω → J → Bool) (s : J → Bool) + (φ : Ω → ℝ) (sign : ℝ) (hsign : |sign| = 1) + (hT : ∀ x, maskChar s (T x) = sign * φ x) : + |sliceCorrelation μ A t (fun x => maskChar s (G x) * maskChar s (T x))| = + |sliceCorrelation μ A t (fun x => maskChar s (G x) * φ x)| := by + have hfun : (fun x => maskChar s (G x) * maskChar s (T x)) = + (fun x => sign * (maskChar s (G x) * φ x)) := by + funext x + rw [hT] + ring + unfold sliceCorrelation + rw [hfun, sliceNumerator_const_mul] + simp only [abs_div, abs_mul, hsign, one_mul] + + +variable {F : Type*} [AddCommMonoid F] [Fintype F] + +theorem equality_implies_affine_heavy_witness (μ : FiniteDistribution Ω) + (χ : F → Ω → ℝ) (hzero : ∀ x, χ 0 x = 1) + (hadd : ∀ a b x, χ (a + b) x = χ a x * χ b x) + (rows : I → F) (A : Ω → I → Bool) + (hrows : ∀ i x, χ (rows i) x = bitSign (A x i)) + (hindependent : Function.Injective (rowCombination rows)) + (t : I → Bool) (G T : Ω → J → Bool) + (base : (J → Bool) → F) (sign : (J → Bool) → ℝ) + (hsign : ∀ s, |sign s| = 1) + (htarget : ∀ s x, maskChar s (T x) = sign s * χ (base s) x) + (bad : Finset (J → Bool)) (rho h0 biasBound : ℝ) + (hrho : 0 < rho) (hh0 : 0 < h0) + (hsize : h0 ≤ 1 / (Fintype.card (I → Bool) : ℝ)) + (hb : 0 ≤ biasBound) (hbsmall : biasBound ≤ h0 / 2) + (hbias : ∀ a : F, a ≠ 0 → |μ.expectation (χ a)| ≤ biasBound) + (hbad : (bad.card : ℝ) / (Fintype.card (J → Bool) : ℝ) < rho / 8) + (hequality : rho ≤ conditionalEquality μ A t G T) : + ∃ s : J → Bool, s ∉ bad ∧ ∃ mask : I → Bool, + base s + rowCombination rows mask ∈ + heavySet μ χ (fun x => maskChar s (G x)) (rho * h0 / 4) := by + have hmaskbias : ∀ mask : I → Bool, mask ≠ (fun _ => false) → + |μ.expectation (fun x => maskChar mask (A x))| ≤ biasBound := by + intro mask hmask + have hne : rowCombination rows mask ≠ 0 := by + intro hz + apply hmask + apply hindependent + simpa using hz + have h := hbias (rowCombination rows mask) hne + change |μ.expectation (fun x => χ (rowCombination rows mask) x)| ≤ biasBound at h + simpa only [character_rowCombination χ hzero hadd rows A hrows] using h + have hmass : 0 < sliceMass μ A t := by + have h := sliceMass_lower μ A t biasBound hb hmaskbias + linarith + obtain ⟨s, hsbad, hcorr⟩ := + equality_implies_nonbad_correlation μ A t G T bad rho hrho hmass hbad hequality + rw [abs_conditional_sign_transport μ A t G T s (χ (base s)) (sign s) + (hsign s) (htarget s)] at hcorr + refine ⟨s, hsbad, ?_⟩ + exact affine_coset_heavy_witness μ χ hzero hadd rows A hrows hindependent t + (fun x => maskChar s (G x)) (base s) rho h0 biasBound hrho hh0 hsize hb hbsmall + hbias hcorr + + +end + +end PerfectCompleteness.OutputCharacters + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Algebra/PrefixMatrixAcceptance.lean b/lean/OAI/Computability/PerfectCompleteness/Algebra/PrefixMatrixAcceptance.lean new file mode 100644 index 0000000000000000000000000000000000000000..7cfa6658a9150f1388c0b2badd257e7c6d904bc0 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Algebra/PrefixMatrixAcceptance.lean @@ -0,0 +1,101 @@ +import OAI.Computability.PerfectCompleteness.Algebra.PreliminaryMatrixAcceptance +import OAI.Computability.PerfectCompleteness.Foundations.PrefixTests +import OAI.Computability.PerfectCompleteness.Machines.StoppedOwnInputGeometry + +namespace OAI + +section + +namespace PerfectCompleteness.PrefixMatrixAcceptance + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays + +variable {branch rows : Nat → Nat} {v m n t : Nat} + (clauses : Fin m → SourceClause.NormalizedClause v) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (questions : PreliminarySampler.Questions branch n t m) + +local notation "slots" => sourceSlots clauses (PreliminarySampler.endpoints questions) + +theorem observe_iff_matrix + (arrays : Arrays slots rows) (level : Fin n) + (node : PrefixTests.LevelNode branch level) + (a : PrefixTests.LevelDirection rows level) : + PrefixTests.observeAtLevelNode clauses σ questions arrays level node a = true ↔ + CanonicalMatrixTable.Accepts (TreeCanonical.numberedSlots slots) + (NodeEmbedding.RowSpace slots node.val) + (HierarchicalMatrixTable.other slots node.val + (HierarchicalMatrixTable.backgroundOf slots node.val arrays)) + σ (PrefixTests.nodeDirection rows level node a).val + (NodeEmbedding.matrix arrays node.val) := by + have h := (HierarchicalMatrixTable.accepts_iff_canonical slots node.val σ + (HierarchicalMatrixTable.backgroundOf slots node.val arrays) + (NodeEmbedding.matrix arrays node.val) + (PrefixTests.nodeDirection rows level node a).val).symm + rw [HierarchicalMatrixTable.displayed_original] at h + unfold PrefixTests.observeAtLevelNode + dsimp only + constructor + · intro hevent + exact h.mp (@of_decide_eq_true _ _ hevent) + · intro haccept + exact @decide_eq_true _ _ (h.mpr haccept) + +theorem observe_iff_lower + (arrays : Arrays slots rows) (level : Fin n) + (node : PrefixTests.LevelNode branch level) + (a : PrefixTests.LevelDirection rows level) (upper : Nodes branch n) : + PrefixTests.observeAtLevelNode clauses σ questions arrays level node a = true ↔ + HierarchicalPrediction.LowerAccepts slots upper + (HierarchicalMatrixTable.backgroundOf slots upper arrays) σ node.val + (PrefixTests.nodeDirection rows level node a).val + (NodeEmbedding.matrix arrays upper) := by + unfold HierarchicalPrediction.LowerAccepts + rw [HierarchicalMatrixTable.displayed_original] + unfold PrefixTests.observeAtLevelNode + dsimp only + constructor + · intro hevent + exact @of_decide_eq_true _ _ hevent + · intro haccept + exact @decide_eq_true _ _ haccept + +theorem observe_eq_lower + (arrays : Arrays slots rows) (level : Fin n) + (node : PrefixTests.LevelNode branch level) + (a : PrefixTests.LevelDirection rows level) (upper : Nodes branch n) : + PrefixTests.observeAtLevelNode clauses σ questions arrays level node a = + decide (HierarchicalPrediction.LowerAccepts slots upper + (HierarchicalMatrixTable.backgroundOf slots upper arrays) σ node.val + (PrefixTests.nodeDirection rows level node a).val + (NodeEmbedding.matrix arrays upper)) := by + apply Bool.eq_iff_iff.mpr + simpa only [decide_eq_true_eq] using + observe_iff_lower clauses σ questions arrays level node a upper + +theorem observe_endpoint {k : Nat} (p : Path branch n (k + 1)) + (suffix : Slots branch (k + 1)) (arrays : Arrays slots rows) + (a : PrefixTests.LevelDirection rows + (⟨k, Nat.lt_of_lt_of_le (Nat.lt_succ_self k) p.height_le⟩ : Fin n)) : + PreliminaryStrategy.observe clauses σ (questions, p.slotEmbedding suffix) arrays + (PrefixTests.choiceAt rows (p.slotEmbedding suffix) + ⟨k, Nat.lt_of_lt_of_le (Nat.lt_succ_self k) p.height_le⟩ a) = + PrefixTests.observeAtLevelNode clauses σ questions arrays + ⟨k, Nat.lt_of_lt_of_le (Nat.lt_succ_self k) p.height_le⟩ + ⟨WholeArrayInteriorExterior.upperNode p, + WholeArrayInteriorExterior.upperNode_height p⟩ a := by + rw [PrefixTests.observe_choiceAt_eq] + apply congrArg (fun node => PrefixTests.observeAtLevelNode clauses σ questions arrays + ⟨k, Nat.lt_of_lt_of_le (Nat.lt_succ_self k) p.height_le⟩ node a) + apply Subtype.ext + exact StoppedOwnInputGeometry.nodeAtLevel_endpoint p suffix + +end +end PerfectCompleteness.PrefixMatrixAcceptance + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Algebra/PreliminaryMatrixAcceptance.lean b/lean/OAI/Computability/PerfectCompleteness/Algebra/PreliminaryMatrixAcceptance.lean new file mode 100644 index 0000000000000000000000000000000000000000..a11d727f44751a39c105b5c25d949df5f32d42bb --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Algebra/PreliminaryMatrixAcceptance.lean @@ -0,0 +1,99 @@ +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalPrediction +import OAI.Computability.PerfectCompleteness.Reduction.HierarchicalFixedAdviceFamilyLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.PreliminaryMatrixAcceptance + +noncomputable section + +open scoped Classical +open PreliminarySampler TreeSourceSpaces HierarchicalArrays + +variable {v m n t : Nat} {branch rows : Nat → Nat} + (clauses : Fin m → SourceClause.NormalizedClause v) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (b : Base branch n t m) + +theorem observe_iff_matrix_accepts + (arrays : Arrays (sourceSlots clauses (endpoints b.1)) rows) + (choice : Choice rows b.2) : + PreliminaryStrategy.observe clauses σ b arrays choice = true ↔ + CanonicalMatrixTable.Accepts + (TreeCanonical.numberedSlots (sourceSlots clauses (endpoints b.1))) + (NodeEmbedding.RowSpace (sourceSlots clauses (endpoints b.1)) + (GeometricPath.nodeAtLevel b.2 choice.1)) + (HierarchicalMatrixTable.other (sourceSlots clauses (endpoints b.1)) + (GeometricPath.nodeAtLevel b.2 choice.1) + (HierarchicalMatrixTable.backgroundOf (sourceSlots clauses (endpoints b.1)) + (GeometricPath.nodeAtLevel b.2 choice.1) arrays)) + σ choice.2.val (NodeEmbedding.matrix arrays (GeometricPath.nodeAtLevel b.2 choice.1)) := by + have h := (HierarchicalMatrixTable.accepts_iff_canonical + (sourceSlots clauses (endpoints b.1)) (GeometricPath.nodeAtLevel b.2 choice.1) σ + (HierarchicalMatrixTable.backgroundOf (sourceSlots clauses (endpoints b.1)) + (GeometricPath.nodeAtLevel b.2 choice.1) arrays) + (NodeEmbedding.matrix arrays (GeometricPath.nodeAtLevel b.2 choice.1)) choice.2.val).symm + rw [HierarchicalMatrixTable.displayed_original] at h + unfold PreliminaryStrategy.observe + dsimp only + constructor + · intro hobserve + exact h.mp (@of_decide_eq_true _ _ hobserve) + · intro haccepts + exact @decide_eq_true _ _ (h.mpr haccepts) + +theorem observe_eq_decide_matrix_accepts + (arrays : Arrays (sourceSlots clauses (endpoints b.1)) rows) + (choice : Choice rows b.2) : + PreliminaryStrategy.observe clauses σ b arrays choice = + decide (CanonicalMatrixTable.Accepts + (TreeCanonical.numberedSlots (sourceSlots clauses (endpoints b.1))) + (NodeEmbedding.RowSpace (sourceSlots clauses (endpoints b.1)) + (GeometricPath.nodeAtLevel b.2 choice.1)) + (HierarchicalMatrixTable.other (sourceSlots clauses (endpoints b.1)) + (GeometricPath.nodeAtLevel b.2 choice.1) + (HierarchicalMatrixTable.backgroundOf (sourceSlots clauses (endpoints b.1)) + (GeometricPath.nodeAtLevel b.2 choice.1) arrays)) + σ choice.2.val (NodeEmbedding.matrix arrays (GeometricPath.nodeAtLevel b.2 choice.1))) := by + apply Bool.eq_iff_iff.mpr + simpa only [decide_eq_true_eq] using observe_iff_matrix_accepts clauses σ b arrays choice + +theorem observe_assembled_iff_lower_accepts (upper : Nodes branch n) + (background : HierarchicalMatrixTable.Background (rows := rows) + (sourceSlots clauses (endpoints b.1)) upper) + (X : HierarchicalMatrixTable.Matrix (rows := rows) (sourceSlots clauses (endpoints b.1)) upper) + (choice : Choice rows b.2) : + PreliminaryStrategy.observe clauses σ b + (HierarchicalMatrixTable.assemble (sourceSlots clauses (endpoints b.1)) upper background X) + choice = true ↔ + HierarchicalPrediction.LowerAccepts (sourceSlots clauses (endpoints b.1)) upper + background σ (GeometricPath.nodeAtLevel b.2 choice.1) choice.2.val X := by + unfold PreliminaryStrategy.observe + dsimp only + constructor + · intro hobserve + have hcanonical := @of_decide_eq_true _ _ hobserve + exact hcanonical + · intro haccepts + exact @decide_eq_true _ _ haccepts + +theorem observe_iff_lower_accepts + (arrays : Arrays (sourceSlots clauses (endpoints b.1)) rows) + (choice : Choice rows b.2) (upper : Nodes branch n) : + PreliminaryStrategy.observe clauses σ b arrays choice = true ↔ + HierarchicalPrediction.LowerAccepts (sourceSlots clauses (endpoints b.1)) upper + (HierarchicalMatrixTable.backgroundOf (sourceSlots clauses (endpoints b.1)) upper arrays) + σ (GeometricPath.nodeAtLevel b.2 choice.1) choice.2.val (NodeEmbedding.matrix arrays upper) := by + have h := observe_assembled_iff_lower_accepts clauses σ b upper + (HierarchicalMatrixTable.backgroundOf (sourceSlots clauses (endpoints b.1)) upper arrays) + (NodeEmbedding.matrix arrays upper) choice + rwa [HierarchicalMatrixTable.assemble_original] at h + +end +end PerfectCompleteness.PreliminaryMatrixAcceptance + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Algebra/ProductEvaluationRank.lean b/lean/OAI/Computability/PerfectCompleteness/Algebra/ProductEvaluationRank.lean new file mode 100644 index 0000000000000000000000000000000000000000..1879ecd4d7ea9e30e775dfe449704c177fc544da --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Algebra/ProductEvaluationRank.lean @@ -0,0 +1,35 @@ +import Mathlib.LinearAlgebra.Matrix.Rank +import OAI.Computability.PerfectCompleteness.Foundations.ManyGoodRowsLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.ProductEvaluationRank + +open ProductEvaluation MixedSupport CanonicalKeys + +noncomputable section + +variable {n : Nat} {C Z : Type*} {Row : C → Type*} + +theorem extension_productMatrix_rank_le_one + (slots : Fin n → Slot) (H : Submodule F2 (Assignment slots → F2)) + (rows : (c : C) → Row c → Assignment slots → F2) + (other : Assignment slots → Z) (hone : (1 : Assignment slots → F2) ∈ H) + (hproducts : ∀ c u v, rows c u * rows c v ∈ H) + (P : Label slots (displayedJoint rows other)) (z : Module.Dual F2 H) + (hz : z.comp (productSpan H rows hone hproducts).subtype = + labelFunctional slots H rows other hone hproducts P) + (c : C) [Fintype (Row c)] : + Matrix.rank (fun u v : Row c => z ⟨rows c u * rows c v, hproducts c u v⟩) ≤ 1 := by + rw [extension_productMatrix slots H rows other hone hproducts P z hz c] + exact Matrix.rank_vecMulVec_le (restoredRows slots rows other P c) + (restoredRows slots rows other P c) + +end +end PerfectCompleteness.ProductEvaluationRank + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Algebra/RightDecoderAffineSuccess.lean b/lean/OAI/Computability/PerfectCompleteness/Algebra/RightDecoderAffineSuccess.lean new file mode 100644 index 0000000000000000000000000000000000000000..48d38d22f048d3e532e04b1a8576e5d87df92829 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Algebra/RightDecoderAffineSuccess.lean @@ -0,0 +1,85 @@ +import OAI.Computability.PerfectCompleteness.Decoding.RightDecoderLemmas +import OAI.Computability.PerfectCompleteness.Decoding.RightDecoderWitness +import OAI.Computability.PerfectCompleteness.Foundations.OutputAnnihilator + +namespace OAI + +section + +namespace PerfectCompleteness.RightDecoderAffineSuccess + +open scoped TensorProduct Classical +open UniqueGamesTheorem.Foundations.Games +open TreeSourceSpaces HierarchicalArrays OwnInputReference + +abbrev F2 := ZMod 2 + +noncomputable section + +variable {branch : Nat → Nat} {n t : Nat} + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (rows : Nat → Nat) (upper lower : Nodes branch n) + (W : Submodule F2 (UpperVector rows upper)) (a : LowerVector rows lower) + (repeats : Nat → Nat) (cut : Cut upper lower) + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (input : Input slots rows upper lower W a) + +attribute [local instance] RightDecoder.characterFintype RightDecoder.scalarFintype + +theorem character_count : + Fintype.card (Module.Dual F2 (UpperVector rows upper)) = + 2 ^ rows (Nodes.height upper) := by + simpa only [OwnInputReference.UpperVector, HierarchicalArrays.Block, + Module.finrank_fin_fun] using + (OutputAnnihilator.card_dual (K := UpperVector rows upper)) + +theorem coset_probability_lower + (ρ h₀ : ℝ) (hρ : 0 < ρ) (hh₀ : 0 < h₀) + (hrep : RecursiveSamplerBias.RepetitionsBalanced repeats) + (hslice : (7 / 8 : ℝ) ^ repeats (Nodes.height upper) ≤ h₀ / 2) + (hlist : (7 / 8 : ℝ) ^ repeats (Nodes.height upper) ≤ (ρ * h₀ / 4) ^ 2 / 2) + (hexcluded : 1 / (2 : ℝ) ^ Module.finrank F2 W < ρ / 8) + (Q : Submodule F2 (Module.Dual F2 (UpperSpace slots upper))) + (hsize : h₀ ≤ 1 / (2 : ℝ) ^ Module.finrank F2 (Q →ₗ[F2] W)) + (target : Q →ₗ[F2] W) (z : Module.Dual F2 (UpperSpace slots upper)) + (offset : UpperVector rows upper) + (hmatch : ρ ≤ RightDecoderWitness.conditionalMatch slots rows upper lower W a + repeats cut labeling input Q target z offset) : + (ρ * h₀ / 4) ^ 2 / (2 * (2 : ℝ) ^ rows (Nodes.height upper)) ≤ + (RightDecoder.law slots rows upper lower W a repeats cut labeling input (ρ * h₀ / 4)).probability + (fun decoded => decide (decoded - z ∈ Q)) := by + have hthreshold : 0 < ρ * h₀ / 4 := div_pos (mul_pos hρ hh₀) (by norm_num) + obtain ⟨σ, hσ, Φ, hΦ, herror⟩ := + RightDecoderWitness.exists_heavy_error_coset slots rows upper lower W a + repeats cut labeling input ρ h₀ hρ hh₀ hrep hslice hexcluded Q hsize target z offset hmatch + have h := RightDecoder.coset_lower_of_balanced slots rows upper lower W a + repeats cut labeling input (ρ * h₀ / 4) hrep hthreshold hlist Q z + ⟨σ, Φ, hΦ, hσ, herror⟩ + simpa only [character_count rows upper, Nat.cast_pow, Nat.cast_ofNat] using h + +theorem coset_probability_pos + (ρ h₀ : ℝ) (hρ : 0 < ρ) (hh₀ : 0 < h₀) + (hrep : RecursiveSamplerBias.RepetitionsBalanced repeats) + (hslice : (7 / 8 : ℝ) ^ repeats (Nodes.height upper) ≤ h₀ / 2) + (hlist : (7 / 8 : ℝ) ^ repeats (Nodes.height upper) ≤ (ρ * h₀ / 4) ^ 2 / 2) + (hexcluded : 1 / (2 : ℝ) ^ Module.finrank F2 W < ρ / 8) + (Q : Submodule F2 (Module.Dual F2 (UpperSpace slots upper))) + (hsize : h₀ ≤ 1 / (2 : ℝ) ^ Module.finrank F2 (Q →ₗ[F2] W)) + (target : Q →ₗ[F2] W) (z : Module.Dual F2 (UpperSpace slots upper)) + (offset : UpperVector rows upper) + (hmatch : ρ ≤ RightDecoderWitness.conditionalMatch slots rows upper lower W a + repeats cut labeling input Q target z offset) : + 0 < (RightDecoder.law slots rows upper lower W a repeats cut labeling input (ρ * h₀ / 4)).probability + (fun decoded => decide (decoded - z ∈ Q)) := by + have hthreshold : 0 < ρ * h₀ / 4 := div_pos (mul_pos hρ hh₀) (by norm_num) + have hfactor : 0 < (ρ * h₀ / 4) ^ 2 / (2 * (2 : ℝ) ^ rows (Nodes.height upper)) := + div_pos (pow_pos hthreshold _) (mul_pos (by norm_num) (pow_pos (by norm_num) _)) + exact hfactor.trans_le (coset_probability_lower slots rows upper lower W a repeats cut + labeling input ρ h₀ hρ hh₀ hrep hslice hlist hexcluded Q hsize target z offset hmatch) + +end +end PerfectCompleteness.RightDecoderAffineSuccess + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Algebra/TensorAffineHeavyWitness.lean b/lean/OAI/Computability/PerfectCompleteness/Algebra/TensorAffineHeavyWitness.lean new file mode 100644 index 0000000000000000000000000000000000000000..4e2f327e5c9f6fde220757f2cadf79289905955a --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Algebra/TensorAffineHeavyWitness.lean @@ -0,0 +1,152 @@ +import OAI.Computability.PerfectCompleteness.Algebra.AffineLinearHeavyWitness +import OAI.Computability.PerfectCompleteness.Algebra.BilinearGramCompressionLemmas +import OAI.Computability.PerfectCompleteness.Algebra.TensorBucketEvaluationLemmas +import OAI.Computability.PerfectCompleteness.Algebra.TensorSliceDimension +import OAI.Computability.PerfectCompleteness.Foundations.OutputAnnihilator +import OAI.Computability.PerfectCompleteness.Sampling.OwnLawHeavyList + +namespace OAI + +section + +namespace PerfectCompleteness.TensorAffineHeavyWitness + +open scoped TensorProduct Classical +open QuarterBalance (F2) +open UniqueGamesTheorem.Foundations.Games + +noncomputable section + +variable {ℓ : Nat} {H : Type*} [AddCommGroup H] [Module F2 H] + [Finite H] [FiniteDimensional F2 H] + +local instance dualFintype {V : Type*} [AddCommGroup V] [Module F2 V] [Fintype V] : + Fintype (Module.Dual F2 V) := + Fintype.ofInjective (fun f : Module.Dual F2 V => (f : V → F2)) DFunLike.coe_injective + +def heavyList (W : Submodule F2 (Fin ℓ → F2)) + (μ : FiniteDistribution (W ⊗[F2] H)) (G : (W ⊗[F2] H) → (Fin ℓ → F2)) + (τ : ℝ) (σ : Module.Dual F2 (Fin ℓ → F2)) : + Finset (Module.Dual F2 (W ⊗[F2] H)) := + OwnLawHeavyList.heavyList μ (fun X => QuarterBalance.sign (σ (G X))) τ + +omit [FiniteDimensional F2 H] in +theorem heavyList_card_le (W : Submodule F2 (Fin ℓ → F2)) + (μ : FiniteDistribution (W ⊗[F2] H)) (G : (W ⊗[F2] H) → (Fin ℓ → F2)) + (τ biasBound : ℝ) (hτ : 0 < τ) (hbiasBound : 0 ≤ biasBound) (hsmall : biasBound ≤ τ ^ 2 / 2) + (hbias : ∀ Φ : Module.Dual F2 (W ⊗[F2] H), Φ ≠ 0 → + |μ.expectation (fun X => QuarterBalance.sign (Φ X))| ≤ biasBound) + (σ : Module.Dual F2 (Fin ℓ → F2)) : + ((heavyList W μ G τ σ).card : ℝ) ≤ 2 / τ ^ 2 := by + apply OwnLawHeavyList.heavyList_card_le μ _ τ biasBound hτ hbiasBound hsmall + · intro X + exact (OwnLawHeavyList.character_sq σ (G X)).le + · exact hbias + +def conditionalMatch (W : Submodule F2 (Fin ℓ → F2)) + (μ : FiniteDistribution (W ⊗[F2] H)) (G : (W ⊗[F2] H) → (Fin ℓ → F2)) + (Q : Submodule F2 (Module.Dual F2 H)) (target : Q →ₗ[F2] W) + (z : Module.Dual F2 H) (offset : Fin ℓ → F2) : ℝ := + AffineLinearHeavyWitness.conditionalMatch μ (TensorRestriction.restrictionMap Q) + target G (TensorBucketEvaluation.tensorOutputLinear W z) offset + +theorem exists_heavy_candidate (W : Submodule F2 (Fin ℓ → F2)) + (μ : FiniteDistribution (W ⊗[F2] H)) (G : (W ⊗[F2] H) → (Fin ℓ → F2)) + (ρ h₀ biasBound : ℝ) (hρ : 0 < ρ) (hh₀ : 0 < h₀) (hbiasBound : 0 ≤ biasBound) + (hsmall : biasBound ≤ h₀ / 2) + (hbias : ∀ Φ : Module.Dual F2 (W ⊗[F2] H), Φ ≠ 0 → + |μ.expectation (fun X => QuarterBalance.sign (Φ X))| ≤ biasBound) + (hexcluded : 1 / (2 : ℝ) ^ Module.finrank F2 W < ρ / 8) + (Q : Submodule F2 (Module.Dual F2 H)) + (hsize : h₀ ≤ 1 / (2 : ℝ) ^ Module.finrank F2 (Q →ₗ[F2] W)) + (target : Q →ₗ[F2] W) (z : Module.Dual F2 H) (offset : Fin ℓ → F2) + (hmatch : ρ ≤ conditionalMatch W μ G Q target z offset) : + ∃ σ : Module.Dual F2 (Fin ℓ → F2), σ.comp W.subtype ≠ 0 ∧ + ∃ Φ ∈ heavyList W μ G (ρ * h₀ / 4) σ, + ∀ w : W, σ w = 1 → TensorCosetEvaluation.scalarRestriction Φ w - z ∈ Q := by + let : Module.Free F2 (Q →ₗ[F2] W) := Module.Free.of_divisionRing F2 (Q →ₗ[F2] W) + let : Fintype (Module.Dual F2 (W ⊗[F2] H)) := + Fintype.ofInjective (fun functional : Module.Dual F2 (W ⊗[F2] H) => + (functional : (W ⊗[F2] H) → F2)) DFunLike.coe_injective + let b := Module.finBasis F2 (Q →ₗ[F2] W) + let c := Module.finBasis F2 (Fin ℓ → F2) + have hsize' : h₀ ≤ 1 / (Fintype.card + (Fin (Module.finrank F2 (Q →ₗ[F2] W)) → Bool) : ℝ) := by + simpa only [Fintype.card_fun, Fintype.card_bool, Fintype.card_fin, + Nat.cast_pow, Nat.cast_ofNat] using hsize + have hbad : ((OutputAnnihilator.bad W).card : ℝ) / + Fintype.card (Module.Dual F2 (Fin ℓ → F2)) < ρ / 8 := by + rw [OutputAnnihilator.bad_fraction] + exact hexcluded + unfold conditionalMatch at hmatch + have candidateBasis := + AffineLinearHeavyWitness.exists_heavy_in_dual_coset + (U := W ⊗[F2] H) (V := Q →ₗ[F2] W) (K := Fin ℓ → F2) μ b c + have candidateRestriction := candidateBasis + (TensorRestriction.restrictionMap Q) + (TensorRestriction.restrictionMap_surjective (W := W) Q) + have candidateData := candidateRestriction + target G (TensorBucketEvaluation.tensorOutputLinear W z) offset + (OutputAnnihilator.bad W) ρ h₀ biasBound + have candidateBounds := candidateData hρ hh₀ hsize' hbiasBound hsmall hbias hbad + have candidateWitness := candidateBounds hmatch + obtain ⟨σ, hσ, ψ, hψ, hheavy⟩ := candidateWitness + refine ⟨σ, (OutputAnnihilator.not_mem_bad_iff W σ).mp hσ, + σ.comp (TensorBucketEvaluation.tensorOutputLinear W z) + ψ, ?_, ?_⟩ + · simp only [heavyList, OwnLawHeavyList.heavyList, SmallBias.heavySet, + Finset.mem_filter, Finset.mem_univ, true_and] at hheavy ⊢ + simpa only [OwnLawHeavyList.character, BinaryDualCoordinates.character] using hheavy + · intro w hw + have hψ' : TensorCosetEvaluation.scalarRestriction ψ w ∈ Q := + TensorCosetEvaluation.scalarRestriction_mem_of_vanishes Q ψ + (TensorRestriction.dualImage_vanishes Q ψ hψ) w + rw [TensorTargetCharacter.comp_tensorOutputLinear, + TensorCosetEvaluation.scalarRestriction_add, + TensorCosetEvaluation.scalarRestriction_pure] + have hw' : (σ.comp W.subtype) w = 1 := hw + rw [hw', one_smul, add_sub_cancel_left] + exact hψ' + +theorem lemma53 (W : Submodule F2 (Fin ℓ → F2)) + (μ : FiniteDistribution (W ⊗[F2] H)) (G : (W ⊗[F2] H) → (Fin ℓ → F2)) + (r : Nat) (hcodim : Module.finrank F2 ((Fin ℓ → F2) ⧸ W) ≤ r) + (ρ biasBound : ℝ) (hρ : 0 < ρ) (hbiasBound : 0 ≤ biasBound) + (hgap : 1 / (2 : ℝ) ^ (ℓ - r) < ρ / 8) + (hsmall : biasBound ≤ min ((1 / (2 : ℝ) ^ (r * ℓ)) / 2) + ((ρ * (1 / (2 : ℝ) ^ (r * ℓ)) / 4) ^ 2 / 2)) + (hbias : ∀ Φ : Module.Dual F2 (W ⊗[F2] H), Φ ≠ 0 → + |μ.expectation (fun X => QuarterBalance.sign (Φ X))| ≤ biasBound) : + (∀ σ : Module.Dual F2 (Fin ℓ → F2), + ((heavyList W μ G (ρ * (1 / (2 : ℝ) ^ (r * ℓ)) / 4) σ).card : ℝ) ≤ + 2 / (ρ * (1 / (2 : ℝ) ^ (r * ℓ)) / 4) ^ 2) ∧ + ∀ (Q : Submodule F2 (Module.Dual F2 H)), Module.finrank F2 Q ≤ r → + ∀ (target : Q →ₗ[F2] W) (z : Module.Dual F2 H) (offset : Fin ℓ → F2), + ρ ≤ conditionalMatch W μ G Q target z offset → + ∃ σ : Module.Dual F2 (Fin ℓ → F2), σ.comp W.subtype ≠ 0 ∧ + ∃ Φ ∈ heavyList W μ G (ρ * (1 / (2 : ℝ) ^ (r * ℓ)) / 4) σ, + ∀ w : W, σ w = 1 → + TensorCosetEvaluation.scalarRestriction Φ w - z ∈ Q := by + have hh₀ : 0 < 1 / (2 : ℝ) ^ (r * ℓ) := by positivity + have hτ : 0 < ρ * (1 / (2 : ℝ) ^ (r * ℓ)) / 4 := by positivity + have hsmall' := le_min_iff.mp hsmall + constructor + · intro σ + exact heavyList_card_le W μ G _ biasBound hτ hbiasBound hsmall'.2 hbias σ + · intro Q hQ target z offset hmatch + have hexcluded : 1 / (2 : ℝ) ^ Module.finrank F2 W < ρ / 8 := by + rw [← OutputAnnihilator.bad_fraction W] + apply OutputAnnihilator.bad_fraction_lt_of_codim_le W r ρ hcodim + simpa only [Module.finrank_fin_fun] using hgap + have hsize : 1 / (2 : ℝ) ^ (r * ℓ) ≤ + 1 / (2 : ℝ) ^ Module.finrank F2 (Q →ₗ[F2] W) := by + simpa only [TensorSliceDimension.mask_card, Nat.cast_pow, Nat.cast_ofNat] using + TensorSliceDimension.reciprocal_equation_mask_card_ge W Q hQ + exact exists_heavy_candidate W μ G ρ _ biasBound hρ hh₀ hbiasBound hsmall'.1 hbias hexcluded + Q hsize target z offset hmatch + +end +end PerfectCompleteness.TensorAffineHeavyWitness + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Algebra/TensorBucketEvaluationLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Algebra/TensorBucketEvaluationLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..74a3359c2ed685fb0aa9d2ec0dc48c2b91b57854 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Algebra/TensorBucketEvaluationLemmas.lean @@ -0,0 +1,390 @@ +import Mathlib.LinearAlgebra.TensorProduct.Associator +import OAI.Computability.PerfectCompleteness.Algebra.BilinearGramCompressionLemmas +import OAI.Computability.PerfectCompleteness.Algebra.EvaluationMatrix +import OAI.Computability.PerfectCompleteness.Construction.HiddenBucketBias +import OAI.Computability.PerfectCompleteness.Construction.NodeEmbedding +import OAI.Computability.PerfectCompleteness.Foundations.PartitionsLemmas + +namespace OAI + + +namespace PerfectCompleteness.TensorBucketEvaluation + +open scoped BigOperators TensorProduct Classical + +noncomputable section + +abbrev F2 := BucketSampler.F2 + +variable {ℓ : Nat} {Ω H : Type*} [AddCommGroup H] [Module F2 H] + +def tensorOutputLinear (W : Submodule F2 (Fin ℓ → F2)) + (q : Module.Dual F2 H) : (W ⊗[F2] H) →ₗ[F2] (Fin ℓ → F2) := + W.subtype.comp + ((TensorProduct.rid F2 W).toLinearMap.comp + (TensorProduct.map (LinearMap.id : W →ₗ[F2] W) q)) + +def tensorOutput (W : Submodule F2 (Fin ℓ → F2)) + (q : Module.Dual F2 H) (X : W ⊗[F2] H) : Fin ℓ → F2 := + tensorOutputLinear W q X + +@[simp] theorem tensorOutput_tmul (W : Submodule F2 (Fin ℓ → F2)) + (q : Module.Dual F2 H) (w : W) (h : H) : + tensorOutput W q (w ⊗ₜ[F2] h) = q h • w.val := by + simp [tensorOutput, tensorOutputLinear] + +@[simp] theorem tensorOutput_zero (W : Submodule F2 (Fin ℓ → F2)) + (q : Module.Dual F2 H) : tensorOutput W q 0 = 0 := + (tensorOutputLinear W q).map_zero + +@[simp] theorem tensorOutput_add (W : Submodule F2 (Fin ℓ → F2)) + (q : Module.Dual F2 H) (X Y : W ⊗[F2] H) : + tensorOutput W q (X + Y) = tensorOutput W q X + tensorOutput W q Y := + (tensorOutputLinear W q).map_add X Y + +theorem tensorOutput_hiddenSum (W : Submodule F2 (Fin ℓ → F2)) + (q : Module.Dual F2 H) (eval : Ω → H) + (ω : HiddenBucketBias.HiddenTape W Ω) : + tensorOutput W q (HiddenBucketBias.hiddenSum W eval ω) = + ∑ v : HiddenBucketBias.HiddenDirection W, q (eval (ω v)) • v.val.val := by + change tensorOutputLinear W q + (∑ v : HiddenBucketBias.HiddenDirection W, + HiddenBucketBias.directionIn W v ⊗ₜ[F2] eval (ω v)) = _ + rw [map_sum] + apply Finset.sum_congr rfl + intro v _ + exact tensorOutput_tmul W q (HiddenBucketBias.directionIn W v) (eval (ω v)) + +def visibleOutput (W : Submodule F2 (Fin ℓ → F2)) + (q : Module.Dual F2 H) (eval : Ω → H) + (ω : HiddenBucketBias.VisibleTape W Ω) : Fin ℓ → F2 := + ∑ v : HiddenBucketBias.VisibleDirection W, q (eval (ω v)) • v.val.val + +theorem evaluate_eq_direction_sum (q : Module.Dual F2 H) + (eval : Ω → H) (t : BucketSampler.Tape ℓ Ω) : + (fun i => q (BucketSampler.evaluate ℓ eval t i)) = + ∑ v : BucketSampler.Direction ℓ, q (eval (t v)) • v.val := by + funext i + rw [BucketSampler.linearMap_evaluate] + simp only [Finset.sum_apply, Pi.smul_apply, smul_eq_mul] + apply Finset.sum_congr rfl + intro v _ + exact mul_comm _ _ + +theorem evaluate_split (W : Submodule F2 (Fin ℓ → F2)) + (q : Module.Dual F2 H) (eval : Ω → H) (t : BucketSampler.Tape ℓ Ω) : + (fun i => q (BucketSampler.evaluate ℓ eval t i)) = + visibleOutput W q eval (fun v => t v.val) + + tensorOutput W q + (HiddenBucketBias.hiddenSum W eval (fun v => t v.val)) := by + rw [evaluate_eq_direction_sum, tensorOutput_hiddenSum] + exact (Fintype.sum_subtype_add_sum_subtype + (fun v : BucketSampler.Direction ℓ => v.val ∈ W) + (fun v => q (eval (t v)) • v.val)).symm.trans (add_comm _ _) + +theorem evaluate_splitTape (W : Submodule F2 (Fin ℓ → F2)) + (q : Module.Dual F2 H) (eval : Ω → H) (t : BucketSampler.Tape ℓ Ω) : + (fun i => q (BucketSampler.evaluate ℓ eval t i)) = + visibleOutput W q eval (HiddenBucketBias.splitTape W Ω t).2 + + tensorOutput W q + (HiddenBucketBias.hiddenSum W eval (HiddenBucketBias.splitTape W Ω t).1) := + evaluate_split W q eval t + +theorem evaluate_apply_split {A : Type*} + (W : Submodule F2 (Fin ℓ → F2)) (V : Submodule F2 (A → F2)) + (eval : Ω → V) (t : BucketSampler.Tape ℓ Ω) (a : A) : + (fun i => (BucketSampler.evaluate ℓ eval t i).val a) = + visibleOutput W (EvaluationMatrix.evaluation V a) eval + (HiddenBucketBias.splitTape W Ω t).2 + + tensorOutput W (EvaluationMatrix.evaluation V a) + (HiddenBucketBias.hiddenSum W eval (HiddenBucketBias.splitTape W Ω t).1) := + evaluate_splitTape W (EvaluationMatrix.evaluation V a) eval t + +end + +end PerfectCompleteness.TensorBucketEvaluation + + + +namespace PerfectCompleteness.TensorProjectedSlice + +noncomputable section + +open scoped TensorProduct +open UniqueGamesTheorem.Integration.BinaryLinear (F2) + +variable {K H H' : Type*} [AddCommGroup K] [Module F2 K] + [AddCommGroup H] [Module F2 H] [AddCommGroup H'] [Module F2 H'] + [FiniteDimensional F2 H'] + (i : H' →ₗ[F2] H) (W : Submodule F2 K) + +def totalMatrix (X₀ : Module.Dual F2 H →ₗ[F2] K) (T : W ⊗[F2] H') : + Module.Dual F2 H →ₗ[F2] K := + X₀ + W.subtype.comp ((TensorRestriction.tensorEquivHom T).comp i.dualMap) + +@[simp] theorem totalMatrix_apply (X₀ : Module.Dual F2 H →ₗ[F2] K) + (T : W ⊗[F2] H') (z : Module.Dual F2 H) : + totalMatrix i W X₀ T z = + X₀ z + (TensorRestriction.tensorEquivHom T (i.dualMap z) : K) := rfl + +variable (Z : Submodule F2 (Module.Dual F2 H)) + +def Compatible (X₀ : Module.Dual F2 H →ₗ[F2] K) (v : Z →ₗ[F2] K) + (T : W ⊗[F2] H') : Prop := + (totalMatrix i W X₀ T).domRestrict Z = v + +def targetAt (T₀ : W ⊗[F2] H') : + ProjectedColumnSlice.projectedColumns i Z →ₗ[F2] W := + TensorRestriction.restrictionMap (ProjectedColumnSlice.projectedColumns i Z) T₀ + +theorem compatible_iff_restrictionMap_eq + (X₀ : Module.Dual F2 H →ₗ[F2] K) (v : Z →ₗ[F2] K) + (T₀ : W ⊗[F2] H') (h₀ : Compatible i W Z X₀ v T₀) + (T : W ⊗[F2] H') : + Compatible i W Z X₀ v T ↔ + TensorRestriction.restrictionMap (ProjectedColumnSlice.projectedColumns i Z) T = + targetAt i W Z T₀ := by + constructor + · intro hT + apply LinearMap.ext + intro q + obtain ⟨z, rfl⟩ := ProjectedColumnSlice.restrictionZ_surjective i Z q + apply Subtype.ext + have hTz := LinearMap.congr_fun hT z + have h₀z := LinearMap.congr_fun h₀ z + change X₀ z.val + (TensorRestriction.tensorEquivHom T (i.dualMap z.val) : K) = + v z at hTz + change X₀ z.val + (TensorRestriction.tensorEquivHom T₀ (i.dualMap z.val) : K) = + v z at h₀z + exact add_left_cancel (hTz.trans h₀z.symm) + · intro hT + apply LinearMap.ext + intro z + have hz := LinearMap.congr_fun hT (ProjectedColumnSlice.restrictionZ i Z z) + change TensorRestriction.tensorEquivHom T (i.dualMap z.val) = + TensorRestriction.tensorEquivHom T₀ (i.dualMap z.val) at hz + change X₀ z.val + (TensorRestriction.tensorEquivHom T (i.dualMap z.val) : K) = v z + rw [hz] + exact LinearMap.congr_fun h₀ z + +theorem targetAt_comp_restrictionZ + (X₀ : Module.Dual F2 H →ₗ[F2] K) (v : Z →ₗ[F2] K) + (T₀ : W ⊗[F2] H') (h₀ : Compatible i W Z X₀ v T₀) : + W.subtype.comp ((targetAt i W Z T₀).comp + (ProjectedColumnSlice.restrictionZ i Z)) = v - X₀.domRestrict Z := by + apply LinearMap.ext + intro z + have h₀z := LinearMap.congr_fun h₀ z + change X₀ z.val + (TensorRestriction.tensorEquivHom T₀ (i.dualMap z.val) : K) = + v z at h₀z + change (TensorRestriction.tensorEquivHom T₀ (i.dualMap z.val) : K) = v z - X₀ z.val + rw [← h₀z, add_sub_cancel_left] + +theorem targetAt_independent + (X₀ : Module.Dual F2 H →ₗ[F2] K) (v : Z →ₗ[F2] K) + (T₀ T₁ : W ⊗[F2] H') + (h₀ : Compatible i W Z X₀ v T₀) (h₁ : Compatible i W Z X₀ v T₁) : + targetAt i W Z T₀ = targetAt i W Z T₁ := + (compatible_iff_restrictionMap_eq i W Z X₀ v T₁ h₁ T₀).mp h₀ + +def inducedTarget (X₀ : Module.Dual F2 H →ₗ[F2] K) (v : Z →ₗ[F2] K) + (hne : ∃ T : W ⊗[F2] H', Compatible i W Z X₀ v T) : + ProjectedColumnSlice.projectedColumns i Z →ₗ[F2] W := + targetAt i W Z (Classical.choose hne) + +theorem inducedTarget_eq_targetAt + (X₀ : Module.Dual F2 H →ₗ[F2] K) (v : Z →ₗ[F2] K) + (hne : ∃ T : W ⊗[F2] H', Compatible i W Z X₀ v T) + (T₀ : W ⊗[F2] H') (h₀ : Compatible i W Z X₀ v T₀) : + inducedTarget i W Z X₀ v hne = targetAt i W Z T₀ := + targetAt_independent i W Z X₀ v (Classical.choose hne) T₀ + (Classical.choose_spec hne) h₀ + +theorem inducedTarget_comp_restrictionZ + (X₀ : Module.Dual F2 H →ₗ[F2] K) (v : Z →ₗ[F2] K) + (hne : ∃ T : W ⊗[F2] H', Compatible i W Z X₀ v T) : + W.subtype.comp ((inducedTarget i W Z X₀ v hne).comp + (ProjectedColumnSlice.restrictionZ i Z)) = v - X₀.domRestrict Z := + targetAt_comp_restrictionZ i W Z X₀ v (Classical.choose hne) (Classical.choose_spec hne) + +theorem columnEquations_iff_inducedTarget + (X₀ : Module.Dual F2 H →ₗ[F2] K) (v : Z →ₗ[F2] K) + (hne : ∃ T : W ⊗[F2] H', Compatible i W Z X₀ v T) + (T : W ⊗[F2] H') : + (totalMatrix i W X₀ T).domRestrict Z = v ↔ + TensorRestriction.restrictionMap (ProjectedColumnSlice.projectedColumns i Z) T = + inducedTarget i W Z X₀ v hne := + compatible_iff_restrictionMap_eq i W Z X₀ v + (Classical.choose hne) (Classical.choose_spec hne) T + +def sliceEquiv (X₀ : Module.Dual F2 H →ₗ[F2] K) (v : Z →ₗ[F2] K) + (hne : ∃ T : W ⊗[F2] H', Compatible i W Z X₀ v T) : + {T : W ⊗[F2] H' // (totalMatrix i W X₀ T).domRestrict Z = v} ≃ + {T : W ⊗[F2] H' // + TensorRestriction.restrictionMap (ProjectedColumnSlice.projectedColumns i Z) T = + inducedTarget i W Z X₀ v hne} where + toFun T := ⟨T.val, (columnEquations_iff_inducedTarget i W Z X₀ v hne T.val).mp T.property⟩ + invFun T := ⟨T.val, (columnEquations_iff_inducedTarget i W Z X₀ v hne T.val).mpr T.property⟩ + left_inv _ := rfl + right_inv _ := rfl + +omit [FiniteDimensional F2 H'] in +theorem finrank_projectedColumns_le [FiniteDimensional F2 Z] : + Module.finrank F2 (ProjectedColumnSlice.projectedColumns i Z) ≤ Module.finrank F2 Z := + ProjectedColumnSlice.finrank_projectedColumns_le i Z + + +variable {ℓ : Nat} (R : Submodule F2 (Fin ℓ → F2)) + +theorem includedEvaluation_eq_tensorOutputLinear (q : Module.Dual F2 H') : + R.subtype.comp ((LinearMap.applyₗ (R := F2) q).comp + (TensorRestriction.tensorEquivHom (W := R) (H := H')).toLinearMap) = + TensorBucketEvaluation.tensorOutputLinear R q := by + apply TensorProduct.ext' + intro w h + change (TensorRestriction.tensorEquivHom (w ⊗ₜ[F2] h) q : Fin ℓ → F2) = + TensorBucketEvaluation.tensorOutput R q (w ⊗ₜ[F2] h) + rw [TensorRestriction.tensorEquivHom_tmul, TensorBucketEvaluation.tensorOutput_tmul] + rfl + +theorem includedEvaluation_eq_tensorOutput (q : Module.Dual F2 H') + (T : R ⊗[F2] H') : + (TensorRestriction.tensorEquivHom T q : Fin ℓ → F2) = + TensorBucketEvaluation.tensorOutput R q T := + LinearMap.congr_fun (includedEvaluation_eq_tensorOutputLinear R q) T + +theorem prediction_eq_visible_add_tensorOutput + (X₀ : Module.Dual F2 H →ₗ[F2] (Fin ℓ → F2)) + (T : R ⊗[F2] H') (z : Module.Dual F2 H) (u : Fin ℓ → F2) : + totalMatrix i R X₀ T z + u = + (X₀ z + u) + TensorBucketEvaluation.tensorOutput R (i.dualMap z) T := by + rw [totalMatrix_apply, includedEvaluation_eq_tensorOutput] + exact add_right_comm _ _ _ + +end +end PerfectCompleteness.TensorProjectedSlice + + + +namespace PerfectCompleteness.HierarchicalTensorMatrix + +noncomputable section + +open scoped BigOperators TensorProduct Classical +open TreeSourceSpaces HierarchicalArrays + +variable {branch rows : Nat → Nat} {n t : Nat} + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (upper : Nodes branch n) (W : Submodule F2 (Block rows upper)) + +def visibleMatrix + (known : HiddenBucketBias.VisibleDirection W → NodeEmbedding.NodeH slots upper) : + Module.Dual F2 (NodeEmbedding.RowSpace slots upper) →ₗ[F2] Block rows upper := + ∑ v : HiddenBucketBias.VisibleDirection W, + (Module.Dual.eval F2 (NodeEmbedding.RowSpace slots upper) + (NodeEmbedding.embed slots upper (known v))).smulRight v.val.val + +theorem visibleMatrix_apply + (known : HiddenBucketBias.VisibleDirection W → NodeEmbedding.NodeH slots upper) + (q : Module.Dual F2 (NodeEmbedding.RowSpace slots upper)) : + visibleMatrix slots upper W known q = + ∑ v : HiddenBucketBias.VisibleDirection W, + (q.comp (NodeEmbedding.embed slots upper)) (known v) • v.val.val := by + simp only [visibleMatrix, LinearMap.sum_apply, LinearMap.smulRight_apply] + rfl + +variable {Ω : Type*} (eval : Ω → NodeEmbedding.NodeH slots upper) + (tape : BucketSampler.Tape (rows (Nodes.height upper)) Ω) + +theorem matrix_eq_totalMatrix (arrays : Arrays slots rows) + (hrows : BucketSampler.evaluate (rows (Nodes.height upper)) eval tape = arrays upper) : + NodeEmbedding.matrix arrays upper = + TensorProjectedSlice.totalMatrix (NodeEmbedding.embed slots upper) W + (visibleMatrix slots upper W + (fun v => eval ((HiddenBucketBias.splitTape W Ω tape).2 v))) + (HiddenBucketBias.hiddenSum W eval (HiddenBucketBias.splitTape W Ω tape).1) := by + apply LinearMap.ext + intro q + calc + NodeEmbedding.matrix arrays upper q = + (fun i => (q.comp (NodeEmbedding.embed slots upper)) (arrays upper i)) := rfl + _ = (fun i => (q.comp (NodeEmbedding.embed slots upper)) + (BucketSampler.evaluate (rows (Nodes.height upper)) eval tape i)) := by rw [hrows] + _ = TensorBucketEvaluation.visibleOutput W (q.comp (NodeEmbedding.embed slots upper)) + eval (HiddenBucketBias.splitTape W Ω tape).2 + + TensorBucketEvaluation.tensorOutput W (q.comp (NodeEmbedding.embed slots upper)) + (HiddenBucketBias.hiddenSum W eval (HiddenBucketBias.splitTape W Ω tape).1) := + TensorBucketEvaluation.evaluate_splitTape W (q.comp (NodeEmbedding.embed slots upper)) eval tape + _ = _ := by + rw [TensorProjectedSlice.totalMatrix_apply, + TensorProjectedSlice.includedEvaluation_eq_tensorOutput, visibleMatrix_apply] + rfl + +theorem prediction_eq_visible_add_tensorOutput (arrays : Arrays slots rows) + (hrows : BucketSampler.evaluate (rows (Nodes.height upper)) eval tape = arrays upper) + (z : Module.Dual F2 (NodeEmbedding.RowSpace slots upper)) (u : Block rows upper) : + NodeEmbedding.matrix arrays upper z + u = + (visibleMatrix slots upper W + (fun v => eval ((HiddenBucketBias.splitTape W Ω tape).2 v)) z + u) + + TensorBucketEvaluation.tensorOutput W + (z.comp (NodeEmbedding.embed slots upper)) + (HiddenBucketBias.hiddenSum W eval (HiddenBucketBias.splitTape W Ω tape).1) := by + rw [matrix_eq_totalMatrix slots upper W eval tape arrays hrows] + exact TensorProjectedSlice.prediction_eq_visible_add_tensorOutput + (NodeEmbedding.embed slots upper) W _ _ z u + +end +end PerfectCompleteness.HierarchicalTensorMatrix + + + +namespace PerfectCompleteness.TensorTargetCharacter + +noncomputable section + +open scoped TensorProduct +open UniqueGamesTheorem.Integration.BinaryLinear (F2) +open TensorCosetEvaluation (pureFrequency) + +variable {ℓ : Nat} {H : Type*} [AddCommGroup H] [Module F2 H] + +theorem comp_tensorOutputLinear (W : Submodule F2 (Fin ℓ → F2)) + (σ : Module.Dual F2 (Fin ℓ → F2)) (z : Module.Dual F2 H) : + σ.comp (TensorBucketEvaluation.tensorOutputLinear W z) = + pureFrequency (σ.comp W.subtype) z := by + apply TensorProduct.ext' + intro w h + change σ (TensorBucketEvaluation.tensorOutput W z (w ⊗ₜ[F2] h)) = + pureFrequency (σ.comp W.subtype) z (w ⊗ₜ[F2] h) + rw [TensorBucketEvaluation.tensorOutput_tmul, + TensorCosetEvaluation.pureFrequency_tmul, map_smul] + change z h * σ w.val = σ w.val * z h + exact mul_comm _ _ + +theorem apply_tensorOutput (W : Submodule F2 (Fin ℓ → F2)) + (σ : Module.Dual F2 (Fin ℓ → F2)) (z : Module.Dual F2 H) + (X : W ⊗[F2] H) : + σ (TensorBucketEvaluation.tensorOutput W z X) = + pureFrequency (σ.comp W.subtype) z X := + LinearMap.congr_fun (comp_tensorOutputLinear W σ z) X + +theorem character_affine_tensorOutput (W : Submodule F2 (Fin ℓ → F2)) + (χ : AddChar F2 ℝ) (σ : Module.Dual F2 (Fin ℓ → F2)) + (z : Module.Dual F2 H) (offset : Fin ℓ → F2) (X : W ⊗[F2] H) : + χ (σ (offset + TensorBucketEvaluation.tensorOutput W z X)) = + χ (σ offset) * χ (pureFrequency (σ.comp W.subtype) z X) := by + rw [map_add, apply_tensorOutput, χ.map_add_eq_mul] + +theorem sign_affine_tensorOutput (W : Submodule F2 (Fin ℓ → F2)) + (σ : Module.Dual F2 (Fin ℓ → F2)) (z : Module.Dual F2 H) + (offset : Fin ℓ → F2) (X : W ⊗[F2] H) : + HiddenBucketBias.signCharacter + (σ (offset + TensorBucketEvaluation.tensorOutput W z X)) = + HiddenBucketBias.signCharacter (σ offset) * + HiddenBucketBias.signCharacter (pureFrequency (σ.comp W.subtype) z X) := + character_affine_tensorOutput W HiddenBucketBias.signCharacter σ z offset X + +end +end PerfectCompleteness.TensorTargetCharacter + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Algebra/TensorRowAdviceLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Algebra/TensorRowAdviceLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..dd791fa90423efd35e372bdf99d067cd9a87d5ec --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Algebra/TensorRowAdviceLemmas.lean @@ -0,0 +1,541 @@ +import OAI.Computability.PerfectCompleteness.Algebra.TensorBucketEvaluationLemmas +import OAI.Computability.PerfectCompleteness.Foundations.GoodAdviceEventsLemmas +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalFrozenTablesLemmas +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalPrediction + +namespace OAI + + +namespace PerfectCompleteness.TensorRowAdvice + +noncomputable section + +open scoped Classical TensorProduct +open UniqueGamesTheorem.Integration.BinaryLinear (F2) +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype + +section Algebra + +variable {K H H' D : Type*} [AddCommGroup K] [Module F2 K] + [AddCommGroup H] [Module F2 H] [AddCommGroup H'] [Module F2 H'] + [AddCommGroup D] [Module F2 D] [FiniteDimensional F2 H'] + (i : H' →ₗ[F2] H) (W : Submodule F2 K) + +theorem comp_subtype_eq_zero (A : K →ₗ[F2] D) (hW : W ≤ LinearMap.ker A) : + A.comp W.subtype = 0 := by + apply LinearMap.ext + intro w + exact LinearMap.mem_ker.mp (hW w.property) + +theorem rowAdvice_totalMatrix (A : K →ₗ[F2] D) (hW : W ≤ LinearMap.ker A) + (X₀ : Module.Dual F2 H →ₗ[F2] K) (T : W ⊗[F2] H') : + A.comp (TensorProjectedSlice.totalMatrix i W X₀ T) = A.comp X₀ := by + apply LinearMap.ext + intro z + change A (X₀ z + (TensorRestriction.tensorEquivHom T (i.dualMap z) : K)) = A (X₀ z) + rw [map_add] + have hzero : A (TensorRestriction.tensorEquivHom T (i.dualMap z) : K) = 0 := + LinearMap.mem_ker.mp (hW (TensorRestriction.tensorEquivHom T (i.dualMap z)).property) + rw [hzero, add_zero] + +theorem rowAdvice_projectMatrix (A : K →ₗ[F2] D) (hW : W ≤ LinearMap.ker A) + (B : Submodule F2 H) (X₀ : Module.Dual F2 H →ₗ[F2] K) + (T : W ⊗[F2] H') : + A.comp (MatrixRowQuotient.projectMatrix B (TensorProjectedSlice.totalMatrix i W X₀ T)) = + A.comp (MatrixRowQuotient.projectMatrix B X₀) := by + apply LinearMap.ext + intro q + exact LinearMap.congr_fun (rowAdvice_totalMatrix i W A hW X₀ T) (B.mkQ.dualMap q) + +theorem rowAdvice_kernel_totalMatrix (A : K →ₗ[F2] D) + (X₀ : Module.Dual F2 H →ₗ[F2] K) (T : LinearMap.ker A ⊗[F2] H') : + A.comp (TensorProjectedSlice.totalMatrix i (LinearMap.ker A) X₀ T) = A.comp X₀ := + rowAdvice_totalMatrix i (LinearMap.ker A) A le_rfl X₀ T + +end Algebra + +section SelectionCongruence + +variable {E K Y : Type*} [AddCommGroup E] [Module F2 E] + [AddCommGroup K] [Module F2 K] [FiniteDimensional F2 E] + [FiniteDimensional F2 K] [Fintype E] [Fintype K] [Fintype Y] + +omit [FiniteDimensional F2 E] [FiniteDimensional F2 K] [Fintype Y] in +theorem goodRow_iff_of_advice_eq (f : (E →ₗ[F2] K) → Option Y) + (r : Nat) (ρ : ℝ) (A : ManyGoodRows.RowMap K r) (X X₀ : E →ₗ[F2] K) + (hrow : A.comp X = A.comp X₀) : + ManyGoodRows.GoodRow f r ρ A (A.comp X) ↔ + ManyGoodRows.GoodRow f r ρ A (A.comp X₀) := by + rw [hrow] + +omit [FiniteDimensional F2 E] [FiniteDimensional F2 K] [Fintype Y] in +theorem selectedValue_eq_of_advice_eq (f : (E →ₗ[F2] K) → Option Y) + (r : Nat) (ρ : ℝ) (A : ManyGoodRows.RowMap K r) (X X₀ : E →ₗ[F2] K) + (hrow : A.comp X = A.comp X₀) : + HierarchicalPrediction.selectedValue f r ρ A X = + HierarchicalPrediction.selectedValue f r ρ A X₀ := by + exact congrArg + (fun U : E →ₗ[F2] (Fin r → F2) => + if h : ManyGoodRows.GoodRow f r ρ A U then + some (ManyGoodRows.selectWitness f r ρ A U h).value + else none) hrow + +omit [FiniteDimensional F2 E] [FiniteDimensional F2 K] [Fintype Y] in +theorem selectWitness_fields_eq_of_advice_eq (f : (E →ₗ[F2] K) → Option Y) + (r : Nat) (ρ : ℝ) (A : ManyGoodRows.RowMap K r) + (U U₀ : E →ₗ[F2] (Fin r → F2)) (hrow : U = U₀) + (h : ManyGoodRows.GoodRow f r ρ A U) (h₀ : ManyGoodRows.GoodRow f r ρ A U₀) : + (ManyGoodRows.selectWitness f r ρ A U h).columnSpace = + (ManyGoodRows.selectWitness f r ρ A U₀ h₀).columnSpace ∧ + (ManyGoodRows.selectWitness f r ρ A U h).base = + (ManyGoodRows.selectWitness f r ρ A U₀ h₀).base ∧ + (ManyGoodRows.selectWitness f r ρ A U h).value = + (ManyGoodRows.selectWitness f r ρ A U₀ h₀).value := by + cases hrow + exact ⟨rfl, rfl, rfl⟩ + +end SelectionCongruence + + +variable {K H H' Y : Type*} [AddCommGroup K] [Module F2 K] + [AddCommGroup H] [Module F2 H] [AddCommGroup H'] [Module F2 H'] + [FiniteDimensional F2 H'] [FiniteDimensional F2 H] [FiniteDimensional F2 K] + [Fintype H] [Fintype K] [Fintype Y] + (i : H' →ₗ[F2] H) (W : Submodule F2 K) + {r : Nat} (A : ManyGoodRows.RowMap K r) (hW : W ≤ LinearMap.ker A) + +include hW + +omit [FiniteDimensional F2 H] [FiniteDimensional F2 K] [Fintype Y] in +theorem goodRow_totalMatrix_iff + (f : (Module.Dual F2 H →ₗ[F2] K) → Option Y) (ρ : ℝ) + (X₀ : Module.Dual F2 H →ₗ[F2] K) (T : W ⊗[F2] H') : + ManyGoodRows.GoodRow f r ρ A (A.comp (TensorProjectedSlice.totalMatrix i W X₀ T)) ↔ + ManyGoodRows.GoodRow f r ρ A (A.comp X₀) := + goodRow_iff_of_advice_eq f r ρ A _ _ (rowAdvice_totalMatrix i W A hW X₀ T) + +omit [FiniteDimensional F2 H] [FiniteDimensional F2 K] [Fintype Y] in +theorem selectedValue_totalMatrix_eq + (f : (Module.Dual F2 H →ₗ[F2] K) → Option Y) (ρ : ℝ) + (X₀ : Module.Dual F2 H →ₗ[F2] K) (T : W ⊗[F2] H') : + HierarchicalPrediction.selectedValue f r ρ A (TensorProjectedSlice.totalMatrix i W X₀ T) = + HierarchicalPrediction.selectedValue f r ρ A X₀ := + selectedValue_eq_of_advice_eq f r ρ A _ _ (rowAdvice_totalMatrix i W A hW X₀ T) + +omit [FiniteDimensional F2 H] [FiniteDimensional F2 K] [Fintype Y] in +theorem goodRow_projectMatrix_iff (B : Submodule F2 H) + (f : (Module.Dual F2 (H ⧸ B) →ₗ[F2] K) → Option Y) (ρ : ℝ) + (X₀ : Module.Dual F2 H →ₗ[F2] K) (T : W ⊗[F2] H') : + ManyGoodRows.GoodRow f r ρ A + (A.comp (MatrixRowQuotient.projectMatrix B + (TensorProjectedSlice.totalMatrix i W X₀ T))) ↔ + ManyGoodRows.GoodRow f r ρ A (A.comp (MatrixRowQuotient.projectMatrix B X₀)) := + goodRow_iff_of_advice_eq f r ρ A _ _ (rowAdvice_projectMatrix i W A hW B X₀ T) + +omit [FiniteDimensional F2 H] [FiniteDimensional F2 K] [Fintype Y] in +theorem selectedValue_projectMatrix_eq (B : Submodule F2 H) + (f : (Module.Dual F2 (H ⧸ B) →ₗ[F2] K) → Option Y) (ρ : ℝ) + (X₀ : Module.Dual F2 H →ₗ[F2] K) (T : W ⊗[F2] H') : + HierarchicalPrediction.selectedValue f r ρ A + (MatrixRowQuotient.projectMatrix B (TensorProjectedSlice.totalMatrix i W X₀ T)) = + HierarchicalPrediction.selectedValue f r ρ A (MatrixRowQuotient.projectMatrix B X₀) := + selectedValue_eq_of_advice_eq f r ρ A _ _ (rowAdvice_projectMatrix i W A hW B X₀ T) + +omit [FiniteDimensional F2 H] [FiniteDimensional F2 K] [Fintype Y] in +theorem selectWitness_projectMatrix_fields_eq (B : Submodule F2 H) + (f : (Module.Dual F2 (H ⧸ B) →ₗ[F2] K) → Option Y) (ρ : ℝ) + (X₀ : Module.Dual F2 H →ₗ[F2] K) (T : W ⊗[F2] H') + (h : ManyGoodRows.GoodRow f r ρ A + (A.comp (MatrixRowQuotient.projectMatrix B (TensorProjectedSlice.totalMatrix i W X₀ T)))) + (h₀ : ManyGoodRows.GoodRow f r ρ A (A.comp (MatrixRowQuotient.projectMatrix B X₀))) : + (ManyGoodRows.selectWitness f r ρ A + (A.comp (MatrixRowQuotient.projectMatrix B (TensorProjectedSlice.totalMatrix i W X₀ T))) h).columnSpace = + (ManyGoodRows.selectWitness f r ρ A (A.comp (MatrixRowQuotient.projectMatrix B X₀)) h₀).columnSpace ∧ + (ManyGoodRows.selectWitness f r ρ A + (A.comp (MatrixRowQuotient.projectMatrix B (TensorProjectedSlice.totalMatrix i W X₀ T))) h).base = + (ManyGoodRows.selectWitness f r ρ A (A.comp (MatrixRowQuotient.projectMatrix B X₀)) h₀).base ∧ + (ManyGoodRows.selectWitness f r ρ A + (A.comp (MatrixRowQuotient.projectMatrix B (TensorProjectedSlice.totalMatrix i W X₀ T))) h).value = + (ManyGoodRows.selectWitness f r ρ A (A.comp (MatrixRowQuotient.projectMatrix B X₀)) h₀).value := + selectWitness_fields_eq_of_advice_eq f r ρ A _ _ + (rowAdvice_projectMatrix i W A hW B X₀ T) h h₀ + +end +end PerfectCompleteness.TensorRowAdvice + + + +namespace PerfectCompleteness.TensorSelectedSlice + +noncomputable section + +open scoped Classical TensorProduct +open UniqueGamesTheorem.Integration.BinaryLinear (F2) +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype + +variable {K H H' Y : Type*} [AddCommGroup K] [Module F2 K] + [AddCommGroup H] [Module F2 H] [AddCommGroup H'] [Module F2 H'] + [FiniteDimensional F2 H'] [FiniteDimensional F2 H] [FiniteDimensional F2 K] + [Fintype H] [Fintype K] [Fintype Y] + (i : H' →ₗ[F2] H) (W : Submodule F2 K) (B : Submodule F2 H) + +abbrev projectedMatrix (X₀ : Module.Dual F2 H →ₗ[F2] K) (T : W ⊗[F2] H') := + MatrixRowQuotient.projectMatrix B (TensorProjectedSlice.totalMatrix i W X₀ T) + +omit [FiniteDimensional F2 H] [FiniteDimensional F2 K] [Fintype H] [Fintype K] in +theorem projectedMatrix_eq_totalMatrix + (X₀ : Module.Dual F2 H →ₗ[F2] K) (T : W ⊗[F2] H') : + projectedMatrix i W B X₀ T = + TensorProjectedSlice.totalMatrix (B.mkQ.comp i) W + (MatrixRowQuotient.projectMatrix B X₀) T := by + apply LinearMap.ext + intro q + rfl + +variable (f : (Module.Dual F2 (H ⧸ B) →ₗ[F2] K) → Option Y) + (r : Nat) (ρ : ℝ) (A : ManyGoodRows.RowMap K r) + (X₀ : Module.Dual F2 H →ₗ[F2] K) + +def witness + (hgood : ManyGoodRows.GoodRow f r ρ A (A.comp (MatrixRowQuotient.projectMatrix B X₀))) : + ManyGoodRows.Witness f r ρ A (A.comp (MatrixRowQuotient.projectMatrix B X₀)) := + ManyGoodRows.selectWitness f r ρ A (A.comp (MatrixRowQuotient.projectMatrix B X₀)) hgood + +def columnSpace + (hgood : ManyGoodRows.GoodRow f r ρ A (A.comp (MatrixRowQuotient.projectMatrix B X₀))) : + Submodule F2 (Module.Dual F2 H') := + ProjectedColumnSlice.projectedColumns (B.mkQ.comp i) + (witness B f r ρ A X₀ hgood).columnSpace + +omit [FiniteDimensional F2 H'] [FiniteDimensional F2 H] [FiniteDimensional F2 K] [Fintype Y] in +theorem columnSpace_eq_sequential_maps + (hgood : ManyGoodRows.GoodRow f r ρ A (A.comp (MatrixRowQuotient.projectMatrix B X₀))) : + columnSpace i B f r ρ A X₀ hgood = + ((witness B f r ρ A X₀ hgood).columnSpace.map B.mkQ.dualMap).map i.dualMap := by + unfold columnSpace ProjectedColumnSlice.projectedColumns + exact Submodule.map_comp B.mkQ.dualMap i.dualMap _ + +omit [FiniteDimensional F2 H'] [FiniteDimensional F2 K] [Fintype Y] in +theorem finrank_columnSpace_le + (hgood : ManyGoodRows.GoodRow f r ρ A (A.comp (MatrixRowQuotient.projectMatrix B X₀))) : + Module.finrank F2 (columnSpace i B f r ρ A X₀ hgood) ≤ r := + (ProjectedColumnSlice.finrank_projectedColumns_le (B.mkQ.comp i) + (witness B f r ρ A X₀ hgood).columnSpace).trans + (witness B f r ρ A X₀ hgood).column_count + +variable (hW : W ≤ LinearMap.ker A) + +include hW + +omit [FiniteDimensional F2 H] [FiniteDimensional F2 K] [Fintype Y] in +theorem J_eq_decide_columns + (hgood : ManyGoodRows.GoodRow f r ρ A (A.comp (MatrixRowQuotient.projectMatrix B X₀))) + (T : W ⊗[F2] H') : + GoodAdviceEvents.J f r ρ (A, projectedMatrix i W B X₀ T) = + decide ((projectedMatrix i W B X₀ T).domRestrict + (witness B f r ρ A X₀ hgood).columnSpace = + (witness B f r ρ A X₀ hgood).base.domRestrict + (witness B f r ρ A X₀ hgood).columnSpace) := by + change GoodAdviceEvents.selectedColumn f r ρ A + (A.comp (projectedMatrix i W B X₀ T)) (projectedMatrix i W B X₀ T) = _ + unfold GoodAdviceEvents.selectedColumn + have hrow : A.comp (projectedMatrix i W B X₀ T) = + A.comp (MatrixRowQuotient.projectMatrix B X₀) := + TensorRowAdvice.rowAdvice_projectMatrix i W A hW B X₀ T + rw [hrow] + simp only [dite_eq_left hgood, witness] + exact decide_eq_decide.mpr Iff.rfl + +omit [FiniteDimensional F2 H] [FiniteDimensional F2 K] [Fintype Y] in +theorem J_false_of_not_good + (hbad : ¬ ManyGoodRows.GoodRow f r ρ A (A.comp (MatrixRowQuotient.projectMatrix B X₀))) + (T : W ⊗[F2] H') : + GoodAdviceEvents.J f r ρ (A, projectedMatrix i W B X₀ T) = false := by + change GoodAdviceEvents.selectedColumn f r ρ A + (A.comp (projectedMatrix i W B X₀ T)) (projectedMatrix i W B X₀ T) = false + unfold GoodAdviceEvents.selectedColumn + have hrow : A.comp (projectedMatrix i W B X₀ T) = + A.comp (MatrixRowQuotient.projectMatrix B X₀) := + TensorRowAdvice.rowAdvice_projectMatrix i W A hW B X₀ T + rw [hrow] + exact dite_eq_right hbad + +omit [FiniteDimensional F2 H] [FiniteDimensional F2 K] [Fintype Y] in +theorem J_iff_compatible + (hgood : ManyGoodRows.GoodRow f r ρ A (A.comp (MatrixRowQuotient.projectMatrix B X₀))) + (T : W ⊗[F2] H') : + GoodAdviceEvents.J f r ρ (A, projectedMatrix i W B X₀ T) = true ↔ + TensorProjectedSlice.Compatible (B.mkQ.comp i) W + (witness B f r ρ A X₀ hgood).columnSpace + (MatrixRowQuotient.projectMatrix B X₀) + ((witness B f r ρ A X₀ hgood).base.domRestrict + (witness B f r ρ A X₀ hgood).columnSpace) T := by + calc + _ ↔ (projectedMatrix i W B X₀ T).domRestrict + (witness B f r ρ A X₀ hgood).columnSpace = + (witness B f r ρ A X₀ hgood).base.domRestrict + (witness B f r ρ A X₀ hgood).columnSpace := by + rw [J_eq_decide_columns i W B f r ρ A X₀ hW hgood T, decide_eq_true_eq] + _ ↔ _ := Iff.of_eq (congrArg + (fun X : Module.Dual F2 (H ⧸ B) →ₗ[F2] K => + X.domRestrict (witness B f r ρ A X₀ hgood).columnSpace = + (witness B f r ρ A X₀ hgood).base.domRestrict + (witness B f r ρ A X₀ hgood).columnSpace) + (projectedMatrix_eq_totalMatrix i W B X₀ T)) + +omit [FiniteDimensional F2 H] [FiniteDimensional F2 K] [Fintype Y] in +theorem exists_compatible + (hgood : ManyGoodRows.GoodRow f r ρ A (A.comp (MatrixRowQuotient.projectMatrix B X₀))) + (hne : ∃ T : W ⊗[F2] H', GoodAdviceEvents.J f r ρ (A, projectedMatrix i W B X₀ T) = true) : + ∃ T : W ⊗[F2] H', TensorProjectedSlice.Compatible (B.mkQ.comp i) W + (witness B f r ρ A X₀ hgood).columnSpace + (MatrixRowQuotient.projectMatrix B X₀) + ((witness B f r ρ A X₀ hgood).base.domRestrict + (witness B f r ρ A X₀ hgood).columnSpace) T := by + obtain ⟨T, hT⟩ := hne + exact ⟨T, (J_iff_compatible i W B f r ρ A X₀ hW hgood T).mp hT⟩ + +def target + (hgood : ManyGoodRows.GoodRow f r ρ A (A.comp (MatrixRowQuotient.projectMatrix B X₀))) + (hne : ∃ T : W ⊗[F2] H', GoodAdviceEvents.J f r ρ (A, projectedMatrix i W B X₀ T) = true) : + columnSpace i B f r ρ A X₀ hgood →ₗ[F2] W := + TensorProjectedSlice.inducedTarget (B.mkQ.comp i) W + (witness B f r ρ A X₀ hgood).columnSpace + (MatrixRowQuotient.projectMatrix B X₀) + ((witness B f r ρ A X₀ hgood).base.domRestrict + (witness B f r ρ A X₀ hgood).columnSpace) + (exists_compatible i W B f r ρ A X₀ hW hgood hne) + +omit [FiniteDimensional F2 H] [FiniteDimensional F2 K] [Fintype Y] in +theorem J_iff_restriction + (hgood : ManyGoodRows.GoodRow f r ρ A (A.comp (MatrixRowQuotient.projectMatrix B X₀))) + (hne : ∃ T : W ⊗[F2] H', GoodAdviceEvents.J f r ρ (A, projectedMatrix i W B X₀ T) = true) + (T : W ⊗[F2] H') : + GoodAdviceEvents.J f r ρ (A, projectedMatrix i W B X₀ T) = true ↔ + TensorRestriction.restrictionMap (columnSpace i B f r ρ A X₀ hgood) T = + target i W B f r ρ A X₀ hW hgood hne := + (J_iff_compatible i W B f r ρ A X₀ hW hgood T).trans + (TensorProjectedSlice.columnEquations_iff_inducedTarget (B.mkQ.comp i) W + (witness B f r ρ A X₀ hgood).columnSpace + (MatrixRowQuotient.projectMatrix B X₀) + ((witness B f r ρ A X₀ hgood).base.domRestrict + (witness B f r ρ A X₀ hgood).columnSpace) + (exists_compatible i W B f r ρ A X₀ hW hgood hne) T) + +omit [FiniteDimensional F2 K] [Fintype Y] in +theorem exists_tensor_slice + (hgood : ManyGoodRows.GoodRow f r ρ A (A.comp (MatrixRowQuotient.projectMatrix B X₀))) + (hne : ∃ T : W ⊗[F2] H', GoodAdviceEvents.J f r ρ (A, projectedMatrix i W B X₀ T) = true) : + ∃ (Q : Submodule F2 (Module.Dual F2 H')) (t : Q →ₗ[F2] W), + Module.finrank F2 Q ≤ r ∧ + ∀ T : W ⊗[F2] H', GoodAdviceEvents.J f r ρ (A, projectedMatrix i W B X₀ T) = true ↔ + TensorRestriction.restrictionMap Q T = t := by + exact ⟨columnSpace i B f r ρ A X₀ hgood, + target i W B f r ρ A X₀ hW hgood hne, + finrank_columnSpace_le i B f r ρ A X₀ hgood, + J_iff_restriction i W B f r ρ A X₀ hW hgood hne⟩ + +end +end PerfectCompleteness.TensorSelectedSlice + + + +namespace PerfectCompleteness.HierarchicalTensorSlice + +noncomputable section + +open scoped Classical TensorProduct +open TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype + +variable {branch rows : Nat → Nat} {n t : Nat} + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (upper : Nodes branch n) (lowerLevel : Nat) + (background : HierarchicalMatrixTable.Background (rows := rows) slots upper) + +local instance rowSpaceFintype : Fintype (NodeEmbedding.RowSpace slots upper) := + Fintype.ofFinite _ + +local instance valueFintype : Fintype + (Block rows upper × HierarchicalMatrixTable.SideOutput (rows := rows) upper) := + Fintype.ofFinite _ + +variable {Ω : Type*} [Fintype Ω] + (original : FiniteDistribution Ω) (arrays : Ω → Arrays slots rows) + (lowerEvent : Ω → Bool) (κ : ℝ) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + {r : Nat} (ρ : ℝ) (A : ManyGoodRows.RowMap (Block rows upper) r) + (known : HiddenBucketBias.VisibleDirection (LinearMap.ker A) → NodeEmbedding.NodeH slots upper) + +abbrev HiddenTensor := LinearMap.ker A ⊗[F2] NodeEmbedding.NodeH slots upper + +abbrev visibleMatrix := HierarchicalTensorMatrix.visibleMatrix slots upper (LinearMap.ker A) known + +abbrev matrix (T : HiddenTensor slots upper A) := + TensorProjectedSlice.totalMatrix (NodeEmbedding.embed slots upper) (LinearMap.ker A) + (visibleMatrix slots upper A known) T + +abbrev quotientMatrix (T : HiddenTensor slots upper A) := + MatrixRowQuotient.projectMatrix + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + (matrix slots upper A known T) + +abbrev table := + HierarchicalUsefulness.table slots upper lowerLevel original arrays lowerEvent κ σ background + +abbrev VisibleGood : Prop := + ManyGoodRows.GoodRow (table slots upper lowerLevel background original arrays lowerEvent κ σ) + r ρ A (A.comp (MatrixRowQuotient.projectMatrix + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + (visibleMatrix slots upper A known))) + +def witness + (hgood : VisibleGood slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known) := + TensorSelectedSlice.witness + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + (table slots upper lowerLevel background original arrays lowerEvent κ σ) + r ρ A (visibleMatrix slots upper A known) hgood + +def columnSpace + (hgood : VisibleGood slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known) : + Submodule F2 (Module.Dual F2 (NodeEmbedding.NodeH slots upper)) := + TensorSelectedSlice.columnSpace (NodeEmbedding.embed slots upper) + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + (table slots upper lowerLevel background original arrays lowerEvent κ σ) + r ρ A (visibleMatrix slots upper A known) hgood + +theorem columnSpace_eq_pulled + (hgood : VisibleGood slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known) : + columnSpace slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood = + ((witness slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood).columnSpace.map + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background).mkQ.dualMap).map + (NodeEmbedding.embed slots upper).dualMap := + TensorSelectedSlice.columnSpace_eq_sequential_maps (NodeEmbedding.embed slots upper) + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + (table slots upper lowerLevel background original arrays lowerEvent κ σ) + r ρ A (visibleMatrix slots upper A known) hgood + +theorem finrank_columnSpace_le + (hgood : VisibleGood slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known) : + Module.finrank F2 + (columnSpace slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood) ≤ r := + TensorSelectedSlice.finrank_columnSpace_le (NodeEmbedding.embed slots upper) + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + (table slots upper lowerLevel background original arrays lowerEvent κ σ) + r ρ A (visibleMatrix slots upper A known) hgood + +def J (T : HiddenTensor slots upper A) : Bool := + GoodAdviceEvents.J (table slots upper lowerLevel background original arrays lowerEvent κ σ) + r ρ (A, quotientMatrix slots upper lowerLevel background A known T) + +def target + (hgood : VisibleGood slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known) + (hne : ∃ T, J slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known T = true) : + columnSpace slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood →ₗ[F2] + LinearMap.ker A := + TensorSelectedSlice.target (NodeEmbedding.embed slots upper) (LinearMap.ker A) + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + (table slots upper lowerLevel background original arrays lowerEvent κ σ) + r ρ A (visibleMatrix slots upper A known) le_rfl hgood hne + +theorem J_iff_restriction + (hgood : VisibleGood slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known) + (hne : ∃ T, J slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known T = true) + (T : HiddenTensor slots upper A) : + J slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known T = true ↔ + TensorRestriction.restrictionMap + (columnSpace slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood) T = + target slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood hne := + TensorSelectedSlice.J_iff_restriction (NodeEmbedding.embed slots upper) (LinearMap.ker A) + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + (table slots upper lowerLevel background original arrays lowerEvent κ σ) + r ρ A (visibleMatrix slots upper A known) le_rfl hgood hne T + +theorem J_false_of_not_good + (hbad : ¬ VisibleGood slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known) + (T : HiddenTensor slots upper A) : + J slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known T = false := + TensorSelectedSlice.J_false_of_not_good (NodeEmbedding.embed slots upper) (LinearMap.ker A) + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + (table slots upper lowerLevel background original arrays lowerEvent κ σ) + r ρ A (visibleMatrix slots upper A known) le_rfl hbad T + +theorem selectedValue_eq_some + (hgood : VisibleGood slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known) + (T : HiddenTensor slots upper A) : + HierarchicalPrediction.selectedValue + (table slots upper lowerLevel background original arrays lowerEvent κ σ) r ρ A + (quotientMatrix slots upper lowerLevel background A known T) = + some (witness slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood).value := by + change HierarchicalPrediction.selectedValue _ r ρ A + (MatrixRowQuotient.projectMatrix _ (TensorProjectedSlice.totalMatrix _ _ _ T)) = _ + rw [TensorRowAdvice.selectedValue_projectMatrix_eq (NodeEmbedding.embed slots upper) + (LinearMap.ker A) A le_rfl + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + (table slots upper lowerLevel background original arrays lowerEvent κ σ) ρ + (visibleMatrix slots upper A known) T] + simp only [HierarchicalPrediction.selectedValue, dite_eq_left hgood, witness, + TensorSelectedSlice.witness] + +def correction + (y : Block rows upper × HierarchicalMatrixTable.SideOutput (rows := rows) upper) : + Module.Dual F2 (NodeEmbedding.RowSpace slots upper) := + RepresentativeMatrixTable.correctionFunctional (TreeCanonical.numberedSlots slots) + (NodeEmbedding.RowSpace slots upper) (HierarchicalMatrixTable.other slots upper background) + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + (HierarchicalFrozenTables.sectionMap slots upper lowerLevel background) + (HierarchicalFrozenTables.sectionMap_spec slots upper lowerLevel background) y.2 + +def nativeCorrection + (hgood : VisibleGood slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known) : + Module.Dual F2 (NodeEmbedding.NodeH slots upper) := + (correction slots upper lowerLevel background + (witness slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood).value).comp + (NodeEmbedding.embed slots upper) + +def visibleOffset + (hgood : VisibleGood slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known) : + Block rows upper := + visibleMatrix slots upper A known + (correction slots upper lowerLevel background + (witness slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood).value) + + (witness slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood).value.1 + +theorem selectedCorrection_eq_some + (hgood : VisibleGood slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known) + (T : HiddenTensor slots upper A) : + (HierarchicalPrediction.selectedValue + (table slots upper lowerLevel background original arrays lowerEvent κ σ) r ρ A + (quotientMatrix slots upper lowerLevel background A known T)).map + (fun y => (correction slots upper lowerLevel background y).comp + (NodeEmbedding.embed slots upper)) = + some (nativeCorrection slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood) := by + simp only [selectedValue_eq_some slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood T, + Option.map_some, nativeCorrection] + +theorem affinePrediction_eq_tensor + (hgood : VisibleGood slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known) + (T : HiddenTensor slots upper A) : + HierarchicalPrediction.affinePrediction slots upper lowerLevel background + (matrix slots upper A known T) + (witness slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood).value = + visibleOffset slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood + + TensorBucketEvaluation.tensorOutput (LinearMap.ker A) + (nativeCorrection slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood) T := + TensorProjectedSlice.prediction_eq_visible_add_tensorOutput (NodeEmbedding.embed slots upper) + (LinearMap.ker A) (visibleMatrix slots upper A known) T + (correction slots upper lowerLevel background + (witness slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood).value) + (witness slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood).value.1 + +end +end PerfectCompleteness.HierarchicalTensorSlice + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Algebra/TensorSliceDimension.lean b/lean/OAI/Computability/PerfectCompleteness/Algebra/TensorSliceDimension.lean new file mode 100644 index 0000000000000000000000000000000000000000..01fdfeb5d0e419a54c7e1517dd018683b2ce2b1b --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Algebra/TensorSliceDimension.lean @@ -0,0 +1,85 @@ +import Mathlib.Algebra.Order.Field.Basic +import Mathlib.Basic.Real.Basic +import Mathlib.LinearAlgebra.FreeModule.Finite.Matrix +import Mathlib.Tactic.NormNum +import OAI.Computability.PerfectCompleteness.Algebra.BilinearGramCompressionLemmas + +namespace OAI + + +namespace PerfectCompleteness.TensorSliceDimension + +noncomputable section + +open UniqueGamesTheorem.Integration.BinaryLinear (F2) + +theorem mask_card (n : Nat) : Fintype.card (Fin n → Bool) = 2 ^ n := by + simp only [Fintype.card_fun, Fintype.card_bool, Fintype.card_fin] + +theorem mask_card_le {n N : Nat} (h : n ≤ N) : + Fintype.card (Fin n → Bool) ≤ 2 ^ N := by + rw [mask_card] + exact Nat.pow_le_pow_right (by decide : 0 < 2) h + +theorem reciprocal_mask_card_ge {n N : Nat} (h : n ≤ N) : + 1 / (2 ^ N : ℝ) ≤ 1 / (Fintype.card (Fin n → Bool) : ℝ) := by + simpa only [mask_card, Nat.cast_pow, Nat.cast_ofNat] using + (one_div_pow_le_one_div_pow_of_le (by norm_num : (1 : ℝ) ≤ 2) h) + +section GeneralEquationSpace + +variable {Q W : Type*} [AddCommGroup Q] [Module F2 Q] + [AddCommGroup W] [Module F2 W] + [FiniteDimensional F2 Q] [FiniteDimensional F2 W] + +theorem linearMap_finrank_le {r ℓ : Nat} + (hQ : Module.finrank F2 Q ≤ r) (hW : Module.finrank F2 W ≤ ℓ) : + Module.finrank F2 (Q →ₗ[F2] W) ≤ r * ℓ := by + rw [Module.finrank_linearMap] + exact Nat.mul_le_mul hQ hW + +theorem reciprocal_linearMap_masks_ge {r ℓ : Nat} + (hQ : Module.finrank F2 Q ≤ r) (hW : Module.finrank F2 W ≤ ℓ) : + 1 / (2 ^ (r * ℓ) : ℝ) ≤ + 1 / (Fintype.card (Fin (Module.finrank F2 (Q →ₗ[F2] W)) → Bool) : ℝ) := + reciprocal_mask_card_ge (linearMap_finrank_le hQ hW) + +end GeneralEquationSpace + +variable {H : Type*} [AddCommGroup H] [Module F2 H] [FiniteDimensional F2 H] + {ℓ : Nat} (W : Submodule F2 (Fin ℓ → F2)) + (Q : Submodule F2 (Module.Dual F2 H)) + +theorem row_finrank_le : Module.finrank F2 W ≤ ℓ := by + simpa only [Module.finrank_fin_fun] using (Submodule.finrank_le W) + +theorem equation_finrank_le {r : Nat} (hQ : Module.finrank F2 Q ≤ r) : + Module.finrank F2 (Q →ₗ[F2] W) ≤ r * ℓ := + linearMap_finrank_le (Q := Q) (W := W) hQ (row_finrank_le W) + +theorem equation_mask_card : + Fintype.card (Fin (Module.finrank F2 (Q →ₗ[F2] W)) → Bool) = + 2 ^ (Module.finrank F2 Q * Module.finrank F2 W) := by + let : Module.Free F2 Q := Module.Free.of_divisionRing F2 Q + let : Module.Free F2 W := Module.Free.of_divisionRing F2 W + rw [mask_card, Module.finrank_linearMap F2 F2 Q W] + +theorem equation_mask_card_le {r : Nat} (hQ : Module.finrank F2 Q ≤ r) : + Fintype.card (Fin (Module.finrank F2 (Q →ₗ[F2] W)) → Bool) ≤ 2 ^ (r * ℓ) := + mask_card_le (equation_finrank_le W Q hQ) + +theorem reciprocal_equation_mask_card_ge {r : Nat} (hQ : Module.finrank F2 Q ≤ r) : + 1 / (2 ^ (r * ℓ) : ℝ) ≤ + 1 / (Fintype.card (Fin (Module.finrank F2 (Q →ₗ[F2] W)) → Bool) : ℝ) := + reciprocal_mask_card_ge (equation_finrank_le W Q hQ) + +theorem restriction_finrank_le {r : Nat} (hQ : Module.finrank F2 Q ≤ r) : + Module.finrank F2 (LinearMap.range (TensorRestriction.restrictionMap (W := W) Q)) ≤ + r * ℓ := by + rw [TensorRestriction.finrank_range, Nat.mul_comm] + exact Nat.mul_le_mul hQ (row_finrank_le W) + +end +end PerfectCompleteness.TensorSliceDimension + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Algebra/UniformLinearImage.lean b/lean/OAI/Computability/PerfectCompleteness/Algebra/UniformLinearImage.lean new file mode 100644 index 0000000000000000000000000000000000000000..b4b94b64c1d1f776252856903713a5866f296763 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Algebra/UniformLinearImage.lean @@ -0,0 +1,113 @@ +import Mathlib.GroupTheory.Index +import Mathlib.LinearAlgebra.Pi +import OAI.Computability.PerfectCompleteness.Foundations.FiniteProduct +import OAI.Computability.UniqueGames.Foundations.SamplingLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.UniformLinearImage + +open scoped BigOperators +open UniqueGamesTheorem.Foundations.Games + +noncomputable section + +theorem eq_uniform_of_weight_constant {A : Type*} [Fintype A] [Nonempty A] + (μ : FiniteDistribution A) (constant : ∀ x y, μ.weight x = μ.weight y) : + μ = FiniteDistribution.uniform A := by + apply FiniteDistribution.eq_of_weight_eq + intro x + change μ.weight x = 1 / (Fintype.card A : ℝ) + apply (eq_div_iff (Nat.cast_ne_zero.mpr Fintype.card_ne_zero)).mpr + calc + μ.weight x * (Fintype.card A : ℝ) = ∑ _y : A, μ.weight x := by + simp [mul_comm] + _ = ∑ y : A, μ.weight y := by + apply Finset.sum_congr rfl + intro y _ + exact constant x y + _ = 1 := μ.normalized + +theorem uniform_pushforward_weight {A B : Type*} [Fintype A] [Nonempty A] + [Fintype B] [DecidableEq B] (f : A → B) (y : B) : + ((FiniteDistribution.uniform A).pushforward f).weight y = + ((Finset.univ.filter (fun x => f x = y)).card : ℝ) / Fintype.card A := by + classical + calc + _ = ∑ x : A, if f x = y then (1 / (Fintype.card A : ℝ)) else 0 := by + unfold FiniteDistribution.pushforward FiniteDistribution.uniform + apply Finset.sum_congr rfl + intro x _ + by_cases h : f x = y <;> simp [h] + _ = _ := by + rw [← Finset.sum_filter] + simp [nsmul_eq_mul, div_eq_mul_inv] + +theorem uniform_pushforward_addHom {A B : Type*} + [AddGroup A] [AddMonoid B] [Fintype A] [Fintype B] + (f : A →+ B) (surjective : Function.Surjective f) : + (FiniteDistribution.uniform A).pushforward f = FiniteDistribution.uniform B := by + classical + apply eq_uniform_of_weight_constant + intro y z + rw [uniform_pushforward_weight, uniform_pushforward_weight, + AddMonoidHom.card_fiber_eq_of_mem_range f (surjective y) (surjective z)] + +theorem uniform_pushforward_linearMap {R A B : Type*} [Semiring R] + [AddCommGroup A] [AddCommMonoid B] [Module R A] [Module R B] + [Fintype A] [Fintype B] (f : A →ₗ[R] B) (surjective : Function.Surjective f) : + (FiniteDistribution.uniform A).pushforward f = FiniteDistribution.uniform B := + uniform_pushforward_addHom f.toAddMonoidHom surjective + +section Product + +variable {I : Type*} [Fintype I] [DecidableEq I] + {Ω : I → Type*} [∀ i, Fintype (Ω i)] + +theorem law_uniform [∀ i, Nonempty (Ω i)] : + FiniteProduct.law (fun i => FiniteDistribution.uniform (Ω i)) = + FiniteDistribution.uniform ((i : I) → Ω i) := by + apply FiniteDistribution.eq_of_weight_eq + intro x + change (∏ i, 1 / (Fintype.card (Ω i) : ℝ)) = + 1 / (Fintype.card ((i : I) → Ω i) : ℝ) + simp only [Fintype.card_pi, Nat.cast_prod, Finset.prod_div_distrib, + Finset.prod_const_one] + +variable {R V : Type*} [Semiring R] [AddCommGroup V] [Module R V] + [∀ i, AddCommGroup (Ω i)] [∀ i, Module R (Ω i)] + +def linearSum (maps : (i : I) → Ω i →ₗ[R] V) : ((i : I) → Ω i) →ₗ[R] V where + toFun x := ∑ i, maps i (x i) + map_add' x y := by simp only [Pi.add_apply, map_add, Finset.sum_add_distrib] + map_smul' c x := by simp only [Pi.smul_apply, map_smul, Finset.smul_sum, + RingHom.id_apply] + +omit [DecidableEq I] [∀ index, Fintype (Ω index)] in +@[simp] theorem linearSum_apply (maps : (i : I) → Ω i →ₗ[R] V) + (x : (i : I) → Ω i) : linearSum maps x = ∑ i, maps i (x i) := rfl + +variable [Fintype V] + +theorem product_uniform_linear_image (f : ((i : I) → Ω i) →ₗ[R] V) + (surjective : Function.Surjective f) : + (FiniteProduct.law (fun i => FiniteDistribution.uniform (Ω i))).pushforward f = + FiniteDistribution.uniform V := by + rw [law_uniform] + exact uniform_pushforward_linearMap f surjective + +theorem product_uniform_sum_image (maps : (i : I) → Ω i →ₗ[R] V) + (surjective : Function.Surjective (linearSum maps)) : + (FiniteProduct.law (fun i => FiniteDistribution.uniform (Ω i))).pushforward + (fun x => ∑ i, maps i (x i)) = FiniteDistribution.uniform V := + product_uniform_linear_image (linearSum maps) surjective + +end Product +end +end PerfectCompleteness.UniformLinearImage + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/AscendingBranchingLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/AscendingBranchingLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..354236758d2c8730f18ab5a4e5f3f38e63e4715c --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/AscendingBranchingLemmas.lean @@ -0,0 +1,180 @@ +import Mathlib.Data.Set.Finite.Basic +import OAI.Computability.PerfectCompleteness.Algebra.MatrixInverseConstantsLemmas +import OAI.Computability.PerfectCompleteness.Decoding.TwoResponseCollisionLemmas +import OAI.Computability.PerfectCompleteness.Foundations.CoordinateReplacementLemmas + +namespace OAI + + +namespace PerfectCompleteness.AscendingBranching + +open scoped BigOperators Classical + +noncomputable section + +theorem exists_prior_sequence {P : (n : Nat) → (Fin n → Nat) → Nat → Prop} + (h : ∀ n prior, ∃ x, P n prior x) : + ∃ values : Nat → Nat, ∀ n, P n (fun i => values i.val) (values n) := by + let pick := fun n prior => Classical.choose (h n prior) + let step := fun n (previous : ∀ m, m < n → Nat) => + pick n (fun i => previous i.val i.isLt) + let values : Nat → Nat := fun n => Nat.strongRecOn n step + refine ⟨values, fun n => ?_⟩ + have hrec : values n = pick n (fun i => values i.val) := + Nat.strongRecOn_eq step n + rw [hrec] + exact Classical.choose_spec (h n (fun i => values i.val)) + +def CubeErrors (L c ε : ℝ) (m : Nat) : Prop := + 2 ≤ m ∧ + Real.sqrt (L ^ 2 / (m : ℝ) ^ 3) / 2 < ε ∧ + Real.sqrt ((1 + L ^ 2 / (m : ℝ) ^ 4) ^ (m ^ 3) - 1) / 2 < ε ∧ + 2 * ((1 / (m : ℝ) ^ 2) * L / (1 - 1 / (m : ℝ) ^ 2)) < ε ∧ + (1 - c / (m : ℝ) ^ 2) ^ (m ^ 3) < ε + +theorem exists_ascending_cubes + (L c : (n : Nat) → (Fin n → Nat) → ℝ) + (hL : ∀ n prior, 0 ≤ L n prior) + (hc : ∀ n prior, 0 < c n prior) + (hc' : ∀ n prior, c n prior ≤ 1) + {ε : ℝ} (hε : 0 < ε) : + ∃ size : Nat → Nat, ∀ n, + CubeErrors (L n (fun i => size i.val ^ 3)) + (c n (fun i => size i.val ^ 3)) ε (size n) := by + apply exists_prior_sequence (P := fun n prior size => + CubeErrors (L n (fun i => prior i ^ 3)) (c n (fun i => prior i ^ 3)) ε size) + intro n prior + exact CubicErrorSchedule.exists_cube_errors_lt + (hL n (fun i => prior i ^ 3)) + (hc n (fun i => prior i ^ 3)) + (hc' n (fun i => prior i ^ 3)) hε + +theorem exists_common_accuracy {I : Type*} [Fintype I] + (tolerance : I → ℝ) (positive : ∀ i, 0 < tolerance i) : + ∃ ε : ℝ, 0 < ε ∧ ∀ i, ε < tolerance i := by + have hfinite : ∀ S : Finset I, ∃ ε : ℝ, 0 < ε ∧ ∀ i ∈ S, ε < tolerance i := by + intro S + induction S using Finset.induction_on with + | empty => exact ⟨1, by norm_num, by simp⟩ + | @insert a S ha ih => + obtain ⟨ε, hε, hsmall⟩ := ih + refine ⟨min ε (tolerance a) / 2, div_pos (lt_min hε (positive a)) (by norm_num), ?_⟩ + intro i hi + have hhalf : min ε (tolerance a) / 2 < min ε (tolerance a) := by + have := lt_min hε (positive a) + linarith + rcases Finset.mem_insert.mp hi with rfl | hi + · exact hhalf.trans_le (min_le_right _ _) + · exact (hhalf.trans_le (min_le_left _ _)).trans (hsmall i hi) + obtain ⟨ε, hε, hsmall⟩ := hfinite Finset.univ + exact ⟨ε, hε, fun i => hsmall i (Finset.mem_univ i)⟩ + +end +end PerfectCompleteness.AscendingBranching + + + +namespace PerfectCompleteness.DescendingRows + +open scoped BigOperators Classical +open UniqueGamesTheorem.Appendix UniqueGamesTheorem.Fourier +open UpperParameterScalars + +noncomputable section + +structure Exclusion (threshold : ℝ) where + order : Nat + crossSize : Nat + cutoff : Nat + minimumRows : Nat + density : ℝ + order_pos : 1 ≤ order + cross_pos : 0 < crossSize + cutoff_pos : 1 ≤ cutoff + density_pos : 0 < density + density_lt_one : density < 1 + spectral : MatrixLevelBridge.levelCutoffConstant order density + + RankLevelFilter.node (order + 1) < threshold + row_bound : ∀ ℓ, minimumRows ≤ ℓ → 2 * crossSize + order ≤ ℓ + error_bound : ∀ s, cutoff ≤ s → + (2 : ℝ) ^ crossSize / (2 : ℝ) ^ (s - 2 * order) + + (2 : ℝ) ^ (2 * crossSize) / (2 : ℝ) ^ (crossSize * crossSize) < density + +theorem exclusion_exists {threshold : ℝ} (h : 0 < threshold) : + Nonempty (Exclusion threshold) := by + obtain ⟨r, m, s, rowMin, hr, hm, hs, ρ, hρ, hρ', hcut, hrows, herror⟩ := + LowerRankParameters.exists_lower_parameters h + exact ⟨⟨r, m, s, rowMin, ρ, hr, hm, hs, hρ, hρ', hcut, hrows, herror⟩⟩ + +variable {κ α η : ℝ} (hκ : 0 < κ) (hα : 0 < α) (hη : 0 < η) + +def lowerChoice (r ℓ : Nat) : Exclusion (gamma κ α η r ℓ ^ 2 / 8) := + Classical.choice (exclusion_exists (by + have := gamma_pos hκ hα hη r ℓ + positivity)) + +theorem exists_rows (r minimum : Nat) : + ∃ rows : Nat → Nat, ∀ n, + minimum ≤ rows n ∧ r ≤ rows n ∧ 1 ≤ rows n ∧ + 1 / (2 : ℝ) ^ (rows n - r) < rhoPred κ α / 8 ∧ + ∀ i : Fin n, (lowerChoice hκ hα hη r (rows i.val)).minimumRows ≤ rows n := by + apply AscendingBranching.exists_prior_sequence (P := fun n prior ℓ => + minimum ≤ ℓ ∧ r ≤ ℓ ∧ 1 ≤ ℓ ∧ + 1 / (2 : ℝ) ^ (ℓ - r) < rhoPred κ α / 8 ∧ + ∀ i : Fin n, (lowerChoice hκ hα hη r (prior i)).minimumRows ≤ ℓ) + intro n prior + let required := fun i : Fin n => (lowerChoice hκ hα hη r (prior i)).minimumRows + obtain ⟨ℓ, hmin, hr, hpos, hsmall⟩ := + exists_rows_rhoPred (minimum + ∑ i, required i) r hκ hα + refine ⟨ℓ, (Nat.le_add_right _ _).trans hmin, hr, hpos, hsmall, ?_⟩ + intro i + have hi : required i ≤ ∑ j, required j := + Finset.single_le_sum (fun j _ => Nat.zero_le (required j)) (Finset.mem_univ i) + exact hi.trans ((Nat.le_add_left _ _).trans hmin) + +def commonCutoff (r depth : Nat) (rows : Nat → Nat) : Nat := + 1 + ∑ i : Fin depth, (lowerChoice hκ hα hη r (rows i.val)).cutoff + +theorem commonCutoff_pos (r depth : Nat) (rows : Nat → Nat) : + 1 ≤ commonCutoff hκ hα hη r depth rows := Nat.le_add_right _ _ + +theorem cutoff_le_common (r depth : Nat) (rows : Nat → Nat) (i : Fin depth) : + (lowerChoice hκ hα hη r (rows i.val)).cutoff ≤ + commonCutoff hκ hα hη r depth rows := by + have hi : (lowerChoice hκ hα hη r (rows i.val)).cutoff ≤ + ∑ j : Fin depth, (lowerChoice hκ hα hη r (rows j.val)).cutoff := + Finset.single_le_sum + (fun j _ => Nat.zero_le (lowerChoice hκ hα hη r (rows j.val)).cutoff) + (Finset.mem_univ i) + exact hi.trans (Nat.le_add_left _ _) + +theorem error_at_common (r depth : Nat) (rows : Nat → Nat) (i : Fin depth) : + let lower := lowerChoice hκ hα hη r (rows i.val) + (2 : ℝ) ^ lower.crossSize / + (2 : ℝ) ^ (commonCutoff hκ hα hη r depth rows - 2 * lower.order) + + (2 : ℝ) ^ (2 * lower.crossSize) / + (2 : ℝ) ^ (lower.crossSize * lower.crossSize) < lower.density := + (lowerChoice hκ hα hη r (rows i.val)).error_bound _ + (cutoff_le_common hκ hα hη r depth rows i) + +def treeRows (depth : Nat) (rows : Nat → Nat) : Nat → Nat := + fun height => rows (depth - height) + +theorem tree_pair_requirement (r depth : Nat) (rows : Nat → Nat) + (ordered : ∀ n, ∀ i : Fin n, + (lowerChoice hκ hα hη r (rows i.val)).minimumRows ≤ rows n) + {i j : Nat} (hij : i < j) (hj : j ≤ depth) : + (lowerChoice hκ hα hη r (treeRows depth rows j)).minimumRows ≤ + treeRows depth rows i := by + exact ordered (depth - i) ⟨depth - j, by omega⟩ + +theorem tree_cutoff_le_common (r depth : Nat) (rows : Nat → Nat) + {j : Nat} (hj : 0 < j) (hjd : j ≤ depth) : + (lowerChoice hκ hα hη r (treeRows depth rows j)).cutoff ≤ + commonCutoff hκ hα hη r depth rows := + cutoff_le_common hκ hα hη r depth rows ⟨depth - j, by omega⟩ + +end +end PerfectCompleteness.DescendingRows + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/BucketFullAgreement.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/BucketFullAgreement.lean new file mode 100644 index 0000000000000000000000000000000000000000..146ae9227be7b85f65455c442e41572321c25f01 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/BucketFullAgreement.lean @@ -0,0 +1,67 @@ +import OAI.Computability.PerfectCompleteness.Construction.BucketQuotientAgreement + +namespace OAI + +section + +namespace PerfectCompleteness.BucketFullAgreement + +noncomputable section + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games +open BucketSampler (F2 Direction Tape) +open PartialTableInverse (definedEquality nonzeroAgreement) + +attribute [local instance] UniqueGamesTheorem.Appendix.RankLevelFilter.linearMapFintype + +variable {Ω Y : Type*} [Fintype Y] + (V : Submodule F2 (Ω → F2)) [Fintype V] [FiniteDimensional F2 V] + (ℓ : Nat) + +abbrev Sample := Direction ℓ × (Tape ℓ V × V) + +def law [Nonempty (Direction ℓ)] : FiniteDistribution (Sample V ℓ) := + (FiniteDistribution.uniform (Direction ℓ)).product + ((BucketSampler.tapeLaw ℓ (FiniteDistribution.uniform V)).product + (FiniteDistribution.uniform V)) + +def pair (sample : Sample V ℓ) : + BucketMatrixResampling.Matrix V ℓ × BucketMatrixResampling.Matrix V ℓ := + (BucketMatrixResampling.assembledMatrix V ℓ sample.2.1, + BucketMatrixResampling.assembledMatrix V ℓ + (Function.update sample.2.1 sample.1 sample.2.2)) + +private theorem expectation_uniform_eq_expect {A : Type*} [Fintype A] [Nonempty A] + (f : A → ℝ) : + (FiniteDistribution.uniform A).expectation f = 𝔼 x : A, f x := by + rw [FiniteDistribution.expectation_uniform, Fintype.expect_eq_sum_div_card] + +theorem collision_probability [Nonempty (Direction ℓ)] + (f : BucketMatrixResampling.Matrix V ℓ → Option Y) : + (law V ℓ).probability (fun sample => TwoResponseCollision.collision f (pair V ℓ sample)) = + nonzeroAgreement f := by + rw [law, BucketQuotientAgreement.probability_collision_eq_expectation, + FiniteDistribution.expectation_product, expectation_uniform_eq_expect] + calc + _ = FiniteRangeInverse.agreement f := by + unfold FiniteRangeInverse.agreement + refine Finset.expect_congr (ι := Direction ℓ) ?_ ?_ + · ext a + simp only [Finset.mem_univ] + intro a _ + have hevent := BucketMatrixResampling.uniform_resampled_event_probability V ℓ a + (TwoResponseCollision.collision f) + rw [BucketQuotientAgreement.probability_collision_eq_expectation, + BucketQuotientAgreement.probability_collision_eq_expectation, + FiniteDistribution.expectation_product] at hevent + simpa only [FiniteDistribution.expectation_product, expectation_uniform_eq_expect, + pair, EvaluationMatrix.shift, FiniteRangeInverse.matrixStep] using hevent + _ = nonzeroAgreement f := FiniteRangeInverse.agreement_eq_nonzeroAgreement f + +end +end PerfectCompleteness.BucketFullAgreement + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/BucketQuotientAgreement.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/BucketQuotientAgreement.lean new file mode 100644 index 0000000000000000000000000000000000000000..c1e2f01588e824e4e1a6c2c9ae276c7564b163b6 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/BucketQuotientAgreement.lean @@ -0,0 +1,122 @@ +import OAI.Computability.PerfectCompleteness.Algebra.BucketMatrixResampling +import OAI.Computability.PerfectCompleteness.Decoding.TwoResponseCollisionLemmas +import OAI.Computability.PerfectCompleteness.Foundations.QuotientTableAgreementLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.BucketQuotientAgreement + +noncomputable section + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games +open BucketSampler (F2 Direction Tape) +open PartialTableInverse (definedEquality nonzeroAgreement) + +attribute [local instance] UniqueGamesTheorem.Appendix.RankLevelFilter.linearMapFintype + +theorem collision_indicator_eq {A Y : Type*} [Fintype A] [Fintype Y] + (f : A → Option Y) (x y : A) : + (if TwoResponseCollision.collision f (x, y) then (1 : ℝ) else 0) = + definedEquality f x y := by + simp [TwoResponseCollision.collision, definedEquality] + +theorem probability_collision_eq_expectation {A B Y : Type*} + [Fintype A] [Fintype B] [Fintype Y] + (μ : FiniteDistribution A) (f : B → Option Y) (p q : A → B) : + μ.probability (fun x => TwoResponseCollision.collision f (p x, q x)) = + μ.expectation (fun x => definedEquality f (p x) (q x)) := by + unfold FiniteDistribution.probability FiniteDistribution.expectation + apply Finset.sum_congr rfl + intro x _ + by_cases h : ∃ y, f (p x) = some y ∧ f (q x) = some y <;> + simp [TwoResponseCollision.collision, definedEquality, h] + +private theorem expectation_uniform_eq_expect {A : Type*} [Fintype A] [Nonempty A] + (f : A → ℝ) : + (FiniteDistribution.uniform A).expectation f = 𝔼 x : A, f x := by + rw [FiniteDistribution.expectation_uniform, Fintype.expect_eq_sum_div_card] + +variable {Ω Y : Type*} [Fintype Y] + (V : Submodule F2 (Ω → F2)) [Fintype V] [FiniteDimensional F2 V] + (ℓ : Nat) (W : Submodule F2 V) + +def directionCollision + (f : (Module.Dual F2 (V ⧸ W) →ₗ[F2] (Fin ℓ → F2)) → Option Y) + (a : Direction ℓ) : ℝ := + ((BucketSampler.tapeLaw ℓ (FiniteDistribution.uniform V)).product + (FiniteDistribution.uniform V)).probability + (fun p => TwoResponseCollision.collision f + (MatrixRowQuotient.projectMatrix W (BucketMatrixResampling.assembledMatrix V ℓ p.1), + MatrixRowQuotient.projectMatrix W + (BucketMatrixResampling.assembledMatrix V ℓ (Function.update p.1 a p.2)))) + +theorem directionCollision_eq + (f : (Module.Dual F2 (V ⧸ W) →ₗ[F2] (Fin ℓ → F2)) → Option Y) + (a : Direction ℓ) : + directionCollision V ℓ W f a = + 𝔼 X : Module.Dual F2 V →ₗ[F2] (Fin ℓ → F2), 𝔼 h : V, + definedEquality f (MatrixRowQuotient.projectMatrix W X) + (MatrixRowQuotient.projectMatrix W (EvaluationMatrix.shift V X a.val h)) := by + unfold directionCollision + rw [BucketMatrixResampling.uniform_resampled_event_probability V ℓ a + (fun p => TwoResponseCollision.collision f + (MatrixRowQuotient.projectMatrix W p.1, MatrixRowQuotient.projectMatrix W p.2))] + rw [probability_collision_eq_expectation, FiniteDistribution.expectation_product] + simp only [expectation_uniform_eq_expect] + +def agreement + (f : (Module.Dual F2 (V ⧸ W) →ₗ[F2] (Fin ℓ → F2)) → Option Y) : ℝ := + 𝔼 a : Direction ℓ, directionCollision V ℓ W f a + +theorem agreement_eq_projectedAgreement + (f : (Module.Dual F2 (V ⧸ W) →ₗ[F2] (Fin ℓ → F2)) → Option Y) : + agreement V ℓ W f = QuotientTableAgreement.projectedAgreement W f := by + unfold agreement QuotientTableAgreement.projectedAgreement + refine Finset.expect_congr (ι := Direction ℓ) ?_ ?_ + · ext a + simp only [Finset.mem_univ] + · intro a _ + exact directionCollision_eq V ℓ W f a + +theorem agreement_eq_nonzeroAgreement + (f : (Module.Dual F2 (V ⧸ W) →ₗ[F2] (Fin ℓ → F2)) → Option Y) : + agreement V ℓ W f = nonzeroAgreement f := by + rw [agreement_eq_projectedAgreement, + QuotientTableAgreement.projectedAgreement_eq_nonzeroAgreement] + +theorem uniform_bucket_collision_probability [Nonempty (Direction ℓ)] + (f : (Module.Dual F2 (V ⧸ W) →ₗ[F2] (Fin ℓ → F2)) → Option Y) : + ((FiniteDistribution.uniform (Direction ℓ)).product + ((BucketSampler.tapeLaw ℓ (FiniteDistribution.uniform V)).product + (FiniteDistribution.uniform V))).probability + (fun p => TwoResponseCollision.collision f + (MatrixRowQuotient.projectMatrix W + (BucketMatrixResampling.assembledMatrix V ℓ p.2.1), + MatrixRowQuotient.projectMatrix W + (BucketMatrixResampling.assembledMatrix V ℓ + (Function.update p.2.1 p.1 p.2.2)))) = nonzeroAgreement f := by + rw [probability_collision_eq_expectation, FiniteDistribution.expectation_product, + expectation_uniform_eq_expect] + calc + _ = agreement V ℓ W f := by + unfold agreement + apply Finset.expect_congr rfl + intro a _ + exact (probability_collision_eq_expectation + ((BucketSampler.tapeLaw ℓ (FiniteDistribution.uniform V)).product + (FiniteDistribution.uniform V)) f + (fun p => MatrixRowQuotient.projectMatrix W + (BucketMatrixResampling.assembledMatrix V ℓ p.1)) + (fun p => MatrixRowQuotient.projectMatrix W + (BucketMatrixResampling.assembledMatrix V ℓ (Function.update p.1 a p.2)))).symm + _ = nonzeroAgreement f := agreement_eq_nonzeroAgreement V ℓ W f + +end +end PerfectCompleteness.BucketQuotientAgreement + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/CanonicalLocalCompletion.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/CanonicalLocalCompletion.lean new file mode 100644 index 0000000000000000000000000000000000000000..85d2b176b8707803554dec1d861c6510957842b6 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/CanonicalLocalCompletion.lean @@ -0,0 +1,238 @@ +import OAI.Computability.PerfectCompleteness.Construction.FlexibleLocalCompletionLemmas +import OAI.Computability.PerfectCompleteness.Foundations.LegalOutputLemmas +import OAI.Computability.PerfectCompleteness.Machines.CanonicalLabelEncoding +import OAI.Computability.PerfectCompleteness.Machines.LocalCompletionMachineLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.CanonicalLocalCompletion + +open scoped Classical +open Turing UniqueGamesTheorem.Foundations.Complexity UniqueGamesTheorem.Foundations.Games +open SourceClause CanonicalKeys CanonicalGame CanonicalKeyEncoding CanonicalLabelEncoding +open CompletionSoundness CompletionSoundness.LegalProjectionGame + +noncomputable section + +def alphabet (n : Nat) (δ : ℚ) : Nat := CompletionAlphabet.size (partitionWidth n) δ + +theorem alphabet_positive (n : Nat) (δ : ℚ) : 0 < alphabet n δ := + CompletionAlphabet.size_positive (partitionWidth n) δ + +theorem partitionWidth_le_alphabet (n : Nat) (δ : ℚ) : partitionWidth n ≤ alphabet n δ := + CompletionAlphabet.cap_le_size (partitionWidth n) δ + +theorem partitionWidth_le_leftAlphabet (n : Nat) (δ : ℚ) : + partitionWidth n ≤ 2 * alphabet n δ := by + have h := partitionWidth_le_alphabet n δ + omega + +theorem alphabet_ge_two (n : Nat) (δ : ℚ) : 2 ≤ alphabet n δ := by + have hpos : 0 < partitionWidth n := by + rw [partitionWidth_eq] + exact pow_pos (by decide) _ + have hcap : partitionWidth n + 1 ≤ alphabet n δ := le_max_left _ _ + omega + +local instance rightAlphabet_nonempty (n : Nat) (δ : ℚ) : Nonempty (Fin (alphabet n δ)) := + ⟨⟨0, alphabet_positive n δ⟩⟩ + +local instance leftAlphabet_nonempty (n : Nat) (δ : ℚ) : Nonempty (Fin (2 * alphabet n δ)) := + ⟨⟨0, Nat.mul_pos (by decide) (alphabet_positive n δ)⟩⟩ + +variable {v m n : Nat} {E I B : Type*} {V : I → Type*} + [DecidableEq I] [∀ i, AddCommGroup (V i)] + [∀ i, Module DirectionQuotient.F2 (V i)] + [Finite I] [∀ i, Finite (V i)] [Finite B] + {clauses : Fin m → NormalizedClause v} + (F : BlockFamily clauses n E I V B) + +def legalL (δ : ℚ) (x : LeftVertex F) : LeftLabel F x ↪ Fin (2 * alphabet n δ) := + labelEmbedding x.val (partitionWidth_le_leftAlphabet n δ) + +def legalR (δ : ℚ) (y : RightVertex F) : RightLabel F y ↪ Fin (alphabet n δ) := + labelEmbedding y.val (partitionWidth_le_alphabet n δ) + +omit [DecidableEq I] [Finite I] [∀ index, Finite (V index)] [Finite B] in +@[simp] theorem legalL_val (δ : ℚ) (x : LeftVertex F) (label : LeftLabel F x) : + (legalL F δ x label).val = (partEnum n label.val).val := rfl + +omit [Finite I] [∀ index, Finite (V index)] [Finite B] in +@[simp] theorem legalR_val (δ : ℚ) (y : RightVertex F) (label : RightLabel F y) : + (legalR F δ y label).val = (partEnum n label.val).val := rfl + +def defaultL (x : LeftVertex F) : LeftLabel F x := Classical.choice inferInstance + +variable [Fintype E] [Fintype (LeftVertex F)] [Fintype (RightVertex F)] + [∀ x, Fintype (LeftLabel F x)] [∀ y, Fintype (RightLabel F y)] + +omit [DecidableEq I] [Finite I] [∀ index, Finite (V index)] [Finite B] [Fintype E] + [Fintype (LeftVertex F)] [Fintype (RightVertex F)] + [∀ vertex, Fintype (RightLabel F vertex)] in +theorem leftLabel_card_le (δ : ℚ) (x : LeftVertex F) : + Fintype.card (LeftLabel F x) ≤ alphabet n δ := by + let : Fintype (KeyLabel x.val) := inferInstanceAs (Fintype (LeftLabel F x)) + exact (label_card_le x.val).trans (partitionWidth_le_alphabet n δ) + +omit [Finite I] [∀ index, Finite (V index)] [Finite B] [Fintype E] + [Fintype (LeftVertex F)] [Fintype (RightVertex F)] + [∀ vertex, Fintype (LeftLabel F vertex)] in +theorem rightLabel_card_le (δ : ℚ) (y : RightVertex F) : + Fintype.card (RightLabel F y) ≤ alphabet n δ := by + let : Fintype (KeyLabel y.val) := inferInstanceAs (Fintype (RightLabel F y)) + exact (label_card_le y.val).trans (partitionWidth_le_alphabet n δ) + +omit [Fintype (LeftVertex F)] [Fintype (RightVertex F)] + [∀ vertex, Fintype (RightLabel F vertex)] in +theorem small (μ : FiniteDistribution E) : + ∀ e b, Fintype.card + {a : LeftLabel F ((game F μ).left e) // (game F μ).projection e a = b} ≤ 2 := by + intro e b + rw [Fintype.card_eq_nat_card] + change Nat.card {a : LeftLabel F (leftAt F e) // edge F e a = b} ≤ 2 + exact edge_at_most_two F e b + +def input (μ : FiniteDistribution E) (δ : ℚ) (e : E) : + LocalCompletionFamily.Input (alphabet n δ) := + LocalCompletionGame.input (game F μ) (legalL F δ) (legalR F δ) (defaultL F) e + +omit [Finite I] [∀ index, Finite (V index)] [Finite B] + [Fintype (LeftVertex F)] [Fintype (RightVertex F)] + [∀ vertex, Fintype (RightLabel F vertex)] in +theorem input_mask (μ : FiniteDistribution E) (δ : ℚ) (e : E) : + (input F μ δ e).1 = paddedMask (leftKey F e) := by + funext a + apply Bool.eq_iff_iff.mpr + exact (LocalCompletionGame.input_mask_true + (game F μ) (legalL F δ) (legalR F δ) (defaultL F) e a).trans + (paddedMask_eq_true_iff (leftKey F e) (partitionWidth_le_leftAlphabet n δ) a).symm + +omit [Finite I] [∀ index, Finite (V index)] [Finite B] + [Fintype (LeftVertex F)] [Fintype (RightVertex F)] + [∀ vertex, Fintype (RightLabel F vertex)] in +theorem input_image_legal (μ : FiniteDistribution E) (δ : ℚ) (e : E) + (label : LeftLabel F (leftAt F e)) : + (input F μ δ e).2 (legalL F δ (leftAt F e) label) = + legalR F δ (rightAt F e) (edge F e label) := + LocalCompletionGame.input_image_legal + (game F μ) (legalL F δ) (legalR F δ) (defaultL F) e label + +omit [Finite I] [∀ index, Finite (V index)] [Finite B] + [Fintype (LeftVertex F)] [Fintype (RightVertex F)] + [∀ vertex, Fintype (RightLabel F vertex)] in +theorem input_independent_of_law (μ ν : FiniteDistribution E) (δ : ℚ) (e : E) : + input F μ δ e = input F ν δ e := rfl + +omit [Fintype (LeftVertex F)] [Fintype (RightVertex F)] + [∀ vertex, Fintype (RightLabel F vertex)] in +theorem input_admissible (μ : FiniteDistribution E) (δ : ℚ) (e : E) : + LocalCompletionFamily.Admissible (input F μ δ e) := + LocalCompletionGame.input_admissible + (game F μ) (legalL F δ) (legalR F δ) (defaultL F) (by + intro occurrence label + rw [Fintype.card_eq_nat_card] + have h := small F μ occurrence label + rw [Fintype.card_eq_nat_card] at h + exact h) e + +def result (μ : FiniteDistribution E) (δ : ℚ) (e : E) : + LocalCompletionFamily.Result (alphabet n δ) := + LocalCompletionFamily.lookup (alphabet_positive n δ) (input F μ δ e) + +omit [Fintype (LeftVertex F)] [Fintype (RightVertex F)] + [∀ vertex, Fintype (RightLabel F vertex)] in +theorem result_correct (μ : FiniteDistribution E) (δ : ℚ) (e : E) : + LocalCompletionFamily.Correct (input F μ δ e) (result F μ δ e) := + LocalCompletionFamily.lookup_correct (alphabet_positive n δ) _ (input_admissible F μ δ e) + +def family (μ : FiniteDistribution E) (δ : ℚ) : + (game F μ).CompletionFamily (legalL F δ) (legalR F δ) := + LocalCompletionGame.family (game F μ) (legalL F δ) (legalR F δ) (defaultL F) + (alphabet_positive n δ) (by + intro occurrence label + rw [Fintype.card_eq_nat_card] + have h := small F μ occurrence label + rw [Fintype.card_eq_nat_card] at h + exact h) + +omit [Fintype (LeftVertex F)] [Fintype (RightVertex F)] + [∀ vertex, Fintype (RightLabel F vertex)] in +@[simp] theorem family_size (μ : FiniteDistribution E) (δ : ℚ) (e : E) : + (family F μ δ).size e = LocalCompletionFamily.activeCount (result F μ δ e) := rfl + +omit [Fintype (LeftVertex F)] [Fintype (RightVertex F)] + [∀ vertex, Fintype (RightLabel F vertex)] in +@[simp] theorem family_map (μ : FiniteDistribution E) (δ : ℚ) (e : E) : + (family F μ δ).map e = LocalCompletionFamily.table (result F μ δ e) := rfl + +omit [Fintype (LeftVertex F)] [Fintype (RightVertex F)] + [∀ vertex, Fintype (RightLabel F vertex)] in +theorem family_size_le (μ : FiniteDistribution E) (δ : ℚ) (e : E) : + (family F μ δ).size e ≤ 2 * alphabet n δ := + LocalCompletionFamily.activeCount_le (result F μ δ e) + +def machine_output (μ : FiniteDistribution E) (δ : ℚ) (e : E) : + TM2OutputsInTime + (LocalCompletionSerialization.computation (alphabet_positive n δ)).tm + (LocalCompletionMachine.inputBits (input F μ δ e)) + (some (LocalCompletionSerialization.payloadBits (result F μ δ e))) 1 := + LocalCompletionSerialization.machine_output (alphabet_positive n δ) (input F μ δ e) + +omit [Fintype (LeftVertex F)] [Fintype (RightVertex F)] + [∀ vertex, Fintype (RightLabel F vertex)] in +theorem payload_parses (μ : FiniteDistribution E) (δ : ℚ) (e : E) : + decodeWords (LocalCompletionSerialization.payloadBits (result F μ δ e)) >>= + LocalCompletionSerialization.parsePayload (alphabet n δ) = + some ((List.finRange (LocalCompletionFamily.activeCount (result F μ δ e))).map + (LocalCompletionSerialization.projection (result_correct F μ δ e))) := by + rw [LocalCompletionSerialization.decode_payloadBits] + exact LocalCompletionSerialization.parse_payload (result_correct F μ δ e) + +omit [Fintype (LeftVertex F)] [Fintype (RightVertex F)] + [∀ vertex, Fintype (RightLabel F vertex)] in +theorem parsed_projection_eq_family_map (μ : FiniteDistribution E) (δ : ℚ) (e : E) + (seed : Fin ((family F μ δ).size e)) (a : Fin (2 * alphabet n δ)) : + (LocalCompletionSerialization.projection (result_correct F μ δ e) seed).images[a] = + (family F μ δ).map e seed a := + LocalCompletionSerialization.projection_apply (result_correct F μ δ e) seed a + +omit [Finite I] [∀ index, Finite (V index)] [Finite B] + [Fintype (LeftVertex F)] [Fintype (RightVertex F)] + [∀ vertex, Fintype (RightLabel F vertex)] in +theorem payload_length_le (μ : FiniteDistribution E) (δ : ℚ) (e : E) : + (LocalCompletionSerialization.payloadBits (result F μ δ e)).length ≤ + (1 + (2 * alphabet n δ) * (2 * alphabet n δ)) * (2 * alphabet n δ + 1) := + LocalCompletionSerialization.payloadBits_length_le _ + +theorem family_value_le (μ : FiniteDistribution E) (δ : ℚ) (hδ : 0 < δ) : + (family F μ δ).game.value ≤ (game F μ).value + (δ : ℝ) / 3 := by + apply (family F μ δ).value_le_of_bound ((δ : ℝ) / 3) + intro e + have hδreal : (0 : ℝ) < (δ : ℝ) := by exact_mod_cast hδ + have h := CompletionParameters.residual_le_third (alphabet_positive n δ) + (leftLabel_card_le F δ (leftAt F e)) hδreal + (CompletionAlphabet.size_budget (partitionWidth n) δ hδ) + simp only [Fintype.card_fin] + rw [Fintype.card_eq_nat_card] + rw [Fintype.card_eq_nat_card] at h + simpa only [CanonicalGame.game] using h + +theorem family_value_of_satisfying (μ : FiniteDistribution E) (δ : ℚ) + (assignment : Fin v → Bool) (hsat : ∀ c, (clauses c).clause.eval assignment = true) : + (family F μ δ).game.value = 1 := by + let : Nonempty E := by + by_contra hempty + have : IsEmpty E := ⟨fun e => hempty ⟨e⟩⟩ + have hnormalized := μ.normalized + simp at hnormalized + apply (family F μ δ).value_eq_one + exact CanonicalOutput.game_value_of_satisfying F μ assignment hsat + +end +end PerfectCompleteness.CanonicalLocalCompletion + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/ChildCallNumbering.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/ChildCallNumbering.lean new file mode 100644 index 0000000000000000000000000000000000000000..75aeefc7b8a9d16da8ea126def0ef4240f8d9a5c --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/ChildCallNumbering.lean @@ -0,0 +1,144 @@ +import OAI.Computability.PerfectCompleteness.Algebra.UniformLinearImage +import OAI.Computability.PerfectCompleteness.Decoding.ChildBlockProjection + +namespace OAI + +section + +namespace PerfectCompleteness.ChildCallNumbering + +open RecursiveSpaces TreeSourceSpaces HierarchicalArrays PointwiseSpaces +open UniqueGamesTheorem.Foundations.Games +open scoped Classical + +noncomputable section + +variable {C : Type*} [Fintype C] {branch : Nat → Nat} {n t : Nat} + +abbrev Raw (rows : Nat → Nat) (slots : Slots branch n → Fin t → MixedSupport.Slot) := + (C → squareSpace (H slots)) × Arrays slots rows + +instance rawFintype (rows : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Fintype (Raw (C := C) rows slots) := Fintype.ofFinite _ + +instance rawNonempty (rows : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Nonempty (Raw (C := C) rows slots) := ⟨(fun _ => 0, fun _ _ => 0)⟩ + +def equiv (rows : Nat → Nat) (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Raw (C := C) rows slots ≃ₗ[F2] + ChildBlockCardinality.Raw (Fintype.card C) rows slots where + toFun x := (fun k => x.1 ((Fintype.equivFin C).symm k), x.2) + invFun x := (fun c => x.1 (Fintype.equivFin C c), x.2) + left_inv x := by + apply Prod.ext + · funext c + simp only [Equiv.symm_apply_apply] + · rfl + right_inv x := by + apply Prod.ext + · funext k + simp only [Equiv.apply_symm_apply] + · rfl + map_add' x y := rfl + map_smul' c x := rfl + +@[simp] theorem equiv_calls (rows : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (x : Raw (C := C) rows slots) (k : Fin (Fintype.card C)) : + (equiv rows slots x).1 k = x.1 ((Fintype.equivFin C).symm k) := rfl + +@[simp] theorem equiv_arrays (rows : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (x : Raw (C := C) rows slots) : (equiv rows slots x).2 = x.2 := rfl + +@[simp] theorem equiv_symm_calls (rows : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (x : ChildBlockCardinality.Raw (Fintype.card C) rows slots) (c : C) : + ((equiv (C := C) rows slots).symm x).1 c = x.1 (Fintype.equivFin C c) := rfl + +@[simp] theorem equiv_symm_arrays (rows : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (x : ChildBlockCardinality.Raw (Fintype.card C) rows slots) : + ((equiv (C := C) rows slots).symm x).2 = x.2 := rfl + +def pullback (rows : Nat → Nat) + {slots projected : Slots branch n → Fin t → MixedSupport.Slot} + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) : + Raw (C := C) rows projected →ₗ[F2] Raw (C := C) rows slots where + toFun x := (fun c => ChildBlockProjection.squarePullback p (x.1 c), + ChildBlockProjection.arraysPullback rows p x.2) + map_add' x y := by + apply Prod.ext + · funext c + exact map_add (ChildBlockProjection.squarePullback p) (x.1 c) (y.1 c) + · exact map_add (ChildBlockProjection.arraysPullback rows p) x.2 y.2 + map_smul' a x := by + apply Prod.ext + · funext c + exact map_smul (ChildBlockProjection.squarePullback p) a (x.1 c) + · exact map_smul (ChildBlockProjection.arraysPullback rows p) a x.2 + +omit [Fintype C] in +@[simp] theorem pullback_calls (rows : Nat → Nat) + {slots projected : Slots branch n → Fin t → MixedSupport.Slot} + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (x : Raw (C := C) rows projected) (c : C) : + (pullback rows p x).1 c = ChildBlockProjection.squarePullback p (x.1 c) := rfl + +omit [Fintype C] in +@[simp] theorem pullback_arrays (rows : Nat → Nat) + {slots projected : Slots branch n → Fin t → MixedSupport.Slot} + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (x : Raw (C := C) rows projected) : + (pullback rows p x).2 = ChildBlockProjection.arraysPullback rows p x.2 := rfl + +theorem equiv_pullback (rows : Nat → Nat) + {slots projected : Slots branch n → Fin t → MixedSupport.Slot} + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (x : Raw (C := C) rows projected) : + equiv rows slots (pullback rows p x) = + ChildBlockProjection.rawPullback (Fintype.card C) rows p + (equiv rows projected x) := rfl + +omit [Fintype C] in +theorem pullback_cast (rows : Nat → Nat) + {slots target projected : Slots branch n → Fin t → MixedSupport.Slot} + (h : slots = target) + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (x : Raw (C := C) rows projected) : + cast (congrArg (Raw (C := C) rows) h) (pullback rows p x) = + pullback rows + (cast (congrArg + (fun ss : Slots branch n → Fin t → MixedSupport.Slot => + ∀ s k, MixedSupport.Projection (ss s k) (projected s k)) h) p) x := by + cases h + rfl + +theorem uniform_equiv (rows : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + (FiniteDistribution.uniform (Raw (C := C) rows slots)).pushforward + (equiv (C := C) rows slots) = + FiniteDistribution.uniform (ChildBlockCardinality.Raw (Fintype.card C) rows slots) := + UniformLinearImage.uniform_pushforward_linearMap + (equiv (C := C) rows slots).toLinearMap (equiv (C := C) rows slots).surjective + +theorem card_le (rows : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Fintype.card (Raw (C := C) rows slots) ≤ + ChildBlockCardinality.bound branch n t (Fintype.card C) rows := by + calc + Fintype.card (Raw (C := C) rows slots) = + Fintype.card (ChildBlockCardinality.Raw (Fintype.card C) rows slots) := + Fintype.card_congr (equiv (C := C) rows slots).toEquiv + _ ≤ _ := by + simpa only [Nat.card_eq_fintype_card] using + ChildBlockCardinality.card_le (Fintype.card C) rows slots + +end +end PerfectCompleteness.ChildCallNumbering + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/ChildUnmarkedSpace.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/ChildUnmarkedSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..119b6d6aef6e55d2e6ed9a2a430586754b35bdf3 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/ChildUnmarkedSpace.lean @@ -0,0 +1,122 @@ +import OAI.Computability.PerfectCompleteness.Algebra.BilinearWitnessLemmas +import OAI.Computability.PerfectCompleteness.Decoding.ChildAssemblyProjection +import OAI.Computability.PerfectCompleteness.Sampling.UniformChildSum + +namespace OAI + +section + +namespace PerfectCompleteness.ChildUnmarkedSpace + +open RecursiveSpaces TreeSourceSpaces PointwiseSpaces +open scoped BigOperators Classical + +noncomputable section + +variable {branch : Nat → Nat} {n t : Nat} + +def childMap (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (i : Fin (branch n)) : squareSpace (H (childSlots slots i)) →ₗ[F2] H slots where + toFun v := ⟨PointwiseSpaces.pullback F2 (restrictChild slots i) v.val, + child_square_le_H slots i (Submodule.mem_map_of_mem v.property)⟩ + map_add' v w := by apply Subtype.ext; rfl + map_smul' c v := by apply Subtype.ext; rfl + +@[simp] theorem childMap_apply + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (i : Fin (branch n)) (v : squareSpace (H (childSlots slots i))) (x : Domain slots) : + (childMap slots i v).val x = v.val (restrictChild slots i x) := rfl + +theorem assemble_eq_recursiveSum + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (v : (i : Fin (branch n)) → squareSpace (H (childSlots slots i))) : + BilinearWitness.assemble (childMap slots) v = + UniformChildSum.recursiveSum (LeafDomain slots) v := by + apply Subtype.ext + simp only [BilinearWitness.assemble, Submodule.coe_sum] + rfl + +theorem assemble_surjective + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) : + Function.Surjective (BilinearWitness.assemble (childMap slots)) := by + intro v + obtain ⟨w, hw⟩ := UniformChildSum.recursiveSum_surjective + (𝕜 := F2) (LeafDomain slots) v + exact ⟨w, (assemble_eq_recursiveSum slots w).trans hw⟩ + +def space (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (mask : Fin (branch n) → Bool) : Submodule F2 (H slots) := + ⨆ i, ⨆ (_ : mask i = false), LinearMap.range (childMap slots i) + +theorem childMap_mem_space + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (mask : Fin (branch n) → Bool) (i : Fin (branch n)) (hi : mask i = false) + (v : squareSpace (H (childSlots slots i))) : childMap slots i v ∈ space slots mask := by + have hle : LinearMap.range (childMap slots i) ≤ space slots mask := by + unfold space + exact le_iSup_of_le i (le_iSup_of_le hi le_rfl) + exact hle ⟨v, rfl⟩ + +private theorem projection_self_map (s : MixedSupport.Slot) + (p : MixedSupport.Projection s s) (x : s.Domain) : p.map x = x := by + cases s <;> cases p <;> rfl + +private theorem sourceProjection_self + {slots : Slots branch n → Fin t → MixedSupport.Slot} + (p : ∀ s k, MixedSupport.Projection (slots s k) (slots s k)) + (x : Domain slots) : sourceProjection p x = x := by + funext s k + exact projection_self_map (slots s k) (p s k) (x s k) + +theorem squarePullback_surjective_of_eq + {slots projected : Slots branch n → Fin t → MixedSupport.Slot} + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (heq : projected = slots) : Function.Surjective (ChildBlockProjection.squarePullback p) := by + subst projected + intro v + refine ⟨v, ?_⟩ + apply Subtype.ext + funext x + change v.val (sourceProjection p x) = v.val x + rw [sourceProjection_self] + +theorem childMap_pullback + {slots projected : Slots branch (n + 1) → Fin t → MixedSupport.Slot} + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (i : Fin (branch n)) (v : squareSpace (H (childSlots projected i))) : + childMap slots i + (ChildBlockProjection.squarePullback (ChildAssemblyProjection.childProjection p i) v) = + HPullback p (childMap projected i v) := by + apply Subtype.ext + funext x + rfl + +theorem childMap_mem_projected_range + {slots projected : Slots branch (n + 1) → Fin t → MixedSupport.Slot} + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (i : Fin (branch n)) (heq : childSlots projected i = childSlots slots i) + (v : squareSpace (H (childSlots slots i))) : + childMap slots i v ∈ LinearMap.range (HPullback p) := by + obtain ⟨w, rfl⟩ := squarePullback_surjective_of_eq + (ChildAssemblyProjection.childProjection p i) heq v + exact ⟨childMap projected i w, (childMap_pullback p i w).symm⟩ + +theorem space_le_projected_range + {slots projected : Slots branch (n + 1) → Fin t → MixedSupport.Slot} + (mask : Fin (branch n) → Bool) + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (hkeep : ∀ i, mask i = false → childSlots projected i = childSlots slots i) : + space slots mask ≤ LinearMap.range (HPullback p) := by + apply iSup_le + intro i + apply iSup_le + intro hi + rintro _ ⟨v, rfl⟩ + exact childMap_mem_projected_range p i (hkeep i hi) v + +end +end PerfectCompleteness.ChildUnmarkedSpace + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/CutBucketTransportLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/CutBucketTransportLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..f8e3fe81c37819f73661b47316820d1ef6ed43f4 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/CutBucketTransportLemmas.lean @@ -0,0 +1,163 @@ +import OAI.Computability.PerfectCompleteness.Construction.CutNodeRows +import OAI.Computability.PerfectCompleteness.Decoding.HierarchicalUsefulCollision +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalAgreementMean + +namespace OAI + +section + +namespace PerfectCompleteness.CutBucketTransport + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCutTape WholeArrayInteriorExterior +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +noncomputable section + +attribute [local instance] linearMapFintype + +variable {branch : Nat → Nat} {n m t : Nat} + +local instance rowSpaceFintype (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Fintype (NodeEmbedding.RowSpace slots (upperNode p)) := Fintype.ofFinite _ + +def nativeLaw (rows : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) (hrows : 0 < rows (m + 1)) : + FiniteDistribution (BucketSampler.Direction (rows (m + 1)) × + (BucketSampler.Tape (rows (m + 1)) (H (cutSlots p slots)) × H (cutSlots p slots))) := by + letI : Nonempty (BucketSampler.Direction (rows (m + 1))) := + ⟨BucketUniform.coordinateDirection ⟨0, hrows⟩⟩ + exact (FiniteDistribution.uniform (BucketSampler.Direction (rows (m + 1)))).product + ((BucketSampler.tapeLaw (rows (m + 1)) + (FiniteDistribution.uniform (H (cutSlots p slots)))).product + (FiniteDistribution.uniform (H (cutSlots p slots)))) + +theorem nativeLaw_pushforward (rows : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) (hrows : 0 < rows (m + 1)) : + (nativeLaw rows p slots hrows).pushforward (CutNodeRows.bucketSampleEquiv rows p slots) = + HierarchicalAgreementMean.bucketLaw slots (upperNode p) + (by simpa only [upperNode_height] using hrows) := by + let : Nonempty (BucketSampler.Direction (rows (m + 1))) := + ⟨BucketUniform.coordinateDirection ⟨0, hrows⟩⟩ + let : Nonempty (BucketSampler.Direction (rows (Nodes.height (upperNode p)))) := + ⟨CutNodeRows.directionEquiv rows p (BucketUniform.coordinateDirection ⟨0, hrows⟩)⟩ + unfold nativeLaw HierarchicalAgreementMean.bucketLaw + simp only [BucketSampler.tapeLaw, UniformLinearImage.law_uniform, + WholeCutSampler.uniform_product] + rw [← FiniteDistribution.transport_eq_pushforward] + exact UniformConditioning.uniform_transport (CutNodeRows.bucketSampleEquiv rows p slots) + +end +end PerfectCompleteness.CutBucketTransport + +end + +section + +namespace PerfectCompleteness.CutBucketTransportActual + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCutTape WholeArrayInteriorExterior +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +noncomputable section + +variable {branch : Nat → Nat} {n m t : Nat} + +local instance rowSpaceFintype (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Fintype (NodeEmbedding.RowSpace slots (upperNode p)) := Fintype.ofFinite _ + +theorem tapeLaw_pushforward (rows : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (scalar : FiniteDistribution (H (cutSlots p slots))) : + (BucketSampler.tapeLaw (rows (m + 1)) scalar).pushforward + (CutNodeRows.bucketTapeEquiv rows p slots) = + BucketSampler.tapeLaw (rows (Nodes.height (upperNode p))) + (scalar.pushforward (CutNodeRows.cutRowEquiv p slots)) := by + have hscalar := FiniteDistribution.transport_eq_pushforward scalar + (CutNodeRows.cutRowEquiv p slots).toEquiv + change scalar.transport (CutNodeRows.cutRowEquiv p slots).toEquiv = + scalar.pushforward (CutNodeRows.cutRowEquiv p slots) at hscalar + rw [← FiniteDistribution.transport_eq_pushforward + (BucketSampler.tapeLaw (rows (m + 1)) scalar) (CutNodeRows.bucketTapeEquiv rows p slots), + ← hscalar] + apply FiniteDistribution.eq_of_weight_eq + intro tape + change (∏ a : BucketSampler.Direction (rows (m + 1)), + scalar.weight ((CutNodeRows.cutRowEquiv p slots).symm + (tape (CutNodeRows.directionEquiv rows p a)))) = + ∏ a : BucketSampler.Direction (rows (Nodes.height (upperNode p))), + scalar.weight ((CutNodeRows.cutRowEquiv p slots).symm (tape a)) + exact (CutNodeRows.directionEquiv rows p).prod_comp (M := ℝ) + (fun a : BucketSampler.Direction (rows (Nodes.height (upperNode p))) => + scalar.weight ((CutNodeRows.cutRowEquiv p slots).symm (tape a))) + +theorem bucketSampleLaw_pushforward (rows : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (directions : FiniteDistribution (BucketSampler.Direction (rows (m + 1)))) + (scalar : FiniteDistribution (H (cutSlots p slots))) : + (directions.product ((BucketSampler.tapeLaw (rows (m + 1)) scalar).product scalar)).pushforward + (CutNodeRows.bucketSampleEquiv rows p slots) = + (directions.pushforward (CutNodeRows.directionEquiv rows p)).product + ((BucketSampler.tapeLaw (rows (Nodes.height (upperNode p))) + (scalar.pushforward (CutNodeRows.cutRowEquiv p slots))).product + (scalar.pushforward (CutNodeRows.cutRowEquiv p slots))) := by + change (directions.product + ((BucketSampler.tapeLaw (rows (m + 1)) scalar).product scalar)).pushforward + (fun z => (CutNodeRows.directionEquiv rows p z.1, + (CutNodeRows.bucketTapeEquiv rows p slots z.2.1, + CutNodeRows.cutRowEquiv p slots z.2.2))) = _ + rw [FiniteDistribution.product_pushforward directions + ((BucketSampler.tapeLaw (rows (m + 1)) scalar).product scalar) + (CutNodeRows.directionEquiv rows p) + (fun z => (CutNodeRows.bucketTapeEquiv rows p slots z.1, + CutNodeRows.cutRowEquiv p slots z.2))] + rw [FiniteDistribution.product_pushforward + (BucketSampler.tapeLaw (rows (m + 1)) scalar) scalar + (CutNodeRows.bucketTapeEquiv rows p slots) (CutNodeRows.cutRowEquiv p slots), + tapeLaw_pushforward] + +def nativeLaw (rows : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (scalar : FiniteDistribution (H (cutSlots p slots))) (hrows : 0 < rows (m + 1)) : + FiniteDistribution (BucketSampler.Direction (rows (m + 1)) × + (BucketSampler.Tape (rows (m + 1)) (H (cutSlots p slots)) × H (cutSlots p slots))) := by + letI : Nonempty (BucketSampler.Direction (rows (m + 1))) := + ⟨BucketUniform.coordinateDirection ⟨0, hrows⟩⟩ + exact (FiniteDistribution.uniform (BucketSampler.Direction (rows (m + 1)))).product + ((BucketSampler.tapeLaw (rows (m + 1)) scalar).product scalar) + +theorem nativeLaw_pushforward (rows : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (scalar : FiniteDistribution (H (cutSlots p slots))) (hrows : 0 < rows (m + 1)) : + (nativeLaw rows p slots scalar hrows).pushforward (CutNodeRows.bucketSampleEquiv rows p slots) = + HierarchicalUsefulCollision.bucketLaw slots (upperNode p) + (scalar.pushforward (CutNodeRows.cutRowEquiv p slots)) + (by simpa only [upperNode_height] using hrows) := by + let : Nonempty (BucketSampler.Direction (rows (m + 1))) := + ⟨BucketUniform.coordinateDirection ⟨0, hrows⟩⟩ + let : Nonempty (BucketSampler.Direction (rows (Nodes.height (upperNode p)))) := + ⟨CutNodeRows.directionEquiv rows p (BucketUniform.coordinateDirection ⟨0, hrows⟩)⟩ + have hdirections : + (FiniteDistribution.uniform (BucketSampler.Direction (rows (m + 1)))).pushforward + (CutNodeRows.directionEquiv rows p) = + HierarchicalUsefulCollision.directionLaw (rows := rows) (upperNode p) + (by simpa only [upperNode_height] using hrows) := by + change (FiniteDistribution.uniform (BucketSampler.Direction (rows (m + 1)))).pushforward + (CutNodeRows.directionEquiv rows p) = + FiniteDistribution.uniform (BucketSampler.Direction (rows (Nodes.height (upperNode p)))) + rw [← FiniteDistribution.transport_eq_pushforward] + exact UniformConditioning.uniform_transport (CutNodeRows.directionEquiv rows p) + unfold nativeLaw HierarchicalUsefulCollision.bucketLaw + rw [bucketSampleLaw_pushforward, hdirections] + +end +end PerfectCompleteness.CutBucketTransportActual + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/CutChildGrouping.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/CutChildGrouping.lean new file mode 100644 index 0000000000000000000000000000000000000000..c4458950461b1313d8e8f39312b68e768b43f66a --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/CutChildGrouping.lean @@ -0,0 +1,98 @@ +import OAI.Computability.PerfectCompleteness.Repetition.CleanTreeFactors +import OAI.Computability.PerfectCompleteness.Sampling.UniformChildSum + +namespace OAI + +section + +namespace PerfectCompleteness.CutChildGrouping + +open scoped BigOperators Classical +open TreeSourceSpaces HierarchicalArrays PointwiseSpaces +open UniqueGamesTheorem.Foundations.Games + +abbrev F2 := ZMod 2 + +noncomputable section + +variable {branch : Nat → Nat} {n t : Nat} {C : Type*} [Fintype C] + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (rows : Nat → Nat) + +abbrev Child (i : Fin (branch n)) := + (C → squareSpace (H (childSlots slots i))) × Arrays (childSlots slots i) rows + +instance childFintype (i : Fin (branch n)) : Fintype (Child (C := C) slots rows i) := + Fintype.ofFinite _ + +abbrev Raw := (i : Fin (branch n)) → Child (C := C) slots rows i + +abbrev Assembled := + (C → H slots) × ((i : Fin (branch n)) → Arrays (childSlots slots i) rows) + +instance assembledFintype : Fintype (Assembled (C := C) slots rows) := Fintype.ofFinite _ + +def rawLaw : FiniteDistribution (Raw (C := C) slots rows) := + FiniteProduct.law (fun i => FiniteDistribution.uniform (Child (C := C) slots rows i)) + +def assemble : Raw (C := C) slots rows →ₗ[F2] Assembled (C := C) slots rows where + toFun x := + (fun q => UniformChildSum.recursiveSum (TreeSourceSpaces.LeafDomain slots) + (fun i => (x i).1 q), fun i => (x i).2) + map_add' x y := by + apply Prod.ext + · funext q + exact map_add (UniformChildSum.recursiveSum (TreeSourceSpaces.LeafDomain slots)) + (fun i => (x i).1 q) (fun i => (y i).1 q) + · rfl + map_smul' c x := by + apply Prod.ext + · funext q + exact map_smul (UniformChildSum.recursiveSum (TreeSourceSpaces.LeafDomain slots)) c + (fun i => (x i).1 q) + · rfl + +omit [Fintype C] in +@[simp] theorem assemble_calls (x : Raw (C := C) slots rows) (q : C) : + (assemble slots rows x).1 q = + UniformChildSum.recursiveSum (TreeSourceSpaces.LeafDomain slots) + (fun i => (x i).1 q) := rfl + +omit [Fintype C] in +@[simp] theorem assemble_arrays (x : Raw (C := C) slots rows) (i : Fin (branch n)) : + (assemble slots rows x).2 i = (x i).2 := rfl + +omit [Fintype C] in +theorem assemble_surjective : Function.Surjective (assemble (C := C) slots rows) := by + rintro ⟨calls, arrays⟩ + have hex : ∀ q : C, ∃ u : (i : Fin (branch n)) → squareSpace (H (childSlots slots i)), + UniformChildSum.recursiveSum (TreeSourceSpaces.LeafDomain slots) u = calls q := by + intro q + exact UniformChildSum.recursiveSum_surjective (TreeSourceSpaces.LeafDomain slots) (calls q) + choose u hu using hex + refine ⟨fun i => (fun q => u q i, arrays i), ?_⟩ + apply Prod.ext + · funext q + exact hu q + · rfl + +theorem assemble_law : + (rawLaw (C := C) slots rows).pushforward (assemble slots rows) = + FiniteDistribution.uniform (Assembled (C := C) slots rows) := by + unfold rawLaw + rw [UniformLinearImage.law_uniform] + exact UniformLinearImage.uniform_pushforward_linearMap + (assemble slots rows) (assemble_surjective slots rows) + +theorem projected_child_type (calls : Nat) + (ids : RecursiveSpaces.Slots branch (n + 1) → Fin t → Nat) + (i : Fin (branch n)) : + Child (C := Fin calls) (ProjectedCardinality.projectedSlots ids) rows i = + CleanTreeFactors.Raw calls rows (fun s k => ids (i, s) k) := rfl + +end +end PerfectCompleteness.CutChildGrouping + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/CutNodeRows.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/CutNodeRows.lean new file mode 100644 index 0000000000000000000000000000000000000000..f927a07156bb483cf35e5c39865f1bfc1594fd47 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/CutNodeRows.lean @@ -0,0 +1,171 @@ +import OAI.Computability.PerfectCompleteness.Algebra.BucketMatrixResampling +import OAI.Computability.PerfectCompleteness.Algebra.HierarchicalMatrixTable +import OAI.Computability.PerfectCompleteness.Foundations.WholeArrayInteriorExteriorLemmas +import OAI.Computability.PerfectCompleteness.Machines.OriginalWholeCutTape + +namespace OAI + +section + +namespace PerfectCompleteness.CutNodeRows + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCutTape WholeArrayInteriorExterior +open scoped BigOperators Classical + +noncomputable section + +variable {branch : Nat → Nat} {N cut t : Nat} + +theorem nativeH_eq (p : Path branch N (cut + 1)) + (slots : Slots branch N → Fin t → MixedSupport.Slot) : + (H (cutSlots p slots) : Type) = (NodeEmbedding.NodeH slots (upperNode p) : Type) := + (congrArg (fun z : Σ h, Path branch N h => (H (cutSlots z.2 slots) : Type)) + (upperNode_spec p)).symm + +def nativeEquiv : {N cut : Nat} → (p : Path branch N (cut + 1)) → + (slots : Slots branch N → Fin t → MixedSupport.Slot) → + H (cutSlots p slots) ≃ₗ[F2] NodeEmbedding.NodeH slots (upperNode p) + | _, _, .refl _, _ => LinearEquiv.refl F2 _ + | _, _, .step i p, slots => nativeEquiv p (childSlots slots i) + +def cutRowEquiv (p : Path branch N (cut + 1)) + (slots : Slots branch N → Fin t → MixedSupport.Slot) : + H (cutSlots p slots) ≃ₗ[F2] NodeEmbedding.RowSpace slots (upperNode p) := + (nativeEquiv p slots).trans (NodeEmbedding.equiv slots (upperNode p)) + +def rowIndexEquiv (rows : Nat → Nat) (p : Path branch N (cut + 1)) : + Fin (rows (cut + 1)) ≃ Fin (rows (Nodes.height (upperNode p))) := + Equiv.cast (congrArg (fun height => Fin (rows height)) (upperNode_height p).symm) + +def directionEquiv (rows : Nat → Nat) (p : Path branch N (cut + 1)) : + BucketSampler.Direction (rows (cut + 1)) ≃ + BucketSampler.Direction (rows (Nodes.height (upperNode p))) := + Equiv.cast (congrArg (fun height => BucketSampler.Direction (rows height)) + (upperNode_height p).symm) + +theorem native_selectedRows (rows : Nat → Nat) : + {N cut : Nat} → (p : Path branch N (cut + 1)) → + (slots : Slots branch N → Fin t → MixedSupport.Slot) → (arrays : Arrays slots rows) → + (fun i => nativeEquiv p slots + (SelectedArrayReplacement.selectedRows rows p slots arrays ((rowIndexEquiv rows p).symm i))) = + arrays (upperNode p) + | _, _, .refl _, _, _ => rfl + | _, _, .step i p, slots, arrays => + native_selectedRows rows p (childSlots slots i) (fun node => arrays (.inr (i, node))) + +def transportRows (rows : Nat → Nat) (p : Path branch N (cut + 1)) + (slots : Slots branch N → Fin t → MixedSupport.Slot) + (fresh : Fin (rows (cut + 1)) → H (cutSlots p slots)) : + Fin (rows (Nodes.height (upperNode p))) → NodeEmbedding.RowSpace slots (upperNode p) := + fun i => cutRowEquiv p slots (fresh ((rowIndexEquiv rows p).symm i)) + +theorem transportRows_selectedRows (rows : Nat → Nat) (p : Path branch N (cut + 1)) + (slots : Slots branch N → Fin t → MixedSupport.Slot) (arrays : Arrays slots rows) : + transportRows rows p slots (SelectedArrayReplacement.selectedRows rows p slots arrays) = + NodeEmbedding.embeddedRows arrays (upperNode p) := by + funext i + exact congrArg (NodeEmbedding.embed slots (upperNode p)) + (congrFun (native_selectedRows rows p slots arrays) i) + +def matrixOfRows (rows : Nat → Nat) (p : Path branch N (cut + 1)) + (slots : Slots branch N → Fin t → MixedSupport.Slot) + (fresh : Fin (rows (cut + 1)) → H (cutSlots p slots)) : + HierarchicalMatrixTable.Matrix (rows := rows) slots (upperNode p) := + EvaluationMatrix.ofRows (NodeEmbedding.RowSpace slots (upperNode p)) + (transportRows rows p slots fresh) + +theorem ofRows_selectedRows (rows : Nat → Nat) (p : Path branch N (cut + 1)) + (slots : Slots branch N → Fin t → MixedSupport.Slot) (arrays : Arrays slots rows) : + EvaluationMatrix.ofRows (NodeEmbedding.RowSpace slots (upperNode p)) + (transportRows rows p slots (SelectedArrayReplacement.selectedRows rows p slots arrays)) = + NodeEmbedding.matrix arrays (upperNode p) := by + rw [transportRows_selectedRows] + rfl + +theorem matrixOfRows_selectedRows (rows : Nat → Nat) (p : Path branch N (cut + 1)) + (slots : Slots branch N → Fin t → MixedSupport.Slot) (arrays : Arrays slots rows) : + matrixOfRows rows p slots (SelectedArrayReplacement.selectedRows rows p slots arrays) = + NodeEmbedding.matrix arrays (upperNode p) := + ofRows_selectedRows rows p slots arrays + +def bucketTapeEquiv (rows : Nat → Nat) (p : Path branch N (cut + 1)) + (slots : Slots branch N → Fin t → MixedSupport.Slot) : + BucketSampler.Tape (rows (cut + 1)) (H (cutSlots p slots)) ≃ + BucketSampler.Tape (rows (Nodes.height (upperNode p))) + (NodeEmbedding.RowSpace slots (upperNode p)) := + Equiv.arrowCongr (directionEquiv rows p) (cutRowEquiv p slots).toEquiv + +def bucketSampleEquiv (rows : Nat → Nat) (p : Path branch N (cut + 1)) + (slots : Slots branch N → Fin t → MixedSupport.Slot) : + (BucketSampler.Direction (rows (cut + 1)) × + (BucketSampler.Tape (rows (cut + 1)) (H (cutSlots p slots)) × H (cutSlots p slots))) ≃ + (BucketSampler.Direction (rows (Nodes.height (upperNode p))) × + (BucketSampler.Tape (rows (Nodes.height (upperNode p))) + (NodeEmbedding.RowSpace slots (upperNode p)) × + NodeEmbedding.RowSpace slots (upperNode p))) := + (directionEquiv rows p).prodCongr + ((bucketTapeEquiv rows p slots).prodCongr (cutRowEquiv p slots).toEquiv) + +private theorem tape_equiv_update {V W : Type*} {ℓ ℓ' : Nat} (h : ℓ = ℓ') + (e : V ≃ W) (tape : BucketSampler.Tape ℓ V) (a : BucketSampler.Direction ℓ) (fresh : V) : + Equiv.arrowCongr (Equiv.cast (congrArg BucketSampler.Direction h)) e + (Function.update tape a fresh) = + Function.update + (Equiv.arrowCongr (Equiv.cast (congrArg BucketSampler.Direction h)) e tape) + (Equiv.cast (congrArg BucketSampler.Direction h) a) (e fresh) := by + cases h + funext d + change e (Function.update tape a fresh d) = + Function.update (fun v => e (tape v)) a (e fresh) d + exact Function.apply_update (fun (_ : BucketSampler.Direction ℓ) (v : V) => e v) + tape a fresh d + +theorem bucketTapeEquiv_update (rows : Nat → Nat) (p : Path branch N (cut + 1)) + (slots : Slots branch N → Fin t → MixedSupport.Slot) + (tape : BucketSampler.Tape (rows (cut + 1)) (H (cutSlots p slots))) + (a : BucketSampler.Direction (rows (cut + 1))) (fresh : H (cutSlots p slots)) : + bucketTapeEquiv rows p slots (Function.update tape a fresh) = + Function.update (bucketTapeEquiv rows p slots tape) + (directionEquiv rows p a) (cutRowEquiv p slots fresh) := + tape_equiv_update (congrArg rows (upperNode_height p)).symm + (cutRowEquiv p slots).toEquiv tape a fresh + +private theorem evaluate_equiv {V W : Type*} [AddCommGroup V] [AddCommGroup W] + [Module F2 V] [Module F2 W] {ℓ ℓ' : Nat} (h : ℓ = ℓ') + (e : V ≃ₗ[F2] W) (tape : BucketSampler.Tape ℓ V) : + (fun i => e (BucketSampler.evaluate ℓ (id : V → V) tape + ((Equiv.cast (congrArg Fin h)).symm i))) = + BucketSampler.evaluate ℓ' (id : W → W) + (Equiv.arrowCongr (Equiv.cast (congrArg BucketSampler.Direction h)) e.toEquiv tape) := by + cases h + funext i + change e (∑ v : BucketSampler.Direction ℓ, v.val i • tape v) = + ∑ v : BucketSampler.Direction ℓ, v.val i • e (tape v) + simp only [map_sum, map_smul] + +theorem transportRows_evaluate (rows : Nat → Nat) (p : Path branch N (cut + 1)) + (slots : Slots branch N → Fin t → MixedSupport.Slot) + (tape : BucketSampler.Tape (rows (cut + 1)) (H (cutSlots p slots))) : + transportRows rows p slots + (BucketSampler.evaluate (rows (cut + 1)) (id : H (cutSlots p slots) → _) tape) = + BucketSampler.evaluate (rows (Nodes.height (upperNode p))) + (id : NodeEmbedding.RowSpace slots (upperNode p) → _) (bucketTapeEquiv rows p slots tape) := + evaluate_equiv (congrArg rows (upperNode_height p)).symm (cutRowEquiv p slots) tape + +theorem matrixOfRows_evaluate (rows : Nat → Nat) (p : Path branch N (cut + 1)) + (slots : Slots branch N → Fin t → MixedSupport.Slot) + (tape : BucketSampler.Tape (rows (cut + 1)) (H (cutSlots p slots))) : + matrixOfRows rows p slots + (BucketSampler.evaluate (rows (cut + 1)) (id : H (cutSlots p slots) → _) tape) = + BucketMatrixResampling.assembledMatrix (NodeEmbedding.RowSpace slots (upperNode p)) + (rows (Nodes.height (upperNode p))) (bucketTapeEquiv rows p slots tape) := by + unfold matrixOfRows BucketMatrixResampling.assembledMatrix + rw [transportRows_evaluate] + +end +end PerfectCompleteness.CutNodeRows + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/DescendantSpacesLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/DescendantSpacesLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..4f3da1f0cf022cb0fcbd46d7255430afba37029b --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/DescendantSpacesLemmas.lean @@ -0,0 +1,184 @@ +import OAI.Computability.PerfectCompleteness.Construction.FactoredFunctionsLemmas +import OAI.Computability.PerfectCompleteness.Foundations.PartitionsLemmas +import OAI.Computability.PerfectCompleteness.Foundations.RecursiveSpaces + +namespace OAI + + +namespace PerfectCompleteness.DescendantSpaces + +open PointwiseSpaces RecursiveSpaces + +universe u w + +inductive Path (branch : Nat → Nat) : Nat → Nat → Type + | refl (n : Nat) : Path branch n n + | step {n m : Nat} (i : Fin (branch n)) (tail : Path branch n m) : + Path branch (n + 1) m + +namespace Path + +variable {branch : Nat → Nat} {n m : Nat} + +def slotEmbedding : {n m : Nat} → Path branch n m → Slots branch m → Slots branch n + | _, _, .refl _, s => s + | _, _, .step i p, s => (i, slotEmbedding p s) + +@[simp] theorem slotEmbedding_refl (s : Slots branch n) : + slotEmbedding (.refl n) s = s := rfl + +@[simp] theorem slotEmbedding_step (i : Fin (branch n)) (p : Path branch n m) + (s : Slots branch m) : + slotEmbedding (.step i p) s = (i, slotEmbedding p s) := rfl + +theorem slotEmbedding_injective (p : Path branch n m) : + Function.Injective p.slotEmbedding := by + induction p with + | refl n => exact fun _ _ h => h + | step i p ih => + intro s t h + exact ih (congrArg Prod.snd h) + +theorem height_le (p : Path branch n m) : m ≤ n := by + induction p with + | refl n => exact Nat.le_refl n + | step i p ih => exact Nat.le_trans ih (Nat.le_succ _) + +abbrev family (p : Path branch n m) (A : Slots branch n → Type u) : + Slots branch m → Type u := fun s => A (p.slotEmbedding s) + +def restriction (p : Path branch n m) (A : Slots branch n → Type u) : + Assignment A → Assignment (p.family A) := fun x s => x (p.slotEmbedding s) + +@[simp] theorem restriction_apply (p : Path branch n m) + (A : Slots branch n → Type u) (x : Assignment A) (s : Slots branch m) : + p.restriction A x s = x (p.slotEmbedding s) := rfl + +@[simp] theorem restriction_refl (A : Slots branch n → Type u) : + restriction (.refl n) A = id := rfl + +theorem restriction_step (A : Slots branch (n + 1) → Type u) + (i : Fin (branch n)) (p : Path branch n m) : + restriction (.step i p) A = + p.restriction (childFamily A i) ∘ childRestriction A i := rfl + +theorem restriction_surjective (p : Path branch n m) : + ∀ (A : Slots branch n → Type u), (∀ s, Nonempty (A s)) → + Function.Surjective (p.restriction A) := by + induction p with + | refl n => + intro A _ y + exact ⟨y, rfl⟩ + | step i p ih => + intro A hnonempty + exact (ih (childFamily A i) (fun s => hnonempty (i, s))).comp + (childRestriction_surjective A hnonempty i) + +end Path + +variable {𝕜 : Type w} [Field 𝕜] {branch : Nat → Nat} {n m : Nat} + +theorem space_descendant_le (p : Path branch n m) : + ∀ (A : Slots branch n → Type u), (∀ k < n, 0 < branch k) → + (space 𝕜 branch m (p.family A)).map (pullback 𝕜 (p.restriction A)) ≤ + space 𝕜 branch n A := by + induction p with + | refl n => + intro A _ f hf + obtain ⟨g, hg, rfl⟩ := Submodule.mem_map.mp hf + exact hg + | @step n m i p ih => + intro A hbranch f hf + obtain ⟨g, hg, rfl⟩ := Submodule.mem_map.mp hf + have hb : ∀ k < n, 0 < branch k := + fun k hk => hbranch k (Nat.lt_trans hk (Nat.lt_succ_self n)) + have hchild : pullback 𝕜 (p.restriction (childFamily A i)) g ∈ + space 𝕜 branch n (childFamily A i) := + ih (childFamily A i) hb (Submodule.mem_map_of_mem hg) + exact child_le_space A i hb (Submodule.mem_map_of_mem hchild) + +theorem squareSpace_descendant_le (p : Path branch n m) + (A : Slots branch n → Type u) (hbranch : ∀ k < n, 0 < branch k) : + (squareSpace (space 𝕜 branch m (p.family A))).map + (pullback 𝕜 (p.restriction A)) ≤ squareSpace (space 𝕜 branch n A) := + squareSpace_pullback_le _ _ _ (space_descendant_le p A hbranch) + +theorem step_square_le_space (A : Slots branch (n + 1) → Type u) + (i : Fin (branch n)) (p : Path branch n m) + (hbranch : ∀ k < n, 0 < branch k) : + (squareSpace (space 𝕜 branch m ((Path.step i p).family A))).map + (pullback 𝕜 ((Path.step i p).restriction A)) ≤ space 𝕜 branch (n + 1) A := by + intro f hf + obtain ⟨g, hg, rfl⟩ := Submodule.mem_map.mp hf + have hchild : pullback 𝕜 (p.restriction (childFamily A i)) g ∈ + squareSpace (space 𝕜 branch n (childFamily A i)) := + squareSpace_descendant_le p (childFamily A i) hbranch + (Submodule.mem_map_of_mem hg) + exact child_square_le_space A i (Submodule.mem_map_of_mem hchild) + +theorem descendant_square_le_space (p : Path branch n m) + (A : Slots branch n → Type u) (hbranch : ∀ k < n, 0 < branch k) + (hproper : m < n) : + (squareSpace (space 𝕜 branch m (p.family A))).map + (pullback 𝕜 (p.restriction A)) ≤ space 𝕜 branch n A := by + cases p with + | refl n => exact False.elim (Nat.lt_irrefl n hproper) + | @step n m i p => + exact step_square_le_space A i p + (fun k hk => hbranch k (Nat.lt_trans hk (Nat.lt_succ_self n))) + +theorem descendant_pullback_injective (p : Path branch n m) + (A : Slots branch n → Type u) (hnonempty : ∀ s, Nonempty (A s)) : + Function.Injective (pullback 𝕜 (p.restriction A)) := + pullback_injective _ (p.restriction_surjective A hnonempty) + +end PerfectCompleteness.DescendantSpaces + + + +namespace PerfectCompleteness.DescendantProducts + +open RecursiveSpaces DescendantSpaces PointwiseSpaces FactoredFunctionsDependent + +variable {𝕜 I : Type*} [Field 𝕜] {branch : Nat → Nat} {n : Nat} + {height : I → Nat} {Row : I → Type*} + +def lower (domains : Slots branch n → Type*) + (paths : ∀ i, Path branch n (height i)) + (rows : ∀ i, Row i → space 𝕜 branch (height i) ((paths i).family domains)) : + Assignment domains → (i : I) → Row i → 𝕜 := + fun x i row => (rows i row).val ((paths i).restriction domains x) + +theorem quadraticSpan_le_ancestor (domains : Slots branch n → Type*) + (hbranch : ∀ k < n, 0 < branch k) + (paths : ∀ i, Path branch n (height i)) (hproper : ∀ i, height i < n) + (rows : ∀ i, Row i → space 𝕜 branch (height i) ((paths i).family domains)) : + dependentQuadraticSpan (lower domains paths rows) ≤ space 𝕜 branch n domains := by + apply Submodule.span_le.mpr + intro f hf + rcases hf with rfl | ⟨i, t, u, rfl⟩ + · exact one_mem_space branch n domains hbranch + · have hp : (rows i t).val * (rows i u).val ∈ + squareSpace (space 𝕜 branch (height i) ((paths i).family domains)) := + mul_mem_squareSpace _ (rows i t).property (rows i u).property + exact descendant_square_le_space (paths i) domains hbranch (hproper i) + (Submodule.mem_map_of_mem hp) + +theorem quadraticSpan_le_displayed (domains : Slots branch n → Type*) + (paths : ∀ i, Path branch n (height i)) + (rows : ∀ i, Row i → space 𝕜 branch (height i) ((paths i).family domains)) : + dependentQuadraticSpan (lower domains paths rows) ≤ + FactoredFunctions.factoringSpace (lower domains paths rows) := + dependentQuadraticSpan_le_factoringSpace _ + +def ancestorRow (domains : Slots branch n → Type*) + (hbranch : ∀ k < n, 0 < branch k) + (paths : ∀ i, Path branch n (height i)) (hproper : ∀ i, height i < n) + (rows : ∀ i, Row i → space 𝕜 branch (height i) ((paths i).family domains)) + (shift : dependentQuadraticSpan (lower domains paths rows)) : + space 𝕜 branch n domains := + ⟨shift.val, quadraticSpan_le_ancestor domains hbranch paths hproper rows shift.property⟩ + +end PerfectCompleteness.DescendantProducts + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/FactoredFunctionsLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/FactoredFunctionsLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..03e55e6d9ddf29eeca01478ba5ab3c3ecf6ab7ae --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/FactoredFunctionsLemmas.lean @@ -0,0 +1,165 @@ +import Mathlib.LinearAlgebra.Pi +import Mathlib.LinearAlgebra.Span.Basic + +namespace OAI + + +namespace PerfectCompleteness.FactoredFunctions + +variable {𝕜 Ω Z I J : Type*} [Field 𝕜] + +def factoringSpace (other : Ω → Z) : Submodule 𝕜 (Ω → 𝕜) where + carrier := {f | ∀ x y, other x = other y → f x = f y} + zero_mem' := by intro x y _; rfl + add_mem' := by + intro f g hf hg x y h + change f x + g x = f y + g y + rw [hf x y h, hg x y h] + smul_mem' := by + intro c f hf x y h + change c • f x = c • f y + rw [hf x y h] + +@[simp] theorem mem_factoringSpace (other : Ω → Z) (f : Ω → 𝕜) : + f ∈ factoringSpace other ↔ ∀ x y, other x = other y → f x = f y := Iff.rfl + +theorem mem_factoringSpace_iff_exists_factor (other : Ω → Z) (f : Ω → 𝕜) : + f ∈ factoringSpace other ↔ ∃ g : Z → 𝕜, ∀ x, f x = g (other x) := by + classical + constructor + · intro hf + let g : Z → 𝕜 := fun z => + if h : ∃ x, other x = z then f (Classical.choose h) else 0 + refine ⟨g, ?_⟩ + intro x + have hx : ∃ y, other y = other x := ⟨x, rfl⟩ + change f x = if h : ∃ y, other y = other x then f (Classical.choose h) else 0 + rw [dite_eq_left hx] + exact hf x _ (Classical.choose_spec hx).symm + · rintro ⟨g, hg⟩ x y h + rw [hg x, hg y, h] + +theorem const_mem_factoringSpace (other : Ω → Z) (c : 𝕜) : + (fun _ : Ω => c) ∈ factoringSpace other := by + intro x y _ + rfl + +theorem one_mem_factoringSpace (other : Ω → Z) : + (1 : Ω → 𝕜) ∈ factoringSpace other := + const_mem_factoringSpace other 1 + +theorem mul_mem_factoringSpace (other : Ω → Z) {f g : Ω → 𝕜} + (hf : f ∈ factoringSpace other) (hg : g ∈ factoringSpace other) : + f * g ∈ factoringSpace other := by + intro x y h + change f x * g x = f y * g y + rw [hf x y h, hg x y h] + +theorem coordinate_mem_factoringSpace (lower : Ω → I → J → 𝕜) (i : I) (t : J) : + (fun x => lower x i t) ∈ factoringSpace lower := by + intro x y h + exact congrFun (congrFun h i) t + +def quadraticSpan (lower : Ω → I → J → 𝕜) : Submodule 𝕜 (Ω → 𝕜) := + Submodule.span 𝕜 {f | f = 1 ∨ + ∃ (i : I) (t u : J), f = fun x => lower x i t * lower x i u} + +theorem one_mem_quadraticSpan (lower : Ω → I → J → 𝕜) : + (1 : Ω → 𝕜) ∈ quadraticSpan lower := + Submodule.subset_span (Or.inl rfl) + +theorem product_mem_quadraticSpan (lower : Ω → I → J → 𝕜) (i : I) (t u : J) : + (fun x => lower x i t * lower x i u) ∈ quadraticSpan lower := + Submodule.subset_span (Or.inr ⟨i, t, u, rfl⟩) + +theorem quadraticSpan_le_factoringSpace (lower : Ω → I → J → 𝕜) : + quadraticSpan lower ≤ factoringSpace lower := by + apply Submodule.span_le.mpr + intro f hf + rcases hf with rfl | ⟨i, t, u, rfl⟩ + · exact one_mem_factoringSpace lower + · exact mul_mem_factoringSpace lower + (coordinate_mem_factoringSpace lower i t) (coordinate_mem_factoringSpace lower i u) + +noncomputable section + +def realizer (other : Ω → Z) (z : Set.range other) : Ω := + Classical.choose z.property + +theorem realizer_spec (other : Ω → Z) (z : Set.range other) : + other (realizer other z) = z.val := + Classical.choose_spec z.property + +def evaluation {other : Ω → Z} {B : Submodule 𝕜 (Ω → 𝕜)} + (_hB : B ≤ factoringSpace other) (z : Set.range other) : B →ₗ[𝕜] 𝕜 := + (LinearMap.proj (realizer other z)).comp B.subtype + +@[simp] theorem evaluation_apply {other : Ω → Z} {B : Submodule 𝕜 (Ω → 𝕜)} + (hB : B ≤ factoringSpace other) (z : Set.range other) (b : B) : + evaluation hB z b = b.val (realizer other z) := rfl + +theorem evaluation_apply_of_eq {other : Ω → Z} {B : Submodule 𝕜 (Ω → 𝕜)} + (hB : B ≤ factoringSpace other) (z : Set.range other) (x : Ω) + (hx : other x = z.val) (b : B) : evaluation hB z b = b.val x := + hB b.property (realizer other z) x ((realizer_spec other z).trans hx.symm) + +theorem evaluation_eq_pointEvaluation {other : Ω → Z} {B : Submodule 𝕜 (Ω → 𝕜)} + (hB : B ≤ factoringSpace other) (z : Set.range other) (x : Ω) + (hx : other x = z.val) : + evaluation hB z = (LinearMap.proj x).comp B.subtype := by + apply LinearMap.ext + intro b + exact evaluation_apply_of_eq hB z x hx b + +@[simp] theorem evaluation_at_image {other : Ω → Z} {B : Submodule 𝕜 (Ω → 𝕜)} + (hB : B ≤ factoringSpace other) (x : Ω) (b : B) : + evaluation hB ⟨other x, ⟨x, rfl⟩⟩ b = b.val x := + evaluation_apply_of_eq hB _ x rfl b + +theorem evaluation_one {other : Ω → Z} {B : Submodule 𝕜 (Ω → 𝕜)} + (hB : B ≤ factoringSpace other) (z : Set.range other) (h1 : (1 : Ω → 𝕜) ∈ B) : + evaluation hB z ⟨1, h1⟩ = 1 := rfl + +end +end PerfectCompleteness.FactoredFunctions + + + +namespace PerfectCompleteness.FactoredFunctionsDependent + +open PerfectCompleteness.FactoredFunctions + +variable {𝕜 Ω I : Type*} [Field 𝕜] {J : I → Type*} + +theorem coordinate_mem_factoringSpace (lower : Ω → (i : I) → J i → 𝕜) + (i : I) (t : J i) : + (fun x => lower x i t) ∈ factoringSpace lower := by + intro x y h + exact congrFun (congrFun h i) t + +def dependentQuadraticSpan (lower : Ω → (i : I) → J i → 𝕜) : + Submodule 𝕜 (Ω → 𝕜) := + Submodule.span 𝕜 {f | f = 1 ∨ + ∃ (i : I) (t u : J i), f = fun x => lower x i t * lower x i u} + +theorem one_mem_dependentQuadraticSpan (lower : Ω → (i : I) → J i → 𝕜) : + (1 : Ω → 𝕜) ∈ dependentQuadraticSpan lower := + Submodule.subset_span (Or.inl rfl) + +theorem product_mem_dependentQuadraticSpan (lower : Ω → (i : I) → J i → 𝕜) + (i : I) (t u : J i) : + (fun x => lower x i t * lower x i u) ∈ dependentQuadraticSpan lower := + Submodule.subset_span (Or.inr ⟨i, t, u, rfl⟩) + +theorem dependentQuadraticSpan_le_factoringSpace (lower : Ω → (i : I) → J i → 𝕜) : + dependentQuadraticSpan lower ≤ factoringSpace lower := by + apply Submodule.span_le.mpr + intro f hf + rcases hf with rfl | ⟨i, t, u, rfl⟩ + · exact one_mem_factoringSpace lower + · exact mul_mem_factoringSpace lower + (coordinate_mem_factoringSpace lower i t) (coordinate_mem_factoringSpace lower i u) + +end PerfectCompleteness.FactoredFunctionsDependent + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/FlexibleLocalCompletionLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/FlexibleLocalCompletionLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..0e8ff3a62606577306a119066c38ec1a4c212f48 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/FlexibleLocalCompletionLemmas.lean @@ -0,0 +1,237 @@ +import Mathlib.Logic.Equiv.Set +import OAI.Computability.PerfectCompleteness.Construction.LocalCompletionFamily + +namespace OAI + + +namespace PerfectCompleteness.FlexibleLocalCompletion + +open scoped Classical +open CompletionSoundness CompletionSoundness.LegalProjectionGame + +noncomputable section + +variable {E Q₁ Q₂ : Type*} [Fintype E] + {L : Q₁ → Type*} {R : Q₂ → Type*} [∀ x, Fintype (L x)] + {q : Nat} + (G : LegalProjectionGame E Q₁ Q₂ L R) + (legalL : ∀ x, L x ↪ Fin (2 * q)) (legalR : ∀ y, R y ↪ Fin q) + +structure Compatible (data : E → LocalCompletionFamily.Input q) : Prop where + mask : ∀ e a, (data e).1 a = true ↔ a ∈ Set.range (legalL (G.left e)) + image : ∀ e l, (data e).2 (legalL (G.left e) l) = + legalR (G.right e) (G.projection e l) + +variable (data : E → LocalCompletionFamily.Input q) + (compatible : Compatible G legalL legalR data) + +def localLegalEquiv (e : E) : L (G.left e) ≃ LocalCompletionFamily.Legal (data e) := + (Equiv.ofInjective (legalL (G.left e)) (legalL (G.left e)).injective).trans + (Equiv.subtypeEquivRight (fun a => (compatible.mask e a).symm)) + +omit [∀ x, Fintype (L x)] in +@[simp] theorem localLegalEquiv_apply_val (e : E) (l : L (G.left e)) : + (localLegalEquiv G legalL legalR data compatible e l).val = legalL (G.left e) l := rfl + +include legalL legalR compatible in +theorem card_legal (e : E) : + Fintype.card (LocalCompletionFamily.Legal (data e)) = Fintype.card (L (G.left e)) := + (Fintype.card_congr (localLegalEquiv G legalL legalR data compatible e)).symm + +include legalL legalR compatible in + +theorem input_admissible + (hsmall : ∀ e b, Fintype.card {l : L (G.left e) // G.projection e l = b} ≤ 2) + (e : E) : LocalCompletionFamily.Admissible (data e) := by + intro b + rw [Fintype.card_eq_nat_card] + have hmatch (l : L (G.left e)) : + (data e).2 (localLegalEquiv G legalL legalR data compatible e l).val = + legalR (G.right e) (G.projection e l) := by + rw [localLegalEquiv_apply_val] + exact compatible.image e l + let fibers : {l : L (G.left e) // legalR (G.right e) (G.projection e l) = b} ≃ + {a : LocalCompletionFamily.Legal (data e) // (data e).2 a.val = b} := + (localLegalEquiv G legalL legalR data compatible e).subtypeEquiv + (fun l => by rw [hmatch l]) + have hcard := Nat.card_congr fibers + have hbound := embedded_fiber_le_two (legalR (G.right e)) (G.projection e) (hsmall e) b + rw [Fintype.card_eq_nat_card] at hbound + exact hcard.symm.le.trans hbound + +def result (hq : 0 < q) (e : E) : LocalCompletionFamily.Result q := + LocalCompletionFamily.lookup hq (data e) + +include legalL legalR compatible in +theorem result_correct (hq : 0 < q) + (hsmall : ∀ e b, Fintype.card {l : L (G.left e) // G.projection e l = b} ≤ 2) + (e : E) : LocalCompletionFamily.Correct (data e) (result data hq e) := + LocalCompletionFamily.lookup_correct hq (data e) + (input_admissible G legalL legalR data compatible hsmall e) + +def family (hq : 0 < q) + (hsmall : ∀ e b, Fintype.card {l : L (G.left e) // G.projection e l = b} ≤ 2) : + G.CompletionFamily legalL legalR where + size e := LocalCompletionFamily.activeCount (result data hq e) + positive e := LocalCompletionFamily.activeCount_positive _ + map e := LocalCompletionFamily.table (result data hq e) + agrees e seed l := + ((result_correct G legalL legalR data compatible hq hsmall e).agrees seed + (legalL (G.left e) l) ((compatible.mask e _).2 ⟨l, rfl⟩)).trans + (compatible.image e l) + exact_two e seed b := by + rw [Fintype.card_eq_nat_card] + have h := (result_correct G legalL legalR data compatible hq hsmall e).exact_two seed b + rw [Fintype.card_eq_nat_card] at h + exact h + illegal_probability e a b := by + have hmask : (data e).1 a.val ≠ true := by + intro h + exact a.property ((compatible.mask e a.val).1 h) + have h := (result_correct G legalL legalR data compatible hq hsmall e).illegal_probability + a.val hmask b + simpa only [Fintype.card_fin, card_legal G legalL legalR data compatible] using h + +@[simp] theorem family_size (hq : 0 < q) + (hsmall : ∀ e b, Fintype.card {l : L (G.left e) // G.projection e l = b} ≤ 2) (e : E) : + (family G legalL legalR data compatible hq hsmall).size e = + LocalCompletionFamily.activeCount (LocalCompletionFamily.lookup hq (data e)) := rfl + +@[simp] theorem family_map (hq : 0 < q) + (hsmall : ∀ e b, Fintype.card {l : L (G.left e) // G.projection e l = b} ≤ 2) (e : E) : + (family G legalL legalR data compatible hq hsmall).map e = + LocalCompletionFamily.table (LocalCompletionFamily.lookup hq (data e)) := rfl + +theorem family_size_le (hq : 0 < q) + (hsmall : ∀ e b, Fintype.card {l : L (G.left e) // G.projection e l = b} ≤ 2) (e : E) : + (family G legalL legalR data compatible hq hsmall).size e ≤ 2 * q := + LocalCompletionFamily.activeCount_le (result data hq e) + +end +end PerfectCompleteness.FlexibleLocalCompletion + + +namespace PerfectCompleteness.LocalCompletionGame + +open scoped Classical +open UniqueGamesTheorem.Foundations.Games +open CompletionSoundness CompletionSoundness.LegalProjectionGame + +noncomputable section + +variable {E Q₁ Q₂ : Type*} [Fintype E] + {L : Q₁ → Type*} {R : Q₂ → Type*} [∀ x, Fintype (L x)] + {q : Nat} + (G : LegalProjectionGame E Q₁ Q₂ L R) + (legalL : ∀ x, L x ↪ Fin (2 * q)) (legalR : ∀ y, R y ↪ Fin q) + (defaultL : ∀ x, L x) + +def input (e : E) : LocalCompletionFamily.Input q := + (fun a => decide (a ∈ Set.range (legalL (G.left e))), + fun a => legalR (G.right e) + (G.projection e (roundLabel (legalL (G.left e)) (defaultL (G.left e)) a))) + +theorem input_mask_true (e : E) (a : Fin (2 * q)) : + (input G legalL legalR defaultL e).1 a = true ↔ + a ∈ Set.range (legalL (G.left e)) := by + simp only [input, decide_eq_true_iff] + +theorem input_image_legal (e : E) (l : L (G.left e)) : + (input G legalL legalR defaultL e).2 (legalL (G.left e) l) = + legalR (G.right e) (G.projection e l) := by + simp only [input, roundLabel_legal] + +def localLegalEquiv (e : E) : + L (G.left e) ≃ LocalCompletionFamily.Legal (input G legalL legalR defaultL e) where + toFun l := ⟨legalL (G.left e) l, + (input_mask_true G legalL legalR defaultL e _).2 ⟨l, rfl⟩⟩ + invFun a := roundLabel (legalL (G.left e)) (defaultL (G.left e)) a.val + left_inv l := roundLabel_legal (legalL (G.left e)) (defaultL (G.left e)) l + right_inv a := by + apply Subtype.ext + obtain ⟨l, hl⟩ := (input_mask_true G legalL legalR defaultL e a.val).1 a.property + change legalL (G.left e) + (roundLabel (legalL (G.left e)) (defaultL (G.left e)) a.val) = a.val + rw [← hl, roundLabel_legal] + +@[simp] theorem localLegalEquiv_apply_val (e : E) (l : L (G.left e)) : + (localLegalEquiv G legalL legalR defaultL e l).val = legalL (G.left e) l := rfl + +theorem card_legal (e : E) : + Fintype.card (LocalCompletionFamily.Legal (input G legalL legalR defaultL e)) = + Fintype.card (L (G.left e)) := + (Fintype.card_congr (localLegalEquiv G legalL legalR defaultL e)).symm + +theorem input_admissible + (hsmall : ∀ e b, Fintype.card {l : L (G.left e) // G.projection e l = b} ≤ 2) + (e : E) : LocalCompletionFamily.Admissible (input G legalL legalR defaultL e) := by + intro b + have hmatch (l : L (G.left e)) : + (input G legalL legalR defaultL e).2 + (localLegalEquiv G legalL legalR defaultL e l).val = + legalR (G.right e) (G.projection e l) := by + rw [localLegalEquiv_apply_val] + exact input_image_legal G legalL legalR defaultL e l + let fibers : {l : L (G.left e) // legalR (G.right e) (G.projection e l) = b} ≃ + {a : LocalCompletionFamily.Legal (input G legalL legalR defaultL e) // + (input G legalL legalR defaultL e).2 a.val = b} := + (localLegalEquiv G legalL legalR defaultL e).subtypeEquiv + (fun l => by rw [hmatch l]) + have hcard := Fintype.card_congr fibers + have hbound := embedded_fiber_le_two (legalR (G.right e)) (G.projection e) (hsmall e) b + simp only [← Nat.card_eq_fintype_card] at hcard hbound ⊢ + exact hcard.symm.le.trans hbound + +def result (hq : 0 < q) (e : E) : LocalCompletionFamily.Result q := + LocalCompletionFamily.lookup hq (input G legalL legalR defaultL e) + +theorem result_correct (hq : 0 < q) + (hsmall : ∀ e b, Fintype.card {l : L (G.left e) // G.projection e l = b} ≤ 2) + (e : E) : LocalCompletionFamily.Correct (input G legalL legalR defaultL e) + (result G legalL legalR defaultL hq e) := + LocalCompletionFamily.lookup_correct hq _ + (input_admissible G legalL legalR defaultL hsmall e) + +def family (hq : 0 < q) + (hsmall : ∀ e b, Fintype.card {l : L (G.left e) // G.projection e l = b} ≤ 2) : + G.CompletionFamily legalL legalR where + size e := LocalCompletionFamily.activeCount (result G legalL legalR defaultL hq e) + positive e := LocalCompletionFamily.activeCount_positive _ + map e := LocalCompletionFamily.table (result G legalL legalR defaultL hq e) + agrees e seed l := + ((result_correct G legalL legalR defaultL hq hsmall e).agrees seed + (legalL (G.left e) l) + ((input_mask_true G legalL legalR defaultL e _).2 ⟨l, rfl⟩)).trans + (input_image_legal G legalL legalR defaultL e l) + exact_two e seed b := by + simpa only [← Nat.card_eq_fintype_card] using + (result_correct G legalL legalR defaultL hq hsmall e).exact_two seed b + illegal_probability e a b := by + have hmask : (input G legalL legalR defaultL e).1 a.val ≠ true := by + intro h + exact a.property ((input_mask_true G legalL legalR defaultL e a.val).1 h) + have h := (result_correct G legalL legalR defaultL hq hsmall e).illegal_probability + a.val hmask b + simpa only [Fintype.card_fin, card_legal] using h + +@[simp] theorem family_size (hq : 0 < q) + (hsmall : ∀ e b, Fintype.card {l : L (G.left e) // G.projection e l = b} ≤ 2) (e : E) : + (family G legalL legalR defaultL hq hsmall).size e = + LocalCompletionFamily.activeCount + (LocalCompletionFamily.lookup hq (input G legalL legalR defaultL e)) := rfl + +@[simp] theorem family_map (hq : 0 < q) + (hsmall : ∀ e b, Fintype.card {l : L (G.left e) // G.projection e l = b} ≤ 2) (e : E) : + (family G legalL legalR defaultL hq hsmall).map e = + LocalCompletionFamily.table + (LocalCompletionFamily.lookup hq (input G legalL legalR defaultL e)) := rfl + +theorem family_size_le (hq : 0 < q) + (hsmall : ∀ e b, Fintype.card {l : L (G.left e) // G.projection e l = b} ≤ 2) (e : E) : + (family G legalL legalR defaultL hq hsmall).size e ≤ 2 * q := + LocalCompletionFamily.activeCount_le (result G legalL legalR defaultL hq e) + +end +end PerfectCompleteness.LocalCompletionGame + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/HiddenBucketBias.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/HiddenBucketBias.lean new file mode 100644 index 0000000000000000000000000000000000000000..91554978cc1db3b75abb9d390d8101ad888a13fd --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/HiddenBucketBias.lean @@ -0,0 +1,323 @@ +import Mathlib.Algebra.CharP.Two +import Mathlib.Algebra.Group.AddChar +import Mathlib.LinearAlgebra.TensorProduct.Finiteness +import Mathlib.Logic.Equiv.Prod +import OAI.Computability.PerfectCompleteness.Foundations.QuarterBalanceLemmas +import OAI.Computability.PerfectCompleteness.Repetition.CleanConditioning +import OAI.Computability.PerfectCompleteness.Sampling.BucketSampler + +namespace OAI + + +namespace PerfectCompleteness.HiddenBucketBias + +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators TensorProduct Classical + +noncomputable section + +abbrev F2 := BucketSampler.F2 + +variable {ℓ : Nat} {Ω H : Type*} [Fintype Ω] + [AddCommGroup H] [Module F2 H] + +abbrev HiddenDirection (W : Submodule F2 (Fin ℓ → F2)) := + {v : BucketSampler.Direction ℓ // v.val ∈ W} + +abbrev VisibleDirection (W : Submodule F2 (Fin ℓ → F2)) := + {v : BucketSampler.Direction ℓ // v.val ∉ W} + +abbrev HiddenTape (W : Submodule F2 (Fin ℓ → F2)) (Ω : Type*) := HiddenDirection W → Ω +abbrev VisibleTape (W : Submodule F2 (Fin ℓ → F2)) (Ω : Type*) := VisibleDirection W → Ω + +def hiddenTapeLaw (W : Submodule F2 (Fin ℓ → F2)) (μ : FiniteDistribution Ω) : + FiniteDistribution (HiddenTape W Ω) := + FiniteProduct.law (fun _ : HiddenDirection W => μ) + +def visibleTapeLaw (W : Submodule F2 (Fin ℓ → F2)) (μ : FiniteDistribution Ω) : + FiniteDistribution (VisibleTape W Ω) := + FiniteProduct.law (fun _ : VisibleDirection W => μ) + +def splitTape (W : Submodule F2 (Fin ℓ → F2)) (Ω : Type*) : + BucketSampler.Tape ℓ Ω ≃ HiddenTape W Ω × VisibleTape W Ω := + Equiv.piEquivPiSubtypeProd (fun v : BucketSampler.Direction ℓ => v.val ∈ W) (fun _ => Ω) + +theorem split_tapeLaw (W : Submodule F2 (Fin ℓ → F2)) (μ : FiniteDistribution Ω) : + (BucketSampler.tapeLaw ℓ μ).transport (splitTape W Ω) = + (hiddenTapeLaw W μ).product (visibleTapeLaw W μ) := by + apply FiniteDistribution.eq_of_weight_eq + intro y + change (∏ v : BucketSampler.Direction ℓ, μ.weight ((splitTape W Ω).symm y v)) = + (∏ v : HiddenDirection W, μ.weight (y.1 v)) * + ∏ v : VisibleDirection W, μ.weight (y.2 v) + calc + _ = ∏ v : BucketSampler.Direction ℓ, + if h : v.val ∈ W then μ.weight (y.1 ⟨v, h⟩) else μ.weight (y.2 ⟨v, h⟩) := by + apply Finset.prod_congr rfl + intro v _ + by_cases hv : v.val ∈ W <;> simp [splitTape, Equiv.piEquivPiSubtypeProd, hv] + _ = _ := Fintype.prod_dite _ _ + +theorem split_tapeLaw_pushforward (W : Submodule F2 (Fin ℓ → F2)) + (μ : FiniteDistribution Ω) : + (BucketSampler.tapeLaw ℓ μ).pushforward (splitTape W Ω) = + (hiddenTapeLaw W μ).product (visibleTapeLaw W μ) := by + rw [← FiniteDistribution.transport_eq_pushforward] + exact split_tapeLaw W μ + +theorem product_fst {A B : Type*} [Fintype A] [Fintype B] + (μ : FiniteDistribution A) (ν : FiniteDistribution B) : + (μ.product ν).pushforward Prod.fst = μ := by + apply FiniteDistribution.eq_of_weight_eq + intro a + calc + _ = (μ.product ν).expectation (fun x => if x.1 = a then 1 else 0) := by + simp [FiniteDistribution.pushforward, FiniteDistribution.expectation, mul_ite] + _ = μ.expectation (fun x => ν.expectation (fun _ => if x = a then 1 else 0)) := + FiniteDistribution.expectation_product μ ν _ + _ = _ := by simp [FiniteDistribution.expectation, mul_ite, ν.normalized] + +theorem hidden_marginal (W : Submodule F2 (Fin ℓ → F2)) (μ : FiniteDistribution Ω) : + (BucketSampler.tapeLaw ℓ μ).pushforward + (fun ω (v : HiddenDirection W) => ω v.val) = hiddenTapeLaw W μ := by + change (BucketSampler.tapeLaw ℓ μ).pushforward + (fun ω => (splitTape W Ω ω).1) = _ + rw [← FiniteDistribution.pushforward_comp (BucketSampler.tapeLaw ℓ μ) + (splitTape W Ω) Prod.fst, split_tapeLaw_pushforward, product_fst] + +theorem hidden_coordinate_marginal (W : Submodule F2 (Fin ℓ → F2)) + (μ : FiniteDistribution Ω) (v : HiddenDirection W) : + (hiddenTapeLaw W μ).pushforward (fun ω => ω v) = μ := + FiniteProduct.eval_pushforward (fun _ : HiddenDirection W => μ) v + +theorem hidden_coordinates_independent (W : Submodule F2 (Fin ℓ → F2)) + (μ : FiniteDistribution Ω) (v w : HiddenDirection W) (hvw : v ≠ w) + (f g : Ω → ℝ) : + (hiddenTapeLaw W μ).expectation (fun ω => f (ω v) * g (ω w)) = + μ.expectation f * μ.expectation g := + FiniteProduct.expectation_eval_mul (fun _ : HiddenDirection W => μ) v w hvw f g + +def directionIn (W : Submodule F2 (Fin ℓ → F2)) (v : HiddenDirection W) : W := + ⟨v.val.val, v.property⟩ + +theorem directionIn_ne_zero (W : Submodule F2 (Fin ℓ → F2)) (v : HiddenDirection W) : + directionIn W v ≠ 0 := by + intro h + exact v.val.property (congrArg Subtype.val h) + +def hiddenSum (W : Submodule F2 (Fin ℓ → F2)) (eval : Ω → H) (ω : HiddenTape W Ω) : + W ⊗[F2] H := + ∑ v : HiddenDirection W, directionIn W v ⊗ₜ[F2] eval (ω v) + +def scalarRestriction (W : Submodule F2 (Fin ℓ → F2)) + (Φ : Module.Dual F2 (W ⊗[F2] H)) (v : W) : Module.Dual F2 H := + Φ.comp (TensorProduct.mk F2 W H v) + +@[simp] theorem scalarRestriction_apply (W : Submodule F2 (Fin ℓ → F2)) + (Φ : Module.Dual F2 (W ⊗[F2] H)) (v : W) (h : H) : + scalarRestriction W Φ v h = Φ (v ⊗ₜ[F2] h) := rfl + +theorem exists_nonzero_restriction (W : Submodule F2 (Fin ℓ → F2)) + (Φ : Module.Dual F2 (W ⊗[F2] H)) (hΦ : Φ ≠ 0) : + ∃ v : HiddenDirection W, scalarRestriction W Φ (directionIn W v) ≠ 0 := by + by_contra hn + apply hΦ + apply TensorProduct.ext' + intro v h + by_cases hv : v = 0 + · simp [hv] + · let d : HiddenDirection W := + ⟨⟨v.val, fun hzero => hv (Subtype.ext hzero)⟩, v.property⟩ + have hs : scalarRestriction W Φ (directionIn W d) = 0 := by + by_contra hs + exact hn ⟨d, hs⟩ + simpa only [scalarRestriction_apply, directionIn, d, LinearMap.zero_apply] using + LinearMap.congr_fun hs h + +theorem abs_character (χ : AddChar F2 ℝ) (b : F2) : |χ b| = 1 := by + have hs : χ b * χ b = 1 := by + rw [← χ.map_add_eq_mul, CharTwo.add_self_eq_zero, χ.map_zero_eq_one] + have hs' : χ b ^ 2 = 1 := by simpa only [pow_two] using hs + rcases sq_eq_one_iff.mp hs' with hb | hb <;> rw [hb] <;> norm_num + +def signCharacter : AddChar F2 ℝ where + toFun := QuarterBalance.sign + map_zero_eq_one' := QuarterBalance.sign_zero + map_add_eq_mul' := QuarterBalance.sign_add + +theorem character_sum {I : Type*} [Fintype I] (χ : AddChar F2 ℝ) (f : I → F2) : + χ (∑ i, f i) = ∏ i, χ (f i) := by + have h (s : Finset I) : χ (∑ i ∈ s, f i) = ∏ i ∈ s, χ (f i) := by + induction s using Finset.induction_on with + | empty => simp + | @insert i s hi ih => + rw [Finset.sum_insert hi, Finset.prod_insert hi, χ.map_add_eq_mul, ih] + exact h Finset.univ + +omit [Fintype Ω] in +theorem character_hiddenSum (W : Submodule F2 (Fin ℓ → F2)) + (eval : Ω → H) (χ : AddChar F2 ℝ) (Φ : Module.Dual F2 (W ⊗[F2] H)) + (ω : HiddenTape W Ω) : + χ (Φ (hiddenSum W eval ω)) = + ∏ v : HiddenDirection W, χ (scalarRestriction W Φ (directionIn W v) (eval (ω v))) := by + simp only [hiddenSum, map_sum, scalarRestriction_apply] + exact character_sum χ _ + +theorem character_expectation_product (W : Submodule F2 (Fin ℓ → F2)) + (μ : FiniteDistribution Ω) (eval : Ω → H) (χ : AddChar F2 ℝ) + (Φ : Module.Dual F2 (W ⊗[F2] H)) : + (hiddenTapeLaw W μ).expectation (fun ω => χ (Φ (hiddenSum W eval ω))) = + ∏ v : HiddenDirection W, + μ.expectation (fun ω => χ (scalarRestriction W Φ (directionIn W v) (eval ω))) := by + let f : HiddenDirection W → Ω → ℝ := + fun v ω => χ (scalarRestriction W Φ (directionIn W v) (eval ω)) + have hprod := FiniteProduct.expectation_product + (I := HiddenDirection W) (Ω := fun _ : HiddenDirection W => Ω) + (fun _ : HiddenDirection W => μ) f + calc + _ = (hiddenTapeLaw W μ).expectation (fun ω => ∏ v : HiddenDirection W, f v (ω v)) := + FiniteDistribution.expectation_congr _ (fun ω => character_hiddenSum W eval χ Φ ω) + _ = _ := hprod + +theorem abs_expectation_character_le_one (μ : FiniteDistribution Ω) + (χ : AddChar F2 ℝ) (f : Ω → F2) : |μ.expectation (fun ω => χ (f ω))| ≤ 1 := by + calc + _ ≤ ∑ ω, |μ.weight ω * χ (f ω)| := Finset.abs_sum_le_sum_abs _ _ + _ = ∑ ω, μ.weight ω := by + apply Finset.sum_congr rfl + intro ω _ + rw [abs_mul, abs_of_nonneg (μ.nonnegative ω), abs_character, mul_one] + _ = 1 := μ.normalized + +theorem hidden_bias_le (W : Submodule F2 (Fin ℓ → F2)) + (μ : FiniteDistribution Ω) (eval : Ω → H) (χ : AddChar F2 ℝ) (bound : ℝ) + (scalar_bias : ∀ f : Module.Dual F2 H, f ≠ 0 → + |μ.expectation (fun ω => χ (f (eval ω)))| ≤ bound) + (Φ : Module.Dual F2 (W ⊗[F2] H)) (hΦ : Φ ≠ 0) : + |(hiddenTapeLaw W μ).expectation (fun ω => χ (Φ (hiddenSum W eval ω)))| ≤ bound := by + obtain ⟨v, hv⟩ := exists_nonzero_restriction W Φ hΦ + rw [character_expectation_product, Finset.abs_prod] + let a : HiddenDirection W → ℝ := fun w => + |μ.expectation (fun ω => χ (scalarRestriction W Φ (directionIn W w) (eval ω)))| + change (∏ w, a w) ≤ bound + rw [← Finset.mul_prod_erase Finset.univ a (Finset.mem_univ v)] + have hrest : (∏ w ∈ Finset.univ.erase v, a w) ≤ 1 := + Finset.prod_le_one₀ (fun _ _ => abs_nonneg _) + (fun w _ => abs_expectation_character_le_one μ χ _) + calc + _ ≤ a v * 1 := mul_le_mul_of_nonneg_left hrest (abs_nonneg _) + _ = a v := mul_one _ + _ ≤ bound := scalar_bias _ hv + +theorem hidden_sign_bias_le (W : Submodule F2 (Fin ℓ → F2)) + (μ : FiniteDistribution Ω) (eval : Ω → H) (bound : ℝ) + (scalar_bias : ∀ f : Module.Dual F2 H, f ≠ 0 → + |μ.expectation (fun ω => QuarterBalance.sign (f (eval ω)))| ≤ bound) + (Φ : Module.Dual F2 (W ⊗[F2] H)) (hΦ : Φ ≠ 0) : + |(hiddenTapeLaw W μ).expectation + (fun ω => QuarterBalance.sign (Φ (hiddenSum W eval ω)))| ≤ bound := + hidden_bias_le W μ eval signCharacter bound scalar_bias Φ hΦ + +instance tensorFinite (W : Submodule F2 (Fin ℓ → F2)) [Finite H] : + Finite (W ⊗[F2] H) := by + let : Fintype W := Fintype.ofFinite _ + apply Finite.of_surjective (fun f : W → H => ∑ w, w ⊗ₜ[F2] f w) + intro z + obtain ⟨s, hs⟩ := TensorProduct.exists_finsupp_left z + refine ⟨fun w => s w, ?_⟩ + exact (s.sum_fintype (fun w h => w ⊗ₜ[F2] h) (fun _ => by simp)).symm.trans hs.symm + +instance tensorFintype (W : Submodule F2 (Fin ℓ → F2)) [Finite H] : + Fintype (W ⊗[F2] H) := Fintype.ofFinite _ + +def law (W : Submodule F2 (Fin ℓ → F2)) [Finite H] + (μ : FiniteDistribution Ω) (eval : Ω → H) : FiniteDistribution (W ⊗[F2] H) := + (hiddenTapeLaw W μ).pushforward (hiddenSum W eval) + +theorem law_from_full_buckets (W : Submodule F2 (Fin ℓ → F2)) [Finite H] + (μ : FiniteDistribution Ω) (eval : Ω → H) : + (BucketSampler.tapeLaw ℓ μ).pushforward + (fun ω => hiddenSum W eval (fun v => ω v.val)) = law W μ eval := by + rw [← FiniteDistribution.pushforward_comp (BucketSampler.tapeLaw ℓ μ) + (fun ω (v : HiddenDirection W) => ω v.val) (hiddenSum W eval), hidden_marginal] + rfl + +theorem law_bias_le (W : Submodule F2 (Fin ℓ → F2)) [Finite H] + (μ : FiniteDistribution Ω) (eval : Ω → H) (χ : AddChar F2 ℝ) (bound : ℝ) + (scalar_bias : ∀ f : Module.Dual F2 H, f ≠ 0 → + |μ.expectation (fun ω => χ (f (eval ω)))| ≤ bound) + (Φ : Module.Dual F2 (W ⊗[F2] H)) (hΦ : Φ ≠ 0) : + |(law W μ eval).expectation (fun x => χ (Φ x))| ≤ bound := by + rw [law, FiniteDistribution.expectation_pushforward] + exact hidden_bias_le W μ eval χ bound scalar_bias Φ hΦ + +theorem law_sign_bias_le (W : Submodule F2 (Fin ℓ → F2)) [Finite H] + (μ : FiniteDistribution Ω) (eval : Ω → H) (bound : ℝ) + (scalar_bias : ∀ f : Module.Dual F2 H, f ≠ 0 → + |μ.expectation (fun ω => QuarterBalance.sign (f (eval ω)))| ≤ bound) + (Φ : Module.Dual F2 (W ⊗[F2] H)) (hΦ : Φ ≠ 0) : + |(law W μ eval).expectation (fun x => QuarterBalance.sign (Φ x))| ≤ bound := + law_bias_le W μ eval signCharacter bound scalar_bias Φ hΦ + +section Recursive + +universe u +variable {branch : Nat → Nat} {n m : Nat} + +def recursiveLaw (W : Submodule F2 (Fin ℓ → F2)) (repeats : Nat → Nat) + (p : DescendantSpaces.Path branch n m) (A : RecursiveSpaces.Slots branch n → Type u) + [∀ s, Finite (A s)] : + FiniteDistribution (W ⊗[F2] RecursiveSpaces.space F2 branch n A) := + law W (RecursiveSampler.tapeLaw F2 repeats p A) (RecursiveSampler.evaluate F2 repeats p A) + +theorem recursive_law_sign_bias_le (W : Submodule F2 (Fin ℓ → F2)) (repeats : Nat → Nat) + (p : DescendantSpaces.Path branch n m) (A : RecursiveSpaces.Slots branch n → Type u) + [∀ s, Finite (A s)] [Fintype (RecursiveSpaces.space F2 branch n A)] + (bound : ℝ) + (scalar_bias : ∀ f : Module.Dual F2 (RecursiveSpaces.space F2 branch n A), f ≠ 0 → + |(RecursiveSampler.law F2 repeats p A).expectation + (fun h => QuarterBalance.sign (f h))| ≤ bound) + (Φ : Module.Dual F2 (W ⊗[F2] RecursiveSpaces.space F2 branch n A)) (hΦ : Φ ≠ 0) : + |(recursiveLaw W repeats p A).expectation (fun x => QuarterBalance.sign (Φ x))| ≤ bound := by + apply law_sign_bias_le W (RecursiveSampler.tapeLaw F2 repeats p A) + (RecursiveSampler.evaluate F2 repeats p A) bound ?_ Φ hΦ + intro f hf + simpa only [RecursiveSampler.law, FiniteDistribution.expectation_pushforward] using + scalar_bias f hf + +end Recursive + + +variable {E : Type*} [Fintype E] + +def exposedLaw (W : Submodule F2 (Fin ℓ → F2)) + (μ : FiniteDistribution Ω) (ν : FiniteDistribution E) : + FiniteDistribution (HiddenTape W Ω × (VisibleTape W Ω × E)) := + (hiddenTapeLaw W μ).product ((visibleTapeLaw W μ).product ν) + +theorem hidden_condition_exterior (W : Submodule F2 (Fin ℓ → F2)) + (μ : FiniteDistribution Ω) (ν : FiniteDistribution E) + (event : VisibleTape W Ω × E → Bool) + (positive : 0 < (exposedLaw W μ ν).probability (fun x => event x.2)) : + ((exposedLaw W μ ν).condition (fun x => event x.2) positive).pushforward Prod.fst = + hiddenTapeLaw W μ := + CleanConditioning.source_condition_of_constant (hiddenTapeLaw W μ) + (fun _ => (visibleTapeLaw W μ).product ν) (fun x => event x.2) + (((visibleTapeLaw W μ).product ν).probability event) (fun _ => rfl) positive + +theorem law_condition_exterior (W : Submodule F2 (Fin ℓ → F2)) [Finite H] + (μ : FiniteDistribution Ω) (ν : FiniteDistribution E) (eval : Ω → H) + (event : VisibleTape W Ω × E → Bool) + (positive : 0 < (exposedLaw W μ ν).probability (fun x => event x.2)) : + ((exposedLaw W μ ν).condition (fun x => event x.2) positive).pushforward + (fun x => hiddenSum W eval x.1) = law W μ eval := by + rw [← FiniteDistribution.pushforward_comp + ((exposedLaw W μ ν).condition (fun x => event x.2) positive) Prod.fst (hiddenSum W eval), + hidden_condition_exterior] + rfl + +end + +end PerfectCompleteness.HiddenBucketBias + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/HiddenChildMixture.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/HiddenChildMixture.lean new file mode 100644 index 0000000000000000000000000000000000000000..fa4b45d146c3a9c5ee0c5e0780c8e470b2b92d11 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/HiddenChildMixture.lean @@ -0,0 +1,118 @@ +import OAI.Computability.PerfectCompleteness.Foundations.FiniteProduct +import OAI.Computability.PerfectCompleteness.Sampling.DensityVariation + +namespace OAI + +section + +namespace PerfectCompleteness.HiddenChildMixture + +open scoped BigOperators +open UniqueGamesTheorem.Foundations.Games +open PerfectCompleteness SmallBias DensityVariation + +noncomputable section + +variable {I : Type*} [Fintype I] [DecidableEq I] [Nonempty I] + {Ω : I → Type*} [∀ i, Fintype (Ω i)] + +def averageDensity (q : (i : I) → Ω i → ℝ) (x : (i : I) → Ω i) : ℝ := + (∑ i, q i (x i)) / Fintype.card I + +theorem averageDensity_mean (P : (i : I) → FiniteDistribution (Ω i)) + (q : (i : I) → Ω i → ℝ) (mean : ∀ i, (P i).expectation (q i) = 1) : + (FiniteProduct.law P).expectation (averageDensity q) = 1 := by + change (FiniteProduct.law P).expectation + (fun x => (∑ i, q i (x i)) / Fintype.card I) = 1 + rw [expectation_div, expectation_sum] + simp only [FiniteProduct.expectation_eval, mean, Finset.sum_const, Finset.card_univ, + nsmul_eq_mul, mul_one] + exact div_self (by exact_mod_cast Fintype.card_ne_zero (α := I)) + +def mixture (R : I → FiniteDistribution ((i : I) → Ω i)) : + FiniteDistribution ((i : I) → Ω i) where + weight x := (∑ i, (R i).weight x) / Fintype.card I + nonnegative x := div_nonneg (Finset.sum_nonneg fun i _ => (R i).nonnegative x) + (Nat.cast_nonneg _) + normalized := by + simp only [div_eq_mul_inv, ← Finset.sum_mul] + rw [Finset.sum_comm] + simp only [FiniteDistribution.normalized, Finset.sum_const, + Finset.card_univ, nsmul_eq_mul, mul_one] + exact mul_inv_cancel₀ (by exact_mod_cast Fintype.card_ne_zero (α := I)) + +theorem mixture_density (P : (i : I) → FiniteDistribution (Ω i)) + (R : I → FiniteDistribution ((i : I) → Ω i)) + (q : (i : I) → Ω i → ℝ) + (weight : ∀ i x, (R i).weight x = (FiniteProduct.law P).weight x * q i (x i)) + (x : (i : I) → Ω i) : + (mixture R).weight x = (FiniteProduct.law P).weight x * averageDensity q x := by + simp only [mixture, weight, ← Finset.mul_sum, averageDensity, mul_div_assoc] + +omit [Nonempty I] in +theorem centered_cross (P : (i : I) → FiniteDistribution (Ω i)) + (q : (i : I) → Ω i → ℝ) (mean : ∀ i, (P i).expectation (q i) = 1) + (i j : I) (different : i ≠ j) : + (FiniteProduct.law P).expectation (fun x => (q i (x i) - 1) * (q j (x j) - 1)) = 0 := by + rw [FiniteProduct.expectation_eval_mul P i j different (fun a => q i a - 1) + (fun a => q j a - 1)] + simp only [expectation_sub, expectation_const, mean, sub_self, mul_zero] + +omit [Nonempty I] in +theorem centered_sum_second_moment (P : (i : I) → FiniteDistribution (Ω i)) + (q : (i : I) → Ω i → ℝ) (mean : ∀ i, (P i).expectation (q i) = 1) : + (FiniteProduct.law P).expectation (fun x => (∑ i, (q i (x i) - 1)) ^ 2) = + ∑ i, (P i).expectation (fun a => (q i a - 1) ^ 2) := by + simp only [pow_two, Finset.sum_mul, Finset.mul_sum, expectation_sum] + apply Finset.sum_congr rfl + intro i _ + rw [Finset.sum_eq_single i] + · exact FiniteProduct.expectation_eval P i (fun a => (q i a - 1) * (q i a - 1)) + · intro j _ different + exact centered_cross P q mean j i different + · simp + +omit [DecidableEq I] [∀ i, Fintype (Ω i)] in +theorem average_centered (q : (i : I) → Ω i → ℝ) (x : (i : I) → Ω i) : + averageDensity q x - 1 = (∑ i, (q i (x i) - 1)) / Fintype.card I := by + have hn : (Fintype.card I : ℝ) ≠ 0 := by exact_mod_cast Fintype.card_ne_zero (α := I) + simp only [averageDensity, Finset.sum_sub_distrib, Finset.sum_const, + Finset.card_univ, nsmul_eq_mul, mul_one] + field_simp + +theorem average_second_moment (P : (i : I) → FiniteDistribution (Ω i)) + (q : (i : I) → Ω i → ℝ) (mean : ∀ i, (P i).expectation (q i) = 1) : + (FiniteProduct.law P).expectation (fun x => (averageDensity q x - 1) ^ 2) = + (∑ i, (P i).expectation (fun a => (q i a - 1) ^ 2)) / (Fintype.card I : ℝ) ^ 2 := by + simp only [average_centered, div_pow, expectation_div, centered_sum_second_moment P q mean] + +theorem average_second_moment_le (P : (i : I) → FiniteDistribution (Ω i)) + (q : (i : I) → Ω i → ℝ) (mean : ∀ i, (P i).expectation (q i) = 1) + (v : ℝ) (bound : ∀ i, (P i).expectation (fun a => (q i a - 1) ^ 2) ≤ v) : + (FiniteProduct.law P).expectation (fun x => (averageDensity q x - 1) ^ 2) ≤ + v / Fintype.card I := by + rw [average_second_moment P q mean] + have hn : (Fintype.card I : ℝ) ≠ 0 := by exact_mod_cast Fintype.card_ne_zero (α := I) + calc + _ ≤ (∑ _i : I, v) / (Fintype.card I : ℝ) ^ 2 := + div_le_div_of_nonneg_right (Finset.sum_le_sum fun i _ => bound i) (sq_nonneg _) + _ = _ := by simp only [Finset.sum_const, Finset.card_univ, nsmul_eq_mul]; field_simp + +theorem observed_mixture_variation {Γ : Type*} [Fintype Γ] + (P : (i : I) → FiniteDistribution (Ω i)) + (R : I → FiniteDistribution ((i : I) → Ω i)) (q : (i : I) → Ω i → ℝ) + (weight : ∀ i x, (R i).weight x = (FiniteProduct.law P).weight x * q i (x i)) + (mean : ∀ i, (P i).expectation (q i) = 1) + (v : ℝ) (bound : ∀ i, (P i).expectation (fun a => (q i a - 1) ^ 2) ≤ v) + (observe : ((i : I) → Ω i) → Γ) : + ((mixture R).pushforward observe).totalVariation + ((FiniteProduct.law P).pushforward observe) ≤ Real.sqrt (v / Fintype.card I) / 2 := + observed_variation_le_sqrt (FiniteProduct.law P) (mixture R) (averageDensity q) + (mixture_density P R q weight) _ (average_second_moment_le P q mean v bound) observe + +end +end PerfectCompleteness.HiddenChildMixture + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/HierarchicalAdviceFromBuckets.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/HierarchicalAdviceFromBuckets.lean new file mode 100644 index 0000000000000000000000000000000000000000..3751a86351904121b1ba19eff2414677eef260d8 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/HierarchicalAdviceFromBuckets.lean @@ -0,0 +1,142 @@ +import OAI.Computability.PerfectCompleteness.Decoding.HierarchicalUsefulCollision +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalAdviceExperimentLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.HierarchicalAdviceFromBuckets + +noncomputable section + +open scoped Classical +open TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Fourier.MatrixLevelBridge +open UniqueGamesTheorem.Appendix.RankLevelFilter + +attribute [local instance] linearMapFintype + +variable {branch rows : Nat → Nat} {n t : Nat} {Ω P : Type*} + [Fintype Ω] [Fintype P] + (S : HierarchicalAdviceExperiment.Experiment branch rows n t Ω) + +local instance backgroundFintype : Fintype (HierarchicalAdviceExperiment.Background S) := + Fintype.ofFinite _ + +local instance rowSpaceFintype : Fintype (NodeEmbedding.RowSpace S.slots S.upper) := + Fintype.ofFinite _ + +local instance inputFintype : + (b : HierarchicalAdviceExperiment.Background S) → Fintype (HierarchicalAdviceExperiment.Input S b) := + HierarchicalAdviceExperiment.inputFintype S + +local instance inputFiniteDimensional : + (b : HierarchicalAdviceExperiment.Background S) → + FiniteDimensional F2 (HierarchicalAdviceExperiment.Input S b) := + HierarchicalAdviceExperiment.inputFiniteDimensional S + +def backgroundLaw (externalLaw : FiniteDistribution P) + (background : P → HierarchicalAdviceExperiment.Background S) : + FiniteDistribution (HierarchicalAdviceExperiment.Background S) := + externalLaw.pushforward background + +def pairedLaw (externalLaw : FiniteDistribution P) + (background : P → HierarchicalAdviceExperiment.Background S) + (scalarLaw : P → FiniteDistribution (NodeEmbedding.RowSpace S.slots S.upper)) + (hrows : 0 < rows (Nodes.height S.upper)) := + HierarchicalUsefulCollision.pairLaw S.slots S.upper externalLaw background scalarLaw hrows + +def usefulProbability (κ : ℝ) (externalLaw : FiniteDistribution P) + (background : P → HierarchicalAdviceExperiment.Background S) + (scalarLaw : P → FiniteDistribution (NodeEmbedding.RowSpace S.slots S.upper)) + (hrows : 0 < rows (Nodes.height S.upper)) : ℝ := + (HierarchicalUsefulCollision.law S.slots S.upper externalLaw scalarLaw hrows).probability + (HierarchicalUsefulCollision.usefulEvent S.slots S.upper S.lowerLevel S.original S.arrays + (HierarchicalAdviceExperiment.lowerEvent S) κ S.strategy background) + +def adviceFactor (r : Nat) (η : ℝ) : ℝ := + (η ^ 2 / 4) / ((2 : ℝ) ^ (r * rows (Nodes.height S.upper))) ^ 2 + +variable (κ : ℝ) (externalLaw : FiniteDistribution P) + (background : P → HierarchicalAdviceExperiment.Background S) + (scalarLaw : P → FiniteDistribution (NodeEmbedding.RowSpace S.slots S.upper)) + (hrows : 0 < rows (Nodes.height S.upper)) + +theorem mean_agreement_ge (c : ℝ) (hc : 0 ≤ c) + (hmass : c / 2 ≤ usefulProbability S κ externalLaw background scalarLaw hrows) + (hpaired : (pairedLaw S externalLaw background scalarLaw hrows).totalVariation + (HierarchicalAgreementMean.referenceLaw S.slots S.upper + (backgroundLaw S externalLaw background) hrows) ≤ c ^ 2 / 16) : + c ^ 2 / 16 ≤ (backgroundLaw S externalLaw background).expectation + (fun b => PartialTableInverse.nonzeroAgreement (HierarchicalAdviceExperiment.table S κ b)) := by + have hcollision := HierarchicalUsefulCollision.collision_probability_ge_eighth + S.slots S.upper S.lowerLevel S.original S.arrays + (HierarchicalAdviceExperiment.lowerEvent S) κ S.strategy externalLaw background scalarLaw + hrows c hc hmass + have hmean := HierarchicalAgreementMean.mean_nonzeroAgreement_ge_sixteenth + S.slots S.upper S.lowerLevel S.original S.arrays + (HierarchicalAdviceExperiment.lowerEvent S) κ S.strategy + (backgroundLaw S externalLaw background) hrows + (pairedLaw S externalLaw background scalarLaw hrows) c hcollision hpaired + change 2 * (c ^ 2 / 32) ≤ + (backgroundLaw S externalLaw background).expectation + (fun b => PartialTableInverse.nonzeroAgreement (HierarchicalAdviceExperiment.table S κ b)) at hmean + linarith + +theorem prediction_difference (hκ : 0 ≤ κ) + (c : ℝ) (hc : 0 ≤ c) + (hmass : c / 2 ≤ usefulProbability S κ externalLaw background scalarLaw hrows) + (hpaired : (pairedLaw S externalLaw background scalarLaw hrows).totalVariation + (HierarchicalAgreementMean.referenceLaw S.slots S.upper + (backgroundLaw S externalLaw background) hrows) ≤ c ^ 2 / 16) + (r : Nat) (ρ η v : ℝ) (hη : 0 < η) (hηbound : 2 * η ≤ c ^ 2 / 16) + (hρ : 0 < ρ) (hρ1 : ρ < 1) + (hconstants : levelCutoffConstant r ρ + node (r + 1) < η / 2) + (hv : 0 ≤ v) (hsmall : v ≤ ρ * adviceFactor S r η / 16) + (hcoarse : ((HierarchicalAdviceExperiment.originalLaw S r).pushforward + (HierarchicalAdviceExperiment.observe S r)).totalVariation + ((HierarchicalAdviceExperiment.referenceLaw S (backgroundLaw S externalLaw background) r).pushforward (HierarchicalAdviceExperiment.referenceObserve S r)) ≤ v) : + κ * ρ * adviceFactor S r η / 4 ≤ + (HierarchicalAdviceExperiment.originalLaw S r).probability + (HierarchicalAdviceExperiment.prediction S κ r ρ) - + (κ * ρ / 4) * (HierarchicalAdviceExperiment.originalLaw S r).probability + (fun x => HierarchicalAdviceExperiment.J S κ r ρ + (HierarchicalAdviceExperiment.observe S r x)) := by + exact HierarchicalAdviceExperiment.prediction_difference S κ hκ + (backgroundLaw S externalLaw background) hrows r ρ η v hη hρ hρ1 hconstants + (hηbound.trans (mean_agreement_ge S κ externalLaw background scalarLaw hrows + c hc hmass hpaired)) hv hsmall hcoarse + +theorem good_record_mass_ge {R : Type*} [Fintype R] + (hκ : 0 ≤ κ) (c : ℝ) (hc : 0 ≤ c) + (hmass : c / 2 ≤ usefulProbability S κ externalLaw background scalarLaw hrows) + (hpaired : (pairedLaw S externalLaw background scalarLaw hrows).totalVariation + (HierarchicalAgreementMean.referenceLaw S.slots S.upper + (backgroundLaw S externalLaw background) hrows) ≤ c ^ 2 / 16) + (r : Nat) (ρ η v : ℝ) (hη : 0 < η) (hηbound : 2 * η ≤ c ^ 2 / 16) + (hρ : 0 < ρ) (hρ1 : ρ < 1) + (hconstants : levelCutoffConstant r ρ + node (r + 1) < η / 2) + (hv : 0 ≤ v) (hsmall : v ≤ ρ * adviceFactor S r η / 16) + (hcoarse : ((HierarchicalAdviceExperiment.originalLaw S r).pushforward + (HierarchicalAdviceExperiment.observe S r)).totalVariation + ((HierarchicalAdviceExperiment.referenceLaw S (backgroundLaw S externalLaw background) r).pushforward (HierarchicalAdviceExperiment.referenceObserve S r)) ≤ v) + (record : Ω × HierarchicalAdviceExperiment.Advice S r → R) : + κ * ρ * adviceFactor S r η / 4 ≤ + (HierarchicalAdviceExperiment.originalLaw S r).probability + (fun x => HierarchicalAdviceExperiment.J S κ r ρ + (HierarchicalAdviceExperiment.observe S r x) && + PositiveFiberMass.goodRecord (HierarchicalAdviceExperiment.originalLaw S r) record + (fun y => HierarchicalAdviceExperiment.J S κ r ρ + (HierarchicalAdviceExperiment.observe S r y)) + (HierarchicalAdviceExperiment.prediction S κ r ρ) (κ * ρ / 4) (record x)) := + (prediction_difference S κ externalLaw background scalarLaw hrows hκ c hc hmass hpaired + r ρ η v hη hηbound hρ hρ1 hconstants hv hsmall hcoarse).trans + (HierarchicalAdviceExperiment.prediction_difference_le_good_mass S κ hκ r ρ hρ.le record) + +end +end PerfectCompleteness.HierarchicalAdviceFromBuckets + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/HierarchicalBucketFamily.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/HierarchicalBucketFamily.lean new file mode 100644 index 0000000000000000000000000000000000000000..1d0a7950b9a30a67707acf6e7bf9c9a29df8f92d --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/HierarchicalBucketFamily.lean @@ -0,0 +1,161 @@ +import OAI.Computability.PerfectCompleteness.Construction.HierarchicalAdviceFromBuckets +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalAdviceExperimentLemmas +import OAI.Computability.PerfectCompleteness.Sampling.CandidateCoupling + +namespace OAI + +section + +namespace PerfectCompleteness.HierarchicalBucketFamily + +noncomputable section + +open scoped Classical +open TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype + +variable {branch rows : Nat → Nat} {n t : Nat} {O : Type*} [Fintype O] + {Ω : O → Type*} [∀ o, Fintype (Ω o)] + (S : (o : O) → HierarchicalAdviceExperiment.Experiment branch rows n t (Ω o)) + +local instance backgroundFiberFintype (o : O) : + Fintype (HierarchicalAdviceExperiment.Background (S o)) := + HierarchicalAdviceExperiment.backgroundFintype (S o) + +local instance rowSpaceFintype (o : O) : + Fintype (NodeEmbedding.RowSpace (S o).slots (S o).upper) := Fintype.ofFinite _ + +local instance inputFintype (b : HierarchicalAdviceFamily.Background S) : + Fintype (HierarchicalAdviceFamily.Input S b) := + HierarchicalAdviceFamily.inputFintype S b + +local instance inputFiniteDimensional (b : HierarchicalAdviceFamily.Background S) : + FiniteDimensional F2 (HierarchicalAdviceFamily.Input S b) := + HierarchicalAdviceFamily.inputFiniteDimensional S b + +local instance valueFintype (b : HierarchicalAdviceFamily.Background S) : + Fintype (HierarchicalAdviceFamily.Value S b) := + HierarchicalAdviceFamily.valueFintype S b + +abbrev PairRecord := + (o : O) × HierarchicalAgreementMean.PairRecord (rows := rows) (S o).slots (S o).upper + +def collision (κ : ℝ) (z : PairRecord S) : Bool := + HierarchicalAgreementMean.collision (S z.1).slots (S z.1).upper (S z.1).lowerLevel + (S z.1).original (S z.1).arrays (HierarchicalAdviceExperiment.lowerEvent (S z.1)) + κ (S z.1).strategy z.2 + +def referencePairLaw (outer : FiniteDistribution O) + (backgrounds : (o : O) → FiniteDistribution (HierarchicalAdviceExperiment.Background (S o))) + (hrows : ∀ o, 0 < rows (Nodes.height (S o).upper)) : + FiniteDistribution (PairRecord S) := + CompletionSoundness.sigmaLaw outer (fun o => + HierarchicalAgreementMean.referenceLaw (S o).slots (S o).upper (backgrounds o) (hrows o)) + +theorem reference_collision_eq_mean (κ : ℝ) (outer : FiniteDistribution O) + (backgrounds : (o : O) → FiniteDistribution (HierarchicalAdviceExperiment.Background (S o))) + (hrows : ∀ o, 0 < rows (Nodes.height (S o).upper)) : + (referencePairLaw S outer backgrounds hrows).probability (collision S κ) = + (HierarchicalAdviceFamily.backgroundLaw S outer backgrounds).expectation + (fun b => PartialTableInverse.nonzeroAgreement (HierarchicalAdviceFamily.table S κ b)) := by + rw [referencePairLaw, CompletionSoundness.sigmaLaw_probability, + HierarchicalAdviceFamily.backgroundLaw, CandidateCoupling.expectation_sigmaLaw] + apply FiniteDistribution.expectation_congr + intro o + exact HierarchicalAgreementMean.reference_collision_eq_mean + (S o).slots (S o).upper (S o).lowerLevel (S o).original (S o).arrays + (HierarchicalAdviceExperiment.lowerEvent (S o)) κ (S o).strategy (backgrounds o) (hrows o) + +variable {P : O → Type*} [∀ o, Fintype (P o)] + +def actualBackgrounds (externalLaw : (o : O) → FiniteDistribution (P o)) + (background : (o : O) → P o → HierarchicalAdviceExperiment.Background (S o)) + (o : O) : FiniteDistribution (HierarchicalAdviceExperiment.Background (S o)) := + HierarchicalAdviceFromBuckets.backgroundLaw (S o) (externalLaw o) (background o) + +def actualPairLaw (outer : FiniteDistribution O) + (externalLaw : (o : O) → FiniteDistribution (P o)) + (background : (o : O) → P o → HierarchicalAdviceExperiment.Background (S o)) + (scalarLaw : (o : O) → P o → + FiniteDistribution (NodeEmbedding.RowSpace (S o).slots (S o).upper)) + (hrows : ∀ o, 0 < rows (Nodes.height (S o).upper)) : + FiniteDistribution (PairRecord S) := + CompletionSoundness.sigmaLaw outer (fun o => + HierarchicalAdviceFromBuckets.pairedLaw (S o) (externalLaw o) (background o) (scalarLaw o) (hrows o)) + +def usefulMass (κ : ℝ) (outer : FiniteDistribution O) + (externalLaw : (o : O) → FiniteDistribution (P o)) + (background : (o : O) → P o → HierarchicalAdviceExperiment.Background (S o)) + (scalarLaw : (o : O) → P o → + FiniteDistribution (NodeEmbedding.RowSpace (S o).slots (S o).upper)) + (hrows : ∀ o, 0 < rows (Nodes.height (S o).upper)) : ℝ := + outer.expectation (fun o => HierarchicalAdviceFromBuckets.usefulProbability (S o) κ + (externalLaw o) (background o) (scalarLaw o) (hrows o)) + +variable (κ : ℝ) (outer : FiniteDistribution O) + (externalLaw : (o : O) → FiniteDistribution (P o)) + (background : (o : O) → P o → HierarchicalAdviceExperiment.Background (S o)) + (scalarLaw : (o : O) → P o → + FiniteDistribution (NodeEmbedding.RowSpace (S o).slots (S o).upper)) + (hrows : ∀ o, 0 < rows (Nodes.height (S o).upper)) + +theorem collision_probability_lower_bound : + usefulMass S κ outer externalLaw background scalarLaw hrows ^ 2 / 2 ≤ + (actualPairLaw S outer externalLaw background scalarLaw hrows).probability (collision S κ) := by + rw [usefulMass, actualPairLaw, CompletionSoundness.sigmaLaw_probability] + apply CollisionAveraging.average_square_bound outer + intro o + exact HierarchicalUsefulCollision.collision_probability_lower_bound + (S o).slots (S o).upper (S o).lowerLevel (S o).original (S o).arrays + (HierarchicalAdviceExperiment.lowerEvent (S o)) κ (S o).strategy + (externalLaw o) (background o) (scalarLaw o) (hrows o) + +theorem collision_probability_ge_eighth (c : ℝ) (hc : 0 ≤ c) + (hmass : c / 2 ≤ usefulMass S κ outer externalLaw background scalarLaw hrows) : + c ^ 2 / 8 ≤ + (actualPairLaw S outer externalLaw background scalarLaw hrows).probability (collision S κ) := by + rw [actualPairLaw, CompletionSoundness.sigmaLaw_probability] + refine CollisionAveraging.eighth_square_bound outer + (fun o => HierarchicalAdviceFromBuckets.usefulProbability (S o) κ + (externalLaw o) (background o) (scalarLaw o) (hrows o)) _ ?_ c hc hmass + intro o + exact HierarchicalUsefulCollision.collision_probability_lower_bound + (S o).slots (S o).upper (S o).lowerLevel (S o).original (S o).arrays + (HierarchicalAdviceExperiment.lowerEvent (S o)) κ (S o).strategy + (externalLaw o) (background o) (scalarLaw o) (hrows o) + +theorem mean_agreement_ge + (backgrounds : (o : O) → FiniteDistribution (HierarchicalAdviceExperiment.Background (S o))) + (c : ℝ) (hc : 0 ≤ c) + (hmass : c / 2 ≤ usefulMass S κ outer externalLaw background scalarLaw hrows) + (hpaired : (actualPairLaw S outer externalLaw background scalarLaw hrows).totalVariation + (referencePairLaw S outer backgrounds hrows) ≤ c ^ 2 / 16) : + c ^ 2 / 16 ≤ (HierarchicalAdviceFamily.backgroundLaw S outer backgrounds).expectation + (fun b => PartialTableInverse.nonzeroAgreement (HierarchicalAdviceFamily.table S κ b)) := by + have hcollision := collision_probability_ge_eighth S κ outer externalLaw background scalarLaw + hrows c hc hmass + have htransfer := FiniteDistribution.probability_le_add_totalVariation + (actualPairLaw S outer externalLaw background scalarLaw hrows) + (referencePairLaw S outer backgrounds hrows) (collision S κ) + rw [reference_collision_eq_mean] at htransfer + linarith + +theorem mean_agreement_ge_actual_background (c : ℝ) (hc : 0 ≤ c) + (hmass : c / 2 ≤ usefulMass S κ outer externalLaw background scalarLaw hrows) + (hpaired : (actualPairLaw S outer externalLaw background scalarLaw hrows).totalVariation + (referencePairLaw S outer (actualBackgrounds S externalLaw background) hrows) ≤ c ^ 2 / 16) : + c ^ 2 / 16 ≤ + (HierarchicalAdviceFamily.backgroundLaw S outer (actualBackgrounds S externalLaw background)).expectation + (fun b => PartialTableInverse.nonzeroAgreement (HierarchicalAdviceFamily.table S κ b)) := + mean_agreement_ge S κ outer externalLaw background scalarLaw hrows + (actualBackgrounds S externalLaw background) c hc hmass hpaired + +end +end PerfectCompleteness.HierarchicalBucketFamily + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/LocalCompletionFamily.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/LocalCompletionFamily.lean new file mode 100644 index 0000000000000000000000000000000000000000..58beffbe924dd38780730bd73c81fd39ccd1331f --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/LocalCompletionFamily.lean @@ -0,0 +1,174 @@ +import OAI.Computability.PerfectCompleteness.Reduction.CanonicalGameLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.LocalCompletionFamily + +open scoped Classical +open CompletionProbability + +noncomputable section + +abbrev Input (q : Nat) := (Fin (2 * q) → Bool) × (Fin (2 * q) → Fin q) + +abbrev Result (q : Nat) := Fin (2 * q) × (Fin (2 * q) → Fin (2 * q) → Fin q) + +abbrev Legal {q : Nat} (input : Input q) := {a : Fin (2 * q) // input.1 a = true} + +def legalEmbedding {q : Nat} (input : Input q) : Legal input ↪ Fin (2 * q) := + ⟨Subtype.val, Subtype.val_injective⟩ + +def legalProjection {q : Nat} (input : Input q) (a : Legal input) : Fin q := input.2 a.val + +def Admissible {q : Nat} (input : Input q) : Prop := + ∀ b, Fintype.card {a : Legal input // input.2 a.val = b} ≤ 2 + +def activeCount {q : Nat} (result : Result q) : Nat := result.1.val + 1 + +theorem activeCount_positive {q : Nat} (result : Result q) : 0 < activeCount result := + Nat.succ_pos _ + +theorem activeCount_le {q : Nat} (result : Result q) : activeCount result ≤ 2 * q := + Nat.succ_le_of_lt result.1.isLt + +def table {q : Nat} (result : Result q) (seed : Fin (activeCount result)) : + Fin (2 * q) → Fin q := + result.2 ⟨seed.val, lt_of_lt_of_le seed.isLt (activeCount_le result)⟩ + +structure Correct {q : Nat} (input : Input q) (result : Result q) : Prop where + agrees : ∀ seed a, input.1 a = true → table result seed a = input.2 a + exact_two : ∀ seed b, Fintype.card {a : Fin (2 * q) // table result seed a = b} = 2 + illegal_probability : ∀ a, input.1 a ≠ true → ∀ b, + uniformProbability (fun seed : Fin (activeCount result) => table result seed a = b) ≤ + 2 / (2 * q - Fintype.card (Legal input) : Nat) + +def packSampler {q n : Nat} (hn : 0 < n) (hbound : n ≤ 2 * q) + (sampler : Fin n → Fin (2 * q) → Fin q) : Result q := + (⟨n - 1, by omega⟩, + fun slot => if h : slot.val < n then sampler ⟨slot.val, h⟩ else sampler ⟨0, hn⟩) + +@[simp] theorem activeCount_packSampler {q n : Nat} (hn : 0 < n) (hbound : n ≤ 2 * q) + (sampler : Fin n → Fin (2 * q) → Fin q) : + activeCount (packSampler hn hbound sampler) = n := by + change n - 1 + 1 = n + omega + +def packedSeedEquiv {q n : Nat} (hn : 0 < n) (hbound : n ≤ 2 * q) + (sampler : Fin n → Fin (2 * q) → Fin q) : + Fin (activeCount (packSampler hn hbound sampler)) ≃ Fin n where + toFun seed := ⟨seed.val, by simpa only [activeCount_packSampler] using seed.isLt⟩ + invFun seed := ⟨seed.val, by simpa only [activeCount_packSampler] using seed.isLt⟩ + left_inv seed := Fin.ext rfl + right_inv seed := Fin.ext rfl + +theorem table_packSampler {q n : Nat} (hn : 0 < n) (hbound : n ≤ 2 * q) + (sampler : Fin n → Fin (2 * q) → Fin q) + (seed : Fin (activeCount (packSampler hn hbound sampler))) : + table (packSampler hn hbound sampler) seed = + sampler (packedSeedEquiv hn hbound sampler seed) := by + have hs : seed.val < n := (packedSeedEquiv hn hbound sampler seed).isLt + change (if h : seed.val < n then sampler ⟨seed.val, h⟩ else sampler ⟨0, hn⟩) = + sampler ⟨seed.val, hs⟩ + rw [dite_eq_left hs] + +private theorem uniformProbability_equiv {Ω Γ : Type*} [Fintype Ω] [Fintype Γ] + (equiv : Ω ≃ Γ) (event : Γ → Prop) : + uniformProbability (fun seed => event (equiv seed)) = uniformProbability event := by + let restricted : {seed : Ω // event (equiv seed)} ≃ {seed : Γ // event seed} := + equiv.subtypeEquiv (fun _ => Iff.rfl) + unfold uniformProbability + rw [Fintype.card_congr restricted, Fintype.card_congr equiv] + +private theorem uniformProbability_packSampler {q n : Nat} + (hn : 0 < n) (hbound : n ≤ 2 * q) + (sampler : Fin n → Fin (2 * q) → Fin q) (a : Fin (2 * q)) (b : Fin q) : + uniformProbability (fun seed : Fin (activeCount (packSampler hn hbound sampler)) => + table (packSampler hn hbound sampler) seed a = b) = + uniformProbability (fun seed : Fin n => sampler seed a = b) := by + have hevent : + (fun seed : Fin (activeCount (packSampler hn hbound sampler)) => + table (packSampler hn hbound sampler) seed a = b) = + (fun seed : Fin (activeCount (packSampler hn hbound sampler)) => + sampler (packedSeedEquiv hn hbound sampler seed) a = b) := by + funext seed + exact congrArg (fun f : Fin (2 * q) → Fin q => f a = b) + (table_packSampler hn hbound sampler seed) + exact (congrArg + (uniformProbability (Ω := Fin (activeCount (packSampler hn hbound sampler)))) + hevent).trans + (uniformProbability_equiv + (Ω := Fin (activeCount (packSampler hn hbound sampler))) (Γ := Fin n) + (packedSeedEquiv hn hbound sampler) (fun seed : Fin n => sampler seed a = b)) + +private theorem correct_packSampler {q n : Nat} (input : Input q) + (hn : 0 < n) (hbound : n ≤ 2 * q) + (sampler : Fin n → Fin (2 * q) → Fin q) + (hext : ∀ seed l, sampler seed (legalEmbedding input l) = legalProjection input l) + (hexact : ∀ seed b, Fintype.card {a : Fin (2 * q) // sampler seed a = b} = 2) + (hprob : ∀ (a : Illegal (legalEmbedding input)) (b : Fin q), + uniformProbability (fun seed : Fin n => sampler seed a.val = b) ≤ + 2 / (2 * q - Fintype.card (Legal input) : Nat)) : + Correct input (packSampler hn hbound sampler) := by + constructor + · intro seed a ha + rw [table_packSampler] + exact hext (packedSeedEquiv hn hbound sampler seed) ⟨a, ha⟩ + · intro seed b + rw [table_packSampler] + have hb := hexact (packedSeedEquiv hn hbound sampler seed) b + simp only [← Nat.card_eq_fintype_card] at hb ⊢ + exact hb + · intro a ha b + rw [uniformProbability_packSampler] + have hillegal : a ∉ Set.range (legalEmbedding input) := by + rintro ⟨l, hl⟩ + have hval : l.val = a := hl + exact ha (hval ▸ l.property) + exact hprob ⟨a, hillegal⟩ b + +theorem exists_correct {q : Nat} (hq : 0 < q) (input : Input q) + (hadmissible : Admissible input) : ∃ result : Result q, Correct input result := by + obtain ⟨n, hn, hsize, sampler, hext, hexact, hprob⟩ := + exists_completion_sampler_bounded (legalEmbedding input) (legalProjection input) + (by + intro b + rw [Fintype.card_eq_nat_card] + change Nat.card {l : Legal input // input.2 l.val = b} ≤ 2 + have hb := hadmissible b + rw [Fintype.card_eq_nat_card] at hb + exact hb) + (by simp) + have hfull : 0 < 2 * q := Nat.mul_pos (by decide) hq + have hbound : n ≤ 2 * q := by + have hsize' : n ≤ max 1 (2 * q - Fintype.card (Legal input)) := by + simpa only [Fintype.card_fin] using hsize + exact hsize'.trans (max_le (Nat.succ_le_of_lt hfull) (Nat.sub_le _ _)) + refine ⟨packSampler hn hbound sampler, + correct_packSampler input hn hbound sampler hext ?_ ?_⟩ + · intro seed b + have hb := hexact seed b + simp only [← Nat.card_eq_fintype_card] at hb ⊢ + exact hb + · intro a b + simpa only [Fintype.card_fin] using (hprob a b).2 + +def fallback {q : Nat} (hq : 0 < q) : Result q := + (⟨0, Nat.mul_pos (by decide) hq⟩, fun _ _ => ⟨0, hq⟩) + +def lookup {q : Nat} (hq : 0 < q) (input : Input q) : Result q := + if h : Admissible input then Classical.choose (exists_correct hq input h) else fallback hq + +theorem lookup_correct {q : Nat} (hq : 0 < q) (input : Input q) + (hadmissible : Admissible input) : Correct input (lookup hq input) := by + unfold lookup + rw [dite_eq_left hadmissible] + exact Classical.choose_spec (exists_correct hq input hadmissible) + +end +end PerfectCompleteness.LocalCompletionFamily + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/LocalCompletionOutput.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/LocalCompletionOutput.lean new file mode 100644 index 0000000000000000000000000000000000000000..1f4423ca6530bcf1b76ba460b98e80e81c89631f --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/LocalCompletionOutput.lean @@ -0,0 +1,122 @@ +import OAI.Computability.PerfectCompleteness.Construction.FlexibleLocalCompletionLemmas +import OAI.Computability.PerfectCompleteness.Machines.EncodingLemmas +import OAI.Computability.PerfectCompleteness.Machines.LocalCompletionMachineLemmas +import OAI.Computability.PerfectCompleteness.Reduction.CanonicalGameLemmas +import OAI.Computability.PerfectCompleteness.Reduction.CompletionOutputLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.LocalCompletionOutput + +open scoped BigOperators Classical +open Turing +open UniqueGamesTheorem.Foundations.Games +open CompletionSoundness WeightRounding + +noncomputable section + +variable {m l r q : Nat} {L : Fin l → Type*} {R : Fin r → Type*} + [∀ x, Fintype (L x)] + (G : LegalProjectionGame (Fin m) (Fin l) (Fin r) L R) + (legalL : ∀ x, L x ↪ Fin (2 * q)) (legalR : ∀ y, R y ↪ Fin q) + (defaultL : ∀ x, L x) (hq : 0 < q) + (hsmall : ∀ e b, Fintype.card {a : L (G.left e) // G.projection e a = b} ≤ 2) + +def construct (w : PositiveWeights m) (δ : ℚ) (hδ : 0 < δ) : Instance q := + CompletionRounding.output w + (LocalCompletionGame.family G legalL legalR defaultL hq hsmall) δ hδ + +def local_machine_output (e : Fin m) : + TM2OutputsInTime (LocalCompletionMachine.computation hq).tm + (LocalCompletionMachine.inputBits (LocalCompletionGame.input G legalL legalR defaultL e)) + (some (LocalCompletionMachine.resultBits + (LocalCompletionGame.result G legalL legalR defaultL hq e))) 1 := by + have h := (LocalCompletionMachine.computation hq).outputsFun + (LocalCompletionGame.input G legalL legalR defaultL e) + change TM2OutputsInTime (LocalCompletionMachine.computation hq).tm + ((LocalCompletionMachine.inputBits + (LocalCompletionGame.input G legalL legalR defaultL e)).map id) + (some ((LocalCompletionMachine.resultBits + (LocalCompletionGame.result G legalL legalR defaultL hq e)).map id)) + ((1 : Polynomial Nat).eval _) at h + rw [Polynomial.eval_one] at h + exact Eq.mp (congrArg₂ + (fun (i o : List Bool) => TM2OutputsInTime (LocalCompletionMachine.computation hq).tm + i (some o) 1) + (List.map_id (LocalCompletionMachine.inputBits + (LocalCompletionGame.input G legalL legalR defaultL e))) + (List.map_id (LocalCompletionMachine.resultBits + (LocalCompletionGame.result G legalL legalR defaultL hq e)))) h + +theorem total_active_seeds_le : + (∑ e, (LocalCompletionGame.family G legalL legalR defaultL hq hsmall).size e) ≤ + m * (2 * q) := by + calc + _ ≤ ∑ _e : Fin m, 2 * q := by + apply Finset.sum_le_sum + intro e _ + exact LocalCompletionGame.family_size_le G legalL legalR defaultL hq hsmall e + _ = m * (2 * q) := by simp + +theorem edge_count (w : PositiveWeights m) (δ : ℚ) (hδ : 0 < δ) : + (construct G legalL legalR defaultL hq hsmall w δ hδ).edges.length ≤ + ⌈(3 : ℚ) / δ⌉₊ * m * (2 * q) := by + exact (CompletionRounding.output_edge_count_le w + (LocalCompletionGame.family G legalL legalR defaultL hq hsmall) δ hδ).trans + (by + have h := Nat.mul_le_mul_left (⌈(3 : ℚ) / δ⌉₊) + (total_active_seeds_le G legalL legalR defaultL hq hsmall) + simpa only [Nat.mul_assoc] using h) + +theorem bit_count (w : PositiveWeights m) (δ : ℚ) (hδ : 0 < δ) : + let M := ⌈(3 : ℚ) / δ⌉₊ * m * (2 * q) + (Encoding.gameBits (construct G legalL legalR defaultL hq hsmall w δ hδ)).length ≤ + l + r + q + M + 4 + M * (l + r + 2 * q * q + 2 * q + 2) := by + exact Encoding.gameBits_length_le_of_edge_count _ _ + (edge_count G legalL legalR defaultL hq hsmall w δ hδ) + +section Values +variable [∀ y, Fintype (R y)] [∀ x, Nonempty (L x)] [∀ y, Nonempty (R y)] + +theorem value_le (w : PositiveWeights m) + (hweights : ∀ e, G.occurrences.weight e = (w.weight e : ℝ)) + (δ : ℚ) (hδ : 0 < δ) : + (construct G legalL legalR defaultL hq hsmall w δ hδ).value ≤ + G.value + G.occurrences.expectation + (fun e => 2 / (2 * q - Fintype.card (L (G.left e)) : Nat)) + (δ : ℝ) / 3 := + CompletionRounding.output_value_le w + (LocalCompletionGame.family G legalL legalR defaultL hq hsmall) hweights δ hδ hq + +theorem value_le_delta (w : PositiveWeights m) + (hweights : ∀ e, G.occurrences.weight e = (w.weight e : ℝ)) + (δ : ℚ) (hδ : 0 < δ) (hleft : ∀ x, Fintype.card (L x) ≤ q) + (hbudget : (6 : ℝ) ≤ (δ : ℝ) * q) (hsound : G.value ≤ (δ : ℝ) / 3) : + (construct G legalL legalR defaultL hq hsmall w δ hδ).value ≤ (δ : ℝ) := by + have hδreal : (0 : ℝ) < (δ : ℝ) := by exact_mod_cast hδ + have hres : ∀ e, 2 / (2 * q - Fintype.card (L (G.left e)) : Nat) ≤ (δ : ℝ) / 3 := + fun e => CompletionParameters.residual_le_third hq (hleft (G.left e)) hδreal hbudget + have h := CompletionRounding.output_value_le_of_residual_bound w + (LocalCompletionGame.family G legalL legalR defaultL hq hsmall) + hweights δ hδ hq ((δ : ℝ) / 3) hres + change (construct G legalL legalR defaultL hq hsmall w δ hδ).value ≤ + G.value + (δ : ℝ) / 3 + (δ : ℝ) / 3 at h + linarith + +theorem perfectlyComplete (w : PositiveWeights m) + (hweights : ∀ e, G.occurrences.weight e = (w.weight e : ℝ)) + (δ : ℚ) (hδ : 0 < δ) (hcomplete : G.value = 1) : + PerfectlyComplete (construct G legalL legalR defaultL hq hsmall w δ hδ) := by + apply ((construct G legalL legalR defaultL hq hsmall w δ hδ).perfectlyComplete_iff_value_eq_one hq).2 + exact CompletionRounding.output_value_eq_one w + (LocalCompletionGame.family G legalL legalR defaultL hq hsmall) + hweights δ hδ hq hcomplete + +end Values +end +end PerfectCompleteness.LocalCompletionOutput + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/LocalCompletionSerializedOutput.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/LocalCompletionSerializedOutput.lean new file mode 100644 index 0000000000000000000000000000000000000000..c17d363de2ccd3392a1073dac64778cb5ce36eb2 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/LocalCompletionSerializedOutput.lean @@ -0,0 +1,88 @@ +import OAI.Computability.PerfectCompleteness.Construction.LocalCompletionOutput +import OAI.Computability.PerfectCompleteness.Machines.LocalCompletionMachineLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.LocalCompletionSerializedOutput + +open Turing +open UniqueGamesTheorem.Foundations.Complexity +open CompletionSoundness CompletionSoundness.LegalProjectionGame +open LocalCompletionFamily +open scoped Classical + +noncomputable section + +variable {m l r q : Nat} {L : Fin l → Type*} {R : Fin r → Type*} + [∀ x, Fintype (L x)] + (G : LegalProjectionGame (Fin m) (Fin l) (Fin r) L R) + (legalL : ∀ x, L x ↪ Fin (2 * q)) (legalR : ∀ y, R y ↪ Fin q) + (defaultL : ∀ x, L x) (hq : 0 < q) + (hsmall : ∀ e b, Fintype.card {a : L (G.left e) // G.projection e a = b} ≤ 2) + +private theorem projection_eq_of_images {a b : ProjectionTable q} + (h : a.images = b.images) : a = b := by + cases a + cases b + cases h + rfl + +def entry (e : Fin m) + (seed : Fin ((LocalCompletionGame.family G legalL legalR defaultL hq hsmall).size e)) : + Edge l r q := + CompletionRounding.entries (LocalCompletionGame.family G legalL legalR defaultL hq hsmall) + (CompletionRounding.enumeration + (LocalCompletionGame.family G legalL legalR defaultL hq hsmall) ⟨e, seed⟩) + +@[simp] theorem entry_left (e : Fin m) + (seed : Fin ((LocalCompletionGame.family G legalL legalR defaultL hq hsmall).size e)) : + (entry G legalL legalR defaultL hq hsmall e seed).left = G.left e := by + simp only [entry, CompletionRounding.entries, Equiv.symm_apply_apply] + +@[simp] theorem entry_right (e : Fin m) + (seed : Fin ((LocalCompletionGame.family G legalL legalR defaultL hq hsmall).size e)) : + (entry G legalL legalR defaultL hq hsmall e seed).right = G.right e := by + simp only [entry, CompletionRounding.entries, Equiv.symm_apply_apply] + +theorem entry_projection (e : Fin m) + (seed : Fin ((LocalCompletionGame.family G legalL legalR defaultL hq hsmall).size e)) : + (entry G legalL legalR defaultL hq hsmall e seed).projection = + LocalCompletionSerialization.projection + (LocalCompletionGame.result_correct G legalL legalR defaultL hq hsmall e) seed := by + apply projection_eq_of_images + let F := LocalCompletionGame.family G legalL legalR defaultL hq hsmall + have h := congrArg (fun es : CompletionRounding.CompletedOccurrence F => + Vector.ofFn (F.map es.1 es.2)) + ((CompletionRounding.enumeration F).symm_apply_apply ⟨e, seed⟩) + exact h + +def local_machine_output (e : Fin m) : + TM2OutputsInTime (LocalCompletionSerialization.computation hq).tm + (LocalCompletionMachine.inputBits (LocalCompletionGame.input G legalL legalR defaultL e)) + (some (LocalCompletionSerialization.payloadBits + (LocalCompletionGame.result G legalL legalR defaultL hq e))) 1 := + LocalCompletionSerialization.machine_output hq _ + +theorem local_machine_output_decodes (e : Fin m) : + decodeWords (LocalCompletionSerialization.payloadBits + (LocalCompletionGame.result G legalL legalR defaultL hq e)) >>= + LocalCompletionSerialization.parsePayload q = + some ((List.finRange + ((LocalCompletionGame.family G legalL legalR defaultL hq hsmall).size e)).map + (fun seed => (entry G legalL legalR defaultL hq hsmall e seed).projection)) := by + rw [LocalCompletionSerialization.decode_payloadBits, Option.bind_eq_bind, Option.bind_some] + rw [LocalCompletionSerialization.parse_payload + (LocalCompletionGame.result_correct G legalL legalR defaultL hq hsmall e)] + congr 1 + apply List.map_congr_left + intro seed _ + exact (entry_projection G legalL legalR defaultL hq hsmall e seed).symm + +end +end PerfectCompleteness.LocalCompletionSerializedOutput + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/LocalReconstruction.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/LocalReconstruction.lean new file mode 100644 index 0000000000000000000000000000000000000000..9db8657361026f8c514ab2f200a85cd3a6f63296 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/LocalReconstruction.lean @@ -0,0 +1,126 @@ +import OAI.Computability.PerfectCompleteness.Construction.FactoredFunctionsLemmas +import OAI.Computability.PerfectCompleteness.Sampling.UniformChildSum + +namespace OAI + + +namespace PerfectCompleteness.LocalReconstruction + +open scoped BigOperators +open PointwiseSpaces RecursiveSpaces FactoredFunctions + +noncomputable section + +variable {𝕜 : Type*} [Field 𝕜] {branch : Nat → Nat} {n : Nat} + +abbrev Retained (A : Slots branch (n + 1) → Type*) + (clean : Fin (branch n) → Prop) := + (j : {j : Fin (branch n) // ¬ clean j}) → Assignment (childFamily A j.1) + +def retain (A : Slots branch (n + 1) → Type*) (clean : Fin (branch n) → Prop) : + Assignment A → Retained A clean := + fun x j => childRestriction A j.1 x + +abbrev Summands (A : Slots branch (n + 1) → Type*) + (clean : Fin (branch n) → Prop) := + (j : {j : Fin (branch n) // ¬ clean j}) → + squareSpace (space 𝕜 branch n (childFamily A j.1)) + +def retainedCut (A : Slots branch (n + 1) → Type*) + (clean : Fin (branch n) → Prop) [DecidablePred clean] + (u : Summands (𝕜 := 𝕜) A clean) : Retained A clean → 𝕜 := + fun x => ∑ j, (u j).val (x j) + +def cutCall (A : Slots branch (n + 1) → Type*) + (clean : Fin (branch n) → Prop) [DecidablePred clean] + (u : Summands (𝕜 := 𝕜) A clean) : space 𝕜 branch (n + 1) A := + ⟨∑ j, pullback 𝕜 (childRestriction A j.1) (u j).val, by + apply (space 𝕜 branch (n + 1) A).sum_mem + intro j _ + exact child_square_le_space A j.1 (Submodule.mem_map_of_mem (u j).property)⟩ + +theorem cutCall_factors (A : Slots branch (n + 1) → Type*) + (clean : Fin (branch n) → Prop) [DecidablePred clean] + (u : Summands (𝕜 := 𝕜) A clean) : + (cutCall A clean u).val = retainedCut A clean u ∘ retain A clean := by + funext x + simp only [cutCall, retainedCut, retain, Function.comp_apply, + Finset.sum_apply, PointwiseSpaces.pullback_apply] + +theorem cutCall_ignores_clean (A : Slots branch (n + 1) → Type*) + (clean : Fin (branch n) → Prop) [DecidablePred clean] + (u : Summands (𝕜 := 𝕜) A clean) : + (cutCall A clean u).val ∈ factoringSpace (retain A clean) := by + rw [mem_factoringSpace_iff_exists_factor] + exact ⟨retainedCut A clean u, fun x => congrFun (cutCall_factors A clean u) x⟩ + +theorem actual_sum_eq_cutCall (A : Slots branch (n + 1) → Type*) + (clean : Fin (branch n) → Prop) [DecidablePred clean] + (u : (j : Fin (branch n)) → squareSpace (space 𝕜 branch n (childFamily A j))) + (zero : ∀ j, clean j → u j = 0) : + UniformChildSum.recursiveSum A u = cutCall A clean (fun j => u j.1) := by + apply Subtype.ext + change (∑ j : Fin (branch n), pullback 𝕜 (childRestriction A j) (u j).val) = _ + rw [← Fintype.sum_subtype_add_sum_subtype clean + (fun j => pullback 𝕜 (childRestriction A j) (u j).val)] + have hz : (∑ j : {j : Fin (branch n) // clean j}, + pullback 𝕜 (childRestriction A j.1) (u j.1).val) = 0 := by + apply Finset.sum_eq_zero + intro j _ + rw [zero j.1 j.2] + exact map_zero _ + rw [hz, zero_add] + rfl + +theorem actual_sum_ignores_clean (A : Slots branch (n + 1) → Type*) + (clean : Fin (branch n) → Prop) [DecidablePred clean] + (u : (j : Fin (branch n)) → squareSpace (space 𝕜 branch n (childFamily A j))) + (zero : ∀ j, clean j → u j = 0) : + (UniformChildSum.recursiveSum A u).val ∈ factoringSpace (retain A clean) := by + rw [actual_sum_eq_cutCall A clean u zero] + exact cutCall_ignores_clean A clean _ + +inductive Recipe (𝕜 Atom : Type*) where + | constant : 𝕜 → Recipe 𝕜 Atom + | atom : Atom → Recipe 𝕜 Atom + | add : Recipe 𝕜 Atom → Recipe 𝕜 Atom → Recipe 𝕜 Atom + | mul : Recipe 𝕜 Atom → Recipe 𝕜 Atom → Recipe 𝕜 Atom + +namespace Recipe + +variable {Atom X Z : Type*} + +def evaluate (atoms : Atom → X → 𝕜) : Recipe 𝕜 Atom → X → 𝕜 + | .constant c => fun _ => c + | .atom a => atoms a + | .add f g => evaluate atoms f + evaluate atoms g + | .mul f g => evaluate atoms f * evaluate atoms g + +theorem evaluate_factors (other : X → Z) (atoms : Atom → X → 𝕜) + (known : ∀ a, atoms a ∈ factoringSpace other) (r : Recipe 𝕜 Atom) : + r.evaluate atoms ∈ factoringSpace other := by + induction r with + | constant c => exact const_mem_factoringSpace other c + | atom a => exact known a + | add f g hf hg => exact (factoringSpace other).add_mem hf hg + | mul f g hf hg => exact mul_mem_factoringSpace other hf hg + +theorem evaluate_pullback (other : X → Z) (atoms : Atom → Z → 𝕜) + (r : Recipe 𝕜 Atom) : + r.evaluate (fun a => atoms a ∘ other) = r.evaluate atoms ∘ other := by + induction r with + | constant c => rfl + | atom a => rfl + | add f g hf hg => + simp only [evaluate, hf, hg] + rfl + | mul f g hf hg => + simp only [evaluate, hf, hg] + rfl + +end Recipe + +end +end PerfectCompleteness.LocalReconstruction + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/MixedSourceLocalOddLists.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/MixedSourceLocalOddLists.lean new file mode 100644 index 0000000000000000000000000000000000000000..4bf5cd40f54357130450928453844bba53fc5f7e --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/MixedSourceLocalOddLists.lean @@ -0,0 +1,269 @@ +import OAI.Computability.PerfectCompleteness.Construction.SourceLocalOddLists + +namespace OAI + +section + +namespace PerfectCompleteness.MixedSourceLocalOddLists + +open scoped BigOperators Classical +open PointwiseSpaces TreeSourceSpaces SourceAnswerEquiv +open UniqueGamesTheorem.Foundations.Games + +abbrev F2 := ZMod 2 + +noncomputable section + +section Composition + +variable {A B C : Type*} [Fintype A] [Fintype B] [Fintype C] + [DecidableEq A] [DecidableEq B] [DecidableEq C] + +private theorem parity_comp (π : A → B) (ρ : B → C) (L : Finset A) : + OddLists.parityPushforward ρ (OddLists.parityPushforward π L) = + OddLists.parityPushforward (ρ ∘ π) L := by + let f : A → F2 := fun a => if a ∈ L then 1 else 0 + have hf : OddLists.support f = L := by + ext a + by_cases ha : a ∈ L <;> simp [OddLists.mem_support, f, ha] + rw [← hf, OddLists.parityPushforward_support, OddLists.parityPushforward_support, + OddLists.parityPushforward_support] + congr 1 + funext c + calc + (∑ b, if ρ b = c then ∑ a, if π a = b then f a else 0 else 0) = + ∑ b, ∑ a, if ρ b = c then (if π a = b then f a else 0) else 0 := by + apply Finset.sum_congr rfl + intro b _ + by_cases hb : ρ b = c <;> simp only [hb, ite_true, ite_false, Finset.sum_const_zero] + _ = ∑ a, ∑ b, if ρ b = c then (if π a = b then f a else 0) else 0 := + Finset.sum_comm + _ = ∑ a, if (ρ ∘ π) a = c then f a else 0 := by + apply Finset.sum_congr rfl + intro a _ + rw [Finset.sum_eq_single (π a)] + · simp only [Function.comp_apply, ite_true] + · intro b _ hb + simp only [ite_eq_right (Ne.symm hb), ite_self] + · intro h + exact (h (Finset.mem_univ _)).elim + +private theorem oddList_map_comp {s : Nat} (π : A → B) (ρ : B → C) + (L : OddLists.OddList s A) : + OddLists.OddList.map ρ (OddLists.OddList.map π L) = + OddLists.OddList.map (ρ ∘ π) L := by + apply Subtype.ext + exact parity_comp π ρ L.val + +end Composition + +private theorem map_eq_of_map_eq {A B : Type*} {s : Nat} + {f₁ f₂ : Fintype B} {d₁ d₂ : DecidableEq B} + (π : A → B) (L : OddLists.OddList s A) (R : OddLists.OddList s B) + (accepted : @OddLists.OddList.map A B s f₁ d₁ π L = R) : + @OddLists.OddList.map A B s f₂ d₂ π L = R := by + have hf : f₁ = f₂ := Subsingleton.elim _ _ + cases hf + have hd : d₁ = d₂ := Subsingleton.elim _ _ + cases hd + exact accepted + +variable {branch : Nat → Nat} {h t v m s : Nat} + (clauses : Fin m → SourceClause.NormalizedClause v) + +private theorem encoded_accepts {B : Type*} [Fintype B] [DecidableEq B] + (e : SourceOddLists.Occurrences m t) + (π : LeftDomain clauses (SourceOddLists.left e) → B) + (ρ : B → SourceOddLists.RightLabels t) + (hcomm : ρ ∘ π = (actualProjection clauses e : + LeftDomain clauses (SourceOddLists.left e) → SourceOddLists.RightLabels t)) + (L : OddLists.OddList s (LeftDomain clauses (SourceOddLists.left e))) + (R : OddLists.OddList s B) (hnative : OddLists.OddList.map π L = R) : + OddLists.OddList.map (SourceOddLists.projection clauses e) + (encodeOddList clauses (SourceOddLists.left e) L) = OddLists.OddList.map ρ R := by + let actual : LeftDomain clauses (SourceOddLists.left e) → SourceOddLists.RightLabels t := + actualProjection clauses e + have henc0 := encodeOddList_projection clauses e L + have henc : OddLists.OddList.map actual L = + OddLists.OddList.map (SourceOddLists.projection clauses e) + (encodeOddList clauses (SourceOddLists.left e) L) := + map_eq_of_map_eq (B := SourceOddLists.RightLabels t) actual L _ henc0.symm + calc + _ = OddLists.OddList.map actual L := henc.symm + _ = OddLists.OddList.map (ρ ∘ π) L := + congrArg (fun f : LeftDomain clauses (SourceOddLists.left e) → SourceOddLists.RightLabels t => + OddLists.OddList.map f L) hcomm.symm + _ = OddLists.OddList.map ρ (OddLists.OddList.map π L) := (oddList_map_comp π ρ L).symm + _ = OddLists.OddList.map ρ R := congrArg (OddLists.OddList.map ρ) hnative + +abbrev Endpoints := RecursiveSpaces.Slots branch h → Fin t → SourceKeys.Endpoint v m + +def slotsOf (q : Endpoints (branch := branch) (h := h) (t := t) (v := v) (m := m)) : + RecursiveSpaces.Slots branch h → Fin t → MixedSupport.Slot := + fun leaf k => SourceKeys.slot clauses (q leaf k) + +abbrev RightForms := + (q : Endpoints (branch := branch) (h := h) (t := t) (v := v) (m := m)) → + SourceLocalOddLists.Form (slotsOf clauses q) + +def defaultValue : (q : SourceKeys.Endpoint v m) → (SourceKeys.slot clauses q).Domain + | .clause c => (clauseAnswerEquiv (clauses c).signs).symm 0 + | .variable _ => false + +def readBit : (q : SourceKeys.Endpoint v m) → (SourceKeys.slot clauses q).Domain → Bool + | .clause _, _ => false + | .variable _, b => b + +def leafToBits (q : Fin t → SourceKeys.Endpoint v m) + (a : MixedSupport.Assignment (fun k => SourceKeys.slot clauses (q k))) : + SourceOddLists.RightLabels t := + fun k => readBit clauses (q k) (a k) + +def rightResponse (positive : 0 < s) (forms : RightForms (branch := branch) (h := h) (t := t) clauses) + (q : Endpoints (branch := branch) (h := h) (t := t) (v := v) (m := m)) + (leaf : RecursiveSpaces.Slots branch h) : OddLists.OddList s (SourceOddLists.RightLabels t) := + OddLists.OddList.map (leafToBits clauses (q leaf)) + (SourceLocalOddLists.extract positive (slotsOf clauses q) (forms q) leaf + (fun k => defaultValue clauses (q leaf k))) + +def target : Bool → SourceClause.Occurrence m → SourceKeys.Endpoint v m + | false, e => .clause e.1 + | true, e => .variable ((clauses e.1).variable e.2) + +def step : (projected : Bool) → (e : SourceClause.Occurrence m) → + SourceKeys.Step clauses (.clause e.1) (target clauses projected e) + | false, e => .keep (.clause e.1) + | true, e => .select e.1 e.2 + +def rightEndpoints (projected : RecursiveSpaces.Slots branch h → Bool) + (e : SourceLocalOddLists.Occurrences (branch := branch) (h := h) (m := m) (t := t)) : + Endpoints (branch := branch) (h := h) (t := t) (v := v) (m := m) := + fun leaf k => target clauses (projected leaf) (e leaf k) + +def treeProjection (projected : RecursiveSpaces.Slots branch h → Bool) + (e : SourceLocalOddLists.Occurrences (branch := branch) (h := h) (m := m) (t := t)) : + ∀ leaf k, MixedSupport.Projection + (leftTreeSlots clauses (fun j => SourceOddLists.left (e j)) leaf k) + (slotsOf clauses (rightEndpoints clauses projected e) leaf k) := + fun leaf k => (step clauses (projected leaf) (e leaf k)).projection + +theorem clean_leaf_projection (projected : RecursiveSpaces.Slots branch h → Bool) + (e : SourceLocalOddLists.Occurrences (branch := branch) (h := h) (m := m) (t := t)) + (leaf : RecursiveSpaces.Slots branch h) (hp : projected leaf = true) : + leafToBits clauses (rightEndpoints clauses projected e leaf) ∘ + MixedSupport.projectionMap (treeProjection clauses projected e leaf) = + actualProjection clauses (e leaf) := by + funext a k + change readBit clauses (target clauses (projected leaf) (e leaf k)) + ((step clauses (projected leaf) (e leaf k)).projection.map (a k)) = + (a k).val.at (e leaf k).2 + rw [hp] + rfl + +section Clean + +open SourceLocalOddLists (CleanLeaves fill) + +variable (clean : RecursiveSpaces.Slots branch h → Prop) + (projected : RecursiveSpaces.Slots branch h → Bool) + (background : SourceLocalOddLists.Occurrences (branch := branch) (h := h) (m := m) (t := t)) + +def strategy (positive : 0 < s) + (leftForms : SourceLocalOddLists.LeftForms (branch := branch) (h := h) (t := t) clauses) (rightForms : RightForms (branch := branch) (h := h) (t := t) clauses) : + Strategy (CleanLeaves clean → Fin t → Fin m) (CleanLeaves clean → Fin t → Fin v) + (CleanLeaves clean → OddLists.OddList s (SourceOddLists.LeftLabels t)) + (CleanLeaves clean → OddLists.OddList s (SourceOddLists.RightLabels t)) := + (fun q leaf => SourceLocalOddLists.leftResponse clauses positive leftForms + (fill clean (fun j => SourceOddLists.left (background j)) q) leaf.val, + fun q leaf => rightResponse clauses positive rightForms + (fill clean (rightEndpoints clauses projected background) + (fun i k => SourceKeys.Endpoint.variable (q i k))) leaf.val) + +theorem fill_rightEndpoints (hclean : ∀ leaf, clean leaf → projected leaf = true) + (e : CleanLeaves clean → SourceOddLists.Occurrences m t) : + fill clean (rightEndpoints clauses projected background) + (fun i k => SourceKeys.Endpoint.variable (SourceOddLists.right clauses (e i) k)) = + rightEndpoints clauses projected (fill clean background e) := by + funext leaf k + by_cases hc : clean leaf + · simp only [SourceLocalOddLists.fill, dite_eq_left hc, rightEndpoints, hclean leaf hc, target] + rfl + · simp only [SourceLocalOddLists.fill, dite_eq_right hc, rightEndpoints] + +theorem strategy_wins [NeZero m] (positive : 0 < s) + (leftForms : SourceLocalOddLists.LeftForms (branch := branch) (h := h) (t := t) clauses) (rightForms : RightForms (branch := branch) (h := h) (t := t) clauses) + (hclean : ∀ leaf, clean leaf → projected leaf = true) + (e : CleanLeaves clean → SourceOddLists.Occurrences m t) + (z : Module.Dual F2 (squareSpace + (H (leftTreeSlots clauses (fun j => SourceOddLists.left (fill clean background e j)))))) + (hform : leftForms (fun j => SourceOddLists.left (fill clean background e j)) = + OddListExtraction.multiplicationForm + (H (leftTreeSlots clauses (fun j => SourceOddLists.left (fill clean background e j)))) z) + (hone : + (1 : Domain (leftTreeSlots clauses (fun j => SourceOddLists.left (fill clean background e j))) → F2) ∈ + squareSpace (H (leftTreeSlots clauses (fun j => SourceOddLists.left (fill clean background e j))))) + (hnorm : z ⟨1, hone⟩ = 1) + (hrank : OddListExtraction.formRank + (H (leftTreeSlots clauses (fun j => SourceOddLists.left (fill clean background e j)))) + (leftForms (fun j => SourceOddLists.left (fill clean background e j))) ≤ s) + (hagree : ∀ f g, + rightForms (rightEndpoints clauses projected (fill clean background e)) f g = + OddListExtraction.multiplicationForm + (H (leftTreeSlots clauses (fun j => SourceOddLists.left (fill clean background e j)))) z + (HPullback (treeProjection clauses projected (fill clean background e)) f) + (HPullback (treeProjection clauses projected (fill clean background e)) g)) : + (IndexedRepetition.game (SourceOddLists.game s clauses t) (CleanLeaves clean)).wins + (strategy clauses clean projected background positive leftForms rightForms) e = true := by + simp only [OccurrenceGame.wins, IndexedRepetition.game, SourceOddLists.game, + OddListGame.game, OccurrenceGame.ofProjection, strategy, decide_eq_true_eq] + intro leaf + rw [SourceLocalOddLists.fill_comp clean background e SourceOddLists.left, + fill_rightEndpoints clauses clean projected background hclean e] + let full : SourceLocalOddLists.Occurrences (branch := branch) (h := h) (m := m) (t := t) := + fill clean background e + let qL : SourceLocalOddLists.LeftQuestions (branch := branch) (h := h) (t := t) (m := m) := + fun j => SourceOddLists.left (full j) + let qR : Endpoints (branch := branch) (h := h) (t := t) (v := v) (m := m) := + rightEndpoints clauses projected full + let slotsL : RecursiveSpaces.Slots branch h → Fin t → MixedSupport.Slot := + leftTreeSlots (branch := branch) (n := h) clauses qL + let slotsR : RecursiveSpaces.Slots branch h → Fin t → MixedSupport.Slot := + slotsOf (branch := branch) (h := h) (t := t) clauses qR + let L : OddLists.OddList s (LeftDomain clauses (SourceOddLists.left (full leaf.val))) := + SourceLocalOddLists.extract (branch := branch) (h := h) (t := t) + positive slotsL (leftForms qL) leaf.val + ((leftEquiv clauses (SourceOddLists.left (full leaf.val))).symm (fun _ => 0)) + let R : OddLists.OddList s (LeafDomain slotsR leaf.val) := + SourceLocalOddLists.extract (branch := branch) (h := h) (t := t) + positive slotsR (rightForms qR) leaf.val + (fun k => defaultValue clauses (qR leaf.val k)) + let π : LeftDomain clauses (SourceOddLists.left (full leaf.val)) → LeafDomain slotsR leaf.val := + MixedSupport.projectionMap + (treeProjection (branch := branch) (h := h) (t := t) clauses projected full leaf.val) + let ρ : LeafDomain slotsR leaf.val → SourceOddLists.RightLabels t := + leafToBits clauses (qR leaf.val) + have hraw := SourceLocalOddLists.extract_accepts (branch := branch) (h := h) (t := t) + (slots := slotsL) (projected := slotsR) positive + (treeProjection (branch := branch) (h := h) (t := t) clauses projected full) + leaf.val (leftForms qL) (rightForms qR) z hform hone hnorm hrank hagree + ((leftEquiv clauses (SourceOddLists.left (full leaf.val))).symm (fun _ => 0)) + (fun k => defaultValue clauses (qR leaf.val k)) + have hnative : OddLists.OddList.map π L = R := map_eq_of_map_eq π L R hraw + have hcomm : ρ ∘ π = + (actualProjection clauses (full leaf.val) : + LeftDomain clauses (SourceOddLists.left (full leaf.val)) → SourceOddLists.RightLabels t) := + clean_leaf_projection clauses projected full leaf.val (hclean leaf.val leaf.property) + have haccept := encoded_accepts clauses (full leaf.val) π ρ hcomm L R hnative + rw [← SourceLocalOddLists.fill_clean clean background e leaf] + change OddLists.OddList.map (SourceOddLists.projection clauses (full leaf.val)) + (encodeOddList clauses (SourceOddLists.left (full leaf.val)) L) = OddLists.OddList.map ρ R + exact haccept + +end Clean + +end +end PerfectCompleteness.MixedSourceLocalOddLists + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/NativeLeafAlphabet.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/NativeLeafAlphabet.lean new file mode 100644 index 0000000000000000000000000000000000000000..d051e3bbb335ab409a158e0b656ffc57c91bbff3 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/NativeLeafAlphabet.lean @@ -0,0 +1,56 @@ +import OAI.Computability.PerfectCompleteness.Foundations.SourceOddListsLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.NativeLeafAlphabet + +open SourceClause + +variable {I : Type*} {v m t : Nat} + +def castAssignment {a b : I → MixedSupport.Slot} (h : a = b) : + MixedSupport.Assignment a ≃ MixedSupport.Assignment b := + Equiv.cast (congrArg (fun slots : I → MixedSupport.Slot => + MixedSupport.Assignment slots) h) + +@[simp] theorem castAssignment_rfl (a : I → MixedSupport.Slot) : + castAssignment (rfl : a = a) = Equiv.refl (MixedSupport.Assignment a) := rfl + +def nativeLeftEquiv (clauses : Fin m → NormalizedClause v) + (question : Fin t → Fin m) {a : Fin t → MixedSupport.Slot} + (ha : a = SourceAnswerEquiv.leftSlots clauses question) : + MixedSupport.Assignment a ≃ SourceOddLists.LeftLabels t := + (castAssignment ha).trans (SourceAnswerEquiv.leftEquiv clauses question) + +def nativeRightEquiv (clauses : Fin m → NormalizedClause v) + (question : Fin t → Fin v) {b : Fin t → MixedSupport.Slot} + (hb : b = SourceAnswerEquiv.rightSlots clauses question) : + MixedSupport.Assignment b ≃ SourceOddLists.RightLabels t := + (castAssignment hb).trans (SourceAnswerEquiv.rightEquiv clauses question) + +theorem projection_encode (clauses : Fin m → NormalizedClause v) + (e : SourceOddLists.Occurrences m t) {a b : Fin t → MixedSupport.Slot} + (ha : a = SourceAnswerEquiv.leftSlots clauses (SourceOddLists.left e)) + (hb : b = SourceAnswerEquiv.rightSlots clauses (SourceOddLists.right clauses e)) + (q : ∀ k, MixedSupport.Projection (a k) (b k)) + (hq : ∀ k, HEq (q k) (SourceAnswerEquiv.slotProjection clauses e k)) + (x : MixedSupport.Assignment a) : + nativeRightEquiv clauses (SourceOddLists.right clauses e) hb + (MixedSupport.projectionMap q x) = + SourceOddLists.projection clauses e + (nativeLeftEquiv clauses (SourceOddLists.left e) ha x) := by + subst a + subst b + have hprojection : q = SourceAnswerEquiv.slotProjection clauses e := by + funext k + exact eq_of_heq (hq k) + subst q + exact SourceAnswerEquiv.projection_encode clauses e x + +end PerfectCompleteness.NativeLeafAlphabet + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/NodeEmbedding.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/NodeEmbedding.lean new file mode 100644 index 0000000000000000000000000000000000000000..23522e261f205903bed234d58fdd11e3020da82b --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/NodeEmbedding.lean @@ -0,0 +1,155 @@ +import Mathlib.LinearAlgebra.Dimension.Finrank +import OAI.Computability.PerfectCompleteness.Algebra.EvaluationMatrix +import OAI.Computability.PerfectCompleteness.Algebra.UniformLinearImage +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalArrays + +namespace OAI + + +namespace PerfectCompleteness.NodeEmbedding + +open TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open scoped Classical + +noncomputable section + +variable {branch : Nat → Nat} {n t : Nat} + +abbrev NumberedDomain (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) := + MixedSupport.Assignment (TreeCanonical.numberedSlots slots) + +abbrev NodeH (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (node : Nodes branch n) := H (nodeSlots slots node) + +variable (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (node : Nodes branch n) + +def numberedRestriction : NumberedDomain slots → Domain (nodeSlots slots node) := + restrictNode slots node ∘ (TreeCanonical.assignmentEquiv slots).symm + +theorem numberedRestriction_surjective : Function.Surjective (numberedRestriction slots node) := + (restrictNode_surjective slots node).comp (TreeCanonical.assignmentEquiv slots).symm.surjective + +theorem pullback_injective : + Function.Injective (PointwiseSpaces.pullback F2 (numberedRestriction slots node)) := + PointwiseSpaces.pullback_injective _ (numberedRestriction_surjective slots node) + +def RowSpace : Submodule F2 (NumberedDomain slots → F2) := + (NodeH slots node).map (PointwiseSpaces.pullback F2 (numberedRestriction slots node)) + +def equiv : NodeH slots node ≃ₗ[F2] RowSpace slots node := + Submodule.equivMapOfInjective + (PointwiseSpaces.pullback F2 (numberedRestriction slots node)) + (pullback_injective slots node) (NodeH slots node) + +def embed : NodeH slots node →ₗ[F2] RowSpace slots node := + (equiv slots node).toLinearMap + +@[simp] theorem equiv_apply (f : NodeH slots node) (x : NumberedDomain slots) : + (equiv slots node f).val x = f.val (numberedRestriction slots node x) := rfl + +@[simp] theorem embed_apply (f : NodeH slots node) (x : NumberedDomain slots) : + (embed slots node f).val x = f.val (numberedRestriction slots node x) := rfl + +theorem embed_injective : Function.Injective (embed slots node) := + (equiv slots node).injective + +theorem embed_surjective : Function.Surjective (embed slots node) := + (equiv slots node).surjective + +theorem finrank_eq : + Module.finrank F2 (RowSpace slots node) = Module.finrank F2 (NodeH slots node) := + (equiv slots node).finrank_eq.symm + +theorem card_eq : Nat.card (RowSpace slots node) = Nat.card (NodeH slots node) := + (Nat.card_congr (equiv slots node).toEquiv).symm + +theorem uniform_embed [Fintype (NodeH slots node)] [Fintype (RowSpace slots node)] : + (FiniteDistribution.uniform (NodeH slots node)).pushforward (embed slots node) = + FiniteDistribution.uniform (RowSpace slots node) := + UniformLinearImage.uniform_pushforward_linearMap (embed slots node) + (embed_surjective slots node) + +def rowsEquiv (ℓ : Nat) : + (Fin ℓ → NodeH slots node) ≃ₗ[F2] (Fin ℓ → RowSpace slots node) := + LinearEquiv.piCongrRight (fun _ : Fin ℓ => equiv slots node) + +@[simp] theorem rowsEquiv_apply (ℓ : Nat) (f : Fin ℓ → NodeH slots node) (i : Fin ℓ) : + rowsEquiv slots node ℓ f i = embed slots node (f i) := rfl + +theorem uniform_rowsEquiv (ℓ : Nat) + [Fintype (NodeH slots node)] [Fintype (RowSpace slots node)] : + (FiniteDistribution.uniform (Fin ℓ → NodeH slots node)).pushforward + (rowsEquiv slots node ℓ) = + FiniteDistribution.uniform (Fin ℓ → RowSpace slots node) := + UniformLinearImage.uniform_pushforward_linearMap + (rowsEquiv slots node ℓ).toLinearMap (rowsEquiv slots node ℓ).surjective + +theorem squareSpace_eq : + PointwiseSpaces.squareSpace (RowSpace slots node) = + (PointwiseSpaces.squareSpace (NodeH slots node)).map + (PointwiseSpaces.pullback F2 (numberedRestriction slots node)) := + (PointwiseSpaces.squareSpace_map_pullback + (numberedRestriction slots node) (NodeH slots node)).symm + +theorem embed_mul (f g : NodeH slots node) : + (embed slots node f).val * (embed slots node g).val = + PointwiseSpaces.pullback F2 (numberedRestriction slots node) (f.val * g.val) := rfl + +def RootRowSpace : Submodule F2 (NumberedDomain slots → F2) := + (H slots).map (PointwiseSpaces.pullback F2 (TreeCanonical.assignmentEquiv slots).symm) + +theorem rowSpace_le_root (hbranch : ∀ k < n, 0 < branch k) : + RowSpace slots node ≤ RootRowSpace slots := by + intro f hf + obtain ⟨g, hg, rfl⟩ := Submodule.mem_map.mp hf + have hroot : PointwiseSpaces.pullback F2 (restrictNode slots node) g ∈ H slots := + DescendantSpaces.space_descendant_le (Nodes.path node) (LeafDomain slots) hbranch + (Submodule.mem_map_of_mem hg) + exact Submodule.mem_map.mpr + ⟨PointwiseSpaces.pullback F2 (restrictNode slots node) g, hroot, rfl⟩ + +theorem squareSpace_le_root (hbranch : ∀ k < n, 0 < branch k) + (hproper : Nodes.height node < n) : + PointwiseSpaces.squareSpace (RowSpace slots node) ≤ RootRowSpace slots := by + rw [squareSpace_eq] + intro f hf + obtain ⟨g, hg, rfl⟩ := Submodule.mem_map.mp hf + have hroot : PointwiseSpaces.pullback F2 (restrictNode slots node) g ∈ H slots := + DescendantSpaces.descendant_square_le_space (Nodes.path node) (LeafDomain slots) + hbranch hproper (Submodule.mem_map_of_mem hg) + exact Submodule.mem_map.mpr + ⟨PointwiseSpaces.pullback F2 (restrictNode slots node) g, hroot, rfl⟩ + + +variable {slots} {rows : Nat → Nat} + +def embeddedRows (arrays : Arrays slots rows) (node : Nodes branch n) : + Fin (rows (Nodes.height node)) → RowSpace slots node := + fun i => embed slots node (arrays node i) + +@[simp] theorem embeddedRows_apply (arrays : Arrays slots rows) (node : Nodes branch n) + (i : Fin (rows (Nodes.height node))) (x : NumberedDomain slots) : + (embeddedRows arrays node i).val x = + (TreeCanonical.numberedFunction slots (fullJoint arrays) x).1 node i := rfl + +def matrix (arrays : Arrays slots rows) (node : Nodes branch n) : + Module.Dual F2 (RowSpace slots node) →ₗ[F2] Block rows node := + EvaluationMatrix.ofRows (RowSpace slots node) (embeddedRows arrays node) + +@[simp] theorem matrix_evaluate (arrays : Arrays slots rows) (node : Nodes branch n) + (x : NumberedDomain slots) : + EvaluationMatrix.evaluate (RowSpace slots node) (matrix arrays node) x = + (TreeCanonical.numberedFunction slots (fullJoint arrays) x).1 node := rfl + +theorem evaluation_comp_embed (x : NumberedDomain slots) : + (EvaluationMatrix.evaluation (RowSpace slots node) x).comp (embed slots node) = + EvaluationMatrix.evaluation (NodeH slots node) (numberedRestriction slots node x) := by + ext f + rfl + +end +end PerfectCompleteness.NodeEmbedding + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/OriginalChildBlockProducts.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/OriginalChildBlockProducts.lean new file mode 100644 index 0000000000000000000000000000000000000000..e27fe2fbe7497d817378ac46787d5fa8bcaf661c --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/OriginalChildBlockProducts.lean @@ -0,0 +1,103 @@ +import OAI.Computability.PerfectCompleteness.Foundations.QuarterBalanceLemmas +import OAI.Computability.PerfectCompleteness.Sampling.RationalFiniteLawLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.OriginalChildBlockProducts + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games + +noncomputable section + +universe uC uI uΩ uΓ uΔ + +theorem transpose_law {C : Type uC} {I : Type uI} + [Fintype C] [DecidableEq C] [Fintype I] [DecidableEq I] + {Ω : C → I → Type uΩ} [∀ c i, Fintype (Ω c i)] + (P : (c : C) → (i : I) → FiniteDistribution (Ω c i)) : + (FiniteProduct.law (fun c => FiniteProduct.law (P c))).pushforward + (fun x i c => x c i) = + FiniteProduct.law (fun i => FiniteProduct.law (fun c => P c i)) := by + change (FiniteProduct.law (fun c => FiniteProduct.law (P c))).pushforward + (Equiv.piComm Ω) = _ + rw [← FiniteDistribution.transport_eq_pushforward] + apply FiniteDistribution.eq_of_weight_eq + intro y + change (∏ c, ∏ i, (P c i).weight (y i c)) = + ∏ i, ∏ c, (P c i).weight (y i c) + exact Finset.prod_comm + +def pairEquiv {I : Type uI} (Ω : I → Type uΩ) (Γ : I → Type uΓ) : + ((i : I) → Ω i) × ((i : I) → Γ i) ≃ ((i : I) → Ω i × Γ i) where + toFun z i := (z.1 i, z.2 i) + invFun z := (fun i => (z i).1, fun i => (z i).2) + left_inv _ := rfl + right_inv _ := rfl + +theorem pair_law {I : Type uI} [Fintype I] [DecidableEq I] + {Ω : I → Type uΩ} {Γ : I → Type uΓ} + [∀ i, Fintype (Ω i)] [∀ i, Fintype (Γ i)] + (μ : (i : I) → FiniteDistribution (Ω i)) + (ν : (i : I) → FiniteDistribution (Γ i)) : + ((FiniteProduct.law μ).product (FiniteProduct.law ν)).pushforward + (fun z i => (z.1 i, z.2 i)) = + FiniteProduct.law (fun i => (μ i).product (ν i)) := by + change ((FiniteProduct.law μ).product (FiniteProduct.law ν)).pushforward + (pairEquiv Ω Γ) = _ + rw [← FiniteDistribution.transport_eq_pushforward] + apply FiniteDistribution.eq_of_weight_eq + intro y + change (∏ i, (μ i).weight (y i).1) * (∏ i, (ν i).weight (y i).2) = + ∏ i, (μ i).weight (y i).1 * (ν i).weight (y i).2 + exact (Finset.prod_mul_distrib).symm + +theorem pair_transport_law {I : Type uI} [Fintype I] [DecidableEq I] + {Ω : I → Type uΩ} {Γ : I → Type uΓ} {Δ : I → Type uΔ} + [∀ i, Fintype (Ω i)] [∀ i, Fintype (Γ i)] [∀ i, Fintype (Δ i)] + (e : (i : I) → Ω i × Γ i ≃ Δ i) + (μ : (i : I) → FiniteDistribution (Ω i)) + (ν : (i : I) → FiniteDistribution (Γ i)) : + ((FiniteProduct.law μ).product (FiniteProduct.law ν)).pushforward + (fun z i => e i (z.1 i, z.2 i)) = + FiniteProduct.law (fun i => ((μ i).product (ν i)).transport (e i)) := by + calc + _ = (((FiniteProduct.law μ).product (FiniteProduct.law ν)).pushforward + (fun z i => (z.1 i, z.2 i))).pushforward (fun x i => e i (x i)) := + (FiniteDistribution.pushforward_comp + ((FiniteProduct.law μ).product (FiniteProduct.law ν)) + (fun z i => (z.1 i, z.2 i)) (fun x i => e i (x i))).symm + _ = (FiniteProduct.law (fun i => (μ i).product (ν i))).pushforward + (fun x i => e i (x i)) := + congrArg (fun ρ : FiniteDistribution ((i : I) → Ω i × Γ i) => + ρ.pushforward (fun x i => e i (x i))) (pair_law μ ν) + _ = FiniteProduct.law (fun i => ((μ i).product (ν i)).pushforward (e i)) := + FiniteProduct.pushforward_map (fun i => (μ i).product (ν i)) (fun i => e i) + _ = _ := by + apply congrArg (fun laws : (i : I) → FiniteDistribution (Δ i) => + FiniteProduct.law laws) + funext i + exact (FiniteDistribution.transport_eq_pushforward + ((μ i).product (ν i)) (e i)).symm + +theorem merge_law {I : Type uI} [Fintype I] [DecidableEq I] + {Ω : I → Type uΩ} [∀ i, Fintype (Ω i)] + (P : (i : I) → FiniteDistribution (Ω i)) (chosen : I) : + ((P chosen).product (FiniteProductSplit.otherLaw P chosen)).pushforward + (Equiv.piSplitAt chosen Ω).symm = + FiniteProduct.law P := by + rw [← FiniteProductSplit.split_law P chosen, FiniteDistribution.pushforward_comp] + have hmap : (fun x => (Equiv.piSplitAt chosen Ω).symm + ((Equiv.piSplitAt chosen Ω) x)) = id := by + funext x + exact (Equiv.piSplitAt chosen Ω).symm_apply_apply x + rw [hmap, FiniteDistribution.pushforward_id] + +end +end PerfectCompleteness.OriginalChildBlockProducts + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/OriginalChildBlocks.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/OriginalChildBlocks.lean new file mode 100644 index 0000000000000000000000000000000000000000..8759d771c227705cc8e47d9000db60f7ae490611 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/OriginalChildBlocks.lean @@ -0,0 +1,218 @@ +import OAI.Computability.PerfectCompleteness.Construction.CutChildGrouping +import OAI.Computability.PerfectCompleteness.Construction.OriginalChildScalarAssemblyLemmas +import OAI.Computability.PerfectCompleteness.Construction.OriginalChildScalars +import OAI.Computability.PerfectCompleteness.Foundations.OriginalBelowCut +import OAI.Computability.PerfectCompleteness.Sampling.CutSamplerReplayTransportLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.OriginalChildBlocks + +open PointwiseSpaces RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalChildScalars +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +noncomputable section + +private theorem uniform_product {A B : Type*} [Fintype A] [Fintype B] + [Nonempty A] [Nonempty B] : + (FiniteDistribution.uniform A).product (FiniteDistribution.uniform B) = + FiniteDistribution.uniform (A × B) := by + apply FiniteDistribution.eq_of_weight_eq + intro x + simp only [FiniteDistribution.product, FiniteDistribution.uniform, + Fintype.card_prod, Nat.cast_mul, one_div_mul_one_div] + +variable {branch : Nat → Nat} {n m t : Nat} + +def rawEquiv (calls : Nat) (rows : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) (child : Fin (branch n)) : + ((Fin calls → Square slots child) × Arrays (childSlots slots child) rows) ≃ + ChildBlockCardinality.Raw calls rows (childSlots slots child) := Equiv.refl _ + +def arrayComponent (rows repeats : Nat → Nat) (chosen : Fin (branch n)) + (q : Path branch n m) (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) : + (child : Fin (branch n)) → FiniteDistribution (Arrays (childSlots slots child) rows) := + ChildBlockMixture.component + (fun child => WholeArraySampler.law rows repeats q (childSlots slots child)) chosen + +def specialLaw (calls : Nat) (rows repeats : Nat → Nat) (q : Path branch n m) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) (child : Fin (branch n)) : + FiniteDistribution (ChildBlockCardinality.Raw calls rows (childSlots slots child)) := + @FiniteDistribution.transport + ((Fin calls → Square slots child) × Arrays (childSlots slots child) rows) + (ChildBlockCardinality.Raw calls rows (childSlots slots child)) + (instFintypeProd _ _) (ChildBlockCardinality.rawFintype calls rows (childSlots slots child)) + ((FiniteProduct.law (fun _ : Fin calls => specialSquareLaw repeats q slots child)).product + (WholeArraySampler.law rows repeats q (childSlots slots child))) + (rawEquiv calls rows slots child) + +def componentLaw (calls : Nat) (rows repeats : Nat → Nat) (chosen : Fin (branch n)) + (q : Path branch n m) (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (child : Fin (branch n)) : + FiniteDistribution (ChildBlockCardinality.Raw calls rows (childSlots slots child)) := + @FiniteDistribution.transport + ((Fin calls → Square slots child) × Arrays (childSlots slots child) rows) + (ChildBlockCardinality.Raw calls rows (childSlots slots child)) + (instFintypeProd _ _) (ChildBlockCardinality.rawFintype calls rows (childSlots slots child)) + ((callComponent calls repeats chosen q slots child).product + (arrayComponent rows repeats chosen q slots child)) (rawEquiv calls rows slots child) + +theorem callComponent_uniform (calls : Nat) (repeats : Nat → Nat) + (chosen : Fin (branch n)) (q : Path branch n m) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (child : Fin (branch n)) (hne : child ≠ chosen) : + callComponent calls repeats chosen q slots child = + FiniteDistribution.uniform (Fin calls → Square slots child) := by + have h := squareComponent_other repeats q slots chosen ⟨child, hne⟩ + unfold callComponent + rw [h] + exact UniformLinearImage.law_uniform + +theorem componentLaw_eq (calls : Nat) (rows repeats : Nat → Nat) + (chosen : Fin (branch n)) (q : Path branch n m) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) (child : Fin (branch n)) : + componentLaw calls rows repeats chosen q slots child = + ChildBlockMixture.component (specialLaw calls rows repeats q slots) chosen child := by + by_cases h : child = chosen + · subst child + simp only [componentLaw, callComponent, squareComponent_self, arrayComponent, + ChildBlockMixture.component, dite_eq_left rfl, dite_true, specialLaw] + · have harray : arrayComponent rows repeats chosen q slots child = + FiniteDistribution.uniform (Arrays (childSlots slots child) rows) := + dite_eq_right (Ne.symm h) + rw [componentLaw, callComponent_uniform calls repeats chosen q slots child h, harray] + rw [uniform_product] + have huniform := @UniformConditioning.uniform_transport + ((Fin calls → Square slots child) × Arrays (childSlots slots child) rows) + (ChildBlockCardinality.Raw calls rows (childSlots slots child)) + (instFintypeProd _ _) (ChildBlockCardinality.rawFintype calls rows (childSlots slots child)) + inferInstance inferInstance (rawEquiv calls rows slots child) + have hcomponent : + ChildBlockMixture.component (specialLaw calls rows repeats q slots) chosen child = + FiniteDistribution.uniform + (ChildBlockCardinality.Raw calls rows (childSlots slots child)) := by + simp only [ChildBlockMixture.component, dite_eq_right (Ne.symm h)] + exact huniform.trans hcomponent.symm + +abbrev SourceTape (calls : Nat) (rows repeats : Nat → Nat) (chosen : Fin (branch n)) + (q : Path branch n m) (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) := + (Fin calls → ScalarTape repeats chosen q slots) × + WholeArraySampler.Tape rows repeats (.step chosen q) slots + +def sourceLaw (calls : Nat) (rows repeats : Nat → Nat) (chosen : Fin (branch n)) + (q : Path branch n m) (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) : + FiniteDistribution (SourceTape calls rows repeats chosen q slots) := + (callsLaw calls repeats chosen q slots).product + (WholeArraySampler.tapeLaw rows repeats (.step chosen q) slots) + +def rawMap (calls : Nat) (rows repeats : Nat → Nat) (chosen : Fin (branch n)) + (q : Path branch n m) (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ω : SourceTape calls rows repeats chosen q slots) : + (child : Fin (branch n)) → ChildBlockCardinality.Raw calls rows (childSlots slots child) := + fun child => rawEquiv calls rows slots child + (callContributions calls repeats chosen q slots ω.1 child, + OriginalBelowCut.below rows repeats chosen q slots ω.2 child) + +@[simp] theorem rawMap_call (calls : Nat) (rows repeats : Nat → Nat) + (chosen : Fin (branch n)) (q : Path branch n m) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ω : SourceTape calls rows repeats chosen q slots) (child : Fin (branch n)) (call : Fin calls) : + (rawMap calls rows repeats chosen q slots ω child).1 call = + stepSquareMap repeats chosen q slots (ω.1 call) child := rfl + +@[simp] theorem rawMap_array (calls : Nat) (rows repeats : Nat → Nat) + (chosen : Fin (branch n)) (q : Path branch n m) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ω : SourceTape calls rows repeats chosen q slots) (child : Fin (branch n)) + (node : Nodes branch n) : + (rawMap calls rows repeats chosen q slots ω child).2 node = + WholeArraySampler.evaluate rows repeats (.step chosen q) slots ω.2 (.inr (child, node)) := rfl + +theorem rawMap_product_law (calls : Nat) (rows repeats : Nat → Nat) + (chosen : Fin (branch n)) (q : Path branch n m) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) : + (sourceLaw calls rows repeats chosen q slots).pushforward + (rawMap calls rows repeats chosen q slots) = + FiniteProduct.law (componentLaw calls rows repeats chosen q slots) := by + calc + _ = ((sourceLaw calls rows repeats chosen q slots).pushforward + (fun ω => (callContributions calls repeats chosen q slots ω.1, + OriginalBelowCut.below rows repeats chosen q slots ω.2))).pushforward + (fun z child => rawEquiv calls rows slots child (z.1 child, z.2 child)) := + (FiniteDistribution.pushforward_comp _ _ _).symm + _ = ((FiniteProduct.law (callComponent calls repeats chosen q slots)).product + (FiniteProduct.law (arrayComponent rows repeats chosen q slots))).pushforward + (fun z child => rawEquiv calls rows slots child (z.1 child, z.2 child)) := by + rw [sourceLaw, FiniteDistribution.product_pushforward, + callContributions_law, OriginalBelowCut.below_pushforward, arrayComponent] + _ = _ := by + have hpair := OriginalChildBlockProducts.pair_transport_law + (Ω := fun child : Fin (branch n) => Fin calls → ↥(Square slots child)) + (Γ := fun child => Arrays (childSlots slots child) rows) + (Δ := fun child => ChildBlockCardinality.Raw calls rows (childSlots slots child)) + (rawEquiv calls rows slots) (callComponent calls repeats chosen q slots) + (arrayComponent rows repeats chosen q slots) + apply FiniteDistribution.eq_of_weight_eq + intro x + have hw := congrFun (congrArg FiniteDistribution.weight hpair) x + simpa only [componentLaw, FiniteProduct.law, FiniteDistribution.transport] using hw + +theorem rawMap_law (calls : Nat) (rows repeats : Nat → Nat) + (chosen : Fin (branch n)) (q : Path branch n m) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) : + (sourceLaw calls rows repeats chosen q slots).pushforward + (rawMap calls rows repeats chosen q slots) = + ChildBlockMixture.special (specialLaw calls rows repeats q slots) chosen := by + rw [rawMap_product_law] + apply congrArg (fun laws : (child : Fin (branch n)) → + FiniteDistribution (ChildBlockCardinality.Raw calls rows (childSlots slots child)) => + FiniteProduct.law laws) + funext child + exact componentLaw_eq calls rows repeats chosen q slots child + +def observed (calls : Nat) (rows repeats : Nat → Nat) (chosen : Fin (branch n)) + (q : Path branch n m) (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ω : SourceTape calls rows repeats chosen q slots) : + CutChildGrouping.Assembled (C := Fin calls) slots rows := + (fun call => RecursiveSampler.evaluate F2 repeats (.step chosen q) (LeafDomain slots) (ω.1 call), + OriginalBelowCut.below rows repeats chosen q slots ω.2) + +theorem assemble_rawMap (calls : Nat) (rows repeats : Nat → Nat) + (chosen : Fin (branch n)) (q : Path branch n m) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ω : SourceTape calls rows repeats chosen q slots) : + CutChildGrouping.assemble slots rows (rawMap calls rows repeats chosen q slots ω) = + observed calls rows repeats chosen q slots ω := by + apply Prod.ext + · funext call + exact OriginalChildScalarAssembly.recursiveSum_callContributions + calls repeats chosen q slots ω.1 call + · rfl + +theorem observed_law (calls : Nat) (rows repeats : Nat → Nat) + (chosen : Fin (branch n)) (q : Path branch n m) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) : + (sourceLaw calls rows repeats chosen q slots).pushforward + (observed calls rows repeats chosen q slots) = + (ChildBlockMixture.special (specialLaw calls rows repeats q slots) chosen).pushforward + (CutChildGrouping.assemble slots rows) := by + calc + _ = ((sourceLaw calls rows repeats chosen q slots).pushforward + (rawMap calls rows repeats chosen q slots)).pushforward + (CutChildGrouping.assemble slots rows) := by + rw [FiniteDistribution.pushforward_comp] + congr 1 + funext ω + exact (assemble_rawMap calls rows repeats chosen q slots ω).symm + _ = _ := by rw [rawMap_law] + +end +end PerfectCompleteness.OriginalChildBlocks + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/OriginalChildScalarAssemblyLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/OriginalChildScalarAssemblyLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fe7bc8b699b86e28219d2a9cbdb72a8d9f560af --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/OriginalChildScalarAssemblyLemmas.lean @@ -0,0 +1,509 @@ +import Mathlib.Data.Fintype.BigOperators +import OAI.Computability.PerfectCompleteness.Construction.AscendingBranchingLemmas +import OAI.Computability.PerfectCompleteness.Construction.OriginalChildScalars +import OAI.Computability.PerfectCompleteness.Construction.SourceQuestionOrderLemmas +import OAI.Computability.PerfectCompleteness.Reduction.FixedRows +import OAI.Computability.PerfectCompleteness.Sampling.UniformChildSum +import OAI.Computability.PerfectCompleteness.Sampling.UniformLatent + +namespace OAI + + +namespace PerfectCompleteness.OriginalChildScalarAssembly + +open PointwiseSpaces RecursiveSpaces DescendantSpaces TreeSourceSpaces +open OriginalChildScalars RecursiveSamplerBiasAlgebra +open scoped BigOperators Classical + +noncomputable section + +variable {branch : Nat → Nat} {n m t : Nat} + +@[simp] theorem stepSquareMap_self (repeats : Nat → Nat) (chosen : Fin (branch n)) + (q : Path branch n m) (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ω : ScalarTape repeats chosen q slots) : + stepSquareMap repeats chosen q slots ω chosen = + squareSum repeats slots chosen + (RecursiveSampler.splitEvaluatedTape F2 repeats chosen q (LeafDomain slots) ω).2 := by + exact congrArg Prod.fst + ((Equiv.piSplitAt chosen (fun child => ↥(Square slots child))).apply_symm_apply + (selectedAndOthers repeats chosen q slots ω)) + +@[simp] theorem stepSquareMap_other (repeats : Nat → Nat) (chosen : Fin (branch n)) + (q : Path branch n m) (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ω : ScalarTape repeats chosen q slots) (child : RecursiveSampler.OffPath chosen) : + stepSquareMap repeats chosen q slots ω child.val = ω (.inl child) := by + exact congrArg + (fun z : Square slots chosen × + ((j : RecursiveSampler.OffPath chosen) → Square slots j.val) => z.2 child) + ((Equiv.piSplitAt chosen (fun child => ↥(Square slots child))).apply_symm_apply + (selectedAndOthers repeats chosen q slots ω)) + +theorem recursiveSum_eq_sum (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (values : (child : Fin (branch n)) → Square slots child) : + UniformChildSum.recursiveSum (𝕜 := F2) (LeafDomain slots) values = + ∑ child : Fin (branch n), childSquareLift F2 (LeafDomain slots) child (values child) := by + apply Subtype.ext + change (∑ child : Fin (branch n), + pullback F2 (childRestriction (LeafDomain slots) child) (values child).val) = + (H slots).subtype + (∑ child : Fin (branch n), childSquareLift F2 (LeafDomain slots) child (values child)) + rw [map_sum] + rfl + +theorem childSquareLift_squareSum (repeats : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) (chosen : Fin (branch n)) + (values : RecursiveSampler.CallIndex repeats n → H (childSlots slots chosen)) : + childSquareLift F2 (LeafDomain slots) chosen (squareSum repeats slots chosen values) = + ∑ pair : Fin (repeats (n + 1)), childProduct F2 (LeafDomain slots) chosen + (values (pair, false)) (values (pair, true)) := by + rw [squareSum, map_sum] + rfl + +theorem recursiveSum_stepSquareMap (repeats : Nat → Nat) (chosen : Fin (branch n)) + (q : Path branch n m) (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ω : ScalarTape repeats chosen q slots) : + UniformChildSum.recursiveSum (𝕜 := F2) (LeafDomain slots) + (stepSquareMap repeats chosen q slots ω) = + RecursiveSampler.evaluate F2 repeats (.step chosen q) (LeafDomain slots) ω := by + let ordinary : (child : RecursiveSampler.OffPath chosen) → Square slots child.val := + (RecursiveSampler.splitEvaluatedTape F2 repeats chosen q (LeafDomain slots) ω).1 + let values : RecursiveSampler.CallIndex repeats n → H (childSlots slots chosen) := + (RecursiveSampler.splitEvaluatedTape F2 repeats chosen q (LeafDomain slots) ω).2 + have hself : stepSquareMap repeats chosen q slots ω chosen = + squareSum repeats slots chosen values := + stepSquareMap_self repeats chosen q slots ω + have hother (child : RecursiveSampler.OffPath chosen) : + stepSquareMap repeats chosen q slots ω child.val = ordinary child := + stepSquareMap_other repeats chosen q slots ω child + have heval : RecursiveSampler.evaluate F2 repeats (.step chosen q) (LeafDomain slots) ω = + (∑ child : RecursiveSampler.OffPath chosen, + childSquareLift F2 (LeafDomain slots) child.val (ordinary child)) + + ∑ pair : Fin (repeats (n + 1)), childProduct F2 (LeafDomain slots) chosen + (values (pair, false)) (values (pair, true)) := + (RecursiveSampler.stepCombine_splitEvaluatedTape F2 repeats chosen q (LeafDomain slots) ω).symm.trans + (RecursiveSamplerBiasAlgebra.combine_eq F2 (LeafDomain slots) chosen (repeats (n + 1)) + ordinary (fun pair => values (pair, false)) (fun pair => values (pair, true))) + calc + _ = ∑ child : Fin (branch n), childSquareLift F2 (LeafDomain slots) child + (stepSquareMap repeats chosen q slots ω child) := + recursiveSum_eq_sum slots (stepSquareMap repeats chosen q slots ω) + _ = childSquareLift F2 (LeafDomain slots) chosen (stepSquareMap repeats chosen q slots ω chosen) + + ∑ child : RecursiveSampler.OffPath chosen, childSquareLift F2 (LeafDomain slots) child.val + (stepSquareMap repeats chosen q slots ω child.val) := + Fintype.sum_eq_add_sum_subtype_ne _ chosen + _ = childSquareLift F2 (LeafDomain slots) chosen (squareSum repeats slots chosen values) + + ∑ child : RecursiveSampler.OffPath chosen, + childSquareLift F2 (LeafDomain slots) child.val (ordinary child) := + congrArg₂ (fun a b : H slots => a + b) + (congrArg (childSquareLift F2 (LeafDomain slots) chosen) hself) + (Finset.sum_congr rfl (fun child _ => + congrArg (childSquareLift F2 (LeafDomain slots) child.val) (hother child))) + _ = (∑ pair : Fin (repeats (n + 1)), childProduct F2 (LeafDomain slots) chosen + (values (pair, false)) (values (pair, true))) + + ∑ child : RecursiveSampler.OffPath chosen, + childSquareLift F2 (LeafDomain slots) child.val (ordinary child) := + congrArg (fun z : H slots => z + ∑ child : RecursiveSampler.OffPath chosen, + childSquareLift F2 (LeafDomain slots) child.val (ordinary child)) + (childSquareLift_squareSum repeats slots chosen values) + _ = _ := (add_comm _ _).trans heval.symm + +theorem recursiveSum_callContributions (calls : Nat) (repeats : Nat → Nat) + (chosen : Fin (branch n)) (q : Path branch n m) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ω : Fin calls → ScalarTape repeats chosen q slots) (call : Fin calls) : + UniformChildSum.recursiveSum (𝕜 := F2) (LeafDomain slots) + (fun child => callContributions calls repeats chosen q slots ω child call) = + RecursiveSampler.evaluate F2 repeats (.step chosen q) (LeafDomain slots) (ω call) := + recursiveSum_stepSquareMap repeats chosen q slots (ω call) + +theorem recursiveSum_callContributions_tuple (calls : Nat) (repeats : Nat → Nat) + (chosen : Fin (branch n)) (q : Path branch n m) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ω : Fin calls → ScalarTape repeats chosen q slots) : + (fun call => UniformChildSum.recursiveSum (𝕜 := F2) (LeafDomain slots) + (fun child => callContributions calls repeats chosen q slots ω child call)) = + (fun call => RecursiveSampler.evaluate F2 repeats (.step chosen q) + (LeafDomain slots) (ω call)) := by + funext call + exact recursiveSum_callContributions calls repeats chosen q slots ω call + +end +end PerfectCompleteness.OriginalChildScalarAssembly + + +namespace PerfectCompleteness.TreeShapeBounds + +open TreeCardinality HierarchicalArrays +open scoped BigOperators + +def leafCount (branch : Nat → Nat) : Nat → Nat + | 0 => 1 + | n + 1 => branch n * leafCount branch n + +def domainCountBound (branch : Nat → Nat) (n t : Nat) : Nat := + (7 ^ t) ^ leafCount branch n + +def functionCountBound (branch : Nat → Nat) (n t : Nat) : Nat := + 2 ^ domainCountBound branch n t + +def arrayCountBound (branch : Nat → Nat) : (n t : Nat) → (Nat → Nat) → Nat + | 0, _, _ => 1 + | n + 1, t, rows => + functionCountBound branch (n + 1) t ^ rows (n + 1) * + arrayCountBound branch n t rows ^ branch n + +theorem slots_card_eq_leafCount (branch : Nat → Nat) (n : Nat) : + Fintype.card (RecursiveSpaces.Slots branch n) = leafCount branch n := by + induction n with + | zero => + change Fintype.card Unit = 1 + simp + | succ n ih => + change Fintype.card (Fin (branch n) × RecursiveSpaces.Slots branch n) = + branch n * leafCount branch n + rw [Fintype.card_prod, Fintype.card_fin, ih] + +theorem domainBound_eq (branch : Nat → Nat) (n t : Nat) : + domainBound branch n t = domainCountBound branch n t := by + simp only [domainBound, domainCountBound, slots_card_eq_leafCount] + +theorem functionBound_eq (branch : Nat → Nat) (n t : Nat) : + functionBound branch n t = functionCountBound branch n t := by + rw [functionBound, functionCountBound, domainBound_eq] + +@[simp] theorem domainBound_zero (branch : Nat → Nat) (t : Nat) : + domainBound branch 0 t = 7 ^ t := by + rw [domainBound_eq] + simp [domainCountBound, leafCount] + +theorem domainBound_succ (branch : Nat → Nat) (n t : Nat) : + domainBound branch (n + 1) t = domainBound branch n t ^ branch n := by + rw [domainBound_eq, domainBound_eq] + change (7 ^ t) ^ (branch n * leafCount branch n) = + ((7 ^ t) ^ leafCount branch n) ^ branch n + rw [Nat.mul_comm (branch n) (leafCount branch n), pow_mul] + +@[simp] theorem functionBound_zero (branch : Nat → Nat) (t : Nat) : + functionBound branch 0 t = 2 ^ (7 ^ t) := by + rw [functionBound, domainBound_zero] + +theorem functionBound_succ (branch : Nat → Nat) (n t : Nat) : + functionBound branch (n + 1) t = 2 ^ (domainBound branch n t ^ branch n) := by + rw [functionBound, domainBound_succ] + +@[simp] theorem arraysBound_zero (branch : Nat → Nat) (t : Nat) (rows : Nat → Nat) : + arraysBound branch 0 t rows = 1 := by + simp [arraysBound, Nodes] + +theorem arraysBound_succ (branch : Nat → Nat) (n t : Nat) (rows : Nat → Nat) : + arraysBound branch (n + 1) t rows = + functionBound branch (n + 1) t ^ rows (n + 1) * + arraysBound branch n t rows ^ branch n := by + change (∏ node : Unit ⊕ (Fin (branch n) × Nodes branch n), + functionBound branch (Nodes.height (branch := branch) (n := n + 1) node) t ^ + rows (Nodes.height (branch := branch) (n := n + 1) node)) = _ + rw [Fintype.prod_sum_type, Fintype.prod_prod_type] + simp only [Fintype.prod_unique] + change (functionBound branch (n + 1) t ^ rows (n + 1)) * + (∏ _j : Fin (branch n), arraysBound branch n t rows) = + (functionBound branch (n + 1) t ^ rows (n + 1)) * + arraysBound branch n t rows ^ branch n + simp only [Finset.prod_const, Finset.card_univ, Fintype.card_fin] + +theorem arraysBound_eq (branch : Nat → Nat) (n t : Nat) (rows : Nat → Nat) : + arraysBound branch n t rows = arrayCountBound branch n t rows := by + induction n with + | zero => exact arraysBound_zero branch t rows + | succ n ih => + rw [arraysBound_succ, ih, functionBound_eq] + rfl + +theorem leafCount_congr {branch branch' : Nat → Nat} (n : Nat) + (hbranch : ∀ k < n, branch k = branch' k) : + leafCount branch n = leafCount branch' n := by + revert hbranch + induction n with + | zero => intro _; rfl + | succ n ih => + intro hbranch + have hlow : ∀ k < n, branch k = branch' k := + fun k hk => hbranch k (Nat.lt_trans hk (Nat.lt_succ_self n)) + simp only [leafCount, hbranch n (Nat.lt_succ_self n), ih hlow] + +theorem domainCountBound_congr {branch branch' : Nat → Nat} (n t : Nat) + (hbranch : ∀ k < n, branch k = branch' k) : + domainCountBound branch n t = domainCountBound branch' n t := by + simp only [domainCountBound, leafCount_congr n hbranch] + +theorem functionCountBound_congr {branch branch' : Nat → Nat} (n t : Nat) + (hbranch : ∀ k < n, branch k = branch' k) : + functionCountBound branch n t = functionCountBound branch' n t := by + rw [functionCountBound, functionCountBound, domainCountBound_congr n t hbranch] + +theorem arrayCountBound_congr {branch branch' rows rows' : Nat → Nat} (n t : Nat) + (hbranch : ∀ k < n, branch k = branch' k) + (hrows : ∀ k ≤ n, rows k = rows' k) : + arrayCountBound branch n t rows = arrayCountBound branch' n t rows' := by + revert hbranch hrows + induction n with + | zero => intro _ _; rfl + | succ n ih => + intro hbranch hrows + have hlow : ∀ k < n, branch k = branch' k := + fun k hk => hbranch k (Nat.lt_trans hk (Nat.lt_succ_self n)) + have hrowsLow : ∀ k ≤ n, rows k = rows' k := + fun k hk => hrows k (Nat.le_trans hk (Nat.le_succ n)) + simp only [arrayCountBound, functionCountBound_congr (n + 1) t hbranch, + hrows (n + 1) le_rfl, ih hlow hrowsLow, hbranch n (Nat.lt_succ_self n)] + +theorem domainBound_congr {branch branch' : Nat → Nat} (n t : Nat) + (hbranch : ∀ k < n, branch k = branch' k) : + domainBound branch n t = domainBound branch' n t := by + rw [domainBound_eq, domainBound_eq] + exact domainCountBound_congr n t hbranch + +theorem functionBound_congr {branch branch' : Nat → Nat} (n t : Nat) + (hbranch : ∀ k < n, branch k = branch' k) : + functionBound branch n t = functionBound branch' n t := by + rw [functionBound_eq, functionBound_eq] + exact functionCountBound_congr n t hbranch + +theorem arraysBound_congr {branch branch' rows rows' : Nat → Nat} (n t : Nat) + (hbranch : ∀ k < n, branch k = branch' k) + (hrows : ∀ k ≤ n, rows k = rows' k) : + arraysBound branch n t rows = arraysBound branch' n t rows' := by + rw [arraysBound_eq, arraysBound_eq] + exact arrayCountBound_congr n t hbranch hrows + +theorem update_agrees_below (branch : Nat → Nat) (n k value : Nat) (hnk : n ≤ k) : + ∀ j < n, Function.update branch k value j = branch j := by + intro j hj + exact Function.update_of_ne (Nat.ne_of_lt (Nat.lt_of_lt_of_le hj hnk)) value branch + +theorem domainBound_update (branch : Nat → Nat) (n t k value : Nat) (hnk : n ≤ k) : + domainBound (Function.update branch k value) n t = domainBound branch n t := + domainBound_congr n t (update_agrees_below branch n k value hnk) + +theorem functionBound_update (branch : Nat → Nat) (n t k value : Nat) (hnk : n ≤ k) : + functionBound (Function.update branch k value) n t = functionBound branch n t := + functionBound_congr n t (update_agrees_below branch n k value hnk) + +theorem arraysBound_update (branch : Nat → Nat) (n t k value : Nat) + (rows : Nat → Nat) (hnk : n ≤ k) : + arraysBound (Function.update branch k value) n t rows = arraysBound branch n t rows := + arraysBound_congr n t (update_agrees_below branch n k value hnk) (fun _ _ => rfl) + +end PerfectCompleteness.TreeShapeBounds + + +namespace PerfectCompleteness.ChildBlockCardinality + +theorem shape_bound_pos (branch : Nat → Nat) (n t calls : Nat) (rows : Nat → Nat) : + 0 < bound branch n t calls rows := + bound_pos calls rows (fun _ _ => MixedSupport.Slot.bit 0) + +theorem bound_congr {branch branch' : Nat → Nat} (n t calls : Nat) + {rows rows' : Nat → Nat} (hbranch : ∀ k < n, branch k = branch' k) + (hrows : ∀ k ≤ n, rows k = rows' k) : + bound branch n t calls rows = bound branch' n t calls rows' := by + unfold bound + rw [TreeShapeBounds.functionBound_congr n t hbranch, + TreeShapeBounds.arraysBound_congr n t hbranch hrows] + +theorem bound_update (branch : Nat → Nat) (n t calls k value : Nat) + (rows : Nat → Nat) (hnk : n ≤ k) : + bound (Function.update branch k value) n t calls rows = + bound branch n t calls rows := by + unfold bound + rw [TreeShapeBounds.functionBound_update branch n t k value hnk, + TreeShapeBounds.arraysBound_update branch n t k value rows hnk] + + +open RecursiveSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +noncomputable section + +variable {branch : Nat → Nat} {n t calls : Nat} {rows : Nat → Nat} + {slots : Slots branch n → Fin t → MixedSupport.Slot} + +def zeroRaw (calls : Nat) (rows : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : Raw calls rows slots := + (fun _ => 0, fun _ _ => 0) + +def allZero (x : Raw calls rows slots) : Bool := by + classical + exact decide ((∀ q, x.1 q = 0) ∧ ∀ node row, x.2 node row = 0) + +theorem allZero_iff (x : Raw calls rows slots) : + allZero x = true ↔ x = zeroRaw calls rows slots := by + classical + simp only [allZero, decide_eq_true_eq] + constructor + · rintro ⟨hc, ha⟩ + apply Prod.ext + · funext q + exact hc q + · funext node row + exact ha node row + · intro h + subst x + exact ⟨fun _ => rfl, fun _ _ => rfl⟩ + +theorem probability_allZero : + (FiniteDistribution.uniform (Raw calls rows slots)).probability allZero = + 1 / (Fintype.card (Raw calls rows slots) : ℝ) := by + classical + have hevent : (allZero : Raw calls rows slots → Bool) = + fun x => decide (x = zeroRaw calls rows slots) := by + funext x + apply Bool.eq_iff_iff.mpr + rw [allZero_iff, decide_eq_true_eq] + rw [hevent] + simp only [FiniteDistribution.probability, FiniteDistribution.uniform, + decide_eq_true_eq, one_div] + rw [Finset.sum_eq_single (zeroRaw calls rows slots)] + · simp + · intro x _ hx + exact ite_eq_right hx + · simp only [Finset.mem_univ, not_true_eq_false, false_implies] + +def cleanLowerBound (branch : Nat → Nat) (n t calls : Nat) (rows : Nat → Nat) : ℝ := + 1 / (bound branch n t calls rows : ℝ) + +theorem cleanLowerBound_pos (branch : Nat → Nat) (n t calls : Nat) (rows : Nat → Nat) : + 0 < cleanLowerBound branch n t calls rows := + one_div_pos.mpr (Nat.cast_pos.mpr (shape_bound_pos branch n t calls rows)) + +theorem cleanLowerBound_le_one (branch : Nat → Nat) (n t calls : Nat) (rows : Nat → Nat) : + cleanLowerBound branch n t calls rows ≤ 1 := by + have hpos : (0 : ℝ) < bound branch n t calls rows := + Nat.cast_pos.mpr (shape_bound_pos branch n t calls rows) + apply (div_le_one hpos).2 + exact_mod_cast Nat.succ_le_of_lt (shape_bound_pos branch n t calls rows) + +theorem cleanLowerBound_le_probability : + cleanLowerBound branch n t calls rows ≤ + (FiniteDistribution.uniform (Raw calls rows slots)).probability allZero := by + rw [probability_allZero] + exact one_div_le_one_div_of_le (Nat.cast_pos.mpr Fintype.card_pos) + (by exact_mod_cast fintype_card_le calls rows slots) + +theorem cleanLowerBound_update (branch : Nat → Nat) (n t calls k value : Nat) + (rows : Nat → Nat) (hnk : n ≤ k) : + cleanLowerBound (Function.update branch k value) n t calls rows = + cleanLowerBound branch n t calls rows := by + unfold cleanLowerBound + rw [bound_update branch n t calls k value rows hnk] + +end +end PerfectCompleteness.ChildBlockCardinality + + +namespace PerfectCompleteness.FixedBranching + +open AscendingBranching ChildBlockCardinality + +noncomputable section + +def extend {n : Nat} (prior : Fin n → Nat) : Nat → Nat := + fun k => if h : k < n then prior ⟨k, h⟩ else 0 + +def cleanRate (cost : Nat) (L : ℝ) : ℝ := 1 / ((48000 : ℝ) * cost * L) + +theorem cleanRate_pos {cost : Nat} (hcost : 0 < cost) {L : ℝ} (hL : 0 < L) : + 0 < cleanRate cost L := by + have : (0 : ℝ) < cost := by exact_mod_cast hcost + unfold cleanRate + positivity + +theorem cleanRate_le_one {cost : Nat} (hcost : 0 < cost) {L : ℝ} (hL : 1 ≤ L) : + cleanRate cost L ≤ 1 := by + have hc : (1 : ℝ) ≤ cost := by exact_mod_cast hcost + have hp : (1 : ℝ) ≤ (cost : ℝ) * L := by nlinarith + unfold cleanRate + apply (div_le_one (by positivity)).2 + nlinarith + +theorem exists_branching (t cost : Nat) (rows calls : Nat → Nat) + (hcost : 0 < cost) {ε : ℝ} (hε : 0 < ε) : + ∃ size : Nat → Nat, ∀ n, + CubeErrors (bound (fun k => size k ^ 3) n t (calls n) rows : ℝ) + (cleanRate cost (bound (fun k => size k ^ 3) n t (calls n) rows : ℝ)) ε (size n) := by + let L := fun n (prior : Fin n → Nat) => (bound (extend prior) n t (calls n) rows : ℝ) + have hL : ∀ n prior, 0 < L n prior := by + intro n prior + dsimp [L] + exact_mod_cast shape_bound_pos (extend prior) n t (calls n) rows + have hL1 : ∀ n prior, 1 ≤ L n prior := by + intro n prior + dsimp [L] + exact_mod_cast Nat.succ_le_of_lt (shape_bound_pos (extend prior) n t (calls n) rows) + obtain ⟨size, hsize⟩ := exists_ascending_cubes L + (fun n prior => cleanRate cost (L n prior)) + (fun n prior => (hL n prior).le) + (fun n prior => cleanRate_pos hcost (hL n prior)) + (fun n prior => cleanRate_le_one hcost (hL1 n prior)) hε + refine ⟨size, fun n => ?_⟩ + have hbound : bound (extend (fun i : Fin n => size i.val ^ 3)) n t (calls n) rows = + bound (fun k => size k ^ 3) n t (calls n) rows := by + apply bound_congr n t (calls n) + · intro k hk + simp only [extend, dite_eq_left hk] + · intro k hk + rfl + simpa only [L, hbound] using hsize n + +theorem rational_probability {m : Nat} (hm : 2 ≤ m) : + 0 < (1 : ℚ) / (m : ℚ) ^ 2 ∧ (1 : ℚ) / (m : ℚ) ^ 2 < 1 := by + have hmr : (2 : ℚ) ≤ m := by exact_mod_cast hm + have hp : (0 : ℚ) < (m : ℚ) ^ 2 := by positivity + constructor + · positivity + · apply (div_lt_one hp).2 + nlinarith + +end +end PerfectCompleteness.FixedBranching + + +namespace PerfectCompleteness.FixedSourceBranching + +open FixedRows AscendingBranching ChildBlockCardinality + +noncomputable section + +variable {δ : ℚ} (plan : Plan δ) (hδ : 0 < δ) + +theorem source_rate (cost : Nat) (hcost : 0 < cost) + (hbudget : SourceOddLists.alphabetLog (cutoff plan hδ) (sourceLength plan hδ) ≤ cost) + (input : List Bool) (unsat : ¬BinaryLanguage.language input) (k : Nat) : + ((SourceOddLists.game (cutoff plan hδ) + (PCPSource.clauseFamily (BinaryLanguage.totalRename input)) + (sourceLength plan hδ)).repetition k).value ≤ + (RepetitionRate.halfRate cost : ℝ) ^ k := + SourceOddLists.repetition_halfRate + (PCPSource.clauseFamily (BinaryLanguage.totalRename input)) PCPSource.sourceGap + PCPSource.sourceGap_pos PCPSource.sourceGap_le_one + (PCPSourceMachine.rawSource_clauseGap input unsat) hcost hbudget k + +theorem exists_source_branching (calls : Nat → Nat) {ε : ℝ} (hε : 0 < ε) : + ∃ cost : Nat, 0 < cost ∧ + SourceOddLists.alphabetLog (cutoff plan hδ) (sourceLength plan hδ) ≤ cost ∧ + ∃ size : Nat → Nat, ∀ n, + CubeErrors + (bound (fun k => size k ^ 3) n (sourceLength plan hδ) (calls n) (rows plan) : ℝ) + (FixedBranching.cleanRate cost + (bound (fun k => size k ^ 3) n (sourceLength plan hδ) (calls n) (rows plan) : ℝ)) + ε (size n) := by + obtain ⟨cost, hcost, hbudget⟩ := + SourceOddLists.exists_alphabet_budget (cutoff plan hδ) (sourceLength plan hδ) + obtain ⟨size, hsize⟩ := FixedBranching.exists_branching + (sourceLength plan hδ) cost (rows plan) calls hcost hε + exact ⟨cost, hcost, hbudget, size, hsize⟩ + +end +end PerfectCompleteness.FixedSourceBranching + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/OriginalChildScalars.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/OriginalChildScalars.lean new file mode 100644 index 0000000000000000000000000000000000000000..594754b9d03ffba974991c8987d6c52ef0b94e4b --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/OriginalChildScalars.lean @@ -0,0 +1,204 @@ +import OAI.Computability.PerfectCompleteness.Construction.OriginalChildBlockProducts +import OAI.Computability.PerfectCompleteness.Construction.SourceQuestionOrderLemmas +import OAI.Computability.PerfectCompleteness.Sampling.BucketUniformLemmas +import OAI.Computability.PerfectCompleteness.Sampling.WholeArraySampler + +namespace OAI + +section + +namespace PerfectCompleteness.OriginalChildScalars + +open PointwiseSpaces RecursiveSpaces DescendantSpaces TreeSourceSpaces +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +noncomputable section + +private theorem product_swap {A B : Type*} [Fintype A] [Fintype B] + (μ : FiniteDistribution A) (ν : FiniteDistribution B) : + (μ.product ν).pushforward Prod.swap = ν.product μ := by + change (μ.product ν).pushforward (Equiv.prodComm A B) = _ + rw [← FiniteDistribution.transport_eq_pushforward] + apply FiniteDistribution.eq_of_weight_eq + rintro ⟨b, a⟩ + exact mul_comm _ _ + +private theorem product_swap_map {A B C : Type*} [Fintype A] [Fintype B] [Fintype C] + (μ : FiniteDistribution A) (ν : FiniteDistribution B) (f : B → C) : + (μ.product ν).pushforward (fun z => (f z.2, z.1)) = (ν.pushforward f).product μ := by + calc + _ = ((μ.product ν).pushforward Prod.swap).pushforward (fun z => (f z.1, z.2)) := + (FiniteDistribution.pushforward_comp _ _ _).symm + _ = (ν.product μ).pushforward (fun z => (f z.1, z.2)) := by rw [product_swap] + _ = _ := by + simpa only [id_eq, FiniteDistribution.pushforward_id] using + FiniteDistribution.product_pushforward ν μ f (id : A → A) + +variable {branch : Nat → Nat} {n m t : Nat} + +abbrev Square (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (child : Fin (branch n)) := squareSpace (H (childSlots slots child)) + +instance squareFintype (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (child : Fin (branch n)) : Fintype (Square slots child) := Fintype.ofFinite _ + +def squareSum (repeats : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) (chosen : Fin (branch n)) + (values : RecursiveSampler.CallIndex repeats n → H (childSlots slots chosen)) : + Square slots chosen := + ∑ pair : Fin (repeats (n + 1)), + RecursiveSamplerBiasAlgebra.squareProduct F2 (H (childSlots slots chosen)) + (values (pair, false)) (values (pair, true)) + +def specialSquareLaw (repeats : Nat → Nat) (q : Path branch n m) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) (chosen : Fin (branch n)) : + FiniteDistribution (Square slots chosen) := + (RecursiveSampler.callScalarLaw F2 repeats chosen q (LeafDomain slots)).pushforward + (squareSum repeats slots chosen) + +def squareComponent (repeats : Nat → Nat) (q : Path branch n m) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) (chosen : Fin (branch n)) : + (child : Fin (branch n)) → FiniteDistribution (Square slots child) := + ChildBlockMixture.component (specialSquareLaw repeats q slots) chosen + +@[simp] theorem squareComponent_self (repeats : Nat → Nat) (q : Path branch n m) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) (chosen : Fin (branch n)) : + squareComponent repeats q slots chosen chosen = specialSquareLaw repeats q slots chosen := + dite_eq_left rfl + +@[simp] theorem squareComponent_other (repeats : Nat → Nat) (q : Path branch n m) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (chosen : Fin (branch n)) (child : RecursiveSampler.OffPath chosen) : + squareComponent repeats q slots chosen child.val = FiniteDistribution.uniform (Square slots child.val) := + dite_eq_right (Ne.symm child.property) + +abbrev ScalarTape (repeats : Nat → Nat) (chosen : Fin (branch n)) (q : Path branch n m) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) := + RecursiveSampler.Tape F2 repeats (.step chosen q) (LeafDomain slots) + +def selectedAndOthers (repeats : Nat → Nat) (chosen : Fin (branch n)) (q : Path branch n m) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ω : ScalarTape repeats chosen q slots) : + Square slots chosen × ((child : RecursiveSampler.OffPath chosen) → Square slots child.val) := + let split := RecursiveSampler.splitEvaluatedTape F2 repeats chosen q (LeafDomain slots) ω + (squareSum repeats slots chosen split.2, split.1) + +def stepSquareMap (repeats : Nat → Nat) (chosen : Fin (branch n)) (q : Path branch n m) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ω : ScalarTape repeats chosen q slots) : (child : Fin (branch n)) → Square slots child := + (Equiv.piSplitAt chosen (fun child => ↥(Square slots child))).symm + (selectedAndOthers repeats chosen q slots ω) + +theorem selectedAndOthers_law (repeats : Nat → Nat) (chosen : Fin (branch n)) + (q : Path branch n m) (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) : + (RecursiveSampler.tapeLaw F2 repeats (.step chosen q) (LeafDomain slots)).pushforward + (selectedAndOthers repeats chosen q slots) = + (specialSquareLaw repeats q slots chosen).product + (RecursiveSampler.ordinaryLaw F2 repeats chosen q (LeafDomain slots)) := by + calc + _ = ((RecursiveSampler.tapeLaw F2 repeats (.step chosen q) (LeafDomain slots)).pushforward + (RecursiveSampler.splitEvaluatedTape F2 repeats chosen q (LeafDomain slots))).pushforward + (fun z => (squareSum repeats slots chosen z.2, z.1)) := + (FiniteDistribution.pushforward_comp _ _ _).symm + _ = ((RecursiveSampler.ordinaryLaw F2 repeats chosen q (LeafDomain slots)).product + (RecursiveSampler.callScalarLaw F2 repeats chosen q (LeafDomain slots))).pushforward + (fun z => (squareSum repeats slots chosen z.2, z.1)) := by + rw [RecursiveSampler.splitEvaluatedTape_law] + _ = _ := product_swap_map _ _ (squareSum repeats slots chosen) + +theorem squareComponent_otherLaw (repeats : Nat → Nat) (chosen : Fin (branch n)) + (q : Path branch n m) (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) : + FiniteProductSplit.otherLaw (squareComponent repeats q slots chosen) chosen = + RecursiveSampler.ordinaryLaw F2 repeats chosen q (LeafDomain slots) := by + apply congrArg (fun laws : (child : RecursiveSampler.OffPath chosen) → + FiniteDistribution (Square slots child.val) => FiniteProduct.law laws) + funext child + exact squareComponent_other repeats q slots chosen child + +theorem stepSquareMap_law (repeats : Nat → Nat) (chosen : Fin (branch n)) + (q : Path branch n m) (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) : + (RecursiveSampler.tapeLaw F2 repeats (.step chosen q) (LeafDomain slots)).pushforward + (stepSquareMap repeats chosen q slots) = + FiniteProduct.law (squareComponent repeats q slots chosen) := by + let merge : + Square slots chosen × ((child : RecursiveSampler.OffPath chosen) → Square slots child.val) → + (child : Fin (branch n)) → Square slots child := + (Equiv.piSplitAt chosen (fun child => ↥(Square slots child))).symm + have hsplit : + (RecursiveSampler.tapeLaw F2 repeats (.step chosen q) (LeafDomain slots)).pushforward + (selectedAndOthers repeats chosen q slots) = + (squareComponent repeats q slots chosen chosen).product + (FiniteProductSplit.otherLaw (squareComponent repeats q slots chosen) chosen) := + (selectedAndOthers_law repeats chosen q slots).trans + (congrArg₂ + (fun (μ : FiniteDistribution (Square slots chosen)) + (ν : FiniteDistribution + ((child : RecursiveSampler.OffPath chosen) → Square slots child.val)) => μ.product ν) + (squareComponent_self repeats q slots chosen).symm + (squareComponent_otherLaw repeats chosen q slots).symm) + have hmerge : + ((squareComponent repeats q slots chosen chosen).product + (FiniteProductSplit.otherLaw (squareComponent repeats q slots chosen) chosen)).pushforward + merge = FiniteProduct.law (squareComponent repeats q slots chosen) := + OriginalChildBlockProducts.merge_law (Ω := fun child => ↥(Square slots child)) + (squareComponent repeats q slots chosen) chosen + calc + _ = ((RecursiveSampler.tapeLaw F2 repeats (.step chosen q) (LeafDomain slots)).pushforward + (selectedAndOthers repeats chosen q slots)).pushforward merge := + (FiniteDistribution.pushforward_comp _ _ _).symm + _ = ((squareComponent repeats q slots chosen chosen).product + (FiniteProductSplit.otherLaw (squareComponent repeats q slots chosen) chosen)).pushforward + merge := + congrArg (fun μ : FiniteDistribution + (Square slots chosen × ((child : RecursiveSampler.OffPath chosen) → Square slots child.val)) => + μ.pushforward merge) hsplit + _ = _ := hmerge + +def callsLaw (calls : Nat) (repeats : Nat → Nat) (chosen : Fin (branch n)) + (q : Path branch n m) (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) : + FiniteDistribution (Fin calls → ScalarTape repeats chosen q slots) := + FiniteProduct.law (fun _ : Fin calls => + RecursiveSampler.tapeLaw F2 repeats (.step chosen q) (LeafDomain slots)) + +def callContributions (calls : Nat) (repeats : Nat → Nat) (chosen : Fin (branch n)) + (q : Path branch n m) (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ω : Fin calls → ScalarTape repeats chosen q slots) : + (child : Fin (branch n)) → Fin calls → Square slots child := + fun child call => stepSquareMap repeats chosen q slots (ω call) child + +def callComponent (calls : Nat) (repeats : Nat → Nat) (chosen : Fin (branch n)) + (q : Path branch n m) (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (child : Fin (branch n)) : FiniteDistribution (Fin calls → Square slots child) := + FiniteProduct.law (fun _ : Fin calls => squareComponent repeats q slots chosen child) + +theorem callContributions_law (calls : Nat) (repeats : Nat → Nat) (chosen : Fin (branch n)) + (q : Path branch n m) (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) : + (callsLaw calls repeats chosen q slots).pushforward + (callContributions calls repeats chosen q slots) = + FiniteProduct.law (callComponent calls repeats chosen q slots) := by + have hcalls : (callsLaw calls repeats chosen q slots).pushforward + (fun ω call => stepSquareMap repeats chosen q slots (ω call)) = + FiniteProduct.law (fun _ : Fin calls => + FiniteProduct.law (squareComponent repeats q slots chosen)) := by + have h := FiniteProduct.pushforward_map + (fun _ : Fin calls => RecursiveSampler.tapeLaw F2 repeats (.step chosen q) (LeafDomain slots)) + (fun _ => stepSquareMap repeats chosen q slots) + simpa only [callsLaw, stepSquareMap_law] using h + calc + _ = ((callsLaw calls repeats chosen q slots).pushforward + (fun ω call => stepSquareMap repeats chosen q slots (ω call))).pushforward + (fun x child call => x call child) := + (FiniteDistribution.pushforward_comp _ _ _).symm + _ = (FiniteProduct.law (fun _ : Fin calls => + FiniteProduct.law (squareComponent repeats q slots chosen))).pushforward + (fun x child call => x call child) := by rw [hcalls] + _ = _ := OriginalChildBlockProducts.transpose_law + (fun _ : Fin calls => squareComponent repeats q slots chosen) + +end +end PerfectCompleteness.OriginalChildScalars + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/OriginalCutBucketReplacement.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/OriginalCutBucketReplacement.lean new file mode 100644 index 0000000000000000000000000000000000000000..8045c6f3209c86cb339428dab9a796465e2f2e47 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/OriginalCutBucketReplacement.lean @@ -0,0 +1,279 @@ +import OAI.Computability.PerfectCompleteness.Algebra.BucketMatrixResampling +import OAI.Computability.PerfectCompleteness.Foundations.OriginalWholeCut +import OAI.Computability.PerfectCompleteness.Foundations.WholeArrayInteriorExteriorLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.OriginalCutBucketReplacement + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCut OriginalWholeCutTape +open scoped Classical + +noncomputable section + +variable {branch : Nat → Nat} {n m t : Nat} + +def ownValues (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (values : Values rows repeats p slots) : + BucketSampler.Direction (rows (m + 1)) → H (cutSlots p slots) := + fun a => values (OriginalCutCalls.ownBucket rows repeats p a) + +def replaceValues (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (values : Values rows repeats p slots) + (a : BucketSampler.Direction (rows (m + 1))) (fresh : H (cutSlots p slots)) : + Values rows repeats p slots := + Function.update values (OriginalCutCalls.ownBucket rows repeats p a) fresh + +theorem ownValues_replaceValues (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (values : Values rows repeats p slots) + (a : BucketSampler.Direction (rows (m + 1))) (fresh : H (cutSlots p slots)) : + ownValues rows repeats p slots (replaceValues rows repeats p slots values a fresh) = + Function.update (ownValues rows repeats p slots values) a fresh := + Function.update_comp_eq_of_injective' values + (OriginalCutCalls.ownBucket_injective rows repeats p) a fresh + +theorem replaceValues_rootCalls (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n (m + 1)) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (values : Values rows repeats (.step i p) slots) + (a : BucketSampler.Direction (rows (m + 1))) + (fresh : H (cutSlots (.step i p) slots)) : + (fun direction terminal => replaceValues rows repeats (.step i p) slots values a fresh + (.inl (direction, terminal))) = + (fun direction terminal => values (.inl (direction, terminal))) := by + funext direction terminal + exact Function.update_of_ne + (OriginalCutCalls.root_ne_ownBucket rows repeats i p (direction, terminal) a) _ _ + +theorem replaceValues_lowerCalls (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n (m + 1)) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (values : Values rows repeats (.step i p) slots) + (a : BucketSampler.Direction (rows (m + 1))) + (fresh : H (cutSlots (.step i p) slots)) : + (fun call => replaceValues rows repeats (.step i p) slots values a fresh (.inr call)) = + replaceValues rows repeats p (childSlots slots i) + (fun call => values (.inr call)) a fresh := + Function.update_comp_eq_of_injective' values Sum.inr_injective + (OriginalCutCalls.ownBucket rows repeats p a) fresh + +theorem selectedRows_reconstruct (rows repeats : Nat → Nat) : + ∀ {n m : Nat} (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (exterior : Exterior rows repeats p slots) (values : Values rows repeats p slots) + (below : BelowArrays rows p slots), + SelectedArrayReplacement.selectedRows rows p slots + (reconstruct rows repeats p slots exterior values below) = + BucketSampler.evaluate (rows (m + 1)) (id : H (cutSlots p slots) → H (cutSlots p slots)) + (ownValues rows repeats p slots values) := by + intro n + induction n with + | zero => intro m p; cases p + | succ n ih => + intro m p slots exterior values below + cases p with + | refl => rfl + | step i p => + change SelectedArrayReplacement.selectedRows rows (.step i p) slots + (WholeArraySampler.assemble slots rows + (reconstructBuckets rows repeats (.step i p) slots + (fun direction terminal => values (.inl (direction, terminal))) exterior.1) + (WholeArraySampler.childrenAt slots rows i + (reconstruct rows repeats p (childSlots slots i) exterior.2.1 + (fun call => values (.inr call)) below) exterior.2.2)) = _ + rw [SelectedArrayReplacement.selectedRows_assemble_step] + exact ih p (childSlots slots i) exterior.2.1 (fun call => values (.inr call)) below + +theorem reconstruct_replaceValues (rows repeats : Nat → Nat) : + ∀ {n m : Nat} (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (exterior : Exterior rows repeats p slots) (values : Values rows repeats p slots) + (below : BelowArrays rows p slots) + (a : BucketSampler.Direction (rows (m + 1))) (fresh : H (cutSlots p slots)), + reconstruct rows repeats p slots exterior + (replaceValues rows repeats p slots values a fresh) below = + SelectedArrayReplacement.replace rows p slots + (reconstruct rows repeats p slots exterior values below) + (BucketSampler.evaluate (rows (m + 1)) + (id : H (cutSlots p slots) → H (cutSlots p slots)) + (Function.update (ownValues rows repeats p slots values) a fresh)) := by + intro n + induction n with + | zero => intro m p; cases p + | succ n ih => + intro m p slots exterior values below a fresh + cases p with + | refl => + exact congrArg + (fun buckets : BucketSampler.Direction (rows (n + 1)) → H slots => + WholeArraySampler.assemble slots rows + (BucketSampler.evaluate (rows (n + 1)) (id : H slots → H slots) buckets) below) + (ownValues_replaceValues rows repeats (.refl (n + 1)) slots values a fresh) + | step i p => + change WholeArraySampler.assemble slots rows + (reconstructBuckets rows repeats (.step i p) slots + (fun direction terminal => + replaceValues rows repeats (.step i p) slots values a fresh + (.inl (direction, terminal))) exterior.1) + (WholeArraySampler.childrenAt slots rows i + (reconstruct rows repeats p (childSlots slots i) exterior.2.1 + (fun call => replaceValues rows repeats (.step i p) slots values a fresh + (.inr call)) below) exterior.2.2) = + SelectedArrayReplacement.replace rows (.step i p) slots + (WholeArraySampler.assemble slots rows + (reconstructBuckets rows repeats (.step i p) slots + (fun direction terminal => values (.inl (direction, terminal))) exterior.1) + (WholeArraySampler.childrenAt slots rows i + (reconstruct rows repeats p (childSlots slots i) exterior.2.1 + (fun call => values (.inr call)) below) exterior.2.2)) _ + rw [replaceValues_rootCalls, replaceValues_lowerCalls, + SelectedArrayReplacement.replace_assemble_step] + exact congrArg (fun selected => WholeArraySampler.assemble slots rows + (reconstructBuckets rows repeats (.step i p) slots + (fun direction terminal => values (.inl (direction, terminal))) exterior.1) + (WholeArraySampler.childrenAt slots rows i selected exterior.2.2)) + (ih p (childSlots slots i) exterior.2.1 + (fun call => values (.inr call)) below a fresh) + +def replaceRecord (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : Record rows repeats p slots) + (a : BucketSampler.Direction (rows (m + 1))) (fresh : H (cutSlots p slots)) : + Record rows repeats p slots := + (record.1, (replaceValues rows repeats p slots record.2.1 a fresh, record.2.2)) + +theorem reconstructRecord_replace_outside (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : Record rows repeats p slots) + (a : BucketSampler.Direction (rows (m + 1))) (fresh : H (cutSlots p slots)) + (node : Nodes branch n) (hnode : node ≠ WholeArrayInteriorExterior.upperNode p) : + reconstructRecord rows repeats p slots (replaceRecord rows repeats p slots record a fresh) node = + reconstructRecord rows repeats p slots record node := by + change reconstruct rows repeats p slots record.1 + (replaceValues rows repeats p slots record.2.1 a fresh) record.2.2 node = _ + rw [reconstruct_replaceValues] + exact SelectedArrayReplacement.replace_outside rows p slots _ _ node hnode + +theorem reconstruct_outside_eq_of_nonown_eq (rows repeats : Nat → Nat) : + ∀ {n m : Nat} (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (exterior : Exterior rows repeats p slots) + (values₁ values₂ : Values rows repeats p slots) (below : BelowArrays rows p slots), + (∀ call, (∀ a, call ≠ OriginalCutCalls.ownBucket rows repeats p a) → + values₁ call = values₂ call) → + ∀ node : Nodes branch n, node ≠ WholeArrayInteriorExterior.upperNode p → + reconstruct rows repeats p slots exterior values₁ below node = + reconstruct rows repeats p slots exterior values₂ below node := by + intro n + induction n with + | zero => intro m p; cases p + | succ n ih => + intro m p slots exterior values₁ values₂ below hvalues node hnode + cases p with + | refl => + cases node with + | inl u => cases u; exact False.elim (hnode rfl) + | inr pair => rfl + | step i p => + have hroot : (fun direction terminal => values₁ (.inl (direction, terminal))) = + (fun direction terminal => values₂ (.inl (direction, terminal))) := by + funext direction terminal + exact hvalues (.inl (direction, terminal)) + (fun a => OriginalCutCalls.root_ne_ownBucket rows repeats i p + (direction, terminal) a) + have hlower : ∀ call, + (∀ a, call ≠ OriginalCutCalls.ownBucket rows repeats p a) → + values₁ (.inr call) = values₂ (.inr call) := by + intro call hcall + apply hvalues (.inr call) + intro a heq + exact hcall a (Sum.inr.inj heq) + cases node with + | inl u => + cases u + change reconstructBuckets rows repeats (.step i p) slots + (fun direction terminal => values₁ (.inl (direction, terminal))) exterior.1 = + reconstructBuckets rows repeats (.step i p) slots + (fun direction terminal => values₂ (.inl (direction, terminal))) exterior.1 + rw [hroot] + | inr pair => + rcases pair with ⟨child, node⟩ + by_cases hchild : child = i + · subst child + have hnode' : node ≠ WholeArrayInteriorExterior.upperNode p := by + intro h + exact hnode (congrArg (fun v => Sum.inr (i, v)) h) + change WholeArraySampler.childrenAt slots rows i + (reconstruct rows repeats p (childSlots slots i) exterior.2.1 + (fun call => values₁ (.inr call)) below) exterior.2.2 i node = + WholeArraySampler.childrenAt slots rows i + (reconstruct rows repeats p (childSlots slots i) exterior.2.1 + (fun call => values₂ (.inr call)) below) exterior.2.2 i node + rw [WholeArraySampler.childrenAt_selected, + WholeArraySampler.childrenAt_selected] + exact ih p (childSlots slots i) exterior.2.1 + (fun call => values₁ (.inr call)) (fun call => values₂ (.inr call)) + below hlower node hnode' + · change WholeArraySampler.childrenAt slots rows i + (reconstruct rows repeats p (childSlots slots i) exterior.2.1 + (fun call => values₁ (.inr call)) below) exterior.2.2 child node = + WholeArraySampler.childrenAt slots rows i + (reconstruct rows repeats p (childSlots slots i) exterior.2.1 + (fun call => values₂ (.inr call)) below) exterior.2.2 child node + simp only [WholeArraySampler.childrenAt, dite_eq_right hchild] + +theorem selectedRows_reconstructRecord_replace (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : Record rows repeats p slots) + (a : BucketSampler.Direction (rows (m + 1))) (fresh : H (cutSlots p slots)) : + SelectedArrayReplacement.selectedRows rows p slots + (reconstructRecord rows repeats p slots (replaceRecord rows repeats p slots record a fresh)) = + SelectedArrayReplacement.selectedRows rows p slots + (reconstructRecord rows repeats p slots record) + + BucketSampler.rankOne a.val + (fresh - record.2.1 (OriginalCutCalls.ownBucket rows repeats p a)) := by + change SelectedArrayReplacement.selectedRows rows p slots + (reconstruct rows repeats p slots record.1 + (replaceValues rows repeats p slots record.2.1 a fresh) record.2.2) = + SelectedArrayReplacement.selectedRows rows p slots + (reconstruct rows repeats p slots record.1 record.2.1 record.2.2) + _ + rw [selectedRows_reconstruct, selectedRows_reconstruct, ownValues_replaceValues, + BucketSampler.evaluate_update] + rfl + +theorem selectedMatrix_reconstructRecord_replace (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : Record rows repeats p slots) + (a : BucketSampler.Direction (rows (m + 1))) (fresh : H (cutSlots p slots)) : + EvaluationMatrix.ofRows (H (cutSlots p slots)) + (SelectedArrayReplacement.selectedRows rows p slots + (reconstructRecord rows repeats p slots (replaceRecord rows repeats p slots record a fresh))) = + EvaluationMatrix.shift (H (cutSlots p slots)) + (EvaluationMatrix.ofRows (H (cutSlots p slots)) + (SelectedArrayReplacement.selectedRows rows p slots + (reconstructRecord rows repeats p slots record))) + a.val (fresh - record.2.1 (OriginalCutCalls.ownBucket rows repeats p a)) := by + change EvaluationMatrix.ofRows (H (cutSlots p slots)) + (SelectedArrayReplacement.selectedRows rows p slots + (reconstruct rows repeats p slots record.1 + (replaceValues rows repeats p slots record.2.1 a fresh) record.2.2)) = _ + rw [selectedRows_reconstruct, ownValues_replaceValues] + have hold := selectedRows_reconstruct rows repeats p slots record.1 record.2.1 record.2.2 + change SelectedArrayReplacement.selectedRows rows p slots + (reconstructRecord rows repeats p slots record) = _ at hold + rw [hold] + exact BucketMatrixResampling.assembledMatrix_update (H (cutSlots p slots)) + (rows (m + 1)) (ownValues rows repeats p slots record.2.1) a fresh + +end +end PerfectCompleteness.OriginalCutBucketReplacement + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/OriginalHiddenChild.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/OriginalHiddenChild.lean new file mode 100644 index 0000000000000000000000000000000000000000..41bdedcb7f50e08c9b182a42a8ab87332b4f1390 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/OriginalHiddenChild.lean @@ -0,0 +1,207 @@ +import OAI.Computability.PerfectCompleteness.Construction.OriginalChildBlocks +import OAI.Computability.PerfectCompleteness.Construction.SourceQuestionOrderLemmas +import OAI.Computability.PerfectCompleteness.Foundations.GeometricPathLemmas +import OAI.Computability.PerfectCompleteness.Reduction.CompletionSoundness + +namespace OAI + +section + +namespace PerfectCompleteness.OriginalHiddenChild + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +noncomputable section + +private theorem sigmaLaw_pushforward {E Γ : Type*} {F : E → Type*} + [Fintype E] [∀ e, Fintype (F e)] [Fintype Γ] + (μ : FiniteDistribution E) (ν : ∀ e, FiniteDistribution (F e)) + (f : ∀ e, F e → Γ) : + (CompletionSoundness.sigmaLaw μ ν).pushforward (fun x => f x.1 x.2) = + μ.mixture (fun e => (ν e).pushforward (f e)) := by + apply FiniteDistribution.eq_of_weight_eq + intro z + simp only [FiniteDistribution.pushforward, CompletionSoundness.sigmaLaw, + FiniteDistribution.mixture, Fintype.sum_sigma, Finset.mul_sum, mul_ite, mul_zero] + +private theorem product_mixture {E F Γ : Type*} + [Fintype E] [Fintype F] [Fintype Γ] + (μ : FiniteDistribution E) (ν : FiniteDistribution F) + (R : E × F → FiniteDistribution Γ) : + (μ.product ν).mixture R = μ.mixture (fun e => ν.mixture (fun f => R (e, f))) := by + apply FiniteDistribution.eq_of_weight_eq + intro z + simp only [FiniteDistribution.mixture, FiniteDistribution.product, + Fintype.sum_prod_type, Finset.mul_sum, mul_assoc] + +variable {branch : Nat → Nat} {n t : Nat} + +abbrev Blocks (calls : Nat) (rows : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) := + (child : Fin (branch n)) → ChildBlockCardinality.Raw calls rows (childSlots slots child) + +abbrev Tape (calls : Nat) (rows repeats : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) := + Σ leaf : Slots branch (n + 1), OriginalChildBlocks.SourceTape calls rows repeats + leaf.1 (GeometricPath.leafPath leaf.2) slots + +def sourceLaw (calls : Nat) (rows repeats : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (hbranch : ∀ k < n + 1, 0 < branch k) : + FiniteDistribution (Tape calls rows repeats slots) := + CompletionSoundness.sigmaLaw (GeometricPath.law (n + 1) hbranch) + (fun leaf => OriginalChildBlocks.sourceLaw calls rows repeats leaf.1 + (GeometricPath.leafPath leaf.2) slots) + +def rawMap (calls : Nat) (rows repeats : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ω : Tape calls rows repeats slots) : Blocks calls rows slots := + OriginalChildBlocks.rawMap calls rows repeats ω.1.1 + (GeometricPath.leafPath ω.1.2) slots ω.2 + +def continuationLaw (hbranch : ∀ k < n + 1, 0 < branch k) : + FiniteDistribution (Slots branch n) := + GeometricPath.law n (fun k hk => hbranch k (Nat.lt_trans hk (Nat.lt_succ_self n))) + +def averagedSpecial (calls : Nat) (rows repeats : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (hbranch : ∀ k < n + 1, 0 < branch k) (child : Fin (branch n)) : + FiniteDistribution (ChildBlockCardinality.Raw calls rows (childSlots slots child)) := + (continuationLaw hbranch).mixture (fun leaf => + OriginalChildBlocks.specialLaw calls rows repeats (GeometricPath.leafPath leaf) slots child) + +def blockMixture (calls : Nat) (rows repeats : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (hbranch : ∀ k < n + 1, 0 < branch k) : FiniteDistribution (Blocks calls rows slots) := by + letI : Nonempty (Fin (branch n)) := ⟨⟨0, hbranch n (Nat.lt_succ_self n)⟩⟩ + exact ChildBlockMixture.mixture (averagedSpecial calls rows repeats slots hbranch) + +private theorem special_as_continued (calls : Nat) (rows repeats : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (chosen : Fin (branch n)) (leaf : Slots branch n) : + ChildBlockMixture.special + (OriginalChildBlocks.specialLaw calls rows repeats (GeometricPath.leafPath leaf) slots) + chosen = + ChildBlockContinuation.continuedSpecial + (fun child leaf => OriginalChildBlocks.specialLaw calls rows repeats + (GeometricPath.leafPath leaf) slots child) chosen leaf := by + let : Nonempty (Fin (branch n)) := ⟨chosen⟩ + apply FiniteDistribution.eq_of_weight_eq + intro x + rw [ChildBlockMixture.special_weight, ChildBlockContinuation.continuedSpecial_weight] + +theorem rawMap_law (calls : Nat) (rows repeats : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (hbranch : ∀ k < n + 1, 0 < branch k) : + (sourceLaw calls rows repeats slots hbranch).pushforward (rawMap calls rows repeats slots) = + blockMixture calls rows repeats slots hbranch := by + let : Nonempty (Fin (branch n)) := ⟨⟨0, hbranch n (Nat.lt_succ_self n)⟩⟩ + refine (sigmaLaw_pushforward + (E := Fin (branch n) × Slots branch n) (Γ := Blocks calls rows slots) + (GeometricPath.law (n + 1) hbranch) + (fun leaf => OriginalChildBlocks.sourceLaw calls rows repeats leaf.1 + (GeometricPath.leafPath leaf.2) slots) + (fun leaf tape => OriginalChildBlocks.rawMap calls rows repeats leaf.1 + (GeometricPath.leafPath leaf.2) slots tape)).trans ?_ + simp_rw [OriginalChildBlocks.rawMap_law] + rw [GeometricPath.law_step] + refine (product_mixture (FiniteDistribution.uniform (Fin (branch n))) + (continuationLaw hbranch) + (fun tag : Fin (branch n) × Slots branch n => + ChildBlockMixture.special + (OriginalChildBlocks.specialLaw calls rows repeats (GeometricPath.leafPath tag.2) slots) + tag.1)).trans ?_ + simp_rw [special_as_continued] + exact ChildBlockContinuation.uniform_average + (fun _ : Fin (branch n) => continuationLaw hbranch) + (fun child leaf => OriginalChildBlocks.specialLaw calls rows repeats + (GeometricPath.leafPath leaf) slots child) + +theorem rawMap_eq_mixture [Nonempty (Fin (branch n))] + (calls : Nat) (rows repeats : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (hbranch : ∀ k < n + 1, 0 < branch k) : + (sourceLaw calls rows repeats slots hbranch).pushforward (rawMap calls rows repeats slots) = + ChildBlockMixture.mixture (averagedSpecial calls rows repeats slots hbranch) := + rawMap_law calls rows repeats slots hbranch + +def observed (calls : Nat) (rows repeats : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ω : Tape calls rows repeats slots) : CutChildGrouping.Assembled (C := Fin calls) slots rows := + OriginalChildBlocks.observed calls rows repeats ω.1.1 + (GeometricPath.leafPath ω.1.2) slots ω.2 + +theorem assemble_rawMap (calls : Nat) (rows repeats : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ω : Tape calls rows repeats slots) : + CutChildGrouping.assemble slots rows (rawMap calls rows repeats slots ω) = + observed calls rows repeats slots ω := + OriginalChildBlocks.assemble_rawMap calls rows repeats ω.1.1 + (GeometricPath.leafPath ω.1.2) slots ω.2 + +theorem observed_law (calls : Nat) (rows repeats : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (hbranch : ∀ k < n + 1, 0 < branch k) : + (sourceLaw calls rows repeats slots hbranch).pushforward (observed calls rows repeats slots) = + (blockMixture calls rows repeats slots hbranch).pushforward + (CutChildGrouping.assemble slots rows) := by + rw [← rawMap_law calls rows repeats slots hbranch, FiniteDistribution.pushforward_comp] + congr 1 + funext ω + exact (assemble_rawMap calls rows repeats slots ω).symm + +theorem raw_observed_variation {Γ : Type*} [Fintype Γ] + (calls : Nat) (rows repeats : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (hbranch : ∀ k < n + 1, 0 < branch k) (observe : Blocks calls rows slots → Γ) : + ((sourceLaw calls rows repeats slots hbranch).pushforward + (fun ω => observe (rawMap calls rows repeats slots ω))).totalVariation + ((ChildBlockMixture.reference (Ω := fun child : Fin (branch n) => + ChildBlockCardinality.Raw calls rows (childSlots slots child))).pushforward observe) ≤ + Real.sqrt ((ChildBlockCardinality.bound branch n t calls rows : ℝ) ^ 2 / + branch n) / 2 := by + let : Nonempty (Fin (branch n)) := ⟨⟨0, hbranch n (Nat.lt_succ_self n)⟩⟩ + have hpush : (sourceLaw calls rows repeats slots hbranch).pushforward + (fun ω => observe (rawMap calls rows repeats slots ω)) = + (blockMixture calls rows repeats slots hbranch).pushforward observe := by + rw [← rawMap_law calls rows repeats slots hbranch] + exact (FiniteDistribution.pushforward_comp _ _ _).symm + rw [hpush] + simpa only [blockMixture, Fintype.card_fin] using + (ChildBlockMixture.actual_observed_variation calls rows (fun child => childSlots slots child) + (averagedSpecial calls rows repeats slots hbranch) observe) + +theorem observed_variation {Γ : Type*} [Fintype Γ] + (calls : Nat) (rows repeats : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (hbranch : ∀ k < n + 1, 0 < branch k) + (observe : CutChildGrouping.Assembled (C := Fin calls) slots rows → Γ) : + ((sourceLaw calls rows repeats slots hbranch).pushforward + (fun ω => observe (observed calls rows repeats slots ω))).totalVariation + ((FiniteDistribution.uniform (CutChildGrouping.Assembled (C := Fin calls) slots rows)).pushforward + observe) ≤ + Real.sqrt ((ChildBlockCardinality.bound branch n t calls rows : ℝ) ^ 2 / + branch n) / 2 := by + have hclean : (ChildBlockMixture.reference (Ω := fun child : Fin (branch n) => + ChildBlockCardinality.Raw calls rows (childSlots slots child))).pushforward + (fun x => observe (CutChildGrouping.assemble slots rows x)) = + (FiniteDistribution.uniform (CutChildGrouping.Assembled (C := Fin calls) slots rows)).pushforward + observe := by + rw [← FiniteDistribution.pushforward_comp] + have h := CutChildGrouping.assemble_law (C := Fin calls) slots rows + change (ChildBlockMixture.reference (Ω := fun child : Fin (branch n) => + ChildBlockCardinality.Raw calls rows (childSlots slots child))).pushforward + (CutChildGrouping.assemble slots rows) = _ at h + rw [h] + have h := raw_observed_variation calls rows repeats slots hbranch + (fun x => observe (CutChildGrouping.assemble slots rows x)) + simpa only [assemble_rawMap, hclean] using h + +end +end PerfectCompleteness.OriginalHiddenChild + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/OriginalOwnBucketSplit.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/OriginalOwnBucketSplit.lean new file mode 100644 index 0000000000000000000000000000000000000000..c5de5055758ab4f3b57b80ce2786767d654a62ec --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/OriginalOwnBucketSplit.lean @@ -0,0 +1,509 @@ +import OAI.Computability.PerfectCompleteness.Algebra.HierarchicalMatrixTable +import OAI.Computability.PerfectCompleteness.Construction.OriginalCutBucketReplacement +import OAI.Computability.PerfectCompleteness.Sampling.CutSamplerReplayTransportLemmas +import OAI.Computability.PerfectCompleteness.Sampling.OriginalWholeCutLaw + +namespace OAI + +section + +namespace PerfectCompleteness.OriginalOwnBucketSplit + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays TerminalCalls +open OriginalWholeCut OriginalWholeCutTape +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +noncomputable section + +variable {branch : Nat → Nat} {n m k t : Nat} + +@[instance_reducible] def valuesChildrenFintype (C : Type*) [Fintype C] + (slots : Slots branch (m + 1) → Fin t → MixedSupport.Slot) (rows : Nat → Nat) : + Fintype ((C → H slots) × ChildArrays rows slots) := + @instFintypeProd (C → H slots) (ChildArrays rows slots) inferInstance inferInstance + +attribute [local instance 2000] valuesChildrenFintype + +def OtherIndex (rows repeats : Nat → Nat) : {n m : Nat} → Path branch n m → Type + | _, _, .refl _ => Empty + | n + 1, _, .step i p => + (BucketSampler.Direction (rows (n + 1)) × TerminalIndex repeats (.step i p)) ⊕ + OtherIndex rows repeats p + +instance otherIndexFintype (rows repeats : Nat → Nat) (p : Path branch n m) : + Fintype (OtherIndex rows repeats p) := by + induction p with + | refl m => exact inferInstanceAs (Fintype Empty) + | @step n m i p ih => + letI : Fintype (OtherIndex rows repeats p) := ih + exact inferInstanceAs (Fintype + ((BucketSampler.Direction (rows (n + 1)) × TerminalIndex repeats (.step i p)) ⊕ + OtherIndex rows repeats p)) + +private def sumEmpty (A : Type*) : A ≃ A ⊕ Empty where + toFun := Sum.inl + invFun := Sum.elim id Empty.elim + left_inv _ := rfl + right_inv x := by + cases x with + | inl a => rfl + | inr e => exact Empty.elim e + +private def swapFirstSum (R A O : Type*) : R ⊕ (A ⊕ O) ≃ A ⊕ (R ⊕ O) where + toFun + | .inl r => .inr (.inl r) + | .inr (.inl a) => .inl a + | .inr (.inr o) => .inr (.inr o) + invFun + | .inl a => .inr (.inl a) + | .inr (.inl r) => .inl r + | .inr (.inr o) => .inr (.inr o) + left_inv x := by rcases x with r | (a | o) <;> rfl + right_inv x := by rcases x with a | (r | o) <;> rfl + +def indexEquiv (rows repeats : Nat → Nat) : {n m : Nat} → (p : Path branch n m) → + OriginalCutCalls.Index rows repeats p ≃ + BucketSampler.Direction (rows m) ⊕ OtherIndex rows repeats p + | _, _, .refl _ => sumEmpty _ + | n + 1, _, .step i p => + (Equiv.sumCongr + (Equiv.refl (BucketSampler.Direction (rows (n + 1)) × + TerminalIndex repeats (.step i p))) + (indexEquiv rows repeats p)).trans (swapFirstSum _ _ _) + +@[simp] theorem indexEquiv_ownBucket (rows repeats : Nat → Nat) + (p : Path branch n m) (a : BucketSampler.Direction (rows m)) : + indexEquiv rows repeats p (OriginalCutCalls.ownBucket rows repeats p a) = .inl a := by + revert a + induction p with + | refl m => intro a; rfl + | @step n m i p ih => + intro a + change swapFirstSum _ _ _ + (.inr (indexEquiv rows repeats p (OriginalCutCalls.ownBucket rows repeats p a))) = _ + rw [ih a] + rfl + +@[simp] theorem indexEquiv_symm_inl (rows repeats : Nat → Nat) + (p : Path branch n m) (a : BucketSampler.Direction (rows m)) : + (indexEquiv rows repeats p).symm (.inl a) = + OriginalCutCalls.ownBucket rows repeats p a := by + apply (indexEquiv rows repeats p).injective + rw [Equiv.apply_symm_apply, indexEquiv_ownBucket] + +def otherCall (rows repeats : Nat → Nat) (p : Path branch n m) + (call : OtherIndex rows repeats p) : OriginalCutCalls.Index rows repeats p := + (indexEquiv rows repeats p).symm (.inr call) + +@[simp] theorem indexEquiv_otherCall (rows repeats : Nat → Nat) + (p : Path branch n m) (call : OtherIndex rows repeats p) : + indexEquiv rows repeats p (otherCall rows repeats p call) = .inr call := + (indexEquiv rows repeats p).apply_symm_apply (.inr call) + +theorem otherCall_injective (rows repeats : Nat → Nat) (p : Path branch n m) : + Function.Injective (otherCall rows repeats p) := by + intro a b h + have h' := congrArg (indexEquiv rows repeats p) h + simpa only [indexEquiv_otherCall, Sum.inr.injEq] using h' + +theorem otherCall_ne_ownBucket (rows repeats : Nat → Nat) (p : Path branch n m) + (call : OtherIndex rows repeats p) (a : BucketSampler.Direction (rows m)) : + otherCall rows repeats p call ≠ OriginalCutCalls.ownBucket rows repeats p a := by + intro h + have h' := congrArg (indexEquiv rows repeats p) h + rw [indexEquiv_otherCall, indexEquiv_ownBucket] at h' + cases h' + +def valuesEquiv (rows repeats : Nat → Nat) (p : Path branch n m) (A : Type*) : + (OriginalCutCalls.Index rows repeats p → A) ≃ + (BucketSampler.Direction (rows m) → A) × (OtherIndex rows repeats p → A) := + (Equiv.arrowCongr (indexEquiv rows repeats p) (Equiv.refl A)).trans + (Equiv.sumArrowEquivProdArrow _ _ _) + +@[simp] theorem valuesEquiv_own (rows repeats : Nat → Nat) (p : Path branch n m) + (A : Type*) (values : OriginalCutCalls.Index rows repeats p → A) + (a : BucketSampler.Direction (rows m)) : + (valuesEquiv rows repeats p A values).1 a = + values (OriginalCutCalls.ownBucket rows repeats p a) := by + change values ((indexEquiv rows repeats p).symm (.inl a)) = _ + rw [indexEquiv_symm_inl] + +@[simp] theorem valuesEquiv_other (rows repeats : Nat → Nat) (p : Path branch n m) + (A : Type*) (values : OriginalCutCalls.Index rows repeats p → A) + (call : OtherIndex rows repeats p) : + (valuesEquiv rows repeats p A values).2 call = + values (otherCall rows repeats p call) := rfl + +@[simp] theorem valuesEquiv_symm_own (rows repeats : Nat → Nat) (p : Path branch n m) + (A : Type*) (own : BucketSampler.Direction (rows m) → A) + (other : OtherIndex rows repeats p → A) (a : BucketSampler.Direction (rows m)) : + (valuesEquiv rows repeats p A).symm (own, other) + (OriginalCutCalls.ownBucket rows repeats p a) = own a := by + have h := congrArg (fun z => z.1 a) + ((valuesEquiv rows repeats p A).apply_symm_apply (own, other)) + simpa only [valuesEquiv_own] using h + +@[simp] theorem valuesEquiv_symm_other (rows repeats : Nat → Nat) (p : Path branch n m) + (A : Type*) (own : BucketSampler.Direction (rows m) → A) + (other : OtherIndex rows repeats p → A) (call : OtherIndex rows repeats p) : + (valuesEquiv rows repeats p A).symm (own, other) + (otherCall rows repeats p call) = other call := by + have h := congrArg (fun z => z.2 call) + ((valuesEquiv rows repeats p A).apply_symm_apply (own, other)) + simpa only [valuesEquiv_other] using h + +theorem valuesEquiv_law (rows repeats : Nat → Nat) (p : Path branch n m) + {A : Type*} [Fintype A] (μ : FiniteDistribution A) : + (FiniteProduct.law (fun _ : OriginalCutCalls.Index rows repeats p => μ)).pushforward + (valuesEquiv rows repeats p A) = + (FiniteProduct.law (fun _ : BucketSampler.Direction (rows m) => μ)).product + (FiniteProduct.law (fun _ : OtherIndex rows repeats p => μ)) := by + rw [← FiniteDistribution.transport_eq_pushforward] + apply FiniteDistribution.eq_of_weight_eq + intro z + change (∏ call : OriginalCutCalls.Index rows repeats p, + μ.weight (Sum.elim z.1 z.2 (indexEquiv rows repeats p call))) = + (∏ a : BucketSampler.Direction (rows m), μ.weight (z.1 a)) * + ∏ other : OtherIndex rows repeats p, μ.weight (z.2 other) + rw [(indexEquiv rows repeats p).prod_comp + (fun tag => μ.weight (Sum.elim z.1 z.2 tag)), Fintype.prod_sum_type] + simp only [Sum.elim_inl, Sum.elim_inr] + +abbrev BucketTape (rows : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) := + BucketSampler.Tape (rows (m + 1)) (H (cutSlots p slots)) + +abbrev OtherValues (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) := + OtherIndex rows repeats p → H (cutSlots p slots) + +abbrev Complement (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) := + Exterior rows repeats p slots × (OtherValues rows repeats p slots × BelowArrays rows p slots) + +def recordEquiv (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Record rows repeats p slots ≃ BucketTape rows p slots × Complement rows repeats p slots where + toFun record := + ((valuesEquiv rows repeats p (H (cutSlots p slots)) record.2.1).1, + (record.1, + ((valuesEquiv rows repeats p (H (cutSlots p slots)) record.2.1).2, record.2.2))) + invFun z := + (z.2.1, ((valuesEquiv rows repeats p (H (cutSlots p slots))).symm (z.1, z.2.2.1), + z.2.2.2)) + left_inv record := by + rcases record with ⟨exterior, values, below⟩ + change (exterior, ((valuesEquiv rows repeats p (H (cutSlots p slots))).symm + (valuesEquiv rows repeats p (H (cutSlots p slots)) values), below)) = _ + rw [Equiv.symm_apply_apply] + right_inv z := by + rcases z with ⟨own, exterior, other, below⟩ + change + (((valuesEquiv rows repeats p (H (cutSlots p slots))) + ((valuesEquiv rows repeats p (H (cutSlots p slots))).symm (own, other))).1, + (exterior, + (((valuesEquiv rows repeats p (H (cutSlots p slots))) + ((valuesEquiv rows repeats p (H (cutSlots p slots))).symm (own, other))).2, + below))) = _ + rw [Equiv.apply_symm_apply] + +def assembleRecord (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (own : BucketTape rows p slots) (complement : Complement rows repeats p slots) : + Record rows repeats p slots := + (recordEquiv rows repeats p slots).symm (own, complement) + +@[simp] theorem recordEquiv_own (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : Record rows repeats p slots) (a : BucketSampler.Direction (rows (m + 1))) : + (recordEquiv rows repeats p slots record).1 a = + record.2.1 (OriginalCutCalls.ownBucket rows repeats p a) := + valuesEquiv_own rows repeats p (H (cutSlots p slots)) record.2.1 a + +@[simp] theorem split_assembleRecord (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (own : BucketTape rows p slots) (complement : Complement rows repeats p slots) : + recordEquiv rows repeats p slots (assembleRecord rows repeats p slots own complement) = + (own, complement) := + (recordEquiv rows repeats p slots).apply_symm_apply (own, complement) + +@[simp] theorem assembleRecord_split (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : Record rows repeats p slots) : + assembleRecord rows repeats p slots (recordEquiv rows repeats p slots record).1 + (recordEquiv rows repeats p slots record).2 = record := + (recordEquiv rows repeats p slots).symm_apply_apply record + +@[simp] theorem assembleRecord_exterior (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (own : BucketTape rows p slots) (complement : Complement rows repeats p slots) : + (assembleRecord rows repeats p slots own complement).1 = complement.1 := rfl + +@[simp] theorem assembleRecord_below (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (own : BucketTape rows p slots) (complement : Complement rows repeats p slots) : + (assembleRecord rows repeats p slots own complement).2.2 = complement.2.2 := rfl + +@[simp] theorem assembleRecord_own (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (own : BucketTape rows p slots) (complement : Complement rows repeats p slots) + (a : BucketSampler.Direction (rows (m + 1))) : + (assembleRecord rows repeats p slots own complement).2.1 + (OriginalCutCalls.ownBucket rows repeats p a) = own a := + valuesEquiv_symm_own rows repeats p (H (cutSlots p slots)) own complement.2.1 a + +@[simp] theorem assembleRecord_other (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (own : BucketTape rows p slots) (complement : Complement rows repeats p slots) + (call : OtherIndex rows repeats p) : + (assembleRecord rows repeats p slots own complement).2.1 (otherCall rows repeats p call) = + complement.2.1 call := + valuesEquiv_symm_other rows repeats p (H (cutSlots p slots)) own complement.2.1 call + +theorem assembleRecord_nonown_eq (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (own₁ own₂ : BucketTape rows p slots) (complement : Complement rows repeats p slots) + (call : OriginalCutCalls.Index rows repeats p) + (hcall : ∀ a, call ≠ OriginalCutCalls.ownBucket rows repeats p a) : + (assembleRecord rows repeats p slots own₁ complement).2.1 call = + (assembleRecord rows repeats p slots own₂ complement).2.1 call := by + cases he : indexEquiv rows repeats p call with + | inl a => + exfalso + apply hcall a + apply (indexEquiv rows repeats p).injective + rw [indexEquiv_ownBucket] + exact he + | inr other => + have hc : call = otherCall rows repeats p other := by + apply (indexEquiv rows repeats p).injective + rw [indexEquiv_otherCall] + exact he + rw [hc, assembleRecord_other, assembleRecord_other] + +def complementLaw (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (scalar : FiniteDistribution (H (cutSlots p slots))) + (exterior : FiniteDistribution (Exterior rows repeats p slots)) + (below : FiniteDistribution (BelowArrays rows p slots)) : + FiniteDistribution (Complement rows repeats p slots) := + exterior.product ((FiniteProduct.law + (fun _ : OtherIndex rows repeats p => scalar)).product below) + +theorem independent_record_split (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (scalar : FiniteDistribution (H (cutSlots p slots))) + (exterior : FiniteDistribution (Exterior rows repeats p slots)) + (below : FiniteDistribution (BelowArrays rows p slots)) : + (exterior.product ((FiniteProduct.law + (fun _ : OriginalCutCalls.Index rows repeats p => scalar)).product below)).pushforward + (recordEquiv rows repeats p slots) = + (BucketSampler.tapeLaw (rows (m + 1)) scalar).product + (complementLaw rows repeats p slots scalar exterior below) := by + rw [← FiniteDistribution.transport_eq_pushforward] + apply FiniteDistribution.eq_of_weight_eq + intro z + change exterior.weight z.2.1 * + ((∏ call : OriginalCutCalls.Index rows repeats p, + scalar.weight (Sum.elim z.1 z.2.2.1 (indexEquiv rows repeats p call))) * + below.weight z.2.2.2) = + (∏ a : BucketSampler.Direction (rows (m + 1)), scalar.weight (z.1 a)) * + (exterior.weight z.2.1 * + ((∏ other : OtherIndex rows repeats p, scalar.weight (z.2.2.1 other)) * + below.weight z.2.2.2)) + rw [(indexEquiv rows repeats p).prod_comp + (fun tag => scalar.weight (Sum.elim z.1 z.2.2.1 tag)), Fintype.prod_sum_type] + simp only [Sum.elim_inl, Sum.elim_inr] + ring + +def actualComplementLaw (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (chosen : Fin (branch m)) (q : Path branch m k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + FiniteDistribution (Complement rows repeats p slots) := + complementLaw rows repeats p slots + (RecursiveSampler.law F2 repeats (.step chosen q) (LeafDomain (cutSlots p slots))) + (exteriorLaw rows repeats p slots) + (OriginalWholeCutLaw.belowArraysLaw rows repeats chosen q (cutSlots p slots)) + +theorem recordLaw_split (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (chosen : Fin (branch m)) (q : Path branch m k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + (OriginalWholeCutLaw.recordLaw rows repeats p chosen q slots).pushforward + (recordEquiv rows repeats p slots) = + (BucketSampler.tapeLaw (rows (m + 1)) + (RecursiveSampler.law F2 repeats (.step chosen q) (LeafDomain (cutSlots p slots)))).product + (actualComplementLaw rows repeats p chosen q slots) := + independent_record_split rows repeats p slots + (RecursiveSampler.law F2 repeats (.step chosen q) (LeafDomain (cutSlots p slots))) + (exteriorLaw rows repeats p slots) + (OriginalWholeCutLaw.belowArraysLaw rows repeats chosen q (cutSlots p slots)) + +theorem uniform_record_split (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) : + (FiniteDistribution.uniform (Record rows repeats p slots)).pushforward + (recordEquiv rows repeats p slots) = + (FiniteDistribution.uniform (BucketTape rows p slots)).product + (FiniteDistribution.uniform (Complement rows repeats p slots)) := by + rw [← FiniteDistribution.transport_eq_pushforward, + UniformConditioning.uniform_transport, WholeCutSampler.uniform_product] + +theorem uniform_record_split_bucketLaw (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) : + (FiniteDistribution.uniform (Record rows repeats p slots)).pushforward + (recordEquiv rows repeats p slots) = + (BucketSampler.tapeLaw (rows (m + 1)) + (FiniteDistribution.uniform (H (cutSlots p slots)))).product + (FiniteDistribution.uniform (Complement rows repeats p slots)) := by + rw [BucketSampler.tapeLaw, UniformLinearImage.law_uniform] + exact uniform_record_split rows repeats p slots + +theorem uniform_assembleRecord (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) : + ((FiniteDistribution.uniform (BucketTape rows p slots)).product + (FiniteDistribution.uniform (Complement rows repeats p slots))).pushforward + (fun z => assembleRecord rows repeats p slots z.1 z.2) = + FiniteDistribution.uniform (Record rows repeats p slots) := by + rw [WholeCutSampler.uniform_product] + change (FiniteDistribution.uniform + (BucketTape rows p slots × Complement rows repeats p slots)).pushforward + (recordEquiv rows repeats p slots).symm = _ + rw [← FiniteDistribution.transport_eq_pushforward] + exact UniformConditioning.uniform_transport (recordEquiv rows repeats p slots).symm + +def zeroOwnReconstruction (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (complement : Complement rows repeats p slots) : Arrays slots rows := + reconstructRecord rows repeats p slots (assembleRecord rows repeats p slots 0 complement) + +theorem reconstruct_assembleRecord_outside (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (own₁ own₂ : BucketTape rows p slots) (complement : Complement rows repeats p slots) + (node : Nodes branch n) (hnode : node ≠ WholeArrayInteriorExterior.upperNode p) : + reconstructRecord rows repeats p slots (assembleRecord rows repeats p slots own₁ complement) + node = + reconstructRecord rows repeats p slots (assembleRecord rows repeats p slots own₂ complement) + node := by + change reconstruct rows repeats p slots complement.1 + (assembleRecord rows repeats p slots own₁ complement).2.1 complement.2.2 node = + reconstruct rows repeats p slots complement.1 + (assembleRecord rows repeats p slots own₂ complement).2.1 complement.2.2 node + exact OriginalCutBucketReplacement.reconstruct_outside_eq_of_nonown_eq rows repeats p slots + complement.1 _ _ complement.2.2 + (assembleRecord_nonown_eq rows repeats p slots own₁ own₂ complement) node hnode + +def background (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (complement : Complement rows repeats p slots) : + HierarchicalMatrixTable.Background (rows := rows) slots (WholeArrayInteriorExterior.upperNode p) := + HierarchicalMatrixTable.backgroundOf slots (WholeArrayInteriorExterior.upperNode p) + (zeroOwnReconstruction rows repeats p slots complement) + +theorem background_assembleRecord (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (own : BucketTape rows p slots) (complement : Complement rows repeats p slots) : + HierarchicalMatrixTable.backgroundOf slots (WholeArrayInteriorExterior.upperNode p) + (reconstructRecord rows repeats p slots (assembleRecord rows repeats p slots own complement)) = + background rows repeats p slots complement := by + funext node + exact reconstruct_assembleRecord_outside rows repeats p slots own 0 complement node.val node.property + +theorem background_record (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : Record rows repeats p slots) : + HierarchicalMatrixTable.backgroundOf slots (WholeArrayInteriorExterior.upperNode p) + (reconstructRecord rows repeats p slots record) = + background rows repeats p slots (recordEquiv rows repeats p slots record).2 := by + have h := background_assembleRecord rows repeats p slots + (recordEquiv rows repeats p slots record).1 (recordEquiv rows repeats p slots record).2 + rw [assembleRecord_split] at h + exact h + +local instance backgroundFintype (rows : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Fintype (HierarchicalMatrixTable.Background (rows := rows) slots + (WholeArrayInteriorExterior.upperNode p)) := Fintype.ofFinite _ + +def backgroundLaw (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + FiniteDistribution (HierarchicalMatrixTable.Background (rows := rows) slots + (WholeArrayInteriorExterior.upperNode p)) := + (FiniteDistribution.uniform (Complement rows repeats p slots)).pushforward + (background rows repeats p slots) + +def actualBackgroundLaw (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (chosen : Fin (branch m)) (q : Path branch m k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + FiniteDistribution (HierarchicalMatrixTable.Background (rows := rows) slots + (WholeArrayInteriorExterior.upperNode p)) := + (actualComplementLaw rows repeats p chosen q slots).pushforward + (background rows repeats p slots) + +theorem recordLaw_own_background (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) (chosen : Fin (branch m)) (q : Path branch m k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + (OriginalWholeCutLaw.recordLaw rows repeats p chosen q slots).pushforward + (fun record => + ((recordEquiv rows repeats p slots record).1, + HierarchicalMatrixTable.backgroundOf slots (WholeArrayInteriorExterior.upperNode p) + (reconstructRecord rows repeats p slots record))) = + (BucketSampler.tapeLaw (rows (m + 1)) + (RecursiveSampler.law F2 repeats (.step chosen q) (LeafDomain (cutSlots p slots)))).product + (actualBackgroundLaw rows repeats p chosen q slots) := by + calc + _ = ((OriginalWholeCutLaw.recordLaw rows repeats p chosen q slots).pushforward + (recordEquiv rows repeats p slots)).pushforward + (fun z => (z.1, background rows repeats p slots z.2)) := by + rw [FiniteDistribution.pushforward_comp] + apply congrArg (OriginalWholeCutLaw.recordLaw rows repeats p chosen q slots).pushforward + funext record + exact Prod.ext rfl (background_record rows repeats p slots record) + _ = ((BucketSampler.tapeLaw (rows (m + 1)) + (RecursiveSampler.law F2 repeats (.step chosen q) (LeafDomain (cutSlots p slots)))).product + (actualComplementLaw rows repeats p chosen q slots)).pushforward + (fun z => (z.1, background rows repeats p slots z.2)) := by + rw [recordLaw_split] + _ = _ := by + simpa only [id_eq, FiniteDistribution.pushforward_id, actualBackgroundLaw] using + (FiniteDistribution.product_pushforward + (BucketSampler.tapeLaw (rows (m + 1)) + (RecursiveSampler.law F2 repeats (.step chosen q) (LeafDomain (cutSlots p slots)))) + (actualComplementLaw rows repeats p chosen q slots) + (id : BucketTape rows p slots → BucketTape rows p slots) + (background rows repeats p slots)) + +theorem uniform_own_background (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) : + (FiniteDistribution.uniform (Record rows repeats p slots)).pushforward + (fun record => + ((recordEquiv rows repeats p slots record).1, + HierarchicalMatrixTable.backgroundOf slots (WholeArrayInteriorExterior.upperNode p) + (reconstructRecord rows repeats p slots record))) = + (FiniteDistribution.uniform (BucketTape rows p slots)).product + (backgroundLaw rows repeats p slots) := by + calc + _ = ((FiniteDistribution.uniform (Record rows repeats p slots)).pushforward + (recordEquiv rows repeats p slots)).pushforward + (fun z => (z.1, background rows repeats p slots z.2)) := by + rw [FiniteDistribution.pushforward_comp] + apply congrArg ((FiniteDistribution.uniform (Record rows repeats p slots)).pushforward) + funext record + exact Prod.ext rfl (background_record rows repeats p slots record) + _ = ((FiniteDistribution.uniform (BucketTape rows p slots)).product + (FiniteDistribution.uniform (Complement rows repeats p slots))).pushforward + (fun z => (z.1, background rows repeats p slots z.2)) := by + rw [uniform_record_split] + _ = _ := by + simpa only [id_eq, FiniteDistribution.pushforward_id, backgroundLaw] using + (FiniteDistribution.product_pushforward + (FiniteDistribution.uniform (BucketTape rows p slots)) + (FiniteDistribution.uniform (Complement rows repeats p slots)) + (id : BucketTape rows p slots → BucketTape rows p slots) + (background rows repeats p slots)) + +end +end PerfectCompleteness.OriginalOwnBucketSplit + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/OwnBucketBias.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/OwnBucketBias.lean new file mode 100644 index 0000000000000000000000000000000000000000..a9df7eb515817167c97daff5bc47c4f87279bca7 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/OwnBucketBias.lean @@ -0,0 +1,55 @@ +import OAI.Computability.PerfectCompleteness.Construction.HiddenBucketBias +import OAI.Computability.PerfectCompleteness.Construction.TreeSourceSpaces +import OAI.Computability.PerfectCompleteness.Sampling.UniformLatentSupportLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.OwnBucketBias + +open RecursiveSpaces DescendantSpaces HiddenBucketBias +open UniqueGamesTheorem.Foundations.Games +open scoped TensorProduct + +noncomputable section + +universe u +variable {branch : Nat → Nat} {n m width : Nat} + +theorem bias_le (W : Submodule F2 (Fin width → F2)) + (repeats : Nat → Nat) (hrep : RecursiveSamplerBias.RepetitionsBalanced repeats) + (p : Path branch n m) (A : Slots branch n → Type u) + [∀ s, Finite (A s)] [Fintype (space F2 branch n A)] + (Φ : Module.Dual F2 (W ⊗[F2] space F2 branch n A)) (hΦ : Φ ≠ 0) : + |(recursiveLaw W repeats p A).expectation (fun x => QuarterBalance.sign (Φ x))| ≤ + (7 / 8 : ℝ) ^ repeats n := by + apply recursive_law_sign_bias_le W repeats p A _ ?_ Φ hΦ + intro f hf + exact RecursiveSamplerBias.law_bias_le_height repeats hrep p A f hf + +theorem bias_le_of_six_le (W : Submodule F2 (Fin width → F2)) + (repeats : Nat → Nat) (hrep : ∀ k, 6 ≤ repeats (k + 1)) + (p : Path branch n m) (A : Slots branch n → Type u) + [∀ s, Finite (A s)] [Fintype (space F2 branch n A)] + (Φ : Module.Dual F2 (W ⊗[F2] space F2 branch n A)) (hΦ : Φ ≠ 0) : + |(recursiveLaw W repeats p A).expectation (fun x => QuarterBalance.sign (Φ x))| ≤ + (7 / 8 : ℝ) ^ repeats n := + bias_le W repeats (RecursiveSamplerBias.repetitionsBalanced_of_six_le repeats hrep) p A Φ hΦ + +theorem mixed_bias_le {t : Nat} (W : Submodule F2 (Fin width → F2)) + (repeats : Nat → Nat) (hrep : RecursiveSamplerBias.RepetitionsBalanced repeats) + (p : Path branch n m) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (Φ : Module.Dual F2 (W ⊗[F2] TreeSourceSpaces.H slots)) (hΦ : Φ ≠ 0) : + |(recursiveLaw W repeats p (TreeSourceSpaces.LeafDomain slots)).expectation + (fun x => QuarterBalance.sign (Φ x))| ≤ (7 / 8 : ℝ) ^ repeats n := by + let : Fintype (TreeSourceSpaces.H slots) := Fintype.ofFinite _ + exact bias_le W repeats hrep p (TreeSourceSpaces.LeafDomain slots) Φ hΦ + +end +end PerfectCompleteness.OwnBucketBias + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/ProjectedNodeEmbedding.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/ProjectedNodeEmbedding.lean new file mode 100644 index 0000000000000000000000000000000000000000..77bcd6e9b4b27f5928d2893d3514f8c20845c7a7 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/ProjectedNodeEmbedding.lean @@ -0,0 +1,132 @@ +import OAI.Computability.PerfectCompleteness.Construction.NodeEmbedding +import OAI.Computability.PerfectCompleteness.Decoding.DecoderSourcePullback + +namespace OAI + +section + +namespace PerfectCompleteness.ProjectedNodeEmbedding + +noncomputable section + +open RecursiveSpaces TreeSourceSpaces HierarchicalArrays +open ChildBlockProjection (nodeProjection squarePullback) + +variable {branch : Nat → Nat} {n t : Nat} + {slots projected : Slots branch n → Fin t → MixedSupport.Slot} + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (upper : Nodes branch n) + +def nativePullback : + NodeEmbedding.NodeH projected upper →ₗ[F2] NodeEmbedding.NodeH slots upper := + HPullback (nodeProjection p upper) + +@[simp] theorem nativePullback_apply + (f : NodeEmbedding.NodeH projected upper) (x : Domain (nodeSlots slots upper)) : + (nativePullback p upper f).val x = + f.val (sourceProjection (nodeProjection p upper) x) := rfl + +theorem nativePullback_injective : Function.Injective (nativePullback p upper) := + HPullback_injective (nodeProjection p upper) + +def intoOriginal : + NodeEmbedding.NodeH projected upper →ₗ[F2] NodeEmbedding.RowSpace slots upper := + (NodeEmbedding.embed slots upper).comp (nativePullback p upper) + +theorem intoOriginal_injective : Function.Injective (intoOriginal p upper) := + (NodeEmbedding.embed_injective slots upper).comp (nativePullback_injective p upper) + +@[simp] theorem intoOriginal_apply + (f : NodeEmbedding.NodeH projected upper) (x : NodeEmbedding.NumberedDomain slots) : + (intoOriginal p upper f).val x = + f.val (sourceProjection (nodeProjection p upper) + (NodeEmbedding.numberedRestriction slots upper x)) := rfl + +theorem numberedRestriction_projection (x : NodeEmbedding.NumberedDomain slots) : + sourceProjection (nodeProjection p upper) (NodeEmbedding.numberedRestriction slots upper x) = + NodeEmbedding.numberedRestriction projected upper + (MixedSupport.projectionMap (TreeCanonical.numberedProjection p) x) := by + change restrictNode projected upper + (sourceProjection p ((TreeCanonical.assignmentEquiv slots).symm x)) = _ + exact congrArg (restrictNode projected upper) + (TreeCanonical.assignmentEquiv_symm_projection p x) + +theorem intoOriginal_apply_projected + (f : NodeEmbedding.NodeH projected upper) (x : NodeEmbedding.NumberedDomain slots) : + (intoOriginal p upper f).val x = + (NodeEmbedding.embed projected upper f).val + (MixedSupport.projectionMap (TreeCanonical.numberedProjection p) x) := by + exact congrArg f.val (numberedRestriction_projection p upper x) + +theorem intoOriginal_val (f : NodeEmbedding.NodeH projected upper) : + (intoOriginal p upper f).val = + PointwiseSpaces.pullback F2 + (MixedSupport.projectionMap (TreeCanonical.numberedProjection p)) + (NodeEmbedding.embed projected upper f).val := by + funext x + exact intoOriginal_apply_projected p upper f x + +theorem intoOriginal_at_assignment + (f : NodeEmbedding.NodeH projected upper) (x : Domain slots) : + (intoOriginal p upper f).val (TreeCanonical.assignmentEquiv slots x) = + f.val (restrictNode projected upper (sourceProjection p x)) := by + change f.val (sourceProjection (nodeProjection p upper) + (restrictNode slots upper ((TreeCanonical.assignmentEquiv slots).symm + (TreeCanonical.assignmentEquiv slots x)))) = _ + rw [Equiv.symm_apply_apply] + rfl + +theorem dualMap_eq_upperTarget + (q : Module.Dual F2 (NodeEmbedding.RowSpace slots upper)) : + (intoOriginal p upper).dualMap q = DecoderSourcePullback.upperTarget p upper q := by + apply LinearMap.ext + intro f + rfl + +theorem evaluation_dualMap (x : NodeEmbedding.NumberedDomain slots) : + (intoOriginal p upper).dualMap + (EvaluationMatrix.evaluation (NodeEmbedding.RowSpace slots upper) x) = + EvaluationMatrix.evaluation (NodeEmbedding.NodeH projected upper) + (NodeEmbedding.numberedRestriction projected upper + (MixedSupport.projectionMap (TreeCanonical.numberedProjection p) x)) := by + apply LinearMap.ext + intro f + exact congrArg f.val (numberedRestriction_projection p upper x) + +theorem intoOriginal_mul (f g : NodeEmbedding.NodeH projected upper) : + (intoOriginal p upper f).val * (intoOriginal p upper g).val = + PointwiseSpaces.pullback F2 + (sourceProjection (nodeProjection p upper) ∘ NodeEmbedding.numberedRestriction slots upper) + (f.val * g.val) := rfl + +def intoOriginalSquare : + PointwiseSpaces.squareSpace (NodeEmbedding.NodeH projected upper) →ₗ[F2] + PointwiseSpaces.squareSpace (NodeEmbedding.RowSpace slots upper) where + toFun f := ⟨PointwiseSpaces.pullback F2 (NodeEmbedding.numberedRestriction slots upper) + (squarePullback (nodeProjection p upper) f).val, by + rw [NodeEmbedding.squareSpace_eq] + exact Submodule.mem_map_of_mem (squarePullback (nodeProjection p upper) f).property⟩ + map_add' f g := by apply Subtype.ext; rfl + map_smul' c f := by apply Subtype.ext; rfl + +@[simp] theorem intoOriginalSquare_apply + (f : PointwiseSpaces.squareSpace (NodeEmbedding.NodeH projected upper)) + (x : NodeEmbedding.NumberedDomain slots) : + (intoOriginalSquare p upper f).val x = + f.val (sourceProjection (nodeProjection p upper) + (NodeEmbedding.numberedRestriction slots upper x)) := rfl + +theorem intoOriginalSquare_product (f g : NodeEmbedding.NodeH projected upper) : + intoOriginalSquare p upper + (OddListExtraction.productElement (NodeEmbedding.NodeH projected upper) f g) = + OddListExtraction.productElement (NodeEmbedding.RowSpace slots upper) + (intoOriginal p upper f) (intoOriginal p upper g) := by + apply Subtype.ext + rfl + +end +end PerfectCompleteness.ProjectedNodeEmbedding + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/RelativeDescendantProductsLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/RelativeDescendantProductsLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..0120f879981f5b96045b4e6109edc60eea1a288d --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/RelativeDescendantProductsLemmas.lean @@ -0,0 +1,289 @@ +import OAI.Computability.PerfectCompleteness.Construction.DescendantSpacesLemmas +import OAI.Computability.PerfectCompleteness.Foundations.GeometricPathLemmas + +namespace OAI + + +namespace PerfectCompleteness.RelativeDescendantProducts + +open TreeSourceSpaces HierarchicalArrays + +variable {branch : Nat → Nat} {n t : Nat} + +inductive Below (branch : Nat → Nat) : + {n : Nat} → Nodes branch n → Nodes branch n → Prop + | root {n : Nat} (i : Fin (branch n)) (lower : Nodes branch n) : + Below branch (n := n + 1) (.inl ()) (.inr (i, lower)) + | child {n : Nat} {upper lower : Nodes branch n} (i : Fin (branch n)) : + Below branch upper lower → + Below branch (n := n + 1) (.inr (i, upper)) (.inr (i, lower)) + +theorem Below.height_lt {upper lower : Nodes branch n} + (h : Below branch upper lower) : Nodes.height lower < Nodes.height upper := by + induction h with + | root i lower => exact Nat.lt_succ_of_le (Nodes.height_le lower) + | child i h ih => exact ih + +theorem Below.ne {upper lower : Nodes branch n} + (h : Below branch upper lower) : lower ≠ upper := by + intro heq + have hlt := h.height_lt + rw [heq] at hlt + exact Nat.lt_irrefl _ hlt + +def relativeNode : {n : Nat} → (upper : Nodes branch n) → + Nodes branch (Nodes.height upper) → Nodes branch n + | 0, upper, _ => nomatch upper + | _ + 1, .inl _, lower => lower + | _ + 1, .inr (i, upper), lower => .inr (i, relativeNode upper lower) + +theorem relativeNode_height : ∀ {n : Nat} (upper : Nodes branch n) + (lower : Nodes branch (Nodes.height upper)), + Nodes.height (relativeNode upper lower) = Nodes.height lower := by + intro n + induction n with + | zero => intro upper; exact nomatch upper + | succ n ih => + intro upper lower + cases upper with + | inl _ => rfl + | inr pair => exact ih pair.2 lower + +theorem relativeNode_injective : ∀ {n : Nat} (upper : Nodes branch n), + Function.Injective (relativeNode upper) := by + intro n + induction n with + | zero => intro upper; exact nomatch upper + | succ n ih => + intro upper + cases upper with + | inl _ => exact fun _ _ h => h + | inr pair => + intro x y h + exact ih pair.2 (congrArg Prod.snd (Sum.inr.inj h)) + +theorem relativeNode_below : ∀ {n : Nat} (upper : Nodes branch n) + (lower : Nodes branch (Nodes.height upper)), + Nodes.height lower < Nodes.height upper → + Below branch upper (relativeNode upper lower) := by + intro n + induction n with + | zero => intro upper; exact nomatch upper + | succ n ih => + intro upper lower hproper + cases upper with + | inl u => + cases u + cases lower with + | inl _ => exact False.elim (Nat.lt_irrefl _ hproper) + | inr pair => exact Below.root pair.1 pair.2 + | inr pair => exact Below.child pair.1 (ih pair.2 lower hproper) + +abbrev RelativeDescendant (upper : Nodes branch n) := + {lower : Nodes branch (Nodes.height upper) // Nodes.height lower < Nodes.height upper} + +def descendantIndex (upper : Nodes branch n) (lower : RelativeDescendant upper) : + {j : Nodes branch n // j ≠ upper} := + ⟨relativeNode upper lower.val, (relativeNode_below upper lower.val lower.property).ne⟩ + +theorem descendantIndex_below (upper : Nodes branch n) + (lower : RelativeDescendant upper) : + Below branch upper (descendantIndex upper lower).val := + relativeNode_below upper lower.val lower.property + +theorem descendantIndex_injective (upper : Nodes branch n) : + Function.Injective (descendantIndex upper) := by + intro x y h + apply Subtype.ext + exact relativeNode_injective upper + (congrArg (fun z : {j : Nodes branch n // j ≠ upper} => z.val) h) + +theorem pullback_square_exists {upper lower : Nodes branch n} + (h : Below branch upper lower) : + ∀ (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (_ : ∀ k < n, 0 < branch k) + (f : Domain (nodeSlots slots lower) → F2), + f ∈ PointwiseSpaces.squareSpace (NodeEmbedding.NodeH slots lower) → + ∃ g ∈ NodeEmbedding.NodeH slots upper, + PointwiseSpaces.pullback F2 (restrictNode slots upper) g = + PointwiseSpaces.pullback F2 (restrictNode slots lower) f := by + induction h with + | @root n i lower => + intro slots hbranch f hf + refine ⟨PointwiseSpaces.pullback F2 (restrictNode slots (.inr (i, lower))) f, ?_, rfl⟩ + exact DescendantSpaces.descendant_square_le_space + (.step i (Nodes.path lower)) (LeafDomain slots) hbranch + (Nat.lt_succ_of_le (Nodes.height_le lower)) (Submodule.mem_map_of_mem hf) + | @child n upper lower i h ih => + intro slots hbranch f hf + let childSlots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot := + fun s => slots (i, s) + have hb : ∀ k < n, 0 < branch k := + fun k hk => hbranch k (Nat.lt_trans hk (Nat.lt_succ_self n)) + obtain ⟨g, hg, heq⟩ := ih childSlots hb f hf + refine ⟨g, hg, ?_⟩ + exact congrArg + (PointwiseSpaces.pullback F2 (RecursiveSpaces.childRestriction (LeafDomain slots) i)) heq + +noncomputable section + +theorem squareSpace_le_rowSpace + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (hbranch : ∀ k < n, 0 < branch k) {upper lower : Nodes branch n} + (h : Below branch upper lower) : + PointwiseSpaces.squareSpace (NodeEmbedding.RowSpace slots lower) ≤ + NodeEmbedding.RowSpace slots upper := by + rw [NodeEmbedding.squareSpace_eq] + intro f hf + obtain ⟨g, hg, rfl⟩ := Submodule.mem_map.mp hf + obtain ⟨u, hu, heq⟩ := pullback_square_exists h slots hbranch g hg + refine Submodule.mem_map.mpr ⟨u, hu, ?_⟩ + funext x + exact congrFun heq ((TreeCanonical.assignmentEquiv slots).symm x) + +theorem one_mem_rowSpace + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (hbranch : ∀ k < n, 0 < branch k) (upper : Nodes branch n) : + (1 : NodeEmbedding.NumberedDomain slots → F2) ∈ NodeEmbedding.RowSpace slots upper := by + have hb : ∀ k < Nodes.height upper, 0 < branch k := + fun k hk => hbranch k (Nat.lt_of_lt_of_le hk (Nodes.height_le upper)) + exact Submodule.mem_map_of_mem (TreeSourceSpaces.one_mem_H (nodeSlots slots upper) hb) + +variable {rows : Nat → Nat} {D : Type*} + +theorem knownSpace_le_rowSpace + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (hbranch : ∀ k < n, 0 < branch k) (upper : Nodes branch n) + (background : HierarchicalMatrixTable.Background (rows := rows) slots upper) + (descendant : D → {j : Nodes branch n // j ≠ upper}) + (hbelow : ∀ d, Below branch upper (descendant d).val) : + HierarchicalKnownRows.knownSpace slots upper background descendant ≤ + NodeEmbedding.RowSpace slots upper := by + apply Submodule.span_le.mpr + intro f hf + rcases hf with rfl | ⟨d, i, j, rfl⟩ + · exact one_mem_rowSpace slots hbranch upper + · have hi : PointwiseSpaces.pullback F2 + (NodeEmbedding.numberedRestriction slots (descendant d).val) + (background (descendant d) i).val ∈ NodeEmbedding.RowSpace slots (descendant d).val := + Submodule.mem_map_of_mem (background (descendant d) i).property + have hj : PointwiseSpaces.pullback F2 + (NodeEmbedding.numberedRestriction slots (descendant d).val) + (background (descendant d) j).val ∈ NodeEmbedding.RowSpace slots (descendant d).val := + Submodule.mem_map_of_mem (background (descendant d) j).property + exact squareSpace_le_rowSpace slots hbranch (hbelow d) + (PointwiseSpaces.mul_mem_squareSpace _ hi hj) + +theorem relative_knownSpace_le_rowSpace + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (hbranch : ∀ k < n, 0 < branch k) (upper : Nodes branch n) + (background : HierarchicalMatrixTable.Background (rows := rows) slots upper) + (descendant : D → RelativeDescendant upper) : + HierarchicalKnownRows.knownSpace slots upper background + (fun d => descendantIndex upper (descendant d)) ≤ + NodeEmbedding.RowSpace slots upper := + knownSpace_le_rowSpace slots hbranch upper background + (fun d => descendantIndex upper (descendant d)) + (fun d => descendantIndex_below upper (descendant d)) + +end +end PerfectCompleteness.RelativeDescendantProducts + + + +namespace PerfectCompleteness.GeometricDescendants + +open TreeSourceSpaces HierarchicalArrays RelativeDescendantProducts + +variable {branch : Nat → Nat} + +theorem below_nodeAtLevel : ∀ {n : Nat} (leaf : RecursiveSpaces.Slots branch n) + (upper lower : Fin n), lower < upper → + Below branch (GeometricPath.nodeAtLevel leaf upper) + (GeometricPath.nodeAtLevel leaf lower) := by + intro n + induction n with + | zero => intro leaf upper; exact Fin.elim0 upper + | succ n ih => + intro leaf upper + refine Fin.lastCases ?_ (fun upper' => ?_) upper + · intro lower + refine Fin.lastCases ?_ (fun lower' => ?_) lower + · intro h + exact False.elim (lt_irrefl _ h) + · intro _ + simpa only [GeometricPath.nodeAtLevel_last, GeometricPath.nodeAtLevel_castSucc] using + (Below.root leaf.1 (GeometricPath.nodeAtLevel leaf.2 lower')) + · intro lower + refine Fin.lastCases ?_ (fun lower' => ?_) lower + · intro h + exact False.elim ((not_lt_of_ge (Fin.le_last upper'.castSucc)) h) + · intro h + simpa only [GeometricPath.nodeAtLevel_castSucc] using + (Below.child leaf.1 (ih leaf.2 upper' lower' h)) + +variable {n t : Nat} + +def lowerLevel (upper : Fin n) (lower : Fin upper.val) : Fin n := + ⟨lower.val, Nat.lt_trans lower.isLt upper.isLt⟩ + +theorem lowerLevel_lt (upper : Fin n) (lower : Fin upper.val) : + lowerLevel upper lower < upper := lower.isLt + +theorem lowerLevel_injective (upper : Fin n) : Function.Injective (lowerLevel upper) := by + intro i j h + apply Fin.ext + exact congrArg (fun z : Fin n => z.val) h + +def pathDescendant (leaf : RecursiveSpaces.Slots branch n) (upper : Fin n) + (lower : Fin upper.val) : + {j : Nodes branch n // j ≠ GeometricPath.nodeAtLevel leaf upper} := + ⟨GeometricPath.nodeAtLevel leaf (lowerLevel upper lower), + (below_nodeAtLevel leaf upper (lowerLevel upper lower) (lowerLevel_lt upper lower)).ne⟩ + +theorem pathDescendant_below (leaf : RecursiveSpaces.Slots branch n) (upper : Fin n) + (lower : Fin upper.val) : + Below branch (GeometricPath.nodeAtLevel leaf upper) (pathDescendant leaf upper lower).val := + below_nodeAtLevel leaf upper (lowerLevel upper lower) (lowerLevel_lt upper lower) + +theorem pathDescendant_injective (leaf : RecursiveSpaces.Slots branch n) (upper : Fin n) : + Function.Injective (pathDescendant leaf upper) := by + intro i j h + apply lowerLevel_injective upper + apply GeometricPath.nodeAtLevel_injective leaf + exact congrArg + (fun z : {j : Nodes branch n // j ≠ GeometricPath.nodeAtLevel leaf upper} => z.val) h + +noncomputable section + +variable {rows : Nat → Nat} + +theorem knownSpace_le_rowSpace + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (hbranch : ∀ k < n, 0 < branch k) (leaf : RecursiveSpaces.Slots branch n) + (upper : Fin n) + (background : HierarchicalMatrixTable.Background (rows := rows) slots + (GeometricPath.nodeAtLevel leaf upper)) : + HierarchicalKnownRows.knownSpace slots (GeometricPath.nodeAtLevel leaf upper) background + (pathDescendant leaf upper) ≤ + NodeEmbedding.RowSpace slots (GeometricPath.nodeAtLevel leaf upper) := + RelativeDescendantProducts.knownSpace_le_rowSpace slots hbranch + (GeometricPath.nodeAtLevel leaf upper) background (pathDescendant leaf upper) + (pathDescendant_below leaf upper) + +theorem knownSpace_le_factoringSpace + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (leaf : RecursiveSpaces.Slots branch n) (upper : Fin n) + (background : HierarchicalMatrixTable.Background (rows := rows) slots + (GeometricPath.nodeAtLevel leaf upper)) : + HierarchicalKnownRows.knownSpace slots (GeometricPath.nodeAtLevel leaf upper) background + (pathDescendant leaf upper) ≤ + FactoredFunctions.factoringSpace + (HierarchicalMatrixTable.other slots (GeometricPath.nodeAtLevel leaf upper) background) := + HierarchicalKnownRows.knownSpace_le_factoringSpace slots + (GeometricPath.nodeAtLevel leaf upper) background (pathDescendant leaf upper) + +end +end PerfectCompleteness.GeometricDescendants + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/SourceChildKernelLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/SourceChildKernelLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..f4d0dd783ad4d28ab75db447315908ed0c6da3dc --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/SourceChildKernelLemmas.lean @@ -0,0 +1,526 @@ +import OAI.Computability.PerfectCompleteness.Decoding.ChildAssemblyProjection +import OAI.Computability.PerfectCompleteness.Foundations.SourceOddListsLemmas +import OAI.Computability.PerfectCompleteness.Repetition.CutChildCleanLawLemmas +import OAI.Computability.PerfectCompleteness.Sampling.UniformLatentSupportLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.SourceChildKernel + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games +open RecursiveSpaces TreeSourceSpaces PointwiseSpaces HierarchicalArrays +open SourceQuestionReconstruction + +noncomputable section + +variable {branch : Nat → Nat} {n t v m : Nat} {C : Type*} [Fintype C] + +abbrev Block (C : Type*) (rows : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) := + (C → squareSpace (H slots)) × Arrays slots rows + +instance blockFintype (rows : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Fintype (Block C rows slots) := Fintype.ofFinite _ + +def zeroBlock (rows : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : Block C rows slots := + (fun _ => 0, fun _ _ => 0) + +instance blockNonempty (rows : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Nonempty (Block C rows slots) := ⟨zeroBlock rows slots⟩ + +variable (rows : Nat → Nat) (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch n) → Slots branch n) + +abbrev Rest (i : Fin (branch n)) := + CleanSourceRecord.Rest (m := m) (t := t) designated i + +abbrev Source (i : Fin (branch n)) := SourceTuple m t × Rest (m := m) (t := t) designated i + +def tree (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) : + Slots branch n → SourceTuple m t := + CleanSourceRecord.assemble designated i s.1 s.2 + +def nativeSlots (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) : + Slots branch n → Fin t → MixedSupport.Slot := + fun leaf k => SourceKeys.slot clauses (.clause (tree designated i s leaf k).1) + +def ids (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) : + Slots branch n → Fin t → Nat := + fun leaf k => (SourceClause.occurrenceVariable clauses (tree designated i s leaf k)).val + +def mixedSlots (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) : + Bool → Slots branch n → Fin t → MixedSupport.Slot + | false => nativeSlots clauses designated i s + | true => ProjectedCardinality.projectedSlots (ids clauses designated i s) + +theorem mixedSlots_eq_rightTuple (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) + (b : Bool) (leaf : Slots branch n) (k : Fin t) : + mixedSlots clauses designated i s b leaf k = + SourceKeys.slot clauses (rightTuple clauses b (tree designated i s leaf) k) := by + cases b <;> rfl + +abbrev Native (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) := + Block C rows (nativeSlots clauses designated i s) + +abbrev Projected (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) := + Block C rows (ProjectedCardinality.projectedSlots (ids clauses designated i s)) + +abbrev Factors (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) := + CleanTreeFactors.Factors (Fintype.card C) rows (ids clauses designated i s) + +abbrev D (i : Fin (branch n)) := + NativeTaggedUniform.Raw (Native (C := C) (t := t) rows clauses designated i) + +abbrev Raw (i : Fin (branch n)) := + D (C := C) (t := t) rows clauses designated i ⊕ + UniformLatent.Raw (Factors (C := C) (t := t) rows clauses designated i) + +instance rawFintype (i : Fin (branch n)) : + Fintype (Raw (C := C) (t := t) rows clauses designated i) := by + unfold Raw + infer_instance + +def nonprojected (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) : + FiniteDistribution (D (C := C) (t := t) rows clauses designated i) := + NativeTaggedUniform.kernel (Native (C := C) (t := t) rows clauses designated i) s + +def kernel (flag : Fin (branch n) → FiniteDistribution Bool) + (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) : + FiniteDistribution (Raw (C := C) (t := t) rows clauses designated i) := + UniformLatent.projectedKernel (Factors (C := C) (t := t) rows clauses designated i) + (flag i) (nonprojected (C := C) (t := t) rows clauses designated i) s + +def projectedEquiv (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) : + ((j : CleanTreeFactors.Index branch n (Fintype.card C) rows) → + Factors (C := C) (t := t) rows clauses designated i s j) ≃ + Projected (C := C) (t := t) rows clauses designated i s := + (CleanTreeFactors.rawEquiv (Fintype.card C) rows (ids clauses designated i s)).trans + (CutChildCleanLaw.rawEquiv (C := C) rows (ids clauses designated i s)).symm + +def zero (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) + (j : CleanTreeFactors.Index branch n (Fintype.card C) rows) : + Factors (C := C) (t := t) rows clauses designated i s j := + ProjectedCardinality.factorZero (CleanTreeFactors.square (Fintype.card C) rows j) + (CleanTreeFactors.factorIds (Fintype.card C) rows (ids clauses designated i s) j) + +theorem projectedEquiv_zero (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) : + projectedEquiv (C := C) (t := t) rows clauses designated i s (zero (C := C) (t := t) rows clauses designated i s) = + zeroBlock rows (ProjectedCardinality.projectedSlots (ids clauses designated i s)) := rfl + +theorem projectedEquiv_law (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) : + (FiniteProduct.law (fun j => FiniteDistribution.uniform + (Factors (C := C) (t := t) rows clauses designated i s j))).pushforward + (projectedEquiv (C := C) (t := t) rows clauses designated i s) = + FiniteDistribution.uniform (Projected (C := C) (t := t) rows clauses designated i s) := by + rw [UniformLinearImage.law_uniform, FiniteDistribution.pushforward_equiv] + apply FiniteDistribution.eq_of_weight_eq + intro x + change 1 / (Fintype.card ((j : CleanTreeFactors.Index branch n (Fintype.card C) rows) → + Factors (C := C) (t := t) rows clauses designated i s j) : ℝ) = + 1 / (Fintype.card (Projected (C := C) (t := t) rows clauses designated i s) : ℝ) + rw [Fintype.card_congr (projectedEquiv (C := C) (t := t) rows clauses designated i s)] + +def rawProjected (i : Fin (branch n)) : Raw (C := C) (t := t) rows clauses designated i → Bool + | .inl _ => false + | .inr _ => true + +def rawTag (i : Fin (branch n)) : + Raw (C := C) (t := t) rows clauses designated i → Source (m := m) (t := t) designated i := + NativeTaggedUniform.sourceTag (Native (C := C) (t := t) rows clauses designated i) + (Factors (C := C) (t := t) rows clauses designated i) + +theorem kernel_tag (flag : Fin (branch n) → FiniteDistribution Bool) + (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) + (raw : Raw (C := C) (t := t) rows clauses designated i) + (hraw : (kernel rows clauses designated flag i s).weight raw ≠ 0) : + rawTag rows clauses designated i raw = s := + NativeTaggedUniform.projectedKernel_sourceTag + (Native (C := C) (t := t) rows clauses designated i) (Factors (C := C) (t := t) rows clauses designated i) + (flag i) s raw hraw + +def decodeNative (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) + (raw : D (C := C) (t := t) rows clauses designated i) : Native (C := C) (t := t) rows clauses designated i s := + if h : raw.1 = s then + cast (congrArg (Native (C := C) (t := t) rows clauses designated i) h) raw.2 + else zeroBlock rows (nativeSlots clauses designated i s) + +def decodeProjected (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) + (raw : UniformLatent.Raw (Factors (C := C) (t := t) rows clauses designated i)) : + Projected (C := C) (t := t) rows clauses designated i s := + if h : raw.1 = s then + cast (congrArg (Projected (C := C) (t := t) rows clauses designated i) h) + (projectedEquiv (C := C) (t := t) rows clauses designated i raw.1 raw.2) + else zeroBlock rows (ProjectedCardinality.projectedSlots (ids clauses designated i s)) + +omit [Fintype C] in +@[simp] theorem decodeNative_tagged (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) + (x : Native (C := C) (t := t) rows clauses designated i s) : + decodeNative rows clauses designated i s ⟨s, x⟩ = x := by + simp [decodeNative] + +@[simp] theorem decodeProjected_tagged (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) + (x : (j : CleanTreeFactors.Index branch n (Fintype.card C) rows) → + Factors (C := C) (t := t) rows clauses designated i s j) : + decodeProjected rows clauses designated i s ⟨s, x⟩ = + projectedEquiv (C := C) (t := t) rows clauses designated i s x := by + simp [decodeProjected] + +def decodeRight (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) : + (raw : Raw (C := C) (t := t) rows clauses designated i) → + Block C rows (mixedSlots clauses designated i s (rawProjected rows clauses designated i raw)) + | .inl raw => decodeNative rows clauses designated i s raw + | .inr raw => decodeProjected rows clauses designated i s raw + +theorem decodeNative_law (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) : + (nonprojected (C := C) (t := t) rows clauses designated i s).pushforward + (decodeNative rows clauses designated i s) = + FiniteDistribution.uniform (Native (C := C) (t := t) rows clauses designated i s) := by + unfold nonprojected NativeTaggedUniform.kernel + rw [FiniteDistribution.pushforward_comp] + simp only [decodeNative_tagged] + change (FiniteDistribution.uniform (Native (C := C) (t := t) rows clauses designated i s)).pushforward + (Equiv.refl _) = _ + rw [FiniteDistribution.pushforward_equiv] + rfl + +theorem decodeProjected_law (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) : + (UniformLatent.latentKernel (Factors (C := C) (t := t) rows clauses designated i) s).pushforward + (decodeProjected rows clauses designated i s) = + FiniteDistribution.uniform (Projected (C := C) (t := t) rows clauses designated i s) := by + rw [UniformLatent.latentKernel, FiniteDistribution.pushforward_comp] + simp only [decodeProjected_tagged] + exact projectedEquiv_law rows clauses designated i s + +theorem decodeRight_clean (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) + (raw : Raw (C := C) (t := t) rows clauses designated i) + (htag : rawTag rows clauses designated i raw = s) + (hclean : UniformLatent.projectedZero (Factors (C := C) (t := t) rows clauses designated i) + (zero (C := C) (t := t) rows clauses designated i) raw = true) : + decodeRight rows clauses designated i s raw = + zeroBlock rows (mixedSlots clauses designated i s + (rawProjected rows clauses designated i raw)) := by + cases raw with + | inl raw => + simp only [UniformLatent.projectedZero, Bool.false_eq_true] at hclean + | inr raw => + rcases raw with ⟨tag, values⟩ + change tag = s at htag + subst tag + change decide (∀ j, values j = zero (C := C) (t := t) rows clauses designated i s j) = true at hclean + have hvalues : values = zero (C := C) (t := t) rows clauses designated i s := + funext (of_decide_eq_true hclean) + change decodeProjected rows clauses designated i s ⟨s, values⟩ = _ + rw [hvalues, decodeProjected_tagged] + exact projectedEquiv_zero (C := C) (t := t) rows clauses designated i s + +def projection (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) (b : Bool) : + ∀ leaf k, MixedSupport.Projection (nativeSlots clauses designated i s leaf k) + (mixedSlots clauses designated i s b leaf k) := by + cases b with + | false => exact fun leaf k => .keep (nativeSlots clauses designated i s leaf k) + | true => exact fun leaf k => + (SourceKeys.Step.select (clauses := clauses) + (tree designated i s leaf k).1 (tree designated i s leaf k).2).projection + +abbrev Sources := (i : Fin (branch n)) → Source (m := m) (t := t) designated i + +def parentLeftSlots (sources : Sources (m := m) (t := t) designated) : + Slots branch (n + 1) → Fin t → MixedSupport.Slot := + fun leaf k => nativeSlots clauses designated leaf.1 (sources leaf.1) leaf.2 k + +def parentRightSlots (sources : Sources (m := m) (t := t) designated) + (raw : (i : Fin (branch n)) → Raw (C := C) (t := t) rows clauses designated i) : + Slots branch (n + 1) → Fin t → MixedSupport.Slot := + fun leaf k => mixedSlots clauses designated leaf.1 (sources leaf.1) + (rawProjected rows clauses designated leaf.1 (raw leaf.1)) leaf.2 k + +def parentProjection (sources : Sources (m := m) (t := t) designated) + (raw : (i : Fin (branch n)) → Raw (C := C) (t := t) rows clauses designated i) : + ∀ leaf k, MixedSupport.Projection (parentLeftSlots clauses designated sources leaf k) + (parentRightSlots rows clauses designated sources raw leaf k) := + fun leaf k => projection clauses designated leaf.1 (sources leaf.1) + (rawProjected rows clauses designated leaf.1 (raw leaf.1)) leaf.2 k + +def rightChildren (sources : Sources (m := m) (t := t) designated) + (raw : (i : Fin (branch n)) → Raw (C := C) (t := t) rows clauses designated i) : + CutChildGrouping.Raw (C := C) (t := t) (parentRightSlots rows clauses designated sources raw) rows := + fun i => decodeRight rows clauses designated i (sources i) (raw i) + +def leftChildren (sources : Sources (m := m) (t := t) designated) + (raw : (i : Fin (branch n)) → Raw (C := C) (t := t) rows clauses designated i) : + CutChildGrouping.Raw (C := C) (t := t) (parentLeftSlots clauses designated sources) rows := + ChildAssemblyProjection.rawPullback rows + (parentProjection rows clauses designated sources raw) + (rightChildren rows clauses designated sources raw) + +theorem leftChildren_apply (sources : Sources (m := m) (t := t) designated) + (raw : (i : Fin (branch n)) → Raw (C := C) (t := t) rows clauses designated i) + (i : Fin (branch n)) : + leftChildren rows clauses designated sources raw i = + ChildAssemblyProjection.childPullback rows + (parentProjection rows clauses designated sources raw) i + (rightChildren rows clauses designated sources raw i) := rfl + +theorem assemble_leftChildren (sources : Sources (m := m) (t := t) designated) + (raw : (i : Fin (branch n)) → Raw (C := C) (t := t) rows clauses designated i) : + CutChildGrouping.assemble (parentLeftSlots clauses designated sources) rows + (leftChildren rows clauses designated sources raw) = + ChildAssemblyProjection.assembledPullback rows + (parentProjection rows clauses designated sources raw) + (CutChildGrouping.assemble (parentRightSlots rows clauses designated sources raw) rows + (rightChildren rows clauses designated sources raw)) := + ChildAssemblyProjection.assemble_pullback rows + (parentProjection rows clauses designated sources raw) + (rightChildren rows clauses designated sources raw) + +abbrev Sample := (i : Fin (branch n)) → SourceTuple m t × + (Rest (m := m) (t := t) designated i × Raw (C := C) (t := t) rows clauses designated i) + +instance sampleFintype : Fintype (Sample (C := C) (t := t) rows clauses designated) := by + unfold Sample + infer_instance + +def childrenLaw (μ : Fin (branch n) → FiniteDistribution (SourceTuple m t)) + (ν : (i : Fin (branch n)) → FiniteDistribution (Rest (m := m) (t := t) designated i)) + (flag : Fin (branch n) → FiniteDistribution Bool) : + FiniteDistribution (Sample (C := C) (t := t) rows clauses designated) := + UniformCleanSources.childrenLaw (Factors (C := C) (t := t) rows clauses designated) μ ν flag + (nonprojected (C := C) (t := t) rows clauses designated) + +theorem childrenLaw_tag (μ : Fin (branch n) → FiniteDistribution (SourceTuple m t)) + (ν : (i : Fin (branch n)) → FiniteDistribution (Rest (m := m) (t := t) designated i)) + (flag : Fin (branch n) → FiniteDistribution Bool) + (x : Sample (C := C) (t := t) rows clauses designated) + (hx : (childrenLaw rows clauses designated μ ν flag).weight x ≠ 0) (i : Fin (branch n)) : + rawTag rows clauses designated i (x i).2.2 = ((x i).1, (x i).2.1) := + NativeTaggedUniform.childrenLaw_sourceTag + (Native (C := C) (t := t) rows clauses designated) (Factors (C := C) (t := t) rows clauses designated) + μ ν flag x hx i + +theorem childrenLaw_clean_zero + (μ : Fin (branch n) → FiniteDistribution (SourceTuple m t)) + (ν : (i : Fin (branch n)) → FiniteDistribution (Rest (m := m) (t := t) designated i)) + (flag : Fin (branch n) → FiniteDistribution Bool) + (x : Sample (C := C) (t := t) rows clauses designated) + (hx : (childrenLaw rows clauses designated μ ν flag).weight x ≠ 0) + (i : Fin (branch n)) + (hclean : UniformCleanSources.childClean (Factors (C := C) (t := t) rows clauses designated) + (zero (C := C) (t := t) rows clauses designated) i (x i).1 (x i).2.1 (x i).2.2 = true) : + decodeRight rows clauses designated i ((x i).1, (x i).2.1) (x i).2.2 = + zeroBlock rows (mixedSlots clauses designated i ((x i).1, (x i).2.1) + (rawProjected rows clauses designated i (x i).2.2)) := + decodeRight_clean rows clauses designated i ((x i).1, (x i).2.1) (x i).2.2 + (childrenLaw_tag rows clauses designated μ ν flag x hx i) hclean + +def originalLaw [NeZero m] (flag : Fin (branch n) → FiniteDistribution Bool) : + FiniteDistribution (Sample (C := C) (t := t) rows clauses designated) := + childrenLaw rows clauses designated (fun _ => SourceOddLists.tupleLaw m t) + (fun i => FiniteProduct.law (fun _ : {leaf : Slots branch n // leaf ≠ designated i} => + SourceOddLists.tupleLaw m t)) flag + +end +end PerfectCompleteness.SourceChildKernel + +end + +section + +namespace PerfectCompleteness.SourceChildKernelJoint + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games +open RecursiveSpaces SourceQuestionReconstruction + +noncomputable section + +variable {branch : Nat → Nat} {n t v m : Nat} {C : Type*} [Fintype C] + (rows : Nat → Nat) (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch n) → Slots branch n) + +abbrev RawTuple := + (i : Fin (branch n)) → SourceChildKernel.Raw (C := C) (t := t) rows clauses designated i + +def groupEquiv : + SourceChildKernel.Sample (C := C) (t := t) rows clauses designated ≃ + SourceChildKernel.Sources (m := m) (t := t) designated × + RawTuple (C := C) (t := t) rows clauses designated where + toFun x := (fun i => ((x i).1, (x i).2.1), fun i => (x i).2.2) + invFun x := fun i => ((x.1 i).1, (x.1 i).2, x.2 i) + left_inv _ := rfl + right_inv _ := rfl + +@[simp] theorem groupEquiv_sources + (x : SourceChildKernel.Sample (C := C) (t := t) rows clauses designated) + (i : Fin (branch n)) : + (groupEquiv rows clauses designated x).1 i = ((x i).1, (x i).2.1) := rfl + +@[simp] theorem groupEquiv_raw + (x : SourceChildKernel.Sample (C := C) (t := t) rows clauses designated) + (i : Fin (branch n)) : + (groupEquiv rows clauses designated x).2 i = (x i).2.2 := rfl + +theorem childrenLaw_group + (μ : Fin (branch n) → FiniteDistribution (SourceTuple m t)) + (ν : (i : Fin (branch n)) → + FiniteDistribution (SourceChildKernel.Rest (m := m) (t := t) designated i)) + (flag : Fin (branch n) → FiniteDistribution Bool) : + (SourceChildKernel.childrenLaw (C := C) (t := t) rows clauses designated μ ν flag).pushforward + (groupEquiv rows clauses designated) = + CleanConditioning.kernelJoint + (FiniteProduct.law (fun i => (μ i).product (ν i))) + (fun sources => FiniteProduct.law (fun i => + SourceChildKernel.kernel (C := C) (t := t) rows clauses designated flag i (sources i))) := by + rw [FiniteDistribution.pushforward_equiv] + apply FiniteDistribution.eq_of_weight_eq + rintro ⟨sources, raw⟩ + change (∏ i : Fin (branch n), + (μ i).weight (sources i).1 * ((ν i).weight (sources i).2 * + (SourceChildKernel.kernel (C := C) (t := t) rows clauses designated flag i + (sources i)).weight (raw i))) = + (∏ i : Fin (branch n), (μ i).weight (sources i).1 * (ν i).weight (sources i).2) * + ∏ i : Fin (branch n), + (SourceChildKernel.kernel (C := C) (t := t) rows clauses designated flag i + (sources i)).weight (raw i) + rw [← Finset.prod_mul_distrib] + apply Finset.prod_congr rfl + intro i _ + exact (mul_assoc _ _ _).symm + +theorem originalLaw_group [NeZero m] + (flag : Fin (branch n) → FiniteDistribution Bool) : + (SourceChildKernel.originalLaw (C := C) (t := t) rows clauses designated flag).pushforward + (groupEquiv rows clauses designated) = + CleanConditioning.kernelJoint + (FiniteProduct.law (fun i : Fin (branch n) => + (SourceOddLists.tupleLaw m t).product + (FiniteProduct.law (fun _ : {leaf : Slots branch n // leaf ≠ designated i} => + SourceOddLists.tupleLaw m t)))) + (fun sources => FiniteProduct.law (fun i => + SourceChildKernel.kernel (C := C) (t := t) rows clauses designated flag i (sources i))) := + childrenLaw_group rows clauses designated _ _ flag + +end +end PerfectCompleteness.SourceChildKernelJoint + +end + +section + +namespace PerfectCompleteness.SourceChildKernelRate + +noncomputable section + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games +open RecursiveSpaces ProjectedCardinality + +variable {branch : Nat → Nat} {height t v m : Nat} [NeZero m] + {C : Type*} [Fintype C] + (rows : Nat → Nat) (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch height) → Slots branch height) + +abbrev Factors := SourceChildKernel.Factors (C := C) (t := t) rows clauses designated +abbrev Record := UniformCleanSoundness.FullRecord + (D := SourceChildKernel.D (C := C) (t := t) rows clauses designated) + (Factors (C := C) (t := t) rows clauses designated) +abbrev Sample := SourceChildKernel.Sample (C := C) (t := t) rows clauses designated +abbrev CleanChildren (record : Record (C := C) (t := t) rows clauses designated) := + UniformCleanSources.CleanIndices (Factors (C := C) (t := t) rows clauses designated) record + +theorem bound_from_repetition {s L cube : Nat} [NeZero s] (hcube : 0 < cube) + (repetition : ∀ k, ((SourceOddLists.game s clauses t).repetition k).value ≤ + (RepetitionRate.halfRate L : ℝ) ^ k) + (event : Sample (C := C) (t := t) rows clauses designated → Bool) + (strategies : (record : Record (C := C) (t := t) rows clauses designated) → + Strategy (CleanChildren rows clauses designated record → Fin t → Fin m) + (CleanChildren rows clauses designated record → Fin t → Fin v) + (CleanChildren rows clauses designated record → OddLists.OddList s (SourceOddLists.LeftLabels t)) + (CleanChildren rows clauses designated record → OddLists.OddList s (SourceOddLists.RightLabels t))) + (inclusion : ∀ record x, + UniformCleanSources.recordEvent (Factors (C := C) (t := t) rows clauses designated) + (SourceChildKernel.zero (C := C) (t := t) rows clauses designated) record x = true → + event x = true → + (IndexedRepetition.game (SourceOddLists.game s clauses t) + (CleanChildren rows clauses designated record)).wins (strategies record) + (fun i => (x i.val).1) = true) : + (SourceChildKernel.originalLaw (C := C) (t := t) rows clauses designated + (fun _ => ProjectedCleanRate.projectionFlag cube hcube)).probability event ≤ + (1 - ProjectedCleanRate.coefficient L branch height t (Fintype.card C) rows / + (cube : ℝ) ^ 2) ^ (branch height) := by + let restLaw := fun i : Fin (branch height) => FiniteProduct.law + (fun _ : {leaf : Slots branch height // leaf ≠ designated i} => + SourceOddLists.tupleLaw m t) + have bound := UniformCleanSoundness.source_soundness + (Factors (C := C) (t := t) rows clauses designated) + (SourceOddLists.game s clauses t) restLaw + (fun _ => ProjectedCleanRate.projectionFlag cube hcube) + (SourceChildKernel.nonprojected (C := C) (t := t) rows clauses designated) + (SourceChildKernel.zero (C := C) (t := t) rows clauses designated) + (fun _ => shapeCardinality branch t + (CleanTreeFactors.height (Fintype.card C) rows) + (CleanTreeFactors.square (Fintype.card C) rows)) + (fun i source j => factor_card_eq + (CleanTreeFactors.square (Fintype.card C) rows j) + (CleanTreeFactors.factorIds (Fintype.card C) rows + (SourceChildKernel.ids clauses designated i source) j) (fun _ _ => 0)) + event (RepetitionRate.halfRate L : ℝ) repetition strategies inclusion + have hoccurrences : (SourceOddLists.game s clauses t).occurrences = + SourceOddLists.tupleLaw m t := rfl + rw [hoccurrences] at bound + have hbase : + 1 - (1 - (RepetitionRate.halfRate L : ℝ)) * + (ProjectedCleanRate.projectionDensity cube * + ProjectedCleanRate.zeroProbability branch height t (Fintype.card C) rows) = + 1 - ProjectedCleanRate.coefficient L branch height t (Fintype.card C) rows / + (cube : ℝ) ^ 2 := by + rw [ProjectedCleanRate.coefficient_eq] + unfold ProjectedCleanRate.projectionDensity + ring + calc + _ ≤ ∏ _i : Fin (branch height), + (1 - (1 - (RepetitionRate.halfRate L : ℝ)) * + (ProjectedCleanRate.projectionDensity cube * + ProjectedCleanRate.zeroProbability branch height t (Fintype.card C) rows)) := by + simpa only [SourceChildKernel.originalLaw, SourceChildKernel.childrenLaw, Factors, restLaw, + ProjectedCleanRate.projectionFlag_true, ProjectedCleanRate.zeroProbability] using bound + _ = _ := by + simp only [hbase, Finset.prod_const, Finset.card_univ, Fintype.card_fin] + +theorem amplified_bound {s L cube : Nat} [NeZero s] + (γ : ℚ) (hγ : 0 < γ) (hγ1 : γ ≤ 1) + (ht : t = SourceOddLists.repetitionLength γ s hγ hγ1) + (hcube : 0 < cube) (gap : SourceAmplification.ClauseGap clauses γ) + (hL : 0 < L) (alphabet : SourceOddLists.alphabetLog s t ≤ L) + (event : Sample (C := C) (t := t) rows clauses designated → Bool) + (strategies : (record : Record (C := C) (t := t) rows clauses designated) → + Strategy (CleanChildren rows clauses designated record → Fin t → Fin m) + (CleanChildren rows clauses designated record → Fin t → Fin v) + (CleanChildren rows clauses designated record → OddLists.OddList s (SourceOddLists.LeftLabels t)) + (CleanChildren rows clauses designated record → OddLists.OddList s (SourceOddLists.RightLabels t))) + (inclusion : ∀ record x, + UniformCleanSources.recordEvent (Factors (C := C) (t := t) rows clauses designated) + (SourceChildKernel.zero (C := C) (t := t) rows clauses designated) record x = true → + event x = true → + (IndexedRepetition.game (SourceOddLists.game s clauses t) + (CleanChildren rows clauses designated record)).wins (strategies record) + (fun i => (x i.val).1) = true) : + (SourceChildKernel.originalLaw (C := C) (t := t) rows clauses designated + (fun _ => ProjectedCleanRate.projectionFlag cube hcube)).probability event ≤ + (1 - ProjectedCleanRate.coefficient L branch height t (Fintype.card C) rows / + (cube : ℝ) ^ 2) ^ (branch height) := by + apply bound_from_repetition rows clauses designated hcube _ event strategies inclusion + subst t + exact SourceOddLists.repetition_halfRate clauses γ hγ hγ1 gap hL alphabet + +end +end PerfectCompleteness.SourceChildKernelRate + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/SourceLocalOddLists.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/SourceLocalOddLists.lean new file mode 100644 index 0000000000000000000000000000000000000000..e70488c65b20675acf92ad2361fe3833b991b2ff --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/SourceLocalOddLists.lean @@ -0,0 +1,215 @@ +import OAI.Computability.PerfectCompleteness.Foundations.OddListExtraction +import OAI.Computability.PerfectCompleteness.Foundations.SourceOddListsLemmas +import OAI.Computability.PerfectCompleteness.Repetition.RepetitionRateLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.SourceLocalOddLists + +open scoped Classical +open PointwiseSpaces TreeSourceSpaces SourceAnswerEquiv +open UniqueGamesTheorem.Foundations.Games + +abbrev F2 := ZMod 2 + +noncomputable section + +variable {branch : Nat → Nat} {h t v m s : Nat} + +abbrev Form (slots : RecursiveSpaces.Slots branch h → Fin t → MixedSupport.Slot) := + H slots →ₗ[F2] H slots →ₗ[F2] F2 + +def leafSupport (slots : RecursiveSpaces.Slots branch h → Fin t → MixedSupport.Slot) + (F : Form slots) (leaf : RecursiveSpaces.Slots branch h) : Finset (LeafDomain slots leaf) := + OddLists.support (fun a => F + (OddListExtraction.atom (H slots) (fun x => x leaf) + (OddListExtraction.source_leaf_indicator_mem slots leaf) a) + (OddListExtraction.atom (H slots) (fun x => x leaf) + (OddListExtraction.source_leaf_indicator_mem slots leaf) a)) + +def extract (positive : 0 < s) + (slots : RecursiveSpaces.Slots branch h → Fin t → MixedSupport.Slot) + (F : Form slots) (leaf : RecursiveSpaces.Slots branch h) (fallback : LeafDomain slots leaf) : + OddLists.OddList s (LeafDomain slots leaf) := + OddLists.OddList.extract positive fallback (leafSupport slots F leaf) + +theorem extract_accepts (positive : 0 < s) + {slots projected : RecursiveSpaces.Slots branch h → Fin t → MixedSupport.Slot} + (p : ∀ leaf k, MixedSupport.Projection (slots leaf k) (projected leaf k)) + (leaf : RecursiveSpaces.Slots branch h) (F : Form slots) (F' : Form projected) + (z : Module.Dual F2 (squareSpace (H slots))) + (hform : F = OddListExtraction.multiplicationForm (H slots) z) + (hone : (1 : Domain slots → F2) ∈ squareSpace (H slots)) + (hnorm : z ⟨1, hone⟩ = 1) (hrank : OddListExtraction.formRank (H slots) F ≤ s) + (hagree : ∀ f g, F' f g = OddListExtraction.multiplicationForm (H slots) z + (HPullback p f) (HPullback p g)) + (leftFallback : LeafDomain slots leaf) (rightFallback : LeafDomain projected leaf) : + OddLists.OddList.map (MixedSupport.projectionMap (p leaf)) + (extract positive slots F leaf leftFallback) = + extract positive projected F' leaf rightFallback := by + have hleft : Odd (leafSupport slots F leaf).card ∧ (leafSupport slots F leaf).card ≤ s := by + rw [hform] at hrank ⊢ + exact (OddListExtraction.extractedList (H slots) (fun x => x leaf) + (OddListExtraction.source_leaf_indicator_mem slots leaf) z hone hnorm s hrank).property + have hsupport : leafSupport projected F' leaf = + OddLists.parityPushforward (MixedSupport.projectionMap (p leaf)) (leafSupport slots F leaf) := by + rw [hform] + exact OddListExtraction.source_projected_support p leaf z F' hagree + have hright : Odd (leafSupport projected F' leaf).card ∧ + (leafSupport projected F' leaf).card ≤ s := by + rw [hsupport] + exact ⟨OddLists.parityPushforward_odd _ _ hleft.1, + (OddLists.parityPushforward_card_le _ _).trans hleft.2⟩ + apply Subtype.ext + rw [OddLists.OddList.map_val] + change OddLists.parityPushforward (MixedSupport.projectionMap (p leaf)) + (OddLists.OddList.extract positive leftFallback (leafSupport slots F leaf)).val = + (OddLists.OddList.extract positive rightFallback (leafSupport projected F' leaf)).val + rw [OddLists.OddList.extract_valid positive leftFallback _ hleft, + OddLists.OddList.extract_valid positive rightFallback _ hright] + exact hsupport.symm + +private theorem map_eq_of_map_eq {A B : Type*} {s : Nat} + {f₁ f₂ : Fintype B} {d₁ d₂ : DecidableEq B} + (π : A → B) (L : OddLists.OddList s A) (R : OddLists.OddList s B) + (accepted : @OddLists.OddList.map A B s f₁ d₁ π L = R) : + @OddLists.OddList.map A B s f₂ d₂ π L = R := by + have hf : f₁ = f₂ := Subsingleton.elim _ _ + cases hf + have hd : d₁ = d₂ := Subsingleton.elim _ _ + cases hd + exact accepted + +variable (clauses : Fin m → SourceClause.NormalizedClause v) + +abbrev LeftQuestions := RecursiveSpaces.Slots branch h → Fin t → Fin m +abbrev RightQuestions := RecursiveSpaces.Slots branch h → Fin t → Fin v +abbrev Occurrences := RecursiveSpaces.Slots branch h → SourceOddLists.Occurrences m t + +abbrev LeftForms := (q : LeftQuestions (branch := branch) (h := h) (t := t) (m := m)) → + Form (leftTreeSlots clauses q) + +abbrev RightForms := (q : RightQuestions (branch := branch) (h := h) (t := t) (v := v)) → + Form (rightTreeSlots clauses q) + +def leftResponse (positive : 0 < s) (forms : LeftForms (branch := branch) (h := h) (t := t) clauses) + (q : LeftQuestions (branch := branch) (h := h) (t := t) (m := m)) + (leaf : RecursiveSpaces.Slots branch h) : OddLists.OddList s (SourceOddLists.LeftLabels t) := + encodeOddList clauses (q leaf) + (extract positive (leftTreeSlots clauses q) (forms q) leaf + ((leftEquiv clauses (q leaf)).symm (fun _ => 0))) + +def rightResponse (positive : 0 < s) (forms : RightForms (branch := branch) (h := h) (t := t) clauses) + (q : RightQuestions (branch := branch) (h := h) (t := t) (v := v)) + (leaf : RecursiveSpaces.Slots branch h) : OddLists.OddList s (SourceOddLists.RightLabels t) := + extract positive (rightTreeSlots clauses q) (forms q) leaf (fun _ => false) + +def treeProjection (e : Occurrences (branch := branch) (h := h) (m := m) (t := t)) : + ∀ leaf k, MixedSupport.Projection + (leftTreeSlots clauses (fun j => SourceOddLists.left (e j)) leaf k) + (rightTreeSlots clauses (fun j => SourceOddLists.right clauses (e j)) leaf k) := + fun leaf => slotProjection clauses (e leaf) + +section Clean + +variable (clean : RecursiveSpaces.Slots branch h → Prop) + +abbrev CleanLeaves := {leaf : RecursiveSpaces.Slots branch h // clean leaf} + +def fill {Q : Type*} (background : RecursiveSpaces.Slots branch h → Q) + (q : CleanLeaves clean → Q) : RecursiveSpaces.Slots branch h → Q := + fun leaf => if hc : clean leaf then q ⟨leaf, hc⟩ else background leaf + +@[simp] theorem fill_clean {Q : Type*} (background : RecursiveSpaces.Slots branch h → Q) + (q : CleanLeaves clean → Q) (leaf : CleanLeaves clean) : + fill clean background q leaf.val = q leaf := by + simp only [fill, dite_eq_left leaf.property] + +theorem fill_comp {Q R : Type*} (background : RecursiveSpaces.Slots branch h → Q) + (q : CleanLeaves clean → Q) (f : Q → R) : + fill clean (fun leaf => f (background leaf)) (fun leaf => f (q leaf)) = + fun leaf => f (fill clean background q leaf) := by + funext leaf + by_cases hc : clean leaf + · simp only [fill, dite_eq_left hc] + · simp only [fill, dite_eq_right hc] + +variable (background : Occurrences (branch := branch) (h := h) (m := m) (t := t)) + +def strategy (positive : 0 < s) (leftForms : LeftForms (branch := branch) (h := h) (t := t) clauses) (rightForms : RightForms (branch := branch) (h := h) (t := t) clauses) : + Strategy (CleanLeaves clean → Fin t → Fin m) (CleanLeaves clean → Fin t → Fin v) + (CleanLeaves clean → OddLists.OddList s (SourceOddLists.LeftLabels t)) + (CleanLeaves clean → OddLists.OddList s (SourceOddLists.RightLabels t)) := + (fun q leaf => leftResponse clauses positive leftForms + (fill clean (fun j => SourceOddLists.left (background j)) q) leaf.val, + fun q leaf => rightResponse clauses positive rightForms + (fill clean (fun j => SourceOddLists.right clauses (background j)) q) leaf.val) + +theorem strategy_wins [NeZero m] (positive : 0 < s) + (leftForms : LeftForms (branch := branch) (h := h) (t := t) clauses) (rightForms : RightForms (branch := branch) (h := h) (t := t) clauses) + (e : CleanLeaves clean → SourceOddLists.Occurrences m t) + (z : Module.Dual F2 (squareSpace + (H (leftTreeSlots clauses (fun j => SourceOddLists.left (fill clean background e j)))))) + (hform : leftForms (fun j => SourceOddLists.left (fill clean background e j)) = + OddListExtraction.multiplicationForm + (H (leftTreeSlots clauses (fun j => SourceOddLists.left (fill clean background e j)))) z) + (hone : + (1 : Domain (leftTreeSlots clauses (fun j => SourceOddLists.left (fill clean background e j))) → F2) ∈ + squareSpace (H (leftTreeSlots clauses (fun j => SourceOddLists.left (fill clean background e j))))) + (hnorm : z ⟨1, hone⟩ = 1) + (hrank : OddListExtraction.formRank + (H (leftTreeSlots clauses (fun j => SourceOddLists.left (fill clean background e j)))) + (leftForms (fun j => SourceOddLists.left (fill clean background e j))) ≤ s) + (hagree : ∀ f g, + rightForms (fun j => SourceOddLists.right clauses (fill clean background e j)) f g = + OddListExtraction.multiplicationForm + (H (leftTreeSlots clauses (fun j => SourceOddLists.left (fill clean background e j)))) z + (HPullback (treeProjection clauses (fill clean background e)) f) + (HPullback (treeProjection clauses (fill clean background e)) g)) : + (IndexedRepetition.game (SourceOddLists.game s clauses t) (CleanLeaves clean)).wins + (strategy clauses clean background positive leftForms rightForms) e = true := by + simp only [OccurrenceGame.wins, IndexedRepetition.game, SourceOddLists.game, + OddListGame.game, OccurrenceGame.ofProjection, strategy, decide_eq_true_eq] + intro leaf + rw [fill_comp clean background e SourceOddLists.left, + fill_comp clean background e (SourceOddLists.right clauses)] + let full : Occurrences (branch := branch) (h := h) (m := m) (t := t) := + fill clean background e + let qL : LeftQuestions (branch := branch) (h := h) (t := t) (m := m) := + fun j => SourceOddLists.left (full j) + let qR : RightQuestions (branch := branch) (h := h) (t := t) (v := v) := + fun j => SourceOddLists.right clauses (full j) + let slotsL : RecursiveSpaces.Slots branch h → Fin t → MixedSupport.Slot := + leftTreeSlots (branch := branch) (n := h) clauses qL + let slotsR : RecursiveSpaces.Slots branch h → Fin t → MixedSupport.Slot := + rightTreeSlots (branch := branch) (n := h) clauses qR + let L : OddLists.OddList s (LeftDomain clauses (SourceOddLists.left (full leaf.val))) := + extract (branch := branch) (h := h) (t := t) positive slotsL (leftForms qL) leaf.val + ((leftEquiv clauses (SourceOddLists.left (full leaf.val))).symm (fun _ => 0)) + let R : OddLists.OddList s (RightDomain clauses (SourceOddLists.right clauses (full leaf.val))) := + extract (branch := branch) (h := h) (t := t) positive slotsR (rightForms qR) leaf.val + (fun _ => false) + have hraw := extract_accepts (branch := branch) (h := h) (t := t) + (slots := slotsL) (projected := slotsR) positive + (treeProjection (branch := branch) (h := h) (t := t) clauses full) + leaf.val (leftForms qL) (rightForms qR) z hform hone hnorm hrank hagree + ((leftEquiv clauses (SourceOddLists.left (full leaf.val))).symm (fun _ => 0)) + (fun _ => false) + have hnative : OddLists.OddList.map (actualProjection clauses (full leaf.val)) L = R := + map_eq_of_map_eq _ L R hraw + have haccept := encodeOddList_accepted clauses (full leaf.val) L R hnative + rw [← fill_clean clean background e leaf] + change OddLists.OddList.map (SourceOddLists.projection clauses (full leaf.val)) + (encodeOddList clauses (SourceOddLists.left (full leaf.val)) L) = R + exact haccept + +end Clean + +end +end PerfectCompleteness.SourceLocalOddLists + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/SourcePhysicalChildExpectation.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/SourcePhysicalChildExpectation.lean new file mode 100644 index 0000000000000000000000000000000000000000..b2ddf8986b192f9714e8eec8a259b21b9a01870c --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/SourcePhysicalChildExpectation.lean @@ -0,0 +1,134 @@ +import OAI.Computability.PerfectCompleteness.Construction.SourcePhysicalTaggedChildren +import OAI.Computability.PerfectCompleteness.Construction.SourceQuestionRawSwap +import OAI.Computability.PerfectCompleteness.Sampling.CandidateCoupling + +namespace OAI + +section + +namespace PerfectCompleteness.SourcePhysicalChildExpectation + +noncomputable section + +open scoped Classical +open RecursiveSpaces +open UniqueGamesTheorem.Foundations.Games + +variable {branch : Nat → Nat} {n t v m : Nat} {C : Type*} [Fintype C] + (rows : Nat → Nat) (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch n) → Slots branch n) + +def observe (q : PreliminarySampler.Questions branch (n + 1) t m) + (choices : SourceQuestionKernelJoint.ChoiceTuple (branch := branch) (n := n) (t := t)) + (raw : SourceChildKernelJoint.RawTuple (C := C) (t := t) rows clauses designated) : + Σ flags : SourceProjectedTag.Flags (branch := branch) (n := n), + CutChildGrouping.Raw (C := C) + (SourceProjectedTag.mixedInside clauses designated q choices flags) rows := + SourcePhysicalTaggedChildren.observe rows clauses designated + (SourceQuestionKernelJoint.sources designated q choices) raw + +@[simp] theorem observe_flags + (q : PreliminarySampler.Questions branch (n + 1) t m) + (choices : SourceQuestionKernelJoint.ChoiceTuple (branch := branch) (n := n) (t := t)) + (raw : SourceChildKernelJoint.RawTuple (C := C) (t := t) rows clauses designated) : + (observe rows clauses designated q choices raw).1 = + fun child => SourceChildKernel.rawProjected rows clauses designated child (raw child) := rfl + +theorem observe_sample_heq + (sample : SourceChildKernel.Sample (C := C) (t := t) rows clauses designated) : + HEq (observe rows clauses designated + (SourceQuestionRawSwap.insideQuestions rows clauses designated sample) + (SourceQuestionRawSwap.positions rows clauses designated sample) + (SourceQuestionRawSwap.raw rows clauses designated sample)) + (SourcePhysicalTaggedChildren.observe rows clauses designated + (fun child => ((sample child).1, (sample child).2.1)) + (fun child => (sample child).2.2)) := by + have congrObserve (sources other : SourceChildKernel.Sources (m := m) (t := t) designated) + (hs : sources = other) + (raw : SourceChildKernelJoint.RawTuple (C := C) (t := t) rows clauses designated) : + HEq (SourcePhysicalTaggedChildren.observe rows clauses designated sources raw) + (SourcePhysicalTaggedChildren.observe rows clauses designated other raw) := by + cases hs + rfl + exact congrObserve _ _ + (SourceQuestionRawSwap.sources_insideQuestions_positions rows clauses designated sample) + (SourceQuestionRawSwap.raw rows clauses designated sample) + +theorem kernel_expectation + (flag : Fin (branch n) → FiniteDistribution Bool) + (q : PreliminarySampler.Questions branch (n + 1) t m) + (choices : SourceQuestionKernelJoint.ChoiceTuple (branch := branch) (n := n) (t := t)) + (F : (flags : SourceProjectedTag.Flags (branch := branch) (n := n)) → + CutChildGrouping.Raw (C := C) + (SourceProjectedTag.mixedInside clauses designated q choices flags) rows → ℝ) : + (SourceQuestionRawSwap.kernelLaw (C := C) rows clauses designated flag q choices).expectation + (fun raw => + let observed := observe rows clauses designated q choices raw + F observed.1 observed.2) = + (SourceProjectedTag.flagLaw flag).expectation (fun flags => + (CutChildGrouping.rawLaw (C := C) + (SourceProjectedTag.mixedInside clauses designated q choices flags) rows).expectation + (F flags)) := by + let statistic : + (Σ flags : SourceProjectedTag.Flags (branch := branch) (n := n), + CutChildGrouping.Raw (C := C) + (SourceProjectedTag.mixedInside clauses designated q choices flags) rows) → ℝ := + fun observed => F observed.1 observed.2 + let physical := fun flags : SourceProjectedTag.Flags (branch := branch) (n := n) => + CutChildGrouping.rawLaw (C := C) + (SourceProjectedTag.mixedInside clauses designated q choices flags) rows + have hlaw : + (SourceQuestionRawSwap.kernelLaw (C := C) rows clauses designated flag q choices).pushforward + (observe rows clauses designated q choices) = + CompletionSoundness.sigmaLaw (SourceProjectedTag.flagLaw flag) physical := + SourcePhysicalTaggedChildren.kernels_tagged (C := C) rows clauses designated flag + (SourceQuestionKernelJoint.sources designated q choices) + calc + _ = ((SourceQuestionRawSwap.kernelLaw (C := C) rows clauses designated flag q choices).pushforward + (observe rows clauses designated q choices)).expectation statistic := + (FiniteDistribution.expectation_pushforward + (SourceQuestionRawSwap.kernelLaw (C := C) rows clauses designated flag q choices) + (observe rows clauses designated q choices) statistic).symm + _ = (CompletionSoundness.sigmaLaw (SourceProjectedTag.flagLaw flag) physical).expectation + statistic := congrArg (fun μ => FiniteDistribution.expectation μ statistic) hlaw + _ = _ := CandidateCoupling.expectation_sigmaLaw + (SourceProjectedTag.flagLaw flag) physical statistic + +theorem originalLaw_expectation [NeZero m] + (flag : Fin (branch n) → FiniteDistribution Bool) + (F : (q : PreliminarySampler.Questions branch (n + 1) t m) → + (choices : SourceQuestionKernelJoint.ChoiceTuple (branch := branch) (n := n) (t := t)) → + (flags : SourceProjectedTag.Flags (branch := branch) (n := n)) → + CutChildGrouping.Raw (C := C) + (SourceProjectedTag.mixedInside clauses designated q choices flags) rows → ℝ) : + (SourceChildKernel.originalLaw (C := C) (t := t) rows clauses designated flag).expectation + (fun sample => + let q := SourceQuestionRawSwap.insideQuestions rows clauses designated sample + let choices := SourceQuestionRawSwap.positions rows clauses designated sample + let observed := observe rows clauses designated q choices + (SourceQuestionRawSwap.raw rows clauses designated sample) + F q choices observed.1 observed.2) = + (PreliminarySampler.questionsLaw + (branch := branch) (n := n + 1) (t := t) (m := m)).expectation + (fun q => (SourceProjectedTag.positionLaw + (branch := branch) (n := n) (t := t)).expectation + (fun choices => (SourceProjectedTag.flagLaw flag).expectation + (fun flags => (CutChildGrouping.rawLaw (C := C) + (SourceProjectedTag.mixedInside clauses designated q choices flags) rows).expectation + (F q choices flags)))) := by + rw [SourceQuestionRawSwap.originalLaw_expectation rows clauses designated flag + (fun q choices raw => + let observed := observe rows clauses designated q choices raw + F q choices observed.1 observed.2)] + apply FiniteDistribution.expectation_congr + intro q + apply FiniteDistribution.expectation_congr + intro choices + exact kernel_expectation rows clauses designated flag q choices (F q choices) + +end +end PerfectCompleteness.SourcePhysicalChildExpectation + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/SourcePhysicalTaggedChildren.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/SourcePhysicalTaggedChildren.lean new file mode 100644 index 0000000000000000000000000000000000000000..e3d38898104ed35537a070c36e5c8a7087cf0e03 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/SourcePhysicalTaggedChildren.lean @@ -0,0 +1,110 @@ +import OAI.Computability.PerfectCompleteness.Foundations.DependentPredictionDifferenceLemmas +import OAI.Computability.PerfectCompleteness.Sampling.SourceChildKernelLaw + +namespace OAI + +section + +namespace PerfectCompleteness.SourcePhysicalTaggedChildren + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games +open RecursiveSpaces TreeSourceSpaces SourceChildKernel + +noncomputable section + +variable {branch : Nat → Nat} {n t v m : Nat} {C : Type*} [Fintype C] + (rows : Nat → Nat) (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch n) → Slots branch n) + +def slots (sources : Sources (m := m) (t := t) designated) + (flags : Fin (branch n) → Bool) : + Slots branch (n + 1) → Fin t → MixedSupport.Slot := + fun leaf k => mixedSlots clauses designated leaf.1 (sources leaf.1) + (flags leaf.1) leaf.2 k + +def pack (sources : Sources (m := m) (t := t) designated) : + ((i : Fin (branch n)) → + SourceChildKernelLaw.Physical (C := C) (t := t) rows clauses designated i (sources i)) ≃ + Σ flags : Fin (branch n) → Bool, + CutChildGrouping.Raw (C := C) (slots clauses designated sources flags) rows where + toFun x := ⟨fun i => (x i).1, fun i => (x i).2⟩ + invFun x i := ⟨x.1 i, x.2 i⟩ + left_inv x := by + funext i + exact Sigma.eta (x i) + right_inv x := by + cases x + rfl + +def observe (sources : Sources (m := m) (t := t) designated) + (raw : (i : Fin (branch n)) → Raw (C := C) (t := t) rows clauses designated i) : + Σ flags : Fin (branch n) → Bool, + CutChildGrouping.Raw (C := C) (slots clauses designated sources flags) rows := + pack rows clauses designated sources + (fun i => SourceChildKernelLaw.physical rows clauses designated i (sources i) (raw i)) + +@[simp] theorem observe_fst (sources : Sources (m := m) (t := t) designated) + (raw : (i : Fin (branch n)) → Raw (C := C) (t := t) rows clauses designated i) : + (observe rows clauses designated sources raw).1 = + fun i => rawProjected rows clauses designated i (raw i) := rfl + +theorem slots_observe (sources : Sources (m := m) (t := t) designated) + (raw : (i : Fin (branch n)) → Raw (C := C) (t := t) rows clauses designated i) : + slots clauses designated sources (observe rows clauses designated sources raw).1 = + parentRightSlots rows clauses designated sources raw := rfl + +@[simp] theorem observe_snd (sources : Sources (m := m) (t := t) designated) + (raw : (i : Fin (branch n)) → Raw (C := C) (t := t) rows clauses designated i) : + (observe rows clauses designated sources raw).2 = + rightChildren rows clauses designated sources raw := rfl + +private theorem physicalLaw_sigma (flag : Fin (branch n) → FiniteDistribution Bool) + (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) : + SourceChildKernelLaw.physicalLaw (C := C) (t := t) rows clauses designated flag i s = + CompletionSoundness.sigmaLaw (flag i) (fun b => + FiniteDistribution.uniform (Block C rows (mixedSlots clauses designated i s b))) := by + apply SigmaObservation.eq_of_probability_eq + intro event + unfold SourceChildKernelLaw.physicalLaw + rw [FiniteDistribution.probability_mixture, CompletionSoundness.sigmaLaw_probability] + apply FiniteDistribution.expectation_congr + intro b + exact FiniteDistribution.probability_pushforward _ _ _ + +theorem pack_law (flag : Fin (branch n) → FiniteDistribution Bool) + (sources : Sources (m := m) (t := t) designated) : + (FiniteProduct.law (fun i => + SourceChildKernelLaw.physicalLaw (C := C) (t := t) rows clauses designated flag i + (sources i))).pushforward (pack rows clauses designated sources) = + CompletionSoundness.sigmaLaw (FiniteProduct.law flag) (fun flags => + CutChildGrouping.rawLaw (C := C) (slots clauses designated sources flags) rows) := by + rw [FiniteDistribution.pushforward_equiv] + apply FiniteDistribution.eq_of_weight_eq + rintro ⟨flags, children⟩ + change (∏ i, (SourceChildKernelLaw.physicalLaw (C := C) (t := t) + rows clauses designated flag i (sources i)).weight ⟨flags i, children i⟩) = + (∏ i, (flag i).weight (flags i)) * + (∏ i, (FiniteDistribution.uniform + (Block C rows (mixedSlots clauses designated i (sources i) (flags i)))).weight + (children i)) + simp_rw [physicalLaw_sigma] + exact Finset.prod_mul_distrib + +theorem kernels_tagged (flag : Fin (branch n) → FiniteDistribution Bool) + (sources : Sources (m := m) (t := t) designated) : + (FiniteProduct.law (fun i => + kernel (C := C) (t := t) rows clauses designated flag i (sources i))).pushforward + (observe rows clauses designated sources) = + CompletionSoundness.sigmaLaw (FiniteProduct.law flag) (fun flags => + CutChildGrouping.rawLaw (C := C) (slots clauses designated sources flags) rows) := by + unfold observe + rw [← FiniteDistribution.pushforward_comp, SourceChildKernelLaw.kernels_physical] + exact pack_law rows clauses designated flag sources + +end +end PerfectCompleteness.SourcePhysicalTaggedChildren + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/SourceQuestionCutSplit.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/SourceQuestionCutSplit.lean new file mode 100644 index 0000000000000000000000000000000000000000..b4a2325c450dd661a60ca92b7d6eacdff59b6330 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/SourceQuestionCutSplit.lean @@ -0,0 +1,154 @@ +import OAI.Computability.PerfectCompleteness.Foundations.CutSlotOutside +import OAI.Computability.PerfectCompleteness.Sampling.PreliminarySampler + +namespace OAI + +section + +namespace PerfectCompleteness.SourceQuestionCutSplit + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces +open UniqueGamesTheorem.Foundations.Games + +variable {branch : Nat → Nat} {root h t m : Nat} + +abbrev OutsideLeaf (p : Path branch root h) := + {leaf : Slots branch root // leaf ∉ Set.range p.slotEmbedding} + +abbrev OutsideQuestions (p : Path branch root h) (t m : Nat) := + OutsideLeaf p → Fin t → Fin m + +def restrict (p : Path branch root h) + (q : PreliminarySampler.Questions branch root t m) : + PreliminarySampler.Questions branch h t m := + fun leaf => q (p.slotEmbedding leaf) + +def outside (p : Path branch root h) + (q : PreliminarySampler.Questions branch root t m) : OutsideQuestions p t m := + fun leaf => q leaf.val + +def join (p : Path branch root h) + (inside : PreliminarySampler.Questions branch h t m) (external : OutsideQuestions p t m) : + PreliminarySampler.Questions branch root t m := + fun leaf => if hleaf : leaf ∈ Set.range p.slotEmbedding then + inside (Classical.choose hleaf) else external ⟨leaf, hleaf⟩ + +@[simp] theorem join_at_cut (p : Path branch root h) + (inside : PreliminarySampler.Questions branch h t m) (external : OutsideQuestions p t m) + (leaf : Slots branch h) : + join p inside external (p.slotEmbedding leaf) = inside leaf := by + have hleaf : p.slotEmbedding leaf ∈ Set.range p.slotEmbedding := ⟨leaf, rfl⟩ + have hchoose : Classical.choose hleaf = leaf := + p.slotEmbedding_injective (Classical.choose_spec hleaf) + simp only [join, dite_eq_left hleaf, hchoose] + +@[simp] theorem join_outside (p : Path branch root h) + (inside : PreliminarySampler.Questions branch h t m) (external : OutsideQuestions p t m) + (leaf : OutsideLeaf p) : + join p inside external leaf.val = external leaf := by + simp only [join, dite_eq_right leaf.property] + +theorem join_restrict (p : Path branch root h) + (q : PreliminarySampler.Questions branch root t m) : + join p (restrict p q) (outside p q) = q := by + funext leaf + by_cases hleaf : leaf ∈ Set.range p.slotEmbedding + · simp only [join, dite_eq_left hleaf, restrict, Classical.choose_spec hleaf] + · simp only [join, dite_eq_right hleaf, outside] + +def splitEquiv (p : Path branch root h) : + PreliminarySampler.Questions branch root t m ≃ + PreliminarySampler.Questions branch h t m × OutsideQuestions p t m where + toFun q := (restrict p q, outside p q) + invFun parts := join p parts.1 parts.2 + left_inv q := join_restrict p q + right_inv parts := by + apply Prod.ext + · funext leaf + exact join_at_cut p parts.1 parts.2 leaf + · funext leaf + exact join_outside p parts.1 parts.2 leaf + +@[simp] theorem splitEquiv_apply (p : Path branch root h) + (q : PreliminarySampler.Questions branch root t m) : + splitEquiv p q = (restrict p q, outside p q) := rfl + +@[simp] theorem splitEquiv_symm_apply (p : Path branch root h) + (inside : PreliminarySampler.Questions branch h t m) (external : OutsideQuestions p t m) : + (splitEquiv p).symm (inside, external) = join p inside external := rfl + +theorem split_law [NeZero m] (p : Path branch root h) : + (PreliminarySampler.questionsLaw (branch := branch) (n := root) (t := t) (m := m)).pushforward + (splitEquiv p) = + (PreliminarySampler.questionsLaw (branch := branch) (n := h) (t := t) (m := m)).product + (FiniteDistribution.uniform (OutsideQuestions p t m)) := by + rw [FiniteDistribution.pushforward_equiv] + apply FiniteDistribution.eq_of_weight_eq + intro pair + change 1 / (Fintype.card (PreliminarySampler.Questions branch root t m) : ℝ) = + (1 / (Fintype.card (PreliminarySampler.Questions branch h t m) : ℝ)) * + (1 / (Fintype.card (OutsideQuestions p t m) : ℝ)) + rw [Fintype.card_congr (splitEquiv (t := t) (m := m) p), Fintype.card_prod, + Nat.cast_mul, one_div_mul_one_div] + +theorem join_eq_fill (p : Path branch root h) + (q : PreliminarySampler.Questions branch root t m) + (inside : PreliminarySampler.Questions branch h t m) : + join p inside (outside p q) = CutSlotAssembly.fill p q inside := by + funext leaf + by_cases hleaf : leaf ∈ Set.range p.slotEmbedding + · obtain ⟨s, rfl⟩ := hleaf + exact (join_at_cut p inside (outside p q) s).trans + (CutSlotAssembly.fill_at_cut p q inside s).symm + · exact (join_outside p inside (outside p q) ⟨leaf, hleaf⟩).trans + (CutSlotAssembly.fill_outside p q inside leaf hleaf).symm + +variable {v : Nat} (clauses : Fin m → SourceClause.NormalizedClause v) + +theorem sourceSlots_restrict (p : Path branch root h) + (q : PreliminarySampler.Questions branch root t m) : + HierarchicalArrays.sourceSlots clauses (PreliminarySampler.endpoints (restrict p q)) = + fun leaf j => HierarchicalArrays.sourceSlots clauses + (PreliminarySampler.endpoints q) (p.slotEmbedding leaf) j := rfl + +theorem sourceSlots_fill (p : Path branch root h) + (q : PreliminarySampler.Questions branch root t m) + (inside : PreliminarySampler.Questions branch h t m) : + HierarchicalArrays.sourceSlots clauses + (PreliminarySampler.endpoints (CutSlotAssembly.fill p q inside)) = + CutSlotAssembly.fill p + (HierarchicalArrays.sourceSlots clauses (PreliminarySampler.endpoints q)) + (HierarchicalArrays.sourceSlots clauses (PreliminarySampler.endpoints inside)) := by + funext leaf j + by_cases hleaf : leaf ∈ Set.range p.slotEmbedding + · obtain ⟨s, rfl⟩ := hleaf + exact (congrArg (fun row : Fin t → Fin m => SourceKeys.slot clauses (.clause (row j))) + (CutSlotAssembly.fill_at_cut p q inside s)).trans + (congrFun (CutSlotAssembly.fill_at_cut p + (HierarchicalArrays.sourceSlots clauses (PreliminarySampler.endpoints q)) + (HierarchicalArrays.sourceSlots clauses (PreliminarySampler.endpoints inside)) s) j).symm + · exact (congrArg (fun row : Fin t → Fin m => SourceKeys.slot clauses (.clause (row j))) + (CutSlotAssembly.fill_outside p q inside leaf hleaf)).trans + (congrFun (CutSlotAssembly.fill_outside p + (HierarchicalArrays.sourceSlots clauses (PreliminarySampler.endpoints q)) + (HierarchicalArrays.sourceSlots clauses (PreliminarySampler.endpoints inside)) leaf hleaf) j).symm + +theorem sourceSlots_join (p : Path branch root h) + (q : PreliminarySampler.Questions branch root t m) + (inside : PreliminarySampler.Questions branch h t m) : + HierarchicalArrays.sourceSlots clauses (PreliminarySampler.endpoints (join p inside (outside p q))) = + CutSlotAssembly.fill p + (HierarchicalArrays.sourceSlots clauses (PreliminarySampler.endpoints q)) + (HierarchicalArrays.sourceSlots clauses (PreliminarySampler.endpoints inside)) := by + rw [join_eq_fill] + exact sourceSlots_fill clauses p q inside + +end +end PerfectCompleteness.SourceQuestionCutSplit + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/SourceQuestionKernelJoint.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/SourceQuestionKernelJoint.lean new file mode 100644 index 0000000000000000000000000000000000000000..d10b6564b1282b60f4945aa0318691babd2eca27 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/SourceQuestionKernelJoint.lean @@ -0,0 +1,125 @@ +import OAI.Computability.PerfectCompleteness.Construction.SourceChildKernelLemmas +import OAI.Computability.PerfectCompleteness.Construction.SourceQuestionPositionSplit + +namespace OAI + +section + +namespace PerfectCompleteness.SourceQuestionKernelJoint + +open scoped Classical +open RecursiveSpaces SourceQuestionPositionSplit +open UniqueGamesTheorem.Foundations.Games + +noncomputable section + +private theorem kernelJoint_pushforward_first {S T R : Type*} + [Fintype S] [Fintype T] [Fintype R] + (μ : FiniteDistribution S) (kernel : S → FiniteDistribution R) (e : S ≃ T) : + (CleanConditioning.kernelJoint μ kernel).pushforward + (Equiv.prodCongr e (Equiv.refl R)) = + CleanConditioning.kernelJoint (μ.pushforward e) (fun s => kernel (e.symm s)) := by + simp only [FiniteDistribution.pushforward_equiv] + apply FiniteDistribution.eq_of_weight_eq + intro point + rfl + +variable {branch : Nat → Nat} {n t v m : Nat} + +abbrev ChoiceTuple := + Fin (branch n) → ChildPositions (branch := branch) (n := n) (t := t) + +def sourceEquiv (designated : Fin (branch n) → Slots branch n) : + SourceChildKernel.Sources (m := m) (t := t) designated ≃ + Questions (branch := branch) (n := n) (t := t) (m := m) × + ChoiceTuple (branch := branch) (n := n) (t := t) := + (SourceQuestionPositionSplit.split designated).trans + (Equiv.prodCongr (Equiv.refl _) SourceQuestionPositionSplit.byChild) + +def sources (designated : Fin (branch n) → Slots branch n) + (q : Questions (branch := branch) (n := n) (t := t) (m := m)) + (choices : ChoiceTuple (branch := branch) (n := n) (t := t)) : + SourceChildKernel.Sources (m := m) (t := t) designated := + (sourceEquiv designated).symm (q, choices) + +@[simp] theorem sources_eq_join (designated : Fin (branch n) → Slots branch n) + (q : Questions (branch := branch) (n := n) (t := t) (m := m)) + (choices : ChoiceTuple (branch := branch) (n := n) (t := t)) : + sources designated q choices = + SourceQuestionPositionSplit.join designated q + (SourceQuestionPositionSplit.byChild.symm choices) := rfl + +theorem sourceLaw_sourceEquiv [NeZero m] + (designated : Fin (branch n) → Slots branch n) : + (SourceChildQuestionLaw.sourceLaw m t designated).pushforward (sourceEquiv designated) = + (PreliminarySampler.questionsLaw (branch := branch) (n := n + 1) (t := t) (m := m)).product + (FiniteProduct.law (fun _ : Fin (branch n) => + FiniteDistribution.uniform (ChildPositions (branch := branch) (n := n) (t := t)))) := by + calc + _ = ((SourceChildQuestionLaw.sourceLaw m t designated).pushforward + (SourceQuestionPositionSplit.split designated)).pushforward + (Equiv.prodCongr (Equiv.refl _) SourceQuestionPositionSplit.byChild) := by + rw [FiniteDistribution.pushforward_comp] + rfl + _ = _ := by + rw [SourceQuestionPositionSplit.sourceLaw_split] + change ((PreliminarySampler.questionsLaw + (branch := branch) (n := n + 1) (t := t) (m := m)).product + (FiniteDistribution.uniform (Positions (branch := branch) (n := n) (t := t)))).pushforward + (fun x => (id x.1, SourceQuestionPositionSplit.byChild x.2)) = _ + rw [FiniteDistribution.product_pushforward, FiniteDistribution.pushforward_id, + SourceQuestionPositionSplit.positions_byChild] + +variable {C : Type*} [Fintype C] + (rows : Nat → Nat) (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch n) → Slots branch n) + +def groupEquiv : + SourceChildKernel.Sample (C := C) (t := t) rows clauses designated ≃ + (Questions (branch := branch) (n := n) (t := t) (m := m) × + ChoiceTuple (branch := branch) (n := n) (t := t)) × + SourceChildKernelJoint.RawTuple (C := C) (t := t) rows clauses designated := + (SourceChildKernelJoint.groupEquiv rows clauses designated).trans + (Equiv.prodCongr (sourceEquiv designated) (Equiv.refl _)) + +@[simp] theorem groupEquiv_raw + (sample : SourceChildKernel.Sample (C := C) (t := t) rows clauses designated) + (i : Fin (branch n)) : + (groupEquiv rows clauses designated sample).2 i = (sample i).2.2 := rfl + +theorem originalLaw_group [NeZero m] + (flag : Fin (branch n) → FiniteDistribution Bool) : + (SourceChildKernel.originalLaw (C := C) (t := t) rows clauses designated flag).pushforward + (groupEquiv rows clauses designated) = + CleanConditioning.kernelJoint + ((PreliminarySampler.questionsLaw + (branch := branch) (n := n + 1) (t := t) (m := m)).product + (FiniteProduct.law (fun _ : Fin (branch n) => + FiniteDistribution.uniform + (ChildPositions (branch := branch) (n := n) (t := t))))) + (fun qp => FiniteProduct.law (fun i => + SourceChildKernel.kernel (C := C) (t := t) rows clauses designated flag i + (sources designated qp.1 qp.2 i))) := by + calc + _ = ((SourceChildKernel.originalLaw (C := C) (t := t) rows clauses designated flag).pushforward + (SourceChildKernelJoint.groupEquiv rows clauses designated)).pushforward + (Equiv.prodCongr (sourceEquiv designated) (Equiv.refl _)) := by + rw [FiniteDistribution.pushforward_comp] + rfl + _ = (CleanConditioning.kernelJoint (SourceChildQuestionLaw.sourceLaw m t designated) + (fun source => FiniteProduct.law (fun i => + SourceChildKernel.kernel (C := C) (t := t) rows clauses designated flag i + (source i)))).pushforward + (Equiv.prodCongr (sourceEquiv designated) (Equiv.refl _)) := by + rw [SourceChildKernelJoint.originalLaw_group] + rfl + _ = _ := by + rw [kernelJoint_pushforward_first, sourceLaw_sourceEquiv] + rfl + +end +end PerfectCompleteness.SourceQuestionKernelJoint + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/SourceQuestionOrderLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/SourceQuestionOrderLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..6b95b80723dcbb9136144d919ecf9a2f4abdf50f --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/SourceQuestionOrderLemmas.lean @@ -0,0 +1,506 @@ +import Mathlib.Algebra.BigOperators.Group.Finset.Basic +import Mathlib.Data.List.FinRange +import OAI.Computability.PerfectCompleteness.Construction.HiddenChildMixture +import OAI.Computability.PerfectCompleteness.Construction.TreeCanonical +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalArrays +import OAI.Computability.PerfectCompleteness.Foundations.KeyFiniteness +import OAI.Computability.PerfectCompleteness.Machines.TupleIndexMachine +import OAI.Computability.PerfectCompleteness.Sampling.CommonProductVariationLemmas +import OAI.Computability.PerfectCompleteness.Sampling.PreliminarySampler +import OAI.Computability.PerfectCompleteness.Sampling.RationalFiniteLawLemmas +import OAI.Computability.PerfectCompleteness.Sampling.UniformDensity +import OAI.Computability.UniqueGames.Foundations.MixtureLemmas + +namespace OAI + + +namespace PerfectCompleteness.SourceQuestionOrder + +open Turing UniqueGamesTheorem.Foundations.Complexity +open scoped BigOperators Classical + +noncomputable section + +variable {branch : Nat → Nat} {n t m : Nat} + +def questionToTuple (question : PreliminarySampler.Questions branch n t m) : + Fin (TreeCanonical.locationCount branch n t) → Fin m := + fun j => question ((TreeCanonical.numbering branch n t).symm j).1 + ((TreeCanonical.numbering branch n t).symm j).2 + +def tupleToQuestion (tuple : Fin (TreeCanonical.locationCount branch n t) → Fin m) : + PreliminarySampler.Questions branch n t m := + fun leaf coordinate => tuple (TreeCanonical.numbering branch n t (leaf, coordinate)) + +@[simp] theorem tupleToQuestion_questionToTuple + (question : PreliminarySampler.Questions branch n t m) : + tupleToQuestion (questionToTuple question) = question := by + funext leaf coordinate + simp only [tupleToQuestion, questionToTuple, Equiv.symm_apply_apply] + +@[simp] theorem questionToTuple_tupleToQuestion + (tuple : Fin (TreeCanonical.locationCount branch n t) → Fin m) : + questionToTuple (tupleToQuestion (branch := branch) (n := n) (t := t) tuple) = tuple := by + funext j + simp only [questionToTuple, tupleToQuestion, Prod.mk.eta, Equiv.apply_symm_apply] + +def questionTupleEquiv (branch : Nat → Nat) (n t m : Nat) : + PreliminarySampler.Questions branch n t m ≃ + (Fin (TreeCanonical.locationCount branch n t) → Fin m) where + toFun := questionToTuple + invFun := tupleToQuestion + left_inv := tupleToQuestion_questionToTuple + right_inv := questionToTuple_tupleToQuestion + +def sourceOrder (branch : Nat → Nat) (n t m : Nat) : + List (PreliminarySampler.Questions branch n t m) := + (MachineTupleOdometer.tupleOrder m (TreeCanonical.locationCount branch n t)).reverse.map + tupleToQuestion + +@[simp] theorem sourceOrder_length (branch : Nat → Nat) (n t m : Nat) : + (sourceOrder branch n t m).length = m ^ TreeCanonical.locationCount branch n t := by + simp only [sourceOrder, List.length_map, List.length_reverse, + MachineTupleOdometer.tupleOrder_length] + +theorem sourceOrder_nodup (branch : Nat → Nat) (n t m : Nat) : + (sourceOrder branch n t m).Nodup := by + apply List.Nodup.map (questionTupleEquiv branch n t m).symm.injective + apply List.nodup_reverse.mpr + exact List.nodup_ofFn.mpr + (finFunctionFinEquiv (m := m) (n := TreeCanonical.locationCount branch n t)).symm.injective + +theorem mem_sourceOrder (question : PreliminarySampler.Questions branch n t m) : + question ∈ sourceOrder branch n t m := by + apply List.mem_map.mpr + refine ⟨questionToTuple question, ?_, tupleToQuestion_questionToTuple question⟩ + rw [List.mem_reverse] + change questionToTuple question ∈ List.ofFn + (finFunctionFinEquiv (m := m) (n := TreeCanonical.locationCount branch n t)).symm + apply List.mem_ofFn.mpr + exact ⟨finFunctionFinEquiv (questionToTuple question), Equiv.symm_apply_apply _ _⟩ + +@[simp] theorem sourceOrder_toFinset (branch : Nat → Nat) (n t m : Nat) : + (sourceOrder branch n t m).toFinset = Finset.univ := by + ext question + simp only [List.mem_toFinset, Finset.mem_univ, iff_true] + exact mem_sourceOrder question + +theorem sum_map_sourceOrder {A : Type*} [AddCommMonoid A] + (f : PreliminarySampler.Questions branch n t m → A) : + ((sourceOrder branch n t m).map f).sum = ∑ question, f question := by + rw [← List.sum_toFinset f (sourceOrder_nodup branch n t m), sourceOrder_toFinset] + +def numberedClauseIDs (question : PreliminarySampler.Questions branch n t m) : List Nat := + List.ofFn (fun j => (questionToTuple question j).val) + +@[simp] theorem numberedClauseIDs_length + (question : PreliminarySampler.Questions branch n t m) : + (numberedClauseIDs question).length = TreeCanonical.locationCount branch n t := by + simp only [numberedClauseIDs, List.length_ofFn] + +@[simp] theorem numberedClauseIDs_tupleToQuestion + (tuple : Fin (TreeCanonical.locationCount branch n t) → Fin m) : + numberedClauseIDs (tupleToQuestion (branch := branch) (n := n) (t := t) tuple) = + List.ofFn (fun j => (tuple j).val) := by + simp only [numberedClauseIDs, questionToTuple_tupleToQuestion] + +theorem outputBlock_all_eq_sourceOrder (branch : Nat → Nat) (n t m : Nat) : + TupleEnumerationMachine.outputBlock (width := TreeCanonical.locationCount branch n t) + m (TreeCanonical.locationCount branch n t) + (fun _ => 0) = + (sourceOrder branch n t m).flatMap (fun question => encodeWords (numberedClauseIDs question)) := by + rw [TupleEnumerationMachine.outputBlock_all] + simp only [sourceOrder, List.flatMap_map, + numberedClauseIDs_tupleToQuestion] + +theorem output_eq_sourceOrder (branch : Nat → Nat) (n t m : Nat) : + TupleIndexMachine.output (TreeCanonical.locationCount branch n t) m = + (sourceOrder branch n t m).flatMap (fun question => encodeWords (numberedClauseIDs question)) := by + exact outputBlock_all_eq_sourceOrder branch n t m + +def sourceOutputsInTime (branch : Nat → Nat) (n t m : Nat) (positive : 0 < m) : + TM2OutputsInTime (TupleIndexMachine.machine (TreeCanonical.locationCount branch n t)) + (encodeWord m) + (some ((sourceOrder branch n t m).flatMap + (fun question => encodeWords (numberedClauseIDs question)))) + (TupleIndexMachine.totalBudget (TreeCanonical.locationCount branch n t) m) := by + exact Eq.mp + (congrArg (fun words : List Bool => + TM2OutputsInTime (TupleIndexMachine.machine (TreeCanonical.locationCount branch n t)) + (encodeWord m) (some words) + (TupleIndexMachine.totalBudget (TreeCanonical.locationCount branch n t) m)) + (output_eq_sourceOrder branch n t m)) + (TupleIndexMachine.outputsInTime (width := TreeCanonical.locationCount branch n t) m positive) + +end + +end PerfectCompleteness.SourceQuestionOrder + + +namespace PerfectCompleteness.TreeCardinality + +open TreeSourceSpaces HierarchicalArrays +open scoped BigOperators + +noncomputable section + +variable {branch : Nat → Nat} {n t : Nat} + +def domainBound (branch : Nat → Nat) (n t : Nat) : Nat := + (7 ^ t) ^ Fintype.card (RecursiveSpaces.Slots branch n) + +def functionBound (branch : Nat → Nat) (n t : Nat) : Nat := + 2 ^ domainBound branch n t + +theorem domain_card_le + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) : + Nat.card (Domain slots) ≤ domainBound branch n t := by + change Nat.card (∀ leaf, LeafDomain slots leaf) ≤ _ + rw [Nat.card_pi] + calc + _ ≤ ∏ _leaf : RecursiveSpaces.Slots branch n, (7 ^ t : Nat) := + Finset.prod_le_prod (fun leaf _ => + CanonicalKeys.card_assignment_le_seven_pow (slots leaf)) + _ = domainBound branch n t := by simp [domainBound] + +theorem subspace_card_le + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (V : Submodule F2 (Domain slots → F2)) : + Nat.card V ≤ functionBound branch n t := by + calc + Nat.card V ≤ Nat.card (Domain slots → F2) := + Nat.card_le_card_of_injective (fun f : V => f.val) Subtype.val_injective + _ = 2 ^ Nat.card (Domain slots) := by rw [Nat.card_fun, Nat.card_zmod] + _ ≤ functionBound branch n t := + pow_le_pow_right₀ (by decide : (1 : Nat) ≤ 2) (domain_card_le slots) + +theorem H_card_le + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) : + Nat.card (H slots) ≤ functionBound branch n t := + subspace_card_le slots (H slots) + +theorem square_card_le + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) : + Nat.card (PointwiseSpaces.squareSpace (H slots)) ≤ functionBound branch n t := + subspace_card_le slots (PointwiseSpaces.squareSpace (H slots)) + +def arraysBound (branch : Nat → Nat) (n t : Nat) (rows : Nat → Nat) : Nat := + ∏ node : Nodes branch n, + functionBound branch (Nodes.height node) t ^ rows (Nodes.height node) + +theorem arrays_card_le + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (rows : Nat → Nat) : + Nat.card (Arrays slots rows) ≤ arraysBound branch n t rows := by + change Nat.card (∀ node : Nodes branch n, + Fin (rows (Nodes.height node)) → H (nodeSlots slots node)) ≤ _ + rw [Nat.card_pi] + apply Finset.prod_le_prod + intro node _ + rw [Nat.card_fun, Nat.card_fin] + exact pow_le_pow_left₀ (Nat.zero_le _) (H_card_le (nodeSlots slots node)) _ + +theorem source_questions_card (m : Nat) : + Nat.card (PreliminarySampler.Questions branch n t m) = + m ^ (t * Fintype.card (RecursiveSpaces.Slots branch n)) := by + simp only [PreliminarySampler.Questions, Nat.card_eq_fintype_card, + Fintype.card_fun, Fintype.card_fin, ← pow_mul] + +theorem source_base_card (m : Nat) : + Nat.card (PreliminarySampler.Base branch n t m) = + m ^ (t * Fintype.card (RecursiveSpaces.Slots branch n)) * + Fintype.card (RecursiveSpaces.Slots branch n) := by + rw [Nat.card_prod, source_questions_card, Nat.card_eq_fintype_card] + +end +end PerfectCompleteness.TreeCardinality + + +namespace PerfectCompleteness.ChildBlockCardinality + +open RecursiveSpaces TreeSourceSpaces HierarchicalArrays PointwiseSpaces +open UniqueGamesTheorem.Foundations.Games + +noncomputable section + +variable {branch : Nat → Nat} {n t : Nat} + +abbrev Raw (calls : Nat) (rows : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) := + (Fin calls → squareSpace (H slots)) × Arrays slots rows + +instance rawFintype (calls : Nat) (rows : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Fintype (Raw calls rows slots) := Fintype.ofFinite _ + +instance rawNonempty (calls : Nat) (rows : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Nonempty (Raw calls rows slots) := ⟨(fun _ => 0, fun _ _ => 0)⟩ + +def bound (branch : Nat → Nat) (n t calls : Nat) (rows : Nat → Nat) : Nat := + TreeCardinality.functionBound branch n t ^ calls * + TreeCardinality.arraysBound branch n t rows + +theorem card_le (calls : Nat) (rows : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Nat.card (Raw calls rows slots) ≤ bound branch n t calls rows := by + rw [Nat.card_prod, Nat.card_fun, Nat.card_fin] + exact Nat.mul_le_mul + (pow_le_pow_left₀ (Nat.zero_le _) (TreeCardinality.square_card_le slots) calls) + (TreeCardinality.arrays_card_le slots rows) + +theorem fintype_card_le (calls : Nat) (rows : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Fintype.card (Raw calls rows slots) ≤ bound branch n t calls rows := by + simpa only [Nat.card_eq_fintype_card] using card_le calls rows slots + +theorem bound_pos (calls : Nat) (rows : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + 0 < bound branch n t calls rows := + lt_of_lt_of_le (Nat.card_pos (α := Raw calls rows slots)) (card_le calls rows slots) + +def density {calls : Nat} {rows : Nat → Nat} + {slots : Slots branch n → Fin t → MixedSupport.Slot} + (μ : FiniteDistribution (Raw calls rows slots)) : Raw calls rows slots → ℝ := + UniformDensity.density μ + +theorem weight_eq {calls : Nat} {rows : Nat → Nat} + {slots : Slots branch n → Fin t → MixedSupport.Slot} + (μ : FiniteDistribution (Raw calls rows slots)) (x : Raw calls rows slots) : + μ.weight x = (FiniteDistribution.uniform (Raw calls rows slots)).weight x * density μ x := + UniformDensity.weight_eq μ x + +theorem mean_one {calls : Nat} {rows : Nat → Nat} + {slots : Slots branch n → Fin t → MixedSupport.Slot} + (μ : FiniteDistribution (Raw calls rows slots)) : + (FiniteDistribution.uniform (Raw calls rows slots)).expectation (density μ) = 1 := + UniformDensity.mean_one μ + +theorem density_le {calls : Nat} {rows : Nat → Nat} + {slots : Slots branch n → Fin t → MixedSupport.Slot} + (μ : FiniteDistribution (Raw calls rows slots)) (x : Raw calls rows slots) : + density μ x ≤ (bound branch n t calls rows : ℝ) := + (UniformDensity.density_le_card μ x).trans + (by exact_mod_cast fintype_card_le calls rows slots) + +theorem second_moment_le {calls : Nat} {rows : Nat → Nat} + {slots : Slots branch n → Fin t → MixedSupport.Slot} + (μ : FiniteDistribution (Raw calls rows slots)) : + (FiniteDistribution.uniform (Raw calls rows slots)).expectation + (fun x => (density μ x - 1) ^ 2) ≤ (bound branch n t calls rows : ℝ) ^ 2 := by + apply UniformDensity.second_moment_le + exact_mod_cast fintype_card_le calls rows slots + +end +end PerfectCompleteness.ChildBlockCardinality + + +namespace PerfectCompleteness.ChildBlockMixture + +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators + +noncomputable section + +section General + +variable {I : Type*} [Fintype I] [DecidableEq I] [Nonempty I] + {Ω : I → Type*} [∀ i, Fintype (Ω i)] [∀ i, Nonempty (Ω i)] + +def component (Q : (i : I) → FiniteDistribution (Ω i)) (chosen i : I) : + FiniteDistribution (Ω i) := + if h : chosen = i then h ▸ Q chosen else FiniteDistribution.uniform (Ω i) + +def reference : FiniteDistribution ((i : I) → Ω i) := + FiniteProduct.law (fun i => FiniteDistribution.uniform (Ω i)) + +def special (Q : (i : I) → FiniteDistribution (Ω i)) (chosen : I) : + FiniteDistribution ((i : I) → Ω i) := + FiniteProduct.law (component Q chosen) + +def mixture (Q : (i : I) → FiniteDistribution (Ω i)) : + FiniteDistribution ((i : I) → Ω i) := + HiddenChildMixture.mixture (special Q) + +omit [Fintype I] [Nonempty I] in +theorem component_weight (Q : (i : I) → FiniteDistribution (Ω i)) + (chosen i : I) (x : Ω i) : + (component Q chosen i).weight x = + (FiniteDistribution.uniform (Ω i)).weight x * + FiniteProduct.factor chosen (UniformDensity.density (Q chosen)) i x := by + by_cases h : i = chosen + · subst i + simp only [component, FiniteProduct.factor_self] + exact UniformDensity.weight_eq (Q chosen) x + · simp only [component, dite_eq_right (Ne.symm h), + FiniteProduct.factor_other chosen i h, mul_one] + +omit [Nonempty I] in +theorem special_weight (Q : (i : I) → FiniteDistribution (Ω i)) + (chosen : I) (x : (i : I) → Ω i) : + (special Q chosen).weight x = (reference (Ω := Ω)).weight x * + UniformDensity.density (Q chosen) (x chosen) := by + change (∏ i, (component Q chosen i).weight (x i)) = + (∏ i, (FiniteDistribution.uniform (Ω i)).weight (x i)) * _ + simp_rw [component_weight] + rw [Finset.prod_mul_distrib, FiniteProduct.product_factor] + +theorem observed_variation {Γ : Type*} [Fintype Γ] + (Q : (i : I) → FiniteDistribution (Ω i)) (L : ℝ) + (hcard : ∀ i, (Fintype.card (Ω i) : ℝ) ≤ L) + (observe : ((i : I) → Ω i) → Γ) : + ((mixture Q).pushforward observe).totalVariation + ((reference (Ω := Ω)).pushforward observe) ≤ + Real.sqrt (L ^ 2 / Fintype.card I) / 2 := by + apply HiddenChildMixture.observed_mixture_variation + (fun i => FiniteDistribution.uniform (Ω i)) (special Q) + (fun i => UniformDensity.density (Q i)) + · exact special_weight Q + · intro i + exact UniformDensity.mean_one (Q i) + · intro i + exact UniformDensity.second_moment_le (Q i) L (hcard i) + +end General + +theorem actual_observed_variation + {I : Type*} [Fintype I] [DecidableEq I] [Nonempty I] + {branch : Nat → Nat} {n t : Nat} (calls : Nat) (rows : Nat → Nat) + (slots : I → RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (Q : (i : I) → FiniteDistribution (ChildBlockCardinality.Raw calls rows (slots i))) + {Γ : Type*} [Fintype Γ] + (observe : ((i : I) → ChildBlockCardinality.Raw calls rows (slots i)) → Γ) : + ((mixture Q).pushforward observe).totalVariation + ((reference (Ω := fun i => ChildBlockCardinality.Raw calls rows (slots i))).pushforward + observe) ≤ + Real.sqrt ((ChildBlockCardinality.bound branch n t calls rows : ℝ) ^ 2 / + Fintype.card I) / 2 := by + apply observed_variation Q + intro i + exact_mod_cast ChildBlockCardinality.fintype_card_le calls rows (slots i) + +end +end PerfectCompleteness.ChildBlockMixture + + +namespace PerfectCompleteness.ChildBlockMixture + +open UniqueGamesTheorem.Foundations.Games + +noncomputable section + +theorem conditional_actual_observed_variation + {S I : Type*} [Fintype S] [Fintype I] [DecidableEq I] [Nonempty I] + {branch : Nat → Nat} {n t : Nat} (calls : Nat) (rows : Nat → Nat) + (slots : S → I → RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (μ : FiniteDistribution S) + (Q : (s : S) → (i : I) → + FiniteDistribution (ChildBlockCardinality.Raw calls rows (slots s i))) + {Γ : Type*} [Fintype Γ] + (observe : (Σ s : S, (i : I) → ChildBlockCardinality.Raw calls rows (slots s i)) → Γ) : + ((CompletionSoundness.sigmaLaw μ (fun s => mixture (Q s))).pushforward observe).totalVariation + ((CompletionSoundness.sigmaLaw μ + (fun s => reference (Ω := fun i => ChildBlockCardinality.Raw calls rows (slots s i)))).pushforward observe) ≤ + Real.sqrt ((ChildBlockCardinality.bound branch n t calls rows : ℝ) ^ 2 / + Fintype.card I) / 2 := by + refine ConditionalVariation.observed_sigma_le_const μ + (fun s => mixture (Q s)) + (fun s => reference (Ω := fun i => ChildBlockCardinality.Raw calls rows (slots s i))) + _ ?_ observe + intro s + simpa only [FiniteDistribution.pushforward_id] using + actual_observed_variation calls rows (slots s) (Q s) + (id : ((i : I) → ChildBlockCardinality.Raw calls rows (slots s i)) → + ((i : I) → ChildBlockCardinality.Raw calls rows (slots s i))) + +end +end PerfectCompleteness.ChildBlockMixture + + +namespace PerfectCompleteness.ChildBlockContinuation + +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators + +noncomputable section + +variable {I : Type*} [Fintype I] [DecidableEq I] [Nonempty I] + {Ω : I → Type*} [∀ i, Fintype (Ω i)] [∀ i, Nonempty (Ω i)] + {T : I → Type*} [∀ i, Fintype (T i)] + +def continuedSpecial (Q : (i : I) → T i → FiniteDistribution (Ω i)) + (chosen : I) (t : T chosen) : FiniteDistribution ((i : I) → Ω i) := + ChildBlockMixture.special + (Function.update (fun i => FiniteDistribution.uniform (Ω i)) chosen (Q chosen t)) + chosen + +omit [Nonempty I] [∀ i, Fintype (T i)] in +theorem continuedSpecial_eq_product + (Q : (i : I) → T i → FiniteDistribution (Ω i)) (chosen : I) (t : T chosen) : + continuedSpecial Q chosen t = FiniteProduct.law + (fun i => if h : chosen = i then h ▸ Q chosen t else + FiniteDistribution.uniform (Ω i)) := by + unfold continuedSpecial ChildBlockMixture.special + apply congrArg (fun P : (i : I) → FiniteDistribution (Ω i) => FiniteProduct.law P) + funext i + by_cases h : chosen = i + · subst i + simp only [ChildBlockMixture.component, Function.update_self] + · simp only [ChildBlockMixture.component, dite_eq_right h] + +omit [Nonempty I] [∀ i, Fintype (T i)] in +theorem continuedSpecial_weight + (Q : (i : I) → T i → FiniteDistribution (Ω i)) + (chosen : I) (t : T chosen) (x : (i : I) → Ω i) : + (continuedSpecial Q chosen t).weight x = + (ChildBlockMixture.reference (Ω := Ω)).weight x * + UniformDensity.density (Q chosen t) (x chosen) := by + unfold continuedSpecial + rw [ChildBlockMixture.special_weight, Function.update_self] + +omit [Nonempty I] in +theorem average_special (P : (i : I) → FiniteDistribution (T i)) + (Q : (i : I) → T i → FiniteDistribution (Ω i)) (chosen : I) : + (P chosen).mixture (continuedSpecial Q chosen) = + ChildBlockMixture.special (fun i => (P i).mixture (Q i)) chosen := by + apply FiniteDistribution.eq_of_weight_eq + intro x + change (∑ t, (P chosen).weight t * (continuedSpecial Q chosen t).weight x) = _ + simp_rw [continuedSpecial_weight] + rw [ChildBlockMixture.special_weight] + change (∑ t, (P chosen).weight t * + ((ChildBlockMixture.reference (Ω := Ω)).weight x * + ((Fintype.card (Ω chosen) : ℝ) * (Q chosen t).weight (x chosen)))) = + (ChildBlockMixture.reference (Ω := Ω)).weight x * + ((Fintype.card (Ω chosen) : ℝ) * + ∑ t, (P chosen).weight t * (Q chosen t).weight (x chosen)) + simp only [Finset.mul_sum] + apply Finset.sum_congr rfl + intro t _ + ring + +theorem hidden_average (P : (i : I) → FiniteDistribution (T i)) + (Q : (i : I) → T i → FiniteDistribution (Ω i)) : + HiddenChildMixture.mixture (fun i => (P i).mixture (continuedSpecial Q i)) = + ChildBlockMixture.mixture (fun i => (P i).mixture (Q i)) := by + simp only [average_special, ChildBlockMixture.mixture] + +theorem uniform_average (P : (i : I) → FiniteDistribution (T i)) + (Q : (i : I) → T i → FiniteDistribution (Ω i)) : + (FiniteDistribution.uniform I).mixture + (fun i => (P i).mixture (continuedSpecial Q i)) = + ChildBlockMixture.mixture (fun i => (P i).mixture (Q i)) := by + simp only [average_special] + apply FiniteDistribution.eq_of_weight_eq + intro x + change (∑ i, (1 / (Fintype.card I : ℝ)) * + (ChildBlockMixture.special (fun j => (P j).mixture (Q j)) i).weight x) = + (∑ i, (ChildBlockMixture.special (fun j => (P j).mixture (Q j)) i).weight x) / + (Fintype.card I : ℝ) + rw [← Finset.mul_sum] + ring + +end +end PerfectCompleteness.ChildBlockContinuation + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/SourceQuestionPairPullback.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/SourceQuestionPairPullback.lean new file mode 100644 index 0000000000000000000000000000000000000000..0cdc88425630f4a5be4c5e3c11f734bab6d91418 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/SourceQuestionPairPullback.lean @@ -0,0 +1,214 @@ +import OAI.Computability.PerfectCompleteness.Construction.SourceQuestionPhysicalHigh +import OAI.Computability.PerfectCompleteness.Decoding.LowerCutFiberDisintegrationLemmas +import OAI.Computability.PerfectCompleteness.Decoding.WholeCutGroupedProjection + +namespace OAI + +section + +namespace PerfectCompleteness.SourceQuestionPairPullback + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open WholeArrayInteriorExterior + +variable {branch : Nat → Nat} {n height t : Nat} + +def rawAtCut (rows repeats : Nat → Nat) (path : Path branch n (height + 1)) + (outside : Slots branch n → Fin t → MixedSupport.Slot) + (inside : Slots branch (height + 1) → Fin t → MixedSupport.Slot) + (raw : CutCallExtension.Extended + (C := WholeCutCalls.Index rows repeats path) inside rows) : + LowerCutPair.Raw rows repeats path (CutSlotAssembly.fill path outside inside) := + SourceQuestionLowerForms.rawCast rows + (CleanPhysicalReplay.cutSlots_fill path outside inside).symm raw + +theorem selectedRows_pullback (rows : Nat → Nat) : + {n height : Nat} → (path : Path branch n (height + 1)) → + (left right : Slots branch n → Fin t → MixedSupport.Slot) → + (p : ∀ leaf j, MixedSupport.Projection (left leaf j) (right leaf j)) → + (arrays : Arrays right rows) → + SelectedArrayReplacement.selectedRows rows path left + (ChildBlockProjection.arraysPullback rows p arrays) = + (fun i => HPullback (CutGroupedProjection.cutProjection path p) + (SelectedArrayReplacement.selectedRows rows path right arrays i)) + | _, _, .refl _, _, _, _, _ => rfl + | _, _, .step child path, left, right, p, arrays => + selectedRows_pullback rows path (childSlots left child) (childSlots right child) + (fun leaf j => p (child, leaf) j) (fun node => arrays (.inr (child, node))) + +section Grouped + +variable (rows repeats : Nat → Nat) (path : Path branch n (height + 1)) + (left right : Slots branch n → Fin t → MixedSupport.Slot) + (p : ∀ leaf j, MixedSupport.Projection (left leaf j) (right leaf j)) + (hs : ∀ leaf, WholeCutExteriorTransport.Outside path leaf → left leaf = right leaf) + (hk : ∀ leaf, WholeCutExteriorTransport.Outside path leaf → ∀ j, + HEq (p leaf j) (MixedSupport.Projection.keep (left leaf j))) + (exterior : WholeCutGrouping.Exterior rows repeats path right) + +include hk in + +theorem first_grouped_pullback (raw : LowerCutPair.Raw rows repeats path right) : + ChildBlockProjection.arraysPullback rows p + (LowerCutPair.first rows repeats path right exterior raw) = + LowerCutPair.first rows repeats path left + (WholeCutExteriorTransport.equiv rows repeats path right left + (fun leaf h => (hs leaf h).symm) exterior) + (ChildAssemblyProjection.rawPullback rows + (CutGroupedProjection.cutProjection path p) raw) := by + symm + change WholeCutGroupedProjection.evaluateGrouped rows repeats path left _ + (CutCallExtension.original (WholeCutGrouping.cutSlots path left) rows + (ChildAssemblyProjection.rawPullback rows + (CutGroupedProjection.cutProjection path p) raw)) = + ChildBlockProjection.arraysPullback rows p + (WholeCutGroupedProjection.evaluateGrouped rows repeats path right exterior + (CutCallExtension.original (WholeCutGrouping.cutSlots path right) rows raw)) + rw [LowerCutProjection.original_pullback] + exact WholeCutGroupedProjection.evaluateGrouped_pullback rows repeats path + left right p hs hk exterior _ + +include hk in + +theorem second_grouped_pullback + (direction : BucketSampler.Direction (rows (height + 1))) + (raw : LowerCutPair.Raw rows repeats path right) : + ChildBlockProjection.arraysPullback rows p + (LowerCutPair.second rows repeats path right exterior direction raw) = + LowerCutPair.second rows repeats path left + (WholeCutExteriorTransport.equiv rows repeats path right left + (fun leaf h => (hs leaf h).symm) exterior) direction + (ChildAssemblyProjection.rawPullback rows + (CutGroupedProjection.cutProjection path p) raw) := by + let exterior' := WholeCutExteriorTransport.equiv rows repeats path right left + (fun leaf h => (hs leaf h).symm) exterior + have hselected : + SelectedArrayReplacement.selectedRows rows path left + (ChildBlockProjection.arraysPullback rows p + (LowerCutPair.second rows repeats path right exterior direction raw)) = + SelectedArrayReplacement.selectedRows rows path left + (LowerCutPair.second rows repeats path left exterior' direction + (ChildAssemblyProjection.rawPullback rows + (CutGroupedProjection.cutProjection path p) raw)) := by + rw [selectedRows_pullback] + exact (congrArg Prod.snd + (LowerCutProjection.selectedPair_pullback rows repeats path + (CutGroupedProjection.cutProjection path p) exterior' exterior direction raw)).symm + funext node + by_cases hnode : node = upperNode path + · subst node + simpa only [LowerCutNodeCoordinates.rowEquiv_selectedRows] using + congrArg (LowerCutNodeCoordinates.rowEquiv rows path left) hselected + · funext row + change HPullback (ChildBlockProjection.nodeProjection p node) + (LowerCutPair.second rows repeats path right exterior direction raw node row) = + LowerCutPair.second rows repeats path left exterior' direction + (ChildAssemblyProjection.rawPullback rows + (CutGroupedProjection.cutProjection path p) raw) node row + rw [LowerCutPair.second_outside rows repeats path right exterior direction raw node hnode, + LowerCutPair.second_outside rows repeats path left exterior' direction _ node hnode] + exact congrFun (congrFun + (first_grouped_pullback rows repeats path left right p hs hk exterior raw) node) row + +end Grouped + +section Filled + +private theorem rawCast_child_heq {C : Type*} [Fintype C] (rows : Nat → Nat) + {source target : Slots branch (height + 1) → Fin t → MixedSupport.Slot} + (h : source = target) (raw : CutChildGrouping.Raw (C := C) source rows) + (i : Fin (branch height)) : + HEq ((SourceQuestionLowerForms.rawCast rows h raw) i) (raw i) := by + cases h + rfl + +theorem rawAtCut_pullback (rows repeats : Nat → Nat) + (path : Path branch n (height + 1)) + (outside : Slots branch n → Fin t → MixedSupport.Slot) + (left right : Slots branch (height + 1) → Fin t → MixedSupport.Slot) + (p : ∀ leaf j, MixedSupport.Projection (left leaf j) (right leaf j)) + (raw : CutCallExtension.Extended + (C := WholeCutCalls.Index rows repeats path) right rows) : + rawAtCut rows repeats path outside left + (ChildAssemblyProjection.rawPullback rows p raw) = + ChildAssemblyProjection.rawPullback rows + (CutGroupedProjection.cutProjection path + (CutProjectionAssembly.fillProjection path outside left right p)) + (rawAtCut rows repeats path outside right raw) := by + funext i + apply eq_of_heq + exact (rawCast_child_heq rows + (CleanPhysicalReplay.cutSlots_fill path outside left).symm + (ChildAssemblyProjection.rawPullback rows p raw) i).trans + (CutProjectionGeometry.childPullback_heq rows + (CleanPhysicalReplay.cutSlots_fill path outside left) + (CleanPhysicalReplay.cutSlots_fill path outside right) + (CutGroupedProjection.cutProjection path + (CutProjectionAssembly.fillProjection path outside left right p)) p + (CutProjectionAssembly.fillProjection_at_cut path outside left right p) i + (rawAtCut rows repeats path outside right raw i) (raw i) + (rawCast_child_heq rows + (CleanPhysicalReplay.cutSlots_fill path outside right).symm raw i)).symm + +variable (rows repeats : Nat → Nat) (path : Path branch n (height + 1)) + (outside : Slots branch n → Fin t → MixedSupport.Slot) + (placeholder left right : Slots branch (height + 1) → Fin t → MixedSupport.Slot) + (p : ∀ leaf j, MixedSupport.Projection (left leaf j) (right leaf j)) + (exterior : CleanPhysicalReplay.Exterior rows repeats path outside placeholder) + +theorem first_pullback + (raw : CutCallExtension.Extended + (C := WholeCutCalls.Index rows repeats path) right rows) : + ChildBlockProjection.arraysPullback rows + (CutProjectionAssembly.fillProjection path outside left right p) + (LowerCutPair.first rows repeats path (CutSlotAssembly.fill path outside right) + (CleanPhysicalReplay.exteriorAt rows repeats path outside placeholder right exterior) + (rawAtCut rows repeats path outside right raw)) = + LowerCutPair.first rows repeats path (CutSlotAssembly.fill path outside left) + (CleanPhysicalReplay.exteriorAt rows repeats path outside placeholder left exterior) + (rawAtCut rows repeats path outside left + (ChildAssemblyProjection.rawPullback rows p raw)) := by + rw [rawAtCut_pullback, + WholeCutGroupedProjection.exteriorAt_pullback rows repeats path outside placeholder + left right exterior] + exact first_grouped_pullback rows repeats path + (CutSlotAssembly.fill path outside left) (CutSlotAssembly.fill path outside right) + (CutProjectionAssembly.fillProjection path outside left right p) + (CutSlotAssembly.fill_outside_eq path outside left right) + (CutProjectionGeometry.fillProjection_outside path outside left right p) + (CleanPhysicalReplay.exteriorAt rows repeats path outside placeholder right exterior) _ + +theorem second_pullback + (direction : BucketSampler.Direction (rows (height + 1))) + (raw : CutCallExtension.Extended + (C := WholeCutCalls.Index rows repeats path) right rows) : + ChildBlockProjection.arraysPullback rows + (CutProjectionAssembly.fillProjection path outside left right p) + (LowerCutPair.second rows repeats path (CutSlotAssembly.fill path outside right) + (CleanPhysicalReplay.exteriorAt rows repeats path outside placeholder right exterior) + direction (rawAtCut rows repeats path outside right raw)) = + LowerCutPair.second rows repeats path (CutSlotAssembly.fill path outside left) + (CleanPhysicalReplay.exteriorAt rows repeats path outside placeholder left exterior) + direction (rawAtCut rows repeats path outside left + (ChildAssemblyProjection.rawPullback rows p raw)) := by + rw [rawAtCut_pullback, + WholeCutGroupedProjection.exteriorAt_pullback rows repeats path outside placeholder + left right exterior] + exact second_grouped_pullback rows repeats path + (CutSlotAssembly.fill path outside left) (CutSlotAssembly.fill path outside right) + (CutProjectionAssembly.fillProjection path outside left right p) + (CutSlotAssembly.fill_outside_eq path outside left right) + (CutProjectionGeometry.fillProjection_outside path outside left right p) + (CleanPhysicalReplay.exteriorAt rows repeats path outside placeholder right exterior) + direction _ + +end Filled +end +end PerfectCompleteness.SourceQuestionPairPullback + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/SourceQuestionPhysicalHigh.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/SourceQuestionPhysicalHigh.lean new file mode 100644 index 0000000000000000000000000000000000000000..969dafe31fb47c82654bb066987f1768e990533e --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/SourceQuestionPhysicalHigh.lean @@ -0,0 +1,141 @@ +import OAI.Computability.PerfectCompleteness.Construction.SourcePhysicalTaggedChildren +import OAI.Computability.PerfectCompleteness.Decoding.CutProjectionAssembly +import OAI.Computability.PerfectCompleteness.Decoding.LowerCutScalarProjectionLemmas +import OAI.Computability.PerfectCompleteness.Decoding.LowerProjectedOriginalSuccessLemmas +import OAI.Computability.PerfectCompleteness.Foundations.SourceProjectedTag + +namespace OAI + +section + +namespace PerfectCompleteness.SourceQuestionPhysicalHigh + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +attribute [local instance] RightDecoder.scalarFintype + +variable {branch rows repeats : Nat → Nat} {n height t v m : Nat} + (path : Path branch n (height + 1)) + (outside : Slots branch n → Fin t → MixedSupport.Slot) + (placeholder : Slots branch (height + 1) → Fin t → MixedSupport.Slot) + (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch height) → Slots branch height) + (q : SourceQuestionLowerForms.Questions + (branch := branch) (height := height) (t := t) (m := m)) + (choices : SourceQuestionKernelJoint.ChoiceTuple + (branch := branch) (n := height) (t := t)) + (flags : SourceProjectedTag.Flags (branch := branch) (n := height)) + +abbrev originalSlots := SourceQuestionLowerForms.slots path outside clauses q + +def projectedSlots : Slots branch n → Fin t → MixedSupport.Slot := + CutSlotAssembly.fill path outside + (SourceProjectedTag.mixedInside clauses designated q choices flags) + +def projection : ∀ leaf j, MixedSupport.Projection + (originalSlots path outside clauses q leaf j) + (projectedSlots path outside clauses designated q choices flags leaf j) := + CutProjectionAssembly.fillProjection path outside + (SourceChildMarkedLaw.questionSlots clauses q) + (SourceProjectedTag.mixedInside clauses designated q choices flags) + (SourceProjectedTag.projection clauses designated q choices flags) + +def exteriorAt + (exterior : CleanPhysicalReplay.Exterior rows repeats path outside placeholder) : + WholeCutGrouping.Exterior rows repeats path + (projectedSlots path outside clauses designated q choices flags) := + CleanPhysicalReplay.exteriorAt rows repeats path outside placeholder + (SourceProjectedTag.mixedInside clauses designated q choices flags) exterior + +section Collision + +variable (upper : Nodes branch n) (level : Nat) + (d : HierarchicalFrozenTables.LowerNodes upper level) + (hbranch : ∀ k < n, 0 < branch k) + {adviceRows : Nat} (A : ManyGoodRows.RowMap (Block rows upper) adviceRows) + (exterior : CleanPhysicalReplay.Exterior rows repeats path outside placeholder) + (direction : BucketSampler.Direction (rows (height + 1))) + (cutoff : Nat) + (table : SourceQuestionLowerForms.UpperTable (rows := rows) + path outside clauses upper level (adviceRows := adviceRows) q) + +def collision : ℝ := + LowerProjectedFiberAverage.rawCollision path + (originalSlots path outside clauses q) + (projectedSlots path outside clauses designated q choices flags) + (projection path outside clauses designated q choices flags) + upper level hbranch d direction + (exteriorAt path outside placeholder clauses designated q choices flags exterior) + A cutoff table + +end Collision + +section Success + +variable (upper : Nodes branch n) + (pDown : Path branch (Nodes.height upper) (height + 1)) + (hproper : height + 1 < Nodes.height upper) + (level : Nat) (hbranch : ∀ k < n, 0 < branch k) + (d : HierarchicalFrozenTables.LowerNodes upper level) + (hnode : WholeArrayInteriorExterior.upperNode ((Nodes.path upper).append pDown) = + HierarchicalLeftDecoder.LowerNode upper level d) + {adviceRows : Nat} (A : ManyGoodRows.RowMap (Block rows upper) adviceRows) + (cut : OwnInputReference.Cut upper (ProjectedLowerFiber.lower upper level d)) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (useful : (bg : HierarchicalMatrixTable.Background (rows := rows) + (originalSlots ((Nodes.path upper).append pDown) outside clauses q) upper) → + HierarchicalFrozenTables.QuotientMatrix + (originalSlots ((Nodes.path upper).append pDown) outside clauses q) upper level bg → Prop) + (ρ threshold : ℝ) + (exterior : CleanPhysicalReplay.Exterior rows repeats + ((Nodes.path upper).append pDown) outside placeholder) + (direction : BucketSampler.Direction (rows (height + 1))) + (cutoff : Nat) + +local instance rowSpaceFintype : + Fintype (NodeEmbedding.RowSpace + (originalSlots ((Nodes.path upper).append pDown) outside clauses q) upper) := + Fintype.ofFinite _ + +local instance upperAnswerFintype : + Fintype (HierarchicalAllDecoderTables.UpperAnswer + (originalSlots ((Nodes.path upper).append pDown) outside clauses q) upper) := + LeftDecoder.dualFintype (V := NodeEmbedding.RowSpace + (originalSlots ((Nodes.path upper).append pDown) outside clauses q) upper) + +def success : ℝ := + LowerPhysicalFiberSuccess.physicalSuccess + (originalSlots ((Nodes.path upper).append pDown) outside clauses q) + (projectedSlots ((Nodes.path upper).append pDown) outside clauses designated q choices flags) + (projection ((Nodes.path upper).append pDown) outside clauses designated q choices flags) + upper pDown hproper level hbranch d hnode direction + (exteriorAt ((Nodes.path upper).append pDown) outside placeholder clauses designated + q choices flags exterior) A cut σ useful ρ threshold cutoff + +theorem success_square_le : + success outside placeholder clauses designated q choices flags upper pDown hproper level + hbranch d hnode A cut σ useful ρ threshold exterior direction cutoff ^ 2 ≤ + (HierarchicalAllDecoderTables.upperTableLaw + (originalSlots ((Nodes.path upper).append pDown) outside clauses q) + upper level σ useful adviceRows ρ).expectation + (collision ((Nodes.path upper).append pDown) outside placeholder clauses designated + q choices flags upper level d hbranch A exterior direction cutoff) := + LowerPhysicalFiberSuccess.physicalSuccess_square_le + (originalSlots ((Nodes.path upper).append pDown) outside clauses q) + (projectedSlots ((Nodes.path upper).append pDown) outside clauses designated q choices flags) + (projection ((Nodes.path upper).append pDown) outside clauses designated q choices flags) + upper pDown hproper level hbranch d hnode direction + (exteriorAt ((Nodes.path upper).append pDown) outside placeholder clauses designated + q choices flags exterior) A cut σ useful ρ threshold cutoff + +end Success +end +end PerfectCompleteness.SourceQuestionPhysicalHigh + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/SourceQuestionPositionSplit.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/SourceQuestionPositionSplit.lean new file mode 100644 index 0000000000000000000000000000000000000000..431552babba098923e3ecbe62c2e849d03cec3bd --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/SourceQuestionPositionSplit.lean @@ -0,0 +1,107 @@ +import OAI.Computability.PerfectCompleteness.Sampling.SourceChildQuestionLaw + +namespace OAI + +section + +namespace PerfectCompleteness.SourceQuestionPositionSplit + +noncomputable section + +open scoped Classical +open RecursiveSpaces SourceQuestionReconstruction TreeSourceSpaces +open UniqueGamesTheorem.Foundations.Games + +variable {branch : Nat → Nat} {n t m : Nat} + +abbrev Questions := PreliminarySampler.Questions branch (n + 1) t m +abbrev Positions := Slots branch (n + 1) → Fin t → Fin 3 +abbrev ChildPositions := Slots branch n → Fin t → Fin 3 + +def splitTree : (Slots branch (n + 1) → SourceTuple m t) ≃ + Questions (branch := branch) (n := n) (t := t) (m := m) × + Positions (branch := branch) (n := n) (t := t) where + toFun tree := (fun leaf k => (tree leaf k).1, fun leaf k => (tree leaf k).2) + invFun parts leaf k := (parts.1 leaf k, parts.2 leaf k) + left_inv _ := rfl + right_inv _ := rfl + +def split (designated : Fin (branch n) → Slots branch n) : + SourceChildKernel.Sources (m := m) (t := t) designated ≃ + Questions (branch := branch) (n := n) (t := t) (m := m) × + Positions (branch := branch) (n := n) (t := t) := + (SourceChildQuestionLaw.assembleEquiv (m := m) (t := t) designated).trans splitTree + +def join (designated : Fin (branch n) → Slots branch n) + (q : Questions (branch := branch) (n := n) (t := t) (m := m)) + (positions : Positions (branch := branch) (n := n) (t := t)) : + SourceChildKernel.Sources (m := m) (t := t) designated := + (split designated).symm (q, positions) + +@[simp] theorem questions_join (designated : Fin (branch n) → Slots branch n) + (q : Questions (branch := branch) (n := n) (t := t) (m := m)) + (positions : Positions (branch := branch) (n := n) (t := t)) : + SourceChildQuestionLaw.questions designated (join designated q positions) = q := + congrArg Prod.fst ((split designated).apply_symm_apply (q, positions)) + +theorem tree_join (designated : Fin (branch n) → Slots branch n) + (q : Questions (branch := branch) (n := n) (t := t) (m := m)) + (positions : Positions (branch := branch) (n := n) (t := t)) : + SourceChildQuestionLaw.assembleEquiv designated (join designated q positions) = + fun leaf k => (q leaf k, positions leaf k) := + (SourceChildQuestionLaw.assembleEquiv (m := m) (t := t) designated).apply_symm_apply _ + +theorem child_tree_join (designated : Fin (branch n) → Slots branch n) + (q : Questions (branch := branch) (n := n) (t := t) (m := m)) + (positions : Positions (branch := branch) (n := n) (t := t)) + (i : Fin (branch n)) (leaf : Slots branch n) (k : Fin t) : + SourceChildKernel.tree designated i (join designated q positions i) leaf k = + (q (i, leaf) k, positions (i, leaf) k) := + congrFun (congrFun (tree_join designated q positions) (i, leaf)) k + +theorem sourceLaw_split [NeZero m] (designated : Fin (branch n) → Slots branch n) : + (SourceChildQuestionLaw.sourceLaw m t designated).pushforward (split designated) = + (PreliminarySampler.questionsLaw (branch := branch) (n := n + 1) (t := t) (m := m)).product + (FiniteDistribution.uniform (Positions (branch := branch) (n := n) (t := t))) := by + rw [SourceChildQuestionLaw.sourceLaw_uniform, FiniteDistribution.pushforward_equiv] + apply FiniteDistribution.eq_of_weight_eq + intro x + change 1 / (Fintype.card (SourceChildKernel.Sources (m := m) (t := t) designated) : ℝ) = + (1 / (Fintype.card (Questions (branch := branch) (n := n) (t := t) (m := m)) : ℝ)) * + (1 / (Fintype.card (Positions (branch := branch) (n := n) (t := t)) : ℝ)) + rw [Fintype.card_congr (split (m := m) (t := t) designated), Fintype.card_prod, + Nat.cast_mul, one_div_mul_one_div] + +def byChild : Positions (branch := branch) (n := n) (t := t) ≃ + (Fin (branch n) → ChildPositions (branch := branch) (n := n) (t := t)) where + toFun positions i leaf k := positions (i, leaf) k + invFun positions leaf k := positions leaf.1 leaf.2 k + left_inv _ := rfl + right_inv _ := rfl + +theorem positions_byChild : + (FiniteDistribution.uniform (Positions (branch := branch) (n := n) (t := t))).pushforward + (byChild (branch := branch) (n := n) (t := t)) = + FiniteProduct.law (fun _ : Fin (branch n) => + FiniteDistribution.uniform (ChildPositions (branch := branch) (n := n) (t := t))) := by + rw [UniformLinearImage.law_uniform, FiniteDistribution.pushforward_equiv] + apply FiniteDistribution.eq_of_weight_eq + intro x + change 1 / (Fintype.card (Positions (branch := branch) (n := n) (t := t)) : ℝ) = + 1 / (Fintype.card (Fin (branch n) → ChildPositions (branch := branch) (n := n) (t := t)) : ℝ) + rw [Fintype.card_congr (byChild (branch := branch) (n := n) (t := t))] + +theorem parentLeftSlots_join {v : Nat} (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch n) → Slots branch n) + (q : Questions (branch := branch) (n := n) (t := t) (m := m)) + (positions : Positions (branch := branch) (n := n) (t := t)) : + SourceChildKernel.parentLeftSlots clauses designated (join designated q positions) = + HierarchicalArrays.sourceSlots clauses (PreliminarySampler.endpoints q) := by + rw [SourceChildQuestionLaw.parentLeftSlots_eq, questions_join] + +end +end PerfectCompleteness.SourceQuestionPositionSplit + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/SourceQuestionRawSwap.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/SourceQuestionRawSwap.lean new file mode 100644 index 0000000000000000000000000000000000000000..ed98c8a70049e29ca57fc3712967b93bc4656928 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/SourceQuestionRawSwap.lean @@ -0,0 +1,160 @@ +import OAI.Computability.PerfectCompleteness.Construction.SourceQuestionCutSplit +import OAI.Computability.PerfectCompleteness.Foundations.SourceProjectedTag + +namespace OAI + +section + +namespace PerfectCompleteness.SourceQuestionRawSwap + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces +open UniqueGamesTheorem.Foundations.Games + +private theorem expectation_kernelJoint {S R : Type*} [Fintype S] [Fintype R] + (μ : FiniteDistribution S) (P : S → FiniteDistribution R) (f : S × R → ℝ) : + (CleanConditioning.kernelJoint μ P).expectation f = + μ.expectation (fun s => (P s).expectation (fun r => f (s, r))) := by + simp only [FiniteDistribution.expectation, CleanConditioning.kernelJoint, + Fintype.sum_prod_type, Finset.mul_sum, mul_assoc] + +variable {branch : Nat → Nat} {root h n t v m : Nat} + +@[simp] theorem restrict_join (p : Path branch root h) + (inside : PreliminarySampler.Questions branch h t m) + (external : SourceQuestionCutSplit.OutsideQuestions p t m) : + SourceQuestionCutSplit.restrict p (SourceQuestionCutSplit.join p inside external) = + inside := by + funext leaf + exact SourceQuestionCutSplit.join_at_cut p inside external leaf + +theorem questions_expectation [NeZero m] (p : Path branch root h) + (F : PreliminarySampler.Questions branch root t m → ℝ) : + (PreliminarySampler.questionsLaw + (branch := branch) (n := root) (t := t) (m := m)).expectation F = + (FiniteDistribution.uniform (SourceQuestionCutSplit.OutsideQuestions p t m)).expectation + (fun external => (PreliminarySampler.questionsLaw + (branch := branch) (n := h) (t := t) (m := m)).expectation + (fun inside => F (SourceQuestionCutSplit.join p inside external))) := by + have hsplit := congrArg (fun μ : FiniteDistribution + (PreliminarySampler.Questions branch h t m × + SourceQuestionCutSplit.OutsideQuestions p t m) => + μ.expectation (fun parts => F ((SourceQuestionCutSplit.splitEquiv p).symm parts))) + (SourceQuestionCutSplit.split_law (t := t) (m := m) p) + rw [FiniteDistribution.expectation_pushforward, + FiniteDistribution.expectation_product] at hsplit + simp only [Equiv.symm_apply_apply] at hsplit + exact hsplit.trans (FiniteDistribution.expectation_comm + (PreliminarySampler.questionsLaw (branch := branch) (n := h) (t := t) (m := m)) + (FiniteDistribution.uniform (SourceQuestionCutSplit.OutsideQuestions p t m)) + (fun inside external => F (SourceQuestionCutSplit.join p inside external))) + +variable {C : Type*} [Fintype C] + (rows : Nat → Nat) (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch n) → Slots branch n) + +def insideQuestions + (sample : SourceChildKernel.Sample (C := C) (t := t) rows clauses designated) : + PreliminarySampler.Questions branch (n + 1) t m := + (SourceQuestionKernelJoint.groupEquiv rows clauses designated sample).1.1 + +def positions + (sample : SourceChildKernel.Sample (C := C) (t := t) rows clauses designated) : + SourceQuestionKernelJoint.ChoiceTuple (branch := branch) (n := n) (t := t) := + (SourceQuestionKernelJoint.groupEquiv rows clauses designated sample).1.2 + +def raw + (sample : SourceChildKernel.Sample (C := C) (t := t) rows clauses designated) : + SourceChildKernelJoint.RawTuple (C := C) (t := t) rows clauses designated := + (SourceQuestionKernelJoint.groupEquiv rows clauses designated sample).2 + +@[simp] theorem raw_apply + (sample : SourceChildKernel.Sample (C := C) (t := t) rows clauses designated) + (child : Fin (branch n)) : + raw rows clauses designated sample child = (sample child).2.2 := rfl + +theorem sources_insideQuestions_positions + (sample : SourceChildKernel.Sample (C := C) (t := t) rows clauses designated) : + SourceQuestionKernelJoint.sources designated + (insideQuestions rows clauses designated sample) + (positions rows clauses designated sample) = + fun child => ((sample child).1, (sample child).2.1) := by + change (SourceQuestionKernelJoint.sourceEquiv designated).symm + ((SourceQuestionKernelJoint.sourceEquiv designated) + (fun child => ((sample child).1, (sample child).2.1))) = _ + exact (SourceQuestionKernelJoint.sourceEquiv designated).symm_apply_apply _ + +def kernelLaw (flag : Fin (branch n) → FiniteDistribution Bool) + (inside : PreliminarySampler.Questions branch (n + 1) t m) + (choices : SourceQuestionKernelJoint.ChoiceTuple (branch := branch) (n := n) (t := t)) : + FiniteDistribution (SourceChildKernelJoint.RawTuple (C := C) (t := t) + rows clauses designated) := + FiniteProduct.law (fun child => + SourceChildKernel.kernel (C := C) (t := t) rows clauses designated flag child + (SourceQuestionKernelJoint.sources designated inside choices child)) + +theorem originalLaw_expectation [NeZero m] + (flag : Fin (branch n) → FiniteDistribution Bool) + (F : PreliminarySampler.Questions branch (n + 1) t m → + SourceQuestionKernelJoint.ChoiceTuple (branch := branch) (n := n) (t := t) → + SourceChildKernelJoint.RawTuple (C := C) (t := t) rows clauses designated → ℝ) : + (SourceChildKernel.originalLaw (C := C) (t := t) rows clauses designated flag).expectation + (fun sample => F (insideQuestions rows clauses designated sample) + (positions rows clauses designated sample) (raw rows clauses designated sample)) = + (PreliminarySampler.questionsLaw + (branch := branch) (n := n + 1) (t := t) (m := m)).expectation + (fun inside => (SourceProjectedTag.positionLaw + (branch := branch) (n := n) (t := t)).expectation + (fun choices => (kernelLaw rows clauses designated flag inside choices).expectation + (F inside choices))) := by + let statistic : (PreliminarySampler.Questions branch (n + 1) t m × + SourceQuestionKernelJoint.ChoiceTuple (branch := branch) (n := n) (t := t)) × + SourceChildKernelJoint.RawTuple (C := C) (t := t) rows clauses designated → ℝ := + fun grouped => F grouped.1.1 grouped.1.2 grouped.2 + have hgroup := congrArg (fun μ : FiniteDistribution + ((PreliminarySampler.Questions branch (n + 1) t m × + SourceQuestionKernelJoint.ChoiceTuple (branch := branch) (n := n) (t := t)) × + SourceChildKernelJoint.RawTuple (C := C) (t := t) rows clauses designated) => + μ.expectation statistic) + (SourceQuestionKernelJoint.originalLaw_group (C := C) (t := t) + rows clauses designated flag) + simpa only [FiniteDistribution.expectation_pushforward, expectation_kernelJoint, + FiniteDistribution.expectation_product, statistic, insideQuestions, positions, raw, + kernelLaw, SourceProjectedTag.positionLaw] using hgroup + +theorem fullQuestions_expectation [NeZero m] + (flag : Fin (branch n) → FiniteDistribution Bool) + (p : Path branch root (n + 1)) + (F : PreliminarySampler.Questions branch root t m → + SourceQuestionKernelJoint.ChoiceTuple (branch := branch) (n := n) (t := t) → + SourceChildKernelJoint.RawTuple (C := C) (t := t) rows clauses designated → ℝ) : + (PreliminarySampler.questionsLaw + (branch := branch) (n := root) (t := t) (m := m)).expectation + (fun q => (SourceProjectedTag.positionLaw + (branch := branch) (n := n) (t := t)).expectation + (fun choices => (kernelLaw rows clauses designated flag + (SourceQuestionCutSplit.restrict p q) choices).expectation + (fun sampleRaw => F q choices sampleRaw))) = + (FiniteDistribution.uniform (SourceQuestionCutSplit.OutsideQuestions p t m)).expectation + (fun external => (SourceChildKernel.originalLaw (C := C) (t := t) + rows clauses designated flag).expectation + (fun sample => F + (SourceQuestionCutSplit.join p + (insideQuestions rows clauses designated sample) external) + (positions rows clauses designated sample) (raw rows clauses designated sample))) := by + rw [questions_expectation p] + apply FiniteDistribution.expectation_congr + intro external + simp only [restrict_join] + exact (originalLaw_expectation rows clauses designated flag + (fun inside choices sampleRaw => + F (SourceQuestionCutSplit.join p inside external) choices sampleRaw)).symm + +end +end PerfectCompleteness.SourceQuestionRawSwap + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/SourceQuestionReconstruction.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/SourceQuestionReconstruction.lean new file mode 100644 index 0000000000000000000000000000000000000000..3ae0fe48911c075ddc7690049589cd4f90f4fe4f --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/SourceQuestionReconstruction.lean @@ -0,0 +1,96 @@ +import OAI.Computability.PerfectCompleteness.Foundations.CanonicalEdgesLemmas + +namespace OAI + + +namespace PerfectCompleteness.SourceQuestionReconstruction + +open SourceClause SourceKeys + +noncomputable section + +variable {I E Q : Type*} {Leaf : I → Type*} + (designated : (i : I) → Leaf i) (clean : I → Prop) [DecidablePred clean] + [∀ i, DecidableEq (Leaf i)] + +abbrev Visible := (i : I) → {s : Leaf i // ¬(clean i ∧ s = designated i)} → E + +def reveal (x : (i : I) → Leaf i → E) : Visible (E := E) designated clean := + fun i s => x i s.1 + +def reconstruct (endpoint : I → E → Q) + (visible : Visible (E := E) designated clean) (own : {i : I // clean i} → Q) : + (i : I) → Leaf i → Q := + fun i s => if h : clean i ∧ s = designated i then own ⟨i, h.1⟩ + else endpoint i (visible i ⟨s, h⟩) + +theorem reconstruct_eq (endpoint : I → E → Q) (x : (i : I) → Leaf i → E) : + reconstruct designated clean endpoint (reveal designated clean x) + (fun i => endpoint i.1 (x i.1 (designated i.1))) = + fun i s => endpoint i (x i s) := by + funext i s + by_cases h : clean i ∧ s = designated i + · simp [reconstruct, h] + · simp [reconstruct, reveal, h] + + +variable {v m t : Nat} + (clauses : Fin m → NormalizedClause v) + +abbrev SourceTuple (m t : Nat) := Fin t → Occurrence m + +def leftTuple (e : SourceTuple m t) : Fin t → Endpoint v m := + fun k => .clause (e k).1 + +def rightTuple (projected : Bool) (e : SourceTuple m t) : Fin t → Endpoint v m := + fun k => if projected then .variable (occurrenceVariable clauses (e k)) else .clause (e k).1 + +def reconstructLeft + (visible : Visible (E := SourceTuple m t) designated clean) + (own : {i : I // clean i} → Fin t → Fin m) : + (i : I) → Leaf i → Fin t → Endpoint v m := + reconstruct designated clean (fun _ => leftTuple) visible + (fun i k => .clause (own i k)) + +def reconstructRight (projected : I → Bool) + (visible : Visible (E := SourceTuple m t) designated clean) + (own : {i : I // clean i} → Fin t → Fin v) : + (i : I) → Leaf i → Fin t → Endpoint v m := + reconstruct designated clean (fun i => rightTuple clauses (projected i)) visible + (fun i k => .variable (own i k)) + +theorem reconstructLeft_eq (x : (i : I) → Leaf i → SourceTuple m t) : + reconstructLeft designated clean (reveal designated clean x) + (fun i k => (x i.1 (designated i.1) k).1) = + fun i s => leftTuple (v := v) (x i s) := by + exact reconstruct_eq designated clean (fun _ => leftTuple) x + +theorem reconstructRight_eq (projected : I → Bool) + (clean_projected : ∀ i, clean i → projected i = true) + (x : (i : I) → Leaf i → SourceTuple m t) : + reconstructRight designated clean clauses projected (reveal designated clean x) + (fun i k => occurrenceVariable clauses (x i.1 (designated i.1) k)) = + fun i s => rightTuple clauses (projected i) (x i s) := by + have hown : (fun (i : {i : I // clean i}) k => + Endpoint.variable (m := m) (occurrenceVariable clauses (x i.1 (designated i.1) k))) = + (fun (i : {i : I // clean i}) => + rightTuple clauses (projected i.1) (x i.1 (designated i.1))) := by + funext i k + simp only [rightTuple, clean_projected i.1 i.2, ite_true] + unfold reconstructRight + rw [hown] + exact reconstruct_eq designated clean (fun i => rightTuple clauses (projected i)) x + +theorem reconstructRight_slots (projected : I → Bool) + (clean_projected : ∀ i, clean i → projected i = true) + (x : (i : I) → Leaf i → SourceTuple m t) : + (fun i s k => slot clauses + (reconstructRight designated clean clauses projected (reveal designated clean x) + (fun i k => occurrenceVariable clauses (x i.1 (designated i.1) k)) i s k)) = + (fun i s k => slot clauses (rightTuple clauses (projected i) (x i s) k)) := by + rw [reconstructRight_eq designated clean clauses projected clean_projected x] + +end +end PerfectCompleteness.SourceQuestionReconstruction + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/SourceQuestionUnmarkedRange.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/SourceQuestionUnmarkedRange.lean new file mode 100644 index 0000000000000000000000000000000000000000..743903a40b919bce44128b6275e82ac8ff1f9e79 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/SourceQuestionUnmarkedRange.lean @@ -0,0 +1,66 @@ +import OAI.Computability.PerfectCompleteness.Decoding.ProjectedNativeCollision +import OAI.Computability.PerfectCompleteness.Foundations.CutNativeForms +import OAI.Computability.PerfectCompleteness.Sampling.SourceChildMarkedLaw + +namespace OAI + +section + +namespace PerfectCompleteness.SourceQuestionUnmarkedRange + +open scoped Classical +open RecursiveSpaces TreeSourceSpaces SourceChildKernel + +noncomputable section + +variable {branch : Nat → Nat} {height t v m : Nat} + +private theorem unmarked_range_cast + {left native right : Slots branch (height + 1) → Fin t → MixedSupport.Slot} + (h : left = native) + (p : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (mask : Fin (branch height) → Bool) + (hin : ChildUnmarkedSpace.space left mask ≤ LinearMap.range (HPullback p)) : + ChildUnmarkedSpace.space native mask ≤ + LinearMap.range (HPullback (CutNativeForms.projectionCast h rfl p)) := by + cases h + exact hin + +variable (rows : Nat → Nat) (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch height) → Slots branch height) + (q : SourceChildMarkedLaw.Questions (branch := branch) (n := height) (t := t) (m := m)) + (choices : SourceQuestionKernelJoint.ChoiceTuple (branch := branch) (n := height) (t := t)) + +theorem leftSlots_eq : + parentLeftSlots clauses designated (SourceQuestionKernelJoint.sources designated q choices) = + SourceChildMarkedLaw.questionSlots clauses q := + SourceQuestionPositionSplit.parentLeftSlots_join clauses designated q _ + +variable {C : Type*} [Fintype C] + (raw : (i : Fin (branch height)) → Raw (C := C) (t := t) rows clauses designated i) + +def projection : ∀ s k, MixedSupport.Projection + (SourceChildMarkedLaw.questionSlots clauses q s k) + (parentRightSlots rows clauses designated + (SourceQuestionKernelJoint.sources designated q choices) raw s k) := + CutNativeForms.projectionCast (leftSlots_eq clauses designated q choices) rfl + (parentProjection rows clauses designated + (SourceQuestionKernelJoint.sources designated q choices) raw) + +theorem unmarked_le_range : + ChildUnmarkedSpace.space (SourceChildMarkedLaw.questionSlots clauses q) + (fun i => rawProjected rows clauses designated i (raw i)) ≤ + LinearMap.range (HPullback (projection rows clauses designated q choices raw)) := by + exact unmarked_range_cast (leftSlots_eq clauses designated q choices) + (parentProjection rows clauses designated + (SourceQuestionKernelJoint.sources designated q choices) raw) + (fun i => rawProjected rows clauses designated i (raw i)) + (ProjectedNativeCollision.parent_unmarked_le_range clauses designated + (SourceQuestionKernelJoint.sources designated q choices) raw) + +end +end PerfectCompleteness.SourceQuestionUnmarkedRange + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/StoppedBucketRows.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/StoppedBucketRows.lean new file mode 100644 index 0000000000000000000000000000000000000000..ac460d91c7035efd09219889d7922c9035dc926d --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/StoppedBucketRows.lean @@ -0,0 +1,67 @@ +import OAI.Computability.PerfectCompleteness.Decoding.SelectedArrayProjection +import OAI.Computability.PerfectCompleteness.Sampling.WholeArrayBucketsLaw + +namespace OAI + +section + +namespace PerfectCompleteness.StoppedBucketRows + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open WholeArraySubtreeSplit SelectedArrayReplacement +open scoped BigOperators Classical + +noncomputable section + +variable {branch : Nat → Nat} {N n m t : Nat} + +theorem selectedRows_evaluate (rows repeats : Nat → Nat) + (p : Path branch N (n + 1)) (chosen : Fin (branch n)) (q : Path branch n m) + (slots : Slots branch N → Fin t → MixedSupport.Slot) + (tape : WholeArraySampler.Tape rows repeats (p.append (.step chosen q)) slots) : + selectedRows rows p slots + (WholeArraySampler.evaluate rows repeats (p.append (.step chosen q)) slots tape) = + BucketSampler.evaluate (rows (n + 1)) + (RecursiveSampler.evaluate F2 repeats (.step chosen q) + (LeafDomain (WholeCutGrouping.cutSlots p slots))) + (WholeArrayBucketsLaw.split rows repeats p chosen q slots tape).1 := by + exact congrArg + (fun arrays : Arrays (subtreeSlots p slots) rows => arrays (.inl ())) + (restrictArrays_evaluate rows repeats p (.step chosen q) slots tape) + +theorem pullback_bucket_evaluate {Ω : Type*} (width : Nat) + {left right : Slots branch n → Fin t → MixedSupport.Slot} + (projection : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (eval : Ω → H right) (tape : BucketSampler.Tape width Ω) : + (fun row => HPullback projection (BucketSampler.evaluate width eval tape row)) = + BucketSampler.evaluate width id (fun direction => HPullback projection (eval (tape direction))) := by + funext row + simp only [BucketSampler.evaluate, map_sum, map_smul, id_eq] + +theorem selectedRows_pullback_evaluate (rows repeats : Nat → Nat) + (p : Path branch N (n + 1)) (chosen : Fin (branch n)) (q : Path branch n m) + (left right : Slots branch N → Fin t → MixedSupport.Slot) + (projection : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (tape : WholeArraySampler.Tape rows repeats (p.append (.step chosen q)) right) : + selectedRows rows p left + (ChildBlockProjection.arraysPullback rows projection + (WholeArraySampler.evaluate rows repeats (p.append (.step chosen q)) right tape)) = + BucketSampler.evaluate (rows (n + 1)) id + (fun direction => HPullback (CutGroupedProjection.cutProjection p projection) + (RecursiveSampler.evaluate F2 repeats (.step chosen q) + (LeafDomain (WholeCutGrouping.cutSlots p right)) + ((WholeArrayBucketsLaw.split rows repeats p chosen q right tape).1 direction))) := by + rw [SelectedArrayProjection.selectedRows_pullback] + simp only [selectedRows_evaluate rows repeats p chosen q right tape] + exact pullback_bucket_evaluate (rows (n + 1)) + (CutGroupedProjection.cutProjection p projection) + (RecursiveSampler.evaluate F2 repeats (.step chosen q) + (LeafDomain (WholeCutGrouping.cutSlots p right))) + (WholeArrayBucketsLaw.split rows repeats p chosen q right tape).1 + +end +end PerfectCompleteness.StoppedBucketRows + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/StoppedProjectedBucketIndex.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/StoppedProjectedBucketIndex.lean new file mode 100644 index 0000000000000000000000000000000000000000..e7d4e335fb6c6aa061cdfb52dbf5f195921d986f --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/StoppedProjectedBucketIndex.lean @@ -0,0 +1,114 @@ +import OAI.Computability.PerfectCompleteness.Decoding.CanonicalUpperDirectionSplit +import OAI.Computability.PerfectCompleteness.Foundations.StoppedProjectedExperiment + +namespace OAI + +section + +namespace PerfectCompleteness.StoppedProjectedBucketIndex + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +variable {branch : Nat → Nat} {n i j t v m : Nat} + +abbrev Base := GeometricCutSplit.Prefix branch (j + 1) (i + 1) × + SourceProjectedTag.Tag (branch := branch) (n := i) (t := t) + +def baseOf (rows : Nat → Nat) + (k : StoppedProjectedExperiment.Inner (branch := branch) (n := n) + (i := i) (j := j) (t := t) rows) : Base (branch := branch) (i := i) (j := j) (t := t) := + (k.1, k.2.1) + +def withDirections (rows : Nat → Nat) + (base : Base (branch := branch) (i := i) (j := j) (t := t)) + (directions : CanonicalDirections.Tuple rows n) : + StoppedProjectedExperiment.Inner (branch := branch) (n := n) + (i := i) (j := j) (t := t) rows := + (base.1, (base.2, directions)) + +@[simp] theorem baseOf_withDirections (rows : Nat → Nat) + (base : Base (branch := branch) (i := i) (j := j) (t := t)) + (directions : CanonicalDirections.Tuple rows n) : + baseOf rows (withDirections rows base directions) = base := rfl + +@[simp] theorem withDirections_baseOf (rows : Nat → Nat) + (k : StoppedProjectedExperiment.Inner (branch := branch) (n := n) + (i := i) (j := j) (t := t) rows) : + withDirections rows (baseOf rows k) k.2.2 = k := rfl + +def defaultDirections (rows : Nat → Nat) (hrows : ∀ k, 0 < rows (k + 1)) : + CanonicalDirections.Tuple rows n := + fun level => Classical.choice + (PreliminarySampler.directionNonempty (rows (level.val + 1)) (hrows level.val)) + +def baseLaw (hij : i < j) (hbranch : ∀ k < j + 1, 0 < branch k) + (flag : Fin (branch i) → FiniteDistribution Bool) : + FiniteDistribution (Base (branch := branch) (i := i) (j := j) (t := t)) := + (GeometricCutSplit.prefixLaw (Nat.succ_le_succ hij.le) hbranch).product + (SourceProjectedTag.law (t := t) flag) + +variable (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hupper : j + 1 ≤ n) (hij : i < j) + (designated : Fin (branch i) → Slots branch i) + (hrows : ∀ k, 0 < rows (k + 1)) + (o : StoppedProjectedExperiment.Outer + (branch := branch) (n := n) (j := j) (t := t) (m := m)) + +abbrev key (base : Base (branch := branch) (i := i) (j := j) (t := t)) := + withDirections (n := n) rows base (defaultDirections rows hrows) + +abbrev Tape (base : Base (branch := branch) (i := i) (j := j) (t := t)) := + WholeArraySampler.Tape rows repeats + (StoppedProjectedExperiment.stoppedPath rows hupper hij o (key rows hrows base)) + (StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated o + (key rows hrows base)) + +def tapeLaw (base : Base (branch := branch) (i := i) (j := j) (t := t)) : + FiniteDistribution (Tape clauses rows repeats hupper hij designated hrows o base) := + WholeArraySampler.tapeLaw rows repeats + (StoppedProjectedExperiment.stoppedPath rows hupper hij o (key rows hrows base)) + (StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated o + (key rows hrows base)) + +theorem projectedSlots_eq + (k : StoppedProjectedExperiment.Inner (branch := branch) (n := n) + (i := i) (j := j) (t := t) rows) : + StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated o k = + StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated o + (key rows hrows (baseOf rows k)) := rfl + +theorem expectation_coordinate + (hbranch : ∀ k < j + 1, 0 < branch k) + (flag : Fin (branch i) → FiniteDistribution Bool) (level : Fin n) + (f : (base : Base (branch := branch) (i := i) (j := j) (t := t)) → + PrefixTests.LevelDirection rows level → + Tape clauses rows repeats hupper hij designated hrows o base → ℝ) : + (StoppedProjectedExperiment.tapeLaw clauses rows repeats hupper hij designated + hbranch hrows flag o).expectation + (fun sample => f (baseOf rows sample.1) (sample.1.2.2 level) sample.2) = + (baseLaw (t := t) hij hbranch flag).expectation (fun base => + (CanonicalDirections.levelLaw rows hrows level).expectation (fun direction => + (tapeLaw clauses rows repeats hupper hij designated hrows o base).expectation + (f base direction))) := by + rw [StoppedProjectedExperiment.tapeLaw, CandidateCoupling.expectation_sigmaLaw] + simp only [StoppedProjectedExperiment.innerLaw, baseLaw, + FiniteDistribution.expectation_product] + apply FiniteDistribution.expectation_congr + intro lowerPrefix + apply FiniteDistribution.expectation_congr + intro tag + exact FiniteProduct.expectation_eval (CanonicalDirections.levelLaw rows hrows) level + (fun direction => + (tapeLaw clauses rows repeats hupper hij designated hrows o (lowerPrefix, tag)).expectation + (f (lowerPrefix, tag) direction)) + +end +end PerfectCompleteness.StoppedProjectedBucketIndex + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/StoppedProjectedBuckets.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/StoppedProjectedBuckets.lean new file mode 100644 index 0000000000000000000000000000000000000000..b1666388dc4043d541f1c109ef41608156a8fb95 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/StoppedProjectedBuckets.lean @@ -0,0 +1,148 @@ +import OAI.Computability.PerfectCompleteness.Construction.HierarchicalAdviceFromBuckets +import OAI.Computability.PerfectCompleteness.Construction.StoppedProjectedBucketIndex +import OAI.Computability.PerfectCompleteness.Foundations.StoppedPathHead +import OAI.Computability.PerfectCompleteness.Sampling.StoppedUsefulPairLaw + +namespace OAI + +section + +namespace PerfectCompleteness.StoppedProjectedBuckets + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype + +variable {branch : Nat → Nat} {n i j t v m : Nat} + (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hupper : j + 1 ≤ n) (hij : i < j) + (designated : Fin (branch i) → Slots branch i) + (hrows : ∀ k, 0 < rows (k + 1)) + (o : StoppedProjectedExperiment.Outer + (branch := branch) (n := n) (j := j) (t := t) (m := m)) + +abbrev Base := StoppedProjectedBucketIndex.Base (branch := branch) (i := i) (j := j) (t := t) + +abbrev key (base : Base (branch := branch) (i := i) (j := j) (t := t)) := + StoppedProjectedBucketIndex.key (n := n) rows hrows base + +abbrev lowerPath (base : Base (branch := branch) (i := i) (j := j) (t := t)) := + StoppedProjectedExperiment.lowerPath rows hij (key (n := n) rows hrows base) + +def chosen (base : Base (branch := branch) (i := i) (j := j) (t := t)) : Fin (branch j) := + StoppedPathHead.child hij (lowerPath (n := n) rows hij hrows base) + +def continuation (base : Base (branch := branch) (i := i) (j := j) (t := t)) : + Path branch j (i + 1) := + StoppedPathHead.tail hij (lowerPath (n := n) rows hij hrows base) + +theorem lowerPath_eq_step (base : Base (branch := branch) (i := i) (j := j) (t := t)) : + lowerPath (n := n) rows hij hrows base = + .step (chosen (n := n) rows hij hrows base) (continuation (n := n) rows hij hrows base) := + StoppedPathHead.step_eq hij _ + +abbrev projected (base : Base (branch := branch) (i := i) (j := j) (t := t)) := + StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated o + (key (n := n) rows hrows base) + +abbrev projection (base : Base (branch := branch) (i := i) (j := j) (t := t)) := + StoppedProjectedExperiment.projection clauses rows hupper hij designated o + (key (n := n) rows hrows base) + +abbrev Exterior (base : Base (branch := branch) (i := i) (j := j) (t := t)) := + StoppedUsefulPairLaw.Descriptor rows repeats (StoppedProjectedExperiment.upperPath hupper o) + (chosen (n := n) rows hij hrows base) (continuation (n := n) rows hij hrows base) + (projected clauses rows hupper hij designated hrows o base) + +abbrev Descriptor := (base : Base (branch := branch) (i := i) (j := j) (t := t)) × + Exterior clauses rows repeats hupper hij designated hrows o base + +def exteriorLaw (base : Base (branch := branch) (i := i) (j := j) (t := t)) : + FiniteDistribution (Exterior clauses rows repeats hupper hij designated hrows o base) := + StoppedUsefulPairLaw.externalLaw rows repeats (StoppedProjectedExperiment.upperPath hupper o) + (chosen (n := n) rows hij hrows base) (continuation (n := n) rows hij hrows base) + (projected clauses rows hupper hij designated hrows o base) + +def externalLaw (hbranch : ∀ k < j + 1, 0 < branch k) + (flag : Fin (branch i) → FiniteDistribution Bool) : + FiniteDistribution (Descriptor clauses rows repeats hupper hij designated hrows o) := + CompletionSoundness.sigmaLaw + (StoppedProjectedBucketIndex.baseLaw (t := t) hij hbranch flag) + (exteriorLaw clauses rows repeats hupper hij designated hrows o) + +local instance backgroundFintype : Fintype (HierarchicalMatrixTable.Background (rows := rows) + (StoppedProjectedExperiment.nativeSlots clauses o) (StoppedProjectedExperiment.upper hupper o)) := + Fintype.ofFinite _ + +local instance rowSpaceFintype : Fintype (NodeEmbedding.RowSpace + (StoppedProjectedExperiment.nativeSlots clauses o) (StoppedProjectedExperiment.upper hupper o)) := + Fintype.ofFinite _ + +def background (descriptor : Descriptor clauses rows repeats hupper hij designated hrows o) : + HierarchicalMatrixTable.Background (rows := rows) + (StoppedProjectedExperiment.nativeSlots clauses o) (StoppedProjectedExperiment.upper hupper o) := + StoppedUsefulPairLaw.background rows repeats (StoppedProjectedExperiment.upperPath hupper o) + (chosen (n := n) rows hij hrows descriptor.1) + (continuation (n := n) rows hij hrows descriptor.1) + (StoppedProjectedExperiment.nativeSlots clauses o) + (projected clauses rows hupper hij designated hrows o descriptor.1) + (projection clauses rows hupper hij designated hrows o descriptor.1) descriptor.2 + +def scalarLaw (descriptor : Descriptor clauses rows repeats hupper hij designated hrows o) : + FiniteDistribution (NodeEmbedding.RowSpace + (StoppedProjectedExperiment.nativeSlots clauses o) (StoppedProjectedExperiment.upper hupper o)) := + StoppedUsefulPairLaw.scalarLaw rows repeats (StoppedProjectedExperiment.upperPath hupper o) + (chosen (n := n) rows hij hrows descriptor.1) + (continuation (n := n) rows hij hrows descriptor.1) + (StoppedProjectedExperiment.nativeSlots clauses o) + (projected clauses rows hupper hij designated hrows o descriptor.1) + (projection clauses rows hupper hij designated hrows o descriptor.1) descriptor.2 + +variable (hbranch : ∀ k < j + 1, 0 < branch k) + (flag : Fin (branch i) → FiniteDistribution Bool) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + +abbrev experiment := + StoppedProjectedExperiment.experiment clauses rows repeats hupper hij designated + hbranch hrows flag σ o + +include hrows in +theorem rows_positive : 0 < rows (Nodes.height (StoppedProjectedExperiment.upper hupper o)) := by + rw [StoppedProjectedExperiment.upper_height] + exact hrows j + +def usefulProbability (κ : ℝ) : ℝ := + HierarchicalAdviceFromBuckets.usefulProbability + (experiment clauses rows repeats hupper hij designated hrows o hbranch flag σ) κ + (externalLaw clauses rows repeats hupper hij designated hrows o hbranch flag) + (background clauses rows repeats hupper hij designated hrows o) + (scalarLaw clauses rows repeats hupper hij designated hrows o) + (rows_positive rows hupper hrows o) + +theorem usefulProbability_eq_mean (κ : ℝ) : + usefulProbability clauses rows repeats hupper hij designated hrows o hbranch flag σ κ = + (StoppedProjectedBucketIndex.baseLaw (t := t) hij hbranch flag).expectation (fun base => + HierarchicalAdviceFromBuckets.usefulProbability + (experiment clauses rows repeats hupper hij designated hrows o hbranch flag σ) κ + (exteriorLaw clauses rows repeats hupper hij designated hrows o base) + (fun external => background clauses rows repeats hupper hij designated hrows o + ⟨base, external⟩) + (fun external => scalarLaw clauses rows repeats hupper hij designated hrows o + ⟨base, external⟩) + (rows_positive rows hupper hrows o)) := by + simp only [usefulProbability, HierarchicalAdviceFromBuckets.usefulProbability, + HierarchicalUsefulCollision.law, CompletionSoundness.sigmaLaw_probability, + externalLaw, CandidateCoupling.expectation_sigmaLaw, + HierarchicalUsefulCollision.usefulEvent] + +end +end PerfectCompleteness.StoppedProjectedBuckets + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/TreeCanonical.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/TreeCanonical.lean new file mode 100644 index 0000000000000000000000000000000000000000..2ce98903eb9703b7dd9f9b37fef63881a3ac8014 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/TreeCanonical.lean @@ -0,0 +1,127 @@ +import Mathlib.Data.Fintype.EquivFin +import Mathlib.Logic.Equiv.Basic +import OAI.Computability.PerfectCompleteness.Construction.TreeSourceSpaces +import OAI.Computability.PerfectCompleteness.Foundations.CanonicalKeys + +namespace OAI + +section + +namespace PerfectCompleteness.TreeCanonical + +open MixedSupport TreeSourceSpaces + +noncomputable section + +abbrev Location (branch : Nat → Nat) (n t : Nat) := RecursiveSpaces.Slots branch n × Fin t + +def locationCount (branch : Nat → Nat) (n t : Nat) : Nat := + Fintype.card (Location branch n t) + +def numbering (branch : Nat → Nat) (n t : Nat) : + Location branch n t ≃ Fin (locationCount branch n t) := + Fintype.equivFin (Location branch n t) + +variable {branch : Nat → Nat} {n t : Nat} {Y : Type*} + +def numberedSlots (slots : RecursiveSpaces.Slots branch n → Fin t → Slot) : + Fin (locationCount branch n t) → Slot := + fun j => flatSlots slots ((numbering branch n t).symm j) + +def assignmentEquiv (slots : RecursiveSpaces.Slots branch n → Fin t → Slot) : + Domain slots ≃ MixedSupport.Assignment (numberedSlots slots) := + (flattenAssignment slots).trans + (Equiv.piCongrLeft' (fun sk : Location branch n t => (flatSlots slots sk).Domain) + (numbering branch n t)) + +@[simp] theorem assignmentEquiv_apply + (slots : RecursiveSpaces.Slots branch n → Fin t → Slot) (x : Domain slots) + (j : Fin (locationCount branch n t)) : + assignmentEquiv slots x j = + x ((numbering branch n t).symm j).1 ((numbering branch n t).symm j).2 := rfl + +def numberedProjection {slots projected : RecursiveSpaces.Slots branch n → Fin t → Slot} + (p : ∀ s k, Projection (slots s k) (projected s k)) : + ∀ j, Projection (numberedSlots slots j) (numberedSlots projected j) := + fun j => p ((numbering branch n t).symm j).1 ((numbering branch n t).symm j).2 + +theorem assignmentEquiv_projection + {slots projected : RecursiveSpaces.Slots branch n → Fin t → Slot} + (p : ∀ s k, Projection (slots s k) (projected s k)) (x : Domain slots) : + assignmentEquiv projected (sourceProjection p x) = + MixedSupport.projectionMap (numberedProjection p) (assignmentEquiv slots x) := rfl + +theorem assignmentEquiv_symm_projection + {slots projected : RecursiveSpaces.Slots branch n → Fin t → Slot} + (p : ∀ s k, Projection (slots s k) (projected s k)) + (x : MixedSupport.Assignment (numberedSlots slots)) : + sourceProjection p ((assignmentEquiv slots).symm x) = + (assignmentEquiv projected).symm (MixedSupport.projectionMap (numberedProjection p) x) := by + apply (assignmentEquiv projected).injective + simpa only [Equiv.apply_symm_apply] using + assignmentEquiv_projection p ((assignmentEquiv slots).symm x) + +def numberedFunction (slots : RecursiveSpaces.Slots branch n → Fin t → Slot) + (f : Domain slots → Y) : MixedSupport.Assignment (numberedSlots slots) → Y := + f ∘ (assignmentEquiv slots).symm + +theorem numberedFunction_projection + {slots projected : RecursiveSpaces.Slots branch n → Fin t → Slot} + (p : ∀ s k, Projection (slots s k) (projected s k)) (f : Domain projected → Y) : + numberedFunction slots (f ∘ sourceProjection p) = + numberedFunction projected f ∘ MixedSupport.projectionMap (numberedProjection p) := by + funext x + exact congrArg f (assignmentEquiv_symm_projection p x) + +def key (side : CanonicalKeys.Side) + (slots : RecursiveSpaces.Slots branch n → Fin t → Slot) (f : Domain slots → Y) : + CanonicalKeys.Key (locationCount branch n t) := + CanonicalKeys.key side (numberedSlots slots) (numberedFunction slots f) + +theorem key_projection (side : CanonicalKeys.Side) + {slots projected : RecursiveSpaces.Slots branch n → Fin t → Slot} + (p : ∀ s k, Projection (slots s k) (projected s k)) (f : Domain projected → Y) : + key side slots (f ∘ sourceProjection p) = key side projected f := by + unfold key + rw [numberedFunction_projection] + exact CanonicalKeys.key_projection side (numberedProjection p) (numberedFunction projected f) + +theorem H_key_projection (side : CanonicalKeys.Side) + {slots projected : RecursiveSpaces.Slots branch n → Fin t → Slot} + (p : ∀ s k, Projection (slots s k) (projected s k)) (f : H projected) : + key side slots (HPullback p f).val = key side projected f.val := + key_projection side p f.val + +abbrev Label (slots : RecursiveSpaces.Slots branch n → Fin t → Slot) + (f : Domain slots → Y) := + CanonicalKeys.Label (numberedSlots slots) (numberedFunction slots f) + +def evaluateLabel (slots : RecursiveSpaces.Slots branch n → Fin t → Slot) + (f : Domain slots → Y) (x : Domain slots) : Label slots f := + CanonicalKeys.evaluateLabel (numberedSlots slots) (numberedFunction slots f) + (assignmentEquiv slots x) + +def restore (slots : RecursiveSpaces.Slots branch n → Fin t → Slot) + (f : Domain slots → Y) (P : Label slots f) : Y := + CanonicalKeys.restore (numberedSlots slots) (numberedFunction slots f) P + +@[simp] theorem restore_evaluateLabel + (slots : RecursiveSpaces.Slots branch n → Fin t → Slot) + (f : Domain slots → Y) (x : Domain slots) : + restore slots f (evaluateLabel slots f x) = f x := by + simpa only [restore, evaluateLabel, numberedFunction, Function.comp_apply, + Equiv.symm_apply_apply] using + CanonicalKeys.restore_evaluateLabel (numberedSlots slots) (numberedFunction slots f) + (assignmentEquiv slots x) + +theorem restore_injective (slots : RecursiveSpaces.Slots branch n → Fin t → Slot) + (f : Domain slots → Y) : Function.Injective (restore slots f) := + CanonicalKeys.restore_injective (numberedSlots slots) (numberedFunction slots f) + +end + +end PerfectCompleteness.TreeCanonical + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/TreeSourceSpaces.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/TreeSourceSpaces.lean new file mode 100644 index 0000000000000000000000000000000000000000..ca212c6937f10f738e52cdf1afd5e8f2c00d634c --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/TreeSourceSpaces.lean @@ -0,0 +1,159 @@ +import Mathlib.Algebra.Field.ZMod +import OAI.Computability.PerfectCompleteness.Foundations.ClauseSupportLemmas +import OAI.Computability.PerfectCompleteness.Foundations.RecursiveSpaces + +namespace OAI + +section + +namespace PerfectCompleteness.TreeSourceSpaces + +open MixedSupport + +abbrev F2 := ZMod 2 + +variable {branch : Nat → Nat} {n t : Nat} + +instance slotDomainFintype (s : Slot) : Fintype s.Domain := by + cases s with + | clause occurrence variableIDs signs => + exact inferInstanceAs (Fintype (ClauseSupport.Answer signs)) + | bit variableID => exact inferInstanceAs (Fintype Bool) + +abbrev LeafDomain (slots : RecursiveSpaces.Slots branch n → Fin t → Slot) + (s : RecursiveSpaces.Slots branch n) := MixedSupport.Assignment (slots s) + +abbrev Domain (slots : RecursiveSpaces.Slots branch n → Fin t → Slot) := + RecursiveSpaces.Assignment (LeafDomain slots) + +abbrev H (slots : RecursiveSpaces.Slots branch n → Fin t → Slot) : + Submodule F2 (Domain slots → F2) := + RecursiveSpaces.space F2 branch n (LeafDomain slots) + +theorem domain_nonempty (slots : RecursiveSpaces.Slots branch n → Fin t → Slot) : + Nonempty (Domain slots) := by + infer_instance + +theorem domain_finite (slots : RecursiveSpaces.Slots branch n → Fin t → Slot) : + Finite (Domain slots) := by + infer_instance + +theorem H_finite (slots : RecursiveSpaces.Slots branch n → Fin t → Slot) : + Finite (H slots) := by + infer_instance + +theorem one_mem_H (slots : RecursiveSpaces.Slots branch n → Fin t → Slot) + (hbranch : ∀ k < n, 0 < branch k) : (1 : Domain slots → F2) ∈ H slots := + RecursiveSpaces.one_mem_space branch n (LeafDomain slots) hbranch + +theorem H_le_squareSpace (slots : RecursiveSpaces.Slots branch n → Fin t → Slot) + (hbranch : ∀ k < n, 0 < branch k) : H slots ≤ PointwiseSpaces.squareSpace (H slots) := + RecursiveSpaces.space_le_squareSpace (LeafDomain slots) hbranch + +theorem one_mem_squareSpace (slots : RecursiveSpaces.Slots branch n → Fin t → Slot) + (hbranch : ∀ k < n, 0 < branch k) : + (1 : Domain slots → F2) ∈ PointwiseSpaces.squareSpace (H slots) := + RecursiveSpaces.one_mem_space_square (LeafDomain slots) hbranch + +def sourceProjection {slots projected : RecursiveSpaces.Slots branch n → Fin t → Slot} + (p : ∀ s k, Projection (slots s k) (projected s k)) : + Domain slots → Domain projected := + RecursiveSpaces.project (fun s => MixedSupport.projectionMap (p s)) + +@[simp] theorem sourceProjection_apply + {slots projected : RecursiveSpaces.Slots branch n → Fin t → Slot} + (p : ∀ s k, Projection (slots s k) (projected s k)) + (x : Domain slots) (s : RecursiveSpaces.Slots branch n) (k : Fin t) : + sourceProjection p x s k = (p s k).map (x s k) := rfl + +theorem sourceProjection_surjective + {slots projected : RecursiveSpaces.Slots branch n → Fin t → Slot} + (p : ∀ s k, Projection (slots s k) (projected s k)) : + Function.Surjective (sourceProjection p) := + RecursiveSpaces.project_surjective _ + (fun s => MixedSupport.projectionMap_surjective (p s)) + +theorem H_pullback_le {slots projected : RecursiveSpaces.Slots branch n → Fin t → Slot} + (p : ∀ s k, Projection (slots s k) (projected s k)) : + (H projected).map (PointwiseSpaces.pullback F2 (sourceProjection p)) ≤ H slots := + RecursiveSpaces.space_project_le branch n (LeafDomain slots) (LeafDomain projected) + (fun s => MixedSupport.projectionMap (p s)) + +theorem squareSpace_pullback_le + {slots projected : RecursiveSpaces.Slots branch n → Fin t → Slot} + (p : ∀ s k, Projection (slots s k) (projected s k)) : + (PointwiseSpaces.squareSpace (H projected)).map + (PointwiseSpaces.pullback F2 (sourceProjection p)) ≤ + PointwiseSpaces.squareSpace (H slots) := + PointwiseSpaces.squareSpace_pullback_le _ _ _ (H_pullback_le p) + +def HPullback {slots projected : RecursiveSpaces.Slots branch n → Fin t → Slot} + (p : ∀ s k, Projection (slots s k) (projected s k)) : H projected →ₗ[F2] H slots := + RecursiveSpaces.spacePullback (LeafDomain slots) (LeafDomain projected) + (fun s => MixedSupport.projectionMap (p s)) + +@[simp] theorem HPullback_apply + {slots projected : RecursiveSpaces.Slots branch n → Fin t → Slot} + (p : ∀ s k, Projection (slots s k) (projected s k)) + (f : H projected) (x : Domain slots) : + (HPullback p f).val x = f.val (sourceProjection p x) := rfl + +theorem HPullback_injective + {slots projected : RecursiveSpaces.Slots branch n → Fin t → Slot} + (p : ∀ s k, Projection (slots s k) (projected s k)) : + Function.Injective (HPullback p) := + RecursiveSpaces.spacePullback_injective (LeafDomain slots) (LeafDomain projected) + (fun s => MixedSupport.projectionMap (p s)) + (fun s => MixedSupport.projectionMap_surjective (p s)) + +abbrev childSlots (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → Slot) + (i : Fin (branch n)) : RecursiveSpaces.Slots branch n → Fin t → Slot := + fun s => slots (i, s) + +def restrictChild (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → Slot) + (i : Fin (branch n)) : Domain slots → Domain (childSlots slots i) := + RecursiveSpaces.childRestriction (LeafDomain slots) i + +theorem child_square_le_H (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → Slot) + (i : Fin (branch n)) : + (PointwiseSpaces.squareSpace (H (childSlots slots i))).map + (PointwiseSpaces.pullback F2 (restrictChild slots i)) ≤ H slots := + RecursiveSpaces.child_square_le_space (LeafDomain slots) i + +theorem child_H_le_H (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → Slot) + (i : Fin (branch n)) (hbranch : ∀ k < n, 0 < branch k) : + (H (childSlots slots i)).map (PointwiseSpaces.pullback F2 (restrictChild slots i)) ≤ H slots := + RecursiveSpaces.child_le_space (LeafDomain slots) i hbranch + +theorem restrictChild_surjective (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → Slot) + (i : Fin (branch n)) : Function.Surjective (restrictChild slots i) := + RecursiveSpaces.childRestriction_surjective (LeafDomain slots) (fun _ => inferInstance) i + +def flatSlots (slots : RecursiveSpaces.Slots branch n → Fin t → Slot) : + RecursiveSpaces.Slots branch n × Fin t → Slot := fun sk => slots sk.1 sk.2 + +def flattenAssignment (slots : RecursiveSpaces.Slots branch n → Fin t → Slot) : + Domain slots ≃ MixedSupport.Assignment (flatSlots slots) where + toFun x sk := x sk.1 sk.2 + invFun x s k := x (s, k) + left_inv x := by + funext s k + rfl + right_inv x := by + funext sk + cases sk + rfl + +theorem flattenAssignment_projection + {slots projected : RecursiveSpaces.Slots branch n → Fin t → Slot} + (p : ∀ s k, Projection (slots s k) (projected s k)) (x : Domain slots) : + flattenAssignment projected (sourceProjection p x) = + MixedSupport.projectionMap + (fun sk : RecursiveSpaces.Slots branch n × Fin t => p sk.1 sk.2) + (flattenAssignment slots x) := rfl + +end PerfectCompleteness.TreeSourceSpaces + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Construction/WholeCutLocalityLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Construction/WholeCutLocalityLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..89f8212df1814ddba1d93779dc203eebb8cc7085 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Construction/WholeCutLocalityLemmas.lean @@ -0,0 +1,278 @@ +import OAI.Computability.PerfectCompleteness.Foundations.WholeCutExteriorTransportLemmas +import OAI.Computability.PerfectCompleteness.Sampling.CutSamplerKeyLocalityLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.WholeCutLocality + +open scoped BigOperators Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays + +abbrev F2 := ZMod 2 + +noncomputable section + +variable {branch : Nat → Nat} {n m t : Nat} + +theorem evaluate_root (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (tape : WholeCutSampler.Tape rows repeats (.step i p) slots) : + WholeCutSampler.evaluate rows repeats (.step i p) slots tape (.inl ()) = + BucketSampler.evaluate (rows (n + 1)) + (CutSamplerRefinement.evaluate F2 repeats (.step i p) (LeafDomain slots)) tape.1 := rfl + +theorem evaluate_selected (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (tape : WholeCutSampler.Tape rows repeats (.step i p) slots) (node : Nodes branch n) : + WholeCutSampler.evaluate rows repeats (.step i p) slots tape (.inr (i, node)) = + WholeCutSampler.evaluate rows repeats p (childSlots slots i) tape.2.1 node := by + unfold WholeCutSampler.evaluate + rw [WholeArraySampler.evaluate_selected] + rfl + +theorem evaluate_ordinary (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (tape : WholeCutSampler.Tape rows repeats (.step i p) slots) + (j : RecursiveSampler.OffPath i) (node : Nodes branch n) : + WholeCutSampler.evaluate rows repeats (.step i p) slots tape (.inr (j.val, node)) = + tape.2.2 j node := by + unfold WholeCutSampler.evaluate + rw [WholeArraySampler.evaluate_ordinary] + rfl + +theorem joint_eq_of_view_eq (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) : + ∀ (slots : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (tape : WholeCutSampler.Tape rows repeats p slots), + WholeCutZero.ZeroAtClean rows repeats p slots clean tape → + ∀ x y : Domain slots, + CutSamplerLocality.view p (LeafDomain slots) clean x = + CutSamplerLocality.view p (LeafDomain slots) clean y → + joint (WholeCutSampler.evaluate rows repeats p slots tape) x = + joint (WholeCutSampler.evaluate rows repeats p slots tape) y := by + induction n generalizing m with + | zero => + have h := p.height_le + omega + | succ n ih => + cases p with + | refl => + intro slots clean tape hzero x y hview + funext node row + rcases node with u | ⟨i, node⟩ + · cases u + let scalarTape : CutSamplerRefinement.Tape F2 repeats (.refl (n + 1)) + (LeafDomain slots) := fun _ i => (tape i).1 row + have hz : CutSamplerLocality.ZeroAtClean F2 repeats (.refl (n + 1)) + (LeafDomain slots) clean scalarTape := + fun i hi => (hzero i hi).1 row + exact CutSamplerLocality.evaluate_eq_of_view_eq F2 repeats (.refl (n + 1)) + (LeafDomain slots) clean scalarTape hz x y hview + · change ((tape i).2 node row).val + (restrictNode (childSlots slots i) node (restrictChild slots i x)) = + ((tape i).2 node row).val + (restrictNode (childSlots slots i) node (restrictChild slots i y)) + by_cases hi : clean i + · rw [(hzero i hi).2 node row] + rfl + · exact congrArg + (fun z => ((tape i).2 node row).val (restrictNode (childSlots slots i) node z)) + (congrFun hview ⟨i, hi⟩) + | step i p => + intro slots clean tape hzero x y hview + have hout : ∀ j : RecursiveSampler.OffPath i, + restrictChild slots j.val x = restrictChild slots j.val y := + congrFun (congrArg Prod.fst hview) + have hin : + CutSamplerLocality.view p (LeafDomain (childSlots slots i)) clean + (restrictChild slots i x) = + CutSamplerLocality.view p (LeafDomain (childSlots slots i)) clean + (restrictChild slots i y) := congrArg Prod.snd hview + funext node row + rcases node with u | ⟨j, node⟩ + · cases u + change + (WholeCutSampler.evaluate rows repeats (.step i p) slots tape (.inl ()) row).val x = + (WholeCutSampler.evaluate rows repeats (.step i p) slots tape (.inl ()) row).val y + simp only [evaluate_root] + have hx := BucketSampler.evaluate_apply (rows (n + 1)) + (space F2 branch (n + 1) (LeafDomain slots)) + (CutSamplerRefinement.evaluate F2 repeats (.step i p) (LeafDomain slots)) + tape.1 row x + have hy := BucketSampler.evaluate_apply (rows (n + 1)) + (space F2 branch (n + 1) (LeafDomain slots)) + (CutSamplerRefinement.evaluate F2 repeats (.step i p) (LeafDomain slots)) + tape.1 row y + refine hx.trans (Eq.trans ?_ hy.symm) + refine Finset.sum_congr (ι := BucketSampler.Direction (rows (n + 1))) ?_ ?_ + · ext v + simp only [Finset.mem_univ] + · intro v _ + exact congrArg (fun z : F2 => v.val row * z) + (CutSamplerLocality.evaluate_eq_of_view_eq F2 repeats (.step i p) + (LeafDomain slots) clean (tape.1 v) (hzero.1 v) x y hview) + · by_cases hji : j = i + · subst j + have hselected := ih p (childSlots slots i) clean tape.2.1 hzero.2 + (restrictChild slots i x) (restrictChild slots i y) hin + have hrow := congrFun (congrFun hselected node) row + change + (WholeCutSampler.evaluate rows repeats (.step i p) slots tape + (.inr (i, node)) row).val + (restrictNode (childSlots slots i) node (restrictChild slots i x)) = + (WholeCutSampler.evaluate rows repeats (.step i p) slots tape + (.inr (i, node)) row).val + (restrictNode (childSlots slots i) node (restrictChild slots i y)) + simp only [evaluate_selected] + exact hrow + · change + (WholeCutSampler.evaluate rows repeats (.step i p) slots tape + (.inr (j, node)) row).val + (restrictNode (childSlots slots j) node (restrictChild slots j x)) = + (WholeCutSampler.evaluate rows repeats (.step i p) slots tape + (.inr (j, node)) row).val + (restrictNode (childSlots slots j) node (restrictChild slots j y)) + rw [evaluate_ordinary rows repeats i p slots tape ⟨j, hji⟩ node] + rw [hout ⟨j, hji⟩] + +theorem joint_eq_of_grouped_zero (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (tape : WholeCutSampler.Tape rows repeats p slots) + (hzero : WholeCutZero.GroupedAtClean rows repeats p slots clean tape) + (x y : Domain slots) + (hview : CutSamplerLocality.view p (LeafDomain slots) clean x = + CutSamplerLocality.view p (LeafDomain slots) clean y) : + joint (WholeCutSampler.evaluate rows repeats p slots tape) x = + joint (WholeCutSampler.evaluate rows repeats p slots tape) y := + joint_eq_of_view_eq rows repeats p slots clean tape + ((WholeCutZero.grouped_iff rows repeats p slots clean tape).mp hzero) x y hview + +theorem fullJoint_eq_of_grouped_zero (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (tape : WholeCutSampler.Tape rows repeats p slots) + (hzero : WholeCutZero.GroupedAtClean rows repeats p slots clean tape) + (x y : Domain slots) + (hview : CutSamplerLocality.view p (LeafDomain slots) clean x = + CutSamplerLocality.view p (LeafDomain slots) clean y) : + fullJoint (WholeCutSampler.evaluate rows repeats p slots tape) x = + fullJoint (WholeCutSampler.evaluate rows repeats p slots tape) y := + Prod.ext (joint_eq_of_grouped_zero rows repeats p slots clean tape hzero x y hview) rfl + +end +end PerfectCompleteness.WholeCutLocality + +end + +section + +namespace PerfectCompleteness.WholeCutKeyLocality + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open CutSamplerKeyLocality + +noncomputable section + +variable {branch : Nat → Nat} {n m t : Nat} {Y : Type*} + (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (tape : WholeCutSampler.Tape rows repeats p slots) + (post : Output branch n rows → Y) + +def query : MixedSupport.Assignment (TreeCanonical.numberedSlots slots) → Y := + post ∘ TreeCanonical.numberedFunction slots + (fullJoint (WholeCutSampler.evaluate rows repeats p slots tape)) + +theorem query_constant + (hzero : WholeCutZero.GroupedAtClean rows repeats p slots clean tape) + (x y : MixedSupport.Assignment (TreeCanonical.numberedSlots slots)) + (hret : CleanKeyErasure.retain (TreeCanonical.numberedSlots slots) (numberedKeep p clean) x = + CleanKeyErasure.retain (TreeCanonical.numberedSlots slots) (numberedKeep p clean) y) : + query rows repeats p slots tape post x = query rows repeats p slots tape post y := + congrArg post (WholeCutLocality.fullJoint_eq_of_grouped_zero rows repeats p slots clean + tape hzero _ _ (view_eq_of_retained p slots clean x y hret)) + +def retainedQuery : CleanKeyErasure.Retained (TreeCanonical.numberedSlots slots) + (numberedKeep p clean) → Y := + query rows repeats p slots tape post ∘ + CleanKeyFactorization.fill (TreeCanonical.numberedSlots slots) (numberedKeep p clean) + +theorem retainedQuery_eq_of_extension + (hzero : WholeCutZero.GroupedAtClean rows repeats p slots clean tape) + (x : CleanKeyErasure.Retained (TreeCanonical.numberedSlots slots) (numberedKeep p clean)) + (y : MixedSupport.Assignment (TreeCanonical.numberedSlots slots)) + (hy : CleanKeyErasure.retain (TreeCanonical.numberedSlots slots) (numberedKeep p clean) y = x) : + retainedQuery rows repeats p slots clean tape post x = + query rows repeats p slots tape post y := by + apply query_constant rows repeats p slots clean tape post hzero + exact (CleanKeyFactorization.retain_fill (TreeCanonical.numberedSlots slots) + (numberedKeep p clean) x).trans hy.symm + +theorem query_factor + (hzero : WholeCutZero.GroupedAtClean rows repeats p slots clean tape) : + query rows repeats p slots tape post = retainedQuery rows repeats p slots clean tape post ∘ + CleanKeyErasure.retain (TreeCanonical.numberedSlots slots) (numberedKeep p clean) := by + funext x + exact (retainedQuery_eq_of_extension rows repeats p slots clean tape post hzero _ x rfl).symm + +theorem clean_position_dropped + (hzero : WholeCutZero.GroupedAtClean rows repeats p slots clean tape) + (i : Fin (branch m)) (hi : clean i) (s : Slots branch m) (k : Fin t) : + MixedSupport.keyFields (TreeCanonical.numberedSlots slots) + (query rows repeats p slots tape post) + (TreeCanonical.numbering branch n t (p.slotEmbedding (i, s), k)) = .dropped := + CleanKeyErasure.keyFields_dropped_of_retained (TreeCanonical.numberedSlots slots) + (numberedKeep p clean) (query rows repeats p slots tape post) + (query_constant rows repeats p slots clean tape post hzero) _ + (not_numberedKeep_clean p clean i hi s k) + +theorem key_eq_retained + (hzero : WholeCutZero.GroupedAtClean rows repeats p slots clean tape) + (side : CanonicalKeys.Side) : + CanonicalKeys.key side (TreeCanonical.numberedSlots slots) + (query rows repeats p slots tape post) = + CleanKeyFactorization.retainedKey side (numberedKeep p clean) + (CleanKeyFactorization.retainedSlots (TreeCanonical.numberedSlots slots) (numberedKeep p clean)) + (retainedQuery rows repeats p slots clean tape post) := by + rw [query_factor rows repeats p slots clean tape post hzero] + exact CleanKeyFactorization.key_factor side (TreeCanonical.numberedSlots slots) + (numberedKeep p clean) (retainedQuery rows repeats p slots clean tape post) + +theorem label_eq_retained + (hzero : WholeCutZero.GroupedAtClean rows repeats p slots clean tape) + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (side : CanonicalKeys.Side) : + (KeyStrategy.label labeling side (TreeCanonical.numberedSlots slots) + (query rows repeats p slots tape post)).val = + (labeling (CleanKeyFactorization.retainedQueryKey side (numberedKeep p clean) + (CleanKeyFactorization.retainedSlots (TreeCanonical.numberedSlots slots) (numberedKeep p clean)) + (retainedQuery rows repeats p slots clean tape post))).val := by + rw [query_factor rows repeats p slots clean tape post hzero] + exact CleanKeyFactorization.label_factor labeling side (TreeCanonical.numberedSlots slots) + (numberedKeep p clean) (retainedQuery rows repeats p slots clean tape post) + +theorem response_eq_retained + (hzero : WholeCutZero.GroupedAtClean rows repeats p slots clean tape) + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (side : CanonicalKeys.Side) : + KeyStrategy.response labeling side (TreeCanonical.numberedSlots slots) + (query rows repeats p slots tape post) = + CleanKeyFactorization.retainedResponse labeling side (numberedKeep p clean) + (CleanKeyFactorization.retainedSlots (TreeCanonical.numberedSlots slots) (numberedKeep p clean)) + (retainedQuery rows repeats p slots clean tape post) := by + rw [query_factor rows repeats p slots clean tape post hzero] + exact CleanKeyFactorization.response_factor labeling side (TreeCanonical.numberedSlots slots) + (numberedKeep p clean) (retainedQuery rows repeats p slots clean tape post) + +end +end PerfectCompleteness.WholeCutKeyLocality + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/BucketUsefulCollision.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/BucketUsefulCollision.lean new file mode 100644 index 0000000000000000000000000000000000000000..9d7eccdbf18e3ea1aa5bd790e6c9aa65cd56dff3 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/BucketUsefulCollision.lean @@ -0,0 +1,170 @@ +import OAI.Computability.PerfectCompleteness.Algebra.BucketMatrixResampling +import OAI.Computability.PerfectCompleteness.Decoding.CollisionAveragingLemmas +import OAI.Computability.PerfectCompleteness.Decoding.RepresentativeBucketCollisionLemmas +import OAI.Computability.PerfectCompleteness.Foundations.QuarterBalanceLemmas + +namespace OAI + + +namespace PerfectCompleteness.BucketUsefulCollision + +noncomputable section + +open scoped Classical +open ClauseSupport MixedSupport +open UniqueGamesTheorem.Foundations.Games +open BucketSampler (F2 Direction Tape) + +section Product + +variable {H : Type*} {ℓ : Nat} + +def fill (a : Direction ℓ) + (b : FiniteProductSplit.Others (Ω := fun _ : Direction ℓ => H) a) + (h : H) : Tape ℓ H := + fun d => if hd : d = a then h else b ⟨d, hd⟩ + +@[simp] theorem fill_self (a : Direction ℓ) + (b : FiniteProductSplit.Others (Ω := fun _ : Direction ℓ => H) a) + (h : H) : fill a b h a = h := by + simp [fill] + +theorem fill_update (a : Direction ℓ) + (b : FiniteProductSplit.Others (Ω := fun _ : Direction ℓ => H) a) + (h h' : H) : Function.update (fill a b h) a h' = fill a b h' := by + funext d + by_cases hd : d = a + · subst d + simp [fill] + · simp only [Function.update_of_ne hd, fill, dite_eq_right hd] + +theorem fill_others (a : Direction ℓ) (t : Tape ℓ H) : + fill a (FiniteProductSplit.others a t) (t a) = t := by + funext d + by_cases hd : d = a + · subst d + simp [fill] + · simp only [fill, dite_eq_right hd, FiniteProductSplit.others] + +theorem fill_others_update (a : Direction ℓ) (t : Tape ℓ H) (h : H) : + fill a (FiniteProductSplit.others a t) h = Function.update t a h := by + rw [← fill_update a (FiniteProductSplit.others a t) (t a) h, fill_others] + +private theorem probability_eq_expectation {A : Type*} [Fintype A] + (μ : FiniteDistribution A) (event : A → Bool) : + μ.probability event = μ.expectation (fun x => if event x then 1 else 0) := by + simp only [FiniteDistribution.probability, FiniteDistribution.expectation, + mul_ite, mul_one, mul_zero] + +variable [Fintype H] + +theorem probability_background_first (μ : FiniteDistribution H) + (a : Direction ℓ) (event : Tape ℓ H → Bool) : + (BucketSampler.tapeLaw ℓ μ).probability event = + (FiniteProductSplit.otherLaw (fun _ : Direction ℓ => μ) a).expectation + (fun b => μ.probability (fun h => event (fill a b h))) := by + have h := FiniteProductSplit.expectation_background_first + (fun _ : Direction ℓ => μ) a + (fun h b => if event (fill a b h) then (1 : ℝ) else 0) + simpa only [fill_others, ← probability_eq_expectation, BucketSampler.tapeLaw] using h + +theorem probability_resampling (μ : FiniteDistribution H) + (a : Direction ℓ) (event : Tape ℓ H → Tape ℓ H → Bool) : + ((BucketSampler.tapeLaw ℓ μ).product μ).probability + (fun z => event z.1 (Function.update z.1 a z.2)) = + (FiniteProductSplit.otherLaw (fun _ : Direction ℓ => μ) a).expectation + (fun b => (μ.product μ).probability + (fun z => event (fill a b z.1) (fill a b z.2))) := by + have h := FiniteProductSplit.resampling_expectation + (fun _ : Direction ℓ => μ) a + (fun b h h' => if event (fill a b h) (fill a b h') then (1 : ℝ) else 0) + simp only [fill_others] at h + simpa only [fill_others_update, ← probability_eq_expectation, BucketSampler.tapeLaw] using h + +end Product + + +variable {n ℓ : Nat} {Z : Type*} + (slots : Fin n → Slot) (V : Submodule F2 (Assignment slots → F2)) + (other : Assignment slots → Z) (σ : KeyStrategy.Strategy n) + (W : Submodule F2 V) (s : (V ⧸ W) →ₗ[F2] V) + +theorem assembledMatrix_fill (a : Direction ℓ) + (b : FiniteProductSplit.Others (Ω := fun _ : Direction ℓ => V) a) (h : V) : + BucketMatrixResampling.assembledMatrix V ℓ (fill a b h) = + EvaluationMatrix.shift V + (BucketMatrixResampling.assembledMatrix V ℓ (fill a b 0)) a.val h := by + have he := BucketMatrixResampling.assembledMatrix_update V ℓ (fill a b 0) a h + rw [fill_update] at he + simpa only [fill_self, sub_zero] using he + +variable [Fintype V] [Finite Z] + +theorem collision_probability_lower_bound + (hs : W.mkQ.comp s = LinearMap.id) + (hW : RepresentativeMatrixTable.Determined slots V other W) + (μ : FiniteDistribution V) + (useful : (Module.Dual F2 (V ⧸ W) →ₗ[F2] (Fin ℓ → F2)) → Prop) + (a : Direction ℓ) : + (BucketSampler.tapeLaw ℓ μ).probability + (fun t => decide (CanonicalMatrixTable.Accepts slots V other σ a.val + (BucketMatrixResampling.assembledMatrix V ℓ t)) && + (RepresentativeMatrixTable.partialTable slots V other σ W s useful + (MatrixRowQuotient.projectMatrix W + (BucketMatrixResampling.assembledMatrix V ℓ t))).isSome) ^ 2 / 2 ≤ + ((BucketSampler.tapeLaw ℓ μ).product μ).probability + (fun z => TwoResponseCollision.collision + (RepresentativeMatrixTable.partialTable slots V other σ W s useful) + (MatrixRowQuotient.projectMatrix W + (BucketMatrixResampling.assembledMatrix V ℓ z.1), + MatrixRowQuotient.projectMatrix W + (BucketMatrixResampling.assembledMatrix V ℓ (Function.update z.1 a z.2)))) := by + let f := RepresentativeMatrixTable.partialTable slots V other σ W s useful + let good : Tape ℓ V → Bool := fun t => + decide (CanonicalMatrixTable.Accepts slots V other σ a.val + (BucketMatrixResampling.assembledMatrix V ℓ t)) && + (f (MatrixRowQuotient.projectMatrix W + (BucketMatrixResampling.assembledMatrix V ℓ t))).isSome + let collision : Tape ℓ V → Tape ℓ V → Bool := fun t t' => + TwoResponseCollision.collision f + (MatrixRowQuotient.projectMatrix W (BucketMatrixResampling.assembledMatrix V ℓ t), + MatrixRowQuotient.projectMatrix W (BucketMatrixResampling.assembledMatrix V ℓ t')) + change (BucketSampler.tapeLaw ℓ μ).probability good ^ 2 / 2 ≤ + ((BucketSampler.tapeLaw ℓ μ).product μ).probability + (fun z => collision z.1 (Function.update z.1 a z.2)) + rw [probability_background_first μ a good, probability_resampling μ a collision] + apply CollisionAveraging.average_square_bound + intro b + have hgood : (fun h : V => good (fill a b h)) = + TwoResponseCollision.goodDefined + (RepresentativeBucketCollision.bucketTable slots V other σ W s useful a.val + (BucketMatrixResampling.assembledMatrix V ℓ (fill a b 0))) + (RepresentativeBucketCollision.bucketAccepted slots V other σ a.val + (BucketMatrixResampling.assembledMatrix V ℓ (fill a b 0))) := by + funext h + dsimp only [good, f, TwoResponseCollision.goodDefined, + RepresentativeBucketCollision.bucketTable, RepresentativeBucketCollision.bucketAccepted] + simp only [assembledMatrix_fill slots V a b h] + have htable (h : V) : + f (MatrixRowQuotient.projectMatrix W + (BucketMatrixResampling.assembledMatrix V ℓ (fill a b h))) = + RepresentativeBucketCollision.bucketTable slots V other σ W s useful a.val + (BucketMatrixResampling.assembledMatrix V ℓ (fill a b 0)) h := by + dsimp only [f, RepresentativeBucketCollision.bucketTable] + rw [assembledMatrix_fill slots V a b h] + have hcollision : + (fun z : V × V => collision (fill a b z.1) (fill a b z.2)) = + TwoResponseCollision.collision + (RepresentativeBucketCollision.bucketTable slots V other σ W s useful a.val + (BucketMatrixResampling.assembledMatrix V ℓ (fill a b 0))) := by + exact congrArg (fun g : V → Option ((Fin ℓ → F2) × Z) => + TwoResponseCollision.collision g) (funext htable) + rw [hgood, hcollision] + exact RepresentativeBucketCollision.collision_probability_lower_bound + slots V other σ W s hs hW μ useful a.val a.property + (BucketMatrixResampling.assembledMatrix V ℓ (fill a b 0)) + +end +end PerfectCompleteness.BucketUsefulCollision + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/CanonicalBucketCollision.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/CanonicalBucketCollision.lean new file mode 100644 index 0000000000000000000000000000000000000000..06a67c79ae2c84be8bc37b865188b70b1d6d57df --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/CanonicalBucketCollision.lean @@ -0,0 +1,61 @@ +import OAI.Computability.PerfectCompleteness.Algebra.CanonicalMatrixTable +import OAI.Computability.PerfectCompleteness.Decoding.TwoResponseCollisionLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.CanonicalBucketCollision + +noncomputable section + +open scoped Classical +open ClauseSupport MixedSupport CanonicalKeys +open DirectionQuotient (F2) +open CanonicalMatrixTable TwoResponseCollision +open UniqueGamesTheorem.Foundations.Games + +variable {n : Nat} {K Z : Type*} [AddCommGroup K] [Module F2 K] + (slots : Fin n → Slot) (H : Submodule F2 (Assignment slots → F2)) + (other : Assignment slots → Z) (σ : KeyStrategy.Strategy n) + +def bucketTable (useful : Matrix (K := K) slots H → Prop) (a : K) (X : Matrix (K := K) slots H) + (h : H) : Option (K × Z) := + partialTable slots H other σ useful (EvaluationMatrix.shift H X a h) + +def bucketAccepted (a : K) (X : Matrix (K := K) slots H) (h : H) : Bool := + decide (Accepts slots H other σ a (EvaluationMatrix.shift H X a h)) + +theorem bucketTable_eq_some_iff (useful : Matrix (K := K) slots H → Prop) + (a : K) (X : Matrix (K := K) slots H) (h : H) (y : K × Z) : + bucketTable slots H other σ useful a X h = some y ↔ + useful (EvaluationMatrix.shift H X a h) ∧ + response slots H other σ (EvaluationMatrix.shift H X a h) = y := by + by_cases hu : useful (EvaluationMatrix.shift H X a h) <;> + simp [bucketTable, partialTable, hu] + +theorem collision_probability_lower_bound [Finite K] [Finite Z] [Fintype H] + (μ : FiniteDistribution H) (useful : Matrix (K := K) slots H → Prop) + (a : K) (ha : a ≠ 0) (X : Matrix (K := K) slots H) : + μ.probability (goodDefined (bucketTable slots H other σ useful a X) + (bucketAccepted slots H other σ a X)) ^ 2 / 2 ≤ + (μ.product μ).probability (collision (bucketTable slots H other σ useful a X)) := by + let : Fintype K := Fintype.ofFinite K + let : Fintype Z := Fintype.ofFinite Z + apply collision_probability_ge_of_response_set μ + (bucketTable slots H other σ useful a X) (bucketAccepted slots H other σ a X) + (fun y => ∃ h : H, + Accepts slots H other σ a (EvaluationMatrix.shift H X a h) ∧ + response slots H other σ (EvaluationMatrix.shift H X a h) = y) + · exact card_accepted_responses_le_two slots H other σ a ha X + · intro h y hgood hresponse + refine ⟨h, ?_, ?_⟩ + · simpa only [bucketAccepted, decide_eq_true_eq] using hgood + · exact ((bucketTable_eq_some_iff slots H other σ useful a X h y).mp hresponse).2 + +end +end PerfectCompleteness.CanonicalBucketCollision + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/CanonicalUpperDirectionSplit.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/CanonicalUpperDirectionSplit.lean new file mode 100644 index 0000000000000000000000000000000000000000..6254e6fa190605dabd26e036857fadfeefa1ca26 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/CanonicalUpperDirectionSplit.lean @@ -0,0 +1,130 @@ +import OAI.Computability.PerfectCompleteness.Foundations.CanonicalDirections +import OAI.Computability.PerfectCompleteness.Foundations.QuarterBalanceLemmas +import OAI.Computability.PerfectCompleteness.Foundations.TupleIndexEmitterLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.CanonicalUpperDirectionSplit + +noncomputable section + +open scoped Classical +open UniqueGamesTheorem.Foundations.Games + +variable {n : Nat} + +abbrev Complement (rows : Nat → Nat) (upper : Fin n) := + FiniteProductSplit.Others + (Ω := fun level : Fin n => PrefixTests.LevelDirection rows level) upper + +def splitEquiv (rows : Nat → Nat) (upper : Fin n) : + CanonicalDirections.Tuple rows n ≃ + PrefixTests.LevelDirection rows upper × Complement rows upper := + Equiv.piSplitAt upper (fun level => PrefixTests.LevelDirection rows level) + +def complement (rows : Nat → Nat) (upper : Fin n) + (directions : CanonicalDirections.Tuple rows n) : Complement rows upper := + (splitEquiv rows upper directions).2 + +def assemble (rows : Nat → Nat) (upper : Fin n) + (direction : PrefixTests.LevelDirection rows upper) (rest : Complement rows upper) : + CanonicalDirections.Tuple rows n := + (splitEquiv rows upper).symm (direction, rest) + +@[simp] theorem split_selected (rows : Nat → Nat) (upper : Fin n) + (directions : CanonicalDirections.Tuple rows n) : + (splitEquiv rows upper directions).1 = directions upper := rfl + +@[simp] theorem complement_apply (rows : Nat → Nat) (upper : Fin n) + (directions : CanonicalDirections.Tuple rows n) (i : {i : Fin n // i ≠ upper}) : + complement rows upper directions i = directions i.val := rfl + +@[simp] theorem assemble_at_upper (rows : Nat → Nat) (upper : Fin n) + (direction : PrefixTests.LevelDirection rows upper) (rest : Complement rows upper) : + assemble rows upper direction rest upper = direction := by + exact congrArg Prod.fst ((splitEquiv rows upper).apply_symm_apply (direction, rest)) + +@[simp] theorem assemble_at_other (rows : Nat → Nat) (upper : Fin n) + (direction : PrefixTests.LevelDirection rows upper) (rest : Complement rows upper) + (i : Fin n) (hne : i ≠ upper) : + assemble rows upper direction rest i = rest ⟨i, hne⟩ := by + exact congrArg + (fun z : PrefixTests.LevelDirection rows upper × Complement rows upper => z.2 ⟨i, hne⟩) + ((splitEquiv rows upper).apply_symm_apply (direction, rest)) + +theorem assemble_split (rows : Nat → Nat) (upper : Fin n) + (directions : CanonicalDirections.Tuple rows n) : + assemble rows upper (directions upper) (complement rows upper directions) = directions := + (splitEquiv rows upper).symm_apply_apply directions + +theorem lower_preserved (rows : Nat → Nat) (upper lower : Fin n) (hne : lower ≠ upper) + (direction : PrefixTests.LevelDirection rows upper) + (directions : CanonicalDirections.Tuple rows n) : + assemble rows upper direction (complement rows upper directions) lower = directions lower := by + rw [assemble_at_other rows upper direction (complement rows upper directions) lower hne] + rfl + +def complementLaw (rows : Nat → Nat) (hrows : ∀ k, 0 < rows (k + 1)) (upper : Fin n) : + FiniteDistribution (Complement rows upper) := + FiniteProductSplit.otherLaw (CanonicalDirections.levelLaw rows hrows) upper + +theorem split_law (rows : Nat → Nat) (hrows : ∀ k, 0 < rows (k + 1)) (upper : Fin n) : + (CanonicalDirections.law rows n hrows).pushforward (splitEquiv rows upper) = + (CanonicalDirections.levelLaw rows hrows upper).product (complementLaw rows hrows upper) := + FiniteProductSplit.split_law (CanonicalDirections.levelLaw rows hrows) upper + +theorem assemble_law (rows : Nat → Nat) (hrows : ∀ k, 0 < rows (k + 1)) (upper : Fin n) : + ((CanonicalDirections.levelLaw rows hrows upper).product + (complementLaw rows hrows upper)).pushforward + (fun z => assemble rows upper z.1 z.2) = CanonicalDirections.law rows n hrows := by + have h := congrArg + (fun μ : FiniteDistribution (PrefixTests.LevelDirection rows upper × Complement rows upper) => + μ.pushforward (splitEquiv rows upper).symm) (split_law rows hrows upper) + rw [FiniteDistribution.pushforward_comp] at h + have hid : (fun directions : CanonicalDirections.Tuple rows n => + (splitEquiv rows upper).symm (splitEquiv rows upper directions)) = id := by + funext directions + exact (splitEquiv rows upper).symm_apply_apply directions + rw [hid, FiniteDistribution.pushforward_id] at h + exact h.symm + +theorem selected_law (rows : Nat → Nat) (hrows : ∀ k, 0 < rows (k + 1)) (upper : Fin n) : + (CanonicalDirections.law rows n hrows).pushforward (fun directions => directions upper) = + CanonicalDirections.levelLaw rows hrows upper := + FiniteProduct.eval_pushforward (CanonicalDirections.levelLaw rows hrows) upper + +theorem probability_split (rows : Nat → Nat) (hrows : ∀ k, 0 < rows (k + 1)) + (upper : Fin n) (event : CanonicalDirections.Tuple rows n → Bool) : + (CanonicalDirections.law rows n hrows).probability event = + ((CanonicalDirections.levelLaw rows hrows upper).product + (complementLaw rows hrows upper)).probability + (fun z => event (assemble rows upper z.1 z.2)) := by + rw [← assemble_law rows hrows upper, FiniteDistribution.probability_pushforward] + +theorem probability_complement_first (rows : Nat → Nat) + (hrows : ∀ k, 0 < rows (k + 1)) (upper : Fin n) + (event : CanonicalDirections.Tuple rows n → Bool) : + (CanonicalDirections.law rows n hrows).probability event = + (complementLaw rows hrows upper).expectation (fun rest => + (CanonicalDirections.levelLaw rows hrows upper).probability + (fun direction => event (assemble rows upper direction rest))) := by + rw [probability_split rows hrows upper] + exact UsefulAdvice.product_probability_advice_first _ _ _ + +theorem lower_choice_preserved {branch : Nat → Nat} (rows : Nat → Nat) + (leaf : RecursiveSpaces.Slots branch n) (upper lower : Fin n) (hne : lower ≠ upper) + (direction : PrefixTests.LevelDirection rows upper) + (directions : CanonicalDirections.Tuple rows n) : + PrefixTests.choiceAt rows leaf lower + (assemble rows upper direction (complement rows upper directions) lower) = + PrefixTests.choiceAt rows leaf lower (directions lower) := by + rw [lower_preserved rows upper lower hne direction directions] + +end +end PerfectCompleteness.CanonicalUpperDirectionSplit + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/ChildAssemblyProjection.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/ChildAssemblyProjection.lean new file mode 100644 index 0000000000000000000000000000000000000000..b8b4cf3381ab1db2e3d7d066f6dc4248d8a07d31 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/ChildAssemblyProjection.lean @@ -0,0 +1,171 @@ +import OAI.Computability.PerfectCompleteness.Construction.CutChildGrouping +import OAI.Computability.PerfectCompleteness.Decoding.ChildBlockProjection + +namespace OAI + +section + +namespace PerfectCompleteness.ChildAssemblyProjection + +open RecursiveSpaces TreeSourceSpaces HierarchicalArrays PointwiseSpaces +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +noncomputable section + +variable {branch : Nat → Nat} {n t : Nat} + {slots projected : Slots branch (n + 1) → Fin t → MixedSupport.Slot} + +def childProjection + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (i : Fin (branch n)) : + ∀ s k, MixedSupport.Projection (childSlots slots i s k) (childSlots projected i s k) := + fun s k => p (i, s) k + +theorem restrictChild_projection + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (i : Fin (branch n)) (x : Domain slots) : + sourceProjection (childProjection p i) (restrictChild slots i x) = + restrictChild projected i (sourceProjection p x) := rfl + +theorem recursiveSum_pullback + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (f : (i : Fin (branch n)) → squareSpace (H (childSlots projected i))) : + UniformChildSum.recursiveSum (LeafDomain slots) + (fun i => ChildBlockProjection.squarePullback (childProjection p i) (f i)) = + HPullback p (UniformChildSum.recursiveSum (LeafDomain projected) f) := by + apply Subtype.ext + change (∑ i, PointwiseSpaces.pullback F2 (childRestriction (LeafDomain slots) i) + (ChildBlockProjection.squarePullback (childProjection p i) (f i)).val) = + PointwiseSpaces.pullback F2 (sourceProjection p) + (∑ i, PointwiseSpaces.pullback F2 (childRestriction (LeafDomain projected) i) (f i).val) + rw [map_sum] + apply Finset.sum_congr rfl + intro i _ + rfl + +variable {C : Type*} [Fintype C] + +def childPullback (rows : Nat → Nat) + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (i : Fin (branch n)) : + CutChildGrouping.Child (C := C) projected rows i →ₗ[F2] + CutChildGrouping.Child (C := C) slots rows i where + toFun block := + (fun call => ChildBlockProjection.squarePullback (childProjection p i) (block.1 call), + ChildBlockProjection.arraysPullback rows (childProjection p i) block.2) + map_add' a b := by + apply Prod.ext + · funext call + exact map_add (ChildBlockProjection.squarePullback (childProjection p i)) + (a.1 call) (b.1 call) + · exact map_add (ChildBlockProjection.arraysPullback rows (childProjection p i)) a.2 b.2 + map_smul' c a := by + apply Prod.ext + · funext call + exact map_smul (ChildBlockProjection.squarePullback (childProjection p i)) c (a.1 call) + · exact map_smul (ChildBlockProjection.arraysPullback rows (childProjection p i)) c a.2 + +theorem childPullback_fin (calls : Nat) (rows : Nat → Nat) + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (i : Fin (branch n)) : + childPullback (C := Fin calls) rows p i = + ChildBlockProjection.rawPullback calls rows (childProjection p i) := rfl + +def rawPullback (rows : Nat → Nat) + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) : + CutChildGrouping.Raw (C := C) projected rows →ₗ[F2] + CutChildGrouping.Raw (C := C) slots rows where + toFun block i := childPullback rows p i (block i) + map_add' a b := by + funext i + exact map_add (childPullback rows p i) (a i) (b i) + map_smul' c a := by + funext i + exact map_smul (childPullback rows p i) c (a i) + +def assembledPullback (rows : Nat → Nat) + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) : + CutChildGrouping.Assembled (C := C) projected rows →ₗ[F2] + CutChildGrouping.Assembled (C := C) slots rows where + toFun z := (fun call => HPullback p (z.1 call), + fun i => ChildBlockProjection.arraysPullback rows (childProjection p i) (z.2 i)) + map_add' a b := by + apply Prod.ext + · funext call + exact map_add (HPullback p) (a.1 call) (b.1 call) + · funext i + exact map_add (ChildBlockProjection.arraysPullback rows (childProjection p i)) (a.2 i) (b.2 i) + map_smul' c a := by + apply Prod.ext + · funext call + exact map_smul (HPullback p) c (a.1 call) + · funext i + exact map_smul (ChildBlockProjection.arraysPullback rows (childProjection p i)) c (a.2 i) + +omit [Fintype C] in +theorem assemble_pullback (rows : Nat → Nat) + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (block : CutChildGrouping.Raw (C := C) projected rows) : + CutChildGrouping.assemble slots rows (rawPullback rows p block) = + assembledPullback rows p (CutChildGrouping.assemble projected rows block) := by + apply Prod.ext + · funext call + exact recursiveSum_pullback p (fun i => (block i).1 call) + · rfl + +omit [Fintype C] in +theorem assemble_comp_pullback (rows : Nat → Nat) + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) : + (CutChildGrouping.assemble (C := C) slots rows).comp (rawPullback rows p) = + (assembledPullback rows p).comp (CutChildGrouping.assemble projected rows) := by + apply LinearMap.ext + intro block + exact assemble_pullback rows p block + +def evaluate {rows : Nat → Nat} + (z : CutChildGrouping.Assembled (C := C) slots rows) (x : Domain slots) : + (C → F2) × (Fin (branch n) → Output branch n rows) := + (fun call => (z.1 call).val x, + fun i => fullJoint (z.2 i) (restrictChild slots i x)) + +omit [Fintype C] in +theorem evaluate_pullback (rows : Nat → Nat) + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (z : CutChildGrouping.Assembled (C := C) projected rows) (x : Domain slots) : + evaluate (assembledPullback rows p z) x = evaluate z (sourceProjection p x) := rfl + +omit [Fintype C] in +theorem evaluate_assemble_pullback (rows : Nat → Nat) + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (block : CutChildGrouping.Raw (C := C) projected rows) (x : Domain slots) : + evaluate (CutChildGrouping.assemble slots rows (rawPullback rows p block)) x = + evaluate (CutChildGrouping.assemble projected rows block) (sourceProjection p x) := by + rw [assemble_pullback] + exact evaluate_pullback rows p _ x + +theorem pushforward_assemble (rows : Nat → Nat) + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (μ : FiniteDistribution (CutChildGrouping.Raw (C := C) projected rows)) : + (μ.pushforward (rawPullback rows p)).pushforward (CutChildGrouping.assemble slots rows) = + (μ.pushforward (CutChildGrouping.assemble projected rows)).pushforward + (assembledPullback rows p) := by + rw [FiniteDistribution.pushforward_comp, FiniteDistribution.pushforward_comp] + congr 1 + funext block + exact assemble_pullback rows p block + +theorem uniform_projected_assembly (rows : Nat → Nat) + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) : + ((CutChildGrouping.rawLaw (C := C) projected rows).pushforward + (rawPullback rows p)).pushforward (CutChildGrouping.assemble slots rows) = + (FiniteDistribution.uniform (CutChildGrouping.Assembled (C := C) projected rows)).pushforward + (assembledPullback rows p) := by + rw [pushforward_assemble, CutChildGrouping.assemble_law] + +end +end PerfectCompleteness.ChildAssemblyProjection + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/ChildBlockProjection.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/ChildBlockProjection.lean new file mode 100644 index 0000000000000000000000000000000000000000..d8a028646988cb365c30e7f7370ccd147b6d50d2 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/ChildBlockProjection.lean @@ -0,0 +1,222 @@ +import OAI.Computability.PerfectCompleteness.Algebra.UniformLinearImage +import OAI.Computability.PerfectCompleteness.Construction.SourceQuestionOrderLemmas +import OAI.Computability.PerfectCompleteness.Foundations.MultiplicationFormInjectiveLemmas +import OAI.Computability.UniqueGames.Games.FinishBoundsLemmas + +namespace OAI + + +namespace PerfectCompleteness.ChildBlockProjection + +open RecursiveSpaces TreeSourceSpaces HierarchicalArrays PointwiseSpaces +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +noncomputable section + +variable {branch : Nat → Nat} {n t : Nat} + {slots projected : Slots branch n → Fin t → MixedSupport.Slot} + +def nodeProjection + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (node : Nodes branch n) : + ∀ s k, MixedSupport.Projection (nodeSlots slots node s k) (nodeSlots projected node s k) := + fun s k => p ((Nodes.path node).slotEmbedding s) k + +theorem restrictNode_projection + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (node : Nodes branch n) (x : Domain slots) : + sourceProjection (nodeProjection p node) (restrictNode slots node x) = + restrictNode projected node (sourceProjection p x) := rfl + +def squarePullback + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) : + squareSpace (H projected) →ₗ[F2] squareSpace (H slots) where + toFun f := ⟨PointwiseSpaces.pullback F2 (sourceProjection p) f.val, + TreeSourceSpaces.squareSpace_pullback_le p (Submodule.mem_map_of_mem f.property)⟩ + map_add' f g := by apply Subtype.ext; rfl + map_smul' c f := by apply Subtype.ext; rfl + +@[simp] theorem squarePullback_apply + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (f : squareSpace (H projected)) (x : Domain slots) : + (squarePullback p f).val x = f.val (sourceProjection p x) := rfl + +theorem squarePullback_injective + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) : + Function.Injective (squarePullback p) := by + intro f g h + apply Subtype.ext + exact PointwiseSpaces.pullback_injective (sourceProjection p) (sourceProjection_surjective p) + (congrArg (fun z : squareSpace (H slots) => z.val) h) + +def arraysPullback (rows : Nat → Nat) + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) : + Arrays projected rows →ₗ[F2] Arrays slots rows where + toFun arrays node row := HPullback (nodeProjection p node) (arrays node row) + map_add' a b := by + funext node row + exact map_add (HPullback (nodeProjection p node)) (a node row) (b node row) + map_smul' c a := by + funext node row + exact map_smul (HPullback (nodeProjection p node)) c (a node row) + +@[simp] theorem arraysPullback_apply (rows : Nat → Nat) + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (arrays : Arrays projected rows) (node : Nodes branch n) + (row : Fin (rows (Nodes.height node))) : + arraysPullback rows p arrays node row = + HPullback (nodeProjection p node) (arrays node row) := rfl + +theorem arraysPullback_injective (rows : Nat → Nat) + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) : + Function.Injective (arraysPullback rows p) := by + intro a b h + funext node row + exact HPullback_injective (nodeProjection p node) + (congrArg (fun z : Arrays slots rows => z node row) h) + +theorem fullJoint_pullback (rows : Nat → Nat) + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (arrays : Arrays projected rows) (x : Domain slots) : + fullJoint (arraysPullback rows p arrays) x = fullJoint arrays (sourceProjection p x) := rfl + +def rawPullback (calls : Nat) (rows : Nat → Nat) + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) : + ChildBlockCardinality.Raw calls rows projected →ₗ[F2] + ChildBlockCardinality.Raw calls rows slots where + toFun block := (fun call => squarePullback p (block.1 call), arraysPullback rows p block.2) + map_add' a b := by + apply Prod.ext + · funext call + exact map_add (squarePullback p) (a.1 call) (b.1 call) + · exact map_add (arraysPullback rows p) a.2 b.2 + map_smul' c a := by + apply Prod.ext + · funext call + exact map_smul (squarePullback p) c (a.1 call) + · exact map_smul (arraysPullback rows p) c a.2 + +theorem rawPullback_injective (calls : Nat) (rows : Nat → Nat) + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) : + Function.Injective (rawPullback calls rows p) := by + intro a b h + apply Prod.ext + · funext call + exact squarePullback_injective p + (congrArg (fun z : ChildBlockCardinality.Raw calls rows slots => z.1 call) h) + · exact arraysPullback_injective rows p + (congrArg (fun z : ChildBlockCardinality.Raw calls rows slots => z.2) h) + +def evaluate {calls : Nat} {rows : Nat → Nat} + (block : ChildBlockCardinality.Raw calls rows slots) (x : Domain slots) : + (Fin calls → F2) × Output branch n rows := + (fun call => (block.1 call).val x, fullJoint block.2 x) + +theorem evaluate_pullback (calls : Nat) (rows : Nat → Nat) + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (block : ChildBlockCardinality.Raw calls rows projected) (x : Domain slots) : + evaluate (rawPullback calls rows p block) x = evaluate block (sourceProjection p x) := rfl + +def liftedLaw (calls : Nat) (rows : Nat → Nat) + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) : + FiniteDistribution (ChildBlockCardinality.Raw calls rows slots) := + (FiniteDistribution.uniform (ChildBlockCardinality.Raw calls rows projected)).pushforward + (rawPullback calls rows p) + +instance liftedRangeFintype (calls : Nat) (rows : Nat → Nat) + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) : + Fintype (LinearMap.range (rawPullback calls rows p)) := Fintype.ofFinite _ + +theorem liftedLaw_eq_uniform_range (calls : Nat) (rows : Nat → Nat) + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) : + liftedLaw calls rows p = + (FiniteDistribution.uniform (LinearMap.range (rawPullback calls rows p))).pushforward + (LinearMap.range (rawPullback calls rows p)).subtype := by + rw [← UniformLinearImage.uniform_pushforward_linearMap + (rawPullback calls rows p).rangeRestrict + (rawPullback calls rows p).surjective_rangeRestrict] + rw [FiniteDistribution.pushforward_comp] + rfl + +theorem liftedLaw_evaluate (calls : Nat) (rows : Nat → Nat) + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (x : Domain slots) : + (liftedLaw calls rows p).pushforward (fun block => evaluate block x) = + (FiniteDistribution.uniform (ChildBlockCardinality.Raw calls rows projected)).pushforward + (fun block => evaluate block (sourceProjection p x)) := by + rw [liftedLaw, FiniteDistribution.pushforward_comp] + rfl + +def mixtureLaw {Z : Type*} [Fintype Z] (calls : Nat) (rows : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (projected : Z → Slots branch n → Fin t → MixedSupport.Slot) + (p : ∀ z s k, MixedSupport.Projection (slots s k) (projected z s k)) + (choiceLaw : FiniteDistribution Z) : + FiniteDistribution (ChildBlockCardinality.Raw calls rows slots) := + choiceLaw.mixture (fun z => liftedLaw calls rows (p z)) + +theorem mixtureLaw_weight {Z : Type*} [Fintype Z] (calls : Nat) (rows : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (projected : Z → Slots branch n → Fin t → MixedSupport.Slot) + (p : ∀ z s k, MixedSupport.Projection (slots s k) (projected z s k)) + (choiceLaw : FiniteDistribution Z) (block : ChildBlockCardinality.Raw calls rows slots) : + (mixtureLaw calls rows slots projected p choiceLaw).weight block = + ∑ z, choiceLaw.weight z * (liftedLaw calls rows (p z)).weight block := rfl + + +variable {I : Type*} [Fintype I] [DecidableEq I] [Nonempty I] + {Z : I → Type*} [∀ i, Fintype (Z i)] + +def replacementLaws (calls : Nat) (rows : Nat → Nat) + (slots : I → Slots branch n → Fin t → MixedSupport.Slot) + (projected : (i : I) → Z i → Slots branch n → Fin t → MixedSupport.Slot) + (p : ∀ i z s k, MixedSupport.Projection (slots i s k) (projected i z s k)) + (choiceLaw : (i : I) → FiniteDistribution (Z i)) : + (i : I) → FiniteDistribution (ChildBlockCardinality.Raw calls rows (slots i)) := + fun i => mixtureLaw calls rows (slots i) (projected i) (p i) (choiceLaw i) + +theorem observed_variation {Γ : Type*} [Fintype Γ] + (calls : Nat) (rows : Nat → Nat) + (slots : I → Slots branch n → Fin t → MixedSupport.Slot) + (projected : (i : I) → Z i → Slots branch n → Fin t → MixedSupport.Slot) + (p : ∀ i z s k, MixedSupport.Projection (slots i s k) (projected i z s k)) + (choiceLaw : (i : I) → FiniteDistribution (Z i)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) + (observe : ((i : I) → ChildBlockCardinality.Raw calls rows (slots i)) → Γ) : + ((SparseReplacement.law + (fun i => FiniteDistribution.uniform (ChildBlockCardinality.Raw calls rows (slots i))) + (replacementLaws calls rows slots projected p choiceLaw) β hβ hβ').pushforward + observe).totalVariation + ((FiniteProduct.law (fun i => + FiniteDistribution.uniform (ChildBlockCardinality.Raw calls rows (slots i)))).pushforward + observe) ≤ + Real.sqrt ((1 + β ^ 2 * ((ChildBlockCardinality.bound branch n t calls rows : ℝ) - 1)) ^ + Fintype.card I - 1) / 2 := by + apply SparseReplacement.observed_uniform_variation + intro i + exact_mod_cast ChildBlockCardinality.fintype_card_le calls rows (slots i) + +theorem adaptive_selection + (calls : Nat) (rows : Nat → Nat) + (slots : I → Slots branch n → Fin t → MixedSupport.Slot) + (projected : (i : I) → Z i → Slots branch n → Fin t → MixedSupport.Slot) + (p : ∀ i z s k, MixedSupport.Projection (slots i s k) (projected i z s k)) + (choiceLaw : (i : I) → FiniteDistribution (Z i)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β < 1) + (select : ((i : I) → ChildBlockCardinality.Raw calls rows (slots i)) → Finset I) + (budget : Nat) (size : ∀ x, (select x).card ≤ budget) : + (SparseReplacement.markedLaw + (fun i => FiniteDistribution.uniform (ChildBlockCardinality.Raw calls rows (slots i))) + (replacementLaws calls rows slots projected p choiceLaw) β hβ hβ'.le).probability + (fun z => decide (∃ i ∈ select z.2, z.1 i = true)) ≤ + budget * (β * (ChildBlockCardinality.bound branch n t calls rows : ℝ) / (1 - β)) := by + apply SparseReplacement.adaptive_uniform_selection _ β hβ hβ' + (ChildBlockCardinality.bound branch n t calls rows : ℝ) ?_ select budget size + intro i + exact_mod_cast ChildBlockCardinality.fintype_card_le calls rows (slots i) + +end +end PerfectCompleteness.ChildBlockProjection + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/ChildFiniteCallCollisionTransfer.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/ChildFiniteCallCollisionTransfer.lean new file mode 100644 index 0000000000000000000000000000000000000000..beb89d97a405941f331b0158b1077843b28caf1c --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/ChildFiniteCallCollisionTransfer.lean @@ -0,0 +1,59 @@ +import OAI.Computability.PerfectCompleteness.Algebra.ChildBilinearCollisionTransfer +import OAI.Computability.PerfectCompleteness.Sampling.ChildCallNumberingLaws + +namespace OAI + +section + +namespace PerfectCompleteness.ChildFiniteCallCollisionTransfer + +noncomputable section + +open scoped Classical +open RecursiveSpaces TreeSourceSpaces +open UniqueGamesTheorem.Foundations.Games + +variable {branch : Nat → Nat} {n t : Nat} {C : Type*} [Fintype C] + {Z : Fin (branch n) → Type*} [∀ i, Fintype (Z i)] + +theorem marked_restricted_le_uniform_full + (rows : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (projected : (i : Fin (branch n)) → Z i → Slots branch n → Fin t → MixedSupport.Slot) + (p : ∀ i z s k, MixedSupport.Projection + (childSlots slots i s k) (projected i z s k)) + (choiceLaw : (i : Fin (branch n)) → FiniteDistribution (Z i)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β < 1) + (F₀ F₁ : CutChildGrouping.Raw (C := C) slots rows → + Option (ChildBilinearCollisionTransfer.ParentForm slots)) : + (SparseReplacement.markedLaw + (fun i => FiniteDistribution.uniform + (ChildCallNumbering.Raw (C := C) rows (childSlots slots i))) + (ChildCallNumberingLaws.replacementLaws (C := C) rows (childSlots slots) + projected p choiceLaw) β hβ hβ'.le).probability + (fun z => BilinearCollisionTransfer.restrictedCollision + (F₀ z.2) (F₁ z.2) (ChildUnmarkedSpace.space slots z.1)) ≤ + (FiniteProduct.law (fun i => FiniteDistribution.uniform + (ChildCallNumbering.Raw (C := C) rows (childSlots slots i)))).probability + (fun x => BilinearCollisionTransfer.fullCollision (F₀ x) (F₁ x)) + + 2 * (β * (ChildBlockCardinality.bound branch n t (Fintype.card C) rows : ℝ) / + (1 - β)) + + Real.sqrt ((1 + β ^ 2 * + ((ChildBlockCardinality.bound branch n t (Fintype.card C) rows : ℝ) - 1)) ^ + branch n - 1) / 2 := by + have h := ChildBilinearCollisionTransfer.marked_restricted_le_uniform_full + (Fintype.card C) rows slots projected p choiceLaw β hβ hβ' + (fun x => F₀ (ChildCallNumberingLaws.unnumber (C := C) rows (childSlots slots) x)) + (fun x => F₁ (ChildCallNumberingLaws.unnumber (C := C) rows (childSlots slots) x)) + rw [← ChildCallNumberingLaws.markedLaw_numbered (C := C) rows (childSlots slots) + projected p choiceLaw β hβ hβ'.le, FiniteDistribution.probability_pushforward] at h + rw [← ChildCallNumberingLaws.uniform_product_numbered (C := C) rows (childSlots slots), + FiniteDistribution.probability_pushforward] at h + simpa only [ChildCallNumberingLaws.unnumber_number] using h + +end +end PerfectCompleteness.ChildFiniteCallCollisionTransfer + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/CleanDecoderOddLists.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/CleanDecoderOddLists.lean new file mode 100644 index 0000000000000000000000000000000000000000..3636fbe3178047143cab8a4ecbb3d345804f18c5 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/CleanDecoderOddLists.lean @@ -0,0 +1,216 @@ +import OAI.Computability.PerfectCompleteness.Construction.NativeLeafAlphabet +import OAI.Computability.PerfectCompleteness.Construction.SourceLocalOddLists +import OAI.Computability.PerfectCompleteness.Decoding.CleanEndpointProjection +import OAI.Computability.PerfectCompleteness.Decoding.CleanLeftDecoderLemmas +import OAI.Computability.PerfectCompleteness.Foundations.OddListAlphabetTransport + +namespace OAI + +section + +namespace PerfectCompleteness.CleanDecoderOddLists + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays PointwiseSpaces +open ChildBlockProjection CleanDecoderContext +open UniqueGamesTheorem.Foundations.Games + +abbrev F2 := ZMod 2 + +variable {branch rows repeats : Nat → Nat} {n h t v m s : Nat} [NeZero m] + {upper : Nodes branch n} {d : HierarchicalFrozenTables.LowerNodes upper (h + 1)} + (E : Exposed branch rows repeats n h t v m upper d) + +def nativeLeaf (_E : Exposed branch rows repeats n h t v m upper d) + (leaf : Slots branch (h + 1)) : Slots branch (Nodes.height (lower _E)) := + cast (congrArg (Slots branch) (lowerHeight upper d).symm) leaf + +private theorem slotEmbedding_cast_target {a b c : Nat} (hab : b = c) + (p : Path branch a b) (leaf : Slots branch c) : + (hab ▸ p).slotEmbedding leaf = + p.slotEmbedding (cast (congrArg (Slots branch) hab.symm) leaf) := by + cases hab + rfl + +theorem nativeLeaf_embedding (leaf : Slots branch (h + 1)) : + (Nodes.path (lower E)).slotEmbedding (nativeLeaf E leaf) = + (path E).slotEmbedding leaf := by + rw [← E.cut.slots_agree] + unfold path CleanRightDecoder.fullPath CleanRightDecoder.suffix + simp only [Path.slotEmbedding_append, slotEmbedding_cast_target, nativeLeaf] + +theorem nativeLeaf_slots (inside : Slots branch (h + 1) → Fin t → MixedSupport.Slot) + (leaf : Slots branch (h + 1)) : + nodeSlots (CutSlotAssembly.fill (path E) E.outside inside) (lower E) + (nativeLeaf E leaf) = inside leaf := by + change CutSlotAssembly.fill (path E) E.outside inside + ((Nodes.path (lower E)).slotEmbedding (nativeLeaf E leaf)) = inside leaf + rw [nativeLeaf_embedding] + exact CutSlotAssembly.fill_at_cut (path E) E.outside inside leaf + +abbrev leftNative (own : LeftOwn E) := nodeSlots (leftSlots E own) (lower E) +abbrev rightNative (own : RightOwn E) := nodeSlots (rightSlots E own) (lower E) + +def designatedLeaf (i : CleanChildren E) := nativeLeaf E (i.val, E.designated i.val) + +theorem leftNative_designated (own : LeftOwn E) (i : CleanChildren E) : + leftNative E own (designatedLeaf E i) = SourceAnswerEquiv.leftSlots E.clauses (own i) := by + exact (nativeLeaf_slots E + (CleanEndpointSlots.leftInside E.clauses E.designated E.clean E.visible own) + (i.val, E.designated i.val)).trans + (CleanEndpointProjection.leftInside_designated + E.clauses E.designated E.clean E.visible own i) + +theorem rightNative_designated (own : RightOwn E) (i : CleanChildren E) : + rightNative E own (designatedLeaf E i) = SourceAnswerEquiv.rightSlots E.clauses (own i) := by + exact (nativeLeaf_slots E + (CleanEndpointSlots.rightInside E.clauses E.designated E.clean E.visible E.projected own) + (i.val, E.designated i.val)).trans + (CleanEndpointProjection.rightInside_designated + E.clauses E.designated E.clean E.visible E.projected own i) + +def leftEncoding (own : LeftOwn E) (i : CleanChildren E) : + LeafDomain (leftNative E own) (designatedLeaf E i) ≃ SourceOddLists.LeftLabels t := + NativeLeafAlphabet.nativeLeftEquiv E.clauses (own i) (leftNative_designated E own i) + +def rightEncoding (own : RightOwn E) (i : CleanChildren E) : + LeafDomain (rightNative E own) (designatedLeaf E i) ≃ SourceOddLists.RightLabels t := + NativeLeafAlphabet.nativeRightEquiv E.clauses (own i) (rightNative_designated E own i) + +abbrev Occurrences := CleanChildren E → SourceOddLists.Occurrences m t + +def leftQuestions (e : Occurrences E) : LeftOwn E := fun i => SourceOddLists.left (e i) +def rightQuestions (e : Occurrences E) : RightOwn E := + fun i => SourceOddLists.right E.clauses (e i) + +def fullProjection (e : Occurrences E) : ∀ leaf k, + MixedSupport.Projection (leftSlots E (leftQuestions E e) leaf k) + (rightSlots E (rightQuestions E e) leaf k) := + CutProjectionAssembly.fillProjection (path E) E.outside + (CleanEndpointSlots.leftInside E.clauses E.designated E.clean E.visible (leftQuestions E e)) + (CleanEndpointSlots.rightInside E.clauses E.designated E.clean E.visible E.projected + (rightQuestions E e)) + (CleanEndpointProjection.insideProjection E.clauses E.designated E.clean E.visible + E.projected E.cleanProjected e) + +theorem nativeProjection_designated (e : Occurrences E) (i : CleanChildren E) (k : Fin t) : + HEq (nodeProjection (fullProjection E e) (lower E) (designatedLeaf E i) k) + (SourceAnswerEquiv.slotProjection E.clauses (e i) k) := by + have hcut := (CutProjectionAssembly.fillProjection_at_cut (path E) E.outside + (CleanEndpointSlots.leftInside E.clauses E.designated E.clean E.visible (leftQuestions E e)) + (CleanEndpointSlots.rightInside E.clauses E.designated E.clean E.visible E.projected + (rightQuestions E e)) + (CleanEndpointProjection.insideProjection E.clauses E.designated E.clean E.visible + E.projected E.cleanProjected e) + (i.val, E.designated i.val) k).trans + (CleanEndpointProjection.insideProjection_designated E.clauses E.designated E.clean + E.visible E.projected E.cleanProjected e i k) + exact Eq.mpr (congrArg (fun leaf : Slots branch n => + HEq (fullProjection E e leaf k) (SourceAnswerEquiv.slotProjection E.clauses (e i) k)) + (nativeLeaf_embedding E (i.val, E.designated i.val))) hcut + +theorem projection_encode (e : Occurrences E) (i : CleanChildren E) + (x : LeafDomain (leftNative E (leftQuestions E e)) (designatedLeaf E i)) : + rightEncoding E (rightQuestions E e) i + (MixedSupport.projectionMap + (nodeProjection (fullProjection E e) (lower E) (designatedLeaf E i)) x) = + SourceOddLists.projection E.clauses (e i) + (leftEncoding E (leftQuestions E e) i x) := + NativeLeafAlphabet.projection_encode E.clauses (e i) + (leftNative_designated E (leftQuestions E e) i) + (rightNative_designated E (rightQuestions E e) i) _ + (nativeProjection_designated E e i) x + +variable (hbranch : ∀ k < n, 0 < branch k) + +def target (seed : LeftSeed E) (e : Occurrences E) := + DecoderSourcePullback.upperTarget (fullProjection E e) upper (seed (leftQuestions E e)) + +def leftResponse (positive : 0 < s) (seed : LeftSeed E) (own : LeftOwn E) + (i : CleanChildren E) : OddLists.OddList s (SourceOddLists.LeftLabels t) := + OddLists.OddList.map (leftEncoding E own i) + (SourceLocalOddLists.extract positive (leftNative E own) (leftForm E hbranch seed own) + (designatedLeaf E i) ((leftEncoding E own i).symm (fun _ => 0))) + +def rightResponse (positive : 0 < s) (seed : RightSeed E) (own : RightOwn E) + (i : CleanChildren E) : OddLists.OddList s (SourceOddLists.RightLabels t) := + OddLists.OddList.map (rightEncoding E own i) + (SourceLocalOddLists.extract positive (rightNative E own) (rightForm E hbranch seed own) + (designatedLeaf E i) ((rightEncoding E own i).symm (fun _ => false))) + +def strategy (positive : 0 < s) (leftSeed : LeftSeed E) (rightSeed : RightSeed E) : + Strategy (LeftOwn E) (RightOwn E) + (CleanChildren E → OddLists.OddList s (SourceOddLists.LeftLabels t)) + (CleanChildren E → OddLists.OddList s (SourceOddLists.RightLabels t)) := + (leftResponse E hbranch positive leftSeed, rightResponse E hbranch positive rightSeed) + +theorem forms_agree (leftSeed : LeftSeed E) (rightSeed : RightSeed E) + (e : Occurrences E) (htarget : rightSeed (rightQuestions E e) = target E leftSeed e) + (f g : H (rightNative E (rightQuestions E e))) : + rightForm E hbranch rightSeed (rightQuestions E e) f g = + OddListExtraction.multiplicationForm (H (leftNative E (leftQuestions E e))) + (leftOutput E hbranch leftSeed (leftQuestions E e)) + (HPullback (nodeProjection (fullProjection E e) (lower E)) f) + (HPullback (nodeProjection (fullProjection E e) (lower E)) g) := by + change RightDecoderDescendant.form (rightSlots E (rightQuestions E e)) upper (lower E) + E.cut (DecoderSourcePullback.upperBranch upper hbranch) + (rightSeed (rightQuestions E e)) f g = _ + rw [htarget] + exact DecoderSourcePullback.form_upperTarget (fullProjection E e) upper (h + 1) + hbranch d E.cut (leftSeed (leftQuestions E e)) f g + +variable (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (useful : CleanLeftDecoder.Useful (leftExposed E) upper (h + 1)) + +theorem responses_accept (positive : 0 < s) (r : Nat) (ρ : ℝ) (hρ : 0 < ρ) + (A : ManyGoodRows.RowMap (Block rows upper) r) + (leftSeed : LeftSeed E) + (hsupport : (CleanLeftDecoder.seedLaw (leftExposed E) upper (h + 1) + σ useful r ρ A).weight leftSeed ≠ 0) + (rightSeed : RightSeed E) (e : Occurrences E) + (htarget : rightSeed (rightQuestions E e) = target E leftSeed e) + (hrank : OddListExtraction.formRank (H (leftNative E (leftQuestions E e))) + (leftForm E hbranch leftSeed (leftQuestions E e)) ≤ s) + (i : CleanChildren E) : + OddLists.OddList.map (SourceOddLists.projection E.clauses (e i)) + (leftResponse E hbranch positive leftSeed (leftQuestions E e) i) = + rightResponse E hbranch positive rightSeed (rightQuestions E e) i := by + have hnorm := CleanLeftDecoder.supported_output_normalized (leftExposed E) upper (h + 1) + σ useful hbranch r ρ hρ A leftSeed hsupport d (leftQuestions E e) + have hnative := SourceLocalOddLists.extract_accepts positive + (nodeProjection (fullProjection E e) (lower E)) (designatedLeaf E i) + (leftForm E hbranch leftSeed (leftQuestions E e)) + (rightForm E hbranch rightSeed (rightQuestions E e)) + (leftOutput E hbranch leftSeed (leftQuestions E e)) rfl + (HierarchicalLeftDecoder.lowerOne (leftSlots E (leftQuestions E e)) upper (h + 1) + hbranch d).property hnorm hrank (forms_agree E hbranch leftSeed rightSeed e htarget) + ((leftEncoding E (leftQuestions E e) i).symm (fun _ => 0)) + ((rightEncoding E (rightQuestions E e) i).symm (fun _ => false)) + exact OddLists.OddList.map_commutes _ (leftEncoding E (leftQuestions E e) i) + (rightEncoding E (rightQuestions E e) i) (SourceOddLists.projection E.clauses (e i)) + (fun x => (projection_encode E e i x).symm) _ _ hnative + +theorem strategy_wins (positive : 0 < s) (r : Nat) (ρ : ℝ) (hρ : 0 < ρ) + (A : ManyGoodRows.RowMap (Block rows upper) r) + (leftSeed : LeftSeed E) + (hsupport : (CleanLeftDecoder.seedLaw (leftExposed E) upper (h + 1) + σ useful r ρ A).weight leftSeed ≠ 0) + (rightSeed : RightSeed E) (e : Occurrences E) + (htarget : rightSeed (rightQuestions E e) = target E leftSeed e) + (hrank : OddListExtraction.formRank (H (leftNative E (leftQuestions E e))) + (leftForm E hbranch leftSeed (leftQuestions E e)) ≤ s) : + (IndexedRepetition.game (SourceOddLists.game s E.clauses t) (CleanChildren E)).wins + (strategy E hbranch positive leftSeed rightSeed) e = true := by + simp only [OccurrenceGame.wins, IndexedRepetition.game, SourceOddLists.game, + OddListGame.game, OccurrenceGame.ofProjection, strategy, decide_eq_true_eq] + exact responses_accept E hbranch σ useful positive r ρ hρ A + leftSeed hsupport rightSeed e htarget hrank + +end +end PerfectCompleteness.CleanDecoderOddLists + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/CleanDecoderRateLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/CleanDecoderRateLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..2846c45266fb392129022ece357b67232705542b --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/CleanDecoderRateLemmas.lean @@ -0,0 +1,309 @@ +import OAI.Computability.PerfectCompleteness.Construction.SourceChildKernelLemmas +import OAI.Computability.PerfectCompleteness.Decoding.CleanDecoderOddLists +import OAI.Computability.PerfectCompleteness.Decoding.CleanDecoderSeedLawLemmas +import OAI.Computability.PerfectCompleteness.Machines.CleanRecordDecoderInput +import OAI.Computability.PerfectCompleteness.Sampling.RecordSeedSamplingLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.CleanDecoderRate + +noncomputable section + +open scoped BigOperators Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +abbrev F2 := ZMod 2 + +structure Setup (branch rows repeats : Nat → Nat) (n h t v m : Nat) [NeZero m] + (upper : Nodes branch n) (d : HierarchicalFrozenTables.LowerNodes upper (h + 1)) where + clauses : Fin m → SourceClause.NormalizedClause v + designated : Fin (branch h) → Slots branch h + cut : OwnInputReference.Cut upper (HierarchicalLeftDecoder.LowerNode upper (h + 1) d) + outside : Slots branch n → Fin t → MixedSupport.Slot + placeholder : Slots branch (h + 1) → Fin t → MixedSupport.Slot + exterior : CleanPhysicalReplay.Exterior rows repeats + (CleanRecordDecoderInput.path upper d cut) outside placeholder + +variable {branch rows repeats : Nat → Nat} {n h t v m : Nat} [NeZero m] + {upper : Nodes branch n} {d : HierarchicalFrozenTables.LowerNodes upper (h + 1)} + (S : Setup branch rows repeats n h t v m upper d) + +abbrev path := CleanRecordDecoderInput.path upper d S.cut +abbrev Calls := WholeCutCalls.Index rows repeats (path S) +abbrev Record := CleanRecordDecoderInput.Record (t := t) rows repeats upper d S.cut + S.clauses S.designated +abbrev Sample := CleanRecordDecoderInput.Sample (t := t) rows repeats upper d S.cut + S.clauses S.designated + +def context (record : Record S) := + CleanRecordDecoderInput.exposed rows repeats upper d S.cut S.outside S.placeholder + S.clauses S.designated record S.exterior + +abbrev Seed (record : Record S) := CleanDecoderSeedLaw.Seed (context S record) + +instance seedFintype (record : Record S) : Fintype (Seed S record) := + CleanDecoderSeedLaw.seedFintype (context S record) + +abbrev observations (x : Sample S) : Record S := + CleanRecordDecoderInput.observe rows repeats upper d S.cut S.clauses S.designated x + +abbrev sources (record : Record S) (x : Sample S) := + CleanRecordDecoderInput.sources rows repeats upper d S.cut S.clauses S.designated record x + +def rawLaw (cube : Nat) (hcube : 0 < cube) : FiniteDistribution (Sample S) := + SourceChildKernel.originalLaw (C := Calls S) (t := t) rows S.clauses S.designated + (fun _ => ProjectedCleanRate.projectionFlag cube hcube) + +variable (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (useful : (record : Record S) → + CleanLeftDecoder.Useful (CleanDecoderContext.leftExposed (context S record)) upper (h + 1)) + (r : Nat) (ρ : ℝ) (A : ManyGoodRows.RowMap (Block rows upper) r) + (W : Submodule F2 (OwnInputReference.UpperVector rows upper)) + (a : OwnInputReference.LowerVector rows (HierarchicalLeftDecoder.LowerNode upper (h + 1) d)) + (threshold : ℝ) + +def kernel (record : Record S) : FiniteDistribution (Seed S record) := + CleanDecoderSeedLaw.seedLaw (context S record) σ (useful record) r ρ A W a threshold + +def law (cube : Nat) (hcube : 0 < cube) : + FiniteDistribution (Σ x : Sample S, Seed S (observations S x)) := + RecordSeedSampling.freshLaw (rawLaw S cube hcube) (observations S) + (kernel S σ useful r ρ A W a threshold) + +variable (hbranch : ∀ k < n, 0 < branch k) + +def agrees (s : Nat) (x : Sample S) (seed : Seed S (observations S x)) : Bool := + decide + (OddListExtraction.formRank + (H (CleanDecoderOddLists.leftNative (context S (observations S x)) + (CleanDecoderOddLists.leftQuestions (context S (observations S x)) + (sources S (observations S x) x)))) + (CleanDecoderContext.leftForm (context S (observations S x)) hbranch seed.1 + (CleanDecoderOddLists.leftQuestions (context S (observations S x)) + (sources S (observations S x) x))) ≤ s ∧ + seed.2 (CleanDecoderOddLists.rightQuestions (context S (observations S x)) + (sources S (observations S x) x)) = + CleanDecoderOddLists.target (context S (observations S x)) seed.1 + (sources S (observations S x) x)) + +theorem bound {s L cube : Nat} [NeZero s] (hcube : 0 < cube) (hρ : 0 < ρ) + (repetition : ∀ k, ((SourceOddLists.game s S.clauses t).repetition k).value ≤ + (RepetitionRate.halfRate L : ℝ) ^ k) : + (law S σ useful r ρ A W a threshold cube hcube).probability + (fun z => agrees S hbranch s z.1 z.2) ≤ + (1 - ProjectedCleanRate.coefficient L branch h t (Fintype.card (Calls S)) rows / + (cube : ℝ) ^ 2) ^ (branch h) := by + unfold law + apply RecordSeedSampling.probability_le_of_supported_tables + intro table htable + let strategies := fun record : Record S => + CleanDecoderOddLists.strategy (context S record) hbranch (Nat.pos_of_neZero s) + (table record).1 (table record).2 + apply SourceChildKernelRate.bound_from_repetition rows S.clauses S.designated + hcube repetition _ strategies + intro record x hevent heventSeed + have hrecord : observations S x = record := by + apply of_decide_eq_true + exact (CleanRecordObservation.event_eq rows S.clauses S.designated record x).symm.trans hevent + subst record + have hseed := RecordSeedSampling.supported_row + (kernel S σ useful r ρ A W a threshold) table htable (observations S x) + have hleft := CleanDecoderSeedLaw.supported_left (context S (observations S x)) + σ (useful (observations S x)) r ρ A W a threshold + (table (observations S x)) hseed + have hagrees : agrees S hbranch s x (table (observations S x)) = true := + (Bool.and_eq_true_iff.mp heventSeed).2 + have hactual := of_decide_eq_true hagrees + simp only [OccurrenceGame.wins, IndexedRepetition.game, SourceOddLists.game, + OddListGame.game, OccurrenceGame.ofProjection, strategies, + CleanDecoderOddLists.strategy, decide_eq_true_eq] + intro i + exact CleanDecoderOddLists.responses_accept (context S (observations S x)) hbranch + σ (useful (observations S x)) (Nat.pos_of_neZero s) r ρ hρ A + (table (observations S x)).1 hleft (table (observations S x)).2 + (sources S (observations S x) x) hactual.2 hactual.1 i + +theorem amplified_bound {s L cube : Nat} [NeZero s] + (γ : ℚ) (hγ : 0 < γ) (hγ1 : γ ≤ 1) + (ht : t = SourceOddLists.repetitionLength γ s hγ hγ1) + (hcube : 0 < cube) (hρ : 0 < ρ) + (gap : SourceAmplification.ClauseGap S.clauses γ) + (hL : 0 < L) (alphabet : SourceOddLists.alphabetLog s t ≤ L) : + (law S σ useful r ρ A W a threshold cube hcube).probability + (fun z => agrees S hbranch s z.1 z.2) ≤ + (1 - ProjectedCleanRate.coefficient L branch h t (Fintype.card (Calls S)) rows / + (cube : ℝ) ^ 2) ^ (branch h) := by + apply bound S σ useful r ρ A W a threshold hbranch hcube hρ + subst t + exact SourceOddLists.repetition_halfRate S.clauses γ hγ hγ1 gap hL alphabet + +end +end PerfectCompleteness.CleanDecoderRate + +end + +section + +namespace PerfectCompleteness.CleanDecoderPairLaw + +noncomputable section + +open scoped Classical +open TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +abbrev F2 := ZMod 2 + +variable {branch rows repeats : Nat → Nat} {n h t v m : Nat} [NeZero m] + {upper : Nodes branch n} {d : HierarchicalFrozenTables.LowerNodes upper (h + 1)} + (S : CleanDecoderRate.Setup branch rows repeats n h t v m upper d) + +abbrev context (x : CleanDecoderRate.Sample S) := + CleanDecoderRate.context S (CleanDecoderRate.observations S x) + +abbrev occurrences (x : CleanDecoderRate.Sample S) := + CleanDecoderRate.sources S (CleanDecoderRate.observations S x) x + +abbrev leftOwn (x : CleanDecoderRate.Sample S) := + CleanDecoderOddLists.leftQuestions (context S x) (occurrences S x) + +abbrev rightOwn (x : CleanDecoderRate.Sample S) := + CleanDecoderOddLists.rightQuestions (context S x) (occurrences S x) + +abbrev LeftAnswer (x : CleanDecoderRate.Sample S) := + CleanDecoderSeedLaw.LeftAnswer (context S x) (leftOwn S x) + +abbrev RightAnswer (x : CleanDecoderRate.Sample S) := + CleanDecoderSeedLaw.RightAnswer (context S x) (rightOwn S x) + +instance leftAnswerFintype (x : CleanDecoderRate.Sample S) : Fintype (LeftAnswer S x) := + CleanLeftDecoder.upperAnswerFintype + (CleanDecoderContext.leftExposed (context S x)) upper (leftOwn S x) + +instance rightAnswerFintype (x : CleanDecoderRate.Sample S) : Fintype (RightAnswer S x) := + RightDecoder.scalarFintype (CleanDecoderContext.rightSlots (context S x) (rightOwn S x)) upper + +abbrev Pair (x : CleanDecoderRate.Sample S) := LeftAnswer S x × RightAnswer S x + +instance pairFintype (x : CleanDecoderRate.Sample S) : Fintype (Pair S x) := + inferInstanceAs (Fintype (LeftAnswer S x × RightAnswer S x)) + +def read (x : CleanDecoderRate.Sample S) + (seed : CleanDecoderRate.Seed S (CleanDecoderRate.observations S x)) : Pair S x := + (seed.1 (leftOwn S x), seed.2 (rightOwn S x)) + +def readSample + (z : Σ x : CleanDecoderRate.Sample S, CleanDecoderRate.Seed S (CleanDecoderRate.observations S x)) : + Σ x : CleanDecoderRate.Sample S, Pair S x := + ⟨z.1, read S z.1 z.2⟩ + +variable (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (useful : (record : CleanDecoderRate.Record S) → + CleanLeftDecoder.Useful (CleanDecoderContext.leftExposed (CleanDecoderRate.context S record)) + upper (h + 1)) + (r : Nat) (ρ : ℝ) (A : ManyGoodRows.RowMap (Block rows upper) r) + (W : Submodule F2 (OwnInputReference.UpperVector rows upper)) + (a : OwnInputReference.LowerVector rows (HierarchicalLeftDecoder.LowerNode upper (h + 1) d)) + (threshold : ℝ) + +def pairKernel (x : CleanDecoderRate.Sample S) : FiniteDistribution (Pair S x) := + (CleanDecoderSeedLaw.leftKernel (context S x) σ (useful (CleanDecoderRate.observations S x)) + r ρ A (leftOwn S x)).product + (CleanDecoderSeedLaw.rightKernel (context S x) σ W a threshold (rightOwn S x)) + +def pairLaw (cube : Nat) (hcube : 0 < cube) : + FiniteDistribution (Σ x : CleanDecoderRate.Sample S, Pair S x) := + CompletionSoundness.sigmaLaw (CleanDecoderRate.rawLaw S cube hcube) + (pairKernel S σ useful r ρ A W a threshold) + +theorem read_law (x : CleanDecoderRate.Sample S) : + (CleanDecoderRate.kernel S σ useful r ρ A W a threshold + (CleanDecoderRate.observations S x)).pushforward (read S x) = + pairKernel S σ useful r ρ A W a threshold x := + CleanDecoderSeedLaw.read_law (context S x) σ (useful (CleanDecoderRate.observations S x)) + r ρ A W a threshold (leftOwn S x) (rightOwn S x) + +theorem probability_read (cube : Nat) (hcube : 0 < cube) + (event : (x : CleanDecoderRate.Sample S) → Pair S x → Bool) : + (pairLaw S σ useful r ρ A W a threshold cube hcube).probability + (fun z => event z.1 z.2) = + (CleanDecoderRate.law S σ useful r ρ A W a threshold cube hcube).probability + (fun z => event z.1 (read S z.1 z.2)) := by + rw [pairLaw, CleanDecoderRate.law, RecordSeedSampling.freshLaw, + CompletionSoundness.sigmaLaw_probability, CompletionSoundness.sigmaLaw_probability] + apply FiniteDistribution.expectation_congr + intro x + exact (CleanDecoderSeedLaw.probability_read (context S x) σ + (useful (CleanDecoderRate.observations S x)) r ρ A W a threshold + (leftOwn S x) (rightOwn S x) (fun left right => event x (left, right))).symm + +theorem law_pushforward (cube : Nat) (hcube : 0 < cube) : + (CleanDecoderRate.law S σ useful r ρ A W a threshold cube hcube).pushforward (readSample S) = + pairLaw S σ useful r ρ A W a threshold cube hcube := by + apply FiniteDistribution.eq_of_weight_eq + intro answer + rw [FiniteDistribution.weight_eq_probability_singleton, + FiniteDistribution.weight_eq_probability_singleton, FiniteDistribution.probability_pushforward] + have readProbability := probability_read S σ useful r ρ A W a threshold cube hcube + (fun sample pair => + decide ((⟨sample, pair⟩ : Σ x : CleanDecoderRate.Sample S, Pair S x) = answer)) + simp only [Sigma.eta] at readProbability + convert readProbability.symm using 1 + congr 1 + +variable (hbranch : ∀ k < n, 0 < branch k) + +def pairAgrees (s : Nat) (x : CleanDecoderRate.Sample S) (answer : Pair S x) : Bool := + decide + (OddListExtraction.formRank + (H (CleanDecoderOddLists.leftNative (context S x) (leftOwn S x))) + (CleanLeftDecoder.form (CleanDecoderContext.leftExposed (context S x)) upper (h + 1) + hbranch d (leftOwn S x) answer.1) ≤ s ∧ + answer.2 = DecoderSourcePullback.upperTarget + (CleanDecoderOddLists.fullProjection (context S x) (occurrences S x)) upper answer.1) + +@[simp] theorem pairAgrees_read (s : Nat) (x : CleanDecoderRate.Sample S) + (seed : CleanDecoderRate.Seed S (CleanDecoderRate.observations S x)) : + pairAgrees S hbranch s x (read S x seed) = CleanDecoderRate.agrees S hbranch s x seed := rfl + +theorem pair_probability_eq (s cube : Nat) (hcube : 0 < cube) : + (pairLaw S σ useful r ρ A W a threshold cube hcube).probability + (fun z => pairAgrees S hbranch s z.1 z.2) = + (CleanDecoderRate.law S σ useful r ρ A W a threshold cube hcube).probability + (fun z => CleanDecoderRate.agrees S hbranch s z.1 z.2) := by + exact probability_read S σ useful r ρ A W a threshold cube hcube (pairAgrees S hbranch s) + +theorem bound {s L cube : Nat} [NeZero s] (hcube : 0 < cube) (hρ : 0 < ρ) + (repetition : ∀ k, ((SourceOddLists.game s S.clauses t).repetition k).value ≤ + (RepetitionRate.halfRate L : ℝ) ^ k) : + (pairLaw S σ useful r ρ A W a threshold cube hcube).probability + (fun z => pairAgrees S hbranch s z.1 z.2) ≤ + (1 - ProjectedCleanRate.coefficient L branch h t + (Fintype.card (CleanDecoderRate.Calls S)) rows / (cube : ℝ) ^ 2) ^ (branch h) := by + rw [pair_probability_eq] + exact CleanDecoderRate.bound S σ useful r ρ A W a threshold hbranch hcube hρ repetition + +theorem amplified_bound {s L cube : Nat} [NeZero s] + (γ : ℚ) (hγ : 0 < γ) (hγ1 : γ ≤ 1) + (ht : t = SourceOddLists.repetitionLength γ s hγ hγ1) + (hcube : 0 < cube) (hρ : 0 < ρ) + (gap : SourceAmplification.ClauseGap S.clauses γ) + (hL : 0 < L) (alphabet : SourceOddLists.alphabetLog s t ≤ L) : + (pairLaw S σ useful r ρ A W a threshold cube hcube).probability + (fun z => pairAgrees S hbranch s z.1 z.2) ≤ + (1 - ProjectedCleanRate.coefficient L branch h t + (Fintype.card (CleanDecoderRate.Calls S)) rows / (cube : ℝ) ^ 2) ^ (branch h) := by + rw [pair_probability_eq] + exact CleanDecoderRate.amplified_bound S σ useful r ρ A W a threshold hbranch + γ hγ hγ1 ht hcube hρ gap hL alphabet + +end +end PerfectCompleteness.CleanDecoderPairLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/CleanDecoderSeedLawLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/CleanDecoderSeedLawLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..dfec03181f6d22fc9b2491bc3b0a4ff723416475 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/CleanDecoderSeedLawLemmas.lean @@ -0,0 +1,269 @@ +import OAI.Computability.PerfectCompleteness.Decoding.CleanLeftDecoderLemmas +import OAI.Computability.PerfectCompleteness.Decoding.DependentDecoderSampling +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalFrozenTablesLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.CleanDecoderSeedLaw + +noncomputable section + +open scoped Classical +open TreeSourceSpaces HierarchicalArrays CleanDecoderContext +open UniqueGamesTheorem.Foundations.Games + +abbrev F2 := ZMod 2 + +variable {branch rows repeats : Nat → Nat} {n h t v m : Nat} [NeZero m] + {upper : Nodes branch n} {d : HierarchicalFrozenTables.LowerNodes upper (h + 1)} + (E : Exposed branch rows repeats n h t v m upper d) + +abbrev LeftAnswer (own : LeftOwn E) := + CleanLeftDecoder.UpperAnswer (leftExposed E) upper own + +abbrev RightAnswer (own : RightOwn E) := + CleanRightDecoder.Answer E.clauses E.designated E.clean E.visible E.projected + upper (lower E) E.cut (lowerHeight upper d) E.outside own + +local instance leftOwnFintype : Fintype (LeftOwn E) := + CleanLeftDecoder.ownFintype (leftExposed E) + +local instance rightOwnFintype : Fintype (RightOwn E) := + inferInstanceAs (Fintype ({i : Fin (branch h) // E.clean i} → Fin t → Fin v)) + +local instance leftAnswerFintype (own : LeftOwn E) : Fintype (LeftAnswer E own) := + CleanLeftDecoder.upperAnswerFintype (leftExposed E) upper own + +local instance rightAnswerFintype (own : RightOwn E) : Fintype (RightAnswer E own) := + RightDecoder.scalarFintype (rightSlots E own) upper + +abbrev Seed := LeftSeed E × RightSeed E + +instance seedFintype : Fintype (Seed E) := + inferInstanceAs (Fintype + (((own : LeftOwn E) → LeftAnswer E own) × + ((own : RightOwn E) → RightAnswer E own))) + +variable (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (useful : CleanLeftDecoder.Useful (leftExposed E) upper (h + 1)) + (r : Nat) (ρ : ℝ) (A : ManyGoodRows.RowMap (Block rows upper) r) + (W : Submodule F2 (OwnInputReference.UpperVector rows upper)) + (a : OwnInputReference.LowerVector rows (lower E)) (threshold : ℝ) + +def leftKernel (own : LeftOwn E) : FiniteDistribution (LeftAnswer E own) := + CleanLeftDecoder.law (leftExposed E) upper (h + 1) σ useful r ρ A own + +def rightKernel (own : RightOwn E) : FiniteDistribution (RightAnswer E own) := + CleanRightDecoder.kernel E.clauses E.designated E.clean E.visible E.projected + upper (lower E) E.cut (lowerHeight upper d) E.outside + rows repeats E.rightTape W a σ threshold own + +def leftSeedLaw : FiniteDistribution (LeftSeed E) := + CleanLeftDecoder.seedLaw (leftExposed E) upper (h + 1) σ useful r ρ A + +def rightSeedLaw : FiniteDistribution (RightSeed E) := + CleanRightDecoder.seedLaw E.clauses E.designated E.clean E.visible E.projected + upper (lower E) E.cut (lowerHeight upper d) E.outside + rows repeats E.rightTape W a σ threshold + +def seedLaw : FiniteDistribution (Seed E) := + (leftSeedLaw E σ useful r ρ A).product (rightSeedLaw E σ W a threshold) + +theorem seedLaw_eq_dependent : + seedLaw E σ useful r ρ A W a threshold = + DependentDecoderSampling.seedLaw + (leftKernel E σ useful r ρ A) (rightKernel E σ W a threshold) := rfl + +theorem read_law (left : LeftOwn E) (right : RightOwn E) : + (seedLaw E σ useful r ρ A W a threshold).pushforward + (fun seed => (seed.1 left, seed.2 right)) = + (leftKernel E σ useful r ρ A left).product + (rightKernel E σ W a threshold right) := + DependentDecoderSampling.read_law + (leftKernel E σ useful r ρ A) (rightKernel E σ W a threshold) left right + +theorem probability_read (left : LeftOwn E) (right : RightOwn E) + (event : LeftAnswer E left → RightAnswer E right → Bool) : + (seedLaw E σ useful r ρ A W a threshold).probability + (fun seed => event (seed.1 left) (seed.2 right)) = + ((leftKernel E σ useful r ρ A left).product + (rightKernel E σ W a threshold right)).probability + (fun answer => event answer.1 answer.2) := by + have hread := FiniteDistribution.probability_pushforward + (seedLaw E σ useful r ρ A W a threshold) + (fun seed : Seed E => (seed.1 left, seed.2 right)) + (fun answer => event answer.1 answer.2) + rw [read_law] at hread + exact hread.symm + +theorem supported_left (seed : Seed E) + (hs : (seedLaw E σ useful r ρ A W a threshold).weight seed ≠ 0) : + (leftSeedLaw E σ useful r ρ A).weight seed.1 ≠ 0 := by + intro hz + apply hs + change (leftSeedLaw E σ useful r ρ A).weight seed.1 * + (rightSeedLaw E σ W a threshold).weight seed.2 = 0 + rw [hz, zero_mul] + +theorem supported_right (seed : Seed E) + (hs : (seedLaw E σ useful r ρ A W a threshold).weight seed ≠ 0) : + (rightSeedLaw E σ W a threshold).weight seed.2 ≠ 0 := by + intro hz + apply hs + change (leftSeedLaw E σ useful r ρ A).weight seed.1 * + (rightSeedLaw E σ W a threshold).weight seed.2 = 0 + rw [hz, mul_zero] + +theorem supported_left_row (seed : Seed E) + (hs : (seedLaw E σ useful r ρ A W a threshold).weight seed ≠ 0) + (own : LeftOwn E) : + (leftKernel E σ useful r ρ A own).weight (seed.1 own) ≠ 0 := + CleanLeftDecoder.supported_row (leftExposed E) upper (h + 1) σ useful r ρ A + seed.1 (supported_left E σ useful r ρ A W a threshold seed hs) own + +theorem supported_right_row (seed : Seed E) + (hs : (seedLaw E σ useful r ρ A W a threshold).weight seed ≠ 0) + (own : RightOwn E) : + (rightKernel E σ W a threshold own).weight (seed.2 own) ≠ 0 := + DependentDecoderSampling.supported_right + (leftKernel E σ useful r ρ A) (rightKernel E σ W a threshold) seed hs own + +variable (hbranch : ∀ k < n, 0 < branch k) + +theorem supported_output_normalized (hρ : 0 < ρ) (seed : Seed E) + (hs : (seedLaw E σ useful r ρ A W a threshold).weight seed ≠ 0) + (own : LeftOwn E) : + leftOutput E hbranch seed.1 own + (HierarchicalLeftDecoder.lowerOne (leftSlots E own) upper (h + 1) hbranch d) = 1 := + CleanLeftDecoder.supported_output_normalized (leftExposed E) upper (h + 1) σ useful + hbranch r ρ hρ A seed.1 + (supported_left E σ useful r ρ A W a threshold seed hs) d own + +theorem supported_form_tested_rank (hρ : 0 < ρ) (seed : Seed E) + (hs : (seedLaw E σ useful r ρ A W a threshold).weight seed ≠ 0) + (own : LeftOwn E) : + (LowerAffineSliceRank.testedGram + (FunctionSpaceLowerRank.matrixForm + (CleanLeftDecoder.LowerH (leftExposed E) upper (h + 1) d own) + (leftForm E hbranch seed.1 own)) + (HierarchicalLeftDecoder.testedMatrix (leftSlots E own) upper (h + 1) + (CleanLeftDecoder.background (leftExposed E) upper own) d)).rank ≤ 1 := + CleanLeftDecoder.supported_form_tested_rank (leftExposed E) upper (h + 1) σ useful + hbranch r ρ hρ A seed.1 + (supported_left E σ useful r ρ A W a threshold seed hs) d own + +end +end PerfectCompleteness.CleanDecoderSeedLaw + +end + +section + +namespace PerfectCompleteness.OriginalDecoderMark + +noncomputable section + +open scoped Classical +open TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +abbrev SlotFamily (branch : Nat → Nat) (n t : Nat) := + RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot + +structure Family (branch rows : Nat → Nat) (n t : Nat) + (Sample : SlotFamily branch n t → Type*) [∀ slots, Fintype (Sample slots)] where + original : (slots : SlotFamily branch n t) → FiniteDistribution (Sample slots) + arrays : (slots : SlotFamily branch n t) → Sample slots → Arrays slots rows + lowerEvent : (slots : SlotFamily branch n t) → Sample slots → Bool + +variable {branch rows : Nat → Nat} {n t : Nat} + {Sample : SlotFamily branch n t → Type*} [∀ slots, Fintype (Sample slots)] + (F : Family branch rows n t Sample) (upper : Nodes branch n) (lowerLevel : Nat) (κ : ℝ) + +def mark (slots : SlotFamily branch n t) + (background : HierarchicalMatrixTable.Background (rows := rows) slots upper) + (X : HierarchicalFrozenTables.QuotientMatrix slots upper lowerLevel background) : Prop := + HierarchicalUsefulness.mark slots upper lowerLevel + (F.original slots) (F.arrays slots) (F.lowerEvent slots) κ ⟨background, X⟩ = true + +theorem mark_heq {slots₁ slots₂ : SlotFamily branch n t} (hs : slots₁ = slots₂) + {background₁ : HierarchicalMatrixTable.Background (rows := rows) slots₁ upper} + {background₂ : HierarchicalMatrixTable.Background (rows := rows) slots₂ upper} + (hb : HEq background₁ background₂) : + HEq (mark F upper lowerLevel κ slots₁ background₁) + (mark F upper lowerLevel κ slots₂ background₂) := by + cases hs + have hb' : background₁ = background₂ := eq_of_heq hb + cases hb' + rfl + +theorem mark_congr {slots₁ slots₂ : SlotFamily branch n t} (hs : slots₁ = slots₂) + {background₁ : HierarchicalMatrixTable.Background (rows := rows) slots₁ upper} + {background₂ : HierarchicalMatrixTable.Background (rows := rows) slots₂ upper} + (hb : HEq background₁ background₂) + {X₁ : HierarchicalFrozenTables.QuotientMatrix slots₁ upper lowerLevel background₁} + {X₂ : HierarchicalFrozenTables.QuotientMatrix slots₂ upper lowerLevel background₂} + (hX : HEq X₁ X₂) : + mark F upper lowerLevel κ slots₁ background₁ X₁ ↔ + mark F upper lowerLevel κ slots₂ background₂ X₂ := by + cases hs + have hb' : background₁ = background₂ := eq_of_heq hb + cases hb' + have hX' : X₁ = X₂ := eq_of_heq hX + cases hX' + rfl + +theorem table_eq_original (slots : SlotFamily branch n t) + (background : HierarchicalMatrixTable.Background (rows := rows) slots upper) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) : + HierarchicalFrozenTables.table slots upper lowerLevel background σ + (mark F upper lowerLevel κ slots background) = + HierarchicalUsefulness.table slots upper lowerLevel (F.original slots) + (F.arrays slots) (F.lowerEvent slots) κ σ background := rfl + +variable {repeats : Nat → Nat} {h v m : Nat} [NeZero m] + +def useful (E : CleanLeftDecoder.Exposed branch rows repeats n h t v m) : + CleanLeftDecoder.Useful E upper lowerLevel := + fun own X => mark F upper lowerLevel κ + (CleanLeftDecoder.slots E own) (CleanLeftDecoder.background E upper own) X + +theorem useful_heq + (E₁ E₂ : CleanLeftDecoder.Exposed branch rows repeats n h t v m) + (own₁ : CleanLeftDecoder.Own E₁) (own₂ : CleanLeftDecoder.Own E₂) + (hs : CleanLeftDecoder.slots E₁ own₁ = CleanLeftDecoder.slots E₂ own₂) + (hb : HEq (CleanLeftDecoder.background E₁ upper own₁) + (CleanLeftDecoder.background E₂ upper own₂)) : + HEq (useful F upper lowerLevel κ E₁ own₁) (useful F upper lowerLevel κ E₂ own₂) := + mark_heq F upper lowerLevel κ hs hb + +theorem useful_at_quotientMatrix + (E : CleanLeftDecoder.Exposed branch rows repeats n h t v m) + (own : CleanLeftDecoder.Own E) : + useful F upper lowerLevel κ E own (CleanLeftDecoder.quotientMatrix E upper lowerLevel own) ↔ + HierarchicalUsefulness.mark (CleanLeftDecoder.slots E own) upper lowerLevel + (F.original (CleanLeftDecoder.slots E own)) (F.arrays (CleanLeftDecoder.slots E own)) + (F.lowerEvent (CleanLeftDecoder.slots E own)) κ + (HierarchicalUsefulness.observe (CleanLeftDecoder.slots E own) upper lowerLevel + (CleanLeftDecoder.arrays E own)) = true := Iff.rfl + +theorem law_eq_adviceLaw + (E : CleanLeftDecoder.Exposed branch rows repeats n h t v m) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (r : Nat) (ρ : ℝ) (A : ManyGoodRows.RowMap (Block rows upper) r) + (own : CleanLeftDecoder.Own E) : + CleanLeftDecoder.law E upper lowerLevel σ (useful F upper lowerLevel κ E) r ρ A own = + HierarchicalLeftDecoder.adviceLaw (CleanLeftDecoder.slots E own) upper lowerLevel + (CleanLeftDecoder.background E upper own) σ + (mark F upper lowerLevel κ (CleanLeftDecoder.slots E own) + (CleanLeftDecoder.background E upper own)) r ρ A + (A.comp (CleanLeftDecoder.quotientMatrix E upper lowerLevel own)) := rfl + +end +end PerfectCompleteness.OriginalDecoderMark + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/CleanEndpointProjection.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/CleanEndpointProjection.lean new file mode 100644 index 0000000000000000000000000000000000000000..8c9bc50f65380aa162009f644c61b4049770b6cb --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/CleanEndpointProjection.lean @@ -0,0 +1,119 @@ +import OAI.Computability.PerfectCompleteness.Decoding.CutProjectionAssembly +import OAI.Computability.PerfectCompleteness.Foundations.SourceOddListsLemmas +import OAI.Computability.PerfectCompleteness.Repetition.CleanEndpointSlots + +namespace OAI + +section + +namespace PerfectCompleteness.CleanEndpointProjection + +open scoped Classical +open RecursiveSpaces MixedSupport SourceQuestionReconstruction + +noncomputable section + +private theorem reconstruct_designated {I E Q : Type*} {Leaf : I → Type*} + (designated : (i : I) → Leaf i) (clean : I → Prop) [DecidablePred clean] + [∀ i, DecidableEq (Leaf i)] (endpoint : I → E → Q) + (visible : Visible (E := E) designated clean) (own : {i : I // clean i} → Q) + (i : {i : I // clean i}) : + reconstruct designated clean endpoint visible own i.val (designated i.val) = own i := by + exact dite_eq_left ⟨i.property, rfl⟩ + +private theorem dite_heq_of_pos {α β : Type} {P : Prop} [Decidable P] + (f : P → α) (g : ¬ P → α) (b : β) (hP : P) + (h : HEq (f hP) b) : HEq (dite P f g) b := by + rw [dite_eq_left hP] + exact h + +variable {v m t : Nat} (clauses : Fin m → SourceClause.NormalizedClause v) + +def sourceProjection (projected : Bool) (e : SourceOddLists.Occurrences m t) : + ∀ k, Projection (SourceAnswerEquiv.leftSlots clauses (SourceOddLists.left e) k) + (SourceKeys.slot clauses (rightTuple clauses projected e k)) := + match projected with + | false => fun k => Projection.keep + (SourceAnswerEquiv.leftSlots clauses (SourceOddLists.left e) k) + | true => SourceAnswerEquiv.slotProjection clauses e + +theorem sourceProjection_of_true (projected : Bool) + (e : SourceOddLists.Occurrences m t) (k : Fin t) (hp : projected = true) : + HEq (sourceProjection clauses projected e k) + (SourceAnswerEquiv.slotProjection clauses e k) := by + subst projected + rfl + +variable {branch : Nat → Nat} {h : Nat} + (designated : Fin (branch h) → Slots branch h) + (clean : Fin (branch h) → Prop) + (visible : Visible (E := SourceTuple m t) designated clean) + +theorem leftInside_designated + (own : {i : Fin (branch h) // clean i} → Fin t → Fin m) + (i : {i : Fin (branch h) // clean i}) : + CleanEndpointSlots.leftInside clauses designated clean visible own + (i.val, designated i.val) = + SourceAnswerEquiv.leftSlots clauses (own i) := by + funext k + exact congrArg + (fun question : Fin t → SourceKeys.Endpoint v m => SourceKeys.slot clauses (question k)) + (reconstruct_designated designated clean (fun _ => leftTuple (v := v)) visible + (fun j k => SourceKeys.Endpoint.clause (v := v) (own j k)) i) + +variable (projected : Fin (branch h) → Bool) + +theorem rightInside_designated + (own : {i : Fin (branch h) // clean i} → Fin t → Fin v) + (i : {i : Fin (branch h) // clean i}) : + CleanEndpointSlots.rightInside clauses designated clean visible projected own + (i.val, designated i.val) = + SourceAnswerEquiv.rightSlots clauses (own i) := by + funext k + exact congrArg + (fun question : Fin t → SourceKeys.Endpoint v m => SourceKeys.slot clauses (question k)) + (reconstruct_designated designated clean (fun j => rightTuple clauses (projected j)) visible + (fun j k => SourceKeys.Endpoint.variable (m := m) (own j k)) i) + +def insideProjection (cleanProjected : ∀ i, clean i → projected i = true) + (e : {i : Fin (branch h) // clean i} → SourceOddLists.Occurrences m t) : + ∀ s k, Projection + (CleanEndpointSlots.leftInside clauses designated clean visible + (fun i => SourceOddLists.left (e i)) s k) + (CleanEndpointSlots.rightInside clauses designated clean visible projected + (fun i => SourceOddLists.right clauses (e i)) s k) := + fun s k => if hs : clean s.1 ∧ s.2 = designated s.1 then + CutProjectionAssembly.castProjection + (by simp only [SourceAnswerEquiv.leftSlots, SourceOddLists.left, + CleanEndpointSlots.leftInside, reconstructLeft, reconstruct, dite_eq_left hs]) + (by simp only [rightTuple, cleanProjected s.1 hs.1, ite_true, + CleanEndpointSlots.rightInside, reconstructRight, reconstruct, dite_eq_left hs, + SourceOddLists.right]) + (sourceProjection clauses (projected s.1) (e ⟨s.1, hs.1⟩) k) + else + CutProjectionAssembly.castProjection + (by simp only [SourceAnswerEquiv.leftSlots, SourceOddLists.left, + CleanEndpointSlots.leftInside, reconstructLeft, reconstruct, dite_eq_right hs, leftTuple]) + (by simp only [CleanEndpointSlots.rightInside, reconstructRight, reconstruct, dite_eq_right hs]) + (sourceProjection clauses (projected s.1) (visible s.1 ⟨s.2, hs⟩) k) + +theorem insideProjection_designated + (cleanProjected : ∀ i, clean i → projected i = true) + (e : {i : Fin (branch h) // clean i} → SourceOddLists.Occurrences m t) + (i : {i : Fin (branch h) // clean i}) (k : Fin t) : + HEq (insideProjection clauses designated clean visible projected cleanProjected e + (i.val, designated i.val) k) + (SourceAnswerEquiv.slotProjection clauses (e i) k) := by + refine @dite_heq_of_pos _ _ + (clean i.val ∧ designated i.val = designated i.val) _ _ _ + (SourceAnswerEquiv.slotProjection clauses (e i) k) ⟨i.property, rfl⟩ ?_ + exact (CutProjectionAssembly.castProjection_heq _ _ _).trans + (sourceProjection_of_true clauses (projected i.val) (e i) k + (cleanProjected i.val i.property)) + +end +end PerfectCompleteness.CleanEndpointProjection + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/CleanLeftDecoderLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/CleanLeftDecoderLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..1dcfc5a98f3f6c686a2892e55ae06b7568a1bc5d --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/CleanLeftDecoderLemmas.lean @@ -0,0 +1,537 @@ +import OAI.Computability.PerfectCompleteness.Decoding.DecoderSourcePullback +import OAI.Computability.PerfectCompleteness.Decoding.HierarchicalLeftDecoder +import OAI.Computability.PerfectCompleteness.Decoding.RightDecoderLemmas +import OAI.Computability.PerfectCompleteness.Decoding.TwoResponseCollisionLemmas +import OAI.Computability.PerfectCompleteness.Foundations.WholeCutReplayLemmas +import OAI.Computability.PerfectCompleteness.Foundations.WholeReplaySubtreeLemmas +import OAI.Computability.PerfectCompleteness.Repetition.CleanEndpointSlots +import OAI.Computability.PerfectCompleteness.Sampling.RecursiveSamplerLaws + +namespace OAI + +section + +namespace PerfectCompleteness.CleanLeftDecoder + +noncomputable section + +open scoped BigOperators Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays PointwiseSpaces +open UniqueGamesTheorem.Foundations.Games + +structure Exposed (branch rows repeats : Nat → Nat) (n h t v m : Nat) [NeZero m] where + clauses : Fin m → SourceClause.NormalizedClause v + designated : Fin (branch h) → Slots branch h + clean : Fin (branch h) → Prop + visible : SourceQuestionReconstruction.Visible + (E := SourceQuestionReconstruction.SourceTuple m t) designated clean + path : Path branch n (h + 1) + outside : Slots branch n → Fin t → MixedSupport.Slot + tape : WholeCutReplay.Tape rows repeats path + (CutSlotAssembly.fill path outside + (CleanEndpointSlots.leftReference clauses designated clean visible)) clean + +variable {branch rows repeats : Nat → Nat} {n h t v m : Nat} [NeZero m] + (E : Exposed branch rows repeats n h t v m) + +abbrev Own := {i : Fin (branch h) // E.clean i} → Fin t → Fin m + +instance ownFintype : Fintype (Own E) := Fintype.ofFinite _ + +def slots (own : Own E) : Slots branch n → Fin t → MixedSupport.Slot := + CleanEndpointSlots.leftSlots E.clauses E.designated E.clean E.visible E.path E.outside own + +def replay (own : Own E) : WholeCutReplay.Tape rows repeats E.path (slots E own) E.clean := + CleanEndpointSlots.leftReplay E.clauses E.designated E.clean E.visible + rows repeats E.path E.outside E.tape own + +def arrays (own : Own E) : Arrays (slots E own) rows := + WholeCutReplay.evaluateArrays rows repeats E.path (slots E own) E.clean (replay E own) + +variable (upper : Nodes branch n) (lowerLevel : Nat) + +def background (own : Own E) : + HierarchicalMatrixTable.Background (rows := rows) (slots E own) upper := + HierarchicalMatrixTable.backgroundOf (slots E own) upper (arrays E own) + +def upperMatrix (own : Own E) : + HierarchicalMatrixTable.Matrix (rows := rows) (slots E own) upper := + NodeEmbedding.matrix (arrays E own) upper + +def quotientMatrix (own : Own E) : + HierarchicalFrozenTables.QuotientMatrix (slots E own) upper lowerLevel + (background E upper own) := + MatrixRowQuotient.projectMatrix + (HierarchicalFrozenTables.knownRows (slots E own) upper lowerLevel (background E upper own)) + (upperMatrix E upper own) + +abbrev QuotientAdvice (r : Nat) (own : Own E) := + Module.Dual F2 (NodeEmbedding.RowSpace (slots E own) upper ⧸ + HierarchicalFrozenTables.knownRows (slots E own) upper lowerLevel (background E upper own)) + →ₗ[F2] (Fin r → F2) + +def advice (r : Nat) (A : ManyGoodRows.RowMap (Block rows upper) r) (own : Own E) : + ManyGoodRows.RowMap (Block rows upper) r × QuotientAdvice E upper lowerLevel r own := + (A, A.comp (quotientMatrix E upper lowerLevel own)) + +abbrev UpperAnswer (own : Own E) := Module.Dual F2 (NodeEmbedding.RowSpace (slots E own) upper) + +local instance rowSpaceFintype (own : Own E) (node : Nodes branch n) : + Fintype (NodeEmbedding.RowSpace (slots E own) node) := Fintype.ofFinite _ + +local instance nodeSpaceFintype (own : Own E) (node : Nodes branch n) : + Fintype (NodeEmbedding.NodeH (slots E own) node) := Fintype.ofFinite _ + +instance upperAnswerFintype (own : Own E) : Fintype (UpperAnswer E upper own) := + LeftDecoder.dualFintype (V := NodeEmbedding.RowSpace (slots E own) upper) + +abbrev Useful := (own : Own E) → + HierarchicalFrozenTables.QuotientMatrix (slots E own) upper lowerLevel + (background E upper own) → Prop + +variable (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (useful : Useful E upper lowerLevel) + +def law (r : Nat) (ρ : ℝ) (A : ManyGoodRows.RowMap (Block rows upper) r) (own : Own E) : + FiniteDistribution (UpperAnswer E upper own) := + HierarchicalLeftDecoder.adviceLaw (slots E own) upper lowerLevel (background E upper own) + σ (useful own) r ρ (advice E upper lowerLevel r A own).1 + (advice E upper lowerLevel r A own).2 + +abbrev Seed := (own : Own E) → UpperAnswer E upper own + +def seedLaw (r : Nat) (ρ : ℝ) (A : ManyGoodRows.RowMap (Block rows upper) r) : + FiniteDistribution (Seed E upper) := + FiniteProduct.law (I := Own E) (Ω := UpperAnswer E upper) + (law E upper lowerLevel σ useful r ρ A) + +theorem seedLaw_marginal (r : Nat) (ρ : ℝ) + (A : ManyGoodRows.RowMap (Block rows upper) r) (own : Own E) : + (seedLaw E upper lowerLevel σ useful r ρ A).pushforward (fun seed => seed own) = + law E upper lowerLevel σ useful r ρ A own := + FiniteProduct.eval_pushforward (I := Own E) (Ω := UpperAnswer E upper) + (law E upper lowerLevel σ useful r ρ A) own + +theorem supported_row (r : Nat) (ρ : ℝ) + (A : ManyGoodRows.RowMap (Block rows upper) r) (seed : Seed E upper) + (hsupport : (seedLaw E upper lowerLevel σ useful r ρ A).weight seed ≠ 0) + (own : Own E) : (law E upper lowerLevel σ useful r ρ A own).weight (seed own) ≠ 0 := by + intro hz + apply hsupport + change (∏ q, (law E upper lowerLevel σ useful r ρ A q).weight (seed q)) = 0 + exact Finset.prod_eq_zero (Finset.mem_univ own) hz + +variable (hbranch : ∀ k < n, 0 < branch k) + +theorem law_valid (r : Nat) (ρ : ℝ) (hρ : 0 < ρ) + (A : ManyGoodRows.RowMap (Block rows upper) r) (own : Own E) : + (law E upper lowerLevel σ useful r ρ A own).probability + (fun q => decide (HierarchicalLeftDecoder.Valid (slots E own) upper lowerLevel + hbranch (background E upper own) q)) = 1 := + HierarchicalLeftDecoder.adviceLaw_valid (slots E own) upper lowerLevel hbranch + (background E upper own) σ (useful own) r ρ hρ + (advice E upper lowerLevel r A own).1 (advice E upper lowerLevel r A own).2 + +theorem supported_seed_valid (r : Nat) (ρ : ℝ) (hρ : 0 < ρ) + (A : ManyGoodRows.RowMap (Block rows upper) r) (seed : Seed E upper) + (hsupport : (seedLaw E upper lowerLevel σ useful r ρ A).weight seed ≠ 0) + (own : Own E) : + HierarchicalLeftDecoder.Valid (slots E own) upper lowerLevel hbranch + (background E upper own) (seed own) := by + exact of_decide_eq_true (DecoderTableAdmissibility.event_of_probability_one + (law E upper lowerLevel σ useful r ρ A own) + (fun q => decide (HierarchicalLeftDecoder.Valid (slots E own) upper lowerLevel + hbranch (background E upper own) q)) + (law_valid E upper lowerLevel σ useful hbranch r ρ hρ A own) (seed own) + (supported_row E upper lowerLevel σ useful r ρ A seed hsupport own)) + +theorem seedLaw_valid (r : Nat) (ρ : ℝ) (hρ : 0 < ρ) + (A : ManyGoodRows.RowMap (Block rows upper) r) : + (seedLaw E upper lowerLevel σ useful r ρ A).probability + (fun seed => decide (∀ own : Own E, + HierarchicalLeftDecoder.Valid (slots E own) upper lowerLevel hbranch + (background E upper own) (seed own))) = 1 := by + apply DecoderTableAdmissibility.probability_one_of_support + intro seed hs + exact decide_eq_true (supported_seed_valid E upper lowerLevel σ useful hbranch + r ρ hρ A seed hs) + +abbrev LowerH (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) (own : Own E) := + NodeEmbedding.NodeH (slots E own) (HierarchicalLeftDecoder.LowerNode upper lowerLevel d) + +abbrev LowerAnswer (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) (own : Own E) := + Module.Dual F2 (squareSpace (LowerH E upper lowerLevel d own)) + +instance lowerAnswerFintype (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) + (own : Own E) : Fintype (LowerAnswer E upper lowerLevel d own) := + LeftDecoder.dualFintype (V := squareSpace (LowerH E upper lowerLevel d own)) + +def output (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) (own : Own E) + (q : UpperAnswer E upper own) : LowerAnswer E upper lowerLevel d own := + HierarchicalLeftDecoder.output (slots E own) upper lowerLevel hbranch d q + +def form (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) (own : Own E) + (q : UpperAnswer E upper own) : + LowerH E upper lowerLevel d own →ₗ[F2] LowerH E upper lowerLevel d own →ₗ[F2] F2 := + OddListExtraction.multiplicationForm (LowerH E upper lowerLevel d own) + (output E upper lowerLevel hbranch d own q) + +def formFamily (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) (seed : Seed E upper) : + (own : Own E) → + LowerH E upper lowerLevel d own →ₗ[F2] LowerH E upper lowerLevel d own →ₗ[F2] F2 := + fun own => form E upper lowerLevel hbranch d own (seed own) + +def outputLaw (r : Nat) (ρ : ℝ) (A : ManyGoodRows.RowMap (Block rows upper) r) + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) (own : Own E) : + FiniteDistribution (LowerAnswer E upper lowerLevel d own) := + (law E upper lowerLevel σ useful r ρ A own).pushforward + (output E upper lowerLevel hbranch d own) + +theorem seedLaw_output_marginal (r : Nat) (ρ : ℝ) + (A : ManyGoodRows.RowMap (Block rows upper) r) + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) (own : Own E) : + (seedLaw E upper lowerLevel σ useful r ρ A).pushforward + (fun seed => output E upper lowerLevel hbranch d own (seed own)) = + outputLaw E upper lowerLevel σ useful hbranch r ρ A d own := by + calc + _ = ((seedLaw E upper lowerLevel σ useful r ρ A).pushforward + (fun seed : Seed E upper => seed own)).pushforward + (output E upper lowerLevel hbranch d own) := + (FiniteDistribution.pushforward_comp (seedLaw E upper lowerLevel σ useful r ρ A) + (fun seed : Seed E upper => seed own) (output E upper lowerLevel hbranch d own)).symm + _ = _ := by rw [seedLaw_marginal]; rfl + +theorem supported_output_normalized (r : Nat) (ρ : ℝ) (hρ : 0 < ρ) + (A : ManyGoodRows.RowMap (Block rows upper) r) (seed : Seed E upper) + (hsupport : (seedLaw E upper lowerLevel σ useful r ρ A).weight seed ≠ 0) + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) (own : Own E) : + output E upper lowerLevel hbranch d own (seed own) + (HierarchicalLeftDecoder.lowerOne (slots E own) upper lowerLevel hbranch d) = 1 := + (supported_seed_valid E upper lowerLevel σ useful hbranch r ρ hρ A seed hsupport own d).1 + +theorem supported_form_tested_rank (r : Nat) (ρ : ℝ) (hρ : 0 < ρ) + (A : ManyGoodRows.RowMap (Block rows upper) r) (seed : Seed E upper) + (hsupport : (seedLaw E upper lowerLevel σ useful r ρ A).weight seed ≠ 0) + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) (own : Own E) : + (LowerAffineSliceRank.testedGram + (FunctionSpaceLowerRank.matrixForm (LowerH E upper lowerLevel d own) + (formFamily E upper lowerLevel hbranch d seed own)) + (HierarchicalLeftDecoder.testedMatrix (slots E own) upper lowerLevel + (background E upper own) d)).rank ≤ 1 := + (supported_seed_valid E upper lowerLevel σ useful hbranch r ρ hρ A seed hsupport own d).2 + +end +end PerfectCompleteness.CleanLeftDecoder + +end + +section + +namespace PerfectCompleteness.CleanRightDecoder + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +abbrev F2 := ZMod 2 + +noncomputable section + +variable {branch : Nat → Nat} {N h : Nat} + +def suffix (upper lower : Nodes branch N) (cut : OwnInputReference.Cut upper lower) + (hlower : Nodes.height lower = h + 1) : Path branch (Nodes.height upper) (h + 1) := + hlower ▸ cut.path + +theorem suffix_proper (upper lower : Nodes branch N) + (cut : OwnInputReference.Cut upper lower) (hlower : Nodes.height lower = h + 1) : + h + 1 < Nodes.height upper := by + simpa only [hlower] using cut.proper + +def fullPath (upper lower : Nodes branch N) (cut : OwnInputReference.Cut upper lower) + (hlower : Nodes.height lower = h + 1) : Path branch N (h + 1) := + (Nodes.path upper).append (suffix upper lower cut hlower) + +variable {t v m : Nat} + +abbrev OwnQuestions (clean : Fin (branch h) → Prop) := + {i : Fin (branch h) // clean i} → Fin t → Fin v + +variable [NeZero m] + (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch h) → Slots branch h) + (clean : Fin (branch h) → Prop) + (visible : SourceQuestionReconstruction.Visible + (E := SourceQuestionReconstruction.SourceTuple m t) designated clean) + (projected : Fin (branch h) → Bool) + (upper lower : Nodes branch N) (cut : OwnInputReference.Cut upper lower) + (hlower : Nodes.height lower = h + 1) + (outside : Slots branch N → Fin t → MixedSupport.Slot) + +def slots (own : OwnQuestions (t := t) (v := v) clean) : + Slots branch N → Fin t → MixedSupport.Slot := + CleanEndpointSlots.rightSlots clauses designated clean visible + (fullPath upper lower cut hlower) outside projected own + +variable (rows repeats : Nat → Nat) + +abbrev Record := WholeCutReplay.Tape rows repeats (fullPath upper lower cut hlower) + (CutSlotAssembly.fill (fullPath upper lower cut hlower) outside + (CleanEndpointSlots.rightReference clauses designated clean visible projected)) clean + +variable (record : Record clauses designated clean visible projected + upper lower cut hlower outside rows repeats) + +def replay (own : OwnQuestions (t := t) (v := v) clean) : + WholeCutReplay.Tape rows repeats (fullPath upper lower cut hlower) + (slots clauses designated clean visible projected upper lower cut hlower outside own) clean := + CleanEndpointSlots.rightReplay clauses designated clean visible rows repeats + (fullPath upper lower cut hlower) outside projected record own + +def arrays (own : OwnQuestions (t := t) (v := v) clean) : + Arrays (slots clauses designated clean visible projected upper lower cut hlower outside own) rows := + WholeCutReplay.evaluateArrays rows repeats (fullPath upper lower cut hlower) + (slots clauses designated clean visible projected upper lower cut hlower outside own) clean + (replay clauses designated clean visible projected upper lower cut hlower outside + rows repeats record own) + +def exterior (own : OwnQuestions (t := t) (v := v) clean) : + OwnInputReference.Exterior + (slots clauses designated clean visible projected upper lower cut hlower outside own) + rows upper lower where + otherArrays node := arrays clauses designated clean visible projected + upper lower cut hlower outside rows repeats record own node.val + lowerRows := arrays clauses designated clean visible projected + upper lower cut hlower outside rows repeats record own lower + +variable (W : Submodule F2 (OwnInputReference.UpperVector rows upper)) + (a : OwnInputReference.LowerVector rows lower) + +def knownBuckets (own : OwnQuestions (t := t) (v := v) clean) : + HiddenBucketBias.VisibleDirection W → + OwnInputReference.UpperSpace + (slots clauses designated clean visible projected upper lower cut hlower outside own) upper := + WholeReplaySubtree.knownBucketsAtNode rows repeats + (slots clauses designated clean visible projected upper lower cut hlower outside own) + upper (suffix upper lower cut hlower) (suffix_proper upper lower cut hlower) clean W + (replay clauses designated clean visible projected upper lower cut hlower outside + rows repeats record own) + +def input (own : OwnQuestions (t := t) (v := v) clean) : + OwnInputReference.Input + (slots clauses designated clean visible projected upper lower cut hlower outside own) + rows upper lower W a := + OwnInputReference.readInput + (slots clauses designated clean visible projected upper lower cut hlower outside own) + rows upper lower W a id + (knownBuckets clauses designated clean visible projected upper lower cut hlower outside + rows repeats record W own, + exterior clauses designated clean visible projected upper lower cut hlower outside + rows repeats record own) + +@[simp] theorem input_knownBuckets (own : OwnQuestions (t := t) (v := v) clean) : + (input clauses designated clean visible projected upper lower cut hlower outside + rows repeats record W a own).knownBuckets = + knownBuckets clauses designated clean visible projected upper lower cut hlower outside + rows repeats record W own := rfl + +@[simp] theorem input_otherArrays (own : OwnQuestions (t := t) (v := v) clean) + (node : OwnInputReference.OtherNodes upper lower) : + (input clauses designated clean visible projected upper lower cut hlower outside + rows repeats record W a own).otherArrays node = + arrays clauses designated clean visible projected upper lower cut hlower outside + rows repeats record own node.val := rfl + +@[simp] theorem input_lowerQuotient (own : OwnQuestions (t := t) (v := v) clean) + (x : Domain (nodeSlots + (slots clauses designated clean visible projected upper lower cut hlower outside own) lower)) : + (input clauses designated clean visible projected upper lower cut hlower outside + rows repeats record W a own).lowerQuotient x = + DirectionQuotient.proj a (fun row => + (arrays clauses designated clean visible projected upper lower cut hlower outside + rows repeats record own lower row).val x) := rfl + +abbrev Answer (own : OwnQuestions (t := t) (v := v) clean) := + Module.Dual F2 (OwnInputReference.UpperSpace + (slots clauses designated clean visible projected upper lower cut hlower outside own) upper) + +local instance answerFintype (own : OwnQuestions (t := t) (v := v) clean) : + Fintype (Answer clauses designated clean visible projected upper lower cut hlower outside own) := + RightDecoder.scalarFintype + (slots clauses designated clean visible projected upper lower cut hlower outside own) upper + +variable (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch N t)) + (threshold : ℝ) + +def kernel (own : OwnQuestions (t := t) (v := v) clean) : + FiniteDistribution (Answer clauses designated clean visible projected + upper lower cut hlower outside own) := + RightDecoder.law + (slots clauses designated clean visible projected upper lower cut hlower outside own) + rows upper lower W a repeats cut labeling + (input clauses designated clean visible projected upper lower cut hlower outside + rows repeats record W a own) threshold + +abbrev Seed := (own : OwnQuestions (t := t) (v := v) clean) → + Answer clauses designated clean visible projected upper lower cut hlower outside own + +def seedLaw : FiniteDistribution + (Seed clauses designated clean visible projected upper lower cut hlower outside) := + FiniteProduct.law + (kernel clauses designated clean visible projected upper lower cut hlower outside + rows repeats record W a labeling threshold) + +theorem seedLaw_eval (own : OwnQuestions (t := t) (v := v) clean) : + (seedLaw clauses designated clean visible projected upper lower cut hlower outside + rows repeats record W a labeling threshold).pushforward (fun seed => seed own) = + kernel clauses designated clean visible projected upper lower cut hlower outside + rows repeats record W a labeling threshold own := + FiniteProduct.eval_pushforward + (kernel clauses designated clean visible projected upper lower cut hlower outside + rows repeats record W a labeling threshold) own + +variable (hbranch : ∀ k < Nodes.height upper, 0 < branch k) + +abbrev Form (own : OwnQuestions (t := t) (v := v) clean) := + RightDecoderDescendant.Form + (slots clauses designated clean visible projected upper lower cut hlower outside own) lower + +local instance formFintype (own : OwnQuestions (t := t) (v := v) clean) : + Fintype (Form clauses designated clean visible projected upper lower cut hlower outside own) := + RightDecoderDescendant.formFintype + (slots clauses designated clean visible projected upper lower cut hlower outside own) lower + +def forms (seed : Seed clauses designated clean visible projected upper lower cut hlower outside) + (own : OwnQuestions (t := t) (v := v) clean) : + Form clauses designated clean visible projected upper lower cut hlower outside own := + RightDecoderDescendant.form + (slots clauses designated clean visible projected upper lower cut hlower outside own) + upper lower cut hbranch (seed own) + +def formKernel (own : OwnQuestions (t := t) (v := v) clean) : + FiniteDistribution (Form clauses designated clean visible projected + upper lower cut hlower outside own) := + RightDecoderDescendant.formLaw + (slots clauses designated clean visible projected upper lower cut hlower outside own) + upper lower cut hbranch rows W a repeats labeling + (input clauses designated clean visible projected upper lower cut hlower outside + rows repeats record W a own) threshold + +theorem seedLaw_forms (own : OwnQuestions (t := t) (v := v) clean) : + (seedLaw clauses designated clean visible projected upper lower cut hlower outside + rows repeats record W a labeling threshold).pushforward + (fun seed => forms clauses designated clean visible projected upper lower cut hlower outside + hbranch seed own) = + formKernel clauses designated clean visible projected upper lower cut hlower outside + rows repeats record W a labeling threshold hbranch own := by + let decode := RightDecoderDescendant.form + (slots clauses designated clean visible projected upper lower cut hlower outside own) + upper lower cut hbranch + change (seedLaw clauses designated clean visible projected upper lower cut hlower outside + rows repeats record W a labeling threshold).pushforward + (fun seed => decode (seed own)) = _ + rw [← FiniteDistribution.pushforward_comp + (seedLaw clauses designated clean visible projected upper lower cut hlower outside + rows repeats record W a labeling threshold) + (fun seed : Seed clauses designated clean visible projected + upper lower cut hlower outside => seed own) decode, + seedLaw_eval clauses designated clean visible projected upper lower cut hlower outside + rows repeats record W a labeling threshold own] + rfl + +end +end PerfectCompleteness.CleanRightDecoder + +end + +section + +namespace PerfectCompleteness.CleanDecoderContext + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays + +abbrev F2 := ZMod 2 + +variable {branch : Nat → Nat} {n h : Nat} + +theorem lowerHeight (upper : Nodes branch n) + (d : HierarchicalFrozenTables.LowerNodes upper (h + 1)) : + Nodes.height (HierarchicalLeftDecoder.LowerNode upper (h + 1) d) = h + 1 := + (RelativeDescendantProducts.relativeNode_height upper d.val.val).trans d.property + +structure Exposed (branch rows repeats : Nat → Nat) (n h t v m : Nat) [NeZero m] + (upper : Nodes branch n) (d : HierarchicalFrozenTables.LowerNodes upper (h + 1)) where + clauses : Fin m → SourceClause.NormalizedClause v + designated : Fin (branch h) → Slots branch h + clean : Fin (branch h) → Prop + visible : SourceQuestionReconstruction.Visible + (E := SourceQuestionReconstruction.SourceTuple m t) designated clean + projected : Fin (branch h) → Bool + cleanProjected : ∀ i, clean i → projected i = true + cut : OwnInputReference.Cut upper (HierarchicalLeftDecoder.LowerNode upper (h + 1) d) + outside : Slots branch n → Fin t → MixedSupport.Slot + leftTape : WholeCutReplay.Tape rows repeats + (CleanRightDecoder.fullPath upper (HierarchicalLeftDecoder.LowerNode upper (h + 1) d) + cut (lowerHeight upper d)) + (CutSlotAssembly.fill + (CleanRightDecoder.fullPath upper (HierarchicalLeftDecoder.LowerNode upper (h + 1) d) + cut (lowerHeight upper d)) outside + (CleanEndpointSlots.leftReference clauses designated clean visible)) clean + rightTape : CleanRightDecoder.Record clauses designated clean visible projected upper + (HierarchicalLeftDecoder.LowerNode upper (h + 1) d) cut (lowerHeight upper d) + outside rows repeats + +variable {rows repeats : Nat → Nat} {t v m : Nat} [NeZero m] + {upper : Nodes branch n} {d : HierarchicalFrozenTables.LowerNodes upper (h + 1)} + (E : Exposed branch rows repeats n h t v m upper d) + +abbrev lower (_E : Exposed branch rows repeats n h t v m upper d) := + HierarchicalLeftDecoder.LowerNode upper (h + 1) d + +def path : Path branch n (h + 1) := + CleanRightDecoder.fullPath upper (lower E) E.cut (lowerHeight upper d) + +abbrev CleanChildren := {i : Fin (branch h) // E.clean i} +abbrev LeftOwn := CleanChildren E → Fin t → Fin m +abbrev RightOwn := CleanChildren E → Fin t → Fin v + +def leftExposed : CleanLeftDecoder.Exposed branch rows repeats n h t v m where + clauses := E.clauses + designated := E.designated + clean := E.clean + visible := E.visible + path := path E + outside := E.outside + tape := E.leftTape + +abbrev leftSlots (own : LeftOwn E) := CleanLeftDecoder.slots (leftExposed E) own +abbrev rightSlots (own : RightOwn E) := + CleanRightDecoder.slots E.clauses E.designated E.clean E.visible E.projected + upper (lower E) E.cut (lowerHeight upper d) E.outside own + +abbrev LeftSeed := CleanLeftDecoder.Seed (leftExposed E) upper +abbrev RightSeed := CleanRightDecoder.Seed E.clauses E.designated E.clean E.visible + E.projected upper (lower E) E.cut (lowerHeight upper d) E.outside + +variable (hbranch : ∀ k < n, 0 < branch k) + +def leftOutput (seed : LeftSeed E) (own : LeftOwn E) := + CleanLeftDecoder.output (leftExposed E) upper (h + 1) hbranch d own (seed own) + +def leftForm (seed : LeftSeed E) (own : LeftOwn E) := + CleanLeftDecoder.form (leftExposed E) upper (h + 1) hbranch d own (seed own) + +def rightForm (seed : RightSeed E) (own : RightOwn E) := + CleanRightDecoder.forms E.clauses E.designated E.clean E.visible E.projected + upper (lower E) E.cut (lowerHeight upper d) E.outside + (DecoderSourcePullback.upperBranch upper hbranch) seed own + +end +end PerfectCompleteness.CleanDecoderContext + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/CleanPhysicalDecoderLaw.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/CleanPhysicalDecoderLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..193a948e6a3507b0d79b8af82636744050e06f39 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/CleanPhysicalDecoderLaw.lean @@ -0,0 +1,389 @@ +import OAI.Computability.PerfectCompleteness.Decoding.CleanDecoderSeedLawLemmas +import OAI.Computability.PerfectCompleteness.Decoding.CleanRecordProjection +import OAI.Computability.PerfectCompleteness.Foundations.WholeReplaySubtreeLemmas +import OAI.Computability.PerfectCompleteness.Machines.WholeArrayInteriorOwnInputLaw +import OAI.Computability.PerfectCompleteness.Repetition.CleanNativeReplay + +namespace OAI + +section + +namespace PerfectCompleteness.CleanPhysicalDecoderLaw + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +abbrev F2 := ZMod 2 + +attribute [local instance] RightDecoder.scalarFintype + +local instance nativeLeftFintype {branch : Nat → Nat} {n t : Nat} + (slots : Slots branch n → Fin t → MixedSupport.Slot) (upper : Nodes branch n) : + Fintype (Module.Dual F2 (NodeEmbedding.RowSpace slots upper)) := + LeftDecoder.dualFintype (V := NodeEmbedding.RowSpace slots upper) + +section NativeData + +variable {branch rows repeats : Nat → Nat} {n t : Nat} + +def inputOfArrays (slots : Slots branch n → Fin t → MixedSupport.Slot) + (upper lower : Nodes branch n) (W : Submodule F2 (Block rows upper)) + (a : Block rows lower) + (known : HiddenBucketBias.VisibleDirection W → H (nodeSlots slots upper)) + (arrays : Arrays slots rows) : OwnInputReference.Input slots rows upper lower W a where + knownBuckets := known + otherArrays node := arrays node.val + lowerQuotient x := DirectionQuotient.proj a (fun row => (arrays lower row).val x) + +private theorem inputOfArrays_heq + (slots target : Slots branch n → Fin t → MixedSupport.Slot) (hs : slots = target) + (upper lower : Nodes branch n) (W : Submodule F2 (Block rows upper)) + (a : Block rows lower) + (known : HiddenBucketBias.VisibleDirection W → H (nodeSlots slots upper)) + (otherKnown : HiddenBucketBias.VisibleDirection W → H (nodeSlots target upper)) + (hk : HEq known otherKnown) (arrays : Arrays slots rows) (other : Arrays target rows) + (ha : HEq arrays other) : + HEq (inputOfArrays slots upper lower W a known arrays) + (inputOfArrays target upper lower W a otherKnown other) := by + cases hs + cases eq_of_heq hk + cases eq_of_heq ha + rfl + +private theorem replayKnown_heq {h : Nat} + (slots target : Slots branch n → Fin t → MixedSupport.Slot) (hs : slots = target) + (upper : Nodes branch n) (p : Path branch (Nodes.height upper) (h + 1)) + (hp : h + 1 < Nodes.height upper) (clean : Fin (branch h) → Prop) + (W : Submodule F2 (Block rows upper)) + (tape : WholeCutReplay.Tape rows repeats ((Nodes.path upper).append p) slots clean) + (other : WholeCutReplay.Tape rows repeats ((Nodes.path upper).append p) target clean) + (ht : HEq tape other) : + HEq (WholeReplaySubtree.knownBucketsAtNode rows repeats slots upper p hp clean W tape) + (WholeReplaySubtree.knownBucketsAtNode rows repeats target upper p hp clean W other) := by + cases hs + cases eq_of_heq ht + rfl + +def uncastTape (slots : Slots branch n → Fin t → MixedSupport.Slot) + (upper lower : Nodes branch n) (cut : OwnInputReference.Cut upper lower) + {k : Nat} (hk : Nodes.height lower = k) + (tape : WholeArraySampler.Tape rows repeats + ((Nodes.path upper).append (hk ▸ cut.path)) slots) : + WholeArraySampler.Tape rows repeats ((Nodes.path upper).append cut.path) slots := by + cases hk + exact tape + +def inputFromTape (slots : Slots branch n → Fin t → MixedSupport.Slot) + (upper lower : Nodes branch n) (cut : OwnInputReference.Cut upper lower) + {k : Nat} (hk : Nodes.height lower = k) + (W : Submodule F2 (Block rows upper)) (a : Block rows lower) + (tape : WholeArraySampler.Tape rows repeats + ((Nodes.path upper).append (hk ▸ cut.path)) slots) : + OwnInputReference.Input slots rows upper lower W a := + inputOfArrays slots upper lower W a + (fun v => RecursiveSampler.evaluate F2 repeats (hk ▸ cut.path) + (LeafDomain (nodeSlots slots upper)) + ((WholeArrayPositiveSplit.split rows repeats (Nodes.path upper) (hk ▸ cut.path) + (by simpa only [hk] using cut.proper) slots W tape).2.1 v)) + (WholeArraySampler.evaluate rows repeats ((Nodes.path upper).append (hk ▸ cut.path)) slots tape) + +theorem inputFromTape_eq_ownInput + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (upper lower : Nodes branch n) (cut : OwnInputReference.Cut upper lower) + {k : Nat} (hk : Nodes.height lower = k) + (W : Submodule F2 (Block rows upper)) (a : Block rows lower) + (tape : WholeArraySampler.Tape rows repeats + ((Nodes.path upper).append (hk ▸ cut.path)) slots) : + inputFromTape slots upper lower cut hk W a tape = + WholeArrayInteriorOwnInputLaw.ownInput rows repeats slots upper lower cut W a + (uncastTape slots upper lower cut hk tape) := by + cases hk + rfl + +variable {Sample : OriginalDecoderMark.SlotFamily branch n t → Type*} + [∀ slots, Fintype (Sample slots)] + (F : OriginalDecoderMark.Family branch rows n t Sample) + +def adviceLaw (slots : Slots branch n → Fin t → MixedSupport.Slot) + (upper : Nodes branch n) (level : Nat) (κ : ℝ) + (arrays : Arrays slots rows) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (r : Nat) (ρ : ℝ) (A : ManyGoodRows.RowMap (Block rows upper) r) : + FiniteDistribution (Module.Dual F2 (NodeEmbedding.RowSpace slots upper)) := + HierarchicalLeftDecoder.adviceLaw slots upper level + (HierarchicalMatrixTable.backgroundOf slots upper arrays) σ + (OriginalDecoderMark.mark F upper level κ slots + (HierarchicalMatrixTable.backgroundOf slots upper arrays)) r ρ A + (A.comp (MatrixRowQuotient.projectMatrix + (HierarchicalFrozenTables.knownRows slots upper level + (HierarchicalMatrixTable.backgroundOf slots upper arrays)) + (NodeEmbedding.matrix arrays upper))) + +private theorem adviceLaw_heq + (slots target : Slots branch n → Fin t → MixedSupport.Slot) (hs : slots = target) + (upper : Nodes branch n) (level : Nat) (κ : ℝ) + (arrays : Arrays slots rows) (other : Arrays target rows) (ha : HEq arrays other) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (r : Nat) (ρ : ℝ) (A : ManyGoodRows.RowMap (Block rows upper) r) : + HEq (adviceLaw F slots upper level κ arrays σ r ρ A) + (adviceLaw F target upper level κ other σ r ρ A) := by + cases hs + cases eq_of_heq ha + rfl + +private theorem rightLaw_heq + (slots target : Slots branch n → Fin t → MixedSupport.Slot) (hs : slots = target) + (upper lower : Nodes branch n) (W : Submodule F2 (Block rows upper)) + (a : Block rows lower) (cut : OwnInputReference.Cut upper lower) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (input : OwnInputReference.Input slots rows upper lower W a) + (other : OwnInputReference.Input target rows upper lower W a) (hi : HEq input other) + (threshold : ℝ) : + HEq (RightDecoder.law slots rows upper lower W a repeats cut σ input threshold) + (RightDecoder.law target rows upper lower W a repeats cut σ other threshold) := by + cases hs + cases eq_of_heq hi + rfl + +abbrev Answers (slots projected : Slots branch n → Fin t → MixedSupport.Slot) + (upper : Nodes branch n) := + Module.Dual F2 (NodeEmbedding.RowSpace slots upper) × + Module.Dual F2 (OwnInputReference.UpperSpace projected upper) + +instance answersFintype (slots projected : Slots branch n → Fin t → MixedSupport.Slot) + (upper : Nodes branch n) : Fintype (Answers slots projected upper) := by + letI := LeftDecoder.dualFintype (V := NodeEmbedding.RowSpace slots upper) + letI := RightDecoder.scalarFintype projected upper + exact inferInstanceAs (Fintype + (Module.Dual F2 (NodeEmbedding.RowSpace slots upper) × + Module.Dual F2 (OwnInputReference.UpperSpace projected upper))) + +def answerEquiv (slots projected target other : Slots branch n → Fin t → MixedSupport.Slot) + (hs : slots = target) (hp : projected = other) (upper : Nodes branch n) : + Answers slots projected upper ≃ Answers target other upper := by + cases hs + cases hp + exact Equiv.refl _ + +private theorem product_heq + (slots projected target other : Slots branch n → Fin t → MixedSupport.Slot) + (hs : slots = target) (hp : projected = other) (upper : Nodes branch n) + (μ : FiniteDistribution (Module.Dual F2 (NodeEmbedding.RowSpace slots upper))) + (μ' : FiniteDistribution (Module.Dual F2 (NodeEmbedding.RowSpace target upper))) + (ν : FiniteDistribution (Module.Dual F2 (OwnInputReference.UpperSpace projected upper))) + (ν' : FiniteDistribution (Module.Dual F2 (OwnInputReference.UpperSpace other upper))) + (hμ : HEq μ μ') (hν : HEq ν ν') : HEq (μ.product ν) (μ'.product ν') := by + cases hs + cases hp + cases eq_of_heq hμ + cases eq_of_heq hν + rfl + +private theorem pushforward_answerEquiv + (slots projected target other : Slots branch n → Fin t → MixedSupport.Slot) + (hs : slots = target) (hp : projected = other) (upper : Nodes branch n) + (μ : FiniteDistribution (Answers slots projected upper)) + (ν : FiniteDistribution (Answers target other upper)) (hμ : HEq μ ν) : + μ.pushforward (answerEquiv slots projected target other hs hp upper) = ν := by + cases hs + cases hp + cases eq_of_heq hμ + exact FiniteDistribution.pushforward_id μ + +private theorem meeting_answerEquiv + (slots projected target other : Slots branch n → Fin t → MixedSupport.Slot) + (hs : slots = target) (hp : projected = other) (upper : Nodes branch n) + (q : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (q' : ∀ s k, MixedSupport.Projection (target s k) (other s k)) + (hq : ∀ s k, HEq (q s k) (q' s k)) (answer : Answers slots projected upper) : + decide ((answerEquiv slots projected target other hs hp upper answer).2 = + DecoderSourcePullback.upperTarget q' upper + (answerEquiv slots projected target other hs hp upper answer).1) = + decide (answer.2 = DecoderSourcePullback.upperTarget q upper answer.1) := by + cases hs + cases hp + have hqq : q = q' := funext (fun s => funext (fun k => eq_of_heq (hq s k))) + cases hqq + rfl + +end NativeData + +variable {branch rows repeats : Nat → Nat} {n h t v m : Nat} [NeZero m] + {upper : Nodes branch n} {d : HierarchicalFrozenTables.LowerNodes upper (h + 1)} + (S : CleanDecoderRate.Setup branch rows repeats n h t v m upper d) + +abbrev lower (_S : CleanDecoderRate.Setup branch rows repeats n h t v m upper d) := + HierarchicalLeftDecoder.LowerNode upper (h + 1) d + +abbrev leftArrays (x : CleanDecoderRate.Sample S) := + WholeCutSampler.evaluate rows repeats (CleanDecoderRate.path S) + (CleanNativeReplay.leftSlots S x) (CleanNativeReplay.leftTape S x) + +abbrev rightArrays (x : CleanDecoderRate.Sample S) := + WholeCutSampler.evaluate rows repeats (CleanDecoderRate.path S) + (CleanNativeReplay.rightSlots S x) (CleanNativeReplay.rightTape S x) + +abbrev rightWholeTape (x : CleanDecoderRate.Sample S) := + WholeCutSampler.collapse rows repeats (CleanDecoderRate.path S) + (CleanNativeReplay.rightSlots S x) (CleanNativeReplay.rightTape S x) + +def rightInput (W : Submodule F2 (Block rows upper)) (a : Block rows (lower S)) + (x : CleanDecoderRate.Sample S) : + OwnInputReference.Input (CleanNativeReplay.rightSlots S x) rows upper (lower S) W a := + inputFromTape (CleanNativeReplay.rightSlots S x) upper (lower S) S.cut + (CleanDecoderContext.lowerHeight upper d) W a (rightWholeTape S x) + +theorem rightInput_eq_ownInput (W : Submodule F2 (Block rows upper)) + (a : Block rows (lower S)) (x : CleanDecoderRate.Sample S) : + rightInput S W a x = + WholeArrayInteriorOwnInputLaw.ownInput rows repeats (CleanNativeReplay.rightSlots S x) + upper (lower S) S.cut W a + (uncastTape (CleanNativeReplay.rightSlots S x) upper (lower S) S.cut + (CleanDecoderContext.lowerHeight upper d) (rightWholeTape S x)) := + inputFromTape_eq_ownInput _ _ _ _ _ _ _ _ + +variable {Sample : OriginalDecoderMark.SlotFamily branch n t → Type*} + [∀ slots, Fintype (Sample slots)] + (F : OriginalDecoderMark.Family branch rows n t Sample) (κ : ℝ) + +def useful (record : CleanDecoderRate.Record S) := + OriginalDecoderMark.useful F upper (h + 1) κ + (CleanDecoderContext.leftExposed (CleanDecoderRate.context S record)) + +variable (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (r : Nat) (ρ : ℝ) (A : ManyGoodRows.RowMap (Block rows upper) r) + (W : Submodule F2 (Block rows upper)) (a : Block rows (lower S)) + (threshold : ℝ) + +def leftLaw (x : CleanDecoderRate.Sample S) := + adviceLaw F (CleanNativeReplay.leftSlots S x) upper (h + 1) κ (leftArrays S x) σ r ρ A + +def rightLaw (x : CleanDecoderRate.Sample S) := + RightDecoder.law (CleanNativeReplay.rightSlots S x) rows upper (lower S) W a + repeats S.cut σ (rightInput S W a x) threshold + +def pairKernel (x : CleanDecoderRate.Sample S) := + (leftLaw S F κ σ r ρ A x).product (rightLaw S σ W a threshold x) + +variable (cube : Nat) (hcube : 0 < cube) + +theorem leftKernel_heq (x : CleanDecoderRate.Sample S) + (hx : (CleanDecoderRate.rawLaw S cube hcube).weight x ≠ 0) : + HEq (CleanDecoderSeedLaw.leftKernel (CleanDecoderPairLaw.context S x) σ + (useful S F κ (CleanDecoderRate.observations S x)) r ρ A (CleanDecoderPairLaw.leftOwn S x)) + (leftLaw S F κ σ r ρ A x) := + adviceLaw_heq F _ _ (CleanNativeReplay.leftSlots_eq S x) upper (h + 1) κ + _ _ (CleanNativeReplay.leftArrays_heq S cube hcube x hx) σ r ρ A + +theorem rightKnownBuckets_heq (x : CleanDecoderRate.Sample S) + (hx : (CleanDecoderRate.rawLaw S cube hcube).weight x ≠ 0) : + HEq (CleanRightDecoder.knownBuckets + (CleanDecoderPairLaw.context S x).clauses (CleanDecoderPairLaw.context S x).designated + (CleanDecoderPairLaw.context S x).clean (CleanDecoderPairLaw.context S x).visible + (CleanDecoderPairLaw.context S x).projected upper (lower S) S.cut + (CleanDecoderContext.lowerHeight upper d) S.outside rows repeats + (CleanDecoderPairLaw.context S x).rightTape W (CleanDecoderPairLaw.rightOwn S x)) + (rightInput S W a x).knownBuckets := by + let suffix := CleanRightDecoder.suffix upper (lower S) S.cut + (CleanDecoderContext.lowerHeight upper d) + have hp : h + 1 < Nodes.height upper := + CleanRightDecoder.suffix_proper upper (lower S) S.cut (CleanDecoderContext.lowerHeight upper d) + have hzero := (WholeCutZero.grouped_iff rows repeats (CleanDecoderRate.path S) + (CleanNativeReplay.rightSlots S x) (CleanDecoderPairLaw.context S x).clean + (CleanNativeReplay.rightTape S x)).mp (CleanNativeReplay.right_grouped_zero S cube hcube x hx) + have h := replayKnown_heq _ _ (CleanNativeReplay.rightSlots_eq S x) upper suffix hp + (CleanDecoderPairLaw.context S x).clean W _ _ (CleanNativeReplay.rightReplay_heq S x) + have he := WholeCutSubtree.knownBucketsAtNode_erase rows repeats + (CleanNativeReplay.rightSlots S x) upper suffix hp (CleanDecoderPairLaw.context S x).clean + W (CleanNativeReplay.rightTape S x) hzero + have ho := WholeCutSubtree.knownBuckets_eq_original rows repeats (Nodes.path upper) suffix hp + (CleanNativeReplay.rightSlots S x) W (CleanNativeReplay.rightTape S x) + exact h.trans ((heq_of_eq he).trans (heq_of_eq ho)) + +theorem rightInput_heq (x : CleanDecoderRate.Sample S) + (hx : (CleanDecoderRate.rawLaw S cube hcube).weight x ≠ 0) : + HEq (CleanRightDecoder.input + (CleanDecoderPairLaw.context S x).clauses (CleanDecoderPairLaw.context S x).designated + (CleanDecoderPairLaw.context S x).clean (CleanDecoderPairLaw.context S x).visible + (CleanDecoderPairLaw.context S x).projected upper (lower S) S.cut + (CleanDecoderContext.lowerHeight upper d) S.outside rows repeats + (CleanDecoderPairLaw.context S x).rightTape W a (CleanDecoderPairLaw.rightOwn S x)) + (rightInput S W a x) := + inputOfArrays_heq _ _ (CleanNativeReplay.rightSlots_eq S x) upper (lower S) W a + _ _ (rightKnownBuckets_heq S W a cube hcube x hx) + _ _ (CleanNativeReplay.rightArrays_heq S cube hcube x hx) + +theorem rightKernel_heq (x : CleanDecoderRate.Sample S) + (hx : (CleanDecoderRate.rawLaw S cube hcube).weight x ≠ 0) : + HEq (CleanDecoderSeedLaw.rightKernel (CleanDecoderPairLaw.context S x) σ W a threshold + (CleanDecoderPairLaw.rightOwn S x)) (rightLaw S σ W a threshold x) := + rightLaw_heq _ _ (CleanNativeReplay.rightSlots_eq S x) upper (lower S) W a S.cut σ + _ _ (rightInput_heq S W a cube hcube x hx) threshold + +theorem pairKernel_heq (x : CleanDecoderRate.Sample S) + (hx : (CleanDecoderRate.rawLaw S cube hcube).weight x ≠ 0) : + HEq (CleanDecoderPairLaw.pairKernel S σ (useful S F κ) r ρ A W a threshold x) + (pairKernel S F κ σ r ρ A W a threshold x) := + product_heq _ _ _ _ (CleanNativeReplay.leftSlots_eq S x) + (CleanNativeReplay.rightSlots_eq S x) upper _ _ _ _ + (leftKernel_heq S F κ σ r ρ A cube hcube x hx) + (rightKernel_heq S σ W a threshold cube hcube x hx) + +def physicalAnswerEquiv (x : CleanDecoderRate.Sample S) : + CleanDecoderPairLaw.Pair S x ≃ + Answers (CleanNativeReplay.leftSlots S x) (CleanNativeReplay.rightSlots S x) upper := + answerEquiv _ _ _ _ (CleanNativeReplay.leftSlots_eq S x) + (CleanNativeReplay.rightSlots_eq S x) upper + +theorem pairKernel_pushforward (x : CleanDecoderRate.Sample S) + (hx : (CleanDecoderRate.rawLaw S cube hcube).weight x ≠ 0) : + (CleanDecoderPairLaw.pairKernel S σ (useful S F κ) r ρ A W a threshold x).pushforward + (physicalAnswerEquiv S x) = pairKernel S F κ σ r ρ A W a threshold x := + pushforward_answerEquiv _ _ _ _ (CleanNativeReplay.leftSlots_eq S x) + (CleanNativeReplay.rightSlots_eq S x) upper _ _ + (pairKernel_heq S F κ σ r ρ A W a threshold cube hcube x hx) + +theorem probability_pairKernel (x : CleanDecoderRate.Sample S) + (hx : (CleanDecoderRate.rawLaw S cube hcube).weight x ≠ 0) + (event : Answers (CleanNativeReplay.leftSlots S x) (CleanNativeReplay.rightSlots S x) upper → Bool) : + (pairKernel S F κ σ r ρ A W a threshold x).probability event = + (CleanDecoderPairLaw.pairKernel S σ (useful S F κ) r ρ A W a threshold x).probability + (fun answer => event (physicalAnswerEquiv S x answer)) := by + rw [← pairKernel_pushforward S F κ σ r ρ A W a threshold cube hcube x hx] + exact FiniteDistribution.probability_pushforward _ _ _ + +abbrev physicalProjection (x : CleanDecoderRate.Sample S) := + CleanPhysicalCanonicalQuery.projection rows repeats (CleanDecoderRate.path S) + S.outside S.clauses S.designated x + +theorem projection_heq (x : CleanDecoderRate.Sample S) (leaf : Slots branch n) (k : Fin t) : + HEq (CleanDecoderOddLists.fullProjection (CleanDecoderPairLaw.context S x) + (CleanDecoderPairLaw.occurrences S x) leaf k) (physicalProjection S x leaf k) := + CleanRecordProjection.decoderProjection_heq rows S.clauses S.designated repeats upper d S.cut + S.outside S.placeholder (CleanDecoderRate.observations S x) S.exterior x + (CleanRecordDecoderInput.event_observe rows repeats upper d S.cut S.clauses S.designated x) leaf k + +theorem meeting_probability_eq (x : CleanDecoderRate.Sample S) + (hx : (CleanDecoderRate.rawLaw S cube hcube).weight x ≠ 0) : + (pairKernel S F κ σ r ρ A W a threshold x).probability + (fun answer => decide (answer.2 = DecoderSourcePullback.upperTarget + (physicalProjection S x) upper answer.1)) = + (CleanDecoderPairLaw.pairKernel S σ (useful S F κ) r ρ A W a threshold x).probability + (fun answer => decide (answer.2 = DecoderSourcePullback.upperTarget + (CleanDecoderOddLists.fullProjection (CleanDecoderPairLaw.context S x) + (CleanDecoderPairLaw.occurrences S x)) upper answer.1)) := by + rw [probability_pairKernel S F κ σ r ρ A W a threshold cube hcube x hx] + congr 1 + funext answer + exact meeting_answerEquiv _ _ _ _ (CleanNativeReplay.leftSlots_eq S x) + (CleanNativeReplay.rightSlots_eq S x) upper _ _ (projection_heq S x) answer + +end +end PerfectCompleteness.CleanPhysicalDecoderLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/CleanRecordProjection.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/CleanRecordProjection.lean new file mode 100644 index 0000000000000000000000000000000000000000..135adc3c77f10a4697f080e1d8674c3338a89aa7 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/CleanRecordProjection.lean @@ -0,0 +1,157 @@ +import OAI.Computability.PerfectCompleteness.Decoding.CleanDecoderOddLists +import OAI.Computability.PerfectCompleteness.Decoding.CleanEndpointProjection +import OAI.Computability.PerfectCompleteness.Machines.CleanRecordDecoderInput +import OAI.Computability.PerfectCompleteness.Repetition.CleanRecordObservation + +namespace OAI + +section + +namespace PerfectCompleteness.CleanRecordProjection + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces + +variable {branch : Nat → Nat} {h t v m : Nat} [NeZero m] + {C : Type*} [Fintype C] + (rows : Nat → Nat) (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch h) → Slots branch h) + +omit [NeZero m] in +private theorem sourceProjection_congr (b b' : Bool) + (e e' : SourceOddLists.Occurrences m t) (hb : b = b') (he : e = e') (k : Fin t) : + HEq (CleanEndpointProjection.sourceProjection clauses b e k) + (CleanEndpointProjection.sourceProjection clauses b' e' k) := by + cases hb + cases he + rfl + +omit [NeZero m] in +private theorem sourceProjection_tree (i : Fin (branch h)) + (source : SourceChildKernel.Source (m := m) (t := t) designated i) + (b : Bool) (leaf : Slots branch h) (k : Fin t) : + HEq (CleanEndpointProjection.sourceProjection clauses b + (SourceChildKernel.tree designated i source leaf) k) + (SourceChildKernel.projection clauses designated i source b leaf k) := by + cases b <;> rfl + +omit [NeZero m] in +theorem insideProjection_heq + (record : CleanRecordObservation.Record (C := C) (t := t) rows clauses designated) + (x : CleanRecordObservation.Sample (C := C) (t := t) rows clauses designated) + (hevent : CleanRecordChildBlocks.event rows clauses designated record x = true) + (s : Slots branch (h + 1)) (k : Fin t) : + HEq + (CleanEndpointProjection.insideProjection clauses designated + (CleanRecordChildBlocks.clean rows clauses designated record) + (CleanRecordChildBlocks.visible rows clauses designated record) + (CleanRecordChildBlocks.projected rows clauses designated record) + (CleanSourceRecord.clean_projected designated + (SourceChildKernel.Factors (C := C) (t := t) rows clauses designated) record) + (fun i => (x i.val).1) s k) + (SourceChildKernel.parentProjection rows clauses designated + (fun i => ((x i).1, (x i).2.1)) (fun i => (x i).2.2) s k) := by + have hp := congrFun (CleanSourceRecord.projected_eq_raw designated + (D := SourceChildKernel.D (C := C) (t := t) rows clauses designated) + (SourceChildKernel.Factors (C := C) (t := t) rows clauses designated) + (SourceChildKernel.zero (C := C) (t := t) rows clauses designated) + record x hevent) s.1 + have hflag : CleanSourceRecord.rawProjected designated + (D := SourceChildKernel.D (C := C) (t := t) rows clauses designated) + (SourceChildKernel.Factors (C := C) (t := t) rows clauses designated) + s.1 (x s.1).2.2 = + SourceChildKernel.rawProjected rows clauses designated s.1 (x s.1).2.2 := by + cases (x s.1).2.2 <;> rfl + by_cases hs : CleanRecordChildBlocks.clean rows clauses designated record s.1 ∧ + s.2 = designated s.1 + · simp only [CleanEndpointProjection.insideProjection, dite_eq_left hs] + apply (CutProjectionAssembly.castProjection_heq _ _ _).trans + have he : (x s.1).1 = SourceChildKernel.tree designated s.1 + ((x s.1).1, (x s.1).2.1) s.2 := by + rw [hs.2] + exact (CleanSourceRecord.assemble_designated designated s.1 _ _).symm + exact (sourceProjection_congr clauses _ _ _ _ (hp.trans hflag) he k).trans + (sourceProjection_tree clauses designated s.1 ((x s.1).1, (x s.1).2.1) + (SourceChildKernel.rawProjected rows clauses designated s.1 (x s.1).2.2) s.2 k) + · simp only [CleanEndpointProjection.insideProjection, dite_eq_right hs] + apply (CutProjectionAssembly.castProjection_heq _ _ _).trans + have hv := CleanSourceRecord.visible_eq_reveal designated + (D := SourceChildKernel.D (C := C) (t := t) rows clauses designated) + (SourceChildKernel.Factors (C := C) (t := t) rows clauses designated) + (SourceChildKernel.zero (C := C) (t := t) rows clauses designated) + record x hevent + have he : CleanRecordChildBlocks.visible rows clauses designated record s.1 ⟨s.2, hs⟩ = + SourceChildKernel.tree designated s.1 ((x s.1).1, (x s.1).2.1) s.2 := + congrArg (fun visible => visible s.1 ⟨s.2, hs⟩) hv + exact (sourceProjection_congr clauses _ _ _ _ (hp.trans hflag) he k).trans + (sourceProjection_tree clauses designated s.1 ((x s.1).1, (x s.1).2.1) + (SourceChildKernel.rawProjected rows clauses designated s.1 (x s.1).2.2) s.2 k) + +private theorem fillProjection_congr {n : Nat} (p : Path branch n (h + 1)) + (outside : Slots branch n → Fin t → MixedSupport.Slot) + {left left' right right' : Slots branch (h + 1) → Fin t → MixedSupport.Slot} + (hl : left = left') (hr : right = right') + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (q' : ∀ s k, MixedSupport.Projection (left' s k) (right' s k)) + (hq : ∀ s k, HEq (q s k) (q' s k)) (s : Slots branch n) (k : Fin t) : + HEq (CutProjectionAssembly.fillProjection p outside left right q s k) + (CutProjectionAssembly.fillProjection p outside left' right' q' s k) := by + cases hl + cases hr + have hqq : q = q' := funext (fun s => funext (fun k => eq_of_heq (hq s k))) + cases hqq + rfl + +omit [NeZero m] in +theorem fillProjection_heq {n : Nat} (p : Path branch n (h + 1)) + (outside : Slots branch n → Fin t → MixedSupport.Slot) + (record : CleanRecordObservation.Record (C := C) (t := t) rows clauses designated) + (x : CleanRecordObservation.Sample (C := C) (t := t) rows clauses designated) + (hevent : CleanRecordChildBlocks.event rows clauses designated record x = true) + (s : Slots branch n) (k : Fin t) : + HEq + (CutProjectionAssembly.fillProjection p outside _ _ + (CleanEndpointProjection.insideProjection clauses designated + (CleanRecordChildBlocks.clean rows clauses designated record) + (CleanRecordChildBlocks.visible rows clauses designated record) + (CleanRecordChildBlocks.projected rows clauses designated record) + (CleanSourceRecord.clean_projected designated + (SourceChildKernel.Factors (C := C) (t := t) rows clauses designated) record) + (fun i => (x i.val).1)) s k) + (CutProjectionAssembly.fillProjection p outside _ _ + (SourceChildKernel.parentProjection rows clauses designated + (fun i => ((x i).1, (x i).2.1)) (fun i => (x i).2.2)) s k) := + fillProjection_congr p outside + (CleanRecordObservation.leftInside_eq rows clauses designated record x hevent) + (CleanRecordObservation.rightInside_eq rows clauses designated record x hevent) _ _ + (insideProjection_heq rows clauses designated record x hevent) s k + +theorem decoderProjection_heq {root : Nat} (repeats : Nat → Nat) + (upper : HierarchicalArrays.Nodes branch root) + (d : HierarchicalFrozenTables.LowerNodes upper (h + 1)) + (cut : OwnInputReference.Cut upper (HierarchicalLeftDecoder.LowerNode upper (h + 1) d)) + (outside : Slots branch root → Fin t → MixedSupport.Slot) + (placeholder : Slots branch (h + 1) → Fin t → MixedSupport.Slot) + (record : CleanRecordDecoderInput.Record (t := t) rows repeats upper d cut clauses designated) + (external : CleanRecordDecoderInput.Exterior rows repeats upper d cut outside placeholder) + (x : CleanRecordDecoderInput.Sample (t := t) rows repeats upper d cut clauses designated) + (hevent : CleanRecordChildBlocks.event rows clauses designated record x = true) + (s : Slots branch root) (k : Fin t) : + HEq (CleanDecoderOddLists.fullProjection + (CleanRecordDecoderInput.exposed rows repeats upper d cut outside placeholder + clauses designated record external) + (CleanRecordDecoderInput.sources rows repeats upper d cut clauses designated record x) s k) + (CutProjectionAssembly.fillProjection (CleanRecordDecoderInput.path upper d cut) outside _ _ + (SourceChildKernel.parentProjection rows clauses designated + (fun i => ((x i).1, (x i).2.1)) (fun i => (x i).2.2)) s k) := + fillProjection_heq rows clauses designated (CleanRecordDecoderInput.path upper d cut) + outside record x hevent s k + +end +end PerfectCompleteness.CleanRecordProjection + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/CollisionAveragingLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/CollisionAveragingLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..5c8d8243d6b04223ce40410034240b505cc9123d --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/CollisionAveragingLemmas.lean @@ -0,0 +1,418 @@ +import Mathlib.Tactic.Linarith +import OAI.Computability.PerfectCompleteness.Construction.HiddenChildMixture +import OAI.Computability.PerfectCompleteness.Decoding.TwoResponseCollisionLemmas +import OAI.Computability.PerfectCompleteness.Repetition.CleanConditioning +import OAI.Computability.PerfectCompleteness.Sampling.DensityVariation + +namespace OAI + + +namespace PerfectCompleteness.CollisionAveraging + +noncomputable section + +open scoped BigOperators +open UniqueGamesTheorem.Foundations.Games + +variable {B : Type*} [Fintype B] + +theorem mean_square_le (μ : FiniteDistribution B) (p : B → ℝ) : + μ.expectation p ^ 2 ≤ μ.expectation (fun b => p b ^ 2) := + UniqueGamesTheorem.Foundations.Information.weighted_sum_sq_le μ.weight p + ⟨μ.nonnegative, μ.normalized⟩ + +theorem average_square_bound (μ : FiniteDistribution B) (p collision : B → ℝ) + (hlocal : ∀ b, p b ^ 2 / 2 ≤ collision b) : + μ.expectation p ^ 2 / 2 ≤ μ.expectation collision := by + calc + _ ≤ μ.expectation (fun b => p b ^ 2) / 2 := + div_le_div_of_nonneg_right (mean_square_le μ p) (by norm_num) + _ = μ.expectation (fun b => p b ^ 2 / 2) := + (DensityVariation.expectation_div μ (fun b => p b ^ 2) 2).symm + _ ≤ μ.expectation collision := by + apply Finset.sum_le_sum + intro b _ + exact mul_le_mul_of_nonneg_left (hlocal b) (μ.nonnegative b) + +theorem eighth_square_bound (μ : FiniteDistribution B) (p collision : B → ℝ) + (hlocal : ∀ b, p b ^ 2 / 2 ≤ collision b) + (c : ℝ) (hc : 0 ≤ c) (hmass : c / 2 ≤ μ.expectation p) : + c ^ 2 / 8 ≤ μ.expectation collision := by + have h := average_square_bound μ p collision hlocal + have hprod : 0 ≤ (μ.expectation p - c / 2) * (μ.expectation p + c / 2) := + mul_nonneg (sub_nonneg.mpr hmass) (by linarith) + nlinarith + + +variable {Ω Y : B → Type*} [∀ b, Fintype (Ω b)] [∀ b, Fintype (Y b)] + +theorem average_collision (μ : FiniteDistribution B) + (ν : (b : B) → FiniteDistribution (Ω b)) + (f : (b : B) → Ω b → Option (Y b)) (good : (b : B) → Ω b → Bool) + (hcard : ∀ b, Nat.card {y : Y b // TwoResponseCollision.GoodResponse (f b) (good b) y} ≤ 2) : + μ.expectation (fun b => (ν b).probability (TwoResponseCollision.goodDefined (f b) (good b))) ^ 2 / 2 ≤ + μ.expectation (fun b => ((ν b).product (ν b)).probability (TwoResponseCollision.collision (f b))) := + average_square_bound μ _ _ (fun b => + TwoResponseCollision.collision_probability_ge (ν b) (f b) (good b) (hcard b)) + +theorem actual_eighth_square_bound (μ : FiniteDistribution B) + (ν : (b : B) → FiniteDistribution (Ω b)) + (f : (b : B) → Ω b → Option (Y b)) (good : (b : B) → Ω b → Bool) + (hcard : ∀ b, Nat.card {y : Y b // TwoResponseCollision.GoodResponse (f b) (good b) y} ≤ 2) + (c : ℝ) (hc : 0 ≤ c) + (hmass : c / 2 ≤ μ.expectation + (fun b => (ν b).probability (TwoResponseCollision.goodDefined (f b) (good b)))) : + c ^ 2 / 8 ≤ μ.expectation + (fun b => ((ν b).product (ν b)).probability (TwoResponseCollision.collision (f b))) := + eighth_square_bound μ _ _ (fun b => + TwoResponseCollision.collision_probability_ge (ν b) (f b) (good b) (hcard b)) c hc hmass + +end +end PerfectCompleteness.CollisionAveraging + + +namespace PerfectCompleteness.SparseProjection + +open scoped BigOperators +open UniqueGamesTheorem.Foundations.Games +open PerfectCompleteness SmallBias DensityVariation + +noncomputable section + +variable {I : Type*} [Fintype I] [DecidableEq I] + {Ω : I → Type*} [∀ i, Fintype (Ω i)] + +def localDensity (β : ℝ) (q : (i : I) → Ω i → ℝ) (i : I) (x : Ω i) : ℝ := + 1 - β + β * q i x + +omit [Fintype I] [DecidableEq I] in +theorem local_mean (P : (i : I) → FiniteDistribution (Ω i)) + (q : (i : I) → Ω i → ℝ) (mean : ∀ i, (P i).expectation (q i) = 1) + (β : ℝ) (i : I) : (P i).expectation (localDensity β q i) = 1 := by + calc + _ = (1 - β) * (P i).expectation (fun _ => 1) + β * (P i).expectation (q i) := by + simp only [FiniteDistribution.expectation, localDensity, Finset.mul_sum, + ← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro x _ + ring + _ = 1 := by rw [expectation_const, mean]; ring + +omit [Fintype I] [DecidableEq I] in +theorem local_second_moment (P : (i : I) → FiniteDistribution (Ω i)) + (q : (i : I) → Ω i → ℝ) (mean : ∀ i, (P i).expectation (q i) = 1) + (β : ℝ) (i : I) : + (P i).expectation (fun x => localDensity β q i x ^ 2) = + 1 + β ^ 2 * (P i).expectation (fun x => (q i x - 1) ^ 2) := by + calc + _ = (P i).expectation (fun _ => 1) + + (2 * β) * ((P i).expectation (q i) - (P i).expectation (fun _ => 1)) + + β ^ 2 * (P i).expectation (fun x => (q i x - 1) ^ 2) := by + simp only [FiniteDistribution.expectation, localDensity, Finset.mul_sum, + ← Finset.sum_sub_distrib, ← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro x _ + ring + _ = _ := by rw [expectation_const, mean]; ring + +def density (β : ℝ) (q : (i : I) → Ω i → ℝ) (x : (i : I) → Ω i) : ℝ := + ∏ i, localDensity β q i (x i) + +theorem density_mean (P : (i : I) → FiniteDistribution (Ω i)) + (q : (i : I) → Ω i → ℝ) (mean : ∀ i, (P i).expectation (q i) = 1) + (β : ℝ) : (FiniteProduct.law P).expectation (density β q) = 1 := by + change (FiniteProduct.law P).expectation (fun x => ∏ i, localDensity β q i (x i)) = 1 + rw [FiniteProduct.expectation_product] + simp only [local_mean P q mean, Finset.prod_const_one] + +theorem density_second_moment (P : (i : I) → FiniteDistribution (Ω i)) + (q : (i : I) → Ω i → ℝ) (mean : ∀ i, (P i).expectation (q i) = 1) + (β : ℝ) : + (FiniteProduct.law P).expectation (fun x => (density β q x - 1) ^ 2) = + (∏ i, (1 + β ^ 2 * (P i).expectation (fun x => (q i x - 1) ^ 2))) - 1 := by + have identity : (FiniteProduct.law P).expectation (fun x => (density β q x - 1) ^ 2) = + (FiniteProduct.law P).expectation (fun x => density β q x ^ 2) - + 2 * (FiniteProduct.law P).expectation (density β q) + 1 := by + calc + _ = (FiniteProduct.law P).expectation (fun x => density β q x ^ 2) - + 2 * (FiniteProduct.law P).expectation (density β q) + + (FiniteProduct.law P).expectation (fun _ => 1) := by + simp only [FiniteDistribution.expectation, Finset.mul_sum, + ← Finset.sum_sub_distrib, ← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro x _ + ring + _ = _ := by rw [expectation_const] + rw [identity, density_mean P q mean] + have square : (FiniteProduct.law P).expectation (fun x => density β q x ^ 2) = + ∏ i, (P i).expectation (fun x => localDensity β q i x ^ 2) := by + simp only [density, ← Finset.prod_pow] + exact FiniteProduct.expectation_product P (fun i x => localDensity β q i x ^ 2) + rw [square] + simp only [local_second_moment P q mean] + ring + +theorem density_second_moment_le (P : (i : I) → FiniteDistribution (Ω i)) + (q : (i : I) → Ω i → ℝ) (mean : ∀ i, (P i).expectation (q i) = 1) + (β v : ℝ) (bound : ∀ i, (P i).expectation (fun x => (q i x - 1) ^ 2) ≤ v) : + (FiniteProduct.law P).expectation (fun x => (density β q x - 1) ^ 2) ≤ + (1 + β ^ 2 * v) ^ Fintype.card I - 1 := by + rw [density_second_moment P q mean] + apply sub_le_sub_right + calc + _ ≤ ∏ _i : I, (1 + β ^ 2 * v) := by + apply Finset.prod_le_prod₀ + · intro i _ + have h : 0 ≤ (P i).expectation (fun x => (q i x - 1) ^ 2) := + Finset.sum_nonneg fun x _ => mul_nonneg ((P i).nonnegative x) (sq_nonneg _) + positivity + · intro i _ + exact add_le_add (le_refl 1) (mul_le_mul_of_nonneg_left (bound i) (sq_nonneg β)) + _ = _ := by simp + +def projectedLaw (P : (i : I) → FiniteDistribution (Ω i)) + (q : (i : I) → Ω i → ℝ) (nonnegative : ∀ i x, 0 ≤ q i x) + (mean : ∀ i, (P i).expectation (q i) = 1) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) : FiniteDistribution ((i : I) → Ω i) := + FiniteProduct.law (fun i => reweight (P i) (localDensity β q i) + (fun x => add_nonneg (sub_nonneg.mpr hβ') (mul_nonneg hβ (nonnegative i x))) + (local_mean P q mean β i)) + +theorem projected_weight (P : (i : I) → FiniteDistribution (Ω i)) + (q : (i : I) → Ω i → ℝ) (nonnegative : ∀ i x, 0 ≤ q i x) + (mean : ∀ i, (P i).expectation (q i) = 1) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) (x : (i : I) → Ω i) : + (projectedLaw P q nonnegative mean β hβ hβ').weight x = + (FiniteProduct.law P).weight x * density β q x := by + simp only [projectedLaw, FiniteProduct.law, reweight, Finset.prod_mul_distrib, density] + +theorem observed_variation {Γ : Type*} [Fintype Γ] + (P : (i : I) → FiniteDistribution (Ω i)) + (q : (i : I) → Ω i → ℝ) (nonnegative : ∀ i x, 0 ≤ q i x) + (mean : ∀ i, (P i).expectation (q i) = 1) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) + (v : ℝ) (bound : ∀ i, (P i).expectation (fun x => (q i x - 1) ^ 2) ≤ v) + (observe : ((i : I) → Ω i) → Γ) : + ((projectedLaw P q nonnegative mean β hβ hβ').pushforward observe).totalVariation + ((FiniteProduct.law P).pushforward observe) ≤ + Real.sqrt ((1 + β ^ 2 * v) ^ Fintype.card I - 1) / 2 := + observed_variation_le_sqrt (FiniteProduct.law P) _ (density β q) + (projected_weight P q nonnegative mean β hβ hβ') _ + (density_second_moment_le P q mean β v bound) observe + +end +end PerfectCompleteness.SparseProjection + + +namespace PerfectCompleteness.ProjectionPosterior + +open scoped BigOperators +open UniqueGamesTheorem.Foundations.Games +open PerfectCompleteness SmallBias DensityVariation SparseProjection CleanConditioning + +noncomputable section + +def bernoulli (p : ℝ) (hp : 0 ≤ p) (hp' : p ≤ 1) : FiniteDistribution Bool where + weight b := if b then p else 1 - p + nonnegative b := by cases b <;> simp [hp, sub_nonneg.mpr hp'] + normalized := by simp + +theorem bernoulli_true (p : ℝ) (hp : 0 ≤ p) (hp' : p ≤ 1) : + (bernoulli p hp hp').probability id = p := by + simp [FiniteDistribution.probability, bernoulli] + +variable {I : Type*} [Fintype I] [DecidableEq I] + {Ω : I → Type*} [∀ i, Fintype (Ω i)] + +def posterior (β : ℝ) (q : (i : I) → Ω i → ℝ) (i : I) (x : Ω i) : ℝ := + β * q i x / localDensity β q i x + +omit [Fintype I] [DecidableEq I] [∀ i, Fintype (Ω i)] in +theorem localDensity_positive (β : ℝ) (hβ : 0 ≤ β) (hβ' : β < 1) + (q : (i : I) → Ω i → ℝ) (nonnegative : ∀ i x, 0 ≤ q i x) (i : I) (x : Ω i) : + 0 < localDensity β q i x := + add_pos_of_pos_of_nonneg (sub_pos.mpr hβ') (mul_nonneg hβ (nonnegative i x)) + +omit [Fintype I] [DecidableEq I] [∀ i, Fintype (Ω i)] in +theorem posterior_nonnegative (β : ℝ) (hβ : 0 ≤ β) (hβ' : β < 1) + (q : (i : I) → Ω i → ℝ) (nonnegative : ∀ i x, 0 ≤ q i x) (i : I) (x : Ω i) : + 0 ≤ posterior β q i x := + div_nonneg (mul_nonneg hβ (nonnegative i x)) + (le_of_lt (localDensity_positive β hβ hβ' q nonnegative i x)) + +omit [Fintype I] [DecidableEq I] [∀ i, Fintype (Ω i)] in +theorem posterior_le_one (β : ℝ) (hβ : 0 ≤ β) (hβ' : β < 1) + (q : (i : I) → Ω i → ℝ) (nonnegative : ∀ i x, 0 ≤ q i x) (i : I) (x : Ω i) : + posterior β q i x ≤ 1 := by + apply (div_le_iff₀ (localDensity_positive β hβ hβ' q nonnegative i x)).mpr + unfold localDensity + linarith + +omit [Fintype I] [DecidableEq I] [∀ i, Fintype (Ω i)] in +theorem posterior_le (β : ℝ) (hβ : 0 ≤ β) (hβ' : β < 1) + (q : (i : I) → Ω i → ℝ) (nonnegative : ∀ i x, 0 ≤ q i x) + (L : ℝ) (hL : 0 ≤ L) (bound : ∀ i x, q i x ≤ L) (i : I) (x : Ω i) : + posterior β q i x ≤ β * L / (1 - β) := by + have hd := localDensity_positive β hβ hβ' q nonnegative i x + calc + _ ≤ β * L / localDensity β q i x := + div_le_div_of_nonneg_right (mul_le_mul_of_nonneg_left (bound i x) hβ) hd.le + _ ≤ _ := div_le_div_of_nonneg_left (mul_nonneg hβ hL) (sub_pos.mpr hβ') + (by unfold localDensity; linarith [mul_nonneg hβ (nonnegative i x)]) + +def posteriorMask (β : ℝ) (hβ : 0 ≤ β) (hβ' : β < 1) + (q : (i : I) → Ω i → ℝ) (nonnegative : ∀ i x, 0 ≤ q i x) + (x : (i : I) → Ω i) : FiniteDistribution (I → Bool) := + FiniteProduct.law fun i => bernoulli (posterior β q i (x i)) + (posterior_nonnegative β hβ hβ' q nonnegative i (x i)) + (posterior_le_one β hβ hβ' q nonnegative i (x i)) + +def forward (P : (i : I) → FiniteDistribution (Ω i)) + (q : (i : I) → Ω i → ℝ) (nonnegative : ∀ i x, 0 ≤ q i x) + (mean : ∀ i, (P i).expectation (q i) = 1) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β < 1) : + FiniteDistribution ((I → Bool) × ((i : I) → Ω i)) := + kernelJoint (FiniteProduct.law fun _ : I => bernoulli β hβ hβ'.le) + (fun mask => FiniteProduct.law fun i => + if mask i then reweight (P i) (q i) (nonnegative i) (mean i) else P i) + +def reverse (P : (i : I) → FiniteDistribution (Ω i)) + (q : (i : I) → Ω i → ℝ) (nonnegative : ∀ i x, 0 ≤ q i x) + (mean : ∀ i, (P i).expectation (q i) = 1) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β < 1) : + FiniteDistribution (((i : I) → Ω i) × (I → Bool)) := + kernelJoint (projectedLaw P q nonnegative mean β hβ hβ'.le) + (posteriorMask β hβ hβ' q nonnegative) + +theorem forward_reverse_weight (P : (i : I) → FiniteDistribution (Ω i)) + (q : (i : I) → Ω i → ℝ) (nonnegative : ∀ i x, 0 ≤ q i x) + (mean : ∀ i, (P i).expectation (q i) = 1) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β < 1) + (mask : I → Bool) (x : (i : I) → Ω i) : + (forward P q nonnegative mean β hβ hβ').weight (mask, x) = + (reverse P q nonnegative mean β hβ hβ').weight (x, mask) := by + change (∏ i, (bernoulli β hβ hβ'.le).weight (mask i)) * + (∏ i, (if mask i then reweight (P i) (q i) (nonnegative i) (mean i) else P i).weight (x i)) = + (∏ i, (P i).weight (x i) * localDensity β q i (x i)) * + (∏ i, (bernoulli (posterior β q i (x i)) _ _).weight (mask i)) + rw [← Finset.prod_mul_distrib, ← Finset.prod_mul_distrib] + apply Finset.prod_congr rfl + intro i _ + have hd := ne_of_gt (localDensity_positive β hβ hβ' q nonnegative i (x i)) + cases hi : mask i <;> simp only [bernoulli, Bool.false_eq_true, ite_false, + ite_true, reweight, posterior] + · field_simp + unfold localDensity + ring + · field_simp + +theorem probability_reverse (P : (i : I) → FiniteDistribution (Ω i)) + (q : (i : I) → Ω i → ℝ) (nonnegative : ∀ i x, 0 ≤ q i x) + (mean : ∀ i, (P i).expectation (q i) = 1) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β < 1) + (event : ((i : I) → Ω i) → (I → Bool) → Bool) : + (forward P q nonnegative mean β hβ hβ').probability (fun z => event z.2 z.1) = + (reverse P q nonnegative mean β hβ hβ').probability (fun z => event z.1 z.2) := by + simp only [FiniteDistribution.probability, Fintype.sum_prod_type, + forward_reverse_weight P q nonnegative mean β hβ hβ'] + exact Finset.sum_comm + +end +end PerfectCompleteness.ProjectionPosterior + + +namespace PerfectCompleteness.AdaptiveProjection + +open scoped BigOperators +open UniqueGamesTheorem.Foundations.Games +open PerfectCompleteness SmallBias ProjectionPosterior CleanConditioning + +noncomputable section + +variable {I : Type*} [Fintype I] [DecidableEq I] + +theorem probability_selected_le (μ : FiniteDistribution (I → Bool)) (S : Finset I) + (t : ℝ) (bound : ∀ i, μ.probability (fun mask => mask i) ≤ t) : + μ.probability (fun mask => decide (∃ i ∈ S, mask i = true)) ≤ S.card * t := by + classical + have indicator (mask : I → Bool) : + (if ∃ i ∈ S, mask i = true then (1 : ℝ) else 0) ≤ + ∑ i ∈ S, if mask i then (1 : ℝ) else 0 := by + by_cases h : ∃ i ∈ S, mask i = true + · obtain ⟨i, hi, hm⟩ := h + rw [ite_eq_left ⟨i, hi, hm⟩] + calc + _ = (if mask i then (1 : ℝ) else 0) := by rw [hm]; rfl + _ ≤ _ := Finset.single_le_sum (s := S) (a := i) + (f := fun j : I => if mask j then (1 : ℝ) else 0) + (fun j _ => by split <;> norm_num) hi + · rw [ite_eq_right h] + exact Finset.sum_nonneg fun i _ => by split <;> norm_num + calc + _ = μ.expectation (fun mask => if ∃ i ∈ S, mask i = true then 1 else 0) := by + simp [FiniteDistribution.probability, FiniteDistribution.expectation, mul_ite] + _ ≤ μ.expectation (fun mask => ∑ i ∈ S, if mask i then (1 : ℝ) else 0) := + expectation_mono μ indicator + _ = ∑ i ∈ S, μ.probability (fun mask => mask i) := by + simp only [FiniteDistribution.expectation, FiniteDistribution.probability, + Finset.mul_sum, mul_ite, mul_one, mul_zero] + exact Finset.sum_comm + _ ≤ ∑ _i ∈ S, t := Finset.sum_le_sum fun i _ => bound i + _ = _ := by simp + +variable {Ω : I → Type*} [∀ i, Fintype (Ω i)] + +omit [∀ i, Fintype (Ω i)] in +theorem posteriorMask_marginal (β : ℝ) (hβ : 0 ≤ β) (hβ' : β < 1) + (q : (i : I) → Ω i → ℝ) (nonnegative : ∀ i x, 0 ≤ q i x) + (x : (i : I) → Ω i) (i : I) : + (posteriorMask β hβ hβ' q nonnegative x).probability (fun mask => mask i) = + posterior β q i (x i) := by + calc + _ = (posteriorMask β hβ hβ' q nonnegative x).expectation + (fun mask => if mask i then 1 else 0) := by + simp [FiniteDistribution.probability, FiniteDistribution.expectation, mul_ite] + _ = (bernoulli (posterior β q i (x i)) _ _).expectation + (fun b => if b then 1 else 0) := + FiniteProduct.expectation_eval + (fun j : I => bernoulli (posterior β q j (x j)) + (posterior_nonnegative β hβ hβ' q nonnegative j (x j)) + (posterior_le_one β hβ hβ' q nonnegative j (x j))) + i (fun b : Bool => if b then 1 else 0) + _ = _ := by simp [FiniteDistribution.expectation, ProjectionPosterior.bernoulli] + +theorem adaptive_selection (P : (i : I) → FiniteDistribution (Ω i)) + (q : (i : I) → Ω i → ℝ) (nonnegative : ∀ i x, 0 ≤ q i x) + (mean : ∀ i, (P i).expectation (q i) = 1) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β < 1) + (L : ℝ) (hL : 0 ≤ L) (bound : ∀ i x, q i x ≤ L) + (select : ((i : I) → Ω i) → Finset I) (m : ℕ) + (size : ∀ x, (select x).card ≤ m) : + (forward P q nonnegative mean β hβ hβ').probability + (fun z => decide (∃ i ∈ select z.2, z.1 i = true)) ≤ + m * (β * L / (1 - β)) := by + classical + rw [probability_reverse P q nonnegative mean β hβ hβ' + (fun x mask => decide (∃ i ∈ select x, mask i = true))] + unfold reverse + rw [probability_kernelJoint] + have hnonneg : 0 ≤ β * L / (1 - β) := + div_nonneg (mul_nonneg hβ hL) (le_of_lt (sub_pos.mpr hβ')) + calc + _ ≤ ∑ x, (SparseProjection.projectedLaw P q nonnegative mean β hβ hβ'.le).weight x * + (m * (β * L / (1 - β))) := by + apply Finset.sum_le_sum + intro x _ + apply mul_le_mul_of_nonneg_left _ (FiniteDistribution.nonnegative _ x) + calc + _ ≤ (select x).card * (β * L / (1 - β)) := + probability_selected_le _ (select x) _ (fun i => by + rw [posteriorMask_marginal] + exact posterior_le β hβ hβ' q nonnegative L hL bound i (x i)) + _ ≤ _ := mul_le_mul_of_nonneg_right (by exact_mod_cast size x) hnonneg + _ = _ := by rw [← Finset.sum_mul, FiniteDistribution.normalized, one_mul] + +end +end PerfectCompleteness.AdaptiveProjection + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/CutGroupedProjectionLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/CutGroupedProjectionLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..6354bbac7a4c67420e76850fd8df8badf660a309 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/CutGroupedProjectionLemmas.lean @@ -0,0 +1,526 @@ +import OAI.Computability.PerfectCompleteness.Decoding.ChildAssemblyProjection +import OAI.Computability.PerfectCompleteness.Decoding.CutProjectionGeometry +import OAI.Computability.PerfectCompleteness.Foundations.OriginalTerminalSplitLemmas +import OAI.Computability.PerfectCompleteness.Sampling.CutSamplerReplayGroupingTransport + +namespace OAI + +section + +namespace PerfectCompleteness.CutGroupedProjection + +open PointwiseSpaces RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open RecursiveSampler TerminalCalls +open scoped BigOperators Classical + +abbrev F2 := ZMod 2 + +noncomputable section + +variable {branch : Nat → Nat} {n m t : Nat} + +def cutProjection (p : Path branch n (m + 1)) + {left right : Slots branch n → Fin t → MixedSupport.Slot} + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) : + ∀ s k, MixedSupport.Projection + (WholeCutGrouping.cutSlots p left s k) (WholeCutGrouping.cutSlots p right s k) := + fun s k => q (p.slotEmbedding s) k + +def terminalPullback (repeats : Nat → Nat) (p : Path branch n (m + 1)) + {left right : Slots branch n → Fin t → MixedSupport.Slot} + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (terminal : CutTerminalSplit.TerminalTape F2 repeats p (LeafDomain right)) : + CutTerminalSplit.TerminalTape F2 repeats p (LeafDomain left) := + fun call child => ChildBlockProjection.squarePullback + (ChildAssemblyProjection.childProjection (cutProjection p q) child) (terminal call child) + +def factorPullback (repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n (m + 1)) → + (left right : Slots branch n → Fin t → MixedSupport.Slot) → + (∀ s k, MixedSupport.Projection (left s k) (right s k)) → + (j : DrawIndex repeats p) → + CutSamplerRefinement.RefinedSpace F2 repeats p (LeafDomain right) j → + CutSamplerRefinement.RefinedSpace F2 repeats p (LeafDomain left) j + | _ + 1, _, .refl _, _, _, q, _, x => + fun child => ChildBlockProjection.squarePullback + (ChildAssemblyProjection.childProjection q child) (x child) + | _ + 1, _, .step i p, left, right, q, j, x => + match j with + | Sum.inl j => + ChildBlockProjection.squarePullback (ChildAssemblyProjection.childProjection q j.val) x + | Sum.inr j => + factorPullback repeats p (childSlots left i) (childSlots right i) + (ChildAssemblyProjection.childProjection q i) j.2 x + +def tapePullback (repeats : Nat → Nat) (p : Path branch n (m + 1)) + (left right : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (tape : CutSamplerRefinement.Tape F2 repeats p (LeafDomain right)) : + CutSamplerRefinement.Tape F2 repeats p (LeafDomain left) := + fun j => factorPullback repeats p left right q j (tape j) + +theorem evaluate_tapePullback (repeats : Nat → Nat) (p : Path branch n (m + 1)) : + ∀ (left right : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (tape : CutSamplerRefinement.Tape F2 repeats p (LeafDomain right)) (x : Domain left), + (CutSamplerRefinement.evaluate F2 repeats p (LeafDomain left) + (tapePullback repeats p left right q tape)).val x = + (CutSamplerRefinement.evaluate F2 repeats p (LeafDomain right) tape).val + (sourceProjection q x) := by + induction n generalizing m with + | zero => + have h := p.height_le + omega + | succ n ih => + cases p with + | refl => + intro left right q tape x + exact congrArg (fun f : H left => f.val x) + (ChildAssemblyProjection.recursiveSum_pullback q (tape ())) + | step i p => + intro left right q tape x + simp only [CutSamplerLocality.evaluate_step, RecursiveSampler.combine, + RecursiveSampler.combineFunction, Finset.sum_apply, Pi.add_apply, Pi.mul_apply, + PointwiseSpaces.pullback_apply] + change + (∑ j : OffPath i, + (ChildBlockProjection.squarePullback (ChildAssemblyProjection.childProjection q j.val) + (tape (.inl j))).val (restrictChild left j.val x)) + + (∑ h : Fin (repeats (n + 1)), + (CutSamplerRefinement.evaluate F2 repeats p (LeafDomain (childSlots left i)) + (tapePullback repeats p (childSlots left i) (childSlots right i) + (ChildAssemblyProjection.childProjection q i) + (CutSamplerLocality.subTape F2 repeats i p (LeafDomain right) tape h false))).val + (restrictChild left i x) * + (CutSamplerRefinement.evaluate F2 repeats p (LeafDomain (childSlots left i)) + (tapePullback repeats p (childSlots left i) (childSlots right i) + (ChildAssemblyProjection.childProjection q i) + (CutSamplerLocality.subTape F2 repeats i p (LeafDomain right) tape h true))).val + (restrictChild left i x)) = + (∑ j : OffPath i, (tape (.inl j)).val (restrictChild right j.val (sourceProjection q x))) + + (∑ h : Fin (repeats (n + 1)), + (CutSamplerRefinement.evaluate F2 repeats p (LeafDomain (childSlots right i)) + (CutSamplerLocality.subTape F2 repeats i p (LeafDomain right) tape h false)).val + (restrictChild right i (sourceProjection q x)) * + (CutSamplerRefinement.evaluate F2 repeats p (LeafDomain (childSlots right i)) + (CutSamplerLocality.subTape F2 repeats i p (LeafDomain right) tape h true)).val + (restrictChild right i (sourceProjection q x))) + apply congrArg₂ (fun a b : F2 => a + b) + · exact Finset.sum_congr rfl (fun _ _ => rfl) + · apply Finset.sum_congr rfl + intro h _ + apply congrArg₂ (fun a b : F2 => a * b) + · exact ih p (childSlots left i) (childSlots right i) + (ChildAssemblyProjection.childProjection q i) + (CutSamplerLocality.subTape F2 repeats i p (LeafDomain right) tape h false) + (restrictChild left i x) + · exact ih p (childSlots left i) (childSlots right i) + (ChildAssemblyProjection.childProjection q i) + (CutSamplerLocality.subTape F2 repeats i p (LeafDomain right) tape h true) + (restrictChild left i x) + +theorem terminalFactor_pullback (repeats : Nat → Nat) (p : Path branch n (m + 1)) : + ∀ (left right : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (call : TerminalIndex repeats p) + (x : CutSamplerRefinement.RefinedSpace F2 repeats p (LeafDomain right) + (drawIndex repeats p call)), + CutTerminalSplit.terminalFactorEquiv F2 repeats p (LeafDomain left) call + (factorPullback repeats p left right q (drawIndex repeats p call) x) = + fun child => ChildBlockProjection.squarePullback + (ChildAssemblyProjection.childProjection (cutProjection p q) child) + (CutTerminalSplit.terminalFactorEquiv F2 repeats p (LeafDomain right) call x child) := by + induction n generalizing m with + | zero => + have h := p.height_le + omega + | succ n ih => + cases p with + | refl => + intro left right q call x + cases call + rfl + | step i p => + intro left right q call x + exact ih p (childSlots left i) (childSlots right i) + (ChildAssemblyProjection.childProjection q i) call.2 x + +theorem exteriorFactor_pullback (repeats : Nat → Nat) (p : Path branch n (m + 1)) : + ∀ (left right : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (hs : ∀ s, WholeCutExteriorTransport.Outside p s → left s = right s) + (_hk : ∀ s (_hout : WholeCutExteriorTransport.Outside p s) k, + HEq (q s k) (MixedSupport.Projection.keep (left s k))) + (j : DrawIndex repeats p) (hj : ¬ IsTerminal repeats p j) + (x : CutSamplerRefinement.RefinedSpace F2 repeats p (LeafDomain right) j), + factorPullback repeats p left right q j x = + cast (WholeCutExteriorTransport.factor_eq repeats p right left + (fun s h => (hs s h).symm) j hj) x := by + induction n generalizing m with + | zero => + have h := p.height_le + omega + | succ n ih => + cases p with + | refl => + intro left right q hs hk j hj x + exact False.elim (hj True.intro) + | step i p => + intro left right q hs hk j hj x + cases j with + | inl j => + exact CutProjectionGeometry.squarePullback_eq_cast + (childSlots left j.val) (childSlots right j.val) + (ChildAssemblyProjection.childProjection q j.val) + (WholeCutExteriorTransport.ordinarySlots_eq i p left right hs j) + (fun s k => hk (j.val, s) (WholeCutExteriorTransport.outside_ordinary i p j s) k) x + | inr j => + exact ih p (childSlots left i) (childSlots right i) + (ChildAssemblyProjection.childProjection q i) + (fun s h => hs (i, s) (WholeCutExteriorTransport.outside_selected i p s h)) + (fun s h k => hk (i, s) (WholeCutExteriorTransport.outside_selected i p s h) k) + j.2 hj x + +theorem splitTape_tapePullback (repeats : Nat → Nat) (p : Path branch n (m + 1)) + (left right : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (hs : ∀ s, WholeCutExteriorTransport.Outside p s → left s = right s) + (hk : ∀ s (_hout : WholeCutExteriorTransport.Outside p s) k, + HEq (q s k) (MixedSupport.Projection.keep (left s k))) + (tape : CutSamplerRefinement.Tape F2 repeats p (LeafDomain right)) : + CutTerminalSplit.splitTape F2 repeats p (LeafDomain left) + (tapePullback repeats p left right q tape) = + (terminalPullback repeats p q (CutTerminalSplit.splitTape F2 repeats p (LeafDomain right) tape).1, + cast (WholeCutExteriorTransport.scalarExterior_eq repeats p right left + (fun s h => (hs s h).symm)) + (CutTerminalSplit.splitTape F2 repeats p (LeafDomain right) tape).2) := by + apply Prod.ext + · funext call + exact terminalFactor_pullback repeats p left right q call (tape (drawIndex repeats p call)) + · funext j + exact (exteriorFactor_pullback repeats p left right q hs hk j.val j.property (tape j.val)).trans + (CutSamplerReplayGroupingTransport.cast_pi_apply + (WholeCutExteriorTransport.scalarExterior_eq repeats p right left + (fun s h => (hs s h).symm)) + (fun j => WholeCutExteriorTransport.factor_eq repeats p right left + (fun s h => (hs s h).symm) j.val j.property) + (CutTerminalSplit.splitTape F2 repeats p (LeafDomain right) tape).2 j).symm + +theorem evaluate_rebuild (repeats : Nat → Nat) (p : Path branch n (m + 1)) + (left right : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (hs : ∀ s, WholeCutExteriorTransport.Outside p s → left s = right s) + (hk : ∀ s (_hout : WholeCutExteriorTransport.Outside p s) k, + HEq (q s k) (MixedSupport.Projection.keep (left s k))) + (terminal : CutTerminalSplit.TerminalTape F2 repeats p (LeafDomain right)) + (exterior : CutTerminalSplit.ExteriorTape F2 repeats p (LeafDomain right)) (x : Domain left) : + (CutSamplerRefinement.evaluate F2 repeats p (LeafDomain left) + ((CutTerminalSplit.splitTape F2 repeats p (LeafDomain left)).symm + (terminalPullback repeats p q terminal, + cast (WholeCutExteriorTransport.scalarExterior_eq repeats p right left + (fun s h => (hs s h).symm)) exterior))).val x = + (CutSamplerRefinement.evaluate F2 repeats p (LeafDomain right) + ((CutTerminalSplit.splitTape F2 repeats p (LeafDomain right)).symm (terminal, exterior))).val + (sourceProjection q x) := by + let tape := (CutTerminalSplit.splitTape F2 repeats p (LeafDomain right)).symm (terminal, exterior) + have hsplit : + CutTerminalSplit.splitTape F2 repeats p (LeafDomain left) + (tapePullback repeats p left right q tape) = + (terminalPullback repeats p q terminal, + cast (WholeCutExteriorTransport.scalarExterior_eq repeats p right left + (fun s h => (hs s h).symm)) exterior) := by + simpa only [tape, Equiv.apply_symm_apply] using + splitTape_tapePullback repeats p left right q hs hk tape + have hleft := congrArg (CutTerminalSplit.splitTape F2 repeats p (LeafDomain left)).symm hsplit + simp only [Equiv.symm_apply_apply] at hleft + rw [← hleft] + exact evaluate_tapePullback repeats p left right q tape x + +end +end PerfectCompleteness.CutGroupedProjection + +end + +section + +namespace PerfectCompleteness.OriginalScalarProjection + +open PointwiseSpaces RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open RecursiveSampler TerminalCalls +open scoped BigOperators Classical + +abbrev F2 := ZMod 2 + +noncomputable section + +variable {branch : Nat → Nat} {n m t : Nat} + +theorem factor_eq (repeats : Nat → Nat) (p : Path branch n m) : + ∀ (left right : Slots branch n → Fin t → MixedSupport.Slot), + (∀ s, WholeCutExteriorTransport.Outside p s → left s = right s) → + ∀ (j : DrawIndex repeats p), ¬ IsTerminal repeats p j → + DrawSpace F2 repeats p (LeafDomain left) j = + DrawSpace F2 repeats p (LeafDomain right) j := by + induction p with + | refl n => + intro left right hs j hj + exact False.elim (hj True.intro) + | @step n m i p ih => + intro left right hs j hj + cases j with + | inl j => + exact congrArg + (fun ss : Slots branch n → Fin t → MixedSupport.Slot => + (squareSpace (space F2 branch n (LeafDomain ss)) : Type)) + (WholeCutExteriorTransport.ordinarySlots_eq i p left right hs j) + | inr j => + exact ih (childSlots left i) (childSlots right i) + (fun s h => hs (i, s) (WholeCutExteriorTransport.outside_selected i p s h)) j.2 hj + +theorem scalarExterior_eq (repeats : Nat → Nat) (p : Path branch n (m + 1)) + (left right : Slots branch n → Fin t → MixedSupport.Slot) + (hs : ∀ s, WholeCutExteriorTransport.Outside p s → left s = right s) : + OriginalTerminalSplit.ExteriorTape F2 repeats p (LeafDomain left) = + OriginalTerminalSplit.ExteriorTape F2 repeats p (LeafDomain right) := + congrArg + (fun A : OriginalTerminalSplit.ExteriorIndex repeats p → Type => + (j : OriginalTerminalSplit.ExteriorIndex repeats p) → A j) + (funext (fun j => factor_eq repeats p left right hs j.val j.property)) + +def terminalPullback (repeats : Nat → Nat) (p : Path branch n (m + 1)) + {left right : Slots branch n → Fin t → MixedSupport.Slot} + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (values : OriginalScalarReconstruction.TerminalValues F2 repeats p (LeafDomain right)) : + OriginalScalarReconstruction.TerminalValues F2 repeats p (LeafDomain left) := + fun call => HPullback (CutGroupedProjection.cutProjection p q) (values call) + +def factorPullback (repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n (m + 1)) → + (left right : Slots branch n → Fin t → MixedSupport.Slot) → + (∀ s k, MixedSupport.Projection (left s k) (right s k)) → + (j : DrawIndex repeats p) → + RecursiveSampler.DrawSpace F2 repeats p (LeafDomain right) j → + RecursiveSampler.DrawSpace F2 repeats p (LeafDomain left) j + | _ + 1, _, .refl _, _, _, q, _, x => HPullback q x + | _ + 1, _, .step i p, left, right, q, j, x => + match j with + | Sum.inl j => + ChildBlockProjection.squarePullback (ChildAssemblyProjection.childProjection q j.val) x + | Sum.inr j => + factorPullback repeats p (childSlots left i) (childSlots right i) + (ChildAssemblyProjection.childProjection q i) j.2 x + +def tapePullback (repeats : Nat → Nat) (p : Path branch n (m + 1)) + (left right : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (tape : RecursiveSampler.Tape F2 repeats p (LeafDomain right)) : + RecursiveSampler.Tape F2 repeats p (LeafDomain left) := + fun j => factorPullback repeats p left right q j (tape j) + +theorem evaluate_tapePullback (repeats : Nat → Nat) (p : Path branch n (m + 1)) : + ∀ (left right : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (tape : RecursiveSampler.Tape F2 repeats p (LeafDomain right)) (x : Domain left), + (RecursiveSampler.evaluate F2 repeats p (LeafDomain left) + (tapePullback repeats p left right q tape)).val x = + (RecursiveSampler.evaluate F2 repeats p (LeafDomain right) tape).val + (sourceProjection q x) := by + induction n generalizing m with + | zero => + have h := p.height_le + omega + | succ n ih => + cases p with + | refl => + intro left right q tape x + rfl + | step i p => + intro left right q tape x + simp only [RecursiveSampler.evaluate_step, RecursiveSampler.combine, + RecursiveSampler.combineFunction, Finset.sum_apply, Pi.add_apply, Pi.mul_apply, + PointwiseSpaces.pullback_apply] + change + (∑ j : OffPath i, + (ChildBlockProjection.squarePullback (ChildAssemblyProjection.childProjection q j.val) + (tape (.inl j))).val (restrictChild left j.val x)) + + (∑ h : Fin (repeats (n + 1)), + (RecursiveSampler.evaluate F2 repeats p (LeafDomain (childSlots left i)) + (tapePullback repeats p (childSlots left i) (childSlots right i) + (ChildAssemblyProjection.childProjection q i) + (RecursiveSampler.subTape F2 repeats i p (LeafDomain right) tape h false))).val + (restrictChild left i x) * + (RecursiveSampler.evaluate F2 repeats p (LeafDomain (childSlots left i)) + (tapePullback repeats p (childSlots left i) (childSlots right i) + (ChildAssemblyProjection.childProjection q i) + (RecursiveSampler.subTape F2 repeats i p (LeafDomain right) tape h true))).val + (restrictChild left i x)) = + (∑ j : OffPath i, (tape (.inl j)).val (restrictChild right j.val (sourceProjection q x))) + + (∑ h : Fin (repeats (n + 1)), + (RecursiveSampler.evaluate F2 repeats p (LeafDomain (childSlots right i)) + (RecursiveSampler.subTape F2 repeats i p (LeafDomain right) tape h false)).val + (restrictChild right i (sourceProjection q x)) * + (RecursiveSampler.evaluate F2 repeats p (LeafDomain (childSlots right i)) + (RecursiveSampler.subTape F2 repeats i p (LeafDomain right) tape h true)).val + (restrictChild right i (sourceProjection q x))) + apply congrArg₂ (fun a b : F2 => a + b) + · exact Finset.sum_congr rfl (fun _ _ => rfl) + · apply Finset.sum_congr rfl + intro h _ + apply congrArg₂ (fun a b : F2 => a * b) + · exact ih p (childSlots left i) (childSlots right i) + (ChildAssemblyProjection.childProjection q i) + (RecursiveSampler.subTape F2 repeats i p (LeafDomain right) tape h false) + (restrictChild left i x) + · exact ih p (childSlots left i) (childSlots right i) + (ChildAssemblyProjection.childProjection q i) + (RecursiveSampler.subTape F2 repeats i p (LeafDomain right) tape h true) + (restrictChild left i x) + +theorem terminalFactor_pullback (repeats : Nat → Nat) (p : Path branch n (m + 1)) : + ∀ (left right : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (call : TerminalIndex repeats p) + (x : RecursiveSampler.DrawSpace F2 repeats p (LeafDomain right) + (drawIndex repeats p call)), + TerminalCalls.terminalSpaceEquiv F2 repeats p (LeafDomain left) call + (factorPullback repeats p left right q (drawIndex repeats p call) x) = + HPullback (CutGroupedProjection.cutProjection p q) + (TerminalCalls.terminalSpaceEquiv F2 repeats p (LeafDomain right) call x) := by + induction n generalizing m with + | zero => + have h := p.height_le + omega + | succ n ih => + cases p with + | refl => + intro left right q call x + cases call + rfl + | step i p => + intro left right q call x + exact ih p (childSlots left i) (childSlots right i) + (ChildAssemblyProjection.childProjection q i) call.2 x + +theorem exteriorFactor_pullback (repeats : Nat → Nat) (p : Path branch n (m + 1)) : + ∀ (left right : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (hs : ∀ s, WholeCutExteriorTransport.Outside p s → left s = right s) + (_hk : ∀ s (_hout : WholeCutExteriorTransport.Outside p s) k, + HEq (q s k) (MixedSupport.Projection.keep (left s k))) + (j : DrawIndex repeats p) (hj : ¬ IsTerminal repeats p j) + (x : RecursiveSampler.DrawSpace F2 repeats p (LeafDomain right) j), + factorPullback repeats p left right q j x = + cast (factor_eq repeats p right left + (fun s h => (hs s h).symm) j hj) x := by + induction n generalizing m with + | zero => + have h := p.height_le + omega + | succ n ih => + cases p with + | refl => + intro left right q hs hk j hj x + exact False.elim (hj True.intro) + | step i p => + intro left right q hs hk j hj x + cases j with + | inl j => + exact CutProjectionGeometry.squarePullback_eq_cast + (childSlots left j.val) (childSlots right j.val) + (ChildAssemblyProjection.childProjection q j.val) + (WholeCutExteriorTransport.ordinarySlots_eq i p left right hs j) + (fun s k => hk (j.val, s) (WholeCutExteriorTransport.outside_ordinary i p j s) k) x + | inr j => + exact ih p (childSlots left i) (childSlots right i) + (ChildAssemblyProjection.childProjection q i) + (fun s h => hs (i, s) (WholeCutExteriorTransport.outside_selected i p s h)) + (fun s h k => hk (i, s) (WholeCutExteriorTransport.outside_selected i p s h) k) + j.2 hj x + +theorem prefixSplit_tapePullback (repeats : Nat → Nat) (p : Path branch n (m + 1)) + (left right : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (hs : ∀ s, WholeCutExteriorTransport.Outside p s → left s = right s) + (hk : ∀ s (_hout : WholeCutExteriorTransport.Outside p s) k, + HEq (q s k) (MixedSupport.Projection.keep (left s k))) + (tape : RecursiveSampler.Tape F2 repeats p (LeafDomain right)) : + OriginalScalarReconstruction.prefixSplit F2 repeats p (LeafDomain left) + (tapePullback repeats p left right q tape) = + (terminalPullback repeats p q (OriginalScalarReconstruction.prefixSplit F2 repeats p (LeafDomain right) tape).1, + cast (scalarExterior_eq repeats p right left + (fun s h => (hs s h).symm)) + (OriginalScalarReconstruction.prefixSplit F2 repeats p (LeafDomain right) tape).2) := by + apply Prod.ext + · funext call + exact terminalFactor_pullback repeats p left right q call (tape (drawIndex repeats p call)) + · funext j + exact (exteriorFactor_pullback repeats p left right q hs hk j.val j.property (tape j.val)).trans + (CutSamplerReplayGroupingTransport.cast_pi_apply + (scalarExterior_eq repeats p right left + (fun s h => (hs s h).symm)) + (fun j => factor_eq repeats p right left + (fun s h => (hs s h).symm) j.val j.property) + (OriginalScalarReconstruction.prefixSplit F2 repeats p (LeafDomain right) tape).2 j).symm + +theorem reconstruct_pullback_apply (repeats : Nat → Nat) (p : Path branch n (m + 1)) + (left right : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (hs : ∀ s, WholeCutExteriorTransport.Outside p s → left s = right s) + (hk : ∀ s (_hout : WholeCutExteriorTransport.Outside p s) k, + HEq (q s k) (MixedSupport.Projection.keep (left s k))) + (values : OriginalScalarReconstruction.TerminalValues F2 repeats p (LeafDomain right)) + (exterior : OriginalTerminalSplit.ExteriorTape F2 repeats p (LeafDomain right)) + (x : Domain left) : + (OriginalScalarReconstruction.reconstruct F2 repeats p (LeafDomain left) + (fun call => HPullback (CutGroupedProjection.cutProjection p q) (values call)) + (cast (scalarExterior_eq repeats p right left + (fun s h => (hs s h).symm)) exterior)).val x = + (OriginalScalarReconstruction.reconstruct F2 repeats p (LeafDomain right) + values exterior).val (sourceProjection q x) := by + let tape := (OriginalScalarReconstruction.prefixSplit F2 repeats p (LeafDomain right)).symm + (values, exterior) + have hsplit : + OriginalScalarReconstruction.prefixSplit F2 repeats p (LeafDomain left) + (tapePullback repeats p left right q tape) = + (terminalPullback repeats p q values, + cast (scalarExterior_eq repeats p right left + (fun s h => (hs s h).symm)) exterior) := by + simpa only [tape, Equiv.apply_symm_apply] using + prefixSplit_tapePullback repeats p left right q hs hk tape + have hleft := congrArg + (OriginalScalarReconstruction.prefixSplit F2 repeats p (LeafDomain left)).symm hsplit + simp only [Equiv.symm_apply_apply] at hleft + unfold OriginalScalarReconstruction.reconstruct + change (RecursiveSampler.evaluate F2 repeats p (LeafDomain left) + ((OriginalScalarReconstruction.prefixSplit F2 repeats p (LeafDomain left)).symm + (terminalPullback repeats p q values, + cast (scalarExterior_eq repeats p right left + (fun s h => (hs s h).symm)) exterior))).val x = + (RecursiveSampler.evaluate F2 repeats p (LeafDomain right) tape).val (sourceProjection q x) + rw [← hleft] + exact evaluate_tapePullback repeats p left right q tape x + +theorem reconstruct_pullback (repeats : Nat → Nat) (p : Path branch n (m + 1)) + (left right : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (hs : ∀ s, WholeCutExteriorTransport.Outside p s → left s = right s) + (hk : ∀ s (_hout : WholeCutExteriorTransport.Outside p s) k, + HEq (q s k) (MixedSupport.Projection.keep (left s k))) + (values : OriginalScalarReconstruction.TerminalValues F2 repeats p (LeafDomain right)) + (exterior : OriginalTerminalSplit.ExteriorTape F2 repeats p (LeafDomain right)) : + OriginalScalarReconstruction.reconstruct F2 repeats p (LeafDomain left) + (fun call => HPullback (CutGroupedProjection.cutProjection p q) (values call)) + (cast (scalarExterior_eq repeats p right left + (fun s h => (hs s h).symm)) exterior) = + HPullback q (OriginalScalarReconstruction.reconstruct F2 repeats p (LeafDomain right) + values exterior) := by + apply Subtype.ext + funext x + exact reconstruct_pullback_apply repeats p left right q hs hk values exterior x + +end +end PerfectCompleteness.OriginalScalarProjection + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/CutProjectionAssembly.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/CutProjectionAssembly.lean new file mode 100644 index 0000000000000000000000000000000000000000..06092f5c3bc873a8d5d91b1a2e95522c5925f302 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/CutProjectionAssembly.lean @@ -0,0 +1,85 @@ +import OAI.Computability.PerfectCompleteness.Foundations.CutSlotAssembly + +namespace OAI + +section + +namespace PerfectCompleteness.CutProjectionAssembly + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces MixedSupport + +variable {branch : Nat → Nat} {n m t : Nat} + +def castProjection {a b c d : Slot} (hab : a = b) (hcd : c = d) + (q : Projection a c) : Projection b d := by + cases hab + cases hcd + exact q + +@[simp] theorem castProjection_heq {a b c d : Slot} (hab : a = b) (hcd : c = d) + (q : Projection a c) : HEq (castProjection hab hcd q) q := by + cases hab + cases hcd + rfl + +def fillProjection : {n m : Nat} → (p : Path branch n m) → + (outside : Slots branch n → Fin t → Slot) → + (left right : Slots branch m → Fin t → Slot) → + (∀ s k, Projection (left s k) (right s k)) → + ∀ s k, Projection (CutSlotAssembly.fill p outside left s k) + (CutSlotAssembly.fill p outside right s k) + | _, _, .refl _, _, _, _, q => q + | _, _, .step i p, outside, left, right, q => fun s k => + if hs : s.1 = i then + castProjection + (by simp only [CutSlotAssembly.fill, ite_eq_left hs]) + (by simp only [CutSlotAssembly.fill, ite_eq_left hs]) + (fillProjection p (fun j => outside (i, j)) left right q s.2 k) + else + castProjection + (by simp only [CutSlotAssembly.fill, ite_eq_right hs]) + (by simp only [CutSlotAssembly.fill, ite_eq_right hs]) + (Projection.keep (outside s k)) + +private theorem dite_heq_of_pos {α β : Type} {P : Prop} [Decidable P] + (f : P → α) (g : ¬ P → α) (b : β) (hP : P) + (h : HEq (f hP) b) : HEq (dite P f g) b := by + rw [dite_eq_left hP] + exact h + +theorem fillProjection_at_cut (p : Path branch n m) + (outside : Slots branch n → Fin t → Slot) + (left right : Slots branch m → Fin t → Slot) + (q : ∀ s k, Projection (left s k) (right s k)) + (s : Slots branch m) (k : Fin t) : + HEq (fillProjection p outside left right q (p.slotEmbedding s) k) (q s k) := by + revert outside left right q s k + induction p with + | refl _ => intros; rfl + | step i p ih => + intro outside left right q s k + refine @dite_heq_of_pos _ _ (i = i) _ _ _ (q s k) rfl ?_ + exact (castProjection_heq _ _ _).trans + (ih (fun j => outside (i, j)) left right q s k) + +theorem fillProjection_at_cut_cast (p : Path branch n m) + (outside : Slots branch n → Fin t → Slot) + (left right : Slots branch m → Fin t → Slot) + (q : ∀ s k, Projection (left s k) (right s k)) + (s : Slots branch m) (k : Fin t) : + castProjection + (congrFun (CutSlotAssembly.fill_at_cut p outside left s) k) + (congrFun (CutSlotAssembly.fill_at_cut p outside right s) k) + (fillProjection p outside left right q (p.slotEmbedding s) k) = q s k := by + apply eq_of_heq + exact (castProjection_heq _ _ _).trans (fillProjection_at_cut p outside left right q s k) + +end +end PerfectCompleteness.CutProjectionAssembly + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/CutProjectionGeometry.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/CutProjectionGeometry.lean new file mode 100644 index 0000000000000000000000000000000000000000..6208f3f86c6ff4db800d70eb299fadecd2090381 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/CutProjectionGeometry.lean @@ -0,0 +1,168 @@ +import OAI.Computability.PerfectCompleteness.Decoding.ChildAssemblyProjection +import OAI.Computability.PerfectCompleteness.Decoding.CutProjectionAssembly +import OAI.Computability.PerfectCompleteness.Foundations.CutSlotOutside + +namespace OAI + +section + +namespace PerfectCompleteness.CutProjectionGeometry + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays PointwiseSpaces +open scoped Classical + +noncomputable section + +variable {branch : Nat → Nat} {n t : Nat} + +theorem sourceProjection_eq_cast + (slots projected : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (hs : slots = projected) + (hk : ∀ s k, HEq (q s k) (MixedSupport.Projection.keep (slots s k))) + (x : Domain slots) : + sourceProjection q x = cast (congrArg Domain hs) x := by + cases hs + have hq : q = fun s k => MixedSupport.Projection.keep (slots s k) := by + funext s k + exact eq_of_heq (hk s k) + subst q + rfl + +theorem HPullback_eq_cast + (slots projected : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (hs : slots = projected) + (hk : ∀ s k, HEq (q s k) (MixedSupport.Projection.keep (slots s k))) + (f : H projected) : + HPullback q f = cast (congrArg + (fun ss : Slots branch n → Fin t → MixedSupport.Slot => (H ss : Type)) hs.symm) f := by + cases hs + have hq : q = fun s k => MixedSupport.Projection.keep (slots s k) := by + funext s k + exact eq_of_heq (hk s k) + subst q + apply Subtype.ext + rfl + +theorem squarePullback_eq_cast + (slots projected : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (hs : slots = projected) + (hk : ∀ s k, HEq (q s k) (MixedSupport.Projection.keep (slots s k))) + (f : squareSpace (H projected)) : + ChildBlockProjection.squarePullback q f = cast (congrArg + (fun ss : Slots branch n → Fin t → MixedSupport.Slot => + (squareSpace (H ss) : Type)) hs.symm) f := by + cases hs + have hq : q = fun s k => MixedSupport.Projection.keep (slots s k) := by + funext s k + exact eq_of_heq (hk s k) + subst q + apply Subtype.ext + rfl + +theorem arraysPullback_eq_cast (rows : Nat → Nat) + (slots projected : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (hs : slots = projected) + (hk : ∀ s k, HEq (q s k) (MixedSupport.Projection.keep (slots s k))) + (arrays : Arrays projected rows) : + ChildBlockProjection.arraysPullback rows q arrays = cast (congrArg + (fun ss : Slots branch n → Fin t → MixedSupport.Slot => Arrays ss rows) hs.symm) arrays := by + cases hs + have hq : q = fun s k => MixedSupport.Projection.keep (slots s k) := by + funext s k + exact eq_of_heq (hk s k) + subst q + funext node row + apply Subtype.ext + rfl + +theorem rawPullback_eq_cast (calls : Nat) (rows : Nat → Nat) + (slots projected : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (hs : slots = projected) + (hk : ∀ s k, HEq (q s k) (MixedSupport.Projection.keep (slots s k))) + (block : ChildBlockCardinality.Raw calls rows projected) : + ChildBlockProjection.rawPullback calls rows q block = cast (congrArg + (fun ss : Slots branch n → Fin t → MixedSupport.Slot => + ChildBlockCardinality.Raw calls rows ss) hs.symm) block := by + cases hs + have hq : q = fun s k => MixedSupport.Projection.keep (slots s k) := by + funext s k + exact eq_of_heq (hk s k) + subst q + apply Prod.ext + · funext call + apply Subtype.ext + rfl + · funext node row + apply Subtype.ext + rfl + +theorem childPullback_heq {C : Type*} [Fintype C] (rows : Nat → Nat) + {left right left' right' : Slots branch (n + 1) → Fin t → MixedSupport.Slot} + (hL : left = left') (hR : right = right') + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (q' : ∀ s k, MixedSupport.Projection (left' s k) (right' s k)) + (hq : ∀ s k, HEq (q s k) (q' s k)) (i : Fin (branch n)) + (block : CutChildGrouping.Child (C := C) right rows i) + (block' : CutChildGrouping.Child (C := C) right' rows i) + (hb : HEq block block') : + HEq (ChildAssemblyProjection.childPullback rows q i block) + (ChildAssemblyProjection.childPullback rows q' i block') := by + cases hL + cases hR + have hqq' : q = q' := by + funext s k + exact eq_of_heq (hq s k) + cases hqq' + have hbb' : block = block' := eq_of_heq hb + cases hbb' + rfl + +private theorem keep_heq {a b : MixedSupport.Slot} (h : a = b) : + HEq (MixedSupport.Projection.keep a) (MixedSupport.Projection.keep b) := by + cases h + rfl + +theorem fillProjection_outside {m : Nat} (p : Path branch n m) + (outside : Slots branch n → Fin t → MixedSupport.Slot) + (left right : Slots branch m → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (s : Slots branch n) (hout : s ∉ Set.range p.slotEmbedding) (k : Fin t) : + HEq (CutProjectionAssembly.fillProjection p outside left right q s k) + (MixedSupport.Projection.keep (CutSlotAssembly.fill p outside left s k)) := by + revert outside left right q s hout k + induction p with + | refl _ => + intro outside left right q s hout k + exact False.elim (hout ⟨s, rfl⟩) + | step i p ih => + intro outside left right q s hout k + obtain ⟨j, s⟩ := s + by_cases hji : j = i + · subst j + have htail : s ∉ Set.range p.slotEmbedding := by + rintro ⟨a, ha⟩ + exact hout ⟨a, congrArg (fun b => (i, b)) ha⟩ + have hfill : CutSlotAssembly.fill (.step i p) outside left (i, s) = + CutSlotAssembly.fill p (fun b => outside (i, b)) left s := + ite_eq_left (show i = i from rfl) + simp only [CutProjectionAssembly.fillProjection] + exact (CutProjectionAssembly.castProjection_heq _ _ _).trans + ((ih (fun b => outside (i, b)) left right q s htail k).trans + (keep_heq (congrFun hfill k).symm)) + · have hfill : CutSlotAssembly.fill (.step i p) outside left (j, s) = outside (j, s) := + ite_eq_right hji + simp only [CutProjectionAssembly.fillProjection, dite_eq_right hji] + exact (CutProjectionAssembly.castProjection_heq _ _ _).trans + (keep_heq (congrFun hfill k).symm) + +end +end PerfectCompleteness.CutProjectionGeometry + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/DecoderContraction.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/DecoderContraction.lean new file mode 100644 index 0000000000000000000000000000000000000000..e3f8549eb21911f5554cdf5eca931c341e36ed61 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/DecoderContraction.lean @@ -0,0 +1,174 @@ +import OAI.Computability.PerfectCompleteness.Algebra.BilinearGramCompressionLemmas +import OAI.Computability.PerfectCompleteness.Construction.DescendantSpacesLemmas +import OAI.Computability.PerfectCompleteness.Foundations.OddListExtraction + +namespace OAI + + +namespace PerfectCompleteness.DecoderContraction + +open scoped TensorProduct Classical +open TensorCosetEvaluation +open PointwiseSpaces RecursiveSpaces + +noncomputable section + +abbrev F2 := ZMod 2 + +variable {K H : Type*} [AddCommGroup K] [Module F2 K] + [AddCommGroup H] [Module F2 H] + +def chosenRow (W : Submodule F2 K) (σ : Module.Dual F2 K) + (hσ : σ.comp W.subtype ≠ 0) : W := + Classical.choose (exists_value_one (σ.comp W.subtype) hσ) + +theorem chosenRow_value_one (W : Submodule F2 K) (σ : Module.Dual F2 K) + (hσ : σ.comp W.subtype ≠ 0) : σ (chosenRow W σ hσ).val = 1 := + Classical.choose_spec (exists_value_one (σ.comp W.subtype) hσ) + +def contract (W : Submodule F2 K) (σ : Module.Dual F2 K) + (Φ : Module.Dual F2 (W ⊗[F2] H)) : Module.Dual F2 H := + if hσ : σ.comp W.subtype ≠ 0 then scalarRestriction Φ (chosenRow W σ hσ) else 0 + +theorem contract_eq (W : Submodule F2 K) (σ : Module.Dual F2 K) + (Φ : Module.Dual F2 (W ⊗[F2] H)) (hσ : σ.comp W.subtype ≠ 0) : + contract W σ Φ = scalarRestriction Φ (chosenRow W σ hσ) := by + simp only [contract, dite_eq_left hσ] + +theorem contract_eq_zero (W : Submodule F2 K) (σ : Module.Dual F2 K) + (Φ : Module.Dual F2 (W ⊗[F2] H)) (hσ : σ.comp W.subtype = 0) : + contract W σ Φ = 0 := by + simp [contract, hσ] + +def baseFrequency (W : Submodule F2 K) (σ : Module.Dual F2 K) + (z : Module.Dual F2 H) : Module.Dual F2 (W ⊗[F2] H) := + pureFrequency (σ.comp W.subtype) z + +@[simp] theorem baseFrequency_tmul (W : Submodule F2 K) (σ : Module.Dual F2 K) + (z : Module.Dual F2 H) (w : W) (h : H) : + baseFrequency W σ z (w ⊗ₜ[F2] h) = σ w.val * z h := + pureFrequency_tmul (σ.comp W.subtype) z w h + +theorem contract_baseFrequency (W : Submodule F2 K) (σ : Module.Dual F2 K) + (z : Module.Dual F2 H) (hσ : σ.comp W.subtype ≠ 0) : + contract W σ (baseFrequency W σ z) = z := by + rw [contract_eq W σ _ hσ] + change scalarRestriction (pureFrequency (σ.comp W.subtype) z) (chosenRow W σ hσ) = z + rw [scalarRestriction_pure] + change σ (chosenRow W σ hσ).val • z = z + rw [chosenRow_value_one, one_smul] + +def errorSpace (W : Submodule F2 K) (Q : Submodule F2 (Module.Dual F2 H)) : + Submodule F2 (Module.Dual F2 (W ⊗[F2] H)) where + carrier := {Ψ | ∀ w : W, scalarRestriction Ψ w ∈ Q} + zero_mem' := by + intro w + rw [scalarRestriction_zero] + exact Q.zero_mem + add_mem' := by + intro Φ Ψ hΦ hΨ w + rw [scalarRestriction_add] + exact Q.add_mem (hΦ w) (hΨ w) + smul_mem' := by + intro c Ψ hΨ w + rw [scalarRestriction_smul] + exact Q.smul_mem c (hΨ w) + +@[simp] theorem mem_errorSpace (W : Submodule F2 K) + (Q : Submodule F2 (Module.Dual F2 H)) (Ψ : Module.Dual F2 (W ⊗[F2] H)) : + Ψ ∈ errorSpace W Q ↔ ∀ w : W, scalarRestriction Ψ w ∈ Q := Iff.rfl + +theorem equationSpace_le_errorSpace (W : Submodule F2 K) + (Q : Submodule F2 (Module.Dual F2 H)) : equationSpace (U := W) Q ≤ errorSpace W Q := by + intro Ψ hΨ w + exact scalarRestriction_mem Q Ψ hΨ w + +theorem contract_sub_mem (W : Submodule F2 K) (Q : Submodule F2 (Module.Dual F2 H)) + (σ : Module.Dual F2 K) (Φ : Module.Dual F2 (W ⊗[F2] H)) (z : Module.Dual F2 H) + (hσ : σ.comp W.subtype ≠ 0) (hΦ : Φ - baseFrequency W σ z ∈ errorSpace W Q) : + contract W σ Φ - z ∈ Q := by + have h := hΦ (chosenRow W σ hσ) + rw [scalarRestriction_sub] at h + rw [contract_eq W σ Φ hσ] + have hbase : scalarRestriction (baseFrequency W σ z) (chosenRow W σ hσ) = z := by + rw [← contract_eq W σ _ hσ] + exact contract_baseFrequency W σ z hσ + rw [hbase] at h + exact h + +theorem contract_sub_mem_of_equationSpace (W : Submodule F2 K) + (Q : Submodule F2 (Module.Dual F2 H)) (σ : Module.Dual F2 K) + (Φ : Module.Dual F2 (W ⊗[F2] H)) (z : Module.Dual F2 H) + (hσ : σ.comp W.subtype ≠ 0) + (hΦ : Φ - baseFrequency W σ z ∈ equationSpace (U := W) Q) : + contract W σ Φ - z ∈ Q := + contract_sub_mem W Q σ Φ z hσ (equationSpace_le_errorSpace W Q hΦ) + +theorem factored_mem_errorSpace {L : Type*} [AddCommGroup L] [Module F2 L] + (W : Submodule F2 K) (Q : Submodule F2 (Module.Dual F2 H)) [FiniteDimensional F2 Q] + (R : (W ⊗[F2] H) →ₗ[F2] L) + (hR : ∀ w h, h ∈ Q.dualCoannihilator → R (w ⊗ₜ[F2] h) = 0) + (ψ : Module.Dual F2 L) : ψ.comp R ∈ errorSpace W Q := by + intro w + exact scalarRestriction_factor_mem Q R hR ψ w + + +variable {branch : Nat → Nat} {n m : Nat} + +def descendantSquareEmbedding (p : DescendantSpaces.Path branch n m) + (A : Slots branch n → Type*) (hbranch : ∀ k < n, 0 < branch k) (hproper : m < n) : + squareSpace (space F2 branch m (p.family A)) →ₗ[F2] space F2 branch n A where + toFun f := ⟨pullback F2 (p.restriction A) f.val, + DescendantSpaces.descendant_square_le_space p A hbranch hproper + (Submodule.mem_map_of_mem f.property)⟩ + map_add' _ _ := Subtype.ext rfl + map_smul' _ _ := Subtype.ext rfl + +@[simp] theorem descendantSquareEmbedding_apply (p : DescendantSpaces.Path branch n m) + (A : Slots branch n → Type*) (hbranch : ∀ k < n, 0 < branch k) (hproper : m < n) + (f : squareSpace (space F2 branch m (p.family A))) (x : Assignment A) : + (descendantSquareEmbedding p A hbranch hproper f).val x = f.val (p.restriction A x) := rfl + +theorem descendantSquareEmbedding_injective (p : DescendantSpaces.Path branch n m) + (A : Slots branch n → Type*) (hbranch : ∀ k < n, 0 < branch k) (hproper : m < n) + (hnonempty : ∀ s, Nonempty (A s)) : + Function.Injective (descendantSquareEmbedding p A hbranch hproper) := by + intro f g h + apply Subtype.ext + exact DescendantSpaces.descendant_pullback_injective p A hnonempty (congrArg Subtype.val h) + +def descendantFunctional (p : DescendantSpaces.Path branch n m) + (A : Slots branch n → Type*) (hbranch : ∀ k < n, 0 < branch k) (hproper : m < n) + (z : Module.Dual F2 (space F2 branch n A)) : + Module.Dual F2 (squareSpace (space F2 branch m (p.family A))) := + z.comp (descendantSquareEmbedding p A hbranch hproper) + +def descendantForm (p : DescendantSpaces.Path branch n m) + (A : Slots branch n → Type*) (hbranch : ∀ k < n, 0 < branch k) (hproper : m < n) + (z : Module.Dual F2 (space F2 branch n A)) : + space F2 branch m (p.family A) →ₗ[F2] space F2 branch m (p.family A) →ₗ[F2] F2 := + OddListExtraction.multiplicationForm _ (descendantFunctional p A hbranch hproper z) + +theorem descendantFunctional_contract_eq (p : DescendantSpaces.Path branch n m) + (A : Slots branch n → Type*) (hbranch : ∀ k < n, 0 < branch k) (hproper : m < n) + (W : Submodule F2 K) + (Q : Submodule F2 (Module.Dual F2 (space F2 branch n A))) + (σ : Module.Dual F2 K) (Φ : Module.Dual F2 (W ⊗[F2] space F2 branch n A)) + (z : Module.Dual F2 (space F2 branch n A)) (hσ : σ.comp W.subtype ≠ 0) + (hΦ : Φ - baseFrequency W σ z ∈ errorSpace W Q) + (hvanish : ∀ q ∈ Q, q.comp (descendantSquareEmbedding p A hbranch hproper) = 0) : + descendantFunctional p A hbranch hproper (contract W σ Φ) = + descendantFunctional p A hbranch hproper z := by + have h := hvanish (contract W σ Φ - z) (contract_sub_mem W Q σ Φ z hσ hΦ) + apply LinearMap.ext + intro f + have he := LinearMap.congr_fun h f + change contract W σ Φ (descendantSquareEmbedding p A hbranch hproper f) - + z (descendantSquareEmbedding p A hbranch hproper f) = 0 at he + exact sub_eq_zero.mp he + + +end +end PerfectCompleteness.DecoderContraction + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/DecoderFamilyLawLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/DecoderFamilyLawLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..5e9b48d3304b2fafc94112c82f7ca9e39a31ba19 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/DecoderFamilyLawLemmas.lean @@ -0,0 +1,397 @@ +import OAI.Computability.PerfectCompleteness.Algebra.DecoderRankSplit +import OAI.Computability.PerfectCompleteness.Foundations.ProjectedFiberSquare + +namespace OAI + +section + +namespace PerfectCompleteness.DecoderFamilyLaw + +noncomputable section + +open scoped Classical +open TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +variable {branch rows repeats : Nat → Nat} {n h t v m : Nat} [NeZero m] + {O : Type*} [Fintype O] + {upper : O → Nodes branch n} + {lower : (o : O) → HierarchicalFrozenTables.LowerNodes (upper o) (h + 1)} + (S : (o : O) → CleanDecoderRate.Setup branch rows repeats n h t v m (upper o) (lower o)) + +abbrev Fiber (o : O) := + Σ x : CleanDecoderRate.Sample (S o), CleanDecoderPairLaw.Pair (S o) x + +abbrev Sample := Σ o : O, Fiber S o + +def meeting (z : Sample S) : Bool := + DecoderRankSplit.meeting (S z.1) z.2.1 z.2.2 + +variable (hbranch : ∀ k < n, 0 < branch k) + +def lowAgreement (s : Nat) (z : Sample S) : Bool := + CleanDecoderPairLaw.pairAgrees (S z.1) hbranch s z.2.1 z.2.2 + +def highAgreement (s : Nat) (z : Sample S) : Bool := + DecoderRankSplit.highAgrees (S z.1) hbranch s z.2.1 z.2.2 + +variable (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (useful : (o : O) → (record : CleanDecoderRate.Record (S o)) → + CleanLeftDecoder.Useful + (CleanDecoderContext.leftExposed (CleanDecoderRate.context (S o) record)) + (upper o) (h + 1)) + (r : Nat) (ρ : ℝ) + (A : (o : O) → ManyGoodRows.RowMap (Block rows (upper o)) r) + (a : (o : O) → OwnInputReference.LowerVector rows + (HierarchicalLeftDecoder.LowerNode (upper o) (h + 1) (lower o))) + (threshold : ℝ) + +def fiberLaw (cube : Nat) (hcube : 0 < cube) (o : O) : + FiniteDistribution (Fiber S o) := + CleanDecoderPairLaw.pairLaw (S o) σ (useful o) r ρ (A o) + (LinearMap.ker (A o)) (a o) threshold cube hcube + +def law (outer : FiniteDistribution O) (cube : Nat) (hcube : 0 < cube) : + FiniteDistribution (Sample S) := + CompletionSoundness.sigmaLaw outer + (fiberLaw S σ useful r ρ A a threshold cube hcube) + +theorem probability_eq_expectation + (outer : FiniteDistribution O) (cube : Nat) (hcube : 0 < cube) + (event : Sample S → Bool) : + (law S σ useful r ρ A a threshold outer cube hcube).probability event = + outer.expectation (fun o => + (fiberLaw S σ useful r ρ A a threshold cube hcube o).probability + (fun x => event ⟨o, x⟩)) := by + exact CompletionSoundness.sigmaLaw_probability outer + (fiberLaw S σ useful r ρ A a threshold cube hcube) event + +theorem probability_split + (outer : FiniteDistribution O) (s cube : Nat) (hcube : 0 < cube) : + (law S σ useful r ρ A a threshold outer cube hcube).probability (meeting S) = + (law S σ useful r ρ A a threshold outer cube hcube).probability + (lowAgreement S hbranch s) + + (law S σ useful r ρ A a threshold outer cube hcube).probability + (highAgreement S hbranch s) := by + rw [probability_eq_expectation, probability_eq_expectation, + probability_eq_expectation] + have heq := FiniteDistribution.expectation_congr outer + (fun o => DecoderRankSplit.pair_probability_split (S o) hbranch σ (useful o) + r ρ (A o) (LinearMap.ker (A o)) (a o) threshold s cube hcube) + simpa only [FiniteDistribution.expectation, mul_add, Finset.sum_add_distrib, + meeting, lowAgreement, highAgreement, fiberLaw] using heq + +theorem meeting_probability_ge + (outer : FiniteDistribution O) (cube : Nat) (hcube : 0 < cube) + (bound : O → ℝ) + (hbound : ∀ o, bound o ≤ + (fiberLaw S σ useful r ρ A a threshold cube hcube o).probability + (fun x => DecoderRankSplit.meeting (S o) x.1 x.2)) : + outer.expectation bound ≤ + (law S σ useful r ρ A a threshold outer cube hcube).probability (meeting S) := by + rw [probability_eq_expectation] + exact SmallBias.expectation_mono outer hbound + +end +end PerfectCompleteness.DecoderFamilyLaw + +end + +section + +namespace PerfectCompleteness.DecoderPairHighOutput + +noncomputable section + +open scoped Classical +open TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +abbrev F2 := ZMod 2 + +variable {branch rows repeats : Nat → Nat} {n h t v m : Nat} [NeZero m] + {upper : Nodes branch n} {d : HierarchicalFrozenTables.LowerNodes upper (h + 1)} + (S : CleanDecoderRate.Setup branch rows repeats n h t v m upper d) + +abbrev exposed (x : CleanDecoderRate.Sample S) := + CleanDecoderContext.leftExposed (CleanDecoderPairLaw.context S x) + +abbrev slots (x : CleanDecoderRate.Sample S) := + CleanLeftDecoder.slots (exposed S x) (CleanDecoderPairLaw.leftOwn S x) + +abbrev background (x : CleanDecoderRate.Sample S) := + CleanLeftDecoder.background (exposed S x) upper (CleanDecoderPairLaw.leftOwn S x) + +abbrev advice (r : Nat) (A : ManyGoodRows.RowMap (Block rows upper) r) + (x : CleanDecoderRate.Sample S) := + CleanLeftDecoder.advice (exposed S x) upper (h + 1) r A (CleanDecoderPairLaw.leftOwn S x) + +abbrev Answer (x : CleanDecoderRate.Sample S) := + HierarchicalDecoderTables.Answer (slots S x) upper (h + 1) d + +instance answerFintype (x : CleanDecoderRate.Sample S) : Fintype (Answer S x) := + HierarchicalDecoderTables.answerFintype (slots S x) upper (h + 1) d + +theorem actualInput_eq (r : Nat) (A : ManyGoodRows.RowMap (Block rows upper) r) + (x : CleanDecoderRate.Sample S) : + LowerCutDecoderInput.actualInput (slots S x) upper (h + 1) + (CleanLeftDecoder.arrays (exposed S x) (CleanDecoderPairLaw.leftOwn S x)) A = + ⟨background S x, advice S r A x⟩ := rfl + +variable (hbranch : ∀ k < n, 0 < branch k) + +abbrev output (x : CleanDecoderRate.Sample S) (q : CleanDecoderPairLaw.LeftAnswer S x) : + Answer S x := + CleanLeftDecoder.output (exposed S x) upper (h + 1) hbranch d + (CleanDecoderPairLaw.leftOwn S x) q + +abbrev decode (s : Nat) (x : CleanDecoderRate.Sample S) + (q : CleanDecoderPairLaw.LeftAnswer S x) : Option (Answer S x) := + HierarchicalDecoderTables.decode (slots S x) upper (h + 1) hbranch d s q + +theorem nativeRank_eq_fullRank (x : CleanDecoderRate.Sample S) + (answer : CleanDecoderPairLaw.Pair S x) : + DecoderRankSplit.nativeRank S hbranch x answer = + HierarchicalDecoderTables.fullRank (slots S x) upper (h + 1) d + (output S hbranch x answer.1) := rfl + +theorem decode_of_highAgrees (s : Nat) (x : CleanDecoderRate.Sample S) + (answer : CleanDecoderPairLaw.Pair S x) + (hhigh : DecoderRankSplit.highAgrees S hbranch s x answer = true) : + decode S hbranch s x answer.1 = some (output S hbranch x answer.1) := by + have hrank := (DecoderRankSplit.highAgrees_eq_true S hbranch s x answer).mp hhigh + exact ProjectedNativeCollision.decode_eq_some_of_high + (slots := slots S x) upper (h + 1) hbranch d s answer.1 + ((nativeRank_eq_fullRank S hbranch x answer) ▸ hrank.1) + +theorem highAgrees_eq_highMeeting (s : Nat) (x : CleanDecoderRate.Sample S) + (answer : CleanDecoderPairLaw.Pair S x) : + DecoderRankSplit.highAgrees S hbranch s x answer = + ProjectedFiberSquare.highMeeting (slots S x) + (CleanDecoderContext.rightSlots (CleanDecoderPairLaw.context S x) + (CleanDecoderPairLaw.rightOwn S x)) + (CleanDecoderOddLists.fullProjection (CleanDecoderPairLaw.context S x) + (CleanDecoderPairLaw.occurrences S x)) upper (h + 1) hbranch d s + answer.1 answer.2 := by + apply Bool.eq_iff_iff.mpr + rw [DecoderRankSplit.highAgrees_eq_true] + simp only [ProjectedFiberSquare.highMeeting, DecoderRankSplit.meeting, + decide_eq_true_eq, nativeRank_eq_fullRank] + exact and_congr Iff.rfl eq_comm + +variable (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (useful : (record : CleanDecoderRate.Record S) → + CleanLeftDecoder.Useful (CleanDecoderContext.leftExposed (CleanDecoderRate.context S record)) + upper (h + 1)) + (r : Nat) (ρ : ℝ) (A : ManyGoodRows.RowMap (Block rows upper) r) + (W : Submodule F2 (OwnInputReference.UpperVector rows upper)) + (a : OwnInputReference.LowerVector rows (HierarchicalLeftDecoder.LowerNode upper (h + 1) d)) + (threshold : ℝ) + +theorem supported_left (x : CleanDecoderRate.Sample S) + (answer : CleanDecoderPairLaw.Pair S x) + (hs : (CleanDecoderPairLaw.pairKernel S σ useful r ρ A W a threshold x).weight answer ≠ 0) : + (CleanLeftDecoder.law (exposed S x) upper (h + 1) σ + (useful (CleanDecoderRate.observations S x)) r ρ A + (CleanDecoderPairLaw.leftOwn S x)).weight answer.1 ≠ 0 := by + intro hz + apply hs + change (CleanLeftDecoder.law (exposed S x) upper (h + 1) σ + (useful (CleanDecoderRate.observations S x)) r ρ A + (CleanDecoderPairLaw.leftOwn S x)).weight answer.1 * + (CleanDecoderSeedLaw.rightKernel (CleanDecoderPairLaw.context S x) σ W a threshold + (CleanDecoderPairLaw.rightOwn S x)).weight answer.2 = 0 + rw [hz, zero_mul] + +theorem valid_of_support (hρ : 0 < ρ) (x : CleanDecoderRate.Sample S) + (answer : CleanDecoderPairLaw.Pair S x) + (hs : (CleanDecoderPairLaw.pairKernel S σ useful r ρ A W a threshold x).weight answer ≠ 0) : + HierarchicalLeftDecoder.Valid (slots S x) upper (h + 1) hbranch + (background S x) answer.1 := by + exact of_decide_eq_true (DecoderTableAdmissibility.event_of_probability_one + (CleanLeftDecoder.law (exposed S x) upper (h + 1) σ + (useful (CleanDecoderRate.observations S x)) r ρ A (CleanDecoderPairLaw.leftOwn S x)) + (fun q => decide (HierarchicalLeftDecoder.Valid (slots S x) upper (h + 1) hbranch + (background S x) q)) + (CleanLeftDecoder.law_valid (exposed S x) upper (h + 1) σ + (useful (CleanDecoderRate.observations S x)) hbranch r ρ hρ A + (CleanDecoderPairLaw.leftOwn S x)) answer.1 + (supported_left S σ useful r ρ A W a threshold x answer hs)) + +theorem valid_output_of_highAgrees (hρ : 0 < ρ) (s : Nat) + (x : CleanDecoderRate.Sample S) (answer : CleanDecoderPairLaw.Pair S x) + (hs : (CleanDecoderPairLaw.pairKernel S σ useful r ρ A W a threshold x).weight answer ≠ 0) + (hhigh : DecoderRankSplit.highAgrees S hbranch s x answer = true) : + HierarchicalDecoderTables.Valid (slots S x) upper (h + 1) (background S x) + hbranch d s (output S hbranch x answer.1) := + HierarchicalDecoderTables.decode_valid (slots S x) upper (h + 1) (background S x) + hbranch d s answer.1 + (valid_of_support S hbranch σ useful r ρ A W a threshold hρ x answer hs) + (output S hbranch x answer.1) (decode_of_highAgrees S hbranch s x answer hhigh) + +theorem responseLaw_eq_pushforward (s : Nat) (x : CleanDecoderRate.Sample S) : + HierarchicalDecoderTables.responseLaw (slots S x) upper (h + 1) (background S x) + hbranch σ (useful (CleanDecoderRate.observations S x) (CleanDecoderPairLaw.leftOwn S x)) + r ρ d s (advice S r A x) = + (CleanDecoderSeedLaw.leftKernel (CleanDecoderPairLaw.context S x) σ + (useful (CleanDecoderRate.observations S x)) r ρ A + (CleanDecoderPairLaw.leftOwn S x)).pushforward (decode S hbranch s x) := rfl + +theorem pair_decode_law (s : Nat) (x : CleanDecoderRate.Sample S) : + (CleanDecoderPairLaw.pairKernel S σ useful r ρ A W a threshold x).pushforward + (fun answer => decode S hbranch s x answer.1) = + HierarchicalDecoderTables.responseLaw (slots S x) upper (h + 1) (background S x) + hbranch σ (useful (CleanDecoderRate.observations S x) (CleanDecoderPairLaw.leftOwn S x)) + r ρ d s (advice S r A x) := by + have hfst : + (CleanDecoderPairLaw.pairKernel S σ useful r ρ A W a threshold x).pushforward Prod.fst = + CleanDecoderSeedLaw.leftKernel (CleanDecoderPairLaw.context S x) σ + (useful (CleanDecoderRate.observations S x)) r ρ A + (CleanDecoderPairLaw.leftOwn S x) := + HiddenBucketBias.product_fst _ _ + rw [← FiniteDistribution.pushforward_comp + (CleanDecoderPairLaw.pairKernel S σ useful r ρ A W a threshold x) + (Prod.fst : CleanDecoderPairLaw.Pair S x → CleanDecoderPairLaw.LeftAnswer S x) + (decode S hbranch s x), hfst] + exact (responseLaw_eq_pushforward S hbranch σ useful r ρ A s x).symm + +end +end PerfectCompleteness.DecoderPairHighOutput + +end + +section + +namespace PerfectCompleteness.FixedDecoderFamilyRate + +noncomputable section + +open scoped BigOperators Classical +open HierarchicalArrays FixedDecoderCleanRate +open UniqueGamesTheorem.Foundations.Games + +theorem expectation_lt_const {O : Type*} [Fintype O] + (μ : FiniteDistribution O) (f : O → ℝ) (bound : ℝ) + (hbound : ∀ o, f o < bound) : μ.expectation f < bound := by + have hpositive : ∃ o, 0 < μ.weight o := by + by_contra hn + push Not at hn + have hzero : ∑ o, μ.weight o = 0 := + Finset.sum_eq_zero (fun o _ => le_antisymm (hn o) (μ.nonnegative o)) + linarith [μ.normalized] + obtain ⟨o, ho⟩ := hpositive + calc + μ.expectation f < μ.expectation (fun _ => bound) := by + apply Finset.sum_lt_sum + · intro x _ + exact mul_le_mul_of_nonneg_left (hbound x).le (μ.nonnegative x) + · exact ⟨o, Finset.mem_univ o, mul_lt_mul_of_pos_left (hbound o) ho⟩ + _ = bound := SmallBias.expectation_const μ bound + +variable {δ : ℚ} {hδ : 0 < δ} (p : FixedParameters.Parameters δ hδ) + {O : Type*} [Fintype O] {n h : Nat} + {upper : O → Nodes (FixedParameters.branch p) n} + {lower : (o : O) → HierarchicalFrozenTables.LowerNodes (upper o) (h + 1)} + (G : (o : O) → Geometry p n h (upper o) (lower o)) + (input : List Bool) + +def setups (o : O) := setup p (G o) input + +variable + (σ : KeyStrategy.Strategy + (TreeCanonical.locationCount (FixedParameters.branch p) n + (FixedRows.sourceLength p.plan hδ))) + (useful : (o : O) → (record : CleanDecoderRate.Record (setups p G input o)) → + CleanLeftDecoder.Useful + (CleanDecoderContext.leftExposed (CleanDecoderRate.context (setups p G input o) record)) + (upper o) (h + 1)) + (r : Nat) (ρ : ℝ) + (A : (o : O) → ManyGoodRows.RowMap (Block (FixedRows.rows p.plan) (upper o)) r) + (a : (o : O) → OwnInputReference.LowerVector (FixedRows.rows p.plan) + (HierarchicalLeftDecoder.LowerNode (upper o) (h + 1) (lower o))) + (threshold : ℝ) (outer : FiniteDistribution O) + +theorem probability_lt_accuracy (unsat : ¬BinaryLanguage.language input) + (hn : n ≤ p.plan.depth) (hρ : 0 < ρ) : + (DecoderFamilyLaw.law (setups p G input) σ useful r ρ A a threshold + outer (p.cubeSize h) (cubePositive p h)).probability + (DecoderFamilyLaw.lowAgreement (setups p G input) (branchPositive p) + (FixedRows.cutoff p.plan hδ)) < p.accuracy := by + rw [DecoderFamilyLaw.probability_eq_expectation] + apply expectation_lt_const + intro o + exact FixedDecoderPairRate.probability_lt_accuracy p (G o) input σ (useful o) + r ρ (A o) (LinearMap.ker (A o)) (a o) threshold unsat hn hρ + +end +end PerfectCompleteness.FixedDecoderFamilyRate + +end + +section + +namespace PerfectCompleteness.FixedDecoderFamilyContradiction + +noncomputable section + +open scoped Classical +open HierarchicalArrays FixedDecoderCleanRate FixedDecoderFamilyRate +open UniqueGamesTheorem.Foundations.Games + +variable {δ : ℚ} {hδ : 0 < δ} (p : FixedParameters.Parameters δ hδ) + {O : Type*} [Fintype O] {n h : Nat} + {upper : O → Nodes (FixedParameters.branch p) n} + {lower : (o : O) → HierarchicalFrozenTables.LowerNodes (upper o) (h + 1)} + (G : (o : O) → Geometry p n h (upper o) (lower o)) + (input : List Bool) + (σ : KeyStrategy.Strategy + (TreeCanonical.locationCount (FixedParameters.branch p) n + (FixedRows.sourceLength p.plan hδ))) + (useful : (o : O) → (record : CleanDecoderRate.Record (setups p G input o)) → + CleanLeftDecoder.Useful + (CleanDecoderContext.leftExposed (CleanDecoderRate.context (setups p G input o) record)) + (upper o) (h + 1)) + (r : Nat) (ρ : ℝ) + (A : (o : O) → ManyGoodRows.RowMap (Block (FixedRows.rows p.plan) (upper o)) r) + (a : (o : O) → OwnInputReference.LowerVector (FixedRows.rows p.plan) + (HierarchicalLeftDecoder.LowerNode (upper o) (h + 1) (lower o))) + (threshold : ℝ) (outer : FiniteDistribution O) + +theorem impossible (unsat : ¬BinaryLanguage.language input) + (hn : n ≤ p.plan.depth) (hρ : 0 < ρ) + (height : Nat) (hheight : height ≤ p.plan.depth) + (hupper : FixedRankContradiction.gamma p height ≤ + (DecoderFamilyLaw.law (setups p G input) σ useful r ρ A a threshold + outer (p.cubeSize h) (cubePositive p h)).probability + (DecoderFamilyLaw.meeting (setups p G input))) + (hhigh : (DecoderFamilyLaw.law (setups p G input) σ useful r ρ A a threshold + outer (p.cubeSize h) (cubePositive p h)).probability + (DecoderFamilyLaw.highAgreement (setups p G input) (branchPositive p) + (FixedRows.cutoff p.plan hδ)) ^ 2 ≤ + FixedRankContradiction.gamma p height ^ 2 / 8 + 2 * p.accuracy) : False := by + let μ := DecoderFamilyLaw.law (setups p G input) σ useful r ρ A a threshold + outer (p.cubeSize h) (cubePositive p h) + let low := fun z : DecoderFamilyLaw.Sample (setups p G input) => + DecoderRankSplit.low (setups p G input z.1) (branchPositive p) + (FixedRows.cutoff p.plan hδ) z.2.1 z.2.2 + apply FixedRankContradiction.impossible p μ + (DecoderFamilyLaw.meeting (setups p G input)) low height hheight hupper + · exact hhigh + · have hlow := FixedDecoderFamilyRate.probability_lt_accuracy p G input σ useful + r ρ A a threshold outer unsat hn hρ + have hevent : (fun z : DecoderFamilyLaw.Sample (setups p G input) => + DecoderFamilyLaw.meeting (setups p G input) z && low z) = + DecoderFamilyLaw.lowAgreement (setups p G input) (branchPositive p) + (FixedRows.cutoff p.plan hδ) := by + funext z + exact DecoderRankSplit.meeting_low (setups p G input z.1) (branchPositive p) + (FixedRows.cutoff p.plan hδ) z.2.1 z.2.2 + rw [hevent] + exact hlow + +end +end PerfectCompleteness.FixedDecoderFamilyContradiction + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/DecoderSourcePullback.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/DecoderSourcePullback.lean new file mode 100644 index 0000000000000000000000000000000000000000..e5ffa6c7bb82cdc1551c6c9c123775ce0cf6bf56 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/DecoderSourcePullback.lean @@ -0,0 +1,195 @@ +import OAI.Computability.PerfectCompleteness.Decoding.ChildBlockProjection +import OAI.Computability.PerfectCompleteness.Decoding.HierarchicalLeftDecoder +import OAI.Computability.PerfectCompleteness.Decoding.RightDecoderLemmas + +namespace OAI + + +namespace PerfectCompleteness.DecoderSourcePullback + +open RecursiveSpaces TreeSourceSpaces HierarchicalArrays PointwiseSpaces OwnInputReference +open ChildBlockProjection + +noncomputable section + +abbrev F2 := ZMod 2 + +variable {branch : Nat → Nat} {n t : Nat} + {slots projected : Slots branch n → Fin t → MixedSupport.Slot} + +def relativeCut : + {n : Nat} → (upper : Nodes branch n) → + (lower : Nodes branch (Nodes.height upper)) → + Nodes.height lower < Nodes.height upper → + Cut upper (RelativeDescendantProducts.relativeNode upper lower) + | 0, upper, _, _ => nomatch upper + | _ + 1, .inl _, lower, h => + { proper := h + path := Nodes.path lower + slots_agree := fun _ => rfl } + | _ + 1, .inr (i, upper), lower, h => + let c := relativeCut upper lower h + { proper := c.proper + path := c.path + slots_agree := fun s => congrArg (fun z => (i, z)) (c.slots_agree s) } + +def selectedCut (upper : Nodes branch n) (level : Nat) + (d : HierarchicalFrozenTables.LowerNodes upper level) : + Cut upper (HierarchicalLeftDecoder.LowerNode upper level d) := + relativeCut upper d.val.val d.val.property + +theorem upperBranch (upper : Nodes branch n) (hbranch : ∀ k < n, 0 < branch k) : + ∀ k < Nodes.height upper, 0 < branch k := + fun k hk => hbranch k (Nat.lt_of_lt_of_le hk (Nodes.height_le upper)) + +variable (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (upper lower : Nodes branch n) (cut : Cut upper lower) + +theorem restriction_projection (x : Domain (nodeSlots slots upper)) : + RightDecoderDescendant.restriction projected upper lower cut + (sourceProjection (nodeProjection p upper) x) = + sourceProjection (nodeProjection p lower) + (RightDecoderDescendant.restriction slots upper lower cut x) := by + obtain ⟨y, rfl⟩ := restrictNode_surjective slots upper x + rw [restrictNode_projection, RightDecoderDescendant.restriction_restrictNode, + RightDecoderDescendant.restriction_restrictNode] + exact (restrictNode_projection p lower y).symm + +theorem squareEmbedding_pullback + (hbranch : ∀ k < Nodes.height upper, 0 < branch k) : + (HPullback (nodeProjection p upper)).comp + (RightDecoderDescendant.squareEmbedding projected upper lower cut hbranch) = + (RightDecoderDescendant.squareEmbedding slots upper lower cut hbranch).comp + (squarePullback (nodeProjection p lower)) := by + apply LinearMap.ext + intro f + apply Subtype.ext + funext x + change f.val (RightDecoderDescendant.restriction projected upper lower cut + (sourceProjection (nodeProjection p upper) x)) = + f.val (sourceProjection (nodeProjection p lower) + (RightDecoderDescendant.restriction slots upper lower cut x)) + rw [restriction_projection p upper lower cut] + +theorem squarePullback_product (f g : H projected) : + squarePullback p (OddListExtraction.productElement (H projected) f g) = + OddListExtraction.productElement (H slots) (HPullback p f) (HPullback p g) := by + apply Subtype.ext + rfl + +def upperTarget (q : Module.Dual F2 (NodeEmbedding.RowSpace slots upper)) : + Module.Dual F2 (UpperSpace projected upper) := + (q.comp (NodeEmbedding.equiv slots upper).toLinearMap).comp + (HPullback (nodeProjection p upper)) + +@[simp] theorem upperTarget_apply + (q : Module.Dual F2 (NodeEmbedding.RowSpace slots upper)) + (f : UpperSpace projected upper) : + upperTarget p upper q f = + q (NodeEmbedding.embed slots upper (HPullback (nodeProjection p upper) f)) := rfl + + +variable (level : Nat) (hbranch : ∀ k < n, 0 < branch k) + (d : HierarchicalFrozenTables.LowerNodes upper level) + +theorem embed_squareEmbedding + (cut : Cut upper (HierarchicalLeftDecoder.LowerNode upper level d)) : + (NodeEmbedding.embed slots upper).comp + (RightDecoderDescendant.squareEmbedding slots upper + (HierarchicalLeftDecoder.LowerNode upper level d) cut (upperBranch upper hbranch)) = + HierarchicalLeftDecoder.squareEmbedding slots upper level hbranch d := by + apply LinearMap.ext + intro f + apply Subtype.ext + funext x + change (RightDecoderDescendant.squareEmbedding slots upper + (HierarchicalLeftDecoder.LowerNode upper level d) cut (upperBranch upper hbranch) f).val + (restrictNode slots upper ((TreeCanonical.assignmentEquiv slots).symm x)) = + f.val (restrictNode slots (HierarchicalLeftDecoder.LowerNode upper level d) + ((TreeCanonical.assignmentEquiv slots).symm x)) + exact RightDecoderDescendant.squareEmbedding_restrictNode slots upper + (HierarchicalLeftDecoder.LowerNode upper level d) cut (upperBranch upper hbranch) f + ((TreeCanonical.assignmentEquiv slots).symm x) + +theorem functional_upperTarget + (cut : Cut upper (HierarchicalLeftDecoder.LowerNode upper level d)) + (q : Module.Dual F2 (NodeEmbedding.RowSpace slots upper)) : + RightDecoderDescendant.functional projected upper + (HierarchicalLeftDecoder.LowerNode upper level d) cut (upperBranch upper hbranch) + (upperTarget p upper q) = + (HierarchicalLeftDecoder.output slots upper level hbranch d q).comp + (squarePullback (nodeProjection p (HierarchicalLeftDecoder.LowerNode upper level d))) := by + apply LinearMap.ext + intro f + change q (NodeEmbedding.embed slots upper + (HPullback (nodeProjection p upper) + (RightDecoderDescendant.squareEmbedding projected upper + (HierarchicalLeftDecoder.LowerNode upper level d) cut (upperBranch upper hbranch) f))) = + q (HierarchicalLeftDecoder.squareEmbedding slots upper level hbranch d + (squarePullback (nodeProjection p (HierarchicalLeftDecoder.LowerNode upper level d)) f)) + calc + _ = q (NodeEmbedding.embed slots upper + (RightDecoderDescendant.squareEmbedding slots upper + (HierarchicalLeftDecoder.LowerNode upper level d) cut (upperBranch upper hbranch) + (squarePullback (nodeProjection p + (HierarchicalLeftDecoder.LowerNode upper level d)) f))) := + congrArg (fun g => q (NodeEmbedding.embed slots upper g)) + (LinearMap.congr_fun (squareEmbedding_pullback p upper + (HierarchicalLeftDecoder.LowerNode upper level d) cut (upperBranch upper hbranch)) f) + _ = _ := congrArg q (LinearMap.congr_fun + (embed_squareEmbedding (slots := slots) upper level hbranch d cut) + (squarePullback (nodeProjection p (HierarchicalLeftDecoder.LowerNode upper level d)) f)) + +theorem form_upperTarget + (cut : Cut upper (HierarchicalLeftDecoder.LowerNode upper level d)) + (q : Module.Dual F2 (NodeEmbedding.RowSpace slots upper)) + (f g : H (nodeSlots projected (HierarchicalLeftDecoder.LowerNode upper level d))) : + RightDecoderDescendant.form projected upper + (HierarchicalLeftDecoder.LowerNode upper level d) cut (upperBranch upper hbranch) + (upperTarget p upper q) f g = + OddListExtraction.multiplicationForm + (H (nodeSlots slots (HierarchicalLeftDecoder.LowerNode upper level d))) + (HierarchicalLeftDecoder.output slots upper level hbranch d q) + (HPullback (nodeProjection p (HierarchicalLeftDecoder.LowerNode upper level d)) f) + (HPullback (nodeProjection p (HierarchicalLeftDecoder.LowerNode upper level d)) g) := by + change RightDecoderDescendant.functional projected upper + (HierarchicalLeftDecoder.LowerNode upper level d) cut (upperBranch upper hbranch) + (upperTarget p upper q) + (OddListExtraction.productElement + (H (nodeSlots projected (HierarchicalLeftDecoder.LowerNode upper level d))) f g) = _ + rw [functional_upperTarget p upper level hbranch d cut q] + change (HierarchicalLeftDecoder.output slots upper level hbranch d q) + (squarePullback (nodeProjection p (HierarchicalLeftDecoder.LowerNode upper level d)) + (OddListExtraction.productElement + (H (nodeSlots projected (HierarchicalLeftDecoder.LowerNode upper level d))) f g)) = _ + rw [squarePullback_product] + rfl + +theorem form_eq_of_target_error + (cut : Cut upper (HierarchicalLeftDecoder.LowerNode upper level d)) + (q : Module.Dual F2 (NodeEmbedding.RowSpace slots upper)) + (Q : Submodule F2 (Module.Dual F2 (UpperSpace projected upper))) + (decoded : Module.Dual F2 (UpperSpace projected upper)) + (herror : decoded - upperTarget p upper q ∈ Q) + (hvanish : ∀ z ∈ Q, z.comp + (RightDecoderDescendant.squareEmbedding projected upper + (HierarchicalLeftDecoder.LowerNode upper level d) cut (upperBranch upper hbranch)) = 0) + (f g : H (nodeSlots projected (HierarchicalLeftDecoder.LowerNode upper level d))) : + RightDecoderDescendant.form projected upper + (HierarchicalLeftDecoder.LowerNode upper level d) cut (upperBranch upper hbranch) + decoded f g = + OddListExtraction.multiplicationForm + (H (nodeSlots slots (HierarchicalLeftDecoder.LowerNode upper level d))) + (HierarchicalLeftDecoder.output slots upper level hbranch d q) + (HPullback (nodeProjection p (HierarchicalLeftDecoder.LowerNode upper level d)) f) + (HPullback (nodeProjection p (HierarchicalLeftDecoder.LowerNode upper level d)) g) := by + rw [RightDecoderDescendant.form_eq_of_sub_mem projected upper + (HierarchicalLeftDecoder.LowerNode upper level d) cut (upperBranch upper hbranch) + Q decoded (upperTarget p upper q) herror hvanish] + exact form_upperTarget p upper level hbranch d cut q f g + + +end +end PerfectCompleteness.DecoderSourcePullback + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/DecoderTableCoupling.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/DecoderTableCoupling.lean new file mode 100644 index 0000000000000000000000000000000000000000..e54a0780dc9a5229b195d5b30638361886b4fff2 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/DecoderTableCoupling.lean @@ -0,0 +1,159 @@ +import OAI.Computability.PerfectCompleteness.Decoding.TwoResponseCollisionLemmas +import OAI.Computability.PerfectCompleteness.Foundations.FiniteProduct +import OAI.Computability.UniqueGames.Foundations.KernelSampling + +namespace OAI + +section + +namespace PerfectCompleteness.DecoderTableCoupling + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games + +noncomputable section + +variable {Q A : Type*} [Fintype Q] [DecidableEq Q] [Fintype A] + +theorem probability_eq_expectation {X : Type*} [Fintype X] + (μ : FiniteDistribution X) (event : X → Bool) : + μ.probability event = μ.expectation (fun x => if event x then 1 else 0) := by + simp only [FiniteDistribution.probability, FiniteDistribution.expectation, mul_ite, + mul_one, mul_zero] + +theorem table_eq_product (responses : Q → FiniteDistribution A) : + FiniteDistribution.table responses = FiniteProduct.law responses := + FiniteDistribution.eq_of_weight_eq (fun _ => rfl) + +theorem pair_law_of_ne (responses : Q → FiniteDistribution A) + (q r : Q) (hne : q ≠ r) : + (FiniteDistribution.table responses).pushforward (fun f => (f q, f r)) = + (responses q).product (responses r) := by + apply FiniteDistribution.eq_of_weight_eq + rintro ⟨a, b⟩ + calc + _ = (FiniteDistribution.table responses).expectation + (fun f => (if f q = a then 1 else 0) * (if f r = b then 1 else 0)) := by + unfold FiniteDistribution.pushforward FiniteDistribution.expectation + apply Finset.sum_congr rfl + intro f _ + by_cases hq : f q = a <;> by_cases hr : f r = b <;> simp [hq, hr] + _ = (responses q).expectation (fun a' => if a' = a then 1 else 0) * + (responses r).expectation (fun b' => if b' = b then 1 else 0) := by + rw [table_eq_product] + exact FiniteProduct.expectation_eval_mul responses q r hne + (fun a' : A => if a' = a then (1 : ℝ) else 0) + (fun b' : A => if b' = b then (1 : ℝ) else 0) + _ = _ := by simp [FiniteDistribution.expectation, FiniteDistribution.product, mul_ite] + +def definedEqual (a b : Option A) : Bool := + decide (∃ value, a = some value ∧ b = some value) + +omit [Fintype A] in +@[simp] theorem definedEqual_none_left (a : Option A) : definedEqual none a = false := by + simp [definedEqual] + +omit [Fintype A] in +@[simp] theorem definedEqual_none_right (a : Option A) : definedEqual a none = false := by + simp [definedEqual] + +omit [Fintype A] in +@[simp] theorem definedEqual_self (a : Option A) : definedEqual a a = a.isSome := by + cases a <;> simp [definedEqual] + +omit [Fintype Q] [DecidableEq Q] [Fintype A] in +@[simp] theorem definedEqual_collision (f : Q → Option A) (q r : Q) : + definedEqual (f q) (f r) = TwoResponseCollision.collision f (q, r) := rfl + +def freshCollision (responses : Q → FiniteDistribution (Option A)) (q r : Q) : ℝ := + ((responses q).product (responses r)).probability (fun a => definedEqual a.1 a.2) + +def frozenCollision (responses : Q → FiniteDistribution (Option A)) (q r : Q) : ℝ := + (FiniteDistribution.table responses).probability (fun f => definedEqual (f q) (f r)) + +theorem frozenCollision_of_ne (responses : Q → FiniteDistribution (Option A)) + (q r : Q) (hne : q ≠ r) : + frozenCollision responses q r = freshCollision responses q r := by + unfold frozenCollision freshCollision + rw [← pair_law_of_ne responses q r hne, FiniteDistribution.probability_pushforward] + +theorem frozenCollision_self (responses : Q → FiniteDistribution (Option A)) (q : Q) : + frozenCollision responses q q = (responses q).probability Option.isSome := by + unfold frozenCollision + simp only [definedEqual_self] + rw [← FiniteDistribution.table_eval_pushforward responses q, + FiniteDistribution.probability_pushforward] + +theorem product_probability_first {X Y : Type*} [Fintype X] [Fintype Y] + (μ : FiniteDistribution X) (ν : FiniteDistribution Y) (event : X → Bool) : + (μ.product ν).probability (fun p => event p.1) = μ.probability event := by + unfold FiniteDistribution.probability + rw [Fintype.sum_prod_type] + apply Finset.sum_congr rfl + intro x _ + cases he : event x <;> + simp [FiniteDistribution.product, he, ← Finset.mul_sum, ν.normalized] + +omit [Fintype Q] [DecidableEq Q] in +theorem freshCollision_self_le (responses : Q → FiniteDistribution (Option A)) (q : Q) : + freshCollision responses q q ≤ (responses q).probability Option.isSome := by + unfold freshCollision + calc + _ ≤ ((responses q).product (responses q)).probability (fun a => a.1.isSome) := by + apply FiniteDistribution.probability_mono + intro a ha + obtain ⟨value, hleft, _⟩ := of_decide_eq_true ha + simp only [hleft, Option.isSome_some] + _ = _ := product_probability_first _ _ _ + +theorem freshCollision_le_frozenCollision + (responses : Q → FiniteDistribution (Option A)) (q r : Q) : + freshCollision responses q r ≤ frozenCollision responses q r := by + by_cases hqr : q = r + · subst r + rw [frozenCollision_self] + exact freshCollision_self_le responses q + · exact (frozenCollision_of_ne responses q r hqr).symm.le + +theorem mean_freshCollision_le_frozen + (responses : Q → FiniteDistribution (Option A)) (questions : FiniteDistribution (Q × Q)) : + questions.expectation (fun p => freshCollision responses p.1 p.2) ≤ + (FiniteDistribution.table responses).expectation + (fun f => questions.probability (TwoResponseCollision.collision f)) := by + calc + _ ≤ questions.expectation (fun p => frozenCollision responses p.1 p.2) := by + unfold FiniteDistribution.expectation + apply Finset.sum_le_sum + intro p _ + exact mul_le_mul_of_nonneg_left (freshCollision_le_frozenCollision responses p.1 p.2) + (questions.nonnegative p) + _ = _ := by + simp only [frozenCollision, probability_eq_expectation] + exact FiniteDistribution.expectation_comm questions (FiniteDistribution.table responses) + (fun p f => if definedEqual (f p.1) (f p.2) then (1 : ℝ) else 0) + +theorem freshCollision_le_of_supported_tables + (responses : Q → FiniteDistribution (Option A)) (questions : FiniteDistribution (Q × Q)) + (bound : ℝ) + (hbound : ∀ f, (FiniteDistribution.table responses).weight f ≠ 0 → + questions.probability (TwoResponseCollision.collision f) ≤ bound) : + questions.expectation (fun p => freshCollision responses p.1 p.2) ≤ bound := by + apply (mean_freshCollision_le_frozen responses questions).trans + calc + _ ≤ ∑ f, (FiniteDistribution.table responses).weight f * bound := by + unfold FiniteDistribution.expectation + apply Finset.sum_le_sum + intro f _ + by_cases hf : (FiniteDistribution.table responses).weight f = 0 + · simp only [hf, zero_mul, le_refl] + · exact mul_le_mul_of_nonneg_left (hbound f hf) + ((FiniteDistribution.table responses).nonnegative f) + _ = bound := by + rw [← Finset.sum_mul, (FiniteDistribution.table responses).normalized, one_mul] + +end +end PerfectCompleteness.DecoderTableCoupling + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/DependentDecoderSampling.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/DependentDecoderSampling.lean new file mode 100644 index 0000000000000000000000000000000000000000..70067da40972e5cdc980f6232a318a834b817ff6 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/DependentDecoderSampling.lean @@ -0,0 +1,117 @@ +import OAI.Computability.PerfectCompleteness.Decoding.TwoResponseCollisionLemmas +import OAI.Computability.PerfectCompleteness.Reduction.CompletionSoundness +import OAI.Computability.PerfectCompleteness.Sampling.RecursiveSamplerLaws + +namespace OAI + +section + +namespace PerfectCompleteness.DependentDecoderSampling + +noncomputable section + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games + +variable {Q₁ Q₂ E : Type*} [Fintype Q₁] [Fintype Q₂] [Fintype E] + [DecidableEq Q₁] [DecidableEq Q₂] + {A : Q₁ → Type*} {B : Q₂ → Type*} + [∀ q, Fintype (A q)] [∀ q, Fintype (B q)] + +abbrev Seed (A : Q₁ → Type*) (B : Q₂ → Type*) := + ((q : Q₁) → A q) × ((q : Q₂) → B q) + +def seedLaw (leftKernel : (q : Q₁) → FiniteDistribution (A q)) + (rightKernel : (q : Q₂) → FiniteDistribution (B q)) : + FiniteDistribution (Seed A B) := + (FiniteProduct.law leftKernel).product (FiniteProduct.law rightKernel) + +theorem read_law (leftKernel : (q : Q₁) → FiniteDistribution (A q)) + (rightKernel : (q : Q₂) → FiniteDistribution (B q)) (q₁ : Q₁) (q₂ : Q₂) : + (seedLaw leftKernel rightKernel).pushforward (fun seed => (seed.1 q₁, seed.2 q₂)) = + (leftKernel q₁).product (rightKernel q₂) := by + have h := FiniteDistribution.product_pushforward + (FiniteProduct.law leftKernel) (FiniteProduct.law rightKernel) + (fun table : (q : Q₁) → A q => table q₁) + (fun table : (q : Q₂) → B q => table q₂) + rw [FiniteProduct.eval_pushforward, FiniteProduct.eval_pushforward] at h + exact h + +def sampleLaw (μ : FiniteDistribution E) (left : E → Q₁) (right : E → Q₂) + (leftKernel : (q : Q₁) → FiniteDistribution (A q)) + (rightKernel : (q : Q₂) → FiniteDistribution (B q)) : + FiniteDistribution (Σ e : E, A (left e) × B (right e)) := + CompletionSoundness.sigmaLaw μ (fun e => (leftKernel (left e)).product (rightKernel (right e))) + +theorem sample_probability_eq (μ : FiniteDistribution E) (left : E → Q₁) (right : E → Q₂) + (leftKernel : (q : Q₁) → FiniteDistribution (A q)) + (rightKernel : (q : Q₂) → FiniteDistribution (B q)) + (event : (e : E) → A (left e) → B (right e) → Bool) : + (sampleLaw μ left right leftKernel rightKernel).probability + (fun x => event x.1 x.2.1 x.2.2) = + (seedLaw leftKernel rightKernel).expectation + (fun seed => μ.probability (fun e => event e (seed.1 (left e)) (seed.2 (right e)))) := by + rw [sampleLaw, CompletionSoundness.sigmaLaw_probability] + calc + _ = μ.expectation (fun e => (seedLaw leftKernel rightKernel).probability + (fun seed => event e (seed.1 (left e)) (seed.2 (right e)))) := by + apply FiniteDistribution.expectation_congr + intro e + have h := FiniteDistribution.probability_pushforward + (seedLaw leftKernel rightKernel) (fun seed => (seed.1 (left e), seed.2 (right e))) + (fun answer => event e answer.1 answer.2) + rw [read_law] at h + exact h + _ = μ.expectation (fun e => (seedLaw leftKernel rightKernel).expectation + (fun seed => if event e (seed.1 (left e)) (seed.2 (right e)) then 1 else 0)) := by + simp only [FiniteDistribution.probability, FiniteDistribution.expectation, + mul_ite, mul_one, mul_zero] + _ = (seedLaw leftKernel rightKernel).expectation (fun seed => μ.expectation + (fun e => if event e (seed.1 (left e)) (seed.2 (right e)) then 1 else 0)) := + FiniteDistribution.expectation_comm μ (seedLaw leftKernel rightKernel) _ + _ = _ := by + simp only [FiniteDistribution.probability, FiniteDistribution.expectation, + mul_ite, mul_one, mul_zero] + +theorem probability_le_of_supported_seeds + (μ : FiniteDistribution E) (left : E → Q₁) (right : E → Q₂) + (leftKernel : (q : Q₁) → FiniteDistribution (A q)) + (rightKernel : (q : Q₂) → FiniteDistribution (B q)) + (event : (e : E) → A (left e) → B (right e) → Bool) (bound : ℝ) + (hbound : ∀ seed, (seedLaw leftKernel rightKernel).weight seed ≠ 0 → + μ.probability (fun e => event e (seed.1 (left e)) (seed.2 (right e))) ≤ bound) : + (sampleLaw μ left right leftKernel rightKernel).probability + (fun x => event x.1 x.2.1 x.2.2) ≤ bound := by + rw [sample_probability_eq] + exact DecoderTableAdmissibility.expectation_le_of_support _ _ bound hbound + +theorem supported_left (leftKernel : (q : Q₁) → FiniteDistribution (A q)) + (rightKernel : (q : Q₂) → FiniteDistribution (B q)) + (seed : Seed A B) (hs : (seedLaw leftKernel rightKernel).weight seed ≠ 0) (q : Q₁) : + (leftKernel q).weight (seed.1 q) ≠ 0 := by + intro hq + apply hs + have hz : (FiniteProduct.law leftKernel).weight seed.1 = 0 := by + exact Finset.prod_eq_zero (Finset.mem_univ q) hq + change (FiniteProduct.law leftKernel).weight seed.1 * + (FiniteProduct.law rightKernel).weight seed.2 = 0 + rw [hz, zero_mul] + +theorem supported_right (leftKernel : (q : Q₁) → FiniteDistribution (A q)) + (rightKernel : (q : Q₂) → FiniteDistribution (B q)) + (seed : Seed A B) (hs : (seedLaw leftKernel rightKernel).weight seed ≠ 0) (q : Q₂) : + (rightKernel q).weight (seed.2 q) ≠ 0 := by + intro hq + apply hs + have hz : (FiniteProduct.law rightKernel).weight seed.2 = 0 := by + exact Finset.prod_eq_zero (Finset.mem_univ q) hq + change (FiniteProduct.law leftKernel).weight seed.1 * + (FiniteProduct.law rightKernel).weight seed.2 = 0 + rw [hz, mul_zero] + +end +end PerfectCompleteness.DependentDecoderSampling + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/FixedDecoderCleanRateLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/FixedDecoderCleanRateLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..43d789fd2265041bd3e2d94fb67e2b6d4252cfc2 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/FixedDecoderCleanRateLemmas.lean @@ -0,0 +1,138 @@ +import OAI.Computability.PerfectCompleteness.Decoding.CleanDecoderRateLemmas +import OAI.Computability.PerfectCompleteness.Repetition.FixedCleanRate + +namespace OAI + +section + +namespace PerfectCompleteness.FixedDecoderCleanRate + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +abbrev F2 := ZMod 2 + +structure Geometry {δ : ℚ} {hδ : 0 < δ} (p : FixedParameters.Parameters δ hδ) + (n h : Nat) (upper : Nodes (FixedParameters.branch p) n) + (d : HierarchicalFrozenTables.LowerNodes upper (h + 1)) where + designated : Fin (FixedParameters.branch p h) → Slots (FixedParameters.branch p) h + cut : OwnInputReference.Cut upper (HierarchicalLeftDecoder.LowerNode upper (h + 1) d) + outside : Slots (FixedParameters.branch p) n → + Fin (FixedRows.sourceLength p.plan hδ) → MixedSupport.Slot + placeholder : Slots (FixedParameters.branch p) (h + 1) → + Fin (FixedRows.sourceLength p.plan hδ) → MixedSupport.Slot + exterior : CleanPhysicalReplay.Exterior (FixedRows.rows p.plan) (FixedRows.repeats p.plan) + (CleanRecordDecoderInput.path upper d cut) outside placeholder + +variable {δ : ℚ} {hδ : 0 < δ} (p : FixedParameters.Parameters δ hδ) + {n h : Nat} {upper : Nodes (FixedParameters.branch p) n} + {d : HierarchicalFrozenTables.LowerNodes upper (h + 1)} + (G : Geometry p n h upper d) + +def setup (input : List Bool) : + CleanDecoderRate.Setup (FixedParameters.branch p) (FixedRows.rows p.plan) + (FixedRows.repeats p.plan) n h (FixedRows.sourceLength p.plan hδ) + (PCPSource.normalizedFormula (BinaryLanguage.totalRename input)).variables + (PCPSource.normalizedFormula (BinaryLanguage.totalRename input)).clauses.length + upper d where + clauses := PCPSource.clauseFamily (BinaryLanguage.totalRename input) + designated := G.designated + cut := G.cut + outside := G.outside + placeholder := G.placeholder + exterior := G.exterior + +theorem calls_le (input : List Bool) (hn : n ≤ p.plan.depth) : + Fintype.card (CleanDecoderRate.Calls (setup p G input)) ≤ FixedParameters.calls p.plan := by + have hactual := FixedCallBudget.modified_calls_le (FixedRows.rows p.plan) + (FixedRows.repeats p.plan) (CleanDecoderRate.path (setup p G input)) hn + apply hactual.trans + unfold FixedParameters.calls + omega + +theorem cubePositive (height : Nat) : 0 < p.cubeSize height := by + have hsize := (p.cube_errors height).1 + omega + +theorem branchPositive : ∀ k < n, 0 < FixedParameters.branch p k := + fun k _ => FixedParameters.branch_pos p k + +variable (input : List Bool) + (σ : KeyStrategy.Strategy + (TreeCanonical.locationCount (FixedParameters.branch p) n + (FixedRows.sourceLength p.plan hδ))) + (useful : (record : CleanDecoderRate.Record (setup p G input)) → + CleanLeftDecoder.Useful + (CleanDecoderContext.leftExposed (CleanDecoderRate.context (setup p G input) record)) + upper (h + 1)) + (r : Nat) (ρ : ℝ) (A : ManyGoodRows.RowMap (Block (FixedRows.rows p.plan) upper) r) + (W : Submodule F2 (OwnInputReference.UpperVector (FixedRows.rows p.plan) upper)) + (a : OwnInputReference.LowerVector (FixedRows.rows p.plan) + (HierarchicalLeftDecoder.LowerNode upper (h + 1) d)) + (threshold : ℝ) + +theorem probability_lt_accuracy (unsat : ¬ BinaryLanguage.language input) + (hn : n ≤ p.plan.depth) (hρ : 0 < ρ) : + (CleanDecoderRate.law (setup p G input) σ useful r ρ A W a threshold + (p.cubeSize h) (cubePositive p h)).probability + (fun z => CleanDecoderRate.agrees (setup p G input) (branchPositive p) + (FixedRows.cutoff p.plan hδ) z.1 z.2) < p.accuracy := by + have hbound := CleanDecoderRate.bound (setup p G input) σ useful r ρ A W a threshold + (branchPositive p) (cubePositive p h) hρ (FixedParameters.source_rate p input unsat) + apply hbound.trans_lt + simpa only [FixedParameters.branch] using + FixedCleanRate.actual_clean_error p (calls_le p G input hn) h + +end +end PerfectCompleteness.FixedDecoderCleanRate + +end + +section + +namespace PerfectCompleteness.FixedDecoderPairRate + +noncomputable section + +open scoped Classical +open TreeSourceSpaces HierarchicalArrays FixedDecoderCleanRate + +abbrev F2 := ZMod 2 + +variable {δ : ℚ} {hδ : 0 < δ} (p : FixedParameters.Parameters δ hδ) + {n h : Nat} {upper : Nodes (FixedParameters.branch p) n} + {d : HierarchicalFrozenTables.LowerNodes upper (h + 1)} + (G : Geometry p n h upper d) + (input : List Bool) + (σ : KeyStrategy.Strategy + (TreeCanonical.locationCount (FixedParameters.branch p) n + (FixedRows.sourceLength p.plan hδ))) + (useful : (record : CleanDecoderRate.Record (setup p G input)) → + CleanLeftDecoder.Useful + (CleanDecoderContext.leftExposed (CleanDecoderRate.context (setup p G input) record)) + upper (h + 1)) + (r : Nat) (ρ : ℝ) (A : ManyGoodRows.RowMap (Block (FixedRows.rows p.plan) upper) r) + (W : Submodule F2 (OwnInputReference.UpperVector (FixedRows.rows p.plan) upper)) + (a : OwnInputReference.LowerVector (FixedRows.rows p.plan) + (HierarchicalLeftDecoder.LowerNode upper (h + 1) d)) + (threshold : ℝ) + +theorem probability_lt_accuracy (unsat : ¬ BinaryLanguage.language input) + (hn : n ≤ p.plan.depth) (hρ : 0 < ρ) : + (CleanDecoderPairLaw.pairLaw (setup p G input) σ useful r ρ A W a threshold + (p.cubeSize h) (cubePositive p h)).probability + (fun z => CleanDecoderPairLaw.pairAgrees (setup p G input) (branchPositive p) + (FixedRows.cutoff p.plan hδ) z.1 z.2) < p.accuracy := by + rw [CleanDecoderPairLaw.pair_probability_eq] + exact FixedDecoderCleanRate.probability_lt_accuracy p G input σ useful r ρ A W a threshold + unsat hn hρ + +end +end PerfectCompleteness.FixedDecoderPairRate + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/FixedLowerUniformCollision.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/FixedLowerUniformCollision.lean new file mode 100644 index 0000000000000000000000000000000000000000..d7cf5a2ab1ea49d28a58a0171b6b96edeb77ca46 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/FixedLowerUniformCollision.lean @@ -0,0 +1,117 @@ +import OAI.Computability.PerfectCompleteness.Construction.BucketFullAgreement +import OAI.Computability.PerfectCompleteness.Decoding.HierarchicalLowerInverseLemmas +import OAI.Computability.PerfectCompleteness.Foundations.MultiplicationFormInjectiveLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.FixedLowerUniformCollision + +noncomputable section + +open scoped BigOperators Classical +open TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +attribute [local instance] UniqueGamesTheorem.Appendix.RankLevelFilter.linearMapFintype + +private theorem expectation_uniform_eq_expect {A : Type*} [Fintype A] [Nonempty A] + (f : A → ℝ) : + (FiniteDistribution.uniform A).expectation f = 𝔼 x : A, f x := by + rw [FiniteDistribution.expectation_uniform, Fintype.expect_eq_sum_div_card] + +section Uniform + +variable {Ω Y : Type*} [Fintype Y] + (V : Submodule F2 (Ω → F2)) [Fintype V] [FiniteDimensional F2 V] + (ℓ : Nat) [Nonempty (BucketSampler.Direction ℓ)] + +def uniformLaw : FiniteDistribution + (BucketSampler.Direction ℓ × (BucketMatrixResampling.Matrix V ℓ × V)) := + (FiniteDistribution.uniform (BucketSampler.Direction ℓ)).product + ((FiniteDistribution.uniform (BucketMatrixResampling.Matrix V ℓ)).product + (FiniteDistribution.uniform V)) + +def uniformCollision (f : BucketMatrixResampling.Matrix V ℓ → Option Y) + (x : BucketSampler.Direction ℓ × (BucketMatrixResampling.Matrix V ℓ × V)) : Bool := + TwoResponseCollision.collision f + (x.2.1, EvaluationMatrix.shift V x.2.1 x.1.val x.2.2) + +theorem uniform_collision_eq (f : BucketMatrixResampling.Matrix V ℓ → Option Y) : + (uniformLaw V ℓ).probability (uniformCollision V ℓ f) = + PartialTableInverse.nonzeroAgreement f := by + unfold uniformLaw uniformCollision + rw [BucketQuotientAgreement.probability_collision_eq_expectation] + simp only [FiniteDistribution.expectation_product, expectation_uniform_eq_expect] + calc + _ = FiniteRangeInverse.agreement f := by + unfold FiniteRangeInverse.agreement + refine Finset.expect_congr (ι := BucketSampler.Direction ℓ) ?_ ?_ + · ext a + simp only [Finset.mem_univ] + intro a _ + rfl + _ = _ := FiniteRangeInverse.agreement_eq_nonzeroAgreement f + +end Uniform + +variable {δ : ℚ} (plan : FixedRows.Plan δ) (hδ : 0 < δ) + {branch : Nat → Nat} {t : Nat} + (slots : RecursiveSpaces.Slots branch plan.depth → Fin t → MixedSupport.Slot) + (upper : Nodes branch plan.depth) (lowerLevel : Nat) + (background : HierarchicalMatrixTable.Background (rows := FixedRows.rows plan) slots upper) + +local instance lowerHFintype (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) : + Fintype (HierarchicalDecoderTables.LowerH slots upper lowerLevel d) := Fintype.ofFinite _ + +local instance upperDualFintype : + Fintype (HierarchicalAllDecoderTables.UpperAnswer slots upper) := + HierarchicalAllDecoderTables.upperDualFintype slots upper + +variable (hbranch : ∀ k < plan.depth, 0 < branch k) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch plan.depth t)) + (useful : (bg : HierarchicalMatrixTable.Background + (rows := FixedRows.rows plan) slots upper) → + HierarchicalFrozenTables.QuotientMatrix slots upper lowerLevel bg → Prop) + +include hbranch σ useful + +local instance directionNonempty (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) : + Nonempty (BucketSampler.Direction + (FixedRows.rows plan (Nodes.height (HierarchicalLeftDecoder.LowerNode upper lowerLevel d)))) := + ⟨BucketUniform.coordinateDirection ⟨0, + lt_of_lt_of_le Nat.zero_lt_one + (plan.rows_pos (plan.depth - + Nodes.height (HierarchicalLeftDecoder.LowerNode upper lowerLevel d)))⟩⟩ + +theorem supported_collision_lt {adviceRows : Nat} + (density : ℝ) (hdensity : 0 < density) + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) + (upperMatrix : HierarchicalMatrixTable.Matrix (rows := FixedRows.rows plan) slots upper) + (A : ManyGoodRows.RowMap (Block (FixedRows.rows plan) upper) adviceRows) + (table : HierarchicalAllDecoderTables.Input + (rows := FixedRows.rows plan) slots upper lowerLevel adviceRows → + HierarchicalAllDecoderTables.UpperAnswer slots upper) + (hsupport : (HierarchicalAllDecoderTables.upperTableLaw slots upper lowerLevel σ useful + adviceRows density).weight table ≠ 0) : + (uniformLaw (HierarchicalDecoderTables.LowerH slots upper lowerLevel d) + (FixedRows.rows plan (Nodes.height (HierarchicalLeftDecoder.LowerNode upper lowerLevel d)))).probability + (uniformCollision _ _ + (HierarchicalLowerInverse.matrixTable slots upper lowerLevel background d upperMatrix A + (HierarchicalAllDecoderTables.decodeTable slots upper lowerLevel hbranch adviceRows d + (FixedRows.cutoff plan hδ) table))) < + UpperParameterScalars.gamma (InitialParameters.useful δ) plan.density + (InitialParameters.inverse δ) plan.order + (FixedRows.rows plan (Nodes.height upper)) ^ 2 / 8 := by + rw [uniform_collision_eq] + exact HierarchicalFixedLowerInverse.supported_upper_matrixTable_agreement_lt + plan hδ slots upper lowerLevel background hbranch σ useful density hdensity + d upperMatrix A table hsupport + +end +end PerfectCompleteness.FixedLowerUniformCollision + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/FixedProjectionErrorLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/FixedProjectionErrorLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..9114e5576eec7d183354fa64ad02dfcf833c217a --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/FixedProjectionErrorLemmas.lean @@ -0,0 +1,141 @@ +import OAI.Computability.PerfectCompleteness.Decoding.ChildFiniteCallCollisionTransfer +import OAI.Computability.PerfectCompleteness.Foundations.ProjectedPrefixComparison +import OAI.Computability.PerfectCompleteness.Reduction.FixedComparisonErrorsLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.FixedProjectionError + +open FixedParameters FixedRows + +noncomputable section + +variable {δ : ℚ} {hδ : 0 < δ} (p : Parameters δ hδ) + +theorem sparse_error_lt {retained : Nat} (hcalls : retained ≤ calls p.plan) + (height : Nat) : + Real.sqrt ((1 + (projectionProbability p height : ℝ) ^ 2 * + ((ChildBlockCardinality.bound (branch p) height (sourceLength p.plan hδ) + retained (rows p.plan) : ℝ) - 1)) ^ branch p height - 1) / 2 < p.accuracy := by + let L : ℝ := ChildBlockCardinality.bound (branch p) height (sourceLength p.plan hδ) + retained (rows p.plan) + let m : ℝ := p.cubeSize height + have hL : 1 ≤ L := by + dsimp only [L] + exact_mod_cast Nat.one_le_iff_ne_zero.mpr + (Nat.ne_of_gt (ChildBlockCardinality.shape_bound_pos (branch p) height + (sourceLength p.plan hδ) retained (rows p.plan))) + have hm4 : 0 ≤ m ^ 4 := by positivity + have hbeta : (projectionProbability p height : ℝ) ^ 2 = 1 / m ^ 4 := by + simp only [projectionProbability, Rat.cast_div, Rat.cast_one, Rat.cast_pow, + Rat.cast_natCast] + dsimp only [m] + ring + have hbase : 1 + (projectionProbability p height : ℝ) ^ 2 * (L - 1) ≤ + 1 + L ^ 2 / m ^ 4 := by + rw [hbeta] + have hsq : L - 1 ≤ L ^ 2 := by nlinarith + have hdiv := div_le_div_of_nonneg_right hsq hm4 + calc + 1 + (1 / m ^ 4) * (L - 1) = 1 + (L - 1) / m ^ 4 := by ring + _ ≤ 1 + L ^ 2 / m ^ 4 := by linarith + have hnonneg : 0 ≤ 1 + (projectionProbability p height : ℝ) ^ 2 * (L - 1) := by + have : 0 ≤ L - 1 := by linarith + positivity + have h := (FixedComparisonErrors.comparison_errors p hcalls height).2.1 + change Real.sqrt ((1 + (projectionProbability p height : ℝ) ^ 2 * (L - 1)) ^ + (p.cubeSize height ^ 3) - 1) / 2 < p.accuracy + apply lt_of_le_of_lt _ h + apply div_le_div_of_nonneg_right _ (by norm_num : (0 : ℝ) ≤ 2) + apply Real.sqrt_le_sqrt + exact sub_le_sub_right (pow_le_pow_left₀ hnonneg hbase _) 1 + +end +end PerfectCompleteness.FixedProjectionError + +end + +section + +namespace PerfectCompleteness.FixedChildCollisionTransfer + +noncomputable section + +open scoped Classical +open FixedParameters FixedRows RecursiveSpaces DescendantSpaces TreeSourceSpaces +open UniqueGamesTheorem.Foundations.Games + +variable {δ : ℚ} {hδ : 0 < δ} (parameters : Parameters δ hδ) + +theorem posterior_error_lt {retained : Nat} + (hcalls : retained ≤ calls parameters.plan) (height : Nat) : + 2 * ((projectionProbability parameters height : ℝ) * + (ChildBlockCardinality.bound (branch parameters) height + (sourceLength parameters.plan hδ) retained (rows parameters.plan) : ℝ) / + (1 - (projectionProbability parameters height : ℝ))) < parameters.accuracy := by + have h := (FixedComparisonErrors.comparison_errors parameters hcalls height).2.2 + simpa only [projectionProbability, Rat.cast_div, Rat.cast_one, Rat.cast_pow, + Rat.cast_natCast] using h + +theorem lower_pair_calls_le {n height : Nat} + (path : Path (branch parameters) n (height + 1)) (hn : n ≤ parameters.plan.depth) : + Fintype.card (Option + (WholeCutCalls.Index (rows parameters.plan) (repeats parameters.plan) path)) ≤ + calls parameters.plan := by + have h := FixedCallBudget.modified_calls_le (rows parameters.plan) + (repeats parameters.plan) path hn + rw [Fintype.card_option] + unfold calls + omega + +variable {height : Nat} {C : Type*} [Fintype C] + {Z : Fin (branch parameters height) → Type*} [∀ i, Fintype (Z i)] + +theorem marked_restricted_lt_uniform_full + (hcalls : Fintype.card C ≤ calls parameters.plan) + (slots : Slots (branch parameters) (height + 1) → + Fin (sourceLength parameters.plan hδ) → MixedSupport.Slot) + (projected : (i : Fin (branch parameters height)) → Z i → + Slots (branch parameters) height → Fin (sourceLength parameters.plan hδ) → + MixedSupport.Slot) + (projection : ∀ i z s k, MixedSupport.Projection + (childSlots slots i s k) (projected i z s k)) + (choiceLaw : (i : Fin (branch parameters height)) → FiniteDistribution (Z i)) + (F₀ F₁ : CutChildGrouping.Raw (C := C) slots (rows parameters.plan) → + Option (ChildBilinearCollisionTransfer.ParentForm slots)) : + (SparseReplacement.markedLaw + (fun i => FiniteDistribution.uniform + (ChildCallNumbering.Raw (C := C) (rows parameters.plan) (childSlots slots i))) + (ChildCallNumberingLaws.replacementLaws (C := C) (rows parameters.plan) + (childSlots slots) projected projection choiceLaw) + (projectionProbability parameters height : ℝ) + (by exact_mod_cast (projectionProbability_bounds parameters height).1.le) + (by exact_mod_cast (projectionProbability_bounds parameters height).2.le)).probability + (fun z => BilinearCollisionTransfer.restrictedCollision + (F₀ z.2) (F₁ z.2) (ChildUnmarkedSpace.space slots z.1)) < + (CutChildGrouping.rawLaw (C := C) slots (rows parameters.plan)).probability + (fun raw => BilinearCollisionTransfer.fullCollision (F₀ raw) (F₁ raw)) + + 2 * parameters.accuracy := by + have hβ : 0 ≤ (projectionProbability parameters height : ℝ) := by + exact_mod_cast (projectionProbability_bounds parameters height).1.le + have hβ' : (projectionProbability parameters height : ℝ) < 1 := by + exact_mod_cast (projectionProbability_bounds parameters height).2 + have htransfer := ChildFiniteCallCollisionTransfer.marked_restricted_le_uniform_full + (C := C) (rows parameters.plan) slots projected projection choiceLaw + (projectionProbability parameters height : ℝ) hβ hβ' F₀ F₁ + have hposterior := posterior_error_lt parameters hcalls height + have hvariation := FixedProjectionError.sparse_error_lt parameters hcalls height + change _ < (FiniteProduct.law (fun i => FiniteDistribution.uniform + (ChildCallNumbering.Raw (C := C) (rows parameters.plan) (childSlots slots i)))).probability + (fun raw => BilinearCollisionTransfer.fullCollision (F₀ raw) (F₁ raw)) + + 2 * parameters.accuracy + linarith + +end +end PerfectCompleteness.FixedChildCollisionTransfer + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/FixedSourceChildCollision.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/FixedSourceChildCollision.lean new file mode 100644 index 0000000000000000000000000000000000000000..64886314b72d67bbfac2c18592888c425fe3683f --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/FixedSourceChildCollision.lean @@ -0,0 +1,118 @@ +import OAI.Computability.PerfectCompleteness.Decoding.FixedProjectionErrorLemmas +import OAI.Computability.PerfectCompleteness.Sampling.SourceChildMarkedLaw + +namespace OAI + +section + +namespace PerfectCompleteness.FixedSourceChildCollision + +noncomputable section + +open scoped Classical BigOperators +open FixedParameters FixedRows RecursiveSpaces DescendantSpaces TreeSourceSpaces +open UniqueGamesTheorem.Foundations.Games + +variable {δ : ℚ} {hδ : 0 < δ} (parameters : Parameters δ hδ) + {n height v m : Nat} [NeZero m] + (path : Path (branch parameters) n (height + 1)) + (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch parameters height) → Slots (branch parameters) height) + +abbrev Calls := Option (WholeCutCalls.Index (rows parameters.plan) (repeats parameters.plan) path) + +abbrev Questions := SourceChildMarkedLaw.Questions + (branch := branch parameters) (n := height) + (t := sourceLength parameters.plan hδ) (m := m) + +abbrev Native (q : Questions (m := m) parameters (height := height)) := + CutChildGrouping.Raw (C := Calls parameters path) + (SourceChildMarkedLaw.questionSlots clauses q) (rows parameters.plan) + +abbrev Form (q : Questions (m := m) parameters (height := height)) := + ChildBilinearCollisionTransfer.ParentForm (SourceChildMarkedLaw.questionSlots clauses q) + +abbrev Sample := SourceChildKernel.Sample (C := Calls parameters path) + (t := sourceLength parameters.plan hδ) (rows parameters.plan) clauses designated + +def markedLaw : FiniteDistribution (Sample parameters path clauses designated) := + SourceChildKernel.originalLaw (C := Calls parameters path) + (t := sourceLength parameters.plan hδ) (rows parameters.plan) clauses designated + (fun _ => ProjectionPosterior.bernoulli (projectionProbability parameters height : ℝ) + (by exact_mod_cast (projectionProbability_bounds parameters height).1.le) + (by exact_mod_cast (projectionProbability_bounds parameters height).2.le)) + +def uniformLaw : FiniteDistribution + (Σ q : Questions (m := m) parameters (height := height), Native parameters path clauses q) := + CompletionSoundness.sigmaLaw + (PreliminarySampler.questionsLaw (branch := branch parameters) (n := height + 1) + (t := sourceLength parameters.plan hδ) (m := m)) + (fun q => CutChildGrouping.rawLaw (C := Calls parameters path) + (SourceChildMarkedLaw.questionSlots clauses q) (rows parameters.plan)) + +variable (F₀ F₁ : (q : Questions (m := m) parameters (height := height)) → + Native parameters path clauses q → Option (Form parameters clauses q)) + +def restrictedEvent (sample : Sample parameters path clauses designated) : Bool := + let record := SourceChildMarkedLaw.observe (rows parameters.plan) clauses designated sample + BilinearCollisionTransfer.restrictedCollision + (F₀ record.1 record.2.2) (F₁ record.1 record.2.2) + (ChildUnmarkedSpace.space (SourceChildMarkedLaw.questionSlots clauses record.1) record.2.1) + +def fullEvent (record : + Σ q : Questions (m := m) parameters (height := height), Native parameters path clauses q) : Bool := + BilinearCollisionTransfer.fullCollision (F₀ record.1 record.2) (F₁ record.1 record.2) + +private theorem expectation_add_const {A : Type*} [Fintype A] + (μ : FiniteDistribution A) (f : A → ℝ) (c : ℝ) : + μ.expectation (fun x => f x + c) = μ.expectation f + c := by + simp only [FiniteDistribution.expectation, mul_add, Finset.sum_add_distrib, + ← Finset.sum_mul, μ.normalized, one_mul] + +theorem restricted_probability_le (hn : n ≤ parameters.plan.depth) : + (markedLaw parameters path clauses designated).probability + (restrictedEvent parameters path clauses designated F₀ F₁) ≤ + (uniformLaw parameters path clauses).probability + (fullEvent parameters path clauses F₀ F₁) + 2 * parameters.accuracy := by + have hβ : 0 ≤ (projectionProbability parameters height : ℝ) := by + exact_mod_cast (projectionProbability_bounds parameters height).1.le + have hβ' : (projectionProbability parameters height : ℝ) ≤ 1 := by + exact_mod_cast (projectionProbability_bounds parameters height).2.le + have hlaw := SourceChildMarkedLaw.original_extended_marked_law + (t := sourceLength parameters.plan hδ) (rows parameters.plan) clauses designated + (repeats parameters.plan) path (projectionProbability parameters height : ℝ) hβ hβ' + have hprob := congrArg + (fun μ : FiniteDistribution + (SourceChildMarkedLaw.Observation (C := Calls parameters path) + (t := sourceLength parameters.plan hδ) (rows parameters.plan) clauses) => + μ.probability (fun record => BilinearCollisionTransfer.restrictedCollision + (F₀ record.1 record.2.2) (F₁ record.1 record.2.2) + (ChildUnmarkedSpace.space (SourceChildMarkedLaw.questionSlots clauses record.1) + record.2.1))) hlaw + rw [FiniteDistribution.probability_pushforward, + CompletionSoundness.sigmaLaw_probability] at hprob + rw [show (markedLaw parameters path clauses designated).probability + (restrictedEvent parameters path clauses designated F₀ F₁) = _ from hprob] + rw [uniformLaw, CompletionSoundness.sigmaLaw_probability] + have hpoint := fun q : Questions (m := m) parameters (height := height) => + (FixedChildCollisionTransfer.marked_restricted_lt_uniform_full parameters + (FixedChildCollisionTransfer.lower_pair_calls_le parameters path hn) + (SourceChildMarkedLaw.questionSlots clauses q) + (SourceChildMarkedLaw.projectedSlots clauses designated q) + (SourceChildMarkedLaw.questionProjection clauses designated q) + (fun _ => FiniteDistribution.uniform + (SourceChildMarkedLaw.Choice (branch := branch parameters) (n := height) + (t := sourceLength parameters.plan hδ))) + (F₀ q) (F₁ q)).le + have havg := SmallBias.expectation_mono + (PreliminarySampler.questionsLaw (branch := branch parameters) (n := height + 1) + (t := sourceLength parameters.plan hδ) (m := m)) hpoint + rw [expectation_add_const] at havg + simpa only [← SourceChildMarkedLaw.replacementLaws_eq, fullEvent] using havg + +end +end PerfectCompleteness.FixedSourceChildCollision + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/FixedSourceLowerCollision.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/FixedSourceLowerCollision.lean new file mode 100644 index 0000000000000000000000000000000000000000..cd3ad6c80fe0d38d919fc17b81e946e78f54164c --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/FixedSourceLowerCollision.lean @@ -0,0 +1,214 @@ +import OAI.Computability.PerfectCompleteness.Decoding.FixedSourceChildCollision +import OAI.Computability.PerfectCompleteness.Decoding.LowerCutScalarProjectionLemmas +import OAI.Computability.PerfectCompleteness.Decoding.LowerCutUniformCoordinatesLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.FixedSourceLowerCollision + +noncomputable section + +open scoped Classical BigOperators +open FixedParameters FixedRows RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +variable {δ : ℚ} {hδ : 0 < δ} (parameters : Parameters δ hδ) + {height v m : Nat} [NeZero m] + (path : Path (branch parameters) parameters.plan.depth (height + 1)) + (outside : Slots (branch parameters) parameters.plan.depth → + Fin (sourceLength parameters.plan hδ) → MixedSupport.Slot) + (placeholder : Slots (branch parameters) (height + 1) → + Fin (sourceLength parameters.plan hδ) → MixedSupport.Slot) + (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch parameters height) → Slots (branch parameters) height) + (upper : Nodes (branch parameters) parameters.plan.depth) + (d : HierarchicalFrozenTables.LowerNodes upper (height + 1)) + (hnode : WholeArrayInteriorExterior.upperNode path = + HierarchicalLeftDecoder.LowerNode upper (height + 1) d) + {adviceRows : Nat} + (A : ManyGoodRows.RowMap (Block (rows parameters.plan) upper) adviceRows) + (exterior : CleanPhysicalReplay.Exterior (rows parameters.plan) (repeats parameters.plan) + path outside placeholder) + +abbrev Questions := FixedSourceChildCollision.Questions + (m := m) parameters (height := height) + +abbrev Table (q : Questions (m := m) parameters (height := height)) := + SourceQuestionLowerForms.UpperTable (rows := rows parameters.plan) + path outside clauses upper (height + 1) (adviceRows := adviceRows) q + +local instance rowSpaceFintype (q : Questions (m := m) parameters (height := height)) : + Fintype (NodeEmbedding.RowSpace (SourceQuestionLowerForms.slots path outside clauses q) upper) := + Fintype.ofFinite _ + +local instance upperAnswerFintype (q : Questions (m := m) parameters (height := height)) : + Fintype (HierarchicalAllDecoderTables.UpperAnswer + (SourceQuestionLowerForms.slots path outside clauses q) upper) := + LeftDecoder.dualFintype + (V := NodeEmbedding.RowSpace (SourceQuestionLowerForms.slots path outside clauses q) upper) + +local instance tableFintype (q : Questions (m := m) parameters (height := height)) : + Fintype (Table parameters path outside clauses upper (adviceRows := adviceRows) q) := + inferInstanceAs (Fintype (HierarchicalAllDecoderTables.Input (rows := rows parameters.plan) + (SourceQuestionLowerForms.slots path outside clauses q) upper (height + 1) adviceRows → + HierarchicalAllDecoderTables.UpperAnswer + (SourceQuestionLowerForms.slots path outside clauses q) upper)) + +abbrev TableFamily := (q : Questions (m := m) parameters (height := height)) → + Table parameters path outside clauses upper (adviceRows := adviceRows) q + +local instance directionNonempty : + Nonempty (BucketSampler.Direction (rows parameters.plan (height + 1))) := + ⟨BucketUniform.coordinateDirection ⟨0, lt_of_lt_of_le Nat.zero_lt_one + (parameters.plan.rows_pos (parameters.plan.depth - (height + 1)))⟩⟩ + +def first (tables : TableFamily parameters path outside clauses upper (adviceRows := adviceRows)) := + SourceQuestionLowerForms.first path outside placeholder clauses upper (height + 1) d hnode + (FixedLowerRawCollision.branchPositive parameters) A exterior tables (cutoff parameters.plan hδ) + +def second (tables : TableFamily parameters path outside clauses upper (adviceRows := adviceRows)) + (direction : BucketSampler.Direction (rows parameters.plan (height + 1))) := + SourceQuestionLowerForms.second path outside placeholder clauses upper (height + 1) d hnode + (FixedLowerRawCollision.branchPositive parameters) A exterior tables (cutoff parameters.plan hδ) + direction + +def markedProbability + (tables : TableFamily parameters path outside clauses upper (adviceRows := adviceRows)) + (direction : BucketSampler.Direction (rows parameters.plan (height + 1))) : ℝ := + (FixedSourceChildCollision.markedLaw parameters path clauses designated).probability + (FixedSourceChildCollision.restrictedEvent parameters path clauses designated + (first parameters path outside placeholder clauses upper d hnode A exterior tables) + (second parameters path outside placeholder clauses upper d hnode A exterior tables direction)) + +def uniformProbability + (tables : TableFamily parameters path outside clauses upper (adviceRows := adviceRows)) + (direction : BucketSampler.Direction (rows parameters.plan (height + 1))) : ℝ := + (FixedSourceChildCollision.uniformLaw parameters path clauses).probability + (FixedSourceChildCollision.fullEvent parameters path clauses + (first parameters path outside placeholder clauses upper d hnode A exterior tables) + (second parameters path outside placeholder clauses upper d hnode A exterior tables direction)) + +variable + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount (branch parameters) parameters.plan.depth + (sourceLength parameters.plan hδ))) + (useful : (q : Questions (m := m) parameters (height := height)) → + (bg : HierarchicalMatrixTable.Background (rows := rows parameters.plan) + (SourceQuestionLowerForms.slots path outside clauses q) upper) → + HierarchicalFrozenTables.QuotientMatrix + (SourceQuestionLowerForms.slots path outside clauses q) upper (height + 1) bg → Prop) + (density : ℝ) + +def tableLaw : FiniteDistribution + (TableFamily parameters path outside clauses upper (adviceRows := adviceRows)) := + FiniteProduct.law (fun q => HierarchicalAllDecoderTables.upperTableLaw + (SourceQuestionLowerForms.slots path outside clauses q) upper (height + 1) + σ (useful q) adviceRows density) + +omit [NeZero m] in +private theorem supported_row + (tables : TableFamily parameters path outside clauses upper (adviceRows := adviceRows)) + (hsupport : (tableLaw parameters path outside clauses upper σ useful density).weight tables ≠ 0) + (q : Questions (m := m) parameters (height := height)) : + (HierarchicalAllDecoderTables.upperTableLaw + (SourceQuestionLowerForms.slots path outside clauses q) upper (height + 1) + σ (useful q) adviceRows density).weight (tables q) ≠ 0 := by + intro hz + apply hsupport + exact Finset.prod_eq_zero (Finset.mem_univ q) hz + +theorem supported_uniform_le (hdensity : 0 < density) + (tables : TableFamily parameters path outside clauses upper (adviceRows := adviceRows)) + (hsupport : (tableLaw parameters path outside clauses upper σ useful density).weight tables ≠ 0) : + (FiniteDistribution.uniform (BucketSampler.Direction (rows parameters.plan (height + 1)))).expectation + (uniformProbability parameters path outside placeholder clauses upper d hnode A exterior tables) ≤ + FixedRankContradiction.gamma parameters (Nodes.height upper) ^ 2 / 8 := by + have hprob : + uniformProbability parameters path outside placeholder clauses upper d hnode A exterior tables = + fun direction => (PreliminarySampler.questionsLaw + (branch := branch parameters) (n := height + 1) + (t := sourceLength parameters.plan hδ) (m := m)).expectation (fun q => + (CutChildGrouping.rawLaw (C := FixedSourceChildCollision.Calls parameters path) + (SourceChildMarkedLaw.questionSlots clauses q) (rows parameters.plan)).probability + (fun raw => BilinearCollisionTransfer.fullCollision + (first parameters path outside placeholder clauses upper d hnode A exterior tables q raw) + (second parameters path outside placeholder clauses upper d hnode A exterior tables + direction q raw))) := by + funext direction + exact CompletionSoundness.sigmaLaw_probability _ _ _ + rw [hprob, FiniteDistribution.expectation_comm] + calc + _ ≤ (PreliminarySampler.questionsLaw (branch := branch parameters) (n := height + 1) + (t := sourceLength parameters.plan hδ) (m := m)).expectation + (fun _ => FixedRankContradiction.gamma parameters (Nodes.height upper) ^ 2 / 8) := by + apply SmallBias.expectation_mono + intro q + have heq : + (FiniteDistribution.uniform (BucketSampler.Direction + (rows parameters.plan (height + 1)))).expectation + (fun direction => (CutChildGrouping.rawLaw + (C := FixedSourceChildCollision.Calls parameters path) + (SourceChildMarkedLaw.questionSlots clauses q) (rows parameters.plan)).probability + (fun raw => BilinearCollisionTransfer.fullCollision + (first parameters path outside placeholder clauses upper d hnode A exterior tables q raw) + (second parameters path outside placeholder clauses upper d hnode A exterior tables + direction q raw))) = + FixedLowerRawCollision.fullCollisionProbability parameters path + (SourceQuestionLowerForms.slots path outside clauses q) upper d hnode A + (CleanPhysicalReplay.exteriorAt (rows parameters.plan) (repeats parameters.plan) + path outside placeholder (SourceChildMarkedLaw.questionSlots clauses q) exterior) + (tables q) := by + apply FiniteDistribution.expectation_congr + intro direction + exact SourceQuestionLowerForms.fullCollision_probability path outside placeholder clauses upper + (height + 1) d hnode (FixedLowerRawCollision.branchPositive parameters) A exterior tables + (cutoff parameters.plan hδ) direction q + rw [heq] + exact FixedLowerRawCollision.supported_fullCollision_le parameters path + (SourceQuestionLowerForms.slots path outside clauses q) upper d hnode A + (CleanPhysicalReplay.exteriorAt (rows parameters.plan) (repeats parameters.plan) + path outside placeholder (SourceChildMarkedLaw.questionSlots clauses q) exterior) + σ (useful q) density hdensity (tables q) + (supported_row parameters path outside clauses upper σ useful density tables hsupport q) + _ = _ := SmallBias.expectation_const _ _ + +private theorem expectation_add_const {X : Type*} [Fintype X] + (μ : FiniteDistribution X) (f : X → ℝ) (c : ℝ) : + μ.expectation (fun x => f x + c) = μ.expectation f + c := by + simp only [FiniteDistribution.expectation, mul_add, Finset.sum_add_distrib, + ← Finset.sum_mul, μ.normalized, one_mul] + +theorem mean_marked_le (hdensity : 0 < density) : + (tableLaw parameters path outside clauses upper σ useful density).expectation + (fun tables => (FiniteDistribution.uniform + (BucketSampler.Direction (rows parameters.plan (height + 1)))).expectation + (markedProbability parameters path outside placeholder clauses designated upper d hnode + A exterior tables)) ≤ + FixedRankContradiction.gamma parameters (Nodes.height upper) ^ 2 / 8 + + 2 * parameters.accuracy := by + apply DecoderTableAdmissibility.expectation_le_of_support + intro tables hsupport + have hpoint : ∀ direction : BucketSampler.Direction (rows parameters.plan (height + 1)), + markedProbability parameters path outside placeholder clauses designated upper d hnode + A exterior tables direction ≤ + uniformProbability parameters path outside placeholder clauses upper d hnode + A exterior tables direction + 2 * parameters.accuracy := by + intro direction + exact FixedSourceChildCollision.restricted_probability_le parameters path clauses designated + (first parameters path outside placeholder clauses upper d hnode A exterior tables) + (second parameters path outside placeholder clauses upper d hnode A exterior tables direction) + le_rfl + have hmean := SmallBias.expectation_mono + (FiniteDistribution.uniform (BucketSampler.Direction (rows parameters.plan (height + 1)))) hpoint + rw [expectation_add_const] at hmean + have huniform := supported_uniform_le parameters path outside placeholder clauses upper d hnode A exterior + σ useful density hdensity tables hsupport + linarith + +end +end PerfectCompleteness.FixedSourceLowerCollision + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/FixedSourceProjectionComparison.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/FixedSourceProjectionComparison.lean new file mode 100644 index 0000000000000000000000000000000000000000..ad8141cd175d8375a2c584827a736593e01cbcc2 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/FixedSourceProjectionComparison.lean @@ -0,0 +1,87 @@ +import OAI.Computability.PerfectCompleteness.Decoding.FixedProjectionErrorLemmas +import OAI.Computability.PerfectCompleteness.Decoding.SourceChildProjectionComparison + +namespace OAI + +section + +namespace PerfectCompleteness.FixedSourceProjectionComparison + +open FixedParameters FixedRows RecursiveSpaces +open UniqueGamesTheorem.Foundations.Games +open scoped Classical + +noncomputable section + +variable {δ : ℚ} {hδ : 0 < δ} (p : Parameters δ hδ) + +def projectionFlag (height : Nat) : FiniteDistribution Bool := + ProjectionPosterior.bernoulli (projectionProbability p height : ℝ) + (by exact_mod_cast (projectionProbability_bounds p height).1.le) + (by exact_mod_cast (projectionProbability_bounds p height).2.le) + +variable {v m height : Nat} {C : Type*} [Fintype C] + (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch p height) → Slots (branch p) height) + +abbrev Observation := + SourcePhysicalAssemblyLaw.Observation (C := C) (t := sourceLength p.plan hδ) + (rows p.plan) clauses designated + +def mixedLaw [NeZero m] : FiniteDistribution (Observation (C := C) p clauses designated) := + (SourceChildKernel.originalLaw (C := C) (t := sourceLength p.plan hδ) + (rows p.plan) clauses designated (fun _ => projectionFlag p height)).pushforward + (SourcePhysicalAssemblyLaw.observe (rows p.plan) clauses designated) + +def uniformLaw [NeZero m] : FiniteDistribution (Observation (C := C) p clauses designated) := + (SourceChildKernel.originalLaw (C := C) (t := sourceLength p.plan hδ) + (rows p.plan) clauses designated (fun _ => SourceChildNativeLaw.falseFlag)).pushforward + (SourcePhysicalAssemblyLaw.observe (rows p.plan) clauses designated) + +theorem observed_totalVariation_lt [NeZero m] {Γ : Type*} [Fintype Γ] + (hcalls : Fintype.card C ≤ calls p.plan) + (observe : Observation (C := C) p clauses designated → Γ) : + ((mixedLaw p clauses designated).pushforward observe).totalVariation + ((uniformLaw p clauses designated).pushforward observe) < p.accuracy := by + have hβ : 0 ≤ (projectionProbability p height : ℝ) := by + exact_mod_cast (projectionProbability_bounds p height).1.le + have hβ' : (projectionProbability p height : ℝ) ≤ 1 := by + exact_mod_cast (projectionProbability_bounds p height).2.le + have h := SourceChildProjectionComparison.original_observed_variation + (C := C) (t := sourceLength p.plan hδ) (rows p.plan) clauses designated + (branch_pos p height) (projectionProbability p height : ℝ) hβ hβ' observe + have herror := FixedProjectionError.sparse_error_lt p hcalls height + have hlt := h.trans_lt herror + simpa only [mixedLaw, uniformLaw, projectionFlag, + FiniteDistribution.pushforward_comp] using hlt + +theorem event_probability_abs_sub_lt [NeZero m] {Γ : Type*} [Fintype Γ] + (hcalls : Fintype.card C ≤ calls p.plan) + (observe : Observation (C := C) p clauses designated → Γ) (event : Γ → Bool) : + |(mixedLaw p clauses designated).probability (fun record => event (observe record)) - + (uniformLaw p clauses designated).probability (fun record => event (observe record))| < + p.accuracy := by + have h := FiniteDistribution.probability_abs_sub_le_totalVariation + ((mixedLaw p clauses designated).pushforward observe) + ((uniformLaw p clauses designated).pushforward observe) event + have hlt := h.trans_lt (observed_totalVariation_lt p clauses designated hcalls observe) + simpa only [FiniteDistribution.probability_pushforward] using hlt + +theorem event_probability_transfer [NeZero m] {Γ : Type*} [Fintype Γ] + (hcalls : Fintype.card C ≤ calls p.plan) + (observe : Observation (C := C) p clauses designated → Γ) (event : Γ → Bool) : + (mixedLaw p clauses designated).probability (fun record => event (observe record)) < + (uniformLaw p clauses designated).probability (fun record => event (observe record)) + + p.accuracy := by + have h := event_probability_abs_sub_lt p clauses designated hcalls observe event + have hsub := lt_of_le_of_lt (le_abs_self + ((mixedLaw p clauses designated).probability (fun record => event (observe record)) - + (uniformLaw p clauses designated).probability (fun record => event (observe record)))) h + exact (sub_lt_iff_lt_add').mp hsub + +end +end PerfectCompleteness.FixedSourceProjectionComparison + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/FixedStoppedDecoderContext.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/FixedStoppedDecoderContext.lean new file mode 100644 index 0000000000000000000000000000000000000000..80605e2766a263b045919a9953544ff1499ce596 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/FixedStoppedDecoderContext.lean @@ -0,0 +1,140 @@ +import OAI.Computability.PerfectCompleteness.Decoding.DecoderFamilyLawLemmas +import OAI.Computability.PerfectCompleteness.Foundations.CanonicalDirections +import OAI.Computability.PerfectCompleteness.Foundations.GeometricPrefixSplit +import OAI.Computability.PerfectCompleteness.Repetition.StoppedCleanGeometry + +namespace OAI + +section + +namespace PerfectCompleteness.FixedStoppedDecoderContext + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype + +variable {δ : ℚ} {hδ : 0 < δ} (parameters : FixedParameters.Parameters δ hδ) + (i j : Fin parameters.plan.depth) (hij : i < j) + +abbrev Prefixes := + GeometricCutSplit.Prefix (FixedParameters.branch parameters) parameters.plan.depth (j.val + 1) × + GeometricCutSplit.Prefix (FixedParameters.branch parameters) (j.val + 1) (i.val + 1) + +def upperPath (pref : Prefixes parameters i j) : + Path (FixedParameters.branch parameters) parameters.plan.depth (j.val + 1) := + GeometricCutSplit.prefixPath (Nat.succ_le_of_lt j.isLt) pref.1 + +def lowerPath (pref : Prefixes parameters i j) : + Path (FixedParameters.branch parameters) (j.val + 1) (i.val + 1) := + GeometricCutSplit.prefixPath (Nat.succ_le_succ (Nat.le_of_lt hij)) pref.2 + +def upper (pref : Prefixes parameters i j) : Nodes (FixedParameters.branch parameters) parameters.plan.depth := + WholeArrayInteriorExterior.upperNode (upperPath parameters i j pref) + +def lower (pref : Prefixes parameters i j) : + HierarchicalFrozenTables.LowerNodes (upper parameters i j pref) (i.val + 1) := + StoppedCleanGeometry.descendant (upperPath parameters i j pref) + (lowerPath parameters i j hij pref) hij + +@[simp] theorem upper_height (pref : Prefixes parameters i j) : + Nodes.height (upper parameters i j pref) = j.val + 1 := + WholeArrayInteriorExterior.upperNode_height _ + +def prefixLaw : FiniteDistribution (Prefixes parameters i j) := + (GeometricCutSplit.prefixLaw (Nat.succ_le_of_lt j.isLt) + (fun k _ => FixedParameters.branch_pos parameters k)).product + (GeometricCutSplit.prefixLaw (Nat.succ_le_succ (Nat.le_of_lt hij)) + (fun k _ => FixedParameters.branch_pos parameters k)) + +variable (input : List Bool) + +abbrev OutsideQuestions (pref : Prefixes parameters i j) := + StoppedCleanGeometry.OutsideQuestions parameters input + (upperPath parameters i j pref) (lowerPath parameters i j hij pref) + +abbrev Exterior (pref : Prefixes parameters i j) + (external : OutsideQuestions parameters i j hij input pref) := + StoppedCleanGeometry.Exterior parameters input + (upperPath parameters i j pref) (lowerPath parameters i j hij pref) external + +abbrev Advice (pref : Prefixes parameters i j) := + ManyGoodRows.RowMap (Block (FixedRows.rows parameters.plan) (upper parameters i j pref)) + parameters.plan.order + +abbrev Directions := CanonicalDirections.Tuple (FixedRows.rows parameters.plan) parameters.plan.depth + +abbrev Fiber (pref : Prefixes parameters i j) + (external : OutsideQuestions parameters i j hij input pref) := + Advice parameters i j pref × + (Directions parameters × Exterior parameters i j hij input pref external) + +abbrev Context := + (pref : Prefixes parameters i j) × + (external : OutsideQuestions parameters i j hij input pref) × + Fiber parameters i j hij input pref external + +def directionLaw : FiniteDistribution (Directions parameters) := + CanonicalDirections.law (FixedRows.rows parameters.plan) parameters.plan.depth + (fun k => parameters.plan.rows_pos (parameters.plan.depth - (k + 1))) + +def fiberLaw (pref : Prefixes parameters i j) + (external : OutsideQuestions parameters i j hij input pref) : + FiniteDistribution (Fiber parameters i j hij input pref external) := + (FiniteDistribution.uniform (Advice parameters i j pref)).product + ((directionLaw parameters).product + (FiniteDistribution.uniform (Exterior parameters i j hij input pref external))) + +def law : FiniteDistribution (Context parameters i j hij input) := + CompletionSoundness.sigmaLaw (prefixLaw parameters i j hij) (fun pref => + CompletionSoundness.sigmaLaw + (FiniteDistribution.uniform (OutsideQuestions parameters i j hij input pref)) + (fiberLaw parameters i j hij input pref)) + +def upperNode (context : Context parameters i j hij input) := upper parameters i j context.1 + +def lowerIndex (context : Context parameters i j hij input) := lower parameters i j hij context.1 + +def geometry (context : Context parameters i j hij input) : + FixedDecoderCleanRate.Geometry parameters parameters.plan.depth i.val + (upperNode parameters i j hij input context) (lowerIndex parameters i j hij input context) := + StoppedCleanGeometry.geometry parameters input + (upperPath parameters i j context.1) (lowerPath parameters i j hij context.1) hij + context.2.1 context.2.2.2.2 + +def advice (context : Context parameters i j hij input) : + ManyGoodRows.RowMap + (Block (FixedRows.rows parameters.plan) (upperNode parameters i j hij input context)) + parameters.plan.order := context.2.2.1 + +def direction (context : Context parameters i j hij input) : + OwnInputReference.LowerVector (FixedRows.rows parameters.plan) + (HierarchicalLeftDecoder.LowerNode (upperNode parameters i j hij input context) + (i.val + 1) (lowerIndex parameters i j hij input context)) := + (PrefixTests.nodeDirection (FixedRows.rows parameters.plan) i + ⟨HierarchicalLeftDecoder.LowerNode (upperNode parameters i j hij input context) + (i.val + 1) (lowerIndex parameters i j hij input context), + CleanDecoderContext.lowerHeight (upperNode parameters i j hij input context) + (lowerIndex parameters i j hij input context)⟩ (context.2.2.2.1 i)).val + +theorem row_count (context : Context parameters i j hij input) : + FixedRows.rows parameters.plan (Nodes.height (upperNode parameters i j hij input context)) = + FixedRows.rows parameters.plan (j.val + 1) := by + rw [upperNode, upper_height] + +theorem advice_marginal (pref : Prefixes parameters i j) + (external : OutsideQuestions parameters i j hij input pref) : + (fiberLaw parameters i j hij input pref external).pushforward Prod.fst = + FiniteDistribution.uniform (Advice parameters i j pref) := + HiddenBucketBias.product_fst _ _ + +end +end PerfectCompleteness.FixedStoppedDecoderContext + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/FixedStoppedDecoderLaw.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/FixedStoppedDecoderLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..158398ec485ab6106150668816fb292ef6b3f2b8 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/FixedStoppedDecoderLaw.lean @@ -0,0 +1,140 @@ +import OAI.Computability.PerfectCompleteness.Decoding.DecoderFamilyLawLemmas +import OAI.Computability.PerfectCompleteness.Decoding.FixedStoppedDecoderContext +import OAI.Computability.PerfectCompleteness.Foundations.SlotProjectedExperiment +import OAI.Computability.PerfectCompleteness.Reduction.FixedPhysicalStoppedComparison +import OAI.Computability.PerfectCompleteness.Reduction.PreliminaryOutputLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.FixedStoppedDecoderLaw + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +private abbrev familySampleFintype + {branch rows repeats : Nat → Nat} {n h t v m : Nat} [NeZero m] + {O : Type*} [Fintype O] + {upper : O → Nodes branch n} + {lower : (o : O) → HierarchicalFrozenTables.LowerNodes (upper o) (h + 1)} + (S : (o : O) → CleanDecoderRate.Setup branch rows repeats n h t v m (upper o) (lower o)) : + Fintype (DecoderFamilyLaw.Sample S) := inferInstance + +attribute [local instance] linearMapFintype + +variable {δ : ℚ} {hδ : 0 < δ} (parameters : FixedParameters.Parameters δ hδ) + (i j : Fin parameters.plan.depth) (hij : i < j) (input : List Bool) + +abbrev Context := FixedStoppedDecoderContext.Context parameters i j hij input + +def labeling (strategy : FixedPreliminaryGame.Strategy parameters input) : + KeyStrategy.Strategy (TreeCanonical.locationCount (FixedParameters.branch parameters) + parameters.plan.depth (FixedRows.sourceLength parameters.plan hδ)) := + PreliminaryStrategy.extend (PCPSource.clauseFamily (BinaryLanguage.totalRename input)) + (FixedParameters.branch parameters) parameters.plan.depth + (FixedRows.sourceLength parameters.plan hδ) (FixedRows.rows parameters.plan) + (FixedRows.repeats parameters.plan) strategy + +def flag : Fin (FixedParameters.branch parameters i.val) → FiniteDistribution Bool := + fun _ => ProjectionPosterior.bernoulli + (FixedParameters.projectionProbability parameters i.val : ℝ) + (FixedPhysicalStoppedComparison.beta_nonneg parameters) + (FixedPhysicalStoppedComparison.beta_le_one parameters) + +def markFamily (strategy : FixedPreliminaryGame.Strategy parameters input) + (pref : FixedStoppedDecoderContext.Prefixes parameters i j) := + SlotProjectedExperiment.family + (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij pref.1 + (fun k _ => FixedParameters.branch_pos parameters k) + (fun k => FixedPreliminaryGame.rows_pos parameters (k + 1)) + (flag parameters i) (labeling parameters input strategy) + +abbrev setups := + FixedDecoderFamilyRate.setups parameters + (FixedStoppedDecoderContext.geometry parameters i j hij input) input + +def useful (strategy : FixedPreliminaryGame.Strategy parameters input) + (context : Context parameters i j hij input) + (record : CleanDecoderRate.Record (setups parameters i j hij input context)) : + CleanLeftDecoder.Useful + (CleanDecoderContext.leftExposed + (CleanDecoderRate.context (setups parameters i j hij input context) record)) + (FixedStoppedDecoderContext.upperNode parameters i j hij input context) (i.val + 1) := + OriginalDecoderMark.useful + (markFamily parameters i j hij input strategy context.1) + (FixedStoppedDecoderContext.upperNode parameters i j hij input context) (i.val + 1) + (InitialParameters.useful δ) + (CleanDecoderContext.leftExposed + (CleanDecoderRate.context (setups parameters i j hij input context) record)) + +def threshold : ℝ := + UpperParameterScalars.tau (InitialParameters.useful δ) parameters.plan.density + parameters.plan.order (FixedRows.rows parameters.plan (j.val + 1)) + +abbrev Sample := DecoderFamilyLaw.Sample (setups parameters i j hij input) + +local instance sampleFintype : Fintype (Sample parameters i j hij input) := + familySampleFintype (setups parameters i j hij input) + +def law (strategy : FixedPreliminaryGame.Strategy parameters input) : + FiniteDistribution (Sample parameters i j hij input) := + DecoderFamilyLaw.law (setups parameters i j hij input) + (labeling parameters input strategy) (useful parameters i j hij input strategy) + parameters.plan.order parameters.plan.density + (FixedStoppedDecoderContext.advice parameters i j hij input) (FixedStoppedDecoderContext.direction parameters i j hij input) + (threshold parameters j) (FixedStoppedDecoderContext.law parameters i j hij input) + (parameters.cubeSize i.val) (FixedDecoderCleanRate.cubePositive parameters i.val) + +abbrev meeting : Sample parameters i j hij input → Bool := + DecoderFamilyLaw.meeting (setups parameters i j hij input) + +abbrev lowAgreement : Sample parameters i j hij input → Bool := + DecoderFamilyLaw.lowAgreement (setups parameters i j hij input) + (FixedDecoderCleanRate.branchPositive parameters) + (FixedRows.cutoff parameters.plan hδ) + +abbrev highAgreement : Sample parameters i j hij input → Bool := + DecoderFamilyLaw.highAgreement (setups parameters i j hij input) + (FixedDecoderCleanRate.branchPositive parameters) + (FixedRows.cutoff parameters.plan hδ) + +theorem probability_split (strategy : FixedPreliminaryGame.Strategy parameters input) : + (law parameters i j hij input strategy).probability (meeting parameters i j hij input) = + (law parameters i j hij input strategy).probability + (lowAgreement parameters i j hij input) + + (law parameters i j hij input strategy).probability + (highAgreement parameters i j hij input) := + DecoderFamilyLaw.probability_split (setups parameters i j hij input) + (FixedDecoderCleanRate.branchPositive parameters) + (labeling parameters input strategy) (useful parameters i j hij input strategy) + parameters.plan.order parameters.plan.density + (FixedStoppedDecoderContext.advice parameters i j hij input) (FixedStoppedDecoderContext.direction parameters i j hij input) + (threshold parameters j) (FixedStoppedDecoderContext.law parameters i j hij input) + (FixedRows.cutoff parameters.plan hδ) (parameters.cubeSize i.val) + (FixedDecoderCleanRate.cubePositive parameters i.val) + +theorem low_probability_lt_accuracy + (strategy : FixedPreliminaryGame.Strategy parameters input) + (unsat : ¬ BinaryLanguage.language input) : + (law parameters i j hij input strategy).probability + (lowAgreement parameters i j hij input) < parameters.accuracy := + FixedDecoderFamilyRate.probability_lt_accuracy parameters + (FixedStoppedDecoderContext.geometry parameters i j hij input) input + (labeling parameters input strategy) (useful parameters i j hij input strategy) + parameters.plan.order parameters.plan.density + (FixedStoppedDecoderContext.advice parameters i j hij input) (FixedStoppedDecoderContext.direction parameters i j hij input) + (threshold parameters j) (FixedStoppedDecoderContext.law parameters i j hij input) + unsat (le_refl _) parameters.plan.density_pos + +end +end PerfectCompleteness.FixedStoppedDecoderLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/FixedStoppedNativeProjection.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/FixedStoppedNativeProjection.lean new file mode 100644 index 0000000000000000000000000000000000000000..618b3a47c93befd8a5355a4b3ccb20bd2fa50e58 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/FixedStoppedNativeProjection.lean @@ -0,0 +1,347 @@ +import OAI.Computability.PerfectCompleteness.Decoding.CleanPhysicalDecoderLaw +import OAI.Computability.PerfectCompleteness.Decoding.CutProjectionGeometry +import OAI.Computability.PerfectCompleteness.Foundations.StoppedProjectedArrays +import OAI.Computability.PerfectCompleteness.Sampling.FixedStoppedPhysicalLawLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.FixedStoppedNativeProjection + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open FixedStoppedPhysicalLaw (clauses designated) + +section PathTransport + +variable {branch : Nat → Nat} {root h t v m : Nat} [NeZero m] + (rows repeats : Nat → Nat) + (outside : Slots branch root → Fin t → MixedSupport.Slot) + (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch h) → Slots branch h) + {p q : Path branch root (h + 1)} + +omit [NeZero m] in +theorem leftSlots_sourceSampleEquiv (hp : p = q) + (x : SourceChildKernel.Sample (C := WholeCutCalls.Index rows repeats p) (t := t) + rows clauses designated) : + CleanPhysicalCanonicalQuery.leftSlots rows repeats p outside clauses designated x = + CleanPhysicalCanonicalQuery.leftSlots rows repeats q outside clauses designated + (FixedStoppedNativeLaw.sourceSampleEquiv rows repeats clauses designated hp x) := by + cases hp + rfl + +omit [NeZero m] in +theorem rightSlots_sourceSampleEquiv (hp : p = q) + (x : SourceChildKernel.Sample (C := WholeCutCalls.Index rows repeats p) (t := t) + rows clauses designated) : + CleanPhysicalCanonicalQuery.rightSlots rows repeats p outside clauses designated x = + CleanPhysicalCanonicalQuery.rightSlots rows repeats q outside clauses designated + (FixedStoppedNativeLaw.sourceSampleEquiv rows repeats clauses designated hp x) := by + cases hp + rfl + +omit [NeZero m] in +theorem projection_sourceSampleEquiv_heq (hp : p = q) + (x : SourceChildKernel.Sample (C := WholeCutCalls.Index rows repeats p) (t := t) + rows clauses designated) (leaf : Slots branch root) (coordinate : Fin t) : + HEq (CleanPhysicalCanonicalQuery.projection rows repeats p outside clauses designated x + leaf coordinate) + (CleanPhysicalCanonicalQuery.projection rows repeats q outside clauses designated + (FixedStoppedNativeLaw.sourceSampleEquiv rows repeats clauses designated hp x) + leaf coordinate) := by + cases hp + rfl + +end PathTransport + +theorem fillProjection_outsidePresentation_heq + {branch : Nat → Nat} {root h t : Nat} (p : Path branch root h) + (outside otherOutside : Slots branch root → Fin t → MixedSupport.Slot) + (left right : Slots branch h → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (hfillLeft : CutSlotAssembly.fill p outside left = + CutSlotAssembly.fill p otherOutside left) (leaf : Slots branch root) (a : Fin t) : + HEq (CutProjectionAssembly.fillProjection p outside left right q leaf a) + (CutProjectionAssembly.fillProjection p otherOutside left right q leaf a) := by + by_cases hin : leaf ∈ Set.range p.slotEmbedding + · obtain ⟨s, rfl⟩ := hin + exact (CutProjectionAssembly.fillProjection_at_cut p outside left right q s a).trans + (CutProjectionAssembly.fillProjection_at_cut p otherOutside left right q s a).symm + · have hkeep (s u : MixedSupport.Slot) (hsu : s = u) : + HEq (MixedSupport.Projection.keep s) (MixedSupport.Projection.keep u) := by + cases hsu + rfl + exact (CutProjectionGeometry.fillProjection_outside p outside left right q leaf hin a).trans + ((hkeep _ _ (congrFun (congrFun hfillLeft leaf) a)).trans + (CutProjectionGeometry.fillProjection_outside p otherOutside left right q leaf hin a).symm) + +private theorem fullProjection_sources_heq + {branch : Nat → Nat} {root h t v m : Nat} [NeZero m] + (p : Path branch root (h + 1)) + (outside : Slots branch root → Fin t → MixedSupport.Slot) + (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch h) → Slots branch h) + {sources other : SourceChildKernel.Sources (m := m) (t := t) designated} + (hsources : sources = other) (flags : Fin (branch h) → Bool) + (leaf : Slots branch root) (a : Fin t) : + HEq (SourcePhysicalTapeLaw.fullProjection p outside clauses designated (sources, flags) leaf a) + (SourcePhysicalTapeLaw.fullProjection p outside clauses designated (other, flags) leaf a) := by + cases hsources + rfl + +private theorem projection_function_heq + {branch : Nat → Nat} {n t : Nat} + {left left' right right' : Slots branch n → Fin t → MixedSupport.Slot} + (hl : left = left') (hr : right = right') + (p : ∀ leaf a, MixedSupport.Projection (left leaf a) (right leaf a)) + (q : ∀ leaf a, MixedSupport.Projection (left' leaf a) (right' leaf a)) + (hpq : ∀ leaf a, HEq (p leaf a) (q leaf a)) : HEq p q := by + cases hl + cases hr + exact heq_of_eq (funext (fun leaf => funext (fun a => eq_of_heq (hpq leaf a)))) + +private theorem projectedSlots_physicalRead_eq + {branch : Nat → Nat} {n i j t v m : Nat} [NeZero m] + (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hupper : j + 1 ≤ n) (hij : i < j) + (designated : Fin (branch i) → Slots branch i) + (o : StoppedProjectedExperiment.Outer + (branch := branch) (n := n) (j := j) (t := t) (m := m)) + (sample : StoppedProjectedExperiment.PhysicalSample + clauses rows repeats hupper hij designated o) : + StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated o + (StoppedProjectedExperiment.physicalRead clauses rows repeats hupper hij designated o sample).1 = + SourcePhysicalTapeLaw.projectedSlots + (StoppedProjectedExperiment.stoppedPath rows hupper hij o + (StoppedProjectedExperiment.baseTag rows sample.1)) + (StoppedProjectedExperiment.nativeSlots clauses o) clauses designated + (StoppedProjectedExperiment.physicalSources rows hupper hij designated o sample.1, + (StoppedProjectedExperiment.physicalRead + clauses rows repeats hupper hij designated o sample).1.2.1.2) := rfl + +private theorem projectedSlots_tag_eq_rightSlots + {branch : Nat → Nat} {root h t v m : Nat} [NeZero m] + (rows repeats : Nat → Nat) (p : Path branch root (h + 1)) + (outside : Slots branch root → Fin t → MixedSupport.Slot) + (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch h) → Slots branch h) + (sample : SourceChildKernel.Sample (C := WholeCutCalls.Index rows repeats p) (t := t) + rows clauses designated) : + SourcePhysicalTapeLaw.projectedSlots p outside clauses designated + (SourcePhysicalTapeLaw.tag rows repeats p clauses designated sample) = + CleanPhysicalCanonicalQuery.rightSlots rows repeats p outside clauses designated sample := rfl + +variable {δ : ℚ} {hδ : 0 < δ} (parameters : FixedParameters.Parameters δ hδ) + (i j : Fin parameters.plan.depth) (hij : i < j) (input : List Bool) + +abbrev physicalSample (sample : FixedStoppedNativeLaw.Sample parameters i j hij input) := + FixedStoppedNativeLaw.read parameters i j hij input sample + +abbrev innerTag (sample : FixedStoppedNativeLaw.Sample parameters i j hij input) := + (StoppedProjectedExperiment.physicalRead (clauses input) + (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij (designated parameters i) + (physicalSample parameters i j hij input sample).1 + (physicalSample parameters i j hij input sample).2.1).1 + +abbrev originalQuestions (sample : FixedStoppedNativeLaw.Sample parameters i j hij input) := + (physicalSample parameters i j hij input sample).1.1 + +abbrev path (sample : FixedStoppedNativeLaw.Sample parameters i j hij input) := + FixedStoppedPhysicalLaw.path parameters i j hij sample.1.1 + +abbrev childSample (sample : FixedStoppedNativeLaw.Sample parameters i j hij input) := + FixedStoppedNativeLaw.childRead parameters i j hij input sample.1 sample.2 + +abbrev sources (sample : FixedStoppedNativeLaw.Sample parameters i j hij input) := + SourcePhysicalTapeLaw.sourceTag (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (path parameters i j hij input sample) (clauses input) (designated parameters i) + (childSample parameters i j hij input sample) + +abbrev flags (sample : FixedStoppedNativeLaw.Sample parameters i j hij input) := + fun child => SourceChildKernel.rawProjected (FixedRows.rows parameters.plan) + (clauses input) (designated parameters i) child + ((childSample parameters i j hij input sample) child).2.2 + +theorem physicalSources_eq (sample : FixedStoppedNativeLaw.Sample parameters i j hij input) : + StoppedProjectedExperiment.physicalSources (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij (designated parameters i) + (physicalSample parameters i j hij input sample).1 + (physicalSample parameters i j hij input sample).2.1.1 = + sources parameters i j hij input sample := by + change SourceQuestionKernelJoint.sources (designated parameters i) + (SourceQuestionCutSplit.restrict (path parameters i j hij input sample) + (SourceQuestionCutSplit.join (path parameters i j hij input sample) + (SourceQuestionRawSwap.insideQuestions (FixedRows.rows parameters.plan) + (clauses input) (designated parameters i) (childSample parameters i j hij input sample)) + sample.1.2.1)) + (SourceQuestionRawSwap.positions (FixedRows.rows parameters.plan) + (clauses input) (designated parameters i) (childSample parameters i j hij input sample)) = _ + have hrestrict := SourceQuestionRawSwap.restrict_join (path parameters i j hij input sample) + (SourceQuestionRawSwap.insideQuestions (FixedRows.rows parameters.plan) + (clauses input) (designated parameters i) (childSample parameters i j hij input sample)) + sample.1.2.1 + have hsources := congrArg (fun questions => SourceQuestionKernelJoint.sources + (designated parameters i) questions + (SourceQuestionRawSwap.positions (FixedRows.rows parameters.plan) + (clauses input) (designated parameters i) (childSample parameters i j hij input sample))) hrestrict + exact hsources.trans + (SourceQuestionRawSwap.sources_insideQuestions_positions (FixedRows.rows parameters.plan) + (clauses input) (designated parameters i) (childSample parameters i j hij input sample)) + +@[simp] theorem flags_eq (sample : FixedStoppedNativeLaw.Sample parameters i j hij input) : + (innerTag parameters i j hij input sample).2.1.2 = flags parameters i j hij input sample := rfl + +theorem outside_eq (sample : FixedStoppedNativeLaw.Sample parameters i j hij input) : + (FixedStoppedNativeLaw.setup parameters i j hij input sample.1).outside = + SourcePhysicalExteriorSwap.canonicalSlots (clauses input) (path parameters i j hij input sample) + (SourceQuestionCutSplit.outside (path parameters i j hij input sample) + (originalQuestions parameters i j hij input sample)) := by + change SourcePhysicalExteriorSwap.canonicalSlots (clauses input) + (path parameters i j hij input sample) sample.1.2.1 = + SourcePhysicalExteriorSwap.canonicalSlots (clauses input) (path parameters i j hij input sample) + (SourceQuestionCutSplit.outside (path parameters i j hij input sample) + (SourceQuestionCutSplit.join (path parameters i j hij input sample) _ sample.1.2.1)) + exact (congrArg (SourcePhysicalExteriorSwap.canonicalSlots (clauses input) + (path parameters i j hij input sample)) + (SourcePhysicalSourceSwap.outside_join (path parameters i j hij input sample) + (SourceQuestionRawSwap.insideQuestions (FixedRows.rows parameters.plan) + (clauses input) (designated parameters i) (childSample parameters i j hij input sample)) + sample.1.2.1)).symm + +theorem fill_outside_eq (sample : FixedStoppedNativeLaw.Sample parameters i j hij input) + (inside : Slots (FixedParameters.branch parameters) (i.val + 1) → + Fin (FixedRows.sourceLength parameters.plan hδ) → MixedSupport.Slot) : + CutSlotAssembly.fill (path parameters i j hij input sample) + (FixedStoppedNativeLaw.setup parameters i j hij input sample.1).outside inside = + CutSlotAssembly.fill (path parameters i j hij input sample) + (StoppedProjectedExperiment.nativeSlots (clauses input) + (physicalSample parameters i j hij input sample).1) inside := by + rw [outside_eq] + exact (SourcePhysicalExteriorSwap.fill_eq (clauses input) + (path parameters i j hij input sample) (originalQuestions parameters i j hij input sample) + inside).symm + +theorem leftSlots_eq (sample : FixedStoppedNativeLaw.Sample parameters i j hij input) : + CleanNativeReplay.leftSlots (FixedStoppedNativeLaw.setup parameters i j hij input sample.1) + sample.2 = + StoppedProjectedExperiment.nativeSlots (clauses input) + (physicalSample parameters i j hij input sample).1 := by + have hp := leftSlots_sourceSampleEquiv (FixedRows.rows parameters.plan) + (FixedRows.repeats parameters.plan) + (FixedStoppedNativeLaw.setup parameters i j hij input sample.1).outside + (clauses input) (designated parameters i) + (FixedStoppedNativeLaw.path_eq parameters i j hij input sample.1) sample.2 + refine hp.trans ((fill_outside_eq parameters i j hij input sample _).trans ?_) + exact (congrArg (SourcePhysicalTapeLaw.nativeSlots (path parameters i j hij input sample) + (StoppedProjectedExperiment.nativeSlots (clauses input) + (physicalSample parameters i j hij input sample).1) (clauses input) (designated parameters i)) + (physicalSources_eq parameters i j hij input sample)).symm.trans + (StoppedProjectedArrays.nativeSlots_eq (clauses input) (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij (designated parameters i) + (physicalSample parameters i j hij input sample).1 + (physicalSample parameters i j hij input sample).2.1.1) + +theorem physicalRightSlots_eq (sample : FixedStoppedNativeLaw.Sample parameters i j hij input) : + StoppedProjectedExperiment.projectedSlots (clauses input) (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij (designated parameters i) + (physicalSample parameters i j hij input sample).1 + (innerTag parameters i j hij input sample) = + CleanPhysicalCanonicalQuery.rightSlots (FixedRows.rows parameters.plan) + (FixedRows.repeats parameters.plan) (path parameters i j hij input sample) + (StoppedProjectedExperiment.nativeSlots (clauses input) + (physicalSample parameters i j hij input sample).1) + (clauses input) (designated parameters i) (childSample parameters i j hij input sample) := by + have hread := projectedSlots_physicalRead_eq (clauses input) (FixedRows.rows parameters.plan) + (FixedRows.repeats parameters.plan) (Nat.succ_le_of_lt j.isLt) hij (designated parameters i) + (physicalSample parameters i j hij input sample).1 + (physicalSample parameters i j hij input sample).2.1 + have htags := congrArg₂ Prod.mk (physicalSources_eq parameters i j hij input sample) + (flags_eq parameters i j hij input sample) + have hslots := congrArg (SourcePhysicalTapeLaw.projectedSlots + (path parameters i j hij input sample) + (StoppedProjectedExperiment.nativeSlots (clauses input) + (physicalSample parameters i j hij input sample).1) (clauses input) (designated parameters i)) htags + have hright := projectedSlots_tag_eq_rightSlots (FixedRows.rows parameters.plan) + (FixedRows.repeats parameters.plan) (path parameters i j hij input sample) + (StoppedProjectedExperiment.nativeSlots (clauses input) + (physicalSample parameters i j hij input sample).1) (clauses input) (designated parameters i) + (childSample parameters i j hij input sample) + exact hread.trans (hslots.trans hright) + +theorem rightSlots_eq (sample : FixedStoppedNativeLaw.Sample parameters i j hij input) : + CleanNativeReplay.rightSlots (FixedStoppedNativeLaw.setup parameters i j hij input sample.1) + sample.2 = + StoppedProjectedExperiment.projectedSlots (clauses input) (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij (designated parameters i) + (physicalSample parameters i j hij input sample).1 + (innerTag parameters i j hij input sample) := by + have hp := rightSlots_sourceSampleEquiv (FixedRows.rows parameters.plan) + (FixedRows.repeats parameters.plan) + (FixedStoppedNativeLaw.setup parameters i j hij input sample.1).outside + (clauses input) (designated parameters i) + (FixedStoppedNativeLaw.path_eq parameters i j hij input sample.1) sample.2 + refine hp.trans ((fill_outside_eq parameters i j hij input sample _).trans ?_) + exact (physicalRightSlots_eq parameters i j hij input sample).symm + +theorem projection_apply_heq (sample : FixedStoppedNativeLaw.Sample parameters i j hij input) + (leaf : Slots (FixedParameters.branch parameters) parameters.plan.depth) + (a : Fin (FixedRows.sourceLength parameters.plan hδ)) : + HEq (CleanPhysicalDecoderLaw.physicalProjection + (FixedStoppedNativeLaw.setup parameters i j hij input sample.1) sample.2 leaf a) + (StoppedProjectedExperiment.projection (clauses input) (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij (designated parameters i) + (physicalSample parameters i j hij input sample).1 + (innerTag parameters i j hij input sample) leaf a) := by + have hp := projection_sourceSampleEquiv_heq (FixedRows.rows parameters.plan) + (FixedRows.repeats parameters.plan) + (FixedStoppedNativeLaw.setup parameters i j hij input sample.1).outside + (clauses input) (designated parameters i) + (FixedStoppedNativeLaw.path_eq parameters i j hij input sample.1) sample.2 leaf a + have hout := fillProjection_outsidePresentation_heq (path parameters i j hij input sample) + (FixedStoppedNativeLaw.setup parameters i j hij input sample.1).outside + (StoppedProjectedExperiment.nativeSlots (clauses input) + (physicalSample parameters i j hij input sample).1) + (CleanPhysicalReplay.leftInside (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (path parameters i j hij input sample) (clauses input) (designated parameters i) + (childSample parameters i j hij input sample)) + (CleanPhysicalReplay.rightInside (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (path parameters i j hij input sample) (clauses input) (designated parameters i) + (childSample parameters i j hij input sample)) + (SourceChildKernel.parentProjection (FixedRows.rows parameters.plan) (clauses input) + (designated parameters i) (sources parameters i j hij input sample) + (fun child => ((childSample parameters i j hij input sample) child).2.2)) + (fill_outside_eq parameters i j hij input sample _) leaf a + have hs := fullProjection_sources_heq (path parameters i j hij input sample) + (StoppedProjectedExperiment.nativeSlots (clauses input) + (physicalSample parameters i j hij input sample).1) (clauses input) (designated parameters i) + (physicalSources_eq parameters i j hij input sample).symm + (flags parameters i j hij input sample) leaf a + have hphysical := StoppedProjectedArrays.projection_heq (clauses input) + (FixedRows.rows parameters.plan) (Nat.succ_le_of_lt j.isLt) hij (designated parameters i) + (physicalSample parameters i j hij input sample).1 + (physicalSample parameters i j hij input sample).2.1.1 + (flags parameters i j hij input sample) leaf a + exact hp.trans (hout.trans (hs.trans hphysical.symm)) + +theorem projection_heq (sample : FixedStoppedNativeLaw.Sample parameters i j hij input) : + HEq (CleanPhysicalDecoderLaw.physicalProjection + (FixedStoppedNativeLaw.setup parameters i j hij input sample.1) sample.2) + (StoppedProjectedExperiment.projection (clauses input) (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij (designated parameters i) + (physicalSample parameters i j hij input sample).1 + (innerTag parameters i j hij input sample)) := + projection_function_heq (leftSlots_eq parameters i j hij input sample) + (rightSlots_eq parameters i j hij input sample) _ _ + (projection_apply_heq parameters i j hij input sample) + +end +end PerfectCompleteness.FixedStoppedNativeProjection + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/FixedStoppedUpperProbability.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/FixedStoppedUpperProbability.lean new file mode 100644 index 0000000000000000000000000000000000000000..7161922488dbd8bcd98cb9b0f9d6ea1a57282a6e --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/FixedStoppedUpperProbability.lean @@ -0,0 +1,58 @@ +import OAI.Computability.PerfectCompleteness.Reduction.FixedStoppedActualBounds +import OAI.Computability.PerfectCompleteness.Reduction.FixedStoppedMeetingEquality +import OAI.Computability.PerfectCompleteness.Sampling.FixedSourcePairVariation + +namespace OAI + +section + +namespace PerfectCompleteness.FixedStoppedUpperProbability + +noncomputable section + +attribute [local instance] FixedStoppedDecoderLaw.sampleFintype + UniqueGamesTheorem.Appendix.RankLevelFilter.linearMapFintype + +variable {δ : ℚ} {hδ : 0 < δ} (parameters : FixedParameters.Parameters δ hδ) + (i j : Fin parameters.plan.depth) (hij : i < j) (input : List Bool) + (strategy : FixedPreliminaryGame.Strategy parameters input) + +theorem pairedVariation_le : + FixedStoppedInverseBound.pairedVariation parameters i j hij input strategy ≤ + 10 * parameters.accuracy := + FixedSourcePairVariation.totalVariation_le_ten parameters + (PCPSource.clauseFamily (BinaryLanguage.totalRename input)) + (Nat.succ_le_of_lt j.isLt) hij (FixedStoppedPhysicalLaw.designated parameters i) + (FixedStoppedDecoderLaw.labeling parameters input strategy) (le_refl _) + (FixedStoppedInverseBound.outerLaw parameters j input) + +theorem meeting_ge_gamma + (hreserve : InitialParameters.simultaneous δ + 2 * parameters.accuracy ≤ + (StoppedSharedSampler.stoppedLaw + (PCPSource.clauseFamily (BinaryLanguage.totalRename input)) + (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (Nat.succ_le_of_lt i.isLt) (fun k _ => FixedParameters.branch_pos parameters k) + (fun k => FixedPreliminaryGame.rows_pos parameters (k + 1))).probability + (StoppedSharedEvents.pair (PCPSource.clauseFamily (BinaryLanguage.totalRename input)) + strategy (Nat.succ_le_of_lt i.isLt) + (fun k _ => FixedParameters.branch_pos parameters k) i j)) : + FixedRankContradiction.gamma parameters (j.val + 1) ≤ + (FixedStoppedDecoderLaw.law parameters i j hij input strategy).probability + (FixedStoppedDecoderLaw.meeting parameters i j hij input) := by + have hpaired := pairedVariation_le parameters i j hij input strategy + have hmass := FixedStoppedActualBounds.usefulMass_ge parameters i j hij input strategy hreserve + have hcoarse := + (FixedStoppedActualBounds.coarseVariation_le_pairedVariation parameters i j hij input strategy).trans + hpaired + have hupper := FixedStoppedInverseBound.expectedMeeting_ge_gamma + parameters i j hij input strategy hmass hpaired hcoarse + exact hupper.trans_eq + (FixedStoppedMeetingEquality.meeting_probability_eq_expectedMeeting + parameters i j hij input strategy).symm + +end +end PerfectCompleteness.FixedStoppedUpperProbability + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/FixedUpperPairErrorLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/FixedUpperPairErrorLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..47a2e371d392836958416859c8b553b33eacb616 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/FixedUpperPairErrorLemmas.lean @@ -0,0 +1,256 @@ +import OAI.Computability.PerfectCompleteness.Decoding.FixedProjectionErrorLemmas +import OAI.Computability.PerfectCompleteness.Decoding.UpperCutTriangle +import OAI.Computability.PerfectCompleteness.Decoding.UpperScalarCutCalls +import OAI.Computability.PerfectCompleteness.Reduction.FixedStoppedError +import OAI.Computability.PerfectCompleteness.Sampling.CommonProductVariationLemmas +import OAI.Computability.PerfectCompleteness.Sampling.HierarchicalBackgroundVariation + +namespace OAI + +section + +namespace PerfectCompleteness.FixedUpperPairError + +open FixedParameters FixedRows DescendantSpaces + +noncomputable section + +variable {δ : ℚ} {hδ : 0 < δ} (params : Parameters δ hδ) + {root upper lower : Nat} + +theorem lower_errors_lt (pref : Path (branch params) root (upper + 1)) + (segment : Path (branch params) (upper + 1) (lower + 1)) + (direction : BucketSampler.Direction (rows params.plan (upper + 1))) + (hroot : root ≤ params.plan.depth) : + let L : ℝ := ChildBlockCardinality.bound (branch params) lower + (sourceLength params.plan hδ) + (UpperScalarCutCalls.count (rows params.plan) (repeats params.plan) + root (upper + 1) (lower + 1)) (rows params.plan) + Real.sqrt ((1 + (projectionProbability params lower : ℝ) ^ 2 * (L - 1)) ^ + branch params lower - 1) / 2 + + Real.sqrt (L ^ 2 / branch params lower) / 2 < 2 * params.accuracy := by + have hcalls := UpperScalarCutCalls.count_le_fixed_calls params.plan pref segment direction hroot + have hsparse := FixedProjectionError.sparse_error_lt params hcalls lower + have hhidden := FixedStoppedError.hidden_error_lt params hcalls lower + dsimp only + linarith + +theorem three_errors_lt (pref : Path (branch params) root (upper + 1)) + (segment : Path (branch params) (upper + 1) (lower + 1)) + (direction : BucketSampler.Direction (rows params.plan (upper + 1))) + (hroot : root ≤ params.plan.depth) : + let L : ℝ := ChildBlockCardinality.bound (branch params) lower + (sourceLength params.plan hδ) + (UpperScalarCutCalls.count (rows params.plan) (repeats params.plan) + root (upper + 1) (lower + 1)) (rows params.plan) + Real.sqrt ((1 + (projectionProbability params lower : ℝ) ^ 2 * (L - 1)) ^ + branch params lower - 1) / 2 + + Real.sqrt (L ^ 2 / branch params lower) / 2 + + Real.sqrt ((ChildBlockCardinality.bound (branch params) upper + (sourceLength params.plan hδ) + (OriginalCutCalls.count (rows params.plan) (repeats params.plan) root (upper + 1) + 1) + (rows params.plan) : ℝ) ^ 2 / branch params upper) / 2 < + 3 * params.accuracy := by + have hlower := lower_errors_lt params pref segment direction hroot + have hupper := FixedStoppedError.collision_error_lt params hroot pref.height_le + dsimp only at hlower ⊢ + linarith + +end +end PerfectCompleteness.FixedUpperPairError + +end + +section + +namespace PerfectCompleteness.FixedUpperCutTriangle + +open FixedParameters FixedRows RecursiveSpaces DescendantSpaces +open TreeSourceSpaces HierarchicalArrays OriginalWholeCutTape WholeArrayInteriorExterior +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) +open scoped Classical + +noncomputable section + +attribute [local instance] linearMapFintype + +variable {δ : ℚ} {hδ : 0 < δ} (params : Parameters δ hδ) + {root upper lower : Nat} + +theorem rows_positive (height : Nat) : 0 < rows params.plan height := + lt_of_lt_of_le Nat.zero_lt_one (params.plan.rows_pos (params.plan.depth - height)) + +variable (pref : Path (branch params) root (upper + 1)) + (hcut : lower + 1 ≤ upper + 1) + (slots : Slots (branch params) root → Fin (sourceLength params.plan hδ) → MixedSupport.Slot) + +local instance backgroundFintype : + Fintype (HierarchicalAgreementMean.Background (rows := rows params.plan) slots (upperNode pref)) := + Fintype.ofFinite _ + +local instance rowSpaceFintype : Fintype (NodeEmbedding.RowSpace slots (upperNode pref)) := + Fintype.ofFinite _ + +def upperReferenceLaw : + FiniteDistribution (HierarchicalAgreementMean.PairRecord (rows := rows params.plan) slots (upperNode pref)) := + HierarchicalAgreementMean.referenceLaw slots (upperNode pref) + (OriginalOwnBucketSplit.backgroundLaw (rows params.plan) (repeats params.plan) pref slots) + (by simpa only [upperNode_height] using rows_positive params (upper + 1)) + +variable {Z : UpperCutTriangle.Prefix (branch params) upper lower → Fin (branch params lower) → Type*} + [∀ lowerPref child, Fintype (Z lowerPref child)] + (projected : (lowerPref : UpperCutTriangle.Prefix (branch params) upper lower) → + (child : Fin (branch params lower)) → Z lowerPref child → + Slots (branch params) lower → Fin (sourceLength params.plan hδ) → MixedSupport.Slot) + (projection : ∀ lowerPref child z s a, MixedSupport.Projection + (childSlots (cutSlots (pref.append (GeometricCutSplit.prefixPath hcut lowerPref)) slots) child s a) + (projected lowerPref child z s a)) + (choiceLaw : (lowerPref : UpperCutTriangle.Prefix (branch params) upper lower) → + (child : Fin (branch params lower)) → FiniteDistribution (Z lowerPref child)) + +def modifiedPairLaw : + FiniteDistribution (HierarchicalAgreementMean.PairRecord (rows := rows params.plan) slots (upperNode pref)) := + UpperCutTriangle.modifiedPairLaw (rows params.plan) (repeats params.plan) pref hcut slots + (fun k _ => branch_pos params k) (rows_positive params (upper + 1)) + projected projection choiceLaw (projectionProbability params lower : ℝ) + (by exact_mod_cast (projectionProbability_bounds params lower).1.le) + (by exact_mod_cast (projectionProbability_bounds params lower).2.le) + +def originalReferenceLaw : + FiniteDistribution (HierarchicalAgreementMean.PairRecord (rows := rows params.plan) slots (upperNode pref)) := + HierarchicalAgreementMean.referenceLaw slots (upperNode pref) + ((modifiedPairLaw params pref hcut slots projected projection choiceLaw).pushforward Prod.fst) + (by simpa only [upperNode_height] using rows_positive params (upper + 1)) + +theorem modified_reference_lt (hroot : root ≤ params.plan.depth) : + (modifiedPairLaw params pref hcut slots projected projection choiceLaw).totalVariation + (upperReferenceLaw params pref slots) < 3 * params.accuracy := by + have hcomparison := UpperCutTriangle.modified_reference_variation + (rows params.plan) (repeats params.plan) pref hcut slots + (fun k _ => branch_pos params k) (rows_positive params (upper + 1)) + projected projection choiceLaw (projectionProbability params lower : ℝ) + (by exact_mod_cast (projectionProbability_bounds params lower).1.le) + (by exact_mod_cast (projectionProbability_bounds params lower).2.le) + let lowerPref : UpperCutTriangle.Prefix (branch params) upper lower := + Classical.choice (GeometricCutSplit.prefix_nonempty hcut (fun k _ => branch_pos params k)) + let direction : BucketSampler.Direction (rows params.plan (upper + 1)) := + BucketUniform.coordinateDirection ⟨0, rows_positive params (upper + 1)⟩ + have herror := FixedUpperPairError.three_errors_lt params pref + (GeometricCutSplit.prefixPath hcut lowerPref) direction hroot + simpa only [modifiedPairLaw, upperReferenceLaw] using hcomparison.trans_lt herror + +theorem original_reference_lt (hroot : root ≤ params.plan.depth) : + (modifiedPairLaw params pref hcut slots projected projection choiceLaw).totalVariation + (originalReferenceLaw params pref hcut slots projected projection choiceLaw) < + 6 * params.accuracy := by + have h := HierarchicalBackgroundVariation.original_background_variation slots (upperNode pref) + (modifiedPairLaw params pref hcut slots projected projection choiceLaw) + (OriginalOwnBucketSplit.backgroundLaw (rows params.plan) (repeats params.plan) pref slots) + (by simpa only [upperNode_height] using rows_positive params (upper + 1)) + change (modifiedPairLaw params pref hcut slots projected projection choiceLaw).totalVariation + (originalReferenceLaw params pref hcut slots projected projection choiceLaw) ≤ + 2 * (modifiedPairLaw params pref hcut slots projected projection choiceLaw).totalVariation + (upperReferenceLaw params pref slots) at h + have hthree := modified_reference_lt params pref hcut slots projected projection choiceLaw hroot + linarith + +theorem original_reference_le_ten (hroot : root ≤ params.plan.depth) : + (modifiedPairLaw params pref hcut slots projected projection choiceLaw).totalVariation + (originalReferenceLaw params pref hcut slots projected projection choiceLaw) ≤ + 10 * params.accuracy := by + have h := original_reference_lt params pref hcut slots projected projection choiceLaw hroot + have hpositive := params.accuracy_pos + linarith + +end +end PerfectCompleteness.FixedUpperCutTriangle + +end + +section + +namespace PerfectCompleteness.FixedUpperCutFamily + +open FixedParameters FixedRows RecursiveSpaces DescendantSpaces +open TreeSourceSpaces HierarchicalArrays OriginalWholeCutTape WholeArrayInteriorExterior +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) +open scoped Classical + +noncomputable section + +attribute [local instance] linearMapFintype + +variable {δ : ℚ} {hδ : 0 < δ} (params : Parameters δ hδ) + {root upper lower : Nat} {O : Type*} [Fintype O] + (pref : O → Path (branch params) root (upper + 1)) + (hcut : lower + 1 ≤ upper + 1) + (slots : O → Slots (branch params) root → Fin (sourceLength params.plan hδ) → MixedSupport.Slot) + +local instance backgroundFintype (o : O) : + Fintype (HierarchicalAgreementMean.Background (rows := rows params.plan) (slots o) (upperNode (pref o))) := + Fintype.ofFinite _ + +local instance rowSpaceFintype (o : O) : + Fintype (NodeEmbedding.RowSpace (slots o) (upperNode (pref o))) := Fintype.ofFinite _ + +abbrev Record := Σ o : O, + HierarchicalAgreementMean.PairRecord (rows := rows params.plan) (slots o) (upperNode (pref o)) + +variable {Z : O → UpperCutTriangle.Prefix (branch params) upper lower → Fin (branch params lower) → Type*} + [∀ o lowerPref child, Fintype (Z o lowerPref child)] + (projected : (o : O) → (lowerPref : UpperCutTriangle.Prefix (branch params) upper lower) → + (child : Fin (branch params lower)) → Z o lowerPref child → + Slots (branch params) lower → Fin (sourceLength params.plan hδ) → MixedSupport.Slot) + (projection : ∀ o lowerPref child z s a, MixedSupport.Projection + (childSlots (cutSlots ((pref o).append (GeometricCutSplit.prefixPath hcut lowerPref)) (slots o)) child s a) + (projected o lowerPref child z s a)) + (choiceLaw : (o : O) → (lowerPref : UpperCutTriangle.Prefix (branch params) upper lower) → + (child : Fin (branch params lower)) → FiniteDistribution (Z o lowerPref child)) + +def modifiedLaw (outerLaw : FiniteDistribution O) : + FiniteDistribution (Record params pref slots) := + CompletionSoundness.sigmaLaw outerLaw (fun o => + FixedUpperCutTriangle.modifiedPairLaw params (pref o) hcut (slots o) + (projected o) (projection o) (choiceLaw o)) + +def referenceLaw (outerLaw : FiniteDistribution O) : + FiniteDistribution (Record params pref slots) := + CompletionSoundness.sigmaLaw outerLaw (fun o => + FixedUpperCutTriangle.originalReferenceLaw params (pref o) hcut (slots o) + (projected o) (projection o) (choiceLaw o)) + +theorem totalVariation_le_six (outerLaw : FiniteDistribution O) + (hroot : root ≤ params.plan.depth) : + (modifiedLaw params pref hcut slots projected projection choiceLaw outerLaw).totalVariation + (referenceLaw params pref hcut slots projected projection choiceLaw outerLaw) ≤ + 6 * params.accuracy := by + have h := ConditionalVariation.observed_sigma_le_const outerLaw + (fun o => FixedUpperCutTriangle.modifiedPairLaw params (pref o) hcut (slots o) + (projected o) (projection o) (choiceLaw o)) + (fun o => FixedUpperCutTriangle.originalReferenceLaw params (pref o) hcut (slots o) + (projected o) (projection o) (choiceLaw o)) + (6 * params.accuracy) + (fun o => (FixedUpperCutTriangle.original_reference_lt params (pref o) hcut (slots o) + (projected o) (projection o) (choiceLaw o) hroot).le) + (id : Record params pref slots → Record params pref slots) + simpa only [modifiedLaw, referenceLaw, FiniteDistribution.pushforward_id] using h + +theorem observed_totalVariation_le_ten {Γ : Type*} [Fintype Γ] + (outerLaw : FiniteDistribution O) (hroot : root ≤ params.plan.depth) + (observe : Record params pref slots → Γ) : + ((modifiedLaw params pref hcut slots projected projection choiceLaw outerLaw).pushforward observe).totalVariation + ((referenceLaw params pref hcut slots projected projection choiceLaw outerLaw).pushforward observe) ≤ + 10 * params.accuracy := by + have h := (DensityVariation.variation_pushforward_le _ _ observe).trans + (totalVariation_le_six params pref hcut slots projected projection choiceLaw outerLaw hroot) + have hpositive := params.accuracy_pos + linarith + +end +end PerfectCompleteness.FixedUpperCutFamily + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/HierarchicalAllDecoderTables.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/HierarchicalAllDecoderTables.lean new file mode 100644 index 0000000000000000000000000000000000000000..940c92794f73acaaec339fc21a3e4373b48b2879 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/HierarchicalAllDecoderTables.lean @@ -0,0 +1,206 @@ +import Mathlib.Data.Fintype.Sigma +import OAI.Computability.PerfectCompleteness.Decoding.HierarchicalDecoderTables + +namespace OAI + +section + +namespace PerfectCompleteness.HierarchicalAllDecoderTables + +noncomputable section + +open scoped Classical +open TreeSourceSpaces HierarchicalArrays PointwiseSpaces +open UniqueGamesTheorem.Foundations.Games + +attribute [local instance] UniqueGamesTheorem.Appendix.RankLevelFilter.linearMapFintype + +private theorem row_probability_of_raw {Q A : Type*} [Fintype A] + (μ : FiniteDistribution (Option A)) (valid : Q → A → Prop) (q : Q) + (predicate : A → Prop) (hp : valid q = predicate) + (hv : μ.probability (fun answer => decide + (∀ z, answer = some z → predicate z)) = 1) : + μ.probability (fun answer => decide + (DecoderTableAdmissibility.RowValid valid q answer)) = 1 := by + have hevent : (fun answer : Option A => decide + (DecoderTableAdmissibility.RowValid valid q answer)) = + (fun answer : Option A => decide (∀ z, answer = some z → predicate z)) := by + funext answer + apply (@decide_eq_decide + (DecoderTableAdmissibility.RowValid valid q answer) + (∀ z, answer = some z → predicate z) _ _).mpr + unfold DecoderTableAdmissibility.RowValid + rw [hp] + rw [hevent] + exact hv + +variable {branch rows : Nat → Nat} {n t : Nat} + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (upper : Nodes branch n) (lowerLevel : Nat) + +abbrev Background := HierarchicalMatrixTable.Background (rows := rows) slots upper + +abbrev Input (r : Nat) := + (background : Background (rows := rows) slots upper) × + HierarchicalDecoderTables.Advice slots upper lowerLevel background r + +local instance rowSpaceFintype (node : Nodes branch n) : + Fintype (NodeEmbedding.RowSpace slots node) := Fintype.ofFinite _ + +local instance nodeSpaceFintype (node : Nodes branch n) : + Fintype (NodeEmbedding.NodeH slots node) := Fintype.ofFinite _ + +instance inputFintype (r : Nat) : Fintype (Input (rows := rows) slots upper lowerLevel r) := by + letI : Fintype (Background (rows := rows) slots upper) := Fintype.ofFinite _ + letI : (background : Background (rows := rows) slots upper) → + Fintype (HierarchicalDecoderTables.Advice slots upper lowerLevel background r) := + fun _ => inferInstance + exact inferInstanceAs (Fintype + ((background : Background (rows := rows) slots upper) × + HierarchicalDecoderTables.Advice slots upper lowerLevel background r)) + +abbrev UpperAnswer := Module.Dual F2 (NodeEmbedding.RowSpace slots upper) + +local instance upperDualFintype : Fintype (UpperAnswer slots upper) := + LeftDecoder.dualFintype (V := NodeEmbedding.RowSpace slots upper) + +local instance answerFintype (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) : + Fintype (HierarchicalDecoderTables.Answer slots upper lowerLevel d) := + LeftDecoder.dualFintype + (V := squareSpace (HierarchicalDecoderTables.LowerH slots upper lowerLevel d)) + +variable (hbranch : ∀ k < n, 0 < branch k) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (useful : (background : Background (rows := rows) slots upper) → + HierarchicalFrozenTables.QuotientMatrix slots upper lowerLevel background → Prop) + +def upperKernel (r : Nat) (ρ : ℝ) (input : Input (rows := rows) slots upper lowerLevel r) : + FiniteDistribution (UpperAnswer slots upper) := + HierarchicalLeftDecoder.adviceLaw slots upper lowerLevel input.1 σ (useful input.1) + r ρ input.2.1 input.2.2 + +def upperTableLaw (r : Nat) (ρ : ℝ) : + FiniteDistribution (Input (rows := rows) slots upper lowerLevel r → UpperAnswer slots upper) := + FiniteDistribution.table (upperKernel slots upper lowerLevel σ useful r ρ) + +def decodeTable (r : Nat) + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) (s : Nat) + (table : Input (rows := rows) slots upper lowerLevel r → UpperAnswer slots upper) : + Input (rows := rows) slots upper lowerLevel r → + Option (HierarchicalDecoderTables.Answer slots upper lowerLevel d) := + fun input => HierarchicalDecoderTables.decode slots upper lowerLevel hbranch d s (table input) + +def responseLaw (r : Nat) (ρ : ℝ) + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) (s : Nat) + (input : Input (rows := rows) slots upper lowerLevel r) : + FiniteDistribution (Option (HierarchicalDecoderTables.Answer slots upper lowerLevel d)) := + (upperKernel slots upper lowerLevel σ useful r ρ input).pushforward + (HierarchicalDecoderTables.decode slots upper lowerLevel hbranch d s) + +def tableLaw (r : Nat) (ρ : ℝ) + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) (s : Nat) : + FiniteDistribution (Input (rows := rows) slots upper lowerLevel r → + Option (HierarchicalDecoderTables.Answer slots upper lowerLevel d)) := + FiniteDistribution.table (responseLaw slots upper lowerLevel hbranch σ useful r ρ d s) + +theorem upperTableLaw_pushforward (r : Nat) (ρ : ℝ) + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) (s : Nat) : + (upperTableLaw slots upper lowerLevel σ useful r ρ).pushforward + (decodeTable slots upper lowerLevel hbranch r d s) = + tableLaw slots upper lowerLevel hbranch σ useful r ρ d s := by + exact CleanConditioning.pushforward_law + (I := Input (rows := rows) slots upper lowerLevel r) + (Ω := fun _ => UpperAnswer slots upper) + (Γ := fun _ => Option (HierarchicalDecoderTables.Answer slots upper lowerLevel d)) + (upperKernel slots upper lowerLevel σ useful r ρ) + (fun _ => HierarchicalDecoderTables.decode slots upper lowerLevel hbranch d s) + +theorem supported_upper_table_valid (r : Nat) (ρ : ℝ) (hρ : 0 < ρ) + (table : Input (rows := rows) slots upper lowerLevel r → UpperAnswer slots upper) + (hsupport : (upperTableLaw slots upper lowerLevel σ useful r ρ).weight table ≠ 0) + (input : Input (rows := rows) slots upper lowerLevel r) : + HierarchicalLeftDecoder.Valid slots upper lowerLevel hbranch input.1 (table input) := by + have hrow := FiniteDistribution.table_row_weight_ne_zero + (upperKernel slots upper lowerLevel σ useful r ρ) table hsupport input + exact of_decide_eq_true (DecoderTableAdmissibility.event_of_probability_one + (upperKernel slots upper lowerLevel σ useful r ρ input) + (fun q => decide (HierarchicalLeftDecoder.Valid slots upper lowerLevel hbranch input.1 q)) + (HierarchicalLeftDecoder.adviceLaw_valid slots upper lowerLevel hbranch input.1 + σ (useful input.1) r ρ hρ input.2.1 input.2.2) (table input) hrow) + +theorem upperTableLaw_valid (r : Nat) (ρ : ℝ) (hρ : 0 < ρ) : + (upperTableLaw slots upper lowerLevel σ useful r ρ).probability + (fun table => decide (∀ input : Input (rows := rows) slots upper lowerLevel r, + HierarchicalLeftDecoder.Valid slots upper lowerLevel hbranch input.1 (table input))) = 1 := by + apply DecoderTableAdmissibility.probability_one_of_support + intro table hsupport + exact decide_eq_true (supported_upper_table_valid slots upper lowerLevel hbranch σ useful + r ρ hρ table hsupport) + +def RowValid (r : Nat) (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) (s : Nat) + (input : Input (rows := rows) slots upper lowerLevel r) + (z : HierarchicalDecoderTables.Answer slots upper lowerLevel d) : Prop := + HierarchicalDecoderTables.Valid slots upper lowerLevel input.1 hbranch d s z + +theorem responseLaw_valid (r : Nat) (ρ : ℝ) (hρ : 0 < ρ) + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) (s : Nat) + (input : Input (rows := rows) slots upper lowerLevel r) : + (responseLaw slots upper lowerLevel hbranch σ useful r ρ d s input).probability + (fun answer => decide (DecoderTableAdmissibility.RowValid + (RowValid slots upper lowerLevel hbranch r d s) input answer)) = 1 := by + have hlaw : responseLaw slots upper lowerLevel hbranch σ useful r ρ d s input = + HierarchicalDecoderTables.responseLaw slots upper lowerLevel input.1 hbranch + σ (useful input.1) r ρ d s input.2 := rfl + rw [hlaw] + apply row_probability_of_raw + (Q := Input (rows := rows) slots upper lowerLevel r) + (A := HierarchicalDecoderTables.Answer slots upper lowerLevel d) + (HierarchicalDecoderTables.responseLaw slots upper lowerLevel input.1 hbranch + σ (useful input.1) r ρ d s input.2) + (RowValid slots upper lowerLevel hbranch r d s) input + (HierarchicalDecoderTables.Valid slots upper lowerLevel input.1 hbranch d s) rfl + rw [← HierarchicalDecoderTables.responseLaw_valid slots upper lowerLevel input.1 hbranch + σ (useful input.1) r ρ hρ d s input.2] + apply congrArg (HierarchicalDecoderTables.responseLaw slots upper lowerLevel input.1 hbranch + σ (useful input.1) r ρ d s input.2).probability + funext answer + exact (@decide_eq_decide _ _ _ _).mpr Iff.rfl + +theorem supported_table_valid (r : Nat) (ρ : ℝ) (hρ : 0 < ρ) + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) (s : Nat) + (table : Input (rows := rows) slots upper lowerLevel r → + Option (HierarchicalDecoderTables.Answer slots upper lowerLevel d)) + (hsupport : (tableLaw slots upper lowerLevel hbranch σ useful r ρ d s).weight table ≠ 0) : + DecoderTableAdmissibility.Admissible (RowValid slots upper lowerLevel hbranch r d s) table := by + exact DecoderTableAdmissibility.table_admissible_of_probability_one + (responseLaw slots upper lowerLevel hbranch σ useful r ρ d s) + (RowValid slots upper lowerLevel hbranch r d s) + (responseLaw_valid slots upper lowerLevel hbranch σ useful r ρ hρ d s) table hsupport + +theorem tableLaw_valid (r : Nat) (ρ : ℝ) (hρ : 0 < ρ) + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) (s : Nat) : + (tableLaw slots upper lowerLevel hbranch σ useful r ρ d s).probability + (fun table => decide (DecoderTableAdmissibility.Admissible + (RowValid slots upper lowerLevel hbranch r d s) table)) = 1 := + DecoderTableAdmissibility.table_admissible_probability_one + (responseLaw slots upper lowerLevel hbranch σ useful r ρ d s) + (RowValid slots upper lowerLevel hbranch r d s) + (responseLaw_valid slots upper lowerLevel hbranch σ useful r ρ hρ d s) + +theorem decoded_supported_table_valid (r : Nat) (ρ : ℝ) (hρ : 0 < ρ) + (table : Input (rows := rows) slots upper lowerLevel r → UpperAnswer slots upper) + (hsupport : (upperTableLaw slots upper lowerLevel σ useful r ρ).weight table ≠ 0) + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) (s : Nat) : + DecoderTableAdmissibility.Admissible (RowValid slots upper lowerLevel hbranch r d s) + (decodeTable slots upper lowerLevel hbranch r d s table) := by + intro input z hz + exact HierarchicalDecoderTables.decode_valid slots upper lowerLevel input.1 hbranch d s + (table input) (supported_upper_table_valid slots upper lowerLevel hbranch σ useful + r ρ hρ table hsupport input) z hz + +end +end PerfectCompleteness.HierarchicalAllDecoderTables + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/HierarchicalDecoderMeetingLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/HierarchicalDecoderMeetingLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..f50d75bfdcf1e1faf730c54a2d14fcce55a5168e --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/HierarchicalDecoderMeetingLemmas.lean @@ -0,0 +1,317 @@ +import Mathlib.LinearAlgebra.FiniteDimensional.Lemmas +import OAI.Computability.PerfectCompleteness.Algebra.AffineDecoderMeeting +import OAI.Computability.PerfectCompleteness.Algebra.RightDecoderAffineSuccess +import OAI.Computability.PerfectCompleteness.Algebra.TensorRowAdviceLemmas +import OAI.Computability.PerfectCompleteness.Algebra.TensorSliceDimension +import OAI.Computability.PerfectCompleteness.Decoding.HierarchicalLeftDecoder +import OAI.Computability.PerfectCompleteness.Reduction.FixedRows + +namespace OAI + + +namespace PerfectCompleteness.HierarchicalDecoderMeeting + +noncomputable section + +open scoped Classical TensorProduct +open TreeSourceSpaces HierarchicalArrays HierarchicalTensorSlice +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype +attribute [local instance] RightDecoder.characterFintype RightDecoder.scalarFintype + +private theorem affine_meeting_probability_lower + {source native : Type*} [AddCommGroup source] [Module F2 source] + [AddCommGroup native] [Module F2 native] + [FiniteDimensional F2 source] [FiniteDimensional F2 native] + (embedding : native →ₗ[F2] source) (knownRows : Submodule F2 source) + (columns : Submodule F2 (Module.Dual F2 (source ⧸ knownRows))) + (center : Module.Dual F2 source) {dimension : Nat} + (hcolumns : Module.finrank F2 columns ≤ dimension) + [nativeFintype : Fintype (Module.Dual F2 native)] + (right : FiniteDistribution (Module.Dual F2 native)) : + letI : Fintype (Module.Dual F2 source) := LeftDecoder.dualFintype (V := source) + ∀ (left : FiniteDistribution (Module.Dual F2 source)) + (nativeColumns : Submodule F2 (Module.Dual F2 native)) (offset : Module.Dual F2 native), + left = LeftDecoder.affineLaw knownRows columns center → + nativeColumns = AffineDecoderMeeting.nativeQ embedding knownRows columns → + offset = AffineDecoderMeeting.nativeCenter embedding center → + (1 / (2 : ℝ) ^ dimension) * right.probability + (fun decoded => decide (decoded - offset ∈ nativeColumns)) ≤ + (left.product right).probability + (fun pair => decide (embedding.dualMap pair.1 = pair.2)) := by + intro left nativeColumns offset hleft hcolumns' hoffset + rw [hleft, hcolumns', hoffset] + cases Subsingleton.elim nativeFintype (LeftDecoder.dualFintype (V := native)) + exact AffineDecoderMeeting.meeting_probability_lower embedding knownRows columns center hcolumns right + +variable {branch rows : Nat → Nat} {n t : Nat} + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (upper : Nodes branch n) (lowerLevel : Nat) + (background : HierarchicalMatrixTable.Background (rows := rows) slots upper) + +local instance rowSpaceFintype : Fintype (NodeEmbedding.RowSpace slots upper) := + Fintype.ofFinite _ + +local instance valueFintype : Fintype + (Block rows upper × HierarchicalMatrixTable.SideOutput (rows := rows) upper) := + Fintype.ofFinite _ + +local instance upperDualFintype : Fintype (Module.Dual F2 (NodeEmbedding.RowSpace slots upper)) := + LeftDecoder.dualFintype (V := NodeEmbedding.RowSpace slots upper) + +variable {Ω : Type*} [Fintype Ω] + (original : FiniteDistribution Ω) (arrays : Ω → Arrays slots rows) + (lowerEvent : Ω → Bool) (κ : ℝ) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + {r : Nat} (ρ : ℝ) (A : ManyGoodRows.RowMap (Block rows upper) r) + (known : HiddenBucketBias.VisibleDirection (LinearMap.ker A) → NodeEmbedding.NodeH slots upper) + +def useful (X : HierarchicalFrozenTables.QuotientMatrix slots upper lowerLevel background) : Prop := + HierarchicalUsefulness.mark slots upper lowerLevel original arrays lowerEvent κ + ⟨background, X⟩ = true + +def leftLaw : FiniteDistribution (Module.Dual F2 (NodeEmbedding.RowSpace slots upper)) := + HierarchicalLeftDecoder.adviceLaw slots upper lowerLevel background σ + (useful slots upper lowerLevel background original arrays lowerEvent κ) r ρ A + (A.comp (MatrixRowQuotient.projectMatrix + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + (visibleMatrix slots upper A known))) + +theorem leftLaw_eq_affine + (hgood : VisibleGood slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known) : + leftLaw slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known = + LeftDecoder.affineLaw + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + (witness slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood).columnSpace + (correction slots upper lowerLevel background + (witness slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood).value) := by + have h := LeftDecoder.adviceLaw_of_good (TreeCanonical.numberedSlots slots) + (NodeEmbedding.RowSpace slots upper) (HierarchicalMatrixTable.other slots upper background) σ + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + (HierarchicalFrozenTables.sectionMap slots upper lowerLevel background) + (HierarchicalFrozenTables.sectionMap_spec slots upper lowerLevel background) + (useful slots upper lowerLevel background original arrays lowerEvent κ) r ρ A + (A.comp (MatrixRowQuotient.projectMatrix + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + (visibleMatrix slots upper A known))) hgood + dsimp only [leftLaw, HierarchicalLeftDecoder.adviceLaw, LeftDecoder.law, LeftDecoder.center, + HierarchicalTensorSlice.witness, TensorSelectedSlice.witness, HierarchicalTensorSlice.correction, + HierarchicalTensorSlice.table, HierarchicalUsefulness.table, HierarchicalFrozenTables.table, + useful] at h ⊢ + exact h + +theorem columnSpace_eq_nativeQ + (hgood : VisibleGood slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known) : + columnSpace slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood = + AffineDecoderMeeting.nativeQ (NodeEmbedding.embed slots upper) + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + (witness slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood).columnSpace := + HierarchicalTensorSlice.columnSpace_eq_pulled slots upper lowerLevel background + original arrays lowerEvent κ σ ρ A known hgood + +theorem nativeCorrection_eq_nativeCenter + (hgood : VisibleGood slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known) : + nativeCorrection slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood = + AffineDecoderMeeting.nativeCenter (NodeEmbedding.embed slots upper) + (correction slots upper lowerLevel background + (witness slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood).value) := rfl + +variable (lower : Nodes branch n) (a : Block rows lower) + (repeats : Nat → Nat) (cut : OwnInputReference.Cut upper lower) + (input : OwnInputReference.Input slots rows upper lower (LinearMap.ker A) a) + +theorem meeting_probability_ge_coset + (hgood : VisibleGood slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known) + (threshold : ℝ) : + (1 / (2 : ℝ) ^ r) * + (RightDecoder.law slots rows upper lower (LinearMap.ker A) a repeats cut σ input threshold).probability + (fun decoded => decide (decoded - + nativeCorrection slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood ∈ + columnSpace slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood)) ≤ + ((leftLaw slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known).product + (RightDecoder.law slots rows upper lower (LinearMap.ker A) a repeats cut σ input threshold)).probability + (fun pair => decide ((NodeEmbedding.embed slots upper).dualMap pair.1 = pair.2)) := by + convert affine_meeting_probability_lower + (source := NodeEmbedding.RowSpace slots upper) + (native := OwnInputReference.UpperSpace slots upper) + (NodeEmbedding.embed slots upper) + (nativeFintype := RightDecoder.scalarFintype slots upper) + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + (witness slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood).columnSpace + (correction slots upper lowerLevel background + (witness slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood).value) + (witness slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood).column_count + (RightDecoder.law slots rows upper lower (LinearMap.ker A) a repeats cut σ input threshold) + (leftLaw slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known) + (columnSpace slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood) + (nativeCorrection slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood) + (leftLaw_eq_affine slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood) + (columnSpace_eq_nativeQ slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood) + (nativeCorrection_eq_nativeCenter slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood) + +theorem meeting_probability_lower + (hgood : VisibleGood slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known) + (hne : ∃ T, J slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known T = true) + (ρpred h₀ : ℝ) (hρpred : 0 < ρpred) (hh₀ : 0 < h₀) + (hrep : RecursiveSamplerBias.RepetitionsBalanced repeats) + (hslice : (7 / 8 : ℝ) ^ repeats (Nodes.height upper) ≤ h₀ / 2) + (hlist : (7 / 8 : ℝ) ^ repeats (Nodes.height upper) ≤ (ρpred * h₀ / 4) ^ 2 / 2) + (hexcluded : 1 / (2 : ℝ) ^ Module.finrank F2 (LinearMap.ker A) < ρpred / 8) + (hsize : h₀ ≤ 1 / (2 : ℝ) ^ (r * rows (Nodes.height upper))) + (hmatch : ρpred ≤ RightDecoderWitness.conditionalMatch slots rows upper lower + (LinearMap.ker A) a repeats cut σ input + (columnSpace slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood) + (target slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood hne) + (nativeCorrection slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood) + (visibleOffset slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood)) : + (1 / (2 : ℝ) ^ r) * + ((ρpred * h₀ / 4) ^ 2 / (2 * (2 : ℝ) ^ rows (Nodes.height upper))) ≤ + ((leftLaw slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known).product + (RightDecoder.law slots rows upper lower (LinearMap.ker A) a repeats cut σ input + (ρpred * h₀ / 4))).probability + (fun pair => decide ((NodeEmbedding.embed slots upper).dualMap pair.1 = pair.2)) := by + have hdimension := TensorSliceDimension.equation_finrank_le (LinearMap.ker A) + (columnSpace slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood) + (HierarchicalTensorSlice.finrank_columnSpace_le slots upper lowerLevel background + original arrays lowerEvent κ σ ρ A known hgood) + have hsize' : h₀ ≤ 1 / (2 : ℝ) ^ Module.finrank F2 + ((columnSpace slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood) →ₗ[F2] + LinearMap.ker A) := + hsize.trans (one_div_pow_le_one_div_pow_of_le (by norm_num : (1 : ℝ) ≤ 2) hdimension) + have hright := RightDecoderAffineSuccess.coset_probability_lower slots rows upper lower + (LinearMap.ker A) a repeats cut σ input ρpred h₀ hρpred hh₀ hrep hslice hlist hexcluded + (columnSpace slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood) + hsize' + (target slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood hne) + (nativeCorrection slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood) + (visibleOffset slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood) hmatch + exact (mul_le_mul_of_nonneg_left hright + (div_nonneg zero_le_one (pow_nonneg (by norm_num : (0 : ℝ) ≤ 2) r))).trans + (meeting_probability_ge_coset slots upper lowerLevel background original arrays lowerEvent κ σ ρ A known + lower a repeats cut input hgood (ρpred * h₀ / 4)) + +end +end PerfectCompleteness.HierarchicalDecoderMeeting + + +namespace PerfectCompleteness.HierarchicalFixedDecoderMeeting + +noncomputable section + +open scoped Classical TensorProduct +open TreeSourceSpaces HierarchicalArrays HierarchicalTensorSlice +open UpperParameterScalars +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype +attribute [local instance] RightDecoder.characterFintype RightDecoder.scalarFintype + +theorem kernel_finrank_ge {ℓ r : Nat} (A : ManyGoodRows.RowMap (Fin ℓ → F2) r) : + ℓ - r ≤ Module.finrank F2 (LinearMap.ker A) := by + have hrange : Module.finrank F2 (LinearMap.range A) ≤ r := by + simpa only [Module.finrank_fin_fun] using (Submodule.finrank_le (LinearMap.range A)) + have hdim := LinearMap.finrank_range_add_finrank_ker A + simp only [Module.finrank_fin_fun] at hdim + change Module.finrank F2 (LinearMap.range A) + Module.finrank F2 (LinearMap.ker A) = ℓ at hdim + omega + +variable {δ : ℚ} (plan : FixedRows.Plan δ) + +theorem repetitionsBalanced : RecursiveSamplerBias.RepetitionsBalanced (FixedRows.repeats plan) := + RecursiveSamplerBias.repetitionsBalanced_of_six_le (FixedRows.repeats plan) + (fun k => plan.repeats_min (FixedRows.rows plan (k + 1))) + +theorem slice_error (height : Nat) : + (7 / 8 : ℝ) ^ FixedRows.repeats plan height ≤ + h plan.order (FixedRows.rows plan height) / 2 := + (plan.repeats_error (FixedRows.rows plan height)).trans (min_le_left _ _) + +theorem list_error (height : Nat) : + (7 / 8 : ℝ) ^ FixedRows.repeats plan height ≤ + tau (InitialParameters.useful δ) plan.density plan.order (FixedRows.rows plan height) ^ 2 / 2 := + (plan.repeats_error (FixedRows.rows plan height)).trans (min_le_right _ _) + +theorem kernel_excluded (height : Nat) + (A : ManyGoodRows.RowMap (Fin (FixedRows.rows plan height) → F2) plan.order) : + 1 / (2 : ℝ) ^ Module.finrank F2 (LinearMap.ker A) < + rhoPred (InitialParameters.useful δ) plan.density / 8 := by + have hker := kernel_finrank_ge A + apply (one_div_pow_le_one_div_pow_of_le (by norm_num : (1 : ℝ) ≤ 2) hker).trans_lt + simpa only [FixedRows.rows, DescendingRows.treeRows] using + plan.rows_correction (plan.depth - height) + +variable (hδ : 0 < δ) {branch : Nat → Nat} {t : Nat} + (slots : RecursiveSpaces.Slots branch plan.depth → Fin t → MixedSupport.Slot) + (upper : Nodes branch plan.depth) (lowerLevel : Nat) + (background : HierarchicalMatrixTable.Background + (rows := FixedRows.rows plan) slots upper) + +local instance rowSpaceFintype : Fintype (NodeEmbedding.RowSpace slots upper) := + Fintype.ofFinite _ + +local instance valueFintype : Fintype + (Block (FixedRows.rows plan) upper × + HierarchicalMatrixTable.SideOutput (rows := FixedRows.rows plan) upper) := + Fintype.ofFinite _ + +local instance upperDualFintype : Fintype (Module.Dual F2 (NodeEmbedding.RowSpace slots upper)) := + LeftDecoder.dualFintype (V := NodeEmbedding.RowSpace slots upper) + +variable {Ω : Type*} [Fintype Ω] + (original : FiniteDistribution Ω) (arrays : Ω → Arrays slots (FixedRows.rows plan)) + (lowerEvent : Ω → Bool) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch plan.depth t)) + (A : ManyGoodRows.RowMap (Block (FixedRows.rows plan) upper) plan.order) + (known : HiddenBucketBias.VisibleDirection (LinearMap.ker A) → NodeEmbedding.NodeH slots upper) + (lower : Nodes branch plan.depth) (a : Block (FixedRows.rows plan) lower) + (cut : OwnInputReference.Cut upper lower) + (input : OwnInputReference.Input slots (FixedRows.rows plan) upper lower (LinearMap.ker A) a) + +include hδ + +theorem meeting_probability_lower + (hgood : VisibleGood slots upper lowerLevel background original arrays lowerEvent + (InitialParameters.useful δ) σ plan.density A known) + (hne : ∃ T, J slots upper lowerLevel background original arrays lowerEvent + (InitialParameters.useful δ) σ plan.density A known T = true) + (hmatch : rhoPred (InitialParameters.useful δ) plan.density ≤ + RightDecoderWitness.conditionalMatch slots (FixedRows.rows plan) upper lower + (LinearMap.ker A) a (FixedRows.repeats plan) cut σ input + (columnSpace slots upper lowerLevel background original arrays lowerEvent + (InitialParameters.useful δ) σ plan.density A known hgood) + (target slots upper lowerLevel background original arrays lowerEvent + (InitialParameters.useful δ) σ plan.density A known hgood hne) + (nativeCorrection slots upper lowerLevel background original arrays lowerEvent + (InitialParameters.useful δ) σ plan.density A known hgood) + (visibleOffset slots upper lowerLevel background original arrays lowerEvent + (InitialParameters.useful δ) σ plan.density A known hgood)) : + (1 / (2 : ℝ) ^ plan.order) * + (tau (InitialParameters.useful δ) plan.density plan.order + (FixedRows.rows plan (Nodes.height upper)) ^ 2 / + (2 * (2 : ℝ) ^ FixedRows.rows plan (Nodes.height upper))) ≤ + ((HierarchicalDecoderMeeting.leftLaw slots upper lowerLevel background original arrays lowerEvent + (InitialParameters.useful δ) σ plan.density A known).product + (RightDecoder.law slots (FixedRows.rows plan) upper lower (LinearMap.ker A) a + (FixedRows.repeats plan) cut σ input + (tau (InitialParameters.useful δ) plan.density plan.order + (FixedRows.rows plan (Nodes.height upper))))).probability + (fun pair => decide ((NodeEmbedding.embed slots upper).dualMap pair.1 = pair.2)) := by + simpa only [UpperParameterScalars.tau] using + (HierarchicalDecoderMeeting.meeting_probability_lower slots upper lowerLevel background + original arrays lowerEvent (InitialParameters.useful δ) σ plan.density A known + lower a (FixedRows.repeats plan) cut input hgood hne + (rhoPred (InitialParameters.useful δ) plan.density) + (h plan.order (FixedRows.rows plan (Nodes.height upper))) + (rhoPred_pos (InitialParameters.useful_pos hδ) plan.density_pos) + (h_pos plan.order (FixedRows.rows plan (Nodes.height upper))) + (repetitionsBalanced plan) (slice_error plan (Nodes.height upper)) + (list_error plan (Nodes.height upper)) (kernel_excluded plan (Nodes.height upper) A) + le_rfl hmatch) + +end +end PerfectCompleteness.HierarchicalFixedDecoderMeeting + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/HierarchicalDecoderTables.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/HierarchicalDecoderTables.lean new file mode 100644 index 0000000000000000000000000000000000000000..11e3d48588b21adb8cbf808b870ddcbbbf669453 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/HierarchicalDecoderTables.lean @@ -0,0 +1,253 @@ +import OAI.Computability.PerfectCompleteness.Decoding.HierarchicalLeftDecoder +import OAI.Computability.PerfectCompleteness.Foundations.MultiplicationFormInjectiveLemmas +import OAI.Computability.PerfectCompleteness.Repetition.CleanConditioning + +namespace OAI + +section + +namespace PerfectCompleteness.HierarchicalDecoderTables + +noncomputable section + +open scoped Classical +open TreeSourceSpaces HierarchicalArrays PointwiseSpaces +open UniqueGamesTheorem.Foundations.Games + +attribute [local instance] UniqueGamesTheorem.Appendix.RankLevelFilter.linearMapFintype + +section ConstantValidity + +variable {Q A Ω : Type*} [Fintype Q] [DecidableEq Q] [Fintype A] [Fintype Ω] + +omit [Fintype Q] [DecidableEq Q] in +private theorem constant_row_event_eq (valid : A → Prop) (q : Q) : + (fun answer : Option A => decide + (DecoderTableAdmissibility.RowValid (fun (_ : Q) => valid) q answer)) = + (fun answer : Option A => decide (∀ z, answer = some z → valid z)) := by + funext answer + exact (@decide_eq_decide + (DecoderTableAdmissibility.RowValid (fun (_ : Q) => valid) q answer) + (∀ z, answer = some z → valid z) _ _).mpr Iff.rfl + +private theorem table_admissible_of_constant_probability_one + (responses : Q → FiniteDistribution (Option A)) (valid : A → Prop) + (hvalid : ∀ q, (responses q).probability + (fun answer => decide (∀ z, answer = some z → valid z)) = 1) + (table : Q → Option A) + (hsupport : (FiniteDistribution.table responses).weight table ≠ 0) : + DecoderTableAdmissibility.Admissible (fun (_ : Q) => valid) table := by + apply DecoderTableAdmissibility.table_admissible_of_probability_one + responses (fun (_ : Q) => valid) _ table hsupport + intro q + exact (congrArg (responses q).probability (constant_row_event_eq valid q)).trans (hvalid q) + +private theorem hit_square_le_of_constant_probability_one + (responses : Q → FiniteDistribution (Option A)) + (ν : FiniteDistribution Ω) (ownInput : Ω → Q) (right : A) + (valid : A → Prop) + (hvalid : ∀ q, (responses q).probability + (fun answer => decide (∀ z, answer = some z → valid z)) = 1) + (bound : ℝ) + (hbound : ∀ table : Q → Option A, + DecoderTableAdmissibility.Admissible (fun (_ : Q) => valid) table → + StochasticSingleResponse.tableCollision ν ownInput table ≤ bound) : + StochasticSingleResponse.hit responses ν ownInput right ^ 2 ≤ bound := by + apply StochasticSingleResponse.hit_square_le_of_probability_one + responses ν ownInput right (fun (_ : Q) => valid) _ bound hbound + intro q + exact (congrArg (responses q).probability (constant_row_event_eq valid q)).trans (hvalid q) + +end ConstantValidity + +variable {branch rows : Nat → Nat} {n t : Nat} + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (upper : Nodes branch n) (lowerLevel : Nat) + (background : HierarchicalMatrixTable.Background (rows := rows) slots upper) + +local instance rowSpaceFintype (node : Nodes branch n) : + Fintype (NodeEmbedding.RowSpace slots node) := Fintype.ofFinite _ + +local instance nodeSpaceFintype (node : Nodes branch n) : + Fintype (NodeEmbedding.NodeH slots node) := Fintype.ofFinite _ + +local instance upperDualFintype : + Fintype (Module.Dual F2 (NodeEmbedding.RowSpace slots upper)) := + LeftDecoder.dualFintype (V := NodeEmbedding.RowSpace slots upper) + +abbrev Advice (r : Nat) := + ManyGoodRows.RowMap (Block rows upper) r × + (Module.Dual F2 (NodeEmbedding.RowSpace slots upper ⧸ + HierarchicalFrozenTables.knownRows slots upper lowerLevel background) →ₗ[F2] + (Fin r → F2)) + +local instance adviceFintype (r : Nat) : + Fintype (Advice slots upper lowerLevel background r) := by + letI : Fintype (Module.Dual F2 (NodeEmbedding.RowSpace slots upper ⧸ + HierarchicalFrozenTables.knownRows slots upper lowerLevel background)) := + LeftDecoder.dualFintype + infer_instance + +variable (hbranch : ∀ k < n, 0 < branch k) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (useful : HierarchicalFrozenTables.QuotientMatrix slots upper lowerLevel background → Prop) + +abbrev LowerH (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) := + NodeEmbedding.NodeH slots (HierarchicalLeftDecoder.LowerNode upper lowerLevel d) + +abbrev Answer (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) := + Module.Dual F2 (squareSpace (LowerH slots upper lowerLevel d)) + +local instance answerFintype (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) : + Fintype (Answer slots upper lowerLevel d) := + LeftDecoder.dualFintype (V := squareSpace (LowerH slots upper lowerLevel d)) + +def fullRank (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) + (z : Answer slots upper lowerLevel d) : Nat := + OddListExtraction.formRank (LowerH slots upper lowerLevel d) + (OddListExtraction.multiplicationForm (LowerH slots upper lowerLevel d) z) + +def decode (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) (s : Nat) + (q : Module.Dual F2 (NodeEmbedding.RowSpace slots upper)) : + Option (Answer slots upper lowerLevel d) := + let z := HierarchicalLeftDecoder.output slots upper lowerLevel hbranch d q + if fullRank slots upper lowerLevel d z ≤ s then none else some z + +def responseLaw (r : Nat) (ρ : ℝ) + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) (s : Nat) + (advice : Advice slots upper lowerLevel background r) : + FiniteDistribution (Option (Answer slots upper lowerLevel d)) := + (HierarchicalLeftDecoder.adviceLaw slots upper lowerLevel background σ useful r ρ + advice.1 advice.2).pushforward (decode slots upper lowerLevel hbranch d s) + +def Valid (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) (s : Nat) + (z : Answer slots upper lowerLevel d) : Prop := + z (HierarchicalLeftDecoder.lowerOne slots upper lowerLevel hbranch d) = 1 ∧ + (LowerAffineSliceRank.testedGram + (FunctionSpaceLowerRank.matrixForm (LowerH slots upper lowerLevel d) + (OddListExtraction.multiplicationForm (LowerH slots upper lowerLevel d) z)) + (HierarchicalLeftDecoder.testedMatrix slots upper lowerLevel background d)).rank ≤ 1 ∧ + s < fullRank slots upper lowerLevel d z + +theorem decode_valid + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) (s : Nat) + (q : Module.Dual F2 (NodeEmbedding.RowSpace slots upper)) + (hq : HierarchicalLeftDecoder.Valid slots upper lowerLevel hbranch background q) + (z : Answer slots upper lowerLevel d) + (hz : decode slots upper lowerLevel hbranch d s q = some z) : + Valid slots upper lowerLevel background hbranch d s z := by + change (if fullRank slots upper lowerLevel d + (HierarchicalLeftDecoder.output slots upper lowerLevel hbranch d q) ≤ s then none + else some (HierarchicalLeftDecoder.output slots upper lowerLevel hbranch d q)) = some z at hz + split at hz + · cases hz + · rename_i hrank + have heq := Option.some.inj hz + subst z + exact ⟨(hq d).1, (hq d).2, Nat.lt_of_not_ge hrank⟩ + +theorem responseLaw_valid (r : Nat) (ρ : ℝ) (hρ : 0 < ρ) + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) (s : Nat) + (advice : Advice slots upper lowerLevel background r) : + (responseLaw slots upper lowerLevel background hbranch σ useful r ρ d s advice).probability + (fun answer => decide (∀ z, answer = some z → + Valid slots upper lowerLevel background hbranch d s z)) = 1 := by + rw [responseLaw, FiniteDistribution.probability_pushforward] + apply le_antisymm (FiniteDistribution.probability_le_one _ _) + rw [← HierarchicalLeftDecoder.adviceLaw_valid slots upper lowerLevel hbranch background + σ useful r ρ hρ advice.1 advice.2] + apply FiniteDistribution.probability_mono + intro q hq + apply decide_eq_true + intro z hz + exact decode_valid slots upper lowerLevel background hbranch d s q + (of_decide_eq_true hq) z hz + +def tableLaw (r : Nat) (ρ : ℝ) + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) (s : Nat) : + FiniteDistribution (Advice slots upper lowerLevel background r → + Option (Answer slots upper lowerLevel d)) := + FiniteDistribution.table + (responseLaw slots upper lowerLevel background hbranch σ useful r ρ d s) + +def upperTableLaw (r : Nat) (ρ : ℝ) : + FiniteDistribution (Advice slots upper lowerLevel background r → + Module.Dual F2 (NodeEmbedding.RowSpace slots upper)) := + FiniteDistribution.table (fun advice : Advice slots upper lowerLevel background r => + HierarchicalLeftDecoder.adviceLaw slots upper lowerLevel background σ useful + r ρ advice.1 advice.2) + +theorem upperTableLaw_pushforward (r : Nat) (ρ : ℝ) + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) (s : Nat) : + (upperTableLaw slots upper lowerLevel background σ useful r ρ).pushforward + (fun table advice => decode slots upper lowerLevel hbranch d s (table advice)) = + tableLaw slots upper lowerLevel background hbranch σ useful r ρ d s := by + exact CleanConditioning.pushforward_law + (fun advice : Advice slots upper lowerLevel background r => + HierarchicalLeftDecoder.adviceLaw slots upper lowerLevel background σ useful + r ρ advice.1 advice.2) + (fun _ => decode slots upper lowerLevel hbranch d s) + +theorem supported_table_valid (r : Nat) (ρ : ℝ) (hρ : 0 < ρ) + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) (s : Nat) + (table : Advice slots upper lowerLevel background r → Option (Answer slots upper lowerLevel d)) + (hsupport : (tableLaw slots upper lowerLevel background hbranch σ useful r ρ d s).weight table ≠ 0) : + DecoderTableAdmissibility.Admissible + (Q := Advice slots upper lowerLevel background r) + (A := Answer slots upper lowerLevel d) + (fun (_ : Advice slots upper lowerLevel background r) + (z : Answer slots upper lowerLevel d) => + Valid slots upper lowerLevel background hbranch d s z) table := by + apply table_admissible_of_constant_probability_one + (Q := Advice slots upper lowerLevel background r) + (A := Answer slots upper lowerLevel d) + (responseLaw slots upper lowerLevel background hbranch σ useful r ρ d s) + (Valid slots upper lowerLevel background hbranch d s) + _ table hsupport + intro advice + rw [← responseLaw_valid slots upper lowerLevel background hbranch σ useful r ρ hρ d s advice] + apply congrArg (responseLaw slots upper lowerLevel background hbranch σ useful r ρ d s + advice).probability + funext answer + exact (@decide_eq_decide _ _ _ _).mpr Iff.rfl + +theorem hit_square_le {Ω : Type*} [Fintype Ω] + (r : Nat) (ρ : ℝ) (hρ : 0 < ρ) + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) (s : Nat) + (ν : FiniteDistribution Ω) (ownInput : Ω → Advice slots upper lowerLevel background r) + (right : Answer slots upper lowerLevel d) (bound : ℝ) + (hbound : ∀ table : Advice slots upper lowerLevel background r → + Option (Answer slots upper lowerLevel d), + DecoderTableAdmissibility.Admissible + (Q := Advice slots upper lowerLevel background r) + (A := Answer slots upper lowerLevel d) + (fun (_ : Advice slots upper lowerLevel background r) + (z : Answer slots upper lowerLevel d) => + Valid slots upper lowerLevel background hbranch d s z) table → + StochasticSingleResponse.tableCollision + (Q := Advice slots upper lowerLevel background r) + (A := Answer slots upper lowerLevel d) (Ω := Ω) ν ownInput table ≤ bound) : + StochasticSingleResponse.hit + (Q := Advice slots upper lowerLevel background r) + (A := Answer slots upper lowerLevel d) (Ω := Ω) + (responseLaw slots upper lowerLevel background hbranch σ useful r ρ d s) + ν ownInput right ^ 2 ≤ bound := by + apply hit_square_le_of_constant_probability_one + (Q := Advice slots upper lowerLevel background r) + (A := Answer slots upper lowerLevel d) (Ω := Ω) + (responseLaw slots upper lowerLevel background hbranch σ useful r ρ d s) + ν ownInput right (Valid slots upper lowerLevel background hbranch d s) + _ bound hbound + intro advice + rw [← responseLaw_valid slots upper lowerLevel background hbranch σ useful r ρ hρ d s advice] + apply congrArg (responseLaw slots upper lowerLevel background hbranch σ useful r ρ d s + advice).probability + funext answer + exact (@decide_eq_decide _ _ _ _).mpr Iff.rfl + +end +end PerfectCompleteness.HierarchicalDecoderTables + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/HierarchicalLeftDecoder.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/HierarchicalLeftDecoder.lean new file mode 100644 index 0000000000000000000000000000000000000000..a5bc3059fc62aef13c821ab8187912ef4776f78b --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/HierarchicalLeftDecoder.lean @@ -0,0 +1,218 @@ +import OAI.Computability.PerfectCompleteness.Algebra.FunctionSpaceLowerRank +import OAI.Computability.PerfectCompleteness.Decoding.LeftDecoderKnownRows +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalFrozenTablesLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.HierarchicalLeftDecoder + +noncomputable section + +open scoped Classical +open TreeSourceSpaces HierarchicalArrays PointwiseSpaces +open UniqueGamesTheorem.Foundations.Games + +attribute [local instance] UniqueGamesTheorem.Appendix.RankLevelFilter.linearMapFintype + +variable {branch rows : Nat → Nat} {n t : Nat} + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (upper : Nodes branch n) (lowerLevel : Nat) + +abbrev LowerNode (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) := + (HierarchicalFrozenTables.lowerIndex upper lowerLevel d).val + +local instance rowSpaceFintype (node : Nodes branch n) : + Fintype (NodeEmbedding.RowSpace slots node) := Fintype.ofFinite _ + +local instance nodeSpaceFintype (node : Nodes branch n) : + Fintype (NodeEmbedding.NodeH slots node) := Fintype.ofFinite _ + +local instance upperDualFintype : Fintype (Module.Dual F2 (NodeEmbedding.RowSpace slots upper)) := + LeftDecoder.dualFintype (V := NodeEmbedding.RowSpace slots upper) + +variable (hbranch : ∀ k < n, 0 < branch k) + +def squareEmbedding (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) : + squareSpace (NodeEmbedding.NodeH slots (LowerNode upper lowerLevel d)) →ₗ[F2] + NodeEmbedding.RowSpace slots upper where + toFun f := ⟨PointwiseSpaces.pullback F2 + (NodeEmbedding.numberedRestriction slots (LowerNode upper lowerLevel d)) f.val, by + apply RelativeDescendantProducts.squareSpace_le_rowSpace slots hbranch + (RelativeDescendantProducts.descendantIndex_below upper d.val) + rw [NodeEmbedding.squareSpace_eq] + exact Submodule.mem_map_of_mem f.property⟩ + map_add' _ _ := Subtype.ext rfl + map_smul' _ _ := Subtype.ext rfl + +@[simp] theorem squareEmbedding_apply + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) + (f : squareSpace (NodeEmbedding.NodeH slots (LowerNode upper lowerLevel d))) + (x : NodeEmbedding.NumberedDomain slots) : + (squareEmbedding slots upper lowerLevel hbranch d f).val x = + f.val (NodeEmbedding.numberedRestriction slots (LowerNode upper lowerLevel d) x) := rfl + +def output (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) + (q : Module.Dual F2 (NodeEmbedding.RowSpace slots upper)) : + Module.Dual F2 (squareSpace (NodeEmbedding.NodeH slots (LowerNode upper lowerLevel d))) := + q.comp (squareEmbedding slots upper lowerLevel hbranch d) + +def lowerOne (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) : + squareSpace (NodeEmbedding.NodeH slots (LowerNode upper lowerLevel d)) := + ⟨1, TreeSourceSpaces.one_mem_squareSpace + (nodeSlots slots (LowerNode upper lowerLevel d)) + (fun k hk => hbranch k (Nat.lt_of_lt_of_le hk + (Nodes.height_le (LowerNode upper lowerLevel d))))⟩ + +variable (background : HierarchicalMatrixTable.Background (rows := rows) slots upper) + +def testedMatrix (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) : + Module.Dual F2 (NodeEmbedding.NodeH slots (LowerNode upper lowerLevel d)) →ₗ[F2] + Block rows (LowerNode upper lowerLevel d) := + EvaluationMatrix.ofRows (NodeEmbedding.NodeH slots (LowerNode upper lowerLevel d)) + (background (HierarchicalFrozenTables.lowerIndex upper lowerLevel d)) + +def oneKnown : HierarchicalFrozenTables.knownRows slots upper lowerLevel background := + ⟨⟨1, RelativeDescendantProducts.one_mem_rowSpace slots hbranch upper⟩, + HierarchicalKnownRows.one_mem_knownSpace slots upper background + (HierarchicalFrozenTables.lowerIndex upper lowerLevel)⟩ + +def productKnown (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) + (i j : Fin (rows (Nodes.height (LowerNode upper lowerLevel d)))) : + HierarchicalFrozenTables.knownRows slots upper lowerLevel background := + ⟨squareEmbedding slots upper lowerLevel hbranch d + (OddListExtraction.productElement + (NodeEmbedding.NodeH slots (LowerNode upper lowerLevel d)) + (background (HierarchicalFrozenTables.lowerIndex upper lowerLevel d) i) + (background (HierarchicalFrozenTables.lowerIndex upper lowerLevel d) j)), + HierarchicalKnownRows.product_mem_knownSpace slots upper background + (HierarchicalFrozenTables.lowerIndex upper lowerLevel) d i j⟩ + +theorem output_normalized_of_known_realizer + (q : Module.Dual F2 (NodeEmbedding.RowSpace slots upper)) + (x : NodeEmbedding.NumberedDomain slots) + (hknown : ∀ b : HierarchicalFrozenTables.knownRows slots upper lowerLevel background, + q (b : NodeEmbedding.RowSpace slots upper) = b.val.val x) + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) : + output slots upper lowerLevel hbranch d q (lowerOne slots upper lowerLevel hbranch d) = 1 := by + exact hknown (oneKnown slots upper lowerLevel hbranch background) + +theorem tested_rank_le_one_of_known_realizer + (q : Module.Dual F2 (NodeEmbedding.RowSpace slots upper)) + (x : NodeEmbedding.NumberedDomain slots) + (hknown : ∀ b : HierarchicalFrozenTables.knownRows slots upper lowerLevel background, + q (b : NodeEmbedding.RowSpace slots upper) = b.val.val x) + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) : + (LowerAffineSliceRank.testedGram + (FunctionSpaceLowerRank.matrixForm + (NodeEmbedding.NodeH slots (LowerNode upper lowerLevel d)) + (OddListExtraction.multiplicationForm + (NodeEmbedding.NodeH slots (LowerNode upper lowerLevel d)) + (output slots upper lowerLevel hbranch d q))) + (testedMatrix slots upper lowerLevel background d)).rank ≤ 1 := by + let v := HierarchicalKnownRows.lower slots upper background + (HierarchicalFrozenTables.lowerIndex upper lowerLevel) x d + have hgram : LowerAffineSliceRank.testedGram + (FunctionSpaceLowerRank.matrixForm + (NodeEmbedding.NodeH slots (LowerNode upper lowerLevel d)) + (OddListExtraction.multiplicationForm + (NodeEmbedding.NodeH slots (LowerNode upper lowerLevel d)) + (output slots upper lowerLevel hbranch d q))) + (testedMatrix slots upper lowerLevel background d) = fun i j => v i * v j := by + rw [FunctionSpaceLowerRank.testedGram_multiplicationForm] + simp only [testedMatrix, EvaluationMatrix.rows_ofRows] + funext i j + exact hknown (productKnown slots upper lowerLevel hbranch background d i j) + rw [hgram] + exact Matrix.rank_vecMulVec_le v v + +def Valid (q : Module.Dual F2 (NodeEmbedding.RowSpace slots upper)) : Prop := + ∀ d : HierarchicalFrozenTables.LowerNodes upper lowerLevel, + output slots upper lowerLevel hbranch d q (lowerOne slots upper lowerLevel hbranch d) = 1 ∧ + (LowerAffineSliceRank.testedGram + (FunctionSpaceLowerRank.matrixForm + (NodeEmbedding.NodeH slots (LowerNode upper lowerLevel d)) + (OddListExtraction.multiplicationForm + (NodeEmbedding.NodeH slots (LowerNode upper lowerLevel d)) + (output slots upper lowerLevel hbranch d q))) + (testedMatrix slots upper lowerLevel background d)).rank ≤ 1 + +theorem valid_of_known_realizer + (q : Module.Dual F2 (NodeEmbedding.RowSpace slots upper)) + (hreal : ∃ x : NodeEmbedding.NumberedDomain slots, + ∀ b : HierarchicalFrozenTables.knownRows slots upper lowerLevel background, + q (b : NodeEmbedding.RowSpace slots upper) = b.val.val x) : + Valid slots upper lowerLevel hbranch background q := by + obtain ⟨x, hx⟩ := hreal + intro d + exact ⟨output_normalized_of_known_realizer slots upper lowerLevel hbranch background q x hx d, + tested_rank_le_one_of_known_realizer slots upper lowerLevel hbranch background q x hx d⟩ + +variable (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (useful : HierarchicalFrozenTables.QuotientMatrix slots upper lowerLevel background → Prop) + +def adviceLaw (r : Nat) (ρ : ℝ) (A : ManyGoodRows.RowMap (Block rows upper) r) + (U : Module.Dual F2 (NodeEmbedding.RowSpace slots upper ⧸ + HierarchicalFrozenTables.knownRows slots upper lowerLevel background) →ₗ[F2] + (Fin r → F2)) : FiniteDistribution (Module.Dual F2 (NodeEmbedding.RowSpace slots upper)) := + LeftDecoder.adviceLaw (TreeCanonical.numberedSlots slots) (NodeEmbedding.RowSpace slots upper) + (HierarchicalMatrixTable.other slots upper background) σ + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + (HierarchicalFrozenTables.sectionMap slots upper lowerLevel background) + (HierarchicalFrozenTables.sectionMap_spec slots upper lowerLevel background) useful r ρ A U + +theorem adviceLaw_valid (r : Nat) (ρ : ℝ) (hρ : 0 < ρ) + (A : ManyGoodRows.RowMap (Block rows upper) r) + (U : Module.Dual F2 (NodeEmbedding.RowSpace slots upper ⧸ + HierarchicalFrozenTables.knownRows slots upper lowerLevel background) →ₗ[F2] + (Fin r → F2)) : + (adviceLaw slots upper lowerLevel background σ useful r ρ A U).probability + (fun q => decide (Valid slots upper lowerLevel hbranch background q)) = 1 := by + unfold adviceLaw + apply LeftDecoderKnownRows.adviceLaw_probability_eq_one_of_known_realizer + (TreeCanonical.numberedSlots slots) (NodeEmbedding.RowSpace slots upper) + (HierarchicalMatrixTable.other slots upper background) σ + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + (HierarchicalFrozenTables.sectionMap slots upper lowerLevel background) + (HierarchicalFrozenTables.sectionMap_spec slots upper lowerLevel background) useful + (HierarchicalFrozenTables.determined slots upper lowerLevel background) r ρ hρ A U + intro q hq + exact decide_eq_true (valid_of_known_realizer slots upper lowerLevel hbranch background q hq) + +variable {r : Nat} {ρ : ℝ} {A : ManyGoodRows.RowMap (Block rows upper) r} + {U : Module.Dual F2 (NodeEmbedding.RowSpace slots upper ⧸ + HierarchicalFrozenTables.knownRows slots upper lowerLevel background) →ₗ[F2] + (Fin r → F2)} + +theorem candidate_valid + (w : DenseWitnessRealization.RepresentativeWitness + (TreeCanonical.numberedSlots slots) (NodeEmbedding.RowSpace slots upper) + (HierarchicalMatrixTable.other slots upper background) σ + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + (HierarchicalFrozenTables.sectionMap slots upper lowerLevel background) useful + (r := r) (ρ := ρ) (A := A) (U := U)) + (hρ : 0 < ρ) + (q : PulledColumnSpace.Candidates + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) w.columnSpace + (LeftDecoder.center (TreeCanonical.numberedSlots slots) (NodeEmbedding.RowSpace slots upper) + (HierarchicalMatrixTable.other slots upper background) σ + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + (HierarchicalFrozenTables.sectionMap slots upper lowerLevel background) + (HierarchicalFrozenTables.sectionMap_spec slots upper lowerLevel background) useful w)) : + Valid slots upper lowerLevel hbranch background q.val := by + obtain ⟨x, _, hx⟩ := LeftDecoder.exists_candidate_realizer + (TreeCanonical.numberedSlots slots) (NodeEmbedding.RowSpace slots upper) + (HierarchicalMatrixTable.other slots upper background) σ + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + (HierarchicalFrozenTables.sectionMap slots upper lowerLevel background) + (HierarchicalFrozenTables.sectionMap_spec slots upper lowerLevel background) useful + (HierarchicalFrozenTables.determined slots upper lowerLevel background) w hρ + exact valid_of_known_realizer slots upper lowerLevel hbranch background q.val ⟨x, hx q⟩ + +end +end PerfectCompleteness.HierarchicalLeftDecoder + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/HierarchicalLowerInverseLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/HierarchicalLowerInverseLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..11fea5ac207e174449a1e0d24a89559044377925 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/HierarchicalLowerInverseLemmas.lean @@ -0,0 +1,291 @@ +import OAI.Computability.PerfectCompleteness.Machines.HierarchicalLowerMatrixInput +import OAI.Computability.PerfectCompleteness.Reduction.FixedRows + +namespace OAI + +section + +namespace PerfectCompleteness.HierarchicalLowerInverse + +noncomputable section + +open scoped Classical +open TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Fourier.MatrixLevelBridge +open UniqueGamesTheorem.Appendix.RankLevelFilter + +attribute [local instance] linearMapFintype + +variable {branch rows : Nat → Nat} {n t : Nat} + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (upper : Nodes branch n) (lowerLevel : Nat) + (background : HierarchicalMatrixTable.Background (rows := rows) slots upper) + +local instance lowerHFintype (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) : + Fintype (HierarchicalDecoderTables.LowerH slots upper lowerLevel d) := Fintype.ofFinite _ + +abbrev Answer (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) := + HierarchicalDecoderTables.Answer slots upper lowerLevel d + +local instance answerFintype (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) : + Fintype (Answer slots upper lowerLevel d) := + HierarchicalAllDecoderTables.answerFintype slots upper lowerLevel d + +local instance upperDualFintype : Fintype (HierarchicalAllDecoderTables.UpperAnswer slots upper) := + HierarchicalAllDecoderTables.upperDualFintype slots upper + +def matrixTable {r : Nat} + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) + (upperMatrix : HierarchicalMatrixTable.Matrix (rows := rows) slots upper) + (A : ManyGoodRows.RowMap (Block rows upper) r) + (table : HierarchicalAllDecoderTables.Input (rows := rows) slots upper lowerLevel r → + Option (Answer slots upper lowerLevel d)) : + HierarchicalLowerMatrixInput.Matrix (rows := rows) slots upper lowerLevel d → + Option (Answer slots upper lowerLevel d) := + fun X => table (HierarchicalLowerMatrixInput.input slots upper lowerLevel + background d upperMatrix A X) + +variable (hbranch : ∀ k < n, 0 < branch k) + +theorem matrixTable_tested {r s : Nat} + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) + (upperMatrix : HierarchicalMatrixTable.Matrix (rows := rows) slots upper) + (A : ManyGoodRows.RowMap (Block rows upper) r) + (table : HierarchicalAllDecoderTables.Input (rows := rows) slots upper lowerLevel r → + Option (Answer slots upper lowerLevel d)) + (hvalid : DecoderTableAdmissibility.Admissible + (HierarchicalAllDecoderTables.RowValid slots upper lowerLevel hbranch r d s) table) + (X : HierarchicalLowerMatrixInput.Matrix (rows := rows) slots upper lowerLevel d) + (z : Answer slots upper lowerLevel d) + (hz : matrixTable slots upper lowerLevel background d upperMatrix A table X = some z) : + (LowerAffineSliceRank.testedGram + (FunctionSpaceLowerRank.matrixForm + (HierarchicalDecoderTables.LowerH slots upper lowerLevel d) + (OddListExtraction.multiplicationForm + (HierarchicalDecoderTables.LowerH slots upper lowerLevel d) z)) X).rank ≤ 1 := by + have h := hvalid + (HierarchicalLowerMatrixInput.input slots upper lowerLevel background d upperMatrix A X) + z hz + have ht := h.2.1 + simpa only [HierarchicalLowerMatrixInput.input_testedMatrix] using ht + +theorem matrixTable_high_rank {r s : Nat} + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) + (upperMatrix : HierarchicalMatrixTable.Matrix (rows := rows) slots upper) + (A : ManyGoodRows.RowMap (Block rows upper) r) + (table : HierarchicalAllDecoderTables.Input (rows := rows) slots upper lowerLevel r → + Option (Answer slots upper lowerLevel d)) + (hvalid : DecoderTableAdmissibility.Admissible + (HierarchicalAllDecoderTables.RowValid slots upper lowerLevel hbranch r d s) table) + (X : HierarchicalLowerMatrixInput.Matrix (rows := rows) slots upper lowerLevel d) + (z : Answer slots upper lowerLevel d) + (hz : matrixTable slots upper lowerLevel background d upperMatrix A table X = some z) : + s < Module.finrank F2 (LinearMap.range + (FunctionSpaceLowerRank.matrixForm + (HierarchicalDecoderTables.LowerH slots upper lowerLevel d) + (OddListExtraction.multiplicationForm + (HierarchicalDecoderTables.LowerH slots upper lowerLevel d) z))) := by + rw [FunctionSpaceLowerRank.matrixForm_rank] + exact (hvalid + (HierarchicalLowerMatrixInput.input slots upper lowerLevel background d upperMatrix A X) + z hz).2.2 + +theorem matrixTable_agreement_lt {r s m adviceRows : Nat} + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) + (upperMatrix : HierarchicalMatrixTable.Matrix (rows := rows) slots upper) + (A : ManyGoodRows.RowMap (Block rows upper) adviceRows) + (table : HierarchicalAllDecoderTables.Input (rows := rows) slots upper lowerLevel adviceRows → + Option (Answer slots upper lowerLevel d)) + (hvalid : DecoderTableAdmissibility.Admissible + (HierarchicalAllDecoderTables.RowValid slots upper lowerLevel hbranch adviceRows d s) table) + (ρ η : ℝ) (hm : 0 < m) (hρ : 0 < ρ) (hρ1 : ρ < 1) + (hconstants : levelCutoffConstant r ρ + node (r + 1) < η) + (hrows : 2 * m + r ≤ rows (Nodes.height (HierarchicalLeftDecoder.LowerNode upper lowerLevel d))) + (herror : (2 : ℝ) ^ m / (2 : ℝ) ^ (s - 2 * r) + + (2 : ℝ) ^ (2 * m) / (2 : ℝ) ^ (m * m) ≤ ρ) : + PartialTableInverse.nonzeroAgreement + (matrixTable slots upper lowerLevel background d upperMatrix A table) < η := by + let f := matrixTable slots upper lowerLevel background d upperMatrix A table + let form := fun z : Answer slots upper lowerLevel d => + FunctionSpaceLowerRank.matrixForm + (HierarchicalDecoderTables.LowerH slots upper lowerLevel d) + (OddListExtraction.multiplicationForm + (HierarchicalDecoderTables.LowerH slots upper lowerLevel d) z) + have tested : ∀ X z, f X = some z → (LowerAffineSliceRank.testedGram (form z) X).rank ≤ 1 := + fun X z hz => matrixTable_tested slots upper lowerLevel background hbranch + d upperMatrix A table hvalid X z hz + have high : ∀ X z, f X = some z → s < Module.finrank F2 (LinearMap.range (form z)) := + fun X z hz => matrixTable_high_rank slots upper lowerLevel background hbranch + d upperMatrix A table hvalid X z hz + have h := LowerAffineSliceRank.high_rank_agreement_lt f form tested r s ρ η + hm hρ hρ1 hconstants hrows herror + have herase : MatrixErasure.erase f (fun X => ∃ z, f X = some z ∧ + Module.finrank F2 (LinearMap.range (form z)) ≤ s) = f := by + funext X + apply MatrixErasure.erase_eq_of_not + rintro ⟨z, hz, hrank⟩ + exact (not_le_of_gt (high X z hz)) hrank + rw [herase] at h + exact h + +variable (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (useful : (bg : HierarchicalMatrixTable.Background (rows := rows) slots upper) → + HierarchicalFrozenTables.QuotientMatrix slots upper lowerLevel bg → Prop) + +include hbranch σ useful + +theorem supported_matrixTable_agreement_lt {r s m adviceRows : Nat} + (decoderDensity : ℝ) (hdecoderDensity : 0 < decoderDensity) + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) + (upperMatrix : HierarchicalMatrixTable.Matrix (rows := rows) slots upper) + (A : ManyGoodRows.RowMap (Block rows upper) adviceRows) + (table : HierarchicalAllDecoderTables.Input (rows := rows) slots upper lowerLevel adviceRows → + Option (Answer slots upper lowerLevel d)) + (hsupport : (HierarchicalAllDecoderTables.tableLaw slots upper lowerLevel hbranch σ useful + adviceRows decoderDensity d s).weight table ≠ 0) + (ρ η : ℝ) (hm : 0 < m) (hρ : 0 < ρ) (hρ1 : ρ < 1) + (hconstants : levelCutoffConstant r ρ + node (r + 1) < η) + (hrows : 2 * m + r ≤ rows (Nodes.height (HierarchicalLeftDecoder.LowerNode upper lowerLevel d))) + (herror : (2 : ℝ) ^ m / (2 : ℝ) ^ (s - 2 * r) + + (2 : ℝ) ^ (2 * m) / (2 : ℝ) ^ (m * m) ≤ ρ) : + PartialTableInverse.nonzeroAgreement + (matrixTable slots upper lowerLevel background d upperMatrix A table) < η := by + exact matrixTable_agreement_lt slots upper lowerLevel background hbranch + d upperMatrix A table + (HierarchicalAllDecoderTables.supported_table_valid slots upper lowerLevel hbranch σ useful + adviceRows decoderDensity hdecoderDensity d s table hsupport) + ρ η hm hρ hρ1 hconstants hrows herror + +theorem mean_matrixTable_agreement_le {r s m adviceRows : Nat} + (decoderDensity : ℝ) (hdecoderDensity : 0 < decoderDensity) + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) + (upperMatrix : HierarchicalMatrixTable.Matrix (rows := rows) slots upper) + (A : ManyGoodRows.RowMap (Block rows upper) adviceRows) + (ρ η : ℝ) (hm : 0 < m) (hρ : 0 < ρ) (hρ1 : ρ < 1) + (hconstants : levelCutoffConstant r ρ + node (r + 1) < η) + (hrows : 2 * m + r ≤ rows (Nodes.height (HierarchicalLeftDecoder.LowerNode upper lowerLevel d))) + (herror : (2 : ℝ) ^ m / (2 : ℝ) ^ (s - 2 * r) + + (2 : ℝ) ^ (2 * m) / (2 : ℝ) ^ (m * m) ≤ ρ) : + (HierarchicalAllDecoderTables.tableLaw slots upper lowerLevel hbranch σ useful + adviceRows decoderDensity d s).expectation + (fun table => PartialTableInverse.nonzeroAgreement + (matrixTable slots upper lowerLevel background d upperMatrix A table)) ≤ η := by + apply DecoderTableAdmissibility.expectation_le_of_support + intro table hsupport + exact (supported_matrixTable_agreement_lt slots upper lowerLevel background hbranch + σ useful decoderDensity hdecoderDensity d upperMatrix A table hsupport + ρ η hm hρ hρ1 hconstants hrows herror).le + +theorem supported_upper_matrixTable_agreement_lt {r s m adviceRows : Nat} + (decoderDensity : ℝ) (hdecoderDensity : 0 < decoderDensity) + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) + (upperMatrix : HierarchicalMatrixTable.Matrix (rows := rows) slots upper) + (A : ManyGoodRows.RowMap (Block rows upper) adviceRows) + (table : HierarchicalAllDecoderTables.Input (rows := rows) slots upper lowerLevel adviceRows → + HierarchicalAllDecoderTables.UpperAnswer slots upper) + (hsupport : (HierarchicalAllDecoderTables.upperTableLaw slots upper lowerLevel σ useful + adviceRows decoderDensity).weight table ≠ 0) + (ρ η : ℝ) (hm : 0 < m) (hρ : 0 < ρ) (hρ1 : ρ < 1) + (hconstants : levelCutoffConstant r ρ + node (r + 1) < η) + (hrows : 2 * m + r ≤ rows (Nodes.height (HierarchicalLeftDecoder.LowerNode upper lowerLevel d))) + (herror : (2 : ℝ) ^ m / (2 : ℝ) ^ (s - 2 * r) + + (2 : ℝ) ^ (2 * m) / (2 : ℝ) ^ (m * m) ≤ ρ) : + PartialTableInverse.nonzeroAgreement + (matrixTable slots upper lowerLevel background d upperMatrix A + (HierarchicalAllDecoderTables.decodeTable slots upper lowerLevel hbranch adviceRows d s table)) < η := by + exact matrixTable_agreement_lt slots upper lowerLevel background hbranch + d upperMatrix A + (HierarchicalAllDecoderTables.decodeTable slots upper lowerLevel hbranch adviceRows d s table) + (HierarchicalAllDecoderTables.decoded_supported_table_valid slots upper lowerLevel hbranch + σ useful adviceRows decoderDensity hdecoderDensity table hsupport d s) + ρ η hm hρ hρ1 hconstants hrows herror + +end +end PerfectCompleteness.HierarchicalLowerInverse + +end + +section + +namespace PerfectCompleteness.HierarchicalFixedLowerInverse + +noncomputable section + +open scoped Classical +open TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +attribute [local instance] UniqueGamesTheorem.Appendix.RankLevelFilter.linearMapFintype + +variable {δ : ℚ} (plan : FixedRows.Plan δ) (hδ : 0 < δ) + {branch : Nat → Nat} {t : Nat} + (slots : RecursiveSpaces.Slots branch plan.depth → Fin t → MixedSupport.Slot) + (upper : Nodes branch plan.depth) (lowerLevel : Nat) + (background : HierarchicalMatrixTable.Background + (rows := FixedRows.rows plan) slots upper) + +local instance lowerHFintype (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) : + Fintype (HierarchicalDecoderTables.LowerH slots upper lowerLevel d) := Fintype.ofFinite _ + +local instance upperDualFintype : Fintype (HierarchicalAllDecoderTables.UpperAnswer slots upper) := + HierarchicalAllDecoderTables.upperDualFintype slots upper + +variable (hbranch : ∀ k < plan.depth, 0 < branch k) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch plan.depth t)) + (useful : (bg : HierarchicalMatrixTable.Background + (rows := FixedRows.rows plan) slots upper) → + HierarchicalFrozenTables.QuotientMatrix slots upper lowerLevel bg → Prop) + +include hbranch σ useful + +theorem supported_upper_matrixTable_agreement_lt {adviceRows : Nat} + (decoderDensity : ℝ) (hdecoderDensity : 0 < decoderDensity) + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) + (upperMatrix : HierarchicalMatrixTable.Matrix + (rows := FixedRows.rows plan) slots upper) + (A : ManyGoodRows.RowMap (Block (FixedRows.rows plan) upper) adviceRows) + (table : HierarchicalAllDecoderTables.Input + (rows := FixedRows.rows plan) slots upper lowerLevel adviceRows → + HierarchicalAllDecoderTables.UpperAnswer slots upper) + (hsupport : (HierarchicalAllDecoderTables.upperTableLaw slots upper lowerLevel σ useful + adviceRows decoderDensity).weight table ≠ 0) : + PartialTableInverse.nonzeroAgreement + (HierarchicalLowerInverse.matrixTable slots upper lowerLevel background d upperMatrix A + (HierarchicalAllDecoderTables.decodeTable slots upper lowerLevel hbranch adviceRows d + (FixedRows.cutoff plan hδ) table)) < + UpperParameterScalars.gamma (InitialParameters.useful δ) plan.density + (InitialParameters.inverse δ) plan.order + (FixedRows.rows plan (Nodes.height upper)) ^ 2 / 8 := by + let lower := DescendingRows.lowerChoice (InitialParameters.useful_pos hδ) + plan.density_pos (InitialParameters.inverse_pos hδ) plan.order + (FixedRows.rows plan (Nodes.height upper)) + have hheight : Nodes.height (HierarchicalLeftDecoder.LowerNode upper lowerLevel d) = + lowerLevel := + (RelativeDescendantProducts.relativeNode_height upper d.val.val).trans d.property + have hproper : lowerLevel < Nodes.height upper := by + rw [← hheight] + exact (RelativeDescendantProducts.descendantIndex_below upper d.val).height_lt + have hminimum : lower.minimumRows ≤ FixedRows.rows plan lowerLevel := + FixedRows.lower_row_requirement plan hδ hproper (Nodes.height_le upper) + have hrows : 2 * lower.crossSize + lower.order ≤ + FixedRows.rows plan (Nodes.height (HierarchicalLeftDecoder.LowerNode upper lowerLevel d)) := by + rw [hheight] + exact lower.row_bound _ hminimum + have hcutoff : lower.cutoff ≤ FixedRows.cutoff plan hδ := by + simpa only [lower, FixedRows.rows, FixedRows.cutoff] using + DescendingRows.tree_cutoff_le_common (InitialParameters.useful_pos hδ) + plan.density_pos (InitialParameters.inverse_pos hδ) plan.order plan.depth + plan.rootFirstRows (Nat.zero_lt_of_lt hproper) (Nodes.height_le upper) + exact HierarchicalLowerInverse.supported_upper_matrixTable_agreement_lt + (r := lower.order) (s := FixedRows.cutoff plan hδ) (m := lower.crossSize) + slots upper lowerLevel background hbranch σ useful decoderDensity hdecoderDensity + d upperMatrix A table hsupport lower.density _ lower.cross_pos lower.density_pos + lower.density_lt_one lower.spectral hrows (lower.error_bound _ hcutoff).le + +end +end PerfectCompleteness.HierarchicalFixedLowerInverse + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/HierarchicalUsefulCollision.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/HierarchicalUsefulCollision.lean new file mode 100644 index 0000000000000000000000000000000000000000..af0edb3b0cd48bf8be38344f2ded08a99fadf3f1 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/HierarchicalUsefulCollision.lean @@ -0,0 +1,215 @@ +import OAI.Computability.PerfectCompleteness.Decoding.BucketUsefulCollision +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalAgreementMean +import OAI.Computability.PerfectCompleteness.Reduction.CompletionSoundness + +namespace OAI + +section + +namespace PerfectCompleteness.HierarchicalUsefulCollision + +noncomputable section + +open scoped BigOperators Classical +open TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype + +private theorem probability_product {A B : Type*} [Fintype A] [Fintype B] + (μ : FiniteDistribution A) (ν : FiniteDistribution B) (event : A × B → Bool) : + (μ.product ν).probability event = + μ.expectation (fun a => ν.probability (fun b => event (a, b))) := by + simp only [FiniteDistribution.probability, FiniteDistribution.expectation, + FiniteDistribution.product, Fintype.sum_prod_type, Finset.mul_sum, mul_ite, mul_zero] + +private theorem probability_product_first {A B : Type*} [Fintype A] [Fintype B] + (μ : FiniteDistribution A) (ν : FiniteDistribution B) (event : A → Bool) : + (μ.product ν).probability (fun x => event x.1) = μ.probability event := by + unfold FiniteDistribution.probability + rw [Fintype.sum_prod_type] + apply Finset.sum_congr rfl + intro a _ + cases he : event a <;> + simp [FiniteDistribution.product, he, ← Finset.mul_sum, ν.normalized] + +variable {branch rows : Nat → Nat} {n t : Nat} + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (upper : Nodes branch n) + +abbrev Background := HierarchicalAgreementMean.Background (rows := rows) slots upper +abbrev Matrix := HierarchicalAgreementMean.Matrix (rows := rows) slots upper +abbrev Direction := BucketSampler.Direction (rows (Nodes.height upper)) +abbrev Tape := BucketSampler.Tape (rows (Nodes.height upper)) (NodeEmbedding.RowSpace slots upper) + +local instance backgroundFintype : Fintype (Background (rows := rows) slots upper) := + Fintype.ofFinite _ + +local instance rowSpaceFintype : Fintype (NodeEmbedding.RowSpace slots upper) := + Fintype.ofFinite _ + +local instance valueFintype : + Fintype (Block rows upper × HierarchicalMatrixTable.SideOutput (rows := rows) upper) := + Fintype.ofFinite _ + +def directionLaw (hrows : 0 < rows (Nodes.height upper)) : + FiniteDistribution (Direction (rows := rows) upper) := by + letI : Nonempty (Direction (rows := rows) upper) := + ⟨BucketUniform.coordinateDirection ⟨0, hrows⟩⟩ + exact FiniteDistribution.uniform _ + +def bucketLaw (ν : FiniteDistribution (NodeEmbedding.RowSpace slots upper)) + (hrows : 0 < rows (Nodes.height upper)) : + FiniteDistribution (HierarchicalAgreementMean.BucketSample (rows := rows) slots upper) := + (directionLaw upper hrows).product + ((BucketSampler.tapeLaw (rows (Nodes.height upper)) ν).product ν) + +variable {P : Type*} [Fintype P] + +abbrev Sample := (_ : P) × HierarchicalAgreementMean.BucketSample (rows := rows) slots upper + +def law (externalLaw : FiniteDistribution P) + (scalarLaw : P → FiniteDistribution (NodeEmbedding.RowSpace slots upper)) + (hrows : 0 < rows (Nodes.height upper)) : + FiniteDistribution (Sample (P := P) (rows := rows) slots upper) := + CompletionSoundness.sigmaLaw externalLaw (fun p => bucketLaw slots upper (scalarLaw p) hrows) + +def pairRecord (background : P → Background (rows := rows) slots upper) + (sample : Sample (P := P) (rows := rows) slots upper) : + HierarchicalAgreementMean.PairRecord (rows := rows) slots upper := + HierarchicalAgreementMean.pairRecord slots upper (background sample.1, sample.2) + +def pairLaw (externalLaw : FiniteDistribution P) + (background : P → Background (rows := rows) slots upper) + (scalarLaw : P → FiniteDistribution (NodeEmbedding.RowSpace slots upper)) + (hrows : 0 < rows (Nodes.height upper)) : + FiniteDistribution (HierarchicalAgreementMean.PairRecord (rows := rows) slots upper) := + (law slots upper externalLaw scalarLaw hrows).pushforward (pairRecord slots upper background) + +variable (lowerLevel : Nat) {Ω : Type*} [Fintype Ω] + (original : FiniteDistribution Ω) (arrays : Ω → Arrays slots rows) + (lower : Ω → Bool) (κ : ℝ) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + +def usefulAccepted (background : Background (rows := rows) slots upper) + (a : Direction (rows := rows) upper) (tape : Tape (rows := rows) slots upper) : Bool := + decide (CanonicalMatrixTable.Accepts (TreeCanonical.numberedSlots slots) + (NodeEmbedding.RowSpace slots upper) (HierarchicalMatrixTable.other slots upper background) + σ a.val (BucketMatrixResampling.assembledMatrix (NodeEmbedding.RowSpace slots upper) + (rows (Nodes.height upper)) tape)) && + (HierarchicalUsefulness.table slots upper lowerLevel original arrays lower κ σ background + (MatrixRowQuotient.projectMatrix + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + (BucketMatrixResampling.assembledMatrix (NodeEmbedding.RowSpace slots upper) + (rows (Nodes.height upper)) tape))).isSome + +def usefulEvent (background : P → Background (rows := rows) slots upper) + (sample : Sample (P := P) (rows := rows) slots upper) : Bool := + usefulAccepted slots upper lowerLevel original arrays lower κ σ + (background sample.1) sample.2.1 sample.2.2.1 + +theorem direction_collision_lower_bound + (background : Background (rows := rows) slots upper) + (ν : FiniteDistribution (NodeEmbedding.RowSpace slots upper)) + (a : Direction (rows := rows) upper) : + (BucketSampler.tapeLaw (rows (Nodes.height upper)) ν).probability + (usefulAccepted slots upper lowerLevel original arrays lower κ σ background a) ^ 2 / 2 ≤ + ((BucketSampler.tapeLaw (rows (Nodes.height upper)) ν).product ν).probability + (fun z => HierarchicalAgreementMean.collision slots upper lowerLevel + original arrays lower κ σ + (HierarchicalAgreementMean.pairRecord slots upper (background, (a, z)))) := by + exact BucketUsefulCollision.collision_probability_lower_bound + (TreeCanonical.numberedSlots slots) (NodeEmbedding.RowSpace slots upper) + (HierarchicalMatrixTable.other slots upper background) σ + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + (HierarchicalFrozenTables.sectionMap slots upper lowerLevel background) + (HierarchicalFrozenTables.sectionMap_spec slots upper lowerLevel background) + (HierarchicalFrozenTables.determined slots upper lowerLevel background) ν + (fun X => HierarchicalUsefulness.mark slots upper lowerLevel original arrays lower κ + ⟨background, X⟩ = true) a + +theorem useful_probability_eq + (externalLaw : FiniteDistribution P) + (background : P → Background (rows := rows) slots upper) + (scalarLaw : P → FiniteDistribution (NodeEmbedding.RowSpace slots upper)) + (hrows : 0 < rows (Nodes.height upper)) : + (law slots upper externalLaw scalarLaw hrows).probability + (usefulEvent slots upper lowerLevel original arrays lower κ σ background) = + externalLaw.expectation (fun p => (directionLaw upper hrows).expectation (fun a => + (BucketSampler.tapeLaw (rows (Nodes.height upper)) (scalarLaw p)).probability + (usefulAccepted slots upper lowerLevel original arrays lower κ σ (background p) a))) := by + rw [law, CompletionSoundness.sigmaLaw_probability] + apply FiniteDistribution.expectation_congr + intro p + rw [bucketLaw, probability_product] + apply FiniteDistribution.expectation_congr + intro a + exact probability_product_first + (BucketSampler.tapeLaw (rows (Nodes.height upper)) (scalarLaw p)) (scalarLaw p) + (usefulAccepted slots upper lowerLevel original arrays lower κ σ (background p) a) + +theorem collision_probability_eq + (externalLaw : FiniteDistribution P) + (background : P → Background (rows := rows) slots upper) + (scalarLaw : P → FiniteDistribution (NodeEmbedding.RowSpace slots upper)) + (hrows : 0 < rows (Nodes.height upper)) : + (pairLaw slots upper externalLaw background scalarLaw hrows).probability + (HierarchicalAgreementMean.collision slots upper lowerLevel original arrays lower κ σ) = + externalLaw.expectation (fun p => (directionLaw upper hrows).expectation (fun a => + ((BucketSampler.tapeLaw (rows (Nodes.height upper)) (scalarLaw p)).product + (scalarLaw p)).probability (fun z => + HierarchicalAgreementMean.collision slots upper lowerLevel original arrays lower κ σ + (HierarchicalAgreementMean.pairRecord slots upper (background p, (a, z)))))) := by + rw [pairLaw, FiniteDistribution.probability_pushforward, law, + CompletionSoundness.sigmaLaw_probability] + apply FiniteDistribution.expectation_congr + intro p + exact probability_product (directionLaw upper hrows) + ((BucketSampler.tapeLaw (rows (Nodes.height upper)) (scalarLaw p)).product (scalarLaw p)) + (fun z => HierarchicalAgreementMean.collision slots upper lowerLevel original arrays lower κ σ + (HierarchicalAgreementMean.pairRecord slots upper (background p, z))) + +theorem collision_probability_lower_bound + (externalLaw : FiniteDistribution P) + (background : P → Background (rows := rows) slots upper) + (scalarLaw : P → FiniteDistribution (NodeEmbedding.RowSpace slots upper)) + (hrows : 0 < rows (Nodes.height upper)) : + (law slots upper externalLaw scalarLaw hrows).probability + (usefulEvent slots upper lowerLevel original arrays lower κ σ background) ^ 2 / 2 ≤ + (pairLaw slots upper externalLaw background scalarLaw hrows).probability + (HierarchicalAgreementMean.collision slots upper lowerLevel original arrays lower κ σ) := by + rw [useful_probability_eq, collision_probability_eq] + apply CollisionAveraging.average_square_bound + intro p + apply CollisionAveraging.average_square_bound + intro a + exact direction_collision_lower_bound slots upper lowerLevel original arrays lower κ σ + (background p) (scalarLaw p) a + +theorem collision_probability_ge_eighth + (externalLaw : FiniteDistribution P) + (background : P → Background (rows := rows) slots upper) + (scalarLaw : P → FiniteDistribution (NodeEmbedding.RowSpace slots upper)) + (hrows : 0 < rows (Nodes.height upper)) (c : ℝ) (hc : 0 ≤ c) + (hmass : c / 2 ≤ (law slots upper externalLaw scalarLaw hrows).probability + (usefulEvent slots upper lowerLevel original arrays lower κ σ background)) : + c ^ 2 / 8 ≤ + (pairLaw slots upper externalLaw background scalarLaw hrows).probability + (HierarchicalAgreementMean.collision slots upper lowerLevel original arrays lower κ σ) := by + have h := collision_probability_lower_bound slots upper lowerLevel original arrays lower κ σ + externalLaw background scalarLaw hrows + have hprod : 0 ≤ + ((law slots upper externalLaw scalarLaw hrows).probability + (usefulEvent slots upper lowerLevel original arrays lower κ σ background) - c / 2) * + ((law slots upper externalLaw scalarLaw hrows).probability + (usefulEvent slots upper lowerLevel original arrays lower κ σ background) + c / 2) := + mul_nonneg (sub_nonneg.mpr hmass) (by linarith) + nlinarith + +end +end PerfectCompleteness.HierarchicalUsefulCollision + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/LeftDecoder.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/LeftDecoder.lean new file mode 100644 index 0000000000000000000000000000000000000000..cc3ec29340ad515bfa324935103f9f922a12af43 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/LeftDecoder.lean @@ -0,0 +1,255 @@ +import OAI.Computability.PerfectCompleteness.Decoding.RepresentativeBucketCollisionLemmas +import OAI.Computability.PerfectCompleteness.Foundations.PartitionsLemmas +import OAI.Computability.PerfectCompleteness.Sampling.FiniteListSampling +import OAI.Computability.UniqueGames.Foundations.SamplingLemmas + +namespace OAI + + +namespace PerfectCompleteness.LeftDecoder + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games +open ClauseSupport MixedSupport + +abbrev F2 := ZMod 2 + +noncomputable section + +section Affine + +variable {V : Type*} [AddCommGroup V] [Module F2 V] [FiniteDimensional F2 V] + +local instance dualFintype : Fintype (Module.Dual F2 V) := + Fintype.ofEquiv (Fin (Module.finrank F2 (Module.Dual F2 V)) → F2) + (Module.finBasis F2 (Module.Dual F2 V)).equivFun.toEquiv.symm + +def affineLaw (W : Submodule F2 V) + (C : Submodule F2 (Module.Dual F2 (V ⧸ W))) (center : Module.Dual F2 V) : + FiniteDistribution (Module.Dual F2 V) := + (FiniteDistribution.uniform (PulledColumnSpace.Candidates W C center)).pushforward Subtype.val + +theorem affineLaw_probability (W : Submodule F2 V) + (C : Submodule F2 (Module.Dual F2 (V ⧸ W))) (center : Module.Dual F2 V) + (event : Module.Dual F2 V → Bool) : + (affineLaw W C center).probability event = + (FiniteDistribution.uniform (PulledColumnSpace.Candidates W C center)).probability + (fun q => event q.val) := + FiniteDistribution.probability_pushforward _ _ _ + +theorem affineLaw_probability_eq_one (W : Submodule F2 V) + (C : Submodule F2 (Module.Dual F2 (V ⧸ W))) (center : Module.Dual F2 V) + (event : Module.Dual F2 V → Bool) + (hevent : ∀ q : PulledColumnSpace.Candidates W C center, event q.val = true) : + (affineLaw W C center).probability event = 1 := by + rw [affineLaw_probability] + have heq : (fun q : PulledColumnSpace.Candidates W C center => event q.val) = + fun _ => true := funext hevent + rw [heq, FiniteDistribution.probability_true] + +theorem affineLaw_weight (W : Submodule F2 V) + (C : Submodule F2 (Module.Dual F2 (V ⧸ W))) (center q : Module.Dual F2 V) : + (affineLaw W C center).weight q = + if q - center ∈ PulledColumnSpace.pulled W C then + 1 / (2 : ℝ) ^ Module.finrank F2 C else 0 := by + have hweight : (affineLaw W C center).weight q = + if q - center ∈ PulledColumnSpace.pulled W C then + 1 / (Fintype.card (PulledColumnSpace.Candidates W C center) : ℝ) else 0 := by + let : Fintype {p : Module.Dual F2 V // p - center ∈ PulledColumnSpace.pulled W C} := + PulledColumnSpace.candidatesFintype W C center + change (∑ p : {p : Module.Dual F2 V // p - center ∈ PulledColumnSpace.pulled W C}, + if p.val = q then + 1 / (Fintype.card (PulledColumnSpace.Candidates W C center) : ℝ) else 0) = _ + by_cases hq : q - center ∈ PulledColumnSpace.pulled W C + · rw [ite_eq_left hq, Finset.sum_eq_single + (⟨q, hq⟩ : {p : Module.Dual F2 V // p - center ∈ PulledColumnSpace.pulled W C})] + · simp + · intro p _ hp + have hne : p.val ≠ q := fun heq => hp (Subtype.ext heq) + simp [hne] + · simp + · rw [ite_eq_right hq] + apply Finset.sum_eq_zero + intro p _ + have hne : p.val ≠ q := fun heq => hq (heq ▸ p.property) + simp [hne] + simpa only [PulledColumnSpace.fintype_card_candidates, Nat.cast_pow, Nat.cast_ofNat] + using hweight + +theorem affineLaw_support (W : Submodule F2 V) + (C : Submodule F2 (Module.Dual F2 (V ⧸ W))) (center : Module.Dual F2 V) : + (affineLaw W C center).probability + (fun q => decide (q - center ∈ PulledColumnSpace.pulled W C)) = 1 := by + rw [affineLaw_probability] + have hevent : (fun q : PulledColumnSpace.Candidates W C center => + decide (q.val - center ∈ PulledColumnSpace.pulled W C)) = fun _ => true := by + funext q + exact decide_eq_true q.property + rw [hevent, FiniteDistribution.probability_true] + +theorem affineLaw_success_lower (W : Submodule F2 V) + (C : Submodule F2 (Module.Dual F2 (V ⧸ W))) (center : Module.Dual F2 V) + {r : Nat} (hC : Module.finrank F2 C ≤ r) (event : Module.Dual F2 V → Bool) + (witness : ∃ q : PulledColumnSpace.Candidates W C center, event q.val = true) : + 1 / (2 : ℝ) ^ r ≤ (affineLaw W C center).probability event := by + obtain ⟨q, hq⟩ := witness + have hweight := FiniteListSampling.probability_ge_weight + (affineLaw W C center) event q.val hq + rw [affineLaw_weight, ite_eq_left q.property] at hweight + exact (one_div_le_one_div_of_le (pow_pos (by norm_num : (0 : ℝ) < 2) _) + (pow_le_pow_right₀ (by norm_num : (1 : ℝ) ≤ 2) hC)).trans hweight + +end Affine + + +attribute [local instance] UniqueGamesTheorem.Appendix.RankLevelFilter.linearMapFintype + +variable {n : Nat} {K Z : Type*} [AddCommGroup K] [Module F2 K] + (slots : Fin n → Slot) (H : Submodule F2 (Assignment slots → F2)) + (other : Assignment slots → Z) (labeling : KeyStrategy.Strategy n) + (W : Submodule F2 H) (s : (H ⧸ W) →ₗ[F2] H) + (hs : W.mkQ.comp s = LinearMap.id) + [FiniteDimensional F2 H] [FiniteDimensional F2 K] + [Fintype H] [Fintype K] [Fintype Z] + (useful : (Module.Dual F2 (H ⧸ W) →ₗ[F2] K) → Prop) + {r : Nat} {ρ : ℝ} {A : ManyGoodRows.RowMap K r} + {U : Module.Dual F2 (H ⧸ W) →ₗ[F2] (Fin r → F2)} + +local instance representativeDualFintype : Fintype (Module.Dual F2 H) := + dualFintype (V := H) + +def center (w : DenseWitnessRealization.RepresentativeWitness + slots H other labeling W s useful (r := r) (ρ := ρ) (A := A) (U := U)) : + Module.Dual F2 H := + RepresentativeMatrixTable.correctionFunctional slots H other W s hs w.value.2 + +def law (w : DenseWitnessRealization.RepresentativeWitness + slots H other labeling W s useful (r := r) (ρ := ρ) (A := A) (U := U)) : + FiniteDistribution (Module.Dual F2 H) := + affineLaw W w.columnSpace (center slots H other labeling W s hs useful w) + +omit [FiniteDimensional F2 K] [Fintype Z] + +theorem law_weight (w : DenseWitnessRealization.RepresentativeWitness + slots H other labeling W s useful (r := r) (ρ := ρ) (A := A) (U := U)) + (q : Module.Dual F2 H) : + (law slots H other labeling W s hs useful w).weight q = + if q - center slots H other labeling W s hs useful w ∈ + PulledColumnSpace.pulled W w.columnSpace then + 1 / (2 : ℝ) ^ Module.finrank F2 w.columnSpace else 0 := + affineLaw_weight W w.columnSpace _ q + +theorem law_support (w : DenseWitnessRealization.RepresentativeWitness + slots H other labeling W s useful (r := r) (ρ := ρ) (A := A) (U := U)) : + (law slots H other labeling W s hs useful w).probability + (fun q => decide (q - center slots H other labeling W s hs useful w ∈ + PulledColumnSpace.pulled W w.columnSpace)) = 1 := + affineLaw_support W w.columnSpace _ + +omit [FiniteDimensional F2 H] in +theorem exists_candidate_realizer + (hW : RepresentativeMatrixTable.Determined slots H other W) + (w : DenseWitnessRealization.RepresentativeWitness + slots H other labeling W s useful (r := r) (ρ := ρ) (A := A) (U := U)) + (hρ : 0 < ρ) : + ∃ x : Assignment slots, other x = w.value.2 ∧ + ∀ q : PulledColumnSpace.Candidates W w.columnSpace + (center slots H other labeling W s hs useful w), + ∀ b : W, q.val (b : H) = b.val.val x := by + obtain ⟨X, _, x, hx, hknown⟩ := DenseWitnessRealization.exists_coset_realizer + slots H other labeling W s useful hs hW w hρ + (PulledColumnSpace.pulled W w.columnSpace) + (PulledColumnSpace.pulled_le_annihilator W w.columnSpace) + refine ⟨x, congrArg Prod.snd hx, ?_⟩ + intro q b + rw [PulledColumnSpace.candidate_apply_known] + simpa only [center, Submodule.coe_zero, add_zero] using hknown 0 b + +omit [FiniteDimensional F2 H] in +theorem candidate_one (hW : RepresentativeMatrixTable.Determined slots H other W) + (w : DenseWitnessRealization.RepresentativeWitness + slots H other labeling W s useful (r := r) (ρ := ρ) (A := A) (U := U)) + (hρ : 0 < ρ) (b : W) (hb : b.val.val = (1 : Assignment slots → F2)) + (q : PulledColumnSpace.Candidates W w.columnSpace + (center slots H other labeling W s hs useful w)) : q.val (b : H) = 1 := by + obtain ⟨x, _, hknown⟩ := + exists_candidate_realizer slots H other labeling W s hs useful hW w hρ + rw [hknown q b, hb] + rfl + +theorem law_normalized_on_one + (hW : RepresentativeMatrixTable.Determined slots H other W) + (w : DenseWitnessRealization.RepresentativeWitness + slots H other labeling W s useful (r := r) (ρ := ρ) (A := A) (U := U)) + (hρ : 0 < ρ) (b : W) (hb : b.val.val = (1 : Assignment slots → F2)) : + (law slots H other labeling W s hs useful w).probability + (fun q => decide (q (b : H) = 1)) = 1 := by + rw [law, affineLaw_probability] + have hevent : (fun q : PulledColumnSpace.Candidates W w.columnSpace + (center slots H other labeling W s hs useful w) => decide (q.val (b : H) = 1)) = + fun _ => true := by + funext q + exact decide_eq_true (candidate_one slots H other labeling W s hs useful hW w hρ b hb q) + rw [hevent, FiniteDistribution.probability_true] + +theorem success_lower (w : DenseWitnessRealization.RepresentativeWitness + slots H other labeling W s useful (r := r) (ρ := ρ) (A := A) (U := U)) + (event : Module.Dual F2 H → Bool) + (witness : ∃ q : PulledColumnSpace.Candidates W w.columnSpace + (center slots H other labeling W s hs useful w), event q.val = true) : + 1 / (2 : ℝ) ^ r ≤ + (law slots H other labeling W s hs useful w).probability event := + affineLaw_success_lower W w.columnSpace _ w.column_count event witness + +def adviceLaw (r : Nat) (ρ : ℝ) (A : ManyGoodRows.RowMap K r) + (U : Module.Dual F2 (H ⧸ W) →ₗ[F2] (Fin r → F2)) : + FiniteDistribution (Module.Dual F2 H) := + if hgood : ManyGoodRows.GoodRow + (RepresentativeMatrixTable.partialTable slots H other labeling W s useful) r ρ A U then + law slots H other labeling W s hs useful + (ManyGoodRows.selectWitness + (RepresentativeMatrixTable.partialTable slots H other labeling W s useful) r ρ A U hgood) + else + affineLaw W ⊥ (RepresentativeMatrixTable.correctionFunctional slots H other W s hs + (CanonicalMatrixTable.response slots H other labeling (0 : CanonicalMatrixTable.Matrix + (K := K) slots H)).2) + +theorem adviceLaw_of_good (r : Nat) (ρ : ℝ) (A : ManyGoodRows.RowMap K r) + (U : Module.Dual F2 (H ⧸ W) →ₗ[F2] (Fin r → F2)) + (hgood : ManyGoodRows.GoodRow + (RepresentativeMatrixTable.partialTable slots H other labeling W s useful) r ρ A U) : + adviceLaw slots H other labeling W s hs useful r ρ A U = + law slots H other labeling W s hs useful + (ManyGoodRows.selectWitness + (RepresentativeMatrixTable.partialTable slots H other labeling W s useful) + r ρ A U hgood) := by + simp only [adviceLaw, dite_eq_left hgood] + +theorem adviceLaw_normalized_on_one + (hW : RepresentativeMatrixTable.Determined slots H other W) + (r : Nat) (ρ : ℝ) (hρ : 0 < ρ) (A : ManyGoodRows.RowMap K r) + (U : Module.Dual F2 (H ⧸ W) →ₗ[F2] (Fin r → F2)) + (b : W) (hb : b.val.val = (1 : Assignment slots → F2)) : + (adviceLaw slots H other labeling W s hs useful r ρ A U).probability + (fun q => decide (q (b : H) = 1)) = 1 := by + by_cases hgood : ManyGoodRows.GoodRow + (RepresentativeMatrixTable.partialTable slots H other labeling W s useful) r ρ A U + · rw [adviceLaw_of_good slots H other labeling W s hs useful r ρ A U hgood] + exact law_normalized_on_one slots H other labeling W s hs useful hW _ hρ b hb + · simp only [adviceLaw, dite_eq_right hgood] + apply affineLaw_probability_eq_one + intro q + apply decide_eq_true + rw [PulledColumnSpace.candidate_apply_known] + obtain ⟨x, _, hx⟩ := CanonicalMatrixTable.response_realized slots H other labeling + (0 : CanonicalMatrixTable.Matrix (K := K) slots H) + rw [← hx] + simpa only [add_zero] using RepresentativeDecoder.coset_one_at_image + slots H other W s hs hW x 0 W.dualAnnihilator.zero_mem b hb + + +end + +end PerfectCompleteness.LeftDecoder + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/LeftDecoderKnownRows.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/LeftDecoderKnownRows.lean new file mode 100644 index 0000000000000000000000000000000000000000..ecd215581a658d7e69a799a1c9903f76b93789a4 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/LeftDecoderKnownRows.lean @@ -0,0 +1,92 @@ +import OAI.Computability.PerfectCompleteness.Decoding.LeftDecoder + +namespace OAI + + +namespace PerfectCompleteness.LeftDecoderKnownRows + +open scoped Classical +open UniqueGamesTheorem.Foundations.Games +open ClauseSupport MixedSupport +open LeftDecoder (F2) + +noncomputable section + +variable {n : Nat} {K Z : Type*} [AddCommGroup K] [Module F2 K] + (slots : Fin n → Slot) (H : Submodule F2 (Assignment slots → F2)) + (other : Assignment slots → Z) (labeling : KeyStrategy.Strategy n) + (W : Submodule F2 H) (s : (H ⧸ W) →ₗ[F2] H) + (hs : W.mkQ.comp s = LinearMap.id) + +theorem exists_fallback_candidate_realizer + (hW : RepresentativeMatrixTable.Determined slots H other W) : + ∃ x : Assignment slots, + other x = (CanonicalMatrixTable.response slots H other labeling + (0 : CanonicalMatrixTable.Matrix (K := K) slots H)).2 ∧ + ∀ q : PulledColumnSpace.Candidates W ⊥ + (RepresentativeMatrixTable.correctionFunctional slots H other W s hs + (CanonicalMatrixTable.response slots H other labeling + (0 : CanonicalMatrixTable.Matrix (K := K) slots H)).2), + ∀ b : W, q.val (b : H) = b.val.val x := by + obtain ⟨x, _, hx⟩ := CanonicalMatrixTable.response_realized slots H other labeling + (0 : CanonicalMatrixTable.Matrix (K := K) slots H) + refine ⟨x, hx, ?_⟩ + intro q b + rw [PulledColumnSpace.candidate_apply_known, ← hx] + simpa only [add_zero] using RepresentativeDecoder.coset_apply_at_image + slots H other W s hs hW x 0 W.dualAnnihilator.zero_mem b + + +attribute [local instance] UniqueGamesTheorem.Appendix.RankLevelFilter.linearMapFintype + +variable [FiniteDimensional F2 H] + [Fintype H] [Fintype K] + (useful : (Module.Dual F2 (H ⧸ W) →ₗ[F2] K) → Prop) + +local instance representativeDualFintype : Fintype (Module.Dual F2 H) := + LeftDecoder.dualFintype (V := H) + +theorem adviceLaw_probability_eq_one_of_known_realizer + (hW : RepresentativeMatrixTable.Determined slots H other W) + (r : Nat) (ρ : ℝ) (hρ : 0 < ρ) (A : ManyGoodRows.RowMap K r) + (U : Module.Dual F2 (H ⧸ W) →ₗ[F2] (Fin r → F2)) + (event : Module.Dual F2 H → Bool) + (hevent : ∀ q : Module.Dual F2 H, + (∃ x : Assignment slots, ∀ b : W, q (b : H) = b.val.val x) → event q = true) : + (LeftDecoder.adviceLaw slots H other labeling W s hs useful r ρ A U).probability + event = 1 := by + by_cases hgood : ManyGoodRows.GoodRow + (RepresentativeMatrixTable.partialTable slots H other labeling W s useful) r ρ A U + · rw [LeftDecoder.adviceLaw_of_good slots H other labeling W s hs useful r ρ A U hgood] + unfold LeftDecoder.law + apply LeftDecoder.affineLaw_probability_eq_one + intro q + obtain ⟨x, _, hknown⟩ := LeftDecoder.exists_candidate_realizer + slots H other labeling W s hs useful hW + (ManyGoodRows.selectWitness + (RepresentativeMatrixTable.partialTable slots H other labeling W s useful) + r ρ A U hgood) hρ + exact hevent q.val ⟨x, hknown q⟩ + · simp only [LeftDecoder.adviceLaw, dite_eq_right hgood] + apply LeftDecoder.affineLaw_probability_eq_one + intro q + obtain ⟨x, _, hknown⟩ := + exists_fallback_candidate_realizer (K := K) slots H other labeling W s hs hW + exact hevent q.val ⟨x, hknown q⟩ + +theorem adviceLaw_known_realizer + (hW : RepresentativeMatrixTable.Determined slots H other W) + (r : Nat) (ρ : ℝ) (hρ : 0 < ρ) (A : ManyGoodRows.RowMap K r) + (U : Module.Dual F2 (H ⧸ W) →ₗ[F2] (Fin r → F2)) : + (LeftDecoder.adviceLaw slots H other labeling W s hs useful r ρ A U).probability + (fun q => decide (∃ x : Assignment slots, + ∀ b : W, q (b : H) = b.val.val x)) = 1 := + adviceLaw_probability_eq_one_of_known_realizer + slots H other labeling W s hs useful hW r ρ hρ A U _ + (fun _ hx => decide_eq_true hx) + + +end +end PerfectCompleteness.LeftDecoderKnownRows + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerCutBucketLocality.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerCutBucketLocality.lean new file mode 100644 index 0000000000000000000000000000000000000000..f282eb662a980e7151ff4de9630bb95c8febe50e --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerCutBucketLocality.lean @@ -0,0 +1,269 @@ +import OAI.Computability.PerfectCompleteness.Decoding.LowerCutRowsLemmas +import OAI.Computability.PerfectCompleteness.Foundations.WholeCutReplayLemmas +import OAI.Computability.PerfectCompleteness.Foundations.WholeReplaySubtreeLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.LowerCutBucketLocality + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open WholeCutGrouping WholeArraySubtreeSplit + +abbrev F2 := ZMod 2 + +variable {branch : Nat → Nat} {n k m t : Nat} + +def rootBuckets (rows repeats : Nat → Nat) : + {k m : Nat} → (pDown : Path branch k (m + 1)) → m + 1 < k → + (slots : Slots branch k → Fin t → MixedSupport.Slot) → + Exterior rows repeats pDown slots → + LowerCutCallSplit.Assembled rows repeats pDown slots → + BucketSampler.Direction (rows k) → H slots + | _, _, .refl _, hproper, _, _, _, _ => False.elim ((Nat.lt_irrefl _) hproper) + | _, _, .step i pDown, _, slots, exterior, assembled, direction => + LowerCutScalar.reconstruct F2 repeats (.step i pDown) (LeafDomain slots) + (fun terminal => assembled.1 (.inl (direction, terminal))) (exterior.1 direction) + +def buckets (rows repeats : Nat → Nat) : + {n k m : Nat} → (pUp : Path branch n k) → (pDown : Path branch k (m + 1)) → + m + 1 < k → (slots : Slots branch n → Fin t → MixedSupport.Slot) → + Exterior rows repeats (pUp.append pDown) slots → + LowerCutCallSplit.Assembled rows repeats (pUp.append pDown) slots → + BucketSampler.Direction (rows k) → H (subtreeSlots pUp slots) + | _, _, _, .refl _, pDown, hproper, slots, exterior, assembled => + rootBuckets rows repeats pDown hproper slots exterior assembled + | _, _, _, .step i pUp, pDown, hproper, slots, exterior, assembled => + buckets rows repeats pUp pDown hproper (childSlots slots i) exterior.2.1 + (fun call => assembled.1 (.inr call), assembled.2) + +theorem buckets_congr_otherCalls (rows repeats : Nat → Nat) (pUp : Path branch n k) : + ∀ {m : Nat} (pDown : Path branch k (m + 1)) (hproper : m + 1 < k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (exterior : Exterior rows repeats (pUp.append pDown) slots) + (x y : LowerCutCallSplit.Assembled rows repeats (pUp.append pDown) slots), + (∀ call, (∀ row, call ≠ WholeCutCalls.directRow rows repeats (pUp.append pDown) row) → + y.1 call = x.1 call) → + buckets rows repeats pUp pDown hproper slots exterior y = + buckets rows repeats pUp pDown hproper slots exterior x := by + induction pUp with + | refl k => + intro m pDown hproper slots exterior x y hcalls + cases pDown with + | refl => exact False.elim ((Nat.lt_irrefl _) hproper) + | step i pDown => + funext direction + have hvalues : + ((fun terminal => y.1 (.inl (direction, terminal))) : + LowerCutScalar.Values F2 repeats (.step i pDown) (LeafDomain slots)) = + (fun terminal => x.1 (.inl (direction, terminal))) := by + funext terminal + apply hcalls (.inl (direction, terminal)) + intro row h + cases h + simp only [buckets, rootBuckets] + rw [hvalues] + | step i pUp ih => + intro m pDown hproper slots exterior x y hcalls + apply ih pDown hproper (childSlots slots i) exterior.2.1 + (fun call => x.1 (.inr call), x.2) (fun call => y.1 (.inr call), y.2) + intro call hcall + apply hcalls (.inr call) + intro row h + exact hcall row (Sum.inr.inj h) + +theorem buckets_splitTape (rows repeats : Nat → Nat) (pUp : Path branch n k) : + ∀ {m : Nat} (pDown : Path branch k (m + 1)) (hproper : m + 1 < k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (tape : WholeCutSampler.Tape rows repeats (pUp.append pDown) slots), + buckets rows repeats pUp pDown hproper slots + (splitTape rows repeats (pUp.append pDown) slots tape).1 + (CutChildGrouping.assemble (cutSlots (pUp.append pDown) slots) rows + (splitTape rows repeats (pUp.append pDown) slots tape).2) = + WholeCutSubtree.rootBuckets rows repeats pDown hproper (subtreeSlots pUp slots) + (WholeCutSubtree.extract rows repeats pUp pDown slots tape) := by + induction pUp with + | refl k => + intro m pDown hproper slots tape + cases pDown with + | refl => exact False.elim ((Nat.lt_irrefl _) hproper) + | step i pDown => + funext direction + exact LowerCutScalar.reconstruct_splitTape F2 repeats (.step i pDown) + (LeafDomain slots) (tape.1 direction) + | step i pUp ih => + intro m pDown hproper slots tape + exact ih pDown hproper (childSlots slots i) tape.2.1 + +def knownBuckets (rows repeats : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) (upper : Nodes branch n) + (pDown : Path branch (Nodes.height upper) (m + 1)) + (hproper : m + 1 < Nodes.height upper) + (W : Submodule F2 (OwnInputReference.UpperVector rows upper)) + (exterior : Exterior rows repeats ((Nodes.path upper).append pDown) slots) + (assembled : LowerCutCallSplit.Assembled rows repeats ((Nodes.path upper).append pDown) slots) : + HiddenBucketBias.VisibleDirection W → OwnInputReference.UpperSpace slots upper := + fun v => buckets rows repeats (Nodes.path upper) pDown hproper slots exterior assembled v.val + +def knownBucketsOfComplement (rows repeats : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) (upper : Nodes branch n) + (pDown : Path branch (Nodes.height upper) (m + 1)) + (hproper : m + 1 < Nodes.height upper) + (W : Submodule F2 (OwnInputReference.UpperVector rows upper)) + (exterior : Exterior rows repeats ((Nodes.path upper).append pDown) slots) + (complement : LowerCutCallSplit.Complement rows repeats ((Nodes.path upper).append pDown) slots) : + HiddenBucketBias.VisibleDirection W → OwnInputReference.UpperSpace slots upper := + knownBuckets rows repeats slots upper pDown hproper W exterior + (LowerCutCallSplit.merge rows repeats ((Nodes.path upper).append pDown) slots complement 0) + +theorem knownBuckets_merge (rows repeats : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) (upper : Nodes branch n) + (pDown : Path branch (Nodes.height upper) (m + 1)) + (hproper : m + 1 < Nodes.height upper) + (W : Submodule F2 (OwnInputReference.UpperVector rows upper)) + (exterior : Exterior rows repeats ((Nodes.path upper).append pDown) slots) + (complement : LowerCutCallSplit.Complement rows repeats ((Nodes.path upper).append pDown) slots) + (fresh : LowerCutCallSplit.NativeRows rows ((Nodes.path upper).append pDown) slots) : + knownBuckets rows repeats slots upper pDown hproper W exterior + (LowerCutCallSplit.merge rows repeats ((Nodes.path upper).append pDown) slots complement fresh) = + knownBucketsOfComplement rows repeats slots upper pDown hproper W exterior complement := by + have h := buckets_congr_otherCalls rows repeats (Nodes.path upper) pDown hproper slots exterior + (LowerCutCallSplit.merge rows repeats ((Nodes.path upper).append pDown) slots complement 0) + (LowerCutCallSplit.merge rows repeats ((Nodes.path upper).append pDown) slots complement fresh) + (fun call hcall => + (LowerCutCallSplit.merge_otherCall rows repeats ((Nodes.path upper).append pDown) slots + complement fresh ⟨call, hcall⟩).trans + (LowerCutCallSplit.merge_otherCall rows repeats ((Nodes.path upper).append pDown) slots + complement 0 ⟨call, hcall⟩).symm) + funext v + exact congrFun h v.val + +theorem knownBuckets_eq_complement (rows repeats : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) (upper : Nodes branch n) + (pDown : Path branch (Nodes.height upper) (m + 1)) + (hproper : m + 1 < Nodes.height upper) + (W : Submodule F2 (OwnInputReference.UpperVector rows upper)) + (exterior : Exterior rows repeats ((Nodes.path upper).append pDown) slots) + (assembled : LowerCutCallSplit.Assembled rows repeats ((Nodes.path upper).append pDown) slots) : + knownBuckets rows repeats slots upper pDown hproper W exterior assembled = + knownBucketsOfComplement rows repeats slots upper pDown hproper W exterior + (LowerCutCallSplit.complement rows repeats ((Nodes.path upper).append pDown) slots assembled) := by + have h := buckets_congr_otherCalls rows repeats (Nodes.path upper) pDown hproper slots exterior + (LowerCutCallSplit.merge rows repeats ((Nodes.path upper).append pDown) slots + (LowerCutCallSplit.complement rows repeats ((Nodes.path upper).append pDown) slots assembled) 0) + assembled (fun call hcall => + (LowerCutCallSplit.merge_otherCall rows repeats ((Nodes.path upper).append pDown) slots + (LowerCutCallSplit.complement rows repeats ((Nodes.path upper).append pDown) slots assembled) + 0 ⟨call, hcall⟩).symm) + funext v + exact congrFun h v.val + +theorem knownBucketsAtNode_eq_complement (rows repeats : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) (upper : Nodes branch n) + (pDown : Path branch (Nodes.height upper) (m + 1)) + (hproper : m + 1 < Nodes.height upper) + (W : Submodule F2 (OwnInputReference.UpperVector rows upper)) + (tape : WholeCutSampler.Tape rows repeats ((Nodes.path upper).append pDown) slots) : + WholeCutSubtree.knownBucketsAtNode rows repeats slots upper pDown hproper W tape = + knownBucketsOfComplement rows repeats slots upper pDown hproper W + (splitTape rows repeats ((Nodes.path upper).append pDown) slots tape).1 + (LowerCutCallSplit.complement rows repeats ((Nodes.path upper).append pDown) slots + (CutChildGrouping.assemble (cutSlots ((Nodes.path upper).append pDown) slots) rows + (splitTape rows repeats ((Nodes.path upper).append pDown) slots tape).2)) := by + have hreader := buckets_splitTape rows repeats (Nodes.path upper) pDown hproper slots tape + have hknown : WholeCutSubtree.knownBucketsAtNode rows repeats slots upper pDown hproper W tape = + knownBuckets rows repeats slots upper pDown hproper W + (splitTape rows repeats ((Nodes.path upper).append pDown) slots tape).1 + (CutChildGrouping.assemble (cutSlots ((Nodes.path upper).append pDown) slots) rows + (splitTape rows repeats ((Nodes.path upper).append pDown) slots tape).2) := by + funext v + exact (congrFun hreader v.val).symm + exact hknown.trans (knownBuckets_eq_complement rows repeats slots upper pDown hproper W _ _) + +theorem knownBucketsAtNode_join (rows repeats : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) (upper : Nodes branch n) + (pDown : Path branch (Nodes.height upper) (m + 1)) + (hproper : m + 1 < Nodes.height upper) + (W : Submodule F2 (OwnInputReference.UpperVector rows upper)) + (exterior : Exterior rows repeats ((Nodes.path upper).append pDown) slots) + (raw : CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats ((Nodes.path upper).append pDown)) + (cutSlots ((Nodes.path upper).append pDown) slots) rows) : + WholeCutSubtree.knownBucketsAtNode rows repeats slots upper pDown hproper W + ((splitTape rows repeats ((Nodes.path upper).append pDown) slots).symm (exterior, raw)) = + knownBucketsOfComplement rows repeats slots upper pDown hproper W exterior + (LowerCutCallSplit.complement rows repeats ((Nodes.path upper).append pDown) slots + (CutChildGrouping.assemble (cutSlots ((Nodes.path upper).append pDown) slots) rows raw)) := by + have h := knownBucketsAtNode_eq_complement rows repeats slots upper pDown hproper W + ((splitTape rows repeats ((Nodes.path upper).append pDown) slots).symm (exterior, raw)) + rw [Equiv.apply_symm_apply] at h + exact h + +theorem knownBucketsAtNode_erase_eq (rows repeats : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) (upper : Nodes branch n) + (pDown : Path branch (Nodes.height upper) (m + 1)) + (hproper : m + 1 < Nodes.height upper) (clean : Fin (branch m) → Prop) + (W : Submodule F2 (OwnInputReference.UpperVector rows upper)) + (tape : WholeCutSampler.Tape rows repeats ((Nodes.path upper).append pDown) slots) + (hzero : WholeCutZero.ZeroAtClean rows repeats ((Nodes.path upper).append pDown) slots clean tape) : + WholeReplaySubtree.knownBucketsAtNode rows repeats slots upper pDown hproper clean W + (WholeCutReplay.erase rows repeats ((Nodes.path upper).append pDown) slots clean tape) = + knownBucketsOfComplement rows repeats slots upper pDown hproper W + (splitTape rows repeats ((Nodes.path upper).append pDown) slots tape).1 + (LowerCutCallSplit.complement rows repeats ((Nodes.path upper).append pDown) slots + (CutChildGrouping.assemble (cutSlots ((Nodes.path upper).append pDown) slots) rows + (splitTape rows repeats ((Nodes.path upper).append pDown) slots tape).2)) := + (WholeCutSubtree.knownBucketsAtNode_erase rows repeats slots upper pDown hproper clean W tape hzero).trans + (knownBucketsAtNode_eq_complement rows repeats slots upper pDown hproper W tape) + +theorem knownBucketsAtNode_assemble_splitTape (rows repeats : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) (upper : Nodes branch n) + (pDown : Path branch (Nodes.height upper) (m + 1)) + (hproper : m + 1 < Nodes.height upper) (clean : Fin (branch m) → Prop) + (W : Submodule F2 (OwnInputReference.UpperVector rows upper)) + (tape : WholeCutSampler.Tape rows repeats ((Nodes.path upper).append pDown) slots) + (hzero : WholeCutZero.ZeroAtClean rows repeats ((Nodes.path upper).append pDown) slots clean tape) : + WholeReplaySubtree.knownBucketsAtNode rows repeats slots upper pDown hproper clean W + (WholeCutReplayGrouping.assemble rows repeats ((Nodes.path upper).append pDown) slots clean + (splitTape rows repeats ((Nodes.path upper).append pDown) slots tape).1 + (fun child => (splitTape rows repeats ((Nodes.path upper).append pDown) slots tape).2 child.val)) = + knownBucketsOfComplement rows repeats slots upper pDown hproper W + (splitTape rows repeats ((Nodes.path upper).append pDown) slots tape).1 + (LowerCutCallSplit.complement rows repeats ((Nodes.path upper).append pDown) slots + (CutChildGrouping.assemble (cutSlots ((Nodes.path upper).append pDown) slots) rows + (splitTape rows repeats ((Nodes.path upper).append pDown) slots tape).2)) := by + exact (congrArg (WholeReplaySubtree.knownBucketsAtNode rows repeats slots upper pDown hproper clean W) + (WholeCutReplayGrouping.assemble_splitTape rows repeats ((Nodes.path upper).append pDown) + slots clean tape)).trans + (knownBucketsAtNode_erase_eq rows repeats slots upper pDown hproper clean W tape hzero) + +theorem knownBucketsAtNode_assemble (rows repeats : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) (upper : Nodes branch n) + (pDown : Path branch (Nodes.height upper) (m + 1)) + (hproper : m + 1 < Nodes.height upper) (clean : Fin (branch m) → Prop) + (W : Submodule F2 (OwnInputReference.UpperVector rows upper)) + (exterior : Exterior rows repeats ((Nodes.path upper).append pDown) slots) + (raw : CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats ((Nodes.path upper).append pDown)) + (cutSlots ((Nodes.path upper).append pDown) slots) rows) + (hzero : WholeCutZero.ZeroAtClean rows repeats ((Nodes.path upper).append pDown) slots clean + ((splitTape rows repeats ((Nodes.path upper).append pDown) slots).symm (exterior, raw))) : + WholeReplaySubtree.knownBucketsAtNode rows repeats slots upper pDown hproper clean W + (WholeCutReplayGrouping.assemble rows repeats ((Nodes.path upper).append pDown) slots clean + exterior (fun child => raw child.val)) = + knownBucketsOfComplement rows repeats slots upper pDown hproper W exterior + (LowerCutCallSplit.complement rows repeats ((Nodes.path upper).append pDown) slots + (CutChildGrouping.assemble (cutSlots ((Nodes.path upper).append pDown) slots) rows raw)) := by + have h := knownBucketsAtNode_assemble_splitTape rows repeats slots upper pDown hproper clean W + ((splitTape rows repeats ((Nodes.path upper).append pDown) slots).symm (exterior, raw)) hzero + rw [Equiv.apply_symm_apply] at h + exact h + +end +end PerfectCompleteness.LowerCutBucketLocality + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerCutFiberDisintegrationLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerCutFiberDisintegrationLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..a7f8cd8417c9359104fa9deec70964e3bbf0dde6 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerCutFiberDisintegrationLemmas.lean @@ -0,0 +1,451 @@ +import OAI.Computability.PerfectCompleteness.Decoding.ChildAssemblyProjection +import OAI.Computability.PerfectCompleteness.Decoding.LowerCutPairBackground +import OAI.Computability.PerfectCompleteness.Decoding.LowerCutPairLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.LowerCutFiberDisintegration + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open WholeCutGrouping +open UniqueGamesTheorem.Foundations.Games + +variable {branch : Nat → Nat} {n m t : Nat} + (rows repeats : Nat → Nat) (path : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (a : BucketSampler.Direction (rows (m + 1))) + +abbrev Scalar := H (cutSlots path slots) +abbrev Quotient := LowerDirectionFiber.Complement a (Scalar path slots) +abbrev Background := LowerCutPairBackground.Complement rows repeats path slots × + Quotient rows path slots a +abbrev Coordinates := Background rows repeats path slots a × + (Scalar path slots × Scalar path slots) + +def coordinateEquiv : LowerCutPairBackground.Observation rows repeats path slots ≃ + Coordinates rows repeats path slots a where + toFun z := ((z.1, LowerDirectionFiber.complement a z.2.1), + (z.2.1 (LowerDirectionFiber.pivot a), z.2.2)) + invFun z := (z.1.1, (LowerDirectionFiber.restore a z.1.2 z.2.1, z.2.2)) + left_inv z := by + change (z.1, (LowerDirectionFiber.restore a + (LowerDirectionFiber.complement a z.2.1) (z.2.1 (LowerDirectionFiber.pivot a)), + z.2.2)) = z + exact Prod.ext rfl (Prod.ext (LowerDirectionFiber.restore_complement a z.2.1) rfl) + right_inv z := by + apply Prod.ext + · exact Prod.ext rfl (LowerDirectionFiber.complement_restore a z.1.2 z.2.1) + · exact Prod.ext (LowerDirectionFiber.restore_pivot a z.1.2 z.2.1) rfl + +@[simp] theorem coordinateEquiv_apply (z : LowerCutPairBackground.Observation rows repeats path slots) : + coordinateEquiv rows repeats path slots a z = + ((z.1, LowerDirectionFiber.complement a z.2.1), + (z.2.1 (LowerDirectionFiber.pivot a), z.2.2)) := rfl + +def coordinates (raw : LowerCutPair.Raw rows repeats path slots) : + Coordinates rows repeats path slots a := + coordinateEquiv rows repeats path slots a + (LowerCutPairBackground.observe rows repeats path slots raw) + +def law : FiniteDistribution (Coordinates rows repeats path slots a) := + ((FiniteDistribution.uniform (LowerCutPairBackground.Complement rows repeats path slots)).product + (FiniteDistribution.uniform (Quotient rows path slots a))).product + ((FiniteDistribution.uniform (Scalar path slots)).product + (FiniteDistribution.uniform (Scalar path slots))) + +theorem coordinates_law : + (CutChildGrouping.rawLaw (C := Option (LowerCutPair.Calls rows repeats path)) + (cutSlots path slots) rows).pushforward (coordinates rows repeats path slots a) = + law rows repeats path slots a := by + change (CutChildGrouping.rawLaw (C := Option (LowerCutPair.Calls rows repeats path)) + (cutSlots path slots) rows).pushforward + (fun raw => coordinateEquiv rows repeats path slots a + (LowerCutPairBackground.observe rows repeats path slots raw)) = _ + rw [← FiniteDistribution.pushforward_comp, + LowerCutPairBackground.observe_law] + have h := UniformConditioning.uniform_transport + (coordinateEquiv rows repeats path slots a) + rw [FiniteDistribution.transport_eq_pushforward] at h + simpa only [law, WholeCutSampler.uniform_product] using h + +def arraysAt (exterior : Exterior rows repeats path slots) + (background : Background rows repeats path slots a) (fresh : Scalar path slots) : + Arrays slots rows := + LowerCutPairBackground.installRows rows repeats path slots exterior background.1 + (LowerDirectionFiber.restore a background.2 fresh) + +theorem first_eq_arraysAt (exterior : Exterior rows repeats path slots) + (raw : LowerCutPair.Raw rows repeats path slots) : + LowerCutPair.first rows repeats path slots exterior raw = + arraysAt rows repeats path slots a exterior + (coordinates rows repeats path slots a raw).1 + (coordinates rows repeats path slots a raw).2.1 := by + simp only [arraysAt, coordinates, coordinateEquiv_apply, LowerDirectionFiber.restore_complement] + rw [LowerCutPairBackground.observe_rows rows repeats path slots exterior] + exact LowerCutPairBackground.first_eq_installRows rows repeats path slots exterior raw + +theorem second_eq_arraysAt (exterior : Exterior rows repeats path slots) + (raw : LowerCutPair.Raw rows repeats path slots) : + LowerCutPair.second rows repeats path slots exterior a raw = + arraysAt rows repeats path slots a exterior + (coordinates rows repeats path slots a raw).1 + (coordinates rows repeats path slots a raw).2.2 := by + rw [LowerCutPairBackground.second_eq_installRows, + LowerCutPair.selected_second] + simp only [arraysAt, coordinates, coordinateEquiv_apply, + LowerDirectionFiber.replace, LowerCutPairBackground.observe_rows rows repeats path slots exterior, + LowerCutPairBackground.observe_fresh] + +def pair (exterior : Exterior rows repeats path slots) + (z : Coordinates rows repeats path slots a) : Arrays slots rows × Arrays slots rows := + (arraysAt rows repeats path slots a exterior z.1 z.2.1, + arraysAt rows repeats path slots a exterior z.1 z.2.2) + +theorem pair_coordinates (exterior : Exterior rows repeats path slots) + (raw : LowerCutPair.Raw rows repeats path slots) : + pair rows repeats path slots a exterior (coordinates rows repeats path slots a raw) = + LowerCutPair.arraysPair rows repeats path slots exterior a raw := + Prod.ext (first_eq_arraysAt rows repeats path slots a exterior raw).symm + (second_eq_arraysAt rows repeats path slots a exterior raw).symm + +theorem arraysPair_law (exterior : Exterior rows repeats path slots) : + (CutChildGrouping.rawLaw (C := Option (LowerCutPair.Calls rows repeats path)) + (cutSlots path slots) rows).pushforward + (LowerCutPair.arraysPair rows repeats path slots exterior a) = + (law rows repeats path slots a).pushforward (pair rows repeats path slots a exterior) := by + have h := congrArg + (fun μ : FiniteDistribution (Coordinates rows repeats path slots a) => + μ.pushforward (pair rows repeats path slots a exterior)) + (coordinates_law rows repeats path slots a) + rw [FiniteDistribution.pushforward_comp] at h + simpa only [pair_coordinates] using h + +theorem probability_pair (exterior : Exterior rows repeats path slots) + (event : Arrays slots rows × Arrays slots rows → Bool) : + (CutChildGrouping.rawLaw (C := Option (LowerCutPair.Calls rows repeats path)) + (cutSlots path slots) rows).probability + (fun raw => event (LowerCutPair.arraysPair rows repeats path slots exterior a raw)) = + (law rows repeats path slots a).probability + (fun z => event (pair rows repeats path slots a exterior z)) := by + rw [← FiniteDistribution.probability_pushforward, + arraysPair_law, FiniteDistribution.probability_pushforward] + +end +end PerfectCompleteness.LowerCutFiberDisintegration + +end + +section + +namespace PerfectCompleteness.LowerCutProjection + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open scoped Classical + +noncomputable section + +section Linear + +variable {H K : Type*} [AddCommGroup H] [AddCommGroup K] + [Module F2 H] [Module F2 K] {ℓ : Nat} + +theorem linearMap_replace (f : H →ₗ[F2] K) (a : BucketSampler.Direction ℓ) + (S : Fin ℓ → H) (fresh : H) : + (fun i => f (LowerDirectionFiber.replace a S fresh i)) = + LowerDirectionFiber.replace a (fun i => f (S i)) (f fresh) := by + rw [LowerDirectionFiber.replace_eq, LowerDirectionFiber.replace_eq] + funext i + simp only [Pi.add_apply, BucketSampler.rankOne, map_add, map_smul, map_sub] + +end Linear + +section Local + +variable {branch : Nat → Nat} {n t : Nat} {C : Type*} [Fintype C] + {slots projected : Slots branch (n + 1) → Fin t → MixedSupport.Slot} + +omit [Fintype C] in +theorem original_pullback (rows : Nat → Nat) + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (raw : CutCallExtension.Extended (C := C) projected rows) : + CutCallExtension.original slots rows + (ChildAssemblyProjection.rawPullback (C := Option C) rows p raw) = + ChildAssemblyProjection.rawPullback (C := C) rows p + (CutCallExtension.original projected rows raw) := rfl + +omit [Fintype C] in +theorem fresh_pullback (rows : Nat → Nat) + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (raw : CutCallExtension.Extended (C := C) projected rows) : + CutCallExtension.fresh slots rows + (ChildAssemblyProjection.rawPullback (C := Option C) rows p raw) = + HPullback p (CutCallExtension.fresh projected rows raw) := + ChildAssemblyProjection.recursiveSum_pullback p (fun i => (raw i).1 none) + +def observePullback (rows : Nat → Nat) + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) : + (CutChildGrouping.Assembled (C := C) projected rows × H projected) →ₗ[F2] + (CutChildGrouping.Assembled (C := C) slots rows × H slots) := + (ChildAssemblyProjection.assembledPullback (C := C) rows p).prodMap (HPullback p) + +omit [Fintype C] in +theorem observe_pullback (rows : Nat → Nat) + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (raw : CutCallExtension.Extended (C := C) projected rows) : + CutCallExtension.observe slots rows + (ChildAssemblyProjection.rawPullback (C := Option C) rows p raw) = + observePullback rows p (CutCallExtension.observe projected rows raw) := by + apply Prod.ext + · change CutChildGrouping.assemble slots rows + (CutCallExtension.original slots rows + (ChildAssemblyProjection.rawPullback (C := Option C) rows p raw)) = + ChildAssemblyProjection.assembledPullback rows p + (CutChildGrouping.assemble projected rows (CutCallExtension.original projected rows raw)) + rw [original_pullback] + exact ChildAssemblyProjection.assemble_pullback rows p _ + · exact fresh_pullback rows p raw + +theorem pushforward_observe (rows : Nat → Nat) + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (μ : FiniteDistribution (CutCallExtension.Extended (C := C) projected rows)) : + (μ.pushforward (ChildAssemblyProjection.rawPullback (C := Option C) rows p)).pushforward + (CutCallExtension.observe slots rows) = + (μ.pushforward (CutCallExtension.observe projected rows)).pushforward + (observePullback rows p) := by + rw [FiniteDistribution.pushforward_comp, FiniteDistribution.pushforward_comp] + congr 1 + funext raw + exact observe_pullback rows p raw + +theorem uniform_projected_observe (rows : Nat → Nat) + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) : + ((CutChildGrouping.rawLaw (C := Option C) projected rows).pushforward + (ChildAssemblyProjection.rawPullback rows p)).pushforward + (CutCallExtension.observe slots rows) = + ((FiniteDistribution.uniform (CutChildGrouping.Assembled (C := C) projected rows)).product + (FiniteDistribution.uniform (H projected))).pushforward (observePullback rows p) := by + rw [pushforward_observe, CutCallExtension.observe_law] + +theorem HPullback_replace {ℓ : Nat} + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (a : BucketSampler.Direction ℓ) (S : Fin ℓ → H projected) (fresh : H projected) : + (fun i => HPullback p (LowerDirectionFiber.replace a S fresh i)) = + LowerDirectionFiber.replace a (fun i => HPullback p (S i)) (HPullback p fresh) := + linearMap_replace (HPullback p) a S fresh + +end Local + +section Selected + +variable {branch : Nat → Nat} {n m t : Nat} + (rows repeats : Nat → Nat) (path : Path branch n (m + 1)) + {slots projected : Slots branch n → Fin t → MixedSupport.Slot} + +theorem firstRows_pullback + (p : ∀ s k, MixedSupport.Projection + (WholeCutGrouping.cutSlots path slots s k) (WholeCutGrouping.cutSlots path projected s k)) + (exterior : WholeCutGrouping.Exterior rows repeats path slots) + (projectedExterior : WholeCutGrouping.Exterior rows repeats path projected) + (raw : LowerCutPair.Raw rows repeats path projected) : + SelectedArrayReplacement.selectedRows rows path slots + (LowerCutPair.first rows repeats path slots exterior + (ChildAssemblyProjection.rawPullback rows p raw)) = + (fun i => HPullback p + (SelectedArrayReplacement.selectedRows rows path projected + (LowerCutPair.first rows repeats path projected projectedExterior raw) i)) := by + simp only [LowerCutPair.first, LowerCutRows.selectedRows_reconstruct_eq] + rw [original_pullback] + exact congrArg (LowerCutRows.selectRows rows repeats path slots) + (ChildAssemblyProjection.assemble_pullback rows p + (CutCallExtension.original (WholeCutGrouping.cutSlots path projected) rows raw)) + +theorem selectedPair_pullback + (p : ∀ s k, MixedSupport.Projection + (WholeCutGrouping.cutSlots path slots s k) (WholeCutGrouping.cutSlots path projected s k)) + (exterior : WholeCutGrouping.Exterior rows repeats path slots) + (projectedExterior : WholeCutGrouping.Exterior rows repeats path projected) + (a : BucketSampler.Direction (rows (m + 1))) + (raw : LowerCutPair.Raw rows repeats path projected) : + LowerCutPair.selectedPair rows repeats path slots exterior a + (ChildAssemblyProjection.rawPullback rows p raw) = + ((fun i => HPullback p + ((LowerCutPair.selectedPair rows repeats path projected projectedExterior a raw).1 i)), + (fun i => HPullback p + ((LowerCutPair.selectedPair rows repeats path projected projectedExterior a raw).2 i))) := by + simp only [LowerCutPair.selectedPair, LowerCutPair.selected_second] + apply Prod.ext + · exact firstRows_pullback rows repeats path p exterior projectedExterior raw + · rw [firstRows_pullback rows repeats path p exterior projectedExterior raw] + simp only [LowerCutPair.fresh] + rw [fresh_pullback] + exact (HPullback_replace p a _ _).symm + +end Selected +end +end PerfectCompleteness.LowerCutProjection + +end + +section + +namespace PerfectCompleteness.LowerCutSingleFiberDisintegration + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open WholeCutGrouping +open UniqueGamesTheorem.Foundations.Games + +variable {branch : Nat → Nat} {n m t : Nat} + (rows repeats : Nat → Nat) (path : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (a : BucketSampler.Direction (rows (m + 1))) + +abbrev Raw := CutChildGrouping.Raw (C := LowerCutPair.Calls rows repeats path) + (cutSlots path slots) rows + +abbrev Coordinates := LowerCutFiberDisintegration.Background rows repeats path slots a × + H (cutSlots path slots) + +def coordinateEquiv : + (LowerCutCallSplit.Complement rows repeats path slots × + LowerCutCallSplit.NativeRows rows path slots) ≃ + Coordinates rows repeats path slots a where + toFun z := ((z.1, LowerDirectionFiber.complement a z.2), + z.2 (LowerDirectionFiber.pivot a)) + invFun z := (z.1.1, LowerDirectionFiber.restore a z.1.2 z.2) + left_inv z := Prod.ext rfl (LowerDirectionFiber.restore_complement a z.2) + right_inv z := Prod.ext + (Prod.ext rfl (LowerDirectionFiber.complement_restore a z.1.2 z.2)) + (LowerDirectionFiber.restore_pivot a z.1.2 z.2) + +@[simp] theorem coordinateEquiv_apply + (z : LowerCutCallSplit.Complement rows repeats path slots × + LowerCutCallSplit.NativeRows rows path slots) : + coordinateEquiv rows repeats path slots a z = + ((z.1, LowerDirectionFiber.complement a z.2), + z.2 (LowerDirectionFiber.pivot a)) := rfl + +def coordinates (raw : Raw rows repeats path slots) : + Coordinates rows repeats path slots a := + coordinateEquiv rows repeats path slots a + (LowerCutCallSplit.splitAssembled rows repeats path slots + (CutChildGrouping.assemble (cutSlots path slots) rows raw)) + +@[simp] theorem coordinates_complement (raw : Raw rows repeats path slots) : + (coordinates rows repeats path slots a raw).1.1 = + LowerCutCallSplit.complement rows repeats path slots + (CutChildGrouping.assemble (cutSlots path slots) rows raw) := rfl + +theorem coordinates_law : + (CutChildGrouping.rawLaw (C := LowerCutPair.Calls rows repeats path) + (cutSlots path slots) rows).pushforward (coordinates rows repeats path slots a) = + ((FiniteDistribution.uniform + (LowerCutPairBackground.Complement rows repeats path slots)).product + (FiniteDistribution.uniform + (LowerCutFiberDisintegration.Quotient rows path slots a))).product + (FiniteDistribution.uniform (H (cutSlots path slots))) := by + have hsplit : + (CutChildGrouping.rawLaw (C := LowerCutPair.Calls rows repeats path) + (cutSlots path slots) rows).pushforward (fun raw => + LowerCutCallSplit.splitAssembled rows repeats path slots + (CutChildGrouping.assemble (cutSlots path slots) rows raw)) = + FiniteDistribution.uniform + (LowerCutCallSplit.Complement rows repeats path slots × + LowerCutCallSplit.NativeRows rows path slots) := by + rw [← FiniteDistribution.pushforward_comp, CutChildGrouping.assemble_law] + exact UniformLinearImage.uniform_pushforward_linearMap + (LowerCutCallSplit.splitAssembled rows repeats path slots) + (LowerCutCallSplit.splitAssembled_surjective rows repeats path slots) + have h := congrArg + (fun μ : FiniteDistribution + (LowerCutCallSplit.Complement rows repeats path slots × + LowerCutCallSplit.NativeRows rows path slots) => + μ.pushforward (coordinateEquiv rows repeats path slots a)) hsplit + rw [FiniteDistribution.pushforward_comp] at h + have hcoord := UniformConditioning.uniform_transport + (coordinateEquiv rows repeats path slots a) + rw [FiniteDistribution.transport_eq_pushforward] at hcoord + have hfinal := h.trans hcoord + change (CutChildGrouping.rawLaw (C := LowerCutPair.Calls rows repeats path) + (cutSlots path slots) rows).pushforward (fun raw => + coordinateEquiv rows repeats path slots a + (LowerCutCallSplit.splitAssembled rows repeats path slots + (CutChildGrouping.assemble (cutSlots path slots) rows raw))) = _ + calc + _ = FiniteDistribution.uniform (Coordinates rows repeats path slots a) := hfinal + _ = _ := by + apply FiniteDistribution.eq_of_weight_eq + intro z + simp only [FiniteDistribution.uniform, FiniteDistribution.product, + Coordinates, LowerCutFiberDisintegration.Background, + Fintype.card_prod, Nat.cast_mul, one_div_mul_one_div] + +theorem reconstruct_eq_arraysAt (exterior : Exterior rows repeats path slots) + (raw : Raw rows repeats path slots) : + LowerCutRows.reconstruct rows repeats path slots exterior raw = + LowerCutFiberDisintegration.arraysAt rows repeats path slots a exterior + (coordinates rows repeats path slots a raw).1 + (coordinates rows repeats path slots a raw).2 := by + simp only [LowerCutFiberDisintegration.arraysAt, coordinates, + coordinateEquiv_apply, LowerDirectionFiber.restore_complement] + rw [← LowerCutAssembled.reconstruct_assemble, + ← LowerCutPairBackground.reconstruct_merge, LowerCutCallSplit.merge_split] + +theorem expectation_fiber (exterior : Exterior rows repeats path slots) + (f : LowerCutFiberDisintegration.Background rows repeats path slots a → + Arrays slots rows → ℝ) : + (CutChildGrouping.rawLaw (C := LowerCutPair.Calls rows repeats path) + (cutSlots path slots) rows).expectation (fun raw => + f (coordinates rows repeats path slots a raw).1 + (LowerCutRows.reconstruct rows repeats path slots exterior raw)) = + (((FiniteDistribution.uniform + (LowerCutPairBackground.Complement rows repeats path slots)).product + (FiniteDistribution.uniform + (LowerCutFiberDisintegration.Quotient rows path slots a))).product + (FiniteDistribution.uniform (H (cutSlots path slots)))).expectation + (fun z => f z.1 + (LowerCutFiberDisintegration.arraysAt rows repeats path slots a exterior z.1 z.2)) := by + have h := congrArg + (fun μ : FiniteDistribution (Coordinates rows repeats path slots a) => + μ.expectation (fun z => f z.1 + (LowerCutFiberDisintegration.arraysAt rows repeats path slots a exterior z.1 z.2))) + (coordinates_law rows repeats path slots a) + rw [FiniteDistribution.expectation_pushforward] at h + simpa only [← reconstruct_eq_arraysAt rows repeats path slots a exterior] using h + +theorem probability_fiber (exterior : Exterior rows repeats path slots) + (event : LowerCutFiberDisintegration.Background rows repeats path slots a → + Arrays slots rows → Bool) : + (CutChildGrouping.rawLaw (C := LowerCutPair.Calls rows repeats path) + (cutSlots path slots) rows).probability (fun raw => + event (coordinates rows repeats path slots a raw).1 + (LowerCutRows.reconstruct rows repeats path slots exterior raw)) = + (((FiniteDistribution.uniform + (LowerCutPairBackground.Complement rows repeats path slots)).product + (FiniteDistribution.uniform + (LowerCutFiberDisintegration.Quotient rows path slots a))).product + (FiniteDistribution.uniform (H (cutSlots path slots)))).probability + (fun z => event z.1 + (LowerCutFiberDisintegration.arraysAt rows repeats path slots a exterior z.1 z.2)) := by + have h := congrArg + (fun μ : FiniteDistribution (Coordinates rows repeats path slots a) => + μ.probability (fun z => event z.1 + (LowerCutFiberDisintegration.arraysAt rows repeats path slots a exterior z.1 z.2))) + (coordinates_law rows repeats path slots a) + rw [FiniteDistribution.probability_pushforward] at h + simpa only [← reconstruct_eq_arraysAt rows repeats path slots a exterior] using h + +end +end PerfectCompleteness.LowerCutSingleFiberDisintegration + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerCutFormCollision.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerCutFormCollision.lean new file mode 100644 index 0000000000000000000000000000000000000000..4d5349bcb1bb49d635284d79a952d7bdd2c78eaf --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerCutFormCollision.lean @@ -0,0 +1,124 @@ +import OAI.Computability.PerfectCompleteness.Decoding.LowerCutScalarProjectionLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.LowerCutFormCollision + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays + +variable {branch : Nat → Nat} {n height t : Nat} + (path : Path branch n (height + 1)) + (outside : Slots branch n → Fin t → MixedSupport.Slot) + (inside : Slots branch (height + 1) → Fin t → MixedSupport.Slot) + (upper : Nodes branch n) (level : Nat) + (d : HierarchicalFrozenTables.LowerNodes upper level) + (hnode : WholeArrayInteriorExterior.upperNode path = + HierarchicalLeftDecoder.LowerNode upper level d) + +def nativeScalar (f : H inside) : + HierarchicalDecoderTables.LowerH (CutSlotAssembly.fill path outside inside) upper level d := + LowerCutDecoderForm.spaceEquiv path (CutSlotAssembly.fill path outside inside) + upper level d hnode + (CutNativeForms.spaceCast (CleanPhysicalReplay.cutSlots_fill path outside inside).symm f) + +def nativeForm + (answer : HierarchicalDecoderTables.Answer + (CutSlotAssembly.fill path outside inside) upper level d) : + ChildBilinearCollisionTransfer.ParentForm inside := + CutNativeForms.formCast (CleanPhysicalReplay.cutSlots_fill path outside inside) + (LowerCutDecoderForm.form path (CutSlotAssembly.fill path outside inside) + upper level d hnode answer) + +private theorem formCast_apply_inverse + {source target : Slots branch (height + 1) → Fin t → MixedSupport.Slot} + (h : source = target) (F : ChildBilinearCollisionTransfer.ParentForm source) + (f g : H target) : + CutNativeForms.formCast h F f g = + F (CutNativeForms.spaceCast h.symm f) (CutNativeForms.spaceCast h.symm g) := by + cases h + rfl + +theorem nativeForm_apply + (answer : HierarchicalDecoderTables.Answer + (CutSlotAssembly.fill path outside inside) upper level d) (f g : H inside) : + nativeForm path outside inside upper level d hnode answer f g = + OddListExtraction.multiplicationForm + (HierarchicalDecoderTables.LowerH + (CutSlotAssembly.fill path outside inside) upper level d) answer + (nativeScalar path outside inside upper level d hnode f) + (nativeScalar path outside inside upper level d hnode g) := by + unfold nativeForm + rw [formCast_apply_inverse] + rfl + +variable (projected : Slots branch (height + 1) → Fin t → MixedSupport.Slot) + (projection : ∀ s k, MixedSupport.Projection (inside s k) (projected s k)) + +theorem nativeScalar_HPullback (f : H projected) : + nativeScalar path outside inside upper level d hnode (HPullback projection f) = + HPullback (ChildBlockProjection.nodeProjection + (CutProjectionAssembly.fillProjection path outside inside projected projection) + (HierarchicalLeftDecoder.LowerNode upper level d)) + (nativeScalar path outside projected upper level d hnode f) := + LowerCutScalarProjection.spaceEquiv_fill_HPullback path outside inside projected + upper level d hnode projection f + +theorem restricted_on_native + (answer₀ answer₁ : Option (HierarchicalDecoderTables.Answer + (CutSlotAssembly.fill path outside inside) upper level d)) + (U : Submodule F2 (H inside)) (hU : U ≤ LinearMap.range (HPullback projection)) + (hcollision : BilinearCollisionTransfer.restrictedCollision + (answer₀.map (OddListExtraction.multiplicationForm + (HierarchicalDecoderTables.LowerH + (CutSlotAssembly.fill path outside inside) upper level d))) + (answer₁.map (OddListExtraction.multiplicationForm + (HierarchicalDecoderTables.LowerH + (CutSlotAssembly.fill path outside inside) upper level d))) + (LinearMap.range (HPullback (ChildBlockProjection.nodeProjection + (CutProjectionAssembly.fillProjection path outside inside projected projection) + (HierarchicalLeftDecoder.LowerNode upper level d)))) = true) : + BilinearCollisionTransfer.restrictedCollision + (answer₀.map (nativeForm path outside inside upper level d hnode)) + (answer₁.map (nativeForm path outside inside upper level d hnode)) U = true := by + obtain ⟨F, G, hF, hG, heq⟩ := of_decide_eq_true hcollision + cases answer₀ with + | none => cases hF + | some a₀ => + cases answer₁ with + | none => cases hG + | some a₁ => + have hF' := Option.some.inj hF + have hG' := Option.some.inj hG + rw [← hF', ← hG'] at heq + apply decide_eq_true + refine ⟨nativeForm path outside inside upper level d hnode a₀, + nativeForm path outside inside upper level d hnode a₁, rfl, rfl, ?_⟩ + intro f hf g hg + rw [nativeForm_apply, nativeForm_apply] + obtain ⟨f', hf'⟩ := hU hf + obtain ⟨g', hg'⟩ := hU hg + have hfmem : nativeScalar path outside inside upper level d hnode f ∈ + LinearMap.range (HPullback (ChildBlockProjection.nodeProjection + (CutProjectionAssembly.fillProjection path outside inside projected projection) + (HierarchicalLeftDecoder.LowerNode upper level d))) := by + refine ⟨nativeScalar path outside projected upper level d hnode f', ?_⟩ + rw [← nativeScalar_HPullback, hf'] + have hgmem : nativeScalar path outside inside upper level d hnode g ∈ + LinearMap.range (HPullback (ChildBlockProjection.nodeProjection + (CutProjectionAssembly.fillProjection path outside inside projected projection) + (HierarchicalLeftDecoder.LowerNode upper level d))) := by + refine ⟨nativeScalar path outside projected upper level d hnode g', ?_⟩ + rw [← nativeScalar_HPullback, hg'] + exact heq _ hfmem _ hgmem + +end +end PerfectCompleteness.LowerCutFormCollision + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerCutNodeCoordinates.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerCutNodeCoordinates.lean new file mode 100644 index 0000000000000000000000000000000000000000..fe8d21f8c5fd003af72ad837d224db8e0226f6f9 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerCutNodeCoordinates.lean @@ -0,0 +1,124 @@ +import OAI.Computability.PerfectCompleteness.Decoding.LowerDirectionFiber +import OAI.Computability.PerfectCompleteness.Foundations.WholeArrayInteriorExteriorLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.LowerCutNodeCoordinates + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open WholeArraySubtreeSplit WholeArrayInteriorExterior +open scoped Classical + +noncomputable section + +variable {branch : Nat → Nat} {n m t : Nat} + +def scalarEquiv : {n m : Nat} → (p : Path branch n (m + 1)) → + (slots : Slots branch n → Fin t → MixedSupport.Slot) → + H (subtreeSlots p slots) ≃ₗ[F2] H (nodeSlots slots (upperNode p)) + | _, _, .refl _, _ => LinearEquiv.refl F2 _ + | _, _, .step i p, slots => scalarEquiv p (childSlots slots i) + +def rowIndexEquiv (rows : Nat → Nat) : {n m : Nat} → + (p : Path branch n (m + 1)) → + Fin (rows (m + 1)) ≃ Fin (rows (Nodes.height (upperNode p))) + | _, _, .refl _ => Equiv.refl _ + | _, _, .step _ p => rowIndexEquiv rows p + +def directionEquiv (rows : Nat → Nat) : {n m : Nat} → + (p : Path branch n (m + 1)) → + BucketSampler.Direction (rows (m + 1)) ≃ + BucketSampler.Direction (rows (Nodes.height (upperNode p))) + | _, _, .refl _ => Equiv.refl _ + | _, _, .step _ p => directionEquiv rows p + +def rowEquiv (rows : Nat → Nat) : {n m : Nat} → + (p : Path branch n (m + 1)) → + (slots : Slots branch n → Fin t → MixedSupport.Slot) → + (Fin (rows (m + 1)) → H (subtreeSlots p slots)) ≃ₗ[F2] + (Fin (rows (Nodes.height (upperNode p))) → H (nodeSlots slots (upperNode p))) + | _, _, .refl _, _ => LinearEquiv.refl F2 _ + | _, _, .step i p, slots => rowEquiv rows p (childSlots slots i) + +theorem directionEquiv_apply (rows : Nat → Nat) : + {n m : Nat} → (p : Path branch n (m + 1)) → + (a : BucketSampler.Direction (rows (m + 1))) → (i : Fin (rows (m + 1))) → + (directionEquiv rows p a).val (rowIndexEquiv rows p i) = a.val i + | _, _, .refl _, _, _ => rfl + | _, _, .step _ p, a, i => directionEquiv_apply rows p a i + +theorem rowEquiv_apply (rows : Nat → Nat) : + {n m : Nat} → (p : Path branch n (m + 1)) → + (slots : Slots branch n → Fin t → MixedSupport.Slot) → + (S : Fin (rows (m + 1)) → H (subtreeSlots p slots)) → + (i : Fin (rows (m + 1))) → + rowEquiv rows p slots S (rowIndexEquiv rows p i) = scalarEquiv p slots (S i) + | _, _, .refl _, _, _, _ => rfl + | _, _, .step i p, slots, S, j => rowEquiv_apply rows p (childSlots slots i) S j + +theorem pivot_transport (rows : Nat → Nat) : + {n m : Nat} → (p : Path branch n (m + 1)) → + (a : BucketSampler.Direction (rows (m + 1))) → + rowIndexEquiv rows p (LowerDirectionFiber.pivot a) = + LowerDirectionFiber.pivot (directionEquiv rows p a) + | _, _, .refl _, _ => rfl + | _, _, .step _ p, a => pivot_transport rows p a + +theorem rowEquiv_selectedRows (rows : Nat → Nat) : + {n m : Nat} → (p : Path branch n (m + 1)) → + (slots : Slots branch n → Fin t → MixedSupport.Slot) → + (arrays : Arrays slots rows) → + rowEquiv rows p slots (SelectedArrayReplacement.selectedRows rows p slots arrays) = + arrays (upperNode p) + | _, _, .refl _, _, _ => rfl + | _, _, .step i p, slots, arrays => + rowEquiv_selectedRows rows p (childSlots slots i) (fun node => arrays (.inr (i, node))) + +theorem replace_eq_update (rows : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) (arrays : Arrays slots rows) + (fresh : Fin (rows (m + 1)) → H (subtreeSlots p slots)) : + SelectedArrayReplacement.replace rows p slots arrays fresh = + Function.update arrays (upperNode p) (rowEquiv rows p slots fresh) := by + funext node + by_cases hnode : node = upperNode p + · subst node + rw [Function.update_self] + have h := rowEquiv_selectedRows rows p slots + (SelectedArrayReplacement.replace rows p slots arrays fresh) + rw [SelectedArrayReplacement.selectedRows_replace] at h + exact h.symm + · rw [Function.update_of_ne hnode] + exact SelectedArrayReplacement.replace_outside rows p slots arrays fresh node hnode + +theorem rowEquiv_replace (rows : Nat → Nat) : + {n m : Nat} → (p : Path branch n (m + 1)) → + (slots : Slots branch n → Fin t → MixedSupport.Slot) → + (a : BucketSampler.Direction (rows (m + 1))) → + (S : Fin (rows (m + 1)) → H (subtreeSlots p slots)) → + (fresh : H (subtreeSlots p slots)) → + rowEquiv rows p slots (LowerDirectionFiber.replace a S fresh) = + LowerDirectionFiber.replace (directionEquiv rows p a) + (rowEquiv rows p slots S) (scalarEquiv p slots fresh) + | _, _, .refl _, _, _, _, _ => rfl + | _, _, .step i p, slots, a, S, fresh => + rowEquiv_replace rows p (childSlots slots i) a S fresh + +theorem replace_fiber_eq_update (rows : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) (arrays : Arrays slots rows) + (a : BucketSampler.Direction (rows (m + 1))) (fresh : H (subtreeSlots p slots)) : + SelectedArrayReplacement.replace rows p slots arrays + (LowerDirectionFiber.replace a + (SelectedArrayReplacement.selectedRows rows p slots arrays) fresh) = + Function.update arrays (upperNode p) + (LowerDirectionFiber.replace (directionEquiv rows p a) + (arrays (upperNode p)) (scalarEquiv p slots fresh)) := by + rw [replace_eq_update, rowEquiv_replace, rowEquiv_selectedRows] + +end +end PerfectCompleteness.LowerCutNodeCoordinates + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerCutPairBackground.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerCutPairBackground.lean new file mode 100644 index 0000000000000000000000000000000000000000..e7ef95c285072388e745b27899aebedbd291f49d --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerCutPairBackground.lean @@ -0,0 +1,298 @@ +import OAI.Computability.PerfectCompleteness.Algebra.HierarchicalMatrixTable +import OAI.Computability.PerfectCompleteness.Decoding.LowerCutNodeCoordinates +import OAI.Computability.PerfectCompleteness.Decoding.LowerCutPairLemmas +import OAI.Computability.PerfectCompleteness.Decoding.LowerCutRowsLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.LowerCutPairBackground + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open WholeCutGrouping +open UniqueGamesTheorem.Foundations.Games +open scoped Classical + +abbrev F2 := ZMod 2 + +noncomputable section + +variable {branch : Nat → Nat} {n m t : Nat} + (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + +abbrev Complement := LowerCutCallSplit.Complement rows repeats p slots +abbrev NativeRows := LowerCutPair.NativeRows rows p slots +abbrev NativeMatrix := LowerCutPair.NativeMatrix rows p slots + +abbrev Observation := Complement rows repeats p slots × + (NativeRows rows p slots × H (cutSlots p slots)) + +def splitObservation : + (CutChildGrouping.Assembled (C := LowerCutPair.Calls rows repeats p) + (cutSlots p slots) rows × H (cutSlots p slots)) →ₗ[F2] + Observation rows repeats p slots where + toFun z := + ((LowerCutCallSplit.splitAssembled rows repeats p slots z.1).1, + ((LowerCutCallSplit.splitAssembled rows repeats p slots z.1).2, z.2)) + map_add' _ _ := rfl + map_smul' _ _ := rfl + +theorem splitObservation_surjective : + Function.Surjective (splitObservation rows repeats p slots) := by + rintro ⟨c, S, h⟩ + obtain ⟨record, hrecord⟩ := + LowerCutCallSplit.splitAssembled_surjective rows repeats p slots (c, S) + refine ⟨(record, h), ?_⟩ + change ((LowerCutCallSplit.splitAssembled rows repeats p slots record).1, + ((LowerCutCallSplit.splitAssembled rows repeats p slots record).2, h)) = (c, S, h) + rw [hrecord] + +def observe (raw : LowerCutPair.Raw rows repeats p slots) : + Observation rows repeats p slots := + splitObservation rows repeats p slots (CutCallExtension.observe (cutSlots p slots) rows raw) + +theorem observe_law : + (CutChildGrouping.rawLaw (C := Option (LowerCutPair.Calls rows repeats p)) + (cutSlots p slots) rows).pushforward (observe rows repeats p slots) = + (FiniteDistribution.uniform (Complement rows repeats p slots)).product + ((FiniteDistribution.uniform (NativeRows rows p slots)).product + (FiniteDistribution.uniform (H (cutSlots p slots)))) := by + change (CutChildGrouping.rawLaw (C := Option (LowerCutPair.Calls rows repeats p)) + (cutSlots p slots) rows).pushforward + (fun raw => splitObservation rows repeats p slots + (CutCallExtension.observe (cutSlots p slots) rows raw)) = _ + rw [← FiniteDistribution.pushforward_comp, CutCallExtension.observe_law, + WholeCutSampler.uniform_product, + UniformLinearImage.uniform_pushforward_linearMap + (splitObservation rows repeats p slots) (splitObservation_surjective rows repeats p slots)] + rw [WholeCutSampler.uniform_product, WholeCutSampler.uniform_product] + +@[simp] theorem observe_rows (exterior : Exterior rows repeats p slots) + (raw : LowerCutPair.Raw rows repeats p slots) : + (observe rows repeats p slots raw).2.1 = + SelectedArrayReplacement.selectedRows rows p slots + (LowerCutPair.first rows repeats p slots exterior raw) := by + exact (LowerCutRows.selectedRows_reconstruct_eq rows repeats p slots exterior _).symm + +@[simp] theorem observe_fresh (raw : LowerCutPair.Raw rows repeats p slots) : + (observe rows repeats p slots raw).2.2 = LowerCutPair.fresh rows repeats p slots raw := rfl + +def rowPair (exterior : Exterior rows repeats p slots) + (a : BucketSampler.Direction (rows (m + 1))) + (raw : LowerCutPair.Raw rows repeats p slots) : + Complement rows repeats p slots × (NativeRows rows p slots × NativeRows rows p slots) := + ((observe rows repeats p slots raw).1, + LowerCutPair.selectedPair rows repeats p slots exterior a raw) + +theorem rowPair_law (exterior : Exterior rows repeats p slots) + (a : BucketSampler.Direction (rows (m + 1))) : + (CutChildGrouping.rawLaw (C := Option (LowerCutPair.Calls rows repeats p)) + (cutSlots p slots) rows).pushforward (rowPair rows repeats p slots exterior a) = + (FiniteDistribution.uniform (Complement rows repeats p slots)).product + (LowerDirectionFiber.fiberPairLaw (H := H (cutSlots p slots)) a) := by + have h := congrArg + (fun μ : FiniteDistribution (Observation rows repeats p slots) => μ.pushforward + (fun z => (z.1, (z.2.1, LowerDirectionFiber.replace a z.2.1 z.2.2)))) + (observe_law rows repeats p slots) + rw [FiniteDistribution.pushforward_comp] at h + have hp := FiniteDistribution.product_pushforward + (FiniteDistribution.uniform (Complement rows repeats p slots)) + ((FiniteDistribution.uniform (NativeRows rows p slots)).product + (FiniteDistribution.uniform (H (cutSlots p slots)))) + (id : Complement rows repeats p slots → Complement rows repeats p slots) + (fun z => (z.1, LowerDirectionFiber.replace a z.1 z.2)) + simp only [FiniteDistribution.pushforward_id, id_eq, LowerDirectionFiber.two_copy_law] at hp + have hfinal := h.trans hp + change (CutChildGrouping.rawLaw (C := Option (LowerCutPair.Calls rows repeats p)) + (cutSlots p slots) rows).pushforward (fun raw => + ((observe rows repeats p slots raw).1, + (SelectedArrayReplacement.selectedRows rows p slots + (LowerCutPair.first rows repeats p slots exterior raw), + SelectedArrayReplacement.selectedRows rows p slots + (LowerCutPair.second rows repeats p slots exterior a raw)))) = _ + simpa only [LowerCutPair.selected_second, + observe_rows rows repeats p slots exterior, observe_fresh] using hfinal + +attribute [local instance] UniqueGamesTheorem.Appendix.RankLevelFilter.linearMapFintype + +def matrixPair (exterior : Exterior rows repeats p slots) + (a : BucketSampler.Direction (rows (m + 1))) + (raw : LowerCutPair.Raw rows repeats p slots) : + Complement rows repeats p slots × (NativeMatrix rows p slots × NativeMatrix rows p slots) := + ((observe rows repeats p slots raw).1, + LowerCutPair.matrixPair rows repeats p slots exterior a raw) + +theorem matrixPair_law (exterior : Exterior rows repeats p slots) + (a : BucketSampler.Direction (rows (m + 1))) : + (CutChildGrouping.rawLaw (C := Option (LowerCutPair.Calls rows repeats p)) + (cutSlots p slots) rows).pushforward (matrixPair rows repeats p slots exterior a) = + (FiniteDistribution.uniform (Complement rows repeats p slots)).product + (((FiniteDistribution.uniform (NativeMatrix rows p slots)).product + (FiniteDistribution.uniform (H (cutSlots p slots)))).pushforward + (fun z => (z.1, EvaluationMatrix.shift (H (cutSlots p slots)) z.1 a.val z.2))) := by + have h := congrArg + (fun μ : FiniteDistribution + (Complement rows repeats p slots × (NativeRows rows p slots × NativeRows rows p slots)) => + μ.pushforward (fun z => (z.1, + (EvaluationMatrix.ofRows (H (cutSlots p slots)) z.2.1, + EvaluationMatrix.ofRows (H (cutSlots p slots)) z.2.2)))) + (rowPair_law rows repeats p slots exterior a) + rw [FiniteDistribution.pushforward_comp] at h + have hp := FiniteDistribution.product_pushforward + (FiniteDistribution.uniform (Complement rows repeats p slots)) + (LowerDirectionFiber.fiberPairLaw (H := H (cutSlots p slots)) a) + (id : Complement rows repeats p slots → Complement rows repeats p slots) + (fun z => (EvaluationMatrix.ofRows (H (cutSlots p slots)) z.1, + EvaluationMatrix.ofRows (H (cutSlots p slots)) z.2)) + simp only [FiniteDistribution.pushforward_id, id_eq, LowerDirectionFiber.matrix_pair_law] at hp + exact h.trans hp + +def backgroundArrays (exterior : Exterior rows repeats p slots) + (c : Complement rows repeats p slots) : Arrays slots rows := + LowerCutAssembled.reconstruct rows repeats p slots exterior + (LowerCutCallSplit.merge rows repeats p slots c 0) + +def installRows (exterior : Exterior rows repeats p slots) + (c : Complement rows repeats p slots) (S : NativeRows rows p slots) : Arrays slots rows := + SelectedArrayReplacement.replace rows p slots + (backgroundArrays rows repeats p slots exterior c) S + +theorem reconstruct_merge (exterior : Exterior rows repeats p slots) + (c : Complement rows repeats p slots) (S : NativeRows rows p slots) : + LowerCutAssembled.reconstruct rows repeats p slots exterior + (LowerCutCallSplit.merge rows repeats p slots c S) = + installRows rows repeats p slots exterior c S := by + have h := LowerCutAssembled.reconstruct_congr_replace rows repeats p slots exterior + (LowerCutCallSplit.merge rows repeats p slots c 0) + (LowerCutCallSplit.merge rows repeats p slots c S) + (fun call hcall => + (LowerCutCallSplit.merge_otherCall rows repeats p slots c S ⟨call, hcall⟩).trans + (LowerCutCallSplit.merge_otherCall rows repeats p slots c 0 ⟨call, hcall⟩).symm) rfl + rw [LowerCutCallSplit.selectRows_merge] at h + exact h + +theorem first_eq_installRows (exterior : Exterior rows repeats p slots) + (raw : LowerCutPair.Raw rows repeats p slots) : + LowerCutPair.first rows repeats p slots exterior raw = + installRows rows repeats p slots exterior (observe rows repeats p slots raw).1 + (SelectedArrayReplacement.selectedRows rows p slots + (LowerCutPair.first rows repeats p slots exterior raw)) := by + rw [← observe_rows rows repeats p slots exterior] + change LowerCutRows.reconstruct rows repeats p slots exterior + (CutCallExtension.original (cutSlots p slots) rows raw) = + installRows rows repeats p slots exterior + (LowerCutCallSplit.splitAssembled rows repeats p slots + (CutChildGrouping.assemble (cutSlots p slots) rows + (CutCallExtension.original (cutSlots p slots) rows raw))).1 + (LowerCutCallSplit.splitAssembled rows repeats p slots + (CutChildGrouping.assemble (cutSlots p slots) rows + (CutCallExtension.original (cutSlots p slots) rows raw))).2 + rw [← LowerCutAssembled.reconstruct_assemble, ← reconstruct_merge, + LowerCutCallSplit.merge_split] + +private theorem replace_replace (arrays : Arrays slots rows) + (S T : NativeRows rows p slots) : + SelectedArrayReplacement.replace rows p slots + (SelectedArrayReplacement.replace rows p slots arrays S) T = + SelectedArrayReplacement.replace rows p slots arrays T := by + simp only [LowerCutNodeCoordinates.replace_eq_update] + funext node + by_cases hnode : node = WholeArrayInteriorExterior.upperNode p + · subst node + simp only [Function.update_self] + · simp only [Function.update_of_ne hnode] + +theorem second_eq_installRows (exterior : Exterior rows repeats p slots) + (a : BucketSampler.Direction (rows (m + 1))) + (raw : LowerCutPair.Raw rows repeats p slots) : + LowerCutPair.second rows repeats p slots exterior a raw = + installRows rows repeats p slots exterior (observe rows repeats p slots raw).1 + (SelectedArrayReplacement.selectedRows rows p slots + (LowerCutPair.second rows repeats p slots exterior a raw)) := by + rw [LowerCutPair.selected_second] + exact (congrArg + (fun arrays => SelectedArrayReplacement.replace rows p slots arrays + (LowerDirectionFiber.replace a + (SelectedArrayReplacement.selectedRows rows p slots + (LowerCutPair.first rows repeats p slots exterior raw)) + (LowerCutPair.fresh rows repeats p slots raw))) + (first_eq_installRows rows repeats p slots exterior raw)).trans + (replace_replace rows p slots _ _ _) + +def installMatrix (exterior : Exterior rows repeats p slots) + (c : Complement rows repeats p slots) (X : NativeMatrix rows p slots) : Arrays slots rows := + installRows rows repeats p slots exterior c (EvaluationMatrix.rows (H (cutSlots p slots)) X) + +theorem arraysPair_eq (exterior : Exterior rows repeats p slots) + (a : BucketSampler.Direction (rows (m + 1))) + (raw : LowerCutPair.Raw rows repeats p slots) : + LowerCutPair.arraysPair rows repeats p slots exterior a raw = + (installMatrix rows repeats p slots exterior (matrixPair rows repeats p slots exterior a raw).1 + (matrixPair rows repeats p slots exterior a raw).2.1, + installMatrix rows repeats p slots exterior (matrixPair rows repeats p slots exterior a raw).1 + (matrixPair rows repeats p slots exterior a raw).2.2) := by + simp only [matrixPair, LowerCutPair.matrixPair, LowerCutPair.selectedPair, + installMatrix, EvaluationMatrix.rows_ofRows] + exact Prod.ext (first_eq_installRows rows repeats p slots exterior raw) + (second_eq_installRows rows repeats p slots exterior a raw) + +theorem arraysPair_law (exterior : Exterior rows repeats p slots) + (a : BucketSampler.Direction (rows (m + 1))) : + (CutChildGrouping.rawLaw (C := Option (LowerCutPair.Calls rows repeats p)) + (cutSlots p slots) rows).pushforward (LowerCutPair.arraysPair rows repeats p slots exterior a) = + ((FiniteDistribution.uniform (Complement rows repeats p slots)).product + (((FiniteDistribution.uniform (NativeMatrix rows p slots)).product + (FiniteDistribution.uniform (H (cutSlots p slots)))).pushforward + (fun z => (z.1, EvaluationMatrix.shift (H (cutSlots p slots)) z.1 a.val z.2)))).pushforward + (fun z => (installMatrix rows repeats p slots exterior z.1 z.2.1, + installMatrix rows repeats p slots exterior z.1 z.2.2)) := by + have h := congrArg + (fun μ : FiniteDistribution + (Complement rows repeats p slots × (NativeMatrix rows p slots × NativeMatrix rows p slots)) => + μ.pushforward (fun z => (installMatrix rows repeats p slots exterior z.1 z.2.1, + installMatrix rows repeats p slots exterior z.1 z.2.2))) + (matrixPair_law rows repeats p slots exterior a) + rw [FiniteDistribution.pushforward_comp] at h + simpa only [← arraysPair_eq] using h + +theorem installMatrix_eq_update (exterior : Exterior rows repeats p slots) + (c : Complement rows repeats p slots) (X : NativeMatrix rows p slots) : + installMatrix rows repeats p slots exterior c X = + Function.update (backgroundArrays rows repeats p slots exterior c) + (WholeArrayInteriorExterior.upperNode p) + (LowerCutNodeCoordinates.rowEquiv rows p slots + (EvaluationMatrix.rows (H (cutSlots p slots)) X)) := + LowerCutNodeCoordinates.replace_eq_update rows p slots _ _ + +theorem installMatrix_outside (exterior : Exterior rows repeats p slots) + (c : Complement rows repeats p slots) (X : NativeMatrix rows p slots) + (node : Nodes branch n) (hne : node ≠ WholeArrayInteriorExterior.upperNode p) : + installMatrix rows repeats p slots exterior c X node = + backgroundArrays rows repeats p slots exterior c node := + SelectedArrayReplacement.replace_outside rows p slots _ _ node hne + +theorem backgroundOf_installMatrix (exterior : Exterior rows repeats p slots) + (c : Complement rows repeats p slots) (X : NativeMatrix rows p slots) : + HierarchicalMatrixTable.backgroundOf slots (WholeArrayInteriorExterior.upperNode p) + (installMatrix rows repeats p slots exterior c X) = + HierarchicalMatrixTable.backgroundOf slots (WholeArrayInteriorExterior.upperNode p) + (backgroundArrays rows repeats p slots exterior c) := by + funext node + exact installMatrix_outside rows repeats p slots exterior c X node.val node.property + +theorem upperMatrix_installMatrix (exterior : Exterior rows repeats p slots) + (c : Complement rows repeats p slots) (X : NativeMatrix rows p slots) + (upper : Nodes branch n) (hne : upper ≠ WholeArrayInteriorExterior.upperNode p) : + NodeEmbedding.matrix (installMatrix rows repeats p slots exterior c X) upper = + NodeEmbedding.matrix (backgroundArrays rows repeats p slots exterior c) upper := by + unfold NodeEmbedding.matrix NodeEmbedding.embeddedRows + rw [installMatrix_outside rows repeats p slots exterior c X upper hne] + +end +end PerfectCompleteness.LowerCutPairBackground + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerCutPairLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerCutPairLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..deb55fb64d8ceae1e5c11578be509197803a280f --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerCutPairLemmas.lean @@ -0,0 +1,285 @@ +import OAI.Computability.PerfectCompleteness.Algebra.ChildBilinearCollisionTransfer +import OAI.Computability.PerfectCompleteness.Decoding.ChildAssemblyProjection +import OAI.Computability.PerfectCompleteness.Decoding.LowerCutNodeCoordinates +import OAI.Computability.PerfectCompleteness.Decoding.LowerCutRowsLemmas +import OAI.Computability.PerfectCompleteness.Decoding.LowerDirectionFiber +import OAI.Computability.PerfectCompleteness.Foundations.CutCallExtension +import OAI.Computability.PerfectCompleteness.Foundations.MultiplicationFormInjectiveLemmas +import OAI.Computability.PerfectCompleteness.Machines.LowerCutDecoderInput +import OAI.Computability.PerfectCompleteness.Machines.OwnInputReferenceLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.LowerCutPair + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open WholeCutGrouping +open UniqueGamesTheorem.Foundations.Games +open scoped Classical + +abbrev F2 := ZMod 2 + +noncomputable section + +variable {branch : Nat → Nat} {n m t : Nat} + (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + +abbrev Calls := WholeCutCalls.Index rows repeats p +abbrev Raw := CutCallExtension.Extended (C := Calls rows repeats p) (cutSlots p slots) rows +abbrev NativeRows := Fin (rows (m + 1)) → H (cutSlots p slots) +abbrev NativeMatrix := Module.Dual F2 (H (cutSlots p slots)) →ₗ[F2] (Fin (rows (m + 1)) → F2) + +def first (exterior : Exterior rows repeats p slots) (raw : Raw rows repeats p slots) : + Arrays slots rows := + LowerCutRows.reconstruct rows repeats p slots exterior + (CutCallExtension.original (cutSlots p slots) rows raw) + +def fresh (raw : Raw rows repeats p slots) : H (cutSlots p slots) := + CutCallExtension.fresh (cutSlots p slots) rows raw + +def second (exterior : Exterior rows repeats p slots) + (a : BucketSampler.Direction (rows (m + 1))) (raw : Raw rows repeats p slots) : + Arrays slots rows := + SelectedArrayReplacement.replace rows p slots (first rows repeats p slots exterior raw) + (LowerDirectionFiber.replace a + (SelectedArrayReplacement.selectedRows rows p slots (first rows repeats p slots exterior raw)) + (fresh rows repeats p slots raw)) + +def arraysPair (exterior : Exterior rows repeats p slots) + (a : BucketSampler.Direction (rows (m + 1))) (raw : Raw rows repeats p slots) : + Arrays slots rows × Arrays slots rows := + (first rows repeats p slots exterior raw, second rows repeats p slots exterior a raw) + +@[simp] theorem selected_second (exterior : Exterior rows repeats p slots) + (a : BucketSampler.Direction (rows (m + 1))) (raw : Raw rows repeats p slots) : + SelectedArrayReplacement.selectedRows rows p slots (second rows repeats p slots exterior a raw) = + LowerDirectionFiber.replace a + (SelectedArrayReplacement.selectedRows rows p slots (first rows repeats p slots exterior raw)) + (fresh rows repeats p slots raw) := + SelectedArrayReplacement.selectedRows_replace rows p slots _ _ + +theorem second_outside (exterior : Exterior rows repeats p slots) + (a : BucketSampler.Direction (rows (m + 1))) (raw : Raw rows repeats p slots) + (node : Nodes branch n) (hne : node ≠ WholeArrayInteriorExterior.upperNode p) : + second rows repeats p slots exterior a raw node = + first rows repeats p slots exterior raw node := + SelectedArrayReplacement.replace_outside rows p slots _ _ node hne + +theorem selected_quotient (exterior : Exterior rows repeats p slots) + (a : BucketSampler.Direction (rows (m + 1))) (raw : Raw rows repeats p slots) : + LowerDirectionFiber.quotientQuery (H (cutSlots p slots)) a + (SelectedArrayReplacement.selectedRows rows p slots + (second rows repeats p slots exterior a raw)) = + LowerDirectionFiber.quotientQuery (H (cutSlots p slots)) a + (SelectedArrayReplacement.selectedRows rows p slots + (first rows repeats p slots exterior raw)) := by + rw [selected_second] + exact LowerDirectionFiber.quotientQuery_replace _ _ _ _ + +def readRowsFresh (exterior : Exterior rows repeats p slots) (raw : Raw rows repeats p slots) : + NativeRows rows p slots × H (cutSlots p slots) := + (SelectedArrayReplacement.selectedRows rows p slots (first rows repeats p slots exterior raw), + fresh rows repeats p slots raw) + +def selectPair : + (CutChildGrouping.Assembled (C := Calls rows repeats p) (cutSlots p slots) rows × + H (cutSlots p slots)) →ₗ[F2] (NativeRows rows p slots × H (cutSlots p slots)) := + (LowerCutRows.selectRows rows repeats p slots).prodMap LinearMap.id + +theorem selectPair_surjective : Function.Surjective (selectPair rows repeats p slots) := by + rintro ⟨S, h⟩ + obtain ⟨record, hrecord⟩ := LowerCutRows.selectRows_surjective rows repeats p slots S + exact ⟨(record, h), Prod.ext hrecord rfl⟩ + +@[simp] theorem readRowsFresh_eq (exterior : Exterior rows repeats p slots) + (raw : Raw rows repeats p slots) : + readRowsFresh rows repeats p slots exterior raw = + selectPair rows repeats p slots + (CutCallExtension.observe (cutSlots p slots) rows raw) := by + apply Prod.ext + · exact LowerCutRows.selectedRows_reconstruct_eq rows repeats p slots exterior _ + · rfl + +theorem readRowsFresh_law (exterior : Exterior rows repeats p slots) : + (CutChildGrouping.rawLaw (C := Option (Calls rows repeats p)) (cutSlots p slots) rows).pushforward + (readRowsFresh rows repeats p slots exterior) = + (FiniteDistribution.uniform (NativeRows rows p slots)).product + (FiniteDistribution.uniform (H (cutSlots p slots))) := by + change (CutChildGrouping.rawLaw (C := Option (Calls rows repeats p)) (cutSlots p slots) rows).pushforward + (fun raw => readRowsFresh rows repeats p slots exterior raw) = _ + simp only [readRowsFresh_eq] + rw [← FiniteDistribution.pushforward_comp, CutCallExtension.observe_law, + WholeCutSampler.uniform_product, + UniformLinearImage.uniform_pushforward_linearMap + (selectPair rows repeats p slots) (selectPair_surjective rows repeats p slots)] + exact WholeCutSampler.uniform_product.symm + +def selectedPair (exterior : Exterior rows repeats p slots) + (a : BucketSampler.Direction (rows (m + 1))) (raw : Raw rows repeats p slots) : + NativeRows rows p slots × NativeRows rows p slots := + (SelectedArrayReplacement.selectedRows rows p slots (first rows repeats p slots exterior raw), + SelectedArrayReplacement.selectedRows rows p slots (second rows repeats p slots exterior a raw)) + +theorem selectedPair_law (exterior : Exterior rows repeats p slots) + (a : BucketSampler.Direction (rows (m + 1))) : + (CutChildGrouping.rawLaw (C := Option (Calls rows repeats p)) (cutSlots p slots) rows).pushforward + (selectedPair rows repeats p slots exterior a) = + LowerDirectionFiber.fiberPairLaw (H := H (cutSlots p slots)) a := by + have h := congrArg + (fun μ : FiniteDistribution (NativeRows rows p slots × H (cutSlots p slots)) => + μ.pushforward (fun z => (z.1, LowerDirectionFiber.replace a z.1 z.2))) + (readRowsFresh_law rows repeats p slots exterior) + rw [FiniteDistribution.pushforward_comp, LowerDirectionFiber.two_copy_law] at h + change (CutChildGrouping.rawLaw (C := Option (Calls rows repeats p)) (cutSlots p slots) rows).pushforward + (fun raw => + (SelectedArrayReplacement.selectedRows rows p slots (first rows repeats p slots exterior raw), + SelectedArrayReplacement.selectedRows rows p slots (second rows repeats p slots exterior a raw))) = _ + simpa only [readRowsFresh, selected_second] using h + +def matrixPair (exterior : Exterior rows repeats p slots) + (a : BucketSampler.Direction (rows (m + 1))) (raw : Raw rows repeats p slots) : + NativeMatrix rows p slots × NativeMatrix rows p slots := + let z := selectedPair rows repeats p slots exterior a raw + (EvaluationMatrix.ofRows (H (cutSlots p slots)) z.1, + EvaluationMatrix.ofRows (H (cutSlots p slots)) z.2) + +local instance nativeMatrixFintype : Fintype (NativeMatrix rows p slots) := + Fintype.ofEquiv (NativeRows rows p slots) (EvaluationMatrix.rowsEquiv (H (cutSlots p slots))).symm + +theorem matrixPair_law (exterior : Exterior rows repeats p slots) + (a : BucketSampler.Direction (rows (m + 1))) : + (CutChildGrouping.rawLaw (C := Option (Calls rows repeats p)) (cutSlots p slots) rows).pushforward + (matrixPair rows repeats p slots exterior a) = + ((FiniteDistribution.uniform (NativeMatrix rows p slots)).product + (FiniteDistribution.uniform (H (cutSlots p slots)))).pushforward + (fun z => (z.1, EvaluationMatrix.shift (H (cutSlots p slots)) z.1 a.val z.2)) := by + have h := congrArg + (fun μ : FiniteDistribution (NativeRows rows p slots × NativeRows rows p slots) => + μ.pushforward (fun z => (EvaluationMatrix.ofRows (H (cutSlots p slots)) z.1, + EvaluationMatrix.ofRows (H (cutSlots p slots)) z.2))) + (selectedPair_law rows repeats p slots exterior a) + rw [FiniteDistribution.pushforward_comp, LowerDirectionFiber.matrix_pair_law] at h + exact h + +end +end PerfectCompleteness.LowerCutPair + +end + +section + +namespace PerfectCompleteness.LowerCutDecoderForm + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open WholeCutGrouping + +variable {branch rows repeats : Nat → Nat} {n height t : Nat} + (path : Path branch n (height + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (upper : Nodes branch n) (lowerLevel : Nat) + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) + (hnode : WholeArrayInteriorExterior.upperNode path = + HierarchicalLeftDecoder.LowerNode upper lowerLevel d) + +def spaceEquiv : H (cutSlots path slots) ≃ₗ[ZMod 2] + HierarchicalDecoderTables.LowerH slots upper lowerLevel d := + (LowerCutNodeCoordinates.scalarEquiv path slots).trans (by + rw [hnode]) + +def form (answer : HierarchicalDecoderTables.Answer slots upper lowerLevel d) : + ChildBilinearCollisionTransfer.ParentForm (cutSlots path slots) where + toFun f := (OddListExtraction.multiplicationForm + (HierarchicalDecoderTables.LowerH slots upper lowerLevel d) answer + (spaceEquiv path slots upper lowerLevel d hnode f)).comp + (spaceEquiv path slots upper lowerLevel d hnode).toLinearMap + map_add' f g := by + ext h + simp only [LinearMap.comp_apply, map_add, LinearMap.add_apply] + map_smul' c f := by + ext h + simp only [LinearMap.comp_apply, map_smul, + LinearMap.smul_apply, RingHom.id_apply] + +@[simp] theorem form_apply + (answer : HierarchicalDecoderTables.Answer slots upper lowerLevel d) + (f g : H (cutSlots path slots)) : + form path slots upper lowerLevel d hnode answer f g = + OddListExtraction.multiplicationForm + (HierarchicalDecoderTables.LowerH slots upper lowerLevel d) answer + (spaceEquiv path slots upper lowerLevel d hnode f) + (spaceEquiv path slots upper lowerLevel d hnode g) := rfl + +theorem form_injective : + Function.Injective (form path slots upper lowerLevel d hnode) := by + intro answer answer' hform + apply MultiplicationFormInjective.multiplicationForm_injective + (HierarchicalDecoderTables.LowerH slots upper lowerLevel d) + ext f g + obtain ⟨f', rfl⟩ := (spaceEquiv path slots upper lowerLevel d hnode).surjective f + obtain ⟨g', rfl⟩ := (spaceEquiv path slots upper lowerLevel d hnode).surjective g + exact congrArg (fun F : ChildBilinearCollisionTransfer.ParentForm + (cutSlots path slots) => F f' g') hform + +variable (hbranch : ∀ k < n, 0 < branch k) {adviceRows : Nat} + (A : ManyGoodRows.RowMap (Block rows upper) adviceRows) + (table : HierarchicalAllDecoderTables.Input (rows := rows) + slots upper lowerLevel adviceRows → HierarchicalAllDecoderTables.UpperAnswer slots upper) + (cutoff : Nat) + +def answer (arrays : Arrays slots rows) : + Option (HierarchicalDecoderTables.Answer slots upper lowerLevel d) := + HierarchicalDecoderTables.decode slots upper lowerLevel hbranch d cutoff + (table (LowerCutDecoderInput.actualInput slots upper lowerLevel arrays A)) + +def readForm (arrays : Arrays slots rows) : + Option (ChildBilinearCollisionTransfer.ParentForm (cutSlots path slots)) := + (answer slots upper lowerLevel d hbranch A table cutoff arrays).map + (form path slots upper lowerLevel d hnode) + +def first (exterior : Exterior rows repeats path slots) + (raw : LowerCutPair.Raw rows repeats path slots) : + Option (ChildBilinearCollisionTransfer.ParentForm (cutSlots path slots)) := + readForm path slots upper lowerLevel d hnode hbranch A table cutoff + (LowerCutPair.first rows repeats path slots exterior raw) + +def second (exterior : Exterior rows repeats path slots) + (direction : BucketSampler.Direction (rows (height + 1))) + (raw : LowerCutPair.Raw rows repeats path slots) : + Option (ChildBilinearCollisionTransfer.ParentForm (cutSlots path slots)) := + readForm path slots upper lowerLevel d hnode hbranch A table cutoff + (LowerCutPair.second rows repeats path slots exterior direction raw) + +theorem fullCollision_readForm (arrays arrays' : Arrays slots rows) : + BilinearCollisionTransfer.fullCollision + (readForm path slots upper lowerLevel d hnode hbranch A table cutoff arrays) + (readForm path slots upper lowerLevel d hnode hbranch A table cutoff arrays') = + DecoderTableCoupling.definedEqual + (answer slots upper lowerLevel d hbranch A table cutoff arrays) + (answer slots upper lowerLevel d hbranch A table cutoff arrays') := + MultiplicationFormInjective.definedEqual_map_of_injective + (form path slots upper lowerLevel d hnode) + (form_injective path slots upper lowerLevel d hnode) _ _ + +theorem fullCollision_pair (exterior : Exterior rows repeats path slots) + (direction : BucketSampler.Direction (rows (height + 1))) + (raw : LowerCutPair.Raw rows repeats path slots) : + BilinearCollisionTransfer.fullCollision + (first path slots upper lowerLevel d hnode hbranch A table cutoff exterior raw) + (second path slots upper lowerLevel d hnode hbranch A table cutoff exterior direction raw) = + TwoResponseCollision.collision + (answer slots upper lowerLevel d hbranch A table cutoff) + (LowerCutPair.arraysPair rows repeats path slots exterior direction raw) := + fullCollision_readForm path slots upper lowerLevel d hnode hbranch A table cutoff _ _ + +end +end PerfectCompleteness.LowerCutDecoderForm + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerCutRowsLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerCutRowsLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..b93953cfcf95d872fd6519c48ec3348577f31f94 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerCutRowsLemmas.lean @@ -0,0 +1,456 @@ +import OAI.Computability.PerfectCompleteness.Decoding.LowerCutScalar +import OAI.Computability.PerfectCompleteness.Foundations.WholeArrayInteriorExteriorLemmas +import OAI.Computability.PerfectCompleteness.Foundations.WholeCutGrouping + +namespace OAI + +section + +namespace PerfectCompleteness.LowerCutRows + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open WholeCutGrouping +open UniqueGamesTheorem.Foundations.Games +open scoped Classical + +abbrev F2 := ZMod 2 + +noncomputable section + +variable {branch : Nat → Nat} {n m t : Nat} + +def reconstruct (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (exterior : Exterior rows repeats p slots) + (raw : CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) + (cutSlots p slots) rows) : Arrays slots rows := + WholeCutSampler.evaluate rows repeats p slots + ((splitTape rows repeats p slots).symm (exterior, raw)) + +theorem selectedRows_heq_upperNode (rows : Nat → Nat) + (p : Path branch n (m + 1)) : + ∀ (slots : Slots branch n → Fin t → MixedSupport.Slot) (arrays : Arrays slots rows), + HEq (SelectedArrayReplacement.selectedRows rows p slots arrays) + (arrays (WholeArrayInteriorExterior.upperNode p)) := by + induction n generalizing m with + | zero => cases p + | succ n ih => + cases p with + | refl => intro slots arrays; rfl + | step i p => + intro slots arrays + exact ih p (childSlots slots i) (fun node => arrays (.inr (i, node))) + +theorem selectedRows_evaluate_step (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n (m + 1)) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (tape : WholeCutSampler.Tape rows repeats (.step i p) slots) : + SelectedArrayReplacement.selectedRows rows (.step i p) slots + (WholeCutSampler.evaluate rows repeats (.step i p) slots tape) = + SelectedArrayReplacement.selectedRows rows p (childSlots slots i) + (WholeCutSampler.evaluate rows repeats p (childSlots slots i) tape.2.1) := by + rw [SelectedArrayReplacement.selectedRows_step] + apply congrArg (SelectedArrayReplacement.selectedRows rows p (childSlots slots i)) + funext node + unfold WholeCutSampler.evaluate + rw [WholeArraySampler.evaluate_selected] + rfl + +theorem selectedRows_evaluate (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) : + ∀ (slots : Slots branch n → Fin t → MixedSupport.Slot) + (tape : WholeCutSampler.Tape rows repeats p slots) (row : Fin (rows (m + 1))), + SelectedArrayReplacement.selectedRows rows p slots + (WholeCutSampler.evaluate rows repeats p slots tape) row = + (CutChildGrouping.assemble (cutSlots p slots) rows + ((splitTape rows repeats p slots tape).2)).1 + (WholeCutCalls.directRow rows repeats p row) := by + induction n generalizing m with + | zero => cases p + | succ n ih => + cases p with + | refl => intro slots tape row; rfl + | step i p => + intro slots tape row + rw [selectedRows_evaluate_step] + exact ih p (childSlots slots i) tape.2.1 row + +theorem selectedRows_reconstruct (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (exterior : Exterior rows repeats p slots) + (raw : CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) + (cutSlots p slots) rows) (row : Fin (rows (m + 1))) : + SelectedArrayReplacement.selectedRows rows p slots + (reconstruct rows repeats p slots exterior raw) row = + (CutChildGrouping.assemble (cutSlots p slots) rows raw).1 + (WholeCutCalls.directRow rows repeats p row) := by + unfold reconstruct + rw [selectedRows_evaluate, Equiv.apply_symm_apply] + +def selectRows (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + CutChildGrouping.Assembled (C := WholeCutCalls.Index rows repeats p) + (cutSlots p slots) rows →ₗ[F2] + (Fin (rows (m + 1)) → H (cutSlots p slots)) where + toFun x row := x.1 (WholeCutCalls.directRow rows repeats p row) + map_add' _ _ := rfl + map_smul' _ _ := rfl + +@[simp] theorem selectRows_apply (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (x : CutChildGrouping.Assembled (C := WholeCutCalls.Index rows repeats p) + (cutSlots p slots) rows) (row : Fin (rows (m + 1))) : + selectRows rows repeats p slots x row = + x.1 (WholeCutCalls.directRow rows repeats p row) := rfl + +theorem selectRows_surjective (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Function.Surjective (selectRows rows repeats p slots) := by + intro fresh + refine ⟨(Function.extend (WholeCutCalls.directRow rows repeats p) fresh (fun _ => 0), + fun _ _ _ => 0), ?_⟩ + funext row + exact (WholeCutCalls.directRow_injective rows repeats p).extend_apply fresh + (fun _ => 0) row + +theorem selectedRows_reconstruct_eq (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (exterior : Exterior rows repeats p slots) + (raw : CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) + (cutSlots p slots) rows) : + SelectedArrayReplacement.selectedRows rows p slots + (reconstruct rows repeats p slots exterior raw) = + selectRows rows repeats p slots + (CutChildGrouping.assemble (cutSlots p slots) rows raw) := by + funext row + exact selectedRows_reconstruct rows repeats p slots exterior raw row + +end +end PerfectCompleteness.LowerCutRows + +end + +section + +namespace PerfectCompleteness.LowerCutAssembled + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open WholeCutGrouping +open scoped Classical + +abbrev F2 := ZMod 2 + +noncomputable section + +variable {branch : Nat → Nat} {n m t : Nat} + +abbrev Assembled (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) := + CutChildGrouping.Assembled (C := WholeCutCalls.Index rows repeats p) + (cutSlots p slots) rows + +def reconstructBuckets (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (values : BucketSampler.Direction (rows n) → + TerminalCalls.TerminalIndex repeats p → H (cutSlots p slots)) + (exterior : BucketSampler.Direction (rows n) → + CutTerminalSplit.ExteriorTape F2 repeats p (LeafDomain slots)) : + Fin (rows n) → H slots := + BucketSampler.evaluate (rows n) (id : H slots → H slots) (fun direction => + LowerCutScalar.reconstruct F2 repeats p (LeafDomain slots) + (values direction) (exterior direction)) + +def reconstruct (rows repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n (m + 1)) → + (slots : Slots branch n → Fin t → MixedSupport.Slot) → + Exterior rows repeats p slots → Assembled rows repeats p slots → Arrays slots rows + | _, _, .refl _, slots, _, assembled => + WholeArraySampler.assemble slots rows assembled.1 assembled.2 + | _, _, .step i p, slots, exterior, assembled => + WholeArraySampler.assemble slots rows + (reconstructBuckets rows repeats (.step i p) slots + (fun direction terminal => assembled.1 (.inl (direction, terminal))) exterior.1) + (WholeArraySampler.childrenAt slots rows i + (reconstruct rows repeats p (childSlots slots i) exterior.2.1 + (fun call => assembled.1 (.inr call), assembled.2)) exterior.2.2) + +theorem selectedRows_reconstruct (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) : + ∀ (slots : Slots branch n → Fin t → MixedSupport.Slot) + (exterior : Exterior rows repeats p slots) (assembled : Assembled rows repeats p slots), + SelectedArrayReplacement.selectedRows rows p slots + (reconstruct rows repeats p slots exterior assembled) = + LowerCutRows.selectRows rows repeats p slots assembled := by + induction n generalizing m with + | zero => cases p + | succ n ih => + cases p with + | refl => intro slots exterior assembled; rfl + | step i p => + intro slots exterior assembled + rw [reconstruct, SelectedArrayReplacement.selectedRows_assemble_step] + exact ih p (childSlots slots i) exterior.2.1 + (fun call => assembled.1 (.inr call), assembled.2) + +theorem reconstruct_splitTape (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) : + ∀ (slots : Slots branch n → Fin t → MixedSupport.Slot) + (tape : WholeCutSampler.Tape rows repeats p slots), + reconstruct rows repeats p slots (splitTape rows repeats p slots tape).1 + (CutChildGrouping.assemble (cutSlots p slots) rows + (splitTape rows repeats p slots tape).2) = + WholeCutSampler.evaluate rows repeats p slots tape := by + induction n generalizing m with + | zero => cases p + | succ n ih => + cases p with + | refl => intro slots tape; rfl + | step i p => + intro slots tape + apply congrArg₂ (WholeArraySampler.assemble slots rows) + · apply congrArg (BucketSampler.evaluate (rows (n + 1)) (id : H slots → H slots)) + funext direction + exact LowerCutScalar.reconstruct_splitTape F2 repeats (.step i p) + (LeafDomain slots) (tape.1 direction) + · exact congrArg (fun selected : Arrays (childSlots slots i) rows => + WholeArraySampler.childrenAt slots rows i selected tape.2.2) + (ih p (childSlots slots i) tape.2.1) + +theorem reconstruct_assemble (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (exterior : Exterior rows repeats p slots) + (raw : CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) + (cutSlots p slots) rows) : + reconstruct rows repeats p slots exterior + (CutChildGrouping.assemble (cutSlots p slots) rows raw) = + LowerCutRows.reconstruct rows repeats p slots exterior raw := by + have h := reconstruct_splitTape rows repeats p slots + ((splitTape rows repeats p slots).symm (exterior, raw)) + rw [Equiv.apply_symm_apply] at h + exact h + +theorem reconstruct_congr_replace (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) : + ∀ (slots : Slots branch n → Fin t → MixedSupport.Slot) + (exterior : Exterior rows repeats p slots) + (x y : Assembled rows repeats p slots), + (∀ call, (∀ row, call ≠ WholeCutCalls.directRow rows repeats p row) → + y.1 call = x.1 call) → y.2 = x.2 → + reconstruct rows repeats p slots exterior y = + SelectedArrayReplacement.replace rows p slots + (reconstruct rows repeats p slots exterior x) + (LowerCutRows.selectRows rows repeats p slots y) := by + induction n generalizing m with + | zero => cases p + | succ n ih => + cases p with + | refl => + intro slots exterior x y hcalls harrays + change WholeArraySampler.assemble slots rows y.1 y.2 = + WholeArraySampler.assemble slots rows y.1 x.2 + rw [harrays] + | step i p => + intro slots exterior x y hcalls harrays + simp only [reconstruct, SelectedArrayReplacement.replace_assemble_step] + apply congrArg₂ (WholeArraySampler.assemble slots rows) + · unfold reconstructBuckets + apply congrArg (BucketSampler.evaluate (rows (n + 1)) (id : H slots → H slots)) + funext direction + apply congrArg (fun values => LowerCutScalar.reconstruct F2 repeats (.step i p) + (LeafDomain slots) values (exterior.1 direction)) + funext terminal + apply hcalls (.inl (direction, terminal)) + intro row h + cases h + · apply congrArg (fun selected : Arrays (childSlots slots i) rows => + WholeArraySampler.childrenAt slots rows i selected exterior.2.2) + apply ih p (childSlots slots i) exterior.2.1 + (fun call => x.1 (.inr call), x.2) + (fun call => y.1 (.inr call), y.2) + · intro call hcall + apply hcalls (.inr call) + intro row h + exact hcall row (Sum.inr.inj h) + · exact harrays + +theorem reconstruct_congr_outside (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (exterior : Exterior rows repeats p slots) (x y : Assembled rows repeats p slots) + (hcalls : ∀ call, (∀ row, call ≠ WholeCutCalls.directRow rows repeats p row) → + y.1 call = x.1 call) (harrays : y.2 = x.2) + (node : Nodes branch n) (hnode : node ≠ WholeArrayInteriorExterior.upperNode p) : + reconstruct rows repeats p slots exterior y node = + reconstruct rows repeats p slots exterior x node := by + rw [reconstruct_congr_replace rows repeats p slots exterior x y hcalls harrays] + exact SelectedArrayReplacement.replace_outside rows p slots + (reconstruct rows repeats p slots exterior x) + (LowerCutRows.selectRows rows repeats p slots y) node hnode + +end +end PerfectCompleteness.LowerCutAssembled + +end + +section + +namespace PerfectCompleteness.LowerCutCallSplit + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open WholeCutGrouping +open scoped Classical + +abbrev F2 := ZMod 2 + +noncomputable section + +variable {branch : Nat → Nat} {n m t : Nat} + (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + +abbrev OtherCall := + {q : WholeCutCalls.Index rows repeats p // + ∀ row : Fin (rows (m + 1)), q ≠ WholeCutCalls.directRow rows repeats p row} + +variable (slots : Slots branch n → Fin t → MixedSupport.Slot) + +abbrev ChildArrays := + (i : Fin (branch m)) → Arrays (childSlots (cutSlots p slots) i) rows + +abbrev Complement := + (OtherCall rows repeats p → H (cutSlots p slots)) × ChildArrays rows p slots + +abbrev NativeRows := Fin (rows (m + 1)) → H (cutSlots p slots) + +abbrev Assembled := + CutChildGrouping.Assembled (C := WholeCutCalls.Index rows repeats p) (cutSlots p slots) rows + +instance complementFintype : Fintype (Complement rows repeats p slots) := Fintype.ofFinite _ + +def complement (x : Assembled rows repeats p slots) : Complement rows repeats p slots := + (fun q => x.1 q.val, x.2) + +def splitAssembled : Assembled rows repeats p slots →ₗ[F2] + Complement rows repeats p slots × NativeRows rows p slots where + toFun x := (complement rows repeats p slots x, LowerCutRows.selectRows rows repeats p slots x) + map_add' _ _ := rfl + map_smul' _ _ := rfl + +@[simp] theorem splitAssembled_complement (x : Assembled rows repeats p slots) : + (splitAssembled rows repeats p slots x).1 = complement rows repeats p slots x := rfl + +@[simp] theorem splitAssembled_rows (x : Assembled rows repeats p slots) : + (splitAssembled rows repeats p slots x).2 = LowerCutRows.selectRows rows repeats p slots x := rfl + +@[simp] theorem complement_call (x : Assembled rows repeats p slots) + (q : OtherCall rows repeats p) : + (complement rows repeats p slots x).1 q = x.1 q.val := rfl + +@[simp] theorem complement_arrays (x : Assembled rows repeats p slots) : + (complement rows repeats p slots x).2 = x.2 := rfl + +def merge (bg : Complement rows repeats p slots) (fresh : NativeRows rows p slots) : + Assembled rows repeats p slots := + (fun q => if h : ∃ row, q = WholeCutCalls.directRow rows repeats p row then + fresh (Classical.choose h) + else bg.1 ⟨q, fun row hq => h ⟨row, hq⟩⟩, + bg.2) + +@[simp] theorem merge_directRow (bg : Complement rows repeats p slots) + (fresh : NativeRows rows p slots) (row : Fin (rows (m + 1))) : + (merge rows repeats p slots bg fresh).1 (WholeCutCalls.directRow rows repeats p row) = + fresh row := by + have hex : ∃ j, WholeCutCalls.directRow rows repeats p row = + WholeCutCalls.directRow rows repeats p j := ⟨row, rfl⟩ + change (if h : ∃ j, WholeCutCalls.directRow rows repeats p row = + WholeCutCalls.directRow rows repeats p j then fresh (Classical.choose h) else _) = fresh row + rw [dite_eq_left hex] + apply congrArg fresh + exact (WholeCutCalls.directRow_injective rows repeats p (Classical.choose_spec hex)).symm + +@[simp] theorem merge_otherCall (bg : Complement rows repeats p slots) + (fresh : NativeRows rows p slots) (q : OtherCall rows repeats p) : + (merge rows repeats p slots bg fresh).1 q.val = bg.1 q := by + have hnot : ¬ ∃ row, q.val = WholeCutCalls.directRow rows repeats p row := by + rintro ⟨row, hrow⟩ + exact q.property row hrow + simp only [merge, dite_eq_right hnot] + +@[simp] theorem merge_arrays (bg : Complement rows repeats p slots) + (fresh : NativeRows rows p slots) : + (merge rows repeats p slots bg fresh).2 = bg.2 := rfl + +@[simp] theorem split_merge (bg : Complement rows repeats p slots) + (fresh : NativeRows rows p slots) : + splitAssembled rows repeats p slots (merge rows repeats p slots bg fresh) = (bg, fresh) := by + apply Prod.ext + · apply Prod.ext + · funext q + exact merge_otherCall rows repeats p slots bg fresh q + · rfl + · funext row + exact merge_directRow rows repeats p slots bg fresh row + +@[simp] theorem merge_split (x : Assembled rows repeats p slots) : + merge rows repeats p slots (splitAssembled rows repeats p slots x).1 + (splitAssembled rows repeats p slots x).2 = x := by + apply Prod.ext + · funext q + by_cases h : ∃ row, q = WholeCutCalls.directRow rows repeats p row + · rcases h with ⟨row, rfl⟩ + exact merge_directRow rows repeats p slots _ _ row + · exact merge_otherCall rows repeats p slots _ _ ⟨q, fun row hq => h ⟨row, hq⟩⟩ + · rfl + +def splitEquiv : Assembled rows repeats p slots ≃ₗ[F2] + Complement rows repeats p slots × NativeRows rows p slots where + toFun := splitAssembled rows repeats p slots + invFun z := merge rows repeats p slots z.1 z.2 + left_inv := merge_split rows repeats p slots + right_inv z := split_merge rows repeats p slots z.1 z.2 + map_add' := (splitAssembled rows repeats p slots).map_add + map_smul' := (splitAssembled rows repeats p slots).map_smul + +@[simp] theorem splitEquiv_apply (x : Assembled rows repeats p slots) : + splitEquiv rows repeats p slots x = splitAssembled rows repeats p slots x := rfl + +@[simp] theorem splitEquiv_symm_apply + (z : Complement rows repeats p slots × NativeRows rows p slots) : + (splitEquiv rows repeats p slots).symm z = merge rows repeats p slots z.1 z.2 := rfl + +theorem splitAssembled_surjective : Function.Surjective (splitAssembled rows repeats p slots) := + (splitEquiv rows repeats p slots).surjective + +theorem splitAssembled_injective : Function.Injective (splitAssembled rows repeats p slots) := + (splitEquiv rows repeats p slots).injective + +@[simp] theorem complement_merge (bg : Complement rows repeats p slots) + (fresh : NativeRows rows p slots) : + complement rows repeats p slots (merge rows repeats p slots bg fresh) = bg := + congrArg Prod.fst (split_merge rows repeats p slots bg fresh) + +@[simp] theorem selectRows_merge (bg : Complement rows repeats p slots) + (fresh : NativeRows rows p slots) : + LowerCutRows.selectRows rows repeats p slots (merge rows repeats p slots bg fresh) = fresh := + congrArg Prod.snd (split_merge rows repeats p slots bg fresh) + +theorem complement_eq_iff (x y : Assembled rows repeats p slots) : + complement rows repeats p slots x = complement rows repeats p slots y ↔ + (∀ q : OtherCall rows repeats p, x.1 q.val = y.1 q.val) ∧ x.2 = y.2 := by + constructor + · intro h + exact ⟨fun q => congrArg (fun z : Complement rows repeats p slots => z.1 q) h, + congrArg (fun z : Complement rows repeats p slots => z.2) h⟩ + · rintro ⟨hcalls, harrays⟩ + exact Prod.ext (funext hcalls) harrays + +end +end PerfectCompleteness.LowerCutCallSplit + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerCutScalar.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerCutScalar.lean new file mode 100644 index 0000000000000000000000000000000000000000..a2b3857198c044169608953b214eb6709768ec81 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerCutScalar.lean @@ -0,0 +1,108 @@ +import OAI.Computability.PerfectCompleteness.Sampling.CutSamplerKeyLocalityLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.LowerCutScalar + +open RecursiveSpaces DescendantSpaces RecursiveSampler TerminalCalls + +noncomputable section + +universe u w + +variable {branch : Nat → Nat} {n m : Nat} + +abbrev Values (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) + (p : Path branch n (m + 1)) (A : Slots branch n → Type u) := + TerminalIndex repeats p → space 𝕜 branch (m + 1) (p.family A) + +def reconstruct (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n (m + 1)) → (A : Slots branch n → Type u) → + Values 𝕜 repeats p A → CutTerminalSplit.ExteriorTape 𝕜 repeats p A → + space 𝕜 branch n A + | _, _, .refl _, _, values, _ => values () + | n + 1, _, .step i p, A, values, exterior => + RecursiveSampler.combine 𝕜 A i (repeats (n + 1)) + (fun j => exterior ⟨.inl j, not_isTerminal_ordinary repeats i p j⟩) + (fun h => reconstruct 𝕜 repeats p (childFamily A i) + (fun terminal => values ((h, false), terminal)) + (CutSamplerReplayGrouping.subExterior 𝕜 repeats i p A (h, false) exterior)) + (fun h => reconstruct 𝕜 repeats p (childFamily A i) + (fun terminal => values ((h, true), terminal)) + (CutSamplerReplayGrouping.subExterior 𝕜 repeats i p A (h, true) exterior)) + +@[simp] theorem reconstruct_refl (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) + (A : Slots branch (m + 1) → Type u) + (values : Values 𝕜 repeats (.refl (m + 1)) A) + (exterior : CutTerminalSplit.ExteriorTape 𝕜 repeats (.refl (m + 1)) A) : + reconstruct 𝕜 repeats (.refl (m + 1)) A values exterior = values () := rfl + +theorem reconstruct_step (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) + (i : Fin (branch n)) (p : Path branch n (m + 1)) + (A : Slots branch (n + 1) → Type u) + (values : Values 𝕜 repeats (.step i p) A) + (exterior : CutTerminalSplit.ExteriorTape 𝕜 repeats (.step i p) A) : + reconstruct 𝕜 repeats (.step i p) A values exterior = + RecursiveSampler.combine 𝕜 A i (repeats (n + 1)) + (fun j => exterior ⟨.inl j, not_isTerminal_ordinary repeats i p j⟩) + (fun h => reconstruct 𝕜 repeats p (childFamily A i) + (fun terminal => values ((h, false), terminal)) + (CutSamplerReplayGrouping.subExterior 𝕜 repeats i p A (h, false) exterior)) + (fun h => reconstruct 𝕜 repeats p (childFamily A i) + (fun terminal => values ((h, true), terminal)) + (CutSamplerReplayGrouping.subExterior 𝕜 repeats i p A (h, true) exterior)) := rfl + +theorem reconstruct_splitTape (𝕜 : Type w) [Field 𝕜] + (repeats : Nat → Nat) (p : Path branch n (m + 1)) : + ∀ (A : Slots branch n → Type u) + (tape : CutSamplerRefinement.Tape 𝕜 repeats p A), + reconstruct 𝕜 repeats p A + (fun terminal => UniformChildSum.recursiveSum (p.family A) + ((CutTerminalSplit.splitTape 𝕜 repeats p A tape).1 terminal)) + (CutTerminalSplit.splitTape 𝕜 repeats p A tape).2 = + CutSamplerRefinement.evaluate 𝕜 repeats p A tape := by + induction n generalizing m with + | zero => + have h := p.height_le + omega + | succ n ih => + cases p with + | refl => + intro A tape + rfl + | step i p => + intro A tape + rw [reconstruct_step, CutSamplerLocality.evaluate_step] + apply congrArg₂ (RecursiveSampler.combine 𝕜 A i (repeats (n + 1)) + (fun j => tape (.inl j))) + · funext h + rw [CutSamplerReplayGrouping.subExterior_splitTape] + simp_rw [CutTerminalZero.splitTape_terminal_step] + exact ih p (childFamily A i) + (CutSamplerLocality.subTape 𝕜 repeats i p A tape h false) + · funext h + rw [CutSamplerReplayGrouping.subExterior_splitTape] + simp_rw [CutTerminalZero.splitTape_terminal_step] + exact ih p (childFamily A i) + (CutSamplerLocality.subTape 𝕜 repeats i p A tape h true) + +theorem reconstruct_join (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) + (p : Path branch n (m + 1)) (A : Slots branch n → Type u) + (terminal : CutTerminalSplit.TerminalTape 𝕜 repeats p A) + (exterior : CutTerminalSplit.ExteriorTape 𝕜 repeats p A) : + reconstruct 𝕜 repeats p A + (fun call => UniformChildSum.recursiveSum (p.family A) (terminal call)) exterior = + CutSamplerRefinement.evaluate 𝕜 repeats p A + ((CutTerminalSplit.splitTape 𝕜 repeats p A).symm (terminal, exterior)) := by + simpa only [Equiv.apply_symm_apply] using + reconstruct_splitTape 𝕜 repeats p A + ((CutTerminalSplit.splitTape 𝕜 repeats p A).symm (terminal, exterior)) + +end +end PerfectCompleteness.LowerCutScalar + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerCutScalarProjectionLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerCutScalarProjectionLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..e3ef1b36b2404bf80e69fad0d8731093ecefc982 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerCutScalarProjectionLemmas.lean @@ -0,0 +1,320 @@ +import OAI.Computability.PerfectCompleteness.Decoding.CutProjectionAssembly +import OAI.Computability.PerfectCompleteness.Decoding.LowerCutPairLemmas +import OAI.Computability.PerfectCompleteness.Foundations.CutNativeForms +import OAI.Computability.PerfectCompleteness.Repetition.CleanPhysicalReplay +import OAI.Computability.PerfectCompleteness.Sampling.SourceChildMarkedLaw + +namespace OAI + +section + +namespace PerfectCompleteness.LowerCutScalarProjection + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open WholeArraySubtreeSplit WholeArrayInteriorExterior +open scoped Classical + +noncomputable section + +variable {branch : Nat → Nat} {n m t : Nat} + +theorem scalarEquiv_HPullback : + {n m : Nat} → (p : Path branch n (m + 1)) → + (slots projected : Slots branch n → Fin t → MixedSupport.Slot) → + (q : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) → + (f : H (subtreeSlots p projected)) → + LowerCutNodeCoordinates.scalarEquiv p slots + (HPullback (fun s k => q (p.slotEmbedding s) k) f) = + HPullback (ChildBlockProjection.nodeProjection q (upperNode p)) + (LowerCutNodeCoordinates.scalarEquiv p projected f) + | _, _, .refl _, _, _, _, _ => rfl + | _, _, .step i p, slots, projected, q, f => + scalarEquiv_HPullback p (childSlots slots i) (childSlots projected i) + (fun s k => q (i, s) k) f + +theorem projectionCast_apply + {a b c d : Slots branch m → Fin t → MixedSupport.Slot} + (hab : a = b) (hcd : c = d) + (q : ∀ s k, MixedSupport.Projection (a s k) (c s k)) + (s : Slots branch m) (k : Fin t) : + CutNativeForms.projectionCast hab hcd q s k = + CutProjectionAssembly.castProjection + (congrFun (congrFun hab s) k) (congrFun (congrFun hcd s) k) (q s k) := by + cases hab + cases hcd + rfl + +theorem projectionCast_fill (p : Path branch n (m + 1)) + (outside : Slots branch n → Fin t → MixedSupport.Slot) + (left right : Slots branch (m + 1) → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) : + CutNativeForms.projectionCast + (CleanPhysicalReplay.cutSlots_fill p outside left) + (CleanPhysicalReplay.cutSlots_fill p outside right) + (fun s k => CutProjectionAssembly.fillProjection p outside left right q + (p.slotEmbedding s) k) = q := by + funext s k + rw [projectionCast_apply] + exact CutProjectionAssembly.fillProjection_at_cut_cast p outside left right q s k + +theorem inverse_spaceCast_HPullback + {a b c d : Slots branch m → Fin t → MixedSupport.Slot} + (hab : a = b) (hcd : c = d) + (q : ∀ s k, MixedSupport.Projection (a s k) (c s k)) (f : H d) : + CutNativeForms.spaceCast hab.symm + (HPullback (CutNativeForms.projectionCast hab hcd q) f) = + HPullback q (CutNativeForms.spaceCast hcd.symm f) := by + cases hab + cases hcd + rfl + +theorem fill_spaceCast_HPullback (p : Path branch n (m + 1)) + (outside : Slots branch n → Fin t → MixedSupport.Slot) + (left right : Slots branch (m + 1) → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) (f : H right) : + CutNativeForms.spaceCast (CleanPhysicalReplay.cutSlots_fill p outside left).symm + (HPullback q f) = + HPullback + (fun s k => CutProjectionAssembly.fillProjection p outside left right q + (p.slotEmbedding s) k) + (CutNativeForms.spaceCast + (CleanPhysicalReplay.cutSlots_fill p outside right).symm f) := by + have h := inverse_spaceCast_HPullback + (CleanPhysicalReplay.cutSlots_fill p outside left) + (CleanPhysicalReplay.cutSlots_fill p outside right) + (fun s k => CutProjectionAssembly.fillProjection p outside left right q + (p.slotEmbedding s) k) f + rw [projectionCast_fill] at h + exact h + +theorem scalarEquiv_fill_HPullback (p : Path branch n (m + 1)) + (outside : Slots branch n → Fin t → MixedSupport.Slot) + (left right : Slots branch (m + 1) → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) (f : H right) : + LowerCutNodeCoordinates.scalarEquiv p (CutSlotAssembly.fill p outside left) + (CutNativeForms.spaceCast (CleanPhysicalReplay.cutSlots_fill p outside left).symm + (HPullback q f)) = + HPullback (ChildBlockProjection.nodeProjection + (CutProjectionAssembly.fillProjection p outside left right q) (upperNode p)) + (LowerCutNodeCoordinates.scalarEquiv p (CutSlotAssembly.fill p outside right) + (CutNativeForms.spaceCast + (CleanPhysicalReplay.cutSlots_fill p outside right).symm f)) := by + rw [fill_spaceCast_HPullback] + exact scalarEquiv_HPullback p _ _ _ _ + +def nodeEquiv (slots : Slots branch n → Fin t → MixedSupport.Slot) + {a b : Nodes branch n} (hab : a = b) : + H (nodeSlots slots a) ≃ₗ[F2] H (nodeSlots slots b) := by + rw [hab] + +theorem nodeEquiv_HPullback + (slots projected : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + {a b : Nodes branch n} (hab : a = b) (f : H (nodeSlots projected a)) : + nodeEquiv slots hab (HPullback (ChildBlockProjection.nodeProjection q a) f) = + HPullback (ChildBlockProjection.nodeProjection q b) (nodeEquiv projected hab f) := by + cases hab + rfl + +theorem spaceEquiv_HPullback (p : Path branch n (m + 1)) + (slots projected : Slots branch n → Fin t → MixedSupport.Slot) + (upper : Nodes branch n) (level : Nat) + (d : HierarchicalFrozenTables.LowerNodes upper level) + (hnode : upperNode p = HierarchicalLeftDecoder.LowerNode upper level d) + (q : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (f : H (subtreeSlots p projected)) : + LowerCutDecoderForm.spaceEquiv p slots upper level d hnode + (HPullback (fun s k => q (p.slotEmbedding s) k) f) = + HPullback (ChildBlockProjection.nodeProjection q + (HierarchicalLeftDecoder.LowerNode upper level d)) + (LowerCutDecoderForm.spaceEquiv p projected upper level d hnode f) := by + change nodeEquiv slots hnode + (LowerCutNodeCoordinates.scalarEquiv p slots + (HPullback (fun s k => q (p.slotEmbedding s) k) f)) = + HPullback (ChildBlockProjection.nodeProjection q + (HierarchicalLeftDecoder.LowerNode upper level d)) + (nodeEquiv projected hnode (LowerCutNodeCoordinates.scalarEquiv p projected f)) + rw [scalarEquiv_HPullback, nodeEquiv_HPullback] + +theorem spaceEquiv_fill_HPullback (p : Path branch n (m + 1)) + (outside : Slots branch n → Fin t → MixedSupport.Slot) + (left right : Slots branch (m + 1) → Fin t → MixedSupport.Slot) + (upper : Nodes branch n) (level : Nat) + (d : HierarchicalFrozenTables.LowerNodes upper level) + (hnode : upperNode p = HierarchicalLeftDecoder.LowerNode upper level d) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) (f : H right) : + LowerCutDecoderForm.spaceEquiv p (CutSlotAssembly.fill p outside left) + upper level d hnode + (CutNativeForms.spaceCast (CleanPhysicalReplay.cutSlots_fill p outside left).symm + (HPullback q f)) = + HPullback (ChildBlockProjection.nodeProjection + (CutProjectionAssembly.fillProjection p outside left right q) + (HierarchicalLeftDecoder.LowerNode upper level d)) + (LowerCutDecoderForm.spaceEquiv p (CutSlotAssembly.fill p outside right) + upper level d hnode + (CutNativeForms.spaceCast + (CleanPhysicalReplay.cutSlots_fill p outside right).symm f)) := by + rw [fill_spaceCast_HPullback] + exact spaceEquiv_HPullback p _ _ upper level d hnode _ _ + +end +end PerfectCompleteness.LowerCutScalarProjection + +end + +section + +namespace PerfectCompleteness.SourceQuestionLowerForms + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +section Casts + +variable {branch : Nat → Nat} {height t : Nat} {C : Type*} [Fintype C] + (rows : Nat → Nat) + {source target : Slots branch (height + 1) → Fin t → MixedSupport.Slot} + +def rawCast (h : source = target) : + CutChildGrouping.Raw (C := C) source rows ≃ CutChildGrouping.Raw (C := C) target rows := by + cases h + exact Equiv.refl _ + +theorem rawCast_law (h : source = target) : + (CutChildGrouping.rawLaw (C := C) source rows).pushforward (rawCast rows h) = + CutChildGrouping.rawLaw (C := C) target rows := by + cases h + exact FiniteDistribution.pushforward_id _ + +theorem formCast_injective (h : source = target) : + Function.Injective (CutNativeForms.formCast h) := by + cases h + exact Function.injective_id + +theorem fullCollision_formCast (h : source = target) + (F G : Option (ChildBilinearCollisionTransfer.ParentForm source)) : + BilinearCollisionTransfer.fullCollision (F.map (CutNativeForms.formCast h)) + (G.map (CutNativeForms.formCast h)) = + BilinearCollisionTransfer.fullCollision F G := + MultiplicationFormInjective.definedEqual_map_of_injective + (CutNativeForms.formCast h) (formCast_injective h) F G + +end Casts + +variable {branch rows repeats : Nat → Nat} {n height t v m : Nat} + (path : Path branch n (height + 1)) + (outside : Slots branch n → Fin t → MixedSupport.Slot) + (placeholder : Slots branch (height + 1) → Fin t → MixedSupport.Slot) + (clauses : Fin m → SourceClause.NormalizedClause v) + +abbrev Questions := SourceChildMarkedLaw.Questions + (branch := branch) (n := height) (t := t) (m := m) +abbrev Calls := Option (WholeCutCalls.Index rows repeats path) + +def slots (q : Questions (branch := branch) (height := height) (t := t) (m := m)) : + Slots branch n → Fin t → MixedSupport.Slot := + CutSlotAssembly.fill path outside (SourceChildMarkedLaw.questionSlots clauses q) + +abbrev Raw (q : Questions (branch := branch) (height := height) (t := t) (m := m)) := + CutChildGrouping.Raw (C := Calls (rows := rows) (repeats := repeats) path) + (SourceChildMarkedLaw.questionSlots clauses q) rows + +abbrev Form (q : Questions (branch := branch) (height := height) (t := t) (m := m)) := + ChildBilinearCollisionTransfer.ParentForm (SourceChildMarkedLaw.questionSlots clauses q) + +theorem cutSlots_eq (q : Questions (branch := branch) (height := height) (t := t) (m := m)) : + WholeCutGrouping.cutSlots path (slots path outside clauses q) = + SourceChildMarkedLaw.questionSlots clauses q := + CleanPhysicalReplay.cutSlots_fill path outside _ + +def rawAtCut (q : Questions (branch := branch) (height := height) (t := t) (m := m)) + (raw : Raw (rows := rows) (repeats := repeats) path clauses q) : + LowerCutPair.Raw rows repeats path (slots path outside clauses q) := + rawCast rows (cutSlots_eq path outside clauses q).symm raw + +theorem rawAtCut_law + (q : Questions (branch := branch) (height := height) (t := t) (m := m)) : + (CutChildGrouping.rawLaw (C := Calls (rows := rows) (repeats := repeats) path) + (SourceChildMarkedLaw.questionSlots clauses q) rows).pushforward + (rawAtCut (rows := rows) (repeats := repeats) path outside clauses q) = + CutChildGrouping.rawLaw (C := Calls (rows := rows) (repeats := repeats) path) + (WholeCutGrouping.cutSlots path (slots path outside clauses q)) rows := + rawCast_law rows (cutSlots_eq path outside clauses q).symm + +variable (upper : Nodes branch n) (level : Nat) + (d : HierarchicalFrozenTables.LowerNodes upper level) + (hnode : WholeArrayInteriorExterior.upperNode path = + HierarchicalLeftDecoder.LowerNode upper level d) + (hbranch : ∀ k < n, 0 < branch k) + {adviceRows : Nat} (A : ManyGoodRows.RowMap (Block rows upper) adviceRows) + (exterior : CleanPhysicalReplay.Exterior rows repeats path outside placeholder) + +abbrev UpperTable (q : Questions (branch := branch) (height := height) (t := t) (m := m)) := + HierarchicalAllDecoderTables.Input (rows := rows) + (slots path outside clauses q) upper level adviceRows → + HierarchicalAllDecoderTables.UpperAnswer (slots path outside clauses q) upper + +variable (tables : (q : Questions (branch := branch) (height := height) (t := t) (m := m)) → + UpperTable (rows := rows) path outside clauses upper level (adviceRows := adviceRows) q) + (cutoff : Nat) + +def first (q : Questions (branch := branch) (height := height) (t := t) (m := m)) + (raw : Raw (rows := rows) (repeats := repeats) path clauses q) : Option (Form clauses q) := + (LowerCutDecoderForm.first path (slots path outside clauses q) upper level d hnode hbranch A + (tables q) cutoff + (CleanPhysicalReplay.exteriorAt rows repeats path outside placeholder + (SourceChildMarkedLaw.questionSlots clauses q) exterior) + (rawAtCut path outside clauses q raw)).map + (CutNativeForms.formCast (cutSlots_eq path outside clauses q)) + +def second (direction : BucketSampler.Direction (rows (height + 1))) + (q : Questions (branch := branch) (height := height) (t := t) (m := m)) + (raw : Raw (rows := rows) (repeats := repeats) path clauses q) : Option (Form clauses q) := + (LowerCutDecoderForm.second path (slots path outside clauses q) upper level d hnode hbranch A + (tables q) cutoff + (CleanPhysicalReplay.exteriorAt rows repeats path outside placeholder + (SourceChildMarkedLaw.questionSlots clauses q) exterior) + direction (rawAtCut path outside clauses q raw)).map + (CutNativeForms.formCast (cutSlots_eq path outside clauses q)) + +theorem fullCollision_probability + (direction : BucketSampler.Direction (rows (height + 1))) + (q : Questions (branch := branch) (height := height) (t := t) (m := m)) : + (CutChildGrouping.rawLaw (C := Calls (rows := rows) (repeats := repeats) path) + (SourceChildMarkedLaw.questionSlots clauses q) rows).probability + (fun raw => BilinearCollisionTransfer.fullCollision + (first path outside placeholder clauses upper level d hnode hbranch A exterior tables cutoff q raw) + (second path outside placeholder clauses upper level d hnode hbranch A exterior tables cutoff + direction q raw)) = + (CutChildGrouping.rawLaw (C := Calls (rows := rows) (repeats := repeats) path) + (WholeCutGrouping.cutSlots path (slots path outside clauses q)) rows).probability + (fun raw => BilinearCollisionTransfer.fullCollision + (LowerCutDecoderForm.first path (slots path outside clauses q) upper level d hnode hbranch A + (tables q) cutoff (CleanPhysicalReplay.exteriorAt rows repeats path outside placeholder + (SourceChildMarkedLaw.questionSlots clauses q) exterior) raw) + (LowerCutDecoderForm.second path (slots path outside clauses q) upper level d hnode hbranch A + (tables q) cutoff (CleanPhysicalReplay.exteriorAt rows repeats path outside placeholder + (SourceChildMarkedLaw.questionSlots clauses q) exterior) direction raw)) := by + have h := congrArg (fun μ : FiniteDistribution + (CutChildGrouping.Raw (C := Calls (rows := rows) (repeats := repeats) path) + (WholeCutGrouping.cutSlots path (slots path outside clauses q)) rows) => μ.probability + (fun raw => BilinearCollisionTransfer.fullCollision + (LowerCutDecoderForm.first path (slots path outside clauses q) upper level d hnode hbranch A + (tables q) cutoff (CleanPhysicalReplay.exteriorAt rows repeats path outside placeholder + (SourceChildMarkedLaw.questionSlots clauses q) exterior) raw) + (LowerCutDecoderForm.second path (slots path outside clauses q) upper level d hnode hbranch A + (tables q) cutoff (CleanPhysicalReplay.exteriorAt rows repeats path outside placeholder + (SourceChildMarkedLaw.questionSlots clauses q) exterior) direction raw))) + (rawAtCut_law (rows := rows) (repeats := repeats) path outside clauses q) + rw [FiniteDistribution.probability_pushforward] at h + simpa only [first, second, fullCollision_formCast] using h + +end +end PerfectCompleteness.SourceQuestionLowerForms + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerCutUniformCoordinatesLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerCutUniformCoordinatesLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..56702e8b696b71e2c2e0c06c79fb76d37c97eba2 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerCutUniformCoordinatesLemmas.lean @@ -0,0 +1,398 @@ +import OAI.Computability.PerfectCompleteness.Algebra.FixedRankContradiction +import OAI.Computability.PerfectCompleteness.Decoding.FixedLowerUniformCollision +import OAI.Computability.PerfectCompleteness.Decoding.LowerCutPairLemmas +import OAI.Computability.PerfectCompleteness.Machines.LowerCutInstalledInput +import OAI.Computability.PerfectCompleteness.Reduction.PreliminaryAveraging + +namespace OAI + +section + +namespace PerfectCompleteness.LowerCutUniformCoordinates + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open scoped Classical + +noncomputable section + +attribute [local instance] UniqueGamesTheorem.Appendix.RankLevelFilter.linearMapFintype + +variable {branch : Nat → Nat} {n m t : Nat} + (rows : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (upper : Nodes branch n) (lowerLevel : Nat) + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) + (hnode : WholeArrayInteriorExterior.upperNode p = + HierarchicalLeftDecoder.LowerNode upper lowerLevel d) + +abbrev NativeSample := + BucketSampler.Direction (rows (m + 1)) × + (LowerCutPair.NativeMatrix rows p slots × H (WholeCutGrouping.cutSlots p slots)) + +abbrev LowerSample := + BucketSampler.Direction + (rows (Nodes.height (HierarchicalLeftDecoder.LowerNode upper lowerLevel d))) × + (HierarchicalLowerMatrixInput.Matrix (rows := rows) slots upper lowerLevel d × + HierarchicalDecoderTables.LowerH slots upper lowerLevel d) + +def sampleEquiv : NativeSample rows p slots ≃ LowerSample rows slots upper lowerLevel d := + (LowerCutInstalledInput.lowerDirectionEquiv rows p upper lowerLevel d hnode).prodCongr + ((LowerCutInstalledInput.lowerMatrixEquiv rows p slots upper lowerLevel d hnode).toEquiv.prodCongr + (LowerCutInstalledInput.lowerScalarEquiv p slots upper lowerLevel d hnode).toEquiv) + +@[simp] theorem sampleEquiv_apply (x : NativeSample rows p slots) : + sampleEquiv rows p slots upper lowerLevel d hnode x = + (LowerCutInstalledInput.lowerDirectionEquiv rows p upper lowerLevel d hnode x.1, + (LowerCutInstalledInput.lowerMatrixEquiv rows p slots upper lowerLevel d hnode x.2.1, + LowerCutInstalledInput.lowerScalarEquiv p slots upper lowerLevel d hnode x.2.2)) := rfl + +variable [Nonempty (BucketSampler.Direction (rows (m + 1)))] + +include p hnode in + +theorem lowerDirection_nonempty : + Nonempty (BucketSampler.Direction + (rows (Nodes.height (HierarchicalLeftDecoder.LowerNode upper lowerLevel d)))) := by + obtain ⟨a⟩ := (inferInstance : Nonempty (BucketSampler.Direction (rows (m + 1)))) + exact ⟨LowerCutInstalledInput.lowerDirectionEquiv rows p upper lowerLevel d hnode a⟩ + +local instance lowerHFintype : + Fintype (HierarchicalDecoderTables.LowerH slots upper lowerLevel d) := Fintype.ofFinite _ + +theorem uniformLaw_pushforward : + letI := lowerDirection_nonempty rows p upper lowerLevel d hnode + (FixedLowerUniformCollision.uniformLaw (H (WholeCutGrouping.cutSlots p slots)) + (rows (m + 1))).pushforward (sampleEquiv rows p slots upper lowerLevel d hnode) = + FixedLowerUniformCollision.uniformLaw (HierarchicalDecoderTables.LowerH slots upper lowerLevel d) + (rows (Nodes.height (HierarchicalLeftDecoder.LowerNode upper lowerLevel d))) := by + let := lowerDirection_nonempty rows p upper lowerLevel d hnode + have h := UniformConditioning.uniform_transport (sampleEquiv rows p slots upper lowerLevel d hnode) + rw [FiniteDistribution.transport_eq_pushforward] at h + simpa only [FixedLowerUniformCollision.uniformLaw, WholeCutSampler.uniform_product] using h + +theorem probability_transport (event : LowerSample rows slots upper lowerLevel d → Bool) : + letI := lowerDirection_nonempty rows p upper lowerLevel d hnode + (FixedLowerUniformCollision.uniformLaw (H (WholeCutGrouping.cutSlots p slots)) + (rows (m + 1))).probability + (fun x => event (sampleEquiv rows p slots upper lowerLevel d hnode x)) = + (FixedLowerUniformCollision.uniformLaw (HierarchicalDecoderTables.LowerH slots upper lowerLevel d) + (rows (Nodes.height (HierarchicalLeftDecoder.LowerNode upper lowerLevel d)))).probability event := by + let := lowerDirection_nonempty rows p upper lowerLevel d hnode + have h := congrArg + (fun μ : FiniteDistribution (LowerSample rows slots upper lowerLevel d) => μ.probability event) + (uniformLaw_pushforward rows p slots upper lowerLevel d hnode) + rw [FiniteDistribution.probability_pushforward] at h + exact h + +theorem expectation_transport (f : LowerSample rows slots upper lowerLevel d → ℝ) : + letI := lowerDirection_nonempty rows p upper lowerLevel d hnode + (FixedLowerUniformCollision.uniformLaw (H (WholeCutGrouping.cutSlots p slots)) + (rows (m + 1))).expectation + (fun x => f (sampleEquiv rows p slots upper lowerLevel d hnode x)) = + (FixedLowerUniformCollision.uniformLaw (HierarchicalDecoderTables.LowerH slots upper lowerLevel d) + (rows (Nodes.height (HierarchicalLeftDecoder.LowerNode upper lowerLevel d)))).expectation f := by + let := lowerDirection_nonempty rows p upper lowerLevel d hnode + have h := congrArg + (fun μ : FiniteDistribution (LowerSample rows slots upper lowerLevel d) => μ.expectation f) + (uniformLaw_pushforward rows p slots upper lowerLevel d hnode) + rw [FiniteDistribution.expectation_pushforward] at h + exact h + +variable {Y : Type*} [Fintype Y] + +omit [Nonempty (BucketSampler.Direction (rows (m + 1)))] [Fintype Y] in +theorem collision_transport + (f : HierarchicalLowerMatrixInput.Matrix (rows := rows) slots upper lowerLevel d → Option Y) + (x : NativeSample rows p slots) : + FixedLowerUniformCollision.uniformCollision (H (WholeCutGrouping.cutSlots p slots)) + (rows (m + 1)) + (fun X => f (LowerCutInstalledInput.lowerMatrixEquiv rows p slots upper lowerLevel d hnode X)) x = + FixedLowerUniformCollision.uniformCollision + (HierarchicalDecoderTables.LowerH slots upper lowerLevel d) + (rows (Nodes.height (HierarchicalLeftDecoder.LowerNode upper lowerLevel d))) f + (sampleEquiv rows p slots upper lowerLevel d hnode x) := by + exact congrArg + (fun X => TwoResponseCollision.collision f + (LowerCutInstalledInput.lowerMatrixEquiv rows p slots upper lowerLevel d hnode x.2.1, X)) + (LowerCutInstalledInput.shift_lowerMatrixEquiv rows p slots upper lowerLevel d hnode + x.2.1 x.1 x.2.2) + +omit [Fintype Y] in +theorem collision_probability + (f : HierarchicalLowerMatrixInput.Matrix (rows := rows) slots upper lowerLevel d → Option Y) : + letI := lowerDirection_nonempty rows p upper lowerLevel d hnode + (FixedLowerUniformCollision.uniformLaw (H (WholeCutGrouping.cutSlots p slots)) + (rows (m + 1))).probability + (FixedLowerUniformCollision.uniformCollision (H (WholeCutGrouping.cutSlots p slots)) + (rows (m + 1)) + (fun X => f (LowerCutInstalledInput.lowerMatrixEquiv rows p slots upper lowerLevel d hnode X))) = + (FixedLowerUniformCollision.uniformLaw (HierarchicalDecoderTables.LowerH slots upper lowerLevel d) + (rows (Nodes.height (HierarchicalLeftDecoder.LowerNode upper lowerLevel d)))).probability + (FixedLowerUniformCollision.uniformCollision + (HierarchicalDecoderTables.LowerH slots upper lowerLevel d) + (rows (Nodes.height (HierarchicalLeftDecoder.LowerNode upper lowerLevel d))) f) := by + let := lowerDirection_nonempty rows p upper lowerLevel d hnode + have hevent := funext (collision_transport rows p slots upper lowerLevel d hnode f) + rw [hevent] + exact probability_transport rows p slots upper lowerLevel d hnode _ + +end +end PerfectCompleteness.LowerCutUniformCoordinates + +end + +section + +namespace PerfectCompleteness.LowerCutUniformCollisionLaw + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open scoped Classical + +noncomputable section + +attribute [local instance] UniqueGamesTheorem.Appendix.RankLevelFilter.linearMapFintype + +variable {branch : Nat → Nat} {n m t : Nat} + (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + +theorem direction_probability_eq {Y : Type*} [Fintype Y] + (answer : Arrays slots rows → Option Y) + (exterior : WholeCutGrouping.Exterior rows repeats p slots) + (a : BucketSampler.Direction (rows (m + 1))) : + (CutChildGrouping.rawLaw (C := Option (LowerCutPair.Calls rows repeats p)) + (WholeCutGrouping.cutSlots p slots) rows).probability + (fun raw => TwoResponseCollision.collision answer + (LowerCutPair.arraysPair rows repeats p slots exterior a raw)) = + (FiniteDistribution.uniform (LowerCutPairBackground.Complement rows repeats p slots)).expectation + (fun c => ((FiniteDistribution.uniform (LowerCutPair.NativeMatrix rows p slots)).product + (FiniteDistribution.uniform (H (WholeCutGrouping.cutSlots p slots)))).probability + (fun z => TwoResponseCollision.collision + (fun X => answer (LowerCutPairBackground.installMatrix rows repeats p slots exterior c X)) + (z.1, EvaluationMatrix.shift (H (WholeCutGrouping.cutSlots p slots)) z.1 a.val z.2))) := by + have h := congrArg + (fun μ : FiniteDistribution (Arrays slots rows × Arrays slots rows) => + μ.probability (TwoResponseCollision.collision answer)) + (LowerCutPairBackground.arraysPair_law rows repeats p slots exterior a) + simp only [FiniteDistribution.probability_pushforward] at h + rw [PreliminaryAveraging.probability_product] at h + simp only [FiniteDistribution.probability_pushforward] at h + exact h + +theorem native_probability_eq {Y : Type*} [Fintype Y] + [Nonempty (BucketSampler.Direction (rows (m + 1)))] + (answer : Arrays slots rows → Option Y) + (exterior : WholeCutGrouping.Exterior rows repeats p slots) : + (FiniteDistribution.uniform (BucketSampler.Direction (rows (m + 1)))).expectation + (fun a => (CutChildGrouping.rawLaw (C := Option (LowerCutPair.Calls rows repeats p)) + (WholeCutGrouping.cutSlots p slots) rows).probability + (fun raw => TwoResponseCollision.collision answer + (LowerCutPair.arraysPair rows repeats p slots exterior a raw))) = + (FiniteDistribution.uniform (LowerCutPairBackground.Complement rows repeats p slots)).expectation + (fun c => (FixedLowerUniformCollision.uniformLaw (H (WholeCutGrouping.cutSlots p slots)) + (rows (m + 1))).probability + (FixedLowerUniformCollision.uniformCollision _ _ + (fun X => answer (LowerCutPairBackground.installMatrix rows repeats p slots exterior c X)))) := by + simp_rw [direction_probability_eq rows repeats p slots answer exterior] + rw [FiniteDistribution.expectation_comm] + apply FiniteDistribution.expectation_congr + intro c + exact (PreliminaryAveraging.probability_product + (FiniteDistribution.uniform (BucketSampler.Direction (rows (m + 1)))) + ((FiniteDistribution.uniform (LowerCutPair.NativeMatrix rows p slots)).product + (FiniteDistribution.uniform (H (WholeCutGrouping.cutSlots p slots)))) + (FixedLowerUniformCollision.uniformCollision (H (WholeCutGrouping.cutSlots p slots)) + (rows (m + 1)) + (fun X => answer (LowerCutPairBackground.installMatrix rows repeats p slots exterior c X)))).symm + +variable (upper : Nodes branch n) (lowerLevel : Nat) + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) + (hnode : WholeArrayInteriorExterior.upperNode p = + HierarchicalLeftDecoder.LowerNode upper lowerLevel d) + (hbranch : ∀ k < n, 0 < branch k) {adviceRows : Nat} + (A : ManyGoodRows.RowMap (Block rows upper) adviceRows) + (table : HierarchicalAllDecoderTables.Input (rows := rows) + slots upper lowerLevel adviceRows → HierarchicalAllDecoderTables.UpperAnswer slots upper) + (cutoff : Nat) + +local instance lowerHFintype : + Fintype (HierarchicalDecoderTables.LowerH slots upper lowerLevel d) := Fintype.ofFinite _ +local instance answerFintype : + Fintype (HierarchicalDecoderTables.Answer slots upper lowerLevel d) := + LeftDecoder.dualFintype (V := PointwiseSpaces.squareSpace + (HierarchicalDecoderTables.LowerH slots upper lowerLevel d)) + +theorem answer_installMatrix + (exterior : WholeCutGrouping.Exterior rows repeats p slots) + (c : LowerCutPairBackground.Complement rows repeats p slots) + (X : LowerCutPair.NativeMatrix rows p slots) : + LowerCutDecoderForm.answer slots upper lowerLevel d hbranch A table cutoff + (LowerCutPairBackground.installMatrix rows repeats p slots exterior c X) = + HierarchicalLowerInverse.matrixTable slots upper lowerLevel + (HierarchicalMatrixTable.backgroundOf slots upper + (LowerCutPairBackground.backgroundArrays rows repeats p slots exterior c)) d + (NodeEmbedding.matrix (LowerCutPairBackground.backgroundArrays rows repeats p slots exterior c) upper) + A (HierarchicalAllDecoderTables.decodeTable slots upper lowerLevel hbranch adviceRows d cutoff table) + (LowerCutInstalledInput.lowerMatrixEquiv rows p slots upper lowerLevel d hnode X) := by + exact congrArg + (fun input : HierarchicalAllDecoderTables.Input (rows := rows) slots upper lowerLevel adviceRows => + HierarchicalDecoderTables.decode slots upper lowerLevel hbranch d cutoff (table input)) + (LowerCutInstalledInput.actualInput_installMatrix rows p slots upper lowerLevel d hnode + repeats exterior c A X) + +include hnode in + +theorem probability_eq + [Nonempty (BucketSampler.Direction (rows (m + 1)))] + [Nonempty (BucketSampler.Direction + (rows (Nodes.height (HierarchicalLeftDecoder.LowerNode upper lowerLevel d))))] + (exterior : WholeCutGrouping.Exterior rows repeats p slots) : + (FiniteDistribution.uniform (BucketSampler.Direction (rows (m + 1)))).expectation + (fun a => (CutChildGrouping.rawLaw (C := Option (LowerCutPair.Calls rows repeats p)) + (WholeCutGrouping.cutSlots p slots) rows).probability + (fun raw => TwoResponseCollision.collision + (LowerCutDecoderForm.answer slots upper lowerLevel d hbranch A table cutoff) + (LowerCutPair.arraysPair rows repeats p slots exterior a raw))) = + (FiniteDistribution.uniform (LowerCutPairBackground.Complement rows repeats p slots)).expectation + (fun c => (FixedLowerUniformCollision.uniformLaw + (HierarchicalDecoderTables.LowerH slots upper lowerLevel d) + (rows (Nodes.height (HierarchicalLeftDecoder.LowerNode upper lowerLevel d)))).probability + (FixedLowerUniformCollision.uniformCollision _ _ + (HierarchicalLowerInverse.matrixTable slots upper lowerLevel + (HierarchicalMatrixTable.backgroundOf slots upper + (LowerCutPairBackground.backgroundArrays rows repeats p slots exterior c)) d + (NodeEmbedding.matrix + (LowerCutPairBackground.backgroundArrays rows repeats p slots exterior c) upper) + A (HierarchicalAllDecoderTables.decodeTable + slots upper lowerLevel hbranch adviceRows d cutoff table)))) := by + rw [native_probability_eq rows repeats p slots] + apply FiniteDistribution.expectation_congr + intro c + have h := LowerCutUniformCoordinates.collision_probability rows p slots upper lowerLevel d hnode + (HierarchicalLowerInverse.matrixTable slots upper lowerLevel + (HierarchicalMatrixTable.backgroundOf slots upper + (LowerCutPairBackground.backgroundArrays rows repeats p slots exterior c)) d + (NodeEmbedding.matrix (LowerCutPairBackground.backgroundArrays rows repeats p slots exterior c) upper) + A (HierarchicalAllDecoderTables.decodeTable slots upper lowerLevel hbranch adviceRows d cutoff table)) + have hf := funext + (answer_installMatrix rows repeats p slots upper lowerLevel d hnode hbranch A table cutoff exterior c) + rw [hf] + exact h + +end +end PerfectCompleteness.LowerCutUniformCollisionLaw + +end + +section + +namespace PerfectCompleteness.FixedLowerRawCollision + +noncomputable section + +open scoped Classical +open FixedParameters FixedRows RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +variable {δ : ℚ} {hδ : 0 < δ} (parameters : Parameters δ hδ) + {height t : Nat} + (path : Path (branch parameters) parameters.plan.depth (height + 1)) + (slots : Slots (branch parameters) parameters.plan.depth → Fin t → MixedSupport.Slot) + (upper : Nodes (branch parameters) parameters.plan.depth) + (d : HierarchicalFrozenTables.LowerNodes upper (height + 1)) + (hnode : WholeArrayInteriorExterior.upperNode path = + HierarchicalLeftDecoder.LowerNode upper (height + 1) d) + +local instance cutDirectionNonempty : + Nonempty (BucketSampler.Direction (rows parameters.plan (height + 1))) := + ⟨BucketUniform.coordinateDirection ⟨0, lt_of_lt_of_le Nat.zero_lt_one + (parameters.plan.rows_pos (parameters.plan.depth - (height + 1)))⟩⟩ + +local instance lowerDirectionNonempty : + Nonempty (BucketSampler.Direction (rows parameters.plan + (Nodes.height (HierarchicalLeftDecoder.LowerNode upper (height + 1) d)))) := + ⟨BucketUniform.coordinateDirection ⟨0, lt_of_lt_of_le Nat.zero_lt_one + (parameters.plan.rows_pos (parameters.plan.depth - + Nodes.height (HierarchicalLeftDecoder.LowerNode upper (height + 1) d)))⟩⟩ + +local instance lowerHFintype : + Fintype (HierarchicalDecoderTables.LowerH slots upper (height + 1) d) := + Fintype.ofFinite _ + +local instance upperDualFintype : + Fintype (HierarchicalAllDecoderTables.UpperAnswer slots upper) := + HierarchicalAllDecoderTables.upperDualFintype slots upper + +theorem branchPositive : ∀ k < parameters.plan.depth, 0 < branch parameters k := + fun k _ => branch_pos parameters k + +variable {adviceRows : Nat} + (A : ManyGoodRows.RowMap (Block (rows parameters.plan) upper) adviceRows) + (exterior : WholeCutGrouping.Exterior (rows parameters.plan) (repeats parameters.plan) path slots) + +abbrev UpperTable := + HierarchicalAllDecoderTables.Input (rows := rows parameters.plan) + slots upper (height + 1) adviceRows → + HierarchicalAllDecoderTables.UpperAnswer slots upper + +def fullCollisionProbability (table : UpperTable parameters slots upper (height := height) + (adviceRows := adviceRows)) : ℝ := + (FiniteDistribution.uniform (BucketSampler.Direction (rows parameters.plan (height + 1)))).expectation + (fun direction => + (CutChildGrouping.rawLaw + (C := Option (WholeCutCalls.Index (rows parameters.plan) (repeats parameters.plan) path)) + (WholeCutGrouping.cutSlots path slots) (rows parameters.plan)).probability + (fun raw => BilinearCollisionTransfer.fullCollision + (LowerCutDecoderForm.first path slots upper (height + 1) d hnode + (branchPositive parameters) A table (cutoff parameters.plan hδ) exterior raw) + (LowerCutDecoderForm.second path slots upper (height + 1) d hnode + (branchPositive parameters) A table (cutoff parameters.plan hδ) exterior direction raw))) + +variable + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount (branch parameters) parameters.plan.depth t)) + (useful : (bg : HierarchicalMatrixTable.Background (rows := rows parameters.plan) slots upper) → + HierarchicalFrozenTables.QuotientMatrix slots upper (height + 1) bg → Prop) + (density : ℝ) (hdensity : 0 < density) + +include σ useful density hdensity + +theorem supported_fullCollision_le + (table : UpperTable parameters slots upper (height := height) (adviceRows := adviceRows)) + (hsupport : (HierarchicalAllDecoderTables.upperTableLaw slots upper (height + 1) + σ useful adviceRows density).weight table ≠ 0) : + fullCollisionProbability parameters path slots upper d hnode A exterior table ≤ + FixedRankContradiction.gamma parameters (Nodes.height upper) ^ 2 / 8 := by + unfold fullCollisionProbability + simp_rw [LowerCutDecoderForm.fullCollision_pair] + rw [LowerCutUniformCollisionLaw.probability_eq + (rows parameters.plan) (repeats parameters.plan) path slots upper (height + 1) d hnode + (branchPositive parameters) A table (cutoff parameters.plan hδ) exterior] + apply (SmallBias.expectation_mono _ (fun c => + (FixedLowerUniformCollision.supported_collision_lt parameters.plan hδ slots upper (height + 1) + (HierarchicalMatrixTable.backgroundOf slots upper + (LowerCutPairBackground.backgroundArrays (rows parameters.plan) (repeats parameters.plan) + path slots exterior c)) + (branchPositive parameters) σ useful density hdensity d + (NodeEmbedding.matrix (LowerCutPairBackground.backgroundArrays + (rows parameters.plan) (repeats parameters.plan) path slots exterior c) upper) + A table hsupport).le)).trans + exact le_of_eq (SmallBias.expectation_const _ _) + +theorem mean_fullCollision_le : + (HierarchicalAllDecoderTables.upperTableLaw slots upper (height + 1) σ useful + adviceRows density).expectation + (fullCollisionProbability parameters path slots upper d hnode A exterior) ≤ + FixedRankContradiction.gamma parameters (Nodes.height upper) ^ 2 / 8 := by + apply DecoderTableAdmissibility.expectation_le_of_support + intro table hsupport + exact supported_fullCollision_le parameters path slots upper d hnode A exterior + σ useful density hdensity table hsupport + +end +end PerfectCompleteness.FixedLowerRawCollision + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerDirectionFiber.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerDirectionFiber.lean new file mode 100644 index 0000000000000000000000000000000000000000..200ff380826c42105f92bf0ce025c4316d088658 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerDirectionFiber.lean @@ -0,0 +1,322 @@ +import Mathlib.Tactic.Abel +import Mathlib.Tactic.Ring +import OAI.Computability.PerfectCompleteness.Foundations.LinearEvaluationLemmas +import OAI.Computability.PerfectCompleteness.Sampling.BucketSampler +import OAI.Computability.PerfectCompleteness.Sampling.CutSamplerReplayTransportLemmas +import OAI.Computability.PerfectCompleteness.Sampling.UniformDifference + +namespace OAI + +section + +namespace PerfectCompleteness.LowerDirectionFiber + +noncomputable section + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games +open BucketSampler (F2 Direction) + +variable {ℓ : Nat} + +private theorem exists_pivot (a : Direction ℓ) : ∃ i : Fin ℓ, a.val i = 1 := by + by_contra h + apply a.property + funext i + rcases UniqueGamesTheorem.Integration.BinaryLinear.scalar_cases (a.val i) with hz | ho + · exact hz + · exact False.elim (h ⟨i, ho⟩) + +def pivot (a : Direction ℓ) : Fin ℓ := Classical.choose (exists_pivot a) + +@[simp] theorem pivot_value (a : Direction ℓ) : a.val (pivot a) = 1 := + Classical.choose_spec (exists_pivot a) + +abbrev Other (a : Direction ℓ) := {i : Fin ℓ // i ≠ pivot a} +abbrev Rows (H : Type*) (ℓ : Nat) := Fin ℓ → H +abbrev Complement (a : Direction ℓ) (H : Type*) := Other a → H + +theorem scalar_count (a : Direction ℓ) : Fintype.card (Other a ⊕ Fin 2) = ℓ + 1 := by + have h : ℓ = 1 + Fintype.card (Other a) := by + simpa [Other] using + (Fintype.sum_eq_add_sum_subtype_ne (fun _ : Fin ℓ => (1 : Nat)) (pivot a)) + rw [Fintype.card_sum, Fintype.card_fin] + omega + +variable {H : Type*} [AddCommGroup H] [Module F2 H] + +def complement (a : Direction ℓ) (S : Rows H ℓ) : Complement a H := + fun j => S j.val - a.val j.val • S (pivot a) + +def restore (a : Direction ℓ) (c : Complement a H) (h : H) : Rows H ℓ := + fun i => if hi : i = pivot a then h else c ⟨i, hi⟩ + a.val i • h + +@[simp] theorem restore_pivot (a : Direction ℓ) (c : Complement a H) (h : H) : + restore a c h (pivot a) = h := by simp [restore] + +@[simp] theorem restore_other (a : Direction ℓ) (c : Complement a H) (h : H) + (j : Other a) : restore a c h j.val = c j + a.val j.val • h := by + simp only [restore, dite_eq_right j.property] + +@[simp] theorem complement_restore (a : Direction ℓ) (c : Complement a H) (h : H) : + complement a (restore a c h) = c := by + funext j + simp only [complement, restore_other, restore_pivot, add_sub_cancel_right] + +@[simp] theorem restore_complement (a : Direction ℓ) (S : Rows H ℓ) : + restore a (complement a S) (S (pivot a)) = S := by + funext i + by_cases hi : i = pivot a + · subst i + exact restore_pivot a (complement a S) (S (pivot a)) + · simp only [restore, dite_eq_right hi, complement, sub_add_cancel] + +def split (a : Direction ℓ) : Rows H ℓ ≃ Complement a H × H where + toFun S := (complement a S, S (pivot a)) + invFun z := restore a z.1 z.2 + left_inv := restore_complement a + right_inv z := Prod.ext (complement_restore a z.1 z.2) (restore_pivot a z.1 z.2) + +@[simp] theorem split_apply (a : Direction ℓ) (S : Rows H ℓ) : + split a S = (complement a S, S (pivot a)) := rfl + +def replace (a : Direction ℓ) (S : Rows H ℓ) (fresh : H) : Rows H ℓ := + restore a (complement a S) fresh + +@[simp] theorem complement_replace (a : Direction ℓ) (S : Rows H ℓ) (fresh : H) : + complement a (replace a S fresh) = complement a S := + complement_restore a _ _ + +theorem replace_eq (a : Direction ℓ) (S : Rows H ℓ) (fresh : H) : + replace a S fresh = S + BucketSampler.rankOne a.val (fresh - S (pivot a)) := by + funext i + by_cases hi : i = pivot a + · subst i + simp only [replace, restore_pivot, Pi.add_apply, BucketSampler.rankOne, + pivot_value, one_smul] + abel + · simp only [replace, restore, dite_eq_right hi, complement, Pi.add_apply, + BucketSampler.rankOne, smul_sub] + abel + +def fiberEquiv (a : Direction ℓ) (c : Complement a H) : + H ≃ {S : Rows H ℓ // complement a S = c} where + toFun h := ⟨restore a c h, complement_restore a c h⟩ + invFun S := S.val (pivot a) + left_inv := restore_pivot a c + right_inv S := by + apply Subtype.ext + change restore a c (S.val (pivot a)) = S.val + exact (congrArg (fun c' => restore a c' (S.val (pivot a))) S.property.symm).trans + (restore_complement a S.val) + +instance fiberNonempty (a : Direction ℓ) (c : Complement a H) : + Nonempty {S : Rows H ℓ // complement a S = c} := ⟨(fiberEquiv a c) 0⟩ + +theorem quotient_replace (a : Direction ℓ) (S : Rows H ℓ) (fresh : H) + (eval : H →ₗ[F2] F2) : + DirectionQuotient.proj a.val (fun i => eval (replace a S fresh i)) = + DirectionQuotient.proj a.val (fun i => eval (S i)) := by + have heq : (fun i => eval (replace a S fresh i)) = + (fun i => eval (S i)) + eval (fresh - S (pivot a)) • a.val := by + rw [replace_eq] + funext i + simp only [Pi.add_apply, BucketSampler.rankOne, map_add, map_smul, + Pi.smul_apply, smul_eq_mul, mul_comm] + rw [heq, map_add, map_smul] + have hz : DirectionQuotient.proj a.val a.val = 0 := + (DirectionQuotient.proj_eq_zero_iff a.val a.val).mpr (Or.inr rfl) + rw [hz, smul_zero, add_zero] + +private theorem scalar_complement_eq (a : Direction ℓ) (x y : Fin ℓ → F2) + (h : DirectionQuotient.proj a.val x = DirectionQuotient.proj a.val y) + (i : Fin ℓ) : + x i - a.val i * x (pivot a) = y i - a.val i * y (pivot a) := by + rcases (DirectionQuotient.proj_eq_iff a.val x y).mp h with hz | ha + · have hxy : x = y := sub_eq_zero.mp hz + rw [hxy] + · have hi : x i = y i + a.val i := by + have h' := congrFun ha i + change x i - y i = a.val i at h' + exact ((sub_eq_iff_eq_add).mp h').trans (add_comm _ _) + have hp : x (pivot a) = y (pivot a) + 1 := by + have h' := congrFun ha (pivot a) + change x (pivot a) - y (pivot a) = a.val (pivot a) at h' + rw [pivot_value] at h' + exact ((sub_eq_iff_eq_add).mp h').trans (add_comm _ _) + rw [hi, hp] + ring + +section ActualFunctions + +variable {X : Type*} (V : Submodule F2 (X → F2)) + +def quotientQuery (a : Direction ℓ) (S : Rows V ℓ) : X → DirectionQuotient.Space a.val := + fun x => DirectionQuotient.proj a.val (fun i => (S i).val x) + +@[simp] theorem quotientQuery_replace (a : Direction ℓ) (S : Rows V ℓ) (fresh : V) : + quotientQuery V a (replace a S fresh) = quotientQuery V a S := by + funext x + exact quotient_replace a S fresh (EvaluationMatrix.evaluation V x) + +theorem quotientQuery_eq_iff (a : Direction ℓ) (S T : Rows V ℓ) : + quotientQuery V a S = quotientQuery V a T ↔ complement a S = complement a T := by + constructor + · intro h + funext j + apply Subtype.ext + funext x + exact scalar_complement_eq a (fun i => (S i).val x) (fun i => (T i).val x) + (congrFun h x) j.val + · intro h + have hT : replace a S (T (pivot a)) = T := by + unfold replace + rw [h, restore_complement] + rw [← hT] + exact (quotientQuery_replace V a S (T (pivot a))).symm + +theorem response_replace {Y : Type*} (a : Direction ℓ) + (read : (X → DirectionQuotient.Space a.val) → Y) + (S : Rows V ℓ) (fresh : V) : + read (quotientQuery V a (replace a S fresh)) = read (quotientQuery V a S) := by + rw [quotientQuery_replace] + +theorem ofRows_add_rankOne (a : Direction ℓ) (S : Rows V ℓ) (h : V) : + EvaluationMatrix.ofRows V (S + BucketSampler.rankOne a.val h) = + EvaluationMatrix.shift V (EvaluationMatrix.ofRows V S) a.val h := by + apply LinearMap.ext + intro q + funext i + change q (S i + a.val i • h) = q (S i) + q h * a.val i + simp only [map_add, map_smul, smul_eq_mul, mul_comm] + +theorem ofRows_replace (a : Direction ℓ) (S : Rows V ℓ) (fresh : V) : + EvaluationMatrix.ofRows V (replace a S fresh) = + EvaluationMatrix.shift V (EvaluationMatrix.ofRows V S) a.val + (fresh - S (pivot a)) := by + rw [replace_eq] + exact ofRows_add_rankOne V a S _ + +end ActualFunctions + +section Laws + +variable [Fintype H] + +private theorem uniform_product {A B : Type*} [Fintype A] [Fintype B] + [Nonempty A] [Nonempty B] : + (FiniteDistribution.uniform A).product (FiniteDistribution.uniform B) = + FiniteDistribution.uniform (A × B) := by + apply FiniteDistribution.eq_of_weight_eq + intro z + change (1 / (Fintype.card A : ℝ)) * (1 / (Fintype.card B : ℝ)) = + 1 / (Fintype.card (A × B) : ℝ) + simp only [Fintype.card_prod, Nat.cast_mul, one_div, mul_inv] + +theorem split_uniform (a : Direction ℓ) : + (FiniteDistribution.uniform (Rows H ℓ)).pushforward (split a) = + (FiniteDistribution.uniform (Complement a H)).product (FiniteDistribution.uniform H) := by + rw [← FiniteDistribution.transport_eq_pushforward, UniformConditioning.uniform_transport] + exact uniform_product.symm + +theorem uniform_fiber (a : Direction ℓ) (c : Complement a H) : + (FiniteDistribution.uniform H).pushforward (restore a c) = + (FiniteDistribution.uniform {S : Rows H ℓ // complement a S = c}).pushforward + Subtype.val := by + have h := UniformConditioning.uniform_transport (fiberEquiv (H := H) a c) + rw [FiniteDistribution.transport_eq_pushforward] at h + have h' := congrArg + (fun μ : FiniteDistribution {S : Rows H ℓ // complement a S = c} => + μ.pushforward (Subtype.val : {S : Rows H ℓ // complement a S = c} → Rows H ℓ)) h + rw [FiniteDistribution.pushforward_comp] at h' + exact h' + +def pairCoordinates (a : Direction ℓ) : + (Rows H ℓ × H) ≃ Complement a H × (H × H) where + toFun z := (complement a z.1, (z.1 (pivot a), z.2)) + invFun z := (restore a z.1 z.2.1, z.2.2) + left_inv z := Prod.ext (restore_complement a z.1) rfl + right_inv z := Prod.ext (complement_restore a z.1 z.2.1) + (Prod.ext (restore_pivot a z.1 z.2.1) rfl) + +omit [Fintype H] in +@[simp] theorem pairCoordinates_apply (a : Direction ℓ) (z : Rows H ℓ × H) : + pairCoordinates a z = (complement a z.1, (z.1 (pivot a), z.2)) := rfl + +def fiberPairLaw (a : Direction ℓ) : FiniteDistribution (Rows H ℓ × Rows H ℓ) := + ((FiniteDistribution.uniform (Complement a H)).product + ((FiniteDistribution.uniform H).product (FiniteDistribution.uniform H))).pushforward + (fun z => (restore a z.1 z.2.1, restore a z.1 z.2.2)) + +theorem two_copy_law (a : Direction ℓ) : + ((FiniteDistribution.uniform (Rows H ℓ)).product (FiniteDistribution.uniform H)).pushforward + (fun z => (z.1, replace a z.1 z.2)) = fiberPairLaw (H := H) a := by + have h : + ((FiniteDistribution.uniform (Rows H ℓ)).product (FiniteDistribution.uniform H)).pushforward + (pairCoordinates a) = + (FiniteDistribution.uniform (Complement a H)).product + ((FiniteDistribution.uniform H).product (FiniteDistribution.uniform H)) := by + rw [uniform_product, uniform_product, uniform_product, + ← FiniteDistribution.transport_eq_pushforward, UniformConditioning.uniform_transport] + have h' := congrArg + (fun μ : FiniteDistribution (Complement a H × (H × H)) => μ.pushforward + (fun z => (restore a z.1 z.2.1, restore a z.1 z.2.2))) h + rw [FiniteDistribution.pushforward_comp] at h' + simpa only [pairCoordinates_apply, restore_complement, replace, fiberPairLaw] using h' + +theorem resampled_pair_law (μ : FiniteDistribution (Rows H ℓ)) (a : Direction ℓ) : + (μ.product (FiniteDistribution.uniform H)).pushforward + (fun z => (z.1, replace a z.1 z.2)) = + (μ.product (FiniteDistribution.uniform H)).pushforward + (fun z => (z.1, z.1 + BucketSampler.rankOne a.val z.2)) := by + have h := congrArg + (fun ν : FiniteDistribution (Rows H ℓ × H) => ν.pushforward + (fun z => (z.1, z.1 + BucketSampler.rankOne a.val z.2))) + (UniformDifference.difference_law μ (fun S => S (pivot a))) + rw [FiniteDistribution.pushforward_comp] at h + simpa only [UniformDifference.difference, replace_eq] using h + +theorem fiberPairLaw_eq_rankOne (a : Direction ℓ) : + fiberPairLaw (H := H) a = + ((FiniteDistribution.uniform (Rows H ℓ)).product (FiniteDistribution.uniform H)).pushforward + (fun z => (z.1, z.1 + BucketSampler.rankOne a.val z.2)) := by + rw [← two_copy_law] + exact resampled_pair_law (FiniteDistribution.uniform (Rows H ℓ)) a + +end Laws + +section MatrixLaws + +variable {X : Type*} (V : Submodule F2 (X → F2)) + [FiniteDimensional F2 V] [Fintype V] + [Fintype (Module.Dual F2 V →ₗ[F2] (Fin ℓ → F2))] + +theorem matrix_pair_law (a : Direction ℓ) : + (fiberPairLaw (H := V) a).pushforward + (fun z => (EvaluationMatrix.ofRows V z.1, EvaluationMatrix.ofRows V z.2)) = + ((FiniteDistribution.uniform (Module.Dual F2 V →ₗ[F2] (Fin ℓ → F2))).product + (FiniteDistribution.uniform V)).pushforward + (fun z => (z.1, EvaluationMatrix.shift V z.1 a.val z.2)) := by + have hprod : + ((FiniteDistribution.uniform (Rows V ℓ)).product (FiniteDistribution.uniform V)).pushforward + (fun z => (EvaluationMatrix.ofRows V z.1, z.2)) = + (FiniteDistribution.uniform (Module.Dual F2 V →ₗ[F2] (Fin ℓ → F2))).product + (FiniteDistribution.uniform V) := by + rw [uniform_product, uniform_product] + change (FiniteDistribution.uniform (Rows V ℓ × V)).pushforward + (Equiv.prodCongr (EvaluationMatrix.rowsEquiv V).symm (Equiv.refl V)) = _ + rw [← FiniteDistribution.transport_eq_pushforward, UniformConditioning.uniform_transport] + have h := congrArg + (fun μ : FiniteDistribution ((Module.Dual F2 V →ₗ[F2] (Fin ℓ → F2)) × V) => + μ.pushforward (fun z => (z.1, EvaluationMatrix.shift V z.1 a.val z.2))) hprod + rw [FiniteDistribution.pushforward_comp] at h + rw [fiberPairLaw_eq_rankOne, FiniteDistribution.pushforward_comp] + simpa only [ofRows_add_rankOne] using h + +end MatrixLaws +end +end PerfectCompleteness.LowerDirectionFiber + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerProjectedFiberAverage.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerProjectedFiberAverage.lean new file mode 100644 index 0000000000000000000000000000000000000000..016b6f3ece1d410359599a59867dfb8cbc428c35 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerProjectedFiberAverage.lean @@ -0,0 +1,179 @@ +import OAI.Computability.PerfectCompleteness.Decoding.ProjectedFiberUpperSeed +import OAI.Computability.PerfectCompleteness.Foundations.ProjectedFiberBackground + +namespace OAI + +section + +namespace PerfectCompleteness.LowerProjectedFiberAverage + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open WholeCutGrouping +open UniqueGamesTheorem.Foundations.Games + +attribute [local instance] RightDecoder.scalarFintype + +private theorem probability_product {X Y : Type*} [Fintype X] [Fintype Y] + (μ : FiniteDistribution X) (ν : FiniteDistribution Y) (event : X × Y → Bool) : + (μ.product ν).probability event = + μ.expectation (fun x => ν.probability (fun y => event (x, y))) := by + simp only [FiniteDistribution.probability, FiniteDistribution.expectation, + FiniteDistribution.product, Fintype.sum_prod_type, Finset.mul_sum, mul_ite, mul_zero] + +variable {branch rows repeats : Nat → Nat} {n m t : Nat} + (path : Path branch n (m + 1)) + (slots projected : Slots branch n → Fin t → MixedSupport.Slot) + (projection : ∀ leaf j, MixedSupport.Projection (slots leaf j) (projected leaf j)) + (upper : Nodes branch n) (level : Nat) + (hbranch : ∀ k < n, 0 < branch k) + (d : HierarchicalFrozenTables.LowerNodes upper level) + (hnode : WholeArrayInteriorExterior.upperNode path = + HierarchicalLeftDecoder.LowerNode upper level d) + (a : BucketSampler.Direction (rows (m + 1))) + (exterior : Exterior rows repeats path projected) + +local instance rowSpaceFintype : Fintype (NodeEmbedding.RowSpace slots upper) := + Fintype.ofFinite _ + +local instance upperAnswerFintype : + Fintype (HierarchicalAllDecoderTables.UpperAnswer slots upper) := + LeftDecoder.dualFintype (V := NodeEmbedding.RowSpace slots upper) + +abbrev Background := LowerCutFiberDisintegration.Background rows repeats path projected a + +def backgroundLaw : FiniteDistribution (Background (repeats := repeats) path projected a) := + (FiniteDistribution.uniform (LowerCutPairBackground.Complement rows repeats path projected)).product + (FiniteDistribution.uniform (LowerCutFiberDisintegration.Quotient rows path projected a)) + +def baseline (bg : Background (repeats := repeats) path projected a) : Arrays projected rows := + LowerCutFiberDisintegration.arraysAt rows repeats path projected a exterior bg 0 + +variable {r : Nat} (A : ManyGoodRows.RowMap (Block rows upper) r) + +def readForm (s : Nat) (table : ProjectedLowerFiber.UpperTable (rows := rows) slots upper level r) + (arrays : Arrays projected rows) := + (LowerCutDecoderForm.answer slots upper level d hbranch A table s + (ChildBlockProjection.arraysPullback rows projection arrays)).map + (OddListExtraction.multiplicationForm + (HierarchicalDecoderTables.LowerH slots upper level d)) + +def collision (s : Nat) (table : ProjectedLowerFiber.UpperTable (rows := rows) slots upper level r) + (pair : Arrays projected rows × Arrays projected rows) : Bool := + BilinearCollisionTransfer.restrictedCollision + (readForm slots projected projection upper level hbranch d A s table pair.1) + (readForm slots projected projection upper level hbranch d A s table pair.2) + (LinearMap.range (HPullback (ChildBlockProjection.nodeProjection projection + (HierarchicalLeftDecoder.LowerNode upper level d)))) + +def rawCollision (s : Nat) + (table : ProjectedLowerFiber.UpperTable (rows := rows) slots upper level r) : ℝ := + (CutChildGrouping.rawLaw (C := Option (LowerCutPair.Calls rows repeats path)) + (cutSlots path projected) rows).probability + (fun raw => collision slots projected projection upper level hbranch d A s table + (LowerCutPair.arraysPair rows repeats path projected exterior a raw)) + +theorem fiber_collision_eq (s : Nat) + (table : ProjectedLowerFiber.UpperTable (rows := rows) slots upper level r) + (bg : Background path projected a) : + ((FiniteDistribution.uniform (ProjectedLowerFiber.Scalar projected upper level d)).product + (FiniteDistribution.uniform (ProjectedLowerFiber.Scalar projected upper level d))).probability + (ProjectedFiberSquare.restrictedPair slots projected projection upper level hbranch d A + (ProjectedFiberRawPair.direction path upper level d hnode a) + (baseline path projected a exterior bg) s table) = + ((FiniteDistribution.uniform (H (cutSlots path projected))).product + (FiniteDistribution.uniform (H (cutSlots path projected)))).probability + (fun pair => collision slots projected projection upper level hbranch d A s table + (LowerCutFiberDisintegration.arraysAt rows repeats path projected a exterior bg pair.1, + LowerCutFiberDisintegration.arraysAt rows repeats path projected a exterior bg pair.2)) := by + have hprod := FiniteDistribution.product_pushforward + (FiniteDistribution.uniform (H (cutSlots path projected))) + (FiniteDistribution.uniform (H (cutSlots path projected))) + (ProjectedFiberRawPair.scalar path projected upper level d hnode) + (ProjectedFiberRawPair.scalar path projected upper level d hnode) + simp only [ProjectedFiberBackground.scalar_uniform path projected upper level d hnode] at hprod + rw [← hprod, FiniteDistribution.probability_pushforward] + apply congrArg (fun event : H (cutSlots path projected) × H (cutSlots path projected) → Bool => + ((FiniteDistribution.uniform (H (cutSlots path projected))).product + (FiniteDistribution.uniform (H (cutSlots path projected)))).probability event) + funext pair + unfold ProjectedFiberSquare.restrictedPair baseline collision readForm + rw [ProjectedFiberBackground.form_at_fiber rows repeats path projected upper level d hnode a + exterior bg slots projection hbranch A table s pair.1, + ProjectedFiberBackground.form_at_fiber rows repeats path projected upper level d hnode a + exterior bg slots projection hbranch A table s pair.2] + +theorem rawCollision_eq_mean (s : Nat) + (table : ProjectedLowerFiber.UpperTable (rows := rows) slots upper level r) : + rawCollision path slots projected projection upper level hbranch d a exterior A s table = + (backgroundLaw path projected a).expectation (fun bg => + ((FiniteDistribution.uniform (ProjectedLowerFiber.Scalar projected upper level d)).product + (FiniteDistribution.uniform (ProjectedLowerFiber.Scalar projected upper level d))).probability + (ProjectedFiberSquare.restrictedPair slots projected projection upper level hbranch d A + (ProjectedFiberRawPair.direction path upper level d hnode a) + (baseline path projected a exterior bg) s table)) := by + unfold rawCollision + rw [LowerCutFiberDisintegration.probability_pair rows repeats path projected a exterior] + unfold LowerCutFiberDisintegration.law + rw [probability_product] + apply FiniteDistribution.expectation_congr + intro bg + exact (fiber_collision_eq path slots projected projection upper level hbranch d hnode a exterior + A s table bg).symm + +variable + (known : Background path projected a → HiddenBucketBias.VisibleDirection (LinearMap.ker A) → + OwnInputReference.UpperSpace projected upper) + (cut : OwnInputReference.Cut upper (ProjectedLowerFiber.lower upper level d)) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (useful : (bg : HierarchicalMatrixTable.Background (rows := rows) slots upper) → + HierarchicalFrozenTables.QuotientMatrix slots upper level bg → Prop) + (ρ threshold : ℝ) + +def meanSuccess (s : Nat) : ℝ := + (backgroundLaw path projected a).expectation (fun bg => + ProjectedFiberSquare.success slots projected projection upper level hbranch d A + (ProjectedFiberRawPair.direction path upper level d hnode a) + (baseline path projected a exterior bg) (known bg) repeats cut σ useful ρ threshold s + (FiniteDistribution.uniform (ProjectedLowerFiber.Scalar projected upper level d))) + +theorem meanSuccess_square_le (s : Nat) : + meanSuccess path slots projected projection upper level hbranch d hnode a exterior A + known cut σ useful ρ threshold s ^ 2 ≤ + (HierarchicalAllDecoderTables.upperTableLaw slots upper level σ useful r ρ).expectation + (rawCollision path slots projected projection upper level hbranch d a exterior A s) := by + unfold meanSuccess + apply (CollisionAveraging.mean_square_le _ _).trans + calc + _ ≤ (backgroundLaw path projected a).expectation (fun bg => + (HierarchicalAllDecoderTables.upperTableLaw slots upper level σ useful r ρ).expectation + (fun table => + ((FiniteDistribution.uniform (ProjectedLowerFiber.Scalar projected upper level d)).product + (FiniteDistribution.uniform (ProjectedLowerFiber.Scalar projected upper level d))).probability + (ProjectedFiberSquare.restrictedPair slots projected projection upper level hbranch d A + (ProjectedFiberRawPair.direction path upper level d hnode a) + (baseline path projected a exterior bg) s table))) := by + apply Finset.sum_le_sum + intro bg _ + exact mul_le_mul_of_nonneg_left + (ProjectedFiberUpperSeed.success_square_le_upperSeed slots projected upper level d A + (ProjectedFiberRawPair.direction path upper level d hnode a) + (baseline path projected a exterior bg) (known bg) repeats cut σ useful ρ threshold + projection hbranch s (FiniteDistribution.uniform + (ProjectedLowerFiber.Scalar projected upper level d))) + ((backgroundLaw path projected a).nonnegative bg) + _ = _ := by + rw [FiniteDistribution.expectation_comm] + apply FiniteDistribution.expectation_congr + intro table + exact (rawCollision_eq_mean path slots projected projection upper level hbranch d hnode a + exterior A s table).symm + +end +end PerfectCompleteness.LowerProjectedFiberAverage + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerProjectedOriginalSuccessLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerProjectedOriginalSuccessLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..bbfa77d54bd8a7434e32b59c078d0d9084c651c8 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/LowerProjectedOriginalSuccessLemmas.lean @@ -0,0 +1,252 @@ +import OAI.Computability.PerfectCompleteness.Decoding.LowerCutBucketLocality +import OAI.Computability.PerfectCompleteness.Decoding.LowerCutFiberDisintegrationLemmas +import OAI.Computability.PerfectCompleteness.Decoding.LowerProjectedFiberAverage + +namespace OAI + +section + +namespace PerfectCompleteness.LowerProjectedOriginalSuccess + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open WholeCutGrouping +open UniqueGamesTheorem.Foundations.Games + +attribute [local instance] RightDecoder.scalarFintype + +variable {branch rows repeats : Nat → Nat} {n m t : Nat} + (path : Path branch n (m + 1)) + (slots projected : Slots branch n → Fin t → MixedSupport.Slot) + (projection : ∀ leaf j, MixedSupport.Projection (slots leaf j) (projected leaf j)) + (upper : Nodes branch n) (level : Nat) + (hbranch : ∀ k < n, 0 < branch k) + (d : HierarchicalFrozenTables.LowerNodes upper level) + (hnode : WholeArrayInteriorExterior.upperNode path = + HierarchicalLeftDecoder.LowerNode upper level d) + (a : BucketSampler.Direction (rows (m + 1))) + (exterior : Exterior rows repeats path projected) + +local instance rowSpaceFintype : Fintype (NodeEmbedding.RowSpace slots upper) := + Fintype.ofFinite _ + +local instance upperAnswerFintype : + Fintype (HierarchicalAllDecoderTables.UpperAnswer slots upper) := + LeftDecoder.dualFintype (V := NodeEmbedding.RowSpace slots upper) + +variable {r : Nat} (A : ManyGoodRows.RowMap (Block rows upper) r) + (cut : OwnInputReference.Cut upper (ProjectedLowerFiber.lower upper level d)) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (useful : (bg : HierarchicalMatrixTable.Background (rows := rows) slots upper) → + HierarchicalFrozenTables.QuotientMatrix slots upper level bg → Prop) + (ρ threshold : ℝ) + +def kernelSuccess (s : Nat) + (known : HiddenBucketBias.VisibleDirection (LinearMap.ker A) → + OwnInputReference.UpperSpace projected upper) + (arrays : Arrays projected rows) : ℝ := + ((HierarchicalAllDecoderTables.upperKernel slots upper level σ useful r ρ + (LowerCutDecoderInput.actualInput slots upper level + (ChildBlockProjection.arraysPullback rows projection arrays) A)).product + (RightDecoder.law projected rows upper (ProjectedLowerFiber.lower upper level d) + (LinearMap.ker A) (ProjectedFiberRawPair.direction path upper level d hnode a).val + repeats cut σ + (LowerCutOwnInput.ofArrays projected rows upper (ProjectedLowerFiber.lower upper level d) + (LinearMap.ker A) (ProjectedFiberRawPair.direction path upper level d hnode a).val + known arrays) threshold)).probability + (fun pair => ProjectedFiberSquare.highMeeting slots projected projection upper level hbranch d + s pair.1 pair.2) + +variable + (known : LowerProjectedFiberAverage.Background path projected a → + HiddenBucketBias.VisibleDirection (LinearMap.ker A) → + OwnInputReference.UpperSpace projected upper) + +def rawSuccess (s : Nat) : ℝ := + (CutChildGrouping.rawLaw (C := LowerCutPair.Calls rows repeats path) + (cutSlots path projected) rows).expectation (fun raw => + kernelSuccess (repeats := repeats) path slots projected projection upper level hbranch d hnode a A cut σ useful + ρ threshold s + (known (LowerCutSingleFiberDisintegration.coordinates rows repeats path projected a raw).1) + (LowerCutRows.reconstruct rows repeats path projected exterior raw)) + +theorem fiberSuccess_eq (s : Nat) + (bg : LowerProjectedFiberAverage.Background path projected a) : + ProjectedFiberSquare.success slots projected projection upper level hbranch d A + (ProjectedFiberRawPair.direction path upper level d hnode a) + (LowerProjectedFiberAverage.baseline path projected a exterior bg) + (known bg) repeats cut σ useful ρ threshold s + (FiniteDistribution.uniform (ProjectedLowerFiber.Scalar projected upper level d)) = + (FiniteDistribution.uniform (H (cutSlots path projected))).expectation (fun fresh => + kernelSuccess (repeats := repeats) path slots projected projection upper level hbranch d hnode a A cut σ useful + ρ threshold s (known bg) + (LowerCutFiberDisintegration.arraysAt rows repeats path projected a exterior bg fresh)) := by + unfold ProjectedFiberSquare.success + rw [← ProjectedFiberBackground.scalar_uniform path projected upper level d hnode, + FiniteDistribution.expectation_pushforward] + apply FiniteDistribution.expectation_congr + intro fresh + unfold ProjectedLowerFiber.inputAt ProjectedLowerFiber.originalArraysAt + LowerProjectedFiberAverage.baseline kernelSuccess + simp only [← ProjectedFiberBackground.arraysAt_eq_fiber rows repeats path projected upper level d hnode + a exterior bg fresh] + +theorem rawSuccess_eq_meanSuccess (s : Nat) : + rawSuccess path slots projected projection upper level hbranch d hnode a exterior A cut σ useful + ρ threshold known s = + LowerProjectedFiberAverage.meanSuccess path slots projected projection upper level hbranch d hnode + a exterior A known cut σ useful ρ threshold s := by + have h := congrArg + (fun μ : FiniteDistribution + (LowerCutFiberDisintegration.Background rows repeats path projected a × + H (cutSlots path projected)) => + μ.expectation (fun z => + kernelSuccess (repeats := repeats) path slots projected projection upper level hbranch d hnode a A cut σ useful + ρ threshold s (known z.1) + (LowerCutFiberDisintegration.arraysAt rows repeats path projected a exterior z.1 z.2))) + (LowerCutSingleFiberDisintegration.coordinates_law rows repeats path projected a) + rw [FiniteDistribution.expectation_pushforward, FiniteDistribution.expectation_product] at h + simp only [← LowerCutSingleFiberDisintegration.reconstruct_eq_arraysAt + rows repeats path projected a exterior] at h + unfold rawSuccess LowerProjectedFiberAverage.meanSuccess + refine h.trans ?_ + apply FiniteDistribution.expectation_congr + intro bg + exact (fiberSuccess_eq path slots projected projection upper level hbranch d hnode a exterior A cut σ + useful ρ threshold known s bg).symm + +theorem rawSuccess_square_le (s : Nat) : + rawSuccess path slots projected projection upper level hbranch d hnode a exterior A cut σ useful + ρ threshold known s ^ 2 ≤ + (HierarchicalAllDecoderTables.upperTableLaw slots upper level σ useful r ρ).expectation + (LowerProjectedFiberAverage.rawCollision path slots projected projection upper level hbranch d + a exterior A s) := by + rw [rawSuccess_eq_meanSuccess] + exact LowerProjectedFiberAverage.meanSuccess_square_le path slots projected projection upper level hbranch + d hnode a exterior A known cut σ useful ρ threshold s + +end +end PerfectCompleteness.LowerProjectedOriginalSuccess + +end + +section + +namespace PerfectCompleteness.LowerPhysicalFiberSuccess + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open WholeCutGrouping +open UniqueGamesTheorem.Foundations.Games + +attribute [local instance] RightDecoder.scalarFintype + +variable {branch rows repeats : Nat → Nat} {n m t : Nat} + (slots projected : Slots branch n → Fin t → MixedSupport.Slot) + (projection : ∀ leaf j, MixedSupport.Projection (slots leaf j) (projected leaf j)) + (upper : Nodes branch n) + (pDown : Path branch (Nodes.height upper) (m + 1)) + (hproper : m + 1 < Nodes.height upper) + (level : Nat) (hbranch : ∀ k < n, 0 < branch k) + (d : HierarchicalFrozenTables.LowerNodes upper level) + +abbrev path := (Nodes.path upper).append pDown + +variable + (hnode : WholeArrayInteriorExterior.upperNode (path upper pDown) = + HierarchicalLeftDecoder.LowerNode upper level d) + (a : BucketSampler.Direction (rows (m + 1))) + (exterior : Exterior rows repeats (path upper pDown) projected) + +local instance rowSpaceFintype : Fintype (NodeEmbedding.RowSpace slots upper) := + Fintype.ofFinite _ + +local instance upperAnswerFintype : + Fintype (HierarchicalAllDecoderTables.UpperAnswer slots upper) := + LeftDecoder.dualFintype (V := NodeEmbedding.RowSpace slots upper) + +abbrev Raw := CutChildGrouping.Raw (C := LowerCutPair.Calls rows repeats (path upper pDown)) + (cutSlots (path upper pDown) projected) rows + +def tape (raw : Raw (rows := rows) (repeats := repeats) projected upper pDown) : + WholeCutSampler.Tape rows repeats (path upper pDown) projected := + (splitTape rows repeats (path upper pDown) projected).symm (exterior, raw) + +variable {r : Nat} (A : ManyGoodRows.RowMap (Block rows upper) r) + +def knownRaw (raw : Raw (rows := rows) (repeats := repeats) projected upper pDown) : + HiddenBucketBias.VisibleDirection (LinearMap.ker A) → + OwnInputReference.UpperSpace projected upper := + WholeCutSubtree.knownBucketsAtNode rows repeats projected upper pDown hproper (LinearMap.ker A) + (tape projected upper pDown exterior raw) + +def knownBackground + (bg : LowerProjectedFiberAverage.Background (repeats := repeats) (path upper pDown) projected a) : + HiddenBucketBias.VisibleDirection (LinearMap.ker A) → + OwnInputReference.UpperSpace projected upper := + LowerCutBucketLocality.knownBucketsOfComplement rows repeats projected upper pDown hproper + (LinearMap.ker A) exterior bg.1 + +theorem knownRaw_eq + (raw : Raw (rows := rows) (repeats := repeats) projected upper pDown) : + knownRaw projected upper pDown hproper exterior A raw = + knownBackground projected upper pDown hproper a exterior A + (LowerCutSingleFiberDisintegration.coordinates rows repeats (path upper pDown) + projected a raw).1 := by + unfold knownRaw knownBackground tape + simpa only [LowerCutSingleFiberDisintegration.coordinates_complement] using + (LowerCutBucketLocality.knownBucketsAtNode_join rows repeats projected upper pDown hproper + (LinearMap.ker A) exterior raw) + +variable + (cut : OwnInputReference.Cut upper (ProjectedLowerFiber.lower upper level d)) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (useful : (bg : HierarchicalMatrixTable.Background (rows := rows) slots upper) → + HierarchicalFrozenTables.QuotientMatrix slots upper level bg → Prop) + (ρ threshold : ℝ) + +def physicalSuccess (s : Nat) : ℝ := + (CutChildGrouping.rawLaw (C := LowerCutPair.Calls rows repeats (path upper pDown)) + (cutSlots (path upper pDown) projected) rows).expectation (fun raw => + LowerProjectedOriginalSuccess.kernelSuccess (repeats := repeats) (path upper pDown) slots projected projection upper level + hbranch d hnode a A cut σ useful ρ threshold s + (knownRaw projected upper pDown hproper exterior A raw) + (WholeCutSampler.evaluate rows repeats (path upper pDown) projected + (tape projected upper pDown exterior raw))) + +theorem physicalSuccess_eq_rawSuccess (s : Nat) : + physicalSuccess slots projected projection upper pDown hproper level hbranch d hnode a exterior A + cut σ useful ρ threshold s = + LowerProjectedOriginalSuccess.rawSuccess (path upper pDown) slots projected projection upper level + hbranch d hnode a exterior A cut σ useful ρ threshold + (knownBackground projected upper pDown hproper a exterior A) s := by + unfold physicalSuccess LowerProjectedOriginalSuccess.rawSuccess + apply FiniteDistribution.expectation_congr + intro raw + exact congrArg + (fun known => LowerProjectedOriginalSuccess.kernelSuccess (repeats := repeats) (path upper pDown) slots projected + projection upper level hbranch d hnode a A cut σ useful ρ threshold s known + (LowerCutRows.reconstruct rows repeats (path upper pDown) projected exterior raw)) + (knownRaw_eq projected upper pDown hproper a exterior A raw) + +theorem physicalSuccess_square_le (s : Nat) : + physicalSuccess slots projected projection upper pDown hproper level hbranch d hnode a exterior A + cut σ useful ρ threshold s ^ 2 ≤ + (HierarchicalAllDecoderTables.upperTableLaw slots upper level σ useful r ρ).expectation + (LowerProjectedFiberAverage.rawCollision (path upper pDown) slots projected projection upper level + hbranch d a exterior A s) := by + rw [physicalSuccess_eq_rawSuccess] + exact LowerProjectedOriginalSuccess.rawSuccess_square_le (path upper pDown) slots projected projection + upper level hbranch d hnode a exterior A cut σ useful ρ threshold + (knownBackground projected upper pDown hproper a exterior A) s + +end +end PerfectCompleteness.LowerPhysicalFiberSuccess + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/OriginalCutCollision.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/OriginalCutCollision.lean new file mode 100644 index 0000000000000000000000000000000000000000..7403d47a891f482497f1381516b399b14059a942 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/OriginalCutCollision.lean @@ -0,0 +1,114 @@ +import OAI.Computability.PerfectCompleteness.Construction.OriginalCutBucketReplacement +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalAgreementMean +import OAI.Computability.PerfectCompleteness.Foundations.OriginalExtraCutComparison + +namespace OAI + +section + +namespace PerfectCompleteness.OriginalCutCollision + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCutTape +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +noncomputable section + +attribute [local instance] linearMapFintype + +variable {branch : Nat → Nat} {n m k t : Nat} + +abbrev PairRecord (rows : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) := + HierarchicalAgreementMean.PairRecord (rows := rows) slots + (WholeArrayInteriorExterior.upperNode p) + +local instance backgroundFintype (rows : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Fintype (HierarchicalMatrixTable.Background (rows := rows) slots + (WholeArrayInteriorExterior.upperNode p)) := Fintype.ofFinite _ + +local instance rowSpaceFintype (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Fintype (NodeEmbedding.RowSpace slots (WholeArrayInteriorExterior.upperNode p)) := + Fintype.ofFinite _ + +def oldRecord (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : OriginalExtraCutComparison.Record rows repeats p slots) : + OriginalWholeCut.Record rows repeats p slots := + (NumberedUniformCut.numberRecordEquiv rows repeats p slots).symm record.1 + +def oldArrays (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : OriginalExtraCutComparison.Record rows repeats p slots) : Arrays slots rows := + OriginalWholeCut.reconstructRecord rows repeats p slots (oldRecord rows repeats p slots record) + +theorem oldArrays_eq (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : OriginalExtraCutComparison.Record rows repeats p slots) : + oldArrays rows repeats p slots record = + OriginalWholeCutBridge.reconstruct rows repeats p slots record.1 := by + have h := OriginalWholeCutBridge.reconstruct_numberRecord rows repeats p slots + (oldRecord rows repeats p slots record) + have hnumber : OriginalWholeCutBridge.numberRecord rows repeats p slots + (oldRecord rows repeats p slots record) = record.1 := by + change (NumberedUniformCut.numberRecordEquiv rows repeats p slots) + ((NumberedUniformCut.numberRecordEquiv rows repeats p slots).symm record.1) = record.1 + exact (NumberedUniformCut.numberRecordEquiv rows repeats p slots).apply_symm_apply record.1 + rw [hnumber] at h + exact h.symm + +def replacementArrays (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (direction : BucketSampler.Direction (rows (m + 1))) + (record : OriginalExtraCutComparison.Record rows repeats p slots) : Arrays slots rows := + OriginalWholeCut.reconstructRecord rows repeats p slots + (OriginalCutBucketReplacement.replaceRecord rows repeats p slots + (oldRecord rows repeats p slots record) direction record.2) + +theorem replacement_background_eq (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (direction : BucketSampler.Direction (rows (m + 1))) + (record : OriginalExtraCutComparison.Record rows repeats p slots) : + HierarchicalMatrixTable.backgroundOf slots (WholeArrayInteriorExterior.upperNode p) + (replacementArrays rows repeats p slots direction record) = + HierarchicalMatrixTable.backgroundOf slots (WholeArrayInteriorExterior.upperNode p) + (oldArrays rows repeats p slots record) := by + funext node + exact OriginalCutBucketReplacement.reconstructRecord_replace_outside + rows repeats p slots (oldRecord rows repeats p slots record) direction record.2 + node.val node.property + +def pairRecord (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (sample : BucketSampler.Direction (rows (m + 1)) × + OriginalExtraCutComparison.Record rows repeats p slots) : PairRecord rows p slots := + (HierarchicalMatrixTable.backgroundOf slots (WholeArrayInteriorExterior.upperNode p) + (oldArrays rows repeats p slots sample.2), + (NodeEmbedding.matrix (oldArrays rows repeats p slots sample.2) + (WholeArrayInteriorExterior.upperNode p), + NodeEmbedding.matrix (replacementArrays rows repeats p slots sample.1 sample.2) + (WholeArrayInteriorExterior.upperNode p))) + +theorem pair_totalVariation_le {K : Type*} [Fintype K] + (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (ν : FiniteDistribution K) (q : K → Path branch m k) (hbranch : 0 < branch m) + (directions : FiniteDistribution (BucketSampler.Direction (rows (m + 1)))) : + ((directions.product (OriginalExtraCutComparison.actualLaw rows repeats p slots ν q hbranch)).pushforward + (pairRecord rows repeats p slots)).totalVariation + ((directions.product (OriginalExtraCutComparison.referenceLaw rows repeats p slots)).pushforward + (pairRecord rows repeats p slots)) ≤ + Real.sqrt ((ChildBlockCardinality.bound branch m t + (OriginalCutCalls.count rows repeats n (m + 1) + 1) rows : ℝ) ^ 2 / branch m) / 2 := + OriginalExtraCutComparison.observed_totalVariation_le rows repeats p slots ν q hbranch + directions (pairRecord rows repeats p slots) + +end +end PerfectCompleteness.OriginalCutCollision + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/OriginalWholeCutProjection.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/OriginalWholeCutProjection.lean new file mode 100644 index 0000000000000000000000000000000000000000..39efe362e66bd0ab733922000a7d922334c8b07b --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/OriginalWholeCutProjection.lean @@ -0,0 +1,292 @@ +import OAI.Computability.PerfectCompleteness.Decoding.ChildAssemblyProjection +import OAI.Computability.PerfectCompleteness.Decoding.CutGroupedProjectionLemmas +import OAI.Computability.PerfectCompleteness.Sampling.NumberedUniformCut + +namespace OAI + +section + +namespace PerfectCompleteness.OriginalWholeCutProjection + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCutTape OriginalWholeCut +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +noncomputable section + +variable {branch : Nat → Nat} {n m t : Nat} + +theorem exterior_eq (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) : + ∀ (left right : Slots branch n → Fin t → MixedSupport.Slot), + (∀ s, WholeCutExteriorTransport.Outside p s → left s = right s) → + Exterior rows repeats p left = Exterior rows repeats p right := by + induction n generalizing m with + | zero => cases p + | succ n ih => + cases p with + | refl => intro left right hs; rfl + | step i p => + intro left right hs + have hroot := OriginalScalarProjection.scalarExterior_eq repeats (.step i p) left right hs + have hselected := ih p (childSlots left i) (childSlots right i) + (fun s h => hs (i, s) (WholeCutExteriorTransport.outside_selected i p s h)) + have hord : + ((j : RecursiveSampler.OffPath i) → Arrays (childSlots left j.val) rows) = + ((j : RecursiveSampler.OffPath i) → Arrays (childSlots right j.val) rows) := + congrArg (fun A : RecursiveSampler.OffPath i → Type => (j : RecursiveSampler.OffPath i) → A j) + (funext (fun j => congrArg + (fun ss : Slots branch n → Fin t → MixedSupport.Slot => Arrays ss rows) + (WholeCutExteriorTransport.ordinarySlots_eq i p left right hs j))) + exact congrArg₂ (fun A B : Type => A × B) + (congrArg (fun A : Type => BucketSampler.Direction (rows (n + 1)) → A) hroot) + (congrArg₂ (fun A B : Type => A × B) hselected hord) + +def exteriorEquiv (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (left right : Slots branch n → Fin t → MixedSupport.Slot) + (hs : ∀ s, WholeCutExteriorTransport.Outside p s → left s = right s) : + Exterior rows repeats p left ≃ Exterior rows repeats p right := + Equiv.cast (exterior_eq rows repeats p left right hs) + +theorem exteriorEquiv_law (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (left right : Slots branch n → Fin t → MixedSupport.Slot) + (hs : ∀ s, WholeCutExteriorTransport.Outside p s → left s = right s) : + (OriginalWholeCutTape.exteriorLaw rows repeats p left).pushforward + (exteriorEquiv rows repeats p left right hs) = + OriginalWholeCutTape.exteriorLaw rows repeats p right := by + unfold OriginalWholeCutTape.exteriorLaw + rw [← FiniteDistribution.transport_eq_pushforward] + exact UniformConditioning.uniform_transport (exteriorEquiv rows repeats p left right hs) + +private theorem cast_exterior_parts {I J A A' B B' : Type} {C C' : J → Type} + (ha : A = A') (hb : B = B') (hc : ∀ j, C j = C' j) + (h : ((I → A) × (B × ((j : J) → C j))) = ((I → A') × (B' × ((j : J) → C' j)))) + (x : (I → A) × (B × ((j : J) → C j))) : + cast h x = (fun i => cast ha (x.1 i), (cast hb x.2.1, fun j => cast (hc j) (x.2.2 j))) := by + have hC : C = C' := funext hc + cases ha + cases hb + cases hC + rfl + +theorem exteriorEquiv_step (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n (m + 1)) + (left right : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (hs : ∀ s, WholeCutExteriorTransport.Outside (.step i p) s → left s = right s) + (ext : Exterior rows repeats (.step i p) right) : + exteriorEquiv rows repeats (.step i p) right left (fun s h => (hs s h).symm) ext = + (fun bucket => cast + (OriginalScalarProjection.scalarExterior_eq repeats (.step i p) right left + (fun s h => (hs s h).symm)) (ext.1 bucket), + (exteriorEquiv rows repeats p (childSlots right i) (childSlots left i) + (fun s h => (hs (i, s) (WholeCutExteriorTransport.outside_selected i p s h)).symm) ext.2.1, + fun j => cast (congrArg (fun ss => Arrays ss rows) + (WholeCutExteriorTransport.ordinarySlots_eq i p right left + (fun s h => (hs s h).symm) j)) (ext.2.2 j))) := + cast_exterior_parts _ _ _ _ ext + +private theorem reconstruct_root (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n (m + 1)) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ext : Exterior rows repeats (.step i p) slots) + (values : Values rows repeats (.step i p) slots) + (below : BelowArrays rows (.step i p) slots) : + reconstruct rows repeats (.step i p) slots ext values below (.inl ()) = + reconstructBuckets rows repeats (.step i p) slots + (fun bucket terminal => values (.inl (bucket, terminal))) ext.1 := rfl + +private theorem reconstruct_selected (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n (m + 1)) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ext : Exterior rows repeats (.step i p) slots) + (values : Values rows repeats (.step i p) slots) + (below : BelowArrays rows (.step i p) slots) (node : Nodes branch n) : + reconstruct rows repeats (.step i p) slots ext values below (.inr (i, node)) = + reconstruct rows repeats p (childSlots slots i) ext.2.1 + (fun call => values (.inr call)) below node := by + exact congrFun (WholeArraySampler.childrenAt_selected slots rows i + (reconstruct rows repeats p (childSlots slots i) ext.2.1 + (fun call => values (.inr call)) below) ext.2.2) node + +private theorem reconstruct_ordinary (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n (m + 1)) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ext : Exterior rows repeats (.step i p) slots) + (values : Values rows repeats (.step i p) slots) + (below : BelowArrays rows (.step i p) slots) + (j : RecursiveSampler.OffPath i) (node : Nodes branch n) : + reconstruct rows repeats (.step i p) slots ext values below (.inr (j.val, node)) = + ext.2.2 j node := by + exact congrFun (WholeArraySampler.childrenAt_ordinary slots rows i + (reconstruct rows repeats p (childSlots slots i) ext.2.1 + (fun call => values (.inr call)) below) ext.2.2 j) node + +private theorem bucket_evaluate_pullback {ΩL ΩR : Type*} (width : Nat) + (left right : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (evalL : ΩL → H left) (evalR : ΩR → H right) + (tapeL : BucketSampler.Tape width ΩL) (tapeR : BucketSampler.Tape width ΩR) + (heval : ∀ bucket x, (evalL (tapeL bucket)).val x = + (evalR (tapeR bucket)).val (sourceProjection q x)) : + BucketSampler.evaluate width evalL tapeL = + fun row => HPullback q (BucketSampler.evaluate width evalR tapeR row) := by + funext row + apply Subtype.ext + funext x + exact (BucketSampler.evaluate_apply width (H left) evalL tapeL row x).trans + ((Finset.sum_congr rfl (fun bucket _ => + congrArg (fun z : F2 => bucket.val row * z) (heval bucket x))).trans + (BucketSampler.evaluate_apply width (H right) evalR tapeR row + (sourceProjection q x)).symm) + +theorem reconstruct_pullback (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) : + ∀ (left right : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (hs : ∀ s, WholeCutExteriorTransport.Outside p s → left s = right s) + (_ : ∀ s, WholeCutExteriorTransport.Outside p s → ∀ k, + HEq (q s k) (MixedSupport.Projection.keep (left s k))) + (ext : Exterior rows repeats p right) (values : Values rows repeats p right) + (below : BelowArrays rows p right), + reconstruct rows repeats p left + (exteriorEquiv rows repeats p right left (fun s h => (hs s h).symm) ext) + (fun call => HPullback (CutGroupedProjection.cutProjection p q) (values call)) + (fun child => ChildBlockProjection.arraysPullback rows + (ChildAssemblyProjection.childProjection (CutGroupedProjection.cutProjection p q) child) + (below child)) = + ChildBlockProjection.arraysPullback rows q (reconstruct rows repeats p right ext values below) := by + induction n generalizing m with + | zero => cases p + | succ n ih => + cases p with + | refl => + intro left right q hs hk ext values below + funext node row + rcases node with u | ⟨child, node⟩ + · cases u + change BucketSampler.evaluate (rows (n + 1)) id + (fun a => HPullback q (values a)) row = + HPullback q (BucketSampler.evaluate (rows (n + 1)) id values row) + simp only [BucketSampler.evaluate, id_eq, map_sum, map_smul] + rfl + · rfl + | step i p => + intro left right q hs hk ext values below + let leftValues : Values rows repeats (.step i p) left := + fun call => HPullback (CutGroupedProjection.cutProjection (.step i p) q) (values call) + let leftBelow : BelowArrays rows (.step i p) left := + fun child => ChildBlockProjection.arraysPullback rows + (ChildAssemblyProjection.childProjection (CutGroupedProjection.cutProjection (.step i p) q) child) + (below child) + let leftExterior : Exterior rows repeats (.step i p) left := + (fun bucket => cast + (OriginalScalarProjection.scalarExterior_eq repeats (.step i p) right left + (fun s h => (hs s h).symm)) (ext.1 bucket), + (exteriorEquiv rows repeats p (childSlots right i) (childSlots left i) + (fun s h => (hs (i, s) + (WholeCutExteriorTransport.outside_selected i p s h)).symm) ext.2.1, + fun j => cast (congrArg (fun ss => Arrays ss rows) + (WholeCutExteriorTransport.ordinarySlots_eq i p right left + (fun s h => (hs s h).symm) j)) (ext.2.2 j))) + have hext : exteriorEquiv rows repeats (.step i p) right left + (fun s h => (hs s h).symm) ext = leftExterior := + exteriorEquiv_step rows repeats i p left right hs ext + refine (congrArg (fun e : Exterior rows repeats (.step i p) left => + reconstruct rows repeats (.step i p) left e leftValues leftBelow) hext).trans ?_ + funext node row + rcases node with u | ⟨j, node⟩ + · cases u + have hrootL := reconstruct_root rows repeats i p left leftExterior leftValues leftBelow + have hrootR := reconstruct_root rows repeats i p right ext values below + have hbucket := bucket_evaluate_pullback (rows (n + 1)) left right q + (id : H left → H left) (id : H right → H right) + (fun bucket => OriginalScalarReconstruction.reconstruct F2 repeats (.step i p) + (LeafDomain left) (fun terminal => leftValues (.inl (bucket, terminal))) + (leftExterior.1 bucket)) + (fun bucket => OriginalScalarReconstruction.reconstruct F2 repeats (.step i p) + (LeafDomain right) (fun terminal => values (.inl (bucket, terminal))) (ext.1 bucket)) + (fun bucket x => OriginalScalarProjection.reconstruct_pullback_apply repeats (.step i p) + left right q hs hk + (fun terminal => values (.inl (bucket, terminal))) (ext.1 bucket) x) + exact congrFun (hrootL.trans (hbucket.trans + (congrArg (fun f : Fin (rows (n + 1)) → H right => + fun r => HPullback q (f r)) hrootR).symm)) row + · by_cases hji : j = i + · subst j + have hnodeL := congrFun + (reconstruct_selected rows repeats i p left leftExterior leftValues leftBelow node) row + have hnodeR := congrFun + (reconstruct_selected rows repeats i p right ext values below node) row + have hchild := congrFun (congrFun + (ih p (childSlots left i) (childSlots right i) (fun s k => q (i, s) k) + (fun s h => hs (i, s) (WholeCutExteriorTransport.outside_selected i p s h)) + (fun s h k => hk (i, s) (WholeCutExteriorTransport.outside_selected i p s h) k) + ext.2.1 (fun call => values (.inr call)) below) node) row + exact hnodeL.trans (hchild.trans + (congrArg (HPullback (ChildBlockProjection.nodeProjection q (.inr (i, node)))) + hnodeR).symm) + · have hnodeL := congrFun + (reconstruct_ordinary rows repeats i p left leftExterior leftValues leftBelow ⟨j, hji⟩ node) row + have hnodeR := congrFun + (reconstruct_ordinary rows repeats i p right ext values below ⟨j, hji⟩ node) row + have hcast := CutProjectionGeometry.arraysPullback_eq_cast rows + (childSlots left j) (childSlots right j) (fun s k => q (j, s) k) + (WholeCutExteriorTransport.ordinarySlots_eq i p left right hs ⟨j, hji⟩) + (fun s k => hk (j, s) (WholeCutExteriorTransport.outside_ordinary i p ⟨j, hji⟩ s) k) + (ext.2.2 ⟨j, hji⟩) + have hcastRow := congrFun (congrFun hcast.symm node) row + exact hnodeL.trans (hcastRow.trans + (congrArg (HPullback (ChildBlockProjection.nodeProjection q (.inr (j, node)))) + hnodeR).symm) + +theorem reconstruct_numbered_pullback (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (left right : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (hs : ∀ s, WholeCutExteriorTransport.Outside p s → left s = right s) + (hk : ∀ s, WholeCutExteriorTransport.Outside p s → ∀ k, + HEq (q s k) (MixedSupport.Projection.keep (left s k))) + (record : OriginalWholeCutBridge.NumberedRecord rows repeats p right) : + OriginalWholeCutBridge.reconstruct rows repeats p left + (exteriorEquiv rows repeats p right left (fun s h => (hs s h).symm) record.1, + ChildAssemblyProjection.assembledPullback rows (CutGroupedProjection.cutProjection p q) record.2) = + ChildBlockProjection.arraysPullback rows q + (OriginalWholeCutBridge.reconstruct rows repeats p right record) := + reconstruct_pullback rows repeats p left right q hs hk record.1 + (fun call => record.2.1 (callNumbering rows repeats p call)) record.2.2 + +theorem fixed_projected_law (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (left right : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (hs : ∀ s, WholeCutExteriorTransport.Outside p s → left s = right s) + (hk : ∀ s, WholeCutExteriorTransport.Outside p s → ∀ k, + HEq (q s k) (MixedSupport.Projection.keep (left s k))) : + ((OriginalWholeCutTape.exteriorLaw rows repeats p left).product + ((FiniteDistribution.uniform (CutChildGrouping.Assembled + (C := Fin (OriginalCutCalls.count rows repeats n (m + 1))) (cutSlots p right) rows)).pushforward + (ChildAssemblyProjection.assembledPullback rows (CutGroupedProjection.cutProjection p q)))).pushforward + (OriginalWholeCutBridge.reconstruct rows repeats p left) = + (WholeArraySampler.law rows repeats p right).pushforward (ChildBlockProjection.arraysPullback rows q) := by + rw [← exteriorEquiv_law rows repeats p right left (fun s h => (hs s h).symm), + ← FiniteDistribution.product_pushforward + (OriginalWholeCutTape.exteriorLaw rows repeats p right) + (FiniteDistribution.uniform (CutChildGrouping.Assembled + (C := Fin (OriginalCutCalls.count rows repeats n (m + 1))) (cutSlots p right) rows)) + (exteriorEquiv rows repeats p right left (fun s h => (hs s h).symm)) + (ChildAssemblyProjection.assembledPullback rows (CutGroupedProjection.cutProjection p q)), + FiniteDistribution.pushforward_comp] + have hmap : + (fun record : OriginalWholeCutBridge.NumberedRecord rows repeats p right => + OriginalWholeCutBridge.reconstruct rows repeats p left + (exteriorEquiv rows repeats p right left (fun s h => (hs s h).symm) record.1, + ChildAssemblyProjection.assembledPullback rows (CutGroupedProjection.cutProjection p q) record.2)) = + (fun record => ChildBlockProjection.arraysPullback rows q + (OriginalWholeCutBridge.reconstruct rows repeats p right record)) := + funext (reconstruct_numbered_pullback rows repeats p left right q hs hk) + rw [hmap, ← FiniteDistribution.pushforward_comp, + NumberedUniformCut.reconstruct_product_uniform] + +end +end PerfectCompleteness.OriginalWholeCutProjection + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/ProjectedFiberUpperSeed.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/ProjectedFiberUpperSeed.lean new file mode 100644 index 0000000000000000000000000000000000000000..6e441cefb37058e2e7745604d0b9be64f1d5088e --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/ProjectedFiberUpperSeed.lean @@ -0,0 +1,78 @@ +import OAI.Computability.PerfectCompleteness.Foundations.ProjectedFiberSquare + +namespace OAI + +section + +namespace PerfectCompleteness.ProjectedFiberUpperSeed + +noncomputable section + +open scoped BigOperators Classical +open TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open ProjectedLowerFiber ProjectedFiberSquare + +attribute [local instance] RightDecoder.scalarFintype + +variable {branch rows : Nat → Nat} {n t : Nat} + (slots projected : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (upper : Nodes branch n) (level : Nat) + (d : HierarchicalFrozenTables.LowerNodes upper level) + +local instance rowSpaceFintype : Fintype (NodeEmbedding.RowSpace slots upper) := + Fintype.ofFinite _ + +local instance upperAnswerFintype : + Fintype (HierarchicalAllDecoderTables.UpperAnswer slots upper) := + LeftDecoder.dualFintype (V := NodeEmbedding.RowSpace slots upper) + +variable {r : Nat} (A : ManyGoodRows.RowMap (Block rows upper) r) + (a : Direction (rows := rows) upper level d) (arrays : Arrays projected rows) + (known : HiddenBucketBias.VisibleDirection (LinearMap.ker A) → + OwnInputReference.UpperSpace projected upper) + (repeats : Nat → Nat) (cut : OwnInputReference.Cut upper (lower upper level d)) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (useful : (bg : HierarchicalMatrixTable.Background (rows := rows) slots upper) → + HierarchicalFrozenTables.QuotientMatrix slots upper level bg → Prop) + (ρ threshold : ℝ) + +theorem seed_mean_ignore_right (f : UpperTable (rows := rows) slots upper level r → ℝ) : + (seedLaw slots projected upper level d A a arrays known repeats cut σ useful ρ threshold).expectation + (fun seed => f seed.1) = + (HierarchicalAllDecoderTables.upperTableLaw slots upper level σ useful r ρ).expectation f := by + unfold seedLaw + rw [FiniteDistribution.expectation_product] + apply FiniteDistribution.expectation_congr + intro table + unfold FiniteDistribution.expectation + change (∑ x, (rightLaw projected upper level d A a arrays known repeats cut σ threshold).weight x * + f table) = f table + rw [← Finset.sum_mul, + (rightLaw projected upper level d A a arrays known repeats cut σ threshold).normalized, + one_mul] + +variable (projection : ∀ leaf j, MixedSupport.Projection (slots leaf j) (projected leaf j)) + (hbranch : ∀ k < n, 0 < branch k) + +theorem success_square_le_upperSeed (s : Nat) + (ν : FiniteDistribution (Scalar projected upper level d)) : + success slots projected projection upper level hbranch d A a arrays known + repeats cut σ useful ρ threshold s ν ^ 2 ≤ + (HierarchicalAllDecoderTables.upperTableLaw slots upper level σ useful r ρ).expectation + (fun table => (ν.product ν).probability + (restrictedPair slots projected projection upper level hbranch d A a arrays s table)) := by + have h := success_square_le slots projected projection upper level hbranch d A a arrays known + repeats cut σ useful ρ threshold s ν + calc + _ ≤ _ := h + _ = _ := seed_mean_ignore_right slots projected upper level d A a arrays known + repeats cut σ useful ρ threshold (fun table => (ν.product ν).probability + (restrictedPair slots projected projection upper level hbranch d A a arrays s table)) + +end +end PerfectCompleteness.ProjectedFiberUpperSeed + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/ProjectedLowerFiber.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/ProjectedLowerFiber.lean new file mode 100644 index 0000000000000000000000000000000000000000..103e3aebd668acc682bd1dafe002cc9f650b490b --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/ProjectedLowerFiber.lean @@ -0,0 +1,134 @@ +import OAI.Computability.PerfectCompleteness.Construction.ProjectedNodeEmbedding +import OAI.Computability.PerfectCompleteness.Decoding.RightDecoderLemmas +import OAI.Computability.PerfectCompleteness.Machines.LowerCutDecoderInput +import OAI.Computability.PerfectCompleteness.Machines.LowerCutOwnInput + +namespace OAI + +section + +namespace PerfectCompleteness.ProjectedLowerFiber + +noncomputable section + +open scoped Classical +open TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +variable {branch rows : Nat → Nat} {n t : Nat} + (slots projected : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (projection : ∀ leaf j, MixedSupport.Projection (slots leaf j) (projected leaf j)) + (upper : Nodes branch n) (level : Nat) + (d : HierarchicalFrozenTables.LowerNodes upper level) + +abbrev lower := HierarchicalLeftDecoder.LowerNode upper level d +abbrev Scalar := H (nodeSlots projected (lower upper level d)) +abbrev Direction := BucketSampler.Direction (rows (Nodes.height (lower upper level d))) + +def arraysAt (a : Direction (rows := rows) upper level d) + (arrays : Arrays projected rows) (fresh : Scalar projected upper level d) : + Arrays projected rows := + Function.update arrays (lower upper level d) + (LowerDirectionFiber.replace a (arrays (lower upper level d)) fresh) + +theorem rightInput_fixed {r : Nat} + (A : ManyGoodRows.RowMap (Block rows upper) r) + (a : Direction (rows := rows) upper level d) + (known : HiddenBucketBias.VisibleDirection (LinearMap.ker A) → + OwnInputReference.UpperSpace projected upper) + (arrays : Arrays projected rows) (fresh : Scalar projected upper level d) : + LowerCutOwnInput.ofArrays projected rows upper (lower upper level d) + (LinearMap.ker A) a.val known (arraysAt projected upper level d a arrays fresh) = + LowerCutOwnInput.ofArrays projected rows upper (lower upper level d) + (LinearMap.ker A) a.val known arrays := + LowerCutOwnInput.ofArrays_update projected rows upper (lower upper level d) + (LinearMap.ker A) a known arrays fresh + +theorem rightLaw_fixed {r : Nat} + (A : ManyGoodRows.RowMap (Block rows upper) r) + (a : Direction (rows := rows) upper level d) + (known : HiddenBucketBias.VisibleDirection (LinearMap.ker A) → + OwnInputReference.UpperSpace projected upper) + (arrays : Arrays projected rows) (fresh : Scalar projected upper level d) + (repeats : Nat → Nat) (cut : OwnInputReference.Cut upper (lower upper level d)) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) (threshold : ℝ) : + RightDecoder.law projected rows upper (lower upper level d) (LinearMap.ker A) a.val + repeats cut σ + (LowerCutOwnInput.ofArrays projected rows upper (lower upper level d) + (LinearMap.ker A) a.val known (arraysAt projected upper level d a arrays fresh)) threshold = + RightDecoder.law projected rows upper (lower upper level d) (LinearMap.ker A) a.val + repeats cut σ + (LowerCutOwnInput.ofArrays projected rows upper (lower upper level d) + (LinearMap.ker A) a.val known arrays) threshold := by + rw [rightInput_fixed projected upper level d A a known arrays fresh] + +def originalArraysAt (a : Direction (rows := rows) upper level d) + (arrays : Arrays projected rows) (fresh : Scalar projected upper level d) : + Arrays slots rows := + ChildBlockProjection.arraysPullback rows projection + (arraysAt projected upper level d a arrays fresh) + +theorem originalArraysAt_eq_update + (a : Direction (rows := rows) upper level d) + (arrays : Arrays projected rows) (fresh : Scalar projected upper level d) : + originalArraysAt slots projected projection upper level d a arrays fresh = + Function.update (ChildBlockProjection.arraysPullback rows projection arrays) + (lower upper level d) + (fun i => HPullback (ChildBlockProjection.nodeProjection projection (lower upper level d)) + (LowerDirectionFiber.replace a (arrays (lower upper level d)) fresh i)) := by + funext node + by_cases hnode : node = lower upper level d + · subst node + funext i + simp only [originalArraysAt, ChildBlockProjection.arraysPullback_apply, + arraysAt, Function.update_self] + · funext i + simp only [originalArraysAt, ChildBlockProjection.arraysPullback_apply, + arraysAt, Function.update_of_ne hnode] + +def inputAt {r : Nat} (A : ManyGoodRows.RowMap (Block rows upper) r) + (a : Direction (rows := rows) upper level d) + (arrays : Arrays projected rows) (fresh : Scalar projected upper level d) : + HierarchicalAllDecoderTables.Input (rows := rows) slots upper level r := + LowerCutDecoderInput.actualInput slots upper level + (originalArraysAt slots projected projection upper level d a arrays fresh) A + +theorem inputAt_eq_lowerInput {r : Nat} (A : ManyGoodRows.RowMap (Block rows upper) r) + (a : Direction (rows := rows) upper level d) + (arrays : Arrays projected rows) (fresh : Scalar projected upper level d) : + inputAt slots projected projection upper level d A a arrays fresh = + HierarchicalLowerMatrixInput.input slots upper level + (HierarchicalMatrixTable.backgroundOf slots upper + (ChildBlockProjection.arraysPullback rows projection arrays)) d + (NodeEmbedding.matrix (ChildBlockProjection.arraysPullback rows projection arrays) upper) A + (EvaluationMatrix.ofRows (HierarchicalDecoderTables.LowerH slots upper level d) + (fun i => HPullback (ChildBlockProjection.nodeProjection projection (lower upper level d)) + (LowerDirectionFiber.replace a (arrays (lower upper level d)) fresh i))) := by + unfold inputAt + rw [originalArraysAt_eq_update] + exact LowerCutDecoderInput.actualInput_update slots upper level + (ChildBlockProjection.arraysPullback rows projection arrays) d A _ + +abbrev UpperTable (r : Nat) := + HierarchicalAllDecoderTables.Input (rows := rows) slots upper level r → + HierarchicalAllDecoderTables.UpperAnswer slots upper + +def upperAt {r : Nat} (A : ManyGoodRows.RowMap (Block rows upper) r) + (a : Direction (rows := rows) upper level d) (arrays : Arrays projected rows) + (table : UpperTable (rows := rows) slots upper level r) + (fresh : Scalar projected upper level d) : + HierarchicalAllDecoderTables.UpperAnswer slots upper := + table (inputAt slots projected projection upper level d A a arrays fresh) + +theorem upperTarget_eq_dualMap + (q : HierarchicalAllDecoderTables.UpperAnswer slots upper) : + DecoderSourcePullback.upperTarget projection upper q = + (ProjectedNodeEmbedding.intoOriginal projection upper).dualMap q := + (ProjectedNodeEmbedding.dualMap_eq_upperTarget projection upper q).symm + +end +end PerfectCompleteness.ProjectedLowerFiber + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/ProjectedNativeCollision.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/ProjectedNativeCollision.lean new file mode 100644 index 0000000000000000000000000000000000000000..e6ff8ed8ce16746d15900b66b4540ca6f39b03f7 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/ProjectedNativeCollision.lean @@ -0,0 +1,146 @@ +import OAI.Computability.PerfectCompleteness.Algebra.BilinearWitnessLemmas +import OAI.Computability.PerfectCompleteness.Construction.ChildUnmarkedSpace +import OAI.Computability.PerfectCompleteness.Construction.ProjectedNodeEmbedding +import OAI.Computability.PerfectCompleteness.Construction.SourceChildKernelLemmas +import OAI.Computability.PerfectCompleteness.Decoding.HierarchicalDecoderTables + +namespace OAI + +section + +namespace PerfectCompleteness.ProjectedNativeCollision + +noncomputable section + +open scoped Classical +open RecursiveSpaces TreeSourceSpaces HierarchicalArrays PointwiseSpaces + +variable {branch : Nat → Nat} {n t : Nat} + {slots projected : Slots branch n → Fin t → MixedSupport.Slot} + (p : ∀ leaf k, MixedSupport.Projection (slots leaf k) (projected leaf k)) + (upper : Nodes branch n) (level : Nat) + (hbranch : ∀ k < n, 0 < branch k) + (d : HierarchicalFrozenTables.LowerNodes upper level) + +theorem form_eq_on_pullbacks + (q0 q1 : Module.Dual F2 (NodeEmbedding.RowSpace slots upper)) + (htarget : DecoderSourcePullback.upperTarget p upper q0 = + DecoderSourcePullback.upperTarget p upper q1) + (f g : H (nodeSlots projected (HierarchicalLeftDecoder.LowerNode upper level d))) : + OddListExtraction.multiplicationForm + (HierarchicalDecoderTables.LowerH slots upper level d) + (HierarchicalLeftDecoder.output slots upper level hbranch d q0) + (HPullback (ChildBlockProjection.nodeProjection p + (HierarchicalLeftDecoder.LowerNode upper level d)) f) + (HPullback (ChildBlockProjection.nodeProjection p + (HierarchicalLeftDecoder.LowerNode upper level d)) g) = + OddListExtraction.multiplicationForm + (HierarchicalDecoderTables.LowerH slots upper level d) + (HierarchicalLeftDecoder.output slots upper level hbranch d q1) + (HPullback (ChildBlockProjection.nodeProjection p + (HierarchicalLeftDecoder.LowerNode upper level d)) f) + (HPullback (ChildBlockProjection.nodeProjection p + (HierarchicalLeftDecoder.LowerNode upper level d)) g) := by + have h0 := DecoderSourcePullback.form_upperTarget p upper level hbranch d + (DecoderSourcePullback.selectedCut upper level d) q0 f g + have h1 := DecoderSourcePullback.form_upperTarget p upper level hbranch d + (DecoderSourcePullback.selectedCut upper level d) q1 f g + rw [htarget] at h0 + exact h0.symm.trans h1 + +theorem decode_eq_some_of_high (s : Nat) + (q : Module.Dual F2 (NodeEmbedding.RowSpace slots upper)) + (hhigh : s < HierarchicalDecoderTables.fullRank slots upper level d + (HierarchicalLeftDecoder.output slots upper level hbranch d q)) : + HierarchicalDecoderTables.decode slots upper level hbranch d s q = + some (HierarchicalLeftDecoder.output slots upper level hbranch d q) := by + exact ite_eq_right (Nat.not_le.mpr hhigh) + +theorem two_high_hits_restricted (s : Nat) + (q0 q1 : Module.Dual F2 (NodeEmbedding.RowSpace slots upper)) + (right : Module.Dual F2 (OwnInputReference.UpperSpace projected upper)) + (hrank0 : s < HierarchicalDecoderTables.fullRank slots upper level d + (HierarchicalLeftDecoder.output slots upper level hbranch d q0)) + (hrank1 : s < HierarchicalDecoderTables.fullRank slots upper level d + (HierarchicalLeftDecoder.output slots upper level hbranch d q1)) + (hhit0 : DecoderSourcePullback.upperTarget p upper q0 = right) + (hhit1 : DecoderSourcePullback.upperTarget p upper q1 = right) : + BilinearCollisionTransfer.restrictedCollision + ((HierarchicalDecoderTables.decode slots upper level hbranch d s q0).map + (OddListExtraction.multiplicationForm + (HierarchicalDecoderTables.LowerH slots upper level d))) + ((HierarchicalDecoderTables.decode slots upper level hbranch d s q1).map + (OddListExtraction.multiplicationForm + (HierarchicalDecoderTables.LowerH slots upper level d))) + (LinearMap.range (HPullback (ChildBlockProjection.nodeProjection p + (HierarchicalLeftDecoder.LowerNode upper level d)))) = true := by + rw [decode_eq_some_of_high upper level hbranch d s q0 hrank0, + decode_eq_some_of_high upper level hbranch d s q1 hrank1] + apply decide_eq_true + refine ⟨_, _, rfl, rfl, ?_⟩ + rintro v ⟨f, rfl⟩ w ⟨g, rfl⟩ + exact form_eq_on_pullbacks p upper level hbranch d q0 q1 + (hhit0.trans hhit1.symm) f g + +theorem two_high_hits_restricted_on (s : Nat) + (q0 q1 : Module.Dual F2 (NodeEmbedding.RowSpace slots upper)) + (right : Module.Dual F2 (OwnInputReference.UpperSpace projected upper)) + (hrank0 : s < HierarchicalDecoderTables.fullRank slots upper level d + (HierarchicalLeftDecoder.output slots upper level hbranch d q0)) + (hrank1 : s < HierarchicalDecoderTables.fullRank slots upper level d + (HierarchicalLeftDecoder.output slots upper level hbranch d q1)) + (hhit0 : DecoderSourcePullback.upperTarget p upper q0 = right) + (hhit1 : DecoderSourcePullback.upperTarget p upper q1 = right) + (U : Submodule F2 (HierarchicalDecoderTables.LowerH slots upper level d)) + (hU : U ≤ LinearMap.range (HPullback (ChildBlockProjection.nodeProjection p + (HierarchicalLeftDecoder.LowerNode upper level d)))) : + BilinearCollisionTransfer.restrictedCollision + ((HierarchicalDecoderTables.decode slots upper level hbranch d s q0).map + (OddListExtraction.multiplicationForm + (HierarchicalDecoderTables.LowerH slots upper level d))) + ((HierarchicalDecoderTables.decode slots upper level hbranch d s q1).map + (OddListExtraction.multiplicationForm + (HierarchicalDecoderTables.LowerH slots upper level d))) U = true := by + obtain ⟨F, G, hF, hG, hFG⟩ := of_decide_eq_true + (two_high_hits_restricted p upper level hbranch d s q0 q1 right + hrank0 hrank1 hhit0 hhit1) + apply decide_eq_true + exact ⟨F, G, hF, hG, fun v hv w hw => hFG v (hU hv) w (hU hw)⟩ + +section SourceKernel + +variable {rows : Nat → Nat} {v m k : Nat} {C : Type*} [Fintype C] + (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch k) → Slots branch k) + (sources : SourceChildKernel.Sources (m := m) (t := t) designated) + (raw : (i : Fin (branch k)) → + SourceChildKernel.Raw (C := C) (t := t) rows clauses designated i) + +theorem parent_childSlots_of_unmarked (i : Fin (branch k)) + (hi : SourceChildKernel.rawProjected rows clauses designated i (raw i) = false) : + childSlots (SourceChildKernel.parentRightSlots rows clauses designated sources raw) i = + childSlots (SourceChildKernel.parentLeftSlots clauses designated sources) i := by + funext leaf a + change SourceChildKernel.mixedSlots clauses designated i (sources i) + (SourceChildKernel.rawProjected rows clauses designated i (raw i)) leaf a = + SourceChildKernel.nativeSlots clauses designated i (sources i) leaf a + rw [hi] + rfl + +theorem parent_unmarked_le_range : + ChildUnmarkedSpace.space + (SourceChildKernel.parentLeftSlots clauses designated sources) + (fun i => SourceChildKernel.rawProjected rows clauses designated i (raw i)) ≤ + LinearMap.range (HPullback + (SourceChildKernel.parentProjection rows clauses designated sources raw)) := by + apply ChildUnmarkedSpace.space_le_projected_range + exact parent_childSlots_of_unmarked clauses designated sources raw + +end SourceKernel + +end +end PerfectCompleteness.ProjectedNativeCollision + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/ProjectedRawDecoderLaw.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/ProjectedRawDecoderLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..3f5e8b595f320cda266b27a3eeeff3ce8974e519 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/ProjectedRawDecoderLaw.lean @@ -0,0 +1,80 @@ +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalProjectedSliceLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.ProjectedRawDecoderLaw + +noncomputable section + +open scoped Classical +open TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +variable {branch : Nat → Nat} {n t : Nat} + (slots projected : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (projection : ∀ s j, MixedSupport.Projection (slots s j) (projected s j)) + (rows : Nat → Nat) (upper lower : Nodes branch n) (level : Nat) + +local instance upperDualFintype : Fintype (Module.Dual F2 (NodeEmbedding.RowSpace slots upper)) := + LeftDecoder.dualFintype (V := NodeEmbedding.RowSpace slots upper) + +theorem advice_eq_visible + (background : HierarchicalMatrixTable.Background (rows := rows) slots upper) + {r : Nat} (A : ManyGoodRows.RowMap (Block rows upper) r) + (repeats : Nat → Nat) (cut : OwnInputReference.Cut upper lower) + (raw : OwnInputReference.RawSample projected rows upper lower (LinearMap.ker A) repeats cut) : + A.comp (MatrixRowQuotient.projectMatrix + (HierarchicalFrozenTables.knownRows slots upper level background) + (NodeEmbedding.matrix + (ProjectedRawAssembly.arrays slots projected projection rows upper lower + (LinearMap.ker A) repeats cut raw) upper)) = + A.comp (MatrixRowQuotient.projectMatrix + (HierarchicalFrozenTables.knownRows slots upper level background) + (HierarchicalProjectedSlice.visibleMatrix slots projected projection upper A + (HierarchicalProjectedRawPrediction.known projected rows upper lower A repeats cut raw.2))) := by + rw [ProjectedRawAssembly.matrix_arrays] + exact TensorRowAdvice.rowAdvice_projectMatrix + (ProjectedNodeEmbedding.intoOriginal projection upper) (LinearMap.ker A) A le_rfl + (HierarchicalFrozenTables.knownRows slots upper level background) + (ProjectedRawAssembly.visibleMatrix slots projected projection rows upper lower + (LinearMap.ker A) repeats cut raw.2) + (OwnInputAffineSlice.hiddenOutput projected rows upper lower (LinearMap.ker A) repeats cut raw) + +variable {Ω : Type*} [Fintype Ω] + (original : FiniteDistribution Ω) (originalArrays : Ω → Arrays slots rows) + (lowerEvent : Ω → Bool) (κ : ℝ) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + {r : Nat} (ρ : ℝ) (A : ManyGoodRows.RowMap (Block rows upper) r) + (repeats : Nat → Nat) (cut : OwnInputReference.Cut upper lower) + +theorem adviceLaw_eq_leftLaw + (raw : OwnInputReference.RawSample projected rows upper lower (LinearMap.ker A) repeats cut) : + let actual := ProjectedRawAssembly.arrays slots projected projection rows upper lower + (LinearMap.ker A) repeats cut raw + let background := HierarchicalMatrixTable.backgroundOf slots upper actual + HierarchicalLeftDecoder.adviceLaw slots upper level background σ + (HierarchicalProjectedMeeting.useful slots upper level background + original originalArrays lowerEvent κ) r ρ A + (A.comp (MatrixRowQuotient.projectMatrix + (HierarchicalFrozenTables.knownRows slots upper level background) + (NodeEmbedding.matrix actual upper))) = + HierarchicalProjectedMeeting.leftLaw slots projected projection upper level + (HierarchicalProjectedRawPrediction.visibleBackground + slots projected projection rows upper lower A repeats cut raw.2) + original originalArrays lowerEvent κ σ ρ A + (HierarchicalProjectedRawPrediction.known projected rows upper lower A repeats cut raw.2) := by + dsimp only + rw [ProjectedRawAssembly.background_arrays] + unfold HierarchicalProjectedMeeting.leftLaw + rw [advice_eq_visible slots projected projection rows upper lower level + (ProjectedRawAssembly.background slots projected projection rows upper lower + (LinearMap.ker A) repeats cut raw.2) A repeats cut raw] + +end +end PerfectCompleteness.ProjectedRawDecoderLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/ProjectedUpperPair.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/ProjectedUpperPair.lean new file mode 100644 index 0000000000000000000000000000000000000000..9d231e26c6c46c2e5f9e63672c19c762cbea3a57 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/ProjectedUpperPair.lean @@ -0,0 +1,148 @@ +import OAI.Computability.PerfectCompleteness.Decoding.UpperScalarCutProjection +import OAI.Computability.PerfectCompleteness.Decoding.UpperScalarFreshProjectionLemmas +import OAI.Computability.PerfectCompleteness.Foundations.ProjectedWholeCut + +namespace OAI + +section + +namespace PerfectCompleteness.ProjectedUpperPair + +noncomputable section + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCutTape WholeArrayInteriorExterior +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) +open scoped BigOperators Classical + +attribute [local instance] linearMapFintype + +private theorem product_mixture_right {A B C : Type*} + [Fintype A] [Fintype B] [Fintype C] + (μ : FiniteDistribution A) (ν : FiniteDistribution B) + (P : B → FiniteDistribution C) : + μ.product (ν.mixture P) = ν.mixture (fun b => μ.product (P b)) := by + apply FiniteDistribution.eq_of_weight_eq + intro x + change μ.weight x.1 * (∑ b, ν.weight b * (P b).weight x.2) = + ∑ b, ν.weight b * (μ.weight x.1 * (P b).weight x.2) + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro b _ + ring + +private theorem lifted_assembled_congr {branch : Nat → Nat} {m t : Nat} + (calls : Nat) (rows : Nat → Nat) + (left right right' : Slots branch (m + 1) → Fin t → MixedSupport.Slot) + (q : ∀ s a, MixedSupport.Projection (left s a) (right s a)) + (q' : ∀ s a, MixedSupport.Projection (left s a) (right' s a)) + (hright : right = right') (hq : ∀ s a, HEq (q s a) (q' s a)) : + (FiniteDistribution.uniform (CutChildGrouping.Assembled (C := Fin calls) right rows)).pushforward + (ChildAssemblyProjection.assembledPullback rows q) = + (FiniteDistribution.uniform (CutChildGrouping.Assembled (C := Fin calls) right' rows)).pushforward + (ChildAssemblyProjection.assembledPullback rows q') := by + cases hright + have heq : q = q' := by + funext s a + exact eq_of_heq (hq s a) + cases heq + rfl + +variable {branch : Nat → Nat} {n j i t : Nat} + +local instance backgroundFintype (rows : Nat → Nat) (p : Path branch n (j + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Fintype (HierarchicalMatrixTable.Background (rows := rows) slots (upperNode p)) := + Fintype.ofFinite _ + +local instance rowSpaceFintype (p : Path branch n (j + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Fintype (NodeEmbedding.RowSpace slots (upperNode p)) := Fintype.ofFinite _ + +variable (p : Path branch n (j + 1)) (r : Path branch (j + 1) (i + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + {Z : Fin (branch i) → Type*} [∀ child, Fintype (Z child)] + (projected : (child : Fin (branch i)) → Z child → Slots branch i → Fin t → MixedSupport.Slot) + (projection : ∀ child z s a, MixedSupport.Projection + (childSlots (cutSlots (p.append r) slots) child s a) (projected child z s a)) + +omit [∀ child, Fintype (Z child)] in +theorem fixed_law (rows repeats : Nat → Nat) (hproper : i + 1 < j + 1) + (directions : FiniteDistribution (BucketSampler.Direction (rows (j + 1)))) + (choices : ProjectedCutChoices.Choices (Z := Z)) : + UpperScalarPairComparison.pairLaw rows repeats p r slots directions + ((FiniteDistribution.uniform (CutChildGrouping.Assembled + (C := Fin (UpperScalarCutCalls.count rows repeats n (j + 1) (i + 1))) + (ProjectedCutChoices.selectedSlots (cutSlots (p.append r) slots) projected choices) rows)).pushforward + (ChildAssemblyProjection.assembledPullback rows + (ProjectedCutChoices.selectedProjection (cutSlots (p.append r) slots) + projected projection choices))) = + (directions.product + ((WholeArraySampler.tapeLaw rows repeats (p.append r) + (ProjectedWholeCut.fullSlots (p.append r) slots projected choices)).product + (RecursiveSampler.law F2 repeats r + (LeafDomain (cutSlots p + (ProjectedWholeCut.fullSlots (p.append r) slots projected choices)))))).pushforward + (UpperScalarCutProjection.stoppedProjectedPair rows repeats p r hproper slots + (ProjectedWholeCut.fullSlots (p.append r) slots projected choices) + (ProjectedWholeCut.fullProjection (p.append r) slots projected projection choices)) := by + have h := UpperScalarCutProjection.fixed_projected_law rows repeats p r hproper slots + (ProjectedWholeCut.fullSlots (p.append r) slots projected choices) + (ProjectedWholeCut.fullProjection (p.append r) slots projected projection choices) + (ProjectedWholeCut.fullSlots_outside (p.append r) slots projected choices) + (ProjectedWholeCut.fullProjection_outside (p.append r) slots projected projection choices) + directions + have hblocks := lifted_assembled_congr + (UpperScalarCutCalls.count rows repeats n (j + 1) (i + 1)) rows + (cutSlots (p.append r) slots) + (cutSlots (p.append r) (ProjectedWholeCut.fullSlots (p.append r) slots projected choices)) + (ProjectedCutChoices.selectedSlots (cutSlots (p.append r) slots) projected choices) + (CutGroupedProjection.cutProjection (p.append r) + (ProjectedWholeCut.fullProjection (p.append r) slots projected projection choices)) + (ProjectedCutChoices.selectedProjection (cutSlots (p.append r) slots) projected projection choices) + (ProjectedWholeCut.cut_fullSlots (p.append r) slots projected choices) + (ProjectedWholeCut.cut_fullProjection (p.append r) slots projected projection choices) + rw [hblocks] at h + exact h + +def pairLaw (rows repeats : Nat → Nat) (hproper : i + 1 < j + 1) + (directions : FiniteDistribution (BucketSampler.Direction (rows (j + 1)))) + (choiceLaw : (child : Fin (branch i)) → FiniteDistribution (Z child)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) : + FiniteDistribution (HierarchicalAgreementMean.PairRecord (rows := rows) slots (upperNode p)) := + (ProjectedCutChoices.choicesLaw choiceLaw β hβ hβ').mixture (fun choices => + (directions.product + ((WholeArraySampler.tapeLaw rows repeats (p.append r) + (ProjectedWholeCut.fullSlots (p.append r) slots projected choices)).product + (RecursiveSampler.law F2 repeats r + (LeafDomain (cutSlots p + (ProjectedWholeCut.fullSlots (p.append r) slots projected choices)))))).pushforward + (UpperScalarCutProjection.stoppedProjectedPair rows repeats p r hproper slots + (ProjectedWholeCut.fullSlots (p.append r) slots projected choices) + (ProjectedWholeCut.fullProjection (p.append r) slots projected projection choices))) + +theorem reconstruct_assembled_law (rows repeats : Nat → Nat) (hproper : i + 1 < j + 1) + (directions : FiniteDistribution (BucketSampler.Direction (rows (j + 1)))) + (choiceLaw : (child : Fin (branch i)) → FiniteDistribution (Z child)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) : + UpperScalarPairComparison.pairLaw rows repeats p r slots directions + (ProjectedPrefixComparison.assembledLaw + (UpperScalarCutCalls.count rows repeats n (j + 1) (i + 1)) rows + (cutSlots (p.append r) slots) projected projection choiceLaw β hβ hβ') = + pairLaw p r slots projected projection rows repeats hproper directions choiceLaw β hβ hβ' := by + unfold UpperScalarPairComparison.pairLaw + rw [ProjectedCutChoices.assembled_eq_mixture (cutSlots (p.append r) slots) projected projection + (UpperScalarCutCalls.count rows repeats n (j + 1) (i + 1)) rows choiceLaw β hβ hβ', + product_mixture_right, product_mixture_right, FiniteDistribution.pushforward_mixture] + unfold pairLaw + apply congrArg ((ProjectedCutChoices.choicesLaw choiceLaw β hβ hβ').mixture) + funext choices + exact fixed_law p r slots projected projection rows repeats hproper directions choices + +end +end PerfectCompleteness.ProjectedUpperPair + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/Projection.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/Projection.lean new file mode 100644 index 0000000000000000000000000000000000000000..418238204df00e152055b4f5a88517f697b2d5f9 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/Projection.lean @@ -0,0 +1,40 @@ +import Mathlib.Data.Fintype.Card +import Mathlib.Data.Fintype.Fin +import OAI.Computability.PerfectCompleteness.Reduction.Target + +namespace OAI + +section + +namespace PerfectCompleteness + +private theorem fiber_card_eq_filter_length {n : Nat} (p : Fin n → Prop) + [DecidablePred p] : + Fintype.card {a : Fin n // p a} = + ((List.finRange n).filter (fun a => decide (p a))).length := by + rw [Fintype.card_of_subtype + (((List.finRange n).filter (fun a => decide (p a))).toFinset) + (by intro a; simp)] + exact List.toFinset_card_of_nodup ((List.nodup_finRange n).filter _) + +theorem ProjectionTable.fiber_card {q : Nat} (table : ProjectionTable q) (b : Fin q) : + Fintype.card {a : Fin (2 * q) // table.images[a] = b} = 2 := by + rw [fiber_card_eq_filter_length] + exact table.exactlyTwo b + +def ProjectionTable.ofMap {q : Nat} (p : Fin (2 * q) → Fin q) + (h : ∀ b, Fintype.card {a : Fin (2 * q) // p a = b} = 2) : ProjectionTable q where + images := Vector.ofFn p + exactlyTwo b := by + simpa [fiber_card_eq_filter_length] using h b + +@[simp] theorem ProjectionTable.ofMap_apply {q : Nat} (p : Fin (2 * q) → Fin q) + (h : ∀ b, Fintype.card {a : Fin (2 * q) // p a = b} = 2) (a : Fin (2 * q)) : + (ProjectionTable.ofMap p h).images[a] = p a := by + simp [ProjectionTable.ofMap] + +end PerfectCompleteness + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/RepresentativeBucketCollisionLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/RepresentativeBucketCollisionLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..ef35aa9203045a2c484f674ac8ebee91ba8bda8f --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/RepresentativeBucketCollisionLemmas.lean @@ -0,0 +1,363 @@ +import OAI.Computability.PerfectCompleteness.Algebra.MatrixTriangularFoldingLemmas +import OAI.Computability.PerfectCompleteness.Decoding.TwoResponseCollisionLemmas +import OAI.Computability.PerfectCompleteness.Foundations.ManyGoodRowsLemmas + +namespace OAI + + +namespace PerfectCompleteness.RepresentativeBucketCollision + +noncomputable section + +open scoped Classical +open ClauseSupport MixedSupport CanonicalKeys +open DirectionQuotient (F2) +open TwoResponseCollision +open UniqueGamesTheorem.Foundations.Games + +variable {n : Nat} {K Z : Type*} [AddCommGroup K] [Module F2 K] + (slots : Fin n → Slot) (H : Submodule F2 (Assignment slots → F2)) + (other : Assignment slots → Z) (σ : KeyStrategy.Strategy n) + (W : Submodule F2 H) (s : (H ⧸ W) →ₗ[F2] H) + (hs : W.mkQ.comp s = LinearMap.id) + +def bucketTable (useful : (Module.Dual F2 (H ⧸ W) →ₗ[F2] K) → Prop) + (a : K) (X : CanonicalMatrixTable.Matrix (K := K) slots H) (h : H) : Option (K × Z) := + RepresentativeMatrixTable.partialTable slots H other σ W s useful + (MatrixRowQuotient.projectMatrix W (EvaluationMatrix.shift H X a h)) + +def bucketAccepted (a : K) (X : CanonicalMatrixTable.Matrix (K := K) slots H) (h : H) : Bool := + decide (CanonicalMatrixTable.Accepts slots H other σ a (EvaluationMatrix.shift H X a h)) + +theorem bucketTable_eq_some_iff + (useful : (Module.Dual F2 (H ⧸ W) →ₗ[F2] K) → Prop) + (a : K) (X : CanonicalMatrixTable.Matrix (K := K) slots H) (h : H) (y : K × Z) : + bucketTable slots H other σ W s useful a X h = some y ↔ + useful (MatrixRowQuotient.projectMatrix W (EvaluationMatrix.shift H X a h)) ∧ + RepresentativeMatrixTable.response slots H other σ W s + (EvaluationMatrix.shift H X a h) = y := by + by_cases hu : useful (MatrixRowQuotient.projectMatrix W (EvaluationMatrix.shift H X a h)) <;> + simp [bucketTable, RepresentativeMatrixTable.partialTable, + RepresentativeMatrixTable.response, RepresentativeMatrixTable.representative, hu] + +include hs in + +theorem collision_probability_lower_bound [Finite K] [Finite Z] [Fintype H] + (hW : RepresentativeMatrixTable.Determined slots H other W) + (μ : FiniteDistribution H) + (useful : (Module.Dual F2 (H ⧸ W) →ₗ[F2] K) → Prop) + (a : K) (ha : a ≠ 0) (X : CanonicalMatrixTable.Matrix (K := K) slots H) : + μ.probability (goodDefined (bucketTable slots H other σ W s useful a X) + (bucketAccepted slots H other σ a X)) ^ 2 / 2 ≤ + (μ.product μ).probability + (collision (bucketTable slots H other σ W s useful a X)) := by + let : Fintype K := Fintype.ofFinite K + let : Fintype Z := Fintype.ofFinite Z + apply collision_probability_ge_of_response_set μ + (bucketTable slots H other σ W s useful a X) (bucketAccepted slots H other σ a X) + (fun y => ∃ h : H, + CanonicalMatrixTable.Accepts slots H other σ a (EvaluationMatrix.shift H X a h) ∧ + RepresentativeMatrixTable.response slots H other σ W s + (EvaluationMatrix.shift H X a h) = y) + · exact RepresentativeMatrixTable.card_accepted_responses_le_two + slots H other σ W s hs hW a ha X + · intro h y hgood hresponse + refine ⟨h, ?_, ?_⟩ + · simpa only [bucketAccepted, decide_eq_true_eq] using hgood + · exact ((bucketTable_eq_some_iff slots H other σ W s useful a X h y).mp hresponse).2 + +end +end PerfectCompleteness.RepresentativeBucketCollision + + + +namespace PerfectCompleteness.RepresentativeDecoder + +noncomputable section + +open scoped Classical +open ClauseSupport MixedSupport CanonicalKeys +open DirectionQuotient (F2) +open RepresentativeMatrixTable + +variable {n : Nat} {K Z : Type*} [AddCommGroup K] [Module F2 K] + (slots : Fin n → Slot) (H : Submodule F2 (Assignment slots → F2)) + (other : Assignment slots → Z) (W : Submodule F2 H) + (s : (H ⧸ W) →ₗ[F2] H) (hs : W.mkQ.comp s = LinearMap.id) + +theorem residualVector_subtype (b : W) : + MatrixRowQuotient.residualVector W s hs (b : H) = b := by + apply Subtype.ext + rw [MatrixRowQuotient.residualVector_val] + have hb : W.mkQ (b : H) = 0 := + (Submodule.Quotient.mk_eq_zero W).mpr b.property + rw [hb, map_zero, sub_zero] + +theorem residualVector_section (h : H ⧸ W) : + MatrixRowQuotient.residualVector W s hs (s h) = 0 := by + apply Subtype.ext + rw [MatrixRowQuotient.residualVector_val] + have hh := LinearMap.congr_fun hs h + change W.mkQ (s h) = h at hh + change s h - s (W.mkQ (s h)) = 0 + rw [hh, sub_self] + +theorem correctionFunctional_comp_subtype (z : Z) : + (correctionFunctional slots H other W s hs z).comp W.subtype = + sideEvaluation slots H other W z := by + apply LinearMap.ext + intro b + change sideEvaluation slots H other W z + (MatrixRowQuotient.residualVector W s hs (b : H)) = + sideEvaluation slots H other W z b + rw [residualVector_subtype slots H W s hs] + +theorem correctionFunctional_comp_section (z : Z) : + (correctionFunctional slots H other W s hs z).comp s = 0 := by + apply LinearMap.ext + intro h + change sideEvaluation slots H other W z + (MatrixRowQuotient.residualVector W s hs (s h)) = 0 + rw [residualVector_section slots H W s hs, map_zero] + +theorem correctionFunctional_decomposition (z : Z) (b : W) (h : H ⧸ W) : + correctionFunctional slots H other W s hs z ((b : H) + s h) = + sideEvaluation slots H other W z b := by + rw [map_add] + have hb := LinearMap.congr_fun + (correctionFunctional_comp_subtype slots H other W s hs z) b + have hh := LinearMap.congr_fun + (correctionFunctional_comp_section slots H other W s hs z) h + change correctionFunctional slots H other W s hs z (b : H) = + sideEvaluation slots H other W z b at hb + change correctionFunctional slots H other W s hs z (s h) = 0 at hh + rw [hb, hh, add_zero] + +theorem correctionFunctional_unique (z : Z) (f : Module.Dual F2 H) + (hW : f.comp W.subtype = sideEvaluation slots H other W z) + (hsection : f.comp s = 0) : + f = correctionFunctional slots H other W s hs z := by + apply LinearMap.ext + intro h + have hb := LinearMap.congr_fun hW (MatrixRowQuotient.residualVector W s hs h) + have hh := LinearMap.congr_fun hsection (W.mkQ h) + change f (s (W.mkQ h)) = 0 at hh + change f (h - s (W.mkQ h)) = + sideEvaluation slots H other W z (MatrixRowQuotient.residualVector W s hs h) at hb + rw [map_sub, hh, sub_zero] at hb + exact hb + +theorem quotientFunctional_mem_annihilator (q : Module.Dual F2 (H ⧸ W)) : + q.comp W.mkQ ∈ W.dualAnnihilator := by + apply (Submodule.mem_dualAnnihilator (W := W) _).mpr + intro b hb + change q (W.mkQ b) = 0 + have hbzero : W.mkQ b = 0 := (Submodule.Quotient.mk_eq_zero W).mpr hb + rw [hbzero, map_zero] + +theorem coset_apply (z : Z) (δ : Module.Dual F2 H) + (hδ : δ ∈ W.dualAnnihilator) (b : W) : + (correctionFunctional slots H other W s hs z + δ) (b : H) = + sideEvaluation slots H other W z b := by + have hb := LinearMap.congr_fun + (correctionFunctional_comp_subtype slots H other W s hs z) b + have hzero : δ (b : H) = 0 := + (Submodule.mem_dualAnnihilator (W := W) δ).mp hδ b b.property + change correctionFunctional slots H other W s hs z (b : H) + δ (b : H) = _ + rw [hzero, add_zero] + exact hb + +theorem coset_comp_subtype (z : Z) (δ : Module.Dual F2 H) + (hδ : δ ∈ W.dualAnnihilator) : + (correctionFunctional slots H other W s hs z + δ).comp W.subtype = + sideEvaluation slots H other W z := by + apply LinearMap.ext + exact coset_apply slots H other W s hs z δ hδ + +theorem add_quotient_comp_subtype (z : Z) (q : Module.Dual F2 (H ⧸ W)) : + (correctionFunctional slots H other W s hs z + q.comp W.mkQ).comp W.subtype = + sideEvaluation slots H other W z := + coset_comp_subtype slots H other W s hs z _ + (quotientFunctional_mem_annihilator slots H W q) + +theorem coset_apply_at_image (hW : Determined slots H other W) + (x : Assignment slots) (δ : Module.Dual F2 H) + (hδ : δ ∈ W.dualAnnihilator) (b : W) : + (correctionFunctional slots H other W s hs (other x) + δ) (b : H) = + b.val.val x := by + rw [coset_apply slots H other W s hs (other x) δ hδ b, + sideEvaluation_at_image slots H other W hW x] + rfl + +theorem coset_one_at_image (hW : Determined slots H other W) + (x : Assignment slots) (δ : Module.Dual F2 H) + (hδ : δ ∈ W.dualAnnihilator) (b : W) + (hb : b.val.val = (1 : Assignment slots → F2)) : + (correctionFunctional slots H other W s hs (other x) + δ) (b : H) = 1 := by + rw [coset_apply_at_image slots H other W s hs hW x δ hδ b, hb] + rfl + +theorem coset_product_at_image (hW : Determined slots H other W) + (x : Assignment slots) (δ : Module.Dual F2 H) + (hδ : δ ∈ W.dualAnnihilator) (b : W) + (f g : Assignment slots → F2) (hb : b.val.val = f * g) : + (correctionFunctional slots H other W s hs (other x) + δ) (b : H) = + f x * g x := by + rw [coset_apply_at_image slots H other W s hs hW x δ hδ b, hb] + rfl + +variable (σ : KeyStrategy.Strategy n) + +theorem matched_coset_realized_on_W (hW : Determined slots H other W) + (X : CanonicalMatrixTable.Matrix (K := K) slots H) (y : K × Z) + (hmatch : response slots H other σ W s X = y) + (V : Submodule F2 (Module.Dual F2 H)) (hV : V ≤ W.dualAnnihilator) : + ∃ x : Assignment slots, other x = y.2 ∧ + ∀ δ : V, ∀ b : W, + (correctionFunctional slots H other W s hs y.2 + (δ : Module.Dual F2 H)) + (b : H) = b.val.val x := by + obtain ⟨x, _, hx⟩ := CanonicalMatrixTable.response_realized slots H other σ + (representative slots H W s X) + change other x = (response slots H other σ W s X).2 at hx + rw [hmatch] at hx + refine ⟨x, hx, ?_⟩ + intro δ b + rw [← hx] + exact coset_apply_at_image slots H other W s hs hW x δ (hV δ.property) b + +theorem raw_selected_output_at_match (hW : Determined slots H other W) + (X : CanonicalMatrixTable.Matrix (K := K) slots H) (y : K × Z) + (hmatch : response slots H other σ W s X = y) : + (CanonicalMatrixTable.response slots H other σ X).1 = + X (correctionFunctional slots H other W s hs y.2) + y.1 := by + rw [raw_response slots H other σ W s hs hW X, hmatch] + change y.1 + X (correctionFunctional slots H other W s hs y.2) = _ + exact add_comm _ _ + +end +end PerfectCompleteness.RepresentativeDecoder + + + +namespace PerfectCompleteness.DenseWitnessRealization + +noncomputable section + +open scoped BigOperators Classical +open UniqueGamesTheorem.Fourier.MatrixLevelBridge +open ClauseSupport MixedSupport CanonicalKeys +open DirectionQuotient (F2) +open ManyGoodRows PartialTableInverse + +attribute [local instance] UniqueGamesTheorem.Appendix.RankLevelFilter.linearMapFintype + +section Generic + +variable {E F Y : Type*} + [AddCommGroup E] [Module F2 E] [AddCommGroup F] [Module F2 F] + [FiniteDimensional F2 E] [FiniteDimensional F2 F] + [Fintype E] [Fintype F] [Fintype Y] + {f : (E →ₗ[F2] F) → Option Y} {r : Nat} {ρ : ℝ} + {A : RowMap F r} {U : E →ₗ[F2] (Fin r → F2)} + +omit [FiniteDimensional F2 E] [FiniteDimensional F2 F] [Fintype Y] in +theorem witness_value_attained (w : Witness f r ρ A U) (hρ : 0 < ρ) : + ∃ X : MatrixSlice.Slice w.columnSpace (LinearMap.ker A) w.base, + f X.val = some w.value := by + by_contra hnone + have hzero : + (𝔼 X : MatrixSlice.Slice w.columnSpace (LinearMap.ker A) w.base, + indicator f w.value X.val) = 0 := by + apply Finset.expect_eq_zero + intro X _ + have hX : f X.val ≠ some w.value := fun h => hnone ⟨X, h⟩ + simp [indicator, hX] + have hdensity := w.density + rw [hzero] at hdensity + exact (not_le_of_gt hρ) hdensity + +end Generic + + +variable {n : Nat} {K Z : Type*} [AddCommGroup K] [Module F2 K] + (slots : Fin n → Slot) (H : Submodule F2 (Assignment slots → F2)) + (other : Assignment slots → Z) (σ : KeyStrategy.Strategy n) + (W : Submodule F2 H) (s : (H ⧸ W) →ₗ[F2] H) + [FiniteDimensional F2 H] [FiniteDimensional F2 K] + [Fintype H] [Fintype K] [Fintype Z] + (useful : (Module.Dual F2 (H ⧸ W) →ₗ[F2] K) → Prop) + {r : Nat} {ρ : ℝ} {A : RowMap K r} + {U : Module.Dual F2 (H ⧸ W) →ₗ[F2] (Fin r → F2)} + +abbrev RepresentativeWitness := + Witness (RepresentativeMatrixTable.partialTable slots H other σ W s useful) r ρ A U + +omit [FiniteDimensional F2 H] [FiniteDimensional F2 K] [Fintype Z] + +theorem exists_useful_match + (w : RepresentativeWitness slots H other σ W s useful (r := r) (ρ := ρ) (A := A) (U := U)) + (hρ : 0 < ρ) : + ∃ X : MatrixSlice.Slice w.columnSpace (LinearMap.ker A) w.base, + useful X.val ∧ + CanonicalMatrixTable.response slots H other σ + (MatrixRowQuotient.liftMatrix W s X.val) = w.value := by + obtain ⟨X, hX⟩ := witness_value_attained w hρ + have huseful : useful X.val := by + by_contra hbad + simp [RepresentativeMatrixTable.partialTable, hbad] at hX + refine ⟨X, huseful, ?_⟩ + simpa [RepresentativeMatrixTable.partialTable, huseful] using hX + +theorem exists_joint_realizer + (w : RepresentativeWitness slots H other σ W s useful (r := r) (ρ := ρ) (A := A) (U := U)) + (hρ : 0 < ρ) : + ∃ X : MatrixSlice.Slice w.columnSpace (LinearMap.ker A) w.base, + useful X.val ∧ ∃ x : Assignment slots, + CanonicalMatrixTable.query slots H other + (MatrixRowQuotient.liftMatrix W s X.val) x = w.value := by + obtain ⟨X, huseful, hmatch⟩ := + exists_useful_match slots H other σ W s useful w hρ + obtain ⟨x, hfirst, hsecond⟩ := CanonicalMatrixTable.response_realized slots H other σ + (MatrixRowQuotient.liftMatrix W s X.val) + rw [hmatch] at hfirst hsecond + refine ⟨X, huseful, x, ?_⟩ + exact Prod.ext hfirst hsecond + +theorem selected_side_mem_range + (w : RepresentativeWitness slots H other σ W s useful (r := r) (ρ := ρ) (A := A) (U := U)) + (hρ : 0 < ρ) : w.value.2 ∈ Set.range other := by + obtain ⟨X, _, x, hx⟩ := exists_joint_realizer slots H other σ W s useful w hρ + exact ⟨x, congrArg Prod.snd hx⟩ + +theorem exists_coset_realizer + (hs : W.mkQ.comp s = LinearMap.id) + (hW : RepresentativeMatrixTable.Determined slots H other W) + (w : RepresentativeWitness slots H other σ W s useful (r := r) (ρ := ρ) (A := A) (U := U)) + (hρ : 0 < ρ) (V : Submodule F2 (Module.Dual F2 H)) + (hV : V ≤ W.dualAnnihilator) : + ∃ X : MatrixSlice.Slice w.columnSpace (LinearMap.ker A) w.base, + useful X.val ∧ ∃ x : Assignment slots, + CanonicalMatrixTable.query slots H other + (MatrixRowQuotient.liftMatrix W s X.val) x = w.value ∧ + ∀ δ : V, ∀ b : W, + (RepresentativeMatrixTable.correctionFunctional slots H other W s hs w.value.2 + + (δ : Module.Dual F2 H)) (b : H) = b.val.val x := by + obtain ⟨X, huseful, x, hx⟩ := exists_joint_realizer slots H other σ W s useful w hρ + refine ⟨X, huseful, x, hx, ?_⟩ + intro δ b + have hxside : other x = w.value.2 := congrArg Prod.snd hx + rw [← hxside] + exact RepresentativeDecoder.coset_apply_at_image slots H other W s hs hW x δ + (hV δ.property) b + +theorem selected_columns_le_annihilator + (w : RepresentativeWitness slots H other σ W s useful (r := r) (ρ := ρ) (A := A) (U := U)) : + w.columnSpace.map W.mkQ.dualMap ≤ W.dualAnnihilator := by + intro δ hδ + obtain ⟨q, _, rfl⟩ := Submodule.mem_map.mp hδ + exact RepresentativeDecoder.quotientFunctional_mem_annihilator slots H W q + +end +end PerfectCompleteness.DenseWitnessRealization + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/RightDecoderLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/RightDecoderLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..9d329d9f5371e8bef97eb83c886612ed8a6be844 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/RightDecoderLemmas.lean @@ -0,0 +1,327 @@ +import OAI.Computability.PerfectCompleteness.Decoding.DecoderContraction +import OAI.Computability.PerfectCompleteness.Foundations.RecursiveSpaceEquivLemmas +import OAI.Computability.PerfectCompleteness.Machines.OwnInputHeavyBounds +import OAI.Computability.PerfectCompleteness.Sampling.BoundedListSamplingLemmas + +namespace OAI + + +namespace PerfectCompleteness.RightDecoder + +open scoped TensorProduct Classical +open UniqueGamesTheorem.Foundations.Games +open TreeSourceSpaces HierarchicalArrays OwnInputReference + +abbrev F2 := ZMod 2 + +noncomputable section + +variable {branch : Nat → Nat} {n t : Nat} + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (rows : Nat → Nat) (upper lower : Nodes branch n) + (W : Submodule F2 (UpperVector rows upper)) (a : LowerVector rows lower) + +local instance characterFintype : Fintype (Module.Dual F2 (UpperVector rows upper)) := + Fintype.ofInjective + (fun f : Module.Dual F2 (UpperVector rows upper) => + (f : UpperVector rows upper → F2)) DFunLike.coe_injective + +local instance scalarFintype : Fintype (Module.Dual F2 (UpperSpace slots upper)) := by + letI : Fintype (UpperSpace slots upper) := Fintype.ofFinite _ + exact Fintype.ofInjective + (fun f : Module.Dual F2 (UpperSpace slots upper) => + (f : UpperSpace slots upper → F2)) DFunLike.coe_injective + +variable (repeats : Nat → Nat) (cut : Cut upper lower) + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (input : Input slots rows upper lower W a) (threshold : ℝ) + +def law : FiniteDistribution (Module.Dual F2 (UpperSpace slots upper)) := + BoundedListSampling.outputLaw + (fun σ => heavyList slots rows upper lower W a repeats cut labeling input σ threshold) + 0 (DecoderContraction.contract W) + +theorem probability_law (event : Module.Dual F2 (UpperSpace slots upper) → Bool) : + (law slots rows upper lower W a repeats cut labeling input threshold).probability event = + (BoundedListSampling.jointLaw + (fun σ => heavyList slots rows upper lower W a repeats cut labeling input σ threshold) + 0).probability (fun choice => event + (DecoderContraction.contract W choice.1 choice.2)) := by + unfold law BoundedListSampling.outputLaw + exact FiniteDistribution.probability_pushforward _ _ _ + +theorem success_lower (M : ℝ) (hM : 0 < M) + (hcard : ∀ σ : Module.Dual F2 (UpperVector rows upper), + ((heavyList slots rows upper lower W a repeats cut labeling input σ threshold).card : ℝ) ≤ M) + (event : Module.Dual F2 (UpperSpace slots upper) → Bool) + (witness : ∃ σ Φ, + Φ ∈ heavyList slots rows upper lower W a repeats cut labeling input σ threshold ∧ + event (DecoderContraction.contract W σ Φ) = true) : + 1 / ((Fintype.card (Module.Dual F2 (UpperVector rows upper)) : ℝ) * M) ≤ + (law slots rows upper lower W a repeats cut labeling input threshold).probability event := by + exact BoundedListSampling.output_success_lower + (fun σ => heavyList slots rows upper lower W a repeats cut labeling input σ threshold) + 0 (DecoderContraction.contract W) M hM hcard event witness + +theorem coset_lower (M : ℝ) (hM : 0 < M) + (hcard : ∀ σ : Module.Dual F2 (UpperVector rows upper), + ((heavyList slots rows upper lower W a repeats cut labeling input σ threshold).card : ℝ) ≤ M) + (Q : Submodule F2 (Module.Dual F2 (UpperSpace slots upper))) + (z : Module.Dual F2 (UpperSpace slots upper)) + (witness : ∃ σ Φ, + Φ ∈ heavyList slots rows upper lower W a repeats cut labeling input σ threshold ∧ + σ.comp W.subtype ≠ 0 ∧ + Φ - DecoderContraction.baseFrequency W σ z ∈ DecoderContraction.errorSpace W Q) : + 1 / ((Fintype.card (Module.Dual F2 (UpperVector rows upper)) : ℝ) * M) ≤ + (law slots rows upper lower W a repeats cut labeling input threshold).probability + (fun decoded => decide (decoded - z ∈ Q)) := by + apply success_lower slots rows upper lower W a repeats cut labeling input threshold M hM hcard + obtain ⟨σ, Φ, hlist, hσ, hΦ⟩ := witness + exact ⟨σ, Φ, hlist, by + simpa only [decide_eq_true_eq] using + DecoderContraction.contract_sub_mem W Q σ Φ z hσ hΦ⟩ + +theorem coset_lower_of_balanced + (hrep : RecursiveSamplerBias.RepetitionsBalanced repeats) + (hthreshold : 0 < threshold) + (hsmall : (7 / 8 : ℝ) ^ repeats (Nodes.height upper) ≤ threshold ^ 2 / 2) + (Q : Submodule F2 (Module.Dual F2 (UpperSpace slots upper))) + (z : Module.Dual F2 (UpperSpace slots upper)) + (witness : ∃ σ Φ, + Φ ∈ heavyList slots rows upper lower W a repeats cut labeling input σ threshold ∧ + σ.comp W.subtype ≠ 0 ∧ + Φ - DecoderContraction.baseFrequency W σ z ∈ DecoderContraction.errorSpace W Q) : + threshold ^ 2 / + (2 * (Fintype.card (Module.Dual F2 (UpperVector rows upper)) : ℝ)) ≤ + (law slots rows upper lower W a repeats cut labeling input threshold).probability + (fun decoded => decide (decoded - z ∈ Q)) := by + have hsq : 0 < threshold ^ 2 := sq_pos_of_pos hthreshold + have hcard : ∀ σ : Module.Dual F2 (UpperVector rows upper), + ((heavyList slots rows upper lower W a repeats cut labeling input σ threshold).card : ℝ) ≤ + 2 / threshold ^ 2 := by + intro σ + exact OwnInputHeavyBounds.heavyList_card_le_of_balanced slots rows upper lower W a + repeats cut hrep labeling input σ threshold hthreshold hsmall + have h := coset_lower slots rows upper lower W a repeats cut labeling input threshold + (2 / threshold ^ 2) (div_pos (by norm_num) hsq) hcard Q z witness + have hcount : + (Fintype.card (Module.Dual F2 (UpperVector rows upper)) : ℝ) ≠ 0 := + Nat.cast_ne_zero.mpr Fintype.card_ne_zero + have heq : + 1 / ((Fintype.card (Module.Dual F2 (UpperVector rows upper)) : ℝ) * + (2 / threshold ^ 2)) = + threshold ^ 2 / (2 * (Fintype.card (Module.Dual F2 (UpperVector rows upper)) : ℝ)) := by + field_simp [hcount, ne_of_gt hsq] + rwa [heq] at h + +end +end PerfectCompleteness.RightDecoder + + + +namespace PerfectCompleteness.RightDecoderDescendant + +open scoped TensorProduct Classical +open UniqueGamesTheorem.Foundations.Games +open PointwiseSpaces TreeSourceSpaces HierarchicalArrays OwnInputReference + +abbrev F2 := ZMod 2 + +noncomputable section + +variable {branch : Nat → Nat} {n t : Nat} + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (upper lower : Nodes branch n) (cut : Cut upper lower) + +def leafEquiv (s : RecursiveSpaces.Slots branch (Nodes.height lower)) : + cut.path.family (LeafDomain (nodeSlots slots upper)) s ≃ + LeafDomain (nodeSlots slots lower) s := + Equiv.cast (congrFun + (Cut.family_eq (slots := slots) (upper := upper) (lower := lower) cut) s) + +def restriction : Domain (nodeSlots slots upper) → Domain (nodeSlots slots lower) := + fun x => RecursiveSpaces.project (fun s => leafEquiv slots upper lower cut s) + (cut.path.restriction (LeafDomain (nodeSlots slots upper)) x) + +theorem restriction_restrictNode (x : Domain slots) : + restriction slots upper lower cut (restrictNode slots upper x) = + restrictNode slots lower x := by + have cast_apply : + ∀ (i j : RecursiveSpaces.Slots branch n) (_ : i = j) + (hA : LeafDomain slots i = LeafDomain slots j), + Equiv.cast hA (x i) = x j := by + intro i j hij hA + subst j + rfl + funext s + exact cast_apply _ _ (cut.slots_agree s) + (congrFun (Cut.family_eq (slots := slots) (upper := upper) (lower := lower) cut) s) + +variable (hbranch : ∀ k < Nodes.height upper, 0 < branch k) + +def squareEmbedding : + squareSpace (H (nodeSlots slots lower)) →ₗ[F2] UpperSpace slots upper := + (DecoderContraction.descendantSquareEmbedding cut.path + (LeafDomain (nodeSlots slots upper)) hbranch cut.proper).comp + (RecursiveSpaceEquiv.squareEquiv (𝕜 := F2) + (leafEquiv slots upper lower cut)).toLinearMap + +@[simp] theorem squareEmbedding_apply + (f : squareSpace (H (nodeSlots slots lower))) (x : Domain (nodeSlots slots upper)) : + (squareEmbedding slots upper lower cut hbranch f).val x = + f.val (restriction slots upper lower cut x) := rfl + +theorem squareEmbedding_restrictNode + (f : squareSpace (H (nodeSlots slots lower))) (x : Domain slots) : + (squareEmbedding slots upper lower cut hbranch f).val (restrictNode slots upper x) = + f.val (restrictNode slots lower x) := by + rw [squareEmbedding_apply, restriction_restrictNode] + +theorem squareEmbedding_injective : + Function.Injective (squareEmbedding slots upper lower cut hbranch) := by + exact (DecoderContraction.descendantSquareEmbedding_injective cut.path + (LeafDomain (nodeSlots slots upper)) hbranch cut.proper + (fun _ => inferInstance)).comp + (RecursiveSpaceEquiv.squareEquiv (𝕜 := F2) + (leafEquiv slots upper lower cut)).injective + +def functional (z : Module.Dual F2 (UpperSpace slots upper)) : + Module.Dual F2 (squareSpace (H (nodeSlots slots lower))) := + z.comp (squareEmbedding slots upper lower cut hbranch) + +abbrev Form := H (nodeSlots slots lower) →ₗ[F2] H (nodeSlots slots lower) →ₗ[F2] F2 + +def form (z : Module.Dual F2 (UpperSpace slots upper)) : Form slots lower := + OddListExtraction.multiplicationForm (H (nodeSlots slots lower)) + (functional slots upper lower cut hbranch z) + +@[simp] theorem form_apply (z : Module.Dual F2 (UpperSpace slots upper)) + (f g : H (nodeSlots slots lower)) : + form slots upper lower cut hbranch z f g = + z (squareEmbedding slots upper lower cut hbranch + (OddListExtraction.productElement (H (nodeSlots slots lower)) f g)) := rfl + +theorem form_evaluation (x : Domain (nodeSlots slots upper)) + (f g : H (nodeSlots slots lower)) : + form slots upper lower cut hbranch + (EvaluationMatrix.evaluation (UpperSpace slots upper) x) f g = + f.val (restriction slots upper lower cut x) * + g.val (restriction slots upper lower cut x) := rfl + +theorem form_evaluation_restrictNode (x : Domain slots) + (f g : H (nodeSlots slots lower)) : + form slots upper lower cut hbranch + (EvaluationMatrix.evaluation (UpperSpace slots upper) (restrictNode slots upper x)) f g = + f.val (restrictNode slots lower x) * g.val (restrictNode slots lower x) := by + rw [form_evaluation, restriction_restrictNode] + +theorem functional_eq_of_sub_mem + (Q : Submodule F2 (Module.Dual F2 (UpperSpace slots upper))) + (z' z : Module.Dual F2 (UpperSpace slots upper)) (herror : z' - z ∈ Q) + (hvanish : ∀ q ∈ Q, q.comp (squareEmbedding slots upper lower cut hbranch) = 0) : + functional slots upper lower cut hbranch z' = + functional slots upper lower cut hbranch z := by + have h := hvanish (z' - z) herror + apply LinearMap.ext + intro f + have he := LinearMap.congr_fun h f + change z' (squareEmbedding slots upper lower cut hbranch f) - + z (squareEmbedding slots upper lower cut hbranch f) = 0 at he + exact sub_eq_zero.mp he + +theorem form_eq_of_sub_mem + (Q : Submodule F2 (Module.Dual F2 (UpperSpace slots upper))) + (z' z : Module.Dual F2 (UpperSpace slots upper)) (herror : z' - z ∈ Q) + (hvanish : ∀ q ∈ Q, q.comp (squareEmbedding slots upper lower cut hbranch) = 0) : + form slots upper lower cut hbranch z' = form slots upper lower cut hbranch z := by + unfold form + rw [functional_eq_of_sub_mem slots upper lower cut hbranch Q z' z herror hvanish] + + +variable (rows : Nat → Nat) + (W : Submodule F2 (UpperVector rows upper)) (a : LowerVector rows lower) + (repeats : Nat → Nat) + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (input : Input slots rows upper lower W a) (threshold : ℝ) + +local instance scalarFintype : Fintype (Module.Dual F2 (UpperSpace slots upper)) := + RightDecoder.scalarFintype slots upper + +local instance formFintype : Fintype (Form slots lower) := by + letI : Fintype (H (nodeSlots slots lower)) := Fintype.ofFinite _ + letI : Fintype (Module.Dual F2 (H (nodeSlots slots lower))) := + Fintype.ofInjective + (fun f : Module.Dual F2 (H (nodeSlots slots lower)) => + (f : H (nodeSlots slots lower) → F2)) DFunLike.coe_injective + exact Fintype.ofInjective + (fun f : Form slots lower => + (f : H (nodeSlots slots lower) → Module.Dual F2 (H (nodeSlots slots lower)))) + DFunLike.coe_injective + +local instance characterFintype : Fintype (Module.Dual F2 (UpperVector rows upper)) := + RightDecoder.characterFintype rows upper + +def formLaw : FiniteDistribution (Form slots lower) := + (RightDecoder.law slots rows upper lower W a repeats cut labeling input threshold).pushforward + (form slots upper lower cut hbranch) + +theorem probability_formLaw (event : Form slots lower → Bool) : + (formLaw slots upper lower cut hbranch rows W a repeats labeling input threshold).probability + event = + (RightDecoder.law slots rows upper lower W a repeats cut labeling input threshold).probability + (fun z => event (form slots upper lower cut hbranch z)) := + FiniteDistribution.probability_pushforward _ _ _ + +theorem coset_probability_le_form_probability + (Q : Submodule F2 (Module.Dual F2 (UpperSpace slots upper))) + (z : Module.Dual F2 (UpperSpace slots upper)) + (hvanish : ∀ q ∈ Q, q.comp (squareEmbedding slots upper lower cut hbranch) = 0) : + (RightDecoder.law slots rows upper lower W a repeats cut labeling input threshold).probability + (fun decoded => decide (decoded - z ∈ Q)) ≤ + (formLaw slots upper lower cut hbranch rows W a repeats labeling input threshold).probability + (fun decoded => decide (decoded = form slots upper lower cut hbranch z)) := by + rw [probability_formLaw] + apply FiniteDistribution.probability_mono + intro decoded hdecoded + have hmem : decoded - z ∈ Q := of_decide_eq_true hdecoded + simpa only [decide_eq_true_eq] using + form_eq_of_sub_mem slots upper lower cut hbranch Q decoded z hmem hvanish + +theorem form_contract_eq + (Q : Submodule F2 (Module.Dual F2 (UpperSpace slots upper))) + (σ : Module.Dual F2 (UpperVector rows upper)) + (Φ : Module.Dual F2 (W ⊗[F2] UpperSpace slots upper)) + (z : Module.Dual F2 (UpperSpace slots upper)) + (hσ : σ.comp W.subtype ≠ 0) + (hΦ : Φ - DecoderContraction.baseFrequency W σ z ∈ DecoderContraction.errorSpace W Q) + (hvanish : ∀ q ∈ Q, q.comp (squareEmbedding slots upper lower cut hbranch) = 0) : + form slots upper lower cut hbranch (DecoderContraction.contract W σ Φ) = + form slots upper lower cut hbranch z := + form_eq_of_sub_mem slots upper lower cut hbranch Q _ z + (DecoderContraction.contract_sub_mem W Q σ Φ z hσ hΦ) hvanish + +theorem form_success_lower_of_balanced + (hrep : RecursiveSamplerBias.RepetitionsBalanced repeats) + (hthreshold : 0 < threshold) + (hsmall : (7 / 8 : ℝ) ^ repeats (Nodes.height upper) ≤ threshold ^ 2 / 2) + (Q : Submodule F2 (Module.Dual F2 (UpperSpace slots upper))) + (z : Module.Dual F2 (UpperSpace slots upper)) + (hvanish : ∀ q ∈ Q, q.comp (squareEmbedding slots upper lower cut hbranch) = 0) + (witness : ∃ σ Φ, + Φ ∈ heavyList slots rows upper lower W a repeats cut labeling input σ threshold ∧ + σ.comp W.subtype ≠ 0 ∧ + Φ - DecoderContraction.baseFrequency W σ z ∈ DecoderContraction.errorSpace W Q) : + threshold ^ 2 / + (2 * (Fintype.card (Module.Dual F2 (UpperVector rows upper)) : ℝ)) ≤ + (formLaw slots upper lower cut hbranch rows W a repeats labeling input threshold).probability + (fun decoded => decide (decoded = form slots upper lower cut hbranch z)) := + (RightDecoder.coset_lower_of_balanced slots rows upper lower W a repeats cut labeling input + threshold hrep hthreshold hsmall Q z witness).trans + (coset_probability_le_form_probability slots upper lower cut hbranch rows W a repeats + labeling input threshold Q z hvanish) + + +end +end PerfectCompleteness.RightDecoderDescendant + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/RightDecoderWitness.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/RightDecoderWitness.lean new file mode 100644 index 0000000000000000000000000000000000000000..1e82fe21c0ad63c015a2b6134f507f6d7ffff875 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/RightDecoderWitness.lean @@ -0,0 +1,138 @@ +import Mathlib.Tactic.Abel +import OAI.Computability.PerfectCompleteness.Algebra.TensorAffineHeavyWitness +import OAI.Computability.PerfectCompleteness.Decoding.DecoderContraction +import OAI.Computability.PerfectCompleteness.Machines.OwnInputHeavyBounds + +namespace OAI + + +namespace PerfectCompleteness.RightDecoderWitness + +open scoped TensorProduct Classical +open UniqueGamesTheorem.Foundations.Games +open TensorCosetEvaluation +open TreeSourceSpaces HierarchicalArrays OwnInputReference + +abbrev F2 := ZMod 2 + +noncomputable section + +section Algebra + +variable {K H : Type*} [AddCommGroup K] [Module F2 K] + [AddCommGroup H] [Module F2 H] + +theorem scalarRestriction_row_add (W : Submodule F2 K) + (Φ : Module.Dual F2 (W ⊗[F2] H)) (u v : W) : + scalarRestriction Φ (u + v) = scalarRestriction Φ u + scalarRestriction Φ v := by + ext h + simp only [scalarRestriction_apply, TensorProduct.add_tmul, map_add, LinearMap.add_apply] + +theorem errorSpace_of_normalized_rows (W : Submodule F2 K) + (Q : Submodule F2 (Module.Dual F2 H)) (σ : Module.Dual F2 K) + (Φ : Module.Dual F2 (W ⊗[F2] H)) (z : Module.Dual F2 H) + (hσ : σ.comp W.subtype ≠ 0) + (hgood : ∀ w : W, σ w.val = 1 → scalarRestriction Φ w - z ∈ Q) : + Φ - DecoderContraction.baseFrequency W σ z ∈ DecoderContraction.errorSpace W Q := by + intro w + rw [scalarRestriction_sub] + change scalarRestriction Φ w - scalarRestriction (pureFrequency (σ.comp W.subtype) z) w ∈ Q + rw [scalarRestriction_pure] + change scalarRestriction Φ w - σ w.val • z ∈ Q + rcases UniqueGamesTheorem.Integration.BinaryLinear.scalar_cases (σ w.val) with hzero | hone + · rw [hzero, zero_smul, sub_zero] + let w₀ := DecoderContraction.chosenRow W σ hσ + have hw₀ : σ w₀.val = 1 := DecoderContraction.chosenRow_value_one W σ hσ + have hsum : σ (w₀ + w).val = 1 := by + simp only [Submodule.coe_add, map_add, hw₀, hzero, add_zero] + have hdifference := Q.sub_mem (hgood (w₀ + w) hsum) (hgood w₀ hw₀) + rw [scalarRestriction_row_add] at hdifference + have heq : (scalarRestriction Φ w₀ + scalarRestriction Φ w - z) - + (scalarRestriction Φ w₀ - z) = scalarRestriction Φ w := by + abel + rwa [heq] at hdifference + · simpa only [hone, one_smul] using hgood w hone + +end Algebra + +variable {branch : Nat → Nat} {n t : Nat} + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (rows : Nat → Nat) (upper lower : Nodes branch n) + (W : Submodule F2 (UpperVector rows upper)) (a : LowerVector rows lower) + (repeats : Nat → Nat) (cut : Cut upper lower) + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (input : Input slots rows upper lower W a) + +local instance upperSpaceFintype : Fintype (UpperSpace slots upper) := Fintype.ofFinite _ + +theorem heavyList_eq (threshold : ℝ) (σ : Module.Dual F2 (UpperVector rows upper)) : + TensorAffineHeavyWitness.heavyList W + (referenceLaw slots rows upper lower W repeats cut) + (response slots rows upper lower W a labeling input) threshold σ = + heavyList slots rows upper lower W a repeats cut labeling input σ threshold := by + ext Φ + simp only [TensorAffineHeavyWitness.heavyList, OwnLawHeavyList.mem_heavyList, + OwnLawHeavyList.character, OwnInputReference.mem_heavyList] + +def conditionalMatch + (Q : Submodule F2 (Module.Dual F2 (UpperSpace slots upper))) + (target : Q →ₗ[F2] W) (z : Module.Dual F2 (UpperSpace slots upper)) + (offset : UpperVector rows upper) : ℝ := + TensorAffineHeavyWitness.conditionalMatch W + (referenceLaw slots rows upper lower W repeats cut) + (response slots rows upper lower W a labeling input) Q target z offset + +theorem exists_heavy_error_coset + (ρ h₀ : ℝ) (hρ : 0 < ρ) (hh₀ : 0 < h₀) + (hrep : RecursiveSamplerBias.RepetitionsBalanced repeats) + (hsmall : (7 / 8 : ℝ) ^ repeats (Nodes.height upper) ≤ h₀ / 2) + (hexcluded : 1 / (2 : ℝ) ^ Module.finrank F2 W < ρ / 8) + (Q : Submodule F2 (Module.Dual F2 (UpperSpace slots upper))) + (hsize : h₀ ≤ 1 / (2 : ℝ) ^ Module.finrank F2 (Q →ₗ[F2] W)) + (target : Q →ₗ[F2] W) (z : Module.Dual F2 (UpperSpace slots upper)) + (offset : UpperVector rows upper) + (hmatch : ρ ≤ conditionalMatch slots rows upper lower W a repeats cut labeling input + Q target z offset) : + ∃ σ : Module.Dual F2 (UpperVector rows upper), σ.comp W.subtype ≠ 0 ∧ + ∃ Φ ∈ heavyList slots rows upper lower W a repeats cut labeling input σ (ρ * h₀ / 4), + Φ - DecoderContraction.baseFrequency W σ z ∈ DecoderContraction.errorSpace W Q := by + have hbias : ∀ Φ : Module.Dual F2 (W ⊗[F2] UpperSpace slots upper), Φ ≠ 0 → + |(referenceLaw slots rows upper lower W repeats cut).expectation + (fun X => QuarterBalance.sign (Φ X))| ≤ (7 / 8 : ℝ) ^ repeats (Nodes.height upper) := by + intro Φ hΦ + apply OwnInputHeavyBounds.referenceLaw_sign_bias_le slots rows upper lower W repeats cut + ((7 / 8 : ℝ) ^ repeats (Nodes.height upper)) ?_ Φ hΦ + intro f hf + exact RecursiveSamplerBias.law_bias_le_height repeats hrep cut.path + (LeafDomain (nodeSlots slots upper)) f hf + obtain ⟨σ, hσ, Φ, hΦ, hgood⟩ := TensorAffineHeavyWitness.exists_heavy_candidate W + (referenceLaw slots rows upper lower W repeats cut) + (response slots rows upper lower W a labeling input) + ρ h₀ ((7 / 8 : ℝ) ^ repeats (Nodes.height upper)) hρ hh₀ + (pow_nonneg (by norm_num) _) hsmall hbias hexcluded Q hsize target z offset hmatch + refine ⟨σ, hσ, Φ, ?_, errorSpace_of_normalized_rows W Q σ Φ z hσ hgood⟩ + rw [← heavyList_eq slots rows upper lower W a repeats cut labeling input] + exact hΦ + +theorem exists_contracted_candidate + (ρ h₀ : ℝ) (hρ : 0 < ρ) (hh₀ : 0 < h₀) + (hrep : RecursiveSamplerBias.RepetitionsBalanced repeats) + (hsmall : (7 / 8 : ℝ) ^ repeats (Nodes.height upper) ≤ h₀ / 2) + (hexcluded : 1 / (2 : ℝ) ^ Module.finrank F2 W < ρ / 8) + (Q : Submodule F2 (Module.Dual F2 (UpperSpace slots upper))) + (hsize : h₀ ≤ 1 / (2 : ℝ) ^ Module.finrank F2 (Q →ₗ[F2] W)) + (target : Q →ₗ[F2] W) (z : Module.Dual F2 (UpperSpace slots upper)) + (offset : UpperVector rows upper) + (hmatch : ρ ≤ conditionalMatch slots rows upper lower W a repeats cut labeling input + Q target z offset) : + ∃ σ : Module.Dual F2 (UpperVector rows upper), σ.comp W.subtype ≠ 0 ∧ + ∃ Φ ∈ heavyList slots rows upper lower W a repeats cut labeling input σ (ρ * h₀ / 4), + DecoderContraction.contract W σ Φ - z ∈ Q := by + obtain ⟨σ, hσ, Φ, hΦ, herror⟩ := exists_heavy_error_coset slots rows upper lower W a + repeats cut labeling input ρ h₀ hρ hh₀ hrep hsmall hexcluded Q hsize target z offset hmatch + exact ⟨σ, hσ, Φ, hΦ, DecoderContraction.contract_sub_mem W Q σ Φ z hσ herror⟩ + +end +end PerfectCompleteness.RightDecoderWitness + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/SelectedArrayProjection.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/SelectedArrayProjection.lean new file mode 100644 index 0000000000000000000000000000000000000000..465c7cfbc81bb01241f3722484cf978e4809e713 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/SelectedArrayProjection.lean @@ -0,0 +1,107 @@ +import OAI.Computability.PerfectCompleteness.Decoding.CutGroupedProjectionLemmas +import OAI.Computability.PerfectCompleteness.Foundations.WholeArrayInteriorExteriorLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.SelectedArrayProjection + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open WholeArraySubtreeSplit SelectedArrayReplacement +open scoped Classical + +noncomputable section + +variable {branch : Nat → Nat} {n m t : Nat} + +theorem selectedRows_pullback (rows : Nat → Nat) (p : Path branch n (m + 1)) : + ∀ (left right : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (arrays : Arrays right rows), + selectedRows rows p left (ChildBlockProjection.arraysPullback rows q arrays) = + fun row => HPullback (CutGroupedProjection.cutProjection p q) + (selectedRows rows p right arrays row) := by + induction n generalizing m with + | zero => cases p + | succ n ih => + cases p with + | refl => intro left right q arrays; rfl + | step i p => + intro left right q arrays + exact ih p (childSlots left i) (childSlots right i) + (ChildAssemblyProjection.childProjection q i) + (fun node => arrays (.inr (i, node))) + +private theorem replace_selected (rows : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n (m + 1)) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (arrays : Arrays slots rows) + (fresh : Fin (rows (m + 1)) → H (subtreeSlots (.step i p) slots)) + (node : Nodes branch n) : + replace rows (.step i p) slots arrays fresh (.inr (i, node)) = + replace rows p (childSlots slots i) (fun v => arrays (.inr (i, v))) fresh node := + congrFun (WholeArraySampler.childrenAt_selected slots rows i + (replace rows p (childSlots slots i) (fun v => arrays (.inr (i, v))) fresh) + (fun child v => arrays (.inr (child.val, v)))) node + +private theorem replace_ordinary (rows : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n (m + 1)) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (arrays : Arrays slots rows) + (fresh : Fin (rows (m + 1)) → H (subtreeSlots (.step i p) slots)) + (child : RecursiveSampler.OffPath i) (node : Nodes branch n) : + replace rows (.step i p) slots arrays fresh (.inr (child.val, node)) = + arrays (.inr (child.val, node)) := + congrFun (WholeArraySampler.childrenAt_ordinary slots rows i + (replace rows p (childSlots slots i) (fun v => arrays (.inr (i, v))) fresh) + (fun j v => arrays (.inr (j.val, v))) child) node + +theorem replace_pullback (rows : Nat → Nat) (p : Path branch n (m + 1)) : + ∀ (left right : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (arrays : Arrays right rows) + (fresh : Fin (rows (m + 1)) → H (subtreeSlots p right)), + replace rows p left (ChildBlockProjection.arraysPullback rows q arrays) + (fun row => HPullback (CutGroupedProjection.cutProjection p q) (fresh row)) = + ChildBlockProjection.arraysPullback rows q (replace rows p right arrays fresh) := by + induction n generalizing m with + | zero => cases p + | succ n ih => + cases p with + | refl => + intro left right q arrays fresh + funext node row + rcases node with u | ⟨child, node⟩ + · cases u + rfl + · rfl + | step i p => + intro left right q arrays fresh + funext node row + rcases node with u | ⟨child, node⟩ + · cases u + rfl + · change replace rows (.step i p) left + (ChildBlockProjection.arraysPullback rows q arrays) + (fun row => HPullback (CutGroupedProjection.cutProjection (.step i p) q) + (fresh row)) (.inr (child, node)) row = + HPullback (ChildBlockProjection.nodeProjection q (.inr (child, node))) + (replace rows (.step i p) right arrays fresh (.inr (child, node)) row) + by_cases hchild : child = i + · subst child + rw [replace_selected, replace_selected] + exact congrFun (congrFun + (ih p (childSlots left i) (childSlots right i) + (ChildAssemblyProjection.childProjection q i) + (fun node => arrays (.inr (i, node))) fresh) node) row + · rw [replace_ordinary rows i p left _ _ ⟨child, hchild⟩ node, + replace_ordinary rows i p right arrays fresh ⟨child, hchild⟩ node] + rfl + +end +end PerfectCompleteness.SelectedArrayProjection + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/SourceChildProjectionComparison.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/SourceChildProjectionComparison.lean new file mode 100644 index 0000000000000000000000000000000000000000..1aa99d4214dae732b32ca946ccd1ee1f6d37f379 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/SourceChildProjectionComparison.lean @@ -0,0 +1,129 @@ +import OAI.Computability.PerfectCompleteness.Foundations.MultiplicationFormInjectiveLemmas +import OAI.Computability.PerfectCompleteness.Sampling.CommonProductVariationLemmas +import OAI.Computability.PerfectCompleteness.Sampling.SourcePhysicalAssemblyLaw + +namespace OAI + +section + +namespace PerfectCompleteness.SourceChildProjectionComparison + +open RecursiveSpaces TreeSourceSpaces HierarchicalArrays PointwiseSpaces +open SourceChildKernel +open UniqueGamesTheorem.Foundations.Games +open scoped Classical + +noncomputable section + +variable {branch : Nat → Nat} {n t v m : Nat} {C : Type*} [Fintype C] + +theorem block_card_le (rows : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Fintype.card (Block C rows slots) ≤ + ChildBlockCardinality.bound branch n t (Fintype.card C) rows := by + let e : Block C rows slots ≃ + ChildBlockCardinality.Raw (Fintype.card C) rows slots := + (Equiv.arrowCongr (Fintype.equivFin C) + (Equiv.refl (squareSpace (H slots)))).prodCongr (Equiv.refl (Arrays slots rows)) + calc + _ = Fintype.card (ChildBlockCardinality.Raw (Fintype.card C) rows slots) := + Fintype.card_congr e + _ ≤ _ := ChildBlockCardinality.fintype_card_le (Fintype.card C) rows slots + +def error (branch : Nat → Nat) (n t calls : Nat) (rows : Nat → Nat) (β : ℝ) : ℝ := + Real.sqrt ((1 + β ^ 2 * + ((ChildBlockCardinality.bound branch n t calls rows : ℝ) - 1)) ^ branch n - 1) / 2 + +variable (rows : Nat → Nat) (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch n) → Slots branch n) + +theorem conditional_observed_variation {Γ : Type*} [Fintype Γ] + (hbranch : 0 < branch n) + (sources : Sources (m := m) (t := t) designated) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) + (observe : ((i : Fin (branch n)) → + Native (C := C) (t := t) rows clauses designated i (sources i)) → Γ) : + ((FiniteProduct.law (fun i => SourceChildNativeLaw.leftLaw + (C := C) (t := t) rows clauses designated + (fun _ => ProjectionPosterior.bernoulli β hβ hβ') i (sources i))).pushforward + observe).totalVariation + ((FiniteProduct.law (fun i => FiniteDistribution.uniform + (Native (C := C) (t := t) rows clauses designated i (sources i)))).pushforward + observe) ≤ error branch n t (Fintype.card C) rows β := by + let : Nonempty (Fin (branch n)) := ⟨⟨0, hbranch⟩⟩ + let projected := fun i : Fin (branch n) => + (FiniteDistribution.uniform + (Projected (C := C) (t := t) rows clauses designated i (sources i))).pushforward + (SourceChildNativeLaw.pullback rows clauses designated i (sources i) true) + have hcard : ∀ i : Fin (branch n), + (Fintype.card (Native (C := C) (t := t) rows clauses designated i (sources i)) : ℝ) ≤ + (ChildBlockCardinality.bound branch n t (Fintype.card C) rows : ℝ) := by + intro i + exact_mod_cast block_card_le (C := C) rows (nativeSlots clauses designated i (sources i)) + have h := SparseReplacement.observed_uniform_variation projected β hβ hβ' + (ChildBlockCardinality.bound branch n t (Fintype.card C) rows : ℝ) hcard observe + have hlaw : SparseReplacement.law + (fun i => FiniteDistribution.uniform + (Native (C := C) (t := t) rows clauses designated i (sources i))) + projected β hβ hβ' = + FiniteProduct.law (fun i => SourceChildNativeLaw.leftLaw + (C := C) (t := t) rows clauses designated + (fun _ => ProjectionPosterior.bernoulli β hβ hβ') i (sources i)) := by + rfl + rw [hlaw] at h + simpa only [error, Fintype.card_fin] using h + +theorem conditional_assembled_variation + (hbranch : 0 < branch n) + (sources : Sources (m := m) (t := t) designated) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) : + ((FiniteProduct.law (fun i => SourceChildNativeLaw.leftLaw + (C := C) (t := t) rows clauses designated + (fun _ => ProjectionPosterior.bernoulli β hβ hβ') i (sources i))).pushforward + (CutChildGrouping.assemble (C := C) (parentLeftSlots clauses designated sources) rows)).totalVariation + (FiniteDistribution.uniform + (CutChildGrouping.Assembled (C := C) (parentLeftSlots clauses designated sources) rows)) ≤ + error branch n t (Fintype.card C) rows β := by + have h := conditional_observed_variation rows clauses designated hbranch sources β hβ hβ' + (CutChildGrouping.assemble (C := C) (parentLeftSlots clauses designated sources) rows) + have huniform : (FiniteProduct.law (fun i => FiniteDistribution.uniform + (Native (C := C) (t := t) rows clauses designated i (sources i)))).pushforward + (CutChildGrouping.assemble (C := C) (parentLeftSlots clauses designated sources) rows) = + FiniteDistribution.uniform + (CutChildGrouping.Assembled (C := C) (parentLeftSlots clauses designated sources) rows) := + CutChildGrouping.assemble_law (C := C) (parentLeftSlots clauses designated sources) rows + rw [huniform] at h + exact h + +theorem original_observed_variation [NeZero m] {Γ : Type*} [Fintype Γ] + (hbranch : 0 < branch n) (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) + (observe : SourcePhysicalAssemblyLaw.Observation (C := C) (t := t) + rows clauses designated → Γ) : + ((SourceChildKernel.originalLaw (C := C) (t := t) rows clauses designated + (fun _ => ProjectionPosterior.bernoulli β hβ hβ')).pushforward + (fun sample => observe (SourcePhysicalAssemblyLaw.observe rows clauses designated sample))).totalVariation + ((SourceChildKernel.originalLaw (C := C) (t := t) rows clauses designated + (fun _ => SourceChildNativeLaw.falseFlag)).pushforward + (fun sample => observe (SourcePhysicalAssemblyLaw.observe rows clauses designated sample))) ≤ + error branch n t (Fintype.card C) rows β := by + rw [← FiniteDistribution.pushforward_comp + (SourceChildKernel.originalLaw (C := C) (t := t) rows clauses designated + (fun _ => ProjectionPosterior.bernoulli β hβ hβ')) + (SourcePhysicalAssemblyLaw.observe rows clauses designated) observe, + ← FiniteDistribution.pushforward_comp + (SourceChildKernel.originalLaw (C := C) (t := t) rows clauses designated + (fun _ => SourceChildNativeLaw.falseFlag)) + (SourcePhysicalAssemblyLaw.observe rows clauses designated) observe, + SourcePhysicalAssemblyLaw.original_assembleLeft_law rows clauses designated + (fun _ => ProjectionPosterior.bernoulli β hβ hβ'), + SourcePhysicalAssemblyLaw.original_assembleLeft_false_law rows clauses designated] + refine ConditionalVariation.observed_sigma_le_const _ _ _ _ ?_ observe + intro sources + exact conditional_assembled_variation rows clauses designated hbranch sources β hβ hβ' + +end +end PerfectCompleteness.SourceChildProjectionComparison + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/SourceQuestionCollisionTransportLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/SourceQuestionCollisionTransportLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..e8da80564bf7e6f35f40bf15ca6f0c817fc0408c --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/SourceQuestionCollisionTransportLemmas.lean @@ -0,0 +1,444 @@ +import OAI.Computability.PerfectCompleteness.Construction.SourceQuestionRawSwap +import OAI.Computability.PerfectCompleteness.Construction.SourceQuestionUnmarkedRange +import OAI.Computability.PerfectCompleteness.Decoding.FixedSourceLowerCollision +import OAI.Computability.PerfectCompleteness.Decoding.LowerCutFormCollision + +namespace OAI + +section + +namespace PerfectCompleteness.SourceQuestionCollisionTransport + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays + +variable {branch rows repeats : Nat → Nat} {n height t v m : Nat} + (path : Path branch n (height + 1)) + (outside : Slots branch n → Fin t → MixedSupport.Slot) + (placeholder : Slots branch (height + 1) → Fin t → MixedSupport.Slot) + (clauses : Fin m → SourceClause.NormalizedClause v) + (upper : Nodes branch n) (level : Nat) + (d : HierarchicalFrozenTables.LowerNodes upper level) + (hbranch : ∀ k < n, 0 < branch k) + {adviceRows : Nat} (A : ManyGoodRows.RowMap (Block rows upper) adviceRows) + (exterior : CleanPhysicalReplay.Exterior rows repeats path outside placeholder) + (tables : (q : SourceQuestionLowerForms.Questions + (branch := branch) (height := height) (t := t) (m := m)) → + SourceQuestionLowerForms.UpperTable (rows := rows) path outside clauses + upper level (adviceRows := adviceRows) q) + (cutoff : Nat) + +def firstAnswer + (q : SourceQuestionLowerForms.Questions + (branch := branch) (height := height) (t := t) (m := m)) + (raw : SourceQuestionLowerForms.Raw (rows := rows) (repeats := repeats) path clauses q) : + Option (HierarchicalDecoderTables.Answer + (SourceQuestionLowerForms.slots path outside clauses q) upper level d) := + LowerCutDecoderForm.answer (SourceQuestionLowerForms.slots path outside clauses q) + upper level d hbranch A (tables q) cutoff + (LowerCutPair.first rows repeats path (SourceQuestionLowerForms.slots path outside clauses q) + (CleanPhysicalReplay.exteriorAt rows repeats path outside placeholder + (SourceChildMarkedLaw.questionSlots clauses q) exterior) + (SourceQuestionLowerForms.rawAtCut path outside clauses q raw)) + +def secondAnswer (direction : BucketSampler.Direction (rows (height + 1))) + (q : SourceQuestionLowerForms.Questions + (branch := branch) (height := height) (t := t) (m := m)) + (raw : SourceQuestionLowerForms.Raw (rows := rows) (repeats := repeats) path clauses q) : + Option (HierarchicalDecoderTables.Answer + (SourceQuestionLowerForms.slots path outside clauses q) upper level d) := + LowerCutDecoderForm.answer (SourceQuestionLowerForms.slots path outside clauses q) + upper level d hbranch A (tables q) cutoff + (LowerCutPair.second rows repeats path (SourceQuestionLowerForms.slots path outside clauses q) + (CleanPhysicalReplay.exteriorAt rows repeats path outside placeholder + (SourceChildMarkedLaw.questionSlots clauses q) exterior) + direction (SourceQuestionLowerForms.rawAtCut path outside clauses q raw)) + +variable + (designated : Fin (branch height) → Slots branch height) + (q : SourceQuestionLowerForms.Questions + (branch := branch) (height := height) (t := t) (m := m)) + (choices : SourceQuestionKernelJoint.ChoiceTuple (branch := branch) (n := height) (t := t)) + (raw : (i : Fin (branch height)) → + SourceChildKernel.Raw (C := SourceQuestionLowerForms.Calls (rows := rows) (repeats := repeats) path) + (t := t) rows clauses designated i) + +def projection : ∀ s k, MixedSupport.Projection + (SourceQuestionLowerForms.slots path outside clauses q s k) + (CutSlotAssembly.fill path outside + (SourceChildKernel.parentRightSlots rows clauses designated + (SourceQuestionKernelJoint.sources designated q choices) raw) s k) := + CutProjectionAssembly.fillProjection path outside + (SourceChildMarkedLaw.questionSlots clauses q) + (SourceChildKernel.parentRightSlots rows clauses designated + (SourceQuestionKernelJoint.sources designated q choices) raw) + (SourceQuestionUnmarkedRange.projection rows clauses designated q choices raw) + +def globalRestricted (direction : BucketSampler.Direction (rows (height + 1))) : Bool := + let record := SourceChildMarkedLaw.markedBlocks rows clauses designated q choices raw + BilinearCollisionTransfer.restrictedCollision + ((firstAnswer path outside placeholder clauses upper level d hbranch A exterior tables cutoff + q record.2).map (OddListExtraction.multiplicationForm + (HierarchicalDecoderTables.LowerH + (SourceQuestionLowerForms.slots path outside clauses q) upper level d))) + ((secondAnswer path outside placeholder clauses upper level d hbranch A exterior tables cutoff + direction q record.2).map (OddListExtraction.multiplicationForm + (HierarchicalDecoderTables.LowerH + (SourceQuestionLowerForms.slots path outside clauses q) upper level d))) + (LinearMap.range (HPullback (ChildBlockProjection.nodeProjection + (projection path outside clauses designated q choices raw) + (HierarchicalLeftDecoder.LowerNode upper level d)))) + +theorem globalRestricted_imp_native + (hnode : WholeArrayInteriorExterior.upperNode path = + HierarchicalLeftDecoder.LowerNode upper level d) + (direction : BucketSampler.Direction (rows (height + 1))) + (hcollision : globalRestricted path outside placeholder clauses upper level d hbranch A + exterior tables cutoff designated q choices raw direction = true) : + BilinearCollisionTransfer.restrictedCollision + (SourceQuestionLowerForms.first path outside placeholder clauses upper level d hnode hbranch A + exterior tables cutoff q (SourceChildMarkedLaw.markedBlocks rows clauses designated q choices raw).2) + (SourceQuestionLowerForms.second path outside placeholder clauses upper level d hnode hbranch A + exterior tables cutoff direction q + (SourceChildMarkedLaw.markedBlocks rows clauses designated q choices raw).2) + (ChildUnmarkedSpace.space (SourceChildMarkedLaw.questionSlots clauses q) + (SourceChildMarkedLaw.markedBlocks rows clauses designated q choices raw).1) = true := by + have hU : ChildUnmarkedSpace.space (SourceChildMarkedLaw.questionSlots clauses q) + (SourceChildMarkedLaw.markedBlocks rows clauses designated q choices raw).1 ≤ + LinearMap.range (HPullback + (SourceQuestionUnmarkedRange.projection rows clauses designated q choices raw)) := + SourceQuestionUnmarkedRange.unmarked_le_range rows clauses designated q choices raw + have h := LowerCutFormCollision.restricted_on_native path outside + (SourceChildMarkedLaw.questionSlots clauses q) upper level d hnode + (SourceChildKernel.parentRightSlots rows clauses designated + (SourceQuestionKernelJoint.sources designated q choices) raw) + (SourceQuestionUnmarkedRange.projection rows clauses designated q choices raw) + (firstAnswer path outside placeholder clauses upper level d hbranch A exterior tables cutoff + q (SourceChildMarkedLaw.markedBlocks rows clauses designated q choices raw).2) + (secondAnswer path outside placeholder clauses upper level d hbranch A exterior tables cutoff + direction q (SourceChildMarkedLaw.markedBlocks rows clauses designated q choices raw).2) + (ChildUnmarkedSpace.space (SourceChildMarkedLaw.questionSlots clauses q) + (SourceChildMarkedLaw.markedBlocks rows clauses designated q choices raw).1) + hU hcollision + have hmapper : + LowerCutFormCollision.nativeForm path outside (SourceChildMarkedLaw.questionSlots clauses q) + upper level d hnode = + (fun answer : HierarchicalDecoderTables.Answer + (SourceQuestionLowerForms.slots path outside clauses q) upper level d => + CutNativeForms.formCast (SourceQuestionLowerForms.cutSlots_eq path outside clauses q) + (LowerCutDecoderForm.form path (SourceQuestionLowerForms.slots path outside clauses q) + upper level d hnode answer)) := by + funext answer + rfl + have hfirst (record : SourceQuestionLowerForms.Raw + (rows := rows) (repeats := repeats) path clauses q) : + SourceQuestionLowerForms.first path outside placeholder clauses upper level d hnode hbranch A + exterior tables cutoff q record = + (firstAnswer path outside placeholder clauses upper level d hbranch A exterior tables cutoff + q record).map (LowerCutFormCollision.nativeForm path outside + (SourceChildMarkedLaw.questionSlots clauses q) upper level d hnode) := by + change ((firstAnswer path outside placeholder clauses upper level d hbranch A exterior tables + cutoff q record).map + (LowerCutDecoderForm.form path (SourceQuestionLowerForms.slots path outside clauses q) + upper level d hnode)).map + (CutNativeForms.formCast (SourceQuestionLowerForms.cutSlots_eq path outside clauses q)) = _ + rw [Option.map_map] + exact congrArg (fun mapper => (firstAnswer path outside placeholder clauses upper level d + hbranch A exterior tables cutoff q record).map mapper) hmapper.symm + have hsecond (record : SourceQuestionLowerForms.Raw + (rows := rows) (repeats := repeats) path clauses q) : + SourceQuestionLowerForms.second path outside placeholder clauses upper level d hnode hbranch A + exterior tables cutoff direction q record = + (secondAnswer path outside placeholder clauses upper level d hbranch A exterior tables cutoff + direction q record).map (LowerCutFormCollision.nativeForm path outside + (SourceChildMarkedLaw.questionSlots clauses q) upper level d hnode) := by + change ((secondAnswer path outside placeholder clauses upper level d hbranch A exterior tables + cutoff direction q record).map + (LowerCutDecoderForm.form path (SourceQuestionLowerForms.slots path outside clauses q) + upper level d hnode)).map + (CutNativeForms.formCast (SourceQuestionLowerForms.cutSlots_eq path outside clauses q)) = _ + rw [Option.map_map] + exact congrArg (fun mapper => (secondAnswer path outside placeholder clauses upper level d + hbranch A exterior tables cutoff direction q record).map mapper) hmapper.symm + rw [hfirst, hsecond] + exact h + +end +end PerfectCompleteness.SourceQuestionCollisionTransport + +end + +section + +namespace PerfectCompleteness.FixedSourceGlobalCollision + +noncomputable section + +open scoped Classical BigOperators +open FixedParameters FixedRows RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +variable {δ : ℚ} {hδ : 0 < δ} (parameters : Parameters δ hδ) + {height v m : Nat} [NeZero m] + (path : Path (branch parameters) parameters.plan.depth (height + 1)) + (outside : Slots (branch parameters) parameters.plan.depth → + Fin (sourceLength parameters.plan hδ) → MixedSupport.Slot) + (placeholder : Slots (branch parameters) (height + 1) → + Fin (sourceLength parameters.plan hδ) → MixedSupport.Slot) + (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch parameters height) → Slots (branch parameters) height) + (upper : Nodes (branch parameters) parameters.plan.depth) + (d : HierarchicalFrozenTables.LowerNodes upper (height + 1)) + (hnode : WholeArrayInteriorExterior.upperNode path = + HierarchicalLeftDecoder.LowerNode upper (height + 1) d) + {adviceRows : Nat} + (A : ManyGoodRows.RowMap (Block (rows parameters.plan) upper) adviceRows) + (exterior : CleanPhysicalReplay.Exterior (rows parameters.plan) (repeats parameters.plan) + path outside placeholder) + +abbrev Questions := FixedSourceChildCollision.Questions + (m := m) parameters (height := height) + +abbrev Table (q : Questions (m := m) parameters (height := height)) := + SourceQuestionLowerForms.UpperTable (rows := rows parameters.plan) + path outside clauses upper (height + 1) (adviceRows := adviceRows) q + +local instance rowSpaceFintype (q : Questions (m := m) parameters (height := height)) : + Fintype (NodeEmbedding.RowSpace (SourceQuestionLowerForms.slots path outside clauses q) upper) := + Fintype.ofFinite _ + +local instance upperAnswerFintype (q : Questions (m := m) parameters (height := height)) : + Fintype (HierarchicalAllDecoderTables.UpperAnswer + (SourceQuestionLowerForms.slots path outside clauses q) upper) := + LeftDecoder.dualFintype + (V := NodeEmbedding.RowSpace (SourceQuestionLowerForms.slots path outside clauses q) upper) + +local instance tableFintype (q : Questions (m := m) parameters (height := height)) : + Fintype (Table parameters path outside clauses upper (adviceRows := adviceRows) q) := + inferInstanceAs (Fintype (HierarchicalAllDecoderTables.Input (rows := rows parameters.plan) + (SourceQuestionLowerForms.slots path outside clauses q) upper (height + 1) adviceRows → + HierarchicalAllDecoderTables.UpperAnswer + (SourceQuestionLowerForms.slots path outside clauses q) upper)) + +abbrev TableFamily := (q : Questions (m := m) parameters (height := height)) → + Table parameters path outside clauses upper (adviceRows := adviceRows) q + +local instance directionNonempty : + Nonempty (BucketSampler.Direction (rows parameters.plan (height + 1))) := + ⟨BucketUniform.coordinateDirection ⟨0, lt_of_lt_of_le Nat.zero_lt_one + (parameters.plan.rows_pos (parameters.plan.depth - (height + 1)))⟩⟩ + +def flag : Fin (branch parameters height) → FiniteDistribution Bool := + fun _ => ProjectionPosterior.bernoulli (projectionProbability parameters height : ℝ) + (by exact_mod_cast (projectionProbability_bounds parameters height).1.le) + (by exact_mod_cast (projectionProbability_bounds parameters height).2.le) + +abbrev Choice := SourceQuestionKernelJoint.ChoiceTuple + (branch := branch parameters) (n := height) (t := sourceLength parameters.plan hδ) + +def nativeProbability + (tables : TableFamily parameters path outside clauses upper (adviceRows := adviceRows)) + (direction : BucketSampler.Direction (rows parameters.plan (height + 1))) : ℝ := + (PreliminarySampler.questionsLaw (branch := branch parameters) (n := height + 1) + (t := sourceLength parameters.plan hδ) (m := m)).expectation (fun q => + (SourceProjectedTag.positionLaw (branch := branch parameters) (n := height) + (t := sourceLength parameters.plan hδ)).expectation (fun choices => + (SourceQuestionRawSwap.kernelLaw + (C := FixedSourceChildCollision.Calls parameters path) + (rows parameters.plan) clauses designated (flag parameters) q choices).probability (fun raw => + let record := SourceChildMarkedLaw.markedBlocks + (rows parameters.plan) clauses designated q choices raw + BilinearCollisionTransfer.restrictedCollision + (FixedSourceLowerCollision.first parameters path outside placeholder clauses + upper d hnode A exterior tables q record.2) + (FixedSourceLowerCollision.second parameters path outside placeholder clauses + upper d hnode A exterior tables direction q record.2) + (ChildUnmarkedSpace.space (SourceChildMarkedLaw.questionSlots clauses q) record.1)))) + +theorem nativeProbability_eq_marked + (tables : TableFamily parameters path outside clauses upper (adviceRows := adviceRows)) + (direction : BucketSampler.Direction (rows parameters.plan (height + 1))) : + nativeProbability parameters path outside placeholder clauses designated upper d hnode A + exterior tables direction = + FixedSourceLowerCollision.markedProbability parameters path outside placeholder clauses + designated upper d hnode A exterior tables direction := by + let event (q : Questions (m := m) parameters (height := height)) + (choices : Choice parameters (height := height)) + (raw : SourceChildKernelJoint.RawTuple + (C := FixedSourceChildCollision.Calls parameters path) + (t := sourceLength parameters.plan hδ) (rows parameters.plan) clauses designated) : Bool := + let record := SourceChildMarkedLaw.markedBlocks + (rows parameters.plan) clauses designated q choices raw + BilinearCollisionTransfer.restrictedCollision + (FixedSourceLowerCollision.first parameters path outside placeholder clauses + upper d hnode A exterior tables q record.2) + (FixedSourceLowerCollision.second parameters path outside placeholder clauses + upper d hnode A exterior tables direction q record.2) + (ChildUnmarkedSpace.space (SourceChildMarkedLaw.questionSlots clauses q) record.1) + have hlaw : FixedSourceChildCollision.markedLaw parameters path clauses designated = + SourceChildKernel.originalLaw + (C := FixedSourceChildCollision.Calls parameters path) + (t := sourceLength parameters.plan hδ) + (rows parameters.plan) clauses designated (flag parameters) := rfl + have hevent : FixedSourceChildCollision.restrictedEvent parameters path clauses designated + (FixedSourceLowerCollision.first parameters path outside placeholder clauses + upper d hnode A exterior tables) + (FixedSourceLowerCollision.second parameters path outside placeholder clauses + upper d hnode A exterior tables direction) = + (fun sample => event + (SourceQuestionRawSwap.insideQuestions (rows parameters.plan) clauses designated sample) + (SourceQuestionRawSwap.positions (rows parameters.plan) clauses designated sample) + (SourceQuestionRawSwap.raw (rows parameters.plan) clauses designated sample)) := by + funext sample + rfl + unfold nativeProbability FixedSourceLowerCollision.markedProbability + rw [hlaw, hevent] + simp_rw [DecoderTableCoupling.probability_eq_expectation] + exact (SourceQuestionRawSwap.originalLaw_expectation + (C := FixedSourceChildCollision.Calls parameters path) + (rows parameters.plan) clauses designated (flag parameters) + (fun q choices raw => if event q choices raw then 1 else 0)).symm + +def globalProbability + (tables : TableFamily parameters path outside clauses upper (adviceRows := adviceRows)) + (direction : BucketSampler.Direction (rows parameters.plan (height + 1))) : ℝ := + (PreliminarySampler.questionsLaw (branch := branch parameters) (n := height + 1) + (t := sourceLength parameters.plan hδ) (m := m)).expectation (fun q => + (SourceProjectedTag.positionLaw (branch := branch parameters) (n := height) + (t := sourceLength parameters.plan hδ)).expectation (fun choices => + (SourceQuestionRawSwap.kernelLaw + (C := FixedSourceChildCollision.Calls parameters path) + (rows parameters.plan) clauses designated (flag parameters) q choices).probability + (fun raw => SourceQuestionCollisionTransport.globalRestricted path outside placeholder + clauses upper (height + 1) d (FixedLowerRawCollision.branchPositive parameters) + A exterior tables (cutoff parameters.plan hδ) designated q choices raw direction))) + +theorem globalProbability_le_marked + (tables : TableFamily parameters path outside clauses upper (adviceRows := adviceRows)) + (direction : BucketSampler.Direction (rows parameters.plan (height + 1))) : + globalProbability parameters path outside placeholder clauses designated upper d A + exterior tables direction ≤ + FixedSourceLowerCollision.markedProbability parameters path outside placeholder clauses + designated upper d hnode A exterior tables direction := by + rw [← nativeProbability_eq_marked] + apply SmallBias.expectation_mono + intro q + apply SmallBias.expectation_mono + intro choices + apply FiniteDistribution.probability_mono + intro raw hcollision + exact SourceQuestionCollisionTransport.globalRestricted_imp_native path outside placeholder clauses + upper (height + 1) d (FixedLowerRawCollision.branchPositive parameters) A exterior tables + (cutoff parameters.plan hδ) designated q choices raw hnode direction hcollision + +def localTables (q : Questions (m := m) parameters (height := height)) + (table : Table parameters path outside clauses upper (adviceRows := adviceRows) q) : + TableFamily parameters path outside clauses upper (adviceRows := adviceRows) := + Function.update (fun _ => fun _ => 0) q table + +def localProbability (q : Questions (m := m) parameters (height := height)) + (table : Table parameters path outside clauses upper (adviceRows := adviceRows) q) + (direction : BucketSampler.Direction (rows parameters.plan (height + 1))) : ℝ := + (SourceProjectedTag.positionLaw (branch := branch parameters) (n := height) + (t := sourceLength parameters.plan hδ)).expectation (fun choices => + (SourceQuestionRawSwap.kernelLaw + (C := FixedSourceChildCollision.Calls parameters path) + (rows parameters.plan) clauses designated (flag parameters) q choices).probability + (fun raw => SourceQuestionCollisionTransport.globalRestricted path outside placeholder + clauses upper (height + 1) d (FixedLowerRawCollision.branchPositive parameters) + A exterior (localTables parameters path outside clauses upper q table) + (cutoff parameters.plan hδ) designated q choices raw direction)) + +theorem globalProbability_eq_local + (tables : TableFamily parameters path outside clauses upper (adviceRows := adviceRows)) + (direction : BucketSampler.Direction (rows parameters.plan (height + 1))) : + globalProbability parameters path outside placeholder clauses designated upper d A + exterior tables direction = + (PreliminarySampler.questionsLaw (branch := branch parameters) (n := height + 1) + (t := sourceLength parameters.plan hδ) (m := m)).expectation (fun q => + localProbability parameters path outside placeholder clauses designated upper d A + exterior q (tables q) direction) := by + simp only [globalProbability, localProbability, SourceQuestionCollisionTransport.globalRestricted, + SourceQuestionCollisionTransport.firstAnswer, SourceQuestionCollisionTransport.secondAnswer, + localTables, Function.update_self] + +variable + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount (branch parameters) parameters.plan.depth + (sourceLength parameters.plan hδ))) + (useful : (q : Questions (m := m) parameters (height := height)) → + (bg : HierarchicalMatrixTable.Background (rows := rows parameters.plan) + (SourceQuestionLowerForms.slots path outside clauses q) upper) → + HierarchicalFrozenTables.QuotientMatrix + (SourceQuestionLowerForms.slots path outside clauses q) upper (height + 1) bg → Prop) + (density : ℝ) + +include hnode in +theorem mean_global_le (hdensity : 0 < density) : + (FixedSourceLowerCollision.tableLaw parameters path outside clauses upper σ useful density).expectation + (fun tables => (FiniteDistribution.uniform + (BucketSampler.Direction (rows parameters.plan (height + 1)))).expectation + (globalProbability parameters path outside placeholder clauses designated upper d A + exterior tables)) ≤ + FixedRankContradiction.gamma parameters (Nodes.height upper) ^ 2 / 8 + + 2 * parameters.accuracy := by + apply le_trans _ (FixedSourceLowerCollision.mean_marked_le parameters path outside placeholder clauses + designated upper d hnode A exterior σ useful density hdensity) + apply SmallBias.expectation_mono + intro tables + apply SmallBias.expectation_mono + intro direction + exact globalProbability_le_marked parameters path outside placeholder clauses designated upper d hnode A + exterior tables direction + +include hnode in + +theorem mean_local_le (hdensity : 0 < density) : + (FiniteDistribution.uniform + (BucketSampler.Direction (rows parameters.plan (height + 1)))).expectation (fun direction => + (PreliminarySampler.questionsLaw (branch := branch parameters) (n := height + 1) + (t := sourceLength parameters.plan hδ) (m := m)).expectation (fun q => + (HierarchicalAllDecoderTables.upperTableLaw + (SourceQuestionLowerForms.slots path outside clauses q) upper (height + 1) + σ (useful q) adviceRows density).expectation (fun table => + localProbability parameters path outside placeholder clauses designated upper d A + exterior q table direction))) ≤ + FixedRankContradiction.gamma parameters (Nodes.height upper) ^ 2 / 8 + + 2 * parameters.accuracy := by + have h := mean_global_le parameters path outside placeholder clauses designated upper d hnode A exterior + σ useful density hdensity + have hglobal : ∀ tables : TableFamily parameters path outside clauses upper + (adviceRows := adviceRows), + globalProbability parameters path outside placeholder clauses designated upper d A + exterior tables = + fun direction => (PreliminarySampler.questionsLaw + (branch := branch parameters) (n := height + 1) + (t := sourceLength parameters.plan hδ) (m := m)).expectation (fun q => + localProbability parameters path outside placeholder clauses designated upper d A + exterior q (tables q) direction) := by + intro tables + funext direction + exact globalProbability_eq_local parameters path outside placeholder clauses designated upper d A + exterior tables direction + simp_rw [hglobal] at h + rw [FiniteDistribution.expectation_comm] at h + convert h using 1 + apply FiniteDistribution.expectation_congr + intro direction + rw [FiniteDistribution.expectation_comm] + apply FiniteDistribution.expectation_congr + intro q + exact (FiniteProduct.expectation_eval + (fun q => HierarchicalAllDecoderTables.upperTableLaw + (SourceQuestionLowerForms.slots path outside clauses q) upper (height + 1) + σ (useful q) adviceRows density) q + (fun table => localProbability parameters path outside placeholder clauses designated upper d A + exterior q table direction)).symm + +end +end PerfectCompleteness.FixedSourceGlobalCollision + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/SourceQuestionPhysicalCollision.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/SourceQuestionPhysicalCollision.lean new file mode 100644 index 0000000000000000000000000000000000000000..3ec13afe56eb79f2c58d7084d34520242a040391 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/SourceQuestionPhysicalCollision.lean @@ -0,0 +1,255 @@ +import OAI.Computability.PerfectCompleteness.Construction.SourceQuestionPairPullback +import OAI.Computability.PerfectCompleteness.Construction.SourceQuestionPhysicalHigh +import OAI.Computability.PerfectCompleteness.Construction.SourceQuestionRawSwap +import OAI.Computability.PerfectCompleteness.Decoding.SourceQuestionCollisionTransportLemmas +import OAI.Computability.PerfectCompleteness.Decoding.SourceQuestionTaggedProjection + +namespace OAI + +section + +namespace PerfectCompleteness.SourceQuestionPhysicalCollision + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +variable {branch rows repeats : Nat → Nat} {n height t v m : Nat} + (path : Path branch n (height + 1)) + (outside : Slots branch n → Fin t → MixedSupport.Slot) + (placeholder : Slots branch (height + 1) → Fin t → MixedSupport.Slot) + (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch height) → Slots branch height) + (upper : Nodes branch n) (level : Nat) + (d : HierarchicalFrozenTables.LowerNodes upper level) + (hbranch : ∀ k < n, 0 < branch k) + {adviceRows : Nat} (A : ManyGoodRows.RowMap (Block rows upper) adviceRows) + (exterior : CleanPhysicalReplay.Exterior rows repeats path outside placeholder) + (q : SourceQuestionLowerForms.Questions + (branch := branch) (height := height) (t := t) (m := m)) + (choices : SourceQuestionKernelJoint.ChoiceTuple + (branch := branch) (n := height) (t := t)) + (direction : BucketSampler.Direction (rows (height + 1))) + (cutoff : Nat) + (table : SourceQuestionLowerForms.UpperTable (rows := rows) + path outside clauses upper level (adviceRows := adviceRows) q) + +def rawEvent (flags : SourceProjectedTag.Flags (branch := branch) (n := height)) + (raw : CutChildGrouping.Raw + (C := SourceQuestionLowerForms.Calls (rows := rows) (repeats := repeats) path) + (SourceProjectedTag.mixedInside clauses designated q choices flags) rows) : Bool := + LowerProjectedFiberAverage.collision + (SourceQuestionPhysicalHigh.originalSlots path outside clauses q) + (SourceQuestionPhysicalHigh.projectedSlots path outside clauses designated q choices flags) + (SourceQuestionPhysicalHigh.projection path outside clauses designated q choices flags) + upper level hbranch d A cutoff table + (LowerCutPair.arraysPair rows repeats path + (SourceQuestionPhysicalHigh.projectedSlots path outside clauses designated q choices flags) + (SourceQuestionPhysicalHigh.exteriorAt path outside placeholder clauses designated + q choices flags exterior) direction + (SourceQuestionPairPullback.rawAtCut rows repeats path outside + (SourceProjectedTag.mixedInside clauses designated q choices flags) raw)) + +theorem collision_eq_probability + (flags : SourceProjectedTag.Flags (branch := branch) (n := height)) : + SourceQuestionPhysicalHigh.collision path outside placeholder clauses designated + q choices flags upper level d hbranch A exterior direction cutoff table = + (CutChildGrouping.rawLaw + (C := SourceQuestionLowerForms.Calls (rows := rows) (repeats := repeats) path) + (SourceProjectedTag.mixedInside clauses designated q choices flags) rows).probability + (rawEvent path outside placeholder clauses designated upper level d hbranch A exterior + q choices direction cutoff table flags) := by + let event : LowerCutPair.Raw rows repeats path + (SourceQuestionPhysicalHigh.projectedSlots path outside clauses designated q choices flags) → + Bool := fun raw => + LowerProjectedFiberAverage.collision + (SourceQuestionPhysicalHigh.originalSlots path outside clauses q) + (SourceQuestionPhysicalHigh.projectedSlots path outside clauses designated q choices flags) + (SourceQuestionPhysicalHigh.projection path outside clauses designated q choices flags) + upper level hbranch d A cutoff table + (LowerCutPair.arraysPair rows repeats path + (SourceQuestionPhysicalHigh.projectedSlots path outside clauses designated q choices flags) + (SourceQuestionPhysicalHigh.exteriorAt path outside placeholder clauses designated + q choices flags exterior) direction raw) + have hlaw : + (CutChildGrouping.rawLaw + (C := SourceQuestionLowerForms.Calls (rows := rows) (repeats := repeats) path) + (SourceProjectedTag.mixedInside clauses designated q choices flags) rows).pushforward + (SourceQuestionPairPullback.rawAtCut rows repeats path outside + (SourceProjectedTag.mixedInside clauses designated q choices flags)) = + CutChildGrouping.rawLaw + (C := SourceQuestionLowerForms.Calls (rows := rows) (repeats := repeats) path) + (WholeCutGrouping.cutSlots path + (SourceQuestionPhysicalHigh.projectedSlots path outside clauses designated + q choices flags)) rows := + SourceQuestionLowerForms.rawCast_law rows + (CleanPhysicalReplay.cutSlots_fill path outside + (SourceProjectedTag.mixedInside clauses designated q choices flags)).symm + exact (congrArg (fun μ : FiniteDistribution (LowerCutPair.Raw rows repeats path + (SourceQuestionPhysicalHigh.projectedSlots path outside clauses designated q choices flags)) => + μ.probability event) hlaw).symm.trans + (FiniteDistribution.probability_pushforward _ _ event) + +theorem flags_collision_eq_kernels + (flag : Fin (branch height) → FiniteDistribution Bool) : + (SourceProjectedTag.flagLaw flag).expectation (fun flags => + SourceQuestionPhysicalHigh.collision path outside placeholder clauses designated + q choices flags upper level d hbranch A exterior direction cutoff table) = + (SourceQuestionRawSwap.kernelLaw + (C := SourceQuestionLowerForms.Calls (rows := rows) (repeats := repeats) path) + rows clauses designated flag q choices).probability (fun raw => + let observed := SourcePhysicalTaggedChildren.observe rows clauses designated + (SourceQuestionKernelJoint.sources designated q choices) raw + rawEvent path outside placeholder clauses designated upper level d hbranch A exterior + q choices direction cutoff table observed.1 observed.2) := by + let event : + (Σ flags : SourceProjectedTag.Flags (branch := branch) (n := height), + CutChildGrouping.Raw + (C := SourceQuestionLowerForms.Calls (rows := rows) (repeats := repeats) path) + (SourcePhysicalTaggedChildren.slots clauses designated + (SourceQuestionKernelJoint.sources designated q choices) flags) rows) → Bool := + fun observed => rawEvent path outside placeholder clauses designated upper level d hbranch A + exterior q choices direction cutoff table observed.1 observed.2 + have h := congrArg (fun μ : FiniteDistribution + (Σ flags : SourceProjectedTag.Flags (branch := branch) (n := height), + CutChildGrouping.Raw + (C := SourceQuestionLowerForms.Calls (rows := rows) (repeats := repeats) path) + (SourcePhysicalTaggedChildren.slots clauses designated + (SourceQuestionKernelJoint.sources designated q choices) flags) rows) => + μ.probability event) + (SourcePhysicalTaggedChildren.kernels_tagged + (C := SourceQuestionLowerForms.Calls (rows := rows) (repeats := repeats) path) + rows clauses designated flag (SourceQuestionKernelJoint.sources designated q choices)) + have hpush := FiniteDistribution.probability_pushforward + (FiniteProduct.law (fun i => SourceChildKernel.kernel + (C := SourceQuestionLowerForms.Calls (rows := rows) (repeats := repeats) path) + rows clauses designated flag i (SourceQuestionKernelJoint.sources designated q choices i))) + (SourcePhysicalTaggedChildren.observe rows clauses designated + (SourceQuestionKernelJoint.sources designated q choices)) event + have hsigma := CompletionSoundness.sigmaLaw_probability (FiniteProduct.law flag) + (fun flags => CutChildGrouping.rawLaw + (C := SourceQuestionLowerForms.Calls (rows := rows) (repeats := repeats) path) + (SourcePhysicalTaggedChildren.slots clauses designated + (SourceQuestionKernelJoint.sources designated q choices) flags) rows) event + calc + _ = (SourceProjectedTag.flagLaw flag).expectation (fun flags => + (CutChildGrouping.rawLaw + (C := SourceQuestionLowerForms.Calls (rows := rows) (repeats := repeats) path) + (SourceProjectedTag.mixedInside clauses designated q choices flags) rows).probability + (rawEvent path outside placeholder clauses designated upper level d hbranch A exterior + q choices direction cutoff table flags)) := by + apply FiniteDistribution.expectation_congr + intro flags + exact collision_eq_probability path outside placeholder clauses designated upper level d + hbranch A exterior q choices direction cutoff table flags + _ = _ := (hpush.symm.trans (h.trans hsigma)).symm + +variable + (tables : (q : SourceQuestionLowerForms.Questions + (branch := branch) (height := height) (t := t) (m := m)) → + SourceQuestionLowerForms.UpperTable (rows := rows) + path outside clauses upper level (adviceRows := adviceRows) q) + +theorem rawEvent_observe + (raw : SourceChildKernelJoint.RawTuple + (C := SourceQuestionLowerForms.Calls (rows := rows) (repeats := repeats) path) + (t := t) rows clauses designated) : + let observed := SourcePhysicalTaggedChildren.observe rows clauses designated + (SourceQuestionKernelJoint.sources designated q choices) raw + rawEvent path outside placeholder clauses designated upper level d hbranch A exterior + q choices direction cutoff (tables q) observed.1 observed.2 = + SourceQuestionCollisionTransport.globalRestricted path outside placeholder clauses + upper level d hbranch A exterior tables cutoff designated q choices raw direction := by + let observed : + Σ flags : SourceProjectedTag.Flags (branch := branch) (n := height), + CutChildGrouping.Raw + (C := SourceQuestionLowerForms.Calls (rows := rows) (repeats := repeats) path) + (SourceProjectedTag.mixedInside clauses designated q choices flags) rows := + SourcePhysicalTaggedChildren.observe rows clauses designated + (SourceQuestionKernelJoint.sources designated q choices) raw + let first : SourceQuestionLowerForms.Raw (rows := rows) (repeats := repeats) path clauses q → + Arrays (SourceQuestionLowerForms.slots path outside clauses q) rows := fun record => + LowerCutPair.first rows repeats path (SourceQuestionLowerForms.slots path outside clauses q) + (CleanPhysicalReplay.exteriorAt rows repeats path outside placeholder + (SourceChildMarkedLaw.questionSlots clauses q) exterior) + (SourceQuestionLowerForms.rawAtCut path outside clauses q record) + let second : SourceQuestionLowerForms.Raw (rows := rows) (repeats := repeats) path clauses q → + Arrays (SourceQuestionLowerForms.slots path outside clauses q) rows := fun record => + LowerCutPair.second rows repeats path (SourceQuestionLowerForms.slots path outside clauses q) + (CleanPhysicalReplay.exteriorAt rows repeats path outside placeholder + (SourceChildMarkedLaw.questionSlots clauses q) exterior) direction + (SourceQuestionLowerForms.rawAtCut path outside clauses q record) + let read : Arrays (SourceQuestionLowerForms.slots path outside clauses q) rows → + Option (BilinearCollisionTransfer.Form (𝕜 := F2) + (H := HierarchicalDecoderTables.LowerH + (SourceQuestionLowerForms.slots path outside clauses q) upper level d)) := fun arrays => + (LowerCutDecoderForm.answer (SourceQuestionLowerForms.slots path outside clauses q) + upper level d hbranch A (tables q) cutoff arrays).map + (OddListExtraction.multiplicationForm (HierarchicalDecoderTables.LowerH + (SourceQuestionLowerForms.slots path outside clauses q) upper level d)) + have hfirst := SourceQuestionPairPullback.first_pullback rows repeats path outside placeholder + (SourceChildMarkedLaw.questionSlots clauses q) + (SourceProjectedTag.mixedInside clauses designated q choices observed.1) + (SourceProjectedTag.projection clauses designated q choices observed.1) + exterior observed.2 + have hsecond := SourceQuestionPairPullback.second_pullback rows repeats path outside placeholder + (SourceChildMarkedLaw.questionSlots clauses q) + (SourceProjectedTag.mixedInside clauses designated q choices observed.1) + (SourceProjectedTag.projection clauses designated q choices observed.1) + exterior direction observed.2 + have hrecord : (SourceChildMarkedLaw.markedBlocks rows clauses designated q choices raw).2 = + ChildAssemblyProjection.rawPullback rows + (SourceProjectedTag.projection clauses designated q choices observed.1) observed.2 := + SourceQuestionTaggedProjection.markedBlocks_snd rows clauses designated q choices raw + have hfirstForm := congrArg read (hfirst.trans (congrArg first hrecord.symm)) + have hsecondForm := congrArg read (hsecond.trans (congrArg second hrecord.symm)) + have hinside : SourceProjectedTag.projection clauses designated q choices observed.1 = + SourceQuestionUnmarkedRange.projection rows clauses designated q choices raw := + SourceQuestionTaggedProjection.projection_observe rows clauses designated q choices raw + have hprojection : + SourceQuestionPhysicalHigh.projection path outside clauses designated q choices observed.1 = + SourceQuestionCollisionTransport.projection path outside clauses designated q choices raw := + congrArg (CutProjectionAssembly.fillProjection path outside + (SourceChildMarkedLaw.questionSlots clauses q) + (SourceProjectedTag.mixedInside clauses designated q choices observed.1)) hinside + have hspace := congrArg (fun projection : ∀ leaf j, MixedSupport.Projection + (SourceQuestionLowerForms.slots path outside clauses q leaf j) + (SourceQuestionPhysicalHigh.projectedSlots path outside clauses designated + q choices observed.1 leaf j) => + LinearMap.range (HPullback (ChildBlockProjection.nodeProjection projection + (HierarchicalLeftDecoder.LowerNode upper level d)))) hprojection + exact congrArg₂ (fun (pair : _ × _) space => + BilinearCollisionTransfer.restrictedCollision pair.1 pair.2 space) + (congrArg₂ Prod.mk hfirstForm hsecondForm) hspace + +theorem mean_collision_eq + (flag : Fin (branch height) → FiniteDistribution Bool) : + (SourceProjectedTag.positionLaw (branch := branch) (n := height) (t := t)).expectation + (fun choices => (SourceProjectedTag.flagLaw flag).expectation (fun flags => + SourceQuestionPhysicalHigh.collision path outside placeholder clauses designated + q choices flags upper level d hbranch A exterior direction cutoff (tables q))) = + (SourceProjectedTag.positionLaw (branch := branch) (n := height) (t := t)).expectation + (fun choices => (SourceQuestionRawSwap.kernelLaw + (C := SourceQuestionLowerForms.Calls (rows := rows) (repeats := repeats) path) + rows clauses designated flag q choices).probability (fun raw => + SourceQuestionCollisionTransport.globalRestricted path outside placeholder clauses + upper level d hbranch A exterior tables cutoff designated q choices raw direction)) := by + apply FiniteDistribution.expectation_congr + intro choices + rw [flags_collision_eq_kernels path outside placeholder clauses designated upper level d + hbranch A exterior q choices direction cutoff (tables q) flag] + apply congrArg (fun event => (SourceQuestionRawSwap.kernelLaw + (C := SourceQuestionLowerForms.Calls (rows := rows) (repeats := repeats) path) + rows clauses designated flag q choices).probability event) + funext raw + exact rawEvent_observe path outside placeholder clauses designated upper level d hbranch A + exterior q choices direction cutoff tables raw + +end +end PerfectCompleteness.SourceQuestionPhysicalCollision + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/SourceQuestionProjectionWitness.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/SourceQuestionProjectionWitness.lean new file mode 100644 index 0000000000000000000000000000000000000000..f56da01d6336428f61307219e3db8cd7ddc2602a --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/SourceQuestionProjectionWitness.lean @@ -0,0 +1,62 @@ +import OAI.Computability.PerfectCompleteness.Construction.SourceQuestionUnmarkedRange +import OAI.Computability.PerfectCompleteness.Foundations.SourceProjectedTag + +namespace OAI + +section + +namespace PerfectCompleteness.SourceQuestionProjectionWitness + +noncomputable section + +open scoped Classical +open RecursiveSpaces + +variable {branch : Nat → Nat} {n t v m : Nat} + +private theorem projectionCast_apply_heq + {left native right : Slots branch (n + 1) → Fin t → MixedSupport.Slot} + (h : left = native) + (p : ∀ leaf k, MixedSupport.Projection (left leaf k) (right leaf k)) + (leaf : Slots branch (n + 1)) (k : Fin t) : + HEq (CutNativeForms.projectionCast h rfl p leaf k) (p leaf k) := by + cases h + rfl + +private theorem mpr_heq {α β : Sort _} (h : α = β) (x : β) : + HEq (Eq.mpr h x) x := by + cases h + rfl + +variable {C : Type*} [Fintype C] + (rows : Nat → Nat) (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch n) → Slots branch n) + (q : SourceQuestionPositionSplit.Questions (branch := branch) (n := n) (t := t) (m := m)) + (choices : SourceQuestionKernelJoint.ChoiceTuple (branch := branch) (n := n) (t := t)) + (raw : (i : Fin (branch n)) → SourceChildKernel.Raw (C := C) (t := t) rows clauses designated i) + +theorem projection_observe : + SourceProjectedTag.projection clauses designated q choices + (fun i => SourceChildKernel.rawProjected rows clauses designated i (raw i)) = + SourceQuestionUnmarkedRange.projection rows clauses designated q choices raw := by + funext leaf k + have htag : HEq + (SourceProjectedTag.projection clauses designated q choices + (fun i => SourceChildKernel.rawProjected rows clauses designated i (raw i)) leaf k) + (SourceChildKernel.parentProjection rows clauses designated + (SourceQuestionKernelJoint.sources designated q choices) raw leaf k) := by + unfold SourceProjectedTag.projection + dsimp only [id] + exact mpr_heq _ _ + have hnative := projectionCast_apply_heq + (SourceQuestionUnmarkedRange.leftSlots_eq clauses designated q choices) + (SourceChildKernel.parentProjection rows clauses designated + (SourceQuestionKernelJoint.sources designated q choices) raw) leaf k + exact eq_of_heq (htag.trans hnative.symm) + +end +end PerfectCompleteness.SourceQuestionProjectionWitness + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/SourceQuestionTaggedProjection.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/SourceQuestionTaggedProjection.lean new file mode 100644 index 0000000000000000000000000000000000000000..31343622457f9ca29a07a338a857d0ecc1a39001 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/SourceQuestionTaggedProjection.lean @@ -0,0 +1,84 @@ +import OAI.Computability.PerfectCompleteness.Construction.SourcePhysicalTaggedChildren +import OAI.Computability.PerfectCompleteness.Decoding.SourceQuestionProjectionWitness + +namespace OAI + +section + +namespace PerfectCompleteness.SourceQuestionTaggedProjection + +noncomputable section + +open scoped Classical +open RecursiveSpaces TreeSourceSpaces HierarchicalArrays + +variable {branch : Nat → Nat} {n t v m : Nat} {C : Type*} [Fintype C] + +omit [Fintype C] in +private theorem castRaw_apply (rows : Nat → Nat) + {left native : Slots branch (n + 1) → Fin t → MixedSupport.Slot} + (h : left = native) (block : CutChildGrouping.Raw (C := C) left rows) + (i : Fin (branch n)) : + (cast (congrArg (fun slots => CutChildGrouping.Raw (C := C) slots rows) h) block) i = + cast (congrArg (fun slots => ChildCallNumbering.Raw (C := C) rows (childSlots slots i)) h) + (block i) := by + cases h + rfl + +omit [Fintype C] in +private theorem castRaw_pullback (rows : Nat → Nat) + {left native right : Slots branch (n + 1) → Fin t → MixedSupport.Slot} + (h : left = native) + (p : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (block : CutChildGrouping.Raw (C := C) right rows) : + cast (congrArg (fun slots => CutChildGrouping.Raw (C := C) slots rows) h) + (ChildAssemblyProjection.rawPullback rows p block) = + ChildAssemblyProjection.rawPullback rows (CutNativeForms.projectionCast h rfl p) block := by + cases h + rfl + +variable (rows : Nat → Nat) (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch n) → Slots branch n) + (q : SourceQuestionPositionSplit.Questions (branch := branch) (n := n) (t := t) (m := m)) + (choices : SourceQuestionKernelJoint.ChoiceTuple (branch := branch) (n := n) (t := t)) + (raw : (i : Fin (branch n)) → SourceChildKernel.Raw (C := C) (t := t) rows clauses designated i) + +theorem projection_observe : + SourceProjectedTag.projection clauses designated q choices + (fun i => SourceChildKernel.rawProjected rows clauses designated i (raw i)) = + SourceQuestionUnmarkedRange.projection rows clauses designated q choices raw := + SourceQuestionProjectionWitness.projection_observe rows clauses designated q choices raw + +theorem markedBlocks_snd_cast : + (SourceChildMarkedLaw.markedBlocks rows clauses designated q choices raw).2 = + cast (congrArg (fun slots => CutChildGrouping.Raw (C := C) slots rows) + (SourceQuestionUnmarkedRange.leftSlots_eq clauses designated q choices)) + (SourceChildKernel.leftChildren rows clauses designated + (SourceQuestionKernelJoint.sources designated q choices) raw) := by + funext i + rw [castRaw_apply rows + (SourceQuestionUnmarkedRange.leftSlots_eq clauses designated q choices)] + rfl + +theorem markedBlocks_snd : + (SourceChildMarkedLaw.markedBlocks rows clauses designated q choices raw).2 = + ChildAssemblyProjection.rawPullback rows + (SourceProjectedTag.projection clauses designated q choices + (fun i => SourceChildKernel.rawProjected rows clauses designated i (raw i))) + (SourcePhysicalTaggedChildren.observe rows clauses designated + (SourceQuestionKernelJoint.sources designated q choices) raw).2 := by + rw [projection_observe] + rw [markedBlocks_snd_cast] + exact castRaw_pullback rows + (SourceQuestionUnmarkedRange.leftSlots_eq clauses designated q choices) + (SourceChildKernel.parentProjection rows clauses designated + (SourceQuestionKernelJoint.sources designated q choices) raw) + (SourceChildKernel.rightChildren rows clauses designated + (SourceQuestionKernelJoint.sources designated q choices) raw) + +end +end PerfectCompleteness.SourceQuestionTaggedProjection + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/TwoResponseCollisionLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/TwoResponseCollisionLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..73c6bfc3e2d475aa4b9aec917d2e5121876a443f --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/TwoResponseCollisionLemmas.lean @@ -0,0 +1,520 @@ +import Lean.Elab.Tactic.Omega +import Mathlib.Algebra.Order.Archimedean.Real.Basic +import Mathlib.Algebra.Order.BigOperators.Ring.Finset +import Mathlib.SetTheory.Cardinal.Finite +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Positivity +import OAI.Computability.UniqueGames.Foundations.KernelSampling +import OAI.Computability.UniqueGames.Foundations.ValueLemmas + +namespace OAI + + +namespace PerfectCompleteness.TwoResponseCollision + +noncomputable section + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games + +variable {Ω Y : Type*} [Fintype Ω] [Fintype Y] + +def responds (f : Ω → Option Y) (good : Ω → Bool) (y : Y) (x : Ω) : Bool := + good x && decide (f x = some y) + +def goodDefined (f : Ω → Option Y) (good : Ω → Bool) (x : Ω) : Bool := + good x && (f x).isSome + +def collision (f : Ω → Option Y) (p : Ω × Ω) : Bool := + decide (∃ y, f p.1 = some y ∧ f p.2 = some y) + +def goodCollision (f : Ω → Option Y) (good : Ω → Bool) (p : Ω × Ω) : Bool := + good p.1 && good p.2 && collision f p + +def GoodResponse (f : Ω → Option Y) (good : Ω → Bool) (y : Y) : Prop := + ∃ x, good x = true ∧ f x = some y + +def responseMass (μ : FiniteDistribution Ω) (f : Ω → Option Y) + (good : Ω → Bool) (y : Y) : ℝ := + μ.probability (responds f good y) + +theorem goodDefined_weight_eq_sum (μ : FiniteDistribution Ω) (f : Ω → Option Y) + (good : Ω → Bool) (x : Ω) : + (if goodDefined f good x then μ.weight x else 0) = + ∑ y, if responds f good y x then μ.weight x else 0 := by + cases hg : good x <;> cases hf : f x <;> + simp [goodDefined, responds, hg, hf, eq_comm] + +theorem goodDefined_probability_eq_sum (μ : FiniteDistribution Ω) + (f : Ω → Option Y) (good : Ω → Bool) : + μ.probability (goodDefined f good) = ∑ y, responseMass μ f good y := by + change (∑ x, if goodDefined f good x then μ.weight x else 0) = + ∑ y, ∑ x, if responds f good y x then μ.weight x else 0 + simp_rw [goodDefined_weight_eq_sum] + exact Finset.sum_comm + +theorem goodCollision_weight_eq_sum (μ : FiniteDistribution Ω) (f : Ω → Option Y) + (good : Ω → Bool) (x x' : Ω) : + (if goodCollision f good (x, x') then μ.weight x * μ.weight x' else 0) = + ∑ y, (if responds f good y x then μ.weight x else 0) * + (if responds f good y x' then μ.weight x' else 0) := by + cases hg : good x <;> cases hg' : good x' <;> + cases hf : f x <;> cases hf' : f x' <;> + simp [goodCollision, collision, responds, hg, hg', hf, hf', ite_mul, mul_ite, eq_comm] + +theorem goodCollision_probability_eq_sum_sq (μ : FiniteDistribution Ω) + (f : Ω → Option Y) (good : Ω → Bool) : + (μ.product μ).probability (goodCollision f good) = + ∑ y, responseMass μ f good y ^ 2 := by + change (∑ p : Ω × Ω, + if goodCollision f good p then μ.weight p.1 * μ.weight p.2 else 0) = _ + rw [Fintype.sum_prod_type] + calc + _ = ∑ x, ∑ x', ∑ y, + (if responds f good y x then μ.weight x else 0) * + (if responds f good y x' then μ.weight x' else 0) := by + apply Finset.sum_congr rfl + intro x _ + apply Finset.sum_congr rfl + intro x' _ + exact goodCollision_weight_eq_sum μ f good x x' + _ = ∑ x, ∑ y, ∑ x', + (if responds f good y x then μ.weight x else 0) * + (if responds f good y x' then μ.weight x' else 0) := by + apply Finset.sum_congr rfl + intro x _ + exact Finset.sum_comm + _ = ∑ y, ∑ x, ∑ x', + (if responds f good y x then μ.weight x else 0) * + (if responds f good y x' then μ.weight x' else 0) := Finset.sum_comm + _ = ∑ y, responseMass μ f good y ^ 2 := by + apply Finset.sum_congr rfl + intro y _ + change (∑ x, ∑ x', + (if responds f good y x then μ.weight x else 0) * + (if responds f good y x' then μ.weight x' else 0)) = + (∑ x, if responds f good y x then μ.weight x else 0) ^ 2 + rw [← Finset.sum_mul_sum, pow_two] + +omit [Fintype Y] in +theorem responseMass_eq_zero_of_not_goodResponse (μ : FiniteDistribution Ω) + (f : Ω → Option Y) (good : Ω → Bool) (y : Y) + (hy : ¬GoodResponse f good y) : responseMass μ f good y = 0 := by + unfold responseMass FiniteDistribution.probability + apply Finset.sum_eq_zero + intro x _ + by_cases hg : good x = true + · have hf : f x ≠ some y := fun hf => hy ⟨x, hg, hf⟩ + simp [responds, hg, hf] + · simp [responds, hg] + +theorem sum_sq_bound_of_support_card_le_two (q : Y → ℝ) (R : Y → Prop) + (hzero : ∀ y, ¬R y → q y = 0) + (hcard : Nat.card {y : Y // R y} ≤ 2) : + (∑ y, q y) ^ 2 ≤ 2 * ∑ y, q y ^ 2 := by + let S : Finset Y := Finset.univ.filter R + have hsum : (∑ y ∈ S, q y) = ∑ y, q y := by + apply Finset.sum_subset (Finset.filter_subset _ _) + intro y _ hy + exact hzero y (by simpa [S] using hy) + have hsumSq : (∑ y ∈ S, q y ^ 2) = ∑ y, q y ^ 2 := by + apply Finset.sum_subset (Finset.filter_subset _ _) + intro y _ hy + rw [hzero y (by simpa [S] using hy)] + norm_num + have hcardNat : S.card ≤ 2 := by + simpa [Nat.card_eq_fintype_card, Fintype.card_subtype, S] using hcard + have hcardReal : (S.card : ℝ) ≤ 2 := by exact_mod_cast hcardNat + have hcs := Finset.sum_mul_sq_le_sq_mul_sq S (fun _ : Y => (1 : ℝ)) q + simp only [one_mul, one_pow, Finset.sum_const, nsmul_eq_mul, mul_one] at hcs + rw [hsum, hsumSq] at hcs + exact hcs.trans (mul_le_mul_of_nonneg_right hcardReal + (Finset.sum_nonneg (fun y _ => sq_nonneg (q y)))) + +theorem goodCollision_probability_ge (μ : FiniteDistribution Ω) + (f : Ω → Option Y) (good : Ω → Bool) + (hcard : Nat.card {y : Y // GoodResponse f good y} ≤ 2) : + μ.probability (goodDefined f good) ^ 2 / 2 ≤ + (μ.product μ).probability (goodCollision f good) := by + rw [goodDefined_probability_eq_sum, goodCollision_probability_eq_sum_sq] + have h := sum_sq_bound_of_support_card_le_two (responseMass μ f good) + (GoodResponse f good) (responseMass_eq_zero_of_not_goodResponse μ f good) hcard + linarith + +theorem collision_probability_ge (μ : FiniteDistribution Ω) + (f : Ω → Option Y) (good : Ω → Bool) + (hcard : Nat.card {y : Y // GoodResponse f good y} ≤ 2) : + μ.probability (goodDefined f good) ^ 2 / 2 ≤ + (μ.product μ).probability (collision f) := by + apply (goodCollision_probability_ge μ f good hcard).trans + apply FiniteDistribution.probability_mono + intro p hp + exact (Bool.and_eq_true_iff.mp hp).2 + +theorem collision_probability_ge_of_response_set (μ : FiniteDistribution Ω) + (f : Ω → Option Y) (good : Ω → Bool) (R : Y → Prop) + (hcard : Nat.card {y : Y // R y} ≤ 2) + (hR : ∀ x y, good x = true → f x = some y → R y) : + μ.probability (goodDefined f good) ^ 2 / 2 ≤ + (μ.product μ).probability (collision f) := by + let into : {y : Y // GoodResponse f good y} → {y : Y // R y} := fun y => + ⟨y.val, by + obtain ⟨x, hg, hf⟩ := y.property + exact hR x y.val hg hf⟩ + have hi : Function.Injective into := by + intro y y' h + exact Subtype.ext (congrArg (fun z : {y : Y // R y} => z.val) h) + apply collision_probability_ge μ f good + exact (Nat.card_le_card_of_injective into hi).trans hcard + +theorem collision_probability_ge_of_good_defined (μ : FiniteDistribution Ω) + (f : Ω → Option Y) (good : Ω → Bool) + (hdefined : ∀ x, good x = true → ∃ y, f x = some y) + (hcard : Nat.card {y : Y // GoodResponse f good y} ≤ 2) : + μ.probability good ^ 2 / 2 ≤ (μ.product μ).probability (collision f) := by + have hevent : goodDefined f good = good := by + funext x + cases hg : good x with + | false => simp [goodDefined, hg] + | true => + obtain ⟨y, hy⟩ := hdefined x hg + simp [goodDefined, hg, hy] + simpa only [hevent] using collision_probability_ge μ f good hcard + +end +end PerfectCompleteness.TwoResponseCollision + + + +namespace PerfectCompleteness.DecoderTableAdmissibility + +noncomputable section + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games + +section FiniteLaw + +variable {Ω : Type*} [Fintype Ω] + +theorem event_of_probability_one (μ : FiniteDistribution Ω) (event : Ω → Bool) + (hone : μ.probability event = 1) (x : Ω) (hx : μ.weight x ≠ 0) : + event x = true := by + by_contra hfalse + have hle (y : Ω) : (if event y then μ.weight y else 0) ≤ μ.weight y := by + split + · exact le_rfl + · exact μ.nonnegative y + have hlt : μ.probability event < ∑ y, μ.weight y := by + unfold FiniteDistribution.probability + apply Finset.sum_lt_sum (fun y _ => hle y) + refine ⟨x, Finset.mem_univ _, ?_⟩ + simpa only [ite_eq_right hfalse] using + lt_of_le_of_ne (μ.nonnegative x) (Ne.symm hx) + have hbad : (1 : ℝ) < 1 := by simpa only [hone, μ.normalized] using hlt + exact (lt_irrefl (1 : ℝ)) hbad + +theorem probability_one_of_support (μ : FiniteDistribution Ω) (event : Ω → Bool) + (hevent : ∀ x, μ.weight x ≠ 0 → event x = true) : μ.probability event = 1 := by + rw [← μ.normalized] + apply Finset.sum_congr rfl + intro x _ + by_cases hx : μ.weight x = 0 + · simp [hx] + · simp only [hevent x hx, ite_true] + +theorem expectation_le_of_support (μ : FiniteDistribution Ω) (score : Ω → ℝ) + (bound : ℝ) (hbound : ∀ x, μ.weight x ≠ 0 → score x ≤ bound) : + μ.expectation score ≤ bound := by + calc + _ ≤ ∑ x, μ.weight x * bound := by + apply Finset.sum_le_sum + intro x _ + by_cases hx : μ.weight x = 0 + · simp only [hx, zero_mul, le_refl] + · exact mul_le_mul_of_nonneg_left (hbound x hx) (μ.nonnegative x) + _ = bound := by rw [← Finset.sum_mul, μ.normalized, one_mul] + +end FiniteLaw + +variable {Q A : Type*} [Fintype Q] [Fintype A] [DecidableEq Q] + +def RowValid (valid : Q → A → Prop) (q : Q) (answer : Option A) : Prop := + ∀ a, answer = some a → valid q a + +def Admissible (valid : Q → A → Prop) (answers : Q → Option A) : Prop := + ∀ q a, answers q = some a → valid q a + +theorem table_admissible_of_support (responses : Q → FiniteDistribution (Option A)) + (valid : Q → A → Prop) + (hvalid : ∀ q a, (responses q).weight (some a) ≠ 0 → valid q a) + (answers : Q → Option A) (hanswers : (FiniteDistribution.table responses).weight answers ≠ 0) : + Admissible valid answers := by + intro q a ha + apply hvalid q a + have hrow := FiniteDistribution.table_row_weight_ne_zero responses answers hanswers q + simpa only [ha] using hrow + +omit [Fintype Q] [DecidableEq Q] in +theorem row_valid_of_probability_one (responses : Q → FiniteDistribution (Option A)) + (valid : Q → A → Prop) + (hvalid : ∀ q, (responses q).probability (fun answer => decide (RowValid valid q answer)) = 1) + (q : Q) (a : A) (ha : (responses q).weight (some a) ≠ 0) : valid q a := by + have h := event_of_probability_one (responses q) + (fun answer => decide (RowValid valid q answer)) (hvalid q) (some a) ha + exact (of_decide_eq_true h) a rfl + +theorem table_admissible_of_probability_one (responses : Q → FiniteDistribution (Option A)) + (valid : Q → A → Prop) + (hvalid : ∀ q, (responses q).probability (fun answer => decide (RowValid valid q answer)) = 1) + (answers : Q → Option A) (hanswers : (FiniteDistribution.table responses).weight answers ≠ 0) : + Admissible valid answers := + table_admissible_of_support responses valid + (row_valid_of_probability_one responses valid hvalid) answers hanswers + +theorem table_admissible_probability_one (responses : Q → FiniteDistribution (Option A)) + (valid : Q → A → Prop) + (hvalid : ∀ q, (responses q).probability (fun answer => decide (RowValid valid q answer)) = 1) : + (FiniteDistribution.table responses).probability + (fun answers => decide (Admissible valid answers)) = 1 := by + apply probability_one_of_support + intro answers hanswers + exact decide_eq_true + (table_admissible_of_probability_one responses valid hvalid answers hanswers) + +theorem table_erased_of_support (responses : Q → FiniteDistribution (Option A)) + (erased : Q → Prop) + (herased : ∀ q, erased q → ∀ a, (responses q).weight (some a) = 0) + (answers : Q → Option A) (hanswers : (FiniteDistribution.table responses).weight answers ≠ 0) + (q : Q) (hq : erased q) : answers q = none := by + cases ha : answers q with + | none => rfl + | some a => + have hrow := FiniteDistribution.table_row_weight_ne_zero responses answers hanswers q + rw [ha, herased q hq a] at hrow + exact False.elim (hrow rfl) + +theorem table_erased_of_probability_one (responses : Q → FiniteDistribution (Option A)) + (erased : Q → Prop) + (herased : ∀ q, erased q → + (responses q).probability (fun answer => decide (answer = none)) = 1) + (answers : Q → Option A) (hanswers : (FiniteDistribution.table responses).weight answers ≠ 0) + (q : Q) (hq : erased q) : answers q = none := by + exact of_decide_eq_true (event_of_probability_one (responses q) + (fun answer => decide (answer = none)) (herased q hq) (answers q) + (FiniteDistribution.table_row_weight_ne_zero responses answers hanswers q)) + +def eraseTable (erased : Q → Prop) (answers : Q → Option A) (q : Q) : Option A := + if erased q then none else answers q + +omit [Fintype Q] [Fintype A] [DecidableEq Q] in +theorem eraseTable_admissible (valid : Q → A → Prop) (erased : Q → Prop) + (answers : Q → Option A) (hanswers : Admissible valid answers) : + Admissible valid (eraseTable erased answers) := by + intro q a ha + by_cases hq : erased q + · simp only [eraseTable, ite_eq_left hq, reduceCtorEq] at ha + · exact hanswers q a (by simpa only [eraseTable, ite_eq_right hq] using ha) + +theorem eraseTable_eq_of_support (responses : Q → FiniteDistribution (Option A)) + (erased : Q → Prop) + (herased : ∀ q, erased q → ∀ a, (responses q).weight (some a) = 0) + (answers : Q → Option A) (hanswers : (FiniteDistribution.table responses).weight answers ≠ 0) : + eraseTable erased answers = answers := by + funext q + by_cases hq : erased q + · simpa only [eraseTable, ite_eq_left hq] using + (table_erased_of_support responses erased herased answers hanswers q hq).symm + · simp only [eraseTable, ite_eq_right hq] + +theorem eraseTable_pushforward_eq (responses : Q → FiniteDistribution (Option A)) + (erased : Q → Prop) + (herased : ∀ q, erased q → ∀ a, (responses q).weight (some a) = 0) : + (FiniteDistribution.table responses).pushforward (eraseTable erased) = + FiniteDistribution.table responses := by + calc + _ = (FiniteDistribution.table responses).pushforward id := by + apply FiniteDistribution.pushforward_eq_of_agree_on_support + intro answers hanswers + exact eraseTable_eq_of_support responses erased herased answers hanswers + _ = _ := by + apply FiniteDistribution.eq_of_weight_eq + intro answers + simp only [FiniteDistribution.pushforward, id_eq] + rw [Finset.sum_eq_single answers] + · simp + · intro x _ hx + exact ite_eq_right hx + · intro hx + exact False.elim (hx (Finset.mem_univ answers)) + +theorem expectation_le_of_admissible (responses : Q → FiniteDistribution (Option A)) + (valid : Q → A → Prop) + (hvalid : ∀ q a, (responses q).weight (some a) ≠ 0 → valid q a) + (score : (Q → Option A) → ℝ) (bound : ℝ) + (hbound : ∀ answers, Admissible valid answers → score answers ≤ bound) : + (FiniteDistribution.table responses).expectation score ≤ bound := by + apply expectation_le_of_support + intro answers hanswers + exact hbound answers (table_admissible_of_support responses valid hvalid answers hanswers) + +theorem expectation_le_of_probability_one (responses : Q → FiniteDistribution (Option A)) + (valid : Q → A → Prop) + (hvalid : ∀ q, (responses q).probability (fun answer => decide (RowValid valid q answer)) = 1) + (score : (Q → Option A) → ℝ) (bound : ℝ) + (hbound : ∀ answers, Admissible valid answers → score answers ≤ bound) : + (FiniteDistribution.table responses).expectation score ≤ bound := + expectation_le_of_admissible responses valid + (row_valid_of_probability_one responses valid hvalid) score bound hbound + +theorem collision_expectation_le (responses : Q → FiniteDistribution (Option A)) + (valid : Q → A → Prop) + (hvalid : ∀ q, (responses q).probability (fun answer => decide (RowValid valid q answer)) = 1) + (questions : FiniteDistribution (Q × Q)) (bound : ℝ) + (hbound : ∀ answers, Admissible valid answers → + questions.probability (TwoResponseCollision.collision answers) ≤ bound) : + (FiniteDistribution.table responses).expectation + (fun answers => questions.probability (TwoResponseCollision.collision answers)) ≤ bound := + expectation_le_of_probability_one responses valid hvalid _ bound hbound + +end +end PerfectCompleteness.DecoderTableAdmissibility + + + +namespace PerfectCompleteness.UpperParameterScalars + +noncomputable section + +def h (r ℓ : Nat) : ℝ := 1 / (2 : ℝ) ^ (r * ℓ) + +def g (η : ℝ) (r ℓ : Nat) : ℝ := (η ^ 2 / 4) * h r ℓ + +def q (η : ℝ) (r ℓ : Nat) : ℝ := g η r ℓ * h r ℓ + +def rhoPred (κ α : ℝ) : ℝ := κ * α / 4 + +def b (κ α η : ℝ) (r ℓ : Nat) : ℝ := rhoPred κ α * q η r ℓ + +def tau (κ α : ℝ) (r ℓ : Nat) : ℝ := rhoPred κ α * h r ℓ / 4 + +def gamma (κ α η : ℝ) (r ℓ : Nat) : ℝ := + b κ α η r ℓ * (1 / (2 : ℝ) ^ (ℓ + r)) * tau κ α r ℓ ^ 2 / 2 + +theorem h_pos (r ℓ : Nat) : 0 < h r ℓ := by unfold h; positivity + +theorem g_pos {η : ℝ} (hη : 0 < η) (r ℓ : Nat) : 0 < g η r ℓ := by + unfold g + exact mul_pos (by positivity) (h_pos r ℓ) + +theorem q_pos {η : ℝ} (hη : 0 < η) (r ℓ : Nat) : 0 < q η r ℓ := + mul_pos (g_pos hη r ℓ) (h_pos r ℓ) + +theorem rhoPred_pos {κ α : ℝ} (hκ : 0 < κ) (hα : 0 < α) : 0 < rhoPred κ α := by + unfold rhoPred + positivity + +theorem b_pos {κ α η : ℝ} (hκ : 0 < κ) (hα : 0 < α) (hη : 0 < η) + (r ℓ : Nat) : 0 < b κ α η r ℓ := + mul_pos (rhoPred_pos hκ hα) (q_pos hη r ℓ) + +theorem tau_pos {κ α : ℝ} (hκ : 0 < κ) (hα : 0 < α) + (r ℓ : Nat) : 0 < tau κ α r ℓ := by + unfold tau + exact div_pos (mul_pos (rhoPred_pos hκ hα) (h_pos r ℓ)) (by norm_num) + +theorem gamma_pos {κ α η : ℝ} (hκ : 0 < κ) (hα : 0 < α) (hη : 0 < η) + (r ℓ : Nat) : 0 < gamma κ α η r ℓ := by + unfold gamma + have hb := b_pos hκ hα hη r ℓ + have ht := tau_pos hκ hα r ℓ + positivity + +theorem all_pos {κ α η : ℝ} (hκ : 0 < κ) (hα : 0 < α) (hη : 0 < η) + (r ℓ : Nat) : + 0 < h r ℓ ∧ 0 < g η r ℓ ∧ 0 < q η r ℓ ∧ 0 < rhoPred κ α ∧ + 0 < b κ α η r ℓ ∧ 0 < tau κ α r ℓ ∧ 0 < gamma κ α η r ℓ := + ⟨h_pos r ℓ, g_pos hη r ℓ, q_pos hη r ℓ, rhoPred_pos hκ hα, + b_pos hκ hα hη r ℓ, tau_pos hκ hα r ℓ, gamma_pos hκ hα hη r ℓ⟩ + +theorem reciprocal_pow_eq_zpow (k : Nat) : + 1 / (2 : ℝ) ^ k = (2 : ℝ) ^ (-(k : ℤ)) := by + simp only [one_div, zpow_neg, zpow_natCast] + +theorem gamma_eq_neg_zpow (κ α η : ℝ) (r ℓ : Nat) : + gamma κ α η r ℓ = + b κ α η r ℓ * (2 : ℝ) ^ (-(ℓ : ℤ) - (r : ℤ)) * tau κ α r ℓ ^ 2 / 2 := by + have hexp : -((ℓ + r : Nat) : ℤ) = -(ℓ : ℤ) - (r : ℤ) := by + simp only [Nat.cast_add] + omega + rw [gamma, reciprocal_pow_eq_zpow, hexp] + +theorem reciprocal_power_sub_antitone (r : Nat) {ℓ ℓ' : Nat} (hℓ : ℓ ≤ ℓ') : + 1 / (2 : ℝ) ^ (ℓ' - r) ≤ 1 / (2 : ℝ) ^ (ℓ - r) := by + have hp := pow_le_pow_of_le_one (by norm_num : (0 : ℝ) ≤ 1 / 2) + (by norm_num : (1 / 2 : ℝ) ≤ 1) (Nat.sub_le_sub_right hℓ r) + simpa only [div_pow, one_pow] using hp + +theorem exists_rows_upward (minimum r : Nat) {ρ : ℝ} (hρ : 0 < ρ) : + ∃ ℓ : Nat, minimum ≤ ℓ ∧ r ≤ ℓ ∧ 1 ≤ ℓ ∧ + ∀ ℓ' : Nat, ℓ ≤ ℓ' → 1 / (2 : ℝ) ^ (ℓ' - r) < ρ / 8 := by + obtain ⟨k, hk⟩ := exists_pow_lt_of_lt_one + (show 0 < ρ / 8 by positivity) (by norm_num : (1 / 2 : ℝ) < 1) + let ℓ := r + k + minimum + 1 + refine ⟨ℓ, by dsimp [ℓ]; omega, by dsimp [ℓ]; omega, + by dsimp [ℓ]; omega, ?_⟩ + intro ℓ' hℓ' + have hkℓ : k ≤ ℓ' - r := by dsimp [ℓ] at hℓ'; omega + have hp := pow_le_pow_of_le_one (by norm_num : (0 : ℝ) ≤ 1 / 2) + (by norm_num : (1 / 2 : ℝ) ≤ 1) hkℓ + simpa only [div_pow, one_pow] using hp.trans_lt hk + +theorem exists_rows (minimum r : Nat) {ρ : ℝ} (hρ : 0 < ρ) : + ∃ ℓ : Nat, minimum ≤ ℓ ∧ r ≤ ℓ ∧ 1 ≤ ℓ ∧ + 1 / (2 : ℝ) ^ (ℓ - r) < ρ / 8 := by + obtain ⟨ℓ, hmin, hr, hpos, hbound⟩ := exists_rows_upward minimum r hρ + exact ⟨ℓ, hmin, hr, hpos, hbound ℓ le_rfl⟩ + +theorem exists_rows_rhoPred (minimum r : Nat) {κ α : ℝ} + (hκ : 0 < κ) (hα : 0 < α) : + ∃ ℓ : Nat, minimum ≤ ℓ ∧ r ≤ ℓ ∧ 1 ≤ ℓ ∧ + 1 / (2 : ℝ) ^ (ℓ - r) < rhoPred κ α / 8 := + exists_rows minimum r (rhoPred_pos hκ hα) + +theorem exists_repeats_upward {h₀ τ : ℝ} (hh : 0 < h₀) (hτ : 0 < τ) : + ∃ R : Nat, 6 ≤ R ∧ ∀ R' : Nat, R ≤ R' → + (7 / 8 : ℝ) ^ R' ≤ min (h₀ / 2) (τ ^ 2 / 2) := by + have htarget : 0 < min (h₀ / 2) (τ ^ 2 / 2) := by positivity + obtain ⟨k, hk⟩ := exists_pow_lt_of_lt_one htarget + (by norm_num : (7 / 8 : ℝ) < 1) + refine ⟨k + 6, by omega, ?_⟩ + intro R hR + have hp := pow_le_pow_of_le_one (by norm_num : (0 : ℝ) ≤ 7 / 8) + (by norm_num : (7 / 8 : ℝ) ≤ 1) (show k ≤ R by omega) + exact hp.trans hk.le + +theorem exists_repeats {h₀ τ : ℝ} (hh : 0 < h₀) (hτ : 0 < τ) : + ∃ R : Nat, 6 ≤ R ∧ (7 / 8 : ℝ) ^ R ≤ min (h₀ / 2) (τ ^ 2 / 2) := by + obtain ⟨R, hR, hbound⟩ := exists_repeats_upward hh hτ + exact ⟨R, hR, hbound R le_rfl⟩ + +theorem exists_upper_repeats {κ α : ℝ} (hκ : 0 < κ) (hα : 0 < α) + (r ℓ : Nat) : + ∃ R : Nat, 6 ≤ R ∧ (7 / 8 : ℝ) ^ R ≤ + min (h r ℓ / 2) (tau κ α r ℓ ^ 2 / 2) := + exists_repeats (h_pos r ℓ) (tau_pos hκ hα r ℓ) + +theorem exists_upper_choices (minimum r : Nat) {κ α : ℝ} + (hκ : 0 < κ) (hα : 0 < α) : + ∃ ℓ R : Nat, minimum ≤ ℓ ∧ r ≤ ℓ ∧ 1 ≤ ℓ ∧ + 1 / (2 : ℝ) ^ (ℓ - r) < rhoPred κ α / 8 ∧ 6 ≤ R ∧ + (7 / 8 : ℝ) ^ R ≤ min (h r ℓ / 2) (tau κ α r ℓ ^ 2 / 2) := by + obtain ⟨ℓ, hmin, hr, hpos, hrow⟩ := exists_rows_rhoPred minimum r hκ hα + obtain ⟨R, hR, hrep⟩ := exists_upper_repeats hκ hα r ℓ + exact ⟨ℓ, R, hmin, hr, hpos, hrow, hR, hrep⟩ + +end +end PerfectCompleteness.UpperParameterScalars + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/UpperCutOldRecord.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/UpperCutOldRecord.lean new file mode 100644 index 0000000000000000000000000000000000000000..c88132a6e6422bcb401b0d7775348f35780f2b86 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/UpperCutOldRecord.lean @@ -0,0 +1,254 @@ +import OAI.Computability.PerfectCompleteness.Decoding.UpperCutTriangle +import OAI.Computability.PerfectCompleteness.Foundations.ProjectedCallRestriction + +namespace OAI + +section + +namespace PerfectCompleteness.UpperCutOldRecord + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCutTape WholeArrayInteriorExterior +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) +open scoped Classical + +noncomputable section + +attribute [local instance] linearMapFintype + +private theorem product_swap {A B : Type*} [Fintype A] [Fintype B] + (μ : FiniteDistribution A) (ν : FiniteDistribution B) : + (μ.product ν).pushforward (Equiv.prodComm A B) = ν.product μ := by + rw [← FiniteDistribution.transport_eq_pushforward] + apply FiniteDistribution.eq_of_weight_eq + intro z + exact mul_comm _ _ + +private theorem product_fst {A B : Type*} [Fintype A] [Fintype B] + (μ : FiniteDistribution A) (ν : FiniteDistribution B) : + (μ.product ν).pushforward Prod.fst = μ := by + calc + _ = ((μ.product ν).pushforward (Equiv.prodComm A B)).pushforward Prod.snd := + (FiniteDistribution.pushforward_comp _ _ _).symm + _ = _ := by rw [product_swap, FiniteDistribution.product_pushforward_snd] + +variable {branch : Nat → Nat} {n j i t : Nat} + +local instance backgroundFintype (rows : Nat → Nat) (p : Path branch n (j + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Fintype (HierarchicalAgreementMean.Background (rows := rows) slots (upperNode p)) := + Fintype.ofFinite _ + +local instance rowSpaceFintype (p : Path branch n (j + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Fintype (NodeEmbedding.RowSpace slots (upperNode p)) := Fintype.ofFinite _ + +abbrev OldRecord (rows : Nat → Nat) (p : Path branch n (j + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) := + HierarchicalAgreementMean.Background (rows := rows) slots (upperNode p) × + HierarchicalAgreementMean.Matrix (rows := rows) slots (upperNode p) + +def oldView (rows : Nat → Nat) (p : Path branch n (j + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : HierarchicalAgreementMean.PairRecord (rows := rows) slots (upperNode p)) : + OldRecord rows p slots := (record.1, record.2.1) + +def arrayView (rows : Nat → Nat) (p : Path branch n (j + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) (arrays : Arrays slots rows) : + OldRecord rows p slots := + (HierarchicalMatrixTable.backgroundOf slots (upperNode p) arrays, + NodeEmbedding.matrix arrays (upperNode p)) + +def oldCall (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) : + Fin (OriginalCutCalls.count rows repeats n (i + 1)) → + Fin (UpperScalarCutCalls.count rows repeats n (j + 1) (i + 1)) := + fun call => UpperScalarCutCalls.numbering rows repeats p r + (.inl ((OriginalWholeCut.callNumbering rows repeats (p.append r)).symm call)) + +theorem oldCall_injective (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) : + Function.Injective (oldCall rows repeats p r) := by + intro a b h + apply (OriginalWholeCut.callNumbering rows repeats (p.append r)).symm.injective + exact Sum.inl.inj ((UpperScalarCutCalls.numbering rows repeats p r).injective h) + +def restrictedRecord (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : UpperScalarCutReconstruction.NumberedRecord rows repeats p r slots) : + OriginalWholeCutBridge.NumberedRecord rows repeats (p.append r) slots := + (record.1.1, ProjectedCallRestriction.assembledRestrict rows + (cutSlots (p.append r) slots) (oldCall rows repeats p r) record.2) + +theorem number_oldRecord (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : UpperScalarCutReconstruction.NumberedRecord rows repeats p r slots) : + OriginalWholeCutBridge.numberRecord rows repeats (p.append r) slots + (UpperScalarCutReconstruction.oldRecord rows repeats p r slots + ((UpperScalarCutReconstruction.numberRecordEquiv rows repeats p r slots).symm record)) = + restrictedRecord rows repeats p r slots record := by + rfl + +theorem oldView_numberedPairRecord (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (sample : BucketSampler.Direction (rows (j + 1)) × + UpperScalarCutReconstruction.NumberedRecord rows repeats p r slots) : + oldView rows p slots (UpperScalarCutBucket.numberedPairRecord rows repeats p r slots sample) = + arrayView rows p slots (OriginalWholeCutBridge.reconstruct rows repeats (p.append r) slots + (restrictedRecord rows repeats p r slots sample.2)) := by + change arrayView rows p slots + (OriginalWholeCut.reconstructRecord rows repeats (p.append r) slots + (UpperScalarCutReconstruction.oldRecord rows repeats p r slots + ((UpperScalarCutReconstruction.numberRecordEquiv rows repeats p r slots).symm sample.2))) = _ + apply congrArg (arrayView rows p slots) + exact (OriginalWholeCutBridge.reconstruct_numberRecord rows repeats (p.append r) slots _).symm.trans + (congrArg (OriginalWholeCutBridge.reconstruct rows repeats (p.append r) slots) + (number_oldRecord rows repeats p r slots sample.2)) + +variable {Z : Fin (branch i) → Type*} [∀ child, Fintype (Z child)] + +def arrayLaw (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (projected : (child : Fin (branch i)) → Z child → Slots branch i → Fin t → MixedSupport.Slot) + (projection : ∀ child z s a, MixedSupport.Projection + (childSlots (cutSlots (p.append r) slots) child s a) (projected child z s a)) + (choiceLaw : (child : Fin (branch i)) → FiniteDistribution (Z child)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) : FiniteDistribution (Arrays slots rows) := + ((OriginalWholeCutTape.exteriorLaw rows repeats (p.append r) slots).product + (ProjectedPrefixComparison.assembledLaw (OriginalCutCalls.count rows repeats n (i + 1)) + rows (cutSlots (p.append r) slots) projected projection choiceLaw β hβ hβ')).pushforward + (OriginalWholeCutBridge.reconstruct rows repeats (p.append r) slots) + +theorem restrictedRecord_law (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (projected : (child : Fin (branch i)) → Z child → Slots branch i → Fin t → MixedSupport.Slot) + (projection : ∀ child z s a, MixedSupport.Projection + (childSlots (cutSlots (p.append r) slots) child s a) (projected child z s a)) + (choiceLaw : (child : Fin (branch i)) → FiniteDistribution (Z child)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) : + ((UpperScalarCutLaw.exteriorLaw rows repeats p r slots).product + (ProjectedPrefixComparison.assembledLaw (UpperScalarCutCalls.count rows repeats n (j + 1) (i + 1)) + rows (cutSlots (p.append r) slots) projected projection choiceLaw β hβ hβ')).pushforward + (restrictedRecord rows repeats p r slots) = + (OriginalWholeCutTape.exteriorLaw rows repeats (p.append r) slots).product + (ProjectedPrefixComparison.assembledLaw (OriginalCutCalls.count rows repeats n (i + 1)) + rows (cutSlots (p.append r) slots) projected projection choiceLaw β hβ hβ') := by + have h := FiniteDistribution.product_pushforward + (UpperScalarCutLaw.exteriorLaw rows repeats p r slots) + (ProjectedPrefixComparison.assembledLaw (UpperScalarCutCalls.count rows repeats n (j + 1) (i + 1)) + rows (cutSlots (p.append r) slots) projected projection choiceLaw β hβ hβ') + Prod.fst (ProjectedCallRestriction.assembledRestrict rows (cutSlots (p.append r) slots) + (oldCall rows repeats p r)) + rw [UpperScalarCutLaw.exteriorLaw, product_fst, + ProjectedCallRestriction.assembled_restrict_law rows (cutSlots (p.append r) slots) + projected projection choiceLaw β hβ hβ' (oldCall rows repeats p r) + (oldCall_injective rows repeats p r)] at h + exact h + +theorem pairLaw_oldView (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (projected : (child : Fin (branch i)) → Z child → Slots branch i → Fin t → MixedSupport.Slot) + (projection : ∀ child z s a, MixedSupport.Projection + (childSlots (cutSlots (p.append r) slots) child s a) (projected child z s a)) + (choiceLaw : (child : Fin (branch i)) → FiniteDistribution (Z child)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) + (directions : FiniteDistribution (BucketSampler.Direction (rows (j + 1)))) : + (UpperScalarPairComparison.pairLaw rows repeats p r slots directions + (ProjectedPrefixComparison.assembledLaw (UpperScalarCutCalls.count rows repeats n (j + 1) (i + 1)) + rows (cutSlots (p.append r) slots) projected projection choiceLaw β hβ hβ')).pushforward + (oldView rows p slots) = + (arrayLaw rows repeats p r slots projected projection choiceLaw β hβ hβ').pushforward + (arrayView rows p slots) := by + let P := (UpperScalarCutLaw.exteriorLaw rows repeats p r slots).product + (ProjectedPrefixComparison.assembledLaw (UpperScalarCutCalls.count rows repeats n (j + 1) (i + 1)) + rows (cutSlots (p.append r) slots) projected projection choiceLaw β hβ hβ') + calc + _ = (directions.product P).pushforward (fun sample => + arrayView rows p slots (OriginalWholeCutBridge.reconstruct rows repeats (p.append r) slots + (restrictedRecord rows repeats p r slots sample.2))) := by + rw [UpperScalarPairComparison.pairLaw, FiniteDistribution.pushforward_comp] + exact congrArg (FiniteDistribution.pushforward (directions.product P)) + (funext (oldView_numberedPairRecord rows repeats p r slots)) + _ = ((directions.product P).pushforward Prod.snd).pushforward (fun record => + arrayView rows p slots (OriginalWholeCutBridge.reconstruct rows repeats (p.append r) slots + (restrictedRecord rows repeats p r slots record))) := + (FiniteDistribution.pushforward_comp (directions.product P) + (Prod.snd : BucketSampler.Direction (rows (j + 1)) × + UpperScalarCutReconstruction.NumberedRecord rows repeats p r slots → + UpperScalarCutReconstruction.NumberedRecord rows repeats p r slots) + (fun record : UpperScalarCutReconstruction.NumberedRecord rows repeats p r slots => + arrayView rows p slots (OriginalWholeCutBridge.reconstruct rows repeats (p.append r) slots + (restrictedRecord rows repeats p r slots record)))).symm + _ = P.pushforward (fun record => arrayView rows p slots + (OriginalWholeCutBridge.reconstruct rows repeats (p.append r) slots + (restrictedRecord rows repeats p r slots record))) := by + rw [FiniteDistribution.product_pushforward_snd] + _ = (P.pushforward (restrictedRecord rows repeats p r slots)).pushforward (fun record => + arrayView rows p slots (OriginalWholeCutBridge.reconstruct rows repeats (p.append r) slots record)) := + (FiniteDistribution.pushforward_comp P (restrictedRecord rows repeats p r slots) + (fun record : OriginalWholeCutBridge.NumberedRecord rows repeats (p.append r) slots => + arrayView rows p slots + (OriginalWholeCutBridge.reconstruct rows repeats (p.append r) slots record))).symm + _ = _ := by + dsimp only [P] + rw [restrictedRecord_law rows repeats p r slots projected projection choiceLaw β hβ hβ'] + exact (FiniteDistribution.pushforward_comp + ((OriginalWholeCutTape.exteriorLaw rows repeats (p.append r) slots).product + (ProjectedPrefixComparison.assembledLaw (OriginalCutCalls.count rows repeats n (i + 1)) + rows (cutSlots (p.append r) slots) projected projection choiceLaw β hβ hβ')) + (OriginalWholeCutBridge.reconstruct rows repeats (p.append r) slots) + (arrayView rows p slots)).symm + +variable {Y : UpperCutTriangle.Prefix branch j i → Fin (branch i) → Type*} + [∀ lowerPref child, Fintype (Y lowerPref child)] + +def modifiedArrayLaw (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (hcut : i + 1 ≤ j + 1) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (hbranch : ∀ k < j + 1, 0 < branch k) + (projected : (lowerPref : UpperCutTriangle.Prefix branch j i) → + (child : Fin (branch i)) → Y lowerPref child → Slots branch i → Fin t → MixedSupport.Slot) + (projection : ∀ lowerPref child z s a, MixedSupport.Projection + (childSlots (cutSlots (p.append (GeometricCutSplit.prefixPath hcut lowerPref)) slots) child s a) + (projected lowerPref child z s a)) + (choiceLaw : (lowerPref : UpperCutTriangle.Prefix branch j i) → + (child : Fin (branch i)) → FiniteDistribution (Y lowerPref child)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) : FiniteDistribution (Arrays slots rows) := + (GeometricCutSplit.prefixLaw hcut hbranch).mixture (fun lowerPref => + arrayLaw rows repeats p (GeometricCutSplit.prefixPath hcut lowerPref) slots + (projected lowerPref) (projection lowerPref) (choiceLaw lowerPref) β hβ hβ') + +theorem modifiedPair_oldView (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (hcut : i + 1 ≤ j + 1) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (hbranch : ∀ k < j + 1, 0 < branch k) (hrows : 0 < rows (j + 1)) + (projected : (lowerPref : UpperCutTriangle.Prefix branch j i) → + (child : Fin (branch i)) → Y lowerPref child → Slots branch i → Fin t → MixedSupport.Slot) + (projection : ∀ lowerPref child z s a, MixedSupport.Projection + (childSlots (cutSlots (p.append (GeometricCutSplit.prefixPath hcut lowerPref)) slots) child s a) + (projected lowerPref child z s a)) + (choiceLaw : (lowerPref : UpperCutTriangle.Prefix branch j i) → + (child : Fin (branch i)) → FiniteDistribution (Y lowerPref child)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) : + (UpperCutTriangle.modifiedPairLaw rows repeats p hcut slots hbranch hrows + projected projection choiceLaw β hβ hβ').pushforward (oldView rows p slots) = + (modifiedArrayLaw rows repeats p hcut slots hbranch projected projection choiceLaw β hβ hβ').pushforward (arrayView rows p slots) := by + simp only [UpperCutTriangle.modifiedPairLaw, modifiedArrayLaw, + FiniteDistribution.pushforward_mixture] + apply congrArg ((GeometricCutSplit.prefixLaw hcut hbranch).mixture) + funext lowerPref + exact pairLaw_oldView rows repeats p (GeometricCutSplit.prefixPath hcut lowerPref) slots + (projected lowerPref) (projection lowerPref) (choiceLaw lowerPref) β hβ hβ' + (OriginalCutPairLaw.directionsLaw rows j hrows) + +end +end PerfectCompleteness.UpperCutOldRecord + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/UpperCutTriangle.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/UpperCutTriangle.lean new file mode 100644 index 0000000000000000000000000000000000000000..9c25550c2ac74578cc6d2f028228fa1130fd5d5b --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/UpperCutTriangle.lean @@ -0,0 +1,138 @@ +import OAI.Computability.PerfectCompleteness.Decoding.UpperScalarPairAveraging +import OAI.Computability.PerfectCompleteness.Foundations.DependentPredictionDifferenceLemmas +import OAI.Computability.PerfectCompleteness.Sampling.CommonProductVariationLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.UpperCutTriangle + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCutTape WholeArrayInteriorExterior +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) +open scoped Classical + +noncomputable section + +attribute [local instance] linearMapFintype + +private theorem sigma_snd {S A : Type*} [Fintype S] [Fintype A] + (μ : FiniteDistribution S) (P : S → FiniteDistribution A) : + (CompletionSoundness.sigmaLaw μ P).pushforward (fun x => x.2) = μ.mixture P := by + apply SigmaObservation.eq_of_probability_eq + intro event + rw [FiniteDistribution.probability_pushforward, CompletionSoundness.sigmaLaw_probability, + FiniteDistribution.probability_mixture] + rfl + +private theorem mixture_variation_le {S A : Type*} [Fintype S] [Fintype A] + (μ : FiniteDistribution S) (P Q : S → FiniteDistribution A) (error : ℝ) + (h : ∀ s, (P s).totalVariation (Q s) ≤ error) : + (μ.mixture P).totalVariation (μ.mixture Q) ≤ error := by + have hmix := ConditionalVariation.observed_sigma_le_const μ P Q error h + (fun x : Σ _ : S, A => x.2) + simpa only [sigma_snd] using hmix + +private theorem variation_triangle {A : Type*} [Fintype A] + (P U Q : FiniteDistribution A) : + P.totalVariation Q ≤ P.totalVariation U + U.totalVariation Q := by + unfold FiniteDistribution.totalVariation + have h := Finset.sum_le_sum (s := Finset.univ) + (fun x _ => abs_sub_le (P.weight x) (U.weight x) (Q.weight x)) + rw [Finset.sum_add_distrib] at h + linarith + +variable {branch : Nat → Nat} {n j i t : Nat} + +local instance backgroundFintype (rows : Nat → Nat) (p : Path branch n (j + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Fintype (HierarchicalAgreementMean.Background (rows := rows) slots (upperNode p)) := Fintype.ofFinite _ + +local instance rowSpaceFintype (p : Path branch n (j + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Fintype (NodeEmbedding.RowSpace slots (upperNode p)) := Fintype.ofFinite _ + +abbrev Prefix (branch : Nat → Nat) (j i : Nat) := GeometricCutSplit.Prefix branch (j + 1) (i + 1) + +variable {Z : Prefix branch j i → Fin (branch i) → Type*} + [∀ pref c, Fintype (Z pref c)] + +def modifiedPairLaw (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (hcut : i + 1 ≤ j + 1) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (hbranch : ∀ k < j + 1, 0 < branch k) (hrows : 0 < rows (j + 1)) + (projected : (pref : Prefix branch j i) → (c : Fin (branch i)) → Z pref c → + Slots branch i → Fin t → MixedSupport.Slot) + (projection : ∀ pref c z s a, MixedSupport.Projection + (childSlots (cutSlots (p.append (GeometricCutSplit.prefixPath hcut pref)) slots) c s a) + (projected pref c z s a)) + (choiceLaw : (pref : Prefix branch j i) → (c : Fin (branch i)) → FiniteDistribution (Z pref c)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) : + FiniteDistribution (HierarchicalAgreementMean.PairRecord (rows := rows) slots (upperNode p)) := + (GeometricCutSplit.prefixLaw hcut hbranch).mixture (fun pref => + UpperScalarPairComparison.pairLaw rows repeats p (GeometricCutSplit.prefixPath hcut pref) + slots (OriginalCutPairLaw.directionsLaw rows j hrows) + (ProjectedPrefixComparison.assembledLaw + (UpperScalarCutCalls.count rows repeats n (j + 1) (i + 1)) rows + (cutSlots (p.append (GeometricCutSplit.prefixPath hcut pref)) slots) + (projected pref) (projection pref) (choiceLaw pref) β hβ hβ')) + +theorem modified_reference_variation (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (hcut : i + 1 ≤ j + 1) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (hbranch : ∀ k < j + 1, 0 < branch k) (hrows : 0 < rows (j + 1)) + (projected : (pref : Prefix branch j i) → (c : Fin (branch i)) → Z pref c → + Slots branch i → Fin t → MixedSupport.Slot) + (projection : ∀ pref c z s a, MixedSupport.Projection + (childSlots (cutSlots (p.append (GeometricCutSplit.prefixPath hcut pref)) slots) c s a) + (projected pref c z s a)) + (choiceLaw : (pref : Prefix branch j i) → (c : Fin (branch i)) → FiniteDistribution (Z pref c)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) : + (modifiedPairLaw rows repeats p hcut slots hbranch hrows projected projection choiceLaw β hβ hβ').totalVariation + (HierarchicalAgreementMean.referenceLaw slots (upperNode p) + (OriginalOwnBucketSplit.backgroundLaw rows repeats p slots) + (by simpa only [upperNode_height] using hrows)) ≤ + Real.sqrt ((1 + β ^ 2 * ((ChildBlockCardinality.bound branch i t + (UpperScalarCutCalls.count rows repeats n (j + 1) (i + 1)) rows : ℝ) - 1)) ^ branch i - 1) / 2 + + Real.sqrt ((ChildBlockCardinality.bound branch i t + (UpperScalarCutCalls.count rows repeats n (j + 1) (i + 1)) rows : ℝ) ^ 2 / branch i) / 2 + + Real.sqrt ((ChildBlockCardinality.bound branch j t + (OriginalCutCalls.count rows repeats n (j + 1) + 1) rows : ℝ) ^ 2 / branch j) / 2 := by + let directions := OriginalCutPairLaw.directionsLaw rows j hrows + let ν := GeometricPath.law i (fun k hk => + hbranch k (Nat.lt_of_lt_of_le (Nat.lt_trans hk (Nat.lt_succ_self i)) hcut)) + let lowerOriginal := fun pref : Prefix branch j i => + UpperScalarPairComparison.pairLaw rows repeats p (GeometricCutSplit.prefixPath hcut pref) + slots directions + (OriginalPrefixContinuation.assembledLaw + (UpperScalarCutCalls.count rows repeats n (j + 1) (i + 1)) rows repeats + (cutSlots (p.append (GeometricCutSplit.prefixPath hcut pref)) slots) ν GeometricPath.leafPath + (hbranch i (Nat.lt_of_lt_of_le (Nat.lt_succ_self i) hcut))) + have hlower := mixture_variation_le (GeometricCutSplit.prefixLaw hcut hbranch) + (fun pref => UpperScalarPairComparison.pairLaw rows repeats p + (GeometricCutSplit.prefixPath hcut pref) slots directions + (ProjectedPrefixComparison.assembledLaw + (UpperScalarCutCalls.count rows repeats n (j + 1) (i + 1)) rows + (cutSlots (p.append (GeometricCutSplit.prefixPath hcut pref)) slots) + (projected pref) (projection pref) (choiceLaw pref) β hβ hβ')) + lowerOriginal _ (fun pref => + UpperScalarPairComparison.modified_original_variation rows repeats p + (GeometricCutSplit.prefixPath hcut pref) slots + (projected pref) (projection pref) (choiceLaw pref) β hβ hβ' + ν GeometricPath.leafPath + (hbranch i (Nat.lt_of_lt_of_le (Nat.lt_succ_self i) hcut)) directions) + have heq := UpperScalarPairAveraging.geometric_average_eq_actual rows repeats p hcut slots + directions hbranch + change (GeometricCutSplit.prefixLaw hcut hbranch).mixture lowerOriginal = _ at heq + rw [heq] at hlower + have hupper := OriginalCutPairLaw.actual_pair_totalVariation_le rows repeats p slots + (GeometricPath.law j (fun k hk => hbranch k (Nat.lt_trans hk (Nat.lt_succ_self j)))) + GeometricPath.leafPath (hbranch j (Nat.lt_succ_self j)) hrows + exact (variation_triangle _ _ _).trans (add_le_add hlower hupper) + +end +end PerfectCompleteness.UpperCutTriangle + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/UpperScalarCutCalls.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/UpperScalarCutCalls.lean new file mode 100644 index 0000000000000000000000000000000000000000..9410fd353f9eabaf629d099edd8794cc52c1b7ea --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/UpperScalarCutCalls.lean @@ -0,0 +1,150 @@ +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalFrozenTablesLemmas +import OAI.Computability.PerfectCompleteness.Reduction.FixedCallBudgetLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.UpperScalarCutCalls + +open DescendantSpaces +open scoped BigOperators Classical + +noncomputable section + +variable {branch : Nat → Nat} {n j i depth : Nat} + +abbrev Index (rows repeats : Nat → Nat) (p : Path branch n j) (r : Path branch j i) := + OriginalCutCalls.Index rows repeats (p.append r) ⊕ TerminalCalls.TerminalIndex repeats r + +def oldCall (rows repeats : Nat → Nat) (p : Path branch n j) (r : Path branch j i) : + OriginalCutCalls.Index rows repeats (p.append r) → Index rows repeats p r := Sum.inl + +def freshCall (rows repeats : Nat → Nat) (p : Path branch n j) (r : Path branch j i) : + TerminalCalls.TerminalIndex repeats r → Index rows repeats p r := Sum.inr + +theorem oldCall_injective (rows repeats : Nat → Nat) + (p : Path branch n j) (r : Path branch j i) : + Function.Injective (oldCall rows repeats p r) := by + intro a b h + exact Sum.inl.inj h + +theorem freshCall_injective (rows repeats : Nat → Nat) + (p : Path branch n j) (r : Path branch j i) : + Function.Injective (freshCall rows repeats p r) := by + intro a b h + exact Sum.inr.inj h + +theorem old_ne_fresh (rows repeats : Nat → Nat) + (p : Path branch n j) (r : Path branch j i) + (old : OriginalCutCalls.Index rows repeats (p.append r)) + (fresh : TerminalCalls.TerminalIndex repeats r) : + oldCall rows repeats p r old ≠ freshCall rows repeats p r fresh := by + intro h + cases h + +theorem old_fresh_disjoint (rows repeats : Nat → Nat) + (p : Path branch n j) (r : Path branch j i) : + Disjoint (Set.range (oldCall rows repeats p r)) + (Set.range (freshCall rows repeats p r)) := by + refine Set.disjoint_left.mpr ?_ + rintro x ⟨old, rfl⟩ ⟨fresh, h⟩ + exact old_ne_fresh rows repeats p r old fresh h.symm + +def count (rows repeats : Nat → Nat) (root upper lower : Nat) : Nat := + OriginalCutCalls.count rows repeats root lower + + ∏ h ∈ Finset.Ioc lower upper, 2 * repeats h + +theorem card_eq_count (rows repeats : Nat → Nat) + (p : Path branch n j) (r : Path branch j i) : + Fintype.card (Index rows repeats p r) = count rows repeats n j i := by + simp only [Index, Fintype.card_sum, OriginalCutCalls.card_eq_count, + TerminalCalls.card_eq_prod, count] + +def numbering (rows repeats : Nat → Nat) (p : Path branch n j) (r : Path branch j i) : + Index rows repeats p r ≃ Fin (count rows repeats n j i) := + Fintype.equivFinOfCardEq (card_eq_count rows repeats p r) + +def terminalToOriginal (rows repeats : Nat → Nat) : + {j i : Nat} → (r : Path branch j i) → BucketSampler.Direction (rows j) → + TerminalCalls.TerminalIndex repeats r → OriginalCutCalls.Index rows repeats r + | _, _, .refl _, a, _ => a + | _, _, .step _ _, a, terminal => Sum.inl (a, terminal) + +theorem terminalToOriginal_injective (rows repeats : Nat → Nat) + (r : Path branch j i) (a : BucketSampler.Direction (rows j)) : + Function.Injective (terminalToOriginal rows repeats r a) := by + cases r with + | refl j => + change Function.Injective (fun _ : Unit => a) + intro x y _ + exact Subsingleton.elim x y + | @step k l child q => + intro x y h + exact congrArg Prod.snd (Sum.inl.inj h) + +def terminalEmbedding (rows repeats : Nat → Nat) + (r : Path branch j i) (a : BucketSampler.Direction (rows j)) : + TerminalCalls.TerminalIndex repeats r ↪ OriginalCutCalls.Index rows repeats r := + ⟨terminalToOriginal rows repeats r a, terminalToOriginal_injective rows repeats r a⟩ + +theorem terminal_card_le_original (rows repeats : Nat → Nat) + (r : Path branch j i) (a : BucketSampler.Direction (rows j)) : + Fintype.card (TerminalCalls.TerminalIndex repeats r) ≤ + Fintype.card (OriginalCutCalls.Index rows repeats r) := + Fintype.card_le_of_injective (terminalToOriginal rows repeats r a) + (terminalToOriginal_injective rows repeats r a) + +theorem card_le_two_budget (rows repeats : Nat → Nat) + (p : Path branch n j) (r : Path branch j i) + (a : BucketSampler.Direction (rows j)) (hroot : n ≤ depth) : + Fintype.card (Index rows repeats p r) ≤ 2 * FixedCallBudget.budget depth rows repeats := by + have hold := FixedCallBudget.original_calls_le rows repeats (p.append r) hroot + have hfresh := (terminal_card_le_original rows repeats r a).trans + (FixedCallBudget.original_calls_le rows repeats r (p.height_le.trans hroot)) + change Fintype.card + (OriginalCutCalls.Index rows repeats (p.append r) ⊕ TerminalCalls.TerminalIndex repeats r) ≤ _ + rw [Fintype.card_sum] + omega + +theorem count_le_two_budget (rows repeats : Nat → Nat) + (p : Path branch n j) (r : Path branch j i) + (a : BucketSampler.Direction (rows j)) (hroot : n ≤ depth) : + count rows repeats n j i ≤ 2 * FixedCallBudget.budget depth rows repeats := by + rw [← card_eq_count rows repeats p r] + exact card_le_two_budget rows repeats p r a hroot + +theorem card_le_budget_with_extra (rows repeats : Nat → Nat) + (p : Path branch n j) (r : Path branch j i) + (a : BucketSampler.Direction (rows j)) (hroot : n ≤ depth) : + Fintype.card (Index rows repeats p r) ≤ + 2 * FixedCallBudget.budget depth rows repeats + 1 := + (card_le_two_budget rows repeats p r a hroot).trans (Nat.le_succ _) + +theorem count_le_budget_with_extra (rows repeats : Nat → Nat) + (p : Path branch n j) (r : Path branch j i) + (a : BucketSampler.Direction (rows j)) (hroot : n ≤ depth) : + count rows repeats n j i ≤ 2 * FixedCallBudget.budget depth rows repeats + 1 := + (count_le_two_budget rows repeats p r a hroot).trans (Nat.le_succ _) + +theorem card_le_fixed_calls {δ : ℚ} (plan : FixedRows.Plan δ) + (p : Path branch n j) (r : Path branch j i) + (a : BucketSampler.Direction (FixedRows.rows plan j)) (hroot : n ≤ plan.depth) : + Fintype.card (Index (FixedRows.rows plan) (FixedRows.repeats plan) p r) ≤ + FixedParameters.calls plan := by + simpa only [FixedParameters.calls] using + card_le_budget_with_extra (FixedRows.rows plan) (FixedRows.repeats plan) p r a hroot + +theorem count_le_fixed_calls {δ : ℚ} (plan : FixedRows.Plan δ) + (p : Path branch n j) (r : Path branch j i) + (a : BucketSampler.Direction (FixedRows.rows plan j)) (hroot : n ≤ plan.depth) : + count (FixedRows.rows plan) (FixedRows.repeats plan) n j i ≤ FixedParameters.calls plan := by + simpa only [FixedParameters.calls] using + count_le_budget_with_extra (FixedRows.rows plan) (FixedRows.repeats plan) p r a hroot + +end +end PerfectCompleteness.UpperScalarCutCalls + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/UpperScalarCutComparison.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/UpperScalarCutComparison.lean new file mode 100644 index 0000000000000000000000000000000000000000..f3b67f4bfd924423c3d5642db83f53e42188452c --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/UpperScalarCutComparison.lean @@ -0,0 +1,128 @@ +import OAI.Computability.PerfectCompleteness.Decoding.UpperScalarCutLaw +import OAI.Computability.PerfectCompleteness.Foundations.ProjectedPrefixComparison + +namespace OAI + +section + +namespace PerfectCompleteness.UpperScalarCutComparison + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCutTape UpperScalarCutReconstruction +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +noncomputable section + +private theorem product_mixture_pushforward {E A B Γ : Type*} + [Fintype E] [Fintype A] [Fintype B] [Fintype Γ] + (μ : FiniteDistribution A) (κ : FiniteDistribution E) + (ν : E → FiniteDistribution B) (f : A × B → Γ) : + (μ.product (κ.mixture ν)).pushforward f = + κ.mixture (fun e => (μ.product (ν e)).pushforward f) := by + have hp : μ.product (κ.mixture ν) = κ.mixture (fun e => μ.product (ν e)) := by + apply FiniteDistribution.eq_of_weight_eq + intro x + simp only [FiniteDistribution.product, FiniteDistribution.mixture, Finset.mul_sum] + apply Finset.sum_congr rfl + intro e _ + exact mul_left_comm _ _ _ + rw [hp, FiniteDistribution.pushforward_mixture] + +variable {branch : Nat → Nat} {n j i k t : Nat} {K : Type*} [Fintype K] + +abbrev Observation (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) := + OriginalWholeCutBridge.NumberedRecord rows repeats (p.append r) slots × H (cutSlots p slots) + +def originalLaw (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (ν : FiniteDistribution K) (q : K → Path branch i k) (hbranch : 0 < branch i) : + FiniteDistribution (Observation rows repeats p r slots) := + ((UpperScalarCutLaw.exteriorLaw rows repeats p r slots).product + (OriginalPrefixContinuation.assembledLaw + (UpperScalarCutCalls.count rows repeats n j (i + 1)) rows repeats + (cutSlots (p.append r) slots) ν q hbranch)).pushforward + (numberedObserve rows repeats p r slots) + +attribute [local instance 2000] OriginalWholeCutLaw.valuesBelowFintype + +theorem originalLaw_eq_mixture (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (ν : FiniteDistribution K) (q : K → Path branch i k) (hbranch : 0 < branch i) : + originalLaw rows repeats p r slots ν q hbranch = + (OriginalPrefixContinuation.tagLaw ν hbranch).mixture (fun tag => + ((OriginalWholeCutLaw.recordLaw rows repeats (p.append r) tag.1 (q tag.2) slots).pushforward + (OriginalWholeCutBridge.numberRecord rows repeats (p.append r) slots)).product + (RecursiveSampler.law F2 repeats (r.append (.step tag.1 (q tag.2))) + (LeafDomain (cutSlots p slots)))) := by + unfold originalLaw + rw [OriginalPrefixContinuation.assembledLaw_eq_mixture, product_mixture_pushforward] + apply congrArg ((OriginalPrefixContinuation.tagLaw ν hbranch).mixture) + funext tag + exact UpperScalarCutLaw.numberedObserve_law rows repeats p r tag.1 (q tag.2) slots + +def uniformLaw (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) : + FiniteDistribution (Observation rows repeats p r slots) := + ((UpperScalarCutLaw.exteriorLaw rows repeats p r slots).product + (FiniteDistribution.uniform (CutChildGrouping.Assembled + (C := Fin (UpperScalarCutCalls.count rows repeats n j (i + 1))) + (cutSlots (p.append r) slots) rows))).pushforward + (numberedObserve rows repeats p r slots) + +theorem original_uniform_variation (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (ν : FiniteDistribution K) (q : K → Path branch i k) (hbranch : 0 < branch i) : + (originalLaw rows repeats p r slots ν q hbranch).totalVariation + (uniformLaw rows repeats p r slots) ≤ + Real.sqrt ((ChildBlockCardinality.bound branch i t + (UpperScalarCutCalls.count rows repeats n j (i + 1)) rows : ℝ) ^ 2 / branch i) / 2 := + CommonProductVariation.observed_product_le_of_bound + (UpperScalarCutLaw.exteriorLaw rows repeats p r slots) _ _ + (numberedObserve rows repeats p r slots) + (OriginalPrefixContinuation.assembledLaw_variation + (UpperScalarCutCalls.count rows repeats n j (i + 1)) rows repeats + (cutSlots (p.append r) slots) ν q hbranch) + +variable {Z : Fin (branch i) → Type*} [∀ c, Fintype (Z c)] + +def modifiedLaw (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (projected : (c : Fin (branch i)) → Z c → Slots branch i → Fin t → MixedSupport.Slot) + (projection : ∀ c z s a, MixedSupport.Projection + (childSlots (cutSlots (p.append r) slots) c s a) (projected c z s a)) + (choiceLaw : (c : Fin (branch i)) → FiniteDistribution (Z c)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) : + FiniteDistribution (Observation rows repeats p r slots) := + ((UpperScalarCutLaw.exteriorLaw rows repeats p r slots).product + (ProjectedPrefixComparison.assembledLaw + (UpperScalarCutCalls.count rows repeats n j (i + 1)) rows + (cutSlots (p.append r) slots) projected projection choiceLaw β hβ hβ')).pushforward + (numberedObserve rows repeats p r slots) + +theorem modified_original_variation (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (projected : (c : Fin (branch i)) → Z c → Slots branch i → Fin t → MixedSupport.Slot) + (projection : ∀ c z s a, MixedSupport.Projection + (childSlots (cutSlots (p.append r) slots) c s a) (projected c z s a)) + (choiceLaw : (c : Fin (branch i)) → FiniteDistribution (Z c)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) + (ν : FiniteDistribution K) (q : K → Path branch i k) (hbranch : 0 < branch i) : + (modifiedLaw rows repeats p r slots projected projection choiceLaw β hβ hβ').totalVariation + (originalLaw rows repeats p r slots ν q hbranch) ≤ + Real.sqrt ((1 + β ^ 2 * ((ChildBlockCardinality.bound branch i t + (UpperScalarCutCalls.count rows repeats n j (i + 1)) rows : ℝ) - 1)) ^ branch i - 1) / 2 + + Real.sqrt ((ChildBlockCardinality.bound branch i t + (UpperScalarCutCalls.count rows repeats n j (i + 1)) rows : ℝ) ^ 2 / branch i) / 2 := + ProjectedPrefixComparison.observed_original_variation + (UpperScalarCutCalls.count rows repeats n j (i + 1)) rows repeats + (cutSlots (p.append r) slots) projected projection choiceLaw β hβ hβ' ν q hbranch + (UpperScalarCutLaw.exteriorLaw rows repeats p r slots) (numberedObserve rows repeats p r slots) + +end +end PerfectCompleteness.UpperScalarCutComparison + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/UpperScalarCutErasure.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/UpperScalarCutErasure.lean new file mode 100644 index 0000000000000000000000000000000000000000..ce35f2771207186527fccca77e59ffd95da9cbb9 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/UpperScalarCutErasure.lean @@ -0,0 +1,235 @@ +import OAI.Computability.PerfectCompleteness.Decoding.UpperScalarCutReconstructionLemmas +import OAI.Computability.PerfectCompleteness.Sampling.OriginalCutPairLaw + +namespace OAI + +section + +namespace PerfectCompleteness.UpperScalarCutErasure + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCutTape WholeArrayInteriorExterior +open scoped Classical + +noncomputable section + +variable {branch : Nat → Nat} {n j i k t : Nat} + +def assocTapeEquiv (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j i) (q : Path branch i k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + WholeArraySampler.Tape rows repeats ((p.append r).append q) slots ≃ + WholeArraySampler.Tape rows repeats (p.append (r.append q)) slots := + Equiv.cast (congrArg (fun path => WholeArraySampler.Tape rows repeats path slots) + (p.append_assoc r q)) + +private theorem evaluate_cast (rows repeats : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + {u v : Path branch n k} (h : u = v) + (tape : WholeArraySampler.Tape rows repeats u slots) : + WholeArraySampler.evaluate rows repeats v slots + (Equiv.cast (congrArg (fun path => WholeArraySampler.Tape rows repeats path slots) h) tape) = + WholeArraySampler.evaluate rows repeats u slots tape := by + cases h + rfl + +theorem evaluate_assocTapeEquiv (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j i) (q : Path branch i k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (tape : WholeArraySampler.Tape rows repeats ((p.append r).append q) slots) : + WholeArraySampler.evaluate rows repeats (p.append (r.append q)) slots + (assocTapeEquiv rows repeats p r q slots tape) = + WholeArraySampler.evaluate rows repeats ((p.append r).append q) slots tape := + evaluate_cast rows repeats slots (p.append_assoc r q) tape + +private theorem cast_step_selected (rows repeats : Nat → Nat) (child : Fin (branch n)) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + {u v : Path branch n k} (h : u = v) + (tape : WholeArraySampler.Tape rows repeats (.step child u) slots) : + (Equiv.cast (congrArg (fun path => WholeArraySampler.Tape rows repeats path slots) + (congrArg (Path.step child) h)) tape) (.inr (.inl ())) = + Equiv.cast (congrArg + (fun path => WholeArraySampler.Tape rows repeats path (childSlots slots child)) h) + (tape (.inr (.inl ()))) := by + cases h + rfl + +theorem assocTapeEquiv_selected (rows repeats : Nat → Nat) (child : Fin (branch n)) + (p : Path branch n j) (r : Path branch j i) (q : Path branch i k) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (tape : WholeArraySampler.Tape rows repeats (((Path.step child p).append r).append q) slots) : + (assocTapeEquiv rows repeats (.step child p) r q slots tape) (.inr (.inl ())) = + assocTapeEquiv rows repeats p r q (childSlots slots child) (tape (.inr (.inl ()))) := + cast_step_selected rows repeats child slots (p.append_assoc r q) tape + +theorem extract_assocTapeEquiv (rows repeats : Nat → Nat) (p : Path branch n j) : + ∀ (r : Path branch j (i + 1)) (chosen : Fin (branch i)) (q : Path branch i k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (tape : WholeArraySampler.Tape rows repeats ((p.append r).append (.step chosen q)) slots), + WholeArraySubtreeSplit.extract rows repeats p (r.append (.step chosen q)) slots + (assocTapeEquiv rows repeats p r (.step chosen q) slots tape) = + UpperScalarCutBucket.descendTape rows repeats p r chosen q slots tape := by + induction p with + | refl n => intro r chosen q slots tape; rfl + | step child p ih => + intro r chosen q slots tape + rw [WholeArraySubtreeSplit.extract_step, assocTapeEquiv_selected] + exact ih r chosen q (childSlots slots child) (tape (.inr (.inl ()))) + +def upperReadRecord (rows repeats : Nat → Nat) : + {n j i k : Nat} → (p : Path branch n (j + 1)) → + (r : Path branch (j + 1) (i + 1)) → (chosen : Fin (branch i)) → (q : Path branch i k) → + (slots : Slots branch n → Fin t → MixedSupport.Slot) → + WholeArraySampler.Tape rows repeats (p.append (r.append (.step chosen q))) slots → + OriginalWholeCut.Record rows repeats p slots + | _, _, _, _, p, .refl _, chosen, q, slots, tape => + OriginalWholeCut.readRecord rows repeats p chosen q slots tape + | _, _, _, _, p, .step upperChild tail, chosen, q, slots, tape => + OriginalWholeCut.readRecord rows repeats p upperChild (tail.append (.step chosen q)) slots tape + +theorem upperReadRecord_reconstruct (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) (chosen : Fin (branch i)) (q : Path branch i k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (tape : WholeArraySampler.Tape rows repeats (p.append (r.append (.step chosen q))) slots) : + OriginalWholeCut.reconstructRecord rows repeats p slots + (upperReadRecord rows repeats p r chosen q slots tape) = + WholeArraySampler.evaluate rows repeats (p.append (r.append (.step chosen q))) slots tape := by + cases r with + | refl => exact OriginalWholeCut.reconstruct_original rows repeats p chosen q slots tape + | step upperChild tail => + exact OriginalWholeCut.reconstruct_original rows repeats p upperChild + (tail.append (.step chosen q)) slots tape + +theorem ownValues_readRecord (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) : + ∀ (chosen : Fin (branch j)) (q : Path branch j k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (tape : WholeArraySampler.Tape rows repeats (p.append (.step chosen q)) slots), + OriginalCutBucketReplacement.ownValues rows repeats p slots + (OriginalWholeCut.readRecord rows repeats p chosen q slots tape).2.1 = + fun direction => RecursiveSampler.evaluate F2 repeats (.step chosen q) + (LeafDomain (cutSlots p slots)) + ((WholeArraySubtreeSplit.extract rows repeats p (.step chosen q) slots tape) + (.inl ()) direction) := by + induction n generalizing j with + | zero => cases p + | succ n ih => + cases p with + | refl => intro chosen q slots tape; rfl + | step child p => + intro chosen q slots tape + exact ih p chosen q (childSlots slots child) (tape (.inr (.inl ()))) + +theorem upperReadRecord_ownValues (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) (chosen : Fin (branch i)) (q : Path branch i k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (tape : WholeArraySampler.Tape rows repeats (p.append (r.append (.step chosen q))) slots) : + OriginalCutBucketReplacement.ownValues rows repeats p slots + (upperReadRecord rows repeats p r chosen q slots tape).2.1 = + fun direction => RecursiveSampler.evaluate F2 repeats (r.append (.step chosen q)) + (LeafDomain (cutSlots p slots)) + (UpperScalarCutBucket.continuedRootTape rows repeats r chosen q (cutSlots p slots) + (WholeArraySubtreeSplit.extract rows repeats p (r.append (.step chosen q)) slots tape) + direction) := by + cases r with + | refl => exact ownValues_readRecord rows repeats p chosen q slots tape + | step upperChild tail => + exact ownValues_readRecord rows repeats p upperChild (tail.append (.step chosen q)) slots tape + +def upperPairRecord (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) (chosen : Fin (branch i)) (q : Path branch i k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (tape : WholeArraySampler.Tape rows repeats (p.append (r.append (.step chosen q))) slots) + (a : BucketSampler.Direction (rows (j + 1))) (fresh : H (cutSlots p slots)) : + HierarchicalAgreementMean.PairRecord (rows := rows) slots (upperNode p) := + OriginalCutCollision.pairRecord rows repeats p slots + (a, (OriginalWholeCutBridge.numberRecord rows repeats p slots + (upperReadRecord rows repeats p r chosen q slots tape), fresh)) + +private theorem originalPairRecord_numberRecord (rows repeats : Nat → Nat) + (p : Path branch n (j + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : OriginalWholeCut.Record rows repeats p slots) + (a : BucketSampler.Direction (rows (j + 1))) (fresh : H (cutSlots p slots)) : + OriginalCutCollision.pairRecord rows repeats p slots + (a, (OriginalWholeCutBridge.numberRecord rows repeats p slots record, fresh)) = + HierarchicalAgreementMean.pairRecord slots (upperNode p) + (HierarchicalMatrixTable.backgroundOf slots (upperNode p) + (OriginalWholeCut.reconstructRecord rows repeats p slots record), + CutNodeRows.bucketSampleEquiv rows p slots + (a, (OriginalCutBucketReplacement.ownValues rows repeats p slots record.2.1, fresh))) := by + simpa only [OriginalCutPairLaw.transportPair, OriginalCutBucketLaw.read, + OriginalCutCollision.oldArrays, OriginalCutBucketLaw.oldRecord_numberRecord] using + OriginalCutPairLaw.pairRecord_eq rows repeats p slots + (a, (OriginalWholeCutBridge.numberRecord rows repeats p slots record, fresh)) + +theorem upperBuckets_eq_ownValues (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) (chosen : Fin (branch i)) (q : Path branch i k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (tape : WholeArraySampler.Tape rows repeats ((p.append r).append (.step chosen q)) slots) : + UpperScalarCutBucket.upperBuckets rows repeats p r slots + (OriginalWholeCut.readRecord rows repeats (p.append r) chosen q slots tape) = + OriginalCutBucketReplacement.ownValues rows repeats p slots + (upperReadRecord rows repeats p r chosen q slots + (assocTapeEquiv rows repeats p r (.step chosen q) slots tape)).2.1 := by + rw [UpperScalarCutBucket.upperBuckets_readRecord, upperReadRecord_ownValues, + extract_assocTapeEquiv] + +theorem pairRecord_read_eq_upper (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) (chosen : Fin (branch i)) (q : Path branch i k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (tape : WholeArraySampler.Tape rows repeats ((p.append r).append (.step chosen q)) slots) + (a : BucketSampler.Direction (rows (j + 1))) (fresh : H (cutSlots p slots)) : + UpperScalarCutBucket.pairRecord rows repeats p r slots + (OriginalWholeCut.readRecord rows repeats (p.append r) chosen q slots tape) a fresh = + upperPairRecord rows repeats p r chosen q slots + (assocTapeEquiv rows repeats p r (.step chosen q) slots tape) a fresh := by + have harrays : + OriginalWholeCut.reconstructRecord rows repeats (p.append r) slots + (OriginalWholeCut.readRecord rows repeats (p.append r) chosen q slots tape) = + OriginalWholeCut.reconstructRecord rows repeats p slots + (upperReadRecord rows repeats p r chosen q slots + (assocTapeEquiv rows repeats p r (.step chosen q) slots tape)) := by + rw [OriginalWholeCut.reconstruct_original, upperReadRecord_reconstruct, + evaluate_assocTapeEquiv] + rw [UpperScalarCutBucket.pairRecord_eq] + unfold upperPairRecord + rw [originalPairRecord_numberRecord, harrays, upperBuckets_eq_ownValues] + +theorem enlargedPairRecord_read_eq_upper (rows repeats : Nat → Nat) + (p : Path branch n (j + 1)) (r : Path branch (j + 1) (i + 1)) + (chosen : Fin (branch i)) (q : Path branch i k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (a : BucketSampler.Direction (rows (j + 1))) + (tapes : WholeArraySampler.Tape rows repeats ((p.append r).append (.step chosen q)) slots × + RecursiveSampler.Tape F2 repeats (r.append (.step chosen q)) (LeafDomain (cutSlots p slots))) : + UpperScalarCutBucket.enlargedPairRecord rows repeats p r slots + (a, UpperScalarCutReconstruction.read rows repeats p r chosen q slots tapes) = + upperPairRecord rows repeats p r chosen q slots + (assocTapeEquiv rows repeats p r (.step chosen q) slots tapes.1) a + (RecursiveSampler.evaluate F2 repeats (r.append (.step chosen q)) + (LeafDomain (cutSlots p slots)) tapes.2) := by + rw [UpperScalarCutBucket.enlargedPairRecord_read] + exact pairRecord_read_eq_upper rows repeats p r chosen q slots tapes.1 a _ + +theorem numberedPairRecord_read_eq_upper (rows repeats : Nat → Nat) + (p : Path branch n (j + 1)) (r : Path branch (j + 1) (i + 1)) + (chosen : Fin (branch i)) (q : Path branch i k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (a : BucketSampler.Direction (rows (j + 1))) + (tapes : WholeArraySampler.Tape rows repeats ((p.append r).append (.step chosen q)) slots × + RecursiveSampler.Tape F2 repeats (r.append (.step chosen q)) (LeafDomain (cutSlots p slots))) : + UpperScalarCutBucket.numberedPairRecord rows repeats p r slots + (a, UpperScalarCutReconstruction.numberRecordEquiv rows repeats p r slots + (UpperScalarCutReconstruction.read rows repeats p r chosen q slots tapes)) = + upperPairRecord rows repeats p r chosen q slots + (assocTapeEquiv rows repeats p r (.step chosen q) slots tapes.1) a + (RecursiveSampler.evaluate F2 repeats (r.append (.step chosen q)) + (LeafDomain (cutSlots p slots)) tapes.2) := by + rw [UpperScalarCutBucket.numberedPairRecord_numberRecord] + exact enlargedPairRecord_read_eq_upper rows repeats p r chosen q slots a tapes + +end +end PerfectCompleteness.UpperScalarCutErasure + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/UpperScalarCutLaw.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/UpperScalarCutLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..d2dae0fb2e7d6e8a143f07292288dbaf8cbc4ecf --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/UpperScalarCutLaw.lean @@ -0,0 +1,318 @@ +import OAI.Computability.PerfectCompleteness.Decoding.UpperScalarCutReconstructionLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.UpperScalarCutLaw + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCutTape UpperScalarCutReconstruction +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +noncomputable section + +variable {branch : Nat → Nat} {n j i k t : Nat} + +private theorem scalarLaw_cast (repeats : Nat → Nat) (suffix : Path branch i k) + (slots slots' : Slots branch i → Fin t → MixedSupport.Slot) (h : slots = slots') : + (RecursiveSampler.law F2 repeats suffix (LeafDomain slots')).pushforward + (Equiv.cast (congrArg + (fun s : Slots branch i → Fin t → MixedSupport.Slot => ↥(H s)) h)).symm = + RecursiveSampler.law F2 repeats suffix (LeafDomain slots) := by + cases h + change (RecursiveSampler.law F2 repeats suffix (LeafDomain slots)).pushforward id = _ + exact FiniteDistribution.pushforward_id _ + +theorem cutSpaceEquiv_scalarLaw (repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j i) (suffix : Path branch i k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + (RecursiveSampler.law F2 repeats suffix + (r.family (LeafDomain (cutSlots p slots)))).pushforward + (cutSpaceEquiv p r slots).symm = + RecursiveSampler.law F2 repeats suffix (LeafDomain (cutSlots (p.append r) slots)) := + scalarLaw_cast repeats suffix (cutSlots (p.append r) slots) + (cutSlots r (cutSlots p slots)) (cutSlots_append p r slots) + +def freshExteriorLaw (repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j i) (slots : Slots branch n → Fin t → MixedSupport.Slot) : + FiniteDistribution (FreshExterior repeats p r slots) := + OriginalTerminalSplit.exteriorLaw F2 repeats r (LeafDomain (cutSlots p slots)) + +def freshValuesLaw (repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j i) (suffix : Path branch i k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + FiniteDistribution (FreshValues repeats p r slots) := + FiniteProduct.law (fun _ : TerminalCalls.TerminalIndex repeats r => + RecursiveSampler.law F2 repeats suffix (LeafDomain (cutSlots (p.append r) slots))) + +theorem readFresh_law (repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j i) (suffix : Path branch i k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + (RecursiveSampler.tapeLaw F2 repeats (r.append suffix) (LeafDomain (cutSlots p slots))).pushforward + (readFresh repeats p r suffix slots) = + (freshValuesLaw repeats p r suffix slots).product (freshExteriorLaw repeats p r slots) := by + let A := LeafDomain (cutSlots p slots) + let scalarTape := RecursiveSampler.tapeLaw F2 repeats suffix (r.family A) + let value : RecursiveSampler.Tape F2 repeats suffix (r.family A) → + H (cutSlots (p.append r) slots) := fun tape => + (cutSpaceEquiv p r slots).symm (RecursiveSampler.evaluate F2 repeats suffix (r.family A) tape) + let callsValue : OriginalTerminalSplit.TerminalTape F2 repeats r suffix A → + FreshValues repeats p r slots := fun tapes call => value (tapes call) + have hvalue : scalarTape.pushforward value = + RecursiveSampler.law F2 repeats suffix (LeafDomain (cutSlots (p.append r) slots)) := by + calc + _ = (RecursiveSampler.law F2 repeats suffix (r.family A)).pushforward + (cutSpaceEquiv p r slots).symm := + (FiniteDistribution.pushforward_comp scalarTape + (RecursiveSampler.evaluate F2 repeats suffix (r.family A)) + (cutSpaceEquiv p r slots).symm).symm + _ = _ := cutSpaceEquiv_scalarLaw repeats p r suffix slots + have hcalls : (OriginalTerminalSplit.terminalLaw F2 repeats r suffix A).pushforward + callsValue = freshValuesLaw repeats p r suffix slots := by + calc + _ = FiniteProduct.law (fun _ : TerminalCalls.TerminalIndex repeats r => + scalarTape.pushforward value) := + FiniteProduct.pushforward_map + (fun _ : TerminalCalls.TerminalIndex repeats r => scalarTape) (fun _ => value) + _ = _ := congrArg (fun μ : FiniteDistribution (H (cutSlots (p.append r) slots)) => + FiniteProduct.law (fun _ : TerminalCalls.TerminalIndex repeats r => μ)) hvalue + calc + _ = ((RecursiveSampler.tapeLaw F2 repeats (r.append suffix) A).pushforward + (OriginalTerminalSplit.splitTape F2 repeats r suffix A)).pushforward + (fun z => (callsValue z.1, z.2)) := + (FiniteDistribution.pushforward_comp _ _ _).symm + _ = ((OriginalTerminalSplit.terminalLaw F2 repeats r suffix A).product + (OriginalTerminalSplit.exteriorLaw F2 repeats r A)).pushforward + (fun z => (callsValue z.1, z.2)) := by + rw [OriginalTerminalSplit.split_tapeLaw] + _ = ((OriginalTerminalSplit.terminalLaw F2 repeats r suffix A).pushforward + callsValue).product + ((OriginalTerminalSplit.exteriorLaw F2 repeats r A).pushforward id) := + FiniteDistribution.product_pushforward + (OriginalTerminalSplit.terminalLaw F2 repeats r suffix A) + (OriginalTerminalSplit.exteriorLaw F2 repeats r A) callsValue id + _ = _ := by simp only [hcalls, FiniteDistribution.pushforward_id, freshExteriorLaw, A] + +def exteriorLaw (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) : + FiniteDistribution (UpperScalarCutReconstruction.Exterior rows repeats p r slots) := + (OriginalWholeCutTape.exteriorLaw rows repeats (p.append r) slots).product + (freshExteriorLaw repeats p r slots) + +def valuesLaw (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j i) (suffix : Path branch i k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + FiniteDistribution (UpperScalarCutCalls.Index rows repeats p r → + H (cutSlots (p.append r) slots)) := + FiniteProduct.law (fun _ : UpperScalarCutCalls.Index rows repeats p r => + RecursiveSampler.law F2 repeats suffix (LeafDomain (cutSlots (p.append r) slots))) + +def assembledEquiv (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) : + ((UpperScalarCutCalls.Index rows repeats p r → H (cutSlots (p.append r) slots)) × + OriginalWholeCut.ChildArrays rows (cutSlots (p.append r) slots)) ≃ + CutChildGrouping.Assembled (C := UpperScalarCutCalls.Index rows repeats p r) + (cutSlots (p.append r) slots) rows := Equiv.refl _ + +def assembledLaw (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (chosen : Fin (branch i)) (q : Path branch i k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + FiniteDistribution (CutChildGrouping.Assembled + (C := UpperScalarCutCalls.Index rows repeats p r) (cutSlots (p.append r) slots) rows) := + @FiniteDistribution.transport + ((UpperScalarCutCalls.Index rows repeats p r → H (cutSlots (p.append r) slots)) × + OriginalWholeCut.ChildArrays rows (cutSlots (p.append r) slots)) + (CutChildGrouping.Assembled (C := UpperScalarCutCalls.Index rows repeats p r) + (cutSlots (p.append r) slots) rows) + (instFintypeProd _ _) + (CutChildGrouping.assembledFintype (C := UpperScalarCutCalls.Index rows repeats p r) + (cutSlots (p.append r) slots) rows) + ((valuesLaw rows repeats p r (.step chosen q) slots).product + (OriginalWholeCutLaw.belowArraysLaw rows repeats chosen q (cutSlots (p.append r) slots))) + (assembledEquiv rows repeats p r slots) + +def recordLaw (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (chosen : Fin (branch i)) (q : Path branch i k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + FiniteDistribution (UpperScalarCutReconstruction.Record rows repeats p r slots) := + (exteriorLaw rows repeats p r slots).product (assembledLaw rows repeats p r chosen q slots) + +attribute [local instance 2000] OriginalWholeCutLaw.valuesBelowFintype + +theorem pack_law (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (chosen : Fin (branch i)) (q : Path branch i k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + ((OriginalWholeCutLaw.recordLaw rows repeats (p.append r) chosen q slots).product + ((freshValuesLaw repeats p r (.step chosen q) slots).product + (freshExteriorLaw repeats p r slots))).pushforward (packEquiv rows repeats p r slots) = + recordLaw rows repeats p r chosen q slots := by + rw [← FiniteDistribution.transport_eq_pushforward] + apply FiniteDistribution.eq_of_weight_eq + intro z + let scalar := RecursiveSampler.law F2 repeats (.step chosen q) + (LeafDomain (cutSlots (p.append r) slots)) + change + (OriginalWholeCutTape.exteriorLaw rows repeats (p.append r) slots).weight z.1.1 * + ((∏ call : OriginalCutCalls.Index rows repeats (p.append r), + scalar.weight (z.2.1 (.inl call))) * + (OriginalWholeCutLaw.belowArraysLaw rows repeats chosen q + (cutSlots (p.append r) slots)).weight z.2.2) * + ((∏ call : TerminalCalls.TerminalIndex repeats r, + scalar.weight (z.2.1 (.inr call))) * + (freshExteriorLaw repeats p r slots).weight z.1.2) = + ((OriginalWholeCutTape.exteriorLaw rows repeats (p.append r) slots).weight z.1.1 * + (freshExteriorLaw repeats p r slots).weight z.1.2) * + ((∏ call : OriginalCutCalls.Index rows repeats (p.append r) ⊕ + TerminalCalls.TerminalIndex repeats r, scalar.weight (z.2.1 call)) * + (OriginalWholeCutLaw.belowArraysLaw rows repeats chosen q + (cutSlots (p.append r) slots)).weight z.2.2) + rw [Fintype.prod_sum_type] + ring + +theorem read_law (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (chosen : Fin (branch i)) (q : Path branch i k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + ((WholeArraySampler.tapeLaw rows repeats ((p.append r).append (.step chosen q)) slots).product + (RecursiveSampler.tapeLaw F2 repeats (r.append (.step chosen q)) + (LeafDomain (cutSlots p slots)))).pushforward + (read rows repeats p r chosen q slots) = + recordLaw rows repeats p r chosen q slots := by + calc + _ = (((WholeArraySampler.tapeLaw rows repeats ((p.append r).append (.step chosen q)) slots).product + (RecursiveSampler.tapeLaw F2 repeats (r.append (.step chosen q)) + (LeafDomain (cutSlots p slots)))).pushforward + (fun tapes => + (OriginalWholeCut.readRecord rows repeats (p.append r) chosen q slots tapes.1, + readFresh repeats p r (.step chosen q) slots tapes.2))).pushforward + (packEquiv rows repeats p r slots) := + (FiniteDistribution.pushforward_comp _ _ _).symm + _ = (((WholeArraySampler.tapeLaw rows repeats ((p.append r).append (.step chosen q)) slots).pushforward + (OriginalWholeCut.readRecord rows repeats (p.append r) chosen q slots)).product + ((RecursiveSampler.tapeLaw F2 repeats (r.append (.step chosen q)) + (LeafDomain (cutSlots p slots))).pushforward + (readFresh repeats p r (.step chosen q) slots))).pushforward + (packEquiv rows repeats p r slots) := by + exact congrArg + (fun μ : FiniteDistribution (OriginalWholeCut.Record rows repeats (p.append r) slots × + FreshRecord repeats p r slots) => μ.pushforward (packEquiv rows repeats p r slots)) + (FiniteDistribution.product_pushforward + (WholeArraySampler.tapeLaw rows repeats ((p.append r).append (.step chosen q)) slots) + (RecursiveSampler.tapeLaw F2 repeats (r.append (.step chosen q)) + (LeafDomain (cutSlots p slots))) + (OriginalWholeCut.readRecord rows repeats (p.append r) chosen q slots) + (readFresh repeats p r (.step chosen q) slots)) + _ = _ := by + rw [OriginalWholeCutLaw.readRecord_law, readFresh_law] + exact pack_law rows repeats p r chosen q slots + +theorem numberRecord_law (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (chosen : Fin (branch i)) (q : Path branch i k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + (recordLaw rows repeats p r chosen q slots).pushforward (numberRecordEquiv rows repeats p r slots) = + (exteriorLaw rows repeats p r slots).product + ((OriginalChildBlocks.sourceLaw (UpperScalarCutCalls.count rows repeats n j (i + 1)) + rows repeats chosen q (cutSlots (p.append r) slots)).pushforward + (OriginalChildBlocks.observed (UpperScalarCutCalls.count rows repeats n j (i + 1)) + rows repeats chosen q (cutSlots (p.append r) slots))) := by + rw [OriginalWholeCutBridge.observed_product_law, + ← FiniteDistribution.transport_eq_pushforward + (recordLaw rows repeats p r chosen q slots) (numberRecordEquiv rows repeats p r slots)] + apply FiniteDistribution.eq_of_weight_eq + intro z + let scalar := RecursiveSampler.law F2 repeats (.step chosen q) + (LeafDomain (cutSlots (p.append r) slots)) + change (exteriorLaw rows repeats p r slots).weight z.1 * + ((∏ call : UpperScalarCutCalls.Index rows repeats p r, + scalar.weight (z.2.1 (UpperScalarCutCalls.numbering rows repeats p r call))) * + (OriginalWholeCutLaw.belowArraysLaw rows repeats chosen q + (cutSlots (p.append r) slots)).weight z.2.2) = + (exteriorLaw rows repeats p r slots).weight z.1 * + ((∏ call : Fin (UpperScalarCutCalls.count rows repeats n j (i + 1)), + scalar.weight (z.2.1 call)) * + (OriginalWholeCutLaw.belowArraysLaw rows repeats chosen q + (cutSlots (p.append r) slots)).weight z.2.2) + exact congrArg (fun w : ℝ => (exteriorLaw rows repeats p r slots).weight z.1 * + (w * (OriginalWholeCutLaw.belowArraysLaw rows repeats chosen q + (cutSlots (p.append r) slots)).weight z.2.2)) + ((UpperScalarCutCalls.numbering rows repeats p r).prod_comp + (fun call => scalar.weight (z.2.1 call))) + +theorem numbered_read_law (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (chosen : Fin (branch i)) (q : Path branch i k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + ((WholeArraySampler.tapeLaw rows repeats ((p.append r).append (.step chosen q)) slots).product + (RecursiveSampler.tapeLaw F2 repeats (r.append (.step chosen q)) + (LeafDomain (cutSlots p slots)))).pushforward + (fun tapes => numberRecordEquiv rows repeats p r slots + (read rows repeats p r chosen q slots tapes)) = + (exteriorLaw rows repeats p r slots).product + ((OriginalChildBlocks.sourceLaw (UpperScalarCutCalls.count rows repeats n j (i + 1)) + rows repeats chosen q (cutSlots (p.append r) slots)).pushforward + (OriginalChildBlocks.observed (UpperScalarCutCalls.count rows repeats n j (i + 1)) + rows repeats chosen q (cutSlots (p.append r) slots))) := by + rw [← FiniteDistribution.pushforward_comp, read_law, numberRecord_law] + +theorem observe_law (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (chosen : Fin (branch i)) (q : Path branch i k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + (recordLaw rows repeats p r chosen q slots).pushforward (observe rows repeats p r slots) = + ((OriginalWholeCutLaw.recordLaw rows repeats (p.append r) chosen q slots).pushforward + (OriginalWholeCutBridge.numberRecord rows repeats (p.append r) slots)).product + (RecursiveSampler.law F2 repeats (r.append (.step chosen q)) + (LeafDomain (cutSlots p slots))) := by + have hmap : + (fun tapes => observe rows repeats p r slots (read rows repeats p r chosen q slots tapes)) = + (fun tapes => + (OriginalWholeCutBridge.numberRecord rows repeats (p.append r) slots + (OriginalWholeCut.readRecord rows repeats (p.append r) chosen q slots tapes.1), + RecursiveSampler.evaluate F2 repeats (r.append (.step chosen q)) + (LeafDomain (cutSlots p slots)) tapes.2)) := + funext (fun tapes => observe_read rows repeats p r chosen q slots tapes) + rw [← read_law rows repeats p r chosen q slots, FiniteDistribution.pushforward_comp, hmap] + apply Eq.trans (FiniteDistribution.product_pushforward + (A := OriginalWholeCutBridge.NumberedRecord rows repeats (p.append r) slots) + (B := ↥(H (cutSlots p slots))) + (WholeArraySampler.tapeLaw rows repeats ((p.append r).append (.step chosen q)) slots) + (RecursiveSampler.tapeLaw F2 repeats (r.append (.step chosen q)) + (LeafDomain (cutSlots p slots))) + (fun tape => OriginalWholeCutBridge.numberRecord rows repeats (p.append r) slots + (OriginalWholeCut.readRecord rows repeats (p.append r) chosen q slots tape)) + (RecursiveSampler.evaluate F2 repeats (r.append (.step chosen q)) + (LeafDomain (cutSlots p slots)))) + rw [← FiniteDistribution.pushforward_comp + (WholeArraySampler.tapeLaw rows repeats ((p.append r).append (.step chosen q)) slots) + (OriginalWholeCut.readRecord rows repeats (p.append r) chosen q slots) + (OriginalWholeCutBridge.numberRecord rows repeats (p.append r) slots), + OriginalWholeCutLaw.readRecord_law] + rfl + +theorem numberedObserve_law (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (chosen : Fin (branch i)) (q : Path branch i k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + ((exteriorLaw rows repeats p r slots).product + ((OriginalChildBlocks.sourceLaw (UpperScalarCutCalls.count rows repeats n j (i + 1)) + rows repeats chosen q (cutSlots (p.append r) slots)).pushforward + (OriginalChildBlocks.observed (UpperScalarCutCalls.count rows repeats n j (i + 1)) + rows repeats chosen q (cutSlots (p.append r) slots)))).pushforward + (numberedObserve rows repeats p r slots) = + ((OriginalWholeCutLaw.recordLaw rows repeats (p.append r) chosen q slots).pushforward + (OriginalWholeCutBridge.numberRecord rows repeats (p.append r) slots)).product + (RecursiveSampler.law F2 repeats (r.append (.step chosen q)) + (LeafDomain (cutSlots p slots))) := by + rw [← numberRecord_law rows repeats p r chosen q slots, + FiniteDistribution.pushforward_comp] + have hmap : + (fun record => numberedObserve rows repeats p r slots + (numberRecordEquiv rows repeats p r slots record)) = observe rows repeats p r slots := + funext (fun record => numberedObserve_numberRecord rows repeats p r slots record) + rw [hmap] + exact observe_law rows repeats p r chosen q slots + +end +end PerfectCompleteness.UpperScalarCutLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/UpperScalarCutProjection.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/UpperScalarCutProjection.lean new file mode 100644 index 0000000000000000000000000000000000000000..ea6ee938b6ae71eabb15122565f0eb9471d11d95 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/UpperScalarCutProjection.lean @@ -0,0 +1,418 @@ +import OAI.Computability.PerfectCompleteness.Decoding.OriginalWholeCutProjection +import OAI.Computability.PerfectCompleteness.Decoding.SelectedArrayProjection +import OAI.Computability.PerfectCompleteness.Decoding.UpperScalarCutReconstructionLemmas +import OAI.Computability.PerfectCompleteness.Decoding.UpperScalarCutReference +import OAI.Computability.PerfectCompleteness.Decoding.UpperScalarFreshProjectionLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.UpperScalarCutProjection + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCutTape WholeArrayInteriorExterior +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) +open scoped BigOperators Classical + +noncomputable section + +variable {branch : Nat → Nat} {n j i t : Nat} + +def oldRecordPullback (rows repeats : Nat → Nat) (p : Path branch n (i + 1)) + (left right : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (hs : ∀ s, WholeCutExteriorTransport.Outside p s → left s = right s) + (record : OriginalWholeCut.Record rows repeats p right) : + OriginalWholeCut.Record rows repeats p left := + (OriginalWholeCutProjection.exteriorEquiv rows repeats p right left + (fun s h => (hs s h).symm) record.1, + ChildAssemblyProjection.assembledPullback rows (CutGroupedProjection.cutProjection p q) record.2) + +theorem reconstruct_pullback (rows repeats : Nat → Nat) (p : Path branch n (i + 1)) + (left right : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (hs : ∀ s, WholeCutExteriorTransport.Outside p s → left s = right s) + (hk : ∀ s, WholeCutExteriorTransport.Outside p s → ∀ k, + HEq (q s k) (MixedSupport.Projection.keep (left s k))) + (record : OriginalWholeCut.Record rows repeats p right) : + OriginalWholeCut.reconstructRecord rows repeats p left + (oldRecordPullback rows repeats p left right q hs record) = + ChildBlockProjection.arraysPullback rows q + (OriginalWholeCut.reconstructRecord rows repeats p right record) := + OriginalWholeCutProjection.reconstruct_pullback rows repeats p left right q hs hk + record.1 record.2.1 record.2.2 + +theorem rootBuckets_pullback (rows repeats : Nat → Nat) + (r : Path branch (j + 1) (i + 1)) + (left right : Slots branch (j + 1) → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (hs : ∀ s, WholeCutExteriorTransport.Outside r s → left s = right s) + (hk : ∀ s, WholeCutExteriorTransport.Outside r s → ∀ k, + HEq (q s k) (MixedSupport.Projection.keep (left s k))) + (record : OriginalWholeCut.Record rows repeats r right) : + UpperScalarCutBucket.rootBuckets rows repeats r left + (oldRecordPullback rows repeats r left right q hs record) = + fun a => HPullback q (UpperScalarCutBucket.rootBuckets rows repeats r right record a) := by + cases r with + | refl => rfl + | step child r => + funext a + unfold oldRecordPullback + rw [OriginalWholeCutProjection.exteriorEquiv_step rows repeats child r left right hs record.1] + exact OriginalScalarProjection.reconstruct_pullback repeats (.step child r) + left right q hs hk (fun terminal => record.2.1 (.inl (a, terminal))) (record.1.1 a) + +theorem upperBuckets_pullback (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) : + ∀ (r : Path branch (j + 1) (i + 1)) + (left right : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (hs : ∀ s, WholeCutExteriorTransport.Outside (p.append r) s → left s = right s), + (∀ s, WholeCutExteriorTransport.Outside (p.append r) s → ∀ k, + HEq (q s k) (MixedSupport.Projection.keep (left s k))) → + ∀ (record : OriginalWholeCut.Record rows repeats (p.append r) right), + UpperScalarCutBucket.upperBuckets rows repeats p r left + (oldRecordPullback rows repeats (p.append r) left right q hs record) = + fun a => HPullback (CutGroupedProjection.cutProjection p q) + (UpperScalarCutBucket.upperBuckets rows repeats p r right record a) := by + induction n generalizing j with + | zero => cases p + | succ n ih => + cases p with + | refl => + intro r left right q hs hk record + exact rootBuckets_pullback rows repeats r left right q hs hk record + | step child p => + intro r left right q hs hk record + unfold oldRecordPullback + have hext := OriginalWholeCutProjection.exteriorEquiv_step rows repeats child + (p.append r) left right hs record.1 + refine (congrArg (fun exterior : OriginalWholeCutTape.Exterior rows repeats + ((Path.step child p).append r) left => + UpperScalarCutBucket.upperBuckets rows repeats (.step child p) r left + (exterior, ChildAssemblyProjection.assembledPullback rows + (CutGroupedProjection.cutProjection ((Path.step child p).append r) q) + record.2)) hext).trans ?_ + exact ih p r (childSlots left child) (childSlots right child) (fun s k => q (child, s) k) + (fun s h => hs (child, s) (WholeCutExteriorTransport.outside_selected child (p.append r) s h)) + (fun s h k => hk (child, s) (WholeCutExteriorTransport.outside_selected child (p.append r) s h) k) + (record.1.2.1, (fun call => record.2.1 (.inr call), record.2.2)) + +theorem map_updated_buckets {A B : Type*} [AddCommGroup A] [AddCommGroup B] + [Module F2 A] [Module F2 B] {w : Nat} (f : A →ₗ[F2] B) + (buckets : BucketSampler.Tape w A) (a : BucketSampler.Direction w) (fresh : A) : + BucketSampler.evaluate w id (Function.update (fun b => f (buckets b)) a (f fresh)) = + fun row => f (BucketSampler.evaluate w id (Function.update buckets a fresh) row) := by + have hupdate : Function.update (fun b => f (buckets b)) a (f fresh) = + fun b => f (Function.update buckets a fresh b) := by + funext b + by_cases h : b = a <;> simp [h] + rw [hupdate] + funext row + simp only [BucketSampler.evaluate, id_eq, map_sum, map_smul] + +theorem replaceArrays_pullback (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) + (left right : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (hs : ∀ s, WholeCutExteriorTransport.Outside (p.append r) s → left s = right s) + (hk : ∀ s, WholeCutExteriorTransport.Outside (p.append r) s → ∀ k, + HEq (q s k) (MixedSupport.Projection.keep (left s k))) + (record : OriginalWholeCut.Record rows repeats (p.append r) right) + (a : BucketSampler.Direction (rows (j + 1))) (fresh : H (cutSlots p right)) : + UpperScalarCutBucket.replaceArrays rows repeats p r left + (oldRecordPullback rows repeats (p.append r) left right q hs record) a + (HPullback (CutGroupedProjection.cutProjection p q) fresh) = + ChildBlockProjection.arraysPullback rows q + (UpperScalarCutBucket.replaceArrays rows repeats p r right record a fresh) := by + unfold UpperScalarCutBucket.replaceArrays + rw [reconstruct_pullback rows repeats (p.append r) left right q hs hk, + upperBuckets_pullback rows repeats p r left right q hs hk, + map_updated_buckets] + exact SelectedArrayProjection.replace_pullback rows p left right q _ _ + +def projectedPair (rows : Nat → Nat) (p : Path branch n (j + 1)) + (left right : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (arrays : Arrays right rows) + (buckets : BucketSampler.Tape (rows (j + 1)) (H (cutSlots p right))) + (a : BucketSampler.Direction (rows (j + 1))) (fresh : H (cutSlots p right)) : + HierarchicalAgreementMean.PairRecord (rows := rows) left (upperNode p) := + (HierarchicalMatrixTable.backgroundOf left (upperNode p) + (ChildBlockProjection.arraysPullback rows q arrays), + (NodeEmbedding.matrix (ChildBlockProjection.arraysPullback rows q arrays) (upperNode p), + NodeEmbedding.matrix (ChildBlockProjection.arraysPullback rows q + (SelectedArrayReplacement.replace rows p right arrays + (BucketSampler.evaluate (rows (j + 1)) id (Function.update buckets a fresh)))) (upperNode p))) + +theorem pairRecord_pullback (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) + (left right : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (hs : ∀ s, WholeCutExteriorTransport.Outside (p.append r) s → left s = right s) + (hk : ∀ s, WholeCutExteriorTransport.Outside (p.append r) s → ∀ k, + HEq (q s k) (MixedSupport.Projection.keep (left s k))) + (record : OriginalWholeCut.Record rows repeats (p.append r) right) + (a : BucketSampler.Direction (rows (j + 1))) (fresh : H (cutSlots p right)) : + UpperScalarCutBucket.pairRecord rows repeats p r left + (oldRecordPullback rows repeats (p.append r) left right q hs record) a + (HPullback (CutGroupedProjection.cutProjection p q) fresh) = + projectedPair rows p left right q + (OriginalWholeCut.reconstructRecord rows repeats (p.append r) right record) + (UpperScalarCutBucket.upperBuckets rows repeats p r right record) a fresh := by + unfold UpperScalarCutBucket.pairRecord projectedPair + rw [reconstruct_pullback rows repeats (p.append r) left right q hs hk, + replaceArrays_pullback rows repeats p r left right q hs hk] + rfl + +def exteriorEquiv (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) + (left right : Slots branch n → Fin t → MixedSupport.Slot) + (hs : ∀ s, WholeCutExteriorTransport.Outside (p.append r) s → left s = right s) : + UpperScalarCutReconstruction.Exterior rows repeats p r right ≃ + UpperScalarCutReconstruction.Exterior rows repeats p r left := + Equiv.prodCongr + (OriginalWholeCutProjection.exteriorEquiv rows repeats (p.append r) right left + (fun s h => (hs s h).symm)) + (UpperScalarFreshProjection.freshExteriorEquiv repeats p r left right hs) + +theorem exteriorEquiv_law (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) + (left right : Slots branch n → Fin t → MixedSupport.Slot) + (hs : ∀ s, WholeCutExteriorTransport.Outside (p.append r) s → left s = right s) : + (UpperScalarCutLaw.exteriorLaw rows repeats p r right).pushforward + (exteriorEquiv rows repeats p r left right hs) = + UpperScalarCutLaw.exteriorLaw rows repeats p r left := by + unfold UpperScalarCutLaw.exteriorLaw + change ((OriginalWholeCutTape.exteriorLaw rows repeats (p.append r) right).product + (UpperScalarCutLaw.freshExteriorLaw repeats p r right)).pushforward (fun z => + (OriginalWholeCutProjection.exteriorEquiv rows repeats (p.append r) right left + (fun s h => (hs s h).symm) z.1, + UpperScalarFreshProjection.freshExteriorEquiv repeats p r left right hs z.2)) = _ + rw [FiniteDistribution.product_pushforward + (OriginalWholeCutTape.exteriorLaw rows repeats (p.append r) right) + (UpperScalarCutLaw.freshExteriorLaw repeats p r right) + (OriginalWholeCutProjection.exteriorEquiv rows repeats (p.append r) right left + (fun s h => (hs s h).symm)) + (UpperScalarFreshProjection.freshExteriorEquiv repeats p r left right hs), + OriginalWholeCutProjection.exteriorEquiv_law, + UpperScalarFreshProjection.freshExteriorEquiv_law] + +def recordPullback (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) + (left right : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (hs : ∀ s, WholeCutExteriorTransport.Outside (p.append r) s → left s = right s) + (record : UpperScalarCutReconstruction.Record rows repeats p r right) : + UpperScalarCutReconstruction.Record rows repeats p r left := + (exteriorEquiv rows repeats p r left right hs record.1, + ChildAssemblyProjection.assembledPullback rows + (CutGroupedProjection.cutProjection (p.append r) q) record.2) + +def numberedRecordPullback (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) + (left right : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (hs : ∀ s, WholeCutExteriorTransport.Outside (p.append r) s → left s = right s) + (record : UpperScalarCutReconstruction.NumberedRecord rows repeats p r right) : + UpperScalarCutReconstruction.NumberedRecord rows repeats p r left := + (exteriorEquiv rows repeats p r left right hs record.1, + ChildAssemblyProjection.assembledPullback rows + (CutGroupedProjection.cutProjection (p.append r) q) record.2) + +theorem enlargedPairRecord_pullback (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) + (left right : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (hs : ∀ s, WholeCutExteriorTransport.Outside (p.append r) s → left s = right s) + (hk : ∀ s, WholeCutExteriorTransport.Outside (p.append r) s → ∀ k, + HEq (q s k) (MixedSupport.Projection.keep (left s k))) + (a : BucketSampler.Direction (rows (j + 1))) + (record : UpperScalarCutReconstruction.Record rows repeats p r right) : + UpperScalarCutBucket.enlargedPairRecord rows repeats p r left + (a, recordPullback rows repeats p r left right q hs record) = + projectedPair rows p left right q + (OriginalWholeCut.reconstructRecord rows repeats (p.append r) right + (UpperScalarCutReconstruction.oldRecord rows repeats p r right record)) + (UpperScalarCutBucket.upperBuckets rows repeats p r right + (UpperScalarCutReconstruction.oldRecord rows repeats p r right record)) a + (UpperScalarCutReconstruction.reconstructFresh repeats p r right + (UpperScalarCutReconstruction.freshRecord rows repeats p r right record)) := by + change UpperScalarCutBucket.pairRecord rows repeats p r left + (oldRecordPullback rows repeats (p.append r) left right q hs + (UpperScalarCutReconstruction.oldRecord rows repeats p r right record)) a + (UpperScalarCutReconstruction.reconstructFresh repeats p r left + (fun call => HPullback (CutGroupedProjection.cutProjection (p.append r) q) + (record.2.1 (.inr call)), + UpperScalarFreshProjection.freshExteriorEquiv repeats p r left right hs record.1.2)) = _ + rw [UpperScalarFreshProjection.reconstructFresh_pullback repeats p r left right q hs hk] + exact pairRecord_pullback rows repeats p r left right q hs hk _ a _ + +theorem numberedPairRecord_pullback (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) + (left right : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (hs : ∀ s, WholeCutExteriorTransport.Outside (p.append r) s → left s = right s) + (hk : ∀ s, WholeCutExteriorTransport.Outside (p.append r) s → ∀ k, + HEq (q s k) (MixedSupport.Projection.keep (left s k))) + (a : BucketSampler.Direction (rows (j + 1))) + (record : UpperScalarCutReconstruction.Record rows repeats p r right) : + UpperScalarCutBucket.numberedPairRecord rows repeats p r left + (a, numberedRecordPullback rows repeats p r left right q hs + (UpperScalarCutReconstruction.numberRecordEquiv rows repeats p r right record)) = + projectedPair rows p left right q + (OriginalWholeCut.reconstructRecord rows repeats (p.append r) right + (UpperScalarCutReconstruction.oldRecord rows repeats p r right record)) + (UpperScalarCutBucket.upperBuckets rows repeats p r right + (UpperScalarCutReconstruction.oldRecord rows repeats p r right record)) a + (UpperScalarCutReconstruction.reconstructFresh repeats p r right + (UpperScalarCutReconstruction.freshRecord rows repeats p r right record)) := by + have hnumber : numberedRecordPullback rows repeats p r left right q hs + (UpperScalarCutReconstruction.numberRecordEquiv rows repeats p r right record) = + UpperScalarCutReconstruction.numberRecordEquiv rows repeats p r left + (recordPullback rows repeats p r left right q hs record) := rfl + rw [hnumber, UpperScalarCutBucket.numberedPairRecord_numberRecord] + exact enlargedPairRecord_pullback rows repeats p r left right q hs hk a record + +def stoppedProjectedPair (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) (hproper : i + 1 < j + 1) + (left right : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (sample : BucketSampler.Direction (rows (j + 1)) × + (WholeArraySampler.Tape rows repeats (p.append r) right × H (cutSlots p right))) : + HierarchicalAgreementMean.PairRecord (rows := rows) left (upperNode p) := + projectedPair rows p left right q + (WholeArraySampler.evaluate rows repeats (p.append r) right sample.2.1) + (UpperStoppedBuckets.stoppedBuckets rows repeats p r hproper right sample.2.1) + sample.1 sample.2.2 + +private def stoppedRead (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : UpperScalarCutReconstruction.Record rows repeats p r slots) : + WholeArraySampler.Tape rows repeats (p.append r) slots × H (cutSlots p slots) := + (OriginalUniformCut.toStoppedTape rows repeats (p.append r) slots + (UpperScalarCutReconstruction.oldRecord rows repeats p r slots record), + UpperScalarCutReconstruction.reconstructFresh repeats p r slots + (UpperScalarCutReconstruction.freshRecord rows repeats p r slots record)) + +private theorem numberedPairRecord_stoppedRead (rows repeats : Nat → Nat) + (p : Path branch n (j + 1)) (r : Path branch (j + 1) (i + 1)) + (hproper : i + 1 < j + 1) + (left right : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (hs : ∀ s, WholeCutExteriorTransport.Outside (p.append r) s → left s = right s) + (hk : ∀ s, WholeCutExteriorTransport.Outside (p.append r) s → ∀ k, + HEq (q s k) (MixedSupport.Projection.keep (left s k))) + (a : BucketSampler.Direction (rows (j + 1))) + (record : UpperScalarCutReconstruction.Record rows repeats p r right) : + UpperScalarCutBucket.numberedPairRecord rows repeats p r left + (a, numberedRecordPullback rows repeats p r left right q hs + (UpperScalarCutReconstruction.numberRecordEquiv rows repeats p r right record)) = + stoppedProjectedPair rows repeats p r hproper left right q + (a, stoppedRead rows repeats p r right record) := by + rw [numberedPairRecord_pullback rows repeats p r left right q hs hk] + unfold stoppedProjectedPair stoppedRead + rw [OriginalUniformCut.evaluate_toStoppedTape, + ← UpperStoppedBuckets.upperBuckets_toStoppedTape] + +attribute [local instance] linearMapFintype + +local instance backgroundFintype (rows : Nat → Nat) (p : Path branch n (j + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Fintype (HierarchicalMatrixTable.Background (rows := rows) slots (upperNode p)) := + Fintype.ofFinite _ + +local instance rowSpaceFintype (p : Path branch n (j + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Fintype (NodeEmbedding.RowSpace slots (upperNode p)) := Fintype.ofFinite _ + +private theorem product_push_right {A B C : Type*} [Fintype A] [Fintype B] [Fintype C] + (μ : FiniteDistribution A) (ν : FiniteDistribution B) (f : B → C) : + (μ.product ν).pushforward (fun z => (z.1, f z.2)) = μ.product (ν.pushforward f) := by + simpa only [FiniteDistribution.pushforward_id, id_eq] using + (FiniteDistribution.product_pushforward μ ν id f) + +attribute [local instance 2000] OriginalWholeCutLaw.valuesBelowFintype in +private theorem stoppedRead_law (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + (UpperScalarCutReference.referenceLaw rows repeats p r slots).pushforward + (stoppedRead rows repeats p r slots) = + (WholeArraySampler.tapeLaw rows repeats (p.append r) slots).product + (RecursiveSampler.law F2 repeats r (LeafDomain (cutSlots p slots))) := by + rw [← UpperScalarCutReference.pack_referenceLaw rows repeats p r slots, + FiniteDistribution.pushforward_comp] + change ((OriginalUniformCut.referenceLaw rows repeats (p.append r) slots).product + (UpperScalarCutReference.freshReferenceLaw repeats p r slots)).pushforward + (fun z => (OriginalUniformCut.toStoppedTape rows repeats (p.append r) slots z.1, + UpperScalarCutReconstruction.reconstructFresh repeats p r slots z.2)) = _ + rw [FiniteDistribution.product_pushforward + (OriginalUniformCut.referenceLaw rows repeats (p.append r) slots) + (UpperScalarCutReference.freshReferenceLaw repeats p r slots) + (OriginalUniformCut.toStoppedTape rows repeats (p.append r) slots) + (UpperScalarCutReconstruction.reconstructFresh repeats p r slots), + UpperStoppedBuckets.reference_toStoppedTape, + UpperScalarCutReference.reconstructFresh_referenceLaw] + +theorem fixed_projected_law (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) (hproper : i + 1 < j + 1) + (left right : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (hs : ∀ s, WholeCutExteriorTransport.Outside (p.append r) s → left s = right s) + (hk : ∀ s, WholeCutExteriorTransport.Outside (p.append r) s → ∀ k, + HEq (q s k) (MixedSupport.Projection.keep (left s k))) + (directions : FiniteDistribution (BucketSampler.Direction (rows (j + 1)))) : + (directions.product ((UpperScalarCutLaw.exteriorLaw rows repeats p r left).product + ((FiniteDistribution.uniform (CutChildGrouping.Assembled + (C := Fin (UpperScalarCutCalls.count rows repeats n (j + 1) (i + 1))) + (cutSlots (p.append r) right) rows)).pushforward + (ChildAssemblyProjection.assembledPullback rows + (CutGroupedProjection.cutProjection (p.append r) q))))).pushforward + (UpperScalarCutBucket.numberedPairRecord rows repeats p r left) = + (directions.product ((WholeArraySampler.tapeLaw rows repeats (p.append r) right).product + (RecursiveSampler.law F2 repeats r (LeafDomain (cutSlots p right))))).pushforward + (stoppedProjectedPair rows repeats p r hproper left right q) := by + have hlift : (UpperScalarCutReference.numberedReferenceLaw rows repeats p r right).pushforward + (numberedRecordPullback rows repeats p r left right q hs) = + (UpperScalarCutLaw.exteriorLaw rows repeats p r left).product + ((FiniteDistribution.uniform (CutChildGrouping.Assembled + (C := Fin (UpperScalarCutCalls.count rows repeats n (j + 1) (i + 1))) + (cutSlots (p.append r) right) rows)).pushforward + (ChildAssemblyProjection.assembledPullback rows + (CutGroupedProjection.cutProjection (p.append r) q))) := by + unfold UpperScalarCutReference.numberedReferenceLaw numberedRecordPullback + rw [FiniteDistribution.product_pushforward + (UpperScalarCutLaw.exteriorLaw rows repeats p r right) + (FiniteDistribution.uniform (CutChildGrouping.Assembled + (C := Fin (UpperScalarCutCalls.count rows repeats n (j + 1) (i + 1))) + (cutSlots (p.append r) right) rows)) + (exteriorEquiv rows repeats p r left right hs) + (ChildAssemblyProjection.assembledPullback rows + (CutGroupedProjection.cutProjection (p.append r) q)), exteriorEquiv_law] + rw [← hlift, ← product_push_right, FiniteDistribution.pushforward_comp, + ← UpperScalarCutReference.numberRecord_referenceLaw rows repeats p r right, + ← product_push_right, FiniteDistribution.pushforward_comp] + have hmap : + (fun sample : BucketSampler.Direction (rows (j + 1)) × + UpperScalarCutReconstruction.Record rows repeats p r right => + UpperScalarCutBucket.numberedPairRecord rows repeats p r left + (sample.1, numberedRecordPullback rows repeats p r left right q hs + (UpperScalarCutReconstruction.numberRecordEquiv rows repeats p r right sample.2))) = + (fun sample => stoppedProjectedPair rows repeats p r hproper left right q + (sample.1, stoppedRead rows repeats p r right sample.2)) := by + funext sample + exact numberedPairRecord_stoppedRead rows repeats p r hproper left right q hs hk sample.1 sample.2 + rw [hmap, ← FiniteDistribution.pushforward_comp + (directions.product (UpperScalarCutReference.referenceLaw rows repeats p r right)) + (fun sample => (sample.1, stoppedRead rows repeats p r right sample.2)) + (stoppedProjectedPair rows repeats p r hproper left right q), + product_push_right, stoppedRead_law] + +end +end PerfectCompleteness.UpperScalarCutProjection + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/UpperScalarCutReconstructionLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/UpperScalarCutReconstructionLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..3ab14f7238c62904b264e9b58fb549284b2ee86d --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/UpperScalarCutReconstructionLemmas.lean @@ -0,0 +1,494 @@ +import OAI.Computability.PerfectCompleteness.Construction.CutNodeRows +import OAI.Computability.PerfectCompleteness.Decoding.UpperScalarCutCalls +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalAgreementMean +import OAI.Computability.PerfectCompleteness.Foundations.OriginalWholeCutBridge + +namespace OAI + +section + +namespace PerfectCompleteness.UpperScalarCutReconstruction + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCutTape +open scoped Classical + +noncomputable section + +variable {branch : Nat → Nat} {n j i k t : Nat} + +theorem cutSlots_append (p : Path branch n j) (r : Path branch j i) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + cutSlots (p.append r) slots = cutSlots r (cutSlots p slots) := by + funext s a + exact congrArg (fun leaf => slots leaf a) (p.slotEmbedding_append r s) + +def cutSpaceEquiv (p : Path branch n j) (r : Path branch j i) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + H (cutSlots (p.append r) slots) ≃ H (cutSlots r (cutSlots p slots)) := + Equiv.cast (congrArg (fun s : Slots branch i → Fin t → MixedSupport.Slot => ↥(H s)) + (cutSlots_append p r slots)) + +abbrev FreshExterior (repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j i) (slots : Slots branch n → Fin t → MixedSupport.Slot) := + OriginalTerminalSplit.ExteriorTape F2 repeats r (LeafDomain (cutSlots p slots)) + +abbrev FreshValues (repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j i) (slots : Slots branch n → Fin t → MixedSupport.Slot) := + TerminalCalls.TerminalIndex repeats r → H (cutSlots (p.append r) slots) + +abbrev FreshRecord (repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j i) (slots : Slots branch n → Fin t → MixedSupport.Slot) := + FreshValues repeats p r slots × FreshExterior repeats p r slots + +def readFresh (repeats : Nat → Nat) (p : Path branch n j) (r : Path branch j i) + (suffix : Path branch i k) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (tape : RecursiveSampler.Tape F2 repeats (r.append suffix) (LeafDomain (cutSlots p slots))) : + FreshRecord repeats p r slots := + let split := OriginalTerminalSplit.splitTape F2 repeats r suffix + (LeafDomain (cutSlots p slots)) tape + (fun call => (cutSpaceEquiv p r slots).symm + (RecursiveSampler.evaluate F2 repeats suffix + (r.family (LeafDomain (cutSlots p slots))) (split.1 call)), split.2) + +def reconstructFresh (repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j i) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : FreshRecord repeats p r slots) : H (cutSlots p slots) := + OriginalScalarReconstruction.reconstruct F2 repeats r (LeafDomain (cutSlots p slots)) + (fun call => cutSpaceEquiv p r slots (record.1 call)) record.2 + +theorem reconstructFresh_readFresh (repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j i) (suffix : Path branch i k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (tape : RecursiveSampler.Tape F2 repeats (r.append suffix) (LeafDomain (cutSlots p slots))) : + reconstructFresh repeats p r slots (readFresh repeats p r suffix slots tape) = + RecursiveSampler.evaluate F2 repeats (r.append suffix) (LeafDomain (cutSlots p slots)) tape := by + simpa only [reconstructFresh, readFresh, Equiv.apply_symm_apply] using + OriginalScalarReconstruction.reconstruct_original F2 repeats r + (LeafDomain (cutSlots p slots)) suffix tape + +abbrev Exterior (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) := + OriginalWholeCutTape.Exterior rows repeats (p.append r) slots × + FreshExterior repeats p r slots + +abbrev Record (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) := + Exterior rows repeats p r slots × + CutChildGrouping.Assembled (C := UpperScalarCutCalls.Index rows repeats p r) + (cutSlots (p.append r) slots) rows + +def pack (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (old : OriginalWholeCut.Record rows repeats (p.append r) slots) + (fresh : FreshRecord repeats p r slots) : Record rows repeats p r slots := + ((old.1, fresh.2), (Sum.elim old.2.1 fresh.1, old.2.2)) + +def oldRecord (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : Record rows repeats p r slots) : + OriginalWholeCut.Record rows repeats (p.append r) slots := + (record.1.1, (fun call => record.2.1 (.inl call), record.2.2)) + +def freshRecord (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : Record rows repeats p r slots) : FreshRecord repeats p r slots := + (fun call => record.2.1 (.inr call), record.1.2) + +def packEquiv (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) : + (OriginalWholeCut.Record rows repeats (p.append r) slots × FreshRecord repeats p r slots) ≃ + Record rows repeats p r slots where + toFun z := pack rows repeats p r slots z.1 z.2 + invFun z := (oldRecord rows repeats p r slots z, freshRecord rows repeats p r slots z) + left_inv _ := rfl + right_inv z := by + apply Prod.ext + · rfl + · apply Prod.ext + · funext call + cases call <;> rfl + · rfl + +def observe (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : Record rows repeats p r slots) : + OriginalWholeCutBridge.NumberedRecord rows repeats (p.append r) slots × H (cutSlots p slots) := + (OriginalWholeCutBridge.numberRecord rows repeats (p.append r) slots + (oldRecord rows repeats p r slots record), + reconstructFresh repeats p r slots (freshRecord rows repeats p r slots record)) + +def read (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (chosen : Fin (branch i)) (q : Path branch i k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (tapes : WholeArraySampler.Tape rows repeats ((p.append r).append (.step chosen q)) slots × + RecursiveSampler.Tape F2 repeats (r.append (.step chosen q)) (LeafDomain (cutSlots p slots))) : + Record rows repeats p r slots := + pack rows repeats p r slots + (OriginalWholeCut.readRecord rows repeats (p.append r) chosen q slots tapes.1) + (readFresh repeats p r (.step chosen q) slots tapes.2) + +theorem observe_read (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (chosen : Fin (branch i)) (q : Path branch i k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (tapes : WholeArraySampler.Tape rows repeats ((p.append r).append (.step chosen q)) slots × + RecursiveSampler.Tape F2 repeats (r.append (.step chosen q)) (LeafDomain (cutSlots p slots))) : + observe rows repeats p r slots (read rows repeats p r chosen q slots tapes) = + (OriginalWholeCutBridge.numberRecord rows repeats (p.append r) slots + (OriginalWholeCut.readRecord rows repeats (p.append r) chosen q slots tapes.1), + RecursiveSampler.evaluate F2 repeats (r.append (.step chosen q)) + (LeafDomain (cutSlots p slots)) tapes.2) := by + apply Prod.ext + · rfl + · exact reconstructFresh_readFresh repeats p r (.step chosen q) slots tapes.2 + +def reconstruct (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : Record rows repeats p r slots) : Arrays slots rows × H (cutSlots p slots) := + (OriginalWholeCut.reconstructRecord rows repeats (p.append r) slots + (oldRecord rows repeats p r slots record), + reconstructFresh repeats p r slots (freshRecord rows repeats p r slots record)) + +theorem reconstruct_read (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (chosen : Fin (branch i)) (q : Path branch i k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (tapes : WholeArraySampler.Tape rows repeats ((p.append r).append (.step chosen q)) slots × + RecursiveSampler.Tape F2 repeats (r.append (.step chosen q)) (LeafDomain (cutSlots p slots))) : + reconstruct rows repeats p r slots (read rows repeats p r chosen q slots tapes) = + (WholeArraySampler.evaluate rows repeats ((p.append r).append (.step chosen q)) slots tapes.1, + RecursiveSampler.evaluate F2 repeats (r.append (.step chosen q)) + (LeafDomain (cutSlots p slots)) tapes.2) := by + apply Prod.ext + · exact OriginalWholeCut.reconstruct_original rows repeats (p.append r) chosen q slots tapes.1 + · exact reconstructFresh_readFresh repeats p r (.step chosen q) slots tapes.2 + +abbrev NumberedRecord (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) := + Exterior rows repeats p r slots × + CutChildGrouping.Assembled + (C := Fin (UpperScalarCutCalls.count rows repeats n j (i + 1))) + (cutSlots (p.append r) slots) rows + +def numberRecordEquiv (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Record rows repeats p r slots ≃ NumberedRecord rows repeats p r slots := + Equiv.prodCongr (Equiv.refl _) + (Equiv.prodCongr (Equiv.arrowCongr (UpperScalarCutCalls.numbering rows repeats p r) + (Equiv.refl _)) (Equiv.refl _)) + +def numberedObserve (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : NumberedRecord rows repeats p r slots) : + OriginalWholeCutBridge.NumberedRecord rows repeats (p.append r) slots × H (cutSlots p slots) := + observe rows repeats p r slots ((numberRecordEquiv rows repeats p r slots).symm record) + +@[simp] theorem numberedObserve_numberRecord (rows repeats : Nat → Nat) + (p : Path branch n j) (r : Path branch j (i + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) (record : Record rows repeats p r slots) : + numberedObserve rows repeats p r slots (numberRecordEquiv rows repeats p r slots record) = + observe rows repeats p r slots record := by + simp only [numberedObserve, Equiv.symm_apply_apply] + +end +end PerfectCompleteness.UpperScalarCutReconstruction + +end + +section + +namespace PerfectCompleteness.UpperScalarCutBucket + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCutTape WholeArrayInteriorExterior +open scoped Classical + +noncomputable section + +variable {branch : Nat → Nat} {n j i k t : Nat} + +def descendRecord (rows repeats : Nat → Nat) : + {n j i : Nat} → (p : Path branch n j) → (r : Path branch j (i + 1)) → + (slots : Slots branch n → Fin t → MixedSupport.Slot) → + OriginalWholeCut.Record rows repeats (p.append r) slots → + OriginalWholeCut.Record rows repeats r (cutSlots p slots) + | _, _, _, .refl _, _, _, record => record + | _, _, _, .step child p, r, slots, record => + descendRecord rows repeats p r (childSlots slots child) + (record.1.2.1, (fun call => record.2.1 (.inr call), record.2.2)) + +theorem restrictArrays_reconstruct (rows repeats : Nat → Nat) (p : Path branch n j) : + ∀ (r : Path branch j (i + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : OriginalWholeCut.Record rows repeats (p.append r) slots), + WholeArraySubtreeSplit.restrictArrays rows p slots + (OriginalWholeCut.reconstructRecord rows repeats (p.append r) slots record) = + OriginalWholeCut.reconstructRecord rows repeats r (cutSlots p slots) + (descendRecord rows repeats p r slots record) := by + induction p with + | refl n => + intro r slots record + cases r <;> rfl + | step child p ih => + intro r slots record + let lower : OriginalWholeCut.Record rows repeats (p.append r) + (childSlots slots child) := + (record.1.2.1, (fun call => record.2.1 (.inr call), record.2.2)) + have hselected : + (fun node => OriginalWholeCut.reconstructRecord rows repeats + ((Path.step child p).append r) slots record (.inr (child, node))) = + OriginalWholeCut.reconstructRecord rows repeats (p.append r) + (childSlots slots child) lower := by + funext node + exact congrFun (WholeArraySampler.childrenAt_selected slots rows child + (OriginalWholeCut.reconstructRecord rows repeats (p.append r) + (childSlots slots child) lower) record.1.2.2) node + exact (congrArg (WholeArraySubtreeSplit.restrictArrays rows p + (childSlots slots child)) hselected).trans (ih r (childSlots slots child) lower) + +def rootBuckets (rows repeats : Nat → Nat) : + {j i : Nat} → (r : Path branch (j + 1) (i + 1)) → + (slots : Slots branch (j + 1) → Fin t → MixedSupport.Slot) → + OriginalWholeCut.Record rows repeats r slots → + BucketSampler.Tape (rows (j + 1)) (H slots) + | _, _, .refl _, _, record => record.2.1 + | _, _, .step child r, slots, record => fun direction => + OriginalScalarReconstruction.reconstruct F2 repeats (.step child r) (LeafDomain slots) + (fun terminal => record.2.1 (.inl (direction, terminal))) (record.1.1 direction) + +theorem rootRows_reconstruct (rows repeats : Nat → Nat) + (r : Path branch (j + 1) (i + 1)) + (slots : Slots branch (j + 1) → Fin t → MixedSupport.Slot) + (record : OriginalWholeCut.Record rows repeats r slots) : + OriginalWholeCut.reconstructRecord rows repeats r slots record (.inl ()) = + BucketSampler.evaluate (rows (j + 1)) (id : H slots → H slots) + (rootBuckets rows repeats r slots record) := by + cases r <;> rfl + +def upperBuckets (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : OriginalWholeCut.Record rows repeats (p.append r) slots) : + BucketSampler.Tape (rows (j + 1)) (H (cutSlots p slots)) := + rootBuckets rows repeats r (cutSlots p slots) (descendRecord rows repeats p r slots record) + +theorem selectedRows_reconstruct (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : OriginalWholeCut.Record rows repeats (p.append r) slots) : + SelectedArrayReplacement.selectedRows rows p slots + (OriginalWholeCut.reconstructRecord rows repeats (p.append r) slots record) = + BucketSampler.evaluate (rows (j + 1)) (id : H (cutSlots p slots) → _) + (upperBuckets rows repeats p r slots record) := by + unfold SelectedArrayReplacement.selectedRows + rw [restrictArrays_reconstruct] + exact rootRows_reconstruct rows repeats r (cutSlots p slots) _ + +def descendTape (rows repeats : Nat → Nat) : + {n j i k : Nat} → (p : Path branch n j) → (r : Path branch j (i + 1)) → + (chosen : Fin (branch i)) → (q : Path branch i k) → + (slots : Slots branch n → Fin t → MixedSupport.Slot) → + WholeArraySampler.Tape rows repeats ((p.append r).append (.step chosen q)) slots → + WholeArraySampler.Tape rows repeats (r.append (.step chosen q)) (cutSlots p slots) + | _, _, _, _, .refl _, _, _, _, _, tape => tape + | _, _, _, _, .step child p, r, chosen, q, slots, tape => + descendTape rows repeats p r chosen q (childSlots slots child) + (tape (.inr (.inl ()))) + +theorem descendRecord_readRecord (rows repeats : Nat → Nat) (p : Path branch n j) : + ∀ (r : Path branch j (i + 1)) (chosen : Fin (branch i)) (q : Path branch i k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (tape : WholeArraySampler.Tape rows repeats ((p.append r).append (.step chosen q)) slots), + descendRecord rows repeats p r slots + (OriginalWholeCut.readRecord rows repeats (p.append r) chosen q slots tape) = + OriginalWholeCut.readRecord rows repeats r chosen q (cutSlots p slots) + (descendTape rows repeats p r chosen q slots tape) := by + induction p with + | refl n => + intro r chosen q slots tape + cases r <;> rfl + | step child p ih => + intro r chosen q slots tape + exact ih r chosen q (childSlots slots child) (tape (.inr (.inl ()))) + +def continuedRootTape (rows repeats : Nat → Nat) : + {j i k : Nat} → (r : Path branch (j + 1) (i + 1)) → + (chosen : Fin (branch i)) → (q : Path branch i k) → + (slots : Slots branch (j + 1) → Fin t → MixedSupport.Slot) → + WholeArraySampler.Tape rows repeats (r.append (.step chosen q)) slots → + WholeArraySampler.RootTape rows repeats (r.append (.step chosen q)) slots + | _, _, _, .refl _, _, _, _, tape => tape (.inl ()) + | _, _, _, .step _ _, _, _, _, tape => tape (.inl ()) + +theorem rootBuckets_readRecord (rows repeats : Nat → Nat) + (r : Path branch (j + 1) (i + 1)) (chosen : Fin (branch i)) (q : Path branch i k) + (slots : Slots branch (j + 1) → Fin t → MixedSupport.Slot) + (tape : WholeArraySampler.Tape rows repeats (r.append (.step chosen q)) slots) : + rootBuckets rows repeats r slots (OriginalWholeCut.readRecord rows repeats r chosen q slots tape) = + fun direction => RecursiveSampler.evaluate F2 repeats (r.append (.step chosen q)) + (LeafDomain slots) (continuedRootTape rows repeats r chosen q slots tape direction) := by + cases r with + | refl => rfl + | step child r => + funext direction + exact OriginalScalarReconstruction.reconstruct_original F2 repeats (.step child r) + (LeafDomain slots) (.step chosen q) (tape (.inl ()) direction) + +theorem upperBuckets_readRecord (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) (chosen : Fin (branch i)) (q : Path branch i k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (tape : WholeArraySampler.Tape rows repeats ((p.append r).append (.step chosen q)) slots) : + upperBuckets rows repeats p r slots + (OriginalWholeCut.readRecord rows repeats (p.append r) chosen q slots tape) = + fun direction => RecursiveSampler.evaluate F2 repeats (r.append (.step chosen q)) + (LeafDomain (cutSlots p slots)) + (continuedRootTape rows repeats r chosen q (cutSlots p slots) + (descendTape rows repeats p r chosen q slots tape) direction) := by + unfold upperBuckets + rw [descendRecord_readRecord, rootBuckets_readRecord] + +def replaceArrays (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : OriginalWholeCut.Record rows repeats (p.append r) slots) + (a : BucketSampler.Direction (rows (j + 1))) (fresh : H (cutSlots p slots)) : + Arrays slots rows := + SelectedArrayReplacement.replace rows p slots + (OriginalWholeCut.reconstructRecord rows repeats (p.append r) slots record) + (BucketSampler.evaluate (rows (j + 1)) (id : H (cutSlots p slots) → _) + (Function.update (upperBuckets rows repeats p r slots record) a fresh)) + +theorem replaceArrays_rankOne (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : OriginalWholeCut.Record rows repeats (p.append r) slots) + (a : BucketSampler.Direction (rows (j + 1))) (fresh : H (cutSlots p slots)) : + replaceArrays rows repeats p r slots record a fresh = + SelectedArrayReplacement.replace rows p slots + (OriginalWholeCut.reconstructRecord rows repeats (p.append r) slots record) + (SelectedArrayReplacement.selectedRows rows p slots + (OriginalWholeCut.reconstructRecord rows repeats (p.append r) slots record) + + BucketSampler.rankOne a.val (fresh - upperBuckets rows repeats p r slots record a)) := by + unfold replaceArrays + rw [BucketSampler.evaluate_update, selectedRows_reconstruct] + simp only [id_eq] + +theorem replaceArrays_outside (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : OriginalWholeCut.Record rows repeats (p.append r) slots) + (a : BucketSampler.Direction (rows (j + 1))) (fresh : H (cutSlots p slots)) + (node : Nodes branch n) (hnode : node ≠ upperNode p) : + replaceArrays rows repeats p r slots record a fresh node = + OriginalWholeCut.reconstructRecord rows repeats (p.append r) slots record node := + SelectedArrayReplacement.replace_outside rows p slots _ _ node hnode + +theorem matrix_reconstruct (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : OriginalWholeCut.Record rows repeats (p.append r) slots) : + NodeEmbedding.matrix (OriginalWholeCut.reconstructRecord rows repeats (p.append r) slots record) + (upperNode p) = + BucketMatrixResampling.assembledMatrix (NodeEmbedding.RowSpace slots (upperNode p)) + (rows (Nodes.height (upperNode p))) + (CutNodeRows.bucketTapeEquiv rows p slots (upperBuckets rows repeats p r slots record)) := by + rw [← CutNodeRows.matrixOfRows_selectedRows, selectedRows_reconstruct] + exact CutNodeRows.matrixOfRows_evaluate rows p slots _ + +theorem matrix_replaceArrays (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : OriginalWholeCut.Record rows repeats (p.append r) slots) + (a : BucketSampler.Direction (rows (j + 1))) (fresh : H (cutSlots p slots)) : + NodeEmbedding.matrix (replaceArrays rows repeats p r slots record a fresh) (upperNode p) = + BucketMatrixResampling.assembledMatrix (NodeEmbedding.RowSpace slots (upperNode p)) + (rows (Nodes.height (upperNode p))) + (Function.update + (CutNodeRows.bucketTapeEquiv rows p slots (upperBuckets rows repeats p r slots record)) + (CutNodeRows.directionEquiv rows p a) (CutNodeRows.cutRowEquiv p slots fresh)) := by + rw [← CutNodeRows.matrixOfRows_selectedRows] + unfold replaceArrays + rw [SelectedArrayReplacement.selectedRows_replace, CutNodeRows.matrixOfRows_evaluate, + CutNodeRows.bucketTapeEquiv_update] + +def pairRecord (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : OriginalWholeCut.Record rows repeats (p.append r) slots) + (a : BucketSampler.Direction (rows (j + 1))) (fresh : H (cutSlots p slots)) : + HierarchicalAgreementMean.PairRecord (rows := rows) slots (upperNode p) := + (HierarchicalMatrixTable.backgroundOf slots (upperNode p) + (OriginalWholeCut.reconstructRecord rows repeats (p.append r) slots record), + (NodeEmbedding.matrix (OriginalWholeCut.reconstructRecord rows repeats (p.append r) slots record) + (upperNode p), + NodeEmbedding.matrix (replaceArrays rows repeats p r slots record a fresh) (upperNode p))) + +theorem pairRecord_eq (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : OriginalWholeCut.Record rows repeats (p.append r) slots) + (a : BucketSampler.Direction (rows (j + 1))) (fresh : H (cutSlots p slots)) : + pairRecord rows repeats p r slots record a fresh = + HierarchicalAgreementMean.pairRecord slots (upperNode p) + (HierarchicalMatrixTable.backgroundOf slots (upperNode p) + (OriginalWholeCut.reconstructRecord rows repeats (p.append r) slots record), + CutNodeRows.bucketSampleEquiv rows p slots + (a, (upperBuckets rows repeats p r slots record, fresh))) := by + apply Prod.ext + · rfl + · apply Prod.ext + · exact matrix_reconstruct rows repeats p r slots record + · exact matrix_replaceArrays rows repeats p r slots record a fresh + +def enlargedPairRecord (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (sample : BucketSampler.Direction (rows (j + 1)) × + UpperScalarCutReconstruction.Record rows repeats p r slots) : + HierarchicalAgreementMean.PairRecord (rows := rows) slots (upperNode p) := + pairRecord rows repeats p r slots + (UpperScalarCutReconstruction.oldRecord rows repeats p r slots sample.2) sample.1 + (UpperScalarCutReconstruction.reconstructFresh repeats p r slots + (UpperScalarCutReconstruction.freshRecord rows repeats p r slots sample.2)) + +theorem enlargedPairRecord_read (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) (chosen : Fin (branch i)) (q : Path branch i k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (a : BucketSampler.Direction (rows (j + 1))) + (tapes : WholeArraySampler.Tape rows repeats ((p.append r).append (.step chosen q)) slots × + RecursiveSampler.Tape F2 repeats (r.append (.step chosen q)) (LeafDomain (cutSlots p slots))) : + enlargedPairRecord rows repeats p r slots + (a, UpperScalarCutReconstruction.read rows repeats p r chosen q slots tapes) = + pairRecord rows repeats p r slots + (OriginalWholeCut.readRecord rows repeats (p.append r) chosen q slots tapes.1) a + (RecursiveSampler.evaluate F2 repeats (r.append (.step chosen q)) + (LeafDomain (cutSlots p slots)) tapes.2) := by + change pairRecord rows repeats p r slots + (OriginalWholeCut.readRecord rows repeats (p.append r) chosen q slots tapes.1) a + (UpperScalarCutReconstruction.reconstructFresh repeats p r slots + (UpperScalarCutReconstruction.readFresh repeats p r (.step chosen q) slots tapes.2)) = _ + rw [UpperScalarCutReconstruction.reconstructFresh_readFresh] + +def numberedPairRecord (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (sample : BucketSampler.Direction (rows (j + 1)) × + UpperScalarCutReconstruction.NumberedRecord rows repeats p r slots) : + HierarchicalAgreementMean.PairRecord (rows := rows) slots (upperNode p) := + enlargedPairRecord rows repeats p r slots + (sample.1, (UpperScalarCutReconstruction.numberRecordEquiv rows repeats p r slots).symm sample.2) + +@[simp] theorem numberedPairRecord_numberRecord (rows repeats : Nat → Nat) + (p : Path branch n (j + 1)) (r : Path branch (j + 1) (i + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (a : BucketSampler.Direction (rows (j + 1))) + (record : UpperScalarCutReconstruction.Record rows repeats p r slots) : + numberedPairRecord rows repeats p r slots + (a, UpperScalarCutReconstruction.numberRecordEquiv rows repeats p r slots record) = + enlargedPairRecord rows repeats p r slots (a, record) := by + simp only [numberedPairRecord, Equiv.symm_apply_apply] + +end +end PerfectCompleteness.UpperScalarCutBucket + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/UpperScalarCutReference.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/UpperScalarCutReference.lean new file mode 100644 index 0000000000000000000000000000000000000000..6675fc62018d247e2b4b27d2633cf198f59eb3a2 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/UpperScalarCutReference.lean @@ -0,0 +1,183 @@ +import OAI.Computability.PerfectCompleteness.Decoding.UpperScalarCutLaw +import OAI.Computability.PerfectCompleteness.Sampling.NumberedUniformCut + +namespace OAI + +section + +namespace PerfectCompleteness.UpperScalarCutReference + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCutTape UpperScalarCutReconstruction +open UniqueGamesTheorem.Foundations.Games +open scoped Classical + +noncomputable section + +private theorem uniform_equiv {A B : Type*} [Fintype A] [Fintype B] + [Nonempty A] [Nonempty B] (e : A ≃ B) : + (FiniteDistribution.uniform A).pushforward e = FiniteDistribution.uniform B := by + rw [← FiniteDistribution.transport_eq_pushforward] + exact UniformConditioning.uniform_transport e + +variable {branch : Nat → Nat} {n j i t : Nat} + +def freshReferenceLaw (repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j i) (slots : Slots branch n → Fin t → MixedSupport.Slot) : + FiniteDistribution (FreshRecord repeats p r slots) := + (FiniteDistribution.uniform (FreshValues repeats p r slots)).product + (UpperScalarCutLaw.freshExteriorLaw repeats p r slots) + +theorem freshReferenceLaw_uniform (repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j i) (slots : Slots branch n → Fin t → MixedSupport.Slot) : + freshReferenceLaw repeats p r slots = + FiniteDistribution.uniform (FreshRecord repeats p r slots) := by + unfold freshReferenceLaw UpperScalarCutLaw.freshExteriorLaw + rw [OriginalTerminalSplit.exteriorLaw_uniform, WholeCutSampler.uniform_product] + +def freshStoppedTapeEquiv (repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j i) (slots : Slots branch n → Fin t → MixedSupport.Slot) : + FreshRecord repeats p r slots ≃ + RecursiveSampler.Tape F2 repeats r (LeafDomain (cutSlots p slots)) := + (Equiv.prodCongr + (Equiv.arrowCongr (Equiv.refl (TerminalCalls.TerminalIndex repeats r)) + (cutSpaceEquiv p r slots)) + (Equiv.refl (FreshExterior repeats p r slots))).trans + (OriginalScalarReconstruction.prefixSplit F2 repeats r + (LeafDomain (cutSlots p slots))).symm + +theorem freshStoppedTape_law (repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j i) (slots : Slots branch n → Fin t → MixedSupport.Slot) : + (freshReferenceLaw repeats p r slots).pushforward + (freshStoppedTapeEquiv repeats p r slots) = + RecursiveSampler.tapeLaw F2 repeats r (LeafDomain (cutSlots p slots)) := by + rw [freshReferenceLaw_uniform, RecursiveSampler.tapeLaw_eq_uniform] + exact uniform_equiv (freshStoppedTapeEquiv repeats p r slots) + +theorem reconstructFresh_referenceLaw (repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j i) (slots : Slots branch n → Fin t → MixedSupport.Slot) : + (freshReferenceLaw repeats p r slots).pushforward (reconstructFresh repeats p r slots) = + RecursiveSampler.law F2 repeats r (LeafDomain (cutSlots p slots)) := by + change (freshReferenceLaw repeats p r slots).pushforward + (fun record => RecursiveSampler.evaluate F2 repeats r (LeafDomain (cutSlots p slots)) + (freshStoppedTapeEquiv repeats p r slots record)) = + (RecursiveSampler.tapeLaw F2 repeats r (LeafDomain (cutSlots p slots))).pushforward + (RecursiveSampler.evaluate F2 repeats r (LeafDomain (cutSlots p slots))) + rw [← FiniteDistribution.pushforward_comp, freshStoppedTape_law] + +theorem exteriorLaw_uniform (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) : + UpperScalarCutLaw.exteriorLaw rows repeats p r slots = + FiniteDistribution.uniform (UpperScalarCutReconstruction.Exterior rows repeats p r slots) := by + unfold UpperScalarCutLaw.exteriorLaw UpperScalarCutLaw.freshExteriorLaw + OriginalWholeCutTape.exteriorLaw + rw [OriginalTerminalSplit.exteriorLaw_uniform, WholeCutSampler.uniform_product] + +def referenceLaw (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) : + FiniteDistribution (UpperScalarCutReconstruction.Record rows repeats p r slots) := + (UpperScalarCutLaw.exteriorLaw rows repeats p r slots).product + (FiniteDistribution.uniform (CutChildGrouping.Assembled + (C := UpperScalarCutCalls.Index rows repeats p r) (cutSlots (p.append r) slots) rows)) + +theorem referenceLaw_uniform (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) : + referenceLaw rows repeats p r slots = + FiniteDistribution.uniform (UpperScalarCutReconstruction.Record rows repeats p r slots) := by + rw [referenceLaw, exteriorLaw_uniform, WholeCutSampler.uniform_product] + +def numberedReferenceLaw (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) : + FiniteDistribution (UpperScalarCutReconstruction.NumberedRecord rows repeats p r slots) := + (UpperScalarCutLaw.exteriorLaw rows repeats p r slots).product + (FiniteDistribution.uniform (CutChildGrouping.Assembled + (C := Fin (UpperScalarCutCalls.count rows repeats n j (i + 1))) + (cutSlots (p.append r) slots) rows)) + +theorem numberedReferenceLaw_uniform (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) : + numberedReferenceLaw rows repeats p r slots = + FiniteDistribution.uniform (UpperScalarCutReconstruction.NumberedRecord rows repeats p r slots) := by + rw [numberedReferenceLaw, exteriorLaw_uniform, WholeCutSampler.uniform_product] + +theorem numberRecord_referenceLaw (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) : + (referenceLaw rows repeats p r slots).pushforward (numberRecordEquiv rows repeats p r slots) = + numberedReferenceLaw rows repeats p r slots := by + rw [referenceLaw_uniform, numberedReferenceLaw_uniform] + exact uniform_equiv (numberRecordEquiv rows repeats p r slots) + +attribute [local instance 2000] OriginalWholeCutLaw.valuesBelowFintype + +theorem pack_referenceLaw (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) : + ((OriginalUniformCut.referenceLaw rows repeats (p.append r) slots).product + (freshReferenceLaw repeats p r slots)).pushforward (packEquiv rows repeats p r slots) = + referenceLaw rows repeats p r slots := by + rw [OriginalUniformCut.referenceLaw_uniform, freshReferenceLaw_uniform, + WholeCutSampler.uniform_product, referenceLaw_uniform] + exact uniform_equiv (packEquiv rows repeats p r slots) + +private theorem reference_pair_map {A B : Type*} [Fintype A] [Fintype B] + (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (f : OriginalWholeCut.Record rows repeats (p.append r) slots → A) + (g : FreshRecord repeats p r slots → B) : + (referenceLaw rows repeats p r slots).pushforward + (fun record => (f (oldRecord rows repeats p r slots record), + g (freshRecord rows repeats p r slots record))) = + ((OriginalUniformCut.referenceLaw rows repeats (p.append r) slots).pushforward f).product + ((freshReferenceLaw repeats p r slots).pushforward g) := by + rw [← pack_referenceLaw rows repeats p r slots, FiniteDistribution.pushforward_comp] + change ((OriginalUniformCut.referenceLaw rows repeats (p.append r) slots).product + (freshReferenceLaw repeats p r slots)).pushforward (fun z => (f z.1, g z.2)) = _ + exact FiniteDistribution.product_pushforward _ _ f g + +theorem observe_referenceLaw (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) : + (referenceLaw rows repeats p r slots).pushforward (observe rows repeats p r slots) = + ((OriginalUniformCut.referenceLaw rows repeats (p.append r) slots).pushforward + (OriginalWholeCutBridge.numberRecord rows repeats (p.append r) slots)).product + (RecursiveSampler.law F2 repeats r (LeafDomain (cutSlots p slots))) := by + change (referenceLaw rows repeats p r slots).pushforward + (fun record => + (OriginalWholeCutBridge.numberRecord rows repeats (p.append r) slots + (oldRecord rows repeats p r slots record), + reconstructFresh repeats p r slots (freshRecord rows repeats p r slots record))) = _ + rw [reference_pair_map, reconstructFresh_referenceLaw] + +theorem reconstruct_referenceLaw (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) : + (referenceLaw rows repeats p r slots).pushforward + (UpperScalarCutReconstruction.reconstruct rows repeats p r slots) = + (WholeArraySampler.law rows repeats (p.append r) slots).product + (RecursiveSampler.law F2 repeats r (LeafDomain (cutSlots p slots))) := by + change (referenceLaw rows repeats p r slots).pushforward + (fun record => + (OriginalWholeCut.reconstructRecord rows repeats (p.append r) slots + (oldRecord rows repeats p r slots record), + reconstructFresh repeats p r slots (freshRecord rows repeats p r slots record))) = _ + rw [reference_pair_map, OriginalUniformCut.reconstruct_referenceLaw, + reconstructFresh_referenceLaw] + +theorem numberedObserve_referenceLaw (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) : + (numberedReferenceLaw rows repeats p r slots).pushforward + (numberedObserve rows repeats p r slots) = + ((OriginalUniformCut.referenceLaw rows repeats (p.append r) slots).pushforward + (OriginalWholeCutBridge.numberRecord rows repeats (p.append r) slots)).product + (RecursiveSampler.law F2 repeats r (LeafDomain (cutSlots p slots))) := by + rw [← numberRecord_referenceLaw rows repeats p r slots, FiniteDistribution.pushforward_comp] + have hmap : (fun record : UpperScalarCutReconstruction.Record rows repeats p r slots => + numberedObserve rows repeats p r slots (numberRecordEquiv rows repeats p r slots record)) = + observe rows repeats p r slots := + funext (numberedObserve_numberRecord rows repeats p r slots) + rw [hmap] + exact observe_referenceLaw rows repeats p r slots + +end +end PerfectCompleteness.UpperScalarCutReference + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/UpperScalarFreshProjectionLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/UpperScalarFreshProjectionLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..88cb3424229e36ae1b3587e043b56cdaa99dca30 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/UpperScalarFreshProjectionLemmas.lean @@ -0,0 +1,313 @@ +import OAI.Computability.PerfectCompleteness.Decoding.CutGroupedProjectionLemmas +import OAI.Computability.PerfectCompleteness.Decoding.UpperScalarCutLaw +import OAI.Computability.PerfectCompleteness.Decoding.UpperScalarCutReconstructionLemmas +import OAI.Computability.PerfectCompleteness.Foundations.ProjectedPrefixComparison +import OAI.Computability.PerfectCompleteness.Sampling.OriginalUniformCut + +namespace OAI + +section + +namespace PerfectCompleteness.UpperScalarFreshProjection + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCutTape UpperScalarCutReconstruction +open UniqueGamesTheorem.Foundations.Games +open scoped Classical + +noncomputable section + +variable {branch : Nat → Nat} {n j i t : Nat} + +theorem outside_append (p : Path branch n j) (r : Path branch j i) + (s : Slots branch j) (hs : WholeCutExteriorTransport.Outside r s) : + WholeCutExteriorTransport.Outside (p.append r) (p.slotEmbedding s) := by + rintro ⟨u, hu⟩ + apply hs + refine ⟨u, p.slotEmbedding_injective ?_⟩ + exact (p.slotEmbedding_append r u).symm.trans hu + +theorem restricted_outside_eq (p : Path branch n j) (r : Path branch j i) + (left right : Slots branch n → Fin t → MixedSupport.Slot) + (hs : ∀ s, WholeCutExteriorTransport.Outside (p.append r) s → left s = right s) : + ∀ s, WholeCutExteriorTransport.Outside r s → cutSlots p left s = cutSlots p right s := + fun s h => hs (p.slotEmbedding s) (outside_append p r s h) + +theorem restricted_keep (p : Path branch n j) (r : Path branch j i) + (left right : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s a, MixedSupport.Projection (left s a) (right s a)) + (hk : ∀ s, WholeCutExteriorTransport.Outside (p.append r) s → ∀ a, + HEq (q s a) (MixedSupport.Projection.keep (left s a))) : + ∀ s, WholeCutExteriorTransport.Outside r s → ∀ a, + HEq (q (p.slotEmbedding s) a) (MixedSupport.Projection.keep (cutSlots p left s a)) := + fun s h a => hk (p.slotEmbedding s) (outside_append p r s h) a + +def freshExteriorEquiv (repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) + (left right : Slots branch n → Fin t → MixedSupport.Slot) + (hs : ∀ s, WholeCutExteriorTransport.Outside (p.append r) s → left s = right s) : + FreshExterior repeats p r right ≃ FreshExterior repeats p r left := + Equiv.cast (OriginalScalarProjection.scalarExterior_eq repeats r + (cutSlots p right) (cutSlots p left) + (fun s h => (restricted_outside_eq p r left right hs s h).symm)) + +theorem freshExteriorEquiv_law (repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j (i + 1)) + (left right : Slots branch n → Fin t → MixedSupport.Slot) + (hs : ∀ s, WholeCutExteriorTransport.Outside (p.append r) s → left s = right s) : + (UpperScalarCutLaw.freshExteriorLaw repeats p r right).pushforward + (freshExteriorEquiv repeats p r left right hs) = + UpperScalarCutLaw.freshExteriorLaw repeats p r left := by + simp only [UpperScalarCutLaw.freshExteriorLaw, OriginalTerminalSplit.exteriorLaw_uniform] + rw [← FiniteDistribution.transport_eq_pushforward] + exact UniformConditioning.uniform_transport (freshExteriorEquiv repeats p r left right hs) + +theorem cutSpaceEquiv_HPullback (p : Path branch n j) : + ∀ (r : Path branch j (i + 1)) + (left right : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s a, MixedSupport.Projection (left s a) (right s a)) + (f : H (cutSlots (p.append r) right)), + cutSpaceEquiv p r left + (HPullback (CutGroupedProjection.cutProjection (p.append r) q) f) = + HPullback (CutGroupedProjection.cutProjection r (fun s a => q (p.slotEmbedding s) a)) + (cutSpaceEquiv p r right f) := by + induction p with + | refl j => intro r left right q f; rfl + | step child p ih => + intro r left right q f + exact ih r (childSlots left child) (childSlots right child) + (ChildAssemblyProjection.childProjection q child) f + +theorem reconstructFresh_pullback (repeats : Nat → Nat) + (p : Path branch n (j + 1)) (r : Path branch (j + 1) (i + 1)) + (left right : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s a, MixedSupport.Projection (left s a) (right s a)) + (hs : ∀ s, WholeCutExteriorTransport.Outside (p.append r) s → left s = right s) + (hk : ∀ s, WholeCutExteriorTransport.Outside (p.append r) s → ∀ a, + HEq (q s a) (MixedSupport.Projection.keep (left s a))) + (values : FreshValues repeats p r right) (exterior : FreshExterior repeats p r right) : + reconstructFresh repeats p r left + (fun call => HPullback (CutGroupedProjection.cutProjection (p.append r) q) (values call), + freshExteriorEquiv repeats p r left right hs exterior) = + HPullback (CutGroupedProjection.cutProjection p q) + (reconstructFresh repeats p r right (values, exterior)) := by + have hvalues : + (fun call : TerminalCalls.TerminalIndex repeats r => + cutSpaceEquiv p r left + (HPullback (CutGroupedProjection.cutProjection (p.append r) q) (values call))) = + (fun call => HPullback + (CutGroupedProjection.cutProjection r (CutGroupedProjection.cutProjection p q)) + (cutSpaceEquiv p r right (values call))) := by + funext call + exact cutSpaceEquiv_HPullback p r left right q (values call) + unfold reconstructFresh + rw [hvalues] + exact OriginalScalarProjection.reconstruct_pullback repeats r + (cutSlots p left) (cutSlots p right) (CutGroupedProjection.cutProjection p q) + (restricted_outside_eq p r left right hs) (restricted_keep p r left right q hk) + (fun call => cutSpaceEquiv p r right (values call)) exterior + +end +end PerfectCompleteness.UpperScalarFreshProjection + +end + +section + +namespace PerfectCompleteness.UpperScalarPairComparison + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCutTape WholeArrayInteriorExterior +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) +open scoped Classical + +noncomputable section + +attribute [local instance] linearMapFintype + +variable {branch : Nat → Nat} {n j i k t : Nat} {K : Type*} [Fintype K] + +local instance backgroundFintype (rows : Nat → Nat) (p : Path branch n (j + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Fintype (HierarchicalMatrixTable.Background (rows := rows) slots (upperNode p)) := + Fintype.ofFinite _ + +local instance rowSpaceFintype (p : Path branch n (j + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Fintype (NodeEmbedding.RowSpace slots (upperNode p)) := Fintype.ofFinite _ + +def pairLaw (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (directions : FiniteDistribution (BucketSampler.Direction (rows (j + 1)))) + (assembled : FiniteDistribution (CutChildGrouping.Assembled + (C := Fin (UpperScalarCutCalls.count rows repeats n (j + 1) (i + 1))) + (cutSlots (p.append r) slots) rows)) : + FiniteDistribution (HierarchicalAgreementMean.PairRecord (rows := rows) slots (upperNode p)) := + (directions.product ((UpperScalarCutLaw.exteriorLaw rows repeats p r slots).product + assembled)).pushforward (UpperScalarCutBucket.numberedPairRecord rows repeats p r slots) + +theorem variation_le (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (directions : FiniteDistribution (BucketSampler.Direction (rows (j + 1)))) + (P Q : FiniteDistribution (CutChildGrouping.Assembled + (C := Fin (UpperScalarCutCalls.count rows repeats n (j + 1) (i + 1))) + (cutSlots (p.append r) slots) rows)) : + (pairLaw rows repeats p r slots directions P).totalVariation + (pairLaw rows repeats p r slots directions Q) ≤ P.totalVariation Q := by + have h := CommonProductVariation.observed_product_le directions + ((UpperScalarCutLaw.exteriorLaw rows repeats p r slots).product P) + ((UpperScalarCutLaw.exteriorLaw rows repeats p r slots).product Q) + (UpperScalarCutBucket.numberedPairRecord rows repeats p r slots) + simpa only [pairLaw, CommonProductVariation.product_totalVariation] using h + +variable {Z : Fin (branch i) → Type*} [∀ c, Fintype (Z c)] + +theorem modified_original_variation (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (projected : (c : Fin (branch i)) → Z c → Slots branch i → Fin t → MixedSupport.Slot) + (projection : ∀ c z s a, MixedSupport.Projection + (childSlots (cutSlots (p.append r) slots) c s a) (projected c z s a)) + (choiceLaw : (c : Fin (branch i)) → FiniteDistribution (Z c)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) + (ν : FiniteDistribution K) (q : K → Path branch i k) (hbranch : 0 < branch i) + (directions : FiniteDistribution (BucketSampler.Direction (rows (j + 1)))) : + (pairLaw rows repeats p r slots directions + (ProjectedPrefixComparison.assembledLaw + (UpperScalarCutCalls.count rows repeats n (j + 1) (i + 1)) rows + (cutSlots (p.append r) slots) projected projection choiceLaw β hβ hβ')).totalVariation + (pairLaw rows repeats p r slots directions + (OriginalPrefixContinuation.assembledLaw + (UpperScalarCutCalls.count rows repeats n (j + 1) (i + 1)) rows repeats + (cutSlots (p.append r) slots) ν q hbranch)) ≤ + Real.sqrt ((1 + β ^ 2 * ((ChildBlockCardinality.bound branch i t + (UpperScalarCutCalls.count rows repeats n (j + 1) (i + 1)) rows : ℝ) - 1)) ^ branch i - 1) / 2 + + Real.sqrt ((ChildBlockCardinality.bound branch i t + (UpperScalarCutCalls.count rows repeats n (j + 1) (i + 1)) rows : ℝ) ^ 2 / branch i) / 2 := + (variation_le rows repeats p r slots directions _ _).trans + (ProjectedPrefixComparison.original_variation + (UpperScalarCutCalls.count rows repeats n (j + 1) (i + 1)) rows repeats + (cutSlots (p.append r) slots) projected projection choiceLaw β hβ hβ' ν q hbranch) + +end +end PerfectCompleteness.UpperScalarPairComparison + +end + +section + +namespace PerfectCompleteness.UpperStoppedBuckets + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCut OriginalWholeCutTape +open UniqueGamesTheorem.Foundations.Games + +abbrev F2 := ZMod 2 + +attribute [local instance 2000] OriginalUniformCutBase.valuesChildrenFintype + +variable {branch : Nat → Nat} {n j i t : Nat} + +def stoppedRootBuckets (rows repeats : Nat → Nat) : + {j i : Nat} → (r : Path branch (j + 1) (i + 1)) → i + 1 < j + 1 → + (slots : Slots branch (j + 1) → Fin t → MixedSupport.Slot) → + WholeArraySampler.Tape rows repeats r slots → + BucketSampler.Tape (rows (j + 1)) (H slots) + | _, _, .refl _, hproper, _, _, _ => False.elim ((Nat.lt_irrefl _) hproper) + | _, _, .step child r, _, slots, tape, direction => + RecursiveSampler.evaluate F2 repeats (.step child r) (LeafDomain slots) + (tape (.inl ()) direction) + +def stoppedBuckets (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) (hproper : i + 1 < j + 1) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (tape : WholeArraySampler.Tape rows repeats (p.append r) slots) : + BucketSampler.Tape (rows (j + 1)) (H (cutSlots p slots)) := + stoppedRootBuckets rows repeats r hproper (cutSlots p slots) + (WholeArraySubtreeSplit.extract rows repeats p r slots tape) + +theorem extract_toStoppedTape (rows repeats : Nat → Nat) (p : Path branch n j) : + ∀ (r : Path branch j (i + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : Record rows repeats (p.append r) slots), + WholeArraySubtreeSplit.extract rows repeats p r slots + (OriginalUniformCut.toStoppedTape rows repeats (p.append r) slots record) = + OriginalUniformCut.toStoppedTape rows repeats r (cutSlots p slots) + (UpperScalarCutBucket.descendRecord rows repeats p r slots record) := by + induction p with + | refl n => + intro r slots record + cases r <;> rfl + | step child p ih => + intro r slots record + exact ih r (childSlots slots child) + (record.1.2.1, (fun call => record.2.1 (.inr call), record.2.2)) + +theorem rootBuckets_toStoppedTape (rows repeats : Nat → Nat) + (r : Path branch (j + 1) (i + 1)) (hproper : i + 1 < j + 1) + (slots : Slots branch (j + 1) → Fin t → MixedSupport.Slot) + (record : Record rows repeats r slots) : + UpperScalarCutBucket.rootBuckets rows repeats r slots record = + stoppedRootBuckets rows repeats r hproper slots + (OriginalUniformCut.toStoppedTape rows repeats r slots record) := by + cases r with + | refl => exact False.elim ((Nat.lt_irrefl _) hproper) + | step child r => rfl + +theorem upperBuckets_toStoppedTape (rows repeats : Nat → Nat) + (p : Path branch n (j + 1)) (r : Path branch (j + 1) (i + 1)) + (hproper : i + 1 < j + 1) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : Record rows repeats (p.append r) slots) : + UpperScalarCutBucket.upperBuckets rows repeats p r slots record = + stoppedBuckets rows repeats p r hproper slots + (OriginalUniformCut.toStoppedTape rows repeats (p.append r) slots record) := + (rootBuckets_toStoppedTape rows repeats r hproper (cutSlots p slots) + (UpperScalarCutBucket.descendRecord rows repeats p r slots record)).trans + (congrArg (stoppedRootBuckets rows repeats r hproper (cutSlots p slots)) + (extract_toStoppedTape rows repeats p r slots record)).symm + +theorem reference_toStoppedTape (rows repeats : Nat → Nat) + (p : Path branch n (i + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + (OriginalUniformCut.referenceLaw rows repeats p slots).pushforward + (OriginalUniformCut.toStoppedTape rows repeats p slots) = + WholeArraySampler.tapeLaw rows repeats p slots := by + rw [OriginalUniformCut.referenceLaw_uniform, OriginalUniformCut.uniform_toStoppedTape, + WholeArraySubtreeSplit.tapeLaw_eq_uniform] + +theorem joint_referenceLaw (rows repeats : Nat → Nat) + (p : Path branch n (j + 1)) (r : Path branch (j + 1) (i + 1)) + (hproper : i + 1 < j + 1) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + (OriginalUniformCut.referenceLaw rows repeats (p.append r) slots).pushforward + (fun record => (reconstructRecord rows repeats (p.append r) slots record, + UpperScalarCutBucket.upperBuckets rows repeats p r slots record)) = + (WholeArraySampler.tapeLaw rows repeats (p.append r) slots).pushforward + (fun tape => (WholeArraySampler.evaluate rows repeats (p.append r) slots tape, + stoppedBuckets rows repeats p r hproper slots tape)) := by + calc + _ = ((OriginalUniformCut.referenceLaw rows repeats (p.append r) slots).pushforward + (OriginalUniformCut.toStoppedTape rows repeats (p.append r) slots)).pushforward + (fun tape => (WholeArraySampler.evaluate rows repeats (p.append r) slots tape, + stoppedBuckets rows repeats p r hproper slots tape)) := by + rw [FiniteDistribution.pushforward_comp] + congr 1 + funext record + exact Prod.ext + (OriginalUniformCut.evaluate_toStoppedTape rows repeats (p.append r) slots record).symm + (upperBuckets_toStoppedTape rows repeats p r hproper slots record) + _ = _ := by rw [reference_toStoppedTape] + +end +end PerfectCompleteness.UpperStoppedBuckets + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/UpperScalarPairAveraging.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/UpperScalarPairAveraging.lean new file mode 100644 index 0000000000000000000000000000000000000000..dfa13e3430f9298570639b8a2cf078c5de0e700a --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/UpperScalarPairAveraging.lean @@ -0,0 +1,273 @@ +import OAI.Computability.PerfectCompleteness.Decoding.UpperScalarCutErasure +import OAI.Computability.PerfectCompleteness.Decoding.UpperScalarFreshProjectionLemmas +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalFrozenTablesLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.UpperScalarPairAveraging + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCutTape WholeArrayInteriorExterior +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) +open scoped BigOperators Classical + +noncomputable section + +attribute [local instance] linearMapFintype + +private theorem map_right {D A B Γ : Type*} + [Fintype D] [Fintype A] [Fintype B] [Fintype Γ] + (δ : FiniteDistribution D) (μ : FiniteDistribution A) + (f : A → B) (g : D × B → Γ) : + (δ.product (μ.pushforward f)).pushforward g = + (δ.product μ).pushforward (fun z => g (z.1, f z.2)) := by + have h := FiniteDistribution.product_pushforward δ μ id f + simp only [FiniteDistribution.pushforward_id, id_eq] at h + rw [← h, FiniteDistribution.pushforward_comp] + +private theorem map_three {D A B A' B' Γ : Type*} + [Fintype D] [Fintype A] [Fintype B] [Fintype A'] [Fintype B'] [Fintype Γ] + (δ : FiniteDistribution D) (μ : FiniteDistribution A) (ν : FiniteDistribution B) + (f : A → A') (g : B → B') (observe : D × (A' × B') → Γ) : + (δ.product ((μ.pushforward f).product (ν.pushforward g))).pushforward observe = + (δ.product (μ.product ν)).pushforward + (fun z => observe (z.1, (f z.2.1, g z.2.2))) := by + rw [← FiniteDistribution.product_pushforward μ ν f g] + exact map_right δ (μ.product ν) (fun z => (f z.1, g z.2)) observe + +private theorem product_mixture {E A B : Type*} + [Fintype E] [Fintype A] [Fintype B] + (μ : FiniteDistribution A) (κ : FiniteDistribution E) + (ν : E → FiniteDistribution B) : + μ.product (κ.mixture ν) = κ.mixture (fun e => μ.product (ν e)) := by + apply FiniteDistribution.eq_of_weight_eq + intro x + simp only [FiniteDistribution.product, FiniteDistribution.mixture, Finset.mul_sum] + apply Finset.sum_congr rfl + intro e _ + exact mul_left_comm _ _ _ + +variable {branch : Nat → Nat} {n j i k t : Nat} + +local instance backgroundFintype (rows : Nat → Nat) (p : Path branch n (j + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Fintype (HierarchicalMatrixTable.Background (rows := rows) slots (upperNode p)) := + Fintype.ofFinite _ + +local instance rowSpaceFintype (p : Path branch n (j + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Fintype (NodeEmbedding.RowSpace slots (upperNode p)) := Fintype.ofFinite _ + +private theorem tapeLaw_cast (rows repeats : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + {u v : Path branch n k} (h : u = v) : + (WholeArraySampler.tapeLaw rows repeats u slots).pushforward + (Equiv.cast (congrArg (fun path => WholeArraySampler.Tape rows repeats path slots) h)) = + WholeArraySampler.tapeLaw rows repeats v slots := by + cases h + change (WholeArraySampler.tapeLaw rows repeats u slots).pushforward id = _ + exact FiniteDistribution.pushforward_id _ + +theorem assocTapeEquiv_law (rows repeats : Nat → Nat) (p : Path branch n j) + (r : Path branch j i) (q : Path branch i k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + (WholeArraySampler.tapeLaw rows repeats ((p.append r).append q) slots).pushforward + (UpperScalarCutErasure.assocTapeEquiv rows repeats p r q slots) = + WholeArraySampler.tapeLaw rows repeats (p.append (r.append q)) slots := + tapeLaw_cast rows repeats slots (p.append_assoc r q) + +attribute [local instance 2000] OriginalWholeCutLaw.valuesBelowFintype + +def pathPairLaw (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (directions : FiniteDistribution (BucketSampler.Direction (rows (j + 1)))) : + Path branch (j + 1) 0 → + FiniteDistribution (HierarchicalAgreementMean.PairRecord (rows := rows) slots (upperNode p)) + | .step chosen q => + (directions.product + (((OriginalWholeCutLaw.recordLaw rows repeats p chosen q slots).pushforward + (OriginalWholeCutBridge.numberRecord rows repeats p slots)).product + (RecursiveSampler.law F2 repeats (.step chosen q) (LeafDomain (cutSlots p slots))))).pushforward + (OriginalCutCollision.pairRecord rows repeats p slots) + +private theorem upper_step_tape_law (rows repeats : Nat → Nat) + (p : Path branch n (j + 1)) (chosen : Fin (branch j)) (q : Path branch j 0) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (directions : FiniteDistribution (BucketSampler.Direction (rows (j + 1)))) : + (directions.product + ((WholeArraySampler.tapeLaw rows repeats (p.append (.step chosen q)) slots).product + (RecursiveSampler.tapeLaw F2 repeats (.step chosen q) + (LeafDomain (cutSlots p slots))))).pushforward + (fun z => OriginalCutCollision.pairRecord rows repeats p slots + (z.1, (OriginalWholeCutBridge.numberRecord rows repeats p slots + (OriginalWholeCut.readRecord rows repeats p chosen q slots z.2.1), + RecursiveSampler.evaluate F2 repeats (.step chosen q) + (LeafDomain (cutSlots p slots)) z.2.2))) = + pathPairLaw rows repeats p slots directions (.step chosen q) := by + let : Fintype (OriginalWholeCut.Values rows repeats p slots × + OriginalWholeCut.BelowArrays rows p slots) := + OriginalWholeCutLaw.valuesBelowFintype rows repeats p slots + rw [← map_three directions + (WholeArraySampler.tapeLaw rows repeats (p.append (.step chosen q)) slots) + (RecursiveSampler.tapeLaw F2 repeats (.step chosen q) (LeafDomain (cutSlots p slots))) + (fun tape => OriginalWholeCutBridge.numberRecord rows repeats p slots + (OriginalWholeCut.readRecord rows repeats p chosen q slots tape)) + (RecursiveSampler.evaluate F2 repeats (.step chosen q) (LeafDomain (cutSlots p slots))) + (OriginalCutCollision.pairRecord rows repeats p slots)] + rw [← FiniteDistribution.pushforward_comp + (WholeArraySampler.tapeLaw rows repeats (p.append (.step chosen q)) slots) + (OriginalWholeCut.readRecord rows repeats p chosen q slots) + (OriginalWholeCutBridge.numberRecord rows repeats p slots), + OriginalWholeCutLaw.readRecord_law] + rfl + +private theorem upper_read_law (rows repeats : Nat → Nat) + (p : Path branch n (j + 1)) (r : Path branch (j + 1) (i + 1)) + (chosen : Fin (branch i)) (q : Path branch i 0) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (directions : FiniteDistribution (BucketSampler.Direction (rows (j + 1)))) : + (directions.product + ((WholeArraySampler.tapeLaw rows repeats (p.append (r.append (.step chosen q))) slots).product + (RecursiveSampler.tapeLaw F2 repeats (r.append (.step chosen q)) + (LeafDomain (cutSlots p slots))))).pushforward + (fun z => UpperScalarCutErasure.upperPairRecord rows repeats p r chosen q slots z.2.1 z.1 + (RecursiveSampler.evaluate F2 repeats (r.append (.step chosen q)) + (LeafDomain (cutSlots p slots)) z.2.2)) = + pathPairLaw rows repeats p slots directions (r.append (.step chosen q)) := by + cases r with + | refl => exact upper_step_tape_law rows repeats p chosen q slots directions + | step upperChild tail => + exact upper_step_tape_law rows repeats p upperChild (tail.append (.step chosen q)) slots directions + +theorem fixed_pairLaw (rows repeats : Nat → Nat) + (p : Path branch n (j + 1)) (r : Path branch (j + 1) (i + 1)) + (chosen : Fin (branch i)) (q : Path branch i 0) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (directions : FiniteDistribution (BucketSampler.Direction (rows (j + 1)))) : + UpperScalarPairComparison.pairLaw rows repeats p r slots directions + ((OriginalChildBlocks.sourceLaw (UpperScalarCutCalls.count rows repeats n (j + 1) (i + 1)) + rows repeats chosen q (cutSlots (p.append r) slots)).pushforward + (OriginalChildBlocks.observed (UpperScalarCutCalls.count rows repeats n (j + 1) (i + 1)) + rows repeats chosen q (cutSlots (p.append r) slots))) = + pathPairLaw rows repeats p slots directions (r.append (.step chosen q)) := by + let oldTape := WholeArraySampler.tapeLaw rows repeats ((p.append r).append (.step chosen q)) slots + let freshTape := RecursiveSampler.tapeLaw F2 repeats (r.append (.step chosen q)) + (LeafDomain (cutSlots p slots)) + let observe := fun z : BucketSampler.Direction (rows (j + 1)) × + (WholeArraySampler.Tape rows repeats (p.append (r.append (.step chosen q))) slots × + RecursiveSampler.Tape F2 repeats (r.append (.step chosen q)) (LeafDomain (cutSlots p slots))) => + UpperScalarCutErasure.upperPairRecord rows repeats p r chosen q slots z.2.1 z.1 + (RecursiveSampler.evaluate F2 repeats (r.append (.step chosen q)) + (LeafDomain (cutSlots p slots)) z.2.2) + unfold UpperScalarPairComparison.pairLaw + rw [← UpperScalarCutLaw.numbered_read_law rows repeats p r chosen q slots, map_right] + have hmap : + (fun z : BucketSampler.Direction (rows (j + 1)) × + (WholeArraySampler.Tape rows repeats ((p.append r).append (.step chosen q)) slots × + RecursiveSampler.Tape F2 repeats (r.append (.step chosen q)) (LeafDomain (cutSlots p slots))) => + UpperScalarCutBucket.numberedPairRecord rows repeats p r slots + (z.1, UpperScalarCutReconstruction.numberRecordEquiv rows repeats p r slots + (UpperScalarCutReconstruction.read rows repeats p r chosen q slots z.2))) = + (fun z => observe (z.1, + (UpperScalarCutErasure.assocTapeEquiv rows repeats p r (.step chosen q) slots z.2.1, + id z.2.2))) := by + funext z + exact UpperScalarCutErasure.numberedPairRecord_read_eq_upper + rows repeats p r chosen q slots z.1 z.2 + rw [hmap, ← map_three directions oldTape freshTape + (UpperScalarCutErasure.assocTapeEquiv rows repeats p r (.step chosen q) slots) id observe] + dsimp only [oldTape] + rw [assocTapeEquiv_law, FiniteDistribution.pushforward_id] + exact upper_read_law rows repeats p r chosen q slots directions + +theorem continued_pairLaw_eq_mixture {K : Type*} [Fintype K] + (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (directions : FiniteDistribution (BucketSampler.Direction (rows (j + 1)))) + (ν : FiniteDistribution K) (q : K → Path branch i 0) (hbranch : 0 < branch i) : + UpperScalarPairComparison.pairLaw rows repeats p r slots directions + (OriginalPrefixContinuation.assembledLaw + (UpperScalarCutCalls.count rows repeats n (j + 1) (i + 1)) rows repeats + (cutSlots (p.append r) slots) ν q hbranch) = + (OriginalPrefixContinuation.tagLaw ν hbranch).mixture + (fun tag => pathPairLaw rows repeats p slots directions (r.append (.step tag.1 (q tag.2)))) := by + unfold UpperScalarPairComparison.pairLaw + rw [OriginalPrefixContinuation.assembledLaw_eq_mixture, product_mixture, + product_mixture, FiniteDistribution.pushforward_mixture] + apply congrArg ((OriginalPrefixContinuation.tagLaw ν hbranch).mixture) + funext tag + exact fixed_pairLaw rows repeats p r tag.1 (q tag.2) slots directions + +private theorem geometric_tagLaw (m : Nat) (hbranch : ∀ k < m + 1, 0 < branch k) : + OriginalPrefixContinuation.tagLaw + (GeometricPath.law m (fun k hk => hbranch k (Nat.lt_trans hk (Nat.lt_succ_self m)))) + (hbranch m (Nat.lt_succ_self m)) = GeometricPath.law (m + 1) hbranch := + (GeometricPath.law_step m hbranch).symm + +theorem lower_geometric_pairLaw (rows repeats : Nat → Nat) + (p : Path branch n (j + 1)) (r : Path branch (j + 1) (i + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (directions : FiniteDistribution (BucketSampler.Direction (rows (j + 1)))) + (hbranch : ∀ k < i + 1, 0 < branch k) : + UpperScalarPairComparison.pairLaw rows repeats p r slots directions + (OriginalPrefixContinuation.assembledLaw + (UpperScalarCutCalls.count rows repeats n (j + 1) (i + 1)) rows repeats + (cutSlots (p.append r) slots) + (GeometricPath.law i (fun k hk => hbranch k (Nat.lt_trans hk (Nat.lt_succ_self i)))) + GeometricPath.leafPath (hbranch i (Nat.lt_succ_self i))) = + (GeometricPath.law (i + 1) hbranch).mixture + (fun leaf => pathPairLaw rows repeats p slots directions (r.append (GeometricPath.leafPath leaf))) := by + rw [continued_pairLaw_eq_mixture, geometric_tagLaw] + rfl + +theorem upper_geometric_pairLaw (rows repeats : Nat → Nat) + (p : Path branch n (j + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (directions : FiniteDistribution (BucketSampler.Direction (rows (j + 1)))) + (hbranch : ∀ k < j + 1, 0 < branch k) : + (directions.product (OriginalExtraCutComparison.actualLaw rows repeats p slots + (GeometricPath.law j (fun k hk => hbranch k (Nat.lt_trans hk (Nat.lt_succ_self j)))) + GeometricPath.leafPath (hbranch j (Nat.lt_succ_self j)))).pushforward + (OriginalCutCollision.pairRecord rows repeats p slots) = + (GeometricPath.law (j + 1) hbranch).mixture + (fun leaf => pathPairLaw rows repeats p slots directions (GeometricPath.leafPath leaf)) := by + rw [OriginalExtraCutComparison.actualLaw_eq_mixture, product_mixture, + FiniteDistribution.pushforward_mixture, geometric_tagLaw] + rfl + +theorem geometric_average_eq_actual (rows repeats : Nat → Nat) + (p : Path branch n (j + 1)) (hcut : i + 1 ≤ j + 1) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (directions : FiniteDistribution (BucketSampler.Direction (rows (j + 1)))) + (hbranch : ∀ k < j + 1, 0 < branch k) : + (GeometricCutSplit.prefixLaw hcut hbranch).mixture (fun pref => + UpperScalarPairComparison.pairLaw rows repeats p (GeometricCutSplit.prefixPath hcut pref) + slots directions + (OriginalPrefixContinuation.assembledLaw + (UpperScalarCutCalls.count rows repeats n (j + 1) (i + 1)) rows repeats + (cutSlots (p.append (GeometricCutSplit.prefixPath hcut pref)) slots) + (GeometricPath.law i (fun k hk => + hbranch k (Nat.lt_of_lt_of_le (Nat.lt_trans hk (Nat.lt_succ_self i)) hcut))) + GeometricPath.leafPath + (hbranch i (Nat.lt_of_lt_of_le (Nat.lt_succ_self i) hcut)))) = + (directions.product (OriginalExtraCutComparison.actualLaw rows repeats p slots + (GeometricPath.law j (fun k hk => hbranch k (Nat.lt_trans hk (Nat.lt_succ_self j)))) + GeometricPath.leafPath (hbranch j (Nat.lt_succ_self j)))).pushforward + (OriginalCutCollision.pairRecord rows repeats p slots) := by + rw [upper_geometric_pairLaw] + rw [GeometricCutMixture.path_mixture_split hcut hbranch] + apply congrArg ((GeometricCutSplit.prefixLaw hcut hbranch).mixture) + funext pref + exact lower_geometric_pairLaw rows repeats p (GeometricCutSplit.prefixPath hcut pref) + slots directions (fun k hk => hbranch k (Nat.lt_of_lt_of_le hk hcut)) + +end +end PerfectCompleteness.UpperScalarPairAveraging + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Decoding/WholeCutGroupedProjection.lean b/lean/OAI/Computability/PerfectCompleteness/Decoding/WholeCutGroupedProjection.lean new file mode 100644 index 0000000000000000000000000000000000000000..24afea5dd1390e889da5cf7d59c1a6efb4b93e82 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Decoding/WholeCutGroupedProjection.lean @@ -0,0 +1,315 @@ +import OAI.Computability.PerfectCompleteness.Decoding.CutGroupedProjectionLemmas +import OAI.Computability.PerfectCompleteness.Decoding.CutProjectionAssembly +import OAI.Computability.PerfectCompleteness.Repetition.CleanPhysicalReplay + +namespace OAI + +section + +namespace PerfectCompleteness.WholeCutGroupedProjection + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +abbrev F2 := ZMod 2 + +noncomputable section + +variable {branch : Nat → Nat} {n m t : Nat} + +def evaluateGrouped (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (ext : WholeCutGrouping.Exterior rows repeats p slots) + (children : CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) + (WholeCutGrouping.cutSlots p slots) rows) : Arrays slots rows := + WholeCutSampler.evaluate rows repeats p slots + ((WholeCutGrouping.splitTape rows repeats p slots).symm (ext, children)) + +theorem evaluateGrouped_root (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n (m + 1)) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ext : WholeCutGrouping.Exterior rows repeats (.step i p) slots) + (children : CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats (.step i p)) + (WholeCutGrouping.cutSlots (.step i p) slots) rows) : + evaluateGrouped rows repeats (.step i p) slots ext children (.inl ()) = + BucketSampler.evaluate (rows (n + 1)) + (CutSamplerRefinement.evaluate F2 repeats (.step i p) (LeafDomain slots)) + (fun bucket => (CutTerminalSplit.splitTape F2 repeats (.step i p) (LeafDomain slots)).symm + (fun terminal child => (children child).1 (.inl (bucket, terminal)), ext.1 bucket)) := rfl + +theorem evaluateGrouped_selected (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n (m + 1)) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ext : WholeCutGrouping.Exterior rows repeats (.step i p) slots) + (children : CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats (.step i p)) + (WholeCutGrouping.cutSlots (.step i p) slots) rows) (node : Nodes branch n) : + evaluateGrouped rows repeats (.step i p) slots ext children (.inr (i, node)) = + evaluateGrouped rows repeats p (childSlots slots i) ext.2.1 + (fun child => (fun call => (children child).1 (.inr call), (children child).2)) node := + WholeArraySampler.evaluate_selected rows repeats i p slots + (WholeCutSampler.collapse rows repeats (.step i p) slots + ((WholeCutGrouping.splitTape rows repeats (.step i p) slots).symm (ext, children))) node + +theorem evaluateGrouped_ordinary (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n (m + 1)) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ext : WholeCutGrouping.Exterior rows repeats (.step i p) slots) + (children : CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats (.step i p)) + (WholeCutGrouping.cutSlots (.step i p) slots) rows) + (j : RecursiveSampler.OffPath i) (node : Nodes branch n) : + evaluateGrouped rows repeats (.step i p) slots ext children (.inr (j.val, node)) = + ext.2.2 j node := + WholeArraySampler.evaluate_ordinary rows repeats i p slots + (WholeCutSampler.collapse rows repeats (.step i p) slots + ((WholeCutGrouping.splitTape rows repeats (.step i p) slots).symm (ext, children))) j node + +private theorem cast_exterior_parts {I J A A' B B' : Type} {C C' : J → Type} + (ha : A = A') (hb : B = B') (hc : ∀ j, C j = C' j) + (h : ((I → A) × (B × ((j : J) → C j))) = ((I → A') × (B' × ((j : J) → C' j)))) + (x : (I → A) × (B × ((j : J) → C j))) : + cast h x = (fun i => cast ha (x.1 i), (cast hb x.2.1, fun j => cast (hc j) (x.2.2 j))) := by + have hC : C = C' := funext hc + cases ha + cases hb + cases hC + rfl + +theorem exterior_equiv_step (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n (m + 1)) + (left right : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (hs : ∀ s, WholeCutExteriorTransport.Outside (.step i p) s → left s = right s) + (ext : WholeCutGrouping.Exterior rows repeats (.step i p) right) : + WholeCutExteriorTransport.equiv rows repeats (.step i p) right left + (fun s h => (hs s h).symm) ext = + (fun bucket => cast + (WholeCutExteriorTransport.scalarExterior_eq repeats (.step i p) right left + (fun s h => (hs s h).symm)) (ext.1 bucket), + (WholeCutExteriorTransport.equiv rows repeats p (childSlots right i) (childSlots left i) + (fun s h => (hs (i, s) (WholeCutExteriorTransport.outside_selected i p s h)).symm) ext.2.1, + fun j => cast (congrArg (fun ss => Arrays ss rows) + (WholeCutExteriorTransport.ordinarySlots_eq i p right left + (fun s h => (hs s h).symm) j)) (ext.2.2 j))) := + cast_exterior_parts _ _ _ _ ext + +private theorem assembleArrays_pullback (rows : Nat → Nat) + (left right : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (data : CutChildGrouping.Assembled (C := Fin (rows (n + 1))) right rows) : + WholeCutSampler.assembleArrays left rows (ChildAssemblyProjection.assembledPullback rows q data) = + ChildBlockProjection.arraysPullback rows q (WholeCutSampler.assembleArrays right rows data) := by + funext node row + rcases node with u | ⟨i, node⟩ <;> rfl + +private theorem bucket_evaluate_pullback {ΩL ΩR : Type*} (width : Nat) + (left right : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (evalL : ΩL → H left) (evalR : ΩR → H right) + (tapeL : BucketSampler.Tape width ΩL) (tapeR : BucketSampler.Tape width ΩR) + (heval : ∀ bucket x, (evalL (tapeL bucket)).val x = + (evalR (tapeR bucket)).val (sourceProjection q x)) : + BucketSampler.evaluate width evalL tapeL = + fun row => HPullback q (BucketSampler.evaluate width evalR tapeR row) := by + funext row + apply Subtype.ext + funext x + exact (BucketSampler.evaluate_apply width (H left) evalL tapeL row x).trans + ((Finset.sum_congr rfl (fun bucket _ => + congrArg (fun z : F2 => bucket.val row * z) (heval bucket x))).trans + (BucketSampler.evaluate_apply width (H right) evalR tapeR row + (sourceProjection q x)).symm) + +theorem evaluateGrouped_pullback (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) : + ∀ (left right : Slots branch n → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (hs : ∀ s, WholeCutExteriorTransport.Outside p s → left s = right s) + (_ : ∀ s, WholeCutExteriorTransport.Outside p s → ∀ k, + HEq (q s k) (MixedSupport.Projection.keep (left s k))) + (ext : WholeCutGrouping.Exterior rows repeats p right) + (children : CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) + (WholeCutGrouping.cutSlots p right) rows), + evaluateGrouped rows repeats p left + (WholeCutExteriorTransport.equiv rows repeats p right left (fun s h => (hs s h).symm) ext) + (ChildAssemblyProjection.rawPullback rows (CutGroupedProjection.cutProjection p q) children) = + ChildBlockProjection.arraysPullback rows q + (evaluateGrouped rows repeats p right ext children) := by + induction n generalizing m with + | zero => + have h := p.height_le + omega + | succ n ih => + cases p with + | refl => + intro left right q hs hk ext children + exact (congrArg (WholeCutSampler.assembleArrays left rows) + (ChildAssemblyProjection.assemble_pullback (C := Fin (rows (n + 1))) + rows q children)).trans + (assembleArrays_pullback rows left right q + (CutChildGrouping.assemble right rows children)) + | step i p => + intro left right q hs hk ext children + let leftChildren := ChildAssemblyProjection.rawPullback rows + (CutGroupedProjection.cutProjection (.step i p) q) children + let leftExterior : WholeCutGrouping.Exterior rows repeats (.step i p) left := + (fun bucket => cast + (WholeCutExteriorTransport.scalarExterior_eq repeats (.step i p) right left + (fun s h => (hs s h).symm)) (ext.1 bucket), + (WholeCutExteriorTransport.equiv rows repeats p (childSlots right i) (childSlots left i) + (fun s h => (hs (i, s) + (WholeCutExteriorTransport.outside_selected i p s h)).symm) ext.2.1, + fun j => cast (congrArg (fun ss => Arrays ss rows) + (WholeCutExteriorTransport.ordinarySlots_eq i p right left + (fun s h => (hs s h).symm) j)) (ext.2.2 j))) + have hext : WholeCutExteriorTransport.equiv rows repeats (.step i p) right left + (fun s h => (hs s h).symm) ext = leftExterior := + exterior_equiv_step rows repeats i p left right hs ext + refine (congrArg + (fun e : WholeCutGrouping.Exterior rows repeats (.step i p) left => + evaluateGrouped rows repeats (.step i p) left e leftChildren) hext).trans ?_ + funext node row + rcases node with u | ⟨j, node⟩ + · cases u + have hrootL := evaluateGrouped_root rows repeats i p left leftExterior leftChildren + have hrootR := evaluateGrouped_root rows repeats i p right ext children + have hbucket := bucket_evaluate_pullback (rows (n + 1)) left right q + (CutSamplerRefinement.evaluate F2 repeats (.step i p) (LeafDomain left)) + (CutSamplerRefinement.evaluate F2 repeats (.step i p) (LeafDomain right)) + (fun bucket => + (CutTerminalSplit.splitTape F2 repeats (.step i p) (LeafDomain left)).symm + (fun terminal child => (leftChildren child).1 (.inl (bucket, terminal)), + leftExterior.1 bucket)) + (fun bucket => + (CutTerminalSplit.splitTape F2 repeats (.step i p) (LeafDomain right)).symm + (fun terminal child => (children child).1 (.inl (bucket, terminal)), ext.1 bucket)) + (fun bucket x => CutGroupedProjection.evaluate_rebuild repeats (.step i p) + left right q hs hk + (fun terminal child => (children child).1 (.inl (bucket, terminal))) (ext.1 bucket) x) + exact congrFun (hrootL.trans (hbucket.trans + (congrArg (fun f : Fin (rows (n + 1)) → H right => + fun r => HPullback q (f r)) hrootR).symm)) row + · by_cases hji : j = i + · subst j + have hnodeL := congrFun + (evaluateGrouped_selected rows repeats i p left leftExterior leftChildren node) row + have hnodeR := congrFun + (evaluateGrouped_selected rows repeats i p right ext children node) row + have hchild := congrFun (congrFun + (ih p (childSlots left i) (childSlots right i) (fun s k => q (i, s) k) + (fun s h => hs (i, s) (WholeCutExteriorTransport.outside_selected i p s h)) + (fun s h k => hk (i, s) (WholeCutExteriorTransport.outside_selected i p s h) k) + ext.2.1 (fun child => (fun call => (children child).1 (.inr call), (children child).2))) node) row + exact hnodeL.trans (hchild.trans + (congrArg (HPullback (ChildBlockProjection.nodeProjection q (.inr (i, node)))) + hnodeR).symm) + · have hnodeL := congrFun + (evaluateGrouped_ordinary rows repeats i p left leftExterior leftChildren ⟨j, hji⟩ node) row + have hnodeR := congrFun + (evaluateGrouped_ordinary rows repeats i p right ext children ⟨j, hji⟩ node) row + have hcast := CutProjectionGeometry.arraysPullback_eq_cast rows + (childSlots left j) (childSlots right j) (fun s k => q (j, s) k) + (WholeCutExteriorTransport.ordinarySlots_eq i p left right hs ⟨j, hji⟩) + (fun s k => hk (j, s) (WholeCutExteriorTransport.outside_ordinary i p ⟨j, hji⟩ s) k) + (ext.2.2 ⟨j, hji⟩) + have hcastRow := congrFun (congrFun hcast.symm node) row + exact hnodeL.trans (hcastRow.trans + (congrArg (HPullback (ChildBlockProjection.nodeProjection q (.inr (j, node)))) + hnodeR).symm) + +theorem exteriorAt_pullback (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (outside : Slots branch n → Fin t → MixedSupport.Slot) + (placeholder left right : Slots branch (m + 1) → Fin t → MixedSupport.Slot) + (external : CleanPhysicalReplay.Exterior rows repeats p outside placeholder) : + CleanPhysicalReplay.exteriorAt rows repeats p outside placeholder left external = + WholeCutExteriorTransport.equiv rows repeats p + (CutSlotAssembly.fill p outside right) (CutSlotAssembly.fill p outside left) + (fun s h => (CutSlotAssembly.fill_outside_eq p outside left right s h).symm) + (CleanPhysicalReplay.exteriorAt rows repeats p outside placeholder right external) := by + apply eq_of_heq + have hleft : HEq + (CleanPhysicalReplay.exteriorAt rows repeats p outside placeholder left external) external := + cast_heq _ _ + have hright : HEq + (CleanPhysicalReplay.exteriorAt rows repeats p outside placeholder right external) external := + cast_heq _ _ + exact hleft.trans ((cast_heq _ _).trans hright).symm + +theorem fillChildren_pullback (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (outside : Slots branch n → Fin t → MixedSupport.Slot) + (left right : Slots branch (m + 1) → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (children : CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) right rows) : + (fun i => CleanPhysicalReplay.fillChild rows repeats p outside left i + ((ChildAssemblyProjection.rawPullback rows q children) i)) = + ChildAssemblyProjection.rawPullback rows + (CutGroupedProjection.cutProjection p + (CutProjectionAssembly.fillProjection p outside left right q)) + (fun i => CleanPhysicalReplay.fillChild rows repeats p outside right i (children i)) := by + funext i + apply eq_of_heq + exact (CleanPhysicalReplay.fillChild_heq rows repeats p outside left i + ((ChildAssemblyProjection.rawPullback rows q children) i)).trans + (CutProjectionGeometry.childPullback_heq rows + (CleanPhysicalReplay.cutSlots_fill p outside left) + (CleanPhysicalReplay.cutSlots_fill p outside right) + (CutGroupedProjection.cutProjection p + (CutProjectionAssembly.fillProjection p outside left right q)) q + (CutProjectionAssembly.fillProjection_at_cut p outside left right q) i + (CleanPhysicalReplay.fillChild rows repeats p outside right i (children i)) + (children i) (CleanPhysicalReplay.fillChild_heq rows repeats p outside right i + (children i))).symm + +theorem physicalTape_pullback (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (outside : Slots branch n → Fin t → MixedSupport.Slot) + (placeholder left right : Slots branch (m + 1) → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (external : CleanPhysicalReplay.Exterior rows repeats p outside placeholder) + (children : CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) right rows) : + WholeCutSampler.evaluate rows repeats p (CutSlotAssembly.fill p outside left) + (CleanPhysicalReplay.physicalTape rows repeats p outside placeholder left external + (ChildAssemblyProjection.rawPullback rows q children)) = + ChildBlockProjection.arraysPullback rows + (CutProjectionAssembly.fillProjection p outside left right q) + (WholeCutSampler.evaluate rows repeats p (CutSlotAssembly.fill p outside right) + (CleanPhysicalReplay.physicalTape rows repeats p outside placeholder right external children)) := by + change evaluateGrouped rows repeats p (CutSlotAssembly.fill p outside left) + (CleanPhysicalReplay.exteriorAt rows repeats p outside placeholder left external) + (fun i => CleanPhysicalReplay.fillChild rows repeats p outside left i + ((ChildAssemblyProjection.rawPullback rows q children) i)) = + ChildBlockProjection.arraysPullback rows + (CutProjectionAssembly.fillProjection p outside left right q) + (evaluateGrouped rows repeats p (CutSlotAssembly.fill p outside right) + (CleanPhysicalReplay.exteriorAt rows repeats p outside placeholder right external) + (fun i => CleanPhysicalReplay.fillChild rows repeats p outside right i (children i))) + rw [exteriorAt_pullback rows repeats p outside placeholder left right external, + fillChildren_pullback] + exact evaluateGrouped_pullback rows repeats p + (CutSlotAssembly.fill p outside left) (CutSlotAssembly.fill p outside right) + (CutProjectionAssembly.fillProjection p outside left right q) + (CutSlotAssembly.fill_outside_eq p outside left right) + (CutProjectionGeometry.fillProjection_outside p outside left right q) + (CleanPhysicalReplay.exteriorAt rows repeats p outside placeholder right external) + (fun i => CleanPhysicalReplay.fillChild rows repeats p outside right i (children i)) + +theorem fullJoint_physicalTape_pullback (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) + (outside : Slots branch n → Fin t → MixedSupport.Slot) + (placeholder left right : Slots branch (m + 1) → Fin t → MixedSupport.Slot) + (q : ∀ s k, MixedSupport.Projection (left s k) (right s k)) + (external : CleanPhysicalReplay.Exterior rows repeats p outside placeholder) + (children : CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) right rows) + (x : Domain (CutSlotAssembly.fill p outside left)) : + fullJoint (WholeCutSampler.evaluate rows repeats p (CutSlotAssembly.fill p outside left) + (CleanPhysicalReplay.physicalTape rows repeats p outside placeholder left external + (ChildAssemblyProjection.rawPullback rows q children))) x = + fullJoint (WholeCutSampler.evaluate rows repeats p (CutSlotAssembly.fill p outside right) + (CleanPhysicalReplay.physicalTape rows repeats p outside placeholder right external children)) + (sourceProjection (CutProjectionAssembly.fillProjection p outside left right q) x) := by + rw [physicalTape_pullback] + rfl + +end +end PerfectCompleteness.WholeCutGroupedProjection + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/CanonicalCoarseningErasure.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/CanonicalCoarseningErasure.lean new file mode 100644 index 0000000000000000000000000000000000000000..7c5fb8a777d2bc215137236b3a01329b9be9e311 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/CanonicalCoarseningErasure.lean @@ -0,0 +1,120 @@ +import OAI.Computability.PerfectCompleteness.Foundations.CanonicalEdgesLemmas +import OAI.Computability.PerfectCompleteness.Machines.CanonicalLabelEncoding + +namespace OAI + +section + +namespace PerfectCompleteness.CanonicalCoarseningErasure + +open MixedSupport CanonicalKeys CanonicalKeyShape CanonicalEdges + +noncomputable section + +variable {n : Nat} {Y Z : Type*} + +def transportLabel (slots : Fin n → Slot) (f : Assignment slots → Y) + (P : Label slots f) : Label (dummySlots (shape slots)) (transport slots f) := + ⟨P.val, by + change P.val ∈ CanonicalKeys.partition (dummySlots (shape slots)) (transport slots f) + rw [← partition_erasure slots f] + exact P.property⟩ + +@[simp] theorem transportLabel_val (slots : Fin n → Slot) (f : Assignment slots → Y) + (P : Label slots f) : (transportLabel slots f P).val = P.val := rfl + +theorem transportLabel_bijective (slots : Fin n → Slot) (f : Assignment slots → Y) : + Function.Bijective (transportLabel slots f) := by + constructor + · intro P Q h + apply Subtype.ext + exact congrArg + (fun R : Label (dummySlots (shape slots)) (transport slots f) => R.val) h + · intro Q + have hQ : Q.val ∈ CanonicalKeys.partition slots f := by + rw [partition_erasure slots f] + exact Q.property + exact ⟨⟨Q.val, hQ⟩, Subtype.ext rfl⟩ + +theorem transportLabel_evaluateLabel (slots : Fin n → Slot) + (f : Assignment slots → Y) (x : Assignment slots) : + transportLabel slots f (evaluateLabel slots f x) = + evaluateLabel (dummySlots (shape slots)) (transport slots f) (assignmentEquiv slots x) := by + apply Subtype.ext + exact ReducedPartition.fiber_eq_of_pullback + (assignmentEquiv slots) (assignmentEquiv slots).surjective + (reduction slots f) (reduction (dummySlots (shape slots)) (transport slots f)) + f (transport slots f) (reduction_erasure slots f) + (fun x => (transport_apply slots f x).symm) x + +theorem restore_transportLabel (slots : Fin n → Slot) (f : Assignment slots → Y) + (P : Label slots f) : + restore slots f P = + restore (dummySlots (shape slots)) (transport slots f) (transportLabel slots f P) := by + exact ReducedPartition.output_eq_of_shared_part + (assignmentEquiv slots) + (reduction slots f) (reduction (dummySlots (shape slots)) (transport slots f)) + f (transport slots f) (reduction_erasure slots f) + (fun x => (transport_apply slots f x).symm) + (constantOnFibers (dummySlots (shape slots)) (transport slots f)) + P (transportLabel slots f P) rfl + +theorem coarsen_transportLabel (slots : Fin n → Slot) (f : Assignment slots → Y) + (p : Y → Z) (P : Label slots f) : + transportLabel slots (p ∘ f) (coarsen slots f p P) = + coarsen (dummySlots (shape slots)) (transport slots f) p (transportLabel slots f P) := by + apply restore_injective (dummySlots (shape slots)) (p ∘ transport slots f) + calc + restore (dummySlots (shape slots)) (p ∘ transport slots f) + (transportLabel slots (p ∘ f) (coarsen slots f p P)) = + restore slots (p ∘ f) (coarsen slots f p P) := + (restore_transportLabel slots (p ∘ f) (coarsen slots f p P)).symm + _ = p (restore slots f P) := restore_coarsen slots f p P + _ = p (restore (dummySlots (shape slots)) (transport slots f) + (transportLabel slots f P)) := congrArg p (restore_transportLabel slots f P) + _ = restore (dummySlots (shape slots)) (p ∘ transport slots f) + (coarsen (dummySlots (shape slots)) (transport slots f) p (transportLabel slots f P)) := + (restore_coarsen (dummySlots (shape slots)) (transport slots f) p + (transportLabel slots f P)).symm + +theorem coarsen_val (slots : Fin n → Slot) (f : Assignment slots → Y) + (p : Y → Z) (P : Label slots f) : + (coarsen slots f p P).val = + (coarsen (dummySlots (shape slots)) (transport slots f) p + (transportLabel slots f P)).val := + congrArg Subtype.val (coarsen_transportLabel slots f p P) + +@[simp] theorem partIndex_transportLabel (slots : Fin n → Slot) + (f : Assignment slots → Y) (P : Label slots f) : + CanonicalKeyEncoding.partEnum n (transportLabel slots f P).val = + CanonicalKeyEncoding.partEnum n P.val := rfl + +theorem partIndex_coarsen (slots : Fin n → Slot) (f : Assignment slots → Y) + (p : Y → Z) (P : Label slots f) : + CanonicalKeyEncoding.partEnum n (coarsen slots f p P).val = + CanonicalKeyEncoding.partEnum n + (coarsen (dummySlots (shape slots)) (transport slots f) p + (transportLabel slots f P)).val := + congrArg (CanonicalKeyEncoding.partEnum n) (coarsen_val slots f p P) + +@[simp] theorem labelIndex_transportLabel (side : Side) (slots : Fin n → Slot) + (f : Assignment slots → Y) (P : Label slots f) : + CanonicalLabelEncoding.labelIndex (key side slots f) P = + CanonicalLabelEncoding.labelIndex + (key side (dummySlots (shape slots)) (transport slots f)) (transportLabel slots f P) := rfl + +theorem labelIndex_coarsen (side : Side) (slots : Fin n → Slot) + (f : Assignment slots → Y) (p : Y → Z) (P : Label slots f) : + CanonicalLabelEncoding.labelIndex (key side slots (p ∘ f)) (coarsen slots f p P) = + CanonicalLabelEncoding.labelIndex + (key side (dummySlots (shape slots)) (p ∘ transport slots f)) + (coarsen (dummySlots (shape slots)) (transport slots f) p + (transportLabel slots f P)) := + partIndex_coarsen slots f p P + +end +end PerfectCompleteness.CanonicalCoarseningErasure + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/CanonicalDictionaryNames.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/CanonicalDictionaryNames.lean new file mode 100644 index 0000000000000000000000000000000000000000..f9c24386f07038e158203335aa89c28cdfc09bb9 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/CanonicalDictionaryNames.lean @@ -0,0 +1,178 @@ +import OAI.Computability.PerfectCompleteness.Machines.CanonicalDictionaryMachine +import OAI.Computability.PerfectCompleteness.Machines.CanonicalKeyShapeMachineLemmas + +namespace OAI + + +namespace PerfectCompleteness.CanonicalDictionaryNames + +open CanonicalKeys Turing +open UniqueGamesTheorem.Foundations.Complexity MachineComposition + +noncomputable section + +variable {n : Nat} + +theorem updatedTokens_eq (earlier : List (Key n)) (key : Key n) : + CanonicalDictionaryMachine.updatedTokens (CanonicalVertexNames.tokens earlier) + (CanonicalVertexNames.payload key) = + CanonicalVertexNames.tokens (earlier ++ [key]) := + (CanonicalOnlineNames.tokens_append_current earlier key).symm + +theorem keyWord_eq (key : Key n) : + (CanonicalVertexNames.payload key).reverse = + (CanonicalKeyEncoding.bits key ++ [true]).reverse := rfl + +theorem index_eq_onlineID (earlier : List (Key n)) (key : Key n) : + CanonicalDictionaryMachine.index (CanonicalVertexNames.tokens earlier) + (CanonicalVertexNames.payload key) = CanonicalOnlineNames.onlineID earlier key := by + unfold CanonicalDictionaryMachine.index CanonicalOnlineNames.onlineID + rw [updatedTokens_eq] + +theorem index_eq_finalName (earlier suffix : List (Key n)) (key : Key n) : + CanonicalDictionaryMachine.index (CanonicalVertexNames.tokens earlier) + (CanonicalVertexNames.payload key) = + (CanonicalVertexNames.name (earlier ++ key :: suffix) key (by simp)).val := by + rw [index_eq_onlineID, CanonicalOnlineNames.onlineID_eq_name_val earlier suffix key] + +def steps (earlier : List (Key n)) (key : Key n) : Nat := + CanonicalDictionaryMachine.steps (CanonicalVertexNames.tokens earlier) + (CanonicalVertexNames.payload key) + +theorem steps_le (earlier : List (Key n)) (key : Key n) : + steps earlier key ≤ + 3 * (BinaryNameSearch.stream (CanonicalVertexNames.tokens (earlier ++ [key]))).length ^ 2 + + 16 * (BinaryNameSearch.stream (CanonicalVertexNames.tokens (earlier ++ [key]))).length + + 12 := by + simpa only [steps, updatedTokens_eq] using + CanonicalDictionaryMachine.steps_le (CanonicalVertexNames.tokens earlier) + (CanonicalVertexNames.payload key) + +def streamBound (n bound count : Nat) : Nat := + (2 * CanonicalVertexNames.payloadBound n bound + 2) * count + +theorem steps_le_metadata (earlier : List (Key n)) (key : Key n) (bound : Nat) + (hretained : ∀ k ∈ earlier ++ [key], k.retained.length ≤ n) + (hIDs : ∀ k ∈ earlier ++ [key], ∀ entry ∈ k.retained, + KeyMetadataEncoding.entryID entry.2 ≤ bound) : + steps earlier key ≤ + 3 * streamBound n bound (earlier.length + 1) ^ 2 + + 16 * streamBound n bound (earlier.length + 1) + 12 := by + have hstream : + (BinaryNameSearch.stream (CanonicalVertexNames.tokens (earlier ++ [key]))).length ≤ + streamBound n bound (earlier.length + 1) := by + simpa only [streamBound, List.length_append, List.length_singleton] using + CanonicalVertexNames.stream_length_le (earlier ++ [key]) bound hretained hIDs + have hsquare := Nat.mul_le_mul hstream hstream + apply (steps_le earlier key).trans + nlinarith + + +variable {K Λ A : Type} [DecidableEq K] + +theorem dictionaryTrace (tape : Fin 8 → K) (distinct : Function.Injective tape) + (labels : CanonicalDictionaryMachine.Label → Λ) (done rejected : Option Λ) + (program : Λ → TM2.Stmt (CanonicalDictionaryMachine.Alphabet (K := K)) Λ + (CanonicalDictionaryMachine.State A)) + (atLabels : ∀ l, program (labels l) = + CanonicalDictionaryMachine.instruction tape labels done rejected l) + (base : K → List Bool) (ambient : A) (earlier : List (Key n)) (key : Key n) + (keyWord : base (tape 0) = (CanonicalVertexNames.payload key).reverse) + (dictionaryWord : base (tape 1) = + BinaryNameSearch.stream (CanonicalVertexNames.tokens earlier)) + (empty : ∀ i : Fin 8, 2 ≤ i.val → i.val ≤ 6 → base (tape i) = []) : + (advance (TM2.step program))^[steps earlier key] + (some ⟨some (labels CanonicalDictionaryMachine.main), + CanonicalDictionaryMachine.clean ambient, base⟩) = + some ⟨done, CanonicalDictionaryMachine.clean ambient, + Function.update (Function.update base (tape 1) + (BinaryNameSearch.stream (CanonicalVertexNames.tokens (earlier ++ [key])))) (tape 7) + ((encodeWord (CanonicalOnlineNames.onlineID earlier key)).reverse ++ base (tape 7))⟩ := by + simpa only [steps, updatedTokens_eq, index_eq_onlineID] using + CanonicalDictionaryMachine.dictionaryTrace tape distinct labels done rejected program + atLabels base ambient (CanonicalVertexNames.tokens earlier) (CanonicalVertexNames.payload key) + (CanonicalVertexNames.payload_canonical key) (CanonicalVertexNames.tokens_canonical earlier) + keyWord dictionaryWord empty + +def dictionaryInTime (tape : Fin 8 → K) (distinct : Function.Injective tape) + (labels : CanonicalDictionaryMachine.Label → Λ) (done rejected : Option Λ) + (program : Λ → TM2.Stmt (CanonicalDictionaryMachine.Alphabet (K := K)) Λ + (CanonicalDictionaryMachine.State A)) + (atLabels : ∀ l, program (labels l) = + CanonicalDictionaryMachine.instruction tape labels done rejected l) + (base : K → List Bool) (ambient : A) (earlier : List (Key n)) (key : Key n) + (keyWord : base (tape 0) = (CanonicalVertexNames.payload key).reverse) + (dictionaryWord : base (tape 1) = + BinaryNameSearch.stream (CanonicalVertexNames.tokens earlier)) + (empty : ∀ i : Fin 8, 2 ≤ i.val → i.val ≤ 6 → base (tape i) = []) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels CanonicalDictionaryMachine.main), CanonicalDictionaryMachine.clean ambient, + base⟩ + (some ⟨done, CanonicalDictionaryMachine.clean ambient, + Function.update (Function.update base (tape 1) + (BinaryNameSearch.stream (CanonicalVertexNames.tokens (earlier ++ [key])))) (tape 7) + ((encodeWord (CanonicalOnlineNames.onlineID earlier key)).reverse ++ base (tape 7))⟩) + (3 * (BinaryNameSearch.stream (CanonicalVertexNames.tokens (earlier ++ [key]))).length ^ 2 + + 16 * (BinaryNameSearch.stream (CanonicalVertexNames.tokens (earlier ++ [key]))).length + + 12) where + steps := steps earlier key + evals_in_steps := dictionaryTrace tape distinct labels done rejected program atLabels + base ambient earlier key keyWord dictionaryWord empty + steps_le_m := steps_le earlier key + +theorem dictionaryTrace_finalName (tape : Fin 8 → K) (distinct : Function.Injective tape) + (labels : CanonicalDictionaryMachine.Label → Λ) (done rejected : Option Λ) + (program : Λ → TM2.Stmt (CanonicalDictionaryMachine.Alphabet (K := K)) Λ + (CanonicalDictionaryMachine.State A)) + (atLabels : ∀ l, program (labels l) = + CanonicalDictionaryMachine.instruction tape labels done rejected l) + (base : K → List Bool) (ambient : A) (earlier suffix : List (Key n)) (key : Key n) + (keyWord : base (tape 0) = (CanonicalVertexNames.payload key).reverse) + (dictionaryWord : base (tape 1) = + BinaryNameSearch.stream (CanonicalVertexNames.tokens earlier)) + (empty : ∀ i : Fin 8, 2 ≤ i.val → i.val ≤ 6 → base (tape i) = []) : + (advance (TM2.step program))^[steps earlier key] + (some ⟨some (labels CanonicalDictionaryMachine.main), + CanonicalDictionaryMachine.clean ambient, base⟩) = + some ⟨done, CanonicalDictionaryMachine.clean ambient, + Function.update (Function.update base (tape 1) + (BinaryNameSearch.stream (CanonicalVertexNames.tokens (earlier ++ [key])))) (tape 7) + ((encodeWord (CanonicalVertexNames.name + (earlier ++ key :: suffix) key (by simp)).val).reverse ++ base (tape 7))⟩ := by + simpa only [CanonicalOnlineNames.onlineID_eq_name_val earlier suffix key] using + dictionaryTrace tape distinct labels done rejected program atLabels + base ambient earlier key keyWord dictionaryWord empty + +def dictionaryInTime_metadata (tape : Fin 8 → K) (distinct : Function.Injective tape) + (labels : CanonicalDictionaryMachine.Label → Λ) (done rejected : Option Λ) + (program : Λ → TM2.Stmt (CanonicalDictionaryMachine.Alphabet (K := K)) Λ + (CanonicalDictionaryMachine.State A)) + (atLabels : ∀ l, program (labels l) = + CanonicalDictionaryMachine.instruction tape labels done rejected l) + (base : K → List Bool) (ambient : A) (earlier : List (Key n)) (key : Key n) + (keyWord : base (tape 0) = (CanonicalVertexNames.payload key).reverse) + (dictionaryWord : base (tape 1) = + BinaryNameSearch.stream (CanonicalVertexNames.tokens earlier)) + (empty : ∀ i : Fin 8, 2 ≤ i.val → i.val ≤ 6 → base (tape i) = []) + (bound : Nat) + (hretained : ∀ k ∈ earlier ++ [key], k.retained.length ≤ n) + (hIDs : ∀ k ∈ earlier ++ [key], ∀ entry ∈ k.retained, + KeyMetadataEncoding.entryID entry.2 ≤ bound) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels CanonicalDictionaryMachine.main), CanonicalDictionaryMachine.clean ambient, + base⟩ + (some ⟨done, CanonicalDictionaryMachine.clean ambient, + Function.update (Function.update base (tape 1) + (BinaryNameSearch.stream (CanonicalVertexNames.tokens (earlier ++ [key])))) (tape 7) + ((encodeWord (CanonicalOnlineNames.onlineID earlier key)).reverse ++ base (tape 7))⟩) + (3 * streamBound n bound (earlier.length + 1) ^ 2 + + 16 * streamBound n bound (earlier.length + 1) + 12) where + steps := steps earlier key + evals_in_steps := dictionaryTrace tape distinct labels done rejected program atLabels + base ambient earlier key keyWord dictionaryWord empty + steps_le_m := steps_le_metadata earlier key bound hretained hIDs + +end +end PerfectCompleteness.CanonicalDictionaryNames + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/CanonicalDirections.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/CanonicalDirections.lean new file mode 100644 index 0000000000000000000000000000000000000000..4fcc1525f52bbfabd778a652590a6e31ce1bf388 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/CanonicalDirections.lean @@ -0,0 +1,131 @@ +import OAI.Computability.PerfectCompleteness.Foundations.PrefixTests +import OAI.Computability.PerfectCompleteness.Reduction.PreliminaryLevelPair +import OAI.Computability.PerfectCompleteness.Sampling.CutSamplerReplayTransportLemmas +import OAI.Computability.PerfectCompleteness.Sampling.RationalFiniteLawLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.CanonicalDirections + +open RecursiveSpaces HierarchicalArrays PreliminarySampler +open UniqueGamesTheorem.Foundations.Games +open scoped Classical + +noncomputable section + +variable {branch : Nat → Nat} {n : Nat} + +abbrev Tuple (rows : Nat → Nat) (n : Nat) := + (level : Fin n) → PrefixTests.LevelDirection rows level + +def directionEquiv (rows : Nat → Nat) (leaf : Slots branch n) (level : Fin n) : + PrefixTests.LevelDirection rows level ≃ + BucketSampler.Direction (rows (Nodes.height (GeometricPath.nodeAtLevel leaf level))) := + (Equiv.cast (congrArg (fun height => BucketSampler.Direction (rows height)) + (GeometricPath.nodeAtLevel_height leaf level))).symm + +def tupleEquiv (rows : Nat → Nat) (leaf : Slots branch n) : + Tuple rows n ≃ CandidateCoupling.DirectionTuple rows leaf := + Equiv.piCongrRight (directionEquiv rows leaf) + +@[simp] theorem tupleEquiv_apply (rows : Nat → Nat) (leaf : Slots branch n) + (directions : Tuple rows n) (level : Fin n) : + tupleEquiv rows leaf directions level = directionEquiv rows leaf level (directions level) := rfl + +@[simp] theorem tupleEquiv_symm_apply (rows : Nat → Nat) (leaf : Slots branch n) + (directions : CandidateCoupling.DirectionTuple rows leaf) (level : Fin n) : + (tupleEquiv rows leaf).symm directions level = + (directionEquiv rows leaf level).symm (directions level) := rfl + +def levelLaw (rows : Nat → Nat) (hrows : ∀ k, 0 < rows (k + 1)) (level : Fin n) : + FiniteDistribution (PrefixTests.LevelDirection rows level) := by + letI := directionNonempty (rows (level.val + 1)) (hrows level.val) + exact FiniteDistribution.uniform _ + +def law (rows : Nat → Nat) (n : Nat) (hrows : ∀ k, 0 < rows (k + 1)) : + FiniteDistribution (Tuple rows n) := + FiniteProduct.law (levelLaw rows hrows) + +theorem directionLaw_toCanonical (rows : Nat → Nat) (leaf : Slots branch n) + (level : Fin n) (hrows : ∀ k, 0 < rows (k + 1)) : + (PreliminaryAveraging.directionLaw leaf level hrows).pushforward + (directionEquiv rows leaf level).symm = levelLaw rows hrows level := by + let : Nonempty (PrefixTests.LevelDirection rows level) := + directionNonempty (rows (level.val + 1)) (hrows level.val) + let : Nonempty (BucketSampler.Direction + (rows (Nodes.height (GeometricPath.nodeAtLevel leaf level)))) := + directionNonempty _ (by rw [GeometricPath.nodeAtLevel_height]; exact hrows level.val) + change (FiniteDistribution.uniform + (BucketSampler.Direction (rows (Nodes.height (GeometricPath.nodeAtLevel leaf level))))).pushforward + (directionEquiv rows leaf level).symm = + FiniteDistribution.uniform (PrefixTests.LevelDirection rows level) + rw [← FiniteDistribution.transport_eq_pushforward] + exact UniformConditioning.uniform_transport (directionEquiv rows leaf level).symm + +theorem directionsLaw_toCanonical (rows : Nat → Nat) (leaf : Slots branch n) + (hrows : ∀ k, 0 < rows (k + 1)) : + (CandidateCoupling.directionsLaw leaf hrows).pushforward (tupleEquiv rows leaf).symm = + law rows n hrows := by + change (FiniteProduct.law (fun level => PreliminaryAveraging.directionLaw leaf level hrows)).pushforward + (fun directions level => (directionEquiv rows leaf level).symm (directions level)) = _ + rw [FiniteProduct.pushforward_map] + apply congrArg (fun laws : (level : Fin n) → + FiniteDistribution (PrefixTests.LevelDirection rows level) => FiniteProduct.law laws) + funext level + exact directionLaw_toCanonical rows leaf level hrows + +theorem canonicalLaw_toDirections (rows : Nat → Nat) (leaf : Slots branch n) + (hrows : ∀ k, 0 < rows (k + 1)) : + (law rows n hrows).pushforward (tupleEquiv rows leaf) = + CandidateCoupling.directionsLaw leaf hrows := by + have h := congrArg + (fun μ : FiniteDistribution (Tuple rows n) => μ.pushforward (tupleEquiv rows leaf)) + (directionsLaw_toCanonical rows leaf hrows) + rw [FiniteDistribution.pushforward_comp] at h + have hid : (fun directions : CandidateCoupling.DirectionTuple rows leaf => + tupleEquiv rows leaf ((tupleEquiv rows leaf).symm directions)) = id := by + funext directions + exact (tupleEquiv rows leaf).apply_symm_apply directions + rw [hid, FiniteDistribution.pushforward_id] at h + exact h.symm + +@[simp] theorem choiceAt_toCanonical (rows : Nat → Nat) (leaf : Slots branch n) + (directions : CandidateCoupling.DirectionTuple rows leaf) (level : Fin n) : + PrefixTests.choiceAt rows leaf level ((tupleEquiv rows leaf).symm directions level) = + (⟨level, directions level⟩ : Choice rows leaf) := by + change (⟨level, directionEquiv rows leaf level + ((directionEquiv rows leaf level).symm (directions level))⟩ : Choice rows leaf) = _ + rw [Equiv.apply_symm_apply] + +variable {v m t : Nat} {rows repeats : Nat → Nat} + +theorem win_eq_observe_canonical (clauses : Fin m → SourceClause.NormalizedClause v) + (strategy : PreliminaryStrategy.Strategy clauses branch n t rows repeats) + (b : Base branch n t m) + (arrays : Arrays (HierarchicalArrays.sourceSlots clauses (endpoints b.1)) rows) + (directions : Tuple rows n) (level : Fin n) : + PreliminaryLevelPair.win clauses strategy level + ⟨b, arrays, tupleEquiv rows b.2 directions⟩ = + PreliminaryStrategy.observe clauses + (PreliminaryStrategy.extend clauses branch n t rows repeats strategy) b arrays + (PrefixTests.choiceAt rows b.2 level (directions level)) := rfl + +theorem win_eq_observe (clauses : Fin m → SourceClause.NormalizedClause v) + (strategy : PreliminaryStrategy.Strategy clauses branch n t rows repeats) + (level : Fin n) (e : CandidateCoupling.Shared clauses branch n t rows) : + PreliminaryLevelPair.win clauses strategy level e = + PreliminaryStrategy.observe clauses + (PreliminaryStrategy.extend clauses branch n t rows repeats strategy) e.1 e.2.1 + (PrefixTests.choiceAt rows e.1.2 level + ((tupleEquiv rows e.1.2).symm e.2.2 level)) := by + rw [choiceAt_toCanonical] + rfl + +end +end PerfectCompleteness.CanonicalDirections + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/CanonicalEdgesLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/CanonicalEdgesLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..9396e1e8dd42b08ccb18cc5c2cef8149da0efc83 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/CanonicalEdgesLemmas.lean @@ -0,0 +1,442 @@ +import Mathlib.Data.Fintype.Pi +import Mathlib.Data.Fintype.Sigma +import Mathlib.Tactic.DeriveFintype +import OAI.Computability.PerfectCompleteness.Foundations.CanonicalKeys + +namespace OAI + +section + +namespace PerfectCompleteness.CanonicalEdges + +open MixedSupport CanonicalKeys + +variable {n : Nat} {Y Z : Type*} + +noncomputable def coarsen (slots : Fin n → Slot) (f : Assignment slots → Y) + (p : Y → Z) (P : Label slots f) : Label slots (p ∘ f) := + evaluateLabel slots (p ∘ f) (ReducedPartition.representative (reduction slots f) f P) + +@[simp] theorem restore_coarsen (slots : Fin n → Slot) (f : Assignment slots → Y) + (p : Y → Z) (P : Label slots f) : + restore slots (p ∘ f) (coarsen slots f p P) = p (restore slots f P) := by + exact restore_evaluateLabel slots (p ∘ f) + (ReducedPartition.representative (reduction slots f) f P) + +theorem coarsen_eq_iff (slots : Fin n → Slot) (f : Assignment slots → Y) + (p : Y → Z) (P : Label slots f) (Q : Label slots (p ∘ f)) : + coarsen slots f p P = Q ↔ p (restore slots f P) = restore slots (p ∘ f) Q := by + constructor + · intro h + rw [← restore_coarsen slots f p P, h] + · intro h + apply restore_injective slots (p ∘ f) + exact (restore_coarsen slots f p P).trans h + +@[simp] theorem coarsen_evaluateLabel (slots : Fin n → Slot) + (f : Assignment slots → Y) (p : Y → Z) (x : Assignment slots) : + coarsen slots f p (evaluateLabel slots f x) = evaluateLabel slots (p ∘ f) x := by + apply (coarsen_eq_iff slots f p _ _).2 + rw [restore_evaluateLabel, restore_evaluateLabel] + rfl + +theorem coarsen_surjective (slots : Fin n → Slot) (f : Assignment slots → Y) + (p : Y → Z) : Function.Surjective (coarsen slots f p) := by + intro Q + refine ⟨evaluateLabel slots f + (ReducedPartition.representative (reduction slots (p ∘ f)) (p ∘ f) Q), ?_⟩ + rw [coarsen_evaluateLabel] + exact ReducedPartition.label_representative (reduction slots (p ∘ f)) (p ∘ f) Q + +theorem card_coarsen_fiber_le [Finite Y] (slots : Fin n → Slot) + (f : Assignment slots → Y) (p : Y → Z) (Q : Label slots (p ∘ f)) : + Nat.card {P : Label slots f // coarsen slots f p P = Q} ≤ + Nat.card {y : Y // p y = restore slots (p ∘ f) Q} := by + let restoreFiber : {P : Label slots f // coarsen slots f p P = Q} → + {y : Y // p y = restore slots (p ∘ f) Q} := + fun P => ⟨restore slots f P.val, (coarsen_eq_iff slots f p P.val Q).1 P.property⟩ + apply Nat.card_le_card_of_injective restoreFiber + intro P P' h + apply Subtype.ext + apply restore_injective slots f + exact congrArg Subtype.val h + +theorem coarsen_at_most_two [Finite Y] (slots : Fin n → Slot) + (f : Assignment slots → Y) (p : Y → Z) + (hp : ∀ z, Nat.card {y : Y // p y = z} ≤ 2) (Q : Label slots (p ∘ f)) : + Nat.card {P : Label slots f // coarsen slots f p P = Q} ≤ 2 := + (card_coarsen_fiber_le slots f p Q).trans (hp (restore slots (p ∘ f) Q)) + +theorem binaryDeletion_at_most_two [Finite Y] (slots : Fin n → Slot) + (f : Assignment slots → Bool × Y) (Q : Label slots (Prod.snd ∘ f)) : + Nat.card {P : Label slots f // coarsen slots f Prod.snd P = Q} ≤ 2 := by + apply coarsen_at_most_two slots f Prod.snd + intro y + exact (CanonicalPartition.card_binaryDeletion_fiber y).le + +theorem coarsen_transportLabel {slots projected : Fin n → Slot} + (π : ∀ i, Projection (slots i) (projected i)) (f : Assignment projected → Y) + (p : Y → Z) (P : Label slots (f ∘ projectionMap π)) : + transportLabel π (p ∘ f) (coarsen slots (f ∘ projectionMap π) p P) = + coarsen projected f p (transportLabel π f P) := by + apply restore_injective projected (p ∘ f) + calc + restore projected (p ∘ f) + (transportLabel π (p ∘ f) (coarsen slots (f ∘ projectionMap π) p P)) = + restore slots ((p ∘ f) ∘ projectionMap π) + (coarsen slots (f ∘ projectionMap π) p P) := + (restore_projection π (p ∘ f) _).symm + _ = p (restore slots (f ∘ projectionMap π) P) := + restore_coarsen slots (f ∘ projectionMap π) p P + _ = p (restore projected f (transportLabel π f P)) := + congrArg p (restore_projection π f P) + _ = restore projected (p ∘ f) (coarsen projected f p (transportLabel π f P)) := + (restore_coarsen projected f p (transportLabel π f P)).symm + +end PerfectCompleteness.CanonicalEdges + +end + +section + +namespace PerfectCompleteness.CanonicalKeyShape + +open ClauseSupport MixedSupport +open scoped Classical + +noncomputable section + +inductive Shape where + | clause (signs : SourceClause.Triple) + | bit + deriving DecidableEq, Fintype + +def erase : Slot → Shape + | .clause _ _ signs => .clause signs + | .bit _ => .bit + +def dummy : Shape → Slot + | .clause signs => .clause 0 (fun _ => 0) signs + | .bit => .bit 0 + +@[simp] theorem erase_dummy (s : Shape) : erase (dummy s) = s := by + cases s <;> rfl + +def domainEquiv (s : Slot) : s.Domain ≃ (dummy (erase s)).Domain := by + cases s <;> exact Equiv.refl _ + +instance dummyDomainFintype (s : Shape) : Fintype (dummy s).Domain := by + cases s <;> dsimp [dummy, Slot.Domain] <;> infer_instance + +def shape {I : Type*} (slots : I → Slot) : I → Shape := fun i => erase (slots i) + +def dummySlots {I : Type*} (shapes : I → Shape) : I → Slot := fun i => dummy (shapes i) + +instance dummyAssignmentFintype {I : Type*} [Fintype I] [DecidableEq I] + (shapes : I → Shape) : Fintype (Assignment (dummySlots shapes)) := by + change Fintype (∀ i : I, (dummy (shapes i)).Domain) + infer_instance + +def assignmentEquiv {I : Type*} (slots : I → Slot) : + Assignment slots ≃ Assignment (dummySlots (shape slots)) where + toFun x i := domainEquiv (slots i) (x i) + invFun x i := (domainEquiv (slots i)).symm (x i) + left_inv x := by funext i; exact (domainEquiv (slots i)).symm_apply_apply (x i) + right_inv x := by funext i; exact (domainEquiv (slots i)).apply_symm_apply (x i) + +@[simp] theorem assignmentEquiv_apply {I : Type*} (slots : I → Slot) + (x : Assignment slots) (i : I) : + assignmentEquiv slots x i = domainEquiv (slots i) (x i) := rfl + +def transport {I Y : Type*} (slots : I → Slot) (f : Assignment slots → Y) : + Assignment (dummySlots (shape slots)) → Y := f ∘ (assignmentEquiv slots).symm + +@[simp] theorem transport_apply {I Y : Type*} (slots : I → Slot) + (f : Assignment slots → Y) (x : Assignment slots) : + transport slots f (assignmentEquiv slots x) = f x := by + simp only [transport, Function.comp_apply, Equiv.symm_apply_apply] + +theorem assignmentEquiv_update {I : Type*} [DecidableEq I] + (slots : I → Slot) (x : Assignment slots) (i : I) (u : (slots i).Domain) : + assignmentEquiv slots (Function.update x i u) = + Function.update (assignmentEquiv slots x) i (domainEquiv (slots i) u) := by + funext j + exact Function.apply_update (fun i => domainEquiv (slots i)) x i u j + +theorem sectionFunction_erasure {I Y : Type*} [DecidableEq I] + (slots : I → Slot) (f : Assignment slots → Y) (i : I) : + sectionFunction slots f i = + pull (sectionFunction (dummySlots (shape slots)) (transport slots f) i) + (assignmentEquiv slots) (domainEquiv (slots i)) := by + funext context u + change f (Function.update context i u) = + f ((assignmentEquiv slots).symm + (Function.update (assignmentEquiv slots context) i (domainEquiv (slots i) u))) + rw [← assignmentEquiv_update, Equiv.symm_apply_apply] + +theorem localReduction_erasure {C C' Y : Type*} (s : Slot) + (f : C → (dummy (erase s)).Domain → Y) (context : C' → C) + (hcontext : Function.Surjective context) (u : s.Domain) : + localReduction s (pull f context (domainEquiv s)) u = + localReduction (dummy (erase s)) f (domainEquiv s u) := by + cases s with + | clause occurrence variableIDs signs => + exact unprojected_clause_reduction_eq f context hcontext u + | bit variableID => + exact unprojected_bit_reduction_eq f context hcontext u + +theorem reduction_erasure {I Y : Type*} [DecidableEq I] + (slots : I → Slot) (f : Assignment slots → Y) (x : Assignment slots) : + reduction slots f x = + reduction (dummySlots (shape slots)) (transport slots f) (assignmentEquiv slots x) := by + funext i + change localReduction (slots i) (sectionFunction slots f i) (x i) = _ + rw [sectionFunction_erasure] + exact localReduction_erasure (slots i) + (sectionFunction (dummySlots (shape slots)) (transport slots f) i) + (assignmentEquiv slots) (assignmentEquiv slots).surjective (x i) + +theorem partition_erasure {n : Nat} {Y : Type*} + (slots : Fin n → Slot) (f : Assignment slots → Y) : + CanonicalKeys.partition slots f = + CanonicalKeys.partition (dummySlots (shape slots)) (transport slots f) := by + exact ReducedPartition.parts_eq_of_pullback (assignmentEquiv slots) + (assignmentEquiv slots).surjective + (reduction slots f) (reduction (dummySlots (shape slots)) (transport slots f)) + f (transport slots f) (reduction_erasure slots f) + (fun x => (transport_apply slots f x).symm) + +inductive SupportMode where + | dropped + | clauseBit (position : Fin 3) + | full + | bit + deriving DecidableEq, Fintype + +def mode {C Y : Type*} (s : Slot) : (C → s.Domain → Y) → SupportMode := + match s with + | .clause _ _ _ => fun f => + match clauseMode f with + | .dropped => .dropped + | .bit i => .clauseBit i + | .full => .full + | .bit _ => fun f => if Unused f then .dropped else .bit + +def recover : Slot → SupportMode → SlotKey + | .clause _ variableIDs _, .clauseBit i => .bit (variableIDs i) + | .clause occurrence _ signs, .full => .full occurrence signs + | .bit variableID, .bit => .bit variableID + | _, _ => .dropped + +theorem localKey_recover {C Y : Type*} (s : Slot) (f : C → s.Domain → Y) : + localKey s f = recover s (mode s f) := by + cases s with + | clause occurrence variableIDs signs => + cases hmode : clauseMode f <;> + simp only [localKey, clauseKey, mode, hmode, recover] + | bit variableID => + change C → Bool → Y at f + change (if Unused f then SlotKey.dropped else SlotKey.bit variableID) = + recover (.bit variableID) (if Unused f then SupportMode.dropped else SupportMode.bit) + by_cases h : Unused f <;> simp only [h, ite_true, ite_false, recover] + +theorem mode_erasure {C C' Y : Type*} (s : Slot) + (f : C → (dummy (erase s)).Domain → Y) (context : C' → C) + (hcontext : Function.Surjective context) : + mode s (pull f context (domainEquiv s)) = mode (dummy (erase s)) f := by + cases s with + | clause occurrence variableIDs signs => + change C → Answer signs → Y at f + change (match clauseMode (pull f context id) with + | .dropped => SupportMode.dropped + | .bit i => SupportMode.clauseBit i + | .full => SupportMode.full) = _ + rw [unprojected_mode_eq f context hcontext] + rfl + | bit variableID => + change C → Bool → Y at f + change (if Unused (pull f context id) then SupportMode.dropped else SupportMode.bit) = + (if Unused f then SupportMode.dropped else SupportMode.bit) + rw [unused_pull_iff f context id hcontext Function.surjective_id] + +def modes {I Y : Type*} [DecidableEq I] (slots : I → Slot) + (f : Assignment slots → Y) : I → SupportMode := + fun i => mode (slots i) (sectionFunction slots f i) + +theorem modes_erasure {I Y : Type*} [DecidableEq I] + (slots : I → Slot) (f : Assignment slots → Y) : + modes slots f = modes (dummySlots (shape slots)) (transport slots f) := by + funext i + unfold modes + rw [sectionFunction_erasure] + exact mode_erasure (slots i) + (sectionFunction (dummySlots (shape slots)) (transport slots f) i) + (assignmentEquiv slots) (assignmentEquiv slots).surjective + +theorem keyFields_recover {I Y : Type*} [DecidableEq I] + (slots : I → Slot) (f : Assignment slots → Y) : + keyFields slots f = fun i => + recover (slots i) (modes (dummySlots (shape slots)) (transport slots f) i) := by + have hm := modes_erasure slots f + funext i + change localKey (slots i) (sectionFunction slots f i) = _ + rw [localKey_recover] + change recover (slots i) (modes slots f i) = _ + rw [hm] + +def retained {n : Nat} (slots : Fin n → Slot) (support : Fin n → SupportMode) : + List (Fin n × SlotKey) := + ((List.finRange n).map (fun i => (i, recover (slots i) (support i)))).filter + (fun entry => decide (entry.2 ≠ .dropped)) + +theorem retainedKeys_recover {n : Nat} {Y : Type*} + (slots : Fin n → Slot) (f : Assignment slots → Y) : + retainedKeys slots f = + retained slots (modes (dummySlots (shape slots)) (transport slots f)) := by + simp only [retainedKeys, keyFields_recover, retained] + +abbrev Input (n k : Nat) := + Σ shapes : Fin n → Shape, Assignment (dummySlots shapes) → Fin k + +instance inputFintype (n k : Nat) : Fintype (Input n k) := by + unfold Input + infer_instance + +def input {n k : Nat} (slots : Fin n → Slot) (f : Assignment slots → Fin k) : Input n k := + ⟨shape slots, transport slots f⟩ + +def inputPartition {n k : Nat} (data : Input n k) : + Set (Set (Fin n → ReducedValue)) := + CanonicalKeys.partition (dummySlots data.1) data.2 + +def inputModes {n k : Nat} (data : Input n k) : Fin n → SupportMode := + modes (dummySlots data.1) data.2 + +theorem inputPartition_eq {n k : Nat} (slots : Fin n → Slot) + (f : Assignment slots → Fin k) : + inputPartition (input slots f) = CanonicalKeys.partition slots f := + (partition_erasure slots f).symm + +theorem inputModes_recover {n k : Nat} (slots : Fin n → Slot) + (f : Assignment slots → Fin k) : + retained slots (inputModes (input slots f)) = retainedKeys slots f := + (retainedKeys_recover slots f).symm + +end +end PerfectCompleteness.CanonicalKeyShape + +end + +section + +namespace PerfectCompleteness.SourceKeys + +open SourceClause MixedSupport CanonicalKeys + +variable {v m n : Nat} {I Y Z : Type*} + +inductive Endpoint (v m : Nat) where + | clause (occurrence : Fin m) + | variable (variableID : Fin v) + deriving DecidableEq + +def slot (clauses : Fin m → NormalizedClause v) : Endpoint v m → Slot + | .clause c => .clause c.val (fun i => ((clauses c).variable i).val) (clauses c).signs + | .variable j => .bit j.val + +inductive Step (clauses : Fin m → NormalizedClause v) : + Endpoint v m → Endpoint v m → Type + | keep (s : Endpoint v m) : Step clauses s s + | select (c : Fin m) (position : Fin 3) : + Step clauses (.clause c) (.variable ((clauses c).variable position)) + +def Step.projection {clauses : Fin m → NormalizedClause v} + {s t : Endpoint v m} : Step clauses s t → Projection (slot clauses s) (slot clauses t) + | .keep s => .keep (slot clauses s) + | .select c i => .select c.val (fun j => ((clauses c).variable j).val) (clauses c).signs i + +def stepProjection {clauses : Fin m → NormalizedClause v} + {source target : I → Endpoint v m} (steps : ∀ i, Step clauses (source i) (target i)) : + ∀ i, Projection (slot clauses (source i)) (slot clauses (target i)) := + fun i => (steps i).projection + +theorem key_step (side : Side) (clauses : Fin m → NormalizedClause v) + {source target : Fin n → Endpoint v m} + (steps : ∀ i, Step clauses (source i) (target i)) + (f : Assignment (slot clauses ∘ target) → Y) : + key side (slot clauses ∘ source) (f ∘ projectionMap (stepProjection steps)) = + key side (slot clauses ∘ target) f := + key_projection side (stepProjection steps) f + +def endpointValue (clauses : Fin m → NormalizedClause v) (assignment : Fin v → Bool) + (hsat : ∀ c, (clauses c).clause.eval assignment = true) : + (s : Endpoint v m) → (slot clauses s).Domain + | .clause c => ⟨(clauses c).restrict assignment, by + apply (mem_satisfyingTriples (clauses c).signs _).2 + rw [localEval_restrict] + exact hsat c⟩ + | .variable j => assignment j + +theorem coordinate_restrict (c : NormalizedClause v) (assignment : Fin v → Bool) + (i : Fin 3) : (c.restrict assignment).at i = assignment (c.variable i) := by + refine Fin.cases (by rfl) (fun j => ?_) i + refine Fin.cases (by rfl) (fun k => ?_) j + have hk : k = 0 := Subsingleton.elim _ _ + subst k + rfl + +theorem endpointValue_projection (clauses : Fin m → NormalizedClause v) + (assignment : Fin v → Bool) (hsat : ∀ c, (clauses c).clause.eval assignment = true) + {s t : Endpoint v m} (step : Step clauses s t) : + step.projection.map (endpointValue clauses assignment hsat s) = + endpointValue clauses assignment hsat t := by + cases step with + | keep s => rfl + | select c i => exact coordinate_restrict (clauses c) assignment i + +def realizingAssignment (clauses : Fin m → NormalizedClause v) + (assignment : Fin v → Bool) (hsat : ∀ c, (clauses c).clause.eval assignment = true) + (endpoints : I → Endpoint v m) : Assignment (slot clauses ∘ endpoints) := + fun i => endpointValue clauses assignment hsat (endpoints i) + +theorem realizingAssignment_projection (clauses : Fin m → NormalizedClause v) + (assignment : Fin v → Bool) (hsat : ∀ c, (clauses c).clause.eval assignment = true) + {source target : I → Endpoint v m} + (steps : ∀ i, Step clauses (source i) (target i)) : + projectionMap (stepProjection steps) (realizingAssignment clauses assignment hsat source) = + realizingAssignment clauses assignment hsat target := by + funext i + exact endpointValue_projection clauses assignment hsat (steps i) + +theorem evaluated_label_step (clauses : Fin m → NormalizedClause v) + (assignment : Fin v → Bool) (hsat : ∀ c, (clauses c).clause.eval assignment = true) + {source target : Fin n → Endpoint v m} + (steps : ∀ i, Step clauses (source i) (target i)) + (f : Assignment (slot clauses ∘ target) → Y) : + transportLabel (stepProjection steps) f + (evaluateLabel (slot clauses ∘ source) (f ∘ projectionMap (stepProjection steps)) + (realizingAssignment clauses assignment hsat source)) = + evaluateLabel (slot clauses ∘ target) f + (realizingAssignment clauses assignment hsat target) := by + exact (evaluateLabel_projection (slots := slot clauses ∘ source) + (projected := slot clauses ∘ target) (stepProjection steps) f + (realizingAssignment clauses assignment hsat source)).trans + (congrArg (evaluateLabel (slot clauses ∘ target) f) + (realizingAssignment_projection clauses assignment hsat steps)) + +theorem evaluated_label_satisfies (clauses : Fin m → NormalizedClause v) + (assignment : Fin v → Bool) (hsat : ∀ c, (clauses c).clause.eval assignment = true) + (endpoints : Fin n → Endpoint v m) (f : Assignment (slot clauses ∘ endpoints) → Y) + (p : Y → Z) : + CanonicalEdges.coarsen (slot clauses ∘ endpoints) f p + (evaluateLabel (slot clauses ∘ endpoints) f + (realizingAssignment clauses assignment hsat endpoints)) = + evaluateLabel (slot clauses ∘ endpoints) (p ∘ f) + (realizingAssignment clauses assignment hsat endpoints) := + CanonicalEdges.coarsen_evaluateLabel _ f p _ + +end PerfectCompleteness.SourceKeys + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/CanonicalKeys.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/CanonicalKeys.lean new file mode 100644 index 0000000000000000000000000000000000000000..bfe32d1dfc9540209a129eabbc461740f5f05ae6 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/CanonicalKeys.lean @@ -0,0 +1,128 @@ +import OAI.Computability.PerfectCompleteness.Foundations.RecursiveSpaceEquivLemmas +import OAI.Computability.PerfectCompleteness.Foundations.ReducedDomains + +namespace OAI + +section + +namespace PerfectCompleteness.CanonicalKeys + +open ClauseSupport MixedSupport + +variable {n : Nat} {Y : Type*} + +inductive Side where + | left + | right + deriving DecidableEq + +structure Key (n : Nat) where + side : Side + retained : List (Fin n × SlotKey) + partition : Set (Set (Fin n → ReducedValue)) + +noncomputable def partition (slots : Fin n → Slot) (f : Assignment slots → Y) : + Set (Set (Fin n → ReducedValue)) := + ReducedPartition.parts (reduction slots f) f + +noncomputable def key (side : Side) (slots : Fin n → Slot) + (f : Assignment slots → Y) : Key n := + ⟨side, retainedKeys slots f, partition slots f⟩ + +theorem constantOnFibers (slots : Fin n → Slot) (f : Assignment slots → Y) : + ReducedPartition.ConstantOnFibers (reduction slots f) f := by + intro x x' h + exact constant_on_reduction_fibers slots f h + +theorem covered_iff_legal (slots : Fin n → Slot) (f : Assignment slots → Y) + (values : Fin n → ReducedValue) : + (∃ P ∈ partition slots f, values ∈ P) ↔ + values ∈ ReducedDomains.legalAssignments (keyFields slots f) := by + rw [← ReducedDomains.range_reduction slots f] + exact ReducedPartition.covered_iff_mem_range (reduction slots f) f values + +theorem legal_domain_projection {slots projected : Fin n → Slot} + (p : ∀ i, Projection (slots i) (projected i)) (f : Assignment projected → Y) : + ReducedDomains.legalAssignments (keyFields slots (f ∘ projectionMap p)) = + ReducedDomains.legalAssignments (keyFields projected f) := by + rw [keyFields_projection] + +theorem partition_projection {slots projected : Fin n → Slot} + (p : ∀ i, Projection (slots i) (projected i)) (f : Assignment projected → Y) : + partition slots (f ∘ projectionMap p) = partition projected f := by + exact ReducedPartition.parts_eq_of_pullback + (projectionMap p) (projectionMap_surjective p) + (reduction slots (f ∘ projectionMap p)) (reduction projected f) + (f ∘ projectionMap p) f (reduction_projection p f) (fun _ => rfl) + +theorem key_projection (side : Side) {slots projected : Fin n → Slot} + (p : ∀ i, Projection (slots i) (projected i)) (f : Assignment projected → Y) : + key side slots (f ∘ projectionMap p) = key side projected f := by + simp only [key, retainedKeys_projection, partition_projection] + +abbrev Label (slots : Fin n → Slot) (f : Assignment slots → Y) := + ReducedPartition.Part (reduction slots f) f + +noncomputable def evaluateLabel (slots : Fin n → Slot) (f : Assignment slots → Y) + (x : Assignment slots) : Label slots f := + ReducedPartition.label (reduction slots f) f x + +noncomputable def restore (slots : Fin n → Slot) (f : Assignment slots → Y) + (P : Label slots f) : Y := + ReducedPartition.output (reduction slots f) f P + +@[simp] theorem restore_evaluateLabel (slots : Fin n → Slot) + (f : Assignment slots → Y) (x : Assignment slots) : + restore slots f (evaluateLabel slots f x) = f x := + ReducedPartition.output_label (reduction slots f) f (constantOnFibers slots f) x + +theorem restore_injective (slots : Fin n → Slot) (f : Assignment slots → Y) : + Function.Injective (restore slots f) := + ReducedPartition.output_injective (reduction slots f) f + +noncomputable def transportLabel {slots projected : Fin n → Slot} + (p : ∀ i, Projection (slots i) (projected i)) (f : Assignment projected → Y) + (P : Label slots (f ∘ projectionMap p)) : Label projected f := + ⟨P.val, by + change P.val ∈ partition projected f + rw [← partition_projection p f] + exact P.property⟩ + +theorem transportLabel_bijective {slots projected : Fin n → Slot} + (p : ∀ i, Projection (slots i) (projected i)) (f : Assignment projected → Y) : + Function.Bijective (transportLabel p f) := by + constructor + · intro P Q h + exact Subtype.ext (congrArg (fun R : Label projected f => R.val) h) + · intro Q + have hQ : Q.val ∈ partition slots (f ∘ projectionMap p) := by + rw [partition_projection p f] + exact Q.property + exact ⟨⟨Q.val, hQ⟩, Subtype.ext rfl⟩ + +theorem evaluateLabel_projection {slots projected : Fin n → Slot} + (p : ∀ i, Projection (slots i) (projected i)) (f : Assignment projected → Y) + (x : Assignment slots) : + transportLabel p f (evaluateLabel slots (f ∘ projectionMap p) x) = + evaluateLabel projected f (projectionMap p x) := by + apply Subtype.ext + exact ReducedPartition.fiber_eq_of_pullback + (projectionMap p) (projectionMap_surjective p) + (reduction slots (f ∘ projectionMap p)) (reduction projected f) + (f ∘ projectionMap p) f (reduction_projection p f) (fun _ => rfl) x + +theorem restore_projection {slots projected : Fin n → Slot} + (p : ∀ i, Projection (slots i) (projected i)) (f : Assignment projected → Y) + (P : Label slots (f ∘ projectionMap p)) : + restore slots (f ∘ projectionMap p) P = + restore projected f (transportLabel p f P) := by + exact ReducedPartition.output_eq_of_shared_part + (projectionMap p) (reduction slots (f ∘ projectionMap p)) (reduction projected f) + (f ∘ projectionMap p) f (reduction_projection p f) (fun _ => rfl) + (constantOnFibers projected f) P (transportLabel p f P) rfl + +end PerfectCompleteness.CanonicalKeys + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/CanonicalPartialTable.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/CanonicalPartialTable.lean new file mode 100644 index 0000000000000000000000000000000000000000..9ca75c311df7a6725204afee5e5fea5624b97b35 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/CanonicalPartialTable.lean @@ -0,0 +1,182 @@ +import OAI.Computability.PerfectCompleteness.Construction.LocalCompletionFamily +import OAI.Computability.PerfectCompleteness.Foundations.CanonicalCoarseningErasure + +namespace OAI + +section + +namespace PerfectCompleteness.CanonicalPartialTable + +open MixedSupport CanonicalKeys CanonicalKeyShape CanonicalEdges CanonicalLabelEncoding +open scoped Classical + +noncomputable section + +abbrev Input (n k l : Nat) := + Σ shapes : Fin n → Shape, + (Assignment (dummySlots shapes) → Fin k) × (Fin k → Fin l) + +instance inputFintype (n k l : Nat) : Fintype (Input n k l) := by + unfold Input + infer_instance + +variable {n k l q : Nat} + +def slots (data : Input n k l) : Fin n → Slot := dummySlots data.1 + +def joint (data : Input n k l) : Assignment (slots data) → Fin k := data.2.1 + +def outputMap (data : Input n k l) : Fin k → Fin l := data.2.2 + +def leftKey (data : Input n k l) : Key n := key .left (slots data) (joint data) + +def rightKey (data : Input n k l) : Key n := + key .right (slots data) (outputMap data ∘ joint data) + +theorem left_large (large : CanonicalKeyEncoding.partitionWidth n ≤ q) : + CanonicalKeyEncoding.partitionWidth n ≤ 2 * q := by omega + +def leftEmbedding (large : CanonicalKeyEncoding.partitionWidth n ≤ q) + (data : Input n k l) : Label (slots data) (joint data) ↪ Fin (2 * q) := + labelEmbedding (leftKey data) (left_large large) + +def rightEmbedding (large : CanonicalKeyEncoding.partitionWidth n ≤ q) + (data : Input n k l) : Label (slots data) (outputMap data ∘ joint data) ↪ Fin q := + labelEmbedding (rightKey data) large + +def image (hq : 0 < q) (large : CanonicalKeyEncoding.partitionWidth n ≤ q) + (data : Input n k l) (a : Fin (2 * q)) : Fin q := + if h : a ∈ Set.range (leftEmbedding large data) then + rightEmbedding large data + (coarsen (slots data) (joint data) (outputMap data) h.choose) + else ⟨0, hq⟩ + +def lookup (hq : 0 < q) (large : CanonicalKeyEncoding.partitionWidth n ≤ q) + (data : Input n k l) : LocalCompletionFamily.Input q := + (paddedMask (leftKey data), image hq large data) + +@[simp] theorem lookup_mask (hq : 0 < q) + (large : CanonicalKeyEncoding.partitionWidth n ≤ q) (data : Input n k l) : + (lookup hq large data).1 = paddedMask (leftKey data) := rfl + +theorem mask_true (hq : 0 < q) (large : CanonicalKeyEncoding.partitionWidth n ≤ q) + (data : Input n k l) (a : Fin (2 * q)) : + (lookup hq large data).1 a = true ↔ a ∈ Set.range (leftEmbedding large data) := + paddedMask_eq_true_iff (leftKey data) (left_large large) a + +theorem image_legal (hq : 0 < q) (large : CanonicalKeyEncoding.partitionWidth n ≤ q) + (data : Input n k l) (P : Label (slots data) (joint data)) : + (lookup hq large data).2 (leftEmbedding large data P) = + rightEmbedding large data (coarsen (slots data) (joint data) (outputMap data) P) := by + have h : leftEmbedding large data P ∈ Set.range (leftEmbedding large data) := ⟨P, rfl⟩ + have hchosen : h.choose = P := (leftEmbedding large data).injective h.choose_spec + change image hq large data (leftEmbedding large data P) = _ + rw [image, dite_eq_left h, hchosen] + +theorem image_illegal (hq : 0 < q) (large : CanonicalKeyEncoding.partitionWidth n ≤ q) + (data : Input n k l) (a : Fin (2 * q)) + (hillegal : (lookup hq large data).1 a ≠ true) : + (lookup hq large data).2 a = ⟨0, hq⟩ := by + have h : a ∉ Set.range (leftEmbedding large data) := by + intro ha + exact hillegal ((mask_true hq large data a).2 ha) + exact dite_eq_right h + +def legalEquiv (hq : 0 < q) (large : CanonicalKeyEncoding.partitionWidth n ≤ q) + (data : Input n k l) : + Label (slots data) (joint data) ≃ LocalCompletionFamily.Legal (lookup hq large data) where + toFun P := ⟨leftEmbedding large data P, + (mask_true hq large data _).2 ⟨P, rfl⟩⟩ + invFun a := ((mask_true hq large data a.val).1 a.property).choose + left_inv P := (leftEmbedding large data).injective + ((mask_true hq large data _).1 + ((mask_true hq large data _).2 ⟨P, rfl⟩)).choose_spec + right_inv a := Subtype.ext ((mask_true hq large data a.val).1 a.property).choose_spec + +@[simp] theorem legalEquiv_val (hq : 0 < q) + (large : CanonicalKeyEncoding.partitionWidth n ≤ q) + (data : Input n k l) (P : Label (slots data) (joint data)) : + (legalEquiv hq large data P).val = leftEmbedding large data P := rfl + +theorem admissible (hq : 0 < q) (large : CanonicalKeyEncoding.partitionWidth n ≤ q) + (data : Input n k l) + (hsmall : ∀ Q, Nat.card {P : Label (slots data) (joint data) // + coarsen (slots data) (joint data) (outputMap data) P = Q} ≤ 2) : + LocalCompletionFamily.Admissible (lookup hq large data) := by + let : Fintype (Label (slots data) (joint data)) := Fintype.ofFinite _ + intro b + let fibers : + {P : Label (slots data) (joint data) // rightEmbedding large data + (coarsen (slots data) (joint data) (outputMap data) P) = b} ≃ + {a : LocalCompletionFamily.Legal (lookup hq large data) // + (lookup hq large data).2 a.val = b} := + (legalEquiv hq large data).subtypeEquiv (fun P => by + rw [legalEquiv_val, image_legal]) + have hcard := Nat.card_congr fibers + have hbound := CompletionSoundness.LegalProjectionGame.embedded_fiber_le_two + (rightEmbedding large data) (coarsen (slots data) (joint data) (outputMap data)) + (by intro Q; simpa only [← Nat.card_eq_fintype_card] using hsmall Q) b + simp only [← Nat.card_eq_fintype_card] at hcard hbound ⊢ + exact hcard.symm.le.trans hbound + +theorem admissible_of_output_fibers (hq : 0 < q) + (large : CanonicalKeyEncoding.partitionWidth n ≤ q) (data : Input n k l) + (hsmall : ∀ b, Nat.card {a : Fin k // outputMap data a = b} ≤ 2) : + LocalCompletionFamily.Admissible (lookup hq large data) := + admissible hq large data + (coarsen_at_most_two (slots data) (joint data) (outputMap data) hsmall) + +def input (sourceSlots : Fin n → Slot) (f : Assignment sourceSlots → Fin k) + (p : Fin k → Fin l) : Input n k l := + ⟨shape sourceSlots, transport sourceSlots f, p⟩ + +@[simp] theorem leftEmbedding_input (large : CanonicalKeyEncoding.partitionWidth n ≤ q) + (sourceSlots : Fin n → Slot) (f : Assignment sourceSlots → Fin k) + (p : Fin k → Fin l) (P : Label sourceSlots f) : + leftEmbedding large (input sourceSlots f p) + (CanonicalCoarseningErasure.transportLabel sourceSlots f P) = + labelEmbedding (key .left sourceSlots f) (left_large large) P := rfl + +theorem lookup_mask_actual (hq : 0 < q) + (large : CanonicalKeyEncoding.partitionWidth n ≤ q) + (sourceSlots : Fin n → Slot) (f : Assignment sourceSlots → Fin k) + (p : Fin k → Fin l) : + (lookup hq large (input sourceSlots f p)).1 = paddedMask (key .left sourceSlots f) := by + funext a + change paddedMask (key .left (dummySlots (shape sourceSlots)) (transport sourceSlots f)) a = _ + simp only [paddedMask, key, ← partition_erasure sourceSlots f] + +theorem mask_actual_true (hq : 0 < q) + (large : CanonicalKeyEncoding.partitionWidth n ≤ q) + (sourceSlots : Fin n → Slot) (f : Assignment sourceSlots → Fin k) + (p : Fin k → Fin l) (a : Fin (2 * q)) : + (lookup hq large (input sourceSlots f p)).1 a = true ↔ + a ∈ Set.range (labelEmbedding (key .left sourceSlots f) (left_large large)) := by + rw [lookup_mask_actual] + exact paddedMask_eq_true_iff (key .left sourceSlots f) (left_large large) a + +theorem image_actual_legal (hq : 0 < q) + (large : CanonicalKeyEncoding.partitionWidth n ≤ q) + (sourceSlots : Fin n → Slot) (f : Assignment sourceSlots → Fin k) + (p : Fin k → Fin l) (P : Label sourceSlots f) : + (lookup hq large (input sourceSlots f p)).2 + (labelEmbedding (key .left sourceSlots f) (left_large large) P) = + labelEmbedding (key .right sourceSlots (p ∘ f)) large (coarsen sourceSlots f p P) := by + have h := image_legal hq large (input sourceSlots f p) + (CanonicalCoarseningErasure.transportLabel sourceSlots f P) + rw [leftEmbedding_input] at h + refine h.trans ?_ + apply Fin.ext + change (CanonicalKeyEncoding.partEnum n + (coarsen (dummySlots (shape sourceSlots)) (transport sourceSlots f) p + (CanonicalCoarseningErasure.transportLabel sourceSlots f P)).val).val = + (CanonicalKeyEncoding.partEnum n (coarsen sourceSlots f p P).val).val + exact congrArg (fun a : Fin (CanonicalKeyEncoding.partitionWidth n) => a.val) + (CanonicalCoarseningErasure.partIndex_coarsen sourceSlots f p P).symm + +end +end PerfectCompleteness.CanonicalPartialTable + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/CanonicalVertexNames.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/CanonicalVertexNames.lean new file mode 100644 index 0000000000000000000000000000000000000000..12940a587e7699f551f076305a9e264d1750cd94 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/CanonicalVertexNames.lean @@ -0,0 +1,178 @@ +import OAI.Computability.PerfectCompleteness.Machines.BinaryNameSearch +import OAI.Computability.PerfectCompleteness.Machines.FiniteBlockMachineLemmas + +namespace OAI + + +namespace PerfectCompleteness.CanonicalVertexNames + +open CanonicalKeys +open Turing +open UniqueGamesTheorem.Foundations.Complexity +open MachineComposition +open UniqueGamesTheorem.Reduction.MachineTransfer + +noncomputable section + +variable {n : Nat} + +def payload (key : Key n) : List Bool := CanonicalKeyEncoding.bits key ++ [true] + +theorem payload_injective (n : Nat) : Function.Injective (payload (n := n)) := by + intro a b h + exact CanonicalKeyEncoding.bits_injective n (List.append_cancel_right h) + +private theorem finalDigit_append_true (bits : List Bool) (previous : Option Bool) : + BinaryNameMachine.finalDigit (bits ++ [true]) previous = some true := by + induction bits generalizing previous with + | nil => rfl + | cons bit bits ih => exact ih (some bit) + +@[simp] theorem payload_canonical (key : Key n) : + BinaryNameMachine.canonical (payload key) = true := by + simp [payload, BinaryNameMachine.canonical, finalDigit_append_true] + +@[simp] theorem payload_length (key : Key n) : + (payload key).length = (CanonicalKeyEncoding.bits key).length + 1 := by + simp only [payload, List.length_append, List.length_cons, List.length_nil] + +def tokens (keys : List (Key n)) : List BinaryNameSearch.Token := + keys.map (fun key => (false, payload key)) + +@[simp] theorem tokens_length (keys : List (Key n)) : + (tokens keys).length = keys.length := by + simp only [tokens, List.length_map] + +@[simp] theorem tokens_payloads (keys : List (Key n)) : + BinaryNameSearch.payloads (tokens keys) = keys.map payload := by + simp only [BinaryNameSearch.payloads, tokens, List.map_map, Function.comp_def] + +theorem payload_mem (keys : List (Key n)) (key : Key n) (hmem : key ∈ keys) : + payload key ∈ BinaryNameSearch.payloads (tokens keys) := by + rw [tokens_payloads] + exact List.mem_map.mpr ⟨key, hmem, rfl⟩ + +theorem tokens_canonical (keys : List (Key n)) : + ∀ token ∈ tokens keys, BinaryNameMachine.canonical token.2 = true := by + intro token htoken + obtain ⟨key, _, rfl⟩ := List.mem_map.mp htoken + exact payload_canonical key + +def name (keys : List (Key n)) (key : Key n) (hmem : key ∈ keys) : Fin keys.length := + ⟨(BinaryNameSearch.payloads (tokens keys)).idxOf (payload key), by + have h := List.idxOf_lt_length_of_mem (payload_mem keys key hmem) + simpa only [tokens_payloads, List.length_map] using h⟩ + +@[simp] theorem name_val (keys : List (Key n)) (key : Key n) (hmem : key ∈ keys) : + (name keys key hmem).val = + (BinaryNameSearch.payloads (tokens keys)).idxOf (payload key) := rfl + +theorem name_eq_iff (keys : List (Key n)) (a b : Key n) + (ha : a ∈ keys) (hb : b ∈ keys) : name keys a ha = name keys b hb ↔ a = b := by + constructor + · intro h + have hidx := congrArg Fin.val h + exact payload_injective n ((List.idxOf_inj (payload_mem keys a ha)).mp hidx) + · intro h + subst b + rfl + +theorem name_injective (keys : List (Key n)) : + Function.Injective (fun key : {key // key ∈ keys} => name keys key.val key.property) := by + intro a b h + exact Subtype.ext ((name_eq_iff keys a.val b.val a.property b.property).mp h) + +def embedding (keys : List (Key n)) : {key // key ∈ keys} ↪ Fin keys.length := + ⟨fun key => name keys key.val key.property, name_injective keys⟩ + +def payloadBound (n bound : Nat) : Nat := + (1 + 2 ^ (11 ^ n) + 6 * n) * (max n (max bound 2) + 1) + 1 + +theorem payload_length_le (key : Key n) (bound : Nat) + (hretained : key.retained.length ≤ n) + (hIDs : ∀ entry ∈ key.retained, KeyMetadataEncoding.entryID entry.2 ≤ bound) : + (payload key).length ≤ payloadBound n bound := by + rw [payload_length] + unfold payloadBound + apply Nat.add_le_add_right + apply (CanonicalKeyEncoding.bits_length_le key bound hIDs).trans + apply Nat.mul_le_mul_right + rw [CanonicalKeyEncoding.partitionWidth_eq] + omega + +theorem payloadSize_le (keys : List (Key n)) (B : Nat) + (hbound : ∀ key ∈ keys, (payload key).length ≤ B) : + BinaryNameSearch.payloadSize (tokens keys) ≤ B * keys.length := by + revert hbound + induction keys with + | nil => + intro _ + exact Nat.le_refl 0 + | cons key keys ih => + intro hbound + have hhead := hbound key (by simp) + have htail := ih (fun k hk => hbound k (List.mem_cons_of_mem key hk)) + change (payload key).length + BinaryNameSearch.payloadSize (tokens keys) ≤ + B * (keys.length + 1) + apply (Nat.add_le_add hhead htail).trans_eq + rw [Nat.mul_add, Nat.mul_one] + exact Nat.add_comm _ _ + +theorem stream_length_le (keys : List (Key n)) (bound : Nat) + (hretained : ∀ key ∈ keys, key.retained.length ≤ n) + (hIDs : ∀ key ∈ keys, ∀ entry ∈ key.retained, + KeyMetadataEncoding.entryID entry.2 ≤ bound) : + (BinaryNameSearch.stream (tokens keys)).length ≤ + (2 * payloadBound n bound + 2) * keys.length := by + have hsize := payloadSize_le keys (payloadBound n bound) + (fun key hk => payload_length_le key bound (hretained key hk) (hIDs key hk)) + rw [BinaryNameSearch.stream_length, tokens_length] + calc + _ ≤ 2 * (payloadBound n bound * keys.length) + 2 * keys.length := + Nat.add_le_add_right (Nat.mul_le_mul_left 2 hsize) _ + _ = _ := by rw [Nat.add_mul, Nat.mul_assoc] + + +variable {K Λ A : Type} [DecidableEq K] + +def searchInTime (tape : Fin 6 → K) (distinct : Function.Injective tape) + (labels : BinaryNameSearch.Label → Λ) (foundExit missingExit malformedExit : Option Λ) + (program : Λ → TM2.Stmt (BinaryNameSearch.Alphabet (K := K)) Λ + (BinaryNameSearch.State A)) + (atLabels : ∀ l, program (labels l) = + BinaryNameSearch.instruction tape labels foundExit missingExit malformedExit l) + (base : K → List Bool) (ambient : A) + (keys : List (Key n)) (key : Key n) (hmem : key ∈ keys) + (suffix counter : List Bool) + (keyWord : base (tape 1) = (payload key).reverse) + (candidateEmpty : base (tape 2) = []) (copyEmpty : base (tape 3) = []) + (scratchEmpty : base (tape 4) = []) (bound : Nat) + (hretained : ∀ k ∈ keys, k.retained.length ≤ n) + (hIDs : ∀ k ∈ keys, ∀ entry ∈ k.retained, + KeyMetadataEncoding.entryID entry.2 ≤ bound) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .sign), BinaryNameSearch.clean ambient, + tapesAt (tape 0) (tape 5) base + (BinaryNameSearch.stream (tokens keys) ++ suffix) counter⟩ + (some ⟨foundExit, BinaryNameSearch.clean ambient, + tapesAt (tape 0) (tape 5) base + (BinaryNameSearch.stream (BinaryNameSearch.afterMatch (tokens keys) (payload key)) ++ + suffix) + (List.replicate (name keys key hmem).val true ++ counter)⟩) + ((3 * payloadBound n bound + 7) * + ((2 * payloadBound n bound + 2) * keys.length)) := by + let run := BinaryNameSearch.searchInTime tape distinct labels + foundExit missingExit malformedExit program atLabels base ambient + (tokens keys) (payload key) suffix counter (tokens_canonical keys) + (payload_mem keys key hmem) keyWord candidateEmpty copyEmpty scratchEmpty + have hkey := payload_length_le key bound (hretained key hmem) (hIDs key hmem) + have hstream := stream_length_le keys bound hretained hIDs + exact + { steps := run.steps + evals_in_steps := run.evals_in_steps + steps_le_m := run.steps_le_m.trans (Nat.mul_le_mul (by omega) hstream) } + +end +end PerfectCompleteness.CanonicalVertexNames + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/ClauseSupportLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/ClauseSupportLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..7f01801133bf3c98b55ca4ead76ff87cd461ed79 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/ClauseSupportLemmas.lean @@ -0,0 +1,449 @@ +import OAI.Computability.PerfectCompleteness.Foundations.PartitionsLemmas +import OAI.Computability.PerfectCompleteness.Foundations.SourceClause + +namespace OAI + +section + +namespace PerfectCompleteness.ClauseSupport + +open SourceClause + +variable {C C' D E Y Z : Type*} + +abbrev Answer (signs : Triple) := {u : Triple // u ∈ satisfyingTriples signs} + +def coordinate {signs : Triple} (i : Fin 3) (u : Answer signs) : Bool := + u.val.at i + +theorem coordinate_surjective (signs : Triple) (i : Fin 3) : + Function.Surjective (coordinate (signs := signs) i) := by + intro b + obtain ⟨u, hu, hb⟩ := SourceClause.coordinate_surjective signs i b + exact ⟨⟨u, hu⟩, hb⟩ + +theorem pair_surjective (signs : Triple) (i j : Fin 3) (hij : i ≠ j) + (a b : Bool) : ∃ u : Answer signs, coordinate i u = a ∧ coordinate j u = b := by + obtain ⟨u, hu, hi, hj⟩ := SourceClause.pair_surjective signs i j hij a b + exact ⟨⟨u, hu⟩, hi, hj⟩ + +instance (signs : Triple) : Nonempty (Answer signs) := by + obtain ⟨u, _⟩ := coordinate_surjective signs 0 false + exact ⟨u⟩ + +def Unused (f : C → D → Y) : Prop := ∀ c u v, f c u = f c v + +def Factors (f : C → D → Y) (p : D → E) : Prop := + ∀ c u v, p u = p v → f c u = f c v + +abbrev Reducible {signs : Triple} (f : C → Answer signs → Y) (i : Fin 3) := + Factors f (coordinate i) + +theorem unused_of_two_reductions {signs : Triple} (f : C → Answer signs → Y) + {i j : Fin 3} (hij : i ≠ j) (hi : Reducible f i) (hj : Reducible f j) : + Unused f := by + intro c u v + obtain ⟨w, hw₁, hw₂⟩ := pair_surjective signs i j hij (coordinate i u) (coordinate j v) + exact (hi c u w hw₁.symm).trans (hj c w v hw₂) + +theorem used_reduction_unique {signs : Triple} (f : C → Answer signs → Y) + (hused : ¬ Unused f) {i j : Fin 3} (hi : Reducible f i) (hj : Reducible f j) : + i = j := by + by_contra hij + exact hused (unused_of_two_reductions f hij hi hj) + +def pull (f : C → D → Y) (context : C' → C) (localMap : E → D) : C' → E → Y := + fun c u => f (context c) (localMap u) + +theorem unused_pull_iff (f : C → D → Y) (context : C' → C) (localMap : E → D) + (hcontext : Function.Surjective context) (hlocal : Function.Surjective localMap) : + Unused (pull f context localMap) ↔ Unused f := by + constructor + · intro h c u v + obtain ⟨c', rfl⟩ := hcontext c + obtain ⟨u', rfl⟩ := hlocal u + obtain ⟨v', rfl⟩ := hlocal v + exact h c' u' v' + · intro h c u v + exact h (context c) (localMap u) (localMap v) + +theorem factors_pull_iff (f : C → D → Y) (context : C' → C) (localMap : E → D) + (p : D → Z) (hcontext : Function.Surjective context) + (hlocal : Function.Surjective localMap) : + Factors (pull f context localMap) (p ∘ localMap) ↔ Factors f p := by + constructor + · intro h c u v huv + obtain ⟨c', rfl⟩ := hcontext c + obtain ⟨u', rfl⟩ := hlocal u + obtain ⟨v', rfl⟩ := hlocal v + exact h c' u' v' huv + · intro h c u v huv + exact h (context c) (localMap u) (localMap v) huv + +theorem unused_kernel_invariant (f : C → D → Y) (g : C → D → Z) + (hkernel : ∀ c u v, f c u = f c v ↔ g c u = g c v) : + Unused f ↔ Unused g := by + exact ⟨fun h c u v => (hkernel c u v).1 (h c u v), + fun h c u v => (hkernel c u v).2 (h c u v)⟩ + +theorem factors_kernel_invariant (f : C → D → Y) (g : C → D → Z) (p : D → E) + (hkernel : ∀ c u v, f c u = f c v ↔ g c u = g c v) : + Factors f p ↔ Factors g p := by + exact ⟨fun h c u v hp => (hkernel c u v).1 (h c u v hp), + fun h c u v hp => (hkernel c u v).2 (h c u v hp)⟩ + +inductive Mode where + | dropped + | bit (position : Fin 3) + | full + deriving DecidableEq + +noncomputable def clauseMode {signs : Triple} (f : C → Answer signs → Y) : Mode := by + classical + exact if Unused f then .dropped else + if h : ∃ i, Reducible f i then .bit h.choose else .full + +theorem clauseMode_unused {signs : Triple} (f : C → Answer signs → Y) + (h : Unused f) : clauseMode f = .dropped := by + simp [clauseMode, h] + +theorem clauseMode_bit {signs : Triple} (f : C → Answer signs → Y) + (hused : ¬ Unused f) (i : Fin 3) (hi : Reducible f i) : clauseMode f = .bit i := by + classical + have hex : ∃ j, Reducible f j := ⟨i, hi⟩ + simp only [clauseMode, ite_eq_right hused, dite_eq_left hex] + exact congrArg Mode.bit (used_reduction_unique f hused hex.choose_spec hi) + +theorem clauseMode_full {signs : Triple} (f : C → Answer signs → Y) + (hused : ¬ Unused f) (hfull : ¬ ∃ i, Reducible f i) : clauseMode f = .full := by + simp [clauseMode, hused, hfull] + +theorem clauseMode_eq_of_predicates {signs : Triple} + (f : C → Answer signs → Y) (g : C' → Answer signs → Z) + (hu : Unused f ↔ Unused g) (hr : ∀ i, Reducible f i ↔ Reducible g i) : + clauseMode f = clauseMode g := by + classical + by_cases hf : Unused f + · rw [clauseMode_unused f hf, clauseMode_unused g (hu.1 hf)] + · have hg : ¬ Unused g := fun h => hf (hu.2 h) + by_cases hred : ∃ i, Reducible f i + · obtain ⟨i, hi⟩ := hred + rw [clauseMode_bit f hf i hi, clauseMode_bit g hg i ((hr i).1 hi)] + · have hn : ¬ ∃ i, Reducible g i := by + rintro ⟨i, hi⟩ + exact hred ⟨i, (hr i).2 hi⟩ + rw [clauseMode_full f hf hred, clauseMode_full g hg hn] + +theorem clauseMode_kernel_invariant {signs : Triple} + (f : C → Answer signs → Y) (g : C → Answer signs → Z) + (hkernel : ∀ c u v, f c u = f c v ↔ g c u = g c v) : + clauseMode f = clauseMode g := + clauseMode_eq_of_predicates f g (unused_kernel_invariant f g hkernel) + (fun i => factors_kernel_invariant f g (coordinate i) hkernel) + +theorem unprojected_mode_eq {signs : Triple} (f : C → Answer signs → Y) + (context : C' → C) (hcontext : Function.Surjective context) : + clauseMode (pull f context id) = clauseMode f := by + apply clauseMode_eq_of_predicates + · exact unused_pull_iff f context id hcontext Function.surjective_id + · intro i + exact factors_pull_iff f context id (coordinate i) hcontext Function.surjective_id + +inductive ReducedValue where + | dropped + | bit (value : Bool) + | full (value : Triple) + deriving DecidableEq + +def reduceByMode {signs : Triple} (mode : Mode) (u : Answer signs) : ReducedValue := + match mode with + | .dropped => .dropped + | .bit i => .bit (coordinate i u) + | .full => .full u.val + +noncomputable def clauseReduction {signs : Triple} (f : C → Answer signs → Y) : + Answer signs → ReducedValue := reduceByMode (clauseMode f) + +noncomputable def bitReduction (f : C → Bool → Y) (b : Bool) : ReducedValue := by + classical + exact if Unused f then .dropped else .bit b + +theorem clauseReduction_sound {signs : Triple} (f : C → Answer signs → Y) + (c : C) (u v : Answer signs) (h : clauseReduction f u = clauseReduction f v) : + f c u = f c v := by + classical + by_cases hu : Unused f + · exact hu c u v + · by_cases hr : ∃ i, Reducible f i + · obtain ⟨i, hi⟩ := hr + have hm := clauseMode_bit f hu i hi + have hc : coordinate i u = coordinate i v := by + simpa only [clauseReduction, hm, reduceByMode, ReducedValue.bit.injEq] using h + exact hi c u v hc + · have hm := clauseMode_full f hu hr + have hv : u.val = v.val := by + simpa only [clauseReduction, hm, reduceByMode, ReducedValue.full.injEq] using h + exact congrArg (f c) (Subtype.ext hv) + +theorem bitReduction_sound (f : C → Bool → Y) (c : C) (u v : Bool) + (h : bitReduction f u = bitReduction f v) : f c u = f c v := by + classical + by_cases hu : Unused f + · exact hu c u v + · have huv : u = v := by simpa [bitReduction, hu] using h + exact congrArg (f c) huv + +inductive SlotKey where + | dropped + | bit (variableID : Nat) + | full (clauseOccurrence : Nat) (signs : Triple) + deriving DecidableEq + +noncomputable def clauseKey {signs : Triple} (occurrence : Nat) (variableIDs : Fin 3 → Nat) + (f : C → Answer signs → Y) : SlotKey := + match clauseMode f with + | .dropped => .dropped + | .bit i => .bit (variableIDs i) + | .full => .full occurrence signs + +noncomputable def bitKey (variableID : Nat) (f : C → Bool → Y) : SlotKey := by + classical + exact if Unused f then .dropped else .bit variableID + +theorem unprojected_clause_key_eq {signs : Triple} (f : C → Answer signs → Y) + (context : C' → C) (hcontext : Function.Surjective context) + (occurrence : Nat) (variableIDs : Fin 3 → Nat) : + clauseKey occurrence variableIDs (pull f context id) = clauseKey occurrence variableIDs f := by + simp only [clauseKey, unprojected_mode_eq f context hcontext] + +theorem unprojected_clause_reduction_eq {signs : Triple} (f : C → Answer signs → Y) + (context : C' → C) (hcontext : Function.Surjective context) (u : Answer signs) : + clauseReduction (pull f context id) u = clauseReduction f u := by + simp only [clauseReduction, unprojected_mode_eq f context hcontext] + +theorem unprojected_bit_key_eq (f : C → Bool → Y) + (context : C' → C) (hcontext : Function.Surjective context) (variableID : Nat) : + bitKey variableID (pull f context id) = bitKey variableID f := by + classical + simp only [bitKey, unused_pull_iff f context id hcontext Function.surjective_id] + +theorem unprojected_bit_reduction_eq (f : C → Bool → Y) + (context : C' → C) (hcontext : Function.Surjective context) (b : Bool) : + bitReduction (pull f context id) b = bitReduction f b := by + classical + simp only [bitReduction, unused_pull_iff f context id hcontext Function.surjective_id] + +theorem projected_reducible {signs : Triple} (f : C → Bool → Y) + (context : C' → C) (i : Fin 3) : + Reducible (pull f context (coordinate (signs := signs) i)) i := by + intro c u v h + exact congrArg (f (context c)) h + +theorem projected_unused_iff {signs : Triple} (f : C → Bool → Y) + (context : C' → C) (hcontext : Function.Surjective context) (i : Fin 3) : + Unused (pull f context (coordinate (signs := signs) i)) ↔ Unused f := + unused_pull_iff f context (coordinate i) hcontext (coordinate_surjective signs i) + +theorem projected_key_eq {signs : Triple} (f : C → Bool → Y) + (context : C' → C) (hcontext : Function.Surjective context) + (occurrence : Nat) (variableIDs : Fin 3 → Nat) (i : Fin 3) : + clauseKey occurrence variableIDs (pull f context (coordinate (signs := signs) i)) = + bitKey (variableIDs i) f := by + classical + have hu := projected_unused_iff (signs := signs) f context hcontext i + by_cases hf : Unused f + · simp [clauseKey, clauseMode_unused _ (hu.2 hf), bitKey, hf] + · have hp : ¬ Unused (pull f context (coordinate (signs := signs) i)) := + fun h => hf (hu.1 h) + rw [clauseKey, clauseMode_bit _ hp i (projected_reducible f context i)] + simp [bitKey, hf] + +theorem projected_reduction_eq {signs : Triple} (f : C → Bool → Y) + (context : C' → C) (hcontext : Function.Surjective context) + (i : Fin 3) (u : Answer signs) : + clauseReduction (pull f context (coordinate i)) u = bitReduction f (coordinate i u) := by + classical + have hu := projected_unused_iff (signs := signs) f context hcontext i + by_cases hf : Unused f + · simp [clauseReduction, clauseMode_unused _ (hu.2 hf), reduceByMode, bitReduction, hf] + · have hp : ¬ Unused (pull f context (coordinate (signs := signs) i)) := + fun h => hf (hu.1 h) + rw [clauseReduction, clauseMode_bit _ hp i (projected_reducible f context i)] + simp [reduceByMode, bitReduction, hf] + +end PerfectCompleteness.ClauseSupport + +end + +section + +namespace PerfectCompleteness.MixedSupport + +open ClauseSupport + +variable {I C C' Y : Type*} + +inductive Slot where + | clause (occurrence : Nat) (variableIDs : Fin 3 → Nat) (signs : SourceClause.Triple) + | bit (variableID : Nat) + +def Slot.Domain : Slot → Type + | .clause _ _ signs => Answer signs + | .bit _ => Bool + +instance (s : Slot) : Nonempty s.Domain := by + cases s <;> dsimp [Slot.Domain] <;> infer_instance + +abbrev Assignment (slots : I → Slot) := ∀ i, (slots i).Domain + +inductive Projection : Slot → Slot → Type + | keep (s : Slot) : Projection s s + | select (occurrence : Nat) (variableIDs : Fin 3 → Nat) + (signs : SourceClause.Triple) (position : Fin 3) : + Projection (.clause occurrence variableIDs signs) (.bit (variableIDs position)) + +def Projection.map {s t : Slot} : Projection s t → s.Domain → t.Domain + | .keep _ => id + | .select _ _ _ i => coordinate i + +theorem Projection.surjective {s t : Slot} (p : Projection s t) : + Function.Surjective p.map := by + cases p with + | keep s => exact Function.surjective_id + | select occurrence variableIDs signs i => exact coordinate_surjective signs i + +def projectionMap {slots projected : I → Slot} + (p : ∀ i, Projection (slots i) (projected i)) : + Assignment slots → Assignment projected := + ProductReduction.productMap (fun i => (p i).map) + +theorem projectionMap_surjective {slots projected : I → Slot} + (p : ∀ i, Projection (slots i) (projected i)) : + Function.Surjective (projectionMap p) := + ProductReduction.productMap_surjective _ (fun i => (p i).surjective) + +variable [DecidableEq I] + +theorem projectionMap_update {slots projected : I → Slot} + (p : ∀ i, Projection (slots i) (projected i)) + (x : Assignment slots) (i : I) (u : (slots i).Domain) : + projectionMap p (Function.update x i u) = + Function.update (projectionMap p x) i ((p i).map u) := by + funext j + by_cases hji : j = i + · subst j + simp [projectionMap, ProductReduction.productMap] + · simp [projectionMap, ProductReduction.productMap, Function.update_of_ne hji] + +def sectionFunction (slots : I → Slot) (f : Assignment slots → Y) (i : I) : + Assignment slots → (slots i).Domain → Y := + fun context u => f (Function.update context i u) + +theorem sectionFunction_pullback {slots projected : I → Slot} + (p : ∀ i, Projection (slots i) (projected i)) + (f : Assignment projected → Y) (i : I) : + sectionFunction slots (f ∘ projectionMap p) i = + pull (sectionFunction projected f i) (projectionMap p) (p i).map := by + funext context u + exact congrArg f (projectionMap_update p context i u) + +noncomputable def localKey (s : Slot) : (C → s.Domain → Y) → SlotKey := + match s with + | .clause occurrence variableIDs _ => clauseKey occurrence variableIDs + | .bit variableID => bitKey variableID + +noncomputable def localReduction (s : Slot) : (C → s.Domain → Y) → s.Domain → ReducedValue := + match s with + | .clause _ _ _ => clauseReduction + | .bit _ => bitReduction + +theorem localReduction_sound (s : Slot) (f : C → s.Domain → Y) + (c : C) (u v : s.Domain) (h : localReduction s f u = localReduction s f v) : + f c u = f c v := by + cases s with + | clause occurrence variableIDs signs => exact clauseReduction_sound f c u v h + | bit variableID => exact bitReduction_sound f c u v h + +theorem localKey_projection {s t : Slot} (p : Projection s t) + (f : C → t.Domain → Y) (context : C' → C) + (hcontext : Function.Surjective context) : + localKey s (pull f context p.map) = localKey t f := by + cases p with + | keep s => + cases s with + | clause occurrence variableIDs signs => + exact unprojected_clause_key_eq f context hcontext occurrence variableIDs + | bit variableID => exact unprojected_bit_key_eq f context hcontext variableID + | select occurrence variableIDs signs i => + exact projected_key_eq f context hcontext occurrence variableIDs i + +theorem localReduction_projection {s t : Slot} (p : Projection s t) + (f : C → t.Domain → Y) (context : C' → C) + (hcontext : Function.Surjective context) (u : s.Domain) : + localReduction s (pull f context p.map) u = localReduction t f (p.map u) := by + cases p with + | keep s => + cases s with + | clause occurrence variableIDs signs => + exact unprojected_clause_reduction_eq f context hcontext u + | bit variableID => exact unprojected_bit_reduction_eq f context hcontext u + | select occurrence variableIDs signs i => + exact projected_reduction_eq f context hcontext i u + +noncomputable def keyFields (slots : I → Slot) (f : Assignment slots → Y) : I → SlotKey := + fun i => localKey (slots i) (sectionFunction slots f i) + +noncomputable def coordinateReduction (slots : I → Slot) (f : Assignment slots → Y) + (i : I) : (slots i).Domain → ReducedValue := + localReduction (slots i) (sectionFunction slots f i) + +noncomputable def reduction (slots : I → Slot) (f : Assignment slots → Y) : + Assignment slots → I → ReducedValue := + ProductReduction.productMap (coordinateReduction slots f) + +theorem keyFields_projection {slots projected : I → Slot} + (p : ∀ i, Projection (slots i) (projected i)) (f : Assignment projected → Y) : + keyFields slots (f ∘ projectionMap p) = keyFields projected f := by + funext i + unfold keyFields + rw [sectionFunction_pullback] + exact localKey_projection (p i) (sectionFunction projected f i) + (projectionMap p) (projectionMap_surjective p) + +theorem reduction_projection {slots projected : I → Slot} + (p : ∀ i, Projection (slots i) (projected i)) + (f : Assignment projected → Y) (x : Assignment slots) : + reduction slots (f ∘ projectionMap p) x = reduction projected f (projectionMap p x) := by + funext i + change localReduction (slots i) (sectionFunction slots (f ∘ projectionMap p) i) (x i) = _ + rw [sectionFunction_pullback] + exact localReduction_projection (p i) (sectionFunction projected f i) + (projectionMap p) (projectionMap_surjective p) (x i) + +theorem coordinateInvariant (slots : I → Slot) (f : Assignment slots → Y) : + ProductReduction.CoordinateInvariant (coordinateReduction slots f) f := by + apply ProductReduction.coordinateInvariant_of_update + intro i x u h + have hs := localReduction_sound (slots i) (sectionFunction slots f i) x (x i) u h + simpa only [sectionFunction, Function.update_eq_self] using hs + +theorem constant_on_reduction_fibers [Finite I] + (slots : I → Slot) (f : Assignment slots → Y) {x x' : Assignment slots} + (h : reduction slots f x = reduction slots f x') : f x = f x' := + ProductReduction.constant_on_product_fibers _ f (coordinateInvariant slots f) h + +noncomputable def retainedKeys {n : Nat} (slots : Fin n → Slot) + (f : Assignment slots → Y) : List (Fin n × SlotKey) := + ((List.finRange n).map (fun i => (i, keyFields slots f i))).filter + (fun entry => decide (entry.2 ≠ .dropped)) + +theorem retainedKeys_projection {n : Nat} {slots projected : Fin n → Slot} + (p : ∀ i, Projection (slots i) (projected i)) (f : Assignment projected → Y) : + retainedKeys slots (f ∘ projectionMap p) = retainedKeys projected f := by + simp only [retainedKeys, keyFields_projection] + +end PerfectCompleteness.MixedSupport + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/CommonAccuracy.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/CommonAccuracy.lean new file mode 100644 index 0000000000000000000000000000000000000000..2e244e765a6a2da98bb47baab19500a40b31cfcd --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/CommonAccuracy.lean @@ -0,0 +1,52 @@ +import OAI.Computability.PerfectCompleteness.Construction.AscendingBranchingLemmas +import OAI.Computability.PerfectCompleteness.Reduction.FixedRows + +namespace OAI + +section + +namespace PerfectCompleteness.CommonAccuracy + +open FixedRows InitialParameters UpperParameterScalars + +noncomputable section + +variable {δ : ℚ} (plan : Plan δ) + +def tolerance (j : Nat) : ℝ := + min (epsilon δ ^ 2 / 40) + (min (simultaneous δ ^ 2 / 160) + (min (plan.density * q (inverse δ) plan.order (rows plan j) / 160) + (min (gamma (useful δ) plan.density (inverse δ) plan.order (rows plan j) ^ 2 / 640) + (gamma (useful δ) plan.density (inverse δ) plan.order (rows plan j) / 40)))) + +theorem tolerance_pos (hδ : 0 < δ) (j : Nat) : 0 < tolerance plan j := by + have hε := epsilon_pos hδ + have hc := simultaneous_pos hδ + have hq := q_pos (inverse_pos hδ) plan.order (rows plan j) + have hγ := gamma_pos (useful_pos hδ) plan.density_pos (inverse_pos hδ) + plan.order (rows plan j) + have hα := plan.density_pos + unfold tolerance + positivity + +theorem exists_accuracy (hδ : 0 < δ) : + ∃ ε : ℝ, 0 < ε ∧ ∀ j ≤ plan.depth, + ε < epsilon δ ^ 2 / 40 ∧ + ε < simultaneous δ ^ 2 / 160 ∧ + ε < plan.density * q (inverse δ) plan.order (rows plan j) / 160 ∧ + ε < gamma (useful δ) plan.density (inverse δ) plan.order (rows plan j) ^ 2 / 640 ∧ + ε < gamma (useful δ) plan.density (inverse δ) plan.order (rows plan j) / 40 := by + obtain ⟨ε, hε, hsmall⟩ := AscendingBranching.exists_common_accuracy + (fun j : Fin (plan.depth + 1) => tolerance plan j.val) + (fun j => tolerance_pos plan hδ j.val) + refine ⟨ε, hε, fun j hj => ?_⟩ + have h := hsmall ⟨j, Nat.lt_succ_of_le hj⟩ + simpa only [tolerance, lt_min_iff] using h + +end +end PerfectCompleteness.CommonAccuracy + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/CoordinateReplacementLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/CoordinateReplacementLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..4e0829d8b6b4073d3f3923bcb246282bfff712e1 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/CoordinateReplacementLemmas.lean @@ -0,0 +1,352 @@ +import OAI.Computability.PerfectCompleteness.Construction.HiddenChildMixture +import OAI.Computability.PerfectCompleteness.Foundations.FiniteProduct +import OAI.Computability.PerfectCompleteness.Repetition.RepetitionRateLemmas +import OAI.Computability.PerfectCompleteness.Sampling.DensityVariation +import OAI.Computability.UniqueGames.Foundations.SamplingLemmas +import OAI.Computability.UniqueGames.Games.FinishBoundsLemmas + +namespace OAI + + +namespace PerfectCompleteness.CoordinateReplacement + +open scoped BigOperators +open UniqueGamesTheorem.Foundations.Games +open FiniteProduct + +noncomputable section + +variable {I : Type*} [Fintype I] [DecidableEq I] + {Ω : I → Type*} [∀ i, Fintype (Ω i)] + +def ratio (P Q : (i : I) → FiniteDistribution (Ω i)) (i : I) (a : Ω i) : ℝ := + (Q i).weight a / (P i).weight a + +def replacement (P Q : (i : I) → FiniteDistribution (Ω i)) (i : I) : + FiniteDistribution ((j : I) → Ω j) := + law (Function.update P i (Q i)) + +omit [Fintype I] [DecidableEq I] in +theorem ratio_nonnegative (P Q : (i : I) → FiniteDistribution (Ω i)) + (i : I) (a : Ω i) : 0 ≤ ratio P Q i a := + div_nonneg ((Q i).nonnegative a) ((P i).nonnegative a) + +omit [Fintype I] [DecidableEq I] in +theorem support_of_positive (P Q : (i : I) → FiniteDistribution (Ω i)) + (positive : ∀ i a, 0 < (P i).weight a) : + ∀ i a, (P i).weight a = 0 → (Q i).weight a = 0 := by + intro i a hzero + exact False.elim ((ne_of_gt (positive i a)) hzero) + +omit [Fintype I] [DecidableEq I] in + +theorem support_of_domination (P Q : (i : I) → FiniteDistribution (Ω i)) + (B : ℝ) (domination : ∀ i a, (Q i).weight a ≤ B * (P i).weight a) : + ∀ i a, (P i).weight a = 0 → (Q i).weight a = 0 := by + intro i a hzero + apply le_antisymm + · simpa only [hzero, mul_zero] using domination i a + · exact (Q i).nonnegative a + +omit [Fintype I] [DecidableEq I] in +theorem weight_mul_ratio_of_support (P Q : (i : I) → FiniteDistribution (Ω i)) + (support : ∀ i a, (P i).weight a = 0 → (Q i).weight a = 0) + (i : I) (a : Ω i) : + (P i).weight a * ratio P Q i a = (Q i).weight a := by + by_cases hzero : (P i).weight a = 0 + · simp only [hzero, zero_mul, support i a hzero] + · exact mul_div_cancel₀ ((Q i).weight a) hzero + +omit [Fintype I] [DecidableEq I] in +theorem ratio_mean_one_of_support (P Q : (i : I) → FiniteDistribution (Ω i)) + (support : ∀ i a, (P i).weight a = 0 → (Q i).weight a = 0) (i : I) : + (P i).expectation (ratio P Q i) = 1 := by + change (∑ a, (P i).weight a * ratio P Q i a) = 1 + simp_rw [weight_mul_ratio_of_support P Q support] + exact (Q i).normalized + +omit [Fintype I] [DecidableEq I] in +theorem ratio_mean_one (P Q : (i : I) → FiniteDistribution (Ω i)) + (positive : ∀ i a, 0 < (P i).weight a) (i : I) : + (P i).expectation (ratio P Q i) = 1 := + ratio_mean_one_of_support P Q (support_of_positive P Q positive) i + +omit [Fintype I] [DecidableEq I] in +theorem ratio_mean_one_of_domination (P Q : (i : I) → FiniteDistribution (Ω i)) + (B : ℝ) (domination : ∀ i a, (Q i).weight a ≤ B * (P i).weight a) (i : I) : + (P i).expectation (ratio P Q i) = 1 := + ratio_mean_one_of_support P Q (support_of_domination P Q B domination) i + +theorem replacement_weight_of_support (P Q : (i : I) → FiniteDistribution (Ω i)) + (support : ∀ i a, (P i).weight a = 0 → (Q i).weight a = 0) + (i : I) (x : (j : I) → Ω j) : + (replacement P Q i).weight x = (law P).weight x * ratio P Q i (x i) := by + have hrow (j : I) : + (Function.update P i (Q i) j).weight (x j) = + (P j).weight (x j) * factor i (ratio P Q i) j (x j) := by + by_cases hji : j = i + · subst j + simp only [Function.update_self, factor_self] + exact (weight_mul_ratio_of_support P Q support i (x i)).symm + · simp only [Function.update_of_ne hji, factor_other i j hji, mul_one] + change (∏ j, (Function.update P i (Q i) j).weight (x j)) = + (∏ j, (P j).weight (x j)) * ratio P Q i (x i) + simp_rw [hrow] + rw [Finset.prod_mul_distrib, product_factor] + +theorem replacement_weight (P Q : (i : I) → FiniteDistribution (Ω i)) + (positive : ∀ i a, 0 < (P i).weight a) (i : I) (x : (j : I) → Ω j) : + (replacement P Q i).weight x = (law P).weight x * ratio P Q i (x i) := + replacement_weight_of_support P Q (support_of_positive P Q positive) i x + +theorem replacement_weight_of_domination (P Q : (i : I) → FiniteDistribution (Ω i)) + (B : ℝ) (domination : ∀ i a, (Q i).weight a ≤ B * (P i).weight a) + (i : I) (x : (j : I) → Ω j) : + (replacement P Q i).weight x = (law P).weight x * ratio P Q i (x i) := + replacement_weight_of_support P Q (support_of_domination P Q B domination) i x + +omit [Fintype I] [DecidableEq I] in +theorem ratio_le_of_positive (P Q : (i : I) → FiniteDistribution (Ω i)) + (positive : ∀ i a, 0 < (P i).weight a) (B : ℝ) + (domination : ∀ i a, (Q i).weight a ≤ B * (P i).weight a) + (i : I) (a : Ω i) : ratio P Q i a ≤ B := + (div_le_iff₀ (positive i a)).2 (domination i a) + +omit [Fintype I] [DecidableEq I] in +theorem ratio_bounds_of_domination (P Q : (i : I) → FiniteDistribution (Ω i)) + (B : ℝ) (nonnegative : 0 ≤ B) + (domination : ∀ i a, (Q i).weight a ≤ B * (P i).weight a) + (i : I) (a : Ω i) : 0 ≤ ratio P Q i a ∧ ratio P Q i a ≤ B := by + refine ⟨ratio_nonnegative P Q i a, ?_⟩ + by_cases hzero : (P i).weight a = 0 + · simpa only [ratio, hzero, div_zero] using nonnegative + · exact (div_le_iff₀ (lt_of_le_of_ne ((P i).nonnegative a) (Ne.symm hzero))).2 + (domination i a) + +omit [Fintype I] [DecidableEq I] in + +theorem ratio_second_moment_le (P Q : (i : I) → FiniteDistribution (Ω i)) + (B : ℝ) (nonnegative : 0 ≤ B) + (domination : ∀ i a, (Q i).weight a ≤ B * (P i).weight a) (i : I) : + (P i).expectation (fun a => (ratio P Q i a - 1) ^ 2) ≤ B - 1 := by + have hpoint (a : Ω i) : + (ratio P Q i a - 1) ^ 2 ≤ (B - 2) * ratio P Q i a + 1 := by + obtain ⟨hpos, hbound⟩ := ratio_bounds_of_domination P Q B nonnegative domination i a + have hmul := mul_le_mul_of_nonneg_right hbound hpos + nlinarith + have hexpectation : + (P i).expectation (fun a => (B - 2) * ratio P Q i a + 1) = + (B - 2) * (P i).expectation (ratio P Q i) + 1 := by + unfold FiniteDistribution.expectation + rw [Finset.mul_sum] + simp only [mul_add, mul_one, Finset.sum_add_distrib] + rw [(P i).normalized] + congr 1 + apply Finset.sum_congr rfl + intro a _ + ring + calc + _ ≤ (P i).expectation (fun a => (B - 2) * ratio P Q i a + 1) := + SmallBias.expectation_mono (P i) hpoint + _ = (B - 2) * (P i).expectation (ratio P Q i) + 1 := hexpectation + _ = B - 1 := by + rw [ratio_mean_one_of_domination P Q B domination i] + ring + +theorem observed_replacement_variation [Nonempty I] {Γ : Type*} [Fintype Γ] + (P Q : (i : I) → FiniteDistribution (Ω i)) (B : ℝ) (nonnegative : 0 ≤ B) + (domination : ∀ i a, (Q i).weight a ≤ B * (P i).weight a) + (observe : ((i : I) → Ω i) → Γ) : + ((HiddenChildMixture.mixture (replacement P Q)).pushforward observe).totalVariation + ((law P).pushforward observe) ≤ + Real.sqrt ((B - 1) / Fintype.card I) / 2 := + HiddenChildMixture.observed_mixture_variation P (replacement P Q) (ratio P Q) + (replacement_weight_of_domination P Q B domination) + (ratio_mean_one_of_domination P Q B domination) + (B - 1) (ratio_second_moment_le P Q B nonnegative domination) observe + + +variable [∀ i, Nonempty (Ω i)] + +omit [Fintype I] [DecidableEq I] in + +theorem uniform_domination (Q : (i : I) → FiniteDistribution (Ω i)) (B : ℝ) + (cardinality : ∀ i, (Fintype.card (Ω i) : ℝ) ≤ B) (i : I) (a : Ω i) : + (Q i).weight a ≤ B * (FiniteDistribution.uniform (Ω i)).weight a := by + classical + have hweight : (Q i).weight a ≤ 1 := by + calc + _ ≤ ∑ b, (Q i).weight b := + Finset.single_le_sum (fun b _ => (Q i).nonnegative b) (Finset.mem_univ a) + _ = 1 := (Q i).normalized + have hcard : 0 < (Fintype.card (Ω i) : ℝ) := + Nat.cast_pos.mpr Fintype.card_pos + change (Q i).weight a ≤ B * (1 / (Fintype.card (Ω i) : ℝ)) + calc + _ ≤ 1 := hweight + _ ≤ B * (1 / (Fintype.card (Ω i) : ℝ)) := by + rw [mul_one_div] + exact (one_le_div hcard).2 (cardinality i) + +theorem observed_uniform_replacement_variation [Nonempty I] + {Γ : Type*} [Fintype Γ] + (Q : (i : I) → FiniteDistribution (Ω i)) (B : ℝ) + (cardinality : ∀ i, (Fintype.card (Ω i) : ℝ) ≤ B) + (observe : ((i : I) → Ω i) → Γ) : + ((HiddenChildMixture.mixture + (replacement (fun i => FiniteDistribution.uniform (Ω i)) Q)).pushforward observe).totalVariation + ((law (fun i => FiniteDistribution.uniform (Ω i))).pushforward observe) ≤ + Real.sqrt ((B - 1) / Fintype.card I) / 2 := by + have hB : 0 ≤ B := by + obtain ⟨i⟩ := ‹Nonempty I› + exact (Nat.cast_nonneg (Fintype.card (Ω i))).trans (cardinality i) + exact observed_replacement_variation (fun i => FiniteDistribution.uniform (Ω i)) Q B hB + (uniform_domination Q B cardinality) observe + + +end +end PerfectCompleteness.CoordinateReplacement + + + +namespace PerfectCompleteness.CubicErrorBounds + +theorem pow_sub_one_le_twice {x : ℝ} (hx : 0 ≤ x) (hx' : x ≤ 1) + (n : Nat) (hsmall : (n : ℝ) * x ≤ 1 / 2) : + (1 + x) ^ n - 1 ≤ 2 * ((n : ℝ) * x) := by + have hbern := one_add_mul_le_pow (a := -x) (by linarith : (-2 : ℝ) ≤ -x) n + have hprod : (1 + x) ^ n * (1 - x) ^ n ≤ 1 := by + rw [← mul_pow] + apply pow_le_one₀ (by nlinarith) (by nlinarith) + have hA : 0 ≤ (1 + x) ^ n := pow_nonneg (by linarith) _ + have hmul := mul_le_mul_of_nonneg_left hbern hA + simp only [← sub_eq_add_neg, mul_neg] at hmul + have hbound : (1 + x) ^ n * (1 - (n : ℝ) * x) ≤ 1 := by + nlinarith + have hA2 : (1 + x) ^ n ≤ 2 := by nlinarith + have hnx : 0 ≤ (n : ℝ) * x := mul_nonneg (Nat.cast_nonneg _) hx + nlinarith + +theorem cube_exponent_identity {m : Nat} (hm : 0 < m) (L : ℝ) : + ((m ^ 3 : Nat) : ℝ) * (L ^ 2 / (m : ℝ) ^ 4) = L ^ 2 / m := by + have hm' : (m : ℝ) ≠ 0 := by exact_mod_cast Nat.ne_of_gt hm + push_cast + field_simp + +theorem sparse_cube_bound {m : Nat} (hm : 0 < m) (L : ℝ) + (hsmall : L ^ 2 / (m : ℝ) ≤ 1 / 2) : + (1 + L ^ 2 / (m : ℝ) ^ 4) ^ (m ^ 3) - 1 ≤ 2 * L ^ 2 / m := by + have hm' : (1 : ℝ) ≤ m := by exact_mod_cast hm + have hmpos : (0 : ℝ) < m := by exact_mod_cast hm + have hpow : (m : ℝ) ≤ (m : ℝ) ^ 4 := by nlinarith [sq_nonneg ((m : ℝ) ^ 2 - 1)] + have hx : L ^ 2 / (m : ℝ) ^ 4 ≤ 1 := by + have h := div_le_div_of_nonneg_left (sq_nonneg L) hmpos hpow + linarith + have h := pow_sub_one_le_twice (by positivity) hx (m ^ 3) + (by simpa only [cube_exponent_identity hm] using hsmall) + simpa only [cube_exponent_identity hm, mul_div_assoc] using h + +theorem posterior_cube_bound {m : Nat} (hm : 2 ≤ m) {L : ℝ} (hL : 0 ≤ L) : + 2 * ((1 / (m : ℝ) ^ 2) * L / (1 - 1 / (m : ℝ) ^ 2)) ≤ 4 * L / (m : ℝ) ^ 2 := by + have hm' : (2 : ℝ) ≤ m := by exact_mod_cast hm + have hsq : (4 : ℝ) ≤ (m : ℝ) ^ 2 := by nlinarith + have hsqpos : (0 : ℝ) < (m : ℝ) ^ 2 := by linarith + have hfrac : (1 : ℝ) / (m : ℝ) ^ 2 ≤ 1 / 2 := by + apply (div_le_iff₀ hsqpos).2 + linarith + have hden : (0 : ℝ) < 1 - 1 / (m : ℝ) ^ 2 := by linarith + apply (le_div_iff₀ hsqpos).2 + rw [mul_assoc, div_mul_eq_mul_div, ← mul_div_assoc] + apply (div_le_iff₀ hden).2 + have heq : 2 * ((1 / (m : ℝ) ^ 2) * L * (m : ℝ) ^ 2) = 2 * L := by + field_simp + nlinarith [mul_nonneg hL (sub_nonneg.mpr hfrac)] + +end PerfectCompleteness.CubicErrorBounds + + + +namespace PerfectCompleteness.CubicErrorSchedule + +open CubicErrorBounds + +theorem power_mul_growth_le_one {b : ℝ} (hb : 0 ≤ b) (_ : b ≤ 1) + (n : Nat) : b ^ n * (1 + (n : ℝ) * (1 - b)) ≤ 1 := by + induction n with + | zero => simp + | succ n ih => + have hn : (0 : ℝ) ≤ n := Nat.cast_nonneg _ + have hstep : b * (1 + ((n : ℝ) + 1) * (1 - b)) ≤ + 1 + (n : ℝ) * (1 - b) := by nlinarith [mul_nonneg hn (sq_nonneg (1-b))] + have hprod := mul_le_mul_of_nonneg_left hstep (pow_nonneg hb n) + simp only [pow_succ, Nat.cast_add, Nat.cast_one] + nlinarith + +theorem clean_cube_bound {c : ℝ} (hc : 0 ≤ c) (hc' : c ≤ 1) + {m : Nat} (hm : 0 < m) : + (1 - c / (m : ℝ) ^ 2) ^ (m ^ 3) ≤ 1 / (1 + c * m) := by + have hmone : (1 : ℝ) ≤ m := by exact_mod_cast hm + have hmpos : (0 : ℝ) < m := by exact_mod_cast hm + have hsq : (1 : ℝ) ≤ (m : ℝ) ^ 2 := by nlinarith + have hfrac : c / (m : ℝ) ^ 2 ≤ 1 := (div_le_one (by positivity)).2 (hc'.trans hsq) + have h := power_mul_growth_le_one (by linarith : 0 ≤ 1-c/(m:ℝ)^2) + (by have := div_nonneg hc (sq_nonneg (m:ℝ)); linarith : 1-c/(m:ℝ)^2 ≤ 1) (m^3) + have heq : 1 + ((m ^ 3 : Nat) : ℝ) * (1-(1-c/(m:ℝ)^2)) = 1+c*m := by + push_cast + field_simp + ring + rw [heq] at h + exact (le_div_iff₀ (by positivity)).2 h + +theorem exists_cube_errors_lt {L c ε : ℝ} (hL : 0 ≤ L) + (hc : 0 < c) (hc' : c ≤ 1) (hε : 0 < ε) : + ∃ m : Nat, 2 ≤ m ∧ + Real.sqrt (L ^ 2 / (m : ℝ) ^ 3) / 2 < ε ∧ + Real.sqrt ((1 + L ^ 2 / (m : ℝ) ^ 4) ^ (m ^ 3) - 1) / 2 < ε ∧ + 2 * ((1 / (m : ℝ) ^ 2) * L / (1 - 1 / (m : ℝ) ^ 2)) < ε ∧ + (1 - c / (m : ℝ) ^ 2) ^ (m ^ 3) < ε := by + obtain ⟨m, hm⟩ := exists_nat_gt + (2 + 2 * L ^ 2 + 2 * L ^ 2 / ε ^ 2 + 4 * L / ε + 1 / (c * ε)) + have hs : 0 ≤ 2 * L ^ 2 / ε ^ 2 := by positivity + have hp : 0 ≤ 4 * L / ε := by positivity + have hd : 0 ≤ 1 / (c * ε) := by positivity + have hm2r : (2 : ℝ) < m := by nlinarith [sq_nonneg L] + have hm2 : 2 ≤ m := by exact_mod_cast hm2r.le + have hm0 : 0 < m := by omega + have hmr : (0 : ℝ) < m := by positivity + have hsmall : L ^ 2 / (m : ℝ) ≤ 1/2 := by + apply (div_le_iff₀ hmr).2 + nlinarith + have hlarge : 2 * L ^ 2 / ε ^ 2 < (m : ℝ) := by nlinarith [sq_nonneg L] + have hvar : 2 * L ^ 2 / (m : ℝ) < ε ^ 2 := by + apply (div_lt_iff₀ hmr).2 + have h := (div_lt_iff₀ (sq_pos_of_pos hε)).1 hlarge + nlinarith + have hm3 : (m : ℝ) ≤ (m : ℝ)^3 := by nlinarith [sq_nonneg ((m : ℝ)-1)] + have hidden : L ^ 2 / (m : ℝ)^3 < ε ^ 2 := by + have h := div_le_div_of_nonneg_left (sq_nonneg L) hmr hm3 + have hn : 0 ≤ L^2/(m:ℝ) := by positivity + rw [mul_div_assoc] at hvar + linarith + have sparse : (1+L^2/(m:ℝ)^4)^(m^3)-1 < ε^2 := + (sparse_cube_bound hm0 L hsmall).trans_lt hvar + have hsqrt {x : ℝ} (hx : x < ε^2) : Real.sqrt x / 2 < ε := by + have h := (Real.sqrt_lt' hε).2 hx + linarith + refine ⟨m, hm2, hsqrt hidden, hsqrt sparse, ?_, ?_⟩ + · apply (posterior_cube_bound hm2 hL).trans_lt + have hlarge : 4*L/ε < (m:ℝ) := by nlinarith [sq_nonneg L] + have hsq : (m:ℝ) ≤ (m:ℝ)^2 := by nlinarith + apply (div_le_div_of_nonneg_left (by positivity : 0≤4*L) hmr hsq).trans_lt + apply (div_lt_iff₀ hmr).2 + have h := (div_lt_iff₀ hε).1 hlarge + nlinarith + · apply (clean_cube_bound hc.le hc' hm0).trans_lt + have hlarge : 1/(c*ε) < (m:ℝ) := by nlinarith [sq_nonneg L] + have h := (div_lt_iff₀ (mul_pos hc hε)).1 hlarge + apply (div_lt_iff₀ (by positivity : 0 < 1+c*m)).2 + nlinarith + +end PerfectCompleteness.CubicErrorSchedule + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/CutCallExtension.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/CutCallExtension.lean new file mode 100644 index 0000000000000000000000000000000000000000..0ac1338a921374182288646530e39954a4cf9b96 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/CutCallExtension.lean @@ -0,0 +1,70 @@ +import OAI.Computability.PerfectCompleteness.Foundations.WholeCutGrouping + +namespace OAI + +section + +namespace PerfectCompleteness.CutCallExtension + +open scoped Classical +open TreeSourceSpaces HierarchicalArrays PointwiseSpaces +open UniqueGamesTheorem.Foundations.Games + +noncomputable section + +variable {branch : Nat → Nat} {n t : Nat} {C : Type*} [Fintype C] + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (rows : Nat → Nat) + +abbrev Extended := CutChildGrouping.Raw (C := Option C) slots rows + +def original (x : Extended (C := C) slots rows) : + CutChildGrouping.Raw (C := C) slots rows := + fun i => (fun c => (x i).1 (some c), (x i).2) + +def fresh (x : Extended (C := C) slots rows) : H slots := + UniformChildSum.recursiveSum (LeafDomain slots) (fun i => (x i).1 none) + +def observe (x : Extended (C := C) slots rows) : + CutChildGrouping.Assembled (C := C) slots rows × H slots := + (CutChildGrouping.assemble slots rows (original slots rows x), fresh slots rows x) + +def splitAssembled : CutChildGrouping.Assembled (C := Option C) slots rows →ₗ[F2] + CutChildGrouping.Assembled (C := C) slots rows × H slots where + toFun x := ((fun c => x.1 (some c), x.2), x.1 none) + map_add' _ _ := rfl + map_smul' _ _ := rfl + +omit [Fintype C] in +theorem splitAssembled_surjective : Function.Surjective + (splitAssembled (C := C) slots rows) := by + rintro ⟨⟨old, arrays⟩, extra⟩ + refine ⟨(fun c => match c with | none => extra | some c => old c, arrays), ?_⟩ + rfl + +omit [Fintype C] in +@[simp] theorem split_assemble (x : Extended (C := C) slots rows) : + splitAssembled slots rows (CutChildGrouping.assemble slots rows x) = + observe slots rows x := rfl + +theorem observe_law : + (CutChildGrouping.rawLaw (C := Option C) slots rows).pushforward + (observe slots rows) = + (FiniteDistribution.uniform (CutChildGrouping.Assembled (C := C) slots rows)).product + (FiniteDistribution.uniform (H slots)) := by + change (CutChildGrouping.rawLaw (C := Option C) slots rows).pushforward + (fun x => splitAssembled slots rows (CutChildGrouping.assemble slots rows x)) = _ + rw [← FiniteDistribution.pushforward_comp, CutChildGrouping.assemble_law, + UniformLinearImage.uniform_pushforward_linearMap + (splitAssembled slots rows) (splitAssembled_surjective slots rows)] + exact WholeCutSampler.uniform_product.symm + +theorem call_count : Fintype.card (Option C) = Fintype.card C + 1 := + Fintype.card_option + +end +end PerfectCompleteness.CutCallExtension + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/CutContinuationAveraging.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/CutContinuationAveraging.lean new file mode 100644 index 0000000000000000000000000000000000000000..a23a72a09fc620d2d36a510b471d5476108e413e --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/CutContinuationAveraging.lean @@ -0,0 +1,130 @@ +import OAI.Computability.PerfectCompleteness.Construction.OriginalHiddenChild +import OAI.Computability.PerfectCompleteness.Foundations.OriginalWholeCutBridge + +namespace OAI + +section + +namespace PerfectCompleteness.CutContinuationAveraging + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCutTape OriginalWholeCut OriginalWholeCutLaw +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +noncomputable section + +private theorem sigmaLaw_pushforward {E Γ : Type*} {F : E → Type*} + [Fintype E] [∀ e, Fintype (F e)] [Fintype Γ] + (μ : FiniteDistribution E) (ν : ∀ e, FiniteDistribution (F e)) + (f : ∀ e, F e → Γ) : + (CompletionSoundness.sigmaLaw μ ν).pushforward (fun x => f x.1 x.2) = + μ.mixture (fun e => (ν e).pushforward (f e)) := by + apply FiniteDistribution.eq_of_weight_eq + intro z + simp only [FiniteDistribution.pushforward, CompletionSoundness.sigmaLaw, + FiniteDistribution.mixture, Fintype.sum_sigma, Finset.mul_sum, mul_ite, mul_zero] + +private theorem product_mixture_pushforward {E A B Γ : Type*} + [Fintype E] [Fintype A] [Fintype B] [Fintype Γ] + (μ : FiniteDistribution A) (κ : FiniteDistribution E) + (ν : E → FiniteDistribution B) (f : A × B → Γ) : + (μ.product (κ.mixture ν)).pushforward f = + κ.mixture (fun e => (μ.product (ν e)).pushforward f) := by + have hp : μ.product (κ.mixture ν) = κ.mixture (fun e => μ.product (ν e)) := by + apply FiniteDistribution.eq_of_weight_eq + intro x + simp only [FiniteDistribution.product, FiniteDistribution.mixture, Finset.mul_sum] + apply Finset.sum_congr rfl + intro e _ + exact mul_left_comm _ _ _ + rw [hp, FiniteDistribution.pushforward_mixture] + +private theorem sigma_product_observe {E A B Γ : Type*} + [Fintype E] [Fintype A] [Fintype B] [Fintype Γ] + (μ : FiniteDistribution E) (ν : FiniteDistribution A) + (observe : A → B) (f : E × B → Γ) : + (CompletionSoundness.sigmaLaw μ (fun _ => ν)).pushforward + (fun z => f (z.1, observe z.2)) = + (μ.product (ν.pushforward observe)).pushforward f := by + have hp : (μ.product ν).pushforward (fun z => (z.1, observe z.2)) = + μ.product (ν.pushforward observe) := by + simpa only [FiniteDistribution.pushforward_id, id_eq] using + FiniteDistribution.product_pushforward μ ν id observe + rw [← hp, FiniteDistribution.pushforward_comp] + apply FiniteDistribution.eq_of_weight_eq + intro z + simp only [FiniteDistribution.pushforward, CompletionSoundness.sigmaLaw, + FiniteDistribution.product, Fintype.sum_sigma, Fintype.sum_prod_type] + +variable {branch : Nat → Nat} {n m t : Nat} + +def originalArrayLaw (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (hbranch : ∀ k < m + 1, 0 < branch k) : FiniteDistribution (Arrays slots rows) := + (GeometricPath.law (m + 1) hbranch).mixture (fun leaf => + WholeArraySampler.law rows repeats (p.append (GeometricPath.leafPath leaf)) slots) + +theorem observed_sourceLaw_eq_mixture (calls : Nat) (rows repeats : Nat → Nat) + (slots : Slots branch (m + 1) → Fin t → MixedSupport.Slot) + (hbranch : ∀ k < m + 1, 0 < branch k) : + (OriginalHiddenChild.sourceLaw calls rows repeats slots hbranch).pushforward + (OriginalHiddenChild.observed calls rows repeats slots) = + (GeometricPath.law (m + 1) hbranch).mixture (fun leaf => + (OriginalChildBlocks.sourceLaw calls rows repeats leaf.1 + (GeometricPath.leafPath leaf.2) slots).pushforward + (OriginalChildBlocks.observed calls rows repeats leaf.1 + (GeometricPath.leafPath leaf.2) slots)) := by + unfold OriginalHiddenChild.sourceLaw OriginalHiddenChild.observed + exact sigmaLaw_pushforward + (E := Slots branch (m + 1)) + (F := fun leaf => OriginalChildBlocks.SourceTape calls rows repeats leaf.1 + (GeometricPath.leafPath leaf.2) slots) + (Γ := CutChildGrouping.Assembled (C := Fin calls) slots rows) + (GeometricPath.law (m + 1) hbranch) + (fun leaf => OriginalChildBlocks.sourceLaw calls rows repeats leaf.1 + (GeometricPath.leafPath leaf.2) slots) + (fun leaf tape => OriginalChildBlocks.observed calls rows repeats leaf.1 + (GeometricPath.leafPath leaf.2) slots tape) + +theorem originalArrayLaw_eq (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (hbranch : ∀ k < m + 1, 0 < branch k) : + originalArrayLaw rows repeats p slots hbranch = + ((exteriorLaw rows repeats p slots).product + ((OriginalHiddenChild.sourceLaw (OriginalCutCalls.count rows repeats n (m + 1)) + rows repeats (cutSlots p slots) hbranch).pushforward + (OriginalHiddenChild.observed (OriginalCutCalls.count rows repeats n (m + 1)) + rows repeats (cutSlots p slots)))).pushforward + (OriginalWholeCutBridge.reconstruct rows repeats p slots) := by + symm + rw [observed_sourceLaw_eq_mixture, product_mixture_pushforward] + apply congrArg ((GeometricPath.law (m + 1) hbranch).mixture) + funext leaf + exact OriginalWholeCutBridge.reconstruct_child_law rows repeats p leaf.1 + (GeometricPath.leafPath leaf.2) slots + +theorem originalArrayLaw_eq_sigma (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (hbranch : ∀ k < m + 1, 0 < branch k) : + originalArrayLaw rows repeats p slots hbranch = + (CompletionSoundness.sigmaLaw (exteriorLaw rows repeats p slots) (fun _ => + OriginalHiddenChild.sourceLaw (OriginalCutCalls.count rows repeats n (m + 1)) + rows repeats (cutSlots p slots) hbranch)).pushforward + (fun z => OriginalWholeCutBridge.reconstruct rows repeats p slots + (z.1, OriginalHiddenChild.observed (OriginalCutCalls.count rows repeats n (m + 1)) + rows repeats (cutSlots p slots) z.2)) := by + rw [originalArrayLaw_eq] + exact (sigma_product_observe (exteriorLaw rows repeats p slots) + (OriginalHiddenChild.sourceLaw (OriginalCutCalls.count rows repeats n (m + 1)) + rows repeats (cutSlots p slots) hbranch) + (OriginalHiddenChild.observed (OriginalCutCalls.count rows repeats n (m + 1)) + rows repeats (cutSlots p slots)) + (OriginalWholeCutBridge.reconstruct rows repeats p slots)).symm + +end +end PerfectCompleteness.CutContinuationAveraging + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/CutNativeForms.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/CutNativeForms.lean new file mode 100644 index 0000000000000000000000000000000000000000..7a99c0c1451c34ce5f8589f8445c2bb1497c9555 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/CutNativeForms.lean @@ -0,0 +1,238 @@ +import OAI.Computability.PerfectCompleteness.Construction.SourceLocalOddLists +import OAI.Computability.PerfectCompleteness.Foundations.CutSlotAssembly + +namespace OAI + +section + +namespace PerfectCompleteness.CutNativeForms + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays PointwiseSpaces + +variable {branch : Nat → Nat} {n k t : Nat} + +theorem nodeSlots_fill (lower : Nodes branch n) + (outside : Slots branch n → Fin t → MixedSupport.Slot) + (inside : Slots branch (Nodes.height lower) → Fin t → MixedSupport.Slot) : + nodeSlots (CutSlotAssembly.fill (Nodes.path lower) outside inside) lower = inside := by + funext s + exact CutSlotAssembly.fill_at_cut (Nodes.path lower) outside inside s + +theorem nodeSlots_fill_of_agree (lower : Nodes branch n) + (p : Path branch n (Nodes.height lower)) + (outside : Slots branch n → Fin t → MixedSupport.Slot) + (inside : Slots branch (Nodes.height lower) → Fin t → MixedSupport.Slot) + (hag : ∀ s, p.slotEmbedding s = (Nodes.path lower).slotEmbedding s) : + nodeSlots (CutSlotAssembly.fill p outside inside) lower = inside := by + funext s + change CutSlotAssembly.fill p outside inside ((Nodes.path lower).slotEmbedding s) = inside s + rw [← hag s] + exact CutSlotAssembly.fill_at_cut p outside inside s + +section Equality + +variable {a b c d : Slots branch k → Fin t → MixedSupport.Slot} + +def spaceCast (hab : a = b) : H a ≃ₗ[F2] H b := by + cases hab + exact LinearEquiv.refl F2 (H a) + +def squareCast (hab : a = b) : squareSpace (H a) ≃ₗ[F2] squareSpace (H b) := by + cases hab + exact LinearEquiv.refl F2 (squareSpace (H a)) + +def dualCast (hab : a = b) (z : Module.Dual F2 (squareSpace (H a))) : + Module.Dual F2 (squareSpace (H b)) := by + cases hab + exact z + +def formCast (hab : a = b) (F : SourceLocalOddLists.Form a) : SourceLocalOddLists.Form b := by + cases hab + exact F + +@[simp] theorem dualCast_apply (hab : a = b) + (z : Module.Dual F2 (squareSpace (H a))) (f : squareSpace (H a)) : + dualCast hab z (squareCast hab f) = z f := by + cases hab + rfl + +@[simp] theorem formCast_apply (hab : a = b) (F : SourceLocalOddLists.Form a) + (f g : H a) : formCast hab F (spaceCast hab f) (spaceCast hab g) = F f g := by + cases hab + rfl + +theorem squareCast_product (hab : a = b) (f g : H a) : + squareCast hab (OddListExtraction.productElement (H a) f g) = + OddListExtraction.productElement (H b) (spaceCast hab f) (spaceCast hab g) := by + cases hab + rfl + +theorem formCast_multiplication (hab : a = b) + (z : Module.Dual F2 (squareSpace (H a))) : + formCast hab (OddListExtraction.multiplicationForm (H a) z) = + OddListExtraction.multiplicationForm (H b) (dualCast hab z) := by + cases hab + rfl + +theorem formRank_formCast (hab : a = b) (F : SourceLocalOddLists.Form a) : + OddListExtraction.formRank (H b) (formCast hab F) = + OddListExtraction.formRank (H a) F := by + cases hab + rfl + +theorem squareCast_one (hab : a = b) + (ha : (1 : Domain a → F2) ∈ squareSpace (H a)) + (hb : (1 : Domain b → F2) ∈ squareSpace (H b)) : + squareCast hab ⟨1, ha⟩ = ⟨1, hb⟩ := by + cases hab + rfl + +theorem dualCast_one (hab : a = b) (z : Module.Dual F2 (squareSpace (H a))) + (ha : (1 : Domain a → F2) ∈ squareSpace (H a)) + (hb : (1 : Domain b → F2) ∈ squareSpace (H b)) : + dualCast hab z ⟨1, hb⟩ = z ⟨1, ha⟩ := by + cases hab + rfl + +def oneElement (slots : Slots branch k → Fin t → MixedSupport.Slot) + (hbranch : ∀ j < k, 0 < branch j) : squareSpace (H slots) := + ⟨(1 : Domain slots → F2), TreeSourceSpaces.one_mem_squareSpace slots hbranch⟩ + +theorem dualCast_normalized (hab : a = b) (hbranch : ∀ j < k, 0 < branch j) + (z : Module.Dual F2 (squareSpace (H a))) + (hnorm : z (oneElement a hbranch) = 1) : + dualCast hab z (oneElement b hbranch) = 1 := by + cases hab + exact hnorm + +def projectionCast (hab : a = b) (hcd : c = d) + (p : ∀ s j, MixedSupport.Projection (a s j) (c s j)) : + ∀ s j, MixedSupport.Projection (b s j) (d s j) := by + cases hab + cases hcd + exact p + +theorem spaceCast_HPullback (hab : a = b) (hcd : c = d) + (p : ∀ s j, MixedSupport.Projection (a s j) (c s j)) (f : H c) : + spaceCast hab (HPullback p f) = + HPullback (projectionCast hab hcd p) (spaceCast hcd f) := by + cases hab + cases hcd + rfl + +theorem formCast_projection_agreement (hab : a = b) (hcd : c = d) + (p : ∀ s j, MixedSupport.Projection (a s j) (c s j)) + (F : SourceLocalOddLists.Form a) (G : SourceLocalOddLists.Form c) + (hagree : ∀ f g, G f g = F (HPullback p f) (HPullback p g)) : + ∀ f g, formCast hcd G f g = formCast hab F + (HPullback (projectionCast hab hcd p) f) + (HPullback (projectionCast hab hcd p) g) := by + cases hab + cases hcd + exact hagree + +theorem dualCast_projection_agreement (hab : a = b) (hcd : c = d) + (p : ∀ s j, MixedSupport.Projection (a s j) (c s j)) + (z : Module.Dual F2 (squareSpace (H a))) (G : SourceLocalOddLists.Form c) + (hagree : ∀ f g, G f g = OddListExtraction.multiplicationForm (H a) z + (HPullback p f) (HPullback p g)) : + ∀ f g, formCast hcd G f g = + OddListExtraction.multiplicationForm (H b) (dualCast hab z) + (HPullback (projectionCast hab hcd p) f) + (HPullback (projectionCast hab hcd p) g) := by + cases hab + cases hcd + exact hagree + +end Equality + +section Native + +variable (lower : Nodes branch n) (p : Path branch n (Nodes.height lower)) + (outside : Slots branch n → Fin t → MixedSupport.Slot) + (inside : Slots branch (Nodes.height lower) → Fin t → MixedSupport.Slot) + (hag : ∀ s, p.slotEmbedding s = (Nodes.path lower).slotEmbedding s) + +def nativeDual + (z : Module.Dual F2 (squareSpace (H (nodeSlots (CutSlotAssembly.fill p outside inside) lower)))) : + Module.Dual F2 (squareSpace (H inside)) := + dualCast (nodeSlots_fill_of_agree lower p outside inside hag) z + +def nativeForm + (F : SourceLocalOddLists.Form (nodeSlots (CutSlotAssembly.fill p outside inside) lower)) : + SourceLocalOddLists.Form inside := + formCast (nodeSlots_fill_of_agree lower p outside inside hag) F + +theorem nativeForm_multiplication + (z : Module.Dual F2 (squareSpace (H (nodeSlots (CutSlotAssembly.fill p outside inside) lower)))) : + nativeForm lower p outside inside hag + (OddListExtraction.multiplicationForm + (H (nodeSlots (CutSlotAssembly.fill p outside inside) lower)) z) = + OddListExtraction.multiplicationForm (H inside) (nativeDual lower p outside inside hag z) := + formCast_multiplication (nodeSlots_fill_of_agree lower p outside inside hag) z + +theorem nativeForm_rank + (F : SourceLocalOddLists.Form (nodeSlots (CutSlotAssembly.fill p outside inside) lower)) : + OddListExtraction.formRank (H inside) (nativeForm lower p outside inside hag F) = + OddListExtraction.formRank (H (nodeSlots (CutSlotAssembly.fill p outside inside) lower)) F := + formRank_formCast (nodeSlots_fill_of_agree lower p outside inside hag) F + +theorem nativeDual_normalized (hbranch : ∀ j < Nodes.height lower, 0 < branch j) + (z : Module.Dual F2 (squareSpace (H (nodeSlots (CutSlotAssembly.fill p outside inside) lower)))) + (hnorm : z (oneElement + (nodeSlots (CutSlotAssembly.fill p outside inside) lower) hbranch) = 1) : + nativeDual lower p outside inside hag z (oneElement inside hbranch) = 1 := + dualCast_normalized (nodeSlots_fill_of_agree lower p outside inside hag) hbranch z hnorm + +variable (outside' : Slots branch n → Fin t → MixedSupport.Slot) + (inside' : Slots branch (Nodes.height lower) → Fin t → MixedSupport.Slot) + +def nativeProjection + (projection : ∀ s j, MixedSupport.Projection + (nodeSlots (CutSlotAssembly.fill p outside inside) lower s j) + (nodeSlots (CutSlotAssembly.fill p outside' inside') lower s j)) : + ∀ s j, MixedSupport.Projection (inside s j) (inside' s j) := + projectionCast (nodeSlots_fill_of_agree lower p outside inside hag) + (nodeSlots_fill_of_agree lower p outside' inside' hag) projection + +theorem nativeForm_projection_agreement + (projection : ∀ s j, MixedSupport.Projection + (nodeSlots (CutSlotAssembly.fill p outside inside) lower s j) + (nodeSlots (CutSlotAssembly.fill p outside' inside') lower s j)) + (F : SourceLocalOddLists.Form (nodeSlots (CutSlotAssembly.fill p outside inside) lower)) + (G : SourceLocalOddLists.Form (nodeSlots (CutSlotAssembly.fill p outside' inside') lower)) + (hagree : ∀ f g, G f g = F (HPullback projection f) (HPullback projection g)) : + ∀ f g, nativeForm lower p outside' inside' hag G f g = + nativeForm lower p outside inside hag F + (HPullback (nativeProjection lower p outside inside hag outside' inside' projection) f) + (HPullback (nativeProjection lower p outside inside hag outside' inside' projection) g) := + formCast_projection_agreement (nodeSlots_fill_of_agree lower p outside inside hag) + (nodeSlots_fill_of_agree lower p outside' inside' hag) projection F G hagree + +theorem nativeDual_projection_agreement + (projection : ∀ s j, MixedSupport.Projection + (nodeSlots (CutSlotAssembly.fill p outside inside) lower s j) + (nodeSlots (CutSlotAssembly.fill p outside' inside') lower s j)) + (z : Module.Dual F2 (squareSpace (H (nodeSlots (CutSlotAssembly.fill p outside inside) lower)))) + (G : SourceLocalOddLists.Form (nodeSlots (CutSlotAssembly.fill p outside' inside') lower)) + (hagree : ∀ f g, G f g = OddListExtraction.multiplicationForm + (H (nodeSlots (CutSlotAssembly.fill p outside inside) lower)) z + (HPullback projection f) (HPullback projection g)) : + ∀ f g, nativeForm lower p outside' inside' hag G f g = + OddListExtraction.multiplicationForm (H inside) (nativeDual lower p outside inside hag z) + (HPullback (nativeProjection lower p outside inside hag outside' inside' projection) f) + (HPullback (nativeProjection lower p outside inside hag outside' inside' projection) g) := + dualCast_projection_agreement (nodeSlots_fill_of_agree lower p outside inside hag) + (nodeSlots_fill_of_agree lower p outside' inside' hag) projection z G hagree + +end Native + +end +end PerfectCompleteness.CutNativeForms + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/CutSlotAssembly.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/CutSlotAssembly.lean new file mode 100644 index 0000000000000000000000000000000000000000..c64897e21c165a849bf0c20d3da6187e5f9e4153 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/CutSlotAssembly.lean @@ -0,0 +1,93 @@ +import OAI.Computability.PerfectCompleteness.Foundations.WholeCutReplayKeys + +namespace OAI + +section + +namespace PerfectCompleteness.CutSlotAssembly + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces + +variable {branch : Nat → Nat} {n m : Nat} {V : Type*} + +def fill : {n m : Nat} → Path branch n m → + (Slots branch n → V) → (Slots branch m → V) → Slots branch n → V + | _, _, .refl _, _, inside, s => inside s + | _, _, .step i p, outside, inside, s => + if s.1 = i then fill p (fun j => outside (i, j)) inside s.2 else outside s + +@[simp] theorem fill_at_cut (p : Path branch n m) + (outside : Slots branch n → V) (inside : Slots branch m → V) + (s : Slots branch m) : + fill p outside inside (p.slotEmbedding s) = inside s := by + revert outside inside s + induction p with + | refl _ => intros; rfl + | step i p ih => + intro outside inside s + simp only [fill, Path.slotEmbedding] + exact ih (fun j => outside (i, j)) inside s + +theorem fill_restrict (p : Path branch n m) (outside : Slots branch n → V) : + fill p outside (fun s => outside (p.slotEmbedding s)) = outside := by + induction p with + | refl _ => rfl + | step i p ih => + funext s + by_cases hs : s.1 = i + · obtain ⟨j, s⟩ := s + dsimp only at hs + subst j + simp only [fill] + exact congrFun (ih (fun j => outside (i, j))) s + · simp only [fill, ite_eq_right hs] + +theorem fill_kept_eq (p : Path branch n (m + 1)) + (outside : Slots branch n → V) (left right : Slots branch (m + 1) → V) + (clean : Fin (branch m) → Prop) + (h : ∀ (i : Fin (branch m)), ¬ clean i → ∀ s, left (i, s) = right (i, s)) : + ∀ s, CutSamplerKeyLocality.keptLeaf p clean s → + fill p outside left s = fill p outside right s := by + revert outside left right clean h + induction n generalizing m with + | zero => + have hp := p.height_le + omega + | succ n ih => + cases p with + | refl => + intro outside left right clean h s hs + exact h s.1 hs s.2 + | step i p => + intro outside left right clean h s hs + by_cases hi : s.1 = i + · simp only [fill, ite_eq_left hi] + exact ih p (fun j => outside (i, j)) left right clean h s.2 + (hs.resolve_left (not_not_intro hi)) + · simp only [fill, ite_eq_right hi] + +section Replay + +variable {t : Nat} (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) + (outside : Slots branch n → Fin t → MixedSupport.Slot) + (reference target : Slots branch (m + 1) → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (h : ∀ (i : Fin (branch m)), ¬ clean i → ∀ s, reference (i, s) = target (i, s)) + +def transport (tape : WholeCutReplay.Tape rows repeats p (fill p outside reference) clean) : + WholeCutReplay.Tape rows repeats p (fill p outside target) clean := + WholeCutReplayKeys.transportTape rows repeats p (fill p outside reference) + (fill p outside target) clean (fill_kept_eq p outside reference target clean h) tape + +end Replay + +end +end PerfectCompleteness.CutSlotAssembly + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/CutSlotOutside.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/CutSlotOutside.lean new file mode 100644 index 0000000000000000000000000000000000000000..98f32cf01a9336aa3a62c98ca1b041517e4e1f7c --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/CutSlotOutside.lean @@ -0,0 +1,49 @@ +import OAI.Computability.PerfectCompleteness.Foundations.CutSlotAssembly + +namespace OAI + +section + +namespace PerfectCompleteness.CutSlotAssembly + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces + +variable {branch : Nat → Nat} {n m : Nat} {V : Type*} + +theorem fill_outside (p : Path branch n m) + (outside : Slots branch n → V) (inside : Slots branch m → V) + (s : Slots branch n) (hs : s ∉ Set.range p.slotEmbedding) : + fill p outside inside s = outside s := by + revert outside inside s hs + induction p with + | refl _ => + intro outside inside s hs + exact False.elim (hs ⟨s, rfl⟩) + | step i p ih => + intro outside inside s hs + obtain ⟨j, s⟩ := s + by_cases hji : j = i + · subst j + have htail : s ∉ Set.range p.slotEmbedding := by + rintro ⟨a, ha⟩ + apply hs + exact ⟨a, congrArg (fun b => (i, b)) ha⟩ + simpa only [fill, ite_eq_left rfl, ite_true] using + ih (fun b => outside (i, b)) inside s htail + · simp only [fill, ite_eq_right hji] + +theorem fill_outside_eq (p : Path branch n m) + (outside : Slots branch n → V) (left right : Slots branch m → V) + (s : Slots branch n) (hs : s ∉ Set.range p.slotEmbedding) : + fill p outside left s = fill p outside right s := by + rw [fill_outside p outside left s hs, fill_outside p outside right s hs] + +end +end PerfectCompleteness.CutSlotAssembly + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/CutTerminalSplit.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/CutTerminalSplit.lean new file mode 100644 index 0000000000000000000000000000000000000000..172c990b06062623647ac5a194a972111b58188d --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/CutTerminalSplit.lean @@ -0,0 +1,138 @@ +import Mathlib.Logic.Equiv.Prod +import OAI.Computability.PerfectCompleteness.Construction.HiddenBucketBias +import OAI.Computability.PerfectCompleteness.Foundations.TerminalCalls +import OAI.Computability.PerfectCompleteness.Sampling.CutSamplerRefinement +import OAI.Computability.UniqueGames.Foundations.SamplingLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.CutTerminalSplit + +open PointwiseSpaces RecursiveSpaces DescendantSpaces RecursiveSampler TerminalCalls +open UniqueGamesTheorem.Foundations.Games +open scoped Classical + +noncomputable section + +universe u w + +variable {branch : Nat → Nat} {n m : Nat} + +theorem refinedSpace_eq_terminal (𝕜 : Type w) [Field 𝕜] + (repeats : Nat → Nat) (p : Path branch n m) : + ∀ (A : Slots branch n → Type u) (terminal : TerminalIndex repeats p), + CutSamplerRefinement.RefinedSpace 𝕜 repeats p A (drawIndex repeats p terminal) = + CutSamplerRefinement.RefinedSpace 𝕜 repeats (.refl m) (p.family A) () := by + induction p with + | refl n => + intro A terminal + cases terminal + rfl + | step i p ih => + intro A terminal + exact ih (childFamily A i) terminal.2 + +variable (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) + (p : Path branch n (m + 1)) (A : Slots branch n → Type u) + +abbrev TerminalFactor := + (i : Fin (branch m)) → squareSpace (space 𝕜 branch m (childFamily (p.family A) i)) + +abbrev TerminalTape := TerminalIndex repeats p → TerminalFactor 𝕜 p A + +abbrev ExteriorIndex := {j : DrawIndex repeats p // ¬ IsTerminal repeats p j} + +abbrev ExteriorTape := + (j : ExteriorIndex repeats p) → CutSamplerRefinement.RefinedSpace 𝕜 repeats p A j.val + +def terminalFactorEquiv (terminal : TerminalIndex repeats p) : + CutSamplerRefinement.RefinedSpace 𝕜 repeats p A (drawIndex repeats p terminal) ≃ + TerminalFactor 𝕜 p A := + Equiv.cast (refinedSpace_eq_terminal 𝕜 repeats p A terminal) + +def terminalTapeEquiv : + ((j : {j : DrawIndex repeats p // IsTerminal repeats p j}) → + CutSamplerRefinement.RefinedSpace 𝕜 repeats p A j.val) ≃ + TerminalTape 𝕜 repeats p A := + ((Equiv.piCongrLeft + (fun j : {j : DrawIndex repeats p // IsTerminal repeats p j} => + CutSamplerRefinement.RefinedSpace 𝕜 repeats p A j.val) + (terminalSubtypeEquiv repeats p)).symm).trans + (Equiv.piCongrRight (terminalFactorEquiv 𝕜 repeats p A)) + +def splitTape : + CutSamplerRefinement.Tape 𝕜 repeats p A ≃ + TerminalTape 𝕜 repeats p A × ExteriorTape 𝕜 repeats p A := + (Equiv.piEquivPiSubtypeProd (IsTerminal repeats p) + (CutSamplerRefinement.RefinedSpace 𝕜 repeats p A)).trans + (Equiv.prodCongr (terminalTapeEquiv 𝕜 repeats p A) (Equiv.refl _)) + +@[simp] theorem splitTape_terminal_apply + (x : CutSamplerRefinement.Tape 𝕜 repeats p A) (terminal : TerminalIndex repeats p) : + (splitTape 𝕜 repeats p A x).1 terminal = + terminalFactorEquiv 𝕜 repeats p A terminal (x (drawIndex repeats p terminal)) := rfl + +@[simp] theorem splitTape_exterior_apply + (x : CutSamplerRefinement.Tape 𝕜 repeats p A) (j : ExteriorIndex repeats p) : + (splitTape 𝕜 repeats p A x).2 j = x j.val := rfl + +variable [Finite 𝕜] [∀ s, Finite (A s)] + +instance childSquareFintype (i : Fin (branch m)) : + Fintype (squareSpace (space 𝕜 branch m (childFamily (p.family A) i))) := + Fintype.ofFinite _ + +def terminalLaw : FiniteDistribution (TerminalTape 𝕜 repeats p A) := + FiniteProduct.law (fun _ : TerminalIndex repeats p => + FiniteProduct.law (fun i : Fin (branch m) => + FiniteDistribution.uniform + (squareSpace (space 𝕜 branch m (childFamily (p.family A) i))))) + +def exteriorLaw : FiniteDistribution (ExteriorTape 𝕜 repeats p A) := + FiniteProduct.law (fun j : ExteriorIndex repeats p => + FiniteDistribution.uniform (CutSamplerRefinement.RefinedSpace 𝕜 repeats p A j.val)) + +theorem terminalLaw_uniform : + terminalLaw 𝕜 repeats p A = FiniteDistribution.uniform (TerminalTape 𝕜 repeats p A) := by + simp only [terminalLaw, UniformLinearImage.law_uniform] + +theorem exteriorLaw_uniform : + exteriorLaw 𝕜 repeats p A = FiniteDistribution.uniform (ExteriorTape 𝕜 repeats p A) := + UniformLinearImage.law_uniform + +theorem split_tapeLaw : + (CutSamplerRefinement.tapeLaw 𝕜 repeats p A).pushforward (splitTape 𝕜 repeats p A) = + (terminalLaw 𝕜 repeats p A).product (exteriorLaw 𝕜 repeats p A) := by + unfold CutSamplerRefinement.tapeLaw + rw [UniformLinearImage.law_uniform, FiniteDistribution.pushforward_equiv, + terminalLaw_uniform, exteriorLaw_uniform] + apply FiniteDistribution.eq_of_weight_eq + intro x + change 1 / (Fintype.card (CutSamplerRefinement.Tape 𝕜 repeats p A) : ℝ) = + (1 / (Fintype.card (TerminalTape 𝕜 repeats p A) : ℝ)) * + (1 / (Fintype.card (ExteriorTape 𝕜 repeats p A) : ℝ)) + rw [Fintype.card_congr (splitTape 𝕜 repeats p A), Fintype.card_prod] + simp only [Nat.cast_mul, one_div, mul_inv] + +theorem terminal_marginal : + (CutSamplerRefinement.tapeLaw 𝕜 repeats p A).pushforward + (fun x => (splitTape 𝕜 repeats p A x).1) = terminalLaw 𝕜 repeats p A := by + rw [← FiniteDistribution.pushforward_comp (CutSamplerRefinement.tapeLaw 𝕜 repeats p A) + (splitTape 𝕜 repeats p A) Prod.fst, split_tapeLaw] + exact HiddenBucketBias.product_fst + (terminalLaw 𝕜 repeats p A) (exteriorLaw 𝕜 repeats p A) + +theorem terminal_marginal_uniform : + (CutSamplerRefinement.tapeLaw 𝕜 repeats p A).pushforward + (fun x => (splitTape 𝕜 repeats p A x).1) = + FiniteDistribution.uniform (TerminalTape 𝕜 repeats p A) := by + rw [terminal_marginal, terminalLaw_uniform] + +end +end PerfectCompleteness.CutTerminalSplit + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/CutTerminalZero.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/CutTerminalZero.lean new file mode 100644 index 0000000000000000000000000000000000000000..40aa5f55bf0418b6c170d23a8a53dd476afca2a3 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/CutTerminalZero.lean @@ -0,0 +1,101 @@ +import OAI.Computability.PerfectCompleteness.Foundations.CutTerminalSplit +import OAI.Computability.PerfectCompleteness.Sampling.CutSamplerLocality + +namespace OAI + +section + +namespace PerfectCompleteness.CutTerminalZero + +open RecursiveSpaces DescendantSpaces RecursiveSampler TerminalCalls +open scoped Classical + +noncomputable section + +universe u w + +variable {branch : Nat → Nat} {n m : Nat} + (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) + +theorem terminalFactorEquiv_refl (A : Slots branch (m + 1) → Type u) + (terminal : TerminalIndex repeats (.refl (m + 1))) + (x : CutSamplerRefinement.RefinedSpace 𝕜 repeats (.refl (m + 1)) A + (drawIndex repeats (.refl (m + 1)) terminal)) : + CutTerminalSplit.terminalFactorEquiv 𝕜 repeats (.refl (m + 1)) A terminal x = x := rfl + +theorem terminalFactorEquiv_step (i : Fin (branch n)) + (p : Path branch n (m + 1)) (A : Slots branch (n + 1) → Type u) + (call : Fin (repeats (n + 1)) × Bool) (terminal : TerminalIndex repeats p) + (x : CutSamplerRefinement.RefinedSpace 𝕜 repeats p (childFamily A i) + (drawIndex repeats p terminal)) : + CutTerminalSplit.terminalFactorEquiv 𝕜 repeats (.step i p) A (call, terminal) x = + CutTerminalSplit.terminalFactorEquiv 𝕜 repeats p (childFamily A i) terminal x := rfl + +theorem splitTape_terminal_step (i : Fin (branch n)) + (p : Path branch n (m + 1)) (A : Slots branch (n + 1) → Type u) + (tape : CutSamplerRefinement.Tape 𝕜 repeats (.step i p) A) + (h : Fin (repeats (n + 1))) (b : Bool) (terminal : TerminalIndex repeats p) : + (CutTerminalSplit.splitTape 𝕜 repeats (.step i p) A tape).1 ((h, b), terminal) = + (CutTerminalSplit.splitTape 𝕜 repeats p (childFamily A i) + (CutSamplerLocality.subTape 𝕜 repeats i p A tape h b)).1 terminal := by + simp only [CutTerminalSplit.splitTape_terminal_apply] + rfl + +theorem zeroAtClean_iff (p : Path branch n (m + 1)) : + ∀ (A : Slots branch n → Type u) (clean : Fin (branch m) → Prop) + (tape : CutSamplerRefinement.Tape 𝕜 repeats p A), + (∀ terminal i, clean i → + (CutTerminalSplit.splitTape 𝕜 repeats p A tape).1 terminal i = 0) ↔ + CutSamplerLocality.ZeroAtClean 𝕜 repeats p A clean tape := by + induction n generalizing m with + | zero => + have h := p.height_le + omega + | succ n ih => + cases p with + | refl => + intro A clean tape + constructor + · intro hzero i hi + exact hzero () i hi + · intro hzero terminal i hi + cases terminal + exact hzero i hi + | step i p => + intro A clean tape + constructor + · intro hzero h b + apply (ih p (childFamily A i) clean + (CutSamplerLocality.subTape 𝕜 repeats i p A tape h b)).mp + intro terminal j hj + apply Subtype.ext + have hread := congrArg + (fun f : CutTerminalSplit.TerminalFactor 𝕜 (.step i p) A => (f j).val) + (splitTape_terminal_step 𝕜 repeats i p A tape h b terminal) + exact hread.symm.trans (congrArg Subtype.val (hzero ((h, b), terminal) j hj)) + · intro hzero terminal j hj + rcases terminal with ⟨⟨h, b⟩, terminal⟩ + have hsub := (ih p (childFamily A i) clean + (CutSamplerLocality.subTape 𝕜 repeats i p A tape h b)).mpr (hzero h b) + apply Subtype.ext + have hread := congrArg + (fun f : CutTerminalSplit.TerminalFactor 𝕜 (.step i p) A => (f j).val) + (splitTape_terminal_step 𝕜 repeats i p A tape h b terminal) + exact hread.trans (congrArg Subtype.val (hsub terminal j hj)) + +theorem evaluate_factors_of_split_zero (p : Path branch n (m + 1)) + (A : Slots branch n → Type u) (clean : Fin (branch m) → Prop) + (tape : CutSamplerRefinement.Tape 𝕜 repeats p A) + (hzero : ∀ terminal i, clean i → + (CutTerminalSplit.splitTape 𝕜 repeats p A tape).1 terminal i = 0) : + (CutSamplerRefinement.evaluate 𝕜 repeats p A tape).val ∈ + FactoredFunctions.factoringSpace (CutSamplerLocality.view p A clean) := + CutSamplerLocality.evaluate_factors 𝕜 repeats p A clean tape + ((zeroAtClean_iff 𝕜 repeats p A clean tape).mp hzero) + +end +end PerfectCompleteness.CutTerminalZero + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/DependentPredictionDifferenceLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/DependentPredictionDifferenceLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..f705d560870d8690b86b06471440e4816cca9268 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/DependentPredictionDifferenceLemmas.lean @@ -0,0 +1,249 @@ +import OAI.Computability.PerfectCompleteness.Foundations.TupleIndexEmitterLemmas +import OAI.Computability.PerfectCompleteness.Reduction.CompletionSoundness +import OAI.Computability.UniqueGames.Games.FinishBoundsLemmas + +namespace OAI + + +namespace PerfectCompleteness.DependentPredictionDifference + +noncomputable section + +open scoped Classical +open UniqueGamesTheorem.Foundations.Games + +variable {O : Type*} + +abbrev Sample (Ω A : O → Type*) := (o : O) × (Ω o × A o) + +abbrev Observation (P A : O → Type*) := (o : O) × (P o × A o) + +variable [Fintype O] {Ω P A : O → Type*} + [∀ o, Fintype (Ω o)] [∀ o, Fintype (P o)] [∀ o, Fintype (A o)] + +def law (outer : FiniteDistribution O) + (original : ∀ o, FiniteDistribution (Ω o)) + (advice : ∀ o, FiniteDistribution (A o)) : FiniteDistribution (Sample Ω A) := + CompletionSoundness.sigmaLaw outer (fun o => (original o).product (advice o)) + +def observe (p : ∀ o, Ω o → P o) (x : Sample Ω A) : Observation P A := + ⟨x.1, (p x.1 x.2.1, x.2.2)⟩ + +theorem original_usefulness_predicts + (outer : FiniteDistribution O) + (original : ∀ o, FiniteDistribution (Ω o)) + (advice : ∀ o, FiniteDistribution (A o)) + (p : ∀ o, Ω o → P o) (lower : ∀ o, Ω o → Bool) + (I : Observation P A → Bool) (prediction : Sample Ω A → Bool) (κ : ℝ) + (hmarked : ∀ o z a, I ⟨o, (z, a)⟩ = true → + UsefulMark.useful (original o) (p o) (lower o) κ z = true) + (hprediction : ∀ o x a, lower o x = true → I ⟨o, (p o x, a)⟩ = true → + prediction ⟨o, (x, a)⟩ = true) : + κ * (law outer original advice).probability (fun x => I (observe p x)) ≤ + (law outer original advice).probability prediction := by + unfold law + rw [CompletionSoundness.sigmaLaw_probability, CompletionSoundness.sigmaLaw_probability, + ← SmallBiasSlice.expectation_const_mul] + apply SmallBias.expectation_mono + intro o + exact UsefulAdvice.independent_advice_predicts (original o) (advice o) (p o) (lower o) κ + (fun z => I ⟨o, z⟩) (fun x => prediction ⟨o, x⟩) (hmarked o) (hprediction o) + +theorem of_original_usefulness {Γ : Type*} [Fintype Γ] + (outer : FiniteDistribution O) + (original : ∀ o, FiniteDistribution (Ω o)) + (advice : ∀ o, FiniteDistribution (A o)) + (reference : FiniteDistribution Γ) + (p : ∀ o, Ω o → P o) (referenceObserve : Γ → Observation P A) + (lower : ∀ o, Ω o → Bool) + (I J : Observation P A → Bool) (prediction : Sample Ω A → Bool) + (κ ρ q₀ v : ℝ) (hκ : 0 ≤ κ) (hρ : 0 ≤ ρ) (hρ1 : ρ ≤ 1) + (hq₀ : 0 ≤ q₀) (hv : 0 ≤ v) (hsmall : v ≤ ρ * q₀ / 16) + (hmarked : ∀ o z a, I ⟨o, (z, a)⟩ = true → + UsefulMark.useful (original o) (p o) (lower o) κ z = true) + (hprediction : ∀ o x a, lower o x = true → I ⟨o, (p o x, a)⟩ = true → + prediction ⟨o, (x, a)⟩ = true) + (hvariation : ((law outer original advice).pushforward (observe p)).totalVariation + (reference.pushforward referenceObserve) ≤ v) + (hmass : q₀ ≤ reference.probability (fun x => J (referenceObserve x))) + (hdensity : ρ * reference.probability (fun x => J (referenceObserve x)) ≤ + reference.probability (fun x => I (referenceObserve x))) : + κ * ρ * q₀ / 4 ≤ (law outer original advice).probability prediction - + (κ * ρ / 4) * (law outer original advice).probability (fun x => J (observe p x)) := by + apply PredictionDifference.of_observed_variation + (law outer original advice) reference (observe p) referenceObserve I J prediction + κ ρ q₀ v hκ hρ hρ1 hq₀ hv hsmall hvariation hmass hdensity + exact original_usefulness_predicts outer original advice p lower I prediction κ + hmarked hprediction + +end +end PerfectCompleteness.DependentPredictionDifference + + +namespace PerfectCompleteness.LegalEnumeration + +open scoped Classical +open UniqueGamesTheorem.Foundations.Games CompletionSoundness + +noncomputable section + +section Reindex +variable {E E' Q₁ Q₂ Q₁' Q₂' : Type*} + {L : Q₁ → Type*} {R : Q₂ → Type*} + {L' : Q₁' → Type*} {R' : Q₂' → Type*} + [Fintype E] [Fintype E'] + (G : LegalProjectionGame E Q₁ Q₂ L R) + (ee : E ≃ E') (el : Q₁ ≃ Q₁') (er : Q₂ ≃ Q₂') + (al : ∀ x, L x ≃ L' (el x)) (ar : ∀ y, R y ≃ R' (er y)) + +def reindex : LegalProjectionGame E' Q₁' Q₂' L' R' where + occurrences := G.occurrences.transport ee + left i := el (G.left (ee.symm i)) + right i := er (G.right (ee.symm i)) + projection i a := ar (G.right (ee.symm i)) + (G.projection (ee.symm i) ((al (G.left (ee.symm i))).symm a)) + +def strategies : LegalStrategy L R ≃ LegalStrategy L' R' := + (el.piCongr al).prodCongr (er.piCongr ar) + +theorem reindex_wins (s : LegalStrategy L R) (e : E) : + (reindex G ee el er al ar).wins (strategies el er al ar s) (ee e) = G.wins s e := by + simp only [LegalProjectionGame.wins, reindex] + apply decide_eq_decide.mpr + change ar (G.right (ee.symm (ee e))) + (G.projection (ee.symm (ee e)) + ((al (G.left (ee.symm (ee e)))).symm + ((el.piCongr al) s.1 (el (G.left (ee.symm (ee e))))))) = + (er.piCongr ar) s.2 (er (G.right (ee.symm (ee e)))) ↔ + G.projection e (s.1 (G.left e)) = s.2 (G.right e) + rw [ee.symm_apply_apply e] + rw [Equiv.piCongr_apply_apply, Equiv.piCongr_apply_apply, Equiv.symm_apply_apply] + exact (ar (G.right e)).injective.eq_iff + +theorem reindex_success (s : LegalStrategy L R) : + (reindex G ee el er al ar).success (strategies el er al ar s) = G.success s := by + unfold LegalProjectionGame.success + change (G.occurrences.transport ee).probability _ = _ + rw [FiniteDistribution.probability_transport] + congr 1 + funext e + exact reindex_wins G ee el er al ar s e + +section Fibers +variable [∀ x, Fintype (L x)] [∀ x, Fintype (L' x)] + +theorem reindex_fiber_card (i : E') + (b : R' ((reindex G ee el er al ar).right i)) : + Fintype.card {a : L' ((reindex G ee el er al ar).left i) // + (reindex G ee el er al ar).projection i a = b} = + Fintype.card {a : L (G.left (ee.symm i)) // + G.projection (ee.symm i) a = (ar (G.right (ee.symm i))).symm b} := by + apply Fintype.card_congr + apply (al (G.left (ee.symm i))).symm.subtypeEquiv + intro a + change ar (G.right (ee.symm i)) + (G.projection (ee.symm i) ((al (G.left (ee.symm i))).symm a)) = b ↔ _ + constructor + · intro h + have h' := congrArg (ar (G.right (ee.symm i))).symm h + simpa only [Equiv.symm_apply_apply] using h' + · intro h + have h' := congrArg (ar (G.right (ee.symm i))) h + exact h'.trans ((ar (G.right (ee.symm i))).apply_symm_apply b) + +theorem reindex_at_most_two + (hsmall : ∀ e b, Fintype.card {a : L (G.left e) // G.projection e a = b} ≤ 2) + (i : E') (b : R' ((reindex G ee el er al ar).right i)) : + Fintype.card {a : L' ((reindex G ee el er al ar).left i) // + (reindex G ee el er al ar).projection i a = b} ≤ 2 := by + rw [reindex_fiber_card] + exact hsmall _ _ + +end Fibers + +variable [Fintype Q₁] [Fintype Q₂] [Fintype Q₁'] [Fintype Q₂'] + [∀ x, Fintype (L x)] [∀ y, Fintype (R y)] + [∀ x, Fintype (L' x)] [∀ y, Fintype (R' y)] + [∀ x, Nonempty (L x)] [∀ y, Nonempty (R y)] + [∀ x, Nonempty (L' x)] [∀ y, Nonempty (R' y)] + +theorem reindex_value : (reindex G ee el er al ar).value = G.value := by + apply le_antisymm + · obtain ⟨s, hs⟩ := (reindex G ee el er al ar).exists_optimal_strategy + have h := reindex_success G ee el er al ar ((strategies el er al ar).symm s) + rw [Equiv.apply_symm_apply] at h + rw [← hs, h] + exact G.success_le_value _ + · obtain ⟨s, hs⟩ := G.exists_optimal_strategy + rw [← hs, ← reindex_success G ee el er al ar s] + exact (reindex G ee el er al ar).success_le_value _ + +end Reindex + +variable {E Q₁ Q₂ : Type*} [Fintype E] [Fintype Q₁] [Fintype Q₂] + {L : Q₁ → Type*} {R : Q₂ → Type*} + +abbrev NumberedLabels (P : Q₁ → Type*) (i : Fin (Fintype.card Q₁)) := + P ((Fintype.equivFin Q₁).symm i) + +def numberedLabelEquiv (P : Q₁ → Type*) (x : Q₁) : + P x ≃ NumberedLabels P (Fintype.equivFin Q₁ x) := + Equiv.cast (congrArg P ((Fintype.equivFin Q₁).symm_apply_apply x).symm) + +def numbered (G : LegalProjectionGame E Q₁ Q₂ L R) : + LegalProjectionGame (Fin (Fintype.card E)) + (Fin (Fintype.card Q₁)) (Fin (Fintype.card Q₂)) + (NumberedLabels L) (NumberedLabels R) := + reindex G (Fintype.equivFin E) (Fintype.equivFin Q₁) (Fintype.equivFin Q₂) + (numberedLabelEquiv L) (numberedLabelEquiv R) + +theorem numbered_at_most_two [∀ x, Fintype (L x)] + (G : LegalProjectionGame E Q₁ Q₂ L R) + (hsmall : ∀ e b, Fintype.card {a : L (G.left e) // G.projection e a = b} ≤ 2) + (i : Fin (Fintype.card E)) (b : NumberedLabels R ((numbered G).right i)) : + Fintype.card {a : NumberedLabels L ((numbered G).left i) // + (numbered G).projection i a = b} ≤ 2 := + reindex_at_most_two G (Fintype.equivFin E) (Fintype.equivFin Q₁) (Fintype.equivFin Q₂) + (numberedLabelEquiv L) (numberedLabelEquiv R) hsmall i b + +theorem numbered_value [∀ x, Fintype (L x)] [∀ y, Fintype (R y)] + [∀ x, Nonempty (L x)] [∀ y, Nonempty (R y)] + (G : LegalProjectionGame E Q₁ Q₂ L R) : (numbered G).value = G.value := + reindex_value G (Fintype.equivFin E) (Fintype.equivFin Q₁) (Fintype.equivFin Q₂) + (numberedLabelEquiv L) (numberedLabelEquiv R) + +end +end PerfectCompleteness.LegalEnumeration + + +namespace PerfectCompleteness.SigmaObservation + +open UniqueGamesTheorem.Foundations.Games CompletionSoundness + +noncomputable section + +theorem eq_of_probability_eq {X : Type*} [Fintype X] + (μ ν : FiniteDistribution X) + (h : ∀ event : X → Bool, μ.probability event = ν.probability event) : μ = ν := by + classical + apply FiniteDistribution.eq_of_weight_eq + intro x + simpa [FiniteDistribution.probability] using h (fun y => decide (y = x)) + +theorem pushforward_fiber {S : Type*} [Fintype S] {X Y : S → Type*} + [∀ s, Fintype (X s)] [∀ s, Fintype (Y s)] + (μ : FiniteDistribution S) (P : (s : S) → FiniteDistribution (X s)) + (f : (s : S) → X s → Y s) : + (sigmaLaw μ P).pushforward (fun x => (⟨x.1, f x.1 x.2⟩ : Σ s, Y s)) = + sigmaLaw μ (fun s => (P s).pushforward (f s)) := by + apply eq_of_probability_eq + intro event + rw [FiniteDistribution.probability_pushforward, sigmaLaw_probability, sigmaLaw_probability] + apply FiniteDistribution.expectation_congr + intro s + rw [FiniteDistribution.probability_pushforward] + +end +end PerfectCompleteness.SigmaObservation + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/DescriptorKeyTemplate.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/DescriptorKeyTemplate.lean new file mode 100644 index 0000000000000000000000000000000000000000..d2a0c3d4a794424772393a727fd38398d1bb9691 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/DescriptorKeyTemplate.lean @@ -0,0 +1,133 @@ +import OAI.Computability.PerfectCompleteness.Machines.CanonicalKeyMachine +import OAI.Computability.PerfectCompleteness.Reduction.SignedCompletionSchedule + +namespace OAI + +section + +namespace PerfectCompleteness.DescriptorKeyTemplate + +open CanonicalKeys CanonicalKeyShape MixedSupport MetadataFreeSampler ClauseSupport +open scoped Classical + +noncomputable section + +def occurrence : Slot → Nat + | .clause c _ _ => c + | .bit _ => 0 + +def variableIDs : Slot → Fin 3 → Nat + | .clause _ ids _ => ids + | .bit v => fun _ => v + +@[simp] theorem actualSlot_erase (slot : Slot) : + KeyMetadataMachine.actualSlot (erase slot) (occurrence slot) (variableIDs slot) = slot := by + cases slot <;> rfl + +structure Template (width : Nat) where + shapes : Fin width → Shape + modes : Fin width → SupportMode + partition : Set (Set (Fin width → ReducedValue)) + +instance (width : Nat) : Finite (Template width) := by + let : Finite ReducedValue := ReducedDomains.reducedValue_finite + apply Finite.of_injective + (fun template : Template width => (template.shapes, template.modes, template.partition)) + intro a b h + cases a + cases b + cases h + rfl + +def ofInput {width k : Nat} (data : CanonicalKeyShape.Input width k) : Template width := + ⟨data.1, inputModes data, inputPartition data⟩ + +def recover {width : Nat} (side : Side) (template : Template width) + (ids : Fin width → Nat) (vars : Fin width → Fin 3 → Nat) : Key width := + CanonicalKeyMachine.recoveredKey template.shapes template.modes side template.partition ids vars + +theorem recover_ofInput {width k : Nat} (side : Side) (slots : Fin width → Slot) + (data : CanonicalKeyShape.Input width k) (sameShape : data.1 = shape slots) : + recover side (ofInput data) (fun i => occurrence (slots i)) (fun i => variableIDs (slots i)) = + CanonicalKeyShapeMachine.recoverKey side slots data := by + have restored : CanonicalKeyMachine.actualSlots data.1 + (fun i => occurrence (slots i)) (fun i => variableIDs (slots i)) = slots := by + funext i + rw [sameShape] + exact actualSlot_erase (slots i) + change CanonicalKeyMachine.recoveredKey data.1 (inputModes data) side + (inputPartition data) _ _ = _ + unfold CanonicalKeyMachine.recoveredKey + rw [restored] + rfl + +variable {branch : Nat → Nat} {n t q : Nat} {rows repeats : Nat → Nat} + (hq : 0 < q) + (large : CanonicalKeyEncoding.partitionWidth (TreeCanonical.locationCount branch n t) ≤ q) + +def tapeInput (descriptor : SignedCompletionSchedule.Descriptor + (rows := rows) (repeats := repeats) hq large) : + MetadataFreeTape.Input branch n t rows repeats := ⟨descriptor.1, descriptor.2.1⟩ + +def ofTape (side : Side) (data : MetadataFreeTape.Input branch n t rows repeats) : + Template (TreeCanonical.locationCount branch n t) := + match side with + | .left => ofInput (MetadataFreeTape.keyInput data) + | .right => ofInput (FixedQueryCodec.rightKeyInput data) + +def ofDescriptor (side : Side) (descriptor : SignedCompletionSchedule.Descriptor + (rows := rows) (repeats := repeats) hq large) : + Template (TreeCanonical.locationCount branch n t) := ofTape side (tapeInput hq large descriptor) + +theorem ofDescriptor_seed_independent (side : Side) (signs : SignTuple branch n t) + (outcome : MetadataFreeLaw.SignedOutcome signs rows repeats) + (a b : Fin (SignedCompletionSchedule.active hq large signs outcome)) : + ofDescriptor hq large side ⟨signs, outcome, a⟩ = + ofDescriptor hq large side ⟨signs, outcome, b⟩ := rfl + +variable {v m : Nat} + +theorem recover_left (clauses : Fin m → SourceClause.NormalizedClause v) + (e : PreliminarySampler.Raw clauses branch n t rows repeats) : + let slots := TreeCanonical.numberedSlots (sourceSlots clauses e.1.1) + recover .left (ofTape .left (MetadataFreeTape.encodeRaw clauses rows repeats e)) + (fun i => occurrence (slots i)) (fun i => variableIDs (slots i)) = + CanonicalKeys.key .left slots + (TreeCanonical.numberedFunction (sourceSlots clauses e.1.1) + (HierarchicalArrays.fullJoint + (WholeArraySampler.evaluate rows repeats (GeometricPath.leafPath e.1.2) + (sourceSlots clauses e.1.1) e.2.1))) := by + dsimp only + rw [ofTape, recover_ofInput] + · exact MetadataTapeMachine.recoverKey_encodeRaw .left clauses e + · rw [MetadataFreeTape.keyInput_encodeRaw] + rfl + +theorem recover_right (clauses : Fin m → SourceClause.NormalizedClause v) + (e : PreliminarySampler.Raw clauses branch n t rows repeats) : + let slots := TreeCanonical.numberedSlots (sourceSlots clauses e.1.1) + recover .right (ofTape .right (MetadataFreeTape.encodeRaw clauses rows repeats e)) + (fun i => occurrence (slots i)) (fun i => variableIDs (slots i)) = + CanonicalKeys.key .right slots + (FixedQueryCodec.project (FixedQueryCodec.rawTestIndex clauses e) ∘ + TreeCanonical.numberedFunction (sourceSlots clauses e.1.1) + (HierarchicalArrays.fullJoint + (WholeArraySampler.evaluate rows repeats (GeometricPath.leafPath e.1.2) + (sourceSlots clauses e.1.1) e.2.1))) := by + dsimp only + rw [ofTape, recover_ofInput] + · exact FiniteConstraintMachine.recover_right_key clauses e + · rw [FixedQueryCodec.rightKeyInput_encodeRaw] + rfl + +theorem writer_payload {width : Nat} (side : Side) (template : Template width) + (ids : Fin width → Nat) (vars : Fin width → Fin 3 → Nat) : + CanonicalKeyMachine.payload template.shapes template.modes side template.partition ids vars = + CanonicalKeyEncoding.bits (recover side template ids vars) ++ [true] := rfl + +end +end PerfectCompleteness.DescriptorKeyTemplate + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/DesignatedLeavesLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/DesignatedLeavesLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..0fc3a8b6567606976d1fe9b4b6e65d8d89830372 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/DesignatedLeavesLemmas.lean @@ -0,0 +1,210 @@ +import OAI.Computability.PerfectCompleteness.Foundations.RecursiveSpaces +import OAI.Computability.PerfectCompleteness.Repetition.CleanCountingLemmas +import OAI.Computability.PerfectCompleteness.Repetition.RepetitionRateLemmas + +namespace OAI + + +namespace PerfectCompleteness.DesignatedLeaves + +open UniqueGamesTheorem.Foundations.Games +open RecursiveSpaces +open scoped Classical + +noncomputable section + +variable {branch : Nat → Nat} {height : Nat} + (designated : Fin (branch height) → Slots branch height) + (clean : Fin (branch height) → Prop) + +def selected (leaf : Slots branch (height + 1)) : Prop := + clean leaf.1 ∧ leaf.2 = designated leaf.1 + +abbrev Children := {i : Fin (branch height) // clean i} +abbrev Leaves := {leaf : Slots branch (height + 1) // selected designated clean leaf} + +def equiv : Children clean ≃ Leaves designated clean where + toFun i := ⟨(i.val, designated i.val), i.property, rfl⟩ + invFun leaf := ⟨leaf.val.1, leaf.property.1⟩ + left_inv i := rfl + right_inv leaf := by + apply Subtype.ext + exact Prod.ext rfl leaf.property.2.symm + +@[simp] theorem equiv_apply (i : Children clean) : + (equiv designated clean i).val = (i.val, designated i.val) := rfl + +@[simp] theorem equiv_symm_apply (leaf : Leaves designated clean) : + (equiv designated clean).symm leaf = ⟨leaf.val.1, leaf.property.1⟩ := rfl + +theorem card_leaves : Fintype.card (Leaves designated clean) = Fintype.card (Children clean) := + (Fintype.card_congr (equiv designated clean)).symm + + +variable {E Q₁ Q₂ A₁ A₂ : Type*} + [Fintype E] [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂] + (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) + (strategy : Strategy (Leaves designated clean → Q₁) (Leaves designated clean → Q₂) + (Leaves designated clean → A₁) (Leaves designated clean → A₂)) + +def childStrategy : + Strategy (Children clean → Q₁) (Children clean → Q₂) + (Children clean → A₁) (Children clean → A₂) := + IndexedRepetition.reindexStrategy (equiv designated clean) strategy + +theorem wins_eq (occurrences : Children clean → E) : + (IndexedRepetition.game G (Children clean)).wins + (childStrategy designated clean strategy) occurrences = + (IndexedRepetition.game G (Leaves designated clean)).wins strategy + (occurrences ∘ (equiv designated clean).symm) := by + apply Bool.eq_iff_iff.mpr + change (decide (∀ i : Children clean, + G.accepts (occurrences i) + (strategy.1 ((fun i => G.left (occurrences i)) ∘ (equiv designated clean).symm) + (equiv designated clean i)) + (strategy.2 ((fun i => G.right (occurrences i)) ∘ (equiv designated clean).symm) + (equiv designated clean i)) = true) = true) ↔ + (decide (∀ leaf : Leaves designated clean, + G.accepts (occurrences ((equiv designated clean).symm leaf)) + (strategy.1 (fun leaf => G.left (occurrences ((equiv designated clean).symm leaf))) leaf) + (strategy.2 (fun leaf => G.right (occurrences ((equiv designated clean).symm leaf))) leaf) + = true) = true) + simp only [decide_eq_true_eq, Function.comp_def] + constructor + · intro h leaf + simpa only [Equiv.apply_symm_apply] using h ((equiv designated clean).symm leaf) + · intro h i + simpa only [Equiv.symm_apply_apply] using h (equiv designated clean i) + +theorem occurrence_law : + (IndexedRepetition.game G (Leaves designated clean)).occurrences.pushforward + (fun x => x ∘ equiv designated clean) = + (IndexedRepetition.game G (Children clean)).occurrences := + IndexedRepetition.reindex_law G.occurrences (equiv designated clean) + +theorem success_eq : + (IndexedRepetition.game G (Children clean)).success (childStrategy designated clean strategy) = + (IndexedRepetition.game G (Leaves designated clean)).success strategy := + IndexedRepetition.reindex_success G (equiv designated clean) strategy + + +end +end PerfectCompleteness.DesignatedLeaves + + + +namespace PerfectCompleteness.FiniteConditioningBounds + +open scoped BigOperators +open UniqueGamesTheorem.Foundations.Games +open FiniteProduct + +noncomputable section + +variable {Ω : Type*} [Fintype Ω] + +theorem condition_probability_mono_on (P : FiniteDistribution Ω) + (given event target : Ω → Bool) (positive : 0 < P.probability given) + (inclusion : ∀ x, given x = true → event x = true → target x = true) : + (P.condition given positive).probability event ≤ + (P.condition given positive).probability target := by + rw [FiniteDistribution.probability_condition, FiniteDistribution.probability_condition] + apply div_le_div_of_nonneg_right _ positive.le + apply P.probability_mono + intro x hx + have hx' : given x = true ∧ event x = true := by simpa using hx + simpa using And.intro hx'.1 (inclusion x hx'.1 hx'.2) + +theorem sum_record_inter {R : Type*} [Fintype R] [DecidableEq R] + (P : FiniteDistribution Ω) (record : Ω → R) (event : Ω → Bool) : + (∑ r : R, P.probability (fun x => decide (record x = r) && event x)) = + P.probability event := by + unfold FiniteDistribution.probability + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro x _ + cases he : event x <;> simp [he] + +theorem sum_record_weight {R : Type*} [Fintype R] [DecidableEq R] + (P : FiniteDistribution Ω) (record : Ω → R) (bound : R → ℝ) : + (∑ r : R, P.probability (fun x => decide (record x = r)) * bound r) = + P.expectation (fun x => bound (record x)) := by + simp only [FiniteDistribution.probability, FiniteDistribution.expectation, + Finset.sum_mul] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro x _ + simp + +theorem probability_le_record_bound {R : Type*} [Fintype R] [DecidableEq R] + (P : FiniteDistribution Ω) (record : Ω → R) (event : Ω → Bool) + (bound : R → ℝ) + (conditional : ∀ r (positive : 0 < P.probability (fun x => decide (record x = r))), + (P.condition (fun x => decide (record x = r)) positive).probability event ≤ bound r) : + P.probability event ≤ P.expectation (fun x => bound (record x)) := by + rw [← sum_record_inter P record event, ← sum_record_weight P record bound] + apply Finset.sum_le_sum + intro r _ + by_cases positive : 0 < P.probability (fun x => decide (record x = r)) + · rw [P.probability_inter_eq_mul_conditional _ _ positive] + exact mul_le_mul_of_nonneg_left (conditional r positive) (P.probability_nonnegative _) + · have zero : P.probability (fun x => decide (record x = r)) = 0 := + le_antisymm (le_of_not_gt positive) (P.probability_nonnegative _) + rw [P.probability_and_eq_zero_of_probability_eq_zero _ _ zero, zero, zero_mul] + +section Game + +variable {E Q₁ Q₂ A₁ A₂ I : Type*} + [Fintype E] [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂] + [Fintype I] [DecidableEq I] [Nonempty A₁] [Nonempty A₂] + +theorem conditioned_source_success (P : FiniteDistribution Ω) + (given event : Ω → Bool) (positive : 0 < P.probability given) + (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) (source : Ω → I → E) + (source_law : (P.condition given positive).pushforward source = + law (fun _ : I => G.occurrences)) + (strategy : Strategy (I → Q₁) (I → Q₂) (I → A₁) (I → A₂)) + (inclusion : ∀ x, given x = true → event x = true → + (IndexedRepetition.game G I).wins strategy (source x) = true) : + (P.condition given positive).probability event ≤ + (G.repetition (Fintype.card I)).value := by + have hsource := congrArg + (fun D : FiniteDistribution (I → E) => + D.probability ((IndexedRepetition.game G I).wins strategy)) source_law + rw [FiniteDistribution.probability_pushforward] at hsource + calc + _ ≤ (P.condition given positive).probability + (fun x => (IndexedRepetition.game G I).wins strategy (source x)) := + condition_probability_mono_on P given event _ positive inclusion + _ = (IndexedRepetition.game G I).success strategy := hsource + _ ≤ _ := IndexedRepetition.success_le_repetition_value G strategy + +end Game + +theorem independent_clean_bound {I : Type*} [Fintype I] [DecidableEq I] + {A : I → Type*} [∀ i, Fintype (A i)] + {R : Type*} [Fintype R] [DecidableEq R] + (P : (i : I) → FiniteDistribution (A i)) + (clean : (i : I) → A i → Bool) (record : ((i : I) → A i) → R) + (count : R → Nat) + (count_eq : ∀ x, count (record x) = CleanCounting.cleanCount clean x) + (event : ((i : I) → A i) → Bool) (a : ℝ) + (conditional : ∀ r (positive : 0 < + (law P).probability (fun x => decide (record x = r))), + ((law P).condition (fun x => decide (record x = r)) positive).probability event ≤ + a ^ count r) : + (law P).probability event ≤ + ∏ i : I, (1 - (1 - a) * (P i).probability (clean i)) := by + calc + _ ≤ (law P).expectation (fun x => a ^ count (record x)) := + probability_le_record_bound (law P) record event (fun r => a ^ count r) conditional + _ = (law P).expectation (fun x => a ^ CleanCounting.cleanCount clean x) := by + apply FiniteDistribution.expectation_congr + intro x + rw [count_eq] + _ = _ := CleanCounting.cleanCount_moment P clean a + +end +end PerfectCompleteness.FiniteConditioningBounds + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/DualQuotientRowsLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/DualQuotientRowsLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..39bfcb8ae2f690b8ce4fa6f0e0a3d7c17f02177d --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/DualQuotientRowsLemmas.lean @@ -0,0 +1,614 @@ +import Lean.Elab.Tactic.Omega +import Mathlib.Algebra.BigOperators.Expect +import Mathlib.Data.Fintype.BigOperators +import Mathlib.LinearAlgebra.Dual.Lemmas +import OAI.Computability.PerfectCompleteness.Algebra.UniformLinearImage +import OAI.Computability.PerfectCompleteness.Foundations.RecursiveSpaceEquivLemmas +import OAI.Computability.UniqueGames.Games.FinishBoundsLemmas + +namespace OAI + + +namespace PerfectCompleteness.DualQuotientRows + +noncomputable section + +open Module +open UniqueGamesTheorem.Foundations.Games + +variable {𝕜 E : Type*} [Field 𝕜] [AddCommGroup E] [Module 𝕜 E] + +def quotientRowEquiv (W : Submodule 𝕜 E) : + Module.Dual 𝕜 (E ⧸ W) ≃ₗ[𝕜] W.dualAnnihilator := + W.dualQuotEquivDualAnnihilator + +@[simp] +theorem quotientRowEquiv_val (W : Submodule 𝕜 E) (row : Module.Dual 𝕜 (E ⧸ W)) : + (quotientRowEquiv W row : Module.Dual 𝕜 E) = row.comp W.mkQ := rfl + +theorem codim_dualAnnihilator_eq [FiniteDimensional 𝕜 E] (W : Submodule 𝕜 E) : + finrank 𝕜 (Module.Dual 𝕜 E ⧸ W.dualAnnihilator) = finrank 𝕜 W := by + have hquotient := W.dualAnnihilator.finrank_quotient_add_finrank + have hannihilator := Subspace.finrank_add_finrank_dualAnnihilator_eq W + rw [Subspace.dual_finrank_eq] at hquotient + omega + +theorem uniform_quotientRowEquiv (W : Submodule 𝕜 E) + [Fintype (Module.Dual 𝕜 (E ⧸ W))] [Fintype W.dualAnnihilator] : + (FiniteDistribution.uniform (Module.Dual 𝕜 (E ⧸ W))).pushforward + (quotientRowEquiv W) = FiniteDistribution.uniform W.dualAnnihilator := + UniformLinearImage.uniform_pushforward_linearMap + (quotientRowEquiv W).toLinearMap (quotientRowEquiv W).surjective + +theorem uniform_pullback_rows (W : Submodule 𝕜 E) + [Fintype (Module.Dual 𝕜 (E ⧸ W))] [Fintype W.dualAnnihilator] + [Fintype (Module.Dual 𝕜 E)] : + (FiniteDistribution.uniform (Module.Dual 𝕜 (E ⧸ W))).pushforward W.mkQ.dualMap = + (FiniteDistribution.uniform W.dualAnnihilator).pushforward + W.dualAnnihilator.subtype := by + calc + _ = ((FiniteDistribution.uniform (Module.Dual 𝕜 (E ⧸ W))).pushforward + (quotientRowEquiv W)).pushforward W.dualAnnihilator.subtype := by + rw [FiniteDistribution.pushforward_comp] + rfl + _ = _ := by rw [uniform_quotientRowEquiv] + +theorem uniform_affine_pullback_rows (W : Submodule 𝕜 E) + [Fintype (Module.Dual 𝕜 (E ⧸ W))] [Fintype W.dualAnnihilator] + [Fintype (Module.Dual 𝕜 E)] (offset : Module.Dual 𝕜 E) : + (FiniteDistribution.uniform (Module.Dual 𝕜 (E ⧸ W))).pushforward + (fun row => offset + row.comp W.mkQ) = + (FiniteDistribution.uniform W.dualAnnihilator).pushforward + (fun row => offset + (row : Module.Dual 𝕜 E)) := by + calc + _ = ((FiniteDistribution.uniform (Module.Dual 𝕜 (E ⧸ W))).pushforward + (quotientRowEquiv W)).pushforward + (fun row => offset + (row : Module.Dual 𝕜 E)) := by + rw [FiniteDistribution.pushforward_comp] + rfl + _ = _ := by rw [uniform_quotientRowEquiv] + + +variable {H : Type*} [AddCommGroup H] [Module 𝕜 H] [FiniteDimensional 𝕜 H] + +def nativeRowMap (W : Submodule 𝕜 (Module.Dual 𝕜 H)) : + Module.Dual 𝕜 (Module.Dual 𝕜 H ⧸ W) →ₗ[𝕜] H := + (Module.evalEquiv 𝕜 H).symm.toLinearMap.comp W.mkQ.dualMap + +@[simp] +theorem apply_nativeRowMap (W : Submodule 𝕜 (Module.Dual 𝕜 H)) + (row : Module.Dual 𝕜 (Module.Dual 𝕜 H ⧸ W)) (q : Module.Dual 𝕜 H) : + q (nativeRowMap W row) = row (W.mkQ q) := by + change q ((Module.evalEquiv 𝕜 H).symm (W.mkQ.dualMap row)) = _ + rw [Module.apply_evalEquiv_symm_apply] + rfl + +theorem nativeRowMap_injective (W : Submodule 𝕜 (Module.Dual 𝕜 H)) : + Function.Injective (nativeRowMap W) := by + intro row₁ row₂ h + apply (quotientRowEquiv W).injective + apply Subtype.ext + apply (Module.evalEquiv 𝕜 H).symm.injective + exact h + +theorem range_nativeRowMap (W : Submodule 𝕜 (Module.Dual 𝕜 H)) : + LinearMap.range (nativeRowMap W) = W.dualCoannihilator := by + apply le_antisymm + · rintro x ⟨row, rfl⟩ + apply (Submodule.mem_dualCoannihilator _).mpr + intro q hq + rw [apply_nativeRowMap] + have hzero : W.mkQ q = 0 := (Submodule.Quotient.mk_eq_zero W).mpr hq + rw [hzero, map_zero] + · intro x hx + let v : W.dualAnnihilator := ⟨Module.evalEquiv 𝕜 H x, hx⟩ + obtain ⟨row, hrow⟩ := (quotientRowEquiv W).surjective v + refine ⟨row, ?_⟩ + have hvalue := congrArg (fun z : W.dualAnnihilator => + (z : Module.Dual 𝕜 (Module.Dual 𝕜 H))) hrow + change W.mkQ.dualMap row = Module.evalEquiv 𝕜 H x at hvalue + change (Module.evalEquiv 𝕜 H).symm (W.mkQ.dualMap row) = x + rw [hvalue, LinearEquiv.symm_apply_apply] + +def nativeRowLinear (W : Submodule 𝕜 (Module.Dual 𝕜 H)) : + Module.Dual 𝕜 (Module.Dual 𝕜 H ⧸ W) →ₗ[𝕜] W.dualCoannihilator := + (nativeRowMap W).codRestrict W.dualCoannihilator (fun row => by + rw [← range_nativeRowMap W] + exact LinearMap.mem_range_self (nativeRowMap W) row) + +def nativeRowEquiv (W : Submodule 𝕜 (Module.Dual 𝕜 H)) : + Module.Dual 𝕜 (Module.Dual 𝕜 H ⧸ W) ≃ₗ[𝕜] W.dualCoannihilator := + LinearEquiv.ofBijective (nativeRowLinear W) ⟨by + intro row₁ row₂ h + exact nativeRowMap_injective W + (congrArg (fun x : W.dualCoannihilator => (x : H)) h), by + intro x + have hx : (x : H) ∈ LinearMap.range (nativeRowMap W) := by + rw [range_nativeRowMap] + exact x.property + obtain ⟨row, hrow⟩ := hx + exact ⟨row, Subtype.ext hrow⟩⟩ + +@[simp] +theorem nativeRowEquiv_val (W : Submodule 𝕜 (Module.Dual 𝕜 H)) + (row : Module.Dual 𝕜 (Module.Dual 𝕜 H ⧸ W)) : + (nativeRowEquiv W row : H) = nativeRowMap W row := rfl + +theorem codim_dualCoannihilator_eq (W : Submodule 𝕜 (Module.Dual 𝕜 H)) : + finrank 𝕜 (H ⧸ W.dualCoannihilator) = finrank 𝕜 W := by + have hquotient := W.dualCoannihilator.finrank_quotient_add_finrank + have hannihilator := Subspace.finrank_add_finrank_dualCoannihilator_eq W + omega + +theorem uniform_nativeRowEquiv (W : Submodule 𝕜 (Module.Dual 𝕜 H)) + [Fintype (Module.Dual 𝕜 (Module.Dual 𝕜 H ⧸ W))] + [Fintype W.dualCoannihilator] : + (FiniteDistribution.uniform (Module.Dual 𝕜 (Module.Dual 𝕜 H ⧸ W))).pushforward + (nativeRowEquiv W) = FiniteDistribution.uniform W.dualCoannihilator := + UniformLinearImage.uniform_pushforward_linearMap + (nativeRowEquiv W).toLinearMap (nativeRowEquiv W).surjective + +end +end PerfectCompleteness.DualQuotientRows + + + +namespace PerfectCompleteness.LevelPairCounting + +noncomputable section + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games + +variable {Ω : Type*} [Fintype Ω] {d : Nat} + +def winCount (win : Fin d → Ω → Bool) (ω : Ω) : ℝ := + ∑ i, if win i ω then (1 : ℝ) else 0 + +def pairProbability (μ : FiniteDistribution Ω) (win : Fin d → Ω → Bool) + (i j : Fin d) : ℝ := + μ.probability (fun ω => win i ω && win j ω) + +@[simp] theorem pairProbability_self (μ : FiniteDistribution Ω) + (win : Fin d → Ω → Bool) (i : Fin d) : + pairProbability μ win i i = μ.probability (win i) := by + apply congrArg μ.probability + funext ω + cases win i ω <;> rfl + +theorem pairProbability_comm (μ : FiniteDistribution Ω) + (win : Fin d → Ω → Bool) (i j : Fin d) : + pairProbability μ win i j = pairProbability μ win j i := by + apply congrArg μ.probability + funext ω + cases win i ω <;> cases win j ω <;> rfl + +theorem expectation_indicator (μ : FiniteDistribution Ω) (event : Ω → Bool) : + μ.expectation (fun ω => if event ω then (1 : ℝ) else 0) = μ.probability event := by + simp [FiniteDistribution.expectation, FiniteDistribution.probability, mul_ite] + +theorem expectation_indicator_mul (μ : FiniteDistribution Ω) + (win : Fin d → Ω → Bool) (i j : Fin d) : + μ.expectation (fun ω => + (if win i ω then (1 : ℝ) else 0) * (if win j ω then (1 : ℝ) else 0)) = + pairProbability μ win i j := by + unfold FiniteDistribution.expectation pairProbability FiniteDistribution.probability + apply Finset.sum_congr rfl + intro ω _ + cases hi : win i ω <;> cases hj : win j ω <;> simp [hi, hj] + +theorem first_moment_eq_sum (μ : FiniteDistribution Ω) (win : Fin d → Ω → Bool) : + μ.expectation (winCount win) = ∑ i, μ.probability (win i) := by + unfold winCount + rw [SmallBias.expectation_sum] + apply Finset.sum_congr rfl + intro i _ + exact expectation_indicator μ (win i) + +theorem second_moment_eq_sum (μ : FiniteDistribution Ω) (win : Fin d → Ω → Bool) : + μ.expectation (fun ω => winCount win ω ^ 2) = ∑ i, ∑ j, pairProbability μ win i j := by + simp_rw [winCount, pow_two, Finset.sum_mul, Finset.mul_sum, SmallBias.expectation_sum] + apply Finset.sum_congr rfl + intro i _ + apply Finset.sum_congr rfl + intro j _ + exact expectation_indicator_mul μ win i j + +theorem second_moment_decomposition (μ : FiniteDistribution Ω) (win : Fin d → Ω → Bool) : + μ.expectation (fun ω => winCount win ω ^ 2) = μ.expectation (winCount win) + + ∑ i, ∑ j, if i = j then 0 else pairProbability μ win i j := by + rw [second_moment_eq_sum, first_moment_eq_sum] + calc + _ = ∑ i, ∑ j, + ((if i = j then μ.probability (win i) else 0) + + (if i = j then 0 else pairProbability μ win i j)) := by + apply Finset.sum_congr rfl + intro i _ + apply Finset.sum_congr rfl + intro j _ + by_cases hij : i = j + · subst j + simp + · simp [hij] + _ = _ := by simp [Finset.sum_add_distrib] + +theorem second_moment_le_mean_add (μ : FiniteDistribution Ω) + (win : Fin d → Ω → Bool) (c : ℝ) (hc : 0 ≤ c) + (hpair : ∀ i j, i ≠ j → pairProbability μ win i j ≤ c) : + μ.expectation (fun ω => winCount win ω ^ 2) ≤ + μ.expectation (winCount win) + (d : ℝ) ^ 2 * c := by + rw [second_moment_decomposition] + apply add_le_add (le_refl _) + calc + _ ≤ ∑ _i : Fin d, ∑ _j : Fin d, c := by + apply Finset.sum_le_sum + intro i _ + apply Finset.sum_le_sum + intro j _ + by_cases hij : i = j + · simpa only [ite_eq_left hij] using hc + · simpa only [ite_eq_right hij] using hpair i j hij + _ = (d : ℝ) ^ 2 * c := by + simp [pow_two, mul_assoc] + +theorem exists_level_pair (μ : FiniteDistribution Ω) (win : Fin d → Ω → Bool) + (ε : ℝ) (hε : 0 < ε) + (hmean : ε ≤ (𝔼 i : Fin d, μ.probability (win i))) + (hsize : 4 ≤ (d : ℝ) * ε) : + ∃ i j : Fin d, i < j ∧ + ε ^ 2 / 2 ≤ μ.probability (fun ω => win i ω && win j ω) := by + have hfirst : (d : ℝ) * ε ≤ μ.expectation (winCount win) := by + calc + (d : ℝ) * ε ≤ (d : ℝ) * (𝔼 i : Fin d, μ.probability (win i)) := + mul_le_mul_of_nonneg_left hmean (Nat.cast_nonneg d) + _ = ∑ i, μ.probability (win i) := by + simpa only [Fintype.card_fin] using + Fintype.card_mul_expect (fun i : Fin d => μ.probability (win i)) + _ = μ.expectation (winCount win) := (first_moment_eq_sum μ win).symm + have hfour : 4 ≤ μ.expectation (winCount win) := hsize.trans hfirst + have hjensen := UniqueGamesTheorem.Foundations.Information.weighted_sum_sq_le + μ.weight (winCount win) ⟨μ.nonnegative, μ.normalized⟩ + change μ.expectation (winCount win) ^ 2 ≤ + μ.expectation (fun ω => winCount win ω ^ 2) at hjensen + by_contra hnone + have hsmall : ∀ i j : Fin d, i < j → pairProbability μ win i j < ε ^ 2 / 2 := by + intro i j hij + apply lt_of_not_ge + intro hprob + exact hnone ⟨i, j, hij, hprob⟩ + have hpair : ∀ i j : Fin d, i ≠ j → pairProbability μ win i j ≤ ε ^ 2 / 2 := by + intro i j hij + rcases lt_or_gt_of_ne hij with hlt | hgt + · exact (hsmall i j hlt).le + · rw [pairProbability_comm μ win i j] + exact (hsmall j i hgt).le + have hsecond := second_moment_le_mean_add μ win (ε ^ 2 / 2) + (div_nonneg (sq_nonneg ε) (by norm_num)) hpair + have hscaledNonneg : 0 ≤ (d : ℝ) * ε := mul_nonneg (Nat.cast_nonneg d) hε.le + have hsquare : ((d : ℝ) * ε) ^ 2 ≤ μ.expectation (winCount win) ^ 2 := + (sq_le_sq₀ hscaledNonneg (by linarith)).mpr hfirst + have hproduct : 0 ≤ μ.expectation (winCount win) * (μ.expectation (winCount win) - 4) := + mul_nonneg (by linarith) (by linarith) + nlinarith + +end +end PerfectCompleteness.LevelPairCounting + + + +namespace PerfectCompleteness.LevelPairReserve + +open LevelPairCounting +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators + +noncomputable section + +theorem exists_pair {Ω : Type*} [Fintype Ω] {d : Nat} + (μ : FiniteDistribution Ω) (win : Fin d → Ω → Bool) + (ε : ℝ) (hε : 0 < ε) + (hmean : ε ≤ (𝔼 i : Fin d, μ.probability (win i))) + (hsize : 4 ≤ (d : ℝ) * ε) : + ∃ i j : Fin d, i < j ∧ + 2 * ε ^ 2 / 3 ≤ μ.probability (fun ω => win i ω && win j ω) := by + have hfirst : (d : ℝ) * ε ≤ μ.expectation (winCount win) := by + calc + (d : ℝ) * ε ≤ (d : ℝ) * (𝔼 i : Fin d, μ.probability (win i)) := + mul_le_mul_of_nonneg_left hmean (Nat.cast_nonneg d) + _ = ∑ i, μ.probability (win i) := by + simpa only [Fintype.card_fin] using + Fintype.card_mul_expect (fun i : Fin d => μ.probability (win i)) + _ = μ.expectation (winCount win) := (first_moment_eq_sum μ win).symm + have hfour : 4 ≤ μ.expectation (winCount win) := hsize.trans hfirst + have hjensen := UniqueGamesTheorem.Foundations.Information.weighted_sum_sq_le + μ.weight (winCount win) ⟨μ.nonnegative, μ.normalized⟩ + change μ.expectation (winCount win) ^ 2 ≤ + μ.expectation (fun ω => winCount win ω ^ 2) at hjensen + by_contra hnone + have hsmall : ∀ i j : Fin d, i < j → pairProbability μ win i j < 2 * ε ^ 2 / 3 := by + intro i j hij + apply lt_of_not_ge + intro hprob + exact hnone ⟨i, j, hij, hprob⟩ + have hpair : ∀ i j : Fin d, i ≠ j → pairProbability μ win i j ≤ 2 * ε ^ 2 / 3 := by + intro i j hij + rcases lt_or_gt_of_ne hij with hlt | hgt + · exact (hsmall i j hlt).le + · rw [pairProbability_comm μ win i j] + exact (hsmall j i hgt).le + have hsecond := second_moment_le_mean_add μ win (2 * ε ^ 2 / 3) + (by positivity) hpair + have hscaledNonneg : 0 ≤ (d : ℝ) * ε := mul_nonneg (Nat.cast_nonneg d) hε.le + have hsquare : ((d : ℝ) * ε) ^ 2 ≤ μ.expectation (winCount win) ^ 2 := + (sq_le_sq₀ hscaledNonneg (by linarith)).mpr hfirst + have hproduct : 0 ≤ μ.expectation (winCount win) * (μ.expectation (winCount win) - 4) := + mul_nonneg (by linarith) (by linarith) + nlinarith + +end +end PerfectCompleteness.LevelPairReserve + + + +namespace PerfectCompleteness.SmallBiasSlice + +open scoped BigOperators +open UniqueGamesTheorem.Foundations.Games +open PerfectCompleteness.SmallBias + +noncomputable section + +variable {Ω I : Type*} [Fintype Ω] [Fintype I] [DecidableEq I] + +def bitSign (b : Bool) : ℝ := if b then -1 else 1 + +def maskChar (s v : I → Bool) : ℝ := + ∏ i, if s i then bitSign (v i) else 1 + +omit [DecidableEq I] in +@[simp] theorem maskChar_zero (v : I → Bool) : + maskChar (fun _ => false) v = 1 := by simp [maskChar] + +omit [DecidableEq I] in +@[simp] theorem abs_maskChar (s v : I → Bool) : |maskChar s v| = 1 := by + unfold maskChar + rw [Finset.abs_prod] + apply Finset.prod_eq_one + intro i _ + cases s i <;> cases v i <;> simp [bitSign] + +omit [DecidableEq I] in +theorem maskChar_xor (s t v : I → Bool) : + maskChar (fun i => Bool.xor (s i) (t i)) v = maskChar s v * maskChar t v := by + unfold maskChar + rw [← Finset.prod_mul_distrib] + apply Finset.prod_congr rfl + intro i _ + cases hs : s i <;> cases ht : t i <;> cases hv : v i <;> + simp [hs, ht, bitSign] + +theorem maskChar_kernel (v t : I → Bool) : + (∑ s : I → Bool, maskChar s v * maskChar s t) = + if v = t then (Fintype.card (I → Bool) : ℝ) else 0 := by + classical + calc + _ = ∑ s : I → Bool, ∏ i, + ((if s i then bitSign (v i) else 1) * + (if s i then bitSign (t i) else 1)) := by + simp only [maskChar, Finset.prod_mul_distrib] + _ = ∏ i, ∑ b : Bool, + ((if b then bitSign (v i) else 1) * + (if b then bitSign (t i) else 1)) := + (Fintype.prod_sum (fun (i : I) (b : Bool) => + (if b then bitSign (v i) else 1) * (if b then bitSign (t i) else 1))).symm + _ = ∏ i, (if v i = t i then (2 : ℝ) else 0) := by + apply Finset.prod_congr rfl + intro i _ + cases v i <;> cases t i <;> norm_num [Fintype.sum_bool, bitSign] + _ = _ := by + rw [Fintype.prod_ite_zero] + by_cases h : v = t + · subst t + simp + · have h' : ¬ ∀ i, v i = t i := fun h' => h (funext h') + simp [h, h'] + +theorem expectation_const_mul (μ : FiniteDistribution Ω) (c : ℝ) (g : Ω → ℝ) : + μ.expectation (fun x => c * g x) = c * μ.expectation g := by + unfold FiniteDistribution.expectation + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro x _ + ring + +def sliceNumerator (μ : FiniteDistribution Ω) (A : Ω → I → Bool) + (t : I → Bool) (g : Ω → ℝ) : ℝ := + μ.expectation (fun x => if A x = t then g x else 0) + +def sliceMass (μ : FiniteDistribution Ω) (A : Ω → I → Bool) (t : I → Bool) : ℝ := + sliceNumerator μ A t (fun _ => 1) + +theorem slice_expansion (μ : FiniteDistribution Ω) (A : Ω → I → Bool) + (t : I → Bool) (g : Ω → ℝ) : + (Fintype.card (I → Bool) : ℝ) * sliceNumerator μ A t g = + ∑ s : I → Bool, maskChar s t * + μ.expectation (fun x => g x * maskChar s (A x)) := by + classical + have hpoint : ∀ x, (Fintype.card (I → Bool) : ℝ) * + (if A x = t then g x else 0) = + ∑ s : I → Bool, maskChar s t * (g x * maskChar s (A x)) := by + intro x + calc + _ = g x * (if t = A x then (Fintype.card (I → Bool) : ℝ) else 0) := by + by_cases hx : A x = t + · simp [hx, mul_comm] + · simp [hx, Ne.symm hx] + _ = g x * ∑ s : I → Bool, maskChar s t * maskChar s (A x) := by + rw [maskChar_kernel] + _ = _ := by + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro s _ + ring + calc + _ = μ.expectation (fun x => (Fintype.card (I → Bool) : ℝ) * + (if A x = t then g x else 0)) := + (expectation_const_mul μ _ _).symm + _ = μ.expectation (fun x => ∑ s : I → Bool, + maskChar s t * (g x * maskChar s (A x))) := by simp only [hpoint] + _ = _ := by + rw [expectation_sum] + apply Finset.sum_congr rfl + intro s _ + exact expectation_const_mul μ _ _ + +theorem sliceMass_lower (μ : FiniteDistribution Ω) (A : Ω → I → Bool) + (t : I → Bool) (biasBound : ℝ) (hb : 0 ≤ biasBound) + (hbiased : ∀ s : I → Bool, s ≠ (fun _ => false) → + |μ.expectation (fun x => maskChar s (A x))| ≤ biasBound) : + 1 / (Fintype.card (I → Bool) : ℝ) - biasBound ≤ sliceMass μ A t := by + classical + have hterm : ∀ s : I → Bool, + (if s = (fun _ => false) then (1 : ℝ) else 0) - biasBound ≤ + maskChar s t * μ.expectation (fun x => maskChar s (A x)) := by + intro s + by_cases hs : s = (fun _ => false) + · subst s + simp only [ite_true, maskChar_zero, expectation_const, one_mul] + linarith + · have ha : |maskChar s t * μ.expectation (fun x => maskChar s (A x))| ≤ + biasBound := by + rw [abs_mul, abs_maskChar, one_mul] + exact hbiased s hs + simpa only [ite_eq_right hs, zero_sub] using (abs_le.mp ha).1 + have hsum := Finset.sum_le_sum (fun s (_ : s ∈ (Finset.univ : Finset (I → Bool))) => + hterm s) + have hexp := slice_expansion μ A t (fun _ => 1) + simp only [one_mul] at hexp + have hN : (0 : ℝ) < Fintype.card (I → Bool) := + Nat.cast_pos.mpr Fintype.card_pos + apply le_of_mul_le_mul_left (a := (Fintype.card (I → Bool) : ℝ)) _ hN + calc + _ = 1 - (Fintype.card (I → Bool) : ℝ) * biasBound := by + field_simp [hN.ne'] + _ ≤ ∑ s : I → Bool, maskChar s t * + μ.expectation (fun x => maskChar s (A x)) := by + simpa [Finset.sum_sub_distrib] using hsum + _ = _ := hexp.symm + +theorem slice_coefficient_witness (μ : FiniteDistribution Ω) (A : Ω → I → Bool) + (t : I → Bool) (g : Ω → ℝ) (threshold : ℝ) + (hlarge : threshold ≤ |sliceNumerator μ A t g|) : + ∃ s : I → Bool, + threshold ≤ |μ.expectation (fun x => g x * maskChar s (A x))| := by + classical + have hN : (0 : ℝ) ≤ Fintype.card (I → Bool) := Nat.cast_nonneg _ + have hsum : (∑ _s : I → Bool, threshold) ≤ + ∑ s : I → Bool, |μ.expectation (fun x => g x * maskChar s (A x))| := by + calc + _ = (Fintype.card (I → Bool) : ℝ) * threshold := by simp + _ ≤ (Fintype.card (I → Bool) : ℝ) * |sliceNumerator μ A t g| := + mul_le_mul_of_nonneg_left hlarge hN + _ = |∑ s : I → Bool, maskChar s t * + μ.expectation (fun x => g x * maskChar s (A x))| := by + rw [← slice_expansion, abs_mul, abs_of_nonneg hN] + _ ≤ ∑ s : I → Bool, |maskChar s t * + μ.expectation (fun x => g x * maskChar s (A x))| := + Finset.abs_sum_le_sum_abs _ _ + _ = _ := by simp only [abs_mul, abs_maskChar, one_mul] + obtain ⟨s, _, hs⟩ := Finset.exists_le_of_sum_le Finset.univ_nonempty hsum + exact ⟨s, hs⟩ + + +variable {F : Type*} [AddCommMonoid F] + +def rowCombination (rows : I → F) (s : I → Bool) : F := + ∑ i, if s i then rows i else 0 + +omit [DecidableEq I] in +@[simp] theorem rowCombination_zero (rows : I → F) : + rowCombination rows (fun _ => false) = 0 := by simp [rowCombination] + +omit [Fintype Ω] [DecidableEq I] in +theorem character_rowCombination (χ : F → Ω → ℝ) + (hzero : ∀ x, χ 0 x = 1) + (hadd : ∀ a b x, χ (a + b) x = χ a x * χ b x) + (rows : I → F) (A : Ω → I → Bool) + (hrows : ∀ i x, χ (rows i) x = bitSign (A x i)) (s : I → Bool) (x : Ω) : + χ (rowCombination rows s) x = maskChar s (A x) := by + classical + have hsum : ∀ u : Finset I, + χ (∑ i ∈ u, if s i then rows i else 0) x = + ∏ i ∈ u, χ (if s i then rows i else 0) x := by + intro u + induction u using Finset.induction_on with + | empty => simp [hzero] + | @insert i u hi ih => simp [hi, hadd, ih] + rw [rowCombination, hsum] + unfold maskChar + apply Finset.prod_congr rfl + intro i _ + cases s i <;> simp [hzero, hrows] + +theorem coset_coefficient_witness (μ : FiniteDistribution Ω) + (χ : F → Ω → ℝ) (hzero : ∀ x, χ 0 x = 1) + (hadd : ∀ a b x, χ (a + b) x = χ a x * χ b x) + (rows : I → F) (A : Ω → I → Bool) + (hrows : ∀ i x, χ (rows i) x = bitSign (A x i)) + (t : I → Bool) (g : Ω → ℝ) (base : F) (threshold : ℝ) + (hlarge : threshold ≤ |sliceNumerator μ A t (fun x => g x * χ base x)|) : + ∃ s : I → Bool, threshold ≤ + |μ.expectation (fun x => g x * χ (base + rowCombination rows s) x)| := by + obtain ⟨s, hs⟩ := slice_coefficient_witness μ A t (fun x => g x * χ base x) + threshold hlarge + refine ⟨s, ?_⟩ + simpa only [hadd, character_rowCombination χ hzero hadd rows A hrows, mul_assoc] using hs + +theorem affine_coset_heavy_witness [Fintype F] (μ : FiniteDistribution Ω) + (χ : F → Ω → ℝ) (hzero : ∀ x, χ 0 x = 1) + (hadd : ∀ a b x, χ (a + b) x = χ a x * χ b x) + (rows : I → F) (A : Ω → I → Bool) + (hrows : ∀ i x, χ (rows i) x = bitSign (A x i)) + (hindependent : Function.Injective (rowCombination rows)) + (t : I → Bool) (g : Ω → ℝ) (base : F) + (rho h0 biasBound : ℝ) (hrho : 0 < rho) (hh0 : 0 < h0) + (hsize : h0 ≤ 1 / (Fintype.card (I → Bool) : ℝ)) + (hb : 0 ≤ biasBound) (hbsmall : biasBound ≤ h0 / 2) + (hbias : ∀ a : F, a ≠ 0 → |μ.expectation (χ a)| ≤ biasBound) + (hconditional : rho / 2 ≤ + |sliceNumerator μ A t (fun x => g x * χ base x) / sliceMass μ A t|) : + ∃ s : I → Bool, + base + rowCombination rows s ∈ heavySet μ χ g (rho * h0 / 4) := by + classical + have hmaskbias : ∀ s : I → Bool, s ≠ (fun _ => false) → + |μ.expectation (fun x => maskChar s (A x))| ≤ biasBound := by + intro s hs + have hne : rowCombination rows s ≠ 0 := by + intro hz + apply hs + apply hindependent + simpa using hz + have h := hbias (rowCombination rows s) hne + change |μ.expectation (fun x => χ (rowCombination rows s) x)| ≤ biasBound at h + simpa only [character_rowCombination χ hzero hadd rows A hrows] using h + have hmass : h0 / 2 ≤ sliceMass μ A t := by + have h := sliceMass_lower μ A t biasBound hb hmaskbias + linarith + have hmasspos : 0 < sliceMass μ A t := by linarith + have hcond := hconditional + rw [abs_div, abs_of_pos hmasspos] at hcond + have hnum := (le_div_iff₀ hmasspos).1 hcond + have hthreshold : rho * h0 / 4 ≤ + |sliceNumerator μ A t (fun x => g x * χ base x)| := by + have hmul := mul_le_mul_of_nonneg_left hmass (show 0 ≤ rho / 2 by linarith) + nlinarith + obtain ⟨s, hs⟩ := coset_coefficient_witness μ χ hzero hadd rows A hrows t g base + (rho * h0 / 4) hthreshold + refine ⟨s, Finset.mem_filter.mpr ⟨Finset.mem_univ _, hs⟩⟩ + + +end + +end PerfectCompleteness.SmallBiasSlice + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/DummyEliminationLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/DummyEliminationLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..04b45fa976f3c25eb255dfff07feea2f50911e8a --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/DummyEliminationLemmas.lean @@ -0,0 +1,495 @@ +import Mathlib.Algebra.BigOperators.Group.Finset.Piecewise +import Mathlib.Algebra.BigOperators.Group.Finset.Sigma +import Mathlib.Algebra.BigOperators.Ring.Finset +import Mathlib.Algebra.Order.BigOperators.Expect +import Mathlib.Algebra.Order.BigOperators.Group.Finset +import Mathlib.Algebra.Order.BigOperators.GroupWithZero.Finset +import Mathlib.Data.Fintype.BigOperators +import Mathlib.Data.Fintype.Card +import Mathlib.Data.Fintype.Sigma +import Mathlib.Data.Nat.Cast.Field +import Mathlib.Data.Nat.Factorial.Basic +import Mathlib.Data.Rat.BigOperators +import Mathlib.Data.Rat.Cast.Order +import Mathlib.Basic.Real.Basic +import Mathlib.LinearAlgebra.Basis.VectorSpace +import Mathlib.LinearAlgebra.FiniteDimensional.Basic +import Mathlib.LinearAlgebra.Isomorphisms +import Mathlib.SetTheory.Cardinal.Finite +import Mathlib.Tactic.Abel +import Mathlib.Tactic.FieldSimp +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Ring + +namespace OAI + +section + +namespace PerfectCompleteness.DummyElimination + +noncomputable section + +variable {𝕜 C D V : Type*} [Field 𝕜] + [AddCommGroup C] [Module 𝕜 C] [AddCommGroup D] [Module 𝕜 D] + [AddCommGroup V] [Module 𝕜 V] + +theorem exists_factor (d : C →ₗ[𝕜] D) (f : C →ₗ[𝕜] V) + (h : LinearMap.ker d ≤ LinearMap.ker f) : + ∃ g : D →ₗ[𝕜] V, g.comp d = f := by + let f₀ : LinearMap.range d →ₗ[𝕜] V := + ((LinearMap.ker d).liftQ f h).comp d.quotKerEquivRange.symm.toLinearMap + obtain ⟨g, hg⟩ := f₀.exists_extend + refine ⟨g, ?_⟩ + ext c + have hc := LinearMap.congr_fun hg (⟨d c, LinearMap.mem_range_self d c⟩ : LinearMap.range d) + change g (d c) = (LinearMap.ker d).liftQ f h + (d.quotKerEquivRange.symm ⟨d c, LinearMap.mem_range_self d c⟩) at hc + rw [d.quotKerEquivRange_symm_apply_image] at hc + exact hc + +structure Slice (𝕜 H D K R C : Type*) [Field 𝕜] + [AddCommGroup H] [Module 𝕜 H] [AddCommGroup D] [Module 𝕜 D] + [AddCommGroup K] [Module 𝕜 K] [AddCommGroup R] [Module 𝕜 R] + [AddCommGroup C] [Module 𝕜 C] where + rowMap : K →ₗ[𝕜] R + realTarget : H →ₗ[𝕜] R + dummyTarget : D →ₗ[𝕜] R + realColumns : C →ₗ[𝕜] H + dummyColumns : C →ₗ[𝕜] D + columnTarget : C →ₗ[𝕜] K + +namespace Slice + +variable {H K R : Type*} + [AddCommGroup H] [Module 𝕜 H] [AddCommGroup K] [Module 𝕜 K] + [AddCommGroup R] [Module 𝕜 R] + (S : Slice 𝕜 H D K R C) + +def IsLift (X : H →ₗ[𝕜] K) (Y : D →ₗ[𝕜] K) : Prop := + S.rowMap.comp X = S.realTarget ∧ + S.rowMap.comp Y = S.dummyTarget ∧ + X.comp S.realColumns + Y.comp S.dummyColumns = S.columnTarget + +def Projected (X : H →ₗ[𝕜] K) : Prop := + S.rowMap.comp X = S.realTarget ∧ + ∀ c, S.dummyColumns c = 0 → X (S.realColumns c) = S.columnTarget c + +def Homogeneous (Z : D →ₗ[𝕜] K) : Prop := + S.rowMap.comp Z = 0 ∧ Z.comp S.dummyColumns = 0 + +theorem IsLift.projected {X : H →ₗ[𝕜] K} {Y : D →ₗ[𝕜] K} + (h : S.IsLift X Y) : S.Projected X := by + refine ⟨h.1, ?_⟩ + intro c hc + have he := LinearMap.congr_fun h.2.2 c + simpa [hc] using he + +theorem exists_lift_iff (hne : ∃ X Y, S.IsLift X Y) (X : H →ₗ[𝕜] K) : + (∃ Y, S.IsLift X Y) ↔ S.Projected X := by + constructor + · rintro ⟨Y, hY⟩ + exact IsLift.projected S hY + · intro hX + obtain ⟨X₀, Y₀, h₀⟩ := hne + have hX₀ := IsLift.projected S h₀ + let f : C →ₗ[𝕜] LinearMap.ker S.rowMap := + LinearMap.codRestrict (LinearMap.ker S.rowMap) ((X₀ - X).comp S.realColumns) + (by + intro c + change S.rowMap (X₀ (S.realColumns c) - X (S.realColumns c)) = 0 + rw [map_sub] + have h₁ := LinearMap.congr_fun h₀.1 (S.realColumns c) + have h₂ := LinearMap.congr_fun hX.1 (S.realColumns c) + change S.rowMap (X₀ (S.realColumns c)) = S.realTarget (S.realColumns c) at h₁ + change S.rowMap (X (S.realColumns c)) = S.realTarget (S.realColumns c) at h₂ + rw [h₁, h₂, sub_self]) + have hf : LinearMap.ker S.dummyColumns ≤ LinearMap.ker f := by + intro c hc + apply Subtype.ext + change X₀ (S.realColumns c) - X (S.realColumns c) = 0 + rw [hX₀.2 c hc, hX.2 c hc, sub_self] + obtain ⟨L, hL⟩ := exists_factor S.dummyColumns f hf + let Z : D →ₗ[𝕜] K := (LinearMap.ker S.rowMap).subtype.comp L + have hZrow : S.rowMap.comp Z = 0 := by + ext d + exact (L d).property + have hZcolumn (c : C) : + Z (S.dummyColumns c) = X₀ (S.realColumns c) - X (S.realColumns c) := by + have hc := congrArg Subtype.val (LinearMap.congr_fun hL c) + exact hc + refine ⟨Y₀ + Z, hX.1, ?_, ?_⟩ + · ext d + change S.rowMap (Y₀ d + Z d) = S.dummyTarget d + rw [map_add] + have h₁ := LinearMap.congr_fun h₀.2.1 d + have h₂ := LinearMap.congr_fun hZrow d + change S.rowMap (Y₀ d) = S.dummyTarget d at h₁ + change S.rowMap (Z d) = 0 at h₂ + rw [h₁, h₂, add_zero] + · ext c + change X (S.realColumns c) + (Y₀ (S.dummyColumns c) + Z (S.dummyColumns c)) = + S.columnTarget c + rw [hZcolumn] + have hc := LinearMap.congr_fun h₀.2.2 c + change X₀ (S.realColumns c) + Y₀ (S.dummyColumns c) = S.columnTarget c at hc + calc + _ = X₀ (S.realColumns c) + Y₀ (S.dummyColumns c) := by abel + _ = S.columnTarget c := hc + +def fiberEquivHomogeneous {X : H →ₗ[𝕜] K} {Y₀ : D →ₗ[𝕜] K} + (h₀ : S.IsLift X Y₀) : + {Y : D →ₗ[𝕜] K // S.IsLift X Y} ≃ + {Z : D →ₗ[𝕜] K // S.Homogeneous Z} where + toFun Y := ⟨Y.val - Y₀, by + constructor + · ext d + change S.rowMap (Y.val d - Y₀ d) = 0 + rw [map_sub] + have h₁ := LinearMap.congr_fun Y.property.2.1 d + have h₂ := LinearMap.congr_fun h₀.2.1 d + change S.rowMap (Y.val d) = S.dummyTarget d at h₁ + change S.rowMap (Y₀ d) = S.dummyTarget d at h₂ + rw [h₁, h₂, sub_self] + · ext c + change Y.val (S.dummyColumns c) - Y₀ (S.dummyColumns c) = 0 + have h₁ := LinearMap.congr_fun Y.property.2.2 c + have h₂ := LinearMap.congr_fun h₀.2.2 c + change X (S.realColumns c) + Y.val (S.dummyColumns c) = S.columnTarget c at h₁ + change X (S.realColumns c) + Y₀ (S.dummyColumns c) = S.columnTarget c at h₂ + exact sub_eq_zero.mpr (add_left_cancel (h₁.trans h₂.symm))⟩ + invFun Z := ⟨Y₀ + Z.val, h₀.1, by + ext d + change S.rowMap (Y₀ d + Z.val d) = S.dummyTarget d + rw [map_add] + have h₁ := LinearMap.congr_fun h₀.2.1 d + have h₂ := LinearMap.congr_fun Z.property.1 d + change S.rowMap (Y₀ d) = S.dummyTarget d at h₁ + change S.rowMap (Z.val d) = 0 at h₂ + rw [h₁, h₂, add_zero], by + ext c + change X (S.realColumns c) + (Y₀ (S.dummyColumns c) + Z.val (S.dummyColumns c)) = + S.columnTarget c + have h₁ := LinearMap.congr_fun h₀.2.2 c + have h₂ := LinearMap.congr_fun Z.property.2 c + change Z.val (S.dummyColumns c) = 0 at h₂ + rw [h₂, add_zero] + exact h₁⟩ + left_inv Y := by + apply Subtype.ext + change Y₀ + (Y.val - Y₀) = Y.val + abel + right_inv Z := by + apply Subtype.ext + exact add_sub_cancel_left Y₀ Z.val + +theorem fiber_card_eq {X : H →ₗ[𝕜] K} {Y₀ : D →ₗ[𝕜] K} + (h₀ : S.IsLift X Y₀) : + Nat.card {Y : D →ₗ[𝕜] K // S.IsLift X Y} = + Nat.card {Z : D →ₗ[𝕜] K // S.Homogeneous Z} := + Nat.card_congr (S.fiberEquivHomogeneous h₀) + +theorem projected_fibers_card_eq (hne : ∃ X Y, S.IsLift X Y) + {X X' : H →ₗ[𝕜] K} (hX : S.Projected X) (hX' : S.Projected X') : + Nat.card {Y : D →ₗ[𝕜] K // S.IsLift X Y} = + Nat.card {Y : D →ₗ[𝕜] K // S.IsLift X' Y} := by + obtain ⟨Y, hY⟩ := (S.exists_lift_iff hne X).mpr hX + obtain ⟨Y', hY'⟩ := (S.exists_lift_iff hne X').mpr hX' + exact (S.fiber_card_eq hY).trans (S.fiber_card_eq hY').symm + +theorem projected_iff_basis {ι : Type*} (b : Module.Basis ι 𝕜 (LinearMap.ker S.dummyColumns)) + (X : H →ₗ[𝕜] K) : + S.Projected X ↔ S.rowMap.comp X = S.realTarget ∧ + ∀ i, X (S.realColumns (b i)) = S.columnTarget (b i) := by + constructor + · intro h + exact ⟨h.1, fun i => h.2 (b i) (b i).property⟩ + · rintro ⟨hrow, hcol⟩ + refine ⟨hrow, ?_⟩ + have he : (X.comp S.realColumns).domRestrict (LinearMap.ker S.dummyColumns) = + S.columnTarget.domRestrict (LinearMap.ker S.dummyColumns) := b.ext hcol + intro c hc + exact LinearMap.congr_fun he ⟨c, hc⟩ + +theorem projected_equation_count_le [FiniteDimensional 𝕜 C] : + Module.finrank 𝕜 (LinearMap.ker S.dummyColumns) ≤ Module.finrank 𝕜 C := + Submodule.finrank_le _ + +end Slice +end +end PerfectCompleteness.DummyElimination + +end + +section + +namespace PerfectCompleteness.ExactRationalMultiplicity + +open scoped BigOperators + +noncomputable section + +variable {S : Type*} {E : S → Type*} [Fintype S] [∀ s, Fintype (E s)] + +def commonDenominator (w : ∀ s, E s → ℚ) : Nat := + ∏ x : Sigma E, (w x.1 x.2).den + +def multiplicity (w : ∀ s, E s → ℚ) (s : S) (e : E s) : Nat := + (w s e).num.natAbs * (commonDenominator w / (w s e).den) + +theorem commonDenominator_pos (w : ∀ s, E s → ℚ) : 0 < commonDenominator w := by + apply Finset.prod_pos + intro x _ + exact (w x.1 x.2).den_pos + +theorem denominator_dvd (w : ∀ s, E s → ℚ) (s : S) (e : E s) : + (w s e).den ∣ commonDenominator w := + Finset.dvd_prod_of_mem (fun x : Sigma E => (w x.1 x.2).den) + (Finset.mem_univ (⟨s, e⟩ : Sigma E)) + +@[simp] theorem commonDenominator_of_isEmpty [IsEmpty S] (w : ∀ s, E s → ℚ) : + commonDenominator w = 1 := by + classical + simp [commonDenominator] + +theorem multiplicity_cast (w : ∀ s, E s → ℚ) (positive : ∀ s e, 0 < w s e) + (s : S) (e : E s) : + (multiplicity w s e : ℚ) = (commonDenominator w : ℚ) * w s e := by + have habs : ((w s e).num.natAbs : ℚ) = ((w s e).num : ℚ) := by + simpa only [Int.cast_natCast] using + congrArg (fun z : ℤ => (z : ℚ)) + (Int.natAbs_of_nonneg (Rat.num_pos.mpr (positive s e)).le) + rw [multiplicity, Nat.cast_mul, Nat.cast_div_charZero (denominator_dvd w s e), habs] + calc + ((w s e).num : ℚ) * ((commonDenominator w : ℚ) / (w s e).den) = + (commonDenominator w : ℚ) * (((w s e).num : ℚ) / (w s e).den) := by ring + _ = (commonDenominator w : ℚ) * w s e := by rw [Rat.num_div_den] + +theorem multiplicity_pos (w : ∀ s, E s → ℚ) (positive : ∀ s e, 0 < w s e) + (s : S) (e : E s) : 0 < multiplicity w s e := by + have h : (0 : ℚ) < (multiplicity w s e : ℚ) := by + rw [multiplicity_cast w positive] + exact mul_pos (Nat.cast_pos.mpr (commonDenominator_pos w)) (positive s e) + exact_mod_cast h + +theorem multiplicity_sum (w : ∀ s, E s → ℚ) (positive : ∀ s e, 0 < w s e) + (normalized : ∀ s, ∑ e, w s e = 1) (s : S) : + ∑ e, multiplicity w s e = commonDenominator w := by + have h : ((∑ e, multiplicity w s e : Nat) : ℚ) = (commonDenominator w : ℚ) := by + rw [Nat.cast_sum] + simp_rw [multiplicity_cast w positive] + rw [← Finset.mul_sum, normalized s, mul_one] + exact_mod_cast h + +theorem multiplicity_div (w : ∀ s, E s → ℚ) (positive : ∀ s e, 0 < w s e) + (s : S) (e : E s) : + (multiplicity w s e : ℚ) / (commonDenominator w : ℚ) = w s e := by + have hD : (commonDenominator w : ℚ) ≠ 0 := + Nat.cast_ne_zero.mpr (Nat.ne_of_gt (commonDenominator_pos w)) + apply (div_eq_iff hD).mpr + rw [multiplicity_cast w positive, mul_comm] + +theorem multiplicity_le_denominator (w : ∀ s, E s → ℚ) + (positive : ∀ s e, 0 < w s e) (normalized : ∀ s, ∑ e, w s e = 1) + (s : S) (e : E s) : multiplicity w s e ≤ commonDenominator w := by + calc + multiplicity w s e ≤ ∑ e', multiplicity w s e' := + Finset.single_le_sum (fun _ _ => Nat.zero_le _) (Finset.mem_univ e) + _ = commonDenominator w := multiplicity_sum w positive normalized s + +structure Uniformization (w : ∀ s, E s → ℚ) where + denominator : Nat + denominator_pos : 0 < denominator + count : ∀ s, E s → Nat + count_pos : ∀ s e, 0 < count s e + count_total : ∀ s, ∑ e, count s e = denominator + fraction : ∀ s e, (count s e : ℚ) / (denominator : ℚ) = w s e + +def build (w : ∀ s, E s → ℚ) (positive : ∀ s e, 0 < w s e) + (normalized : ∀ s, ∑ e, w s e = 1) : Uniformization w where + denominator := commonDenominator w + denominator_pos := commonDenominator_pos w + count := multiplicity w + count_pos := multiplicity_pos w positive + count_total := multiplicity_sum w positive normalized + fraction := multiplicity_div w positive + +@[simp] theorem build_denominator (w : ∀ s, E s → ℚ) (positive : ∀ s e, 0 < w s e) + (normalized : ∀ s, ∑ e, w s e = 1) : + (build w positive normalized).denominator = commonDenominator w := rfl + +@[simp] theorem build_count (w : ∀ s, E s → ℚ) (positive : ∀ s e, 0 < w s e) + (normalized : ∀ s, ∑ e, w s e = 1) (s : S) (e : E s) : + (build w positive normalized).count s e = multiplicity w s e := rfl + +end + +end PerfectCompleteness.ExactRationalMultiplicity + +end + +section + +namespace PerfectCompleteness.ExactSeedMultiplicity + +open scoped BigOperators + +def factor (M : Nat) : Nat := M.factorial + +def denominator (D M : Nat) : Nat := D * factor M + +def perSeed (M count copies : Nat) : Nat := copies * (factor M / count) + +theorem factor_positive (M : Nat) : 0 < factor M := Nat.factorial_pos M + +theorem denominator_positive {D : Nat} (hD : 0 < D) (M : Nat) : + 0 < denominator D M := Nat.mul_pos hD (factor_positive M) + +theorem count_dvd_factor {M count : Nat} (positive : 0 < count) (bounded : count ≤ M) : + count ∣ factor M := Nat.dvd_factorial positive bounded + +theorem seed_total {M count : Nat} (positive : 0 < count) (bounded : count ≤ M) + (copies : Nat) : count * perSeed M count copies = copies * factor M := by + unfold perSeed + calc + count * (copies * (factor M / count)) = copies * (count * (factor M / count)) := by ring + _ = copies * factor M := by rw [Nat.mul_div_cancel' (count_dvd_factor positive bounded)] + +theorem perSeed_positive {M count copies : Nat} + (positive : 0 < count) (bounded : count ≤ M) (hcopies : 0 < copies) : + 0 < perSeed M count copies := + Nat.mul_pos hcopies (Nat.div_pos + (Nat.le_of_dvd (factor_positive M) (count_dvd_factor positive bounded)) positive) + +theorem perSeed_cast {M count : Nat} (positive : 0 < count) (bounded : count ≤ M) + (copies : Nat) : + (perSeed M count copies : ℚ) = (copies : ℚ) * factor M / count := by + have hn : (count : ℚ) ≠ 0 := Nat.cast_ne_zero.mpr (Nat.ne_of_gt positive) + apply (eq_div_iff hn).mpr + have h := seed_total positive bounded copies + have hc : (count : ℚ) * (perSeed M count copies : ℚ) = + (copies : ℚ) * (factor M : ℚ) := by exact_mod_cast h + simpa only [mul_comm] using hc + +theorem perSeed_ratio {D M count : Nat} (hD : 0 < D) + (positive : 0 < count) (bounded : count ≤ M) (copies : Nat) : + (perSeed M count copies : ℚ) / denominator D M = ((copies : ℚ) / D) / count := by + rw [perSeed_cast positive bounded copies] + have hDc : (D : ℚ) ≠ 0 := Nat.cast_ne_zero.mpr (Nat.ne_of_gt hD) + have hnc : (count : ℚ) ≠ 0 := Nat.cast_ne_zero.mpr (Nat.ne_of_gt positive) + have hfactor : (factor M : ℚ) ≠ 0 := + Nat.cast_ne_zero.mpr (Nat.ne_of_gt (factor_positive M)) + simp only [denominator, Nat.cast_mul] + field_simp [hDc, hnc, hfactor] + +abbrev Seeded {E : Type*} (count : E → Nat) := Σ e : E, Fin (count e) + +section Family + +variable {E : Type*} [Fintype E] {D M : Nat} + (copies count : E → Nat) (positive : ∀ e, 0 < count e) (bounded : ∀ e, count e ≤ M) + +def multiplicity (outcome : Seeded count) : Nat := + perSeed M (count outcome.1) (copies outcome.1) + +include positive bounded + +omit [Fintype E] in +theorem multiplicity_positive (hcopies : ∀ e, 0 < copies e) (outcome : Seeded count) : + 0 < multiplicity (M := M) copies count outcome := + perSeed_positive (positive outcome.1) (bounded outcome.1) (hcopies outcome.1) + +theorem sum_multiplicity (total : ∑ e, copies e = D) : + (∑ outcome : Seeded count, multiplicity (M := M) copies count outcome) = denominator D M := by + rw [Fintype.sum_sigma] + simp only [multiplicity, Finset.sum_const, Finset.card_univ, Fintype.card_fin, nsmul_eq_mul] + calc + _ = ∑ e, copies e * factor M := by + apply Finset.sum_congr rfl + intro e _ + exact seed_total (positive e) (bounded e) (copies e) + _ = denominator D M := by + rw [← Finset.sum_mul, total] + rfl + +omit [Fintype E] in +theorem multiplicity_ratio (hD : 0 < D) (outcome : Seeded count) : + (multiplicity (M := M) copies count outcome : ℚ) / denominator D M = + ((copies outcome.1 : ℚ) / D) / count outcome.1 := + perSeed_ratio hD (positive outcome.1) (bounded outcome.1) (copies outcome.1) + +omit [Fintype E] in +theorem multiplicity_ratio_of_base (hD : 0 < D) (weights : E → ℚ) + (represented : ∀ e, (copies e : ℚ) / D = weights e) (outcome : Seeded count) : + (multiplicity (M := M) copies count outcome : ℚ) / denominator D M = + weights outcome.1 / count outcome.1 := by + rw [multiplicity_ratio copies count positive bounded hD, represented] + +end Family +end PerfectCompleteness.ExactSeedMultiplicity + +end + +section + +namespace PerfectCompleteness.NonzeroAverage + +open scoped BigOperators + +variable {A : Type*} [Fintype A] [DecidableEq A] + +theorem card_subtype_ne_real (a : A) : + (Fintype.card {x : A // x ≠ a} : ℝ) = (Fintype.card A : ℝ) - 1 := by + have h : (Fintype.card A : ℝ) = + 1 + (Fintype.card {x : A // x ≠ a} : ℝ) := by + simpa using Fintype.sum_eq_add_sum_subtype_ne (fun _ : A => (1 : ℝ)) a + linarith + +theorem card_mul_expect_eq (g : A → ℝ) (a : A) : + (Fintype.card A : ℝ) * (𝔼 x, g x) = + g a + (Fintype.card {x : A // x ≠ a} : ℝ) * + (𝔼 x : {x : A // x ≠ a}, g x.1) := by + rw [Fintype.card_mul_expect, Fintype.card_mul_expect] + exact Fintype.sum_eq_add_sum_subtype_ne g a + +theorem card_mul_expect_eq_sub_one (g : A → ℝ) (a : A) : + (Fintype.card A : ℝ) * (𝔼 x, g x) = + g a + ((Fintype.card A : ℝ) - 1) * + (𝔼 x : {x : A // x ≠ a}, g x.1) := by + rw [← card_subtype_ne_real a] + exact card_mul_expect_eq g a + +theorem expect_subtype_ne_le_expect_of_expect_le (g : A → ℝ) (a : A) + (h : (𝔼 x : {x : A // x ≠ a}, g x.1) ≤ g a) : + (𝔼 x : {x : A // x ≠ a}, g x.1) ≤ (𝔼 x, g x) := by + let : Nonempty A := ⟨a⟩ + have hcard : 0 < (Fintype.card A : ℝ) := by + exact_mod_cast Fintype.card_pos + apply (mul_le_mul_iff_right₀ hcard).mp + have hid := card_mul_expect_eq_sub_one g a + nlinarith + +theorem expect_subtype_ne_le_expect [Nontrivial A] (g : A → ℝ) (a : A) + (h : ∀ x, g x ≤ g a) : + (𝔼 x : {x : A // x ≠ a}, g x.1) ≤ (𝔼 x, g x) := by + obtain ⟨b, hb⟩ := exists_ne a + let : Nonempty {x : A // x ≠ a} := ⟨⟨b, hb⟩⟩ + apply expect_subtype_ne_le_expect_of_expect_le g a + exact Finset.expect_le Finset.univ_nonempty (fun x _ => h x.1) + +theorem zero_card_mul_expect [Zero A] (g : A → ℝ) : + (Fintype.card A : ℝ) * (𝔼 x, g x) = + g 0 + ((Fintype.card A : ℝ) - 1) * + (𝔼 x : {x : A // x ≠ (0 : A)}, g x.1) := + card_mul_expect_eq_sub_one g 0 + +theorem nonzero_expect_le_expect [Zero A] [Nontrivial A] (g : A → ℝ) + (h : ∀ x, g x ≤ g 0) : + (𝔼 x : {x : A // x ≠ (0 : A)}, g x.1) ≤ (𝔼 x, g x) := + expect_subtype_ne_le_expect g 0 h + +end PerfectCompleteness.NonzeroAverage + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/DummyEliminationWeighted.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/DummyEliminationWeighted.lean new file mode 100644 index 0000000000000000000000000000000000000000..d85bccdd1c9d62d71ba903c186c109391f3d87d3 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/DummyEliminationWeighted.lean @@ -0,0 +1,164 @@ +import Mathlib.Tactic.Positivity +import OAI.Computability.PerfectCompleteness.Sampling.CommonProductVariationLemmas +import OAI.Computability.UniqueGames.Foundations.Conditioning +import OAI.Computability.UniqueGames.Foundations.SamplingLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.DummyElimination.Slice + +noncomputable section + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games + +private theorem uniform_probability_card {Ω : Type*} [Fintype Ω] [Nonempty Ω] + (P : Ω → Prop) : + (FiniteDistribution.uniform Ω).probability (fun x => decide (P x)) = + (Fintype.card {x // P x} : ℝ) / Fintype.card Ω := by + calc + _ = (FiniteDistribution.uniform Ω).expectation (fun x => if P x then (1 : ℝ) else 0) := by + unfold FiniteDistribution.probability FiniteDistribution.expectation + apply Finset.sum_congr rfl + intro x _ + by_cases hx : P x <;> simp [hx] + _ = (∑ x, if P x then (1 : ℝ) else 0) / Fintype.card Ω := + FiniteDistribution.expectation_uniform _ + _ = _ := by simp only [Fintype.card_subtype, Finset.sum_boole] + +private theorem expectation_condition {Ω : Type*} [Fintype Ω] + (μ : FiniteDistribution Ω) (event : Ω → Bool) (hp : 0 < μ.probability event) + (g : Ω → ℝ) : + (μ.condition event hp).expectation g = + μ.expectation (fun x => if event x then g x else 0) / μ.probability event := by + simp only [FiniteDistribution.expectation, FiniteDistribution.condition, + div_eq_mul_inv, Finset.sum_mul] + apply Finset.sum_congr rfl + intro x _ + by_cases hx : event x = true <;> simp [hx, mul_left_comm, mul_comm] + +variable {𝕜 H D K R C : Type*} [Field 𝕜] + [AddCommGroup H] [Module 𝕜 H] [AddCommGroup D] [Module 𝕜 D] + [AddCommGroup K] [Module 𝕜 K] [AddCommGroup R] [Module 𝕜 R] + [AddCommGroup C] [Module 𝕜 C] + [Fintype (H →ₗ[𝕜] K)] [Fintype (D →ₗ[𝕜] K)] + (S : DummyElimination.Slice 𝕜 H D K R C) + +def dummyLikelihood (X : H →ₗ[𝕜] K) : ℝ := + (FiniteDistribution.uniform (D →ₗ[𝕜] K)).probability (fun Y => decide (S.IsLift X Y)) + +def dummyConstant : ℝ := + (Fintype.card S.HomogeneousMaps : ℝ) / Fintype.card (D →ₗ[𝕜] K) + +omit [Fintype (H →ₗ[𝕜] K)] in +theorem dummyConstant_pos : 0 < S.dummyConstant := by + let : Nonempty S.HomogeneousMaps := ⟨⟨0, by simp [Homogeneous]⟩⟩ + exact div_pos (Nat.cast_pos.mpr Fintype.card_pos) (Nat.cast_pos.mpr Fintype.card_pos) + +omit [Fintype (H →ₗ[𝕜] K)] in +theorem dummyLikelihood_eq_card (X : H →ₗ[𝕜] K) : + S.dummyLikelihood X = + (Fintype.card {Y : D →ₗ[𝕜] K // S.IsLift X Y} : ℝ) / + Fintype.card (D →ₗ[𝕜] K) := + uniform_probability_card (S.IsLift X) + +omit [Fintype (H →ₗ[𝕜] K)] in +theorem dummyLikelihood_eq (hne : ∃ X Y, S.IsLift X Y) (X : H →ₗ[𝕜] K) : + S.dummyLikelihood X = if S.Projected X then S.dummyConstant else 0 := by + by_cases hX : S.Projected X + · obtain ⟨Y, hY⟩ := (S.exists_lift_iff hne X).mpr hX + rw [ite_eq_left hX, dummyLikelihood_eq_card, + Fintype.card_congr (S.fiberEquivHomogeneous hY)]; rfl + · have hnone : ∀ Y, ¬ S.IsLift X Y := fun Y hY => hX (IsLift.projected S hY) + rw [ite_eq_right hX] + simp [dummyLikelihood, FiniteDistribution.probability, hnone] + +omit [Fintype (H →ₗ[𝕜] K)] in +theorem dummy_restricted_expectation (hne : ∃ X Y, S.IsLift X Y) + (X : H →ₗ[𝕜] K) (a : ℝ) : + (FiniteDistribution.uniform (D →ₗ[𝕜] K)).expectation + (fun Y => if S.IsLift X Y then a else 0) = + S.dummyConstant * (if S.Projected X then a else 0) := by + calc + _ = a * S.dummyLikelihood X := by + unfold FiniteDistribution.expectation dummyLikelihood FiniteDistribution.probability + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro Y _ + by_cases hY : S.IsLift X Y <;> simp [hY, mul_comm] + _ = S.dummyConstant * (if S.Projected X then a else 0) := by + rw [dummyLikelihood_eq S hne X] + by_cases hX : S.Projected X <;> simp [hX, mul_comm] + +theorem weighted_restricted_expectation (hne : ∃ X Y, S.IsLift X Y) + (μ : FiniteDistribution (H →ₗ[𝕜] K)) (g : (H →ₗ[𝕜] K) → ℝ) : + (μ.product (FiniteDistribution.uniform (D →ₗ[𝕜] K))).expectation + (fun p => if S.IsLift p.1 p.2 then g p.1 else 0) = + S.dummyConstant * μ.expectation (fun X => if S.Projected X then g X else 0) := by + rw [FiniteDistribution.expectation_product] + calc + _ = μ.expectation + (fun X => S.dummyConstant * (if S.Projected X then g X else 0)) := + μ.expectation_congr (fun X => S.dummy_restricted_expectation hne X (g X)) + _ = _ := by + unfold FiniteDistribution.expectation + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro X _ + exact mul_left_comm _ _ _ + +theorem padded_probability (hne : ∃ X Y, S.IsLift X Y) + (μ : FiniteDistribution (H →ₗ[𝕜] K)) : + (μ.product (FiniteDistribution.uniform (D →ₗ[𝕜] K))).probability + (fun p => decide (S.IsLift p.1 p.2)) = + S.dummyConstant * μ.probability (fun X => decide (S.Projected X)) := by + simpa [FiniteDistribution.expectation, FiniteDistribution.probability, mul_ite] using + S.weighted_restricted_expectation hne μ (fun _ => (1 : ℝ)) + +theorem padded_probability_pos_iff (hne : ∃ X Y, S.IsLift X Y) + (μ : FiniteDistribution (H →ₗ[𝕜] K)) : + 0 < (μ.product (FiniteDistribution.uniform (D →ₗ[𝕜] K))).probability + (fun p => decide (S.IsLift p.1 p.2)) ↔ + 0 < μ.probability (fun X => decide (S.Projected X)) := by + rw [padded_probability S hne μ] + exact mul_pos_iff_of_pos_left S.dummyConstant_pos + +theorem padded_probability_pos (hne : ∃ X Y, S.IsLift X Y) + (μ : FiniteDistribution (H →ₗ[𝕜] K)) + (hpos : 0 < μ.probability (fun X => decide (S.Projected X))) : + 0 < (μ.product (FiniteDistribution.uniform (D →ₗ[𝕜] K))).probability + (fun p => decide (S.IsLift p.1 p.2)) := + (S.padded_probability_pos_iff hne μ).mpr hpos + +theorem conditioned_expectation_projected (hne : ∃ X Y, S.IsLift X Y) + (μ : FiniteDistribution (H →ₗ[𝕜] K)) + (hpos : 0 < μ.probability (fun X => decide (S.Projected X))) + (g : (H →ₗ[𝕜] K) → ℝ) : + ((μ.product (FiniteDistribution.uniform (D →ₗ[𝕜] K))).condition + (fun p => decide (S.IsLift p.1 p.2)) (S.padded_probability_pos hne μ hpos)).expectation + (fun p => g p.1) = + (μ.condition (fun X => decide (S.Projected X)) hpos).expectation g := by + rw [expectation_condition, expectation_condition] + simp only [decide_eq_true_eq] + rw [weighted_restricted_expectation S hne μ g, padded_probability S hne μ] + exact mul_div_mul_left _ _ (ne_of_gt S.dummyConstant_pos) + +theorem conditioned_probability_projected (hne : ∃ X Y, S.IsLift X Y) + (μ : FiniteDistribution (H →ₗ[𝕜] K)) + (hpos : 0 < μ.probability (fun X => decide (S.Projected X))) + (event : (H →ₗ[𝕜] K) → Bool) : + ((μ.product (FiniteDistribution.uniform (D →ₗ[𝕜] K))).condition + (fun p => decide (S.IsLift p.1 p.2)) (S.padded_probability_pos hne μ hpos)).probability + (fun p => event p.1) = + (μ.condition (fun X => decide (S.Projected X)) hpos).probability event := by + simpa [FiniteDistribution.expectation, FiniteDistribution.probability, mul_ite] using + S.conditioned_expectation_projected hne μ hpos (fun X => if event X then (1 : ℝ) else 0) + +end +end PerfectCompleteness.DummyElimination.Slice + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/ExactConditionalOutput.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/ExactConditionalOutput.lean new file mode 100644 index 0000000000000000000000000000000000000000..bee230438379ced60114d0704083c38b34a1b3df --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/ExactConditionalOutput.lean @@ -0,0 +1,218 @@ +import OAI.Computability.PerfectCompleteness.Foundations.DummyEliminationLemmas +import OAI.Computability.PerfectCompleteness.Reduction.TargetGameLemmas + +namespace OAI + + +namespace PerfectCompleteness.ExactConditionalOutput + +open scoped BigOperators Classical + +noncomputable section + +variable {S X : Type*} {E : S → Type*} [∀ s, Fintype (E s)] + (count : ∀ s, E s → Nat) + +def enumeration (s : S) : E s ≃ Fin (Fintype.card (E s)) := Fintype.equivFin _ + +def copies (s : S) : List (E s) := + (List.ofFn fun i : Fin (Fintype.card (E s)) => + List.replicate (count s ((enumeration s).symm i)) ((enumeration s).symm i)).flatten + +theorem copies_length (s : S) : (copies count s).length = ∑ e, count s e := by + simp only [copies, List.length_flatten, List.map_ofFn, Function.comp_def, + List.length_replicate, List.sum_ofFn] + exact (enumeration s).symm.sum_comp (fun e : E s => count s e) + +theorem copies_filter_length (s : S) (keep : E s → Bool) : + ((copies count s).filter keep).length = ∑ e, if keep e then count s e else 0 := by + simp only [copies, List.filter_flatten, List.length_flatten, List.map_ofFn, + List.sum_ofFn] + calc + _ = ∑ i : Fin (Fintype.card (E s)), + if keep ((enumeration s).symm i) then count s ((enumeration s).symm i) else 0 := by + apply Finset.sum_congr rfl + intro i _ + cases h : keep ((enumeration s).symm i) <;> simp [h] + _ = _ := (enumeration s).symm.sum_comp + (fun e : E s => if keep e then count s e else 0) + +section Lists + +variable {α : Type*} (shape : X → S) (entries : (x : X) → E (shape x) → α) + +def localOutput (x : X) : List α := (copies count (shape x)).map (entries x) + +def output (xs : List X) : List α := xs.flatMap (localOutput count shape entries) + +theorem localOutput_length (D : Nat) (htotal : ∀ s, ∑ e, count s e = D) (x : X) : + (localOutput count shape entries x).length = D := by + rw [localOutput, List.length_map, copies_length, htotal] + +theorem output_length (D : Nat) (htotal : ∀ s, ∑ e, count s e = D) (xs : List X) : + (output count shape entries xs).length = D * xs.length := by + induction xs with + | nil => rfl + | cons x xs ih => + change (localOutput count shape entries x ++ output count shape entries xs).length = _ + rw [List.length_append, localOutput_length count shape entries D htotal, ih, + List.length_cons, Nat.mul_add, Nat.mul_one] + omega + +theorem output_nonempty (D : Nat) (hD : 0 < D) (htotal : ∀ s, ∑ e, count s e = D) + (xs : List X) (hxs : xs ≠ []) : output count shape entries xs ≠ [] := by + intro hempty + have hlength := output_length count shape entries D htotal xs + have hxpos : 0 < xs.length := by + cases xs with + | nil => exact False.elim (hxs rfl) + | cons x xs => simp + rw [hempty, List.length_nil] at hlength + exact (Nat.ne_of_gt (Nat.mul_pos hD hxpos)) hlength.symm + +def localCount (accepts : α → Bool) (x : X) : Nat := + ∑ e, if accepts (entries x e) then count (shape x) e else 0 + +theorem localOutput_filter_length (accepts : α → Bool) (x : X) : + ((localOutput count shape entries x).filter accepts).length = + localCount count shape entries accepts x := by + simpa only [localOutput, localCount, List.filter_map, List.length_map, Function.comp_def] + using copies_filter_length count (shape x) (fun e => accepts (entries x e)) + +theorem output_filter_length (xs : List X) (accepts : α → Bool) : + ((output count shape entries xs).filter accepts).length = + (xs.map (localCount count shape entries accepts)).sum := by + induction xs with + | nil => rfl + | cons x xs ih => + change ((localOutput count shape entries x ++ output count shape entries xs).filter + accepts).length = _ + rw [List.filter_append, List.length_append, localOutput_filter_length, ih] + rfl + +def conditionalRate (D : Nat) (accepts : α → Bool) (x : X) : ℝ := + ∑ e, if accepts (entries x e) then (count (shape x) e : ℝ) / D else 0 + +def average (D : Nat) (xs : List X) (accepts : α → Bool) : ℝ := + (xs.map (conditionalRate count shape entries D accepts)).sum / xs.length + +theorem localCount_div (D : Nat) (accepts : α → Bool) (x : X) : + (localCount count shape entries accepts x : ℝ) / D = + conditionalRate count shape entries D accepts x := by + rw [localCount, Nat.cast_sum, Finset.sum_div] + apply Finset.sum_congr rfl + intro e _ + cases accepts (entries x e) <;> simp + +theorem conditionalRate_sum (D : Nat) (xs : List X) (accepts : α → Bool) : + (xs.map (conditionalRate count shape entries D accepts)).sum = + ((xs.map (localCount count shape entries accepts)).sum : ℝ) / D := by + induction xs with + | nil => simp + | cons x xs ih => + simp only [List.map_cons, List.sum_cons, Nat.cast_add] + rw [← localCount_div, ih, add_div] + +theorem rate_eq (D : Nat) (htotal : ∀ s, ∑ e, count s e = D) + (xs : List X) (accepts : α → Bool) : + (((output count shape entries xs).filter accepts).length : ℝ) / + (output count shape entries xs).length = + average count shape entries D xs accepts := by + rw [output_filter_length, output_length count shape entries D htotal, + Nat.cast_mul, average, conditionalRate_sum] + exact div_mul_eq_div_div _ _ _ + +theorem output_support (xs : List X) (entry : α) + (hentry : entry ∈ output count shape entries xs) : + ∃ x ∈ xs, ∃ e : E (shape x), entries x e = entry := by + obtain ⟨x, hx, hlocal⟩ := List.mem_flatMap.mp hentry + obtain ⟨e, _, he⟩ := List.mem_map.mp hlocal + exact ⟨x, hx, e, he⟩ + +end Lists + +section Target + +variable {l r q : Nat} (shape : X → S) + (entries : (x : X) → E (shape x) → Edge l r q) + +def construct (D : Nat) (hD : 0 < D) (htotal : ∀ s, ∑ e, count s e = D) + (xs : List X) (hxs : xs ≠ []) : Instance q where + leftVertices := l + rightVertices := r + edges := output count shape entries xs + nonempty := output_nonempty count shape entries D hD htotal xs hxs + +theorem construct_length (D : Nat) (hD : 0 < D) (htotal : ∀ s, ∑ e, count s e = D) + (xs : List X) (hxs : xs ≠ []) : + (construct count shape entries D hD htotal xs hxs).edges.length = D * xs.length := + output_length count shape entries D htotal xs + +theorem count_eq (D : Nat) (hD : 0 < D) (htotal : ∀ s, ∑ e, count s e = D) + (xs : List X) (hxs : xs ≠ []) + (a : Fin l → Fin (2 * q)) (b : Fin r → Fin q) : + countSatisfied a b (construct count shape entries D hD htotal xs hxs).edges = + (xs.map (fun x => ∑ e, if (entries x e).satisfied a b then count (shape x) e else 0)).sum := by + change countSatisfied a b (output count shape entries xs) = _ + rw [RoundedTarget.countSatisfied_eq_filter] + exact output_filter_length count shape entries xs (fun e => e.satisfied a b) + +theorem construct_rate_eq (D : Nat) (hD : 0 < D) (htotal : ∀ s, ∑ e, count s e = D) + (xs : List X) (hxs : xs ≠ []) + (a : Fin l → Fin (2 * q)) (b : Fin r → Fin q) : + (countSatisfied a b (construct count shape entries D hD htotal xs hxs).edges : ℝ) / + (construct count shape entries D hD htotal xs hxs).edges.length = + average count shape entries D xs (fun e => e.satisfied a b) := by + change (countSatisfied a b (output count shape entries xs) : ℝ) / + (output count shape entries xs).length = _ + rw [RoundedTarget.countSatisfied_eq_filter] + exact rate_eq count shape entries D htotal xs (fun e => e.satisfied a b) + +theorem value_le (D : Nat) (hD : 0 < D) (htotal : ∀ s, ∑ e, count s e = D) + (xs : List X) (hxs : xs ≠ []) (hq : 0 < q) (bound : ℝ) + (hsound : ∀ a : Fin l → Fin (2 * q), ∀ b : Fin r → Fin q, + average count shape entries D xs (fun e => e.satisfied a b) ≤ bound) : + (construct count shape entries D hD htotal xs hxs).value ≤ bound := by + obtain ⟨s, hs⟩ := (construct count shape entries D hD htotal xs hxs).maxSatisfied_attained hq + unfold Instance.value + rw [← hs] + exact (construct_rate_eq count shape entries D hD htotal xs hxs s.1 s.2).le.trans + (hsound s.1 s.2) + +theorem perfectlyComplete (D : Nat) (hD : 0 < D) (htotal : ∀ s, ∑ e, count s e = D) + (xs : List X) (hxs : xs ≠ []) + (hcomplete : ∃ s : RoundedTarget.EndpointLabeling l r q, + ∀ x ∈ xs, ∀ e : E (shape x), (entries x e).satisfied s.1 s.2 = true) : + PerfectlyComplete (construct count shape entries D hD htotal xs hxs) := by + obtain ⟨s, hs⟩ := hcomplete + refine ⟨s, ?_⟩ + intro edge hedge + obtain ⟨x, hx, e, he⟩ := output_support count shape entries xs edge hedge + rw [← he] + exact hs x hx e + +theorem complete_value_eq_one (D : Nat) (hD : 0 < D) (htotal : ∀ s, ∑ e, count s e = D) + (xs : List X) (hxs : xs ≠ []) (hq : 0 < q) + (hcomplete : ∃ s : RoundedTarget.EndpointLabeling l r q, + ∀ x ∈ xs, ∀ e : E (shape x), (entries x e).satisfied s.1 s.2 = true) : + (construct count shape entries D hD htotal xs hxs).value = 1 := + ((construct count shape entries D hD htotal xs hxs).perfectlyComplete_iff_value_eq_one hq).1 + (perfectlyComplete count shape entries D hD htotal xs hxs hcomplete) + +end Target + +theorem conditionalRate_uniformization {α : Type*} (w : ∀ s, E s → ℚ) + (U : ExactRationalMultiplicity.Uniformization w) (shape : X → S) + (entries : (x : X) → E (shape x) → α) (accepts : α → Bool) (x : X) : + conditionalRate U.count shape entries U.denominator accepts x = + ∑ e, if accepts (entries x e) then (w (shape x) e : ℝ) else 0 := by + apply Finset.sum_congr rfl + intro e _ + have h := congrArg (fun z : ℚ => (z : ℝ)) (U.fraction (shape x) e) + simp only [Rat.cast_div, Rat.cast_natCast] at h + cases accepts (entries x e) <;> simp [h] + +end +end PerfectCompleteness.ExactConditionalOutput + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/ExtraCutCall.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/ExtraCutCall.lean new file mode 100644 index 0000000000000000000000000000000000000000..f5cb8e2e7509456615e9383f8d0adc754144ce15 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/ExtraCutCall.lean @@ -0,0 +1,250 @@ +import Mathlib.Algebra.BigOperators.Fin +import OAI.Computability.PerfectCompleteness.Sampling.NumberedUniformCut + +namespace OAI + +section + +namespace PerfectCompleteness.ExtraCutCall + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCutTape OriginalWholeCut OriginalWholeCutLaw +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +noncomputable section + +def splitLast (calls : Nat) (A : Type*) : + (Fin (calls + 1) → A) ≃ (Fin calls → A) × A where + toFun x := (fun i => x i.castSucc, x (Fin.last calls)) + invFun z := Fin.lastCases z.2 z.1 + left_inv x := by + funext i + refine Fin.lastCases ?_ (fun j => ?_) i + · simp only [Fin.lastCases_last] + · simp only [Fin.lastCases_castSucc] + right_inv z := by + apply Prod.ext + · funext i + simp only [Fin.lastCases_castSucc] + · simp only [Fin.lastCases_last] + +theorem splitLast_law {A : Type*} [Fintype A] (calls : Nat) (μ : FiniteDistribution A) : + (FiniteProduct.law (fun _ : Fin (calls + 1) => μ)).pushforward (splitLast calls A) = + (FiniteProduct.law (fun _ : Fin calls => μ)).product μ := by + rw [← FiniteDistribution.transport_eq_pushforward] + apply FiniteDistribution.eq_of_weight_eq + rintro ⟨values, last⟩ + change (∏ i : Fin (calls + 1), μ.weight (Fin.lastCases last values i)) = + (∏ i : Fin calls, μ.weight (values i)) * μ.weight last + rw [Fin.prod_univ_castSucc] + simp only [Fin.lastCases_castSucc, Fin.lastCases_last] + +private def middleSwap (A B C : Type*) : (A × B) × C ≃ (A × C) × B where + toFun z := ((z.1.1, z.2), z.1.2) + invFun z := ((z.1.1, z.2), z.1.2) + left_inv _ := rfl + right_inv _ := rfl + +private theorem product_assoc_law {E A B : Type*} + [Fintype E] [Fintype A] [Fintype B] + (μ : FiniteDistribution E) (ν : FiniteDistribution A) (ξ : FiniteDistribution B) : + (μ.product (ν.product ξ)).pushforward (fun z => ((z.1, z.2.1), z.2.2)) = + (μ.product ν).product ξ := by + change (μ.product (ν.product ξ)).pushforward (Equiv.prodAssoc E A B).symm = _ + rw [← FiniteDistribution.transport_eq_pushforward] + apply FiniteDistribution.eq_of_weight_eq + intro z + exact (mul_assoc _ _ _).symm + +private theorem lift_split_law {E D A B : Type*} + [Fintype E] [Fintype D] [Fintype A] [Fintype B] + (μ : FiniteDistribution E) (ν : FiniteDistribution D) + (ρ : FiniteDistribution A) (ξ : FiniteDistribution B) (split : D → A × B) + (hsplit : ν.pushforward split = ρ.product ξ) : + (μ.product ν).pushforward (fun z => ((z.1, (split z.2).1), (split z.2).2)) = + (μ.product ρ).product ξ := by + have hmap : (μ.product ν).pushforward (fun z => (z.1, split z.2)) = + μ.product (ρ.product ξ) := by + have h := FiniteDistribution.product_pushforward μ ν id split + simpa only [id_eq, FiniteDistribution.pushforward_id, hsplit] using h + calc + _ = ((μ.product ν).pushforward (fun z => (z.1, split z.2))).pushforward + (fun z => ((z.1, z.2.1), z.2.2)) := + (FiniteDistribution.pushforward_comp _ _ _).symm + _ = (μ.product (ρ.product ξ)).pushforward + (fun z => ((z.1, z.2.1), z.2.2)) := + congrArg (fun law : FiniteDistribution (E × (A × B)) => + law.pushforward (fun z => ((z.1, z.2.1), z.2.2))) hmap + _ = _ := product_assoc_law μ ρ ξ + +variable {branch : Nat → Nat} {n m k t : Nat} + +def splitAssembled (calls : Nat) (rows : Nat → Nat) + (slots : Slots branch (m + 1) → Fin t → MixedSupport.Slot) : + CutChildGrouping.Assembled (C := Fin (calls + 1)) slots rows ≃ + CutChildGrouping.Assembled (C := Fin calls) slots rows × H slots := + (OriginalWholeCutBridge.assembledEquiv (calls + 1) rows slots).symm.trans + ((Equiv.prodCongr (splitLast calls (H slots)) (Equiv.refl (ChildArrays rows slots))).trans + ((middleSwap (Fin calls → H slots) (H slots) (ChildArrays rows slots)).trans + (Equiv.prodCongr (OriginalWholeCutBridge.assembledEquiv calls rows slots) + (Equiv.refl (H slots))))) + +def observationLaw (calls : Nat) (rows repeats : Nat → Nat) (chosen : Fin (branch m)) + (q : Path branch m k) (slots : Slots branch (m + 1) → Fin t → MixedSupport.Slot) : + FiniteDistribution (CutChildGrouping.Assembled (C := Fin calls) slots rows) := + (OriginalChildBlocks.sourceLaw calls rows repeats chosen q slots).pushforward + (OriginalChildBlocks.observed calls rows repeats chosen q slots) + +theorem observation_split_law (calls : Nat) (rows repeats : Nat → Nat) + (chosen : Fin (branch m)) (q : Path branch m k) + (slots : Slots branch (m + 1) → Fin t → MixedSupport.Slot) : + (observationLaw (calls + 1) rows repeats chosen q slots).pushforward + (splitAssembled calls rows slots) = + (observationLaw calls rows repeats chosen q slots).product + (RecursiveSampler.law F2 repeats (.step chosen q) (LeafDomain slots)) := by + simp only [observationLaw, OriginalWholeCutBridge.observed_product_law] + rw [← FiniteDistribution.transport_eq_pushforward] + apply FiniteDistribution.eq_of_weight_eq + intro z + change ((∏ i : Fin (calls + 1), + (RecursiveSampler.law F2 repeats (.step chosen q) (LeafDomain slots)).weight + (Fin.lastCases z.2 z.1.1 i)) * + (belowArraysLaw rows repeats chosen q slots).weight z.1.2) = + ((∏ i : Fin calls, + (RecursiveSampler.law F2 repeats (.step chosen q) (LeafDomain slots)).weight (z.1.1 i)) * + (belowArraysLaw rows repeats chosen q slots).weight z.1.2) * + (RecursiveSampler.law F2 repeats (.step chosen q) (LeafDomain slots)).weight z.2 + rw [Fin.prod_univ_castSucc] + simp only [Fin.lastCases_castSucc, Fin.lastCases_last] + ring + +theorem uniform_split_law (calls : Nat) (rows : Nat → Nat) + (slots : Slots branch (m + 1) → Fin t → MixedSupport.Slot) : + (FiniteDistribution.uniform (CutChildGrouping.Assembled (C := Fin (calls + 1)) slots rows)).pushforward + (splitAssembled calls rows slots) = + (FiniteDistribution.uniform (CutChildGrouping.Assembled (C := Fin calls) slots rows)).product + (FiniteDistribution.uniform (H slots)) := by + rw [← FiniteDistribution.transport_eq_pushforward, UniformConditioning.uniform_transport] + exact WholeCutSampler.uniform_product.symm + +abbrev EnlargedRecord (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) := + Exterior rows repeats p slots × CutChildGrouping.Assembled + (C := Fin (OriginalCutCalls.count rows repeats n (m + 1) + 1)) (cutSlots p slots) rows + +def splitRecord (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : EnlargedRecord rows repeats p slots) : + OriginalWholeCutBridge.NumberedRecord rows repeats p slots × H (cutSlots p slots) := + let split := splitAssembled (OriginalCutCalls.count rows repeats n (m + 1)) rows + (cutSlots p slots) record.2 + ((record.1, split.1), split.2) + +@[simp] theorem splitRecord_oldCall (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : EnlargedRecord rows repeats p slots) + (call : Fin (OriginalCutCalls.count rows repeats n (m + 1))) : + (splitRecord rows repeats p slots record).1.2.1 call = record.2.1 call.castSucc := rfl + +@[simp] theorem splitRecord_fresh (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : EnlargedRecord rows repeats p slots) : + (splitRecord rows repeats p slots record).2 = + record.2.1 (Fin.last (OriginalCutCalls.count rows repeats n (m + 1))) := rfl + +attribute [local instance 2000] OriginalWholeCutLaw.valuesBelowFintype + +theorem record_fresh_law (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (chosen : Fin (branch m)) (q : Path branch m k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + ((exteriorLaw rows repeats p slots).product + (observationLaw (OriginalCutCalls.count rows repeats n (m + 1) + 1) + rows repeats chosen q (cutSlots p slots))).pushforward (splitRecord rows repeats p slots) = + ((recordLaw rows repeats p chosen q slots).pushforward + (OriginalWholeCutBridge.numberRecord rows repeats p slots)).product + (RecursiveSampler.law F2 repeats (.step chosen q) (LeafDomain (cutSlots p slots))) := by + rw [OriginalWholeCutBridge.numberRecord_law] + exact lift_split_law (exteriorLaw rows repeats p slots) _ _ _ + (splitAssembled (OriginalCutCalls.count rows repeats n (m + 1)) rows (cutSlots p slots)) + (observation_split_law (OriginalCutCalls.count rows repeats n (m + 1)) + rows repeats chosen q (cutSlots p slots)) + +theorem uniform_record_fresh_law (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + ((exteriorLaw rows repeats p slots).product + (FiniteDistribution.uniform (CutChildGrouping.Assembled + (C := Fin (OriginalCutCalls.count rows repeats n (m + 1) + 1)) (cutSlots p slots) rows))).pushforward + (splitRecord rows repeats p slots) = + ((OriginalUniformCut.referenceLaw rows repeats p slots).pushforward + (OriginalWholeCutBridge.numberRecord rows repeats p slots)).product + (FiniteDistribution.uniform (H (cutSlots p slots))) := by + rw [NumberedUniformCut.reference_numberRecord_law] + exact lift_split_law (exteriorLaw rows repeats p slots) _ _ _ + (splitAssembled (OriginalCutCalls.count rows repeats n (m + 1)) rows (cutSlots p slots)) + (uniform_split_law (OriginalCutCalls.count rows repeats n (m + 1)) rows (cutSlots p slots)) + +def arraysAndFresh (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : EnlargedRecord rows repeats p slots) : Arrays slots rows × H (cutSlots p slots) := + (OriginalWholeCutBridge.reconstruct rows repeats p slots + (splitRecord rows repeats p slots record).1, (splitRecord rows repeats p slots record).2) + +theorem arrays_fresh_law (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (chosen : Fin (branch m)) (q : Path branch m k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + ((exteriorLaw rows repeats p slots).product + (observationLaw (OriginalCutCalls.count rows repeats n (m + 1) + 1) + rows repeats chosen q (cutSlots p slots))).pushforward (arraysAndFresh rows repeats p slots) = + (WholeArraySampler.law rows repeats (p.append (.step chosen q)) slots).product + (RecursiveSampler.law F2 repeats (.step chosen q) (LeafDomain (cutSlots p slots))) := by + calc + _ = (((exteriorLaw rows repeats p slots).product + (observationLaw (OriginalCutCalls.count rows repeats n (m + 1) + 1) + rows repeats chosen q (cutSlots p slots))).pushforward + (splitRecord rows repeats p slots)).pushforward + (fun z => (OriginalWholeCutBridge.reconstruct rows repeats p slots z.1, z.2)) := + (FiniteDistribution.pushforward_comp _ _ _).symm + _ = _ := by + rw [record_fresh_law, OriginalWholeCutBridge.numberRecord_law] + have h := FiniteDistribution.product_pushforward + ((exteriorLaw rows repeats p slots).product + (observationLaw (OriginalCutCalls.count rows repeats n (m + 1)) + rows repeats chosen q (cutSlots p slots))) + (RecursiveSampler.law F2 repeats (.step chosen q) (LeafDomain (cutSlots p slots))) + (OriginalWholeCutBridge.reconstruct rows repeats p slots) id + simpa only [id_eq, FiniteDistribution.pushforward_id, + observationLaw, OriginalWholeCutBridge.reconstruct_child_law] using h + +theorem uniform_arrays_fresh_law (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + ((exteriorLaw rows repeats p slots).product + (FiniteDistribution.uniform (CutChildGrouping.Assembled + (C := Fin (OriginalCutCalls.count rows repeats n (m + 1) + 1)) (cutSlots p slots) rows))).pushforward + (arraysAndFresh rows repeats p slots) = + (WholeArraySampler.law rows repeats p slots).product + (FiniteDistribution.uniform (H (cutSlots p slots))) := by + calc + _ = (((exteriorLaw rows repeats p slots).product + (FiniteDistribution.uniform (CutChildGrouping.Assembled + (C := Fin (OriginalCutCalls.count rows repeats n (m + 1) + 1)) (cutSlots p slots) rows))).pushforward + (splitRecord rows repeats p slots)).pushforward + (fun z => (OriginalWholeCutBridge.reconstruct rows repeats p slots z.1, z.2)) := + (FiniteDistribution.pushforward_comp _ _ _).symm + _ = _ := by + rw [uniform_record_fresh_law, NumberedUniformCut.reference_numberRecord_law] + have h := FiniteDistribution.product_pushforward + ((exteriorLaw rows repeats p slots).product + (FiniteDistribution.uniform (CutChildGrouping.Assembled + (C := Fin (OriginalCutCalls.count rows repeats n (m + 1))) (cutSlots p slots) rows))) + (FiniteDistribution.uniform (H (cutSlots p slots))) + (OriginalWholeCutBridge.reconstruct rows repeats p slots) id + simpa only [id_eq, FiniteDistribution.pushforward_id, + NumberedUniformCut.reconstruct_product_uniform] using h + +end +end PerfectCompleteness.ExtraCutCall + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/FiniteProduct.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/FiniteProduct.lean new file mode 100644 index 0000000000000000000000000000000000000000..bd853710713a765ad5430cff2735b50840cf4d2b --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/FiniteProduct.lean @@ -0,0 +1,120 @@ +import Mathlib.Data.Fintype.BigOperators +import OAI.Computability.PerfectCompleteness.Foundations.RecursiveSpaceEquivLemmas +import OAI.Computability.UniqueGames.Foundations.ValueLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.FiniteProduct + +open scoped BigOperators +open UniqueGamesTheorem.Foundations.Games + +noncomputable section + +variable {I : Type*} [Fintype I] [DecidableEq I] + {Ω : I → Type*} [∀ i, Fintype (Ω i)] + +def law (P : (i : I) → FiniteDistribution (Ω i)) : + FiniteDistribution ((i : I) → Ω i) where + weight x := ∏ i, (P i).weight (x i) + nonnegative x := Finset.prod_nonneg fun i _ => (P i).nonnegative (x i) + normalized := by + rw [← Fintype.prod_sum] + simp only [FiniteDistribution.normalized, Finset.prod_const_one] + +theorem expectation_product (P : (i : I) → FiniteDistribution (Ω i)) + (f : (i : I) → Ω i → ℝ) : + (law P).expectation (fun x => ∏ i, f i (x i)) = + ∏ i, (P i).expectation (f i) := by + change (∑ x : (i : I) → Ω i, (∏ i, (P i).weight (x i)) * + (∏ i, f i (x i))) = ∏ i, ∑ a, (P i).weight a * f i a + simp only [← Finset.prod_mul_distrib] + exact (Fintype.prod_sum (fun i a => (P i).weight a * f i a)).symm + +def factor (i : I) (f : Ω i → ℝ) (j : I) (a : Ω j) : ℝ := + if h : j = i then f (h ▸ a) else 1 + +omit [Fintype I] [∀ index, Fintype (Ω index)] in +@[simp] theorem factor_self (i : I) (f : Ω i → ℝ) (a : Ω i) : + factor i f i a = f a := by simp [factor] + +omit [Fintype I] [∀ index, Fintype (Ω index)] in +@[simp] theorem factor_other (i j : I) (h : j ≠ i) (f : Ω i → ℝ) (a : Ω j) : + factor i f j a = 1 := by simp [factor, h] + +omit [Fintype I] [∀ index, Fintype (Ω index)] in +@[simp] theorem factor_function_self (i : I) (f : Ω i → ℝ) : + factor i f i = f := by funext a; exact factor_self i f a + +omit [Fintype I] [∀ index, Fintype (Ω index)] in +@[simp] theorem factor_function_other (i j : I) (h : j ≠ i) (f : Ω i → ℝ) : + factor i f j = fun _ => 1 := by funext a; exact factor_other i j h f a + +omit [∀ index, Fintype (Ω index)] in +theorem product_factor (i : I) (f : Ω i → ℝ) (x : (j : I) → Ω j) : + (∏ j, factor i f j (x j)) = f (x i) := by + classical + rw [Finset.prod_eq_single i] + · exact factor_self i f (x i) + · intro j _ h + exact factor_other i j h f (x j) + · simp + +theorem expectation_factor_product (P : (i : I) → FiniteDistribution (Ω i)) + (i : I) (f : Ω i → ℝ) : + (∏ j, (P j).expectation (factor i f j)) = (P i).expectation f := by + classical + rw [Finset.prod_eq_single i] + · congr 1 + funext a + exact factor_self i f a + · intro j _ h + rw [factor_function_other i j h, SmallBias.expectation_const] + · simp + +theorem expectation_eval (P : (i : I) → FiniteDistribution (Ω i)) + (i : I) (f : Ω i → ℝ) : + (law P).expectation (fun x => f (x i)) = (P i).expectation f := by + calc + _ = (law P).expectation (fun x => ∏ j, factor i f j (x j)) := by + apply FiniteDistribution.expectation_congr + intro x + exact (product_factor i f x).symm + _ = ∏ j, (P j).expectation (factor i f j) := expectation_product P _ + _ = _ := expectation_factor_product P i f + +theorem expectation_eval_mul (P : (i : I) → FiniteDistribution (Ω i)) + (i j : I) (hij : i ≠ j) (f : Ω i → ℝ) (g : Ω j → ℝ) : + (law P).expectation (fun x => f (x i) * g (x j)) = + (P i).expectation f * (P j).expectation g := by + have hfactor : ∀ k, + (P k).expectation (fun a => factor i f k a * factor j g k a) = + (P k).expectation (factor i f k) * (P k).expectation (factor j g k) := by + intro k + by_cases hki : k = i + · subst k + simp only [factor_other j i hij, factor_function_other j i hij, + SmallBias.expectation_const, mul_one] + · simp only [factor_other i k hki, factor_function_other i k hki, + SmallBias.expectation_const, one_mul] + calc + _ = (law P).expectation + (fun x => ∏ k, factor i f k (x k) * factor j g k (x k)) := by + apply FiniteDistribution.expectation_congr + intro x + rw [Finset.prod_mul_distrib, product_factor i f x, product_factor j g x] + _ = ∏ k, (P k).expectation (fun a => factor i f k a * factor j g k a) := + expectation_product P (fun k a => factor i f k a * factor j g k a) + _ = (∏ k, (P k).expectation (factor i f k)) * + (∏ k, (P k).expectation (factor j g k)) := by + simp only [hfactor, Finset.prod_mul_distrib] + _ = _ := by rw [expectation_factor_product P i f, expectation_factor_product P j g] + +end +end PerfectCompleteness.FiniteProduct + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/FiniteRangeInverse.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/FiniteRangeInverse.lean new file mode 100644 index 0000000000000000000000000000000000000000..cd23e11eb340f1606de0af580eea89967e26cb30 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/FiniteRangeInverse.lean @@ -0,0 +1,91 @@ +import Mathlib.LinearAlgebra.Dual.Lemmas +import OAI.Computability.PerfectCompleteness.Algebra.BilinearGramCompressionLemmas +import OAI.Computability.PerfectCompleteness.Algebra.MatrixInverseConstantsLemmas +import OAI.Computability.PerfectCompleteness.Foundations.PartialTableInverse + +namespace OAI + +section + +namespace PerfectCompleteness.FiniteRangeInverse + +noncomputable section + +open scoped BigOperators Classical +open UniqueGamesTheorem.Fourier.MatrixCharacters (F2) +open UniqueGamesTheorem.Fourier.MatrixRestrictions +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) +open PerfectCompleteness.PartialTableInverse + +attribute [local instance] linearMapFintype + +universe u v w + +variable {H : Type u} {K : Type v} {Y : Type w} + [AddCommGroup H] [Module F2 H] [AddCommGroup K] [Module F2 K] + [Fintype H] [Fintype K] [Fintype Y] + [FiniteDimensional F2 H] [FiniteDimensional F2 K] + +def matrixStep (X : Module.Dual F2 H →ₗ[F2] K) (a : K) (h : H) : + Module.Dual F2 H →ₗ[F2] K := + X + (Module.Dual.eval F2 H h).smulRight a + +omit [Fintype H] [Fintype K] [FiniteDimensional F2 H] [FiniteDimensional F2 K] in +@[simp] theorem matrixStep_apply (X : Module.Dual F2 H →ₗ[F2] K) (a : K) + (h : H) (q : Module.Dual F2 H) : matrixStep X a h q = X q + q h • a := rfl + +def agreement (f : (Module.Dual F2 H →ₗ[F2] K) → Option Y) : ℝ := + 𝔼 a : {a : K // a ≠ 0}, 𝔼 X : Module.Dual F2 H →ₗ[F2] K, + 𝔼 h : H, definedEquality f X (matrixStep X a.val h) + +omit [Fintype Y] [FiniteDimensional F2 K] in +theorem agreement_eq_nonzeroAgreement + (f : (Module.Dual F2 H →ₗ[F2] K) → Option Y) : + agreement f = nonzeroAgreement f := by + apply Finset.expect_congr rfl + intro a _ + apply Finset.expect_congr rfl + intro X _ + exact Fintype.expect_equiv (Module.evalEquiv F2 H).toEquiv + (fun h : H => definedEquality f X (matrixStep X a.val h)) + (fun φ : Module.Dual F2 (Module.Dual F2 H) => + definedEquality f X (X + φ.smulRight a.val)) (fun _ => rfl) + +theorem dense_slice_of_parameters [Nontrivial K] + (r : Nat) (ρ η : ℝ) (hρ : 0 < ρ) (hρ1 : ρ < 1) + (hconstants : UniqueGamesTheorem.Fourier.MatrixLevelBridge.levelCutoffConstant r ρ + + UniqueGamesTheorem.Appendix.RankLevelFilter.node (r + 1) < η) + (f : (Module.Dual F2 H →ₗ[F2] K) → Option Y) (hagreement : η ≤ agreement f) : + ∃ (y : Y) (W : Submodule F2 (Module.Dual F2 H)) (C' : Submodule F2 K) + (T : Module.Dual F2 H →ₗ[F2] K), + order W C' ≤ r ∧ + ρ < (𝔼 X : MatrixSlice.Slice W C' T, indicator f y X.val) := by + rw [agreement_eq_nonzeroAgreement] at hagreement + obtain ⟨y, W, C', T, horder, hdensity⟩ := + exists_dense_slice_nonzero r ρ η hρ hρ1 hconstants f hagreement + refine ⟨y, W, C', T, horder, ?_⟩ + rwa [MatrixSlice.expect_restrict_eq_slice] at hdensity + +theorem inverse {η : ℝ} (hη : 0 < η) : + ∃ r : Nat, 1 ≤ r ∧ ∃ ρ : ℝ, 0 < ρ ∧ ρ < 1 ∧ + ∀ (H : Type u) (K : Type v) (Y : Type w) + [AddCommGroup H] [Module F2 H] [AddCommGroup K] [Module F2 K] + [Fintype H] [Fintype K] [Fintype Y] + [FiniteDimensional F2 H] [FiniteDimensional F2 K] [Nontrivial K] + (f : (Module.Dual F2 H →ₗ[F2] K) → Option Y), + η ≤ agreement f → + ∃ (y : Y) (W : Submodule F2 (Module.Dual F2 H)) (C' : Submodule F2 K) + (T : Module.Dual F2 H →ₗ[F2] K), + order W C' ≤ r ∧ + ρ < (𝔼 X : MatrixSlice.Slice W C' T, indicator f y X.val) := by + obtain ⟨r, hr, ρ, hρ, hρ1, hconstants⟩ := MatrixInverseConstants.exists_cutoff_density hη + refine ⟨r, hr, ρ, hρ, hρ1, ?_⟩ + intro H K Y _ _ _ _ _ _ _ _ _ _ f hagreement + exact dense_slice_of_parameters r ρ η hρ hρ1 hconstants f hagreement + +end +end PerfectCompleteness.FiniteRangeInverse + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/GeometricPathLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/GeometricPathLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..9247a0b719d64e2e1195b2384ce2e8810690c37e --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/GeometricPathLemmas.lean @@ -0,0 +1,163 @@ +import Mathlib.Data.Fin.Tuple.Basic +import OAI.Computability.PerfectCompleteness.Algebra.HierarchicalMatrixTable +import OAI.Computability.PerfectCompleteness.Algebra.MatrixTriangularFoldingLemmas +import OAI.Computability.PerfectCompleteness.Construction.FactoredFunctionsLemmas +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalArrays +import OAI.Computability.UniqueGames.Foundations.SamplingLemmas +import OAI.Computability.UniqueGames.Foundations.ValueLemmas + +namespace OAI + + +namespace PerfectCompleteness.GeometricPath + +open RecursiveSpaces DescendantSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +variable {branch : Nat → Nat} + +def leafPath : {n : Nat} → Slots branch n → Path branch n 0 + | 0, _ => .refl 0 + | _ + 1, leaf => .step leaf.1 (leafPath leaf.2) + +theorem leafPath_endpoint : ∀ {n : Nat} (leaf : Slots branch n), + (leafPath leaf).slotEmbedding () = leaf := by + intro n + induction n with + | zero => intro leaf; cases leaf; rfl + | succ n ih => + intro leaf + exact Prod.ext rfl (ih leaf.2) + +def nodeAtLevel : {n : Nat} → Slots branch n → Fin n → Nodes branch n + | 0, _, level => Fin.elim0 level + | _ + 1, leaf, level => + Fin.lastCases (.inl ()) (fun lower => .inr (leaf.1, nodeAtLevel leaf.2 lower)) level + +@[simp] theorem nodeAtLevel_last {n : Nat} (leaf : Slots branch (n + 1)) : + nodeAtLevel leaf (Fin.last n) = (.inl () : Nodes branch (n + 1)) := by + exact Fin.lastCases_last (n := n) (motive := fun _ => Nodes branch (n + 1)) + (last := (.inl () : Nodes branch (n + 1))) + (cast := fun lower : Fin n => (.inr (leaf.1, nodeAtLevel leaf.2 lower) : Nodes branch (n + 1))) + +@[simp] theorem nodeAtLevel_castSucc {n : Nat} (leaf : Slots branch (n + 1)) + (lower : Fin n) : + nodeAtLevel leaf lower.castSucc = + (.inr (leaf.1, nodeAtLevel leaf.2 lower) : Nodes branch (n + 1)) := by + exact Fin.lastCases_castSucc (n := n) (motive := fun _ => Nodes branch (n + 1)) + (last := (.inl () : Nodes branch (n + 1))) + (cast := fun j : Fin n => (.inr (leaf.1, nodeAtLevel leaf.2 j) : Nodes branch (n + 1))) lower + +theorem nodeAtLevel_height : ∀ {n : Nat} (leaf : Slots branch n) (level : Fin n), + Nodes.height (nodeAtLevel leaf level) = level.val + 1 := by + intro n + induction n with + | zero => intro leaf level; exact Fin.elim0 level + | succ n ih => + intro leaf level + refine Fin.lastCases ?_ (fun lower => ?_) level + · simp only [nodeAtLevel_last, Nodes.height, Fin.val_last] + · simpa only [nodeAtLevel_castSucc, Nodes.height, Fin.val_castSucc] + using ih leaf.2 lower + +theorem nodeAtLevel_injective {n : Nat} (leaf : Slots branch n) : + Function.Injective (nodeAtLevel leaf) := by + intro i j h + apply Fin.ext + have hh := congrArg Nodes.height h + rw [nodeAtLevel_height, nodeAtLevel_height] at hh + exact Nat.add_right_cancel hh + +theorem slots_nonempty : ∀ (n : Nat), (∀ k < n, 0 < branch k) → Nonempty (Slots branch n) := by + intro n + induction n with + | zero => intro _; exact ⟨()⟩ + | succ n ih => + intro hbranch + obtain ⟨leaf⟩ := ih (fun k hk => hbranch k (Nat.lt_trans hk (Nat.lt_succ_self n))) + exact ⟨(⟨0, hbranch n (Nat.lt_succ_self n)⟩, leaf)⟩ + +noncomputable def law (n : Nat) (hbranch : ∀ k < n, 0 < branch k) : + FiniteDistribution (Slots branch n) := by + letI := slots_nonempty n hbranch + exact FiniteDistribution.uniform (Slots branch n) + +theorem law_step (n : Nat) (hbranch : ∀ k < n + 1, 0 < branch k) : + law (n + 1) hbranch = + (by + letI : Nonempty (Fin (branch n)) := ⟨⟨0, hbranch n (Nat.lt_succ_self n)⟩⟩ + exact (FiniteDistribution.uniform (Fin (branch n))).product + (law n (fun k hk => hbranch k (Nat.lt_trans hk (Nat.lt_succ_self n))))) := by + apply FiniteDistribution.eq_of_weight_eq + intro leaf + change (1 : ℝ) / (Fintype.card (Fin (branch n) × Slots branch n) : ℝ) = + ((1 : ℝ) / (Fintype.card (Fin (branch n)) : ℝ)) * + ((1 : ℝ) / (Fintype.card (Slots branch n) : ℝ)) + simp [Fintype.card_prod, Nat.cast_mul, one_div, mul_inv_rev, mul_comm] + +end PerfectCompleteness.GeometricPath + + + +namespace PerfectCompleteness.HierarchicalKnownRows + +noncomputable section + +open TreeSourceSpaces HierarchicalArrays + +variable {branch rows : Nat → Nat} {n t : Nat} {D : Type*} + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (upper : Nodes branch n) + (background : HierarchicalMatrixTable.Background (rows := rows) slots upper) + (descendant : D → {j : Nodes branch n // j ≠ upper}) + +def lower (x : NodeEmbedding.NumberedDomain slots) (d : D) : + Fin (rows (Nodes.height (descendant d).val)) → F2 := + (HierarchicalMatrixTable.other slots upper background x).1 (descendant d) + +@[simp] theorem lower_apply (x : NodeEmbedding.NumberedDomain slots) + (d : D) (i : Fin (rows (Nodes.height (descendant d).val))) : + lower slots upper background descendant x d i = + (background (descendant d) i).val + (NodeEmbedding.numberedRestriction slots (descendant d).val x) := rfl + +def knownSpace : Submodule F2 (NodeEmbedding.NumberedDomain slots → F2) := + FactoredFunctionsDependent.dependentQuadraticSpan (lower slots upper background descendant) + +theorem one_mem_knownSpace : + (1 : NodeEmbedding.NumberedDomain slots → F2) ∈ knownSpace slots upper background descendant := + FactoredFunctionsDependent.one_mem_dependentQuadraticSpan _ + +theorem product_mem_knownSpace (d : D) + (i j : Fin (rows (Nodes.height (descendant d).val))) : + (fun x => lower slots upper background descendant x d i * + lower slots upper background descendant x d j) ∈ knownSpace slots upper background descendant := + FactoredFunctionsDependent.product_mem_dependentQuadraticSpan + (𝕜 := F2) (Ω := NodeEmbedding.NumberedDomain slots) (I := D) + (J := fun d => Fin (rows (Nodes.height (descendant d).val))) + (lower slots upper background descendant) d i j + +theorem knownSpace_le_factoringSpace : + knownSpace slots upper background descendant ≤ + FactoredFunctions.factoringSpace (HierarchicalMatrixTable.other slots upper background) := by + intro f hf x y hxy + apply FactoredFunctionsDependent.dependentQuadraticSpan_le_factoringSpace + (lower slots upper background descendant) hf x y + funext d i + exact congrArg (fun z : HierarchicalMatrixTable.SideOutput (rows := rows) upper => + z.1 (descendant d) i) hxy + +theorem determined : + RepresentativeMatrixTable.Determined (TreeCanonical.numberedSlots slots) + (NodeEmbedding.RowSpace slots upper) (HierarchicalMatrixTable.other slots upper background) + ((knownSpace slots upper background descendant).comap + (NodeEmbedding.RowSpace slots upper).subtype) := + RepresentativeMatrixTable.determined_comap (TreeCanonical.numberedSlots slots) + (NodeEmbedding.RowSpace slots upper) (HierarchicalMatrixTable.other slots upper background) + (knownSpace slots upper background descendant) + (knownSpace_le_factoringSpace slots upper background descendant) + +end +end PerfectCompleteness.HierarchicalKnownRows + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/GeometricPrefixSplit.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/GeometricPrefixSplit.lean new file mode 100644 index 0000000000000000000000000000000000000000..0fd757d6927931e10249610a93f185f28c164cf5 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/GeometricPrefixSplit.lean @@ -0,0 +1,194 @@ +import Lean.Elab.Tactic.Omega +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalFrozenTablesLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.GeometricPrefixSplit + +open RecursiveSpaces DescendantSpaces +open GeometricCutSplit (Prefix PrefixDepth prefixPathDepth prefixPath castPath prefixLaw) +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +variable {branch : Nat → Nat} + +def depthEquiv (low b : Nat) : (a : Nat) → + PrefixDepth branch low (b + a) ≃ + PrefixDepth branch (low + b) a × PrefixDepth branch low b + | 0 => + { toFun := fun x => ((), x) + invFun := Prod.snd + left_inv := fun _ => rfl + right_inv := by rintro ⟨⟨⟩, x⟩; rfl } + | a + 1 => + ((Equiv.cast (congrArg (fun h => Fin (branch h)) + (Nat.add_assoc low b a).symm)).prodCongr (depthEquiv low b a)).trans + (Equiv.prodAssoc _ _ _).symm + +private theorem castPath_step {x y low : Nat} (h : x = y) + (c : Fin (branch x)) (p : Path branch x low) : + castPath (congrArg Nat.succ h) (.step c p) = + .step (Equiv.cast (congrArg (fun n => Fin (branch n)) h) c) + (castPath h p) := by + cases h + rfl + +theorem depthEquiv_path (low b a : Nat) + (x : PrefixDepth branch low (b + a)) : + castPath (Nat.add_assoc low b a).symm (prefixPathDepth low (b + a) x) = + (prefixPathDepth (low + b) a (depthEquiv low b a x).1).append + (prefixPathDepth low b (depthEquiv low b a x).2) := by + revert x + induction a with + | zero => intro x; rfl + | succ a ih => + intro x + change castPath (congrArg Nat.succ (Nat.add_assoc low b a).symm) + (.step x.1 (prefixPathDepth low (b + a) x.2)) = _ + rw [castPath_step (Nat.add_assoc low b a).symm x.1 + (prefixPathDepth low (b + a) x.2)] + exact congrArg (Path.step _) (ih x.2) + +private theorem castPath_trans {x y z low : Nat} (h : x = y) (g : y = z) + (p : Path branch x low) : + castPath g (castPath h p) = castPath (h.trans g) p := by + cases h + cases g + rfl + +private theorem prefixPathDepth_cast {low d e : Nat} (h : d = e) + (x : PrefixDepth branch low d) : + prefixPathDepth low e (Equiv.cast (congrArg (PrefixDepth branch low) h) x) = + castPath (congrArg (fun n => low + n) h) (prefixPathDepth low d x) := by + cases h + rfl + +private theorem castPath_append {x y mid low : Nat} (h : x = y) + (p : Path branch x mid) (q : Path branch mid low) : + castPath h (p.append q) = (castPath h p).append q := by + cases h + rfl + +private theorem castPath_depth_append {x y low : Nat} (h : x = y) (a : Nat) + (upper : PrefixDepth branch x a) (lower : Path branch x low) : + castPath (congrArg (fun n => n + a) h) + ((prefixPathDepth x a upper).append lower) = + (prefixPathDepth y a + (Equiv.cast (congrArg (fun n => PrefixDepth branch n a) h) upper)).append + (castPath h lower) := by + cases h + rfl + +variable {root mid low : Nat} + +def splitEquiv (hlow : low ≤ mid) (hmid : mid ≤ root) : + Prefix branch root low ≃ Prefix branch root mid × Prefix branch mid low := + (Equiv.cast (congrArg (PrefixDepth branch low) + (show root - low = (mid - low) + (root - mid) by omega))).trans + ((depthEquiv low (mid - low) (root - mid)).trans + ((Equiv.cast (congrArg (fun n => PrefixDepth branch n (root - mid)) + (Nat.add_sub_of_le hlow))).prodCongr (Equiv.refl _))) + +def joinEquiv (hlow : low ≤ mid) (hmid : mid ≤ root) : + Prefix branch root mid × Prefix branch mid low ≃ Prefix branch root low := + (splitEquiv hlow hmid).symm + +@[simp] theorem split_join (hlow : low ≤ mid) (hmid : mid ≤ root) + (pair : Prefix branch root mid × Prefix branch mid low) : + splitEquiv hlow hmid (joinEquiv hlow hmid pair) = pair := + (splitEquiv hlow hmid).apply_symm_apply pair + +@[simp] theorem join_split (hlow : low ≤ mid) (hmid : mid ≤ root) + (pref : Prefix branch root low) : + joinEquiv hlow hmid (splitEquiv hlow hmid pref) = pref := + (splitEquiv hlow hmid).symm_apply_apply pref + +theorem prefixPath_split (hlow : low ≤ mid) (hmid : mid ≤ root) + (pref : Prefix branch root low) : + prefixPath (hlow.trans hmid) pref = + (prefixPath hmid (splitEquiv hlow hmid pref).1).append + (prefixPath hlow (splitEquiv hlow hmid pref).2) := by + let a := root - mid + let b := mid - low + have hd : root - low = b + a := by dsimp [a, b]; omega + have hm : low + b = mid := Nat.add_sub_of_le hlow + let x : PrefixDepth branch low (b + a) := + Equiv.cast (congrArg (PrefixDepth branch low) hd) pref + calc + prefixPath (hlow.trans hmid) pref = + castPath (Nat.add_sub_of_le hmid) + (castPath (congrArg (fun n => n + a) hm) + (castPath (Nat.add_assoc low b a).symm + (prefixPathDepth low (b + a) x))) := by + dsimp only [x] + rw [prefixPathDepth_cast hd pref] + simp only [castPath_trans] + rfl + _ = castPath (Nat.add_sub_of_le hmid) + (castPath (congrArg (fun n => n + a) hm) + ((prefixPathDepth (low + b) a (depthEquiv low b a x).1).append + (prefixPathDepth low b (depthEquiv low b a x).2))) := by + rw [depthEquiv_path] + _ = castPath (Nat.add_sub_of_le hmid) + ((prefixPathDepth mid a + (Equiv.cast (congrArg (fun n => PrefixDepth branch n a) hm) + (depthEquiv low b a x).1)).append + (castPath hm (prefixPathDepth low b (depthEquiv low b a x).2))) := by + rw [castPath_depth_append] + _ = (prefixPath hmid (splitEquiv hlow hmid pref).1).append + (prefixPath hlow (splitEquiv hlow hmid pref).2) := by + rw [castPath_append] + rfl + +theorem prefixPath_split_spec (hlow : low ≤ mid) (hmid : mid ≤ root) + (pref : Prefix branch root low) : + (⟨low, prefixPath (hlow.trans hmid) pref⟩ : Σ height, Path branch root height) = + ⟨low, (prefixPath hmid (splitEquiv hlow hmid pref).1).append + (prefixPath hlow (splitEquiv hlow hmid pref).2)⟩ := + congrArg (fun p : Path branch root low => + (⟨low, p⟩ : Σ height, Path branch root height)) (prefixPath_split hlow hmid pref) + +theorem prefixPath_join (hlow : low ≤ mid) (hmid : mid ≤ root) + (upper : Prefix branch root mid) (lower : Prefix branch mid low) : + prefixPath (hlow.trans hmid) (joinEquiv hlow hmid (upper, lower)) = + (prefixPath hmid upper).append (prefixPath hlow lower) := by + simpa only [split_join] using + prefixPath_split hlow hmid (joinEquiv hlow hmid (upper, lower)) + +noncomputable section + +theorem law_split (hlow : low ≤ mid) (hmid : mid ≤ root) + (hbranch : ∀ k < root, 0 < branch k) : + (prefixLaw (hlow.trans hmid) hbranch).pushforward (splitEquiv hlow hmid) = + (prefixLaw hmid hbranch).product + (prefixLaw hlow (fun k hk => hbranch k (Nat.lt_of_lt_of_le hk hmid))) := by + rw [← FiniteDistribution.transport_eq_pushforward] + apply FiniteDistribution.eq_of_weight_eq + intro pair + change (1 : ℝ) / (Fintype.card (Prefix branch root low) : ℝ) = + ((1 : ℝ) / (Fintype.card (Prefix branch root mid) : ℝ)) * + ((1 : ℝ) / (Fintype.card (Prefix branch mid low) : ℝ)) + rw [Fintype.card_congr (splitEquiv (branch := branch) hlow hmid), + Fintype.card_prod, Nat.cast_mul] + simp only [one_div_mul_one_div] + +theorem expectation_split (hlow : low ≤ mid) (hmid : mid ≤ root) + (hbranch : ∀ k < root, 0 < branch k) + (f : Prefix branch root mid → Prefix branch mid low → ℝ) : + (prefixLaw (hlow.trans hmid) hbranch).expectation + (fun pref => f (splitEquiv hlow hmid pref).1 (splitEquiv hlow hmid pref).2) = + (prefixLaw hmid hbranch).expectation (fun upper => + (prefixLaw hlow (fun k hk => hbranch k (Nat.lt_of_lt_of_le hk hmid))).expectation + (f upper)) := by + rw [← FiniteDistribution.expectation_pushforward + (prefixLaw (hlow.trans hmid) hbranch) (splitEquiv hlow hmid) + (fun pair => f pair.1 pair.2), law_split, FiniteDistribution.expectation_product] + +end +end PerfectCompleteness.GeometricPrefixSplit + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/GlobalityLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/GlobalityLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..b4f426320083b35d4aa2e197fb19dc4b3320d7ba --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/GlobalityLemmas.lean @@ -0,0 +1,942 @@ +import Mathlib.Algebra.Field.ZMod +import Mathlib.Algebra.Order.BigOperators.Expect +import Mathlib.Basic.Real.Basic +import Mathlib.LinearAlgebra.Dual.Lemmas +import Mathlib.RingTheory.Finiteness.Basic +import Mathlib.Tactic.Ring +import OAI.Computability.UniqueGames.Analysis.A13IndexLemmas +import OAI.Computability.UniqueGames.Analysis.A5FrequencyTransportLemmas +import OAI.Computability.UniqueGames.Analysis.FiberEnergyLemmas +import OAI.Computability.UniqueGames.Analysis.HybridCounting +import OAI.Computability.UniqueGames.Analysis.MatrixNoiseLemmas +import OAI.Computability.UniqueGames.Analysis.MatrixRestrictions +import OAI.Computability.UniqueGames.Analysis.RestrictionLemmas +import OAI.Computability.UniqueGames.Gadgets.AdaptivePathsLemmas + +namespace OAI + +section + +open scoped BigOperators + +namespace UniqueGamesTheorem.Appendix.Globality + +noncomputable def energy {N : Type*} [Fintype N] (f : N → ℝ) : ℝ := + 𝔼 n, f n ^ 2 + +theorem energy_nonnegative {N : Type*} [Fintype N] (f : N → ℝ) : + 0 ≤ energy f := by + exact Finset.expect_nonneg fun n _ => sq_nonneg (f n) + +theorem sq_average_le_average_sq {I : Type*} [Fintype I] [Nonempty I] + (f : I → ℝ) : (𝔼 i, f i) ^ 2 ≤ 𝔼 i, f i ^ 2 := by + simpa using Finset.expect_mul_sq_le_sq_mul_sq Finset.univ f (fun _ => (1 : ℝ)) + +theorem energy_average_le {I N : Type*} [Fintype I] [Nonempty I] [Fintype N] + (f : I → N → ℝ) : energy (fun n => 𝔼 i, f i n) ≤ 𝔼 i, energy (f i) := by + calc + energy (fun n => 𝔼 i, f i n) ≤ 𝔼 n, 𝔼 i, f i n ^ 2 := + Finset.expect_le_expect fun n _ => sq_average_le_average_sq (fun i => f i n) + _ = 𝔼 i, energy (f i) := Finset.expect_comm _ _ _ + +theorem energy_average_le_of_bound {I N : Type*} [Fintype I] [Nonempty I] + [Fintype N] (f : I → N → ℝ) (η : ℝ) (h : ∀ i, energy (f i) ≤ η) : + energy (fun n => 𝔼 i, f i n) ≤ η := + (energy_average_le f).trans (Finset.expect_le Finset.univ_nonempty (fun i _ => h i)) + +theorem energy_weighted_sum_le {I N : Type*} [Fintype I] [Fintype N] + (w : I → ℝ) (f : I → N → ℝ) (η : ℝ) + (hw : ∀ i, 0 ≤ w i) (hf : ∀ i, energy (f i) ≤ η) : + energy (fun n => ∑ i, w i * f i n) ≤ (∑ i, w i) ^ 2 * η := by + have hsum : 0 ≤ ∑ i, w i := Finset.sum_nonneg (fun i _ => hw i) + calc + energy (fun n => ∑ i, w i * f i n) ≤ + 𝔼 n, (∑ i, w i) * ∑ i, w i * f i n ^ 2 := by + apply Finset.expect_le_expect + intro n _ + apply Finset.sum_sq_le_sum_mul_sum_of_sq_le_mul Finset.univ + · exact fun i _ => hw i + · exact fun i _ => mul_nonneg (hw i) (sq_nonneg _) + · intro i _ + exact le_of_eq (by ring) + _ = (∑ i, w i) * ∑ i, w i * energy (f i) := by + rw [← Finset.mul_expect, Finset.expect_sum_comm] + simp_rw [← Finset.mul_expect] + rfl + _ ≤ (∑ i, w i) * ∑ i, w i * η := by + apply mul_le_mul_of_nonneg_left _ hsum + exact Finset.sum_le_sum (fun i _ => mul_le_mul_of_nonneg_left (hf i) (hw i)) + _ = (∑ i, w i) ^ 2 * η := by rw [← Finset.sum_mul]; ring + +noncomputable def restrictionEnergy {M N : Type*} [AddCommGroup M] [Fintype N] + (f : M → ℝ) (ι : N → M) (T : M) : ℝ := + energy (fun n => f (T + ι n)) + +theorem restrictionEnergy_translate {M N : Type*} [AddCommGroup M] [Fintype N] + (f : M → ℝ) (ι : N → M) (T a : M) : + restrictionEnergy (fun x => f (x + a)) ι T = restrictionEnergy f ι (T + a) := by + simp only [restrictionEnergy, add_right_comm T] + +theorem restrictionEnergy_average_translate_le {I M N : Type*} + [Fintype I] [Nonempty I] [AddCommGroup M] [Fintype N] + (f : M → ℝ) (ι : N → M) (shifts : I → M) (η : ℝ) + (h : ∀ T, restrictionEnergy f ι T ≤ η) (T : M) : + restrictionEnergy (fun x => 𝔼 i, f (x + shifts i)) ι T ≤ η := by + apply energy_average_le_of_bound (fun i n => f ((T + ι n) + shifts i)) η + intro i + simpa only [restrictionEnergy, add_right_comm T] using h (T + shifts i) + +section BinaryLinear + +open UniqueGamesTheorem.Integration.BinaryLinear +open UniqueGamesTheorem.Fourier.MatrixRestrictions + +variable {E F : Type*} [AddCommGroup E] [Module F2 E] + [AddCommGroup F] [Module F2 F] [Finite E] [Finite F] + +def RestrictionGlobal (d : Nat) (η : ℝ) (f : (E →ₗ[F2] F) → ℝ) : Prop := + ∀ (A : Submodule F2 E) (B : Submodule F2 F), order A B ≤ d → + ∀ T : E →ₗ[F2] F, restrictionEnergy f (embed A B) T ≤ η + +noncomputable def averageTranslates {I : Type*} [Fintype I] + (shifts : I → (E →ₗ[F2] F)) (f : (E →ₗ[F2] F) → ℝ) : (E →ₗ[F2] F) → ℝ := + fun X => 𝔼 i, f (X + shifts i) + +theorem restrictionGlobal_averageTranslates {I : Type*} [Fintype I] [Nonempty I] + (shifts : I → (E →ₗ[F2] F)) (d : Nat) (η : ℝ) (f : (E →ₗ[F2] F) → ℝ) + (hf : RestrictionGlobal d η f) : + RestrictionGlobal d η (averageTranslates shifts f) := by + intro A B hord T + exact restrictionEnergy_average_translate_le f (embed A B) shifts η (hf A B hord) T + +theorem restrictionGlobal_neg (d : Nat) (η : ℝ) (f : (E →ₗ[F2] F) → ℝ) + (hf : RestrictionGlobal d η f) : RestrictionGlobal d η (fun X => -f X) := by + intro A B hord T + simpa only [restrictionEnergy, energy, neg_sq] using hf A B hord T + +theorem restrictionGlobal_weighted_sum {I : Type*} [Fintype I] + (w : I → ℝ) (f : I → (E →ₗ[F2] F) → ℝ) (d : Nat) (η : ℝ) + (hw : ∀ i, 0 ≤ w i) (hf : ∀ i, RestrictionGlobal d η (f i)) : + RestrictionGlobal d ((∑ i, w i) ^ 2 * η) (fun X => ∑ i, w i * f i X) := by + intro A B hord T + exact energy_weighted_sum_le w (fun i n => f i (T + embed A B n)) η hw + (fun i => hf i A B hord T) + +theorem restrictionGlobal_three_terms (d : Nat) (η a b : ℝ) + (f g h : (E →ₗ[F2] F) → ℝ) (ha : 0 ≤ a) (hb : 0 ≤ b) + (hf : RestrictionGlobal d η f) (hg : RestrictionGlobal d η g) + (hh : RestrictionGlobal d η h) : + RestrictionGlobal d ((1 + a + b) ^ 2 * η) + (fun X => f X - a * g X + b * h X) := by + let w : Fin 3 → ℝ := fun i => if i = 0 then 1 else if i = 1 then a else b + let fs : Fin 3 → (E →ₗ[F2] F) → ℝ := fun i => + if i = 0 then f else if i = 1 then (fun X => -g X) else h + have hw : ∀ i, 0 ≤ w i := by + intro i + rcases (show i = 0 ∨ i = 1 ∨ i = 2 by omega) with rfl | rfl | rfl + · simp [w] + · simpa [w] using ha + · simpa [w] using hb + have hfs : ∀ i, RestrictionGlobal d η (fs i) := by + intro i + rcases (show i = 0 ∨ i = 1 ∨ i = 2 by omega) with rfl | rfl | rfl + · simpa [fs] using hf + · simpa [fs] using restrictionGlobal_neg d η g hg + · simpa [fs] using hh + have hs := restrictionGlobal_weighted_sum w fs d η hw hfs + simpa [w, fs, Fin.sum_univ_succ, sub_eq_add_neg, add_assoc] using hs + +noncomputable def quadraticFilter {I : Type*} [Fintype I] + (d : Nat) (shifts : I → (E →ₗ[F2] F)) (f : (E →ₗ[F2] F) → ℝ) : + (E →ₗ[F2] F) → ℝ := fun X => + f X - ((2 : ℝ) ^ d + 2 ^ (d - 1)) * averageTranslates shifts f X + + 2 ^ (2 * d - 1) * averageTranslates shifts (averageTranslates shifts f) X + +theorem restrictionGlobal_quadraticFilter {I : Type*} [Fintype I] [Nonempty I] + (d : Nat) (η : ℝ) (shifts : I → (E →ₗ[F2] F)) + (f : (E →ₗ[F2] F) → ℝ) (hf : RestrictionGlobal d η f) : + RestrictionGlobal d + ((1 + ((2 : ℝ) ^ d + 2 ^ (d - 1)) + 2 ^ (2 * d - 1)) ^ 2 * η) + (quadraticFilter d shifts f) := by + have hg := restrictionGlobal_averageTranslates shifts d η f hf + have hh := restrictionGlobal_averageTranslates shifts d η (averageTranslates shifts f) hg + exact restrictionGlobal_three_terms d η _ _ f _ _ + (add_nonneg (pow_nonneg (by norm_num) _) (pow_nonneg (by norm_num) _)) + (pow_nonneg (by norm_num) _) hf hg hh + +theorem restrictionGlobal_deleted_indicator + (H : (E →ₗ[F2] F) → Bool) (r p q : Nat) (hq : 0 < q) : + RestrictionGlobal r ((p : ℝ) / q) + (fun X => if UniqueGamesTheorem.Fourier.Deletion.remainder (system r) H p q X + then (1 : ℝ) else 0) := by + intro A B hord T + exact remainder_restriction_sq_expect H r p q hq A B hord T + +abbrev LineIndex (v : E) := F × {φ : E →ₗ[F2] F2 // φ v = 1} + +noncomputable instance lineIndexFintype (v : E) : Fintype (LineIndex (F := F) v) := by + classical + letI : Fintype E := Fintype.ofFinite E + letI : Fintype F := Fintype.ofFinite F + letI : Fintype (E →ₗ[F2] F2) := Fintype.ofInjective + (fun φ : E →ₗ[F2] F2 => (φ : E → F2)) DFunLike.coe_injective + exact inferInstance + +def lineShift (v : E) (p : LineIndex (F := F) v) : E →ₗ[F2] F := + p.2.val.smulRight p.1 + +noncomputable def lineAverage (v : E) (f : (E →ₗ[F2] F) → ℝ) : + (E →ₗ[F2] F) → ℝ := averageTranslates (lineShift v) f + +omit [Module F2 F] [Finite F] in +theorem lineIndex_nonempty (v : E) (hv : v ≠ 0) : Nonempty (LineIndex (F := F) v) := by + obtain ⟨φ, hφ⟩ := Module.Projective.exists_dual_eq_one F2 hv + exact ⟨0, φ, hφ⟩ + +theorem restrictionGlobal_lineAverage (v : E) (hv : v ≠ 0) + (d : Nat) (η : ℝ) (f : (E →ₗ[F2] F) → ℝ) (hf : RestrictionGlobal d η f) : + RestrictionGlobal d η (lineAverage v f) := by + let := lineIndex_nonempty (F := F) v hv + exact restrictionGlobal_averageTranslates (lineShift v) d η f hf + +abbrev HyperplaneIndex (ω : F →ₗ[F2] F2) := {a : F // ω a = 1} × (E →ₗ[F2] F2) + +noncomputable instance hyperplaneIndexFintype (ω : F →ₗ[F2] F2) : + Fintype (HyperplaneIndex (E := E) ω) := by + classical + letI : Fintype E := Fintype.ofFinite E + letI : Fintype F := Fintype.ofFinite F + letI : Fintype (E →ₗ[F2] F2) := Fintype.ofInjective + (fun φ : E →ₗ[F2] F2 => (φ : E → F2)) DFunLike.coe_injective + exact inferInstance + +def hyperplaneShift (ω : F →ₗ[F2] F2) (p : HyperplaneIndex (E := E) ω) : E →ₗ[F2] F := + p.2.smulRight p.1.val + +noncomputable def hyperplaneAverage (ω : F →ₗ[F2] F2) + (f : (E →ₗ[F2] F) → ℝ) : (E →ₗ[F2] F) → ℝ := + averageTranslates (hyperplaneShift ω) f + +omit [Finite E] [Finite F] in +theorem hyperplaneIndex_nonempty (ω : F →ₗ[F2] F2) (hω : ω ≠ 0) : + Nonempty (HyperplaneIndex (E := E) ω) := by + classical + have hex : ¬ ∀ a, ω a = 0 := by + intro h + exact hω (LinearMap.ext h) + obtain ⟨a, ha⟩ := not_forall.mp hex + have hone : ω a = 1 := (scalar_cases (ω a)).resolve_left ha + exact ⟨⟨a, hone⟩, 0⟩ + +theorem restrictionGlobal_hyperplaneAverage (ω : F →ₗ[F2] F2) (hω : ω ≠ 0) + (d : Nat) (η : ℝ) (f : (E →ₗ[F2] F) → ℝ) (hf : RestrictionGlobal d η f) : + RestrictionGlobal d η (hyperplaneAverage ω f) := by + let := hyperplaneIndex_nonempty (E := E) ω hω + exact restrictionGlobal_averageTranslates (hyperplaneShift ω) d η f hf + +end BinaryLinear + +end UniqueGamesTheorem.Appendix.Globality + +end + +section + +noncomputable section +open scoped BigOperators +open UniqueGamesTheorem.Integration.BinaryLinear (F2) +open UniqueGamesTheorem.Fourier.MatrixFourier +open UniqueGamesTheorem.Fourier.MatrixRestrictions +open UniqueGamesTheorem.Appendix.LevelInequality +open UniqueGamesTheorem.Appendix.Globality + +namespace UniqueGamesTheorem.Appendix.RankLevelFilter + +attribute [local instance] Classical.propDecidable + +def node : ℕ → ℝ + | 0 => 1 + | n + 1 => node n / 2 + +theorem node_pos (n : ℕ) : 0 < node n := by + induction n with + | zero => norm_num [node] + | succ n ih => exact div_pos ih (by norm_num) + +theorem node_eq_inv_pow (n : ℕ) : node n = ((2 : ℝ) ^ n)⁻¹ := by + induction n with + | zero => simp [node] + | succ n ih => rw [node, ih, pow_succ, mul_inv_rev]; ring + +theorem node_add_le (i k : ℕ) : node (i + k) ≤ node i := by + induction k with + | zero => simp + | succ k ih => + change node (i + k) / 2 ≤ node i + linarith [node_pos (i + k)] + +theorem node_antitone {i j : ℕ} (h : i ≤ j) : node j ≤ node i := by + have he : i + (j - i) = j := by omega + simpa only [he] using node_add_le i (j - i) + +theorem node_le_one (n : ℕ) : node n ≤ 1 := by + simpa [node] using node_add_le 0 n + +theorem node_gap {j d : ℕ} (h : j < d) : + 0 < node j - node d ∧ node d ≤ node j - node d := by + have hm := node_antitone (show j + 1 ≤ d by omega) + change node d ≤ node j / 2 at hm + constructor <;> linarith [node_pos d] + +theorem step_coefficient_bound {j d : ℕ} (h : j < d) : + node j / (node j - node d) + (node j - node d)⁻¹ ≤ (2 : ℝ) ^ (d + 1) := by + have hg := node_gap h + have he : node j / (node j - node d) + (node j - node d)⁻¹ = + (node j + 1) / (node j - node d) := by + simp only [div_eq_mul_inv] + ring + rw [he] + calc + _ ≤ 2 / (node j - node d) := + div_le_div_of_nonneg_right (by linarith [node_le_one j]) hg.1.le + _ ≤ 2 / node d := div_le_div_of_nonneg_left (by norm_num) (node_pos d) hg.2 + _ = (2 : ℝ) ^ (d + 1) := by + rw [node_eq_inv_pow, div_inv_eq_mul, pow_succ] + ring + +def multiplier (d k r : ℕ) : ℝ := + ∏ j ∈ Finset.range k, (node j - node r) / (node j - node d) + +theorem multiplier_succ (d k r : ℕ) : + multiplier d (k + 1) r = + multiplier d k r * ((node k - node r) / (node k - node d)) := by + simp only [multiplier, Finset.prod_range_succ] + +theorem multiplier_target (d k : ℕ) (hk : k ≤ d) : multiplier d k d = 1 := by + unfold multiplier + apply Finset.prod_eq_one + intro j hj + have hjd : j < d := lt_of_lt_of_le (Finset.mem_range.mp hj) hk + exact div_self (ne_of_gt (node_gap hjd).1) + +theorem multiplier_below (d k r : ℕ) (hr : r < k) : multiplier d k r = 0 := by + unfold multiplier + exact Finset.prod_eq_zero_iff.mpr ⟨r, Finset.mem_range.mpr hr, by simp⟩ + +@[instance_reducible] def linearMapFintype {U V : Type*} [AddCommGroup U] [Module F2 U] + [AddCommGroup V] [Module F2 V] [Finite U] [Finite V] : Fintype (U →ₗ[F2] V) := by + classical + letI : Fintype U := Fintype.ofFinite U + letI : Fintype V := Fintype.ofFinite V + exact Fintype.ofInjective (fun φ : U →ₗ[F2] V => (φ : U → V)) DFunLike.coe_injective + +section ActualLinearMaps + +variable {E F : Type*} + [AddCommGroup E] [Module F2 E] [AddCommGroup F] [Module F2 F] + [FiniteDimensional F2 E] [FiniteDimensional F2 F] + +omit [FiniteDimensional F2 E] in +theorem linearNoiseEigenvalue_uniform [Fintype F] (S : F →ₗ[F2] E) : + UniqueGamesTheorem.Fourier.MatrixNoise.linearNoiseEigenvalue + (fun _ : F => (Fintype.card F : ℝ)⁻¹) S = + ((2 : ℝ) ^ Module.finrank F2 S.range)⁻¹ := by + classical + let k := (Finset.univ.filter fun v : F => S v = 0).card + have hs : (∑ v : F, if S v = 0 then (1 : ℝ) else 0) = (k : ℝ) := by + rw [← Finset.sum_filter] + simp [k] + have hc : (k : ℝ) * (2 : ℝ) ^ Module.finrank F2 S.range = + (Fintype.card F : ℝ) := by + have h := congrArg (fun n : ℕ => (n : ℝ)) + (UniqueGamesTheorem.Gadget.LinearKernelCount.zero_event_finset_count_mul_pow_rank S) + simpa only [Nat.cast_mul, Nat.cast_pow, Nat.cast_ofNat] using h + have hn : (Fintype.card F : ℝ) ≠ 0 := Nat.cast_ne_zero.mpr Fintype.card_ne_zero + have hp : (2 : ℝ) ^ Module.finrank F2 S.range ≠ 0 := pow_ne_zero _ two_ne_zero + unfold UniqueGamesTheorem.Fourier.MatrixNoise.linearNoiseEigenvalue + rw [← Finset.mul_sum, hs] + apply mul_right_cancel₀ hp + calc + ((Fintype.card F : ℝ)⁻¹ * (k : ℝ)) * (2 : ℝ) ^ Module.finrank F2 S.range = + (Fintype.card F : ℝ)⁻¹ * ((k : ℝ) * (2 : ℝ) ^ Module.finrank F2 S.range) := + mul_assoc _ _ _ + _ = (Fintype.card F : ℝ)⁻¹ * (Fintype.card F : ℝ) := by rw [hc] + _ = 1 := inv_mul_cancel₀ hn + _ = ((2 : ℝ) ^ Module.finrank F2 S.range)⁻¹ * + (2 : ℝ) ^ Module.finrank F2 S.range := (inv_mul_cancel₀ hp).symm + +variable [Finite E] [Finite F] + +def rankNoise (f : (E →ₗ[F2] F) → ℝ) : (E →ₗ[F2] F) → ℝ := + letI : Fintype F := Fintype.ofFinite F + letI : Fintype (E →ₗ[F2] F2) := linearMapFintype + UniqueGamesTheorem.Fourier.MatrixNoise.linearRealNoiseOperator + (fun _ : F => (Fintype.card F : ℝ)⁻¹) f + +omit [FiniteDimensional F2 E] [FiniteDimensional F2 F] in +theorem rankNoise_eq_average (f : (E →ₗ[F2] F) → ℝ) (X : E →ₗ[F2] F) : + letI : Fintype F := Fintype.ofFinite F + letI : Fintype (E →ₗ[F2] F2) := linearMapFintype + rankNoise f X = 𝔼 v : F, 𝔼 φ : E →ₗ[F2] F2, f (X + φ.smulRight v) := by + classical + dsimp [rankNoise, UniqueGamesTheorem.Fourier.MatrixNoise.linearRealNoiseOperator] + simp only [Fintype.expect_eq_sum_div_card, div_eq_mul_inv] + rw [← Finset.mul_sum] + exact mul_comm _ _ + +omit [FiniteDimensional F2 E] [FiniteDimensional F2 F] in +theorem global_average_family {I : Type*} [Fintype I] [Nonempty I] + (f : I → (E →ₗ[F2] F) → ℝ) (d : ℕ) (η : ℝ) + (hf : ∀ i, RestrictionGlobal d η (f i)) : + RestrictionGlobal d η (fun X => 𝔼 i, f i X) := by + intro A B hord T + exact energy_average_le_of_bound (fun i N => f i (T + embed A B N)) η + (fun i => hf i A B hord T) + +omit [FiniteDimensional F2 E] [FiniteDimensional F2 F] in +theorem rankNoise_global (d : ℕ) (η : ℝ) (f : (E →ₗ[F2] F) → ℝ) + (hf : RestrictionGlobal d η f) : RestrictionGlobal d η (rankNoise f) := by + classical + let : Fintype F := Fintype.ofFinite F + let : Fintype (E →ₗ[F2] F2) := linearMapFintype + have he : rankNoise f = + fun X => 𝔼 v : F, 𝔼 φ : E →ₗ[F2] F2, f (X + φ.smulRight v) := by + funext X + exact rankNoise_eq_average f X + rw [he] + apply global_average_family _ d η + intro v + exact restrictionGlobal_averageTranslates (fun φ : E →ₗ[F2] F2 => φ.smulRight v) + d η f hf + +omit [FiniteDimensional F2 E] in +theorem global_nonneg (d : ℕ) (η : ℝ) (f : (E →ₗ[F2] F) → ℝ) + (hf : RestrictionGlobal d η f) : 0 ≤ η := by + have hord : order (⊥ : Submodule F2 E) (⊤ : Submodule F2 F) ≤ d := by + have hq := (⊤ : Submodule F2 F).finrank_quotient_add_finrank + simp only [finrank_top] at hq + have hz : Module.finrank F2 (F ⧸ (⊤ : Submodule F2 F)) = 0 := by omega + simp [order, hz] + exact (energy_nonnegative _).trans (hf ⊥ ⊤ hord 0) + +omit [FiniteDimensional F2 E] [FiniteDimensional F2 F] in +theorem global_mono_bound {d : ℕ} {η ζ : ℝ} {f : (E →ₗ[F2] F) → ℝ} + (hη : η ≤ ζ) (hf : RestrictionGlobal d η f) : RestrictionGlobal d ζ f := by + intro A B hord T + exact (hf A B hord T).trans hη + +def step (d j : ℕ) (f : (E →ₗ[F2] F) → ℝ) (X : E →ₗ[F2] F) : ℝ := + (node j * f X - rankNoise f X) / (node j - node d) + +omit [FiniteDimensional F2 E] in +theorem step_global (d j : ℕ) (hj : j < d) (η : ℝ) + (f : (E →ₗ[F2] F) → ℝ) (hf : RestrictionGlobal d η f) : + RestrictionGlobal d ((2 : ℝ) ^ (2 * (d + 1)) * η) (step d j f) := by + let a := node j / (node j - node d) + let b := (node j - node d)⁻¹ + have ha : 0 ≤ a := div_nonneg (node_pos j).le (node_gap hj).1.le + have hb : 0 ≤ b := inv_nonneg.mpr (node_gap hj).1.le + let w : Fin 2 → ℝ := fun i => if i = 0 then a else b + let fs : Fin 2 → (E →ₗ[F2] F) → ℝ := fun i => + if i = 0 then f else fun X => -rankNoise f X + have hw : ∀ i, 0 ≤ w i := by + intro i + rcases (show i = 0 ∨ i = 1 by omega) with rfl | rfl + · simpa [w] using ha + · simpa [w] using hb + have hfs : ∀ i, RestrictionGlobal d η (fs i) := by + intro i + rcases (show i = 0 ∨ i = 1 by omega) with rfl | rfl + · simpa [fs] using hf + · simpa [fs] using restrictionGlobal_neg d η (rankNoise f) (rankNoise_global d η f hf) + have hs := restrictionGlobal_weighted_sum w fs d η hw hfs + have he : (fun X => ∑ i : Fin 2, w i * fs i X) = step d j f := by + funext X + simp [w, fs, Fin.sum_univ_succ, step, a, b, div_eq_mul_inv] + ring + have hwSum : (∑ i : Fin 2, w i) = a + b := by simp [w, Fin.sum_univ_succ] + rw [he, hwSum] at hs + apply global_mono_bound _ hs + have hc : a + b ≤ (2 : ℝ) ^ (d + 1) := step_coefficient_bound hj + have hsq : (a + b) ^ 2 ≤ ((2 : ℝ) ^ (d + 1)) ^ 2 := by + nlinarith [mul_nonneg (sub_nonneg.mpr hc) + (show 0 ≤ (2 : ℝ) ^ (d + 1) + (a + b) by positivity)] + have hp : ((2 : ℝ) ^ (d + 1)) ^ 2 = (2 : ℝ) ^ (2 * (d + 1)) := by + rw [← pow_mul] + congr 1 + omega + rw [hp] at hsq + exact mul_le_mul_of_nonneg_right hsq (global_nonneg d η f hf) + +def iterateFilter (d : ℕ) : ℕ → ((E →ₗ[F2] F) → ℝ) → (E →ₗ[F2] F) → ℝ + | 0, f => f + | k + 1, f => step d k (iterateFilter d k f) + +omit [FiniteDimensional F2 E] in +theorem iterateFilter_global (d k : ℕ) (hk : k ≤ d) (η : ℝ) + (f : (E →ₗ[F2] F) → ℝ) (hf : RestrictionGlobal d η f) : + RestrictionGlobal d ((2 : ℝ) ^ (2 * k * (d + 1)) * η) (iterateFilter d k f) := by + induction k with + | zero => simpa [iterateFilter] using hf + | succ k ih => + have hk' : k ≤ d := by omega + have hs := step_global d k (by omega) _ _ (ih hk') + have hex : 2 * (d + 1) + 2 * k * (d + 1) = 2 * (k + 1) * (d + 1) := by ring + simpa only [iterateFilter, ← mul_assoc, ← pow_add, hex] using hs + +variable [Fintype (E →ₗ[F2] F)] [Fintype (F →ₗ[F2] E)] + +theorem rankNoise_coeff (f : (E →ₗ[F2] F) → ℝ) (S : F →ₗ[F2] E) : + linearCoeff (rankNoise f) S = node (frequencyRank S) * linearCoeff f S := by + classical + let : Fintype F := Fintype.ofFinite F + let : Fintype (E →ₗ[F2] F2) := linearMapFintype + rw [rankNoise, UniqueGamesTheorem.Fourier.MatrixNoise.linearRealNoiseOperator_coeff, + linearNoiseEigenvalue_uniform, node_eq_inv_pow] + rfl + +omit [FiniteDimensional F2 E] [FiniteDimensional F2 F] [Finite E] [Finite F] + [Fintype (F →ₗ[F2] E)] in +theorem coefficient_linearCombination (a b : ℝ) (f g : (E →ₗ[F2] F) → ℝ) + (S : F →ₗ[F2] E) : + linearCoeff (fun X => a * f X + b * g X) S = + a * linearCoeff f S + b * linearCoeff g S := by + unfold linearCoeff + simp_rw [add_mul, mul_assoc, Finset.expect_add_distrib, ← Finset.mul_expect] + +theorem step_coeff (d j : ℕ) (f : (E →ₗ[F2] F) → ℝ) (S : F →ₗ[F2] E) : + linearCoeff (step d j f) S = + ((node j - node (frequencyRank S)) / (node j - node d)) * linearCoeff f S := by + have he : step d j f = fun X => + (node j / (node j - node d)) * f X + + (-1 / (node j - node d)) * rankNoise f X := by + funext X + dsimp [step] + ring + rw [he, coefficient_linearCombination, rankNoise_coeff] + simp only [div_eq_mul_inv] + ring + +theorem iterateFilter_coeff (d k : ℕ) (f : (E →ₗ[F2] F) → ℝ) (S : F →ₗ[F2] E) : + linearCoeff (iterateFilter d k f) S = + multiplier d k (frequencyRank S) * linearCoeff f S := by + induction k with + | zero => simp [iterateFilter, multiplier] + | succ k ih => rw [iterateFilter, step_coeff, ih, multiplier_succ]; ring + +theorem iterateFilter_coeff_low (d : ℕ) (f : (E →ₗ[F2] F) → ℝ) + (S : F →ₗ[F2] E) (hS : frequencyRank S ≤ d) : + linearCoeff (iterateFilter d d f) S = + if frequencyRank S = d then linearCoeff f S else 0 := by + rw [iterateFilter_coeff] + by_cases he : frequencyRank S = d + · rw [he, multiplier_target d d le_rfl] + simp + · have hl : frequencyRank S < d := by omega + rw [multiplier_below d d _ hl] + simp [he] + +omit [Finite E] [Finite F] in +theorem rankLevel_eq_projector (d : ℕ) (f : (E →ₗ[F2] F) → ℝ) : + rankLevel d f = Derivatives.spectralProjector (fun Y => frequencyRank Y = d) f := by + apply Derivatives.function_eq_of_linearCoeff_eq + intro Y + rw [linearCoeff_rankLevel, Derivatives.linearCoeff_spectralProjector] + by_cases h : frequencyRank Y = d <;> simp [h] + +theorem filtered_compression_projector (d : ℕ) (f : (E →ₗ[F2] F) → ℝ) + (A : Submodule F2 E) (B : Submodule F2 F) (hord : order A B ≤ d) : + Derivatives.spectralProjector + (fun Y => frequencyRank (Restriction.compressFrequency A B Y) = d - order A B) + (iterateFilter d d f) = Derivatives.hybridProjector A B (rankLevel d f) := by + apply Derivatives.function_eq_of_linearCoeff_eq + intro Y + simp only [Derivatives.hybridProjector, Derivatives.linearCoeff_spectralProjector, + linearCoeff_rankLevel] + have hb := Level.LinearRank.compression_rank_bounds A B Y + have hs := Level.LinearRank.hybrid_rank_loss_iff A B Y + change frequencyRank (Restriction.compressFrequency A B Y) ≤ frequencyRank Y ∧ + frequencyRank Y ≤ frequencyRank (Restriction.compressFrequency A B Y) + + Module.finrank F2 A + Module.finrank F2 (F ⧸ B) at hb + change frequencyRank (Restriction.compressFrequency A B Y) + Module.finrank F2 A + + Module.finrank F2 (F ⧸ B) = frequencyRank Y ↔ LinearIdentities.Hybrid Y A B at hs + have ho : Module.finrank F2 A + Module.finrank F2 (F ⧸ B) ≤ d := hord + by_cases hc : frequencyRank (Restriction.compressFrequency A B Y) = d - order A B + · have hrle : frequencyRank Y ≤ d := by dsimp [order] at hc; omega + rw [ite_eq_left hc, iterateFilter_coeff_low d f Y hrle] + by_cases hr : frequencyRank Y = d + · have hhy : LinearIdentities.Hybrid Y A B := hs.mp (by dsimp [order] at hc; omega) + simp [hr, hhy] + · simp [hr] + · rw [ite_eq_right hc] + by_cases hhy : LinearIdentities.Hybrid Y A B + · rw [ite_eq_left hhy] + by_cases hr : frequencyRank Y = d + · have hl := hs.mpr hhy + have he : frequencyRank (Restriction.compressFrequency A B Y) = d - order A B := by + dsimp [order] + omega + exact (hc he).elim + · simp [hr] + · simp [hhy] + +theorem hybridDerivative_rankLevel_eq_local_projection (d : ℕ) + (f : (E →ₗ[F2] F) → ℝ) (A : Submodule F2 E) (B : Submodule F2 F) + [Fintype (B →ₗ[F2] (E ⧸ A))] (T : E →ₗ[F2] F) (hord : order A B ≤ d) : + Derivatives.hybridDerivative A B T (rankLevel d f) = + rankLevel (d - order A B) (restrict (iterateFilter d d f) A B T) := by + rw [rankLevel_eq_projector (d - order A B) (restrict (iterateFilter d d f) A B T), + Derivatives.spectralProjector_restriction, + filtered_compression_projector d f A B hord] + rfl + +theorem hybridDerivative_rankLevel_energy_le_strong (d : ℕ) (η : ℝ) + (f : (E →ₗ[F2] F) → ℝ) (hf : IsRestrictionGlobal f d η) + (A : Submodule F2 E) (B : Submodule F2 F) (T : E →ₗ[F2] F) + (hord : order A B ≤ d) : + (𝔼 N, Derivatives.hybridDerivative A B T (rankLevel d f) N ^ 2) ≤ + (2 : ℝ) ^ (2 * d * (d + 1)) * η := by + classical + let : Finite (E ⧸ A) := Finite.of_surjective A.mkQ A.mkQ_surjective + let : Fintype (B →ₗ[F2] (E ⧸ A)) := linearMapFintype + have hglobal : RestrictionGlobal d η f := by + intro A' B' horder T' + exact hf A' B' T' horder + have hg := iterateFilter_global d d le_rfl η f hglobal + rw [hybridDerivative_rankLevel_eq_local_projection d f A B T hord] + exact (rankLevel_energy_le _ _).trans (hg A B hord T) + +theorem hybridDerivative_rankLevel_energy_le (d : ℕ) (η : ℝ) + (f : (E →ₗ[F2] F) → ℝ) (hf : IsRestrictionGlobal f d η) + (A : Submodule F2 E) (B : Submodule F2 F) (T : E →ₗ[F2] F) + (hord : order A B ≤ d) : + (𝔼 N, Derivatives.hybridDerivative A B T (rankLevel d f) N ^ 2) ≤ + (2 : ℝ) ^ (10 * d * d) * η := by + have hglobal : RestrictionGlobal d η f := by + intro A' B' horder T' + exact hf A' B' T' horder + have he : 2 * d * (d + 1) ≤ 10 * d * d := by + nlinarith [Nat.le_mul_self d] + exact (hybridDerivative_rankLevel_energy_le_strong d η f hf A B T hord).trans + (mul_le_mul_of_nonneg_right (pow_le_pow_right₀ (by norm_num : (1 : ℝ) ≤ 2) he) + (global_nonneg d η f hglobal)) + +end ActualLinearMaps + +end UniqueGamesTheorem.Appendix.RankLevelFilter + +end + +end + +section + +noncomputable section +open scoped BigOperators +open UniqueGamesTheorem.Integration.BinaryLinear (F2) +open UniqueGamesTheorem.Fourier.MatrixFourier + +namespace UniqueGamesTheorem.Appendix.SelectorEnergy + +variable {E F : Type*} + [AddCommGroup E] [Module F2 E] [AddCommGroup F] [Module F2 F] + [FiniteDimensional F2 E] [FiniteDimensional F2 F] + [Finite E] [Finite F] + [Fintype (E →ₗ[F2] F)] [Fintype (F →ₗ[F2] E)] + +theorem hybridSelectorEnergy_le (d : ℕ) (f : (E →ₗ[F2] F) → ℝ) + (hdegree : ∀ Y, d < Module.finrank F2 Y.range → linearCoeff f Y = 0) : + Derivatives.hybridSelectorEnergy d f ≤ + (2 : ℝ) ^ (3 * d * d) * (𝔼 X, f X ^ 2) := by + classical + unfold Derivatives.hybridSelectorEnergy Derivatives.hybridProjector + apply Derivatives.selector_energy_sum_le + intro Y hY + have hrank : Module.finrank F2 Y.range ≤ d := by + by_contra hn + exact hY (hdegree Y (Nat.lt_of_not_ge hn)) + have hc := HybridCounting.card_hybridIndex_le Y d hrank + have hcount : Derivatives.selectorMultiplicity + (fun s : Derivatives.HybridIndex (E := E) (F := F) d => + fun Y => LinearIdentities.Hybrid Y s.val.1 s.val.2) Y = + Nat.card {s : Derivatives.HybridIndex (E := E) (F := F) d // + LinearIdentities.Hybrid Y s.val.1 s.val.2} := by + simp only [Derivatives.selectorMultiplicity, Nat.card_eq_fintype_card, + Fintype.card_subtype] + rw [hcount] + exact_mod_cast hc + +theorem hybridMomentSum_rankLevel_le (d : ℕ) (η : ℝ) + (f : (E →ₗ[F2] F) → ℝ) (hf : LevelInequality.IsRestrictionGlobal f d η) : + Derivatives.hybridMomentSum d (LevelInequality.rankLevel d f) ≤ + (2 : ℝ) ^ (13 * d * d) * η * (𝔼 X, f X ^ 2) := by + have hglobal : Globality.RestrictionGlobal d η f := by + intro A B hord T + exact hf A B T hord + have hη : 0 ≤ η := RankLevelFilter.global_nonneg d η f hglobal + have hu := Derivatives.hybridMomentSum_le_of_uniform_energy d + (LevelInequality.rankLevel d f) ((2 : ℝ) ^ (10 * d * d) * η) + (fun A B T h => RankLevelFilter.hybridDerivative_rankLevel_energy_le d η f hf A B T h) + have hs := hybridSelectorEnergy_le d (LevelInequality.rankLevel d f) + (fun Y hY => LevelInequality.rankLevel_degree_le d f Y hY) + have hc := LevelInequality.rankLevel_energy_le d f + have hζ : 0 ≤ (2 : ℝ) ^ (10 * d * d) * η := mul_nonneg (by positivity) hη + have hp : (2 : ℝ) ^ (10 * d * d) * (2 : ℝ) ^ (3 * d * d) = + (2 : ℝ) ^ (13 * d * d) := by + rw [← pow_add] + congr 1 + ring + calc + _ ≤ ((2 : ℝ) ^ (10 * d * d) * η) * Derivatives.hybridSelectorEnergy d + (LevelInequality.rankLevel d f) := hu + _ ≤ ((2 : ℝ) ^ (10 * d * d) * η) * ((2 : ℝ) ^ (3 * d * d) * + (𝔼 X, LevelInequality.rankLevel d f X ^ 2)) := + mul_le_mul_of_nonneg_left hs hζ + _ ≤ ((2 : ℝ) ^ (10 * d * d) * η) * ((2 : ℝ) ^ (3 * d * d) * (𝔼 X, f X ^ 2)) := + mul_le_mul_of_nonneg_left (mul_le_mul_of_nonneg_left hc (by positivity)) hζ + _ = ((2 : ℝ) ^ (10 * d * d) * (2 : ℝ) ^ (3 * d * d)) * η * (𝔼 X, f X ^ 2) := by + ring + _ = _ := by rw [hp] + +end UniqueGamesTheorem.Appendix.SelectorEnergy + +end + +end + +section + +noncomputable section +namespace UniqueGamesTheorem.Appendix.LevelTheorem +open scoped BigOperators +open UniqueGamesTheorem.Integration.BinaryLinear (F2) +open UniqueGamesTheorem.Appendix.LevelInequality + +variable {E F : Type*} + [AddCommGroup E] [Module F2 E] [AddCommGroup F] [Module F2 F] + [Finite E] [Finite F] + [Fintype (E →ₗ[F2] F)] [Fintype (F →ₗ[F2] E)] + +section FiniteDimensional +variable [FiniteDimensional F2 E] [FiniteDimensional F2 F] + +theorem rankLevel_fourth_moment_le (d : ℕ) (η : ℝ) + (f : (E →ₗ[F2] F) → ℝ) (hf : IsRestrictionGlobal f d η) : + (𝔼 M, rankLevel d f M^4) ≤ + (2:ℝ)^(113*d*d) * η * (𝔼 M, f M^2) := by + have ha := A5Induction.derivative_inequality d (rankLevel d f) + (DerivativeDegree.degree_rankLevel d f) + have hs := SelectorEnergy.hybridMomentSum_rankLevel_le d η f hf + have hp : (2:ℝ)^(100*d^2) * (2:ℝ)^(13*d*d) = (2:ℝ)^(113*d*d) := by + rw [← pow_add] + congr 1 + ring + calc + _ ≤ (2:ℝ)^(100*d^2) * Derivatives.hybridMomentSum d (rankLevel d f) := ha + _ ≤ (2:ℝ)^(100*d^2) * ((2:ℝ)^(13*d*d) * η * (𝔼 M, f M^2)) := + mul_le_mul_of_nonneg_left hs (by positivity) + _ = ((2:ℝ)^(100*d^2) * (2:ℝ)^(13*d*d)) * η * (𝔼 M, f M^2) := by ring + _ = _ := by rw [hp] + +end FiniteDimensional + +theorem theorem23 : LevelInequality.Theorem23 (E := E) (F := F) := by + let : FiniteDimensional F2 E := Module.Finite.of_finite + let : FiniteDimensional F2 F := Module.Finite.of_finite + intro d _ ρ hρ _ f hf hrestricted + have hglobal : IsRestrictionGlobal f d ρ := + (boolean_global_iff_density f hf d ρ).mpr hrestricted + have hfourth := rankLevel_fourth_moment_le d ρ f hglobal + rw [boolean_squared_norm_eq_density hf] at hfourth + exact rankLevel_bound_of_fourth_moment d f hf ρ hρ.le hfourth + +end UniqueGamesTheorem.Appendix.LevelTheorem + +end + +end + +section + +noncomputable section + +namespace UniqueGamesTheorem.Fourier.MatrixLevelBridge + +open scoped BigOperators Classical +open UniqueGamesTheorem.Fourier.MatrixCharacters UniqueGamesTheorem.Fourier.MatrixFourier +open UniqueGamesTheorem.Fourier.MatrixRestrictions +open UniqueGamesTheorem.Appendix.LevelInequality + +def levelCutoffConstant (r : Nat) (ρ : ℝ) : ℝ := + ∑ d ∈ Finset.range (r + 1), + if d = 0 then ρ else (2 : ℝ) ^ (30 * d * d) * ρ ^ ((1 : ℝ) / 4) + +theorem levelCutoffConstant_nonneg (r : Nat) (ρ : ℝ) (hρ : 0 ≤ ρ) : + 0 ≤ levelCutoffConstant r ρ := by + unfold levelCutoffConstant + apply Finset.sum_nonneg + intro d _ + split_ifs + · exact hρ + · exact mul_nonneg (pow_nonneg (by norm_num : (0 : ℝ) ≤ 2) _) + (Real.rpow_nonneg hρ _) + +theorem sum_rank_le {ι : Type*} [Fintype ι] (rk : ι → Nat) (w : ι → ℝ) (r : Nat) : + (∑ i, if rk i ≤ r then w i else 0) = + ∑ d ∈ Finset.range (r + 1), ∑ i, if rk i = d then w i else 0 := by + calc + _ = ∑ i, ∑ d ∈ Finset.range (r + 1), if rk i = d then w i else 0 := by + apply Finset.sum_congr rfl + intro i _ + simp [Finset.mem_range] + _ = _ := Finset.sum_comm + +section Unrestricted + +variable {E F : Type*} [AddCommGroup E] [Module F2 E] + [AddCommGroup F] [Module F2 F] + +def unrestrictedEquiv : + Parameter (⊥ : Submodule F2 E) (⊤ : Submodule F2 F) ≃ (E →ₗ[F2] F) := + Equiv.ofBijective (embed (⊥ : Submodule F2 E) (⊤ : Submodule F2 F)) + ⟨embed_injective ⊥ ⊤, fun X => + (exists_embed_iff (⊥ : Submodule F2 E) (⊤ : Submodule F2 F) X).mpr + ⟨bot_le, le_top⟩⟩ + +theorem order_bot_top : order (⊥ : Submodule F2 E) (⊤ : Submodule F2 F) = 0 := by + simpa [order] using + (Module.finrank_eq_zero_of_subsingleton F2 (F ⧸ (⊤ : Submodule F2 F))) + +theorem expect_unrestricted [Finite E] [Finite F] [Fintype (E →ₗ[F2] F)] + (f : (E →ₗ[F2] F) → ℝ) : + (𝔼 A : Parameter (⊥ : Submodule F2 E) (⊤ : Submodule F2 F), + restrict f ⊥ ⊤ 0 A) = 𝔼 X : E →ₗ[F2] F, f X := by + apply Finset.expect_equiv (unrestrictedEquiv (E := E) (F := F)) + · intro A + simp + · intro A _ + change f (0 + embed ⊥ ⊤ A) = f (embed ⊥ ⊤ A) + rw [zero_add] + +end Unrestricted + +section ActualLinearMaps + +variable {E F : Type*} +variable [AddCommGroup E] [Module F2 E] [AddCommGroup F] [Module F2 F] +variable [FiniteDimensional F2 E] [FiniteDimensional F2 F] +variable [Fintype (E →ₗ[F2] F)] [Fintype (F →ₗ[F2] E)] + +def rankCutoffEnergy (r : Nat) (f : (E →ₗ[F2] F) → ℝ) : ℝ := + ∑ S with frequencyRank S ≤ r, linearCoeff f S ^ 2 + +omit [FiniteDimensional F2 E] [FiniteDimensional F2 F] in +theorem rankCutoffEnergy_eq_sum_exactRankMass (r : Nat) (f : (E →ₗ[F2] F) → ℝ) : + rankCutoffEnergy r f = + ∑ d ∈ Finset.range (r + 1), ∑ S with frequencyRank S = d, linearCoeff f S ^ 2 := by + simpa only [rankCutoffEnergy, Finset.sum_filter] using + sum_rank_le frequencyRank (fun S => linearCoeff f S ^ 2) r + +theorem rankCutoffEnergy_eq_sum_rankLevel (r : Nat) (f : (E →ₗ[F2] F) → ℝ) : + rankCutoffEnergy r f = + ∑ d ∈ Finset.range (r + 1), (𝔼 X, rankLevel d f X ^ 2) := by + simp only [rankLevel_energy, rankCutoffEnergy_eq_sum_exactRankMass] + +omit [FiniteDimensional F2 E] [Fintype (E →ₗ[F2] F)] [Fintype (F →ₗ[F2] E)] in +theorem frequencyRank_eq_zero_iff (S : F →ₗ[F2] E) : frequencyRank S = 0 ↔ S = 0 := by + rw [frequencyRank, Submodule.finrank_eq_zero, LinearMap.range_eq_bot] + +omit [FiniteDimensional F2 E] [FiniteDimensional F2 F] [Fintype (F →ₗ[F2] E)] in +theorem linearCoeff_zero_frequency (f : (E →ₗ[F2] F) → ℝ) : + linearCoeff f (0 : F →ₗ[F2] E) = 𝔼 X, f X := by + simp [linearCoeff, linearTraceCharacter_zero] + +theorem rankZero_energy (f : (E →ₗ[F2] F) → ℝ) : + (𝔼 X, rankLevel 0 f X ^ 2) = (𝔼 X, f X) ^ 2 := by + rw [rankLevel_energy] + simp [Finset.sum_filter, frequencyRank_eq_zero_iff, linearCoeff_zero_frequency] + +variable [Finite E] [Finite F] + +omit [FiniteDimensional F2 E] [FiniteDimensional F2 F] [Fintype (F →ₗ[F2] E)] in + +theorem fullSecondMoment_le_of_global (f : (E →ₗ[F2] F) → ℝ) (r : Nat) (ρ : ℝ) + (hg : IsRestrictionGlobal f r ρ) : (𝔼 X, f X ^ 2) ≤ ρ := by + rw [← expect_unrestricted (fun X => f X ^ 2)] + exact hg ⊥ ⊤ 0 (by rw [order_bot_top]; exact Nat.zero_le r) + +omit [FiniteDimensional F2 E] [FiniteDimensional F2 F] [Fintype (F →ₗ[F2] E)] in +theorem fullMean_le_of_boolean_global (f : (E →ₗ[F2] F) → ℝ) (r : Nat) (ρ : ℝ) + (hf : IsBoolean f) (hg : IsRestrictionGlobal f r ρ) : (𝔼 X, f X) ≤ ρ := by + rw [← boolean_squared_norm_eq_density hf] + exact fullSecondMoment_le_of_global f r ρ hg + +omit [FiniteDimensional F2 E] [FiniteDimensional F2 F] + [Fintype (E →ₗ[F2] F)] [Fintype (F →ₗ[F2] E)] in +theorem remainder_isRestrictionGlobal_of_le + (H : (E →ₗ[F2] F) → Bool) (r d p q : Nat) (hq : 0 < q) (hdr : d ≤ r) : + IsRestrictionGlobal + (fun X => if Deletion.remainder (system r) H p q X then (1 : ℝ) else 0) + d ((p : ℝ) / q) := by + intro W C' X horder + exact remainder_restriction_sq_expect H r p q hq W C' (horder.trans hdr) X + +theorem rankCutoffEnergy_le_of_theorem23 (h23 : Theorem23 (E := E) (F := F)) + (f : (E →ₗ[F2] F) → ℝ) (r : Nat) (ρ : ℝ) (hρ : 0 < ρ) (hρ1 : ρ < 1) + (hf : IsBoolean f) (hg : IsRestrictionGlobal f r ρ) : + rankCutoffEnergy r f ≤ levelCutoffConstant r ρ * (𝔼 X, f X ^ 2) := by + let μ := 𝔼 X, f X ^ 2 + have hμ : 0 ≤ μ := Finset.expect_nonneg (fun X _ => sq_nonneg (f X)) + have hμρ : μ ≤ ρ := fullSecondMoment_le_of_global f r ρ hg + have hzero : (𝔼 X, rankLevel 0 f X ^ 2) ≤ ρ * μ := by + rw [rankZero_energy, ← boolean_squared_norm_eq_density hf, pow_two] + exact mul_le_mul_of_nonneg_right hμρ hμ + rw [rankCutoffEnergy_eq_sum_rankLevel] + calc + _ ≤ ∑ d ∈ Finset.range (r + 1), + (if d = 0 then ρ else (2 : ℝ) ^ (30 * d * d) * ρ ^ ((1 : ℝ) / 4)) * μ := by + apply Finset.sum_le_sum + intro d hd + by_cases hd0 : d = 0 + · subst d + simpa using hzero + · have hdr : d ≤ r := Nat.lt_succ_iff.mp (Finset.mem_range.mp hd) + have hgd : IsRestrictionGlobal f d ρ := by + intro A B T horder + exact hg A B T (horder.trans hdr) + have hdensity := (boolean_global_iff_density f hf d ρ).mp hgd + have hpositive := h23 d (Nat.pos_of_ne_zero hd0) ρ hρ hρ1 f hf hdensity + simpa only [ite_eq_right hd0] using hpositive + _ = levelCutoffConstant r ρ * μ := by + simp only [levelCutoffConstant, Finset.sum_mul] + +theorem remainder_rankCutoff_le (h23 : Theorem23 (E := E) (F := F)) + (H : (E →ₗ[F2] F) → Bool) (r p q : Nat) (hq : 0 < q) + (hρ : (0 : ℝ) < (p : ℝ) / q) (hρ1 : (p : ℝ) / q < 1) : + (∑ S : F →ₗ[F2] E, if Module.finrank F2 (LinearMap.range S) ≤ r then + linearCoeff (fun X => if Deletion.remainder (system r) H p q X + then (1 : ℝ) else 0) S ^ 2 else 0) ≤ + levelCutoffConstant r ((p : ℝ) / q) * + (𝔼 X, (if Deletion.remainder (system r) H p q X then (1 : ℝ) else 0) ^ 2) := by + let f : (E →ₗ[F2] F) → ℝ := + fun X => if Deletion.remainder (system r) H p q X then (1 : ℝ) else 0 + have hf : IsBoolean f := by + intro X + dsimp only [f] + split + · exact Or.inr rfl + · exact Or.inl rfl + have hg : IsRestrictionGlobal f r ((p : ℝ) / q) := + remainder_isRestrictionGlobal_of_le H r r p q hq le_rfl + rw [← Finset.sum_filter] + exact rankCutoffEnergy_le_of_theorem23 h23 f r ((p : ℝ) / q) hρ hρ1 hf hg + +end ActualLinearMaps + +end UniqueGamesTheorem.Fourier.MatrixLevelBridge + +end + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/GoodAdviceEventsLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/GoodAdviceEventsLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..33e192773f14bee525f72655664b95badfc8f81e --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/GoodAdviceEventsLemmas.lean @@ -0,0 +1,425 @@ +import OAI.Computability.PerfectCompleteness.Foundations.ManyGoodRowsLemmas +import OAI.Computability.PerfectCompleteness.Foundations.TupleIndexEmitterLemmas +import OAI.Computability.PerfectCompleteness.Reduction.CompletionSoundness +import OAI.Computability.PerfectCompleteness.Sampling.GoodRowSampling + +namespace OAI + + +namespace PerfectCompleteness.GoodAdviceEvents + +noncomputable section + +open scoped BigOperators Classical +open UniqueGamesTheorem.Fourier.MatrixCharacters (F2) +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) +open PerfectCompleteness.ManyGoodRows PerfectCompleteness.GoodRowSampling + +attribute [local instance] linearMapFintype + +section FiniteLaws + +variable {Ω P : Type*} [Fintype Ω] [Fintype P] [Nonempty Ω] + +omit [Fintype P] [Nonempty Ω] in +theorem adapted_fiber_probability (μ : FiniteDistribution Ω) (p : Ω → P) + (event : P → Ω → Bool) (z : P) : + UsefulMark.lowerFiberMass μ p (fun x => event (p x) x) z = + μ.probability (fun x => decide (p x = z) && event z x) := by + unfold UsefulMark.lowerFiberMass + congr 1 + funext x + by_cases hx : p x = z <;> simp [hx] + +omit [Fintype P] in +theorem adapted_uniform_fiber_probability (p : Ω → P) + (event : P → Ω → Bool) (z : P) [Nonempty {x : Ω // p x = z}] : + UsefulMark.lowerFiberMass (FiniteDistribution.uniform Ω) p + (fun x => event (p x) x) z = + (FiniteDistribution.uniform Ω).probability (fun x => decide (p x = z)) * + (FiniteDistribution.uniform {x : Ω // p x = z}).probability + (fun x => event z x.val) := by + rw [adapted_fiber_probability] + rw [FiniteDistribution.probability_inter_eq_mul_conditional _ _ _ + (UniformConditioning.uniform_probability_pos (fun x => p x = z))] + rw [UniformConditioning.probability_condition_uniform] + +omit [Fintype P] [Nonempty Ω] in +theorem adapted_fiber_probability_zero (μ : FiniteDistribution Ω) (p : Ω → P) + (event : P → Ω → Bool) (z : P) (h : ∀ x, event z x = false) : + UsefulMark.lowerFiberMass μ p (fun x => event (p x) x) z = 0 := by + rw [adapted_fiber_probability] + simp only [h, Bool.and_false, FiniteDistribution.probability_false] + +theorem uniform_probability_eq_expect (event : Ω → Bool) : + (FiniteDistribution.uniform Ω).probability event = + 𝔼 x : Ω, if event x then (1 : ℝ) else 0 := by + have h : (FiniteDistribution.uniform Ω).probability event = + (FiniteDistribution.uniform Ω).expectation + (fun x => if event x then (1 : ℝ) else 0) := by + simp only [FiniteDistribution.probability, FiniteDistribution.expectation, + mul_ite, mul_one, mul_zero] + rw [h, FiniteDistribution.expectation_uniform, Fintype.expect_eq_sum_div_card] + +omit [Nonempty Ω] in +theorem product_probability {Γ : Type*} [Fintype Γ] + (μ : FiniteDistribution Ω) (ν : FiniteDistribution Γ) (event : Ω × Γ → Bool) : + (μ.product ν).probability event = + μ.expectation (fun x => ν.probability (fun y => event (x, y))) := by + simp only [FiniteDistribution.probability, FiniteDistribution.expectation, + FiniteDistribution.product, Fintype.sum_prod_type, Finset.mul_sum, mul_ite, mul_zero] + +end FiniteLaws + +variable {E F Y : Type*} + [AddCommGroup E] [Module F2 E] [AddCommGroup F] [Module F2 F] + [FiniteDimensional F2 E] [FiniteDimensional F2 F] + [Fintype E] [Fintype F] [Fintype Y] + +def selectedColumn (f : (E →ₗ[F2] F) → Option Y) (r : Nat) (ρ : ℝ) + (A : RowMap F r) (U : E →ₗ[F2] (Fin r → F2)) (X : E →ₗ[F2] F) : Bool := + if h : GoodRow f r ρ A U then + let w := selectWitness f r ρ A U h + decide (X.domRestrict w.columnSpace = w.base.domRestrict w.columnSpace) + else false + +def selectedAgreement (f : (E →ₗ[F2] F) → Option Y) (r : Nat) (ρ : ℝ) + (A : RowMap F r) (U : E →ₗ[F2] (Fin r → F2)) (X : E →ₗ[F2] F) : Bool := + if h : GoodRow f r ρ A U then + let w := selectWitness f r ρ A U h + decide (X.domRestrict w.columnSpace = w.base.domRestrict w.columnSpace ∧ + f X = some w.value) + else false + +def J (f : (E →ₗ[F2] F) → Option Y) (r : Nat) (ρ : ℝ) + (sample : RowMap F r × (E →ₗ[F2] F)) : Bool := + selectedColumn f r ρ sample.1 (sample.1.comp sample.2) sample.2 + +def I (f : (E →ₗ[F2] F) → Option Y) (r : Nat) (ρ : ℝ) + (sample : RowMap F r × (E →ₗ[F2] F)) : Bool := + selectedAgreement f r ρ sample.1 (sample.1.comp sample.2) sample.2 + +def law (E F : Type*) [AddCommGroup E] [Module F2 E] + [AddCommGroup F] [Module F2 F] [Fintype E] [Fintype F] (r : Nat) : + FiniteDistribution (RowMap F r × (E →ₗ[F2] F)) := + (FiniteDistribution.uniform (RowMap F r)).product + (FiniteDistribution.uniform (E →ₗ[F2] F)) + +omit [FiniteDimensional F2 E] [FiniteDimensional F2 F] [Fintype Y] in +theorem I_implies_J (f : (E →ₗ[F2] F) → Option Y) (r : Nat) (ρ : ℝ) + (sample : RowMap F r × (E →ₗ[F2] F)) (hI : I f r ρ sample = true) : + J f r ρ sample = true := by + unfold I selectedAgreement at hI + unfold J selectedColumn + by_cases h : GoodRow f r ρ sample.1 (sample.1.comp sample.2) + · simp only [dite_eq_left h] at hI ⊢ + exact decide_eq_true_eq.mpr ((decide_eq_true_eq.mp hI).1) + · simp [h] at hI + +omit [FiniteDimensional F2 E] [FiniteDimensional F2 F] [Fintype Y] in +theorem witness_agreement_probability {f : (E →ₗ[F2] F) → Option Y} + {r : Nat} {ρ : ℝ} {A : RowMap F r} {U : E →ₗ[F2] (Fin r → F2)} + (w : Witness f r ρ A U) : + letI : Nonempty (RowFiber A U) := witness_rowFiber_nonempty w + ρ * (FiniteDistribution.uniform (RowFiber A U)).probability + (fun X => decide (X.val.domRestrict w.columnSpace = + w.base.domRestrict w.columnSpace)) ≤ + (FiniteDistribution.uniform (RowFiber A U)).probability + (fun X => decide (X.val.domRestrict w.columnSpace = + w.base.domRestrict w.columnSpace ∧ f X.val = some w.value)) := by + let : Nonempty (RowFiber A U) := witness_rowFiber_nonempty w + let S₀ := MatrixSlice.Slice (⊥ : Submodule F2 E) (LinearMap.ker A) w.base + let S := MatrixSlice.Slice w.columnSpace (LinearMap.ker A) w.base + let column : S₀ → Prop := + fun X => X.val.domRestrict w.columnSpace = w.base.domRestrict w.columnSpace + let matchValue : S₀ → Bool := fun X => decide (f X.val = some w.value) + let : Nonempty {X : S₀ // column X} := + ⟨⟨⟨w.base, rfl, rfl⟩, rfl⟩⟩ + have column_decide : (fun X => decide (column X)) = + (fun X => @decide (column X) (Classical.propDecidable _)) := by + funext sample + exact decide_eq_decide.mpr Iff.rfl + have positive : 0 < (FiniteDistribution.uniform S₀).probability + (fun X => decide (column X)) := by + rw [column_decide] + exact UniformConditioning.uniform_probability_pos column + have density : + ρ ≤ (FiniteDistribution.uniform S).probability + (fun X => decide (f X.val = some w.value)) := by + calc + ρ ≤ (𝔼 X : S, PartialTableInverse.indicator f w.value X.val) := w.density + _ = (FiniteDistribution.uniform S).probability + (fun X => decide (f X.val = some w.value)) := by + rw [uniform_probability_eq_expect] + simp only [PartialTableInverse.indicator, decide_eq_true_eq] + have conditional : + ρ ≤ ((FiniteDistribution.uniform S₀).condition + (fun X => decide (column X)) positive).probability matchValue := by + simp only [column_decide] + rw [UniformConditioning.probability_condition_uniform] + have he := UniformConditioning.uniform_probability_equiv + (SliceMass.columnEventEquivSlice w.columnSpace (LinearMap.ker A) w.base) + (fun X : S => decide (f X.val = some w.value)) + convert density.trans_eq he.symm using 1 + congr! + have rowSlice : + ρ * (FiniteDistribution.uniform S₀).probability + (fun X => decide (column X)) ≤ + (FiniteDistribution.uniform S₀).probability + (fun X => decide (column X) && matchValue X) := by + rw [FiniteDistribution.probability_inter_eq_mul_conditional _ _ _ positive] + simpa only [mul_comm] using mul_le_mul_of_nonneg_left conditional + ((FiniteDistribution.uniform S₀).probability_nonnegative + (fun X => decide (column X))) + have hcolumn := UniformConditioning.uniform_probability_equiv + (rowFiberEquiv A U w.base w.row_value) + (fun X : RowFiber A U => decide (X.val.domRestrict w.columnSpace = + w.base.domRestrict w.columnSpace)) + have hmatch := UniformConditioning.uniform_probability_equiv + (rowFiberEquiv A U w.base w.row_value) + (fun X : RowFiber A U => + decide (X.val.domRestrict w.columnSpace = w.base.domRestrict w.columnSpace) && + decide (f X.val = some w.value)) + have hand : (fun X : RowFiber A U => + decide (X.val.domRestrict w.columnSpace = w.base.domRestrict w.columnSpace ∧ + f X.val = some w.value)) = + (fun X : RowFiber A U => + decide (X.val.domRestrict w.columnSpace = w.base.domRestrict w.columnSpace) && + decide (f X.val = some w.value)) := by + funext X + by_cases hcolumn : X.val.domRestrict w.columnSpace = w.base.domRestrict w.columnSpace <;> + by_cases hvalue : f X.val = some w.value <;> simp [hcolumn, hvalue] + rw [hand] + rw [← hcolumn, ← hmatch] + exact rowSlice + +omit [Fintype Y] in +theorem J_probability_fixed_row (f : (E →ₗ[F2] F) → Option Y) + (r : Nat) (ρ : ℝ) (A : RowMap F r) : + (1 / (2 : ℝ) ^ (r * Module.finrank F2 F)) * + (FiniteDistribution.uniform (E →ₗ[F2] F)).probability + (fun X => decide (GoodRow f r ρ A (A.comp X))) ≤ + (FiniteDistribution.uniform (E →ₗ[F2] F)).probability + (fun X => J f r ρ (A, X)) := by + let μ := FiniteDistribution.uniform (E →ₗ[F2] F) + let p : (E →ₗ[F2] F) → (E →ₗ[F2] (Fin r → F2)) := fun X => A.comp X + rw [UsefulMark.probability_eq_sum_fibers μ p, + UsefulMark.probability_eq_sum_fibers μ p, Finset.mul_sum] + apply Finset.sum_le_sum + intro U _ + by_cases hgood : GoodRow f r ρ A U + · let w := selectWitness f r ρ A U hgood + let : Nonempty (RowFiber A U) := witness_rowFiber_nonempty w + have hG : UsefulMark.lowerFiberMass μ p + (fun X => decide (GoodRow f r ρ A (A.comp X))) U = + μ.probability (fun X => @decide (A.comp X = U) (Classical.propDecidable _)) := by + rw [adapted_fiber_probability μ p + (fun V _X => decide (GoodRow f r ρ A V)) U] + simp only [hgood, decide_true, Bool.and_true] + rfl + have hJ : UsefulMark.lowerFiberMass μ p (fun X => J f r ρ (A, X)) U = + μ.probability (fun X => @decide (A.comp X = U) (Classical.propDecidable _)) * + (FiniteDistribution.uniform (RowFiber A U)).probability + (fun X => decide (X.val.domRestrict w.columnSpace = + w.base.domRestrict w.columnSpace)) := by + change UsefulMark.lowerFiberMass (FiniteDistribution.uniform (E →ₗ[F2] F)) p + (fun X => selectedColumn f r ρ A (p X) X) U = _ + refine (adapted_uniform_fiber_probability p (selectedColumn f r ρ A) U).trans ?_ + simp only [selectedColumn, dite_eq_left hgood] + congr! + rw [hG, hJ] + simpa only [mul_comm] using mul_le_mul_of_nonneg_left + (witness_column_probability w) (μ.probability_nonnegative _) + · have hG : UsefulMark.lowerFiberMass μ p + (fun X => decide (GoodRow f r ρ A (A.comp X))) U = 0 := + adapted_fiber_probability_zero μ p + (fun V _X => decide (GoodRow f r ρ A V)) U (by intro X; simp [hgood]) + rw [hG, mul_zero] + exact μ.probability_nonnegative _ + +omit [FiniteDimensional F2 E] [FiniteDimensional F2 F] [Fintype Y] in +theorem I_probability_fixed_row (f : (E →ₗ[F2] F) → Option Y) + (r : Nat) (ρ : ℝ) (A : RowMap F r) : + ρ * (FiniteDistribution.uniform (E →ₗ[F2] F)).probability + (fun X => J f r ρ (A, X)) ≤ + (FiniteDistribution.uniform (E →ₗ[F2] F)).probability + (fun X => I f r ρ (A, X)) := by + let μ := FiniteDistribution.uniform (E →ₗ[F2] F) + let p : (E →ₗ[F2] F) → (E →ₗ[F2] (Fin r → F2)) := fun X => A.comp X + rw [UsefulMark.probability_eq_sum_fibers μ p, + UsefulMark.probability_eq_sum_fibers μ p, Finset.mul_sum] + apply Finset.sum_le_sum + intro U _ + by_cases hgood : GoodRow f r ρ A U + · let w := selectWitness f r ρ A U hgood + let : Nonempty (RowFiber A U) := witness_rowFiber_nonempty w + have hJ : UsefulMark.lowerFiberMass μ p (fun X => J f r ρ (A, X)) U = + μ.probability (fun X => @decide (A.comp X = U) (Classical.propDecidable _)) * + (FiniteDistribution.uniform (RowFiber A U)).probability + (fun X => decide (X.val.domRestrict w.columnSpace = + w.base.domRestrict w.columnSpace)) := by + change UsefulMark.lowerFiberMass (FiniteDistribution.uniform (E →ₗ[F2] F)) p + (fun X => selectedColumn f r ρ A (p X) X) U = _ + refine (adapted_uniform_fiber_probability p (selectedColumn f r ρ A) U).trans ?_ + simp only [selectedColumn, dite_eq_left hgood] + congr! + have hI : UsefulMark.lowerFiberMass μ p (fun X => I f r ρ (A, X)) U = + μ.probability (fun X => @decide (A.comp X = U) (Classical.propDecidable _)) * + (FiniteDistribution.uniform (RowFiber A U)).probability + (fun X => decide (X.val.domRestrict w.columnSpace = + w.base.domRestrict w.columnSpace ∧ f X.val = some w.value)) := by + change UsefulMark.lowerFiberMass (FiniteDistribution.uniform (E →ₗ[F2] F)) p + (fun X => selectedAgreement f r ρ A (p X) X) U = _ + refine (adapted_uniform_fiber_probability p (selectedAgreement f r ρ A) U).trans ?_ + simp only [selectedAgreement, dite_eq_left hgood] + congr! + rw [hJ, hI] + simpa only [mul_left_comm] using mul_le_mul_of_nonneg_left + (witness_agreement_probability w) (μ.probability_nonnegative _) + · have hJ : UsefulMark.lowerFiberMass μ p (fun X => J f r ρ (A, X)) U = 0 := + adapted_fiber_probability_zero μ p (selectedColumn f r ρ A) U + (by intro X; simp [selectedColumn, hgood]) + rw [hJ, mul_zero] + exact μ.probability_nonnegative _ + +omit [FiniteDimensional F2 E] [FiniteDimensional F2 F] [Fintype Y] in +theorem good_probability_eq_adviceMass (f : (E →ₗ[F2] F) → Option Y) + (r : Nat) (ρ : ℝ) : + (law E F r).probability + (fun s => decide (GoodRow f r ρ s.1 (s.1.comp s.2))) = adviceMass f r ρ := by + simp only [law, product_probability, uniform_probability_eq_expect, + FiniteDistribution.expectation_uniform, Fintype.expect_eq_sum_div_card, + adviceMass, decide_eq_true_eq] + +omit [Fintype Y] in +theorem J_probability_ge (f : (E →ₗ[F2] F) → Option Y) (r : Nat) (ρ : ℝ) : + adviceMass f r ρ / (2 : ℝ) ^ (r * Module.finrank F2 F) ≤ + (law E F r).probability (J f r ρ) := by + calc + _ = (1 / (2 : ℝ) ^ (r * Module.finrank F2 F)) * + (law E F r).probability + (fun s => decide (GoodRow f r ρ s.1 (s.1.comp s.2))) := by + rw [good_probability_eq_adviceMass] + ring + _ ≤ _ := by + simp only [law, product_probability, FiniteDistribution.expectation, Finset.mul_sum] + apply Finset.sum_le_sum + intro A _ + simpa only [mul_left_comm] using mul_le_mul_of_nonneg_left + (J_probability_fixed_row f r ρ A) + ((FiniteDistribution.uniform (RowMap F r)).nonnegative A) + +omit [FiniteDimensional F2 E] [FiniteDimensional F2 F] [Fintype Y] in +theorem I_probability_ge (f : (E →ₗ[F2] F) → Option Y) (r : Nat) (ρ : ℝ) : + ρ * (law E F r).probability (J f r ρ) ≤ + (law E F r).probability (I f r ρ) := by + simp only [law, product_probability, FiniteDistribution.expectation, Finset.mul_sum] + apply Finset.sum_le_sum + intro A _ + simpa only [mul_left_comm] using mul_le_mul_of_nonneg_left + (I_probability_fixed_row f r ρ A) + ((FiniteDistribution.uniform (RowMap F r)).nonnegative A) + +end +end PerfectCompleteness.GoodAdviceEvents + + + +namespace PerfectCompleteness.GoodAdviceFamily + +noncomputable section + +open scoped BigOperators Classical +open UniqueGamesTheorem.Fourier.MatrixCharacters (F2) +open UniqueGamesTheorem.Fourier.MatrixLevelBridge +open UniqueGamesTheorem.Appendix.RankLevelFilter +open UniqueGamesTheorem.Foundations.Games +open PerfectCompleteness.ManyGoodRows + +attribute [local instance] linearMapFintype + +variable {P : Type*} [Fintype P] {E Y : P → Type*} {F : Type*} + [AddCommGroup F] [Module F2 F] [FiniteDimensional F2 F] [Fintype F] + [∀ p, AddCommGroup (E p)] [∀ p, Module F2 (E p)] + [∀ p, FiniteDimensional F2 (E p)] [∀ p, Fintype (E p)] [∀ p, Fintype (Y p)] + +abbrev Sample (r : Nat) := Σ p : P, RowMap F r × (E p →ₗ[F2] F) + +def law (μ : FiniteDistribution P) (r : Nat) : + FiniteDistribution (Sample (E := E) (F := F) r) := + CompletionSoundness.sigmaLaw μ (fun p => GoodAdviceEvents.law (E p) F r) + +def J (f : (p : P) → (E p →ₗ[F2] F) → Option (Y p)) + (r : Nat) (ρ : ℝ) (sample : Sample (E := E) (F := F) r) : Bool := + GoodAdviceEvents.J (f sample.1) r ρ sample.2 + +def I (f : (p : P) → (E p →ₗ[F2] F) → Option (Y p)) + (r : Nat) (ρ : ℝ) (sample : Sample (E := E) (F := F) r) : Bool := + GoodAdviceEvents.I (f sample.1) r ρ sample.2 + +omit [FiniteDimensional F2 F] [∀ p, FiniteDimensional F2 (E p)] [∀ p, Fintype (Y p)] in +theorem J_probability_eq_mean (μ : FiniteDistribution P) + (f : (p : P) → (E p →ₗ[F2] F) → Option (Y p)) (r : Nat) (ρ : ℝ) : + (law (E := E) (F := F) μ r).probability (J f r ρ) = + μ.expectation (fun p => + (GoodAdviceEvents.law (E p) F r).probability (GoodAdviceEvents.J (f p) r ρ)) := by + exact CompletionSoundness.sigmaLaw_probability μ + (fun p => GoodAdviceEvents.law (E p) F r) (J f r ρ) + +omit [FiniteDimensional F2 F] [∀ p, FiniteDimensional F2 (E p)] [∀ p, Fintype (Y p)] in +theorem I_probability_eq_mean (μ : FiniteDistribution P) + (f : (p : P) → (E p →ₗ[F2] F) → Option (Y p)) (r : Nat) (ρ : ℝ) : + (law (E := E) (F := F) μ r).probability (I f r ρ) = + μ.expectation (fun p => + (GoodAdviceEvents.law (E p) F r).probability (GoodAdviceEvents.I (f p) r ρ)) := by + exact CompletionSoundness.sigmaLaw_probability μ + (fun p => GoodAdviceEvents.law (E p) F r) (I f r ρ) + +omit [∀ p, Fintype (Y p)] in +theorem J_probability_ge_mean_advice (μ : FiniteDistribution P) + (f : (p : P) → (E p →ₗ[F2] F) → Option (Y p)) (r : Nat) (ρ : ℝ) : + μ.expectation (fun p => adviceMass (f p) r ρ) / + (2 : ℝ) ^ (r * Module.finrank F2 F) ≤ + (law (E := E) (F := F) μ r).probability (J f r ρ) := by + rw [J_probability_eq_mean] + simp only [FiniteDistribution.expectation, div_eq_mul_inv, Finset.sum_mul] + apply Finset.sum_le_sum + intro p _ + simpa only [div_eq_mul_inv, mul_assoc] using + mul_le_mul_of_nonneg_left (GoodAdviceEvents.J_probability_ge (f p) r ρ) + (μ.nonnegative p) + +omit [FiniteDimensional F2 F] [∀ p, FiniteDimensional F2 (E p)] [∀ p, Fintype (Y p)] in +theorem I_probability_ge (μ : FiniteDistribution P) + (f : (p : P) → (E p →ₗ[F2] F) → Option (Y p)) (r : Nat) (ρ : ℝ) : + ρ * (law (E := E) (F := F) μ r).probability (J f r ρ) ≤ + (law (E := E) (F := F) μ r).probability (I f r ρ) := by + rw [J_probability_eq_mean, I_probability_eq_mean] + simp only [FiniteDistribution.expectation, Finset.mul_sum] + apply Finset.sum_le_sum + intro p _ + simpa only [mul_left_comm] using mul_le_mul_of_nonneg_left + (GoodAdviceEvents.I_probability_ge (f p) r ρ) (μ.nonnegative p) + +theorem J_probability_ge [Nontrivial F] (μ : FiniteDistribution P) + (f : (p : P) → (E p →ₗ[F2] F) → Option (Y p)) + (r : Nat) (ρ η : ℝ) (hη : 0 < η) (hρ : 0 < ρ) (hρ1 : ρ < 1) + (hconstants : levelCutoffConstant r ρ + node (r + 1) < η / 2) + (hmean : 2 * η ≤ μ.expectation (fun p => PartialTableInverse.nonzeroAgreement (f p))) : + (η ^ 2 / 4) / ((2 : ℝ) ^ (r * Module.finrank F2 F)) ^ 2 ≤ + (law (E := E) (F := F) μ r).probability (J f r ρ) := by + calc + _ = ((η ^ 2 / 4) / (2 : ℝ) ^ (r * Module.finrank F2 F)) / + (2 : ℝ) ^ (r * Module.finrank F2 F) := by ring + _ ≤ μ.expectation (fun p => adviceMass (f p) r ρ) / + (2 : ℝ) ^ (r * Module.finrank F2 F) := + div_le_div_of_nonneg_right + (FamilyGoodRows.mean_adviceMass_ge μ f r ρ η hη hρ hρ1 hconstants hmean) + (by positivity) + _ ≤ _ := J_probability_ge_mean_advice μ f r ρ + +end +end PerfectCompleteness.GoodAdviceFamily + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/HeterogeneousAdviceFamily.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/HeterogeneousAdviceFamily.lean new file mode 100644 index 0000000000000000000000000000000000000000..b753dbddd2cbdd32241cc4db59badb4be511ca1c --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/HeterogeneousAdviceFamily.lean @@ -0,0 +1,156 @@ +import OAI.Computability.PerfectCompleteness.Foundations.GoodAdviceEventsLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.HeterogeneousAdviceFamily + +noncomputable section + +open scoped BigOperators Classical +open UniqueGamesTheorem.Fourier.MatrixCharacters (F2) +open UniqueGamesTheorem.Fourier.MatrixLevelBridge +open UniqueGamesTheorem.Appendix.RankLevelFilter +open UniqueGamesTheorem.Foundations.Games +open PerfectCompleteness.ManyGoodRows + +attribute [local instance] linearMapFintype + +variable {P : Type*} [Fintype P] {E F Y : P → Type*} + [∀ p, AddCommGroup (E p)] [∀ p, Module F2 (E p)] + [∀ p, FiniteDimensional F2 (E p)] [∀ p, Fintype (E p)] + [∀ p, AddCommGroup (F p)] [∀ p, Module F2 (F p)] + [∀ p, FiniteDimensional F2 (F p)] [∀ p, Fintype (F p)] + [∀ p, Fintype (Y p)] + +abbrev Sample (r : Nat) := Σ p : P, RowMap (F p) r × (E p →ₗ[F2] F p) + +def law (μ : FiniteDistribution P) (r : Nat) : + FiniteDistribution (Sample (E := E) (F := F) r) := + CompletionSoundness.sigmaLaw μ (fun p => GoodAdviceEvents.law (E p) (F p) r) + +def J (f : (p : P) → (E p →ₗ[F2] F p) → Option (Y p)) + (r : Nat) (ρ : ℝ) (sample : Sample (E := E) (F := F) r) : Bool := + GoodAdviceEvents.J (f sample.1) r ρ sample.2 + +def I (f : (p : P) → (E p →ₗ[F2] F p) → Option (Y p)) + (r : Nat) (ρ : ℝ) (sample : Sample (E := E) (F := F) r) : Bool := + GoodAdviceEvents.I (f sample.1) r ρ sample.2 + +omit [∀ p, FiniteDimensional F2 (E p)] [∀ p, FiniteDimensional F2 (F p)] + [∀ p, Fintype (Y p)] in +theorem J_probability_eq_mean (μ : FiniteDistribution P) + (f : (p : P) → (E p →ₗ[F2] F p) → Option (Y p)) (r : Nat) (ρ : ℝ) : + (law (E := E) (F := F) μ r).probability (J f r ρ) = + μ.expectation (fun p => + (GoodAdviceEvents.law (E p) (F p) r).probability (GoodAdviceEvents.J (f p) r ρ)) := + CompletionSoundness.sigmaLaw_probability μ + (fun p => GoodAdviceEvents.law (E p) (F p) r) (J f r ρ) + +omit [∀ p, FiniteDimensional F2 (E p)] [∀ p, FiniteDimensional F2 (F p)] + [∀ p, Fintype (Y p)] in +theorem I_probability_eq_mean (μ : FiniteDistribution P) + (f : (p : P) → (E p →ₗ[F2] F p) → Option (Y p)) (r : Nat) (ρ : ℝ) : + (law (E := E) (F := F) μ r).probability (I f r ρ) = + μ.expectation (fun p => + (GoodAdviceEvents.law (E p) (F p) r).probability (GoodAdviceEvents.I (f p) r ρ)) := + CompletionSoundness.sigmaLaw_probability μ + (fun p => GoodAdviceEvents.law (E p) (F p) r) (I f r ρ) + +private theorem div_pow_le {a : ℝ} (ha : 0 ≤ a) {i j : Nat} (hij : i ≤ j) : + a / (2 : ℝ) ^ j ≤ a / (2 : ℝ) ^ i := by + simpa only [one_div, div_eq_mul_inv, one_mul] using + mul_le_mul_of_nonneg_left + (one_div_pow_le_one_div_pow_of_le (by norm_num : (1 : ℝ) ≤ 2) hij) ha + +omit [∀ p, Fintype (Y p)] in +theorem J_probability_ge_mean_advice (μ : FiniteDistribution P) + (f : (p : P) → (E p →ₗ[F2] F p) → Option (Y p)) (r ℓ : Nat) + (hdim : ∀ p, Module.finrank F2 (F p) ≤ ℓ) (ρ : ℝ) : + μ.expectation (fun p => adviceMass (f p) r ρ) / (2 : ℝ) ^ (r * ℓ) ≤ + (law (E := E) (F := F) μ r).probability (J f r ρ) := by + have hpoint (p : P) : + adviceMass (f p) r ρ / (2 : ℝ) ^ (r * ℓ) ≤ + (GoodAdviceEvents.law (E p) (F p) r).probability (GoodAdviceEvents.J (f p) r ρ) := + (div_pow_le (FamilyGoodRows.adviceMass_nonneg (f p) r ρ) + (Nat.mul_le_mul_left r (hdim p))).trans (GoodAdviceEvents.J_probability_ge (f p) r ρ) + rw [J_probability_eq_mean] + simp only [FiniteDistribution.expectation, div_eq_mul_inv, Finset.sum_mul] + apply Finset.sum_le_sum + intro p _ + simpa only [div_eq_mul_inv, mul_assoc] using + mul_le_mul_of_nonneg_left (hpoint p) (μ.nonnegative p) + +omit [∀ p, FiniteDimensional F2 (E p)] [∀ p, FiniteDimensional F2 (F p)] + [∀ p, Fintype (Y p)] in +theorem I_probability_ge (μ : FiniteDistribution P) + (f : (p : P) → (E p →ₗ[F2] F p) → Option (Y p)) (r : Nat) (ρ : ℝ) : + ρ * (law (E := E) (F := F) μ r).probability (J f r ρ) ≤ + (law (E := E) (F := F) μ r).probability (I f r ρ) := by + rw [J_probability_eq_mean, I_probability_eq_mean] + simp only [FiniteDistribution.expectation, Finset.mul_sum] + apply Finset.sum_le_sum + intro p _ + simpa only [mul_left_comm] using mul_le_mul_of_nonneg_left + (GoodAdviceEvents.I_probability_ge (f p) r ρ) (μ.nonnegative p) + +variable [∀ p, Nontrivial (F p)] + +theorem mean_adviceMass_ge (μ : FiniteDistribution P) + (f : (p : P) → (E p →ₗ[F2] F p) → Option (Y p)) (r ℓ : Nat) + (hdim : ∀ p, Module.finrank F2 (F p) ≤ ℓ) + (ρ η : ℝ) (hη : 0 < η) (hρ : 0 < ρ) (hρ1 : ρ < 1) + (hconstants : levelCutoffConstant r ρ + node (r + 1) < η / 2) + (hmean : 2 * η ≤ μ.expectation (fun p => PartialTableInverse.nonzeroAgreement (f p))) : + (η ^ 2 / 4) / (2 : ℝ) ^ (r * ℓ) ≤ + μ.expectation (fun p => adviceMass (f p) r ρ) := by + let c : ℝ := (η / 4) / (2 : ℝ) ^ (r * ℓ) + have hc : 0 ≤ c := + div_nonneg (div_nonneg hη.le (by norm_num : (0 : ℝ) ≤ 4)) (by positivity) + have hmass : η ≤ μ.probability + (fun p => decide (η ≤ PartialTableInverse.nonzeroAgreement (f p))) := + FamilyGoodRows.threshold_probability_ge μ + (fun p => PartialTableInverse.nonzeroAgreement (f p)) η hη.le + (fun p => FamilyGoodRows.nonzeroAgreement_le_one (f p)) hmean + have hweighted : + μ.probability (fun p => decide (η ≤ PartialTableInverse.nonzeroAgreement (f p))) * c ≤ + μ.expectation (fun p => adviceMass (f p) r ρ) := by + apply FamilyGoodRows.probability_mul_le_expectation μ + (fun p => η ≤ PartialTableInverse.nonzeroAgreement (f p)) + (fun p => adviceMass (f p) r ρ) c + · intro p + exact FamilyGoodRows.adviceMass_nonneg (f p) r ρ + · intro p hp + exact (div_pow_le (div_nonneg hη.le (by norm_num : (0 : ℝ) ≤ 4)) + (Nat.mul_le_mul_left r (hdim p))).trans + (ManyGoodRows.adviceMass_ge r ρ η hρ hρ1 hconstants (f p) hp) + calc + (η ^ 2 / 4) / (2 : ℝ) ^ (r * ℓ) = η * c := by + dsimp [c] + ring + _ ≤ μ.probability (fun p => decide (η ≤ PartialTableInverse.nonzeroAgreement (f p))) * c := + mul_le_mul_of_nonneg_right hmass hc + _ ≤ μ.expectation (fun p => adviceMass (f p) r ρ) := hweighted + +theorem J_probability_ge (μ : FiniteDistribution P) + (f : (p : P) → (E p →ₗ[F2] F p) → Option (Y p)) (r ℓ : Nat) + (hdim : ∀ p, Module.finrank F2 (F p) ≤ ℓ) + (ρ η : ℝ) (hη : 0 < η) (hρ : 0 < ρ) (hρ1 : ρ < 1) + (hconstants : levelCutoffConstant r ρ + node (r + 1) < η / 2) + (hmean : 2 * η ≤ μ.expectation (fun p => PartialTableInverse.nonzeroAgreement (f p))) : + (η ^ 2 / 4) / ((2 : ℝ) ^ (r * ℓ)) ^ 2 ≤ + (law (E := E) (F := F) μ r).probability (J f r ρ) := by + calc + _ = ((η ^ 2 / 4) / (2 : ℝ) ^ (r * ℓ)) / (2 : ℝ) ^ (r * ℓ) := by ring + _ ≤ μ.expectation (fun p => adviceMass (f p) r ρ) / (2 : ℝ) ^ (r * ℓ) := + div_le_div_of_nonneg_right + (mean_adviceMass_ge μ f r ℓ hdim ρ η hη hρ hρ1 hconstants hmean) (by positivity) + _ ≤ _ := J_probability_ge_mean_advice μ f r ℓ hdim ρ + +end +end PerfectCompleteness.HeterogeneousAdviceFamily + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/HeterogeneousPairAdvice.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/HeterogeneousPairAdvice.lean new file mode 100644 index 0000000000000000000000000000000000000000..f9d81496078f84a353e4711c80ee6aea06ea7ee6 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/HeterogeneousPairAdvice.lean @@ -0,0 +1,186 @@ +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalAdviceExperimentLemmas +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalPairCoarse +import OAI.Computability.PerfectCompleteness.Sampling.CandidateCoupling + +namespace OAI + +section + +namespace PerfectCompleteness.HeterogeneousPairAdvice + +noncomputable section + +open scoped BigOperators Classical +open TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype + +private theorem append_totalVariation {X : Type*} [Fintype X] + {Y : X → Type*} [∀ x, Fintype (Y x)] + (P Q : FiniteDistribution X) (kernel : (x : X) → FiniteDistribution (Y x)) : + (CompletionSoundness.sigmaLaw P kernel).totalVariation + (CompletionSoundness.sigmaLaw Q kernel) = P.totalVariation Q := by + change (∑ z : Σ x, Y x, + |P.weight z.1 * (kernel z.1).weight z.2 - + Q.weight z.1 * (kernel z.1).weight z.2|) / 2 = + (∑ x, |P.weight x - Q.weight x|) / 2 + congr 1 + rw [Fintype.sum_sigma] + apply Finset.sum_congr rfl + intro x _ + simp only [← sub_mul, abs_mul, abs_of_nonneg ((kernel x).nonnegative _), + ← Finset.mul_sum, (kernel x).normalized, mul_one] + +variable {branch rows : Nat → Nat} {n t : Nat} {O : Type*} [Fintype O] + {Ω : O → Type*} [∀ o, Fintype (Ω o)] + (S : (o : O) → HierarchicalAdviceExperiment.Experiment branch rows n t (Ω o)) + +local instance backgroundFintype (o : O) : + Fintype (HierarchicalAdviceExperiment.Background (S o)) := + HierarchicalAdviceExperiment.backgroundFintype (S o) + +local instance rowSpaceFintype (o : O) : + Fintype (NodeEmbedding.RowSpace (S o).slots (S o).upper) := + HierarchicalPairCoarse.rowSpaceFintype (S o) + +local instance coarseFintype (o : O) : + Fintype (HierarchicalAdviceExperiment.Coarse (S o)) := + HierarchicalAdviceFamily.coarseFintype S o + +local instance inputFintype (o : O) + (background : HierarchicalAdviceExperiment.Background (S o)) : + Fintype (HierarchicalAdviceExperiment.Input (S o) background) := + HierarchicalAdviceExperiment.inputFintype (S o) background + +local instance inputFiniteDimensional (o : O) + (background : HierarchicalAdviceExperiment.Background (S o)) : + FiniteDimensional F2 (HierarchicalAdviceExperiment.Input (S o) background) := + HierarchicalAdviceExperiment.inputFiniteDimensional (S o) background + +abbrev PairSample := Σ o : O, HierarchicalPairCoarse.PairRecord (S o) + +abbrev AdviceSample (r : Nat) := + Σ z : PairSample S, HierarchicalAdviceExperiment.Advice (S z.1) r + +def appendLaw (P : FiniteDistribution (PairSample S)) (r : Nat) : + FiniteDistribution (AdviceSample S r) := + CompletionSoundness.sigmaLaw P + (fun z => HierarchicalAdviceExperiment.adviceLaw (S z.1) r) + +def observe (r : Nat) (z : AdviceSample S r) : HierarchicalAdviceFamily.Observation S r := + ⟨z.1.1, HierarchicalPairCoarse.observe (S z.1.1) r (z.2, z.1.2)⟩ + +def observedLaw (P : FiniteDistribution (PairSample S)) (r : Nat) : + FiniteDistribution (HierarchicalAdviceFamily.Observation S r) := + (appendLaw S P r).pushforward (observe S r) + +def referencePairLaw (outer : FiniteDistribution O) + (backgrounds : (o : O) → + FiniteDistribution (HierarchicalAdviceExperiment.Background (S o))) + (hrows : ∀ o, 0 < rows (Nodes.height (S o).upper)) : + FiniteDistribution (PairSample S) := + CompletionSoundness.sigmaLaw outer (fun o => + HierarchicalAgreementMean.referenceLaw (S o).slots (S o).upper (backgrounds o) (hrows o)) + +theorem observed_sigmaLaw (outer : FiniteDistribution O) + (P : (o : O) → FiniteDistribution (HierarchicalPairCoarse.PairRecord (S o))) + (r : Nat) : + observedLaw S (CompletionSoundness.sigmaLaw outer P) r = + CompletionSoundness.sigmaLaw outer (fun o => + ((HierarchicalAdviceExperiment.adviceLaw (S o) r).product (P o)).pushforward + (HierarchicalPairCoarse.observe (S o) r)) := by + apply SigmaObservation.eq_of_probability_eq + intro event + rw [observedLaw, FiniteDistribution.probability_pushforward, appendLaw, + CompletionSoundness.sigmaLaw_probability, CandidateCoupling.expectation_sigmaLaw, + CompletionSoundness.sigmaLaw_probability] + apply FiniteDistribution.expectation_congr + intro o + rw [FiniteDistribution.probability_pushforward, UsefulAdvice.product_probability_advice_first] + rfl + +theorem reference_observe_sigmaLaw (outer : FiniteDistribution O) + (backgrounds : (o : O) → + FiniteDistribution (HierarchicalAdviceExperiment.Background (S o))) + (r : Nat) : + (HierarchicalAdviceFamily.referenceLaw S outer backgrounds r).pushforward + (HierarchicalAdviceFamily.referenceObserve S r) = + CompletionSoundness.sigmaLaw outer (fun o => + (HierarchicalAdviceExperiment.referenceLaw (S o) (backgrounds o) r).pushforward + (HierarchicalAdviceExperiment.referenceObserve (S o) r)) := by + apply SigmaObservation.eq_of_probability_eq + intro event + rw [FiniteDistribution.probability_pushforward, + HierarchicalAdviceFamily.referenceLaw, HeterogeneousAdviceFamily.law, + CompletionSoundness.sigmaLaw_probability, HierarchicalAdviceFamily.backgroundLaw, + CandidateCoupling.expectation_sigmaLaw, CompletionSoundness.sigmaLaw_probability] + apply FiniteDistribution.expectation_congr + intro o + rw [FiniteDistribution.probability_pushforward, HierarchicalAdviceExperiment.referenceLaw, + GoodAdviceFamily.law, CompletionSoundness.sigmaLaw_probability] + rfl + +theorem reference_observe_law (outer : FiniteDistribution O) + (backgrounds : (o : O) → + FiniteDistribution (HierarchicalAdviceExperiment.Background (S o))) + (hrows : ∀ o, 0 < rows (Nodes.height (S o).upper)) (r : Nat) : + observedLaw S (referencePairLaw S outer backgrounds hrows) r = + (HierarchicalAdviceFamily.referenceLaw S outer backgrounds r).pushforward + (HierarchicalAdviceFamily.referenceObserve S r) := by + rw [referencePairLaw, observed_sigmaLaw] + simpa only [HierarchicalPairCoarse.reference_observe_law] using + (reference_observe_sigmaLaw S outer backgrounds r).symm + +theorem appendLaw_totalVariation (P Q : FiniteDistribution (PairSample S)) (r : Nat) : + (appendLaw S P r).totalVariation (appendLaw S Q r) = P.totalVariation Q := + append_totalVariation P Q (fun z => HierarchicalAdviceExperiment.adviceLaw (S z.1) r) + +theorem observed_totalVariation_le (P : FiniteDistribution (PairSample S)) + (outer : FiniteDistribution O) + (backgrounds : (o : O) → + FiniteDistribution (HierarchicalAdviceExperiment.Background (S o))) + (hrows : ∀ o, 0 < rows (Nodes.height (S o).upper)) (r : Nat) : + (observedLaw S P r).totalVariation + ((HierarchicalAdviceFamily.referenceLaw S outer backgrounds r).pushforward + (HierarchicalAdviceFamily.referenceObserve S r)) ≤ + P.totalVariation (referencePairLaw S outer backgrounds hrows) := by + rw [← reference_observe_law S outer backgrounds hrows r] + exact (DensityVariation.variation_pushforward_le (appendLaw S P r) + (appendLaw S (referencePairLaw S outer backgrounds hrows) r) (observe S r)).trans_eq + (appendLaw_totalVariation S P (referencePairLaw S outer backgrounds hrows) r) + +theorem observed_totalVariation_le_of_bound (P : FiniteDistribution (PairSample S)) + (outer : FiniteDistribution O) + (backgrounds : (o : O) → + FiniteDistribution (HierarchicalAdviceExperiment.Background (S o))) + (hrows : ∀ o, 0 < rows (Nodes.height (S o).upper)) (r : Nat) + {error : ℝ} (herror : P.totalVariation (referencePairLaw S outer backgrounds hrows) ≤ error) : + (observedLaw S P r).totalVariation + ((HierarchicalAdviceFamily.referenceLaw S outer backgrounds r).pushforward + (HierarchicalAdviceFamily.referenceObserve S r)) ≤ error := + (observed_totalVariation_le S P outer backgrounds hrows r).trans herror + +theorem original_totalVariation_le_of_observed + (P : FiniteDistribution (PairSample S)) (outer : FiniteDistribution O) + (backgrounds : (o : O) → + FiniteDistribution (HierarchicalAdviceExperiment.Background (S o))) + (hrows : ∀ o, 0 < rows (Nodes.height (S o).upper)) (r : Nat) + (hactual : observedLaw S P r = + (HierarchicalAdviceFamily.originalLaw S outer r).pushforward + (HierarchicalAdviceFamily.observe S r)) : + ((HierarchicalAdviceFamily.originalLaw S outer r).pushforward + (HierarchicalAdviceFamily.observe S r)).totalVariation + ((HierarchicalAdviceFamily.referenceLaw S outer backgrounds r).pushforward + (HierarchicalAdviceFamily.referenceObserve S r)) ≤ + P.totalVariation (referencePairLaw S outer backgrounds hrows) := by + rw [← hactual] + exact observed_totalVariation_le S P outer backgrounds hrows r + +end +end PerfectCompleteness.HeterogeneousPairAdvice + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalAdviceExperimentLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalAdviceExperimentLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..36d2342476f15655f933da33e2592edd38a4a1d7 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalAdviceExperimentLemmas.lean @@ -0,0 +1,601 @@ +import OAI.Computability.PerfectCompleteness.Algebra.TensorBucketEvaluationLemmas +import OAI.Computability.PerfectCompleteness.Foundations.DependentPredictionDifferenceLemmas +import OAI.Computability.PerfectCompleteness.Foundations.GoodAdviceEventsLemmas +import OAI.Computability.PerfectCompleteness.Foundations.HeterogeneousAdviceFamily +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalPrediction +import OAI.Computability.PerfectCompleteness.Foundations.TupleIndexEmitterLemmas +import OAI.Computability.PerfectCompleteness.Machines.OwnInputReferenceLemmas + +namespace OAI + + +namespace PerfectCompleteness.HierarchicalAdviceExperiment + +noncomputable section + +open scoped Classical +open TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Fourier.MatrixLevelBridge +open UniqueGamesTheorem.Appendix.RankLevelFilter + +attribute [local instance] linearMapFintype + +structure Experiment (branch rows : Nat → Nat) (n t : Nat) (Ω : Type*) [Fintype Ω] where + slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot + upper : Nodes branch n + lowerLevel : Nat + arrays : Ω → Arrays slots rows + lowerNode : Ω → Nodes branch n + separate : ∀ x, upper ≠ lowerNode x + direction : ∀ x, Block rows (lowerNode x) + original : FiniteDistribution Ω + strategy : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t) + +variable {branch rows : Nat → Nat} {n t : Nat} {Ω : Type*} [Fintype Ω] + (S : Experiment branch rows n t Ω) + +abbrev Background := HierarchicalMatrixTable.Background (rows := rows) S.slots S.upper + +local instance backgroundFintype : Fintype (Background S) := Fintype.ofFinite _ + +abbrev Input (background : Background S) := + Module.Dual F2 (NodeEmbedding.RowSpace S.slots S.upper ⧸ + HierarchicalFrozenTables.knownRows S.slots S.upper S.lowerLevel background) + +local instance inputFintype : (b : Background S) → Fintype (Input S b) := + fun _ => linearMapFintype + +local instance inputFiniteDimensional : + (b : Background S) → FiniteDimensional F2 (Input S b) := + fun _ => inferInstance + +abbrev Value := Block rows S.upper × HierarchicalMatrixTable.SideOutput (rows := rows) S.upper + +local instance valueFintype : Fintype (Value S) := Fintype.ofFinite _ + +abbrev Advice (r : Nat) := ManyGoodRows.RowMap (Block rows S.upper) r +abbrev Coarse := HierarchicalUsefulness.Coarse (rows := rows) S.slots S.upper S.lowerLevel +abbrev ReferenceSample (r : Nat) := + GoodAdviceFamily.Sample (E := Input S) (F := Block rows S.upper) r + +def background (x : Ω) : Background S := + HierarchicalMatrixTable.backgroundOf S.slots S.upper (S.arrays x) + +def matrix (x : Ω) : HierarchicalMatrixTable.Matrix (rows := rows) S.slots S.upper := + NodeEmbedding.matrix (S.arrays x) S.upper + +def coarse (x : Ω) : Coarse S := + HierarchicalUsefulness.observe S.slots S.upper S.lowerLevel (S.arrays x) + +def lowerEvent (x : Ω) : Bool := + decide (HierarchicalPrediction.LowerAccepts S.slots S.upper (background S x) + S.strategy (S.lowerNode x) (S.direction x) (matrix S x)) + +def table (κ : ℝ) (b : Background S) : + (Input S b →ₗ[F2] Block rows S.upper) → Option (Value S) := + HierarchicalUsefulness.table S.slots S.upper S.lowerLevel S.original S.arrays + (lowerEvent S) κ S.strategy b + +def J (κ : ℝ) (r : Nat) (ρ : ℝ) (z : Coarse S × Advice S r) : Bool := + GoodAdviceEvents.J (table S κ z.1.1) r ρ (z.2, z.1.2) + +def I (κ : ℝ) (r : Nat) (ρ : ℝ) (z : Coarse S × Advice S r) : Bool := + GoodAdviceEvents.I (table S κ z.1.1) r ρ (z.2, z.1.2) + +def adviceLaw (r : Nat) : FiniteDistribution (Advice S r) := + FiniteDistribution.uniform _ + +def originalLaw (r : Nat) : FiniteDistribution (Ω × Advice S r) := + S.original.product (adviceLaw S r) + +def observe (r : Nat) (x : Ω × Advice S r) : Coarse S × Advice S r := + (coarse S x.1, x.2) + +def referenceLaw (backgroundLaw : FiniteDistribution (Background S)) (r : Nat) : + FiniteDistribution (ReferenceSample S r) := + GoodAdviceFamily.law backgroundLaw r + +def referenceObserve (r : Nat) (x : ReferenceSample S r) : Coarse S × Advice S r := + (⟨x.1, x.2.2⟩, x.2.1) + +def prediction (κ : ℝ) (r : Nat) (ρ : ℝ) (x : Ω × Advice S r) : Bool := + HierarchicalPrediction.prediction S.slots S.upper S.lowerLevel (background S x.1) + S.strategy (S.lowerNode x.1) (S.separate x.1) (S.direction x.1) + S.original S.arrays (lowerEvent S) κ r ρ x.2 (matrix S x.1) + +theorem I_implies_mark (κ : ℝ) (r : Nat) (ρ : ℝ) (z : Coarse S) (A : Advice S r) + (hI : I S κ r ρ (z, A) = true) : + UsefulMark.useful S.original (coarse S) (lowerEvent S) κ z = true := by + obtain ⟨y, _, hy⟩ := HierarchicalPrediction.selectedValue_of_I + (table S κ z.1) r ρ A z.2 hI + have hsome := congrArg Option.isSome hy + change (HierarchicalUsefulness.table S.slots S.upper S.lowerLevel S.original S.arrays + (lowerEvent S) κ S.strategy z.1 z.2).isSome = true at hsome + rw [HierarchicalUsefulness.table_isSome] at hsome + exact hsome + +theorem lower_I_implies_prediction (κ : ℝ) (r : Nat) (ρ : ℝ) + (x : Ω) (A : Advice S r) (hL : lowerEvent S x = true) + (hI : I S κ r ρ (coarse S x, A) = true) : + prediction S κ r ρ (x, A) = true := by + exact HierarchicalPrediction.lower_accepts_predicts S.slots S.upper S.lowerLevel + (background S x) S.strategy (S.lowerNode x) (S.separate x) (S.direction x) + S.original S.arrays (lowerEvent S) κ r ρ A (matrix S x) + (of_decide_eq_true hL) (by + simpa only [I, table, coarse, HierarchicalUsefulness.observe, background, matrix, + HierarchicalPrediction.quotientMatrix, inputFintype] using! hI) + +theorem prediction_implies_J (κ : ℝ) (r : Nat) (ρ : ℝ) + (x : Ω × Advice S r) (hp : prediction S κ r ρ x = true) : + J S κ r ρ (observe S r x) = true := by + simpa only [J, table, observe, coarse, HierarchicalUsefulness.observe, background, matrix, + HierarchicalPrediction.quotientMatrix, inputFintype] using! (Bool.and_eq_true_iff.mp hp).1 + +theorem reference_J_mass_ge (κ : ℝ) + (backgroundLaw : FiniteDistribution (Background S)) + (hrows : 0 < rows (Nodes.height S.upper)) + (r : Nat) (ρ η : ℝ) (hη : 0 < η) (hρ : 0 < ρ) (hρ1 : ρ < 1) + (hconstants : levelCutoffConstant r ρ + node (r + 1) < η / 2) + (hmean : 2 * η ≤ backgroundLaw.expectation (fun b => + PartialTableInverse.nonzeroAgreement (table S κ b))) : + (η ^ 2 / 4) / ((2 : ℝ) ^ (r * rows (Nodes.height S.upper))) ^ 2 ≤ + (referenceLaw S backgroundLaw r).probability + (fun x => J S κ r ρ (referenceObserve S r x)) := by + let : Nonempty (Fin (rows (Nodes.height S.upper))) := ⟨⟨0, hrows⟩⟩ + have h := GoodAdviceFamily.J_probability_ge backgroundLaw (table S κ) + r ρ η hη hρ hρ1 hconstants hmean + have hevent : GoodAdviceFamily.J (table S κ) r ρ = + (fun x : ReferenceSample S r => J S κ r ρ (referenceObserve S r x)) := by + funext x + rfl + rw [hevent] at h + simpa only [referenceLaw, Block, Module.finrank_fin_fun] using h + +theorem prediction_difference (κ : ℝ) (hκ : 0 ≤ κ) + (backgroundLaw : FiniteDistribution (Background S)) + (hrows : 0 < rows (Nodes.height S.upper)) + (r : Nat) (ρ η v : ℝ) (hη : 0 < η) (hρ : 0 < ρ) (hρ1 : ρ < 1) + (hconstants : levelCutoffConstant r ρ + node (r + 1) < η / 2) + (hmean : 2 * η ≤ backgroundLaw.expectation (fun b => + PartialTableInverse.nonzeroAgreement (table S κ b))) + (hv : 0 ≤ v) + (hsmall : v ≤ ρ * ((η ^ 2 / 4) / + ((2 : ℝ) ^ (r * rows (Nodes.height S.upper))) ^ 2) / 16) + (hvariation : ((originalLaw S r).pushforward (observe S r)).totalVariation + ((referenceLaw S backgroundLaw r).pushforward (referenceObserve S r)) ≤ v) : + κ * ρ * ((η ^ 2 / 4) / ((2 : ℝ) ^ (r * rows (Nodes.height S.upper))) ^ 2) / 4 ≤ + (originalLaw S r).probability (prediction S κ r ρ) - + (κ * ρ / 4) * (originalLaw S r).probability + (fun x => J S κ r ρ (observe S r x)) := by + apply PredictionDifference.of_original_usefulness S.original (adviceLaw S r) + (referenceLaw S backgroundLaw r) (coarse S) (referenceObserve S r) + (lowerEvent S) (I S κ r ρ) (J S κ r ρ) (prediction S κ r ρ) + κ ρ ((η ^ 2 / 4) / ((2 : ℝ) ^ (r * rows (Nodes.height S.upper))) ^ 2) + v hκ hρ.le hρ1.le (by positivity) hv hsmall + · exact I_implies_mark S κ r ρ + · exact lower_I_implies_prediction S κ r ρ + · exact hvariation + · exact reference_J_mass_ge S κ backgroundLaw hrows r ρ η hη hρ hρ1 hconstants hmean + · exact GoodAdviceFamily.I_probability_ge backgroundLaw (table S κ) r ρ + +theorem prediction_difference_le_good_mass {R : Type*} [Fintype R] + (κ : ℝ) (hκ : 0 ≤ κ) (r : Nat) (ρ : ℝ) (hρ : 0 ≤ ρ) + (record : Ω × Advice S r → R) : + (originalLaw S r).probability (prediction S κ r ρ) - + (κ * ρ / 4) * (originalLaw S r).probability + (fun x => J S κ r ρ (observe S r x)) ≤ + (originalLaw S r).probability (fun x => J S κ r ρ (observe S r x) && + PositiveFiberMass.goodRecord (originalLaw S r) record + (fun y => J S κ r ρ (observe S r y)) (prediction S κ r ρ) + (κ * ρ / 4) (record x)) := by + have hevent : (fun x => J S κ r ρ (observe S r x) && prediction S κ r ρ x) = + prediction S κ r ρ := by + funext x + by_cases hp : prediction S κ r ρ x = true + · simp only [hp, prediction_implies_J S κ r ρ x hp, Bool.true_and] + · have hp' : prediction S κ r ρ x = false := Bool.eq_false_iff.mpr hp + simp only [hp', Bool.and_false] + have h := PositiveFiberMass.difference_le_good_mass (originalLaw S r) record + (fun x => J S κ r ρ (observe S r x)) (prediction S κ r ρ) + (κ * ρ / 4) (by positivity) + rw [hevent] at h + exact h + +end +end PerfectCompleteness.HierarchicalAdviceExperiment + + +namespace PerfectCompleteness.HierarchicalAdviceFamily + +noncomputable section + +open scoped Classical +open TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter +open UniqueGamesTheorem.Fourier.MatrixLevelBridge + +attribute [local instance] linearMapFintype + +variable {branch rows : Nat → Nat} {n t : Nat} {O : Type*} [Fintype O] + {Ω : O → Type*} [∀ o, Fintype (Ω o)] + (S : (o : O) → HierarchicalAdviceExperiment.Experiment branch rows n t (Ω o)) + +abbrev Background := (o : O) × HierarchicalAdviceExperiment.Background (S o) + +local instance backgroundFiberFintype (o : O) : + Fintype (HierarchicalAdviceExperiment.Background (S o)) := + HierarchicalAdviceExperiment.backgroundFintype (S o) + +abbrev Input (b : Background S) := HierarchicalAdviceExperiment.Input (S b.1) b.2 +abbrev Row (b : Background S) := Block rows (S b.1).upper +abbrev Value (b : Background S) := HierarchicalAdviceExperiment.Value (S b.1) + +local instance inputFintype (b : Background S) : Fintype (Input S b) := + HierarchicalAdviceExperiment.inputFintype (S b.1) b.2 + +local instance inputFiniteDimensional (b : Background S) : FiniteDimensional F2 (Input S b) := + HierarchicalAdviceExperiment.inputFiniteDimensional (S b.1) b.2 + +local instance valueFintype (b : Background S) : Fintype (Value S b) := + HierarchicalAdviceExperiment.valueFintype (S b.1) + +def table (κ : ℝ) (b : Background S) : + (Input S b →ₗ[F2] Row S b) → Option (Value S b) := + HierarchicalAdviceExperiment.table (S b.1) κ b.2 + +abbrev OriginalSample (r : Nat) := + (o : O) × (Ω o × HierarchicalAdviceExperiment.Advice (S o) r) + +abbrev Observation (r : Nat) := + (o : O) × (HierarchicalAdviceExperiment.Coarse (S o) × + HierarchicalAdviceExperiment.Advice (S o) r) + +local instance coarseFintype (o : O) : Fintype (HierarchicalAdviceExperiment.Coarse (S o)) := + HierarchicalUsefulness.coarseFintype (rows := rows) (S o).slots (S o).upper (S o).lowerLevel + +abbrev ReferenceSample (r : Nat) := + HeterogeneousAdviceFamily.Sample (E := Input S) (F := Row S) r + +def originalLaw (outer : FiniteDistribution O) (r : Nat) : + FiniteDistribution (OriginalSample S r) := + CompletionSoundness.sigmaLaw outer (fun o => HierarchicalAdviceExperiment.originalLaw (S o) r) + +def observe (r : Nat) (x : OriginalSample S r) : Observation S r := + ⟨x.1, HierarchicalAdviceExperiment.observe (S x.1) r x.2⟩ + +def backgroundLaw (outer : FiniteDistribution O) + (backgrounds : (o : O) → FiniteDistribution (HierarchicalAdviceExperiment.Background (S o))) : + FiniteDistribution (Background S) := + CompletionSoundness.sigmaLaw outer backgrounds + +def referenceLaw (outer : FiniteDistribution O) + (backgrounds : (o : O) → FiniteDistribution (HierarchicalAdviceExperiment.Background (S o))) + (r : Nat) : FiniteDistribution (ReferenceSample S r) := + HeterogeneousAdviceFamily.law (backgroundLaw S outer backgrounds) r + +def referenceObserve (r : Nat) (x : ReferenceSample S r) : Observation S r := + ⟨x.1.1, (⟨x.1.2, x.2.2⟩, x.2.1)⟩ + +def J (κ : ℝ) (r : Nat) (ρ : ℝ) (z : Observation S r) : Bool := + HierarchicalAdviceExperiment.J (S z.1) κ r ρ z.2 + +def I (κ : ℝ) (r : Nat) (ρ : ℝ) (z : Observation S r) : Bool := + HierarchicalAdviceExperiment.I (S z.1) κ r ρ z.2 + +def prediction (κ : ℝ) (r : Nat) (ρ : ℝ) (x : OriginalSample S r) : Bool := + HierarchicalAdviceExperiment.prediction (S x.1) κ r ρ x.2 + +omit [Fintype O] in +theorem reference_J (κ : ℝ) (r : Nat) (ρ : ℝ) (x : ReferenceSample S r) : + J S κ r ρ (referenceObserve S r x) = + HeterogeneousAdviceFamily.J (table S κ) r ρ x := rfl + +omit [Fintype O] in +theorem reference_I (κ : ℝ) (r : Nat) (ρ : ℝ) (x : ReferenceSample S r) : + I S κ r ρ (referenceObserve S r x) = + HeterogeneousAdviceFamily.I (table S κ) r ρ x := rfl + +theorem reference_J_mass_ge (κ : ℝ) (outer : FiniteDistribution O) + (backgrounds : (o : O) → FiniteDistribution (HierarchicalAdviceExperiment.Background (S o))) + (hrows : ∀ o, 0 < rows (Nodes.height (S o).upper)) + (ℓ : Nat) (hdim : ∀ o, rows (Nodes.height (S o).upper) ≤ ℓ) + (r : Nat) (ρ η : ℝ) (hη : 0 < η) (hρ : 0 < ρ) (hρ1 : ρ < 1) + (hconstants : levelCutoffConstant r ρ + node (r + 1) < η / 2) + (hmean : 2 * η ≤ (backgroundLaw S outer backgrounds).expectation + (fun b => PartialTableInverse.nonzeroAgreement (table S κ b))) : + (η ^ 2 / 4) / ((2 : ℝ) ^ (r * ℓ)) ^ 2 ≤ + (referenceLaw S outer backgrounds r).probability + (fun x => J S κ r ρ (referenceObserve S r x)) := by + let : ∀ b : Background S, Nontrivial (Row S b) := fun b => by + let : Nonempty (Fin (rows (Nodes.height (S b.1).upper))) := ⟨⟨0, hrows b.1⟩⟩ + exact inferInstance + have hdim' (b : Background S) : Module.finrank F2 (Row S b) ≤ ℓ := by + simpa only [Row, Block, Module.finrank_fin_fun] using hdim b.1 + have hevent : (fun x => J S κ r ρ (referenceObserve S r x)) = + HeterogeneousAdviceFamily.J (table S κ) r ρ := by + funext x + exact reference_J S κ r ρ x + rw [hevent] + exact HeterogeneousAdviceFamily.J_probability_ge + (backgroundLaw S outer backgrounds) (table S κ) r ℓ hdim' ρ η hη hρ hρ1 hconstants hmean + +theorem reference_I_mass_ge (κ : ℝ) (outer : FiniteDistribution O) + (backgrounds : (o : O) → FiniteDistribution (HierarchicalAdviceExperiment.Background (S o))) + (r : Nat) (ρ : ℝ) : + ρ * (referenceLaw S outer backgrounds r).probability + (fun x => J S κ r ρ (referenceObserve S r x)) ≤ + (referenceLaw S outer backgrounds r).probability + (fun x => I S κ r ρ (referenceObserve S r x)) := by + have hJ : (fun x => J S κ r ρ (referenceObserve S r x)) = + HeterogeneousAdviceFamily.J (table S κ) r ρ := by + funext x + exact reference_J S κ r ρ x + have hI : (fun x => I S κ r ρ (referenceObserve S r x)) = + HeterogeneousAdviceFamily.I (table S κ) r ρ := by + funext x + exact reference_I S κ r ρ x + rw [hJ, hI] + exact HeterogeneousAdviceFamily.I_probability_ge + (backgroundLaw S outer backgrounds) (table S κ) r ρ + +omit [Fintype O] in +theorem lower_I_implies_prediction (κ : ℝ) (r : Nat) (ρ : ℝ) + (x : OriginalSample S r) + (hL : HierarchicalAdviceExperiment.lowerEvent (S x.1) x.2.1 = true) + (hI : I S κ r ρ (observe S r x) = true) : + prediction S κ r ρ x = true := + HierarchicalAdviceExperiment.lower_I_implies_prediction (S x.1) κ r ρ x.2.1 x.2.2 hL hI + +theorem prediction_difference (κ : ℝ) (hκ : 0 ≤ κ) (outer : FiniteDistribution O) + (backgrounds : (o : O) → FiniteDistribution (HierarchicalAdviceExperiment.Background (S o))) + (hrows : ∀ o, 0 < rows (Nodes.height (S o).upper)) + (ℓ : Nat) (hdim : ∀ o, rows (Nodes.height (S o).upper) ≤ ℓ) + (r : Nat) (ρ η v : ℝ) (hη : 0 < η) (hρ : 0 < ρ) (hρ1 : ρ < 1) + (hconstants : levelCutoffConstant r ρ + node (r + 1) < η / 2) + (hmean : 2 * η ≤ (backgroundLaw S outer backgrounds).expectation + (fun b => PartialTableInverse.nonzeroAgreement (table S κ b))) + (hv : 0 ≤ v) (hsmall : v ≤ ρ * ((η ^ 2 / 4) / ((2 : ℝ) ^ (r * ℓ)) ^ 2) / 16) + (hvariation : ((originalLaw S outer r).pushforward (observe S r)).totalVariation + ((referenceLaw S outer backgrounds r).pushforward (referenceObserve S r)) ≤ v) : + κ * ρ * ((η ^ 2 / 4) / ((2 : ℝ) ^ (r * ℓ)) ^ 2) / 4 ≤ + (originalLaw S outer r).probability (prediction S κ r ρ) - + (κ * ρ / 4) * (originalLaw S outer r).probability + (fun x => J S κ r ρ (observe S r x)) := by + apply DependentPredictionDifference.of_original_usefulness outer + (fun o => (S o).original) (fun o => HierarchicalAdviceExperiment.adviceLaw (S o) r) + (referenceLaw S outer backgrounds r) (fun o => HierarchicalAdviceExperiment.coarse (S o)) + (referenceObserve S r) (fun o => HierarchicalAdviceExperiment.lowerEvent (S o)) + (I S κ r ρ) (J S κ r ρ) (prediction S κ r ρ) + κ ρ ((η ^ 2 / 4) / ((2 : ℝ) ^ (r * ℓ)) ^ 2) v + hκ hρ.le hρ1.le (by positivity) hv hsmall + · intro o z A hI + exact HierarchicalAdviceExperiment.I_implies_mark (S o) κ r ρ z A hI + · intro o x A hL hI + exact HierarchicalAdviceExperiment.lower_I_implies_prediction (S o) κ r ρ x A hL hI + · exact hvariation + · exact reference_J_mass_ge S κ outer backgrounds hrows ℓ hdim r ρ η + hη hρ hρ1 hconstants hmean + · exact reference_I_mass_ge S κ outer backgrounds r ρ + +end +end PerfectCompleteness.HierarchicalAdviceFamily + + +namespace PerfectCompleteness.HierarchicalOwnPrediction + +noncomputable section + +open scoped TensorProduct Classical +open TreeSourceSpaces HierarchicalArrays + +variable {branch rows : Nat → Nat} {n t : Nat} + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (upper lower : Nodes branch n) (lowerLevel : Nat) + (W : Submodule F2 (Block rows upper)) (a : Block rows lower) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + {Ω : Type*} (eval : Ω → NodeEmbedding.NodeH slots upper) + (tape : BucketSampler.Tape (rows (Nodes.height upper)) Ω) + (arrays : Arrays slots rows) + +def input : OwnInputReference.Input slots rows upper lower W a := + OwnInputReference.readInput slots rows upper lower W a eval + ((HiddenBucketBias.splitTape W Ω tape).2, + OwnInputCanonicalQuery.exteriorOf slots rows upper lower arrays) + +abbrev hidden := HiddenBucketBias.hiddenSum W eval (HiddenBucketBias.splitTape W Ω tape).1 + +theorem response_eq_rightUpper (hne : upper ≠ lower) + (hrows : BucketSampler.evaluate (rows (Nodes.height upper)) eval tape = arrays upper) : + OwnInputReference.response slots rows upper lower W a σ + (input slots upper lower W a eval tape arrays) (hidden slots upper W eval tape) = + HierarchicalPrediction.rightUpper slots upper + (HierarchicalMatrixTable.backgroundOf slots upper arrays) σ lower hne a + (NodeEmbedding.matrix arrays upper) := by + rw [HierarchicalPrediction.rightUpper, HierarchicalMatrixTable.displayed_original] + exact OwnInputCanonicalQuery.response_readInput_hidden_arrays + slots rows upper lower hne W a σ eval tape arrays hrows + +def correction + (y : Block rows upper × HierarchicalMatrixTable.SideOutput (rows := rows) upper) : + Module.Dual F2 (NodeEmbedding.RowSpace slots upper) := + RepresentativeMatrixTable.correctionFunctional (TreeCanonical.numberedSlots slots) + (NodeEmbedding.RowSpace slots upper) + (HierarchicalMatrixTable.other slots upper (HierarchicalMatrixTable.backgroundOf slots upper arrays)) + (HierarchicalFrozenTables.knownRows slots upper lowerLevel + (HierarchicalMatrixTable.backgroundOf slots upper arrays)) + (HierarchicalFrozenTables.sectionMap slots upper lowerLevel + (HierarchicalMatrixTable.backgroundOf slots upper arrays)) + (HierarchicalFrozenTables.sectionMap_spec slots upper lowerLevel + (HierarchicalMatrixTable.backgroundOf slots upper arrays)) y.2 + +theorem correction_eq_of_background_eq (arrays' : Arrays slots rows) + (hbackground : HierarchicalMatrixTable.backgroundOf slots upper arrays = + HierarchicalMatrixTable.backgroundOf slots upper arrays') + (y : Block rows upper × HierarchicalMatrixTable.SideOutput (rows := rows) upper) : + correction slots upper lowerLevel arrays y = + correction slots upper lowerLevel arrays' y := by + exact congrArg (fun bg : HierarchicalMatrixTable.Background (rows := rows) slots upper => + RepresentativeMatrixTable.correctionFunctional (TreeCanonical.numberedSlots slots) + (NodeEmbedding.RowSpace slots upper) (HierarchicalMatrixTable.other slots upper bg) + (HierarchicalFrozenTables.knownRows slots upper lowerLevel bg) + (HierarchicalFrozenTables.sectionMap slots upper lowerLevel bg) + (HierarchicalFrozenTables.sectionMap_spec slots upper lowerLevel bg) y.2) hbackground + +def nativeCorrection + (y : Block rows upper × HierarchicalMatrixTable.SideOutput (rows := rows) upper) : + Module.Dual F2 (NodeEmbedding.NodeH slots upper) := + (correction slots upper lowerLevel arrays y).comp (NodeEmbedding.embed slots upper) + +def visibleOffset + (known : HiddenBucketBias.VisibleDirection W → NodeEmbedding.NodeH slots upper) + (y : Block rows upper × HierarchicalMatrixTable.SideOutput (rows := rows) upper) : + Block rows upper := + HierarchicalTensorMatrix.visibleMatrix slots upper W known + (correction slots upper lowerLevel arrays y) + y.1 + +theorem affinePrediction_eq_tensor + (hrows : BucketSampler.evaluate (rows (Nodes.height upper)) eval tape = arrays upper) + (y : Block rows upper × HierarchicalMatrixTable.SideOutput (rows := rows) upper) : + HierarchicalPrediction.affinePrediction slots upper lowerLevel + (HierarchicalMatrixTable.backgroundOf slots upper arrays) + (NodeEmbedding.matrix arrays upper) y = + visibleOffset slots upper lowerLevel W arrays + (fun v => eval ((HiddenBucketBias.splitTape W Ω tape).2 v)) y + + TensorBucketEvaluation.tensorOutput W (nativeCorrection slots upper lowerLevel arrays y) + (hidden slots upper W eval tape) := + HierarchicalTensorMatrix.prediction_eq_visible_add_tensorOutput slots upper W eval tape + arrays hrows (correction slots upper lowerLevel arrays y) y.1 + +theorem prediction_iff_own_tensor (hne : upper ≠ lower) + (hrows : BucketSampler.evaluate (rows (Nodes.height upper)) eval tape = arrays upper) + (y : Block rows upper × HierarchicalMatrixTable.SideOutput (rows := rows) upper) : + HierarchicalPrediction.rightUpper slots upper + (HierarchicalMatrixTable.backgroundOf slots upper arrays) σ lower hne a + (NodeEmbedding.matrix arrays upper) = + HierarchicalPrediction.affinePrediction slots upper lowerLevel + (HierarchicalMatrixTable.backgroundOf slots upper arrays) + (NodeEmbedding.matrix arrays upper) y ↔ + OwnInputReference.response slots rows upper lower W a σ + (input slots upper lower W a eval tape arrays) (hidden slots upper W eval tape) = + visibleOffset slots upper lowerLevel W arrays + (fun v => eval ((HiddenBucketBias.splitTape W Ω tape).2 v)) y + + TensorBucketEvaluation.tensorOutput W (nativeCorrection slots upper lowerLevel arrays y) + (hidden slots upper W eval tape) := by + rw [response_eq_rightUpper slots upper lower W a σ eval tape arrays hne hrows, + affinePrediction_eq_tensor slots upper lowerLevel W eval tape arrays hrows y] + +end +end PerfectCompleteness.HierarchicalOwnPrediction + + +namespace PerfectCompleteness.HierarchicalUsefulFamily + +noncomputable section + +open scoped BigOperators Classical +open TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +variable {branch rows : Nat → Nat} {n t : Nat} {O : Type*} [Fintype O] + {Ω : O → Type*} [∀ o, Fintype (Ω o)] + (S : (o : O) → HierarchicalAdviceExperiment.Experiment branch rows n t (Ω o)) + +abbrev Sample (Ω : O → Type*) := (o : O) × Ω o + +def originalLaw (outer : FiniteDistribution O) : FiniteDistribution (Sample Ω) := + CompletionSoundness.sigmaLaw outer (fun o => (S o).original) + +def jointEvent (upperEvent : (o : O) → Ω o → Bool) (x : Sample Ω) : Bool := + HierarchicalAdviceExperiment.lowerEvent (S x.1) x.2 && upperEvent x.1 x.2 + +def usefulEvent (κ : ℝ) (upperEvent : (o : O) → Ω o → Bool) (x : Sample Ω) : Bool := + upperEvent x.1 x.2 && + HierarchicalUsefulness.mark (S x.1).slots (S x.1).upper (S x.1).lowerLevel + (S x.1).original (S x.1).arrays (HierarchicalAdviceExperiment.lowerEvent (S x.1)) κ + (HierarchicalAdviceExperiment.coarse (S x.1) x.2) + +omit [Fintype O] in +theorem usefulEvent_eq_table_defined (κ : ℝ) + (upperEvent : (o : O) → Ω o → Bool) (x : Sample Ω) : + usefulEvent S κ upperEvent x = (upperEvent x.1 x.2 && + (HierarchicalAdviceExperiment.table (S x.1) κ + (HierarchicalAdviceExperiment.coarse (S x.1) x.2).1 + (HierarchicalAdviceExperiment.coarse (S x.1) x.2).2).isSome) := by + simp only [HierarchicalAdviceExperiment.table, HierarchicalUsefulness.table_isSome] + rfl + +theorem joint_probability_eq_mean (outer : FiniteDistribution O) + (upperEvent : (o : O) → Ω o → Bool) : + (originalLaw S outer).probability (jointEvent S upperEvent) = + outer.expectation (fun o => (S o).original.probability + (fun x => HierarchicalAdviceExperiment.lowerEvent (S o) x && upperEvent o x)) := + CompletionSoundness.sigmaLaw_probability outer (fun o => (S o).original) + (jointEvent S upperEvent) + +theorem useful_probability_eq_mean (outer : FiniteDistribution O) (κ : ℝ) + (upperEvent : (o : O) → Ω o → Bool) : + (originalLaw S outer).probability (usefulEvent S κ upperEvent) = + outer.expectation (fun o => (S o).original.probability + (fun x => usefulEvent S κ upperEvent ⟨o, x⟩)) := + CompletionSoundness.sigmaLaw_probability outer (fun o => (S o).original) + (usefulEvent S κ upperEvent) + +theorem mean_useful_probability_ge_sub (outer : FiniteDistribution O) + (upperEvent : (o : O) → Ω o → Bool) (κ c : ℝ) (hκ : 0 ≤ κ) + (hjoint : c ≤ outer.expectation (fun o => (S o).original.probability + (fun x => HierarchicalAdviceExperiment.lowerEvent (S o) x && upperEvent o x))) : + c - κ ≤ outer.expectation (fun o => (S o).original.probability + (fun x => usefulEvent S κ upperEvent ⟨o, x⟩)) := by + have hpoint (o : O) : + (S o).original.probability + (fun x => HierarchicalAdviceExperiment.lowerEvent (S o) x && upperEvent o x) - κ ≤ + (S o).original.probability (fun x => usefulEvent S κ upperEvent ⟨o, x⟩) := by + exact UsefulMark.useful_upper_ge_sub (S o).original + (HierarchicalAdviceExperiment.coarse (S o)) + (HierarchicalAdviceExperiment.lowerEvent (S o)) (upperEvent o) κ + ((S o).original.probability + (fun x => HierarchicalAdviceExperiment.lowerEvent (S o) x && upperEvent o x)) + hκ le_rfl + have hsum := Finset.sum_le_sum (fun o (_ : o ∈ (Finset.univ : Finset O)) => + mul_le_mul_of_nonneg_left (hpoint o) (outer.nonnegative o)) + have hintegrated : + outer.expectation (fun o => (S o).original.probability + (fun x => HierarchicalAdviceExperiment.lowerEvent (S o) x && upperEvent o x)) - κ ≤ + outer.expectation (fun o => (S o).original.probability + (fun x => usefulEvent S κ upperEvent ⟨o, x⟩)) := by + simpa only [FiniteDistribution.expectation, mul_sub, Finset.sum_sub_distrib, + ← Finset.sum_mul, outer.normalized, one_mul] using hsum + exact (sub_le_sub_right hjoint κ).trans hintegrated + +theorem useful_probability_ge_sub (outer : FiniteDistribution O) + (upperEvent : (o : O) → Ω o → Bool) (κ c : ℝ) (hκ : 0 ≤ κ) + (hjoint : c ≤ (originalLaw S outer).probability (jointEvent S upperEvent)) : + c - κ ≤ (originalLaw S outer).probability (usefulEvent S κ upperEvent) := by + rw [useful_probability_eq_mean] + exact mean_useful_probability_ge_sub S outer upperEvent κ c hκ + (by simpa only [joint_probability_eq_mean] using hjoint) + +theorem mean_useful_probability_ge_half (outer : FiniteDistribution O) + (upperEvent : (o : O) → Ω o → Bool) (c : ℝ) (hc : 0 ≤ c) + (hjoint : c ≤ outer.expectation (fun o => (S o).original.probability + (fun x => HierarchicalAdviceExperiment.lowerEvent (S o) x && upperEvent o x))) : + c / 2 ≤ outer.expectation (fun o => (S o).original.probability + (fun x => usefulEvent S (c / 2) upperEvent ⟨o, x⟩)) := by + have h := mean_useful_probability_ge_sub S outer upperEvent (c / 2) c + (div_nonneg hc (by norm_num)) hjoint + linarith + +theorem useful_probability_ge_half (outer : FiniteDistribution O) + (upperEvent : (o : O) → Ω o → Bool) (c : ℝ) (hc : 0 ≤ c) + (hjoint : c ≤ (originalLaw S outer).probability (jointEvent S upperEvent)) : + c / 2 ≤ (originalLaw S outer).probability (usefulEvent S (c / 2) upperEvent) := by + have h := useful_probability_ge_sub S outer upperEvent (c / 2) c + (div_nonneg hc (by norm_num)) hjoint + linarith + +end +end PerfectCompleteness.HierarchicalUsefulFamily + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalAgreementMean.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalAgreementMean.lean new file mode 100644 index 0000000000000000000000000000000000000000..0c8eb4da9f11f7848f0c921c945443a39b2d73f2 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalAgreementMean.lean @@ -0,0 +1,143 @@ +import OAI.Computability.PerfectCompleteness.Construction.BucketQuotientAgreement +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalFrozenTablesLemmas +import OAI.Computability.PerfectCompleteness.Sampling.DensityVariation + +namespace OAI + +section + +namespace PerfectCompleteness.HierarchicalAgreementMean + +noncomputable section + +open scoped BigOperators Classical +open TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype + +private theorem probability_product {A B : Type*} [Fintype A] [Fintype B] + (μ : FiniteDistribution A) (ν : FiniteDistribution B) (event : A × B → Bool) : + (μ.product ν).probability event = + μ.expectation (fun a => ν.probability (fun b => event (a, b))) := by + simp only [FiniteDistribution.probability, FiniteDistribution.expectation, + FiniteDistribution.product, Fintype.sum_prod_type, Finset.mul_sum, mul_ite, mul_zero] + +variable {branch rows : Nat → Nat} {n t : Nat} + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (upper : Nodes branch n) + +abbrev Background := HierarchicalMatrixTable.Background (rows := rows) slots upper +abbrev Matrix := HierarchicalMatrixTable.Matrix (rows := rows) slots upper + +local instance backgroundFintype : Fintype (Background (rows := rows) slots upper) := + Fintype.ofFinite _ + +local instance rowSpaceFintype : Fintype (NodeEmbedding.RowSpace slots upper) := + Fintype.ofFinite _ + +local instance valueFintype : + Fintype (Block rows upper × HierarchicalMatrixTable.SideOutput (rows := rows) upper) := + Fintype.ofFinite _ + +abbrev PairRecord := + Background (rows := rows) slots upper × + (Matrix (rows := rows) slots upper × Matrix (rows := rows) slots upper) + +abbrev BucketSample := + BucketSampler.Direction (rows (Nodes.height upper)) × + (BucketSampler.Tape (rows (Nodes.height upper)) (NodeEmbedding.RowSpace slots upper) × + NodeEmbedding.RowSpace slots upper) + +def bucketLaw (hrows : 0 < rows (Nodes.height upper)) : + FiniteDistribution (BucketSample (rows := rows) slots upper) := by + letI : Nonempty (BucketSampler.Direction (rows (Nodes.height upper))) := + ⟨BucketUniform.coordinateDirection ⟨0, hrows⟩⟩ + exact (FiniteDistribution.uniform (BucketSampler.Direction (rows (Nodes.height upper)))).product + ((BucketSampler.tapeLaw (rows (Nodes.height upper)) + (FiniteDistribution.uniform (NodeEmbedding.RowSpace slots upper))).product + (FiniteDistribution.uniform (NodeEmbedding.RowSpace slots upper))) + +def pairRecord + (sample : Background (rows := rows) slots upper × BucketSample (rows := rows) slots upper) : + PairRecord (rows := rows) slots upper := + (sample.1, + (BucketMatrixResampling.assembledMatrix (NodeEmbedding.RowSpace slots upper) + (rows (Nodes.height upper)) sample.2.2.1, + BucketMatrixResampling.assembledMatrix (NodeEmbedding.RowSpace slots upper) + (rows (Nodes.height upper)) (Function.update sample.2.2.1 sample.2.1 sample.2.2.2))) + +def referenceLaw + (backgroundLaw : FiniteDistribution (Background (rows := rows) slots upper)) + (hrows : 0 < rows (Nodes.height upper)) : + FiniteDistribution (PairRecord (rows := rows) slots upper) := + (backgroundLaw.product (bucketLaw slots upper hrows)).pushforward (pairRecord slots upper) + +variable (lowerLevel : Nat) {Ω : Type*} [Fintype Ω] + (original : FiniteDistribution Ω) (arrays : Ω → Arrays slots rows) + (lower : Ω → Bool) (κ : ℝ) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + +def collision (record : PairRecord (rows := rows) slots upper) : Bool := + TwoResponseCollision.collision + (HierarchicalUsefulness.table slots upper lowerLevel original arrays lower κ σ record.1) + (MatrixRowQuotient.projectMatrix + (HierarchicalFrozenTables.knownRows slots upper lowerLevel record.1) record.2.1, + MatrixRowQuotient.projectMatrix + (HierarchicalFrozenTables.knownRows slots upper lowerLevel record.1) record.2.2) + +theorem reference_collision_eq_mean + (backgroundLaw : FiniteDistribution (Background (rows := rows) slots upper)) + (hrows : 0 < rows (Nodes.height upper)) : + (referenceLaw slots upper backgroundLaw hrows).probability + (collision slots upper lowerLevel original arrays lower κ σ) = + backgroundLaw.expectation (fun background => PartialTableInverse.nonzeroAgreement + (HierarchicalUsefulness.table slots upper lowerLevel original arrays lower κ σ background)) := by + let : Nonempty (BucketSampler.Direction (rows (Nodes.height upper))) := + ⟨BucketUniform.coordinateDirection ⟨0, hrows⟩⟩ + rw [referenceLaw, FiniteDistribution.probability_pushforward, probability_product] + apply FiniteDistribution.expectation_congr + intro background + exact BucketQuotientAgreement.uniform_bucket_collision_probability + (NodeEmbedding.RowSpace slots upper) (rows (Nodes.height upper)) + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + (HierarchicalUsefulness.table slots upper lowerLevel original arrays lower κ σ background) + +theorem mean_nonzeroAgreement_ge_of_collision + (backgroundLaw : FiniteDistribution (Background (rows := rows) slots upper)) + (hrows : 0 < rows (Nodes.height upper)) + (sourceLaw : FiniteDistribution (PairRecord (rows := rows) slots upper)) + (b δ : ℝ) + (hcollision : b ≤ sourceLaw.probability + (collision slots upper lowerLevel original arrays lower κ σ)) + (hvariation : sourceLaw.totalVariation (referenceLaw slots upper backgroundLaw hrows) ≤ δ) : + b - δ ≤ backgroundLaw.expectation (fun background => PartialTableInverse.nonzeroAgreement + (HierarchicalUsefulness.table slots upper lowerLevel original arrays lower κ σ background)) := by + have h := FiniteDistribution.probability_le_add_totalVariation sourceLaw + (referenceLaw slots upper backgroundLaw hrows) + (collision slots upper lowerLevel original arrays lower κ σ) + rw [reference_collision_eq_mean] at h + linarith + +theorem mean_nonzeroAgreement_ge_sixteenth + (backgroundLaw : FiniteDistribution (Background (rows := rows) slots upper)) + (hrows : 0 < rows (Nodes.height upper)) + (sourceLaw : FiniteDistribution (PairRecord (rows := rows) slots upper)) (c : ℝ) + (hcollision : c ^ 2 / 8 ≤ sourceLaw.probability + (collision slots upper lowerLevel original arrays lower κ σ)) + (hvariation : sourceLaw.totalVariation (referenceLaw slots upper backgroundLaw hrows) ≤ c ^ 2 / 16) : + 2 * (c ^ 2 / 32) ≤ + backgroundLaw.expectation (fun background => PartialTableInverse.nonzeroAgreement + (HierarchicalUsefulness.table slots upper lowerLevel original arrays lower κ σ background)) := by + have h := mean_nonzeroAgreement_ge_of_collision slots upper lowerLevel + original arrays lower κ σ backgroundLaw hrows sourceLaw (c ^ 2 / 8) (c ^ 2 / 16) + hcollision hvariation + linarith + +end +end PerfectCompleteness.HierarchicalAgreementMean + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalArrays.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalArrays.lean new file mode 100644 index 0000000000000000000000000000000000000000..02ce4996b2625987a7acdd2af6eeeeb23ce6b265 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalArrays.lean @@ -0,0 +1,190 @@ +import Mathlib.Data.Fintype.Sum +import OAI.Computability.PerfectCompleteness.Construction.DescendantSpacesLemmas +import OAI.Computability.PerfectCompleteness.Construction.TreeCanonical +import OAI.Computability.PerfectCompleteness.Foundations.LinearEvaluationLemmas +import OAI.Computability.PerfectCompleteness.Reduction.SourceCompleteness + +namespace OAI + + +namespace PerfectCompleteness.HierarchicalArrays + +open TreeSourceSpaces + +def Nodes (branch : Nat → Nat) : Nat → Type + | 0 => Empty + | n + 1 => Unit ⊕ (Fin (branch n) × Nodes branch n) + +instance nodesFintype (branch : Nat → Nat) (n : Nat) : Fintype (Nodes branch n) := by + induction n with + | zero => exact inferInstanceAs (Fintype Empty) + | succ n ih => + letI : Fintype (Nodes branch n) := ih + exact inferInstanceAs (Fintype (Unit ⊕ (Fin (branch n) × Nodes branch n))) + +instance nodesDecidableEq (branch : Nat → Nat) (n : Nat) : + DecidableEq (Nodes branch n) := by + induction n with + | zero => exact inferInstanceAs (DecidableEq Empty) + | succ n ih => + letI : DecidableEq (Nodes branch n) := ih + exact inferInstanceAs (DecidableEq (Unit ⊕ (Fin (branch n) × Nodes branch n))) + +namespace Nodes + +variable {branch : Nat → Nat} + +def height : {n : Nat} → Nodes branch n → Nat + | 0, node => nomatch node + | n + 1, .inl _ => n + 1 + | _ + 1, .inr (_, node) => height node + +def path : {n : Nat} → (node : Nodes branch n) → + DescendantSpaces.Path branch n (height node) + | 0, node => nomatch node + | n + 1, .inl _ => .refl (n + 1) + | _ + 1, .inr (i, node) => .step i (path node) + +theorem height_pos : ∀ {n : Nat} (node : Nodes branch n), 0 < height node := by + intro n + induction n with + | zero => + intro node + exact nomatch node + | succ n ih => + intro node + cases node with + | inl _ => exact Nat.zero_lt_succ n + | inr pair => exact ih pair.2 + +theorem height_le {n : Nat} (node : Nodes branch n) : height node ≤ n := + (path node).height_le + +end Nodes + +variable {branch : Nat → Nat} {n t : Nat} + +def nodeSlots (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (node : Nodes branch n) : RecursiveSpaces.Slots branch (Nodes.height node) → + Fin t → MixedSupport.Slot := + fun s => slots ((Nodes.path node).slotEmbedding s) + +def restrictNode (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (node : Nodes branch n) : Domain slots → Domain (nodeSlots slots node) := + (Nodes.path node).restriction (LeafDomain slots) + +theorem restrictNode_surjective + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (node : Nodes branch n) : Function.Surjective (restrictNode slots node) := + (Nodes.path node).restriction_surjective (LeafDomain slots) (fun _ => inferInstance) + +abbrev Block (rows : Nat → Nat) (node : Nodes branch n) := Fin (rows (Nodes.height node)) → F2 + +abbrev Arrays (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (rows : Nat → Nat) := + ∀ node : Nodes branch n, Fin (rows (Nodes.height node)) → H (nodeSlots slots node) + +theorem arrays_finite + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) (rows : Nat → Nat) : + Finite (Arrays slots rows) := by + infer_instance + +def joint {slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot} + {rows : Nat → Nat} (arrays : Arrays slots rows) : + Domain slots → ∀ node : Nodes branch n, Block rows node := + fun x node row => (arrays node row).val (restrictNode slots node x) + +@[simp] theorem joint_component + {slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot} + {rows : Nat → Nat} (arrays : Arrays slots rows) (x : Domain slots) + (node : Nodes branch n) (row : Fin (rows (Nodes.height node))) : + joint arrays x node row = (arrays node row).val (restrictNode slots node x) := rfl + +theorem row_mem_root + {slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot} + {rows : Nat → Nat} (arrays : Arrays slots rows) + (hbranch : ∀ k < n, 0 < branch k) (node : Nodes branch n) + (row : Fin (rows (Nodes.height node))) : + (fun x => joint arrays x node row) ∈ H slots := + DescendantSpaces.space_descendant_le (Nodes.path node) (LeafDomain slots) hbranch + (Submodule.mem_map_of_mem (arrays node row).property) + +abbrev Output (branch : Nat → Nat) (n : Nat) (rows : Nat → Nat) : Type := + BlockQuotient.JointOutput (fun node : Nodes branch n => Block rows node) PUnit + +def fullJoint {slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot} + {rows : Nat → Nat} (arrays : Arrays slots rows) : Domain slots → Output branch n rows := + fun x => (joint arrays x, PUnit.unit) + +variable {v m : Nat} + +def sourceSlots (clauses : Fin m → SourceClause.NormalizedClause v) + (endpoints : RecursiveSpaces.Slots branch n → Fin t → SourceKeys.Endpoint v m) : + RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot := + fun s k => SourceKeys.slot clauses (endpoints s k) + +noncomputable section + +def numberedEndpoints + (endpoints : RecursiveSpaces.Slots branch n → Fin t → SourceKeys.Endpoint v m) : + Fin (TreeCanonical.locationCount branch n t) → SourceKeys.Endpoint v m := + fun j => endpoints ((TreeCanonical.numbering branch n t).symm j).1 + ((TreeCanonical.numbering branch n t).symm j).2 + +theorem numberedSlots_sourceSlots (clauses : Fin m → SourceClause.NormalizedClause v) + (endpoints : RecursiveSpaces.Slots branch n → Fin t → SourceKeys.Endpoint v m) : + TreeCanonical.numberedSlots (sourceSlots clauses endpoints) = + SourceKeys.slot clauses ∘ numberedEndpoints endpoints := rfl + +def presentation (clauses : Fin m → SourceClause.NormalizedClause v) + (endpoints : RecursiveSpaces.Slots branch n → Fin t → SourceKeys.Endpoint v m) + (rows : Nat → Nat) (arrays : Arrays (sourceSlots clauses endpoints) rows) : + SourceCompleteness.Presentation clauses (TreeCanonical.locationCount branch n t) + (Output branch n rows) where + endpoints := numberedEndpoints endpoints + joint := TreeCanonical.numberedFunction (sourceSlots clauses endpoints) (fullJoint arrays) + +theorem presentation_key (side : CanonicalKeys.Side) + (clauses : Fin m → SourceClause.NormalizedClause v) + (endpoints : RecursiveSpaces.Slots branch n → Fin t → SourceKeys.Endpoint v m) + (rows : Nat → Nat) (arrays : Arrays (sourceSlots clauses endpoints) rows) : + SourceCompleteness.presentationKey side (presentation clauses endpoints rows arrays) = + TreeCanonical.key side (sourceSlots clauses endpoints) (fullJoint arrays) := rfl + +theorem presentation_evaluate (clauses : Fin m → SourceClause.NormalizedClause v) + (endpoints : RecursiveSpaces.Slots branch n → Fin t → SourceKeys.Endpoint v m) + (rows : Nat → Nat) (arrays : Arrays (sourceSlots clauses endpoints) rows) + (x : Domain (sourceSlots clauses endpoints)) : + (presentation clauses endpoints rows arrays).joint + (TreeCanonical.assignmentEquiv (sourceSlots clauses endpoints) x) = fullJoint arrays x := + congrArg (fullJoint arrays) + ((TreeCanonical.assignmentEquiv (sourceSlots clauses endpoints)).symm_apply_apply x) + +def sourceAssignment (clauses : Fin m → SourceClause.NormalizedClause v) + (assignment : Fin v → Bool) (hsat : ∀ c, (clauses c).clause.eval assignment = true) + (endpoints : RecursiveSpaces.Slots branch n → Fin t → SourceKeys.Endpoint v m) : + Domain (sourceSlots clauses endpoints) := + fun s k => SourceKeys.endpointValue clauses assignment hsat (endpoints s k) + +theorem sourceAssignment_numbered (clauses : Fin m → SourceClause.NormalizedClause v) + (assignment : Fin v → Bool) (hsat : ∀ c, (clauses c).clause.eval assignment = true) + (endpoints : RecursiveSpaces.Slots branch n → Fin t → SourceKeys.Endpoint v m) : + TreeCanonical.assignmentEquiv (sourceSlots clauses endpoints) + (sourceAssignment clauses assignment hsat endpoints) = + SourceKeys.realizingAssignment clauses assignment hsat (numberedEndpoints endpoints) := rfl + +theorem presentation_realizing (clauses : Fin m → SourceClause.NormalizedClause v) + (assignment : Fin v → Bool) (hsat : ∀ c, (clauses c).clause.eval assignment = true) + (endpoints : RecursiveSpaces.Slots branch n → Fin t → SourceKeys.Endpoint v m) + (rows : Nat → Nat) (arrays : Arrays (sourceSlots clauses endpoints) rows) : + (presentation clauses endpoints rows arrays).joint + (SourceKeys.realizingAssignment clauses assignment hsat (numberedEndpoints endpoints)) = + fullJoint arrays (sourceAssignment clauses assignment hsat endpoints) := by + rw [← sourceAssignment_numbered] + exact presentation_evaluate clauses endpoints rows arrays _ + +end + +end PerfectCompleteness.HierarchicalArrays + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalFrozenTablesLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalFrozenTablesLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..3f5df2c0b4ef8ba2e147025a69ad1f67e1e21c42 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalFrozenTablesLemmas.lean @@ -0,0 +1,682 @@ +import Mathlib.Data.Fintype.Sigma +import Mathlib.LinearAlgebra.Dimension.Constructions +import Mathlib.LinearAlgebra.FiniteDimensional.Defs +import OAI.Computability.PerfectCompleteness.Algebra.MatrixTriangularFoldingLemmas +import OAI.Computability.PerfectCompleteness.Construction.DescendantSpacesLemmas +import OAI.Computability.PerfectCompleteness.Construction.RelativeDescendantProductsLemmas +import OAI.Computability.PerfectCompleteness.Foundations.GeometricPathLemmas +import OAI.Computability.PerfectCompleteness.Foundations.GlobalityLemmas +import OAI.Computability.PerfectCompleteness.Foundations.ManyGoodRowsLemmas +import OAI.Computability.PerfectCompleteness.Foundations.TupleIndexEmitterLemmas +import OAI.Computability.UniqueGames.Games.FinishBoundsLemmas + +namespace OAI + + +namespace PerfectCompleteness.HierarchicalFrozenTables + +noncomputable section + +open scoped Classical +open TreeSourceSpaces HierarchicalArrays + +variable {branch rows : Nat → Nat} {n t : Nat} + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (upper : Nodes branch n) (lowerLevel : Nat) + +abbrev LowerNodes := {d : RelativeDescendantProducts.RelativeDescendant upper // + Nodes.height d.val = lowerLevel} + +def lowerIndex (d : LowerNodes upper lowerLevel) : {j : Nodes branch n // j ≠ upper} := + RelativeDescendantProducts.descendantIndex upper d.val + +variable (background : HierarchicalMatrixTable.Background (rows := rows) slots upper) + +def knownSpace : Submodule F2 (NodeEmbedding.NumberedDomain slots → F2) := + HierarchicalKnownRows.knownSpace slots upper background (lowerIndex upper lowerLevel) + +theorem knownSpace_le_rowSpace (hbranch : ∀ k < n, 0 < branch k) : + knownSpace slots upper lowerLevel background ≤ NodeEmbedding.RowSpace slots upper := + RelativeDescendantProducts.relative_knownSpace_le_rowSpace slots hbranch upper background + (fun d : LowerNodes upper lowerLevel => d.val) + +def knownRows : Submodule F2 (NodeEmbedding.RowSpace slots upper) := + (knownSpace slots upper lowerLevel background).comap + (NodeEmbedding.RowSpace slots upper).subtype + +def sectionMap : + (NodeEmbedding.RowSpace slots upper ⧸ knownRows slots upper lowerLevel background) →ₗ[F2] + NodeEmbedding.RowSpace slots upper := + Classical.choose (MatrixRowQuotient.exists_section (knownRows slots upper lowerLevel background)) + +theorem sectionMap_spec : + (knownRows slots upper lowerLevel background).mkQ.comp + (sectionMap slots upper lowerLevel background) = LinearMap.id := + Classical.choose_spec (MatrixRowQuotient.exists_section (knownRows slots upper lowerLevel background)) + +theorem determined : + RepresentativeMatrixTable.Determined (TreeCanonical.numberedSlots slots) + (NodeEmbedding.RowSpace slots upper) (HierarchicalMatrixTable.other slots upper background) + (knownRows slots upper lowerLevel background) := + HierarchicalKnownRows.determined slots upper background (lowerIndex upper lowerLevel) + +abbrev QuotientMatrix := + Module.Dual F2 (NodeEmbedding.RowSpace slots upper ⧸ knownRows slots upper lowerLevel background) + →ₗ[F2] Block rows upper + +variable (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + +def table (useful : QuotientMatrix slots upper lowerLevel background → Prop) : + QuotientMatrix slots upper lowerLevel background → + Option (Block rows upper × HierarchicalMatrixTable.SideOutput (rows := rows) upper) := + RepresentativeMatrixTable.partialTable (TreeCanonical.numberedSlots slots) + (NodeEmbedding.RowSpace slots upper) (HierarchicalMatrixTable.other slots upper background) + σ (knownRows slots upper lowerLevel background) (sectionMap slots upper lowerLevel background) useful + +theorem card_accepted_responses_le_two + (a : Block rows upper) (ha : a ≠ 0) + (X : HierarchicalMatrixTable.Matrix (rows := rows) slots upper) : + Nat.card {y : Block rows upper × HierarchicalMatrixTable.SideOutput (rows := rows) upper // + ∃ h : NodeEmbedding.RowSpace slots upper, + CanonicalMatrixTable.Accepts (TreeCanonical.numberedSlots slots) + (NodeEmbedding.RowSpace slots upper) (HierarchicalMatrixTable.other slots upper background) + σ a (EvaluationMatrix.shift (NodeEmbedding.RowSpace slots upper) X a h) ∧ + RepresentativeMatrixTable.response (TreeCanonical.numberedSlots slots) + (NodeEmbedding.RowSpace slots upper) (HierarchicalMatrixTable.other slots upper background) + σ (knownRows slots upper lowerLevel background) (sectionMap slots upper lowerLevel background) + (EvaluationMatrix.shift (NodeEmbedding.RowSpace slots upper) X a h) = y} ≤ 2 := + RepresentativeMatrixTable.card_accepted_responses_le_two (TreeCanonical.numberedSlots slots) + (NodeEmbedding.RowSpace slots upper) (HierarchicalMatrixTable.other slots upper background) + σ (knownRows slots upper lowerLevel background) (sectionMap slots upper lowerLevel background) + (sectionMap_spec slots upper lowerLevel background) + (determined slots upper lowerLevel background) a ha X + +end +end PerfectCompleteness.HierarchicalFrozenTables + + + +namespace PerfectCompleteness.HierarchicalUsefulness + +open scoped Classical +open TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype + +noncomputable section + +variable {branch rows : Nat → Nat} {n t : Nat} + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (upper : Nodes branch n) (lowerLevel : Nat) + +abbrev Coarse := + (background : HierarchicalMatrixTable.Background (rows := rows) slots upper) × + HierarchicalFrozenTables.QuotientMatrix slots upper lowerLevel background + +instance coarseFintype : Fintype (Coarse (rows := rows) slots upper lowerLevel) := by + letI : Fintype (HierarchicalMatrixTable.Background (rows := rows) slots upper) := + Fintype.ofFinite _ + letI (b : HierarchicalMatrixTable.Background (rows := rows) slots upper) : + Fintype (HierarchicalFrozenTables.QuotientMatrix slots upper lowerLevel b) := + linearMapFintype + exact inferInstance + +def observe (arrays : Arrays slots rows) : Coarse (rows := rows) slots upper lowerLevel := + ⟨HierarchicalMatrixTable.backgroundOf slots upper arrays, + MatrixRowQuotient.projectMatrix + (HierarchicalFrozenTables.knownRows slots upper lowerLevel + (HierarchicalMatrixTable.backgroundOf slots upper arrays)) + (NodeEmbedding.matrix arrays upper)⟩ + +variable {Ω : Type*} [Fintype Ω] + (original : FiniteDistribution Ω) (arrays : Ω → Arrays slots rows) + (lower : Ω → Bool) (κ : ℝ) + +def mark (z : Coarse (rows := rows) slots upper lowerLevel) : Bool := + UsefulMark.useful original (fun x => observe slots upper lowerLevel (arrays x)) lower κ z + +variable (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + +def table (background : HierarchicalMatrixTable.Background (rows := rows) slots upper) : + HierarchicalFrozenTables.QuotientMatrix slots upper lowerLevel background → + Option (Block rows upper × HierarchicalMatrixTable.SideOutput (rows := rows) upper) := + HierarchicalFrozenTables.table slots upper lowerLevel background σ + (fun X => mark slots upper lowerLevel original arrays lower κ ⟨background, X⟩ = true) + +theorem table_isSome (background : HierarchicalMatrixTable.Background (rows := rows) slots upper) + (X : HierarchicalFrozenTables.QuotientMatrix slots upper lowerLevel background) : + (table slots upper lowerLevel original arrays lower κ σ background X).isSome = + mark slots upper lowerLevel original arrays lower κ ⟨background, X⟩ := by + unfold table HierarchicalFrozenTables.table RepresentativeMatrixTable.partialTable + cases h : mark slots upper lowerLevel original arrays lower κ ⟨background, X⟩ <;> + simp [h] + +theorem table_defined_at_observation (x : Ω) : + (table slots upper lowerLevel original arrays lower κ σ + (observe slots upper lowerLevel (arrays x)).1 + (observe slots upper lowerLevel (arrays x)).2).isSome = + UsefulMark.useful original (fun y => observe slots upper lowerLevel (arrays y)) + lower κ (observe slots upper lowerLevel (arrays x)) := + table_isSome slots upper lowerLevel original arrays lower κ σ _ _ + +theorem useful_upper_mass (upperEvent : Ω → Bool) (c : ℝ) (hc : 0 ≤ c) + (hjoint : c ≤ original.probability (fun x => lower x && upperEvent x)) : + c / 2 ≤ original.probability (fun x => upperEvent x && + (table slots upper lowerLevel original arrays lower (c / 2) σ + (observe slots upper lowerLevel (arrays x)).1 + (observe slots upper lowerLevel (arrays x)).2).isSome) := by + simpa only [table_defined_at_observation] using + UsefulMark.useful_upper_ge_half original + (fun x => observe slots upper lowerLevel (arrays x)) lower upperEvent c hc hjoint + +end +end PerfectCompleteness.HierarchicalUsefulness + + + +namespace PerfectCompleteness.HierarchicalInverseAdvice + +open scoped Classical +open TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Fourier.MatrixLevelBridge +open UniqueGamesTheorem.Appendix.RankLevelFilter + +noncomputable section + +attribute [local instance] linearMapFintype + +variable {branch rows : Nat → Nat} {n t : Nat} + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (upper : Nodes branch n) (lowerLevel : Nat) + +local instance backgroundFintype : + Fintype (HierarchicalMatrixTable.Background (rows := rows) slots upper) := + Fintype.ofFinite _ + +abbrev Input (background : HierarchicalMatrixTable.Background (rows := rows) slots upper) := + Module.Dual F2 (NodeEmbedding.RowSpace slots upper ⧸ + HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + +local instance inputFintype + (background : HierarchicalMatrixTable.Background (rows := rows) slots upper) : + Fintype (Input slots upper lowerLevel background) := Fintype.ofFinite _ + +local instance valueFintype : + Fintype (Block rows upper × HierarchicalMatrixTable.SideOutput (rows := rows) upper) := + Fintype.ofFinite _ + +variable {Ω : Type*} [Fintype Ω] + (original : FiniteDistribution Ω) (arrays : Ω → Arrays slots rows) + (lower : Ω → Bool) (κ : ℝ) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + +theorem mean_adviceMass_ge + (backgroundLaw : FiniteDistribution + (HierarchicalMatrixTable.Background (rows := rows) slots upper)) + (hrows : 0 < rows (Nodes.height upper)) + (r : Nat) (ρ η : ℝ) (hη : 0 < η) (hρ : 0 < ρ) (hρ1 : ρ < 1) + (hconstants : levelCutoffConstant r ρ + node (r + 1) < η / 2) + (hmean : 2 * η ≤ backgroundLaw.expectation (fun background => + PartialTableInverse.nonzeroAgreement + (HierarchicalUsefulness.table slots upper lowerLevel + original arrays lower κ σ background))) : + (η ^ 2 / 4) / (2 : ℝ) ^ (r * rows (Nodes.height upper)) ≤ + backgroundLaw.expectation (fun background => + ManyGoodRows.adviceMass + (HierarchicalUsefulness.table slots upper lowerLevel + original arrays lower κ σ background) r ρ) := by + let : Nonempty (Fin (rows (Nodes.height upper))) := ⟨⟨0, hrows⟩⟩ + have h := FamilyGoodRows.mean_adviceMass_ge backgroundLaw + (fun background => HierarchicalUsefulness.table slots upper lowerLevel + original arrays lower κ σ background) + r ρ η hη hρ hρ1 hconstants hmean + simpa only [Block, Module.finrank_fin_fun] using h + +end +end PerfectCompleteness.HierarchicalInverseAdvice + + + +namespace PerfectCompleteness.KnownSpaceDimension + +open FactoredFunctionsDependent + +variable {𝕜 Ω I : Type*} [Field 𝕜] {J : I → Type*} + +abbrev GeneratorIndex (J : I → Type*) := Unit ⊕ (Σ i, J i × J i) + +def generator (lower : Ω → (i : I) → J i → 𝕜) : GeneratorIndex J → Ω → 𝕜 + | .inl _ => 1 + | .inr ⟨i, t, u⟩ => fun x => lower x i t * lower x i u + +theorem generator_range (lower : Ω → (i : I) → J i → 𝕜) : + Set.range (generator lower) = + {f | f = 1 ∨ ∃ (i : I) (t u : J i), f = fun x => lower x i t * lower x i u} := by + ext f + constructor + · rintro ⟨index, rfl⟩ + rcases index with constantIndex | ⟨i, t, u⟩ + · exact Or.inl rfl + · exact Or.inr ⟨i, t, u, rfl⟩ + · rintro (rfl | ⟨i, t, u, rfl⟩) + · exact ⟨.inl (), rfl⟩ + · exact ⟨.inr ⟨i, t, u⟩, rfl⟩ + +theorem quadraticSpan_eq_span_range (lower : Ω → (i : I) → J i → 𝕜) : + dependentQuadraticSpan lower = Submodule.span 𝕜 (Set.range (generator lower)) := by + rw [generator_range] + rfl + +section Finite + +variable [Fintype I] [∀ i, Fintype (J i)] + +theorem card_generatorIndex : + Fintype.card (GeneratorIndex J) = 1 + ∑ i, (Fintype.card (J i)) ^ 2 := by + simp only [GeneratorIndex, Fintype.card_sum, Fintype.card_unit, + Fintype.card_sigma, Fintype.card_prod, pow_two] + +theorem finiteDimensional_quadraticSpan (lower : Ω → (i : I) → J i → 𝕜) : + FiniteDimensional 𝕜 (dependentQuadraticSpan lower) := by + rw [quadraticSpan_eq_span_range] + exact FiniteDimensional.span_of_finite 𝕜 (Set.finite_range (generator lower)) + +theorem finrank_quadraticSpan_le (lower : Ω → (i : I) → J i → 𝕜) : + Module.finrank 𝕜 (dependentQuadraticSpan lower) ≤ + 1 + ∑ i, (Fintype.card (J i)) ^ 2 := by + rw [quadraticSpan_eq_span_range, ← card_generatorIndex (J := J)] + exact finrank_range_le_card (generator lower) + +end Finite + +open TreeSourceSpaces HierarchicalArrays + +variable {branch rows : Nat → Nat} {n t : Nat} {D : Type*} [Fintype D] + +theorem finrank_knownSpace_le + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (upper : Nodes branch n) + (background : HierarchicalMatrixTable.Background (rows := rows) slots upper) + (descendant : D → {j : Nodes branch n // j ≠ upper}) : + Module.finrank F2 (HierarchicalKnownRows.knownSpace slots upper background descendant) ≤ + 1 + ∑ d, (rows (Nodes.height (descendant d).val)) ^ 2 := by + let rowCount : D → Nat := fun d => rows (Nodes.height (descendant d).val) + let lower : NodeEmbedding.NumberedDomain slots → (d : D) → Fin (rowCount d) → F2 := + HierarchicalKnownRows.lower slots upper background descendant + change Module.finrank F2 (dependentQuadraticSpan lower) ≤ 1 + ∑ d : D, (rowCount d) ^ 2 + have hbound : Module.finrank F2 (dependentQuadraticSpan lower) ≤ + 1 + ∑ d : D, (Fintype.card (Fin (rowCount d))) ^ 2 := + finrank_quadraticSpan_le (𝕜 := F2) (Ω := NodeEmbedding.NumberedDomain slots) + (I := D) (J := fun d : D => Fin (rowCount d)) lower + simpa only [Fintype.card_fin] using hbound + +theorem finrank_knownSpace_comap_le + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (upper : Nodes branch n) + (background : HierarchicalMatrixTable.Background (rows := rows) slots upper) + (descendant : D → {j : Nodes branch n // j ≠ upper}) + (hgeometry : HierarchicalKnownRows.knownSpace slots upper background descendant ≤ + NodeEmbedding.RowSpace slots upper) : + Module.finrank F2 ((HierarchicalKnownRows.knownSpace slots upper background descendant).comap + (NodeEmbedding.RowSpace slots upper).subtype) ≤ + 1 + ∑ d, (rows (Nodes.height (descendant d).val)) ^ 2 := by + rw [(Submodule.comapSubtypeEquivOfLe hgeometry).finrank_eq] + exact finrank_knownSpace_le slots upper background descendant + +end PerfectCompleteness.KnownSpaceDimension + + +section + +namespace PerfectCompleteness.DescendantSpaces.Path + +open RecursiveSpaces + +universe u + +variable {branch : Nat → Nat} {n m k l : Nat} + +def append : {n m k : Nat} → Path branch n m → Path branch m k → Path branch n k + | _, _, _, .refl _, q => q + | _, _, _, .step i p, q => .step i (append p q) + +@[simp] theorem append_refl (q : Path branch n m) : (Path.refl n).append q = q := rfl + +@[simp] theorem append_step (i : Fin (branch n)) (p : Path branch n m) + (q : Path branch m k) : (Path.step i p).append q = Path.step i (p.append q) := rfl + +@[simp] theorem append_refl_right (p : Path branch n m) : p.append (.refl m) = p := by + induction p with + | refl n => rfl + | step i p ih => exact congrArg (Path.step i) ih + +theorem append_assoc (p : Path branch n m) : + ∀ (q : Path branch m k) (r : Path branch k l), + (p.append q).append r = p.append (q.append r) := by + induction p with + | refl n => intro q r; rfl + | step i p ih => + intro q r + exact congrArg (Path.step i) (ih q r) + +@[simp] theorem slotEmbedding_append (p : Path branch n m) : + ∀ (q : Path branch m k) (s : Slots branch k), + (p.append q).slotEmbedding s = p.slotEmbedding (q.slotEmbedding s) := by + induction p with + | refl n => intro q s; rfl + | step i p ih => + intro q s + exact congrArg (fun t => (i, t)) (ih q s) + +theorem family_append (p : Path branch n m) (q : Path branch m k) + (A : Slots branch n → Type u) : + (p.append q).family A = q.family (p.family A) := by + funext s + exact congrArg A (slotEmbedding_append p q s) + +theorem restriction_append_heq (p : Path branch n m) : + ∀ (q : Path branch m k) (A : Slots branch n → Type u) (x : Assignment A), + HEq ((p.append q).restriction A x) + (q.restriction (p.family A) (p.restriction A x)) := by + induction p with + | refl n => intro q A x; rfl + | step i p ih => + intro q A x + exact ih q (childFamily A i) (childRestriction A i x) + +def appendAssignmentEquiv (p : Path branch n m) (q : Path branch m k) + (A : Slots branch n → Type u) : + Assignment ((p.append q).family A) ≃ Assignment (q.family (p.family A)) := + Equiv.cast (congrArg (fun B : Slots branch k → Type u => Assignment B) + (family_append p q A)) + +theorem restriction_append (p : Path branch n m) (q : Path branch m k) + (A : Slots branch n → Type u) (x : Assignment A) : + appendAssignmentEquiv p q A ((p.append q).restriction A x) = + q.restriction (p.family A) (p.restriction A x) := by + apply eq_of_heq + exact (cast_heq _ _).trans (restriction_append_heq p q A x) + +theorem restriction_append_comp (p : Path branch n m) (q : Path branch m k) + (A : Slots branch n → Type u) : + appendAssignmentEquiv p q A ∘ (p.append q).restriction A = + q.restriction (p.family A) ∘ p.restriction A := by + funext x + exact restriction_append p q A x + +end PerfectCompleteness.DescendantSpaces.Path + +namespace PerfectCompleteness.PathComposition + +open RecursiveSpaces DescendantSpaces HierarchicalArrays + +variable {branch : Nat → Nat} {n m : Nat} + +theorem append_leafPath (p : Path branch n m) : + ∀ leaf : Slots branch m, p.append (GeometricPath.leafPath leaf) = + GeometricPath.leafPath (p.slotEmbedding leaf) := by + induction p with + | refl n => intro leaf; rfl + | step i p ih => + intro leaf + exact congrArg (Path.step i) (ih leaf) + +theorem exists_leafAtNode : ∀ {n : Nat} (leaf : Slots branch n) (level : Fin n), + ∃ suffix : Slots branch (Nodes.height (GeometricPath.nodeAtLevel leaf level)), + (Nodes.path (GeometricPath.nodeAtLevel leaf level)).slotEmbedding suffix = leaf := by + intro n + induction n with + | zero => intro leaf level; exact Fin.elim0 level + | succ n ih => + intro leaf level + refine Fin.lastCases ?_ (fun lower => ?_) level + · rw [GeometricPath.nodeAtLevel_last] + exact ⟨leaf, rfl⟩ + · rw [GeometricPath.nodeAtLevel_castSucc] + obtain ⟨suffix, hsuffix⟩ := ih leaf.2 lower + exact ⟨suffix, Prod.ext rfl hsuffix⟩ + +noncomputable def leafAtNode (leaf : Slots branch n) (level : Fin n) : + Slots branch (Nodes.height (GeometricPath.nodeAtLevel leaf level)) := + Classical.choose (exists_leafAtNode leaf level) + +theorem leafAtNode_embedding (leaf : Slots branch n) (level : Fin n) : + (Nodes.path (GeometricPath.nodeAtLevel leaf level)).slotEmbedding + (leafAtNode leaf level) = leaf := + Classical.choose_spec (exists_leafAtNode leaf level) + +theorem leafAtNode_unique (leaf : Slots branch n) (level : Fin n) + (suffix : Slots branch (Nodes.height (GeometricPath.nodeAtLevel leaf level))) + (hsuffix : (Nodes.path (GeometricPath.nodeAtLevel leaf level)).slotEmbedding suffix = leaf) : + suffix = leafAtNode leaf level := + (Nodes.path (GeometricPath.nodeAtLevel leaf level)).slotEmbedding_injective + (hsuffix.trans (leafAtNode_embedding leaf level).symm) + +theorem leafPath_split (leaf : Slots branch n) (level : Fin n) : + (Nodes.path (GeometricPath.nodeAtLevel leaf level)).append + (GeometricPath.leafPath (leafAtNode leaf level)) = GeometricPath.leafPath leaf := by + rw [append_leafPath, leafAtNode_embedding] + +end PerfectCompleteness.PathComposition + +end + + +namespace PerfectCompleteness.GeometricCutSplit + +open RecursiveSpaces DescendantSpaces +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +variable {branch : Nat → Nat} + +def PrefixDepth (branch : Nat → Nat) (cutoff : Nat) : Nat → Type + | 0 => Unit + | depth + 1 => Fin (branch (cutoff + depth)) × PrefixDepth branch cutoff depth + +instance prefixDepthFintype (branch : Nat → Nat) (cutoff depth : Nat) : + Fintype (PrefixDepth branch cutoff depth) := by + induction depth with + | zero => exact inferInstanceAs (Fintype Unit) + | succ depth ih => + letI : Fintype (PrefixDepth branch cutoff depth) := ih + exact inferInstanceAs (Fintype + (Fin (branch (cutoff + depth)) × PrefixDepth branch cutoff depth)) + +abbrev Prefix (branch : Nat → Nat) (root cutoff : Nat) := + PrefixDepth branch cutoff (root - cutoff) + +def prefixPathDepth (cutoff : Nat) : (depth : Nat) → + PrefixDepth branch cutoff depth → Path branch (cutoff + depth) cutoff + | 0, _ => .refl cutoff + | depth + 1, pref => .step pref.1 (prefixPathDepth cutoff depth pref.2) + +def splitDepth (cutoff : Nat) : (depth : Nat) → + Slots branch (cutoff + depth) ≃ PrefixDepth branch cutoff depth × Slots branch cutoff + | 0 => + { toFun := fun suffix => ((), suffix) + invFun := Prod.snd + left_inv := fun _ => rfl + right_inv := by rintro ⟨⟨⟩, suffix⟩; rfl } + | depth + 1 => + ((Equiv.refl (Fin (branch (cutoff + depth)))).prodCongr (splitDepth cutoff depth)).trans + (Equiv.prodAssoc _ _ _).symm + +theorem splitDepth_symm_eq_embedding (cutoff depth : Nat) + (pref : PrefixDepth branch cutoff depth) (suffix : Slots branch cutoff) : + (splitDepth cutoff depth).symm (pref, suffix) = + (prefixPathDepth cutoff depth pref).slotEmbedding suffix := by + revert pref + induction depth with + | zero => intro pref; rfl + | succ depth ih => + intro pref + change (pref.1, (splitDepth cutoff depth).symm (pref.2, suffix)) = + (pref.1, (prefixPathDepth cutoff depth pref.2).slotEmbedding suffix) + exact Prod.ext rfl (ih pref.2) + +def castPath {a b cutoff : Nat} (h : a = b) (p : Path branch a cutoff) : + Path branch b cutoff := h ▸ p + +theorem castPath_embedding {a b cutoff : Nat} (h : a = b) + (p : Path branch a cutoff) (suffix : Slots branch cutoff) : + (castPath h p).slotEmbedding suffix = + (Equiv.cast (congrArg (Slots branch) h)) (p.slotEmbedding suffix) := by + cases h + rfl + +variable {root cutoff : Nat} + +def prefixPath (hcut : cutoff ≤ root) (pref : Prefix branch root cutoff) : + Path branch root cutoff := + castPath (Nat.add_sub_of_le hcut) (prefixPathDepth cutoff (root - cutoff) pref) + +def joinEquiv (hcut : cutoff ≤ root) : + Prefix branch root cutoff × Slots branch cutoff ≃ Slots branch root := + (splitDepth cutoff (root - cutoff)).symm.trans + (Equiv.cast (congrArg (Slots branch) (Nat.add_sub_of_le hcut))) + +def splitEquiv (hcut : cutoff ≤ root) : + Slots branch root ≃ Prefix branch root cutoff × Slots branch cutoff := + (joinEquiv hcut).symm + +theorem joinEquiv_apply (hcut : cutoff ≤ root) + (pref : Prefix branch root cutoff) (suffix : Slots branch cutoff) : + joinEquiv hcut (pref, suffix) = (prefixPath hcut pref).slotEmbedding suffix := by + rw [prefixPath, castPath_embedding] + change (Equiv.cast (congrArg (Slots branch) (Nat.add_sub_of_le hcut))) + ((splitDepth cutoff (root - cutoff)).symm (pref, suffix)) = _ + exact congrArg (Equiv.cast (congrArg (Slots branch) (Nat.add_sub_of_le hcut))) + (splitDepth_symm_eq_embedding cutoff (root - cutoff) pref suffix) + +@[simp] theorem join_split (hcut : cutoff ≤ root) (leaf : Slots branch root) : + joinEquiv hcut (splitEquiv hcut leaf) = leaf := + (joinEquiv hcut).apply_symm_apply leaf + +@[simp] theorem split_embedding (hcut : cutoff ≤ root) + (pref : Prefix branch root cutoff) (suffix : Slots branch cutoff) : + splitEquiv hcut ((prefixPath hcut pref).slotEmbedding suffix) = (pref, suffix) := by + rw [← joinEquiv_apply] + exact (joinEquiv hcut).symm_apply_apply (pref, suffix) + +theorem split_embedding_eq (hcut : cutoff ≤ root) (leaf : Slots branch root) : + (prefixPath hcut (splitEquiv hcut leaf).1).slotEmbedding + (splitEquiv hcut leaf).2 = leaf := by + rw [← joinEquiv_apply] + exact join_split hcut leaf + +theorem leafPath_split (hcut : cutoff ≤ root) (leaf : Slots branch root) : + (prefixPath hcut (splitEquiv hcut leaf).1).append + (GeometricPath.leafPath (splitEquiv hcut leaf).2) = GeometricPath.leafPath leaf := by + rw [PathComposition.append_leafPath, split_embedding_eq] + +theorem prefix_nonempty (hcut : cutoff ≤ root) + (hbranch : ∀ k < root, 0 < branch k) : Nonempty (Prefix branch root cutoff) := by + obtain ⟨leaf⟩ := GeometricPath.slots_nonempty root hbranch + exact ⟨(splitEquiv hcut leaf).1⟩ + +noncomputable section + +def prefixLaw (hcut : cutoff ≤ root) (hbranch : ∀ k < root, 0 < branch k) : + FiniteDistribution (Prefix branch root cutoff) := by + letI := prefix_nonempty hcut hbranch + exact FiniteDistribution.uniform _ + +theorem law_split (hcut : cutoff ≤ root) (hbranch : ∀ k < root, 0 < branch k) : + (GeometricPath.law root hbranch).pushforward (splitEquiv hcut) = + (prefixLaw hcut hbranch).product + (GeometricPath.law cutoff + (fun k hk => hbranch k (Nat.lt_of_lt_of_le hk hcut))) := by + rw [← FiniteDistribution.transport_eq_pushforward] + apply FiniteDistribution.eq_of_weight_eq + intro pair + change (1 : ℝ) / (Fintype.card (Slots branch root) : ℝ) = + ((1 : ℝ) / (Fintype.card (Prefix branch root cutoff) : ℝ)) * + ((1 : ℝ) / (Fintype.card (Slots branch cutoff) : ℝ)) + rw [Fintype.card_congr (splitEquiv (branch := branch) hcut), Fintype.card_prod, Nat.cast_mul] + simp only [one_div_mul_one_div] + +theorem expectation_split (hcut : cutoff ≤ root) + (hbranch : ∀ k < root, 0 < branch k) + (f : Prefix branch root cutoff → Slots branch cutoff → ℝ) : + (GeometricPath.law root hbranch).expectation + (fun leaf => f (splitEquiv hcut leaf).1 (splitEquiv hcut leaf).2) = + (prefixLaw hcut hbranch).expectation (fun pref => + (GeometricPath.law cutoff + (fun k hk => hbranch k (Nat.lt_of_lt_of_le hk hcut))).expectation (f pref)) := by + rw [← FiniteDistribution.expectation_pushforward + (GeometricPath.law root hbranch) (splitEquiv hcut) (fun pair => f pair.1 pair.2), + law_split, FiniteDistribution.expectation_product] + +theorem probability_split (hcut : cutoff ≤ root) + (hbranch : ∀ k < root, 0 < branch k) + (event : Prefix branch root cutoff × Slots branch cutoff → Bool) : + (GeometricPath.law root hbranch).probability (fun leaf => event (splitEquiv hcut leaf)) = + (prefixLaw hcut hbranch).expectation (fun pref => + (GeometricPath.law cutoff + (fun k hk => hbranch k (Nat.lt_of_lt_of_le hk hcut))).probability + (fun suffix => event (pref, suffix))) := by + rw [← FiniteDistribution.probability_pushforward + (GeometricPath.law root hbranch) (splitEquiv hcut) event, law_split] + simp only [FiniteDistribution.probability, FiniteDistribution.expectation, + FiniteDistribution.product, Fintype.sum_prod_type, Finset.mul_sum, mul_ite, mul_zero] + +end +end PerfectCompleteness.GeometricCutSplit + + + +namespace PerfectCompleteness.GeometricCutMixture + +open RecursiveSpaces DescendantSpaces +open UniqueGamesTheorem.Foundations.Games + +noncomputable section + +variable {branch : Nat → Nat} {root cutoff : Nat} + {Γ : Type*} [Fintype Γ] + +theorem mixture_split (hcut : cutoff ≤ root) + (hbranch : ∀ k < root, 0 < branch k) + (experiment : Slots branch root → FiniteDistribution Γ) : + (GeometricPath.law root hbranch).mixture experiment = + (GeometricCutSplit.prefixLaw hcut hbranch).mixture (fun pref => + (GeometricPath.law cutoff + (fun k hk => hbranch k (Nat.lt_of_lt_of_le hk hcut))).mixture + (fun suffix => experiment (GeometricCutSplit.joinEquiv hcut (pref, suffix)))) := by + apply FiniteDistribution.eq_of_weight_eq + intro x + change (GeometricPath.law root hbranch).expectation (fun leaf => (experiment leaf).weight x) = + (GeometricCutSplit.prefixLaw hcut hbranch).expectation (fun pref => + (GeometricPath.law cutoff + (fun k hk => hbranch k (Nat.lt_of_lt_of_le hk hcut))).expectation + (fun suffix => (experiment (GeometricCutSplit.joinEquiv hcut (pref, suffix))).weight x)) + simpa only [Prod.mk.eta, GeometricCutSplit.join_split] using + (GeometricCutSplit.expectation_split hcut hbranch + (fun pref suffix => (experiment (GeometricCutSplit.joinEquiv hcut (pref, suffix))).weight x)) + +theorem path_mixture_split (hcut : cutoff ≤ root) + (hbranch : ∀ k < root, 0 < branch k) + (experiment : Path branch root 0 → FiniteDistribution Γ) : + (GeometricPath.law root hbranch).mixture + (fun leaf => experiment (GeometricPath.leafPath leaf)) = + (GeometricCutSplit.prefixLaw hcut hbranch).mixture (fun pref => + (GeometricPath.law cutoff + (fun k hk => hbranch k (Nat.lt_of_lt_of_le hk hcut))).mixture + (fun suffix => experiment ((GeometricCutSplit.prefixPath hcut pref).append + (GeometricPath.leafPath suffix)))) := by + rw [mixture_split hcut hbranch] + apply congrArg ((GeometricCutSplit.prefixLaw hcut hbranch).mixture) + funext pref + apply congrArg ((GeometricPath.law cutoff + (fun k hk => hbranch k (Nat.lt_of_lt_of_le hk hcut))).mixture) + funext suffix + rw [GeometricCutSplit.joinEquiv_apply, PathComposition.append_leafPath] + +end +end PerfectCompleteness.GeometricCutMixture + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalPairCoarse.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalPairCoarse.lean new file mode 100644 index 0000000000000000000000000000000000000000..2d19f85a0152421f5237e4fdf64054610106dac5 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalPairCoarse.lean @@ -0,0 +1,263 @@ +import OAI.Computability.PerfectCompleteness.Algebra.MatrixRowQuotientLaw +import OAI.Computability.PerfectCompleteness.Foundations.DependentPredictionDifferenceLemmas +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalAdviceExperimentLemmas +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalAgreementMean +import OAI.Computability.PerfectCompleteness.Sampling.CommonProductVariationLemmas +import OAI.Computability.PerfectCompleteness.Sampling.RationalFiniteLawLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.HierarchicalPairCoarse + +open TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) +open scoped BigOperators Classical + +noncomputable section + +attribute [local instance] linearMapFintype + +private theorem probability_product {A B : Type*} [Fintype A] [Fintype B] + (μ : FiniteDistribution A) (ν : FiniteDistribution B) (event : A × B → Bool) : + (μ.product ν).probability event = + μ.expectation (fun a => ν.probability (fun b => event (a, b))) := by + simp only [FiniteDistribution.probability, FiniteDistribution.expectation, + FiniteDistribution.product, Fintype.sum_prod_type, Finset.mul_sum, mul_ite, mul_zero] + +private theorem product_swap {A B : Type*} [Fintype A] [Fintype B] + (μ : FiniteDistribution A) (ν : FiniteDistribution B) : + (μ.product ν).pushforward (Equiv.prodComm A B) = ν.product μ := by + rw [← FiniteDistribution.transport_eq_pushforward] + apply FiniteDistribution.eq_of_weight_eq + intro z + exact mul_comm _ _ + +private theorem product_fst {A B : Type*} [Fintype A] [Fintype B] + (μ : FiniteDistribution A) (ν : FiniteDistribution B) : + (μ.product ν).pushforward Prod.fst = μ := by + calc + _ = ((μ.product ν).pushforward (Equiv.prodComm A B)).pushforward Prod.snd := + (FiniteDistribution.pushforward_comp _ _ _).symm + _ = _ := by rw [product_swap, FiniteDistribution.product_pushforward_snd] + +private theorem attach_observation {A B C Γ : Type*} + [Fintype A] [Fintype B] [Fintype C] [Fintype Γ] + (μ : FiniteDistribution A) (ν : FiniteDistribution B) + (g : B → C) (f : A × C → Γ) : + (μ.product ν).pushforward (fun z => f (z.1, g z.2)) = + (μ.product (ν.pushforward g)).pushforward f := by + have h : (μ.product ν).pushforward (fun z => (z.1, g z.2)) = + μ.product (ν.pushforward g) := by + simpa only [id_eq, FiniteDistribution.pushforward_id] using + FiniteDistribution.product_pushforward μ ν id g + calc + _ = ((μ.product ν).pushforward (fun z => (z.1, g z.2))).pushforward f := + (FiniteDistribution.pushforward_comp _ _ _).symm + _ = _ := congrArg (fun ρ : FiniteDistribution (A × C) => ρ.pushforward f) h + +variable {branch rows : Nat → Nat} {n t : Nat} {Ω : Type*} [Fintype Ω] + (S : HierarchicalAdviceExperiment.Experiment branch rows n t Ω) + +abbrev PairRecord := HierarchicalAgreementMean.PairRecord (rows := rows) S.slots S.upper +abbrev Matrix := HierarchicalMatrixTable.Matrix (rows := rows) S.slots S.upper +abbrev OldRecord := HierarchicalAdviceExperiment.Background S × Matrix S + +local instance backgroundFintype : Fintype (HierarchicalAdviceExperiment.Background S) := + Fintype.ofFinite _ + +local instance rowSpaceFintype : Fintype (NodeEmbedding.RowSpace S.slots S.upper) := + Fintype.ofFinite _ + +local instance inputFintype : + (b : HierarchicalAdviceExperiment.Background S) → + Fintype (HierarchicalAdviceExperiment.Input S b) := fun _ => linearMapFintype + +def oldRecord (record : PairRecord S) : OldRecord S := (record.1, record.2.1) + +def coarseOld (record : OldRecord S) : HierarchicalAdviceExperiment.Coarse S := + ⟨record.1, MatrixRowQuotient.projectMatrix + (HierarchicalFrozenTables.knownRows S.slots S.upper S.lowerLevel record.1) record.2⟩ + +def coarse (record : PairRecord S) : HierarchicalAdviceExperiment.Coarse S := + coarseOld S (oldRecord S record) + +def observeOld (r : Nat) + (sample : HierarchicalAdviceExperiment.Advice S r × OldRecord S) : + HierarchicalAdviceExperiment.Coarse S × HierarchicalAdviceExperiment.Advice S r := + (coarseOld S sample.2, sample.1) + +def observe (r : Nat) + (sample : HierarchicalAdviceExperiment.Advice S r × PairRecord S) : + HierarchicalAdviceExperiment.Coarse S × HierarchicalAdviceExperiment.Advice S r := + (coarse S sample.2, sample.1) + +private theorem bucket_oldMatrix_law (hrows : 0 < rows (Nodes.height S.upper)) : + (HierarchicalAgreementMean.bucketLaw S.slots S.upper hrows).pushforward + (fun sample => BucketMatrixResampling.assembledMatrix + (NodeEmbedding.RowSpace S.slots S.upper) (rows (Nodes.height S.upper)) sample.2.1) = + FiniteDistribution.uniform (Matrix S) := by + let : Nonempty (BucketSampler.Direction (rows (Nodes.height S.upper))) := + ⟨BucketUniform.coordinateDirection ⟨0, hrows⟩⟩ + let directions := FiniteDistribution.uniform (BucketSampler.Direction (rows (Nodes.height S.upper))) + let buckets := BucketSampler.tapeLaw (rows (Nodes.height S.upper)) + (FiniteDistribution.uniform (NodeEmbedding.RowSpace S.slots S.upper)) + let fresh := FiniteDistribution.uniform (NodeEmbedding.RowSpace S.slots S.upper) + have hdrop : (HierarchicalAgreementMean.bucketLaw S.slots S.upper hrows).pushforward + (fun sample => sample.2.1) = buckets := by + calc + _ = ((directions.product (buckets.product fresh)).pushforward Prod.snd).pushforward + Prod.fst := (FiniteDistribution.pushforward_comp _ _ _).symm + _ = _ := by rw [FiniteDistribution.product_pushforward_snd, product_fst] + calc + _ = ((HierarchicalAgreementMean.bucketLaw S.slots S.upper hrows).pushforward + (fun sample => sample.2.1)).pushforward + (BucketMatrixResampling.assembledMatrix (NodeEmbedding.RowSpace S.slots S.upper) + (rows (Nodes.height S.upper))) := (FiniteDistribution.pushforward_comp _ _ _).symm + _ = buckets.pushforward + (BucketMatrixResampling.assembledMatrix (NodeEmbedding.RowSpace S.slots S.upper) + (rows (Nodes.height S.upper))) := by rw [hdrop] + _ = _ := BucketMatrixResampling.uniform_assembledMatrix_law + (NodeEmbedding.RowSpace S.slots S.upper) (rows (Nodes.height S.upper)) + +theorem reference_oldRecord_law + (backgroundLaw : FiniteDistribution (HierarchicalAdviceExperiment.Background S)) + (hrows : 0 < rows (Nodes.height S.upper)) : + (HierarchicalAgreementMean.referenceLaw S.slots S.upper backgroundLaw hrows).pushforward + (oldRecord S) = backgroundLaw.product (FiniteDistribution.uniform (Matrix S)) := by + unfold HierarchicalAgreementMean.referenceLaw + rw [FiniteDistribution.pushforward_comp] + change (backgroundLaw.product (HierarchicalAgreementMean.bucketLaw S.slots S.upper hrows)).pushforward + (fun sample => (sample.1, + BucketMatrixResampling.assembledMatrix (NodeEmbedding.RowSpace S.slots S.upper) + (rows (Nodes.height S.upper)) sample.2.2.1)) = _ + have h := FiniteDistribution.product_pushforward backgroundLaw + (HierarchicalAgreementMean.bucketLaw S.slots S.upper hrows) id + (fun sample => BucketMatrixResampling.assembledMatrix + (NodeEmbedding.RowSpace S.slots S.upper) (rows (Nodes.height S.upper)) sample.2.1) + simpa only [id_eq, FiniteDistribution.pushforward_id, bucket_oldMatrix_law] using h + +theorem uniform_projectMatrix (background : HierarchicalAdviceExperiment.Background S) : + (FiniteDistribution.uniform (Matrix S)).pushforward + (MatrixRowQuotient.projectMatrix + (HierarchicalFrozenTables.knownRows S.slots S.upper S.lowerLevel background)) = + FiniteDistribution.uniform + (HierarchicalAdviceExperiment.Input S background →ₗ[F2] Block rows S.upper) := + UniformLinearImage.uniform_pushforward_linearMap + (MatrixRowQuotientLaw.projectMatrixLinear + (HierarchicalFrozenTables.knownRows S.slots S.upper S.lowerLevel background)) + (MatrixRowQuotient.projectMatrix_surjective + (HierarchicalFrozenTables.knownRows S.slots S.upper S.lowerLevel background)) + +theorem observe_oldRecord_law (μ : FiniteDistribution (PairRecord S)) (r : Nat) : + ((HierarchicalAdviceExperiment.adviceLaw S r).product μ).pushforward (observe S r) = + ((HierarchicalAdviceExperiment.adviceLaw S r).product (μ.pushforward (oldRecord S))).pushforward + (observeOld S r) := + attach_observation (HierarchicalAdviceExperiment.adviceLaw S r) μ (oldRecord S) (observeOld S r) + +theorem reference_observe_law + (backgroundLaw : FiniteDistribution (HierarchicalAdviceExperiment.Background S)) + (hrows : 0 < rows (Nodes.height S.upper)) (r : Nat) : + ((HierarchicalAdviceExperiment.adviceLaw S r).product + (HierarchicalAgreementMean.referenceLaw S.slots S.upper backgroundLaw hrows)).pushforward + (observe S r) = + (HierarchicalAdviceExperiment.referenceLaw S backgroundLaw r).pushforward + (HierarchicalAdviceExperiment.referenceObserve S r) := by + rw [observe_oldRecord_law, reference_oldRecord_law] + apply SigmaObservation.eq_of_probability_eq + intro event + calc + _ = (HierarchicalAdviceExperiment.adviceLaw S r).expectation (fun advice => + backgroundLaw.expectation (fun background => + (FiniteDistribution.uniform (Matrix S)).probability (fun X => + event (⟨background, MatrixRowQuotient.projectMatrix + (HierarchicalFrozenTables.knownRows S.slots S.upper S.lowerLevel background) X⟩, + advice)))) := by + rw [FiniteDistribution.probability_pushforward, probability_product] + apply FiniteDistribution.expectation_congr + intro advice + exact probability_product backgroundLaw (FiniteDistribution.uniform (Matrix S)) _ + _ = backgroundLaw.expectation (fun background => + (HierarchicalAdviceExperiment.adviceLaw S r).expectation (fun advice => + (FiniteDistribution.uniform (Matrix S)).probability (fun X => + event (⟨background, MatrixRowQuotient.projectMatrix + (HierarchicalFrozenTables.knownRows S.slots S.upper S.lowerLevel background) X⟩, + advice)))) := FiniteDistribution.expectation_comm _ _ _ + _ = backgroundLaw.expectation (fun background => + (HierarchicalAdviceExperiment.adviceLaw S r).expectation (fun advice => + (FiniteDistribution.uniform + (HierarchicalAdviceExperiment.Input S background →ₗ[F2] Block rows S.upper)).probability + (fun X => event (⟨background, X⟩, advice)))) := by + apply FiniteDistribution.expectation_congr + intro background + apply FiniteDistribution.expectation_congr + intro advice + have h := congrArg + (fun μ : FiniteDistribution + (HierarchicalAdviceExperiment.Input S background →ₗ[F2] Block rows S.upper) => + μ.probability (fun X => event (⟨background, X⟩, advice))) + (uniform_projectMatrix S background) + simpa only [FiniteDistribution.probability_pushforward] using h + _ = _ := by + symm + rw [FiniteDistribution.probability_pushforward] + change (CompletionSoundness.sigmaLaw backgroundLaw + (fun background => GoodAdviceEvents.law (HierarchicalAdviceExperiment.Input S background) + (Block rows S.upper) r)).probability + (fun sample => event (⟨sample.1, sample.2.2⟩, sample.2.1)) = _ + rw [CompletionSoundness.sigmaLaw_probability] + apply FiniteDistribution.expectation_congr + intro background + exact probability_product (HierarchicalAdviceExperiment.adviceLaw S r) + (FiniteDistribution.uniform + (HierarchicalAdviceExperiment.Input S background →ₗ[F2] Block rows S.upper)) _ + +theorem observed_totalVariation_le (μ : FiniteDistribution (PairRecord S)) + (backgroundLaw : FiniteDistribution (HierarchicalAdviceExperiment.Background S)) + (hrows : 0 < rows (Nodes.height S.upper)) (r : Nat) : + (((HierarchicalAdviceExperiment.adviceLaw S r).product μ).pushforward (observe S r)).totalVariation + ((HierarchicalAdviceExperiment.referenceLaw S backgroundLaw r).pushforward + (HierarchicalAdviceExperiment.referenceObserve S r)) ≤ + μ.totalVariation (HierarchicalAgreementMean.referenceLaw S.slots S.upper backgroundLaw hrows) := by + rw [← reference_observe_law S backgroundLaw hrows r] + exact CommonProductVariation.observed_product_le (HierarchicalAdviceExperiment.adviceLaw S r) + μ (HierarchicalAgreementMean.referenceLaw S.slots S.upper backgroundLaw hrows) (observe S r) + +theorem original_observe_law_of_oldRecord (μ : FiniteDistribution (PairRecord S)) (r : Nat) + (hmarginal : μ.pushforward (oldRecord S) = S.original.pushforward + (fun x => (HierarchicalAdviceExperiment.background S x, HierarchicalAdviceExperiment.matrix S x))) : + ((HierarchicalAdviceExperiment.adviceLaw S r).product μ).pushforward (observe S r) = + (HierarchicalAdviceExperiment.originalLaw S r).pushforward + (HierarchicalAdviceExperiment.observe S r) := by + rw [observe_oldRecord_law, hmarginal] + rw [← attach_observation (HierarchicalAdviceExperiment.adviceLaw S r) S.original + (fun x => (HierarchicalAdviceExperiment.background S x, HierarchicalAdviceExperiment.matrix S x)) + (observeOld S r)] + calc + _ = (((HierarchicalAdviceExperiment.adviceLaw S r).product S.original).pushforward + (Equiv.prodComm (HierarchicalAdviceExperiment.Advice S r) Ω)).pushforward + (HierarchicalAdviceExperiment.observe S r) := + (FiniteDistribution.pushforward_comp _ _ _).symm + _ = _ := by simp only [product_swap, HierarchicalAdviceExperiment.originalLaw] + +theorem original_totalVariation_le_of_oldRecord (μ : FiniteDistribution (PairRecord S)) + (backgroundLaw : FiniteDistribution (HierarchicalAdviceExperiment.Background S)) + (hrows : 0 < rows (Nodes.height S.upper)) (r : Nat) + (hmarginal : μ.pushforward (oldRecord S) = S.original.pushforward + (fun x => (HierarchicalAdviceExperiment.background S x, HierarchicalAdviceExperiment.matrix S x))) : + ((HierarchicalAdviceExperiment.originalLaw S r).pushforward + (HierarchicalAdviceExperiment.observe S r)).totalVariation + ((HierarchicalAdviceExperiment.referenceLaw S backgroundLaw r).pushforward + (HierarchicalAdviceExperiment.referenceObserve S r)) ≤ + μ.totalVariation (HierarchicalAgreementMean.referenceLaw S.slots S.upper backgroundLaw hrows) := by + rw [← original_observe_law_of_oldRecord S μ r hmarginal] + exact observed_totalVariation_le S μ backgroundLaw hrows r + +end +end PerfectCompleteness.HierarchicalPairCoarse + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalPrediction.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalPrediction.lean new file mode 100644 index 0000000000000000000000000000000000000000..b6f3604b1ad065fdfcaa1d5e2e6433387ae90b4b --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalPrediction.lean @@ -0,0 +1,162 @@ +import OAI.Computability.PerfectCompleteness.Decoding.RepresentativeBucketCollisionLemmas +import OAI.Computability.PerfectCompleteness.Foundations.GoodAdviceEventsLemmas +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalFrozenTablesLemmas + +namespace OAI + + +namespace PerfectCompleteness.HierarchicalPrediction + +noncomputable section + +open scoped Classical +open TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype + +section Selection + +variable {E K Y : Type*} [AddCommGroup E] [Module F2 E] + [AddCommGroup K] [Module F2 K] [FiniteDimensional F2 E] + [FiniteDimensional F2 K] [Fintype E] [Fintype K] [Fintype Y] + +def selectedValue (f : (E →ₗ[F2] K) → Option Y) (r : Nat) (ρ : ℝ) + (A : ManyGoodRows.RowMap K r) (X : E →ₗ[F2] K) : Option Y := + if h : ManyGoodRows.GoodRow f r ρ A (A.comp X) then + some (ManyGoodRows.selectWitness f r ρ A (A.comp X) h).value + else none + +omit [FiniteDimensional F2 E] [FiniteDimensional F2 K] [Fintype Y] in +theorem selectedValue_of_I (f : (E →ₗ[F2] K) → Option Y) (r : Nat) (ρ : ℝ) + (A : ManyGoodRows.RowMap K r) (X : E →ₗ[F2] K) + (hI : GoodAdviceEvents.I f r ρ (A, X) = true) : + ∃ y, selectedValue f r ρ A X = some y ∧ f X = some y := by + unfold GoodAdviceEvents.I GoodAdviceEvents.selectedAgreement at hI + by_cases h : ManyGoodRows.GoodRow f r ρ A (A.comp X) + · simp only [dite_eq_left h, decide_eq_true_eq] at hI + exact ⟨(ManyGoodRows.selectWitness f r ρ A (A.comp X) h).value, + by simp only [selectedValue, dite_eq_left h], hI.2⟩ + · simp only [dite_eq_right h, Bool.false_eq_true] at hI + +end Selection + +variable {branch rows : Nat → Nat} {n t : Nat} + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (upper : Nodes branch n) (lowerLevel : Nat) + (background : HierarchicalMatrixTable.Background (rows := rows) slots upper) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + +abbrev quotientMatrix (X : HierarchicalMatrixTable.Matrix (rows := rows) slots upper) := + MatrixRowQuotient.projectMatrix + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) X + +def affinePrediction (X : HierarchicalMatrixTable.Matrix (rows := rows) slots upper) + (y : Block rows upper × HierarchicalMatrixTable.SideOutput (rows := rows) upper) : + Block rows upper := + X (RepresentativeMatrixTable.correctionFunctional (TreeCanonical.numberedSlots slots) + (NodeEmbedding.RowSpace slots upper) (HierarchicalMatrixTable.other slots upper background) + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + (HierarchicalFrozenTables.sectionMap slots upper lowerLevel background) + (HierarchicalFrozenTables.sectionMap_spec slots upper lowerLevel background) y.2) + y.1 + +variable (lower : Nodes branch n) (hne : upper ≠ lower) (a : Block rows lower) + +def rightUpper (X : HierarchicalMatrixTable.Matrix (rows := rows) slots upper) : + Block rows upper := + (KeyStrategy.response σ .right (TreeCanonical.numberedSlots slots) + (BlockQuotient.projectBlock lower a ∘ + HierarchicalMatrixTable.displayed slots upper background X)).2.1 ⟨upper, hne⟩ + +def LowerAccepts (X : HierarchicalMatrixTable.Matrix (rows := rows) slots upper) : Prop := + CanonicalEdges.coarsen (TreeCanonical.numberedSlots slots) + (HierarchicalMatrixTable.displayed slots upper background X) + (BlockQuotient.projectBlock lower a) + (KeyStrategy.label σ .left (TreeCanonical.numberedSlots slots) + (HierarchicalMatrixTable.displayed slots upper background X)) = + KeyStrategy.label σ .right (TreeCanonical.numberedSlots slots) + (BlockQuotient.projectBlock lower a ∘ + HierarchicalMatrixTable.displayed slots upper background X) + +theorem rightUpper_eq_raw (X : HierarchicalMatrixTable.Matrix (rows := rows) slots upper) + (hacc : LowerAccepts slots upper background σ lower a X) : + rightUpper slots upper background σ lower hne a X = + (CanonicalMatrixTable.response (TreeCanonical.numberedSlots slots) + (NodeEmbedding.RowSpace slots upper) (HierarchicalMatrixTable.other slots upper background) + σ X).1 := by + unfold LowerAccepts at hacc + rw [CanonicalEdges.coarsen_eq_iff] at hacc + have hcoordinate := congrArg (fun z => z.2.1 ⟨upper, hne⟩) hacc + have hraw := congrArg Prod.fst + (HierarchicalMatrixTable.response_eq_split_response slots upper σ background X) + exact hcoordinate.symm.trans hraw.symm + +variable {Ω : Type*} [Fintype Ω] + (original : FiniteDistribution Ω) (arrays : Ω → Arrays slots rows) + (lowerEvent : Ω → Bool) (κ : ℝ) + +theorem table_some_iff (X : HierarchicalMatrixTable.Matrix (rows := rows) slots upper) + (y : Block rows upper × HierarchicalMatrixTable.SideOutput (rows := rows) upper) : + HierarchicalUsefulness.table slots upper lowerLevel original arrays lowerEvent κ σ background + (quotientMatrix slots upper lowerLevel background X) = some y ↔ + HierarchicalUsefulness.mark slots upper lowerLevel original arrays lowerEvent κ + ⟨background, quotientMatrix slots upper lowerLevel background X⟩ = true ∧ + RepresentativeMatrixTable.response (TreeCanonical.numberedSlots slots) + (NodeEmbedding.RowSpace slots upper) (HierarchicalMatrixTable.other slots upper background) + σ (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + (HierarchicalFrozenTables.sectionMap slots upper lowerLevel background) X = y := by + unfold HierarchicalUsefulness.table HierarchicalFrozenTables.table + RepresentativeMatrixTable.partialTable RepresentativeMatrixTable.response + RepresentativeMatrixTable.representative + split <;> simp_all + +theorem I_implies_mark (r : Nat) (ρ : ℝ) + (A : ManyGoodRows.RowMap (Block rows upper) r) + (X : HierarchicalMatrixTable.Matrix (rows := rows) slots upper) + (hI : GoodAdviceEvents.I + (HierarchicalUsefulness.table slots upper lowerLevel original arrays lowerEvent κ σ background) + r ρ (A, quotientMatrix slots upper lowerLevel background X) = true) : + HierarchicalUsefulness.mark slots upper lowerLevel original arrays lowerEvent κ + ⟨background, quotientMatrix slots upper lowerLevel background X⟩ = true := by + obtain ⟨y, _, hy⟩ := selectedValue_of_I _ r ρ A _ hI + exact ((table_some_iff slots upper lowerLevel background σ original arrays lowerEvent κ X y).mp hy).1 + +def prediction (r : Nat) (ρ : ℝ) (A : ManyGoodRows.RowMap (Block rows upper) r) + (X : HierarchicalMatrixTable.Matrix (rows := rows) slots upper) : Bool := + let f := HierarchicalUsefulness.table slots upper lowerLevel original arrays lowerEvent κ σ background + let Q := quotientMatrix slots upper lowerLevel background X + GoodAdviceEvents.J f r ρ (A, Q) && + match selectedValue f r ρ A Q with + | none => false + | some y => decide (rightUpper slots upper background σ lower hne a X = + affinePrediction slots upper lowerLevel background X y) + +theorem lower_accepts_predicts (r : Nat) (ρ : ℝ) + (A : ManyGoodRows.RowMap (Block rows upper) r) + (X : HierarchicalMatrixTable.Matrix (rows := rows) slots upper) + (hacc : LowerAccepts slots upper background σ lower a X) + (hI : GoodAdviceEvents.I + (HierarchicalUsefulness.table slots upper lowerLevel original arrays lowerEvent κ σ background) + r ρ (A, quotientMatrix slots upper lowerLevel background X) = true) : + prediction slots upper lowerLevel background σ lower hne a original arrays lowerEvent κ r ρ A X = true := by + obtain ⟨y, hselected, hy⟩ := selectedValue_of_I _ r ρ A _ hI + have hmatch := ((table_some_iff slots upper lowerLevel background σ original arrays + lowerEvent κ X y).mp hy).2 + have hraw := RepresentativeDecoder.raw_selected_output_at_match + (TreeCanonical.numberedSlots slots) (NodeEmbedding.RowSpace slots upper) + (HierarchicalMatrixTable.other slots upper background) + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + (HierarchicalFrozenTables.sectionMap slots upper lowerLevel background) + (HierarchicalFrozenTables.sectionMap_spec slots upper lowerLevel background) σ + (HierarchicalFrozenTables.determined slots upper lowerLevel background) X y hmatch + have hright : rightUpper slots upper background σ lower hne a X = + affinePrediction slots upper lowerLevel background X y := + (rightUpper_eq_raw slots upper background σ lower hne a X hacc).trans hraw + have hJ := GoodAdviceEvents.I_implies_J _ r ρ _ hI + simp only [prediction, hJ, hselected, hright, decide_true, Bool.and_true] + +end +end PerfectCompleteness.HierarchicalPrediction + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalProjectedExperimentLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalProjectedExperimentLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..1c0c05e0a0293fff9ddb46dad7da0c685381615a --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalProjectedExperimentLemmas.lean @@ -0,0 +1,234 @@ +import OAI.Computability.PerfectCompleteness.Decoding.ChildBlockProjection +import OAI.Computability.PerfectCompleteness.Foundations.DependentPredictionDifferenceLemmas +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalAdviceExperimentLemmas +import OAI.Computability.PerfectCompleteness.Machines.WholeArrayInteriorOwnInputLaw +import OAI.Computability.PerfectCompleteness.Sampling.CandidateCoupling + +namespace OAI + + +namespace PerfectCompleteness.HierarchicalProjectedExperiment + +noncomputable section + +open scoped Classical +open TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype + +variable {branch rows repeats : Nat → Nat} {n t : Nat} {K : Type*} [Fintype K] + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (projected : K → RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (projection : ∀ k s j, MixedSupport.Projection (slots s j) (projected k s j)) + (upper : Nodes branch n) (lowerLevel : Nat) + (lower : K → Nodes branch n) + (cut : ∀ k, OwnInputReference.Cut upper (lower k)) + (direction : ∀ k, Block rows (lower k)) + +abbrev Sample := (k : K) × WholeArraySampler.Tape rows repeats + (WholeArrayInteriorOwnInputLaw.fullPath upper (lower k) (cut k)) (projected k) + +def originalLaw (outer : FiniteDistribution K) : + FiniteDistribution (Sample (rows := rows) (repeats := repeats) projected upper lower cut) := + CompletionSoundness.sigmaLaw outer (fun k => WholeArraySampler.tapeLaw rows repeats + (WholeArrayInteriorOwnInputLaw.fullPath upper (lower k) (cut k)) (projected k)) + +def arrays (x : Sample (rows := rows) (repeats := repeats) projected upper lower cut) : + Arrays slots rows := + ChildBlockProjection.arraysPullback rows (projection x.1) + (WholeArraySampler.evaluate rows repeats + (WholeArrayInteriorOwnInputLaw.fullPath upper (lower x.1) (cut x.1)) (projected x.1) x.2) + +def experiment (outer : FiniteDistribution K) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) : + HierarchicalAdviceExperiment.Experiment branch rows n t + (Sample (rows := rows) (repeats := repeats) projected upper lower cut) where + slots := slots + upper := upper + lowerLevel := lowerLevel + arrays := arrays slots projected projection upper lower cut + lowerNode x := lower x.1 + separate x := (cut x.1).upper_ne_lower + direction x := direction x.1 + original := originalLaw projected upper lower cut outer + strategy := σ + +abbrev Advice (r : Nat) := ManyGoodRows.RowMap (Block rows upper) r + +abbrev RawSample (r : Nat) := + (A : Advice (rows := rows) upper r) × (k : K) × + OwnInputReference.RawSample (projected k) rows upper (lower k) (LinearMap.ker A) repeats (cut k) + +def rawLaw (outer : FiniteDistribution K) (r : Nat) : + FiniteDistribution (RawSample (rows := rows) (repeats := repeats) projected upper lower cut r) := + CompletionSoundness.sigmaLaw (FiniteDistribution.uniform (Advice (rows := rows) upper r)) + (fun A => CompletionSoundness.sigmaLaw outer (fun k => + OwnInputReference.rawLaw (projected k) rows upper (lower k) (LinearMap.ker A) repeats (cut k) + (WholeArrayInteriorOwnInputLaw.exteriorLaw rows repeats (projected k) upper (lower k) (cut k)))) + +def rawRead (r : Nat) + (x : Sample (rows := rows) (repeats := repeats) projected upper lower cut × + Advice (rows := rows) upper r) : + RawSample (rows := rows) (repeats := repeats) projected upper lower cut r := + ⟨x.2, x.1.1, WholeArrayInteriorOwnInputLaw.exposedRead rows repeats (projected x.1.1) upper + (lower x.1.1) (cut x.1.1) (LinearMap.ker x.2) x.1.2⟩ + +theorem rawRead_expectation (outer : FiniteDistribution K) (r : Nat) + (f : RawSample (rows := rows) (repeats := repeats) projected upper lower cut r → ℝ) : + ((originalLaw projected upper lower cut outer).product + (FiniteDistribution.uniform (Advice (rows := rows) upper r))).expectation + (fun x => f (rawRead projected upper lower cut r x)) = + (rawLaw projected upper lower cut outer r).expectation f := by + rw [FiniteDistribution.expectation_product] + rw [FiniteDistribution.expectation_comm] + unfold rawLaw + rw [CandidateCoupling.expectation_sigmaLaw] + apply FiniteDistribution.expectation_congr + intro A + unfold originalLaw + rw [CandidateCoupling.expectation_sigmaLaw, CandidateCoupling.expectation_sigmaLaw] + apply FiniteDistribution.expectation_congr + intro k + have h := WholeArrayInteriorOwnInputLaw.exposedRead_law rows repeats (projected k) upper + (lower k) (cut k) (LinearMap.ker A) + rw [← h, FiniteDistribution.expectation_pushforward] + rfl + +theorem rawRead_law (outer : FiniteDistribution K) (r : Nat) : + ((originalLaw (rows := rows) (repeats := repeats) projected upper lower cut outer).product + (FiniteDistribution.uniform (Advice (rows := rows) upper r))).pushforward + (rawRead projected upper lower cut r) = + rawLaw projected upper lower cut outer r := by + apply SigmaObservation.eq_of_probability_eq + intro event + rw [FiniteDistribution.probability_pushforward, + CandidateCoupling.probability_eq_expectation, + CandidateCoupling.probability_eq_expectation] + exact rawRead_expectation projected upper lower cut outer r + (fun x => if event x then 1 else 0) + +theorem experiment_rawRead_law (outer : FiniteDistribution K) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) (r : Nat) : + (HierarchicalAdviceExperiment.originalLaw + (experiment (repeats := repeats) slots projected projection upper lowerLevel lower cut + direction outer σ) r).pushforward (rawRead projected upper lower cut r) = + rawLaw projected upper lower cut outer r := + rawRead_law projected upper lower cut outer r + +end +end PerfectCompleteness.HierarchicalProjectedExperiment + + +namespace PerfectCompleteness.HierarchicalWholeExperiment + +noncomputable section + +open scoped Classical +open TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype + +variable {branch rows repeats : Nat → Nat} {n t : Nat} {K : Type*} [Fintype K] + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (upper : Nodes branch n) (lowerLevel : Nat) + (lower : K → Nodes branch n) + (cut : ∀ k, OwnInputReference.Cut upper (lower k)) + (direction : ∀ k, Block rows (lower k)) + +abbrev Sample := (k : K) × WholeArraySampler.Tape rows repeats + (WholeArrayInteriorOwnInputLaw.fullPath upper (lower k) (cut k)) slots + +def originalLaw (outer : FiniteDistribution K) : + FiniteDistribution (Sample (rows := rows) (repeats := repeats) slots upper lower cut) := + CompletionSoundness.sigmaLaw outer (fun k => WholeArraySampler.tapeLaw rows repeats + (WholeArrayInteriorOwnInputLaw.fullPath upper (lower k) (cut k)) slots) + +def arrays (x : Sample (rows := rows) (repeats := repeats) slots upper lower cut) : + Arrays slots rows := + WholeArraySampler.evaluate rows repeats + (WholeArrayInteriorOwnInputLaw.fullPath upper (lower x.1) (cut x.1)) slots x.2 + +def experiment (outer : FiniteDistribution K) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) : + HierarchicalAdviceExperiment.Experiment branch rows n t + (Sample (rows := rows) (repeats := repeats) slots upper lower cut) where + slots := slots + upper := upper + lowerLevel := lowerLevel + arrays := arrays slots upper lower cut + lowerNode x := lower x.1 + separate x := (cut x.1).upper_ne_lower + direction x := direction x.1 + original := originalLaw slots upper lower cut outer + strategy := σ + +abbrev Advice (r : Nat) := ManyGoodRows.RowMap (Block rows upper) r + +abbrev RawSample (r : Nat) := + (A : Advice (rows := rows) upper r) × (k : K) × + OwnInputReference.RawSample slots rows upper (lower k) (LinearMap.ker A) repeats (cut k) + +def rawLaw (outer : FiniteDistribution K) (r : Nat) : + FiniteDistribution (RawSample (rows := rows) (repeats := repeats) slots upper lower cut r) := + CompletionSoundness.sigmaLaw (FiniteDistribution.uniform (Advice (rows := rows) upper r)) + (fun A => CompletionSoundness.sigmaLaw outer (fun k => + OwnInputReference.rawLaw slots rows upper (lower k) (LinearMap.ker A) repeats (cut k) + (WholeArrayInteriorOwnInputLaw.exteriorLaw rows repeats slots upper (lower k) (cut k)))) + +def rawRead (r : Nat) + (x : Sample (rows := rows) (repeats := repeats) slots upper lower cut × + Advice (rows := rows) upper r) : + RawSample (rows := rows) (repeats := repeats) slots upper lower cut r := + ⟨x.2, x.1.1, WholeArrayInteriorOwnInputLaw.exposedRead rows repeats slots upper + (lower x.1.1) (cut x.1.1) (LinearMap.ker x.2) x.1.2⟩ + +theorem rawRead_expectation (outer : FiniteDistribution K) (r : Nat) + (f : RawSample (rows := rows) (repeats := repeats) slots upper lower cut r → ℝ) : + ((originalLaw slots upper lower cut outer).product + (FiniteDistribution.uniform (Advice (rows := rows) upper r))).expectation + (fun x => f (rawRead slots upper lower cut r x)) = + (rawLaw slots upper lower cut outer r).expectation f := by + rw [FiniteDistribution.expectation_product] + rw [FiniteDistribution.expectation_comm] + unfold rawLaw + rw [CandidateCoupling.expectation_sigmaLaw] + apply FiniteDistribution.expectation_congr + intro A + unfold originalLaw + rw [CandidateCoupling.expectation_sigmaLaw, CandidateCoupling.expectation_sigmaLaw] + apply FiniteDistribution.expectation_congr + intro k + have h := WholeArrayInteriorOwnInputLaw.exposedRead_law rows repeats slots upper + (lower k) (cut k) (LinearMap.ker A) + rw [← h, FiniteDistribution.expectation_pushforward] + rfl + +theorem rawRead_law (outer : FiniteDistribution K) (r : Nat) : + ((originalLaw (rows := rows) (repeats := repeats) slots upper lower cut outer).product + (FiniteDistribution.uniform (Advice (rows := rows) upper r))).pushforward + (rawRead slots upper lower cut r) = + rawLaw slots upper lower cut outer r := by + apply SigmaObservation.eq_of_probability_eq + intro event + rw [FiniteDistribution.probability_pushforward, + CandidateCoupling.probability_eq_expectation, + CandidateCoupling.probability_eq_expectation] + exact rawRead_expectation slots upper lower cut outer r + (fun x => if event x then 1 else 0) + +theorem experiment_rawRead_law (outer : FiniteDistribution K) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) (r : Nat) : + (HierarchicalAdviceExperiment.originalLaw + (experiment (repeats := repeats) slots upper lowerLevel lower cut direction outer σ) r).pushforward + (rawRead slots upper lower cut r) = + rawLaw slots upper lower cut outer r := + rawRead_law slots upper lower cut outer r + +end +end PerfectCompleteness.HierarchicalWholeExperiment + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalProjectedPredictionLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalProjectedPredictionLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..52ebadd25851e6270ecd0cd261ab53bc287ada72 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalProjectedPredictionLemmas.lean @@ -0,0 +1,827 @@ +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalAdviceExperimentLemmas +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalProjectedExperimentLemmas +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalProjectedRawAverage +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalProjectedSliceLemmas +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalRawAverage +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalRawPredictionLemmas +import OAI.Computability.PerfectCompleteness.Foundations.WholeArrayRawAssembly +import OAI.Computability.PerfectCompleteness.Reduction.FixedComparisonErrorsLemmas + +namespace OAI + + +namespace PerfectCompleteness.HierarchicalProjectedPrediction + +noncomputable section + +open scoped Classical +open TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype + +variable {branch rows repeats : Nat → Nat} {n t : Nat} {K : Type*} [Fintype K] + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (projected : K → RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (projection : ∀ k s j, MixedSupport.Projection (slots s j) (projected k s j)) + (upper : Nodes branch n) (lowerLevel : Nat) + (lower : K → Nodes branch n) + (cut : ∀ k, OwnInputReference.Cut upper (lower k)) + (direction : ∀ k, Block rows (lower k)) + (outer : FiniteDistribution K) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (κ : ℝ) (r : Nat) (ρ : ℝ) + +local notation "S" => HierarchicalProjectedExperiment.experiment (rows := rows) (repeats := repeats) + slots projected projection upper lowerLevel lower cut direction outer σ + +def rawJ (sample : HierarchicalProjectedExperiment.RawSample (rows := rows) (repeats := repeats) + projected upper lower cut r) : Bool := + HierarchicalProjectedRawPrediction.rawJ slots (projected sample.2.1) (projection sample.2.1) + rows upper (lower sample.2.1) lowerLevel (S).original (S).arrays + (HierarchicalAdviceExperiment.lowerEvent S) κ σ ρ sample.1 + repeats (cut sample.2.1) sample.2.2 + +def rawPrediction + (sample : HierarchicalProjectedExperiment.RawSample (rows := rows) (repeats := repeats) + projected upper lower cut r) : Bool := + HierarchicalProjectedRawPrediction.rawPrediction slots (projected sample.2.1) (projection sample.2.1) + rows upper (lower sample.2.1) lowerLevel (S).original (S).arrays + (HierarchicalAdviceExperiment.lowerEvent S) κ σ ρ sample.1 + repeats (cut sample.2.1) (direction sample.2.1) sample.2.2 + + +theorem J_rawRead + (x : HierarchicalProjectedExperiment.Sample (rows := rows) (repeats := repeats) + projected upper lower cut × HierarchicalProjectedExperiment.Advice (rows := rows) upper r) : + HierarchicalAdviceExperiment.J S κ r ρ (HierarchicalAdviceExperiment.observe S r x) = + rawJ (repeats := repeats) slots projected projection upper lowerLevel lower cut direction outer σ κ r ρ + (HierarchicalProjectedExperiment.rawRead (rows := rows) (repeats := repeats) + projected upper lower cut r x) := by + rcases x with ⟨⟨k, ω⟩, A⟩ + exact (congrArg + (fun X : Arrays slots rows => + GoodAdviceEvents.J + (HierarchicalUsefulness.table slots upper lowerLevel (S).original (S).arrays + (HierarchicalAdviceExperiment.lowerEvent S) κ σ + (HierarchicalMatrixTable.backgroundOf slots upper X)) r ρ + (A, HierarchicalPrediction.quotientMatrix slots upper lowerLevel + (HierarchicalMatrixTable.backgroundOf slots upper X) (NodeEmbedding.matrix X upper))) + (congrArg (ChildBlockProjection.arraysPullback rows (projection k)) + (WholeArrayRawAssembly.arrays_exposedRead rows repeats (projected k) upper (lower k) (cut k) + (LinearMap.ker A) ω))).symm + + +theorem prediction_rawRead + (x : HierarchicalProjectedExperiment.Sample (rows := rows) (repeats := repeats) + projected upper lower cut × HierarchicalProjectedExperiment.Advice (rows := rows) upper r) : + HierarchicalAdviceExperiment.prediction S κ r ρ x = + rawPrediction (repeats := repeats) + slots projected projection upper lowerLevel lower cut direction outer σ κ r ρ + (HierarchicalProjectedExperiment.rawRead (rows := rows) (repeats := repeats) + projected upper lower cut r x) := by + rcases x with ⟨⟨k, ω⟩, A⟩ + exact (congrArg + (fun X : Arrays slots rows => + HierarchicalPrediction.prediction slots upper lowerLevel + (HierarchicalMatrixTable.backgroundOf slots upper X) σ (lower k) + (cut k).upper_ne_lower (direction k) (S).original (S).arrays + (HierarchicalAdviceExperiment.lowerEvent S) κ r ρ A (NodeEmbedding.matrix X upper)) + (congrArg (ChildBlockProjection.arraysPullback rows (projection k)) + (WholeArrayRawAssembly.arrays_exposedRead rows repeats (projected k) upper (lower k) (cut k) + (LinearMap.ker A) ω))).symm + +theorem J_probability : + (HierarchicalAdviceExperiment.originalLaw S r).probability + (fun x => HierarchicalAdviceExperiment.J S κ r ρ (HierarchicalAdviceExperiment.observe S r x)) = + (HierarchicalProjectedExperiment.rawLaw (rows := rows) (repeats := repeats) + projected upper lower cut outer r).probability + (rawJ (repeats := repeats) + slots projected projection upper lowerLevel lower cut direction outer σ κ r ρ) := by + have h := congrArg + (fun μ : FiniteDistribution + (HierarchicalProjectedExperiment.RawSample (rows := rows) (repeats := repeats) + projected upper lower cut r) => + μ.probability (rawJ (repeats := repeats) + slots projected projection upper lowerLevel lower cut direction outer σ κ r ρ)) + (HierarchicalProjectedExperiment.experiment_rawRead_law (rows := rows) (repeats := repeats) + slots projected projection upper lowerLevel lower cut direction outer σ r) + have hp := FiniteDistribution.probability_pushforward + (Ω := HierarchicalProjectedExperiment.Sample (rows := rows) (repeats := repeats) + projected upper lower cut × HierarchicalProjectedExperiment.Advice (rows := rows) upper r) + (Γ := HierarchicalProjectedExperiment.RawSample (rows := rows) (repeats := repeats) + projected upper lower cut r) + (HierarchicalAdviceExperiment.originalLaw S r) + (HierarchicalProjectedExperiment.rawRead (rows := rows) (repeats := repeats) + projected upper lower cut r) + (rawJ (repeats := repeats) + slots projected projection upper lowerLevel lower cut direction outer σ κ r ρ) + have hp' := hp.symm.trans h + have hevent : (fun x => rawJ (repeats := repeats) + slots projected projection upper lowerLevel lower cut direction outer σ κ r ρ + (HierarchicalProjectedExperiment.rawRead (rows := rows) (repeats := repeats) + projected upper lower cut r x)) = + (fun x => HierarchicalAdviceExperiment.J S κ r ρ (HierarchicalAdviceExperiment.observe S r x)) := + funext (fun x => + (J_rawRead (repeats := repeats) + slots projected projection upper lowerLevel lower cut direction outer σ κ r ρ x).symm) + exact (congrArg (fun event => + (HierarchicalAdviceExperiment.originalLaw S r).probability event) hevent).symm.trans hp' + +theorem prediction_probability : + (HierarchicalAdviceExperiment.originalLaw S r).probability + (HierarchicalAdviceExperiment.prediction S κ r ρ) = + (HierarchicalProjectedExperiment.rawLaw (rows := rows) (repeats := repeats) + projected upper lower cut outer r).probability + (rawPrediction (repeats := repeats) + slots projected projection upper lowerLevel lower cut direction outer σ κ r ρ) := by + have h := congrArg + (fun μ : FiniteDistribution + (HierarchicalProjectedExperiment.RawSample (rows := rows) (repeats := repeats) + projected upper lower cut r) => + μ.probability (rawPrediction (repeats := repeats) + slots projected projection upper lowerLevel lower cut direction outer σ κ r ρ)) + (HierarchicalProjectedExperiment.experiment_rawRead_law (rows := rows) (repeats := repeats) + slots projected projection upper lowerLevel lower cut direction outer σ r) + have hp := FiniteDistribution.probability_pushforward + (Ω := HierarchicalProjectedExperiment.Sample (rows := rows) (repeats := repeats) + projected upper lower cut × HierarchicalProjectedExperiment.Advice (rows := rows) upper r) + (Γ := HierarchicalProjectedExperiment.RawSample (rows := rows) (repeats := repeats) + projected upper lower cut r) + (HierarchicalAdviceExperiment.originalLaw S r) + (HierarchicalProjectedExperiment.rawRead (rows := rows) (repeats := repeats) + projected upper lower cut r) + (rawPrediction (repeats := repeats) + slots projected projection upper lowerLevel lower cut direction outer σ κ r ρ) + have hp' := hp.symm.trans h + have hevent : (fun x => rawPrediction (repeats := repeats) + slots projected projection upper lowerLevel lower cut direction outer σ κ r ρ + (HierarchicalProjectedExperiment.rawRead (rows := rows) (repeats := repeats) + projected upper lower cut r x)) = + HierarchicalAdviceExperiment.prediction S κ r ρ := + funext (fun x => + (prediction_rawRead (repeats := repeats) + slots projected projection upper lowerLevel lower cut direction outer σ κ r ρ x).symm) + exact (congrArg (fun event => + (HierarchicalAdviceExperiment.originalLaw S r).probability event) hevent).symm.trans hp' + +end +end PerfectCompleteness.HierarchicalProjectedPrediction + + + +namespace PerfectCompleteness.HierarchicalProjectedAverage + +noncomputable section + +open scoped BigOperators Classical +open TreeSourceSpaces HierarchicalArrays InitialParameters UpperParameterScalars +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype + +section Projected + +variable {δ : ℚ} (plan : FixedRows.Plan δ) {branch : Nat → Nat} {t : Nat} + {K : Type*} [Fintype K] + (slots : RecursiveSpaces.Slots branch plan.depth → Fin t → MixedSupport.Slot) + (projected : K → RecursiveSpaces.Slots branch plan.depth → Fin t → MixedSupport.Slot) + (projection : ∀ k s j, MixedSupport.Projection (slots s j) (projected k s j)) + (upper : Nodes branch plan.depth) (lowerLevel : Nat) + (lower : K → Nodes branch plan.depth) + (cut : ∀ k, OwnInputReference.Cut upper (lower k)) + (direction : ∀ k, Block (FixedRows.rows plan) (lower k)) + (outer : FiniteDistribution K) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch plan.depth t)) + +local notation "S" => HierarchicalProjectedExperiment.experiment + (rows := FixedRows.rows plan) (repeats := FixedRows.repeats plan) + slots projected projection upper lowerLevel lower cut direction outer σ + +abbrev RawSample := HierarchicalProjectedExperiment.RawSample + (rows := FixedRows.rows plan) (repeats := FixedRows.repeats plan) + projected upper lower cut plan.order + +def meetingProbability (sample : RawSample plan projected upper lower cut) : ℝ := + HierarchicalProjectedRawMeeting.meetingProbability plan slots (projected sample.2.1) + (projection sample.2.1) upper (lower sample.2.1) lowerLevel + (S).original (S).arrays (HierarchicalAdviceExperiment.lowerEvent S) σ sample.1 + (direction sample.2.1) (cut sample.2.1) sample.2.2.2 + +def expectedMeeting : ℝ := + (HierarchicalProjectedExperiment.rawLaw (rows := FixedRows.rows plan) + (repeats := FixedRows.repeats plan) projected upper lower cut outer plan.order).expectation + (meetingProbability plan slots projected projection upper lowerLevel lower cut direction outer σ) + +def predictionDifference : ℝ := + (HierarchicalAdviceExperiment.originalLaw S plan.order).probability + (HierarchicalAdviceExperiment.prediction S (useful δ) plan.order plan.density) - + rhoPred (useful δ) plan.density * + (HierarchicalAdviceExperiment.originalLaw S plan.order).probability + (fun x => HierarchicalAdviceExperiment.J S (useful δ) plan.order plan.density + (HierarchicalAdviceExperiment.observe S plan.order x)) + +theorem expectedMeeting_eq_fibers : + expectedMeeting plan slots projected projection upper lowerLevel lower cut direction outer σ = + (FiniteDistribution.uniform + (HierarchicalProjectedExperiment.Advice (rows := FixedRows.rows plan) upper plan.order)).expectation + (fun A => outer.expectation (fun k => + HierarchicalProjectedRawAverage.expectedMeeting plan slots (projected k) (projection k) upper (lower k) lowerLevel + (S).original (S).arrays (HierarchicalAdviceExperiment.lowerEvent S) σ A (direction k) (cut k) + (WholeArrayInteriorOwnInputLaw.exteriorLaw (FixedRows.rows plan) (FixedRows.repeats plan) + (projected k) upper (lower k) (cut k)))) := by + simp only [expectedMeeting, HierarchicalProjectedExperiment.rawLaw, + CandidateCoupling.expectation_sigmaLaw] + rfl + +theorem predictionDifference_eq_fibers : + predictionDifference plan slots projected projection upper lowerLevel lower cut direction outer σ = + (FiniteDistribution.uniform + (HierarchicalProjectedExperiment.Advice (rows := FixedRows.rows plan) upper plan.order)).expectation + (fun A => outer.expectation (fun k => + (HierarchicalProjectedRawAverage.law plan (projected k) upper (lower k) A (cut k) + (WholeArrayInteriorOwnInputLaw.exteriorLaw (FixedRows.rows plan) (FixedRows.repeats plan) + (projected k) upper (lower k) (cut k))).probability + (HierarchicalProjectedRawAverage.prediction plan slots (projected k) (projection k) upper (lower k) lowerLevel + (S).original (S).arrays (HierarchicalAdviceExperiment.lowerEvent S) σ A (direction k) (cut k)) - + rhoPred (useful δ) plan.density * + (HierarchicalProjectedRawAverage.law plan (projected k) upper (lower k) A (cut k) + (WholeArrayInteriorOwnInputLaw.exteriorLaw (FixedRows.rows plan) (FixedRows.repeats plan) + (projected k) upper (lower k) (cut k))).probability + (HierarchicalProjectedRawAverage.J plan slots (projected k) (projection k) upper (lower k) lowerLevel + (S).original (S).arrays (HierarchicalAdviceExperiment.lowerEvent S) σ A (cut k)))) := by + unfold predictionDifference + rw [HierarchicalProjectedPrediction.prediction_probability slots projected projection upper lowerLevel lower cut direction outer σ + (useful δ) plan.order plan.density, + HierarchicalProjectedPrediction.J_probability slots projected projection upper lowerLevel lower cut direction outer σ + (useful δ) plan.order plan.density] + simp only [HierarchicalProjectedExperiment.rawLaw, CompletionSoundness.sigmaLaw_probability, + DensityVariation.expectation_sub, SmallBiasSlice.expectation_const_mul] + rfl + +theorem expectedMeeting_ge_prediction_difference (hδ : 0 < δ) : + HierarchicalProjectedRawAverage.factor plan upper * + predictionDifference plan slots projected projection upper lowerLevel lower cut direction outer σ ≤ + expectedMeeting plan slots projected projection upper lowerLevel lower cut direction outer σ := by + rw [predictionDifference_eq_fibers, expectedMeeting_eq_fibers, + ← SmallBiasSlice.expectation_const_mul] + apply SmallBias.expectation_mono + intro A + rw [← SmallBiasSlice.expectation_const_mul] + apply SmallBias.expectation_mono + intro k + exact HierarchicalProjectedRawAverage.expectedMeeting_ge_prediction_difference plan slots (projected k) + (projection k) upper (lower k) lowerLevel + (S).original (S).arrays (HierarchicalAdviceExperiment.lowerEvent S) σ A (direction k) (cut k) hδ + (WholeArrayInteriorOwnInputLaw.exteriorLaw (FixedRows.rows plan) (FixedRows.repeats plan) + (projected k) upper (lower k) (cut k)) + +theorem factor_mul_b_eq_gamma : + HierarchicalProjectedRawAverage.factor plan upper * + b (useful δ) plan.density (inverse δ) plan.order (FixedRows.rows plan (Nodes.height upper)) = + gamma (useful δ) plan.density (inverse δ) plan.order (FixedRows.rows plan (Nodes.height upper)) := by + unfold HierarchicalProjectedRawAverage.factor UpperParameterScalars.gamma + rw [pow_add] + simp only [div_eq_mul_inv, mul_inv_rev, one_mul] + ring + +end Projected + + +variable {δ : ℚ} {hδ : 0 < δ} (p : FixedParameters.Parameters δ hδ) + {branch : Nat → Nat} {t : Nat} {K P : Type*} [Fintype K] [Fintype P] + (slots : RecursiveSpaces.Slots branch p.plan.depth → Fin t → MixedSupport.Slot) + (projected : K → RecursiveSpaces.Slots branch p.plan.depth → Fin t → MixedSupport.Slot) + (projection : ∀ k s j, MixedSupport.Projection (slots s j) (projected k s j)) + (upper : Nodes branch p.plan.depth) (lowerLevel : Nat) + (lower : K → Nodes branch p.plan.depth) + (cut : ∀ k, OwnInputReference.Cut upper (lower k)) + (direction : ∀ k, Block (FixedRows.rows p.plan) (lower k)) + (outer : FiniteDistribution K) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch p.plan.depth t)) + +local notation "S" => HierarchicalProjectedExperiment.experiment + (rows := FixedRows.rows p.plan) (repeats := FixedRows.repeats p.plan) + slots projected projection upper lowerLevel lower cut direction outer σ + +local instance backgroundFintype : Fintype (HierarchicalAdviceExperiment.Background S) := + Fintype.ofFinite _ + +local instance rowSpaceFintype : Fintype (NodeEmbedding.RowSpace slots upper) := + Fintype.ofFinite _ + +local instance inputFintype : + (background : HierarchicalAdviceExperiment.Background S) → + Fintype (HierarchicalAdviceExperiment.Input S background) := + HierarchicalAdviceExperiment.inputFintype S + +local instance inputFiniteDimensional : + (background : HierarchicalAdviceExperiment.Background S) → + FiniteDimensional F2 (HierarchicalAdviceExperiment.Input S background) := + HierarchicalAdviceExperiment.inputFiniteDimensional S + +theorem expectedMeeting_ge_gamma + (externalLaw : FiniteDistribution P) + (background : P → HierarchicalAdviceExperiment.Background S) + (scalarLaw : P → FiniteDistribution (NodeEmbedding.RowSpace slots upper)) + (hmass : simultaneous δ / 2 ≤ HierarchicalAdviceFromBuckets.usefulProbability + S (useful δ) externalLaw background scalarLaw (HierarchicalFixedAdvice.rows_positive p S)) + (hpaired : (HierarchicalAdviceFromBuckets.pairedLaw S externalLaw background + scalarLaw (HierarchicalFixedAdvice.rows_positive p S)).totalVariation + (HierarchicalAgreementMean.referenceLaw (S).slots (S).upper + (HierarchicalAdviceFromBuckets.backgroundLaw S externalLaw background) + (HierarchicalFixedAdvice.rows_positive p S)) ≤ 10 * p.accuracy) + (hcoarse : ((HierarchicalAdviceExperiment.originalLaw S p.plan.order).pushforward + (HierarchicalAdviceExperiment.observe S p.plan.order)).totalVariation + ((HierarchicalAdviceExperiment.referenceLaw S + (HierarchicalAdviceFromBuckets.backgroundLaw S externalLaw background) p.plan.order).pushforward + (HierarchicalAdviceExperiment.referenceObserve S p.plan.order)) ≤ 10 * p.accuracy) : + gamma (useful δ) p.plan.density (inverse δ) p.plan.order + (FixedRows.rows p.plan (Nodes.height upper)) ≤ + expectedMeeting p.plan slots projected projection upper lowerLevel lower cut direction outer σ := by + have hdifference := HierarchicalFixedAdvice.prediction_difference p S + externalLaw background scalarLaw hmass hpaired hcoarse + rw [← factor_mul_b_eq_gamma p.plan upper] + exact (mul_le_mul_of_nonneg_left hdifference (HierarchicalProjectedRawAverage.factor_nonneg p.plan upper)).trans + (expectedMeeting_ge_prediction_difference p.plan slots projected projection upper lowerLevel lower cut direction outer σ hδ) + +end +end PerfectCompleteness.HierarchicalProjectedAverage + + + +namespace PerfectCompleteness.HierarchicalProjectedOuterAverage + +noncomputable section + +open scoped BigOperators Classical +open TreeSourceSpaces HierarchicalArrays InitialParameters UpperParameterScalars +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype + +variable {δ : ℚ} (plan : FixedRows.Plan δ) + +def factor (ℓ : Nat) : ℝ := + (1 / (2 : ℝ) ^ plan.order) * + (tau (useful δ) plan.density plan.order ℓ ^ 2 / (2 * (2 : ℝ) ^ ℓ)) + +theorem factor_nonneg (ℓ : Nat) : 0 ≤ factor plan ℓ := by + unfold factor + positivity + +theorem factor_mul_b_eq_gamma (ℓ : Nat) : + factor plan ℓ * b (useful δ) plan.density (inverse δ) plan.order ℓ = + gamma (useful δ) plan.density (inverse δ) plan.order ℓ := by + unfold factor gamma + rw [pow_add] + simp only [div_eq_mul_inv, mul_inv_rev, one_mul] + ring + +variable {branch : Nat → Nat} {t : Nat} {O : Type*} [Fintype O] + {K : O → Type*} [∀ o, Fintype (K o)] + (slots : O → RecursiveSpaces.Slots branch plan.depth → Fin t → MixedSupport.Slot) + (projected : (o : O) → K o → RecursiveSpaces.Slots branch plan.depth → Fin t → MixedSupport.Slot) + (projection : ∀ o k s j, MixedSupport.Projection (slots o s j) (projected o k s j)) + (upper : O → Nodes branch plan.depth) (lowerLevel : Nat) + (lower : (o : O) → K o → Nodes branch plan.depth) + (cut : ∀ o k, OwnInputReference.Cut (upper o) (lower o k)) + (direction : ∀ o k, Block (FixedRows.rows plan) (lower o k)) + (inner : (o : O) → FiniteDistribution (K o)) + (outer : FiniteDistribution O) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch plan.depth t)) + +abbrev experiment (o : O) := + HierarchicalProjectedExperiment.experiment + (rows := FixedRows.rows plan) (repeats := FixedRows.repeats plan) + (slots o) (projected o) (projection o) (upper o) lowerLevel (lower o) (cut o) + (direction o) (inner o) σ + +local notation "S" => experiment plan slots projected projection upper lowerLevel lower cut direction inner σ + +def expectedMeeting : ℝ := + outer.expectation (fun o => HierarchicalProjectedAverage.expectedMeeting plan + (slots o) (projected o) (projection o) (upper o) lowerLevel (lower o) (cut o) + (direction o) (inner o) σ) + +def predictionDifference : ℝ := + (HierarchicalAdviceFamily.originalLaw S outer plan.order).probability + (HierarchicalAdviceFamily.prediction S (useful δ) plan.order plan.density) - + rhoPred (useful δ) plan.density * + (HierarchicalAdviceFamily.originalLaw S outer plan.order).probability + (fun x => HierarchicalAdviceFamily.J S (useful δ) plan.order plan.density + (HierarchicalAdviceFamily.observe S plan.order x)) + +theorem predictionDifference_eq_mean : + predictionDifference plan slots projected projection upper lowerLevel lower cut direction inner outer σ = + outer.expectation (fun o => HierarchicalProjectedAverage.predictionDifference plan + (slots o) (projected o) (projection o) (upper o) lowerLevel (lower o) (cut o) + (direction o) (inner o) σ) := by + simp only [predictionDifference, HierarchicalProjectedAverage.predictionDifference, + HierarchicalAdviceFamily.originalLaw, + HierarchicalAdviceFamily.prediction, HierarchicalAdviceFamily.J, HierarchicalAdviceFamily.observe, + CompletionSoundness.sigmaLaw_probability, DensityVariation.expectation_sub, + SmallBiasSlice.expectation_const_mul] + rfl + +theorem expectedMeeting_ge_prediction_difference (hδ : 0 < δ) + (ℓ : Nat) (hrowdim : ∀ o, FixedRows.rows plan (Nodes.height (upper o)) = ℓ) : + factor plan ℓ * + predictionDifference plan slots projected projection upper lowerLevel lower cut direction inner outer σ ≤ + expectedMeeting plan slots projected projection upper lowerLevel lower cut direction inner outer σ := by + unfold expectedMeeting + rw [predictionDifference_eq_mean, ← SmallBiasSlice.expectation_const_mul] + apply SmallBias.expectation_mono + intro o + have h := HierarchicalProjectedAverage.expectedMeeting_ge_prediction_difference plan + (slots o) (projected o) (projection o) (upper o) lowerLevel (lower o) (cut o) + (direction o) (inner o) σ hδ + have hfactor : HierarchicalProjectedRawAverage.factor plan (upper o) = factor plan ℓ := by + simp only [HierarchicalProjectedRawAverage.factor, factor, hrowdim o] + rw [hfactor] at h + exact h + +local instance contextBackgroundFintype (o : O) : + Fintype (HierarchicalAdviceExperiment.Background (S o)) := + HierarchicalAdviceExperiment.backgroundFintype (S o) + +local instance familyInputFintype (b : HierarchicalAdviceFamily.Background S) : + Fintype (HierarchicalAdviceFamily.Input S b) := + HierarchicalAdviceFamily.inputFintype S b + +local instance familyInputFiniteDimensional (b : HierarchicalAdviceFamily.Background S) : + FiniteDimensional F2 (HierarchicalAdviceFamily.Input S b) := + HierarchicalAdviceFamily.inputFiniteDimensional S b + +local instance familyValueFintype (b : HierarchicalAdviceFamily.Background S) : + Fintype (HierarchicalAdviceFamily.Value S b) := + HierarchicalAdviceFamily.valueFintype S b + +theorem expectedMeeting_ge_gamma_of_mean (hδ : 0 < δ) + (ℓ : Nat) (hrowdim : ∀ o, FixedRows.rows plan (Nodes.height (upper o)) = ℓ) + (backgrounds : (o : O) → FiniteDistribution (HierarchicalAdviceExperiment.Background (S o))) + (v : ℝ) (hv : 0 ≤ v) + (hsmall : v ≤ plan.density * + ((inverse δ ^ 2 / 4) / ((2 : ℝ) ^ (plan.order * ℓ)) ^ 2) / 16) + (hmean : 2 * inverse δ ≤ + (HierarchicalAdviceFamily.backgroundLaw S outer backgrounds).expectation + (fun b => PartialTableInverse.nonzeroAgreement + (HierarchicalAdviceFamily.table S (useful δ) b))) + (hvariation : + ((HierarchicalAdviceFamily.originalLaw S outer plan.order).pushforward + (HierarchicalAdviceFamily.observe S plan.order)).totalVariation + ((HierarchicalAdviceFamily.referenceLaw S outer backgrounds plan.order).pushforward + (HierarchicalAdviceFamily.referenceObserve S plan.order)) ≤ v) : + gamma (useful δ) plan.density (inverse δ) plan.order ℓ ≤ + expectedMeeting plan slots projected projection upper lowerLevel lower cut direction inner outer σ := by + have hrows (o : O) : 0 < FixedRows.rows plan (Nodes.height (S o).upper) := + plan.rows_pos (plan.depth - Nodes.height (upper o)) + have hdim (o : O) : FixedRows.rows plan (Nodes.height (S o).upper) ≤ ℓ := + (hrowdim o).le + have hbound := HierarchicalAdviceFamily.prediction_difference S (useful δ) (useful_pos hδ).le + outer backgrounds hrows ℓ hdim plan.order plan.density (inverse δ) v + (inverse_pos hδ) plan.density_pos plan.density_lt plan.spectral hmean hv hsmall hvariation + have hb : useful δ * plan.density * + ((inverse δ ^ 2 / 4) / ((2 : ℝ) ^ (plan.order * ℓ)) ^ 2) / 4 = + b (useful δ) plan.density (inverse δ) plan.order ℓ := by + unfold b rhoPred q g h + simp only [div_eq_mul_inv, pow_two, mul_inv_rev] + ring + rw [hb] at hbound + rw [← factor_mul_b_eq_gamma plan ℓ] + exact (mul_le_mul_of_nonneg_left hbound (factor_nonneg plan ℓ)).trans + (expectedMeeting_ge_prediction_difference plan slots projected projection upper lowerLevel lower cut + direction inner outer σ hδ ℓ hrowdim) + +end +end PerfectCompleteness.HierarchicalProjectedOuterAverage + + + +namespace PerfectCompleteness.HierarchicalWholePrediction + +noncomputable section + +open scoped Classical +open TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype + +variable {branch rows repeats : Nat → Nat} {n t : Nat} {K : Type*} [Fintype K] + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (upper : Nodes branch n) (lowerLevel : Nat) + (lower : K → Nodes branch n) + (cut : ∀ k, OwnInputReference.Cut upper (lower k)) + (direction : ∀ k, Block rows (lower k)) + (outer : FiniteDistribution K) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (κ : ℝ) (r : Nat) (ρ : ℝ) + +local notation "S" => HierarchicalWholeExperiment.experiment (rows := rows) (repeats := repeats) + slots upper lowerLevel lower cut direction outer σ + +def rawJ (sample : HierarchicalWholeExperiment.RawSample (rows := rows) (repeats := repeats) + slots upper lower cut r) : Bool := + HierarchicalRawPrediction.rawJ slots rows upper (lower sample.2.1) lowerLevel + (S).original (S).arrays (HierarchicalAdviceExperiment.lowerEvent S) κ σ ρ sample.1 + repeats (cut sample.2.1) sample.2.2 + +def rawPrediction (sample : HierarchicalWholeExperiment.RawSample (rows := rows) (repeats := repeats) + slots upper lower cut r) : Bool := + HierarchicalRawPrediction.rawPrediction slots rows upper (lower sample.2.1) lowerLevel + (S).original (S).arrays (HierarchicalAdviceExperiment.lowerEvent S) κ σ ρ sample.1 + repeats (cut sample.2.1) (direction sample.2.1) sample.2.2 + + +theorem J_rawRead + (x : HierarchicalWholeExperiment.Sample (rows := rows) (repeats := repeats) + slots upper lower cut × HierarchicalWholeExperiment.Advice (rows := rows) upper r) : + HierarchicalAdviceExperiment.J S κ r ρ (HierarchicalAdviceExperiment.observe S r x) = + rawJ (repeats := repeats) slots upper lowerLevel lower cut direction outer σ κ r ρ + (HierarchicalWholeExperiment.rawRead (rows := rows) (repeats := repeats) + slots upper lower cut r x) := by + rcases x with ⟨⟨k, ω⟩, A⟩ + exact (congrArg + (fun X : Arrays slots rows => + GoodAdviceEvents.J + (HierarchicalUsefulness.table slots upper lowerLevel (S).original (S).arrays + (HierarchicalAdviceExperiment.lowerEvent S) κ σ + (HierarchicalMatrixTable.backgroundOf slots upper X)) r ρ + (A, HierarchicalPrediction.quotientMatrix slots upper lowerLevel + (HierarchicalMatrixTable.backgroundOf slots upper X) (NodeEmbedding.matrix X upper))) + (WholeArrayRawAssembly.arrays_exposedRead rows repeats slots upper (lower k) (cut k) + (LinearMap.ker A) ω)).symm + + +theorem prediction_rawRead + (x : HierarchicalWholeExperiment.Sample (rows := rows) (repeats := repeats) + slots upper lower cut × HierarchicalWholeExperiment.Advice (rows := rows) upper r) : + HierarchicalAdviceExperiment.prediction S κ r ρ x = + rawPrediction (repeats := repeats) slots upper lowerLevel lower cut direction outer σ κ r ρ + (HierarchicalWholeExperiment.rawRead (rows := rows) (repeats := repeats) + slots upper lower cut r x) := by + rcases x with ⟨⟨k, ω⟩, A⟩ + exact (congrArg + (fun X : Arrays slots rows => + HierarchicalPrediction.prediction slots upper lowerLevel + (HierarchicalMatrixTable.backgroundOf slots upper X) σ (lower k) + (cut k).upper_ne_lower (direction k) (S).original (S).arrays + (HierarchicalAdviceExperiment.lowerEvent S) κ r ρ A (NodeEmbedding.matrix X upper)) + (WholeArrayRawAssembly.arrays_exposedRead rows repeats slots upper (lower k) (cut k) + (LinearMap.ker A) ω)).symm + +theorem J_probability : + (HierarchicalAdviceExperiment.originalLaw S r).probability + (fun x => HierarchicalAdviceExperiment.J S κ r ρ (HierarchicalAdviceExperiment.observe S r x)) = + (HierarchicalWholeExperiment.rawLaw (rows := rows) (repeats := repeats) + slots upper lower cut outer r).probability + (rawJ (repeats := repeats) slots upper lowerLevel lower cut direction outer σ κ r ρ) := by + have h := congrArg + (fun μ : FiniteDistribution + (HierarchicalWholeExperiment.RawSample (rows := rows) (repeats := repeats) + slots upper lower cut r) => + μ.probability + (rawJ (repeats := repeats) slots upper lowerLevel lower cut direction outer σ κ r ρ)) + (HierarchicalWholeExperiment.experiment_rawRead_law (rows := rows) (repeats := repeats) + slots upper lowerLevel lower cut direction outer σ r) + have hp := FiniteDistribution.probability_pushforward + (Ω := HierarchicalWholeExperiment.Sample (rows := rows) (repeats := repeats) + slots upper lower cut × HierarchicalWholeExperiment.Advice (rows := rows) upper r) + (Γ := HierarchicalWholeExperiment.RawSample (rows := rows) (repeats := repeats) + slots upper lower cut r) + (HierarchicalAdviceExperiment.originalLaw S r) + (HierarchicalWholeExperiment.rawRead (rows := rows) (repeats := repeats) + slots upper lower cut r) + (rawJ (repeats := repeats) slots upper lowerLevel lower cut direction outer σ κ r ρ) + have hprob := hp.symm.trans h + have hevent : (fun x => rawJ (repeats := repeats) + slots upper lowerLevel lower cut direction outer σ κ r ρ + (HierarchicalWholeExperiment.rawRead (rows := rows) (repeats := repeats) + slots upper lower cut r x)) = + (fun x => HierarchicalAdviceExperiment.J S κ r ρ (HierarchicalAdviceExperiment.observe S r x)) := + funext (fun x => (J_rawRead (repeats := repeats) + slots upper lowerLevel lower cut direction outer σ κ r ρ x).symm) + exact (congrArg + (fun event => (HierarchicalAdviceExperiment.originalLaw S r).probability event) + hevent).symm.trans hprob + +theorem prediction_probability : + (HierarchicalAdviceExperiment.originalLaw S r).probability + (HierarchicalAdviceExperiment.prediction S κ r ρ) = + (HierarchicalWholeExperiment.rawLaw (rows := rows) (repeats := repeats) + slots upper lower cut outer r).probability + (rawPrediction (repeats := repeats) + slots upper lowerLevel lower cut direction outer σ κ r ρ) := by + have h := congrArg + (fun μ : FiniteDistribution + (HierarchicalWholeExperiment.RawSample (rows := rows) (repeats := repeats) + slots upper lower cut r) => + μ.probability + (rawPrediction (repeats := repeats) slots upper lowerLevel lower cut direction outer σ κ r ρ)) + (HierarchicalWholeExperiment.experiment_rawRead_law (rows := rows) (repeats := repeats) + slots upper lowerLevel lower cut direction outer σ r) + have hp := FiniteDistribution.probability_pushforward + (Ω := HierarchicalWholeExperiment.Sample (rows := rows) (repeats := repeats) + slots upper lower cut × HierarchicalWholeExperiment.Advice (rows := rows) upper r) + (Γ := HierarchicalWholeExperiment.RawSample (rows := rows) (repeats := repeats) + slots upper lower cut r) + (HierarchicalAdviceExperiment.originalLaw S r) + (HierarchicalWholeExperiment.rawRead (rows := rows) (repeats := repeats) + slots upper lower cut r) + (rawPrediction (repeats := repeats) slots upper lowerLevel lower cut direction outer σ κ r ρ) + have hprob := hp.symm.trans h + have hevent : (fun x => rawPrediction (repeats := repeats) + slots upper lowerLevel lower cut direction outer σ κ r ρ + (HierarchicalWholeExperiment.rawRead (rows := rows) (repeats := repeats) + slots upper lower cut r x)) = + HierarchicalAdviceExperiment.prediction S κ r ρ := + funext (fun x => (prediction_rawRead (repeats := repeats) + slots upper lowerLevel lower cut direction outer σ κ r ρ x).symm) + exact (congrArg + (fun event => (HierarchicalAdviceExperiment.originalLaw S r).probability event) + hevent).symm.trans hprob + +end +end PerfectCompleteness.HierarchicalWholePrediction + + + +namespace PerfectCompleteness.HierarchicalWholeAverage + +noncomputable section + +open scoped BigOperators Classical +open TreeSourceSpaces HierarchicalArrays InitialParameters UpperParameterScalars +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype + +section Whole + +variable {δ : ℚ} (plan : FixedRows.Plan δ) {branch : Nat → Nat} {t : Nat} + {K : Type*} [Fintype K] + (slots : RecursiveSpaces.Slots branch plan.depth → Fin t → MixedSupport.Slot) + (upper : Nodes branch plan.depth) (lowerLevel : Nat) + (lower : K → Nodes branch plan.depth) + (cut : ∀ k, OwnInputReference.Cut upper (lower k)) + (direction : ∀ k, Block (FixedRows.rows plan) (lower k)) + (outer : FiniteDistribution K) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch plan.depth t)) + +local notation "S" => HierarchicalWholeExperiment.experiment + (rows := FixedRows.rows plan) (repeats := FixedRows.repeats plan) + slots upper lowerLevel lower cut direction outer σ + +abbrev RawSample := HierarchicalWholeExperiment.RawSample + (rows := FixedRows.rows plan) (repeats := FixedRows.repeats plan) + slots upper lower cut plan.order + +def meetingProbability (sample : RawSample plan slots upper lower cut) : ℝ := + HierarchicalRawMeeting.meetingProbability plan slots upper (lower sample.2.1) lowerLevel + (S).original (S).arrays (HierarchicalAdviceExperiment.lowerEvent S) σ sample.1 + (direction sample.2.1) (cut sample.2.1) sample.2.2.2 + +def expectedMeeting : ℝ := + (HierarchicalWholeExperiment.rawLaw (rows := FixedRows.rows plan) + (repeats := FixedRows.repeats plan) slots upper lower cut outer plan.order).expectation + (meetingProbability plan slots upper lowerLevel lower cut direction outer σ) + +def predictionDifference : ℝ := + (HierarchicalAdviceExperiment.originalLaw S plan.order).probability + (HierarchicalAdviceExperiment.prediction S (useful δ) plan.order plan.density) - + rhoPred (useful δ) plan.density * + (HierarchicalAdviceExperiment.originalLaw S plan.order).probability + (fun x => HierarchicalAdviceExperiment.J S (useful δ) plan.order plan.density + (HierarchicalAdviceExperiment.observe S plan.order x)) + +theorem expectedMeeting_eq_fibers : + expectedMeeting plan slots upper lowerLevel lower cut direction outer σ = + (FiniteDistribution.uniform + (HierarchicalWholeExperiment.Advice (rows := FixedRows.rows plan) upper plan.order)).expectation + (fun A => outer.expectation (fun k => + HierarchicalRawAverage.expectedMeeting plan slots upper (lower k) lowerLevel + (S).original (S).arrays (HierarchicalAdviceExperiment.lowerEvent S) σ A (direction k) (cut k) + (WholeArrayInteriorOwnInputLaw.exteriorLaw (FixedRows.rows plan) (FixedRows.repeats plan) + slots upper (lower k) (cut k)))) := by + simp only [expectedMeeting, HierarchicalWholeExperiment.rawLaw, + CandidateCoupling.expectation_sigmaLaw] + rfl + +theorem predictionDifference_eq_fibers : + predictionDifference plan slots upper lowerLevel lower cut direction outer σ = + (FiniteDistribution.uniform + (HierarchicalWholeExperiment.Advice (rows := FixedRows.rows plan) upper plan.order)).expectation + (fun A => outer.expectation (fun k => + (HierarchicalRawAverage.law plan slots upper (lower k) A (cut k) + (WholeArrayInteriorOwnInputLaw.exteriorLaw (FixedRows.rows plan) (FixedRows.repeats plan) + slots upper (lower k) (cut k))).probability + (HierarchicalRawAverage.prediction plan slots upper (lower k) lowerLevel + (S).original (S).arrays (HierarchicalAdviceExperiment.lowerEvent S) σ A (direction k) (cut k)) - + rhoPred (useful δ) plan.density * + (HierarchicalRawAverage.law plan slots upper (lower k) A (cut k) + (WholeArrayInteriorOwnInputLaw.exteriorLaw (FixedRows.rows plan) (FixedRows.repeats plan) + slots upper (lower k) (cut k))).probability + (HierarchicalRawAverage.J plan slots upper (lower k) lowerLevel + (S).original (S).arrays (HierarchicalAdviceExperiment.lowerEvent S) σ A (cut k)))) := by + unfold predictionDifference + rw [HierarchicalWholePrediction.prediction_probability slots upper lowerLevel lower cut direction outer σ + (useful δ) plan.order plan.density, + HierarchicalWholePrediction.J_probability slots upper lowerLevel lower cut direction outer σ + (useful δ) plan.order plan.density] + simp only [HierarchicalWholeExperiment.rawLaw, CompletionSoundness.sigmaLaw_probability, + DensityVariation.expectation_sub, SmallBiasSlice.expectation_const_mul] + rfl + +theorem expectedMeeting_ge_prediction_difference (hδ : 0 < δ) : + HierarchicalRawAverage.factor plan upper * + predictionDifference plan slots upper lowerLevel lower cut direction outer σ ≤ + expectedMeeting plan slots upper lowerLevel lower cut direction outer σ := by + rw [predictionDifference_eq_fibers, expectedMeeting_eq_fibers, + ← SmallBiasSlice.expectation_const_mul] + apply SmallBias.expectation_mono + intro A + rw [← SmallBiasSlice.expectation_const_mul] + apply SmallBias.expectation_mono + intro k + exact HierarchicalRawAverage.expectedMeeting_ge_prediction_difference plan slots upper (lower k) lowerLevel + (S).original (S).arrays (HierarchicalAdviceExperiment.lowerEvent S) σ A (direction k) (cut k) hδ + (WholeArrayInteriorOwnInputLaw.exteriorLaw (FixedRows.rows plan) (FixedRows.repeats plan) + slots upper (lower k) (cut k)) + +theorem factor_mul_b_eq_gamma : + HierarchicalRawAverage.factor plan upper * + b (useful δ) plan.density (inverse δ) plan.order (FixedRows.rows plan (Nodes.height upper)) = + gamma (useful δ) plan.density (inverse δ) plan.order (FixedRows.rows plan (Nodes.height upper)) := by + unfold HierarchicalRawAverage.factor UpperParameterScalars.gamma + rw [pow_add] + simp only [div_eq_mul_inv, mul_inv_rev, one_mul] + ring + +end Whole + + +variable {δ : ℚ} {hδ : 0 < δ} (p : FixedParameters.Parameters δ hδ) + {branch : Nat → Nat} {t : Nat} {K P : Type*} [Fintype K] [Fintype P] + (slots : RecursiveSpaces.Slots branch p.plan.depth → Fin t → MixedSupport.Slot) + (upper : Nodes branch p.plan.depth) (lowerLevel : Nat) + (lower : K → Nodes branch p.plan.depth) + (cut : ∀ k, OwnInputReference.Cut upper (lower k)) + (direction : ∀ k, Block (FixedRows.rows p.plan) (lower k)) + (outer : FiniteDistribution K) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch p.plan.depth t)) + +local notation "S" => HierarchicalWholeExperiment.experiment + (rows := FixedRows.rows p.plan) (repeats := FixedRows.repeats p.plan) + slots upper lowerLevel lower cut direction outer σ + +local instance backgroundFintype : Fintype (HierarchicalAdviceExperiment.Background S) := + Fintype.ofFinite _ + +local instance rowSpaceFintype : Fintype (NodeEmbedding.RowSpace slots upper) := + Fintype.ofFinite _ + +local instance inputFintype : + (background : HierarchicalAdviceExperiment.Background S) → + Fintype (HierarchicalAdviceExperiment.Input S background) := + HierarchicalAdviceExperiment.inputFintype S + +local instance inputFiniteDimensional : + (background : HierarchicalAdviceExperiment.Background S) → + FiniteDimensional F2 (HierarchicalAdviceExperiment.Input S background) := + HierarchicalAdviceExperiment.inputFiniteDimensional S + +theorem expectedMeeting_ge_gamma + (externalLaw : FiniteDistribution P) + (background : P → HierarchicalAdviceExperiment.Background S) + (scalarLaw : P → FiniteDistribution (NodeEmbedding.RowSpace slots upper)) + (hmass : simultaneous δ / 2 ≤ HierarchicalAdviceFromBuckets.usefulProbability + S (useful δ) externalLaw background scalarLaw (HierarchicalFixedAdvice.rows_positive p S)) + (hpaired : (HierarchicalAdviceFromBuckets.pairedLaw S externalLaw background + scalarLaw (HierarchicalFixedAdvice.rows_positive p S)).totalVariation + (HierarchicalAgreementMean.referenceLaw (S).slots (S).upper + (HierarchicalAdviceFromBuckets.backgroundLaw S externalLaw background) + (HierarchicalFixedAdvice.rows_positive p S)) ≤ 10 * p.accuracy) + (hcoarse : ((HierarchicalAdviceExperiment.originalLaw S p.plan.order).pushforward + (HierarchicalAdviceExperiment.observe S p.plan.order)).totalVariation + ((HierarchicalAdviceExperiment.referenceLaw S + (HierarchicalAdviceFromBuckets.backgroundLaw S externalLaw background) p.plan.order).pushforward + (HierarchicalAdviceExperiment.referenceObserve S p.plan.order)) ≤ 10 * p.accuracy) : + gamma (useful δ) p.plan.density (inverse δ) p.plan.order + (FixedRows.rows p.plan (Nodes.height upper)) ≤ + expectedMeeting p.plan slots upper lowerLevel lower cut direction outer σ := by + have hdifference := HierarchicalFixedAdvice.prediction_difference p S + externalLaw background scalarLaw hmass hpaired hcoarse + rw [← factor_mul_b_eq_gamma p.plan upper] + exact (mul_le_mul_of_nonneg_left hdifference (HierarchicalRawAverage.factor_nonneg p.plan upper)).trans + (expectedMeeting_ge_prediction_difference p.plan slots upper lowerLevel lower cut direction outer σ hδ) + +end +end PerfectCompleteness.HierarchicalWholeAverage + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalProjectedRawAverage.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalProjectedRawAverage.lean new file mode 100644 index 0000000000000000000000000000000000000000..639ec36216d1d629ed91fb39d2e6c41b93d295be --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalProjectedRawAverage.lean @@ -0,0 +1,238 @@ +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalProjectedRawMeeting +import OAI.Computability.PerfectCompleteness.Foundations.TupleIndexEmitterLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.HierarchicalProjectedRawAverage + +noncomputable section + +open scoped BigOperators Classical TensorProduct +open TreeSourceSpaces HierarchicalArrays UpperParameterScalars +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype + +private theorem event_mass_le_expectation {X : Type*} [Fintype X] + (μ : FiniteDistribution X) (event : X → Bool) (value : X → ℝ) (factor : ℝ) + (hnonneg : ∀ x, 0 ≤ value x) + (hbound : ∀ x, event x = true → factor ≤ value x) : + factor * μ.probability event ≤ μ.expectation value := by + unfold FiniteDistribution.probability FiniteDistribution.expectation + rw [Finset.mul_sum] + apply Finset.sum_le_sum + intro x _ + by_cases hx : event x = true + · rw [ite_eq_left hx] + calc + factor * μ.weight x = μ.weight x * factor := mul_comm _ _ + _ ≤ μ.weight x * value x := + mul_le_mul_of_nonneg_left (hbound x hx) (μ.nonnegative x) + · rw [ite_eq_right hx, mul_zero] + exact mul_nonneg (μ.nonnegative x) (hnonneg x) + +variable {δ : ℚ} (plan : FixedRows.Plan δ) {branch : Nat → Nat} {t : Nat} + (slots projected : RecursiveSpaces.Slots branch plan.depth → Fin t → MixedSupport.Slot) + (projection : ∀ s j, MixedSupport.Projection (slots s j) (projected s j)) + (upper lower : Nodes branch plan.depth) (lowerLevel : Nat) + {Ω : Type*} [Fintype Ω] + (original : FiniteDistribution Ω) (originalArrays : Ω → Arrays slots (FixedRows.rows plan)) + (lowerEvent : Ω → Bool) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch plan.depth t)) + (A : ManyGoodRows.RowMap (Block (FixedRows.rows plan) upper) plan.order) + (a : Block (FixedRows.rows plan) lower) (cut : OwnInputReference.Cut upper lower) + +abbrev Raw := HierarchicalProjectedRawPrediction.Raw projected (FixedRows.rows plan) upper lower A + (FixedRows.repeats plan) cut + +abbrev Visible := HierarchicalProjectedRawPrediction.Visible projected (FixedRows.rows plan) upper lower A + (FixedRows.repeats plan) cut + +def law (externalLaw : FiniteDistribution + (OwnInputReference.Exterior projected (FixedRows.rows plan) upper lower)) : + FiniteDistribution (Raw plan projected upper lower A cut) := + OwnInputReference.rawLaw projected (FixedRows.rows plan) upper lower (LinearMap.ker A) + (FixedRows.repeats plan) cut externalLaw + +abbrev J := HierarchicalProjectedRawPrediction.rawJ slots projected projection (FixedRows.rows plan) upper lower lowerLevel + original originalArrays lowerEvent (InitialParameters.useful δ) σ plan.density A + (FixedRows.repeats plan) cut + +abbrev prediction := HierarchicalProjectedRawPrediction.rawPrediction slots projected projection (FixedRows.rows plan) upper lower lowerLevel + original originalArrays lowerEvent (InitialParameters.useful δ) σ plan.density A + (FixedRows.repeats plan) cut a + +def goodRecord (externalLaw : FiniteDistribution + (OwnInputReference.Exterior projected (FixedRows.rows plan) upper lower)) + (v : Visible plan projected upper lower A cut) : Bool := + PositiveFiberMass.goodRecord (law plan projected upper lower A cut externalLaw) + (fun sample : Raw plan projected upper lower A cut => sample.2) + (J plan slots projected projection upper lower lowerLevel original originalArrays lowerEvent σ A cut) + (prediction plan slots projected projection upper lower lowerLevel original originalArrays lowerEvent σ A a cut) + (rhoPred (InitialParameters.useful δ) plan.density) v + +def goodEvent (externalLaw : FiniteDistribution + (OwnInputReference.Exterior projected (FixedRows.rows plan) upper lower)) + (sample : Raw plan projected upper lower A cut) : Bool := + J plan slots projected projection upper lower lowerLevel original originalArrays lowerEvent σ A cut sample && + goodRecord plan slots projected projection upper lower lowerLevel original originalArrays lowerEvent σ A a cut + externalLaw sample.2 + +def factor : ℝ := + (1 / (2 : ℝ) ^ plan.order) * + (tau (InitialParameters.useful δ) plan.density plan.order + (FixedRows.rows plan (Nodes.height upper)) ^ 2 / + (2 * (2 : ℝ) ^ FixedRows.rows plan (Nodes.height upper))) + +theorem factor_nonneg : 0 ≤ factor plan upper := by + unfold factor + positivity + +abbrev meetingProbability := + HierarchicalProjectedRawMeeting.meetingProbability plan slots projected projection upper lower lowerLevel + original originalArrays lowerEvent σ A a cut + +def expectedMeeting (externalLaw : FiniteDistribution + (OwnInputReference.Exterior projected (FixedRows.rows plan) upper lower)) : ℝ := + (law plan projected upper lower A cut externalLaw).expectation + (fun sample => meetingProbability plan slots projected projection upper lower lowerLevel + original originalArrays lowerEvent σ A a cut sample.2) + +theorem meeting_lower_of_goodRecord (hδ : 0 < δ) + (externalLaw : FiniteDistribution + (OwnInputReference.Exterior projected (FixedRows.rows plan) upper lower)) + (v : Visible plan projected upper lower A cut) + (hgood : goodRecord plan slots projected projection upper lower lowerLevel original originalArrays lowerEvent σ + A a cut externalLaw v = true) : + factor plan upper ≤ + meetingProbability plan slots projected projection upper lower lowerLevel original originalArrays lowerEvent σ A a cut v := by + have hpositive := (PositiveFiberMass.goodRecord_iff + (law plan projected upper lower A cut externalLaw) + (fun sample : Raw plan projected upper lower A cut => sample.2) + (J plan slots projected projection upper lower lowerLevel original originalArrays lowerEvent σ A cut) + (prediction plan slots projected projection upper lower lowerLevel original originalArrays lowerEvent σ A a cut) + (rhoPred (InitialParameters.useful δ) plan.density) v).mp hgood + let originalGiven : Raw plan projected upper lower A cut → Bool := fun sample => + J plan slots projected projection upper lower lowerLevel original originalArrays lowerEvent σ A cut sample && + @decide (sample.2 = v) (Classical.propDecidable _) + have hgiven : originalGiven = + HierarchicalProjectedRawPrediction.given slots projected projection (FixedRows.rows plan) upper lower lowerLevel + original originalArrays lowerEvent (InitialParameters.useful δ) σ plan.density A + (FixedRows.repeats plan) cut v := by + funext sample + unfold originalGiven HierarchicalProjectedRawPrediction.given + apply congrArg (fun flag : Bool => + J plan slots projected projection upper lower lowerLevel original originalArrays lowerEvent σ A cut sample && flag) + exact (@decide_eq_decide _ _ _ _).mpr Iff.rfl + have positive : 0 < (law plan projected upper lower A cut externalLaw).probability + (HierarchicalProjectedRawPrediction.given slots projected projection (FixedRows.rows plan) upper lower lowerLevel + original originalArrays lowerEvent (InitialParameters.useful δ) σ plan.density A + (FixedRows.repeats plan) cut v) := by + rw [← hgiven] + exact hpositive.1 + have conditional : rhoPred (InitialParameters.useful δ) plan.density ≤ + ((law plan projected upper lower A cut externalLaw).condition + (HierarchicalProjectedRawPrediction.given slots projected projection (FixedRows.rows plan) upper lower lowerLevel + original originalArrays lowerEvent (InitialParameters.useful δ) σ plan.density A + (FixedRows.repeats plan) cut v) positive).probability + (prediction plan slots projected projection upper lower lowerLevel original originalArrays lowerEvent σ A a cut) := by + have hprediction := hpositive.2 + have hmatch : (fun sample : Raw plan projected upper lower A cut => + originalGiven sample && + prediction plan slots projected projection upper lower lowerLevel original originalArrays lowerEvent σ A a cut sample) = + (fun sample => + (J plan slots projected projection upper lower lowerLevel original originalArrays lowerEvent σ A cut sample && + prediction plan slots projected projection upper lower lowerLevel original originalArrays lowerEvent σ A a cut sample) && + @decide (sample.2 = v) (Classical.propDecidable _)) := by + funext sample + dsimp only [originalGiven] + cases J plan slots projected projection upper lower lowerLevel original originalArrays lowerEvent σ A cut sample <;> + cases prediction plan slots projected projection upper lower lowerLevel original originalArrays lowerEvent σ A a cut sample <;> + cases @decide (sample.2 = v) (Classical.propDecidable _) <;> rfl + change rhoPred (InitialParameters.useful δ) plan.density ≤ + (law plan projected upper lower A cut externalLaw).probability + (fun sample => + (J plan slots projected projection upper lower lowerLevel original originalArrays lowerEvent σ A cut sample && + prediction plan slots projected projection upper lower lowerLevel original originalArrays lowerEvent σ A a cut sample) && + @decide (sample.2 = v) (Classical.propDecidable _)) / + (law plan projected upper lower A cut externalLaw).probability originalGiven at hprediction + rw [← hmatch, hgiven] at hprediction + exact hprediction.trans_eq + (FiniteDistribution.probability_condition (law plan projected upper lower A cut externalLaw) + (HierarchicalProjectedRawPrediction.given slots projected projection (FixedRows.rows plan) upper lower lowerLevel + original originalArrays lowerEvent (InitialParameters.useful δ) σ plan.density A + (FixedRows.repeats plan) cut v) + (prediction plan slots projected projection upper lower lowerLevel original originalArrays lowerEvent σ A a cut) + positive).symm + exact HierarchicalProjectedRawMeeting.meeting_probability_lower plan slots projected projection upper lower lowerLevel + original originalArrays lowerEvent σ A a cut v hδ externalLaw positive conditional + +theorem expectedMeeting_ge_good_mass (hδ : 0 < δ) + (externalLaw : FiniteDistribution + (OwnInputReference.Exterior projected (FixedRows.rows plan) upper lower)) : + factor plan upper * + (law plan projected upper lower A cut externalLaw).probability + (goodEvent plan slots projected projection upper lower lowerLevel original originalArrays lowerEvent σ A a cut externalLaw) ≤ + expectedMeeting plan slots projected projection upper lower lowerLevel original originalArrays lowerEvent σ A a cut externalLaw := by + apply event_mass_le_expectation + · intro sample + exact HierarchicalProjectedRawMeeting.meetingProbability_nonneg plan slots projected projection upper lower lowerLevel + original originalArrays lowerEvent σ A a cut sample.2 + · intro sample hs + exact meeting_lower_of_goodRecord plan slots projected projection upper lower lowerLevel original originalArrays lowerEvent σ + A a cut hδ externalLaw sample.2 (Bool.and_eq_true_iff.mp hs).2 + +theorem J_and_prediction : + (fun sample => J plan slots projected projection upper lower lowerLevel original originalArrays lowerEvent σ A cut sample && + prediction plan slots projected projection upper lower lowerLevel original originalArrays lowerEvent σ A a cut sample) = + prediction plan slots projected projection upper lower lowerLevel original originalArrays lowerEvent σ A a cut := by + funext sample + unfold J prediction HierarchicalProjectedRawPrediction.rawJ HierarchicalProjectedRawPrediction.rawPrediction + HierarchicalPrediction.prediction + exact Bool.and_self_left _ _ + +theorem prediction_difference_le_good_mass (hδ : 0 < δ) + (externalLaw : FiniteDistribution + (OwnInputReference.Exterior projected (FixedRows.rows plan) upper lower)) : + (law plan projected upper lower A cut externalLaw).probability + (prediction plan slots projected projection upper lower lowerLevel original originalArrays lowerEvent σ A a cut) - + rhoPred (InitialParameters.useful δ) plan.density * + (law plan projected upper lower A cut externalLaw).probability + (J plan slots projected projection upper lower lowerLevel original originalArrays lowerEvent σ A cut) ≤ + (law plan projected upper lower A cut externalLaw).probability + (goodEvent plan slots projected projection upper lower lowerLevel original originalArrays lowerEvent σ A a cut externalLaw) := by + have h := PositiveFiberMass.difference_le_good_mass + (law plan projected upper lower A cut externalLaw) + (fun sample : Raw plan projected upper lower A cut => sample.2) + (J plan slots projected projection upper lower lowerLevel original originalArrays lowerEvent σ A cut) + (prediction plan slots projected projection upper lower lowerLevel original originalArrays lowerEvent σ A a cut) + (rhoPred (InitialParameters.useful δ) plan.density) + (rhoPred_pos (InitialParameters.useful_pos hδ) plan.density_pos).le + rw [J_and_prediction] at h + exact h + +theorem expectedMeeting_ge_prediction_difference (hδ : 0 < δ) + (externalLaw : FiniteDistribution + (OwnInputReference.Exterior projected (FixedRows.rows plan) upper lower)) : + factor plan upper * + ((law plan projected upper lower A cut externalLaw).probability + (prediction plan slots projected projection upper lower lowerLevel original originalArrays lowerEvent σ A a cut) - + rhoPred (InitialParameters.useful δ) plan.density * + (law plan projected upper lower A cut externalLaw).probability + (J plan slots projected projection upper lower lowerLevel original originalArrays lowerEvent σ A cut)) ≤ + expectedMeeting plan slots projected projection upper lower lowerLevel original originalArrays lowerEvent σ A a cut externalLaw := + (mul_le_mul_of_nonneg_left + (prediction_difference_le_good_mass plan slots projected projection upper lower lowerLevel original originalArrays lowerEvent σ + A a cut hδ externalLaw) (factor_nonneg plan upper)).trans + (expectedMeeting_ge_good_mass plan slots projected projection upper lower lowerLevel original originalArrays lowerEvent σ + A a cut hδ externalLaw) + +end +end PerfectCompleteness.HierarchicalProjectedRawAverage + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalProjectedRawMeeting.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalProjectedRawMeeting.lean new file mode 100644 index 0000000000000000000000000000000000000000..9aec7b79f3e7a91903d138cd2a8163557894079e --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalProjectedRawMeeting.lean @@ -0,0 +1,120 @@ +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalProjectedSliceLemmas +import OAI.Computability.PerfectCompleteness.Reduction.FixedComparisonErrorsLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.HierarchicalProjectedRawMeeting + +noncomputable section + +open scoped Classical TensorProduct +open TreeSourceSpaces HierarchicalArrays +open UpperParameterScalars +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype +attribute [local instance] RightDecoder.characterFintype RightDecoder.scalarFintype + +variable {δ : ℚ} (plan : FixedRows.Plan δ) {branch : Nat → Nat} {t : Nat} + (slots projected : RecursiveSpaces.Slots branch plan.depth → Fin t → MixedSupport.Slot) + (projection : ∀ s j, MixedSupport.Projection (slots s j) (projected s j)) + (upper lower : Nodes branch plan.depth) (lowerLevel : Nat) + +local instance rowSpaceFintype : Fintype (NodeEmbedding.RowSpace slots upper) := + Fintype.ofFinite _ + +local instance valueFintype : Fintype + (Block (FixedRows.rows plan) upper × + HierarchicalMatrixTable.SideOutput (rows := FixedRows.rows plan) upper) := + Fintype.ofFinite _ + +local instance upperDualFintype : Fintype (Module.Dual F2 (NodeEmbedding.RowSpace slots upper)) := + LeftDecoder.dualFintype (V := NodeEmbedding.RowSpace slots upper) + +variable {Ω : Type*} [Fintype Ω] + (original : FiniteDistribution Ω) + (originalArrays : Ω → Arrays slots (FixedRows.rows plan)) + (lowerEvent : Ω → Bool) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch plan.depth t)) + (A : ManyGoodRows.RowMap (Block (FixedRows.rows plan) upper) plan.order) + (a : Block (FixedRows.rows plan) lower) + (cut : OwnInputReference.Cut upper lower) + (v : HierarchicalProjectedRawPrediction.Visible projected (FixedRows.rows plan) upper lower A + (FixedRows.repeats plan) cut) + +def meetingProbability : ℝ := + ((HierarchicalProjectedMeeting.leftLaw slots projected projection upper lowerLevel + (HierarchicalProjectedRawPrediction.visibleBackground slots projected projection + (FixedRows.rows plan) upper lower A (FixedRows.repeats plan) cut v) + original originalArrays lowerEvent (InitialParameters.useful δ) σ plan.density A + (HierarchicalProjectedRawPrediction.known projected (FixedRows.rows plan) upper lower A + (FixedRows.repeats plan) cut v)).product + (RightDecoder.law projected (FixedRows.rows plan) upper lower (LinearMap.ker A) a + (FixedRows.repeats plan) cut σ + (OwnInputReference.readInput projected (FixedRows.rows plan) upper lower (LinearMap.ker A) a + (OwnInputRawAssembly.scalarEval projected upper lower (FixedRows.repeats plan) cut) v) + (tau (InitialParameters.useful δ) plan.density plan.order + (FixedRows.rows plan (Nodes.height upper))))).probability + (fun pair => decide ((ProjectedNodeEmbedding.intoOriginal projection upper).dualMap + pair.1 = pair.2)) + +theorem meetingProbability_nonneg : + 0 ≤ meetingProbability plan slots projected projection upper lower lowerLevel + original originalArrays lowerEvent σ A a cut v := + FiniteDistribution.probability_nonnegative _ _ + +theorem meeting_probability_lower (hδ : 0 < δ) + (externalLaw : FiniteDistribution + (OwnInputReference.Exterior projected (FixedRows.rows plan) upper lower)) + (positive : 0 < + (OwnInputReference.rawLaw projected (FixedRows.rows plan) upper lower (LinearMap.ker A) + (FixedRows.repeats plan) cut externalLaw).probability + (HierarchicalProjectedRawPrediction.given slots projected projection (FixedRows.rows plan) + upper lower lowerLevel original originalArrays lowerEvent (InitialParameters.useful δ) + σ plan.density A (FixedRows.repeats plan) cut v)) + (hprediction : rhoPred (InitialParameters.useful δ) plan.density ≤ + ((OwnInputReference.rawLaw projected (FixedRows.rows plan) upper lower (LinearMap.ker A) + (FixedRows.repeats plan) cut externalLaw).condition + (HierarchicalProjectedRawPrediction.given slots projected projection (FixedRows.rows plan) + upper lower lowerLevel original originalArrays lowerEvent (InitialParameters.useful δ) + σ plan.density A (FixedRows.repeats plan) cut v) positive).probability + (HierarchicalProjectedRawPrediction.rawPrediction slots projected projection (FixedRows.rows plan) + upper lower lowerLevel original originalArrays lowerEvent (InitialParameters.useful δ) + σ plan.density A (FixedRows.repeats plan) cut a)) : + (1 / (2 : ℝ) ^ plan.order) * + (tau (InitialParameters.useful δ) plan.density plan.order + (FixedRows.rows plan (Nodes.height upper)) ^ 2 / + (2 * (2 : ℝ) ^ FixedRows.rows plan (Nodes.height upper))) ≤ + meetingProbability plan slots projected projection upper lower lowerLevel + original originalArrays lowerEvent σ A a cut v := by + obtain ⟨hgood, hne⟩ := HierarchicalProjectedRawPrediction.selection_of_positive + slots projected projection (FixedRows.rows plan) upper lower lowerLevel + original originalArrays lowerEvent (InitialParameters.useful δ) σ plan.density A + (FixedRows.repeats plan) cut externalLaw v positive + unfold meetingProbability + apply HierarchicalFixedProjectedMeeting.meeting_probability_lower plan hδ + slots projected projection upper lowerLevel + (HierarchicalProjectedRawPrediction.visibleBackground slots projected projection + (FixedRows.rows plan) upper lower A (FixedRows.repeats plan) cut v) + original originalArrays lowerEvent σ A + (HierarchicalProjectedRawPrediction.known projected (FixedRows.rows plan) upper lower A + (FixedRows.repeats plan) cut v) + lower a cut + (OwnInputReference.readInput projected (FixedRows.rows plan) upper lower (LinearMap.ker A) a + (OwnInputRawAssembly.scalarEval projected upper lower (FixedRows.repeats plan) cut) v) + hgood hne + exact hprediction.trans_eq + (HierarchicalProjectedRawPrediction.conditional_prediction_eq slots projected projection + (FixedRows.rows plan) upper lower lowerLevel original originalArrays lowerEvent + (InitialParameters.useful δ) σ plan.density A (FixedRows.repeats plan) cut + a externalLaw v hgood hne positive) + +end +end PerfectCompleteness.HierarchicalProjectedRawMeeting + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalProjectedSliceLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalProjectedSliceLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..39ae5859accf635df6c5e34277821af388987edc --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalProjectedSliceLemmas.lean @@ -0,0 +1,1059 @@ +import OAI.Computability.PerfectCompleteness.Algebra.AffineDecoderMeeting +import OAI.Computability.PerfectCompleteness.Algebra.RightDecoderAffineSuccess +import OAI.Computability.PerfectCompleteness.Algebra.TensorBucketEvaluationLemmas +import OAI.Computability.PerfectCompleteness.Algebra.TensorRowAdviceLemmas +import OAI.Computability.PerfectCompleteness.Algebra.TensorSliceDimension +import OAI.Computability.PerfectCompleteness.Construction.ProjectedNodeEmbedding +import OAI.Computability.PerfectCompleteness.Decoding.ChildBlockProjection +import OAI.Computability.PerfectCompleteness.Decoding.HierarchicalLeftDecoder +import OAI.Computability.PerfectCompleteness.Decoding.RightDecoderWitness +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalFrozenTablesLemmas +import OAI.Computability.PerfectCompleteness.Machines.OwnInputAffineSliceLemmas +import OAI.Computability.PerfectCompleteness.Machines.OwnInputReferenceLemmas + +namespace OAI + + +namespace PerfectCompleteness.HierarchicalProjectedSlice + +noncomputable section + +open scoped BigOperators Classical TensorProduct +open TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype + +variable {branch rows : Nat → Nat} {n t : Nat} + (originalSlots projectedSlots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (projection : ∀ s j, MixedSupport.Projection (originalSlots s j) (projectedSlots s j)) + (upper : Nodes branch n) (lowerLevel : Nat) + (background : HierarchicalMatrixTable.Background (rows := rows) originalSlots upper) + +local instance rowSpaceFintype : Fintype (NodeEmbedding.RowSpace originalSlots upper) := + Fintype.ofFinite _ + +local instance valueFintype : Fintype + (Block rows upper × HierarchicalMatrixTable.SideOutput (rows := rows) upper) := + Fintype.ofFinite _ + +variable {Ω : Type*} [Fintype Ω] + (original : FiniteDistribution Ω) (arrays : Ω → Arrays originalSlots rows) + (lowerEvent : Ω → Bool) (κ : ℝ) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + {r : Nat} (ρ : ℝ) (A : ManyGoodRows.RowMap (Block rows upper) r) + (known : HiddenBucketBias.VisibleDirection (LinearMap.ker A) → NodeEmbedding.NodeH projectedSlots upper) + +abbrev HiddenTensor := LinearMap.ker A ⊗[F2] NodeEmbedding.NodeH projectedSlots upper + +abbrev visibleMatrix := HierarchicalTensorMatrix.visibleMatrix originalSlots upper (LinearMap.ker A) + (fun v => ProjectedNodeEmbedding.nativePullback projection upper (known v)) + +theorem visibleMatrix_apply + (q : Module.Dual F2 (NodeEmbedding.RowSpace originalSlots upper)) : + visibleMatrix originalSlots projectedSlots projection upper A known q = + ∑ v : HiddenBucketBias.VisibleDirection (LinearMap.ker A), + ((ProjectedNodeEmbedding.intoOriginal projection upper).dualMap q) (known v) • v.val.val := + HierarchicalTensorMatrix.visibleMatrix_apply originalSlots upper (LinearMap.ker A) + (fun v => ProjectedNodeEmbedding.nativePullback projection upper (known v)) q + +abbrev matrix (T : HiddenTensor projectedSlots upper A) := + TensorProjectedSlice.totalMatrix (ProjectedNodeEmbedding.intoOriginal projection upper) (LinearMap.ker A) + (visibleMatrix originalSlots projectedSlots projection upper A known) T + +abbrev quotientMatrix (T : HiddenTensor projectedSlots upper A) := + MatrixRowQuotient.projectMatrix + (HierarchicalFrozenTables.knownRows originalSlots upper lowerLevel background) + (matrix originalSlots projectedSlots projection upper A known T) + +abbrev table := + HierarchicalUsefulness.table originalSlots upper lowerLevel original arrays lowerEvent κ σ background + +abbrev VisibleGood : Prop := + ManyGoodRows.GoodRow (table originalSlots upper lowerLevel background original arrays lowerEvent κ σ) + r ρ A (A.comp (MatrixRowQuotient.projectMatrix + (HierarchicalFrozenTables.knownRows originalSlots upper lowerLevel background) + (visibleMatrix originalSlots projectedSlots projection upper A known))) + +def witness + (hgood : VisibleGood originalSlots projectedSlots projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known) := + TensorSelectedSlice.witness + (HierarchicalFrozenTables.knownRows originalSlots upper lowerLevel background) + (table originalSlots upper lowerLevel background original arrays lowerEvent κ σ) + r ρ A (visibleMatrix originalSlots projectedSlots projection upper A known) hgood + +def columnSpace + (hgood : VisibleGood originalSlots projectedSlots projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known) : + Submodule F2 (Module.Dual F2 (NodeEmbedding.NodeH projectedSlots upper)) := + TensorSelectedSlice.columnSpace (ProjectedNodeEmbedding.intoOriginal projection upper) + (HierarchicalFrozenTables.knownRows originalSlots upper lowerLevel background) + (table originalSlots upper lowerLevel background original arrays lowerEvent κ σ) + r ρ A (visibleMatrix originalSlots projectedSlots projection upper A known) hgood + +theorem columnSpace_eq_pulled + (hgood : VisibleGood originalSlots projectedSlots projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known) : + columnSpace originalSlots projectedSlots projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood = + ((witness originalSlots projectedSlots projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood).columnSpace.map + (HierarchicalFrozenTables.knownRows originalSlots upper lowerLevel background).mkQ.dualMap).map + (ProjectedNodeEmbedding.intoOriginal projection upper).dualMap := + TensorSelectedSlice.columnSpace_eq_sequential_maps (ProjectedNodeEmbedding.intoOriginal projection upper) + (HierarchicalFrozenTables.knownRows originalSlots upper lowerLevel background) + (table originalSlots upper lowerLevel background original arrays lowerEvent κ σ) + r ρ A (visibleMatrix originalSlots projectedSlots projection upper A known) hgood + +theorem finrank_columnSpace_le + (hgood : VisibleGood originalSlots projectedSlots projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known) : + Module.finrank F2 + (columnSpace originalSlots projectedSlots projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood) ≤ r := + TensorSelectedSlice.finrank_columnSpace_le (ProjectedNodeEmbedding.intoOriginal projection upper) + (HierarchicalFrozenTables.knownRows originalSlots upper lowerLevel background) + (table originalSlots upper lowerLevel background original arrays lowerEvent κ σ) + r ρ A (visibleMatrix originalSlots projectedSlots projection upper A known) hgood + +def J (T : HiddenTensor projectedSlots upper A) : Bool := + GoodAdviceEvents.J (table originalSlots upper lowerLevel background original arrays lowerEvent κ σ) + r ρ (A, quotientMatrix originalSlots projectedSlots projection upper lowerLevel background A known T) + +def target + (hgood : VisibleGood originalSlots projectedSlots projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known) + (hne : ∃ T, J originalSlots projectedSlots projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known T = true) : + columnSpace originalSlots projectedSlots projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood →ₗ[F2] + LinearMap.ker A := + TensorSelectedSlice.target (ProjectedNodeEmbedding.intoOriginal projection upper) (LinearMap.ker A) + (HierarchicalFrozenTables.knownRows originalSlots upper lowerLevel background) + (table originalSlots upper lowerLevel background original arrays lowerEvent κ σ) + r ρ A (visibleMatrix originalSlots projectedSlots projection upper A known) le_rfl hgood hne + +theorem J_iff_restriction + (hgood : VisibleGood originalSlots projectedSlots projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known) + (hne : ∃ T, J originalSlots projectedSlots projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known T = true) + (T : HiddenTensor projectedSlots upper A) : + J originalSlots projectedSlots projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known T = true ↔ + TensorRestriction.restrictionMap + (columnSpace originalSlots projectedSlots projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood) T = + target originalSlots projectedSlots projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood hne := + TensorSelectedSlice.J_iff_restriction (ProjectedNodeEmbedding.intoOriginal projection upper) (LinearMap.ker A) + (HierarchicalFrozenTables.knownRows originalSlots upper lowerLevel background) + (table originalSlots upper lowerLevel background original arrays lowerEvent κ σ) + r ρ A (visibleMatrix originalSlots projectedSlots projection upper A known) le_rfl hgood hne T + +theorem J_false_of_not_good + (hbad : ¬ VisibleGood originalSlots projectedSlots projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known) + (T : HiddenTensor projectedSlots upper A) : + J originalSlots projectedSlots projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known T = false := + TensorSelectedSlice.J_false_of_not_good (ProjectedNodeEmbedding.intoOriginal projection upper) (LinearMap.ker A) + (HierarchicalFrozenTables.knownRows originalSlots upper lowerLevel background) + (table originalSlots upper lowerLevel background original arrays lowerEvent κ σ) + r ρ A (visibleMatrix originalSlots projectedSlots projection upper A known) le_rfl hbad T + +theorem selectedValue_eq_some + (hgood : VisibleGood originalSlots projectedSlots projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known) + (T : HiddenTensor projectedSlots upper A) : + HierarchicalPrediction.selectedValue + (table originalSlots upper lowerLevel background original arrays lowerEvent κ σ) r ρ A + (quotientMatrix originalSlots projectedSlots projection upper lowerLevel background A known T) = + some (witness originalSlots projectedSlots projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood).value := by + change HierarchicalPrediction.selectedValue _ r ρ A + (MatrixRowQuotient.projectMatrix _ (TensorProjectedSlice.totalMatrix _ _ _ T)) = _ + rw [TensorRowAdvice.selectedValue_projectMatrix_eq (ProjectedNodeEmbedding.intoOriginal projection upper) + (LinearMap.ker A) A le_rfl + (HierarchicalFrozenTables.knownRows originalSlots upper lowerLevel background) + (table originalSlots upper lowerLevel background original arrays lowerEvent κ σ) ρ + (visibleMatrix originalSlots projectedSlots projection upper A known) T] + simp only [HierarchicalPrediction.selectedValue, dite_eq_left hgood, witness, + TensorSelectedSlice.witness] + +def correction + (y : Block rows upper × HierarchicalMatrixTable.SideOutput (rows := rows) upper) : + Module.Dual F2 (NodeEmbedding.RowSpace originalSlots upper) := + RepresentativeMatrixTable.correctionFunctional (TreeCanonical.numberedSlots originalSlots) + (NodeEmbedding.RowSpace originalSlots upper) (HierarchicalMatrixTable.other originalSlots upper background) + (HierarchicalFrozenTables.knownRows originalSlots upper lowerLevel background) + (HierarchicalFrozenTables.sectionMap originalSlots upper lowerLevel background) + (HierarchicalFrozenTables.sectionMap_spec originalSlots upper lowerLevel background) y.2 + +def nativeCorrection + (hgood : VisibleGood originalSlots projectedSlots projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known) : + Module.Dual F2 (NodeEmbedding.NodeH projectedSlots upper) := + (correction originalSlots upper lowerLevel background + (witness originalSlots projectedSlots projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood).value).comp + (ProjectedNodeEmbedding.intoOriginal projection upper) + +theorem nativeCorrection_eq_upperTarget + (hgood : VisibleGood originalSlots projectedSlots projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known) : + nativeCorrection originalSlots projectedSlots projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood = + DecoderSourcePullback.upperTarget projection upper + (correction originalSlots upper lowerLevel background + (witness originalSlots projectedSlots projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood).value) := + ProjectedNodeEmbedding.dualMap_eq_upperTarget projection upper + (correction originalSlots upper lowerLevel background + (witness originalSlots projectedSlots projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood).value) + +def visibleOffset + (hgood : VisibleGood originalSlots projectedSlots projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known) : + Block rows upper := + visibleMatrix originalSlots projectedSlots projection upper A known + (correction originalSlots upper lowerLevel background + (witness originalSlots projectedSlots projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood).value) + + (witness originalSlots projectedSlots projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood).value.1 + +theorem selectedCorrection_eq_some + (hgood : VisibleGood originalSlots projectedSlots projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known) + (T : HiddenTensor projectedSlots upper A) : + (HierarchicalPrediction.selectedValue + (table originalSlots upper lowerLevel background original arrays lowerEvent κ σ) r ρ A + (quotientMatrix originalSlots projectedSlots projection upper lowerLevel background A known T)).map + (fun y => (correction originalSlots upper lowerLevel background y).comp + (ProjectedNodeEmbedding.intoOriginal projection upper)) = + some (nativeCorrection originalSlots projectedSlots projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood) := by + simp only [selectedValue_eq_some originalSlots projectedSlots projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood T, + Option.map_some, nativeCorrection] + +theorem affinePrediction_eq_tensor + (hgood : VisibleGood originalSlots projectedSlots projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known) + (T : HiddenTensor projectedSlots upper A) : + HierarchicalPrediction.affinePrediction originalSlots upper lowerLevel background + (matrix originalSlots projectedSlots projection upper A known T) + (witness originalSlots projectedSlots projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood).value = + visibleOffset originalSlots projectedSlots projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood + + TensorBucketEvaluation.tensorOutput (LinearMap.ker A) + (nativeCorrection originalSlots projectedSlots projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood) T := + TensorProjectedSlice.prediction_eq_visible_add_tensorOutput (ProjectedNodeEmbedding.intoOriginal projection upper) + (LinearMap.ker A) (visibleMatrix originalSlots projectedSlots projection upper A known) T + (correction originalSlots upper lowerLevel background + (witness originalSlots projectedSlots projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood).value) + (witness originalSlots projectedSlots projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood).value.1 + +end +end PerfectCompleteness.HierarchicalProjectedSlice + + +namespace PerfectCompleteness.HierarchicalProjectedMeeting + +noncomputable section + +open scoped Classical TensorProduct +open TreeSourceSpaces HierarchicalArrays HierarchicalProjectedSlice +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype +attribute [local instance] RightDecoder.characterFintype RightDecoder.scalarFintype + +variable {branch rows : Nat → Nat} {n t : Nat} + (slots projected : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (projection : ∀ s j, MixedSupport.Projection (slots s j) (projected s j)) + (upper : Nodes branch n) (lowerLevel : Nat) + (background : HierarchicalMatrixTable.Background (rows := rows) slots upper) + +local instance rowSpaceFintype : Fintype (NodeEmbedding.RowSpace slots upper) := + Fintype.ofFinite _ + +local instance valueFintype : Fintype + (Block rows upper × HierarchicalMatrixTable.SideOutput (rows := rows) upper) := + Fintype.ofFinite _ + +local instance upperDualFintype : Fintype (Module.Dual F2 (NodeEmbedding.RowSpace slots upper)) := + LeftDecoder.dualFintype (V := NodeEmbedding.RowSpace slots upper) + +variable {Ω : Type*} [Fintype Ω] + (original : FiniteDistribution Ω) (arrays : Ω → Arrays slots rows) + (lowerEvent : Ω → Bool) (κ : ℝ) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + {r : Nat} (ρ : ℝ) (A : ManyGoodRows.RowMap (Block rows upper) r) + (known : HiddenBucketBias.VisibleDirection (LinearMap.ker A) → NodeEmbedding.NodeH projected upper) + +def useful (X : HierarchicalFrozenTables.QuotientMatrix slots upper lowerLevel background) : Prop := + HierarchicalUsefulness.mark slots upper lowerLevel original arrays lowerEvent κ + ⟨background, X⟩ = true + +def leftLaw : FiniteDistribution (Module.Dual F2 (NodeEmbedding.RowSpace slots upper)) := + HierarchicalLeftDecoder.adviceLaw slots upper lowerLevel background σ + (useful slots upper lowerLevel background original arrays lowerEvent κ) r ρ A + (A.comp (MatrixRowQuotient.projectMatrix + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + (visibleMatrix slots projected projection upper A known))) + +theorem leftLaw_congr + (projected₂ : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (projection₂ : ∀ s j, MixedSupport.Projection (slots s j) (projected₂ s j)) + (known₂ : HiddenBucketBias.VisibleDirection (LinearMap.ker A) → + NodeEmbedding.NodeH projected₂ upper) + (hU : A.comp (MatrixRowQuotient.projectMatrix + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + (visibleMatrix slots projected projection upper A known)) = + A.comp (MatrixRowQuotient.projectMatrix + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + (visibleMatrix slots projected₂ projection₂ upper A known₂))) : + leftLaw slots projected projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known = + leftLaw slots projected₂ projection₂ upper lowerLevel background original arrays lowerEvent κ σ ρ A known₂ := by + unfold leftLaw + rw [hU] + +theorem leftLaw_eq_affine + (hgood : VisibleGood slots projected projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known) : + leftLaw slots projected projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known = + LeftDecoder.affineLaw + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + (witness slots projected projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood).columnSpace + (correction slots upper lowerLevel background + (witness slots projected projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood).value) := by + have h := LeftDecoder.adviceLaw_of_good (TreeCanonical.numberedSlots slots) + (NodeEmbedding.RowSpace slots upper) (HierarchicalMatrixTable.other slots upper background) σ + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + (HierarchicalFrozenTables.sectionMap slots upper lowerLevel background) + (HierarchicalFrozenTables.sectionMap_spec slots upper lowerLevel background) + (useful slots upper lowerLevel background original arrays lowerEvent κ) r ρ A + (A.comp (MatrixRowQuotient.projectMatrix + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + (visibleMatrix slots projected projection upper A known))) hgood + dsimp only [leftLaw, HierarchicalLeftDecoder.adviceLaw, LeftDecoder.law, LeftDecoder.center, + HierarchicalProjectedSlice.witness, TensorSelectedSlice.witness, HierarchicalProjectedSlice.correction, + HierarchicalProjectedSlice.table, HierarchicalUsefulness.table, HierarchicalFrozenTables.table, + useful] at h ⊢ + exact h + +theorem columnSpace_eq_nativeQ + (hgood : VisibleGood slots projected projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known) : + columnSpace slots projected projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood = + AffineDecoderMeeting.nativeQ (ProjectedNodeEmbedding.intoOriginal projection upper) + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + (witness slots projected projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood).columnSpace := + HierarchicalProjectedSlice.columnSpace_eq_pulled slots projected projection upper lowerLevel background + original arrays lowerEvent κ σ ρ A known hgood + +theorem nativeCorrection_eq_nativeCenter + (hgood : VisibleGood slots projected projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known) : + nativeCorrection slots projected projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood = + AffineDecoderMeeting.nativeCenter (ProjectedNodeEmbedding.intoOriginal projection upper) + (correction slots upper lowerLevel background + (witness slots projected projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood).value) := rfl + +variable (lower : Nodes branch n) (a : Block rows lower) + (repeats : Nat → Nat) (cut : OwnInputReference.Cut upper lower) + (input : OwnInputReference.Input projected rows upper lower (LinearMap.ker A) a) + +theorem meeting_probability_ge_coset + (hgood : VisibleGood slots projected projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known) + (threshold : ℝ) : + (1 / (2 : ℝ) ^ r) * + (RightDecoder.law projected rows upper lower (LinearMap.ker A) a repeats cut σ input threshold).probability + (fun decoded => decide (decoded - + nativeCorrection slots projected projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood ∈ + columnSpace slots projected projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood)) ≤ + ((leftLaw slots projected projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known).product + (RightDecoder.law projected rows upper lower (LinearMap.ker A) a repeats cut σ input threshold)).probability + (fun pair => decide ((ProjectedNodeEmbedding.intoOriginal projection upper).dualMap pair.1 = pair.2)) := by + rw [leftLaw_eq_affine slots projected projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood] + apply AffineDecoderMeeting.product_probability_lower + intro decoded hdecoded + have bound := AffineDecoderMeeting.native_point_probability_lower (ProjectedNodeEmbedding.intoOriginal projection upper) + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + (witness slots projected projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood).columnSpace + (correction slots upper lowerLevel background + (witness slots projected projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood).value) + (witness slots projected projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood).column_count decoded (by + have hd := of_decide_eq_true hdecoded + simpa only [columnSpace_eq_nativeQ slots projected projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood, + nativeCorrection_eq_nativeCenter slots projected projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood] + using hd) + convert bound using 1 + congr 1 + funext candidate + exact (@decide_eq_decide _ _ _ _).mpr Iff.rfl + +theorem meeting_probability_lower + (hgood : VisibleGood slots projected projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known) + (hne : ∃ T, J slots projected projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known T = true) + (ρpred h₀ : ℝ) (hρpred : 0 < ρpred) (hh₀ : 0 < h₀) + (hrep : RecursiveSamplerBias.RepetitionsBalanced repeats) + (hslice : (7 / 8 : ℝ) ^ repeats (Nodes.height upper) ≤ h₀ / 2) + (hlist : (7 / 8 : ℝ) ^ repeats (Nodes.height upper) ≤ (ρpred * h₀ / 4) ^ 2 / 2) + (hexcluded : 1 / (2 : ℝ) ^ Module.finrank F2 (LinearMap.ker A) < ρpred / 8) + (hsize : h₀ ≤ 1 / (2 : ℝ) ^ (r * rows (Nodes.height upper))) + (hmatch : ρpred ≤ RightDecoderWitness.conditionalMatch projected rows upper lower + (LinearMap.ker A) a repeats cut σ input + (columnSpace slots projected projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood) + (target slots projected projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood hne) + (nativeCorrection slots projected projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood) + (visibleOffset slots projected projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood)) : + (1 / (2 : ℝ) ^ r) * + ((ρpred * h₀ / 4) ^ 2 / (2 * (2 : ℝ) ^ rows (Nodes.height upper))) ≤ + ((leftLaw slots projected projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known).product + (RightDecoder.law projected rows upper lower (LinearMap.ker A) a repeats cut σ input + (ρpred * h₀ / 4))).probability + (fun pair => decide ((ProjectedNodeEmbedding.intoOriginal projection upper).dualMap pair.1 = pair.2)) := by + have hdimension := TensorSliceDimension.equation_finrank_le (LinearMap.ker A) + (columnSpace slots projected projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood) + (HierarchicalProjectedSlice.finrank_columnSpace_le slots projected projection upper lowerLevel background + original arrays lowerEvent κ σ ρ A known hgood) + have hsize' : h₀ ≤ 1 / (2 : ℝ) ^ Module.finrank F2 + ((columnSpace slots projected projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood) →ₗ[F2] + LinearMap.ker A) := + hsize.trans (one_div_pow_le_one_div_pow_of_le (by norm_num : (1 : ℝ) ≤ 2) hdimension) + have hright := RightDecoderAffineSuccess.coset_probability_lower projected rows upper lower + (LinearMap.ker A) a repeats cut σ input ρpred h₀ hρpred hh₀ hrep hslice hlist hexcluded + (columnSpace slots projected projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood) + hsize' + (target slots projected projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood hne) + (nativeCorrection slots projected projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood) + (visibleOffset slots projected projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known hgood) hmatch + exact (mul_le_mul_of_nonneg_left hright + (div_nonneg zero_le_one (pow_nonneg (by norm_num : (0 : ℝ) ≤ 2) r))).trans + (meeting_probability_ge_coset slots projected projection upper lowerLevel background original arrays lowerEvent κ σ ρ A known + lower a repeats cut input hgood (ρpred * h₀ / 4)) + +end +end PerfectCompleteness.HierarchicalProjectedMeeting + + +namespace PerfectCompleteness.ProjectedRawAssembly + +noncomputable section + +open scoped BigOperators Classical TensorProduct +open TreeSourceSpaces HierarchicalArrays + +variable {branch : Nat → Nat} {n t : Nat} + (originalSlots projectedSlots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (projection : ∀ s k, MixedSupport.Projection (originalSlots s k) (projectedSlots s k)) + (rows : Nat → Nat) (upper lower : Nodes branch n) + +def exteriorBackground + (external : OwnInputReference.Exterior projectedSlots rows upper lower) : + HierarchicalMatrixTable.Background (rows := rows) originalSlots upper := + fun node row => ProjectedNodeEmbedding.nativePullback projection node.val + (OwnInputRawAssembly.exteriorBackground projectedSlots rows upper lower external node row) + +variable (W : Submodule F2 (Block rows upper)) + (repeats : Nat → Nat) (cut : OwnInputReference.Cut upper lower) + +def arrays + (sample : OwnInputReference.RawSample projectedSlots rows upper lower W repeats cut) : + Arrays originalSlots rows := + ChildBlockProjection.arraysPullback rows projection + (OwnInputRawAssembly.arrays projectedSlots rows upper lower W repeats cut sample) + +def background + (visible : OwnInputAffineSlice.VisibleSample projectedSlots rows upper lower W repeats cut) : + HierarchicalMatrixTable.Background (rows := rows) originalSlots upper := + exteriorBackground originalSlots projectedSlots projection rows upper lower visible.2 + +def visibleMatrix + (visible : OwnInputAffineSlice.VisibleSample projectedSlots rows upper lower W repeats cut) : + Module.Dual F2 (NodeEmbedding.RowSpace originalSlots upper) →ₗ[F2] Block rows upper := + HierarchicalTensorMatrix.visibleMatrix originalSlots upper W + (fun v => ProjectedNodeEmbedding.nativePullback projection upper + (OwnInputRawAssembly.knownVisible projectedSlots rows upper lower W repeats cut visible v)) + +theorem visibleMatrix_apply + (visible : OwnInputAffineSlice.VisibleSample projectedSlots rows upper lower W repeats cut) + (q : Module.Dual F2 (NodeEmbedding.RowSpace originalSlots upper)) : + visibleMatrix originalSlots projectedSlots projection rows upper lower W repeats cut visible q = + ∑ v : HiddenBucketBias.VisibleDirection W, + (q.comp (ProjectedNodeEmbedding.intoOriginal projection upper)) + (OwnInputRawAssembly.knownVisible projectedSlots rows upper lower W repeats cut visible v) • + v.val.val := + HierarchicalTensorMatrix.visibleMatrix_apply originalSlots upper W + (fun v => ProjectedNodeEmbedding.nativePullback projection upper + (OwnInputRawAssembly.knownVisible projectedSlots rows upper lower W repeats cut visible v)) q + +theorem arrays_upper + (sample : OwnInputReference.RawSample projectedSlots rows upper lower W repeats cut) + (row : Fin (rows (Nodes.height upper))) : + arrays originalSlots projectedSlots projection rows upper lower W repeats cut sample upper row = + ProjectedNodeEmbedding.nativePullback projection upper + (BucketSampler.evaluate (rows (Nodes.height upper)) + (OwnInputRawAssembly.scalarEval projectedSlots upper lower repeats cut) + (OwnInputRawAssembly.mergedTape projectedSlots rows upper lower W repeats cut sample) row) := by + change ProjectedNodeEmbedding.nativePullback projection upper + (OwnInputRawAssembly.arrays projectedSlots rows upper lower W repeats cut sample upper row) = _ + rw [OwnInputRawAssembly.arrays_upper] + +theorem background_arrays + (sample : OwnInputReference.RawSample projectedSlots rows upper lower W repeats cut) : + HierarchicalMatrixTable.backgroundOf originalSlots upper + (arrays originalSlots projectedSlots projection rows upper lower W repeats cut sample) = + background originalSlots projectedSlots projection rows upper lower W repeats cut sample.2 := by + funext node row + exact congrArg + (fun bg : HierarchicalMatrixTable.Background (rows := rows) projectedSlots upper => + ProjectedNodeEmbedding.nativePullback projection node.val (bg node row)) + (OwnInputRawAssembly.background_arrays projectedSlots rows upper lower W repeats cut sample) + +theorem arrays_eq_matrix_assemble + (sample : OwnInputReference.RawSample projectedSlots rows upper lower W repeats cut) : + arrays originalSlots projectedSlots projection rows upper lower W repeats cut sample = + HierarchicalMatrixTable.assemble originalSlots upper + (background originalSlots projectedSlots projection rows upper lower W repeats cut sample.2) + (NodeEmbedding.matrix + (arrays originalSlots projectedSlots projection rows upper lower W repeats cut sample) upper) := by + have h := HierarchicalMatrixTable.assemble_original originalSlots upper + (arrays originalSlots projectedSlots projection rows upper lower W repeats cut sample) + rw [background_arrays] at h + exact h.symm + +theorem matrix_arrays + (sample : OwnInputReference.RawSample projectedSlots rows upper lower W repeats cut) : + NodeEmbedding.matrix + (arrays originalSlots projectedSlots projection rows upper lower W repeats cut sample) upper = + TensorProjectedSlice.totalMatrix (ProjectedNodeEmbedding.intoOriginal projection upper) W + (visibleMatrix originalSlots projectedSlots projection rows upper lower W repeats cut sample.2) + (OwnInputAffineSlice.hiddenOutput projectedSlots rows upper lower W repeats cut sample) := by + apply LinearMap.ext + intro q + have hsplit := TensorBucketEvaluation.evaluate_splitTape W + (q.comp (ProjectedNodeEmbedding.intoOriginal projection upper)) + (OwnInputRawAssembly.scalarEval projectedSlots upper lower repeats cut) + (OwnInputRawAssembly.mergedTape projectedSlots rows upper lower W repeats cut sample) + rw [OwnInputRawAssembly.split_mergedTape] at hsplit + calc + NodeEmbedding.matrix + (arrays originalSlots projectedSlots projection rows upper lower W repeats cut sample) upper q = + (fun row => (q.comp (ProjectedNodeEmbedding.intoOriginal projection upper)) + (OwnInputRawAssembly.arrays projectedSlots rows upper lower W repeats cut sample upper row)) := rfl + _ = (fun row => (q.comp (ProjectedNodeEmbedding.intoOriginal projection upper)) + (BucketSampler.evaluate (rows (Nodes.height upper)) + (OwnInputRawAssembly.scalarEval projectedSlots upper lower repeats cut) + (OwnInputRawAssembly.mergedTape projectedSlots rows upper lower W repeats cut sample) row)) := by + rw [OwnInputRawAssembly.arrays_upper] + _ = TensorBucketEvaluation.visibleOutput W + (q.comp (ProjectedNodeEmbedding.intoOriginal projection upper)) + (OwnInputRawAssembly.scalarEval projectedSlots upper lower repeats cut) sample.2.1 + + TensorBucketEvaluation.tensorOutput W + (q.comp (ProjectedNodeEmbedding.intoOriginal projection upper)) + (OwnInputAffineSlice.hiddenOutput projectedSlots rows upper lower W repeats cut sample) := hsplit + _ = _ := by + rw [TensorProjectedSlice.totalMatrix_apply, + TensorProjectedSlice.includedEvaluation_eq_tensorOutput, visibleMatrix_apply] + rfl + +end +end PerfectCompleteness.ProjectedRawAssembly + + +namespace PerfectCompleteness.SourceProjectedCanonicalQuery + +open scoped Classical +open RecursiveSpaces TreeSourceSpaces HierarchicalArrays + +noncomputable section + +abbrev F2 := ZMod 2 + +variable {branch : Nat → Nat} {n t : Nat} + {slots projected : Slots branch n → Fin t → MixedSupport.Slot} + (rows : Nat → Nat) + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + +def query {Y : Type*} (arrays : Arrays slots rows) (post : Output branch n rows → Y) : + MixedSupport.Assignment (TreeCanonical.numberedSlots slots) → Y := + post ∘ TreeCanonical.numberedFunction slots (fullJoint arrays) + +theorem query_pullback {Y : Type*} (arrays : Arrays projected rows) + (post : Output branch n rows → Y) : + query rows (ChildBlockProjection.arraysPullback rows p arrays) post = + query rows arrays post ∘ MixedSupport.projectionMap (TreeCanonical.numberedProjection p) := by + funext x + change post (fullJoint (ChildBlockProjection.arraysPullback rows p arrays) + ((TreeCanonical.assignmentEquiv slots).symm x)) = + post (fullJoint arrays ((TreeCanonical.assignmentEquiv projected).symm + (MixedSupport.projectionMap (TreeCanonical.numberedProjection p) x))) + rw [ChildBlockProjection.fullJoint_pullback, TreeCanonical.assignmentEquiv_symm_projection] + +theorem key_pullback {Y : Type*} (arrays : Arrays projected rows) + (post : Output branch n rows → Y) (side : CanonicalKeys.Side) : + CanonicalKeys.key side (TreeCanonical.numberedSlots slots) + (query rows (ChildBlockProjection.arraysPullback rows p arrays) post) = + CanonicalKeys.key side (TreeCanonical.numberedSlots projected) (query rows arrays post) := by + rw [query_pullback] + exact CanonicalKeys.key_projection side (TreeCanonical.numberedProjection p) (query rows arrays post) + +theorem label_val_pullback {Y : Type*} (arrays : Arrays projected rows) + (post : Output branch n rows → Y) + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (side : CanonicalKeys.Side) : + (KeyStrategy.label labeling side (TreeCanonical.numberedSlots slots) + (query rows (ChildBlockProjection.arraysPullback rows p arrays) post)).val = + (KeyStrategy.label labeling side (TreeCanonical.numberedSlots projected) + (query rows arrays post)).val := + KeyStrategy.label_val_eq_of_key_eq labeling side side _ _ _ _ + (key_pullback rows p arrays post side) + +theorem response_pullback {Y : Type*} (arrays : Arrays projected rows) + (post : Output branch n rows → Y) + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (side : CanonicalKeys.Side) : + KeyStrategy.response labeling side (TreeCanonical.numberedSlots slots) + (query rows (ChildBlockProjection.arraysPullback rows p arrays) post) = + KeyStrategy.response labeling side (TreeCanonical.numberedSlots projected) + (query rows arrays post) := by + rw [query_pullback] + exact KeyStrategy.response_projection labeling side (TreeCanonical.numberedProjection p) + (query rows arrays post) + +theorem canonicalQuery_pullback (lower : Nodes branch n) (a : Block rows lower) + (arrays : Arrays projected rows) : + OwnInputCanonicalQuery.canonicalQuery slots rows lower a + (ChildBlockProjection.arraysPullback rows p arrays) = + OwnInputCanonicalQuery.canonicalQuery projected rows lower a arrays ∘ + MixedSupport.projectionMap (TreeCanonical.numberedProjection p) := + query_pullback rows p arrays (BlockQuotient.projectBlock lower a) + +theorem canonical_response_pullback (lower : Nodes branch n) (a : Block rows lower) + (arrays : Arrays projected rows) + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (side : CanonicalKeys.Side) : + KeyStrategy.response labeling side (TreeCanonical.numberedSlots slots) + (OwnInputCanonicalQuery.canonicalQuery slots rows lower a + (ChildBlockProjection.arraysPullback rows p arrays)) = + KeyStrategy.response labeling side (TreeCanonical.numberedSlots projected) + (OwnInputCanonicalQuery.canonicalQuery projected rows lower a arrays) := + response_pullback rows p arrays (BlockQuotient.projectBlock lower a) labeling side + +theorem response_readInput_hidden (upper lower : Nodes branch n) (hne : upper ≠ lower) + (W : Submodule F2 (OwnInputReference.UpperVector rows upper)) (a : Block rows lower) + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + {Ω : Type*} (eval : Ω → OwnInputReference.UpperSpace projected upper) + (tape : BucketSampler.Tape (rows (Nodes.height upper)) Ω) + (external : OwnInputReference.Exterior projected rows upper lower) : + OwnInputReference.response projected rows upper lower W a labeling + (OwnInputReference.readInput projected rows upper lower W a eval + ((HiddenBucketBias.splitTape W Ω tape).2, external)) + (HiddenBucketBias.hiddenSum W eval (HiddenBucketBias.splitTape W Ω tape).1) = + (KeyStrategy.response labeling .right (TreeCanonical.numberedSlots slots) + (OwnInputCanonicalQuery.canonicalQuery slots rows lower a + (ChildBlockProjection.arraysPullback rows p + (OwnInputCanonicalQuery.assemble projected rows upper lower + (BucketSampler.evaluate (rows (Nodes.height upper)) eval tape) external)))).2.1 + ⟨upper, hne⟩ := by + have h := OwnInputCanonicalQuery.response_readInput_hidden_eq projected rows upper lower + hne W a labeling eval tape external + rw [← canonical_response_pullback rows p lower a + (OwnInputCanonicalQuery.assemble projected rows upper lower + (BucketSampler.evaluate (rows (Nodes.height upper)) eval tape) external) labeling .right] at h + exact h + +theorem response_readInput_hidden_arrays (upper lower : Nodes branch n) (hne : upper ≠ lower) + (W : Submodule F2 (OwnInputReference.UpperVector rows upper)) (a : Block rows lower) + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + {Ω : Type*} (eval : Ω → OwnInputReference.UpperSpace projected upper) + (tape : BucketSampler.Tape (rows (Nodes.height upper)) Ω) + (arrays : Arrays projected rows) + (hupper : BucketSampler.evaluate (rows (Nodes.height upper)) eval tape = arrays upper) : + OwnInputReference.response projected rows upper lower W a labeling + (OwnInputReference.readInput projected rows upper lower W a eval + ((HiddenBucketBias.splitTape W Ω tape).2, + OwnInputCanonicalQuery.exteriorOf projected rows upper lower arrays)) + (HiddenBucketBias.hiddenSum W eval (HiddenBucketBias.splitTape W Ω tape).1) = + (KeyStrategy.response labeling .right (TreeCanonical.numberedSlots slots) + (OwnInputCanonicalQuery.canonicalQuery slots rows lower a + (ChildBlockProjection.arraysPullback rows p arrays))).2.1 ⟨upper, hne⟩ := + (OwnInputCanonicalQuery.response_readInput_hidden_arrays projected rows upper lower + hne W a labeling eval tape arrays hupper).trans + (congrArg (fun value : OwnInputCanonicalQuery.CanonicalOutput rows lower a => + value.2.1 ⟨upper, hne⟩) + (canonical_response_pullback rows p lower a arrays labeling .right).symm) + +end +end PerfectCompleteness.SourceProjectedCanonicalQuery + + +namespace PerfectCompleteness.HierarchicalProjectedRawPrediction + +noncomputable section + +open scoped Classical TensorProduct +open TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype + +variable {branch : Nat → Nat} {n t : Nat} + (originalSlots projectedSlots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (projection : ∀ s j, MixedSupport.Projection (originalSlots s j) (projectedSlots s j)) + (rows : Nat → Nat) (upper lower : Nodes branch n) (lowerLevel : Nat) + +local instance rowSpaceFintype : Fintype (NodeEmbedding.RowSpace originalSlots upper) := + Fintype.ofFinite _ + +local instance valueFintype : Fintype + (Block rows upper × HierarchicalMatrixTable.SideOutput (rows := rows) upper) := + Fintype.ofFinite _ + +variable {Ω : Type*} [Fintype Ω] + (original : FiniteDistribution Ω) (originalArrays : Ω → Arrays originalSlots rows) + (lowerEvent : Ω → Bool) (κ : ℝ) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + {r : Nat} (ρ : ℝ) (A : ManyGoodRows.RowMap (Block rows upper) r) + (repeats : Nat → Nat) (cut : OwnInputReference.Cut upper lower) + +abbrev Raw := OwnInputReference.RawSample projectedSlots rows upper lower (LinearMap.ker A) repeats cut +abbrev Visible := OwnInputAffineSlice.VisibleSample projectedSlots rows upper lower (LinearMap.ker A) repeats cut + +abbrev rawArrays (sample : Raw projectedSlots rows upper lower A repeats cut) := + ProjectedRawAssembly.arrays originalSlots projectedSlots projection rows upper lower (LinearMap.ker A) repeats cut sample + +abbrev rawBackground (sample : Raw projectedSlots rows upper lower A repeats cut) := + HierarchicalMatrixTable.backgroundOf originalSlots upper + (rawArrays originalSlots projectedSlots projection rows upper lower A repeats cut sample) + +abbrev rawMatrix (sample : Raw projectedSlots rows upper lower A repeats cut) := + NodeEmbedding.matrix (rawArrays originalSlots projectedSlots projection rows upper lower A repeats cut sample) upper + +abbrev visibleBackground (v : Visible projectedSlots rows upper lower A repeats cut) := + ProjectedRawAssembly.background originalSlots projectedSlots projection rows upper lower (LinearMap.ker A) repeats cut v + +abbrev known (v : Visible projectedSlots rows upper lower A repeats cut) := + OwnInputRawAssembly.knownVisible projectedSlots rows upper lower (LinearMap.ker A) repeats cut v + +abbrev hidden (sample : Raw projectedSlots rows upper lower A repeats cut) := + OwnInputAffineSlice.hiddenOutput projectedSlots rows upper lower (LinearMap.ker A) repeats cut sample + +theorem response_eq_canonical (a : Block rows lower) + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (sample : Raw projectedSlots rows upper lower A repeats cut) : + OwnInputReference.response projectedSlots rows upper lower (LinearMap.ker A) a labeling + (OwnInputReference.readInput projectedSlots rows upper lower (LinearMap.ker A) a + (OwnInputRawAssembly.scalarEval projectedSlots upper lower repeats cut) sample.2) + (hidden projectedSlots rows upper lower A repeats cut sample) = + (KeyStrategy.response labeling .right (TreeCanonical.numberedSlots originalSlots) + (OwnInputCanonicalQuery.canonicalQuery originalSlots rows lower a + (rawArrays originalSlots projectedSlots projection rows upper lower A repeats cut sample))).2.1 + ⟨upper, cut.upper_ne_lower⟩ := by + have h := SourceProjectedCanonicalQuery.response_readInput_hidden rows projection upper lower + cut.upper_ne_lower (LinearMap.ker A) a labeling + (OwnInputRawAssembly.scalarEval projectedSlots upper lower repeats cut) + (OwnInputRawAssembly.mergedTape projectedSlots rows upper lower (LinearMap.ker A) repeats cut sample) + sample.2.2 + rw [OwnInputRawAssembly.split_mergedTape] at h + exact h + +theorem response_eq_rightUpper (a : Block rows lower) + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (sample : Raw projectedSlots rows upper lower A repeats cut) : + OwnInputReference.response projectedSlots rows upper lower (LinearMap.ker A) a labeling + (OwnInputReference.readInput projectedSlots rows upper lower (LinearMap.ker A) a + (OwnInputRawAssembly.scalarEval projectedSlots upper lower repeats cut) sample.2) + (hidden projectedSlots rows upper lower A repeats cut sample) = + HierarchicalPrediction.rightUpper originalSlots upper + (visibleBackground originalSlots projectedSlots projection rows upper lower A repeats cut sample.2) + labeling lower cut.upper_ne_lower a + (rawMatrix originalSlots projectedSlots projection rows upper lower A repeats cut sample) := by + dsimp only [visibleBackground, rawMatrix, rawArrays] + rw [← ProjectedRawAssembly.background_arrays originalSlots projectedSlots projection rows upper lower + (LinearMap.ker A) repeats cut sample, + HierarchicalPrediction.rightUpper, HierarchicalMatrixTable.displayed_original] + exact response_eq_canonical originalSlots projectedSlots projection rows upper lower A repeats cut + a labeling sample + +theorem response_eq_rightUpper_totalMatrix (a : Block rows lower) + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (sample : Raw projectedSlots rows upper lower A repeats cut) : + OwnInputReference.response projectedSlots rows upper lower (LinearMap.ker A) a labeling + (OwnInputReference.readInput projectedSlots rows upper lower (LinearMap.ker A) a + (OwnInputRawAssembly.scalarEval projectedSlots upper lower repeats cut) sample.2) + (hidden projectedSlots rows upper lower A repeats cut sample) = + HierarchicalPrediction.rightUpper originalSlots upper + (visibleBackground originalSlots projectedSlots projection rows upper lower A repeats cut sample.2) + labeling lower cut.upper_ne_lower a + (HierarchicalProjectedSlice.matrix originalSlots projectedSlots projection upper A + (known projectedSlots rows upper lower A repeats cut sample.2) + (hidden projectedSlots rows upper lower A repeats cut sample)) := by + exact (response_eq_rightUpper originalSlots projectedSlots projection rows upper lower A repeats cut + a labeling sample).trans (congrArg + (fun X : HierarchicalMatrixTable.Matrix (rows := rows) originalSlots upper => + HierarchicalPrediction.rightUpper originalSlots upper + (visibleBackground originalSlots projectedSlots projection rows upper lower A repeats cut sample.2) + labeling lower cut.upper_ne_lower a X) + (ProjectedRawAssembly.matrix_arrays originalSlots projectedSlots projection rows upper lower + (LinearMap.ker A) repeats cut sample)) + +def rawJ (sample : Raw projectedSlots rows upper lower A repeats cut) : Bool := + GoodAdviceEvents.J + (HierarchicalUsefulness.table originalSlots upper lowerLevel original originalArrays lowerEvent κ σ + (rawBackground originalSlots projectedSlots projection rows upper lower A repeats cut sample)) r ρ + (A, HierarchicalPrediction.quotientMatrix originalSlots upper lowerLevel + (rawBackground originalSlots projectedSlots projection rows upper lower A repeats cut sample) + (rawMatrix originalSlots projectedSlots projection rows upper lower A repeats cut sample)) + +def rawPrediction (a : Block rows lower) + (sample : Raw projectedSlots rows upper lower A repeats cut) : Bool := + HierarchicalPrediction.prediction originalSlots upper lowerLevel + (rawBackground originalSlots projectedSlots projection rows upper lower A repeats cut sample) σ lower cut.upper_ne_lower a + original originalArrays lowerEvent κ r ρ A (rawMatrix originalSlots projectedSlots projection rows upper lower A repeats cut sample) + +abbrev VisibleGood (v : Visible projectedSlots rows upper lower A repeats cut) : Prop := + HierarchicalProjectedSlice.VisibleGood originalSlots projectedSlots projection upper lowerLevel + (visibleBackground originalSlots projectedSlots projection rows upper lower A repeats cut v) + original originalArrays lowerEvent κ σ ρ A (known projectedSlots rows upper lower A repeats cut v) + +abbrev tensorJ (v : Visible projectedSlots rows upper lower A repeats cut) + (T : HierarchicalProjectedSlice.HiddenTensor projectedSlots upper A) : Bool := + HierarchicalProjectedSlice.J originalSlots projectedSlots projection upper lowerLevel + (visibleBackground originalSlots projectedSlots projection rows upper lower A repeats cut v) + original originalArrays lowerEvent κ σ ρ A (known projectedSlots rows upper lower A repeats cut v) T + +abbrev columnSpace (v : Visible projectedSlots rows upper lower A repeats cut) + (hgood : VisibleGood originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v) := + HierarchicalProjectedSlice.columnSpace originalSlots projectedSlots projection upper lowerLevel + (visibleBackground originalSlots projectedSlots projection rows upper lower A repeats cut v) + original originalArrays lowerEvent κ σ ρ A (known projectedSlots rows upper lower A repeats cut v) hgood + +abbrev target (v : Visible projectedSlots rows upper lower A repeats cut) + (hgood : VisibleGood originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v) + (hne : ∃ T, tensorJ originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v T = true) := + HierarchicalProjectedSlice.target originalSlots projectedSlots projection upper lowerLevel + (visibleBackground originalSlots projectedSlots projection rows upper lower A repeats cut v) + original originalArrays lowerEvent κ σ ρ A (known projectedSlots rows upper lower A repeats cut v) hgood hne + +abbrev nativeCorrection (v : Visible projectedSlots rows upper lower A repeats cut) + (hgood : VisibleGood originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v) := + HierarchicalProjectedSlice.nativeCorrection originalSlots projectedSlots projection upper lowerLevel + (visibleBackground originalSlots projectedSlots projection rows upper lower A repeats cut v) + original originalArrays lowerEvent κ σ ρ A (known projectedSlots rows upper lower A repeats cut v) hgood + +abbrev visibleOffset (v : Visible projectedSlots rows upper lower A repeats cut) + (hgood : VisibleGood originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v) := + HierarchicalProjectedSlice.visibleOffset originalSlots projectedSlots projection upper lowerLevel + (visibleBackground originalSlots projectedSlots projection rows upper lower A repeats cut v) + original originalArrays lowerEvent κ σ ρ A (known projectedSlots rows upper lower A repeats cut v) hgood + +theorem rawJ_eq_tensorJ (sample : Raw projectedSlots rows upper lower A repeats cut) : + rawJ originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ A repeats cut sample = + tensorJ originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ A repeats cut + sample.2 (hidden projectedSlots rows upper lower A repeats cut sample) := by + exact congrArg₂ + (fun (b : HierarchicalMatrixTable.Background (rows := rows) originalSlots upper) + (X : HierarchicalMatrixTable.Matrix (rows := rows) originalSlots upper) => + GoodAdviceEvents.J + (HierarchicalUsefulness.table originalSlots upper lowerLevel original originalArrays lowerEvent κ σ b) + r ρ (A, HierarchicalPrediction.quotientMatrix originalSlots upper lowerLevel b X)) + (ProjectedRawAssembly.background_arrays originalSlots projectedSlots projection rows upper lower (LinearMap.ker A) repeats cut sample) + (ProjectedRawAssembly.matrix_arrays originalSlots projectedSlots projection rows upper lower (LinearMap.ker A) repeats cut sample) + +theorem rawJ_iff_restriction (v : Visible projectedSlots rows upper lower A repeats cut) + (hgood : VisibleGood originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v) + (hne : ∃ T, tensorJ originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v T = true) + (sample : Raw projectedSlots rows upper lower A repeats cut) (hv : sample.2 = v) : + rawJ originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ A repeats cut sample = + true ↔ + TensorRestriction.restrictionMap + (columnSpace originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v hgood) (hidden projectedSlots rows upper lower A repeats cut sample) = + target originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v hgood hne := by + rw [rawJ_eq_tensorJ, hv] + exact HierarchicalProjectedSlice.J_iff_restriction originalSlots projectedSlots projection upper lowerLevel + (visibleBackground originalSlots projectedSlots projection rows upper lower A repeats cut v) + original originalArrays lowerEvent κ σ ρ A (known projectedSlots rows upper lower A repeats cut v) + hgood hne _ + +def responseMatch (a : Block rows lower) (v : Visible projectedSlots rows upper lower A repeats cut) + (hgood : VisibleGood originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v) (sample : Raw projectedSlots rows upper lower A repeats cut) : Bool := + decide (OwnInputReference.response projectedSlots rows upper lower (LinearMap.ker A) a σ + (OwnInputReference.readInput projectedSlots rows upper lower (LinearMap.ker A) a + (OwnInputRawAssembly.scalarEval projectedSlots upper lower repeats cut) sample.2) + (hidden projectedSlots rows upper lower A repeats cut sample) = + visibleOffset originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v hgood + + TensorBucketEvaluation.tensorOutputLinear (LinearMap.ker A) + (nativeCorrection originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v hgood) (hidden projectedSlots rows upper lower A repeats cut sample)) + +theorem rawPrediction_eq (a : Block rows lower) (v : Visible projectedSlots rows upper lower A repeats cut) + (hgood : VisibleGood originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v) (sample : Raw projectedSlots rows upper lower A repeats cut) (hv : sample.2 = v) : + rawPrediction originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut a sample = + (rawJ originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut sample && + responseMatch originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut a v hgood sample) := by + have hbg := ProjectedRawAssembly.background_arrays originalSlots projectedSlots projection rows upper lower (LinearMap.ker A) + repeats cut sample + have hmat := ProjectedRawAssembly.matrix_arrays originalSlots projectedSlots projection rows upper lower (LinearMap.ker A) + repeats cut sample + have hresponse := response_eq_rightUpper_totalMatrix originalSlots projectedSlots projection rows upper lower A repeats cut a σ sample + rw [hv] at hbg hmat hresponse + change rawBackground originalSlots projectedSlots projection rows upper lower A repeats cut sample = + visibleBackground originalSlots projectedSlots projection rows upper lower A repeats cut v at hbg + change rawMatrix originalSlots projectedSlots projection rows upper lower A repeats cut sample = + HierarchicalProjectedSlice.matrix originalSlots projectedSlots projection upper A + (known projectedSlots rows upper lower A repeats cut v) + (hidden projectedSlots rows upper lower A repeats cut sample) at hmat + have hprediction := congrArg₂ + (fun (b : HierarchicalMatrixTable.Background (rows := rows) originalSlots upper) + (X : HierarchicalMatrixTable.Matrix (rows := rows) originalSlots upper) => + HierarchicalPrediction.prediction originalSlots upper lowerLevel b σ lower cut.upper_ne_lower a + original originalArrays lowerEvent κ r ρ A X) hbg hmat + unfold rawPrediction + rw [hprediction, rawJ_eq_tensorJ] + simp only [hv] + dsimp only [HierarchicalPrediction.prediction] + rw [HierarchicalProjectedSlice.selectedValue_eq_some originalSlots projectedSlots projection upper lowerLevel + (visibleBackground originalSlots projectedSlots projection rows upper lower A repeats cut v) + original originalArrays lowerEvent κ σ ρ A (known projectedSlots rows upper lower A repeats cut v) + hgood (hidden projectedSlots rows upper lower A repeats cut sample)] + dsimp only + rw [HierarchicalProjectedSlice.affinePrediction_eq_tensor originalSlots projectedSlots projection upper lowerLevel + (visibleBackground originalSlots projectedSlots projection rows upper lower A repeats cut v) + original originalArrays lowerEvent κ σ ρ A (known projectedSlots rows upper lower A repeats cut v) + hgood (hidden projectedSlots rows upper lower A repeats cut sample), ← hresponse] + simp only [tensorJ, HierarchicalProjectedSlice.J, responseMatch, hv, + TensorBucketEvaluation.tensorOutput] + all_goals + apply congrArg₂ (fun first second : Bool => first && second) + · rfl + · exact (@decide_eq_decide _ _ _ _).mpr Iff.rfl + +def given (v : Visible projectedSlots rows upper lower A repeats cut) + (sample : Raw projectedSlots rows upper lower A repeats cut) : Bool := + rawJ originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut sample && decide (sample.2 = v) + +theorem given_eq_jointEvent (v : Visible projectedSlots rows upper lower A repeats cut) + (hgood : VisibleGood originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v) + (hne : ∃ T, tensorJ originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v T = true) : + given originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ A repeats cut v = + OwnInputAffineSlice.jointEvent projectedSlots rows upper lower (LinearMap.ker A) repeats cut + (fun data => decide (data = v)) + (columnSpace originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v hgood) + (target originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v hgood hne) := by + funext sample + by_cases hv : sample.2 = v + · have hJ : rawJ originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut sample = + OwnInputAffineSlice.tensorSlice (LinearMap.ker A) + (columnSpace originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v hgood) + (target originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v hgood hne) (hidden projectedSlots rows upper lower A repeats cut sample) := by + apply Bool.eq_iff_iff.mpr + simp only [OwnInputAffineSlice.tensorSlice, decide_eq_true_eq] + exact rawJ_iff_restriction originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v hgood hne sample hv + unfold given OwnInputAffineSlice.jointEvent + rw [hJ] + · simp only [given, OwnInputAffineSlice.jointEvent, hv, decide_false, Bool.and_false] + +theorem selection_of_positive + (externalLaw : FiniteDistribution (OwnInputReference.Exterior projectedSlots rows upper lower)) + (v : Visible projectedSlots rows upper lower A repeats cut) + (positive : 0 < + (OwnInputReference.rawLaw projectedSlots rows upper lower (LinearMap.ker A) repeats cut externalLaw).probability + (given originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ A repeats cut v)) : + VisibleGood originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ A repeats cut v ∧ + ∃ T, tensorJ originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v T = true := by + have hex : ∃ sample, given originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v sample = true := by + by_contra hnone + have hfalse : given originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v = fun _ => false := by + funext sample + exact Bool.eq_false_iff.mpr (fun hs => hnone ⟨sample, hs⟩) + rw [hfalse, FiniteDistribution.probability_false] at positive + exact (lt_irrefl 0) positive + obtain ⟨sample, hs⟩ := hex + have hp := Bool.and_eq_true_iff.mp hs + have hv : sample.2 = v := @of_decide_eq_true _ _ hp.2 + have ht := hp.1 + rw [rawJ_eq_tensorJ, hv] at ht + refine ⟨?_, hidden projectedSlots rows upper lower A repeats cut sample, ht⟩ + by_contra hbad + have hfalse := HierarchicalProjectedSlice.J_false_of_not_good originalSlots projectedSlots projection upper lowerLevel + (visibleBackground originalSlots projectedSlots projection rows upper lower A repeats cut v) + original originalArrays lowerEvent κ σ ρ A (known projectedSlots rows upper lower A repeats cut v) + hbad (hidden projectedSlots rows upper lower A repeats cut sample) + exact Bool.noConfusion (hfalse.symm.trans ht) + +theorem conditional_prediction_eq (a : Block rows lower) + (externalLaw : FiniteDistribution (OwnInputReference.Exterior projectedSlots rows upper lower)) + (v : Visible projectedSlots rows upper lower A repeats cut) + (hgood : VisibleGood originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v) + (hne : ∃ T, tensorJ originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v T = true) + (positive : 0 < + (OwnInputReference.rawLaw projectedSlots rows upper lower (LinearMap.ker A) repeats cut externalLaw).probability + (given originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ A repeats cut v)) : + ((OwnInputReference.rawLaw projectedSlots rows upper lower (LinearMap.ker A) repeats cut externalLaw).condition + (given originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ A repeats cut v) + positive).probability + (rawPrediction originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut a) = + RightDecoderWitness.conditionalMatch projectedSlots rows upper lower (LinearMap.ker A) a repeats cut σ + (OwnInputReference.readInput projectedSlots rows upper lower (LinearMap.ker A) a + (OwnInputRawAssembly.scalarEval projectedSlots upper lower repeats cut) v) + (columnSpace originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v hgood) + (target originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v hgood hne) + (nativeCorrection originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v hgood) + (visibleOffset originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v hgood) := by + let μ := OwnInputReference.rawLaw projectedSlots rows upper lower (LinearMap.ker A) repeats cut externalLaw + let joint := OwnInputAffineSlice.jointEvent projectedSlots rows upper lower (LinearMap.ker A) repeats cut + (fun data => decide (data = v)) + (columnSpace originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ A repeats cut v hgood) + (target originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ A repeats cut v hgood hne) + have hgiven : given originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v = joint := + given_eq_jointEvent originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v hgood hne + have hpositive : 0 < μ.probability joint := by + rw [← hgiven] + exact positive + trans (μ.condition + (given originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ A repeats cut v) + positive).probability + (responseMatch originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut a v hgood) + · apply OwnInputAffineSlice.probability_condition_congr + intro sample hs + have hp := Bool.and_eq_true_iff.mp hs + have hv : sample.2 = v := @of_decide_eq_true _ _ hp.2 + rw [rawPrediction_eq originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut a v hgood sample hv, hp.1, Bool.true_and] + trans (μ.condition joint hpositive).probability + (responseMatch originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut a v hgood) + · simp only [FiniteDistribution.probability_condition, hgiven] + · exact OwnInputAffineSlice.conditional_response_probability projectedSlots rows upper lower (LinearMap.ker A) + a repeats cut externalLaw (fun data => decide (data = v)) + (columnSpace originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v hgood) + (target originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v hgood hne) hpositive σ + (OwnInputReference.readInput projectedSlots rows upper lower (LinearMap.ker A) a + (OwnInputRawAssembly.scalarEval projectedSlots upper lower repeats cut) v) + (by + intro data hdata + have hv : data = v := @of_decide_eq_true _ _ hdata + subst data + rfl) + (nativeCorrection originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v hgood) + (visibleOffset originalSlots projectedSlots projection rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v hgood) + +end +end PerfectCompleteness.HierarchicalProjectedRawPrediction + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalRawAverage.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalRawAverage.lean new file mode 100644 index 0000000000000000000000000000000000000000..b26b8c0e33ddab3036b13e1ddd6bd72a0ee6fc7f --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalRawAverage.lean @@ -0,0 +1,237 @@ +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalRawPredictionLemmas +import OAI.Computability.PerfectCompleteness.Foundations.TupleIndexEmitterLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.HierarchicalRawAverage + +noncomputable section + +open scoped BigOperators Classical TensorProduct +open TreeSourceSpaces HierarchicalArrays UpperParameterScalars +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype + +private theorem event_mass_le_expectation {X : Type*} [Fintype X] + (μ : FiniteDistribution X) (event : X → Bool) (value : X → ℝ) (factor : ℝ) + (hnonneg : ∀ x, 0 ≤ value x) + (hbound : ∀ x, event x = true → factor ≤ value x) : + factor * μ.probability event ≤ μ.expectation value := by + unfold FiniteDistribution.probability FiniteDistribution.expectation + rw [Finset.mul_sum] + apply Finset.sum_le_sum + intro x _ + by_cases hx : event x = true + · rw [ite_eq_left hx] + calc + factor * μ.weight x = μ.weight x * factor := mul_comm _ _ + _ ≤ μ.weight x * value x := + mul_le_mul_of_nonneg_left (hbound x hx) (μ.nonnegative x) + · rw [ite_eq_right hx, mul_zero] + exact mul_nonneg (μ.nonnegative x) (hnonneg x) + +variable {δ : ℚ} (plan : FixedRows.Plan δ) {branch : Nat → Nat} {t : Nat} + (slots : RecursiveSpaces.Slots branch plan.depth → Fin t → MixedSupport.Slot) + (upper lower : Nodes branch plan.depth) (lowerLevel : Nat) + {Ω : Type*} [Fintype Ω] + (original : FiniteDistribution Ω) (originalArrays : Ω → Arrays slots (FixedRows.rows plan)) + (lowerEvent : Ω → Bool) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch plan.depth t)) + (A : ManyGoodRows.RowMap (Block (FixedRows.rows plan) upper) plan.order) + (a : Block (FixedRows.rows plan) lower) (cut : OwnInputReference.Cut upper lower) + +abbrev Raw := HierarchicalRawPrediction.Raw slots (FixedRows.rows plan) upper lower A + (FixedRows.repeats plan) cut + +abbrev Visible := HierarchicalRawPrediction.Visible slots (FixedRows.rows plan) upper lower A + (FixedRows.repeats plan) cut + +def law (externalLaw : FiniteDistribution + (OwnInputReference.Exterior slots (FixedRows.rows plan) upper lower)) : + FiniteDistribution (Raw plan slots upper lower A cut) := + OwnInputReference.rawLaw slots (FixedRows.rows plan) upper lower (LinearMap.ker A) + (FixedRows.repeats plan) cut externalLaw + +abbrev J := HierarchicalRawPrediction.rawJ slots (FixedRows.rows plan) upper lower lowerLevel + original originalArrays lowerEvent (InitialParameters.useful δ) σ plan.density A + (FixedRows.repeats plan) cut + +abbrev prediction := HierarchicalRawPrediction.rawPrediction slots (FixedRows.rows plan) upper lower lowerLevel + original originalArrays lowerEvent (InitialParameters.useful δ) σ plan.density A + (FixedRows.repeats plan) cut a + +def goodRecord (externalLaw : FiniteDistribution + (OwnInputReference.Exterior slots (FixedRows.rows plan) upper lower)) + (v : Visible plan slots upper lower A cut) : Bool := + PositiveFiberMass.goodRecord (law plan slots upper lower A cut externalLaw) + (fun sample : Raw plan slots upper lower A cut => sample.2) + (J plan slots upper lower lowerLevel original originalArrays lowerEvent σ A cut) + (prediction plan slots upper lower lowerLevel original originalArrays lowerEvent σ A a cut) + (rhoPred (InitialParameters.useful δ) plan.density) v + +def goodEvent (externalLaw : FiniteDistribution + (OwnInputReference.Exterior slots (FixedRows.rows plan) upper lower)) + (sample : Raw plan slots upper lower A cut) : Bool := + J plan slots upper lower lowerLevel original originalArrays lowerEvent σ A cut sample && + goodRecord plan slots upper lower lowerLevel original originalArrays lowerEvent σ A a cut + externalLaw sample.2 + +def factor : ℝ := + (1 / (2 : ℝ) ^ plan.order) * + (tau (InitialParameters.useful δ) plan.density plan.order + (FixedRows.rows plan (Nodes.height upper)) ^ 2 / + (2 * (2 : ℝ) ^ FixedRows.rows plan (Nodes.height upper))) + +theorem factor_nonneg : 0 ≤ factor plan upper := by + unfold factor + positivity + +abbrev meetingProbability := + HierarchicalRawMeeting.meetingProbability plan slots upper lower lowerLevel + original originalArrays lowerEvent σ A a cut + +def expectedMeeting (externalLaw : FiniteDistribution + (OwnInputReference.Exterior slots (FixedRows.rows plan) upper lower)) : ℝ := + (law plan slots upper lower A cut externalLaw).expectation + (fun sample => meetingProbability plan slots upper lower lowerLevel + original originalArrays lowerEvent σ A a cut sample.2) + +theorem meeting_lower_of_goodRecord (hδ : 0 < δ) + (externalLaw : FiniteDistribution + (OwnInputReference.Exterior slots (FixedRows.rows plan) upper lower)) + (v : Visible plan slots upper lower A cut) + (hgood : goodRecord plan slots upper lower lowerLevel original originalArrays lowerEvent σ + A a cut externalLaw v = true) : + factor plan upper ≤ + meetingProbability plan slots upper lower lowerLevel original originalArrays lowerEvent σ A a cut v := by + have hpositive := (PositiveFiberMass.goodRecord_iff + (law plan slots upper lower A cut externalLaw) + (fun sample : Raw plan slots upper lower A cut => sample.2) + (J plan slots upper lower lowerLevel original originalArrays lowerEvent σ A cut) + (prediction plan slots upper lower lowerLevel original originalArrays lowerEvent σ A a cut) + (rhoPred (InitialParameters.useful δ) plan.density) v).mp hgood + let originalGiven : Raw plan slots upper lower A cut → Bool := fun sample => + J plan slots upper lower lowerLevel original originalArrays lowerEvent σ A cut sample && + @decide (sample.2 = v) (Classical.propDecidable _) + have hgiven : originalGiven = + HierarchicalRawPrediction.given slots (FixedRows.rows plan) upper lower lowerLevel + original originalArrays lowerEvent (InitialParameters.useful δ) σ plan.density A + (FixedRows.repeats plan) cut v := by + funext sample + unfold originalGiven HierarchicalRawPrediction.given + apply congrArg (fun flag : Bool => + J plan slots upper lower lowerLevel original originalArrays lowerEvent σ A cut sample && flag) + exact (@decide_eq_decide _ _ _ _).mpr Iff.rfl + have positive : 0 < (law plan slots upper lower A cut externalLaw).probability + (HierarchicalRawPrediction.given slots (FixedRows.rows plan) upper lower lowerLevel + original originalArrays lowerEvent (InitialParameters.useful δ) σ plan.density A + (FixedRows.repeats plan) cut v) := by + rw [← hgiven] + exact hpositive.1 + have conditional : rhoPred (InitialParameters.useful δ) plan.density ≤ + ((law plan slots upper lower A cut externalLaw).condition + (HierarchicalRawPrediction.given slots (FixedRows.rows plan) upper lower lowerLevel + original originalArrays lowerEvent (InitialParameters.useful δ) σ plan.density A + (FixedRows.repeats plan) cut v) positive).probability + (prediction plan slots upper lower lowerLevel original originalArrays lowerEvent σ A a cut) := by + have hprediction := hpositive.2 + have hmatch : (fun sample : Raw plan slots upper lower A cut => + originalGiven sample && + prediction plan slots upper lower lowerLevel original originalArrays lowerEvent σ A a cut sample) = + (fun sample => + (J plan slots upper lower lowerLevel original originalArrays lowerEvent σ A cut sample && + prediction plan slots upper lower lowerLevel original originalArrays lowerEvent σ A a cut sample) && + @decide (sample.2 = v) (Classical.propDecidable _)) := by + funext sample + dsimp only [originalGiven] + cases J plan slots upper lower lowerLevel original originalArrays lowerEvent σ A cut sample <;> + cases prediction plan slots upper lower lowerLevel original originalArrays lowerEvent σ A a cut sample <;> + cases @decide (sample.2 = v) (Classical.propDecidable _) <;> rfl + change rhoPred (InitialParameters.useful δ) plan.density ≤ + (law plan slots upper lower A cut externalLaw).probability + (fun sample => + (J plan slots upper lower lowerLevel original originalArrays lowerEvent σ A cut sample && + prediction plan slots upper lower lowerLevel original originalArrays lowerEvent σ A a cut sample) && + @decide (sample.2 = v) (Classical.propDecidable _)) / + (law plan slots upper lower A cut externalLaw).probability originalGiven at hprediction + rw [← hmatch, hgiven] at hprediction + exact hprediction.trans_eq + (FiniteDistribution.probability_condition (law plan slots upper lower A cut externalLaw) + (HierarchicalRawPrediction.given slots (FixedRows.rows plan) upper lower lowerLevel + original originalArrays lowerEvent (InitialParameters.useful δ) σ plan.density A + (FixedRows.repeats plan) cut v) + (prediction plan slots upper lower lowerLevel original originalArrays lowerEvent σ A a cut) + positive).symm + exact HierarchicalRawMeeting.meeting_probability_lower plan slots upper lower lowerLevel + original originalArrays lowerEvent σ A a cut v hδ externalLaw positive conditional + +theorem expectedMeeting_ge_good_mass (hδ : 0 < δ) + (externalLaw : FiniteDistribution + (OwnInputReference.Exterior slots (FixedRows.rows plan) upper lower)) : + factor plan upper * + (law plan slots upper lower A cut externalLaw).probability + (goodEvent plan slots upper lower lowerLevel original originalArrays lowerEvent σ A a cut externalLaw) ≤ + expectedMeeting plan slots upper lower lowerLevel original originalArrays lowerEvent σ A a cut externalLaw := by + apply event_mass_le_expectation + · intro sample + exact HierarchicalRawMeeting.meetingProbability_nonneg plan slots upper lower lowerLevel + original originalArrays lowerEvent σ A a cut sample.2 + · intro sample hs + exact meeting_lower_of_goodRecord plan slots upper lower lowerLevel original originalArrays lowerEvent σ + A a cut hδ externalLaw sample.2 (Bool.and_eq_true_iff.mp hs).2 + +theorem J_and_prediction : + (fun sample => J plan slots upper lower lowerLevel original originalArrays lowerEvent σ A cut sample && + prediction plan slots upper lower lowerLevel original originalArrays lowerEvent σ A a cut sample) = + prediction plan slots upper lower lowerLevel original originalArrays lowerEvent σ A a cut := by + funext sample + unfold J prediction HierarchicalRawPrediction.rawJ HierarchicalRawPrediction.rawPrediction + HierarchicalPrediction.prediction + exact Bool.and_self_left _ _ + +theorem prediction_difference_le_good_mass (hδ : 0 < δ) + (externalLaw : FiniteDistribution + (OwnInputReference.Exterior slots (FixedRows.rows plan) upper lower)) : + (law plan slots upper lower A cut externalLaw).probability + (prediction plan slots upper lower lowerLevel original originalArrays lowerEvent σ A a cut) - + rhoPred (InitialParameters.useful δ) plan.density * + (law plan slots upper lower A cut externalLaw).probability + (J plan slots upper lower lowerLevel original originalArrays lowerEvent σ A cut) ≤ + (law plan slots upper lower A cut externalLaw).probability + (goodEvent plan slots upper lower lowerLevel original originalArrays lowerEvent σ A a cut externalLaw) := by + have h := PositiveFiberMass.difference_le_good_mass + (law plan slots upper lower A cut externalLaw) + (fun sample : Raw plan slots upper lower A cut => sample.2) + (J plan slots upper lower lowerLevel original originalArrays lowerEvent σ A cut) + (prediction plan slots upper lower lowerLevel original originalArrays lowerEvent σ A a cut) + (rhoPred (InitialParameters.useful δ) plan.density) + (rhoPred_pos (InitialParameters.useful_pos hδ) plan.density_pos).le + rw [J_and_prediction] at h + exact h + +theorem expectedMeeting_ge_prediction_difference (hδ : 0 < δ) + (externalLaw : FiniteDistribution + (OwnInputReference.Exterior slots (FixedRows.rows plan) upper lower)) : + factor plan upper * + ((law plan slots upper lower A cut externalLaw).probability + (prediction plan slots upper lower lowerLevel original originalArrays lowerEvent σ A a cut) - + rhoPred (InitialParameters.useful δ) plan.density * + (law plan slots upper lower A cut externalLaw).probability + (J plan slots upper lower lowerLevel original originalArrays lowerEvent σ A cut)) ≤ + expectedMeeting plan slots upper lower lowerLevel original originalArrays lowerEvent σ A a cut externalLaw := + (mul_le_mul_of_nonneg_left + (prediction_difference_le_good_mass plan slots upper lower lowerLevel original originalArrays lowerEvent σ + A a cut hδ externalLaw) (factor_nonneg plan upper)).trans + (expectedMeeting_ge_good_mass plan slots upper lower lowerLevel original originalArrays lowerEvent σ + A a cut hδ externalLaw) + +end +end PerfectCompleteness.HierarchicalRawAverage + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalRawPredictionLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalRawPredictionLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..bcec0170f31d00a7d816eb20c4327aabb49fe3f5 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalRawPredictionLemmas.lean @@ -0,0 +1,442 @@ +import OAI.Computability.PerfectCompleteness.Algebra.TensorRowAdviceLemmas +import OAI.Computability.PerfectCompleteness.Decoding.HierarchicalDecoderMeetingLemmas +import OAI.Computability.PerfectCompleteness.Decoding.RightDecoderWitness +import OAI.Computability.PerfectCompleteness.Machines.OwnInputAffineSliceLemmas + +namespace OAI + + +namespace PerfectCompleteness.HierarchicalRawPrediction + +noncomputable section + +open scoped Classical TensorProduct +open TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype + +variable {branch : Nat → Nat} {n t : Nat} + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (rows : Nat → Nat) (upper lower : Nodes branch n) (lowerLevel : Nat) + +local instance rowSpaceFintype : Fintype (NodeEmbedding.RowSpace slots upper) := + Fintype.ofFinite _ + +local instance valueFintype : Fintype + (Block rows upper × HierarchicalMatrixTable.SideOutput (rows := rows) upper) := + Fintype.ofFinite _ + +variable {Ω : Type*} [Fintype Ω] + (original : FiniteDistribution Ω) (originalArrays : Ω → Arrays slots rows) + (lowerEvent : Ω → Bool) (κ : ℝ) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + {r : Nat} (ρ : ℝ) (A : ManyGoodRows.RowMap (Block rows upper) r) + (repeats : Nat → Nat) (cut : OwnInputReference.Cut upper lower) + +abbrev Raw := OwnInputReference.RawSample slots rows upper lower (LinearMap.ker A) repeats cut +abbrev Visible := OwnInputAffineSlice.VisibleSample slots rows upper lower (LinearMap.ker A) repeats cut + +abbrev rawArrays (sample : Raw slots rows upper lower A repeats cut) := + OwnInputRawAssembly.arrays slots rows upper lower (LinearMap.ker A) repeats cut sample + +abbrev rawBackground (sample : Raw slots rows upper lower A repeats cut) := + HierarchicalMatrixTable.backgroundOf slots upper + (rawArrays slots rows upper lower A repeats cut sample) + +abbrev rawMatrix (sample : Raw slots rows upper lower A repeats cut) := + NodeEmbedding.matrix (rawArrays slots rows upper lower A repeats cut sample) upper + +abbrev visibleBackground (v : Visible slots rows upper lower A repeats cut) := + OwnInputRawAssembly.background slots rows upper lower (LinearMap.ker A) repeats cut v + +abbrev known (v : Visible slots rows upper lower A repeats cut) := + OwnInputRawAssembly.knownVisible slots rows upper lower (LinearMap.ker A) repeats cut v + +abbrev hidden (sample : Raw slots rows upper lower A repeats cut) := + OwnInputAffineSlice.hiddenOutput slots rows upper lower (LinearMap.ker A) repeats cut sample + +def rawJ (sample : Raw slots rows upper lower A repeats cut) : Bool := + GoodAdviceEvents.J + (HierarchicalUsefulness.table slots upper lowerLevel original originalArrays lowerEvent κ σ + (rawBackground slots rows upper lower A repeats cut sample)) r ρ + (A, HierarchicalPrediction.quotientMatrix slots upper lowerLevel + (rawBackground slots rows upper lower A repeats cut sample) + (rawMatrix slots rows upper lower A repeats cut sample)) + +def rawPrediction (a : Block rows lower) + (sample : Raw slots rows upper lower A repeats cut) : Bool := + HierarchicalPrediction.prediction slots upper lowerLevel + (rawBackground slots rows upper lower A repeats cut sample) σ lower cut.upper_ne_lower a + original originalArrays lowerEvent κ r ρ A (rawMatrix slots rows upper lower A repeats cut sample) + +abbrev VisibleGood (v : Visible slots rows upper lower A repeats cut) : Prop := + HierarchicalTensorSlice.VisibleGood slots upper lowerLevel + (visibleBackground slots rows upper lower A repeats cut v) + original originalArrays lowerEvent κ σ ρ A (known slots rows upper lower A repeats cut v) + +abbrev tensorJ (v : Visible slots rows upper lower A repeats cut) + (T : HierarchicalTensorSlice.HiddenTensor slots upper A) : Bool := + HierarchicalTensorSlice.J slots upper lowerLevel + (visibleBackground slots rows upper lower A repeats cut v) + original originalArrays lowerEvent κ σ ρ A (known slots rows upper lower A repeats cut v) T + +abbrev columnSpace (v : Visible slots rows upper lower A repeats cut) + (hgood : VisibleGood slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v) := + HierarchicalTensorSlice.columnSpace slots upper lowerLevel + (visibleBackground slots rows upper lower A repeats cut v) + original originalArrays lowerEvent κ σ ρ A (known slots rows upper lower A repeats cut v) hgood + +abbrev target (v : Visible slots rows upper lower A repeats cut) + (hgood : VisibleGood slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v) + (hne : ∃ T, tensorJ slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v T = true) := + HierarchicalTensorSlice.target slots upper lowerLevel + (visibleBackground slots rows upper lower A repeats cut v) + original originalArrays lowerEvent κ σ ρ A (known slots rows upper lower A repeats cut v) hgood hne + +abbrev nativeCorrection (v : Visible slots rows upper lower A repeats cut) + (hgood : VisibleGood slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v) := + HierarchicalTensorSlice.nativeCorrection slots upper lowerLevel + (visibleBackground slots rows upper lower A repeats cut v) + original originalArrays lowerEvent κ σ ρ A (known slots rows upper lower A repeats cut v) hgood + +abbrev visibleOffset (v : Visible slots rows upper lower A repeats cut) + (hgood : VisibleGood slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v) := + HierarchicalTensorSlice.visibleOffset slots upper lowerLevel + (visibleBackground slots rows upper lower A repeats cut v) + original originalArrays lowerEvent κ σ ρ A (known slots rows upper lower A repeats cut v) hgood + +theorem rawJ_eq_tensorJ (sample : Raw slots rows upper lower A repeats cut) : + rawJ slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ A repeats cut sample = + tensorJ slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ A repeats cut + sample.2 (hidden slots rows upper lower A repeats cut sample) := by + exact congrArg₂ + (fun (b : HierarchicalMatrixTable.Background (rows := rows) slots upper) + (X : HierarchicalMatrixTable.Matrix (rows := rows) slots upper) => + GoodAdviceEvents.J + (HierarchicalUsefulness.table slots upper lowerLevel original originalArrays lowerEvent κ σ b) + r ρ (A, HierarchicalPrediction.quotientMatrix slots upper lowerLevel b X)) + (OwnInputRawAssembly.background_arrays slots rows upper lower (LinearMap.ker A) repeats cut sample) + (OwnInputRawAssembly.matrix_arrays slots rows upper lower (LinearMap.ker A) repeats cut sample) + +theorem rawJ_iff_restriction (v : Visible slots rows upper lower A repeats cut) + (hgood : VisibleGood slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v) + (hne : ∃ T, tensorJ slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v T = true) + (sample : Raw slots rows upper lower A repeats cut) (hv : sample.2 = v) : + rawJ slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ A repeats cut sample = + true ↔ + TensorRestriction.restrictionMap + (columnSpace slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v hgood) (hidden slots rows upper lower A repeats cut sample) = + target slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v hgood hne := by + rw [rawJ_eq_tensorJ, hv] + exact HierarchicalTensorSlice.J_iff_restriction slots upper lowerLevel + (visibleBackground slots rows upper lower A repeats cut v) + original originalArrays lowerEvent κ σ ρ A (known slots rows upper lower A repeats cut v) + hgood hne _ + +def responseMatch (a : Block rows lower) (v : Visible slots rows upper lower A repeats cut) + (hgood : VisibleGood slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v) (sample : Raw slots rows upper lower A repeats cut) : Bool := + decide (OwnInputReference.response slots rows upper lower (LinearMap.ker A) a σ + (OwnInputReference.readInput slots rows upper lower (LinearMap.ker A) a + (OwnInputRawAssembly.scalarEval slots upper lower repeats cut) sample.2) + (hidden slots rows upper lower A repeats cut sample) = + visibleOffset slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v hgood + + TensorBucketEvaluation.tensorOutputLinear (LinearMap.ker A) + (nativeCorrection slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v hgood) (hidden slots rows upper lower A repeats cut sample)) + +theorem rawPrediction_eq (a : Block rows lower) (v : Visible slots rows upper lower A repeats cut) + (hgood : VisibleGood slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v) (sample : Raw slots rows upper lower A repeats cut) (hv : sample.2 = v) : + rawPrediction slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut a sample = + (rawJ slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut sample && + responseMatch slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut a v hgood sample) := by + have hbg := OwnInputRawAssembly.background_arrays slots rows upper lower (LinearMap.ker A) + repeats cut sample + have hmat := OwnInputRawAssembly.matrix_arrays slots rows upper lower (LinearMap.ker A) + repeats cut sample + have hresponse := OwnInputRawAssembly.response_eq_rightUpper_totalMatrix slots rows upper lower + (LinearMap.ker A) repeats cut a σ sample + rw [hv] at hbg hmat hresponse + have hprediction := congrArg₂ + (fun (b : HierarchicalMatrixTable.Background (rows := rows) slots upper) + (X : HierarchicalMatrixTable.Matrix (rows := rows) slots upper) => + HierarchicalPrediction.prediction slots upper lowerLevel b σ lower cut.upper_ne_lower a + original originalArrays lowerEvent κ r ρ A X) hbg hmat + unfold rawPrediction + rw [hprediction, rawJ_eq_tensorJ] + simp only [hv] + dsimp only [HierarchicalPrediction.prediction] + rw [HierarchicalTensorSlice.selectedValue_eq_some slots upper lowerLevel + (visibleBackground slots rows upper lower A repeats cut v) + original originalArrays lowerEvent κ σ ρ A (known slots rows upper lower A repeats cut v) + hgood (hidden slots rows upper lower A repeats cut sample)] + dsimp only + rw [HierarchicalTensorSlice.affinePrediction_eq_tensor slots upper lowerLevel + (visibleBackground slots rows upper lower A repeats cut v) + original originalArrays lowerEvent κ σ ρ A (known slots rows upper lower A repeats cut v) + hgood (hidden slots rows upper lower A repeats cut sample), ← hresponse] + simp only [tensorJ, HierarchicalTensorSlice.J, responseMatch, hv, + TensorBucketEvaluation.tensorOutput] + apply congrArg₂ (fun first second : Bool => first && second) + · rfl + · exact (@decide_eq_decide _ _ _ _).mpr Iff.rfl + +def given (v : Visible slots rows upper lower A repeats cut) + (sample : Raw slots rows upper lower A repeats cut) : Bool := + rawJ slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut sample && decide (sample.2 = v) + +theorem given_eq_jointEvent (v : Visible slots rows upper lower A repeats cut) + (hgood : VisibleGood slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v) + (hne : ∃ T, tensorJ slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v T = true) : + given slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ A repeats cut v = + OwnInputAffineSlice.jointEvent slots rows upper lower (LinearMap.ker A) repeats cut + (fun data => decide (data = v)) + (columnSpace slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v hgood) + (target slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v hgood hne) := by + funext sample + by_cases hv : sample.2 = v + · have hJ : rawJ slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut sample = + OwnInputAffineSlice.tensorSlice (LinearMap.ker A) + (columnSpace slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v hgood) + (target slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v hgood hne) (hidden slots rows upper lower A repeats cut sample) := by + apply Bool.eq_iff_iff.mpr + simp only [OwnInputAffineSlice.tensorSlice, decide_eq_true_eq] + exact rawJ_iff_restriction slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v hgood hne sample hv + unfold given OwnInputAffineSlice.jointEvent + rw [hJ] + · simp only [given, OwnInputAffineSlice.jointEvent, hv, decide_false, Bool.and_false] + +theorem selection_of_positive + (externalLaw : FiniteDistribution (OwnInputReference.Exterior slots rows upper lower)) + (v : Visible slots rows upper lower A repeats cut) + (positive : 0 < + (OwnInputReference.rawLaw slots rows upper lower (LinearMap.ker A) repeats cut externalLaw).probability + (given slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ A repeats cut v)) : + VisibleGood slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ A repeats cut v ∧ + ∃ T, tensorJ slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v T = true := by + have hex : ∃ sample, given slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v sample = true := by + by_contra hnone + have hfalse : given slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v = fun _ => false := by + funext sample + exact Bool.eq_false_iff.mpr (fun hs => hnone ⟨sample, hs⟩) + rw [hfalse, FiniteDistribution.probability_false] at positive + exact (lt_irrefl 0) positive + obtain ⟨sample, hs⟩ := hex + have hp := Bool.and_eq_true_iff.mp hs + have hv : sample.2 = v := @of_decide_eq_true _ _ hp.2 + have ht := hp.1 + rw [rawJ_eq_tensorJ, hv] at ht + refine ⟨?_, hidden slots rows upper lower A repeats cut sample, ht⟩ + by_contra hbad + have hfalse := HierarchicalTensorSlice.J_false_of_not_good slots upper lowerLevel + (visibleBackground slots rows upper lower A repeats cut v) + original originalArrays lowerEvent κ σ ρ A (known slots rows upper lower A repeats cut v) + hbad (hidden slots rows upper lower A repeats cut sample) + exact Bool.noConfusion (hfalse.symm.trans ht) + +theorem conditional_prediction_eq (a : Block rows lower) + (externalLaw : FiniteDistribution (OwnInputReference.Exterior slots rows upper lower)) + (v : Visible slots rows upper lower A repeats cut) + (hgood : VisibleGood slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v) + (hne : ∃ T, tensorJ slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v T = true) + (positive : 0 < + (OwnInputReference.rawLaw slots rows upper lower (LinearMap.ker A) repeats cut externalLaw).probability + (given slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ A repeats cut v)) : + ((OwnInputReference.rawLaw slots rows upper lower (LinearMap.ker A) repeats cut externalLaw).condition + (given slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ A repeats cut v) + positive).probability + (rawPrediction slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut a) = + RightDecoderWitness.conditionalMatch slots rows upper lower (LinearMap.ker A) a repeats cut σ + (OwnInputReference.readInput slots rows upper lower (LinearMap.ker A) a + (OwnInputRawAssembly.scalarEval slots upper lower repeats cut) v) + (columnSpace slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v hgood) + (target slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v hgood hne) + (nativeCorrection slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v hgood) + (visibleOffset slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v hgood) := by + let μ := OwnInputReference.rawLaw slots rows upper lower (LinearMap.ker A) repeats cut externalLaw + let joint := OwnInputAffineSlice.jointEvent slots rows upper lower (LinearMap.ker A) repeats cut + (fun data => decide (data = v)) + (columnSpace slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ A repeats cut v hgood) + (target slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ A repeats cut v hgood hne) + have hgiven : given slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v = joint := + given_eq_jointEvent slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v hgood hne + have hpositive : 0 < μ.probability joint := by + rw [← hgiven] + exact positive + trans (μ.condition + (given slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ A repeats cut v) + positive).probability + (responseMatch slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut a v hgood) + · apply OwnInputAffineSlice.probability_condition_congr + intro sample hs + have hp := Bool.and_eq_true_iff.mp hs + have hv : sample.2 = v := @of_decide_eq_true _ _ hp.2 + rw [rawPrediction_eq slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut a v hgood sample hv, hp.1, Bool.true_and] + trans (μ.condition joint hpositive).probability + (responseMatch slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut a v hgood) + · simp only [FiniteDistribution.probability_condition, hgiven] + · exact OwnInputAffineSlice.conditional_response_probability slots rows upper lower (LinearMap.ker A) + a repeats cut externalLaw (fun data => decide (data = v)) + (columnSpace slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v hgood) + (target slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v hgood hne) hpositive σ + (OwnInputReference.readInput slots rows upper lower (LinearMap.ker A) a + (OwnInputRawAssembly.scalarEval slots upper lower repeats cut) v) + (by + intro data hdata + have hv : data = v := @of_decide_eq_true _ _ hdata + subst data + rfl) + (nativeCorrection slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v hgood) + (visibleOffset slots rows upper lower lowerLevel original originalArrays lowerEvent κ σ ρ + A repeats cut v hgood) + +end +end PerfectCompleteness.HierarchicalRawPrediction + + +namespace PerfectCompleteness.HierarchicalRawMeeting + +noncomputable section + +open scoped Classical TensorProduct +open TreeSourceSpaces HierarchicalArrays +open UpperParameterScalars +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype +attribute [local instance] RightDecoder.characterFintype RightDecoder.scalarFintype + +variable {δ : ℚ} (plan : FixedRows.Plan δ) {branch : Nat → Nat} {t : Nat} + (slots : RecursiveSpaces.Slots branch plan.depth → Fin t → MixedSupport.Slot) + (upper lower : Nodes branch plan.depth) (lowerLevel : Nat) + +local instance rowSpaceFintype : Fintype (NodeEmbedding.RowSpace slots upper) := + Fintype.ofFinite _ + +local instance valueFintype : Fintype + (Block (FixedRows.rows plan) upper × + HierarchicalMatrixTable.SideOutput (rows := FixedRows.rows plan) upper) := + Fintype.ofFinite _ + +local instance upperDualFintype : Fintype (Module.Dual F2 (NodeEmbedding.RowSpace slots upper)) := + LeftDecoder.dualFintype (V := NodeEmbedding.RowSpace slots upper) + +variable {Ω : Type*} [Fintype Ω] + (original : FiniteDistribution Ω) (originalArrays : Ω → Arrays slots (FixedRows.rows plan)) + (lowerEvent : Ω → Bool) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch plan.depth t)) + (A : ManyGoodRows.RowMap (Block (FixedRows.rows plan) upper) plan.order) + (a : Block (FixedRows.rows plan) lower) + (cut : OwnInputReference.Cut upper lower) + (v : HierarchicalRawPrediction.Visible slots (FixedRows.rows plan) upper lower A + (FixedRows.repeats plan) cut) + +def meetingProbability : ℝ := + ((HierarchicalDecoderMeeting.leftLaw slots upper lowerLevel + (HierarchicalRawPrediction.visibleBackground slots (FixedRows.rows plan) upper lower A + (FixedRows.repeats plan) cut v) + original originalArrays lowerEvent (InitialParameters.useful δ) σ plan.density A + (HierarchicalRawPrediction.known slots (FixedRows.rows plan) upper lower A + (FixedRows.repeats plan) cut v)).product + (RightDecoder.law slots (FixedRows.rows plan) upper lower (LinearMap.ker A) a + (FixedRows.repeats plan) cut σ + (OwnInputReference.readInput slots (FixedRows.rows plan) upper lower (LinearMap.ker A) a + (OwnInputRawAssembly.scalarEval slots upper lower (FixedRows.repeats plan) cut) v) + (tau (InitialParameters.useful δ) plan.density plan.order + (FixedRows.rows plan (Nodes.height upper))))).probability + (fun pair => decide ((NodeEmbedding.embed slots upper).dualMap pair.1 = pair.2)) + +theorem meetingProbability_nonneg : + 0 ≤ meetingProbability plan slots upper lower lowerLevel original originalArrays lowerEvent σ A a cut v := + FiniteDistribution.probability_nonnegative _ _ + +theorem meeting_probability_lower (hδ : 0 < δ) + (externalLaw : FiniteDistribution + (OwnInputReference.Exterior slots (FixedRows.rows plan) upper lower)) + (positive : 0 < + (OwnInputReference.rawLaw slots (FixedRows.rows plan) upper lower (LinearMap.ker A) + (FixedRows.repeats plan) cut externalLaw).probability + (HierarchicalRawPrediction.given slots (FixedRows.rows plan) upper lower lowerLevel + original originalArrays lowerEvent (InitialParameters.useful δ) σ plan.density A + (FixedRows.repeats plan) cut v)) + (hprediction : rhoPred (InitialParameters.useful δ) plan.density ≤ + ((OwnInputReference.rawLaw slots (FixedRows.rows plan) upper lower (LinearMap.ker A) + (FixedRows.repeats plan) cut externalLaw).condition + (HierarchicalRawPrediction.given slots (FixedRows.rows plan) upper lower lowerLevel + original originalArrays lowerEvent (InitialParameters.useful δ) σ plan.density A + (FixedRows.repeats plan) cut v) positive).probability + (HierarchicalRawPrediction.rawPrediction slots (FixedRows.rows plan) upper lower lowerLevel + original originalArrays lowerEvent (InitialParameters.useful δ) σ plan.density A + (FixedRows.repeats plan) cut a)) : + (1 / (2 : ℝ) ^ plan.order) * + (tau (InitialParameters.useful δ) plan.density plan.order + (FixedRows.rows plan (Nodes.height upper)) ^ 2 / + (2 * (2 : ℝ) ^ FixedRows.rows plan (Nodes.height upper))) ≤ + meetingProbability plan slots upper lower lowerLevel original originalArrays lowerEvent σ A a cut v := by + obtain ⟨hgood, hne⟩ := HierarchicalRawPrediction.selection_of_positive slots (FixedRows.rows plan) + upper lower lowerLevel original originalArrays lowerEvent (InitialParameters.useful δ) + σ plan.density A (FixedRows.repeats plan) cut externalLaw v positive + unfold meetingProbability + apply HierarchicalFixedDecoderMeeting.meeting_probability_lower plan hδ slots upper lowerLevel + (HierarchicalRawPrediction.visibleBackground slots (FixedRows.rows plan) upper lower A + (FixedRows.repeats plan) cut v) + original originalArrays lowerEvent σ A + (HierarchicalRawPrediction.known slots (FixedRows.rows plan) upper lower A + (FixedRows.repeats plan) cut v) + lower a cut + (OwnInputReference.readInput slots (FixedRows.rows plan) upper lower (LinearMap.ker A) a + (OwnInputRawAssembly.scalarEval slots upper lower (FixedRows.repeats plan) cut) v) + hgood hne + exact hprediction.trans_eq + (HierarchicalRawPrediction.conditional_prediction_eq slots (FixedRows.rows plan) upper lower lowerLevel + original originalArrays lowerEvent (InitialParameters.useful δ) σ plan.density A + (FixedRows.repeats plan) cut a externalLaw v hgood hne positive) + +end +end PerfectCompleteness.HierarchicalRawMeeting + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalUsefulBackground.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalUsefulBackground.lean new file mode 100644 index 0000000000000000000000000000000000000000..148db13a9562fa58ed1a607476eb581ff75b1f87 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/HierarchicalUsefulBackground.lean @@ -0,0 +1,83 @@ +import OAI.Computability.PerfectCompleteness.Decoding.HierarchicalUsefulCollision +import OAI.Computability.PerfectCompleteness.Foundations.DependentPredictionDifferenceLemmas +import OAI.Computability.PerfectCompleteness.Sampling.HierarchicalBackgroundVariation + +namespace OAI + +section + +namespace PerfectCompleteness.HierarchicalUsefulBackground + +open TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) +open scoped Classical + +noncomputable section + +attribute [local instance] linearMapFintype + +variable {branch rows : Nat → Nat} {n t : Nat} + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (upper : Nodes branch n) + +local instance backgroundFintype : + Fintype (HierarchicalAgreementMean.Background (rows := rows) slots upper) := Fintype.ofFinite _ + +local instance rowSpaceFintype : Fintype (NodeEmbedding.RowSpace slots upper) := Fintype.ofFinite _ + +variable {P : Type*} [Fintype P] + (externalLaw : FiniteDistribution P) + (background : P → HierarchicalAgreementMean.Background (rows := rows) slots upper) + (scalarLaw : P → FiniteDistribution (NodeEmbedding.RowSpace slots upper)) + (hrows : 0 < rows (Nodes.height upper)) + +theorem pairLaw_background : + (HierarchicalUsefulCollision.pairLaw slots upper externalLaw background scalarLaw hrows).pushforward + Prod.fst = externalLaw.pushforward background := by + apply SigmaObservation.eq_of_probability_eq + intro event + rw [FiniteDistribution.probability_pushforward, HierarchicalUsefulCollision.pairLaw, + FiniteDistribution.probability_pushforward, FiniteDistribution.probability_pushforward] + change (CompletionSoundness.sigmaLaw externalLaw + (fun p => HierarchicalUsefulCollision.bucketLaw slots upper (scalarLaw p) hrows)).probability + (fun sample => event (background sample.1)) = + externalLaw.probability (fun p => event (background p)) + exact CompletionSoundness.sigmaLaw_probability_first externalLaw + (fun p => HierarchicalUsefulCollision.bucketLaw slots upper (scalarLaw p) hrows) + (fun p => event (background p)) + +theorem original_background_variation + (referenceBackground : FiniteDistribution + (HierarchicalAgreementMean.Background (rows := rows) slots upper)) : + (HierarchicalUsefulCollision.pairLaw slots upper externalLaw background scalarLaw hrows).totalVariation + (HierarchicalAgreementMean.referenceLaw slots upper + (externalLaw.pushforward background) hrows) ≤ + 2 * (HierarchicalUsefulCollision.pairLaw slots upper externalLaw background scalarLaw hrows).totalVariation + (HierarchicalAgreementMean.referenceLaw slots upper referenceBackground hrows) := by + have h := HierarchicalBackgroundVariation.original_background_variation slots upper + (HierarchicalUsefulCollision.pairLaw slots upper externalLaw background scalarLaw hrows) + referenceBackground hrows + rw [pairLaw_background] at h + exact h + +theorem original_background_le_of_bound + (referenceBackground : FiniteDistribution + (HierarchicalAgreementMean.Background (rows := rows) slots upper)) {error : ℝ} + (herror : (HierarchicalUsefulCollision.pairLaw slots upper externalLaw background scalarLaw hrows).totalVariation + (HierarchicalAgreementMean.referenceLaw slots upper referenceBackground hrows) ≤ error) : + (HierarchicalUsefulCollision.pairLaw slots upper externalLaw background scalarLaw hrows).totalVariation + (HierarchicalAgreementMean.referenceLaw slots upper + (externalLaw.pushforward background) hrows) ≤ 2 * error := by + have h := HierarchicalBackgroundVariation.original_background_le_of_bound slots upper + (HierarchicalUsefulCollision.pairLaw slots upper externalLaw background scalarLaw hrows) + referenceBackground hrows herror + rw [pairLaw_background] at h + exact h + +end +end PerfectCompleteness.HierarchicalUsefulBackground + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/KeyFiniteness.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/KeyFiniteness.lean new file mode 100644 index 0000000000000000000000000000000000000000..c06063da3a689b9db500716dd890d47c05826ffd --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/KeyFiniteness.lean @@ -0,0 +1,90 @@ +import Mathlib.Algebra.Order.BigOperators.Group.Finset +import OAI.Computability.PerfectCompleteness.Construction.TreeSourceSpaces +import OAI.Computability.PerfectCompleteness.Foundations.CanonicalKeys +import OAI.Computability.PerfectCompleteness.Reduction.SourceGame + +namespace OAI + +section + +namespace PerfectCompleteness.CanonicalKeys + +open ClauseSupport MixedSupport +open scoped BigOperators + +variable {n : Nat} {Y : Type*} + +abbrev KeyLabel (k : Key n) := ↥k.partition + +instance KeyLabel_finite (k : Key n) : Finite (KeyLabel k) := by + let : Finite ReducedValue := ReducedDomains.reducedValue_finite + exact Finite.of_injective (fun P : KeyLabel k => P.val) Subtype.val_injective + +instance keyLabel_nonempty (side : Side) (slots : Fin n → Slot) + (f : Assignment slots → Y) : Nonempty (KeyLabel (key side slots f)) := by + change Nonempty (Label slots f) + infer_instance + +theorem label_finite (slots : Fin n → Slot) (f : Assignment slots → Y) : + Finite (Label slots f) := by + infer_instance + +theorem label_nonempty (slots : Fin n → Slot) (f : Assignment slots → Y) : + Nonempty (Label slots f) := by + infer_instance + +theorem card_label_le_output [Finite Y] (slots : Fin n → Slot) + (f : Assignment slots → Y) : Nat.card (Label slots f) ≤ Nat.card Y := + Nat.card_le_card_of_injective (restore slots f) (restore_injective slots f) + +theorem card_label_le_assignment (slots : Fin n → Slot) (f : Assignment slots → Y) : + Nat.card (Label slots f) ≤ Nat.card (Assignment slots) := + ReducedPartition.card_parts_le (reduction slots f) f + +def answerEquivFinSeven (signs : SourceClause.Triple) : Answer signs ≃ Fin 7 where + toFun u := SourceGame.encodeLabel signs u.val + ((SourceClause.mem_satisfyingTriples signs u.val).mp u.property) + invFun i := ⟨SourceGame.decodeLabel signs i, SourceGame.decodeLabel_mem signs i⟩ + left_inv u := by + apply Subtype.ext + exact SourceGame.decodeLabel_encodeLabel signs u.val _ + right_inv i := by + apply SourceGame.decodeLabel_injective signs + exact SourceGame.decodeLabel_encodeLabel signs (SourceGame.decodeLabel signs i) _ + +theorem card_answer (signs : SourceClause.Triple) : Nat.card (Answer signs) = 7 := by + simpa only [Nat.card_fin] using Nat.card_congr (answerEquivFinSeven signs) + +theorem card_slotDomain_le_seven (s : Slot) : Nat.card s.Domain ≤ 7 := by + cases s with + | clause occurrence variableIDs signs => exact (card_answer signs).le + | bit variableID => + change Nat.card Bool ≤ 7 + simp + +theorem card_assignment_le_seven_pow (slots : Fin n → Slot) : + Nat.card (Assignment slots) ≤ 7 ^ n := by + change Nat.card (∀ i : Fin n, (slots i).Domain) ≤ _ + rw [Nat.card_pi] + calc + (∏ i : Fin n, Nat.card (slots i).Domain) ≤ ∏ _i : Fin n, (7 : Nat) := + Finset.prod_le_prod (fun i _ => card_slotDomain_le_seven (slots i)) + _ = 7 ^ n := by simp + +theorem card_label_le_seven_pow (slots : Fin n → Slot) (f : Assignment slots → Y) : + Nat.card (Label slots f) ≤ 7 ^ n := + (card_label_le_assignment slots f).trans (card_assignment_le_seven_pow slots) + +theorem card_keyLabel_le_output [Finite Y] (side : Side) (slots : Fin n → Slot) + (f : Assignment slots → Y) : Nat.card (KeyLabel (key side slots f)) ≤ Nat.card Y := + card_label_le_output slots f + +theorem card_keyLabel_le_seven_pow (side : Side) (slots : Fin n → Slot) + (f : Assignment slots → Y) : Nat.card (KeyLabel (key side slots f)) ≤ 7 ^ n := + card_label_le_seven_pow slots f + +end PerfectCompleteness.CanonicalKeys + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/LegalOutputLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/LegalOutputLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..3649b5fe4dec366738979f4f51053837005b6485 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/LegalOutputLemmas.lean @@ -0,0 +1,167 @@ +import OAI.Computability.PerfectCompleteness.Foundations.DependentPredictionDifferenceLemmas +import OAI.Computability.PerfectCompleteness.Reduction.CanonicalGameLemmas +import OAI.Computability.PerfectCompleteness.Reduction.CompletionAlphabetLemmas +import OAI.Computability.PerfectCompleteness.Sampling.BoundedListSamplingLemmas + +namespace OAI + + +namespace PerfectCompleteness.LegalOutput + +open scoped Classical +open UniqueGamesTheorem.Foundations.Games +open CompletionSoundness LegalEnumeration + +noncomputable section + +theorem exists_uniform_target {E Q₁ Q₂ : Type*} + [Fintype E] [Nonempty E] [Fintype Q₁] [Fintype Q₂] + {L : Q₁ → Type*} {R : Q₂ → Type*} + [∀ x, Fintype (L x)] [∀ y, Fintype (R y)] + [∀ x, Nonempty (L x)] [∀ y, Nonempty (R y)] + (G : LegalProjectionGame E Q₁ Q₂ L R) + (huniform : G.occurrences = FiniteDistribution.uniform E) + (hsmall : ∀ e b, Fintype.card {a : L (G.left e) // G.projection e a = b} ≤ 2) + (cap : Nat) (hleft : ∀ x, Fintype.card (L x) ≤ cap) + (hright : ∀ y, Fintype.card (R y) ≤ cap) + (δ : ℚ) (hδ : 0 < δ) : + let q := CompletionAlphabet.size cap δ + let M := ⌈(3 : ℚ) / δ⌉₊ * Fintype.card E * (2 * q) + ∃ target : Instance q, + target.leftVertices = Fintype.card Q₁ ∧ + target.rightVertices = Fintype.card Q₂ ∧ + target.edges.length ≤ M ∧ + (Encoding.gameBits target).length ≤ + Fintype.card Q₁ + Fintype.card Q₂ + q + M + 4 + + M * (Fintype.card Q₁ + Fintype.card Q₂ + 2 * q * q + 2 * q + 2) ∧ + (G.value = 1 → PerfectlyComplete target) ∧ + (G.value ≤ (δ : ℝ) / 3 → target.value ≤ (δ : ℝ)) := by + have hw : ∀ i, (numbered G).occurrences.weight i = + ((LegalUniform.uniformWeights E).weight i : ℝ) := + LegalUniform.equivFin_uniform_weight G.occurrences huniform + have hl : ∀ i, Fintype.card (NumberedLabels L i) ≤ cap := + fun i => hleft ((Fintype.equivFin Q₁).symm i) + have hr : ∀ i, Fintype.card (NumberedLabels R i) ≤ cap := + fun i => hright ((Fintype.equivFin Q₂).symm i) + obtain ⟨target, htL, htR, htE, htBits, hc, hs⟩ := CompletionAlphabet.exists_target + (numbered G) (LegalUniform.uniformWeights E) hw (numbered_at_most_two G hsmall) + cap hl hr δ hδ + refine ⟨target, htL, htR, htE, htBits, ?_, ?_⟩ + · intro h + apply hc + rw [numbered_value] + exact h + · intro h + apply hs + rw [numbered_value] + exact h + +end +end PerfectCompleteness.LegalOutput + + +namespace PerfectCompleteness.CanonicalOutput + +open scoped Classical +open UniqueGamesTheorem.Foundations.Games +open SourceClause MixedSupport CanonicalKeys BlockQuotient CanonicalGame +open CompletionSoundness + +noncomputable section + +variable {v m n : Nat} {E I B : Type*} {V : I → Type*} + [DecidableEq I] [∀ i, AddCommGroup (V i)] + [∀ i, Module DirectionQuotient.F2 (V i)] + [Finite I] [∀ i, Finite (V i)] [Finite B] + {clauses : Fin m → NormalizedClause v} + (F : BlockFamily clauses n E I V B) + +omit [DecidableEq I] in +theorem leftLabel_card_le_output (q : LeftVertex F) : + Nat.card (LeftLabel F q) ≤ Nat.card (JointOutput V B) := by + rcases q with ⟨k, e, rfl⟩ + exact card_keyLabel_le_output .left + (SourceKeys.slot clauses ∘ (F.presentation e).endpoints) (F.presentation e).joint + +theorem rightLabel_card_le_output (q : RightVertex F) : + Nat.card (RightLabel F q) ≤ Nat.card (JointOutput V B) := by + rcases q with ⟨k, e, rfl⟩ + let : Finite (RightOutput F e) := Finite.of_surjective + (projectBlock (B := B) (F.selected e) (F.direction e)) + (projectBlock_surjective (F.selected e) (F.direction e)) + have hlabel := card_keyLabel_le_output .right + (SourceKeys.slot clauses ∘ (rightPresentation F e).endpoints) + (rightPresentation F e).joint + exact hlabel.trans (Nat.card_le_card_of_surjective + (projectBlock (B := B) (F.selected e) (F.direction e)) + (projectBlock_surjective (F.selected e) (F.direction e))) + +variable [Fintype E] [Nonempty E] + [Fintype (LeftVertex F)] [Fintype (RightVertex F)] + [∀ x, Fintype (LeftLabel F x)] [∀ y, Fintype (RightLabel F y)] + +include F in +omit [DecidableEq I] [Fintype E] [Fintype (LeftVertex F)] [Fintype (RightVertex F)] + [∀ x, Fintype (LeftLabel F x)] [∀ y, Fintype (RightLabel F y)] in +theorem output_card_positive : 0 < Nat.card (JointOutput V B) := by + let e : E := Classical.choice inferInstance + have hpos : 0 < Nat.card (LeftLabel F (leftAt F e)) := Nat.card_pos + exact hpos.trans_le (leftLabel_card_le_output F (leftAt F e)) + +omit [Finite I] [∀ i, Finite (V i)] [Finite B] [Nonempty E] in +theorem game_value_of_satisfying (μ : FiniteDistribution E) + (assignment : Fin v → Bool) (hsat : ∀ c, (clauses c).clause.eval assignment = true) : + (game F μ).value = 1 := by + apply le_antisymm + · obtain ⟨s, hs⟩ := (game F μ).exists_optimal_strategy + rw [← hs] + exact μ.probability_le_one _ + · calc + 1 = (game F μ).success (satisfyingStrategy F assignment hsat) := + (success_satisfyingStrategy F μ assignment hsat).symm + _ ≤ (game F μ).value := (game F μ).success_le_value _ + +theorem exists_uniform_target (δ : ℚ) (hδ : 0 < δ) : + let q := CompletionAlphabet.size (Nat.card (JointOutput V B)) δ + let M := ⌈(3 : ℚ) / δ⌉₊ * Fintype.card E * (2 * q) + ∃ target : Instance q, + 2 ≤ q ∧ + target.leftVertices = Fintype.card (LeftVertex F) ∧ + target.rightVertices = Fintype.card (RightVertex F) ∧ + target.edges.length ≤ M ∧ + (Encoding.gameBits target).length ≤ + Fintype.card (LeftVertex F) + Fintype.card (RightVertex F) + q + M + 4 + + M * (Fintype.card (LeftVertex F) + Fintype.card (RightVertex F) + + 2 * q * q + 2 * q + 2) ∧ + ((∃ assignment : Fin v → Bool, + ∀ c, (clauses c).clause.eval assignment = true) → PerfectlyComplete target) ∧ + ((game F (FiniteDistribution.uniform E)).value ≤ (δ : ℝ) / 3 → + target.value ≤ (δ : ℝ)) := by + have hl : ∀ x, Fintype.card (LeftLabel F x) ≤ Nat.card (JointOutput V B) := by + intro x + simpa only [← Nat.card_eq_fintype_card] using leftLabel_card_le_output F x + have hr : ∀ y, Fintype.card (RightLabel F y) ≤ Nat.card (JointOutput V B) := by + intro y + simpa only [← Nat.card_eq_fintype_card] using rightLabel_card_le_output F y + obtain ⟨target, htL, htR, htE, htBits, hc, hs⟩ := LegalOutput.exists_uniform_target + (game F (FiniteDistribution.uniform E)) rfl + (by + intro e b + change Fintype.card {a : LeftLabel F (leftAt F e) // edge F e a = b} ≤ 2 + rw [Fintype.card_eq_nat_card] + exact edge_at_most_two F e b) + (Nat.card (JointOutput V B)) hl hr δ hδ + have hq : 2 ≤ CompletionAlphabet.size (Nat.card (JointOutput V B)) δ := by + have hpos := output_card_positive F + have hmax : Nat.card (JointOutput V B) + 1 ≤ + CompletionAlphabet.size (Nat.card (JointOutput V B)) δ := le_max_left _ _ + omega + refine ⟨target, hq, htL, htR, htE, htBits, ?_, hs⟩ + rintro ⟨assignment, hsat⟩ + apply hc + exact game_value_of_satisfying F (FiniteDistribution.uniform E) assignment hsat + +end +end PerfectCompleteness.CanonicalOutput + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/LegalRationalOutputLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/LegalRationalOutputLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..fe81fd04ed1e2585751d5fa31abf5b457cfa1772 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/LegalRationalOutputLemmas.lean @@ -0,0 +1,124 @@ +import OAI.Computability.PerfectCompleteness.Foundations.LegalOutputLemmas +import OAI.Computability.PerfectCompleteness.Sampling.BoundedListSamplingLemmas + +namespace OAI + + +namespace PerfectCompleteness.LegalRationalOutput + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games +open CompletionSoundness LegalEnumeration + +noncomputable section + +theorem exists_rational_target {E Q₁ Q₂ : Type*} + [Fintype E] [Fintype Q₁] [Fintype Q₂] + {L : Q₁ → Type*} {R : Q₂ → Type*} + [∀ x, Fintype (L x)] [∀ y, Fintype (R y)] + [∀ x, Nonempty (L x)] [∀ y, Nonempty (R y)] + (G : LegalProjectionGame E Q₁ Q₂ L R) + (f : E → ℚ) (hpositive : ∀ e, 0 < f e) (htotal : ∑ e, f e = 1) + (hweights : ∀ e, G.occurrences.weight e = (f e : ℝ)) + (hsmall : ∀ e b, Fintype.card {a : L (G.left e) // G.projection e a = b} ≤ 2) + (cap : Nat) (hleft : ∀ x, Fintype.card (L x) ≤ cap) + (hright : ∀ y, Fintype.card (R y) ≤ cap) + (δ : ℚ) (hδ : 0 < δ) : + let q := CompletionAlphabet.size cap δ + let M := ⌈(3 : ℚ) / δ⌉₊ * Fintype.card E * (2 * q) + ∃ target : Instance q, + target.leftVertices = Fintype.card Q₁ ∧ + target.rightVertices = Fintype.card Q₂ ∧ + target.edges.length ≤ M ∧ + (Encoding.gameBits target).length ≤ + Fintype.card Q₁ + Fintype.card Q₂ + q + M + 4 + + M * (Fintype.card Q₁ + Fintype.card Q₂ + 2 * q * q + 2 * q + 2) ∧ + (G.value = 1 → PerfectlyComplete target) ∧ + (G.value ≤ (δ : ℝ) / 3 → target.value ≤ (δ : ℝ)) := by + let w := LegalUniform.enumeratedWeights f hpositive htotal (Fintype.equivFin E) + have hw : ∀ i, (numbered G).occurrences.weight i = (w.weight i : ℝ) := + LegalUniform.transport_weight_eq_enumerated G.occurrences f hpositive htotal + hweights (Fintype.equivFin E) + have hl : ∀ i, Fintype.card (NumberedLabels L i) ≤ cap := + fun i => hleft ((Fintype.equivFin Q₁).symm i) + have hr : ∀ i, Fintype.card (NumberedLabels R i) ≤ cap := + fun i => hright ((Fintype.equivFin Q₂).symm i) + obtain ⟨target, htL, htR, htE, htBits, hc, hs⟩ := CompletionAlphabet.exists_target + (numbered G) w hw (numbered_at_most_two G hsmall) cap hl hr δ hδ + refine ⟨target, htL, htR, htE, htBits, ?_, ?_⟩ + · intro h + apply hc + rw [numbered_value] + exact h + · intro h + apply hs + rw [numbered_value] + exact h + +end +end PerfectCompleteness.LegalRationalOutput + + +namespace PerfectCompleteness.CanonicalRationalOutput + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games +open SourceClause MixedSupport CanonicalKeys BlockQuotient CanonicalGame CanonicalOutput + +noncomputable section + +variable {v m n : Nat} {E I B : Type*} {V : I → Type*} + [DecidableEq I] [∀ i, AddCommGroup (V i)] + [∀ i, Module DirectionQuotient.F2 (V i)] + [Finite I] [∀ i, Finite (V i)] [Finite B] + {clauses : Fin m → NormalizedClause v} + (F : BlockFamily clauses n E I V B) + [Fintype E] [Nonempty E] + [Fintype (LeftVertex F)] [Fintype (RightVertex F)] + [∀ x, Fintype (LeftLabel F x)] [∀ y, Fintype (RightLabel F y)] + +theorem exists_target (μ : FiniteDistribution E) (weights : E → ℚ) + (hpositive : ∀ e, 0 < weights e) (htotal : ∑ e, weights e = 1) + (hweights : ∀ e, μ.weight e = (weights e : ℝ)) (δ : ℚ) (hδ : 0 < δ) : + let q := CompletionAlphabet.size (Nat.card (JointOutput V B)) δ + let M := ⌈(3 : ℚ) / δ⌉₊ * Fintype.card E * (2 * q) + ∃ target : Instance q, + 2 ≤ q ∧ + target.leftVertices = Fintype.card (LeftVertex F) ∧ + target.rightVertices = Fintype.card (RightVertex F) ∧ + target.edges.length ≤ M ∧ + (Encoding.gameBits target).length ≤ + Fintype.card (LeftVertex F) + Fintype.card (RightVertex F) + q + M + 4 + + M * (Fintype.card (LeftVertex F) + Fintype.card (RightVertex F) + + 2 * q * q + 2 * q + 2) ∧ + ((∃ assignment : Fin v → Bool, + ∀ c, (clauses c).clause.eval assignment = true) → PerfectlyComplete target) ∧ + ((game F μ).value ≤ (δ : ℝ) / 3 → target.value ≤ (δ : ℝ)) := by + have hl : ∀ x, Fintype.card (LeftLabel F x) ≤ Nat.card (JointOutput V B) := by + intro x + simpa only [← Nat.card_eq_fintype_card] using leftLabel_card_le_output F x + have hr : ∀ y, Fintype.card (RightLabel F y) ≤ Nat.card (JointOutput V B) := by + intro y + simpa only [← Nat.card_eq_fintype_card] using rightLabel_card_le_output F y + obtain ⟨target, htL, htR, htE, htBits, hc, hs⟩ := + LegalRationalOutput.exists_rational_target (game F μ) weights hpositive htotal hweights + (by + intro e b + change Fintype.card {a : LeftLabel F (leftAt F e) // edge F e a = b} ≤ 2 + rw [Fintype.card_eq_nat_card] + exact edge_at_most_two F e b) + (Nat.card (JointOutput V B)) hl hr δ hδ + have hq : 2 ≤ CompletionAlphabet.size (Nat.card (JointOutput V B)) δ := by + have hpos := output_card_positive F + have hmax : Nat.card (JointOutput V B) + 1 ≤ + CompletionAlphabet.size (Nat.card (JointOutput V B)) δ := le_max_left _ _ + omega + refine ⟨target, hq, htL, htR, htE, htBits, ?_, hs⟩ + rintro ⟨assignment, hsat⟩ + apply hc + exact game_value_of_satisfying F μ assignment hsat + +end +end PerfectCompleteness.CanonicalRationalOutput + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/LinearEvaluationLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/LinearEvaluationLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..2d37ffcb174160b5ed468e7b0268869c09bd7a2f --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/LinearEvaluationLemmas.lean @@ -0,0 +1,433 @@ +import Mathlib.Algebra.Field.ZMod +import Mathlib.Algebra.Module.Torsion.Field +import Mathlib.Algebra.Order.Field.Basic +import Mathlib.Data.Rat.Cast.Order +import Mathlib.LinearAlgebra.Basis.VectorSpace +import Mathlib.LinearAlgebra.Dimension.Constructions +import Mathlib.LinearAlgebra.Quotient.Basic +import Mathlib.Logic.Equiv.Prod +import OAI.Computability.PerfectCompleteness.Foundations.CanonicalEdgesLemmas +import OAI.Computability.UniqueGames.Gadgets.AdaptivePathsLemmas +import OAI.Computability.UniqueGames.Reduction.BinaryLinear +import OAI.Computability.UniqueGames.Reduction.FinalParametersLemmas + +namespace OAI + +section + +namespace UniqueGamesTheorem.Gadget.LinearEvaluation + +universe u v + +variable {V : Type u} {P : Type v} +variable [AddCommGroup V] [Module (ZMod 2) V] +variable [AddCommGroup P] [Module (ZMod 2) P] + +def fiberEquivKernel (f : V →ₗ[ZMod 2] P) (a : P) (v : V) (hv : f v = a) : + {x : V // f x = a} ≃ f.ker where + toFun x := ⟨x.val - v, by simp [x.property, hv]⟩ + invFun k := ⟨k.val + v, by simp [hv]⟩ + left_inv x := by ext; simp + right_inv k := by ext; simp + +theorem fiber_card_eq_kernel_of_surjective (f : V →ₗ[ZMod 2] P) + (hf : Function.Surjective f) (a : P) : + Nat.card {x : V // f x = a} = Nat.card f.ker := by + obtain ⟨v, hv⟩ := hf a + exact Nat.card_congr (fiberEquivKernel f a v hv) + +variable [FiniteDimensional (ZMod 2) V] [FiniteDimensional (ZMod 2) P] + +omit [FiniteDimensional (ZMod 2) P] in + +theorem fiber_card_mul_pow_of_surjective (f : V →ₗ[ZMod 2] P) + (hf : Function.Surjective f) (a : P) : + Nat.card {x : V // f x = a} * 2 ^ Module.finrank (ZMod 2) P = Nat.card V := by + rw [fiber_card_eq_kernel_of_surjective f hf] + have hr : Module.finrank (ZMod 2) f.range = Module.finrank (ZMod 2) P := by + rw [LinearMap.range_eq_top.mpr hf, finrank_top] + rw [← hr] + exact LinearKernelCount.kernel_card_mul_pow_rank f + +theorem fiber_card_mul_card_of_surjective (f : V →ₗ[ZMod 2] P) + (hf : Function.Surjective f) (a : P) : + Nat.card {x : V // f x = a} * Nat.card P = Nat.card V := by + rw [LinearKernelCount.card_binary_space (V := P)] + exact fiber_card_mul_pow_of_surjective f hf a + +omit [FiniteDimensional (ZMod 2) P] in + +theorem cancellation_card_mul_pow_of_surjective (f : V →ₗ[ZMod 2] P) + (hf : Function.Surjective f) (a : P) : + Nat.card {x : V // a + f x = 0} * 2 ^ Module.finrank (ZMod 2) P = Nat.card V := by + have hevent : {x : V // a + f x = 0} ≃ {x : V // f x = -a} := + Equiv.subtypeEquivRight fun _ => add_eq_zero_iff_eq_neg' + rw [Nat.card_congr hevent] + exact fiber_card_mul_pow_of_surjective f hf (-a) + +theorem cancellation_count_of_surjective_card_le_eight (f : V →ₗ[ZMod 2] P) + (hf : Function.Surjective f) (a : P) (hcard : Nat.card P ≤ 8) : + Nat.card V ≤ 8 * Nat.card {x : V // a + f x = 0} := by + have heq := cancellation_card_mul_pow_of_surjective f hf a + rw [← LinearKernelCount.card_binary_space (V := P)] at heq + calc + Nat.card V = Nat.card {x : V // a + f x = 0} * Nat.card P := heq.symm + _ ≤ Nat.card {x : V // a + f x = 0} * 8 := Nat.mul_le_mul_left _ hcard + _ = _ := Nat.mul_comm _ _ + +theorem cancellation_count_at_least_one_eighth_of_surjective (f : V →ₗ[ZMod 2] P) + (hf : Function.Surjective f) (a : P) (hP : Module.finrank (ZMod 2) P ≤ 3) : + Nat.card V ≤ 8 * Nat.card {x : V // a + f x = 0} := by + apply cancellation_count_of_surjective_card_le_eight f hf a + rw [LinearKernelCount.card_binary_space (V := P)] + exact (Nat.pow_le_pow_right (by decide) hP : 2 ^ Module.finrank (ZMod 2) P ≤ 2 ^ 3) + +def evaluation (x : V) : (V →ₗ[ZMod 2] P) →ₗ[ZMod 2] P := LinearMap.applyₗ x + +omit [FiniteDimensional (ZMod 2) V] [FiniteDimensional (ZMod 2) P] in +@[simp] theorem evaluation_apply (x : V) (f : V →ₗ[ZMod 2] P) : + evaluation x f = f x := rfl + +omit [FiniteDimensional (ZMod 2) V] [FiniteDimensional (ZMod 2) P] in + +theorem evaluation_surjective (x : V) (hx : x ≠ 0) : + Function.Surjective (evaluation x : (V →ₗ[ZMod 2] P) →ₗ[ZMod 2] P) := by + intro a + have hxbot : x ∉ (⊥ : Submodule (ZMod 2) V) := by simpa using hx + obtain ⟨f, _, hf⟩ := LinearMap.exists_extend_of_notMem + (0 : (⊥ : Submodule (ZMod 2) V) →ₗ[ZMod 2] P) hxbot a + exact ⟨f, hf⟩ + +theorem evaluation_fiber_card_mul_pow (x : V) (hx : x ≠ 0) (a : P) : + Nat.card {f : V →ₗ[ZMod 2] P // f x = a} * + 2 ^ Module.finrank (ZMod 2) P = Nat.card (V →ₗ[ZMod 2] P) := by + exact fiber_card_mul_pow_of_surjective (evaluation x) (evaluation_surjective x hx) a + +theorem cancellation_count_at_least_one_eighth (x : V) (hx : x ≠ 0) (a : P) + (hP : Module.finrank (ZMod 2) P ≤ 3) : + Nat.card (V →ₗ[ZMod 2] P) ≤ 8 * Nat.card {f : V →ₗ[ZMod 2] P // a + f x = 0} := by + exact cancellation_count_at_least_one_eighth_of_surjective + (evaluation x) (evaluation_surjective x hx) a hP + +noncomputable def uniformProbability (event : V → Prop) : ℚ := + (Nat.card {x : V // event x} : ℚ) / (Nat.card V : ℚ) + +omit [FiniteDimensional (ZMod 2) P] in + +theorem cancellation_probability_of_surjective (f : V →ₗ[ZMod 2] P) + (hf : Function.Surjective f) (a : P) : + uniformProbability (fun x => a + f x = 0) = + 1 / (2 : ℚ) ^ Module.finrank (ZMod 2) P := by + have hV : (Nat.card V : ℚ) ≠ 0 := + Nat.cast_ne_zero.mpr (Nat.ne_of_gt (LinearKernelCount.card_source_pos (V := V))) + have hpow : (2 : ℚ) ^ Module.finrank (ZMod 2) P ≠ 0 := pow_ne_zero _ (by decide) + apply (div_eq_div_iff hV hpow).mpr + have heq := cancellation_card_mul_pow_of_surjective f hf a + simpa only [Nat.cast_mul, Nat.cast_pow, Nat.cast_ofNat, one_mul] using + congrArg (fun k : Nat => (k : ℚ)) heq + +omit [FiniteDimensional (ZMod 2) P] in + +theorem cancellation_probability_at_least_one_eighth_of_surjective + (f : V →ₗ[ZMod 2] P) (hf : Function.Surjective f) (a : P) + (hP : Module.finrank (ZMod 2) P ≤ 3) : + (1 : ℚ) / 8 ≤ uniformProbability (fun x => a + f x = 0) := by + rw [cancellation_probability_of_surjective f hf a] + apply one_div_le_one_div_of_le (pow_pos (by decide) _) + have hnat : 2 ^ Module.finrank (ZMod 2) P ≤ 8 := + (Nat.pow_le_pow_right (by decide) hP : 2 ^ Module.finrank (ZMod 2) P ≤ 2 ^ 3) + exact_mod_cast hnat + +omit [FiniteDimensional (ZMod 2) P] in + +theorem cancellation_probability_target_dim_zero + (f : V →ₗ[ZMod 2] P) (hf : Function.Surjective f) (a : P) + (hP : Module.finrank (ZMod 2) P = 0) : + uniformProbability (fun x => a + f x = 0) = 1 := by + rw [cancellation_probability_of_surjective f hf a, hP] + simp + +theorem evaluation_cancellation_probability (x : V) (hx : x ≠ 0) (a : P) : + uniformProbability (fun f : V →ₗ[ZMod 2] P => a + f x = 0) = + 1 / (2 : ℚ) ^ Module.finrank (ZMod 2) P := + cancellation_probability_of_surjective (evaluation x) (evaluation_surjective x hx) a + +theorem evaluation_cancellation_probability_at_least_one_eighth + (x : V) (hx : x ≠ 0) (a : P) (hP : Module.finrank (ZMod 2) P ≤ 3) : + (1 : ℚ) / 8 ≤ uniformProbability (fun f : V →ₗ[ZMod 2] P => a + f x = 0) := + cancellation_probability_at_least_one_eighth_of_surjective + (evaluation x) (evaluation_surjective x hx) a hP + +theorem cancellation_finset_count_of_surjective [Fintype V] [DecidableEq P] + (f : V →ₗ[ZMod 2] P) (hf : Function.Surjective f) (a : P) + (hP : Module.finrank (ZMod 2) P ≤ 3) : + Fintype.card V ≤ 8 * (Finset.univ.filter (fun x : V => a + f x = 0)).card := by + have h := cancellation_count_at_least_one_eighth_of_surjective f hf a hP + simpa only [Nat.card_eq_fintype_card, Fintype.card_subtype] using h + +theorem evaluation_cancellation_finset_count [Fintype (V →ₗ[ZMod 2] P)] [DecidableEq P] + (x : V) (hx : x ≠ 0) (a : P) (hP : Module.finrank (ZMod 2) P ≤ 3) : + Fintype.card (V →ₗ[ZMod 2] P) ≤ + 8 * (Finset.univ.filter (fun f : V →ₗ[ZMod 2] P => a + f x = 0)).card := by + have h := cancellation_count_at_least_one_eighth x hx a hP + simpa only [Nat.card_eq_fintype_card, Fintype.card_subtype] using h + +theorem correction_space_card_pos : 0 < Nat.card (V →ₗ[ZMod 2] P) := + LinearKernelCount.card_source_pos + +omit [FiniteDimensional (ZMod 2) V] [FiniteDimensional (ZMod 2) P] in + +theorem evaluation_fibers_equal_card (x : V) (hx : x ≠ 0) (a b : P) : + Nat.card {f : V →ₗ[ZMod 2] P // f x = a} = + Nat.card {f : V →ₗ[ZMod 2] P // f x = b} := by + exact (fiber_card_eq_kernel_of_surjective (evaluation x) (evaluation_surjective x hx) a).trans + (fiber_card_eq_kernel_of_surjective (evaluation x) (evaluation_surjective x hx) b).symm + +end UniqueGamesTheorem.Gadget.LinearEvaluation + +end + +section + +namespace PerfectCompleteness.DirectionQuotient + +abbrev F2 := UniqueGamesTheorem.Integration.BinaryLinear.F2 + +variable {V B : Type*} [AddCommGroup V] [Module F2 V] + +def line (a : V) : Submodule F2 V := Submodule.span F2 {a} + +abbrev Space (a : V) := V ⧸ line a + +def proj (a : V) : V →ₗ[F2] Space a := (line a).mkQ + +theorem proj_surjective (a : V) : Function.Surjective (proj a) := + (line a).mkQ_surjective + +theorem mem_line_iff (a x : V) : x ∈ line a ↔ x = 0 ∨ x = a := by + constructor + · intro hx + obtain ⟨c, hc⟩ := Submodule.mem_span_singleton.1 hx + rcases UniqueGamesTheorem.Integration.BinaryLinear.scalar_cases c with hzero | hone + · left + simpa only [hzero, zero_smul] using hc.symm + · right + simpa only [hone, one_smul] using hc.symm + · rintro (rfl | rfl) + · exact (line a).zero_mem + · exact Submodule.mem_span_singleton_self _ + +theorem proj_eq_zero_iff (a x : V) : proj a x = 0 ↔ x = 0 ∨ x = a := + (Submodule.Quotient.mk_eq_zero (line a)).trans (mem_line_iff a x) + +theorem proj_eq_iff (a x y : V) : + proj a x = proj a y ↔ x - y = 0 ∨ x - y = a := + (Submodule.Quotient.eq (line a)).trans (mem_line_iff a (x - y)) + +theorem card_line (a : V) (ha : a ≠ 0) : Nat.card (line a) = 2 := by + calc + Nat.card (line a) = Nat.card F2 := + Nat.card_congr (LinearEquiv.toSpanNonzeroSingleton F2 V a ha).symm.toEquiv + _ = 2 := Nat.card_zmod 2 + +theorem card_proj_fiber (a : V) (ha : a ≠ 0) (z : Space a) : + Nat.card {v : V // proj a v = z} = 2 := by + rw [UniqueGamesTheorem.Gadget.LinearEvaluation.fiber_card_eq_kernel_of_surjective + (proj a) (proj_surjective a) z] + change Nat.card (LinearMap.ker (line a).mkQ) = 2 + rw [Submodule.ker_mkQ] + exact card_line a ha + +def projectWithSide (a : V) (x : V × B) : Space a × B := + (proj a x.1, x.2) + +theorem projectWithSide_surjective (a : V) : + Function.Surjective (projectWithSide (B := B) a) := by + intro z + obtain ⟨v, hv⟩ := proj_surjective a z.1 + exact ⟨(v, z.2), Prod.ext hv rfl⟩ + +def withSideFiberEquiv (a : V) (z : Space a × B) : + {x : V × B // projectWithSide a x = z} ≃ {v : V // proj a v = z.1} where + toFun x := ⟨x.val.1, congrArg Prod.fst x.property⟩ + invFun v := ⟨(v.val, z.2), Prod.ext v.property rfl⟩ + left_inv x := by + apply Subtype.ext + exact Prod.ext rfl (congrArg Prod.snd x.property).symm + right_inv v := by + apply Subtype.ext + rfl + +theorem card_projectWithSide_fiber (a : V) (ha : a ≠ 0) (z : Space a × B) : + Nat.card {x : V × B // projectWithSide a x = z} = 2 := + (Nat.card_congr (withSideFiberEquiv a z)).trans (card_proj_fiber a ha z.1) + +open MixedSupport CanonicalKeys + +theorem coarsen_at_most_two [Finite V] {n : Nat} + (slots : Fin n → Slot) (f : Assignment slots → V) (a : V) (ha : a ≠ 0) + (Q : Label slots (proj a ∘ f)) : + Nat.card {P : Label slots f // CanonicalEdges.coarsen slots f (proj a) P = Q} ≤ 2 := by + apply CanonicalEdges.coarsen_at_most_two slots f (proj a) + intro z + exact (card_proj_fiber a ha z).le + +theorem coarsenWithSide_at_most_two [Finite V] [Finite B] {n : Nat} + (slots : Fin n → Slot) (f : Assignment slots → V × B) (a : V) (ha : a ≠ 0) + (Q : Label slots (projectWithSide a ∘ f)) : + Nat.card {P : Label slots f // + CanonicalEdges.coarsen slots f (projectWithSide a) P = Q} ≤ 2 := by + apply CanonicalEdges.coarsen_at_most_two slots f (projectWithSide a) + intro z + exact (card_projectWithSide_fiber a ha z).le + +end PerfectCompleteness.DirectionQuotient + +end + +section + +namespace PerfectCompleteness.BlockQuotient + +open DirectionQuotient + +variable {I B : Type*} {V : I → Type*} [DecidableEq I] + +abbrev JointOutput (V : I → Type*) (B : Type*) := (∀ i, V i) × B + +abbrev OtherBlocks (V : I → Type*) (selected : I) := ∀ i : {i // i ≠ selected}, V i.val + +def splitOutput (V : I → Type*) (B : Type*) (selected : I) : + JointOutput V B ≃ V selected × (OtherBlocks V selected × B) := + ((Equiv.piSplitAt selected V).prodCongr (Equiv.refl B)).trans (Equiv.prodAssoc _ _ _) + +@[simp] theorem splitOutput_selected (selected : I) (x : JointOutput V B) : + (splitOutput V B selected x).1 = x.1 selected := rfl + +@[simp] theorem splitOutput_other (selected : I) (x : JointOutput V B) + (i : {i // i ≠ selected}) : + (splitOutput V B selected x).2.1 i = x.1 i.val := rfl + +@[simp] theorem splitOutput_side (selected : I) (x : JointOutput V B) : + (splitOutput V B selected x).2.2 = x.2 := rfl + +variable [∀ i, AddCommGroup (V i)] [∀ i, Module F2 (V i)] + +def projectBlock (selected : I) (a : V selected) (x : JointOutput V B) : + Space a × (OtherBlocks V selected × B) := + projectWithSide a (splitOutput V B selected x) + +@[simp] theorem projectBlock_selected (selected : I) (a : V selected) + (x : JointOutput V B) : (projectBlock selected a x).1 = proj a (x.1 selected) := rfl + +@[simp] theorem projectBlock_other (selected : I) (a : V selected) + (x : JointOutput V B) (i : {i // i ≠ selected}) : + (projectBlock selected a x).2.1 i = x.1 i.val := rfl + +@[simp] theorem projectBlock_side (selected : I) (a : V selected) + (x : JointOutput V B) : (projectBlock selected a x).2.2 = x.2 := rfl + +theorem projectBlock_surjective (selected : I) (a : V selected) : + Function.Surjective (projectBlock (B := B) selected a) := + (projectWithSide_surjective a).comp (splitOutput V B selected).surjective + +def blockFiberEquiv (selected : I) (a : V selected) + (z : Space a × (OtherBlocks V selected × B)) : + {x : JointOutput V B // projectBlock selected a x = z} ≃ + {y : V selected × (OtherBlocks V selected × B) // projectWithSide a y = z} where + toFun x := ⟨splitOutput V B selected x.val, x.property⟩ + invFun y := ⟨(splitOutput V B selected).symm y.val, by + change projectWithSide a (splitOutput V B selected ((splitOutput V B selected).symm y.val)) = z + rw [(splitOutput V B selected).apply_symm_apply] + exact y.property⟩ + left_inv x := by + apply Subtype.ext + exact (splitOutput V B selected).symm_apply_apply x.val + right_inv y := by + apply Subtype.ext + exact (splitOutput V B selected).apply_symm_apply y.val + +theorem card_projectBlock_fiber (selected : I) (a : V selected) (ha : a ≠ 0) + (z : Space a × (OtherBlocks V selected × B)) : + Nat.card {x : JointOutput V B // projectBlock selected a x = z} = 2 := + (Nat.card_congr (blockFiberEquiv selected a z)).trans + (card_projectWithSide_fiber a ha z) + +open MixedSupport CanonicalKeys + +theorem coarsenBlock_at_most_two [Finite I] [∀ i, Finite (V i)] [Finite B] {n : Nat} + (slots : Fin n → Slot) (f : Assignment slots → JointOutput V B) + (selected : I) (a : V selected) (ha : a ≠ 0) + (Q : Label slots (projectBlock selected a ∘ f)) : + Nat.card {P : Label slots f // + CanonicalEdges.coarsen slots f (projectBlock selected a) P = Q} ≤ 2 := by + apply CanonicalEdges.coarsen_at_most_two slots f (projectBlock selected a) + intro z + exact (card_projectBlock_fiber selected a ha z).le + +end PerfectCompleteness.BlockQuotient + +end + +section + +namespace UniqueGamesTheorem.Integration.CutoffBudget + +open scoped BigOperators + +noncomputable def cutoffSum (r : Nat) (ρ : ℝ) : ℝ := + ∑ d ∈ Finset.range (r + 1), + if d = 0 then ρ else (2 : ℝ) ^ (30 * d * d) * ρ ^ ((1 : ℝ) / 4) + +theorem cutoffSum_le (r : Nat) {ρ : ℝ} (hρ : 0 < ρ) (hρ1 : ρ ≤ 1) : + cutoffSum r ρ ≤ + (r + 1 : ℝ) * (2 : ℝ) ^ (30 * r * r) * ρ ^ ((1 : ℝ) / 4) := by + have hroot : 0 ≤ ρ ^ ((1 : ℝ) / 4) := Real.rpow_nonneg hρ.le _ + have hrho : ρ ≤ ρ ^ ((1 : ℝ) / 4) := by + simpa only [Real.rpow_one] using + (Real.rpow_le_rpow_of_exponent_ge hρ hρ1 + (by norm_num : (1 : ℝ) / 4 ≤ 1)) + have hone : (1 : ℝ) ≤ 2 ^ (30 * r * r) := one_le_pow₀ (by norm_num) + calc + cutoffSum r ρ ≤ ∑ _d ∈ Finset.range (r + 1), + (2 : ℝ) ^ (30 * r * r) * ρ ^ ((1 : ℝ) / 4) := by + unfold cutoffSum + apply Finset.sum_le_sum + intro d hd + have hdr : d ≤ r := Nat.le_of_lt_succ (Finset.mem_range.mp hd) + split_ifs + · exact hrho.trans (by simpa only [one_mul] using + mul_le_mul_of_nonneg_right hone hroot) + · apply mul_le_mul_of_nonneg_right _ hroot + apply pow_le_pow_right₀ (by norm_num : (1 : ℝ) ≤ 2) + exact Nat.mul_le_mul (Nat.mul_le_mul_left 30 hdr) hdr + _ = _ := by simp [mul_assoc] + +theorem rho_real_bounds {r s : Nat} (hs : r + 1 < s) : + 0 < (FinalParameters.rho r s : ℝ) ∧ (FinalParameters.rho r s : ℝ) < 1 := by + constructor + · exact_mod_cast FinalParameters.rho_pos r s + · have hq : FinalParameters.rho r s < 1 := by + unfold FinalParameters.rho + exact pow_lt_one₀ (by norm_num) (by norm_num) (by omega) + exact_mod_cast hq + +theorem cutoffSum_le_budget {r s : Nat} {δ : ℚ} (hs : r + 1 < s) + (hbudget : (FinalParameters.levelConstant r : ℝ) * + (FinalParameters.rho r s : ℝ) ^ ((1 : ℝ) / 4) ≤ (δ : ℝ) / 8) : + cutoffSum r (FinalParameters.rho r s : ℝ) ≤ (δ : ℝ) / 8 := by + have hρ := rho_real_bounds hs + apply (cutoffSum_le r hρ.1 hρ.2.le).trans + simpa [FinalParameters.levelConstant, pow_two, mul_assoc] using hbudget + +theorem exists_symbol_dimension_cutoff (r : Nat) {δ : ℚ} (hδ : 0 < δ) : + ∃ s : Nat, r + 1 < s ∧ + cutoffSum r (FinalParameters.rho r s : ℝ) ≤ (δ : ℝ) / 8 := by + obtain ⟨s, hs, hbudget⟩ := RealBounds.exists_symbol_dimension_real r hδ + exact ⟨s, hs, cutoffSum_le_budget hs hbudget⟩ + +end UniqueGamesTheorem.Integration.CutoffBudget + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/ManyGoodRowsLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/ManyGoodRowsLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..3b9278bd814b6239707245268fe5d90d973c4821 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/ManyGoodRowsLemmas.lean @@ -0,0 +1,482 @@ +import Mathlib.Algebra.Field.ZMod +import Mathlib.LinearAlgebra.Span.Basic +import Mathlib.Tactic.Ring +import OAI.Computability.PerfectCompleteness.Algebra.EvaluationMatrix +import OAI.Computability.PerfectCompleteness.Algebra.MatrixErasure +import OAI.Computability.PerfectCompleteness.Algebra.MatrixInverseConstantsLemmas +import OAI.Computability.PerfectCompleteness.Foundations.CanonicalKeys +import OAI.Computability.PerfectCompleteness.Foundations.RecursiveSpaceEquivLemmas +import OAI.Computability.UniqueGames.Foundations.FiniteTrialsLemmas + +namespace OAI + + +namespace PerfectCompleteness.ManyGoodRows + +noncomputable section + +open scoped BigOperators Classical +open UniqueGamesTheorem.Fourier.MatrixCharacters (F2) +open UniqueGamesTheorem.Fourier.MatrixRestrictions UniqueGamesTheorem.Fourier.MatrixLevelBridge +open UniqueGamesTheorem.Appendix.RankLevelFilter +open PerfectCompleteness.PartialTableInverse PerfectCompleteness.MatrixErasure + +attribute [local instance] linearMapFintype + +variable {E F Y : Type*} + [AddCommGroup E] [Module F2 E] [AddCommGroup F] [Module F2 F] + [FiniteDimensional F2 E] [FiniteDimensional F2 F] + [Fintype E] [Fintype F] [Fintype Y] + +abbrev RowMap (F : Type*) [AddCommGroup F] [Module F2 F] (r : Nat) := + F →ₗ[F2] (Fin r → F2) + +def GoodRow (f : (E →ₗ[F2] F) → Option Y) (r : Nat) (ρ : ℝ) + (A : RowMap F r) (U : E →ₗ[F2] (Fin r → F2)) : Prop := + ∃ (W : Submodule F2 E) (T : E →ₗ[F2] F) (y : Y), + Module.finrank F2 W ≤ r ∧ A.comp T = U ∧ + ρ ≤ (𝔼 X : MatrixSlice.Slice W (LinearMap.ker A) T, indicator f y X.val) + +structure Witness (f : (E →ₗ[F2] F) → Option Y) (r : Nat) (ρ : ℝ) + (A : RowMap F r) (U : E →ₗ[F2] (Fin r → F2)) where + columnSpace : Submodule F2 E + base : E →ₗ[F2] F + value : Y + column_count : Module.finrank F2 columnSpace ≤ r + row_value : A.comp base = U + density : ρ ≤ (𝔼 X : MatrixSlice.Slice columnSpace (LinearMap.ker A) base, + indicator f value X.val) + +def selectWitness (f : (E →ₗ[F2] F) → Option Y) (r : Nat) (ρ : ℝ) + (A : RowMap F r) (U : E →ₗ[F2] (Fin r → F2)) (h : GoodRow f r ρ A U) : + Witness f r ρ A U := + Classical.choice (by + obtain ⟨W, T, y, hW, hU, hdensity⟩ := h + exact ⟨⟨W, T, y, hW, hU, hdensity⟩⟩) + +def IsGoodPoint (f : (E →ₗ[F2] F) → Option Y) (r : Nat) (ρ : ℝ) + (X : E →ₗ[F2] F) : Prop := + ∃ A : RowMap F r, GoodRow f r ρ A (A.comp X) + +def goodMass (f : (E →ₗ[F2] F) → Option Y) (r : Nat) (ρ : ℝ) : ℝ := + uniformMass (IsGoodPoint f r ρ) + +def adviceMass (f : (E →ₗ[F2] F) → Option Y) (r : Nat) (ρ : ℝ) : ℝ := + 𝔼 A : RowMap F r, 𝔼 X : E →ₗ[F2] F, + if GoodRow f r ρ A (A.comp X) then (1 : ℝ) else 0 + +omit [FiniteDimensional F2 E] [FiniteDimensional F2 F] [Fintype Y] in +theorem GoodRow.mono {f g : (E →ₗ[F2] F) → Option Y} {r : Nat} {ρ : ℝ} + {A : RowMap F r} {U : E →ₗ[F2] (Fin r → F2)} + (h : GoodRow f r ρ A U) + (hfg : ∀ y X, indicator f y X ≤ indicator g y X) : GoodRow g r ρ A U := by + obtain ⟨W, T, y, hW, hU, hdensity⟩ := h + refine ⟨W, T, y, hW, hU, hdensity.trans ?_⟩ + exact Finset.expect_le_expect fun X _ => hfg y X.val + +omit [FiniteDimensional F2 E] [FiniteDimensional F2 F] [Fintype Y] in +theorem isGoodPoint_of_witness {f : (E →ₗ[F2] F) → Option Y} {r : Nat} {ρ : ℝ} + {W : Submodule F2 E} {A : RowMap F r} {T : E →ₗ[F2] F} + (hgood : GoodRow f r ρ A (A.comp T)) + (X : MatrixSlice.Slice W (LinearMap.ker A) T) : IsGoodPoint f r ρ X.val := by + refine ⟨A, ?_⟩ + rw [RowAdvice.slice_row_eq W A T X] + exact hgood + +omit [FiniteDimensional F2 E] [Fintype Y] in +theorem dense_restriction_rowMap (f : (E →ₗ[F2] F) → Option Y) (r : Nat) (ρ : ℝ) + (y : Y) (W : Submodule F2 E) (C' : Submodule F2 F) (T : E →ₗ[F2] F) + (horder : order W C' ≤ r) + (hdensity : ρ < (𝔼 N, restrict (indicator f y) W C' T N)) : + ∃ A : RowMap F r, + Module.finrank F2 W ≤ r ∧ + ρ < (𝔼 X : MatrixSlice.Slice W (LinearMap.ker A) T, indicator f y X.val) := by + let hcodim := (MatrixSlice.row_count_le_order W C').trans horder + let A := RowAdvice.paddedRowMap r C' hcodim + have hker : LinearMap.ker A = C' := RowAdvice.ker_paddedRowMap r C' hcodim + refine ⟨A, (MatrixSlice.column_count_le_order W C').trans horder, ?_⟩ + rw [hker] + rwa [MatrixSlice.expect_restrict_eq_slice] at hdensity + +theorem goodMass_ge [Nontrivial F] + (r : Nat) (ρ η : ℝ) (hρ : 0 < ρ) (hρ1 : ρ < 1) + (hconstants : levelCutoffConstant r ρ + node (r + 1) < η / 2) + (f : (E →ₗ[F2] F) → Option Y) (hagreement : η ≤ nonzeroAgreement f) : + η / 4 ≤ goodMass f r ρ := by + by_contra hsmall + have hsmall' : goodMass f r ρ < η / 4 := lt_of_not_ge hsmall + let erased := erase f (IsGoodPoint f r ρ) + have herasure := nonzeroAgreement_erase f (IsGoodPoint f r ρ) + have hremaining : η / 2 ≤ nonzeroAgreement erased := by + change nonzeroAgreement f - 2 * goodMass f r ρ ≤ nonzeroAgreement erased at herasure + linarith + obtain ⟨y, W, C', T, horder, hdense⟩ := + exists_dense_slice_nonzero r ρ (η / 2) hρ hρ1 hconstants erased hremaining + obtain ⟨A, hW, hdense'⟩ := dense_restriction_rowMap erased r ρ y W C' T horder hdense + have hgoodErased : GoodRow erased r ρ A (A.comp T) := + ⟨W, T, y, hW, rfl, hdense'.le⟩ + have hgood : GoodRow f r ρ A (A.comp T) := + GoodRow.mono hgoodErased (indicator_erase_le f (IsGoodPoint f r ρ)) + have hzero : (𝔼 X : MatrixSlice.Slice W (LinearMap.ker A) T, + indicator erased y X.val) = 0 := by + apply Finset.expect_eq_zero + intro X _ + have hX : IsGoodPoint f r ρ X.val := isGoodPoint_of_witness hgood X + simp [indicator, erased, erase_eq_none_of f (IsGoodPoint f r ρ) hX] + rw [hzero] at hdense' + exact (not_lt_of_ge hρ.le) hdense' + +omit [FiniteDimensional F2 E] [FiniteDimensional F2 F] [Fintype Y] in +theorem goodMass_le_card_mul_adviceMass + (f : (E →ₗ[F2] F) → Option Y) (r : Nat) (ρ : ℝ) : + goodMass f r ρ ≤ (Fintype.card (RowMap F r) : ℝ) * adviceMass f r ρ := by + unfold goodMass uniformMass adviceMass + rw [Fintype.card_mul_expect, ← Finset.expect_sum_comm] + apply Finset.expect_le_expect + intro X _ + by_cases hX : IsGoodPoint f r ρ X + · rw [ite_eq_left hX] + obtain ⟨A, hA⟩ := hX + calc + (1 : ℝ) = (if GoodRow f r ρ A (A.comp X) then 1 else 0) := by rw [ite_eq_left hA] + _ ≤ ∑ B : RowMap F r, if GoodRow f r ρ B (B.comp X) then (1 : ℝ) else 0 := by + apply Finset.single_le_sum + (f := fun B : RowMap F r => + if GoodRow f r ρ B (B.comp X) then (1 : ℝ) else 0) + (s := Finset.univ) (a := A) + · intro B _ + split_ifs <;> norm_num + · exact Finset.mem_univ A + · rw [ite_eq_right hX] + apply Finset.sum_nonneg + intro A _ + split_ifs <;> norm_num + +theorem adviceMass_ge [Nontrivial F] + (r : Nat) (ρ η : ℝ) (hρ : 0 < ρ) (hρ1 : ρ < 1) + (hconstants : levelCutoffConstant r ρ + node (r + 1) < η / 2) + (f : (E →ₗ[F2] F) → Option Y) (hagreement : η ≤ nonzeroAgreement f) : + (η / 4) / (2 : ℝ) ^ (r * Module.finrank F2 F) ≤ adviceMass f r ρ := by + have hmass := (goodMass_ge r ρ η hρ hρ1 hconstants f hagreement).trans + (goodMass_le_card_mul_adviceMass f r ρ) + have hcard : (Fintype.card (RowMap F r) : ℝ) = + (2 : ℝ) ^ (r * Module.finrank F2 F) := by + exact_mod_cast RowAdvice.card_rowMaps (C := F) r + rw [hcard] at hmass + apply (div_le_iff₀ (pow_pos (by norm_num : (0 : ℝ) < 2) _)).mpr + simpa only [mul_comm] using hmass + +theorem exists_uniform_parameters {η : ℝ} (hη : 0 < η) : + ∃ r : Nat, 1 ≤ r ∧ ∃ ρ : ℝ, 0 < ρ ∧ ρ < 1 ∧ + ∀ (E F Y : Type*) + [AddCommGroup E] [Module F2 E] [AddCommGroup F] [Module F2 F] + [FiniteDimensional F2 E] [FiniteDimensional F2 F] + [Fintype E] [Fintype F] [Fintype Y] [Nontrivial F] + (f : (E →ₗ[F2] F) → Option Y), + η ≤ nonzeroAgreement f → + η / 4 ≤ goodMass f r ρ ∧ + (η / 4) / (2 : ℝ) ^ (r * Module.finrank F2 F) ≤ adviceMass f r ρ := by + obtain ⟨r, hr, ρ, hρ, hρ1, hconstants⟩ := + MatrixInverseConstants.exists_cutoff_density (show 0 < η / 2 by positivity) + refine ⟨r, hr, ρ, hρ, hρ1, ?_⟩ + intro E F Y _ _ _ _ _ _ _ _ _ _ f hagreement + exact ⟨goodMass_ge r ρ η hρ hρ1 hconstants f hagreement, + adviceMass_ge r ρ η hρ hρ1 hconstants f hagreement⟩ + +end +end PerfectCompleteness.ManyGoodRows + + + +namespace PerfectCompleteness.FamilyGoodRows + +noncomputable section + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Fourier.MatrixCharacters (F2) +open UniqueGamesTheorem.Fourier.MatrixLevelBridge +open UniqueGamesTheorem.Appendix.RankLevelFilter +open PerfectCompleteness.PartialTableInverse PerfectCompleteness.MatrixErasure +open PerfectCompleteness.ManyGoodRows + +attribute [local instance] linearMapFintype + +variable {P : Type*} [Fintype P] + +theorem expectation_le_threshold_add_probability (μ : FiniteDistribution P) + (g : P → ℝ) (η : ℝ) (hη : 0 ≤ η) (hg : ∀ p, g p ≤ 1) : + μ.expectation g ≤ η + μ.probability (fun p => decide (η ≤ g p)) := by + have hpoint : ∀ p, g p ≤ η + (if η ≤ g p then (1 : ℝ) else 0) := by + intro p + by_cases hp : η ≤ g p + · rw [ite_eq_left hp] + linarith [hg p] + · rw [ite_eq_right hp, add_zero] + exact (lt_of_not_ge hp).le + have hsum := Finset.sum_le_sum (fun p (_ : p ∈ (Finset.univ : Finset P)) => + mul_le_mul_of_nonneg_left (hpoint p) (μ.nonnegative p)) + simpa only [FiniteDistribution.expectation, FiniteDistribution.probability, + mul_add, Finset.sum_add_distrib, mul_ite, mul_one, mul_zero, + ← Finset.sum_mul, μ.normalized, one_mul, decide_eq_true_eq] using hsum + +theorem threshold_probability_ge (μ : FiniteDistribution P) (g : P → ℝ) + (η : ℝ) (hη : 0 ≤ η) (hg : ∀ p, g p ≤ 1) + (hmean : 2 * η ≤ μ.expectation g) : + η ≤ μ.probability (fun p => decide (η ≤ g p)) := by + have h := expectation_le_threshold_add_probability μ g η hη hg + linarith + +theorem probability_mul_le_expectation (μ : FiniteDistribution P) + (S : P → Prop) (g : P → ℝ) (c : ℝ) + (hnonneg : ∀ p, 0 ≤ g p) (hgood : ∀ p, S p → c ≤ g p) : + μ.probability (fun p => decide (S p)) * c ≤ μ.expectation g := by + calc + _ = μ.expectation (fun p => if S p then c else 0) := by + simp only [FiniteDistribution.probability, FiniteDistribution.expectation, + decide_eq_true_eq, Finset.sum_mul, ite_mul, mul_ite, zero_mul, mul_zero] + _ ≤ μ.expectation g := by + apply Finset.sum_le_sum + intro p _ + apply mul_le_mul_of_nonneg_left _ (μ.nonnegative p) + by_cases hp : S p + · simpa only [ite_eq_left hp] using hgood p hp + · simpa only [ite_eq_right hp] using hnonneg p + +section TableBounds + +variable {E F Y : Type*} + [AddCommGroup E] [Module F2 E] [AddCommGroup F] [Module F2 F] + [FiniteDimensional F2 E] [FiniteDimensional F2 F] + [Fintype E] [Fintype F] [Fintype Y] + +omit [FiniteDimensional F2 E] [FiniteDimensional F2 F] [Fintype Y] in +theorem nonzeroAgreement_le_one [Nontrivial F] + (f : (E →ₗ[F2] F) → Option Y) : nonzeroAgreement f ≤ 1 := by + obtain ⟨a, ha⟩ := exists_ne (0 : F) + let : Nonempty {a : F // a ≠ 0} := ⟨⟨a, ha⟩⟩ + unfold nonzeroAgreement stepAgreement + apply Finset.expect_le Finset.univ_nonempty + intro a _ + apply Finset.expect_le Finset.univ_nonempty + intro X _ + apply Finset.expect_le Finset.univ_nonempty + intro h _ + exact definedEquality_le_one f X (X + h.smulRight a.val) + +omit [FiniteDimensional F2 E] [FiniteDimensional F2 F] [Fintype Y] in +theorem adviceMass_nonneg (f : (E →ₗ[F2] F) → Option Y) (r : Nat) (ρ : ℝ) : + 0 ≤ adviceMass f r ρ := by + unfold adviceMass + apply Finset.expect_nonneg + intro A _ + apply Finset.expect_nonneg + intro X _ + split_ifs <;> norm_num + +end TableBounds + + +variable {E Y : P → Type*} {F : Type*} + [AddCommGroup F] [Module F2 F] [FiniteDimensional F2 F] [Fintype F] [Nontrivial F] + [∀ p, AddCommGroup (E p)] [∀ p, Module F2 (E p)] + [∀ p, FiniteDimensional F2 (E p)] [∀ p, Fintype (E p)] [∀ p, Fintype (Y p)] + +theorem mean_adviceMass_ge (μ : FiniteDistribution P) + (f : (p : P) → (E p →ₗ[F2] F) → Option (Y p)) + (r : Nat) (ρ η : ℝ) (hη : 0 < η) (hρ : 0 < ρ) (hρ1 : ρ < 1) + (hconstants : levelCutoffConstant r ρ + node (r + 1) < η / 2) + (hmean : 2 * η ≤ μ.expectation (fun p => nonzeroAgreement (f p))) : + (η ^ 2 / 4) / (2 : ℝ) ^ (r * Module.finrank F2 F) ≤ + μ.expectation (fun p => adviceMass (f p) r ρ) := by + let c : ℝ := (η / 4) / (2 : ℝ) ^ (r * Module.finrank F2 F) + have hc : 0 ≤ c := by + exact div_nonneg (div_nonneg hη.le (by norm_num)) (by positivity) + have hmass : η ≤ μ.probability (fun p => decide (η ≤ nonzeroAgreement (f p))) := + threshold_probability_ge μ (fun p => nonzeroAgreement (f p)) η hη.le + (fun p => nonzeroAgreement_le_one (f p)) hmean + have hweighted : + μ.probability (fun p => decide (η ≤ nonzeroAgreement (f p))) * c ≤ + μ.expectation (fun p => adviceMass (f p) r ρ) := by + apply probability_mul_le_expectation μ + (fun p => η ≤ nonzeroAgreement (f p)) (fun p => adviceMass (f p) r ρ) c + · intro p + exact adviceMass_nonneg (f p) r ρ + · intro p hp + exact ManyGoodRows.adviceMass_ge r ρ η hρ hρ1 hconstants (f p) hp + calc + (η ^ 2 / 4) / (2 : ℝ) ^ (r * Module.finrank F2 F) = η * c := by + dsimp [c] + ring + _ ≤ μ.probability (fun p => decide (η ≤ nonzeroAgreement (f p))) * c := + mul_le_mul_of_nonneg_right hmass hc + _ ≤ μ.expectation (fun p => adviceMass (f p) r ρ) := hweighted + +end +end PerfectCompleteness.FamilyGoodRows + + + +namespace PerfectCompleteness.ProductEvaluation + +open MixedSupport CanonicalKeys + +abbrev F2 := ZMod 2 + +variable {X C Z : Type*} {Row : C → Type*} + +inductive Generator (C : Type*) (Row : C → Type*) where + | one + | product (descendant : C) (first second : Row descendant) + +def displayedJoint (rows : (c : C) → Row c → X → F2) (other : X → Z) (x : X) : + ((c : C) → Row c → F2) × Z := + ((fun c u => rows c u x), other x) + +def generatorValue (values : (c : C) → Row c → F2) : Generator C Row → F2 + | .one => 1 + | .product c u v => values c u * values c v + +def generator (H : Submodule F2 (X → F2)) (rows : (c : C) → Row c → X → F2) + (hone : (1 : X → F2) ∈ H) + (hproducts : ∀ c u v, rows c u * rows c v ∈ H) : Generator C Row → H + | .one => ⟨1, hone⟩ + | .product c u v => ⟨rows c u * rows c v, hproducts c u v⟩ + +def productSpan (H : Submodule F2 (X → F2)) (rows : (c : C) → Row c → X → F2) + (hone : (1 : X → F2) ∈ H) + (hproducts : ∀ c u v, rows c u * rows c v ∈ H) : Submodule F2 H := + Submodule.span F2 (Set.range (generator H rows hone hproducts)) + +def spanGenerator (H : Submodule F2 (X → F2)) (rows : (c : C) → Row c → X → F2) + (hone : (1 : X → F2) ∈ H) + (hproducts : ∀ c u v, rows c u * rows c v ∈ H) (g : Generator C Row) : + productSpan H rows hone hproducts := + ⟨generator H rows hone hproducts g, Submodule.subset_span ⟨g, rfl⟩⟩ + +theorem functional_ext (H : Submodule F2 (X → F2)) + (rows : (c : C) → Row c → X → F2) (hone : (1 : X → F2) ∈ H) + (hproducts : ∀ c u v, rows c u * rows c v ∈ H) + (b b' : Module.Dual F2 (productSpan H rows hone hproducts)) + (h : ∀ g, b (spanGenerator H rows hone hproducts g) = + b' (spanGenerator H rows hone hproducts g)) : b = b' := by + apply (Submodule.linearMap_eq_iff_of_eq_span b b' + (show productSpan H rows hone hproducts = + Submodule.span F2 (Set.range (generator H rows hone hproducts)) from rfl)).2 + rintro ⟨u, ⟨g, rfl⟩⟩ + exact h g + + +variable {n : Nat} +variable (slots : Fin n → Slot) +variable (H : Submodule F2 (Assignment slots → F2)) +variable (rows : (c : C) → Row c → Assignment slots → F2) +variable (other : Assignment slots → Z) +variable (hone : (1 : Assignment slots → F2) ∈ H) +variable (hproducts : ∀ c u v, rows c u * rows c v ∈ H) + +noncomputable def realizingPoint (P : Label slots (displayedJoint rows other)) : + Assignment slots := + ReducedPartition.representative (reduction slots (displayedJoint rows other)) + (displayedJoint rows other) P + +theorem realizingPoint_joint (P : Label slots (displayedJoint rows other)) : + displayedJoint rows other (realizingPoint slots rows other P) = + restore slots (displayedJoint rows other) P := rfl + +noncomputable def restoredRows (P : Label slots (displayedJoint rows other)) : + (c : C) → Row c → F2 := + (restore slots (displayedJoint rows other) P).1 + +@[simp] theorem restoredRows_apply (P : Label slots (displayedJoint rows other)) + (c : C) (u : Row c) : + restoredRows slots rows other P c u = rows c u (realizingPoint slots rows other P) := rfl + +noncomputable def labelExtension (P : Label slots (displayedJoint rows other)) : + Module.Dual F2 H := + EvaluationMatrix.evaluation H (realizingPoint slots rows other P) + +noncomputable def labelFunctional (P : Label slots (displayedJoint rows other)) : + Module.Dual F2 (productSpan H rows hone hproducts) := + (labelExtension slots H rows other P).comp (productSpan H rows hone hproducts).subtype + +theorem labelFunctional_generators (P : Label slots (displayedJoint rows other)) + (g : Generator C Row) : + labelFunctional slots H rows other hone hproducts P (spanGenerator H rows hone hproducts g) = + generatorValue (restoredRows slots rows other P) g := by + cases g <;> rfl + +theorem labelFunctional_unique (P : Label slots (displayedJoint rows other)) + (b : Module.Dual F2 (productSpan H rows hone hproducts)) + (h : ∀ g, b (spanGenerator H rows hone hproducts g) = + generatorValue (restoredRows slots rows other P) g) : + b = labelFunctional slots H rows other hone hproducts P := by + apply functional_ext H rows hone hproducts + intro g + exact (h g).trans (labelFunctional_generators slots H rows other hone hproducts P g).symm + +theorem exists_unique_labelFunctional (P : Label slots (displayedJoint rows other)) : + ∃! b : Module.Dual F2 (productSpan H rows hone hproducts), + ∀ g, b (spanGenerator H rows hone hproducts g) = + generatorValue (restoredRows slots rows other P) g := by + refine ⟨labelFunctional slots H rows other hone hproducts P, + labelFunctional_generators slots H rows other hone hproducts P, ?_⟩ + intro b hb + exact labelFunctional_unique slots H rows other hone hproducts P b hb + +theorem labelFunctional_eq_of_restoredRows_eq + (P Q : Label slots (displayedJoint rows other)) + (h : restoredRows slots rows other P = restoredRows slots rows other Q) : + labelFunctional slots H rows other hone hproducts P = + labelFunctional slots H rows other hone hproducts Q := by + apply functional_ext H rows hone hproducts + intro g + rw [labelFunctional_generators, labelFunctional_generators, h] + +theorem labelExtension_restrict (P : Label slots (displayedJoint rows other)) : + (labelExtension slots H rows other P).comp (productSpan H rows hone hproducts).subtype = + labelFunctional slots H rows other hone hproducts P := rfl + +theorem exists_labelExtension (P : Label slots (displayedJoint rows other)) : + ∃ z : Module.Dual F2 H, + z.comp (productSpan H rows hone hproducts).subtype = + labelFunctional slots H rows other hone hproducts P := + ⟨labelExtension slots H rows other P, rfl⟩ + +theorem extension_generators (P : Label slots (displayedJoint rows other)) + (z : Module.Dual F2 H) + (hz : z.comp (productSpan H rows hone hproducts).subtype = + labelFunctional slots H rows other hone hproducts P) (g : Generator C Row) : + z (generator H rows hone hproducts g) = + generatorValue (restoredRows slots rows other P) g := by + have h := congrArg (fun b : Module.Dual F2 (productSpan H rows hone hproducts) => + b (spanGenerator H rows hone hproducts g)) hz + exact h.trans (labelFunctional_generators slots H rows other hone hproducts P g) + +theorem extension_one (P : Label slots (displayedJoint rows other)) + (z : Module.Dual F2 H) + (hz : z.comp (productSpan H rows hone hproducts).subtype = + labelFunctional slots H rows other hone hproducts P) : z ⟨1, hone⟩ = 1 := + extension_generators slots H rows other hone hproducts P z hz .one + +theorem extension_products (P : Label slots (displayedJoint rows other)) + (z : Module.Dual F2 H) + (hz : z.comp (productSpan H rows hone hproducts).subtype = + labelFunctional slots H rows other hone hproducts P) (c : C) (u v : Row c) : + z ⟨rows c u * rows c v, hproducts c u v⟩ = + restoredRows slots rows other P c u * restoredRows slots rows other P c v := + extension_generators slots H rows other hone hproducts P z hz (.product c u v) + +theorem extension_productMatrix (P : Label slots (displayedJoint rows other)) + (z : Module.Dual F2 H) + (hz : z.comp (productSpan H rows hone hproducts).subtype = + labelFunctional slots H rows other hone hproducts P) (c : C) : + (fun u v : Row c => z ⟨rows c u * rows c v, hproducts c u v⟩) = + (fun u v : Row c => + restoredRows slots rows other P c u * restoredRows slots rows other P c v) := by + funext u v + exact extension_products slots H rows other hone hproducts P z hz c u v + +end PerfectCompleteness.ProductEvaluation + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/MultiplicationFormInjectiveLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/MultiplicationFormInjectiveLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..78d5c11ab81af5cce18e5cb774bd91d547683cc4 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/MultiplicationFormInjectiveLemmas.lean @@ -0,0 +1,563 @@ +import OAI.Computability.PerfectCompleteness.Algebra.BilinearWitnessLemmas +import OAI.Computability.PerfectCompleteness.Decoding.CollisionAveragingLemmas +import OAI.Computability.PerfectCompleteness.Decoding.DecoderTableCoupling +import OAI.Computability.PerfectCompleteness.Decoding.TwoResponseCollisionLemmas +import OAI.Computability.PerfectCompleteness.Foundations.CoordinateReplacementLemmas +import OAI.Computability.PerfectCompleteness.Foundations.DependentPredictionDifferenceLemmas +import OAI.Computability.PerfectCompleteness.Foundations.OddListExtraction +import OAI.Computability.PerfectCompleteness.Reduction.CompletionSoundness +import OAI.Computability.UniqueGames.Foundations.SamplingLemmas + +namespace OAI + + +namespace PerfectCompleteness.MultiplicationFormInjective + +noncomputable section + +open scoped Classical +open PointwiseSpaces OddListExtraction +open UniqueGamesTheorem.Foundations.Games + +variable {X : Type*} (H : Submodule F2 (X → F2)) + +theorem multiplicationForm_injective : + Function.Injective (multiplicationForm H) := by + intro z z' h + apply (Submodule.linearMap_eq_iff_of_eq_span z z' + (show squareSpace H = + Submodule.span F2 {u | ∃ f ∈ H, ∃ g ∈ H, f * g = u} from rfl)).2 + rintro ⟨u, f, hf, g, hg, rfl⟩ + exact congrArg (fun F : H →ₗ[F2] H →ₗ[F2] F2 => F ⟨f, hf⟩ ⟨g, hg⟩) h + +@[simp] theorem multiplicationForm_eq_iff + (z z' : Module.Dual F2 (squareSpace H)) : + multiplicationForm H z = multiplicationForm H z' ↔ z = z' := + (multiplicationForm_injective H).eq_iff + +theorem optionMap_injective : + Function.Injective (Option.map (multiplicationForm H)) := + Option.map_injective (multiplicationForm_injective H) + +theorem definedEqual_map_of_injective {A B : Type*} (f : A → B) + (hf : Function.Injective f) (a b : Option A) : + DecoderTableCoupling.definedEqual (a.map f) (b.map f) = + DecoderTableCoupling.definedEqual a b := by + cases a <;> cases b <;> + simp [DecoderTableCoupling.definedEqual, hf.eq_iff] + +@[simp] theorem definedEqual_map + (a b : Option (Module.Dual F2 (squareSpace H))) : + DecoderTableCoupling.definedEqual (a.map (multiplicationForm H)) + (b.map (multiplicationForm H)) = + DecoderTableCoupling.definedEqual a b := + definedEqual_map_of_injective _ (multiplicationForm_injective H) a b + +@[simp] theorem fullCollision_map + (a b : Option (Module.Dual F2 (squareSpace H))) : + BilinearCollisionTransfer.fullCollision (a.map (multiplicationForm H)) + (b.map (multiplicationForm H)) = + DecoderTableCoupling.definedEqual a b := + definedEqual_map H a b + +@[simp] theorem collision_map {Ω : Type*} + (answers : Ω → Option (Module.Dual F2 (squareSpace H))) (p : Ω × Ω) : + TwoResponseCollision.collision (fun x => (answers x).map (multiplicationForm H)) p = + TwoResponseCollision.collision answers p := + definedEqual_map H (answers p.1) (answers p.2) + +theorem fullCollision_probability {Ω : Type*} [Fintype Ω] + (μ : FiniteDistribution Ω) + (first second : Ω → Option (Module.Dual F2 (squareSpace H))) : + μ.probability (fun x => BilinearCollisionTransfer.fullCollision + ((first x).map (multiplicationForm H)) + ((second x).map (multiplicationForm H))) = + μ.probability (fun x => DecoderTableCoupling.definedEqual (first x) (second x)) := by + apply congrArg μ.probability + funext x + exact fullCollision_map H (first x) (second x) + +theorem collision_probability {Ω : Type*} [Fintype Ω] + (μ : FiniteDistribution (Ω × Ω)) + (answers : Ω → Option (Module.Dual F2 (squareSpace H))) : + μ.probability (TwoResponseCollision.collision + (fun x => (answers x).map (multiplicationForm H))) = + μ.probability (TwoResponseCollision.collision answers) := by + apply congrArg μ.probability + funext p + exact collision_map H answers p + +end +end PerfectCompleteness.MultiplicationFormInjective + + +namespace PerfectCompleteness.SingleResponseResampling + +noncomputable section + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games + +variable {B : Type*} [Fintype B] + {Ω Y : B → Type*} [∀ b, Fintype (Ω b)] [∀ b, Fintype (Y b)] + +def originalLaw (μ : FiniteDistribution B) + (ν : (b : B) → FiniteDistribution (Ω b)) := + CompletionSoundness.sigmaLaw μ ν + +def resampledLaw (μ : FiniteDistribution B) + (ν : (b : B) → FiniteDistribution (Ω b)) := + CompletionSoundness.sigmaLaw μ (fun b => (ν b).product (ν b)) + +theorem probability_rectangle {A C : Type*} [Fintype A] [Fintype C] + (μ : FiniteDistribution A) (ν : FiniteDistribution C) + (p : A → Bool) (q : C → Bool) : + (μ.product ν).probability (fun x => p x.1 && q x.2) = + μ.probability p * ν.probability q := by + unfold FiniteDistribution.probability + rw [Fintype.sum_prod_type, Finset.sum_mul_sum] + apply Finset.sum_congr rfl + intro a _ + apply Finset.sum_congr rfl + intro c _ + cases hp : p a <;> cases hq : q c <;> simp [FiniteDistribution.product, hp, hq] + +theorem local_square_bound {A C : Type*} [Fintype A] [Fintype C] + (ν : FiniteDistribution A) (f : A → Option C) (right : C) : + ν.probability (fun x => decide (f x = some right)) ^ 2 ≤ + (ν.product ν).probability (TwoResponseCollision.collision f) := by + rw [pow_two, ← probability_rectangle] + apply FiniteDistribution.probability_mono + intro x hx + obtain ⟨hx₁, hx₂⟩ := Bool.and_eq_true_iff.mp hx + exact decide_eq_true ⟨right, of_decide_eq_true hx₁, of_decide_eq_true hx₂⟩ + +theorem success_square_le_collision (μ : FiniteDistribution B) + (ν : (b : B) → FiniteDistribution (Ω b)) + (f : (b : B) → Ω b → Option (Y b)) (right : (b : B) → Y b) : + (originalLaw μ ν).probability + (fun x => decide (f x.1 x.2 = some (right x.1))) ^ 2 ≤ + (resampledLaw μ ν).probability + (fun x => TwoResponseCollision.collision (f x.1) x.2) := by + unfold originalLaw resampledLaw + rw [CompletionSoundness.sigmaLaw_probability, + CompletionSoundness.sigmaLaw_probability] + apply (CollisionAveraging.mean_square_le μ _).trans + apply Finset.sum_le_sum + intro b _ + exact mul_le_mul_of_nonneg_left (local_square_bound (ν b) (f b) (right b)) + (μ.nonnegative b) + +theorem success_square_le_event (μ : FiniteDistribution B) + (ν : (b : B) → FiniteDistribution (Ω b)) + (f : (b : B) → Ω b → Option (Y b)) (right : (b : B) → Y b) + (event : (Σ b, Ω b × Ω b) → Bool) + (contains : ∀ b x y z, f b x = some z → f b y = some z → + event ⟨b, x, y⟩ = true) : + (originalLaw μ ν).probability + (fun x => decide (f x.1 x.2 = some (right x.1))) ^ 2 ≤ + (resampledLaw μ ν).probability event := by + apply (success_square_le_collision μ ν f right).trans + apply FiniteDistribution.probability_mono + intro x hx + obtain ⟨z, hz₁, hz₂⟩ := of_decide_eq_true hx + exact contains x.1 x.2.1 x.2.2 z hz₁ hz₂ + +end +end PerfectCompleteness.SingleResponseResampling + + +namespace PerfectCompleteness.SparseReplacement + +open scoped BigOperators +open UniqueGamesTheorem.Foundations.Games +open CoordinateReplacement + +noncomputable section + +variable {I : Type*} [Fintype I] [DecidableEq I] + {Ω : I → Type*} [∀ i, Fintype (Ω i)] + +def row (P Q : (i : I) → FiniteDistribution (Ω i)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) (i : I) : + FiniteDistribution (Ω i) := + (ProjectionPosterior.bernoulli β hβ hβ').mixture + (fun marked => if marked then Q i else P i) + +omit [Fintype I] [DecidableEq I] in +theorem row_weight (P Q : (i : I) → FiniteDistribution (Ω i)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) (i : I) (a : Ω i) : + (row P Q β hβ hβ' i).weight a = + (1 - β) * (P i).weight a + β * (Q i).weight a := by + simp [row, FiniteDistribution.mixture, ProjectionPosterior.bernoulli, + add_comm] + +def law (P Q : (i : I) → FiniteDistribution (Ω i)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) : + FiniteDistribution ((i : I) → Ω i) := + FiniteProduct.law (row P Q β hβ hβ') + +def markedLaw (P Q : (i : I) → FiniteDistribution (Ω i)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) : + FiniteDistribution ((I → Bool) × ((i : I) → Ω i)) := + CleanConditioning.kernelJoint + (FiniteProduct.law fun _ : I => ProjectionPosterior.bernoulli β hβ hβ') + (fun mask => FiniteProduct.law fun i => if mask i then Q i else P i) + +theorem markedLaw_marginal (P Q : (i : I) → FiniteDistribution (Ω i)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) : + (markedLaw P Q β hβ hβ').pushforward Prod.snd = law P Q β hβ hβ' := by + classical + apply FiniteDistribution.eq_of_weight_eq + intro x + have hsum : ((markedLaw P Q β hβ hβ').pushforward Prod.snd).weight x = + ∑ mask : I → Bool, + (∏ i, (ProjectionPosterior.bernoulli β hβ hβ').weight (mask i)) * + (∏ i, (if mask i then Q i else P i).weight (x i)) := by + simp [markedLaw, FiniteDistribution.pushforward, CleanConditioning.kernelJoint, + Fintype.sum_prod_type, FiniteProduct.law] + rw [hsum] + change (∑ mask : I → Bool, + (∏ i, (ProjectionPosterior.bernoulli β hβ hβ').weight (mask i)) * + (∏ i, (if mask i then Q i else P i).weight (x i))) = + ∏ i, ∑ b : Bool, (ProjectionPosterior.bernoulli β hβ hβ').weight b * + (if b then Q i else P i).weight (x i) + simp only [← Finset.prod_mul_distrib] + exact (Fintype.prod_sum (fun i b => + (ProjectionPosterior.bernoulli β hβ hβ').weight b * + (if b then Q i else P i).weight (x i))).symm + +omit [Fintype I] [DecidableEq I] in + +theorem ratio_reweight_eq (P Q : (i : I) → FiniteDistribution (Ω i)) + (support : ∀ i a, (P i).weight a = 0 → (Q i).weight a = 0) (i : I) : + DensityVariation.reweight (P i) (ratio P Q i) (ratio_nonnegative P Q i) + (ratio_mean_one_of_support P Q support i) = Q i := by + apply FiniteDistribution.eq_of_weight_eq + exact weight_mul_ratio_of_support P Q support i + +theorem projectedLaw_eq (P Q : (i : I) → FiniteDistribution (Ω i)) + (support : ∀ i a, (P i).weight a = 0 → (Q i).weight a = 0) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) : + SparseProjection.projectedLaw P (ratio P Q) (ratio_nonnegative P Q) + (ratio_mean_one_of_support P Q support) β hβ hβ' = law P Q β hβ hβ' := by + apply FiniteDistribution.eq_of_weight_eq + intro x + change (∏ i, (P i).weight (x i) * + SparseProjection.localDensity β (ratio P Q) i (x i)) = + ∏ i, (row P Q β hβ hβ' i).weight (x i) + apply Finset.prod_congr rfl + intro i _ + rw [row_weight] + unfold SparseProjection.localDensity + calc + _ = (1 - β) * (P i).weight (x i) + + β * ((P i).weight (x i) * ratio P Q i (x i)) := by ring + _ = _ := by rw [weight_mul_ratio_of_support P Q support] + +theorem forward_eq (P Q : (i : I) → FiniteDistribution (Ω i)) + (support : ∀ i a, (P i).weight a = 0 → (Q i).weight a = 0) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β < 1) : + ProjectionPosterior.forward P (ratio P Q) (ratio_nonnegative P Q) + (ratio_mean_one_of_support P Q support) β hβ hβ' = + markedLaw P Q β hβ hβ'.le := by + unfold ProjectionPosterior.forward markedLaw + simp only [ratio_reweight_eq P Q support] + +theorem markedLaw_posterior_weight (P Q : (i : I) → FiniteDistribution (Ω i)) + (support : ∀ i a, (P i).weight a = 0 → (Q i).weight a = 0) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β < 1) + (mask : I → Bool) (x : (i : I) → Ω i) : + (markedLaw P Q β hβ hβ'.le).weight (mask, x) = + (law P Q β hβ hβ'.le).weight x * + (ProjectionPosterior.posteriorMask β hβ hβ' (ratio P Q) + (ratio_nonnegative P Q) x).weight mask := by + rw [← forward_eq P Q support β hβ hβ'] + rw [ProjectionPosterior.forward_reverse_weight] + change (SparseProjection.projectedLaw P (ratio P Q) (ratio_nonnegative P Q) + (ratio_mean_one_of_support P Q support) β hβ hβ'.le).weight x * _ = _ + rw [projectedLaw_eq P Q support β hβ hβ'.le] + +theorem observed_variation {Γ : Type*} [Fintype Γ] + (P Q : (i : I) → FiniteDistribution (Ω i)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) (B : ℝ) (hB : 0 ≤ B) + (domination : ∀ i a, (Q i).weight a ≤ B * (P i).weight a) + (observe : ((i : I) → Ω i) → Γ) : + ((law P Q β hβ hβ').pushforward observe).totalVariation + ((FiniteProduct.law P).pushforward observe) ≤ + Real.sqrt ((1 + β ^ 2 * (B - 1)) ^ Fintype.card I - 1) / 2 := by + rw [← projectedLaw_eq P Q (support_of_domination P Q B domination) β hβ hβ'] + exact SparseProjection.observed_variation P (ratio P Q) (ratio_nonnegative P Q) + (ratio_mean_one_of_support P Q (support_of_domination P Q B domination)) + β hβ hβ' (B - 1) (ratio_second_moment_le P Q B hB domination) observe + +theorem adaptive_selection (P Q : (i : I) → FiniteDistribution (Ω i)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β < 1) (B : ℝ) (hB : 0 ≤ B) + (domination : ∀ i a, (Q i).weight a ≤ B * (P i).weight a) + (select : ((i : I) → Ω i) → Finset I) (m : Nat) + (size : ∀ x, (select x).card ≤ m) : + (markedLaw P Q β hβ hβ'.le).probability + (fun z => decide (∃ i ∈ select z.2, z.1 i = true)) ≤ + m * (β * B / (1 - β)) := by + rw [← forward_eq P Q (support_of_domination P Q B domination) β hβ hβ'] + exact AdaptiveProjection.adaptive_selection P (ratio P Q) (ratio_nonnegative P Q) + (ratio_mean_one_of_support P Q (support_of_domination P Q B domination)) + β hβ hβ' B hB (fun i a => (ratio_bounds_of_domination P Q B hB domination i a).2) + select m size + + +variable [Nonempty I] [∀ i, Nonempty (Ω i)] + +theorem observed_uniform_variation {Γ : Type*} [Fintype Γ] + (Q : (i : I) → FiniteDistribution (Ω i)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) (B : ℝ) + (cardinality : ∀ i, (Fintype.card (Ω i) : ℝ) ≤ B) + (observe : ((i : I) → Ω i) → Γ) : + ((law (fun i => FiniteDistribution.uniform (Ω i)) Q β hβ hβ').pushforward + observe).totalVariation + ((FiniteProduct.law (fun i => FiniteDistribution.uniform (Ω i))).pushforward + observe) ≤ + Real.sqrt ((1 + β ^ 2 * (B - 1)) ^ Fintype.card I - 1) / 2 := by + have hB : 0 ≤ B := by + obtain ⟨i⟩ := ‹Nonempty I› + exact (Nat.cast_nonneg (Fintype.card (Ω i))).trans (cardinality i) + exact observed_variation (fun i => FiniteDistribution.uniform (Ω i)) Q β hβ hβ' + B hB (uniform_domination Q B cardinality) observe + +theorem adaptive_uniform_selection (Q : (i : I) → FiniteDistribution (Ω i)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β < 1) (B : ℝ) + (cardinality : ∀ i, (Fintype.card (Ω i) : ℝ) ≤ B) + (select : ((i : I) → Ω i) → Finset I) (m : Nat) + (size : ∀ x, (select x).card ≤ m) : + (markedLaw (fun i => FiniteDistribution.uniform (Ω i)) Q β hβ hβ'.le).probability + (fun z => decide (∃ i ∈ select z.2, z.1 i = true)) ≤ + m * (β * B / (1 - β)) := by + have hB : 0 ≤ B := by + obtain ⟨i⟩ := ‹Nonempty I› + exact (Nat.cast_nonneg (Fintype.card (Ω i))).trans (cardinality i) + exact adaptive_selection (fun i => FiniteDistribution.uniform (Ω i)) Q β hβ hβ' + B hB (uniform_domination Q B cardinality) select m size + + +end +end PerfectCompleteness.SparseReplacement + + +namespace PerfectCompleteness.MarkedKernelProduct + +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +noncomputable section + +theorem physical_marked {B Y : Type*} {X : B → Type*} + [Fintype B] [Fintype Y] [∀ b, Fintype (X b)] + (μ : FiniteDistribution B) (P : (b : B) → FiniteDistribution (X b)) + (f : (b : B) → X b → Y) : + (μ.mixture (fun b => (P b).pushforward + (fun x => (⟨b, x⟩ : Σ b, X b)))).pushforward + (fun x => (x.1, f x.1 x.2)) = + CleanConditioning.kernelJoint μ (fun b => (P b).pushforward (f b)) := by + apply SigmaObservation.eq_of_probability_eq + intro event + rw [FiniteDistribution.probability_pushforward, FiniteDistribution.probability_mixture, + CleanConditioning.probability_kernelJoint] + simp only [FiniteDistribution.probability_pushforward] + +def markEquiv {I : Type*} {Ω : I → Type*} : + ((i : I) → Bool × Ω i) ≃ (I → Bool) × ((i : I) → Ω i) where + toFun x := (fun i => (x i).1, fun i => (x i).2) + invFun x i := (x.1 i, x.2 i) + left_inv _ := rfl + right_inv _ := rfl + +variable {I : Type*} [Fintype I] [DecidableEq I] + {Ω : I → Type*} [∀ i, Fintype (Ω i)] + +theorem marked_product (P Q : (i : I) → FiniteDistribution (Ω i)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) : + (FiniteProduct.law (fun i => CleanConditioning.kernelJoint + (ProjectionPosterior.bernoulli β hβ hβ') + (fun b => if b then Q i else P i))).pushforward (markEquiv (Ω := Ω)) = + SparseReplacement.markedLaw P Q β hβ hβ' := by + rw [FiniteDistribution.pushforward_equiv] + apply FiniteDistribution.eq_of_weight_eq + rintro ⟨mask, x⟩ + change (∏ i, (ProjectionPosterior.bernoulli β hβ hβ').weight (mask i) * + (if mask i then Q i else P i).weight (x i)) = + (∏ i, (ProjectionPosterior.bernoulli β hβ hβ').weight (mask i)) * + ∏ i, (if mask i then Q i else P i).weight (x i) + rw [Finset.prod_mul_distrib] + +variable {Z : I → Type*} [∀ i, Fintype (Z i)] + +theorem law_mixture (ρ : (i : I) → FiniteDistribution (Z i)) + (Q : (i : I) → Z i → FiniteDistribution (Ω i)) : + FiniteProduct.law (fun i => (ρ i).mixture (Q i)) = + (FiniteProduct.law ρ).mixture + (fun z => FiniteProduct.law (fun i => Q i (z i))) := by + apply FiniteDistribution.eq_of_weight_eq + intro x + change (∏ i, (ρ i).expectation (fun z => (Q i z).weight (x i))) = + (FiniteProduct.law ρ).expectation (fun z => ∏ i, (Q i (z i)).weight (x i)) + exact (FiniteProduct.expectation_product ρ (fun i z => (Q i z).weight (x i))).symm + +theorem mixture_markedLaw (P : (i : I) → FiniteDistribution (Ω i)) + (ρ : (i : I) → FiniteDistribution (Z i)) + (Q : (i : I) → Z i → FiniteDistribution (Ω i)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) : + (FiniteProduct.law ρ).mixture + (fun z => SparseReplacement.markedLaw P (fun i => Q i (z i)) β hβ hβ') = + SparseReplacement.markedLaw P (fun i => (ρ i).mixture (Q i)) β hβ hβ' := by + apply FiniteDistribution.eq_of_weight_eq + rintro ⟨mask, x⟩ + let B : ℝ := ∏ i, (ProjectionPosterior.bernoulli β hβ hβ').weight (mask i) + change (∑ z, (FiniteProduct.law ρ).weight z * + (B * ∏ i, (if mask i then Q i (z i) else P i).weight (x i))) = + B * ∏ i, (if mask i then (ρ i).mixture (Q i) else P i).weight (x i) + calc + _ = B * (FiniteProduct.law ρ).expectation + (fun z => ∏ i, (if mask i then Q i (z i) else P i).weight (x i)) := by + rw [FiniteDistribution.expectation, Finset.mul_sum] + apply Finset.sum_congr rfl + intro z _ + exact mul_left_comm _ _ _ + _ = B * ∏ i, (ρ i).expectation + (fun z => (if mask i then Q i z else P i).weight (x i)) := + congrArg (fun a : ℝ => B * a) + (FiniteProduct.expectation_product ρ + (fun i z => (if mask i then Q i z else P i).weight (x i))) + _ = _ := by + apply congrArg (fun a : ℝ => B * a) + apply Finset.prod_congr rfl + intro i _ + cases mask i with + | false => + exact SmallBias.expectation_const (ρ i) ((P i).weight (x i)) + | true => rfl + +end +end PerfectCompleteness.MarkedKernelProduct + + +namespace PerfectCompleteness.StochasticSingleResponse + +noncomputable section + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games + +section FixedFiber + +variable {Q A Ω : Type*} [Fintype Q] [DecidableEq Q] [Fintype A] [Fintype Ω] + +def hit (responses : Q → FiniteDistribution (Option A)) (ν : FiniteDistribution Ω) + (ownInput : Ω → Q) (right : A) : ℝ := + ν.expectation (fun x => (responses (ownInput x)).probability + (fun answer => decide (answer = some right))) + +def tableHit (ν : FiniteDistribution Ω) (ownInput : Ω → Q) (right : A) + (answers : Q → Option A) : ℝ := + ν.probability (fun x => decide (answers (ownInput x) = some right)) + +def tableCollision (ν : FiniteDistribution Ω) (ownInput : Ω → Q) + (answers : Q → Option A) : ℝ := + (ν.product ν).probability (TwoResponseCollision.collision (fun x => answers (ownInput x))) + +theorem hit_eq_table_mean (responses : Q → FiniteDistribution (Option A)) + (ν : FiniteDistribution Ω) (ownInput : Ω → Q) (right : A) : + hit responses ν ownInput right = + (FiniteDistribution.table responses).expectation (tableHit ν ownInput right) := by + symm + calc + _ = (FiniteDistribution.table responses).expectation (fun answers => + ν.expectation (fun x => if answers (ownInput x) = some right then 1 else 0)) := by + apply FiniteDistribution.expectation_congr + intro answers + simp only [tableHit, FiniteDistribution.probability, FiniteDistribution.expectation, + decide_eq_true_eq, mul_ite, mul_one, mul_zero] + _ = ν.expectation (fun x => (FiniteDistribution.table responses).expectation + (fun answers => if answers (ownInput x) = some right then 1 else 0)) := + FiniteDistribution.expectation_comm (FiniteDistribution.table responses) ν _ + _ = hit responses ν ownInput right := by + unfold hit + apply FiniteDistribution.expectation_congr + intro x + rw [FiniteDistribution.expectation_table_eval responses (ownInput x) + (fun answer => if answer = some right then (1 : ℝ) else 0)] + simp only [FiniteDistribution.probability, FiniteDistribution.expectation, + decide_eq_true_eq, mul_ite, mul_one, mul_zero] + +theorem hit_square_le_table_collision (responses : Q → FiniteDistribution (Option A)) + (ν : FiniteDistribution Ω) (ownInput : Ω → Q) (right : A) : + hit responses ν ownInput right ^ 2 ≤ + (FiniteDistribution.table responses).expectation (tableCollision ν ownInput) := by + rw [hit_eq_table_mean] + apply (CollisionAveraging.mean_square_le (FiniteDistribution.table responses) + (tableHit ν ownInput right)).trans + apply Finset.sum_le_sum + intro answers _ + exact mul_le_mul_of_nonneg_left + (SingleResponseResampling.local_square_bound ν (fun x => answers (ownInput x)) right) + ((FiniteDistribution.table responses).nonnegative answers) + +theorem hit_square_le_of_supported_tables (responses : Q → FiniteDistribution (Option A)) + (ν : FiniteDistribution Ω) (ownInput : Ω → Q) (right : A) (bound : ℝ) + (hbound : ∀ answers, (FiniteDistribution.table responses).weight answers ≠ 0 → + tableCollision ν ownInput answers ≤ bound) : + hit responses ν ownInput right ^ 2 ≤ bound := + (hit_square_le_table_collision responses ν ownInput right).trans + (DecoderTableAdmissibility.expectation_le_of_support + (FiniteDistribution.table responses) (tableCollision ν ownInput) bound hbound) + +theorem hit_square_le_of_admissible (responses : Q → FiniteDistribution (Option A)) + (ν : FiniteDistribution Ω) (ownInput : Ω → Q) (right : A) + (valid : Q → A → Prop) + (hvalid : ∀ q a, (responses q).weight (some a) ≠ 0 → valid q a) + (bound : ℝ) + (hbound : ∀ answers, DecoderTableAdmissibility.Admissible valid answers → + tableCollision ν ownInput answers ≤ bound) : + hit responses ν ownInput right ^ 2 ≤ bound := + (hit_square_le_table_collision responses ν ownInput right).trans + (DecoderTableAdmissibility.expectation_le_of_admissible responses valid hvalid + (tableCollision ν ownInput) bound hbound) + +theorem hit_square_le_of_probability_one (responses : Q → FiniteDistribution (Option A)) + (ν : FiniteDistribution Ω) (ownInput : Ω → Q) (right : A) + (valid : Q → A → Prop) + (hvalid : ∀ q, (responses q).probability + (fun answer => decide (DecoderTableAdmissibility.RowValid valid q answer)) = 1) + (bound : ℝ) + (hbound : ∀ answers, DecoderTableAdmissibility.Admissible valid answers → + tableCollision ν ownInput answers ≤ bound) : + hit responses ν ownInput right ^ 2 ≤ bound := + (hit_square_le_table_collision responses ν ownInput right).trans + (DecoderTableAdmissibility.expectation_le_of_probability_one responses valid hvalid + (tableCollision ν ownInput) bound hbound) + +end FixedFiber + + +variable {B : Type*} [Fintype B] + {Q A Ω : B → Type*} [∀ b, Fintype (Q b)] [∀ b, DecidableEq (Q b)] + [∀ b, Fintype (A b)] [∀ b, Fintype (Ω b)] + +theorem mean_hit_square_le_table_collision (μ : FiniteDistribution B) + (responses : (b : B) → Q b → FiniteDistribution (Option (A b))) + (ν : (b : B) → FiniteDistribution (Ω b)) + (ownInput : (b : B) → Ω b → Q b) (right : (b : B) → A b) : + μ.expectation (fun b => hit (responses b) (ν b) (ownInput b) (right b)) ^ 2 ≤ + μ.expectation (fun b => (FiniteDistribution.table (responses b)).expectation + (tableCollision (ν b) (ownInput b))) := by + apply (CollisionAveraging.mean_square_le μ + (fun b => hit (responses b) (ν b) (ownInput b) (right b))).trans + apply Finset.sum_le_sum + intro b _ + exact mul_le_mul_of_nonneg_left + (hit_square_le_table_collision (responses b) (ν b) (ownInput b) (right b)) + (μ.nonnegative b) + +end +end PerfectCompleteness.StochasticSingleResponse + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/NormalizationLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/NormalizationLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..a75cab26ba07d311876455eb51f625219b348973 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/NormalizationLemmas.lean @@ -0,0 +1,554 @@ +import Mathlib.Data.Fintype.Prod +import Mathlib.Data.Fintype.Sigma +import Mathlib.Data.Fintype.Sum +import Mathlib.Data.List.Basic +import Mathlib.Tactic.DeriveFintype +import Mathlib.Tactic.Linarith +import OAI.Computability.PerfectCompleteness.Foundations.SourceClause +import OAI.Computability.UniqueGames.Machines.MachineSubroutineLemmas +import OAI.Computability.UniqueGames.PCP.AlphabetTableBoundsLemmas + +namespace OAI + + +namespace PerfectCompleteness.Normalization + +open UniqueGamesTheorem.Foundations +open Target +open SourceClause + +def tripleClause {n : Nat} (a b c : Fin n) (sa sb sc : Bool) : Clause n := + #v[⟨a, sa⟩, ⟨b, sb⟩, ⟨c, sc⟩] + +def normalizedTriple {n : Nat} (a b c : Fin n) (sa sb sc : Bool) + (hab : a ≠ b) (hac : a ≠ c) (hbc : b ≠ c) : NormalizedClause n where + clause := tripleClause a b c sa sb sc + distinct := by + intro i j h + have hi : i = 0 ∨ i = 1 ∨ i = 2 := by omega + have hj : j = 0 ∨ j = 1 ∨ j = 2 := by omega + rcases hi with rfl | rfl | rfl <;> + rcases hj with rfl | rfl | rfl <;> + simp_all [tripleClause] + +def outputVariables (F : Formula) : Nat := F.variables + 4 * F.clauses.length + +def oldVariable (F : Formula) (v : Fin F.variables) : Fin (outputVariables F) := + ⟨v.val, by have := v.isLt; unfold outputVariables; omega⟩ + +def freshVariable (F : Formula) (c : Fin F.clauses.length) (i : Fin 4) : + Fin (outputVariables F) := + ⟨F.variables + 4 * c.val + i.val, by + have hc := c.isLt + have hi := i.isLt + unfold outputVariables + omega⟩ + +def copyVariable (F : Formula) (c : Fin F.clauses.length) (i : Fin 3) : + Fin (outputVariables F) := + freshVariable F c ⟨i.val, by have := i.isLt; omega⟩ + +def paddingVariable (F : Formula) (c : Fin F.clauses.length) : + Fin (outputVariables F) := freshVariable F c 3 + +theorem freshVariable_injective (F : Formula) + (c d : Fin F.clauses.length) (i j : Fin 4) + (h : freshVariable F c i = freshVariable F d j) : c = d ∧ i = j := by + have hv := congrArg Fin.val h + dsimp [freshVariable] at hv + have hi := i.isLt + have hj := j.isLt + have hc : c.val = d.val := by omega + have hij : i.val = j.val := by omega + exact ⟨Fin.ext hc, Fin.ext hij⟩ + +theorem copy_ne_copy (F : Formula) (c : Fin F.clauses.length) + {i j : Fin 3} (hij : i ≠ j) : copyVariable F c i ≠ copyVariable F c j := by + intro h + have hv := congrArg Fin.val h + dsimp [copyVariable, freshVariable] at hv + apply hij + apply Fin.ext + omega + +theorem copy_ne_old (F : Formula) (c : Fin F.clauses.length) + (i : Fin 3) (v : Fin F.variables) : copyVariable F c i ≠ oldVariable F v := by + intro h + have hv := congrArg Fin.val h + have hvlt := v.isLt + dsimp [copyVariable, freshVariable, oldVariable] at hv + omega + +theorem copy_ne_padding (F : Formula) (c : Fin F.clauses.length) + (i : Fin 3) : copyVariable F c i ≠ paddingVariable F c := by + intro h + have hv := congrArg Fin.val h + have hi := i.isLt + dsimp [copyVariable, paddingVariable, freshVariable] at hv + omega + +theorem old_ne_padding (F : Formula) (c : Fin F.clauses.length) + (v : Fin F.variables) : oldVariable F v ≠ paddingVariable F c := by + intro h + have hv := congrArg Fin.val h + have hvlt := v.isLt + dsimp [paddingVariable, freshVariable, oldVariable] at hv + omega + +def mainClause (F : Formula) (c : Fin F.clauses.length) : + NormalizedClause (outputVariables F) := + normalizedTriple (copyVariable F c 0) (copyVariable F c 1) (copyVariable F c 2) + (PCP.clauseAt F c)[0].positive (PCP.clauseAt F c)[1].positive + (PCP.clauseAt F c)[2].positive + (copy_ne_copy F c (by decide)) (copy_ne_copy F c (by decide)) + (copy_ne_copy F c (by decide)) + +def equalityClauses (F : Formula) (c : Fin F.clauses.length) (i : Fin 3) : + List (NormalizedClause (outputVariables F)) := + let x := copyVariable F c i + let v := oldVariable F (PCP.clauseAt F c)[i].variableIndex + let z := paddingVariable F c + let hxv := copy_ne_old F c i (PCP.clauseAt F c)[i].variableIndex + let hxz := copy_ne_padding F c i + let hvz := old_ne_padding F c (PCP.clauseAt F c)[i].variableIndex + [normalizedTriple x v z false true true hxv hxz hvz, + normalizedTriple x v z false true false hxv hxz hvz, + normalizedTriple x v z true false true hxv hxz hvz, + normalizedTriple x v z true false false hxv hxz hvz] + +def gadget (F : Formula) (c : Fin F.clauses.length) : + List (NormalizedClause (outputVariables F)) := + [mainClause F c] ++ equalityClauses F c 0 ++ + equalityClauses F c 1 ++ equalityClauses F c 2 + +def gadgetClauses (F : Formula) (c : Fin F.clauses.length) : + List (Clause (outputVariables F)) := + (gadget F c).map NormalizedClause.clause + +@[simp] theorem equalityClauses_length (F : Formula) (c : Fin F.clauses.length) + (i : Fin 3) : (equalityClauses F c i).length = 4 := rfl + +@[simp] theorem gadget_length (F : Formula) (c : Fin F.clauses.length) : + (gadget F c).length = 13 := by simp [gadget] + +@[simp] theorem gadgetClauses_length (F : Formula) (c : Fin F.clauses.length) : + (gadgetClauses F c).length = 13 := by simp [gadgetClauses] + +def restrictAssignment (F : Formula) (B : Fin (outputVariables F) → Bool) : + Fin F.variables → Bool := fun v => B (oldVariable F v) + +def extendAssignment (F : Formula) (A : Fin F.variables → Bool) + (v : Fin (outputVariables F)) : Bool := + if old : v.val < F.variables then A ⟨v.val, old⟩ + else + let c : Fin F.clauses.length := ⟨(v.val - F.variables) / 4, by + have hv := v.isLt + unfold outputVariables at hv + omega⟩ + if slot : (v.val - F.variables) % 4 < 3 then + A (PCP.clauseAt F c)[(⟨(v.val - F.variables) % 4, slot⟩ : Fin 3)].variableIndex + else false + +@[simp] theorem extend_oldVariable (F : Formula) (A : Fin F.variables → Bool) + (v : Fin F.variables) : extendAssignment F A (oldVariable F v) = A v := by + simp [extendAssignment, oldVariable, v.isLt] + +@[simp] theorem extend_copyVariable (F : Formula) (A : Fin F.variables → Bool) + (c : Fin F.clauses.length) (i : Fin 3) : + extendAssignment F A (copyVariable F c i) = A (PCP.clauseAt F c)[i].variableIndex := by + have hi := i.isLt + have hold : ¬ F.variables + 4 * c.val + i.val < F.variables := by omega + have hdiv : (F.variables + 4 * c.val + i.val - F.variables) / 4 = c.val := by omega + have hmod : (F.variables + 4 * c.val + i.val - F.variables) % 4 = i.val := by omega + simp [extendAssignment, copyVariable, freshVariable, hold, hdiv, hmod, hi] + +@[simp] theorem restrict_extend (F : Formula) (A : Fin F.variables → Bool) : + restrictAssignment F (extendAssignment F A) = A := by + funext v + exact extend_oldVariable F A v + +theorem main_eval_of_copies_match (F : Formula) (c : Fin F.clauses.length) + (B : Fin (outputVariables F) → Bool) + (hcopy : ∀ i : Fin 3, + B (copyVariable F c i) = B (oldVariable F (PCP.clauseAt F c)[i].variableIndex)) : + (mainClause F c).clause.eval B = (PCP.clauseAt F c).eval (restrictAssignment F B) := by + simp [mainClause, normalizedTriple, tripleClause, Clause.eval, Literal.eval, + restrictAssignment, hcopy] + +theorem equalityClauses_failures (F : Formula) (c : Fin F.clauses.length) + (i : Fin 3) (B : Fin (outputVariables F) → Bool) : + PCP.VerifierToCNF.clauseFailures + ((equalityClauses F c i).map NormalizedClause.clause) B = + if B (copyVariable F c i) = B (oldVariable F (PCP.clauseAt F c)[i].variableIndex) + then 0 else 1 := by + cases hx : B (copyVariable F c i) <;> + cases hv : B (oldVariable F (PCP.clauseAt F c)[i].variableIndex) <;> + cases hz : B (paddingVariable F c) <;> + simp only [Fin.getElem_fin] at hv <;> + simp [PCP.VerifierToCNF.clauseFailures, equalityClauses, normalizedTriple, + tripleClause, Clause.eval, Literal.eval, hx, hv, hz] + +theorem gadget_failures (F : Formula) (c : Fin F.clauses.length) + (B : Fin (outputVariables F) → Bool) : + PCP.VerifierToCNF.clauseFailures (gadgetClauses F c) B = + (if (mainClause F c).clause.eval B then 0 else 1) + + (if B (copyVariable F c 0) = B (oldVariable F (PCP.clauseAt F c)[0].variableIndex) + then 0 else 1) + + (if B (copyVariable F c 1) = B (oldVariable F (PCP.clauseAt F c)[1].variableIndex) + then 0 else 1) + + (if B (copyVariable F c 2) = B (oldVariable F (PCP.clauseAt F c)[2].variableIndex) + then 0 else 1) := by + simp only [gadgetClauses, gadget, List.map_append, + PCP.VerifierToCNF.clauseFailures_append, equalityClauses_failures] + cases hmain : (mainClause F c).clause.eval B <;> + simp [PCP.VerifierToCNF.clauseFailures, hmain] + +theorem clauseFailures_zero_iff {n : Nat} (cs : List (Clause n)) (B : Fin n → Bool) : + PCP.VerifierToCNF.clauseFailures cs B = 0 ↔ ∀ c ∈ cs, c.eval B = true := by + rw [PCP.VerifierToCNF.clauseFailures, PCP.VerifierToCNF.zero_false_count_iff_all] + simp only [List.all_map, Function.comp_def, id_eq, List.all_eq_true] + +theorem gadget_complete_of_copies_match (F : Formula) (c : Fin F.clauses.length) + (B : Fin (outputVariables F) → Bool) + (hcopy : ∀ i : Fin 3, + B (copyVariable F c i) = B (oldVariable F (PCP.clauseAt F c)[i].variableIndex)) + (hsat : (PCP.clauseAt F c).eval (restrictAssignment F B) = true) : + ∀ d ∈ gadgetClauses F c, d.eval B = true := by + apply (clauseFailures_zero_iff _ B).1 + rw [gadget_failures, main_eval_of_copies_match F c B hcopy, hsat] + simp [hcopy] + +theorem gadget_failure_domination (F : Formula) (c : Fin F.clauses.length) + (B : Fin (outputVariables F) → Bool) : + (if (PCP.clauseAt F c).eval (restrictAssignment F B) then 0 else 1) ≤ + PCP.VerifierToCNF.clauseFailures (gadgetClauses F c) B := by + rw [gadget_failures] + by_cases h0 : B (copyVariable F c 0) = + B (oldVariable F (PCP.clauseAt F c)[0].variableIndex) + · by_cases h1 : B (copyVariable F c 1) = + B (oldVariable F (PCP.clauseAt F c)[1].variableIndex) + · by_cases h2 : B (copyVariable F c 2) = + B (oldVariable F (PCP.clauseAt F c)[2].variableIndex) + · have hcopy : ∀ i : Fin 3, + B (copyVariable F c i) = + B (oldVariable F (PCP.clauseAt F c)[i].variableIndex) := by + intro i + have hi : i = 0 ∨ i = 1 ∨ i = 2 := by omega + rcases hi with rfl | rfl | rfl + · exact h0 + · exact h1 + · exact h2 + rw [main_eval_of_copies_match F c B hcopy] + simp [h0, h1, h2] + · cases (PCP.clauseAt F c).eval (restrictAssignment F B) <;> + simp [h0, h1, h2] + · cases (PCP.clauseAt F c).eval (restrictAssignment F B) <;> + simp [h0, h1] + omega + · cases (PCP.clauseAt F c).eval (restrictAssignment F B) <;> + simp [h0] + omega + +theorem gadget_failed (F : Formula) (c : Fin F.clauses.length) + (B : Fin (outputVariables F) → Bool) + (unsatisfied : (PCP.clauseAt F c).eval (restrictAssignment F B) = false) : + 1 ≤ PCP.VerifierToCNF.clauseFailures (gadgetClauses F c) B := by + simpa [unsatisfied] using gadget_failure_domination F c B + +def normalizedClauses (F : Formula) : List (NormalizedClause (outputVariables F)) := + (PCP.allIndices F).flatMap (gadget F) + +def normalize (F : Formula) : Formula where + «variables» := outputVariables F + clauses := (PCP.allIndices F).flatMap (gadgetClauses F) + +theorem normalize_clauses_eq_map (F : Formula) : + (normalize F).clauses = (normalizedClauses F).map NormalizedClause.clause := by + simp only [normalize, normalizedClauses, List.map_flatMap] + rfl + +theorem normalize_distinct (F : Formula) (c : Clause (normalize F).variables) + (hc : c ∈ (normalize F).clauses) (i j : Fin 3) + (same : (c)[i].variableIndex = (c)[j].variableIndex) : i = j := by + rw [normalize_clauses_eq_map] at hc + obtain ⟨d, _, hd⟩ := List.mem_map.mp hc + subst c + exact d.distinct i j same + +@[simp] theorem normalize_variables (F : Formula) : + (normalize F).variables = F.variables + 4 * F.clauses.length := rfl + +@[simp] theorem normalize_clause_count (F : Formula) : + (normalize F).clauses.length = 13 * F.clauses.length := by + change ((PCP.allIndices F).flatMap (gadgetClauses F)).length = _ + rw [PCP.VerifierToCNF.length_flatMap_constant _ _ 13 + (fun c _ => gadgetClauses_length F c)] + simp [PCP.allIndices, Nat.mul_comm] + +theorem normalize_nonempty (F : Formula) (hne : F.clauses ≠ []) : + (normalize F).clauses ≠ [] := by + have hm : 0 < F.clauses.length := List.length_pos_iff.mpr hne + have hout : 0 < (normalize F).clauses.length := by + rw [normalize_clause_count] + omega + exact List.ne_nil_of_length_pos hout + +theorem normalize_completeness (F : Formula) (hs : F.Satisfiable) : + (normalize F).Satisfiable := by + obtain ⟨A, hA⟩ := hs + refine ⟨extendAssignment F A, ?_⟩ + intro d hd + obtain ⟨c, _, hd⟩ := List.mem_flatMap.mp hd + apply gadget_complete_of_copies_match F c (extendAssignment F A) ?_ ?_ d hd + · intro i + simp + · rw [restrict_extend] + exact hA _ (List.getElem_mem c.isLt) + +theorem failedCount_domination (F : Formula) (B : Fin (normalize F).variables → Bool) : + PCP.NameCompaction.failedCount F (restrictAssignment F B) ≤ + PCP.NameCompaction.failedCount (normalize F) B := by + change Fin (outputVariables F) → Bool at B + change (PCP.NameCompaction.evaluationList F (restrictAssignment F B)).count false ≤ + PCP.VerifierToCNF.clauseFailures ((PCP.allIndices F).flatMap (gadgetClauses F)) B + rw [← PCP.NameCompaction.evaluations_allIndices F (restrictAssignment F B), + PCP.VerifierToCNF.count_false_map_sum, PCP.VerifierToCNF.clauseFailures_flatMap] + exact PCP.VerifierToCNF.nat_sum_map_le _ _ _ + (fun c _ => gadget_failure_domination F c B) + +theorem normalize_reflects (F : Formula) (hs : (normalize F).Satisfiable) : + F.Satisfiable := by + obtain ⟨B, hB⟩ := hs + have hout : PCP.NameCompaction.failedCount (normalize F) B = 0 := + (clauseFailures_zero_iff (normalize F).clauses B).2 hB + have hin : PCP.NameCompaction.failedCount F (restrictAssignment F B) = 0 := by + have h := failedCount_domination F B + rw [hout] at h + omega + exact ⟨restrictAssignment F B, (clauseFailures_zero_iff F.clauses _).1 hin⟩ + +theorem normalize_satisfiable_iff (F : Formula) : + (normalize F).Satisfiable ↔ F.Satisfiable := + ⟨normalize_reflects F, normalize_completeness F⟩ + +theorem normalize_gap (F : Formula) (a b : Nat) + (gap : ∀ A, a * F.clauses.length ≤ b * PCP.NameCompaction.failedCount F A) + (B : Fin (normalize F).variables → Bool) : + a * (normalize F).clauses.length ≤ + (13 * b) * PCP.NameCompaction.failedCount (normalize F) B := by + have hsource := gap (restrictAssignment F B) + have hcount := Nat.mul_le_mul_left b (failedCount_domination F B) + rw [normalize_clause_count] + calc + a * (13 * F.clauses.length) = 13 * (a * F.clauses.length) := by ac_rfl + _ ≤ 13 * (b * PCP.NameCompaction.failedCount (normalize F) B) := + Nat.mul_le_mul_left 13 (hsource.trans hcount) + _ = (13 * b) * PCP.NameCompaction.failedCount (normalize F) B := by ac_rfl + +end PerfectCompleteness.Normalization + + + +namespace PerfectCompleteness.NormalizationWords + + +open UniqueGamesTheorem.Foundations +open Complexity + +abbrev Signs := Fin 3 → Bool +abbrev Names := Fin 3 → Nat + +inductive NameRef + | old (slot : Fin 3) + | fresh (slot : Fin 4) + deriving DecidableEq, Fintype + +inductive SignRef + | source (slot : Fin 3) + | constant (sign : Bool) + deriving DecidableEq, Fintype + +structure LiteralRecipe where + name : NameRef + sign : SignRef + deriving DecidableEq, Fintype + +def sourceValue (names : Names) (freshBase : Nat) : NameRef → Nat + | .old i => names i + | .fresh _ => freshBase + +def offset : NameRef → Nat + | .old _ => 0 + | .fresh i => i.val + +def nameValue (names : Names) (freshBase : Nat) (name : NameRef) : Nat := + sourceValue names freshBase name + offset name + +def signValue (signs : Signs) : SignRef → Bool + | .source i => signs i + | .constant sign => sign + +def literalWords (signs : Signs) (names : Names) (freshBase : Nat) + (literal : LiteralRecipe) : List Nat := + [nameValue names freshBase literal.name, if signValue signs literal.sign then 1 else 0] + +def literalBits (signs : Signs) (names : Names) (freshBase : Nat) + (literal : LiteralRecipe) : List Bool := + encodeWords (literalWords signs names freshBase literal) + +def mainRecipe : List LiteralRecipe := + [⟨.fresh 0, .source 0⟩, ⟨.fresh 1, .source 1⟩, ⟨.fresh 2, .source 2⟩] + +def equalityRecipe (i : Fin 3) : List LiteralRecipe := + [⟨.fresh i.castSucc, .constant false⟩, ⟨.old i, .constant true⟩, ⟨.fresh 3, .constant true⟩, + ⟨.fresh i.castSucc, .constant false⟩, ⟨.old i, .constant true⟩, ⟨.fresh 3, .constant false⟩, + ⟨.fresh i.castSucc, .constant true⟩, ⟨.old i, .constant false⟩, ⟨.fresh 3, .constant true⟩, + ⟨.fresh i.castSucc, .constant true⟩, ⟨.old i, .constant false⟩, ⟨.fresh 3, .constant false⟩] + +def recipe : List LiteralRecipe := + mainRecipe ++ equalityRecipe 0 ++ equalityRecipe 1 ++ equalityRecipe 2 + +@[simp] theorem recipe_length : recipe.length = 39 := by decide + +def words (signs : Signs) (names : Names) (freshBase : Nat) : List Nat := + recipe.flatMap (literalWords signs names freshBase) + +def bits (signs : Signs) (names : Names) (freshBase : Nat) : List Bool := + encodeWords (words signs names freshBase) + +def clauseSigns {n : Nat} (clause : Target.Clause n) : Signs := fun i => clause[i].positive + +def clauseNames {n : Nat} (clause : Target.Clause n) : Names := fun i => clause[i].variableIndex.val + +theorem encodeWords_flatMap {α : Type} (xs : List α) (f : α → List Nat) : + encodeWords (xs.flatMap f) = xs.flatMap (fun x => encodeWords (f x)) := by + induction xs with + | nil => rfl + | cons x xs ih => simp only [List.flatMap_cons, encodeWords_append, ih] + +theorem bits_eq_flatMap (signs : Signs) (names : Names) (freshBase : Nat) : + bits signs names freshBase = recipe.flatMap (literalBits signs names freshBase) := + encodeWords_flatMap _ _ + +theorem gadget_words (formula : Target.Formula) (c : Fin formula.clauses.length) : + (Normalization.gadgetClauses formula c).flatMap Complexity.clauseWords = + words (clauseSigns (PCP.clauseAt formula c)) (clauseNames (PCP.clauseAt formula c)) + (formula.variables + 4 * c.val) := by + simp [Normalization.gadgetClauses, Normalization.gadget, Normalization.mainClause, + Normalization.equalityClauses, Normalization.normalizedTriple, Normalization.tripleClause, + Normalization.copyVariable, Normalization.freshVariable, Normalization.oldVariable, + Normalization.paddingVariable, Complexity.clauseWords, Complexity.literalWords, + words, recipe, mainRecipe, equalityRecipe, literalWords, nameValue, sourceValue, offset, + signValue, clauseSigns, clauseNames, Fin.getElem_fin] + exact ⟨rfl, rfl, rfl⟩ + +theorem gadget_bits (formula : Target.Formula) (c : Fin formula.clauses.length) : + encodeWords ((Normalization.gadgetClauses formula c).flatMap Complexity.clauseWords) = + bits (clauseSigns (PCP.clauseAt formula c)) (clauseNames (PCP.clauseAt formula c)) + (formula.variables + 4 * c.val) := by + rw [gadget_words] + rfl + +def body (formula : Target.Formula) : List Bool := + (PCP.allIndices formula).flatMap (fun c => + bits (clauseSigns (PCP.clauseAt formula c)) (clauseNames (PCP.clauseAt formula c)) + (formula.variables + 4 * c.val)) + +theorem encoded_body (formula : Target.Formula) : + encodeWords ((Normalization.normalize formula).clauses.flatMap Complexity.clauseWords) = + body formula := by + change encodeWords (((PCP.allIndices formula).flatMap + (Normalization.gadgetClauses formula)).flatMap Complexity.clauseWords) = _ + rw [List.flatMap_assoc, encodeWords_flatMap] + simp only [gadget_bits, body] + +theorem encoded_normalize (formula : Target.Formula) : + formulaBits (Normalization.normalize formula) = + encodeWord (formula.variables + 4 * formula.clauses.length) ++ + encodeWord (13 * formula.clauses.length) ++ body formula := by + have count : (Normalization.normalize formula).clauses.length = + 13 * formula.clauses.length := Normalization.normalize_clause_count formula + simp only [formulaBits, formulaWords, encodeWords_append, encodeWords, List.append_nil, + Normalization.normalize_variables, List.append_assoc] + erw [count, encoded_body] + +end PerfectCompleteness.NormalizationWords + + + +namespace PerfectCompleteness.NormalizationStream + +open UniqueGamesTheorem.Foundations Complexity NormalizationWords + +def blocks {n : Nat} (freshBase : Nat) : List (Target.Clause n) → List Bool + | [] => [] + | clause :: clauses => + bits (clauseSigns clause) (clauseNames clause) freshBase ++ blocks (freshBase + 4) clauses + +theorem blocks_eq_finRange {n : Nat} (clauses : List (Target.Clause n)) (freshBase : Nat) : + blocks freshBase clauses = (List.finRange clauses.length).flatMap (fun i => + bits (clauseSigns clauses[i.val]) (clauseNames clauses[i.val]) (freshBase + 4 * i.val)) := by + induction clauses generalizing freshBase with + | nil => simp [blocks] + | cons clause clauses ih => + simp only [blocks, List.length_cons, List.finRange_succ, List.flatMap_cons, + List.flatMap_map, List.getElem_cons_zero, Fin.val_zero, Nat.mul_zero, Nat.add_zero] + apply congrArg (fun tail => bits (clauseSigns clause) (clauseNames clause) freshBase ++ tail) + rw [ih] + apply List.flatMap_congr + intro i _ + have address : freshBase + 4 + 4 * i.val = freshBase + 4 * (i.val + 1) := by omega + simp only [Fin.val_succ, List.getElem_cons_succ, address] + +theorem body_eq_blocks (formula : Target.Formula) : + NormalizationWords.body formula = blocks formula.variables formula.clauses := by + rw [blocks_eq_finRange] + rfl + +theorem encoded_normalize (formula : Target.Formula) : + formulaBits (Normalization.normalize formula) = + encodeWord (formula.variables + 4 * formula.clauses.length) ++ + encodeWord (13 * formula.clauses.length) ++ blocks formula.variables formula.clauses := by + rw [NormalizationWords.encoded_normalize, body_eq_blocks] + +theorem blocks_length_le {n : Nat} (clauses : List (Target.Clause n)) (freshBase : Nat) + (bound : Nat) (oldBound : n ≤ bound) (freshBound : freshBase + 4 * clauses.length ≤ bound) : + (blocks freshBase clauses).length ≤ clauses.length * (39 * (bound + 3)) := by + have literalBound (names : Names) (fresh : Nat) (signs : Signs) + (hn : ∀ i, names i ≤ bound) (hf : fresh + 3 ≤ bound) (literal : LiteralRecipe) : + (literalBits signs names fresh literal).length ≤ bound + 3 := by + have nameBound : nameValue names fresh literal.name ≤ bound := by + cases h : literal.name with + | old i => simpa [nameValue, sourceValue, offset, h] using hn i + | fresh i => + have hi := i.isLt + simp only [nameValue, sourceValue, offset] + omega + cases h : signValue signs literal.sign <;> + simp [literalBits, NormalizationWords.literalWords, h] <;> omega + have gadgetBound (clause : Target.Clause n) (fresh : Nat) (hf : fresh + 3 ≤ bound) : + (bits (clauseSigns clause) (clauseNames clause) fresh).length ≤ 39 * (bound + 3) := by + rw [bits_eq_flatMap] + have listBound (commands : List LiteralRecipe) : + (commands.flatMap (literalBits (clauseSigns clause) (clauseNames clause) fresh)).length ≤ + commands.length * (bound + 3) := by + induction commands with + | nil => simp + | cons command commands ih => + have hc := literalBound (clauseNames clause) fresh (clauseSigns clause) + (fun i => Nat.le_trans (clause[i].variableIndex.isLt.le) oldBound) hf command + simp only [List.flatMap_cons, List.length_append, List.length_cons, + Nat.add_mul, Nat.one_mul] + omega + simpa only [recipe_length] using listBound recipe + induction clauses generalizing freshBase with + | nil => simp [blocks] + | cons clause clauses ih => + have head := gadgetBound clause freshBase (by simp only [List.length_cons] at freshBound; omega) + have tail := ih (freshBase + 4) (by simp only [List.length_cons] at freshBound; omega) + simp only [blocks, List.length_append, List.length_cons] + nlinarith + +end PerfectCompleteness.NormalizationStream + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/OccurrenceStochasticLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/OccurrenceStochasticLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..534a761acb325483329a40d4253b5b8f7dcb44a1 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/OccurrenceStochasticLemmas.lean @@ -0,0 +1,151 @@ +import OAI.Computability.PerfectCompleteness.Reduction.OccurrenceGame +import OAI.Computability.UniqueGames.Foundations.ValueLemmas + +namespace OAI + + +namespace PerfectCompleteness.OccurrenceGame + +open UniqueGamesTheorem.Foundations.Games + +noncomputable section + +variable {E Q₁ Q₂ A₁ A₂ : Type*} + [Fintype E] [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂] + [DecidableEq Q₁] [DecidableEq Q₂] + +def stochasticSuccess (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) + (responses₁ : Q₁ → FiniteDistribution A₁) + (responses₂ : Q₂ → FiniteDistribution A₂) : ℝ := + G.occurrences.expectation (fun e => + (responses₁ (G.left e)).expectation (fun a => + (responses₂ (G.right e)).expectation + (fun b => if G.accepts e a b then 1 else 0))) + +omit [DecidableEq Q₁] [DecidableEq Q₂] in +theorem success_eq_occurrence_expectation (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) + (strategy : Strategy Q₁ Q₂ A₁ A₂) : + G.success strategy = G.occurrences.expectation + (fun e => if G.wins strategy e then 1 else 0) := by + simp [success, FiniteDistribution.probability, FiniteDistribution.expectation, mul_ite] + +theorem table_success_eq_stochastic (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) + (responses₁ : Q₁ → FiniteDistribution A₁) + (responses₂ : Q₂ → FiniteDistribution A₂) : + ((FiniteDistribution.table responses₁).product (FiniteDistribution.table responses₂)).expectation + G.success = G.stochasticSuccess responses₁ responses₂ := by + classical + unfold stochasticSuccess + calc + _ = ((FiniteDistribution.table responses₁).product (FiniteDistribution.table responses₂)).expectation + (fun strategy => G.occurrences.expectation + (fun e => if G.wins strategy e then 1 else 0)) := + FiniteDistribution.expectation_congr _ G.success_eq_occurrence_expectation + _ = G.occurrences.expectation (fun e => + ((FiniteDistribution.table responses₁).product (FiniteDistribution.table responses₂)).expectation + (fun strategy => if G.wins strategy e then 1 else 0)) := + FiniteDistribution.expectation_comm _ _ _ + _ = _ := by + apply FiniteDistribution.expectation_congr + intro e + rw [FiniteDistribution.expectation_product] + change (FiniteDistribution.table responses₁).expectation + (fun answers₁ => (FiniteDistribution.table responses₂).expectation + (fun answers₂ => + if G.accepts e (answers₁ (G.left e)) (answers₂ (G.right e)) then 1 else 0)) = _ + calc + _ = (FiniteDistribution.table responses₁).expectation + (fun answers₁ => (responses₂ (G.right e)).expectation + (fun b => if G.accepts e (answers₁ (G.left e)) b then 1 else 0)) := by + apply FiniteDistribution.expectation_congr + intro answers₁ + exact FiniteDistribution.expectation_table_eval responses₂ (G.right e) + (fun b => if G.accepts e (answers₁ (G.left e)) b then (1 : ℝ) else 0) + _ = _ := FiniteDistribution.expectation_table_eval responses₁ (G.left e) + (fun a => (responses₂ (G.right e)).expectation + (fun b => if G.accepts e a b then (1 : ℝ) else 0)) + +theorem stochasticSuccess_le_value [Nonempty A₁] [Nonempty A₂] + (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) + (responses₁ : Q₁ → FiniteDistribution A₁) + (responses₂ : Q₂ → FiniteDistribution A₂) : + G.stochasticSuccess responses₁ responses₂ ≤ G.value := by + rw [← G.table_success_eq_stochastic] + exact G.randomized_success_le_value + ((FiniteDistribution.table responses₁).product (FiniteDistribution.table responses₂)) id + +end +end PerfectCompleteness.OccurrenceGame + + + +namespace PerfectCompleteness.OccurrenceVertexEmbedding + +open UniqueGamesTheorem.Foundations.Games + +noncomputable section + +variable {E Q₁ Q₂ N₁ N₂ A₁ A₂ : Type*} + [Fintype E] [Fintype Q₁] [Fintype Q₂] [Fintype N₁] [Fintype N₂] + [Fintype A₁] [Fintype A₂] + +def rename (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) (left : Q₁ ↪ N₁) (right : Q₂ ↪ N₂) : + OccurrenceGame E N₁ N₂ A₁ A₂ where + occurrences := G.occurrences + left e := left (G.left e) + right e := right (G.right e) + accepts := G.accepts + +def restrict (left : Q₁ ↪ N₁) (right : Q₂ ↪ N₂) (strategy : Strategy N₁ N₂ A₁ A₂) : + Strategy Q₁ Q₂ A₁ A₂ := + (fun x => strategy.1 (left x), fun y => strategy.2 (right y)) + +@[simp] theorem wins_restrict (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) + (left : Q₁ ↪ N₁) (right : Q₂ ↪ N₂) (strategy : Strategy N₁ N₂ A₁ A₂) (e : E) : + (rename G left right).wins strategy e = G.wins (restrict left right strategy) e := rfl + +@[simp] theorem success_restrict (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) + (left : Q₁ ↪ N₁) (right : Q₂ ↪ N₂) (strategy : Strategy N₁ N₂ A₁ A₂) : + (rename G left right).success strategy = G.success (restrict left right strategy) := rfl + +def extend (left : Q₁ ↪ N₁) (right : Q₂ ↪ N₂) (defaultLeft : A₁) (defaultRight : A₂) + (strategy : Strategy Q₁ Q₂ A₁ A₂) : Strategy N₁ N₂ A₁ A₂ := + (Function.extend left strategy.1 (fun _ => defaultLeft), + Function.extend right strategy.2 (fun _ => defaultRight)) + +omit [Fintype Q₁] [Fintype Q₂] [Fintype N₁] [Fintype N₂] [Fintype A₁] [Fintype A₂] in +@[simp] theorem restrict_extend (left : Q₁ ↪ N₁) (right : Q₂ ↪ N₂) + (defaultLeft : A₁) (defaultRight : A₂) (strategy : Strategy Q₁ Q₂ A₁ A₂) : + restrict left right (extend left right defaultLeft defaultRight strategy) = strategy := by + apply Prod.ext + · funext x + exact left.injective.extend_apply strategy.1 (fun _ => defaultLeft) x + · funext y + exact right.injective.extend_apply strategy.2 (fun _ => defaultRight) y + +theorem success_extend (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) + (left : Q₁ ↪ N₁) (right : Q₂ ↪ N₂) (defaultLeft : A₁) (defaultRight : A₂) + (strategy : Strategy Q₁ Q₂ A₁ A₂) : + (rename G left right).success (extend left right defaultLeft defaultRight strategy) = + G.success strategy := by + rw [success_restrict, restrict_extend] + +theorem value_eq [Nonempty A₁] [Nonempty A₂] + (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) (left : Q₁ ↪ N₁) (right : Q₂ ↪ N₂) : + (rename G left right).value = G.value := by + apply le_antisymm + · apply ((rename G left right).value_le_iff _).2 + intro strategy + rw [success_restrict] + exact G.success_le_value _ + · apply (G.value_le_iff _).2 + intro strategy + let s := extend left right (Classical.choice inferInstance) (Classical.choice inferInstance) + strategy + have h := (rename G left right).success_le_value s + simpa only [s, success_extend] using h + +end +end PerfectCompleteness.OccurrenceVertexEmbedding + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/OddListAlphabetTransport.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/OddListAlphabetTransport.lean new file mode 100644 index 0000000000000000000000000000000000000000..a103956826879fd81eb104368900629409973c98 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/OddListAlphabetTransport.lean @@ -0,0 +1,67 @@ +import OAI.Computability.PerfectCompleteness.Foundations.OddLists + +namespace OAI + +section + +namespace PerfectCompleteness.OddLists + +open scoped BigOperators Classical + +noncomputable section + +variable {A B C : Type*} [Fintype A] [Fintype B] [Fintype C] + [DecidableEq A] [DecidableEq B] [DecidableEq C] + +private theorem parityPushforward_comp (π : A → B) (ρ : B → C) (L : Finset A) : + parityPushforward ρ (parityPushforward π L) = + parityPushforward (ρ ∘ π) L := by + let f : A → ZMod 2 := fun a => if a ∈ L then 1 else 0 + have hf : support f = L := by + ext a + by_cases ha : a ∈ L <;> simp [mem_support, f, ha] + rw [← hf, parityPushforward_support, parityPushforward_support, + parityPushforward_support] + apply congrArg (fun g : C → ZMod 2 => support g) + funext c + calc + (∑ b, if ρ b = c then ∑ a, if π a = b then f a else 0 else 0) = + ∑ b, ∑ a, if ρ b = c then (if π a = b then f a else 0) else 0 := by + apply Finset.sum_congr rfl + intro b _ + by_cases hb : ρ b = c <;> simp only [hb, ite_true, ite_false, Finset.sum_const_zero] + _ = ∑ a, ∑ b, if ρ b = c then (if π a = b then f a else 0) else 0 := + Finset.sum_comm + _ = ∑ a, if (ρ ∘ π) a = c then f a else 0 := by + apply Finset.sum_congr rfl + intro a _ + rw [Finset.sum_eq_single (π a)] + · simp only [Function.comp_apply, ite_true] + · intro b _ hb + simp only [ite_eq_right (Ne.symm hb), ite_self] + · intro h + exact (h (Finset.mem_univ _)).elim + +namespace OddList + +theorem map_comp {s : Nat} (π : A → B) (ρ : B → C) (L : OddList s A) : + map ρ (map π L) = map (ρ ∘ π) L := by + apply Subtype.ext + exact parityPushforward_comp π ρ L.val + +theorem map_commutes {D : Type*} [Fintype D] [DecidableEq D] {s : Nat} + (π : A → B) (α : A → C) (β : B → D) (ρ : C → D) + (h : ∀ a, ρ (α a) = β (π a)) + (L : OddList s A) (R : OddList s B) (hnative : map π L = R) : + map ρ (map α L) = map β R := by + rw [map_comp α ρ L, show ρ ∘ α = β ∘ π from funext h, + ← map_comp π β L, hnative] + +end OddList + +end +end PerfectCompleteness.OddLists + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/OddListExtraction.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/OddListExtraction.lean new file mode 100644 index 0000000000000000000000000000000000000000..f10a4c7ab5e5a2de52d851341d96b966083d1f0d --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/OddListExtraction.lean @@ -0,0 +1,317 @@ +import Mathlib.LinearAlgebra.BilinearMap +import Mathlib.LinearAlgebra.Dimension.Finite +import Mathlib.LinearAlgebra.Dual.Defs +import Mathlib.LinearAlgebra.FiniteDimensional.Basic +import OAI.Computability.PerfectCompleteness.Construction.TreeSourceSpaces +import OAI.Computability.PerfectCompleteness.Foundations.OddLists + +namespace OAI + + +namespace PerfectCompleteness.OddListExtraction + +open scoped BigOperators Classical +open PointwiseSpaces + +abbrev F2 := ZMod 2 + +variable {X Y A B : Type*} + +noncomputable def indicator (q : X → A) (a : A) : X → F2 := + fun x => if q x = a then 1 else 0 + +@[simp] theorem indicator_mul_self (q : X → A) (a : A) : + indicator q a * indicator q a = indicator q a := by + classical + funext x + by_cases h : q x = a <;> simp [indicator, h] + +theorem indicator_mul_of_ne (q : X → A) {a b : A} (hab : a ≠ b) : + indicator q a * indicator q b = 0 := by + classical + funext x + by_cases ha : q x = a + · simp [indicator, ha, hab] + · simp [indicator, ha] + +@[simp] theorem sum_indicator [Fintype A] (q : X → A) : + ∑ a, indicator q a = (1 : X → F2) := by + classical + funext x + simp [indicator, Finset.sum_apply] + +theorem indicator_comp [Fintype A] (q : X → A) (π : A → B) (b : B) : + indicator (π ∘ q) b = ∑ a ∈ Finset.univ.filter (fun a => π a = b), indicator q a := by + classical + funext x + simp only [Finset.sum_apply, indicator, Function.comp_apply] + by_cases hb : π (q x) = b + · rw [ite_eq_left hb] + symm + rw [Finset.sum_eq_single (q x)] + · simp + · intro a _ ha + simp only [ite_eq_right (Ne.symm ha)] + · intro h + exact (h (by simp [hb])).elim + · rw [ite_eq_right hb] + symm + apply Finset.sum_eq_zero + intro a ha + have hqa : q x ≠ a := by + intro heq + exact hb ((congrArg π heq).trans (Finset.mem_filter.mp ha).2) + exact ite_eq_right hqa + +theorem leaf_indicator_mem (branch : Nat → Nat) : + ∀ (n : Nat) (D : RecursiveSpaces.Slots branch n → Type*) + (s : RecursiveSpaces.Slots branch n) (a : D s), + indicator (fun x : RecursiveSpaces.Assignment D => x s) a ∈ + RecursiveSpaces.space F2 branch n D := by + intro n + induction n with + | zero => + intro D s a + exact Submodule.mem_top + | succ n ih => + intro D s a + rcases s with ⟨i, s⟩ + have h := ih (RecursiveSpaces.childFamily D i) s a + have hsquare : indicator + (fun x : RecursiveSpaces.Assignment (RecursiveSpaces.childFamily D i) => x s) a ∈ + squareSpace (RecursiveSpaces.space F2 branch n (RecursiveSpaces.childFamily D i)) := by + simpa only [indicator_mul_self] using mul_mem_squareSpace _ h h + exact RecursiveSpaces.child_square_le_space D i (Submodule.mem_map_of_mem hsquare) + +theorem source_leaf_indicator_mem {branch : Nat → Nat} {n t : Nat} + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (s : RecursiveSpaces.Slots branch n) (a : TreeSourceSpaces.LeafDomain slots s) : + indicator (fun x : TreeSourceSpaces.Domain slots => x s) a ∈ TreeSourceSpaces.H slots := + leaf_indicator_mem branch n (TreeSourceSpaces.LeafDomain slots) s a + +section Form + +variable (H : Submodule F2 (X → F2)) + +def productElement (f g : H) : squareSpace H := + ⟨f.val * g.val, mul_mem_squareSpace H f.property g.property⟩ + +def multiplicationForm (z : Module.Dual F2 (squareSpace H)) : H →ₗ[F2] H →ₗ[F2] F2 := + LinearMap.mk₂ F2 (fun f g => z (productElement H f g)) + (by + intro f g h + rw [← map_add] + congr 1 + apply Subtype.ext + exact add_mul _ _ _) + (by + intro c f g + rw [← map_smul] + congr 1 + apply Subtype.ext + exact smul_mul_assoc _ _ _) + (by + intro f g h + rw [← map_add] + congr 1 + apply Subtype.ext + exact mul_add _ _ _) + (by + intro c f g + rw [← map_smul] + congr 1 + apply Subtype.ext + exact mul_smul_comm _ _ _) + +@[simp] theorem multiplicationForm_apply (z : Module.Dual F2 (squareSpace H)) + (f g : H) : multiplicationForm H z f g = z (productElement H f g) := rfl + +noncomputable def formRank (F : H →ₗ[F2] H →ₗ[F2] F2) : Nat := + Module.finrank F2 (LinearMap.range F) + +variable (q : X → A) (hmem : ∀ a, indicator q a ∈ H) + +noncomputable def atom (a : A) : H := ⟨indicator q a, hmem a⟩ + +noncomputable def diagonal (z : Module.Dual F2 (squareSpace H)) (a : A) : F2 := + multiplicationForm H z (atom H q hmem a) (atom H q hmem a) + +@[simp] theorem form_atom_self (z : Module.Dual F2 (squareSpace H)) (a : A) : + multiplicationForm H z (atom H q hmem a) (atom H q hmem a) = + diagonal H q hmem z a := rfl + +theorem form_atom_of_ne (z : Module.Dual F2 (squareSpace H)) {a b : A} (hab : a ≠ b) : + multiplicationForm H z (atom H q hmem a) (atom H q hmem b) = 0 := by + have hzero : productElement H (atom H q hmem a) (atom H q hmem b) = 0 := by + apply Subtype.ext + exact indicator_mul_of_ne q hab + simp only [multiplicationForm_apply, hzero, map_zero] + +theorem sum_diagonal [Fintype A] (z : Module.Dual F2 (squareSpace H)) + (hone : (1 : X → F2) ∈ squareSpace H) : + ∑ a, diagonal H q hmem z a = z ⟨1, hone⟩ := by + classical + simp only [diagonal, multiplicationForm_apply, ← map_sum] + congr 1 + apply Subtype.ext + simp only [Submodule.coe_sum] + change (∑ a, (indicator q a * indicator q a)) = (1 : X → F2) + simp only [indicator_mul_self, sum_indicator] + +theorem diagonal_support_card_le_rank [Fintype X] [Fintype A] + (z : Module.Dual F2 (squareSpace H)) : + (OddLists.support (diagonal H q hmem z)).card ≤ formRank H (multiplicationForm H z) := by + classical + let S := OddLists.support (diagonal H q hmem z) + let F := multiplicationForm H z + let v : S → LinearMap.range F := fun a => + ⟨F (atom H q hmem a.val), ⟨atom H q hmem a.val, rfl⟩⟩ + have hv : LinearIndependent F2 v := by + apply (Fintype.linearIndependent_iff (R := F2) (v := v)).mpr + intro c hc a + have he := congrArg (fun w : LinearMap.range F => w.val (atom H q hmem a.val)) hc + have hentry : ∀ b : S, (v b).val (atom H q hmem a.val) = if b = a then 1 else 0 := by + intro b + by_cases hba : b = a + · subst b + have ha : diagonal H q hmem z a.val = 1 := by + exact (Finset.mem_filter.mp a.property).2 + exact ha.trans (ite_eq_left rfl).symm + · have hne : b.val ≠ a.val := fun h => hba (Subtype.ext h) + exact (form_atom_of_ne H q hmem z hne).trans (ite_eq_right hba).symm + simpa only [map_sum, map_smul, Submodule.coe_sum, Submodule.coe_smul, + LinearMap.sum_apply, LinearMap.smul_apply, Submodule.coe_zero, + LinearMap.zero_apply, hentry, smul_eq_mul, mul_ite, mul_one, mul_zero, + Finset.sum_ite_eq', Finset.mem_univ, ite_true] using he + simpa only [Fintype.card_coe, S, F, formRank] using hv.fintype_card_le_finrank + +noncomputable def extractedList [Fintype X] [Fintype A] + (z : Module.Dual F2 (squareSpace H)) (hone : (1 : X → F2) ∈ squareSpace H) + (hnorm : z ⟨1, hone⟩ = 1) (s : Nat) + (hrank : formRank H (multiplicationForm H z) ≤ s) : OddLists.OddList s A := + ⟨OddLists.support (diagonal H q hmem z), + OddLists.support_odd_of_sum_one _ ((sum_diagonal H q hmem z hone).trans hnorm), + (diagonal_support_card_le_rank H q hmem z).trans hrank⟩ + +end Form + +section Projection + +variable [Fintype A] [Fintype B] +variable (H : Submodule F2 (X → F2)) (K : Submodule F2 (Y → F2)) +variable (q : X → A) (r : Y → B) +variable (hH : ∀ a, indicator q a ∈ H) (hK : ∀ b, indicator r b ∈ K) +variable (p : X → Y) (π : A → B) (hcomm : ∀ x, r (p x) = π (q x)) +variable (T : K →ₗ[F2] H) (hT : ∀ (f : K) x, (T f).val x = f.val (p x)) + +include hcomm hT + +omit [Fintype B] in +theorem atom_pullback (b : B) : + T (atom K r hK b) = ∑ a ∈ Finset.univ.filter (fun a => π a = b), atom H q hH a := by + classical + apply Subtype.ext + funext x + simp only [Submodule.coe_sum, Finset.sum_apply, hT, atom] + have h := congrFun (indicator_comp q π b) x + simpa only [indicator, Finset.sum_apply, Function.comp_apply, hcomm] using h + +omit [Fintype B] in +theorem projected_diagonal + (z : Module.Dual F2 (squareSpace H)) (F' : K →ₗ[F2] K →ₗ[F2] F2) + (hagree : ∀ f g, F' f g = multiplicationForm H z (T f) (T g)) (b : B) : + F' (atom K r hK b) (atom K r hK b) = + ∑ a ∈ Finset.univ.filter (fun a => π a = b), diagonal H q hH z a := by + classical + rw [hagree] + simp only [multiplicationForm_apply, diagonal, ← map_sum] + congr 1 + apply Subtype.ext + funext x + change (T (atom K r hK b)).val x * (T (atom K r hK b)).val x = _ + simp only [hT, atom, Submodule.coe_sum, Finset.sum_apply, productElement, + Pi.mul_apply] + have h := congrFun (indicator_comp q π b) x + simp only [Finset.sum_apply] at h + have hidem : ∀ a : A, indicator q a x * indicator q a x = indicator q a x := + fun a => congrFun (indicator_mul_self q a) x + simp only [hidem] + rw [← h] + simp only [indicator, Function.comp_apply, hcomm] + split_ifs <;> simp + +theorem projected_support + (z : Module.Dual F2 (squareSpace H)) (F' : K →ₗ[F2] K →ₗ[F2] F2) + (hagree : ∀ f g, F' f g = multiplicationForm H z (T f) (T g)) : + OddLists.support (fun b => F' (atom K r hK b) (atom K r hK b)) = + OddLists.parityPushforward π (OddLists.support (diagonal H q hH z)) := by + classical + rw [OddLists.parityPushforward_support] + congr 1 + funext b + rw [projected_diagonal H K q r hH hK p π hcomm T hT z F' hagree b] + exact Finset.sum_filter _ _ + +theorem local_extraction_accepts [Fintype X] + (z : Module.Dual F2 (squareSpace H)) (F' : K →ₗ[F2] K →ₗ[F2] F2) + (hagree : ∀ f g, F' f g = multiplicationForm H z (T f) (T g)) + (hone : (1 : X → F2) ∈ squareSpace H) (hnorm : z ⟨1, hone⟩ = 1) + (s : Nat) (positive : 0 < s) (hrank : formRank H (multiplicationForm H z) ≤ s) + (leftFallback : A) (rightFallback : B) : + OddLists.OddList.map π + (OddLists.OddList.extract positive leftFallback + (OddLists.support (diagonal H q hH z))) = + OddLists.OddList.extract positive rightFallback + (OddLists.support (fun b => F' (atom K r hK b) (atom K r hK b))) := by + classical + have hleft : Odd (OddLists.support (diagonal H q hH z)).card ∧ + (OddLists.support (diagonal H q hH z)).card ≤ s := + (extractedList H q hH z hone hnorm s hrank).property + have hsupport := projected_support H K q r hH hK p π hcomm T hT z F' hagree + have hright : + Odd (OddLists.support (fun b => F' (atom K r hK b) (atom K r hK b))).card ∧ + (OddLists.support (fun b => F' (atom K r hK b) (atom K r hK b))).card ≤ s := by + rw [hsupport] + exact ⟨OddLists.parityPushforward_odd π _ hleft.1, + (OddLists.parityPushforward_card_le π _).trans hleft.2⟩ + apply Subtype.ext + rw [OddLists.OddList.map_val, + OddLists.OddList.extract_valid positive leftFallback _ hleft, + OddLists.OddList.extract_valid positive rightFallback _ hright] + exact hsupport.symm + +end Projection + +private theorem parityPushforward_decidableEq_irrel [Fintype B] + (d₁ d₂ : DecidableEq B) (π : A → B) (L : Finset A) : + @OddLists.parityPushforward A B _ d₁ π L = + @OddLists.parityPushforward A B _ d₂ π L := + congrArg (fun d : DecidableEq B => @OddLists.parityPushforward A B _ d π L) + (Subsingleton.elim d₁ d₂) + +theorem source_projected_support {branch : Nat → Nat} {n t : Nat} + {slots projected : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot} + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (s : RecursiveSpaces.Slots branch n) + (z : Module.Dual F2 (squareSpace (TreeSourceSpaces.H slots))) + (F' : TreeSourceSpaces.H projected →ₗ[F2] TreeSourceSpaces.H projected →ₗ[F2] F2) + (hagree : ∀ f g, F' f g = multiplicationForm (TreeSourceSpaces.H slots) z + (TreeSourceSpaces.HPullback p f) (TreeSourceSpaces.HPullback p g)) : + OddLists.support (fun b => F' + (atom (TreeSourceSpaces.H projected) (fun x => x s) + (source_leaf_indicator_mem projected s) b) + (atom (TreeSourceSpaces.H projected) (fun x => x s) + (source_leaf_indicator_mem projected s) b)) = + OddLists.parityPushforward (MixedSupport.projectionMap (p s)) + (OddLists.support (diagonal (TreeSourceSpaces.H slots) (fun x => x s) + (source_leaf_indicator_mem slots s) z)) := by + have h := projected_support (TreeSourceSpaces.H slots) (TreeSourceSpaces.H projected) + (fun x => x s) (fun x => x s) (source_leaf_indicator_mem slots s) + (source_leaf_indicator_mem projected s) (TreeSourceSpaces.sourceProjection p) + (MixedSupport.projectionMap (p s)) (fun _ => rfl) + (TreeSourceSpaces.HPullback p) (fun _ _ => rfl) z F' hagree + exact h.trans (parityPushforward_decidableEq_irrel _ _ _ _) + +end PerfectCompleteness.OddListExtraction + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/OddLists.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/OddLists.lean new file mode 100644 index 0000000000000000000000000000000000000000..8920f1ef1947a401e2940a7b86f939a1e3ffe52e --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/OddLists.lean @@ -0,0 +1,227 @@ +import Mathlib.Algebra.BigOperators.Ring.Finset +import Mathlib.Data.Fintype.Powerset +import Mathlib.Data.ZMod.Basic + +namespace OAI + + +namespace PerfectCompleteness.OddLists + +open scoped BigOperators + +variable {A B : Type*} {s : Nat} + +abbrev OddList (s : Nat) (A : Type*) := + {L : Finset A // Odd L.card ∧ L.card ≤ s} + +namespace OddList + +theorem odd (L : OddList s A) : Odd L.val.card := L.property.1 + +theorem card_le (L : OddList s A) : L.val.card ≤ s := L.property.2 + +theorem card_pos (L : OddList s A) : 0 < L.val.card := by + apply Nat.pos_of_ne_zero + intro hzero + have hodd := L.odd + rw [hzero] at hodd + exact Nat.not_odd_zero hodd + +theorem nonempty (L : OddList s A) : L.val.Nonempty := + Finset.card_pos.mp L.card_pos + +def singleton (positive : 0 < s) (a : A) : OddList s A := + ⟨{a}, by + simp only [Finset.card_singleton] + exact ⟨odd_one, Nat.succ_le_of_lt positive⟩⟩ + +@[simp] theorem singleton_val (positive : 0 < s) (a : A) : + (singleton positive a).val = {a} := rfl + +theorem nonempty_type [Nonempty A] (positive : 0 < s) : Nonempty (OddList s A) := by + obtain ⟨a⟩ := ‹Nonempty A› + exact ⟨singleton positive a⟩ + +instance [Nonempty A] [NeZero s] : Nonempty (OddList s A) := + nonempty_type (Nat.pos_of_ne_zero (NeZero.ne s)) + +end OddList + +section Parity + +variable [Fintype B] [DecidableEq B] + +def parityPushforward (π : A → B) (L : Finset A) : Finset B := + Finset.univ.filter fun b => Odd ((L.filter fun a => π a = b).card) + +@[simp] theorem mem_parityPushforward (π : A → B) (L : Finset A) (b : B) : + b ∈ parityPushforward π L ↔ Odd ((L.filter fun a => π a = b).card) := by + simp only [parityPushforward, Finset.mem_filter, Finset.mem_univ, true_and] + +theorem parityPushforward_preimage (π : A → B) (L : Finset A) (b : B) + (member : b ∈ parityPushforward π L) : ∃ a ∈ L, π a = b := by + have hodd := (mem_parityPushforward π L b).mp member + have hpos : 0 < (L.filter fun a => π a = b).card := by + apply Nat.pos_of_ne_zero + intro hzero + rw [hzero] at hodd + exact Nat.not_odd_zero hodd + obtain ⟨a, ha⟩ := Finset.card_pos.mp hpos + exact ⟨a, (Finset.mem_filter.mp ha).1, (Finset.mem_filter.mp ha).2⟩ + +theorem parityPushforward_subset_image (π : A → B) (L : Finset A) : + parityPushforward π L ⊆ L.image π := by + intro b hb + obtain ⟨a, ha, hab⟩ := parityPushforward_preimage π L b hb + exact Finset.mem_image.mpr ⟨a, ha, hab⟩ + +theorem parityPushforward_card_le (π : A → B) (L : Finset A) : + (parityPushforward π L).card ≤ L.card := + (Finset.card_le_card (parityPushforward_subset_image π L)).trans Finset.card_image_le + +theorem sum_fiber_card (π : A → B) (L : Finset A) : + (∑ b : B, (L.filter fun a => π a = b).card) = L.card := by + simpa using Finset.sum_card_fiberwise_eq_card_filter L Finset.univ π + +theorem mod_two_eq_odd_indicator (n : Nat) : + n % 2 = if Odd n then 1 else 0 := by + by_cases hodd : Odd n + · rw [ite_eq_left hodd] + exact Nat.odd_iff.mp hodd + · rw [ite_eq_right hodd] + exact Nat.not_odd_iff.mp hodd + +theorem parityPushforward_card_mod_two (π : A → B) (L : Finset A) : + (parityPushforward π L).card % 2 = L.card % 2 := by + have hcount : (parityPushforward π L).card = + ∑ b : B, (L.filter fun a => π a = b).card % 2 := by + simp only [mod_two_eq_odd_indicator, Finset.sum_boole, parityPushforward, Nat.cast_id] + rw [hcount, ← Finset.sum_nat_mod, sum_fiber_card] + +theorem parityPushforward_odd (π : A → B) (L : Finset A) (odd : Odd L.card) : + Odd (parityPushforward π L).card := by + apply Nat.odd_iff.mpr + rw [parityPushforward_card_mod_two] + exact Nat.odd_iff.mp odd + +theorem mem_parityPushforward_iff_sum (π : A → B) (L : Finset A) (b : B) : + b ∈ parityPushforward π L ↔ + (∑ a ∈ L, if π a = b then (1 : ZMod 2) else 0) = 1 := by + rw [mem_parityPushforward, Finset.sum_boole] + exact ZMod.natCast_eq_one_iff_odd.symm + +namespace OddList + +def map (π : A → B) (L : OddList s A) : OddList s B := + ⟨parityPushforward π L.val, parityPushforward_odd π L.val L.odd, + (parityPushforward_card_le π L.val).trans L.card_le⟩ + +@[simp] theorem map_val (π : A → B) (L : OddList s A) : + (map π L).val = parityPushforward π L.val := rfl + +theorem exists_preimage (π : A → B) (L : OddList s A) (b : B) + (member : b ∈ (map π L).val) : ∃ a ∈ L.val, π a = b := + parityPushforward_preimage π L.val b member + +theorem exists_accepting_pair (π : A → B) (L : OddList s A) : + ∃ a ∈ L.val, ∃ b ∈ (map π L).val, π a = b := by + obtain ⟨b, hb⟩ := (map π L).nonempty + obtain ⟨a, ha, hab⟩ := exists_preimage π L b hb + exact ⟨a, ha, b, hb, hab⟩ + +theorem exists_accepting_pair_of_eq (π : A → B) (L : OddList s A) (R : OddList s B) + (accepted : map π L = R) : ∃ a ∈ L.val, ∃ b ∈ R.val, π a = b := by + rw [← accepted] + exact exists_accepting_pair π L + +end OddList +end Parity + +section Supports + +variable [Fintype A] + +def support (f : A → ZMod 2) : Finset A := + Finset.univ.filter fun a => f a = 1 + +@[simp] theorem mem_support (f : A → ZMod 2) (a : A) : + a ∈ support f ↔ f a = 1 := by + simp only [support, Finset.mem_filter, Finset.mem_univ, true_and] + +private theorem binary_cases (x : ZMod 2) : x = 0 ∨ x = 1 := by + have h : ∀ z : ZMod 2, z = 0 ∨ z = 1 := by decide + exact h x + +theorem support_card_cast (f : A → ZMod 2) : + ((support f).card : ZMod 2) = ∑ a, f a := by + unfold support + rw [Finset.natCast_card_filter] + apply Finset.sum_congr rfl + intro a _ + rcases binary_cases (f a) with hzero | hone + · simp only [hzero, zero_ne_one, ite_false] + · simp only [hone, ite_true] + +theorem support_odd_of_sum_one (f : A → ZMod 2) (normalized : (∑ a, f a) = 1) : + Odd (support f).card := + ZMod.natCast_eq_one_iff_odd.mp ((support_card_cast f).trans normalized) + +theorem parityPushforward_support [Fintype B] [DecidableEq B] + (π : A → B) (f : A → ZMod 2) : + parityPushforward π (support f) = + support (fun b => ∑ a, if π a = b then f a else 0) := by + ext b + rw [mem_parityPushforward_iff_sum, mem_support] + have hsum : (∑ a ∈ support f, if π a = b then (1 : ZMod 2) else 0) = + ∑ a, if π a = b then f a else 0 := by + unfold support + rw [Finset.sum_filter] + apply Finset.sum_congr rfl + intro a _ + rcases binary_cases (f a) with hzero | hone + · simp [hzero] + · simp [hone] + rw [hsum] + +end Supports + +namespace OddList + +def extract (positive : 0 < s) (fallback : A) (candidate : Finset A) : OddList s A := + if valid : Odd candidate.card ∧ candidate.card ≤ s then + ⟨candidate, valid⟩ else singleton positive fallback + +@[simp] theorem extract_valid (positive : 0 < s) (fallback : A) (candidate : Finset A) + (valid : Odd candidate.card ∧ candidate.card ≤ s) : + (extract positive fallback candidate).val = candidate := by + simp only [extract, dite_eq_left valid] + +theorem extract_invalid (positive : 0 < s) (fallback : A) (candidate : Finset A) + (invalid : ¬ (Odd candidate.card ∧ candidate.card ≤ s)) : + (extract positive fallback candidate).val = {fallback} := by + simp only [extract, dite_eq_right invalid, singleton_val] + +def extractOption (positive : 0 < s) (fallback : A) : Option (Finset A) → OddList s A + | none => singleton positive fallback + | some candidate => extract positive fallback candidate + +@[simp] theorem extractOption_none (positive : 0 < s) (fallback : A) : + (extractOption positive fallback none).val = {fallback} := rfl + +@[simp] theorem extractOption_some_valid (positive : 0 < s) (fallback : A) + (candidate : Finset A) (valid : Odd candidate.card ∧ candidate.card ≤ s) : + (extractOption positive fallback (some candidate)).val = candidate := + extract_valid positive fallback candidate valid + +noncomputable def defaultList [Nonempty A] (positive : 0 < s) : OddList s A := + singleton positive (Classical.choice ‹Nonempty A›) + +noncomputable def extractDefault [Nonempty A] (positive : 0 < s) + (candidate : Option (Finset A)) : OddList s A := + extractOption positive (Classical.choice ‹Nonempty A›) candidate + +end OddList + +end PerfectCompleteness.OddLists + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/OriginalBelowCut.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/OriginalBelowCut.lean new file mode 100644 index 0000000000000000000000000000000000000000..e886870a51531b9376dacccaa5f8ef78e0745421 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/OriginalBelowCut.lean @@ -0,0 +1,136 @@ +import OAI.Computability.PerfectCompleteness.Construction.SourceQuestionOrderLemmas +import OAI.Computability.PerfectCompleteness.Sampling.WholeArrayProductLaw + +namespace OAI + +section + +namespace PerfectCompleteness.OriginalBelowCut + +open TreeSourceSpaces HierarchicalArrays DescendantSpaces WholeArraySampler +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +noncomputable section + +variable {branch : Nat → Nat} {n m t : Nat} + +def below (rows repeats : Nat → Nat) (chosen : Fin (branch n)) + (q : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ω : Tape rows repeats (.step chosen q) slots) : + (child : Fin (branch n)) → Arrays (childSlots slots child) rows := + fun child node => WholeArraySampler.evaluate rows repeats (.step chosen q) slots ω + (.inr (child, node)) + +@[simp] theorem below_selected (rows repeats : Nat → Nat) (chosen : Fin (branch n)) + (q : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ω : Tape rows repeats (.step chosen q) slots) : + below rows repeats chosen q slots ω chosen = + WholeArraySampler.evaluate rows repeats q (childSlots slots chosen) + (ω (.inr (.inl ()))) := by + funext node + exact WholeArraySampler.evaluate_selected rows repeats chosen q slots ω node + +@[simp] theorem below_ordinary (rows repeats : Nat → Nat) (chosen : Fin (branch n)) + (q : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ω : Tape rows repeats (.step chosen q) slots) (j : RecursiveSampler.OffPath chosen) : + below rows repeats chosen q slots ω j.val = ω (.inr (.inr j)) := by + funext node + exact WholeArraySampler.evaluate_ordinary rows repeats chosen q slots ω j node + +def stepObservable (rows repeats : Nat → Nat) (chosen : Fin (branch n)) + (q : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (f : (child : Fin (branch n)) → Arrays (childSlots slots child) rows → ℝ) : + (k : StepIndex chosen) → + StepFactor (RootTape rows repeats (.step chosen q) slots) + (Tape rows repeats q (childSlots slots chosen)) + (fun j => Arrays (childSlots slots j.val) rows) k → ℝ + | .inl _, _ => 1 + | .inr (.inl _), ω => + f chosen (WholeArraySampler.evaluate rows repeats q (childSlots slots chosen) ω) + | .inr (.inr j), arrays => f j.val arrays + +theorem prod_below (rows repeats : Nat → Nat) (chosen : Fin (branch n)) + (q : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (f : (child : Fin (branch n)) → Arrays (childSlots slots child) rows → ℝ) + (ω : Tape rows repeats (.step chosen q) slots) : + (∏ child, f child (below rows repeats chosen q slots ω child)) = + ∏ k : StepIndex chosen, stepObservable rows repeats chosen q slots f k (ω k) := by + rw [Fintype.prod_eq_mul_prod_subtype_ne + (fun child => f child (below rows repeats chosen q slots ω child)) chosen, + WholeArrayProductLaw.prod_stepIndex chosen] + simp only [stepObservable, one_mul, below_selected, below_ordinary] + +theorem expectation_product (rows repeats : Nat → Nat) (chosen : Fin (branch n)) + (q : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (f : (child : Fin (branch n)) → Arrays (childSlots slots child) rows → ℝ) : + (WholeArraySampler.tapeLaw rows repeats (.step chosen q) slots).expectation + (fun ω => ∏ child, f child (below rows repeats chosen q slots ω child)) = + ∏ child, (ChildBlockMixture.component + (fun j => WholeArraySampler.law rows repeats q (childSlots slots j)) + chosen child).expectation (f child) := by + calc + _ = (WholeArraySampler.tapeLaw rows repeats (.step chosen q) slots).expectation + (fun ω => ∏ k : StepIndex chosen, + stepObservable rows repeats chosen q slots f k (ω k)) := + FiniteDistribution.expectation_congr _ (prod_below rows repeats chosen q slots f) + _ = ∏ k : StepIndex chosen, (componentLaw rows repeats chosen q slots k).expectation + (stepObservable rows repeats chosen q slots f k) := + WholeArraySampler.components_expectation_product rows repeats chosen q slots _ + _ = _ := by + let Q : (child : Fin (branch n)) → + FiniteDistribution (Arrays (childSlots slots child) rows) := + fun child => WholeArraySampler.law rows repeats q (childSlots slots child) + let L : StepIndex chosen → ℝ := fun k => + (componentLaw rows repeats chosen q slots k).expectation + (stepObservable rows repeats chosen q slots f k) + let R : Fin (branch n) → ℝ := fun child => + (ChildBlockMixture.component Q chosen child).expectation (f child) + change (∏ k, L k) = ∏ child, R child + have hroot : L (.inl ()) = 1 := + SmallBias.expectation_const _ 1 + have hselected : L (.inr (.inl ())) = R chosen := by + change (WholeArraySampler.tapeLaw rows repeats q (childSlots slots chosen)).expectation + (fun ω => f chosen (WholeArraySampler.evaluate rows repeats q + (childSlots slots chosen) ω)) = + (ChildBlockMixture.component Q chosen chosen).expectation (f chosen) + simp only [ChildBlockMixture.component] + exact (FiniteDistribution.expectation_pushforward + (WholeArraySampler.tapeLaw rows repeats q (childSlots slots chosen)) + (WholeArraySampler.evaluate rows repeats q (childSlots slots chosen)) + (f chosen)).symm + have hordinary (j : RecursiveSampler.OffPath chosen) : + L (.inr (.inr j)) = R j.val := by + change (FiniteDistribution.uniform (Arrays (childSlots slots j.val) rows)).expectation + (f j.val) = (ChildBlockMixture.component Q chosen j.val).expectation (f j.val) + simp only [ChildBlockMixture.component, dite_eq_right (Ne.symm j.property)] + rw [WholeArrayProductLaw.prod_stepIndex chosen, hroot, one_mul, hselected, + Fintype.prod_eq_mul_prod_subtype_ne R chosen] + exact congrArg (fun z : ℝ => R chosen * z) + (Finset.prod_congr rfl (fun j _ => hordinary j)) + +theorem below_pushforward (rows repeats : Nat → Nat) (chosen : Fin (branch n)) + (q : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) : + (WholeArraySampler.tapeLaw rows repeats (.step chosen q) slots).pushforward + (below rows repeats chosen q slots) = + FiniteProduct.law (ChildBlockMixture.component + (fun child => WholeArraySampler.law rows repeats q (childSlots slots child)) chosen) := by + apply WholeArrayProductLaw.eq_law_of_expectation_product + intro f + rw [FiniteDistribution.expectation_pushforward] + exact expectation_product rows repeats chosen q slots f + +end + +end PerfectCompleteness.OriginalBelowCut + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/OriginalExtraCutComparison.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/OriginalExtraCutComparison.lean new file mode 100644 index 0000000000000000000000000000000000000000..3409c26ecf0da38335000caa8204c7d7eae0a745 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/OriginalExtraCutComparison.lean @@ -0,0 +1,105 @@ +import OAI.Computability.PerfectCompleteness.Foundations.ExtraCutCall +import OAI.Computability.PerfectCompleteness.Foundations.OriginalPrefixContinuation +import OAI.Computability.PerfectCompleteness.Sampling.CommonProductVariationLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.OriginalExtraCutComparison + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCutTape OriginalWholeCutLaw +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators + +noncomputable section + +private theorem product_mixture_pushforward {E A B Γ : Type*} + [Fintype E] [Fintype A] [Fintype B] [Fintype Γ] + (μ : FiniteDistribution A) (κ : FiniteDistribution E) + (ν : E → FiniteDistribution B) (f : A × B → Γ) : + (μ.product (κ.mixture ν)).pushforward f = + κ.mixture (fun e => (μ.product (ν e)).pushforward f) := by + have hp : μ.product (κ.mixture ν) = κ.mixture (fun e => μ.product (ν e)) := by + apply FiniteDistribution.eq_of_weight_eq + intro x + simp only [FiniteDistribution.product, FiniteDistribution.mixture, Finset.mul_sum] + apply Finset.sum_congr rfl + intro e _ + exact mul_left_comm _ _ _ + rw [hp, FiniteDistribution.pushforward_mixture] + +variable {branch : Nat → Nat} {n m k t : Nat} {K : Type*} [Fintype K] + +abbrev Record (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) := + OriginalWholeCutBridge.NumberedRecord rows repeats p slots × H (cutSlots p slots) + +def actualLaw (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (ν : FiniteDistribution K) (q : K → Path branch m k) (hbranch : 0 < branch m) : + FiniteDistribution (Record rows repeats p slots) := + ((exteriorLaw rows repeats p slots).product + (OriginalPrefixContinuation.assembledLaw + (OriginalCutCalls.count rows repeats n (m + 1) + 1) + rows repeats (cutSlots p slots) ν q hbranch)).pushforward + (ExtraCutCall.splitRecord rows repeats p slots) + +attribute [local instance 2000] OriginalWholeCutLaw.valuesBelowFintype + +def referenceLaw (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + FiniteDistribution (Record rows repeats p slots) := + ((OriginalUniformCut.referenceLaw rows repeats p slots).pushforward + (OriginalWholeCutBridge.numberRecord rows repeats p slots)).product + (FiniteDistribution.uniform (H (cutSlots p slots))) + +theorem actualLaw_eq_mixture (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (ν : FiniteDistribution K) (q : K → Path branch m k) (hbranch : 0 < branch m) : + actualLaw rows repeats p slots ν q hbranch = + (OriginalPrefixContinuation.tagLaw ν hbranch).mixture (fun tag => + ((recordLaw rows repeats p tag.1 (q tag.2) slots).pushforward + (OriginalWholeCutBridge.numberRecord rows repeats p slots)).product + (RecursiveSampler.law F2 repeats (.step tag.1 (q tag.2)) + (LeafDomain (cutSlots p slots)))) := by + unfold actualLaw + rw [OriginalPrefixContinuation.assembledLaw_eq_mixture, product_mixture_pushforward] + apply congrArg ((OriginalPrefixContinuation.tagLaw ν hbranch).mixture) + funext tag + exact ExtraCutCall.record_fresh_law rows repeats p tag.1 (q tag.2) slots + +theorem totalVariation_le (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (ν : FiniteDistribution K) (q : K → Path branch m k) (hbranch : 0 < branch m) : + (actualLaw rows repeats p slots ν q hbranch).totalVariation + (referenceLaw rows repeats p slots) ≤ + Real.sqrt ((ChildBlockCardinality.bound branch m t + (OriginalCutCalls.count rows repeats n (m + 1) + 1) rows : ℝ) ^ 2 / branch m) / 2 := by + unfold actualLaw referenceLaw + rw [← ExtraCutCall.uniform_record_fresh_law rows repeats p slots] + exact CommonProductVariation.observed_product_le_of_bound + (exteriorLaw rows repeats p slots) _ _ (ExtraCutCall.splitRecord rows repeats p slots) + (OriginalPrefixContinuation.assembledLaw_variation + (OriginalCutCalls.count rows repeats n (m + 1) + 1) + rows repeats (cutSlots p slots) ν q hbranch) + +theorem observed_totalVariation_le {D Γ : Type*} [Fintype D] [Fintype Γ] + (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (ν : FiniteDistribution K) (q : K → Path branch m k) (hbranch : 0 < branch m) + (directions : FiniteDistribution D) (observe : D × Record rows repeats p slots → Γ) : + ((directions.product (actualLaw rows repeats p slots ν q hbranch)).pushforward observe).totalVariation + ((directions.product (referenceLaw rows repeats p slots)).pushforward observe) ≤ + Real.sqrt ((ChildBlockCardinality.bound branch m t + (OriginalCutCalls.count rows repeats n (m + 1) + 1) rows : ℝ) ^ 2 / branch m) / 2 := + CommonProductVariation.observed_product_le_of_bound directions _ _ observe + (totalVariation_le rows repeats p slots ν q hbranch) + +end +end PerfectCompleteness.OriginalExtraCutComparison + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/OriginalHiddenConditional.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/OriginalHiddenConditional.lean new file mode 100644 index 0000000000000000000000000000000000000000..68b3e0e06ad42454ee3a62c228dbf05c8fd55149 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/OriginalHiddenConditional.lean @@ -0,0 +1,60 @@ +import OAI.Computability.PerfectCompleteness.Construction.OriginalHiddenChild +import OAI.Computability.PerfectCompleteness.Foundations.DependentPredictionDifferenceLemmas +import OAI.Computability.PerfectCompleteness.Sampling.CommonProductVariationLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.OriginalHiddenConditional + +open RecursiveSpaces TreeSourceSpaces +open UniqueGamesTheorem.Foundations.Games CompletionSoundness + +noncomputable section + +variable {S : Type*} [Fintype S] {branch : Nat → Nat} {n t : Nat} + +theorem observed_variation {Γ : Type*} [Fintype Γ] + (calls : Nat) (rows repeats : Nat → Nat) + (slots : S → Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (μ : FiniteDistribution S) (hbranch : ∀ k < n + 1, 0 < branch k) + (observe : (Σ s : S, CutChildGrouping.Assembled (C := Fin calls) (slots s) rows) → Γ) : + ((sigmaLaw μ (fun s => OriginalHiddenChild.sourceLaw calls rows repeats (slots s) hbranch)).pushforward (fun z => observe ⟨z.1, + OriginalHiddenChild.observed calls rows repeats (slots z.1) z.2⟩)).totalVariation + ((sigmaLaw μ (fun s => FiniteDistribution.uniform + (CutChildGrouping.Assembled (C := Fin calls) (slots s) rows))).pushforward observe) ≤ + Real.sqrt ((ChildBlockCardinality.bound branch n t calls rows : ℝ) ^ 2 / + branch n) / 2 := by + have hleft : + (sigmaLaw μ (fun s => OriginalHiddenChild.sourceLaw calls rows repeats (slots s) hbranch)).pushforward (fun z => observe ⟨z.1, + OriginalHiddenChild.observed calls rows repeats (slots z.1) z.2⟩) = + (sigmaLaw μ (fun s => + (OriginalHiddenChild.sourceLaw calls rows repeats (slots s) hbranch).pushforward + (OriginalHiddenChild.observed calls rows repeats (slots s)))).pushforward observe := by + calc + _ = ((sigmaLaw μ (fun s => + OriginalHiddenChild.sourceLaw calls rows repeats (slots s) hbranch)).pushforward + (fun z => (⟨z.1, OriginalHiddenChild.observed calls rows repeats (slots z.1) z.2⟩ : + Σ s : S, CutChildGrouping.Assembled (C := Fin calls) (slots s) rows))).pushforward observe := (FiniteDistribution.pushforward_comp _ _ _).symm + _ = _ := congrArg + (fun law : FiniteDistribution + (Σ s : S, CutChildGrouping.Assembled (C := Fin calls) (slots s) rows) => + law.pushforward observe) + (SigmaObservation.pushforward_fiber + (X := fun s => OriginalHiddenChild.Tape calls rows repeats (slots s)) + (Y := fun s => CutChildGrouping.Assembled (C := Fin calls) (slots s) rows) + μ (fun s => OriginalHiddenChild.sourceLaw calls rows repeats (slots s) hbranch) + (fun s => OriginalHiddenChild.observed calls rows repeats (slots s))) + rw [hleft] + apply ConditionalVariation.observed_sigma_le_const + intro s + simpa only [id_eq, FiniteDistribution.pushforward_id] using + OriginalHiddenChild.observed_variation calls rows repeats (slots s) hbranch id + +end +end PerfectCompleteness.OriginalHiddenConditional + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/OriginalPrefixContinuation.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/OriginalPrefixContinuation.lean new file mode 100644 index 0000000000000000000000000000000000000000..d18b9a151a5d3626c0d15c78b3a31307fd10ef6b --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/OriginalPrefixContinuation.lean @@ -0,0 +1,245 @@ +import OAI.Computability.PerfectCompleteness.Construction.OriginalChildBlocks +import OAI.Computability.PerfectCompleteness.Construction.SourceQuestionOrderLemmas +import OAI.Computability.PerfectCompleteness.Foundations.GeometricPathLemmas +import OAI.Computability.PerfectCompleteness.Reduction.CompletionSoundness + +namespace OAI + +section + +namespace PerfectCompleteness.OriginalPrefixContinuation + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +noncomputable section + +private theorem sigmaLaw_pushforward {E Γ : Type*} {F : E → Type*} + [Fintype E] [∀ e, Fintype (F e)] [Fintype Γ] + (μ : FiniteDistribution E) (ν : ∀ e, FiniteDistribution (F e)) + (f : ∀ e, F e → Γ) : + (CompletionSoundness.sigmaLaw μ ν).pushforward (fun x => f x.1 x.2) = + μ.mixture (fun e => (ν e).pushforward (f e)) := by + apply FiniteDistribution.eq_of_weight_eq + intro z + simp only [FiniteDistribution.pushforward, CompletionSoundness.sigmaLaw, + FiniteDistribution.mixture, Fintype.sum_sigma, Finset.mul_sum, mul_ite, mul_zero] + +private theorem product_mixture {E F Γ : Type*} + [Fintype E] [Fintype F] [Fintype Γ] + (μ : FiniteDistribution E) (ν : FiniteDistribution F) + (R : E × F → FiniteDistribution Γ) : + (μ.product ν).mixture R = μ.mixture (fun e => ν.mixture (fun f => R (e, f))) := by + apply FiniteDistribution.eq_of_weight_eq + intro z + simp only [FiniteDistribution.mixture, FiniteDistribution.product, + Fintype.sum_prod_type, Finset.mul_sum, mul_assoc] + +variable {branch : Nat → Nat} {n k t : Nat} {K : Type*} [Fintype K] + +abbrev Blocks (calls : Nat) (rows : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) := + (child : Fin (branch n)) → ChildBlockCardinality.Raw calls rows (childSlots slots child) + +abbrev Tape (calls : Nat) (rows repeats : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (q : K → Path branch n k) := + Σ tag : Fin (branch n) × K, OriginalChildBlocks.SourceTape calls rows repeats + tag.1 (q tag.2) slots + +def tagLaw (ν : FiniteDistribution K) (hbranch : 0 < branch n) : + FiniteDistribution (Fin (branch n) × K) := by + letI : Nonempty (Fin (branch n)) := ⟨⟨0, hbranch⟩⟩ + exact (FiniteDistribution.uniform (Fin (branch n))).product ν + +def sourceLaw (calls : Nat) (rows repeats : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ν : FiniteDistribution K) (q : K → Path branch n k) + (hbranch : 0 < branch n) : + FiniteDistribution (Tape calls rows repeats slots q) := + CompletionSoundness.sigmaLaw (tagLaw ν hbranch) + (fun tag => OriginalChildBlocks.sourceLaw calls rows repeats tag.1 (q tag.2) slots) + +def rawMap (calls : Nat) (rows repeats : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (q : K → Path branch n k) (ω : Tape calls rows repeats slots q) : Blocks calls rows slots := + OriginalChildBlocks.rawMap calls rows repeats ω.1.1 + (q ω.1.2) slots ω.2 + +def averagedSpecial (calls : Nat) (rows repeats : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ν : FiniteDistribution K) (q : K → Path branch n k) + (_ : 0 < branch n) (child : Fin (branch n)) : + FiniteDistribution (ChildBlockCardinality.Raw calls rows (childSlots slots child)) := + ν.mixture (fun tag => OriginalChildBlocks.specialLaw calls rows repeats (q tag) slots child) + +def blockMixture (calls : Nat) (rows repeats : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ν : FiniteDistribution K) (q : K → Path branch n k) + (hbranch : 0 < branch n) : FiniteDistribution (Blocks calls rows slots) := by + letI : Nonempty (Fin (branch n)) := ⟨⟨0, hbranch⟩⟩ + exact ChildBlockMixture.mixture (averagedSpecial calls rows repeats slots ν q hbranch) + +omit [Fintype K] in +private theorem special_as_continued (calls : Nat) (rows repeats : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (q : K → Path branch n k) (chosen : Fin (branch n)) (tag : K) : + ChildBlockMixture.special + (OriginalChildBlocks.specialLaw calls rows repeats (q tag) slots) + chosen = + ChildBlockContinuation.continuedSpecial + (fun child tag => OriginalChildBlocks.specialLaw calls rows repeats + (q tag) slots child) chosen tag := by + let : Nonempty (Fin (branch n)) := ⟨chosen⟩ + apply FiniteDistribution.eq_of_weight_eq + intro x + rw [ChildBlockMixture.special_weight, ChildBlockContinuation.continuedSpecial_weight] + +theorem rawMap_law (calls : Nat) (rows repeats : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ν : FiniteDistribution K) (q : K → Path branch n k) + (hbranch : 0 < branch n) : + (sourceLaw calls rows repeats slots ν q hbranch).pushforward (rawMap calls rows repeats slots q) = + blockMixture calls rows repeats slots ν q hbranch := by + let : Nonempty (Fin (branch n)) := ⟨⟨0, hbranch⟩⟩ + refine (sigmaLaw_pushforward + (E := Fin (branch n) × K) (Γ := Blocks calls rows slots) + (tagLaw ν hbranch) + (fun tag => OriginalChildBlocks.sourceLaw calls rows repeats tag.1 (q tag.2) slots) + (fun tag tape => OriginalChildBlocks.rawMap calls rows repeats tag.1 + (q tag.2) slots tape)).trans ?_ + simp_rw [OriginalChildBlocks.rawMap_law] + rw [tagLaw, product_mixture] + simp_rw [special_as_continued] + exact ChildBlockContinuation.uniform_average + (fun _ : Fin (branch n) => ν) + (fun child tag => OriginalChildBlocks.specialLaw calls rows repeats + (q tag) slots child) + +theorem rawMap_eq_mixture [Nonempty (Fin (branch n))] + (calls : Nat) (rows repeats : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ν : FiniteDistribution K) (q : K → Path branch n k) + (hbranch : 0 < branch n) : + (sourceLaw calls rows repeats slots ν q hbranch).pushforward (rawMap calls rows repeats slots q) = + ChildBlockMixture.mixture (averagedSpecial calls rows repeats slots ν q hbranch) := + rawMap_law calls rows repeats slots ν q hbranch + +def observed (calls : Nat) (rows repeats : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (q : K → Path branch n k) (ω : Tape calls rows repeats slots q) : CutChildGrouping.Assembled (C := Fin calls) slots rows := + OriginalChildBlocks.observed calls rows repeats ω.1.1 + (q ω.1.2) slots ω.2 + +omit [Fintype K] in +theorem assemble_rawMap (calls : Nat) (rows repeats : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (q : K → Path branch n k) (ω : Tape calls rows repeats slots q) : + CutChildGrouping.assemble slots rows (rawMap calls rows repeats slots q ω) = + observed calls rows repeats slots q ω := + OriginalChildBlocks.assemble_rawMap calls rows repeats ω.1.1 + (q ω.1.2) slots ω.2 + +theorem observed_law (calls : Nat) (rows repeats : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ν : FiniteDistribution K) (q : K → Path branch n k) + (hbranch : 0 < branch n) : + (sourceLaw calls rows repeats slots ν q hbranch).pushforward (observed calls rows repeats slots q) = + (blockMixture calls rows repeats slots ν q hbranch).pushforward + (CutChildGrouping.assemble slots rows) := by + rw [← rawMap_law calls rows repeats slots ν q hbranch, FiniteDistribution.pushforward_comp] + congr 1 + funext ω + exact (assemble_rawMap calls rows repeats slots q ω).symm + +theorem raw_observed_variation {Γ : Type*} [Fintype Γ] + (calls : Nat) (rows repeats : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ν : FiniteDistribution K) (q : K → Path branch n k) + (hbranch : 0 < branch n) (observe : Blocks calls rows slots → Γ) : + ((sourceLaw calls rows repeats slots ν q hbranch).pushforward + (fun ω => observe (rawMap calls rows repeats slots q ω))).totalVariation + ((ChildBlockMixture.reference (Ω := fun child : Fin (branch n) => + ChildBlockCardinality.Raw calls rows (childSlots slots child))).pushforward observe) ≤ + Real.sqrt ((ChildBlockCardinality.bound branch n t calls rows : ℝ) ^ 2 / + branch n) / 2 := by + let : Nonempty (Fin (branch n)) := ⟨⟨0, hbranch⟩⟩ + have hpush : (sourceLaw calls rows repeats slots ν q hbranch).pushforward + (fun ω => observe (rawMap calls rows repeats slots q ω)) = + (blockMixture calls rows repeats slots ν q hbranch).pushforward observe := by + rw [← rawMap_law calls rows repeats slots ν q hbranch] + exact (FiniteDistribution.pushforward_comp _ _ _).symm + rw [hpush] + simpa only [blockMixture, Fintype.card_fin] using + (ChildBlockMixture.actual_observed_variation calls rows + (fun child => childSlots slots child) + (averagedSpecial calls rows repeats slots ν q hbranch) observe) + +theorem observed_variation {Γ : Type*} [Fintype Γ] + (calls : Nat) (rows repeats : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ν : FiniteDistribution K) (q : K → Path branch n k) + (hbranch : 0 < branch n) + (observe : CutChildGrouping.Assembled (C := Fin calls) slots rows → Γ) : + ((sourceLaw calls rows repeats slots ν q hbranch).pushforward + (fun ω => observe (observed calls rows repeats slots q ω))).totalVariation + ((FiniteDistribution.uniform (CutChildGrouping.Assembled (C := Fin calls) slots rows)).pushforward + observe) ≤ + Real.sqrt ((ChildBlockCardinality.bound branch n t calls rows : ℝ) ^ 2 / + branch n) / 2 := by + have hclean : (ChildBlockMixture.reference (Ω := fun child : Fin (branch n) => + ChildBlockCardinality.Raw calls rows (childSlots slots child))).pushforward + (fun x => observe (CutChildGrouping.assemble slots rows x)) = + (FiniteDistribution.uniform (CutChildGrouping.Assembled (C := Fin calls) slots rows)).pushforward + observe := by + rw [← FiniteDistribution.pushforward_comp] + have h := CutChildGrouping.assemble_law (C := Fin calls) slots rows + change (ChildBlockMixture.reference (Ω := fun child : Fin (branch n) => + ChildBlockCardinality.Raw calls rows (childSlots slots child))).pushforward + (CutChildGrouping.assemble slots rows) = _ at h + rw [h] + have h := raw_observed_variation calls rows repeats slots ν q hbranch + (fun x => observe (CutChildGrouping.assemble slots rows x)) + simpa only [assemble_rawMap, hclean] using h + +def assembledLaw (calls : Nat) (rows repeats : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ν : FiniteDistribution K) (q : K → Path branch n k) (hbranch : 0 < branch n) : + FiniteDistribution (CutChildGrouping.Assembled (C := Fin calls) slots rows) := + (sourceLaw calls rows repeats slots ν q hbranch).pushforward + (observed calls rows repeats slots q) + +theorem assembledLaw_eq_mixture (calls : Nat) (rows repeats : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ν : FiniteDistribution K) (q : K → Path branch n k) (hbranch : 0 < branch n) : + assembledLaw calls rows repeats slots ν q hbranch = + (tagLaw ν hbranch).mixture (fun tag => + (OriginalChildBlocks.sourceLaw calls rows repeats tag.1 (q tag.2) slots).pushforward + (OriginalChildBlocks.observed calls rows repeats tag.1 (q tag.2) slots)) := by + exact sigmaLaw_pushforward + (E := Fin (branch n) × K) + (Γ := CutChildGrouping.Assembled (C := Fin calls) slots rows) + (tagLaw ν hbranch) + (fun tag => OriginalChildBlocks.sourceLaw calls rows repeats tag.1 (q tag.2) slots) + (fun tag tape => OriginalChildBlocks.observed calls rows repeats tag.1 + (q tag.2) slots tape) + +theorem assembledLaw_variation (calls : Nat) (rows repeats : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ν : FiniteDistribution K) (q : K → Path branch n k) (hbranch : 0 < branch n) : + (assembledLaw calls rows repeats slots ν q hbranch).totalVariation + (FiniteDistribution.uniform (CutChildGrouping.Assembled (C := Fin calls) slots rows)) ≤ + Real.sqrt ((ChildBlockCardinality.bound branch n t calls rows : ℝ) ^ 2 / + branch n) / 2 := by + simpa only [id_eq, FiniteDistribution.pushforward_id, assembledLaw] using + observed_variation calls rows repeats slots ν q hbranch + (id : CutChildGrouping.Assembled (C := Fin calls) slots rows → + CutChildGrouping.Assembled (C := Fin calls) slots rows) + +end +end PerfectCompleteness.OriginalPrefixContinuation + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/OriginalTerminalSplitLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/OriginalTerminalSplitLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..8afea514bc878bfa1ebeb722d50e14e116c868b2 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/OriginalTerminalSplitLemmas.lean @@ -0,0 +1,238 @@ +import Mathlib.Logic.Equiv.Prod +import OAI.Computability.PerfectCompleteness.Foundations.TerminalCalls +import OAI.Computability.PerfectCompleteness.Sampling.SamplerCompositionLaws +import OAI.Computability.UniqueGames.Foundations.SamplingLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.OriginalTerminalSplit + +open RecursiveSpaces DescendantSpaces RecursiveSampler TerminalCalls SamplerComposition +open UniqueGamesTheorem.Foundations.Games +open scoped Classical + +noncomputable section + +universe u w + +variable {branch : Nat → Nat} {n m k : Nat} + +theorem expansionSpace_terminal (𝕜 : Type w) [Field 𝕜] + (repeats : Nat → Nat) (p : Path branch n m) : + ∀ (q : Path branch m k) (A : Slots branch n → Type u) + (terminal : TerminalIndex repeats p), + ExpansionSpace 𝕜 repeats p q A (drawIndex repeats p terminal) = + RecursiveSampler.Tape 𝕜 repeats q (p.family A) := by + induction p with + | refl n => intro q A terminal; rfl + | step i p ih => + intro q A terminal + exact ih q (childFamily A i) terminal.2 + +theorem expansionSpace_exterior (𝕜 : Type w) [Field 𝕜] + (repeats : Nat → Nat) (p : Path branch n m) : + ∀ (q : Path branch m k) (A : Slots branch n → Type u) + (j : DrawIndex repeats p), ¬ IsTerminal repeats p j → + ExpansionSpace 𝕜 repeats p q A j = DrawSpace 𝕜 repeats p A j := by + induction p with + | refl n => + intro q A j hj + exact False.elim (hj True.intro) + | step i p ih => + intro q A j hj + cases j with + | inl j => rfl + | inr j => exact ih q (childFamily A i) j.2 hj + +variable (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) + (p : Path branch n m) (q : Path branch m k) (A : Slots branch n → Type u) + +abbrev ExteriorIndex := {j : DrawIndex repeats p // ¬ IsTerminal repeats p j} + +abbrev ExteriorTape := (j : ExteriorIndex repeats p) → DrawSpace 𝕜 repeats p A j.val + +abbrev TerminalTape := + TerminalIndex repeats p → RecursiveSampler.Tape 𝕜 repeats q (p.family A) + +def terminalFactorEquiv (terminal : TerminalIndex repeats p) : + ExpansionSpace 𝕜 repeats p q A (drawIndex repeats p terminal) ≃ + RecursiveSampler.Tape 𝕜 repeats q (p.family A) := + Equiv.cast (expansionSpace_terminal 𝕜 repeats p q A terminal) + +def exteriorFactorEquiv (j : ExteriorIndex repeats p) : + ExpansionSpace 𝕜 repeats p q A j.val ≃ DrawSpace 𝕜 repeats p A j.val := + Equiv.cast (expansionSpace_exterior 𝕜 repeats p q A j.val j.property) + +def terminalTapeEquiv : + ((j : {j : DrawIndex repeats p // IsTerminal repeats p j}) → + ExpansionSpace 𝕜 repeats p q A j.val) ≃ TerminalTape 𝕜 repeats p q A := + ((Equiv.piCongrLeft + (fun j : {j : DrawIndex repeats p // IsTerminal repeats p j} => + ExpansionSpace 𝕜 repeats p q A j.val) + (terminalSubtypeEquiv repeats p)).symm).trans + (Equiv.piCongrRight (terminalFactorEquiv 𝕜 repeats p q A)) + +def splitExpanded : ExpandedTape 𝕜 repeats p q A ≃ + TerminalTape 𝕜 repeats p q A × ExteriorTape 𝕜 repeats p A := + (Equiv.piEquivPiSubtypeProd (IsTerminal repeats p) + (ExpansionSpace 𝕜 repeats p q A)).trans + (Equiv.prodCongr (terminalTapeEquiv 𝕜 repeats p q A) + (Equiv.piCongrRight (exteriorFactorEquiv 𝕜 repeats p q A))) + +def splitTape : RecursiveSampler.Tape 𝕜 repeats (p.append q) A ≃ + TerminalTape 𝕜 repeats p q A × ExteriorTape 𝕜 repeats p A := + (expandEquiv 𝕜 repeats p q A).trans (splitExpanded 𝕜 repeats p q A) + +@[simp] theorem splitExpanded_terminal_apply + (x : ExpandedTape 𝕜 repeats p q A) (terminal : TerminalIndex repeats p) : + (splitExpanded 𝕜 repeats p q A x).1 terminal = + terminalFactorEquiv 𝕜 repeats p q A terminal (x (drawIndex repeats p terminal)) := rfl + +@[simp] theorem splitExpanded_exterior_apply + (x : ExpandedTape 𝕜 repeats p q A) (j : ExteriorIndex repeats p) : + (splitExpanded 𝕜 repeats p q A x).2 j = + exteriorFactorEquiv 𝕜 repeats p q A j (x j.val) := rfl + +variable [Finite 𝕜] [hA : ∀ s, Finite (A s)] + +local instance familyFinite : ∀ s, Finite (p.family A s) := + fun s => hA (p.slotEmbedding s) + +def terminalLaw : FiniteDistribution (TerminalTape 𝕜 repeats p q A) := + FiniteProduct.law (fun _ : TerminalIndex repeats p => + RecursiveSampler.tapeLaw 𝕜 repeats q (p.family A)) + +def exteriorLaw : FiniteDistribution (ExteriorTape 𝕜 repeats p A) := + FiniteProduct.law (fun j : ExteriorIndex repeats p => + FiniteDistribution.uniform (DrawSpace 𝕜 repeats p A j.val)) + +theorem terminalLaw_uniform : + terminalLaw 𝕜 repeats p q A = FiniteDistribution.uniform (TerminalTape 𝕜 repeats p q A) := by + simp only [terminalLaw, RecursiveSampler.tapeLaw_eq_uniform, UniformLinearImage.law_uniform] + +theorem exteriorLaw_uniform : + exteriorLaw 𝕜 repeats p A = FiniteDistribution.uniform (ExteriorTape 𝕜 repeats p A) := + UniformLinearImage.law_uniform + +theorem split_tapeLaw : + (RecursiveSampler.tapeLaw 𝕜 repeats (p.append q) A).pushforward + (splitTape 𝕜 repeats p q A) = + (terminalLaw 𝕜 repeats p q A).product (exteriorLaw 𝕜 repeats p A) := by + rw [RecursiveSampler.tapeLaw_eq_uniform, FiniteDistribution.pushforward_equiv, + terminalLaw_uniform, exteriorLaw_uniform] + apply FiniteDistribution.eq_of_weight_eq + intro x + change 1 / (Fintype.card (RecursiveSampler.Tape 𝕜 repeats (p.append q) A) : ℝ) = + (1 / (Fintype.card (TerminalTape 𝕜 repeats p q A) : ℝ)) * + (1 / (Fintype.card (ExteriorTape 𝕜 repeats p A) : ℝ)) + rw [Fintype.card_congr (splitTape 𝕜 repeats p q A), Fintype.card_prod] + simp only [Nat.cast_mul, one_div, mul_inv] + +end +end PerfectCompleteness.OriginalTerminalSplit + +end + +section + +namespace PerfectCompleteness.OriginalScalarReconstruction + +open RecursiveSpaces DescendantSpaces RecursiveSampler TerminalCalls SamplerComposition +open OriginalTerminalSplit +open scoped Classical + +noncomputable section + +universe u w + +variable {branch : Nat → Nat} {n m k : Nat} +variable (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) + (p : Path branch n m) (A : Slots branch n → Type u) + +abbrev TerminalValues := TerminalIndex repeats p → space 𝕜 branch m (p.family A) + +def terminalValueEquiv : + ((j : {j : DrawIndex repeats p // IsTerminal repeats p j}) → + DrawSpace 𝕜 repeats p A j.val) ≃ TerminalValues 𝕜 repeats p A := + ((Equiv.piCongrLeft + (fun j : {j : DrawIndex repeats p // IsTerminal repeats p j} => + DrawSpace 𝕜 repeats p A j.val) + (terminalSubtypeEquiv repeats p)).symm).trans + (Equiv.piCongrRight (terminalSpaceEquiv 𝕜 repeats p A)) + +def prefixSplit : RecursiveSampler.Tape 𝕜 repeats p A ≃ + TerminalValues 𝕜 repeats p A × ExteriorTape 𝕜 repeats p A := + (Equiv.piEquivPiSubtypeProd (IsTerminal repeats p) (DrawSpace 𝕜 repeats p A)).trans + (Equiv.prodCongr (terminalValueEquiv 𝕜 repeats p A) (Equiv.refl _)) + +def reconstruct (values : TerminalValues 𝕜 repeats p A) + (exterior : ExteriorTape 𝕜 repeats p A) : space 𝕜 branch n A := + RecursiveSampler.evaluate 𝕜 repeats p A ((prefixSplit 𝕜 repeats p A).symm (values, exterior)) + +theorem collapseFactor_terminal : + ∀ (q : Path branch m k) (A : Slots branch n → Type u) + (terminal : TerminalIndex repeats p) + (x : ExpansionSpace 𝕜 repeats p q A (drawIndex repeats p terminal)), + terminalSpaceEquiv 𝕜 repeats p A terminal + (collapseFactor 𝕜 repeats p q A (drawIndex repeats p terminal) x) = + RecursiveSampler.evaluate 𝕜 repeats q (p.family A) + (terminalFactorEquiv 𝕜 repeats p q A terminal x) := by + induction p with + | refl n => intro q A terminal x; rfl + | step i p ih => + intro q A terminal x + exact ih q (childFamily A i) terminal.2 x + +theorem collapseFactor_exterior : + ∀ (q : Path branch m k) (A : Slots branch n → Type u) + (j : DrawIndex repeats p) (hj : ¬ IsTerminal repeats p j) + (x : ExpansionSpace 𝕜 repeats p q A j), + collapseFactor 𝕜 repeats p q A j x = + exteriorFactorEquiv 𝕜 repeats p q A ⟨j, hj⟩ x := by + induction p with + | refl n => + intro q A j hj x + exact False.elim (hj True.intro) + | step i p ih => + intro q A j hj x + cases j with + | inl j => rfl + | inr j => exact ih q (childFamily A i) j.2 hj x + +theorem prefixSplit_collapseExpanded (q : Path branch m k) + (x : ExpandedTape 𝕜 repeats p q A) : + prefixSplit 𝕜 repeats p A (collapseExpanded 𝕜 repeats p q A x) = + (fun terminal => RecursiveSampler.evaluate 𝕜 repeats q (p.family A) + ((splitExpanded 𝕜 repeats p q A x).1 terminal), + (splitExpanded 𝕜 repeats p q A x).2) := by + apply Prod.ext + · funext terminal + exact collapseFactor_terminal 𝕜 repeats p q A terminal (x (drawIndex repeats p terminal)) + · funext j + exact collapseFactor_exterior 𝕜 repeats p q A j.val j.property (x j.val) + +theorem reconstruct_original (q : Path branch m k) + (x : RecursiveSampler.Tape 𝕜 repeats (p.append q) A) : + reconstruct 𝕜 repeats p A + (fun terminal => RecursiveSampler.evaluate 𝕜 repeats q (p.family A) + ((splitTape 𝕜 repeats p q A x).1 terminal)) + (splitTape 𝕜 repeats p q A x).2 = + RecursiveSampler.evaluate 𝕜 repeats (p.append q) A x := by + have hsplit := prefixSplit_collapseExpanded 𝕜 repeats p A q + (expandEquiv 𝕜 repeats p q A x) + change prefixSplit 𝕜 repeats p A (collapseSuffix 𝕜 repeats p q A x) = + (fun terminal => RecursiveSampler.evaluate 𝕜 repeats q (p.family A) + ((splitTape 𝕜 repeats p q A x).1 terminal), + (splitTape 𝕜 repeats p q A x).2) at hsplit + unfold reconstruct + rw [← hsplit, Equiv.symm_apply_apply] + exact evaluate_collapseSuffix 𝕜 repeats p q A x + +end +end PerfectCompleteness.OriginalScalarReconstruction + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/OriginalWholeCut.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/OriginalWholeCut.lean new file mode 100644 index 0000000000000000000000000000000000000000..1f64e639a20db5b3fad84fc669cd4fddcbb614fb --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/OriginalWholeCut.lean @@ -0,0 +1,169 @@ +import OAI.Computability.PerfectCompleteness.Foundations.OriginalTerminalSplitLemmas +import OAI.Computability.PerfectCompleteness.Machines.OriginalWholeCutTape + +namespace OAI + +section + +namespace PerfectCompleteness.OriginalWholeCut + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCutTape +open scoped BigOperators Classical + +noncomputable section + +variable {branch : Nat → Nat} {n m k t : Nat} + +abbrev Values (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) := + OriginalCutCalls.Index rows repeats p → H (cutSlots p slots) + +abbrev ChildArrays (rows : Nat → Nat) + (slots : Slots branch (m + 1) → Fin t → MixedSupport.Slot) := + (child : Fin (branch m)) → Arrays (childSlots slots child) rows + +abbrev BelowArrays (rows : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) := + ChildArrays rows (cutSlots p slots) + +abbrev Record (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) := + Exterior rows repeats p slots × (Values rows repeats p slots × BelowArrays rows p slots) + +def belowEvaluate (rows repeats : Nat → Nat) (chosen : Fin (branch m)) + (q : Path branch m k) (slots : Slots branch (m + 1) → Fin t → MixedSupport.Slot) + (ω : BelowTape rows repeats chosen q slots) : ChildArrays rows slots := + WholeArraySampler.childrenAt slots rows chosen + (WholeArraySampler.evaluate rows repeats q (childSlots slots chosen) ω.1) ω.2 + +def reconstructBuckets (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (values : BucketSampler.Direction (rows n) → + OriginalScalarReconstruction.TerminalValues F2 repeats p (LeafDomain slots)) + (exterior : BucketSampler.Direction (rows n) → + OriginalTerminalSplit.ExteriorTape F2 repeats p (LeafDomain slots)) : + Fin (rows n) → H slots := + BucketSampler.evaluate (rows n) id (fun direction => + OriginalScalarReconstruction.reconstruct F2 repeats p (LeafDomain slots) + (values direction) (exterior direction)) + +theorem reconstructBuckets_original (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) (r : Path branch (m + 1) k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (ω : WholeArraySampler.RootTape rows repeats (p.append r) slots) : + reconstructBuckets rows repeats p slots + (fun direction terminal => RecursiveSampler.evaluate F2 repeats r + (p.family (LeafDomain slots)) + ((OriginalTerminalSplit.splitTape F2 repeats p r (LeafDomain slots) + (ω direction)).1 terminal)) + (fun direction => (OriginalTerminalSplit.splitTape F2 repeats p r (LeafDomain slots) + (ω direction)).2) = + BucketSampler.recursiveEvaluate (rows n) repeats (p.append r) (LeafDomain slots) ω := by + have h := funext (fun direction : BucketSampler.Direction (rows n) => + OriginalScalarReconstruction.reconstruct_original F2 repeats p (LeafDomain slots) r + (ω direction)) + exact congrArg (BucketSampler.evaluate (rows n) (id : H slots → H slots)) h + +def reconstruct (rows repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n (m + 1)) → + (slots : Slots branch n → Fin t → MixedSupport.Slot) → + Exterior rows repeats p slots → Values rows repeats p slots → + BelowArrays rows p slots → Arrays slots rows + | _, m, .refl _, slots, _, values, below => + WholeArraySampler.assemble slots rows + (BucketSampler.evaluate (rows (m + 1)) (id : H slots → H slots) values) below + | _, _, .step i p, slots, exterior, values, below => + WholeArraySampler.assemble slots rows + (reconstructBuckets rows repeats (.step i p) slots + (fun direction terminal => values (.inl (direction, terminal))) exterior.1) + (WholeArraySampler.childrenAt slots rows i + (reconstruct rows repeats p (childSlots slots i) exterior.2.1 + (fun call => values (.inr call)) below) exterior.2.2) + +def reconstructRecord (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : Record rows repeats p slots) : Arrays slots rows := + reconstruct rows repeats p slots record.1 record.2.1 record.2.2 + +def readRecord (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (chosen : Fin (branch m)) (q : Path branch m k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (ω : WholeArraySampler.Tape rows repeats (p.append (.step chosen q)) slots) : + Record rows repeats p slots := + let split := splitTape rows repeats p chosen q slots ω + (split.1, + (fun call => RecursiveSampler.evaluate F2 repeats (.step chosen q) + (LeafDomain (cutSlots p slots)) (split.2.1 call), + belowEvaluate rows repeats chosen q (cutSlots p slots) split.2.2)) + +theorem reconstruct_original (rows repeats : Nat → Nat) : + ∀ {n m k : Nat} (p : Path branch n (m + 1)) (chosen : Fin (branch m)) + (q : Path branch m k) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (ω : WholeArraySampler.Tape rows repeats (p.append (.step chosen q)) slots), + reconstructRecord rows repeats p slots (readRecord rows repeats p chosen q slots ω) = + WholeArraySampler.evaluate rows repeats (p.append (.step chosen q)) slots ω := by + intro n + induction n with + | zero => + intro m k p + cases p + | succ n ih => + intro m k p chosen q slots ω + cases p with + | refl => rfl + | step i p => + exact congrArg₂ (WholeArraySampler.assemble slots rows) + (reconstructBuckets_original rows repeats (.step i p) (.step chosen q) slots + (ω (.inl ()))) + (congrArg (fun selected : Arrays (childSlots slots i) rows => + WholeArraySampler.childrenAt slots rows i selected (fun j => ω (.inr (.inr j)))) + (ih p chosen q (childSlots slots i) (ω (.inr (.inl ()))))) + +def callNumbering (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) : + OriginalCutCalls.Index rows repeats p ≃ + Fin (OriginalCutCalls.count rows repeats n (m + 1)) := + (Fintype.equivFin (OriginalCutCalls.Index rows repeats p)).trans + (Equiv.cast (congrArg Fin (OriginalCutCalls.card_eq_count rows repeats p))) + +def numberedValues (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) (values : Values rows repeats p slots) : + Fin (OriginalCutCalls.count rows repeats n (m + 1)) → H (cutSlots p slots) := + fun call => values ((callNumbering rows repeats p).symm call) + +def reconstructNumbered (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (exterior : Exterior rows repeats p slots) + (values : Fin (OriginalCutCalls.count rows repeats n (m + 1)) → H (cutSlots p slots)) + (below : BelowArrays rows p slots) : Arrays slots rows := + reconstruct rows repeats p slots exterior (fun call => values (callNumbering rows repeats p call)) below + +theorem reconstructNumbered_numberedValues (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (exterior : Exterior rows repeats p slots) (values : Values rows repeats p slots) + (below : BelowArrays rows p slots) : + reconstructNumbered rows repeats p slots exterior (numberedValues rows repeats p slots values) below = + reconstruct rows repeats p slots exterior values below := by + apply congrArg (fun calls : Values rows repeats p slots => + reconstruct rows repeats p slots exterior calls below) + funext call + exact congrArg values ((callNumbering rows repeats p).symm_apply_apply call) + +theorem reconstructNumbered_original (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) (chosen : Fin (branch m)) (q : Path branch m k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (ω : WholeArraySampler.Tape rows repeats (p.append (.step chosen q)) slots) : + let record := readRecord rows repeats p chosen q slots ω + reconstructNumbered rows repeats p slots record.1 + (numberedValues rows repeats p slots record.2.1) record.2.2 = + WholeArraySampler.evaluate rows repeats (p.append (.step chosen q)) slots ω := by + dsimp only + rw [reconstructNumbered_numberedValues] + exact reconstruct_original rows repeats p chosen q slots ω + +end +end PerfectCompleteness.OriginalWholeCut + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/OriginalWholeCutBridge.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/OriginalWholeCutBridge.lean new file mode 100644 index 0000000000000000000000000000000000000000..922ef4a18e2b5dafb65efe6bc3f30cfd3aaefdb2 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/OriginalWholeCutBridge.lean @@ -0,0 +1,183 @@ +import OAI.Computability.PerfectCompleteness.Construction.OriginalChildBlocks +import OAI.Computability.PerfectCompleteness.Sampling.OriginalWholeCutLaw + +namespace OAI + +section + +namespace PerfectCompleteness.OriginalWholeCutBridge + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCutTape OriginalWholeCut OriginalWholeCutLaw +open UniqueGamesTheorem.Foundations.Games +open scoped Classical + +noncomputable section + +private theorem pair_map_transport {A B C D Z : Type*} + [Fintype A] [Fintype B] [Fintype C] [Fintype D] [Fintype Z] + (μ : FiniteDistribution A) (ν : FiniteDistribution B) + (f : A → C) (g : B → D) (e : C × D ≃ Z) : + (μ.product ν).pushforward (fun x => e (f x.1, g x.2)) = + ((μ.pushforward f).product (ν.pushforward g)).transport e := by + rw [FiniteDistribution.transport_eq_pushforward] + calc + _ = ((μ.product ν).pushforward (fun x => (f x.1, g x.2))).pushforward e := + (FiniteDistribution.pushforward_comp _ _ _).symm + _ = _ := congrArg (fun ρ : FiniteDistribution (C × D) => ρ.pushforward e) + (FiniteDistribution.product_pushforward μ ν f g) + +private theorem product_pair_map {E A B C Z : Type*} + [Fintype E] [Fintype A] [Fintype B] [Fintype C] [Fintype Z] + (μ : FiniteDistribution E) (ν : FiniteDistribution A) (ξ : FiniteDistribution B) + (f : A → C) (e : C × B ≃ Z) : + (μ.product (ν.product ξ)).pushforward (fun x => (x.1, e (f x.2.1, x.2.2))) = + μ.product (((ν.pushforward f).product ξ).transport e) := by + have hpair : (ν.product ξ).pushforward (fun x => e (f x.1, x.2)) = + ((ν.pushforward f).product ξ).transport e := by + simpa only [id_eq, FiniteDistribution.pushforward_id] using + (pair_map_transport ν ξ f (id : B → B) e) + calc + _ = (μ.pushforward id).product + ((ν.product ξ).pushforward (fun x => e (f x.1, x.2))) := + FiniteDistribution.product_pushforward μ (ν.product ξ) id + (fun x => e (f x.1, x.2)) + _ = _ := congrArg₂ + (fun (ρ : FiniteDistribution E) (σ : FiniteDistribution Z) => ρ.product σ) + (FiniteDistribution.pushforward_id μ) hpair + +variable {branch : Nat → Nat} {n m k t : Nat} + +def assembledEquiv (calls : Nat) (rows : Nat → Nat) + (slots : Slots branch (m + 1) → Fin t → MixedSupport.Slot) : + ((Fin calls → H slots) × ChildArrays rows slots) ≃ + CutChildGrouping.Assembled (C := Fin calls) slots rows := Equiv.refl _ + +def scalarValuesLaw (calls : Nat) (repeats : Nat → Nat) (chosen : Fin (branch m)) + (q : Path branch m k) (slots : Slots branch (m + 1) → Fin t → MixedSupport.Slot) : + FiniteDistribution (Fin calls → H slots) := + FiniteProduct.law (fun _ : Fin calls => + RecursiveSampler.law F2 repeats (.step chosen q) (LeafDomain slots)) + +theorem observed_product_law (calls : Nat) (rows repeats : Nat → Nat) + (chosen : Fin (branch m)) (q : Path branch m k) + (slots : Slots branch (m + 1) → Fin t → MixedSupport.Slot) : + (OriginalChildBlocks.sourceLaw calls rows repeats chosen q slots).pushforward + (OriginalChildBlocks.observed calls rows repeats chosen q slots) = + @FiniteDistribution.transport + ((Fin calls → H slots) × ChildArrays rows slots) + (CutChildGrouping.Assembled (C := Fin calls) slots rows) + (instFintypeProd _ _) (CutChildGrouping.assembledFintype (C := Fin calls) slots rows) + ((scalarValuesLaw calls repeats chosen q slots).product + (belowArraysLaw rows repeats chosen q slots)) + (assembledEquiv calls rows slots) := by + have hcalls : (OriginalChildScalars.callsLaw calls repeats chosen q slots).pushforward + (fun tapes call => RecursiveSampler.evaluate F2 repeats (.step chosen q) + (LeafDomain slots) (tapes call)) = scalarValuesLaw calls repeats chosen q slots := + FiniteProduct.pushforward_map + (fun _ : Fin calls => RecursiveSampler.tapeLaw F2 repeats (.step chosen q) (LeafDomain slots)) + (fun _ => RecursiveSampler.evaluate F2 repeats (.step chosen q) (LeafDomain slots)) + have hmap := pair_map_transport + (A := Fin calls → OriginalChildScalars.ScalarTape repeats chosen q slots) + (B := WholeArraySampler.Tape rows repeats (.step chosen q) slots) + (C := Fin calls → H slots) (D := ChildArrays rows slots) + (Z := CutChildGrouping.Assembled (C := Fin calls) slots rows) + (OriginalChildScalars.callsLaw calls repeats chosen q slots) + (WholeArraySampler.tapeLaw rows repeats (.step chosen q) slots) + (fun tapes call => RecursiveSampler.evaluate F2 repeats (.step chosen q) + (LeafDomain slots) (tapes call)) + (OriginalBelowCut.below rows repeats chosen q slots) + (assembledEquiv calls rows slots) + rw [hcalls, OriginalBelowCut.below_pushforward] at hmap + exact hmap + +attribute [local instance 2000] OriginalWholeCutLaw.valuesBelowFintype + +abbrev NumberedRecord (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) := + Exterior rows repeats p slots × + CutChildGrouping.Assembled + (C := Fin (OriginalCutCalls.count rows repeats n (m + 1))) (cutSlots p slots) rows + +def numberRecord (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : Record rows repeats p slots) : NumberedRecord rows repeats p slots := + (record.1, assembledEquiv (OriginalCutCalls.count rows repeats n (m + 1)) rows + (cutSlots p slots) (numberedValues rows repeats p slots record.2.1, record.2.2)) + +def reconstruct (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : NumberedRecord rows repeats p slots) : Arrays slots rows := + reconstructNumbered rows repeats p slots record.1 record.2.1 record.2.2 + +theorem reconstruct_numberRecord (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) (record : Record rows repeats p slots) : + reconstruct rows repeats p slots (numberRecord rows repeats p slots record) = + reconstructRecord rows repeats p slots record := + reconstructNumbered_numberedValues rows repeats p slots record.1 record.2.1 record.2.2 + +theorem numberRecord_law (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (chosen : Fin (branch m)) (q : Path branch m k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + (recordLaw rows repeats p chosen q slots).pushforward (numberRecord rows repeats p slots) = + (exteriorLaw rows repeats p slots).product + ((OriginalChildBlocks.sourceLaw (OriginalCutCalls.count rows repeats n (m + 1)) + rows repeats chosen q (cutSlots p slots)).pushforward + (OriginalChildBlocks.observed (OriginalCutCalls.count rows repeats n (m + 1)) + rows repeats chosen q (cutSlots p slots))) := by + have hmap := product_pair_map + (E := Exterior rows repeats p slots) + (A := Values rows repeats p slots) (B := BelowArrays rows p slots) + (C := Fin (OriginalCutCalls.count rows repeats n (m + 1)) → H (cutSlots p slots)) + (Z := CutChildGrouping.Assembled + (C := Fin (OriginalCutCalls.count rows repeats n (m + 1))) (cutSlots p slots) rows) + (exteriorLaw rows repeats p slots) (valuesLaw rows repeats p chosen q slots) + (belowArraysLaw rows repeats chosen q (cutSlots p slots)) + (numberedValues rows repeats p slots) + (assembledEquiv (OriginalCutCalls.count rows repeats n (m + 1)) rows (cutSlots p slots)) + rw [numberedValues_law] at hmap + apply Eq.trans hmap + exact congrArg + (fun μ : FiniteDistribution (CutChildGrouping.Assembled + (C := Fin (OriginalCutCalls.count rows repeats n (m + 1))) (cutSlots p slots) rows) => + (exteriorLaw rows repeats p slots).product μ) + (observed_product_law (OriginalCutCalls.count rows repeats n (m + 1)) rows repeats + chosen q (cutSlots p slots)).symm + +theorem reconstruct_child_law (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (chosen : Fin (branch m)) (q : Path branch m k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + ((exteriorLaw rows repeats p slots).product + ((OriginalChildBlocks.sourceLaw (OriginalCutCalls.count rows repeats n (m + 1)) + rows repeats chosen q (cutSlots p slots)).pushforward + (OriginalChildBlocks.observed (OriginalCutCalls.count rows repeats n (m + 1)) + rows repeats chosen q (cutSlots p slots)))).pushforward + (reconstruct rows repeats p slots) = + WholeArraySampler.law rows repeats (p.append (.step chosen q)) slots := by + rw [← numberRecord_law rows repeats p chosen q slots, FiniteDistribution.pushforward_comp] + have hmap : (fun record : Record rows repeats p slots => + reconstruct rows repeats p slots (numberRecord rows repeats p slots record)) = + reconstructRecord rows repeats p slots := + funext (reconstruct_numberRecord rows repeats p slots) + rw [hmap] + exact reconstruct_law rows repeats p chosen q slots + +theorem reconstruct_blocks_law (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (chosen : Fin (branch m)) (q : Path branch m k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + ((exteriorLaw rows repeats p slots).product + ((ChildBlockMixture.special + (OriginalChildBlocks.specialLaw (OriginalCutCalls.count rows repeats n (m + 1)) + rows repeats q (cutSlots p slots)) chosen).pushforward + (CutChildGrouping.assemble (C := Fin (OriginalCutCalls.count rows repeats n (m + 1))) + (cutSlots p slots) rows))).pushforward (reconstruct rows repeats p slots) = + WholeArraySampler.law rows repeats (p.append (.step chosen q)) slots := by + rw [← OriginalChildBlocks.observed_law] + exact reconstruct_child_law rows repeats p chosen q slots + +end +end PerfectCompleteness.OriginalWholeCutBridge + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/OriginalWholeCutComparison.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/OriginalWholeCutComparison.lean new file mode 100644 index 0000000000000000000000000000000000000000..df45fc21ce323e0e3632b34e134e5ff2312ead4d --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/OriginalWholeCutComparison.lean @@ -0,0 +1,66 @@ +import OAI.Computability.PerfectCompleteness.Foundations.CutContinuationAveraging +import OAI.Computability.PerfectCompleteness.Foundations.OriginalHiddenConditional +import OAI.Computability.PerfectCompleteness.Sampling.NumberedUniformCut + +namespace OAI + +section + +namespace PerfectCompleteness.OriginalWholeCutComparison + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCutTape +open UniqueGamesTheorem.Foundations.Games + +noncomputable section + +variable {branch : Nat → Nat} {n m t : Nat} + +theorem totalVariation_le (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (hbranch : ∀ k < m + 1, 0 < branch k) : + (CutContinuationAveraging.originalArrayLaw rows repeats p slots hbranch).totalVariation + (WholeArraySampler.law rows repeats p slots) ≤ + Real.sqrt ((ChildBlockCardinality.bound branch m t + (OriginalCutCalls.count rows repeats n (m + 1)) rows : ℝ) ^ 2 / branch m) / 2 := by + rw [CutContinuationAveraging.originalArrayLaw_eq_sigma, + ← NumberedUniformCut.reconstruct_sigma_uniform rows repeats p slots] + exact OriginalHiddenConditional.observed_variation + (OriginalCutCalls.count rows repeats n (m + 1)) rows repeats + (fun _ : Exterior rows repeats p slots => cutSlots p slots) + (exteriorLaw rows repeats p slots) hbranch + (fun z => OriginalWholeCutBridge.reconstruct rows repeats p slots (z.1, z.2)) + +theorem observed_totalVariation_le {Γ : Type*} [Fintype Γ] + (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (hbranch : ∀ k < m + 1, 0 < branch k) (observe : Arrays slots rows → Γ) : + ((CutContinuationAveraging.originalArrayLaw rows repeats p slots hbranch).pushforward observe).totalVariation ((WholeArraySampler.law rows repeats p slots).pushforward observe) ≤ + Real.sqrt ((ChildBlockCardinality.bound branch m t + (OriginalCutCalls.count rows repeats n (m + 1)) rows : ℝ) ^ 2 / branch m) / 2 := + (DensityVariation.variation_pushforward_le _ _ observe).trans + (totalVariation_le rows repeats p slots hbranch) + +theorem conditional_observed_totalVariation_le + {S Γ : Type*} [Fintype S] [Fintype Γ] + (rows repeats : Nat → Nat) (p : S → Path branch n (m + 1)) + (slots : S → Slots branch n → Fin t → MixedSupport.Slot) + (μ : FiniteDistribution S) (hbranch : ∀ k < m + 1, 0 < branch k) + (observe : (Σ s : S, Arrays (slots s) rows) → Γ) : + ((CompletionSoundness.sigmaLaw μ (fun s => + CutContinuationAveraging.originalArrayLaw rows repeats (p s) (slots s) hbranch)).pushforward observe).totalVariation + ((CompletionSoundness.sigmaLaw μ (fun s => + WholeArraySampler.law rows repeats (p s) (slots s))).pushforward observe) ≤ + Real.sqrt ((ChildBlockCardinality.bound branch m t + (OriginalCutCalls.count rows repeats n (m + 1)) rows : ℝ) ^ 2 / branch m) / 2 := by + exact ConditionalVariation.observed_sigma_le_const μ + (fun s => CutContinuationAveraging.originalArrayLaw rows repeats (p s) (slots s) hbranch) + (fun s => WholeArraySampler.law rows repeats (p s) (slots s)) + _ (fun s => totalVariation_le rows repeats (p s) (slots s) hbranch) observe + +end +end PerfectCompleteness.OriginalWholeCutComparison + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/OutputAnnihilator.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/OutputAnnihilator.lean new file mode 100644 index 0000000000000000000000000000000000000000..57d1839431623279b18e1cb69a4e88fa2b3dbfa5 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/OutputAnnihilator.lean @@ -0,0 +1,141 @@ +import Mathlib.Tactic.NormNum +import OAI.Computability.PerfectCompleteness.Algebra.BilinearGramCompressionLemmas +import OAI.Computability.PerfectCompleteness.Machines.BinaryDualCoordinates + +namespace OAI + + +namespace PerfectCompleteness.OutputAnnihilator + +noncomputable section + +open scoped Classical +open UniqueGamesTheorem.Integration.BinaryLinear (F2) + +variable {K : Type*} [AddCommGroup K] [Module F2 K] + [FiniteDimensional F2 K] [Fintype (Module.Dual F2 K)] + +def bad (W : Submodule F2 K) : Finset (Module.Dual F2 K) := + Finset.univ.filter (fun σ => σ ∈ W.dualAnnihilator) + +omit [FiniteDimensional F2 K] in +@[simp] theorem mem_bad (W : Submodule F2 K) (σ : Module.Dual F2 K) : + σ ∈ bad W ↔ σ ∈ W.dualAnnihilator := by + simp only [bad, Finset.mem_filter, Finset.mem_univ, true_and] + +omit [FiniteDimensional F2 K] in +theorem not_mem_bad_iff (W : Submodule F2 K) (σ : Module.Dual F2 K) : + σ ∉ bad W ↔ σ.comp W.subtype ≠ 0 := by + rw [mem_bad, TensorCosetEvaluation.annihilator_iff_restriction_zero] + +theorem card_bad (W : Submodule F2 K) : + (bad W).card = 2 ^ (Module.finrank F2 K - Module.finrank F2 W) := by + calc + _ = Fintype.card W.dualAnnihilator := by + rw [Fintype.card_subtype] + rfl + _ = Nat.card W.dualAnnihilator := Fintype.card_eq_nat_card + _ = _ := TensorCosetEvaluation.card_annihilatingCharacters W + +omit [FiniteDimensional F2 K] in +theorem card_dual : Fintype.card (Module.Dual F2 K) = 2 ^ Module.finrank F2 K := by + rw [Module.card_eq_pow_finrank (K := F2), Subspace.dual_finrank_eq] + rw [show Fintype.card F2 = 2 by decide] + +theorem card_dual_eq_bad_mul (W : Submodule F2 K) : + Fintype.card (Module.Dual F2 K) = (bad W).card * 2 ^ Module.finrank F2 W := by + rw [card_dual, card_bad, ← pow_add, Nat.sub_add_cancel W.finrank_le] + +theorem bad_fraction (W : Submodule F2 K) : + ((bad W).card : ℝ) / Fintype.card (Module.Dual F2 K) = + 1 / (2 : ℝ) ^ Module.finrank F2 W := by + have hbad : ((bad W).card : ℝ) ≠ 0 := by + rw [card_bad] + positivity + rw [card_dual_eq_bad_mul W, Nat.cast_mul, Nat.cast_pow, Nat.cast_ofNat, + div_mul_eq_div_div, div_self hbad] + +theorem bad_fraction_le_of_finrank_le (W : Submodule F2 K) (d : Nat) + (hd : d ≤ Module.finrank F2 W) : + ((bad W).card : ℝ) / Fintype.card (Module.Dual F2 K) ≤ 1 / (2 : ℝ) ^ d := by + rw [bad_fraction] + exact one_div_le_one_div_of_le (pow_pos (by norm_num) _) + (pow_le_pow_right₀ (by norm_num) hd) + +theorem bad_fraction_le_of_dimension_bound (W : Submodule F2 K) (ℓ r : Nat) + (hdim : ℓ ≤ Module.finrank F2 W + r) : + ((bad W).card : ℝ) / Fintype.card (Module.Dual F2 K) ≤ + 1 / (2 : ℝ) ^ (ℓ - r) := + bad_fraction_le_of_finrank_le W (ℓ - r) (Nat.sub_le_iff_le_add.mpr hdim) + +theorem bad_fraction_le_of_codim_le (W : Submodule F2 K) (r : Nat) + (hcodim : Module.finrank F2 (K ⧸ W) ≤ r) : + ((bad W).card : ℝ) / Fintype.card (Module.Dual F2 K) ≤ + 1 / (2 : ℝ) ^ (Module.finrank F2 K - r) := by + have hdim : Module.finrank F2 K - r ≤ Module.finrank F2 W := by + apply Nat.sub_le_iff_le_add.mpr + calc + Module.finrank F2 K = + Module.finrank F2 (K ⧸ W) + Module.finrank F2 W := + W.finrank_quotient_add_finrank.symm + _ ≤ r + Module.finrank F2 W := Nat.add_le_add_right hcodim _ + _ = Module.finrank F2 W + r := Nat.add_comm _ _ + exact bad_fraction_le_of_finrank_le W (Module.finrank F2 K - r) hdim + +theorem bad_fraction_lt_of_codim_le (W : Submodule F2 K) (r : Nat) (ρ : ℝ) + (hcodim : Module.finrank F2 (K ⧸ W) ≤ r) + (hgap : 1 / (2 : ℝ) ^ (Module.finrank F2 K - r) < ρ / 8) : + ((bad W).card : ℝ) / Fintype.card (Module.Dual F2 K) < ρ / 8 := + (bad_fraction_le_of_codim_le W r hcodim).trans_lt hgap + + +variable {I : Type*} [Fintype I] + +def badMasks (b : Module.Basis I F2 K) (W : Submodule F2 K) : Finset (I → Bool) := + Finset.univ.filter + (fun mask => BinaryDualCoordinates.frequency b mask ∈ W.dualAnnihilator) + +omit [FiniteDimensional F2 K] [Fintype (Module.Dual F2 K)] in +@[simp] theorem mem_badMasks (b : Module.Basis I F2 K) (W : Submodule F2 K) + (mask : I → Bool) : + mask ∈ badMasks b W ↔ BinaryDualCoordinates.frequency b mask ∈ W.dualAnnihilator := by + simp only [badMasks, Finset.mem_filter, Finset.mem_univ, true_and] + +omit [FiniteDimensional F2 K] [Fintype (Module.Dual F2 K)] in +theorem not_mem_badMasks_iff (b : Module.Basis I F2 K) (W : Submodule F2 K) + (mask : I → Bool) : mask ∉ badMasks b W ↔ + (BinaryDualCoordinates.frequency b mask).comp W.subtype ≠ 0 := by + rw [mem_badMasks, TensorCosetEvaluation.annihilator_iff_restriction_zero] + +omit [FiniteDimensional F2 K] in +theorem card_badMasks (b : Module.Basis I F2 K) (W : Submodule F2 K) : + (badMasks b W).card = (bad W).card := by + calc + _ = Fintype.card {mask : I → Bool // + BinaryDualCoordinates.frequency b mask ∈ W.dualAnnihilator} := by + rw [Fintype.card_subtype] + rfl + _ = Fintype.card W.dualAnnihilator := by + apply Fintype.card_congr + exact (BinaryDualCoordinates.frequencyEquiv b).subtypeEquiv (fun _ => Iff.rfl) + _ = _ := by + rw [Fintype.card_subtype] + rfl + +theorem badMasks_fraction (b : Module.Basis I F2 K) (W : Submodule F2 K) : + ((badMasks b W).card : ℝ) / Fintype.card (I → Bool) = + 1 / (2 : ℝ) ^ Module.finrank F2 W := by + rw [card_badMasks, Fintype.card_congr (BinaryDualCoordinates.frequencyEquiv b), bad_fraction] + +theorem badMasks_fraction_lt_of_codim_le (b : Module.Basis I F2 K) + (W : Submodule F2 K) (r : Nat) (ρ : ℝ) + (hcodim : Module.finrank F2 (K ⧸ W) ≤ r) + (hgap : 1 / (2 : ℝ) ^ (Module.finrank F2 K - r) < ρ / 8) : + ((badMasks b W).card : ℝ) / Fintype.card (I → Bool) < ρ / 8 := by + rw [card_badMasks, Fintype.card_congr (BinaryDualCoordinates.frequencyEquiv b)] + exact bad_fraction_lt_of_codim_le W r ρ hcodim hgap + +end +end PerfectCompleteness.OutputAnnihilator + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/PCPSource.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/PCPSource.lean new file mode 100644 index 0000000000000000000000000000000000000000..1c0bcafe898812c99e495c6e3926db3f9af0fdee --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/PCPSource.lean @@ -0,0 +1,199 @@ +import OAI.Computability.PerfectCompleteness.Foundations.NormalizationLemmas +import OAI.Computability.PerfectCompleteness.Machines.BinaryFormulaLemmas +import OAI.Computability.PerfectCompleteness.Repetition.SourceAmplification +import OAI.Computability.UniqueGames.PCP.ExpanderTables +import OAI.Computability.UniqueGames.PCP.TableGapReductionLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.PCPSource + +open UniqueGamesTheorem.Foundations Target PCP SourceClause +open scoped BigOperators + +noncomputable section + +def baseTable : RoundTables.BaseTable := + Classical.choose ExpanderTables.exists_base_table + +theorem baseTable_certificate : + SpectralReturn.SpectralCertificate (ExpanderTables.graph baseTable) (1 / 100 : ℝ) := + Classical.choose_spec ExpanderTables.exists_base_table + +def rawFormula (F : Formula) : Formula := TableIteration.gapMap baseTable F + +def normalizedFormula (F : Formula) : Formula := Normalization.normalize (rawFormula F) + +theorem rawFormula_nonempty (F : Formula) : (rawFormula F).clauses ≠ [] := + TableIteration.gapMap_nonempty baseTable F + +theorem normalizedFormula_nonempty (F : Formula) : (normalizedFormula F).clauses ≠ [] := + Normalization.normalize_nonempty (rawFormula F) (rawFormula_nonempty F) + +theorem normalizedFormula_satisfiable_iff (F : Formula) : + (normalizedFormula F).Satisfiable ↔ F.Satisfiable := by + exact (Normalization.normalize_satisfiable_iff (rawFormula F)).trans + (TableGapReduction.gapMap_satisfiable_iff baseTable baseTable_certificate F) + +theorem normalizedFormula_distinct (F : Formula) + (c : Clause (normalizedFormula F).variables) (hc : c ∈ (normalizedFormula F).clauses) + (i j : Fin 3) (same : (c)[i].variableIndex = (c)[j].variableIndex) : i = j := + Normalization.normalize_distinct (rawFormula F) c hc i j same + +def baseDenominator : Nat := 40960 * FinalConstants.walkLength + +def sourceDenominator : Nat := 13 * baseDenominator + +def sourceGap : ℚ := 1 / (sourceDenominator : ℚ) + +theorem baseDenominator_pos : 0 < baseDenominator := + Nat.mul_pos (by decide) FinalConstants.walkLength_positive + +theorem sourceDenominator_pos : 0 < sourceDenominator := + Nat.mul_pos (by decide) baseDenominator_pos + +theorem sourceGap_pos : 0 < sourceGap := by + apply one_div_pos.mpr + exact_mod_cast sourceDenominator_pos + +theorem sourceGap_le_one : sourceGap ≤ 1 := by + have hden : (0 : ℚ) < sourceDenominator := by exact_mod_cast sourceDenominator_pos + have hone : (1 : ℚ) ≤ sourceDenominator := by exact_mod_cast sourceDenominator_pos + exact (div_le_one hden).mpr hone + +theorem finalClauseGap_eq : PCPIteration.finalClauseGap = 1 / (baseDenominator : ℚ) := by + simp only [PCPIteration.finalClauseGap, baseDenominator, Nat.cast_mul, Nat.cast_ofNat] + +theorem sourceGap_eq : sourceGap = PCPIteration.finalClauseGap / 13 := by + rw [finalClauseGap_eq] + simp only [sourceGap, sourceDenominator, Nat.cast_mul, Nat.cast_ofNat, div_div, mul_comm] + +theorem rawFormula_count_gap (F : Formula) (unsat : ¬ F.Satisfiable) + (A : Fin (rawFormula F).variables → Bool) : + 1 * (rawFormula F).clauses.length ≤ + baseDenominator * NameCompaction.failedCount (rawFormula F) A := by + have hr := (TableGapReduction.gapMap_clauseGap baseTable baseTable_certificate F unsat).2 A + have hr' : (PCPIteration.finalClauseGap : ℝ) * ((rawFormula F).clauses.length : ℝ) ≤ + (NameCompaction.failedCount (rawFormula F) A : ℝ) := + hr.trans_eq (congrArg (fun count : Nat => (count : ℝ)) + (NameCompaction.verifier_failureCount (rawFormula F) A)) + have hq : PCPIteration.finalClauseGap * ((rawFormula F).clauses.length : ℚ) ≤ + (NameCompaction.failedCount (rawFormula F) A : ℚ) := by + exact_mod_cast hr' + rw [finalClauseGap_eq, one_div_mul_eq_div] at hq + have hden : (0 : ℚ) < baseDenominator := by exact_mod_cast baseDenominator_pos + have h := (div_le_iff₀ hden).mp hq + have hnat : (rawFormula F).clauses.length ≤ + baseDenominator * NameCompaction.failedCount (rawFormula F) A := by + exact_mod_cast (show ((rawFormula F).clauses.length : ℚ) ≤ + (baseDenominator : ℚ) * (NameCompaction.failedCount (rawFormula F) A : ℚ) by + simpa only [mul_comm] using h) + simpa only [Nat.one_mul] using hnat + +theorem normalizedFormula_count_gap (F : Formula) (unsat : ¬ F.Satisfiable) + (A : Fin (normalizedFormula F).variables → Bool) : + (normalizedFormula F).clauses.length ≤ + sourceDenominator * NameCompaction.failedCount (normalizedFormula F) A := by + simpa only [normalizedFormula, sourceDenominator, Nat.one_mul] using + Normalization.normalize_gap (rawFormula F) 1 baseDenominator + (rawFormula_count_gap F unsat) A + +def clauseFamily (F : Formula) : + Fin (normalizedFormula F).clauses.length → NormalizedClause (normalizedFormula F).variables := + fun c => + { clause := clauseAt (normalizedFormula F) c + distinct := fun i j same => normalizedFormula_distinct F _ + (List.getElem_mem c.isLt) i j same } + +instance clauseCount_neZero (F : Formula) : NeZero (normalizedFormula F).clauses.length := + ⟨Nat.ne_of_gt (List.length_pos_iff.mpr (normalizedFormula_nonempty F))⟩ + +theorem failedCount_eq_fin_sum (F : Formula) (A : Fin F.variables → Bool) : + NameCompaction.failedCount F A = + ∑ i : Fin F.clauses.length, if (clauseAt F i).eval A then 0 else 1 := by + unfold NameCompaction.failedCount + rw [← NameCompaction.evaluations_allIndices, VerifierToCNF.count_false_map_sum] + simp [allIndices, List.finRange, List.map_ofFn, List.sum_ofFn] + +theorem violatedCount_eq_failedCount (F : Formula) + (A : Fin (normalizedFormula F).variables → Bool) : + SourceGame.violatedCount (clauseFamily F) A = + NameCompaction.failedCount (normalizedFormula F) A := by + rw [failedCount_eq_fin_sum] + rfl + +theorem clauseGap (F : Formula) (unsat : ¬ F.Satisfiable) : + SourceAmplification.ClauseGap (clauseFamily F) sourceGap := by + intro A + have hnat := normalizedFormula_count_gap F unsat A + have hq : ((normalizedFormula F).clauses.length : ℚ) ≤ + (sourceDenominator : ℚ) * (NameCompaction.failedCount (normalizedFormula F) A : ℚ) := by + exact_mod_cast hnat + rw [← violatedCount_eq_failedCount] at hq + change (1 / (sourceDenominator : ℚ)) * ((normalizedFormula F).clauses.length : ℚ) ≤ _ + rw [one_div_mul_eq_div] + have hden : (0 : ℚ) < sourceDenominator := by exact_mod_cast sourceDenominator_pos + exact (div_le_iff₀ hden).mpr (by simpa only [mul_comm] using hq) + +def source (F : Formula) := SourceGame.game (clauseFamily F) + +theorem source_complete (F : Formula) (sat : F.Satisfiable) : (source F).value = 1 := by + obtain ⟨A, hA⟩ := (normalizedFormula_satisfiable_iff F).mpr sat + exact SourceGame.completeness_value (clauseFamily F) A + (fun c => hA _ (List.getElem_mem c.isLt)) + +theorem source_sound (F : Formula) (unsat : ¬ F.Satisfiable) : + (source F).value ≤ 1 - ((sourceGap / 3 : ℚ) : ℝ) := + SourceAmplification.source_value_le (clauseFamily F) (clauseGap F unsat) + +def repetitionLength (σ : ℚ) (hσ : 0 < σ) : Nat := + SourceAmplification.repetitionLength sourceGap σ sourceGap_pos sourceGap_le_one hσ + +theorem repetitionLength_positive (σ : ℚ) (hσ : 0 < σ) : 0 < repetitionLength σ hσ := + (SourceAmplification.repetitionLength_spec sourceGap σ sourceGap_pos sourceGap_le_one hσ).1 + +def amplifiedSource (F : Formula) (σ : ℚ) (hσ : 0 < σ) := + (source F).repetition (repetitionLength σ hσ) + +theorem amplifiedSource_complete (F : Formula) (sat : F.Satisfiable) + (σ : ℚ) (hσ : 0 < σ) : (amplifiedSource F σ hσ).value = 1 := by + obtain ⟨A, hA⟩ := (normalizedFormula_satisfiable_iff F).mpr sat + exact SourceAmplification.repeated_completeness_value (clauseFamily F) A + (fun c => hA _ (List.getElem_mem c.isLt)) (repetitionLength σ hσ) + +theorem amplifiedSource_sound (F : Formula) (unsat : ¬ F.Satisfiable) + (σ : ℚ) (hσ : 0 < σ) : (amplifiedSource F σ hσ).value < (σ : ℝ) := + SourceAmplification.repeated_source_value_lt (clauseFamily F) sourceGap σ + sourceGap_pos sourceGap_le_one hσ (clauseGap F unsat) + +def binarySource (F : BinaryFormula.Formula) := source (BinaryFormula.dense F) + +theorem binarySource_complete (F : BinaryFormula.Formula) (sat : F.Satisfiable) : + (binarySource F).value = 1 := + source_complete (BinaryFormula.dense F) (BinaryFormula.dense_completeness F sat) + +theorem binarySource_sound (F : BinaryFormula.Formula) (unsat : ¬ F.Satisfiable) : + (binarySource F).value ≤ 1 - ((sourceGap / 3 : ℚ) : ℝ) := + source_sound (BinaryFormula.dense F) (fun sat => unsat (BinaryFormula.dense_reflects F sat)) + +def binaryAmplifiedSource (F : BinaryFormula.Formula) (σ : ℚ) (hσ : 0 < σ) := + amplifiedSource (BinaryFormula.dense F) σ hσ + +theorem binaryAmplifiedSource_complete (F : BinaryFormula.Formula) (sat : F.Satisfiable) + (σ : ℚ) (hσ : 0 < σ) : (binaryAmplifiedSource F σ hσ).value = 1 := + amplifiedSource_complete (BinaryFormula.dense F) + (BinaryFormula.dense_completeness F sat) σ hσ + +theorem binaryAmplifiedSource_sound (F : BinaryFormula.Formula) (unsat : ¬ F.Satisfiable) + (σ : ℚ) (hσ : 0 < σ) : (binaryAmplifiedSource F σ hσ).value < (σ : ℝ) := + amplifiedSource_sound (BinaryFormula.dense F) + (fun sat => unsat (BinaryFormula.dense_reflects F sat)) σ hσ + +end +end PerfectCompleteness.PCPSource + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/PCPSourceHardness.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/PCPSourceHardness.lean new file mode 100644 index 0000000000000000000000000000000000000000..5e5db896c6b14dbe5e56f34fc44c9001bc50cb8e --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/PCPSourceHardness.lean @@ -0,0 +1,62 @@ +import OAI.Computability.PerfectCompleteness.Machines.Completeness +import OAI.Computability.PerfectCompleteness.Machines.PreprocessingMachineLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.PCPSourceHardness + +open Turing UniqueGamesTheorem.Foundations Complexity Target + +noncomputable section + +def formula {language : List Bool → Prop} + (source : CookLevin.PolynomialThreeSATReduction language) (input : List Bool) : Formula := + PCPSource.normalizedFormula (source.reduce input) + +def computation {language : List Bool → Prop} + (source : CookLevin.PolynomialThreeSATReduction language) : + TM2ComputableInPolyTime (id : List Bool → List Bool) formulaBits (formula source) := by + change TM2ComputableInPolyTime (id : List Bool → List Bool) formulaBits + (fun input => PCPSource.normalizedFormula (source.reduce input)) + exact MachineSequential.composeBits source.computation PCPSourceMachine.normalizedComputation + +theorem computation_finiteAlphabet {language : List Bool → Prop} + (source : CookLevin.PolynomialThreeSATReduction language) + (finiteSource : MachineFiniteAlphabet.FiniteAlphabet source.computation.tm) : + MachineFiniteAlphabet.FiniteAlphabet (computation source).tm := + MachineFiniteAlphabet.composeBits source.computation PCPSourceMachine.normalizedComputation + finiteSource PCPSourceMachine.normalized_finiteAlphabet + +theorem normalizedSource (language : List Bool → Prop) (membership : CookLevin.InNP language) : + ∃ source : CookLevin.PolynomialThreeSATReduction language, + ∃ runtime : TM2ComputableInPolyTime (id : List Bool → List Bool) formulaBits (formula source), + MachineFiniteAlphabet.FiniteAlphabet runtime.tm ∧ + ∀ input : List Bool, + ((formula source input).Satisfiable ↔ language input) ∧ + (formula source input).clauses ≠ [] ∧ + (∀ (clause : Clause (formula source input).variables), + clause ∈ (formula source input).clauses → + ∀ i j : Fin 3, clause[i].variableIndex = clause[j].variableIndex → i = j) ∧ + (¬language input → + SourceAmplification.ClauseGap (PCPSource.clauseFamily (source.reduce input)) + PCPSource.sourceGap) := by + obtain ⟨source, finiteSource⟩ := CookLevin.Completeness.threeSATReduction language membership + refine ⟨source, computation source, computation_finiteAlphabet source finiteSource, ?_⟩ + intro input + refine ⟨?_, PCPSource.normalizedFormula_nonempty (source.reduce input), ?_, ?_⟩ + · exact (PCPSource.normalizedFormula_satisfiable_iff (source.reduce input)).trans + (source.correct input).symm + · intro clause mem i j same + exact PCPSource.normalizedFormula_distinct (source.reduce input) clause mem i j same + · intro rejected + exact PCPSource.clauseGap (source.reduce input) + (fun sat => rejected ((source.correct input).mpr sat)) + +end +end PerfectCompleteness.PCPSourceHardness + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/PartialTableInverse.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/PartialTableInverse.lean new file mode 100644 index 0000000000000000000000000000000000000000..5734c79985a3fcea36fc45ba19ddff965e8df50a --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/PartialTableInverse.lean @@ -0,0 +1,144 @@ +import OAI.Computability.PerfectCompleteness.Algebra.MatrixInverse +import OAI.Computability.PerfectCompleteness.Foundations.DummyEliminationLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.PartialTableInverse + +noncomputable section + +open scoped BigOperators Classical +open UniqueGamesTheorem.Fourier.MatrixCharacters UniqueGamesTheorem.Fourier.MatrixNoise +open UniqueGamesTheorem.Fourier.MatrixRestrictions UniqueGamesTheorem.Fourier.MatrixLevelBridge +open UniqueGamesTheorem.Appendix.LevelInequality UniqueGamesTheorem.Appendix.RankLevelFilter +open PerfectCompleteness.MatrixInverse + +variable {Ω Y : Type*} [Fintype Y] + +def indicator (f : Ω → Option Y) (y : Y) (X : Ω) : ℝ := + if f X = some y then 1 else 0 + +def definedEquality (f : Ω → Option Y) (X X' : Ω) : ℝ := + if ∃ y, f X = some y ∧ f X' = some y then 1 else 0 + +omit [Fintype Y] in +theorem indicator_boolean (f : Ω → Option Y) (y : Y) : IsBoolean (indicator f y) := by + intro X + unfold indicator + split_ifs <;> simp + +theorem sum_indicator_sq_le (f : Ω → Option Y) (X : Ω) : + (∑ y, indicator f y X ^ 2) ≤ 1 := by + cases h : f X <;> simp [indicator, h, eq_comm] + +theorem definedEquality_eq_sum (f : Ω → Option Y) (X X' : Ω) : + definedEquality f X X' = ∑ y, indicator f y X * indicator f y X' := by + cases h : f X <;> cases h' : f X' <;> + simp [definedEquality, indicator, h, h', mul_ite, eq_comm] + +omit [Fintype Y] in +theorem definedEquality_le_self (f : Ω → Option Y) (X X' : Ω) : + definedEquality f X X' ≤ definedEquality f X X := by + unfold definedEquality + split_ifs with h h' h' + · exact le_rfl + · obtain ⟨y, hy, _⟩ := h + exact (h' ⟨y, hy, hy⟩).elim + · norm_num + · exact le_rfl + +variable {E F : Type*} + [AddCommGroup E] [Module F2 E] [AddCommGroup F] [Module F2 F] + [FiniteDimensional F2 E] [FiniteDimensional F2 F] + [Finite E] [Fintype F] [Fintype (E →ₗ[F2] F2)] + [Fintype (E →ₗ[F2] F)] [Fintype (F →ₗ[F2] E)] + +def stepAgreement (f : (E →ₗ[F2] F) → Option Y) (a : F) : ℝ := + 𝔼 X, 𝔼 h : E →ₗ[F2] F2, definedEquality f X (X + h.smulRight a) + +def allAgreement (f : (E →ₗ[F2] F) → Option Y) : ℝ := + 𝔼 a : F, stepAgreement f a + +omit [FiniteDimensional F2 E] [FiniteDimensional F2 F] [Finite E] + [Fintype (E →ₗ[F2] F)] [Fintype (F →ₗ[F2] E)] in +theorem uniform_operator_eq_average (g : (E →ₗ[F2] F) → ℝ) (X : E →ₗ[F2] F) : + linearRealNoiseOperator (fun _ : F => (Fintype.card F : ℝ)⁻¹) g X = + 𝔼 a : F, 𝔼 h : E →ₗ[F2] F2, g (X + h.smulRight a) := by + unfold linearRealNoiseOperator + simp only [Fintype.expect_eq_sum_div_card, div_eq_mul_inv] + rw [← Finset.mul_sum] + exact mul_comm _ _ + +omit [FiniteDimensional F2 E] [FiniteDimensional F2 F] [Finite E] + [Fintype (F →ₗ[F2] E)] in +theorem noiseEnergy_eq_average (g : (E →ₗ[F2] F) → ℝ) : + noiseEnergy g = + 𝔼 X, 𝔼 a : F, 𝔼 h : E →ₗ[F2] F2, g X * g (X + h.smulRight a) := by + unfold noiseEnergy + simp_rw [uniform_operator_eq_average, Finset.mul_expect] + +omit [FiniteDimensional F2 E] [FiniteDimensional F2 F] [Finite E] + [Fintype (F →ₗ[F2] E)] in +theorem allAgreement_eq_sum (f : (E →ₗ[F2] F) → Option Y) : + allAgreement f = ∑ y, noiseEnergy (indicator f y) := by + unfold allAgreement stepAgreement + rw [Finset.expect_comm] + simp_rw [definedEquality_eq_sum, Finset.expect_sum_comm, ← noiseEnergy_eq_average] + +omit [FiniteDimensional F2 E] [FiniteDimensional F2 F] [Finite E] + [Fintype F] [Fintype (E →ₗ[F2] F2)] [Fintype (F →ₗ[F2] E)] in +theorem indicator_mass_le_one (f : (E →ₗ[F2] F) → Option Y) : + (∑ y, 𝔼 X, indicator f y X ^ 2) ≤ 1 := by + rw [← Finset.expect_sum_comm] + calc + _ ≤ 𝔼 _X : E →ₗ[F2] F, (1 : ℝ) := + Finset.expect_le_expect fun X _ => sum_indicator_sq_le f X + _ = 1 := Fintype.expect_const _ + +theorem exists_dense_slice_all (r : Nat) (ρ η : ℝ) (hρ : 0 < ρ) (hρ1 : ρ < 1) + (hconstants : levelCutoffConstant r ρ + node (r + 1) < η) + (f : (E →ₗ[F2] F) → Option Y) (hagreement : η ≤ allAgreement f) : + ∃ (y : Y) (W : Submodule F2 E) (C' : Submodule F2 F) (T : E →ₗ[F2] F), + order W C' ≤ r ∧ ρ < (𝔼 N, restrict (indicator f y) W C' T N) := by + apply exists_dense_restriction_of_family r ρ η hρ hρ1 hconstants (indicator f) + (indicator_boolean f) (indicator_mass_le_one f) + rwa [← allAgreement_eq_sum] + +omit [FiniteDimensional F2 E] [FiniteDimensional F2 F] [Finite E] + [Fintype F] [Fintype (F →ₗ[F2] E)] [Fintype Y] in +theorem stepAgreement_le_zero (f : (E →ₗ[F2] F) → Option Y) (a : F) : + stepAgreement f a ≤ stepAgreement f 0 := by + apply Finset.expect_le_expect + intro X _ + apply Finset.expect_le_expect + intro h _ + simpa using definedEquality_le_self f X (X + h.smulRight a) + +def nonzeroAgreement (f : (E →ₗ[F2] F) → Option Y) : ℝ := + 𝔼 a : {a : F // a ≠ 0}, stepAgreement f a.val + +omit [FiniteDimensional F2 E] [FiniteDimensional F2 F] [Finite E] + [Fintype (F →ₗ[F2] E)] [Fintype Y] in +theorem nonzeroAgreement_le_all [Nontrivial F] + (f : (E →ₗ[F2] F) → Option Y) : + nonzeroAgreement f ≤ allAgreement f := + PerfectCompleteness.NonzeroAverage.nonzero_expect_le_expect + (stepAgreement f) (stepAgreement_le_zero f) + +theorem exists_dense_slice_nonzero [Nontrivial F] + (r : Nat) (ρ η : ℝ) (hρ : 0 < ρ) (hρ1 : ρ < 1) + (hconstants : levelCutoffConstant r ρ + node (r + 1) < η) + (f : (E →ₗ[F2] F) → Option Y) (hagreement : η ≤ nonzeroAgreement f) : + ∃ (y : Y) (W : Submodule F2 E) (C' : Submodule F2 F) (T : E →ₗ[F2] F), + order W C' ≤ r ∧ ρ < (𝔼 N, restrict (indicator f y) W C' T N) := + exists_dense_slice_all r ρ η hρ hρ1 hconstants f + (hagreement.trans (nonzeroAgreement_le_all f)) + +end +end PerfectCompleteness.PartialTableInverse + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/PartitionsLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/PartitionsLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..9170476d7db6170b75bce32c91038f136b8c5ec5 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/PartitionsLemmas.lean @@ -0,0 +1,776 @@ +import Mathlib.Algebra.Field.ZMod +import Mathlib.Data.Finset.Piecewise +import Mathlib.Data.Fintype.EquivFin +import Mathlib.Data.Fintype.Powerset +import Mathlib.FieldTheory.Finiteness +import Mathlib.LinearAlgebra.Dimension.Constructions +import Mathlib.LinearAlgebra.Dual.Defs +import Mathlib.LinearAlgebra.Dual.Lemmas +import Mathlib.LinearAlgebra.FiniteDimensional.Basic +import Mathlib.LinearAlgebra.Pi +import Mathlib.LinearAlgebra.Span.Basic +import Mathlib.Logic.Function.Basic +import Mathlib.SetTheory.Cardinal.Finite +import Mathlib.Tactic.Abel +import OAI.Computability.UniqueGames.Reduction.BinaryLinear + +namespace OAI + +section + +namespace PerfectCompleteness.CanonicalPartition + +variable {X Y Z W : Type*} + +def fiber (f : X → Y) (y : Y) : Set X := {x | f x = y} + +def parts (f : X → Y) : Set (Set X) := + Set.range fun x => fiber f (f x) + +abbrev Part (f : X → Y) := ↥(parts f) + +def label (f : X → Y) (x : X) : Part f := + ⟨fiber f (f x), ⟨x, rfl⟩⟩ + +instance [Nonempty X] (f : X → Y) : Nonempty (Part f) := by + obtain ⟨x⟩ := ‹Nonempty X› + exact ⟨label f x⟩ + +instance [Finite X] (f : X → Y) : Finite (Part f) := by + dsimp [Part] + infer_instance + +noncomputable def representative (f : X → Y) (P : Part f) : X := + P.property.choose + +theorem representative_spec (f : X → Y) (P : Part f) : + fiber f (f (representative f P)) = P.val := + P.property.choose_spec + +noncomputable def output (f : X → Y) (P : Part f) : Y := + f (representative f P) + +theorem part_eq_fiber (f : X → Y) (P : Part f) : + P.val = fiber f (output f P) := + (representative_spec f P).symm + +theorem mem_iff (f : X → Y) (P : Part f) (x : X) : + x ∈ P.val ↔ f x = output f P := by + rw [part_eq_fiber f P] + rfl + +theorem part_nonempty (f : X → Y) (P : Part f) : P.val.Nonempty := by + refine ⟨representative f P, ?_⟩ + exact (mem_iff f P _).2 rfl + +theorem output_mem_range (f : X → Y) (P : Part f) : + output f P ∈ Set.range f := + ⟨representative f P, rfl⟩ + +@[simp] theorem output_label (f : X → Y) (x : X) : + output f (label f x) = f x := by + have hx : x ∈ (label f x).val := rfl + exact ((mem_iff f (label f x) x).1 hx).symm + +theorem output_injective (f : X → Y) : Function.Injective (output f) := by + intro P Q h + apply Subtype.ext + rw [part_eq_fiber f P, part_eq_fiber f Q, h] + +@[simp] theorem label_representative (f : X → Y) (P : Part f) : + label f (representative f P) = P := by + apply Subtype.ext + exact representative_spec f P + +theorem label_surjective (f : X → Y) : Function.Surjective (label f) := by + intro P + exact ⟨representative f P, label_representative f P⟩ + +theorem card_parts_le [Finite X] (f : X → Y) : + Nat.card (Part f) ≤ Nat.card X := + Nat.card_le_card_of_surjective (label f) (label_surjective f) + +theorem restoration_bijective (f : X → Y) : + Function.Bijective + (fun P : Part f => (⟨output f P, output_mem_range f P⟩ : Set.range f)) := by + constructor + · intro P Q h + exact output_injective f (congrArg Subtype.val h) + · intro y + obtain ⟨x, hx⟩ := y.property + refine ⟨label f x, ?_⟩ + apply Subtype.ext + exact (output_label f x).trans hx + +theorem parts_eq_of_kernel_eq (f : X → Y) (g : X → Z) + (h : ∀ x x', f x = f x' ↔ g x = g x') : parts f = parts g := by + have hfiber : ∀ x, fiber f (f x) = fiber g (g x) := by + intro x + ext x' + exact h x' x + apply Set.ext + intro P + constructor + · rintro ⟨x, hx⟩ + exact ⟨x, (hfiber x).symm.trans hx⟩ + · rintro ⟨x, hx⟩ + exact ⟨x, (hfiber x).trans hx⟩ + +theorem kernel_le_of_parts_subset (f : X → Y) (g : X → Z) + (h : parts f ⊆ parts g) {x x' : X} (hxx' : f x = f x') : + g x = g x' := by + obtain ⟨z, hz⟩ := h (show fiber f (f x') ∈ parts f from ⟨x', rfl⟩) + change fiber g (g z) = fiber f (f x') at hz + have hx : x ∈ fiber g (g z) := by + rw [hz] + exact hxx' + have hx' : x' ∈ fiber g (g z) := by + rw [hz] + rfl + exact hx.trans hx'.symm + +theorem parts_eq_iff_kernel_eq (f : X → Y) (g : X → Z) : + parts f = parts g ↔ ∀ x x', f x = f x' ↔ g x = g x' := by + constructor + · intro h x x' + exact ⟨kernel_le_of_parts_subset f g (fun _ hP => h ▸ hP), + kernel_le_of_parts_subset g f (fun _ hP => h.symm ▸ hP)⟩ + · exact parts_eq_of_kernel_eq f g + +theorem label_val_eq_of_parts_eq (f : X → Y) (g : X → Z) + (h : parts f = parts g) (x : X) : + (label f x).val = (label g x).val := by + ext x' + exact (parts_eq_iff_kernel_eq f g).1 h x' x + +theorem parts_postcomp_injective (f : X → Y) (p : Y → Z) + (hp : Function.Injective p) : parts (p ∘ f) = parts f := by + apply parts_eq_of_kernel_eq + intro x x' + exact ⟨fun h => hp h, fun h => congrArg p h⟩ + +noncomputable def coarsen (f : X → Y) (p : Y → Z) (P : Part f) : + Part (p ∘ f) := + label (p ∘ f) (representative f P) + +@[simp] theorem output_coarsen (f : X → Y) (p : Y → Z) (P : Part f) : + output (p ∘ f) (coarsen f p P) = p (output f P) := + output_label (p ∘ f) (representative f P) + +theorem coarsen_eq_iff (f : X → Y) (p : Y → Z) + (P : Part f) (Q : Part (p ∘ f)) : + coarsen f p P = Q ↔ p (output f P) = output (p ∘ f) Q := by + constructor + · intro h + rw [← output_coarsen f p P, h] + · intro h + apply output_injective (p ∘ f) + exact (output_coarsen f p P).trans h + +theorem subset_coarsen (f : X → Y) (p : Y → Z) (P : Part f) : + P.val ⊆ (coarsen f p P).val := by + intro x hx + apply (mem_iff (p ∘ f) (coarsen f p P) x).2 + rw [output_coarsen] + exact congrArg p ((mem_iff f P x).1 hx) + +@[simp] theorem coarsen_label (f : X → Y) (p : Y → Z) (x : X) : + coarsen f p (label f x) = label (p ∘ f) x := by + apply (coarsen_eq_iff f p _ _).2 + rw [output_label, output_label] + rfl + +theorem coarsen_surjective (f : X → Y) (p : Y → Z) : + Function.Surjective (coarsen f p) := by + intro Q + refine ⟨label f (representative (p ∘ f) Q), ?_⟩ + rw [coarsen_label, label_representative] + +theorem card_coarsen_fiber_le [Finite Y] (f : X → Y) (p : Y → Z) + (Q : Part (p ∘ f)) : + Nat.card {P : Part f // coarsen f p P = Q} ≤ + Nat.card {y : Y // p y = output (p ∘ f) Q} := by + let restoreFiber : {P : Part f // coarsen f p P = Q} → + {y : Y // p y = output (p ∘ f) Q} := + fun P => ⟨output f P.val, (coarsen_eq_iff f p P.val Q).1 P.property⟩ + apply Nat.card_le_card_of_injective restoreFiber + intro P P' h + apply Subtype.ext + apply output_injective f + exact congrArg Subtype.val h + +theorem coarsen_at_most_two [Finite Y] (f : X → Y) (p : Y → Z) + (hp : ∀ z : Z, Nat.card {y : Y // p y = z} ≤ 2) + (Q : Part (p ∘ f)) : + Nat.card {P : Part f // coarsen f p P = Q} ≤ 2 := + (card_coarsen_fiber_le f p Q).trans (hp (output (p ∘ f) Q)) + +def binaryDeletionFiberEquiv (y : Y) : + {v : Bool × Y // v.2 = y} ≃ Bool where + toFun v := v.val.1 + invFun b := ⟨(b, y), rfl⟩ + left_inv v := by + apply Subtype.ext + exact Prod.ext rfl v.property.symm + right_inv _ := rfl + +theorem card_binaryDeletion_fiber (y : Y) : + Nat.card {v : Bool × Y // v.2 = y} = 2 := by + rw [Nat.card_congr (binaryDeletionFiberEquiv y), Nat.card_eq_fintype_card] + exact Fintype.card_bool + +theorem binaryDeletion_at_most_two [Finite Y] (f : X → Bool × Y) + (Q : Part (Prod.snd ∘ f)) : + Nat.card {P : Part f // coarsen f Prod.snd P = Q} ≤ 2 := by + apply coarsen_at_most_two f Prod.snd + intro y + exact (card_binaryDeletion_fiber y).le + +theorem evaluation_consistent_and_satisfying (x : X) : + (∀ (f : X → Y) (g : X → Z), parts f = parts g → + (label f x).val = (label g x).val) ∧ + (∀ (f : X → Y) (p : Y → Z), + coarsen f p (label f x) = label (p ∘ f) x) := by + exact ⟨fun f g h => label_val_eq_of_parts_eq f g h x, + fun f p => coarsen_label f p x⟩ + +end PerfectCompleteness.CanonicalPartition + +end + +section + +namespace PerfectCompleteness.PointwiseSpaces + +variable {X Y Z : Type*} + +def pullback (𝕜 : Type*) [Field 𝕜] (r : X → Y) : + (Y → 𝕜) →ₗ[𝕜] (X → 𝕜) where + toFun f := fun x => f (r x) + map_add' _ _ := rfl + map_smul' _ _ := rfl + +variable {𝕜 : Type*} [Field 𝕜] + +@[simp] theorem pullback_apply (r : X → Y) (f : Y → 𝕜) (x : X) : + pullback 𝕜 r f x = f (r x) := rfl + +@[simp] theorem pullback_one (r : X → Y) : + pullback 𝕜 r (1 : Y → 𝕜) = (1 : X → 𝕜) := rfl + +@[simp] theorem pullback_mul (r : X → Y) (f g : Y → 𝕜) : + pullback 𝕜 r (f * g) = pullback 𝕜 r f * pullback 𝕜 r g := rfl + +theorem pullback_comp (r : X → Y) (s : Y → Z) : + (pullback 𝕜 r).comp (pullback 𝕜 s) = pullback 𝕜 (s ∘ r) := by + ext f x + rfl + +theorem pullback_injective (r : X → Y) (hr : Function.Surjective r) : + Function.Injective (pullback 𝕜 r) := by + intro f g h + funext y + obtain ⟨x, rfl⟩ := hr y + exact congrFun h x + +def squareSpace (H : Submodule 𝕜 (X → 𝕜)) : Submodule 𝕜 (X → 𝕜) := + Submodule.span 𝕜 {u | ∃ f ∈ H, ∃ g ∈ H, f * g = u} + +theorem mul_mem_squareSpace (H : Submodule 𝕜 (X → 𝕜)) + {f g : X → 𝕜} (hf : f ∈ H) (hg : g ∈ H) : + f * g ∈ squareSpace H := + Submodule.subset_span ⟨f, hf, g, hg, rfl⟩ + +theorem squareSpace_mono {H K : Submodule 𝕜 (X → 𝕜)} (h : H ≤ K) : + squareSpace H ≤ squareSpace K := by + apply Submodule.span_mono + rintro u ⟨f, hf, g, hg, rfl⟩ + exact ⟨f, h hf, g, h hg, rfl⟩ + +theorem le_squareSpace (H : Submodule 𝕜 (X → 𝕜)) (hone : (1 : X → 𝕜) ∈ H) : + H ≤ squareSpace H := by + intro f hf + simpa only [mul_one] using mul_mem_squareSpace H hf hone + +theorem one_mem_squareSpace (H : Submodule 𝕜 (X → 𝕜)) + (hone : (1 : X → 𝕜) ∈ H) : (1 : X → 𝕜) ∈ squareSpace H := + le_squareSpace H hone hone + +theorem squareSpace_pullback_le (r : X → Y) + (H : Submodule 𝕜 (Y → 𝕜)) (K : Submodule 𝕜 (X → 𝕜)) + (h : H.map (pullback 𝕜 r) ≤ K) : + (squareSpace H).map (pullback 𝕜 r) ≤ squareSpace K := by + apply (Submodule.map_span_le _ _ _).2 + rintro u ⟨f, hf, g, hg, rfl⟩ + simpa only [pullback_mul] using mul_mem_squareSpace K + (h (Submodule.mem_map_of_mem hf)) (h (Submodule.mem_map_of_mem hg)) + +theorem squareSpace_map_pullback (r : X → Y) (H : Submodule 𝕜 (Y → 𝕜)) : + (squareSpace H).map (pullback 𝕜 r) = squareSpace (H.map (pullback 𝕜 r)) := by + apply le_antisymm + · exact squareSpace_pullback_le r H _ le_rfl + · apply Submodule.span_le.mpr + rintro u ⟨f, hf, g, hg, rfl⟩ + obtain ⟨f', hf', rfl⟩ := Submodule.mem_map.mp hf + obtain ⟨g', hg', rfl⟩ := Submodule.mem_map.mp hg + exact Submodule.mem_map.mpr ⟨f' * g', mul_mem_squareSpace H hf' hg', rfl⟩ + +section Children + +variable {J : Type*} {D E : J → Type*} + +def childSpace (r : ∀ i, X → D i) (H : ∀ i, Submodule 𝕜 (D i → 𝕜)) : + Submodule 𝕜 (X → 𝕜) := + ⨆ i, (squareSpace (H i)).map (pullback 𝕜 (r i)) + +theorem child_square_le (r : ∀ i, X → D i) + (H : ∀ i, Submodule 𝕜 (D i → 𝕜)) (i : J) : + (squareSpace (H i)).map (pullback 𝕜 (r i)) ≤ childSpace r H := + le_iSup (fun j => (squareSpace (H j)).map (pullback 𝕜 (r j))) i + +theorem child_le (r : ∀ i, X → D i) + (H : ∀ i, Submodule 𝕜 (D i → 𝕜)) (i : J) + (hone : (1 : D i → 𝕜) ∈ H i) : + (H i).map (pullback 𝕜 (r i)) ≤ childSpace r H := by + intro f hf + obtain ⟨g, hg, rfl⟩ := Submodule.mem_map.mp hf + exact child_square_le r H i + (Submodule.mem_map_of_mem (le_squareSpace (H i) hone hg)) + +theorem one_mem_childSpace_of_child (r : ∀ i, X → D i) + (H : ∀ i, Submodule 𝕜 (D i → 𝕜)) (i : J) + (hone : (1 : D i → 𝕜) ∈ H i) : (1 : X → 𝕜) ∈ childSpace r H := by + have h : pullback 𝕜 (r i) (1 : D i → 𝕜) ∈ childSpace r H := + child_square_le r H i + (Submodule.mem_map_of_mem (one_mem_squareSpace (H i) hone)) + simpa only [pullback_one] using h + +theorem one_mem_childSpace [Nonempty J] (r : ∀ i, X → D i) + (H : ∀ i, Submodule 𝕜 (D i → 𝕜)) + (hone : ∀ i, (1 : D i → 𝕜) ∈ H i) : (1 : X → 𝕜) ∈ childSpace r H := by + obtain ⟨i⟩ := ‹Nonempty J› + exact one_mem_childSpace_of_child r H i (hone i) + +theorem childSpace_mono (r : ∀ i, X → D i) + (H K : ∀ i, Submodule 𝕜 (D i → 𝕜)) (h : ∀ i, H i ≤ K i) : + childSpace r H ≤ childSpace r K := by + exact iSup_mono (fun i => Submodule.map_mono (squareSpace_mono (h i))) + +theorem childSpace_pullback_le (p : X → Y) + (rY : ∀ i, Y → D i) (rX : ∀ i, X → E i) (q : ∀ i, E i → D i) + (H : ∀ i, Submodule 𝕜 (D i → 𝕜)) (K : ∀ i, Submodule 𝕜 (E i → 𝕜)) + (hcomm : ∀ i x, q i (rX i x) = rY i (p x)) + (hchild : ∀ i, (H i).map (pullback 𝕜 (q i)) ≤ K i) : + (childSpace rY H).map (pullback 𝕜 p) ≤ childSpace rX K := by + simp only [childSpace, Submodule.map_iSup] + apply iSup_mono + intro i + have hcomp : (pullback 𝕜 p).comp (pullback 𝕜 (rY i)) = + (pullback 𝕜 (rX i)).comp (pullback 𝕜 (q i)) := by + ext f x + exact congrArg f (hcomm i x).symm + calc + ((squareSpace (H i)).map (pullback 𝕜 (rY i))).map (pullback 𝕜 p) = + ((squareSpace (H i)).map (pullback 𝕜 (q i))).map (pullback 𝕜 (rX i)) := by + rw [← Submodule.map_comp, ← Submodule.map_comp, hcomp] + _ ≤ (squareSpace (K i)).map (pullback 𝕜 (rX i)) := + Submodule.map_mono (squareSpace_pullback_le (q i) (H i) (K i) (hchild i)) + +end Children + +end PerfectCompleteness.PointwiseSpaces + +end + +section + +namespace PerfectCompleteness.ProductReduction + +variable {I : Type*} {X R W : I → Type*} {Y : Type*} + +def productMap (r : ∀ i, X i → R i) (x : ∀ i, X i) : ∀ i, R i := + fun i => r i (x i) + +@[simp] theorem productMap_apply (r : ∀ i, X i → R i) + (x : ∀ i, X i) (i : I) : productMap r x i = r i (x i) := rfl + +theorem productMap_surjective (r : ∀ i, X i → R i) + (hr : ∀ i, Function.Surjective (r i)) : + Function.Surjective (productMap r) := by + intro z + refine ⟨fun i => (hr i (z i)).choose, ?_⟩ + funext i + exact (hr i (z i)).choose_spec + +def CoordinateInvariant (r : ∀ i, X i → R i) (f : (∀ i, X i) → Y) : Prop := + ∀ (i : I) (x x' : ∀ i, X i), + (∀ j, j ≠ i → x j = x' j) → + r i (x i) = r i (x' i) → f x = f x' + +theorem coordinateInvariant_of_update [DecidableEq I] + (r : ∀ i, X i → R i) (f : (∀ i, X i) → Y) + (hf : ∀ (i : I) (x : ∀ i, X i) (u : X i), + r i (x i) = r i u → f x = f (Function.update x i u)) : + CoordinateInvariant r f := by + intro i x x' hfixed hr + have hupdate : Function.update x i (x' i) = x' := + Function.update_eq_iff.2 ⟨rfl, hfixed⟩ + exact (hf i x (x' i) hr).trans (congrArg f hupdate) + +theorem CoordinateInvariant.update [DecidableEq I] + {r : ∀ i, X i → R i} {f : (∀ i, X i) → Y} + (hf : CoordinateInvariant r f) (i : I) (x : ∀ i, X i) (u : X i) + (hr : r i (x i) = r i u) : f x = f (Function.update x i u) := by + apply hf i x (Function.update x i u) + · intro j hji + exact (Function.update_of_ne hji u x).symm + · simpa only [Function.update_self] using hr + +theorem constant_on_product_fibers [Finite I] + (r : ∀ i, X i → R i) (f : (∀ i, X i) → Y) + (hf : CoordinateInvariant r f) {x x' : ∀ i, X i} + (h : productMap r x = productMap r x') : f x = f x' := by + classical + let : Fintype I := Fintype.ofFinite I + have hreplace : ∀ s : Finset I, f (s.piecewise x' x) = f x := by + intro s + induction s using Finset.induction_on with + | empty => simp only [Finset.piecewise_empty] + | @insert i s hi ih => + have hstep : f ((insert i s).piecewise x' x) = f (s.piecewise x' x) := by + apply hf i + · intro j hji + exact Finset.piecewise_insert_of_ne s x' x hji + · simp only [Finset.piecewise_insert_self, + Finset.piecewise_eq_of_notMem s x' x hi] + exact (congrFun h i).symm + exact hstep.trans ih + simpa only [Finset.piecewise_univ] using (hreplace Finset.univ).symm + +noncomputable def preimage (r : ∀ i, X i → R i) + (hr : ∀ i, Function.Surjective (r i)) (z : ∀ i, R i) : ∀ i, X i := + (productMap_surjective r hr z).choose + +@[simp] theorem productMap_preimage (r : ∀ i, X i → R i) + (hr : ∀ i, Function.Surjective (r i)) (z : ∀ i, R i) : + productMap r (preimage r hr z) = z := + (productMap_surjective r hr z).choose_spec + +noncomputable def induced (r : ∀ i, X i → R i) + (hr : ∀ i, Function.Surjective (r i)) (f : (∀ i, X i) → Y) : + (∀ i, R i) → Y := + fun z => f (preimage r hr z) + +@[simp] theorem induced_productMap [Finite I] + (r : ∀ i, X i → R i) (hr : ∀ i, Function.Surjective (r i)) + (f : (∀ i, X i) → Y) (hf : CoordinateInvariant r f) (x : ∀ i, X i) : + induced r hr f (productMap r x) = f x := by + apply constant_on_product_fibers r f hf + exact productMap_preimage r hr (productMap r x) + +theorem induced_factorization [Finite I] + (r : ∀ i, X i → R i) (hr : ∀ i, Function.Surjective (r i)) + (f : (∀ i, X i) → Y) (hf : CoordinateInvariant r f) : + f = induced r hr f ∘ productMap r := by + funext x + exact (induced_productMap r hr f hf x).symm + +theorem induced_unique (r : ∀ i, X i → R i) + (hr : ∀ i, Function.Surjective (r i)) (f : (∀ i, X i) → Y) + (g : (∀ i, R i) → Y) (hg : ∀ x, g (productMap r x) = f x) : + g = induced r hr f := by + funext z + calc + g z = g (productMap r (preimage r hr z)) := + congrArg g (productMap_preimage r hr z).symm + _ = f (preimage r hr z) := hg (preimage r hr z) + _ = induced r hr f z := rfl + +theorem coordinateInvariant_pullback + (p : ∀ i, X i → W i) (r : ∀ i, W i → R i) + (g : (∀ i, W i) → Y) (hg : CoordinateInvariant r g) : + CoordinateInvariant (fun i => r i ∘ p i) (g ∘ productMap p) := by + intro i x x' hfixed hr + apply hg i (productMap p x) (productMap p x') + · intro j hji + exact congrArg (p j) (hfixed j hji) + · exact hr + +theorem induced_eq_of_pullback [Finite I] + (p : ∀ i, X i → W i) + (rX : ∀ i, X i → R i) (rW : ∀ i, W i → R i) + (hrX : ∀ i, Function.Surjective (rX i)) + (hrW : ∀ i, Function.Surjective (rW i)) + (hcomm : ∀ i x, rX i x = rW i (p i x)) + (f : (∀ i, X i) → Y) (g : (∀ i, W i) → Y) + (hg : CoordinateInvariant rW g) + (hfg : ∀ x, f x = g (productMap p x)) : + induced rX hrX f = induced rW hrW g := by + symm + apply induced_unique rX hrX f + intro x + have hmap : productMap rX x = productMap rW (productMap p x) := by + funext i + exact hcomm i (x i) + rw [hmap, induced_productMap rW hrW g hg] + exact (hfg x).symm + +end PerfectCompleteness.ProductReduction + +end + +section + +namespace PerfectCompleteness.ProjectedColumnSlice + +noncomputable section + +variable {𝕜 H H' W : Type*} [Field 𝕜] + [AddCommGroup H] [Module 𝕜 H] [AddCommGroup H'] [Module 𝕜 H'] + [AddCommGroup W] [Module 𝕜 W] + (i : H' →ₗ[𝕜] H) (Z : Submodule 𝕜 (Module.Dual 𝕜 H)) + +def projectedColumns : Submodule 𝕜 (Module.Dual 𝕜 H') := Z.map i.dualMap + +def restrictionZ : Z →ₗ[𝕜] projectedColumns i Z := + (i.dualMap.comp Z.subtype).codRestrict (projectedColumns i Z) (by + intro z + exact Submodule.mem_map.mpr ⟨z.val, z.property, rfl⟩) + +@[simp] theorem restrictionZ_val (z : Z) : + (restrictionZ i Z z : Module.Dual 𝕜 H') = i.dualMap z := rfl + +@[simp] theorem restrictionZ_apply (z : Z) (h : H') : + (restrictionZ i Z z : Module.Dual 𝕜 H') h = z.val (i h) := rfl + +theorem restrictionZ_surjective : Function.Surjective (restrictionZ i Z) := by + intro q + obtain ⟨z, hz, heq⟩ := Submodule.mem_map.mp q.property + refine ⟨⟨z, hz⟩, ?_⟩ + apply Subtype.ext + exact heq + +theorem finrank_projectedColumns_le [FiniteDimensional 𝕜 Z] : + Module.finrank 𝕜 (projectedColumns i Z) ≤ Module.finrank 𝕜 Z := + Submodule.finrank_map_le i.dualMap Z + +def Compatible (v : Z →ₗ[𝕜] W) (X : Module.Dual 𝕜 H' →ₗ[𝕜] W) : Prop := + ∀ z : Z, X (i.dualMap z) = v z + +def targetQ (X₀ : Module.Dual 𝕜 H' →ₗ[𝕜] W) : projectedColumns i Z →ₗ[𝕜] W := + X₀.domRestrict (projectedColumns i Z) + +@[simp] theorem targetQ_apply (X₀ : Module.Dual 𝕜 H' →ₗ[𝕜] W) + (q : projectedColumns i Z) : targetQ i Z X₀ q = X₀ q.val := rfl + +theorem targetQ_comp_restrictionZ (v : Z →ₗ[𝕜] W) + (X₀ : Module.Dual 𝕜 H' →ₗ[𝕜] W) (h₀ : Compatible i Z v X₀) : + (targetQ i Z X₀).comp (restrictionZ i Z) = v := by + apply LinearMap.ext + exact h₀ + +theorem targetQ_independent (v : Z →ₗ[𝕜] W) + (X₀ X₁ : Module.Dual 𝕜 H' →ₗ[𝕜] W) + (h₀ : Compatible i Z v X₀) (h₁ : Compatible i Z v X₁) : + targetQ i Z X₀ = targetQ i Z X₁ := by + apply LinearMap.ext + intro q + obtain ⟨z, rfl⟩ := restrictionZ_surjective i Z q + exact (h₀ z).trans (h₁ z).symm + +theorem compatible_iff_domRestrict (v : Z →ₗ[𝕜] W) + (X₀ : Module.Dual 𝕜 H' →ₗ[𝕜] W) (h₀ : Compatible i Z v X₀) + (X : Module.Dual 𝕜 H' →ₗ[𝕜] W) : + Compatible i Z v X ↔ X.domRestrict (projectedColumns i Z) = targetQ i Z X₀ := by + constructor + · intro hX + exact targetQ_independent i Z v X X₀ hX h₀ + · intro hX z + have hz := LinearMap.congr_fun hX (restrictionZ i Z z) + exact hz.trans (h₀ z) + +theorem target_unique (v : Z →ₗ[𝕜] W) + (t₀ t₁ : projectedColumns i Z →ₗ[𝕜] W) + (h₀ : t₀.comp (restrictionZ i Z) = v) + (h₁ : t₁.comp (restrictionZ i Z) = v) : t₀ = t₁ := by + apply LinearMap.ext + intro q + obtain ⟨z, rfl⟩ := restrictionZ_surjective i Z q + exact (LinearMap.congr_fun h₀ z).trans (LinearMap.congr_fun h₁ z).symm + +def inducedTarget (v : Z →ₗ[𝕜] W) + (hne : ∃ X : Module.Dual 𝕜 H' →ₗ[𝕜] W, Compatible i Z v X) : + projectedColumns i Z →ₗ[𝕜] W := + targetQ i Z (Classical.choose hne) + +theorem inducedTarget_comp_restrictionZ (v : Z →ₗ[𝕜] W) + (hne : ∃ X : Module.Dual 𝕜 H' →ₗ[𝕜] W, Compatible i Z v X) : + (inducedTarget i Z v hne).comp (restrictionZ i Z) = v := + targetQ_comp_restrictionZ i Z v (Classical.choose hne) (Classical.choose_spec hne) + +theorem inducedTarget_eq_targetQ (v : Z →ₗ[𝕜] W) + (hne : ∃ X : Module.Dual 𝕜 H' →ₗ[𝕜] W, Compatible i Z v X) + (X₀ : Module.Dual 𝕜 H' →ₗ[𝕜] W) (h₀ : Compatible i Z v X₀) : + inducedTarget i Z v hne = targetQ i Z X₀ := + targetQ_independent i Z v (Classical.choose hne) X₀ (Classical.choose_spec hne) h₀ + +theorem compatible_iff_inducedTarget (v : Z →ₗ[𝕜] W) + (hne : ∃ X : Module.Dual 𝕜 H' →ₗ[𝕜] W, Compatible i Z v X) + (X : Module.Dual 𝕜 H' →ₗ[𝕜] W) : + Compatible i Z v X ↔ + X.domRestrict (projectedColumns i Z) = inducedTarget i Z v hne := + compatible_iff_domRestrict i Z v (Classical.choose hne) (Classical.choose_spec hne) X + +def sliceEquiv (v : Z →ₗ[𝕜] W) + (hne : ∃ X : Module.Dual 𝕜 H' →ₗ[𝕜] W, Compatible i Z v X) : + {X : Module.Dual 𝕜 H' →ₗ[𝕜] W // Compatible i Z v X} ≃ + {X : Module.Dual 𝕜 H' →ₗ[𝕜] W // + X.domRestrict (projectedColumns i Z) = inducedTarget i Z v hne} where + toFun X := ⟨X.val, (compatible_iff_inducedTarget i Z v hne X.val).mp X.property⟩ + invFun X := ⟨X.val, (compatible_iff_inducedTarget i Z v hne X.val).mpr X.property⟩ + left_inv _ := rfl + right_inv _ := rfl + +end +end PerfectCompleteness.ProjectedColumnSlice + +end + +section + +namespace PerfectCompleteness.PulledColumnSpace + +noncomputable section + +open UniqueGamesTheorem.Integration.BinaryLinear (F2) + +variable {H : Type*} [AddCommGroup H] [Module F2 H] + +def pulled (W : Submodule F2 H) (C : Submodule F2 (Module.Dual F2 (H ⧸ W))) : + Submodule F2 (Module.Dual F2 H) := + C.map W.mkQ.dualMap + +theorem quotientDual_injective (W : Submodule F2 H) : + Function.Injective W.mkQ.dualMap := + LinearMap.dualMap_injective_of_surjective W.mkQ_surjective + +def pulledEquiv (W : Submodule F2 H) (C : Submodule F2 (Module.Dual F2 (H ⧸ W))) : + C ≃ₗ[F2] pulled W C := + Submodule.equivMapOfInjective W.mkQ.dualMap (quotientDual_injective W) C + +@[simp] theorem pulledEquiv_val (W : Submodule F2 H) + (C : Submodule F2 (Module.Dual F2 (H ⧸ W))) (q : C) : + (pulledEquiv W C q : Module.Dual F2 H) = q.val.comp W.mkQ := rfl + +theorem pulled_le_annihilator (W : Submodule F2 H) + (C : Submodule F2 (Module.Dual F2 (H ⧸ W))) : + pulled W C ≤ W.dualAnnihilator := by + rintro q ⟨p, hp, rfl⟩ + apply (Submodule.mem_dualAnnihilator (W := W) _).mpr + intro w hw + change p (W.mkQ w) = 0 + have hwzero : W.mkQ w = 0 := (Submodule.Quotient.mk_eq_zero W).mpr hw + rw [hwzero, map_zero] + +theorem finrank_pulled (W : Submodule F2 H) + (C : Submodule F2 (Module.Dual F2 (H ⧸ W))) : + Module.finrank F2 (pulled W C) = Module.finrank F2 C := + (pulledEquiv W C).finrank_eq.symm + +theorem finrank_pulled_le (W : Submodule F2 H) + (C : Submodule F2 (Module.Dual F2 (H ⧸ W))) {r : Nat} + (hC : Module.finrank F2 C ≤ r) : Module.finrank F2 (pulled W C) ≤ r := by + rw [finrank_pulled] + exact hC + +def Candidates (W : Submodule F2 H) (C : Submodule F2 (Module.Dual F2 (H ⧸ W))) + (center : Module.Dual F2 H) := + {q : Module.Dual F2 H // q - center ∈ pulled W C} + +instance candidatesNonempty (W : Submodule F2 H) + (C : Submodule F2 (Module.Dual F2 (H ⧸ W))) (center : Module.Dual F2 H) : + Nonempty (Candidates W C center) := ⟨⟨center, by + rw [sub_self] + exact (pulled W C).zero_mem⟩⟩ + +def candidateEquiv (W : Submodule F2 H) + (C : Submodule F2 (Module.Dual F2 (H ⧸ W))) (center : Module.Dual F2 H) : + pulled W C ≃ Candidates W C center where + toFun q := ⟨center + q.val, by + have he : center + q.val - center = q.val := by abel + rw [he] + exact q.property⟩ + invFun q := ⟨q.val - center, q.property⟩ + left_inv q := by + apply Subtype.ext + change center + q.val - center = q.val + abel + right_inv q := by + apply Subtype.ext + change center + (q.val - center) = q.val + abel + +@[simp] theorem candidateEquiv_val (W : Submodule F2 H) + (C : Submodule F2 (Module.Dual F2 (H ⧸ W))) (center : Module.Dual F2 H) + (q : pulled W C) : + (candidateEquiv W C center q).val = center + q.val := rfl + +theorem candidate_apply_known (W : Submodule F2 H) + (C : Submodule F2 (Module.Dual F2 (H ⧸ W))) (center : Module.Dual F2 H) + (q : Candidates W C center) (w : W) : q.val w = center w := by + have hq := (Submodule.mem_dualAnnihilator (W := W) (q.val - center)).mp + (pulled_le_annihilator W C q.property) w w.property + change q.val w - center w = 0 at hq + exact sub_eq_zero.mp hq + +variable [FiniteDimensional F2 H] + +theorem card_pulled (W : Submodule F2 H) + (C : Submodule F2 (Module.Dual F2 (H ⧸ W))) : + Nat.card (pulled W C) = 2 ^ Module.finrank F2 C := by + rw [Module.natCard_eq_pow_finrank (K := F2), finrank_pulled] + rw [show Nat.card F2 = 2 from Nat.card_zmod 2] + +theorem card_pulled_le (W : Submodule F2 H) + (C : Submodule F2 (Module.Dual F2 (H ⧸ W))) {r : Nat} + (hC : Module.finrank F2 C ≤ r) : Nat.card (pulled W C) ≤ 2 ^ r := by + rw [card_pulled] + exact Nat.pow_le_pow_right (by decide : 0 < 2) hC + +def candidatesEquivCoordinates (W : Submodule F2 H) + (C : Submodule F2 (Module.Dual F2 (H ⧸ W))) (center : Module.Dual F2 H) : + Candidates W C center ≃ (Fin (Module.finrank F2 C) → F2) := by + let : Module.Free F2 C := Module.Free.of_divisionRing F2 C + exact (candidateEquiv W C center).symm.trans + ((pulledEquiv W C).symm.toEquiv.trans (Module.finBasis F2 C).equivFun.toEquiv) + +instance candidatesFintype (W : Submodule F2 H) + (C : Submodule F2 (Module.Dual F2 (H ⧸ W))) (center : Module.Dual F2 H) : + Fintype (Candidates W C center) := + Fintype.ofEquiv (Fin (Module.finrank F2 C) → F2) + (candidatesEquivCoordinates W C center).symm + +theorem card_candidates (W : Submodule F2 H) + (C : Submodule F2 (Module.Dual F2 (H ⧸ W))) (center : Module.Dual F2 H) : + Nat.card (Candidates W C center) = 2 ^ Module.finrank F2 C := + (Nat.card_congr (candidateEquiv W C center)).symm.trans (card_pulled W C) + +theorem card_candidates_le (W : Submodule F2 H) + (C : Submodule F2 (Module.Dual F2 (H ⧸ W))) (center : Module.Dual F2 H) + {r : Nat} (hC : Module.finrank F2 C ≤ r) : + Nat.card (Candidates W C center) ≤ 2 ^ r := by + rw [card_candidates] + exact Nat.pow_le_pow_right (by decide : 0 < 2) hC + +theorem fintype_card_candidates (W : Submodule F2 H) + (C : Submodule F2 (Module.Dual F2 (H ⧸ W))) (center : Module.Dual F2 H) : + Fintype.card (Candidates W C center) = 2 ^ Module.finrank F2 C := by + rw [← Nat.card_eq_fintype_card] + exact card_candidates W C center + +end +end PerfectCompleteness.PulledColumnSpace + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/PrefixTests.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/PrefixTests.lean new file mode 100644 index 0000000000000000000000000000000000000000..e65817fe189774a14254584fae132ea1c1961a68 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/PrefixTests.lean @@ -0,0 +1,122 @@ +import Lean.Elab.Tactic.Omega +import OAI.Computability.PerfectCompleteness.Reduction.HierarchicalFixedAdviceFamilyLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.PrefixTests + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open scoped Classical + +noncomputable section + +variable {branch : Nat → Nat} {n cutoff : Nat} + +theorem nodeAtLevel_eq (p : Path branch n cutoff) : + ∀ (level : Fin n), cutoff ≤ level.val + 1 → + ∀ suffix reference : Slots branch cutoff, + GeometricPath.nodeAtLevel (p.slotEmbedding suffix) level = + GeometricPath.nodeAtLevel (p.slotEmbedding reference) level := by + induction p with + | refl n => + intro level hlevel suffix reference + cases n with + | zero => exact Fin.elim0 level + | succ n => + have hlast : level = Fin.last n := by + apply Fin.ext + simp only [Fin.val_last] + omega + subst level + exact (GeometricPath.nodeAtLevel_last (branch := branch) (n := n) suffix).trans + (GeometricPath.nodeAtLevel_last (branch := branch) (n := n) reference).symm + | @step n cutoff i p ih => + intro level + refine Fin.lastCases ?_ (fun lower => ?_) level + · intro _ suffix reference + exact (GeometricPath.nodeAtLevel_last (branch := branch) (n := n) + ((Path.step i p).slotEmbedding suffix)).trans + (GeometricPath.nodeAtLevel_last (branch := branch) (n := n) + ((Path.step i p).slotEmbedding reference)).symm + · intro hlevel suffix reference + change cutoff ≤ lower.val + 1 at hlevel + have hnode := congrArg (fun node : Nodes branch n => + (Sum.inr (i, node) : Nodes branch (n + 1))) + (ih lower hlevel suffix reference) + exact (GeometricPath.nodeAtLevel_castSucc (branch := branch) (n := n) + ((Path.step i p).slotEmbedding suffix) lower).trans + (hnode.trans (GeometricPath.nodeAtLevel_castSucc (branch := branch) (n := n) + ((Path.step i p).slotEmbedding reference) lower).symm) + +abbrev LevelDirection (rows : Nat → Nat) (level : Fin n) := + BucketSampler.Direction (rows (level.val + 1)) + +abbrev LevelNode (branch : Nat → Nat) {n : Nat} (level : Fin n) := + {node : Nodes branch n // Nodes.height node = level.val + 1} + +def levelNode (leaf : Slots branch n) (level : Fin n) : LevelNode branch level := + ⟨GeometricPath.nodeAtLevel leaf level, GeometricPath.nodeAtLevel_height leaf level⟩ + +theorem levelNode_eq (p : Path branch n cutoff) (level : Fin n) + (hlevel : cutoff ≤ level.val + 1) (suffix reference : Slots branch cutoff) : + levelNode (p.slotEmbedding suffix) level = levelNode (p.slotEmbedding reference) level := by + apply Subtype.ext + exact nodeAtLevel_eq p level hlevel suffix reference + +def nodeDirection (rows : Nat → Nat) (level : Fin n) (node : LevelNode branch level) + (direction : LevelDirection rows level) : + BucketSampler.Direction (rows (Nodes.height node.val)) := + (Equiv.cast (congrArg (fun height => BucketSampler.Direction (rows height)) node.property)).symm + direction + +def choiceAt (rows : Nat → Nat) (leaf : Slots branch n) (level : Fin n) + (direction : LevelDirection rows level) : PreliminarySampler.Choice rows leaf := + ⟨level, nodeDirection rows level (levelNode leaf level) direction⟩ + +variable {v m t : Nat} {rows : Nat → Nat} + +def observeAtLevelNode (clauses : Fin m → SourceClause.NormalizedClause v) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (q : PreliminarySampler.Questions branch n t m) + (arrays : Arrays (HierarchicalArrays.sourceSlots clauses (PreliminarySampler.endpoints q)) rows) + (level : Fin n) (node : LevelNode branch level) (direction : LevelDirection rows level) : Bool := + let P := HierarchicalArrays.presentation clauses (PreliminarySampler.endpoints q) rows arrays + let slots := SourceKeys.slot clauses ∘ P.endpoints + let projection := BlockQuotient.projectBlock + (V := fun node : Nodes branch n => Block rows node) (B := PUnit.{1}) + node.val (nodeDirection rows level node direction).val + decide (CanonicalEdges.coarsen slots P.joint projection + (KeyStrategy.label σ .left slots P.joint) = + KeyStrategy.label σ .right slots (projection ∘ P.joint)) + +theorem observe_choiceAt_eq (clauses : Fin m → SourceClause.NormalizedClause v) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (q : PreliminarySampler.Questions branch n t m) + (arrays : Arrays (HierarchicalArrays.sourceSlots clauses (PreliminarySampler.endpoints q)) rows) + (leaf : Slots branch n) (level : Fin n) (direction : LevelDirection rows level) : + PreliminaryStrategy.observe clauses σ (q, leaf) arrays (choiceAt rows leaf level direction) = + observeAtLevelNode clauses σ q arrays level (levelNode leaf level) direction := rfl + +theorem observe_above_cut_eq (clauses : Fin m → SourceClause.NormalizedClause v) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (q : PreliminarySampler.Questions branch n t m) + (arrays : Arrays (HierarchicalArrays.sourceSlots clauses (PreliminarySampler.endpoints q)) rows) + (p : Path branch n cutoff) (level : Fin n) (hlevel : cutoff ≤ level.val + 1) + (suffix reference : Slots branch cutoff) (direction : LevelDirection rows level) : + PreliminaryStrategy.observe clauses σ (q, p.slotEmbedding suffix) arrays + (choiceAt rows (p.slotEmbedding suffix) level direction) = + PreliminaryStrategy.observe clauses σ (q, p.slotEmbedding reference) arrays + (choiceAt rows (p.slotEmbedding reference) level direction) := by + simp only [observe_choiceAt_eq] + exact congrArg (fun node : LevelNode branch level => + observeAtLevelNode clauses σ q arrays level node direction) + (levelNode_eq p level hlevel suffix reference) + +end +end PerfectCompleteness.PrefixTests + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/ProjectedCallRestriction.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/ProjectedCallRestriction.lean new file mode 100644 index 0000000000000000000000000000000000000000..d591eeb2147036f6673a85853c0226924c23f485 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/ProjectedCallRestriction.lean @@ -0,0 +1,213 @@ +import OAI.Computability.PerfectCompleteness.Foundations.ProjectedPrefixComparison +import OAI.Computability.PerfectCompleteness.Sampling.RationalFiniteLawLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.ProjectedCallRestriction + +open RecursiveSpaces TreeSourceSpaces HierarchicalArrays PointwiseSpaces +open UniqueGamesTheorem.Foundations.Games +open scoped Classical + +noncomputable section + +variable {branch : Nat → Nat} {n t oldCalls enlargedCalls : Nat} + +def rawRestrict (rows : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (e : Fin oldCalls → Fin enlargedCalls) : + ChildBlockCardinality.Raw enlargedCalls rows slots →ₗ[F2] + ChildBlockCardinality.Raw oldCalls rows slots where + toFun block := (fun call => block.1 (e call), block.2) + map_add' _ _ := rfl + map_smul' _ _ := rfl + +@[simp] theorem rawRestrict_calls (rows : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (e : Fin oldCalls → Fin enlargedCalls) + (block : ChildBlockCardinality.Raw enlargedCalls rows slots) (call : Fin oldCalls) : + (rawRestrict rows slots e block).1 call = block.1 (e call) := rfl + +@[simp] theorem rawRestrict_arrays (rows : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (e : Fin oldCalls → Fin enlargedCalls) + (block : ChildBlockCardinality.Raw enlargedCalls rows slots) : + (rawRestrict rows slots e block).2 = block.2 := rfl + +theorem rawRestrict_surjective (rows : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (e : Fin oldCalls → Fin enlargedCalls) (he : Function.Injective e) : + Function.Surjective (rawRestrict rows slots e) := by + rintro ⟨calls, arrays⟩ + refine ⟨(Function.extend e calls (fun _ => 0), arrays), ?_⟩ + apply Prod.ext + · funext call + exact he.extend_apply calls (fun _ => 0) call + · rfl + +theorem uniform_restrict_law (rows : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (e : Fin oldCalls → Fin enlargedCalls) (he : Function.Injective e) : + (FiniteDistribution.uniform (ChildBlockCardinality.Raw enlargedCalls rows slots)).pushforward + (rawRestrict rows slots e) = + FiniteDistribution.uniform (ChildBlockCardinality.Raw oldCalls rows slots) := + UniformLinearImage.uniform_pushforward_linearMap + (rawRestrict rows slots e) (rawRestrict_surjective rows slots e he) + +theorem rawRestrict_pullback (rows : Nat → Nat) + {slots projected : Slots branch n → Fin t → MixedSupport.Slot} + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (e : Fin oldCalls → Fin enlargedCalls) + (block : ChildBlockCardinality.Raw enlargedCalls rows projected) : + rawRestrict rows slots e (ChildBlockProjection.rawPullback enlargedCalls rows p block) = + ChildBlockProjection.rawPullback oldCalls rows p (rawRestrict rows projected e block) := rfl + +theorem lifted_restrict_law (rows : Nat → Nat) + {slots projected : Slots branch n → Fin t → MixedSupport.Slot} + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (e : Fin oldCalls → Fin enlargedCalls) (he : Function.Injective e) : + (ChildBlockProjection.liftedLaw enlargedCalls rows p).pushforward (rawRestrict rows slots e) = + ChildBlockProjection.liftedLaw oldCalls rows p := by + unfold ChildBlockProjection.liftedLaw + rw [FiniteDistribution.pushforward_comp] + change (FiniteDistribution.uniform (ChildBlockCardinality.Raw enlargedCalls rows projected)).pushforward + (fun block => ChildBlockProjection.rawPullback oldCalls rows p + (rawRestrict rows projected e block)) = _ + rw [← FiniteDistribution.pushforward_comp + (FiniteDistribution.uniform (ChildBlockCardinality.Raw enlargedCalls rows projected)) + (rawRestrict rows projected e) (ChildBlockProjection.rawPullback oldCalls rows p), + uniform_restrict_law rows projected e he] + +theorem mixture_restrict_law {Z : Type*} [Fintype Z] (rows : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (projected : Z → Slots branch n → Fin t → MixedSupport.Slot) + (p : ∀ z s k, MixedSupport.Projection (slots s k) (projected z s k)) + (choiceLaw : FiniteDistribution Z) + (e : Fin oldCalls → Fin enlargedCalls) (he : Function.Injective e) : + (ChildBlockProjection.mixtureLaw enlargedCalls rows slots projected p choiceLaw).pushforward + (rawRestrict rows slots e) = + ChildBlockProjection.mixtureLaw oldCalls rows slots projected p choiceLaw := by + unfold ChildBlockProjection.mixtureLaw + rw [FiniteDistribution.pushforward_mixture] + apply congrArg choiceLaw.mixture + funext z + exact lifted_restrict_law rows (p z) e he + +private theorem sparse_pushforward {I : Type*} [Fintype I] [DecidableEq I] + {Ω Γ : I → Type*} [∀ i, Fintype (Ω i)] [∀ i, Fintype (Γ i)] + (P Q : (i : I) → FiniteDistribution (Ω i)) + (f : (i : I) → Ω i → Γ i) (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) : + (SparseReplacement.law P Q β hβ hβ').pushforward (fun x i => f i (x i)) = + SparseReplacement.law (fun i => (P i).pushforward (f i)) + (fun i => (Q i).pushforward (f i)) β hβ hβ' := by + unfold SparseReplacement.law + rw [FiniteProduct.pushforward_map (SparseReplacement.row P Q β hβ hβ') f] + apply congrArg (fun laws : (i : I) → FiniteDistribution (Γ i) => FiniteProduct.law laws) + funext i + unfold SparseReplacement.row + rw [FiniteDistribution.pushforward_mixture] + apply congrArg ((ProjectionPosterior.bernoulli β hβ hβ').mixture) + funext marked + cases marked <;> rfl + +def restrictChildren {I : Type*} (rows : Nat → Nat) + (slots : I → Slots branch n → Fin t → MixedSupport.Slot) + (e : Fin oldCalls → Fin enlargedCalls) + (blocks : (i : I) → ChildBlockCardinality.Raw enlargedCalls rows (slots i)) : + (i : I) → ChildBlockCardinality.Raw oldCalls rows (slots i) := + fun i => rawRestrict rows (slots i) e (blocks i) + +theorem sparse_restrict_law {I : Type*} [Fintype I] [DecidableEq I] + {Z : I → Type*} [∀ i, Fintype (Z i)] + (rows : Nat → Nat) (slots : I → Slots branch n → Fin t → MixedSupport.Slot) + (projected : (i : I) → Z i → Slots branch n → Fin t → MixedSupport.Slot) + (p : ∀ i z s k, MixedSupport.Projection (slots i s k) (projected i z s k)) + (choiceLaw : (i : I) → FiniteDistribution (Z i)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) + (e : Fin oldCalls → Fin enlargedCalls) (he : Function.Injective e) : + (SparseReplacement.law + (fun i => FiniteDistribution.uniform (ChildBlockCardinality.Raw enlargedCalls rows (slots i))) + (ChildBlockProjection.replacementLaws enlargedCalls rows slots projected p choiceLaw) + β hβ hβ').pushforward (restrictChildren rows slots e) = + SparseReplacement.law + (fun i => FiniteDistribution.uniform (ChildBlockCardinality.Raw oldCalls rows (slots i))) + (ChildBlockProjection.replacementLaws oldCalls rows slots projected p choiceLaw) + β hβ hβ' := by + unfold restrictChildren + rw [sparse_pushforward + (fun i => FiniteDistribution.uniform (ChildBlockCardinality.Raw enlargedCalls rows (slots i))) + (ChildBlockProjection.replacementLaws enlargedCalls rows slots projected p choiceLaw) + (fun i => ⇑(rawRestrict rows (slots i) e)) β hβ hβ'] + apply congrArg₂ (fun (P Q : (i : I) → + FiniteDistribution (ChildBlockCardinality.Raw oldCalls rows (slots i))) => + SparseReplacement.law P Q β hβ hβ') + · funext i + exact uniform_restrict_law rows (slots i) e he + · funext i + exact mixture_restrict_law rows (slots i) (projected i) (p i) (choiceLaw i) e he + +def assembledRestrict (rows : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (e : Fin oldCalls → Fin enlargedCalls) : + CutChildGrouping.Assembled (C := Fin enlargedCalls) slots rows →ₗ[F2] + CutChildGrouping.Assembled (C := Fin oldCalls) slots rows where + toFun record := (fun call => record.1 (e call), record.2) + map_add' _ _ := rfl + map_smul' _ _ := rfl + +@[simp] theorem assembledRestrict_calls (rows : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (e : Fin oldCalls → Fin enlargedCalls) + (record : CutChildGrouping.Assembled (C := Fin enlargedCalls) slots rows) + (call : Fin oldCalls) : + (assembledRestrict rows slots e record).1 call = record.1 (e call) := rfl + +@[simp] theorem assembledRestrict_arrays (rows : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (e : Fin oldCalls → Fin enlargedCalls) + (record : CutChildGrouping.Assembled (C := Fin enlargedCalls) slots rows) : + (assembledRestrict rows slots e record).2 = record.2 := rfl + +theorem assemble_restrict (rows : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (e : Fin oldCalls → Fin enlargedCalls) + (blocks : CutChildGrouping.Raw (C := Fin enlargedCalls) slots rows) : + assembledRestrict rows slots e (CutChildGrouping.assemble slots rows blocks) = + CutChildGrouping.assemble slots rows + (restrictChildren rows (fun i => childSlots slots i) e blocks) := rfl + +theorem assembled_restrict_law + {Z : Fin (branch n) → Type*} [∀ i, Fintype (Z i)] + (rows : Nat → Nat) (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (projected : (i : Fin (branch n)) → Z i → Slots branch n → Fin t → MixedSupport.Slot) + (p : ∀ i z s k, MixedSupport.Projection (childSlots slots i s k) (projected i z s k)) + (choiceLaw : (i : Fin (branch n)) → FiniteDistribution (Z i)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) + (e : Fin oldCalls → Fin enlargedCalls) (he : Function.Injective e) : + (ProjectedPrefixComparison.assembledLaw enlargedCalls rows slots projected p choiceLaw β hβ hβ').pushforward + (assembledRestrict rows slots e) = + ProjectedPrefixComparison.assembledLaw oldCalls rows slots projected p choiceLaw β hβ hβ' := by + unfold ProjectedPrefixComparison.assembledLaw + rw [FiniteDistribution.pushforward_comp] + have hmap : + (fun blocks : CutChildGrouping.Raw (C := Fin enlargedCalls) slots rows => + assembledRestrict rows slots e (CutChildGrouping.assemble slots rows blocks)) = + (fun blocks => CutChildGrouping.assemble slots rows + (restrictChildren rows (fun i => childSlots slots i) e blocks)) := rfl + rw [hmap, ← FiniteDistribution.pushforward_comp + (SparseReplacement.law + (fun i => FiniteDistribution.uniform (ChildBlockCardinality.Raw enlargedCalls rows (childSlots slots i))) + (ChildBlockProjection.replacementLaws enlargedCalls rows (fun i => childSlots slots i) + projected p choiceLaw) β hβ hβ') + (restrictChildren rows (fun i => childSlots slots i) e) + (CutChildGrouping.assemble (C := Fin oldCalls) slots rows), + sparse_restrict_law rows (fun i => childSlots slots i) projected p choiceLaw β hβ hβ' e he] + +end +end PerfectCompleteness.ProjectedCallRestriction + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/ProjectedCardinality.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/ProjectedCardinality.lean new file mode 100644 index 0000000000000000000000000000000000000000..41dda52ca607e6097b921cf8fe12b3a27e813705 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/ProjectedCardinality.lean @@ -0,0 +1,108 @@ +import OAI.Computability.PerfectCompleteness.Construction.TreeSourceSpaces +import OAI.Computability.PerfectCompleteness.Sampling.UniformLatent + +namespace OAI + +section + +namespace PerfectCompleteness.ProjectedCardinality + +open scoped BigOperators +open UniqueGamesTheorem.Foundations.Games +open TreeSourceSpaces PointwiseSpaces UniformLatent + +variable {branch : Nat → Nat} {n t : Nat} + +def projectedSlots (ids : RecursiveSpaces.Slots branch n → Fin t → Nat) : + RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot := + fun s k => MixedSupport.Slot.bit (ids s k) + +theorem projected_leaf_domain (ids : RecursiveSpaces.Slots branch n → Fin t → Nat) + (s : RecursiveSpaces.Slots branch n) : + LeafDomain (projectedSlots ids) s = (Fin t → Bool) := rfl + +def Factor (square : Bool) (ids : RecursiveSpaces.Slots branch n → Fin t → Nat) : Type := + if square then squareSpace (H (projectedSlots ids)) else H (projectedSlots ids) + +instance factorFinite (square : Bool) + (ids : RecursiveSpaces.Slots branch n → Fin t → Nat) : Finite (Factor square ids) := by + cases square <;> dsimp [Factor] <;> infer_instance + +noncomputable instance factorFintype (square : Bool) + (ids : RecursiveSpaces.Slots branch n → Fin t → Nat) : Fintype (Factor square ids) := + Fintype.ofFinite _ + +noncomputable instance factorDecidableEq (square : Bool) + (ids : RecursiveSpaces.Slots branch n → Fin t → Nat) : DecidableEq (Factor square ids) := + Classical.decEq _ + +def factorZero (square : Bool) (ids : RecursiveSpaces.Slots branch n → Fin t → Nat) : + Factor square ids := by + cases square + · change H (projectedSlots ids) + exact 0 + · change squareSpace (H (projectedSlots ids)) + exact 0 + +instance factorNonempty (square : Bool) + (ids : RecursiveSpaces.Slots branch n → Fin t → Nat) : Nonempty (Factor square ids) := + ⟨factorZero square ids⟩ + +def factorEquiv (square : Bool) + (ids ids' : RecursiveSpaces.Slots branch n → Fin t → Nat) : + Factor square ids ≃ Factor square ids' := by + cases square <;> exact Equiv.refl _ + +theorem factor_card_eq (square : Bool) + (ids ids' : RecursiveSpaces.Slots branch n → Fin t → Nat) : + Fintype.card (Factor square ids) = Fintype.card (Factor square ids') := + Fintype.card_congr (factorEquiv square ids ids') + +section Sampler + +variable {S J D : Type*} [Fintype S] [Fintype J] [DecidableEq J] [Fintype D] + (branch : Nat → Nat) (t : Nat) (height : J → Nat) (square : J → Bool) + +noncomputable def shapeCardinality (j : J) : Nat := + Fintype.card (Factor (branch := branch) (n := height j) (t := t) (square j) + (fun _ _ => 0)) + +omit [Fintype J] [DecidableEq J] in +theorem shapeCardinality_pos (j : J) : 0 < shapeCardinality branch t height square j := + Fintype.card_pos + +variable (ids : (s : S) → (j : J) → RecursiveSpaces.Slots branch (height j) → Fin t → Nat) + +abbrev Factors (s : S) (j : J) : Type := Factor (square j) (ids s j) + +omit [Fintype S] [Fintype J] [DecidableEq J] in +theorem factors_same_cardinality (s : S) (j : J) : + Fintype.card (Factors branch t height square ids s j) = + shapeCardinality branch t height square j := + factor_card_eq (square j) (ids s j) (fun _ _ => 0) + +theorem projected_tree_clean_probability (flag : FiniteDistribution Bool) + (nonprojected : S → FiniteDistribution D) (s : S) : + (projectedKernel (Factors branch t height square ids) flag nonprojected s).probability + (projectedZero (Factors branch t height square ids) + (fun s j => factorZero (square j) (ids s j))) = + flag.weight true * (∏ j, 1 / (shapeCardinality branch t height square j : ℝ)) := + probability_projectedKernel_zero_constant (Factors branch t height square ids) + flag nonprojected (fun s j => factorZero (square j) (ids s j)) + (shapeCardinality branch t height square) + (factors_same_cardinality branch t height square ids) s + +omit [DecidableEq J] in +theorem shape_zero_probability_pos : + 0 < (∏ j, 1 / (shapeCardinality branch t height square j : ℝ)) := by + apply Finset.prod_pos + intro j _ + exact one_div_pos.mpr (Nat.cast_pos.mpr (shapeCardinality_pos branch t height square j)) + +end Sampler + +end PerfectCompleteness.ProjectedCardinality + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/ProjectedCutChoices.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/ProjectedCutChoices.lean new file mode 100644 index 0000000000000000000000000000000000000000..632d230abec89f076ddb7ec716ed5895ae472414 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/ProjectedCutChoices.lean @@ -0,0 +1,178 @@ +import OAI.Computability.PerfectCompleteness.Decoding.ChildAssemblyProjection +import OAI.Computability.PerfectCompleteness.Foundations.MultiplicationFormInjectiveLemmas +import OAI.Computability.PerfectCompleteness.Foundations.ProjectedPrefixComparison + +namespace OAI + +section + +namespace PerfectCompleteness.ProjectedCutChoices + +open RecursiveSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +noncomputable section + +private theorem mixture_const {A B : Type*} [Fintype A] [Fintype B] + (μ : FiniteDistribution A) (ν : FiniteDistribution B) : + μ.mixture (fun _ => ν) = ν := by + apply FiniteDistribution.eq_of_weight_eq + intro x + change (∑ a, μ.weight a * ν.weight x) = ν.weight x + rw [← Finset.sum_mul, μ.normalized, one_mul] + +private theorem product_mixture {A B C : Type*} [Fintype A] [Fintype B] [Fintype C] + (μ : FiniteDistribution A) (ν : FiniteDistribution B) + (P : A × B → FiniteDistribution C) : + (μ.product ν).mixture P = μ.mixture (fun a => ν.mixture (fun b => P (a, b))) := by + apply FiniteDistribution.eq_of_weight_eq + intro x + simp only [FiniteDistribution.mixture, + FiniteDistribution.product, Fintype.sum_prod_type, Finset.mul_sum, mul_assoc] + +private theorem lifted_keep {branch : Nat → Nat} {n t : Nat} + (calls : Nat) (rows : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + ChildBlockProjection.liftedLaw calls rows (fun s a => MixedSupport.Projection.keep (slots s a)) = + FiniteDistribution.uniform (ChildBlockCardinality.Raw calls rows slots) := by + unfold ChildBlockProjection.liftedLaw + have hmap : (ChildBlockProjection.rawPullback calls rows + (fun s a => MixedSupport.Projection.keep (slots s a)) : + ChildBlockCardinality.Raw calls rows slots → ChildBlockCardinality.Raw calls rows slots) = id := by + funext block + apply Prod.ext + · funext call + apply Subtype.ext + funext x + rfl + · funext node row + apply Subtype.ext + funext x + rfl + rw [hmap, FiniteDistribution.pushforward_id] + +variable {branch : Nat → Nat} {n t : Nat} + {Z : Fin (branch n) → Type*} [∀ child, Fintype (Z child)] + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (projected : (child : Fin (branch n)) → Z child → Slots branch n → Fin t → MixedSupport.Slot) + (projection : ∀ child z s a, MixedSupport.Projection + (childSlots slots child s a) (projected child z s a)) + +def childDomain (child : Fin (branch n)) (choice : Bool × Z child) : + Slots branch n → Fin t → MixedSupport.Slot := + if choice.1 then projected child choice.2 else childSlots slots child + +def childProjection (child : Fin (branch n)) (choice : Bool × Z child) : + ∀ s a, MixedSupport.Projection (childSlots slots child s a) + (childDomain slots projected child choice s a) := by + rcases choice with ⟨flag, z⟩ + cases flag with + | false => exact fun s a => MixedSupport.Projection.keep (childSlots slots child s a) + | true => exact projection child z + +abbrev Choices := (child : Fin (branch n)) → Bool × Z child + +def selectedSlots (choices : Choices (Z := Z)) : + Slots branch (n + 1) → Fin t → MixedSupport.Slot := + fun (s : Fin (branch n) × Slots branch n) a => + childDomain slots projected s.1 (choices s.1) s.2 a + +def selectedProjection (choices : Choices (Z := Z)) : + ∀ s a, MixedSupport.Projection (slots s a) (selectedSlots slots projected choices s a) := + fun (s : Fin (branch n) × Slots branch n) a => + childProjection slots projected projection s.1 (choices s.1) s.2 a + +def choicesLaw (choiceLaw : (child : Fin (branch n)) → FiniteDistribution (Z child)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) : FiniteDistribution (Choices (Z := Z)) := + FiniteProduct.law (fun child => + (ProjectionPosterior.bernoulli β hβ hβ').product (choiceLaw child)) + +def childLaw (calls : Nat) (rows : Nat → Nat) + (child : Fin (branch n)) (choice : Bool × Z child) : + FiniteDistribution (ChildBlockCardinality.Raw calls rows (childSlots slots child)) := + ChildBlockProjection.liftedLaw calls rows (childProjection slots projected projection child choice) + +theorem row_eq_mixture (calls : Nat) (rows : Nat → Nat) + (choiceLaw : (child : Fin (branch n)) → FiniteDistribution (Z child)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) (child : Fin (branch n)) : + SparseReplacement.row + (fun child => FiniteDistribution.uniform (ChildBlockCardinality.Raw calls rows (childSlots slots child))) + (ChildBlockProjection.replacementLaws calls rows (fun child => childSlots slots child) + projected projection choiceLaw) β hβ hβ' child = + ((ProjectionPosterior.bernoulli β hβ hβ').product (choiceLaw child)).mixture + (childLaw slots projected projection calls rows child) := by + rw [product_mixture] + unfold SparseReplacement.row + apply congrArg ((ProjectionPosterior.bernoulli β hβ hβ').mixture) + funext flag + cases flag with + | false => + simp only [Bool.false_eq_true, ite_false] + change FiniteDistribution.uniform (ChildBlockCardinality.Raw calls rows (childSlots slots child)) = + (choiceLaw child).mixture (fun z => ChildBlockProjection.liftedLaw calls rows + (fun s a => MixedSupport.Projection.keep (childSlots slots child s a))) + simp only [lifted_keep, mixture_const] + | true => rfl + +theorem raw_eq_mixture (calls : Nat) (rows : Nat → Nat) + (choiceLaw : (child : Fin (branch n)) → FiniteDistribution (Z child)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) : + SparseReplacement.law + (fun child => FiniteDistribution.uniform (ChildBlockCardinality.Raw calls rows (childSlots slots child))) + (ChildBlockProjection.replacementLaws calls rows (fun child => childSlots slots child) + projected projection choiceLaw) β hβ hβ' = + (choicesLaw choiceLaw β hβ hβ').mixture (fun choices => + FiniteProduct.law (fun child => childLaw slots projected projection calls rows child (choices child))) := by + unfold SparseReplacement.law + have hrow := funext (row_eq_mixture slots projected projection calls rows choiceLaw β hβ hβ') + rw [hrow] + exact MarkedKernelProduct.law_mixture + (fun child => (ProjectionPosterior.bernoulli β hβ hβ').product (choiceLaw child)) + (childLaw slots projected projection calls rows) + +omit [(child : Fin (branch n)) → Fintype (Z child)] in +theorem fixed_assembly (calls : Nat) (rows : Nat → Nat) (choices : Choices (Z := Z)) : + (FiniteProduct.law (fun child => + childLaw slots projected projection calls rows child (choices child))).pushforward + (CutChildGrouping.assemble slots rows) = + (FiniteDistribution.uniform (CutChildGrouping.Assembled (C := Fin calls) + (selectedSlots slots projected choices) rows)).pushforward + (ChildAssemblyProjection.assembledPullback rows + (selectedProjection slots projected projection choices)) := by + have hraw : (CutChildGrouping.rawLaw (C := Fin calls) + (selectedSlots slots projected choices) rows).pushforward + (ChildAssemblyProjection.rawPullback rows (selectedProjection slots projected projection choices)) = + FiniteProduct.law (fun child => + childLaw slots projected projection calls rows child (choices child)) := by + exact FiniteProduct.pushforward_map + (fun child => FiniteDistribution.uniform (CutChildGrouping.Child (C := Fin calls) + (selectedSlots slots projected choices) rows child)) + (fun child => ChildAssemblyProjection.childPullback rows + (selectedProjection slots projected projection choices) child) + rw [← hraw] + exact ChildAssemblyProjection.uniform_projected_assembly rows + (selectedProjection slots projected projection choices) + +theorem assembled_eq_mixture (calls : Nat) (rows : Nat → Nat) + (choiceLaw : (child : Fin (branch n)) → FiniteDistribution (Z child)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) : + ProjectedPrefixComparison.assembledLaw calls rows slots projected projection choiceLaw β hβ hβ' = + (choicesLaw choiceLaw β hβ hβ').mixture (fun choices => + (FiniteDistribution.uniform (CutChildGrouping.Assembled (C := Fin calls) + (selectedSlots slots projected choices) rows)).pushforward + (ChildAssemblyProjection.assembledPullback rows + (selectedProjection slots projected projection choices))) := by + unfold ProjectedPrefixComparison.assembledLaw + rw [raw_eq_mixture slots projected projection calls rows choiceLaw β hβ hβ', + FiniteDistribution.pushforward_mixture] + apply congrArg ((choicesLaw choiceLaw β hβ hβ').mixture) + funext choices + exact fixed_assembly slots projected projection calls rows choices + +end +end PerfectCompleteness.ProjectedCutChoices + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/ProjectedFiberBackground.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/ProjectedFiberBackground.lean new file mode 100644 index 0000000000000000000000000000000000000000..3d4b2a95dd00b50e4a24a3079613077464275558 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/ProjectedFiberBackground.lean @@ -0,0 +1,156 @@ +import OAI.Computability.PerfectCompleteness.Decoding.LowerCutFiberDisintegrationLemmas +import OAI.Computability.PerfectCompleteness.Foundations.ProjectedFiberRawPair + +namespace OAI + +section + +namespace PerfectCompleteness.ProjectedFiberBackground + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open WholeArrayInteriorExterior +open UniqueGamesTheorem.Foundations.Games + +variable {branch : Nat → Nat} {n m t : Nat} + +def nodeScalarEquiv + (projected : Slots branch n → Fin t → MixedSupport.Slot) + {node node' : Nodes branch n} (h : node = node') : + H (nodeSlots projected node) ≃ₗ[F2] H (nodeSlots projected node') := by + cases h + exact LinearEquiv.refl F2 _ + +@[simp] theorem nodeScalarEquiv_apply + (projected : Slots branch n → Fin t → MixedSupport.Slot) + {node node' : Nodes branch n} (h : node = node') + (x : H (nodeSlots projected node)) : + nodeScalarEquiv projected h x = ProjectedFiberRawPair.castScalar projected h x := by + cases h + rfl + +private theorem update_fiber_transport (rows : Nat → Nat) + (projected : Slots branch n → Fin t → MixedSupport.Slot) + {node node' : Nodes branch n} (h : node = node') + (a : BucketSampler.Direction (rows (Nodes.height node))) + (arrays : Arrays projected rows) (fresh : H (nodeSlots projected node)) : + Function.update arrays node (LowerDirectionFiber.replace a (arrays node) fresh) = + Function.update arrays node' + (LowerDirectionFiber.replace (ProjectedFiberRawPair.castDirection h a) (arrays node') + (ProjectedFiberRawPair.castScalar projected h fresh)) := by + cases h + rfl + +variable (rows repeats : Nat → Nat) (path : Path branch n (m + 1)) + (projected : Slots branch n → Fin t → MixedSupport.Slot) + (upper : Nodes branch n) (level : Nat) + (d : HierarchicalFrozenTables.LowerNodes upper level) + (hnode : upperNode path = HierarchicalLeftDecoder.LowerNode upper level d) + +def scalarEquiv : H (WholeCutGrouping.cutSlots path projected) ≃ₗ[F2] + ProjectedLowerFiber.Scalar projected upper level d := + (LowerCutNodeCoordinates.scalarEquiv path projected).trans + (nodeScalarEquiv projected hnode) + +@[simp] theorem scalarEquiv_apply (x : H (WholeCutGrouping.cutSlots path projected)) : + scalarEquiv path projected upper level d hnode x = + ProjectedFiberRawPair.scalar path projected upper level d hnode x := by + exact nodeScalarEquiv_apply projected hnode + (LowerCutNodeCoordinates.scalarEquiv path projected x) + +theorem scalar_uniform : + (FiniteDistribution.uniform (H (WholeCutGrouping.cutSlots path projected))).pushforward + (ProjectedFiberRawPair.scalar path projected upper level d hnode) = + FiniteDistribution.uniform (ProjectedLowerFiber.Scalar projected upper level d) := by + have h := UniformConditioning.uniform_transport + (scalarEquiv path projected upper level d hnode).toEquiv + rw [FiniteDistribution.transport_eq_pushforward] at h + have hmap : ProjectedFiberRawPair.scalar path projected upper level d hnode = + (scalarEquiv path projected upper level d hnode).toEquiv := by + funext x + exact (scalarEquiv_apply path projected upper level d hnode x).symm + rw [hmap] + exact h + +private theorem replace_replace (arrays : Arrays projected rows) + (S T : Fin (rows (m + 1)) → H (WholeCutGrouping.cutSlots path projected)) : + SelectedArrayReplacement.replace rows path projected + (SelectedArrayReplacement.replace rows path projected arrays S) T = + SelectedArrayReplacement.replace rows path projected arrays T := by + simp only [LowerCutNodeCoordinates.replace_eq_update] + funext node + by_cases hnode : node = upperNode path + · subst node + simp only [Function.update_self] + · simp only [Function.update_of_ne hnode] + +variable (a : BucketSampler.Direction (rows (m + 1))) + (exterior : WholeCutGrouping.Exterior rows repeats path projected) + (background : LowerCutFiberDisintegration.Background rows repeats path projected a) + +theorem arraysAt_eq_native_replace (fresh : H (WholeCutGrouping.cutSlots path projected)) : + LowerCutFiberDisintegration.arraysAt rows repeats path projected a exterior background fresh = + SelectedArrayReplacement.replace rows path projected + (LowerCutFiberDisintegration.arraysAt rows repeats path projected a exterior background 0) + (LowerDirectionFiber.replace a + (SelectedArrayReplacement.selectedRows rows path projected + (LowerCutFiberDisintegration.arraysAt rows repeats path projected a exterior background 0)) + fresh) := by + simp only [LowerCutFiberDisintegration.arraysAt, LowerCutPairBackground.installRows, + SelectedArrayReplacement.selectedRows_replace, LowerDirectionFiber.replace, + LowerDirectionFiber.complement_restore, replace_replace] + +theorem arraysAt_eq_fiber (fresh : H (WholeCutGrouping.cutSlots path projected)) : + LowerCutFiberDisintegration.arraysAt rows repeats path projected a exterior background fresh = + ProjectedLowerFiber.arraysAt projected upper level d + (ProjectedFiberRawPair.direction path upper level d hnode a) + (LowerCutFiberDisintegration.arraysAt rows repeats path projected a exterior background 0) + (ProjectedFiberRawPair.scalar path projected upper level d hnode fresh) := by + rw [arraysAt_eq_native_replace rows repeats path projected a exterior background fresh, + LowerCutNodeCoordinates.replace_fiber_eq_update] + exact update_fiber_transport rows projected hnode + (LowerCutNodeCoordinates.directionEquiv rows path a) + (LowerCutFiberDisintegration.arraysAt rows repeats path projected a exterior background 0) + (LowerCutNodeCoordinates.scalarEquiv path projected fresh) + +variable (slots : Slots branch n → Fin t → MixedSupport.Slot) + (projection : ∀ leaf k, MixedSupport.Projection (slots leaf k) (projected leaf k)) + +theorem pullback_arraysAt (fresh : H (WholeCutGrouping.cutSlots path projected)) : + ChildBlockProjection.arraysPullback rows projection + (LowerCutFiberDisintegration.arraysAt rows repeats path projected a exterior background fresh) = + ProjectedLowerFiber.originalArraysAt slots projected projection upper level d + (ProjectedFiberRawPair.direction path upper level d hnode a) + (LowerCutFiberDisintegration.arraysAt rows repeats path projected a exterior background 0) + (ProjectedFiberRawPair.scalar path projected upper level d hnode fresh) := + congrArg (ChildBlockProjection.arraysPullback rows projection) + (arraysAt_eq_fiber rows repeats path projected upper level d hnode a exterior background fresh) + +variable (hbranch : ∀ k < n, 0 < branch k) {r : Nat} + (A : ManyGoodRows.RowMap (Block rows upper) r) + (table : ProjectedLowerFiber.UpperTable (rows := rows) slots upper level r) + (s : Nat) + +theorem form_at_fiber (fresh : H (WholeCutGrouping.cutSlots path projected)) : + ProjectedFiberSquare.form slots upper level hbranch d s + (ProjectedLowerFiber.upperAt slots projected projection upper level d A + (ProjectedFiberRawPair.direction path upper level d hnode a) + (LowerCutFiberDisintegration.arraysAt rows repeats path projected a exterior background 0) + table (ProjectedFiberRawPair.scalar path projected upper level d hnode fresh)) = + (LowerCutDecoderForm.answer slots upper level d hbranch A table s + (ChildBlockProjection.arraysPullback rows projection + (LowerCutFiberDisintegration.arraysAt rows repeats path projected a exterior background fresh))).map + (OddListExtraction.multiplicationForm + (HierarchicalDecoderTables.LowerH slots upper level d)) := by + rw [ProjectedFiberRawPair.form_upperAt, + ← pullback_arraysAt rows repeats path projected upper level d hnode a exterior background + slots projection fresh] + +end +end PerfectCompleteness.ProjectedFiberBackground + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/ProjectedFiberRawPair.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/ProjectedFiberRawPair.lean new file mode 100644 index 0000000000000000000000000000000000000000..d0239ff89d6b637f88a8f92f2cf04e11aba8d2e2 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/ProjectedFiberRawPair.lean @@ -0,0 +1,194 @@ +import OAI.Computability.PerfectCompleteness.Decoding.LowerCutPairLemmas +import OAI.Computability.PerfectCompleteness.Foundations.ProjectedFiberSquare + +namespace OAI + +section + +namespace PerfectCompleteness.ProjectedFiberRawPair + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open WholeArrayInteriorExterior + +variable {branch rows repeats : Nat → Nat} {n m t : Nat} + +def castDirection {node node' : Nodes branch n} (h : node = node') + (a : BucketSampler.Direction (rows (Nodes.height node))) : + BucketSampler.Direction (rows (Nodes.height node')) := by + cases h + exact a + +def castScalar (projected : Slots branch n → Fin t → MixedSupport.Slot) + {node node' : Nodes branch n} (h : node = node') + (x : H (nodeSlots projected node)) : H (nodeSlots projected node') := by + cases h + exact x + +private theorem castScalar_pivot + (projected : Slots branch n → Fin t → MixedSupport.Slot) + {node node' : Nodes branch n} (h : node = node') + (a : BucketSampler.Direction (rows (Nodes.height node))) + (arrays : Arrays projected rows) : + castScalar projected h (arrays node (LowerDirectionFiber.pivot a)) = + arrays node' (LowerDirectionFiber.pivot (castDirection h a)) := by + cases h + rfl + +private theorem update_fiber_transport + (projected : Slots branch n → Fin t → MixedSupport.Slot) + {node node' : Nodes branch n} (h : node = node') + (a : BucketSampler.Direction (rows (Nodes.height node))) + (arrays : Arrays projected rows) (fresh : H (nodeSlots projected node)) : + Function.update arrays node (LowerDirectionFiber.replace a (arrays node) fresh) = + Function.update arrays node' + (LowerDirectionFiber.replace (castDirection h a) (arrays node') + (castScalar projected h fresh)) := by + cases h + rfl + +variable (path : Path branch n (m + 1)) + (projected : Slots branch n → Fin t → MixedSupport.Slot) + (upper : Nodes branch n) (level : Nat) + (d : HierarchicalFrozenTables.LowerNodes upper level) + (hnode : upperNode path = HierarchicalLeftDecoder.LowerNode upper level d) + +def direction (a : BucketSampler.Direction (rows (m + 1))) : + ProjectedLowerFiber.Direction (rows := rows) upper level d := + castDirection hnode (LowerCutNodeCoordinates.directionEquiv rows path a) + +def scalar (x : H (WholeCutGrouping.cutSlots path projected)) : + ProjectedLowerFiber.Scalar projected upper level d := + castScalar projected hnode (LowerCutNodeCoordinates.scalarEquiv path projected x) + +variable (exterior : WholeCutGrouping.Exterior rows repeats path projected) + (a : BucketSampler.Direction (rows (m + 1))) + (raw : LowerCutPair.Raw rows repeats path projected) + +def oldScalar : ProjectedLowerFiber.Scalar projected upper level d := + scalar path projected upper level d hnode + (SelectedArrayReplacement.selectedRows rows path projected + (LowerCutPair.first rows repeats path projected exterior raw) + (LowerDirectionFiber.pivot a)) + +def freshScalar : ProjectedLowerFiber.Scalar projected upper level d := + scalar path projected upper level d hnode + (LowerCutPair.fresh rows repeats path projected raw) + +theorem oldScalar_eq_pivot : + oldScalar path projected upper level d hnode exterior a raw = + LowerCutPair.first rows repeats path projected exterior raw + (HierarchicalLeftDecoder.LowerNode upper level d) + (LowerDirectionFiber.pivot (direction path upper level d hnode a)) := by + have h := LowerCutNodeCoordinates.rowEquiv_apply rows path projected + (SelectedArrayReplacement.selectedRows rows path projected + (LowerCutPair.first rows repeats path projected exterior raw)) + (LowerDirectionFiber.pivot a) + rw [LowerCutNodeCoordinates.rowEquiv_selectedRows, + LowerCutNodeCoordinates.pivot_transport] at h + unfold oldScalar scalar + rw [← h] + exact castScalar_pivot projected hnode + (LowerCutNodeCoordinates.directionEquiv rows path a) + (LowerCutPair.first rows repeats path projected exterior raw) + +theorem first_eq_arraysAt : + LowerCutPair.first rows repeats path projected exterior raw = + ProjectedLowerFiber.arraysAt projected upper level d + (direction path upper level d hnode a) + (LowerCutPair.first rows repeats path projected exterior raw) + (oldScalar path projected upper level d hnode exterior a raw) := by + rw [oldScalar_eq_pivot] + simp only [ProjectedLowerFiber.arraysAt, LowerDirectionFiber.replace, + LowerDirectionFiber.restore_complement, Function.update_eq_self] + +theorem second_eq_arraysAt : + LowerCutPair.second rows repeats path projected exterior a raw = + ProjectedLowerFiber.arraysAt projected upper level d + (direction path upper level d hnode a) + (LowerCutPair.first rows repeats path projected exterior raw) + (freshScalar path projected upper level d hnode raw) := by + rw [LowerCutOwnInput.second_eq_update] + exact update_fiber_transport projected hnode + (LowerCutNodeCoordinates.directionEquiv rows path a) + (LowerCutPair.first rows repeats path projected exterior raw) + (LowerCutNodeCoordinates.scalarEquiv path projected + (LowerCutPair.fresh rows repeats path projected raw)) + +variable (slots : Slots branch n → Fin t → MixedSupport.Slot) + (projection : ∀ leaf k, MixedSupport.Projection (slots leaf k) (projected leaf k)) + +theorem first_pullback : + ChildBlockProjection.arraysPullback rows projection + (LowerCutPair.first rows repeats path projected exterior raw) = + ProjectedLowerFiber.originalArraysAt slots projected projection upper level d + (direction path upper level d hnode a) + (LowerCutPair.first rows repeats path projected exterior raw) + (oldScalar path projected upper level d hnode exterior a raw) := + congrArg (ChildBlockProjection.arraysPullback rows projection) + (first_eq_arraysAt path projected upper level d hnode exterior a raw) + +theorem second_pullback : + ChildBlockProjection.arraysPullback rows projection + (LowerCutPair.second rows repeats path projected exterior a raw) = + ProjectedLowerFiber.originalArraysAt slots projected projection upper level d + (direction path upper level d hnode a) + (LowerCutPair.first rows repeats path projected exterior raw) + (freshScalar path projected upper level d hnode raw) := + congrArg (ChildBlockProjection.arraysPullback rows projection) + (second_eq_arraysAt path projected upper level d hnode exterior a raw) + +variable (hbranch : ∀ k < n, 0 < branch k) {r : Nat} + (A : ManyGoodRows.RowMap (Block rows upper) r) + (table : ProjectedLowerFiber.UpperTable (rows := rows) slots upper level r) + (s : Nat) + +theorem form_upperAt + (dir : ProjectedLowerFiber.Direction (rows := rows) upper level d) + (arrays : Arrays projected rows) + (fresh : ProjectedLowerFiber.Scalar projected upper level d) : + ProjectedFiberSquare.form slots upper level hbranch d s + (ProjectedLowerFiber.upperAt slots projected projection upper level d + A dir arrays table fresh) = + (LowerCutDecoderForm.answer slots upper level d hbranch A table s + (ProjectedLowerFiber.originalArraysAt slots projected projection upper level d + dir arrays fresh)).map + (OddListExtraction.multiplicationForm + (HierarchicalDecoderTables.LowerH slots upper level d)) := rfl + +theorem first_form : + ProjectedFiberSquare.form slots upper level hbranch d s + (ProjectedLowerFiber.upperAt slots projected projection upper level d A + (direction path upper level d hnode a) + (LowerCutPair.first rows repeats path projected exterior raw) table + (oldScalar path projected upper level d hnode exterior a raw)) = + (LowerCutDecoderForm.answer slots upper level d hbranch A table s + (ChildBlockProjection.arraysPullback rows projection + (LowerCutPair.first rows repeats path projected exterior raw))).map + (OddListExtraction.multiplicationForm + (HierarchicalDecoderTables.LowerH slots upper level d)) := by + rw [form_upperAt, ← first_pullback path projected upper level d hnode exterior a raw + slots projection] + +theorem second_form : + ProjectedFiberSquare.form slots upper level hbranch d s + (ProjectedLowerFiber.upperAt slots projected projection upper level d A + (direction path upper level d hnode a) + (LowerCutPair.first rows repeats path projected exterior raw) table + (freshScalar path projected upper level d hnode raw)) = + (LowerCutDecoderForm.answer slots upper level d hbranch A table s + (ChildBlockProjection.arraysPullback rows projection + (LowerCutPair.second rows repeats path projected exterior a raw))).map + (OddListExtraction.multiplicationForm + (HierarchicalDecoderTables.LowerH slots upper level d)) := by + rw [form_upperAt, ← second_pullback path projected upper level d hnode exterior a raw + slots projection] + +end +end PerfectCompleteness.ProjectedFiberRawPair + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/ProjectedFiberSquare.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/ProjectedFiberSquare.lean new file mode 100644 index 0000000000000000000000000000000000000000..cc7a5efc35da86a9d0a10d945cb5e85e2aa0946f --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/ProjectedFiberSquare.lean @@ -0,0 +1,162 @@ +import OAI.Computability.PerfectCompleteness.Decoding.DecoderTableCoupling +import OAI.Computability.PerfectCompleteness.Decoding.ProjectedLowerFiber +import OAI.Computability.PerfectCompleteness.Decoding.ProjectedNativeCollision +import OAI.Computability.PerfectCompleteness.Foundations.MultiplicationFormInjectiveLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.ProjectedFiberSquare + +noncomputable section + +open scoped Classical +open TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open ProjectedLowerFiber + +attribute [local instance] RightDecoder.scalarFintype + +private theorem table_sampling {Q Y Z Ω : Type*} + [Fintype Q] [DecidableEq Q] [Fintype Y] [Fintype Z] [Fintype Ω] + (responses : Q → FiniteDistribution Y) (right : FiniteDistribution Z) + (ν : FiniteDistribution Ω) (question : Ω → Q) (event : Ω → Y × Z → Bool) : + ν.expectation (fun x => ((responses (question x)).product right).probability (event x)) = + ((FiniteDistribution.table responses).product right).expectation + (fun seed => ν.probability (fun x => event x (seed.1 (question x), seed.2))) := by + simp_rw [DecoderTableCoupling.probability_eq_expectation] + symm + rw [FiniteDistribution.expectation_comm] + apply FiniteDistribution.expectation_congr + intro x + simp only [FiniteDistribution.expectation_product] + exact FiniteDistribution.expectation_table_eval responses (question x) + (fun y => right.expectation (fun z => if event x (y, z) then (1 : ℝ) else 0)) + +variable {branch rows : Nat → Nat} {n t : Nat} + (slots projected : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (projection : ∀ leaf j, MixedSupport.Projection (slots leaf j) (projected leaf j)) + (upper : Nodes branch n) (level : Nat) + (hbranch : ∀ k < n, 0 < branch k) + (d : HierarchicalFrozenTables.LowerNodes upper level) + +local instance rowSpaceFintype : Fintype (NodeEmbedding.RowSpace slots upper) := + Fintype.ofFinite _ + +local instance upperAnswerFintype : + Fintype (HierarchicalAllDecoderTables.UpperAnswer slots upper) := + LeftDecoder.dualFintype (V := NodeEmbedding.RowSpace slots upper) + +def form (s : Nat) (q : HierarchicalAllDecoderTables.UpperAnswer slots upper) := + (HierarchicalDecoderTables.decode slots upper level hbranch d s q).map + (OddListExtraction.multiplicationForm + (HierarchicalDecoderTables.LowerH slots upper level d)) + +def highMeeting (s : Nat) + (q : HierarchicalAllDecoderTables.UpperAnswer slots upper) + (right : Module.Dual F2 (OwnInputReference.UpperSpace projected upper)) : Bool := + decide (s < HierarchicalDecoderTables.fullRank slots upper level d + (HierarchicalLeftDecoder.output slots upper level hbranch d q) ∧ + DecoderSourcePullback.upperTarget projection upper q = right) + +variable {r : Nat} (A : ManyGoodRows.RowMap (Block rows upper) r) + (a : Direction (rows := rows) upper level d) (arrays : Arrays projected rows) + +def restrictedPair (s : Nat) (table : UpperTable (rows := rows) slots upper level r) + (pair : Scalar projected upper level d × Scalar projected upper level d) : Bool := + BilinearCollisionTransfer.restrictedCollision + (form slots upper level hbranch d s + (upperAt slots projected projection upper level d A a arrays table pair.1)) + (form slots upper level hbranch d s + (upperAt slots projected projection upper level d A a arrays table pair.2)) + (LinearMap.range (HPullback + (ChildBlockProjection.nodeProjection projection (lower upper level d)))) + +theorem fixed_seed_square (s : Nat) + (ν : FiniteDistribution (Scalar projected upper level d)) + (table : UpperTable (rows := rows) slots upper level r) + (right : Module.Dual F2 (OwnInputReference.UpperSpace projected upper)) : + ν.probability (fun fresh => highMeeting slots projected projection upper level hbranch d s + (upperAt slots projected projection upper level d A a arrays table fresh) right) ^ 2 ≤ + (ν.product ν).probability + (restrictedPair slots projected projection upper level hbranch d A a arrays s table) := by + rw [pow_two, ← SingleResponseResampling.probability_rectangle] + apply FiniteDistribution.probability_mono + intro pair hpair + obtain ⟨h0, h1⟩ := Bool.and_eq_true_iff.mp hpair + obtain ⟨hrank0, hhit0⟩ := of_decide_eq_true h0 + obtain ⟨hrank1, hhit1⟩ := of_decide_eq_true h1 + exact ProjectedNativeCollision.two_high_hits_restricted projection upper level hbranch d s + (upperAt slots projected projection upper level d A a arrays table pair.1) + (upperAt slots projected projection upper level d A a arrays table pair.2) + right hrank0 hrank1 hhit0 hhit1 + +variable + (known : HiddenBucketBias.VisibleDirection (LinearMap.ker A) → + OwnInputReference.UpperSpace projected upper) + (repeats : Nat → Nat) (cut : OwnInputReference.Cut upper (lower upper level d)) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (useful : (bg : HierarchicalMatrixTable.Background (rows := rows) slots upper) → + HierarchicalFrozenTables.QuotientMatrix slots upper level bg → Prop) + (ρ threshold : ℝ) + +def rightLaw := + RightDecoder.law projected rows upper (lower upper level d) (LinearMap.ker A) a.val + repeats cut σ + (LowerCutOwnInput.ofArrays projected rows upper (lower upper level d) + (LinearMap.ker A) a.val known arrays) threshold + +def seedLaw := + (HierarchicalAllDecoderTables.upperTableLaw slots upper level σ useful r ρ).product + (rightLaw projected upper level d A a arrays known repeats cut σ threshold) + +def success (s : Nat) (ν : FiniteDistribution (Scalar projected upper level d)) : ℝ := + ν.expectation (fun fresh => + ((HierarchicalAllDecoderTables.upperKernel slots upper level σ useful r ρ + (inputAt slots projected projection upper level d A a arrays fresh)).product + (RightDecoder.law projected rows upper (lower upper level d) (LinearMap.ker A) a.val + repeats cut σ + (LowerCutOwnInput.ofArrays projected rows upper (lower upper level d) + (LinearMap.ker A) a.val known (arraysAt projected upper level d a arrays fresh)) + threshold)).probability + (fun pair => highMeeting slots projected projection upper level hbranch d s pair.1 pair.2)) + +theorem success_eq_seed_mean (s : Nat) + (ν : FiniteDistribution (Scalar projected upper level d)) : + success slots projected projection upper level hbranch d A a arrays known + repeats cut σ useful ρ threshold s ν = + (seedLaw slots projected upper level d A a arrays known repeats cut σ useful ρ threshold).expectation + (fun seed => ν.probability (fun fresh => + highMeeting slots projected projection upper level hbranch d s + (upperAt slots projected projection upper level d A a arrays seed.1 fresh) seed.2)) := by + unfold success + simp_rw [ProjectedLowerFiber.rightLaw_fixed projected upper level d A a known arrays] + exact table_sampling + (HierarchicalAllDecoderTables.upperKernel slots upper level σ useful r ρ) + (rightLaw projected upper level d A a arrays known repeats cut σ threshold) ν + (inputAt slots projected projection upper level d A a arrays) + (fun _ pair => highMeeting slots projected projection upper level hbranch d s pair.1 pair.2) + +theorem success_square_le (s : Nat) + (ν : FiniteDistribution (Scalar projected upper level d)) : + success slots projected projection upper level hbranch d A a arrays known + repeats cut σ useful ρ threshold s ν ^ 2 ≤ + (seedLaw slots projected upper level d A a arrays known repeats cut σ useful ρ threshold).expectation + (fun seed => (ν.product ν).probability + (restrictedPair slots projected projection upper level hbranch d A a arrays s seed.1)) := by + rw [success_eq_seed_mean] + apply (CollisionAveraging.mean_square_le _ _).trans + apply Finset.sum_le_sum + intro seed _ + exact mul_le_mul_of_nonneg_left + (fixed_seed_square slots projected projection upper level hbranch d A a arrays + s ν seed.1 seed.2) + ((seedLaw slots projected upper level d A a arrays known repeats cut σ useful ρ threshold).nonnegative seed) + +end +end PerfectCompleteness.ProjectedFiberSquare + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/ProjectedMeetingTransport.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/ProjectedMeetingTransport.lean new file mode 100644 index 0000000000000000000000000000000000000000..92dd56748fd0083cb4aa9166f162e44385bbb265 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/ProjectedMeetingTransport.lean @@ -0,0 +1,88 @@ +import OAI.Computability.PerfectCompleteness.Reduction.FixedRows +import OAI.Computability.PerfectCompleteness.Repetition.CleanPhysicalProjectedMeeting + +namespace OAI + +section + +namespace PerfectCompleteness.ProjectedMeetingTransport + +noncomputable section + +open scoped Classical +open RecursiveSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype RightDecoder.scalarFintype + +local instance physicalLeftFintype {branch : Nat → Nat} {n t : Nat} + (slots : Slots branch n → Fin t → MixedSupport.Slot) (upper : Nodes branch n) : + Fintype (Module.Dual (ZMod 2) (NodeEmbedding.RowSpace slots upper)) := + LeftDecoder.dualFintype (V := NodeEmbedding.RowSpace slots upper) + +variable {δ : ℚ} (plan : FixedRows.Plan δ) {branch : Nat → Nat} {t : Nat} + {Sample : OriginalDecoderMark.SlotFamily branch plan.depth t → Type*} + [∀ slots, Fintype (Sample slots)] + (F : OriginalDecoderMark.Family branch (FixedRows.rows plan) plan.depth t Sample) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch plan.depth t)) + (slots projected : Slots branch plan.depth → Fin t → MixedSupport.Slot) + (projection : ∀ s j, MixedSupport.Projection (slots s j) (projected s j)) + (upper lower : Nodes branch plan.depth) (lowerLevel : Nat) + (A : ManyGoodRows.RowMap (Block (FixedRows.rows plan) upper) plan.order) + (a : Block (FixedRows.rows plan) lower) (cut : OwnInputReference.Cut upper lower) + (threshold : ℝ) + (visible : HierarchicalProjectedRawPrediction.Visible projected (FixedRows.rows plan) + upper lower A (FixedRows.repeats plan) cut) + +def familyMeetingProbability : ℝ := + ((HierarchicalProjectedMeeting.leftLaw slots projected projection upper lowerLevel + (HierarchicalProjectedRawPrediction.visibleBackground slots projected projection + (FixedRows.rows plan) upper lower A (FixedRows.repeats plan) cut visible) + (F.original slots) (F.arrays slots) (F.lowerEvent slots) (InitialParameters.useful δ) + σ plan.density A + (HierarchicalProjectedRawPrediction.known projected (FixedRows.rows plan) + upper lower A (FixedRows.repeats plan) cut visible)).product + (RightDecoder.law projected (FixedRows.rows plan) upper lower (LinearMap.ker A) a + (FixedRows.repeats plan) cut σ + (OwnInputReference.readInput projected (FixedRows.rows plan) upper lower + (LinearMap.ker A) a + (OwnInputRawAssembly.scalarEval projected upper lower (FixedRows.repeats plan) cut) + visible) threshold)).probability + (fun answer => decide ((ProjectedNodeEmbedding.intoOriginal projection upper).dualMap + answer.1 = answer.2)) + +theorem familyMeetingProbability_congr + (target other : Slots branch plan.depth → Fin t → MixedSupport.Slot) + (otherLower : Nodes branch plan.depth) + (projection' : ∀ s j, MixedSupport.Projection (target s j) (other s j)) + (a' : Block (FixedRows.rows plan) otherLower) + (cut' : OwnInputReference.Cut upper otherLower) + (visible' : HierarchicalProjectedRawPrediction.Visible other (FixedRows.rows plan) + upper otherLower A (FixedRows.repeats plan) cut') + (hs : slots = target) (hp : projected = other) (hl : lower = otherLower) + (hprojection : HEq projection projection') (ha : HEq a a') + (hcut : HEq cut cut') (hvisible : HEq visible visible') : + familyMeetingProbability plan F σ slots projected projection upper lower lowerLevel + A a cut threshold visible = + familyMeetingProbability plan F σ target other projection' upper otherLower lowerLevel + A a' cut' threshold visible' := by + cases hs + cases hp + cases hl + have hprojection' : projection = projection' := eq_of_heq hprojection + cases hprojection' + have ha' : a = a' := eq_of_heq ha + cases ha' + have hcut' : cut = cut' := eq_of_heq hcut + cases hcut' + have hvisible' : visible = visible' := eq_of_heq hvisible + cases hvisible' + rfl + +end +end PerfectCompleteness.ProjectedMeetingTransport + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/ProjectedPrefixComparison.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/ProjectedPrefixComparison.lean new file mode 100644 index 0000000000000000000000000000000000000000..6d5eb66c8923ae7dfb2c195c75c2304d82c8902f --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/ProjectedPrefixComparison.lean @@ -0,0 +1,104 @@ +import OAI.Computability.PerfectCompleteness.Decoding.ChildBlockProjection +import OAI.Computability.PerfectCompleteness.Foundations.OriginalPrefixContinuation +import OAI.Computability.PerfectCompleteness.Sampling.CommonProductVariationLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.ProjectedPrefixComparison + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +noncomputable section + +private theorem variation_triangle {Ω : Type*} [Fintype Ω] + (P U Q : FiniteDistribution Ω) : + P.totalVariation Q ≤ P.totalVariation U + U.totalVariation Q := by + unfold FiniteDistribution.totalVariation + have h := Finset.sum_le_sum (s := Finset.univ) + (fun x _ => abs_sub_le (P.weight x) (U.weight x) (Q.weight x)) + rw [Finset.sum_add_distrib] at h + linarith + +variable {branch : Nat → Nat} {n k t : Nat} + {K : Type*} [Fintype K] + {Z : Fin (branch n) → Type*} [∀ i, Fintype (Z i)] + +def assembledLaw (calls : Nat) (rows : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (projected : (i : Fin (branch n)) → Z i → Slots branch n → Fin t → MixedSupport.Slot) + (p : ∀ i z s j, MixedSupport.Projection (childSlots slots i s j) (projected i z s j)) + (choiceLaw : (i : Fin (branch n)) → FiniteDistribution (Z i)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) : + FiniteDistribution (CutChildGrouping.Assembled (C := Fin calls) slots rows) := + (SparseReplacement.law + (fun i => FiniteDistribution.uniform (ChildBlockCardinality.Raw calls rows (childSlots slots i))) + (ChildBlockProjection.replacementLaws calls rows (fun i => childSlots slots i) + projected p choiceLaw) β hβ hβ').pushforward (CutChildGrouping.assemble slots rows) + +theorem uniform_variation (calls : Nat) (rows : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (projected : (i : Fin (branch n)) → Z i → Slots branch n → Fin t → MixedSupport.Slot) + (p : ∀ i z s j, MixedSupport.Projection (childSlots slots i s j) (projected i z s j)) + (choiceLaw : (i : Fin (branch n)) → FiniteDistribution (Z i)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) (hbranch : 0 < branch n) : + (assembledLaw calls rows slots projected p choiceLaw β hβ hβ').totalVariation + (FiniteDistribution.uniform (CutChildGrouping.Assembled (C := Fin calls) slots rows)) ≤ + Real.sqrt ((1 + β ^ 2 * ((ChildBlockCardinality.bound branch n t calls rows : ℝ) - 1)) ^ + branch n - 1) / 2 := by + let : Nonempty (Fin (branch n)) := ⟨⟨0, hbranch⟩⟩ + have huniform := CutChildGrouping.assemble_law (C := Fin calls) slots rows + change (FiniteProduct.law (fun i : Fin (branch n) => + FiniteDistribution.uniform (ChildBlockCardinality.Raw calls rows (childSlots slots i)))).pushforward (CutChildGrouping.assemble slots rows) = _ at huniform + have h := ChildBlockProjection.observed_variation calls rows + (fun i => childSlots slots i) projected p choiceLaw β hβ hβ' + (CutChildGrouping.assemble slots rows) + simpa only [assembledLaw, huniform, Fintype.card_fin] using h + +theorem original_variation (calls : Nat) (rows repeats : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (projected : (i : Fin (branch n)) → Z i → Slots branch n → Fin t → MixedSupport.Slot) + (p : ∀ i z s j, MixedSupport.Projection (childSlots slots i s j) (projected i z s j)) + (choiceLaw : (i : Fin (branch n)) → FiniteDistribution (Z i)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) + (ν : FiniteDistribution K) (q : K → Path branch n k) (hbranch : 0 < branch n) : + (assembledLaw calls rows slots projected p choiceLaw β hβ hβ').totalVariation + (OriginalPrefixContinuation.assembledLaw calls rows repeats slots ν q hbranch) ≤ + Real.sqrt ((1 + β ^ 2 * ((ChildBlockCardinality.bound branch n t calls rows : ℝ) - 1)) ^ + branch n - 1) / 2 + + Real.sqrt ((ChildBlockCardinality.bound branch n t calls rows : ℝ) ^ 2 / branch n) / 2 := by + have hs := uniform_variation calls rows slots projected p choiceLaw β hβ hβ' hbranch + have ho := OriginalPrefixContinuation.assembledLaw_variation + calls rows repeats slots ν q hbranch + rw [FiniteDistribution.totalVariation_comm] at ho + exact (variation_triangle _ + (FiniteDistribution.uniform (CutChildGrouping.Assembled (C := Fin calls) slots rows)) _).trans + (add_le_add hs ho) + +theorem observed_original_variation {E Γ : Type*} [Fintype E] [Fintype Γ] + (calls : Nat) (rows repeats : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (projected : (i : Fin (branch n)) → Z i → Slots branch n → Fin t → MixedSupport.Slot) + (p : ∀ i z s j, MixedSupport.Projection (childSlots slots i s j) (projected i z s j)) + (choiceLaw : (i : Fin (branch n)) → FiniteDistribution (Z i)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) + (ν : FiniteDistribution K) (q : K → Path branch n k) (hbranch : 0 < branch n) + (exterior : FiniteDistribution E) + (observe : E × CutChildGrouping.Assembled (C := Fin calls) slots rows → Γ) : + ((exterior.product (assembledLaw calls rows slots projected p choiceLaw β hβ hβ')).pushforward observe).totalVariation + ((exterior.product (OriginalPrefixContinuation.assembledLaw calls rows repeats slots ν q hbranch)).pushforward observe) ≤ + Real.sqrt ((1 + β ^ 2 * ((ChildBlockCardinality.bound branch n t calls rows : ℝ) - 1)) ^ + branch n - 1) / 2 + + Real.sqrt ((ChildBlockCardinality.bound branch n t calls rows : ℝ) ^ 2 / branch n) / 2 := + CommonProductVariation.observed_product_le_of_bound exterior _ _ observe + (original_variation calls rows repeats slots projected p choiceLaw β hβ hβ' ν q hbranch) + +end +end PerfectCompleteness.ProjectedPrefixComparison + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/ProjectedPrefixConditional.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/ProjectedPrefixConditional.lean new file mode 100644 index 0000000000000000000000000000000000000000..8619b79ca9d96582a0b73ff8a26793905ff9fb4e --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/ProjectedPrefixConditional.lean @@ -0,0 +1,53 @@ +import OAI.Computability.PerfectCompleteness.Foundations.ProjectedPrefixComparison +import OAI.Computability.PerfectCompleteness.Sampling.CommonProductVariationLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.ProjectedPrefixConditional + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open scoped Classical + +noncomputable section + +variable {branch : Nat → Nat} {n k t : Nat} + {S Γ : Type*} [Fintype S] [Fintype Γ] + {K E : S → Type*} [∀ s, Fintype (K s)] [∀ s, Fintype (E s)] + {Z : S → Fin (branch n) → Type*} [∀ s i, Fintype (Z s i)] + +theorem observed_original_variation (calls : Nat) (rows repeats : Nat → Nat) + (slots : S → Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (projected : (s : S) → (i : Fin (branch n)) → Z s i → + Slots branch n → Fin t → MixedSupport.Slot) + (p : ∀ s i z x j, + MixedSupport.Projection (childSlots (slots s) i x j) (projected s i z x j)) + (choiceLaw : (s : S) → (i : Fin (branch n)) → FiniteDistribution (Z s i)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) + (ν : (s : S) → FiniteDistribution (K s)) + (q : (s : S) → K s → Path branch n k) (hbranch : 0 < branch n) + (source : FiniteDistribution S) (exterior : (s : S) → FiniteDistribution (E s)) + (observe : (Σ s : S, E s × CutChildGrouping.Assembled (C := Fin calls) (slots s) rows) → Γ) : + ((CompletionSoundness.sigmaLaw source (fun s => + (exterior s).product (ProjectedPrefixComparison.assembledLaw calls rows (slots s) + (projected s) (p s) (choiceLaw s) β hβ hβ'))).pushforward observe).totalVariation + ((CompletionSoundness.sigmaLaw source (fun s => + (exterior s).product (OriginalPrefixContinuation.assembledLaw calls rows repeats + (slots s) (ν s) (q s) hbranch))).pushforward observe) ≤ + Real.sqrt ((1 + β ^ 2 * ((ChildBlockCardinality.bound branch n t calls rows : ℝ) - 1)) ^ + branch n - 1) / 2 + + Real.sqrt ((ChildBlockCardinality.bound branch n t calls rows : ℝ) ^ 2 / branch n) / 2 := by + refine ConditionalVariation.observed_sigma_le_const source _ _ _ ?_ observe + intro s + rw [CommonProductVariation.product_totalVariation] + exact ProjectedPrefixComparison.original_variation calls rows repeats (slots s) + (projected s) (p s) (choiceLaw s) β hβ hβ' (ν s) (q s) hbranch + +end +end PerfectCompleteness.ProjectedPrefixConditional + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/ProjectedWholeCut.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/ProjectedWholeCut.lean new file mode 100644 index 0000000000000000000000000000000000000000..b4f88a65e9b39a064430e002754ca671afc1a333 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/ProjectedWholeCut.lean @@ -0,0 +1,189 @@ +import OAI.Computability.PerfectCompleteness.Decoding.OriginalWholeCutProjection +import OAI.Computability.PerfectCompleteness.Decoding.UpperCutOldRecord +import OAI.Computability.PerfectCompleteness.Foundations.ProjectedCutChoices + +namespace OAI + +section + +namespace PerfectCompleteness.ProjectedWholeCut + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCutTape +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +noncomputable section + +private theorem product_mixture {E A B Γ : Type*} + [Fintype E] [Fintype A] [Fintype B] [Fintype Γ] + (μ : FiniteDistribution E) (ν : FiniteDistribution A) + (P : A → FiniteDistribution B) (f : E × B → Γ) : + (μ.product (ν.mixture P)).pushforward f = + ν.mixture (fun a => (μ.product (P a)).pushforward f) := by + have hproduct : μ.product (ν.mixture P) = ν.mixture (fun a => μ.product (P a)) := by + apply FiniteDistribution.eq_of_weight_eq + intro x + change μ.weight x.1 * (∑ a, ν.weight a * (P a).weight x.2) = + ∑ a, ν.weight a * (μ.weight x.1 * (P a).weight x.2) + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro a _ + ring + rw [hproduct, FiniteDistribution.pushforward_mixture] + +private theorem lifted_assembled_congr {branch : Nat → Nat} {m t : Nat} + (calls : Nat) (rows : Nat → Nat) + (left right right' : Slots branch (m + 1) → Fin t → MixedSupport.Slot) + (q : ∀ s a, MixedSupport.Projection (left s a) (right s a)) + (q' : ∀ s a, MixedSupport.Projection (left s a) (right' s a)) + (hright : right = right') (hq : ∀ s a, HEq (q s a) (q' s a)) : + (FiniteDistribution.uniform (CutChildGrouping.Assembled (C := Fin calls) right rows)).pushforward + (ChildAssemblyProjection.assembledPullback rows q) = + (FiniteDistribution.uniform (CutChildGrouping.Assembled (C := Fin calls) right' rows)).pushforward + (ChildAssemblyProjection.assembledPullback rows q') := by + cases hright + have heq : q = q' := by + funext s a + exact eq_of_heq (hq s a) + cases heq + rfl + +variable {branch : Nat → Nat} {n m j t : Nat} + (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + {Z : Fin (branch m) → Type*} [∀ child, Fintype (Z child)] + (projected : (child : Fin (branch m)) → Z child → Slots branch m → Fin t → MixedSupport.Slot) + (projection : ∀ child z s a, MixedSupport.Projection + (childSlots (cutSlots p slots) child s a) (projected child z s a)) + +def fullSlots (choices : ProjectedCutChoices.Choices (Z := Z)) : + Slots branch n → Fin t → MixedSupport.Slot := + CutSlotAssembly.fill p slots + (ProjectedCutChoices.selectedSlots (cutSlots p slots) projected choices) + +theorem fill_native : CutSlotAssembly.fill p slots (cutSlots p slots) = slots := + CutSlotAssembly.fill_restrict p slots + +def fullProjection (choices : ProjectedCutChoices.Choices (Z := Z)) : + ∀ s a, MixedSupport.Projection (slots s a) (fullSlots p slots projected choices s a) := + fun s a => CutProjectionAssembly.castProjection + (congrFun (congrFun (fill_native p slots) s) a) rfl + (CutProjectionAssembly.fillProjection p slots (cutSlots p slots) + (ProjectedCutChoices.selectedSlots (cutSlots p slots) projected choices) + (ProjectedCutChoices.selectedProjection (cutSlots p slots) projected projection choices) s a) + +omit [∀ child, Fintype (Z child)] in +theorem cut_fullSlots (choices : ProjectedCutChoices.Choices (Z := Z)) : + cutSlots p (fullSlots p slots projected choices) = + ProjectedCutChoices.selectedSlots (cutSlots p slots) projected choices := by + funext s a + exact congrFun (CutSlotAssembly.fill_at_cut p slots + (ProjectedCutChoices.selectedSlots (cutSlots p slots) projected choices) s) a + +omit [∀ child, Fintype (Z child)] in +theorem cut_fullProjection (choices : ProjectedCutChoices.Choices (Z := Z)) + (s : Slots branch (m + 1)) (a : Fin t) : + HEq (CutGroupedProjection.cutProjection p (fullProjection p slots projected projection choices) s a) + (ProjectedCutChoices.selectedProjection (cutSlots p slots) projected projection choices s a) := + (CutProjectionAssembly.castProjection_heq + (congrFun (congrFun (fill_native p slots) (p.slotEmbedding s)) a) rfl + (CutProjectionAssembly.fillProjection p slots (cutSlots p slots) + (ProjectedCutChoices.selectedSlots (cutSlots p slots) projected choices) + (ProjectedCutChoices.selectedProjection (cutSlots p slots) projected projection choices) + (p.slotEmbedding s) a)).trans + (CutProjectionAssembly.fillProjection_at_cut p slots (cutSlots p slots) + (ProjectedCutChoices.selectedSlots (cutSlots p slots) projected choices) + (ProjectedCutChoices.selectedProjection (cutSlots p slots) projected projection choices) s a) + +omit [∀ child, Fintype (Z child)] in +theorem fullSlots_outside (choices : ProjectedCutChoices.Choices (Z := Z)) + (s : Slots branch n) (hs : WholeCutExteriorTransport.Outside p s) : + slots s = fullSlots p slots projected choices s := by + calc + slots s = CutSlotAssembly.fill p slots (cutSlots p slots) s := + (congrFun (fill_native p slots) s).symm + _ = _ := CutSlotAssembly.fill_outside_eq p slots (cutSlots p slots) + (ProjectedCutChoices.selectedSlots (cutSlots p slots) projected choices) s hs + +omit [∀ child, Fintype (Z child)] in +theorem fullProjection_outside (choices : ProjectedCutChoices.Choices (Z := Z)) + (s : Slots branch n) (hs : WholeCutExteriorTransport.Outside p s) (a : Fin t) : + HEq (fullProjection p slots projected projection choices s a) + (MixedSupport.Projection.keep (slots s a)) := by + have hkeep : HEq + (MixedSupport.Projection.keep (CutSlotAssembly.fill p slots (cutSlots p slots) s a)) + (MixedSupport.Projection.keep (slots s a)) := by + rw [fill_native p slots] + exact (CutProjectionAssembly.castProjection_heq _ _ _).trans + ((CutProjectionGeometry.fillProjection_outside p slots (cutSlots p slots) + (ProjectedCutChoices.selectedSlots (cutSlots p slots) projected choices) + (ProjectedCutChoices.selectedProjection (cutSlots p slots) projected projection choices) s hs a).trans + hkeep) + +omit [∀ child, Fintype (Z child)] in +theorem fixed_law (rows repeats : Nat → Nat) (choices : ProjectedCutChoices.Choices (Z := Z)) : + ((OriginalWholeCutTape.exteriorLaw rows repeats p slots).product + ((FiniteDistribution.uniform (CutChildGrouping.Assembled + (C := Fin (OriginalCutCalls.count rows repeats n (m + 1))) + (ProjectedCutChoices.selectedSlots (cutSlots p slots) projected choices) rows)).pushforward + (ChildAssemblyProjection.assembledPullback rows + (ProjectedCutChoices.selectedProjection (cutSlots p slots) projected projection choices)))).pushforward + (OriginalWholeCutBridge.reconstruct rows repeats p slots) = + (WholeArraySampler.law rows repeats p (fullSlots p slots projected choices)).pushforward + (ChildBlockProjection.arraysPullback rows (fullProjection p slots projected projection choices)) := by + have h := OriginalWholeCutProjection.fixed_projected_law rows repeats p slots + (fullSlots p slots projected choices) (fullProjection p slots projected projection choices) + (fullSlots_outside p slots projected choices) + (fullProjection_outside p slots projected projection choices) + have hblocks := lifted_assembled_congr (OriginalCutCalls.count rows repeats n (m + 1)) rows + (cutSlots p slots) (cutSlots p (fullSlots p slots projected choices)) + (ProjectedCutChoices.selectedSlots (cutSlots p slots) projected choices) + (CutGroupedProjection.cutProjection p (fullProjection p slots projected projection choices)) + (ProjectedCutChoices.selectedProjection (cutSlots p slots) projected projection choices) + (cut_fullSlots p slots projected choices) + (cut_fullProjection p slots projected projection choices) + rw [hblocks] at h + exact h + +def arrayLaw (rows repeats : Nat → Nat) + (choiceLaw : (child : Fin (branch m)) → FiniteDistribution (Z child)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) : FiniteDistribution (Arrays slots rows) := + (ProjectedCutChoices.choicesLaw choiceLaw β hβ hβ').mixture (fun choices => + (WholeArraySampler.law rows repeats p (fullSlots p slots projected choices)).pushforward + (ChildBlockProjection.arraysPullback rows (fullProjection p slots projected projection choices))) + +theorem reconstruct_assembled_law (rows repeats : Nat → Nat) + (choiceLaw : (child : Fin (branch m)) → FiniteDistribution (Z child)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) : + ((OriginalWholeCutTape.exteriorLaw rows repeats p slots).product + (ProjectedPrefixComparison.assembledLaw (OriginalCutCalls.count rows repeats n (m + 1)) + rows (cutSlots p slots) projected projection choiceLaw β hβ hβ')).pushforward + (OriginalWholeCutBridge.reconstruct rows repeats p slots) = + arrayLaw p slots projected projection rows repeats choiceLaw β hβ hβ' := by + rw [ProjectedCutChoices.assembled_eq_mixture (cutSlots p slots) projected projection + (OriginalCutCalls.count rows repeats n (m + 1)) rows choiceLaw β hβ hβ', product_mixture] + unfold arrayLaw + apply congrArg ((ProjectedCutChoices.choicesLaw choiceLaw β hβ hβ').mixture) + funext choices + exact fixed_law p slots projected projection rows repeats choices + +theorem old_arrayLaw_eq (rows repeats : Nat → Nat) (upperPath : Path branch n (j + 1)) + (lowerPath : Path branch (j + 1) (m + 1)) + (projected : (child : Fin (branch m)) → Z child → Slots branch m → Fin t → MixedSupport.Slot) + (projection : ∀ child z s a, MixedSupport.Projection + (childSlots (cutSlots (upperPath.append lowerPath) slots) child s a) (projected child z s a)) + (choiceLaw : (child : Fin (branch m)) → FiniteDistribution (Z child)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) : + UpperCutOldRecord.arrayLaw rows repeats upperPath lowerPath slots + projected projection choiceLaw β hβ hβ' = + arrayLaw (upperPath.append lowerPath) slots projected projection rows repeats choiceLaw β hβ hβ' := + reconstruct_assembled_law (upperPath.append lowerPath) slots projected projection + rows repeats choiceLaw β hβ hβ' + +end +end PerfectCompleteness.ProjectedWholeCut + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/QuarterBalanceLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/QuarterBalanceLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..e0810441a8cb69ee25c5915bbbd8a6b7c25f1196 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/QuarterBalanceLemmas.lean @@ -0,0 +1,407 @@ +import Mathlib.Algebra.BigOperators.GroupWithZero.Finset +import Mathlib.Algebra.Field.ZMod +import Mathlib.LinearAlgebra.Pi +import Mathlib.Logic.Equiv.Prod +import Mathlib.Tactic.FinCases +import OAI.Computability.PerfectCompleteness.Foundations.RecursiveSpaceEquivLemmas +import OAI.Computability.PerfectCompleteness.Repetition.CleanConditioning +import OAI.Computability.UniqueGames.Games.FinishBoundsLemmas + +namespace OAI + + +namespace PerfectCompleteness.QuarterBalance + +open scoped BigOperators +open UniqueGamesTheorem.Foundations.Games +open PerfectCompleteness SmallBias + +noncomputable section + +abbrev F2 := ZMod 2 + +def sign (b : F2) : ℝ := if b = 0 then 1 else -1 + +theorem scalar_cases : ∀ b : F2, b = 0 ∨ b = 1 := by decide + +@[simp] theorem sign_zero : sign 0 = 1 := by simp [sign] +@[simp] theorem sign_one : sign 1 = -1 := by simp [sign] +@[simp] theorem abs_sign (b : F2) : |sign b| = 1 := by unfold sign; split <;> norm_num + +theorem sign_add (a b : F2) : sign (a + b) = sign a * sign b := by + have htwo : (1 : F2) + 1 = 0 := by decide + rcases scalar_cases a with rfl | rfl <;> + rcases scalar_cases b with rfl | rfl <;> simp [htwo] + +theorem sign_sum {J : Type*} (s : Finset J) (f : J → F2) : + sign (∑ j ∈ s, f j) = ∏ j ∈ s, sign (f j) := by + classical + induction s using Finset.induction_on with + | empty => simp + | @insert j s hj ih => simp [Finset.sum_insert, Finset.prod_insert, hj, sign_add, ih] + +variable {Ω : Type*} [Fintype Ω] + +theorem bit_probabilities (μ : FiniteDistribution Ω) (f : Ω → F2) : + μ.probability (fun x => decide (f x = 0)) + + μ.probability (fun x => decide (f x = 1)) = 1 := by + rw [← μ.normalized] + simp only [FiniteDistribution.probability, ← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro x _ + have hb : f x = 0 ∨ f x = 1 := scalar_cases (f x) + rcases hb with h | h <;> simp [h] + +theorem expectation_sign (μ : FiniteDistribution Ω) (f : Ω → F2) : + μ.expectation (fun x => sign (f x)) = + 2 * μ.probability (fun x => decide (f x = 0)) - 1 := by + rw [← μ.normalized] + simp only [FiniteDistribution.expectation, FiniteDistribution.probability, + Finset.mul_sum, ← Finset.sum_sub_distrib, sign] + apply Finset.sum_congr rfl + intro x _ + by_cases h : f x = 0 <;> simp [h] + ring + +theorem bias_of_balanced_bits (μ : FiniteDistribution Ω) (f : Ω → F2) + (c : ℝ) (lower : ∀ b : F2, c ≤ μ.probability (fun x => decide (f x = b))) : + |μ.expectation (fun x => sign (f x))| ≤ 1 - 2 * c := by + rw [expectation_sign] + have h0 := lower 0 + have h1 := lower 1 + have ht := bit_probabilities μ f + exact abs_le.mpr ⟨by linarith, by linarith⟩ + +variable {V W : Type*} [AddCommGroup V] [Module F2 V] [Fintype V] + [AddCommGroup W] [Module F2 W] [Fintype W] + +def Balanced (μ : FiniteDistribution V) : Prop := + ∀ (f : V →ₗ[F2] F2), f ≠ 0 → ∀ b : F2, + (1 / 4 : ℝ) ≤ μ.probability (fun x => decide (f x = b)) + +theorem balanced_of_bias_le_half (μ : FiniteDistribution V) + (bias : ∀ f : V →ₗ[F2] F2, f ≠ 0 → + |μ.expectation (fun x => sign (f x))| ≤ (1 / 2 : ℝ)) : Balanced μ := by + intro f hf b + have h := abs_le.mp (bias f hf) + rw [expectation_sign] at h + have ht := bit_probabilities μ f + rcases scalar_cases b with rfl | rfl <;> linarith + +theorem bilinear_bit_lower (μ : FiniteDistribution V) (ν : FiniteDistribution W) + (hμ : Balanced μ) (hν : Balanced ν) + (B : V →ₗ[F2] W →ₗ[F2] F2) (nonzero : B ≠ 0) (b : F2) : + (1 / 16 : ℝ) ≤ (μ.product ν).probability (fun z => decide (B z.1 z.2 = b)) := by + classical + have hw : ∃ w : W, (B.flip w) ≠ 0 := by + by_contra h + push Not at h + apply nonzero + ext v w + have he := congrArg (fun f : V →ₗ[F2] F2 => f v) (h w) + simpa using he + obtain ⟨w, hw⟩ := hw + have lower (v : V) : + (if B.flip w v = 1 then (1 / 4 : ℝ) else 0) ≤ + ν.probability (fun x => decide (B v x = b)) := by + by_cases h : B.flip w v = 1 + · rw [ite_eq_left h] + apply hν (B v) + intro hz + have he := congrArg (fun f : W →ₗ[F2] F2 => f w) hz + have hh : B v w = 1 := h + simp only [LinearMap.zero_apply] at he + exact zero_ne_one (he.symm.trans hh) + · rw [ite_eq_right h] + exact ν.probability_nonnegative _ + have hfirst := hμ (B.flip w) hw 1 + calc + (1 / 16 : ℝ) ≤ (1 / 4 : ℝ) * μ.probability (fun v => decide (B.flip w v = 1)) := by + nlinarith + _ = ∑ v, μ.weight v * (if B.flip w v = 1 then (1 / 4 : ℝ) else 0) := by + simp only [FiniteDistribution.probability, Finset.mul_sum] + apply Finset.sum_congr rfl + intro v _ + by_cases h : B v w = 1 <;> simp [h, LinearMap.flip_apply] + ring + _ ≤ ∑ v, μ.weight v * ν.probability (fun x => decide (B v x = b)) := + Finset.sum_le_sum fun v _ => mul_le_mul_of_nonneg_left (lower v) (μ.nonnegative v) + _ = _ := by + simp only [FiniteDistribution.probability, FiniteDistribution.product, + Fintype.sum_prod_type, Finset.mul_sum] + apply Finset.sum_congr rfl + intro v _ + apply Finset.sum_congr rfl + intro x _ + by_cases h : B v x = b <;> simp [h] + +theorem bilinear_bias (μ : FiniteDistribution V) (ν : FiniteDistribution W) + (hμ : Balanced μ) (hν : Balanced ν) + (B : V →ₗ[F2] W →ₗ[F2] F2) (nonzero : B ≠ 0) : + |(μ.product ν).expectation (fun z => sign (B z.1 z.2))| ≤ (7 / 8 : ℝ) := by + have h := bias_of_balanced_bits (μ.product ν) (fun z => B z.1 z.2) (1 / 16) + (bilinear_bit_lower μ ν hμ hν B nonzero) + norm_num at h ⊢ + exact h + +end +end PerfectCompleteness.QuarterBalance + + + +namespace PerfectCompleteness.SelectedSources + +open scoped BigOperators +open UniqueGamesTheorem.Foundations.Games +open FiniteProduct CleanConditioning + +noncomputable section + +section Product + +variable {I : Type*} [Fintype I] [DecidableEq I] + {Ω : I → Type*} [∀ i, Fintype (Ω i)] + +theorem expectation_product_selected (P : (i : I) → FiniteDistribution (Ω i)) + (selected : I → Prop) [DecidablePred selected] + (f : (i : Subtype selected) → Ω i → ℝ) : + (law P).expectation (fun x => ∏ i : Subtype selected, f i (x i)) = + ∏ i : Subtype selected, (P i).expectation (f i) := by + let g : (i : I) → Ω i → ℝ := fun i a => + if h : selected i then f ⟨i, h⟩ a else 1 + have hprod (x : (i : I) → Ω i) : + (∏ i, g i (x i)) = ∏ i : Subtype selected, f i (x i) := by + simp only [g, Fintype.prod_dite, Finset.prod_const_one, mul_one] + have hexp (i : I) : (P i).expectation (g i) = + if h : selected i then (P i).expectation (f ⟨i, h⟩) else 1 := by + by_cases hi : selected i <;> simp [g, hi, SmallBias.expectation_const] + calc + _ = (law P).expectation (fun x => ∏ i, g i (x i)) := + FiniteDistribution.expectation_congr _ (fun x => (hprod x).symm) + _ = ∏ i, (P i).expectation (g i) := expectation_product P g + _ = ∏ i, if h : selected i then (P i).expectation (f ⟨i, h⟩) else 1 := by + apply Finset.prod_congr rfl + intro i _ + exact hexp i + _ = _ := by simp only [Fintype.prod_dite, Finset.prod_const_one, mul_one] + +theorem pushforward_law_selected (P : (i : I) → FiniteDistribution (Ω i)) + (selected : I → Prop) [DecidablePred selected] + {Γ : Subtype selected → Type*} [∀ i, Fintype (Γ i)] + (source : (i : Subtype selected) → Ω i → Γ i) : + (law P).pushforward (fun x (i : Subtype selected) => source i (x i)) = + law (fun i : Subtype selected => (P i).pushforward (source i)) := by + classical + apply FiniteDistribution.eq_of_weight_eq + intro y + calc + _ = (law P).expectation + (fun x => if (fun i : Subtype selected => source i (x i)) = y then 1 else 0) := by + simp [FiniteDistribution.pushforward, FiniteDistribution.expectation, mul_ite] + apply Finset.sum_congr rfl + intro x _ + by_cases h : (fun i : Subtype selected => source i (x i)) = y <;> simp [h] + _ = (law P).expectation + (fun x => ∏ i : Subtype selected, if source i (x i) = y i then 1 else 0) := by + apply FiniteDistribution.expectation_congr + intro x + simp only [Fintype.prod_boole, funext_iff] + _ = ∏ i : Subtype selected, (P i).expectation + (fun a => if source i a = y i then 1 else 0) := + expectation_product_selected (I := I) (Ω := Ω) P selected + (fun (i : Subtype selected) (a : Ω i) => if source i a = y i then (1 : ℝ) else 0) + _ = _ := by + simp [law, FiniteDistribution.pushforward, FiniteDistribution.expectation, mul_ite] + +theorem selected_sources_conditioned (P : (i : I) → FiniteDistribution (Ω i)) + (event : (i : I) → Ω i → Bool) + (positive : 0 < (law P).probability (allEvent event)) + (selected : I → Prop) [DecidablePred selected] + {Γ : Subtype selected → Type*} [∀ i, Fintype (Γ i)] + (source : (i : Subtype selected) → Ω i → Γ i) + (μ : (i : Subtype selected) → FiniteDistribution (Γ i)) + (row : ∀ i : Subtype selected, + ((P i).condition (event i) (coordinate_probability_positive P event positive i)).pushforward + (source i) = μ i) : + ((law P).condition (allEvent event) positive).pushforward + (fun x (i : Subtype selected) => source i (x i)) = law μ := by + rw [condition_law_all, pushforward_law_selected] + congr 1 + funext i + exact row i + +end Product + +section Records + +variable {E R T : Type*} + +def childObservation (clean : E → R → T → Bool) (x : E × (R × T)) : + Sum (E × (R × T)) R := + if clean x.1 x.2.1 x.2.2 then Sum.inr x.2.1 else Sum.inl x + +theorem clean_observation_event [DecidableEq E] [DecidableEq R] [DecidableEq T] + (clean : E → R → T → Bool) (record : R) : + (fun x => decide (childObservation clean x = Sum.inr record)) = + (fun x => decide (x.2.1 = record) && clean x.1 x.2.1 x.2.2) := by + funext x + cases h : clean x.1 x.2.1 x.2.2 <;> simp [childObservation, h] + +end Records + + +variable {I : Type*} [Fintype I] [DecidableEq I] + {E R T : I → Type*} + [∀ i, Fintype (E i)] [∀ i, Fintype (R i)] [∀ i, Fintype (T i)] + [∀ i, DecidableEq (E i)] [∀ i, DecidableEq (R i)] [∀ i, DecidableEq (T i)] + +theorem clean_record_sources + (μ : (i : I) → FiniteDistribution (E i)) + (ν : (i : I) → FiniteDistribution (R i)) + (kernel : (i : I) → E i → R i → FiniteDistribution (T i)) + (clean : (i : I) → E i → R i → T i → Bool) + (p : I → ℝ) + (constant : ∀ i e r, (kernel i e r).probability (clean i e r) = p i) + (record : (i : I) → Sum (E i × (R i × T i)) (R i)) + (positive : 0 < + (law (fun i => kernelJoint (μ i) (fun e => kernelJoint (ν i) (kernel i e)))).probability + (allEvent (fun i x => decide (childObservation (clean i) x = record i)))) : + ((law (fun i => kernelJoint (μ i) (fun e => kernelJoint (ν i) (kernel i e)))).condition + (allEvent (fun i x => decide (childObservation (clean i) x = record i))) + positive).pushforward + (fun x (i : {i : I // ∃ r, record i = Sum.inr r}) => (x i).1) = + law (fun i : {i : I // ∃ r, record i = Sum.inr r} => μ i) := by + classical + let P := fun i => kernelJoint (μ i) (fun e => kernelJoint (ν i) (kernel i e)) + let event := fun i x => decide (childObservation (clean i) x = record i) + apply selected_sources_conditioned P event positive + (fun i => ∃ r, record i = Sum.inr r) (fun _ x => x.1) (fun i => μ i) + intro i + obtain ⟨r, hr⟩ := i.property + have hevent : event i = + (fun x => decide (x.2.1 = r) && clean i x.1 x.2.1 x.2.2) := by + dsimp [event] + rw [hr] + exact clean_observation_event (clean i) r + have hpositive := coordinate_probability_positive P event positive i + have hp : 0 < (P i).probability + (fun x => decide (x.2.1 = r) && clean i x.1 x.2.1 x.2.2) := by + rwa [hevent] at hpositive + simpa only [hevent] using + designated_source_condition (μ i) (ν i) (kernel i) (clean i) (p i) (constant i) r hp + + +end +end PerfectCompleteness.SelectedSources + + + +namespace PerfectCompleteness.SourceCoordinateSplit + +open scoped BigOperators +open UniqueGamesTheorem.Foundations.Games +open FiniteProduct + +noncomputable section + +variable {I : Type*} [Fintype I] [DecidableEq I] + {Ω : I → Type*} [∀ i, Fintype (Ω i)] + +theorem coordinate_split (P : (i : I) → FiniteDistribution (Ω i)) (i : I) : + (law P).transport (Equiv.piSplitAt i Ω) = + (P i).product (law (fun j : {j : I // j ≠ i} => P j)) := by + classical + apply FiniteDistribution.eq_of_weight_eq + intro y + change (∏ j, (P j).weight ((Equiv.piSplitAt i Ω).symm y j)) = + (P i).weight y.1 * ∏ j : {j : I // j ≠ i}, (P j).weight (y.2 j) + calc + _ = ∏ j, if h : j = i then (P i).weight y.1 else (P j).weight (y.2 ⟨j, h⟩) := by + apply Finset.prod_congr rfl + intro j _ + by_cases hj : j = i + · subst j + simp [Equiv.piSplitAt] + · simp [Equiv.piSplitAt, hj] + _ = _ := by + rw [Fintype.prod_dite] + simp + +theorem coordinate_split_pushforward (P : (i : I) → FiniteDistribution (Ω i)) + (i : I) : + (law P).pushforward (fun x => (x i, fun j : {j : I // j ≠ i} => x j)) = + (P i).product (law (fun j : {j : I // j ≠ i} => P j)) := by + change (law P).pushforward (Equiv.piSplitAt i Ω) = _ + rw [← FiniteDistribution.transport_eq_pushforward] + exact coordinate_split P i + +theorem iid_coordinate_split {E : Type*} [Fintype E] {n : Nat} + (μ : FiniteDistribution E) (i : Fin n) : + (μ.iid n).pushforward (fun x => (x i, fun j : {j : Fin n // j ≠ i} => x j)) = + μ.product (FiniteDistribution.table (fun _ : {j : Fin n // j ≠ i} => μ)) := by + change (law (fun _ : Fin n => μ)).pushforward + (fun x => (x i, fun j : {j : Fin n // j ≠ i} => x j)) = + μ.product (law (fun _ : {j : Fin n // j ≠ i} => μ)) + exact coordinate_split_pushforward (fun _ : Fin n => μ) i + +end +end PerfectCompleteness.SourceCoordinateSplit + + + +namespace PerfectCompleteness.FiniteProductSplit + +noncomputable section + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games + +variable {I : Type*} [Fintype I] [DecidableEq I] + {Ω : I → Type*} [∀ i, Fintype (Ω i)] + +abbrev Others (i : I) := (j : {j : I // j ≠ i}) → Ω j.val + +def others (i : I) (x : (j : I) → Ω j) : Others (Ω := Ω) i := fun j => x j.val + +def otherLaw (P : (i : I) → FiniteDistribution (Ω i)) (i : I) : + FiniteDistribution (Others (Ω := Ω) i) := + FiniteProduct.law (fun j : {j : I // j ≠ i} => P j.val) + +theorem split_law (P : (i : I) → FiniteDistribution (Ω i)) (i : I) : + (FiniteProduct.law P).pushforward (Equiv.piSplitAt i Ω) = + (P i).product (otherLaw P i) := + SourceCoordinateSplit.coordinate_split_pushforward P i + +theorem expectation_split (P : (i : I) → FiniteDistribution (Ω i)) (i : I) + (f : Ω i → Others (Ω := Ω) i → ℝ) : + (FiniteProduct.law P).expectation (fun x => f (x i) (others i x)) = + (P i).expectation (fun a => (otherLaw P i).expectation (fun b => f a b)) := by + have h := congrArg (fun μ : FiniteDistribution (Ω i × Others (Ω := Ω) i) => + μ.expectation (fun z => f z.1 z.2)) (split_law P i) + rw [FiniteDistribution.expectation_pushforward, FiniteDistribution.expectation_product] at h + exact h + +theorem expectation_background_first (P : (i : I) → FiniteDistribution (Ω i)) (i : I) + (f : Ω i → Others (Ω := Ω) i → ℝ) : + (FiniteProduct.law P).expectation (fun x => f (x i) (others i x)) = + (otherLaw P i).expectation (fun b => (P i).expectation (fun a => f a b)) := by + rw [expectation_split] + exact FiniteDistribution.expectation_comm (P i) (otherLaw P i) f + +theorem resampling_expectation (P : (i : I) → FiniteDistribution (Ω i)) (i : I) + (f : Others (Ω := Ω) i → Ω i → Ω i → ℝ) : + ((FiniteProduct.law P).product (P i)).expectation + (fun z => f (others i z.1) (z.1 i) z.2) = + (otherLaw P i).expectation + (fun b => ((P i).product (P i)).expectation (fun z => f b z.1 z.2)) := by + rw [FiniteDistribution.expectation_product] + rw [expectation_background_first P i + (fun a b => (P i).expectation (fun a' => f b a a'))] + apply FiniteDistribution.expectation_congr + intro b + exact (FiniteDistribution.expectation_product (P i) (P i) (fun z => f b z.1 z.2)).symm + +end +end PerfectCompleteness.FiniteProductSplit + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/QuotientTableAgreementLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/QuotientTableAgreementLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..529346b046a5a83aa4bfd4f71276ddfe78d5d156 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/QuotientTableAgreementLemmas.lean @@ -0,0 +1,343 @@ +import OAI.Computability.PerfectCompleteness.Algebra.MatrixRowQuotientLaw +import OAI.Computability.PerfectCompleteness.Foundations.CanonicalEdgesLemmas +import OAI.Computability.PerfectCompleteness.Foundations.CanonicalKeys +import OAI.Computability.PerfectCompleteness.Foundations.ClauseSupportLemmas +import OAI.Computability.PerfectCompleteness.Foundations.FiniteRangeInverse +import OAI.Computability.PerfectCompleteness.Foundations.RecursiveSpaceEquivLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.QuotientTableAgreement + +noncomputable section + +open scoped BigOperators Classical +open UniqueGamesTheorem.Fourier.MatrixCharacters (F2) +open PartialTableInverse + +attribute [local instance] UniqueGamesTheorem.Appendix.RankLevelFilter.linearMapFintype + +variable {H K Y : Type*} [AddCommGroup H] [Module F2 H] + [AddCommGroup K] [Module F2 K] + [FiniteDimensional F2 H] [FiniteDimensional F2 K] + [Fintype H] [Fintype K] [Fintype Y] + +def projectedAgreement (W : Submodule F2 H) + (f : (Module.Dual F2 (H ⧸ W) →ₗ[F2] K) → Option Y) : ℝ := + 𝔼 a : {a : K // a ≠ 0}, 𝔼 X : Module.Dual F2 H →ₗ[F2] K, 𝔼 h : H, + definedEquality f (MatrixRowQuotient.projectMatrix W X) + (MatrixRowQuotient.projectMatrix W (FiniteRangeInverse.matrixStep X a.val h)) + +omit [FiniteDimensional F2 H] [FiniteDimensional F2 K] [Fintype Y] in +theorem projectedAgreement_eq (W : Submodule F2 H) + (f : (Module.Dual F2 (H ⧸ W) →ₗ[F2] K) → Option Y) : + projectedAgreement W f = FiniteRangeInverse.agreement f := by + unfold projectedAgreement FiniteRangeInverse.agreement + apply Finset.expect_congr rfl + intro a _ + exact MatrixRowQuotientLaw.expect_project_rankOne_pair W a.val + (fun X X' => definedEquality f X X') + +omit [FiniteDimensional F2 K] [Fintype Y] in +theorem projectedAgreement_eq_nonzeroAgreement (W : Submodule F2 H) + (f : (Module.Dual F2 (H ⧸ W) →ₗ[F2] K) → Option Y) : + projectedAgreement W f = nonzeroAgreement f := by + rw [projectedAgreement_eq, FiniteRangeInverse.agreement_eq_nonzeroAgreement] + +end +end PerfectCompleteness.QuotientTableAgreement + +end + +section + +namespace PerfectCompleteness.MixedSupport + +open ClauseSupport + +variable {I C Y Z : Type*} + +theorem localKey_kernel_invariant (s : Slot) + (f : C → s.Domain → Y) (g : C → s.Domain → Z) + (hkernel : ∀ c u v, f c u = f c v ↔ g c u = g c v) : + localKey s f = localKey s g := by + classical + cases s with + | clause occurrence variableIDs signs => + change clauseKey occurrence variableIDs f = clauseKey occurrence variableIDs g + simp only [clauseKey, clauseMode_kernel_invariant f g hkernel] + | bit variableID => + change C → Bool → Y at f + change C → Bool → Z at g + change bitKey variableID f = bitKey variableID g + simp only [bitKey, unused_kernel_invariant f g hkernel] + +theorem localReduction_kernel_invariant (s : Slot) + (f : C → s.Domain → Y) (g : C → s.Domain → Z) + (hkernel : ∀ c u v, f c u = f c v ↔ g c u = g c v) : + localReduction s f = localReduction s g := by + classical + cases s with + | clause occurrence variableIDs signs => + change clauseReduction f = clauseReduction g + simp only [clauseReduction, clauseMode_kernel_invariant f g hkernel] + | bit variableID => + change C → Bool → Y at f + change C → Bool → Z at g + funext b + change bitReduction f b = bitReduction g b + simp only [bitReduction, unused_kernel_invariant f g hkernel] + +variable [DecidableEq I] + +theorem sectionFunction_kernel_invariant (slots : I → Slot) + (f : Assignment slots → Y) (g : Assignment slots → Z) + (hkernel : ∀ x x', f x = f x' ↔ g x = g x') (i : I) : + ∀ context u v, + sectionFunction slots f i context u = sectionFunction slots f i context v ↔ + sectionFunction slots g i context u = sectionFunction slots g i context v := by + intro context u v + exact hkernel (Function.update context i u) (Function.update context i v) + +theorem keyFields_kernel_invariant (slots : I → Slot) + (f : Assignment slots → Y) (g : Assignment slots → Z) + (hkernel : ∀ x x', f x = f x' ↔ g x = g x') : + keyFields slots f = keyFields slots g := by + funext i + exact localKey_kernel_invariant (slots i) + (sectionFunction slots f i) (sectionFunction slots g i) + (sectionFunction_kernel_invariant slots f g hkernel i) + +theorem coordinateReduction_kernel_invariant (slots : I → Slot) + (f : Assignment slots → Y) (g : Assignment slots → Z) + (hkernel : ∀ x x', f x = f x' ↔ g x = g x') : + coordinateReduction slots f = coordinateReduction slots g := by + funext i + exact localReduction_kernel_invariant (slots i) + (sectionFunction slots f i) (sectionFunction slots g i) + (sectionFunction_kernel_invariant slots f g hkernel i) + +theorem reduction_kernel_invariant (slots : I → Slot) + (f : Assignment slots → Y) (g : Assignment slots → Z) + (hkernel : ∀ x x', f x = f x' ↔ g x = g x') : + reduction slots f = reduction slots g := by + unfold reduction + rw [coordinateReduction_kernel_invariant slots f g hkernel] + +theorem retainedKeys_kernel_invariant {n : Nat} (slots : Fin n → Slot) + (f : Assignment slots → Y) (g : Assignment slots → Z) + (hkernel : ∀ x x', f x = f x' ↔ g x = g x') : + retainedKeys slots f = retainedKeys slots g := by + simp only [retainedKeys, keyFields_kernel_invariant slots f g hkernel] + +end PerfectCompleteness.MixedSupport + +namespace PerfectCompleteness.ReducedPartition + +variable {X R Y Z : Type*} + +theorem fiber_kernel_invariant (r : X → R) (f : X → Y) (g : X → Z) + (hkernel : ∀ x x', f x = f x' ↔ g x = g x') (x : X) : + fiber r f x = fiber r g x := by + ext v + constructor + · rintro ⟨z, hz, hfz⟩ + exact ⟨z, hz, (hkernel z x).1 hfz⟩ + · rintro ⟨z, hz, hgz⟩ + exact ⟨z, hz, (hkernel z x).2 hgz⟩ + +theorem parts_kernel_invariant (r : X → R) (f : X → Y) (g : X → Z) + (hkernel : ∀ x x', f x = f x' ↔ g x = g x') : + parts r f = parts r g := by + have hfiber : fiber r f = fiber r g := + funext (fiber_kernel_invariant r f g hkernel) + unfold parts + rw [hfiber] + +end PerfectCompleteness.ReducedPartition + +namespace PerfectCompleteness.MixedSupport + +variable {I Y Z : Type*} [DecidableEq I] + +theorem reducedParts_kernel_invariant (slots : I → Slot) + (f : Assignment slots → Y) (g : Assignment slots → Z) + (hkernel : ∀ x x', f x = f x' ↔ g x = g x') : + ReducedPartition.parts (reduction slots f) f = + ReducedPartition.parts (reduction slots g) g := by + rw [reduction_kernel_invariant slots f g hkernel] + exact ReducedPartition.parts_kernel_invariant (reduction slots g) f g hkernel + +end PerfectCompleteness.MixedSupport + +end + +section + +namespace PerfectCompleteness.CanonicalKeys + +open MixedSupport + +variable {n : Nat} {Y Z : Type*} + +theorem partition_kernel_invariant (slots : Fin n → Slot) + (f : Assignment slots → Y) (g : Assignment slots → Z) + (hkernel : ∀ x x', f x = f x' ↔ g x = g x') : + partition slots f = partition slots g := + reducedParts_kernel_invariant slots f g hkernel + +theorem key_kernel_invariant (side : Side) (slots : Fin n → Slot) + (f : Assignment slots → Y) (g : Assignment slots → Z) + (hkernel : ∀ x x', f x = f x' ↔ g x = g x') : + key side slots f = key side slots g := by + simp only [key, retainedKeys_kernel_invariant slots f g hkernel, + partition_kernel_invariant slots f g hkernel] + +theorem key_postcomp_injective (side : Side) (slots : Fin n → Slot) + (f : Assignment slots → Y) (e : Y → Z) (he : Function.Injective e) : + key side slots (e ∘ f) = key side slots f := by + apply key_kernel_invariant + intro x x' + exact ⟨fun h => he h, fun h => congrArg e h⟩ + +theorem key_postcomp_equiv (side : Side) (slots : Fin n → Slot) + (f : Assignment slots → Y) (e : Y ≃ Z) : + key side slots (e ∘ f) = key side slots f := + key_postcomp_injective side slots f e e.injective + +noncomputable def transportKernel (slots : Fin n → Slot) + (f : Assignment slots → Y) (g : Assignment slots → Z) + (hkernel : ∀ x x', f x = f x' ↔ g x = g x') (P : Label slots f) : + Label slots g := + ⟨P.val, by + change P.val ∈ partition slots g + rw [← partition_kernel_invariant slots f g hkernel] + exact P.property⟩ + +theorem transportKernel_bijective (slots : Fin n → Slot) + (f : Assignment slots → Y) (g : Assignment slots → Z) + (hkernel : ∀ x x', f x = f x' ↔ g x = g x') : + Function.Bijective (transportKernel slots f g hkernel) := by + constructor + · intro P Q h + exact Subtype.ext (congrArg (fun R : Label slots g => R.val) h) + · intro Q + have hQ : Q.val ∈ partition slots f := by + rw [partition_kernel_invariant slots f g hkernel] + exact Q.property + exact ⟨⟨Q.val, hQ⟩, Subtype.ext rfl⟩ + +theorem transportKernel_evaluateLabel (slots : Fin n → Slot) + (f : Assignment slots → Y) (g : Assignment slots → Z) + (hkernel : ∀ x x', f x = f x' ↔ g x = g x') (x : Assignment slots) : + transportKernel slots f g hkernel (evaluateLabel slots f x) = + evaluateLabel slots g x := by + apply Subtype.ext + change ReducedPartition.fiber (reduction slots f) f x = + ReducedPartition.fiber (reduction slots g) g x + rw [reduction_kernel_invariant slots f g hkernel] + exact ReducedPartition.fiber_kernel_invariant (reduction slots g) f g hkernel x + +theorem restore_transportKernel (slots : Fin n → Slot) + (f : Assignment slots → Y) (g : Assignment slots → Z) + (hkernel : ∀ x x', f x = f x' ↔ g x = g x') + (e : Y → Z) (he : ∀ x, g x = e (f x)) (P : Label slots f) : + restore slots g (transportKernel slots f g hkernel P) = e (restore slots f P) := by + obtain ⟨x, hx⟩ := ReducedPartition.label_surjective (reduction slots f) f P + change evaluateLabel slots f x = P at hx + rw [← hx, transportKernel_evaluateLabel, restore_evaluateLabel, restore_evaluateLabel] + exact he x + +end PerfectCompleteness.CanonicalKeys + +end + +section + +namespace PerfectCompleteness.KeyStrategy + +noncomputable section + +open scoped Classical +open ClauseSupport MixedSupport CanonicalKeys + +abbrev NonemptyKey (n : Nat) := {k : Key n // k.partition.Nonempty} + +abbrev Strategy (n : Nat) := + (k : NonemptyKey n) → {P : Set (Fin n → ReducedValue) // P ∈ k.val.partition} + +variable {n : Nat} {Y Z : Type*} + +def queryKey (side : Side) (slots : Fin n → Slot) (f : Assignment slots → Y) : + NonemptyKey n := + ⟨key side slots f, by + obtain ⟨x⟩ := (inferInstance : Nonempty (Assignment slots)) + exact ⟨(evaluateLabel slots f x).val, (evaluateLabel slots f x).property⟩⟩ + +def label (σ : Strategy n) (side : Side) (slots : Fin n → Slot) + (f : Assignment slots → Y) : Label slots f := + σ (queryKey side slots f) + +def response (σ : Strategy n) (side : Side) (slots : Fin n → Slot) + (f : Assignment slots → Y) : Y := + restore slots f (label σ side slots f) + +theorem response_mem_range (σ : Strategy n) (side : Side) (slots : Fin n → Slot) + (f : Assignment slots → Y) : response σ side slots f ∈ Set.range f := + ReducedPartition.output_mem_range (reduction slots f) f (label σ side slots f) + +theorem label_val_eq_of_key_eq (σ : Strategy n) (side side' : Side) + (slots projected : Fin n → Slot) (f : Assignment slots → Y) + (g : Assignment projected → Z) (hkey : key side slots f = key side' projected g) : + (label σ side slots f).val = (label σ side' projected g).val := by + have hk : queryKey side slots f = queryKey side' projected g := Subtype.ext hkey + exact congrArg (fun k : NonemptyKey n => (σ k).val) hk + +theorem response_postcomp_injective (σ : Strategy n) (side : Side) + (slots : Fin n → Slot) (f : Assignment slots → Y) (e : Y → Z) + (he : Function.Injective e) : + response σ side slots (e ∘ f) = e (response σ side slots f) := by + let hkernel : ∀ x x', f x = f x' ↔ (e ∘ f) x = (e ∘ f) x' := + fun _ _ => ⟨fun h => congrArg e h, fun h => he h⟩ + have hlabel : label σ side slots (e ∘ f) = + transportKernel slots f (e ∘ f) hkernel (label σ side slots f) := by + apply Subtype.ext + exact label_val_eq_of_key_eq σ side side slots slots (e ∘ f) f + (key_postcomp_injective side slots f e he) + unfold response + rw [hlabel] + exact restore_transportKernel slots f (e ∘ f) hkernel e (fun _ => rfl) + (label σ side slots f) + +theorem response_projection (σ : Strategy n) (side : Side) + {slots projected : Fin n → Slot} (p : ∀ i, Projection (slots i) (projected i)) + (f : Assignment projected → Y) : + response σ side slots (f ∘ projectionMap p) = response σ side projected f := by + have hlabel : transportLabel p f (label σ side slots (f ∘ projectionMap p)) = + label σ side projected f := by + apply Subtype.ext + exact label_val_eq_of_key_eq σ side side slots projected (f ∘ projectionMap p) f + (key_projection side p f) + unfold response + rw [restore_projection, hlabel] + +def extend (vertices : Set (Key n)) + (σ : (k : ↥vertices) → {P : Set (Fin n → ReducedValue) // P ∈ k.val.partition}) : + Strategy n := fun k => + if h : k.val ∈ vertices then σ ⟨k.val, h⟩ + else ⟨Classical.choose k.property, Classical.choose_spec k.property⟩ + +theorem extend_val (vertices : Set (Key n)) + (σ : (k : ↥vertices) → {P : Set (Fin n → ReducedValue) // P ∈ k.val.partition}) + (k : NonemptyKey n) (hk : k.val ∈ vertices) : + (extend vertices σ k).val = (σ ⟨k.val, hk⟩).val := by + simp [extend, hk] + +end +end PerfectCompleteness.KeyStrategy + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/RawOccurrenceOrderLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/RawOccurrenceOrderLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..61971deb0ffe9fb5009af6199ca9a35c5234dd22 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/RawOccurrenceOrderLemmas.lean @@ -0,0 +1,262 @@ +import Mathlib.Data.List.Nodup +import Mathlib.Data.List.ProdSigma +import Mathlib.Tactic.FieldSimp +import Mathlib.Tactic.Ring +import OAI.Computability.PerfectCompleteness.Construction.SourceQuestionOrderLemmas +import OAI.Computability.PerfectCompleteness.Foundations.DummyEliminationLemmas +import OAI.Computability.PerfectCompleteness.Sampling.MetadataFreeLaw + +namespace OAI + + +namespace PerfectCompleteness.RawOccurrenceOrder + +open MetadataFreeSampler MetadataFreeLaw +open scoped BigOperators Classical + +noncomputable section + +variable {branch : Nat → Nat} {n t v m : Nat} + +def signedOrder (signs : SignTuple branch n t) (rows repeats : Nat → Nat) : + List (SignedOutcome signs rows repeats) := + List.ofFn (Fintype.equivFin (SignedOutcome signs rows repeats)).symm + +@[simp] theorem signedOrder_length (signs : SignTuple branch n t) (rows repeats : Nat → Nat) : + (signedOrder signs rows repeats).length = Fintype.card (SignedOutcome signs rows repeats) := by + simp only [signedOrder, List.length_ofFn] + +theorem signedOrder_nodup (signs : SignTuple branch n t) (rows repeats : Nat → Nat) : + (signedOrder signs rows repeats).Nodup := + List.nodup_ofFn.mpr (Fintype.equivFin (SignedOutcome signs rows repeats)).symm.injective + +theorem mem_signedOrder (signs : SignTuple branch n t) (rows repeats : Nat → Nat) + (outcome : SignedOutcome signs rows repeats) : outcome ∈ signedOrder signs rows repeats := by + apply List.mem_ofFn.mpr + exact ⟨Fintype.equivFin _ outcome, Equiv.symm_apply_apply _ _⟩ + +def rawOrder (clauses : Fin m → SourceClause.NormalizedClause v) + (branch : Nat → Nat) (n t : Nat) (rows repeats : Nat → Nat) : + List (PreliminarySampler.Raw clauses branch n t rows repeats) := + (SourceQuestionOrder.sourceOrder branch n t m).flatMap fun source => + (signedOrder (sourceSigns clauses source) rows repeats).map fun outcome => + (rawEquiv clauses rows repeats).symm ⟨source, outcome⟩ + +theorem mem_rawOrder (clauses : Fin m → SourceClause.NormalizedClause v) + (branch : Nat → Nat) (n t : Nat) (rows repeats : Nat → Nat) + (e : PreliminarySampler.Raw clauses branch n t rows repeats) : + e ∈ rawOrder clauses branch n t rows repeats := by + apply List.mem_flatMap.mpr + refine ⟨e.1.1, SourceQuestionOrder.mem_sourceOrder e.1.1, ?_⟩ + apply List.mem_map.mpr + refine ⟨encodeOutcome clauses rows repeats e, + mem_signedOrder _ rows repeats (encodeOutcome clauses rows repeats e), ?_⟩ + exact (rawEquiv clauses rows repeats).symm_apply_apply e + +theorem rawOrder_eq_map_sigma (clauses : Fin m → SourceClause.NormalizedClause v) + (branch : Nat → Nat) (n t : Nat) (rows repeats : Nat → Nat) : + rawOrder clauses branch n t rows repeats = + ((SourceQuestionOrder.sourceOrder branch n t m).sigma + (fun source => signedOrder (sourceSigns clauses source) rows repeats)).map + (rawEquiv clauses rows repeats).symm := by + simp only [rawOrder, List.sigma, List.map_flatMap, List.map_map, Function.comp_def] + +theorem rawOrder_nodup (clauses : Fin m → SourceClause.NormalizedClause v) + (branch : Nat → Nat) (n t : Nat) (rows repeats : Nat → Nat) : + (rawOrder clauses branch n t rows repeats).Nodup := by + rw [rawOrder_eq_map_sigma] + apply List.Nodup.map (rawEquiv clauses rows repeats).symm.injective + exact (SourceQuestionOrder.sourceOrder_nodup branch n t m).sigma + (fun source => signedOrder_nodup (sourceSigns clauses source) rows repeats) + +theorem rawOrder_length (clauses : Fin m → SourceClause.NormalizedClause v) + (branch : Nat → Nat) (n t : Nat) (rows repeats : Nat → Nat) : + (rawOrder clauses branch n t rows repeats).length = + ∑ source : PreliminarySampler.Questions branch n t m, + Fintype.card (SignedOutcome (sourceSigns clauses source) rows repeats) := by + simp only [rawOrder, List.length_flatMap, List.length_map, signedOrder_length] + exact SourceQuestionOrder.sum_map_sourceOrder _ + +def fiberBound (branch : Nat → Nat) (n t : Nat) (rows repeats : Nat → Nat) : Nat := + ∑ signs : SignTuple branch n t, Fintype.card (SignedOutcome signs rows repeats) + +theorem signed_card_le_fiberBound (signs : SignTuple branch n t) (rows repeats : Nat → Nat) : + Fintype.card (SignedOutcome signs rows repeats) ≤ fiberBound branch n t rows repeats := by + unfold fiberBound + exact Finset.single_le_sum + (fun signs _ => Nat.zero_le (Fintype.card (SignedOutcome signs rows repeats))) + (Finset.mem_univ signs) + +theorem rawOrder_length_le (clauses : Fin m → SourceClause.NormalizedClause v) + (branch : Nat → Nat) (n t : Nat) (rows repeats : Nat → Nat) : + (rawOrder clauses branch n t rows repeats).length ≤ + fiberBound branch n t rows repeats * m ^ TreeCanonical.locationCount branch n t := by + rw [rawOrder_length] + calc + (∑ source : PreliminarySampler.Questions branch n t m, + Fintype.card (SignedOutcome (sourceSigns clauses source) rows repeats)) ≤ + ∑ _source : PreliminarySampler.Questions branch n t m, + fiberBound branch n t rows repeats := + Finset.sum_le_sum (fun source _ => signed_card_le_fiberBound + (sourceSigns clauses source) rows repeats) + _ = fiberBound branch n t rows repeats * m ^ TreeCanonical.locationCount branch n t := by + rw [Finset.sum_const, Finset.card_univ, nsmul_eq_mul, + Fintype.card_congr (SourceQuestionOrder.questionTupleEquiv branch n t m)] + simp only [Fintype.card_fun, Fintype.card_fin, Nat.cast_id, Nat.mul_comm] + +end + +end PerfectCompleteness.RawOccurrenceOrder + + +namespace PerfectCompleteness.SignedMultiplicity + +open RecursiveSpaces MetadataFreeSampler MetadataFreeLaw +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +noncomputable section + +variable (branch : Nat → Nat) (n t : Nat) (rows repeats : Nat → Nat) + (hn : 0 < n) (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) + +def weights (signs : SignTuple branch n t) : SignedOutcome signs rows repeats → ℚ := + (signedRationalLaw signs rows repeats hn hbranch hrows).weights + +theorem weights_positive (signs : SignTuple branch n t) (e : SignedOutcome signs rows repeats) : + 0 < weights branch n t rows repeats hn hbranch hrows signs e := + (signedRationalLaw signs rows repeats hn hbranch hrows).positive e + +theorem weights_total (signs : SignTuple branch n t) : + (∑ e, weights branch n t rows repeats hn hbranch hrows signs e) = 1 := + (signedRationalLaw signs rows repeats hn hbranch hrows).total + +def baseDenominator : Nat := + ExactRationalMultiplicity.commonDenominator (weights branch n t rows repeats hn hbranch hrows) + +def baseCopies (signs : SignTuple branch n t) (e : SignedOutcome signs rows repeats) : Nat := + ExactRationalMultiplicity.multiplicity (weights branch n t rows repeats hn hbranch hrows) signs e + +theorem baseDenominator_positive : 0 < baseDenominator branch n t rows repeats hn hbranch hrows := + ExactRationalMultiplicity.commonDenominator_pos _ + +theorem baseCopies_positive (signs : SignTuple branch n t) (e : SignedOutcome signs rows repeats) : + 0 < baseCopies branch n t rows repeats hn hbranch hrows signs e := + ExactRationalMultiplicity.multiplicity_pos _ + (weights_positive branch n t rows repeats hn hbranch hrows) signs e + +theorem baseCopies_total (signs : SignTuple branch n t) : + (∑ e, baseCopies branch n t rows repeats hn hbranch hrows signs e) = + baseDenominator branch n t rows repeats hn hbranch hrows := + ExactRationalMultiplicity.multiplicity_sum _ + (weights_positive branch n t rows repeats hn hbranch hrows) + (weights_total branch n t rows repeats hn hbranch hrows) signs + +theorem baseCopies_ratio (signs : SignTuple branch n t) (e : SignedOutcome signs rows repeats) : + (baseCopies branch n t rows repeats hn hbranch hrows signs e : ℚ) / + baseDenominator branch n t rows repeats hn hbranch hrows = + weights branch n t rows repeats hn hbranch hrows signs e := + ExactRationalMultiplicity.multiplicity_div _ + (weights_positive branch n t rows repeats hn hbranch hrows) signs e + +def denominator (q : Nat) : Nat := + ExactSeedMultiplicity.denominator (baseDenominator branch n t rows repeats hn hbranch hrows) (2 * q) + +theorem denominator_positive (q : Nat) : + 0 < denominator branch n t rows repeats hn hbranch hrows q := + ExactSeedMultiplicity.denominator_positive + (baseDenominator_positive branch n t rows repeats hn hbranch hrows) (2 * q) + +variable {v m : Nat} (clauses : Fin m → SourceClause.NormalizedClause v) + +def rawCopies (e : PreliminarySampler.Raw clauses branch n t rows repeats) : Nat := + baseCopies branch n t rows repeats hn hbranch hrows (sourceSigns clauses e.1.1) + (encodeOutcome clauses rows repeats e) + +theorem rawCopies_total : + (∑ e, rawCopies branch n t rows repeats hn hbranch hrows clauses e) = + Fintype.card (PreliminarySampler.Questions branch n t m) * + baseDenominator branch n t rows repeats hn hbranch hrows := by + let f : (Σ source : PreliminarySampler.Questions branch n t m, + SignedOutcome (sourceSigns clauses source) rows repeats) → Nat := + fun e => baseCopies branch n t rows repeats hn hbranch hrows + (sourceSigns clauses e.1) e.2 + have hreindex := (rawEquiv (t := t) clauses rows repeats).sum_comp f + change (∑ e, f (rawEquiv clauses rows repeats e)) = _ + rw [hreindex, Fintype.sum_sigma] + simp only [f, baseCopies_total, Finset.sum_const, Finset.card_univ, Nat.nsmul_eq_mul] + +variable {q : Nat} + (count : PreliminarySampler.Raw clauses branch n t rows repeats → Nat) + (positive : ∀ e, 0 < count e) (bounded : ∀ e, count e ≤ 2 * q) + +def completedCopies (e : ExactSeedMultiplicity.Seeded count) : Nat := + ExactSeedMultiplicity.perSeed (2 * q) (count e.1) + (rawCopies branch n t rows repeats hn hbranch hrows clauses e.1) + +include positive bounded + +theorem completedCopies_positive (e : ExactSeedMultiplicity.Seeded count) : + 0 < completedCopies (q := q) branch n t rows repeats hn hbranch hrows clauses count e := + ExactSeedMultiplicity.perSeed_positive (positive e.1) (bounded e.1) + (baseCopies_positive branch n t rows repeats hn hbranch hrows _ _) + +theorem completedCopies_total : + (∑ e, completedCopies (q := q) branch n t rows repeats hn hbranch hrows clauses count e) = + Fintype.card (PreliminarySampler.Questions branch n t m) * + denominator branch n t rows repeats hn hbranch hrows q := by + have h := ExactSeedMultiplicity.sum_multiplicity + (rawCopies branch n t rows repeats hn hbranch hrows clauses) count positive bounded + (rawCopies_total branch n t rows repeats hn hbranch hrows clauses) + change (∑ e, completedCopies (q := q) branch n t rows repeats hn hbranch hrows clauses count e) = + (Fintype.card (PreliminarySampler.Questions branch n t m) * + baseDenominator branch n t rows repeats hn hbranch hrows) * + ExactSeedMultiplicity.factor (2 * q) at h + exact h.trans (Nat.mul_assoc _ _ _) + +theorem completedCopies_polynomial_total : + (∑ e, completedCopies (q := q) branch n t rows repeats hn hbranch hrows clauses count e) = + denominator branch n t rows repeats hn hbranch hrows q * + m ^ (t * Fintype.card (Slots branch n)) := by + rw [completedCopies_total branch n t rows repeats hn hbranch hrows clauses count positive bounded, + Fintype.card_eq_nat_card, TreeCardinality.source_questions_card] + exact Nat.mul_comm _ _ + +theorem completedCopies_conditional_ratio (e : ExactSeedMultiplicity.Seeded count) : + (completedCopies (q := q) branch n t rows repeats hn hbranch hrows clauses count e : ℚ) / + denominator branch n t rows repeats hn hbranch hrows q = + weights branch n t rows repeats hn hbranch hrows (sourceSigns clauses e.1.1.1) + (encodeOutcome clauses rows repeats e.1) / count e.1 := by + change (ExactSeedMultiplicity.perSeed (2 * q) (count e.1) + (rawCopies branch n t rows repeats hn hbranch hrows clauses e.1) : ℚ) / + ExactSeedMultiplicity.denominator + (baseDenominator branch n t rows repeats hn hbranch hrows) (2 * q) = _ + rw [ExactSeedMultiplicity.perSeed_ratio + (baseDenominator_positive branch n t rows repeats hn hbranch hrows) + (positive e.1) (bounded e.1)] + change ((baseCopies branch n t rows repeats hn hbranch hrows + (sourceSigns clauses e.1.1.1) (encodeOutcome clauses rows repeats e.1) : ℚ) / _) / _ = _ + rw [baseCopies_ratio] + +theorem completedCopies_mass [NeZero m] (e : ExactSeedMultiplicity.Seeded count) : + (completedCopies (q := q) branch n t rows repeats hn hbranch hrows clauses count e : ℝ) / + (Fintype.card (PreliminarySampler.Questions branch n t m) * + denominator branch n t rows repeats hn hbranch hrows q : Nat) = + (PreliminarySampler.law clauses rows repeats hn hbranch hrows).weight e.1 / + count e.1 := by + have h := congrArg (fun x : ℚ => (x : ℝ)) + (completedCopies_conditional_ratio branch n t rows repeats hn hbranch hrows + clauses count positive bounded e) + simp only [Rat.cast_div, Rat.cast_natCast] at h + rw [raw_weight_rational clauses rows repeats hn hbranch hrows e.1] + change (_ : ℝ) = (1 / _) * + (weights branch n t rows repeats hn hbranch hrows (sourceSigns clauses e.1.1.1) + (encodeOutcome clauses rows repeats e.1) : ℝ) / _ + rw [Nat.cast_mul, mul_comm + (Fintype.card (PreliminarySampler.Questions branch n t m) : ℝ), ← div_div, h] + ring + +end +end PerfectCompleteness.SignedMultiplicity + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/RecursiveSpaceEquivLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/RecursiveSpaceEquivLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..3fa14026b25acd90166379bfa78fa456b8bd3419 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/RecursiveSpaceEquivLemmas.lean @@ -0,0 +1,808 @@ +import Mathlib.Data.Fintype.Card +import Mathlib.Data.Set.Disjoint +import Mathlib.FieldTheory.Finiteness +import Mathlib.LinearAlgebra.FreeModule.Finite.Matrix +import Mathlib.SetTheory.Cardinal.Finite +import Mathlib.Tactic.NormNum +import OAI.Computability.PerfectCompleteness.Algebra.BilinearGramCompressionLemmas +import OAI.Computability.PerfectCompleteness.Foundations.RecursiveSpaces +import OAI.Computability.UniqueGames.Analysis.MatrixCharactersLemmas +import OAI.Computability.UniqueGames.Foundations.FiniteTrialsLemmas +import OAI.Computability.UniqueGames.Foundations.SamplingLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.RecursiveSpaceEquiv + +open PointwiseSpaces RecursiveSpaces + +universe u v w + +variable {𝕜 : Type w} [Field 𝕜] {branch : Nat → Nat} {n : Nat} + {A : Slots branch n → Type u} {B : Slots branch n → Type v} + +def assignmentEquiv (e : ∀ s, A s ≃ B s) : Assignment A ≃ Assignment B where + toFun := project (fun s => e s) + invFun := project (fun s => (e s).symm) + left_inv x := by + funext s + exact (e s).symm_apply_apply (x s) + right_inv x := by + funext s + exact (e s).apply_symm_apply (x s) + +def spaceEquiv (e : ∀ s, A s ≃ B s) : + space 𝕜 branch n B ≃ₗ[𝕜] space 𝕜 branch n A where + toLinearMap := spacePullback A B (fun s => e s) + invFun := spacePullback B A (fun s => (e s).symm) + left_inv f := by + apply Subtype.ext + funext x + change f.val (project (fun s => e s) (project (fun s => (e s).symm) x)) = f.val x + apply congrArg f.val + funext s + exact (e s).apply_symm_apply (x s) + right_inv f := by + apply Subtype.ext + funext x + change f.val (project (fun s => (e s).symm) (project (fun s => e s) x)) = f.val x + apply congrArg f.val + funext s + exact (e s).symm_apply_apply (x s) + +@[simp] theorem spaceEquiv_apply (e : ∀ s, A s ≃ B s) + (f : space 𝕜 branch n B) (x : Assignment A) : + (spaceEquiv e f).val x = f.val (project (fun s => e s) x) := rfl + +def squarePullback (e : ∀ s, A s → B s) : + squareSpace (space 𝕜 branch n B) →ₗ[𝕜] squareSpace (space 𝕜 branch n A) where + toFun f := ⟨pullback 𝕜 (project e) f.val, + squareSpace_project_le A B e (Submodule.mem_map_of_mem f.property)⟩ + map_add' _ _ := Subtype.ext rfl + map_smul' _ _ := Subtype.ext rfl + +def squareEquiv (e : ∀ s, A s ≃ B s) : + squareSpace (space 𝕜 branch n B) ≃ₗ[𝕜] squareSpace (space 𝕜 branch n A) where + toLinearMap := squarePullback (fun s => e s) + invFun := squarePullback (fun s => (e s).symm) + left_inv f := by + apply Subtype.ext + funext x + change f.val (project (fun s => e s) (project (fun s => (e s).symm) x)) = f.val x + apply congrArg f.val + funext s + exact (e s).apply_symm_apply (x s) + right_inv f := by + apply Subtype.ext + funext x + change f.val (project (fun s => (e s).symm) (project (fun s => e s) x)) = f.val x + apply congrArg f.val + funext s + exact (e s).symm_apply_apply (x s) + +@[simp] theorem squareEquiv_apply (e : ∀ s, A s ≃ B s) + (f : squareSpace (space 𝕜 branch n B)) (x : Assignment A) : + (squareEquiv e f).val x = f.val (project (fun s => e s) x) := rfl + +theorem space_natCard_eq (e : ∀ s, A s ≃ B s) : + Nat.card (space 𝕜 branch n A) = Nat.card (space 𝕜 branch n B) := + Nat.card_congr (spaceEquiv (𝕜 := 𝕜) e).symm.toEquiv + +theorem square_natCard_eq (e : ∀ s, A s ≃ B s) : + Nat.card (squareSpace (space 𝕜 branch n A)) = + Nat.card (squareSpace (space 𝕜 branch n B)) := + Nat.card_congr (squareEquiv (𝕜 := 𝕜) e).symm.toEquiv + +theorem space_card_eq [Fintype (space 𝕜 branch n A)] [Fintype (space 𝕜 branch n B)] + (e : ∀ s, A s ≃ B s) : + Fintype.card (space 𝕜 branch n A) = Fintype.card (space 𝕜 branch n B) := + Fintype.card_congr (spaceEquiv (𝕜 := 𝕜) e).symm.toEquiv + +theorem square_card_eq [Fintype (squareSpace (space 𝕜 branch n A))] + [Fintype (squareSpace (space 𝕜 branch n B))] (e : ∀ s, A s ≃ B s) : + Fintype.card (squareSpace (space 𝕜 branch n A)) = + Fintype.card (squareSpace (space 𝕜 branch n B)) := + Fintype.card_congr (squareEquiv (𝕜 := 𝕜) e).symm.toEquiv + +end PerfectCompleteness.RecursiveSpaceEquiv + +end + +section + +namespace PerfectCompleteness.ReducedPartition + +variable {X W R Y : Type*} + +def ConstantOnFibers (r : X → R) (f : X → Y) : Prop := + ∀ x x', r x = r x' → f x = f x' + +def fiber (r : X → R) (f : X → Y) (x : X) : Set R := + {v | ∃ z, r z = v ∧ f z = f x} + +def parts (r : X → R) (f : X → Y) : Set (Set R) := + Set.range (fiber r f) + +theorem self_mem_fiber (r : X → R) (f : X → Y) (x : X) : + r x ∈ fiber r f x := + ⟨x, rfl, rfl⟩ + +theorem fiber_nonempty (r : X → R) (f : X → Y) (x : X) : + (fiber r f x).Nonempty := + ⟨r x, self_mem_fiber r f x⟩ + +theorem fiber_subset_range (r : X → R) (f : X → Y) (x : X) : + fiber r f x ⊆ Set.range r := by + rintro v ⟨z, hz, _⟩ + exact ⟨z, hz⟩ + +theorem mem_fiber_iff (r : X → R) (f : X → Y) + (hf : ConstantOnFibers r f) (z x : X) : + r z ∈ fiber r f x ↔ f z = f x := by + constructor + · rintro ⟨w, hw, hfw⟩ + exact (hf w z hw).symm.trans hfw + · intro h + exact ⟨z, rfl, h⟩ + +theorem fiber_eq_of_output_eq (r : X → R) (f : X → Y) {x x' : X} + (h : f x = f x') : fiber r f x = fiber r f x' := by + ext v + constructor + · rintro ⟨z, hz, hfz⟩ + exact ⟨z, hz, hfz.trans h⟩ + · rintro ⟨z, hz, hfz⟩ + exact ⟨z, hz, hfz.trans h.symm⟩ + +theorem fiber_eq_iff (r : X → R) (f : X → Y) + (hf : ConstantOnFibers r f) (x x' : X) : + fiber r f x = fiber r f x' ↔ f x = f x' := by + constructor + · intro h + apply (mem_fiber_iff r f hf x x').1 + rw [← h] + exact self_mem_fiber r f x + · exact fiber_eq_of_output_eq r f + +theorem output_eq_of_common_mem (r : X → R) (f : X → Y) + (hf : ConstantOnFibers r f) {x x' : X} {v : R} + (hx : v ∈ fiber r f x) (hx' : v ∈ fiber r f x') : f x = f x' := by + obtain ⟨z, hz, hfz⟩ := hx + obtain ⟨z', hz', hfz'⟩ := hx' + exact hfz.symm.trans ((hf z z' (hz.trans hz'.symm)).trans hfz') + +theorem fiber_disjoint_of_output_ne (r : X → R) (f : X → Y) + (hf : ConstantOnFibers r f) {x x' : X} (h : f x ≠ f x') : + Disjoint (fiber r f x) (fiber r f x') := by + apply Set.disjoint_left.2 + intro v hv hv' + exact h (output_eq_of_common_mem r f hf hv hv') + +theorem fiber_eq_or_disjoint (r : X → R) (f : X → Y) + (hf : ConstantOnFibers r f) (x x' : X) : + fiber r f x = fiber r f x' ∨ Disjoint (fiber r f x) (fiber r f x') := by + classical + by_cases h : f x = f x' + · exact Or.inl (fiber_eq_of_output_eq r f h) + · exact Or.inr (fiber_disjoint_of_output_ne r f hf h) + +theorem covered_iff_mem_range (r : X → R) (f : X → Y) (v : R) : + (∃ P ∈ parts r f, v ∈ P) ↔ v ∈ Set.range r := by + constructor + · rintro ⟨P, ⟨x, hx⟩, hv⟩ + apply fiber_subset_range r f x + rw [hx] + exact hv + · rintro ⟨x, hx⟩ + refine ⟨fiber r f x, ⟨x, rfl⟩, ?_⟩ + exact ⟨x, hx, rfl⟩ + +abbrev Part (r : X → R) (f : X → Y) := ↥(parts r f) + +def label (r : X → R) (f : X → Y) (x : X) : Part r f := + ⟨fiber r f x, ⟨x, rfl⟩⟩ + +instance [Nonempty X] (r : X → R) (f : X → Y) : Nonempty (Part r f) := by + obtain ⟨x⟩ := ‹Nonempty X› + exact ⟨label r f x⟩ + +noncomputable def representative (r : X → R) (f : X → Y) (P : Part r f) : X := + P.property.choose + +theorem representative_spec (r : X → R) (f : X → Y) (P : Part r f) : + fiber r f (representative r f P) = P.val := + P.property.choose_spec + +theorem representative_mem (r : X → R) (f : X → Y) (P : Part r f) : + r (representative r f P) ∈ P.val := by + rw [← representative_spec r f P] + exact self_mem_fiber r f _ + +theorem part_nonempty (r : X → R) (f : X → Y) (P : Part r f) : + P.val.Nonempty := + ⟨r (representative r f P), representative_mem r f P⟩ + +noncomputable def output (r : X → R) (f : X → Y) (P : Part r f) : Y := + f (representative r f P) + +theorem output_mem_range (r : X → R) (f : X → Y) (P : Part r f) : + output r f P ∈ Set.range f := + ⟨representative r f P, rfl⟩ + +theorem mem_iff (r : X → R) (f : X → Y) (hf : ConstantOnFibers r f) + (P : Part r f) (x : X) : r x ∈ P.val ↔ f x = output r f P := by + rw [← representative_spec r f P] + exact mem_fiber_iff r f hf x (representative r f P) + +@[simp] theorem output_label (r : X → R) (f : X → Y) + (hf : ConstantOnFibers r f) (x : X) : output r f (label r f x) = f x := + ((mem_iff r f hf (label r f x) x).1 (self_mem_fiber r f x)).symm + +theorem output_injective (r : X → R) (f : X → Y) : + Function.Injective (output r f) := by + intro P Q h + apply Subtype.ext + calc + P.val = fiber r f (representative r f P) := (representative_spec r f P).symm + _ = fiber r f (representative r f Q) := fiber_eq_of_output_eq r f h + _ = Q.val := representative_spec r f Q + +@[simp] theorem label_representative (r : X → R) (f : X → Y) (P : Part r f) : + label r f (representative r f P) = P := by + apply Subtype.ext + exact representative_spec r f P + +theorem label_surjective (r : X → R) (f : X → Y) : + Function.Surjective (label r f) := by + intro P + exact ⟨representative r f P, label_representative r f P⟩ + +instance [Finite X] (r : X → R) (f : X → Y) : Finite (Part r f) := + Finite.of_surjective (label r f) (label_surjective r f) + +theorem card_parts_le [Finite X] (r : X → R) (f : X → Y) : + Nat.card (Part r f) ≤ Nat.card X := + Nat.card_le_card_of_surjective (label r f) (label_surjective r f) + +theorem restoration_bijective (r : X → R) (f : X → Y) + (hf : ConstantOnFibers r f) : + Function.Bijective + (fun P : Part r f => (⟨output r f P, output_mem_range r f P⟩ : Set.range f)) := by + constructor + · intro P Q h + exact output_injective r f (congrArg Subtype.val h) + · intro y + obtain ⟨x, hx⟩ := y.property + refine ⟨label r f x, ?_⟩ + apply Subtype.ext + exact (output_label r f hf x).trans hx + +def rangeMap (r : X → R) (x : X) : Set.range r := + ⟨r x, ⟨x, rfl⟩⟩ + +noncomputable def preimage (r : X → R) (v : Set.range r) : X := + v.property.choose + +theorem preimage_spec (r : X → R) (v : Set.range r) : r (preimage r v) = v.val := + v.property.choose_spec + +theorem rangeMap_preimage (r : X → R) (v : Set.range r) : + rangeMap r (preimage r v) = v := + Subtype.ext (preimage_spec r v) + +theorem rangeMap_surjective (r : X → R) : Function.Surjective (rangeMap r) := by + intro v + exact ⟨preimage r v, rangeMap_preimage r v⟩ + +noncomputable def induced (r : X → R) (f : X → Y) (v : Set.range r) : Y := + f (preimage r v) + +@[simp] theorem induced_rangeMap (r : X → R) (f : X → Y) + (hf : ConstantOnFibers r f) (x : X) : induced r f (rangeMap r x) = f x := + hf _ x (preimage_spec r (rangeMap r x)) + +theorem induced_factorization (r : X → R) (f : X → Y) + (hf : ConstantOnFibers r f) : f = induced r f ∘ rangeMap r := by + funext x + exact (induced_rangeMap r f hf x).symm + +theorem induced_unique (r : X → R) (f : X → Y) (g : Set.range r → Y) + (hg : ∀ x, g (rangeMap r x) = f x) : g = induced r f := by + funext v + calc + g v = g (rangeMap r (preimage r v)) := congrArg g (rangeMap_preimage r v).symm + _ = f (preimage r v) := hg (preimage r v) + _ = induced r f v := rfl + +theorem mem_fiber_iff_induced (r : X → R) (f : X → Y) + (hf : ConstantOnFibers r f) (v : Set.range r) (x : X) : + v.val ∈ fiber r f x ↔ induced r f v = f x := by + have h := mem_fiber_iff r f hf (preimage r v) x + simpa only [preimage_spec, induced] using h + +theorem fiber_eq_of_pullback + (π : X → W) (hπ : Function.Surjective π) + (rX : X → R) (rW : W → R) (fX : X → Y) (fW : W → Y) + (hr : ∀ x, rX x = rW (π x)) (hf : ∀ x, fX x = fW (π x)) (x : X) : + fiber rX fX x = fiber rW fW (π x) := by + ext v + constructor + · rintro ⟨z, hz, hfz⟩ + exact ⟨π z, (hr z).symm.trans hz, (hf z).symm.trans (hfz.trans (hf x))⟩ + · rintro ⟨w, hw, hfw⟩ + obtain ⟨z, hz⟩ := hπ w + refine ⟨z, (hr z).trans ((congrArg rW hz).trans hw), ?_⟩ + exact (hf z).trans ((congrArg fW hz).trans (hfw.trans (hf x).symm)) + +theorem parts_eq_of_pullback + (π : X → W) (hπ : Function.Surjective π) + (rX : X → R) (rW : W → R) (fX : X → Y) (fW : W → Y) + (hr : ∀ x, rX x = rW (π x)) (hf : ∀ x, fX x = fW (π x)) : + parts rX fX = parts rW fW := by + apply Set.ext + intro P + constructor + · rintro ⟨x, hx⟩ + exact ⟨π x, (fiber_eq_of_pullback π hπ rX rW fX fW hr hf x).symm.trans hx⟩ + · rintro ⟨w, hw⟩ + obtain ⟨x, hx⟩ := hπ w + refine ⟨x, ?_⟩ + calc + fiber rX fX x = fiber rW fW (π x) := + fiber_eq_of_pullback π hπ rX rW fX fW hr hf x + _ = fiber rW fW w := congrArg (fiber rW fW) hx + _ = P := hw + +theorem output_eq_of_shared_part + (π : X → W) (rX : X → R) (rW : W → R) (fX : X → Y) (fW : W → Y) + (hr : ∀ x, rX x = rW (π x)) (hf : ∀ x, fX x = fW (π x)) + (hW : ConstantOnFibers rW fW) + (P : Part rX fX) (Q : Part rW fW) (hPQ : P.val = Q.val) : + output rX fX P = output rW fW Q := by + let x := representative rX fX P + have hx : rX x ∈ P.val := representative_mem rX fX P + have hmem : rW (π x) ∈ Q.val := by + rw [← hr x, ← hPQ] + exact hx + change fX x = output rW fW Q + exact (hf x).trans ((mem_iff rW fW hW Q (π x)).1 hmem) + +end PerfectCompleteness.ReducedPartition + +end + +section + +namespace PerfectCompleteness.RowAdvice + +noncomputable section + +open UniqueGamesTheorem.Integration.BinaryLinear (F2) + +def pad {d r : Nat} (_h : d ≤ r) : (Fin d → F2) →ₗ[F2] (Fin r → F2) where + toFun v i := if hi : i.val < d then v ⟨i.val, hi⟩ else 0 + map_add' v w := by + funext i + by_cases hi : i.val < d <;> simp [hi] + map_smul' a v := by + funext i + by_cases hi : i.val < d <;> simp [hi] + +@[simp] theorem pad_low {d r : Nat} (h : d ≤ r) (v : Fin d → F2) (i : Fin d) : + pad h v ⟨i.val, Nat.lt_of_lt_of_le i.isLt h⟩ = v i := by + simp [pad, i.isLt] + +theorem pad_high {d r : Nat} (h : d ≤ r) (v : Fin d → F2) + (i : Fin r) (hi : d ≤ i.val) : pad h v i = 0 := by + simp [pad, Nat.not_lt.mpr hi] + +theorem pad_injective {d r : Nat} (h : d ≤ r) : Function.Injective (pad h) := by + intro v w hvw + funext i + have hi := congrFun hvw (⟨i.val, Nat.lt_of_lt_of_le i.isLt h⟩ : Fin r) + simpa only [pad_low] using hi + +variable {E C R : Type*} + [AddCommGroup E] [Module F2 E] + [AddCommGroup C] [Module F2 C] + [AddCommGroup R] [Module F2 R] + +theorem apply_eq_iff_ker_mkQ_eq (A : C →ₗ[F2] R) (x y : C) : + A x = A y ↔ (LinearMap.ker A).mkQ x = (LinearMap.ker A).mkQ y := by + calc + A x = A y ↔ A (x - y) = 0 := by rw [map_sub, sub_eq_zero] + _ ↔ (LinearMap.ker A).mkQ (x - y) = 0 := + (Submodule.Quotient.mk_eq_zero (LinearMap.ker A)).symm + _ ↔ _ := by rw [map_sub, sub_eq_zero] + +theorem comp_eq_iff_ker_quotient (A : C →ₗ[F2] R) (X T : E →ₗ[F2] C) : + A.comp X = A.comp T ↔ + (LinearMap.ker A).mkQ.comp X = (LinearMap.ker A).mkQ.comp T := by + constructor + · intro h + apply LinearMap.ext + intro x + exact (apply_eq_iff_ker_mkQ_eq A (X x) (T x)).mp (LinearMap.congr_fun h x) + · intro h + apply LinearMap.ext + intro x + exact (apply_eq_iff_ker_mkQ_eq A (X x) (T x)).mpr (LinearMap.congr_fun h x) + +theorem slice_row_eq (W : Submodule F2 E) (A : C →ₗ[F2] R) + (T : E →ₗ[F2] C) (X : MatrixSlice.Slice W (LinearMap.ker A) T) : + A.comp X.val = A.comp T := + (comp_eq_iff_ker_quotient A X.val T).mpr X.property.2 + +def paddedRowMap [FiniteDimensional F2 C] (r : Nat) (C' : Submodule F2 C) + (h : Module.finrank F2 (C ⧸ C') ≤ r) : C →ₗ[F2] (Fin r → F2) := + (pad h).comp (MatrixSlice.rowMap C') + +theorem paddedRowMap_apply_eq_iff [FiniteDimensional F2 C] + (r : Nat) (C' : Submodule F2 C) (h : Module.finrank F2 (C ⧸ C') ≤ r) + (x y : C) : + paddedRowMap r C' h x = paddedRowMap r C' h y ↔ C'.mkQ x = C'.mkQ y := by + constructor + · intro hxy + apply (Module.finBasis F2 (C ⧸ C')).equivFun.injective + exact pad_injective h hxy + · intro hxy + change pad h ((Module.finBasis F2 (C ⧸ C')).equivFun (C'.mkQ x)) = + pad h ((Module.finBasis F2 (C ⧸ C')).equivFun (C'.mkQ y)) + rw [hxy] + +theorem ker_paddedRowMap [FiniteDimensional F2 C] + (r : Nat) (C' : Submodule F2 C) (h : Module.finrank F2 (C ⧸ C') ≤ r) : + LinearMap.ker (paddedRowMap r C' h) = C' := by + ext x + change paddedRowMap r C' h x = 0 ↔ x ∈ C' + calc + paddedRowMap r C' h x = 0 ↔ + paddedRowMap r C' h x = paddedRowMap r C' h 0 := by rw [map_zero] + _ ↔ C'.mkQ x = C'.mkQ 0 := paddedRowMap_apply_eq_iff r C' h x 0 + _ ↔ x ∈ C' := by + rw [map_zero] + exact Submodule.Quotient.mk_eq_zero C' + +theorem paddedRowMap_comp_eq_iff [FiniteDimensional F2 C] + (r : Nat) (C' : Submodule F2 C) (h : Module.finrank F2 (C ⧸ C') ≤ r) + (X T : E →ₗ[F2] C) : + (paddedRowMap r C' h).comp X = (paddedRowMap r C' h).comp T ↔ + C'.mkQ.comp X = C'.mkQ.comp T := by + rw [comp_eq_iff_ker_quotient, ker_paddedRowMap] + +theorem codimension_le_of_order_le (W : Submodule F2 E) (C' : Submodule F2 C) + {r : Nat} (h : UniqueGamesTheorem.Fourier.MatrixRestrictions.order W C' ≤ r) : + Module.finrank F2 (C ⧸ C') ≤ r := + (MatrixSlice.row_count_le_order W C').trans h + +theorem card_rowMaps [FiniteDimensional F2 C] (r : Nat) + [Fintype (C →ₗ[F2] (Fin r → F2))] : + Fintype.card (C →ₗ[F2] (Fin r → F2)) = 2 ^ (r * Module.finrank F2 C) := by + simpa only [Module.finrank_fin_fun, Nat.mul_comm] using + (UniqueGamesTheorem.Fourier.MatrixParity.card_linearMaps (C := C) (E := Fin r → F2)) + +theorem card_rowMaps_le [FiniteDimensional F2 C] (r s : Nat) + [Fintype (C →ₗ[F2] (Fin r → F2))] (hC : Module.finrank F2 C ≤ s) : + Fintype.card (C →ₗ[F2] (Fin r → F2)) ≤ 2 ^ (r * s) := by + rw [card_rowMaps] + exact Nat.pow_le_pow_right (by decide : 0 < 2) (Nat.mul_le_mul_left r hC) + +end +end PerfectCompleteness.RowAdvice + +end + +section + +namespace PerfectCompleteness.SliceMass + +noncomputable section + +open scoped BigOperators Classical +open UniqueGamesTheorem.Integration.BinaryLinear (F2) +open UniqueGamesTheorem.Fourier.MatrixRestrictions (Parameter) +open UniqueGamesTheorem.Foundations.Games +open PerfectCompleteness.MatrixSlice + +variable {E C : Type*} [AddCommGroup E] [Module F2 E] + [AddCommGroup C] [Module F2 C] + +def columnEventEquivSlice (W : Submodule F2 E) (C' : Submodule F2 C) + (T : E →ₗ[F2] C) : + {X : Slice (⊥ : Submodule F2 E) C' T // + X.val.domRestrict W = T.domRestrict W} ≃ Slice W C' T where + toFun X := ⟨X.val.val, X.property, X.val.property.2⟩ + invFun X := ⟨⟨X.val, by + apply LinearMap.ext + intro x + have hx : (x : E) = 0 := (Submodule.mem_bot F2).mp x.property + simp [hx], X.property.2⟩, X.property.1⟩ + left_inv X := by apply Subtype.ext; rfl + right_inv X := by apply Subtype.ext; rfl + +section Finite + +variable [Finite E] [Finite C] + [FiniteDimensional F2 E] [FiniteDimensional F2 C] + +theorem card_slice (W : Submodule F2 E) (C' : Submodule F2 C) + (T : E →ₗ[F2] C) : + Fintype.card (Slice W C' T) = + 2 ^ (Module.finrank F2 (E ⧸ W) * Module.finrank F2 C') := by + rw [← Fintype.card_congr (parameterEquivSlice W C' T)] + rw [Module.card_eq_pow_finrank (K := F2) (V := Parameter W C')] + rw [show Fintype.card F2 = 2 by decide] + change 2 ^ Module.finrank F2 ((E ⧸ W) →ₗ[F2] C') = _ + rw [Module.finrank_linearMap] + +theorem card_rowFiber (C' : Submodule F2 C) (T : E →ₗ[F2] C) : + Fintype.card (Slice (⊥ : Submodule F2 E) C' T) = + 2 ^ (Module.finrank F2 E * Module.finrank F2 C') := by + rw [card_slice] + have hdim := (⊥ : Submodule F2 E).finrank_quotient_add_finrank + simp only [finrank_bot, add_zero] at hdim + rw [hdim] + +theorem card_rowFiber_eq_card_slice_mul (W : Submodule F2 E) + (C' : Submodule F2 C) (T : E →ₗ[F2] C) : + Fintype.card (Slice (⊥ : Submodule F2 E) C' T) = + Fintype.card (Slice W C' T) * + 2 ^ (Module.finrank F2 W * Module.finrank F2 C') := by + rw [card_rowFiber, card_slice, ← pow_add, ← Nat.add_mul, + W.finrank_quotient_add_finrank] + +theorem card_ratio (W : Submodule F2 E) (C' : Submodule F2 C) + (T : E →ₗ[F2] C) : + (Fintype.card (Slice W C' T) : ℝ) / + Fintype.card (Slice (⊥ : Submodule F2 E) C' T) = + 1 / (2 : ℝ) ^ (Module.finrank F2 W * Module.finrank F2 C') := by + rw [card_rowFiber_eq_card_slice_mul W C' T, Nat.cast_mul, Nat.cast_pow, + Nat.cast_ofNat] + have hcard : (Fintype.card (Slice W C' T) : ℝ) ≠ 0 := + Nat.cast_ne_zero.mpr Fintype.card_ne_zero + rw [div_mul_eq_div_div, div_self hcard] + +theorem probability_columnConstraint (W : Submodule F2 E) + (C' : Submodule F2 C) (T : E →ₗ[F2] C) : + (FiniteDistribution.uniform (Slice (⊥ : Submodule F2 E) C' T)).probability + (fun X => decide (X.val.domRestrict W = T.domRestrict W)) = + 1 / (2 : ℝ) ^ (Module.finrank F2 W * Module.finrank F2 C') := by + let event : Slice (⊥ : Submodule F2 E) C' T → Prop := + fun X => X.val.domRestrict W = T.domRestrict W + calc + _ = (FiniteDistribution.uniform (Slice (⊥ : Submodule F2 E) C' T)).expectation + (fun X => if event X then (1 : ℝ) else 0) := by + unfold FiniteDistribution.probability FiniteDistribution.expectation + apply Finset.sum_congr rfl + intro X _ + by_cases hX : event X <;> simp [event] at hX ⊢ + _ = (∑ X, if event X then (1 : ℝ) else 0) / + (Fintype.card (Slice (⊥ : Submodule F2 E) C' T) : ℝ) := + FiniteDistribution.expectation_uniform _ + _ = (Fintype.card {X // event X} : ℝ) / + (Fintype.card (Slice (⊥ : Submodule F2 E) C' T) : ℝ) := by + simp only [Fintype.card_subtype, Finset.sum_boole] + _ = (Fintype.card (Slice W C' T) : ℝ) / + (Fintype.card (Slice (⊥ : Submodule F2 E) C' T) : ℝ) := by + rw [Fintype.card_congr (columnEventEquivSlice W C' T)] + _ = _ := card_ratio W C' T + +theorem probability_columnConstraint_ge (W : Submodule F2 E) + (C' : Submodule F2 C) (T : E →ₗ[F2] C) : + 1 / (2 : ℝ) ^ (Module.finrank F2 W * Module.finrank F2 C) ≤ + (FiniteDistribution.uniform (Slice (⊥ : Submodule F2 E) C' T)).probability + (fun X => decide (X.val.domRestrict W = T.domRestrict W)) := by + rw [probability_columnConstraint] + apply one_div_le_one_div_of_le (pow_pos (by norm_num) _) + exact pow_le_pow_right₀ (by norm_num) + (Nat.mul_le_mul_left _ C'.finrank_le) + +theorem probability_columnConstraint_ge_of_finrank_le + (W : Submodule F2 E) (C' : Submodule F2 C) (T : E →ₗ[F2] C) + (r : Nat) (hW : Module.finrank F2 W ≤ r) : + 1 / (2 : ℝ) ^ (r * Module.finrank F2 C) ≤ + (FiniteDistribution.uniform (Slice (⊥ : Submodule F2 E) C' T)).probability + (fun X => decide (X.val.domRestrict W = T.domRestrict W)) := by + apply le_trans _ (probability_columnConstraint_ge W C' T) + apply one_div_le_one_div_of_le (pow_pos (by norm_num) _) + exact pow_le_pow_right₀ (by norm_num) + (Nat.mul_le_mul_right _ hW) + +end Finite +end +end PerfectCompleteness.SliceMass + +end + +section + +namespace PerfectCompleteness.SmallBias + +open scoped BigOperators +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Foundations.Information + +noncomputable section + +variable {Ω I : Type*} [Fintype Ω] [Fintype I] + +theorem expectation_mono (μ : FiniteDistribution Ω) {a b : Ω → ℝ} + (h : ∀ x, a x ≤ b x) : μ.expectation a ≤ μ.expectation b := by + apply Finset.sum_le_sum + intro x _ + exact mul_le_mul_of_nonneg_left (h x) (μ.nonnegative x) + +@[simp] theorem expectation_const (μ : FiniteDistribution Ω) (c : ℝ) : + μ.expectation (fun _ => c) = c := by + simp only [FiniteDistribution.expectation, ← Finset.sum_mul, μ.normalized, one_mul] + +@[simp] theorem expectation_neg (μ : FiniteDistribution Ω) (a : Ω → ℝ) : + μ.expectation (fun x => -a x) = -μ.expectation a := by + simp only [FiniteDistribution.expectation, mul_neg, Finset.sum_neg_distrib] + +theorem expectation_sum (μ : FiniteDistribution Ω) (a : I → Ω → ℝ) : + μ.expectation (fun x => ∑ i, a i x) = ∑ i, μ.expectation (a i) := by + simp only [FiniteDistribution.expectation, Finset.mul_sum] + exact Finset.sum_comm + +theorem bounded_target_cauchySchwarz (μ : FiniteDistribution Ω) + (g a : Ω → ℝ) (hg : ∀ x, g x ^ 2 ≤ 1) : + μ.expectation (fun x => g x * a x) ^ 2 ≤ + μ.expectation (fun x => a x ^ 2) := by + have hcs := weighted_sum_sq_le μ.weight (fun x => g x * a x) + ⟨μ.nonnegative, μ.normalized⟩ + change μ.expectation (fun x => g x * a x) ^ 2 ≤ + μ.expectation (fun x => (g x * a x) ^ 2) at hcs + apply hcs.trans + apply expectation_mono + intro x + calc + (g x * a x) ^ 2 = g x ^ 2 * a x ^ 2 := mul_pow _ _ _ + _ ≤ 1 * a x ^ 2 := mul_le_mul_of_nonneg_right (hg x) (sq_nonneg _) + _ = a x ^ 2 := one_mul _ + +theorem gram_energy_bound (μ : FiniteDistribution Ω) (f : I → Ω → ℝ) + (biasBound : ℝ) (hf : ∀ i x, f i x ^ 2 ≤ 1) + (hpair : ∀ i j, i ≠ j → μ.expectation (fun x => f i x * f j x) ≤ biasBound) : + μ.expectation (fun x => (∑ i, f i x) ^ 2) ≤ + (Fintype.card I : ℝ) * (1 + ((Fintype.card I : ℝ) - 1) * biasBound) := by + classical + have hentry : ∀ i j, μ.expectation (fun x => f i x * f j x) ≤ + biasBound + if i = j then 1 - biasBound else 0 := by + intro i j + by_cases hij : i = j + · subst j + have hdiag : μ.expectation (fun x => f i x * f i x) ≤ 1 := by + calc + _ ≤ μ.expectation (fun _ => 1) := expectation_mono μ (fun x => by + simpa only [pow_two] using hf i x) + _ = 1 := expectation_const μ 1 + simp only [ite_true] + linarith + · simpa only [ite_eq_right hij, add_zero] using hpair i j hij + have hrow : ∀ i, (∑ j, μ.expectation (fun x => f i x * f j x)) ≤ + (Fintype.card I : ℝ) * biasBound + (1 - biasBound) := by + intro i + calc + _ ≤ ∑ j, (biasBound + if i = j then 1 - biasBound else 0) := + Finset.sum_le_sum (fun j _ => hentry i j) + _ = _ := by simp [Finset.sum_add_distrib] + calc + _ = ∑ i, ∑ j, μ.expectation (fun x => f i x * f j x) := by + simp only [pow_two, Finset.sum_mul, Finset.mul_sum, expectation_sum] + exact Finset.sum_comm + _ ≤ ∑ _i : I, ((Fintype.card I : ℝ) * biasBound + (1 - biasBound)) := + Finset.sum_le_sum (fun i _ => hrow i) + _ = _ := by + simp only [Finset.sum_const, Finset.card_univ, nsmul_eq_mul] + ring + +theorem aligned_heavy_energy (μ : FiniteDistribution Ω) (f : I → Ω → ℝ) + (g : Ω → ℝ) (τ biasBound : ℝ) (hτ : 0 ≤ τ) + (hg : ∀ x, g x ^ 2 ≤ 1) (hf : ∀ i x, f i x ^ 2 ≤ 1) + (hpair : ∀ i j, i ≠ j → μ.expectation (fun x => f i x * f j x) ≤ biasBound) + (hheavy : ∀ i, τ ≤ μ.expectation (fun x => g x * f i x)) : + ((Fintype.card I : ℝ) * τ) ^ 2 ≤ + (Fintype.card I : ℝ) * (1 + ((Fintype.card I : ℝ) - 1) * biasBound) := by + have hlower : (Fintype.card I : ℝ) * τ ≤ + μ.expectation (fun x => g x * ∑ i, f i x) := by + calc + _ = ∑ _i : I, τ := by simp + _ ≤ ∑ i, μ.expectation (fun x => g x * f i x) := + Finset.sum_le_sum (fun i _ => hheavy i) + _ = _ := by simp only [Finset.mul_sum, expectation_sum] + calc + _ ≤ μ.expectation (fun x => g x * ∑ i, f i x) ^ 2 := + pow_le_pow_left₀ (mul_nonneg (Nat.cast_nonneg _) hτ) hlower 2 + _ ≤ μ.expectation (fun x => (∑ i, f i x) ^ 2) := + bounded_target_cauchySchwarz μ g _ hg + _ ≤ _ := gram_energy_bound μ f biasBound hf hpair + +def align (μ : FiniteDistribution Ω) (g : Ω → ℝ) (f : I → Ω → ℝ) + (i : I) (x : Ω) : ℝ := + if 0 ≤ μ.expectation (fun y => g y * f i y) then f i x else -f i x + +omit [Fintype I] in +theorem align_sq (μ : FiniteDistribution Ω) (g : Ω → ℝ) + (f : I → Ω → ℝ) (i : I) (x : Ω) : + align μ g f i x ^ 2 = f i x ^ 2 := by + unfold align + split <;> simp + +omit [Fintype I] in +theorem align_correlation (μ : FiniteDistribution Ω) (g : Ω → ℝ) + (f : I → Ω → ℝ) (i : I) : + μ.expectation (fun x => g x * align μ g f i x) = + |μ.expectation (fun x => g x * f i x)| := by + by_cases hi : 0 ≤ μ.expectation (fun x => g x * f i x) + · simp only [align, ite_eq_left hi, abs_of_nonneg hi] + · simp only [align, ite_eq_right hi, mul_neg, expectation_neg, + abs_of_neg (lt_of_not_ge hi)] + +omit [Fintype I] in +theorem align_pair_bound (μ : FiniteDistribution Ω) (g : Ω → ℝ) + (f : I → Ω → ℝ) (biasBound : ℝ) + (hpair : ∀ i j, i ≠ j → |μ.expectation (fun x => f i x * f j x)| ≤ biasBound) : + ∀ i j, i ≠ j → μ.expectation (fun x => align μ g f i x * align μ g f j x) ≤ biasBound := by + intro i j hij + have hpos := (abs_le.mp (hpair i j hij)).2 + have hneg : -μ.expectation (fun x => f i x * f j x) ≤ biasBound := by + linarith [(abs_le.mp (hpair i j hij)).1] + by_cases hi : 0 ≤ μ.expectation (fun x => g x * f i x) <;> + by_cases hj : 0 ≤ μ.expectation (fun x => g x * f j x) + · simpa [align, hi, hj] using hpos + · simpa [align, hi, hj, mul_neg, expectation_neg] using hneg + · simpa [align, hi, hj, neg_mul, expectation_neg] using hneg + · simpa [align, hi, hj] using hpos + +theorem heavy_list_card_le (μ : FiniteDistribution Ω) (f : I → Ω → ℝ) + (g : Ω → ℝ) (τ biasBound : ℝ) (hτ : 0 < τ) (hbiasBound : 0 ≤ biasBound) + (hsmall : biasBound ≤ τ ^ 2 / 2) + (hg : ∀ x, g x ^ 2 ≤ 1) (hf : ∀ i x, f i x ^ 2 ≤ 1) + (hpair : ∀ i j, i ≠ j → |μ.expectation (fun x => f i x * f j x)| ≤ biasBound) + (hheavy : ∀ i, τ ≤ |μ.expectation (fun x => g x * f i x)|) : + (Fintype.card I : ℝ) ≤ 2 / τ ^ 2 := by + have he := aligned_heavy_energy μ (align μ g f) g τ biasBound hτ.le hg + (fun i x => (align_sq μ g f i x).trans_le (hf i x)) + (align_pair_bound μ g f biasBound hpair) + (fun i => (hheavy i).trans_eq (align_correlation μ g f i).symm) + have hm : (0 : ℝ) ≤ Fintype.card I := Nat.cast_nonneg _ + have hτsq : 0 < τ ^ 2 := sq_pos_of_pos hτ + apply (le_div_iff₀ hτsq).2 + by_cases hmzero : (Fintype.card I : ℝ) = 0 + · simp [hmzero] + · have hmpos : (0 : ℝ) < Fintype.card I := lt_of_le_of_ne hm (Ne.symm hmzero) + have hscale := mul_le_mul_of_nonneg_left hsmall (sq_nonneg (Fintype.card I : ℝ)) + have hmulbiasBound := mul_nonneg hm hbiasBound + have hbound : (Fintype.card I : ℝ) * ((Fintype.card I : ℝ) * τ ^ 2) ≤ + (Fintype.card I : ℝ) * 2 := by nlinarith + exact le_of_mul_le_mul_left hbound hmpos + +def heavySet (μ : FiniteDistribution Ω) (f : I → Ω → ℝ) + (g : Ω → ℝ) (τ : ℝ) : Finset I := + Finset.univ.filter (fun i => τ ≤ |μ.expectation (fun x => g x * f i x)|) + +theorem heavySet_card_le (μ : FiniteDistribution Ω) (f : I → Ω → ℝ) + (g : Ω → ℝ) (τ biasBound : ℝ) (hτ : 0 < τ) (hbias : 0 ≤ biasBound) + (hsmall : biasBound ≤ τ ^ 2 / 2) + (hg : ∀ x, g x ^ 2 ≤ 1) (hf : ∀ i x, f i x ^ 2 ≤ 1) + (hpair : ∀ i j, i ≠ j → + |μ.expectation (fun x => f i x * f j x)| ≤ biasBound) : + ((heavySet μ f g τ).card : ℝ) ≤ 2 / τ ^ 2 := by + classical + let s := heavySet μ f g τ + have hs := heavy_list_card_le (I := ↥s) μ (fun i => f i.val) g τ biasBound + hτ hbias hsmall hg (fun i x => hf i.val x) + (fun i j hij => hpair i.val j.val (fun heq => hij (Subtype.ext heq))) + (fun i => (Finset.mem_filter.mp i.property).2) + simpa only [Fintype.card_coe] using hs + +end + +end PerfectCompleteness.SmallBias + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/RecursiveSpaces.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/RecursiveSpaces.lean new file mode 100644 index 0000000000000000000000000000000000000000..88931780fc6a3569c72db84a457684c999491970 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/RecursiveSpaces.lean @@ -0,0 +1,189 @@ +import Mathlib.Basic.Finite.Prod +import OAI.Computability.PerfectCompleteness.Foundations.PartitionsLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.RecursiveSpaces + +open PointwiseSpaces + +universe u v w + +def Slots (branch : Nat → Nat) : Nat → Type + | 0 => Unit + | n + 1 => Fin (branch n) × Slots branch n + +instance slotsFintype (branch : Nat → Nat) (n : Nat) : Fintype (Slots branch n) := by + induction n with + | zero => exact inferInstanceAs (Fintype Unit) + | succ n ih => + letI : Fintype (Slots branch n) := ih + exact inferInstanceAs (Fintype (Fin (branch n) × Slots branch n)) + +instance slotsDecidableEq (branch : Nat → Nat) (n : Nat) : + DecidableEq (Slots branch n) := by + induction n with + | zero => exact inferInstanceAs (DecidableEq Unit) + | succ n ih => + letI : DecidableEq (Slots branch n) := ih + exact inferInstanceAs (DecidableEq (Fin (branch n) × Slots branch n)) + +variable {branch : Nat → Nat} {n : Nat} + +abbrev Assignment (A : Slots branch n → Type u) := ∀ s, A s + +abbrev childFamily (A : Slots branch (n + 1) → Type u) (i : Fin (branch n)) : + Slots branch n → Type u := fun s => A (i, s) + +def childRestriction (A : Slots branch (n + 1) → Type u) (i : Fin (branch n)) : + Assignment A → Assignment (childFamily A i) := fun x s => x (i, s) + +theorem assignment_finite (A : Slots branch n → Type u) [∀ s, Finite (A s)] : + Finite (Assignment A) := by + infer_instance + +theorem childRestriction_surjective (A : Slots branch (n + 1) → Type u) + (hnonempty : ∀ s, Nonempty (A s)) (i : Fin (branch n)) : + Function.Surjective (childRestriction A i) := by + classical + intro y + let base : ∀ j : Fin (branch n), Assignment (childFamily A j) := + fun j s => Classical.choice (hnonempty (j, s)) + refine ⟨fun s => Function.update base i y s.1 s.2, ?_⟩ + funext s + simp only [childRestriction, Function.update_self] + +def space (𝕜 : Type w) [Field 𝕜] (branch : Nat → Nat) : + (n : Nat) → (A : Slots branch n → Type u) → + Submodule 𝕜 (Assignment A → 𝕜) + | 0, _ => ⊤ + | n + 1, A => childSpace (childRestriction A) + (fun i => space 𝕜 branch n (childFamily A i)) + +variable {𝕜 : Type w} [Field 𝕜] + +@[simp] theorem space_zero (A : Slots branch 0 → Type u) : + space 𝕜 branch 0 A = ⊤ := rfl + +theorem space_succ (A : Slots branch (n + 1) → Type u) : + space 𝕜 branch (n + 1) A = childSpace (childRestriction A) + (fun i => space 𝕜 branch n (childFamily A i)) := rfl + +theorem space_finite [Finite 𝕜] (A : Slots branch n → Type u) + [∀ s, Finite (A s)] : Finite (space 𝕜 branch n A) := by + infer_instance + +theorem one_mem_space (branch : Nat → Nat) : + ∀ (n : Nat) (A : Slots branch n → Type u), + (∀ k < n, 0 < branch k) → (1 : Assignment A → 𝕜) ∈ space 𝕜 branch n A := by + intro n + induction n with + | zero => + intro A _ + exact Submodule.mem_top + | succ n ih => + intro A hbranch + let i : Fin (branch n) := ⟨0, hbranch n (Nat.lt_succ_self n)⟩ + apply one_mem_childSpace_of_child (childRestriction A) + (fun j => space 𝕜 branch n (childFamily A j)) i + exact ih (childFamily A i) + (fun k hk => hbranch k (Nat.lt_trans hk (Nat.lt_succ_self n))) + +theorem space_le_squareSpace (A : Slots branch n → Type u) + (hbranch : ∀ k < n, 0 < branch k) : + space 𝕜 branch n A ≤ squareSpace (space 𝕜 branch n A) := + le_squareSpace _ (one_mem_space branch n A hbranch) + +theorem one_mem_space_square (A : Slots branch n → Type u) + (hbranch : ∀ k < n, 0 < branch k) : + (1 : Assignment A → 𝕜) ∈ squareSpace (space 𝕜 branch n A) := + one_mem_squareSpace _ (one_mem_space branch n A hbranch) + +theorem child_square_le_space (A : Slots branch (n + 1) → Type u) + (i : Fin (branch n)) : + (squareSpace (space 𝕜 branch n (childFamily A i))).map + (pullback 𝕜 (childRestriction A i)) ≤ space 𝕜 branch (n + 1) A := + child_square_le (childRestriction A) (fun j => space 𝕜 branch n (childFamily A j)) i + +theorem child_le_space (A : Slots branch (n + 1) → Type u) + (i : Fin (branch n)) (hbranch : ∀ k < n, 0 < branch k) : + (space 𝕜 branch n (childFamily A i)).map + (pullback 𝕜 (childRestriction A i)) ≤ space 𝕜 branch (n + 1) A := + child_le (childRestriction A) (fun j => space 𝕜 branch n (childFamily A j)) i + (one_mem_space branch n (childFamily A i) hbranch) + +theorem child_pullback_injective (A : Slots branch (n + 1) → Type u) + (hnonempty : ∀ s, Nonempty (A s)) (i : Fin (branch n)) : + Function.Injective (pullback 𝕜 (childRestriction A i)) := + pullback_injective _ (childRestriction_surjective A hnonempty i) + +def project {A : Slots branch n → Type u} {B : Slots branch n → Type v} + (e : ∀ s, A s → B s) : Assignment A → Assignment B := + fun x s => e s (x s) + +@[simp] theorem project_apply {A : Slots branch n → Type u} {B : Slots branch n → Type v} + (e : ∀ s, A s → B s) (x : Assignment A) (s : Slots branch n) : + project e x s = e s (x s) := rfl + +theorem project_surjective {A : Slots branch n → Type u} {B : Slots branch n → Type v} + (e : ∀ s, A s → B s) (he : ∀ s, Function.Surjective (e s)) : + Function.Surjective (project e) := + Function.Surjective.piMap he + +theorem project_child {A : Slots branch (n + 1) → Type u} + {B : Slots branch (n + 1) → Type v} (e : ∀ s, A s → B s) + (i : Fin (branch n)) (x : Assignment A) : + project (fun s => e (i, s)) (childRestriction A i x) = + childRestriction B i (project e x) := rfl + +theorem space_project_le (branch : Nat → Nat) : + ∀ (n : Nat) (A : Slots branch n → Type u) (B : Slots branch n → Type v) + (e : ∀ s, A s → B s), + (space 𝕜 branch n B).map (pullback 𝕜 (project e)) ≤ space 𝕜 branch n A := by + intro n + induction n with + | zero => + intro A B e + exact le_top + | succ n ih => + intro A B e + apply childSpace_pullback_le (project e) (childRestriction B) (childRestriction A) + (fun i => project (fun s => e (i, s))) + (fun i => space 𝕜 branch n (childFamily B i)) + (fun i => space 𝕜 branch n (childFamily A i)) + · intro i x + exact project_child e i x + · intro i + exact ih (childFamily A i) (childFamily B i) (fun s => e (i, s)) + +theorem squareSpace_project_le (A : Slots branch n → Type u) (B : Slots branch n → Type v) + (e : ∀ s, A s → B s) : + (squareSpace (space 𝕜 branch n B)).map (pullback 𝕜 (project e)) ≤ + squareSpace (space 𝕜 branch n A) := + squareSpace_pullback_le _ _ _ (space_project_le branch n A B e) + +def spacePullback (A : Slots branch n → Type u) (B : Slots branch n → Type v) + (e : ∀ s, A s → B s) : space 𝕜 branch n B →ₗ[𝕜] space 𝕜 branch n A where + toFun f := ⟨pullback 𝕜 (project e) f, + space_project_le branch n A B e (Submodule.mem_map_of_mem f.property)⟩ + map_add' _ _ := Subtype.ext rfl + map_smul' _ _ := Subtype.ext rfl + +@[simp] theorem spacePullback_apply (A : Slots branch n → Type u) (B : Slots branch n → Type v) + (e : ∀ s, A s → B s) (f : space 𝕜 branch n B) (x : Assignment A) : + (spacePullback A B e f).val x = f.val (project e x) := rfl + +theorem spacePullback_injective (A : Slots branch n → Type u) (B : Slots branch n → Type v) + (e : ∀ s, A s → B s) (he : ∀ s, Function.Surjective (e s)) : + Function.Injective (spacePullback (𝕜 := 𝕜) A B e) := by + intro f g h + apply Subtype.ext + exact pullback_injective (project e) (project_surjective e he) (congrArg Subtype.val h) + +end PerfectCompleteness.RecursiveSpaces + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/ReducedDomains.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/ReducedDomains.lean new file mode 100644 index 0000000000000000000000000000000000000000..149bda58d0ea3da4efab70436b80152939922d45 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/ReducedDomains.lean @@ -0,0 +1,133 @@ +import OAI.Computability.PerfectCompleteness.Foundations.ClauseSupportLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.ReducedDomains + +open ClauseSupport + +variable {I C Y : Type*} + +def Allowed : SlotKey → ReducedValue → Prop + | .dropped, .dropped => True + | .bit _, .bit _ => True + | .full _ signs, .full value => value ∈ SourceClause.satisfyingTriples signs + | _, _ => False + +theorem allowed_nonempty (key : SlotKey) : ∃ value, Allowed key value := by + cases key with + | dropped => exact ⟨.dropped, trivial⟩ + | bit variableID => exact ⟨.bit false, trivial⟩ + | full occurrence signs => + obtain ⟨u, _⟩ := ClauseSupport.coordinate_surjective signs 0 false + exact ⟨.full u.val, u.property⟩ + +theorem localReduction_range_iff (s : MixedSupport.Slot) + (f : C → s.Domain → Y) (value : ReducedValue) : + (∃ u : s.Domain, MixedSupport.localReduction s f u = value) ↔ + Allowed (MixedSupport.localKey s f) value := by + classical + cases s with + | clause occurrence variableIDs signs => + change (∃ u : Answer signs, clauseReduction f u = value) ↔ + Allowed (clauseKey occurrence variableIDs f) value + cases hm : clauseMode f with + | dropped => + cases value <;> + simp [clauseReduction, clauseKey, hm, reduceByMode, Allowed] + | bit position => + cases value with + | dropped => + simp [clauseReduction, clauseKey, hm, reduceByMode, Allowed] + | bit b => + simp only [clauseReduction, clauseKey, hm, reduceByMode, Allowed, + ReducedValue.bit.injEq, iff_true] + exact ClauseSupport.coordinate_surjective signs position b + | full triple => + simp [clauseReduction, clauseKey, hm, reduceByMode, Allowed] + | full => + cases value with + | dropped => + simp [clauseReduction, clauseKey, hm, reduceByMode, Allowed] + | bit b => + simp [clauseReduction, clauseKey, hm, reduceByMode, Allowed] + | full triple => + simp only [clauseReduction, clauseKey, hm, reduceByMode, Allowed, + ReducedValue.full.injEq] + constructor + · rintro ⟨u, rfl⟩ + exact u.property + · intro htriple + exact ⟨⟨triple, htriple⟩, rfl⟩ + | bit variableID => + change C → Bool → Y at f + change (∃ b : Bool, bitReduction f b = value) ↔ + Allowed (bitKey variableID f) value + by_cases hu : Unused f + · cases value <;> simp [bitReduction, bitKey, hu, Allowed] + · cases value <;> simp [bitReduction, bitKey, hu, Allowed] + +theorem localReduction_allowed (s : MixedSupport.Slot) + (f : C → s.Domain → Y) (u : s.Domain) : + Allowed (MixedSupport.localKey s f) (MixedSupport.localReduction s f u) := + (localReduction_range_iff s f _).mp ⟨u, rfl⟩ + +def legalAssignments (keys : I → SlotKey) : Set (I → ReducedValue) := + {values | ∀ i, Allowed (keys i) (values i)} + +theorem mem_legalAssignments (keys : I → SlotKey) (values : I → ReducedValue) : + values ∈ legalAssignments keys ↔ ∀ i, Allowed (keys i) (values i) := Iff.rfl + +theorem legalAssignments_nonempty (keys : I → SlotKey) : + (legalAssignments keys).Nonempty := by + classical + choose values hvalues using fun i => allowed_nonempty (keys i) + exact ⟨values, hvalues⟩ + +theorem range_reduction [DecidableEq I] (slots : I → MixedSupport.Slot) + (f : MixedSupport.Assignment slots → Y) : + Set.range (MixedSupport.reduction slots f) = + legalAssignments (MixedSupport.keyFields slots f) := by + classical + ext values + change (∃ x, MixedSupport.reduction slots f x = values) ↔ + ∀ i, Allowed (MixedSupport.keyFields slots f i) (values i) + constructor + · rintro ⟨x, rfl⟩ i + exact localReduction_allowed (slots i) (MixedSupport.sectionFunction slots f i) (x i) + · intro hvalues + have preimages : ∀ i, ∃ u : (slots i).Domain, + MixedSupport.localReduction (slots i) (MixedSupport.sectionFunction slots f i) u = + values i := by + intro i + exact (localReduction_range_iff (slots i) + (MixedSupport.sectionFunction slots f i) (values i)).mpr (hvalues i) + choose x hx using preimages + refine ⟨x, ?_⟩ + funext i + exact hx i + +private def valueCode : ReducedValue → Option (Bool ⊕ SourceClause.Triple) + | .dropped => none + | .bit b => some (.inl b) + | .full triple => some (.inr triple) + +private theorem valueCode_injective : Function.Injective valueCode := by + intro u v h + cases u <;> cases v <;> simp_all [valueCode] + +theorem reducedValue_finite : Finite ReducedValue := + Finite.of_injective valueCode valueCode_injective + +theorem legalAssignments_finite [Finite I] (keys : I → SlotKey) : + (legalAssignments keys).Finite := by + let : Finite ReducedValue := reducedValue_finite + exact Set.toFinite _ + +end PerfectCompleteness.ReducedDomains + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/RetainedKeyTransport.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/RetainedKeyTransport.lean new file mode 100644 index 0000000000000000000000000000000000000000..7d4cbea4f817dee9565a9ebe3826e1c5b99dcd5e --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/RetainedKeyTransport.lean @@ -0,0 +1,149 @@ +import OAI.Computability.PerfectCompleteness.Repetition.CleanCountingLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.RetainedKeyTransport + +open MixedSupport CanonicalKeys CleanKeyErasure CleanKeyFactorization +open scoped Classical + +noncomputable section + +variable {n : Nat} {Y : Type*} + +theorem retainedSlots_eq (slots target : Fin n → Slot) (keep : Fin n → Prop) + (hs : ∀ i, keep i → slots i = target i) : + retainedSlots slots keep = retainedSlots target keep := by + funext i + exact hs i.val i.property + +def retainedAssignmentEquiv (slots target : Fin n → Slot) (keep : Fin n → Prop) + (hs : ∀ i, keep i → slots i = target i) : + Assignment (retainedSlots slots keep) ≃ Assignment (retainedSlots target keep) := + Equiv.cast (congrArg Assignment (retainedSlots_eq slots target keep hs)) + +private theorem assignment_cast_apply {I : Type*} {a b : I → Slot} (h : a = b) + (x : Assignment a) (i : I) : + (Equiv.cast (congrArg Assignment h) x) i = + cast (congrArg Slot.Domain (congrFun h i)) (x i) := by + cases h + rfl + +theorem retainedAssignmentEquiv_apply (slots target : Fin n → Slot) (keep : Fin n → Prop) + (hs : ∀ i, keep i → slots i = target i) + (x : Assignment (retainedSlots slots keep)) (i : {i : Fin n // keep i}) : + retainedAssignmentEquiv slots target keep hs x i = + cast (congrArg Slot.Domain (hs i.val i.property)) (x i) := + assignment_cast_apply (retainedSlots_eq slots target keep hs) x i + +theorem retainedAssignmentEquiv_agree_heq + (slots target : Fin n → Slot) (keep : Fin n → Prop) + (hs : ∀ i, keep i → slots i = target i) + (x : Assignment slots) (y : Assignment target) + (hret : retainedAssignmentEquiv slots target keep hs (retain slots keep x) = + retain target keep y) (i : Fin n) (hi : keep i) : HEq (x i) (y i) := by + have hcoord := congrFun hret ⟨i, hi⟩ + rw [retainedAssignmentEquiv_apply] at hcoord + exact (cast_heq (congrArg Slot.Domain (hs i hi)) (x i)).symm.trans + (heq_of_eq hcoord) + +theorem exists_retained_factor + (slots target : Fin n → Slot) (keep : Fin n → Prop) + (hs : ∀ i, keep i → slots i = target i) + (f : Assignment slots → Y) (g : Assignment target → Y) + (hagree : ∀ x y, + retainedAssignmentEquiv slots target keep hs (retain slots keep x) = + retain target keep y → f x = g y) : + ∃ h : Assignment (retainedSlots target keep) → Y, + f = (h ∘ retainedAssignmentEquiv slots target keep hs) ∘ retain slots keep ∧ + g = h ∘ retain target keep := by + refine ⟨fun u => g (fill target keep u), ?_, ?_⟩ + · funext x + exact hagree x + (fill target keep (retainedAssignmentEquiv slots target keep hs (retain slots keep x))) + (retain_fill target keep _).symm + · funext y + let x := fill slots keep + ((retainedAssignmentEquiv slots target keep hs).symm (retain target keep y)) + have hx : retainedAssignmentEquiv slots target keep hs (retain slots keep x) = + retain target keep y := by + dsimp only [x] + rw [retain_fill, Equiv.apply_symm_apply] + exact (hagree x y hx).symm.trans + (hagree x (fill target keep (retain target keep y)) + (hx.trans (retain_fill target keep _).symm)) + +private theorem retainedKey_cast (side : Side) (keep : Fin n → Prop) + {a b : {i : Fin n // keep i} → Slot} (h : a = b) (g : Assignment b → Y) : + retainedKey side keep a (g ∘ Equiv.cast (congrArg Assignment h)) = + retainedKey side keep b g := by + cases h + rfl + +private theorem retainedResponse_cast (labeling : KeyStrategy.Strategy n) + (side : Side) (keep : Fin n → Prop) + {a b : {i : Fin n // keep i} → Slot} (h : a = b) (g : Assignment b → Y) : + retainedResponse labeling side keep a (g ∘ Equiv.cast (congrArg Assignment h)) = + retainedResponse labeling side keep b g := by + cases h + rfl + +theorem key_eq (side : Side) (slots target : Fin n → Slot) (keep : Fin n → Prop) + (hs : ∀ i, keep i → slots i = target i) + (f : Assignment slots → Y) (g : Assignment target → Y) + (hagree : ∀ x y, + retainedAssignmentEquiv slots target keep hs (retain slots keep x) = + retain target keep y → f x = g y) : + CanonicalKeys.key side slots f = CanonicalKeys.key side target g := by + obtain ⟨h, hf, hg⟩ := exists_retained_factor slots target keep hs f g hagree + calc + _ = retainedKey side keep (retainedSlots slots keep) + (h ∘ retainedAssignmentEquiv slots target keep hs) := by + rw [hf] + exact key_factor side slots keep _ + _ = retainedKey side keep (retainedSlots target keep) h := + retainedKey_cast side keep (retainedSlots_eq slots target keep hs) h + _ = _ := by + rw [hg] + exact (key_factor side target keep h).symm + +theorem label_val_eq (labeling : KeyStrategy.Strategy n) (side : Side) + (slots target : Fin n → Slot) (keep : Fin n → Prop) + (hs : ∀ i, keep i → slots i = target i) + (f : Assignment slots → Y) (g : Assignment target → Y) + (hagree : ∀ x y, + retainedAssignmentEquiv slots target keep hs (retain slots keep x) = + retain target keep y → f x = g y) : + (KeyStrategy.label labeling side slots f).val = + (KeyStrategy.label labeling side target g).val := + KeyStrategy.label_val_eq_of_key_eq labeling side side slots target f g + (key_eq side slots target keep hs f g hagree) + +theorem response_eq (labeling : KeyStrategy.Strategy n) (side : Side) + (slots target : Fin n → Slot) (keep : Fin n → Prop) + (hs : ∀ i, keep i → slots i = target i) + (f : Assignment slots → Y) (g : Assignment target → Y) + (hagree : ∀ x y, + retainedAssignmentEquiv slots target keep hs (retain slots keep x) = + retain target keep y → f x = g y) : + KeyStrategy.response labeling side slots f = KeyStrategy.response labeling side target g := by + obtain ⟨h, hf, hg⟩ := exists_retained_factor slots target keep hs f g hagree + calc + _ = retainedResponse labeling side keep (retainedSlots slots keep) + (h ∘ retainedAssignmentEquiv slots target keep hs) := by + rw [hf] + exact response_factor labeling side slots keep _ + _ = retainedResponse labeling side keep (retainedSlots target keep) h := + retainedResponse_cast labeling side keep (retainedSlots_eq slots target keep hs) h + _ = _ := by + rw [hg] + exact (response_factor labeling side target keep h).symm + +end +end PerfectCompleteness.RetainedKeyTransport + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/SignedCostEnvelope.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/SignedCostEnvelope.lean new file mode 100644 index 0000000000000000000000000000000000000000..a48fda98706212c25a090281bf84b0c3fc8b3cc1 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/SignedCostEnvelope.lean @@ -0,0 +1,169 @@ +import Mathlib.Tactic.Ring +import OAI.Computability.PerfectCompleteness.Foundations.CanonicalDictionaryNames + +namespace OAI + +section + +namespace PerfectCompleteness.SignedCostEnvelope + +def payloadCoeff (w : Nat) : Nat := + (1 + 2 ^ (11 ^ w) + 6 * w) * (w + 3) + 1 + +def streamCoeff (w d : Nat) : Nat := (2 * payloadCoeff w + 2) * d + +def endpointBound (w T count : Nat) : Nat := + 8 * w * (T + 1) + 4 * w + 2 + + 2 * (CanonicalVertexNames.payloadBound w T + 1) + + 3 * (CanonicalDictionaryNames.streamBound w T count) ^ 2 + + 16 * CanonicalDictionaryNames.streamBound w T count + 12 + +def endpointCoeff (w d : Nat) : Nat := + 12 * w + 2 * payloadCoeff w + 3 * (streamCoeff w d) ^ 2 + + 16 * streamCoeff w d + 16 + +def bodyBound (w d T : Nat) : Nat := + 72 * w * (T + 1) + d * (2 * endpointBound w T (d * (T + 1) ^ w) + 4) + + 7 * w * (T + 2) + 2 + +def bodyCoeff (w d : Nat) : Nat := 86 * w + d * (2 * endpointCoeff w d + 4) + 2 + +def degree (w : Nat) : Nat := 2 * w + 2 + +private theorem le_scaled (a : Nat) {b : Nat} (hb : 1 ≤ b) : a ≤ a * b := by + simpa only [Nat.mul_one] using Nat.mul_le_mul_left a hb + +private theorem one_le_envelope (w T : Nat) : 1 ≤ (T + 1) ^ degree w := + Nat.one_le_pow (degree w) (T + 1) (Nat.zero_lt_succ T) + +private theorem input_le_envelope (w T : Nat) : T + 1 ≤ (T + 1) ^ degree w := + Nat.le_pow (show 0 < degree w by unfold degree; omega) + +private theorem streamPower_le_envelope (w T : Nat) : + (T + 1) ^ (w + 1) ≤ (T + 1) ^ degree w := + Nat.pow_le_pow_right (Nat.zero_lt_succ T) (by unfold degree; omega) + +theorem payloadBound_le (w T : Nat) : + CanonicalVertexNames.payloadBound w T ≤ payloadCoeff w * (T + 1) := by + have hone : 1 ≤ T + 1 := Nat.succ_le_succ (Nat.zero_le T) + have hmax : max w (max T 2) + 1 ≤ w + (T + 1) + 2 := by omega + have hfactor : max w (max T 2) + 1 ≤ (w + 3) * (T + 1) := by + calc + max w (max T 2) + 1 ≤ w + (T + 1) + 2 := hmax + _ ≤ w * (T + 1) + (T + 1) + 2 * (T + 1) := + Nat.add_le_add (Nat.add_le_add_right (le_scaled w hone) (T + 1)) + (le_scaled 2 hone) + _ = (w + 3) * (T + 1) := by ring + calc + CanonicalVertexNames.payloadBound w T = + (1 + 2 ^ (11 ^ w) + 6 * w) * (max w (max T 2) + 1) + 1 := rfl + _ ≤ (1 + 2 ^ (11 ^ w) + 6 * w) * ((w + 3) * (T + 1)) + (T + 1) := + Nat.add_le_add (Nat.mul_le_mul_left _ hfactor) hone + _ = payloadCoeff w * (T + 1) := by unfold payloadCoeff; ring + +theorem streamBound_le (w d T : Nat) : + CanonicalDictionaryNames.streamBound w T (d * (T + 1) ^ w) ≤ + streamCoeff w d * (T + 1) ^ (w + 1) := by + have hone : 1 ≤ T + 1 := Nat.succ_le_succ (Nat.zero_le T) + have hfactor : 2 * CanonicalVertexNames.payloadBound w T + 2 ≤ + (2 * payloadCoeff w + 2) * (T + 1) := by + calc + 2 * CanonicalVertexNames.payloadBound w T + 2 ≤ + 2 * (payloadCoeff w * (T + 1)) + 2 * (T + 1) := + Nat.add_le_add (Nat.mul_le_mul_left 2 (payloadBound_le w T)) (le_scaled 2 hone) + _ = (2 * payloadCoeff w + 2) * (T + 1) := by ring + calc + CanonicalDictionaryNames.streamBound w T (d * (T + 1) ^ w) = + (2 * CanonicalVertexNames.payloadBound w T + 2) * (d * (T + 1) ^ w) := rfl + _ ≤ ((2 * payloadCoeff w + 2) * (T + 1)) * (d * (T + 1) ^ w) := + Nat.mul_le_mul_right _ hfactor + _ = streamCoeff w d * (T + 1) ^ (w + 1) := by + rw [Nat.pow_succ] + unfold streamCoeff + ring + +theorem endpointBound_le (w d T : Nat) : + endpointBound w T (d * (T + 1) ^ w) ≤ + endpointCoeff w d * (T + 1) ^ degree w := by + have hone := one_le_envelope w T + have hinput := input_le_envelope w T + have hpayload : CanonicalVertexNames.payloadBound w T ≤ + payloadCoeff w * (T + 1) ^ degree w := + (payloadBound_le w T).trans (Nat.mul_le_mul_left _ hinput) + have hstream := streamBound_le w d T + have hstreamLinear : CanonicalDictionaryNames.streamBound w T (d * (T + 1) ^ w) ≤ + streamCoeff w d * (T + 1) ^ degree w := + hstream.trans (Nat.mul_le_mul_left _ (streamPower_le_envelope w T)) + have hsquare : (CanonicalDictionaryNames.streamBound w T (d * (T + 1) ^ w)) ^ 2 ≤ + (streamCoeff w d) ^ 2 * (T + 1) ^ degree w := by + calc + (CanonicalDictionaryNames.streamBound w T (d * (T + 1) ^ w)) ^ 2 ≤ + (streamCoeff w d * (T + 1) ^ (w + 1)) ^ 2 := + Nat.pow_le_pow_left hstream 2 + _ = (streamCoeff w d) ^ 2 * (T + 1) ^ degree w := by + rw [Nat.mul_pow, ← Nat.pow_mul] + have hexp : (w + 1) * 2 = degree w := by unfold degree; omega + rw [hexp] + have hstart : 8 * w * (T + 1) + 4 * w + 2 ≤ + (12 * w + 2) * (T + 1) ^ degree w := by + calc + 8 * w * (T + 1) + 4 * w + 2 ≤ + (8 * w) * (T + 1) ^ degree w + (4 * w) * (T + 1) ^ degree w + + 2 * (T + 1) ^ degree w := + Nat.add_le_add + (Nat.add_le_add (Nat.mul_le_mul_left (8 * w) hinput) (le_scaled (4 * w) hone)) + (le_scaled 2 hone) + _ = (12 * w + 2) * (T + 1) ^ degree w := by ring + have hpayloadTerm : 2 * (CanonicalVertexNames.payloadBound w T + 1) ≤ + (2 * payloadCoeff w + 2) * (T + 1) ^ degree w := by + calc + 2 * (CanonicalVertexNames.payloadBound w T + 1) ≤ + 2 * (payloadCoeff w * (T + 1) ^ degree w + (T + 1) ^ degree w) := + Nat.mul_le_mul_left 2 (Nat.add_le_add hpayload hone) + _ = (2 * payloadCoeff w + 2) * (T + 1) ^ degree w := by ring + calc + endpointBound w T (d * (T + 1) ^ w) ≤ + (12 * w + 2) * (T + 1) ^ degree w + + (2 * payloadCoeff w + 2) * (T + 1) ^ degree w + + 3 * ((streamCoeff w d) ^ 2 * (T + 1) ^ degree w) + + 16 * (streamCoeff w d * (T + 1) ^ degree w) + 12 * (T + 1) ^ degree w := + Nat.add_le_add + (Nat.add_le_add + (Nat.add_le_add (Nat.add_le_add hstart hpayloadTerm) (Nat.mul_le_mul_left 3 hsquare)) + (Nat.mul_le_mul_left 16 hstreamLinear)) + (le_scaled 12 hone) + _ = endpointCoeff w d * (T + 1) ^ degree w := by unfold endpointCoeff; ring + +theorem bodyBound_le (w d T : Nat) : + bodyBound w d T ≤ bodyCoeff w d * (T + 1) ^ degree w := by + have hone := one_le_envelope w T + have hinput := input_le_envelope w T + have hendpoint := endpointBound_le w d T + have hbody : d * (2 * endpointBound w T (d * (T + 1) ^ w) + 4) ≤ + (d * (2 * endpointCoeff w d + 4)) * (T + 1) ^ degree w := by + calc + d * (2 * endpointBound w T (d * (T + 1) ^ w) + 4) ≤ + d * (2 * (endpointCoeff w d * (T + 1) ^ degree w) + 4 * (T + 1) ^ degree w) := + Nat.mul_le_mul_left d + (Nat.add_le_add (Nat.mul_le_mul_left 2 hendpoint) (le_scaled 4 hone)) + _ = (d * (2 * endpointCoeff w d + 4)) * (T + 1) ^ degree w := by ring + have hcleanup : 7 * w * (T + 2) ≤ (14 * w) * (T + 1) ^ degree w := by + calc + 7 * w * (T + 2) = (7 * w) * ((T + 1) + 1) := rfl + _ ≤ (7 * w) * ((T + 1) ^ degree w + (T + 1) ^ degree w) := + Nat.mul_le_mul_left (7 * w) (Nat.add_le_add hinput hone) + _ = (14 * w) * (T + 1) ^ degree w := by ring + calc + bodyBound w d T ≤ (72 * w) * (T + 1) ^ degree w + + (d * (2 * endpointCoeff w d + 4)) * (T + 1) ^ degree w + + (14 * w) * (T + 1) ^ degree w + 2 * (T + 1) ^ degree w := + Nat.add_le_add + (Nat.add_le_add (Nat.add_le_add (Nat.mul_le_mul_left (72 * w) hinput) hbody) hcleanup) + (le_scaled 2 hone) + _ = bodyCoeff w d * (T + 1) ^ degree w := by unfold bodyCoeff; ring + +end PerfectCompleteness.SignedCostEnvelope + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/SignedScheduleIndex.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/SignedScheduleIndex.lean new file mode 100644 index 0000000000000000000000000000000000000000..1ea61f6517d16c5d0627d60d3adc82560baee06d --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/SignedScheduleIndex.lean @@ -0,0 +1,132 @@ +import Mathlib.Data.List.OfFn +import OAI.Computability.PerfectCompleteness.Reduction.SignedCompletionSchedule + +namespace OAI + +section + +namespace PerfectCompleteness.SignedScheduleIndex + +open MetadataFreeSampler SignedCompletionSchedule +open Turing UniqueGamesTheorem.Foundations.Complexity +open scoped Classical + +noncomputable section + +variable {branch : Nat → Nat} {n t q : Nat} {rows repeats : Nat → Nat} + (hq : 0 < q) + (large : CanonicalKeyEncoding.partitionWidth (TreeCanonical.locationCount branch n t) ≤ q) + (hn : 0 < n) (hbranch : ∀ k < n, 0 < branch k) + (hrows : ∀ k, 0 < rows (k + 1)) + +local notation "D" => SignedMultiplicity.denominator branch n t rows repeats hn hbranch hrows q + +def atIndex (signs : SignTuple branch n t) (i : Fin D) : Descriptor (rows := rows) (repeats := repeats) hq large := + ⟨signs, (schedule (rows := rows) (repeats := repeats) hq large hn hbranch hrows signs).get + (Fin.cast (schedule_length (rows := rows) (repeats := repeats) hq large hn hbranch hrows signs).symm i)⟩ + +@[simp] theorem atIndex_signs (signs : SignTuple branch n t) (i : Fin D) : + (atIndex hq large hn hbranch hrows signs i).1 = signs := rfl + +private theorem ofFn_get_cast {β : Type*} {d : Nat} (xs : List β) (h : xs.length = d) : + List.ofFn (fun i : Fin d => xs.get (Fin.cast h.symm i)) = xs := by + have roundtrip := (List.ofFn_congr h xs.get).symm + rw [List.ofFn_get] at roundtrip + exact roundtrip + +theorem ofFn_atIndex (signs : SignTuple branch n t) : + List.ofFn (atIndex (repeats := repeats) hq large hn hbranch hrows signs) = + (schedule (rows := rows) (repeats := repeats) hq large hn hbranch hrows signs).map (Sigma.mk signs) := by + unfold atIndex + rw [List.ofFn_comp', ofFn_get_cast + (schedule (rows := rows) (repeats := repeats) hq large hn hbranch hrows signs) + (schedule_length (rows := rows) (repeats := repeats) hq large hn hbranch hrows signs)] + +theorem observations_eq {β : Type*} (signs : SignTuple branch n t) + (observe : Descriptor (rows := rows) (repeats := repeats) hq large → β) : + List.ofFn (fun i : Fin D => observe (atIndex hq large hn hbranch hrows signs i)) = + (schedule (rows := rows) (repeats := repeats) hq large hn hbranch hrows signs).map (fun e => observe ⟨signs, e⟩) := by + calc + _ = (List.ofFn (atIndex hq large hn hbranch hrows signs)).map observe := + List.ofFn_comp' _ _ + _ = _ := by simp only [ofFn_atIndex, List.map_map, Function.comp_def] + +theorem tables_eq (signs : SignTuple branch n t) : + List.ofFn (fun i : Fin D => + descriptorTable hq large (atIndex hq large hn hbranch hrows signs i)) = + (schedule (rows := rows) (repeats := repeats) hq large hn hbranch hrows signs).map + (fun e => LocalCompletionFamily.table (result (rows := rows) (repeats := repeats) hq large signs e.1) e.2) := + observations_eq hq large hn hbranch hrows signs (descriptorTable hq large) + +theorem acceptance_values_eq (signs : SignTuple branch n t) + (accepts : Descriptor (rows := rows) (repeats := repeats) hq large → Bool) : + List.ofFn (fun i : Fin D => accepts (atIndex hq large hn hbranch hrows signs i)) = + (schedule (rows := rows) (repeats := repeats) hq large hn hbranch hrows signs).map (fun e => accepts ⟨signs, e⟩) := + observations_eq hq large hn hbranch hrows signs accepts + +theorem acceptance_list_eq (signs : SignTuple branch n t) + (accepts : Descriptor (rows := rows) (repeats := repeats) hq large → Bool) : + (List.ofFn (atIndex (repeats := repeats) hq large hn hbranch hrows signs)).filter accepts = + ((schedule (rows := rows) (repeats := repeats) hq large hn hbranch hrows signs).filter + (fun e => accepts ⟨signs, e⟩)).map (Sigma.mk signs) := by + simp only [ofFn_atIndex, List.filter_map, Function.comp_def] + +theorem acceptance (signs : SignTuple branch n t) + (accepts : Descriptor (rows := rows) (repeats := repeats) hq large → Bool) : + (((List.ofFn (atIndex hq large hn hbranch hrows signs)).filter accepts).length : ℝ) / + D = (law (rows := rows) (repeats := repeats) hq large hn hbranch hrows signs).probability (fun e => accepts ⟨signs, e⟩) := by + have h := schedule_acceptance (rows := rows) (repeats := repeats) hq large hn hbranch hrows signs (fun e => accepts ⟨signs, e⟩) + rw [schedule_length] at h + simpa only [acceptance_list_eq, List.length_map] using h + +def instruction {K Λ σ : Type} [Finite σ] + (selectSigns : σ → SignTuple branch n t) (save : σ → Descriptor (rows := rows) (repeats := repeats) hq large → σ) + (i : Fin D) (exit : Λ) : TM2.Stmt (fun _ : K => Bool) Λ σ := + .load (fun state => save state (atIndex hq large hn hbranch hrows (selectSigns state) i)) + (.goto (fun _ => exit)) + +theorem instruction_pushBound {K Λ σ : Type} [Finite σ] + (selectSigns : σ → SignTuple branch n t) (save : σ → Descriptor (rows := rows) (repeats := repeats) hq large → σ) + (i : Fin D) (exit : Λ) : + Runtime.statementPushBound + (instruction (K := K) hq large hn hbranch hrows selectSigns save i exit) = 0 := rfl + +theorem instruction_trace {K Λ σ : Type} [DecidableEq K] [Finite σ] + (selectSigns : σ → SignTuple branch n t) (save : σ → Descriptor (rows := rows) (repeats := repeats) hq large → σ) + (i : Fin D) (exit : Λ) (state : σ) (tapes : K → List Bool) : + TM2.stepAux (instruction hq large hn hbranch hrows selectSigns save i exit) state tapes = + ⟨some exit, save state (atIndex hq large hn hbranch hrows (selectSigns state) i), tapes⟩ := + rfl + +theorem step {K Λ σ : Type} [DecidableEq K] [Finite σ] + (selectSigns : σ → SignTuple branch n t) (save : σ → Descriptor (rows := rows) (repeats := repeats) hq large → σ) + (i : Fin D) (exit : Λ) (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ σ) + (entry : Λ) + (atEntry : program entry = instruction hq large hn hbranch hrows selectSigns save i exit) + (state : σ) (tapes : K → List Bool) : + TM2.step program ⟨some entry, state, tapes⟩ = + some ⟨some exit, save state (atIndex hq large hn hbranch hrows (selectSigns state) i), + tapes⟩ := by + change some (TM2.stepAux (program entry) state tapes) = _ + rw [atEntry, instruction_trace] + +def inTime {K Λ σ : Type} [DecidableEq K] [Finite σ] + (selectSigns : σ → SignTuple branch n t) (save : σ → Descriptor (rows := rows) (repeats := repeats) hq large → σ) + (i : Fin D) (exit : Λ) (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ σ) + (entry : Λ) + (atEntry : program entry = instruction hq large hn hbranch hrows selectSigns save i exit) + (state : σ) (tapes : K → List Bool) : + StateTransition.EvalsToInTime (TM2.step program) ⟨some entry, state, tapes⟩ + (some ⟨some exit, + save state (atIndex hq large hn hbranch hrows (selectSigns state) i), tapes⟩) 1 where + steps := 1 + evals_in_steps := step hq large hn hbranch hrows selectSigns save i exit + program entry atEntry state tapes + steps_le_m := Nat.le_refl 1 + +end +end PerfectCompleteness.SignedScheduleIndex + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/SignedTupleLayout.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/SignedTupleLayout.lean new file mode 100644 index 0000000000000000000000000000000000000000..e2e97f633e594a4c528ce4ac8de0edc3f0e98844 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/SignedTupleLayout.lean @@ -0,0 +1,126 @@ +import OAI.Computability.PerfectCompleteness.Foundations.SourceTupleResetPlacementLemmas +import OAI.Computability.PerfectCompleteness.Machines.CompletedEdgeMachine + +namespace OAI + +section + +namespace PerfectCompleteness.SignedTupleLayout + +open UniqueGamesTheorem.Foundations Complexity Target +open scoped Classical + +noncomputable section + +inductive Tape (width : Nat) (Extra : Type) where + | source (tape : SourceTupleData.Tape width) + | current (position : Fin width) + | remaining (position : Fin width) + | encodedVariable (position : Fin width) (slot : Fin 3) + | adapterScratch + | edgeWork (slot : Fin 10) + | edgeCount + | extra (value : Extra) + deriving DecidableEq, Fintype + +variable {width : Nat} {Extra U Desc : Type} + +abbrev State (width : Nat) (U Desc : Type) := SourceTupleBodyPlacement.State width U Desc + +def frame (Desc : Type) : SourceTupleBodyPlacement.Frame Desc := ((none, (false, none)), none) + +def initialSource (ambient : U) : SourceTupleMachine.State width U := + SourceTupleMachine.state ambient + (SourceTupleMachine.initial (fun _ => CanonicalKeyShape.Shape.bit) (fun _ => false)) + +def clean (ambient : U) : State width U Desc := + SourceTupleBodyPlacement.registers (initialSource ambient, frame Desc) + +def preparedSource (formula : Formula) (indices : Fin width → Fin formula.clauses.length) + (ambient : U) : SourceTupleMachine.State width U := + SourceClauseReaderMachine.clean + (ambient, fun position => SourceClauseReaderMachine.clauseShape + (SourceTupleData.selectedClause formula indices position)) + (SourceTupleMachine.result formula indices (List.finRange width) + (SourceTupleMachine.initial (fun _ => CanonicalKeyShape.Shape.bit) (fun _ => false))).signs + +def preparedState (formula : Formula) (indices : Fin width → Fin formula.clauses.length) + (ambient : U) : State width U Desc := + SourceTupleBodyPlacement.registers (preparedSource formula indices ambient, frame Desc) + +def sourceView : Tape width Extra → Option (SourceTupleData.Tape width) + | .source tape => some tape + | _ => none + +@[simp] theorem sourceView_left (tape : SourceTupleData.Tape width) : + sourceView (Tape.source (Extra := Extra) tape) = some tape := rfl + +theorem sourceView_right (tape : Tape width Extra) (source : SourceTupleData.Tape width) + (h : sourceView tape = some source) : Tape.source source = tape := by + cases tape <;> simp_all [sourceView] + +def metadata (position : Fin width) : Fin 6 → Tape width Extra + | 0 => .current position + | 1 => .encodedVariable position 0 + | 2 => .encodedVariable position 1 + | 3 => .encodedVariable position 2 + | 4 => .edgeWork 5 + | 5 => .edgeWork 9 + +theorem metadata_injective (position : Fin width) : + Function.Injective (metadata (Extra := Extra) position) := by + intro i j h + fin_cases i <;> fin_cases j <;> simp [metadata] at h ⊢ + +def ids (formula : Formula) (indices : Fin width → Fin formula.clauses.length) : Fin width → Nat := + fun position => (indices position).val + +def vars (formula : Formula) (indices : Fin width → Fin formula.clauses.length) : + Fin width → Fin 3 → Nat := + fun position slot => (SourceTupleData.selectedClause formula indices position)[slot].variableIndex.val + +structure Clear (base : Tape width Extra → List Bool) : Prop where + rawDigits : ∀ i, base (.source (.digit i)) = [] + rawVariables : ∀ i j, base (.source (.variableName i j)) = [] + sourceWork : ∀ j, base (.source (.work j)) = [] + encodedVariables : ∀ i j, base (.encodedVariable i j) = [] + scratch : base .adapterScratch = [] + +structure Input (formula : Formula) (indices : Fin width → Fin formula.clauses.length) + (base : Tape width Extra → List Bool) : Prop extends Clear base where + table : base (.source .table) = SourceOccurrenceEncoding.bits formula + current : ∀ i, base (.current i) = encodeWord (indices i).val + +def digitTapes (formula : Formula) (indices : Fin width → Fin formula.clauses.length) + (base : Tape width Extra → List Bool) : Tape width Extra → List Bool + | .source (.digit i) => List.replicate (indices i).val true + | tape => base tape + +def rawTapes (formula : Formula) (indices : Fin width → Fin formula.clauses.length) + (base : Tape width Extra → List Bool) : Tape width Extra → List Bool + | .source (.digit i) => List.replicate (indices i).val true + | .source (.variableName i j) => List.replicate (vars formula indices i j) true + | tape => base tape + +def preparedTapes (formula : Formula) (indices : Fin width → Fin formula.clauses.length) + (base : Tape width Extra → List Bool) : Tape width Extra → List Bool + | .source (.digit i) => List.replicate (indices i).val true + | .source (.variableName i j) => List.replicate (vars formula indices i j) true + | .encodedVariable i j => encodeWord (vars formula indices i j) + | tape => base tape + +theorem prepared_metadata (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) (base : Tape width Extra → List Bool) + (input : Input formula indices base) (i : Fin width) (field : Fin 4) : + preparedTapes formula indices base (KeyMetadataMachine.idTape (metadata i) field) = + encodeWord (KeyMetadataMachine.fieldValue (ids formula indices i) (vars formula indices i) field) := by + fin_cases field <;> + simp [KeyMetadataMachine.idTape, KeyMetadataMachine.idIndex, metadata, preparedTapes, + KeyMetadataMachine.fieldValue, ids, input.current] <;> rfl + +end +end PerfectCompleteness.SignedTupleLayout + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/SignedTupleSemantics.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/SignedTupleSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..60dda7f549aff67fd39a6216d8f42f2e72bee8d9 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/SignedTupleSemantics.lean @@ -0,0 +1,271 @@ +import OAI.Computability.PerfectCompleteness.Construction.SourceQuestionOrderLemmas +import OAI.Computability.PerfectCompleteness.Machines.ExactTargetOnlineEncoding +import OAI.Computability.PerfectCompleteness.Machines.SignedTupleBodyMachine + +namespace OAI + + +namespace PerfectCompleteness.SignedTupleSemantics + + +open MetadataFreeSampler +open UniqueGamesTheorem.Foundations.Complexity +open scoped Classical + +noncomputable section + +variable {branch : Nat → Nat} {n t v m : Nat} [NeZero m] + (clauses : Fin m → SourceClause.NormalizedClause v) (rows repeats : Nat → Nat) + (hn : 0 < n) (hbranch : ∀ k < n, 0 < branch k) + (hrows : ∀ k, 0 < rows (k + 1)) (δ : ℚ) + +local notation "width" => TreeCanonical.locationCount branch n t +local notation "q" => FinitePreliminaryCompletion.alphabet branch n t δ +local notation "hq" => CanonicalLocalCompletion.alphabet_positive width δ +local notation "large" => CanonicalLocalCompletion.partitionWidth_le_alphabet width δ +local notation "D" => SignedMultiplicity.denominator branch n t rows repeats hn hbranch hrows q +local notation "C" => CompletedSignedLaw.Completed (t := t) clauses rows repeats hn hbranch hrows δ +local notation "F" => FinitePreliminaryCompletion.blockFamily clauses branch n t rows repeats +local notation "equiv" => CompletedSignedLaw.completedEquiv (t := t) clauses rows repeats hn hbranch hrows δ +local notation "order" => CompletedVisitOrder.completedOrder + (t := t) clauses rows repeats hn hbranch hrows δ +local notation "localOrder" => CompletedVisitOrder.localOrder + (t := t) clauses rows repeats hn hbranch hrows δ +local notation "targetEntry" => ExactPreliminaryTarget.entry + (t := t) clauses rows repeats hn hbranch hrows δ + +def sourceIDs (source : PreliminarySampler.Questions branch n t m) : Fin width → Nat := + fun i => (SourceQuestionOrder.questionToTuple source i).val + +def sourceVariables (source : PreliminarySampler.Questions branch n t m) : + Fin width → Fin 3 → Nat := + fun i j => ((clauses (SourceQuestionOrder.questionToTuple source i)).variable j).val + +omit [NeZero m] in +@[simp] theorem sourceIDs_tuple (indices : Fin width → Fin m) : + sourceIDs (SourceQuestionOrder.tupleToQuestion (branch := branch) (n := n) (t := t) indices) = + fun i => (indices i).val := by + exact congrArg (fun tuple : Fin width → Fin m => fun i => (tuple i).val) + (SourceQuestionOrder.questionToTuple_tupleToQuestion + (branch := branch) (n := n) (t := t) indices) + +omit [NeZero m] in +@[simp] theorem sourceVariables_tuple (indices : Fin width → Fin m) : + sourceVariables clauses + (SourceQuestionOrder.tupleToQuestion (branch := branch) (n := n) (t := t) indices) = + fun i j => ((clauses (indices i)).variable j).val := by + exact congrArg + (fun tuple : Fin width → Fin m => fun i j => ((clauses (tuple i)).variable j).val) + (SourceQuestionOrder.questionToTuple_tupleToQuestion + (branch := branch) (n := n) (t := t) indices) + +omit [NeZero m] in +theorem sourceIDs_eq (source : PreliminarySampler.Questions branch n t m) : + sourceIDs source = fun i => DescriptorKeyTemplate.occurrence + (TreeCanonical.numberedSlots (sourceSlots clauses source) i) := rfl + +omit [NeZero m] in +theorem sourceVariables_eq (source : PreliminarySampler.Questions branch n t m) : + sourceVariables clauses source = fun i => DescriptorKeyTemplate.variableIDs + (TreeCanonical.numberedSlots (sourceSlots clauses source) i) := rfl + +def descriptorOf (e : C) : SignedCompletionSchedule.Descriptor + (rows := rows) (repeats := repeats) hq large := + ⟨sourceSigns clauses (equiv e).1, (equiv e).2⟩ + +theorem descriptorOf_tape (e : C) : + DescriptorKeyTemplate.tapeInput hq large + (descriptorOf clauses rows repeats hn hbranch hrows δ e) = + MetadataFreeTape.encodeRaw clauses rows repeats e.1 := rfl + +theorem left_key (e : C) : + CompletedEdgeMachine.key hq large (descriptorOf clauses rows repeats hn hbranch hrows δ e) + .left (sourceIDs e.1.1.1) (sourceVariables clauses e.1.1.1) = + CanonicalGame.leftKey F e.1 := by + rcases e with ⟨raw, seed⟩ + exact (DescriptorKeyTemplate.recover_left clauses raw).trans + (HierarchicalGame.leftKey_eq + (PreliminarySampler.family clauses branch n t rows repeats) raw).symm + +theorem right_key (e : C) : + CompletedEdgeMachine.key hq large (descriptorOf clauses rows repeats hn hbranch hrows δ e) + .right (sourceIDs e.1.1.1) (sourceVariables clauses e.1.1.1) = + CanonicalGame.rightKey F e.1 := by + rcases e with ⟨raw, seed⟩ + exact (DescriptorKeyTemplate.recover_right clauses raw).trans + (HierarchicalGame.rightKey_eq + (PreliminarySampler.family clauses branch n t rows repeats) raw).symm + +omit [NeZero m] in +private theorem projection_ext {alphabet : Nat} {x y : ProjectionTable alphabet} + (same : ∀ a : Fin (2 * alphabet), x.images[a] = y.images[a]) : x = y := by + have images : x.images = y.images := by + apply Vector.ext + intro i hi + exact same ⟨i, hi⟩ + cases x + cases y + cases images + rfl + +theorem projection_eq (e : C) : + DescriptorProjectionMachine.projection hq large + (descriptorOf clauses rows repeats hn hbranch hrows δ e) = + (targetEntry e).projection := by + apply projection_ext (n := n) (alphabet := q) + intro a + have hp := DescriptorProjectionMachine.projection_apply + (branch := branch) (n := n) (t := t) («q» := q) (rows := rows) (repeats := repeats) + hq large (descriptorOf (branch := branch) (n := n) (t := t) (v := v) (m := m) + clauses rows repeats hn hbranch hrows δ e) a + apply hp.trans + delta ExactPreliminaryTarget.entry + rw [ProjectionTable.ofMap_apply] + exact CompletedSignedLaw.descriptorTable_eq_map + (branch := branch) (n := n) (t := t) (v := v) (m := m) + clauses rows repeats hn hbranch hrows δ e a + +def occurrenceAt (source : PreliminarySampler.Questions branch n t m) (i : Fin D) : C := + (equiv).symm ⟨source, + (SignedScheduleIndex.atIndex hq large hn hbranch hrows (sourceSigns clauses source) i).2⟩ + +theorem occurrenceAt_source (source : PreliminarySampler.Questions branch n t m) (i : Fin D) : + (occurrenceAt clauses rows repeats hn hbranch hrows δ source i).1.1.1 = source := + CompletedSignedLaw.completedEquiv_symm_source (t := t) clauses rows repeats hn hbranch hrows δ _ + +theorem descriptorOf_occurrenceAt (source : PreliminarySampler.Questions branch n t m) (i : Fin D) : + descriptorOf clauses rows repeats hn hbranch hrows δ + (occurrenceAt clauses rows repeats hn hbranch hrows δ source i) = + SignedScheduleIndex.atIndex hq large hn hbranch hrows (sourceSigns clauses source) i := by + have roundtrip := congrArg + (fun x : CompletedSignedLaw.SignedCompleted (branch := branch) (n := n) (t := t) + clauses rows repeats δ => + (⟨sourceSigns clauses x.1, x.2⟩ : + SignedCompletionSchedule.Descriptor (rows := rows) (repeats := repeats) hq large)) + ((equiv).apply_symm_apply ⟨source, + (SignedScheduleIndex.atIndex hq large hn hbranch hrows (sourceSigns clauses source) i).2⟩) + exact roundtrip.trans (by rfl) + +theorem ofFn_occurrenceAt (source : PreliminarySampler.Questions branch n t m) : + List.ofFn (occurrenceAt clauses rows repeats hn hbranch hrows δ source) = localOrder source := by + have localSchedule : + List.ofFn (fun i : Fin D => + (SignedScheduleIndex.atIndex hq large hn hbranch hrows (sourceSigns clauses source) i).2) = + SignedCompletionSchedule.schedule hq large hn hbranch hrows (sourceSigns clauses source) := by + let xs := SignedCompletionSchedule.schedule + (branch := branch) (n := n) (t := t) («q» := q) (rows := rows) (repeats := repeats) + hq large hn hbranch hrows (sourceSigns clauses source) + have hlen : xs.length = D := + SignedCompletionSchedule.schedule_length + (branch := branch) (n := n) (t := t) («q» := q) (rows := rows) (repeats := repeats) + hq large hn hbranch hrows (sourceSigns clauses source) + change List.ofFn (fun i : Fin D => xs.get (Fin.cast hlen.symm i)) = xs + have roundtrip := (List.ofFn_congr hlen xs.get).symm + rw [List.ofFn_get] at roundtrip + exact roundtrip + calc + _ = (List.ofFn (fun i : Fin D => + (SignedScheduleIndex.atIndex hq large hn hbranch hrows (sourceSigns clauses source) i).2)).map + (fun outcome => (equiv).symm ⟨source, outcome⟩) := List.ofFn_comp' _ _ + _ = localOrder source := by rw [localSchedule]; rfl + +theorem map_finRange_occurrenceAt (source : PreliminarySampler.Questions branch n t m) : + (List.finRange D).map (occurrenceAt clauses rows repeats hn hbranch hrows δ source) = + localOrder source := by + rw [← List.ofFn_eq_map] + exact ofFn_occurrenceAt clauses rows repeats hn hbranch hrows δ source + +def dataOfPrefix (earlier : List C) (tail : List Bool) : SignedTupleBodyMachine.Data width where + leftKeys := ExactTargetOnlineEncoding.leftKeys (t := t) clauses rows repeats hn hbranch hrows δ earlier + rightKeys := ExactTargetOnlineEncoding.rightKeys (t := t) clauses rows repeats hn hbranch hrows δ earlier + reversedOutput := (earlier.flatMap (fun e => encodeWords (Encoding.edgeWords (targetEntry e)))).reverse ++ tail + count := earlier.length + +theorem edgeBits_eq_entry (earlier suffix : List C) (e : C) + (split : order = earlier ++ e :: suffix) : + CompletedEdgeMachine.edgeBits hq large (descriptorOf clauses rows repeats hn hbranch hrows δ e) + (ExactTargetOnlineEncoding.leftKeys (t := t) clauses rows repeats hn hbranch hrows δ earlier) + (ExactTargetOnlineEncoding.rightKeys (t := t) clauses rows repeats hn hbranch hrows δ earlier) + (sourceIDs e.1.1.1) (sourceVariables clauses e.1.1.1) = + encodeWords (Encoding.edgeWords (targetEntry e)) := by + rw [CompletedEdgeMachine.edgeBits_eq, left_key, right_key, + DescriptorProjectionMachine.outputBits, DescriptorProjectionMachine.outputWords, projection_eq, + ExactTargetOnlineEncoding.left_online (t := t) clauses rows repeats hn hbranch hrows δ + earlier suffix e split, + ExactTargetOnlineEncoding.right_online (t := t) clauses rows repeats hn hbranch hrows δ + earlier suffix e split] + simp only [Encoding.edgeWords, encodeWords_append, encodeWords, List.append_nil, List.append_assoc] + +theorem next_eq_append (earlier suffix : List C) (e : C) (tail : List Bool) + (split : order = earlier ++ e :: suffix) : + SignedTupleBodyMachine.next hq large (descriptorOf clauses rows repeats hn hbranch hrows δ e) + (sourceIDs e.1.1.1) (sourceVariables clauses e.1.1.1) + (dataOfPrefix clauses rows repeats hn hbranch hrows δ earlier tail) = + dataOfPrefix clauses rows repeats hn hbranch hrows δ (earlier ++ [e]) tail := by + have hbits := edgeBits_eq_entry clauses rows repeats hn hbranch hrows δ earlier suffix e split + simp only [ExactTargetOnlineEncoding.leftKeys, ExactTargetOnlineEncoding.rightKeys] at hbits + simp only [SignedTupleBodyMachine.next, dataOfPrefix, left_key, right_key, + hbits, + ExactTargetOnlineEncoding.leftKeys, ExactTargetOnlineEncoding.rightKeys, + List.map_append, List.map_cons, List.map_nil, List.flatMap_append, + List.flatMap_cons, List.flatMap_nil, List.append_nil, List.reverse_append, + List.length_append, List.length_cons, List.length_nil, Nat.zero_add, List.append_assoc] + +theorem next_atIndex_eq (source : PreliminarySampler.Questions branch n t m) (i : Fin D) + (earlier suffix : List C) (tail : List Bool) + (split : order = earlier ++ occurrenceAt clauses rows repeats hn hbranch hrows δ source i :: suffix) : + SignedTupleBodyMachine.next hq large + (SignedScheduleIndex.atIndex hq large hn hbranch hrows (sourceSigns clauses source) i) + (sourceIDs source) (sourceVariables clauses source) + (dataOfPrefix clauses rows repeats hn hbranch hrows δ earlier tail) = + dataOfPrefix clauses rows repeats hn hbranch hrows δ + (earlier ++ [occurrenceAt clauses rows repeats hn hbranch hrows δ source i]) tail := by + simpa only [descriptorOf_occurrenceAt, occurrenceAt_source] using + next_eq_append clauses rows repeats hn hbranch hrows δ earlier suffix + (occurrenceAt clauses rows repeats hn hbranch hrows δ source i) tail split + +theorem result_eq_append (source : PreliminarySampler.Questions branch n t m) + (indices : List (Fin D)) (earlier suffix : List C) (tail : List Bool) + (split : order = earlier ++ + indices.map (occurrenceAt clauses rows repeats hn hbranch hrows δ source) ++ suffix) : + SignedTupleBodyMachine.result hq large hn hbranch hrows (sourceSigns clauses source) + (sourceIDs source) (sourceVariables clauses source) indices + (dataOfPrefix clauses rows repeats hn hbranch hrows δ earlier tail) = + dataOfPrefix clauses rows repeats hn hbranch hrows δ + (earlier ++ indices.map (occurrenceAt clauses rows repeats hn hbranch hrows δ source)) tail := by + induction indices generalizing earlier with + | nil => simp only [SignedTupleBodyMachine.result, List.map_nil, List.append_nil] + | cons i indices ih => + let e := occurrenceAt clauses rows repeats hn hbranch hrows δ source i + have currentSplit : order = earlier ++ e :: + (indices.map (occurrenceAt clauses rows repeats hn hbranch hrows δ source) ++ suffix) := by + simpa only [e, List.map_cons, List.append_assoc, List.cons_append] using split + rw [SignedTupleBodyMachine.result, + next_atIndex_eq clauses rows repeats hn hbranch hrows δ source i earlier + (indices.map (occurrenceAt clauses rows repeats hn hbranch hrows δ source) ++ suffix) tail currentSplit] + have restSplit : order = (earlier ++ [e]) ++ + indices.map (occurrenceAt clauses rows repeats hn hbranch hrows δ source) ++ suffix := by + simpa only [List.append_assoc, List.singleton_append, List.cons_append, List.nil_append] + using currentSplit + simpa only [e, List.map_cons, List.append_assoc, List.singleton_append, List.cons_append, + List.nil_append] using + ih (earlier ++ [e]) restSplit + +theorem full_result_eq (source : PreliminarySampler.Questions branch n t m) + (earlier suffix : List C) (tail : List Bool) + (split : order = earlier ++ localOrder source ++ suffix) : + SignedTupleBodyMachine.result hq large hn hbranch hrows (sourceSigns clauses source) + (sourceIDs source) (sourceVariables clauses source) (List.finRange D) + (dataOfPrefix clauses rows repeats hn hbranch hrows δ earlier tail) = + dataOfPrefix clauses rows repeats hn hbranch hrows δ (earlier ++ localOrder source) tail := by + have indexedSplit : order = earlier ++ + (List.finRange D).map (occurrenceAt clauses rows repeats hn hbranch hrows δ source) ++ suffix := by + rwa [map_finRange_occurrenceAt] + simpa only [map_finRange_occurrenceAt] using + result_eq_append clauses rows repeats hn hbranch hrows δ source (List.finRange D) + earlier suffix tail indexedSplit + +end +end PerfectCompleteness.SignedTupleSemantics + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/SlotProjectedExperiment.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/SlotProjectedExperiment.lean new file mode 100644 index 0000000000000000000000000000000000000000..9e9650bd89592c5589fe479d67e68ce6fb83abf5 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/SlotProjectedExperiment.lean @@ -0,0 +1,380 @@ +import OAI.Computability.PerfectCompleteness.Decoding.CleanDecoderSeedLawLemmas +import OAI.Computability.PerfectCompleteness.Foundations.StoppedProjectedExperiment + +namespace OAI + +section + +namespace PerfectCompleteness.SlotProjectedExperiment + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +def selectSlot : MixedSupport.Slot → Fin 3 → MixedSupport.Slot + | .clause _ ids _, position => .bit (ids position) + | .bit id, _ => .bit id + +def selectProjection (s : MixedSupport.Slot) (position : Fin 3) : + MixedSupport.Projection s (selectSlot s position) := by + cases s with + | clause occurrence ids signs => exact .select occurrence ids signs position + | bit id => exact .keep (.bit id) + +def flaggedSlot (s : MixedSupport.Slot) (position : Fin 3) : Bool → MixedSupport.Slot + | false => s + | true => selectSlot s position + +def flaggedProjection (s : MixedSupport.Slot) (position : Fin 3) : + (b : Bool) → MixedSupport.Projection s (flaggedSlot s position b) + | false => .keep s + | true => selectProjection s position + +variable {branch : Nat → Nat} {n i j t v m : Nat} + +def mixedInside (slots : Slots branch (i + 1) → Fin t → MixedSupport.Slot) + (choices : SourceQuestionKernelJoint.ChoiceTuple (branch := branch) (n := i) (t := t)) + (flags : SourceProjectedTag.Flags (branch := branch) (n := i)) : + Slots branch (i + 1) → Fin t → MixedSupport.Slot := + fun leaf a => flaggedSlot (slots leaf a) (choices leaf.1 leaf.2 a) (flags leaf.1) + +def insideProjection (slots : Slots branch (i + 1) → Fin t → MixedSupport.Slot) + (choices : SourceQuestionKernelJoint.ChoiceTuple (branch := branch) (n := i) (t := t)) + (flags : SourceProjectedTag.Flags (branch := branch) (n := i)) : + ∀ leaf a, MixedSupport.Projection (slots leaf a) (mixedInside slots choices flags leaf a) := + fun leaf a => flaggedProjection (slots leaf a) (choices leaf.1 leaf.2 a) (flags leaf.1) + +abbrev Inner (rows : Nat → Nat) := + StoppedProjectedExperiment.Inner (branch := branch) (n := n) (i := i) (j := j) (t := t) rows + +abbrev innerLaw (rows : Nat → Nat) (hij : i < j) + (hbranch : ∀ k < j + 1, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) + (flag : Fin (branch i) → FiniteDistribution Bool) := + StoppedProjectedExperiment.innerLaw (n := n) (t := t) rows hij hbranch hrows flag + +variable (rows repeats : Nat → Nat) (hupper : j + 1 ≤ n) (hij : i < j) + (pref : GeometricCutSplit.Prefix branch n (j + 1)) + +def upperPath := GeometricCutSplit.prefixPath hupper pref + +abbrev lowerPath (k : Inner (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) := + StoppedProjectedExperiment.lowerPath rows hij k + +def stoppedPath (k : Inner (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) := + (upperPath hupper pref).append (lowerPath rows hij k) + +def upper := WholeArrayInteriorExterior.upperNode (upperPath hupper pref) + +def lower (k : Inner (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) := + WholeArrayInteriorExterior.upperNode (stoppedPath rows hupper hij pref k) + +@[simp] theorem upper_height : Nodes.height (upper hupper pref) = j + 1 := + WholeArrayInteriorExterior.upperNode_height _ + +@[simp] theorem lower_height + (k : Inner (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) : + Nodes.height (lower rows hupper hij pref k) = i + 1 := + WholeArrayInteriorExterior.upperNode_height _ + +def cut (k : Inner (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) : + OwnInputReference.Cut (upper hupper pref) (lower rows hupper hij pref k) := + StoppedOwnInputGeometry.cutOfBelow + (StoppedProjectedExperiment.below_append hij (upperPath hupper pref) (lowerPath rows hij k)) + +def direction (k : Inner (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) : + Block rows (lower rows hupper hij pref k) := + let level : Fin n := ⟨i, Nat.lt_of_lt_of_le (Nat.lt_trans hij (Nat.lt_succ_self j)) hupper⟩ + (PrefixTests.nodeDirection rows level + ⟨lower rows hupper hij pref k, lower_height rows hupper hij pref k⟩ (k.2.2 level)).val + +variable (slots : Slots branch n → Fin t → MixedSupport.Slot) + +def inside (k : Inner (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) : + Slots branch (i + 1) → Fin t → MixedSupport.Slot := + fun leaf a => slots ((stoppedPath rows hupper hij pref k).slotEmbedding leaf) a + +def projectedSlots (k : Inner (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) : + Slots branch n → Fin t → MixedSupport.Slot := + CutSlotAssembly.fill (stoppedPath rows hupper hij pref k) slots + (mixedInside (inside rows hupper hij pref slots k) k.2.1.1 k.2.1.2) + +theorem fill_inside (k : Inner (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) : + CutSlotAssembly.fill (stoppedPath rows hupper hij pref k) slots + (inside rows hupper hij pref slots k) = slots := + CutSlotAssembly.fill_restrict (stoppedPath rows hupper hij pref k) slots + +def projection (k : Inner (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) : + ∀ leaf a, MixedSupport.Projection (slots leaf a) + (projectedSlots rows hupper hij pref slots k leaf a) := + fun leaf a => CutProjectionAssembly.castProjection + (congrFun (congrFun (fill_inside rows hupper hij pref slots k) leaf) a) rfl + (CutProjectionAssembly.fillProjection (stoppedPath rows hupper hij pref k) slots + (inside rows hupper hij pref slots k) + (mixedInside (inside rows hupper hij pref slots k) k.2.1.1 k.2.1.2) + (insideProjection (inside rows hupper hij pref slots k) k.2.1.1 k.2.1.2) leaf a) + +abbrev Sample := HierarchicalProjectedExperiment.Sample (rows := rows) (repeats := repeats) + (projectedSlots rows hupper hij pref slots) (upper hupper pref) + (lower rows hupper hij pref) (cut rows hupper hij pref) + +variable (hbranch : ∀ k < j + 1, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) + (flag : Fin (branch i) → FiniteDistribution Bool) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + +abbrev experiment := + HierarchicalProjectedExperiment.experiment (rows := rows) (repeats := repeats) + slots (projectedSlots rows hupper hij pref slots) (projection rows hupper hij pref slots) + (upper hupper pref) (i + 1) (lower rows hupper hij pref) + (cut rows hupper hij pref) (direction rows hupper hij pref) + (innerLaw rows hij hbranch hrows flag) σ + +def family : OriginalDecoderMark.Family branch rows n t + (Sample rows repeats hupper hij pref) where + original slots := (experiment rows repeats hupper hij pref slots hbranch hrows flag σ).original + arrays slots := (experiment rows repeats hupper hij pref slots hbranch hrows flag σ).arrays + lowerEvent slots := HierarchicalAdviceExperiment.lowerEvent + (experiment rows repeats hupper hij pref slots hbranch hrows flag σ) + +theorem mark_eq (κ : ℝ) + (background : HierarchicalMatrixTable.Background (rows := rows) slots (upper hupper pref)) + (X : HierarchicalFrozenTables.QuotientMatrix slots (upper hupper pref) (i + 1) background) : + OriginalDecoderMark.mark (family rows repeats hupper hij pref hbranch hrows flag σ) + (upper hupper pref) (i + 1) κ slots background X ↔ + HierarchicalUsefulness.mark slots (upper hupper pref) (i + 1) + (experiment rows repeats hupper hij pref slots hbranch hrows flag σ).original + (experiment rows repeats hupper hij pref slots hbranch hrows flag σ).arrays + (HierarchicalAdviceExperiment.lowerEvent + (experiment rows repeats hupper hij pref slots hbranch hrows flag σ)) κ + ⟨background, X⟩ = true := Iff.rfl + +section Source + +variable (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch i) → Slots branch i) + (q : SourceQuestionPositionSplit.Questions (branch := branch) (n := i) (t := t) (m := m)) + (choices : SourceQuestionKernelJoint.ChoiceTuple (branch := branch) (n := i) (t := t)) + (flags : SourceProjectedTag.Flags (branch := branch) (n := i)) + +private theorem tree_sources (leaf : Slots branch (i + 1)) (a : Fin t) : + SourceChildKernel.tree designated leaf.1 + (SourceQuestionKernelJoint.sources designated q choices leaf.1) leaf.2 a = + (q leaf a, choices leaf.1 leaf.2 a) := by + rcases leaf with ⟨child, tail⟩ + have h := SourceQuestionPositionSplit.child_tree_join designated q + (SourceQuestionPositionSplit.byChild.symm choices) child tail a + change SourceChildKernel.tree designated child + (SourceQuestionKernelJoint.sources designated q choices child) tail a = + (q (child, tail) a, choices child tail a) at h + exact h + +theorem mixedInside_source : + mixedInside (SourceProjectedTag.originalSlots clauses q) choices flags = + SourceProjectedTag.mixedInside clauses designated q choices flags := by + funext leaf a + have htree := tree_sources designated q choices leaf a + cases hf : flags leaf.1 <;> + simp only [mixedInside, flaggedSlot, selectSlot, SourceProjectedTag.mixedInside, + SourceProjectedTag.originalSlots, sourceSlots, PreliminarySampler.endpoints, + SourceChildKernel.mixedSlots, SourceChildKernel.nativeSlots, + ProjectedCardinality.projectedSlots, SourceChildKernel.ids, + SourceClause.occurrenceVariable, SourceKeys.slot, hf, htree] + +private theorem projection_family_heq + {left right₁ right₂ : Slots branch (i + 1) → Fin t → MixedSupport.Slot} + (hr : right₁ = right₂) + (p₁ : ∀ leaf a, MixedSupport.Projection (left leaf a) (right₁ leaf a)) + (p₂ : ∀ leaf a, MixedSupport.Projection (left leaf a) (right₂ leaf a)) + (hp : ∀ leaf a, HEq (p₁ leaf a) (p₂ leaf a)) : HEq p₁ p₂ := by + subst right₂ + apply heq_of_eq + funext leaf a + exact eq_of_heq (hp leaf a) + +private theorem mpr_heq {α β : Sort _} (h : α = β) (x : β) : + HEq (Eq.mpr h x) x := by + cases h + rfl + +private theorem flagged_occurrence_heq + {e e' : SourceClause.Occurrence m} (h : e = e') (b : Bool) : + HEq (flaggedProjection (SourceKeys.slot clauses (.clause e.1)) e.2 b) + (flaggedProjection (SourceKeys.slot clauses (.clause e'.1)) e'.2 b) := by + cases h + rfl + +private theorem child_projection_as_flagged (child : Fin (branch i)) + (s : SourceChildKernel.Source (m := m) (t := t) designated child) + (b : Bool) (leaf : Slots branch i) (a : Fin t) : + HEq (SourceChildKernel.projection clauses designated child s b leaf a) + (flaggedProjection + (SourceKeys.slot clauses (.clause (SourceChildKernel.tree designated child s leaf a).1)) + (SourceChildKernel.tree designated child s leaf a).2 b) := by + cases b <;> rfl + +theorem insideProjection_source : + HEq (insideProjection (SourceProjectedTag.originalSlots clauses q) choices flags) + (SourceProjectedTag.projection clauses designated q choices flags) := by + apply projection_family_heq (mixedInside_source clauses designated q choices flags) + intro leaf a + have htree := tree_sources designated q choices leaf a + have hcast : HEq (SourceProjectedTag.projection clauses designated q choices flags leaf a) + (SourceChildKernel.projection clauses designated leaf.1 + (SourceQuestionKernelJoint.sources designated q choices leaf.1) + (flags leaf.1) leaf.2 a) := by + unfold SourceProjectedTag.projection + dsimp only [id] + exact mpr_heq _ _ + have hflagged := flagged_occurrence_heq clauses htree.symm (flags leaf.1) + have hchild := child_projection_as_flagged clauses designated leaf.1 + (SourceQuestionKernelJoint.sources designated q choices leaf.1) + (flags leaf.1) leaf.2 a + exact hflagged.trans (hchild.symm.trans hcast.symm) + +variable (originalQuestions : PreliminarySampler.Questions branch n t m) + +theorem projectedSlots_source + (k : Inner (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) : + projectedSlots rows hupper hij pref + (sourceSlots clauses (PreliminarySampler.endpoints originalQuestions)) k = + StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated + (originalQuestions, pref) k := by + unfold projectedSlots StoppedProjectedExperiment.projectedSlots + exact congrArg (CutSlotAssembly.fill (stoppedPath rows hupper hij pref k) + (sourceSlots clauses (PreliminarySampler.endpoints originalQuestions))) + (mixedInside_source clauses designated + (StoppedProjectedExperiment.cutQuestions rows hupper hij (originalQuestions, pref) k) + k.2.1.1 k.2.1.2) + +private theorem filled_projection_heq (p : Path branch n (i + 1)) + (outside : Slots branch n → Fin t → MixedSupport.Slot) + (left right₁ right₂ : Slots branch (i + 1) → Fin t → MixedSupport.Slot) + (hleft : CutSlotAssembly.fill p outside left = outside) (hr : right₁ = right₂) + (p₁ : ∀ leaf a, MixedSupport.Projection (left leaf a) (right₁ leaf a)) + (p₂ : ∀ leaf a, MixedSupport.Projection (left leaf a) (right₂ leaf a)) + (hp : HEq p₁ p₂) : + HEq (fun leaf a => CutProjectionAssembly.castProjection + (congrFun (congrFun hleft leaf) a) rfl + (CutProjectionAssembly.fillProjection p outside left right₁ p₁ leaf a)) + (fun leaf a => CutProjectionAssembly.castProjection + (congrFun (congrFun hleft leaf) a) rfl + (CutProjectionAssembly.fillProjection p outside left right₂ p₂ leaf a)) := by + subst right₂ + have hp' : p₁ = p₂ := eq_of_heq hp + subst p₂ + rfl + +theorem projection_source + (k : Inner (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) : + HEq (projection rows hupper hij pref + (sourceSlots clauses (PreliminarySampler.endpoints originalQuestions)) k) + (StoppedProjectedExperiment.projection clauses rows hupper hij designated + (originalQuestions, pref) k) := by + exact filled_projection_heq (stoppedPath rows hupper hij pref k) + (sourceSlots clauses (PreliminarySampler.endpoints originalQuestions)) + (SourceProjectedTag.originalSlots clauses + (StoppedProjectedExperiment.cutQuestions rows hupper hij (originalQuestions, pref) k)) + _ _ (StoppedProjectedExperiment.fill_native clauses rows hupper hij (originalQuestions, pref) k) + (mixedInside_source clauses designated + (StoppedProjectedExperiment.cutQuestions rows hupper hij (originalQuestions, pref) k) + k.2.1.1 k.2.1.2) _ _ + (insideProjection_source clauses designated + (StoppedProjectedExperiment.cutQuestions rows hupper hij (originalQuestions, pref) k) + k.2.1.1 k.2.1.2) + +private theorem tagged_projection_heq {K : Type*} + {left : Slots branch n → Fin t → MixedSupport.Slot} + {right₁ right₂ : K → Slots branch n → Fin t → MixedSupport.Slot} + (hr : right₁ = right₂) + (p₁ : ∀ k leaf a, MixedSupport.Projection (left leaf a) (right₁ k leaf a)) + (p₂ : ∀ k leaf a, MixedSupport.Projection (left leaf a) (right₂ k leaf a)) + (hp : ∀ k, HEq (p₁ k) (p₂ k)) : HEq p₁ p₂ := by + subst right₂ + apply heq_of_eq + funext k + exact eq_of_heq (hp k) + +private theorem projected_experiment_heq {K : Type*} [Fintype K] + (native : Slots branch n → Fin t → MixedSupport.Slot) + {right₁ right₂ : K → Slots branch n → Fin t → MixedSupport.Slot} + (hr : right₁ = right₂) + (p₁ : ∀ k leaf a, MixedSupport.Projection (native leaf a) (right₁ k leaf a)) + (p₂ : ∀ k leaf a, MixedSupport.Projection (native leaf a) (right₂ k leaf a)) + (hp : HEq p₁ p₂) (upperNode : Nodes branch n) (lowerLevel : Nat) + (lowerNode : K → Nodes branch n) + (cuts : ∀ k, OwnInputReference.Cut upperNode (lowerNode k)) + (directions : ∀ k, Block rows (lowerNode k)) (μ : FiniteDistribution K) : + HEq (HierarchicalProjectedExperiment.experiment (repeats := repeats) + native right₁ p₁ upperNode lowerLevel lowerNode cuts directions μ σ) + (HierarchicalProjectedExperiment.experiment (repeats := repeats) + native right₂ p₂ upperNode lowerLevel lowerNode cuts directions μ σ) := by + subst right₂ + have hp' : p₁ = p₂ := eq_of_heq hp + subst p₂ + rfl + +theorem experiment_source : + HEq (experiment rows repeats hupper hij pref + (sourceSlots clauses (PreliminarySampler.endpoints originalQuestions)) hbranch hrows flag σ) + (StoppedProjectedExperiment.experiment clauses rows repeats hupper hij designated + hbranch hrows flag σ (originalQuestions, pref)) := by + have hs := funext (projectedSlots_source rows hupper hij pref clauses designated originalQuestions) + have hp := tagged_projection_heq hs _ _ + (projection_source rows hupper hij pref clauses designated originalQuestions) + exact projected_experiment_heq rows repeats σ _ hs _ _ hp _ _ _ _ _ _ + +private theorem projection_data_congr {K : Type*} {α : Sort*} + {native : Slots branch n → Fin t → MixedSupport.Slot} + {right₁ right₂ : K → Slots branch n → Fin t → MixedSupport.Slot} + (hr : right₁ = right₂) + (p₁ : ∀ k leaf a, MixedSupport.Projection (native leaf a) (right₁ k leaf a)) + (p₂ : ∀ k leaf a, MixedSupport.Projection (native leaf a) (right₂ k leaf a)) + (hp : HEq p₁ p₂) + (f : (right : K → Slots branch n → Fin t → MixedSupport.Slot) → + (∀ k leaf a, MixedSupport.Projection (native leaf a) (right k leaf a)) → α) : + f right₁ p₁ = f right₂ p₂ := by + subst right₂ + have hp' : p₁ = p₂ := eq_of_heq hp + subst p₂ + rfl + +theorem mark_source (κ : ℝ) + (background : HierarchicalMatrixTable.Background (rows := rows) + (sourceSlots clauses (PreliminarySampler.endpoints originalQuestions)) (upper hupper pref)) + (X : HierarchicalFrozenTables.QuotientMatrix + (sourceSlots clauses (PreliminarySampler.endpoints originalQuestions)) + (upper hupper pref) (i + 1) background) : + OriginalDecoderMark.mark (family rows repeats hupper hij pref hbranch hrows flag σ) + (upper hupper pref) (i + 1) κ + (sourceSlots clauses (PreliminarySampler.endpoints originalQuestions)) background X ↔ + HierarchicalUsefulness.mark + (sourceSlots clauses (PreliminarySampler.endpoints originalQuestions)) (upper hupper pref) (i + 1) + (StoppedProjectedExperiment.experiment clauses rows repeats hupper hij designated + hbranch hrows flag σ (originalQuestions, pref)).original + (StoppedProjectedExperiment.experiment clauses rows repeats hupper hij designated + hbranch hrows flag σ (originalQuestions, pref)).arrays + (HierarchicalAdviceExperiment.lowerEvent + (StoppedProjectedExperiment.experiment clauses rows repeats hupper hij designated + hbranch hrows flag σ (originalQuestions, pref))) κ ⟨background, X⟩ = true := by + have hs := funext (projectedSlots_source rows hupper hij pref clauses designated originalQuestions) + have hp := tagged_projection_heq hs _ _ + (projection_source rows hupper hij pref clauses designated originalQuestions) + have hm := projection_data_congr hs _ _ hp (fun right proj => + let S := HierarchicalProjectedExperiment.experiment (rows := rows) (repeats := repeats) + (sourceSlots clauses (PreliminarySampler.endpoints originalQuestions)) right proj + (upper hupper pref) (i + 1) (lower rows hupper hij pref) + (cut rows hupper hij pref) (direction rows hupper hij pref) + (innerLaw rows hij hbranch hrows flag) σ + HierarchicalUsefulness.mark S.slots S.upper S.lowerLevel S.original S.arrays + (HierarchicalAdviceExperiment.lowerEvent S) κ ⟨background, X⟩) + exact Iff.of_eq (congrArg (fun b : Bool => b = true) hm) + +end Source + +end +end PerfectCompleteness.SlotProjectedExperiment + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/SourceClause.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/SourceClause.lean new file mode 100644 index 0000000000000000000000000000000000000000..7d5a0bac5b25b56036db0afa9beef710ac26447e --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/SourceClause.lean @@ -0,0 +1,207 @@ +import OAI.Computability.UniqueGames.Foundations.PinskerLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.SourceClause + +open UniqueGamesTheorem.Foundations.Target + +abbrev Triple := Bool × Bool × Bool + +def Triple.at (t : Triple) (i : Fin 3) : Bool := + match i.val with + | 0 => t.1 + | 1 => t.2.1 + | _ => t.2.2 + +def literalTruth (positive value : Bool) : Bool := + if positive then value else !value + +def localEval (signs values : Triple) : Bool := + (literalTruth signs.1 values.1 || literalTruth signs.2.1 values.2.1) || + literalTruth signs.2.2 values.2.2 + +def allTriples : List Triple := + [(false, false, false), (false, false, true), + (false, true, false), (false, true, true), + (true, false, false), (true, false, true), + (true, true, false), (true, true, true)] + +def satisfyingTriples (signs : Triple) : List Triple := + allTriples.filter (localEval signs) + +theorem mem_allTriples (t : Triple) : t ∈ allTriples := by + rcases t with ⟨a, b, c⟩ + cases a <;> cases b <;> cases c <;> decide + +@[simp] theorem mem_satisfyingTriples (signs values : Triple) : + values ∈ satisfyingTriples signs ↔ localEval signs values = true := by + simp [satisfyingTriples, mem_allTriples] + +theorem satisfyingTriples_nodup (signs : Triple) : + (satisfyingTriples signs).Nodup := by + rcases signs with ⟨a, b, c⟩ + cases a <;> cases b <;> cases c <;> decide + +@[simp] theorem satisfyingTriples_length (signs : Triple) : + (satisfyingTriples signs).length = 7 := by + rcases signs with ⟨a, b, c⟩ + cases a <;> cases b <;> cases c <;> rfl + +private theorem coordinate_truth_table : + ∀ s₀ s₁ s₂ : Bool, ∀ i : Fin 3, ∀ value : Bool, + ∃ a b c : Bool, + localEval (s₀, s₁, s₂) (a, b, c) = true ∧ + Triple.at (a, b, c) i = value := by + decide + +theorem coordinate_surjective (signs : Triple) (i : Fin 3) (value : Bool) : + ∃ t ∈ satisfyingTriples signs, t.at i = value := by + obtain ⟨a, b, c, hs, hv⟩ := + coordinate_truth_table signs.1 signs.2.1 signs.2.2 i value + exact ⟨(a, b, c), (mem_satisfyingTriples signs _).mpr hs, hv⟩ + +private theorem pair_truth_table : + ∀ s₀ s₁ s₂ : Bool, ∀ i j : Fin 3, i ≠ j → ∀ first second : Bool, + ∃ a b c : Bool, + localEval (s₀, s₁, s₂) (a, b, c) = true ∧ + Triple.at (a, b, c) i = first ∧ Triple.at (a, b, c) j = second := by + decide + +theorem pair_surjective (signs : Triple) (i j : Fin 3) (distinct : i ≠ j) + (first second : Bool) : + ∃ t ∈ satisfyingTriples signs, t.at i = first ∧ t.at j = second := by + obtain ⟨a, b, c, hs, hv⟩ := + pair_truth_table signs.1 signs.2.1 signs.2.2 i j distinct first second + exact ⟨(a, b, c), (mem_satisfyingTriples signs _).mpr hs, hv⟩ + +structure NormalizedClause («variables» : Nat) where + clause : Clause «variables» + distinct : ∀ i j : Fin 3, + clause[i].variableIndex = clause[j].variableIndex → i = j + +def NormalizedClause.variable {n : Nat} (c : NormalizedClause n) (i : Fin 3) : Fin n := + c.clause[i].variableIndex + +def NormalizedClause.signs {n : Nat} (c : NormalizedClause n) : Triple := + (c.clause[0].positive, c.clause[1].positive, c.clause[2].positive) + +def NormalizedClause.restrict {n : Nat} (c : NormalizedClause n) + (assignment : Fin n → Bool) : Triple := + (assignment (c.variable 0), assignment (c.variable 1), assignment (c.variable 2)) + +@[simp] theorem localEval_restrict {n : Nat} (c : NormalizedClause n) + (assignment : Fin n → Bool) : + localEval c.signs (c.restrict assignment) = c.clause.eval assignment := by + rfl + +theorem variable_ne {n : Nat} (c : NormalizedClause n) {i j : Fin 3} + (different : i ≠ j) : c.variable i ≠ c.variable j := + fun same => different (c.distinct i j same) + +def NormalizedClause.extend {n : Nat} (c : NormalizedClause n) (t : Triple) : + Fin n → Bool := + fun v => if v = c.variable 0 then t.1 else if v = c.variable 1 then t.2.1 else t.2.2 + +@[simp] theorem restrict_extend {n : Nat} (c : NormalizedClause n) (t : Triple) : + c.restrict (c.extend t) = t := by + have h10 := variable_ne c (by decide : (1 : Fin 3) ≠ 0) + have h20 := variable_ne c (by decide : (2 : Fin 3) ≠ 0) + have h21 := variable_ne c (by decide : (2 : Fin 3) ≠ 1) + simp [NormalizedClause.restrict, NormalizedClause.extend, h10, h20, h21] + +theorem satisfying_label_realized {n : Nat} (c : NormalizedClause n) (t : Triple) + (valid : t ∈ satisfyingTriples c.signs) : + ∃ assignment : Fin n → Bool, + c.restrict assignment = t ∧ c.clause.eval assignment = true := by + refine ⟨c.extend t, restrict_extend c t, ?_⟩ + rw [← localEval_restrict, restrict_extend] + exact (mem_satisfyingTriples c.signs t).mp valid + +abbrev Occurrence (clauseCount : Nat) := Fin clauseCount × Fin 3 + +def occurrenceVariable {n m : Nat} (clauses : Fin m → NormalizedClause n) + (e : Occurrence m) : Fin n := + (clauses e.1).variable e.2 + +theorem occurrence_determined_by_endpoints {n m : Nat} + (clauses : Fin m → NormalizedClause n) (e e' : Occurrence m) + (sameClause : e.1 = e'.1) + (sameVariable : occurrenceVariable clauses e = occurrenceVariable clauses e') : + e = e' := by + rcases e with ⟨c, i⟩ + rcases e' with ⟨c', j⟩ + dsimp only at sameClause + subst c' + have samePosition : i = j := (clauses c).distinct i j sameVariable + subst j + rfl + +theorem projection_determined_by_endpoints {n m : Nat} + (clauses : Fin m → NormalizedClause n) (e e' : Occurrence m) + (sameClause : e.1 = e'.1) + (sameVariable : occurrenceVariable clauses e = occurrenceVariable clauses e') + (label : Triple) : label.at e.2 = label.at e'.2 := by + rw [occurrence_determined_by_endpoints clauses e e' sameClause sameVariable] + +def agreementCount {n : Nat} (c : NormalizedClause n) (label : Triple) + (assignment : Fin n → Bool) : Nat := + (if label.1 = assignment (c.variable 0) then 1 else 0) + + (if label.2.1 = assignment (c.variable 1) then 1 else 0) + + (if label.2.2 = assignment (c.variable 2) then 1 else 0) + +theorem agreementCount_le_three {n : Nat} (c : NormalizedClause n) (label : Triple) + (assignment : Fin n → Bool) : agreementCount c label assignment ≤ 3 := by + unfold agreementCount + split <;> split <;> split <;> omega + +theorem agreementCount_le_two_of_unsatisfied {n : Nat} + (c : NormalizedClause n) (label : Triple) (assignment : Fin n → Bool) + (valid : localEval c.signs label = true) + (unsatisfied : c.clause.eval assignment = false) : + agreementCount c label assignment ≤ 2 := by + by_cases h0 : label.1 = assignment (c.variable 0) + · by_cases h1 : label.2.1 = assignment (c.variable 1) + · by_cases h2 : label.2.2 = assignment (c.variable 2) + · have same : label = c.restrict assignment := + Prod.ext h0 (Prod.ext h1 h2) + rw [same, localEval_restrict, unsatisfied] at valid + contradiction + · simp [agreementCount, h0, h1, h2] + · unfold agreementCount + simp only [h0, h1, ↓reduceIte] + split <;> omega + · unfold agreementCount + simp only [h0, ↓reduceIte] + split <;> split <;> omega + +theorem agreementCount_le_two_add_satisfied {n : Nat} + (c : NormalizedClause n) (label : Triple) (assignment : Fin n → Bool) + (valid : localEval c.signs label = true) : + agreementCount c label assignment ≤ + 2 + (if c.clause.eval assignment then 1 else 0) := by + cases h : c.clause.eval assignment with + | false => simpa [h] using agreementCount_le_two_of_unsatisfied c label assignment valid h + | true => simpa [h] using agreementCount_le_three c label assignment + +theorem totalAgreement_le {n : Nat} (states : List (NormalizedClause n × Triple)) + (assignment : Fin n → Bool) + (valid : ∀ p ∈ states, localEval p.1.signs p.2 = true) : + (states.map (fun p => agreementCount p.1 p.2 assignment)).sum ≤ + 2 * states.length + (states.filter (fun p => p.1.clause.eval assignment)).length := by + induction states with + | nil => simp + | cons p rest ih => + have hp := agreementCount_le_two_add_satisfied p.1 p.2 assignment + (valid p (by simp)) + have hr := ih (fun p h => valid p (by simp [h])) + cases h : p.1.clause.eval assignment <;> + simp [h] at hp ⊢ <;> omega + +end PerfectCompleteness.SourceClause + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/SourceKeyBoundsLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/SourceKeyBoundsLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..d4e060bd37bbfc629013abd48e23a438431fba29 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/SourceKeyBoundsLemmas.lean @@ -0,0 +1,241 @@ +import OAI.Computability.PerfectCompleteness.Foundations.CanonicalEdgesLemmas +import OAI.Computability.PerfectCompleteness.Machines.FiniteBlockMachineLemmas +import OAI.Computability.PerfectCompleteness.Machines.SignedTupleBodyMachine +import OAI.Computability.PerfectCompleteness.Reduction.NormalizedTarget + +namespace OAI + + +namespace PerfectCompleteness.SourceKeyBounds + + +open CanonicalKeys CanonicalKeyShape ClauseSupport MixedSupport +open UniqueGamesTheorem.Foundations.Complexity +open scoped Classical + +noncomputable section + +def SlotIDsLe (bound : Nat) : Slot → Prop + | .clause occurrence variableIDs _ => occurrence ≤ bound ∧ ∀ i, variableIDs i ≤ bound + | .bit variableID => variableID ≤ bound + +theorem recover_entryID_le (bound : Nat) (slot : Slot) (support : SupportMode) + (bounded : SlotIDsLe bound slot) : KeyMetadataEncoding.entryID (recover slot support) ≤ bound := by + cases slot <;> cases support <;> + simp_all [SlotIDsLe, recover, KeyMetadataEncoding.entryID] + +theorem actualSlot_IDs_le (bound : Nat) (shape : Shape) (occurrence : Nat) + (variableIDs : Fin 3 → Nat) (occurrenceBound : occurrence ≤ bound) + (variableBounds : ∀ i, variableIDs i ≤ bound) : + SlotIDsLe bound (KeyMetadataMachine.actualSlot shape occurrence variableIDs) := by + cases shape <;> simp_all [KeyMetadataMachine.actualSlot, SlotIDsLe] + +variable {width : Nat} {Y : Type*} + +theorem retained_length_le (slots : Fin width → Slot) (support : Fin width → SupportMode) : + (retained slots support).length ≤ width := by + unfold retained + exact (List.length_filter_le _ _).trans_eq (by simp) + +theorem retained_entryID_le (slots : Fin width → Slot) (support : Fin width → SupportMode) + (bound : Nat) (bounded : ∀ i, SlotIDsLe bound (slots i)) + (entry : Fin width × SlotKey) (present : entry ∈ retained slots support) : + KeyMetadataEncoding.entryID entry.2 ≤ bound := by + unfold retained at present + obtain ⟨i, _, rfl⟩ := List.mem_map.mp (List.mem_filter.mp present).1 + exact recover_entryID_le bound (slots i) (support i) (bounded i) + +theorem key_retained_length (side : Side) (slots : Fin width → Slot) + (f : Assignment slots → Y) : (CanonicalKeys.key side slots f).retained.length ≤ width := by + change (retainedKeys slots f).length ≤ width + rw [retainedKeys_recover] + exact retained_length_le slots _ + +theorem key_entryID_le (side : Side) (slots : Fin width → Slot) + (f : Assignment slots → Y) (bound : Nat) (bounded : ∀ i, SlotIDsLe bound (slots i)) + (entry : Fin width × SlotKey) (present : entry ∈ (CanonicalKeys.key side slots f).retained) : + KeyMetadataEncoding.entryID entry.2 ≤ bound := by + change entry ∈ retainedKeys slots f at present + rw [retainedKeys_recover] at present + exact retained_entryID_le slots _ bound bounded entry present + +theorem variableCount_le_bits (input : NormalizedSourceInput.Input) : + NormalizedSourceInput.variableCount input ≤ (NormalizedSourceInput.bits input).length := by + rw [NormalizedSourceInput.bits_eq] + simp only [List.length_append, encodeWord_length] + omega + +theorem clauseCount_le_bits (input : NormalizedSourceInput.Input) : + NormalizedSourceInput.clauseCount input ≤ (NormalizedSourceInput.bits input).length := by + rw [NormalizedSourceInput.bits_eq] + simp only [List.length_append, encodeWord_length] + omega + +theorem source_variable_le_bits (input : NormalizedSourceInput.Input) + (index : Fin (NormalizedSourceInput.clauseCount input)) (slot : Fin 3) : + ((NormalizedSourceInput.clauses input index).variable slot).val ≤ + (NormalizedSourceInput.bits input).length := + (Nat.le_of_lt ((NormalizedSourceInput.clauses input index).variable slot).isLt).trans + (variableCount_le_bits input) + +variable {branch : Nat → Nat} {n t : Nat} + +theorem numberedSlots_IDs_le (input : NormalizedSourceInput.Input) + (source : PreliminarySampler.Questions branch n t (NormalizedSourceInput.clauseCount input)) + (position : Fin (TreeCanonical.locationCount branch n t)) : + SlotIDsLe (NormalizedSourceInput.bits input).length + (TreeCanonical.numberedSlots + (MetadataFreeSampler.sourceSlots (NormalizedSourceInput.clauses input) source) position) := by + let indices := SourceQuestionOrder.questionToTuple source + have restored : NormalizedTarget.tupleQuestion input indices = source := + SourceQuestionOrder.tupleToQuestion_questionToTuple source + have slotsEq := NormalizedTarget.numberedSlots_eq input indices position + rw [restored] at slotsEq + rw [slotsEq] + apply actualSlot_IDs_le + · exact (Nat.le_of_lt (indices position).isLt).trans (clauseCount_le_bits input) + · intro slot + rw [NormalizedTarget.parsedVariableIDs_eq] + exact source_variable_le_bits input (indices position) slot + +theorem source_key_retained_length (input : NormalizedSourceInput.Input) + (source : PreliminarySampler.Questions branch n t (NormalizedSourceInput.clauseCount input)) + (side : Side) + (f : TreeSourceSpaces.Domain + (MetadataFreeSampler.sourceSlots (NormalizedSourceInput.clauses input) source) → Y) : + (TreeCanonical.key side + (MetadataFreeSampler.sourceSlots (NormalizedSourceInput.clauses input) source) f).retained.length ≤ + TreeCanonical.locationCount branch n t := + key_retained_length side _ _ + +theorem source_key_entryID_le (input : NormalizedSourceInput.Input) + (source : PreliminarySampler.Questions branch n t (NormalizedSourceInput.clauseCount input)) + (side : Side) + (f : TreeSourceSpaces.Domain + (MetadataFreeSampler.sourceSlots (NormalizedSourceInput.clauses input) source) → Y) + (entry : Fin (TreeCanonical.locationCount branch n t) × SlotKey) + (present : entry ∈ (TreeCanonical.key side + (MetadataFreeSampler.sourceSlots (NormalizedSourceInput.clauses input) source) f).retained) : + KeyMetadataEncoding.entryID entry.2 ≤ (NormalizedSourceInput.bits input).length := + key_entryID_le side _ _ _ (numberedSlots_IDs_le input source) entry present + + +variable (input : NormalizedSourceInput.Input) (rows repeats : Nat → Nat) + +local notation "clauses" => NormalizedSourceInput.clauses input +local notation "F" => FinitePreliminaryCompletion.blockFamily clauses branch n t rows repeats +local notation "family" => PreliminarySampler.family clauses branch n t rows repeats + +theorem left_retained_length (e : PreliminarySampler.Raw clauses branch n t rows repeats) : + (CanonicalGame.leftKey F e).retained.length ≤ TreeCanonical.locationCount branch n t := by + rw [HierarchicalGame.leftKey_eq family e] + exact source_key_retained_length input e.1.1 .left _ + +theorem right_retained_length (e : PreliminarySampler.Raw clauses branch n t rows repeats) : + (CanonicalGame.rightKey F e).retained.length ≤ TreeCanonical.locationCount branch n t := by + rw [HierarchicalGame.rightKey_eq family e] + exact source_key_retained_length input e.1.1 .right _ + +theorem left_entryID_le (e : PreliminarySampler.Raw clauses branch n t rows repeats) + (entry : Fin (TreeCanonical.locationCount branch n t) × SlotKey) + (present : entry ∈ (CanonicalGame.leftKey F e).retained) : + KeyMetadataEncoding.entryID entry.2 ≤ (NormalizedSourceInput.bits input).length := by + rw [HierarchicalGame.leftKey_eq family e] at present + exact source_key_entryID_le input e.1.1 .left _ entry present + +theorem right_entryID_le (e : PreliminarySampler.Raw clauses branch n t rows repeats) + (entry : Fin (TreeCanonical.locationCount branch n t) × SlotKey) + (present : entry ∈ (CanonicalGame.rightKey F e).retained) : + KeyMetadataEncoding.entryID entry.2 ≤ (NormalizedSourceInput.bits input).length := by + rw [HierarchicalGame.rightKey_eq family e] at present + exact source_key_entryID_le input e.1.1 .right _ entry present + +end + +end PerfectCompleteness.SourceKeyBounds + + + +namespace PerfectCompleteness.SignedSourceCost + + +open UniqueGamesTheorem.Foundations.Complexity +open scoped BigOperators Classical + +noncomputable section + +variable {branch : Nat → Nat} {n t : Nat} {Extra : Type} [DecidableEq Extra] + +local notation "width" => TreeCanonical.locationCount branch n t + +theorem fieldValue_le_bits (input : NormalizedSourceInput.Input) + (indices : Fin width → Fin (NormalizedSourceInput.clauseCount input)) + (position : Fin width) (field : Fin 4) : + KeyMetadataMachine.fieldValue + (SignedTupleLayout.ids input.formula indices position) + (SignedTupleLayout.vars input.formula indices position) field ≤ + (NormalizedSourceInput.bits input).length := by + refine Fin.cases ?_ (fun slot => ?_) field + · change (indices position).val ≤ (NormalizedSourceInput.bits input).length + exact (Nat.le_of_lt (indices position).isLt).trans + (SourceKeyBounds.clauseCount_le_bits input) + · change (SignedTupleLayout.vars input.formula indices position slot) ≤ + (NormalizedSourceInput.bits input).length + exact SourceKeyBounds.source_variable_le_bits input (indices position) slot + +theorem prepared_metadata (input : NormalizedSourceInput.Input) + (indices : Fin width → Fin (NormalizedSourceInput.clauseCount input)) + (base : SignedTupleLayout.Tape width Extra → List Bool) + (hinput : SignedTupleLayout.Input input.formula indices base) + (data : SignedTupleBodyMachine.Data width) (position : Fin width) (field : Fin 4) : + SignedTupleBodyMachine.tapes SignedTupleLayout.Tape.edgeWork + SignedTupleLayout.Tape.edgeCount + (SignedTupleLayout.preparedTapes input.formula indices base) data + (KeyMetadataMachine.idTape (SignedTupleLayout.metadata position) field) = + encodeWord (KeyMetadataMachine.fieldValue + (SignedTupleLayout.ids input.formula indices position) + (SignedTupleLayout.vars input.formula indices position) field) := by + have unchanged : + SignedTupleBodyMachine.tapes SignedTupleLayout.Tape.edgeWork + SignedTupleLayout.Tape.edgeCount + (SignedTupleLayout.preparedTapes input.formula indices base) data + (KeyMetadataMachine.idTape (SignedTupleLayout.metadata position) field) = + SignedTupleLayout.preparedTapes input.formula indices base + (KeyMetadataMachine.idTape (SignedTupleLayout.metadata position) field) := by + apply SignedTupleBodyMachine.tapes_frame + all_goals + fin_cases field <;> + simp [KeyMetadataMachine.idTape, KeyMetadataMachine.idIndex, SignedTupleLayout.metadata] + exact unchanged.trans + (SignedTupleLayout.prepared_metadata input.formula indices base hinput position field) + +theorem prepared_sourceLength_le (input : NormalizedSourceInput.Input) + (indices : Fin width → Fin (NormalizedSourceInput.clauseCount input)) + (base : SignedTupleLayout.Tape width Extra → List Bool) + (hinput : SignedTupleLayout.Input input.formula indices base) + (data : SignedTupleBodyMachine.Data width) : + CanonicalKeyMachine.sourceLength SignedTupleLayout.metadata + (SignedTupleBodyMachine.tapes SignedTupleLayout.Tape.edgeWork + SignedTupleLayout.Tape.edgeCount + (SignedTupleLayout.preparedTapes input.formula indices base) data) ≤ + 4 * width * ((NormalizedSourceInput.bits input).length + 1) := by + calc + CanonicalKeyMachine.sourceLength SignedTupleLayout.metadata + (SignedTupleBodyMachine.tapes SignedTupleLayout.Tape.edgeWork + SignedTupleLayout.Tape.edgeCount + (SignedTupleLayout.preparedTapes input.formula indices base) data) ≤ + ∑ _ : Fin width, ∑ _ : Fin 4, ((NormalizedSourceInput.bits input).length + 1) := by + unfold CanonicalKeyMachine.sourceLength KeyMetadataMachine.sourceLength + apply Finset.sum_le_sum + intro position _ + apply Finset.sum_le_sum + intro field _ + rw [prepared_metadata input indices base hinput data position field, encodeWord_length] + exact Nat.add_le_add_right (fieldValue_le_bits input indices position field) 1 + _ = 4 * width * ((NormalizedSourceInput.bits input).length + 1) := by + simp [Nat.mul_assoc, Nat.mul_comm, Nat.mul_left_comm] + +end +end PerfectCompleteness.SignedSourceCost + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/SourceOddListsLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/SourceOddListsLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..4e451ac6a9a6579a9766de9822b15f3e983266ad --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/SourceOddListsLemmas.lean @@ -0,0 +1,340 @@ +import OAI.Computability.PerfectCompleteness.Construction.TreeSourceSpaces +import OAI.Computability.PerfectCompleteness.Foundations.CanonicalEdgesLemmas +import OAI.Computability.PerfectCompleteness.Reduction.OddListGame +import OAI.Computability.PerfectCompleteness.Repetition.SourceAmplification + +namespace OAI + + +namespace PerfectCompleteness.SourceOddLists + +open SourceClause OddLists +open UniqueGamesTheorem.Foundations.Games + +noncomputable section + +abbrev Occurrences (m t : Nat) := Fin t → Occurrence m +abbrev LeftLabels (t : Nat) := Fin t → Fin 7 +abbrev RightLabels (t : Nat) := Fin t → Bool + +def tupleLaw (m t : Nat) [NeZero m] : FiniteDistribution (Occurrences m t) := + (FiniteDistribution.uniform (Occurrence m)).iid t + +def left {m t : Nat} (e : Occurrences m t) : Fin t → Fin m := + fun i => (e i).1 + +def right {n m t : Nat} (clauses : Fin m → NormalizedClause n) + (e : Occurrences m t) : Fin t → Fin n := + fun i => occurrenceVariable clauses (e i) + +def projection {n m t : Nat} (clauses : Fin m → NormalizedClause n) + (e : Occurrences m t) (a : LeftLabels t) : RightLabels t := + fun i => SourceGame.projection clauses (e i) (a i) + +def base {n m : Nat} [NeZero m] (clauses : Fin m → NormalizedClause n) (t : Nat) : + OccurrenceGame (Occurrences m t) (Fin t → Fin m) (Fin t → Fin n) + (LeftLabels t) (RightLabels t) := + OddListGame.base (tupleLaw m t) left (right clauses) (projection clauses) + +theorem base_eq_repetition {n m : Nat} [NeZero m] + (clauses : Fin m → NormalizedClause n) (t : Nat) : + base clauses t = (SourceGame.game clauses).repetition t := by + unfold base OddListGame.base tupleLaw left right projection SourceGame.game + unfold OccurrenceGame.ofProjection OccurrenceGame.repetition + congr 1 + funext e a b + apply Bool.eq_iff_iff.mpr + simp only [decide_eq_true_eq] + constructor + · intro h + exact congrFun h + · intro h + exact funext h + +theorem base_endpointDetermined {n m : Nat} [NeZero m] + (clauses : Fin m → NormalizedClause n) (t : Nat) : + (base clauses t).EndpointDetermined := by + rw [base_eq_repetition] + exact OccurrenceGame.EndpointPresentation.determined + ((SourceGame.game clauses).repetition t) + (OccurrenceGame.EndpointPresentation.repetition + (SourceGame.game clauses) (SourceGame.presentation clauses) t) + +def game (s : Nat) {n m : Nat} [NeZero m] + (clauses : Fin m → NormalizedClause n) (t : Nat) : + OccurrenceGame (Occurrences m t) (Fin t → Fin m) (Fin t → Fin n) + (OddList s (LeftLabels t)) (OddList s (RightLabels t)) := + OddListGame.game s (tupleLaw m t) left (right clauses) (projection clauses) + +def tolerance (s : Nat) : ℚ := 1 / (2 * (s : ℚ) ^ 2) + +theorem tolerance_positive (s : Nat) [NeZero s] : 0 < tolerance s := by + have hs : (0 : ℚ) < s := Nat.cast_pos.mpr (Nat.pos_of_neZero s) + unfold tolerance + positivity + +def repetitionLength (γ : ℚ) (s : Nat) [NeZero s] + (hγ : 0 < γ) (hγ1 : γ ≤ 1) : Nat := + SourceAmplification.repetitionLength γ (tolerance s) hγ hγ1 (tolerance_positive s) + +theorem repetitionLength_positive (γ : ℚ) (s : Nat) [NeZero s] + (hγ : 0 < γ) (hγ1 : γ ≤ 1) : 0 < repetitionLength γ s hγ hγ1 := + (SourceAmplification.repetitionLength_spec γ (tolerance s) + hγ hγ1 (tolerance_positive s)).1 + +theorem amplified_base_gap {n m s : Nat} [NeZero m] [NeZero s] + (clauses : Fin m → NormalizedClause n) (γ : ℚ) + (hγ : 0 < γ) (hγ1 : γ ≤ 1) (gap : SourceAmplification.ClauseGap clauses γ) : + (s : ℝ) ^ 2 * (base clauses (repetitionLength γ s hγ hγ1)).value ≤ 1 / 2 := by + rw [base_eq_repetition] + have h : ((SourceGame.game clauses).repetition (repetitionLength γ s hγ hγ1)).value < + (tolerance s : ℝ) := + SourceAmplification.repeated_source_value_lt clauses γ (tolerance s) + hγ hγ1 (tolerance_positive s) gap + have hcast : (tolerance s : ℝ) = 1 / (2 * (s : ℝ) ^ 2) := by + simp only [tolerance, Rat.cast_div, Rat.cast_one, Rat.cast_mul, + Rat.cast_ofNat, Rat.cast_pow, Rat.cast_natCast] + rw [hcast] at h + have hspos : (0 : ℝ) < s := Nat.cast_pos.mpr (Nat.pos_of_neZero s) + have hs : 0 < (s : ℝ) ^ 2 := pow_pos hspos 2 + have hscaled := mul_lt_mul_of_pos_left h hs + have hcancel : (s : ℝ) ^ 2 * (1 / (2 * (s : ℝ) ^ 2)) = 1 / 2 := by + field_simp [ne_of_gt hspos] + exact (hscaled.trans_eq hcancel).le + +def alphabetLog (s t : Nat) : ℝ := + UniqueGamesTheorem.Foundations.Repetition.logTwo + ((Fintype.card (OddList s (LeftLabels t)) : ℝ) * + (Fintype.card (OddList s (RightLabels t)) : ℝ)) + +theorem exists_alphabet_budget (s t : Nat) : + ∃ L : Nat, 0 < L ∧ alphabetLog s t ≤ L := by + obtain ⟨L, hL⟩ := exists_nat_gt (max (alphabetLog s t) 0) + refine ⟨L, ?_, (le_max_left _ _).trans hL.le⟩ + have hpos : (0 : ℝ) < L := (le_max_right _ _).trans_lt hL + exact_mod_cast hpos + +theorem value_le_half {n m s : Nat} [NeZero m] [NeZero s] + (clauses : Fin m → NormalizedClause n) (γ : ℚ) + (hγ : 0 < γ) (hγ1 : γ ≤ 1) (gap : SourceAmplification.ClauseGap clauses γ) : + (game s clauses (repetitionLength γ s hγ hγ1)).value ≤ 1 / 2 := by + exact (OddListGame.value_le (s := s) + (tupleLaw m (repetitionLength γ s hγ hγ1)) left (right clauses) (projection clauses)).trans + (amplified_base_gap clauses γ hγ hγ1 gap) + +theorem repetition_halfRate {n m s L : Nat} [NeZero m] [NeZero s] + (clauses : Fin m → NormalizedClause n) (γ : ℚ) + (hγ : 0 < γ) (hγ1 : γ ≤ 1) (gap : SourceAmplification.ClauseGap clauses γ) + (hL : 0 < L) (alphabet : alphabetLog s (repetitionLength γ s hγ hγ1) ≤ L) + (k : Nat) : + ((game s clauses (repetitionLength γ s hγ hγ1)).repetition k).value ≤ + (RepetitionRate.halfRate L : ℝ) ^ k := + OddListGame.repetition_halfRate (s := s) (L := L) + (tupleLaw m (repetitionLength γ s hγ hγ1)) left (right clauses) (projection clauses) + (base_endpointDetermined clauses (repetitionLength γ s hγ hγ1)) + (amplified_base_gap clauses γ hγ hγ1 gap) hL alphabet k + +end +end PerfectCompleteness.SourceOddLists + + + +namespace PerfectCompleteness.SourceAnswerEquiv + +open SourceClause + +variable {v m t : Nat} + +def clauseAnswerEquiv (signs : Triple) : ClauseSupport.Answer signs ≃ Fin 7 where + toFun a := SourceGame.encodeLabel signs a.val ((mem_satisfyingTriples signs a.val).mp a.property) + invFun a := ⟨SourceGame.decodeLabel signs a, SourceGame.decodeLabel_mem signs a⟩ + left_inv a := by + apply Subtype.ext + exact SourceGame.decodeLabel_encodeLabel signs a.val + ((mem_satisfyingTriples signs a.val).mp a.property) + right_inv a := by + apply SourceGame.decodeLabel_injective signs + exact SourceGame.decodeLabel_encodeLabel signs (SourceGame.decodeLabel signs a) + (SourceGame.decodeLabel_legal signs a) + +@[simp] theorem clauseAnswerEquiv_symm_val (signs : Triple) (a : Fin 7) : + ((clauseAnswerEquiv signs).symm a).val = SourceGame.decodeLabel signs a := rfl + +@[simp] theorem clauseAnswerEquiv_decode (signs : Triple) (a : ClauseSupport.Answer signs) : + SourceGame.decodeLabel signs (clauseAnswerEquiv signs a) = a.val := + SourceGame.decodeLabel_encodeLabel signs a.val + ((mem_satisfyingTriples signs a.val).mp a.property) + +def leftSlots (clauses : Fin m → NormalizedClause v) (question : Fin t → Fin m) : + Fin t → MixedSupport.Slot := + fun i => SourceKeys.slot clauses (.clause (question i)) + +def rightSlots (clauses : Fin m → NormalizedClause v) (question : Fin t → Fin v) : + Fin t → MixedSupport.Slot := + fun i => SourceKeys.slot clauses (.variable (question i)) + +abbrev LeftDomain (clauses : Fin m → NormalizedClause v) (question : Fin t → Fin m) := + MixedSupport.Assignment (leftSlots clauses question) + +abbrev RightDomain (clauses : Fin m → NormalizedClause v) (question : Fin t → Fin v) := + MixedSupport.Assignment (rightSlots clauses question) + +instance rightDomainDecidableEq (clauses : Fin m → NormalizedClause v) + (question : Fin t → Fin v) : DecidableEq (RightDomain clauses question) := + inferInstanceAs (DecidableEq (Fin t → Bool)) + +def leftEquiv (clauses : Fin m → NormalizedClause v) (question : Fin t → Fin m) : + LeftDomain clauses question ≃ SourceOddLists.LeftLabels t where + toFun a i := clauseAnswerEquiv (clauses (question i)).signs (a i) + invFun a i := (clauseAnswerEquiv (clauses (question i)).signs).symm (a i) + left_inv a := by + funext i + exact (clauseAnswerEquiv (clauses (question i)).signs).symm_apply_apply (a i) + right_inv a := by + funext i + exact (clauseAnswerEquiv (clauses (question i)).signs).apply_symm_apply (a i) + +def rightEquiv (clauses : Fin m → NormalizedClause v) (question : Fin t → Fin v) : + RightDomain clauses question ≃ SourceOddLists.RightLabels t := + Equiv.refl _ + +@[simp] theorem leftEquiv_apply (clauses : Fin m → NormalizedClause v) + (question : Fin t → Fin m) (a : LeftDomain clauses question) (i : Fin t) : + leftEquiv clauses question a i = clauseAnswerEquiv (clauses (question i)).signs (a i) := rfl + +@[simp] theorem leftEquiv_symm_apply (clauses : Fin m → NormalizedClause v) + (question : Fin t → Fin m) (a : SourceOddLists.LeftLabels t) (i : Fin t) : + (leftEquiv clauses question).symm a i = + (clauseAnswerEquiv (clauses (question i)).signs).symm (a i) := rfl + +@[simp] theorem rightEquiv_apply (clauses : Fin m → NormalizedClause v) + (question : Fin t → Fin v) (a : RightDomain clauses question) : + rightEquiv clauses question a = a := rfl + +def slotProjection (clauses : Fin m → NormalizedClause v) + (e : SourceOddLists.Occurrences m t) : + ∀ i, MixedSupport.Projection (leftSlots clauses (SourceOddLists.left e) i) + (rightSlots clauses (SourceOddLists.right clauses e) i) := + fun i => (SourceKeys.Step.select (clauses := clauses) (e i).1 (e i).2).projection + +def actualProjection (clauses : Fin m → NormalizedClause v) + (e : SourceOddLists.Occurrences m t) : + LeftDomain clauses (SourceOddLists.left e) → + RightDomain clauses (SourceOddLists.right clauses e) := + MixedSupport.projectionMap (slotProjection clauses e) + +@[simp] theorem actualProjection_apply (clauses : Fin m → NormalizedClause v) + (e : SourceOddLists.Occurrences m t) + (a : LeftDomain clauses (SourceOddLists.left e)) (i : Fin t) : + actualProjection clauses e a i = (a i).val.at (e i).2 := rfl + +theorem projection_decode (clauses : Fin m → NormalizedClause v) + (e : SourceOddLists.Occurrences m t) (a : SourceOddLists.LeftLabels t) : + actualProjection clauses e ((leftEquiv clauses (SourceOddLists.left e)).symm a) = + (rightEquiv clauses (SourceOddLists.right clauses e)).symm + (SourceOddLists.projection clauses e a) := rfl + +theorem projection_encode (clauses : Fin m → NormalizedClause v) + (e : SourceOddLists.Occurrences m t) + (a : LeftDomain clauses (SourceOddLists.left e)) : + rightEquiv clauses (SourceOddLists.right clauses e) (actualProjection clauses e a) = + SourceOddLists.projection clauses e (leftEquiv clauses (SourceOddLists.left e) a) := by + have h := projection_decode clauses e (leftEquiv clauses (SourceOddLists.left e) a) + rw [Equiv.symm_apply_apply] at h + exact congrArg (rightEquiv clauses (SourceOddLists.right clauses e)) h + +def encodeOddList {s : Nat} (clauses : Fin m → NormalizedClause v) + (question : Fin t → Fin m) (L : OddLists.OddList s (LeftDomain clauses question)) : + OddLists.OddList s (SourceOddLists.LeftLabels t) := + ⟨L.val.map (leftEquiv clauses question).toEmbedding, by + simpa only [Finset.card_map] using L.property⟩ + +theorem encodeOddList_projection {s : Nat} (clauses : Fin m → NormalizedClause v) + (e : SourceOddLists.Occurrences m t) + (L : OddLists.OddList s (LeftDomain clauses (SourceOddLists.left e))) : + OddLists.OddList.map (SourceOddLists.projection clauses e) + (encodeOddList clauses (SourceOddLists.left e) L) = + OddLists.OddList.map (actualProjection clauses e) L := by + classical + let nativeProjection : LeftDomain clauses (SourceOddLists.left e) → + SourceOddLists.RightLabels t := actualProjection clauses e + change OddLists.OddList.map (SourceOddLists.projection clauses e) + (encodeOddList clauses (SourceOddLists.left e) L) = + OddLists.OddList.map nativeProjection L + have hcomm : ∀ a : LeftDomain clauses (SourceOddLists.left e), + SourceOddLists.projection clauses e (leftEquiv clauses (SourceOddLists.left e) a) = + nativeProjection a := fun a => (projection_encode clauses e a).symm + apply Subtype.ext + ext b + change b ∈ OddLists.parityPushforward (SourceOddLists.projection clauses e) + (L.val.map (leftEquiv clauses (SourceOddLists.left e)).toEmbedding) ↔ + b ∈ OddLists.parityPushforward nativeProjection L.val + have hfiber : + (L.val.map (leftEquiv clauses (SourceOddLists.left e)).toEmbedding).filter + (fun a => SourceOddLists.projection clauses e a = b) = + (L.val.filter (fun a => nativeProjection a = b)).map + (leftEquiv clauses (SourceOddLists.left e)).toEmbedding := by + rw [Finset.filter_map] + apply congrArg (fun K : Finset (LeftDomain clauses (SourceOddLists.left e)) => + K.map (leftEquiv clauses (SourceOddLists.left e)).toEmbedding) + ext a + rw [Finset.mem_filter, Finset.mem_filter] + constructor + · intro ha + exact ⟨ha.1, (hcomm a).symm.trans ha.2⟩ + · intro ha + exact ⟨ha.1, (hcomm a).trans ha.2⟩ + rw [OddLists.mem_parityPushforward, OddLists.mem_parityPushforward, + hfiber, Finset.card_map] + +theorem encodeOddList_accepted {s : Nat} (clauses : Fin m → NormalizedClause v) + (e : SourceOddLists.Occurrences m t) + (L : OddLists.OddList s (LeftDomain clauses (SourceOddLists.left e))) + (R : OddLists.OddList s (RightDomain clauses (SourceOddLists.right clauses e))) + (accepted : OddLists.OddList.map (actualProjection clauses e) L = R) : + OddLists.OddList.map (SourceOddLists.projection clauses e) + (encodeOddList clauses (SourceOddLists.left e) L) = R := + (encodeOddList_projection clauses e L).trans accepted + + +variable {branch : Nat → Nat} {n : Nat} + +def leftTreeSlots (clauses : Fin m → NormalizedClause v) + (questions : RecursiveSpaces.Slots branch n → Fin t → Fin m) : + RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot := + fun s => leftSlots clauses (questions s) + +def rightTreeSlots (clauses : Fin m → NormalizedClause v) + (questions : RecursiveSpaces.Slots branch n → Fin t → Fin v) : + RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot := + fun s => rightSlots clauses (questions s) + +def leftLeafEquiv (clauses : Fin m → NormalizedClause v) + (questions : RecursiveSpaces.Slots branch n → Fin t → Fin m) + (s : RecursiveSpaces.Slots branch n) : + TreeSourceSpaces.LeafDomain (leftTreeSlots clauses questions) s ≃ + SourceOddLists.LeftLabels t := + leftEquiv clauses (questions s) + +def rightLeafEquiv (clauses : Fin m → NormalizedClause v) + (questions : RecursiveSpaces.Slots branch n → Fin t → Fin v) + (s : RecursiveSpaces.Slots branch n) : + TreeSourceSpaces.LeafDomain (rightTreeSlots clauses questions) s ≃ + SourceOddLists.RightLabels t := + rightEquiv clauses (questions s) + +theorem leaf_projection_encode (clauses : Fin m → NormalizedClause v) + (occurrences : RecursiveSpaces.Slots branch n → SourceOddLists.Occurrences m t) + (s : RecursiveSpaces.Slots branch n) + (a : TreeSourceSpaces.LeafDomain + (leftTreeSlots clauses (fun j => SourceOddLists.left (occurrences j))) s) : + rightLeafEquiv clauses (fun j => SourceOddLists.right clauses (occurrences j)) s + (MixedSupport.projectionMap (slotProjection clauses (occurrences s)) a) = + SourceOddLists.projection clauses (occurrences s) + (leftLeafEquiv clauses (fun j => SourceOddLists.left (occurrences j)) s a) := + projection_encode clauses (occurrences s) a + + +end PerfectCompleteness.SourceAnswerEquiv + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/SourcePhysicalCallExtension.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/SourcePhysicalCallExtension.lean new file mode 100644 index 0000000000000000000000000000000000000000..74cbcc37306495661787be1ecb8fcf7ff5034195 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/SourcePhysicalCallExtension.lean @@ -0,0 +1,100 @@ +import OAI.Computability.PerfectCompleteness.Construction.SourcePhysicalTaggedChildren +import OAI.Computability.PerfectCompleteness.Sampling.CutCallOriginalLaw + +namespace OAI + +section + +namespace PerfectCompleteness.SourcePhysicalCallExtension + +open scoped Classical +open UniqueGamesTheorem.Foundations.Games +open RecursiveSpaces TreeSourceSpaces SourceChildKernel + +noncomputable section + +variable {branch : Nat → Nat} {n t v m : Nat} {C : Type*} [Fintype C] + (rows : Nat → Nat) (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch n) → Slots branch n) + +abbrev Tagged (sources : Sources (m := m) (t := t) designated) := + Σ flags : Fin (branch n) → Bool, + CutChildGrouping.Raw (C := C) + (SourcePhysicalTaggedChildren.slots clauses designated sources flags) rows + +def forget (sources : Sources (m := m) (t := t) designated) + (x : Tagged (C := Option C) rows clauses designated sources) : + Tagged (C := C) rows clauses designated sources := + ⟨x.1, CutCallExtension.original + (SourcePhysicalTaggedChildren.slots clauses designated sources x.1) rows x.2⟩ + +omit [Fintype C] in +@[simp] theorem forget_flags (sources : Sources (m := m) (t := t) designated) + (x : Tagged (C := Option C) rows clauses designated sources) : + (forget rows clauses designated sources x).1 = x.1 := rfl + +theorem forget_law (flag : Fin (branch n) → FiniteDistribution Bool) + (sources : Sources (m := m) (t := t) designated) : + (CompletionSoundness.sigmaLaw (FiniteProduct.law flag) (fun flags => + CutChildGrouping.rawLaw (C := Option C) + (SourcePhysicalTaggedChildren.slots clauses designated sources flags) rows)).pushforward + (forget rows clauses designated sources) = + CompletionSoundness.sigmaLaw (FiniteProduct.law flag) (fun flags => + CutChildGrouping.rawLaw (C := C) + (SourcePhysicalTaggedChildren.slots clauses designated sources flags) rows) := by + apply SigmaObservation.eq_of_probability_eq + intro event + rw [FiniteDistribution.probability_pushforward, + CompletionSoundness.sigmaLaw_probability, CompletionSoundness.sigmaLaw_probability] + apply FiniteDistribution.expectation_congr + intro flags + exact CutCallOriginalLaw.original_probability + (SourcePhysicalTaggedChildren.slots clauses designated sources flags) rows + (fun old => event ⟨flags, old⟩) + +theorem kernels_forget (flag : Fin (branch n) → FiniteDistribution Bool) + (sources : Sources (m := m) (t := t) designated) : + ((FiniteProduct.law (fun i => + kernel (C := Option C) (t := t) rows clauses designated flag i (sources i))).pushforward + (SourcePhysicalTaggedChildren.observe rows clauses designated sources)).pushforward + (forget rows clauses designated sources) = + (FiniteProduct.law (fun i => + kernel (C := C) (t := t) rows clauses designated flag i (sources i))).pushforward + (SourcePhysicalTaggedChildren.observe rows clauses designated sources) := by + rw [SourcePhysicalTaggedChildren.kernels_tagged, forget_law, + SourcePhysicalTaggedChildren.kernels_tagged] + +theorem kernels_observe_forget (flag : Fin (branch n) → FiniteDistribution Bool) + (sources : Sources (m := m) (t := t) designated) : + (FiniteProduct.law (fun i => + kernel (C := Option C) (t := t) rows clauses designated flag i (sources i))).pushforward + (fun raw => forget rows clauses designated sources + (SourcePhysicalTaggedChildren.observe rows clauses designated sources raw)) = + (FiniteProduct.law (fun i => + kernel (C := C) (t := t) rows clauses designated flag i (sources i))).pushforward + (SourcePhysicalTaggedChildren.observe rows clauses designated sources) := by + rw [← FiniteDistribution.pushforward_comp] + exact kernels_forget rows clauses designated flag sources + +theorem kernels_probability (flag : Fin (branch n) → FiniteDistribution Bool) + (sources : Sources (m := m) (t := t) designated) + (event : Tagged (C := C) rows clauses designated sources → Bool) : + (FiniteProduct.law (fun i => + kernel (C := Option C) (t := t) rows clauses designated flag i (sources i))).probability + (fun raw => event (forget rows clauses designated sources + (SourcePhysicalTaggedChildren.observe rows clauses designated sources raw))) = + (FiniteProduct.law (fun i => + kernel (C := C) (t := t) rows clauses designated flag i (sources i))).probability + (fun raw => event + (SourcePhysicalTaggedChildren.observe rows clauses designated sources raw)) := by + have h := congrArg (fun μ : FiniteDistribution + (Tagged (C := C) rows clauses designated sources) => μ.probability event) + (kernels_observe_forget (C := C) rows clauses designated flag sources) + simpa only [FiniteDistribution.probability_pushforward] using h + +end +end PerfectCompleteness.SourcePhysicalCallExtension + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/SourcePhysicalExteriorReplay.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/SourcePhysicalExteriorReplay.lean new file mode 100644 index 0000000000000000000000000000000000000000..e1c4113fd80f5b1cf477ca0cb1f834ebb739e688 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/SourcePhysicalExteriorReplay.lean @@ -0,0 +1,113 @@ +import OAI.Computability.PerfectCompleteness.Foundations.SourcePhysicalExteriorSwap +import OAI.Computability.PerfectCompleteness.Machines.SourcePhysicalTapeLaw + +namespace OAI + +section + +namespace PerfectCompleteness.SourcePhysicalExteriorReplay + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays + +variable {branch : Nat → Nat} {root h t : Nat} + (rows repeats : Nat → Nat) (p : Path branch root (h + 1)) + +private theorem splitTape_symm_heq + {slots target : Slots branch root → Fin t → MixedSupport.Slot} + (hslots : slots = target) + (external : WholeCutGrouping.Exterior rows repeats p slots) + (other : WholeCutGrouping.Exterior rows repeats p target) + (hext : HEq external other) + (children : CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) + (WholeCutGrouping.cutSlots p slots) rows) + (otherChildren : CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) + (WholeCutGrouping.cutSlots p target) rows) + (hchildren : ∀ child, HEq (children child) (otherChildren child)) : + HEq ((WholeCutGrouping.splitTape rows repeats p slots).symm (external, children)) + ((WholeCutGrouping.splitTape rows repeats p target).symm (other, otherChildren)) := by + cases hslots + have he : external = other := eq_of_heq hext + have hc : children = otherChildren := funext (fun child => eq_of_heq (hchildren child)) + cases he + cases hc + rfl + +theorem physicalTape_heq + (outside otherOutside : Slots branch root → Fin t → MixedSupport.Slot) + (placeholder otherPlaceholder inside : Slots branch (h + 1) → Fin t → MixedSupport.Slot) + (hfill : CutSlotAssembly.fill p outside inside = CutSlotAssembly.fill p otherOutside inside) + (external : CleanPhysicalReplay.Exterior rows repeats p outside placeholder) + (other : CleanPhysicalReplay.Exterior rows repeats p otherOutside otherPlaceholder) + (hext : HEq external other) + (children : CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) inside rows) : + HEq (CleanPhysicalReplay.physicalTape rows repeats p outside placeholder inside external children) + (CleanPhysicalReplay.physicalTape rows repeats p otherOutside otherPlaceholder inside other children) := by + apply splitTape_symm_heq rows repeats p hfill + · exact (cast_heq _ _).trans (hext.trans (cast_heq _ _).symm) + · intro child + exact (CleanPhysicalReplay.fillChild_heq rows repeats p outside inside child (children child)).trans + (CleanPhysicalReplay.fillChild_heq rows repeats p otherOutside inside child (children child)).symm + +private theorem collapse_heq + {slots target : Slots branch root → Fin t → MixedSupport.Slot} + (hslots : slots = target) + (tape : WholeCutSampler.Tape rows repeats p slots) + (other : WholeCutSampler.Tape rows repeats p target) (htape : HEq tape other) : + HEq (WholeCutSampler.collapse rows repeats p slots tape) + (WholeCutSampler.collapse rows repeats p target other) := by + cases hslots + cases htape + rfl + +private theorem evaluate_heq + {slots target : Slots branch root → Fin t → MixedSupport.Slot} + (hslots : slots = target) + (tape : WholeCutSampler.Tape rows repeats p slots) + (other : WholeCutSampler.Tape rows repeats p target) (htape : HEq tape other) : + HEq (WholeCutSampler.evaluate rows repeats p slots tape) + (WholeCutSampler.evaluate rows repeats p target other) := by + cases hslots + cases htape + rfl + +theorem collapsedTape_heq + (outside otherOutside : Slots branch root → Fin t → MixedSupport.Slot) + (placeholder otherPlaceholder inside : Slots branch (h + 1) → Fin t → MixedSupport.Slot) + (hfill : CutSlotAssembly.fill p outside inside = CutSlotAssembly.fill p otherOutside inside) + (external : CleanPhysicalReplay.Exterior rows repeats p outside placeholder) + (other : CleanPhysicalReplay.Exterior rows repeats p otherOutside otherPlaceholder) + (hext : HEq external other) + (children : CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) inside rows) : + HEq (WholeCutSampler.collapse rows repeats p (CutSlotAssembly.fill p outside inside) + (CleanPhysicalReplay.physicalTape rows repeats p outside placeholder inside external children)) + (WholeCutSampler.collapse rows repeats p (CutSlotAssembly.fill p otherOutside inside) + (CleanPhysicalReplay.physicalTape rows repeats p otherOutside otherPlaceholder inside other children)) := + collapse_heq rows repeats p hfill _ _ + (physicalTape_heq rows repeats p outside otherOutside placeholder otherPlaceholder inside + hfill external other hext children) + +theorem arrays_heq + (outside otherOutside : Slots branch root → Fin t → MixedSupport.Slot) + (placeholder otherPlaceholder inside : Slots branch (h + 1) → Fin t → MixedSupport.Slot) + (hfill : CutSlotAssembly.fill p outside inside = CutSlotAssembly.fill p otherOutside inside) + (external : CleanPhysicalReplay.Exterior rows repeats p outside placeholder) + (other : CleanPhysicalReplay.Exterior rows repeats p otherOutside otherPlaceholder) + (hext : HEq external other) + (children : CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) inside rows) : + HEq (WholeCutSampler.evaluate rows repeats p (CutSlotAssembly.fill p outside inside) + (CleanPhysicalReplay.physicalTape rows repeats p outside placeholder inside external children)) + (WholeCutSampler.evaluate rows repeats p (CutSlotAssembly.fill p otherOutside inside) + (CleanPhysicalReplay.physicalTape rows repeats p otherOutside otherPlaceholder inside other children)) := + evaluate_heq rows repeats p hfill _ _ + (physicalTape_heq rows repeats p outside otherOutside placeholder otherPlaceholder inside + hfill external other hext children) + +end +end PerfectCompleteness.SourcePhysicalExteriorReplay + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/SourcePhysicalExteriorSwap.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/SourcePhysicalExteriorSwap.lean new file mode 100644 index 0000000000000000000000000000000000000000..1306ab4fd36d74c413f66e9e20f7420ac0df28a1 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/SourcePhysicalExteriorSwap.lean @@ -0,0 +1,129 @@ +import OAI.Computability.PerfectCompleteness.Construction.SourceQuestionCutSplit +import OAI.Computability.PerfectCompleteness.Repetition.CleanPhysicalReplay +import OAI.Computability.PerfectCompleteness.Sampling.CutSamplerReplayTransportLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.SourcePhysicalExteriorSwap + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +variable {branch : Nat → Nat} {root h t v m : Nat} [NeZero m] + (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (p : Path branch root (h + 1)) + +def placeholder : Slots branch (h + 1) → Fin t → MixedSupport.Slot := + sourceSlots clauses (PreliminarySampler.endpoints (fun _ _ => (0 : Fin m))) + +def canonicalSlots (external : SourceQuestionCutSplit.OutsideQuestions p t m) : + Slots branch root → Fin t → MixedSupport.Slot := + sourceSlots clauses (PreliminarySampler.endpoints + (SourceQuestionCutSplit.join p (fun _ _ => (0 : Fin m)) external)) + +abbrev CanonicalExterior (external : SourceQuestionCutSplit.OutsideQuestions p t m) := + WholeCutGrouping.Exterior rows repeats p (canonicalSlots clauses p external) + +abbrev ActualExterior (questions : PreliminarySampler.Questions branch root t m) := + CleanPhysicalReplay.Exterior rows repeats p + (sourceSlots clauses (PreliminarySampler.endpoints questions)) + (sourceSlots clauses (PreliminarySampler.endpoints + (SourceQuestionCutSplit.restrict p questions))) + +theorem canonicalSlots_outside + (external : SourceQuestionCutSplit.OutsideQuestions p t m) + (leaf : SourceQuestionCutSplit.OutsideLeaf p) : + canonicalSlots clauses p external leaf.val = + fun coordinate => SourceKeys.slot clauses (.clause (external leaf coordinate)) := by + funext coordinate + change SourceKeys.slot clauses (.clause + (SourceQuestionCutSplit.join p (fun _ _ => (0 : Fin m)) external leaf.val coordinate)) = _ + rw [SourceQuestionCutSplit.join_outside] + +theorem exteriorSlots_eq + (questions : PreliminarySampler.Questions branch root t m) + (leaf : Slots branch root) (hleaf : WholeCutExteriorTransport.Outside p leaf) : + CutSlotAssembly.fill p + (sourceSlots clauses (PreliminarySampler.endpoints questions)) + (sourceSlots clauses (PreliminarySampler.endpoints + (SourceQuestionCutSplit.restrict p questions))) leaf = + canonicalSlots clauses p (SourceQuestionCutSplit.outside p questions) leaf := by + rw [CutSlotAssembly.fill_outside p _ _ leaf hleaf] + exact (canonicalSlots_outside clauses p + (SourceQuestionCutSplit.outside p questions) ⟨leaf, hleaf⟩).symm + +def toCanonical (questions : PreliminarySampler.Questions branch root t m) : + ActualExterior clauses rows repeats p questions ≃ + CanonicalExterior clauses rows repeats p (SourceQuestionCutSplit.outside p questions) := + WholeCutExteriorTransport.equiv rows repeats p _ _ + (exteriorSlots_eq clauses p questions) + +def fromCanonical (questions : PreliminarySampler.Questions branch root t m) : + CanonicalExterior clauses rows repeats p (SourceQuestionCutSplit.outside p questions) ≃ + ActualExterior clauses rows repeats p questions := + (toCanonical clauses rows repeats p questions).symm + +theorem toCanonical_heq (questions : PreliminarySampler.Questions branch root t m) + (external : ActualExterior clauses rows repeats p questions) : + HEq (toCanonical clauses rows repeats p questions external) external := + cast_heq _ _ + +theorem fromCanonical_heq (questions : PreliminarySampler.Questions branch root t m) + (external : CanonicalExterior clauses rows repeats p + (SourceQuestionCutSplit.outside p questions)) : + HEq (fromCanonical clauses rows repeats p questions external) external := by + exact (toCanonical_heq clauses rows repeats p questions + (fromCanonical clauses rows repeats p questions external)).symm.trans + (heq_of_eq ((toCanonical clauses rows repeats p questions).apply_symm_apply external)) + +theorem toCanonical_law (questions : PreliminarySampler.Questions branch root t m) : + (FiniteDistribution.uniform (ActualExterior clauses rows repeats p questions)).pushforward + (toCanonical clauses rows repeats p questions) = + FiniteDistribution.uniform (CanonicalExterior clauses rows repeats p + (SourceQuestionCutSplit.outside p questions)) := by + rw [← FiniteDistribution.transport_eq_pushforward] + exact UniformConditioning.uniform_transport (toCanonical clauses rows repeats p questions) + +theorem fromCanonical_law (questions : PreliminarySampler.Questions branch root t m) : + (FiniteDistribution.uniform (CanonicalExterior clauses rows repeats p + (SourceQuestionCutSplit.outside p questions))).pushforward + (fromCanonical clauses rows repeats p questions) = + FiniteDistribution.uniform (ActualExterior clauses rows repeats p questions) := by + rw [← FiniteDistribution.transport_eq_pushforward] + exact UniformConditioning.uniform_transport (fromCanonical clauses rows repeats p questions) + +theorem expectation_fromCanonical + (questions : PreliminarySampler.Questions branch root t m) + (value : ActualExterior clauses rows repeats p questions → ℝ) : + (FiniteDistribution.uniform (ActualExterior clauses rows repeats p questions)).expectation value = + (FiniteDistribution.uniform (CanonicalExterior clauses rows repeats p + (SourceQuestionCutSplit.outside p questions))).expectation + (fun external => value (fromCanonical clauses rows repeats p questions external)) := by + rw [← fromCanonical_law clauses rows repeats p questions, + FiniteDistribution.expectation_pushforward] + +theorem fill_eq (questions : PreliminarySampler.Questions branch root t m) + (inside : Slots branch (h + 1) → Fin t → MixedSupport.Slot) : + CutSlotAssembly.fill p (sourceSlots clauses (PreliminarySampler.endpoints questions)) inside = + CutSlotAssembly.fill p + (canonicalSlots clauses p (SourceQuestionCutSplit.outside p questions)) inside := by + funext leaf + by_cases hleaf : leaf ∈ Set.range p.slotEmbedding + · obtain ⟨s, rfl⟩ := hleaf + rw [CutSlotAssembly.fill_at_cut, CutSlotAssembly.fill_at_cut] + · rw [CutSlotAssembly.fill_outside p _ _ leaf hleaf, + CutSlotAssembly.fill_outside p _ _ leaf hleaf] + exact (canonicalSlots_outside clauses p + (SourceQuestionCutSplit.outside p questions) ⟨leaf, hleaf⟩).symm + +end +end PerfectCompleteness.SourcePhysicalExteriorSwap + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/SourcePhysicalSourceSwapLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/SourcePhysicalSourceSwapLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..f85dfa4b8fbe93e3e23c71fe9d7debddecafb5ab --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/SourcePhysicalSourceSwapLemmas.lean @@ -0,0 +1,281 @@ +import OAI.Computability.PerfectCompleteness.Construction.SourceQuestionRawSwap +import OAI.Computability.PerfectCompleteness.Decoding.SourceChildProjectionComparison +import OAI.Computability.PerfectCompleteness.Foundations.SourcePhysicalExteriorSwap +import OAI.Computability.PerfectCompleteness.Sampling.CommonProductVariationLemmas +import OAI.Computability.PerfectCompleteness.Sampling.SourcePhysicalWholeLaw + +namespace OAI + +section + +namespace PerfectCompleteness.SourcePhysicalSourceSwap + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +variable {branch : Nat → Nat} {root h t v m : Nat} [NeZero m] + (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (p : Path branch root (h + 1)) + (designated : Fin (branch h) → Slots branch h) + +abbrev Questions := PreliminarySampler.Questions branch root t m +abbrev Positions := SourceQuestionKernelJoint.ChoiceTuple (branch := branch) (n := h) (t := t) +abbrev Raw := SourceChildKernelJoint.RawTuple (C := WholeCutCalls.Index rows repeats p) + (t := t) rows clauses designated +abbrev ChildSample := SourceChildKernel.Sample (C := WholeCutCalls.Index rows repeats p) + (t := t) rows clauses designated + +omit [NeZero m] in +@[simp] theorem outside_join + (inside : PreliminarySampler.Questions branch (h + 1) t m) + (external : SourceQuestionCutSplit.OutsideQuestions p t m) : + SourceQuestionCutSplit.outside p (SourceQuestionCutSplit.join p inside external) = external := by + funext leaf + exact SourceQuestionCutSplit.join_outside p inside external leaf + +def joinedExterior + (inside : PreliminarySampler.Questions branch (h + 1) t m) + (external : SourceQuestionCutSplit.OutsideQuestions p t m) : + SourcePhysicalExteriorSwap.CanonicalExterior clauses rows repeats p external ≃ + SourcePhysicalExteriorSwap.ActualExterior clauses rows repeats p + (SourceQuestionCutSplit.join p inside external) := + (Equiv.cast (congrArg (SourcePhysicalExteriorSwap.CanonicalExterior clauses rows repeats p) + (outside_join p inside external).symm)).trans + (SourcePhysicalExteriorSwap.fromCanonical clauses rows repeats p + (SourceQuestionCutSplit.join p inside external)) + +theorem joinedExterior_law + (inside : PreliminarySampler.Questions branch (h + 1) t m) + (external : SourceQuestionCutSplit.OutsideQuestions p t m) : + (FiniteDistribution.uniform + (SourcePhysicalExteriorSwap.CanonicalExterior clauses rows repeats p external)).pushforward + (joinedExterior clauses rows repeats p inside external) = + FiniteDistribution.uniform (SourcePhysicalExteriorSwap.ActualExterior clauses rows repeats p + (SourceQuestionCutSplit.join p inside external)) := by + rw [← FiniteDistribution.transport_eq_pushforward] + exact UniformConditioning.uniform_transport (joinedExterior clauses rows repeats p inside external) + +theorem expectation_joinedExterior + (inside : PreliminarySampler.Questions branch (h + 1) t m) + (external : SourceQuestionCutSplit.OutsideQuestions p t m) + (value : SourcePhysicalExteriorSwap.ActualExterior clauses rows repeats p + (SourceQuestionCutSplit.join p inside external) → ℝ) : + (FiniteDistribution.uniform (SourcePhysicalExteriorSwap.ActualExterior clauses rows repeats p + (SourceQuestionCutSplit.join p inside external))).expectation value = + (FiniteDistribution.uniform + (SourcePhysicalExteriorSwap.CanonicalExterior clauses rows repeats p external)).expectation + (fun exterior => value (joinedExterior clauses rows repeats p inside external exterior)) := by + rw [← joinedExterior_law clauses rows repeats p inside external, + FiniteDistribution.expectation_pushforward] + +theorem expectation_swap + (flag : Fin (branch h) → FiniteDistribution Bool) + (value : (questions : Questions (branch := branch) (root := root) (t := t) (m := m)) → + Positions (branch := branch) (h := h) (t := t) → + SourcePhysicalExteriorSwap.ActualExterior clauses rows repeats p questions → + Raw clauses rows repeats p designated → ℝ) : + (PreliminarySampler.questionsLaw + (branch := branch) (n := root) (t := t) (m := m)).expectation + (fun questions => (SourceProjectedTag.positionLaw + (branch := branch) (n := h) (t := t)).expectation (fun positions => + (SourcePhysicalWholeLaw.rawLaw rows repeats p + (sourceSlots clauses (PreliminarySampler.endpoints questions)) + (sourceSlots clauses (PreliminarySampler.endpoints + (SourceQuestionCutSplit.restrict p questions))) + clauses designated flag (SourceQuestionKernelJoint.sources designated + (SourceQuestionCutSplit.restrict p questions) positions)).expectation + (fun sample => value questions positions sample.1 sample.2))) = + (FiniteDistribution.uniform (SourceQuestionCutSplit.OutsideQuestions p t m)).expectation + (fun external => (FiniteDistribution.uniform + (SourcePhysicalExteriorSwap.CanonicalExterior clauses rows repeats p external)).expectation + (fun exterior => (SourceChildKernel.originalLaw + (C := WholeCutCalls.Index rows repeats p) (t := t) + rows clauses designated flag).expectation (fun sample => + value (SourceQuestionCutSplit.join p + (SourceQuestionRawSwap.insideQuestions rows clauses designated sample) external) + (SourceQuestionRawSwap.positions rows clauses designated sample) + (joinedExterior clauses rows repeats p + (SourceQuestionRawSwap.insideQuestions rows clauses designated sample) + external exterior) + (SourceQuestionRawSwap.raw rows clauses designated sample)))) := by + let statistic := fun (questions : Questions (branch := branch) (root := root) (t := t) (m := m)) + (positions : Positions (branch := branch) (h := h) (t := t)) + (raw : Raw clauses rows repeats p designated) => + (FiniteDistribution.uniform + (SourcePhysicalExteriorSwap.ActualExterior clauses rows repeats p questions)).expectation + (fun external => value questions positions external raw) + calc + _ = (PreliminarySampler.questionsLaw + (branch := branch) (n := root) (t := t) (m := m)).expectation + (fun questions => (SourceProjectedTag.positionLaw + (branch := branch) (n := h) (t := t)).expectation (fun positions => + (SourceQuestionRawSwap.kernelLaw rows clauses designated flag + (SourceQuestionCutSplit.restrict p questions) positions).expectation + (statistic questions positions))) := by + apply FiniteDistribution.expectation_congr + intro questions + apply FiniteDistribution.expectation_congr + intro positions + rw [SourcePhysicalWholeLaw.rawLaw, FiniteDistribution.expectation_product] + exact FiniteDistribution.expectation_comm _ _ _ + _ = (FiniteDistribution.uniform (SourceQuestionCutSplit.OutsideQuestions p t m)).expectation + (fun external => (SourceChildKernel.originalLaw + (C := WholeCutCalls.Index rows repeats p) (t := t) + rows clauses designated flag).expectation (fun sample => + statistic (SourceQuestionCutSplit.join p + (SourceQuestionRawSwap.insideQuestions rows clauses designated sample) external) + (SourceQuestionRawSwap.positions rows clauses designated sample) + (SourceQuestionRawSwap.raw rows clauses designated sample))) := + SourceQuestionRawSwap.fullQuestions_expectation rows clauses designated flag p statistic + _ = _ := by + apply FiniteDistribution.expectation_congr + intro external + calc + _ = (SourceChildKernel.originalLaw (C := WholeCutCalls.Index rows repeats p) (t := t) + rows clauses designated flag).expectation (fun sample => + (FiniteDistribution.uniform + (SourcePhysicalExteriorSwap.CanonicalExterior clauses rows repeats p external)).expectation + (fun exterior => value (SourceQuestionCutSplit.join p + (SourceQuestionRawSwap.insideQuestions rows clauses designated sample) external) + (SourceQuestionRawSwap.positions rows clauses designated sample) + (joinedExterior clauses rows repeats p + (SourceQuestionRawSwap.insideQuestions rows clauses designated sample) + external exterior) + (SourceQuestionRawSwap.raw rows clauses designated sample))) := by + apply FiniteDistribution.expectation_congr + intro sample + exact expectation_joinedExterior clauses rows repeats p + (SourceQuestionRawSwap.insideQuestions rows clauses designated sample) external _ + _ = _ := FiniteDistribution.expectation_comm _ _ _ + +end +end PerfectCompleteness.SourcePhysicalSourceSwap + +end + +section + +namespace PerfectCompleteness.SourcePhysicalStoppedComparison + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +variable {branch : Nat → Nat} {root h t v m : Nat} + (rows repeats : Nat → Nat) (p : Path branch root (h + 1)) + (outside : Slots branch root → Fin t → MixedSupport.Slot) + (placeholder : Slots branch (h + 1) → Fin t → MixedSupport.Slot) + (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch h) → Slots branch h) + +abbrev Sources := SourceChildKernel.Sources (m := m) (t := t) designated + +abbrev NativeArrays (sources : Sources (m := m) (t := t) designated) := + Arrays (CutSlotAssembly.fill p outside + (SourceChildKernel.parentLeftSlots clauses designated sources)) rows + +def modifiedLaw (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) + (sources : Sources (m := m) (t := t) designated) : + FiniteDistribution (NativeArrays rows p outside clauses designated sources) := + (SourcePhysicalWholeLaw.rawLaw rows repeats p outside placeholder clauses designated + (fun _ => ProjectionPosterior.bernoulli β hβ hβ') sources).pushforward + (SourcePhysicalWholeLaw.observeLeft rows repeats p outside placeholder clauses designated sources) + +def stoppedLaw (sources : Sources (m := m) (t := t) designated) : + FiniteDistribution (NativeArrays rows p outside clauses designated sources) := + WholeArraySampler.law rows repeats p + (CutSlotAssembly.fill p outside (SourceChildKernel.parentLeftSlots clauses designated sources)) + +theorem conditional_variation (hbranch : 0 < branch h) + (sources : Sources (m := m) (t := t) designated) (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) : + (modifiedLaw rows repeats p outside placeholder clauses designated β hβ hβ' sources).totalVariation + (stoppedLaw rows repeats p outside clauses designated sources) ≤ + SourceChildProjectionComparison.error branch h t + (Fintype.card (WholeCutCalls.Index rows repeats p)) rows β := by + let μ := FiniteDistribution.uniform + (CleanPhysicalReplay.Exterior rows repeats p outside placeholder) + let P := SourcePhysicalWholeLaw.nativeBlockLaw rows repeats p clauses designated + (fun _ => ProjectionPosterior.bernoulli β hβ hβ') sources + let Q := CutChildGrouping.rawLaw (C := WholeCutCalls.Index rows repeats p) + (SourceChildKernel.parentLeftSlots clauses designated sources) rows + let evaluate := fun x : CleanPhysicalReplay.Exterior rows repeats p outside placeholder × + CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) + (SourceChildKernel.parentLeftSlots clauses designated sources) rows => + WholeCutSampler.evaluate rows repeats p + (CutSlotAssembly.fill p outside (SourceChildKernel.parentLeftSlots clauses designated sources)) + (CleanPhysicalReplay.physicalTape rows repeats p outside placeholder + (SourceChildKernel.parentLeftSlots clauses designated sources) x.1 x.2) + have hnative : P.totalVariation Q ≤ + SourceChildProjectionComparison.error branch h t + (Fintype.card (WholeCutCalls.Index rows repeats p)) rows β := by + have hh := SourceChildProjectionComparison.conditional_observed_variation + (C := WholeCutCalls.Index rows repeats p) rows clauses designated hbranch sources β hβ hβ' + (id : CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) + (SourceChildKernel.parentLeftSlots clauses designated sources) rows → _) + change (P.pushforward id).totalVariation (Q.pushforward id) ≤ _ at hh + rw [FiniteDistribution.pushforward_id P, FiniteDistribution.pushforward_id Q] at hh + exact hh + have hcompare := CommonProductVariation.observed_product_le_of_bound μ P Q evaluate hnative + have hmodified : modifiedLaw rows repeats p outside placeholder clauses designated β hβ hβ' sources = + (μ.product P).pushforward evaluate := + SourcePhysicalWholeLaw.observeLeft_law rows repeats p outside placeholder clauses designated + (fun _ => ProjectionPosterior.bernoulli β hβ hβ') sources + have hstopped : (μ.product Q).pushforward evaluate = + stoppedLaw rows repeats p outside clauses designated sources := + CleanPhysicalReplayLaw.evaluate_physicalTape_law rows repeats p outside placeholder + (SourceChildKernel.parentLeftSlots clauses designated sources) + rw [← hmodified, hstopped] at hcompare + exact hcompare + +abbrev Observation := Σ sources : Sources (m := m) (t := t) designated, + NativeArrays rows p outside clauses designated sources + +def sourceModifiedLaw (source : FiniteDistribution (Sources (m := m) (t := t) designated)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) : + FiniteDistribution (Observation rows p outside clauses designated) := + CompletionSoundness.sigmaLaw source + (modifiedLaw rows repeats p outside placeholder clauses designated β hβ hβ') + +def sourceStoppedLaw (source : FiniteDistribution (Sources (m := m) (t := t) designated)) : + FiniteDistribution (Observation rows p outside clauses designated) := + CompletionSoundness.sigmaLaw source (stoppedLaw rows repeats p outside clauses designated) + +theorem source_variation (source : FiniteDistribution (Sources (m := m) (t := t) designated)) + (hbranch : 0 < branch h) (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) : + (sourceModifiedLaw rows repeats p outside placeholder clauses designated source β hβ hβ').totalVariation + (sourceStoppedLaw rows repeats p outside clauses designated source) ≤ + SourceChildProjectionComparison.error branch h t + (Fintype.card (WholeCutCalls.Index rows repeats p)) rows β := by + rw [sourceModifiedLaw, sourceStoppedLaw, ConditionalVariation.sigma_totalVariation] + apply (SmallBias.expectation_mono source + (fun sources => conditional_variation rows repeats p outside placeholder clauses designated + hbranch sources β hβ hβ')).trans_eq + exact SmallBias.expectation_const source _ + +theorem probability_ge_sub (source : FiniteDistribution (Sources (m := m) (t := t) designated)) + (hbranch : 0 < branch h) (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) + (event : Observation rows p outside clauses designated → Bool) : + (sourceStoppedLaw rows repeats p outside clauses designated source).probability event - + SourceChildProjectionComparison.error branch h t + (Fintype.card (WholeCutCalls.Index rows repeats p)) rows β ≤ + (sourceModifiedLaw rows repeats p outside placeholder clauses designated source β hβ hβ').probability + event := by + have htv := source_variation rows repeats p outside placeholder clauses designated + source hbranch β hβ hβ' + have hp := FiniteDistribution.probability_le_add_totalVariation + (sourceStoppedLaw rows repeats p outside clauses designated source) + (sourceModifiedLaw rows repeats p outside placeholder clauses designated source β hβ hβ') event + rw [FiniteDistribution.totalVariation_comm] at hp + linarith + +end +end PerfectCompleteness.SourcePhysicalStoppedComparison + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/SourcePrefixComparison.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/SourcePrefixComparison.lean new file mode 100644 index 0000000000000000000000000000000000000000..927ea26edd85351263525e560cc0058ed34751e0 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/SourcePrefixComparison.lean @@ -0,0 +1,276 @@ +import OAI.Computability.PerfectCompleteness.Decoding.SourceChildProjectionComparison +import OAI.Computability.PerfectCompleteness.Foundations.OriginalPrefixContinuation +import OAI.Computability.PerfectCompleteness.Sampling.CommonProductVariationLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.SourcePrefixComparison + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open SourceChildKernel +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +noncomputable section + +private theorem variation_triangle {Ω : Type*} [Fintype Ω] + (P U Q : FiniteDistribution Ω) : + P.totalVariation Q ≤ P.totalVariation U + U.totalVariation Q := by + unfold FiniteDistribution.totalVariation + have h := Finset.sum_le_sum (s := Finset.univ) + (fun x _ => abs_sub_le (P.weight x) (U.weight x) (Q.weight x)) + rw [Finset.sum_add_distrib] at h + linarith + +private theorem sigma_product_forget {S R : Type*} {E : S → Type*} + [Fintype S] [Fintype R] [∀ s, Fintype (E s)] + (source : FiniteDistribution S) (exterior : (s : S) → FiniteDistribution (E s)) + (kernel : S → FiniteDistribution R) : + (CompletionSoundness.sigmaLaw source (fun s => (exterior s).product (kernel s))).pushforward + (fun z => (z.1, z.2.2)) = CleanConditioning.kernelJoint source kernel := by + apply SigmaObservation.eq_of_probability_eq + intro event + rw [FiniteDistribution.probability_pushforward, CompletionSoundness.sigmaLaw_probability, + CleanConditioning.probability_kernelJoint] + apply FiniteDistribution.expectation_congr + intro s + simpa only [FiniteDistribution.probability_pushforward] using + congrArg (fun law : FiniteDistribution R => law.probability (fun r => event (s, r))) + (FiniteDistribution.product_pushforward_snd (exterior s) (kernel s)) + +variable {branch : Nat → Nat} {n k t v m : Nat} {K : Type*} [Fintype K] + +def hiddenError (branch : Nat → Nat) (n t calls : Nat) (rows : Nat → Nat) : ℝ := + Real.sqrt ((ChildBlockCardinality.bound branch n t calls rows : ℝ) ^ 2 / branch n) / 2 + +def error (branch : Nat → Nat) (n t calls : Nat) (rows : Nat → Nat) (β : ℝ) : ℝ := + SourceChildProjectionComparison.error branch n t calls rows β + hiddenError branch n t calls rows + +variable (calls : Nat) (rows repeats : Nat → Nat) + (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch n) → Slots branch n) + +def nativeAssembledLaw (flag : Fin (branch n) → FiniteDistribution Bool) + (sources : Sources (m := m) (t := t) designated) : + FiniteDistribution (CutChildGrouping.Assembled (C := Fin calls) + (parentLeftSlots clauses designated sources) rows) := + (FiniteProduct.law (fun i => SourceChildNativeLaw.leftLaw (C := Fin calls) (t := t) + rows clauses designated flag i (sources i))).pushforward + (CutChildGrouping.assemble (C := Fin calls) (parentLeftSlots clauses designated sources) rows) + +def uniformLaw [NeZero m] : + FiniteDistribution (SourcePhysicalAssemblyLaw.Observation (C := Fin calls) (t := t) + rows clauses designated) := + CompletionSoundness.sigmaLaw (SourceChildQuestionLaw.sourceLaw m t designated) + (fun sources => FiniteDistribution.uniform + (CutChildGrouping.Assembled (C := Fin calls) (parentLeftSlots clauses designated sources) rows)) + +def continuedLaw [NeZero m] (ν : FiniteDistribution K) (q : K → Path branch n k) + (hbranch : 0 < branch n) : + FiniteDistribution (SourcePhysicalAssemblyLaw.Observation (C := Fin calls) (t := t) + rows clauses designated) := + CompletionSoundness.sigmaLaw (SourceChildQuestionLaw.sourceLaw m t designated) + (fun sources => OriginalPrefixContinuation.assembledLaw calls rows repeats + (parentLeftSlots clauses designated sources) ν q hbranch) + +theorem false_observation_law [NeZero m] : + (SourceChildKernel.originalLaw (C := Fin calls) (t := t) rows clauses designated + (fun _ => SourceChildNativeLaw.falseFlag)).pushforward + (SourcePhysicalAssemblyLaw.observe rows clauses designated) = + uniformLaw calls rows clauses designated := + SourcePhysicalAssemblyLaw.original_assembleLeft_false_law rows clauses designated + +theorem continued_uniform_variation [NeZero m] + (ν : FiniteDistribution K) (q : K → Path branch n k) (hbranch : 0 < branch n) : + (continuedLaw (t := t) calls rows repeats clauses designated ν q hbranch).totalVariation + (uniformLaw (t := t) calls rows clauses designated) ≤ hiddenError branch n t calls rows := by + simpa only [FiniteDistribution.pushforward_id, continuedLaw, uniformLaw, hiddenError] using + (ConditionalVariation.observed_sigma_le_const + (SourceChildQuestionLaw.sourceLaw m t designated) + (fun sources => OriginalPrefixContinuation.assembledLaw calls rows repeats + (parentLeftSlots clauses designated sources) ν q hbranch) + (fun sources => FiniteDistribution.uniform + (CutChildGrouping.Assembled (C := Fin calls) (parentLeftSlots clauses designated sources) rows)) + (hiddenError branch n t calls rows) + (fun sources => OriginalPrefixContinuation.assembledLaw_variation calls rows repeats + (parentLeftSlots clauses designated sources) ν q hbranch) + (id : SourcePhysicalAssemblyLaw.Observation (C := Fin calls) (t := t) + rows clauses designated → _)) + +theorem original_variation [NeZero m] (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) + (ν : FiniteDistribution K) (q : K → Path branch n k) (hbranch : 0 < branch n) : + ((SourceChildKernel.originalLaw (C := Fin calls) (t := t) rows clauses designated + (fun _ => ProjectionPosterior.bernoulli β hβ hβ')).pushforward + (SourcePhysicalAssemblyLaw.observe rows clauses designated)).totalVariation + (continuedLaw calls rows repeats clauses designated ν q hbranch) ≤ + error branch n t calls rows β := by + have hs := SourceChildProjectionComparison.original_observed_variation (C := Fin calls) + rows clauses designated hbranch β hβ hβ' + (id : SourcePhysicalAssemblyLaw.Observation (C := Fin calls) (t := t) + rows clauses designated → _) + simp only [id_eq, Fintype.card_fin] at hs + rw [false_observation_law] at hs + have ho := continued_uniform_variation (t := t) calls rows repeats clauses designated ν q hbranch + rw [FiniteDistribution.totalVariation_comm] at ho + exact (variation_triangle _ (uniformLaw calls rows clauses designated) _).trans (add_le_add hs ho) + +theorem original_observed_variation [NeZero m] {Γ : Type*} [Fintype Γ] + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) + (ν : FiniteDistribution K) (q : K → Path branch n k) (hbranch : 0 < branch n) + (observe : SourcePhysicalAssemblyLaw.Observation (C := Fin calls) (t := t) + rows clauses designated → Γ) : + ((SourceChildKernel.originalLaw (C := Fin calls) (t := t) rows clauses designated + (fun _ => ProjectionPosterior.bernoulli β hβ hβ')).pushforward + (fun sample => observe (SourcePhysicalAssemblyLaw.observe rows clauses designated sample))).totalVariation ((continuedLaw calls rows repeats clauses designated ν q hbranch).pushforward + observe) ≤ error branch n t calls rows β := by + rw [← FiniteDistribution.pushforward_comp + (SourceChildKernel.originalLaw (C := Fin calls) (t := t) rows clauses designated + (fun _ => ProjectionPosterior.bernoulli β hβ hβ')) + (SourcePhysicalAssemblyLaw.observe rows clauses designated) observe] + exact (DensityVariation.variation_pushforward_le _ _ observe).trans + (original_variation calls rows repeats clauses designated β hβ hβ' ν q hbranch) + +theorem conditional_variation (sources : Sources (m := m) (t := t) designated) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) + (ν : FiniteDistribution K) (q : K → Path branch n k) (hbranch : 0 < branch n) : + (nativeAssembledLaw calls rows clauses designated + (fun _ => ProjectionPosterior.bernoulli β hβ hβ') sources).totalVariation + (OriginalPrefixContinuation.assembledLaw calls rows repeats + (parentLeftSlots clauses designated sources) ν q hbranch) ≤ + error branch n t calls rows β := by + have hs := SourceChildProjectionComparison.conditional_assembled_variation (C := Fin calls) + rows clauses designated hbranch sources β hβ hβ' + have ho := OriginalPrefixContinuation.assembledLaw_variation calls rows repeats + (parentLeftSlots clauses designated sources) ν q hbranch + rw [FiniteDistribution.totalVariation_comm] at ho + simpa only [nativeAssembledLaw, error, hiddenError, Fintype.card_fin] using + (variation_triangle _ (FiniteDistribution.uniform + (CutChildGrouping.Assembled (C := Fin calls) (parentLeftSlots clauses designated sources) rows)) _).trans (add_le_add hs ho) + +section Exterior + +variable {E : Sources (m := m) (t := t) designated → Type*} [∀ sources, Fintype (E sources)] + +abbrev ExteriorRaw := + Σ sources : Sources (m := m) (t := t) designated, + E sources × SourceChildKernelJoint.RawTuple (C := Fin calls) (t := t) rows clauses designated + +abbrev ExteriorObservation := + Σ sources : Sources (m := m) (t := t) designated, + E sources × CutChildGrouping.Assembled (C := Fin calls) + (parentLeftSlots clauses designated sources) rows + +def originalExteriorLaw [NeZero m] + (flag : Fin (branch n) → FiniteDistribution Bool) + (exterior : (sources : Sources (m := m) (t := t) designated) → FiniteDistribution (E sources)) : + FiniteDistribution (ExteriorRaw calls rows clauses designated (E := E)) := + CompletionSoundness.sigmaLaw (SourceChildQuestionLaw.sourceLaw m t designated) + (fun sources => (exterior sources).product (FiniteProduct.law + (fun i => SourceChildKernel.kernel (C := Fin calls) (t := t) + rows clauses designated flag i (sources i)))) + +def observeExterior (sample : ExteriorRaw calls rows clauses designated (E := E)) : + ExteriorObservation calls rows clauses designated (E := E) := + ⟨sample.1, (sample.2.1, + SourcePhysicalAssemblyLaw.assembleLeft rows clauses designated sample.1 sample.2.2)⟩ + +theorem originalExteriorLaw_forget [NeZero m] + (flag : Fin (branch n) → FiniteDistribution Bool) + (exterior : (sources : Sources (m := m) (t := t) designated) → FiniteDistribution (E sources)) : + (originalExteriorLaw calls rows clauses designated flag exterior).pushforward + (fun sample => (SourceChildKernelJoint.groupEquiv rows clauses designated).symm + (sample.1, sample.2.2)) = + SourceChildKernel.originalLaw (C := Fin calls) (t := t) rows clauses designated flag := by + unfold originalExteriorLaw + rw [← FiniteDistribution.pushforward_comp + (CompletionSoundness.sigmaLaw (SourceChildQuestionLaw.sourceLaw m t designated) + (fun sources => (exterior sources).product (FiniteProduct.law + (fun i => SourceChildKernel.kernel (C := Fin calls) (t := t) + rows clauses designated flag i (sources i))))) + (fun sample => (sample.1, sample.2.2)) + (SourceChildKernelJoint.groupEquiv rows clauses designated).symm, + sigma_product_forget] + have hgroup : + (SourceChildKernel.originalLaw (C := Fin calls) (t := t) + rows clauses designated flag).pushforward + (SourceChildKernelJoint.groupEquiv rows clauses designated) = + CleanConditioning.kernelJoint (SourceChildQuestionLaw.sourceLaw m t designated) + (fun sources => FiniteProduct.law (fun i => + SourceChildKernel.kernel (C := Fin calls) (t := t) + rows clauses designated flag i (sources i))) := + SourceChildKernelJoint.originalLaw_group (C := Fin calls) (t := t) + rows clauses designated flag + rw [← hgroup, FiniteDistribution.pushforward_comp] + simp only [Equiv.symm_apply_apply] + exact FiniteDistribution.pushforward_id _ + +theorem originalExteriorLaw_observe [NeZero m] + (flag : Fin (branch n) → FiniteDistribution Bool) + (exterior : (sources : Sources (m := m) (t := t) designated) → FiniteDistribution (E sources)) : + (originalExteriorLaw calls rows clauses designated flag exterior).pushforward + (observeExterior calls rows clauses designated) = + CompletionSoundness.sigmaLaw (SourceChildQuestionLaw.sourceLaw m t designated) + (fun sources => (exterior sources).product + (nativeAssembledLaw calls rows clauses designated flag sources)) := by + unfold originalExteriorLaw observeExterior + refine (SigmaObservation.pushforward_fiber + (S := Sources (m := m) (t := t) designated) + (X := fun sources => E sources × + SourceChildKernelJoint.RawTuple (C := Fin calls) (t := t) rows clauses designated) + (Y := fun sources => E sources × CutChildGrouping.Assembled (C := Fin calls) + (parentLeftSlots clauses designated sources) rows) + (SourceChildQuestionLaw.sourceLaw m t designated) + (fun sources => (exterior sources).product (FiniteProduct.law + (fun i => SourceChildKernel.kernel (C := Fin calls) (t := t) + rows clauses designated flag i (sources i)))) + (fun sources sample => (sample.1, + SourcePhysicalAssemblyLaw.assembleLeft (C := Fin calls) (t := t) + rows clauses designated sources sample.2))).trans ?_ + apply congrArg (CompletionSoundness.sigmaLaw (SourceChildQuestionLaw.sourceLaw m t designated)) + funext sources + have h := FiniteDistribution.product_pushforward (exterior sources) + (FiniteProduct.law (fun i => SourceChildKernel.kernel (C := Fin calls) (t := t) + rows clauses designated flag i (sources i))) id + (SourcePhysicalAssemblyLaw.assembleLeft rows clauses designated sources) + simpa only [id_eq, FiniteDistribution.pushforward_id, + SourcePhysicalAssemblyLaw.kernels_assembleLeft, nativeAssembledLaw] using h + +def continuedExteriorLaw [NeZero m] + (exterior : (sources : Sources (m := m) (t := t) designated) → FiniteDistribution (E sources)) + (ν : FiniteDistribution K) (q : K → Path branch n k) (hbranch : 0 < branch n) : + FiniteDistribution (ExteriorObservation calls rows clauses designated (E := E)) := + CompletionSoundness.sigmaLaw (SourceChildQuestionLaw.sourceLaw m t designated) + (fun sources => (exterior sources).product + (OriginalPrefixContinuation.assembledLaw calls rows repeats + (parentLeftSlots clauses designated sources) ν q hbranch)) + +theorem exterior_observed_variation [NeZero m] {Γ : Type*} [Fintype Γ] + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) + (exterior : (sources : Sources (m := m) (t := t) designated) → FiniteDistribution (E sources)) + (ν : FiniteDistribution K) (q : K → Path branch n k) (hbranch : 0 < branch n) + (observe : ExteriorObservation calls rows clauses designated (E := E) → Γ) : + ((originalExteriorLaw calls rows clauses designated + (fun _ => ProjectionPosterior.bernoulli β hβ hβ') exterior).pushforward + (fun sample => observe (observeExterior calls rows clauses designated sample))).totalVariation + ((continuedExteriorLaw calls rows repeats clauses designated exterior ν q hbranch).pushforward + observe) ≤ error branch n t calls rows β := by + rw [← FiniteDistribution.pushforward_comp + (originalExteriorLaw calls rows clauses designated + (fun _ => ProjectionPosterior.bernoulli β hβ hβ') exterior) + (observeExterior calls rows clauses designated) observe, originalExteriorLaw_observe] + unfold continuedExteriorLaw + refine ConditionalVariation.observed_sigma_le_const + (SourceChildQuestionLaw.sourceLaw m t designated) _ _ _ ?_ observe + intro sources + rw [CommonProductVariation.product_totalVariation] + exact conditional_variation calls rows repeats clauses designated sources β hβ hβ' ν q hbranch + +end Exterior +end +end PerfectCompleteness.SourcePrefixComparison + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/SourceProjectedChoices.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/SourceProjectedChoices.lean new file mode 100644 index 0000000000000000000000000000000000000000..af2c6ec03f5990551f98ed60a6c9dd3d658b93c2 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/SourceProjectedChoices.lean @@ -0,0 +1,152 @@ +import OAI.Computability.PerfectCompleteness.Foundations.ProjectedCutChoices +import OAI.Computability.PerfectCompleteness.Foundations.SlotProjectedExperiment + +namespace OAI + +section + +namespace PerfectCompleteness.SourceProjectedChoices + +open RecursiveSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +noncomputable section + +variable {branch : Nat → Nat} {n t m v : Nat} + +abbrev Positions := + SourceQuestionPositionSplit.ChildPositions (branch := branch) (n := n) (t := t) + +abbrev Choices := + ProjectedCutChoices.Choices (Z := fun _ : Fin (branch n) => + Positions (branch := branch) (n := n) (t := t)) + +def tagEquiv : Choices (branch := branch) (n := n) (t := t) ≃ + SourceProjectedTag.Tag (branch := branch) (n := n) (t := t) where + toFun choices := (fun child => (choices child).2, fun child => (choices child).1) + invFun tag child := (tag.2 child, tag.1 child) + left_inv _ := rfl + right_inv _ := rfl + +def choiceLaw (_child : Fin (branch n)) : + FiniteDistribution (Positions (branch := branch) (n := n) (t := t)) := + FiniteDistribution.uniform _ + +theorem tagEquiv_law (flag : Fin (branch n) → FiniteDistribution Bool) : + (FiniteProduct.law (fun child => + (flag child).product (choiceLaw (t := t) child))).pushforward + (tagEquiv (branch := branch) (n := n) (t := t)) = + SourceProjectedTag.law (t := t) flag := by + rw [← FiniteDistribution.transport_eq_pushforward] + apply FiniteDistribution.eq_of_weight_eq + intro tag + change (∏ child : Fin (branch n), (flag child).weight (tag.2 child) * + (choiceLaw (t := t) child).weight (tag.1 child)) = + (∏ child : Fin (branch n), (choiceLaw (t := t) child).weight (tag.1 child)) * + ∏ child : Fin (branch n), (flag child).weight (tag.2 child) + rw [Finset.prod_mul_distrib, mul_comm] + +theorem choicesLaw_tagEquiv (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) : + (ProjectedCutChoices.choicesLaw + (choiceLaw (branch := branch) (n := n) (t := t)) β hβ hβ').pushforward + (tagEquiv (branch := branch) (n := n) (t := t)) = + SourceProjectedTag.law (t := t) + (fun _ : Fin (branch n) => ProjectionPosterior.bernoulli β hβ hβ') := + tagEquiv_law (t := t) (fun _ => ProjectionPosterior.bernoulli β hβ hβ') + +theorem tagLaw_choices (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) : + (SourceProjectedTag.law (t := t) + (fun _ : Fin (branch n) => ProjectionPosterior.bernoulli β hβ hβ')).pushforward + (tagEquiv (branch := branch) (n := n) (t := t)).symm = + ProjectedCutChoices.choicesLaw + (choiceLaw (branch := branch) (n := n) (t := t)) β hβ hβ' := by + rw [← choicesLaw_tagEquiv β hβ hβ', FiniteDistribution.pushforward_comp] + simp only [Equiv.symm_apply_apply] + exact FiniteDistribution.pushforward_id _ + +variable (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + +def projected (child : Fin (branch n)) + (positions : Positions (branch := branch) (n := n) (t := t)) : + Slots branch n → Fin t → MixedSupport.Slot := + fun leaf a => SlotProjectedExperiment.selectSlot (slots (child, leaf) a) (positions leaf a) + +def projection : ∀ child positions leaf a, + MixedSupport.Projection (childSlots slots child leaf a) + (projected slots child positions leaf a) := + fun child positions leaf a => + SlotProjectedExperiment.selectProjection (slots (child, leaf) a) (positions leaf a) + +theorem childDomain_eq (child : Fin (branch n)) (flag : Bool) + (positions : Positions (branch := branch) (n := n) (t := t)) + (leaf : Slots branch n) (a : Fin t) : + ProjectedCutChoices.childDomain slots (projected slots) child (flag, positions) leaf a = + SlotProjectedExperiment.flaggedSlot (slots (child, leaf) a) (positions leaf a) flag := by + cases flag <;> rfl + +theorem childProjection_heq (child : Fin (branch n)) (flag : Bool) + (positions : Positions (branch := branch) (n := n) (t := t)) + (leaf : Slots branch n) (a : Fin t) : + HEq (ProjectedCutChoices.childProjection slots (projected slots) (projection slots) + child (flag, positions) leaf a) + (SlotProjectedExperiment.flaggedProjection + (slots (child, leaf) a) (positions leaf a) flag) := by + cases flag <;> rfl + +theorem selectedSlots_tag + (tag : SourceProjectedTag.Tag (branch := branch) (n := n) (t := t)) : + ProjectedCutChoices.selectedSlots slots (projected slots) (tagEquiv.symm tag) = + SlotProjectedExperiment.mixedInside slots tag.1 tag.2 := by + funext leaf a + exact childDomain_eq slots leaf.1 (tag.2 leaf.1) (tag.1 leaf.1) leaf.2 a + +private theorem projection_family_heq + {left right₁ right₂ : Slots branch (n + 1) → Fin t → MixedSupport.Slot} + (hr : right₁ = right₂) + (p₁ : ∀ leaf a, MixedSupport.Projection (left leaf a) (right₁ leaf a)) + (p₂ : ∀ leaf a, MixedSupport.Projection (left leaf a) (right₂ leaf a)) + (hp : ∀ leaf a, HEq (p₁ leaf a) (p₂ leaf a)) : HEq p₁ p₂ := by + subst right₂ + apply heq_of_eq + funext leaf a + exact eq_of_heq (hp leaf a) + +theorem selectedProjection_tag + (tag : SourceProjectedTag.Tag (branch := branch) (n := n) (t := t)) : + HEq (ProjectedCutChoices.selectedProjection slots (projected slots) (projection slots) + (tagEquiv.symm tag)) + (SlotProjectedExperiment.insideProjection slots tag.1 tag.2) := by + apply projection_family_heq (selectedSlots_tag slots tag) + intro leaf a + exact childProjection_heq slots leaf.1 (tag.2 leaf.1) (tag.1 leaf.1) leaf.2 a + +variable (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch n) → Slots branch n) + (questions : SourceQuestionPositionSplit.Questions + (branch := branch) (n := n) (t := t) (m := m)) + +theorem selectedSlots_source + (tag : SourceProjectedTag.Tag (branch := branch) (n := n) (t := t)) : + ProjectedCutChoices.selectedSlots (SourceProjectedTag.originalSlots clauses questions) + (projected (SourceProjectedTag.originalSlots clauses questions)) (tagEquiv.symm tag) = + SourceProjectedTag.mixedInside clauses designated questions tag.1 tag.2 := + (selectedSlots_tag (SourceProjectedTag.originalSlots clauses questions) tag).trans + (SlotProjectedExperiment.mixedInside_source clauses designated questions tag.1 tag.2) + +theorem selectedProjection_source + (tag : SourceProjectedTag.Tag (branch := branch) (n := n) (t := t)) : + HEq (ProjectedCutChoices.selectedProjection + (SourceProjectedTag.originalSlots clauses questions) + (projected (SourceProjectedTag.originalSlots clauses questions)) + (projection (SourceProjectedTag.originalSlots clauses questions)) (tagEquiv.symm tag)) + (SourceProjectedTag.projection clauses designated questions tag.1 tag.2) := + (selectedProjection_tag (SourceProjectedTag.originalSlots clauses questions) tag).trans + (SlotProjectedExperiment.insideProjection_source clauses designated questions tag.1 tag.2) + +end +end PerfectCompleteness.SourceProjectedChoices + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/SourceProjectedTag.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/SourceProjectedTag.lean new file mode 100644 index 0000000000000000000000000000000000000000..d1840d0b3412db9360e2e7ad0ee51e22c6a6692a --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/SourceProjectedTag.lean @@ -0,0 +1,110 @@ +import OAI.Computability.PerfectCompleteness.Construction.SourceQuestionKernelJoint +import OAI.Computability.PerfectCompleteness.Sampling.WholeArrayHiddenLaw + +namespace OAI + +section + +namespace PerfectCompleteness.SourceProjectedTag + +noncomputable section + +open scoped Classical +open RecursiveSpaces +open UniqueGamesTheorem.Foundations.Games + +variable {branch : Nat → Nat} {n t m v : Nat} + +abbrev Flags := Fin (branch n) → Bool + +abbrev Tag := + SourceQuestionKernelJoint.ChoiceTuple (branch := branch) (n := n) (t := t) × + Flags (branch := branch) (n := n) + +def positionLaw : FiniteDistribution + (SourceQuestionKernelJoint.ChoiceTuple (branch := branch) (n := n) (t := t)) := + FiniteProduct.law (fun _ : Fin (branch n) => + FiniteDistribution.uniform + (SourceQuestionPositionSplit.ChildPositions (branch := branch) (n := n) (t := t))) + +def flagLaw (flag : Fin (branch n) → FiniteDistribution Bool) : + FiniteDistribution (Flags (branch := branch) (n := n)) := + FiniteProduct.law flag + +def law (flag : Fin (branch n) → FiniteDistribution Bool) : + FiniteDistribution (Tag (branch := branch) (n := n) (t := t)) := + (positionLaw (branch := branch) (n := n) (t := t)).product (flagLaw flag) + +def sourceFlagEquiv (designated : Fin (branch n) → Slots branch n) : + (SourceChildKernel.Sources (m := m) (t := t) designated × + Flags (branch := branch) (n := n)) ≃ + SourceQuestionPositionSplit.Questions (branch := branch) (n := n) (t := t) (m := m) × + Tag (branch := branch) (n := n) (t := t) := + (Equiv.prodCongr (SourceQuestionKernelJoint.sourceEquiv designated) (Equiv.refl _)).trans + (Equiv.prodAssoc _ _ _) + +@[simp] theorem sourceFlagEquiv_apply (designated : Fin (branch n) → Slots branch n) + (sources : SourceChildKernel.Sources (m := m) (t := t) designated) + (flags : Flags (branch := branch) (n := n)) : + sourceFlagEquiv designated (sources, flags) = + ((SourceQuestionKernelJoint.sourceEquiv designated sources).1, + ((SourceQuestionKernelJoint.sourceEquiv designated sources).2, flags)) := rfl + +@[simp] theorem sourceFlagEquiv_symm_apply (designated : Fin (branch n) → Slots branch n) + (q : SourceQuestionPositionSplit.Questions (branch := branch) (n := n) (t := t) (m := m)) + (tag : Tag (branch := branch) (n := n) (t := t)) : + (sourceFlagEquiv designated).symm (q, tag) = + (SourceQuestionKernelJoint.sources designated q tag.1, tag.2) := rfl + +theorem sourceFlagEquiv_law [NeZero m] + (designated : Fin (branch n) → Slots branch n) + (flag : Fin (branch n) → FiniteDistribution Bool) : + ((SourceChildQuestionLaw.sourceLaw m t designated).product (flagLaw flag)).pushforward + (sourceFlagEquiv (m := m) (t := t) designated) = + (PreliminarySampler.questionsLaw + (branch := branch) (n := n + 1) (t := t) (m := m)).product (law (t := t) flag) := by + exact WholeArrayHiddenLaw.product_split_first + (SourceChildQuestionLaw.sourceLaw m t designated) (flagLaw flag) + (PreliminarySampler.questionsLaw (branch := branch) (n := n + 1) (t := t) (m := m)) + (positionLaw (branch := branch) (n := n) (t := t)) + (SourceQuestionKernelJoint.sourceEquiv designated) + (SourceQuestionKernelJoint.sourceLaw_sourceEquiv designated) + +variable (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch n) → Slots branch n) + (q : SourceQuestionPositionSplit.Questions (branch := branch) (n := n) (t := t) (m := m)) + (choices : SourceQuestionKernelJoint.ChoiceTuple (branch := branch) (n := n) (t := t)) + (flags : Flags (branch := branch) (n := n)) + +def originalSlots : Slots branch (n + 1) → Fin t → MixedSupport.Slot := + HierarchicalArrays.sourceSlots clauses (PreliminarySampler.endpoints q) + +theorem parentLeftSlots_sources : + SourceChildKernel.parentLeftSlots clauses designated + (SourceQuestionKernelJoint.sources designated q choices) = + originalSlots clauses q := by + rw [SourceQuestionKernelJoint.sources_eq_join, + SourceQuestionPositionSplit.parentLeftSlots_join] + rfl + +def mixedInside : Slots branch (n + 1) → Fin t → MixedSupport.Slot := + fun leaf j => SourceChildKernel.mixedSlots clauses designated leaf.1 + (SourceQuestionKernelJoint.sources designated q choices leaf.1) (flags leaf.1) leaf.2 j + +def projection : ∀ leaf j, MixedSupport.Projection (originalSlots clauses q leaf j) + (mixedInside clauses designated q choices flags leaf j) := by + intro leaf j + have hslots := congrFun (congrFun (parentLeftSlots_sources clauses designated q choices) leaf) j + change SourceChildKernel.nativeSlots clauses designated leaf.1 + (SourceQuestionKernelJoint.sources designated q choices leaf.1) leaf.2 j = + originalSlots clauses q leaf j at hslots + rw [← hslots] + exact SourceChildKernel.projection clauses designated leaf.1 + (SourceQuestionKernelJoint.sources designated q choices leaf.1) (flags leaf.1) leaf.2 j + +end +end PerfectCompleteness.SourceProjectedTag + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/SourceProjectedWholeChoices.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/SourceProjectedWholeChoices.lean new file mode 100644 index 0000000000000000000000000000000000000000..58300ab326c563669ac6a1583e20aa77e38c4b09 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/SourceProjectedWholeChoices.lean @@ -0,0 +1,111 @@ +import OAI.Computability.PerfectCompleteness.Construction.StoppedProjectedBucketIndex +import OAI.Computability.PerfectCompleteness.Foundations.ProjectedWholeCut +import OAI.Computability.PerfectCompleteness.Foundations.SourceProjectedChoices + +namespace OAI + +section + +namespace PerfectCompleteness.SourceProjectedWholeChoices + +noncomputable section + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCutTape +open UniqueGamesTheorem.Foundations.Games + +variable {branch : Nat → Nat} {n i j t v m : Nat} + +abbrev choiceLaw (child : Fin (branch i)) : + FiniteDistribution (SourceProjectedChoices.Positions (branch := branch) (n := i) (t := t)) := + SourceProjectedChoices.choiceLaw child + +variable (clauses : Fin m → SourceClause.NormalizedClause v) + (rows : Nat → Nat) (hupper : j + 1 ≤ n) (hij : i < j) + (designated : Fin (branch i) → Slots branch i) + (hrows : ∀ k, 0 < rows (k + 1)) + (o : StoppedProjectedExperiment.Outer + (branch := branch) (n := n) (j := j) (t := t) (m := m)) + (lowerPref : GeometricCutSplit.Prefix branch (j + 1) (i + 1)) + +abbrev path := + (StoppedProjectedExperiment.upperPath hupper o).append + (GeometricCutSplit.prefixPath (Nat.succ_le_succ hij.le) lowerPref) + +abbrev nativeCutSlots := + cutSlots (path hupper hij o lowerPref) (StoppedProjectedExperiment.nativeSlots clauses o) + +abbrev projected := + SourceProjectedChoices.projected (nativeCutSlots clauses hupper hij o lowerPref) + +abbrev projection := + SourceProjectedChoices.projection (nativeCutSlots clauses hupper hij o lowerPref) + +private theorem filled_projection_heq (p : Path branch n (i + 1)) + (outside : Slots branch n → Fin t → MixedSupport.Slot) + (left right₁ right₂ : Slots branch (i + 1) → Fin t → MixedSupport.Slot) + (hleft : CutSlotAssembly.fill p outside left = outside) (hr : right₁ = right₂) + (q₁ : ∀ leaf a, MixedSupport.Projection (left leaf a) (right₁ leaf a)) + (q₂ : ∀ leaf a, MixedSupport.Projection (left leaf a) (right₂ leaf a)) + (hq : HEq q₁ q₂) : + HEq (fun leaf a => CutProjectionAssembly.castProjection + (congrFun (congrFun hleft leaf) a) rfl + (CutProjectionAssembly.fillProjection p outside left right₁ q₁ leaf a)) + (fun leaf a => CutProjectionAssembly.castProjection + (congrFun (congrFun hleft leaf) a) rfl + (CutProjectionAssembly.fillProjection p outside left right₂ q₂ leaf a)) := by + subst right₂ + have hq' : q₁ = q₂ := eq_of_heq hq + subst q₂ + rfl + +theorem fullSlots_eq + (choices : SourceProjectedChoices.Choices (branch := branch) (n := i) (t := t)) : + ProjectedWholeCut.fullSlots (path hupper hij o lowerPref) + (StoppedProjectedExperiment.nativeSlots clauses o) + (projected clauses hupper hij o lowerPref) choices = + StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated o + (StoppedProjectedBucketIndex.key rows hrows + (lowerPref, SourceProjectedChoices.tagEquiv choices)) := by + have hinside := SourceProjectedChoices.selectedSlots_source clauses designated + (StoppedProjectedExperiment.cutQuestions rows hupper hij o + (StoppedProjectedBucketIndex.key rows hrows + (lowerPref, SourceProjectedChoices.tagEquiv choices))) + (SourceProjectedChoices.tagEquiv choices) + simp only [Equiv.symm_apply_apply] at hinside + exact congrArg (CutSlotAssembly.fill (path hupper hij o lowerPref) + (StoppedProjectedExperiment.nativeSlots clauses o)) hinside + +theorem fullProjection_heq + (choices : SourceProjectedChoices.Choices (branch := branch) (n := i) (t := t)) : + HEq (ProjectedWholeCut.fullProjection (path hupper hij o lowerPref) + (StoppedProjectedExperiment.nativeSlots clauses o) + (projected clauses hupper hij o lowerPref) + (projection clauses hupper hij o lowerPref) choices) + (StoppedProjectedExperiment.projection clauses rows hupper hij designated o + (StoppedProjectedBucketIndex.key rows hrows + (lowerPref, SourceProjectedChoices.tagEquiv choices))) := by + have hinside := SourceProjectedChoices.selectedSlots_source clauses designated + (StoppedProjectedExperiment.cutQuestions rows hupper hij o + (StoppedProjectedBucketIndex.key rows hrows + (lowerPref, SourceProjectedChoices.tagEquiv choices))) + (SourceProjectedChoices.tagEquiv choices) + have hprojection := SourceProjectedChoices.selectedProjection_source clauses designated + (StoppedProjectedExperiment.cutQuestions rows hupper hij o + (StoppedProjectedBucketIndex.key rows hrows + (lowerPref, SourceProjectedChoices.tagEquiv choices))) + (SourceProjectedChoices.tagEquiv choices) + simp only [Equiv.symm_apply_apply] at hinside hprojection + exact filled_projection_heq (path hupper hij o lowerPref) + (StoppedProjectedExperiment.nativeSlots clauses o) + (nativeCutSlots clauses hupper hij o lowerPref) _ _ + (ProjectedWholeCut.fill_native (path hupper hij o lowerPref) + (StoppedProjectedExperiment.nativeSlots clauses o)) + hinside _ _ hprojection + +end +end PerfectCompleteness.SourceProjectedWholeChoices + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/SourceStrategy.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/SourceStrategy.lean new file mode 100644 index 0000000000000000000000000000000000000000..242bec0cd5c780c7026330987618a2626ebfb60f --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/SourceStrategy.lean @@ -0,0 +1,114 @@ +import OAI.Computability.PerfectCompleteness.Foundations.CanonicalEdgesLemmas +import OAI.Computability.PerfectCompleteness.Machines.DomainEncoding + +namespace OAI + +section + +namespace PerfectCompleteness.ReducedPartition + +variable {X W R Y Z : Type*} + +theorem fiber_eq_of_parts_eq_of_reduction_eq + (rX : X → R) (rW : W → R) (f : X → Y) (g : W → Z) + (hg : ConstantOnFibers rW g) (hparts : parts rX f = parts rW g) + (x : X) (w : W) (hpoint : rX x = rW w) : + fiber rX f x = fiber rW g w := by + have hmem : fiber rX f x ∈ parts rW g := by + rw [← hparts] + exact ⟨x, rfl⟩ + obtain ⟨w', hw'⟩ := hmem + have hw : rW w ∈ fiber rW g w' := by + rw [hw', ← hpoint] + exact self_mem_fiber rX f x + have hvalue : g w = g w' := (mem_fiber_iff rW g hg w w').mp hw + exact hw'.symm.trans (fiber_eq_of_output_eq rW g hvalue).symm + +end PerfectCompleteness.ReducedPartition + +namespace PerfectCompleteness.SourceKeys + +open SourceClause ClauseSupport MixedSupport CanonicalKeys + +variable {v m n : Nat} {C Y Z : Type*} + +def assignmentAt (assignment : Fin v → Bool) (j : Nat) : Bool := + if h : j < v then assignment ⟨j, h⟩ else false + +@[simp] theorem assignmentAt_fin (assignment : Fin v → Bool) (j : Fin v) : + assignmentAt assignment j.val = assignment j := by + simp [assignmentAt, j.isLt] + +def valueOfKey (clauses : Fin m → NormalizedClause v) (assignment : Fin v → Bool) : + SlotKey → ReducedValue + | .dropped => .dropped + | .bit j => .bit (assignmentAt assignment j) + | .full c _ => + .full (if h : c < m then (clauses ⟨c, h⟩).restrict assignment else (false, false, false)) + +theorem localReduction_endpointValue (clauses : Fin m → NormalizedClause v) + (assignment : Fin v → Bool) (hsat : ∀ c, (clauses c).clause.eval assignment = true) + (s : Endpoint v m) (f : C → (slot clauses s).Domain → Y) : + localReduction (slot clauses s) f (endpointValue clauses assignment hsat s) = + valueOfKey clauses assignment (localKey (slot clauses s) f) := by + classical + cases s with + | clause c => + change C → Answer (clauses c).signs → Y at f + change clauseReduction f (endpointValue clauses assignment hsat (.clause c)) = + valueOfKey clauses assignment + (clauseKey c.val (fun i => ((clauses c).variable i).val) f) + cases hm : clauseMode f with + | dropped => simp [clauseReduction, clauseKey, hm, reduceByMode, valueOfKey] + | bit i => + simp only [clauseReduction, clauseKey, hm, reduceByMode, valueOfKey, assignmentAt_fin] + change ReducedValue.bit (((clauses c).restrict assignment).at i) = + ReducedValue.bit (assignment ((clauses c).variable i)) + exact congrArg ReducedValue.bit (coordinate_restrict (clauses c) assignment i) + | full => + simp [clauseReduction, clauseKey, hm, reduceByMode, valueOfKey, c.isLt, endpointValue] + | «variable» j => + change C → Bool → Y at f + change bitReduction f (assignment j) = valueOfKey clauses assignment (bitKey j.val f) + by_cases hu : Unused f + · simp [bitReduction, bitKey, hu, valueOfKey] + · simp [bitReduction, bitKey, hu, valueOfKey] + +theorem reduction_realizingAssignment (clauses : Fin m → NormalizedClause v) + (assignment : Fin v → Bool) (hsat : ∀ c, (clauses c).clause.eval assignment = true) + (endpoints : Fin n → Endpoint v m) + (f : Assignment (slot clauses ∘ endpoints) → Y) : + reduction (slot clauses ∘ endpoints) f (realizingAssignment clauses assignment hsat endpoints) = + fun i => valueOfKey clauses assignment (keyFields (slot clauses ∘ endpoints) f i) := by + funext i + exact localReduction_endpointValue clauses assignment hsat (endpoints i) + (sectionFunction (slot clauses ∘ endpoints) f i) + +theorem evaluated_label_eq_of_key_eq (clauses : Fin m → NormalizedClause v) + (assignment : Fin v → Bool) (hsat : ∀ c, (clauses c).clause.eval assignment = true) + (side side' : Side) (source target : Fin n → Endpoint v m) + (f : Assignment (slot clauses ∘ source) → Y) + (g : Assignment (slot clauses ∘ target) → Z) + (hkey : key side (slot clauses ∘ source) f = key side' (slot clauses ∘ target) g) : + (evaluateLabel (slot clauses ∘ source) f + (realizingAssignment clauses assignment hsat source)).val = + (evaluateLabel (slot clauses ∘ target) g + (realizingAssignment clauses assignment hsat target)).val := by + have hfields : keyFields (slot clauses ∘ source) f = keyFields (slot clauses ∘ target) g := + DomainEncoding.keyFields_eq_of_retainedKeys_eq _ _ f g + (congrArg (fun k : Key n => k.retained) hkey) + have hparts : partition (slot clauses ∘ source) f = partition (slot clauses ∘ target) g := + congrArg (fun k : Key n => k.partition) hkey + have hpoint : + reduction (slot clauses ∘ source) f (realizingAssignment clauses assignment hsat source) = + reduction (slot clauses ∘ target) g (realizingAssignment clauses assignment hsat target) := by + rw [reduction_realizingAssignment, reduction_realizingAssignment, hfields] + exact ReducedPartition.fiber_eq_of_parts_eq_of_reduction_eq + (reduction (slot clauses ∘ source) f) (reduction (slot clauses ∘ target) g) f g + (constantOnFibers (slot clauses ∘ target) g) hparts _ _ hpoint + +end PerfectCompleteness.SourceKeys + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/SourceTupleData.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/SourceTupleData.lean new file mode 100644 index 0000000000000000000000000000000000000000..3997b51afe01b9b7ebc281cbd32396200da32cad --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/SourceTupleData.lean @@ -0,0 +1,151 @@ +import Mathlib.Tactic.DeriveFintype +import OAI.Computability.PerfectCompleteness.Machines.SourceCoordinateMachine + +namespace OAI + + +namespace PerfectCompleteness.SourceTupleData + + +open UniqueGamesTheorem.Foundations Target + +inductive Tape (width : Nat) where + | table + | digit (position : Fin width) + | work (slot : Fin 5) + | variableName (position : Fin width) (slot : Fin 3) + deriving DecidableEq, Fintype + +variable {width : Nat} + +def localTape (position : Fin width) : Fin 10 → Tape width + | 0 => .table + | 1 => .digit position + | 2 => .work 0 + | 3 => .work 1 + | 4 => .work 2 + | 5 => .work 3 + | 6 => .work 4 + | 7 => .variableName position 0 + | 8 => .variableName position 1 + | 9 => .variableName position 2 + +theorem localTape_injective (position : Fin width) : Function.Injective (localTape position) := by + intro i j same + fin_cases i <;> fin_cases j <;> simp [localTape] at same ⊢ + +def placedTape {K : Type} (place : Tape width → K) (position : Fin width) : Fin 10 → K := + fun slot => place (localTape position slot) + +theorem placedTape_injective {K : Type} (place : Tape width → K) + (distinct : Function.Injective place) (position : Fin width) : + Function.Injective (placedTape place position) := + distinct.comp (localTape_injective position) + +def selectedClause (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) (position : Fin width) : + Clause formula.variables := formula.clauses[(indices position).val] + +def «stacks» (formula : Formula) (indices : Fin width → Fin formula.clauses.length) + (prepared : Fin width → Bool) : Tape width → List Bool + | .table => SourceOccurrenceEncoding.bits formula + | .digit position => List.replicate (indices position).val true + | .work _ => [] + | .variableName position slot => + if prepared position then + NormalizationReadMachine.clauseCounters (selectedClause formula indices position) slot + else [] + +@[simp] theorem table_at (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) (prepared : Fin width → Bool) : + «stacks» formula indices prepared .table = SourceOccurrenceEncoding.bits formula := rfl + +@[simp] theorem digits_at (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) (prepared : Fin width → Bool) + (position : Fin width) : + «stacks» formula indices prepared (.digit position) = + List.replicate (indices position).val true := rfl + +@[simp] theorem work_at (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) (prepared : Fin width → Bool) + (slot : Fin 5) : «stacks» formula indices prepared (.work slot) = [] := rfl + +@[simp] theorem variables_at (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) (prepared : Fin width → Bool) + (position : Fin width) (slot : Fin 3) : + «stacks» formula indices prepared (.variableName position slot) = + if prepared position then + List.replicate (selectedClause formula indices position)[slot].variableIndex.val true + else [] := rfl + +theorem coordinate_table (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) (prepared : Fin width → Bool) + (position : Fin width) : + «stacks» formula indices prepared (localTape position 0) = + SourceOccurrenceEncoding.bits formula := rfl + +theorem coordinate_digit (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) (prepared : Fin width → Bool) + (position : Fin width) : + «stacks» formula indices prepared (localTape position 1) = + List.replicate (indices position).val true := rfl + +theorem coordinate_initial_empty (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) (prepared : Fin width → Bool) + (position : Fin width) (fresh : prepared position = false) + (slot : Fin 10) (work : 2 ≤ slot.val) : + «stacks» formula indices prepared (localTape position slot) = [] := by + fin_cases slot <;> simp [localTape, «stacks», fresh] at work ⊢ + +theorem resultTapes_eq (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) (prepared : Fin width → Bool) + (position : Fin width) (_fresh : prepared position = false) : + SourceCoordinateMachine.resultTapes (localTape position) («stacks» formula indices prepared) + (selectedClause formula indices position) = + «stacks» formula indices (Function.update prepared position true) := by + funext key + cases key with + | table => + simp [SourceCoordinateMachine.resultTapes, NormalizationReadMachine.tapes, + SourceCoordinateMachine.readerTapes, SourceCoordinateMachine.readerMap, localTape, «stacks»] + | digit other => + simp [SourceCoordinateMachine.resultTapes, NormalizationReadMachine.tapes, + SourceCoordinateMachine.readerTapes, SourceCoordinateMachine.readerMap, localTape, «stacks»] + | work slot => + fin_cases slot <;> + simp [SourceCoordinateMachine.resultTapes, NormalizationReadMachine.tapes, + SourceCoordinateMachine.readerTapes, SourceCoordinateMachine.readerMap, localTape, «stacks»] + | variableName other slot => + by_cases same : other = position + · subst other + fin_cases slot <;> + simp [SourceCoordinateMachine.resultTapes, NormalizationReadMachine.tapes, + SourceCoordinateMachine.readerTapes, SourceCoordinateMachine.readerMap, + localTape, «stacks»] + · simp [SourceCoordinateMachine.resultTapes, NormalizationReadMachine.tapes, + SourceCoordinateMachine.readerTapes, SourceCoordinateMachine.readerMap, + localTape, «stacks», same] + +def shapes (formula : Formula) (indices : Fin width → Fin formula.clauses.length) + (initialShapes : Fin width → CanonicalKeyShape.Shape) (prepared : Fin width → Bool) : + Fin width → CanonicalKeyShape.Shape := + fun position => if prepared position then + SourceClauseReaderMachine.clauseShape (selectedClause formula indices position) + else initialShapes position + +theorem shapes_update (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) + (initialShapes : Fin width → CanonicalKeyShape.Shape) (prepared : Fin width → Bool) + (position : Fin width) : + Function.update (shapes formula indices initialShapes prepared) position + (SourceClauseReaderMachine.clauseShape (selectedClause formula indices position)) = + shapes formula indices initialShapes (Function.update prepared position true) := by + funext other + by_cases same : other = position + · subst other + simp [shapes] + · simp [shapes, same] + +end PerfectCompleteness.SourceTupleData + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/SourceTuplePlacement.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/SourceTuplePlacement.lean new file mode 100644 index 0000000000000000000000000000000000000000..c38e0b03e6bcf59ca330e22c2ca8d43df34f2520 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/SourceTuplePlacement.lean @@ -0,0 +1,149 @@ +import OAI.Computability.PerfectCompleteness.Machines.SourceTupleMachine +import OAI.Computability.UniqueGames.Machines.MachineCloudPadding + +namespace OAI + + +namespace PerfectCompleteness.SourceTuplePlacement + + +open Turing UniqueGamesTheorem.Foundations Complexity Target +open MachineComposition + +open MachineCloudPadding + +abbrev Tape (width : Nat) := SourceTupleData.Tape width +abbrev Label (width : Nat) := SourceTupleMachine.Label (List.finRange width) +abbrev State (width : Nat) (A : Type) := SourceTupleMachine.State width A +abbrev Shape := CanonicalKeyShape.Shape +abbrev Signs := NormalizationReadMachine.Signs +abbrev Alphabet {K : Type} (_ : K) := Bool + +variable {width : Nat} {K Λ A : Type} + +def nativeProgram : Label width → + TM2.Stmt (Alphabet (K := Tape width)) (Label width) (State width A) := + SourceTupleMachine.instruction (List.finRange width) id none none + +def instruction (tape : Tape width → K) (labels : Label width → Λ) (exit : Option Λ) : + Label width → TM2.Stmt (Alphabet (K := K)) Λ (State width A) := + fun label => Placement.statement tape labels exit (nativeProgram label) + +def entry (labels : Label width → Λ) (exit : Option Λ) : Option Λ := + Placement.label labels exit + (SourceTupleMachine.entry (List.finRange width) id none) + +def tapes (view : K → Option (Tape width)) (extra : K → List Bool) + (formula : Formula) (indices : Fin width → Fin formula.clauses.length) + (prepared : Fin width → Bool) : K → List Bool := + Placement.tapes view (SourceTupleData.stacks formula indices prepared) extra + +theorem tape_injective (tape : Tape width → K) (view : K → Option (Tape width)) + (left : ∀ k, view (tape k) = some k) : Function.Injective tape := by + intro a b same + have viewed := congrArg view same + simpa only [left, Option.some.injEq] using viewed + +theorem tapes_placed (tape : Tape width → K) (view : K → Option (Tape width)) + (left : ∀ k, view (tape k) = some k) (extra : K → List Bool) + (formula : Formula) (indices : Fin width → Fin formula.clauses.length) + (prepared : Fin width → Bool) (k : Tape width) : + tapes view extra formula indices prepared (tape k) = + SourceTupleData.stacks formula indices prepared k := + Placement.tapes_apply tape view left _ extra k + +theorem tapes_complement (view : K → Option (Tape width)) (extra : K → List Bool) + (formula : Formula) (indices : Fin width → Fin formula.clauses.length) + (prepared : Fin width → Bool) (k : K) (outside : view k = none) : + tapes view extra formula indices prepared k = extra k := by + simp only [tapes, Placement.tapes, outside] + +theorem tapes_eq_base (tape : Tape width → K) (view : K → Option (Tape width)) + (right : ∀ j k, view j = some k → tape k = j) (base : K → List Bool) + (formula : Formula) (indices : Fin width → Fin formula.clauses.length) + (prepared : Fin width → Bool) + (contents : ∀ k, base (tape k) = SourceTupleData.stacks formula indices prepared k) : + tapes view base formula indices prepared = base := by + funext j + cases viewed : view j with + | none => simp only [tapes, Placement.tapes, viewed] + | some k => + simp only [tapes, Placement.tapes, viewed] + rw [← right j k viewed] + exact (contents k).symm + +theorem complement_preserved (view : K → Option (Tape width)) (extra : K → List Bool) + (formula : Formula) (indices : Fin width → Fin formula.clauses.length) + (before after : Fin width → Bool) (k : K) (outside : view k = none) : + tapes view extra formula indices after k = tapes view extra formula indices before k := by + rw [tapes_complement view extra formula indices after k outside, + tapes_complement view extra formula indices before k outside] + +variable [DecidableEq K] + +theorem tupleTrace (tape : Tape width → K) (view : K → Option (Tape width)) + (left : ∀ k, view (tape k) = some k) + (right : ∀ j k, view j = some k → tape k = j) + (labels : Label width → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State width A)) + (atLabels : ∀ label, program (labels label) = instruction tape labels exit label) + (extra : K → List Bool) (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) + (ambient : A) (shapes : Fin width → Shape) (signs : Signs) : + (advance (TM2.step program))^[SourceTupleMachine.steps formula indices (List.finRange width)] + (some ⟨entry labels exit, + SourceTupleMachine.state ambient (SourceTupleMachine.initial shapes signs), + tapes view extra formula indices (fun _ => false)⟩) = + some ⟨exit, + SourceClauseReaderMachine.clean + (ambient, fun position => SourceClauseReaderMachine.clauseShape + (SourceTupleData.selectedClause formula indices position)) + (SourceTupleMachine.result formula indices (List.finRange width) + (SourceTupleMachine.initial shapes signs)).signs, + tapes view extra formula indices (fun _ => true)⟩ := by + have native := SourceTupleMachine.tupleTrace formula indices id none none + (nativeProgram (width := width) (A := A)) (fun _ => rfl) ambient shapes signs + have placed := Placement.trace tape view left right labels exit extra + (nativeProgram (width := width) (A := A)) program atLabels _ _ _ native + simpa only [Placement.configuration, Placement.label, entry, tapes] using placed + +def tupleInTime (tape : Tape width → K) (view : K → Option (Tape width)) + (left : ∀ k, view (tape k) = some k) + (right : ∀ j k, view j = some k → tape k = j) + (labels : Label width → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State width A)) + (atLabels : ∀ label, program (labels label) = instruction tape labels exit label) + (extra : K → List Bool) (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) + (ambient : A) (shapes : Fin width → Shape) (signs : Signs) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨entry labels exit, + SourceTupleMachine.state ambient (SourceTupleMachine.initial shapes signs), + tapes view extra formula indices (fun _ => false)⟩ + (some ⟨exit, + SourceClauseReaderMachine.clean + (ambient, fun position => SourceClauseReaderMachine.clauseShape + (SourceTupleData.selectedClause formula indices position)) + (SourceTupleMachine.result formula indices (List.finRange width) + (SourceTupleMachine.initial shapes signs)).signs, + tapes view extra formula indices (fun _ => true)⟩) + (width * (60 * ((SourceOccurrenceEncoding.bits formula).length + 1))) where + steps := SourceTupleMachine.steps formula indices (List.finRange width) + evals_in_steps := tupleTrace tape view left right labels exit program atLabels extra + formula indices ambient shapes signs + steps_le_m := by + simpa only [List.length_finRange] using + SourceTupleMachine.steps_le formula indices (List.finRange width) + +theorem finiteState [Finite A] : Finite (State width A) := inferInstance + +theorem finiteLabels : Finite (Label width) := inferInstance + +omit [DecidableEq K] in +theorem finiteAlphabet (k : K) : Finite (Alphabet k) := by + change Finite Bool + infer_instance + +end PerfectCompleteness.SourceTuplePlacement + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/SourceTupleResetPlacementLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/SourceTupleResetPlacementLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..46bfce82a49e5b632bf5b0215216cd909595a6c6 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/SourceTupleResetPlacementLemmas.lean @@ -0,0 +1,202 @@ +import OAI.Computability.PerfectCompleteness.Foundations.SourceTuplePlacement +import OAI.Computability.PerfectCompleteness.Machines.SourceTupleResetMachine +import OAI.Computability.UniqueGames.Machines.MachineRegularLift + +namespace OAI + + +namespace PerfectCompleteness.SourceTupleResetPlacement + + +open Turing UniqueGamesTheorem.Foundations Complexity Target +open MachineComposition MachineCloudPadding + +abbrev Tape (width : Nat) := SourceTupleData.Tape width +abbrev Label (width : Nat) := SourceTupleResetMachine.Label width +abbrev State (A : Type) := SourceTupleResetMachine.State A +abbrev Alphabet {K : Type} (_ : K) := Bool + +variable {width : Nat} {K Λ A : Type} + +def nativeProgram : Label width → + TM2.Stmt (Alphabet (K := Tape width)) (Label width) (State A) := + SourceTupleResetMachine.instruction id none + +def instruction (tape : Tape width → K) (labels : Label width → Λ) (exit : Option Λ) : + Label width → TM2.Stmt (Alphabet (K := K)) Λ (State A) := + fun label => Placement.statement tape labels exit (nativeProgram label) + +def entry (labels : Label width → Λ) (exit : Option Λ) : Option Λ := + Placement.label labels exit (SourceTupleResetMachine.entry id none) + +variable [DecidableEq K] + +theorem resetTrace (tape : Tape width → K) (view : K → Option (Tape width)) + (left : ∀ k, view (tape k) = some k) + (right : ∀ j k, view j = some k → tape k = j) + (labels : Label width → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ label, program (labels label) = instruction tape labels exit label) + (extra : K → List Bool) (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) (ambient : A) : + (advance (TM2.step program))^[SourceTupleResetMachine.steps formula indices] + (some ⟨entry labels exit, (ambient, none), + SourceTuplePlacement.tapes view extra formula indices (fun _ => true)⟩) = + some ⟨exit, (ambient, none), + SourceTuplePlacement.tapes view extra formula indices (fun _ => false)⟩ := by + have native := SourceTupleResetMachine.resetTrace formula indices id none + (nativeProgram (width := width) (A := A)) (fun _ => rfl) ambient + have placed := Placement.trace tape view left right labels exit extra + (nativeProgram (width := width) (A := A)) program atLabels _ _ _ native + simpa only [Placement.configuration, Placement.label, entry, SourceTuplePlacement.tapes] + using placed + +def resetInTime (tape : Tape width → K) (view : K → Option (Tape width)) + (left : ∀ k, view (tape k) = some k) + (right : ∀ j k, view j = some k → tape k = j) + (labels : Label width → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ label, program (labels label) = instruction tape labels exit label) + (extra : K → List Bool) (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) (ambient : A) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨entry labels exit, (ambient, none), + SourceTuplePlacement.tapes view extra formula indices (fun _ => true)⟩ + (some ⟨exit, (ambient, none), + SourceTuplePlacement.tapes view extra formula indices (fun _ => false)⟩) + (3 * width * ((SourceOccurrenceEncoding.bits formula).length + 1)) where + steps := SourceTupleResetMachine.steps formula indices + evals_in_steps := resetTrace tape view left right labels exit program atLabels extra + formula indices ambient + steps_le_m := SourceTupleResetMachine.steps_le formula indices + +end PerfectCompleteness.SourceTupleResetPlacement + + +namespace PerfectCompleteness.SourceTupleBodyPlacement + + +open Turing UniqueGamesTheorem.Foundations Complexity Target +open MachineComposition MachineCloudPadding + +abbrev Shape := CanonicalKeyShape.Shape +abbrev Signs := NormalizationReadMachine.Signs +abbrev Tape (width : Nat) := SourceTupleData.Tape width +abbrev Label (width : Nat) := SourceTuplePlacement.Label width +abbrev ResetLabel (width : Nat) := SourceTupleResetMachine.Label width +abbrev Alphabet {K : Type} (_ : K) := Bool + +abbrev Frame (D : Type) := (Option D × (Bool × Option Bool)) × Option Bool +abbrev State (width : Nat) (U D : Type) := + ((SourceTupleMachine.State width U × Option D) × (Bool × Option Bool)) × Option Bool + +def registers {width : Nat} {U D : Type} : + (SourceTupleMachine.State width U × Frame D) ≃ State width U D where + toFun value := (((value.1, value.2.1.1), value.2.1.2), value.2.2) + invFun value := (value.1.1.1, ((value.1.1.2, value.1.2), value.2)) + left_inv := by rintro ⟨source, ⟨⟨descriptor, comparison⟩, head⟩⟩; rfl + right_inv := by rintro ⟨⟨⟨source, descriptor⟩, comparison⟩, head⟩; rfl + +variable {width : Nat} {K Λ U D : Type} + +def instruction (tape : Tape width → K) (labels : Label width → Λ) (exit : Option Λ) : + Label width → TM2.Stmt (Alphabet (K := K)) Λ (State width U D) := + fun label => MachineRegularTable.Lift.statement tape labels exit registers + (SourceTuplePlacement.nativeProgram label) + +def resetInstruction (tape : Tape width → K) + (labels : ResetLabel width → Λ) (exit : Option Λ) : + ResetLabel width → TM2.Stmt (Alphabet (K := K)) Λ (State width U D) := + fun label => MachineRegularTable.Lift.statement tape labels exit registers + (SourceTupleResetPlacement.nativeProgram label) + +variable [DecidableEq K] + +theorem tupleTrace (tape : Tape width → K) (view : K → Option (Tape width)) + (left : ∀ k, view (tape k) = some k) + (right : ∀ j k, view j = some k → tape k = j) + (labels : Label width → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State width U D)) + (atLabels : ∀ label, program (labels label) = instruction tape labels exit label) + (extra : K → List Bool) (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) + (ambient : U) (shapes : Fin width → Shape) (signs : Signs) (frame : Frame D) : + (advance (TM2.step program))^[SourceTupleMachine.steps formula indices (List.finRange width)] + (some ⟨SourceTuplePlacement.entry labels exit, + registers (SourceTupleMachine.state ambient (SourceTupleMachine.initial shapes signs), frame), + SourceTuplePlacement.tapes view extra formula indices (fun _ => false)⟩) = + some ⟨exit, + registers (SourceClauseReaderMachine.clean + (ambient, fun position => SourceClauseReaderMachine.clauseShape + (SourceTupleData.selectedClause formula indices position)) + (SourceTupleMachine.result formula indices (List.finRange width) + (SourceTupleMachine.initial shapes signs)).signs, frame), + SourceTuplePlacement.tapes view extra formula indices (fun _ => true)⟩ := by + have native := SourceTupleMachine.tupleTrace formula indices id none none + (SourceTuplePlacement.nativeProgram (width := width) (A := U)) (fun _ => rfl) + ambient shapes signs + have lifted := MachineRegularTable.Lift.trace tape view left right labels exit registers frame extra + (SourceTuplePlacement.nativeProgram (width := width) (A := U)) program atLabels _ _ _ native + simpa only [MachineRegularTable.Lift.configuration, Placement.label, + SourceTuplePlacement.entry, SourceTuplePlacement.tapes] using lifted + +def tupleInTime (tape : Tape width → K) (view : K → Option (Tape width)) + (left : ∀ k, view (tape k) = some k) + (right : ∀ j k, view j = some k → tape k = j) + (labels : Label width → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State width U D)) + (atLabels : ∀ label, program (labels label) = instruction tape labels exit label) + (extra : K → List Bool) (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) + (ambient : U) (shapes : Fin width → Shape) (signs : Signs) (frame : Frame D) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨SourceTuplePlacement.entry labels exit, + registers (SourceTupleMachine.state ambient (SourceTupleMachine.initial shapes signs), frame), + SourceTuplePlacement.tapes view extra formula indices (fun _ => false)⟩ + (some ⟨exit, + registers (SourceClauseReaderMachine.clean + (ambient, fun position => SourceClauseReaderMachine.clauseShape + (SourceTupleData.selectedClause formula indices position)) + (SourceTupleMachine.result formula indices (List.finRange width) + (SourceTupleMachine.initial shapes signs)).signs, frame), + SourceTuplePlacement.tapes view extra formula indices (fun _ => true)⟩) + (width * (60 * ((SourceOccurrenceEncoding.bits formula).length + 1))) where + steps := SourceTupleMachine.steps formula indices (List.finRange width) + evals_in_steps := tupleTrace tape view left right labels exit program atLabels extra + formula indices ambient shapes signs frame + steps_le_m := by + simpa only [List.length_finRange] using + SourceTupleMachine.steps_le formula indices (List.finRange width) + +theorem resetTrace (tape : Tape width → K) (view : K → Option (Tape width)) + (left : ∀ k, view (tape k) = some k) + (right : ∀ j k, view j = some k → tape k = j) + (labels : ResetLabel width → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State width U D)) + (atLabels : ∀ label, program (labels label) = resetInstruction tape labels exit label) + (extra : K → List Bool) (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) + (ambient : U) (shapes : Fin width → Shape) (signs : Signs) (frame : Frame D) : + (advance (TM2.step program))^[SourceTupleResetMachine.steps formula indices] + (some ⟨SourceTupleResetPlacement.entry labels exit, + registers (SourceClauseReaderMachine.clean (ambient, shapes) signs, frame), + SourceTuplePlacement.tapes view extra formula indices (fun _ => true)⟩) = + some ⟨exit, registers (SourceClauseReaderMachine.clean (ambient, shapes) signs, frame), + SourceTuplePlacement.tapes view extra formula indices (fun _ => false)⟩ := by + have native := SourceTupleResetMachine.resetTrace formula indices id none + (SourceTupleResetPlacement.nativeProgram + (width := width) (A := (U × (Fin width → Shape)) × Signs)) (fun _ => rfl) + ((ambient, shapes), signs) + have lifted := MachineRegularTable.Lift.trace tape view left right labels exit registers frame extra + (SourceTupleResetPlacement.nativeProgram + (width := width) (A := (U × (Fin width → Shape)) × Signs)) + program atLabels _ _ _ native + simpa only [MachineRegularTable.Lift.configuration, Placement.label, + SourceTupleResetPlacement.entry, SourceTuplePlacement.tapes, + SourceClauseReaderMachine.clean, NormalizationReadMachine.clean] using lifted + +theorem finiteState [Finite U] [Finite D] : Finite (State width U D) := inferInstance + +end PerfectCompleteness.SourceTupleBodyPlacement + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/SourceVisitOrder.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/SourceVisitOrder.lean new file mode 100644 index 0000000000000000000000000000000000000000..d1b4c522f188942fc4141f96a814799f7f74dd6b --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/SourceVisitOrder.lean @@ -0,0 +1,68 @@ +import OAI.Computability.PerfectCompleteness.Construction.SourceQuestionOrderLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.SourceVisitOrder + +open UniqueGamesTheorem.Foundations.Complexity +open scoped BigOperators Classical + +noncomputable section + +variable {branch : Nat → Nat} {n t m : Nat} + +def visitOrder (branch : Nat → Nat) (n t m : Nat) : + List (PreliminarySampler.Questions branch n t m) := + (SourceQuestionOrder.sourceOrder branch n t m).reverse + +theorem visitOrder_eq_tupleOrder (branch : Nat → Nat) (n t m : Nat) : + visitOrder branch n t m = + (MachineTupleOdometer.tupleOrder m (TreeCanonical.locationCount branch n t)).map + SourceQuestionOrder.tupleToQuestion := by + simp only [visitOrder, SourceQuestionOrder.sourceOrder, ← List.map_reverse, + List.reverse_reverse] + +@[simp] theorem visitOrder_reverse (branch : Nat → Nat) (n t m : Nat) : + (visitOrder branch n t m).reverse = SourceQuestionOrder.sourceOrder branch n t m := by + simp only [visitOrder, List.reverse_reverse] + +@[simp] theorem visitOrder_length (branch : Nat → Nat) (n t m : Nat) : + (visitOrder branch n t m).length = m ^ TreeCanonical.locationCount branch n t := by + simp only [visitOrder, List.length_reverse, SourceQuestionOrder.sourceOrder_length] + +theorem visitOrder_nodup (branch : Nat → Nat) (n t m : Nat) : + (visitOrder branch n t m).Nodup := + List.nodup_reverse.mpr (SourceQuestionOrder.sourceOrder_nodup branch n t m) + +theorem mem_visitOrder (question : PreliminarySampler.Questions branch n t m) : + question ∈ visitOrder branch n t m := by + simpa only [visitOrder, List.mem_reverse] using SourceQuestionOrder.mem_sourceOrder question + +@[simp] theorem visitOrder_toFinset (branch : Nat → Nat) (n t m : Nat) : + (visitOrder branch n t m).toFinset = Finset.univ := by + ext question + simp only [List.mem_toFinset, Finset.mem_univ, iff_true] + exact mem_visitOrder question + +theorem sum_map_visitOrder {A : Type*} [AddCommMonoid A] + (f : PreliminarySampler.Questions branch n t m → A) : + ((visitOrder branch n t m).map f).sum = ∑ question, f question := by + rw [visitOrder, List.map_reverse, List.sum_reverse] + exact SourceQuestionOrder.sum_map_sourceOrder f + +theorem output_eq_reverse_visitOrder (branch : Nat → Nat) (n t m : Nat) : + TupleIndexMachine.output (TreeCanonical.locationCount branch n t) m = + (visitOrder branch n t m).reverse.flatMap + (fun question => encodeWords (SourceQuestionOrder.numberedClauseIDs question)) := by + rw [visitOrder_reverse] + exact SourceQuestionOrder.output_eq_sourceOrder branch n t m + +end + +end PerfectCompleteness.SourceVisitOrder + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/StoppedPathHead.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/StoppedPathHead.lean new file mode 100644 index 0000000000000000000000000000000000000000..ba6ccb1f39bfc5aeb345381ca76e111e467a1d5e --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/StoppedPathHead.lean @@ -0,0 +1,58 @@ +import Lean.Elab.Tactic.Omega +import OAI.Computability.PerfectCompleteness.Foundations.StoppedProjectedExperiment + +namespace OAI + +section + +namespace PerfectCompleteness.StoppedPathHead + +open DescendantSpaces + +variable {branch : Nat → Nat} {i j : Nat} + +def headTail (hij : i < j) (p : Path branch (j + 1) (i + 1)) : + Fin (branch j) × Path branch j (i + 1) := by + cases p with + | refl => omega + | step a q => exact (a, q) + +def child (hij : i < j) (p : Path branch (j + 1) (i + 1)) : Fin (branch j) := + (headTail hij p).1 + +def tail (hij : i < j) (p : Path branch (j + 1) (i + 1)) : Path branch j (i + 1) := + (headTail hij p).2 + +theorem step_eq (hij : i < j) (p : Path branch (j + 1) (i + 1)) : + p = Path.step (child hij p) (tail hij p) := by + cases p with + | refl => omega + | step a q => rfl + +@[simp] theorem child_step (hij : i < j) (a : Fin (branch j)) + (q : Path branch j (i + 1)) : child hij (Path.step a q) = a := rfl + +@[simp] theorem tail_step (hij : i < j) (a : Fin (branch j)) + (q : Path branch j (i + 1)) : tail hij (Path.step a q) = q := rfl + +theorem prefixPath_step_eq (hij : i < j) + (pref : GeometricCutSplit.Prefix branch (j + 1) (i + 1)) : + GeometricCutSplit.prefixPath (Nat.succ_le_succ hij.le) pref = + Path.step + (child hij (GeometricCutSplit.prefixPath (Nat.succ_le_succ hij.le) pref)) + (tail hij (GeometricCutSplit.prefixPath (Nat.succ_le_succ hij.le) pref)) := + step_eq hij _ + +theorem lowerPath_step_eq {n t : Nat} (rows : Nat → Nat) (hij : i < j) + (k : StoppedProjectedExperiment.Inner + (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) : + StoppedProjectedExperiment.lowerPath rows hij k = + Path.step (child hij (StoppedProjectedExperiment.lowerPath rows hij k)) + (tail hij (StoppedProjectedExperiment.lowerPath rows hij k)) := + step_eq hij _ + +end PerfectCompleteness.StoppedPathHead + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/StoppedPhysicalPrefixSwap.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/StoppedPhysicalPrefixSwap.lean new file mode 100644 index 0000000000000000000000000000000000000000..799ecac9ef281eac80fa7a976a4e7012da7aee7f --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/StoppedPhysicalPrefixSwap.lean @@ -0,0 +1,91 @@ +import OAI.Computability.PerfectCompleteness.Foundations.StoppedProjectedPhysicalAdvice + +namespace OAI + +section + +namespace PerfectCompleteness.StoppedPhysicalPrefixSwap + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) +attribute [local instance] linearMapFintype +attribute [local instance] StoppedProjectedPhysicalAdvice.adviceFintype + StoppedProjectedPhysicalAdvice.physicalAdviceFintype + +variable {branch : Nat → Nat} {n i j t v m : Nat} [NeZero m] + (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hupper : j + 1 ≤ n) (hij : i < j) + (designated : Fin (branch i) → Slots branch i) + (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) + (flag : Fin (branch i) → FiniteDistribution Bool) + +omit [NeZero m] in +theorem fiber_expectation + (o : StoppedProjectedPhysicalAdvice.Outer + (branch := branch) (n := n) (j := j) (t := t) (m := m)) (r : Nat) + (F : StoppedProjectedPhysicalAdvice.Sample + clauses rows repeats hupper hij designated r → ℝ) : + (StoppedProjectedExperiment.physicalLaw clauses rows repeats hupper hij designated + (fun k hk => hbranch k (Nat.lt_of_lt_of_le hk hupper)) hrows flag o).expectation + (fun sample => (FiniteDistribution.uniform + (StoppedProjectedPhysicalAdvice.Advice rows hupper o r)).expectation + (fun A => F ⟨o, (sample, A)⟩)) = + (GeometricCutSplit.prefixLaw (Nat.succ_le_succ hij.le) + (fun k hk => hbranch k (Nat.lt_of_lt_of_le hk hupper))).expectation + (fun lower => (FiniteDistribution.uniform + (StoppedProjectedPhysicalAdvice.Advice rows hupper o r)).expectation + (fun A => (CanonicalDirections.law rows n hrows).expectation + (fun directions => (SourceProjectedTag.positionLaw + (branch := branch) (n := i) (t := t)).expectation + (fun positions => (StoppedProjectedExperiment.physicalFiberLaw + clauses rows repeats hupper hij designated flag o + (lower, (positions, directions))).expectation + (fun raw => F ⟨o, (⟨(lower, (positions, directions)), raw⟩, A)⟩))))) := by + rw [FiniteDistribution.expectation_comm] + simp only [StoppedProjectedExperiment.physicalLaw, CandidateCoupling.expectation_sigmaLaw, + StoppedProjectedExperiment.physicalBaseLaw, FiniteDistribution.expectation_product] + rw [FiniteDistribution.expectation_comm] + apply FiniteDistribution.expectation_congr + intro lower + apply FiniteDistribution.expectation_congr + intro A + exact FiniteDistribution.expectation_comm _ _ _ + +theorem expectation_prefixes (r : Nat) + (F : StoppedProjectedPhysicalAdvice.Sample + clauses rows repeats hupper hij designated r → ℝ) : + (StoppedProjectedPhysicalAdvice.law clauses rows repeats hupper hij designated + hbranch hrows flag r).expectation F = + ((GeometricCutSplit.prefixLaw hupper hbranch).product + (GeometricCutSplit.prefixLaw (Nat.succ_le_succ hij.le) + (fun k hk => hbranch k (Nat.lt_of_lt_of_le hk hupper)))).expectation + (fun prefixes => (PreliminarySampler.questionsLaw + (branch := branch) (n := n) (t := t) (m := m)).expectation + (fun Q => (FiniteDistribution.uniform + (StoppedProjectedPhysicalAdvice.Advice rows hupper (Q, prefixes.1) r)).expectation + (fun A => (CanonicalDirections.law rows n hrows).expectation + (fun directions => (SourceProjectedTag.positionLaw + (branch := branch) (n := i) (t := t)).expectation + (fun positions => (StoppedProjectedExperiment.physicalFiberLaw + clauses rows repeats hupper hij designated flag (Q, prefixes.1) + (prefixes.2, (positions, directions))).expectation + (fun raw => F ⟨(Q, prefixes.1), + (⟨(prefixes.2, (positions, directions)), raw⟩, A)⟩)))))) := by + rw [StoppedProjectedPhysicalAdvice.law, CandidateCoupling.expectation_sigmaLaw] + simp only [StoppedProjectedExperiment.outerLaw, FiniteDistribution.expectation_product] + simp_rw [fiber_expectation clauses rows repeats hupper hij designated hbranch hrows flag] + rw [FiniteDistribution.expectation_comm] + apply FiniteDistribution.expectation_congr + intro upper + exact FiniteDistribution.expectation_comm _ _ _ + +end +end PerfectCompleteness.StoppedPhysicalPrefixSwap + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/StoppedProjectedArrays.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/StoppedProjectedArrays.lean new file mode 100644 index 0000000000000000000000000000000000000000..a5812ede9cebd09e06cc2d2156def995b741fca3 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/StoppedProjectedArrays.lean @@ -0,0 +1,208 @@ +import OAI.Computability.PerfectCompleteness.Foundations.StoppedProjectedExperiment + +namespace OAI + +section + +namespace PerfectCompleteness.StoppedProjectedArrays + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +private theorem mpr_heq {α β : Sort _} (h : α = β) (x : β) : + HEq (Eq.mpr h x) x := by + cases h + rfl + +private theorem sourceProjection_heq + {branch : Nat → Nat} {i t v m : Nat} + (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch i) → Slots branch i) + (q : PreliminarySampler.Questions branch (i + 1) t m) + (positions : SourceQuestionKernelJoint.ChoiceTuple (branch := branch) (n := i) (t := t)) + (flags : SourceProjectedTag.Flags (branch := branch) (n := i)) + (leaf : Slots branch (i + 1)) (a : Fin t) : + HEq (SourceProjectedTag.projection clauses designated q positions flags leaf a) + (SourceChildKernel.projection clauses designated leaf.1 + (SourceQuestionKernelJoint.sources designated q positions leaf.1) + (flags leaf.1) leaf.2 a) := by + unfold SourceProjectedTag.projection + dsimp only [id] + exact mpr_heq _ _ + +private theorem fillProjection_heq + {branch : Nat → Nat} {n h t : Nat} (p : Path branch n h) + (outside : Slots branch n → Fin t → MixedSupport.Slot) + {left left' right right' : Slots branch h → Fin t → MixedSupport.Slot} + (hl : left = left') (hr : right = right') + (q : ∀ s a, MixedSupport.Projection (left s a) (right s a)) + (q' : ∀ s a, MixedSupport.Projection (left' s a) (right' s a)) + (hq : ∀ s a, HEq (q s a) (q' s a)) (leaf : Slots branch n) (a : Fin t) : + HEq (CutProjectionAssembly.fillProjection p outside left right q leaf a) + (CutProjectionAssembly.fillProjection p outside left' right' q' leaf a) := by + cases hl + cases hr + have he : q = q' := funext (fun s => funext (fun a => eq_of_heq (hq s a))) + cases he + rfl + +private theorem arraysPullback_heq + {branch : Nat → Nat} {n t : Nat} (rows : Nat → Nat) + {left left' right : Slots branch n → Fin t → MixedSupport.Slot} + (hl : left = left') + (q : ∀ s a, MixedSupport.Projection (left s a) (right s a)) + (q' : ∀ s a, MixedSupport.Projection (left' s a) (right s a)) + (hq : ∀ s a, HEq (q s a) (q' s a)) (arrays : Arrays right rows) : + HEq (ChildBlockProjection.arraysPullback rows q arrays) + (ChildBlockProjection.arraysPullback rows q' arrays) := by + cases hl + have he : q = q' := funext (fun s => funext (fun a => eq_of_heq (hq s a))) + cases he + rfl + +variable {branch : Nat → Nat} {n i j t v m : Nat} + (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hupper : j + 1 ≤ n) (hij : i < j) + (designated : Fin (branch i) → Slots branch i) + +theorem nativeSlots_eq + (o : StoppedProjectedExperiment.Outer + (branch := branch) (n := n) (j := j) (t := t) (m := m)) + (base : StoppedProjectedExperiment.PhysicalBase + (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) : + SourcePhysicalTapeLaw.nativeSlots + (StoppedProjectedExperiment.stoppedPath rows hupper hij o + (StoppedProjectedExperiment.baseTag rows base)) + (StoppedProjectedExperiment.nativeSlots clauses o) clauses designated + (StoppedProjectedExperiment.physicalSources rows hupper hij designated o base) = + StoppedProjectedExperiment.nativeSlots clauses o := by + unfold SourcePhysicalTapeLaw.nativeSlots StoppedProjectedExperiment.physicalSources + rw [SourceProjectedTag.parentLeftSlots_sources] + exact StoppedProjectedExperiment.fill_native clauses rows hupper hij o + (StoppedProjectedExperiment.baseTag rows base) + +theorem projection_heq + (o : StoppedProjectedExperiment.Outer + (branch := branch) (n := n) (j := j) (t := t) (m := m)) + (base : StoppedProjectedExperiment.PhysicalBase + (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) + (flags : SourceProjectedTag.Flags (branch := branch) (n := i)) + (leaf : Slots branch n) (a : Fin t) : + HEq (StoppedProjectedExperiment.projection clauses rows hupper hij designated o + (StoppedProjectedExperiment.withFlags rows base flags) leaf a) + (SourcePhysicalTapeLaw.fullProjection + (StoppedProjectedExperiment.stoppedPath rows hupper hij o + (StoppedProjectedExperiment.baseTag rows base)) + (StoppedProjectedExperiment.nativeSlots clauses o) clauses designated + (StoppedProjectedExperiment.physicalSources rows hupper hij designated o base, flags) + leaf a) := by + unfold StoppedProjectedExperiment.projection + apply (CutProjectionAssembly.castProjection_heq _ _ _).trans + exact fillProjection_heq + (StoppedProjectedExperiment.stoppedPath rows hupper hij o + (StoppedProjectedExperiment.baseTag rows base)) + (StoppedProjectedExperiment.nativeSlots clauses o) + (SourceProjectedTag.parentLeftSlots_sources clauses designated + (StoppedProjectedExperiment.cutQuestions rows hupper hij o + (StoppedProjectedExperiment.baseTag rows base)) base.2.1).symm + rfl _ _ + (sourceProjection_heq clauses designated + (StoppedProjectedExperiment.cutQuestions rows hupper hij o + (StoppedProjectedExperiment.baseTag rows base)) base.2.1 flags) leaf a + +abbrev physicalArrays + (o : StoppedProjectedExperiment.Outer + (branch := branch) (n := n) (j := j) (t := t) (m := m)) + (sample : StoppedProjectedExperiment.PhysicalSample + clauses rows repeats hupper hij designated o) := + SourcePhysicalWholeLaw.observeLeft rows repeats + (StoppedProjectedExperiment.stoppedPath rows hupper hij o + (StoppedProjectedExperiment.baseTag rows sample.1)) + (StoppedProjectedExperiment.nativeSlots clauses o) + (SourceProjectedTag.originalSlots clauses + (StoppedProjectedExperiment.cutQuestions rows hupper hij o + (StoppedProjectedExperiment.baseTag rows sample.1))) + clauses designated + (StoppedProjectedExperiment.physicalSources rows hupper hij designated o sample.1) sample.2 + +variable [NeZero m] + (hbranch : ∀ k < j + 1, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) + (flag : Fin (branch i) → FiniteDistribution Bool) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + +omit [NeZero m] in +theorem arrays_physicalExperimentRead_heq + (o : StoppedProjectedExperiment.Outer + (branch := branch) (n := n) (j := j) (t := t) (m := m)) + (sample : StoppedProjectedExperiment.PhysicalSample + clauses rows repeats hupper hij designated o) : + HEq ((StoppedProjectedExperiment.experiment clauses rows repeats hupper hij designated + hbranch hrows flag σ o).arrays + (StoppedProjectedExperiment.physicalExperimentRead clauses rows repeats hupper hij designated + o sample)) + (physicalArrays clauses rows repeats hupper hij designated o sample) := by + let observed := SourcePhysicalTapeLaw.observeFiber rows repeats + (StoppedProjectedExperiment.stoppedPath rows hupper hij o + (StoppedProjectedExperiment.baseTag rows sample.1)) + (StoppedProjectedExperiment.nativeSlots clauses o) + (SourceProjectedTag.originalSlots clauses + (StoppedProjectedExperiment.cutQuestions rows hupper hij o + (StoppedProjectedExperiment.baseTag rows sample.1))) + clauses designated + (StoppedProjectedExperiment.physicalSources rows hupper hij designated o sample.1) sample.2 + have htable := StoppedProjectedExperiment.arrays_tapeRead clauses rows repeats hupper hij + designated hbranch hrows flag σ o + (StoppedProjectedExperiment.physicalRead clauses rows repeats hupper hij designated o sample) + have hpull := arraysPullback_heq rows + (nativeSlots_eq clauses rows hupper hij designated o sample.1).symm + (StoppedProjectedExperiment.projection clauses rows hupper hij designated o + (StoppedProjectedExperiment.withFlags rows sample.1 observed.1)) + (SourcePhysicalTapeLaw.fullProjection + (StoppedProjectedExperiment.stoppedPath rows hupper hij o + (StoppedProjectedExperiment.baseTag rows sample.1)) + (StoppedProjectedExperiment.nativeSlots clauses o) clauses designated + (StoppedProjectedExperiment.physicalSources rows hupper hij designated o sample.1, observed.1)) + (projection_heq clauses rows hupper hij designated o sample.1 observed.1) + (WholeArraySampler.evaluate rows repeats + (StoppedProjectedExperiment.stoppedPath rows hupper hij o + (StoppedProjectedExperiment.baseTag rows sample.1)) + (StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated o + (StoppedProjectedExperiment.withFlags rows sample.1 observed.1)) observed.2) + have hphysical := SourcePhysicalTapeLaw.observeFiber_native_arrays rows repeats + (StoppedProjectedExperiment.stoppedPath rows hupper hij o + (StoppedProjectedExperiment.baseTag rows sample.1)) + (StoppedProjectedExperiment.nativeSlots clauses o) + (SourceProjectedTag.originalSlots clauses + (StoppedProjectedExperiment.cutQuestions rows hupper hij o + (StoppedProjectedExperiment.baseTag rows sample.1))) + clauses designated + (StoppedProjectedExperiment.physicalSources rows hupper hij designated o sample.1) sample.2 + exact (heq_of_eq htable).trans (hpull.trans (heq_of_eq hphysical)) + +omit [NeZero m] in +theorem arrays_physicalExperimentRead_eq + (o : StoppedProjectedExperiment.Outer + (branch := branch) (n := n) (j := j) (t := t) (m := m)) + (sample : StoppedProjectedExperiment.PhysicalSample + clauses rows repeats hupper hij designated o) : + (StoppedProjectedExperiment.experiment clauses rows repeats hupper hij designated + hbranch hrows flag σ o).arrays + (StoppedProjectedExperiment.physicalExperimentRead clauses rows repeats hupper hij designated + o sample) = + cast (congrArg + (fun slots : Slots branch n → Fin t → MixedSupport.Slot => Arrays slots rows) + (nativeSlots_eq clauses rows hupper hij designated o sample.1)) + (physicalArrays clauses rows repeats hupper hij designated o sample) := by + apply eq_of_heq + exact (arrays_physicalExperimentRead_heq clauses rows repeats hupper hij designated + hbranch hrows flag σ o sample).trans (cast_heq _ _).symm + +end +end PerfectCompleteness.StoppedProjectedArrays + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/StoppedProjectedCoarseLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/StoppedProjectedCoarseLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..df7f77b91edb16ac1dedb2364a1c692122c00101 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/StoppedProjectedCoarseLemmas.lean @@ -0,0 +1,294 @@ +import OAI.Computability.PerfectCompleteness.Construction.HierarchicalBucketFamily +import OAI.Computability.PerfectCompleteness.Construction.StoppedProjectedBuckets +import OAI.Computability.PerfectCompleteness.Foundations.DependentPredictionDifferenceLemmas +import OAI.Computability.PerfectCompleteness.Foundations.HeterogeneousPairAdvice +import OAI.Computability.PerfectCompleteness.Foundations.StoppedProjectedOldRecord + +namespace OAI + +section + +namespace PerfectCompleteness.StoppedProjectedCoarse + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype + +variable {branch : Nat → Nat} {n i j t v m : Nat} + (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hupper : j + 1 ≤ n) (hij : i < j) + (designated : Fin (branch i) → Slots branch i) + (hbranch : ∀ k < j + 1, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) + (flag : Fin (branch i) → FiniteDistribution Bool) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + +local notation "O" => StoppedProjectedExperiment.Outer + (branch := branch) (n := n) (j := j) (t := t) (m := m) + +local notation "S" => StoppedProjectedExperiment.experiment clauses rows repeats hupper hij + designated hbranch hrows flag σ + +local instance fixedBackgroundFintype + (slots : Slots branch n → Fin t → MixedSupport.Slot) (upper : Nodes branch n) : + Fintype (HierarchicalMatrixTable.Background (rows := rows) slots upper) := + HierarchicalUsefulCollision.backgroundFintype (rows := rows) slots upper + +local instance backgroundFintype (o : O) : + Fintype (HierarchicalAdviceExperiment.Background (S o)) := + HierarchicalAdviceExperiment.backgroundFintype (S o) + +local instance rowSpaceFintype (o : O) : + Fintype (NodeEmbedding.RowSpace (S o).slots (S o).upper) := + HierarchicalPairCoarse.rowSpaceFintype (S o) + +local instance coarseFintype (o : O) : + Fintype (HierarchicalAdviceExperiment.Coarse (S o)) := + HierarchicalAdviceFamily.coarseFintype S o + +local instance inputFintype (o : O) (background : HierarchicalAdviceExperiment.Background (S o)) : + Fintype (HierarchicalAdviceExperiment.Input (S o) background) := + HierarchicalAdviceExperiment.inputFintype (S o) background + +local instance inputFiniteDimensional (o : O) + (background : HierarchicalAdviceExperiment.Background (S o)) : + FiniteDimensional F2 (HierarchicalAdviceExperiment.Input (S o) background) := + HierarchicalAdviceExperiment.inputFiniteDimensional (S o) background + +local instance projectedSampleFintype (o : O) : + Fintype (HierarchicalProjectedExperiment.Sample (rows := rows) (repeats := repeats) + (StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated o) + (StoppedProjectedExperiment.upper hupper o) + (StoppedProjectedExperiment.lower rows hupper hij o) + (StoppedProjectedExperiment.cut rows hupper hij o)) := by + letI : (k : StoppedProjectedExperiment.Inner + (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) → + Fintype (WholeArraySampler.Tape rows repeats + (WholeArrayInteriorOwnInputLaw.fullPath (StoppedProjectedExperiment.upper hupper o) + (StoppedProjectedExperiment.lower rows hupper hij o k) + (StoppedProjectedExperiment.cut rows hupper hij o k)) + (StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated o k)) := + fun k => WholeArraySampler.tapeFintype rows repeats + (WholeArrayInteriorOwnInputLaw.fullPath (StoppedProjectedExperiment.upper hupper o) + (StoppedProjectedExperiment.lower rows hupper hij o k) + (StoppedProjectedExperiment.cut rows hupper hij o k)) + (StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated o k) + exact Sigma.instFintype + +local instance adviceFintype (o : O) (r : Nat) : + Fintype (HierarchicalAdviceExperiment.Advice (S o) r) := linearMapFintype + +local instance originalFiberFintype (o : O) (r : Nat) : + Fintype (HierarchicalProjectedExperiment.Sample (rows := rows) (repeats := repeats) + (StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated o) + (StoppedProjectedExperiment.upper hupper o) + (StoppedProjectedExperiment.lower rows hupper hij o) + (StoppedProjectedExperiment.cut rows hupper hij o) × + HierarchicalAdviceExperiment.Advice (S o) r) := by + infer_instance + +def pairLaw (outer : FiniteDistribution O) := + HierarchicalBucketFamily.actualPairLaw S outer + (fun o => StoppedProjectedBuckets.externalLaw clauses rows repeats hupper hij designated hrows o hbranch flag) + (fun o => StoppedProjectedBuckets.background clauses rows repeats hupper hij designated hrows o) + (fun o => StoppedProjectedBuckets.scalarLaw clauses rows repeats hupper hij designated hrows o) + (fun o => StoppedProjectedBuckets.rows_positive rows hupper hrows o) + +theorem original_observe_law (outer : FiniteDistribution O) (r : Nat) : + HeterogeneousPairAdvice.observedLaw S + (pairLaw clauses rows repeats hupper hij designated hbranch hrows flag σ outer) r = + (HierarchicalAdviceFamily.originalLaw S outer r).pushforward + (HierarchicalAdviceFamily.observe S r) := by + calc + _ = CompletionSoundness.sigmaLaw outer (fun o => + ((HierarchicalAdviceExperiment.adviceLaw (S o) r).product + (StoppedProjectedOldRecord.pairLaw clauses rows repeats hupper hij designated hrows o + hbranch flag)).pushforward (HierarchicalPairCoarse.observe (S o) r)) := + HeterogeneousPairAdvice.observed_sigmaLaw S outer + (fun o => StoppedProjectedOldRecord.pairLaw clauses rows repeats hupper hij designated + hrows o hbranch flag) r + _ = CompletionSoundness.sigmaLaw outer (fun o => + (HierarchicalAdviceExperiment.originalLaw (S o) r).pushforward + (HierarchicalAdviceExperiment.observe (S o) r)) := by + apply congrArg (CompletionSoundness.sigmaLaw outer) + funext o + exact HierarchicalPairCoarse.original_observe_law_of_oldRecord (S o) + (StoppedProjectedOldRecord.pairLaw clauses rows repeats hupper hij designated hrows o + hbranch flag) r + (StoppedProjectedOldRecord.original_oldRecord_law clauses rows repeats hupper hij designated + hrows o hbranch flag σ).symm + _ = _ := by + exact (SigmaObservation.pushforward_fiber outer + (fun o => HierarchicalAdviceExperiment.originalLaw (S o) r) + (fun o => HierarchicalAdviceExperiment.observe (S o) r)).symm + +theorem totalVariation_le_pair (outer : FiniteDistribution O) + (backgrounds : (o : O) → FiniteDistribution (HierarchicalAdviceExperiment.Background (S o))) + (r : Nat) : + ((HierarchicalAdviceFamily.originalLaw S outer r).pushforward + (HierarchicalAdviceFamily.observe S r)).totalVariation + ((HierarchicalAdviceFamily.referenceLaw S outer backgrounds r).pushforward + (HierarchicalAdviceFamily.referenceObserve S r)) ≤ + (pairLaw clauses rows repeats hupper hij designated hbranch hrows flag σ outer).totalVariation + (HierarchicalBucketFamily.referencePairLaw S outer backgrounds + (fun o => StoppedProjectedBuckets.rows_positive rows hupper hrows o)) := + HeterogeneousPairAdvice.original_totalVariation_le_of_observed S + (pairLaw clauses rows repeats hupper hij designated hbranch hrows flag σ outer) + outer backgrounds (fun o => StoppedProjectedBuckets.rows_positive rows hupper hrows o) r + (original_observe_law clauses rows repeats hupper hij designated hbranch hrows flag σ outer r) + +end +end PerfectCompleteness.StoppedProjectedCoarse + +end + +section + +namespace PerfectCompleteness.StoppedProjectedPairMean + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCutTape WholeArrayInteriorExterior +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) +open scoped Classical + +noncomputable section + +attribute [local instance] linearMapFintype + +variable {branch : Nat → Nat} {n i j t v m : Nat} + +local instance backgroundFintype (rows : Nat → Nat) (p : Path branch n (j + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Fintype (HierarchicalAgreementMean.Background (rows := rows) slots (upperNode p)) := + Fintype.ofFinite _ + +local instance rowSpaceFintype (p : Path branch n (j + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Fintype (NodeEmbedding.RowSpace slots (upperNode p)) := Fintype.ofFinite _ + +theorem proper_pair_law (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) (hij : i < j) + (native right : Slots branch n → Fin t → MixedSupport.Slot) + (projection : ∀ s a, MixedSupport.Projection (native s a) (right s a)) + (hrows : 0 < rows (j + 1)) : + ((StoppedUsefulPairLaw.directionLaw rows j hrows).product + ((WholeArraySampler.tapeLaw rows repeats (p.append r) right).product + (RecursiveSampler.law F2 repeats r (LeafDomain (cutSlots p right))))).pushforward + (UpperScalarCutProjection.stoppedProjectedPair rows repeats p r + (Nat.succ_lt_succ hij) native right projection) = + HierarchicalUsefulCollision.pairLaw native (upperNode p) + (StoppedUsefulPairLaw.externalLaw rows repeats p (StoppedPathHead.child hij r) + (StoppedPathHead.tail hij r) right) + (StoppedUsefulPairLaw.background rows repeats p (StoppedPathHead.child hij r) + (StoppedPathHead.tail hij r) native right projection) + (StoppedUsefulPairLaw.scalarLaw rows repeats p (StoppedPathHead.child hij r) + (StoppedPathHead.tail hij r) native right projection) + (by simpa only [upperNode_height] using hrows) := by + cases r with + | refl => exact False.elim ((Nat.lt_irrefl _) hij) + | step child q => + exact StoppedUsefulPairLaw.stoppedProjectedPair_law rows repeats p child q + (Nat.succ_lt_succ hij) native right projection hrows + +variable (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hupper : j + 1 ≤ n) (hij : i < j) + (designated : Fin (branch i) → Slots branch i) + (hrows : ∀ k, 0 < rows (k + 1)) + (o : StoppedProjectedExperiment.Outer + (branch := branch) (n := n) (j := j) (t := t) (m := m)) + +local instance nativeBackgroundFintype : + Fintype (HierarchicalAgreementMean.Background (rows := rows) + (StoppedProjectedExperiment.nativeSlots clauses o) + (StoppedProjectedExperiment.upper hupper o)) := + Fintype.ofFinite _ + +local instance nativeRowSpaceFintype : + Fintype (NodeEmbedding.RowSpace (StoppedProjectedExperiment.nativeSlots clauses o) + (StoppedProjectedExperiment.upper hupper o)) := + Fintype.ofFinite _ + +def fixedPair (base : StoppedProjectedBucketIndex.Base + (branch := branch) (i := i) (j := j) (t := t)) : + FiniteDistribution (HierarchicalAgreementMean.PairRecord (rows := rows) + (StoppedProjectedExperiment.nativeSlots clauses o) (StoppedProjectedExperiment.upper hupper o)) := + ((StoppedUsefulPairLaw.directionLaw rows j (hrows j)).product + ((WholeArraySampler.tapeLaw rows repeats + ((StoppedProjectedExperiment.upperPath hupper o).append + (StoppedProjectedBuckets.lowerPath (n := n) rows hij hrows base)) + (StoppedProjectedBuckets.projected clauses rows hupper hij designated hrows o base)).product + (RecursiveSampler.law F2 repeats + (StoppedProjectedBuckets.lowerPath (n := n) rows hij hrows base) + (LeafDomain (cutSlots (StoppedProjectedExperiment.upperPath hupper o) + (StoppedProjectedBuckets.projected clauses rows hupper hij designated hrows o base)))))).pushforward + (UpperScalarCutProjection.stoppedProjectedPair rows repeats + (StoppedProjectedExperiment.upperPath hupper o) + (StoppedProjectedBuckets.lowerPath (n := n) rows hij hrows base) (Nat.succ_lt_succ hij) + (StoppedProjectedExperiment.nativeSlots clauses o) + (StoppedProjectedBuckets.projected clauses rows hupper hij designated hrows o base) + (StoppedProjectedBuckets.projection clauses rows hupper hij designated hrows o base)) + +theorem fixedPair_eq (base : StoppedProjectedBucketIndex.Base + (branch := branch) (i := i) (j := j) (t := t)) : + fixedPair clauses rows repeats hupper hij designated hrows o base = + HierarchicalUsefulCollision.pairLaw (StoppedProjectedExperiment.nativeSlots clauses o) + (StoppedProjectedExperiment.upper hupper o) + (StoppedProjectedBuckets.exteriorLaw clauses rows repeats hupper hij designated hrows o base) + (fun external => StoppedProjectedBuckets.background clauses rows repeats hupper hij + designated hrows o ⟨base, external⟩) + (fun external => StoppedProjectedBuckets.scalarLaw clauses rows repeats hupper hij + designated hrows o ⟨base, external⟩) + (StoppedProjectedBuckets.rows_positive rows hupper hrows o) := + proper_pair_law rows repeats (StoppedProjectedExperiment.upperPath hupper o) + (StoppedProjectedBuckets.lowerPath (n := n) rows hij hrows base) hij + (StoppedProjectedExperiment.nativeSlots clauses o) + (StoppedProjectedBuckets.projected clauses rows hupper hij designated hrows o base) + (StoppedProjectedBuckets.projection clauses rows hupper hij designated hrows o base) (hrows j) + +theorem pairedLaw_eq_mixture (hbranch : ∀ k < j + 1, 0 < branch k) + (flag : Fin (branch i) → FiniteDistribution Bool) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) : + HierarchicalAdviceFromBuckets.pairedLaw + (StoppedProjectedBuckets.experiment clauses rows repeats hupper hij designated hrows o hbranch flag σ) + (StoppedProjectedBuckets.externalLaw clauses rows repeats hupper hij designated hrows o hbranch flag) + (StoppedProjectedBuckets.background clauses rows repeats hupper hij designated hrows o) + (StoppedProjectedBuckets.scalarLaw clauses rows repeats hupper hij designated hrows o) + (StoppedProjectedBuckets.rows_positive rows hupper hrows o) = + (StoppedProjectedBucketIndex.baseLaw (t := t) hij hbranch flag).mixture + (fixedPair clauses rows repeats hupper hij designated hrows o) := by + apply SigmaObservation.eq_of_probability_eq + (X := HierarchicalAgreementMean.PairRecord (rows := rows) + (StoppedProjectedExperiment.nativeSlots clauses o) + (StoppedProjectedExperiment.upper hupper o)) + intro event + change (HierarchicalUsefulCollision.pairLaw + (StoppedProjectedExperiment.nativeSlots clauses o) + (StoppedProjectedExperiment.upper hupper o) + (StoppedProjectedBuckets.externalLaw clauses rows repeats hupper hij designated hrows o hbranch flag) + (StoppedProjectedBuckets.background clauses rows repeats hupper hij designated hrows o) + (StoppedProjectedBuckets.scalarLaw clauses rows repeats hupper hij designated hrows o) + (StoppedProjectedBuckets.rows_positive rows hupper hrows o)).probability event = + ((StoppedProjectedBucketIndex.baseLaw (t := t) hij hbranch flag).mixture + (fixedPair clauses rows repeats hupper hij designated hrows o)).probability event + rw [HierarchicalUsefulCollision.pairLaw, FiniteDistribution.probability_pushforward, + HierarchicalUsefulCollision.law, CompletionSoundness.sigmaLaw_probability, + StoppedProjectedBuckets.externalLaw, CandidateCoupling.expectation_sigmaLaw, + FiniteDistribution.probability_mixture] + apply FiniteDistribution.expectation_congr + intro base + rw [fixedPair_eq] + rw [HierarchicalUsefulCollision.pairLaw, FiniteDistribution.probability_pushforward, + HierarchicalUsefulCollision.law, CompletionSoundness.sigmaLaw_probability] + rfl + +end +end PerfectCompleteness.StoppedProjectedPairMean + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/StoppedProjectedContext.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/StoppedProjectedContext.lean new file mode 100644 index 0000000000000000000000000000000000000000..0fc2689dbb40b0cf5a2ddf2b5c3b2fde0fd7a555 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/StoppedProjectedContext.lean @@ -0,0 +1,142 @@ +import OAI.Computability.PerfectCompleteness.Foundations.GeometricPrefixSplit +import OAI.Computability.PerfectCompleteness.Foundations.StoppedProjectedExperiment +import OAI.Computability.PerfectCompleteness.Sampling.StoppedSharedSampler + +namespace OAI + +section + +namespace PerfectCompleteness.StoppedProjectedContext + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +variable {branch : Nat → Nat} {n i j t m : Nat} + +abbrev Sample (rows : Nat → Nat) := + StoppedSharedSampler.Context branch n t m i rows × + SourceProjectedTag.Tag (branch := branch) (n := i) (t := t) + +abbrev SplitSample (rows : Nat → Nat) := + StoppedProjectedExperiment.Outer (branch := branch) (n := n) (j := j) (t := t) (m := m) × + StoppedProjectedExperiment.Inner (branch := branch) (n := n) (i := i) (j := j) (t := t) rows + +variable (rows : Nat → Nat) (hupper : j + 1 ≤ n) (hij : i < j) + +def splitEquiv : Sample (branch := branch) (n := n) (i := i) (t := t) (m := m) rows ≃ + SplitSample (branch := branch) (n := n) (i := i) (j := j) (t := t) (m := m) rows where + toFun x := + let prefixes := GeometricPrefixSplit.splitEquiv (Nat.succ_le_succ hij.le) hupper x.1.2.1 + ((x.1.1, prefixes.1), (prefixes.2, (x.2, x.1.2.2))) + invFun x := + ((x.1.1, ((GeometricPrefixSplit.splitEquiv (Nat.succ_le_succ hij.le) hupper).symm + (x.1.2, x.2.1), x.2.2.2)), x.2.2.1) + left_inv x := by + rcases x with ⟨⟨q, pref, directions⟩, tag⟩ + exact congrArg (fun pref => ((q, pref, directions), tag)) + ((GeometricPrefixSplit.splitEquiv (Nat.succ_le_succ hij.le) hupper).symm_apply_apply pref) + right_inv x := by + rcases x with ⟨⟨q, upper⟩, lower, tag, directions⟩ + simp only [Equiv.apply_symm_apply] + +@[simp] theorem questions_split + (x : Sample (branch := branch) (n := n) (i := i) (t := t) (m := m) rows) : + (splitEquiv rows hupper hij x).1.1 = x.1.1 := rfl + +@[simp] theorem tag_split + (x : Sample (branch := branch) (n := n) (i := i) (t := t) (m := m) rows) : + (splitEquiv rows hupper hij x).2.2.1 = x.2 := rfl + +@[simp] theorem directions_split + (x : Sample (branch := branch) (n := n) (i := i) (t := t) (m := m) rows) : + (splitEquiv rows hupper hij x).2.2.2 = x.1.2.2 := rfl + +theorem stoppedPath_split (hi : i + 1 ≤ n) + (x : Sample (branch := branch) (n := n) (i := i) (t := t) (m := m) rows) : + StoppedProjectedExperiment.stoppedPath rows hupper hij + (splitEquiv rows hupper hij x).1 (splitEquiv rows hupper hij x).2 = + GeometricCutSplit.prefixPath hi x.1.2.1 := + (GeometricPrefixSplit.prefixPath_split (Nat.succ_le_succ hij.le) hupper x.1.2.1).symm + +theorem lower_split (hi : i + 1 ≤ n) + (x : Sample (branch := branch) (n := n) (i := i) (t := t) (m := m) rows) : + StoppedProjectedExperiment.lower rows hupper hij + (splitEquiv rows hupper hij x).1 (splitEquiv rows hupper hij x).2 = + WholeArrayInteriorExterior.upperNode (GeometricCutSplit.prefixPath hi x.1.2.1) := + congrArg (fun p : Path branch n (i + 1) => WholeArrayInteriorExterior.upperNode p) + (stoppedPath_split rows hupper hij hi x) + +theorem fullPath_split_spec (hi : i + 1 ≤ n) + (x : Sample (branch := branch) (n := n) (i := i) (t := t) (m := m) rows) : + (⟨Nodes.height (StoppedProjectedExperiment.lower rows hupper hij + (splitEquiv rows hupper hij x).1 (splitEquiv rows hupper hij x).2), + WholeArrayInteriorOwnInputLaw.fullPath + (StoppedProjectedExperiment.upper hupper (splitEquiv rows hupper hij x).1) + (StoppedProjectedExperiment.lower rows hupper hij + (splitEquiv rows hupper hij x).1 (splitEquiv rows hupper hij x).2) + (StoppedProjectedExperiment.cut rows hupper hij + (splitEquiv rows hupper hij x).1 (splitEquiv rows hupper hij x).2)⟩ : + Σ height, Path branch n height) = + ⟨i + 1, GeometricCutSplit.prefixPath hi x.1.2.1⟩ := + (StoppedProjectedExperiment.fullPath_spec rows hupper hij + (splitEquiv rows hupper hij x).1 (splitEquiv rows hupper hij x).2).trans + (congrArg (fun p : Path branch n (i + 1) => + (⟨i + 1, p⟩ : Σ height, Path branch n height)) + (stoppedPath_split rows hupper hij hi x)) + +variable [NeZero m] (hi : i + 1 ≤ n) + (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) + (flag : Fin (branch i) → FiniteDistribution Bool) + +theorem expectation_split + (f : SplitSample (branch := branch) (n := n) (i := i) (j := j) (t := t) (m := m) rows → ℝ) : + ((StoppedSharedSampler.contextLaw (cut := i) hi hbranch hrows).product + (SourceProjectedTag.law (t := t) flag)).expectation + (fun x => f (splitEquiv rows hupper hij x)) = + ((StoppedProjectedExperiment.outerLaw (t := t) (m := m) hupper hbranch).product + (StoppedProjectedExperiment.innerLaw rows hij + (fun k hk => hbranch k (Nat.lt_of_lt_of_le hk hupper)) hrows flag)).expectation f := by + simp only [StoppedSharedSampler.contextLaw, StoppedProjectedExperiment.outerLaw, + StoppedProjectedExperiment.innerLaw, FiniteDistribution.expectation_product] + apply FiniteDistribution.expectation_congr + intro q + calc + _ = (GeometricCutSplit.prefixLaw hupper hbranch).expectation (fun upper => + (GeometricCutSplit.prefixLaw (Nat.succ_le_succ hij.le) + (fun k hk => hbranch k (Nat.lt_of_lt_of_le hk hupper))).expectation (fun lower => + (CanonicalDirections.law rows n hrows).expectation (fun directions => + (SourceProjectedTag.law (t := t) flag).expectation (fun tag => + f ((q, upper), (lower, (tag, directions))))))) := + GeometricPrefixSplit.expectation_split (Nat.succ_le_succ hij.le) hupper hbranch + (fun upper lower => (CanonicalDirections.law rows n hrows).expectation (fun directions => + (SourceProjectedTag.law (t := t) flag).expectation (fun tag => + f ((q, upper), (lower, (tag, directions)))))) + _ = _ := by + apply FiniteDistribution.expectation_congr + intro upper + apply FiniteDistribution.expectation_congr + intro lower + exact FiniteDistribution.expectation_comm _ _ _ + +theorem split_law : + ((StoppedSharedSampler.contextLaw (cut := i) hi hbranch hrows).product + (SourceProjectedTag.law (t := t) flag)).pushforward (splitEquiv rows hupper hij) = + (StoppedProjectedExperiment.outerLaw (t := t) (m := m) hupper hbranch).product + (StoppedProjectedExperiment.innerLaw rows hij + (fun k hk => hbranch k (Nat.lt_of_lt_of_le hk hupper)) hrows flag) := by + apply SigmaObservation.eq_of_probability_eq + intro event + rw [FiniteDistribution.probability_pushforward, CandidateCoupling.probability_eq_expectation, + CandidateCoupling.probability_eq_expectation] + exact expectation_split rows hupper hij hi hbranch hrows flag + (fun x => if event x then 1 else 0) + +end +end PerfectCompleteness.StoppedProjectedContext + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/StoppedProjectedExperiment.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/StoppedProjectedExperiment.lean new file mode 100644 index 0000000000000000000000000000000000000000..1e28f630708f8a5cf32e31f07924f08647a0d5d1 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/StoppedProjectedExperiment.lean @@ -0,0 +1,378 @@ +import OAI.Computability.PerfectCompleteness.Decoding.CutProjectionAssembly +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalProjectedExperimentLemmas +import OAI.Computability.PerfectCompleteness.Foundations.SourceProjectedTag +import OAI.Computability.PerfectCompleteness.Machines.SourcePhysicalTapeLaw +import OAI.Computability.PerfectCompleteness.Machines.StoppedOwnInputGeometry + +namespace OAI + +section + +namespace PerfectCompleteness.StoppedProjectedExperiment + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open RelativeDescendantProducts +open UniqueGamesTheorem.Foundations.Games + +variable {branch : Nat → Nat} {n i j t v m : Nat} + +theorem below_append (hij : i < j) : {n : Nat} → (p : Path branch n (j + 1)) → + (q : Path branch (j + 1) (i + 1)) → + Below branch (WholeArrayInteriorExterior.upperNode p) + (WholeArrayInteriorExterior.upperNode (p.append q)) + | _, .refl _, q => by + cases q with + | refl => omega + | step child q => exact Below.root child (WholeArrayInteriorExterior.upperNode q) + | _, .step child p, q => Below.child child (below_append hij p q) + +abbrev Outer := PreliminarySampler.Questions branch n t m × + GeometricCutSplit.Prefix branch n (j + 1) + +abbrev Inner (rows : Nat → Nat) := + GeometricCutSplit.Prefix branch (j + 1) (i + 1) × + (SourceProjectedTag.Tag (branch := branch) (n := i) (t := t) × + CanonicalDirections.Tuple rows n) + +def outerLaw [NeZero m] (hupper : j + 1 ≤ n) + (hbranch : ∀ k < n, 0 < branch k) : + FiniteDistribution (Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) := + PreliminarySampler.questionsLaw.product (GeometricCutSplit.prefixLaw hupper hbranch) + +def innerLaw (rows : Nat → Nat) (hij : i < j) + (hbranch : ∀ k < j + 1, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) + (flag : Fin (branch i) → FiniteDistribution Bool) : + FiniteDistribution (Inner (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) := + (GeometricCutSplit.prefixLaw (Nat.succ_le_succ hij.le) hbranch).product + ((SourceProjectedTag.law (t := t) flag).product (CanonicalDirections.law rows n hrows)) + +variable (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hupper : j + 1 ≤ n) (hij : i < j) + (designated : Fin (branch i) → Slots branch i) + +abbrev nativeSlots (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) := + sourceSlots clauses (PreliminarySampler.endpoints o.1) + +def upperPath (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) := + GeometricCutSplit.prefixPath hupper o.2 + +def lowerPath (k : Inner (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) := + GeometricCutSplit.prefixPath (Nat.succ_le_succ hij.le) k.1 + +def stoppedPath (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) + (k : Inner (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) := + (upperPath hupper o).append (lowerPath rows hij k) + +def upper (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) := + WholeArrayInteriorExterior.upperNode (upperPath hupper o) + +def lower (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) + (k : Inner (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) := + WholeArrayInteriorExterior.upperNode (stoppedPath rows hupper hij o k) + +@[simp] theorem upper_height (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) : + Nodes.height (upper hupper o) = j + 1 := + WholeArrayInteriorExterior.upperNode_height _ + +@[simp] theorem lower_height (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) + (k : Inner (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) : + Nodes.height (lower rows hupper hij o k) = i + 1 := + WholeArrayInteriorExterior.upperNode_height _ + +def cut (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) + (k : Inner (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) : + OwnInputReference.Cut (upper hupper o) (lower rows hupper hij o k) := + StoppedOwnInputGeometry.cutOfBelow (below_append hij (upperPath hupper o) (lowerPath rows hij k)) + +theorem fullPath_spec (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) + (k : Inner (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) : + (⟨Nodes.height (lower rows hupper hij o k), + WholeArrayInteriorOwnInputLaw.fullPath (upper hupper o) (lower rows hupper hij o k) + (cut rows hupper hij o k)⟩ : Σ height, Path branch n height) = + ⟨i + 1, stoppedPath rows hupper hij o k⟩ := by + have hpath : + WholeArrayInteriorOwnInputLaw.fullPath (upper hupper o) (lower rows hupper hij o k) + (cut rows hupper hij o k) = Nodes.path (lower rows hupper hij o k) := + StoppedOwnInputGeometry.fullPath_cutOfBelow + (below_append hij (upperPath hupper o) (lowerPath rows hij k)) + exact (congrArg (fun path : Path branch n (Nodes.height (lower rows hupper hij o k)) => + (⟨Nodes.height (lower rows hupper hij o k), path⟩ : Σ height, Path branch n height)) + hpath).trans + (WholeArrayInteriorExterior.upperNode_spec (stoppedPath rows hupper hij o k)) + +def cutQuestions (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) + (k : Inner (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) : + PreliminarySampler.Questions branch (i + 1) t m := + fun leaf a => o.1 ((stoppedPath rows hupper hij o k).slotEmbedding leaf) a + +def projectedSlots (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) + (k : Inner (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) : + Slots branch n → Fin t → MixedSupport.Slot := + CutSlotAssembly.fill (stoppedPath rows hupper hij o k) (nativeSlots clauses o) + (SourceProjectedTag.mixedInside clauses designated (cutQuestions rows hupper hij o k) + k.2.1.1 k.2.1.2) + +theorem fill_native (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) + (k : Inner (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) : + CutSlotAssembly.fill (stoppedPath rows hupper hij o k) (nativeSlots clauses o) + (SourceProjectedTag.originalSlots clauses (cutQuestions rows hupper hij o k)) = + nativeSlots clauses o := + CutSlotAssembly.fill_restrict (stoppedPath rows hupper hij o k) (nativeSlots clauses o) + +def projection (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) + (k : Inner (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) : + ∀ leaf a, MixedSupport.Projection (nativeSlots clauses o leaf a) + (projectedSlots clauses rows hupper hij designated o k leaf a) := + fun leaf a => CutProjectionAssembly.castProjection + (congrFun (congrFun (fill_native clauses rows hupper hij o k) leaf) a) rfl + (CutProjectionAssembly.fillProjection (stoppedPath rows hupper hij o k) (nativeSlots clauses o) + (SourceProjectedTag.originalSlots clauses (cutQuestions rows hupper hij o k)) + (SourceProjectedTag.mixedInside clauses designated (cutQuestions rows hupper hij o k) + k.2.1.1 k.2.1.2) + (SourceProjectedTag.projection clauses designated (cutQuestions rows hupper hij o k) + k.2.1.1 k.2.1.2) leaf a) + +def direction (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) + (k : Inner (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) : + Block rows (lower rows hupper hij o k) := + let level : Fin n := ⟨i, Nat.lt_of_lt_of_le (Nat.lt_trans hij (Nat.lt_succ_self j)) hupper⟩ + (PrefixTests.nodeDirection rows level + ⟨lower rows hupper hij o k, lower_height rows hupper hij o k⟩ (k.2.2 level)).val + +variable (hbranch : ∀ k < j + 1, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) + (flag : Fin (branch i) → FiniteDistribution Bool) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + +abbrev experiment (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) := + HierarchicalProjectedExperiment.experiment (rows := rows) (repeats := repeats) + (nativeSlots clauses o) (projectedSlots clauses rows hupper hij designated o) + (projection clauses rows hupper hij designated o) (upper hupper o) (i + 1) + (lower rows hupper hij o) (cut rows hupper hij o) (direction rows hupper hij o) + (innerLaw rows hij hbranch hrows flag) σ + +abbrev TapeSample (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) := + (k : Inner (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) × + WholeArraySampler.Tape rows repeats (stoppedPath rows hupper hij o k) + (projectedSlots clauses rows hupper hij designated o k) + +def tapeLaw (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) : + FiniteDistribution (TapeSample clauses rows repeats hupper hij designated o) := + CompletionSoundness.sigmaLaw (innerLaw rows hij hbranch hrows flag) (fun k => + WholeArraySampler.tapeLaw rows repeats (stoppedPath rows hupper hij o k) + (projectedSlots clauses rows hupper hij designated o k)) + +def tapeRead (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) + (sample : TapeSample clauses rows repeats hupper hij designated o) : + HierarchicalProjectedExperiment.Sample (rows := rows) (repeats := repeats) + (projectedSlots clauses rows hupper hij designated o) (upper hupper o) + (lower rows hupper hij o) (cut rows hupper hij o) := + ⟨sample.1, StoppedOwnInputGeometry.pathTapeEquiv rows repeats + (projectedSlots clauses rows hupper hij designated o sample.1) + (fullPath_spec rows hupper hij o sample.1).symm sample.2⟩ + +theorem tapeRead_law (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) : + (tapeLaw clauses rows repeats hupper hij designated hbranch hrows flag o).pushforward + (tapeRead clauses rows repeats hupper hij designated o) = + (experiment clauses rows repeats hupper hij designated hbranch hrows flag σ o).original := by + calc + _ = CompletionSoundness.sigmaLaw (innerLaw rows hij hbranch hrows flag) (fun k => + (WholeArraySampler.tapeLaw rows repeats (stoppedPath rows hupper hij o k) + (projectedSlots clauses rows hupper hij designated o k)).pushforward + (StoppedOwnInputGeometry.pathTapeEquiv rows repeats + (projectedSlots clauses rows hupper hij designated o k) + (fullPath_spec rows hupper hij o k).symm)) := + SigmaObservation.pushforward_fiber (innerLaw rows hij hbranch hrows flag) + (fun k => WholeArraySampler.tapeLaw rows repeats (stoppedPath rows hupper hij o k) + (projectedSlots clauses rows hupper hij designated o k)) + (fun k tape => StoppedOwnInputGeometry.pathTapeEquiv rows repeats + (projectedSlots clauses rows hupper hij designated o k) + (fullPath_spec rows hupper hij o k).symm tape) + _ = _ := + congrArg (fun kernel : + (k : Inner (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) → + FiniteDistribution (WholeArraySampler.Tape rows repeats + (WholeArrayInteriorOwnInputLaw.fullPath (upper hupper o) + (lower rows hupper hij o k) (cut rows hupper hij o k)) + (projectedSlots clauses rows hupper hij designated o k)) => + CompletionSoundness.sigmaLaw (innerLaw rows hij hbranch hrows flag) kernel) + (funext (fun k => StoppedOwnInputGeometry.pathTapeEquiv_law rows repeats + (projectedSlots clauses rows hupper hij designated o k) + (fullPath_spec rows hupper hij o k).symm)) + +theorem arrays_tapeRead (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) + (sample : TapeSample clauses rows repeats hupper hij designated o) : + (experiment clauses rows repeats hupper hij designated hbranch hrows flag σ o).arrays + (tapeRead clauses rows repeats hupper hij designated o sample) = + ChildBlockProjection.arraysPullback rows + (projection clauses rows hupper hij designated o sample.1) + (WholeArraySampler.evaluate rows repeats (stoppedPath rows hupper hij o sample.1) + (projectedSlots clauses rows hupper hij designated o sample.1) sample.2) := + congrArg (ChildBlockProjection.arraysPullback rows + (projection clauses rows hupper hij designated o sample.1)) + (StoppedOwnInputGeometry.evaluate_pathTapeEquiv rows repeats + (projectedSlots clauses rows hupper hij designated o sample.1) + (fullPath_spec rows hupper hij o sample.1).symm sample.2) + +section Physical + +variable [NeZero m] + +abbrev PhysicalBase := + GeometricCutSplit.Prefix branch (j + 1) (i + 1) × + (SourceQuestionKernelJoint.ChoiceTuple (branch := branch) (n := i) (t := t) × + CanonicalDirections.Tuple rows n) + +def withFlags (base : PhysicalBase (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) + (flags : SourceProjectedTag.Flags (branch := branch) (n := i)) : + Inner (branch := branch) (n := n) (i := i) (j := j) (t := t) rows := + (base.1, ((base.2.1, flags), base.2.2)) + +def physicalBaseLaw : + FiniteDistribution (PhysicalBase (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) := + (GeometricCutSplit.prefixLaw (Nat.succ_le_succ hij.le) hbranch).product + ((SourceProjectedTag.positionLaw (branch := branch) (n := i) (t := t)).product + (CanonicalDirections.law rows n hrows)) + +abbrev baseTag (base : PhysicalBase (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) := + withFlags rows base (fun _ => false) + +def physicalSources (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) + (base : PhysicalBase (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) := + SourceQuestionKernelJoint.sources designated + (cutQuestions rows hupper hij o (baseTag rows base)) base.2.1 + +abbrev PhysicalRaw (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) + (base : PhysicalBase (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) := + SourcePhysicalWholeLaw.Raw rows repeats (stoppedPath rows hupper hij o (baseTag rows base)) + (nativeSlots clauses o) + (SourceProjectedTag.originalSlots clauses (cutQuestions rows hupper hij o (baseTag rows base))) + clauses designated + +abbrev PhysicalSample (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) := + (base : PhysicalBase (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) × + PhysicalRaw clauses rows repeats hupper hij designated o base + +def physicalFiberLaw (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) + (base : PhysicalBase (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) : + FiniteDistribution (PhysicalRaw clauses rows repeats hupper hij designated o base) := + SourcePhysicalWholeLaw.rawLaw rows repeats (stoppedPath rows hupper hij o (baseTag rows base)) + (nativeSlots clauses o) + (SourceProjectedTag.originalSlots clauses (cutQuestions rows hupper hij o (baseTag rows base))) + clauses designated flag (physicalSources rows hupper hij designated o base) + +def physicalLaw (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) : + FiniteDistribution (PhysicalSample clauses rows repeats hupper hij designated o) := + CompletionSoundness.sigmaLaw (physicalBaseLaw rows hij hbranch hrows) + (physicalFiberLaw clauses rows repeats hupper hij designated flag o) + +def physicalRead (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) + (sample : PhysicalSample clauses rows repeats hupper hij designated o) : + TapeSample clauses rows repeats hupper hij designated o := + let observed := SourcePhysicalTapeLaw.observeFiber rows repeats + (stoppedPath rows hupper hij o (baseTag rows sample.1)) (nativeSlots clauses o) + (SourceProjectedTag.originalSlots clauses (cutQuestions rows hupper hij o (baseTag rows sample.1))) + clauses designated (physicalSources rows hupper hij designated o sample.1) sample.2 + ⟨withFlags rows sample.1 observed.1, observed.2⟩ + +omit [NeZero m] in +theorem physicalFiber_probability + (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) + (base : PhysicalBase (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) + (event : TapeSample clauses rows repeats hupper hij designated o → Bool) : + (physicalFiberLaw clauses rows repeats hupper hij designated flag o base).probability + (fun raw => event (physicalRead clauses rows repeats hupper hij designated o ⟨base, raw⟩)) = + (SourceProjectedTag.flagLaw flag).expectation (fun flags => + (WholeArraySampler.tapeLaw rows repeats + (stoppedPath rows hupper hij o (withFlags rows base flags)) + (projectedSlots clauses rows hupper hij designated o (withFlags rows base flags))).probability + (fun tape => event ⟨withFlags rows base flags, tape⟩)) := by + have hlaw := SourcePhysicalTapeLaw.observeFiber_law rows repeats + (stoppedPath rows hupper hij o (baseTag rows base)) (nativeSlots clauses o) + (SourceProjectedTag.originalSlots clauses (cutQuestions rows hupper hij o (baseTag rows base))) + clauses designated flag (physicalSources rows hupper hij designated o base) + have h := congrArg (fun μ : FiniteDistribution + ((flags : SourceProjectedTag.Flags (branch := branch) (n := i)) × + WholeArraySampler.Tape rows repeats + (stoppedPath rows hupper hij o (withFlags rows base flags)) + (projectedSlots clauses rows hupper hij designated o (withFlags rows base flags))) => + μ.probability (fun observed => + event (⟨withFlags rows base observed.1, observed.2⟩ : + TapeSample clauses rows repeats hupper hij designated o))) hlaw + have hp := FiniteDistribution.probability_pushforward + (Ω := PhysicalRaw clauses rows repeats hupper hij designated o base) + (Γ := ((flags : SourceProjectedTag.Flags (branch := branch) (n := i)) × + WholeArraySampler.Tape rows repeats + (stoppedPath rows hupper hij o (withFlags rows base flags)) + (projectedSlots clauses rows hupper hij designated o (withFlags rows base flags)))) + (physicalFiberLaw clauses rows repeats hupper hij designated flag o base) + (SourcePhysicalTapeLaw.observeFiber rows repeats + (stoppedPath rows hupper hij o (baseTag rows base)) (nativeSlots clauses o) + (SourceProjectedTag.originalSlots clauses (cutQuestions rows hupper hij o (baseTag rows base))) + clauses designated (physicalSources rows hupper hij designated o base)) + (fun observed => event ⟨withFlags rows base observed.1, observed.2⟩) + have hs := CompletionSoundness.sigmaLaw_probability (SourceProjectedTag.flagLaw flag) + (fun flags => WholeArraySampler.tapeLaw rows repeats + (stoppedPath rows hupper hij o (withFlags rows base flags)) + (projectedSlots clauses rows hupper hij designated o (withFlags rows base flags))) + (fun observed => event ⟨withFlags rows base observed.1, observed.2⟩) + exact hp.symm.trans (h.trans hs) + +omit [NeZero m] in +theorem physicalRead_law + (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) : + (physicalLaw clauses rows repeats hupper hij designated hbranch hrows flag o).pushforward + (physicalRead clauses rows repeats hupper hij designated o) = + tapeLaw clauses rows repeats hupper hij designated hbranch hrows flag o := by + apply SigmaObservation.eq_of_probability_eq + intro event + rw [FiniteDistribution.probability_pushforward, physicalLaw, + CompletionSoundness.sigmaLaw_probability, tapeLaw, CompletionSoundness.sigmaLaw_probability] + simp only [physicalBaseLaw, innerLaw, SourceProjectedTag.law, + FiniteDistribution.expectation_product] + apply FiniteDistribution.expectation_congr + intro pref + apply FiniteDistribution.expectation_congr + intro positions + calc + _ = (CanonicalDirections.law rows n hrows).expectation (fun directions => + (SourceProjectedTag.flagLaw flag).expectation (fun flags => + (WholeArraySampler.tapeLaw rows repeats + (stoppedPath rows hupper hij o (withFlags rows (pref, (positions, directions)) flags)) + (projectedSlots clauses rows hupper hij designated o + (withFlags rows (pref, (positions, directions)) flags))).probability + (fun tape => event ⟨withFlags rows (pref, (positions, directions)) flags, tape⟩))) := by + apply FiniteDistribution.expectation_congr + intro directions + exact physicalFiber_probability clauses rows repeats hupper hij designated flag o + (pref, (positions, directions)) event + _ = _ := FiniteDistribution.expectation_comm _ _ _ + +def physicalExperimentRead + (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) + (sample : PhysicalSample clauses rows repeats hupper hij designated o) := + tapeRead clauses rows repeats hupper hij designated o + (physicalRead clauses rows repeats hupper hij designated o sample) + +omit [NeZero m] in +theorem physicalExperimentRead_law + (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) : + (physicalLaw clauses rows repeats hupper hij designated hbranch hrows flag o).pushforward + (physicalExperimentRead clauses rows repeats hupper hij designated o) = + (experiment clauses rows repeats hupper hij designated hbranch hrows flag σ o).original := by + change (physicalLaw clauses rows repeats hupper hij designated hbranch hrows flag o).pushforward + (fun sample => tapeRead clauses rows repeats hupper hij designated o + (physicalRead clauses rows repeats hupper hij designated o sample)) = _ + rw [← FiniteDistribution.pushforward_comp, physicalRead_law] + exact tapeRead_law clauses rows repeats hupper hij designated hbranch hrows flag σ o + +end Physical + +end +end PerfectCompleteness.StoppedProjectedExperiment + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/StoppedProjectedOldRecord.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/StoppedProjectedOldRecord.lean new file mode 100644 index 0000000000000000000000000000000000000000..dd177dfc34f84b6176071b75c6f9bd2571de5eb4 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/StoppedProjectedOldRecord.lean @@ -0,0 +1,328 @@ +import OAI.Computability.PerfectCompleteness.Construction.StoppedProjectedBuckets +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalPairCoarse +import OAI.Computability.PerfectCompleteness.Sampling.StoppedProjectedGlobalLawLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.StoppedProjectedOldRecord + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype + +variable {branch : Nat → Nat} {n i j t v m : Nat} + +local instance fixedBackgroundFintype (rows : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) (upper : Nodes branch n) : + Fintype (HierarchicalMatrixTable.Background (rows := rows) slots upper) := + HierarchicalUsefulCollision.backgroundFintype (rows := rows) slots upper + +private theorem fixed_old_probability (rows repeats : Nat → Nat) + (p : Path branch n (j + 1)) (chosen : Fin (branch j)) (q : Path branch j (i + 1)) + (native right : Slots branch n → Fin t → MixedSupport.Slot) + (projection : ∀ s a, MixedSupport.Projection (native s a) (right s a)) + (hrows : 0 < rows (j + 1)) + (event : HierarchicalMatrixTable.Background (rows := rows) native + (WholeArrayInteriorExterior.upperNode p) × + HierarchicalMatrixTable.Matrix (rows := rows) native + (WholeArrayInteriorExterior.upperNode p) → Bool) : + (WholeArraySampler.law rows repeats (p.append (.step chosen q)) right).probability + (fun arrays => event + (HierarchicalMatrixTable.backgroundOf native (WholeArrayInteriorExterior.upperNode p) + (ChildBlockProjection.arraysPullback rows projection arrays), + NodeEmbedding.matrix (ChildBlockProjection.arraysPullback rows projection arrays) + (WholeArrayInteriorExterior.upperNode p))) = + (HierarchicalUsefulCollision.pairLaw native (WholeArrayInteriorExterior.upperNode p) + (StoppedUsefulPairLaw.externalLaw rows repeats p chosen q right) + (StoppedUsefulPairLaw.background rows repeats p chosen q native right projection) + (StoppedUsefulPairLaw.scalarLaw rows repeats p chosen q native right projection) + (by simpa only [WholeArrayInteriorExterior.upperNode_height] using hrows)).probability + (fun record => event (record.1, record.2.1)) := by + rw [← StoppedUsefulPairLaw.actualPair_law rows repeats p chosen q native right projection hrows, + FiniteDistribution.probability_pushforward, WholeArraySampler.probability_law] + simp only [StoppedUsefulPairLaw.actualLaw, StoppedUsefulPairLaw.actualPair, + UpperScalarCutProjection.projectedPair, CandidateCoupling.probability_eq_expectation, + FiniteDistribution.expectation_product] + let directions := StoppedUsefulPairLaw.directionLaw rows j hrows + let tapes := WholeArraySampler.tapeLaw rows repeats (p.append (.step chosen q)) right + let fresh := RecursiveSampler.law TreeSourceSpaces.F2 repeats (.step chosen q) + (LeafDomain (OriginalWholeCutTape.cutSlots p right)) + let oldValue : WholeArraySampler.Tape rows repeats (p.append (.step chosen q)) right → ℝ := + fun tape => if event + (HierarchicalMatrixTable.backgroundOf native (WholeArrayInteriorExterior.upperNode p) + (ChildBlockProjection.arraysPullback rows projection + (WholeArraySampler.evaluate rows repeats (p.append (.step chosen q)) right tape)), + NodeEmbedding.matrix (ChildBlockProjection.arraysPullback rows projection + (WholeArraySampler.evaluate rows repeats (p.append (.step chosen q)) right tape)) + (WholeArrayInteriorExterior.upperNode p)) then 1 else 0 + change tapes.expectation oldValue = directions.expectation + (fun _ => tapes.expectation (fun tape => fresh.expectation (fun _ => oldValue tape))) + symm + calc + _ = tapes.expectation (fun tape => fresh.expectation (fun _ => oldValue tape)) := + SmallBias.expectation_const directions + (tapes.expectation (fun tape => fresh.expectation (fun _ => oldValue tape))) + _ = tapes.expectation oldValue := by + apply FiniteDistribution.expectation_congr + intro tape + exact SmallBias.expectation_const fresh (oldValue tape) + +variable (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hupper : j + 1 ≤ n) (hij : i < j) + (designated : Fin (branch i) → Slots branch i) + (hrows : ∀ k, 0 < rows (k + 1)) + (o : StoppedProjectedExperiment.Outer + (branch := branch) (n := n) (j := j) (t := t) (m := m)) + +abbrev OldRecord := + HierarchicalMatrixTable.Background (rows := rows) + (StoppedProjectedExperiment.nativeSlots clauses o) (StoppedProjectedExperiment.upper hupper o) × + HierarchicalMatrixTable.Matrix (rows := rows) + (StoppedProjectedExperiment.nativeSlots clauses o) (StoppedProjectedExperiment.upper hupper o) + +local instance backgroundFintype : Fintype (HierarchicalMatrixTable.Background (rows := rows) + (StoppedProjectedExperiment.nativeSlots clauses o) (StoppedProjectedExperiment.upper hupper o)) := + StoppedProjectedBuckets.backgroundFintype clauses rows hupper o + +local instance rowSpaceFintype : Fintype (NodeEmbedding.RowSpace + (StoppedProjectedExperiment.nativeSlots clauses o) (StoppedProjectedExperiment.upper hupper o)) := + StoppedProjectedBuckets.rowSpaceFintype clauses hupper o + +def arrayRecord (arrays : Arrays (StoppedProjectedExperiment.nativeSlots clauses o) rows) : + OldRecord clauses rows hupper o := + (HierarchicalMatrixTable.backgroundOf (StoppedProjectedExperiment.nativeSlots clauses o) + (StoppedProjectedExperiment.upper hupper o) arrays, + NodeEmbedding.matrix arrays (StoppedProjectedExperiment.upper hupper o)) + +def baseProbability + (event : OldRecord clauses rows hupper o → Bool) + (base : StoppedProjectedBuckets.Base (branch := branch) (i := i) (j := j) (t := t)) : ℝ := + (WholeArraySampler.law rows repeats + (StoppedProjectedExperiment.stoppedPath rows hupper hij o + (StoppedProjectedBuckets.key (n := n) rows hrows base)) + (StoppedProjectedBuckets.projected clauses rows hupper hij designated hrows o base)).probability + (fun arrays => event (arrayRecord clauses rows hupper o + (ChildBlockProjection.arraysPullback rows + (StoppedProjectedBuckets.projection clauses rows hupper hij designated hrows o base) + arrays))) + +theorem base_probability_eq_pair + (event : OldRecord clauses rows hupper o → Bool) + (base : StoppedProjectedBuckets.Base (branch := branch) (i := i) (j := j) (t := t)) : + baseProbability clauses rows repeats hupper hij designated hrows o event base = + (HierarchicalUsefulCollision.pairLaw + (StoppedProjectedExperiment.nativeSlots clauses o) (StoppedProjectedExperiment.upper hupper o) + (StoppedProjectedBuckets.exteriorLaw clauses rows repeats hupper hij designated hrows o base) + (fun external => StoppedProjectedBuckets.background clauses rows repeats hupper hij + designated hrows o ⟨base, external⟩) + (fun external => StoppedProjectedBuckets.scalarLaw clauses rows repeats hupper hij + designated hrows o ⟨base, external⟩) + (StoppedProjectedBuckets.rows_positive rows hupper hrows o)).probability + (fun record => event (record.1, record.2.1)) := by + have hp : StoppedProjectedExperiment.stoppedPath rows hupper hij o + (StoppedProjectedBuckets.key (n := n) rows hrows base) = + (StoppedProjectedExperiment.upperPath hupper o).append + (.step (StoppedProjectedBuckets.chosen (n := n) rows hij hrows base) + (StoppedProjectedBuckets.continuation (n := n) rows hij hrows base)) := + congrArg (fun path => (StoppedProjectedExperiment.upperPath hupper o).append path) + (StoppedProjectedBuckets.lowerPath_eq_step (n := n) rows hij hrows base) + unfold baseProbability + rw [hp] + exact fixed_old_probability rows repeats (StoppedProjectedExperiment.upperPath hupper o) + (StoppedProjectedBuckets.chosen (n := n) rows hij hrows base) + (StoppedProjectedBuckets.continuation (n := n) rows hij hrows base) + (StoppedProjectedExperiment.nativeSlots clauses o) + (StoppedProjectedBuckets.projected clauses rows hupper hij designated hrows o base) + (StoppedProjectedBuckets.projection clauses rows hupper hij designated hrows o base) + (hrows j) event + +variable (hbranch : ∀ k < j + 1, 0 < branch k) + (flag : Fin (branch i) → FiniteDistribution Bool) + +abbrev pairLaw := + HierarchicalUsefulCollision.pairLaw + (StoppedProjectedExperiment.nativeSlots clauses o) (StoppedProjectedExperiment.upper hupper o) + (StoppedProjectedBuckets.externalLaw clauses rows repeats hupper hij designated hrows o hbranch flag) + (StoppedProjectedBuckets.background clauses rows repeats hupper hij designated hrows o) + (StoppedProjectedBuckets.scalarLaw clauses rows repeats hupper hij designated hrows o) + (StoppedProjectedBuckets.rows_positive rows hupper hrows o) + +theorem pair_probability_eq_mean (event : OldRecord clauses rows hupper o → Bool) : + (pairLaw clauses rows repeats hupper hij designated hrows o hbranch flag).probability + (fun record => event (record.1, record.2.1)) = + (StoppedProjectedBucketIndex.baseLaw (t := t) hij hbranch flag).expectation + (baseProbability clauses rows repeats hupper hij designated hrows o event) := by + simp only [pairLaw, HierarchicalUsefulCollision.pairLaw, + FiniteDistribution.probability_pushforward, HierarchicalUsefulCollision.law, + CompletionSoundness.sigmaLaw_probability, StoppedProjectedBuckets.externalLaw, + CandidateCoupling.expectation_sigmaLaw] + apply FiniteDistribution.expectation_congr + intro base + simpa only [HierarchicalUsefulCollision.pairLaw, + FiniteDistribution.probability_pushforward, HierarchicalUsefulCollision.law, + CompletionSoundness.sigmaLaw_probability, HierarchicalUsefulCollision.pairRecord, + HierarchicalAgreementMean.pairRecord] using + (base_probability_eq_pair clauses rows repeats hupper hij designated hrows o event base).symm + +variable (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + +theorem original_probability_eq_mean (event : OldRecord clauses rows hupper o → Bool) : + (StoppedProjectedBuckets.experiment clauses rows repeats hupper hij designated hrows o + hbranch flag σ).original.probability (fun x => + event (HierarchicalAdviceExperiment.background + (StoppedProjectedBuckets.experiment clauses rows repeats hupper hij designated hrows o + hbranch flag σ) x, + HierarchicalAdviceExperiment.matrix + (StoppedProjectedBuckets.experiment clauses rows repeats hupper hij designated hrows o + hbranch flag σ) x)) = + (StoppedProjectedBucketIndex.baseLaw (t := t) hij hbranch flag).expectation + (baseProbability clauses rows repeats hupper hij designated hrows o event) := by + rw [← StoppedProjectedExperiment.tapeRead_law clauses rows repeats hupper hij designated + hbranch hrows flag σ o, FiniteDistribution.probability_pushforward] + have hread : (fun sample : StoppedProjectedExperiment.TapeSample clauses rows repeats + hupper hij designated o => + event (HierarchicalAdviceExperiment.background + (StoppedProjectedBuckets.experiment clauses rows repeats hupper hij designated hrows o + hbranch flag σ) + (StoppedProjectedExperiment.tapeRead clauses rows repeats hupper hij designated o sample), + HierarchicalAdviceExperiment.matrix + (StoppedProjectedBuckets.experiment clauses rows repeats hupper hij designated hrows o + hbranch flag σ) + (StoppedProjectedExperiment.tapeRead clauses rows repeats hupper hij designated o sample))) = + (fun sample => event (arrayRecord clauses rows hupper o + (ChildBlockProjection.arraysPullback rows + (StoppedProjectedExperiment.projection clauses rows hupper hij designated o sample.1) + (WholeArraySampler.evaluate rows repeats + (StoppedProjectedExperiment.stoppedPath rows hupper hij o sample.1) + (StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated o sample.1) + sample.2)))) := by + funext sample + unfold HierarchicalAdviceExperiment.background HierarchicalAdviceExperiment.matrix arrayRecord + rw [StoppedProjectedExperiment.arrays_tapeRead clauses rows repeats hupper hij designated + hbranch hrows flag σ o sample] + rfl + rw [hread, CandidateCoupling.probability_eq_expectation] + let level : Fin n := ⟨j, Nat.lt_of_lt_of_le (Nat.lt_succ_self j) hupper⟩ + have hcoord := StoppedProjectedBucketIndex.expectation_coordinate clauses rows repeats + hupper hij designated hrows o hbranch flag level + (fun base _ tape => if event (arrayRecord clauses rows hupper o + (ChildBlockProjection.arraysPullback rows + (StoppedProjectedBuckets.projection clauses rows hupper hij designated hrows o base) + (WholeArraySampler.evaluate rows repeats + (StoppedProjectedExperiment.stoppedPath rows hupper hij o + (StoppedProjectedBuckets.key (n := n) rows hrows base)) + (StoppedProjectedBuckets.projected clauses rows hupper hij designated hrows o base) + tape))) then 1 else 0) + simp only [SmallBias.expectation_const, StoppedProjectedBucketIndex.tapeLaw] at hcoord + unfold baseProbability + simp only [CandidateCoupling.probability_eq_expectation, WholeArraySampler.law, + FiniteDistribution.expectation_pushforward] + exact hcoord + +theorem original_oldRecord_law : + (StoppedProjectedBuckets.experiment clauses rows repeats hupper hij designated hrows o + hbranch flag σ).original.pushforward (fun x => + (HierarchicalAdviceExperiment.background + (StoppedProjectedBuckets.experiment clauses rows repeats hupper hij designated hrows o + hbranch flag σ) x, + HierarchicalAdviceExperiment.matrix + (StoppedProjectedBuckets.experiment clauses rows repeats hupper hij designated hrows o + hbranch flag σ) x)) = + (pairLaw clauses rows repeats hupper hij designated hrows o hbranch flag).pushforward + (HierarchicalPairCoarse.oldRecord + (StoppedProjectedBuckets.experiment clauses rows repeats hupper hij designated hrows o + hbranch flag σ)) := by + apply SigmaObservation.eq_of_probability_eq + intro event + calc + _ = (StoppedProjectedBuckets.experiment clauses rows repeats hupper hij designated hrows o + hbranch flag σ).original.probability (fun x => event + (HierarchicalAdviceExperiment.background + (StoppedProjectedBuckets.experiment clauses rows repeats hupper hij designated hrows o + hbranch flag σ) x, + HierarchicalAdviceExperiment.matrix + (StoppedProjectedBuckets.experiment clauses rows repeats hupper hij designated hrows o + hbranch flag σ) x)) := + FiniteDistribution.probability_pushforward _ _ event + _ = (pairLaw clauses rows repeats hupper hij designated hrows o hbranch flag).probability + (fun record => event (record.1, record.2.1)) := + (original_probability_eq_mean clauses rows repeats hupper hij designated hrows o + hbranch flag σ event).trans + (pair_probability_eq_mean clauses rows repeats hupper hij designated hrows o + hbranch flag event).symm + _ = _ := (FiniteDistribution.probability_pushforward + (pairLaw clauses rows repeats hupper hij designated hrows o hbranch flag) + (fun record => (record.1, record.2.1)) event).symm + +theorem global_oldRecord_law [NeZero m] (hbranchAll : ∀ k < n, 0 < branch k) : + (StoppedProjectedGlobalLaw.experimentLaw clauses rows repeats hupper hij designated + hbranchAll hrows flag σ).pushforward + (fun x => (⟨x.1, + (HierarchicalAdviceExperiment.background + (StoppedProjectedGlobalLaw.experiment clauses rows repeats hupper hij designated + hbranchAll hrows flag σ x.1) x.2, + HierarchicalAdviceExperiment.matrix + (StoppedProjectedGlobalLaw.experiment clauses rows repeats hupper hij designated + hbranchAll hrows flag σ x.1) x.2)⟩ : + (o : StoppedProjectedExperiment.Outer + (branch := branch) (n := n) (j := j) (t := t) (m := m)) × + OldRecord clauses rows hupper o)) = + (CompletionSoundness.sigmaLaw (StoppedProjectedExperiment.outerLaw hupper hbranchAll) + (fun o => pairLaw clauses rows repeats hupper hij designated hrows o + (fun k hk => hbranchAll k (Nat.lt_of_lt_of_le hk hupper)) flag)).pushforward + (fun record => (⟨record.1, (record.2.1, record.2.2.1)⟩ : + (o : StoppedProjectedExperiment.Outer + (branch := branch) (n := n) (j := j) (t := t) (m := m)) × + OldRecord clauses rows hupper o)) := by + let originalFiber := fun context : StoppedProjectedExperiment.Outer + (branch := branch) (n := n) (j := j) (t := t) (m := m) => + (StoppedProjectedGlobalLaw.experiment clauses rows repeats hupper hij designated + hbranchAll hrows flag σ context).original + let pairedFiber := fun context : StoppedProjectedExperiment.Outer + (branch := branch) (n := n) (j := j) (t := t) (m := m) => + pairLaw clauses rows repeats hupper hij designated hrows context + (fun k hk => hbranchAll k (Nat.lt_of_lt_of_le hk hupper)) flag + let originalRecord := fun (context : StoppedProjectedExperiment.Outer + (branch := branch) (n := n) (j := j) (t := t) (m := m)) x => + ((HierarchicalAdviceExperiment.background + (StoppedProjectedGlobalLaw.experiment clauses rows repeats hupper hij designated + hbranchAll hrows flag σ context) x, + HierarchicalAdviceExperiment.matrix + (StoppedProjectedGlobalLaw.experiment clauses rows repeats hupper hij designated + hbranchAll hrows flag σ context) x) : OldRecord clauses rows hupper context) + let pairedRecord := fun (context : StoppedProjectedExperiment.Outer + (branch := branch) (n := n) (j := j) (t := t) (m := m)) + (record : HierarchicalAgreementMean.PairRecord (rows := rows) + (StoppedProjectedExperiment.nativeSlots clauses context) + (StoppedProjectedExperiment.upper hupper context)) => + ((record.1, record.2.1) : OldRecord clauses rows hupper context) + calc + _ = CompletionSoundness.sigmaLaw (StoppedProjectedExperiment.outerLaw hupper hbranchAll) + (fun context => (originalFiber context).pushforward (originalRecord context)) := + SigmaObservation.pushforward_fiber + (Y := fun context => OldRecord clauses rows hupper context) + (StoppedProjectedExperiment.outerLaw hupper hbranchAll) originalFiber originalRecord + _ = CompletionSoundness.sigmaLaw (StoppedProjectedExperiment.outerLaw hupper hbranchAll) + (fun context => (pairedFiber context).pushforward (pairedRecord context)) := by + apply congrArg (CompletionSoundness.sigmaLaw + (StoppedProjectedExperiment.outerLaw hupper hbranchAll)) + funext context + exact original_oldRecord_law clauses rows repeats hupper hij designated hrows context + (fun k hk => hbranchAll k (Nat.lt_of_lt_of_le hk hupper)) flag σ + _ = _ := (SigmaObservation.pushforward_fiber + (Y := fun context => OldRecord clauses rows hupper context) + (StoppedProjectedExperiment.outerLaw hupper hbranchAll) pairedFiber pairedRecord).symm + +end +end PerfectCompleteness.StoppedProjectedOldRecord + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/StoppedProjectedPhysicalAdvice.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/StoppedProjectedPhysicalAdvice.lean new file mode 100644 index 0000000000000000000000000000000000000000..44fc771fe5db20490eedfc07094c68080b12ea34 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/StoppedProjectedPhysicalAdvice.lean @@ -0,0 +1,232 @@ +import OAI.Computability.PerfectCompleteness.Sampling.StoppedProjectedGlobalLawLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.StoppedProjectedPhysicalAdvice + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +private abbrev physicalSampleFintype + {branch : Nat → Nat} {n i j t v m : Nat} + (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hupper : j + 1 ≤ n) (hij : i < j) + (designated : Fin (branch i) → Slots branch i) + (o : StoppedProjectedExperiment.Outer + (branch := branch) (n := n) (j := j) (t := t) (m := m)) : + Fintype (StoppedProjectedExperiment.PhysicalSample clauses rows repeats hupper hij designated o) := + inferInstance + +attribute [local instance] linearMapFintype + +variable {branch : Nat → Nat} {n i j t v m : Nat} + (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hupper : j + 1 ≤ n) (hij : i < j) + (designated : Fin (branch i) → Slots branch i) + +abbrev Outer := StoppedProjectedExperiment.Outer (branch := branch) (n := n) + (j := j) (t := t) (m := m) + +abbrev Advice (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) (r : Nat) := + ManyGoodRows.RowMap (Block rows (StoppedProjectedExperiment.upper hupper o)) r + +local instance adviceFintype + (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) (r : Nat) : + Fintype (Advice rows hupper o r) := linearMapFintype + +abbrev Sample (r : Nat) := + (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) × + (StoppedProjectedExperiment.PhysicalSample clauses rows repeats hupper hij designated o × + Advice rows hupper o r) + +abbrev RawSample (r : Nat) := + (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) × + HierarchicalProjectedExperiment.RawSample (rows := rows) (repeats := repeats) + (StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated o) + (StoppedProjectedExperiment.upper hupper o) + (StoppedProjectedExperiment.lower rows hupper hij o) + (StoppedProjectedExperiment.cut rows hupper hij o) r + +local instance physicalAdviceFintype + (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) (r : Nat) : + Fintype (StoppedProjectedExperiment.PhysicalSample clauses rows repeats hupper hij designated o × + Advice rows hupper o r) := by + let : Fintype (StoppedProjectedExperiment.PhysicalSample + clauses rows repeats hupper hij designated o) := + physicalSampleFintype clauses rows repeats hupper hij designated o + infer_instance + +local instance rawFiberFintype + (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) (r : Nat) : + Fintype (HierarchicalProjectedExperiment.RawSample (rows := rows) (repeats := repeats) + (StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated o) + (StoppedProjectedExperiment.upper hupper o) + (StoppedProjectedExperiment.lower rows hupper hij o) + (StoppedProjectedExperiment.cut rows hupper hij o) r) := by + let : (A : Advice rows hupper o r) → + (k : StoppedProjectedExperiment.Inner + (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) → + Fintype (OwnInputReference.RawSample + (StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated o k) rows + (StoppedProjectedExperiment.upper hupper o) (StoppedProjectedExperiment.lower rows hupper hij o k) + (LinearMap.ker A) repeats (StoppedProjectedExperiment.cut rows hupper hij o k)) := + fun A k => OwnInputReference.rawSampleFintype + (StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated o k) rows + (StoppedProjectedExperiment.upper hupper o) (StoppedProjectedExperiment.lower rows hupper hij o k) + (LinearMap.ker A) repeats (StoppedProjectedExperiment.cut rows hupper hij o k) + let : (A : Advice rows hupper o r) → + Fintype ((k : StoppedProjectedExperiment.Inner + (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) × + OwnInputReference.RawSample + (StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated o k) rows + (StoppedProjectedExperiment.upper hupper o) (StoppedProjectedExperiment.lower rows hupper hij o k) + (LinearMap.ker A) repeats (StoppedProjectedExperiment.cut rows hupper hij o k)) := + fun _ => Sigma.instFintype + exact Sigma.instFintype + +def read (r : Nat) (sample : Sample (t := t) clauses rows repeats hupper hij designated r) : + RawSample (t := t) clauses rows repeats hupper hij designated r := + ⟨sample.1, HierarchicalProjectedExperiment.rawRead (rows := rows) (repeats := repeats) + (StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated sample.1) + (StoppedProjectedExperiment.upper hupper sample.1) + (StoppedProjectedExperiment.lower rows hupper hij sample.1) + (StoppedProjectedExperiment.cut rows hupper hij sample.1) r + (StoppedProjectedExperiment.physicalExperimentRead clauses rows repeats hupper hij designated + sample.1 sample.2.1, sample.2.2)⟩ + +variable [NeZero m] + (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) + (flag : Fin (branch i) → FiniteDistribution Bool) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + +def law (r : Nat) : FiniteDistribution (Sample (t := t) clauses rows repeats hupper hij designated r) := + CompletionSoundness.sigmaLaw (StoppedProjectedExperiment.outerLaw (t := t) (m := m) hupper hbranch) + (fun o => (StoppedProjectedExperiment.physicalLaw clauses rows repeats hupper hij designated + (fun k hk => hbranch k (Nat.lt_of_lt_of_le hk hupper)) hrows flag o).product + (FiniteDistribution.uniform (Advice rows hupper o r))) + +def rawLaw (r : Nat) : FiniteDistribution (RawSample (t := t) clauses rows repeats hupper hij designated r) := + CompletionSoundness.sigmaLaw (StoppedProjectedExperiment.outerLaw (t := t) (m := m) hupper hbranch) + (fun o => HierarchicalProjectedExperiment.rawLaw (rows := rows) (repeats := repeats) + (StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated o) + (StoppedProjectedExperiment.upper hupper o) + (StoppedProjectedExperiment.lower rows hupper hij o) + (StoppedProjectedExperiment.cut rows hupper hij o) + (StoppedProjectedExperiment.innerLaw rows hij + (fun k hk => hbranch k (Nat.lt_of_lt_of_le hk hupper)) hrows flag) r) + +include σ + +omit [NeZero m] in +theorem fiber_read_law + (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) (r : Nat) : + ((StoppedProjectedExperiment.physicalLaw clauses rows repeats hupper hij designated + (fun k hk => hbranch k (Nat.lt_of_lt_of_le hk hupper)) hrows flag o).product + (FiniteDistribution.uniform (Advice rows hupper o r))).pushforward + (fun x => HierarchicalProjectedExperiment.rawRead (rows := rows) (repeats := repeats) + (StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated o) + (StoppedProjectedExperiment.upper hupper o) + (StoppedProjectedExperiment.lower rows hupper hij o) + (StoppedProjectedExperiment.cut rows hupper hij o) r + (StoppedProjectedExperiment.physicalExperimentRead + clauses rows repeats hupper hij designated o x.1, x.2)) = + HierarchicalProjectedExperiment.rawLaw (rows := rows) (repeats := repeats) + (StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated o) + (StoppedProjectedExperiment.upper hupper o) + (StoppedProjectedExperiment.lower rows hupper hij o) + (StoppedProjectedExperiment.cut rows hupper hij o) + (StoppedProjectedExperiment.innerLaw rows hij + (fun k hk => hbranch k (Nat.lt_of_lt_of_le hk hupper)) hrows flag) r := by + let μ := StoppedProjectedExperiment.physicalLaw clauses rows repeats hupper hij designated + (fun k hk => hbranch k (Nat.lt_of_lt_of_le hk hupper)) hrows flag o + let ν := FiniteDistribution.uniform (Advice rows hupper o r) + let readTape := StoppedProjectedExperiment.physicalExperimentRead + clauses rows repeats hupper hij designated o + let readRaw := HierarchicalProjectedExperiment.rawRead (rows := rows) (repeats := repeats) + (StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated o) + (StoppedProjectedExperiment.upper hupper o) + (StoppedProjectedExperiment.lower rows hupper hij o) + (StoppedProjectedExperiment.cut rows hupper hij o) r + have hprod := FiniteDistribution.product_pushforward μ ν readTape (id : Advice rows hupper o r → _) + rw [FiniteDistribution.pushforward_id] at hprod + have hcomp := FiniteDistribution.pushforward_comp (μ.product ν) + (fun x => (readTape x.1, (id : Advice rows hupper o r → _) x.2)) readRaw + have hphysical := StoppedProjectedExperiment.physicalExperimentRead_law + clauses rows repeats hupper hij designated + (fun k hk => hbranch k (Nat.lt_of_lt_of_le hk hupper)) hrows flag σ o + change μ.pushforward readTape = _ at hphysical + have hraw := HierarchicalProjectedExperiment.rawRead_law (rows := rows) (repeats := repeats) + (StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated o) + (StoppedProjectedExperiment.upper hupper o) + (StoppedProjectedExperiment.lower rows hupper hij o) + (StoppedProjectedExperiment.cut rows hupper hij o) + (StoppedProjectedExperiment.innerLaw rows hij + (fun k hk => hbranch k (Nat.lt_of_lt_of_le hk hupper)) hrows flag) r + have hprodRaw := congrArg + (fun P : FiniteDistribution + (HierarchicalProjectedExperiment.Sample (rows := rows) (repeats := repeats) + (StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated o) + (StoppedProjectedExperiment.upper hupper o) + (StoppedProjectedExperiment.lower rows hupper hij o) + (StoppedProjectedExperiment.cut rows hupper hij o) × Advice rows hupper o r) => + P.pushforward readRaw) hprod + have hphysicalRaw := congrArg + (fun P : FiniteDistribution + (HierarchicalProjectedExperiment.Sample (rows := rows) (repeats := repeats) + (StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated o) + (StoppedProjectedExperiment.upper hupper o) + (StoppedProjectedExperiment.lower rows hupper hij o) + (StoppedProjectedExperiment.cut rows hupper hij o)) => + (P.product ν).pushforward readRaw) hphysical + exact hcomp.symm.trans (hprodRaw.trans (hphysicalRaw.trans hraw)) + +theorem read_law (r : Nat) : + (law (t := t) clauses rows repeats hupper hij designated hbranch hrows flag r).pushforward + (read (t := t) clauses rows repeats hupper hij designated r) = + rawLaw (t := t) clauses rows repeats hupper hij designated hbranch hrows flag r := by + have hsplit := SigmaObservation.pushforward_fiber + (X := fun o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m) => + StoppedProjectedExperiment.PhysicalSample clauses rows repeats hupper hij designated o × + Advice rows hupper o r) + (Y := fun o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m) => + HierarchicalProjectedExperiment.RawSample (rows := rows) (repeats := repeats) + (StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated o) + (StoppedProjectedExperiment.upper hupper o) + (StoppedProjectedExperiment.lower rows hupper hij o) + (StoppedProjectedExperiment.cut rows hupper hij o) r) + (StoppedProjectedExperiment.outerLaw (t := t) (m := m) hupper hbranch) + (fun o => (StoppedProjectedExperiment.physicalLaw clauses rows repeats hupper hij designated + (fun k hk => hbranch k (Nat.lt_of_lt_of_le hk hupper)) hrows flag o).product + (FiniteDistribution.uniform (Advice rows hupper o r))) + (fun o x => HierarchicalProjectedExperiment.rawRead (rows := rows) (repeats := repeats) + (StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated o) + (StoppedProjectedExperiment.upper hupper o) + (StoppedProjectedExperiment.lower rows hupper hij o) + (StoppedProjectedExperiment.cut rows hupper hij o) r + (StoppedProjectedExperiment.physicalExperimentRead + clauses rows repeats hupper hij designated o x.1, x.2)) + exact hsplit.trans (congrArg + (CompletionSoundness.sigmaLaw (StoppedProjectedExperiment.outerLaw (t := t) (m := m) hupper hbranch)) + (funext (fun o => fiber_read_law clauses rows repeats hupper hij designated + hbranch hrows flag σ o r))) + +theorem expectation_read (r : Nat) + (value : RawSample (t := t) clauses rows repeats hupper hij designated r → ℝ) : + (law clauses rows repeats hupper hij designated hbranch hrows flag r).expectation + (fun sample => value (read clauses rows repeats hupper hij designated r sample)) = + (rawLaw clauses rows repeats hupper hij designated hbranch hrows flag r).expectation value := by + rw [← read_law clauses rows repeats hupper hij designated hbranch hrows flag σ r] + exact (FiniteDistribution.expectation_pushforward _ _ _).symm + +end +end PerfectCompleteness.StoppedProjectedPhysicalAdvice + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/StoppedProjectedUsefulAverage.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/StoppedProjectedUsefulAverage.lean new file mode 100644 index 0000000000000000000000000000000000000000..0a9fa8c8d91cef22328b5b4fcd0c9654d1df44e1 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/StoppedProjectedUsefulAverage.lean @@ -0,0 +1,97 @@ +import OAI.Computability.PerfectCompleteness.Foundations.StoppedProjectedUsefulEvent + +namespace OAI + +section + +namespace PerfectCompleteness.StoppedProjectedUsefulAverage + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype + +variable {branch : Nat → Nat} {n i j t v m : Nat} + (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hupper : j + 1 ≤ n) (hij : i < j) + (designated : Fin (branch i) → Slots branch i) + (hbranch : ∀ k < j + 1, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) + (flag : Fin (branch i) → FiniteDistribution Bool) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) (κ : ℝ) + (o : StoppedProjectedExperiment.Outer + (branch := branch) (n := n) (j := j) (t := t) (m := m)) + +local notation "S" => StoppedProjectedExperiment.experiment clauses rows repeats hupper hij + designated hbranch hrows flag σ + +def bucketEvent + (base : StoppedProjectedBucketIndex.Base (branch := branch) (i := i) (j := j) (t := t)) + (direction : PrefixTests.LevelDirection rows (StoppedProjectedUsefulEvent.upperLevel hupper)) + (tape : StoppedProjectedBucketIndex.Tape clauses rows repeats hupper hij designated hrows o base) : Bool := + let sample : StoppedProjectedExperiment.TapeSample clauses rows repeats hupper hij designated o := + ⟨StoppedProjectedBucketIndex.key (n := n) rows hrows base, tape⟩ + HierarchicalUsefulCollision.usefulAccepted + (StoppedProjectedExperiment.nativeSlots clauses o) (StoppedProjectedExperiment.upper hupper o) + (i + 1) (S o).original (S o).arrays (HierarchicalAdviceExperiment.lowerEvent (S o)) κ σ + (StoppedProjectedUsefulEvent.background clauses rows repeats hupper hij designated o sample) + (StoppedProjectedUsefulEvent.upperDirection rows hupper o direction) + (StoppedProjectedUsefulEvent.buckets clauses rows repeats hupper hij designated o sample) + +def mean : ℝ := + (StoppedProjectedBucketIndex.baseLaw (t := t) hij hbranch flag).expectation (fun base => + (CanonicalDirections.levelLaw rows hrows (StoppedProjectedUsefulEvent.upperLevel hupper)).expectation + (fun direction => + (StoppedProjectedBucketIndex.tapeLaw clauses rows repeats hupper hij designated hrows o base).probability + (bucketEvent clauses rows repeats hupper hij designated hbranch hrows flag σ κ o base direction))) + +theorem usefulEvent_eq_bucketEvent + (sample : StoppedProjectedExperiment.TapeSample clauses rows repeats hupper hij designated o) : + HierarchicalUsefulFamily.usefulEvent S κ + (StoppedProjectedUsefulEvent.upperEvent clauses rows repeats hupper hij designated + hbranch hrows flag σ) + ⟨o, StoppedProjectedExperiment.tapeRead clauses rows repeats hupper hij designated o sample⟩ = + bucketEvent clauses rows repeats hupper hij designated hbranch hrows flag σ κ o + (StoppedProjectedBucketIndex.baseOf rows sample.1) + (sample.1.2.2 (StoppedProjectedUsefulEvent.upperLevel hupper)) sample.2 := by + exact StoppedProjectedUsefulEvent.usefulEvent_eq clauses rows repeats hupper hij designated + hbranch hrows flag σ κ o sample + +theorem original_probability_eq_mean : + (S o).original.probability (fun x => + HierarchicalUsefulFamily.usefulEvent S κ + (StoppedProjectedUsefulEvent.upperEvent clauses rows repeats hupper hij designated + hbranch hrows flag σ) ⟨o, x⟩) = + mean clauses rows repeats hupper hij designated hbranch hrows flag σ κ o := by + rw [← StoppedProjectedExperiment.tapeRead_law clauses rows repeats hupper hij designated + hbranch hrows flag σ o, FiniteDistribution.probability_pushforward, + CandidateCoupling.probability_eq_expectation] + calc + _ = (StoppedProjectedExperiment.tapeLaw clauses rows repeats hupper hij designated + hbranch hrows flag o).expectation (fun sample => + if bucketEvent clauses rows repeats hupper hij designated hbranch hrows flag σ κ o + (StoppedProjectedBucketIndex.baseOf rows sample.1) + (sample.1.2.2 (StoppedProjectedUsefulEvent.upperLevel hupper)) sample.2 then 1 else 0) := by + apply FiniteDistribution.expectation_congr + intro sample + rw [usefulEvent_eq_bucketEvent] + _ = _ := by + have hcoordinate := StoppedProjectedBucketIndex.expectation_coordinate + clauses rows repeats hupper hij designated hrows o hbranch flag + (StoppedProjectedUsefulEvent.upperLevel hupper) + (fun base direction tape => + if bucketEvent clauses rows repeats hupper hij designated hbranch hrows flag σ κ o + base direction tape then (1 : ℝ) else 0) + exact hcoordinate.trans (by + unfold mean + simp only [CandidateCoupling.probability_eq_expectation]) + +end +end PerfectCompleteness.StoppedProjectedUsefulAverage + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/StoppedProjectedUsefulEvent.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/StoppedProjectedUsefulEvent.lean new file mode 100644 index 0000000000000000000000000000000000000000..9ef6038d58558c65eecacfa667f707369ed9bbc0 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/StoppedProjectedUsefulEvent.lean @@ -0,0 +1,264 @@ +import OAI.Computability.PerfectCompleteness.Algebra.PrefixMatrixAcceptance +import OAI.Computability.PerfectCompleteness.Construction.StoppedProjectedBucketIndex +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalAdviceExperimentLemmas +import OAI.Computability.PerfectCompleteness.Foundations.StoppedPathHead +import OAI.Computability.PerfectCompleteness.Sampling.StoppedUsefulPairLaw + +namespace OAI + +section + +namespace PerfectCompleteness.StoppedProjectedUsefulEvent + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) +attribute [local instance] linearMapFintype + +private theorem observe_assemble + {branch rows : Nat → Nat} {n t : Nat} + (slots : Slots branch n → Fin t → MixedSupport.Slot) (upper : Nodes branch n) + (lowerLevel : Nat) (background : HierarchicalMatrixTable.Background (rows := rows) slots upper) + (matrix : HierarchicalMatrixTable.Matrix (rows := rows) slots upper) : + HierarchicalUsefulness.observe slots upper lowerLevel + (HierarchicalMatrixTable.assemble slots upper background matrix) = + ⟨background, MatrixRowQuotient.projectMatrix + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) matrix⟩ := by + have hbackground : HierarchicalMatrixTable.backgroundOf slots upper + (HierarchicalMatrixTable.assemble slots upper background matrix) = background := by + funext node row + exact congrFun (HierarchicalMatrixTable.assemble_other slots upper background matrix node) row + exact congrArg₂ (fun (b : HierarchicalMatrixTable.Background (rows := rows) slots upper) + (X : HierarchicalMatrixTable.Matrix (rows := rows) slots upper) => + (⟨b, MatrixRowQuotient.projectMatrix + (HierarchicalFrozenTables.knownRows slots upper lowerLevel b) X⟩ : + HierarchicalUsefulness.Coarse (rows := rows) slots upper lowerLevel)) + hbackground (HierarchicalMatrixTable.matrix_assemble slots upper background matrix) + +private theorem upper_observe_assemble + {branch rows : Nat → Nat} {n t v m : Nat} + (clauses : Fin m → SourceClause.NormalizedClause v) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (questions : PreliminarySampler.Questions branch n t m) + (level : Fin n) (node : PrefixTests.LevelNode branch level) + (direction : PrefixTests.LevelDirection rows level) + (background : HierarchicalMatrixTable.Background (rows := rows) + (sourceSlots clauses (PreliminarySampler.endpoints questions)) node.val) + (matrix : HierarchicalMatrixTable.Matrix (rows := rows) + (sourceSlots clauses (PreliminarySampler.endpoints questions)) node.val) : + PrefixTests.observeAtLevelNode clauses σ questions + (HierarchicalMatrixTable.assemble + (sourceSlots clauses (PreliminarySampler.endpoints questions)) node.val background matrix) + level node direction = + decide (CanonicalMatrixTable.Accepts + (TreeCanonical.numberedSlots (sourceSlots clauses (PreliminarySampler.endpoints questions))) + (NodeEmbedding.RowSpace (sourceSlots clauses (PreliminarySampler.endpoints questions)) node.val) + (HierarchicalMatrixTable.other + (sourceSlots clauses (PreliminarySampler.endpoints questions)) node.val background) + σ (PrefixTests.nodeDirection rows level node direction).val matrix) := by + let slots := sourceSlots clauses (PreliminarySampler.endpoints questions) + have hb : HierarchicalMatrixTable.backgroundOf slots node.val + (HierarchicalMatrixTable.assemble slots node.val background matrix) = background := by + funext other row + exact congrFun (HierarchicalMatrixTable.assemble_other slots node.val background matrix other) row + apply Bool.eq_iff_iff.mpr + rw [decide_eq_true_eq] + exact (PrefixMatrixAcceptance.observe_iff_matrix clauses σ questions + (HierarchicalMatrixTable.assemble slots node.val background matrix) level node direction).trans + (Iff.of_eq (congrArg₂ + (fun (b : HierarchicalMatrixTable.Background (rows := rows) slots node.val) + (X : HierarchicalMatrixTable.Matrix (rows := rows) slots node.val) => + CanonicalMatrixTable.Accepts (TreeCanonical.numberedSlots slots) + (NodeEmbedding.RowSpace slots node.val) (HierarchicalMatrixTable.other slots node.val b) + σ (PrefixTests.nodeDirection rows level node direction).val X) + hb (HierarchicalMatrixTable.matrix_assemble slots node.val background matrix))) + +variable {branch : Nat → Nat} {n i j t v m : Nat} + (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hupper : j + 1 ≤ n) (hij : i < j) + (designated : Fin (branch i) → Slots branch i) + +abbrev Outer := StoppedProjectedExperiment.Outer (branch := branch) (n := n) + (j := j) (t := t) (m := m) +abbrev Inner := StoppedProjectedExperiment.Inner (branch := branch) (n := n) + (i := i) (j := j) (t := t) rows + +def upperLevel : Fin n := ⟨j, Nat.lt_of_lt_of_le (Nat.lt_succ_self j) hupper⟩ + +abbrev chosen (k : Inner (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) := + StoppedPathHead.child hij (StoppedProjectedExperiment.lowerPath rows hij k) + +abbrev continuation (k : Inner (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) := + StoppedPathHead.tail hij (StoppedProjectedExperiment.lowerPath rows hij k) + +theorem stepPath_eq (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) + (k : Inner (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) : + StoppedProjectedExperiment.stoppedPath rows hupper hij o k = + (StoppedProjectedExperiment.upperPath hupper o).append + (.step (chosen rows hij k) (continuation rows hij k)) := + congrArg (fun p => (StoppedProjectedExperiment.upperPath hupper o).append p) + (StoppedPathHead.lowerPath_step_eq rows hij k) + +def stepTape (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) + (sample : StoppedProjectedExperiment.TapeSample clauses rows repeats hupper hij designated o) := + StoppedOwnInputGeometry.pathTapeEquiv rows repeats + (StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated o sample.1) + (congrArg (fun p : Path branch n (i + 1) => + (⟨i + 1, p⟩ : Σ height, Path branch n height)) + (stepPath_eq rows hupper hij o sample.1)) sample.2 + +def readout (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) + (sample : StoppedProjectedExperiment.TapeSample clauses rows repeats hupper hij designated o) := + StoppedUsefulPairLaw.readout rows repeats (StoppedProjectedExperiment.upperPath hupper o) + (chosen rows hij sample.1) (continuation rows hij sample.1) + (StoppedProjectedExperiment.nativeSlots clauses o) + (StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated o sample.1) + (StoppedProjectedExperiment.projection clauses rows hupper hij designated o sample.1) + (stepTape clauses rows repeats hupper hij designated o sample) + +def background (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) + (sample : StoppedProjectedExperiment.TapeSample clauses rows repeats hupper hij designated o) := + StoppedUsefulPairLaw.background rows repeats (StoppedProjectedExperiment.upperPath hupper o) + (chosen rows hij sample.1) (continuation rows hij sample.1) + (StoppedProjectedExperiment.nativeSlots clauses o) + (StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated o sample.1) + (StoppedProjectedExperiment.projection clauses rows hupper hij designated o sample.1) + (readout clauses rows repeats hupper hij designated o sample).1 + +def buckets (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) + (sample : StoppedProjectedExperiment.TapeSample clauses rows repeats hupper hij designated o) := + CutNodeRows.bucketTapeEquiv rows (StoppedProjectedExperiment.upperPath hupper o) + (StoppedProjectedExperiment.nativeSlots clauses o) + (readout clauses rows repeats hupper hij designated o sample).2 + +def upperDirection (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) + (direction : PrefixTests.LevelDirection rows (upperLevel hupper)) := + PrefixTests.nodeDirection rows (upperLevel hupper) + ⟨StoppedProjectedExperiment.upper hupper o, StoppedProjectedExperiment.upper_height hupper o⟩ + direction + +theorem upperDirection_eq (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) + (direction : PrefixTests.LevelDirection rows (upperLevel hupper)) : + upperDirection rows hupper o direction = + CutNodeRows.directionEquiv rows (StoppedProjectedExperiment.upperPath hupper o) direction := rfl + +variable (hbranch : ∀ k < j + 1, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) + (flag : Fin (branch i) → FiniteDistribution Bool) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + +abbrev experiment := StoppedProjectedExperiment.experiment clauses rows repeats hupper hij designated + hbranch hrows flag σ + +def upperEvent (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) + (x : HierarchicalProjectedExperiment.Sample (rows := rows) (repeats := repeats) + (StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated o) + (StoppedProjectedExperiment.upper hupper o) + (StoppedProjectedExperiment.lower rows hupper hij o) + (StoppedProjectedExperiment.cut rows hupper hij o)) : Bool := + PrefixTests.observeAtLevelNode clauses σ o.1 + ((experiment clauses rows repeats hupper hij designated hbranch hrows flag σ o).arrays x) + (upperLevel hupper) + ⟨StoppedProjectedExperiment.upper hupper o, StoppedProjectedExperiment.upper_height hupper o⟩ + (x.1.2.2 (upperLevel hupper)) + +theorem arrays_readout (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) + (sample : StoppedProjectedExperiment.TapeSample clauses rows repeats hupper hij designated o) : + (experiment clauses rows repeats hupper hij designated hbranch hrows flag σ o).arrays + (StoppedProjectedExperiment.tapeRead clauses rows repeats hupper hij designated o sample) = + HierarchicalMatrixTable.assemble (StoppedProjectedExperiment.nativeSlots clauses o) + (StoppedProjectedExperiment.upper hupper o) + (background clauses rows repeats hupper hij designated o sample) + (BucketMatrixResampling.assembledMatrix + (NodeEmbedding.RowSpace (StoppedProjectedExperiment.nativeSlots clauses o) + (StoppedProjectedExperiment.upper hupper o)) + (rows (Nodes.height (StoppedProjectedExperiment.upper hupper o))) + (buckets clauses rows repeats hupper hij designated o sample)) := by + have heval := congrArg + (ChildBlockProjection.arraysPullback rows + (StoppedProjectedExperiment.projection clauses rows hupper hij designated o sample.1)) + (StoppedOwnInputGeometry.evaluate_pathTapeEquiv rows repeats + (StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated o sample.1) + (congrArg (fun p : Path branch n (i + 1) => + (⟨i + 1, p⟩ : Σ height, Path branch n height)) + (stepPath_eq rows hupper hij o sample.1)) sample.2) + have hassemble := StoppedUsefulPairLaw.assembled_arrays rows repeats + (StoppedProjectedExperiment.upperPath hupper o) + (chosen rows hij sample.1) (continuation rows hij sample.1) + (StoppedProjectedExperiment.nativeSlots clauses o) + (StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated o sample.1) + (StoppedProjectedExperiment.projection clauses rows hupper hij designated o sample.1) + (stepTape clauses rows repeats hupper hij designated o sample) + exact (StoppedProjectedExperiment.arrays_tapeRead clauses rows repeats hupper hij designated + hbranch hrows flag σ o sample).trans (heval.symm.trans hassemble.symm) + +theorem usefulEvent_eq (κ : ℝ) + (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) + (sample : StoppedProjectedExperiment.TapeSample clauses rows repeats hupper hij designated o) : + HierarchicalUsefulFamily.usefulEvent + (experiment clauses rows repeats hupper hij designated hbranch hrows flag σ) κ + (upperEvent clauses rows repeats hupper hij designated hbranch hrows flag σ) + ⟨o, StoppedProjectedExperiment.tapeRead clauses rows repeats hupper hij designated o sample⟩ = + HierarchicalUsefulCollision.usefulAccepted + (StoppedProjectedExperiment.nativeSlots clauses o) (StoppedProjectedExperiment.upper hupper o) + (i + 1) + (experiment clauses rows repeats hupper hij designated hbranch hrows flag σ o).original + (experiment clauses rows repeats hupper hij designated hbranch hrows flag σ o).arrays + (HierarchicalAdviceExperiment.lowerEvent + (experiment clauses rows repeats hupper hij designated hbranch hrows flag σ o)) κ σ + (background clauses rows repeats hupper hij designated o sample) + (upperDirection rows hupper o (sample.1.2.2 (upperLevel hupper))) + (buckets clauses rows repeats hupper hij designated o sample) := by + let S := experiment clauses rows repeats hupper hij designated hbranch hrows flag σ o + let x := StoppedProjectedExperiment.tapeRead clauses rows repeats hupper hij designated o sample + let b : HierarchicalMatrixTable.Background (rows := rows) S.slots S.upper := + background clauses rows repeats hupper hij designated o sample + let X : HierarchicalMatrixTable.Matrix (rows := rows) S.slots S.upper := + BucketMatrixResampling.assembledMatrix + (NodeEmbedding.RowSpace (StoppedProjectedExperiment.nativeSlots clauses o) + (StoppedProjectedExperiment.upper hupper o)) + (rows (Nodes.height (StoppedProjectedExperiment.upper hupper o))) + (buckets clauses rows repeats hupper hij designated o sample) + have harray : S.arrays x = HierarchicalMatrixTable.assemble S.slots S.upper b X := + arrays_readout clauses rows repeats hupper hij designated hbranch hrows flag σ o sample + have hcoarse : HierarchicalAdviceExperiment.coarse S x = + (⟨b, MatrixRowQuotient.projectMatrix + (HierarchicalFrozenTables.knownRows S.slots S.upper (i + 1) b) X⟩ : + HierarchicalUsefulness.Coarse S.slots S.upper (i + 1)) := + (congrArg (fun arrays : Arrays S.slots rows => + HierarchicalUsefulness.observe S.slots S.upper (i + 1) arrays) harray).trans + (observe_assemble S.slots S.upper (i + 1) b X) + have htest : upperEvent clauses rows repeats hupper hij designated hbranch hrows flag σ o x = + decide (CanonicalMatrixTable.Accepts (TreeCanonical.numberedSlots S.slots) + (NodeEmbedding.RowSpace S.slots S.upper) (HierarchicalMatrixTable.other S.slots S.upper b) + σ (upperDirection rows hupper o (sample.1.2.2 (upperLevel hupper))).val X) := + (congrArg (fun arrays : Arrays S.slots rows => + PrefixTests.observeAtLevelNode clauses σ o.1 arrays (upperLevel hupper) + ⟨StoppedProjectedExperiment.upper hupper o, StoppedProjectedExperiment.upper_height hupper o⟩ + (sample.1.2.2 (upperLevel hupper))) harray).trans + (upper_observe_assemble clauses σ o.1 (upperLevel hupper) + ⟨StoppedProjectedExperiment.upper hupper o, StoppedProjectedExperiment.upper_height hupper o⟩ + (sample.1.2.2 (upperLevel hupper)) b X) + change (upperEvent clauses rows repeats hupper hij designated hbranch hrows flag σ o x && + HierarchicalUsefulness.mark S.slots S.upper (i + 1) S.original S.arrays + (HierarchicalAdviceExperiment.lowerEvent S) κ (HierarchicalAdviceExperiment.coarse S x)) = _ + exact (congrArg₂ (fun accepted marked : Bool => accepted && marked) htest + (congrArg (HierarchicalUsefulness.mark S.slots S.upper (i + 1) S.original S.arrays + (HierarchicalAdviceExperiment.lowerEvent S) κ) hcoarse)).trans + (congrArg (fun marked => + decide (CanonicalMatrixTable.Accepts (TreeCanonical.numberedSlots S.slots) + (NodeEmbedding.RowSpace S.slots S.upper) (HierarchicalMatrixTable.other S.slots S.upper b) + σ (upperDirection rows hupper o (sample.1.2.2 (upperLevel hupper))).val X) && marked) + (HierarchicalUsefulness.table_isSome S.slots S.upper (i + 1) S.original S.arrays + (HierarchicalAdviceExperiment.lowerEvent S) κ σ b + (MatrixRowQuotient.projectMatrix + (HierarchicalFrozenTables.knownRows S.slots S.upper (i + 1) b) X)).symm) + +end +end PerfectCompleteness.StoppedProjectedUsefulEvent + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/StoppedSharedComparison.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/StoppedSharedComparison.lean new file mode 100644 index 0000000000000000000000000000000000000000..03324e2990e86b95bf5b4ef0cd94712acff3fc82 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/StoppedSharedComparison.lean @@ -0,0 +1,91 @@ +import OAI.Computability.PerfectCompleteness.Foundations.OriginalWholeCutComparison +import OAI.Computability.PerfectCompleteness.Foundations.StoppedSharedEvents +import OAI.Computability.PerfectCompleteness.Sampling.StoppedSharedLaw + +namespace OAI + +section + +namespace PerfectCompleteness.StoppedSharedComparison + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open StoppedSharedSampler +open UniqueGamesTheorem.Foundations.Games + +noncomputable section + +variable {v m n t cut : Nat} {branch rows repeats : Nat → Nat} + +def error (branch rows repeats : Nat → Nat) (n cut t : Nat) : ℝ := + Real.sqrt ((ChildBlockCardinality.bound branch cut t + (OriginalCutCalls.count rows repeats n (cut + 1)) rows : ℝ) ^ 2 / branch cut) / 2 + +theorem observed_totalVariation_le [NeZero m] {Γ : Type*} [Fintype Γ] + (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hcut : cut + 1 ≤ n) + (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) + (observe : Record clauses branch n t cut rows → Γ) : + ((originalLaw clauses rows repeats hcut hbranch hrows).pushforward observe).totalVariation + ((stoppedLaw clauses rows repeats hcut hbranch hrows).pushforward observe) ≤ + error branch rows repeats n cut t := by + rw [StoppedSharedLaw.originalLaw_eq_averagedLaw] + exact OriginalWholeCutComparison.conditional_observed_totalVariation_le rows repeats + (fun context : Context branch n t m cut rows => + GeometricCutSplit.prefixPath hcut context.2.1) + (fun context => sourceSlots clauses (PreliminarySampler.endpoints context.1)) + (contextLaw hcut hbranch hrows) + (fun k hk => hbranch k (Nat.lt_of_lt_of_le hk hcut)) observe + +theorem totalVariation_le [NeZero m] + (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hcut : cut + 1 ≤ n) + (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) : + (originalLaw (t := t) clauses rows repeats hcut hbranch hrows).totalVariation + (stoppedLaw (t := t) clauses rows repeats hcut hbranch hrows) ≤ + error branch rows repeats n cut t := by + simpa only [FiniteDistribution.pushforward_id] using + observed_totalVariation_le clauses rows repeats hcut hbranch hrows + (id : Record clauses branch n t cut rows → Record clauses branch n t cut rows) + +theorem pair_probability_transfer [NeZero m] + (clauses : Fin m → SourceClause.NormalizedClause v) + (strategy : PreliminaryStrategy.Strategy clauses branch n t rows repeats) + (hcut : cut + 1 ≤ n) (hbranch : ∀ k < n, 0 < branch k) + (hrows : ∀ k, 0 < rows (k + 1)) (i j : Fin n) + (hi : cut + 1 ≤ i.val + 1) (hj : cut + 1 ≤ j.val + 1) : + (CandidateCoupling.sharedLaw clauses rows repeats hbranch hrows).probability + (fun sample => PreliminaryLevelPair.win clauses strategy i sample && + PreliminaryLevelPair.win clauses strategy j sample) ≤ + (stoppedLaw clauses rows repeats hcut hbranch hrows).probability + (StoppedSharedEvents.pair clauses strategy hcut hbranch i j) + + error branch rows repeats n cut t := by + have h := FiniteDistribution.probability_le_add_totalVariation + (originalLaw clauses rows repeats hcut hbranch hrows) + (stoppedLaw clauses rows repeats hcut hbranch hrows) + (StoppedSharedEvents.pair clauses strategy hcut hbranch i j) + rw [StoppedSharedEvents.original_pair_probability clauses strategy hcut hbranch hrows i j hi hj] at h + exact h.trans (add_le_add le_rfl + (totalVariation_le (t := t) clauses rows repeats hcut hbranch hrows)) + +theorem pair_probability_lower [NeZero m] + (clauses : Fin m → SourceClause.NormalizedClause v) + (strategy : PreliminaryStrategy.Strategy clauses branch n t rows repeats) + (hcut : cut + 1 ≤ n) (hbranch : ∀ k < n, 0 < branch k) + (hrows : ∀ k, 0 < rows (k + 1)) (i j : Fin n) + (hi : cut + 1 ≤ i.val + 1) (hj : cut + 1 ≤ j.val + 1) + {mass : ℝ} (hmass : mass ≤ + (CandidateCoupling.sharedLaw clauses rows repeats hbranch hrows).probability + (fun sample => PreliminaryLevelPair.win clauses strategy i sample && + PreliminaryLevelPair.win clauses strategy j sample)) : + mass - error branch rows repeats n cut t ≤ + (stoppedLaw clauses rows repeats hcut hbranch hrows).probability + (StoppedSharedEvents.pair clauses strategy hcut hbranch i j) := by + have h := pair_probability_transfer clauses strategy hcut hbranch hrows i j hi hj + linarith + +end +end PerfectCompleteness.StoppedSharedComparison + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/StoppedSharedEvents.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/StoppedSharedEvents.lean new file mode 100644 index 0000000000000000000000000000000000000000..b3f5836bc1d1cb33877dee648fd024cc75c27f22 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/StoppedSharedEvents.lean @@ -0,0 +1,83 @@ +import OAI.Computability.PerfectCompleteness.Sampling.StoppedSharedSampler + +namespace OAI + +section + +namespace PerfectCompleteness.StoppedSharedEvents + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open StoppedSharedSampler +open UniqueGamesTheorem.Foundations.Games + +noncomputable section + +variable {v m n t cut : Nat} {branch rows repeats : Nat → Nat} + +def referenceSuffix (hcut : cut + 1 ≤ n) (hbranch : ∀ k < n, 0 < branch k) : + Slots branch (cut + 1) := + Classical.choice (GeometricPath.slots_nonempty (cut + 1) + (fun k hk => hbranch k (Nat.lt_of_lt_of_le hk hcut))) + +def representativeLeaf (hcut : cut + 1 ≤ n) (hbranch : ∀ k < n, 0 < branch k) + (context : Context branch n t m cut rows) : Slots branch n := + (GeometricCutSplit.prefixPath hcut context.2.1).slotEmbedding (referenceSuffix hcut hbranch) + +def win (clauses : Fin m → SourceClause.NormalizedClause v) + (strategy : PreliminaryStrategy.Strategy clauses branch n t rows repeats) + (hcut : cut + 1 ≤ n) (hbranch : ∀ k < n, 0 < branch k) + (level : Fin n) (record : Record clauses branch n t cut rows) : Bool := + PreliminaryStrategy.observe clauses + (PreliminaryStrategy.extend clauses branch n t rows repeats strategy) + (record.1.1, representativeLeaf hcut hbranch record.1) record.2 + (PrefixTests.choiceAt rows (representativeLeaf hcut hbranch record.1) level + (record.1.2.2 level)) + +theorem actual_win_eq (clauses : Fin m → SourceClause.NormalizedClause v) + (strategy : PreliminaryStrategy.Strategy clauses branch n t rows repeats) + (hcut : cut + 1 ≤ n) (hbranch : ∀ k < n, 0 < branch k) + (level : Fin n) (hlevel : cut + 1 ≤ level.val + 1) + (sample : CandidateCoupling.Shared clauses branch n t rows) : + PreliminaryLevelPair.win clauses strategy level sample = + win clauses strategy hcut hbranch level (forgetSuffix clauses hcut sample) := by + rw [CanonicalDirections.win_eq_observe] + have h := PrefixTests.observe_above_cut_eq clauses + (PreliminaryStrategy.extend clauses branch n t rows repeats strategy) + sample.1.1 sample.2.1 + (GeometricCutSplit.prefixPath hcut (GeometricCutSplit.splitEquiv hcut sample.1.2).1) + level hlevel (GeometricCutSplit.splitEquiv hcut sample.1.2).2 + (referenceSuffix hcut hbranch) + ((CanonicalDirections.tupleEquiv rows sample.1.2).symm sample.2.2 level) + rw [GeometricCutSplit.split_embedding_eq] at h + exact h + +def pair (clauses : Fin m → SourceClause.NormalizedClause v) + (strategy : PreliminaryStrategy.Strategy clauses branch n t rows repeats) + (hcut : cut + 1 ≤ n) (hbranch : ∀ k < n, 0 < branch k) (i j : Fin n) + (record : Record clauses branch n t cut rows) : Bool := + win clauses strategy hcut hbranch i record && win clauses strategy hcut hbranch j record + +theorem original_pair_probability [NeZero m] + (clauses : Fin m → SourceClause.NormalizedClause v) + (strategy : PreliminaryStrategy.Strategy clauses branch n t rows repeats) + (hcut : cut + 1 ≤ n) (hbranch : ∀ k < n, 0 < branch k) + (hrows : ∀ k, 0 < rows (k + 1)) (i j : Fin n) + (hi : cut + 1 ≤ i.val + 1) (hj : cut + 1 ≤ j.val + 1) : + (originalLaw clauses rows repeats hcut hbranch hrows).probability + (pair clauses strategy hcut hbranch i j) = + (CandidateCoupling.sharedLaw clauses rows repeats hbranch hrows).probability + (fun sample => PreliminaryLevelPair.win clauses strategy i sample && + PreliminaryLevelPair.win clauses strategy j sample) := by + rw [originalLaw, FiniteDistribution.probability_pushforward] + apply congrArg (CandidateCoupling.sharedLaw clauses rows repeats hbranch hrows).probability + funext sample + exact (congrArg₂ Bool.and + (actual_win_eq clauses strategy hcut hbranch i hi sample) + (actual_win_eq clauses strategy hcut hbranch j hj sample)).symm + +end +end PerfectCompleteness.StoppedSharedEvents + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/TerminalCalls.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/TerminalCalls.lean new file mode 100644 index 0000000000000000000000000000000000000000..bd5e16572fd1ea2645e9846a0dfb4806df243288 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/TerminalCalls.lean @@ -0,0 +1,184 @@ +import Mathlib.Algebra.BigOperators.Intervals +import OAI.Computability.PerfectCompleteness.Sampling.RecordSeedSamplingLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.TerminalCalls + +open RecursiveSpaces DescendantSpaces RecursiveSampler +open scoped BigOperators + +universe u w + +variable {branch : Nat → Nat} {n m : Nat} + +def TerminalIndex (repeats : Nat → Nat) : {n m : Nat} → Path branch n m → Type + | _, _, .refl _ => Unit + | n + 1, _, .step _ p => + (Fin (repeats (n + 1)) × Bool) × TerminalIndex repeats p + +noncomputable instance terminalIndexFintype (repeats : Nat → Nat) (p : Path branch n m) : + Fintype (TerminalIndex repeats p) := by + induction p with + | refl n => exact inferInstanceAs (Fintype Unit) + | @step n m i p ih => + letI : Fintype (TerminalIndex repeats p) := ih + exact inferInstanceAs (Fintype + ((Fin (repeats (n + 1)) × Bool) × TerminalIndex repeats p)) + +noncomputable instance terminalIndexDecidableEq (repeats : Nat → Nat) + (p : Path branch n m) : DecidableEq (TerminalIndex repeats p) := by + induction p with + | refl n => exact inferInstanceAs (DecidableEq Unit) + | @step n m i p ih => + letI : DecidableEq (TerminalIndex repeats p) := ih + exact inferInstanceAs (DecidableEq + ((Fin (repeats (n + 1)) × Bool) × TerminalIndex repeats p)) + +def drawIndex (repeats : Nat → Nat) : {n m : Nat} → (p : Path branch n m) → + TerminalIndex repeats p → DrawIndex repeats p + | _, _, .refl _, terminal => terminal + | _, _, .step _ p, terminal => .inr (terminal.1, drawIndex repeats p terminal.2) + +@[simp] theorem drawIndex_refl (repeats : Nat → Nat) + (terminal : TerminalIndex (branch := branch) repeats (.refl n)) : + drawIndex (branch := branch) repeats (.refl n) terminal = terminal := rfl + +@[simp] theorem drawIndex_step (repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) (terminal : TerminalIndex repeats (.step i p)) : + drawIndex repeats (.step i p) terminal = + .inr (terminal.1, drawIndex repeats p terminal.2) := rfl + +theorem drawIndex_injective (repeats : Nat → Nat) (p : Path branch n m) : + Function.Injective (drawIndex repeats p) := by + induction p with + | refl n => exact fun _ _ h => h + | @step n m i p ih => + intro a b h + have heq := Sum.inr.inj h + apply Prod.ext + · exact congrArg + (fun z : (Fin (repeats (n + 1)) × Bool) × DrawIndex repeats p => z.1) heq + · exact ih (congrArg + (fun z : (Fin (repeats (n + 1)) × Bool) × DrawIndex repeats p => z.2) heq) + +def terminalEmbedding (repeats : Nat → Nat) (p : Path branch n m) : + TerminalIndex repeats p ↪ DrawIndex repeats p := + ⟨drawIndex repeats p, drawIndex_injective repeats p⟩ + +def IsTerminal (repeats : Nat → Nat) : {n m : Nat} → (p : Path branch n m) → + DrawIndex repeats p → Prop + | _, _, .refl _, _ => True + | _, _, .step _ p, j => + match j with + | .inl _ => False + | .inr j => IsTerminal repeats p j.2 + +@[simp] theorem isTerminal_refl (repeats : Nat → Nat) + (j : DrawIndex (branch := branch) repeats (.refl n)) : + IsTerminal (branch := branch) repeats (.refl n) j := True.intro + +@[simp] theorem not_isTerminal_ordinary (repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) (j : OffPath i) : + ¬ IsTerminal repeats (.step i p) (.inl j) := id + +@[simp] theorem isTerminal_recursive (repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) (call : Fin (repeats (n + 1)) × Bool) + (j : DrawIndex repeats p) : + IsTerminal repeats (.step i p) (.inr (call, j)) ↔ IsTerminal repeats p j := Iff.rfl + +theorem isTerminal_iff_exists (repeats : Nat → Nat) (p : Path branch n m) : + ∀ j : DrawIndex repeats p, + IsTerminal repeats p j ↔ ∃ terminal, drawIndex repeats p terminal = j := by + induction p with + | refl n => + intro j + constructor + · intro _ + exact ⟨j, rfl⟩ + · intro _ + exact True.intro + | step i p ih => + intro j + cases j with + | inl j => + constructor + · intro h + exact False.elim h + · rintro ⟨terminal, h⟩ + change (Sum.inr (terminal.1, drawIndex repeats p terminal.2) : + DrawIndex repeats (.step i p)) = Sum.inl j at h + exact Sum.inr_ne_inl h + | inr j => + constructor + · intro h + obtain ⟨terminal, heq⟩ := (ih j.2).mp h + refine ⟨(j.1, terminal), ?_⟩ + exact congrArg Sum.inr (Prod.ext rfl heq) + · rintro ⟨terminal, h⟩ + exact (ih j.2).mpr + ⟨terminal.2, congrArg Prod.snd (Sum.inr.inj h)⟩ + +theorem isTerminal_drawIndex (repeats : Nat → Nat) (p : Path branch n m) + (terminal : TerminalIndex repeats p) : + IsTerminal repeats p (drawIndex repeats p terminal) := + (isTerminal_iff_exists repeats p _).mpr ⟨terminal, rfl⟩ + +noncomputable def terminalSubtypeEquiv (repeats : Nat → Nat) (p : Path branch n m) : + TerminalIndex repeats p ≃ {j : DrawIndex repeats p // IsTerminal repeats p j} := + Equiv.ofBijective + (fun terminal => ⟨drawIndex repeats p terminal, isTerminal_drawIndex repeats p terminal⟩) + ⟨fun _ _ h => drawIndex_injective repeats p (congrArg Subtype.val h), by + rintro ⟨j, hj⟩ + obtain ⟨terminal, heq⟩ := (isTerminal_iff_exists repeats p j).mp hj + exact ⟨terminal, Subtype.ext heq⟩⟩ + +@[simp] theorem terminalSubtypeEquiv_apply (repeats : Nat → Nat) (p : Path branch n m) + (terminal : TerminalIndex repeats p) : + (terminalSubtypeEquiv repeats p terminal).val = drawIndex repeats p terminal := rfl + +@[simp] theorem card_refl (repeats : Nat → Nat) : + Fintype.card (TerminalIndex (branch := branch) repeats (.refl n)) = 1 := by + change Fintype.card Unit = 1 + exact Fintype.card_unit + +theorem card_step (repeats : Nat → Nat) (i : Fin (branch n)) (p : Path branch n m) : + Fintype.card (TerminalIndex repeats (.step i p)) = + (2 * repeats (n + 1)) * Fintype.card (TerminalIndex repeats p) := by + change Fintype.card ((Fin (repeats (n + 1)) × Bool) × TerminalIndex repeats p) = _ + simp only [Fintype.card_prod, Fintype.card_fin, Fintype.card_bool] + exact congrArg (fun a => a * Fintype.card (TerminalIndex repeats p)) (Nat.mul_comm _ _) + +theorem card_eq_prod (repeats : Nat → Nat) (p : Path branch n m) : + Fintype.card (TerminalIndex repeats p) = ∏ h ∈ Finset.Ioc m n, 2 * repeats h := by + induction p with + | refl n => simp only [card_refl, Finset.Ioc_self, Finset.prod_empty] + | step i p ih => + rw [card_step, ih, Finset.prod_Ioc_succ_top p.height_le] + exact Nat.mul_comm _ _ + +theorem drawSpace_eq_terminal (𝕜 : Type w) [Field 𝕜] + (repeats : Nat → Nat) (p : Path branch n m) : + ∀ (A : Slots branch n → Type u) (terminal : TerminalIndex repeats p), + DrawSpace 𝕜 repeats p A (drawIndex repeats p terminal) = + space 𝕜 branch m (p.family A) := by + induction p with + | refl n => intro A terminal; rfl + | step i p ih => + intro A terminal + exact ih (childFamily A i) terminal.2 + +noncomputable def terminalSpaceEquiv (𝕜 : Type w) [Field 𝕜] + (repeats : Nat → Nat) (p : Path branch n m) + (A : Slots branch n → Type u) (terminal : TerminalIndex repeats p) : + DrawSpace 𝕜 repeats p A (drawIndex repeats p terminal) ≃ + space 𝕜 branch m (p.family A) := + Equiv.cast (drawSpace_eq_terminal 𝕜 repeats p A terminal) + +end PerfectCompleteness.TerminalCalls + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/TriangularFolding.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/TriangularFolding.lean new file mode 100644 index 0000000000000000000000000000000000000000..860518fc6c3cebb61dec1dad1bf5334619697bf6 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/TriangularFolding.lean @@ -0,0 +1,115 @@ +import Mathlib.Algebra.BigOperators.Module +import OAI.Computability.PerfectCompleteness.Construction.DescendantSpacesLemmas +import OAI.Computability.PerfectCompleteness.Foundations.LinearEvaluationLemmas +import OAI.Computability.PerfectCompleteness.Foundations.QuotientTableAgreementLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.TriangularFolding + +open MixedSupport CanonicalKeys PointwiseSpaces + +variable {A B X : Type*} [AddCommGroup A] + +def translate (q : B → A) : A × B ≃ A × B where + toFun y := (y.1 + q y.2, y.2) + invFun y := (y.1 - q y.2, y.2) + left_inv y := by ext <;> simp + right_inv y := by ext <;> simp + +@[simp] theorem translate_first (q : B → A) (y : A × B) : + (translate q y).1 = y.1 + q y.2 := rfl + +@[simp] theorem translate_second (q : B → A) (y : A × B) : + (translate q y).2 = y.2 := rfl + +def shifted (f : X → A × B) (q : B → A) : X → A × B := translate q ∘ f + +theorem shifted_kernel (f : X → A × B) (q : B → A) (x x' : X) : + f x = f x' ↔ shifted f q x = shifted f q x' := + ⟨fun h => congrArg (translate q) h, fun h => (translate q).injective h⟩ + +theorem key_shifted {n : Nat} (side : Side) (slots : Fin n → Slot) + (f : Assignment slots → A × B) (q : B → A) : + key side slots (shifted f q) = key side slots f := + key_postcomp_equiv side slots f (translate q) + +noncomputable def shiftLabel {n : Nat} (slots : Fin n → Slot) + (f : Assignment slots → A × B) (q : B → A) (P : Label slots f) : + Label slots (shifted f q) := + transportKernel slots f (shifted f q) (shifted_kernel f q) P + +theorem restore_shiftLabel {n : Nat} (slots : Fin n → Slot) + (f : Assignment slots → A × B) (q : B → A) (P : Label slots f) : + restore slots (shifted f q) (shiftLabel slots f q P) = + ((restore slots f P).1 + q (restore slots f P).2, (restore slots f P).2) := + restore_transportKernel slots f (shifted f q) (shifted_kernel f q) + (translate q) (fun _ => rfl) P + +def displayedTranslate {I : Type*} [DecidableEq I] (V : I → Type*) + [∀ i, AddCommGroup (V i)] (B : Type*) (selected : I) + (q : BlockQuotient.OtherBlocks V selected × B → V selected) : + BlockQuotient.JointOutput V B ≃ + V selected × (BlockQuotient.OtherBlocks V selected × B) := + (BlockQuotient.splitOutput V B selected).trans (translate q) + +theorem key_displayedTranslate {n : Nat} {I : Type*} [DecidableEq I] + (V : I → Type*) [∀ i, AddCommGroup (V i)] (B : Type*) + (side : Side) (slots : Fin n → Slot) (f : Assignment slots → BlockQuotient.JointOutput V B) + (selected : I) (q : BlockQuotient.OtherBlocks V selected × B → V selected) : + key side slots (displayedTranslate V B selected q ∘ f) = key side slots f := + key_postcomp_equiv side slots f (displayedTranslate V B selected q) + +section Quadratics + +variable {𝕜 J : Type*} [Field 𝕜] [Fintype J] + +open scoped BigOperators + +def quadraticValue (c : 𝕜) (coeff : J → J → 𝕜) (values : J → 𝕜) : 𝕜 := + c + ∑ i, ∑ j, coeff i j * (values i * values j) + +def quadraticFunction (c : 𝕜) (coeff : J → J → 𝕜) (rows : J → X → 𝕜) : X → 𝕜 := + c • 1 + ∑ i, ∑ j, coeff i j • (rows i * rows j) + +@[simp] theorem quadraticFunction_apply (c : 𝕜) (coeff : J → J → 𝕜) + (rows : J → X → 𝕜) (x : X) : + quadraticFunction c coeff rows x = quadraticValue c coeff (fun i => rows i x) := by + simp [quadraticFunction, quadraticValue, Finset.sum_apply, Pi.smul_apply, smul_eq_mul] + +theorem quadraticFunction_mem_squareSpace (H : Submodule 𝕜 (X → 𝕜)) + (hone : (1 : X → 𝕜) ∈ H) (c : 𝕜) (coeff : J → J → 𝕜) + (rows : J → H) : quadraticFunction c coeff (fun i => (rows i).val) ∈ squareSpace H := by + apply (squareSpace H).add_mem + · exact (squareSpace H).smul_mem c (one_mem_squareSpace H hone) + · apply Submodule.sum_mem + intro i _ + apply Submodule.sum_mem + intro j _ + exact (squareSpace H).smul_mem (coeff i j) + (mul_mem_squareSpace H (rows i).property (rows j).property) + +theorem quadratic_descendant_mem {branch : Nat → Nat} {n m : Nat} + (p : DescendantSpaces.Path branch n m) + (domains : RecursiveSpaces.Slots branch n → Type*) + (hbranch : ∀ k < n, 0 < branch k) (hproper : m < n) + (c : 𝕜) (coeff : J → J → 𝕜) + (rows : J → RecursiveSpaces.space 𝕜 branch m (p.family domains)) : + pullback 𝕜 (p.restriction domains) + (quadraticFunction c coeff (fun i => (rows i).val)) ∈ + RecursiveSpaces.space 𝕜 branch n domains := by + apply DescendantSpaces.descendant_square_le_space p domains hbranch hproper + apply Submodule.mem_map_of_mem + apply quadraticFunction_mem_squareSpace + exact RecursiveSpaces.one_mem_space branch m (p.family domains) + (fun k hk => hbranch k (Nat.lt_trans hk hproper)) + +end Quadratics + +end PerfectCompleteness.TriangularFolding + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/TupleIndexEmitterLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/TupleIndexEmitterLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..c5b2eb0cccfd90646454d108dbbb8ea381a1991c --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/TupleIndexEmitterLemmas.lean @@ -0,0 +1,739 @@ +import Mathlib.Algebra.BigOperators.Fin +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.NormNum +import OAI.Computability.PerfectCompleteness.Foundations.DualQuotientRowsLemmas +import OAI.Computability.UniqueGames.Foundations.Conditioning +import OAI.Computability.UniqueGames.Foundations.MixtureLemmas +import OAI.Computability.UniqueGames.Foundations.ValueLemmas +import OAI.Computability.UniqueGames.Machines.MachineCopy +import OAI.Computability.UniqueGames.Machines.MachineSubroutineLemmas + +namespace OAI + + +namespace PerfectCompleteness.TupleIndexEmitter + +open Turing UniqueGamesTheorem.Foundations.Complexity + +inductive Tape (width : Nat) (Extra : Type) + | current (coordinate : Fin width) + | scratch + | output + | extra (value : Extra) + deriving DecidableEq, Fintype + +inductive Label (width : Nat) + | copyOut (coordinate : Fin width) + | copyBack (coordinate : Fin width) + | done + deriving DecidableEq, Fintype + +variable {width : Nat} {Extra σ : Type} + +def labelAt : Nat → Label width + | 0 => .done + | r + 1 => if h : r < width then .copyOut ⟨r, h⟩ else .done + +def program : Label width → + TM2.Stmt (fun _ : Tape width Extra => Bool) (Label width) (σ × Option Bool) + | .copyOut j => UniqueGamesTheorem.Reduction.MachineTransfer.loopAt + (.current j) .scratch id false (.copyOut j) (some (.copyBack j)) + | .copyBack j => MachineCopy.forkLoop + .scratch (.current j) .output false (.copyBack j) (some (labelAt j.val)) + | .done => .halt + +def prefixWords (d : Fin width → Nat) (r : Nat) (hr : r ≤ width) : List Nat := + List.ofFn (fun i : Fin r => d ⟨i.val, Nat.lt_of_lt_of_le i.isLt hr⟩) + +@[simp] theorem prefixWords_zero (d : Fin width → Nat) : + prefixWords d 0 (Nat.zero_le _) = [] := rfl + +theorem prefixWords_succ (d : Fin width → Nat) (r : Nat) (hr : r + 1 ≤ width) : + prefixWords d (r + 1) hr = + prefixWords d r (by omega) ++ [d ⟨r, by omega⟩] := by + rw [prefixWords, List.ofFn_succ', List.concat_eq_append] + rfl + +@[simp] theorem prefixWords_all (d : Fin width → Nat) : + prefixWords d width (Nat.le_refl _) = List.ofFn d := by + rfl + +def prefixBudget (d : Fin width → Nat) (r : Nat) (hr : r ≤ width) : Nat := + ((prefixWords d r hr).map (fun n => 2 * (n + 2))).sum + +@[simp] theorem prefixBudget_zero (d : Fin width → Nat) : + prefixBudget d 0 (Nat.zero_le _) = 0 := rfl + +theorem prefixBudget_succ (d : Fin width → Nat) (r : Nat) (hr : r + 1 ≤ width) : + prefixBudget d (r + 1) hr = + prefixBudget d r (by omega) + 2 * (d ⟨r, by omega⟩ + 2) := by + simp only [prefixBudget, prefixWords_succ, List.map_append, List.sum_append, + List.map_cons, List.map_nil, List.sum_cons, List.sum_nil, Nat.add_zero] + +@[simp] theorem prefixBudget_all (d : Fin width → Nat) : + prefixBudget d width (Nat.le_refl _) = ∑ j, 2 * (d j + 2) := by + simp only [prefixBudget, prefixWords_all, List.map_ofFn, Function.comp_def, + List.sum_ofFn] + +variable [DecidableEq Extra] + +def outputTapes (base : Tape width Extra → List Bool) (bits : List Bool) : + Tape width Extra → List Bool := + Function.update base .output (bits ++ base .output) + +@[simp] theorem outputTapes_output (base : Tape width Extra → List Bool) (bits : List Bool) : + outputTapes base bits .output = bits ++ base .output := by + simp [outputTapes] + +@[simp] theorem outputTapes_current (base : Tape width Extra → List Bool) + (bits : List Bool) (j : Fin width) : + outputTapes base bits (.current j) = base (.current j) := by + simp [outputTapes] + +@[simp] theorem outputTapes_scratch (base : Tape width Extra → List Bool) (bits : List Bool) : + outputTapes base bits .scratch = base .scratch := by + simp [outputTapes] + +@[simp] theorem outputTapes_extra (base : Tape width Extra → List Bool) + (bits : List Bool) (x : Extra) : + outputTapes base bits (.extra x) = base (.extra x) := by + simp [outputTapes] + +@[simp] theorem outputTapes_nil (base : Tape width Extra → List Bool) : + outputTapes base [] = base := by + simp [outputTapes] + +theorem outputTapes_outputTapes (base : Tape width Extra → List Bool) + (first second : List Bool) : + outputTapes (outputTapes base first) second = outputTapes base (second ++ first) := by + simp [outputTapes, Function.update_idem, List.append_assoc] + +noncomputable def prefixInTimeFor {Λ : Type} + (labels : Label width → Λ) + (target : Λ → TM2.Stmt (fun _ : Tape width Extra => Bool) Λ (σ × Option Bool)) + (atCopyOut : ∀ j, target (labels (.copyOut j)) = + UniqueGamesTheorem.Reduction.MachineTransfer.loopAt (.current j) .scratch id false + (labels (.copyOut j)) (some (labels (.copyBack j)))) + (atCopyBack : ∀ j, target (labels (.copyBack j)) = + MachineCopy.forkLoop .scratch (.current j) .output false + (labels (.copyBack j)) (some (labels (labelAt j.val)))) + (d : Fin width → Nat) (r : Nat) (hr : r ≤ width) + (base : Tape width Extra → List Bool) + (hsaved : ∀ j, base (.current j) = encodeWord (d j)) + (hscratch : base .scratch = []) (ambient : σ) : + StateTransition.EvalsToInTime (TM2.step target) + ⟨some (labels (labelAt r)), (ambient, none), base⟩ + (some ⟨some (labels .done), (ambient, none), + outputTapes base (encodeWords (prefixWords d r hr))⟩) + (prefixBudget d r hr) := by + induction r generalizing base with + | zero => + exact { + steps := 0 + evals_in_steps := by simp [labelAt, encodeWords] + steps_le_m := Nat.le_refl _ + } + | succ r ih => + have hlt : r < width := by omega + let j : Fin width := ⟨r, hlt⟩ + let after := outputTapes base (encodeWord (d j)) + have copied := MachineCopy.copyInTime (.current j) .output .scratch + (by simp) (by simp) (by simp) false (labels (.copyOut j)) (labels (.copyBack j)) + (some (labels (labelAt j.val))) target (atCopyOut j) (atCopyBack j) base hscratch ambient none + have first : StateTransition.EvalsToInTime (TM2.step target) + ⟨some (labels (labelAt (r + 1))), (ambient, none), base⟩ + (some ⟨some (labels (labelAt r)), (ambient, none), after⟩) + (2 * (d j + 2)) := by + simpa only [labelAt, dite_eq_left hlt, hsaved j, encodeWord_length, + Nat.add_assoc, after, outputTapes, j] using copied + have rest := ih (by omega) after + (by intro i; simpa only [after, outputTapes_current] using hsaved i) + (by simpa only [after, outputTapes_scratch] using hscratch) + have joined := StateTransition.EvalsToInTime.trans (TM2.step target) _ _ _ _ _ first rest + have output_eq : + outputTapes after (encodeWords (prefixWords d r (by omega))) = + outputTapes base (encodeWords (prefixWords d (r + 1) hr)) := by + dsimp only [after] + rw [outputTapes_outputTapes, prefixWords_succ, encodeWords_append] + simp only [encodeWords, List.append_nil, j] + rw [output_eq] at joined + simpa only [prefixBudget_succ, j] using joined + +noncomputable def prefixInTime (d : Fin width → Nat) (r : Nat) (hr : r ≤ width) + (base : Tape width Extra → List Bool) + (hsaved : ∀ j, base (.current j) = encodeWord (d j)) + (hscratch : base .scratch = []) (ambient : σ) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labelAt r), (ambient, none), base⟩ + (some ⟨some .done, (ambient, none), + outputTapes base (encodeWords (prefixWords d r hr))⟩) + (prefixBudget d r hr) := + prefixInTimeFor id program (fun _ => rfl) (fun _ => rfl) + d r hr base hsaved hscratch ambient + +noncomputable def emitInTimeFor {Λ : Type} + (labels : Label width → Λ) + (target : Λ → TM2.Stmt (fun _ : Tape width Extra => Bool) Λ (σ × Option Bool)) + (atCopyOut : ∀ j, target (labels (.copyOut j)) = + UniqueGamesTheorem.Reduction.MachineTransfer.loopAt (.current j) .scratch id false + (labels (.copyOut j)) (some (labels (.copyBack j)))) + (atCopyBack : ∀ j, target (labels (.copyBack j)) = + MachineCopy.forkLoop .scratch (.current j) .output false + (labels (.copyBack j)) (some (labels (labelAt j.val)))) + (d : Fin width → Nat) (base : Tape width Extra → List Bool) + (hsaved : ∀ j, base (.current j) = encodeWord (d j)) + (hscratch : base .scratch = []) (ambient : σ) : + StateTransition.EvalsToInTime (TM2.step target) + ⟨some (labels (labelAt width)), (ambient, none), base⟩ + (some ⟨some (labels .done), (ambient, none), + outputTapes base (encodeWords (List.ofFn d))⟩) + (∑ j, 2 * (d j + 2)) := by + simpa only [prefixWords_all, prefixBudget_all] using + prefixInTimeFor labels target atCopyOut atCopyBack d width (Nat.le_refl _) + base hsaved hscratch ambient + +noncomputable def emitInTime (d : Fin width → Nat) + (base : Tape width Extra → List Bool) + (hsaved : ∀ j, base (.current j) = encodeWord (d j)) + (hscratch : base .scratch = []) (ambient : σ) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labelAt width), (ambient, none), base⟩ + (some ⟨some .done, (ambient, none), + outputTapes base (encodeWords (List.ofFn d))⟩) + (∑ j, 2 * (d j + 2)) := by + simpa only [prefixWords_all, prefixBudget_all] using + prefixInTime d width (Nat.le_refl _) base hsaved hscratch ambient + +theorem budget_eq (d : Fin width → Nat) : + (∑ j, 2 * (d j + 2)) = 2 * (∑ j : Fin width, (d j + 1)) + 2 * width := by + calc + (∑ j, 2 * (d j + 2)) = ∑ j : Fin width, (2 * (d j + 1) + 2) := by + apply Finset.sum_congr rfl + intro j _ + omega + _ = 2 * (∑ j : Fin width, (d j + 1)) + 2 * width := by + have hconst : (∑ _j : Fin width, (2 : Nat)) = 2 * width := by + simpa only [Finset.sum_const, Finset.card_univ, Fintype.card_fin, + Nat.nsmul_eq_mul] using (Nat.mul_comm width 2) + rw [Finset.sum_add_distrib, ← Finset.mul_sum, hconst] + +noncomputable def placedEmitInTime {Λ : Type} + (labels : Label width → Λ) (exit : Option Λ) + (target : Λ → TM2.Stmt (fun _ : Tape width Extra => Bool) Λ (σ × Option Bool)) + (atLabels : ∀ l, target (labels l) = MachineSubroutine.statement labels exit (program l)) + (d : Fin width → Nat) (base : Tape width Extra → List Bool) + (hsaved : ∀ j, base (.current j) = encodeWord (d j)) + (hscratch : base .scratch = []) (ambient : σ) : + StateTransition.EvalsToInTime (TM2.step target) + ⟨some (labels (labelAt width)), (ambient, none), base⟩ + (some ⟨some (labels .done), (ambient, none), + outputTapes base (encodeWords (List.ofFn d))⟩) + (∑ j, 2 * (d j + 2)) := + MachineSubroutine.execution labels exit program target atLabels + (emitInTime d base hsaved hscratch ambient) + +noncomputable def haltInTime (d : Fin width → Nat) + (base : Tape width Extra → List Bool) + (hsaved : ∀ j, base (.current j) = encodeWord (d j)) + (hscratch : base .scratch = []) (ambient : σ) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labelAt width), (ambient, none), base⟩ + (some ⟨none, (ambient, none), + outputTapes base (encodeWords (List.ofFn d))⟩) + ((∑ j, 2 * (d j + 2)) + 1) := by + have body := emitInTime d base hsaved hscratch ambient + have finish : StateTransition.EvalsToInTime (TM2.step program) + ⟨some .done, (ambient, none), outputTapes base (encodeWords (List.ofFn d))⟩ + (some ⟨none, (ambient, none), outputTapes base (encodeWords (List.ofFn d))⟩) 1 := + { steps := 1, evals_in_steps := rfl, steps_le_m := Nat.le_refl _ } + have joined := StateTransition.EvalsToInTime.trans (TM2.step program) _ _ _ _ _ body finish + simpa only [Nat.add_comm] using joined + +def machine (width : Nat) (Extra : Type) [DecidableEq Extra] [Fintype Extra] : FinTM2 where + K := Tape width Extra + k₀ := .output + k₁ := .output + Γ _ := Bool + Λ := Label width + main := labelAt width + σ := Unit × Option Bool + initialState := ((), none) + m := program + +end PerfectCompleteness.TupleIndexEmitter + + + +namespace PerfectCompleteness.UsefulMark + +noncomputable section + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games + +variable {Ω P : Type*} [Fintype Ω] [Fintype P] + +def marginalMass (μ : FiniteDistribution Ω) (p : Ω → P) (z : P) : ℝ := + μ.probability (fun x => decide (p x = z)) + +def lowerFiberMass (μ : FiniteDistribution Ω) (p : Ω → P) (L : Ω → Bool) + (z : P) : ℝ := + μ.probability (fun x => L x && decide (p x = z)) + +def conditionalLower (μ : FiniteDistribution Ω) (p : Ω → P) (L : Ω → Bool) + (z : P) : ℝ := + lowerFiberMass μ p L z / marginalMass μ p z + +def useful (μ : FiniteDistribution Ω) (p : Ω → P) (L : Ω → Bool) + (κ : ℝ) (z : P) : Bool := + decide (0 < marginalMass μ p z ∧ κ ≤ conditionalLower μ p L z) + +omit [Fintype P] in +theorem useful_iff (μ : FiniteDistribution Ω) (p : Ω → P) (L : Ω → Bool) + (κ : ℝ) (z : P) : + useful μ p L κ z = true ↔ + 0 < marginalMass μ p z ∧ κ ≤ conditionalLower μ p L z := by + simp only [useful, decide_eq_true_eq] + +omit [Fintype P] in +theorem marginalMass_nonneg (μ : FiniteDistribution Ω) (p : Ω → P) (z : P) : + 0 ≤ marginalMass μ p z := μ.probability_nonnegative _ + +omit [Fintype P] in +theorem lowerFiberMass_nonneg (μ : FiniteDistribution Ω) (p : Ω → P) + (L : Ω → Bool) (z : P) : 0 ≤ lowerFiberMass μ p L z := + μ.probability_nonnegative _ + +omit [Fintype P] in +theorem lowerFiberMass_le_marginalMass (μ : FiniteDistribution Ω) (p : Ω → P) + (L : Ω → Bool) (z : P) : lowerFiberMass μ p L z ≤ marginalMass μ p z := + μ.probability_and_le_right L (fun x => decide (p x = z)) + +omit [Fintype P] in +theorem lowerFiberMass_eq_zero (μ : FiniteDistribution Ω) (p : Ω → P) + (L : Ω → Bool) (z : P) (hzero : marginalMass μ p z = 0) : + lowerFiberMass μ p L z = 0 := + le_antisymm ((lowerFiberMass_le_marginalMass μ p L z).trans_eq hzero) + (lowerFiberMass_nonneg μ p L z) + +omit [Fintype P] in +theorem conditionalLower_eq_zero (μ : FiniteDistribution Ω) (p : Ω → P) + (L : Ω → Bool) (z : P) (hzero : marginalMass μ p z = 0) : + conditionalLower μ p L z = 0 := by + simp [conditionalLower, hzero] + +theorem marginalMass_eq_pushforward_weight (μ : FiniteDistribution Ω) + (p : Ω → P) (z : P) : marginalMass μ p z = (μ.pushforward p).weight z := by + simp [marginalMass, FiniteDistribution.probability, FiniteDistribution.pushforward] + +theorem sum_marginalMass (μ : FiniteDistribution Ω) (p : Ω → P) : + (∑ z, marginalMass μ p z) = 1 := by + simp_rw [marginalMass_eq_pushforward_weight] + exact (μ.pushforward p).normalized + +theorem probability_eq_sum_fibers (μ : FiniteDistribution Ω) (p : Ω → P) + (event : Ω → Bool) : μ.probability event = ∑ z, lowerFiberMass μ p event z := by + unfold lowerFiberMass FiniteDistribution.probability + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro x _ + cases he : event x <;> simp [he, eq_comm] + +theorem probability_mark_eq_sum (μ : FiniteDistribution Ω) (p : Ω → P) + (L : Ω → Bool) (mark : P → Bool) : + μ.probability (fun x => L x && mark (p x)) = + ∑ z, if mark z then lowerFiberMass μ p L z else 0 := by + rw [probability_eq_sum_fibers μ p] + apply Finset.sum_congr rfl + intro z _ + unfold lowerFiberMass FiniteDistribution.probability + by_cases hz : mark z = true + · rw [ite_eq_left hz] + apply Finset.sum_congr rfl + intro x _ + by_cases hx : p x = z <;> simp [hx, hz] + · rw [ite_eq_right hz] + apply Finset.sum_eq_zero + intro x _ + by_cases hx : p x = z <;> simp [hx, hz] + +omit [Fintype P] in +theorem lowerFiberMass_le_of_not_useful (μ : FiniteDistribution Ω) (p : Ω → P) + (L : Ω → Bool) (κ : ℝ) (z : P) (h : useful μ p L κ z ≠ true) : + lowerFiberMass μ p L z ≤ κ * marginalMass μ p z := by + by_cases hpos : 0 < marginalMass μ p z + · have hlt : conditionalLower μ p L z < κ := by + apply lt_of_not_ge + intro hκ + exact h ((useful_iff μ p L κ z).mpr ⟨hpos, hκ⟩) + change lowerFiberMass μ p L z / marginalMass μ p z < κ at hlt + exact ((div_lt_iff₀ hpos).mp hlt).le + · have hzero : marginalMass μ p z = 0 := + le_antisymm (le_of_not_gt hpos) (marginalMass_nonneg μ p z) + simp [lowerFiberMass_eq_zero μ p L z hzero, hzero] + +theorem discarded_lower_le (μ : FiniteDistribution Ω) (p : Ω → P) + (L : Ω → Bool) (κ : ℝ) (hκ : 0 ≤ κ) : + μ.probability (fun x => L x && !useful μ p L κ (p x)) ≤ κ := by + rw [probability_mark_eq_sum μ p L (fun z => !useful μ p L κ z)] + calc + _ ≤ ∑ z, κ * marginalMass μ p z := by + apply Finset.sum_le_sum + intro z _ + by_cases hz : useful μ p L κ z = true + · simpa [hz] using mul_nonneg hκ (marginalMass_nonneg μ p z) + · simpa [hz] using + lowerFiberMass_le_of_not_useful μ p L κ z hz + _ = κ := by rw [← Finset.mul_sum, sum_marginalMass, mul_one] + +omit [Fintype P] in +theorem joint_le_discarded_add_marked (μ : FiniteDistribution Ω) (p : Ω → P) + (L upper : Ω → Bool) (mark : P → Bool) : + μ.probability (fun x => L x && upper x) ≤ + μ.probability (fun x => L x && !mark (p x)) + + μ.probability (fun x => upper x && mark (p x)) := by + unfold FiniteDistribution.probability + rw [← Finset.sum_add_distrib] + apply Finset.sum_le_sum + intro x _ + cases hL : L x <;> cases hU : upper x <;> cases hmark : mark (p x) <;> + simp [hL, hU, hmark, μ.nonnegative x] + +theorem useful_upper_ge_sub (μ : FiniteDistribution Ω) (p : Ω → P) + (L upper : Ω → Bool) (κ c : ℝ) (hκ : 0 ≤ κ) + (hjoint : c ≤ μ.probability (fun x => L x && upper x)) : + c - κ ≤ μ.probability (fun x => upper x && useful μ p L κ (p x)) := by + have hsplit := joint_le_discarded_add_marked μ p L upper (useful μ p L κ) + have hdiscard := discarded_lower_le μ p L κ hκ + linarith + +theorem useful_upper_ge_half (μ : FiniteDistribution Ω) (p : Ω → P) + (L upper : Ω → Bool) (c : ℝ) (hc : 0 ≤ c) + (hjoint : c ≤ μ.probability (fun x => L x && upper x)) : + c / 2 ≤ μ.probability (fun x => upper x && useful μ p L (c / 2) (p x)) := by + have h := useful_upper_ge_sub μ p L upper (c / 2) c + (div_nonneg hc (by norm_num)) hjoint + linarith + +end +end PerfectCompleteness.UsefulMark + + + +namespace PerfectCompleteness.PositiveFiberMass + +noncomputable section + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games + +variable {Ω R : Type*} [Fintype Ω] [Fintype R] + +def jMass (μ : FiniteDistribution Ω) (record : Ω → R) (J : Ω → Bool) (r : R) : ℝ := + UsefulMark.lowerFiberMass μ record J r + +def matchMass (μ : FiniteDistribution Ω) (record : Ω → R) + (J prediction : Ω → Bool) (r : R) : ℝ := + UsefulMark.lowerFiberMass μ record (fun x => J x && prediction x) r + +def conditionalMatch (μ : FiniteDistribution Ω) (record : Ω → R) + (J prediction : Ω → Bool) (r : R) : ℝ := + matchMass μ record J prediction r / jMass μ record J r + +def goodRecord (μ : FiniteDistribution Ω) (record : Ω → R) + (J prediction : Ω → Bool) (ρ : ℝ) (r : R) : Bool := + decide (0 < jMass μ record J r ∧ ρ ≤ conditionalMatch μ record J prediction r) + +omit [Fintype R] in +theorem goodRecord_iff (μ : FiniteDistribution Ω) (record : Ω → R) + (J prediction : Ω → Bool) (ρ : ℝ) (r : R) : + goodRecord μ record J prediction ρ r = true ↔ + 0 < jMass μ record J r ∧ ρ ≤ conditionalMatch μ record J prediction r := by + simp only [goodRecord, decide_eq_true_eq] + +omit [Fintype R] in +theorem jMass_nonneg (μ : FiniteDistribution Ω) (record : Ω → R) + (J : Ω → Bool) (r : R) : 0 ≤ jMass μ record J r := + μ.probability_nonnegative _ + +omit [Fintype R] in +theorem matchMass_nonneg (μ : FiniteDistribution Ω) (record : Ω → R) + (J prediction : Ω → Bool) (r : R) : 0 ≤ matchMass μ record J prediction r := + μ.probability_nonnegative _ + +omit [Fintype R] in +theorem matchMass_le_jMass (μ : FiniteDistribution Ω) (record : Ω → R) + (J prediction : Ω → Bool) (r : R) : + matchMass μ record J prediction r ≤ jMass μ record J r := by + apply μ.probability_mono + intro x hx + simp only [Bool.and_eq_true] at hx ⊢ + exact ⟨hx.1.1, hx.2⟩ + +omit [Fintype R] in +theorem matchMass_eq_zero (μ : FiniteDistribution Ω) (record : Ω → R) + (J prediction : Ω → Bool) (r : R) (hzero : jMass μ record J r = 0) : + matchMass μ record J prediction r = 0 := + le_antisymm ((matchMass_le_jMass μ record J prediction r).trans_eq hzero) + (matchMass_nonneg μ record J prediction r) + +omit [Fintype R] in +theorem matchMass_le_of_not_goodRecord (μ : FiniteDistribution Ω) (record : Ω → R) + (J prediction : Ω → Bool) (ρ : ℝ) (r : R) + (hbad : goodRecord μ record J prediction ρ r ≠ true) : + matchMass μ record J prediction r ≤ ρ * jMass μ record J r := by + by_cases hpos : 0 < jMass μ record J r + · have hlt : conditionalMatch μ record J prediction r < ρ := by + apply lt_of_not_ge + intro hρ + exact hbad ((goodRecord_iff μ record J prediction ρ r).mpr ⟨hpos, hρ⟩) + change matchMass μ record J prediction r / jMass μ record J r < ρ at hlt + exact ((div_lt_iff₀ hpos).mp hlt).le + · have hzero : jMass μ record J r = 0 := + le_antisymm (le_of_not_gt hpos) (jMass_nonneg μ record J r) + rw [matchMass_eq_zero μ record J prediction r hzero, hzero, mul_zero] + +omit [Fintype R] in +theorem fiber_difference_le_good_mass (μ : FiniteDistribution Ω) (record : Ω → R) + (J prediction : Ω → Bool) (ρ : ℝ) (hρ : 0 ≤ ρ) (r : R) : + matchMass μ record J prediction r - ρ * jMass μ record J r ≤ + if goodRecord μ record J prediction ρ r then jMass μ record J r else 0 := by + by_cases hgood : goodRecord μ record J prediction ρ r = true + · rw [ite_eq_left hgood] + have hmatch := matchMass_le_jMass μ record J prediction r + have hproduct := mul_nonneg hρ (jMass_nonneg μ record J r) + linarith + · rw [ite_eq_right hgood] + exact sub_nonpos.mpr (matchMass_le_of_not_goodRecord μ record J prediction ρ r hgood) + +theorem sum_jMass (μ : FiniteDistribution Ω) (record : Ω → R) (J : Ω → Bool) : + (∑ r, jMass μ record J r) = μ.probability J := + (UsefulMark.probability_eq_sum_fibers μ record J).symm + +theorem sum_matchMass (μ : FiniteDistribution Ω) (record : Ω → R) + (J prediction : Ω → Bool) : + (∑ r, matchMass μ record J prediction r) = + μ.probability (fun x => J x && prediction x) := + (UsefulMark.probability_eq_sum_fibers μ record (fun x => J x && prediction x)).symm + +theorem difference_eq_sum (μ : FiniteDistribution Ω) (record : Ω → R) + (J prediction : Ω → Bool) (ρ : ℝ) : + μ.probability (fun x => J x && prediction x) - ρ * μ.probability J = + ∑ r, (matchMass μ record J prediction r - ρ * jMass μ record J r) := by + rw [Finset.sum_sub_distrib, ← Finset.mul_sum, sum_matchMass, sum_jMass] + +theorem difference_le_good_mass (μ : FiniteDistribution Ω) (record : Ω → R) + (J prediction : Ω → Bool) (ρ : ℝ) (hρ : 0 ≤ ρ) : + μ.probability (fun x => J x && prediction x) - ρ * μ.probability J ≤ + μ.probability (fun x => J x && goodRecord μ record J prediction ρ (record x)) := by + rw [difference_eq_sum μ record J prediction ρ, + UsefulMark.probability_mark_eq_sum μ record J (goodRecord μ record J prediction ρ)] + apply Finset.sum_le_sum + intro r _ + exact fiber_difference_le_good_mass μ record J prediction ρ hρ r + +theorem good_mass_ge_difference_lower_bound + (μ : FiniteDistribution Ω) (record : Ω → R) (J prediction : Ω → Bool) + (ρ b : ℝ) (hρ : 0 ≤ ρ) + (hdifference : b ≤ μ.probability (fun x => J x && prediction x) - ρ * μ.probability J) : + b ≤ μ.probability (fun x => J x && goodRecord μ record J prediction ρ (record x)) := + hdifference.trans (difference_le_good_mass μ record J prediction ρ hρ) + +omit [Fintype R] in +theorem conditional_probability_ge_of_goodRecord + (μ : FiniteDistribution Ω) (record : Ω → R) (J prediction : Ω → Bool) + (ρ : ℝ) (r : R) (hgood : goodRecord μ record J prediction ρ r = true) : + ρ ≤ (μ.condition (fun x => J x && decide (record x = r)) + ((goodRecord_iff μ record J prediction ρ r).mp hgood).1).probability prediction := by + have hp : 0 < μ.probability (fun x => J x && decide (record x = r)) := + ((goodRecord_iff μ record J prediction ρ r).mp hgood).1 + change ρ ≤ (μ.condition (fun x => J x && decide (record x = r)) hp).probability prediction + rw [FiniteDistribution.probability_condition] + have hevent : (fun x => (J x && decide (record x = r)) && prediction x) = + (fun x => (J x && prediction x) && decide (record x = r)) := by + funext x + cases J x <;> cases prediction x <;> cases decide (record x = r) <;> rfl + rw [hevent] + exact ((goodRecord_iff μ record J prediction ρ r).mp hgood).2 + +end +end PerfectCompleteness.PositiveFiberMass + + + +namespace PerfectCompleteness.UsefulAdvice + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games +open UsefulMark + +noncomputable section + +variable {Ω P : Type*} [Fintype Ω] [Fintype P] + +theorem marked_probability_eq_sum (μ : FiniteDistribution Ω) (p : Ω → P) + (event : P → Bool) : + μ.probability (fun x => event (p x)) = + ∑ z, if event z then marginalMass μ p z else 0 := by + simpa only [lowerFiberMass, marginalMass, Bool.true_and] using + probability_mark_eq_sum μ p (fun _ => true) event + +omit [Fintype P] in +theorem useful_fiber_lower (μ : FiniteDistribution Ω) (p : Ω → P) + (L : Ω → Bool) (κ : ℝ) (z : P) (hz : useful μ p L κ z = true) : + κ * marginalMass μ p z ≤ lowerFiberMass μ p L z := by + obtain ⟨hpos, hratio⟩ := (useful_iff μ p L κ z).mp hz + exact (le_div_iff₀ hpos).mp hratio + +theorem marked_lower_bound (μ : FiniteDistribution Ω) (p : Ω → P) + (L : Ω → Bool) (κ : ℝ) (event : P → Bool) + (hmarked : ∀ z, event z = true → useful μ p L κ z = true) : + κ * μ.probability (fun x => event (p x)) ≤ + μ.probability (fun x => L x && event (p x)) := by + rw [marked_probability_eq_sum μ p event, + probability_mark_eq_sum μ p L event, Finset.mul_sum] + apply Finset.sum_le_sum + intro z _ + by_cases hz : event z = true + · simpa only [ite_eq_left hz] using useful_fiber_lower μ p L κ z (hmarked z hz) + · simp only [ite_eq_right hz, mul_zero, le_refl] + +variable {A : Type*} [Fintype A] + +theorem product_probability_advice_first (μ : FiniteDistribution Ω) + (ν : FiniteDistribution A) (event : Ω × A → Bool) : + (μ.product ν).probability event = + ν.expectation (fun a => μ.probability (fun x => event (x, a))) := by + calc + _ = ∑ x, ∑ a, if event (x, a) then μ.weight x * ν.weight a else 0 := by + simp only [FiniteDistribution.probability, FiniteDistribution.product, + Fintype.sum_prod_type] + _ = ∑ a, ∑ x, if event (x, a) then μ.weight x * ν.weight a else 0 := + Finset.sum_comm + _ = _ := by + simp only [FiniteDistribution.expectation, FiniteDistribution.probability, + Finset.mul_sum] + apply Finset.sum_congr rfl + intro a _ + apply Finset.sum_congr rfl + intro x _ + by_cases he : event (x, a) = true <;> simp [he, mul_comm] + +theorem independent_advice_lower_bound (μ : FiniteDistribution Ω) + (ν : FiniteDistribution A) (p : Ω → P) (L : Ω → Bool) (κ : ℝ) + (event : P × A → Bool) + (hmarked : ∀ z a, event (z, a) = true → useful μ p L κ z = true) : + κ * (μ.product ν).probability (fun x => event (p x.1, x.2)) ≤ + (μ.product ν).probability (fun x => L x.1 && event (p x.1, x.2)) := by + rw [product_probability_advice_first, product_probability_advice_first, + ← SmallBiasSlice.expectation_const_mul] + apply PerfectCompleteness.SmallBias.expectation_mono + intro a + exact marked_lower_bound μ p L κ (fun z => event (z, a)) (fun z => hmarked z a) + +theorem independent_advice_predicts (μ : FiniteDistribution Ω) + (ν : FiniteDistribution A) (p : Ω → P) (L : Ω → Bool) (κ : ℝ) + (event : P × A → Bool) (prediction : Ω × A → Bool) + (hmarked : ∀ z a, event (z, a) = true → useful μ p L κ z = true) + (hpredict : ∀ x a, L x = true → event (p x, a) = true → + prediction (x, a) = true) : + κ * (μ.product ν).probability (fun x => event (p x.1, x.2)) ≤ + (μ.product ν).probability prediction := by + apply (independent_advice_lower_bound μ ν p L κ event hmarked).trans + apply FiniteDistribution.probability_mono + rintro ⟨x, a⟩ h + have hh := Bool.and_eq_true_iff.mp h + exact hpredict x a hh.1 hh.2 + +end +end PerfectCompleteness.UsefulAdvice + + + +namespace PerfectCompleteness.PredictionDifference + +open scoped Classical +open UniqueGamesTheorem.Foundations.Games + +noncomputable section + +theorem scalar_bound (κ α q₀ v h pI pJ pMatch : ℝ) + (hκ : 0 ≤ κ) (hα : 0 ≤ α) (hα1 : α ≤ 1) (hq₀ : 0 ≤ q₀) + (hv : 0 ≤ v) (hsmall : v ≤ α * q₀ / 16) (hmass : q₀ ≤ h) + (hI : α * h - v ≤ pI) (hJ : pJ ≤ h + v) + (hpredict : κ * pI ≤ pMatch) : + κ * α * q₀ / 4 ≤ pMatch - (κ * α / 4) * pJ := by + have hκα : 0 ≤ κ * α := mul_nonneg hκ hα + have hρ : 0 ≤ κ * α / 4 := div_nonneg hκα (by norm_num) + have hρκ : κ * α / 4 ≤ κ := by + have h := mul_le_mul_of_nonneg_left hα1 hκ + nlinarith + have hp := (mul_le_mul_of_nonneg_left hI hκ).trans hpredict + have hj := mul_le_mul_of_nonneg_left hJ hρ + have hc : 0 ≤ κ * α - κ * α / 4 := by nlinarith + have hh := mul_le_mul_of_nonneg_left hmass hc + have he := mul_le_mul_of_nonneg_left hsmall hκ + have he' := mul_le_mul_of_nonneg_right hρκ hv + have hmain := mul_nonneg hκα hq₀ + nlinarith + +variable {Ω Γ O : Type*} [Fintype Ω] [Fintype Γ] [Fintype O] + +theorem of_observed_variation + (μ : FiniteDistribution Ω) (ν : FiniteDistribution Γ) + (observe : Ω → O) (referenceObserve : Γ → O) + (I J : O → Bool) (prediction : Ω → Bool) + (κ α q₀ v : ℝ) (hκ : 0 ≤ κ) (hα : 0 ≤ α) (hα1 : α ≤ 1) + (hq₀ : 0 ≤ q₀) (hv : 0 ≤ v) (hsmall : v ≤ α * q₀ / 16) + (hvariation : (μ.pushforward observe).totalVariation + (ν.pushforward referenceObserve) ≤ v) + (hmass : q₀ ≤ ν.probability (fun x => J (referenceObserve x))) + (hdensity : α * ν.probability (fun x => J (referenceObserve x)) ≤ + ν.probability (fun x => I (referenceObserve x))) + (hpredict : κ * μ.probability (fun x => I (observe x)) ≤ μ.probability prediction) : + κ * α * q₀ / 4 ≤ μ.probability prediction - + (κ * α / 4) * μ.probability (fun x => J (observe x)) := by + have hi := (μ.pushforward observe).probability_abs_sub_le_totalVariation + (ν.pushforward referenceObserve) I + have hj := (μ.pushforward observe).probability_abs_sub_le_totalVariation + (ν.pushforward referenceObserve) J + rw [FiniteDistribution.probability_pushforward, + FiniteDistribution.probability_pushforward] at hi hj + have hi' := (abs_le.mp (hi.trans hvariation)).1 + have hj' := (abs_le.mp (hj.trans hvariation)).2 + apply scalar_bound κ α q₀ v (ν.probability (fun x => J (referenceObserve x))) + (μ.probability (fun x => I (observe x))) + (μ.probability (fun x => J (observe x))) (μ.probability prediction) + hκ hα hα1 hq₀ hv hsmall hmass + · linarith + · linarith + · exact hpredict + +variable {P A : Type*} [Fintype P] [Fintype A] + +theorem of_original_usefulness + (μ : FiniteDistribution Ω) (advice : FiniteDistribution A) + (reference : FiniteDistribution Γ) (p : Ω → P) + (referenceObserve : Γ → P × A) (L : Ω → Bool) + (I J : P × A → Bool) (prediction : Ω × A → Bool) + (κ α q₀ v : ℝ) (hκ : 0 ≤ κ) (hα : 0 ≤ α) (hα1 : α ≤ 1) + (hq₀ : 0 ≤ q₀) (hv : 0 ≤ v) (hsmall : v ≤ α * q₀ / 16) + (hmarked : ∀ z a, I (z, a) = true → UsefulMark.useful μ p L κ z = true) + (hprediction : ∀ x a, L x = true → I (p x, a) = true → + prediction (x, a) = true) + (hvariation : ((μ.product advice).pushforward (fun x => (p x.1, x.2))).totalVariation + (reference.pushforward referenceObserve) ≤ v) + (hmass : q₀ ≤ reference.probability (fun x => J (referenceObserve x))) + (hdensity : α * reference.probability (fun x => J (referenceObserve x)) ≤ + reference.probability (fun x => I (referenceObserve x))) : + κ * α * q₀ / 4 ≤ (μ.product advice).probability prediction - + (κ * α / 4) * (μ.product advice).probability (fun x => J (p x.1, x.2)) := by + apply of_observed_variation (μ.product advice) reference (fun x => (p x.1, x.2)) + referenceObserve I J prediction κ α q₀ v hκ hα hα1 hq₀ hv hsmall + hvariation hmass hdensity + exact UsefulAdvice.independent_advice_predicts μ advice p L κ I prediction hmarked hprediction + +end +end PerfectCompleteness.PredictionDifference + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/WholeArrayComposition.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/WholeArrayComposition.lean new file mode 100644 index 0000000000000000000000000000000000000000..3e899ad03c55eca672e3e1ffdf8430443b67a7c9 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/WholeArrayComposition.lean @@ -0,0 +1,223 @@ +import OAI.Computability.PerfectCompleteness.Sampling.SamplerCompositionLaws +import OAI.Computability.PerfectCompleteness.Sampling.WholeArraySampler + +namespace OAI + +section + +namespace PerfectCompleteness.WholeArrayComposition + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open WholeArraySampler +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +noncomputable section + +variable {branch : Nat → Nat} {n m k t : Nat} + +def collapseRoot (rows repeats : Nat → Nat) (p : Path branch n m) (q : Path branch m k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + RootTape rows repeats (p.append q) slots → RootTape rows repeats p slots := + fun ω direction => + SamplerComposition.collapseSuffix F2 repeats p q (LeafDomain slots) (ω direction) + +theorem evaluate_collapseRoot (rows repeats : Nat → Nat) + (p : Path branch n m) (q : Path branch m k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (ω : RootTape rows repeats (p.append q) slots) : + BucketSampler.recursiveEvaluate (rows n) repeats p (LeafDomain slots) + (collapseRoot rows repeats p q slots ω) = + BucketSampler.recursiveEvaluate (rows n) repeats (p.append q) (LeafDomain slots) ω := by + funext row + change (∑ direction : BucketSampler.Direction (rows n), direction.val row • + RecursiveSampler.evaluate F2 repeats p (LeafDomain slots) + (SamplerComposition.collapseSuffix F2 repeats p q (LeafDomain slots) (ω direction))) = + ∑ direction : BucketSampler.Direction (rows n), direction.val row • + RecursiveSampler.evaluate F2 repeats (p.append q) (LeafDomain slots) (ω direction) + apply Finset.sum_congr rfl + intro direction _ + exact congrArg (fun h : H slots => direction.val row • h) + (SamplerComposition.evaluate_collapseSuffix F2 repeats p q (LeafDomain slots) (ω direction)) + +def collapseSuffix (rows repeats : Nat → Nat) : + {n m k : Nat} → (p : Path branch n m) → (q : Path branch m k) → + (slots : Slots branch n → Fin t → MixedSupport.Slot) → + Tape rows repeats (p.append q) slots → Tape rows repeats p slots + | _, _, _, .refl _, q, slots, ω => evaluate rows repeats q slots ω + | _, _, _, .step i p, q, slots, ω => fun field => + match field with + | .inl _ => collapseRoot rows repeats (.step i p) q slots (ω (.inl ())) + | .inr (.inl _) => + collapseSuffix rows repeats p q (childSlots slots i) (ω (.inr (.inl ()))) + | .inr (.inr j) => ω (.inr (.inr j)) + +@[simp] theorem collapseSuffix_refl (rows repeats : Nat → Nat) (q : Path branch n k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (ω : Tape rows repeats q slots) : + collapseSuffix rows repeats (.refl n) q slots ω = evaluate rows repeats q slots ω := rfl + +@[simp] theorem collapseSuffix_root (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) (q : Path branch m k) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ω : Tape rows repeats ((Path.step i p).append q) slots) : + collapseSuffix rows repeats (.step i p) q slots ω (.inl ()) = + collapseRoot rows repeats (.step i p) q slots (ω (.inl ())) := rfl + +@[simp] theorem collapseSuffix_selected (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) (q : Path branch m k) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ω : Tape rows repeats ((Path.step i p).append q) slots) : + collapseSuffix rows repeats (.step i p) q slots ω (.inr (.inl ())) = + collapseSuffix rows repeats p q (childSlots slots i) (ω (.inr (.inl ()))) := rfl + +@[simp] theorem collapseSuffix_ordinary (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) (q : Path branch m k) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ω : Tape rows repeats ((Path.step i p).append q) slots) (j : RecursiveSampler.OffPath i) : + collapseSuffix rows repeats (.step i p) q slots ω (.inr (.inr j)) = + ω (.inr (.inr j)) := rfl + +theorem evaluate_collapseSuffix (rows repeats : Nat → Nat) (p : Path branch n m) : + ∀ (q : Path branch m k) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (ω : Tape rows repeats (p.append q) slots), + evaluate rows repeats p slots (collapseSuffix rows repeats p q slots ω) = + evaluate rows repeats (p.append q) slots ω := by + induction p with + | refl n => intro q slots ω; rfl + | @step n m i p ih => + intro q slots ω + exact congrArg₂ (assemble slots rows) + (evaluate_collapseRoot rows repeats (.step i p) q slots (ω (.inl ()))) + (congrArg (fun selected : Arrays (childSlots slots i) rows => + childrenAt slots rows i selected (fun j => ω (.inr (.inr j)))) + (ih q (childSlots slots i) (ω (.inr (.inl ()))))) + +def collapsedRootLaw (rows repeats : Nat → Nat) (p : Path branch n m) (q : Path branch m k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + FiniteDistribution (RootTape rows repeats p slots) := + BucketSampler.tapeLaw (rows n) + (FiniteProduct.law (SamplerComposition.factorLaw F2 repeats p q (LeafDomain slots))) + +theorem collapseRoot_tapeLaw (rows repeats : Nat → Nat) + (p : Path branch n m) (q : Path branch m k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + (BucketSampler.recursiveTapeLaw (rows n) repeats (p.append q) (LeafDomain slots)).pushforward + (collapseRoot rows repeats p q slots) = collapsedRootLaw rows repeats p q slots := by + calc + _ = FiniteProduct.law (fun _ : BucketSampler.Direction (rows n) => + (RecursiveSampler.tapeLaw F2 repeats (p.append q) (LeafDomain slots)).pushforward + (SamplerComposition.collapseSuffix F2 repeats p q (LeafDomain slots))) := + FiniteProduct.pushforward_map + (fun _ : BucketSampler.Direction (rows n) => + RecursiveSampler.tapeLaw F2 repeats (p.append q) (LeafDomain slots)) + (fun _ => SamplerComposition.collapseSuffix F2 repeats p q (LeafDomain slots)) + _ = _ := by + rw [SamplerComposition.collapseSuffix_tapeLaw, collapsedRootLaw, BucketSampler.tapeLaw] + +def collapsedTapeLaw (rows repeats : Nat → Nat) : + {n m k : Nat} → (p : Path branch n m) → (q : Path branch m k) → + (slots : Slots branch n → Fin t → MixedSupport.Slot) → + FiniteDistribution (Tape rows repeats p slots) + | _, _, _, .refl _, q, slots => WholeArraySampler.law rows repeats q slots + | _, _, _, .step i p, q, slots => by + letI : (field : StepIndex i) → Fintype + (StepFactor (RootTape rows repeats (.step i p) slots) + (Tape rows repeats p (childSlots slots i)) + (fun j => Arrays (childSlots slots j.val) rows) field) := + fun field => stepFactorFintype _ _ _ field + exact FiniteProduct.law + (Ω := fun field : StepIndex i => + StepFactor (RootTape rows repeats (.step i p) slots) + (Tape rows repeats p (childSlots slots i)) + (fun j => Arrays (childSlots slots j.val) rows) field) + (fun field => match field with + | .inl _ => collapsedRootLaw rows repeats (.step i p) q slots + | .inr (.inl _) => collapsedTapeLaw rows repeats p q (childSlots slots i) + | .inr (.inr j) => FiniteDistribution.uniform (Arrays (childSlots slots j.val) rows)) + +def collapseField (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) (q : Path branch m k) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) : + (field : StepIndex i) → + StepFactor (RootTape rows repeats (.step i (p.append q)) slots) + (Tape rows repeats (p.append q) (childSlots slots i)) + (fun j => Arrays (childSlots slots j.val) rows) field → + StepFactor (RootTape rows repeats (.step i p) slots) + (Tape rows repeats p (childSlots slots i)) + (fun j => Arrays (childSlots slots j.val) rows) field + | .inl _ => collapseRoot rows repeats (.step i p) q slots + | .inr (.inl _) => collapseSuffix rows repeats p q (childSlots slots i) + | .inr (.inr _) => id + +theorem collapseSuffix_step (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) (q : Path branch m k) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) : + collapseSuffix rows repeats (.step i p) q slots = + fun ω field => collapseField rows repeats i p q slots field (ω field) := by + funext ω field + rcases field with u | (u | j) + · cases u + rfl + · cases u + rfl + · rfl + +theorem collapseSuffix_tapeLaw (rows repeats : Nat → Nat) (p : Path branch n m) : + ∀ (q : Path branch m k) (slots : Slots branch n → Fin t → MixedSupport.Slot), + (tapeLaw rows repeats (p.append q) slots).pushforward + (collapseSuffix rows repeats p q slots) = collapsedTapeLaw rows repeats p q slots := by + induction p with + | refl n => intro q slots; rfl + | @step n m i p ih => + intro q slots + let : (field : StepIndex i) → Fintype + (StepFactor (RootTape rows repeats (.step i (p.append q)) slots) + (Tape rows repeats (p.append q) (childSlots slots i)) + (fun j => Arrays (childSlots slots j.val) rows) field) := + fun field => stepFactorFintype _ _ _ field + let : (field : StepIndex i) → Fintype + (StepFactor (RootTape rows repeats (.step i p) slots) + (Tape rows repeats p (childSlots slots i)) + (fun j => Arrays (childSlots slots j.val) rows) field) := + fun field => stepFactorFintype _ _ _ field + calc + _ = FiniteProduct.law (fun field : StepIndex i => + (componentLaw rows repeats i (p.append q) slots field).pushforward + (collapseField rows repeats i p q slots field)) := by + rw [collapseSuffix_step] + exact FiniteProduct.pushforward_map (componentLaw rows repeats i (p.append q) slots) + (collapseField rows repeats i p q slots) + _ = _ := by + apply congrArg (fun laws : (field : StepIndex i) → FiniteDistribution + (StepFactor (RootTape rows repeats (.step i p) slots) + (Tape rows repeats p (childSlots slots i)) + (fun j => Arrays (childSlots slots j.val) rows) field) => FiniteProduct.law laws) + funext field + rcases field with u | (u | j) + · cases u + exact collapseRoot_tapeLaw rows repeats (.step i p) q slots + · cases u + exact ih q (childSlots slots i) + · exact FiniteDistribution.pushforward_id _ + +theorem law_append (rows repeats : Nat → Nat) (p : Path branch n m) (q : Path branch m k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + WholeArraySampler.law rows repeats (p.append q) slots = + (collapsedTapeLaw rows repeats p q slots).pushforward (evaluate rows repeats p slots) := by + calc + _ = ((tapeLaw rows repeats (p.append q) slots).pushforward + (collapseSuffix rows repeats p q slots)).pushforward (evaluate rows repeats p slots) := by + rw [FiniteDistribution.pushforward_comp] + unfold WholeArraySampler.law + congr 1 + funext ω + exact (evaluate_collapseSuffix rows repeats p q slots ω).symm + _ = _ := by rw [collapseSuffix_tapeLaw] + +end +end PerfectCompleteness.WholeArrayComposition + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/WholeArrayInteriorExteriorLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/WholeArrayInteriorExteriorLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..5ca03a5fd0f00ec03ad8c61dff029fdeeed1db3b --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/WholeArrayInteriorExteriorLemmas.lean @@ -0,0 +1,370 @@ +import OAI.Computability.PerfectCompleteness.Foundations.WholeArraySubtreeSplit +import OAI.Computability.PerfectCompleteness.Sampling.WholeArrayInteriorHiddenLaw + +namespace OAI + + +namespace PerfectCompleteness.WholeArrayInteriorExterior + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays WholeArraySampler +open WholeArraySubtreeSplit +open scoped Classical + +noncomputable section + +variable {branch : Nat → Nat} {N n m t : Nat} + +def upperNode : {N n : Nat} → Path branch N (n + 1) → Nodes branch N + | _, _, .refl _ => .inl () + | _, _, .step j p => .inr (j, upperNode p) + +@[simp] theorem upperNode_refl : + upperNode (DescendantSpaces.Path.refl (n + 1) : Path branch (n + 1) (n + 1)) = + (Sum.inl () : Nodes branch (n + 1)) := rfl + +@[simp] theorem upperNode_step (j : Fin (branch N)) (p : Path branch N (n + 1)) : + upperNode (.step j p) = .inr (j, upperNode p) := rfl + +@[simp] theorem upperNode_height : + {N n : Nat} → (p : Path branch N (n + 1)) → Nodes.height (upperNode p) = n + 1 + | _, _, .refl _ => rfl + | _, _, .step _ p => upperNode_height p + +theorem upperNode_spec : + {N n : Nat} → (p : Path branch N (n + 1)) → + (⟨Nodes.height (upperNode p), Nodes.path (upperNode p)⟩ : + Σ h, Path branch N h) = ⟨n + 1, p⟩ + | _, _, .refl _ => rfl + | N + 1, _, .step j p => + congrArg (fun z : Σ h, Path branch N h => + (⟨z.1, Path.step j z.2⟩ : Σ h, Path branch (N + 1) h)) (upperNode_spec p) + +theorem upperNode_path_heq (p : Path branch N (n + 1)) : + HEq (Nodes.path (upperNode p)) p := + (Sigma.mk.inj (upperNode_spec p)).2 + +def selectedNode : {N h : Nat} → (p : Path branch N h) → 0 < h → Nodes branch N + | _, 0, _, hpos => False.elim (Nat.not_lt_zero _ hpos) + | _, _ + 1, p, _ => upperNode p + +@[simp] theorem selectedNode_succ (p : Path branch N (n + 1)) (hpos : 0 < n + 1) : + selectedNode p hpos = upperNode p := rfl + +theorem selectedNode_step {h : Nat} (j : Fin (branch N)) (p : Path branch N h) + (hpos : 0 < h) : + selectedNode (.step j p) hpos = .inr (j, selectedNode p hpos) := by + cases h with + | zero => exact False.elim (Nat.not_lt_zero _ hpos) + | succ h => rfl + +@[simp] theorem selectedNode_nodePath : + {N : Nat} → (node : Nodes branch N) → (hpos : 0 < Nodes.height node) → + selectedNode (Nodes.path node) hpos = node + | 0, node, _ => nomatch node + | _ + 1, .inl u, _ => by cases u; rfl + | N + 1, .inr (j, node), hpos => + (selectedNode_step j (Nodes.path node) hpos).trans + (congrArg (fun a : Nodes branch N => (Sum.inr (j, a) : Nodes branch (N + 1))) + (selectedNode_nodePath node hpos)) + +def upperTape (rows repeats : Nat → Nat) (i : Fin (branch n)) (q : Path branch n m) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (rest : WholeArrayHiddenLaw.RestTape rows repeats i q slots) : + Tape rows repeats (.step i q) slots := fun field => + match field with + | .inl _ => fun _ => RecursiveSampler.zeroTape F2 repeats (.step i q) (LeafDomain slots) + | .inr (.inl _) => rest ⟨.inr (.inl ()), by simp⟩ + | .inr (.inr j) => rest ⟨.inr (.inr j), by simp⟩ + +def read (rows repeats : Nat → Nat) (p : Path branch N (n + 1)) + (i : Fin (branch n)) (q : Path branch n m) + (slots : Slots branch N → Fin t → MixedSupport.Slot) + (ω : Tape rows repeats (p.append (.step i q)) slots) : + WholeArrayInteriorHiddenLaw.Exterior rows repeats p i q slots := + let subtree := splitEquiv rows repeats p (.step i q) slots ω + (subtree.1, fun field => subtree.2 field.val) + +theorem read_split (rows repeats : Nat → Nat) (p : Path branch N (n + 1)) + (i : Fin (branch n)) (q : Path branch n m) + (slots : Slots branch N → Fin t → MixedSupport.Slot) + (W : Submodule F2 (Fin (rows (n + 1)) → F2)) + (ω : Tape rows repeats (p.append (.step i q)) slots) : + (WholeArrayInteriorHiddenLaw.split rows repeats p i q slots W ω).2.2 = + read rows repeats p i q slots ω := rfl + +def rebuild (rows repeats : Nat → Nat) (p : Path branch N (n + 1)) + (i : Fin (branch n)) (q : Path branch n m) + (slots : Slots branch N → Fin t → MixedSupport.Slot) + (external : WholeArrayInteriorHiddenLaw.Exterior rows repeats p i q slots) : + Tape rows repeats (p.append (.step i q)) slots := + (splitEquiv rows repeats p (.step i q) slots).symm + (external.1, upperTape rows repeats i q (subtreeSlots p slots) external.2) + +theorem evaluate_rebuild_read (rows repeats : Nat → Nat) (p : Path branch N (n + 1)) : + ∀ {m : Nat} (i : Fin (branch n)) (q : Path branch n m) + (slots : Slots branch N → Fin t → MixedSupport.Slot) + (ω : Tape rows repeats (p.append (.step i q)) slots) + (node : Nodes branch N), node ≠ upperNode p → + WholeArraySampler.evaluate rows repeats (p.append (.step i q)) slots + (rebuild rows repeats p i q slots (read rows repeats p i q slots ω)) node = + WholeArraySampler.evaluate rows repeats (p.append (.step i q)) slots ω node := by + induction N generalizing n with + | zero => + have h := p.height_le + omega + | succ N ih => + cases p with + | refl => + intro m i q slots ω node hnode + cases node with + | inl u => + cases u + exact False.elim (hnode rfl) + | inr pair => + rcases pair with ⟨j, node⟩ + rfl + | step j p => + intro m i q slots ω node hnode + cases node with + | inl u => + cases u + rfl + | inr pair => + rcases pair with ⟨l, node⟩ + by_cases hlj : l = j + · subst l + have hchild : node ≠ upperNode p := by + intro h + exact hnode (congrArg (fun a => Sum.inr (j, a)) h) + exact (WholeArraySampler.evaluate_selected rows repeats j + (p.append (.step i q)) slots + (rebuild rows repeats (.step j p) i q slots + (read rows repeats (.step j p) i q slots ω)) node).trans + ((ih p i q (childSlots slots j) (ω (.inr (.inl ()))) node hchild).trans + (WholeArraySampler.evaluate_selected rows repeats j + (p.append (.step i q)) slots ω node).symm) + · exact (WholeArraySampler.evaluate_ordinary rows repeats j + (p.append (.step i q)) slots + (rebuild rows repeats (.step j p) i q slots + (read rows repeats (.step j p) i q slots ω)) ⟨l, hlj⟩ node).trans + (WholeArraySampler.evaluate_ordinary rows repeats j + (p.append (.step i q)) slots ω ⟨l, hlj⟩ node).symm + +theorem evaluate_rebuild_split (rows repeats : Nat → Nat) (p : Path branch N (n + 1)) + (i : Fin (branch n)) (q : Path branch n m) + (slots : Slots branch N → Fin t → MixedSupport.Slot) + (W : Submodule F2 (Fin (rows (n + 1)) → F2)) + (ω : Tape rows repeats (p.append (.step i q)) slots) + (node : Nodes branch N) (hnode : node ≠ upperNode p) : + WholeArraySampler.evaluate rows repeats (p.append (.step i q)) slots + (rebuild rows repeats p i q slots + (WholeArrayInteriorHiddenLaw.split rows repeats p i q slots W ω).2.2) node = + WholeArraySampler.evaluate rows repeats (p.append (.step i q)) slots ω node := + evaluate_rebuild_read rows repeats p i q slots ω node hnode + +abbrev NonUpper (p : Path branch N (n + 1)) := + {node : Nodes branch N // node ≠ upperNode p} + +def nodeArray (rows repeats : Nat → Nat) (p : Path branch N (n + 1)) + (i : Fin (branch n)) (q : Path branch n m) + (slots : Slots branch N → Fin t → MixedSupport.Slot) + (external : WholeArrayInteriorHiddenLaw.Exterior rows repeats p i q slots) + (node : NonUpper p) : + Fin (rows (Nodes.height node.val)) → H (nodeSlots slots node.val) := + WholeArraySampler.evaluate rows repeats (p.append (.step i q)) slots + (rebuild rows repeats p i q slots external) node.val + +theorem nodeArray_read (rows repeats : Nat → Nat) (p : Path branch N (n + 1)) + (i : Fin (branch n)) (q : Path branch n m) + (slots : Slots branch N → Fin t → MixedSupport.Slot) + (ω : Tape rows repeats (p.append (.step i q)) slots) (node : NonUpper p) : + nodeArray rows repeats p i q slots (read rows repeats p i q slots ω) node = + WholeArraySampler.evaluate rows repeats (p.append (.step i q)) slots ω node.val := + evaluate_rebuild_read rows repeats p i q slots ω node.val node.property + +theorem nodeArray_split (rows repeats : Nat → Nat) (p : Path branch N (n + 1)) + (i : Fin (branch n)) (q : Path branch n m) + (slots : Slots branch N → Fin t → MixedSupport.Slot) + (W : Submodule F2 (Fin (rows (n + 1)) → F2)) + (ω : Tape rows repeats (p.append (.step i q)) slots) (node : NonUpper p) : + nodeArray rows repeats p i q slots + (WholeArrayInteriorHiddenLaw.split rows repeats p i q slots W ω).2.2 node = + WholeArraySampler.evaluate rows repeats (p.append (.step i q)) slots ω node.val := + evaluate_rebuild_split rows repeats p i q slots W ω node.val node.property + +end +end PerfectCompleteness.WholeArrayInteriorExterior + + +namespace PerfectCompleteness.SelectedArrayReplacement + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open WholeArraySubtreeSplit WholeArrayInteriorExterior +open scoped Classical + +noncomputable section + +variable {branch : Nat → Nat} {n m t : Nat} + +def selectedRows (rows : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) (arrays : Arrays slots rows) : + Fin (rows (m + 1)) → H (subtreeSlots p slots) := + restrictArrays rows p slots arrays (.inl ()) + +def replace (rows : Nat → Nat) : + {n m : Nat} → (p : Path branch n (m + 1)) → + (slots : Slots branch n → Fin t → MixedSupport.Slot) → Arrays slots rows → + (Fin (rows (m + 1)) → H (subtreeSlots p slots)) → Arrays slots rows + | _, _, .refl _, slots, arrays, fresh => + WholeArraySampler.assemble slots rows fresh + (fun child node => arrays (.inr (child, node))) + | _, _, .step i p, slots, arrays, fresh => + WholeArraySampler.assemble slots rows (arrays (.inl ())) + (WholeArraySampler.childrenAt slots rows i + (replace rows p (childSlots slots i) (fun node => arrays (.inr (i, node))) fresh) + (fun child node => arrays (.inr (child.val, node)))) + +@[simp] theorem selectedRows_refl (rows : Nat → Nat) + (slots : Slots branch (m + 1) → Fin t → MixedSupport.Slot) (arrays : Arrays slots rows) : + selectedRows rows (.refl (m + 1)) slots arrays = arrays (.inl ()) := rfl + +@[simp] theorem selectedRows_step (rows : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n (m + 1)) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) (arrays : Arrays slots rows) : + selectedRows rows (.step i p) slots arrays = + selectedRows rows p (childSlots slots i) (fun node => arrays (.inr (i, node))) := rfl + +theorem replace_step (rows : Nat → Nat) (i : Fin (branch n)) (p : Path branch n (m + 1)) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) (arrays : Arrays slots rows) + (fresh : Fin (rows (m + 1)) → H (subtreeSlots (.step i p) slots)) : + replace rows (.step i p) slots arrays fresh = + WholeArraySampler.assemble slots rows (arrays (.inl ())) + (WholeArraySampler.childrenAt slots rows i + (replace rows p (childSlots slots i) (fun node => arrays (.inr (i, node))) fresh) + (fun child node => arrays (.inr (child.val, node)))) := rfl + +@[simp] theorem selectedRows_assemble_refl (rows : Nat → Nat) + (slots : Slots branch (m + 1) → Fin t → MixedSupport.Slot) + (root : Fin (rows (m + 1)) → H slots) + (children : ∀ child, Arrays (childSlots slots child) rows) : + selectedRows rows (.refl (m + 1)) slots + (WholeArraySampler.assemble slots rows root children) = root := rfl + +@[simp] theorem selectedRows_assemble_step (rows : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n (m + 1)) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (root : Fin (rows (n + 1)) → H slots) (selected : Arrays (childSlots slots i) rows) + (ordinary : ∀ child : RecursiveSampler.OffPath i, Arrays (childSlots slots child.val) rows) : + selectedRows rows (.step i p) slots + (WholeArraySampler.assemble slots rows root + (WholeArraySampler.childrenAt slots rows i selected ordinary)) = + selectedRows rows p (childSlots slots i) selected := by + exact congrArg (selectedRows rows p (childSlots slots i)) + (WholeArraySampler.childrenAt_selected slots rows i selected ordinary) + +@[simp] theorem replace_assemble_refl (rows : Nat → Nat) + (slots : Slots branch (m + 1) → Fin t → MixedSupport.Slot) + (root : Fin (rows (m + 1)) → H slots) + (children : ∀ child, Arrays (childSlots slots child) rows) + (fresh : Fin (rows (m + 1)) → H slots) : + replace rows (.refl (m + 1)) slots + (WholeArraySampler.assemble slots rows root children) fresh = + WholeArraySampler.assemble slots rows fresh children := rfl + +@[simp] theorem replace_assemble_step (rows : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n (m + 1)) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (root : Fin (rows (n + 1)) → H slots) (selected : Arrays (childSlots slots i) rows) + (ordinary : ∀ child : RecursiveSampler.OffPath i, Arrays (childSlots slots child.val) rows) + (fresh : Fin (rows (m + 1)) → H (subtreeSlots (.step i p) slots)) : + replace rows (.step i p) slots + (WholeArraySampler.assemble slots rows root + (WholeArraySampler.childrenAt slots rows i selected ordinary)) fresh = + WholeArraySampler.assemble slots rows root + (WholeArraySampler.childrenAt slots rows i + (replace rows p (childSlots slots i) selected fresh) ordinary) := by + simp only [replace_step, WholeArraySampler.assemble, + WholeArraySampler.childrenAt_selected, WholeArraySampler.childrenAt_ordinary] + +@[simp] theorem selectedRows_replace (rows : Nat → Nat) (p : Path branch n (m + 1)) : + ∀ (slots : Slots branch n → Fin t → MixedSupport.Slot) (arrays : Arrays slots rows) + (fresh : Fin (rows (m + 1)) → H (subtreeSlots p slots)), + selectedRows rows p slots (replace rows p slots arrays fresh) = fresh := by + induction n generalizing m with + | zero => cases p + | succ n ih => + cases p with + | refl => intro slots arrays fresh; rfl + | step i p => + intro slots arrays fresh + exact (selectedRows_assemble_step rows i p slots (arrays (.inl ())) + (replace rows p (childSlots slots i) (fun node => arrays (.inr (i, node))) fresh) + (fun child node => arrays (.inr (child.val, node)))).trans + (ih p (childSlots slots i) (fun node => arrays (.inr (i, node))) fresh) + +theorem replace_outside (rows : Nat → Nat) (p : Path branch n (m + 1)) : + ∀ (slots : Slots branch n → Fin t → MixedSupport.Slot) (arrays : Arrays slots rows) + (fresh : Fin (rows (m + 1)) → H (subtreeSlots p slots)) (node : Nodes branch n), + node ≠ upperNode p → replace rows p slots arrays fresh node = arrays node := by + induction n generalizing m with + | zero => cases p + | succ n ih => + cases p with + | refl => + intro slots arrays fresh node hnode + cases node with + | inl u => cases u; exact False.elim (hnode rfl) + | inr pair => rfl + | step i p => + intro slots arrays fresh node hnode + cases node with + | inl u => cases u; rfl + | inr pair => + rcases pair with ⟨child, node⟩ + by_cases hchild : child = i + · subst child + have hnode' : node ≠ upperNode p := by + intro h + exact hnode (congrArg (fun v => Sum.inr (i, v)) h) + exact (congrFun (WholeArraySampler.childrenAt_selected slots rows i + (replace rows p (childSlots slots i) (fun v => arrays (.inr (i, v))) fresh) + (fun j v => arrays (.inr (j.val, v)))) node).trans + (ih p (childSlots slots i) (fun v => arrays (.inr (i, v))) fresh node hnode') + · exact congrFun (WholeArraySampler.childrenAt_ordinary slots rows i + (replace rows p (childSlots slots i) (fun v => arrays (.inr (i, v))) fresh) + (fun j v => arrays (.inr (j.val, v))) ⟨child, hchild⟩) node + +@[simp] theorem replace_same (rows : Nat → Nat) (p : Path branch n (m + 1)) : + ∀ (slots : Slots branch n → Fin t → MixedSupport.Slot) (arrays : Arrays slots rows), + replace rows p slots arrays (selectedRows rows p slots arrays) = arrays := by + induction n generalizing m with + | zero => cases p + | succ n ih => + cases p with + | refl => + intro slots arrays + funext node + rcases node with u | ⟨child, node⟩ + · cases u + rfl + · rfl + | step i p => + intro slots arrays + rw [replace_step, selectedRows_step, + ih p (childSlots slots i) (fun v => arrays (.inr (i, v)))] + funext node + rcases node with u | ⟨child, node⟩ + · cases u + rfl + · by_cases hchild : child = i + · subst child + exact congrFun (WholeArraySampler.childrenAt_selected slots rows i + (fun v => arrays (.inr (i, v))) (fun j v => arrays (.inr (j.val, v)))) node + · exact congrFun (WholeArraySampler.childrenAt_ordinary slots rows i + (fun v => arrays (.inr (i, v))) (fun j v => arrays (.inr (j.val, v))) + ⟨child, hchild⟩) node + +end +end PerfectCompleteness.SelectedArrayReplacement + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/WholeArrayPositiveSplit.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/WholeArrayPositiveSplit.lean new file mode 100644 index 0000000000000000000000000000000000000000..0690aa81f3575826a306a62a2201bc7f60d07655 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/WholeArrayPositiveSplit.lean @@ -0,0 +1,146 @@ +import OAI.Computability.PerfectCompleteness.Foundations.WholeArrayInteriorExteriorLemmas +import OAI.Computability.PerfectCompleteness.Sampling.WholeArrayInteriorHiddenLaw + +namespace OAI + +section + +namespace PerfectCompleteness.WholeArrayPositiveSplit + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays WholeArraySampler +open WholeArraySubtreeSplit +open UniqueGamesTheorem.Foundations.Games +open scoped Classical + +noncomputable section + +variable {branch : Nat → Nat} {N h k t : Nat} + +abbrev ScalarTape (repeats : Nat → Nat) (p : Path branch N h) (q : Path branch h k) + (slots : Slots branch N → Fin t → MixedSupport.Slot) := + RecursiveSampler.Tape F2 repeats q (LeafDomain (subtreeSlots p slots)) + +instance scalarTapeFintype (repeats : Nat → Nat) (p : Path branch N h) + (q : Path branch h k) (slots : Slots branch N → Fin t → MixedSupport.Slot) : + Fintype (ScalarTape repeats p q slots) := by + letI : (j : RecursiveSampler.DrawIndex repeats q) → + Fintype (RecursiveSampler.DrawSpace F2 repeats q + (LeafDomain (subtreeSlots p slots)) j) := + fun j => RecursiveSampler.drawSpaceFintype F2 repeats q + (LeafDomain (subtreeSlots p slots)) j + change Fintype ((j : RecursiveSampler.DrawIndex repeats q) → + RecursiveSampler.DrawSpace F2 repeats q (LeafDomain (subtreeSlots p slots)) j) + infer_instance + +def RestTape (rows repeats : Nat → Nat) : + {h k : Nat} → (q : Path branch h k) → + (Slots branch h → Fin t → MixedSupport.Slot) → Type + | _, _, .refl _, _ => Unit + | _, _, .step i q, slots => WholeArrayHiddenLaw.RestTape rows repeats i q slots + +@[instance_reducible] def restTapeFintypeAux (rows repeats : Nat → Nat) : + {h k : Nat} → (q : Path branch h k) → + (slots : Slots branch h → Fin t → MixedSupport.Slot) → + Fintype (RestTape rows repeats q slots) + | _, _, .refl _, _ => inferInstanceAs (Fintype Unit) + | _, _, .step i q, slots => WholeArrayHiddenLaw.restTapeFintype rows repeats i q slots + +instance restTapeFintype (rows repeats : Nat → Nat) (q : Path branch h k) + (slots : Slots branch h → Fin t → MixedSupport.Slot) : + Fintype (RestTape rows repeats q slots) := + restTapeFintypeAux rows repeats q slots + +abbrev Exterior (rows repeats : Nat → Nat) (p : Path branch N h) (q : Path branch h k) + (slots : Slots branch N → Fin t → MixedSupport.Slot) := + Complement rows repeats p q slots × RestTape rows repeats q (subtreeSlots p slots) + +def scalarLaw (repeats : Nat → Nat) (p : Path branch N h) (q : Path branch h k) + (slots : Slots branch N → Fin t → MixedSupport.Slot) : + FiniteDistribution (ScalarTape repeats p q slots) := + RecursiveSampler.tapeLaw F2 repeats q (LeafDomain (subtreeSlots p slots)) + +def restLaw (rows repeats : Nat → Nat) : + {h k : Nat} → (q : Path branch h k) → + (slots : Slots branch h → Fin t → MixedSupport.Slot) → + FiniteDistribution (RestTape rows repeats q slots) + | _, _, .refl _, _ => FiniteDistribution.uniform Unit + | _, _, .step i q, slots => WholeArrayHiddenLaw.restLaw rows repeats i q slots + +def exteriorLaw (rows repeats : Nat → Nat) (p : Path branch N h) (q : Path branch h k) + (slots : Slots branch N → Fin t → MixedSupport.Slot) : + FiniteDistribution (Exterior rows repeats p q slots) := + (complementLaw rows repeats p q slots).product + (restLaw rows repeats q (subtreeSlots p slots)) + +def split (rows repeats : Nat → Nat) (p : Path branch N h) (q : Path branch h k) + (hproper : k < h) (slots : Slots branch N → Fin t → MixedSupport.Slot) + (W : Submodule F2 (Fin (rows h) → F2)) + (ω : Tape rows repeats (p.append q) slots) : + HiddenBucketBias.HiddenTape W (ScalarTape repeats p q slots) × + (HiddenBucketBias.VisibleTape W (ScalarTape repeats p q slots) × + Exterior rows repeats p q slots) := by + cases q with + | refl => exact False.elim ((Nat.lt_irrefl _) hproper) + | step i q => exact WholeArrayInteriorHiddenLaw.split rows repeats p i q slots W ω + +theorem split_law (rows repeats : Nat → Nat) (p : Path branch N h) (q : Path branch h k) + (hproper : k < h) (slots : Slots branch N → Fin t → MixedSupport.Slot) + (W : Submodule F2 (Fin (rows h) → F2)) : + (WholeArraySampler.tapeLaw rows repeats (p.append q) slots).pushforward + (split rows repeats p q hproper slots W) = + (HiddenBucketBias.hiddenTapeLaw W (scalarLaw repeats p q slots)).product + ((HiddenBucketBias.visibleTapeLaw W (scalarLaw repeats p q slots)).product + (exteriorLaw rows repeats p q slots)) := by + cases q with + | refl => exact False.elim ((Nat.lt_irrefl _) hproper) + | step i q => exact WholeArrayInteriorHiddenLaw.split_law rows repeats p i q slots W + +theorem split_readout_law {E : Type*} [Fintype E] + (rows repeats : Nat → Nat) (p : Path branch N h) (q : Path branch h k) + (hproper : k < h) (slots : Slots branch N → Fin t → MixedSupport.Slot) + (W : Submodule F2 (Fin (rows h) → F2)) + (read : Exterior rows repeats p q slots → E) : + (WholeArraySampler.tapeLaw rows repeats (p.append q) slots).pushforward + (fun ω => ((split rows repeats p q hproper slots W ω).1, + ((split rows repeats p q hproper slots W ω).2.1, + read (split rows repeats p q hproper slots W ω).2.2))) = + HiddenBucketBias.exposedLaw W (scalarLaw repeats p q slots) + ((exteriorLaw rows repeats p q slots).pushforward read) := by + cases q with + | refl => exact False.elim ((Nat.lt_irrefl _) hproper) + | step i q => + exact WholeArrayInteriorHiddenLaw.split_readout_law rows repeats p i q slots W read + +def nodeArray (rows repeats : Nat → Nat) (p : Path branch N h) (q : Path branch h k) + (hproper : k < h) (slots : Slots branch N → Fin t → MixedSupport.Slot) + (external : Exterior rows repeats p q slots) (node : Nodes branch N) + (hnode : node ≠ WholeArrayInteriorExterior.selectedNode p + (Nat.zero_lt_of_lt hproper)) : + Fin (rows (Nodes.height node)) → H (nodeSlots slots node) := by + cases q with + | refl => exact False.elim ((Nat.lt_irrefl _) hproper) + | step i q => + exact WholeArrayInteriorExterior.nodeArray rows repeats p i q slots external ⟨node, hnode⟩ + +theorem nodeArray_split (rows repeats : Nat → Nat) (p : Path branch N h) + (q : Path branch h k) (hproper : k < h) + (slots : Slots branch N → Fin t → MixedSupport.Slot) + (W : Submodule F2 (Fin (rows h) → F2)) + (ω : Tape rows repeats (p.append q) slots) (node : Nodes branch N) + (hnode : node ≠ WholeArrayInteriorExterior.selectedNode p + (Nat.zero_lt_of_lt hproper)) : + nodeArray rows repeats p q hproper slots + (split rows repeats p q hproper slots W ω).2.2 node hnode = + WholeArraySampler.evaluate rows repeats (p.append q) slots ω node := by + cases q with + | refl => exact False.elim ((Nat.lt_irrefl _) hproper) + | step i q => + exact WholeArrayInteriorExterior.nodeArray_split rows repeats p i q slots W ω + ⟨node, hnode⟩ + +end +end PerfectCompleteness.WholeArrayPositiveSplit + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/WholeArrayRawAssembly.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/WholeArrayRawAssembly.lean new file mode 100644 index 0000000000000000000000000000000000000000..a85a9835d22ede841fe34b8416656e02e8d525cd --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/WholeArrayRawAssembly.lean @@ -0,0 +1,187 @@ +import OAI.Computability.PerfectCompleteness.Machines.OwnInputAffineSliceLemmas +import OAI.Computability.PerfectCompleteness.Machines.WholeArrayInteriorOwnInputLaw + +namespace OAI + +section + +namespace PerfectCompleteness.WholeArrayRawAssembly + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open WholeArrayInteriorOwnInputLaw (fullPath exposedRead exteriorLaw) + +variable {branch : Nat → Nat} {N h k t : Nat} + +private def mergedBuckets (rows repeats : Nat → Nat) + (p : Path branch N h) (q : Path branch h k) (hproper : k < h) + (slots : Slots branch N → Fin t → MixedSupport.Slot) + (W : Submodule F2 (Fin (rows h) → F2)) + (ω : WholeArraySampler.Tape rows repeats (p.append q) slots) : + BucketSampler.Tape (rows h) (WholeArrayPositiveSplit.ScalarTape repeats p q slots) := + let parts := WholeArrayPositiveSplit.split rows repeats p q hproper slots W ω + (HiddenBucketBias.splitTape W _).symm (parts.1, parts.2.1) + +private theorem mergedBuckets_step (rows repeats : Nat → Nat) + (j : Fin (branch N)) (p : Path branch N h) (q : Path branch h k) + (hproper : k < h) + (slots : Slots branch (N + 1) → Fin t → MixedSupport.Slot) + (W : Submodule F2 (Fin (rows h) → F2)) + (ω : WholeArraySampler.Tape rows repeats ((Path.step j p).append q) slots) : + mergedBuckets rows repeats (.step j p) q hproper slots W ω = + mergedBuckets rows repeats p q hproper (childSlots slots j) + W (ω (.inr (.inl ()))) := by + cases q with + | refl => exact False.elim ((Nat.lt_irrefl _) hproper) + | step i q => rfl + +private theorem upper_rows_split (rows repeats : Nat → Nat) : + ∀ {N k : Nat} (upper : Nodes branch N) + (q : Path branch (Nodes.height upper) k) (hproper : k < Nodes.height upper) + (slots : Slots branch N → Fin t → MixedSupport.Slot) + (W : Submodule F2 (Block rows upper)) + (ω : WholeArraySampler.Tape rows repeats ((Nodes.path upper).append q) slots), + BucketSampler.evaluate (rows (Nodes.height upper)) + (RecursiveSampler.evaluate F2 repeats q (LeafDomain (nodeSlots slots upper))) + (mergedBuckets rows repeats (Nodes.path upper) q hproper slots W ω) = + WholeArraySampler.evaluate rows repeats ((Nodes.path upper).append q) slots ω upper := by + intro N + induction N with + | zero => intro k upper; exact nomatch upper + | succ N ih => + intro k upper q hproper slots W ω + cases upper with + | inl u => + cases u + cases q with + | refl => exact False.elim ((Nat.lt_irrefl _) hproper) + | step i q => + change BucketSampler.evaluate (rows (N + 1)) + (RecursiveSampler.evaluate F2 repeats (.step i q) (LeafDomain slots)) + ((HiddenBucketBias.splitTape W _).symm + (HiddenBucketBias.splitTape W _ (ω (.inl ())))) = + BucketSampler.evaluate (rows (N + 1)) + (RecursiveSampler.evaluate F2 repeats (.step i q) (LeafDomain slots)) + (ω (.inl ())) + exact congrArg + (BucketSampler.evaluate (rows (N + 1)) + (RecursiveSampler.evaluate F2 repeats (.step i q) (LeafDomain slots))) + ((HiddenBucketBias.splitTape W _).symm_apply_apply (ω (.inl ()))) + | inr pair => + rcases pair with ⟨j, upper⟩ + change BucketSampler.evaluate (rows (Nodes.height upper)) + (RecursiveSampler.evaluate F2 repeats q + (LeafDomain (nodeSlots (childSlots slots j) upper))) + (mergedBuckets rows repeats (.step j (Nodes.path upper)) q hproper slots W ω) = + WholeArraySampler.evaluate rows repeats (.step j ((Nodes.path upper).append q)) + slots ω (.inr (j, upper)) + exact (congrArg + (BucketSampler.evaluate (rows (Nodes.height upper)) + (RecursiveSampler.evaluate F2 repeats q + (LeafDomain (nodeSlots (childSlots slots j) upper)))) + (mergedBuckets_step rows repeats j (Nodes.path upper) q hproper slots W ω)).trans + ((ih upper q hproper (childSlots slots j) W (ω (.inr (.inl ())))).trans + (WholeArraySampler.evaluate_selected rows repeats j + ((Nodes.path upper).append q) slots ω upper).symm) + +variable (rows repeats : Nat → Nat) + (slots : Slots branch N → Fin t → MixedSupport.Slot) + (upper lower : Nodes branch N) (cut : OwnInputReference.Cut upper lower) + (W : Submodule F2 (Block rows upper)) + +theorem arrays_exposedRead + (ω : WholeArraySampler.Tape rows repeats (fullPath upper lower cut) slots) : + OwnInputRawAssembly.arrays slots rows upper lower W repeats cut + (exposedRead rows repeats slots upper lower cut W ω) = + WholeArraySampler.evaluate rows repeats (fullPath upper lower cut) slots ω := by + have hupper := upper_rows_split rows repeats upper cut.path cut.proper slots W ω + change OwnInputCanonicalQuery.assemble slots rows upper lower + (BucketSampler.evaluate (rows (Nodes.height upper)) + (RecursiveSampler.evaluate F2 repeats cut.path (LeafDomain (nodeSlots slots upper))) + (mergedBuckets rows repeats (Nodes.path upper) cut.path cut.proper slots W ω)) + (OwnInputCanonicalQuery.exteriorOf slots rows upper lower + (WholeArraySampler.evaluate rows repeats (fullPath upper lower cut) slots ω)) = _ + rw [hupper] + exact OwnInputCanonicalQuery.assemble_original slots rows upper lower _ + +theorem arrays_law : + (OwnInputReference.rawLaw slots rows upper lower W repeats cut + (exteriorLaw rows repeats slots upper lower cut)).pushforward (Γ := Arrays slots rows) + (OwnInputRawAssembly.arrays slots rows upper lower W repeats cut) = + WholeArraySampler.law rows repeats (fullPath upper lower cut) slots := by + have h := congrArg + (fun μ : FiniteDistribution (OwnInputReference.RawSample slots rows upper lower W repeats cut) => + μ.pushforward (Γ := Arrays slots rows) + (OwnInputRawAssembly.arrays slots rows upper lower W repeats cut)) + (WholeArrayInteriorOwnInputLaw.exposedRead_law rows repeats slots upper lower cut W) + rw [FiniteDistribution.pushforward_comp] at h + have hmap : (fun ω => OwnInputRawAssembly.arrays slots rows upper lower W repeats cut + (exposedRead rows repeats slots upper lower cut W ω)) = + WholeArraySampler.evaluate rows repeats (fullPath upper lower cut) slots := + funext (arrays_exposedRead rows repeats slots upper lower cut W) + rw [hmap] at h + exact h.symm + +theorem joint_readout_law {R : Type*} [Fintype R] + (read : OwnInputReference.RawSample slots rows upper lower W repeats cut → R) : + (WholeArraySampler.tapeLaw rows repeats (fullPath upper lower cut) slots).pushforward + (Γ := Arrays slots rows × R) + (fun ω => (WholeArraySampler.evaluate rows repeats (fullPath upper lower cut) slots ω, + read (exposedRead rows repeats slots upper lower cut W ω))) = + (OwnInputReference.rawLaw slots rows upper lower W repeats cut + (exteriorLaw rows repeats slots upper lower cut)).pushforward + (Γ := Arrays slots rows × R) + (fun sample => (OwnInputRawAssembly.arrays slots rows upper lower W repeats cut sample, + read sample)) := by + have h := congrArg + (fun μ : FiniteDistribution (OwnInputReference.RawSample slots rows upper lower W repeats cut) => + μ.pushforward (Γ := Arrays slots rows × R) + (fun sample => (OwnInputRawAssembly.arrays slots rows upper lower W repeats cut sample, + read sample))) + (WholeArrayInteriorOwnInputLaw.exposedRead_law rows repeats slots upper lower cut W) + rw [FiniteDistribution.pushforward_comp] at h + simpa only [arrays_exposedRead] using h + +theorem raw_probability + (event : OwnInputReference.RawSample slots rows upper lower W repeats cut → Bool) : + (WholeArraySampler.tapeLaw rows repeats (fullPath upper lower cut) slots).probability + (fun ω => event (exposedRead rows repeats slots upper lower cut W ω)) = + (OwnInputReference.rawLaw slots rows upper lower W repeats cut + (exteriorLaw rows repeats slots upper lower cut)).probability event := by + have h := congrArg (fun μ => FiniteDistribution.probability μ event) + (WholeArrayInteriorOwnInputLaw.exposedRead_law rows repeats slots upper lower cut W) + exact (FiniteDistribution.probability_pushforward _ _ event).symm.trans h + +theorem raw_expectation + (statistic : OwnInputReference.RawSample slots rows upper lower W repeats cut → ℝ) : + (WholeArraySampler.tapeLaw rows repeats (fullPath upper lower cut) slots).expectation + (fun ω => statistic (exposedRead rows repeats slots upper lower cut W ω)) = + (OwnInputReference.rawLaw slots rows upper lower W repeats cut + (exteriorLaw rows repeats slots upper lower cut)).expectation statistic := by + have h := congrArg (fun μ => FiniteDistribution.expectation μ statistic) + (WholeArrayInteriorOwnInputLaw.exposedRead_law rows repeats slots upper lower cut W) + exact (FiniteDistribution.expectation_pushforward _ _ statistic).symm.trans h + +theorem joint_expectation + (statistic : Arrays slots rows → + OwnInputReference.RawSample slots rows upper lower W repeats cut → ℝ) : + (WholeArraySampler.tapeLaw rows repeats (fullPath upper lower cut) slots).expectation + (fun ω => statistic + (WholeArraySampler.evaluate rows repeats (fullPath upper lower cut) slots ω) + (exposedRead rows repeats slots upper lower cut W ω)) = + (OwnInputReference.rawLaw slots rows upper lower W repeats cut + (exteriorLaw rows repeats slots upper lower cut)).expectation + (fun sample => statistic + (OwnInputRawAssembly.arrays slots rows upper lower W repeats cut sample) sample) := by + simpa only [arrays_exposedRead] using raw_expectation rows repeats slots upper lower cut W + (fun sample => statistic (OwnInputRawAssembly.arrays slots rows upper lower W repeats cut sample) sample) + +end +end PerfectCompleteness.WholeArrayRawAssembly + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/WholeArraySubtreeSplit.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/WholeArraySubtreeSplit.lean new file mode 100644 index 0000000000000000000000000000000000000000..278cbbaa4a20908276221b09fcb0e110cb93a8f6 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/WholeArraySubtreeSplit.lean @@ -0,0 +1,286 @@ +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalFrozenTablesLemmas +import OAI.Computability.PerfectCompleteness.Sampling.RationalFiniteLawLemmas +import OAI.Computability.PerfectCompleteness.Sampling.WholeArraySampler +import OAI.Computability.UniqueGames.Foundations.SamplingLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.WholeArraySubtreeSplit + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays WholeArraySampler +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +noncomputable section + +variable {branch : Nat → Nat} {n m k t : Nat} + +abbrev subtreeSlots (p : Path branch n m) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Slots branch m → Fin t → MixedSupport.Slot := + fun s => slots (p.slotEmbedding s) + +def Complement (rows repeats : Nat → Nat) : + {n m k : Nat} → (p : Path branch n m) → (q : Path branch m k) → + (Slots branch n → Fin t → MixedSupport.Slot) → Type + | _, _, _, .refl _, _, _ => Unit + | _, _, _, .step i p, q, slots => + RootTape rows repeats (.step i (p.append q)) slots × + (((j : RecursiveSampler.OffPath i) → Arrays (childSlots slots j.val) rows) × + Complement rows repeats p q (childSlots slots i)) + +@[instance_reducible] def complementFintypeAux (rows repeats : Nat → Nat) : + {n m k : Nat} → (p : Path branch n m) → (q : Path branch m k) → + (slots : Slots branch n → Fin t → MixedSupport.Slot) → + Fintype (Complement rows repeats p q slots) + | _, _, _, .refl _, _, _ => inferInstanceAs (Fintype Unit) + | _, _, _, .step i p, q, slots => + letI := complementFintypeAux rows repeats p q (childSlots slots i) + inferInstanceAs (Fintype + (RootTape rows repeats (.step i (p.append q)) slots × + (((j : RecursiveSampler.OffPath i) → Arrays (childSlots slots j.val) rows) × + Complement rows repeats p q (childSlots slots i)))) + +instance complementFintype (rows repeats : Nat → Nat) + (p : Path branch n m) (q : Path branch m k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Fintype (Complement rows repeats p q slots) := + complementFintypeAux rows repeats p q slots + +theorem complementNonemptyAux (rows repeats : Nat → Nat) : + {n m k : Nat} → (p : Path branch n m) → (q : Path branch m k) → + (slots : Slots branch n → Fin t → MixedSupport.Slot) → + Nonempty (Complement rows repeats p q slots) + | _, _, _, .refl _, _, _ => inferInstanceAs (Nonempty Unit) + | _, _, _, .step i p, q, slots => + let := complementNonemptyAux rows repeats p q (childSlots slots i) + inferInstanceAs (Nonempty + (RootTape rows repeats (.step i (p.append q)) slots × + (((j : RecursiveSampler.OffPath i) → Arrays (childSlots slots j.val) rows) × + Complement rows repeats p q (childSlots slots i)))) + +instance complementNonempty (rows repeats : Nat → Nat) + (p : Path branch n m) (q : Path branch m k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Nonempty (Complement rows repeats p q slots) := + complementNonemptyAux rows repeats p q slots + +def splitEquiv (rows repeats : Nat → Nat) : + {n m k : Nat} → (p : Path branch n m) → (q : Path branch m k) → + (slots : Slots branch n → Fin t → MixedSupport.Slot) → + Tape rows repeats (p.append q) slots ≃ + Complement rows repeats p q slots × Tape rows repeats q (subtreeSlots p slots) + | _, _, _, .refl _, _, _ => + { toFun := fun ω => ((), ω) + invFun := Prod.snd + left_inv := fun _ => rfl + right_inv := by rintro ⟨u, ω⟩; cases u; rfl } + | _, _, _, .step i p, q, slots => + let e := splitEquiv rows repeats p q (childSlots slots i) + { toFun := fun ω => + ((ω (.inl ()), (fun j => ω (.inr (.inr j)), + (e (ω (.inr (.inl ())))).1)), + (e (ω (.inr (.inl ())))).2) + invFun := fun x field => match field with + | .inl _ => x.1.1 + | .inr (.inl _) => e.symm (x.1.2.2, x.2) + | .inr (.inr j) => x.1.2.1 j + left_inv := by + intro ω + funext field + rcases field with u | (u | j) + · cases u + rfl + · cases u + exact e.symm_apply_apply (ω (.inr (.inl ()))) + · rfl + right_inv := by + rintro ⟨⟨root, ordinary, lower⟩, selected⟩ + change ((root, (ordinary, (e (e.symm (lower, selected))).1)), + (e (e.symm (lower, selected))).2) = ((root, (ordinary, lower)), selected) + rw [e.apply_symm_apply] + rfl } + +def extract (rows repeats : Nat → Nat) (p : Path branch n m) (q : Path branch m k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (ω : Tape rows repeats (p.append q) slots) : + Tape rows repeats q (subtreeSlots p slots) := + (splitEquiv rows repeats p q slots ω).2 + +@[simp] theorem extract_refl (rows repeats : Nat → Nat) (q : Path branch n k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (ω : Tape rows repeats q slots) : + extract rows repeats (.refl n) q slots ω = ω := rfl + +@[simp] theorem extract_step (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) (q : Path branch m k) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ω : Tape rows repeats ((Path.step i p).append q) slots) : + extract rows repeats (.step i p) q slots ω = + extract rows repeats p q (childSlots slots i) (ω (.inr (.inl ()))) := rfl + +def restrictArrays (rows : Nat → Nat) : + {n m : Nat} → (p : Path branch n m) → + (slots : Slots branch n → Fin t → MixedSupport.Slot) → + Arrays slots rows → Arrays (subtreeSlots p slots) rows + | _, _, .refl _, _, arrays => arrays + | _, _, .step i p, slots, arrays => + restrictArrays rows p (childSlots slots i) (fun node => arrays (.inr (i, node))) + +theorem restrictArrays_evaluate (rows repeats : Nat → Nat) (p : Path branch n m) : + ∀ {k : Nat} (q : Path branch m k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (ω : Tape rows repeats (p.append q) slots), + restrictArrays rows p slots (evaluate rows repeats (p.append q) slots ω) = + evaluate rows repeats q (subtreeSlots p slots) (extract rows repeats p q slots ω) := by + induction p with + | refl n => intro k q slots ω; rfl + | @step n m i p ih => + intro k q slots ω + have hselected := funext (WholeArraySampler.evaluate_selected + rows repeats i (p.append q) slots ω) + exact (congrArg (restrictArrays rows p (childSlots slots i)) hselected).trans + (ih q (childSlots slots i) (ω (.inr (.inl ())))) + +def complementLaw (rows repeats : Nat → Nat) : + {n m k : Nat} → (p : Path branch n m) → (q : Path branch m k) → + (slots : Slots branch n → Fin t → MixedSupport.Slot) → + FiniteDistribution (Complement rows repeats p q slots) + | _, _, _, .refl _, _, _ => FiniteDistribution.uniform Unit + | n + 1, _, _, .step i p, q, slots => + (BucketSampler.recursiveTapeLaw (rows (n + 1)) repeats (.step i (p.append q)) + (LeafDomain slots)).product + ((FiniteProduct.law (fun j : RecursiveSampler.OffPath i => + FiniteDistribution.uniform (Arrays (childSlots slots j.val) rows))).product + (complementLaw rows repeats p q (childSlots slots i))) + +private theorem uniform_product {A B : Type*} [Fintype A] [Fintype B] + [Nonempty A] [Nonempty B] : + (FiniteDistribution.uniform A).product (FiniteDistribution.uniform B) = + FiniteDistribution.uniform (A × B) := by + apply FiniteDistribution.eq_of_weight_eq + intro x + simp only [FiniteDistribution.product, FiniteDistribution.uniform, + Fintype.card_prod, Nat.cast_mul, one_div_mul_one_div] + +private theorem uniform_pushforward_equiv {A B : Type*} + [Fintype A] [Fintype B] [Nonempty A] [Nonempty B] (e : A ≃ B) : + (FiniteDistribution.uniform A).pushforward e = FiniteDistribution.uniform B := by + rw [FiniteDistribution.pushforward_equiv] + apply FiniteDistribution.eq_of_weight_eq + intro x + change 1 / (Fintype.card A : ℝ) = 1 / (Fintype.card B : ℝ) + rw [Fintype.card_congr e] + +theorem rootTapeLaw_eq_uniform (rows repeats : Nat → Nat) (p : Path branch n m) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + BucketSampler.recursiveTapeLaw (rows n) repeats p (LeafDomain slots) = + FiniteDistribution.uniform (RootTape rows repeats p slots) := by + change FiniteProduct.law (fun _ : BucketSampler.Direction (rows n) => + RecursiveSampler.tapeLaw F2 repeats p (LeafDomain slots)) = _ + simp only [RecursiveSampler.tapeLaw_eq_uniform] + exact UniformLinearImage.law_uniform + +local instance stepFactorNonempty {i : Fin (branch n)} (Root Selected : Type) + (Ordinary : RecursiveSampler.OffPath i → Type) + [Nonempty Root] [Nonempty Selected] [∀ j, Nonempty (Ordinary j)] + (field : StepIndex i) : Nonempty (StepFactor Root Selected Ordinary field) := by + rcases field with _ | (_ | j) <;> dsimp only [StepFactor] <;> infer_instance + +theorem tapeLaw_eq_uniform (rows repeats : Nat → Nat) (p : Path branch n m) : + ∀ slots : Slots branch n → Fin t → MixedSupport.Slot, + WholeArraySampler.tapeLaw rows repeats p slots = + FiniteDistribution.uniform (Tape rows repeats p slots) := by + induction p with + | refl n => intro slots; rfl + | @step n m i p ih => + intro slots + let : (field : StepIndex i) → Fintype + (StepFactor (RootTape rows repeats (.step i p) slots) + (Tape rows repeats p (childSlots slots i)) + (fun j => Arrays (childSlots slots j.val) rows) field) := + fun field => stepFactorFintype _ _ _ field + have hcomponent : componentLaw rows repeats i p slots = + (fun field : StepIndex i => FiniteDistribution.uniform + (StepFactor (RootTape rows repeats (.step i p) slots) + (Tape rows repeats p (childSlots slots i)) + (fun j => Arrays (childSlots slots j.val) rows) field)) := by + funext field + rcases field with u | (u | j) + · cases u + exact rootTapeLaw_eq_uniform rows repeats (.step i p) slots + · cases u + exact ih (childSlots slots i) + · rfl + change FiniteProduct.law (componentLaw rows repeats i p slots) = _ + rw [hcomponent] + exact UniformLinearImage.law_uniform + +theorem complementLaw_eq_uniform (rows repeats : Nat → Nat) (p : Path branch n m) : + ∀ {k : Nat} (q : Path branch m k) + (slots : Slots branch n → Fin t → MixedSupport.Slot), + complementLaw rows repeats p q slots = + FiniteDistribution.uniform (Complement rows repeats p q slots) := by + induction p with + | refl n => intro k q slots; rfl + | @step n m i p ih => + intro k q slots + change (BucketSampler.recursiveTapeLaw (rows (n + 1)) repeats (.step i (p.append q)) + (LeafDomain slots)).product + ((FiniteProduct.law (fun j : RecursiveSampler.OffPath i => + FiniteDistribution.uniform (Arrays (childSlots slots j.val) rows))).product + (complementLaw rows repeats p q (childSlots slots i))) = + FiniteDistribution.uniform + (RootTape rows repeats (.step i (p.append q)) slots × + (((j : RecursiveSampler.OffPath i) → Arrays (childSlots slots j.val) rows) × + Complement rows repeats p q (childSlots slots i))) + rw [rootTapeLaw_eq_uniform rows repeats (.step i (p.append q)) slots, + UniformLinearImage.law_uniform, ih q (childSlots slots i)] + rw [uniform_product + (A := (j : RecursiveSampler.OffPath i) → Arrays (childSlots slots j.val) rows) + (B := Complement rows repeats p q (childSlots slots i)), uniform_product] + +theorem splitEquiv_tapeLaw (rows repeats : Nat → Nat) (p : Path branch n m) + (q : Path branch m k) (slots : Slots branch n → Fin t → MixedSupport.Slot) : + (WholeArraySampler.tapeLaw rows repeats (p.append q) slots).pushforward + (splitEquiv rows repeats p q slots) = + (complementLaw rows repeats p q slots).product + (WholeArraySampler.tapeLaw rows repeats q (subtreeSlots p slots)) := by + rw [tapeLaw_eq_uniform, uniform_pushforward_equiv, complementLaw_eq_uniform, + tapeLaw_eq_uniform] + exact uniform_product.symm + +theorem extract_tapeLaw (rows repeats : Nat → Nat) (p : Path branch n m) + (q : Path branch m k) (slots : Slots branch n → Fin t → MixedSupport.Slot) : + (WholeArraySampler.tapeLaw rows repeats (p.append q) slots).pushforward + (extract rows repeats p q slots) = + WholeArraySampler.tapeLaw rows repeats q (subtreeSlots p slots) := by + change (WholeArraySampler.tapeLaw rows repeats (p.append q) slots).pushforward + (fun ω => (splitEquiv rows repeats p q slots ω).2) = _ + rw [← FiniteDistribution.pushforward_comp, splitEquiv_tapeLaw, + FiniteDistribution.product_pushforward_snd] + +theorem restrictArrays_law (rows repeats : Nat → Nat) (p : Path branch n m) + (q : Path branch m k) (slots : Slots branch n → Fin t → MixedSupport.Slot) : + (WholeArraySampler.law rows repeats (p.append q) slots).pushforward + (restrictArrays rows p slots) = + WholeArraySampler.law rows repeats q (subtreeSlots p slots) := by + unfold WholeArraySampler.law + rw [FiniteDistribution.pushforward_comp] + have hfun : + (fun ω : Tape rows repeats (p.append q) slots => + restrictArrays rows p slots (evaluate rows repeats (p.append q) slots ω)) = + (fun ω => evaluate rows repeats q (subtreeSlots p slots) + (extract rows repeats p q slots ω)) := by + funext ω + exact restrictArrays_evaluate rows repeats p q slots ω + rw [hfun, ← FiniteDistribution.pushforward_comp, extract_tapeLaw] + +end +end PerfectCompleteness.WholeArraySubtreeSplit + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/WholeCutCallsLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/WholeCutCallsLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..3df19de1ab71f430b698df34873e0744fdd294bd --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/WholeCutCallsLemmas.lean @@ -0,0 +1,214 @@ +import OAI.Computability.PerfectCompleteness.Foundations.TerminalCalls +import OAI.Computability.PerfectCompleteness.Sampling.BucketSampler + +namespace OAI + + +namespace PerfectCompleteness.WholeCutCalls + +open RecursiveSpaces DescendantSpaces TerminalCalls +open scoped BigOperators Classical + +noncomputable section + +variable {branch : Nat → Nat} {n m : Nat} + +def Index (rows repeats : Nat → Nat) : {n m : Nat} → Path branch n m → Type + | m, _, .refl _ => Fin (rows m) + | n + 1, _, .step i p => + (BucketSampler.Direction (rows (n + 1)) × TerminalIndex repeats (.step i p)) ⊕ + Index rows repeats p + +instance indexFintype (rows repeats : Nat → Nat) (p : Path branch n m) : + Fintype (Index rows repeats p) := by + induction p with + | refl m => exact inferInstanceAs (Fintype (Fin (rows m))) + | @step n m i p ih => + letI : Fintype (Index rows repeats p) := ih + exact inferInstanceAs (Fintype + ((BucketSampler.Direction (rows (n + 1)) × TerminalIndex repeats (.step i p)) ⊕ + Index rows repeats p)) + +def directRow (rows repeats : Nat → Nat) : {n m : Nat} → (p : Path branch n m) → + Fin (rows m) → Index rows repeats p + | _, _, .refl _, q => q + | _, _, .step _ p, q => Sum.inr (directRow rows repeats p q) + +theorem directRow_injective (rows repeats : Nat → Nat) (p : Path branch n m) : + Function.Injective (directRow rows repeats p) := by + induction p with + | refl m => exact fun _ _ h => h + | step i p ih => + intro a b h + exact ih (Sum.inr.inj h) + +theorem root_ne_lower (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) + (root : BucketSampler.Direction (rows (n + 1)) × TerminalIndex repeats (.step i p)) + (lower : Index rows repeats p) : + (Sum.inl root : Index rows repeats (.step i p)) ≠ Sum.inr lower := by + intro h + cases h + +theorem direction_card (ℓ : Nat) : + Fintype.card (BucketSampler.Direction ℓ) = 2 ^ ℓ - 1 := by + have h : 2 ^ ℓ = 1 + Fintype.card (BucketSampler.Direction ℓ) := by + simpa [BucketSampler.Direction, BucketSampler.F2] using + Fintype.sum_eq_add_sum_subtype_ne (fun _ : Fin ℓ → BucketSampler.F2 => (1 : Nat)) 0 + omega + +@[simp] theorem card_refl (rows repeats : Nat → Nat) : + Fintype.card (Index (branch := branch) rows repeats (.refl m)) = rows m := by + exact Fintype.card_fin (rows m) + +theorem card_step (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) : + Fintype.card (Index rows repeats (.step i p)) = + (2 ^ rows (n + 1) - 1) * Fintype.card (TerminalIndex repeats (.step i p)) + + Fintype.card (Index rows repeats p) := by + change Fintype.card + ((BucketSampler.Direction (rows (n + 1)) × TerminalIndex repeats (.step i p)) ⊕ + Index rows repeats p) = _ + rw [Fintype.card_sum, Fintype.card_prod, direction_card] + +theorem card_eq_formula (rows repeats : Nat → Nat) (p : Path branch n m) : + Fintype.card (Index rows repeats p) = rows m + + ∑ h ∈ Finset.Ioc m n, (2 ^ rows h - 1) * + ∏ k ∈ Finset.Ioc m h, 2 * repeats k := by + induction p with + | refl m => simp only [card_refl, Finset.Ioc_self, Finset.sum_empty, Nat.add_zero] + | @step n m i p ih => + rw [card_step, TerminalCalls.card_eq_prod, ih, + Finset.sum_Ioc_succ_top p.height_le] + omega + +end +end PerfectCompleteness.WholeCutCalls + + + +namespace PerfectCompleteness.OriginalCutCalls + +open RecursiveSpaces DescendantSpaces TerminalCalls +open scoped BigOperators Classical + +noncomputable section + +variable {branch : Nat → Nat} {n m : Nat} + +def Index (rows repeats : Nat → Nat) : {n m : Nat} → Path branch n m → Type + | m, _, .refl _ => BucketSampler.Direction (rows m) + | n + 1, _, .step i p => + (BucketSampler.Direction (rows (n + 1)) × TerminalIndex repeats (.step i p)) ⊕ + Index rows repeats p + +instance indexFintype (rows repeats : Nat → Nat) (p : Path branch n m) : + Fintype (Index rows repeats p) := by + induction p with + | refl m => exact inferInstanceAs (Fintype (BucketSampler.Direction (rows m))) + | @step n m i p ih => + letI : Fintype (Index rows repeats p) := ih + exact inferInstanceAs (Fintype + ((BucketSampler.Direction (rows (n + 1)) × TerminalIndex repeats (.step i p)) ⊕ + Index rows repeats p)) + +def ownBucket (rows repeats : Nat → Nat) : {n m : Nat} → (p : Path branch n m) → + BucketSampler.Direction (rows m) → Index rows repeats p + | _, _, .refl _, v => v + | _, _, .step _ p, v => Sum.inr (ownBucket rows repeats p v) + +theorem ownBucket_injective (rows repeats : Nat → Nat) (p : Path branch n m) : + Function.Injective (ownBucket rows repeats p) := by + induction p with + | refl m => exact fun _ _ h => h + | step i p ih => + intro a b h + exact ih (Sum.inr.inj h) + +def rootCall (rows repeats : Nat → Nat) (i : Fin (branch n)) (p : Path branch n m) + (origin : BucketSampler.Direction (rows (n + 1)) × TerminalIndex repeats (.step i p)) : + Index rows repeats (.step i p) := Sum.inl origin + +def lowerCall (rows repeats : Nat → Nat) (i : Fin (branch n)) (p : Path branch n m) + (origin : Index rows repeats p) : Index rows repeats (.step i p) := Sum.inr origin + +theorem rootCall_injective (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) : Function.Injective (rootCall rows repeats i p) := by + intro a b h + exact Sum.inl.inj h + +theorem lowerCall_injective (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) : Function.Injective (lowerCall rows repeats i p) := by + intro a b h + exact Sum.inr.inj h + +theorem root_ne_lower (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) + (root : BucketSampler.Direction (rows (n + 1)) × TerminalIndex repeats (.step i p)) + (lower : Index rows repeats p) : + rootCall rows repeats i p root ≠ lowerCall rows repeats i p lower := by + intro h + cases h + +theorem root_ne_ownBucket (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) + (root : BucketSampler.Direction (rows (n + 1)) × TerminalIndex repeats (.step i p)) + (own : BucketSampler.Direction (rows m)) : + rootCall rows repeats i p root ≠ ownBucket rows repeats (.step i p) own := + root_ne_lower rows repeats i p root (ownBucket rows repeats p own) + +theorem rootCall_mk_eq_iff (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) (v w : BucketSampler.Direction (rows (n + 1))) + (a b : TerminalIndex repeats (.step i p)) : + rootCall rows repeats i p (v, a) = rootCall rows repeats i p (w, b) ↔ + v = w ∧ a = b := by + constructor + · intro h + have hp := rootCall_injective rows repeats i p h + exact ⟨congrArg Prod.fst hp, congrArg Prod.snd hp⟩ + · rintro ⟨rfl, rfl⟩ + rfl + +@[simp] theorem card_refl (rows repeats : Nat → Nat) : + Fintype.card (Index (branch := branch) rows repeats (.refl m)) = 2 ^ rows m - 1 := + WholeCutCalls.direction_card (rows m) + +theorem card_step (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) : + Fintype.card (Index rows repeats (.step i p)) = + (2 ^ rows (n + 1) - 1) * Fintype.card (TerminalIndex repeats (.step i p)) + + Fintype.card (Index rows repeats p) := by + change Fintype.card + ((BucketSampler.Direction (rows (n + 1)) × TerminalIndex repeats (.step i p)) ⊕ + Index rows repeats p) = _ + rw [Fintype.card_sum, Fintype.card_prod, WholeCutCalls.direction_card] + +theorem card_eq_formula (rows repeats : Nat → Nat) (p : Path branch n m) : + Fintype.card (Index rows repeats p) = (2 ^ rows m - 1) + + ∑ h ∈ Finset.Ioc m n, (2 ^ rows h - 1) * + ∏ k ∈ Finset.Ioc m h, 2 * repeats k := by + induction p with + | refl m => simp only [card_refl, Finset.Ioc_self, Finset.sum_empty, Nat.add_zero] + | @step n m i p ih => + rw [card_step, TerminalCalls.card_eq_prod, ih, + Finset.sum_Ioc_succ_top p.height_le] + omega + +def count (rows repeats : Nat → Nat) (root cutoff : Nat) : Nat := + (2 ^ rows cutoff - 1) + + ∑ h ∈ Finset.Ioc cutoff root, (2 ^ rows h - 1) * + ∏ k ∈ Finset.Ioc cutoff h, 2 * repeats k + +theorem card_eq_count (rows repeats : Nat → Nat) (p : Path branch n m) : + Fintype.card (Index rows repeats p) = count rows repeats n m := + card_eq_formula rows repeats p + +theorem card_branch_independent {branch' : Nat → Nat} + (rows repeats : Nat → Nat) (p : Path branch n m) (q : Path branch' n m) : + Fintype.card (Index rows repeats p) = Fintype.card (Index rows repeats q) := by + rw [card_eq_count, card_eq_count] + +end +end PerfectCompleteness.OriginalCutCalls + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/WholeCutExteriorTransportLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/WholeCutExteriorTransportLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..b68acbfe34181c20d0b00eb08050e7d49c6621ac --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/WholeCutExteriorTransportLemmas.lean @@ -0,0 +1,232 @@ +import OAI.Computability.PerfectCompleteness.Foundations.CutTerminalZero +import OAI.Computability.PerfectCompleteness.Foundations.WholeCutGrouping + +namespace OAI + +section + +namespace PerfectCompleteness.WholeCutExteriorTransport + +open PointwiseSpaces RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open RecursiveSampler TerminalCalls +open UniqueGamesTheorem.Foundations.Games +open scoped Classical + +abbrev F2 := ZMod 2 + +noncomputable section + +variable {branch : Nat → Nat} {n m t : Nat} + +def Outside (p : Path branch n m) (s : Slots branch n) : Prop := + s ∉ Set.range p.slotEmbedding + +theorem outside_ordinary (i : Fin (branch n)) (p : Path branch n m) + (j : OffPath i) (s : Slots branch n) : Outside (.step i p) (j.val, s) := by + rintro ⟨u, hu⟩ + exact j.property (congrArg Prod.fst hu).symm + +theorem outside_selected (i : Fin (branch n)) (p : Path branch n m) + (s : Slots branch n) (hs : Outside p s) : Outside (.step i p) (i, s) := by + rintro ⟨u, hu⟩ + exact hs ⟨u, congrArg Prod.snd hu⟩ + +theorem ordinarySlots_eq (i : Fin (branch n)) (p : Path branch n m) + (slots target : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (hs : ∀ s, Outside (.step i p) s → slots s = target s) (j : OffPath i) : + childSlots slots j.val = childSlots target j.val := by + funext s + exact hs (j.val, s) (outside_ordinary i p j s) + +theorem factor_eq (repeats : Nat → Nat) (p : Path branch n m) : + ∀ (slots target : Slots branch n → Fin t → MixedSupport.Slot), + (∀ s, Outside p s → slots s = target s) → + ∀ (j : DrawIndex repeats p), ¬ IsTerminal repeats p j → + CutSamplerRefinement.RefinedSpace F2 repeats p (LeafDomain slots) j = + CutSamplerRefinement.RefinedSpace F2 repeats p (LeafDomain target) j := by + induction p with + | refl n => + intro slots target hs j hj + exact False.elim (hj True.intro) + | @step n m i p ih => + intro slots target hs j hj + cases j with + | inl j => + exact congrArg + (fun ss : Slots branch n → Fin t → MixedSupport.Slot => + (squareSpace (space F2 branch n (LeafDomain ss)) : Type)) + (ordinarySlots_eq i p slots target hs j) + | inr j => + exact ih (childSlots slots i) (childSlots target i) + (fun s h => hs (i, s) (outside_selected i p s h)) j.2 hj + +theorem scalarExterior_eq (repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots target : Slots branch n → Fin t → MixedSupport.Slot) + (hs : ∀ s, Outside p s → slots s = target s) : + CutTerminalSplit.ExteriorTape F2 repeats p (LeafDomain slots) = + CutTerminalSplit.ExteriorTape F2 repeats p (LeafDomain target) := + congrArg + (fun A : CutTerminalSplit.ExteriorIndex repeats p → Type => + (j : CutTerminalSplit.ExteriorIndex repeats p) → A j) + (funext (fun j => factor_eq repeats p slots target hs j.val j.property)) + +def scalarEquiv (repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots target : Slots branch n → Fin t → MixedSupport.Slot) + (hs : ∀ s, Outside p s → slots s = target s) : + CutTerminalSplit.ExteriorTape F2 repeats p (LeafDomain slots) ≃ + CutTerminalSplit.ExteriorTape F2 repeats p (LeafDomain target) := + Equiv.piCongrRight (fun j => Equiv.cast (factor_eq repeats p slots target hs j.val j.property)) + +@[simp] theorem scalarEquiv_apply (repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots target : Slots branch n → Fin t → MixedSupport.Slot) + (hs : ∀ s, Outside p s → slots s = target s) + (x : CutTerminalSplit.ExteriorTape F2 repeats p (LeafDomain slots)) + (j : CutTerminalSplit.ExteriorIndex repeats p) : + scalarEquiv repeats p slots target hs x j = + cast (factor_eq repeats p slots target hs j.val j.property) (x j) := rfl + +theorem square_cast_eval + (slots target : Slots branch n → Fin t → MixedSupport.Slot) (hs : slots = target) + (f : squareSpace (space F2 branch n (LeafDomain slots))) (x : Domain slots) : + (cast (congrArg + (fun ss : Slots branch n → Fin t → MixedSupport.Slot => + (squareSpace (space F2 branch n (LeafDomain ss)) : Type)) hs) f).val + (cast (congrArg Domain hs) x) = f.val x := by + cases hs + rfl + +theorem exterior_eq (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) : + ∀ (slots target : Slots branch n → Fin t → MixedSupport.Slot), + (∀ s, Outside p s → slots s = target s) → + WholeCutGrouping.Exterior rows repeats p slots = + WholeCutGrouping.Exterior rows repeats p target := by + induction n generalizing m with + | zero => + have h := p.height_le + omega + | succ n ih => + cases p with + | refl => intro slots target hs; rfl + | step i p => + intro slots target hs + have hroot := scalarExterior_eq repeats (.step i p) slots target hs + have hselected := ih p (childSlots slots i) (childSlots target i) + (fun s h => hs (i, s) (outside_selected i p s h)) + have hord : + ((j : OffPath i) → Arrays (childSlots slots j.val) rows) = + ((j : OffPath i) → Arrays (childSlots target j.val) rows) := + congrArg (fun A : OffPath i → Type => (j : OffPath i) → A j) + (funext (fun j => congrArg + (fun ss : Slots branch n → Fin t → MixedSupport.Slot => Arrays ss rows) + (ordinarySlots_eq i p slots target hs j))) + exact congrArg₂ (fun A B : Type => A × B) + (congrArg (fun A : Type => BucketSampler.Direction (rows (n + 1)) → A) hroot) + (congrArg₂ (fun A B : Type => A × B) hselected hord) + +def equiv (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots target : Slots branch n → Fin t → MixedSupport.Slot) + (hs : ∀ s, Outside p s → slots s = target s) : + WholeCutGrouping.Exterior rows repeats p slots ≃ + WholeCutGrouping.Exterior rows repeats p target := + Equiv.cast (exterior_eq rows repeats p slots target hs) + +theorem pushforward_exteriorLaw (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots target : Slots branch n → Fin t → MixedSupport.Slot) + (hs : ∀ s, Outside p s → slots s = target s) : + (WholeCutGrouping.exteriorLaw rows repeats p slots).pushforward + (equiv rows repeats p slots target hs) = + WholeCutGrouping.exteriorLaw rows repeats p target := by + unfold WholeCutGrouping.exteriorLaw + rw [FiniteDistribution.pushforward_equiv] + apply FiniteDistribution.eq_of_weight_eq + intro x + change 1 / (Fintype.card (WholeCutGrouping.Exterior rows repeats p slots) : ℝ) = + 1 / (Fintype.card (WholeCutGrouping.Exterior rows repeats p target) : ℝ) + rw [Fintype.card_congr (equiv rows repeats p slots target hs)] + +end +end PerfectCompleteness.WholeCutExteriorTransport + +end + +section + +namespace PerfectCompleteness.WholeCutZero + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays + +abbrev F2 := ZMod 2 + +variable {branch : Nat → Nat} {n m t : Nat} + +def GroupedAtClean (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) (tape : WholeCutSampler.Tape rows repeats p slots) : Prop := + ∀ child, clean child → + (∀ q, ((WholeCutGrouping.splitTape rows repeats p slots tape).2 child).1 q = 0) ∧ + ∀ node row, ((WholeCutGrouping.splitTape rows repeats p slots tape).2 child).2 node row = 0 + +def ZeroAtClean (rows repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n (m + 1)) → + (slots : Slots branch n → Fin t → MixedSupport.Slot) → + (clean : Fin (branch m) → Prop) → WholeCutSampler.Tape rows repeats p slots → Prop + | _, _, .refl _, _, clean, tape => + ∀ child, clean child → + (∀ q, (tape child).1 q = 0) ∧ ∀ node row, (tape child).2 node row = 0 + | _, _, .step i p, slots, clean, tape => + (∀ bucket, CutSamplerLocality.ZeroAtClean F2 repeats (.step i p) + (LeafDomain slots) clean (tape.1 bucket)) ∧ + ZeroAtClean rows repeats p (childSlots slots i) clean tape.2.1 + +theorem grouped_step_iff (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n (m + 1)) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (tape : WholeCutSampler.Tape rows repeats (.step i p) slots) : + GroupedAtClean rows repeats (.step i p) slots clean tape ↔ + (∀ bucket terminal child, clean child → + (CutTerminalSplit.splitTape F2 repeats (.step i p) + (LeafDomain slots) (tape.1 bucket)).1 terminal child = 0) ∧ + GroupedAtClean rows repeats p (childSlots slots i) clean tape.2.1 := by + constructor + · intro h + constructor + · intro bucket terminal child hchild + exact (h child hchild).1 (.inl (bucket, terminal)) + · intro child hchild + exact ⟨fun q => (h child hchild).1 (.inr q), (h child hchild).2⟩ + · rintro ⟨hroot, hselected⟩ child hchild + refine ⟨?_, (hselected child hchild).2⟩ + intro q + rcases q with ⟨bucket, terminal⟩ | q + · exact hroot bucket terminal child hchild + · exact (hselected child hchild).1 q + +theorem grouped_iff (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) : + ∀ (slots : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) (tape : WholeCutSampler.Tape rows repeats p slots), + GroupedAtClean rows repeats p slots clean tape ↔ + ZeroAtClean rows repeats p slots clean tape := by + induction n generalizing m with + | zero => + have h := p.height_le + omega + | succ n ih => + cases p with + | refl => + intro slots clean tape + rfl + | step i p => + intro slots clean tape + rw [grouped_step_iff] + exact and_congr + (forall_congr' (fun bucket => + CutTerminalZero.zeroAtClean_iff F2 repeats (.step i p) + (LeafDomain slots) clean (tape.1 bucket))) + (ih p (childSlots slots i) clean tape.2.1) + +end PerfectCompleteness.WholeCutZero + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/WholeCutGrouping.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/WholeCutGrouping.lean new file mode 100644 index 0000000000000000000000000000000000000000..a735147a4d9539d88d9505a9bd40599100f5bdbc --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/WholeCutGrouping.lean @@ -0,0 +1,141 @@ +import OAI.Computability.PerfectCompleteness.Foundations.CutTerminalSplit +import OAI.Computability.PerfectCompleteness.Foundations.WholeCutCallsLemmas +import OAI.Computability.PerfectCompleteness.Sampling.WholeCutSampler + +namespace OAI + +section + +namespace PerfectCompleteness.WholeCutGrouping + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open scoped Classical + +abbrev F2 := ZMod 2 + +noncomputable section + +section Rearrangement + +variable {V C T I E F O : Type*} {D A : I → Type*} + +def regroupStep : + ((V → ((C → (i : I) → D i) × E)) × + ((F × ((i : I) → (T → D i) × A i)) × O)) ≃ + (((V → E) × (F × O)) × ((i : I) → ((V × C ⊕ T) → D i) × A i)) where + toFun x := + ((fun v => (x.1 v).2, (x.2.1.1, x.2.2)), + fun i => + (fun q => match q with + | .inl vc => (x.1 vc.1).1 vc.2 i + | .inr t => (x.2.1.2 i).1 t, + (x.2.1.2 i).2)) + invFun x := + ((fun v => (fun c i => (x.2 i).1 (.inl (v, c)), x.1.1 v)), + ((x.1.2.1, fun i => (fun t => (x.2 i).1 (.inr t), (x.2 i).2)), x.1.2.2)) + left_inv x := rfl + right_inv x := by + apply Prod.ext + · rfl + · funext i + apply Prod.ext + · funext q + cases q <;> rfl + · rfl + +end Rearrangement + +variable {branch : Nat → Nat} {n m t : Nat} + +abbrev cutSlots (p : Path branch n m) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Slots branch m → Fin t → MixedSupport.Slot := + fun s => slots (p.slotEmbedding s) + +def Exterior (rows repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n (m + 1)) → + (Slots branch n → Fin t → MixedSupport.Slot) → Type + | _, _, .refl _, _ => Unit + | n + 1, _, .step i p, slots => + (BucketSampler.Direction (rows (n + 1)) → + CutTerminalSplit.ExteriorTape F2 repeats (.step i p) (LeafDomain slots)) × + (Exterior rows repeats p (childSlots slots i) × + ((j : RecursiveSampler.OffPath i) → Arrays (childSlots slots j.val) rows)) + +@[instance_reducible] def exteriorFintypeAux (rows repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n (m + 1)) → + (slots : Slots branch n → Fin t → MixedSupport.Slot) → + Fintype (Exterior rows repeats p slots) + | _, _, .refl _, _ => inferInstanceAs (Fintype Unit) + | n + 1, _, .step i p, slots => + letI : Fintype (Exterior rows repeats p (childSlots slots i)) := + exteriorFintypeAux rows repeats p (childSlots slots i) + inferInstanceAs (Fintype + ((BucketSampler.Direction (rows (n + 1)) → + CutTerminalSplit.ExteriorTape F2 repeats (.step i p) (LeafDomain slots)) × + (Exterior rows repeats p (childSlots slots i) × + ((j : RecursiveSampler.OffPath i) → Arrays (childSlots slots j.val) rows)))) + +instance exteriorFintype (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Fintype (Exterior rows repeats p slots) := exteriorFintypeAux rows repeats p slots + +def exteriorZero (rows repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n (m + 1)) → + (slots : Slots branch n → Fin t → MixedSupport.Slot) → Exterior rows repeats p slots + | _, _, .refl _, _ => () + | _, _, .step i p, slots => + ((fun _ j => CutSamplerRefinement.zeroFactor F2 repeats (.step i p) (LeafDomain slots) j.val), + (exteriorZero rows repeats p (childSlots slots i), fun _ _ _ => 0)) + +instance exteriorNonempty (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Nonempty (Exterior rows repeats p slots) := ⟨exteriorZero rows repeats p slots⟩ + +def splitTape (rows repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n (m + 1)) → + (slots : Slots branch n → Fin t → MixedSupport.Slot) → + WholeCutSampler.Tape rows repeats p slots ≃ + Exterior rows repeats p slots × + CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) (cutSlots p slots) rows + | _, _, .refl _, slots => + { toFun := fun x => ((), x) + invFun := Prod.snd + left_inv := fun _ => rfl + right_inv := by rintro ⟨⟨⟩, x⟩; rfl } + | n + 1, _, .step i p, slots => + (Equiv.prodCongr + (Equiv.piCongrRight (fun _ : BucketSampler.Direction (rows (n + 1)) => + CutTerminalSplit.splitTape F2 repeats (.step i p) (LeafDomain slots))) + (Equiv.prodCongr (splitTape rows repeats p (childSlots slots i)) (Equiv.refl _))).trans + regroupStep + +def exteriorLaw (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + FiniteDistribution (Exterior rows repeats p slots) := + FiniteDistribution.uniform _ + +theorem split_tapeLaw (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + (WholeCutSampler.tapeLaw rows repeats p slots).pushforward (splitTape rows repeats p slots) = + (exteriorLaw rows repeats p slots).product + (CutChildGrouping.rawLaw (C := WholeCutCalls.Index rows repeats p) (cutSlots p slots) rows) := by + rw [WholeCutSampler.tapeLaw_eq_uniform, FiniteDistribution.pushforward_equiv] + unfold exteriorLaw CutChildGrouping.rawLaw + rw [UniformLinearImage.law_uniform] + apply FiniteDistribution.eq_of_weight_eq + intro x + change 1 / (Fintype.card (WholeCutSampler.Tape rows repeats p slots) : ℝ) = + (1 / (Fintype.card (Exterior rows repeats p slots) : ℝ)) * + (1 / (Fintype.card + (CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) (cutSlots p slots) rows) : ℝ)) + rw [Fintype.card_congr (splitTape rows repeats p slots), Fintype.card_prod] + simp only [Nat.cast_mul, one_div, mul_inv] + +end +end PerfectCompleteness.WholeCutGrouping + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/WholeCutReplayGroupingTransport.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/WholeCutReplayGroupingTransport.lean new file mode 100644 index 0000000000000000000000000000000000000000..fa6a824b8db69f49d9c373f48594c9de9833ca2b --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/WholeCutReplayGroupingTransport.lean @@ -0,0 +1,260 @@ +import OAI.Computability.PerfectCompleteness.Foundations.WholeCutReplayLemmas +import OAI.Computability.PerfectCompleteness.Sampling.CutSamplerReplayGroupingTransport + +namespace OAI + +section + +namespace PerfectCompleteness.WholeCutReplayGroupingTransport + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open CutSamplerKeyLocality +open scoped Classical + +abbrev F2 := ZMod 2 + +noncomputable section + +variable {branch : Nat → Nat} {n m t : Nat} + +export CutSamplerReplayGroupingTransport (outside_kept outside_eq retainedChildSlots_eq) + +abbrev ChildBlock (C : Type) (rows : Nat → Nat) + (slots : Slots branch m → Fin t → MixedSupport.Slot) := + (C → PointwiseSpaces.squareSpace (H slots)) × Arrays slots rows + +def castChildren (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots target : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (hs : ∀ s, keptLeaf p clean s → slots s = target s) + (children : WholeCutReplayGrouping.RetainedChildren rows repeats p slots clean) : + WholeCutReplayGrouping.RetainedChildren rows repeats p target clean := + fun child => cast + (congrArg (ChildBlock (WholeCutCalls.Index rows repeats p) rows) + (retainedChildSlots_eq p slots target clean hs child)) (children child) + +theorem castChildren_apply_heq (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots target : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (hs : ∀ s, keptLeaf p clean s → slots s = target s) + (children : WholeCutReplayGrouping.RetainedChildren rows repeats p slots clean) + (child : {i : Fin (branch m) // ¬ clean i}) : + HEq (castChildren rows repeats p slots target clean hs children child) (children child) := + cast_heq _ _ + +private theorem blockCast_calls {C : Type} (rows : Nat → Nat) + {slots target : Slots branch m → Fin t → MixedSupport.Slot} (hs : slots = target) + (x : ChildBlock C rows slots) (c : C) : + (cast (congrArg (ChildBlock C rows) hs) x).1 c = + cast (congrArg (fun ss => (PointwiseSpaces.squareSpace (H ss) : Type)) hs) (x.1 c) := by + cases hs + rfl + +private theorem blockCast_arrays {C : Type} (rows : Nat → Nat) + {slots target : Slots branch m → Fin t → MixedSupport.Slot} (hs : slots = target) + (x : ChildBlock C rows slots) : + (cast (congrArg (ChildBlock C rows) hs) x).2 = + cast (congrArg (fun ss => Arrays ss rows) hs) x.2 := by + cases hs + rfl + +theorem castChildren_calls (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots target : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (hs : ∀ s, keptLeaf p clean s → slots s = target s) + (children : WholeCutReplayGrouping.RetainedChildren rows repeats p slots clean) + (child : {i : Fin (branch m) // ¬ clean i}) (c : WholeCutCalls.Index rows repeats p) : + (castChildren rows repeats p slots target clean hs children child).1 c = + cast (congrArg (fun ss => (PointwiseSpaces.squareSpace (H ss) : Type)) + (retainedChildSlots_eq p slots target clean hs child)) ((children child).1 c) := + blockCast_calls rows (retainedChildSlots_eq p slots target clean hs child) (children child) c + +theorem castChildren_arrays (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots target : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (hs : ∀ s, keptLeaf p clean s → slots s = target s) + (children : WholeCutReplayGrouping.RetainedChildren rows repeats p slots clean) + (child : {i : Fin (branch m) // ¬ clean i}) : + (castChildren rows repeats p slots target clean hs children child).2 = + cast (congrArg (fun ss => Arrays ss rows) + (retainedChildSlots_eq p slots target clean hs child)) (children child).2 := + blockCast_arrays rows (retainedChildSlots_eq p slots target clean hs child) (children child) + +private theorem blockCast_reindex {C D : Type} (rows : Nat → Nat) (f : D → C) + {slots target : Slots branch m → Fin t → MixedSupport.Slot} (hs : slots = target) + (x : ChildBlock C rows slots) : + ((fun d => (cast (congrArg (ChildBlock C rows) hs) x).1 (f d)), + (cast (congrArg (ChildBlock C rows) hs) x).2) = + cast (congrArg (ChildBlock D rows) hs) (fun d => x.1 (f d), x.2) := by + cases hs + rfl + +private theorem blockTransport_eq_cast {C : Type} (rows : Nat → Nat) + (slots target : Slots branch m → Fin t → MixedSupport.Slot) (hs : slots = target) + (x : ChildBlock C rows slots) : + ((fun c => (RecursiveSpaceEquiv.squareEquiv (𝕜 := F2) + (fun s => Equiv.cast (congrArg MixedSupport.Assignment (congrFun hs s)))).symm (x.1 c)), + WholeCutReplayTransport.arraysTransport rows slots target + (fun s => Equiv.cast (congrArg MixedSupport.Assignment (congrFun hs s))) x.2) = + cast (congrArg (ChildBlock C rows) hs) x := by + cases hs + apply Prod.ext + · funext c + apply Subtype.ext + funext y + rfl + · funext node row + apply Subtype.ext + funext y + rfl + +private theorem arraysTransport_eq_cast (rows : Nat → Nat) + (slots target : Slots branch n → Fin t → MixedSupport.Slot) (hs : slots = target) + (arrays : Arrays slots rows) : + WholeCutReplayTransport.arraysTransport rows slots target + (fun s => Equiv.cast (congrArg MixedSupport.Assignment (congrFun hs s))) arrays = + cast (congrArg (fun ss => Arrays ss rows) hs) arrays := by + cases hs + funext node row + apply Subtype.ext + funext y + rfl + +private theorem cast_exterior_parts {I J A A' B B' : Type} {C C' : J → Type} + (ha : A = A') (hb : B = B') (hc : ∀ j, C j = C' j) + (h : ((I → A) × (B × ((j : J) → C j))) = ((I → A') × (B' × ((j : J) → C' j)))) + (x : (I → A) × (B × ((j : J) → C j))) : + cast h x = (fun i => cast ha (x.1 i), (cast hb x.2.1, fun j => cast (hc j) (x.2.2 j))) := by + have hC : C = C' := funext hc + cases ha + cases hb + cases hC + rfl + +theorem exterior_equiv_step (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n (m + 1)) + (slots target : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (hs : ∀ s, keptLeaf (.step i p) clean s → slots s = target s) + (ext : WholeCutGrouping.Exterior rows repeats (.step i p) slots) : + WholeCutExteriorTransport.equiv rows repeats (.step i p) slots target + (outside_eq (.step i p) slots target clean hs) ext = + (fun bucket => cast + (WholeCutExteriorTransport.scalarExterior_eq repeats (.step i p) slots target + (outside_eq (.step i p) slots target clean hs)) (ext.1 bucket), + (WholeCutExteriorTransport.equiv rows repeats p (childSlots slots i) (childSlots target i) + (outside_eq p (childSlots slots i) (childSlots target i) clean + (fun s h => hs (i, s) (Or.inr h))) ext.2.1, + fun j => cast (congrArg (fun ss => Arrays ss rows) + (WholeCutExteriorTransport.ordinarySlots_eq i p slots target + (outside_eq (.step i p) slots target clean hs) j)) (ext.2.2 j))) := + cast_exterior_parts _ _ _ _ ext + +private theorem castChildren_tail (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n (m + 1)) + (slots target : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (hs : ∀ s, keptLeaf (.step i p) clean s → slots s = target s) + (children : WholeCutReplayGrouping.RetainedChildren rows repeats (.step i p) slots clean) : + (fun child => + (fun q => (castChildren rows repeats (.step i p) slots target clean hs children child).1 (.inr q), + (castChildren rows repeats (.step i p) slots target clean hs children child).2)) = + castChildren rows repeats p (childSlots slots i) (childSlots target i) clean + (fun s h => hs (i, s) (Or.inr h)) + (fun child => (fun q => (children child).1 (.inr q), (children child).2)) := by + funext child + exact blockCast_reindex rows Sum.inr + (retainedChildSlots_eq (.step i p) slots target clean hs child) (children child) + +theorem transport_assemble (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) : + ∀ (slots target : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (hs : ∀ s, keptLeaf p clean s → slots s = target s) + (ext : WholeCutGrouping.Exterior rows repeats p slots) + (children : WholeCutReplayGrouping.RetainedChildren rows repeats p slots clean), + WholeCutReplayKeys.transportTape rows repeats p slots target clean hs + (WholeCutReplayGrouping.assemble rows repeats p slots clean ext children) = + WholeCutReplayGrouping.assemble rows repeats p target clean + (WholeCutExteriorTransport.equiv rows repeats p slots target + (outside_eq p slots target clean hs) ext) + (castChildren rows repeats p slots target clean hs children) := by + induction n generalizing m with + | zero => + have h := p.height_le + omega + | succ n ih => + cases p with + | refl => + intro slots target clean hs ext children + funext child + exact blockTransport_eq_cast rows _ _ + (retainedChildSlots_eq (.refl (n + 1)) slots target clean hs child) (children child) + | step i p => + intro slots target clean hs ext children + rw [exterior_equiv_step rows repeats i p slots target clean hs ext] + apply Prod.ext + · funext bucket + refine (CutSamplerReplayGroupingTransport.transport_assemble repeats (.step i p) + slots target clean hs (ext.1 bucket) + (fun terminal child => (children child).1 (.inl (bucket, terminal)))).trans ?_ + let exterior : CutTerminalSplit.ExteriorTape F2 repeats (.step i p) (LeafDomain target) := + cast (WholeCutExteriorTransport.scalarExterior_eq repeats (.step i p) slots target + (outside_eq (.step i p) slots target clean hs)) (ext.1 bucket) + change CutSamplerReplayGrouping.assemble F2 repeats (.step i p) + (LeafDomain target) clean exterior + (CutSamplerReplayGroupingTransport.castTerminal repeats (.step i p) + slots target clean hs + (fun terminal child => (children child).1 (.inl (bucket, terminal)))) = + CutSamplerReplayGrouping.assemble F2 repeats (.step i p) + (LeafDomain target) clean exterior + (fun terminal child => + (castChildren rows repeats (.step i p) slots target clean hs children child).1 + (.inl (bucket, terminal))) + apply congrArg (CutSamplerReplayGrouping.assemble F2 repeats (.step i p) + (LeafDomain target) clean exterior) + funext terminal child + exact (castChildren_calls rows repeats (.step i p) slots target clean hs + children child (.inl (bucket, terminal))).symm + · apply Prod.ext + · refine (ih p (childSlots slots i) (childSlots target i) clean + (fun s h => hs (i, s) (Or.inr h)) ext.2.1 + (fun child => (fun q => (children child).1 (.inr q), (children child).2))).trans ?_ + let exterior : WholeCutGrouping.Exterior rows repeats p (childSlots target i) := + WholeCutExteriorTransport.equiv rows repeats p (childSlots slots i) (childSlots target i) + (outside_eq p (childSlots slots i) (childSlots target i) clean + (fun s h => hs (i, s) (Or.inr h))) ext.2.1 + change WholeCutReplayGrouping.assemble rows repeats p (childSlots target i) clean exterior + (castChildren rows repeats p (childSlots slots i) (childSlots target i) clean + (fun s h => hs (i, s) (Or.inr h)) + (fun child => (fun q => (children child).1 (.inr q), (children child).2))) = + WholeCutReplayGrouping.assemble rows repeats p (childSlots target i) clean exterior + (fun child => + (fun q => (castChildren rows repeats (.step i p) slots target clean hs + children child).1 (.inr q), + (castChildren rows repeats (.step i p) slots target clean hs children child).2)) + apply congrArg (WholeCutReplayGrouping.assemble rows repeats p + (childSlots target i) clean exterior) + exact (castChildren_tail rows repeats i p slots target clean hs children).symm + · funext j + exact arraysTransport_eq_cast rows _ _ + (WholeCutExteriorTransport.ordinarySlots_eq i p slots target + (outside_eq (.step i p) slots target clean hs) j) (ext.2.2 j) + +theorem transportTape_target_eq (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots target target' : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (hs : ∀ s, keptLeaf p clean s → slots s = target s) (ht : target = target') + (tape : WholeCutReplay.Tape rows repeats p slots clean) : + cast (congrArg (fun ss => WholeCutReplay.Tape rows repeats p ss clean) ht) + (WholeCutReplayKeys.transportTape rows repeats p slots target clean hs tape) = + WholeCutReplayKeys.transportTape rows repeats p slots target' clean + (fun s h => (hs s h).trans (congrFun ht s)) tape := by + cases ht + rfl + +end +end PerfectCompleteness.WholeCutReplayGroupingTransport + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/WholeCutReplayKeys.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/WholeCutReplayKeys.lean new file mode 100644 index 0000000000000000000000000000000000000000..e2dd0fb056ce372462c123768a3e573ceaeb530e --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/WholeCutReplayKeys.lean @@ -0,0 +1,220 @@ +import OAI.Computability.PerfectCompleteness.Construction.WholeCutLocalityLemmas +import OAI.Computability.PerfectCompleteness.Foundations.RetainedKeyTransport +import OAI.Computability.PerfectCompleteness.Foundations.WholeCutReplayLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.WholeCutReplayKeys + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open CutSamplerKeyLocality +open scoped Classical + +noncomputable section + +variable {branch : Nat → Nat} {n m t : Nat} {Y : Type*} + +def leafEquiv (p : Path branch n (m + 1)) + (slots target : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (hs : ∀ s, keptLeaf p clean s → slots s = target s) + (s : Slots branch n) (hkeep : keptLeaf p clean s) : + LeafDomain slots s ≃ LeafDomain target s := + Equiv.cast (congrArg MixedSupport.Assignment (hs s hkeep)) + +def transportTape (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots target : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (hs : ∀ s, keptLeaf p clean s → slots s = target s) + (tape : WholeCutReplay.Tape rows repeats p slots clean) : + WholeCutReplay.Tape rows repeats p target clean := + WholeCutReplayTransport.transport rows repeats p slots target clean + (leafEquiv p slots target clean hs) tape + +def query (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) (tape : WholeCutReplay.Tape rows repeats p slots clean) + (post : Output branch n rows → Y) : + MixedSupport.Assignment (TreeCanonical.numberedSlots slots) → Y := + post ∘ TreeCanonical.numberedFunction slots (WholeCutReplay.fullQuery rows repeats p slots clean tape) + +theorem numberedSlotEquality (p : Path branch n (m + 1)) + (slots target : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (hs : ∀ s, keptLeaf p clean s → slots s = target s) + (j : Fin (TreeCanonical.locationCount branch n t)) (hj : numberedKeep p clean j) : + TreeCanonical.numberedSlots slots j = TreeCanonical.numberedSlots target j := + congrFun (hs ((TreeCanonical.numbering branch n t).symm j).1 hj) + ((TreeCanonical.numbering branch n t).symm j).2 + +private theorem assignmentEquiv_symm_apply + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (x : MixedSupport.Assignment (TreeCanonical.numberedSlots slots)) + (s : Slots branch n) (k : Fin t) : + HEq ((TreeCanonical.assignmentEquiv slots).symm x s k) + (x (TreeCanonical.numbering branch n t (s, k))) := by + have h := congrFun ((TreeCanonical.assignmentEquiv slots).apply_symm_apply x) + (TreeCanonical.numbering branch n t (s, k)) + exact Eq.mp (congrArg (fun sk : TreeCanonical.Location branch n t => + HEq ((TreeCanonical.assignmentEquiv slots).symm x sk.1 sk.2) + (x (TreeCanonical.numbering branch n t (s, k)))) + ((TreeCanonical.numbering branch n t).symm_apply_apply (s, k))) (heq_of_eq h) + +private theorem assignmentCast_eq {I : Type*} {slots target : I → MixedSupport.Slot} + (h : slots = target) (x : MixedSupport.Assignment slots) + (y : MixedSupport.Assignment target) (hxy : ∀ i, HEq (x i) (y i)) : + Equiv.cast (congrArg MixedSupport.Assignment h) x = y := by + cases h + funext i + exact eq_of_heq (hxy i) + +theorem leaf_agreement (p : Path branch n (m + 1)) + (slots target : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (hs : ∀ s, keptLeaf p clean s → slots s = target s) + (x : MixedSupport.Assignment (TreeCanonical.numberedSlots slots)) + (y : MixedSupport.Assignment (TreeCanonical.numberedSlots target)) + (hret : RetainedKeyTransport.retainedAssignmentEquiv + (TreeCanonical.numberedSlots slots) (TreeCanonical.numberedSlots target) + (numberedKeep p clean) (numberedSlotEquality p slots target clean hs) + (CleanKeyErasure.retain (TreeCanonical.numberedSlots slots) (numberedKeep p clean) x) = + CleanKeyErasure.retain (TreeCanonical.numberedSlots target) (numberedKeep p clean) y) : + ∀ s hkeep, leafEquiv p slots target clean hs s hkeep + ((TreeCanonical.assignmentEquiv slots).symm x s) = + (TreeCanonical.assignmentEquiv target).symm y s := by + intro s hkeep + change Equiv.cast (congrArg MixedSupport.Assignment (hs s hkeep)) + ((TreeCanonical.assignmentEquiv slots).symm x s) = + (TreeCanonical.assignmentEquiv target).symm y s + apply assignmentCast_eq (hs s hkeep) + intro k + have hj : numberedKeep p clean (TreeCanonical.numbering branch n t (s, k)) := by + simpa only [numberedKeep, Equiv.symm_apply_apply] using hkeep + have hnumbered := RetainedKeyTransport.retainedAssignmentEquiv_agree_heq + (TreeCanonical.numberedSlots slots) (TreeCanonical.numberedSlots target) + (numberedKeep p clean) (numberedSlotEquality p slots target clean hs) x y hret + (TreeCanonical.numbering branch n t (s, k)) hj + exact (assignmentEquiv_symm_apply slots x s k).trans + (hnumbered.trans (assignmentEquiv_symm_apply target y s k).symm) + +theorem query_agreement (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots target : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (hs : ∀ s, keptLeaf p clean s → slots s = target s) + (tape : WholeCutReplay.Tape rows repeats p slots clean) (post : Output branch n rows → Y) + (x : MixedSupport.Assignment (TreeCanonical.numberedSlots slots)) + (y : MixedSupport.Assignment (TreeCanonical.numberedSlots target)) + (hret : RetainedKeyTransport.retainedAssignmentEquiv + (TreeCanonical.numberedSlots slots) (TreeCanonical.numberedSlots target) + (numberedKeep p clean) (numberedSlotEquality p slots target clean hs) + (CleanKeyErasure.retain (TreeCanonical.numberedSlots slots) (numberedKeep p clean) x) = + CleanKeyErasure.retain (TreeCanonical.numberedSlots target) (numberedKeep p clean) y) : + query rows repeats p slots clean tape post x = + query rows repeats p target clean (transportTape rows repeats p slots target clean hs tape) + post y := + congrArg post (WholeCutReplayTransport.fullQuery_transport rows repeats p slots target clean + (leafEquiv p slots target clean hs) tape + ((TreeCanonical.assignmentEquiv slots).symm x) + ((TreeCanonical.assignmentEquiv target).symm y) + (leaf_agreement p slots target clean hs x y hret)).symm + +theorem key_eq_transport (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots target : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (hs : ∀ s, keptLeaf p clean s → slots s = target s) + (tape : WholeCutReplay.Tape rows repeats p slots clean) (post : Output branch n rows → Y) + (side : CanonicalKeys.Side) : + CanonicalKeys.key side (TreeCanonical.numberedSlots slots) + (query rows repeats p slots clean tape post) = + CanonicalKeys.key side (TreeCanonical.numberedSlots target) + (query rows repeats p target clean (transportTape rows repeats p slots target clean hs tape) post) := + RetainedKeyTransport.key_eq side (TreeCanonical.numberedSlots slots) + (TreeCanonical.numberedSlots target) (numberedKeep p clean) + (numberedSlotEquality p slots target clean hs) _ _ + (query_agreement rows repeats p slots target clean hs tape post) + +theorem label_val_eq_transport (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots target : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (hs : ∀ s, keptLeaf p clean s → slots s = target s) + (tape : WholeCutReplay.Tape rows repeats p slots clean) (post : Output branch n rows → Y) + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (side : CanonicalKeys.Side) : + (KeyStrategy.label labeling side (TreeCanonical.numberedSlots slots) + (query rows repeats p slots clean tape post)).val = + (KeyStrategy.label labeling side (TreeCanonical.numberedSlots target) + (query rows repeats p target clean + (transportTape rows repeats p slots target clean hs tape) post)).val := + KeyStrategy.label_val_eq_of_key_eq labeling side side _ _ _ _ + (key_eq_transport rows repeats p slots target clean hs tape post side) + +theorem response_eq_transport (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots target : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (hs : ∀ s, keptLeaf p clean s → slots s = target s) + (tape : WholeCutReplay.Tape rows repeats p slots clean) (post : Output branch n rows → Y) + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (side : CanonicalKeys.Side) : + KeyStrategy.response labeling side (TreeCanonical.numberedSlots slots) + (query rows repeats p slots clean tape post) = + KeyStrategy.response labeling side (TreeCanonical.numberedSlots target) + (query rows repeats p target clean + (transportTape rows repeats p slots target clean hs tape) post) := + RetainedKeyTransport.response_eq labeling side (TreeCanonical.numberedSlots slots) + (TreeCanonical.numberedSlots target) (numberedKeep p clean) + (numberedSlotEquality p slots target clean hs) _ _ + (query_agreement rows repeats p slots target clean hs tape post) + +theorem query_erase (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) (tape : WholeCutSampler.Tape rows repeats p slots) + (post : Output branch n rows → Y) + (hzero : WholeCutZero.GroupedAtClean rows repeats p slots clean tape) : + query rows repeats p slots clean (WholeCutReplay.erase rows repeats p slots clean tape) post = + WholeCutKeyLocality.query rows repeats p slots tape post := by + funext x + exact congrArg post (WholeCutReplay.fullQuery_erase_of_grouped_zero + rows repeats p slots clean tape hzero ((TreeCanonical.assignmentEquiv slots).symm x)) + +theorem original_key_eq_transport (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots target : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (hs : ∀ s, keptLeaf p clean s → slots s = target s) + (tape : WholeCutSampler.Tape rows repeats p slots) (post : Output branch n rows → Y) + (hzero : WholeCutZero.GroupedAtClean rows repeats p slots clean tape) + (side : CanonicalKeys.Side) : + CanonicalKeys.key side (TreeCanonical.numberedSlots slots) + (WholeCutKeyLocality.query rows repeats p slots tape post) = + CanonicalKeys.key side (TreeCanonical.numberedSlots target) + (query rows repeats p target clean (transportTape rows repeats p slots target clean hs + (WholeCutReplay.erase rows repeats p slots clean tape)) post) := by + rw [← query_erase rows repeats p slots clean tape post hzero] + exact key_eq_transport rows repeats p slots target clean hs + (WholeCutReplay.erase rows repeats p slots clean tape) post side + +theorem original_response_eq_transport (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) + (slots target : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (hs : ∀ s, keptLeaf p clean s → slots s = target s) + (tape : WholeCutSampler.Tape rows repeats p slots) (post : Output branch n rows → Y) + (hzero : WholeCutZero.GroupedAtClean rows repeats p slots clean tape) + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (side : CanonicalKeys.Side) : + KeyStrategy.response labeling side (TreeCanonical.numberedSlots slots) + (WholeCutKeyLocality.query rows repeats p slots tape post) = + KeyStrategy.response labeling side (TreeCanonical.numberedSlots target) + (query rows repeats p target clean (transportTape rows repeats p slots target clean hs + (WholeCutReplay.erase rows repeats p slots clean tape)) post) := by + rw [← query_erase rows repeats p slots clean tape post hzero] + exact response_eq_transport rows repeats p slots target clean hs + (WholeCutReplay.erase rows repeats p slots clean tape) post labeling side + +end +end PerfectCompleteness.WholeCutReplayKeys + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/WholeCutReplayLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/WholeCutReplayLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..8e05dc6a1f719a41d3b1f3c44462267edaefa1d3 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/WholeCutReplayLemmas.lean @@ -0,0 +1,822 @@ +import OAI.Computability.PerfectCompleteness.Construction.WholeCutLocalityLemmas +import OAI.Computability.PerfectCompleteness.Sampling.CutSamplerKeyLocalityLemmas +import OAI.Computability.PerfectCompleteness.Sampling.CutSamplerReplayTransportLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.WholeCutReplay + +open scoped BigOperators Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays + +abbrev F2 := ZMod 2 + +noncomputable section + +variable {branch : Nat → Nat} {n m t : Nat} + +def Tape (rows repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n (m + 1)) → + (slots : Slots branch n → Fin t → MixedSupport.Slot) → + (clean : Fin (branch m) → Prop) → Type + | _, m, .refl _, slots, clean => + (i : {i : Fin (branch m) // ¬ clean i}) → + CutChildGrouping.Child (C := Fin (rows (m + 1))) slots rows i.val + | n + 1, _, .step i p, slots, clean => + (BucketSampler.Direction (rows (n + 1)) → + CutSamplerReplay.Tape F2 repeats (.step i p) (LeafDomain slots) clean) × + (Tape rows repeats p (childSlots slots i) clean × + ((j : RecursiveSampler.OffPath i) → Arrays (childSlots slots j.val) rows)) + +def erase (rows repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n (m + 1)) → + (slots : Slots branch n → Fin t → MixedSupport.Slot) → + (clean : Fin (branch m) → Prop) → WholeCutSampler.Tape rows repeats p slots → + Tape rows repeats p slots clean + | _, _, .refl _, _, _, tape => fun i => tape i.val + | _, _, .step i p, slots, clean, tape => + (fun bucket => CutSamplerReplay.erase F2 repeats (.step i p) + (LeafDomain slots) clean (tape.1 bucket), + erase rows repeats p (childSlots slots i) clean tape.2.1, tape.2.2) + +def evaluate (rows repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n (m + 1)) → + (slots : Slots branch n → Fin t → MixedSupport.Slot) → + (clean : Fin (branch m) → Prop) → Tape rows repeats p slots clean → + Domain slots → (node : Nodes branch n) → Block rows node + | _, m, .refl _, slots, clean, tape, x, .inl _, row => + ∑ i : {i : Fin (branch m) // ¬ clean i}, + ((tape i).1 row).val (restrictChild slots i.val x) + | _, _, .refl _, slots, clean, tape, x, .inr (i, node), row => + if hi : ¬ clean i then + ((tape ⟨i, hi⟩).2 node row).val + (restrictNode (childSlots slots i) node (restrictChild slots i x)) + else 0 + | n + 1, _, .step i p, slots, clean, tape, x, .inl _, row => + ∑ bucket : BucketSampler.Direction (rows (n + 1)), bucket.val row * + CutSamplerReplay.evaluate F2 repeats (.step i p) (LeafDomain slots) + clean (tape.1 bucket) x + | _, _, .step i p, slots, clean, tape, x, .inr (j, node), row => + if hji : j = i then + evaluate rows repeats p (childSlots slots i) clean tape.2.1 + (restrictChild slots i x) node row + else + ((tape.2.2 ⟨j, hji⟩) node row).val + (restrictNode (childSlots slots j) node (restrictChild slots j x)) + +theorem evaluate_refl_root (rows repeats : Nat → Nat) + (slots : Slots branch (m + 1) → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (tape : Tape rows repeats (.refl (m + 1)) slots clean) (x : Domain slots) + (row : Fin (rows (m + 1))) : + evaluate rows repeats (.refl (m + 1)) slots clean tape x (.inl ()) row = + ∑ i : {i : Fin (branch m) // ¬ clean i}, + ((tape i).1 row).val (restrictChild slots i.val x) := rfl + +theorem evaluate_refl_child (rows repeats : Nat → Nat) + (slots : Slots branch (m + 1) → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (tape : Tape rows repeats (.refl (m + 1)) slots clean) (x : Domain slots) + (i : Fin (branch m)) (node : Nodes branch m) (row : Fin (rows (Nodes.height node))) : + evaluate rows repeats (.refl (m + 1)) slots clean tape x (.inr (i, node)) row = + if hi : ¬ clean i then + ((tape ⟨i, hi⟩).2 node row).val + (restrictNode (childSlots slots i) node (restrictChild slots i x)) + else 0 := rfl + +theorem evaluate_step_root (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n (m + 1)) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (tape : Tape rows repeats (.step i p) slots clean) (x : Domain slots) + (row : Fin (rows (n + 1))) : + evaluate rows repeats (.step i p) slots clean tape x (.inl ()) row = + ∑ bucket : BucketSampler.Direction (rows (n + 1)), bucket.val row * + CutSamplerReplay.evaluate F2 repeats (.step i p) (LeafDomain slots) + clean (tape.1 bucket) x := rfl + +theorem evaluate_step_selected (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n (m + 1)) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (tape : Tape rows repeats (.step i p) slots clean) (x : Domain slots) + (node : Nodes branch n) (row : Fin (rows (Nodes.height node))) : + evaluate rows repeats (.step i p) slots clean tape x (.inr (i, node)) row = + evaluate rows repeats p (childSlots slots i) clean tape.2.1 + (restrictChild slots i x) node row := by + simp only [evaluate] + exact dite_eq_left True.intro + +theorem evaluate_step_ordinary (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n (m + 1)) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (tape : Tape rows repeats (.step i p) slots clean) (x : Domain slots) + (j : RecursiveSampler.OffPath i) (node : Nodes branch n) + (row : Fin (rows (Nodes.height node))) : + evaluate rows repeats (.step i p) slots clean tape x (.inr (j.val, node)) row = + ((tape.2.2 j) node row).val + (restrictNode (childSlots slots j.val) node (restrictChild slots j.val x)) := by + simp only [evaluate, dite_eq_right j.property] + +theorem evaluate_erase (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) : + ∀ (slots : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (tape : WholeCutSampler.Tape rows repeats p slots), + WholeCutZero.ZeroAtClean rows repeats p slots clean tape → + ∀ x : Domain slots, + evaluate rows repeats p slots clean (erase rows repeats p slots clean tape) x = + joint (WholeCutSampler.evaluate rows repeats p slots tape) x := by + induction n generalizing m with + | zero => + have h := p.height_le + omega + | succ n ih => + cases p with + | refl => + intro slots clean tape hzero x + funext node row + rcases node with u | ⟨i, node⟩ + · cases u + let scalarTape : CutSamplerRefinement.Tape F2 repeats (.refl (n + 1)) + (LeafDomain slots) := fun _ i => (tape i).1 row + have hz : CutSamplerLocality.ZeroAtClean F2 repeats (.refl (n + 1)) + (LeafDomain slots) clean scalarTape := + fun i hi => (hzero i hi).1 row + exact CutSamplerReplay.evaluate_erase F2 repeats (.refl (n + 1)) + (LeafDomain slots) clean scalarTape hz x + · refine (evaluate_refl_child rows repeats slots clean + (erase rows repeats (.refl (n + 1)) slots clean tape) x i node row).trans ?_ + change (if hi : ¬ clean i then + ((tape i).2 node row).val + (restrictNode (childSlots slots i) node (restrictChild slots i x)) + else 0) = + ((tape i).2 node row).val + (restrictNode (childSlots slots i) node (restrictChild slots i x)) + by_cases hi : clean i + · rw [dite_eq_right (not_not_intro hi), (hzero i hi).2 node row] + rfl + · rw [dite_eq_left hi] + | step i p => + intro slots clean tape hzero x + funext node row + rcases node with u | ⟨j, node⟩ + · cases u + refine (evaluate_step_root rows repeats i p slots clean + (erase rows repeats (.step i p) slots clean tape) x row).trans ?_ + change (∑ bucket : BucketSampler.Direction (rows (n + 1)), bucket.val row * + CutSamplerReplay.evaluate F2 repeats (.step i p) (LeafDomain slots) clean + (CutSamplerReplay.erase F2 repeats (.step i p) (LeafDomain slots) + clean (tape.1 bucket)) x) = + (WholeCutSampler.evaluate rows repeats (.step i p) slots tape (.inl ()) row).val x + have heval := BucketSampler.evaluate_apply (rows (n + 1)) + (space F2 branch (n + 1) (LeafDomain slots)) + (CutSamplerRefinement.evaluate F2 repeats (.step i p) (LeafDomain slots)) + tape.1 row x + refine Eq.trans ?_ heval.symm + refine Finset.sum_congr (ι := BucketSampler.Direction (rows (n + 1))) ?_ ?_ + · ext bucket + simp only [Finset.mem_univ] + · intro bucket _ + exact congrArg (fun z : F2 => bucket.val row * z) + (CutSamplerReplay.evaluate_erase F2 repeats (.step i p) + (LeafDomain slots) clean (tape.1 bucket) (hzero.1 bucket) x) + · by_cases hji : j = i + · subst j + refine (evaluate_step_selected rows repeats i p slots clean + (erase rows repeats (.step i p) slots clean tape) x node row).trans ?_ + exact (congrFun (congrFun + (ih p (childSlots slots i) clean tape.2.1 hzero.2 + (restrictChild slots i x)) node) row).trans + (congrArg + (fun block : Fin (rows (Nodes.height node)) → H (nodeSlots (childSlots slots i) node) => + (block row).val + (restrictNode (childSlots slots i) node (restrictChild slots i x))) + (WholeCutLocality.evaluate_selected rows repeats i p slots tape node)).symm + · refine (evaluate_step_ordinary rows repeats i p slots clean + (erase rows repeats (.step i p) slots clean tape) x ⟨j, hji⟩ node row).trans ?_ + exact (congrArg + (fun block : Fin (rows (Nodes.height node)) → H (nodeSlots (childSlots slots j) node) => + (block row).val + (restrictNode (childSlots slots j) node (restrictChild slots j x))) + (WholeCutLocality.evaluate_ordinary rows repeats i p slots tape ⟨j, hji⟩ node)).symm + +theorem evaluate_erase_of_grouped_zero (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) (tape : WholeCutSampler.Tape rows repeats p slots) + (hzero : WholeCutZero.GroupedAtClean rows repeats p slots clean tape) (x : Domain slots) : + evaluate rows repeats p slots clean (erase rows repeats p slots clean tape) x = + joint (WholeCutSampler.evaluate rows repeats p slots tape) x := + evaluate_erase rows repeats p slots clean tape + ((WholeCutZero.grouped_iff rows repeats p slots clean tape).mp hzero) x + +def fullQuery (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) (tape : Tape rows repeats p slots clean) + (x : Domain slots) : Output branch n rows := + (evaluate rows repeats p slots clean tape x, PUnit.unit) + +theorem fullQuery_erase_of_grouped_zero (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) (tape : WholeCutSampler.Tape rows repeats p slots) + (hzero : WholeCutZero.GroupedAtClean rows repeats p slots clean tape) (x : Domain slots) : + fullQuery rows repeats p slots clean (erase rows repeats p slots clean tape) x = + fullJoint (WholeCutSampler.evaluate rows repeats p slots tape) x := + Prod.ext (evaluate_erase_of_grouped_zero rows repeats p slots clean tape hzero x) rfl + +end +end PerfectCompleteness.WholeCutReplay + +end + +section + +namespace PerfectCompleteness.WholeCutReplayGrouping + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays + +abbrev F2 := ZMod 2 + +noncomputable section + +variable {branch : Nat → Nat} {n m t : Nat} + +abbrev RetainedChildren (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) (clean : Fin (branch m) → Prop) := + (i : {i : Fin (branch m) // ¬ clean i}) → + CutChildGrouping.Child (C := WholeCutCalls.Index rows repeats p) + (WholeCutGrouping.cutSlots p slots) rows i.val + +def assemble (rows repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n (m + 1)) → + (slots : Slots branch n → Fin t → MixedSupport.Slot) → + (clean : Fin (branch m) → Prop) → WholeCutGrouping.Exterior rows repeats p slots → + RetainedChildren rows repeats p slots clean → WholeCutReplay.Tape rows repeats p slots clean + | _, _, .refl _, _, _, _, children => children + | _, _, .step i p, slots, clean, exterior, children => + (fun bucket => CutSamplerReplayGrouping.assemble F2 repeats (.step i p) + (LeafDomain slots) clean (exterior.1 bucket) + (fun terminal child => (children child).1 (.inl (bucket, terminal))), + assemble rows repeats p (childSlots slots i) clean exterior.2.1 + (fun child => (fun q => (children child).1 (.inr q), (children child).2)), + exterior.2.2) + +theorem assemble_splitTape (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) : + ∀ (slots : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) (tape : WholeCutSampler.Tape rows repeats p slots), + assemble rows repeats p slots clean + (WholeCutGrouping.splitTape rows repeats p slots tape).1 + (fun child => (WholeCutGrouping.splitTape rows repeats p slots tape).2 child.val) = + WholeCutReplay.erase rows repeats p slots clean tape := by + induction n generalizing m with + | zero => + have h := p.height_le + omega + | succ n ih => + cases p with + | refl => + intro slots clean tape + rfl + | step i p => + intro slots clean tape + apply Prod.ext + · funext bucket + exact CutSamplerReplayGrouping.assemble_splitTape F2 repeats (.step i p) + (LeafDomain slots) clean (tape.1 bucket) + · apply Prod.ext + · exact ih p (childSlots slots i) clean tape.2.1 + · rfl + +theorem evaluate_assemble_splitTape (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) (tape : WholeCutSampler.Tape rows repeats p slots) + (hzero : WholeCutZero.GroupedAtClean rows repeats p slots clean tape) (x : Domain slots) : + WholeCutReplay.evaluate rows repeats p slots clean + (assemble rows repeats p slots clean + (WholeCutGrouping.splitTape rows repeats p slots tape).1 + (fun child => (WholeCutGrouping.splitTape rows repeats p slots tape).2 child.val)) x = + joint (WholeCutSampler.evaluate rows repeats p slots tape) x := by + rw [assemble_splitTape] + exact WholeCutReplay.evaluate_erase_of_grouped_zero rows repeats p slots clean tape hzero x + +theorem fullQuery_assemble_splitTape (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) (tape : WholeCutSampler.Tape rows repeats p slots) + (hzero : WholeCutZero.GroupedAtClean rows repeats p slots clean tape) (x : Domain slots) : + WholeCutReplay.fullQuery rows repeats p slots clean + (assemble rows repeats p slots clean + (WholeCutGrouping.splitTape rows repeats p slots tape).1 + (fun child => (WholeCutGrouping.splitTape rows repeats p slots tape).2 child.val)) x = + fullJoint (WholeCutSampler.evaluate rows repeats p slots tape) x := + Prod.ext (evaluate_assemble_splitTape rows repeats p slots clean tape hzero x) rfl + +end +end PerfectCompleteness.WholeCutReplayGrouping + +end + +section + +namespace PerfectCompleteness.CutSamplerReplay + +open scoped BigOperators Classical +open RecursiveSpaces DescendantSpaces RecursiveSampler PointwiseSpaces + +noncomputable section + +universe u w + +variable {branch : Nat → Nat} {n m : Nat} + +def retainedSum (𝕜 : Type w) [Field 𝕜] + (A : Slots branch (m + 1) → Type u) (clean : Fin (branch m) → Prop) + (tape : (i : {i : Fin (branch m) // ¬ clean i}) → + squareSpace (space 𝕜 branch m (childFamily A i.val))) : + space 𝕜 branch (m + 1) A := + ⟨∑ i : {i : Fin (branch m) // ¬ clean i}, + pullback 𝕜 (childRestriction A i.val) (tape i).val, by + apply (space 𝕜 branch (m + 1) A).sum_mem + intro i _ + exact child_square_le_space A i.val + (Submodule.mem_map_of_mem (tape i).property)⟩ + +@[simp] theorem retainedSum_apply (𝕜 : Type w) [Field 𝕜] + (A : Slots branch (m + 1) → Type u) (clean : Fin (branch m) → Prop) + (tape : (i : {i : Fin (branch m) // ¬ clean i}) → + squareSpace (space 𝕜 branch m (childFamily A i.val))) (x : Assignment A) : + (retainedSum 𝕜 A clean tape).val x = + ∑ i : {i : Fin (branch m) // ¬ clean i}, + (tape i).val (childRestriction A i.val x) := by + simp only [retainedSum, Finset.sum_apply, PointwiseSpaces.pullback_apply] + +def evaluateSpace (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n (m + 1)) → (A : Slots branch n → Type u) → + (clean : Fin (branch m) → Prop) → Tape 𝕜 repeats p A clean → + space 𝕜 branch n A + | _, _, .refl _, A, clean, tape => retainedSum 𝕜 A clean tape + | n + 1, _, .step i p, A, clean, tape => + RecursiveSampler.combine 𝕜 A i (repeats (n + 1)) tape.1 + (fun h => evaluateSpace 𝕜 repeats p (childFamily A i) clean (tape.2 (h, false))) + (fun h => evaluateSpace 𝕜 repeats p (childFamily A i) clean (tape.2 (h, true))) + +theorem evaluateSpace_apply (𝕜 : Type w) [Field 𝕜] + (repeats : Nat → Nat) (p : Path branch n (m + 1)) : + ∀ (A : Slots branch n → Type u) (clean : Fin (branch m) → Prop) + (tape : Tape 𝕜 repeats p A clean) (x : Assignment A), + (evaluateSpace 𝕜 repeats p A clean tape).val x = + evaluate 𝕜 repeats p A clean tape x := by + induction n generalizing m with + | zero => + have h := p.height_le + omega + | succ n ih => + cases p with + | refl => + intro A clean tape x + exact retainedSum_apply 𝕜 A clean tape x + | step i p => + intro A clean tape x + rw [evaluateSpace, evaluate_step] + simp only [RecursiveSampler.combine, RecursiveSampler.combineFunction, + Finset.sum_apply, Pi.add_apply, Pi.mul_apply, PointwiseSpaces.pullback_apply] + apply congrArg (fun z => + (∑ j : OffPath i, (tape.1 j).val (childRestriction A j.val x)) + z) + apply Finset.sum_congr rfl + intro h _ + rw [ih p (childFamily A i) clean (tape.2 (h, false)), + ih p (childFamily A i) clean (tape.2 (h, true))] + +theorem evaluateSpace_val (𝕜 : Type w) [Field 𝕜] + (repeats : Nat → Nat) (p : Path branch n (m + 1)) + (A : Slots branch n → Type u) (clean : Fin (branch m) → Prop) + (tape : Tape 𝕜 repeats p A clean) : + (evaluateSpace 𝕜 repeats p A clean tape).val = evaluate 𝕜 repeats p A clean tape := + funext (evaluateSpace_apply 𝕜 repeats p A clean tape) + +theorem evaluateSpace_erase (𝕜 : Type w) [Field 𝕜] + (repeats : Nat → Nat) (p : Path branch n (m + 1)) + (A : Slots branch n → Type u) (clean : Fin (branch m) → Prop) + (tape : CutSamplerRefinement.Tape 𝕜 repeats p A) + (hzero : CutSamplerLocality.ZeroAtClean 𝕜 repeats p A clean tape) : + evaluateSpace 𝕜 repeats p A clean (erase 𝕜 repeats p A clean tape) = + CutSamplerRefinement.evaluate 𝕜 repeats p A tape := by + apply Subtype.ext + funext x + rw [evaluateSpace_apply] + exact evaluate_erase 𝕜 repeats p A clean tape hzero x + +end +end PerfectCompleteness.CutSamplerReplay + +namespace PerfectCompleteness.HierarchicalArrays + +noncomputable section + +variable {branch : Nat → Nat} {n t : Nat} + +theorem joint_injective + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (rows : Nat → Nat) : + Function.Injective (joint (slots := slots) (rows := rows)) := by + intro a b hab + funext node row + apply Subtype.ext + funext x + obtain ⟨global, rfl⟩ := restrictNode_surjective slots node x + exact congrFun (congrFun (congrFun hab global) node) row + +end +end PerfectCompleteness.HierarchicalArrays + +namespace PerfectCompleteness.WholeCutReplay + +open scoped BigOperators Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays + +noncomputable section + +variable {branch : Nat → Nat} {n m t : Nat} + +def evaluateArrays (rows repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n (m + 1)) → + (slots : Slots branch n → Fin t → MixedSupport.Slot) → + (clean : Fin (branch m) → Prop) → Tape rows repeats p slots clean → Arrays slots rows + | _, m, .refl _, slots, clean, tape => + WholeArraySampler.assemble slots rows + (fun row => CutSamplerReplay.evaluateSpace F2 repeats (.refl (m + 1)) + (LeafDomain slots) clean (fun i => (tape i).1 row)) + (fun i => if hi : ¬ clean i then (tape ⟨i, hi⟩).2 else fun _ _ => 0) + | n + 1, _, .step i p, slots, clean, tape => + WholeArraySampler.assemble slots rows + (BucketSampler.evaluate (rows (n + 1)) + (CutSamplerReplay.evaluateSpace F2 repeats (.step i p) (LeafDomain slots) clean) tape.1) + (WholeArraySampler.childrenAt slots rows i + (evaluateArrays rows repeats p (childSlots slots i) clean tape.2.1) tape.2.2) + +def bucketSpace (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n (m + 1)) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (tape : Tape rows repeats (.step i p) slots clean) + (bucket : BucketSampler.Direction (rows (n + 1))) : H slots := + CutSamplerReplay.evaluateSpace F2 repeats (.step i p) (LeafDomain slots) clean + (tape.1 bucket) + +theorem bucketSpace_apply (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n (m + 1)) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (tape : Tape rows repeats (.step i p) slots clean) + (bucket : BucketSampler.Direction (rows (n + 1))) (x : Domain slots) : + (bucketSpace rows repeats i p slots clean tape bucket).val x = + CutSamplerReplay.evaluate F2 repeats (.step i p) (LeafDomain slots) clean + (tape.1 bucket) x := + CutSamplerReplay.evaluateSpace_apply F2 repeats (.step i p) (LeafDomain slots) clean + (tape.1 bucket) x + +theorem evaluateArrays_step_root (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n (m + 1)) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (tape : Tape rows repeats (.step i p) slots clean) : + evaluateArrays rows repeats (.step i p) slots clean tape (.inl ()) = + BucketSampler.evaluate (rows (n + 1)) + (CutSamplerReplay.evaluateSpace F2 repeats (.step i p) (LeafDomain slots) clean) + tape.1 := rfl + +theorem evaluateArrays_step_selected (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n (m + 1)) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (tape : Tape rows repeats (.step i p) slots clean) (node : Nodes branch n) : + evaluateArrays rows repeats (.step i p) slots clean tape (.inr (i, node)) = + evaluateArrays rows repeats p (childSlots slots i) clean tape.2.1 node := by + exact congrFun (WholeArraySampler.childrenAt_selected slots rows i + (evaluateArrays rows repeats p (childSlots slots i) clean tape.2.1) tape.2.2) node + +theorem evaluateArrays_step_ordinary (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n (m + 1)) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (tape : Tape rows repeats (.step i p) slots clean) + (j : RecursiveSampler.OffPath i) (node : Nodes branch n) : + evaluateArrays rows repeats (.step i p) slots clean tape (.inr (j.val, node)) = + tape.2.2 j node := by + exact congrFun (WholeArraySampler.childrenAt_ordinary slots rows i + (evaluateArrays rows repeats p (childSlots slots i) clean tape.2.1) tape.2.2 j) node + +theorem joint_evaluateArrays_apply (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) : + ∀ (slots : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) (tape : Tape rows repeats p slots clean) + (x : Domain slots), + joint (evaluateArrays rows repeats p slots clean tape) x = + evaluate rows repeats p slots clean tape x := by + induction n generalizing m with + | zero => + have h := p.height_le + omega + | succ n ih => + cases p with + | refl => + intro slots clean tape x + funext node row + rcases node with u | ⟨i, node⟩ + · cases u + exact CutSamplerReplay.evaluateSpace_apply F2 repeats (.refl (n + 1)) + (LeafDomain slots) clean (fun i => (tape i).1 row) x + · change + (((if hi : ¬ clean i then (tape ⟨i, hi⟩).2 else fun _ _ => 0) : + Arrays (childSlots slots i) rows) node row).val + (restrictNode (childSlots slots i) node (restrictChild slots i x)) = + (if hi : ¬ clean i then + ((tape ⟨i, hi⟩).2 node row).val + (restrictNode (childSlots slots i) node (restrictChild slots i x)) + else 0) + by_cases hi : ¬ clean i + · simp only [dite_eq_left hi] + · simp only [dite_eq_right hi] + rfl + | step i p => + intro slots clean tape x + funext node row + rcases node with u | ⟨j, node⟩ + · cases u + change (BucketSampler.evaluate (rows (n + 1)) + (CutSamplerReplay.evaluateSpace F2 repeats (.step i p) (LeafDomain slots) clean) + tape.1 row).val x = + ∑ bucket : BucketSampler.Direction (rows (n + 1)), bucket.val row * + CutSamplerReplay.evaluate F2 repeats (.step i p) (LeafDomain slots) + clean (tape.1 bucket) x + have heval := BucketSampler.evaluate_apply (rows (n + 1)) + (space F2 branch (n + 1) (LeafDomain slots)) + (CutSamplerReplay.evaluateSpace F2 repeats (.step i p) (LeafDomain slots) clean) + tape.1 row x + refine heval.trans ?_ + refine Finset.sum_congr (ι := BucketSampler.Direction (rows (n + 1))) ?_ ?_ + · ext bucket + simp only [Finset.mem_univ] + · intro bucket _ + exact congrArg (fun z : F2 => bucket.val row * z) + (CutSamplerReplay.evaluateSpace_apply F2 repeats (.step i p) + (LeafDomain slots) clean (tape.1 bucket) x) + · by_cases hji : j = i + · subst j + exact (congrArg + (fun block : Fin (rows (Nodes.height node)) → H (nodeSlots (childSlots slots i) node) => + (block row).val + (restrictNode (childSlots slots i) node (restrictChild slots i x))) + (evaluateArrays_step_selected rows repeats i p slots clean tape node)).trans + ((congrFun (congrFun + (ih p (childSlots slots i) clean tape.2.1 (restrictChild slots i x)) node) row).trans + (evaluate_step_selected rows repeats i p slots clean tape x node row).symm) + · exact (congrArg + (fun block : Fin (rows (Nodes.height node)) → H (nodeSlots (childSlots slots j) node) => + (block row).val + (restrictNode (childSlots slots j) node (restrictChild slots j x))) + (evaluateArrays_step_ordinary rows repeats i p slots clean tape ⟨j, hji⟩ node)).trans + (evaluate_step_ordinary rows repeats i p slots clean tape x ⟨j, hji⟩ node row).symm + +theorem joint_evaluateArrays (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) (tape : Tape rows repeats p slots clean) : + joint (evaluateArrays rows repeats p slots clean tape) = + evaluate rows repeats p slots clean tape := + funext (joint_evaluateArrays_apply rows repeats p slots clean tape) + +theorem fullJoint_evaluateArrays (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) (tape : Tape rows repeats p slots clean) : + fullJoint (evaluateArrays rows repeats p slots clean tape) = + fullQuery rows repeats p slots clean tape := by + funext x + exact Prod.ext (joint_evaluateArrays_apply rows repeats p slots clean tape x) rfl + +theorem evaluateArrays_erase (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) (tape : WholeCutSampler.Tape rows repeats p slots) + (hzero : WholeCutZero.ZeroAtClean rows repeats p slots clean tape) : + evaluateArrays rows repeats p slots clean (erase rows repeats p slots clean tape) = + WholeCutSampler.evaluate rows repeats p slots tape := by + apply HierarchicalArrays.joint_injective slots rows + funext x + rw [joint_evaluateArrays_apply] + exact evaluate_erase rows repeats p slots clean tape hzero x + +theorem evaluateArrays_erase_of_grouped_zero (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) (tape : WholeCutSampler.Tape rows repeats p slots) + (hzero : WholeCutZero.GroupedAtClean rows repeats p slots clean tape) : + evaluateArrays rows repeats p slots clean (erase rows repeats p slots clean tape) = + WholeCutSampler.evaluate rows repeats p slots tape := + evaluateArrays_erase rows repeats p slots clean tape + ((WholeCutZero.grouped_iff rows repeats p slots clean tape).mp hzero) + +theorem bucketSpace_erase (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n (m + 1)) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (tape : WholeCutSampler.Tape rows repeats (.step i p) slots) + (hzero : WholeCutZero.ZeroAtClean rows repeats (.step i p) slots clean tape) + (bucket : BucketSampler.Direction (rows (n + 1))) : + bucketSpace rows repeats i p slots clean + (erase rows repeats (.step i p) slots clean tape) bucket = + CutSamplerRefinement.evaluate F2 repeats (.step i p) (LeafDomain slots) (tape.1 bucket) := + CutSamplerReplay.evaluateSpace_erase F2 repeats (.step i p) (LeafDomain slots) clean + (tape.1 bucket) (hzero.1 bucket) + +end +end PerfectCompleteness.WholeCutReplay + +namespace PerfectCompleteness.WholeCutReplayGrouping + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays + +noncomputable section + +variable {branch : Nat → Nat} {n m t : Nat} + +theorem evaluateArrays_assemble_splitTape (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) (tape : WholeCutSampler.Tape rows repeats p slots) + (hzero : WholeCutZero.GroupedAtClean rows repeats p slots clean tape) : + WholeCutReplay.evaluateArrays rows repeats p slots clean + (assemble rows repeats p slots clean + (WholeCutGrouping.splitTape rows repeats p slots tape).1 + (fun child => (WholeCutGrouping.splitTape rows repeats p slots tape).2 child.val)) = + WholeCutSampler.evaluate rows repeats p slots tape := by + rw [assemble_splitTape] + exact WholeCutReplay.evaluateArrays_erase_of_grouped_zero rows repeats p slots clean tape hzero + +end +end PerfectCompleteness.WholeCutReplayGrouping + +end + +section + +namespace PerfectCompleteness.WholeCutReplayTransport + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open CutSamplerKeyLocality +open scoped BigOperators Classical + +noncomputable section + +abbrev F2 := ZMod 2 + +variable {branch : Nat → Nat} {n m t : Nat} + +def arraysTransport (rows : Nat → Nat) + (slots target : Slots branch n → Fin t → MixedSupport.Slot) + (e : ∀ s, LeafDomain slots s ≃ LeafDomain target s) + (arrays : Arrays slots rows) : Arrays target rows := + fun node row => (RecursiveSpaceEquiv.spaceEquiv (𝕜 := F2) + (fun s => e ((Nodes.path node).slotEmbedding s))).symm (arrays node row) + +theorem joint_arraysTransport (rows : Nat → Nat) + (slots target : Slots branch n → Fin t → MixedSupport.Slot) + (e : ∀ s, LeafDomain slots s ≃ LeafDomain target s) + (arrays : Arrays slots rows) (x : Domain slots) (y : Domain target) + (hagree : ∀ s, e s (x s) = y s) : + joint (arraysTransport rows slots target e arrays) y = joint arrays x := by + funext node row + change (arrays node row).val + (project (fun s => (e ((Nodes.path node).slotEmbedding s)).symm) + (restrictNode target node y)) = + (arrays node row).val (restrictNode slots node x) + apply congrArg (arrays node row).val + funext s + exact (congrArg (e ((Nodes.path node).slotEmbedding s)).symm + (hagree ((Nodes.path node).slotEmbedding s))).symm.trans + ((e ((Nodes.path node).slotEmbedding s)).symm_apply_apply + (x ((Nodes.path node).slotEmbedding s))) + +def transport (rows repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n (m + 1)) → + (slots target : Slots branch n → Fin t → MixedSupport.Slot) → + (clean : Fin (branch m) → Prop) → + (∀ s, keptLeaf p clean s → LeafDomain slots s ≃ LeafDomain target s) → + WholeCutReplay.Tape rows repeats p slots clean → + WholeCutReplay.Tape rows repeats p target clean + | _, _, .refl _, slots, target, _, e, tape => + fun i => + (fun q => (RecursiveSpaceEquiv.squareEquiv (𝕜 := F2) + (fun s => e (i.val, s) i.property)).symm ((tape i).1 q), + arraysTransport rows (childSlots slots i.val) (childSlots target i.val) + (fun s => e (i.val, s) i.property) (tape i).2) + | _, _, .step i p, slots, target, clean, e, tape => + (fun v => CutSamplerReplayTransport.transport F2 repeats (.step i p) + (LeafDomain slots) (LeafDomain target) clean e (tape.1 v), + transport rows repeats p (childSlots slots i) (childSlots target i) clean + (fun s hs => e (i, s) (Or.inr hs)) tape.2.1, + fun j => arraysTransport rows (childSlots slots j.val) (childSlots target j.val) + (fun s => e (j.val, s) (Or.inl j.property)) (tape.2.2 j)) + +theorem evaluate_transport (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) : + ∀ (slots target : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (e : ∀ s, keptLeaf p clean s → LeafDomain slots s ≃ LeafDomain target s) + (tape : WholeCutReplay.Tape rows repeats p slots clean) + (x : Domain slots) (y : Domain target), + (∀ s hs, e s hs (x s) = y s) → + WholeCutReplay.evaluate rows repeats p target clean + (transport rows repeats p slots target clean e tape) y = + WholeCutReplay.evaluate rows repeats p slots clean tape x := by + induction n generalizing m with + | zero => + have h := p.height_le + omega + | succ n ih => + cases p with + | refl => + intro slots target clean e tape x y hagree + funext node row + rcases node with u | ⟨i, node⟩ + · cases u + refine (WholeCutReplay.evaluate_refl_root rows repeats target clean + (transport rows repeats (.refl (n + 1)) slots target clean e tape) y row).trans ?_ + refine Eq.trans ?_ (WholeCutReplay.evaluate_refl_root + rows repeats slots clean tape x row).symm + apply Finset.sum_congr rfl + intro i _ + exact CutSamplerReplayTransport.squareEquiv_symm_eval_of_agree F2 + (fun s => e (i.val, s) i.property) ((tape i).1 row) + (restrictChild slots i.val x) (restrictChild target i.val y) + (fun s => hagree (i.val, s) i.property) + · refine (WholeCutReplay.evaluate_refl_child rows repeats target clean + (transport rows repeats (.refl (n + 1)) slots target clean e tape) + y i node row).trans ?_ + refine Eq.trans ?_ (WholeCutReplay.evaluate_refl_child + rows repeats slots clean tape x i node row).symm + by_cases hi : ¬ clean i + · simp only [dite_eq_left hi] + exact congrFun (congrFun + (joint_arraysTransport rows (childSlots slots i) (childSlots target i) + (fun s => e (i, s) hi) (tape ⟨i, hi⟩).2 + (restrictChild slots i x) (restrictChild target i y) + (fun s => hagree (i, s) hi)) node) row + · simp only [dite_eq_right hi] + | step i p => + intro slots target clean e tape x y hagree + funext node row + rcases node with u | ⟨j, node⟩ + · cases u + refine (WholeCutReplay.evaluate_step_root rows repeats i p target clean + (transport rows repeats (.step i p) slots target clean e tape) y row).trans ?_ + refine Eq.trans ?_ (WholeCutReplay.evaluate_step_root + rows repeats i p slots clean tape x row).symm + apply Finset.sum_congr rfl + intro bucket _ + apply congrArg (fun z : F2 => bucket.val row * z) + exact CutSamplerReplayTransport.evaluate_transport F2 repeats (.step i p) + (LeafDomain slots) (LeafDomain target) clean e (tape.1 bucket) x y hagree + · by_cases hji : j = i + · subst j + refine (WholeCutReplay.evaluate_step_selected rows repeats i p target clean + (transport rows repeats (.step i p) slots target clean e tape) + y node row).trans ?_ + refine Eq.trans ?_ (WholeCutReplay.evaluate_step_selected + rows repeats i p slots clean tape x node row).symm + exact congrFun (congrFun + (ih p (childSlots slots i) (childSlots target i) clean + (fun s hs => e (i, s) (Or.inr hs)) tape.2.1 + (restrictChild slots i x) (restrictChild target i y) + (fun s hs => hagree (i, s) (Or.inr hs))) node) row + · rw [WholeCutReplay.evaluate_step_ordinary rows repeats i p target clean + (transport rows repeats (.step i p) slots target clean e tape) + y ⟨j, hji⟩ node row, + WholeCutReplay.evaluate_step_ordinary rows repeats i p slots clean tape + x ⟨j, hji⟩ node row] + exact congrFun (congrFun + (joint_arraysTransport rows (childSlots slots j) (childSlots target j) + (fun s => e (j, s) (Or.inl hji)) (tape.2.2 ⟨j, hji⟩) + (restrictChild slots j x) (restrictChild target j y) + (fun s => hagree (j, s) (Or.inl hji))) node) row + +theorem fullQuery_transport (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots target : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (e : ∀ s, keptLeaf p clean s → LeafDomain slots s ≃ LeafDomain target s) + (tape : WholeCutReplay.Tape rows repeats p slots clean) + (x : Domain slots) (y : Domain target) + (hagree : ∀ s hs, e s hs (x s) = y s) : + WholeCutReplay.fullQuery rows repeats p target clean + (transport rows repeats p slots target clean e tape) y = + WholeCutReplay.fullQuery rows repeats p slots clean tape x := + Prod.ext (evaluate_transport rows repeats p slots target clean e tape x y hagree) rfl + +end +end PerfectCompleteness.WholeCutReplayTransport + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Foundations/WholeReplaySubtreeLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Foundations/WholeReplaySubtreeLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..0fe82120944c462f2d2eba3efe70ce12853f1a5f --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Foundations/WholeReplaySubtreeLemmas.lean @@ -0,0 +1,357 @@ +import OAI.Computability.PerfectCompleteness.Foundations.WholeArraySubtreeSplit +import OAI.Computability.PerfectCompleteness.Foundations.WholeCutReplayLemmas +import OAI.Computability.PerfectCompleteness.Machines.OwnInputReferenceLemmas +import OAI.Computability.PerfectCompleteness.Machines.WholeArrayInteriorOwnInputLaw + +namespace OAI + +section + +namespace PerfectCompleteness.WholeReplaySubtree + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open WholeArraySubtreeSplit + +noncomputable section + +abbrev F2 := ZMod 2 + +variable {branch : Nat → Nat} {n k m t : Nat} + +def extract (rows repeats : Nat → Nat) : + {n k m : Nat} → (pUp : Path branch n k) → (pDown : Path branch k (m + 1)) → + (slots : Slots branch n → Fin t → MixedSupport.Slot) → + (clean : Fin (branch m) → Prop) → + WholeCutReplay.Tape rows repeats (pUp.append pDown) slots clean → + WholeCutReplay.Tape rows repeats pDown (subtreeSlots pUp slots) clean + | _, _, _, .refl _, _, _, _, tape => tape + | _, _, _, .step i pUp, pDown, slots, clean, tape => + extract rows repeats pUp pDown (childSlots slots i) clean tape.2.1 + +@[simp] theorem extract_refl (rows repeats : Nat → Nat) (pDown : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) (clean : Fin (branch m) → Prop) + (tape : WholeCutReplay.Tape rows repeats pDown slots clean) : + extract rows repeats (.refl n) pDown slots clean tape = tape := by + cases pDown <;> rfl + +@[simp] theorem extract_step (rows repeats : Nat → Nat) (i : Fin (branch n)) + (pUp : Path branch n k) (pDown : Path branch k (m + 1)) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) (clean : Fin (branch m) → Prop) + (tape : WholeCutReplay.Tape rows repeats ((Path.step i pUp).append pDown) slots clean) : + extract rows repeats (.step i pUp) pDown slots clean tape = + extract rows repeats pUp pDown (childSlots slots i) clean tape.2.1 := rfl + +theorem restrictArrays_evaluateArrays (rows repeats : Nat → Nat) (pUp : Path branch n k) : + ∀ {m : Nat} (pDown : Path branch k (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) (clean : Fin (branch m) → Prop) + (tape : WholeCutReplay.Tape rows repeats (pUp.append pDown) slots clean), + restrictArrays rows pUp slots + (WholeCutReplay.evaluateArrays rows repeats (pUp.append pDown) slots clean tape) = + WholeCutReplay.evaluateArrays rows repeats pDown (subtreeSlots pUp slots) clean + (extract rows repeats pUp pDown slots clean tape) := by + induction pUp with + | refl n => + intro m pDown slots clean tape + cases pDown <;> rfl + | step i pUp ih => + intro m pDown slots clean tape + have hselected := funext (WholeCutReplay.evaluateArrays_step_selected rows repeats i + (pUp.append pDown) slots clean tape) + exact (congrArg (restrictArrays rows pUp (childSlots slots i)) hselected).trans + (ih pDown (childSlots slots i) clean tape.2.1) + +def restrictBlocks (rows : Nat → Nat) : + {n k : Nat} → Path branch n k → + ((node : Nodes branch n) → Block rows node) → (node : Nodes branch k) → Block rows node + | _, _, .refl _, blocks => blocks + | _, _, .step i pUp, blocks => + restrictBlocks rows pUp (fun node => blocks (.inr (i, node))) + +theorem restrictBlocks_joint (rows : Nat → Nat) (pUp : Path branch n k) : + ∀ (slots : Slots branch n → Fin t → MixedSupport.Slot) + (arrays : Arrays slots rows) (x : Domain slots), + restrictBlocks rows pUp (joint arrays x) = + joint (restrictArrays rows pUp slots arrays) (pUp.restriction (LeafDomain slots) x) := by + induction pUp with + | refl n => + intro slots arrays x + rfl + | step i pUp ih => + intro slots arrays x + exact ih (childSlots slots i) (fun node => arrays (.inr (i, node))) + (restrictChild slots i x) + +theorem evaluate_extract (rows repeats : Nat → Nat) + (pUp : Path branch n k) (pDown : Path branch k (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) (clean : Fin (branch m) → Prop) + (tape : WholeCutReplay.Tape rows repeats (pUp.append pDown) slots clean) (x : Domain slots) : + restrictBlocks rows pUp + (WholeCutReplay.evaluate rows repeats (pUp.append pDown) slots clean tape x) = + WholeCutReplay.evaluate rows repeats pDown (subtreeSlots pUp slots) clean + (extract rows repeats pUp pDown slots clean tape) (pUp.restriction (LeafDomain slots) x) := by + calc + _ = restrictBlocks rows pUp + (joint (WholeCutReplay.evaluateArrays rows repeats (pUp.append pDown) slots clean tape) x) := + congrArg (restrictBlocks rows pUp) + (WholeCutReplay.joint_evaluateArrays_apply rows repeats (pUp.append pDown) + slots clean tape x).symm + _ = joint (restrictArrays rows pUp slots + (WholeCutReplay.evaluateArrays rows repeats (pUp.append pDown) slots clean tape)) + (pUp.restriction (LeafDomain slots) x) := + restrictBlocks_joint rows pUp slots _ x + _ = joint (WholeCutReplay.evaluateArrays rows repeats pDown (subtreeSlots pUp slots) clean + (extract rows repeats pUp pDown slots clean tape)) + (pUp.restriction (LeafDomain slots) x) := + congrArg (fun arrays => joint arrays (pUp.restriction (LeafDomain slots) x)) + (restrictArrays_evaluateArrays rows repeats pUp pDown slots clean tape) + _ = _ := WholeCutReplay.joint_evaluateArrays_apply rows repeats pDown + (subtreeSlots pUp slots) clean (extract rows repeats pUp pDown slots clean tape) + (pUp.restriction (LeafDomain slots) x) + +def rootBuckets (rows repeats : Nat → Nat) : + {k m : Nat} → (pDown : Path branch k (m + 1)) → m + 1 < k → + (slots : Slots branch k → Fin t → MixedSupport.Slot) → + (clean : Fin (branch m) → Prop) → WholeCutReplay.Tape rows repeats pDown slots clean → + BucketSampler.Direction (rows k) → H slots + | _, _, .refl _, hproper, _, _, _, _ => False.elim ((Nat.lt_irrefl _) hproper) + | _, _, .step i pDown, _, slots, clean, tape, bucket => + WholeCutReplay.bucketSpace rows repeats i pDown slots clean tape bucket + +@[simp] theorem rootBuckets_step (rows repeats : Nat → Nat) (i : Fin (branch k)) + (pDown : Path branch k (m + 1)) (hproper : m + 1 < k + 1) + (slots : Slots branch (k + 1) → Fin t → MixedSupport.Slot) (clean : Fin (branch m) → Prop) + (tape : WholeCutReplay.Tape rows repeats (.step i pDown) slots clean) + (bucket : BucketSampler.Direction (rows (k + 1))) : + rootBuckets rows repeats (.step i pDown) hproper slots clean tape bucket = + WholeCutReplay.bucketSpace rows repeats i pDown slots clean tape bucket := rfl + +def buckets (rows repeats : Nat → Nat) + (pUp : Path branch n k) (pDown : Path branch k (m + 1)) (hproper : m + 1 < k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) (clean : Fin (branch m) → Prop) + (tape : WholeCutReplay.Tape rows repeats (pUp.append pDown) slots clean) : + BucketSampler.Direction (rows k) → H (subtreeSlots pUp slots) := + rootBuckets rows repeats pDown hproper (subtreeSlots pUp slots) clean + (extract rows repeats pUp pDown slots clean tape) + +def knownBuckets (rows repeats : Nat → Nat) + (pUp : Path branch n k) (pDown : Path branch k (m + 1)) (hproper : m + 1 < k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) (clean : Fin (branch m) → Prop) + (W : Submodule F2 (Fin (rows k) → F2)) + (tape : WholeCutReplay.Tape rows repeats (pUp.append pDown) slots clean) : + HiddenBucketBias.VisibleDirection W → H (subtreeSlots pUp slots) := + fun v => buckets rows repeats pUp pDown hproper slots clean tape v.val + +def knownBucketsAtNode (rows repeats : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) (upper : Nodes branch n) + (pDown : Path branch (Nodes.height upper) (m + 1)) (hproper : m + 1 < Nodes.height upper) + (clean : Fin (branch m) → Prop) (W : Submodule F2 (OwnInputReference.UpperVector rows upper)) + (tape : WholeCutReplay.Tape rows repeats ((Nodes.path upper).append pDown) slots clean) : + HiddenBucketBias.VisibleDirection W → OwnInputReference.UpperSpace slots upper := + knownBuckets rows repeats (Nodes.path upper) pDown hproper slots clean W tape + +@[simp] theorem knownBucketsAtNode_apply (rows repeats : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) (upper : Nodes branch n) + (pDown : Path branch (Nodes.height upper) (m + 1)) (hproper : m + 1 < Nodes.height upper) + (clean : Fin (branch m) → Prop) (W : Submodule F2 (OwnInputReference.UpperVector rows upper)) + (tape : WholeCutReplay.Tape rows repeats ((Nodes.path upper).append pDown) slots clean) + (v : HiddenBucketBias.VisibleDirection W) : + knownBucketsAtNode rows repeats slots upper pDown hproper clean W tape v = + rootBuckets rows repeats pDown hproper (nodeSlots slots upper) clean + (extract rows repeats (Nodes.path upper) pDown slots clean tape) v.val := rfl + +end +end PerfectCompleteness.WholeReplaySubtree + +end + +section + +namespace PerfectCompleteness.WholeCutSubtree + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open WholeArraySubtreeSplit + +abbrev F2 := ZMod 2 + +variable {branch : Nat → Nat} {n k m t : Nat} + +def extract (rows repeats : Nat → Nat) : + {n k m : Nat} → (pUp : Path branch n k) → (pDown : Path branch k m) → + (slots : Slots branch n → Fin t → MixedSupport.Slot) → + WholeCutSampler.Tape rows repeats (pUp.append pDown) slots → + WholeCutSampler.Tape rows repeats pDown (subtreeSlots pUp slots) + | _, _, _, .refl _, _, _, tape => tape + | _, _, _, .step i pUp, pDown, slots, tape => + extract rows repeats pUp pDown (childSlots slots i) tape.2.1 + +@[simp] theorem extract_refl (rows repeats : Nat → Nat) (pDown : Path branch n m) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (tape : WholeCutSampler.Tape rows repeats pDown slots) : + extract rows repeats (.refl n) pDown slots tape = tape := rfl + +@[simp] theorem extract_step (rows repeats : Nat → Nat) (i : Fin (branch n)) + (pUp : Path branch n k) (pDown : Path branch k m) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (tape : WholeCutSampler.Tape rows repeats ((Path.step i pUp).append pDown) slots) : + extract rows repeats (.step i pUp) pDown slots tape = + extract rows repeats pUp pDown (childSlots slots i) tape.2.1 := rfl + +theorem erase_extract (rows repeats : Nat → Nat) (pUp : Path branch n k) : + ∀ {m : Nat} (pDown : Path branch k (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (tape : WholeCutSampler.Tape rows repeats (pUp.append pDown) slots), + WholeReplaySubtree.extract rows repeats pUp pDown slots clean + (WholeCutReplay.erase rows repeats (pUp.append pDown) slots clean tape) = + WholeCutReplay.erase rows repeats pDown (subtreeSlots pUp slots) clean + (extract rows repeats pUp pDown slots tape) := by + induction pUp with + | refl n => + intro m pDown slots clean tape + cases pDown <;> rfl + | step i pUp ih => + intro m pDown slots clean tape + exact ih pDown (childSlots slots i) clean tape.2.1 + +theorem zero_extract (rows repeats : Nat → Nat) (pUp : Path branch n k) : + ∀ {m : Nat} (pDown : Path branch k (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (tape : WholeCutSampler.Tape rows repeats (pUp.append pDown) slots), + WholeCutZero.ZeroAtClean rows repeats (pUp.append pDown) slots clean tape → + WholeCutZero.ZeroAtClean rows repeats pDown (subtreeSlots pUp slots) clean + (extract rows repeats pUp pDown slots tape) := by + induction pUp with + | refl n => intros; assumption + | step i pUp ih => + intro m pDown slots clean tape hzero + exact ih pDown (childSlots slots i) clean tape.2.1 hzero.2 + +theorem collapse_extract (rows repeats : Nat → Nat) (pUp : Path branch n k) : + ∀ {m : Nat} (pDown : Path branch k m) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (tape : WholeCutSampler.Tape rows repeats (pUp.append pDown) slots), + WholeCutSampler.collapse rows repeats pDown (subtreeSlots pUp slots) + (extract rows repeats pUp pDown slots tape) = + WholeArraySubtreeSplit.extract rows repeats pUp pDown slots + (WholeCutSampler.collapse rows repeats (pUp.append pDown) slots tape) := by + induction pUp with + | refl n => intros; rfl + | step i pUp ih => + intro m pDown slots tape + exact ih pDown (childSlots slots i) tape.2.1 + +def rootBuckets (rows repeats : Nat → Nat) : + {k m : Nat} → (pDown : Path branch k m) → m < k → + (slots : Slots branch k → Fin t → MixedSupport.Slot) → + WholeCutSampler.Tape rows repeats pDown slots → + BucketSampler.Direction (rows k) → H slots + | _, _, .refl _, hproper, _, _, _ => False.elim ((Nat.lt_irrefl _) hproper) + | _, _, .step i pDown, _, slots, tape, bucket => + CutSamplerRefinement.evaluate F2 repeats (.step i pDown) (LeafDomain slots) + (tape.1 bucket) + +def knownBuckets (rows repeats : Nat → Nat) + (pUp : Path branch n k) (pDown : Path branch k m) (hproper : m < k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (W : Submodule F2 (Fin (rows k) → F2)) + (tape : WholeCutSampler.Tape rows repeats (pUp.append pDown) slots) : + HiddenBucketBias.VisibleDirection W → H (subtreeSlots pUp slots) := + fun v => rootBuckets rows repeats pDown hproper (subtreeSlots pUp slots) + (extract rows repeats pUp pDown slots tape) v.val + +theorem rootBuckets_erase (rows repeats : Nat → Nat) + (pDown : Path branch k (m + 1)) (hproper : m + 1 < k) + (slots : Slots branch k → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (tape : WholeCutSampler.Tape rows repeats pDown slots) + (hzero : WholeCutZero.ZeroAtClean rows repeats pDown slots clean tape) : + WholeReplaySubtree.rootBuckets rows repeats pDown hproper slots clean + (WholeCutReplay.erase rows repeats pDown slots clean tape) = + rootBuckets rows repeats pDown hproper slots tape := by + cases pDown with + | refl => exact False.elim ((Nat.lt_irrefl _) hproper) + | step i pDown => + funext bucket + exact WholeCutReplay.bucketSpace_erase rows repeats i pDown slots clean tape hzero bucket + +theorem knownBuckets_erase (rows repeats : Nat → Nat) + (pUp : Path branch n k) (pDown : Path branch k (m + 1)) (hproper : m + 1 < k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) (W : Submodule F2 (Fin (rows k) → F2)) + (tape : WholeCutSampler.Tape rows repeats (pUp.append pDown) slots) + (hzero : WholeCutZero.ZeroAtClean rows repeats (pUp.append pDown) slots clean tape) : + WholeReplaySubtree.knownBuckets rows repeats pUp pDown hproper slots clean W + (WholeCutReplay.erase rows repeats (pUp.append pDown) slots clean tape) = + knownBuckets rows repeats pUp pDown hproper slots W tape := by + funext v + unfold WholeReplaySubtree.knownBuckets WholeReplaySubtree.buckets knownBuckets + rw [erase_extract, rootBuckets_erase rows repeats pDown hproper + (subtreeSlots pUp slots) clean (extract rows repeats pUp pDown slots tape) + (zero_extract rows repeats pUp pDown slots clean tape hzero)] + +theorem knownBuckets_eq_original (rows repeats : Nat → Nat) + (pUp : Path branch n k) (pDown : Path branch k m) (hproper : m < k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (W : Submodule F2 (Fin (rows k) → F2)) + (tape : WholeCutSampler.Tape rows repeats (pUp.append pDown) slots) : + knownBuckets rows repeats pUp pDown hproper slots W tape = + fun v => RecursiveSampler.evaluate F2 repeats pDown (LeafDomain (subtreeSlots pUp slots)) + ((WholeArrayPositiveSplit.split rows repeats pUp pDown hproper slots W + (WholeCutSampler.collapse rows repeats (pUp.append pDown) slots tape)).2.1 v) := by + cases pDown with + | refl => exact False.elim ((Nat.lt_irrefl _) hproper) + | step i pDown => + funext v + change CutSamplerRefinement.evaluate F2 repeats (.step i pDown) + (LeafDomain (subtreeSlots pUp slots)) + ((extract rows repeats pUp (.step i pDown) slots tape).1 v.val) = + RecursiveSampler.evaluate F2 repeats (.step i pDown) + (LeafDomain (subtreeSlots pUp slots)) + ((WholeArraySubtreeSplit.extract rows repeats pUp (.step i pDown) slots + (WholeCutSampler.collapse rows repeats (pUp.append (.step i pDown)) slots tape)) + (.inl ()) v.val) + rw [← collapse_extract] + rfl + +def knownBucketsAtNode (rows repeats : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) (upper : Nodes branch n) + (pDown : Path branch (Nodes.height upper) m) (hproper : m < Nodes.height upper) + (W : Submodule F2 (OwnInputReference.UpperVector rows upper)) + (tape : WholeCutSampler.Tape rows repeats ((Nodes.path upper).append pDown) slots) : + HiddenBucketBias.VisibleDirection W → OwnInputReference.UpperSpace slots upper := + knownBuckets rows repeats (Nodes.path upper) pDown hproper slots W tape + +theorem knownBucketsAtNode_erase (rows repeats : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) (upper : Nodes branch n) + (pDown : Path branch (Nodes.height upper) (m + 1)) (hproper : m + 1 < Nodes.height upper) + (clean : Fin (branch m) → Prop) + (W : Submodule F2 (OwnInputReference.UpperVector rows upper)) + (tape : WholeCutSampler.Tape rows repeats ((Nodes.path upper).append pDown) slots) + (hzero : WholeCutZero.ZeroAtClean rows repeats ((Nodes.path upper).append pDown) + slots clean tape) : + WholeReplaySubtree.knownBucketsAtNode rows repeats slots upper pDown hproper clean W + (WholeCutReplay.erase rows repeats ((Nodes.path upper).append pDown) slots clean tape) = + knownBucketsAtNode rows repeats slots upper pDown hproper W tape := + knownBuckets_erase rows repeats (Nodes.path upper) pDown hproper slots clean W tape hzero + +theorem knownBucketsAtNode_eq_ownInput (rows repeats : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (upper lower : Nodes branch n) (cut : OwnInputReference.Cut upper lower) + (W : Submodule F2 (OwnInputReference.UpperVector rows upper)) + (a : OwnInputReference.LowerVector rows lower) + (tape : WholeCutSampler.Tape rows repeats ((Nodes.path upper).append cut.path) slots) : + knownBucketsAtNode rows repeats slots upper cut.path cut.proper W tape = + (WholeArrayInteriorOwnInputLaw.ownInput rows repeats slots upper lower cut W a + (WholeCutSampler.collapse rows repeats ((Nodes.path upper).append cut.path) slots tape)).knownBuckets := + knownBuckets_eq_original rows repeats (Nodes.path upper) cut.path cut.proper slots W tape + +end +end PerfectCompleteness.WholeCutSubtree + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/AcceptanceMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/AcceptanceMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..313e8bb6115df3264eb2e2ce707a604ea60eb742 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/AcceptanceMachine.lean @@ -0,0 +1,439 @@ +import OAI.Computability.PerfectCompleteness.Machines.InitializationTemplateLemmas +import OAI.Computability.PerfectCompleteness.Machines.OrClosure +import OAI.Computability.PerfectCompleteness.Machines.TransitionMachine + +namespace OAI + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.AcceptanceMachine + + +open Turing MachineComposition TermMachine TransitionTemplate PostfixModel + +inductive RootLabel + | seed | scan | restore + | lookup (label : LookupLabel) + deriving DecidableEq, Fintype + +def widthAddress (coefficient offset : Nat) (input : Input) : Nat := + coefficient * input.capacity + offset + +def rootProgram (coefficient offset : Nat) : RootLabel → TM2.Stmt Alphabet RootLabel State + | .seed => MachineUnaryAffineAt.seed .address offset .scan + | .scan => MachineUnaryAffineAt.scan .capacity .scratch .address coefficient .scan .restore + | .restore => Reduction.MachineTransfer.loopAt .scratch .capacity id false .restore + (some (.lookup (.lookup (.run .copyFirst)))) + | .lookup label => MachineSubroutine.statement RootLabel.lookup none (lookupProgram 0 label) + +def rootSteps (coefficient offset : Nat) (input : Input) : Nat := + (2 * (input.capacity + 1) + 1) + + (MachinePreservingLookupClean.steps input.roots (widthAddress coefficient offset input) + + rootLookup input.roots (widthAddress coefficient offset input) + 4) + +private 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 rootTrace (coefficient offset : Nat) (input : Input) + (present : input.roots[widthAddress coefficient offset input]? = + some (rootLookup input.roots (widthAddress coefficient offset input))) + (base : Tape → List Bool) (frame : Frame input base) : + (advance (TM2.step (rootProgram coefficient offset)))^[rootSteps coefficient offset input] + (some ⟨some .seed, initialState, base⟩) = + some ⟨none, initialState, emitTapes base + [.input (rootLookup input.roots (widthAddress coefficient offset input))]⟩ := by + have ha := frame.clean .address (by rfl) + have hs := frame.clean .scratch (by rfl) + have affine := MachineUnaryAffineAt.seededAffineTrace .capacity .scratch .address + (by decide) (by decide) (by decide) coefficient offset RootLabel.seed + RootLabel.scan RootLabel.restore (some (.lookup (.lookup (.run .copyFirst)))) + (rootProgram coefficient offset) rfl rfl rfl base input.capacity [] + (by simpa using frame.capacityWord) hs ((), false) none + simp only [ha, List.append_nil] at affine + have source := lookupTailTrace 0 input (widthAddress coefficient offset input) present base frame + have lookup := MachineSubroutine.trace RootLabel.lookup none (lookupProgram 0) + (rootProgram coefficient offset) (fun _ => rfl) + (MachinePreservingLookupClean.steps input.roots (widthAddress coefficient offset input) + + rootLookup input.roots (widthAddress coefficient offset input) + 4) _ _ source + simp only [MachineSubroutine.configuration, MachineSubroutine.label] at lookup + exact trace_trans _ affine lookup + +theorem rootSteps_le (coefficient offset : Nat) (input : Input) + (present : input.roots[widthAddress coefficient offset input]? = + some (rootLookup input.roots (widthAddress coefficient offset input))) : + rootSteps coefficient offset input ≤ 12 * (input.size + 1) := by + have hl := MachinePreservingLookupClean.steps_le input.roots + (widthAddress coefficient offset input) _ present + have hw := MachineLookupSpec.output_length_le input.roots + (widthAddress coefficient offset input) _ present + rw [encodeWord_length] at hw + unfold rootSteps Input.size + omega + +def rootEmitter (valid : Input → Prop) (coefficient offset : Nat) + (present : ∀ input, valid input → + input.roots[widthAddress coefficient offset input]? = + some (rootLookup input.roots (widthAddress coefficient offset input))) : + Emitter valid (fun input => + [.input (rootLookup input.roots (widthAddress coefficient offset input))]) where + Label := RootLabel + finite := inferInstance + entry := .seed + program := rootProgram coefficient offset + steps := rootSteps coefficient offset + constant := 12 + trace input hv base frame := rootTrace coefficient offset input (present input hv) base frame + bound input hv := rootSteps_le coefficient offset input (present input hv) + +def closurePorts : OrClosure.Ports Tape := + ⟨.position, .reversed, .count, by decide, by decide, by decide⟩ + +inductive ClosureLabel + | seed | scan | restore | orSeed | orLoop | finish + deriving DecidableEq + +protected abbrev ClosureLabel.enumList : List ClosureLabel := [.seed, .scan, .restore, .orSeed, + .orLoop, .finish] + +protected theorem ClosureLabel.enumList_getElem?_ctorIdx_eq (x : ClosureLabel) : + ClosureLabel.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem ClosureLabel.enumList_nodup : ClosureLabel.enumList.Nodup := by decide + +instance : Fintype ClosureLabel where + elems := ⟨ClosureLabel.enumList, ClosureLabel.enumList_nodup⟩ + complete x := by cases x <;> decide + +def closureProgram (coefficient offset : Nat) : + ClosureLabel → TM2.Stmt Alphabet ClosureLabel State + | .seed => MachineUnaryAffineAt.seed .position offset .scan + | .scan => MachineUnaryAffineAt.scan .capacity .scratch .position coefficient .scan .restore + | .restore => Reduction.MachineTransfer.loopAt .scratch .capacity id false .restore (some .orSeed) + | .orSeed => OrClosure.seed closurePorts .orLoop + | .orLoop => OrClosure.loop closurePorts .orLoop (some .finish) + | .finish => .pop .position (fun _ _ => initialState) .halt + +def closureSteps (coefficient offset : Nat) (input : Input) : Nat := + (2 * (input.capacity + 1) + 1) + (widthAddress coefficient offset input + 2) + 1 + +theorem closureTrace (coefficient offset : Nat) (input : Input) + (base : Tape → List Bool) (frame : Frame input base) : + (advance (TM2.step (closureProgram coefficient offset)))^[closureSteps coefficient offset input] + (some ⟨some .seed, initialState, base⟩) = + some ⟨none, initialState, emitTapes base + (InitializationTemplate.closeOr (widthAddress coefficient offset input))⟩ := by + let width := widthAddress coefficient offset input + let finished := OrClosure.frame closurePorts base (encodeWord 0) + ((tokenBits (InitializationTemplate.closeOr width)).reverse ++ base .reversed) + (List.replicate (width + 1) true ++ base .count) + have hp := frame.clean .position (by rfl) + have hs := frame.clean .scratch (by rfl) + have affine := MachineUnaryAffineAt.seededAffineTrace .capacity .scratch .position + (by decide) (by decide) (by decide) coefficient offset ClosureLabel.seed + ClosureLabel.scan ClosureLabel.restore (some .orSeed) + (closureProgram coefficient offset) rfl rfl rfl base input.capacity [] + (by simpa using frame.capacityWord) hs ((), false) none + simp only [hp, List.append_nil] at affine + have closure := OrClosure.closureTrace closurePorts ClosureLabel.orSeed ClosureLabel.orLoop + (some .finish) (closureProgram coefficient offset) rfl rfl base width [] + (base .reversed) (base .count) ((), false) none + have startFrame : OrClosure.frame closurePorts base (encodeWord width ++ []) + (base .reversed) (base .count) = Function.update base .position (encodeWord width) := by + funext tape + cases tape <;> simp [OrClosure.frame, closurePorts] + rw [startFrame] at closure + simp only [List.append_nil] at closure + have finish : (advance (TM2.step (closureProgram coefficient offset)))^[1] + (some ⟨some .finish, initialState, finished⟩) = + some ⟨none, initialState, emitTapes base (InitializationTemplate.closeOr width)⟩ := by + change some (TM2.stepAux (closureProgram coefficient offset .finish) initialState finished) = _ + simp only [closureProgram, TM2.stepAux] + congr 2 + funext tape + cases tape <;> simp [finished, OrClosure.frame, closurePorts, emitTapes, + InitializationTemplate.closeOr, encodeWord, hp, Nat.add_comm] + exact trace_trans _ (trace_trans _ affine closure) finish + +theorem closureSteps_le (coefficient offset : Nat) (input : Input) : + closureSteps coefficient offset input ≤ (coefficient + offset + 8) * (input.size + 1) := by + have hs : input.capacity ≤ input.size := by simp [Input.size]; omega + have hmul := Nat.mul_le_mul_left coefficient hs + unfold closureSteps widthAddress + nlinarith + +def closureEmitter (valid : Input → Prop) (coefficient offset : Nat) : + Emitter valid (fun input => InitializationTemplate.closeOr (widthAddress coefficient offset input)) where + Label := ClosureLabel + finite := inferInstance + entry := .seed + program := closureProgram coefficient offset + steps := closureSteps coefficient offset + constant := coefficient + offset + 8 + trace input _ base frame := closureTrace coefficient offset input base frame + bound input _ := closureSteps_le coefficient offset input + +section Indexed + +variable {K Λ σ : Type} {Γ : K → Type} + +def Valid (indexing : ConfigIndex.Indexing Γ Λ σ) (input : Input) : Prop := + indexing.width input.capacity < input.roots.length + +theorem Valid.roots {indexing : ConfigIndex.Indexing Γ Λ σ} {input : Input} + (valid : Valid indexing input) : RootsValid indexing input := Nat.le_of_lt valid + +theorem Valid.transition {indexing : ConfigIndex.Indexing Γ Λ σ} {input : Input} + (valid : Valid indexing input) (plan : TransitionMachine.Plan (Γ := Γ) (Λ := Λ) (σ := σ)) : + TransitionMachine.Valid indexing plan input := by + unfold Valid at valid + unfold TransitionMachine.Valid + cases plan.carry <;> simp only [Bool.false_eq_true, ite_true, ite_false] <;> omega + +theorem Valid.withCursor {indexing : ConfigIndex.Indexing Γ Λ σ} {input : Input} + (valid : Valid indexing input) (cursor : Nat) : + Valid indexing (TransitionMachine.withCursor input cursor) := valid + +theorem widthAddress_eq (indexing : ConfigIndex.Indexing Γ Λ σ) (input : Input) : + widthAddress indexing.symbolCount (indexing.labelCount + indexing.stateCount) input = + indexing.width input.capacity := by + simp [widthAddress, ConfigIndex.Indexing.width, Nat.mul_comm, + Nat.add_comm, Nat.add_assoc] + +def carryTokens (indexing : ConfigIndex.Indexing Γ Λ σ) (input : Input) : List Token := + [.input (rootLookup input.roots (indexing.width input.capacity))] + +variable [DecidableEq K] [Fintype σ] [DecidableEq σ] +variable [∀ k, DecidableEq (Γ k)] [∀ k, Fintype (Γ k)] [DecidableEq Λ] [Fintype Λ] + +def carryEmitter (indexing : ConfigIndex.Indexing Γ Λ σ) : + Emitter (Valid indexing) (carryTokens indexing) := + (rootEmitter (Valid indexing) indexing.symbolCount (indexing.labelCount + indexing.stateCount) + (fun input hv => by + rw [widthAddress_eq] + simp only [rootLookup, List.getElem?_eq_getElem hv, Option.getD_some])).congr + (fun input => by rw [widthAddress_eq]; rfl) + +def orEmitter (indexing : ConfigIndex.Indexing Γ Λ σ) : + Emitter (Valid indexing) (fun input => InitializationTemplate.closeOr (indexing.width input.capacity)) := + (closureEmitter (Valid indexing) indexing.symbolCount (indexing.labelCount + indexing.stateCount)).congr + (fun input => by rw [widthAddress_eq]) + +def finishEmitter (indexing : ConfigIndex.Indexing Γ Λ σ) : + Emitter (Valid indexing) (fun _ => [.not, .and]) := + Emitter.literal (Valid indexing) [.not, .and] + +inductive Label (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : TransitionMachine.Plan (Γ := Γ) (Λ := Λ) (σ := σ)) + | carry (label : (carryEmitter indexing).Label) + | mismatch (label : TransitionMachine.Label indexing plan) + | close (label : (orEmitter indexing).Label) + | finish (label : (finishEmitter indexing).Label) + deriving Fintype + +attribute [-instance] instFintypeLabel + +instance labelFintype (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : TransitionMachine.Plan (Γ := Γ) (Λ := Λ) (σ := σ)) : Fintype (Label indexing plan) := + Fintype.ofEquiv + ((carryEmitter indexing).Label ⊕ TransitionMachine.Label indexing plan ⊕ + (orEmitter indexing).Label ⊕ (finishEmitter indexing).Label) + (Label.proxyTypeEquiv indexing plan) + +def program (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : TransitionMachine.Plan (Γ := Γ) (Λ := Λ) (σ := σ)) : + Label indexing plan → TM2.Stmt Alphabet (Label indexing plan) State + | .carry label => MachineSubroutine.statement Label.carry + (some (.mismatch (.prefix (TransitionMachine.compilePrefix indexing plan.prefix).entry))) + ((carryEmitter indexing).program label) + | .mismatch label => MachineSubroutine.statement Label.mismatch + (some (.close (orEmitter indexing).entry)) (TransitionMachine.program indexing plan label) + | .close label => MachineSubroutine.statement Label.close + (some (.finish (finishEmitter indexing).entry)) ((orEmitter indexing).program label) + | .finish label => MachineSubroutine.statement Label.finish none ((finishEmitter indexing).program label) + +def machine (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : TransitionMachine.Plan (Γ := Γ) (Λ := Λ) (σ := σ)) : FinTM2 where + K := Tape + k₀ := .capacity + k₁ := .reversed + Γ := Alphabet + Λ := Label indexing plan + main := .carry (carryEmitter indexing).entry + σ := State + initialState := initialState + m := program indexing plan + +def outputTokens (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : TransitionMachine.Plan (Γ := Γ) (Λ := Λ) (σ := σ)) (input : Input) : List Token := + carryTokens indexing input ++ TransitionMachine.outputTokens indexing plan input ++ + InitializationTemplate.closeOr (indexing.width input.capacity) ++ [.not, .and] + +def steps (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : TransitionMachine.Plan (Γ := Γ) (Λ := Λ) (σ := σ)) (input : Input) : Nat := + (carryEmitter indexing).steps (TransitionMachine.withCursor input 0) + + TransitionMachine.steps indexing plan input + + (orEmitter indexing).steps (TransitionMachine.withCursor input 0) + 1 + +omit [DecidableEq K] [Fintype σ] [DecidableEq σ] [∀ k, DecidableEq (Γ k)] + [∀ k, Fintype (Γ k)] [DecidableEq Λ] [Fintype Λ] in +theorem fullTrace (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : TransitionMachine.Plan (Γ := Γ) (Λ := Λ) (σ := σ)) (input : Input) + (valid : Valid indexing input) (base : Tape → List Bool) + (frame : Frame (TransitionMachine.withCursor input 0) base) : + (advance (TM2.step (program indexing plan)))^[steps indexing plan input] + (some ⟨some (Label.carry (carryEmitter indexing).entry), initialState, base⟩) = + some ⟨none, initialState, emitTapes base (outputTokens indexing plan input)⟩ := by + let carried := emitTapes base (carryTokens indexing input) + let mismatch := emitTapes carried (TransitionMachine.outputTokens indexing plan input) + let closed := emitTapes mismatch (InitializationTemplate.closeOr (indexing.width input.capacity)) + have carry := (carryEmitter indexing).traceAt Label.carry + (some (.mismatch (.prefix (TransitionMachine.compilePrefix indexing plan.prefix).entry))) + (program indexing plan) (fun _ => rfl) (TransitionMachine.withCursor input 0) + (valid.withCursor 0) base frame + have hcarry : Frame (TransitionMachine.withCursor input 0) carried := + frame.emit (carryTokens indexing input) + have mid := TransitionMachine.traceAt indexing plan Label.mismatch + (some (.close (orEmitter indexing).entry)) (program indexing plan) (fun _ => rfl) + input (valid.transition plan) carried hcarry + have hmid := hcarry.emit (TransitionMachine.outputTokens indexing plan input) + have close := (orEmitter indexing).traceAt Label.close + (some (.finish (finishEmitter indexing).entry)) (program indexing plan) (fun _ => rfl) + (TransitionMachine.withCursor input 0) (valid.withCursor 0) mismatch hmid + have hclose := hmid.emit (InitializationTemplate.closeOr (indexing.width input.capacity)) + have finish := (finishEmitter indexing).traceAt Label.finish none + (program indexing plan) (fun _ => rfl) (TransitionMachine.withCursor input 0) + (valid.withCursor 0) closed hclose + have h := trace_trans _ (trace_trans _ (trace_trans _ carry mid) close) finish + simpa only [steps, carried, mismatch, closed, finishEmitter, Emitter.literal, + TransitionMachine.withCursor_capacity, TransitionMachine.withCursor_roots, + carryTokens, emitTapes_append, outputTokens, List.append_assoc] using h + +def timeConstant (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : TransitionMachine.Plan (Γ := Γ) (Λ := Λ) (σ := σ)) : Nat := + (carryEmitter indexing).constant + TransitionMachine.timeConstant indexing plan + + (orEmitter indexing).constant + 1 + +noncomputable def timePolynomial (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : TransitionMachine.Plan (Γ := Γ) (Λ := Λ) (σ := σ)) : Polynomial Nat := + Polynomial.C (timeConstant indexing plan) * (Polynomial.X + 1)^2 + +omit [DecidableEq K] [Fintype σ] [DecidableEq σ] [∀ k, DecidableEq (Γ k)] + [∀ k, Fintype (Γ k)] [DecidableEq Λ] [Fintype Λ] in +theorem steps_le (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : TransitionMachine.Plan (Γ := Γ) (Λ := Λ) (σ := σ)) (input : Input) + (valid : Valid indexing input) : + steps indexing plan input ≤ timeConstant indexing plan * (TransitionMachine.dataSize input + 1)^2 := by + have hc := (carryEmitter indexing).bound (TransitionMachine.withCursor input 0) (valid.withCursor 0) + have hm := TransitionMachine.steps_le indexing plan input (valid.transition plan) + have ho := (orEmitter indexing).bound (TransitionMachine.withCursor input 0) (valid.withCursor 0) + have hs : (TransitionMachine.withCursor input 0).size = TransitionMachine.dataSize input := by + simp [TransitionMachine.withCursor, Input.size, TransitionMachine.dataSize] + rw [hs] at hc ho + have hsq : TransitionMachine.dataSize input + 1 ≤ (TransitionMachine.dataSize input + 1)^2 := by + nlinarith + have hc' := hc.trans (Nat.mul_le_mul_left (carryEmitter indexing).constant hsq) + have ho' := ho.trans (Nat.mul_le_mul_left (orEmitter indexing).constant hsq) + unfold steps timeConstant + nlinarith + +def inPolynomialTime (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : TransitionMachine.Plan (Γ := Γ) (Λ := Λ) (σ := σ)) (input : Input) + (valid : Valid indexing input) (base : Tape → List Bool) + (frame : Frame (TransitionMachine.withCursor input 0) base) : + StateTransition.EvalsToInTime (machine indexing plan).step + ⟨some (Label.carry (carryEmitter indexing).entry), initialState, base⟩ + (some ⟨none, initialState, emitTapes base (outputTokens indexing plan input)⟩) + ((timePolynomial indexing plan).eval (TransitionMachine.dataSize input)) where + steps := steps indexing plan input + evals_in_steps := fullTrace indexing plan input valid base frame + steps_le_m := by + simpa only [timePolynomial, Polynomial.eval_mul, Polynomial.eval_C, Polynomial.eval_pow, + Polynomial.eval_add, Polynomial.eval_X, Polynomial.eval_one] using steps_le indexing plan input valid + +end Indexed + +noncomputable section Verifier + +open VerifierCircuit AcceptanceTemplate + +local instance (V : NPVerifier) : Fintype V.computation.tm.Λ := V.computation.tm.ΛFin +local instance (V : NPVerifier) : Fintype V.computation.tm.σ := V.computation.tm.σFin +local instance (V : NPVerifier) : ∀ k, Fintype (V.computation.tm.Γ k) := V.finiteAlphabet +local instance (V : NPVerifier) : DecidableEq V.computation.tm.Λ := Classical.decEq _ +local instance (V : NPVerifier) : DecidableEq V.computation.tm.σ := Classical.decEq _ +local instance (V : NPVerifier) : ∀ k, DecidableEq (V.computation.tm.Γ k) := + fun _ => Classical.decEq _ + +theorem rootLookup_ofFn {n : Nat} (wire : Fin n → Nat) (i : Fin n) : + rootLookup (List.ofFn wire) i.val = wire i := by + simp [rootLookup, i.isLt] + +theorem mismatchForest_ofFn (V : NPVerifier) (input : List Bool) + (wire : Fin (width V input + 1) → Nat) : + AcceptancePlan.mismatchForest V (List.ofFn wire) (capacity V input.length) = + (List.ofFn fun j : Fin (width V input) => + mismatchTokens (targetBit V input j) (wire j.castSucc)).flatten := by + rw [AcceptancePlan.mismatchForest_circuit] + apply congrArg List.flatten + apply congrArg List.ofFn + funext j + exact congrArg (mismatchTokens (targetBit V input j)) (rootLookup_ofFn wire j.castSucc) + +def verifierInput (V : NPVerifier) (input : List Bool) + (wire : Fin (width V input + 1) → Nat) : Input := + ⟨0, capacity V input.length, List.ofFn wire⟩ + +theorem verifierInput_valid (V : NPVerifier) (input : List Bool) + (wire : Fin (width V input + 1) → Nat) : + Valid (indexing V) (verifierInput V input wire) := by + simp [Valid, verifierInput, width] + +theorem outputTokens_eq_acceptance (V : NPVerifier) (input : List Bool) + (wire : Fin (width V input + 1) → Nat) : + outputTokens (indexing V) (AcceptancePlan.plan V) (verifierInput V input wire) = + AcceptanceTemplate.tokens V input wire := by + have hw : (fun j : Fin (width V input + 1) => rootLookup (List.ofFn wire) j.val) = wire := + funext (rootLookup_ofFn wire) + have h := (AcceptancePlan.fullTokens_eq V input (List.ofFn wire)).symm + rw [hw] at h + simpa only [outputTokens, carryTokens, verifierInput, width] using h + +theorem compile_outputTokens (V : NPVerifier) (input : List Bool) + (wire : Fin (width V input + 1) → Nat) (start : Nat) (oldRoots : List Nat) : + compileTokens start oldRoots + (outputTokens (indexing V) (AcceptancePlan.plan V) (verifierInput V input wire)) = + some (start + (acceptanceExpr V input).size, + (acceptanceExpr V input).root start :: oldRoots, + (acceptanceExpr V input).gates wire start) := by + rw [outputTokens_eq_acceptance] + exact AcceptanceTemplate.compile_tokens V input wire start oldRoots + +theorem outputTokens_length_le (V : NPVerifier) (input : List Bool) + (wire : Fin (width V input + 1) → Nat) : + (outputTokens (indexing V) (AcceptancePlan.plan V) (verifierInput V input wire)).length ≤ + 3 * width V input + 4 := by + rw [outputTokens_eq_acceptance] + exact AcceptanceTemplate.tokens_length_le V input wire + +def verifierMachine (V : NPVerifier) : FinTM2 := + machine (indexing V) (AcceptancePlan.plan V) + +def verifierInPolynomialTime (V : NPVerifier) (input : List Bool) + (wire : Fin (width V input + 1) → Nat) (base : Tape → List Bool) + (frame : Frame (verifierInput V input wire) base) : + StateTransition.EvalsToInTime (verifierMachine V).step + ⟨some (Label.carry (carryEmitter (indexing V)).entry), initialState, base⟩ + (some ⟨none, initialState, emitTapes base (AcceptanceTemplate.tokens V input wire)⟩) + ((timePolynomial (indexing V) (AcceptancePlan.plan V)).eval + (TransitionMachine.dataSize (verifierInput V input wire))) := by + have run := inPolynomialTime (indexing V) (AcceptancePlan.plan V) (verifierInput V input wire) + (verifierInput_valid V input wire) base frame + rw [outputTokens_eq_acceptance] at run + exact run + +end Verifier + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.AcceptanceMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/AcceptanceStage.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/AcceptanceStage.lean new file mode 100644 index 0000000000000000000000000000000000000000..f7860981162100fe7b543e2e26451699efc42c1a --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/AcceptanceStage.lean @@ -0,0 +1,256 @@ +import OAI.Computability.PerfectCompleteness.Machines.AcceptanceMachine +import OAI.Computability.PerfectCompleteness.Machines.InitializationStageLemmas + +namespace OAI + +section + +noncomputable section +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.AcceptanceStage + +open Turing MachineComposition StatementCircuit CircuitBatch +open PostfixModel PostfixAlignment ProducerInvariant VerifierCircuit +open TransitionArena + + +local instance (V : NPVerifier) : Fintype V.computation.tm.Λ := V.computation.tm.ΛFin +local instance (V : NPVerifier) : Fintype V.computation.tm.σ := V.computation.tm.σFin +local instance (V : NPVerifier) : ∀ k, Fintype (V.computation.tm.Γ k) := V.finiteAlphabet +local instance (V : NPVerifier) : DecidableEq V.computation.tm.Λ := Classical.decEq _ +local instance (V : NPVerifier) : DecidableEq V.computation.tm.σ := Classical.decEq _ +local instance (V : NPVerifier) : ∀ k, DecidableEq (V.computation.tm.Γ k) := + fun _ => Classical.decEq _ + +abbrev EmitLabel (V : NPVerifier) := + AcceptanceMachine.Label (indexing V) (AcceptancePlan.plan V) + +abbrev Label (V : NPVerifier) := EmitLabel V ⊕ ForestStage.Label + +def entry (V : NPVerifier) : Label V := + .inl (.carry (AcceptanceMachine.carryEmitter (indexing V)).entry) + +def program (V : NPVerifier) : Label V → TM2.Stmt Alphabet (Label V) State + | .inl label => ForestPlacement.statement termPorts Sum.inl + (some (.inr .reverseTokens)) + (AcceptanceMachine.program (indexing V) (AcceptancePlan.plan V) label) + | .inr label => ForestStage.statement forestPorts Sum.inr none label + +def machine (V : NPVerifier) : FinTM2 where + K := Tape + k₀ := .inr .capacity + k₁ := .inl .records + Γ := Alphabet + Λ := Label V + main := entry V + σ := State + initialState := TermMachine.initialState + m := program V + +def expressions (V : NPVerifier) (input : List Bool) : + Fin 1 → Expr (Fin (width V input + 1)) := + fun _ => acceptanceExpr V input + +def wireValues {inputs count : Nat} (frame : Frame inputs count) : Fin count → Nat := + fun i => (frame.wires i).val + +theorem tokens_eq_forest (V : NPVerifier) (input : List Bool) + (wire : Fin (width V input + 1) → Nat) : + AcceptanceTemplate.tokens V input wire = + forestTokens wire (List.ofFn (expressions V input)) := by + rw [AcceptanceTemplate.tokens_eq] + simp [expressions, List.ofFn_succ, forestTokens] + +theorem finish_termFrame (base : Tape → List Bool) (S : Nat) (s : Snapshot) : + TermMachine.Frame (termInput S s) + (fun tape => finishTapes base S s (termPorts tape)) := by + have restriction : (fun tape => finishTapes base S s (termPorts tape)) = + (fun tape => tapes base S 0 s (termPorts tape)) := by + funext tape + rw [termPorts.eq_1] + change finishTapes base S s (termTape tape) = tapes base S 0 s (termTape tape) + cases tape <;> simp [finishTapes, termTape] + rw [restriction] + exact termFrame base S 0 s + +def prepared (base : Tape → List Bool) (S : Nat) (s : Snapshot) + (tokens : List Token) : Tape → List Bool := + Function.update + (Function.update (finishTapes base S s) (.inl .tokens) (tokenBits tokens).reverse) + (.inl (.lower .remaining)) (encodeWord tokens.length) + +theorem finish_place_emitTapes (base : Tape → List Bool) (S : Nat) (s : Snapshot) + (tokens : List Token) : + ForestPlacement.fill termPorts (finishTapes base S s) + (TermMachine.emitTapes (fun tape => finishTapes base S s (termPorts tape)) tokens) = + prepared base S s tokens := by + simp only [TermMachine.emitTapes, ForestPlacement.fill_update, ForestPlacement.fill_self] + simp only [termPorts_apply] + simp [termTape, tapes, finishTapes, prepared, encodeWord] + +theorem prepared_eq_lower (base : Tape → List Bool) (S : Nat) (s : Snapshot) + (tokens : List Token) : + prepared base S s tokens = + ForestPlacement.fill forestPorts (finishTapes base S s) + (ForestStage.initialLocal s.current tokens s.reversedRecords (encodeWords s.roots)) := by + rw [fill_forest] + funext tape + cases tape with + | inl tape => + cases tape with + | lower tape => cases tape <;> + simp [prepared, finishTapes, tapes, ForestStage.initialLocal] + | tokens => simp [prepared, finishTapes, ForestStage.initialLocal] + | records => simp [prepared, finishTapes, tapes, ForestStage.initialLocal] + | rootTable => simp [prepared, finishTapes, tapes, ForestStage.initialLocal] + | inr tape => cases tape <;> + simp [prepared, finishTapes, tapes] + +theorem lower_final_eq {inputs oldWidth newWidth : Nat} + (base : Tape → List Bool) (S : Nat) (frame : Frame inputs oldWidth) + (es : Fin newWidth → Expr (Fin oldWidth)) : + ForestPlacement.fill forestPorts (finishTapes base S (snapshot frame)) + (ForestStage.finalLocal (next (frame.step es)) (rootValues (frame.step es)).reverse + (recordsBits (gateRecords (next frame) + (Batch.gates (wireValues frame) (next frame) (List.ofFn es)))) + (recordBits frame).reverse) = + finishTapes base S (snapshot (frame.step es)) := by + rw [fill_forest] + funext tape + cases tape with + | inl tape => + cases tape with + | lower tape => cases tape <;> rfl + | tokens => rfl + | records => + change (recordsBits (gateRecords (next frame) + (Batch.gates (wireValues frame) (next frame) (List.ofFn es)))).reverse ++ + (recordBits frame).reverse = (recordBits (frame.step es)).reverse + rw [recordBits_step, List.reverse_append] + rfl + | rootTable => + change encodeWords (rootValues (frame.step es)).reverse.reverse = + encodeWords (rootValues (frame.step es)) + rw [List.reverse_reverse] + | inr tape => cases tape <;> rfl + +def emissionSteps (V : NPVerifier) (input : List Bool) {inputs : Nat} + (frame : Frame inputs (width V input + 1)) : Nat := + AcceptanceMachine.steps (indexing V) (AcceptancePlan.plan V) + (AcceptanceMachine.verifierInput V input (wireValues frame)) + +def loweringSteps (V : NPVerifier) (input : List Bool) {inputs : Nat} + (frame : Frame inputs (width V input + 1)) : Nat := + ForestStage.steps (AcceptanceTemplate.tokens V input (wireValues frame)) (next frame) + (rootValues (frame.step (expressions V input))).reverse + (Batch.gates (wireValues frame) (next frame) (List.ofFn (expressions V input))) + (encodeWords (rootValues frame)) + +def steps (V : NPVerifier) (input : List Bool) {inputs : Nat} + (frame : Frame inputs (width V input + 1)) : Nat := + emissionSteps V input frame + loweringSteps V input frame + +private theorem chain {α : Type*} (f : α → α) {n m : Nat} {a b c : α} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm n m, Function.iterate_add_apply, first, second] + +theorem fullTrace (V : NPVerifier) (input : List Bool) {inputs : Nat} + (frame : Frame inputs (width V input + 1)) (base : Tape → List Bool) : + (advance (TM2.step (program V)))^[steps V input frame] + (some ⟨some (entry V), TermMachine.initialState, + finishTapes base (capacity V input.length) (snapshot frame)⟩) = + some ⟨none, TermMachine.initialState, + finishTapes base (capacity V input.length) + (snapshot (frame.step (expressions V input)))⟩ := by + let boundary := finishTapes base (capacity V input.length) (snapshot frame) + let wire := wireValues frame + let inp := AcceptanceMachine.verifierInput V input wire + let tokens := AcceptanceTemplate.tokens V input wire + have hframe : TermMachine.Frame inp (fun tape => boundary (termPorts tape)) := + finish_termFrame base (capacity V input.length) (snapshot frame) + have source := AcceptanceMachine.fullTrace (indexing V) (AcceptancePlan.plan V) inp + (AcceptanceMachine.verifierInput_valid V input wire) + (fun tape => boundary (termPorts tape)) hframe + rw [AcceptanceMachine.outputTokens_eq_acceptance] at source + have emitter := ForestPlacement.trace termPorts Sum.inl (some (.inr .reverseTokens)) + boundary (AcceptanceMachine.program (indexing V) (AcceptancePlan.plan V)) + (program V) (fun _ => rfl) _ _ _ source + change (advance (TM2.step (program V)))^[emissionSteps V input frame] + (some ⟨some (entry V), TermMachine.initialState, + ForestPlacement.fill termPorts boundary (fun tape => boundary (termPorts tape))⟩) = + some ⟨some (.inr .reverseTokens), TermMachine.initialState, + ForestPlacement.fill termPorts boundary + (TermMachine.emitTapes (fun tape => boundary (termPorts tape)) tokens)⟩ at emitter + rw [ForestPlacement.fill_self] at emitter + rw [finish_place_emitTapes, prepared_eq_lower] at emitter + have valid := compile_frameForest frame (expressions V input) + rw [← tokens_eq_forest] at valid + have lower := ForestStage.traceAt forestPorts Sum.inr none (program V) (fun _ => rfl) + boundary ((), false) tokens (next frame) (next (frame.step (expressions V input))) + (rootValues (frame.step (expressions V input))).reverse + (Batch.gates wire (next frame) (List.ofFn (expressions V input))) + (recordBits frame).reverse (encodeWords (rootValues frame)) valid + rw [lower_final_eq] at lower + exact chain _ emitter lower + +def budget (V : NPVerifier) (input : List Bool) {inputs : Nat} + (frame : Frame inputs (width V input + 1)) : Nat := + (AcceptanceMachine.timePolynomial (indexing V) (AcceptancePlan.plan V)).eval + (TransitionMachine.dataSize + (AcceptanceMachine.verifierInput V input (wireValues frame))) + + ForestStage.timePolynomial.eval + (next frame + Batch.cost (List.ofFn (expressions V input)) + + (tokenBits (AcceptanceTemplate.tokens V input (wireValues frame))).length + + (encodeWords (rootValues frame)).length + 1) + +theorem steps_le_budget (V : NPVerifier) (input : List Bool) {inputs : Nat} + (frame : Frame inputs (width V input + 1)) : steps V input frame ≤ budget V input frame := by + have he := AcceptanceMachine.steps_le (indexing V) (AcceptancePlan.plan V) + (AcceptanceMachine.verifierInput V input (wireValues frame)) + (AcceptanceMachine.verifierInput_valid V input (wireValues frame)) + have hl := ForestStage.forest_steps_le (wireValues frame) (List.ofFn (expressions V input)) + (next frame) (encodeWords (rootValues frame)) (fun i => (frame.wires i).isLt) + have roots : rootValues (frame.step (expressions V input)) = + Batch.roots (next frame) (List.ofFn (expressions V input)) := + step_roots frame (expressions V input) + rw [← tokens_eq_forest] at hl + unfold steps emissionSteps loweringSteps budget + rw [roots] + apply Nat.add_le_add _ hl + simpa only [AcceptanceMachine.timePolynomial, Polynomial.eval_mul, Polynomial.eval_C, + Polynomial.eval_pow, Polynomial.eval_add, Polynomial.eval_X, Polynomial.eval_one] using he + +def inTime (V : NPVerifier) (input : List Bool) {inputs : Nat} + (frame : Frame inputs (width V input + 1)) (base : Tape → List Bool) : + StateTransition.EvalsToInTime (machine V).step + ⟨some (entry V), TermMachine.initialState, + finishTapes base (capacity V input.length) (snapshot frame)⟩ + (some ⟨none, TermMachine.initialState, + finishTapes base (capacity V input.length) + (snapshot (frame.step (expressions V input)))⟩) + (budget V input frame) where + steps := steps V input frame + evals_in_steps := fullTrace V input frame base + steps_le_m := steps_le_budget V input frame + +theorem verifierTrace (V : NPVerifier) (input : List Bool) (base : Tape → List Bool) : + (advance (TM2.step (program V)))^[ + steps V input (timeFrame V input (V.horizon input.length))] + (some ⟨some (entry V), TermMachine.initialState, + finishTapes base (capacity V input.length) + (snapshot (timeFrame V input (V.horizon input.length)))⟩) = + some ⟨none, TermMachine.initialState, + finishTapes base (capacity V input.length) (snapshot (finalFrame V input))⟩ := + fullTrace V input (timeFrame V input (V.horizon input.length)) base + +theorem final_root_singleton (V : NPVerifier) (input : List Bool) (base : Tape → List Bool) : + finishTapes base (capacity V input.length) (snapshot (finalFrame V input)) + (.inl .rootTable) = encodeWords [((finalFrame V input).wires 0).val] := by + simp [finishTapes, tapes, snapshot, List.ofFn_succ] + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.AcceptanceStage + +end + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryDualCoordinates.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryDualCoordinates.lean new file mode 100644 index 0000000000000000000000000000000000000000..4095bd4f23004d2190420249b473190d1e0db295 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryDualCoordinates.lean @@ -0,0 +1,177 @@ +import Mathlib.LinearAlgebra.Basis.Defs +import Mathlib.LinearAlgebra.Dimension.Free +import Mathlib.LinearAlgebra.Dual.Defs +import OAI.Computability.PerfectCompleteness.Algebra.OutputCharacters +import OAI.Computability.PerfectCompleteness.Foundations.QuarterBalanceLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.BinaryDualCoordinates + +open scoped BigOperators +open QuarterBalance (F2) +open SmallBiasSlice + +noncomputable section + +def toBool (a : F2) : Bool := decide (a ≠ 0) + +def ofBool (b : Bool) : F2 := if b then 1 else 0 + +@[simp] theorem toBool_ofBool (b : Bool) : toBool (ofBool b) = b := by + cases b <;> simp [toBool, ofBool] + +@[simp] theorem ofBool_toBool (a : F2) : ofBool (toBool a) = a := by + rcases QuarterBalance.scalar_cases a with rfl | rfl <;> simp [toBool, ofBool] + +theorem toBool_injective : Function.Injective toBool := by + intro a b h + simpa using congrArg ofBool h + +theorem ofBool_injective : Function.Injective ofBool := by + intro a b h + simpa using congrArg toBool h + +@[simp] theorem bitSign_toBool (a : F2) : bitSign (toBool a) = + QuarterBalance.sign a := by + rcases QuarterBalance.scalar_cases a with rfl | rfl <;> + simp [bitSign, toBool] + +variable {I V : Type*} [Fintype I] [AddCommGroup V] [Module F2 V] + +def coordinates (b : Module.Basis I F2 V) (x : V) : I → Bool := + fun i => toBool (b.coord i x) + +theorem coordinates_injective (b : Module.Basis I F2 V) : + Function.Injective (coordinates b) := by + intro x y h + apply b.equivFun.injective + funext i + have hi := toBool_injective (congrFun h i) + simpa only [Module.Basis.equivFun_apply, Module.Basis.coord_apply] using hi + +def frequency (b : Module.Basis I F2 V) (s : I → Bool) : Module.Dual F2 V := + rowCombination (fun i => b.coord i) s + +theorem frequency_apply (b : Module.Basis I F2 V) (s : I → Bool) (x : V) : + frequency b s x = ∑ i, if s i then b.coord i x else 0 := by + classical + simp only [frequency, rowCombination, LinearMap.sum_apply] + apply Finset.sum_congr rfl + intro i _ + cases s i <;> simp + +@[simp] theorem frequency_apply_basis (b : Module.Basis I F2 V) + (s : I → Bool) (j : I) : frequency b s (b j) = ofBool (s j) := by + classical + rw [frequency_apply, Finset.sum_eq_single j] + · simp [Module.Basis.coord_apply, ofBool] + · intro i _ hij + simp [Module.Basis.coord_apply, Ne.symm hij] + · simp + +theorem frequency_injective (b : Module.Basis I F2 V) : + Function.Injective (frequency b) := by + intro s t h + funext i + apply ofBool_injective + simpa using congrArg (fun f : Module.Dual F2 V => f (b i)) h + +theorem frequency_surjective (b : Module.Basis I F2 V) : + Function.Surjective (frequency b) := by + intro f + refine ⟨fun i => toBool (f (b i)), ?_⟩ + apply b.ext + intro i + simp + +def frequencyEquiv (b : Module.Basis I F2 V) : + (I → Bool) ≃ Module.Dual F2 V where + toFun := frequency b + invFun f i := toBool (f (b i)) + left_inv s := by funext i; simp + right_inv f := by apply b.ext; intro i; simp + +def character (f : Module.Dual F2 V) (x : V) : ℝ := + QuarterBalance.sign (f x) + +@[simp] theorem character_zero (x : V) : character 0 x = 1 := by + simp [character] + +theorem character_add (f g : Module.Dual F2 V) (x : V) : + character (f + g) x = character f x * character g x := by + simp only [character, LinearMap.add_apply, QuarterBalance.sign_add] + +@[simp] theorem abs_character (f : Module.Dual F2 V) (x : V) : + |character f x| = 1 := QuarterBalance.abs_sign _ + +theorem character_frequency (b : Module.Basis I F2 V) + (s : I → Bool) (x : V) : + character (frequency b s) x = maskChar s (coordinates b x) := by + classical + apply character_rowCombination character character_zero character_add + (fun i => b.coord i) (coordinates b) + intro i y + exact (bitSign_toBool (b.coord i y)).symm + +variable {U : Type*} [AddCommGroup U] [Module F2 U] + +def equationRows (b : Module.Basis I F2 V) (R : U →ₗ[F2] V) : + I → Module.Dual F2 U := fun i => (b.coord i).comp R + +def equations (b : Module.Basis I F2 V) (R : U →ₗ[F2] V) (x : U) : I → Bool := + coordinates b (R x) + +theorem equations_eq_iff (b : Module.Basis I F2 V) (R : U →ₗ[F2] V) + (x : U) (target : V) : + equations b R x = coordinates b target ↔ R x = target := + ⟨fun h => coordinates_injective b h, fun h => congrArg (coordinates b) h⟩ + +omit [Fintype I] in +theorem character_equationRows (b : Module.Basis I F2 V) + (R : U →ₗ[F2] V) (i : I) (x : U) : + character (equationRows b R i) x = bitSign (equations b R x i) := + (bitSign_toBool _).symm + +theorem rowCombination_equationRows (b : Module.Basis I F2 V) + (R : U →ₗ[F2] V) (s : I → Bool) : + rowCombination (equationRows b R) s = (frequency b s).comp R := by + classical + ext x + simp only [equationRows, frequency, rowCombination, LinearMap.comp_apply, + LinearMap.sum_apply] + apply Finset.sum_congr rfl + intro i _ + cases s i <;> simp + +theorem equationRows_independent (b : Module.Basis I F2 V) + (R : U →ₗ[F2] V) (hR : Function.Surjective R) : + Function.Injective (rowCombination (equationRows b R)) := by + intro s t h + apply frequency_injective b + ext v + obtain ⟨x, rfl⟩ := hR v + rw [rowCombination_equationRows, rowCombination_equationRows] at h + exact congrArg (fun f : Module.Dual F2 U => f x) h + +theorem rowCombination_mem_dualRange (b : Module.Basis I F2 V) + (R : U →ₗ[F2] V) (s : I → Bool) : + rowCombination (equationRows b R) s ∈ LinearMap.range R.dualMap := by + refine ⟨frequency b s, ?_⟩ + exact (rowCombination_equationRows b R s).symm + +theorem character_affine_target (b : Module.Basis I F2 V) + (T : U →ₗ[F2] V) (offset : V) (s : I → Bool) (x : U) : + maskChar s (coordinates b (offset + T x)) = + character (frequency b s) offset * character ((frequency b s).comp T) x := by + rw [← character_frequency] + simp only [character, map_add, LinearMap.comp_apply, QuarterBalance.sign_add] + +end +end PerfectCompleteness.BinaryDualCoordinates + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryFormulaLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryFormulaLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..b9a74f2bef2dadf969e77cff11140df63220387e --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryFormulaLemmas.lean @@ -0,0 +1,362 @@ +import Mathlib.Data.Nat.Size +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.Ring +import OAI.Computability.PerfectCompleteness.Model +import OAI.Computability.UniqueGames.PCP.NameCompaction + +namespace OAI + + +namespace PerfectCompleteness.BinaryFormula + +open UniqueGamesTheorem.Foundations + +def clauseNames (c : Clause) : List Nat := + [(c)[0].name, (c)[1].name, (c)[2].name] + +def sourceNames (F : Formula) : List Nat := + F.clauses.flatMap clauseNames + +def activeNames (F : Formula) : List Nat := + (sourceNames F).eraseDups + +theorem literal_mem_active (F : Formula) (c : Clause) + (hc : c ∈ F.clauses) (i : Fin 3) : (c)[i].name ∈ activeNames F := by + simp only [activeNames, List.mem_eraseDups] + apply List.mem_flatMap.mpr + refine ⟨c, hc, ?_⟩ + have hi : i = 0 ∨ i = 1 ∨ i = 2 := by omega + rcases hi with rfl | rfl | rfl <;> simp [clauseNames] + +def compactIndex (F : Formula) (v : Nat) + (hv : v ∈ activeNames F) : Fin (activeNames F).length := + ⟨(activeNames F).idxOf v, List.idxOf_lt_length_iff.mpr hv⟩ + +def decodeName (F : Formula) (v : Fin (activeNames F).length) : Nat := + (activeNames F)[v.val] + +def compactLiteral (F : Formula) (l : Literal) + (hl : l.name ∈ activeNames F) : Target.Literal (activeNames F).length := + ⟨compactIndex F l.name hl, l.positive⟩ + +def compactClause (F : Formula) (c : Clause) + (hc : c ∈ F.clauses) : Target.Clause (activeNames F).length := + #v[compactLiteral F (c)[0] (literal_mem_active F c hc 0), + compactLiteral F (c)[1] (literal_mem_active F c hc 1), + compactLiteral F (c)[2] (literal_mem_active F c hc 2)] + +def compactClauses (F : Formula) : List (Target.Clause (activeNames F).length) := + F.clauses.attach.map (fun c => compactClause F c.val c.property) + +def dense (F : Formula) : Target.Formula where + «variables» := (activeNames F).length + clauses := compactClauses F + +def restrictAssignment (F : Formula) (A : Nat → Bool) : + Fin (activeNames F).length → Bool := fun v => A (decodeName F v) + +def extendAssignment (F : Formula) (B : Fin (activeNames F).length → Bool) + (v : Nat) : Bool := + if hv : v ∈ activeNames F then B (compactIndex F v hv) else false + +@[simp] theorem decode_compactIndex (F : Formula) (v : Nat) + (hv : v ∈ activeNames F) : decodeName F (compactIndex F v hv) = v := by + exact List.getElem_idxOf (List.idxOf_lt_length_iff.mpr hv) + +theorem compactIndex_injective (F : Formula) (u v : Nat) + (hu : u ∈ activeNames F) (hv : v ∈ activeNames F) + (h : compactIndex F u hu = compactIndex F v hv) : u = v := by + have decoded := congrArg (decodeName F) h + simpa only [decode_compactIndex] using decoded + +@[simp] theorem compactLiteral_positive (F : Formula) (l : Literal) + (hl : l.name ∈ activeNames F) : (compactLiteral F l hl).positive = l.positive := rfl + +@[simp] theorem eval_compact_restrict (F : Formula) (c : Clause) + (hc : c ∈ F.clauses) (A : Nat → Bool) : + (compactClause F c hc).eval (restrictAssignment F A) = c.eval A := by + simp [compactClause, compactLiteral, Target.Clause.eval, Target.Literal.eval, + Clause.eval, Literal.eval, restrictAssignment, decode_compactIndex] + +@[simp] theorem eval_compact_extend (F : Formula) (c : Clause) + (hc : c ∈ F.clauses) (B : Fin (activeNames F).length → Bool) : + (compactClause F c hc).eval B = c.eval (extendAssignment F B) := by + have h₀ : (c)[0].name ∈ activeNames F := literal_mem_active F c hc 0 + have h₁ : (c)[1].name ∈ activeNames F := literal_mem_active F c hc 1 + have h₂ : (c)[2].name ∈ activeNames F := literal_mem_active F c hc 2 + simp [compactClause, compactLiteral, Target.Clause.eval, Target.Literal.eval, + Clause.eval, Literal.eval, extendAssignment, h₀, h₁, h₂] + rfl + +def evaluationList (F : Formula) (A : Nat → Bool) : List Bool := + F.clauses.map (fun c => c.eval A) + +theorem evaluationList_restrict (F : Formula) (A : Nat → Bool) : + PCP.NameCompaction.evaluationList (dense F) (restrictAssignment F A) = + evaluationList F A := by + simp only [PCP.NameCompaction.evaluationList, evaluationList, dense, compactClauses, + List.map_map] + simpa only [Function.comp_def, eval_compact_restrict] using + PCP.NameCompaction.map_attach_val F.clauses (fun c => c.eval A) + +theorem evaluationList_extend (F : Formula) (B : Fin (dense F).variables → Bool) : + PCP.NameCompaction.evaluationList (dense F) B = + evaluationList F (extendAssignment F B) := by + simp only [PCP.NameCompaction.evaluationList, evaluationList, dense, compactClauses, + List.map_map] + change F.clauses.attach.map (fun c => (compactClause F c.val c.property).eval B) = _ + calc + _ = F.clauses.attach.map (fun c => c.val.eval (extendAssignment F B)) := by + apply List.map_congr_left + intro c _ + exact eval_compact_extend F c.val c.property B + _ = _ := PCP.NameCompaction.map_attach_val F.clauses + (fun c => c.eval (extendAssignment F B)) + +def failedCount (F : Formula) (A : Nat → Bool) : Nat := + (evaluationList F A).count false + +theorem failedCount_restrict (F : Formula) (A : Nat → Bool) : + PCP.NameCompaction.failedCount (dense F) (restrictAssignment F A) = failedCount F A := by + simp only [PCP.NameCompaction.failedCount, failedCount, evaluationList_restrict] + +theorem failedCount_extend (F : Formula) (B : Fin (dense F).variables → Bool) : + PCP.NameCompaction.failedCount (dense F) B = failedCount F (extendAssignment F B) := by + simp only [PCP.NameCompaction.failedCount, failedCount, evaluationList_extend] + +theorem clauseNames_flat_length (cs : List Clause) : + (cs.flatMap clauseNames).length = 3 * cs.length := by + induction cs with + | nil => simp + | cons c cs ih => + simp only [List.flatMap_cons, List.length_append, clauseNames, + List.length_cons, List.length_nil, ih] + omega + +@[simp] theorem dense_clause_count (F : Formula) : + (dense F).clauses.length = F.clauses.length := by + simp [dense, compactClauses] + +theorem dense_variable_bound (F : Formula) : + (dense F).variables ≤ 3 * F.clauses.length := by + have h := PCP.NameCompaction.length_eraseDups_le (sourceNames F) + simpa only [sourceNames, clauseNames_flat_length, dense, activeNames] using h + +theorem dense_completeness (F : Formula) (hs : F.Satisfiable) : + (dense F).Satisfiable := by + rcases hs with ⟨A, hA⟩ + refine ⟨restrictAssignment F A, ?_⟩ + intro d hd + change d ∈ F.clauses.attach.map (fun c => compactClause F c.val c.property) at hd + rcases List.mem_map.mp hd with ⟨c, _, rfl⟩ + exact (eval_compact_restrict F c.val c.property A).trans (hA c.val c.property) + +theorem dense_reflects (F : Formula) (hs : (dense F).Satisfiable) : F.Satisfiable := by + rcases hs with ⟨B, hB⟩ + refine ⟨extendAssignment F B, ?_⟩ + intro c hc + have hm : compactClause F c hc ∈ (dense F).clauses := by + change _ ∈ F.clauses.attach.map (fun d => compactClause F d.val d.property) + exact List.mem_map.mpr ⟨⟨c, hc⟩, by simp, rfl⟩ + rw [← eval_compact_extend F c hc B] + exact hB _ hm + +theorem dense_satisfiable_iff (F : Formula) : + (dense F).Satisfiable ↔ F.Satisfiable := + ⟨dense_reflects F, dense_completeness F⟩ + +theorem dense_preserves_gap (F : Formula) (a b : Nat) + (gap : ∀ A, a * F.clauses.length ≤ b * failedCount F A) + (B : Fin (dense F).variables → Bool) : + a * (dense F).clauses.length ≤ b * PCP.NameCompaction.failedCount (dense F) B := by + rw [dense_clause_count, failedCount_extend] + exact gap (extendAssignment F B) + +theorem dense_encoding_bound (F : Formula) : + (Complexity.formulaBits (dense F)).length ≤ + 9 * F.clauses.length * F.clauses.length + 10 * F.clauses.length + 2 := by + have enc := Complexity.formulaBits_length_le (dense F) + rw [dense_clause_count] at enc + have active := dense_variable_bound F + have h₁ := Nat.add_le_add_right active (F.clauses.length + 2) + have h₂ := Nat.mul_le_mul_left F.clauses.length + (Nat.mul_le_mul_left 3 (Nat.add_le_add_right active 2)) + have total := Nat.add_le_add h₁ h₂ + have polynomial : 3 * F.clauses.length + (F.clauses.length + 2) + + F.clauses.length * (3 * (3 * F.clauses.length + 2)) = + 9 * F.clauses.length * F.clauses.length + 10 * F.clauses.length + 2 := by + ring + rw [polynomial] at total + omega + +end PerfectCompleteness.BinaryFormula + + + +namespace PerfectCompleteness.BinaryEncoding + +open BinaryFormula + +@[simp] theorem bitsValue_bits (n : Nat) : bitsValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [bitsValue] + | bit b n hn ih => + rw [Nat.bits_append_bit n b hn] + simp only [bitsValue, ih] + +def frame : List Bool → List Bool + | [] => [false] + | b :: bits => true :: b :: frame bits + +@[simp] theorem parseFrame_encoded (bits trailing : List Bool) : + parseFrame (frame bits ++ trailing) = some (bits, trailing) := by + induction bits with + | nil => rfl + | cons b bits ih => simp [frame, parseFrame, ih] + +@[simp] theorem frame_length (bits : List Bool) : + (frame bits).length = 2 * bits.length + 1 := by + induction bits with + | nil => rfl + | cons b bits ih => simp [frame, ih]; omega + +def nameBits (name : Nat) : List Bool := frame name.bits + +@[simp] theorem parseName_encoded (name : Nat) (rest : List Bool) : + parseName (nameBits name ++ rest) = some (name, rest) := by + simp [parseName, nameBits] + +@[simp] theorem nameBits_length (name : Nat) : + (nameBits name).length = 2 * name.size + 1 := by + simp [nameBits, Nat.size_eq_bits_len] + +theorem nameBits_length_le_of_lt_pow (name width : Nat) (bound : name < 2 ^ width) : + (nameBits name).length ≤ 2 * width + 1 := by + rw [nameBits_length] + have h := Nat.size_le.mpr bound + omega + +def literalBits (literal : Literal) : List Bool := + literal.positive :: nameBits literal.name + +@[simp] theorem parseLiteral_encoded (literal : Literal) (rest : List Bool) : + parseLiteral (literalBits literal ++ rest) = some (literal, rest) := by + cases literal with + | mk name sign => simp [literalBits, parseLiteral] + +@[simp] theorem literalBits_length (literal : Literal) : + (literalBits literal).length = 2 * literal.name.size + 2 := by + simp [literalBits] + +def clauseBits (clause : Clause) : List Bool := + literalBits clause[0] ++ literalBits clause[1] ++ literalBits clause[2] + +theorem clause_three_entries (clause : Clause) : #v[clause[0], clause[1], clause[2]] = clause := by + apply Vector.ext + intro i hi + have cases_i : i = 0 ∨ i = 1 ∨ i = 2 := by omega + rcases cases_i with rfl | rfl | rfl <;> rfl + +@[simp] theorem parseClause_encoded (clause : Clause) (rest : List Bool) : + parseClause (clauseBits clause ++ rest) = some (clause, rest) := by + simp [clauseBits, List.append_assoc, parseClause, clause_three_entries] + +def clauseNameSize (clause : Clause) : Nat := + ((clauseNames clause).map Nat.size).sum + +@[simp] theorem clauseBits_length (clause : Clause) : + (clauseBits clause).length = 2 * clauseNameSize clause + 6 := by + simp [clauseBits, clauseNameSize, clauseNames] + omega + +def clausesBits : List Clause → List Bool + | [] => [false] + | clause :: clauses => true :: (clauseBits clause ++ clausesBits clauses) + +def formulaBits (formula : Formula) : List Bool := clausesBits formula.clauses + +def namesBitSize (clauses : List Clause) : Nat := + ((clauses.flatMap clauseNames).map Nat.size).sum + +@[simp] theorem namesBitSize_nil : namesBitSize [] = 0 := rfl + +@[simp] theorem namesBitSize_cons (clause : Clause) (clauses : List Clause) : + namesBitSize (clause :: clauses) = clauseNameSize clause + namesBitSize clauses := by + simp [namesBitSize, clauseNameSize] + +theorem clausesBits_length (clauses : List Clause) : + (clausesBits clauses).length = 7 * clauses.length + 2 * namesBitSize clauses + 1 := by + induction clauses with + | nil => rfl + | cons clause clauses ih => + simp only [clausesBits, List.length_cons, List.length_append, clauseBits_length, + namesBitSize_cons, ih] + omega + +theorem formulaBits_length (formula : Formula) : + (formulaBits formula).length = + 7 * formula.clauses.length + 2 * namesBitSize formula.clauses + 1 := + clausesBits_length formula.clauses + +theorem clauses_length_lt_bits (clauses : List Clause) : + clauses.length < (clausesBits clauses).length := by + rw [clausesBits_length] + omega + +def ordinarySize (formula : Formula) : Nat := + 3 * formula.clauses.length + namesBitSize formula.clauses + 1 + +theorem ordinarySize_le_bits (formula : Formula) : + ordinarySize formula ≤ (formulaBits formula).length := by + rw [formulaBits_length] + unfold ordinarySize + omega + +theorem bits_le_three_ordinarySize (formula : Formula) : + (formulaBits formula).length ≤ 3 * ordinarySize formula := by + rw [formulaBits_length] + unfold ordinarySize + omega + +@[simp] theorem parseClauses_encoded (clauses : List Clause) (rest : List Bool) + (fuel : Nat) (enough : clauses.length < fuel) : + parseClauses fuel (clausesBits clauses ++ rest) = some (clauses, rest) := by + induction clauses generalizing fuel with + | nil => + cases fuel with + | zero => omega + | succ fuel => simp [clausesBits, parseClauses] + | cons clause clauses ih => + cases fuel with + | zero => omega + | succ fuel => + have hrest : clauses.length < fuel := by simp only [List.length_cons] at enough; omega + simp [clausesBits, parseClauses, List.append_assoc, ih fuel hrest] + +@[simp] theorem decodeFormula_encoded (formula : Formula) : + decodeFormula (formulaBits formula) = some formula := by + cases formula with + | mk clauses => + have hlen := clauses_length_lt_bits clauses + have parsed := parseClauses_encoded clauses [] ((clausesBits clauses).length + 1) (by omega) + simp only [List.append_nil] at parsed + simp [formulaBits, decodeFormula, parsed] + +theorem formulaBits_injective {first second : Formula} + (same : formulaBits first = formulaBits second) : first = second := by + have parsed := congrArg decodeFormula same + simpa only [decodeFormula_encoded, Option.some.injEq] using parsed + +theorem dense_encoding_bound (formula : Formula) : + (UniqueGamesTheorem.Foundations.Complexity.formulaBits (dense formula)).length ≤ + 9 * (formulaBits formula).length * (formulaBits formula).length + + 10 * (formulaBits formula).length + 2 := by + have h := BinaryFormula.dense_encoding_bound formula + have hm : formula.clauses.length ≤ (formulaBits formula).length := + (clauses_length_lt_bits formula.clauses).le + have hsq := Nat.mul_self_le_mul_self hm + nlinarith + +end PerfectCompleteness.BinaryEncoding + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryGapReduction.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryGapReduction.lean new file mode 100644 index 0000000000000000000000000000000000000000..0b00074f7c036d83e7eb3f0f40746111e16370b0 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryGapReduction.lean @@ -0,0 +1,41 @@ +import OAI.Computability.PerfectCompleteness.Machines.BinaryParsingLemmas +import OAI.Computability.PerfectCompleteness.Machines.EncodingLemmas +import OAI.Computability.PerfectCompleteness.Model +import OAI.Computability.PerfectCompleteness.Reduction.Value +import OAI.Computability.UniqueGames.Machines.MachineFiniteAlphabet + +namespace OAI + +section + +namespace PerfectCompleteness + +open Turing UniqueGamesTheorem.Foundations.Complexity + +namespace BinaryGapReduction + +variable {δ : ℚ} (reduction : BinaryGapReduction δ) + +theorem nonempty (input : List Bool) : (reduction.construct input).edges ≠ [] := + (reduction.construct input).nonempty + +theorem exactly_two (input : List Bool) + (edge : Fin (reduction.construct input).edges.length) (label : Fin reduction.alphabet) : + ((List.finRange (2 * reduction.alphabet)).filter + (fun a => decide ((reduction.construct input).edges[edge].projection.images[a] = label))).length = 2 := + (reduction.construct input).edges[edge].projection.exactlyTwo label + +theorem malformed_soundness (input : List Bool) + (malformed : BinaryEncoding.decodeFormula input = none) : + (reduction.construct input).value ≤ (δ : ℝ) := by + apply reduction.soundness input + rintro ⟨formula, decoded, _⟩ + rw [malformed] at decoded + cases decoded + +end BinaryGapReduction +end PerfectCompleteness + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryHeaderMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryHeaderMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..501c6bf1ee51d223783dbfbd7f4f615f8f5393e7 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryHeaderMachine.lean @@ -0,0 +1,270 @@ +import OAI.Computability.UniqueGames.Machines.MachineCompositionLemmas +import OAI.Computability.UniqueGames.Machines.MachineSubroutineLemmas +import OAI.Computability.UniqueGames.Reduction.MachineTransfer + +namespace OAI + + +namespace PerfectCompleteness.BinaryHeaderMachine + + +open Turing +open UniqueGamesTheorem.Foundations.Complexity +open MachineComposition +open UniqueGamesTheorem.Reduction.MachineTransfer + +abbrev Alphabet {K : Type} (_ : K) := Bool +abbrev State (A : Type) := A × Option Bool + +section Placement + +variable {K Λ A : Type} [DecidableEq K] + +def delimiter (destination : K) (next : Λ) : TM2.Stmt (Alphabet (K := K)) Λ (State A) := + .push destination (fun _ => false) + (.load (fun state => (state.1, none)) (.goto fun _ => next)) + +def tapes (variableTape clauses destination : K) (base : K → List Bool) + (variableCounter clauseCounter output : List Bool) : K → List Bool := + Function.update (Function.update (Function.update base variableTape variableCounter) + clauses clauseCounter) destination output + +@[simp] theorem tapes_variables (variableTape clauses destination : K) + (vc : variableTape ≠ clauses) (vd : variableTape ≠ destination) (base : K → List Bool) + (variableCounter clauseCounter output : List Bool) : + tapes variableTape clauses destination base variableCounter clauseCounter output variableTape = + variableCounter := by + simp [tapes, vc, vd] + +@[simp] theorem tapes_clauses (variableTape clauses destination : K) + (cd : clauses ≠ destination) (base : K → List Bool) + (variableCounter clauseCounter output : List Bool) : + tapes variableTape clauses destination base variableCounter clauseCounter output clauses = + clauseCounter := by + simp [tapes, cd] + +@[simp] theorem tapes_destination (variableTape clauses destination : K) (base : K → List Bool) + (variableCounter clauseCounter output : List Bool) : + tapes variableTape clauses destination base variableCounter clauseCounter output destination = + output := by + simp [tapes] + +theorem tapes_other (variableTape clauses destination k : K) + (kv : k ≠ variableTape) (kc : k ≠ clauses) (kd : k ≠ destination) + (base : K → List Bool) (variableCounter clauseCounter output : List Bool) : + tapes variableTape clauses destination base variableCounter clauseCounter output k = base k := by + simp [tapes, kv, kc, kd] + +private theorem update_variables (variableTape clauses destination : K) + (vc : variableTape ≠ clauses) (vd : variableTape ≠ destination) (base : K → List Bool) + (variableCounter clauseCounter output replacement : List Bool) : + Function.update (tapes variableTape clauses destination base variableCounter clauseCounter output) + variableTape replacement = tapes variableTape clauses destination base replacement clauseCounter output := by + funext k + by_cases hv : k = variableTape + · subst k + simp [tapes, vc, vd] + · by_cases hd : k = destination + · subst k + simp [tapes, hv] + · by_cases hc : k = clauses + · subst k + simp [tapes, hv, hd] + · simp [tapes, hv, hc, hd] + +private theorem update_clauses (variableTape clauses destination : K) + (cd : clauses ≠ destination) (base : K → List Bool) + (variableCounter clauseCounter output replacement : List Bool) : + Function.update (tapes variableTape clauses destination base variableCounter clauseCounter output) + clauses replacement = tapes variableTape clauses destination base variableCounter replacement output := by + funext k + by_cases hc : k = clauses + · subst k + simp [tapes, cd] + · by_cases hd : k = destination + · subst k + simp [tapes, hc] + · simp [tapes, hc, hd] + +private theorem update_destination (variableTape clauses destination : K) (base : K → List Bool) + (variableCounter clauseCounter output replacement : List Bool) : + Function.update (tapes variableTape clauses destination base variableCounter clauseCounter output) + destination replacement = tapes variableTape clauses destination base variableCounter clauseCounter replacement := by + simp [tapes] + +variable (variableTape clauses destination : K) +variable (vc : variableTape ≠ clauses) (vd : variableTape ≠ destination) (cd : clauses ≠ destination) +variable (clauseStart clauseLoop variableStart variableLoop : Λ) (exit : Option Λ) +variable (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) +variable (atClauseStart : program clauseStart = delimiter destination clauseLoop) +variable (atClauseLoop : program clauseLoop = + loopAt clauses destination id false clauseLoop (some variableStart)) +variable (atVariableStart : program variableStart = delimiter destination variableLoop) +variable (atVariableLoop : program variableLoop = + loopAt variableTape destination id false variableLoop exit) +variable (base : K → List Bool) (ambient : A) + +include atClauseStart in +theorem clauseDelimiterStep (variableCounter clauseCounter output : List Bool) + (register : Option Bool) : + TM2.step program + ⟨some clauseStart, (ambient, register), + tapes variableTape clauses destination base variableCounter clauseCounter output⟩ = + some ⟨some clauseLoop, (ambient, none), + tapes variableTape clauses destination base variableCounter clauseCounter (false :: output)⟩ := by + change some (TM2.stepAux (program clauseStart) _ _) = _ + rw [atClauseStart] + simp [delimiter, TM2.stepAux, update_destination] + +include atVariableStart in +theorem variableDelimiterStep (variableCounter clauseCounter output : List Bool) + (register : Option Bool) : + TM2.step program + ⟨some variableStart, (ambient, register), + tapes variableTape clauses destination base variableCounter clauseCounter output⟩ = + some ⟨some variableLoop, (ambient, none), + tapes variableTape clauses destination base variableCounter clauseCounter (false :: output)⟩ := by + change some (TM2.stepAux (program variableStart) _ _) = _ + rw [atVariableStart] + simp [delimiter, TM2.stepAux, update_destination] + +include cd atClauseLoop in +theorem clauseCounterTrace (m : Nat) (variableCounter output : List Bool) + (register : Option Bool) : + (advance (TM2.step program))^[m + 1] + (some ⟨some clauseLoop, (ambient, register), + tapes variableTape clauses destination base variableCounter (List.replicate m true) output⟩) = + some ⟨some variableStart, (ambient, none), + tapes variableTape clauses destination base variableCounter [] (List.replicate m true ++ output)⟩ := by + have h := transferAt_fromTapes (Γ := Alphabet) clauses destination cd id false + clauseLoop (some variableStart) program atClauseLoop + (tapes variableTape clauses destination base variableCounter (List.replicate m true) output) + ambient register + change (nextAt destination program)^[m + 1] + (some ⟨some clauseLoop, (ambient, register), + tapes variableTape clauses destination base variableCounter (List.replicate m true) output⟩) = _ + simpa only [tapes_clauses variableTape clauses destination cd, tapes_destination, + List.length_replicate, List.reverse_replicate, List.map_id_fun, id_eq, + tapesAt, update_clauses variableTape clauses destination cd, update_destination, + nextAt, advance] using h + +include vc vd atVariableLoop in +theorem variableCounterTrace (n : Nat) (clauseCounter output : List Bool) + (register : Option Bool) : + (advance (TM2.step program))^[n + 1] + (some ⟨some variableLoop, (ambient, register), + tapes variableTape clauses destination base (List.replicate n true) clauseCounter output⟩) = + some ⟨exit, (ambient, none), + tapes variableTape clauses destination base [] clauseCounter (List.replicate n true ++ output)⟩ := by + have h := transferAt_fromTapes (Γ := Alphabet) variableTape destination vd id false + variableLoop exit program atVariableLoop + (tapes variableTape clauses destination base (List.replicate n true) clauseCounter output) + ambient register + change (nextAt destination program)^[n + 1] + (some ⟨some variableLoop, (ambient, register), + tapes variableTape clauses destination base (List.replicate n true) clauseCounter output⟩) = _ + simpa only [tapes_variables variableTape clauses destination vc vd, tapes_destination, + List.length_replicate, List.reverse_replicate, List.map_id_fun, id_eq, + tapesAt, update_variables variableTape clauses destination vc vd, update_destination, + nextAt, advance] using h + +private theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +include vc vd cd atClauseStart atClauseLoop atVariableStart atVariableLoop + +theorem headerTrace (n m : Nat) (body : List Bool) (register : Option Bool) : + (advance (TM2.step program))^[n + m + 4] + (some ⟨some clauseStart, (ambient, register), + tapes variableTape clauses destination base + (List.replicate n true) (List.replicate m true) body⟩) = + some ⟨exit, (ambient, none), + tapes variableTape clauses destination base [] [] (encodeWord n ++ encodeWord m ++ body)⟩ := by + have first := clauseDelimiterStep variableTape clauses destination clauseStart clauseLoop program + atClauseStart base ambient (List.replicate n true) (List.replicate m true) body register + change (advance (TM2.step program))^[1] + (some ⟨some clauseStart, (ambient, register), + tapes variableTape clauses destination base (List.replicate n true) (List.replicate m true) body⟩) = _ at first + have second := clauseCounterTrace variableTape clauses destination cd clauseLoop variableStart program + atClauseLoop base ambient m (List.replicate n true) (false :: body) none + have third := variableDelimiterStep variableTape clauses destination variableStart variableLoop program + atVariableStart base ambient (List.replicate n true) [] + (List.replicate m true ++ false :: body) none + change (advance (TM2.step program))^[1] + (some ⟨some variableStart, (ambient, none), + tapes variableTape clauses destination base (List.replicate n true) [] + (List.replicate m true ++ false :: body)⟩) = _ at third + have fourth := variableCounterTrace variableTape clauses destination vc vd variableLoop exit program + atVariableLoop base ambient n [] (false :: (List.replicate m true ++ false :: body)) none + have full := joinTrace (joinTrace (joinTrace first second) third) fourth + have htime : ((1 + (m + 1)) + 1) + (n + 1) = n + m + 4 := by omega + rw [htime] at full + simpa only [encodeWord, List.append_assoc, List.singleton_append, + List.cons_append, List.nil_append] using full + +def headerInTime (n m : Nat) (body : List Bool) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some clauseStart, (ambient, register), + tapes variableTape clauses destination base (List.replicate n true) (List.replicate m true) body⟩ + (some ⟨exit, (ambient, none), + tapes variableTape clauses destination base [] [] (encodeWord n ++ encodeWord m ++ body)⟩) + (n + m + 4) where + steps := n + m + 4 + evals_in_steps := headerTrace variableTape clauses destination vc vd cd + clauseStart clauseLoop variableStart variableLoop exit program + atClauseStart atClauseLoop atVariableStart atVariableLoop base ambient n m body register + steps_le_m := Nat.le_refl _ + +end Placement + +abbrev ConcreteTape := Fin 3 +abbrev ConcreteLabel := Fin 4 + +def concreteProgram (label : ConcreteLabel) : + TM2.Stmt (Alphabet (K := ConcreteTape)) ConcreteLabel (State Unit) := + if label = 0 then delimiter 2 1 + else if label = 1 then loopAt 1 2 id false 1 (some 2) + else if label = 2 then delimiter 2 3 + else loopAt 0 2 id false 3 none + +abbrev machine : FinTM2 where + K := ConcreteTape + k₀ := 0 + k₁ := 2 + Γ := Alphabet + Λ := ConcreteLabel + main := 0 + σ := State Unit + initialState := ((), none) + m := concreteProgram + +def start (n m : Nat) (body : List Bool) : machine.Cfg := + ⟨some 0, ((), none), + tapes 0 1 2 (fun _ : ConcreteTape => []) (List.replicate n true) (List.replicate m true) body⟩ + +theorem haltList_eq (body : List Bool) : + haltList machine body = + ⟨none, ((), none), tapes 0 1 2 (fun _ : ConcreteTape => []) [] [] body⟩ := by + unfold haltList + congr 1 + funext k + fin_cases k <;> simp [machine, tapes] + +def machineInTime (n m : Nat) (body : List Bool) : + StateTransition.EvalsToInTime machine.step (start n m body) + (some (haltList machine (encodeWord n ++ encodeWord m ++ body))) (n + m + 4) := by + rw [haltList_eq] + exact headerInTime (0 : ConcreteTape) 1 2 (by decide) (by decide) (by decide) + (0 : ConcreteLabel) 1 2 3 none concreteProgram + (by simp [concreteProgram]) (by simp [concreteProgram]) + (by simp [concreteProgram]) (by simp [concreteProgram]) + (fun _ => []) () n m body none + +theorem machine_finiteAlphabet (k : machine.K) : Finite (machine.Γ k) := by + change Finite Bool + infer_instance + +end PerfectCompleteness.BinaryHeaderMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryInputReduction.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryInputReduction.lean new file mode 100644 index 0000000000000000000000000000000000000000..de8a4cf92a5015801e9c72a3b3f66a2d2abd6199 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryInputReduction.lean @@ -0,0 +1,38 @@ +import OAI.Computability.PerfectCompleteness.Machines.BinaryRenameMachine +import OAI.Computability.PerfectCompleteness.Machines.BinaryTotalInputMachine +import OAI.Computability.UniqueGames.Machines.MachineLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.BinaryInputReduction + +open Turing UniqueGamesTheorem.Foundations.Complexity + +noncomputable def computation : + TM2ComputableInPolyTime (id : List Bool → List Bool) formulaBits BinaryLanguage.totalRename := by + change TM2ComputableInPolyTime (id : List Bool → List Bool) formulaBits + (fun input => BinaryOccurrenceRename.renamed (BinaryLanguage.totalParsed input)) + exact MachineSequential.composeBits BinaryTotalInputMachine.computableInPolyTime + BinaryRenameMachine.computableInPolyTime + +theorem computation_finiteAlphabet : MachineFiniteAlphabet.FiniteAlphabet computation.tm := + MachineFiniteAlphabet.composeBits BinaryTotalInputMachine.computableInPolyTime + BinaryRenameMachine.computableInPolyTime + BinaryTotalInputMachine.computation_finiteAlphabet + BinaryRenameMachine.computation_finiteAlphabet + +noncomputable def reduction : CookLevin.PolynomialThreeSATReduction BinaryLanguage.language where + reduce := BinaryLanguage.totalRename + computation := computation + correct input := (BinaryLanguage.totalRename_satisfiable_iff input).symm + +theorem reduction_finiteAlphabet : MachineFiniteAlphabet.FiniteAlphabet reduction.computation.tm := + computation_finiteAlphabet + +end PerfectCompleteness.BinaryInputReduction + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryLiteralMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryLiteralMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..38550f455a9ef019a80bbcd473fdffd8efb54b2c --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryLiteralMachine.lean @@ -0,0 +1,330 @@ +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.NormNum +import OAI.Computability.PerfectCompleteness.Machines.BinaryNameSearch +import OAI.Computability.UniqueGames.Machines.MachineDrain +import OAI.Computability.UniqueGames.Machines.MachineSubroutineLemmas + +namespace OAI + + +namespace PerfectCompleteness.BinaryLiteralMachine + + +open Turing +open UniqueGamesTheorem.Foundations.Complexity +open MachineComposition +open UniqueGamesTheorem.Reduction.MachineTransfer + +variable {K Λ A : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool +abbrev State (A : Type) := BinaryNameCompare.State (A × Bool) +abbrev clean (ambient : A) (sign : Bool := false) : State A := + BinaryNameCompare.clean (ambient, sign) + +inductive Label + | readSign | scanKey | copyOut | copyBack + | search (label : BinaryNameSearch.Label) + | drainSearch | drainKey | emitIndex | emitSign + deriving DecidableEq, Fintype + +def searchTapes (tape : Fin 9 → K) : Fin 6 → K + | 0 => tape 3 + | 1 => tape 2 + | 2 => tape 4 + | 3 => tape 5 + | 4 => tape 6 + | 5 => tape 7 + +omit [DecidableEq K] in +theorem searchTapes_injective (tape : Fin 9 → K) (distinct : Function.Injective tape) : + Function.Injective (searchTapes tape) := by + intro i j h + fin_cases i <;> fin_cases j <;> simp only [searchTapes] at h + all_goals first | rfl | have heq := congrArg Fin.val (distinct h); norm_num at heq + +def finish (exit : Option Λ) : TM2.Stmt (Alphabet (K := K)) Λ (State A) := + .load (fun state => clean state.1.1.1) + (match exit with + | none => .halt + | some label => .goto fun _ => label) + +def readSign (tape : Fin 9 → K) (next : Λ) (malformed : Option Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (State A) := + .push (tape 7) (fun _ => false) + (.pop (tape 0) (fun state head => (state.1, head)) + (.branch (fun state => state.2.isSome) + (.load (fun state => clean state.1.1.1 (state.2.getD false)) (.goto fun _ => next)) + (finish malformed))) + +def emitSign (output : K) (exit : Option Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (State A) := + .branch (fun state => state.1.1.2) + (.push output (fun _ => true) (.push output (fun _ => false) (finish exit))) + (.push output (fun _ => false) (finish exit)) + +def instruction (tape : Fin 9 → K) (labels : Label → Λ) + (exit malformed : Option Λ) : Label → TM2.Stmt (Alphabet (K := K)) Λ (State A) + | .readSign => readSign tape (labels .scanKey) malformed + | .scanKey => MachineStateEquiv.statement (BinaryNameCompare.scanStateEquiv (A × Bool)) + (BinaryNameMachine.scan (tape 0) (tape 2) (labels .scanKey) + (some (labels .copyOut)) malformed) + | .copyOut => loopAt (tape 1) (tape 6) id false + (labels .copyOut) (some (labels .copyBack)) + | .copyBack => MachineCopy.forkLoop (tape 6) (tape 1) (tape 3) false + (labels .copyBack) (some (labels (.search .sign))) + | .search l => BinaryNameSearch.instruction (searchTapes tape) + (fun l => labels (.search l)) (some (labels .drainSearch)) malformed malformed l + | .drainSearch => MachineDrain.drain (tape 3) (labels .drainSearch) + (some (labels .drainKey)) + | .drainKey => MachineDrain.drain (tape 2) (labels .drainKey) + (some (labels .emitIndex)) + | .emitIndex => loopAt (tape 7) (tape 8) id false + (labels .emitIndex) (some (labels .emitSign)) + | .emitSign => emitSign (tape 8) exit + +def signWord (sign : Bool) : List Bool := encodeWord (if sign then 1 else 0) + +def index (tokens : List BinaryNameSearch.Token) (bits : List Bool) : Nat := + (BinaryNameSearch.payloads tokens).idxOf bits + +def outputWord (tokens : List BinaryNameSearch.Token) (bits : List Bool) (sign : Bool) : + List Bool := encodeWord (index tokens bits) ++ signWord sign + +def steps (tokens : List BinaryNameSearch.Token) (bits : List Bool) : Nat := + 1 + (bits.length + 1) + 2 * ((BinaryNameSearch.stream tokens).length + 1) + + BinaryNameSearch.steps tokens bits + + ((BinaryNameSearch.stream (BinaryNameSearch.afterMatch tokens bits)).length + 1) + + (bits.length + 1) + (index tokens bits + 2) + 1 + +theorem afterMatch_length_le (tokens : List BinaryNameSearch.Token) (bits : List Bool) : + (BinaryNameSearch.stream (BinaryNameSearch.afterMatch tokens bits)).length ≤ + (BinaryNameSearch.stream tokens).length := by + induction tokens with + | nil => simp [BinaryNameSearch.afterMatch] + | cons token tokens ih => + simp only [BinaryNameSearch.afterMatch, BinaryNameSearch.stream_cons, List.length_append] + split <;> omega + +theorem steps_le (tokens : List BinaryNameSearch.Token) (bits : List Bool) + (present : bits ∈ BinaryNameSearch.payloads tokens) : + steps tokens bits ≤ + 3 * ((BinaryNameSearch.stream tokens).length + bits.length) ^ 2 + + 13 * ((BinaryNameSearch.stream tokens).length + bits.length) + 9 := by + have search := BinaryNameSearch.steps_le_stream tokens bits + have suffix := afterMatch_length_le tokens bits + have idx : index tokens bits < tokens.length := by + have h := List.idxOf_lt_length_iff.mpr present + simpa [index, BinaryNameSearch.payloads] using h + have count : tokens.length ≤ (BinaryNameSearch.stream tokens).length := by + rw [BinaryNameSearch.stream_length] + omega + unfold steps + nlinarith [Nat.zero_le ((BinaryNameSearch.stream tokens).length * bits.length)] + +@[simp] theorem stepAux_finish (exit : Option Λ) (state : State A) (base : K → List Bool) : + TM2.stepAux (finish exit) state base = ⟨exit, clean state.1.1.1, base⟩ := by + cases exit <;> rfl + +private theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +theorem literalTrace (tape : Fin 9 → K) (distinct : Function.Injective tape) + (labels : Label → Λ) (exit malformed : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ l, program (labels l) = instruction tape labels exit malformed l) + (base : K → List Bool) (tokens : List BinaryNameSearch.Token) + (sign : Bool) (bits suffix : List Bool) + (canonical : BinaryNameMachine.canonical bits = true) + (tokensCanonical : ∀ token ∈ tokens, BinaryNameMachine.canonical token.2 = true) + (present : bits ∈ BinaryNameSearch.payloads tokens) + (cursor : base (tape 0) = sign :: (BinaryNameMachine.frame bits ++ suffix)) + (permanent : base (tape 1) = BinaryNameSearch.stream tokens) + (empty : ∀ i : Fin 9, 2 ≤ i.val → i.val ≤ 7 → base (tape i) = []) + (ambient : A) : + (advance (TM2.step program))^[steps tokens bits] + (some ⟨some (labels .readSign), clean ambient, base⟩) = + some ⟨exit, clean ambient, + Function.update (Function.update base (tape 0) suffix) (tape 8) + ((outputWord tokens bits sign).reverse ++ base (tape 8))⟩ := by + have hd (i j : Fin 9) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + have he (i : Fin 9) (hlo : 2 ≤ i.val := by decide) (hhi : i.val ≤ 7 := by decide) : + base (tape i) = [] := empty i hlo hhi + let s₁ := Function.update (Function.update base (tape 7) [false]) (tape 0) + (BinaryNameMachine.frame bits ++ suffix) + let s₂ := Function.update (Function.update s₁ (tape 0) suffix) (tape 2) bits.reverse + let s₃ := Function.update s₂ (tape 3) (BinaryNameSearch.stream tokens) + let tail := BinaryNameSearch.stream (BinaryNameSearch.afterMatch tokens bits) + let s₄ := tapesAt (tape 3) (tape 7) s₃ tail (encodeWord (index tokens bits)) + let s₅ := Function.update s₄ (tape 3) [] + let s₆ := Function.update s₅ (tape 2) [] + let s₇ := tapesAt (tape 7) (tape 8) s₆ [] + ((encodeWord (index tokens bits)).reverse ++ s₆ (tape 8)) + let s₈ := Function.update s₇ (tape 8) ((signWord sign).reverse ++ s₇ (tape 8)) + have signRun : (advance (TM2.step program))^[1] + (some ⟨some (labels .readSign), clean ambient, base⟩) = + some ⟨some (labels .scanKey), clean ambient sign, s₁⟩ := by + change some (TM2.stepAux (program (labels .readSign)) _ _) = _ + rw [atLabels .readSign] + simp [instruction, readSign, TM2.stepAux, clean, BinaryNameCompare.clean, + cursor, he 7, hd 0 7 (by decide), s₁] + have s₁cursor : s₁ (tape 0) = BinaryNameMachine.frame bits ++ suffix := by simp [s₁] + have s₁key : s₁ (tape 2) = [] := by + simp [s₁, hd 2 0 (by decide), hd 2 7 (by decide), he 2] + have keyRun : (advance (TM2.step program))^[bits.length + 1] + (some ⟨some (labels .scanKey), clean ambient sign, s₁⟩) = + some ⟨some (labels .copyOut), clean ambient sign, s₂⟩ := by + let e := BinaryNameCompare.scanStateEquiv (A × Bool) + let back := MachineStateEquiv.program e.symm program + have atScan : back (labels .scanKey) = + BinaryNameMachine.scan (tape 0) (tape 2) (labels .scanKey) + (some (labels .copyOut)) malformed := by + change MachineStateEquiv.statement e.symm (program (labels .scanKey)) = _ + rw [atLabels .scanKey] + exact MachineStateEquiv.statement_symm_statement e _ + have backForward : MachineStateEquiv.program e back = program := by + funext l + change MachineStateEquiv.statement e (MachineStateEquiv.statement e.symm (program l)) = _ + exact MachineStateEquiv.statement_symm_statement e.symm _ + have initial : tapesAt (tape 0) (tape 2) s₁ + (BinaryNameMachine.frame bits ++ suffix) [] = s₁ := by + rw [← s₁cursor, ← s₁key] + exact tapesAt_self _ _ _ + have native := BinaryNameMachine.framedTrace (tape 0) (tape 2) (hd 0 2 (by decide)) + (labels .scanKey) (some (labels .copyOut)) malformed back atScan s₁ + ((ambient, sign), false) bits suffix [] none + simp only [canonical, ↓reduceIte, initial, List.append_nil] at native + have transported := MachineStateEquiv.trace e back _ _ _ native + rw [backForward] at transported + simpa only [MachineStateEquiv.configuration, e, BinaryNameCompare.scanStateEquiv, Equiv.coe_fn_mk, + BinaryNameMachine.clean, clean, BinaryNameCompare.clean, s₂, tapesAt] using transported + have s₂permanent : s₂ (tape 1) = BinaryNameSearch.stream tokens := by + simpa [s₂, s₁, hd 1 0 (by decide), hd 1 2 (by decide), hd 1 7 (by decide)] using permanent + have s₂empty (i : Fin 9) (hi : i = 3 ∨ i = 4 ∨ i = 5 ∨ i = 6) : s₂ (tape i) = [] := by + rcases hi with rfl | rfl | rfl | rfl <;> + simp [s₂, s₁, hd, he] + have copyRun : (advance (TM2.step program))^[2 * ((BinaryNameSearch.stream tokens).length + 1)] + (some ⟨some (labels .copyOut), clean ambient sign, s₂⟩) = + some ⟨some (labels (.search .sign)), clean ambient sign, s₃⟩ := by + have h := MachineCopy.copyTrace (tape 1) (tape 3) (tape 6) + (hd 1 3 (by decide)) (hd 1 6 (by decide)) (hd 3 6 (by decide)) false + (labels .copyOut) (labels .copyBack) (some (labels (.search .sign))) program + (atLabels .copyOut) (atLabels .copyBack) s₂ + (s₂empty 6 (by simp)) ((ambient, sign), false, none) none + simpa only [s₂permanent, s₂empty 3 (by simp), List.append_nil, + clean, BinaryNameCompare.clean, s₃] using h + have s₃key : s₃ (tape 2) = bits.reverse := by + simp [s₃, s₂, hd 2 3 (by decide)] + have s₃counter : s₃ (tape 7) = [false] := by + simp [s₃, s₂, s₁, hd 7 3 (by decide), hd 7 2 (by decide), hd 7 0 (by decide)] + have s₃stream : s₃ (tape 3) = BinaryNameSearch.stream tokens := by simp [s₃] + have searchRun : (advance (TM2.step program))^[BinaryNameSearch.steps tokens bits] + (some ⟨some (labels (.search .sign)), clean ambient sign, s₃⟩) = + some ⟨some (labels .drainSearch), clean ambient sign, s₄⟩ := by + have h := BinaryNameSearch.searchTrace (searchTapes tape) + (searchTapes_injective tape distinct) (fun l => labels (.search l)) + (some (labels .drainSearch)) malformed malformed program + (fun l => atLabels (.search l)) s₃ (ambient, sign) tokens bits [] [false] + tokensCanonical present s₃key + (by simpa [s₃, searchTapes, hd 4 3 (by decide)] using s₂empty 4 (by simp)) + (by simpa [s₃, searchTapes, hd 5 3 (by decide)] using s₂empty 5 (by simp)) + (by simpa [s₃, searchTapes, hd 6 3 (by decide)] using s₂empty 6 (by simp)) + have initial : tapesAt (tape 3) (tape 7) s₃ (BinaryNameSearch.stream tokens) [false] = s₃ := by + rw [← s₃stream, ← s₃counter] + exact tapesAt_self _ _ _ + simpa only [searchTapes, List.append_nil, initial, clean, BinaryNameSearch.clean, + s₄, tail, encodeWord, index] using h + have s₄stream : s₄ (tape 3) = tail := by simp [s₄, hd 3 7 (by decide)] + have drainSearchRun : (advance (TM2.step program))^[tail.length + 1] + (some ⟨some (labels .drainSearch), clean ambient sign, s₄⟩) = + some ⟨some (labels .drainKey), clean ambient sign, s₅⟩ := by + have h := MachineDrain.drainTrace (tape 3) (labels .drainSearch) + (some (labels .drainKey)) program (atLabels .drainSearch) s₄ tail + ((ambient, sign), false, none) none + have initial : Function.update s₄ (tape 3) tail = s₄ := by + rw [← s₄stream]; exact Function.update_eq_self _ _ + simpa only [initial, clean, BinaryNameCompare.clean, s₅] using h + have s₅key : s₅ (tape 2) = bits.reverse := by + simp [s₅, s₄, tapesAt, hd 2 3 (by decide), hd 2 7 (by decide), s₃key] + have drainKeyRun : (advance (TM2.step program))^[bits.length + 1] + (some ⟨some (labels .drainKey), clean ambient sign, s₅⟩) = + some ⟨some (labels .emitIndex), clean ambient sign, s₆⟩ := by + have h := MachineDrain.drainTrace (tape 2) (labels .drainKey) + (some (labels .emitIndex)) program (atLabels .drainKey) s₅ bits.reverse + ((ambient, sign), false, none) none + have initial : Function.update s₅ (tape 2) bits.reverse = s₅ := by + rw [← s₅key]; exact Function.update_eq_self _ _ + simpa only [initial, List.length_reverse, clean, BinaryNameCompare.clean, s₆] using h + have s₆index : s₆ (tape 7) = encodeWord (index tokens bits) := by + simp [s₆, s₅, s₄, hd 7 2 (by decide), hd 7 3 (by decide)] + have indexRun : (advance (TM2.step program))^[index tokens bits + 2] + (some ⟨some (labels .emitIndex), clean ambient sign, s₆⟩) = + some ⟨some (labels .emitSign), clean ambient sign, s₇⟩ := by + change (nextAt (Γ := Alphabet) (tape 8) program)^[index tokens bits + 2] + (some ⟨some (labels .emitIndex), (((ambient, sign), false, none), none), s₆⟩) = + some ⟨some (labels .emitSign), (((ambient, sign), false, none), none), s₇⟩ + have h := transferAt_fromTapes (Γ := Alphabet) (tape 7) (tape 8) + (hd 7 8 (by decide)) id false (labels .emitIndex) (some (labels .emitSign)) program + (atLabels .emitIndex) s₆ ((ambient, sign), false, none) none + have time : index tokens bits + 1 + 1 = index tokens bits + 2 := by omega + simpa only [s₆index, encodeWord_length, List.map_id_fun, id_eq, time, s₇] using h + have emitRun : (advance (TM2.step program))^[1] + (some ⟨some (labels .emitSign), clean ambient sign, s₇⟩) = + some ⟨exit, clean ambient, s₈⟩ := by + change some (TM2.stepAux (program (labels .emitSign)) _ _) = _ + rw [atLabels .emitSign] + cases sign <;> simp [instruction, emitSign, clean, BinaryNameCompare.clean, + TM2.stepAux, signWord, encodeWord, s₈, Function.update_idem] + have full := joinTrace (joinTrace (joinTrace (joinTrace (joinTrace (joinTrace + (joinTrace signRun keyRun) copyRun) searchRun) drainSearchRun) drainKeyRun) indexRun) emitRun + have finalTapes : s₈ = Function.update (Function.update base (tape 0) suffix) (tape 8) + ((outputWord tokens bits sign).reverse ++ base (tape 8)) := by + funext k + by_cases h8 : k = tape 8 + · subst k + simp [s₈, s₇, s₆, s₅, s₄, s₃, s₂, s₁, tapesAt, outputWord, + List.reverse_append, List.append_assoc, hd] + · by_cases h0 : k = tape 0 + · subst k + simp [s₈, s₇, s₆, s₅, s₄, s₃, s₂, s₁, tapesAt, hd] + · by_cases h2 : k = tape 2 + · subst k + simp [s₈, s₇, s₆, s₅, s₄, s₃, s₂, s₁, tapesAt, hd, he 2] + · by_cases h3 : k = tape 3 + · subst k + simp [s₈, s₇, s₆, s₅, s₄, s₃, s₂, s₁, tapesAt, hd, he 3] + · by_cases h7 : k = tape 7 + · subst k + simp [s₈, s₇, s₆, s₅, s₄, s₃, s₂, s₁, tapesAt, hd, he 7] + · simp [s₈, s₇, s₆, s₅, s₄, s₃, s₂, s₁, tapesAt, h8, h0, h2, h3, h7] + simpa only [steps, tail, finalTapes] using full + +def literalInTime (tape : Fin 9 → K) (distinct : Function.Injective tape) + (labels : Label → Λ) (exit malformed : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ l, program (labels l) = instruction tape labels exit malformed l) + (base : K → List Bool) (tokens : List BinaryNameSearch.Token) + (sign : Bool) (bits suffix : List Bool) + (canonical : BinaryNameMachine.canonical bits = true) + (tokensCanonical : ∀ token ∈ tokens, BinaryNameMachine.canonical token.2 = true) + (present : bits ∈ BinaryNameSearch.payloads tokens) + (cursor : base (tape 0) = sign :: (BinaryNameMachine.frame bits ++ suffix)) + (permanent : base (tape 1) = BinaryNameSearch.stream tokens) + (empty : ∀ i : Fin 9, 2 ≤ i.val → i.val ≤ 7 → base (tape i) = []) + (ambient : A) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .readSign), clean ambient, base⟩ + (some ⟨exit, clean ambient, + Function.update (Function.update base (tape 0) suffix) (tape 8) + ((outputWord tokens bits sign).reverse ++ base (tape 8))⟩) + (3 * ((BinaryNameSearch.stream tokens).length + bits.length) ^ 2 + + 13 * ((BinaryNameSearch.stream tokens).length + bits.length) + 9) where + steps := steps tokens bits + evals_in_steps := literalTrace tape distinct labels exit malformed program atLabels base + tokens sign bits suffix canonical tokensCanonical present cursor permanent empty ambient + steps_le_m := steps_le tokens bits present + +end PerfectCompleteness.BinaryLiteralMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryNameCompare.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryNameCompare.lean new file mode 100644 index 0000000000000000000000000000000000000000..d05a1446c9a8ed91452d23f47ed44a70be4d7953 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryNameCompare.lean @@ -0,0 +1,220 @@ +import OAI.Computability.PerfectCompleteness.Machines.BinaryNameMachine +import OAI.Computability.UniqueGames.Machines.MachineCompositionLemmas +import OAI.Computability.UniqueGames.Machines.MachineCopy + +namespace OAI + + +namespace PerfectCompleteness.BinaryNameCompare + + +open Turing +open UniqueGamesTheorem.Foundations.Complexity +open MachineComposition + +variable {K Λ A : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool +abbrev State (A : Type) := (A × Bool × Option Bool) × Option Bool + +def clean (ambient : A) : State A := ((ambient, false, none), none) + +def scanStateEquiv (A : Type) : BinaryNameMachine.State (A × Bool) ≃ State A where + toFun s := ((s.1.1, s.1.2, s.2.1), s.2.2) + invFun s := ((s.1.1, s.1.2.1), s.1.2.2, s.2) + left_inv := by rintro ⟨⟨a, b⟩, c, d⟩; rfl + right_inv := by rintro ⟨⟨a, b, c⟩, d⟩; rfl + +def compareStateEquiv (A : Type) : MachineCompare.State A ≃ State A where + toFun s := ((s.1, s.2.1, s.2.2.1), s.2.2.2) + invFun s := (s.1.1, s.1.2.1, s.1.2.2, s.2) + left_inv := by rintro ⟨a, b, c, d⟩; rfl + right_inv := by rintro ⟨⟨a, b, c⟩, d⟩; rfl + +inductive Label + | scan | copyOut | copyBack | compare + deriving DecidableEq + +protected abbrev Label.enumList : List Label := [.scan, .copyOut, .copyBack, .compare] + +protected theorem Label.enumList_getElem?_ctorIdx_eq (x : Label) : + Label.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem Label.enumList_nodup : Label.enumList.Nodup := by decide + +instance : Fintype Label where + elems := ⟨Label.enumList, Label.enumList_nodup⟩ + complete x := by cases x <;> decide + +def instruction (tape : Fin 5 → K) (labels : Label → Λ) + (equalExit differentExit malformedExit : Option Λ) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (State A) + | .scan => MachineStateEquiv.statement (scanStateEquiv A) + (BinaryNameMachine.scan (tape 0) (tape 2) (labels .scan) + (some (labels .copyOut)) malformedExit) + | .copyOut => UniqueGamesTheorem.Reduction.MachineTransfer.loopAt (tape 1) (tape 4) id false + (labels .copyOut) (some (labels .copyBack)) + | .copyBack => MachineCopy.forkLoop (tape 4) (tape 1) (tape 3) false + (labels .copyBack) (some (labels .compare)) + | .compare => MachineStateEquiv.statement (compareStateEquiv A) + (MachineCompare.loop (tape 2) (tape 3) (labels .compare) equalExit differentExit) + +def steps (payloadLength keyLength : Nat) : Nat := + (payloadLength + 1) + 2 * (keyLength + 1) + (max payloadLength keyLength + 1) + +theorem steps_le (payloadLength keyLength : Nat) : + steps payloadLength keyLength ≤ 2 * payloadLength + 3 * keyLength + 4 := by + unfold steps + omega + +private theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +theorem compareTrace (tape : Fin 5 → K) (distinct : Function.Injective tape) + (labels : Label → Λ) (equalExit differentExit malformedExit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ l, program (labels l) = + instruction tape labels equalExit differentExit malformedExit l) + (base : K → List Bool) (bits suffix key : List Bool) + (canonical : BinaryNameMachine.canonical bits = true) + (sourceWord : base (tape 0) = BinaryNameMachine.frame bits ++ suffix) + (keyWord : base (tape 1) = key) + (candidateEmpty : base (tape 2) = []) (copyEmpty : base (tape 3) = []) + (scratchEmpty : base (tape 4) = []) (ambient : A) : + (advance (TM2.step program))^[steps bits.length key.length] + (some ⟨some (labels .scan), clean ambient, base⟩) = + some ⟨if bits.reverse = key then equalExit else differentExit, + clean ambient, Function.update base (tape 0) suffix⟩ := by + have hd (i j : Fin 5) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + let finalBase := Function.update base (tape 0) suffix + let afterScan := Function.update finalBase (tape 2) bits.reverse + let afterCopy := Function.update afterScan (tape 3) key + have scanRun : (advance (TM2.step program))^[bits.length + 1] + (some ⟨some (labels .scan), clean ambient, base⟩) = + some ⟨some (labels .copyOut), clean ambient, afterScan⟩ := by + let back := MachineStateEquiv.program (scanStateEquiv A).symm program + have atScan : back (labels .scan) = + BinaryNameMachine.scan (tape 0) (tape 2) (labels .scan) + (some (labels .copyOut)) malformedExit := by + change MachineStateEquiv.statement (scanStateEquiv A).symm + (program (labels .scan)) = _ + rw [atLabels .scan] + exact MachineStateEquiv.statement_symm_statement (scanStateEquiv A) _ + have backForward : MachineStateEquiv.program (scanStateEquiv A) back = program := by + funext l + change MachineStateEquiv.statement (scanStateEquiv A) + (MachineStateEquiv.statement (scanStateEquiv A).symm (program l)) = _ + simpa only [Equiv.symm_symm] using + MachineStateEquiv.statement_symm_statement (scanStateEquiv A).symm (program l) + have initialTapes : UniqueGamesTheorem.Reduction.MachineTransfer.tapesAt (tape 0) (tape 2) + base (BinaryNameMachine.frame bits ++ suffix) [] = base := by + rw [← sourceWord, ← candidateEmpty] + exact UniqueGamesTheorem.Reduction.MachineTransfer.tapesAt_self _ _ _ + have native := BinaryNameMachine.framedTrace (tape 0) (tape 2) (hd 0 2 (by decide)) + (labels .scan) (some (labels .copyOut)) malformedExit back atScan base (ambient, false) + bits suffix [] none + simp only [canonical, ↓reduceIte, initialTapes, List.append_nil] at native + have transported := MachineStateEquiv.trace (scanStateEquiv A) back _ _ _ native + rw [backForward] at transported + simpa only [MachineStateEquiv.configuration, scanStateEquiv, Equiv.coe_fn_mk, BinaryNameMachine.clean, + clean, afterScan, finalBase, UniqueGamesTheorem.Reduction.MachineTransfer.tapesAt] using transported + have afterScanKey : afterScan (tape 1) = key := by + simpa [afterScan, finalBase, hd 1 2 (by decide), hd 1 0 (by decide)] using keyWord + have afterScanCopy : afterScan (tape 3) = [] := by + simpa [afterScan, finalBase, hd 3 2 (by decide), hd 3 0 (by decide)] using copyEmpty + have afterScanScratch : afterScan (tape 4) = [] := by + simpa [afterScan, finalBase, hd 4 2 (by decide), hd 4 0 (by decide)] using scratchEmpty + have copyRun : (advance (TM2.step program))^[2 * (key.length + 1)] + (some ⟨some (labels .copyOut), clean ambient, afterScan⟩) = + some ⟨some (labels .compare), clean ambient, afterCopy⟩ := by + have h := MachineCopy.copyTrace (tape 1) (tape 3) (tape 4) + (hd 1 3 (by decide)) (hd 1 4 (by decide)) (hd 3 4 (by decide)) false + (labels .copyOut) (labels .copyBack) (some (labels .compare)) program + (atLabels .copyOut) (atLabels .copyBack) afterScan afterScanScratch + (ambient, false, none) none + simpa only [afterScanKey, afterScanCopy, List.append_nil, clean, afterCopy] using h + have candidateWord : afterCopy (tape 2) = bits.reverse := by + simp [afterCopy, afterScan, hd 2 3 (by decide)] + have copiedWord : afterCopy (tape 3) = key := by simp [afterCopy] + have restored : UniqueGamesTheorem.Reduction.MachineTransfer.tapesAt (tape 2) (tape 3) + afterCopy [] [] = finalBase := by + funext k + by_cases hc : k = tape 2 + · subst k + simp [UniqueGamesTheorem.Reduction.MachineTransfer.tapesAt, afterCopy, afterScan, finalBase, + hd 2 3 (by decide), hd 2 0 (by decide), candidateEmpty] + · by_cases hk : k = tape 3 + · subst k + simp [UniqueGamesTheorem.Reduction.MachineTransfer.tapesAt, afterCopy, afterScan, finalBase, + hd 3 0 (by decide), copyEmpty] + · simp [UniqueGamesTheorem.Reduction.MachineTransfer.tapesAt, afterCopy, afterScan, hc, hk] + have comparisonRun : (advance (TM2.step program))^[max bits.length key.length + 1] + (some ⟨some (labels .compare), clean ambient, afterCopy⟩) = + some ⟨if bits.reverse = key then equalExit else differentExit, + clean ambient, finalBase⟩ := by + let back := MachineStateEquiv.program (compareStateEquiv A).symm program + have atCompare : back (labels .compare) = + MachineCompare.loop (tape 2) (tape 3) (labels .compare) equalExit differentExit := by + change MachineStateEquiv.statement (compareStateEquiv A).symm + (program (labels .compare)) = _ + rw [atLabels .compare] + exact MachineStateEquiv.statement_symm_statement (compareStateEquiv A) _ + have backForward : MachineStateEquiv.program (compareStateEquiv A) back = program := by + funext l + change MachineStateEquiv.statement (compareStateEquiv A) + (MachineStateEquiv.statement (compareStateEquiv A).symm (program l)) = _ + simpa only [Equiv.symm_symm] using + MachineStateEquiv.statement_symm_statement (compareStateEquiv A).symm (program l) + have native := MachineCompare.compareTrace_fromTapes (tape 2) (tape 3) + (hd 2 3 (by decide)) (labels .compare) equalExit differentExit back atCompare afterCopy + ambient none none + rw [candidateWord, copiedWord, restored, List.length_reverse] at native + have transported := MachineStateEquiv.trace (compareStateEquiv A) back _ _ _ native + rw [backForward] at transported + simpa only [MachineStateEquiv.configuration, compareStateEquiv, Equiv.coe_fn_mk, clean] using transported + exact joinTrace (joinTrace scanRun copyRun) comparisonRun + +def compareInTime (tape : Fin 5 → K) (distinct : Function.Injective tape) + (labels : Label → Λ) (equalExit differentExit malformedExit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ l, program (labels l) = + instruction tape labels equalExit differentExit malformedExit l) + (base : K → List Bool) (bits suffix key : List Bool) + (canonical : BinaryNameMachine.canonical bits = true) + (sourceWord : base (tape 0) = BinaryNameMachine.frame bits ++ suffix) + (keyWord : base (tape 1) = key) + (candidateEmpty : base (tape 2) = []) (copyEmpty : base (tape 3) = []) + (scratchEmpty : base (tape 4) = []) (ambient : A) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .scan), clean ambient, base⟩ + (some ⟨if bits.reverse = key then equalExit else differentExit, + clean ambient, Function.update base (tape 0) suffix⟩) + (2 * bits.length + 3 * key.length + 4) where + steps := steps bits.length key.length + evals_in_steps := compareTrace tape distinct labels equalExit differentExit malformedExit + program atLabels base bits suffix key canonical sourceWord keyWord + candidateEmpty copyEmpty scratchEmpty ambient + steps_le_m := steps_le bits.length key.length + +def machine : FinTM2 where + K := Fin 5 + k₀ := 0 + k₁ := 1 + Γ _ := Bool + Λ := Label ⊕ Fin 3 + main := .inl .scan + σ := State Unit + initialState := clean () + m label := match label with + | .inl l => instruction id Sum.inl (some (.inr 0)) (some (.inr 1)) (some (.inr 2)) l + | .inr _ => .halt + +theorem machine_finiteAlphabet (k : machine.K) : Finite (machine.Γ k) := by + change Finite Bool + infer_instance + +end PerfectCompleteness.BinaryNameCompare + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryNameMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryNameMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..1634a707692809528a8ea0f71672da441e25fa8c --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryNameMachine.lean @@ -0,0 +1,258 @@ +import Mathlib.Data.List.Induction +import OAI.Computability.UniqueGames.Machines.MachineCompare + +namespace OAI + +section + +namespace PerfectCompleteness.BinaryNameMachine + +open Turing +open UniqueGamesTheorem.Foundations.Complexity +open MachineComposition +open UniqueGamesTheorem.Reduction.MachineTransfer + +def frame : List Bool → List Bool + | [] => [false] + | bit :: bits => true :: bit :: frame bits + +def finalDigit : List Bool → Option Bool → Option Bool + | [], previous => previous + | bit :: bits, _ => finalDigit bits (some bit) + +def canonical (bits : List Bool) : Bool := (finalDigit bits none).getD true + +structure Result where + accepted : Bool + remaining : List Bool + reversedPayload : List Bool + deriving DecidableEq + +def scanSpec : List Bool → List Bool → Option Bool → Result + | [], acc, _ => ⟨false, [], acc⟩ + | false :: rest, acc, last => ⟨last.getD true, rest, acc⟩ + | [true], acc, _ => ⟨false, [], acc⟩ + | true :: bit :: rest, acc, _ => scanSpec rest (bit :: acc) (some bit) + +def steps : List Bool → Nat + | true :: _ :: rest => steps rest + 1 + | _ => 1 + +theorem steps_le (input : List Bool) : steps input ≤ input.length + 1 := by + induction input using List.twoStepInduction with + | nil => simp [steps] + | singleton bit => cases bit <;> simp [steps] + | cons_cons flag bit rest ih _ => + cases flag <;> simp only [steps, List.length_cons] + · omega + · omega + +@[simp] theorem frame_length (bits : List Bool) : + (frame bits).length = 2 * bits.length + 1 := by + induction bits with + | nil => simp [frame] + | cons bit bits ih => simp only [frame, List.length_cons, ih]; omega + +theorem scanSpec_frame (bits suffix acc : List Bool) (last : Option Bool) : + scanSpec (frame bits ++ suffix) acc last = + ⟨(finalDigit bits last).getD true, suffix, bits.reverse ++ acc⟩ := by + induction bits generalizing acc last with + | nil => simp [frame, scanSpec, finalDigit] + | cons bit bits ih => + simpa [frame, scanSpec, finalDigit, List.reverse_cons, List.append_assoc] using + ih (bit :: acc) (some bit) + +@[simp] theorem steps_frame (bits suffix : List Bool) : + steps (frame bits ++ suffix) = bits.length + 1 := by + induction bits with + | nil => simp [frame, steps] + | cons bit bits ih => simp [frame, steps, ih] + +section Program + +variable {K Λ A : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool +abbrev State (A : Type) := A × Option Bool × Option Bool + +def clean (ambient : A) : State A := (ambient, none, none) + +def exitAt (exit : Option Λ) : TM2.Stmt (Alphabet (K := K)) Λ (State A) := + match exit with + | none => .halt + | some label => .goto fun _ => label + +def finish (exit : Option Λ) : TM2.Stmt (Alphabet (K := K)) Λ (State A) := + .load (fun state => clean state.1) (exitAt exit) + +def scan (source destination : K) (again : Λ) (accepted rejected : Option Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (State A) := + .pop source (fun state head => (state.1, state.2.1, head)) + (.branch (fun state => state.2.2.isNone) + (finish rejected) + (.branch (fun state => state.2.2.getD false) + (.pop source (fun state head => (state.1, state.2.1, head)) + (.branch (fun state => state.2.2.isSome) + (.push destination (fun state => state.2.2.getD false) + (.load (fun state => (state.1, state.2.2, none)) + (.goto fun _ => again))) + (finish rejected))) + (.branch (fun state => state.2.1.getD true) + (finish accepted) (finish rejected)))) + +@[simp] theorem stepAux_finish (exit : Option Λ) (state : State A) + (base : K → List Bool) : + TM2.stepAux (finish exit) state base = ⟨exit, clean state.1, base⟩ := by + cases exit <;> rfl + +private theorem update_source (source destination : K) (distinct : source ≠ destination) + (base : K → List Bool) (input output replacement : List Bool) : + Function.update (tapesAt source destination base input output) source replacement = + tapesAt source destination base replacement output := by + funext k + by_cases hs : k = source + · subst k; simp [tapesAt, distinct] + · by_cases hd : k = destination + · subst k; simp [tapesAt, Ne.symm distinct] + · simp [tapesAt, hs, hd] + +private theorem update_destination (source destination : K) + (base : K → List Bool) (input output replacement : List Bool) : + Function.update (tapesAt source destination base input output) destination replacement = + tapesAt source destination base input replacement := by + simp [tapesAt] + +variable (source destination : K) (distinct : source ≠ destination) +variable (again : Λ) (accepted rejected : Option Λ) +variable (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) +variable (atScan : program again = scan source destination again accepted rejected) +variable (base : K → List Bool) (ambient : A) + +include distinct atScan + +theorem step_empty (output : List Bool) (last register : Option Bool) : + TM2.step program + ⟨some again, (ambient, last, register), tapesAt source destination base [] output⟩ = + some ⟨rejected, clean ambient, tapesAt source destination base [] output⟩ := by + change some (TM2.stepAux (program again) _ _) = _ + rw [atScan] + simp [scan, TM2.stepAux, distinct, update_source] + +theorem step_end (rest output : List Bool) (last register : Option Bool) : + TM2.step program + ⟨some again, (ambient, last, register), + tapesAt source destination base (false :: rest) output⟩ = + some ⟨if last.getD true then accepted else rejected, clean ambient, + tapesAt source destination base rest output⟩ := by + change some (TM2.stepAux (program again) _ _) = _ + rw [atScan] + cases h : last.getD true <;> + simp [scan, TM2.stepAux, distinct, update_source, h] + +theorem step_truncated (output : List Bool) (last register : Option Bool) : + TM2.step program + ⟨some again, (ambient, last, register), tapesAt source destination base [true] output⟩ = + some ⟨rejected, clean ambient, tapesAt source destination base [] output⟩ := by + change some (TM2.stepAux (program again) _ _) = _ + rw [atScan] + simp [scan, TM2.stepAux, distinct, update_source] + +theorem step_digit (bit : Bool) (rest output : List Bool) (last register : Option Bool) : + TM2.step program + ⟨some again, (ambient, last, register), + tapesAt source destination base (true :: bit :: rest) output⟩ = + some ⟨some again, (ambient, some bit, none), + tapesAt source destination base rest (bit :: output)⟩ := by + change some (TM2.stepAux (program again) _ _) = _ + rw [atScan] + simp [scan, TM2.stepAux, distinct, update_source, update_destination] + +theorem scanTrace (input output : List Bool) (last register : Option Bool) : + (advance (TM2.step program))^[steps input] + (some ⟨some again, (ambient, last, register), + tapesAt source destination base input output⟩) = + some ⟨if (scanSpec input output last).accepted then accepted else rejected, + clean ambient, tapesAt source destination base + (scanSpec input output last).remaining (scanSpec input output last).reversedPayload⟩ := by + induction input using List.twoStepInduction generalizing output last register with + | nil => + simpa only [steps, scanSpec, Bool.false_eq_true, ite_false, + Function.iterate_one, advance_some] using + step_empty source destination distinct again accepted rejected program atScan base ambient + output last register + | singleton flag => + cases flag + · have h := step_end source destination distinct again accepted rejected program atScan + base ambient [] output last register + cases hlast : last.getD true <;> + simpa [steps, scanSpec, hlast] using h + · simpa only [steps, scanSpec, Bool.false_eq_true, ite_false, + Function.iterate_one, advance_some] using + step_truncated source destination distinct again accepted rejected program atScan base ambient + output last register + | cons_cons flag bit rest ih _ => + cases flag + · have h := step_end source destination distinct again accepted rejected program atScan + base ambient (bit :: rest) output last register + cases hlast : last.getD true <;> + simpa [steps, scanSpec, hlast] using h + · rw [steps, Function.iterate_succ_apply] + simp only [advance_some] + rw [step_digit source destination distinct again accepted rejected program atScan] + exact ih (bit :: output) (some bit) none + +def scanInTime (input output : List Bool) (last register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some again, (ambient, last, register), tapesAt source destination base input output⟩ + (some ⟨if (scanSpec input output last).accepted then accepted else rejected, + clean ambient, tapesAt source destination base + (scanSpec input output last).remaining (scanSpec input output last).reversedPayload⟩) + (input.length + 1) where + steps := steps input + evals_in_steps := scanTrace source destination distinct again accepted rejected program atScan + base ambient input output last register + steps_le_m := steps_le input + +theorem framedTrace (bits suffix output : List Bool) (register : Option Bool) : + (advance (TM2.step program))^[bits.length + 1] + (some ⟨some again, (ambient, none, register), + tapesAt source destination base (frame bits ++ suffix) output⟩) = + some ⟨if canonical bits then accepted else rejected, clean ambient, + tapesAt source destination base suffix (bits.reverse ++ output)⟩ := by + have h := scanTrace source destination distinct again accepted rejected program atScan + base ambient (frame bits ++ suffix) output none register + cases hlast : (finalDigit bits none).getD true <;> + simpa [steps_frame, scanSpec_frame, canonical, hlast] using h + +end Program + +def machine : FinTM2 where + K := Bool + k₀ := false + k₁ := true + Γ _ := Bool + Λ := Fin 3 + main := 0 + σ := State Unit + initialState := clean () + m label := if label = 0 then scan false true 0 (some 1) (some 2) else .halt + +theorem machine_finiteAlphabet (k : machine.K) : Finite (machine.Γ k) := by + change Finite Bool + infer_instance + +def machineInTime (input output : List Bool) : + StateTransition.EvalsToInTime machine.step + ⟨some (0 : Fin 3), clean (), tapesAt false true (fun _ : Bool => []) input output⟩ + (some ⟨if (scanSpec input output none).accepted then some (1 : Fin 3) else some (2 : Fin 3), + clean (), tapesAt false true (fun _ : Bool => []) + (scanSpec input output none).remaining (scanSpec input output none).reversedPayload⟩) + (input.length + 1) := + scanInTime false true (by decide) (0 : Fin 3) (some 1) (some 2) machine.m + (by simp [machine]) (fun _ : Bool => []) () input output none none + +end PerfectCompleteness.BinaryNameMachine + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryNameSearch.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryNameSearch.lean new file mode 100644 index 0000000000000000000000000000000000000000..594ee977ca02a3772c707c3507eb38a5a3e455ef --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryNameSearch.lean @@ -0,0 +1,325 @@ +import Mathlib.Tactic.Linarith +import OAI.Computability.PerfectCompleteness.Machines.BinaryNameCompare + +namespace OAI + +section + +namespace PerfectCompleteness.BinaryNameSearch + +open Turing +open UniqueGamesTheorem.Foundations.Complexity +open MachineComposition +open UniqueGamesTheorem.Reduction.MachineTransfer + +abbrev Token := Bool × List Bool + +def tokenBits (token : Token) : List Bool := + token.1 :: BinaryNameMachine.frame token.2 + +def stream : List Token → List Bool + | [] => [] + | token :: tokens => tokenBits token ++ stream tokens + +def payloads (tokens : List Token) : List (List Bool) := tokens.map Prod.snd + +def afterMatch : List Token → List Bool → List Token + | [], _ => [] + | token :: tokens, key => if token.2 = key then tokens else afterMatch tokens key + +def steps : List Token → List Bool → Nat + | [], _ => 0 + | token :: tokens, key => + 1 + BinaryNameCompare.steps token.2.length key.length + + if token.2 = key then 0 else 1 + steps tokens key + +def payloadSize (tokens : List Token) : Nat := (payloads tokens |>.map List.length).sum + +@[simp] theorem stream_nil : stream [] = [] := rfl + +@[simp] theorem stream_cons (token : Token) (tokens : List Token) : + stream (token :: tokens) = tokenBits token ++ stream tokens := rfl + +@[simp] theorem payloads_nil : payloads [] = [] := rfl + +@[simp] theorem payloads_cons (token : Token) (tokens : List Token) : + payloads (token :: tokens) = token.2 :: payloads tokens := rfl + +@[simp] theorem payloadSize_nil : payloadSize [] = 0 := rfl + +@[simp] theorem payloadSize_cons (token : Token) (tokens : List Token) : + payloadSize (token :: tokens) = token.2.length + payloadSize tokens := rfl + +@[simp] theorem stream_length (tokens : List Token) : + (stream tokens).length = 2 * payloadSize tokens + 2 * tokens.length := by + induction tokens with + | nil => rfl + | cons token tokens ih => + simp only [stream_cons, List.length_append, tokenBits, List.length_cons, + BinaryNameMachine.frame_length, ih, payloadSize_cons] + omega + +theorem steps_le (tokens : List Token) (key : List Bool) : + steps tokens key ≤ 2 * payloadSize tokens + (3 * key.length + 6) * tokens.length := by + induction tokens with + | nil => simp [steps] + | cons token tokens ih => + have h := BinaryNameCompare.steps_le token.2.length key.length + simp only [steps, payloadSize_cons, List.length_cons] + split <;> nlinarith + +theorem steps_le_stream (tokens : List Token) (key : List Bool) : + steps tokens key ≤ (3 * key.length + 7) * (stream tokens).length := by + have h := steps_le tokens key + rw [stream_length] + nlinarith + +section Program + +variable {K Λ A : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool +abbrev State (A : Type) := BinaryNameCompare.State A + +abbrev clean (ambient : A) : State A := BinaryNameCompare.clean ambient + +inductive Label + | sign + | comparison (label : BinaryNameCompare.Label) + | increment + deriving DecidableEq, Fintype + +def compareTapes (tape : Fin 6 → K) : Fin 5 → K := fun i => tape i.castSucc + +omit [DecidableEq K] in +theorem compareTapes_injective (tape : Fin 6 → K) (distinct : Function.Injective tape) : + Function.Injective (compareTapes tape) := by + intro i j h + apply Fin.ext + exact congrArg (fun i : Fin 6 => i.val) (distinct h) + +def exitAt (exit : Option Λ) : TM2.Stmt (Alphabet (K := K)) Λ (State A) := + match exit with + | none => .halt + | some label => .goto fun _ => label + +def finish (exit : Option Λ) : TM2.Stmt (Alphabet (K := K)) Λ (State A) := + .load (fun state => clean state.1.1) (exitAt exit) + +def instruction (tape : Fin 6 → K) (labels : Label → Λ) + (foundExit missingExit malformedExit : Option Λ) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (State A) + | .sign => + .pop (tape 0) (fun state head => (state.1, head)) + (.branch (fun state => state.2.isSome) + (finish (some (labels (.comparison .scan)))) (finish missingExit)) + | .comparison l => BinaryNameCompare.instruction (compareTapes tape) + (fun l => labels (.comparison l)) foundExit (some (labels .increment)) malformedExit l + | .increment => .push (tape 5) (fun _ => true) (.goto fun _ => labels .sign) + +@[simp] theorem stepAux_finish (exit : Option Λ) (state : State A) (base : K → List Bool) : + TM2.stepAux (finish exit) state base = ⟨exit, clean state.1.1, base⟩ := by + cases exit <;> rfl + +private theorem update_source (source counter : K) (distinct : source ≠ counter) + (base : K → List Bool) (input count replacement : List Bool) : + Function.update (tapesAt source counter base input count) source replacement = + tapesAt source counter base replacement count := by + funext k + by_cases hs : k = source + · subst k; simp [tapesAt, distinct] + · by_cases hc : k = counter + · subst k; simp [tapesAt, Ne.symm distinct] + · simp [tapesAt, hs, hc] + +private theorem update_counter (source counter : K) + (base : K → List Bool) (input count replacement : List Bool) : + Function.update (tapesAt source counter base input count) counter replacement = + tapesAt source counter base input replacement := by + simp [tapesAt] + +private theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +variable (tape : Fin 6 → K) (distinct : Function.Injective tape) +variable (labels : Label → Λ) (foundExit missingExit malformedExit : Option Λ) +variable (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) +variable (atLabels : ∀ l, program (labels l) = + instruction tape labels foundExit missingExit malformedExit l) +variable (base : K → List Bool) (ambient : A) + +include distinct atLabels + +theorem signStep (sign : Bool) (input counter : List Bool) : + TM2.step program + ⟨some (labels .sign), clean ambient, + tapesAt (tape 0) (tape 5) base (sign :: input) counter⟩ = + some ⟨some (labels (.comparison .scan)), clean ambient, + tapesAt (tape 0) (tape 5) base input counter⟩ := by + have hd : tape 0 ≠ tape 5 := fun h => (by decide : (0 : Fin 6) ≠ 5) (distinct h) + change some (TM2.stepAux (program (labels .sign)) _ _) = _ + rw [atLabels .sign] + simp [instruction, TM2.stepAux, clean, BinaryNameCompare.clean, hd, update_source] + +theorem emptyStep (counter : List Bool) : + TM2.step program + ⟨some (labels .sign), clean ambient, + tapesAt (tape 0) (tape 5) base [] counter⟩ = + some ⟨missingExit, clean ambient, tapesAt (tape 0) (tape 5) base [] counter⟩ := by + have hd : tape 0 ≠ tape 5 := fun h => (by decide : (0 : Fin 6) ≠ 5) (distinct h) + change some (TM2.stepAux (program (labels .sign)) _ _) = _ + rw [atLabels .sign] + simp [instruction, TM2.stepAux, clean, BinaryNameCompare.clean, hd, update_source] + +omit distinct in +theorem incrementStep (input counter : List Bool) : + TM2.step program + ⟨some (labels .increment), clean ambient, + tapesAt (tape 0) (tape 5) base input counter⟩ = + some ⟨some (labels .sign), clean ambient, + tapesAt (tape 0) (tape 5) base input (true :: counter)⟩ := by + change some (TM2.stepAux (program (labels .increment)) _ _) = _ + rw [atLabels .increment] + simp [instruction, TM2.stepAux, update_counter] + +theorem tokenTrace (token : Token) (key suffix counter : List Bool) + (canonical : BinaryNameMachine.canonical token.2 = true) + (keyWord : base (tape 1) = key.reverse) + (candidateEmpty : base (tape 2) = []) (copyEmpty : base (tape 3) = []) + (scratchEmpty : base (tape 4) = []) : + (advance (TM2.step program))^[1 + BinaryNameCompare.steps token.2.length key.length] + (some ⟨some (labels .sign), clean ambient, + tapesAt (tape 0) (tape 5) base (tokenBits token ++ suffix) counter⟩) = + some ⟨if token.2 = key then foundExit else some (labels .increment), clean ambient, + tapesAt (tape 0) (tape 5) base suffix counter⟩ := by + have hd (i j : Fin 6) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + let initial := tapesAt (tape 0) (tape 5) base + (BinaryNameMachine.frame token.2 ++ suffix) counter + have first : (advance (TM2.step program))^[1] + (some ⟨some (labels .sign), clean ambient, + tapesAt (tape 0) (tape 5) base (tokenBits token ++ suffix) counter⟩) = + some ⟨some (labels (.comparison .scan)), clean ambient, initial⟩ := by + simpa only [Function.iterate_one, advance_some, tokenBits, List.cons_append] using + signStep tape distinct labels foundExit missingExit malformedExit program atLabels + base ambient token.1 (BinaryNameMachine.frame token.2 ++ suffix) counter + have second := BinaryNameCompare.compareTrace (compareTapes tape) + (compareTapes_injective tape distinct) (fun l => labels (.comparison l)) + foundExit (some (labels .increment)) malformedExit program + (fun l => atLabels (.comparison l)) initial token.2 suffix key.reverse canonical + (by simp [initial, compareTapes, hd 0 5 (by decide)]) + (by simpa [initial, compareTapes, tapesAt, + hd 1 0 (by decide), hd 1 5 (by decide)] using keyWord) + (by simpa [initial, compareTapes, tapesAt, hd 2 0 (by decide), hd 2 5 (by decide)] + using candidateEmpty) + (by simpa [initial, compareTapes, tapesAt, + hd 3 0 (by decide), hd 3 5 (by decide)] using copyEmpty) + (by simpa [initial, compareTapes, tapesAt, + hd 4 0 (by decide), hd 4 5 (by decide)] using scratchEmpty) + ambient + have heq : token.2.reverse = key.reverse ↔ token.2 = key := by + constructor + · intro h + have := congrArg List.reverse h + simpa only [List.reverse_reverse] using this + · intro h; rw [h] + simp only [List.length_reverse, heq] at second + rw [show Function.update initial (compareTapes tape 0) suffix = + tapesAt (tape 0) (tape 5) base suffix counter by + exact update_source _ _ (hd 0 5 (by decide)) base _ counter suffix] at second + exact joinTrace first second + +theorem searchTrace (tokens : List Token) (key suffix counter : List Bool) + (canonical : ∀ token ∈ tokens, BinaryNameMachine.canonical token.2 = true) + (present : key ∈ payloads tokens) + (keyWord : base (tape 1) = key.reverse) + (candidateEmpty : base (tape 2) = []) (copyEmpty : base (tape 3) = []) + (scratchEmpty : base (tape 4) = []) : + (advance (TM2.step program))^[steps tokens key] + (some ⟨some (labels .sign), clean ambient, + tapesAt (tape 0) (tape 5) base (stream tokens ++ suffix) counter⟩) = + some ⟨foundExit, clean ambient, + tapesAt (tape 0) (tape 5) base (stream (afterMatch tokens key) ++ suffix) + (List.replicate ((payloads tokens).idxOf key) true ++ counter)⟩ := by + induction tokens generalizing counter with + | nil => simp at present + | cons token tokens ih => + have headCanonical := canonical token (by simp) + have tailCanonical : ∀ t ∈ tokens, BinaryNameMachine.canonical t.2 = true := + fun t ht => canonical t (by simp [ht]) + have first := tokenTrace tape distinct labels foundExit missingExit malformedExit + program atLabels base ambient token key (stream tokens ++ suffix) counter + headCanonical keyWord candidateEmpty copyEmpty scratchEmpty + by_cases same : token.2 = key + · simpa only [steps, same, ite_true, Nat.add_zero, stream_cons, + List.append_assoc, afterMatch, payloads_cons, List.idxOf_cons_self, + List.replicate_zero, List.nil_append] using first + · have remaining : key ∈ payloads tokens := by + rcases List.mem_cons.mp present with equal | remaining + · exact False.elim (same equal.symm) + · exact remaining + have increment : (advance (TM2.step program))^[1] + (some ⟨some (labels .increment), clean ambient, + tapesAt (tape 0) (tape 5) base (stream tokens ++ suffix) counter⟩) = + some ⟨some (labels .sign), clean ambient, + tapesAt (tape 0) (tape 5) base (stream tokens ++ suffix) (true :: counter)⟩ := by + simpa only [Function.iterate_one, advance_some] using + incrementStep tape labels foundExit missingExit malformedExit program + atLabels base ambient (stream tokens ++ suffix) counter + have rest := ih (true :: counter) tailCanonical remaining + simp only [same, ite_false] at first + have full := joinTrace first (joinTrace increment rest) + have counterEq : List.replicate ((payloads tokens).idxOf key) true ++ + (true :: counter) = + List.replicate ((payloads tokens).idxOf key + 1) true ++ counter := by + rw [List.replicate_succ'] + simp only [List.append_assoc, List.singleton_append] + have indexEq : (token.2 :: payloads tokens).idxOf key = + (payloads tokens).idxOf key + 1 := by + simp only [List.idxOf_cons, beq_false_of_ne same, Bool.false_eq_true, ite_false] + simpa only [steps, same, ite_false, stream_cons, List.append_assoc, afterMatch, + payloads_cons, indexEq, counterEq] using full + +def searchInTime (tokens : List Token) (key suffix counter : List Bool) + (canonical : ∀ token ∈ tokens, BinaryNameMachine.canonical token.2 = true) + (present : key ∈ payloads tokens) + (keyWord : base (tape 1) = key.reverse) + (candidateEmpty : base (tape 2) = []) (copyEmpty : base (tape 3) = []) + (scratchEmpty : base (tape 4) = []) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .sign), clean ambient, + tapesAt (tape 0) (tape 5) base (stream tokens ++ suffix) counter⟩ + (some ⟨foundExit, clean ambient, + tapesAt (tape 0) (tape 5) base (stream (afterMatch tokens key) ++ suffix) + (List.replicate ((payloads tokens).idxOf key) true ++ counter)⟩) + ((3 * key.length + 7) * (stream tokens).length) where + steps := steps tokens key + evals_in_steps := searchTrace tape distinct labels foundExit missingExit malformedExit + program atLabels base ambient tokens key suffix counter canonical present keyWord + candidateEmpty copyEmpty scratchEmpty + steps_le_m := steps_le_stream tokens key + +end Program + +def machine : FinTM2 where + K := Fin 6 + k₀ := 0 + k₁ := 5 + Γ _ := Bool + Λ := Label ⊕ Fin 3 + main := .inl .sign + σ := State Unit + initialState := clean () + m label := match label with + | .inl l => instruction id Sum.inl (some (.inr 0)) (some (.inr 1)) (some (.inr 2)) l + | .inr _ => .halt + +theorem machine_finiteAlphabet (k : machine.K) : Finite (machine.Γ k) := by + change Finite Bool + infer_instance + +end PerfectCompleteness.BinaryNameSearch + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryOccurrenceRename.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryOccurrenceRename.lean new file mode 100644 index 0000000000000000000000000000000000000000..647761182eb8be9f45a8ee978ae9543e4b421409 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryOccurrenceRename.lean @@ -0,0 +1,122 @@ +import OAI.Computability.PerfectCompleteness.Machines.BinaryFormulaLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.BinaryOccurrenceRename + +open BinaryFormula UniqueGamesTheorem.Foundations + +theorem literal_mem_names (F : Formula) (c : Clause) (hc : c ∈ F.clauses) + (i : Fin 3) : (c)[i].name ∈ sourceNames F := by + apply List.mem_flatMap.mpr + refine ⟨c, hc, ?_⟩ + have hi : i = 0 ∨ i = 1 ∨ i = 2 := by omega + rcases hi with rfl | rfl | rfl <;> simp [clauseNames] + +def nameIndex (F : Formula) (name : Nat) (mem : name ∈ sourceNames F) : + Fin (sourceNames F).length := + ⟨(sourceNames F).idxOf name, List.idxOf_lt_length_of_mem mem⟩ + +def literal (F : Formula) (l : Literal) (mem : l.name ∈ sourceNames F) : + Target.Literal (sourceNames F).length := + ⟨nameIndex F l.name mem, l.positive⟩ + +def clause (F : Formula) (c : Clause) (mem : c ∈ F.clauses) : + Target.Clause (sourceNames F).length := + #v[literal F (c)[0] (literal_mem_names F c mem 0), + literal F (c)[1] (literal_mem_names F c mem 1), + literal F (c)[2] (literal_mem_names F c mem 2)] + +def renamed (F : Formula) : Target.Formula where + «variables» := (sourceNames F).length + clauses := F.clauses.attach.map (fun c => clause F c.val c.property) + +def restrictAssignment (F : Formula) (A : Nat → Bool) : + Fin (sourceNames F).length → Bool := + fun i => A (sourceNames F)[i.val] + +def extendAssignment (F : Formula) (A : Fin (sourceNames F).length → Bool) : Nat → Bool := + fun name => if mem : name ∈ sourceNames F then A (nameIndex F name mem) else false + +@[simp] theorem nameIndex_reads_name (F : Formula) (name : Nat) + (mem : name ∈ sourceNames F) : (sourceNames F)[(nameIndex F name mem).val] = name := + List.getElem_idxOf _ + +@[simp] theorem clause_eval_restrict (F : Formula) (c : Clause) (mem : c ∈ F.clauses) + (A : Nat → Bool) : (clause F c mem).eval (restrictAssignment F A) = c.eval A := by + simp [clause, literal, Target.Clause.eval, Target.Literal.eval, + BinaryFormula.Clause.eval, BinaryFormula.Literal.eval, restrictAssignment] + +@[simp] theorem clause_eval_extend (F : Formula) (c : Clause) (mem : c ∈ F.clauses) + (A : Fin (sourceNames F).length → Bool) : + (clause F c mem).eval A = c.eval (extendAssignment F A) := by + have evalLiteral (l : Literal) (hl : l.name ∈ sourceNames F) : + (literal F l hl).eval A = l.eval (extendAssignment F A) := by + simp only [literal, Target.Literal.eval, BinaryFormula.Literal.eval, + extendAssignment, dite_eq_left hl] + rfl + simp [clause, Target.Clause.eval, BinaryFormula.Clause.eval, evalLiteral] + +@[simp] theorem renamed_clause_count (F : Formula) : + (renamed F).clauses.length = F.clauses.length := by simp [renamed] + +@[simp] theorem renamed_variable_count (F : Formula) : + (renamed F).variables = 3 * F.clauses.length := by + exact clauseNames_flat_length F.clauses + +theorem renamed_satisfiable_iff (F : Formula) : (renamed F).Satisfiable ↔ F.Satisfiable := by + constructor + · rintro ⟨A, hA⟩ + refine ⟨extendAssignment F A, ?_⟩ + intro c mem + have hc : clause F c mem ∈ (renamed F).clauses := + List.mem_map.mpr ⟨⟨c, mem⟩, by simp, rfl⟩ + exact (clause_eval_extend F c mem A).symm.trans (hA _ hc) + · rintro ⟨A, hA⟩ + refine ⟨restrictAssignment F A, ?_⟩ + intro c mem + obtain ⟨original, _, rfl⟩ := List.mem_map.mp mem + exact (clause_eval_restrict F original.val original.property A).trans + (hA original.val original.property) + +theorem nat_bits_injective : Function.Injective Nat.bits := by + intro a b same + have decoded := congrArg BinaryEncoding.bitsValue same + simpa only [BinaryEncoding.bitsValue_bits] using decoded + +theorem idxOf_binary_payloads (names : List Nat) (name : Nat) : + (names.map Nat.bits).idxOf name.bits = names.idxOf name := by + induction names with + | nil => rfl + | cons first names ih => + by_cases same : first = name + · subst first + simp + · have different : first.bits ≠ name.bits := fun h => same (nat_bits_injective h) + simp only [List.map_cons, List.idxOf_cons, beq_false_of_ne same, + beq_false_of_ne different, ih] + +theorem renamed_encoding_bound (F : Formula) : + (Complexity.formulaBits (renamed F)).length ≤ + 9 * F.clauses.length * F.clauses.length + 10 * F.clauses.length + 2 := by + have h := Complexity.formulaBits_length_le (renamed F) + simp only [renamed_clause_count, renamed_variable_count] at h + nlinarith + +theorem renamed_encoding_bound_bits (F : Formula) : + (Complexity.formulaBits (renamed F)).length ≤ + 9 * (BinaryEncoding.formulaBits F).length * (BinaryEncoding.formulaBits F).length + + 10 * (BinaryEncoding.formulaBits F).length + 2 := by + have h := renamed_encoding_bound F + have hm : F.clauses.length ≤ (BinaryEncoding.formulaBits F).length := + (BinaryEncoding.clauses_length_lt_bits F.clauses).le + have hsq := Nat.mul_self_le_mul_self hm + nlinarith + +end PerfectCompleteness.BinaryOccurrenceRename + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryPairMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryPairMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..de71cf4d0e68135dd3fad32ae1af02f3c8440571 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryPairMachine.lean @@ -0,0 +1,231 @@ +import OAI.Computability.UniqueGames.Machines.MachineLemmas +import OAI.Computability.UniqueGames.Reduction.MachineTransfer + +namespace OAI + + +namespace PerfectCompleteness.BinaryPairMachine + + +open Turing +open UniqueGamesTheorem.Foundations.Complexity +open MachineComposition +open UniqueGamesTheorem.Reduction.MachineTransfer + +abbrev Tape := Fin 3 +abbrev Label := Fin 5 +abbrev State := Unit × Option Bool +abbrev Alphabet (_ : Tape) := Bool + +def stop (label : Label) : TM2.Stmt Alphabet Label State := + .load (fun _ => ((), none)) (.goto fun _ => label) + +def count : TM2.Stmt Alphabet Label State := + .pop 0 (fun state head => (state.1, head)) + (.branch (fun state => state.2.isNone) + (stop 4) + (.branch (fun state => state.2.getD false) + (.push 1 (fun _ => true) (.goto fun _ => 0)) + (stop 1))) + +def copy : TM2.Stmt Alphabet Label State := + .pop 1 (fun state head => (state.1, head)) + (.branch (fun state => state.2.isSome) + (.pop 0 (fun state head => (state.1, head)) + (.branch (fun state => state.2.isSome) + (.push 2 (fun state => state.2.getD false) (.goto fun _ => 1)) + (stop 4))) + (stop 2)) + +def program (label : Label) : TM2.Stmt Alphabet Label State := + if label = 0 then count + else if label = 1 then copy + else if label = 2 then loopAt 2 1 id false 2 (some 3) + else .halt + +abbrev machine : FinTM2 where + K := Tape + k₀ := 0 + k₁ := 1 + Γ := Alphabet + Λ := Label + main := 0 + σ := State + initialState := ((), none) + m := program + +def tapes (input counter saved : List Bool) : Tape → List Bool := + fun k => if k = 0 then input else if k = 1 then counter else saved + +def cfg (label : Option Label) (input counter saved : List Bool) + (register : Option Bool := none) : machine.Cfg := + ⟨label, ((), register), tapes input counter saved⟩ + +@[simp] private theorem tapes_zero (input counter saved : List Bool) : + tapes input counter saved 0 = input := rfl + +@[simp] private theorem tapes_one (input counter saved : List Bool) : + tapes input counter saved 1 = counter := rfl + +@[simp] private theorem tapes_two (input counter saved : List Bool) : + tapes input counter saved 2 = saved := rfl + +private theorem update_zero (input counter saved replacement : List Bool) : + Function.update (tapes input counter saved) 0 replacement = + tapes replacement counter saved := by + funext k + fin_cases k <;> simp [tapes] + +private theorem update_one (input counter saved replacement : List Bool) : + Function.update (tapes input counter saved) 1 replacement = + tapes input replacement saved := by + funext k + fin_cases k <;> simp [tapes] + +private theorem update_two (input counter saved replacement : List Bool) : + Function.update (tapes input counter saved) 2 replacement = + tapes input counter replacement := by + funext k + fin_cases k <;> simp [tapes] + +theorem countStep_true (input counter saved : List Bool) (register : Option Bool) : + machine.step (cfg (some 0) (true :: input) counter saved register) = + some (cfg (some 0) input (true :: counter) saved (some true)) := by + change some (TM2.stepAux (program 0) _ _) = _ + simp [program, count, cfg, TM2.stepAux, update_zero, update_one] + rfl + +theorem countStep_false (input counter saved : List Bool) (register : Option Bool) : + machine.step (cfg (some 0) (false :: input) counter saved register) = + some (cfg (some 1) input counter saved) := by + change some (TM2.stepAux (program 0) _ _) = _ + simp [program, count, stop, cfg, TM2.stepAux, update_zero] + rfl + +theorem countTrace (n : Nat) (input counter saved : List Bool) (register : Option Bool) : + (advance machine.step)^[n + 1] + (some (cfg (some 0) (encodeWord n ++ input) counter saved register)) = + some (cfg (some 1) input (List.replicate n true ++ counter) saved) := by + induction n generalizing counter register with + | zero => + simpa only [Nat.zero_add, Function.iterate_one, advance_some, encodeWord, + List.replicate_zero, List.nil_append, List.singleton_append] using + countStep_false input counter saved register + | succ n ih => + rw [show encodeWord (n + 1) ++ input = true :: (encodeWord n ++ input) by + simp only [encodeWord, List.replicate_succ, List.cons_append]] + rw [Function.iterate_succ_apply] + simp only [advance_some] + rw [countStep_true] + rw [ih] + rw [List.replicate_succ'] + simp only [List.append_assoc, List.singleton_append] + +theorem copyStep_empty (input saved : List Bool) (register : Option Bool) : + machine.step (cfg (some 1) input [] saved register) = + some (cfg (some 2) input [] saved) := by + change some (TM2.stepAux (program 1) _ _) = _ + simp [program, copy, stop, cfg, TM2.stepAux, update_one] + rfl + +theorem copyStep_cons (bit : Bool) (input counter saved : List Bool) + (register : Option Bool) : + machine.step (cfg (some 1) (bit :: input) (true :: counter) saved register) = + some (cfg (some 1) input counter (bit :: saved) (some bit)) := by + change some (TM2.stepAux (program 1) _ _) = _ + simp [program, copy, cfg, TM2.stepAux, update_zero, update_one, update_two] + rfl + +theorem copyTrace (input suffix saved : List Bool) (register : Option Bool) : + (advance machine.step)^[input.length + 1] + (some (cfg (some 1) (input ++ suffix) (List.replicate input.length true) saved register)) = + some (cfg (some 2) suffix [] (input.reverse ++ saved)) := by + induction input generalizing saved register with + | nil => + simpa only [List.length_nil, Nat.zero_add, Function.iterate_one, advance_some, + List.nil_append, List.replicate_zero, List.reverse_nil] using + copyStep_empty suffix saved register + | cons bit input ih => + rw [List.length_cons, Function.iterate_succ_apply] + simp only [List.cons_append, List.replicate_succ, advance_some] + rw [copyStep_cons, ih] + simp only [List.reverse_cons, List.append_assoc, List.singleton_append] + +theorem restoreTrace (input witness : List Bool) (register : Option Bool) : + (advance machine.step)^[input.length + 1] + (some (cfg (some 2) witness [] input.reverse register)) = + some (cfg (some 3) witness input []) := by + change (nextAt (Γ := Alphabet) (1 : Tape) program)^[input.length + 1] + (some ⟨some (2 : Label), ((), register), tapes witness [] input.reverse⟩) = + some ⟨some (3 : Label), ((), none), tapes witness input []⟩ + have h := transferAt_steps (Γ := Alphabet) (σ := Unit) (2 : Tape) 1 (by decide) + id false (2 : Label) (some 3) program (by simp [program]) + (tapes witness [] []) input.reverse [] () register + simpa only [tapesAt, update_two, update_one, List.length_reverse, List.reverse_reverse, + List.map_id_fun, id_eq, List.append_nil] using h + +theorem initList_eq (input : List Bool) : + initList machine input = cfg (some 0) input [] [] := by + unfold initList cfg + congr 1 + funext k + fin_cases k <;> simp [tapes, machine] + +private theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +theorem pairTrace (input witness : List Bool) : + (advance machine.step)^[3 * input.length + 3] + (some (initList machine (CookLevin.pairBits (input, witness)))) = + some (cfg (some 3) witness input []) := by + have first := countTrace input.length (input ++ witness) [] [] none + simp only [List.append_nil] at first + have second := copyTrace input witness [] none + simp only [List.append_nil] at second + have third := restoreTrace input witness none + have full := joinTrace (joinTrace first second) third + have htime : (input.length + 1 + (input.length + 1)) + (input.length + 1) = + 3 * input.length + 3 := by omega + rw [htime] at full + simpa only [initList_eq, CookLevin.pairBits, List.append_assoc] using full + +def pairInTime (input witness : List Bool) : + StateTransition.EvalsToInTime machine.step + (initList machine (CookLevin.pairBits (input, witness))) + (some (cfg (some 3) witness input [])) (3 * input.length + 3) where + steps := 3 * input.length + 3 + evals_in_steps := pairTrace input witness + steps_le_m := Nat.le_refl _ + +theorem haltStep (input witness : List Bool) : + machine.step (cfg (some 3) witness input []) = some (cfg none witness input []) := by + change some (TM2.stepAux (program 3) _ _) = _ + simp [program, cfg, TM2.stepAux] + rfl + +def pairHaltInTime (input witness : List Bool) : + StateTransition.EvalsToInTime machine.step + (initList machine (CookLevin.pairBits (input, witness))) + (some (cfg none witness input [])) (3 * input.length + 4) where + steps := 3 * input.length + 4 + evals_in_steps := by + change (advance machine.step)^[3 * input.length + 4] + (some (initList machine (CookLevin.pairBits (input, witness)))) = _ + rw [show 3 * input.length + 4 = (3 * input.length + 3) + 1 by omega, + Function.iterate_succ_apply', pairTrace, advance_some, haltStep] + steps_le_m := Nat.le_refl _ + +theorem pairSteps_le_pairedLength (input witness : List Bool) : + 3 * input.length + 4 ≤ 3 * (CookLevin.pairBits (input, witness)).length + 4 := by + rw [CookLevin.pairBits_length] + dsimp only + omega + +theorem machine_finiteAlphabet (k : machine.K) : Finite (machine.Γ k) := by + change Finite Bool + infer_instance + +end PerfectCompleteness.BinaryPairMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryParsingLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryParsingLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..72fcb74ddf1c5fc5e24d770258e899455f1fbc8c --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryParsingLemmas.lean @@ -0,0 +1,257 @@ +import OAI.Computability.PerfectCompleteness.Machines.BinaryFormulaLemmas +import OAI.Computability.PerfectCompleteness.Machines.BinaryNameMachine +import OAI.Computability.PerfectCompleteness.Machines.BinaryOccurrenceRename +import OAI.Computability.PerfectCompleteness.Model + +namespace OAI + + +namespace PerfectCompleteness.BinaryParsing + +open BinaryEncoding BinaryFormula + +theorem frame_eq (bits : List Bool) : BinaryNameMachine.frame bits = frame bits := by + induction bits with + | nil => rfl + | cons bit bits ih => simp [BinaryNameMachine.frame, frame, ih] + +theorem canonical_cons_cons (a b : Bool) (bits : List Bool) : + BinaryNameMachine.canonical (a :: b :: bits) = BinaryNameMachine.canonical (b :: bits) := rfl + +theorem canonical_iff (bits : List Bool) : + BinaryNameMachine.canonical bits = true ↔ (bitsValue bits).bits = bits := by + induction bits with + | nil => simp [BinaryNameMachine.canonical, BinaryNameMachine.finalDigit, bitsValue] + | cons bit bits ih => + cases bits with + | nil => cases bit <;> decide + | cons next bits => + rw [canonical_cons_cons, ih] + constructor + · intro htail + have hn : bitsValue (next :: bits) ≠ 0 := by + intro hz + rw [hz, Nat.zero_bits] at htail + contradiction + rw [bitsValue, Nat.bits_append_bit _ bit (fun h => False.elim (hn h)), htail] + · intro hfull + calc + (bitsValue (next :: bits)).bits = + (Nat.bit bit (bitsValue (next :: bits))).div2.bits := by rw [Nat.div2_bit] + _ = (Nat.bit bit (bitsValue (next :: bits))).bits.tail := + Nat.div2_bits_eq_tail _ + _ = (bit :: next :: bits).tail := congrArg List.tail hfull + _ = next :: bits := rfl + +@[simp] theorem canonical_nat_bits (name : Nat) : + BinaryNameMachine.canonical name.bits = true := by + apply (canonical_iff _).mpr + rw [bitsValue_bits] + +theorem parseFrame_sound (input digits rest : List Bool) + (parsed : parseFrame input = some (digits, rest)) : input = frame digits ++ rest := by + induction input using List.twoStepInduction generalizing digits rest with + | nil => simp [parseFrame] at parsed + | singleton flag => + cases flag + · simp only [parseFrame, Option.some.injEq, Prod.mk.injEq] at parsed + rcases parsed with ⟨rfl, rfl⟩ + rfl + · simp [parseFrame] at parsed + | cons_cons flag bit input ih _ => + cases flag + · simp only [parseFrame, Option.some.injEq, Prod.mk.injEq] at parsed + rcases parsed with ⟨rfl, rfl⟩ + rfl + · cases h : parseFrame input with + | none => simp [parseFrame, h] at parsed + | some pair => + rcases pair with ⟨ds, tail⟩ + have hs := ih ds tail h + simp [parseFrame, h] at parsed + rcases parsed with ⟨rfl, rfl⟩ + simp [frame, hs] + +theorem parseName_sound (input : List Bool) (name : Nat) (rest : List Bool) + (parsed : parseName input = some (name, rest)) : input = nameBits name ++ rest := by + cases h : parseFrame input with + | none => simp [parseName, h] at parsed + | some pair => + rcases pair with ⟨digits, tail⟩ + by_cases canonical : digits = (bitsValue digits).bits + · simp only [parseName, h, Option.bind_eq_bind, Option.bind_some] at parsed + rw [ite_eq_left canonical] at parsed + simp only [Option.some.injEq, Prod.mk.injEq] at parsed + rcases parsed with ⟨rfl, rfl⟩ + have hs := parseFrame_sound input digits tail h + exact hs.trans (congrArg (fun ds => frame ds ++ tail) canonical) + · simp only [parseName, h, Option.bind_eq_bind, Option.bind_some, ite_eq_right canonical] at parsed + cases parsed + +theorem parseLiteral_sound (input : List Bool) (literal : Literal) (rest : List Bool) + (parsed : parseLiteral input = some (literal, rest)) : + input = literalBits literal ++ rest := by + cases input with + | nil => simp [parseLiteral] at parsed + | cons sign input => + cases h : parseName input with + | none => simp [parseLiteral, h] at parsed + | some pair => + rcases pair with ⟨name, tail⟩ + have hs := parseName_sound input name tail h + simp [parseLiteral, h] at parsed + rcases parsed with ⟨rfl, rfl⟩ + simp [literalBits, hs] + +theorem parseClause_sound (input : List Bool) (clause : Clause) (rest : List Bool) + (parsed : parseClause input = some (clause, rest)) : input = clauseBits clause ++ rest := by + cases ha : parseLiteral input with + | none => simp [parseClause, ha] at parsed + | some first => + rcases first with ⟨a, afterA⟩ + cases hb : parseLiteral afterA with + | none => simp [parseClause, ha, hb] at parsed + | some second => + rcases second with ⟨b, afterB⟩ + cases hc : parseLiteral afterB with + | none => simp [parseClause, ha, hb, hc] at parsed + | some third => + rcases third with ⟨c, afterC⟩ + have hA := parseLiteral_sound input a afterA ha + have hB := parseLiteral_sound afterA b afterB hb + have hC := parseLiteral_sound afterB c afterC hc + have pairEq : (#v[a, b, c], afterC) = (clause, rest) := by + apply Option.some.inj + simpa only [parseClause, ha, hb, hc, Option.bind_eq_bind, + Option.bind_some, Option.pure_def] using parsed + rcases Prod.mk.inj pairEq with ⟨rfl, rfl⟩ + simp [clauseBits, hA, hB, hC, List.append_assoc] + +theorem parseClauses_sound (fuel : Nat) (input : List Bool) + (clauses : List Clause) (rest : List Bool) + (parsed : parseClauses fuel input = some (clauses, rest)) : + input = clausesBits clauses ++ rest := by + induction fuel generalizing input clauses rest with + | zero => simp [parseClauses] at parsed + | succ fuel ih => + cases input with + | nil => simp [parseClauses] at parsed + | cons flag input => + cases flag + · simp only [parseClauses, Option.some.injEq, Prod.mk.injEq] at parsed + rcases parsed with ⟨rfl, rfl⟩ + rfl + · cases hc : parseClause input with + | none => simp [parseClauses, hc] at parsed + | some first => + rcases first with ⟨clause, afterClause⟩ + cases hs : parseClauses fuel afterClause with + | none => simp [parseClauses, hc, hs] at parsed + | some remaining => + rcases remaining with ⟨cs, tail⟩ + have hC := parseClause_sound input clause afterClause hc + have hS := ih afterClause cs tail hs + simp [parseClauses, hc, hs] at parsed + rcases parsed with ⟨rfl, rfl⟩ + simp [clausesBits, hC, hS, List.append_assoc] + +theorem decodeFormula_sound (input : List Bool) (formula : Formula) + (parsed : decodeFormula input = some formula) : input = formulaBits formula := by + cases h : parseClauses (input.length + 1) input with + | none => simp [decodeFormula, h] at parsed + | some pair => + rcases pair with ⟨clauses, rest⟩ + by_cases empty : rest = [] + · subst rest + simp [decodeFormula, h] at parsed + subst formula + simpa only [formulaBits, List.append_nil] using + parseClauses_sound (input.length + 1) input clauses [] h + · simp [decodeFormula, h, empty] at parsed + +theorem decodeFormula_eq_some_iff (input : List Bool) (formula : Formula) : + decodeFormula input = some formula ↔ input = formulaBits formula := + ⟨decodeFormula_sound input formula, fun h => h ▸ decodeFormula_encoded formula⟩ + +theorem scanSpec_nameBits (name : Nat) (suffix output : List Bool) : + BinaryNameMachine.scanSpec (nameBits name ++ suffix) output none = + ⟨true, suffix, name.bits.reverse ++ output⟩ := by + unfold nameBits + rw [← frame_eq, BinaryNameMachine.scanSpec_frame] + have h := canonical_nat_bits name + simpa only [BinaryNameMachine.canonical] using + congrArg (fun accepted => + (⟨accepted, suffix, name.bits.reverse ++ output⟩ : BinaryNameMachine.Result)) h + +end PerfectCompleteness.BinaryParsing + + + +namespace PerfectCompleteness.BinaryLanguage + +open UniqueGamesTheorem.Foundations + +def rejectBinary : BinaryFormula.Formula where + clauses := [#v[⟨0, true⟩, ⟨0, true⟩, ⟨0, true⟩], + #v[⟨0, false⟩, ⟨0, false⟩, ⟨0, false⟩]] + +theorem rejectBinary_unsatisfiable : ¬rejectBinary.Satisfiable := by + rintro ⟨assignment, satisfied⟩ + have positive := satisfied #v[⟨0, true⟩, ⟨0, true⟩, ⟨0, true⟩] + (by simp [rejectBinary]) + have negative := satisfied #v[⟨0, false⟩, ⟨0, false⟩, ⟨0, false⟩] + (by simp [rejectBinary]) + cases h : assignment 0 <;> + simp [BinaryFormula.Clause.eval, BinaryFormula.Literal.eval, h] at positive negative + +def rejectFormula : Target.Formula := BinaryOccurrenceRename.renamed rejectBinary + +theorem reject_unsatisfiable : ¬rejectFormula.Satisfiable := by + simpa only [rejectFormula, BinaryOccurrenceRename.renamed_satisfiable_iff] using + rejectBinary_unsatisfiable + +def totalParsed (input : List Bool) : BinaryFormula.Formula := + (BinaryEncoding.decodeFormula input).getD rejectBinary + +def totalRename (input : List Bool) : Target.Formula := + BinaryOccurrenceRename.renamed (totalParsed input) + +theorem totalParsed_satisfiable_iff (input : List Bool) : + (totalParsed input).Satisfiable ↔ language input := by + cases parsed : BinaryEncoding.decodeFormula input with + | none => simp [totalParsed, parsed, rejectBinary_unsatisfiable, language] + | some formula => simp [totalParsed, parsed, language] + +theorem totalRename_satisfiable_iff (input : List Bool) : + (totalRename input).Satisfiable ↔ language input := by + exact (BinaryOccurrenceRename.renamed_satisfiable_iff (totalParsed input)).trans + (totalParsed_satisfiable_iff input) + +theorem totalRename_encoded (formula : BinaryFormula.Formula) : + totalRename (BinaryEncoding.formulaBits formula) = BinaryOccurrenceRename.renamed formula := by + simp [totalRename, totalParsed] + +theorem language_encoded (formula : BinaryFormula.Formula) : + language (BinaryEncoding.formulaBits formula) ↔ formula.Satisfiable := by + simp [language] + +theorem reject_bits_length : (Complexity.formulaBits rejectFormula).length = 25 := by decide + +theorem totalRename_output_length (input : List Bool) : + (Complexity.formulaBits (totalRename input)).length ≤ + 9 * input.length * input.length + 10 * input.length + 25 := by + cases parsed : BinaryEncoding.decodeFormula input with + | none => + have output : totalRename input = rejectFormula := by simp [totalRename, totalParsed, parsed, rejectFormula] + rw [output, reject_bits_length] + omega + | some formula => + have correct := BinaryParsing.decodeFormula_sound input formula parsed + have bound := BinaryOccurrenceRename.renamed_encoding_bound_bits formula + simp only [totalRename, totalParsed, parsed, Option.getD_some] + rw [correct] + omega + +end PerfectCompleteness.BinaryLanguage + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryRankOneCount.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryRankOneCount.lean new file mode 100644 index 0000000000000000000000000000000000000000..86455a917535a3de1ddf7e4eb08a6ae83d04fcfe --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryRankOneCount.lean @@ -0,0 +1,106 @@ +import Mathlib.Algebra.Field.ZMod +import Mathlib.LinearAlgebra.Dimension.FreeAndStrongRankCondition +import Mathlib.LinearAlgebra.Matrix.Rank +import OAI.Computability.PerfectCompleteness.Sampling.CutSamplerReplayTransportLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.BinaryRankOneCount + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games + +noncomputable section + +theorem rank_le_one_iff_vecMulVec {K I J : Type*} [Field K] + [Fintype I] [Fintype J] (A : Matrix I J K) : + A.rank ≤ 1 ↔ ∃ u : I → K, ∃ v : J → K, Matrix.vecMulVec u v = A := by + constructor + · intro hA + let S : Submodule K (I → K) := Submodule.span K (Set.range A.col) + have hS : Module.finrank K S ≤ 1 := by + simpa only [S, Matrix.rank_eq_finrank_span_cols] using hA + obtain ⟨u, hu⟩ := (finrank_le_one_iff (K := K) (V := S)).mp hS + have hcol (j : J) : A.col j ∈ S := + Submodule.subset_span (Set.mem_range_self j) + choose v hv using (fun j : J => hu ⟨A.col j, hcol j⟩) + refine ⟨u.val, v, ?_⟩ + ext i j + change u.val i * v j = A i j + have hij := congrArg (fun z : S => z.val i) (hv j) + change v j * u.val i = A i j at hij + exact (mul_comm _ _).trans hij + · rintro ⟨u, v, rfl⟩ + exact Matrix.rank_vecMulVec_le u v + +theorem rank_le_one_card_le_vec_pairs {K I J : Type*} [Field K] + [Fintype K] [Fintype I] [Fintype J] : + Fintype.card {A : Matrix I J K // A.rank ≤ 1} ≤ + Fintype.card ((I → K) × (J → K)) := by + let outer : ((I → K) × (J → K)) → {A : Matrix I J K // A.rank ≤ 1} := + fun p => ⟨Matrix.vecMulVec p.1 p.2, Matrix.rank_vecMulVec_le p.1 p.2⟩ + apply Fintype.card_le_of_surjective outer + intro A + obtain ⟨u, v, huv⟩ := (rank_le_one_iff_vecMulVec A.val).mp A.property + exact ⟨(u, v), Subtype.ext huv⟩ + +theorem binary_rank_le_one_card_le (m : Nat) : + Fintype.card {A : Matrix (Fin m) (Fin m) (ZMod 2) // A.rank ≤ 1} ≤ + 2 ^ (2 * m) := by + let outer : ((Fin m → ZMod 2) × (Fin m → ZMod 2)) → + {A : Matrix (Fin m) (Fin m) (ZMod 2) // A.rank ≤ 1} := + fun p => ⟨Matrix.vecMulVec p.1 p.2, Matrix.rank_vecMulVec_le p.1 p.2⟩ + have covers : Function.Surjective outer := by + intro A + obtain ⟨u, v, huv⟩ := (rank_le_one_iff_vecMulVec A.val).mp A.property + exact ⟨(u, v), Subtype.ext huv⟩ + have vector_card : Fintype.card (Fin m → ZMod 2) = 2 ^ m := by + rw [Fintype.card_fun, ZMod.card, Fintype.card_fin] + calc + _ ≤ Fintype.card ((Fin m → ZMod 2) × (Fin m → ZMod 2)) := + Fintype.card_le_of_surjective outer covers + _ = 2 ^ m * 2 ^ m := by rw [Fintype.card_prod, vector_card] + _ = 2 ^ (2 * m) := by rw [← pow_add, two_mul] + +theorem binary_matrix_card (m : Nat) : + Fintype.card (Matrix (Fin m) (Fin m) (ZMod 2)) = 2 ^ (m * m) := by + change Fintype.card (Fin m → Fin m → ZMod 2) = _ + simp only [Fintype.card_fun, Fintype.card_fin, ZMod.card, pow_mul] + +theorem uniform_rank_le_one_probability_le (m : Nat) : + (FiniteDistribution.uniform (Matrix (Fin m) (Fin m) (ZMod 2))).probability + (fun A => decide (A.rank ≤ 1)) ≤ + (2 : ℝ) ^ (2 * m) / (2 : ℝ) ^ (m * m) := by + have hcount : + (Fintype.card {A : Matrix (Fin m) (Fin m) (ZMod 2) // A.rank ≤ 1} : ℝ) ≤ + (2 : ℝ) ^ (2 * m) := by + exact_mod_cast binary_rank_le_one_card_le m + calc + _ = (∑ A : Matrix (Fin m) (Fin m) (ZMod 2), + if A.rank ≤ 1 then (1 : ℝ) else 0) / + (Fintype.card (Matrix (Fin m) (Fin m) (ZMod 2)) : ℝ) := by + change (∑ A : Matrix (Fin m) (Fin m) (ZMod 2), + if decide (A.rank ≤ 1) then + 1 / (Fintype.card (Matrix (Fin m) (Fin m) (ZMod 2)) : ℝ) else 0) = _ + simp only [div_eq_mul_inv, Finset.sum_mul] + apply Finset.sum_congr rfl + intro A _ + by_cases hA : A.rank ≤ 1 <;> simp [hA] + _ = (Fintype.card {A : Matrix (Fin m) (Fin m) (ZMod 2) // A.rank ≤ 1} : ℝ) / + (Fintype.card (Matrix (Fin m) (Fin m) (ZMod 2)) : ℝ) := by + simp only [Fintype.card_subtype, Finset.sum_boole] + _ ≤ (2 : ℝ) ^ (2 * m) / + (Fintype.card (Matrix (Fin m) (Fin m) (ZMod 2)) : ℝ) := + div_le_div_of_nonneg_right hcount (Nat.cast_nonneg _) + _ = (2 : ℝ) ^ (2 * m) / (2 : ℝ) ^ (m * m) := by + rw [binary_matrix_card] + norm_cast + +end +end PerfectCompleteness.BinaryRankOneCount + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryRenameLoop.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryRenameLoop.lean new file mode 100644 index 0000000000000000000000000000000000000000..bfa772406301c4a234f98d2bbb3a216e7a8761f9 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryRenameLoop.lean @@ -0,0 +1,447 @@ +import OAI.Computability.PerfectCompleteness.Machines.BinaryLiteralMachine + +namespace OAI + + +namespace PerfectCompleteness.BinaryRenameLoop + + +open Turing +open UniqueGamesTheorem.Foundations.Complexity +open MachineComposition + +abbrev Token := BinaryNameSearch.Token + +def nextSlot (slot : Fin 3) : Fin 3 := if slot = 0 then 1 else if slot = 1 then 2 else 0 + +def clauseIncrement (slot : Fin 3) : Nat := if slot = 2 then 1 else 0 + +def finalSlot : Nat → Fin 3 → Fin 3 + | 0, slot => slot + | n + 1, slot => finalSlot n (nextSlot slot) + +def completedClauses : Nat → Fin 3 → Nat + | 0, _ => 0 + | n + 1, slot => completedClauses n (nextSlot slot) + clauseIncrement slot + +theorem finalSlot_three (n : Nat) : finalSlot (n + 3) 0 = finalSlot n 0 := by + simp [finalSlot, nextSlot] + +theorem completedClauses_three (n : Nat) : + completedClauses (n + 3) 0 = completedClauses n 0 + 1 := by + simp [completedClauses, nextSlot, clauseIncrement] + +@[simp] theorem finalSlot_triples (n : Nat) : finalSlot (3 * n) 0 = 0 := by + induction n with + | zero => rfl + | succ n ih => rw [Nat.mul_succ, finalSlot_three, ih] + +@[simp] theorem completedClauses_triples (n : Nat) : completedClauses (3 * n) 0 = n := by + induction n with + | zero => rfl + | succ n ih => rw [Nat.mul_succ, completedClauses_three, ih] + +def outputBody (tokens input : List Token) : List Bool := + input.flatMap (fun token => BinaryLiteralMachine.outputWord tokens token.2 token.1) + +@[simp] theorem outputBody_nil (tokens : List Token) : outputBody tokens [] = [] := rfl + +@[simp] theorem outputBody_cons (tokens : List Token) (token : Token) (input : List Token) : + outputBody tokens (token :: input) = + BinaryLiteralMachine.outputWord tokens token.2 token.1 ++ outputBody tokens input := rfl + +def steps (tokens : List Token) : List Token → Nat + | [] => 1 + | token :: input => BinaryLiteralMachine.steps tokens token.2 + 2 + steps tokens input + +theorem payload_length_le_stream (tokens : List Token) (bits : List Bool) + (present : bits ∈ BinaryNameSearch.payloads tokens) : + bits.length ≤ (BinaryNameSearch.stream tokens).length := by + induction tokens with + | nil => simp at present + | cons token tokens ih => + rcases List.mem_cons.mp present with equal | remaining + · rw [equal] + simp only [BinaryNameSearch.stream_cons, List.length_append, + BinaryNameSearch.tokenBits, List.length_cons, BinaryNameMachine.frame_length] + omega + · have tail := ih remaining + simp only [BinaryNameSearch.stream_cons, List.length_append] + omega + +def perLiteralBound (streamLength : Nat) : Nat := + 12 * streamLength ^ 2 + 26 * streamLength + 11 + +theorem literal_steps_le (tokens : List Token) (bits : List Bool) + (present : bits ∈ BinaryNameSearch.payloads tokens) : + BinaryLiteralMachine.steps tokens bits + 2 ≤ + perLiteralBound (BinaryNameSearch.stream tokens).length := by + have body := BinaryLiteralMachine.steps_le tokens bits present + have size := payload_length_le_stream tokens bits present + have sumBound : (BinaryNameSearch.stream tokens).length + bits.length ≤ + 2 * (BinaryNameSearch.stream tokens).length := by omega + have sq := Nat.mul_self_le_mul_self sumBound + unfold perLiteralBound + nlinarith + +theorem steps_le (tokens input : List Token) (included : ∀ token ∈ input, token ∈ tokens) : + steps tokens input ≤ + perLiteralBound (BinaryNameSearch.stream tokens).length * input.length + 1 := by + induction input with + | nil => simp [steps] + | cons token input ih => + have present : token.2 ∈ BinaryNameSearch.payloads tokens := + List.mem_map.mpr ⟨token, included token (by simp), rfl⟩ + have head := literal_steps_le tokens token.2 present + have tail := ih (fun t ht => included t (by simp [ht])) + simp only [steps, List.length_cons] + nlinarith + +theorem steps_le_cubic (tokens input : List Token) + (included : ∀ token ∈ input, token ∈ tokens) + (countBound : input.length ≤ (BinaryNameSearch.stream tokens).length) : + steps tokens input ≤ + 12 * (BinaryNameSearch.stream tokens).length ^ 3 + + 26 * (BinaryNameSearch.stream tokens).length ^ 2 + + 11 * (BinaryNameSearch.stream tokens).length + 1 := by + calc + steps tokens input ≤ + perLiteralBound (BinaryNameSearch.stream tokens).length * input.length + 1 := + steps_le tokens input included + _ ≤ perLiteralBound (BinaryNameSearch.stream tokens).length * + (BinaryNameSearch.stream tokens).length + 1 := + Nat.add_le_add_right (Nat.mul_le_mul_left _ countBound) _ + _ = _ := by unfold perLiteralBound; ring + +section Program + +variable {K Λ A : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool +abbrev State (A : Type) := BinaryLiteralMachine.State (A × Fin 3) +abbrev clean (ambient : A) (slot : Fin 3) : State A := + BinaryLiteralMachine.clean (ambient, slot) + +inductive Label + | entry + | literal (label : BinaryLiteralMachine.Label) + | tally + deriving DecidableEq, Fintype + +def literalTapes (tape : Fin 11 → K) : Fin 9 → K := fun i => tape i.castSucc.castSucc + +omit [DecidableEq K] in +theorem literalTapes_injective (tape : Fin 11 → K) (distinct : Function.Injective tape) : + Function.Injective (literalTapes tape) := by + intro i j h + apply Fin.ext + exact congrArg (fun i : Fin 11 => i.val) (distinct h) + +def finish (exit : Option Λ) : TM2.Stmt (Alphabet (K := K)) Λ (State A) := + .load (fun state => clean state.1.1.1.1 state.1.1.1.2) + (match exit with + | none => .halt + | some label => .goto fun _ => label) + +def next (again : Λ) : TM2.Stmt (Alphabet (K := K)) Λ (State A) := + .load (fun state => clean state.1.1.1.1 (nextSlot state.1.1.1.2)) + (.goto fun _ => again) + +def instruction (tape : Fin 11 → K) (labels : Label → Λ) + (done malformed : Option Λ) : Label → TM2.Stmt (Alphabet (K := K)) Λ (State A) + | .entry => + .pop (tape 0) (fun state head => (state.1, head)) + (.branch (fun state => state.2.isSome) + (.push (tape 0) (fun state => state.2.getD false) + (finish (some (labels (.literal .readSign))))) + (finish done)) + | .literal l => BinaryLiteralMachine.instruction (literalTapes tape) + (fun l => labels (.literal l)) (some (labels .tally)) malformed l + | .tally => + .push (tape 9) (fun _ => true) + (.branch (fun state => state.1.1.1.2 == (2 : Fin 3)) + (.push (tape 10) (fun _ => true) (next (labels .entry))) + (next (labels .entry))) + +def loopTapes (tape : Fin 11 → K) (base : K → List Bool) + (cursor output variableCounter clauses : List Bool) : K → List Bool := + Function.update (Function.update (Function.update (Function.update base + (tape 0) cursor) (tape 8) output) (tape 9) variableCounter) (tape 10) clauses + +theorem loopTapes_cursor (tape : Fin 11 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (cursor output variableCounter clauses : List Bool) : + loopTapes tape base cursor output variableCounter clauses (tape 0) = cursor := by + have hd (i j : Fin 11) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + simp [loopTapes, hd] + +theorem loopTapes_output (tape : Fin 11 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (cursor output variableCounter clauses : List Bool) : + loopTapes tape base cursor output variableCounter clauses (tape 8) = output := by + have hd (i j : Fin 11) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + simp [loopTapes, hd] + +theorem loopTapes_variables (tape : Fin 11 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (cursor output variableCounter clauses : List Bool) : + loopTapes tape base cursor output variableCounter clauses (tape 9) = variableCounter := by + have hd (i j : Fin 11) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + simp [loopTapes, hd] + +theorem loopTapes_clauses (tape : Fin 11 → K) + (base : K → List Bool) (cursor output variableCounter clauses : List Bool) : + loopTapes tape base cursor output variableCounter clauses (tape 10) = clauses := by + simp [loopTapes] + +private theorem update_cursor (tape : Fin 11 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (cursor output variableCounter clauses replacement : List Bool) : + Function.update (loopTapes tape base cursor output variableCounter clauses) (tape 0) replacement = + loopTapes tape base replacement output variableCounter clauses := by + have hd (i j : Fin 11) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + funext k + by_cases h : k = tape 0 + · subst k; simp [loopTapes, hd] + · simp [loopTapes, h, Function.update_apply] + +private theorem update_output (tape : Fin 11 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (cursor output variableCounter clauses replacement : List Bool) : + Function.update (loopTapes tape base cursor output variableCounter clauses) (tape 8) replacement = + loopTapes tape base cursor replacement variableCounter clauses := by + have hd (i j : Fin 11) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + funext k + by_cases h : k = tape 8 + · subst k; simp [loopTapes, hd] + · simp [loopTapes, h, Function.update_apply] + +private theorem update_variables (tape : Fin 11 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (cursor output variableCounter clauses replacement : List Bool) : + Function.update (loopTapes tape base cursor output variableCounter clauses) (tape 9) replacement = + loopTapes tape base cursor output replacement clauses := by + have hd (i j : Fin 11) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + funext k + by_cases h : k = tape 9 + · subst k; simp [loopTapes, hd] + · simp [loopTapes, h, Function.update_apply] + +private theorem update_clauses (tape : Fin 11 → K) + (base : K → List Bool) (cursor output variableCounter clauses replacement : List Bool) : + Function.update (loopTapes tape base cursor output variableCounter clauses) (tape 10) replacement = + loopTapes tape base cursor output variableCounter replacement := by + simp [loopTapes] + +theorem loopTapes_other (tape : Fin 11 → K) (base : K → List Bool) + (cursor output variableCounter clauses : List Bool) (k : K) + (h0 : k ≠ tape 0) (h8 : k ≠ tape 8) (h9 : k ≠ tape 9) (h10 : k ≠ tape 10) : + loopTapes tape base cursor output variableCounter clauses k = base k := by + simp [loopTapes, h0, h8, h9, h10] + +@[simp] theorem stepAux_finish (exit : Option Λ) (state : State A) (base : K → List Bool) : + TM2.stepAux (finish exit) state base = + ⟨exit, clean state.1.1.1.1 state.1.1.1.2, base⟩ := by + cases exit <;> rfl + +private theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +variable (tape : Fin 11 → K) (distinct : Function.Injective tape) +variable (labels : Label → Λ) (done malformed : Option Λ) +variable (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) +variable (atLabels : ∀ l, program (labels l) = instruction tape labels done malformed l) +variable (base : K → List Bool) (ambient : A) + +include distinct atLabels + +theorem peekStep (slot : Fin 3) (head : Bool) (tail output variableCounter clauses : List Bool) : + TM2.step program + ⟨some (labels .entry), clean ambient slot, + loopTapes tape base (head :: tail) output variableCounter clauses⟩ = + some ⟨some (labels (.literal .readSign)), clean ambient slot, + loopTapes tape base (head :: tail) output variableCounter clauses⟩ := by + have hd (i j : Fin 11) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + change some (TM2.stepAux (program (labels .entry)) _ _) = _ + rw [atLabels .entry] + simp [instruction, TM2.stepAux, clean, BinaryLiteralMachine.clean, BinaryNameCompare.clean, + loopTapes_cursor tape distinct, update_cursor tape distinct] + +theorem emptyStep (slot : Fin 3) (output variableCounter clauses : List Bool) : + TM2.step program + ⟨some (labels .entry), clean ambient slot, + loopTapes tape base [] output variableCounter clauses⟩ = + some ⟨done, clean ambient slot, loopTapes tape base [] output variableCounter clauses⟩ := by + have hd (i j : Fin 11) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + change some (TM2.stepAux (program (labels .entry)) _ _) = _ + rw [atLabels .entry] + simp [instruction, TM2.stepAux, clean, BinaryLiteralMachine.clean, BinaryNameCompare.clean, + loopTapes_cursor tape distinct, update_cursor tape distinct] + +theorem tallyStep (slot : Fin 3) (cursor output variableCounter clauses : List Bool) : + TM2.step program + ⟨some (labels .tally), clean ambient slot, + loopTapes tape base cursor output variableCounter clauses⟩ = + some ⟨some (labels .entry), clean ambient (nextSlot slot), + loopTapes tape base cursor output (true :: variableCounter) + (List.replicate (clauseIncrement slot) true ++ clauses)⟩ := by + have hd (i j : Fin 11) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + change some (TM2.stepAux (program (labels .tally)) _ _) = _ + rw [atLabels .tally] + fin_cases slot <;> + simp [instruction, TM2.stepAux, clean, BinaryLiteralMachine.clean, BinaryNameCompare.clean, + next, nextSlot, clauseIncrement, loopTapes_variables tape distinct, loopTapes_clauses, + update_variables tape distinct, update_clauses] + +theorem bodyTrace (tokens : List Token) (token : Token) (slot : Fin 3) + (suffix output variableCounter clauses : List Bool) + (canonical : BinaryNameMachine.canonical token.2 = true) + (tokensCanonical : ∀ t ∈ tokens, BinaryNameMachine.canonical t.2 = true) + (present : token.2 ∈ BinaryNameSearch.payloads tokens) + (permanent : base (tape 1) = BinaryNameSearch.stream tokens) + (empty : ∀ i : Fin 11, 2 ≤ i.val → i.val ≤ 7 → base (tape i) = []) : + (advance (TM2.step program))^[BinaryLiteralMachine.steps tokens token.2 + 2] + (some ⟨some (labels .entry), clean ambient slot, + loopTapes tape base (BinaryNameSearch.tokenBits token ++ suffix) output variableCounter clauses⟩) = + some ⟨some (labels .entry), clean ambient (nextSlot slot), + loopTapes tape base suffix + ((BinaryLiteralMachine.outputWord tokens token.2 token.1).reverse ++ output) + (true :: variableCounter) (List.replicate (clauseIncrement slot) true ++ clauses)⟩ := by + have hd (i j : Fin 11) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + let initial := loopTapes tape base (BinaryNameSearch.tokenBits token ++ suffix) + output variableCounter clauses + have first : (advance (TM2.step program))^[1] + (some ⟨some (labels .entry), clean ambient slot, initial⟩) = + some ⟨some (labels (.literal .readSign)), clean ambient slot, initial⟩ := by + simpa only [Function.iterate_one, advance_some, initial, + BinaryNameSearch.tokenBits, List.cons_append] using + peekStep tape distinct labels done malformed program atLabels base ambient slot token.1 + (BinaryNameMachine.frame token.2 ++ suffix) output variableCounter clauses + have workEmpty (i : Fin 11) (lo : 2 ≤ i.val) (hi : i.val ≤ 7) : + initial (tape i) = [] := by + have h0 : i ≠ 0 := by intro h; subst i; omega + have h8 : i ≠ 8 := by intro h; subst i; omega + have h9 : i ≠ 9 := by intro h; subst i; omega + have h10 : i ≠ 10 := by intro h; subst i; omega + simpa [initial, loopTapes, hd i 0 h0, hd i 8 h8, hd i 9 h9, hd i 10 h10] + using empty i lo hi + have literal := BinaryLiteralMachine.literalTrace (literalTapes tape) + (literalTapes_injective tape distinct) (fun l => labels (.literal l)) + (some (labels .tally)) malformed program (fun l => atLabels (.literal l)) + initial tokens token.1 token.2 suffix canonical tokensCanonical present + (by simp [initial, literalTapes, loopTapes, BinaryNameSearch.tokenBits, hd]) + (by simpa [initial, literalTapes, loopTapes, hd] using permanent) + (fun i lo hi => workEmpty i.castSucc.castSucc lo hi) (ambient, slot) + have finalTapes : + Function.update (Function.update initial (literalTapes tape 0) suffix) + (literalTapes tape 8) + ((BinaryLiteralMachine.outputWord tokens token.2 token.1).reverse ++ + initial (literalTapes tape 8)) = + loopTapes tape base suffix + ((BinaryLiteralMachine.outputWord tokens token.2 token.1).reverse ++ output) + variableCounter clauses := by + have out : initial (literalTapes tape 8) = output := by + simp [initial, literalTapes, loopTapes, hd] + rw [out] + change Function.update (Function.update + (loopTapes tape base (BinaryNameSearch.tokenBits token ++ suffix) output variableCounter clauses) + (tape 0) suffix) (tape 8) _ = _ + rw [update_cursor tape distinct, update_output tape distinct] + rw [finalTapes] at literal + have tally : (advance (TM2.step program))^[1] + (some ⟨some (labels .tally), clean ambient slot, + loopTapes tape base suffix + ((BinaryLiteralMachine.outputWord tokens token.2 token.1).reverse ++ output) + variableCounter clauses⟩) = + some ⟨some (labels .entry), clean ambient (nextSlot slot), + loopTapes tape base suffix + ((BinaryLiteralMachine.outputWord tokens token.2 token.1).reverse ++ output) + (true :: variableCounter) (List.replicate (clauseIncrement slot) true ++ clauses)⟩ := by + simpa only [Function.iterate_one, advance_some] using + tallyStep tape distinct labels done malformed program atLabels base ambient slot suffix + ((BinaryLiteralMachine.outputWord tokens token.2 token.1).reverse ++ output) + variableCounter clauses + have full := joinTrace (joinTrace first literal) tally + simpa only [show 1 + BinaryLiteralMachine.steps tokens token.2 + 1 = + BinaryLiteralMachine.steps tokens token.2 + 2 by omega] using full + +theorem loopTrace (tokens input : List Token) (slot : Fin 3) + (output variableCounter clauses : List Bool) + (tokensCanonical : ∀ t ∈ tokens, BinaryNameMachine.canonical t.2 = true) + (included : ∀ t ∈ input, t ∈ tokens) + (permanent : base (tape 1) = BinaryNameSearch.stream tokens) + (empty : ∀ i : Fin 11, 2 ≤ i.val → i.val ≤ 7 → base (tape i) = []) : + (advance (TM2.step program))^[steps tokens input] + (some ⟨some (labels .entry), clean ambient slot, + loopTapes tape base (BinaryNameSearch.stream input) output variableCounter clauses⟩) = + some ⟨done, clean ambient (finalSlot input.length slot), + loopTapes tape base [] ((outputBody tokens input).reverse ++ output) + (List.replicate input.length true ++ variableCounter) + (List.replicate (completedClauses input.length slot) true ++ clauses)⟩ := by + induction input generalizing slot output variableCounter clauses with + | nil => + simpa only [steps, Function.iterate_one, advance_some, BinaryNameSearch.stream_nil, + List.length_nil, outputBody_nil, List.reverse_nil, List.nil_append, + finalSlot, completedClauses, List.replicate_zero] using + emptyStep tape distinct labels done malformed program atLabels base ambient + slot output variableCounter clauses + | cons token input ih => + have member := included token (by simp) + have present : token.2 ∈ BinaryNameSearch.payloads tokens := + List.mem_map.mpr ⟨token, member, rfl⟩ + have first := bodyTrace tape distinct labels done malformed program atLabels base ambient + tokens token slot (BinaryNameSearch.stream input) output variableCounter clauses + (tokensCanonical token member) tokensCanonical present permanent empty + have rest := ih (nextSlot slot) + ((BinaryLiteralMachine.outputWord tokens token.2 token.1).reverse ++ output) + (true :: variableCounter) (List.replicate (clauseIncrement slot) true ++ clauses) + (fun t ht => included t (by simp [ht])) + have full := joinTrace first rest + have variableEq : List.replicate input.length true ++ (true :: variableCounter) = + List.replicate (input.length + 1) true ++ variableCounter := by + rw [List.replicate_succ'] + simp only [List.append_assoc, List.singleton_append] + have clauseEq : List.replicate (completedClauses input.length (nextSlot slot)) true ++ + (List.replicate (clauseIncrement slot) true ++ clauses) = + List.replicate (completedClauses (input.length + 1) slot) true ++ clauses := by + rw [← List.append_assoc, ← List.replicate_add] + rfl + simpa only [steps, BinaryNameSearch.stream_cons, List.length_cons, finalSlot, + outputBody_cons, List.reverse_append, List.append_assoc, variableEq, clauseEq] using full + +theorem triplesTrace (tokens input : List Token) (count : Nat) + (length_eq : input.length = 3 * count) (output variableCounter clauses : List Bool) + (tokensCanonical : ∀ t ∈ tokens, BinaryNameMachine.canonical t.2 = true) + (included : ∀ t ∈ input, t ∈ tokens) + (permanent : base (tape 1) = BinaryNameSearch.stream tokens) + (empty : ∀ i : Fin 11, 2 ≤ i.val → i.val ≤ 7 → base (tape i) = []) : + (advance (TM2.step program))^[steps tokens input] + (some ⟨some (labels .entry), clean ambient 0, + loopTapes tape base (BinaryNameSearch.stream input) output variableCounter clauses⟩) = + some ⟨done, clean ambient 0, + loopTapes tape base [] ((outputBody tokens input).reverse ++ output) + (List.replicate (3 * count) true ++ variableCounter) + (List.replicate count true ++ clauses)⟩ := by + have h := loopTrace tape distinct labels done malformed program atLabels base ambient + tokens input 0 output variableCounter clauses tokensCanonical included permanent empty + simpa only [length_eq, finalSlot_triples, completedClauses_triples] using h + +def triplesInTime (tokens input : List Token) (count : Nat) + (length_eq : input.length = 3 * count) (output variableCounter clauses : List Bool) + (tokensCanonical : ∀ t ∈ tokens, BinaryNameMachine.canonical t.2 = true) + (included : ∀ t ∈ input, t ∈ tokens) + (permanent : base (tape 1) = BinaryNameSearch.stream tokens) + (empty : ∀ i : Fin 11, 2 ≤ i.val → i.val ≤ 7 → base (tape i) = []) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .entry), clean ambient 0, + loopTapes tape base (BinaryNameSearch.stream input) output variableCounter clauses⟩ + (some ⟨done, clean ambient 0, + loopTapes tape base [] ((outputBody tokens input).reverse ++ output) + (List.replicate (3 * count) true ++ variableCounter) + (List.replicate count true ++ clauses)⟩) + (perLiteralBound (BinaryNameSearch.stream tokens).length * input.length + 1) where + steps := steps tokens input + evals_in_steps := triplesTrace tape distinct labels done malformed program atLabels base ambient + tokens input count length_eq output variableCounter clauses tokensCanonical included permanent empty + steps_le_m := steps_le tokens input included + +end Program + +end PerfectCompleteness.BinaryRenameLoop + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryRenameMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryRenameMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..1ffefaa8cb027a1be7fa040c466a7148be55db31 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryRenameMachine.lean @@ -0,0 +1,343 @@ +import Mathlib.Data.List.Basic +import OAI.Computability.PerfectCompleteness.Machines.BinaryHeaderMachine +import OAI.Computability.PerfectCompleteness.Machines.BinaryRenameLoop +import OAI.Computability.PerfectCompleteness.Machines.BinaryRenameWords +import OAI.Computability.UniqueGames.Machines.GraphCounterStartLemmas +import OAI.Computability.UniqueGames.Machines.MachineFiniteAlphabet + +namespace OAI + + +namespace PerfectCompleteness.BinaryRenameMachine + + +open Turing UniqueGamesTheorem.Foundations +open Complexity Complexity.MachineComposition +open UniqueGamesTheorem.Reduction.MachineTransfer + +abbrev Tape := Fin 12 +abbrev Alphabet (_ : Tape) := Bool +abbrev State := BinaryRenameLoop.State Unit + +inductive Label + | copyOut | copyBack + | loop (label : BinaryRenameLoop.Label) + | restore | clauseStart | clauseLoop | variableStart | variableLoop + | cleanup | reject + deriving DecidableEq, Fintype + +def loopTapes : Fin 11 → Tape := Fin.castSucc + +theorem loopTapes_injective : Function.Injective loopTapes := by + intro i j h + apply Fin.ext + exact congrArg (fun k : Tape => k.val) h + +def program : Label → TM2.Stmt Alphabet Label State + | .copyOut => loopAt 1 6 id false .copyOut (some .copyBack) + | .copyBack => MachineCopy.forkLoop 6 1 0 false .copyBack (some (.loop .entry)) + | .loop label => BinaryRenameLoop.instruction loopTapes Label.loop + (some .restore) (some .reject) label + | .restore => loopAt 8 11 id false .restore (some .clauseStart) + | .clauseStart => BinaryHeaderMachine.delimiter 11 .clauseLoop + | .clauseLoop => loopAt 10 11 id false .clauseLoop (some .variableStart) + | .variableStart => BinaryHeaderMachine.delimiter 11 .variableLoop + | .variableLoop => loopAt 9 11 id false .variableLoop (some .cleanup) + | .cleanup => MachineDrain.drain 1 .cleanup none + | .reject => .halt + +abbrev machine : FinTM2 where + K := Tape + k₀ := 1 + k₁ := 11 + Γ := Alphabet + Λ := Label + main := .copyOut + σ := State + initialState := BinaryRenameLoop.clean () 0 + m := program + +def tapes (permanent cursor reversed variableCounter clauseCounter output : List Bool) : + Tape → List Bool := fun k => + if k = 0 then cursor + else if k = 1 then permanent + else if k = 8 then reversed + else if k = 9 then variableCounter + else if k = 10 then clauseCounter + else if k = 11 then output + else [] + +def cfg (label : Option Label) + (permanent cursor reversed variableCounter clauseCounter output : List Bool) : machine.Cfg := + ⟨label, BinaryRenameLoop.clean () 0, + tapes permanent cursor reversed variableCounter clauseCounter output⟩ + +theorem initList_eq (input : List Bool) : + initList machine input = cfg (some .copyOut) input [] [] [] [] [] := by + unfold initList cfg + congr 1 + funext k + fin_cases k <;> simp [tapes, machine] + +theorem haltList_eq (output : List Bool) : + haltList machine output = cfg none [] [] [] [] [] output := by + unfold haltList cfg + congr 1 + funext k + fin_cases k <;> simp [tapes, machine] + +theorem copyTrace (input : List Bool) : + (advance machine.step)^[2 * (input.length + 1)] + (some (cfg (some .copyOut) input [] [] [] [] [])) = + some (cfg (some (.loop .entry)) input input [] [] [] []) := by + have updated : Function.update (tapes input [] [] [] [] []) 0 input = + tapes input input [] [] [] [] := by + funext k + fin_cases k <;> simp [tapes] + have h := MachineCopy.copyTrace (1 : Tape) 0 6 (by decide) (by decide) (by decide) + false .copyOut .copyBack (some (.loop .entry)) program rfl rfl + (tapes input [] [] [] [] []) (by simp [tapes]) + (BinaryRenameLoop.clean () 0).1 none + have first : tapes input [] [] [] [] [] 1 = input := rfl + have second : tapes input [] [] [] [] [] 0 = [] := rfl + rw [first, second, List.append_nil, updated] at h + exact h + +theorem restoreTrace (input body variableCounter clauseCounter : List Bool) : + (advance machine.step)^[body.length + 1] + (some (cfg (some .restore) input [] body.reverse variableCounter clauseCounter [])) = + some (cfg (some .clauseStart) input [] [] variableCounter clauseCounter body) := by + change (nextAt (11 : Tape) program)^[body.length + 1] + (some (cfg (some .restore) input [] body.reverse variableCounter clauseCounter [])) = _ + have updated : tapesAt (8 : Tape) 11 + (tapes input [] body.reverse variableCounter clauseCounter []) [] body = + tapes input [] [] variableCounter clauseCounter body := by + funext k + fin_cases k <;> simp [tapesAt, tapes] + have h := transferAt_fromTapes (Γ := Alphabet) (8 : Tape) 11 (by decide) id false + .restore (some .clauseStart) program rfl + (tapes input [] body.reverse variableCounter clauseCounter []) + (BinaryRenameLoop.clean () 0).1 none + have source : tapes input [] body.reverse variableCounter clauseCounter [] 8 = body.reverse := rfl + have output : tapes input [] body.reverse variableCounter clauseCounter [] 11 = [] := rfl + rw [source, output, List.length_reverse, List.reverse_reverse, List.map_id_fun, + List.append_nil, id_eq, updated] at h + exact h + +theorem headerTrace (input body : List Bool) (n m : Nat) : + (advance machine.step)^[n + m + 4] + (some (cfg (some .clauseStart) input [] [] + (List.replicate n true) (List.replicate m true) body)) = + some (cfg (some .cleanup) input [] [] [] [] + (encodeWord n ++ encodeWord m ++ body)) := by + change (advance (TM2.step program))^[n + m + 4] + (some ⟨some .clauseStart, ((BinaryRenameLoop.clean () 0).1, none), + tapes input [] [] (List.replicate n true) (List.replicate m true) body⟩) = + some ⟨some .cleanup, ((BinaryRenameLoop.clean () 0).1, none), + tapes input [] [] [] [] (encodeWord n ++ encodeWord m ++ body)⟩ + have updated (variableWord clauses output : List Bool) : + BinaryHeaderMachine.tapes (9 : Tape) 10 11 (tapes input [] [] [] [] []) + variableWord clauses output = tapes input [] [] variableWord clauses output := by + funext k + fin_cases k <;> simp [BinaryHeaderMachine.tapes, tapes] + have h := BinaryHeaderMachine.headerTrace (9 : Tape) 10 11 + (by decide) (by decide) (by decide) + .clauseStart .clauseLoop .variableStart .variableLoop (some .cleanup) program + rfl rfl rfl rfl (tapes input [] [] [] [] []) + (BinaryRenameLoop.clean () 0).1 n m body none + simp only [updated] at h + exact h + +theorem cleanupTrace (input output : List Bool) : + (advance machine.step)^[input.length + 1] + (some (cfg (some .cleanup) input [] [] [] [] output)) = + some (cfg none [] [] [] [] [] output) := by + change (advance (TM2.step program))^[input.length + 1] + (some ⟨some .cleanup, ((BinaryRenameLoop.clean () 0).1, none), + tapes input [] [] [] [] output⟩) = + some ⟨none, ((BinaryRenameLoop.clean () 0).1, none), tapes [] [] [] [] [] output⟩ + have updated (word : List Bool) : + Function.update (tapes [] [] [] [] [] output) 1 word = + tapes word [] [] [] [] output := by + funext k + fin_cases k <;> simp [tapes] + have h := MachineDrain.drainTrace (1 : Tape) .cleanup none program rfl + (tapes [] [] [] [] [] output) input (BinaryRenameLoop.clean () 0).1 none + simp only [updated] at h + exact h + +theorem outputBody_eq (formula : BinaryFormula.Formula) : + BinaryRenameLoop.outputBody (BinaryRenameWords.tokens formula.clauses) + (BinaryRenameWords.tokens formula.clauses) = BinaryRenameWords.body formula := by + change ((BinaryRenameWords.literals formula.clauses).map BinaryRenameWords.token).flatMap + (fun t => BinaryLiteralMachine.outputWord (BinaryRenameWords.tokens formula.clauses) + t.2 t.1) = (BinaryRenameWords.literals formula.clauses).flatMap + (BinaryRenameWords.outputLiteral (BinaryFormula.sourceNames formula)) + rw [List.flatMap_map] + apply List.flatMap_congr + intro literal _ + simp only [BinaryRenameWords.token, BinaryLiteralMachine.outputWord, + BinaryLiteralMachine.index, BinaryLiteralMachine.signWord, + BinaryRenameWords.payload_index, BinaryRenameWords.outputLiteral] + rfl + +theorem loopTrace (formula : BinaryFormula.Formula) : + (advance machine.step)^[BinaryRenameLoop.steps (BinaryRenameWords.tokens formula.clauses) + (BinaryRenameWords.tokens formula.clauses)] + (some (cfg (some (.loop .entry)) (BinaryTokenMachine.tokens formula.clauses) + (BinaryTokenMachine.tokens formula.clauses) [] [] [] [])) = + some (cfg (some .restore) (BinaryTokenMachine.tokens formula.clauses) [] + (BinaryRenameWords.body formula).reverse (List.replicate (3 * formula.clauses.length) true) + (List.replicate formula.clauses.length true) []) := by + change (advance (TM2.step program))^[BinaryRenameLoop.steps + (BinaryRenameWords.tokens formula.clauses) (BinaryRenameWords.tokens formula.clauses)] + (some ⟨some (.loop .entry), BinaryRenameLoop.clean () 0, + tapes (BinaryTokenMachine.tokens formula.clauses) (BinaryTokenMachine.tokens formula.clauses) + [] [] [] []⟩) = + some ⟨some .restore, BinaryRenameLoop.clean () 0, + tapes (BinaryTokenMachine.tokens formula.clauses) [] (BinaryRenameWords.body formula).reverse + (List.replicate (3 * formula.clauses.length) true) + (List.replicate formula.clauses.length true) []⟩ + let input := BinaryTokenMachine.tokens formula.clauses + have updated (cursor output variableWord clauseWord : List Bool) : + BinaryRenameLoop.loopTapes loopTapes (tapes input [] [] [] [] []) + cursor output variableWord clauseWord = + tapes input cursor output variableWord clauseWord [] := by + funext k + fin_cases k <;> simp [BinaryRenameLoop.loopTapes, loopTapes, tapes] + have scratch (i : Fin 11) (lo : 2 ≤ i.val) (hi : i.val ≤ 7) : + tapes input [] [] [] [] [] (loopTapes i) = [] := by + have n0 : loopTapes i ≠ 0 := by intro h; have := congrArg Fin.val h; simp [loopTapes] at this; omega + have n1 : loopTapes i ≠ 1 := by intro h; have := congrArg Fin.val h; simp [loopTapes] at this; omega + have n8 : loopTapes i ≠ 8 := by intro h; have := congrArg Fin.val h; simp [loopTapes] at this; omega + have n9 : loopTapes i ≠ 9 := by intro h; have := congrArg Fin.val h; simp [loopTapes] at this; omega + have n10 : loopTapes i ≠ 10 := by intro h; have := congrArg Fin.val h; simp [loopTapes] at this; omega + have n11 : loopTapes i ≠ 11 := by intro h; have := congrArg Fin.val h; simp [loopTapes] at this; omega + simp [tapes, n0, n1, n8, n9, n10, n11] + have run := BinaryRenameLoop.triplesTrace loopTapes loopTapes_injective Label.loop + (some .restore) (some .reject) program (fun _ => rfl) + (tapes input [] [] [] [] []) () + (BinaryRenameWords.tokens formula.clauses) (BinaryRenameWords.tokens formula.clauses) + formula.clauses.length (BinaryRenameWords.tokens_length formula.clauses) [] [] [] + (BinaryRenameWords.tokens_canonical formula.clauses) (fun _ h => h) + (by change input = _; rw [BinaryRenameWords.tokens_stream]) scratch + simp only [updated, BinaryRenameWords.tokens_stream, outputBody_eq, List.append_nil, input] at run + exact run + +private theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +def steps (formula : BinaryFormula.Formula) : Nat := + 2 * ((BinaryTokenMachine.tokens formula.clauses).length + 1) + + BinaryRenameLoop.steps (BinaryRenameWords.tokens formula.clauses) + (BinaryRenameWords.tokens formula.clauses) + + ((BinaryRenameWords.body formula).length + 1) + (4 * formula.clauses.length + 4) + + ((BinaryTokenMachine.tokens formula.clauses).length + 1) + +theorem renameTrace (formula : BinaryFormula.Formula) : + (advance machine.step)^[steps formula] + (some (initList machine (BinaryTokenMachine.tokens formula.clauses))) = + some (haltList machine (formulaBits (BinaryOccurrenceRename.renamed formula))) := by + have first := copyTrace (BinaryTokenMachine.tokens formula.clauses) + have second := loopTrace formula + have third := restoreTrace (BinaryTokenMachine.tokens formula.clauses) + (BinaryRenameWords.body formula) (List.replicate (3 * formula.clauses.length) true) + (List.replicate formula.clauses.length true) + have fourth := headerTrace (BinaryTokenMachine.tokens formula.clauses) + (BinaryRenameWords.body formula) (3 * formula.clauses.length) formula.clauses.length + have fifth := cleanupTrace (BinaryTokenMachine.tokens formula.clauses) + (encodeWord (3 * formula.clauses.length) ++ encodeWord formula.clauses.length ++ + BinaryRenameWords.body formula) + have full := joinTrace (joinTrace (joinTrace (joinTrace first second) third) fourth) fifth + have count : 3 * formula.clauses.length + formula.clauses.length + 4 = + 4 * formula.clauses.length + 4 := by omega + simpa only [steps, initList_eq, haltList_eq, BinaryRenameWords.encoded_renamed, count] using full + +theorem clause_count_le_stream (formula : BinaryFormula.Formula) : + formula.clauses.length ≤ (BinaryTokenMachine.tokens formula.clauses).length := by + rw [BinaryTokenMachine.tokens_length] + omega + +theorem body_length_le (formula : BinaryFormula.Formula) : + (BinaryRenameWords.body formula).length ≤ + 9 * (BinaryTokenMachine.tokens formula.clauses).length ^ 2 + + 10 * (BinaryTokenMachine.tokens formula.clauses).length + 2 := by + have initial := BinaryOccurrenceRename.renamed_encoding_bound formula + rw [BinaryRenameWords.encoded_renamed] at initial + simp only [List.length_append] at initial + have count := clause_count_le_stream formula + have square := Nat.mul_self_le_mul_self count + nlinarith + +noncomputable def timePolynomial : Polynomial Nat := + Polynomial.C 12 * Polynomial.X ^ 3 + Polynomial.C 35 * Polynomial.X ^ 2 + + Polynomial.C 28 * Polynomial.X + Polynomial.C 11 + +theorem steps_le (formula : BinaryFormula.Formula) : + steps formula ≤ timePolynomial.eval (BinaryTokenMachine.tokens formula.clauses).length := by + have loopBound := BinaryRenameLoop.steps_le + (BinaryRenameWords.tokens formula.clauses) (BinaryRenameWords.tokens formula.clauses) + (fun _ h => h) + rw [BinaryRenameWords.tokens_stream, BinaryRenameWords.tokens_length] at loopBound + have literalCount : 3 * formula.clauses.length ≤ + (BinaryTokenMachine.tokens formula.clauses).length := by + rw [BinaryTokenMachine.tokens_length] + omega + have product := Nat.mul_le_mul_left + (BinaryRenameLoop.perLiteralBound (BinaryTokenMachine.tokens formula.clauses).length) + literalCount + have output := body_length_le formula + have count := clause_count_le_stream formula + simp only [timePolynomial, Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_pow, + Polynomial.eval_C, Polynomial.eval_X] + unfold steps BinaryRenameLoop.perLiteralBound at * + nlinarith + +def outputsInTime (formula : BinaryFormula.Formula) : + TM2OutputsInTime machine (BinaryTokenMachine.tokens formula.clauses) + (some (formulaBits (BinaryOccurrenceRename.renamed formula))) + (timePolynomial.eval (BinaryTokenMachine.tokens formula.clauses).length) where + steps := steps formula + evals_in_steps := renameTrace formula + steps_le_m := steps_le formula + +noncomputable def tokenComputation : + TM2ComputableInPolyTime (fun formula : BinaryFormula.Formula => + BinaryTokenMachine.tokens formula.clauses) formulaBits BinaryOccurrenceRename.renamed where + tm := machine + inputAlphabet := Equiv.refl Bool + outputAlphabet := Equiv.refl Bool + time := timePolynomial + outputsFun formula := by + change TM2OutputsInTime machine ((BinaryTokenMachine.tokens formula.clauses).map id) + (some ((formulaBits (BinaryOccurrenceRename.renamed formula)).map id)) + (timePolynomial.eval (BinaryTokenMachine.tokens formula.clauses).length) + simpa only [List.map_id_fun, id_eq] using outputsInTime formula + +noncomputable def preprocessing : + TM2ComputableInPolyTime BinaryEncoding.formulaBits + (fun formula : BinaryFormula.Formula => BinaryTokenMachine.tokens formula.clauses) + (id : BinaryFormula.Formula → BinaryFormula.Formula) where + tm := BinaryTokenMachine.computableInPolyTime.tm + inputAlphabet := BinaryTokenMachine.computableInPolyTime.inputAlphabet + outputAlphabet := BinaryTokenMachine.computableInPolyTime.outputAlphabet + time := BinaryTokenMachine.computableInPolyTime.time + outputsFun := BinaryTokenMachine.computableInPolyTime.outputsFun + +noncomputable def computableInPolyTime : + TM2ComputableInPolyTime BinaryEncoding.formulaBits formulaBits + BinaryOccurrenceRename.renamed := + MachineSequential.composeBits preprocessing tokenComputation + +theorem machine_finiteAlphabet (k : machine.K) : Finite (machine.Γ k) := by + change Finite Bool + infer_instance + +theorem computation_finiteAlphabet : MachineFiniteAlphabet.FiniteAlphabet computableInPolyTime.tm := + MachineFiniteAlphabet.composeBits preprocessing tokenComputation + BinaryTokenMachine.machine_finiteAlphabet machine_finiteAlphabet + +end PerfectCompleteness.BinaryRenameMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryRenameWords.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryRenameWords.lean new file mode 100644 index 0000000000000000000000000000000000000000..4b4fa07b27ff9946c8a7fea058bed1ce51ffeffe --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryRenameWords.lean @@ -0,0 +1,143 @@ +import OAI.Computability.PerfectCompleteness.Machines.BinaryNameSearch +import OAI.Computability.PerfectCompleteness.Machines.BinaryOccurrenceRename +import OAI.Computability.PerfectCompleteness.Machines.BinaryParsingLemmas +import OAI.Computability.PerfectCompleteness.Machines.BinaryTokenMachine + +namespace OAI + +section + +namespace PerfectCompleteness.BinaryRenameWords + +open BinaryFormula UniqueGamesTheorem.Foundations + +def clauseLiterals (c : Clause) : List Literal := [(c)[0], (c)[1], (c)[2]] + +def literals (clauses : List Clause) : List Literal := clauses.flatMap clauseLiterals + +def token (literal : Literal) : BinaryNameSearch.Token := + (literal.positive, literal.name.bits) + +def tokens (clauses : List Clause) : List BinaryNameSearch.Token := + (literals clauses).map token + +@[simp] theorem literals_nil : literals [] = [] := rfl + +@[simp] theorem literals_cons (c : Clause) (cs : List Clause) : + literals (c :: cs) = (c)[0] :: (c)[1] :: (c)[2] :: literals cs := rfl + +@[simp] theorem literals_length (cs : List Clause) : + (literals cs).length = 3 * cs.length := by + induction cs with + | nil => rfl + | cons c cs ih => simp only [literals_cons, List.length_cons, ih]; omega + +@[simp] theorem tokens_length (cs : List Clause) : + (tokens cs).length = 3 * cs.length := by simp [tokens] + +theorem literals_names (F : Formula) : + (literals F.clauses).map Literal.name = sourceNames F := by + simp only [literals, sourceNames, List.map_flatMap] + rfl + +theorem tokens_payloads (F : Formula) : + BinaryNameSearch.payloads (tokens F.clauses) = (sourceNames F).map Nat.bits := by + rw [← literals_names] + simp only [BinaryNameSearch.payloads, tokens, List.map_map, token, Function.comp_def] + +theorem token_bits (literal : Literal) : + BinaryNameSearch.tokenBits (token literal) = BinaryEncoding.literalBits literal := by + simp only [BinaryNameSearch.tokenBits, token, BinaryEncoding.literalBits, + BinaryEncoding.nameBits, BinaryParsing.frame_eq] + +theorem tokens_stream (cs : List Clause) : + BinaryNameSearch.stream (tokens cs) = BinaryTokenMachine.tokens cs := by + induction cs with + | nil => rfl + | cons c cs ih => + simp only [tokens, literals_cons, List.map_cons, BinaryNameSearch.stream_cons, + token_bits, BinaryTokenMachine.tokens_cons, BinaryEncoding.clauseBits] + simpa only [tokens, List.append_assoc] using + congrArg (fun tail => BinaryEncoding.literalBits (c)[0] ++ + BinaryEncoding.literalBits (c)[1] ++ BinaryEncoding.literalBits (c)[2] ++ tail) ih + +theorem tokens_canonical (cs : List Clause) : + ∀ t ∈ tokens cs, BinaryNameMachine.canonical t.2 = true := by + intro t mem + obtain ⟨literal, _, rfl⟩ := List.mem_map.mp mem + exact BinaryParsing.canonical_nat_bits literal.name + +theorem payload_index (F : Formula) (name : Nat) : + (BinaryNameSearch.payloads (tokens F.clauses)).idxOf name.bits = + (sourceNames F).idxOf name := by + rw [tokens_payloads, BinaryOccurrenceRename.idxOf_binary_payloads] + +theorem token_payload_mem (cs : List Clause) (literal : Literal) + (mem : literal ∈ literals cs) : + literal.name.bits ∈ BinaryNameSearch.payloads (tokens cs) := by + apply List.mem_map.mpr + refine ⟨token literal, ?_, rfl⟩ + exact List.mem_map.mpr ⟨literal, mem, rfl⟩ + +theorem payloadSize_tokens (cs : List Clause) : + BinaryNameSearch.payloadSize (tokens cs) = BinaryEncoding.namesBitSize cs := by + induction cs with + | nil => rfl + | cons c cs ih => + simp only [tokens, literals_cons, List.map_cons, + BinaryNameSearch.payloadSize_cons, token, Nat.size_eq_bits_len, + BinaryEncoding.namesBitSize_cons] at * + simpa only [BinaryEncoding.clauseNameSize, BinaryFormula.clauseNames, + List.map_cons, List.map_nil, List.sum_cons, List.sum_nil, + Nat.add_zero, Nat.add_assoc] using congrArg + (fun tail => (c)[0].name.size + ((c)[1].name.size + ((c)[2].name.size + tail))) ih + +def outputLiteral (names : List Nat) (literal : Literal) : List Bool := + Complexity.encodeWord (names.idxOf literal.name) ++ + Complexity.encodeWord (if literal.positive then 1 else 0) + +def body (F : Formula) : List Bool := + (literals F.clauses).flatMap (outputLiteral (sourceNames F)) + +theorem encoded_clause (F : Formula) (c : Clause) (mem : c ∈ F.clauses) : + Complexity.encodeWords (Complexity.clauseWords (BinaryOccurrenceRename.clause F c mem)) = + (clauseLiterals c).flatMap (outputLiteral (sourceNames F)) := by + simp [Complexity.clauseWords, Complexity.literalWords, Complexity.encodeWords, + BinaryOccurrenceRename.clause, BinaryOccurrenceRename.literal, + BinaryOccurrenceRename.nameIndex, clauseLiterals, outputLiteral, List.append_assoc] + rfl + +private theorem encodeWords_flatMap {α : Type} (xs : List α) (f : α → List Nat) : + Complexity.encodeWords (xs.flatMap f) = + xs.flatMap (fun x => Complexity.encodeWords (f x)) := by + induction xs with + | nil => rfl + | cons x xs ih => simp only [List.flatMap_cons, Complexity.encodeWords_append, ih] + +theorem encoded_body (F : Formula) : + Complexity.encodeWords ((BinaryOccurrenceRename.renamed F).clauses.flatMap + Complexity.clauseWords) = body F := by + rw [encodeWords_flatMap] + change (F.clauses.attach.map (fun c => BinaryOccurrenceRename.clause F c.val c.property)).flatMap + (fun c => Complexity.encodeWords (Complexity.clauseWords c)) = body F + rw [List.flatMap_map] + simp only [encoded_clause] + have h := congrArg (fun cs : List Clause => + cs.flatMap (fun c => (clauseLiterals c).flatMap (outputLiteral (sourceNames F)))) + (List.attach_map_subtype_val F.clauses) + simpa only [List.flatMap_map, body, literals, List.flatMap_assoc] using h + +theorem encoded_renamed (F : Formula) : + Complexity.formulaBits (BinaryOccurrenceRename.renamed F) = + Complexity.encodeWord (3 * F.clauses.length) ++ + Complexity.encodeWord F.clauses.length ++ body F := by + simp only [Complexity.formulaBits, Complexity.formulaWords, Complexity.encodeWords_append, + Complexity.encodeWords, List.append_nil, + BinaryOccurrenceRename.renamed_variable_count, + BinaryOccurrenceRename.renamed_clause_count, encoded_body, List.append_assoc] + +end PerfectCompleteness.BinaryRenameWords + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryTokenMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryTokenMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..bcc36ddeef6db99a310cf2f3e19e4abff9502abc --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryTokenMachine.lean @@ -0,0 +1,357 @@ +import Mathlib.Tactic.DeriveFintype +import OAI.Computability.PerfectCompleteness.Machines.BinaryFormulaLemmas +import OAI.Computability.UniqueGames.Machines.MachineCompositionLemmas +import OAI.Computability.UniqueGames.Reduction.MachineTransfer + +namespace OAI + + +namespace PerfectCompleteness.BinaryTokenMachine + + +open Turing +open UniqueGamesTheorem.Foundations.Complexity +open MachineComposition +open UniqueGamesTheorem.Reduction.MachineTransfer +open BinaryFormula BinaryEncoding + +abbrev Tape := Fin 3 +abbrev Alphabet (_ : Tape) := Bool +abbrev State := Unit × Option Bool + +inductive Label where + | clause + | sign (slot : Fin 3) + | name (slot : Fin 3) + | restore + | accept + | reject + deriving DecidableEq, Fintype + +def afterName (slot : Fin 3) : Label := + if slot = 0 then .sign 1 else if slot = 1 then .sign 2 else .clause + +@[simp] theorem afterName_zero : afterName 0 = .sign 1 := rfl +@[simp] theorem afterName_one : afterName 1 = .sign 2 := rfl +@[simp] theorem afterName_two : afterName 2 = .clause := rfl + +def jump (label : Label) : TM2.Stmt Alphabet Label State := + .load (fun _ => ((), none)) (.goto fun _ => label) + +def clauseInstruction : TM2.Stmt Alphabet Label State := + .pop 0 (fun state head => (state.1, head)) + (.branch (fun state => state.2.isNone) + (jump .reject) + (.branch (fun state => state.2.getD false) + (jump (.sign 0)) (jump .restore))) + +def signInstruction (slot : Fin 3) : TM2.Stmt Alphabet Label State := + .pop 0 (fun state head => (state.1, head)) + (.branch (fun state => state.2.isSome) + (.push 1 (fun state => state.2.getD false) (jump (.name slot))) + (jump .reject)) + +def nameInstruction (slot : Fin 3) : TM2.Stmt Alphabet Label State := + .pop 0 (fun state head => (state.1, head)) + (.branch (fun state => state.2.isNone) + (jump .reject) + (.branch (fun state => state.2.getD false) + (.push 1 (fun _ => true) + (.pop 0 (fun state head => (state.1, head)) + (.branch (fun state => state.2.isSome) + (.push 1 (fun state => state.2.getD false) (jump (.name slot))) + (jump .reject)))) + (.push 1 (fun _ => false) (jump (afterName slot))))) + +def program : Label → TM2.Stmt Alphabet Label State + | .clause => clauseInstruction + | .sign slot => signInstruction slot + | .name slot => nameInstruction slot + | .restore => loopAt 1 2 id false .restore (some .accept) + | .accept => .halt + | .reject => .halt + +abbrev machine : FinTM2 where + K := Tape + k₀ := 0 + k₁ := 2 + Γ := Alphabet + Λ := Label + main := .clause + σ := State + initialState := ((), none) + m := program + +def tapes (input reversed output : List Bool) : Tape → List Bool := + fun k => if k = 0 then input else if k = 1 then reversed else output + +def cfg (label : Option Label) (input reversed output : List Bool) + (register : Option Bool := none) : machine.Cfg := + ⟨label, ((), register), tapes input reversed output⟩ + +@[simp] private theorem tapes_zero (input reversed output : List Bool) : + tapes input reversed output 0 = input := rfl + +@[simp] private theorem tapes_one (input reversed output : List Bool) : + tapes input reversed output 1 = reversed := rfl + +@[simp] private theorem tapes_two (input reversed output : List Bool) : + tapes input reversed output 2 = output := rfl + +private theorem update_zero (input reversed output replacement : List Bool) : + Function.update (tapes input reversed output) 0 replacement = + tapes replacement reversed output := by + funext k + fin_cases k <;> simp [tapes] + +private theorem update_one (input reversed output replacement : List Bool) : + Function.update (tapes input reversed output) 1 replacement = + tapes input replacement output := by + funext k + fin_cases k <;> simp [tapes] + +theorem clauseStep (input reversed output : List Bool) (register : Option Bool) : + machine.step (cfg (some .clause) (true :: input) reversed output register) = + some (cfg (some (.sign 0)) input reversed output) := by + change some (TM2.stepAux (program .clause) _ _) = _ + simp [program, clauseInstruction, jump, cfg, TM2.stepAux, update_zero] + rfl + +theorem finalStep (input reversed output : List Bool) (register : Option Bool) : + machine.step (cfg (some .clause) (false :: input) reversed output register) = + some (cfg (some .restore) input reversed output) := by + change some (TM2.stepAux (program .clause) _ _) = _ + simp [program, clauseInstruction, jump, cfg, TM2.stepAux, update_zero] + rfl + +theorem signStep (slot : Fin 3) (bit : Bool) (input reversed output : List Bool) + (register : Option Bool) : + machine.step (cfg (some (.sign slot)) (bit :: input) reversed output register) = + some (cfg (some (.name slot)) input (bit :: reversed) output) := by + change some (TM2.stepAux (program (.sign slot)) _ _) = _ + simp [program, signInstruction, jump, cfg, TM2.stepAux, update_zero, update_one] + rfl + +theorem nameEndStep (slot : Fin 3) (input reversed output : List Bool) + (register : Option Bool) : + machine.step (cfg (some (.name slot)) (false :: input) reversed output register) = + some (cfg (some (afterName slot)) input (false :: reversed) output) := by + change some (TM2.stepAux (program (.name slot)) _ _) = _ + simp [program, nameInstruction, jump, cfg, TM2.stepAux, update_zero, update_one] + rfl + +theorem nameDigitStep (slot : Fin 3) (bit : Bool) (input reversed output : List Bool) + (register : Option Bool) : + machine.step + (cfg (some (.name slot)) (true :: bit :: input) reversed output register) = + some (cfg (some (.name slot)) input (bit :: true :: reversed) output) := by + change some (TM2.stepAux (program (.name slot)) _ _) = _ + simp [program, nameInstruction, jump, cfg, TM2.stepAux, update_zero, update_one] + rfl + +theorem nameTrace (slot : Fin 3) (bits suffix reversed output : List Bool) + (register : Option Bool) : + (advance machine.step)^[bits.length + 1] + (some (cfg (some (.name slot)) (frame bits ++ suffix) reversed output register)) = + some (cfg (some (afterName slot)) suffix ((frame bits).reverse ++ reversed) output) := by + induction bits generalizing reversed register with + | nil => + simpa only [List.length_nil, Nat.zero_add, Function.iterate_one, advance_some, + frame, List.singleton_append, List.reverse_singleton] using + nameEndStep slot suffix reversed output register + | cons bit bits ih => + rw [List.length_cons, Function.iterate_succ_apply] + simp only [frame, List.cons_append, advance_some] + rw [nameDigitStep, ih] + simp only [List.reverse_cons, List.append_assoc, + List.cons_append, List.nil_append] + +theorem literalTrace (slot : Fin 3) (literal : Literal) + (suffix reversed output : List Bool) (register : Option Bool) : + (advance machine.step)^[literal.name.size + 2] + (some (cfg (some (.sign slot)) (literalBits literal ++ suffix) reversed output register)) = + some (cfg (some (afterName slot)) suffix + ((literalBits literal).reverse ++ reversed) output) := by + rw [show literal.name.size + 2 = (literal.name.bits.length + 1) + 1 by + rw [Nat.size_eq_bits_len]] + rw [Function.iterate_succ_apply] + simp only [literalBits, List.cons_append, advance_some] + rw [signStep] + change (advance machine.step)^[literal.name.bits.length + 1] + (some (cfg (some (.name slot)) (frame literal.name.bits ++ suffix) + (literal.positive :: reversed) output)) = _ + rw [nameTrace] + simp only [nameBits, List.reverse_cons, List.append_assoc, List.singleton_append] + +private theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +theorem clauseTrace (clause : Clause) (suffix reversed output : List Bool) + (register : Option Bool) : + (advance machine.step)^[clauseNameSize clause + 6] + (some (cfg (some (.sign 0)) (clauseBits clause ++ suffix) reversed output register)) = + some (cfg (some .clause) suffix ((clauseBits clause).reverse ++ reversed) output) := by + have first := literalTrace 0 clause[0] + (literalBits clause[1] ++ literalBits clause[2] ++ suffix) reversed output register + have second := literalTrace 1 clause[1] (literalBits clause[2] ++ suffix) + ((literalBits clause[0]).reverse ++ reversed) output none + have third := literalTrace 2 clause[2] suffix + ((literalBits clause[1]).reverse ++ ((literalBits clause[0]).reverse ++ reversed)) output none + simp only [afterName_zero, afterName_one, afterName_two, List.append_assoc] + at first second third + have full := joinTrace (joinTrace first second) third + have htime : (clause[0].name.size + 2 + (clause[1].name.size + 2)) + + (clause[2].name.size + 2) = clauseNameSize clause + 6 := by + simp [clauseNameSize, clauseNames] + omega + rw [htime] at full + simpa only [clauseBits, List.append_assoc, List.reverse_append] using full + +def tokens (clauses : List Clause) : List Bool := clauses.flatMap clauseBits + +@[simp] theorem tokens_nil : tokens [] = [] := rfl + +@[simp] theorem tokens_cons (clause : Clause) (clauses : List Clause) : + tokens (clause :: clauses) = clauseBits clause ++ tokens clauses := by + simp [tokens] + +@[simp] theorem tokens_length (clauses : List Clause) : + (tokens clauses).length = 6 * clauses.length + 2 * namesBitSize clauses := by + induction clauses with + | nil => rfl + | cons clause clauses ih => + simp only [tokens_cons, List.length_append, clauseBits_length, ih, + List.length_cons, namesBitSize_cons] + omega + +theorem stripTrace (clauses : List Clause) (suffix reversed output : List Bool) + (register : Option Bool) : + (advance machine.step)^[7 * clauses.length + namesBitSize clauses + 1] + (some (cfg (some .clause) (clausesBits clauses ++ suffix) reversed output register)) = + some (cfg (some .restore) suffix ((tokens clauses).reverse ++ reversed) output) := by + induction clauses generalizing reversed register with + | nil => + simpa only [List.length_nil, Nat.mul_zero, namesBitSize_nil, Nat.add_zero, + Nat.zero_add, Function.iterate_one, advance_some, clausesBits, + List.singleton_append, tokens_nil, List.reverse_nil, List.nil_append] using + finalStep suffix reversed output register + | cons clause clauses ih => + have first : (advance machine.step)^[1] + (some (cfg (some .clause) + (true :: (clauseBits clause ++ (clausesBits clauses ++ suffix))) + reversed output register)) = + some (cfg (some (.sign 0)) + (clauseBits clause ++ (clausesBits clauses ++ suffix)) reversed output) := by + simpa only [Function.iterate_one, advance_some] using + clauseStep (clauseBits clause ++ (clausesBits clauses ++ suffix)) reversed output register + have second := clauseTrace clause (clausesBits clauses ++ suffix) reversed output none + have third := ih ((clauseBits clause).reverse ++ reversed) none + have full := joinTrace (joinTrace first second) third + have htime : (1 + (clauseNameSize clause + 6)) + + (7 * clauses.length + namesBitSize clauses + 1) = + 7 * (clause :: clauses).length + namesBitSize (clause :: clauses) + 1 := by + simp only [List.length_cons, namesBitSize_cons] + omega + rw [htime] at full + simpa only [clausesBits, List.cons_append, List.append_assoc, + tokens_cons, List.reverse_append] using full + +theorem restoreTrace (input unread output : List Bool) (register : Option Bool) : + (advance machine.step)^[input.length + 1] + (some (cfg (some .restore) unread input.reverse output register)) = + some (cfg (some .accept) unread [] (input ++ output)) := by + have h := transferAt_fromTapes (Γ := Alphabet) (σ := Unit) 1 2 (by decide) + id false .restore (some .accept) program rfl + (tapes unread input.reverse output) () register + have ht : tapesAt 1 2 (tapes unread input.reverse output) [] (input ++ output) = + tapes unread [] (input ++ output) := by + funext k + fin_cases k <;> simp [tapesAt, tapes] + change (nextAt 2 program)^[input.length + 1] + (some (cfg (some .restore) unread input.reverse output register)) = _ + simpa only [tapes_one, tapes_two, List.length_reverse, List.reverse_reverse, + List.map_id_fun, id_eq, ht, nextAt, advance, cfg] using! h + +theorem initList_eq (input : List Bool) : + initList machine input = cfg (some .clause) input [] [] := by + unfold initList cfg + congr 1 + funext k + fin_cases k <;> simp [tapes, machine] + +theorem haltList_eq (output : List Bool) : + haltList machine output = cfg none [] [] output := by + unfold haltList cfg + congr 1 + funext k + fin_cases k <;> simp [tapes, machine] + +theorem acceptTrace (formula : Formula) : + (advance machine.step)^[13 * formula.clauses.length + + 3 * namesBitSize formula.clauses + 2] + (some (initList machine (formulaBits formula))) = + some (cfg (some .accept) [] [] (tokens formula.clauses)) := by + have first := stripTrace formula.clauses [] [] [] none + simp only [List.append_nil] at first + have second := restoreTrace (tokens formula.clauses) [] [] none + simp only [List.append_nil] at second + have full := joinTrace first second + have htime : (7 * formula.clauses.length + namesBitSize formula.clauses + 1) + + ((tokens formula.clauses).length + 1) = + 13 * formula.clauses.length + 3 * namesBitSize formula.clauses + 2 := by + rw [tokens_length] + omega + rw [htime] at full + simpa only [initList_eq, BinaryEncoding.formulaBits] using full + +theorem haltStep (output : List Bool) : + machine.step (cfg (some .accept) [] [] output) = some (cfg none [] [] output) := by + change some (TM2.stepAux (program .accept) _ _) = _ + rfl + +theorem tokenTrace (formula : Formula) : + (advance machine.step)^[13 * formula.clauses.length + + 3 * namesBitSize formula.clauses + 3] + (some (initList machine (formulaBits formula))) = + some (haltList machine (tokens formula.clauses)) := by + rw [show 13 * formula.clauses.length + 3 * namesBitSize formula.clauses + 3 = + (13 * formula.clauses.length + 3 * namesBitSize formula.clauses + 2) + 1 by omega, + Function.iterate_succ_apply', acceptTrace, advance_some, haltStep, haltList_eq] + +theorem tokenSteps_le (formula : Formula) : + 13 * formula.clauses.length + 3 * namesBitSize formula.clauses + 3 ≤ + 3 * (formulaBits formula).length + 3 := by + rw [BinaryEncoding.formulaBits_length] + omega + +def outputsInTime (formula : Formula) : + TM2OutputsInTime machine (formulaBits formula) (some (tokens formula.clauses)) + (3 * (formulaBits formula).length + 3) where + steps := 13 * formula.clauses.length + 3 * namesBitSize formula.clauses + 3 + evals_in_steps := tokenTrace formula + steps_le_m := tokenSteps_le formula + + +noncomputable def computableInPolyTime : + TM2ComputableInPolyTime BinaryEncoding.formulaBits (id : List Bool → List Bool) + (fun formula => tokens formula.clauses) where + tm := machine + inputAlphabet := Equiv.refl Bool + outputAlphabet := Equiv.refl Bool + time := Polynomial.C 3 * Polynomial.X + Polynomial.C 3 + outputsFun formula := by + change TM2OutputsInTime machine ((formulaBits formula).map id) + (some ((tokens formula.clauses).map id)) + ((Polynomial.C 3 * Polynomial.X + Polynomial.C 3 : Polynomial Nat).eval + (formulaBits formula).length) + simpa only [List.map_id_fun, id_eq, Polynomial.eval_add, Polynomial.eval_mul, + Polynomial.eval_C, Polynomial.eval_X] using outputsInTime formula + +theorem machine_finiteAlphabet (k : machine.K) : Finite (machine.Γ k) := by + change Finite Bool + infer_instance + +end PerfectCompleteness.BinaryTokenMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryTotalInputMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryTotalInputMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..90898bd6857e837e3f39dd064bfb7b7a0ad64481 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryTotalInputMachine.lean @@ -0,0 +1,275 @@ +import OAI.Computability.PerfectCompleteness.Machines.BinaryParsingLemmas +import OAI.Computability.PerfectCompleteness.Machines.BinaryValidatorMachine +import OAI.Computability.UniqueGames.Machines.MachineDrain +import OAI.Computability.UniqueGames.Machines.MachineFiniteAlphabet +import OAI.Computability.UniqueGames.Reduction.MachineSubstitution + +namespace OAI + + +namespace PerfectCompleteness.BinaryTotalInputMachine + + +open Turing +open UniqueGamesTheorem.Foundations.Complexity +open MachineComposition +open UniqueGamesTheorem.Reduction.MachineTransfer +open UniqueGamesTheorem.Reduction.MachineSubstitution +open BinaryValidatorMachine (Mode nextMode run) + +inductive Label + | scan + | restore + | drain + | rejectOutput + deriving DecidableEq + +protected abbrev Label.enumList : List Label := [.scan, .restore, .drain, .rejectOutput] + +protected theorem Label.enumList_getElem?_ctorIdx_eq (x : Label) : + Label.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem Label.enumList_nodup : Label.enumList.Nodup := by decide + +instance : Fintype Label where + elems := ⟨Label.enumList, Label.enumList_nodup⟩ + complete x := by cases x <;> decide + +abbrev Alphabet (_ : Fin 3) := Bool +abbrev State := Mode × Option Bool + +def rejectedWord : List Bool := BinaryEncoding.formulaBits BinaryLanguage.rejectBinary + +def instruction : Label → TM2.Stmt Alphabet Label State + | .scan => + .pop 0 (fun state head => (state.1, head)) + (.branch (fun state => state.2.isSome) + (.push 2 (fun state => state.2.getD false) + (.load (fun state => (nextMode state.1 (state.2.getD false), none)) + (.goto fun _ => .scan))) + (.branch (fun state => decide (state.1 = .done)) + (.load (fun _ => (.clause, none)) (.goto fun _ => .restore)) + (.load (fun _ => (.clause, none)) (.goto fun _ => .drain)))) + | .restore => loopAt 2 1 id false .restore none + | .drain => MachineDrain.drain 2 .drain (some .rejectOutput) + | .rejectOutput => pushWord 1 rejectedWord.reverse .halt + +abbrev machine : FinTM2 where + K := Fin 3 + k₀ := 0 + k₁ := 1 + Γ := Alphabet + Λ := Label + main := .scan + σ := State + initialState := (.clause, none) + m := instruction + +def tapes (input output saved : List Bool) : Fin 3 → List Bool + | 0 => input + | 1 => output + | _ => saved + +def cfg (label : Option Label) (input output saved : List Bool) (mode : Mode := .clause) + (register : Option Bool := none) : machine.Cfg := + ⟨label, (mode, register), tapes input output saved⟩ + +@[simp] private theorem tapes_input (input output saved : List Bool) : + tapes input output saved 0 = input := rfl + +@[simp] private theorem tapes_output (input output saved : List Bool) : + tapes input output saved 1 = output := rfl + +@[simp] private theorem tapes_saved (input output saved : List Bool) : + tapes input output saved 2 = saved := rfl + +private theorem update_input (input output saved replacement : List Bool) : + Function.update (tapes input output saved) 0 replacement = + tapes replacement output saved := by + funext k + fin_cases k <;> rfl + +private theorem update_output (input output saved replacement : List Bool) : + Function.update (tapes input output saved) 1 replacement = + tapes input replacement saved := by + funext k + fin_cases k <;> rfl + +private theorem update_saved (input output saved replacement : List Bool) : + Function.update (tapes input output saved) 2 replacement = + tapes input output replacement := by + funext k + fin_cases k <;> rfl + +def afterScan (mode : Mode) : Label := if mode = .done then .restore else .drain + +theorem step_scan_empty (output saved : List Bool) (mode : Mode) (register : Option Bool) : + machine.step (cfg (some .scan) [] output saved mode register) = + some (cfg (some (afterScan mode)) [] output saved) := by + change some (TM2.stepAux (instruction .scan) _ _) = _ + by_cases accepted : mode = .done <;> + simp [instruction, cfg, TM2.stepAux, update_input, afterScan, accepted] <;> rfl + +theorem step_scan_cons (bit : Bool) (input output saved : List Bool) + (mode : Mode) (register : Option Bool) : + machine.step (cfg (some .scan) (bit :: input) output saved mode register) = + some (cfg (some .scan) input output (bit :: saved) (nextMode mode bit)) := by + change some (TM2.stepAux (instruction .scan) _ _) = _ + simp [instruction, cfg, TM2.stepAux, update_input, update_saved] + rfl + +theorem scanTrace (input output saved : List Bool) (mode : Mode) (register : Option Bool) : + (advance machine.step)^[input.length + 1] + (some (cfg (some .scan) input output saved mode register)) = + some (cfg (some (afterScan (run mode input))) [] output (input.reverse ++ saved)) := by + induction input generalizing saved mode register with + | nil => + simpa only [List.length_nil, Nat.zero_add, Function.iterate_one, + advance_some, run, List.reverse_nil, List.nil_append] using + step_scan_empty output saved mode register + | cons bit input ih => + rw [List.length_cons, Function.iterate_succ_apply] + simp only [advance_some] + rw [step_scan_cons] + simpa only [run, List.reverse_cons, List.append_assoc, List.singleton_append] using + ih (bit :: saved) (nextMode mode bit) none + +theorem restoreTrace (saved output : List Bool) (register : Option Bool) : + (advance machine.step)^[saved.length + 1] + (some (cfg (some .restore) [] output saved .clause register)) = + some (cfg none [] (saved.reverse ++ output) []) := by + change (nextAt (1 : Fin 3) instruction)^[saved.length + 1] + (some ⟨some .restore, (Mode.clause, register), tapes [] output saved⟩) = + some ⟨none, (Mode.clause, none), tapes [] (saved.reverse ++ output) []⟩ + have trace := transferAt_steps (2 : Fin 3) 1 (by decide) id false .restore none + instruction rfl (tapes [] [] []) saved output Mode.clause register + simpa only [tapesAt, update_saved, update_output, + List.map_id_fun, id_eq] using trace + +theorem drainTrace (saved output : List Bool) (register : Option Bool) : + (advance machine.step)^[saved.length + 1] + (some (cfg (some .drain) [] output saved .clause register)) = + some (cfg (some .rejectOutput) [] output []) := by + change (advance (TM2.step instruction))^[saved.length + 1] + (some ⟨some .drain, (Mode.clause, register), tapes [] output saved⟩) = + some ⟨some .rejectOutput, (Mode.clause, none), tapes [] output []⟩ + have trace := MachineDrain.drainTrace (2 : Fin 3) .drain (some .rejectOutput) + instruction rfl (tapes [] output []) saved Mode.clause register + simpa only [update_saved] using trace + +theorem step_rejectOutput (output : List Bool) : + machine.step (cfg (some .rejectOutput) [] output []) = + some (cfg none [] (rejectedWord ++ output) []) := by + change some (TM2.stepAux + (pushWord (Γ := Alphabet) (Λ := Label) (σ := State) + (1 : Fin 3) rejectedWord.reverse .halt) _ _) = _ + rw [stepAux_pushWord] + simp only [cfg, List.reverse_reverse, tapes_output, update_output, TM2.stepAux] + rfl + +private theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +theorem acceptedTrace (input : List Bool) (accepted : run .clause input = .done) : + (advance machine.step)^[2 * input.length + 2] + (some (cfg (some .scan) input [] [])) = some (cfg none [] input []) := by + have first := scanTrace input [] [] .clause none + simp only [afterScan, accepted, ↓reduceIte, List.append_nil] at first + have second := restoreTrace input.reverse [] none + simp only [List.length_reverse, List.reverse_reverse, List.append_nil] at second + have time : 2 * input.length + 2 = (input.length + 1) + (input.length + 1) := by omega + rw [time] + exact joinTrace first second + +theorem rejectedTrace (input : List Bool) (rejected : run .clause input ≠ .done) : + (advance machine.step)^[2 * input.length + 3] + (some (cfg (some .scan) input [] [])) = some (cfg none [] rejectedWord []) := by + have first := scanTrace input [] [] .clause none + simp only [afterScan, rejected, ↓reduceIte, List.append_nil] at first + have second := drainTrace input.reverse [] none + simp only [List.length_reverse] at second + have third : (advance machine.step)^[1] + (some (cfg (some .rejectOutput) [] [] [])) = some (cfg none [] rejectedWord []) := by + simpa only [Function.iterate_one, advance_some, List.append_nil] using + step_rejectOutput [] + have time : 2 * input.length + 3 = (input.length + 1) + (input.length + 1) + 1 := by omega + rw [time] + exact joinTrace (joinTrace first second) third + +theorem initList_eq (input : List Bool) : + initList machine input = cfg (some .scan) input [] [] := by + unfold initList cfg + congr 1 + funext k + fin_cases k <;> rfl + +theorem haltList_eq (output : List Bool) : + haltList machine output = cfg none [] output [] := by + unfold haltList cfg + congr 1 + funext k + fin_cases k <;> rfl + +def steps (input : List Bool) : Nat := + if run .clause input = .done then 2 * input.length + 2 else 2 * input.length + 3 + +theorem steps_le (input : List Bool) : steps input ≤ 2 * input.length + 3 := by + unfold steps + split <;> omega + +theorem totalTrace (input : List Bool) : + (advance machine.step)^[steps input] (some (initList machine input)) = + some (haltList machine (BinaryEncoding.formulaBits (BinaryLanguage.totalParsed input))) := by + rw [initList_eq, haltList_eq] + cases parsed : BinaryEncoding.decodeFormula input with + | none => + have rejected : run .clause input ≠ .done := by + intro accepted + obtain ⟨formula, encoded⟩ := (BinaryValidatorMachine.run_clause_iff input).mp accepted + have roundtrip := BinaryEncoding.decodeFormula_encoded formula + rw [← encoded, parsed] at roundtrip + cases roundtrip + simpa only [steps, rejected, ↓reduceIte, BinaryLanguage.totalParsed, parsed, + Option.getD_none, rejectedWord] using rejectedTrace input rejected + | some formula => + have encoded := BinaryParsing.decodeFormula_sound input formula parsed + have accepted := (BinaryValidatorMachine.run_clause_iff input).mpr ⟨formula, encoded⟩ + simp only [steps, accepted, ↓reduceIte, BinaryLanguage.totalParsed, parsed, + Option.getD_some] + rw [← encoded] + exact acceptedTrace input accepted + +def outputsInTime (input : List Bool) : + TM2OutputsInTime machine input + (some (BinaryEncoding.formulaBits (BinaryLanguage.totalParsed input))) + (2 * input.length + 3) where + steps := steps input + evals_in_steps := totalTrace input + steps_le_m := steps_le input + +noncomputable def computableInPolyTime : + TM2ComputableInPolyTime (id : List Bool → List Bool) BinaryEncoding.formulaBits + BinaryLanguage.totalParsed where + tm := machine + inputAlphabet := Equiv.refl Bool + outputAlphabet := Equiv.refl Bool + time := 2 * Polynomial.X + 3 + outputsFun input := by + change TM2OutputsInTime machine (input.map id) + (some ((BinaryEncoding.formulaBits (BinaryLanguage.totalParsed input)).map id)) + ((2 * Polynomial.X + 3 : Polynomial Nat).eval input.length) + simpa only [List.map_id_fun, id_eq, Polynomial.eval_add, Polynomial.eval_mul, + Polynomial.eval_X, Polynomial.eval_ofNat] using outputsInTime input + +theorem machine_finiteAlphabet (k : machine.K) : Finite (machine.Γ k) := by + change Finite Bool + infer_instance + +theorem computation_finiteAlphabet : MachineFiniteAlphabet.FiniteAlphabet computableInPolyTime.tm := + machine_finiteAlphabet + +end PerfectCompleteness.BinaryTotalInputMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryValidatorMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryValidatorMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..05705a7ae74c2a9d117c2b1b4ed67ec00b2a85ad --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/BinaryValidatorMachine.lean @@ -0,0 +1,352 @@ +import Mathlib.Tactic.DeriveFintype +import OAI.Computability.PerfectCompleteness.Machines.BinaryParsingLemmas +import OAI.Computability.UniqueGames.Machines.MachineCompositionLemmas + +namespace OAI + + +namespace PerfectCompleteness.BinaryValidatorMachine + + +open BinaryEncoding BinaryFormula + +inductive Mode + | clause + | sign (slot : Fin 3) + | name (slot : Fin 3) (last : Bool) + | digit (slot : Fin 3) + | done + | reject + deriving DecidableEq, Fintype + +def afterName (slot : Fin 3) : Mode := + if slot = 0 then .sign 1 else if slot = 1 then .sign 2 else .clause + +def nextMode : Mode → Bool → Mode + | .clause, true => .sign 0 + | .clause, false => .done + | .sign slot, _ => .name slot true + | .name slot _, true => .digit slot + | .name slot last, false => if last then afterName slot else .reject + | .digit slot, bit => .name slot bit + | .done, _ => .reject + | .reject, _ => .reject + +def run : Mode → List Bool → Mode + | mode, [] => mode + | mode, bit :: rest => run (nextMode mode bit) rest + +@[simp] theorem run_reject (input : List Bool) : run .reject input = .reject := by + induction input with + | nil => rfl + | cons bit input ih => simpa only [run, nextMode] using ih + +theorem run_done_iff (input : List Bool) : run .done input = .done ↔ input = [] := by + cases input with + | nil => simp [run] + | cons bit rest => simp [run, nextMode] + +private theorem finalDigit_true_iff (bits : List Bool) : + BinaryNameMachine.finalDigit bits (some true) = some true ↔ + BinaryNameMachine.canonical bits = true := by + cases bits with + | nil => simp [BinaryNameMachine.finalDigit, BinaryNameMachine.canonical] + | cons bit bits => + simp only [BinaryNameMachine.finalDigit, BinaryNameMachine.canonical] + have hsome : ∀ (ds : List Bool) (b : Bool), + ∃ last, BinaryNameMachine.finalDigit ds (some b) = some last := by + intro ds + induction ds with + | nil => intro b; exact ⟨b, rfl⟩ + | cons d ds ih => intro b; exact ih d + obtain ⟨last, hlast⟩ := hsome bits bit + rw [hlast] + simp + +theorem run_frame (slot : Fin 3) (bits rest : List Bool) (last : Bool) + (valid : BinaryNameMachine.finalDigit bits (some last) = some true) : + run (.name slot last) (frame bits ++ rest) = run (afterName slot) rest := by + induction bits generalizing last with + | nil => + have hlast : last = true := by simpa [BinaryNameMachine.finalDigit] using valid + subst last + simp [frame, run, nextMode] + | cons bit bits ih => + have hvalid : BinaryNameMachine.finalDigit bits (some bit) = some true := valid + simpa only [frame, List.cons_append, run, nextMode] using ih bit hvalid + +theorem run_name (slot : Fin 3) (name : Nat) (rest : List Bool) : + run (.name slot true) (nameBits name ++ rest) = run (afterName slot) rest := by + apply run_frame + exact (finalDigit_true_iff name.bits).mpr (BinaryParsing.canonical_nat_bits name) + +theorem run_literal (slot : Fin 3) (literal : Literal) (rest : List Bool) : + run (.sign slot) (literalBits literal ++ rest) = run (afterName slot) rest := by + simpa only [literalBits, List.cons_append, run, nextMode] using + run_name slot literal.name rest + +theorem run_clause (clause : Clause) (rest : List Bool) : + run (.sign 0) (clauseBits clause ++ rest) = run .clause rest := by + simp [clauseBits, List.append_assoc, run_literal, afterName] + +theorem run_clauses (clauses : List Clause) : run .clause (clausesBits clauses) = .done := by + induction clauses with + | nil => rfl + | cons clause clauses ih => + change run (.sign 0) (clauseBits clause ++ clausesBits clauses) = .done + rw [run_clause, ih] + +theorem run_formula (formula : Formula) : run .clause (formulaBits formula) = .done := + run_clauses formula.clauses + +theorem frame_inverse (slot : Fin 3) (last : Bool) (input : List Bool) + (accepted : run (.name slot last) input = .done) : + ∃ bits rest, input = frame bits ++ rest ∧ + BinaryNameMachine.finalDigit bits (some last) = some true ∧ + run (afterName slot) rest = .done := by + induction input using List.twoStepInduction generalizing last with + | nil => simp [run] at accepted + | singleton flag => + cases flag with + | false => + cases last with + | false => simp [run, nextMode] at accepted + | true => + exact ⟨[], [], rfl, rfl, by simpa [run, nextMode] using accepted⟩ + | true => simp [run, nextMode] at accepted + | cons_cons flag bit input ih _ => + cases flag with + | false => + cases last with + | false => simp [run, nextMode] at accepted + | true => + exact ⟨[], bit :: input, rfl, rfl, + by simpa [run, nextMode] using accepted⟩ + | true => + have haccepted : run (.name slot bit) input = .done := by + simpa only [run, nextMode] using accepted + obtain ⟨bits, rest, hinput, hvalid, hrest⟩ := ih bit haccepted + refine ⟨bit :: bits, rest, ?_, hvalid, hrest⟩ + simp [frame, hinput] + +theorem name_inverse (slot : Fin 3) (input : List Bool) + (accepted : run (.name slot true) input = .done) : + ∃ name rest, input = nameBits name ++ rest ∧ run (afterName slot) rest = .done := by + obtain ⟨bits, rest, hinput, hvalid, hrest⟩ := frame_inverse slot true input accepted + have hcanonical := (finalDigit_true_iff bits).mp hvalid + have hbits := (BinaryParsing.canonical_iff bits).mp hcanonical + refine ⟨bitsValue bits, rest, ?_, hrest⟩ + simpa only [nameBits, hbits] using hinput + +theorem literal_inverse (slot : Fin 3) (input : List Bool) + (accepted : run (.sign slot) input = .done) : + ∃ literal rest, input = literalBits literal ++ rest ∧ run (afterName slot) rest = .done := by + cases input with + | nil => simp [run] at accepted + | cons sign input => + have haccepted : run (.name slot true) input = .done := accepted + obtain ⟨name, rest, hinput, hrest⟩ := name_inverse slot input haccepted + refine ⟨⟨name, sign⟩, rest, ?_, hrest⟩ + simp [literalBits, hinput] + +theorem clause_inverse (input : List Bool) (accepted : run (.sign 0) input = .done) : + ∃ clause rest, input = clauseBits clause ++ rest ∧ run .clause rest = .done := by + obtain ⟨a, afterA, hA, acceptedA⟩ := literal_inverse 0 input accepted + have hacceptedA : run (.sign 1) afterA = .done := by + simpa [afterName] using acceptedA + obtain ⟨b, afterB, hB, acceptedB⟩ := literal_inverse 1 afterA hacceptedA + have hacceptedB : run (.sign 2) afterB = .done := by + simpa [afterName] using acceptedB + obtain ⟨c, rest, hC, acceptedC⟩ := literal_inverse 2 afterB hacceptedB + have hrest : run .clause rest = .done := by simpa [afterName] using acceptedC + refine ⟨#v[a, b, c], rest, ?_, hrest⟩ + simp [clauseBits, hA, hB, hC, List.append_assoc] + +private theorem clauses_inverse_aux (fuel : Nat) (input : List Bool) + (enough : input.length < fuel) (accepted : run .clause input = .done) : + ∃ clauses, input = clausesBits clauses := by + induction fuel generalizing input with + | zero => omega + | succ fuel ih => + cases input with + | nil => simp [run] at accepted + | cons flag input => + cases flag with + | false => + have hdone : run .done input = .done := accepted + have hempty := (run_done_iff input).mp hdone + subst input + exact ⟨[], rfl⟩ + | true => + have haccepted : run (.sign 0) input = .done := accepted + obtain ⟨clause, rest, hinput, hrest⟩ := clause_inverse input haccepted + have hlength := congrArg List.length hinput + simp only [List.length_append] at hlength + have henough : rest.length < fuel := by + simp only [List.length_cons] at enough + omega + obtain ⟨clauses, hclauses⟩ := ih rest henough hrest + refine ⟨clause :: clauses, ?_⟩ + simp [clausesBits, hinput, hclauses] + +theorem run_clause_iff (input : List Bool) : + run .clause input = .done ↔ ∃ formula, input = formulaBits formula := by + constructor + · intro accepted + obtain ⟨clauses, hclauses⟩ := + clauses_inverse_aux (input.length + 1) input (by omega) accepted + exact ⟨⟨clauses⟩, hclauses⟩ + · rintro ⟨formula, rfl⟩ + exact run_formula formula + +def accepts (input : List Bool) : Bool := decide (run .clause input = .done) + +theorem accepts_eq_decode (input : List Bool) : + accepts input = (decodeFormula input).isSome := by + cases parsed : decodeFormula input with + | none => + have rejected : run .clause input ≠ .done := by + intro accepted + obtain ⟨formula, encoded⟩ := (run_clause_iff input).mp accepted + have roundtrip := decodeFormula_encoded formula + rw [← encoded, parsed] at roundtrip + cases roundtrip + simp [accepts, rejected] + | some formula => + have encoded := BinaryParsing.decodeFormula_sound input formula parsed + have accepted := (run_clause_iff input).mpr ⟨formula, encoded⟩ + simp [accepts, accepted] + +open Turing +open UniqueGamesTheorem.Foundations.Complexity +open MachineComposition + +abbrev Alphabet (_ : Bool) := Bool +abbrev State := Mode × Option Bool + +def instruction : TM2.Stmt Alphabet Unit State := + .pop false (fun state head => (state.1, head)) + (.branch (fun state => state.2.isSome) + (.load (fun state => (nextMode state.1 (state.2.getD false), none)) + (.goto fun _ => ())) + (.push true (fun state => decide (state.1 = .done)) + (.load (fun _ => (.clause, none)) .halt))) + +abbrev machine : FinTM2 where + K := Bool + k₀ := false + k₁ := true + Γ := Alphabet + Λ := Unit + main := () + σ := State + initialState := (.clause, none) + m _ := instruction + +def tapes (input output : List Bool) : Bool → List Bool + | false => input + | true => output + +def cfg (label : Option Unit) (input output : List Bool) (mode : Mode) + (register : Option Bool := none) : machine.Cfg := + ⟨label, (mode, register), tapes input output⟩ + +@[simp] private theorem tapes_input (input output : List Bool) : + tapes input output false = input := rfl + +@[simp] private theorem tapes_output (input output : List Bool) : + tapes input output true = output := rfl + +private theorem update_input (input output replacement : List Bool) : + Function.update (tapes input output) false replacement = tapes replacement output := by + funext k + cases k <;> rfl + +private theorem update_output (input output replacement : List Bool) : + Function.update (tapes input output) true replacement = tapes input replacement := by + funext k + cases k <;> rfl + +theorem step_empty (mode : Mode) (output : List Bool) (register : Option Bool) : + machine.step (cfg (some ()) [] output mode register) = + some (cfg none [] (decide (mode = .done) :: output) .clause) := by + change some (TM2.stepAux instruction _ _) = _ + simp [instruction, cfg, TM2.stepAux, update_input, update_output] + rfl + +theorem step_cons (mode : Mode) (bit : Bool) (input output : List Bool) + (register : Option Bool) : + machine.step (cfg (some ()) (bit :: input) output mode register) = + some (cfg (some ()) input output (nextMode mode bit)) := by + change some (TM2.stepAux instruction _ _) = _ + simp [instruction, cfg, TM2.stepAux, update_input] + rfl + +theorem runTrace (input output : List Bool) (mode : Mode) (register : Option Bool) : + (advance machine.step)^[input.length + 1] + (some (cfg (some ()) input output mode register)) = + some (cfg none [] (decide (run mode input = .done) :: output) .clause) := by + induction input generalizing mode register with + | nil => + simpa only [List.length_nil, Nat.zero_add, Function.iterate_one, + advance_some, run] using! step_empty mode output register + | cons bit input ih => + rw [List.length_cons, Function.iterate_succ_apply] + simp only [advance_some] + rw [step_cons] + exact ih (nextMode mode bit) none + +theorem initList_eq (input : List Bool) : + initList machine input = cfg (some ()) input [] .clause := by + unfold initList cfg + congr 1 + funext k + cases k <;> rfl + +theorem haltList_eq (output : List Bool) : + haltList machine output = cfg none [] output .clause := by + unfold haltList cfg + congr 1 + funext k + cases k <;> rfl + +theorem validatorTrace (input : List Bool) : + (advance machine.step)^[input.length + 1] + (some (initList machine input)) = + some (haltList machine [(BinaryEncoding.decodeFormula input).isSome]) := by + rw [initList_eq, haltList_eq] + have h := runTrace input [] .clause none + change (advance machine.step)^[input.length + 1] + (some (cfg (some ()) input [] .clause)) = + some (cfg none [] [accepts input] .clause) at h + rw [accepts_eq_decode] at h + exact h + +def outputsInTime (input : List Bool) : + TM2OutputsInTime machine input (some [(BinaryEncoding.decodeFormula input).isSome]) + (input.length + 1) where + steps := input.length + 1 + evals_in_steps := validatorTrace input + steps_le_m := Nat.le_refl _ + +noncomputable def computableInPolyTime : + TM2ComputableInPolyTime (id : List Bool → List Bool) (id : List Bool → List Bool) + (fun input => [(BinaryEncoding.decodeFormula input).isSome]) where + tm := machine + inputAlphabet := Equiv.refl Bool + outputAlphabet := Equiv.refl Bool + time := Polynomial.X + 1 + outputsFun input := by + change TM2OutputsInTime machine (input.map id) + (some ([(BinaryEncoding.decodeFormula input).isSome].map id)) + ((Polynomial.X + 1 : Polynomial Nat).eval input.length) + simpa only [List.map_id_fun, id_eq, Polynomial.eval_add, + Polynomial.eval_X, Polynomial.eval_one] using outputsInTime input + +theorem machine_finiteAlphabet (k : machine.K) : Finite (machine.Γ k) := by + change Finite Bool + infer_instance + +end PerfectCompleteness.BinaryValidatorMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/BoundedExecution.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/BoundedExecution.lean new file mode 100644 index 0000000000000000000000000000000000000000..bb6108142537b168577b8ac4e0184b6ded05ecd6 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/BoundedExecution.lean @@ -0,0 +1,362 @@ +import OAI.Computability.UniqueGames.Machines.Runtime + +namespace OAI + +section + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.BoundedExecution + +section Transition +variable {C : Type*} + +def absorbingNext (step : C → Option C) (c : C) : C := (step c).getD c + +@[simp] theorem absorbingNext_of_none (step : C → Option C) {c : C} + (h : step c = none) : absorbingNext step c = c := by simp [absorbingNext, h] + +@[simp] theorem absorbingNext_of_some (step : C → Option C) {c d : C} + (h : step c = some d) : absorbingNext step c = d := by simp [absorbingNext, h] + +private def advance (step : C → Option C) (c : Option C) : Option C := c.bind step + +private theorem advance_iterate_none (step : C → Option C) (n : Nat) : + (advance step)^[n] none = none := Function.iterate_fixed rfl n + +theorem absorbing_of_successfulTrace (step : C → Option C) (n : Nat) (a b : C) + (h : (fun c : Option C => c.bind step)^[n] (some a) = some b) : + (absorbingNext step)^[n] a = b := by + change (advance step)^[n] (some a) = some b at h + induction n generalizing a with + | zero => exact Option.some.inj h + | succ n ih => + rw [Function.iterate_succ_apply] at h ⊢ + change (advance step)^[n] (step a) = some b at h + cases hs : step a with + | none => + rw [hs, advance_iterate_none] at h + contradiction + | some c => + rw [hs] at h + rw [absorbingNext_of_some step hs] + exact ih c h + +def executionToAbsorbing (step : C → Option C) (a : C) (T : Nat) : + StateTransition.EvalsToInTime step a (some ((absorbingNext step)^[T] a)) T := by + induction T generalizing a with + | zero => exact StateTransition.EvalsToInTime.refl step a + | succ n ih => + cases hs : step a with + | none => + have fixed : (absorbingNext step)^[n + 1] a = a := + Function.iterate_fixed (absorbingNext_of_none step hs) _ + exact { + steps := 0 + evals_in_steps := by rw [fixed]; rfl + steps_le_m := Nat.zero_le _ } + | some b => + let first : StateTransition.EvalsToInTime step a (some b) 1 := { + steps := 1 + evals_in_steps := by change step a = some b; exact hs + steps_le_m := le_rfl } + have full := StateTransition.EvalsToInTime.trans step 1 n a b + (some ((absorbingNext step)^[n] b)) first (ih b) + simpa only [Function.iterate_succ_apply, absorbingNext_of_some step hs] using full + +theorem absorbing_eq_of_execution (step : C → Option C) {a b : C} {T : Nat} + (execution : StateTransition.EvalsToInTime step a (some b) T) + (halted : step b = none) : (absorbingNext step)^[T] a = b := by + have hs : (absorbingNext step)^[execution.steps] a = b := by + apply absorbing_of_successfulTrace + exact execution.evals_in_steps + have ht : T = (T - execution.steps) + execution.steps := + (Nat.sub_add_cancel execution.steps_le_m).symm + rw [ht, Function.iterate_add_apply, hs] + exact Function.iterate_fixed (absorbingNext_of_none step halted) _ + +end Transition + +abbrev stickyNext (tm : Turing.FinTM2) : tm.Cfg → tm.Cfg := absorbingNext tm.step + +def run (tm : Turing.FinTM2) (input : List (tm.Γ tm.k₀)) (n : Nat) : tm.Cfg := + (stickyNext tm)^[n] (Turing.initList tm input) + +@[simp] theorem run_zero (tm : Turing.FinTM2) (input : List (tm.Γ tm.k₀)) : + run tm input 0 = Turing.initList tm input := rfl + +theorem run_succ (tm : Turing.FinTM2) (input : List (tm.Γ tm.k₀)) (n : Nat) : + run tm input (n + 1) = stickyNext tm (run tm input n) := by + simp only [run, Function.iterate_succ_apply'] + +theorem step_none_iff (tm : Turing.FinTM2) (c : tm.Cfg) : + tm.step c = none ↔ c.l = none := by + cases c with + | mk label state tapes => + cases label <;> simp [Turing.FinTM2.step, Turing.TM2.step] + rfl + +theorem stickyNext_live (tm : Turing.FinTM2) (c : tm.Cfg) (label : tm.Λ) + (h : c.l = some label) : + stickyNext tm c = Turing.TM2.stepAux (tm.m label) c.var c.stk := by + cases c with + | mk l state tapes => + change l = some label at h + subst l + rfl + +theorem run_eq_halt_of_outputs (tm : Turing.FinTM2) + (input : List (tm.Γ tm.k₀)) (output : List (tm.Γ tm.k₁)) (T : Nat) + (h : Turing.TM2OutputsInTime tm input (some output) T) : + run tm input T = Turing.haltList tm output := + absorbing_eq_of_execution tm.step h rfl + +def outputs_of_run_eq_halt (tm : Turing.FinTM2) + (input : List (tm.Γ tm.k₀)) (output : List (tm.Γ tm.k₁)) (T : Nat) + (h : run tm input T = Turing.haltList tm output) : + Turing.TM2OutputsInTime tm input (some output) T := by + change StateTransition.EvalsToInTime tm.step (Turing.initList tm input) + (some (Turing.haltList tm output)) T + have e : StateTransition.EvalsToInTime tm.step (Turing.initList tm input) + (some (run tm input T)) T := executionToAbsorbing tm.step _ T + rw [h] at e + exact e + +theorem outputs_iff_run_eq_halt (tm : Turing.FinTM2) + (input : List (tm.Γ tm.k₀)) (output : List (tm.Γ tm.k₁)) (T : Nat) : + Nonempty (Turing.TM2OutputsInTime tm input (some output) T) ↔ + run tm input T = Turing.haltList tm output := + ⟨fun ⟨h⟩ => run_eq_halt_of_outputs tm input output T h, + fun h => ⟨outputs_of_run_eq_halt tm input output T h⟩⟩ + +def IsStickyTrace (tm : Turing.FinTM2) (T : Nat) (tr : Fin (T + 1) → tm.Cfg) : Prop := + ∀ i : Fin T, tr i.succ = stickyNext tm (tr i.castSucc) + +def boundedTrace (tm : Turing.FinTM2) (input : List (tm.Γ tm.k₀)) (T : Nat) : + Fin (T + 1) → tm.Cfg := fun i => run tm input i.val + +theorem boundedTrace_isSticky (tm : Turing.FinTM2) + (input : List (tm.Γ tm.k₀)) (T : Nat) : IsStickyTrace tm T (boundedTrace tm input T) := by + intro i + exact run_succ tm input i.val + +theorem trace_eq_run (tm : Turing.FinTM2) (input : List (tm.Γ tm.k₀)) (T : Nat) + (tr : Fin (T + 1) → tm.Cfg) (initial : tr 0 = Turing.initList tm input) + (next : IsStickyTrace tm T tr) (i : Fin (T + 1)) : tr i = run tm input i.val := by + have h : ∀ n (hn : n ≤ T), tr ⟨n, by omega⟩ = run tm input n := by + intro n + induction n with + | zero => intro hn; exact initial + | succ n ih => + intro hn + have hnT : n < T := by omega + have hs := next ⟨n, hnT⟩ + change tr ⟨n + 1, by omega⟩ = stickyNext tm (tr ⟨n, by omega⟩) at hs + rw [run_succ, ← ih (Nat.le_of_lt hnT)] + exact hs + exact h i.val (by omega) + +theorem outputs_iff_trace (tm : Turing.FinTM2) + (input : List (tm.Γ tm.k₀)) (output : List (tm.Γ tm.k₁)) (T : Nat) : + Nonempty (Turing.TM2OutputsInTime tm input (some output) T) ↔ + ∃ tr : Fin (T + 1) → tm.Cfg, + tr 0 = Turing.initList tm input ∧ IsStickyTrace tm T tr ∧ + tr (Fin.last T) = Turing.haltList tm output := by + constructor + · rintro ⟨h⟩ + refine ⟨boundedTrace tm input T, rfl, boundedTrace_isSticky tm input T, ?_⟩ + exact run_eq_halt_of_outputs tm input output T h + · rintro ⟨tr, h0, hs, hT⟩ + apply (outputs_iff_run_eq_halt tm input output T).mpr + have he := trace_eq_run tm input T tr h0 hs (Fin.last T) + exact he.symm.trans hT + +noncomputable def stackCapacity (tm : Turing.FinTM2) + (input : List (tm.Γ tm.k₀)) (T : Nat) : Nat := + input.length + T * Runtime.programPushBound tm + +theorem run_stack_bound (tm : Turing.FinTM2) (input : List (tm.Γ tm.k₀)) + (n : Nat) (k : tm.K) : + ((run tm input n).stk k).length ≤ input.length + n * Runtime.programPushBound tm := by + have h := Runtime.executionSizeBound tm.step (fun c => (c.stk k).length) + (Runtime.programPushBound tm) (Runtime.stepStackLength tm k) + (executionToAbsorbing tm.step (Turing.initList tm input) n) + exact h.trans (Nat.add_le_add_right (Runtime.initialStackLength tm input k) _) + +theorem run_stack_le (tm : Turing.FinTM2) (input : List (tm.Γ tm.k₀)) + (T n : Nat) (hn : n ≤ T) (k : tm.K) : + ((run tm input n).stk k).length ≤ stackCapacity tm input T := + (run_stack_bound tm input n k).trans + (Nat.add_le_add_left (Nat.mul_le_mul_right (Runtime.programPushBound tm) hn) _) + +theorem statement_budget (tm : Turing.FinTM2) (input : List (tm.Γ tm.k₀)) + (T n : Nat) (hn : n < T) (label : tm.Λ) (k : tm.K) : + ((run tm input n).stk k).length + Runtime.statementPushBound (tm.m label) ≤ + stackCapacity tm input T := by + have hlen := run_stack_bound tm input n k + have hstmt := Runtime.statement_le_programPushBound tm label + have htime := Nat.mul_le_mul_right (Runtime.programPushBound tm) (show n + 1 ≤ T by omega) + rw [Nat.add_mul, Nat.one_mul] at htime + unfold stackCapacity + omega + +section Statement +variable {K : Type} {Γ : K → Type} {Λ σ : Type} [DecidableEq K] + +def StackBound (S : Nat) (tapes : ∀ k, List (Γ k)) : Prop := + ∀ k, (tapes k).length ≤ S + +def StatementSafe (S : Nat) : Turing.TM2.Stmt Γ Λ σ → σ → (∀ k, List (Γ k)) → Prop + | .push k f q, v, tapes => StackBound S tapes ∧ (tapes k).length < S ∧ + StatementSafe S q v (Function.update tapes k (f v :: tapes k)) + | .peek k f q, v, tapes => StackBound S tapes ∧ + StatementSafe S q (f v (tapes k).head?) tapes + | .pop k f q, v, tapes => StackBound S tapes ∧ + StatementSafe S q (f v (tapes k).head?) (Function.update tapes k (tapes k).tail) + | .load f q, v, tapes => StackBound S tapes ∧ StatementSafe S q (f v) tapes + | .branch f yes no, v, tapes => StackBound S tapes ∧ + (if f v then StatementSafe S yes v tapes else StatementSafe S no v tapes) + | .goto _, _, tapes => StackBound S tapes + | .halt, _, tapes => StackBound S tapes + +theorem StatementSafe.stackBound {S : Nat} {stmt : Turing.TM2.Stmt Γ Λ σ} + {state : σ} {tapes : ∀ k, List (Γ k)} (h : StatementSafe S stmt state tapes) : + StackBound S tapes := by + cases stmt <;> first | exact h.1 | exact h + +theorem StatementSafe.push_room {S : Nat} {k : K} {f : σ → Γ k} + {q : Turing.TM2.Stmt Γ Λ σ} {state : σ} {tapes : ∀ k, List (Γ k)} + (h : StatementSafe S (.push k f q) state tapes) : (tapes k).length < S := h.2.1 + +theorem StatementSafe.mono {S S' : Nat} {stmt : Turing.TM2.Stmt Γ Λ σ} + {state : σ} {tapes : ∀ k, List (Γ k)} (h : StatementSafe S stmt state tapes) + (hSS' : S ≤ S') : StatementSafe S' stmt state tapes := by + induction stmt generalizing state tapes with + | push j f q ih => + exact ⟨fun k => (h.1 k).trans hSS', lt_of_lt_of_le h.2.1 hSS', ih h.2.2⟩ + | peek j f q ih => exact ⟨fun k => (h.1 k).trans hSS', ih h.2⟩ + | pop j f q ih => exact ⟨fun k => (h.1 k).trans hSS', ih h.2⟩ + | load f q ih => exact ⟨fun k => (h.1 k).trans hSS', ih h.2⟩ + | branch f yes no ihYes ihNo => + refine ⟨fun k => (h.1 k).trans hSS', ?_⟩ + cases decision : f state with + | false => + have hs : StatementSafe S no state tapes := by simpa [decision] using h.2 + simpa [decision] using ihNo hs + | true => + have hs : StatementSafe S yes state tapes := by simpa [decision] using h.2 + simpa [decision] using ihYes hs + | goto f => exact fun k => (h k).trans hSS' + | halt => exact fun k => (h k).trans hSS' + +theorem StatementSafe.resultBound {S : Nat} {stmt : Turing.TM2.Stmt Γ Λ σ} + {state : σ} {tapes : ∀ k, List (Γ k)} (h : StatementSafe S stmt state tapes) : + StackBound S (Turing.TM2.stepAux stmt state tapes).stk := by + induction stmt generalizing state tapes with + | push j f q ih => exact ih h.2.2 + | peek j f q ih => exact ih h.2 + | pop j f q ih => exact ih h.2 + | load f q ih => exact ih h.2 + | branch f yes no ihYes ihNo => + cases decision : f state with + | false => + have hs : StatementSafe S no state tapes := by simpa [decision] using h.2 + simpa only [Turing.TM2.stepAux, decision, Bool.cond_false] using ihNo hs + | true => + have hs : StatementSafe S yes state tapes := by simpa [decision] using h.2 + simpa only [Turing.TM2.stepAux, decision, Bool.cond_true] using ihYes hs + | goto f => exact h + | halt => exact h + +omit [DecidableEq K] in +private theorem stackBound_of_budget (S : Nat) (stmt : Turing.TM2.Stmt Γ Λ σ) + (tapes : ∀ k, List (Γ k)) + (h : ∀ k, (tapes k).length + Runtime.statementPushBound stmt ≤ S) : StackBound S tapes := by + intro k + have hk := h k + omega + +theorem statementSafe_of_budget (S : Nat) (stmt : Turing.TM2.Stmt Γ Λ σ) + (state : σ) (tapes : ∀ k, List (Γ k)) + (h : ∀ k, (tapes k).length + Runtime.statementPushBound stmt ≤ S) : + StatementSafe S stmt state tapes := by + induction stmt generalizing state tapes with + | push j f q ih => + refine ⟨stackBound_of_budget S _ tapes h, ?_, ?_⟩ + · have hj := h j + simp only [Runtime.statementPushBound] at hj + omega + · apply ih + intro k + have hk := h k + have changed : ((Function.update tapes j (f state :: tapes j)) k).length ≤ + (tapes k).length + 1 := by + by_cases same : k = j + · subst k; simp + · simp [Function.update, same] + simp only [Runtime.statementPushBound] at hk + omega + | peek j f q ih => + exact ⟨stackBound_of_budget S _ tapes h, ih _ _ h⟩ + | pop j f q ih => + refine ⟨stackBound_of_budget S _ tapes h, ?_⟩ + apply ih + intro k + have hk := h k + have changed : ((Function.update tapes j (tapes j).tail) k).length ≤ + (tapes k).length := by + by_cases same : k = j + · subst k; simp + · simp [Function.update, same] + simp only [Runtime.statementPushBound] at hk + omega + | load f q ih => + exact ⟨stackBound_of_budget S _ tapes h, ih _ _ h⟩ + | branch f yes no ihYes ihNo => + refine ⟨stackBound_of_budget S _ tapes h, ?_⟩ + cases decision : f state with + | false => + simp only [Bool.false_eq_true, ↓reduceIte] + apply ihNo + intro k + have hk := h k + have hm := Nat.le_max_right (Runtime.statementPushBound yes) (Runtime.statementPushBound no) + simp only [Runtime.statementPushBound] at hk + omega + | true => + simp only [↓reduceIte] + apply ihYes + intro k + have hk := h k + have hm := Nat.le_max_left (Runtime.statementPushBound yes) (Runtime.statementPushBound no) + simp only [Runtime.statementPushBound] at hk + omega + | goto f => exact stackBound_of_budget S _ tapes h + | halt => exact stackBound_of_budget S _ tapes h + +end Statement + +theorem run_statement_safe (tm : Turing.FinTM2) (input : List (tm.Γ tm.k₀)) + (T n : Nat) (hn : n < T) (label : tm.Λ) : + StatementSafe (stackCapacity tm input T) (tm.m label) + (run tm input n).var (run tm input n).stk := + statementSafe_of_budget _ _ _ _ (statement_budget tm input T n hn label) + +theorem trace_stack_le (tm : Turing.FinTM2) (input : List (tm.Γ tm.k₀)) (T : Nat) + (tr : Fin (T + 1) → tm.Cfg) (initial : tr 0 = Turing.initList tm input) + (next : IsStickyTrace tm T tr) (i : Fin (T + 1)) (k : tm.K) : + ((tr i).stk k).length ≤ stackCapacity tm input T := by + rw [trace_eq_run tm input T tr initial next i] + exact run_stack_le tm input T i.val (by omega) k + +theorem trace_statement_safe (tm : Turing.FinTM2) (input : List (tm.Γ tm.k₀)) (T : Nat) + (tr : Fin (T + 1) → tm.Cfg) (initial : tr 0 = Turing.initList tm input) + (next : IsStickyTrace tm T tr) (i : Fin T) (label : tm.Λ) : + StatementSafe (stackCapacity tm input T) (tm.m label) + (tr i.castSucc).var (tr i.castSucc).stk := by + rw [trace_eq_run tm input T tr initial next i.castSucc] + exact run_statement_safe tm input T i.val i.isLt label + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.BoundedExecution + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/CanonicalCoarseningEncoding.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/CanonicalCoarseningEncoding.lean new file mode 100644 index 0000000000000000000000000000000000000000..5cde3a589fe28072afe174f0521a7b1c87f5fa0a --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/CanonicalCoarseningEncoding.lean @@ -0,0 +1,171 @@ +import OAI.Computability.PerfectCompleteness.Foundations.CanonicalEdgesLemmas +import OAI.Computability.PerfectCompleteness.Foundations.QuotientTableAgreementLemmas +import OAI.Computability.PerfectCompleteness.Machines.CanonicalLabelEncoding + +namespace OAI + +section + +namespace PerfectCompleteness.CanonicalCoarseningEncoding + +open MixedSupport CanonicalKeys CanonicalEdges + +noncomputable section + +universe uY uY' uZ uZ' + +variable {n : Nat} {Y : Type uY} {Y' : Type uY'} {Z : Type uZ} {Z' : Type uZ'} + +theorem fineKernel (slots : Fin n → Slot) (f : Assignment slots → Y) + (eL : Y → Y') (heL : Function.Injective eL) : + ∀ x x', f x = f x' ↔ (eL ∘ f) x = (eL ∘ f) x' := by + intro x x' + exact ⟨fun h => congrArg eL h, fun h => heL h⟩ + +theorem coarseKernel (slots : Fin n → Slot) (f : Assignment slots → Y) + (p : Y → Z) (eL : Y → Y') (eR : Z → Z') (p' : Y' → Z') + (heR : Function.Injective eR) (commutes : ∀ y, p' (eL y) = eR (p y)) : + ∀ x x', (p ∘ f) x = (p ∘ f) x' ↔ + (p' ∘ (eL ∘ f)) x = (p' ∘ (eL ∘ f)) x' := by + intro x x' + change p (f x) = p (f x') ↔ p' (eL (f x)) = p' (eL (f x')) + rw [commutes (f x), commutes (f x')] + exact ⟨fun h => congrArg eR h, fun h => heR h⟩ + +theorem key_fine (side : Side) (slots : Fin n → Slot) (f : Assignment slots → Y) + (eL : Y → Y') (heL : Function.Injective eL) : + key side slots (eL ∘ f) = key side slots f := + key_postcomp_injective side slots f eL heL + +theorem key_coarse (side : Side) (slots : Fin n → Slot) (f : Assignment slots → Y) + (p : Y → Z) (eL : Y → Y') (eR : Z → Z') (p' : Y' → Z') + (heR : Function.Injective eR) (commutes : ∀ y, p' (eL y) = eR (p y)) : + key side slots (p' ∘ (eL ∘ f)) = key side slots (p ∘ f) := + (key_kernel_invariant side slots (p ∘ f) (p' ∘ (eL ∘ f)) + (coarseKernel slots f p eL eR p' heR commutes)).symm + +def transportFine (slots : Fin n → Slot) (f : Assignment slots → Y) + (eL : Y → Y') (heL : Function.Injective eL) (P : Label slots f) : + Label slots (eL ∘ f) := + transportKernel slots f (eL ∘ f) (fineKernel slots f eL heL) P + +def transportCoarse (slots : Fin n → Slot) (f : Assignment slots → Y) + (p : Y → Z) (eL : Y → Y') (eR : Z → Z') (p' : Y' → Z') + (heR : Function.Injective eR) (commutes : ∀ y, p' (eL y) = eR (p y)) + (Q : Label slots (p ∘ f)) : Label slots (p' ∘ (eL ∘ f)) := + transportKernel slots (p ∘ f) (p' ∘ (eL ∘ f)) + (coarseKernel slots f p eL eR p' heR commutes) Q + +@[simp] theorem transportFine_val (slots : Fin n → Slot) (f : Assignment slots → Y) + (eL : Y → Y') (heL : Function.Injective eL) (P : Label slots f) : + (transportFine slots f eL heL P).val = P.val := rfl + +@[simp] theorem transportCoarse_val (slots : Fin n → Slot) (f : Assignment slots → Y) + (p : Y → Z) (eL : Y → Y') (eR : Z → Z') (p' : Y' → Z') + (heR : Function.Injective eR) (commutes : ∀ y, p' (eL y) = eR (p y)) + (Q : Label slots (p ∘ f)) : + (transportCoarse slots f p eL eR p' heR commutes Q).val = Q.val := rfl + +theorem transportFine_bijective (slots : Fin n → Slot) (f : Assignment slots → Y) + (eL : Y → Y') (heL : Function.Injective eL) : + Function.Bijective (transportFine slots f eL heL) := + transportKernel_bijective slots f (eL ∘ f) (fineKernel slots f eL heL) + +theorem restore_transportFine (slots : Fin n → Slot) (f : Assignment slots → Y) + (eL : Y → Y') (heL : Function.Injective eL) (P : Label slots f) : + restore slots (eL ∘ f) (transportFine slots f eL heL P) = eL (restore slots f P) := + restore_transportKernel slots f (eL ∘ f) (fineKernel slots f eL heL) + eL (fun _ => rfl) P + +theorem restore_transportCoarse (slots : Fin n → Slot) (f : Assignment slots → Y) + (p : Y → Z) (eL : Y → Y') (eR : Z → Z') (p' : Y' → Z') + (heR : Function.Injective eR) (commutes : ∀ y, p' (eL y) = eR (p y)) + (Q : Label slots (p ∘ f)) : + restore slots (p' ∘ (eL ∘ f)) (transportCoarse slots f p eL eR p' heR commutes Q) = + eR (restore slots (p ∘ f) Q) := + restore_transportKernel slots (p ∘ f) (p' ∘ (eL ∘ f)) + (coarseKernel slots f p eL eR p' heR commutes) eR (fun x => commutes (f x)) Q + +theorem coarsen_transport (slots : Fin n → Slot) (f : Assignment slots → Y) + (p : Y → Z) (eL : Y → Y') (eR : Z → Z') (p' : Y' → Z') + (heL : Function.Injective eL) (heR : Function.Injective eR) + (commutes : ∀ y, p' (eL y) = eR (p y)) (P : Label slots f) : + transportCoarse slots f p eL eR p' heR commutes (coarsen slots f p P) = + coarsen slots (eL ∘ f) p' (transportFine slots f eL heL P) := by + apply restore_injective slots (p' ∘ (eL ∘ f)) + calc + restore slots (p' ∘ (eL ∘ f)) + (transportCoarse slots f p eL eR p' heR commutes (coarsen slots f p P)) = + eR (restore slots (p ∘ f) (coarsen slots f p P)) := + restore_transportCoarse slots f p eL eR p' heR commutes (coarsen slots f p P) + _ = eR (p (restore slots f P)) := congrArg eR (restore_coarsen slots f p P) + _ = p' (eL (restore slots f P)) := (commutes (restore slots f P)).symm + _ = p' (restore slots (eL ∘ f) (transportFine slots f eL heL P)) := + congrArg p' (restore_transportFine slots f eL heL P).symm + _ = restore slots (p' ∘ (eL ∘ f)) + (coarsen slots (eL ∘ f) p' (transportFine slots f eL heL P)) := + (restore_coarsen slots (eL ∘ f) p' (transportFine slots f eL heL P)).symm + +theorem coarsen_val (slots : Fin n → Slot) (f : Assignment slots → Y) + (p : Y → Z) (eL : Y → Y') (eR : Z → Z') (p' : Y' → Z') + (heL : Function.Injective eL) (heR : Function.Injective eR) + (commutes : ∀ y, p' (eL y) = eR (p y)) (P : Label slots f) : + (coarsen slots f p P).val = + (coarsen slots (eL ∘ f) p' (transportFine slots f eL heL P)).val := + congrArg Subtype.val (coarsen_transport slots f p eL eR p' heL heR commutes P) + +@[simp] theorem partIndex_transportFine (slots : Fin n → Slot) (f : Assignment slots → Y) + (eL : Y → Y') (heL : Function.Injective eL) (P : Label slots f) : + CanonicalKeyEncoding.partEnum n (transportFine slots f eL heL P).val = + CanonicalKeyEncoding.partEnum n P.val := rfl + +theorem partIndex_coarsen (slots : Fin n → Slot) (f : Assignment slots → Y) + (p : Y → Z) (eL : Y → Y') (eR : Z → Z') (p' : Y' → Z') + (heL : Function.Injective eL) (heR : Function.Injective eR) + (commutes : ∀ y, p' (eL y) = eR (p y)) (P : Label slots f) : + CanonicalKeyEncoding.partEnum n (coarsen slots f p P).val = + CanonicalKeyEncoding.partEnum n + (coarsen slots (eL ∘ f) p' (transportFine slots f eL heL P)).val := + congrArg (CanonicalKeyEncoding.partEnum n) + (coarsen_val slots f p eL eR p' heL heR commutes P) + +theorem labelIndex_coarsen (side : Side) (slots : Fin n → Slot) + (f : Assignment slots → Y) (p : Y → Z) (eL : Y → Y') (eR : Z → Z') (p' : Y' → Z') + (heL : Function.Injective eL) (heR : Function.Injective eR) + (commutes : ∀ y, p' (eL y) = eR (p y)) (P : Label slots f) : + CanonicalLabelEncoding.labelIndex (key side slots (p ∘ f)) (coarsen slots f p P) = + CanonicalLabelEncoding.labelIndex (key side slots (p' ∘ (eL ∘ f))) + (coarsen slots (eL ∘ f) p' (transportFine slots f eL heL P)) := + partIndex_coarsen slots f p eL eR p' heL heR commutes P + +@[simp] theorem labelEmbedding_transportFine {q : Nat} (side : Side) + (large : CanonicalKeyEncoding.partitionWidth n ≤ q) + (slots : Fin n → Slot) (f : Assignment slots → Y) + (eL : Y → Y') (heL : Function.Injective eL) (P : Label slots f) : + CanonicalLabelEncoding.labelEmbedding (key side slots (eL ∘ f)) large + (transportFine slots f eL heL P) = + CanonicalLabelEncoding.labelEmbedding (key side slots f) large P := rfl + +theorem labelEmbedding_coarsen {q : Nat} (side : Side) + (large : CanonicalKeyEncoding.partitionWidth n ≤ q) + (slots : Fin n → Slot) (f : Assignment slots → Y) + (p : Y → Z) (eL : Y → Y') (eR : Z → Z') (p' : Y' → Z') + (heL : Function.Injective eL) (heR : Function.Injective eR) + (commutes : ∀ y, p' (eL y) = eR (p y)) (P : Label slots f) : + CanonicalLabelEncoding.labelEmbedding (key side slots (p ∘ f)) large + (coarsen slots f p P) = + CanonicalLabelEncoding.labelEmbedding (key side slots (p' ∘ (eL ∘ f))) large + (coarsen slots (eL ∘ f) p' (transportFine slots f eL heL P)) := by + apply Fin.ext + change (CanonicalKeyEncoding.partEnum n (coarsen slots f p P).val).val = + (CanonicalKeyEncoding.partEnum n + (coarsen slots (eL ∘ f) p' (transportFine slots f eL heL P)).val).val + exact congrArg (fun i : Fin (CanonicalKeyEncoding.partitionWidth n) => i.val) + (partIndex_coarsen slots f p eL eR p' heL heR commutes P) + +end +end PerfectCompleteness.CanonicalCoarseningEncoding + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/CanonicalDictionaryAppendMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/CanonicalDictionaryAppendMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..c25ebcd6e9748a834aa081e05ec6ef340fcc5228 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/CanonicalDictionaryAppendMachine.lean @@ -0,0 +1,283 @@ +import OAI.Computability.PerfectCompleteness.Machines.BinaryNameCompare + +namespace OAI + + +namespace PerfectCompleteness.CanonicalDictionaryAppendMachine + + +open Turing +open UniqueGamesTheorem.Foundations.Complexity +open MachineComposition +open UniqueGamesTheorem.Reduction.MachineTransfer + +variable {K Λ A : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool +abbrev State (A : Type) := BinaryNameCompare.State A +abbrev clean (ambient : A) : State A := BinaryNameCompare.clean ambient + +def payload (bits : List Bool) : List Bool := bits.flatMap fun bit => [true, bit] + +theorem payload_frame (bits : List Bool) : + payload bits ++ [false] = BinaryNameMachine.frame bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simpa [payload, BinaryNameMachine.frame] using congrArg (fun tail => true :: bit :: tail) ih + +def finish (destination : K) (exit : Option Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (State A) := + .load (fun state => clean state.1.1) (exitAt destination exit) + +def emitLoop (source destination : K) (again : Λ) (exit : Option Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (State A) := + .pop source (fun state head => (state.1, head)) + (.branch (fun state => state.2.isSome) + (.push destination (fun state => state.2.getD false) + (.push destination (fun _ => true) (finish destination (some again)))) + (.push destination (fun _ => false) (finish destination exit))) + +private theorem update_source (source destination : K) (distinct : source ≠ destination) + (base : K → List Bool) (input output replacement : List Bool) : + Function.update (tapesAt source destination base input output) source replacement = + tapesAt source destination base replacement output := by + funext k + by_cases hs : k = source + · subst k; simp [tapesAt, distinct] + · by_cases hd : k = destination + · subst k; simp [tapesAt, Ne.symm distinct] + · simp [tapesAt, hs, hd] + +private theorem update_destination (source destination : K) + (base : K → List Bool) (input output replacement : List Bool) : + Function.update (tapesAt source destination base input output) destination replacement = + tapesAt source destination base input replacement := by + simp [tapesAt] + +theorem emitStep_empty (source destination : K) (distinct : source ≠ destination) + (again : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLoop : program again = emitLoop source destination again exit) + (base : K → List Bool) (output : List Bool) (ambient : A) : + TM2.step program + ⟨some again, clean ambient, tapesAt source destination base [] output⟩ = + some ⟨exit, clean ambient, tapesAt source destination base [] (false :: output)⟩ := by + change some (TM2.stepAux (program again) _ _) = _ + rw [atLoop] + cases exit <;> + simp [emitLoop, finish, exitAt, TM2.stepAux, clean, BinaryNameCompare.clean, + distinct, update_source, update_destination] + +theorem emitStep_cons (source destination : K) (distinct : source ≠ destination) + (again : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLoop : program again = emitLoop source destination again exit) + (base : K → List Bool) (bit : Bool) (input output : List Bool) (ambient : A) : + TM2.step program + ⟨some again, clean ambient, tapesAt source destination base (bit :: input) output⟩ = + some ⟨some again, clean ambient, + tapesAt source destination base input (true :: bit :: output)⟩ := by + change some (TM2.stepAux (program again) _ _) = _ + rw [atLoop] + simp [emitLoop, finish, exitAt, TM2.stepAux, clean, BinaryNameCompare.clean, + distinct, update_source, update_destination] + +theorem emitTrace (source destination : K) (distinct : source ≠ destination) + (again : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLoop : program again = emitLoop source destination again exit) + (base : K → List Bool) (input output : List Bool) (ambient : A) : + (advance (TM2.step program))^[input.length + 1] + (some ⟨some again, clean ambient, tapesAt source destination base input output⟩) = + some ⟨exit, clean ambient, + tapesAt source destination base [] (false :: (payload input.reverse ++ output))⟩ := by + induction input generalizing output with + | nil => + simpa only [List.length_nil, Nat.zero_add, Function.iterate_one, advance_some, + List.reverse_nil, payload, List.flatMap_nil, List.nil_append] using + emitStep_empty source destination distinct again exit program atLoop base output ambient + | cons bit input ih => + rw [List.length_cons, Function.iterate_succ_apply] + simp only [advance_some] + rw [emitStep_cons source destination distinct again exit program atLoop, ih] + simp only [List.reverse_cons, payload, List.flatMap_append, List.flatMap_cons, + List.flatMap_nil, List.append_nil, List.append_assoc, List.cons_append, + List.nil_append] + +inductive Label + | copyOut | copyBack | save | seed | emit | restore + deriving DecidableEq + +protected abbrev Label.enumList : List Label := [.copyOut, .copyBack, .save, .seed, .emit, + .restore] + +protected theorem Label.enumList_getElem?_ctorIdx_eq (x : Label) : + Label.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem Label.enumList_nodup : Label.enumList.Nodup := by decide + +instance : Fintype Label where + elems := ⟨Label.enumList, Label.enumList_nodup⟩ + complete x := by cases x <;> decide + +def instruction (tape : Fin 5 → K) (labels : Label → Λ) (exit : Option Λ) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (State A) + | .copyOut => loopAt (tape 0) (tape 3) id false + (labels .copyOut) (some (labels .copyBack)) + | .copyBack => MachineCopy.forkLoop (tape 3) (tape 0) (tape 2) false + (labels .copyBack) (some (labels .save)) + | .save => loopAt (tape 1) (tape 4) id false + (labels .save) (some (labels .seed)) + | .seed => .push (tape 1) (fun _ => false) (.goto fun _ => labels .emit) + | .emit => emitLoop (tape 2) (tape 1) (labels .emit) (some (labels .restore)) + | .restore => loopAt (tape 4) (tape 1) id false (labels .restore) exit + +def steps (keyLength dictionaryLength : Nat) : Nat := + 3 * keyLength + 2 * dictionaryLength + 6 + +private theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +theorem appendTrace (tape : Fin 5 → K) (distinct : Function.Injective tape) + (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ l, program (labels l) = instruction tape labels exit l) + (base : K → List Bool) (bits dictionary : List Bool) + (keyWord : base (tape 0) = bits.reverse) + (dictionaryWord : base (tape 1) = dictionary) + (copyEmpty : base (tape 2) = []) (scratchEmpty : base (tape 3) = []) + (savedEmpty : base (tape 4) = []) (ambient : A) : + (advance (TM2.step program))^[steps bits.length dictionary.length] + (some ⟨some (labels .copyOut), clean ambient, base⟩) = + some ⟨exit, clean ambient, + Function.update base (tape 1) (dictionary ++ (false :: BinaryNameMachine.frame bits))⟩ := by + have hd (i j : Fin 5) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + let copyBase := Function.update base (tape 2) bits.reverse + let savedBase := tapesAt (tape 1) (tape 4) copyBase [] dictionary.reverse + let seedBase := Function.update savedBase (tape 1) [false] + let emittedBase := tapesAt (tape 2) (tape 1) seedBase [] + (false :: BinaryNameMachine.frame bits) + have copyRun : (advance (TM2.step program))^[2 * (bits.length + 1)] + (some ⟨some (labels .copyOut), clean ambient, base⟩) = + some ⟨some (labels .save), clean ambient, copyBase⟩ := by + have h := MachineCopy.copyTrace (tape 0) (tape 2) (tape 3) + (hd 0 2 (by decide)) (hd 0 3 (by decide)) (hd 2 3 (by decide)) false + (labels .copyOut) (labels .copyBack) (some (labels .save)) program + (atLabels .copyOut) (atLabels .copyBack) base scratchEmpty + (ambient, false, none) none + simpa only [keyWord, copyEmpty, List.append_nil, List.length_reverse, + clean, BinaryNameCompare.clean, copyBase] using h + have copyDictionary : copyBase (tape 1) = dictionary := by + simpa [copyBase, hd 1 2 (by decide)] using dictionaryWord + have copySaved : copyBase (tape 4) = [] := by + simpa [copyBase, hd 4 2 (by decide)] using savedEmpty + have saveRun : (advance (TM2.step program))^[dictionary.length + 1] + (some ⟨some (labels .save), clean ambient, copyBase⟩) = + some ⟨some (labels .seed), clean ambient, savedBase⟩ := by + have h := transferAt_fromTapes (Γ := Alphabet) (σ := A × Bool × Option Bool) + (tape 1) (tape 4) (hd 1 4 (by decide)) id false (labels .save) + (some (labels .seed)) program (atLabels .save) copyBase (ambient, false, none) none + change (advance (TM2.step program))^[(copyBase (tape 1)).length + 1] + (some ⟨some (labels .save), clean ambient, copyBase⟩) = + some ⟨some (labels .seed), clean ambient, tapesAt (tape 1) (tape 4) copyBase [] + ((copyBase (tape 1)).reverse.map id ++ copyBase (tape 4))⟩ at h + simpa only [copyDictionary, copySaved, List.map_id, + List.append_nil, clean, BinaryNameCompare.clean, savedBase] using h + have seedRun : (advance (TM2.step program))^[1] + (some ⟨some (labels .seed), clean ambient, savedBase⟩) = + some ⟨some (labels .emit), clean ambient, seedBase⟩ := by + simp only [Function.iterate_one, advance_some] + change some (TM2.stepAux (program (labels .seed)) _ _) = _ + rw [atLabels .seed] + simp [instruction, TM2.stepAux, savedBase, tapesAt, seedBase, hd 1 4 (by decide)] + have seedKey : seedBase (tape 2) = bits.reverse := by + simp [seedBase, savedBase, tapesAt, copyBase, hd 2 1 (by decide), hd 2 4 (by decide)] + have seedDictionary : seedBase (tape 1) = [false] := by simp [seedBase] + have emitRun : (advance (TM2.step program))^[bits.length + 1] + (some ⟨some (labels .emit), clean ambient, seedBase⟩) = + some ⟨some (labels .restore), clean ambient, emittedBase⟩ := by + have h := emitTrace (tape 2) (tape 1) (hd 2 1 (by decide)) + (labels .emit) (some (labels .restore)) program (atLabels .emit) seedBase + (seedBase (tape 2)) (seedBase (tape 1)) ambient + rw [tapesAt_self] at h + simpa only [seedKey, seedDictionary, List.length_reverse, List.reverse_reverse, + payload_frame, emittedBase] using h + have emittedSaved : emittedBase (tape 4) = dictionary.reverse := by + simp [emittedBase, seedBase, savedBase, tapesAt, + hd 4 1 (by decide), hd 4 2 (by decide)] + have emittedDictionary : emittedBase (tape 1) = + false :: BinaryNameMachine.frame bits := by simp [emittedBase] + have restored : tapesAt (tape 4) (tape 1) emittedBase [] + (dictionary ++ (false :: BinaryNameMachine.frame bits)) = + Function.update base (tape 1) (dictionary ++ (false :: BinaryNameMachine.frame bits)) := by + funext k + by_cases h1 : k = tape 1 + · subst k; simp [tapesAt] + · by_cases h2 : k = tape 2 + · subst k + simp [tapesAt, emittedBase, hd 2 1 (by decide), hd 2 4 (by decide), copyEmpty] + · by_cases h4 : k = tape 4 + · subst k + simp [tapesAt, hd 4 1 (by decide), savedEmpty] + · simp [tapesAt, emittedBase, seedBase, savedBase, copyBase, h1, h2, h4] + have restoreRun : (advance (TM2.step program))^[dictionary.length + 1] + (some ⟨some (labels .restore), clean ambient, emittedBase⟩) = + some ⟨exit, clean ambient, + Function.update base (tape 1) (dictionary ++ (false :: BinaryNameMachine.frame bits))⟩ := by + have h := transferAt_fromTapes (Γ := Alphabet) (σ := A × Bool × Option Bool) + (tape 4) (tape 1) (hd 4 1 (by decide)) id false (labels .restore) exit + program (atLabels .restore) emittedBase (ambient, false, none) none + change (advance (TM2.step program))^[(emittedBase (tape 4)).length + 1] + (some ⟨some (labels .restore), clean ambient, emittedBase⟩) = + some ⟨exit, clean ambient, tapesAt (tape 4) (tape 1) emittedBase [] + ((emittedBase (tape 4)).reverse.map id ++ emittedBase (tape 1))⟩ at h + simpa only [emittedSaved, emittedDictionary, List.length_reverse, + List.reverse_reverse, List.map_id, restored, clean, BinaryNameCompare.clean] using h + have h := joinTrace (joinTrace (joinTrace (joinTrace copyRun saveRun) seedRun) emitRun) restoreRun + have time : (((2 * (bits.length + 1) + (dictionary.length + 1)) + 1) + + (bits.length + 1)) + (dictionary.length + 1) = steps bits.length dictionary.length := by + unfold steps + omega + rw [time] at h + exact h + +def appendInTime (tape : Fin 5 → K) (distinct : Function.Injective tape) + (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ l, program (labels l) = instruction tape labels exit l) + (base : K → List Bool) (bits dictionary : List Bool) + (keyWord : base (tape 0) = bits.reverse) + (dictionaryWord : base (tape 1) = dictionary) + (copyEmpty : base (tape 2) = []) (scratchEmpty : base (tape 3) = []) + (savedEmpty : base (tape 4) = []) (ambient : A) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .copyOut), clean ambient, base⟩ + (some ⟨exit, clean ambient, + Function.update base (tape 1) (dictionary ++ (false :: BinaryNameMachine.frame bits))⟩) + (3 * bits.length + 2 * dictionary.length + 6) where + steps := steps bits.length dictionary.length + evals_in_steps := appendTrace tape distinct labels exit program atLabels base bits dictionary + keyWord dictionaryWord copyEmpty scratchEmpty savedEmpty ambient + steps_le_m := Nat.le_refl _ + +def machine : FinTM2 where + K := Fin 5 + k₀ := 0 + k₁ := 1 + Γ _ := Bool + Λ := Label + main := .copyOut + σ := State Unit + initialState := clean () + m := instruction id id none + +theorem machine_finiteAlphabet (k : machine.K) : Finite (machine.Γ k) := by + change Finite Bool + infer_instance + +end PerfectCompleteness.CanonicalDictionaryAppendMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/CanonicalDictionaryMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/CanonicalDictionaryMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..273a73e43ee5b1be4f41adb372009ab3ddd0aeb0 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/CanonicalDictionaryMachine.lean @@ -0,0 +1,319 @@ +import Mathlib.Tactic.Linarith +import OAI.Computability.PerfectCompleteness.Machines.BinaryNameSearch +import OAI.Computability.PerfectCompleteness.Machines.CanonicalDictionaryAppendMachine +import OAI.Computability.UniqueGames.Machines.MachineDrain +import OAI.Computability.UniqueGames.Machines.MachineSubroutineLemmas + +namespace OAI + + +namespace PerfectCompleteness.CanonicalDictionaryMachine + + +open Turing +open UniqueGamesTheorem.Foundations.Complexity +open MachineComposition +open UniqueGamesTheorem.Reduction.MachineTransfer + +abbrev Token := BinaryNameSearch.Token + +def updatedTokens (tokens : List Token) (bits : List Bool) : List Token := + tokens ++ [(false, bits)] + +theorem stream_append (first second : List Token) : + BinaryNameSearch.stream (first ++ second) = + BinaryNameSearch.stream first ++ BinaryNameSearch.stream second := by + induction first with + | nil => rfl + | cons token first ih => + simp only [List.cons_append, BinaryNameSearch.stream_cons, ih, List.append_assoc] + +theorem stream_updated (tokens : List Token) (bits : List Bool) : + BinaryNameSearch.stream (updatedTokens tokens bits) = + BinaryNameSearch.stream tokens ++ (false :: BinaryNameMachine.frame bits) := by + simp only [updatedTokens, stream_append, BinaryNameSearch.stream_cons, + BinaryNameSearch.stream_nil, List.append_nil, BinaryNameSearch.tokenBits] + +theorem stream_updated_length (tokens : List Token) (bits : List Bool) : + (BinaryNameSearch.stream (updatedTokens tokens bits)).length = + (BinaryNameSearch.stream tokens).length + 2 * bits.length + 2 := by + rw [stream_updated] + simp only [List.length_append, List.length_cons, BinaryNameMachine.frame_length] + omega + +theorem present (tokens : List Token) (bits : List Bool) : + bits ∈ BinaryNameSearch.payloads (updatedTokens tokens bits) := by + apply List.mem_map.mpr + exact ⟨(false, bits), by simp [updatedTokens], rfl⟩ + +theorem updated_canonical (tokens : List Token) (bits : List Bool) + (canonical : BinaryNameMachine.canonical bits = true) + (allCanonical : ∀ token ∈ tokens, BinaryNameMachine.canonical token.2 = true) : + ∀ token ∈ updatedTokens tokens bits, BinaryNameMachine.canonical token.2 = true := by + intro token mem + rcases List.mem_append.mp mem with old | new + · exact allCanonical token old + · have same : token = (false, bits) := by simpa only [List.mem_singleton] using new + simpa only [same] using canonical + +def index (tokens : List Token) (bits : List Bool) : Nat := + (BinaryNameSearch.payloads (updatedTokens tokens bits)).idxOf bits + +theorem index_le (tokens : List Token) (bits : List Bool) : index tokens bits ≤ tokens.length := by + have h := List.idxOf_lt_length_of_mem (present tokens bits) + simpa only [index, BinaryNameSearch.payloads, List.length_map, updatedTokens, + List.length_append, List.length_singleton, Nat.lt_add_one_iff] using h + +theorem suffix_length_le (tokens : List Token) (bits : List Bool) : + (BinaryNameSearch.stream (BinaryNameSearch.afterMatch tokens bits)).length ≤ + (BinaryNameSearch.stream tokens).length := by + induction tokens with + | nil => simp [BinaryNameSearch.afterMatch] + | cons token tokens ih => + simp only [BinaryNameSearch.afterMatch, BinaryNameSearch.stream_cons, List.length_append] + split <;> omega + +def steps (tokens : List Token) (bits : List Bool) : Nat := + CanonicalDictionaryAppendMachine.steps bits.length (BinaryNameSearch.stream tokens).length + + 2 * ((BinaryNameSearch.stream (updatedTokens tokens bits)).length + 1) + 1 + + BinaryNameSearch.steps (updatedTokens tokens bits) bits + + ((BinaryNameSearch.stream (BinaryNameSearch.afterMatch (updatedTokens tokens bits) bits)).length + 1) + + (index tokens bits + 2) + +theorem steps_le (tokens : List Token) (bits : List Bool) : + steps tokens bits ≤ 3 * (BinaryNameSearch.stream (updatedTokens tokens bits)).length ^ 2 + + 16 * (BinaryNameSearch.stream (updatedTokens tokens bits)).length + 12 := by + have search := BinaryNameSearch.steps_le_stream (updatedTokens tokens bits) bits + have suffix := suffix_length_le (updatedTokens tokens bits) bits + have idx := index_le tokens bits + have oldCount : tokens.length ≤ (BinaryNameSearch.stream tokens).length := by + rw [BinaryNameSearch.stream_length] + omega + have sizes := stream_updated_length tokens bits + have keyBound : bits.length ≤ (BinaryNameSearch.stream (updatedTokens tokens bits)).length := by omega + have product := Nat.mul_le_mul_right (BinaryNameSearch.stream (updatedTokens tokens bits)).length keyBound + unfold steps CanonicalDictionaryAppendMachine.steps + nlinarith + +section Program + +variable {K Λ A : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool +abbrev State (A : Type) := BinaryNameCompare.State A +abbrev clean (ambient : A) : State A := BinaryNameCompare.clean ambient + +def appendMap : Fin 5 → Fin 8 + | 0 => 0 + | 1 => 1 + | 2 => 4 + | 3 => 5 + | 4 => 2 + +def searchMap : Fin 6 → Fin 8 + | 0 => 2 + | 1 => 0 + | 2 => 3 + | 3 => 4 + | 4 => 5 + | 5 => 6 + +def appendTapes (tape : Fin 8 → K) : Fin 5 → K := fun i => tape (appendMap i) +def searchTapes (tape : Fin 8 → K) : Fin 6 → K := fun i => tape (searchMap i) + +omit [DecidableEq K] in +theorem appendTapes_injective (tape : Fin 8 → K) (distinct : Function.Injective tape) : + Function.Injective (appendTapes tape) := + distinct.comp (by decide : Function.Injective appendMap) + +omit [DecidableEq K] in +theorem searchTapes_injective (tape : Fin 8 → K) (distinct : Function.Injective tape) : + Function.Injective (searchTapes tape) := + distinct.comp (by decide : Function.Injective searchMap) + +inductive Label + | append (label : CanonicalDictionaryAppendMachine.Label) + | copyOut + | copyBack + | seed + | search (label : BinaryNameSearch.Label) + | drain + | emit + deriving DecidableEq, Fintype + +def main : Label := .append .copyOut + +def instruction (tape : Fin 8 → K) (labels : Label → Λ) (done rejected : Option Λ) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (State A) + | .append l => CanonicalDictionaryAppendMachine.instruction (appendTapes tape) + (fun l => labels (.append l)) (some (labels .copyOut)) l + | .copyOut => loopAt (tape 1) (tape 5) id false (labels .copyOut) (some (labels .copyBack)) + | .copyBack => MachineCopy.forkLoop (tape 5) (tape 1) (tape 2) false + (labels .copyBack) (some (labels .seed)) + | .seed => .push (tape 6) (fun _ => false) (.goto fun _ => labels (.search .sign)) + | .search l => BinaryNameSearch.instruction (searchTapes tape) + (fun l => labels (.search l)) (some (labels .drain)) rejected rejected l + | .drain => MachineDrain.drain (tape 2) (labels .drain) (some (labels .emit)) + | .emit => loopAt (tape 6) (tape 7) id false (labels .emit) done + +private theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +theorem dictionaryTrace (tape : Fin 8 → K) (distinct : Function.Injective tape) + (labels : Label → Λ) (done rejected : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ l, program (labels l) = instruction tape labels done rejected l) + (base : K → List Bool) (ambient : A) (tokens : List Token) (bits : List Bool) + (canonical : BinaryNameMachine.canonical bits = true) + (allCanonical : ∀ token ∈ tokens, BinaryNameMachine.canonical token.2 = true) + (keyWord : base (tape 0) = bits.reverse) + (dictionaryWord : base (tape 1) = BinaryNameSearch.stream tokens) + (empty : ∀ i : Fin 8, 2 ≤ i.val → i.val ≤ 6 → base (tape i) = []) : + (advance (TM2.step program))^[steps tokens bits] + (some ⟨some (labels main), clean ambient, base⟩) = + some ⟨done, clean ambient, + Function.update (Function.update base (tape 1) + (BinaryNameSearch.stream (updatedTokens tokens bits))) (tape 7) + ((encodeWord (index tokens bits)).reverse ++ base (tape 7))⟩ := by + have hd (i j : Fin 8) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + have he (i : Fin 8) (lo : 2 ≤ i.val := by decide) (hi : i.val ≤ 6 := by decide) : + base (tape i) = [] := empty i lo hi + let updated := updatedTokens tokens bits + let dictionary := BinaryNameSearch.stream updated + let tail := BinaryNameSearch.stream (BinaryNameSearch.afterMatch updated bits) + let s₁ := Function.update base (tape 1) dictionary + let s₂ := Function.update s₁ (tape 2) dictionary + let s₃ := Function.update s₂ (tape 6) [false] + let s₄ := tapesAt (tape 2) (tape 6) s₃ tail (encodeWord (index tokens bits)) + let s₅ := Function.update s₄ (tape 2) [] + let s₆ := tapesAt (tape 6) (tape 7) s₅ [] + ((encodeWord (index tokens bits)).reverse ++ s₅ (tape 7)) + have appended := CanonicalDictionaryAppendMachine.appendTrace (appendTapes tape) + (appendTapes_injective tape distinct) (fun l => labels (.append l)) + (some (labels .copyOut)) program (fun l => atLabels (.append l)) + base bits (BinaryNameSearch.stream tokens) keyWord dictionaryWord + (he 4) (he 5) (he 2) ambient + rw [← stream_updated tokens bits] at appended + change (advance (TM2.step program))^[CanonicalDictionaryAppendMachine.steps + bits.length (BinaryNameSearch.stream tokens).length] + (some ⟨some (labels main), clean ambient, base⟩) = + some ⟨some (labels .copyOut), clean ambient, s₁⟩ at appended + have s₁dictionary : s₁ (tape 1) = dictionary := by simp [s₁] + have s₁empty (i : Fin 8) (lo : 2 ≤ i.val) (hi : i.val ≤ 6) : s₁ (tape i) = [] := by + have ne : i ≠ 1 := by intro h; subst i; omega + simp [s₁, hd i 1 ne, he i lo hi] + have copied : (advance (TM2.step program))^[2 * (dictionary.length + 1)] + (some ⟨some (labels .copyOut), clean ambient, s₁⟩) = + some ⟨some (labels .seed), clean ambient, s₂⟩ := by + have h := MachineCopy.copyTrace (tape 1) (tape 2) (tape 5) + (hd 1 2 (by decide)) (hd 1 5 (by decide)) (hd 2 5 (by decide)) false + (labels .copyOut) (labels .copyBack) (some (labels .seed)) program + (atLabels .copyOut) (atLabels .copyBack) s₁ (s₁empty 5 (by decide) (by decide)) + (ambient, false, none) none + simpa only [s₁dictionary, s₁empty 2 (by decide) (by decide), List.append_nil, + clean, BinaryNameCompare.clean, s₂] using h + have s₂counter : s₂ (tape 6) = [] := by + simp [s₂, hd 6 2 (by decide), s₁empty 6 (by decide) (by decide)] + have seeded : (advance (TM2.step program))^[1] + (some ⟨some (labels .seed), clean ambient, s₂⟩) = + some ⟨some (labels (.search .sign)), clean ambient, s₃⟩ := by + change some (TM2.stepAux (program (labels .seed)) _ _) = _ + rw [atLabels .seed] + simp [instruction, TM2.stepAux, s₂counter, s₃] + have s₃key : s₃ (tape 0) = bits.reverse := by + simpa [s₃, s₂, s₁, hd 0 6 (by decide), hd 0 2 (by decide), hd 0 1 (by decide)] using keyWord + have s₃stream : s₃ (tape 2) = dictionary := by simp [s₃, s₂, hd 2 6 (by decide)] + have s₃counter : s₃ (tape 6) = [false] := by simp [s₃] + have s₃empty (i : Fin 8) (hi : i = 3 ∨ i = 4 ∨ i = 5) : s₃ (tape i) = [] := by + rcases hi with rfl | rfl | rfl <;> simp [s₃, s₂, s₁, hd, he] + have searched : (advance (TM2.step program))^[BinaryNameSearch.steps updated bits] + (some ⟨some (labels (.search .sign)), clean ambient, s₃⟩) = + some ⟨some (labels .drain), clean ambient, s₄⟩ := by + have h := BinaryNameSearch.searchTrace (searchTapes tape) (searchTapes_injective tape distinct) + (fun l => labels (.search l)) (some (labels .drain)) rejected rejected program + (fun l => atLabels (.search l)) s₃ ambient updated bits [] [false] + (updated_canonical tokens bits canonical allCanonical) (present tokens bits) s₃key + (s₃empty 3 (by simp)) (s₃empty 4 (by simp)) (s₃empty 5 (by simp)) + have initial : tapesAt (tape 2) (tape 6) s₃ dictionary [false] = s₃ := by + rw [← s₃stream, ← s₃counter] + exact tapesAt_self _ _ _ + change (advance (TM2.step program))^[BinaryNameSearch.steps updated bits] + (some ⟨some (labels (.search .sign)), clean ambient, + tapesAt (tape 2) (tape 6) s₃ (dictionary ++ []) [false]⟩) = + some ⟨some (labels .drain), clean ambient, + tapesAt (tape 2) (tape 6) s₃ (tail ++ []) (encodeWord (index tokens bits))⟩ at h + simpa only [List.append_nil, initial, s₄] using h + have s₄stream : s₄ (tape 2) = tail := by simp [s₄, hd 2 6 (by decide)] + have drained : (advance (TM2.step program))^[tail.length + 1] + (some ⟨some (labels .drain), clean ambient, s₄⟩) = + some ⟨some (labels .emit), clean ambient, s₅⟩ := by + have h := MachineDrain.drainTrace (tape 2) (labels .drain) (some (labels .emit)) program + (atLabels .drain) s₄ tail (ambient, false, none) none + have initial : Function.update s₄ (tape 2) tail = s₄ := by + rw [← s₄stream] + exact Function.update_eq_self _ _ + simpa only [initial, clean, BinaryNameCompare.clean, s₅] using h + have s₅counter : s₅ (tape 6) = encodeWord (index tokens bits) := by + simp [s₅, s₄, hd 6 2 (by decide)] + have emitted : (advance (TM2.step program))^[index tokens bits + 2] + (some ⟨some (labels .emit), clean ambient, s₅⟩) = + some ⟨done, clean ambient, s₆⟩ := by + have h := transferAt_fromTapes (Γ := Alphabet) (σ := A × Bool × Option Bool) + (tape 6) (tape 7) (hd 6 7 (by decide)) id false (labels .emit) done program + (atLabels .emit) s₅ (ambient, false, none) none + change (advance (TM2.step program))^[(s₅ (tape 6)).length + 1] + (some ⟨some (labels .emit), clean ambient, s₅⟩) = + some ⟨done, clean ambient, tapesAt (tape 6) (tape 7) s₅ [] + ((s₅ (tape 6)).reverse.map id ++ s₅ (tape 7))⟩ at h + simpa only [s₅counter, encodeWord_length, List.map_id_fun, id_eq, Nat.add_assoc, + clean, BinaryNameCompare.clean, s₆] using h + have restored : s₆ = Function.update (Function.update base (tape 1) dictionary) (tape 7) + ((encodeWord (index tokens bits)).reverse ++ base (tape 7)) := by + funext k + by_cases h7 : k = tape 7 + · subst k + simp [s₆, s₅, s₄, s₃, s₂, s₁, tapesAt, hd] + · by_cases h1 : k = tape 1 + · subst k + simp [s₆, s₅, s₄, s₃, s₂, s₁, tapesAt, hd] + · by_cases h2 : k = tape 2 + · subst k + simp [s₆, s₅, tapesAt, hd, he 2] + · by_cases h6 : k = tape 6 + · subst k + simp [s₆, tapesAt, hd, he 6] + · simp [s₆, s₅, s₄, s₃, s₂, s₁, tapesAt, h7, h1, h2, h6, + Function.update_apply] + have full := joinTrace (joinTrace (joinTrace (joinTrace + (joinTrace appended copied) seeded) searched) drained) emitted + simpa only [steps, dictionary, updated, tail, restored] using full + +def dictionaryInTime (tape : Fin 8 → K) (distinct : Function.Injective tape) + (labels : Label → Λ) (done rejected : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ l, program (labels l) = instruction tape labels done rejected l) + (base : K → List Bool) (ambient : A) (tokens : List Token) (bits : List Bool) + (canonical : BinaryNameMachine.canonical bits = true) + (allCanonical : ∀ token ∈ tokens, BinaryNameMachine.canonical token.2 = true) + (keyWord : base (tape 0) = bits.reverse) + (dictionaryWord : base (tape 1) = BinaryNameSearch.stream tokens) + (empty : ∀ i : Fin 8, 2 ≤ i.val → i.val ≤ 6 → base (tape i) = []) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels main), clean ambient, base⟩ + (some ⟨done, clean ambient, + Function.update (Function.update base (tape 1) + (BinaryNameSearch.stream (updatedTokens tokens bits))) (tape 7) + ((encodeWord (index tokens bits)).reverse ++ base (tape 7))⟩) + (3 * (BinaryNameSearch.stream (updatedTokens tokens bits)).length ^ 2 + + 16 * (BinaryNameSearch.stream (updatedTokens tokens bits)).length + 12) where + steps := steps tokens bits + evals_in_steps := dictionaryTrace tape distinct labels done rejected program atLabels base ambient + tokens bits canonical allCanonical keyWord dictionaryWord empty + steps_le_m := steps_le tokens bits + +end Program + +end PerfectCompleteness.CanonicalDictionaryMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/CanonicalEndpointMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/CanonicalEndpointMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..73767df9e6694b6648bbd19bc0937c5014e2a85e --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/CanonicalEndpointMachine.lean @@ -0,0 +1,199 @@ +import OAI.Computability.PerfectCompleteness.Foundations.CanonicalDictionaryNames +import OAI.Computability.PerfectCompleteness.Machines.CanonicalKeyMachine +import OAI.Computability.UniqueGames.Machines.MachineDrain + +namespace OAI + + +namespace PerfectCompleteness.CanonicalEndpointMachine + + +open Turing UniqueGamesTheorem.Foundations.Complexity MachineComposition +open UniqueGamesTheorem.Reduction.MachineTransfer +open CanonicalKeys CanonicalKeyShape ClauseSupport +open scoped Classical + +noncomputable section + +variable {n : Nat} {K Λ A : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool +abbrev State (A : Type) := CanonicalDictionaryMachine.State A +abbrev clean (ambient : A) : State A := CanonicalDictionaryMachine.clean ambient + +inductive Label (n : Nat) + | key (label : CanonicalKeyMachine.Label n) + | reverse + | dictionary (label : CanonicalDictionaryMachine.Label) + | drainKey + deriving DecidableEq, Fintype + +def main (n : Nat) : Label n := .key (.inl ()) + +def instruction (shapes : Fin n → Shape) (modes : Fin n → SupportMode) (side : Side) + (partition : Set (Set (Fin n → ReducedValue))) + (tape : Fin n → Fin 6 → K) (forwardKey : K) (dictionary : Fin 8 → K) + (labels : Label n → Λ) (done rejected : Option Λ) : + Label n → TM2.Stmt (Alphabet (K := K)) Λ (State A) + | .key label => CanonicalKeyMachine.instruction shapes modes side partition tape forwardKey + (fun l => labels (.key l)) (some (labels .reverse)) label + | .reverse => loopAt forwardKey (dictionary 0) id false (labels .reverse) + (some (labels (.dictionary CanonicalDictionaryMachine.main))) + | .dictionary label => CanonicalDictionaryMachine.instruction dictionary + (fun l => labels (.dictionary l)) (some (labels .drainKey)) rejected label + | .drainKey => MachineDrain.drain (dictionary 0) (labels .drainKey) done + +def finalTapes (dictionary : Fin 8 → K) (base : K → List Bool) + (earlier : List (Key n)) (key : Key n) : K → List Bool := + Function.update (Function.update base (dictionary 1) + (BinaryNameSearch.stream (CanonicalVertexNames.tokens (earlier ++ [key])))) (dictionary 7) + ((encodeWord (CanonicalOnlineNames.onlineID earlier key)).reverse ++ base (dictionary 7)) + +def budget (tape : Fin n → Fin 6 → K) (base : K → List Bool) + (earlier : List (Key n)) (key : Key n) : Nat := + ((2 * CanonicalKeyMachine.sourceLength tape base + 4 * n + 2) + + ((CanonicalVertexNames.payload key).length + 1)) + + (3 * (BinaryNameSearch.stream (CanonicalVertexNames.tokens (earlier ++ [key]))).length ^ 2 + + 16 * (BinaryNameSearch.stream (CanonicalVertexNames.tokens (earlier ++ [key]))).length + 12) + + ((CanonicalVertexNames.payload key).length + 1) + +def endpointInTime (shapes : Fin n → Shape) (modes : Fin n → SupportMode) (side : Side) + (partition : Set (Set (Fin n → ReducedValue))) + (occurrences : Fin n → Nat) (variableIDs : Fin n → Fin 3 → Nat) + (tape : Fin n → Fin 6 → K) (distinct : ∀ i, Function.Injective (tape i)) + (forwardKey : K) (dictionary : Fin 8 → K) + (dictionaryDistinct : Function.Injective dictionary) + (forwardDistinct : ∀ i, forwardKey ≠ dictionary i) + (sharedScratch : ∀ i, tape i 4 = dictionary 5) + (sharedOutput : ∀ i, tape i 5 = forwardKey) + (labels : Label n → Λ) (done rejected : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ l, program (labels l) = + instruction shapes modes side partition tape forwardKey dictionary labels done rejected l) + (base : K → List Bool) (ambient : A) (earlier : List (Key n)) + (sourceWords : ∀ i field, base (KeyMetadataMachine.idTape (tape i) field) = + encodeWord (KeyMetadataMachine.fieldValue (occurrences i) (variableIDs i) field)) + (forwardEmpty : base forwardKey = []) (keyEmpty : base (dictionary 0) = []) + (dictionaryWord : base (dictionary 1) = + BinaryNameSearch.stream (CanonicalVertexNames.tokens earlier)) + (empty : ∀ i : Fin 8, 2 ≤ i.val → i.val ≤ 6 → base (dictionary i) = []) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels (main n)), clean ambient, base⟩ + (some ⟨done, clean ambient, finalTapes dictionary base earlier + (CanonicalKeyMachine.recoveredKey shapes modes side partition occurrences variableIDs)⟩) + (budget tape base earlier + (CanonicalKeyMachine.recoveredKey shapes modes side partition occurrences variableIDs)) := by + let key := CanonicalKeyMachine.recoveredKey shapes modes side partition occurrences variableIDs + let bits := CanonicalVertexNames.payload key + let s₁ := Function.update base forwardKey bits + let s₂ := Function.update base (dictionary 0) bits.reverse + let s₃ := Function.update (Function.update s₂ (dictionary 1) + (BinaryNameSearch.stream (CanonicalVertexNames.tokens (earlier ++ [key])))) (dictionary 7) + ((encodeWord (CanonicalOnlineNames.onlineID earlier key)).reverse ++ base (dictionary 7)) + have hd (i j : Fin 8) (hne : i ≠ j) : dictionary i ≠ dictionary j := + fun h => hne (dictionaryDistinct h) + have payloadEq : CanonicalKeyMachine.payload shapes modes side partition occurrences variableIDs = + bits := rfl + have keyEntry : CanonicalKeyMachine.entry (fun l => labels (.key l)) + (some (labels .reverse)) = some (labels (main n)) := rfl + have produced : StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels (main n)), clean ambient, base⟩ + (some ⟨some (labels .reverse), clean ambient, s₁⟩) + (2 * CanonicalKeyMachine.sourceLength tape base + 4 * n + 2) := by + have run := CanonicalKeyMachine.keyInTime shapes modes side partition occurrences variableIDs + tape distinct (dictionary 5) forwardKey (Ne.symm (forwardDistinct 5)) + sharedScratch sharedOutput (fun l => labels (.key l)) (some (labels .reverse)) + program (fun l => atLabels (.key l)) base sourceWords + (empty 5 (by decide) (by decide)) (ambient, false, none) + simpa only [keyEntry, payloadEq, forwardEmpty, List.append_nil, s₁, + KeyMetadataMachine.clean, clean, CanonicalDictionaryMachine.clean, BinaryNameCompare.clean] + using run + have s₁forward : s₁ forwardKey = bits := by simp [s₁] + have s₁key : s₁ (dictionary 0) = [] := by + simp [s₁, Ne.symm (forwardDistinct 0), keyEmpty] + have transferredTapes : tapesAt forwardKey (dictionary 0) s₁ [] bits.reverse = s₂ := by + funext k + by_cases h0 : k = dictionary 0 + · subst k + simp [tapesAt, s₁, s₂] + · by_cases hf : k = forwardKey + · subst k + simp [tapesAt, s₁, s₂, forwardDistinct 0, forwardEmpty] + · simp [tapesAt, s₁, s₂, h0, hf] + have transferred : StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .reverse), clean ambient, s₁⟩ + (some ⟨some (labels (.dictionary CanonicalDictionaryMachine.main)), clean ambient, s₂⟩) + (bits.length + 1) := by + have run := transferAtInTime (Γ := Alphabet) forwardKey (dictionary 0) + (forwardDistinct 0) id false (labels .reverse) + (some (labels (.dictionary CanonicalDictionaryMachine.main))) program (atLabels .reverse) + s₁ (ambient, false, none) none + simpa only [s₁forward, s₁key, List.map_id_fun, id_eq, List.append_nil, transferredTapes, + clean, CanonicalDictionaryMachine.clean, BinaryNameCompare.clean] using run + have s₂key : s₂ (dictionary 0) = bits.reverse := by simp [s₂] + have s₂dictionary : s₂ (dictionary 1) = + BinaryNameSearch.stream (CanonicalVertexNames.tokens earlier) := by + simp [s₂, hd 1 0 (by decide), dictionaryWord] + have s₂accumulator : s₂ (dictionary 7) = base (dictionary 7) := by + simp [s₂, hd 7 0 (by decide)] + have s₂empty (i : Fin 8) (lo : 2 ≤ i.val) (hi : i.val ≤ 6) : s₂ (dictionary i) = [] := by + have ne : i ≠ 0 := by intro h; subst i; omega + simp [s₂, hd i 0 ne, empty i lo hi] + have named : StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels (.dictionary CanonicalDictionaryMachine.main)), clean ambient, s₂⟩ + (some ⟨some (labels .drainKey), clean ambient, s₃⟩) + (3 * (BinaryNameSearch.stream (CanonicalVertexNames.tokens (earlier ++ [key]))).length ^ 2 + + 16 * (BinaryNameSearch.stream (CanonicalVertexNames.tokens (earlier ++ [key]))).length + 12) := by + have run := CanonicalDictionaryNames.dictionaryInTime dictionary dictionaryDistinct + (fun l => labels (.dictionary l)) (some (labels .drainKey)) rejected program + (fun l => atLabels (.dictionary l)) s₂ ambient earlier key s₂key s₂dictionary s₂empty + simpa only [s₂accumulator, s₃, clean] using run + have s₃key : s₃ (dictionary 0) = bits.reverse := by + simp [s₃, s₂, hd 0 7 (by decide), hd 0 1 (by decide)] + have restored : Function.update s₃ (dictionary 0) [] = finalTapes dictionary base earlier key := by + funext k + by_cases h0 : k = dictionary 0 + · subst k + simp [finalTapes, hd 0 7 (by decide), hd 0 1 (by decide), keyEmpty] + · simp [s₃, s₂, finalTapes, Function.update_apply, h0] + have drained : StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .drainKey), clean ambient, s₃⟩ + (some ⟨done, clean ambient, finalTapes dictionary base earlier key⟩) + (bits.length + 1) := by + have run := MachineDrain.drainInTime (dictionary 0) (labels .drainKey) done program + (atLabels .drainKey) s₃ (ambient, false, none) none + simpa only [s₃key, List.length_reverse, restored, clean, + CanonicalDictionaryMachine.clean, BinaryNameCompare.clean] using run + have first := StateTransition.EvalsToInTime.trans (TM2.step program) _ _ _ _ _ produced transferred + have second := StateTransition.EvalsToInTime.trans (TM2.step program) _ _ _ _ _ first named + have all := StateTransition.EvalsToInTime.trans (TM2.step program) _ _ _ _ _ second drained + simpa only [budget, bits, key, Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using all + +theorem finalTapes_frame (dictionary : Fin 8 → K) (base : K → List Bool) + (earlier : List (Key n)) (key : Key n) (k : K) + (notDictionary : k ≠ dictionary 1) (notAccumulator : k ≠ dictionary 7) : + finalTapes dictionary base earlier key k = base k := by + simp only [finalTapes, Function.update_of_ne notAccumulator, + Function.update_of_ne notDictionary] + +theorem finalTapes_sources (tape : Fin n → Fin 6 → K) (dictionary : Fin 8 → K) + (base : K → List Bool) (earlier : List (Key n)) (key : Key n) + (notDictionary : ∀ i field, KeyMetadataMachine.idTape (tape i) field ≠ dictionary 1) + (notAccumulator : ∀ i field, KeyMetadataMachine.idTape (tape i) field ≠ dictionary 7) + (i : Fin n) (field : Fin 4) : + finalTapes dictionary base earlier key (KeyMetadataMachine.idTape (tape i) field) = + base (KeyMetadataMachine.idTape (tape i) field) := + finalTapes_frame dictionary base earlier key _ (notDictionary i field) (notAccumulator i field) + +theorem label_finite : Finite (Label n) := inferInstance + +theorem state_finite [Finite A] : Finite (State A) := inferInstance + +omit [DecidableEq K] in +theorem workAlphabet_finite (k : K) : Finite (Alphabet k) := inferInstance + +end + +end PerfectCompleteness.CanonicalEndpointMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/CanonicalKeyMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/CanonicalKeyMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..7a3a1e237c9a9fbcf044836ee3321da1a75ff3f4 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/CanonicalKeyMachine.lean @@ -0,0 +1,346 @@ +import Mathlib.Algebra.BigOperators.Fin +import OAI.Computability.PerfectCompleteness.Machines.FiniteBlockMachineLemmas +import OAI.Computability.PerfectCompleteness.Machines.KeyMetadataMachine +import OAI.Computability.UniqueGames.Machines.MachineCompositionLemmas + +namespace OAI + + +namespace PerfectCompleteness.CanonicalKeyMachine + + +open Turing UniqueGamesTheorem.Foundations.Complexity MachineComposition +open CanonicalKeys CanonicalKeyShape ClauseSupport MixedSupport +open scoped BigOperators Classical + +noncomputable section + +variable {n : Nat} + +def actualSlots (shapes : Fin n → Shape) (occurrences : Fin n → Nat) + (variableIDs : Fin n → Fin 3 → Nat) : Fin n → Slot := + fun i => KeyMetadataMachine.actualSlot (shapes i) (occurrences i) (variableIDs i) + +def recoveredKey (shapes : Fin n → Shape) (modes : Fin n → SupportMode) (side : Side) + (partition : Set (Set (Fin n → ReducedValue))) + (occurrences : Fin n → Nat) (variableIDs : Fin n → Fin 3 → Nat) : Key n where + side := side + retained := retained (actualSlots shapes occurrences variableIDs) modes + partition := partition + +def prefixBits (side : Side) (partition : Set (Set (Fin n → ReducedValue))) : List Bool := + encodeWords (CanonicalKeyEncoding.sideWord side :: CanonicalKeyEncoding.partitionWords partition) + +def payload (shapes : Fin n → Shape) (modes : Fin n → SupportMode) (side : Side) + (partition : Set (Set (Fin n → ReducedValue))) + (occurrences : Fin n → Nat) (variableIDs : Fin n → Fin 3 → Nat) : List Bool := + CanonicalKeyEncoding.bits (recoveredKey shapes modes side partition occurrences variableIDs) ++ [true] + +private theorem metadata_words (slots : Fin n → Slot) (modes : Fin n → SupportMode) + (positions : List (Fin n)) : + KeyMetadataEncoding.metadataWords + ((positions.map (fun i => (i, recover (slots i) (modes i)))).filter + (fun entry => decide (entry.2 ≠ .dropped))) = + positions.flatMap (fun i => KeyMetadataMachine.retainedWords i (slots i) (modes i)) := by + induction positions with + | nil => rfl + | cons i positions ih => + by_cases h : recover (slots i) (modes i) = .dropped + · simp [KeyMetadataEncoding.metadataWords, KeyMetadataMachine.retainedWords, h] at ih ⊢ + exact ih + · simpa only [List.map_cons, List.filter_cons, h, ne_eq, not_false_eq_true, + decide_true, Bool.cond_true, ite_true, KeyMetadataEncoding.metadataWords_cons, + KeyMetadataMachine.retainedWords, ite_false, List.flatMap_cons] using + congrArg (KeyMetadataEncoding.entryWords (i, recover (slots i) (modes i)) ++ ·) ih + +private 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 payload_eq (shapes : Fin n → Shape) (modes : Fin n → SupportMode) (side : Side) + (partition : Set (Set (Fin n → ReducedValue))) + (occurrences : Fin n → Nat) (variableIDs : Fin n → Fin 3 → Nat) : + payload shapes modes side partition occurrences variableIDs = + prefixBits side partition ++ + (List.finRange n).flatMap (fun i => KeyMetadataMachine.retainedBits i + (KeyMetadataMachine.actualSlot (shapes i) (occurrences i) (variableIDs i)) (modes i)) ++ + [true] := by + change encodeWords + ((CanonicalKeyEncoding.sideWord side :: CanonicalKeyEncoding.partitionWords partition) ++ + KeyMetadataEncoding.metadataWords (retained (actualSlots shapes occurrences variableIDs) modes)) ++ + [true] = _ + rw [encodeWords_append] + unfold retained + rw [metadata_words, encodeWords_flatMap] + rfl + +inductive Command (n : Nat) + | terminal + | metadata (position : Fin n) + | header + deriving DecidableEq, Fintype + +def LocalLabel : Command n → Type + | .terminal => Unit + | .metadata _ => KeyMetadataMachine.Label + | .header => Unit + +instance localLabelFintype (command : Command n) : Fintype (LocalLabel command) := by + cases command <;> unfold LocalLabel <;> infer_instance + +instance localLabelDecidableEq (command : Command n) : DecidableEq (LocalLabel command) := by + cases command <;> unfold LocalLabel <;> infer_instance + +def main : (command : Command n) → LocalLabel command + | .terminal => () + | .metadata _ => .suffix + | .header => () + +def commands (n : Nat) : List (Command n) := + .terminal :: ((List.finRange n).reverse.map .metadata ++ [.header]) + +abbrev Label (n : Nat) := MachineFiniteSequence.Label LocalLabel (commands n) + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool +abbrev State (σ : Type) := KeyMetadataMachine.State σ + +def localInstruction (shapes : Fin n → Shape) (modes : Fin n → SupportMode) (side : Side) + (partition : Set (Set (Fin n → ReducedValue))) (tape : Fin n → Fin 6 → K) (output : K) : + (command : Command n) → (LocalLabel command → Λ) → Option Λ → + LocalLabel command → TM2.Stmt (Alphabet (K := K)) Λ (State σ) + | .terminal, _, exit, _ => KeyMetadataMachine.literal output [true] exit + | .metadata i, labels, exit, label => + KeyMetadataMachine.instruction i (shapes i) (modes i) (tape i) labels exit label + | .header, _, exit, _ => KeyMetadataMachine.literal output (prefixBits side partition) exit + +def entry (labels : Label n → Λ) (exit : Option Λ) : Option Λ := + MachineFiniteSequence.entry LocalLabel main (commands n) labels exit + +def instruction (shapes : Fin n → Shape) (modes : Fin n → SupportMode) (side : Side) + (partition : Set (Set (Fin n → ReducedValue))) (tape : Fin n → Fin 6 → K) (output : K) + (labels : Label n → Λ) (exit : Option Λ) : + Label n → TM2.Stmt (Alphabet (K := K)) Λ (State σ) := + MachineFiniteSequence.instruction LocalLabel main + (localInstruction shapes modes side partition tape output) (commands n) labels exit + +def commandBits (shapes : Fin n → Shape) (modes : Fin n → SupportMode) (side : Side) + (partition : Set (Set (Fin n → ReducedValue))) + (occurrences : Fin n → Nat) (variableIDs : Fin n → Fin 3 → Nat) : Command n → List Bool + | .terminal => [true] + | .metadata i => KeyMetadataMachine.retainedBits i + (KeyMetadataMachine.actualSlot (shapes i) (occurrences i) (variableIDs i)) (modes i) + | .header => prefixBits side partition + +def commandCost (shapes : Fin n → Shape) (modes : Fin n → SupportMode) + (tape : Fin n → Fin 6 → K) (base : K → List Bool) : Command n → Nat + | .terminal => 1 + | .metadata i => match KeyMetadataMachine.sourceField (shapes i) (modes i) with + | none => 1 + | some field => 2 * ((base (KeyMetadataMachine.idTape (tape i) field)).length + 1) + 2 + | .header => 1 + +def sourceLength (tape : Fin n → Fin 6 → K) (base : K → List Bool) : Nat := + ∑ i, KeyMetadataMachine.sourceLength (tape i) base + +private theorem resultOf_prepend {α : Type} (bits : α → List Bool) + (cs : List α) (out : List Bool) : + MachineFiniteSequence.resultOf (fun c acc => bits c ++ acc) cs out = + cs.reverse.flatMap bits ++ out := by + induction cs generalizing out with + | nil => rfl + | cons c cs ih => + rw [MachineFiniteSequence.resultOf, ih] + simp only [List.reverse_cons, List.flatMap_append, List.flatMap_cons, List.flatMap_nil, + List.append_nil, List.append_assoc] + +private theorem steps_constant {α Data : Type} (result : α → Data → Data) (cost : α → Nat) + (cs : List α) (data : Data) : + MachineFiniteSequence.steps result (fun c _ => cost c) cs data = (cs.map cost).sum := by + induction cs generalizing data with + | nil => rfl + | cons c cs ih => simp only [MachineFiniteSequence.steps, List.map_cons, List.sum_cons, ih] + +theorem commands_bits (shapes : Fin n → Shape) (modes : Fin n → SupportMode) (side : Side) + (partition : Set (Set (Fin n → ReducedValue))) + (occurrences : Fin n → Nat) (variableIDs : Fin n → Fin 3 → Nat) : + (commands n).reverse.flatMap (commandBits shapes modes side partition occurrences variableIDs) = + payload shapes modes side partition occurrences variableIDs := by + rw [payload_eq] + simp only [commands, List.reverse_cons, List.reverse_append, List.reverse_nil, + List.map_reverse, List.reverse_reverse, List.flatMap_append, List.flatMap_cons, + List.flatMap_nil, List.flatMap_map, commandBits, List.nil_append, List.append_nil, List.append_assoc] + +omit [DecidableEq K] in +theorem commandCost_metadata_le (shapes : Fin n → Shape) (modes : Fin n → SupportMode) + (tape : Fin n → Fin 6 → K) (base : K → List Bool) (i : Fin n) : + commandCost shapes modes tape base (.metadata i) ≤ + 2 * KeyMetadataMachine.sourceLength (tape i) base + 4 := by + cases h : KeyMetadataMachine.sourceField (shapes i) (modes i) with + | none => simp only [commandCost, h]; omega + | some field => + have hb := KeyMetadataMachine.selected_length_le (tape i) base field + simp only [commandCost, h] + omega + +private theorem commands_cost (cost : Command n → Nat) : + ((commands n).map cost).sum = cost .terminal + (∑ i, cost (.metadata i)) + cost .header := by + simp only [commands, List.map_cons, List.map_append, List.map_map, List.map_reverse, + List.sum_cons, List.sum_append, List.sum_reverse, List.map_nil, List.sum_nil, Nat.add_zero] + rw [← Fin.sum_univ_def] + simp only [Function.comp_def, Nat.add_assoc] + +omit [DecidableEq K] in +theorem commands_cost_le (shapes : Fin n → Shape) (modes : Fin n → SupportMode) + (tape : Fin n → Fin 6 → K) (base : K → List Bool) : + ((commands n).map (commandCost shapes modes tape base)).sum ≤ + 2 * sourceLength tape base + 4 * n + 2 := by + have hsum : (∑ i, commandCost shapes modes tape base (.metadata i)) ≤ + ∑ i : Fin n, (2 * KeyMetadataMachine.sourceLength (tape i) base + 4) := + Finset.sum_le_sum (fun i _ => commandCost_metadata_le shapes modes tape base i) + have htotal : (∑ i : Fin n, (2 * KeyMetadataMachine.sourceLength (tape i) base + 4)) = + 2 * sourceLength tape base + 4 * n := by + rw [Finset.sum_add_distrib, ← Finset.mul_sum] + simp only [sourceLength, Finset.sum_const, Finset.card_univ, Fintype.card_fin, + Nat.nsmul_eq_mul, Nat.mul_comm] + rw [htotal] at hsum + rw [commands_cost] + change 1 + (∑ i, commandCost shapes modes tape base (.metadata i)) + 1 ≤ _ + omega + +omit [DecidableEq K] in +private theorem source_ne_output (tape : Fin n → Fin 6 → K) + (distinct : ∀ i, Function.Injective (tape i)) (output : K) + (sharedOutput : ∀ i, tape i 5 = output) (i : Fin n) (field : Fin 4) : + KeyMetadataMachine.idTape (tape i) field ≠ output := by + intro h + have hi : KeyMetadataMachine.idIndex field = (5 : Fin 6) := + distinct i (h.trans (sharedOutput i).symm) + have hv := congrArg Fin.val hi + have hf := field.isLt + change field.val = 5 at hv + omega + +def keyInTime (shapes : Fin n → Shape) (modes : Fin n → SupportMode) (side : Side) + (partition : Set (Set (Fin n → ReducedValue))) + (occurrences : Fin n → Nat) (variableIDs : Fin n → Fin 3 → Nat) + (tape : Fin n → Fin 6 → K) (distinct : ∀ i, Function.Injective (tape i)) + (scratch output : K) (scratchOutput : scratch ≠ output) + (sharedScratch : ∀ i, tape i 4 = scratch) (sharedOutput : ∀ i, tape i 5 = output) + (labels : Label n → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ label, program (labels label) = + instruction shapes modes side partition tape output labels exit label) + (base : K → List Bool) + (sourceWords : ∀ i field, base (KeyMetadataMachine.idTape (tape i) field) = + encodeWord (KeyMetadataMachine.fieldValue (occurrences i) (variableIDs i) field)) + (scratchEmpty : base scratch = []) (ambient : σ) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨entry labels exit, KeyMetadataMachine.clean ambient, base⟩ + (some ⟨exit, KeyMetadataMachine.clean ambient, Function.update base output + (payload shapes modes side partition occurrences variableIDs ++ base output)⟩) + (2 * sourceLength tape base + 4 * n + 2) := by + let bits := commandBits shapes modes side partition occurrences variableIDs + let result : Command n → List Bool → List Bool := fun command out => bits command ++ out + let cost := commandCost shapes modes tape base + let tapes : List Bool → K → List Bool := fun out => Function.update base output out + have source_preserved (out : List Bool) (i : Fin n) (field : Fin 4) : + tapes out (KeyMetadataMachine.idTape (tape i) field) = + base (KeyMetadataMachine.idTape (tape i) field) := by + exact Function.update_of_ne (source_ne_output tape distinct output sharedOutput i field) out base + have scratch_preserved (out : List Bool) (i : Fin n) : tapes out (tape i 4) = [] := by + rw [sharedScratch i] + exact (Function.update_of_ne scratchOutput out base).trans scratchEmpty + have localTrace : ∀ command ∈ commands n, + ∀ (placed : LocalLabel command → Λ) (next : Option Λ), + (∀ l, program (placed l) = + localInstruction shapes modes side partition tape output command placed next l) → + ∀ out : List Bool, True → + (advance (TM2.step program))^[cost command] + (some ⟨some (placed (main command)), KeyMetadataMachine.clean ambient, tapes out⟩) = + some ⟨next, KeyMetadataMachine.clean ambient, tapes (result command out)⟩ := by + intro command _ placed next atPlaced out _ + cases command with + | terminal => + have h := KeyMetadataMachine.literal_step output [true] next program (placed ()) + (atPlaced ()) (tapes out) ambient + simpa only [cost, commandCost, Function.iterate_one, advance_some, main, + result, bits, commandBits, tapes, Function.update_self, Function.update_idem] using h + | header => + have h := KeyMetadataMachine.literal_step output (prefixBits side partition) next + program (placed ()) (atPlaced ()) (tapes out) ambient + simpa only [cost, commandCost, Function.iterate_one, advance_some, main, + result, bits, commandBits, tapes, Function.update_self, Function.update_idem] using h + | metadata i => + have atMetadata : ∀ l, program (placed l) = + KeyMetadataMachine.instruction i (shapes i) (modes i) (tape i) placed next l := atPlaced + cases hfield : KeyMetadataMachine.sourceField (shapes i) (modes i) with + | none => + have hbits : bits (.metadata i) = [] := by + simp only [bits, commandBits, KeyMetadataMachine.retainedBits, + KeyMetadataMachine.retainedWords_eq, hfield, encodeWords] + have h := KeyMetadataMachine.droppedTrace i (shapes i) (modes i) hfield + (tape i) placed next program atMetadata (tapes out) ambient + simpa only [cost, commandCost, hfield, main, result, hbits, List.nil_append] using h + | some field => + have hbits : bits (.metadata i) = + encodeWords (KeyMetadataMachine.prefixWords i (shapes i) (modes i)) ++ + base (KeyMetadataMachine.idTape (tape i) field) ++ + encodeWords (KeyMetadataMachine.suffixWords (shapes i) (modes i)) := by + rw [sourceWords i field] + simp [bits, commandBits, KeyMetadataMachine.retainedBits, + KeyMetadataMachine.retainedWords_eq, hfield, encodeWords, List.append_assoc] + have h := KeyMetadataMachine.selectedTrace i (shapes i) (modes i) field hfield + (tape i) (distinct i) placed next program atMetadata (tapes out) + (scratch_preserved out i) ambient + rw [source_preserved out i field, sharedOutput i] at h + simpa only [cost, commandCost, hfield, main, result, hbits, + tapes, Function.update_self, Function.update_idem] using h + have run := MachineFiniteSequence.trace LocalLabel main + (localInstruction shapes modes side partition tape output) result (fun command _ => cost command) + program (fun _ : List Bool => True) (fun _ => KeyMetadataMachine.clean ambient) tapes + (commands n) (fun _ _ _ _ => True.intro) localTrace labels exit atLabels (base output) True.intro + have finalOutput : MachineFiniteSequence.resultOf result (commands n) (base output) = + payload shapes modes side partition occurrences variableIDs ++ base output := by + rw [resultOf_prepend] + exact congrArg (· ++ base output) (commands_bits shapes modes side partition occurrences variableIDs) + refine + { steps := MachineFiniteSequence.steps result (fun command _ => cost command) (commands n) (base output) + evals_in_steps := ?_ + steps_le_m := ?_ } + · rw [finalOutput] at run + unfold MachineComposition.advance at run + simpa only [entry, tapes, Function.update_eq_self, Function.flip_def, + Option.bind_eq_bind] using run + · rw [steps_constant] + exact commands_cost_le shapes modes tape base + +theorem output_frame (output : K) (base : K → List Bool) (bits : List Bool) + (k : K) (hne : k ≠ output) : + Function.update base output (bits ++ base output) k = base k := by + simp only [Function.update_of_ne hne] + +theorem output_sources (tape : Fin n → Fin 6 → K) + (distinct : ∀ i, Function.Injective (tape i)) (output : K) + (sharedOutput : ∀ i, tape i 5 = output) (base : K → List Bool) (bits : List Bool) + (i : Fin n) (field : Fin 4) : + Function.update base output (bits ++ base output) (KeyMetadataMachine.idTape (tape i) field) = + base (KeyMetadataMachine.idTape (tape i) field) := + output_frame output base bits _ (source_ne_output tape distinct output sharedOutput i field) + +theorem output_scratch (scratch output : K) (hne : scratch ≠ output) + (base : K → List Bool) (bits : List Bool) (hempty : base scratch = []) : + Function.update base output (bits ++ base output) scratch = [] := + (output_frame output base bits scratch hne).trans hempty + +theorem label_finite : Finite (Label n) := inferInstance + +theorem state_finite [Finite σ] : Finite (State σ) := inferInstance + +end +end PerfectCompleteness.CanonicalKeyMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/CanonicalKeyShapeMachineLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/CanonicalKeyShapeMachineLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..56e6716dc9d75789e24b8696553ed763a0426c95 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/CanonicalKeyShapeMachineLemmas.lean @@ -0,0 +1,269 @@ +import Mathlib.Data.List.Basic +import OAI.Computability.PerfectCompleteness.Foundations.CanonicalEdgesLemmas +import OAI.Computability.PerfectCompleteness.Foundations.CanonicalVertexNames +import OAI.Computability.PerfectCompleteness.Machines.FiniteBlockMachineLemmas + +namespace OAI + + +namespace PerfectCompleteness.CanonicalKeyShapeMachine + +open Turing +open UniqueGamesTheorem.Foundations.Complexity +open CanonicalKeyShape CanonicalKeyEncoding CanonicalKeys + +noncomputable section + +def inputEnum (n k : Nat) : Input n k ≃ Fin (Fintype.card (Input n k)) := + Fintype.equivFin _ + +def inputBits {n k : Nat} (data : Input n k) : List Bool := + FiniteBlockMachine.word (inputEnum n k) data + +def defaultInput (n : Nat) {k : Nat} (hk : 0 < k) : Input n k := + ⟨fun _ => Shape.bit, fun _ => ⟨0, hk⟩⟩ + +def modeEnum : SupportMode ≃ Fin (Fintype.card SupportMode) := Fintype.equivFin _ + +def modeWords {n : Nat} (support : Fin n → SupportMode) : List Nat := + List.ofFn (fun i => (modeEnum (support i)).val) + +@[simp] theorem modeWords_length {n : Nat} (support : Fin n → SupportMode) : + (modeWords support).length = n := List.length_ofFn + +theorem modeWords_injective (n : Nat) : Function.Injective (modeWords (n := n)) := by + intro a b h + have hfun := List.ofFn_injective h + funext i + apply modeEnum.injective + exact Fin.ext (congrFun hfun i) + +def outputWords {n k : Nat} (data : Input n k) : List Nat := + modeWords (inputModes data) ++ partitionWords (inputPartition data) + +def outputBits {n k : Nat} (data : Input n k) : List Bool := encodeWords (outputWords data) + +@[simp] theorem outputWords_length {n k : Nat} (data : Input n k) : + (outputWords data).length = n + partitionWidth n := by + simp only [outputWords, List.length_append, modeWords_length, partitionWords_length] + +theorem outputWords_eq_iff {n k : Nat} (a b : Input n k) : + outputWords a = outputWords b ↔ + inputModes a = inputModes b ∧ inputPartition a = inputPartition b := by + constructor + · intro h + have hlen : (modeWords (inputModes a)).length = (modeWords (inputModes b)).length := by + simp only [modeWords_length] + have hp := List.append_inj h hlen + exact ⟨modeWords_injective n hp.1, partitionWords_injective n hp.2⟩ + · rintro ⟨hm, hp⟩ + simp only [outputWords, hm, hp] + +theorem outputBits_eq_iff {n k : Nat} (a b : Input n k) : + outputBits a = outputBits b ↔ + inputModes a = inputModes b ∧ inputPartition a = inputPartition b := by + constructor + · intro h + exact (outputWords_eq_iff a b).mp (encodeWords_injective h) + · intro h + exact congrArg encodeWords ((outputWords_eq_iff a b).mpr h) + +def computation (n : Nat) {k : Nat} (hk : 0 < k) : + TM2ComputableInPolyTime (inputBits (n := n) (k := k)) id outputBits := + FiniteWordMachine.computation (inputEnum n k) (defaultInput n hk) outputBits + +def machine_output {n k : Nat} (hk : 0 < k) (data : Input n k) : + TM2OutputsInTime (computation n hk).tm (inputBits data) (some (outputBits data)) 1 := by + have h := (computation n hk).outputsFun data + change TM2OutputsInTime (computation n hk).tm ((inputBits data).map id) + (some ((outputBits data).map id)) ((1 : Polynomial Nat).eval _) at h + rw [Polynomial.eval_one] at h + exact Eq.mp (congrArg₂ + (fun (i o : List Bool) => TM2OutputsInTime (computation n hk).tm i (some o) 1) + (List.map_id (inputBits data)) (List.map_id (outputBits data))) h + +def recoverKey {n k : Nat} (side : Side) (slots : Fin n → MixedSupport.Slot) + (data : Input n k) : Key n := + ⟨side, CanonicalKeyShape.retained slots (inputModes data), inputPartition data⟩ + +theorem recoverKey_input {n k : Nat} (side : Side) (slots : Fin n → MixedSupport.Slot) + (f : MixedSupport.Assignment slots → Fin k) : + recoverKey side slots (CanonicalKeyShape.input slots f) = CanonicalKeys.key side slots f := by + simp only [recoverKey, CanonicalKeys.key, inputModes_recover, inputPartition_eq] + +theorem recoverKey_of_same_output {n k : Nat} (side : Side) + (slots : Fin n → MixedSupport.Slot) (a b : Input n k) + (same : outputBits a = outputBits b) : recoverKey side slots a = recoverKey side slots b := by + obtain ⟨hm, hp⟩ := (outputBits_eq_iff a b).mp same + simp only [recoverKey, hm, hp] + +theorem workAlphabet_finite (n : Nat) {k : Nat} (hk : 0 < k) + (tape : (computation n hk).tm.K) : Finite ((computation n hk).tm.Γ tape) := by + change Finite Bool + infer_instance + +end +end PerfectCompleteness.CanonicalKeyShapeMachine + + +namespace PerfectCompleteness.CanonicalOnlineNames + +open CanonicalKeys + +section Lists + +variable {α : Type*} [BEq α] [LawfulBEq α] + +theorem firstIndex_append_current (earlier suffix : List α) (key : α) : + (earlier ++ [key]).idxOf key = (earlier ++ key :: suffix).idxOf key := by + have present : key ∈ earlier ++ [key] := by simp + have found := List.idxOf_append_of_mem (l₂ := suffix) present + simpa only [List.append_assoc, List.singleton_append] using found.symm + +theorem firstIndex_le_prefix (earlier : List α) (key : α) : + (earlier ++ [key]).idxOf key ≤ earlier.length := by + have found := List.idxOf_lt_length_of_mem (by simp : key ∈ earlier ++ [key]) + simp only [List.length_append, List.length_singleton] at found + omega + +theorem firstIndex_eq_prefix (earlier : List α) (key : α) : + (earlier ++ [key]).idxOf key = earlier.idxOf key := by + classical + by_cases present : key ∈ earlier + · exact List.idxOf_append_of_mem present + · rw [List.idxOf_append_of_notMem present, List.idxOf_of_notMem present] + simp + +end Lists + +noncomputable section + +variable {n : Nat} + +def onlineID (earlier : List (Key n)) (key : Key n) : Nat := + (BinaryNameSearch.payloads (CanonicalVertexNames.tokens (earlier ++ [key]))).idxOf + (CanonicalVertexNames.payload key) + +theorem tokens_append_current (earlier : List (Key n)) (key : Key n) : + CanonicalVertexNames.tokens (earlier ++ [key]) = + CanonicalVertexNames.tokens earlier ++ [(false, CanonicalVertexNames.payload key)] := by + simp only [CanonicalVertexNames.tokens, List.map_append, List.map_cons, List.map_nil] + +theorem current_payload_mem (earlier : List (Key n)) (key : Key n) : + CanonicalVertexNames.payload key ∈ + BinaryNameSearch.payloads (CanonicalVertexNames.tokens (earlier ++ [key])) := + CanonicalVertexNames.payload_mem _ _ (by simp) + +theorem dictionary_canonical (earlier : List (Key n)) (key : Key n) : + ∀ token ∈ CanonicalVertexNames.tokens (earlier ++ [key]), + BinaryNameMachine.canonical token.2 = true := + CanonicalVertexNames.tokens_canonical _ + +theorem onlineID_le_prefix (earlier : List (Key n)) (key : Key n) : + onlineID earlier key ≤ earlier.length := by + have bound := firstIndex_le_prefix (earlier.map CanonicalVertexNames.payload) + (CanonicalVertexNames.payload key) + simpa only [onlineID, CanonicalVertexNames.tokens_payloads, List.map_append, + List.map_cons, List.map_nil, List.length_map] using bound + +theorem onlineID_eq_global (earlier suffix : List (Key n)) (key : Key n) : + onlineID earlier key = + (BinaryNameSearch.payloads + (CanonicalVertexNames.tokens (earlier ++ key :: suffix))).idxOf + (CanonicalVertexNames.payload key) := by + simpa only [onlineID, CanonicalVertexNames.tokens_payloads, List.map_append, + List.map_cons, List.map_nil] using + firstIndex_append_current (earlier.map CanonicalVertexNames.payload) + (suffix.map CanonicalVertexNames.payload) (CanonicalVertexNames.payload key) + +theorem onlineID_eq_name_val (earlier suffix : List (Key n)) (key : Key n) : + onlineID earlier key = + (CanonicalVertexNames.name (earlier ++ key :: suffix) key (by simp)).val := + onlineID_eq_global earlier suffix key + +theorem onlineID_eq_prefix_index (earlier : List (Key n)) (key : Key n) : + onlineID earlier key = + (BinaryNameSearch.payloads (CanonicalVertexNames.tokens earlier)).idxOf + (CanonicalVertexNames.payload key) := by + simpa only [onlineID, CanonicalVertexNames.tokens_payloads, List.map_append, + List.map_cons, List.map_nil] using + firstIndex_eq_prefix (earlier.map CanonicalVertexNames.payload) + (CanonicalVertexNames.payload key) + +theorem onlineID_repeat (earlier middle : List (Key n)) (key : Key n) : + onlineID (earlier ++ key :: middle) key = onlineID earlier key := by + calc + _ = (BinaryNameSearch.payloads + (CanonicalVertexNames.tokens (earlier ++ key :: middle))).idxOf + (CanonicalVertexNames.payload key) := onlineID_eq_prefix_index _ key + _ = _ := (onlineID_eq_global earlier middle key).symm + +theorem onlineID_eq_iff_same_final (keys prefixA suffixA prefixB suffixB : List (Key n)) + (a b : Key n) + (first : keys = prefixA ++ a :: suffixA) + (second : keys = prefixB ++ b :: suffixB) : + onlineID prefixA a = onlineID prefixB b ↔ a = b := by + have presentA : a ∈ keys := by rw [first]; simp + rw [onlineID_eq_global prefixA suffixA a, onlineID_eq_global prefixB suffixB b, + ← first, ← second] + constructor + · intro same + apply CanonicalVertexNames.payload_injective n + exact (List.idxOf_inj (CanonicalVertexNames.payload_mem keys a presentA)).mp same + · intro same + subst b + rfl + +def onlineName (earlier : List (Key n)) (key : Key n) : Fin (earlier.length + 1) := + ⟨onlineID earlier key, by have := onlineID_le_prefix earlier key; omega⟩ + +@[simp] theorem onlineName_val (earlier : List (Key n)) (key : Key n) : + (onlineName earlier key).val = onlineID earlier key := rfl + +def paddedName (keys : List (Key n)) (vertices : Nat) (enough : keys.length ≤ vertices) + (key : Key n) (present : key ∈ keys) : Fin vertices := + ⟨(CanonicalVertexNames.name keys key present).val, + lt_of_lt_of_le (CanonicalVertexNames.name keys key present).isLt enough⟩ + +@[simp] theorem paddedName_val (keys : List (Key n)) (vertices : Nat) + (enough : keys.length ≤ vertices) (key : Key n) (present : key ∈ keys) : + (paddedName keys vertices enough key present).val = + (CanonicalVertexNames.name keys key present).val := rfl + +theorem paddedName_eq_iff (keys : List (Key n)) (vertices : Nat) + (enough : keys.length ≤ vertices) (a b : Key n) (ha : a ∈ keys) (hb : b ∈ keys) : + paddedName keys vertices enough a ha = paddedName keys vertices enough b hb ↔ a = b := by + constructor + · intro same + apply (CanonicalVertexNames.name_eq_iff keys a b ha hb).mp + apply Fin.ext + exact congrArg (fun value : Fin vertices => value.val) same + · intro same + subst b + rfl + +def paddedEmbedding (keys : List (Key n)) (vertices : Nat) (enough : keys.length ≤ vertices) : + {key // key ∈ keys} ↪ Fin vertices where + toFun key := paddedName keys vertices enough key.val key.property + inj' := by + intro a b same + exact Subtype.ext ((paddedName_eq_iff keys vertices enough + a.val b.val a.property b.property).mp same) + +def onlinePaddedName (earlier : List (Key n)) (key : Key n) (vertices : Nat) + (room : earlier.length < vertices) : Fin vertices := + ⟨onlineID earlier key, lt_of_le_of_lt (onlineID_le_prefix earlier key) room⟩ + +theorem onlinePaddedName_eq_final (earlier suffix : List (Key n)) (key : Key n) + (vertices : Nat) (enough : (earlier ++ key :: suffix).length ≤ vertices) : + onlinePaddedName earlier key vertices (by + simp only [List.length_append, List.length_cons] at enough + omega) = + paddedName (earlier ++ key :: suffix) vertices enough key (by simp) := by + apply Fin.ext + exact onlineID_eq_name_val earlier suffix key + +end +end PerfectCompleteness.CanonicalOnlineNames + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/CanonicalLabelEncoding.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/CanonicalLabelEncoding.lean new file mode 100644 index 0000000000000000000000000000000000000000..a9540f6a53c89976077613c0ea0191308908e498 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/CanonicalLabelEncoding.lean @@ -0,0 +1,80 @@ +import OAI.Computability.PerfectCompleteness.Foundations.KeyFiniteness +import OAI.Computability.PerfectCompleteness.Machines.FiniteBlockMachineLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.CanonicalLabelEncoding + +open CanonicalKeys CanonicalKeyEncoding +open scoped Classical + +noncomputable section + +def labelIndex {n : Nat} (key : Key n) : KeyLabel key ↪ Fin (partitionWidth n) where + toFun label := partEnum n label.val + inj' := by + intro a b h + exact Subtype.ext ((partEnum n).injective h) + +def labelEmbedding {n q : Nat} (key : Key n) (large : partitionWidth n ≤ q) : + KeyLabel key ↪ Fin q := + (labelIndex key).trans (Fin.castLEEmb large) + +@[simp] theorem labelEmbedding_val {n q : Nat} (key : Key n) + (large : partitionWidth n ≤ q) (label : KeyLabel key) : + (labelEmbedding key large label).val = (partEnum n label.val).val := rfl + +theorem labelIndex_eq_iff {n : Nat} {left right : Key n} + (a : KeyLabel left) (b : KeyLabel right) : + labelIndex left a = labelIndex right b ↔ a.val = b.val := + (partEnum n).injective.eq_iff + +def paddedMask {n q : Nat} (key : Key n) (a : Fin q) : Bool := + if h : a.val < partitionWidth n then partitionMask key.partition ⟨a.val, h⟩ else false + +theorem paddedMask_eq_true_iff {n q : Nat} (key : Key n) + (large : partitionWidth n ≤ q) (a : Fin q) : + paddedMask key a = true ↔ a ∈ Set.range (labelEmbedding key large) := by + by_cases h : a.val < partitionWidth n + · rw [paddedMask, dite_eq_left h] + change decide ((partEnum n).symm ⟨a.val, h⟩ ∈ key.partition) = true ↔ _ + rw [decide_eq_true_iff] + constructor + · intro hpart + refine ⟨⟨(partEnum n).symm ⟨a.val, h⟩, hpart⟩, ?_⟩ + apply Fin.ext + simp only [labelEmbedding_val, Equiv.apply_symm_apply] + · rintro ⟨label, heq⟩ + have hi : partEnum n label.val = (⟨a.val, h⟩ : Fin (partitionWidth n)) := by + apply Fin.ext + exact congrArg (fun x : Fin q => x.val) heq + simpa only [← hi, Equiv.symm_apply_apply] using label.property + · rw [paddedMask, dite_eq_right h] + constructor + · simp + · rintro ⟨label, heq⟩ + have hval : (partEnum n label.val).val = a.val := congrArg (fun x : Fin q => x.val) heq + exact (h (hval ▸ (partEnum n label.val).isLt)).elim + +theorem label_card_le {n : Nat} (key : Key n) [Fintype (KeyLabel key)] : + Fintype.card (KeyLabel key) ≤ partitionWidth n := by + simpa only [Fintype.card_fin] using Fintype.card_le_of_injective (labelIndex key) + (labelIndex key).injective + +theorem labelIndex_projection {n : Nat} {Y : Type*} (side : Side) + {slots projected : Fin n → MixedSupport.Slot} + (p : ∀ i, MixedSupport.Projection (slots i) (projected i)) + (f : MixedSupport.Assignment projected → Y) + (label : CanonicalKeys.Label slots (f ∘ MixedSupport.projectionMap p)) : + labelIndex (CanonicalKeys.key side slots (f ∘ MixedSupport.projectionMap p)) label = + labelIndex (CanonicalKeys.key side projected f) (CanonicalKeys.transportLabel p f label) := + rfl + +end +end PerfectCompleteness.CanonicalLabelEncoding + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/CellsMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/CellsMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..add8f4c242c092911a7da18c3dba865df26787bf --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/CellsMachine.lean @@ -0,0 +1,343 @@ +import OAI.Computability.PerfectCompleteness.Machines.InputCellsMachineLemmas +import OAI.Computability.PerfectCompleteness.Machines.PaddingCellsMachine +import OAI.Computability.PerfectCompleteness.Machines.PayloadRowsLoop + +namespace OAI + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.CellsMachine + +open Turing MachineComposition PostfixModel +open ClashMachine (State clean emitted emitted_append chain) +open PayloadCellsMachine (SymbolSpec) + + +variable {K Λ σ : Type} [DecidableEq K] {A : Nat} + +abbrev Ports (K : Type) := Fin 14 ↪ K +abbrev Alphabet (_ : K) := Bool + +def prefixMap : Fin 7 ↪ Fin 14 := ⟨![0, 2, 3, 4, 5, 6, 7], by decide⟩ +def loopMap : Fin 11 ↪ Fin 14 := ⟨![1, 8, 9, 10, 11, 7, 12, 3, 4, 13, 6], by decide⟩ +def paddingMap : Fin 4 ↪ Fin 14 := ⟨![5, 3, 4, 6], by decide⟩ + +abbrev prefixPorts (p : Ports K) := prefixMap.trans p +abbrev loopPorts (p : Ports K) := loopMap.trans p +abbrev paddingPorts (p : Ports K) := paddingMap.trans p + +def WorkEmpty (p : Ports K) (base : K → List Bool) : Prop := + ∀ j : Fin 14, 5 ≤ j.val → base (p j) = [] + +structure Ready (p : Ports K) (base : K → List Bool) (input : List Bool) (q S : Nat) : Prop where + inputWord : base (p 0) = input + boundWord : base (p 1) = encodeWord q + capacityWord : base (p 2) = encodeWord S + empty : WorkEmpty p base + +theorem workEmpty_emitted (p : Ports K) (base : K → List Bool) (tokens : List Token) + (h : WorkEmpty p base) : WorkEmpty p (emitted (p 3) (p 4) base tokens) := by + intro j hj + have h3 : j ≠ 3 := by intro h; subst j; norm_num at hj + have h4 : j ≠ 4 := by intro h; subst j; norm_num at hj + simpa [emitted, p.injective.eq_iff, h3, h4] using h j hj + +abbrev frame (p : Ports K) (base : K → List Bool) (m i c : Nat) := + PayloadRowsLoop.frame (loopPorts p) base m i c + +private theorem ext_ports (p : Ports K) {f g : K → List Bool} + (atPorts : ∀ j, f (p j) = g (p j)) + (outside : ∀ k, (∀ j, k ≠ p j) → f k = g k) : f = g := by + funext k + by_cases hk : ∃ j, p j = k + · obtain ⟨j, rfl⟩ := hk + exact atPorts j + · exact outside k (fun j h => hk ⟨j, h.symm⟩) + +theorem frame_emitted (p : Ports K) (base : K → List Bool) (m i c : Nat) (ts : List Token) : + emitted (p 3) (p 4) (frame p base m i c) ts = + frame p (emitted (p 3) (p 4) base ts) m i c := + PayloadRowsLoop.frame_emitted (loopPorts p) base m i c ts + +theorem update_emitted_capacity (p : Ports K) (base : K → List Bool) (c : Nat) (ts : List Token) : + emitted (p 3) (p 4) (Function.update base (p 6) (encodeWord c)) ts = + Function.update (emitted (p 3) (p 4) base ts) (p 6) (encodeWord c) := by + apply ext_ports p + · intro j + fin_cases j <;> simp [emitted, p.injective.eq_iff] + · intro k hk + simp [emitted, hk] + +theorem frame_seed (p : Ports K) (base : K → List Bool) (m i c : Nat) : + frame p (Function.update base (p 8) (encodeWord 0)) m i c = frame p base m i c := by + apply ext_ports p + · intro j + fin_cases j <;> simp [frame, PayloadRowsLoop.frame, loopPorts, loopMap, p.injective.eq_iff] + · intro k hk + simp [frame, PayloadRowsLoop.frame, loopPorts, loopMap, hk] + +theorem seed_ready (p : Ports K) (base : K → List Bool) (q : Nat) + (hq : base (p 1) = encodeWord q) (empty : WorkEmpty p base) : + PayloadPresenceMachine.Ready (PayloadRowsLoop.rowPorts (loopPorts p)) + (Function.update base (p 8) (encodeWord 0)) q 0 := by + have rowPort (j : Fin 9) : + PayloadRowsLoop.rowPorts (loopPorts p) j = p (![1, 8, 9, 10, 11, 7, 12, 3, 4] j) := by + fin_cases j <;> rfl + constructor + · simpa [rowPort, p.injective.eq_iff] using hq + · change Function.update base (p 8) (encodeWord 0) (p 8) = encodeWord 0 + simp + · intro j h0 h1 h7 h8 + fin_cases j <;> try contradiction + · simpa [rowPort, p.injective.eq_iff] using empty 9 (by decide) + · simpa [rowPort, p.injective.eq_iff] using empty 10 (by decide) + · simpa [rowPort, p.injective.eq_iff] using empty 11 (by decide) + · simpa [rowPort, p.injective.eq_iff] using empty 7 (by decide) + · simpa [rowPort, p.injective.eq_iff] using empty 12 (by decide) + +inductive Label (A : Nat) + | prefix (entry : CellsPrefixStage.Label A) + | copyFirst | copySecond | seed + | payload (entry : PayloadRowsLoop.Label A) + | padding | cleanup | drain + deriving DecidableEq, Fintype + +def prefixLabels (labels : Label A ↪ Λ) : CellsPrefixStage.Label A ↪ Λ := + ⟨fun l => labels (.prefix l), fun _ _ h => Label.prefix.inj (labels.injective h)⟩ + +def payloadLabels (labels : Label A ↪ Λ) : PayloadRowsLoop.Label A ↪ Λ := + ⟨fun l => labels (.payload l), fun _ _ h => Label.payload.inj (labels.injective h)⟩ + +def statement (p : Ports K) (labels : Label A ↪ Λ) (exit : Option Λ) + (prefixTable : InputCellsMachine.TruthTable A) (payload : Fin A → SymbolSpec) (blank : List Token) : + Label A → TM2.Stmt (Alphabet (K := K)) Λ (State σ) + | .prefix l => CellsPrefixStage.statement (prefixPorts p) (prefixLabels labels) + (some (labels .copyFirst)) prefixTable l + | .copyFirst => Reduction.MachineTransfer.loopAt (p 1) (p 7) id false + (labels .copyFirst) (some (labels .copySecond)) + | .copySecond => MachineCopy.forkLoop (p 7) (p 1) (p 13) false + (labels .copySecond) (some (labels .seed)) + | .seed => .push (p 8) (fun _ => false) (.goto fun _ => labels (.payload .guard)) + | .payload l => PayloadRowsLoop.statement (loopPorts p) (payloadLabels labels) + (labels .padding) payload l + | .padding => PaddingCellsMachine.statement (paddingPorts p) blank (labels .padding) + (some (labels .cleanup)) + | .cleanup => .pop (p 13) (fun s _ => s) + (.pop (p 6) (fun s _ => s) (.goto fun _ => labels .drain)) + | .drain => MachineDrain.drain (p 8) (labels .drain) exit + +def Agrees (p : Ports K) (labels : Label A ↪ Λ) (exit : Option Λ) + (prefixTable : InputCellsMachine.TruthTable A) (payload : Fin A → SymbolSpec) (blank : List Token) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) : Prop := + ∀ l, program (labels l) = statement p labels exit prefixTable payload blank l + +variable (p : Ports K) (labels : Label A ↪ Λ) (exit : Option Λ) + (prefixTable : InputCellsMachine.TruthTable A) (payload : Fin A → SymbolSpec) (blank : List Token) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (ha : Agrees p labels exit prefixTable payload blank program) + +include ha + +theorem prefixTrace (base : K → List Bool) (input : List Bool) (q S : Nat) + (hS : input.length ≤ S) (ready : Ready p base input q S) (ambient : σ) : + (advance (TM2.step program))^[2 * (S + 2) + ((A + 4) * input.length + 3)] + (some ⟨some (labels (.prefix .capacityFirst)), clean ambient, base⟩) = + some ⟨some (labels .copyFirst), clean ambient, + Function.update (emitted (p 3) (p 4) base (InputCellsMachine.streamTokens prefixTable input)) + (p 6) (encodeWord (S - input.length))⟩ := by + have h := CellsPrefixStage.trace (prefixPorts p) (prefixLabels labels) + (some (labels .copyFirst)) prefixTable program (fun l => ha (.prefix l)) base input S hS + ready.inputWord ready.capacityWord (ready.empty 5 (by decide)) + (ready.empty 6 (by decide)) (ready.empty 7 (by decide)) (ambient, false) none + have ht : InputCellsCapacity.tapes (CellsPrefixStage.capacityPorts (prefixPorts p)) base + (S - input.length) [] + ((tokenBits (InputCellsMachine.streamTokens prefixTable input)).reverse ++ base (p 3)) + (List.replicate (A * input.length) true ++ base (p 4)) = + Function.update (emitted (p 3) (p 4) base (InputCellsMachine.streamTokens prefixTable input)) + (p 6) (encodeWord (S - input.length)) := by + have capacityPort (j : Fin 4) : + CellsPrefixStage.capacityPorts (prefixPorts p) j = p (![5, 3, 4, 6] j) := by + unfold prefixPorts + rw [prefixMap.eq_1] + fin_cases j <;> rfl + have corePort (j : Fin 3) : + InputCellsCapacity.corePorts (CellsPrefixStage.capacityPorts (prefixPorts p)) j = + p (![5, 3, 4] j) := by + fin_cases j <;> rfl + apply ext_ports p + · intro j + fin_cases j <;> simp [InputCellsCapacity.tapes, InputCellsMachine.tapes, + corePort, capacityPort, emitted, p.injective.eq_iff, ready.empty 5 (by decide)] + change Function.update (_ : K → List Bool) (p 4) + (List.replicate (A * input.length) true ++ base (p 4)) (p 4) = + List.replicate (A * input.length) true ++ base (p 4) + simp + · intro k hk + simp [InputCellsCapacity.tapes, InputCellsMachine.tapes, + corePort, capacityPort, emitted, hk] + rw [show prefixPorts p 2 = p 3 from rfl, show prefixPorts p 3 = p 4 from rfl, ht] at h + exact h + +theorem preparePayloadTrace (base : K → List Bool) (q c : Nat) + (hq : base (p 1) = encodeWord q) (empty : WorkEmpty p base) (ambient : σ) : + (advance (TM2.step program))^[2 * (q + 2) + 1] + (some ⟨some (labels .copyFirst), clean ambient, + Function.update base (p 6) (encodeWord c)⟩) = + some ⟨some (labels (.payload .guard)), clean ambient, frame p base q 0 c⟩ := by + let start := Function.update base (p 6) (encodeWord c) + have hc := MachineCopy.copyTrace (p 1) (p 13) (p 7) + (p.injective.ne (by decide)) (p.injective.ne (by decide)) (p.injective.ne (by decide)) + false (labels .copyFirst) (labels .copySecond) (some (labels .seed)) program + (ha .copyFirst) (ha .copySecond) start + (by simpa [start, p.injective.eq_iff] using empty 7 (by decide)) (ambient, false) none + have hs : start (p 1) = encodeWord q := by simpa [start, p.injective.eq_iff] using hq + have he : start (p 13) = [] := by simpa [start, p.injective.eq_iff] using empty 13 (by decide) + rw [hs, he, List.append_nil, encodeWord_length] at hc + have hseed : (advance (TM2.step program))^[1] + (some ⟨some (labels .seed), clean ambient, + Function.update start (p 13) (encodeWord q)⟩) = + some ⟨some (labels (.payload .guard)), clean ambient, frame p base q 0 c⟩ := by + change some (TM2.stepAux (program (labels .seed)) _ _) = _ + rw [ha .seed] + simp only [statement, TM2.stepAux] + congr 1 + apply congrArg (fun tapes => (⟨some (labels (.payload .guard)), clean ambient, tapes⟩ : + TM2.Cfg (Alphabet (K := K)) Λ (State σ))) + apply ext_ports p + · intro j + fin_cases j <;> simp [start, frame, PayloadRowsLoop.frame, loopPorts, loopMap, + p.injective.eq_iff, empty 8 (by decide), encodeWord] + · intro k hk + simp [start, frame, PayloadRowsLoop.frame, loopPorts, loopMap, hk] + exact chain hc hseed + +theorem payloadTrace (base : K → List Bool) (q c : Nat) + (hq : base (p 1) = encodeWord q) (empty : WorkEmpty p base) (ambient : σ) : + (advance (TM2.step program))^[PayloadRowsLoop.steps payload q 0 q] + (some ⟨some (labels (.payload .guard)), clean ambient, frame p base q 0 (c + q)⟩) = + some ⟨some (labels .padding), clean ambient, + frame p (emitted (p 3) (p 4) base (PayloadRowsLoop.tokens payload q 0 q)) 0 q c⟩ := by + have h := PayloadRowsLoop.trace (loopPorts p) (payloadLabels labels) (labels .padding) + payload program (fun l => ha (.payload l)) (Function.update base (p 8) (encodeWord 0)) + q 0 q c (by omega) (seed_ready p base q hq empty) ambient + change (advance (TM2.step program))^[PayloadRowsLoop.steps payload q 0 q] + (some ⟨some (labels (.payload .guard)), clean ambient, + frame p (Function.update base (p 8) (encodeWord 0)) q 0 (c + q)⟩) = + some ⟨some (labels .padding), clean ambient, + emitted (p 3) (p 4) (frame p (Function.update base (p 8) (encodeWord 0)) 0 (0 + q) c) + (PayloadRowsLoop.tokens payload q 0 q)⟩ at h + simpa only [frame_seed, Nat.zero_add, frame_emitted] using h + +theorem paddingTrace (base : K → List Bool) (q c : Nat) (ambient : σ) : + (advance (TM2.step program))^[c + 1] + (some ⟨some (labels .padding), clean ambient, frame p base 0 q c⟩) = + some ⟨some (labels .cleanup), clean ambient, + frame p (emitted (p 3) (p 4) base (PaddingCellsMachine.repeatedRows blank c)) 0 q 0⟩ := by + have h := PaddingCellsMachine.trace (paddingPorts p) blank (labels .padding) + (some (labels .cleanup)) program (ha .padding) (frame p base 0 q c) c [] + (base (p 3)) (base (p 4)) (ambient, false) none + have hstart : PaddingCellsMachine.frame (paddingPorts p) (frame p base 0 q c) + (encodeWord c ++ []) (base (p 3)) (base (p 4)) = frame p base 0 q c := by + apply ext_ports p + · intro j + fin_cases j <;> simp [PaddingCellsMachine.frame, OrClosure.frame, + PaddingCellsMachine.corePorts, paddingPorts, paddingMap, frame, PayloadRowsLoop.frame, + loopPorts, loopMap, p.injective.eq_iff] + · intro k hk + simp [PaddingCellsMachine.frame, OrClosure.frame, PaddingCellsMachine.corePorts, + paddingPorts, paddingMap, frame, PayloadRowsLoop.frame, loopPorts, loopMap, hk] + have hend : PaddingCellsMachine.frame (paddingPorts p) (frame p base 0 q c) + (encodeWord 0 ++ []) + ((tokenBits (PaddingCellsMachine.repeatedRows blank c)).reverse ++ base (p 3)) + (List.replicate (c * blank.length) true ++ base (p 4)) = + frame p (emitted (p 3) (p 4) base (PaddingCellsMachine.repeatedRows blank c)) 0 q 0 := by + apply ext_ports p + · intro j + fin_cases j <;> simp [PaddingCellsMachine.frame, OrClosure.frame, + PaddingCellsMachine.corePorts, paddingPorts, paddingMap, frame, PayloadRowsLoop.frame, + loopPorts, loopMap, p.injective.eq_iff, emitted] + · intro k hk + simp [PaddingCellsMachine.frame, OrClosure.frame, PaddingCellsMachine.corePorts, + paddingPorts, paddingMap, frame, PayloadRowsLoop.frame, loopPorts, loopMap, emitted, hk] + simpa only [hstart, hend, clean] using h + +theorem cleanupTrace (base : K → List Bool) (q : Nat) (empty : WorkEmpty p base) (ambient : σ) : + (advance (TM2.step program))^[1 + (q + 2)] + (some ⟨some (labels .cleanup), clean ambient, frame p base 0 q 0⟩) = + some ⟨exit, clean ambient, base⟩ := by + have hc : (advance (TM2.step program))^[1] + (some ⟨some (labels .cleanup), clean ambient, frame p base 0 q 0⟩) = + some ⟨some (labels .drain), clean ambient, Function.update base (p 8) (encodeWord q)⟩ := by + change some (TM2.stepAux (program (labels .cleanup)) _ _) = _ + rw [ha .cleanup] + simp only [statement, TM2.stepAux] + congr 1 + apply congrArg (fun tapes => (⟨some (labels .drain), clean ambient, tapes⟩ : + TM2.Cfg (Alphabet (K := K)) Λ (State σ))) + apply ext_ports p + · intro j + fin_cases j <;> simp [frame, PayloadRowsLoop.frame, loopPorts, loopMap, + p.injective.eq_iff, encodeWord, empty 6 (by decide), empty 13 (by decide)] + · intro k hk + simp [frame, PayloadRowsLoop.frame, loopPorts, loopMap, hk] + have hd := MachineDrain.drainTrace (p 8) (labels .drain) exit program (ha .drain) + base (encodeWord q) (ambient, false) none + rw [encodeWord_length] at hd + have hb : Function.update base (p 8) [] = base := by + rw [← empty 8 (by decide), Function.update_eq_self] + rw [hb] at hd + exact chain hc hd + +omit ha in +def tokens (prefixTable : InputCellsMachine.TruthTable A) (payload : Fin A → SymbolSpec) + (blank : List Token) (input : List Bool) (q S : Nat) : List Token := + InputCellsMachine.streamTokens prefixTable input ++ PayloadRowsLoop.tokens payload q 0 q ++ + PaddingCellsMachine.repeatedRows blank (S - input.length - q) + +omit ha in +def steps (payload : Fin A → SymbolSpec) (inputLength q S : Nat) : Nat := + (2 * (S + 2) + ((A + 4) * inputLength + 3)) + (2 * (q + 2) + 1) + + PayloadRowsLoop.steps payload q 0 q + (S - inputLength - q + 1) + (1 + (q + 2)) + +theorem trace (base : K → List Bool) (input : List Bool) (q S : Nat) + (hS : input.length + q ≤ S) (ready : Ready p base input q S) (ambient : σ) : + (advance (TM2.step program))^[steps payload input.length q S] + (some ⟨some (labels (.prefix .capacityFirst)), clean ambient, base⟩) = + some ⟨exit, clean ambient, emitted (p 3) (p 4) base (tokens prefixTable payload blank input q S)⟩ := by + let pre := InputCellsMachine.streamTokens prefixTable input + let mid := PayloadRowsLoop.tokens payload q 0 q + let post := PaddingCellsMachine.repeatedRows blank (S - input.length - q) + let b₁ := emitted (p 3) (p 4) base pre + let b₂ := emitted (p 3) (p 4) b₁ mid + let b₃ := emitted (p 3) (p 4) b₂ post + have e₁ : WorkEmpty p b₁ := workEmpty_emitted p base pre ready.empty + have e₂ : WorkEmpty p b₂ := workEmpty_emitted p b₁ mid e₁ + have e₃ : WorkEmpty p b₃ := workEmpty_emitted p b₂ post e₂ + have q₁ : b₁ (p 1) = encodeWord q := by + simpa [b₁, emitted, p.injective.eq_iff] using ready.boundWord + have hp := prefixTrace p labels exit prefixTable payload blank program ha base input q S + (by omega) ready ambient + have hprep := preparePayloadTrace p labels exit prefixTable payload blank program ha b₁ q + (S - input.length) q₁ e₁ ambient + have hm := payloadTrace p labels exit prefixTable payload blank program ha b₁ q + (S - input.length - q) q₁ e₁ ambient + rw [show S - input.length - q + q = S - input.length by omega] at hm + have hpad := paddingTrace p labels exit prefixTable payload blank program ha b₂ q + (S - input.length - q) ambient + have hc := cleanupTrace p labels exit prefixTable payload blank program ha b₃ q e₃ ambient + have h := chain (chain (chain (chain hp hprep) hm) hpad) hc + simpa only [steps, b₃, b₂, b₁, pre, mid, post, + emitted_append (p 3) (p 4) (p.injective.ne (by decide : (3 : Fin 14) ≠ 4)), tokens, + List.append_assoc] using h + +omit ha in +theorem steps_le (payload : Fin A → SymbolSpec) (inputLength q S : Nat) : + steps payload inputLength q S ≤ + (2 * (S + 2) + ((A + 4) * inputLength + 3)) + (2 * (q + 2) + 1) + + (q * (A * (120 * (q + 2) ^ 2 + 1) + 3) + 1) + (S + 1) + (q + 3) := by + have h := PayloadRowsLoop.steps_le payload q 0 q (by omega) + unfold steps + omega + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.CellsMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/CellsTokensAlignmentLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/CellsTokensAlignmentLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..6c39fe99a1af02632f355402bda96904b181fed7 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/CellsTokensAlignmentLemmas.lean @@ -0,0 +1,427 @@ +import OAI.Computability.PerfectCompleteness.Machines.CellsMachine +import OAI.Computability.PerfectCompleteness.Machines.CircuitLemmas +import OAI.Computability.PerfectCompleteness.Machines.InitializationControl +import OAI.Computability.PerfectCompleteness.Machines.InputCellsMachineLemmas +import OAI.Computability.PerfectCompleteness.Machines.PaddingCellsMachine +import OAI.Computability.PerfectCompleteness.Machines.PayloadCellsAlignment +import OAI.Computability.PerfectCompleteness.Machines.PayloadRowsLoop +import OAI.Computability.PerfectCompleteness.Machines.ValidityComposition + +namespace OAI + + +noncomputable section +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.CellsTokensAlignment + + +open WitnessEncoding InitializationTemplate PaddingCellsMachine + +local instance (V : NPVerifier) : DecidableEq V.computation.tm.Λ := Classical.decEq _ +local instance (V : NPVerifier) : DecidableEq V.computation.tm.σ := Classical.decEq _ +local instance (V : NPVerifier) : ∀ k, DecidableEq (V.computation.tm.Γ k) := + fun _ => Classical.decEq _ + +theorem cellsInterval_append (V : NPVerifier) (input : List Bool) (S start m n : Nat) + (within : start + (m + n) ≤ S) : + cellsInterval V input S start (m + n) within = + cellsInterval V input S start m (by omega) ++ + cellsInterval V input S (start + m) n (by omega) := by + simp only [cellsInterval, List.flatMap_def, ← List.ofFn_eq_map] + rw [List.ofFn_add, List.flatten_append] + simp only [Fin.val_castLE, Fin.val_natAdd, Nat.add_assoc] + +theorem cellsInterval_full (V : NPVerifier) (input : List Bool) (S : Nat) : + cellsInterval V input S 0 S (by omega) = InitializationControl.cells V input S := by + simp only [cellsInterval, InitializationControl.cells, Nat.zero_add] + +theorem prefix_eq_interval (V : NPVerifier) (input : List Bool) (S : Nat) + (within : (inputPrefix input).length ≤ S) : + InputCellsMachine.streamTokens (InputCellsMachine.prefixTruth V) (inputPrefix input) = + cellsInterval V input S 0 (inputPrefix input).length (by omega) := by + simpa only [cellsInterval, List.flatMap_def, ← List.ofFn_eq_map, Nat.zero_add] using + InputCellsMachine.prefixStream_eq_initialCells V input S within + +theorem payload_eq_interval (V : NPVerifier) (input : List Bool) (S : Nat) + (within : (inputPrefix input).length + V.witnessBound.eval input.length ≤ S) : + PayloadRowsLoop.tokens (PayloadCellsMachine.symbolTable V) + (V.witnessBound.eval input.length) 0 (V.witnessBound.eval input.length) = + cellsInterval V input S (inputPrefix input).length (V.witnessBound.eval input.length) within := by + rw [PayloadRowsLoop.tokens_eq_forTokens, forTokens_eq_ofFn] + simp only [cellsInterval, List.flatMap_def, ← List.ofFn_eq_map, Nat.zero_add] + apply congrArg List.flatten + apply congrArg List.ofFn + funext i + exact PayloadCellsMachine.payloadRowTokens_eq V input S i.val i.isLt (by omega) + +theorem cells_eq_streams (V : NPVerifier) (input : List Bool) (S : Nat) + (within : (inputPrefix input).length + V.witnessBound.eval input.length ≤ S) : + InputCellsMachine.streamTokens (InputCellsMachine.prefixTruth V) (inputPrefix input) ++ + PayloadRowsLoop.tokens (PayloadCellsMachine.symbolTable V) + (V.witnessBound.eval input.length) 0 (V.witnessBound.eval input.length) ++ + repeatedRows (blankRow V) + (S - (inputPrefix input).length - V.witnessBound.eval input.length) = + InitializationControl.cells V input S := by + let P := (inputPrefix input).length + let q := V.witnessBound.eval input.length + let r := S - P - q + have hpq : P + q ≤ S := within + have total : (P + q) + r = S := by dsimp only [r]; omega + have hpre := prefix_eq_interval V input S (by omega) + have hpay := payload_eq_interval V input S within + have hpad := cellsInterval_padding V input S (P + q) r (by omega) (by exact le_rfl) + rw [hpre, hpay, ← hpad] + have first := cellsInterval_append V input S 0 P q (by omega) + have second := cellsInterval_append V input S 0 (P + q) r (by omega) + simp only [Nat.zero_add] at first second + rw [← first, ← second] + simpa only [total] using cellsInterval_full V input S + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.CellsTokensAlignment + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.InitializationAssemblyBounds + +open Polynomial + + +local instance (V : NPVerifier) : ∀ k, DecidableEq (V.computation.tm.Γ k) := + fun _ => Classical.decEq _ + +def cellsPolynomial (V : NPVerifier) : Polynomial Nat := + let A := (VerifierCircuit.indexing V).symbolCount + let q := V.witnessBound + let s := Bounds.capacityPolynomial V.computation.time q + (Runtime.programPushBound V.computation.tm) + (2 * (s + 2) + (C (A + 4) * (2 * X + 1) + 3)) + (2 * (q + 2) + 1) + + (q * (C A * (120 * (q + 2)^2 + 1) + 3) + 1) + (s + 1) + (q + 3) + +def timePolynomial (V : NPVerifier) : Polynomial Nat := + 1 + cellsPolynomial V + ValidityMachine.Full.timePolynomial.comp V.witnessBound + +theorem capacityPolynomial_eval (V : NPVerifier) (n : Nat) : + (Bounds.capacityPolynomial V.computation.time V.witnessBound + (Runtime.programPushBound V.computation.tm)).eval n = VerifierCircuit.capacity V n := by + simp [VerifierCircuit.capacity, NPVerifier.horizon, Nat.mul_comm] + +theorem cellsPolynomial_eval (V : NPVerifier) (input : List Bool) : + (cellsPolynomial V).eval input.length = + (2 * (VerifierCircuit.capacity V input.length + 2) + + (((VerifierCircuit.indexing V).symbolCount + 4) * (WitnessEncoding.inputPrefix input).length + 3)) + + (2 * (V.witnessBound.eval input.length + 2) + 1) + + (V.witnessBound.eval input.length * ((VerifierCircuit.indexing V).symbolCount * + (120 * (V.witnessBound.eval input.length + 2)^2 + 1) + 3) + 1) + + (VerifierCircuit.capacity V input.length + 1) + (V.witnessBound.eval input.length + 3) := by + simp only [cellsPolynomial, Polynomial.eval_add, Polynomial.eval_mul, + Polynomial.eval_pow, Polynomial.eval_C, Polynomial.eval_X, Polynomial.eval_ofNat, + Polynomial.eval_one, capacityPolynomial_eval, WitnessEncoding.inputPrefix_length] + +theorem cells_steps_le (V : NPVerifier) (input : List Bool) : + CellsMachine.steps (PayloadCellsMachine.symbolTable V) (WitnessEncoding.inputPrefix input).length + (V.witnessBound.eval input.length) (VerifierCircuit.capacity V input.length) ≤ + (cellsPolynomial V).eval input.length := by + rw [cellsPolynomial_eval] + exact CellsMachine.steps_le (PayloadCellsMachine.symbolTable V) + (WitnessEncoding.inputPrefix input).length (V.witnessBound.eval input.length) + (VerifierCircuit.capacity V input.length) + +theorem steps_le (V : NPVerifier) (input : List Bool) : + 1 + CellsMachine.steps (PayloadCellsMachine.symbolTable V) (WitnessEncoding.inputPrefix input).length + (V.witnessBound.eval input.length) (VerifierCircuit.capacity V input.length) + + ValidityMachine.Full.steps (V.witnessBound.eval input.length) ≤ + (timePolynomial V).eval input.length := by + simp only [timePolynomial, Polynomial.eval_add, Polynomial.eval_one, Polynomial.eval_comp] + exact Nat.add_le_add (Nat.add_le_add_left (cells_steps_le V input) 1) + (ValidityMachine.Full.steps_le_time (V.witnessBound.eval input.length)) + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.InitializationAssemblyBounds + +end + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.InitializationAssembly + +open Turing PostfixModel + + +inductive Tape (cellWork : Nat) where + | rawInput | framedInput | witnessBound | capacity | reversed | count + | validityWork (index : Fin 7) + | cellWork (index : Fin cellWork) + deriving DecidableEq, Fintype + +def validitySlots (n : Nat) : Fin 10 ↪ Tape n := + ⟨![.witnessBound, .validityWork 0, .validityWork 1, .validityWork 2, + .validityWork 3, .validityWork 4, .validityWork 5, .reversed, .count, + .validityWork 6], by + intro a b h + fin_cases a <;> fin_cases b <;> simp_all⟩ + +def controlPorts (n : Nat) : InitializationControl.Ports (Tape n) where + reversed := .reversed + count := .count + distinct := by intro h; cases h + +theorem validityReady {n : Nat} (base : Tape n → List Bool) (q : Nat) + (hbound : base .witnessBound = encodeWord q) + (hwork : ∀ j, base (.validityWork j) = []) : + ClashMachine.Full.Ready (validitySlots n) base q where + source := hbound + empty := by + intro j hj ho hc + fin_cases j <;> try contradiction + · exact hwork 0 + · exact hwork 1 + · exact hwork 2 + · exact hwork 3 + · exact hwork 4 + · exact hwork 5 + · exact hwork 6 + +theorem control_emitted_eq {n : Nat} (base : Tape n → List Bool) (ts : List Token) : + InitializationControl.emitted (controlPorts n) base ts = + ClashMachine.emitted ((validitySlots n) 7) ((validitySlots n) 8) base ts := rfl + +theorem validityReady_control {n : Nat} {base : Tape n → List Bool} {q : Nat} + (ready : ClashMachine.Full.Ready (validitySlots n) base q) (V : NPVerifier) : + ClashMachine.Full.Ready (validitySlots n) + (InitializationControl.emitted (controlPorts n) base (InitializationControl.tokens V)) q := by + rw [control_emitted_eq] + exact ready.emitted (InitializationControl.tokens V) + +theorem validitySlots_not_cellWork (n : Nat) (i : Fin 10) (j : Fin n) : + validitySlots n i ≠ Tape.cellWork j := by + rw [validitySlots.eq_1] + change (![Tape.witnessBound, Tape.validityWork 0, Tape.validityWork 1, + Tape.validityWork 2, Tape.validityWork 3, Tape.validityWork 4, Tape.validityWork 5, + Tape.reversed, Tape.count, Tape.validityWork 6] i : Tape n) ≠ Tape.cellWork j + fin_cases i <;> simp + +theorem controlTrace {n : Nat} {Λ σ : Type} + (V : NPVerifier) (entry : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : Tape n => Bool) Λ σ) + (code : program entry = InitializationControl.statement V (controlPorts n) exit) + (base : Tape n → List Bool) (state : σ) (q : Nat) + (ready : ClashMachine.Full.Ready (validitySlots n) base q) : + ((MachineComposition.advance (TM2.step program))^[1] + (some ⟨some entry, state, base⟩) = + some ⟨exit, state, InitializationControl.emitted (controlPorts n) base + (InitializationControl.tokens V)⟩) ∧ + ClashMachine.Full.Ready (validitySlots n) + (InitializationControl.emitted (controlPorts n) base (InitializationControl.tokens V)) q := + ⟨InitializationControl.trace V (controlPorts n) entry exit program code base state, + validityReady_control ready V⟩ + +noncomputable section + +open MachineComposition +open ClashMachine (State clean emitted) + +def cellsSlots : Fin 14 ↪ Tape 9 := + ⟨![.framedInput, .witnessBound, .capacity, .reversed, .count, + .cellWork 0, .cellWork 1, .cellWork 2, .cellWork 3, .cellWork 4, + .cellWork 5, .cellWork 6, .cellWork 7, .cellWork 8], by decide⟩ + +inductive CodeLabel (A : Nat) where + | control + | cells (label : CellsMachine.Label A) + | validity (label : ValidityMachine.Full.Label) + deriving DecidableEq, Fintype + +abbrev Label (V : NPVerifier) := CodeLabel (VerifierCircuit.indexing V).symbolCount + +variable {K Λ σ : Type} [DecidableEq K] + +def placedControl (slots : Tape 9 ↪ K) : InitializationControl.Ports K where + reversed := slots .reversed + count := slots .count + distinct := slots.injective.ne (by decide) + +def cellsLabels {V : NPVerifier} (labels : Label V ↪ Λ) : + CellsMachine.Label (VerifierCircuit.indexing V).symbolCount ↪ Λ := + ⟨fun l => labels (.cells l), fun _ _ h => CodeLabel.cells.inj (labels.injective h)⟩ + +structure Ready (V : NPVerifier) (slots : Tape 9 ↪ K) (base : K → List Bool) + (input : List Bool) : Prop where + rawWord : base (slots .rawInput) = input + framedWord : base (slots .framedInput) = WitnessEncoding.inputPrefix input + boundWord : base (slots .witnessBound) = encodeWord (V.witnessBound.eval input.length) + capacityWord : base (slots .capacity) = encodeWord (VerifierCircuit.capacity V input.length) + cellEmpty : ∀ j, base (slots (.cellWork j)) = [] + validityEmpty : ∀ j, base (slots (.validityWork j)) = [] + +theorem Ready.afterEmitted {V : NPVerifier} {slots : Tape 9 ↪ K} + {base : K → List Bool} {input : List Bool} (ready : Ready V slots base input) + (ts : List Token) : + Ready V slots (emitted (slots .reversed) (slots .count) base ts) input := by + constructor + · simpa [emitted, slots.injective.eq_iff] using ready.rawWord + · simpa [emitted, slots.injective.eq_iff] using ready.framedWord + · simpa [emitted, slots.injective.eq_iff] using ready.boundWord + · simpa [emitted, slots.injective.eq_iff] using ready.capacityWord + · intro j + simpa [emitted, slots.injective.eq_iff] using ready.cellEmpty j + · intro j + simpa [emitted, slots.injective.eq_iff] using ready.validityEmpty j + +omit [DecidableEq K] in +theorem Ready.cellsReady {V : NPVerifier} {slots : Tape 9 ↪ K} + {base : K → List Bool} {input : List Bool} (ready : Ready V slots base input) : + CellsMachine.Ready (cellsSlots.trans slots) base (WitnessEncoding.inputPrefix input) + (V.witnessBound.eval input.length) (VerifierCircuit.capacity V input.length) := by + constructor + · exact ready.framedWord + · exact ready.boundWord + · exact ready.capacityWord + · intro j hj + fin_cases j <;> simp_all [cellsSlots, ready.cellEmpty] + +omit [DecidableEq K] in +theorem Ready.validityReady {V : NPVerifier} {slots : Tape 9 ↪ K} + {base : K → List Bool} {input : List Bool} (ready : Ready V slots base input) : + ClashMachine.Full.Ready ((validitySlots 9).trans slots) base + (V.witnessBound.eval input.length) := by + have localReady := InitializationAssembly.validityReady (fun t => base (slots t)) + (V.witnessBound.eval input.length) ready.boundWord ready.validityEmpty + constructor + · exact localReady.source + · intro j hj ho hc + exact localReady.empty j hj ho hc + +theorem capacity_within (V : NPVerifier) (input : List Bool) : + (WitnessEncoding.inputPrefix input).length + V.witnessBound.eval input.length ≤ + VerifierCircuit.capacity V input.length := by + simp only [WitnessEncoding.inputPrefix_length, VerifierCircuit.capacity] + omega + +def statement (V : NPVerifier) (slots : Tape 9 ↪ K) (labels : Label V ↪ Λ) + (exit : Option Λ) : Label V → TM2.Stmt (fun _ : K => Bool) Λ (State σ) + | .control => InitializationControl.statement V (placedControl slots) + (some (labels (.cells (.prefix .capacityFirst)))) + | .cells l => CellsMachine.statement (cellsSlots.trans slots) (cellsLabels labels) + (some (labels (.validity (.nonempty .initialize)))) + (InputCellsMachine.prefixTruth V) (PayloadCellsMachine.symbolTable V) + (PaddingCellsMachine.blankRow V) l + | .validity l => ValidityMachine.Full.statement ((validitySlots 9).trans slots) + (fun l => labels (.validity l)) exit l + +def Agrees (V : NPVerifier) (slots : Tape 9 ↪ K) (labels : Label V ↪ Λ) + (exit : Option Λ) (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State σ)) : Prop := + ∀ l, program (labels l) = statement V slots labels exit l + +def steps (V : NPVerifier) (input : List Bool) : Nat := + 1 + CellsMachine.steps (PayloadCellsMachine.symbolTable V) + (WitnessEncoding.inputPrefix input).length (V.witnessBound.eval input.length) + (VerifierCircuit.capacity V input.length) + + ValidityMachine.Full.steps (V.witnessBound.eval input.length) + +theorem cellsTokens_eq (V : NPVerifier) (input : List Bool) : + CellsMachine.tokens (InputCellsMachine.prefixTruth V) (PayloadCellsMachine.symbolTable V) + (PaddingCellsMachine.blankRow V) (WitnessEncoding.inputPrefix input) + (V.witnessBound.eval input.length) (VerifierCircuit.capacity V input.length) = + InitializationControl.cells V input (VerifierCircuit.capacity V input.length) := + CellsTokensAlignment.cells_eq_streams V input (VerifierCircuit.capacity V input.length) + (capacity_within V input) + +theorem trace (V : NPVerifier) (slots : Tape 9 ↪ K) (labels : Label V ↪ Λ) + (exit : Option Λ) (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State σ)) + (ha : Agrees V slots labels exit program) (base : K → List Bool) (input : List Bool) + (ready : Ready V slots base input) (ambient : σ) : + (advance (TM2.step program))^[steps V input] + (some ⟨some (labels .control), clean ambient, base⟩) = + some ⟨exit, clean ambient, emitted (slots .reversed) (slots .count) base + (InitializationTemplate.initializationTokens V input)⟩ := by + let first := InitializationControl.tokens V + let middle := InitializationControl.cells V input (VerifierCircuit.capacity V input.length) + let b₁ := emitted (slots .reversed) (slots .count) base first + let b₂ := emitted (slots .reversed) (slots .count) b₁ middle + have h₁ := InitializationControl.trace V (placedControl slots) (labels .control) + (some (labels (.cells (.prefix .capacityFirst)))) program (ha .control) base (clean ambient) + change (advance (TM2.step program))^[1] + (some ⟨some (labels .control), clean ambient, base⟩) = + some ⟨some (labels (.cells (.prefix .capacityFirst))), clean ambient, b₁⟩ at h₁ + have h₂ := CellsMachine.trace (cellsSlots.trans slots) (cellsLabels labels) + (some (labels (.validity (.nonempty .initialize)))) + (InputCellsMachine.prefixTruth V) (PayloadCellsMachine.symbolTable V) + (PaddingCellsMachine.blankRow V) program (fun l => ha (.cells l)) b₁ + (WitnessEncoding.inputPrefix input) (V.witnessBound.eval input.length) + (VerifierCircuit.capacity V input.length) (capacity_within V input) + (ready.afterEmitted first).cellsReady ambient + rw [cellsTokens_eq] at h₂ + change (advance (TM2.step program))^[CellsMachine.steps (PayloadCellsMachine.symbolTable V) + (WitnessEncoding.inputPrefix input).length (V.witnessBound.eval input.length) + (VerifierCircuit.capacity V input.length)] + (some ⟨some (labels (.cells (.prefix .capacityFirst))), clean ambient, b₁⟩) = + some ⟨some (labels (.validity (.nonempty .initialize))), clean ambient, b₂⟩ at h₂ + have h₃ := ValidityMachine.Full.trace ((validitySlots 9).trans slots) + (fun l => labels (.validity l)) exit program (fun l => ha (.validity l)) b₂ + (V.witnessBound.eval input.length) + ((ready.afterEmitted first).afterEmitted middle).validityReady ambient + have h := ClashMachine.chain (ClashMachine.chain h₁ h₂) h₃ + simpa only [steps, b₂, b₁, first, middle, + show ((validitySlots 9).trans slots) 7 = slots .reversed from rfl, + show ((validitySlots 9).trans slots) 8 = slots .count from rfl, + ClashMachine.emitted_append (slots .reversed) (slots .count) + (slots.injective.ne (by decide : (Tape.reversed : Tape 9) ≠ .count)), + InitializationControl.initializationTokens_eq_blocks] using h + +def program (V : NPVerifier) : + Label V → TM2.Stmt (fun _ : Tape 9 => Bool) (Label V) (State Unit) := + statement V (Function.Embedding.refl _) (Function.Embedding.refl _) none + +def machine (V : NPVerifier) : FinTM2 where + K := Tape 9 + k₀ := .rawInput + k₁ := .reversed + Γ := fun _ => Bool + Λ := Label V + main := .control + σ := State Unit + initialState := clean () + Γk₀Fin := inferInstance + m := program V + +theorem machineTrace (V : NPVerifier) (base : Tape 9 → List Bool) (input : List Bool) + (ready : Ready V (Function.Embedding.refl _) base input) : + (advance (machine V).step)^[steps V input] + (some ⟨some .control, clean (), base⟩) = + some ⟨none, clean (), emitted .reversed .count base + (InitializationTemplate.initializationTokens V input)⟩ := + trace V (Function.Embedding.refl _) (Function.Embedding.refl _) none + (program V) (fun _ => rfl) base input ready () + +def timePolynomial (V : NPVerifier) : Polynomial Nat := + InitializationAssemblyBounds.timePolynomial V + +theorem steps_le_timePolynomial (V : NPVerifier) (input : List Bool) : + steps V input ≤ (timePolynomial V).eval input.length := + InitializationAssemblyBounds.steps_le V input + +def inPolynomialTime (V : NPVerifier) (slots : Tape 9 ↪ K) (labels : Label V ↪ Λ) + (exit : Option Λ) (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State σ)) + (ha : Agrees V slots labels exit program) (base : K → List Bool) (input : List Bool) + (ready : Ready V slots base input) (ambient : σ) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .control), clean ambient, base⟩ + (some ⟨exit, clean ambient, emitted (slots .reversed) (slots .count) base + (InitializationTemplate.initializationTokens V input)⟩) + ((timePolynomial V).eval input.length) where + steps := steps V input + evals_in_steps := by + change (advance (TM2.step program))^[steps V input] _ = _ + exact trace V slots labels exit program ha base input ready ambient + steps_le_m := steps_le_timePolynomial V input + +def machineInPolynomialTime (V : NPVerifier) (base : Tape 9 → List Bool) (input : List Bool) + (ready : Ready V (Function.Embedding.refl _) base input) : + StateTransition.EvalsToInTime (machine V).step + ⟨some .control, clean (), base⟩ + (some ⟨none, clean (), emitted .reversed .count base + (InitializationTemplate.initializationTokens V input)⟩) + ((timePolynomial V).eval input.length) := + inPolynomialTime V (Function.Embedding.refl _) (Function.Embedding.refl _) none + (program V) (fun _ => rfl) base input ready () + +end +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.InitializationAssembly + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/CircuitBatchLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/CircuitBatchLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..86633f4607093c125696083ca190e8589803f0ad --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/CircuitBatchLemmas.lean @@ -0,0 +1,378 @@ +import Mathlib.Algebra.BigOperators.Fin +import Mathlib.Logic.Equiv.Fin.Basic +import OAI.Computability.PerfectCompleteness.Machines.StatementCircuit + +namespace OAI + +section + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.CircuitBatch + +open StatementCircuit + +namespace Batch + +variable {ι : Type*} + +def cost (es : List (Expr ι)) : Nat := (es.map Expr.size).sum + +def gates (wire : ι → Nat) (start : Nat) : List (Expr ι) → List Gate + | [] => [] + | e :: es => e.gates wire start ++ gates wire (start + e.size) es + +def roots (start : Nat) : List (Expr ι) → List Nat + | [] => [] + | e :: es => e.root start :: roots (start + e.size) es + +@[simp] theorem cost_nil : cost ([] : List (Expr ι)) = 0 := rfl + +@[simp] theorem cost_cons (e : Expr ι) (es : List (Expr ι)) : + cost (e :: es) = e.size + cost es := by simp [cost] + +@[simp] theorem gates_length (wire : ι → Nat) (start : Nat) (es : List (Expr ι)) : + (gates wire start es).length = cost es := by + induction es generalizing start with + | nil => rfl + | cons e es ih => simp [gates, ih] + +@[simp] theorem roots_length (start : Nat) (es : List (Expr ι)) : + (roots start es).length = es.length := by + induction es generalizing start <;> simp [roots, *] + +theorem gates_ordered (wire : ι → Nat) (start : Nat) (es : List (Expr ι)) + (hw : ∀ i, wire i < start) : Ordered start (gates wire start es) := by + induction es generalizing start with + | nil => exact ordered_nil start + | cons e es ih => + apply (e.gates_ordered wire start hw).append + simpa only [Expr.gates_length] using + ih (start + e.size) (fun i => lt_of_lt_of_le (hw i) (by omega)) + +theorem roots_bounds (start : Nat) (es : List (Expr ι)) (r : Nat) + (hr : r ∈ roots start es) : start ≤ r ∧ r < start + cost es := by + induction es generalizing start with + | nil => simp [roots] at hr + | cons e es ih => + simp only [roots, List.mem_cons] at hr + rcases hr with rfl | hr + · have hp := e.size_pos + have hu := e.root_lt start + simp only [cost_cons] + constructor + · unfold Expr.root; omega + · omega + · have ht := ih (start + e.size) hr + simp only [cost_cons] + omega + +theorem eval_roots (wire : ι → Nat) (start : Nat) (es : List (Expr ι)) + (A : Nat → Bool) (hc : Consistent start (gates wire start es) A) : + (roots start es).map A = es.map (fun e => e.eval (fun i => A (wire i))) := by + induction es generalizing start with + | nil => rfl + | cons e es ih => + obtain ⟨he, ht⟩ := (consistent_append start _ _ A).mp hc + simp only [Expr.gates_length] at ht + simp only [roots, List.map_cons, e.eval_of_consistent wire start A he, + ih (start + e.size) ht] + +def rootAt (start : Nat) (es : List (Expr ι)) (i : Fin es.length) : Nat := + (roots start es)[i.val]'(by simpa only [roots_length] using i.isLt) + +theorem rootAt_lt (start : Nat) (es : List (Expr ι)) (i : Fin es.length) : + rootAt start es i < start + cost es := by + have hr : rootAt start es i ∈ roots start es := + List.mem_of_getElem (rfl : + (roots start es)[i.val]'(by simpa only [roots_length] using i.isLt) = rootAt start es i) + exact (roots_bounds start es _ hr).2 + +theorem eval_rootAt (wire : ι → Nat) (start : Nat) (es : List (Expr ι)) + (A : Nat → Bool) (hc : Consistent start (gates wire start es) A) + (i : Fin es.length) : + A (rootAt start es i) = es[i.val].eval (fun j => A (wire j)) := by + have h := congrArg (fun xs : List Bool => xs[i.val]?) (eval_roots wire start es A hc) + have hr : i.val < (roots start es).length := by simp + simpa only [List.getElem?_map, List.getElem?_eq_getElem hr, + List.getElem?_eq_getElem i.isLt, Option.map_some, Option.some.injEq, rootAt] using h + +theorem cost_le (es : List (Expr ι)) (D : Nat) + (h : ∀ e ∈ es, e.size ≤ D) : cost es ≤ es.length * D := by + induction es with + | nil => simp + | cons e es ih => + have he := h e (by simp) + have ht := ih (fun f hf => h f (by simp [hf])) + simp only [cost_cons, List.length_cons, Nat.succ_mul] + omega + +theorem cost_ofFn {n : Nat} (es : Fin n → Expr ι) : + cost (List.ofFn es) = ∑ i, (es i).size := by + simp [cost, List.map_ofFn, List.sum_ofFn] + +theorem cost_ofFn_le {n : Nat} (es : Fin n → Expr ι) (D : Nat) + (h : ∀ i, (es i).size ≤ D) : cost (List.ofFn es) ≤ n * D := by + have hc := cost_le (List.ofFn es) D (by + intro e he + obtain ⟨i, rfl⟩ := List.mem_ofFn.mp he + exact h i) + simpa only [List.length_ofFn] using hc + +end Batch + +structure Fragment (inputs : Nat) where + gates : List Gate + ordered : Ordered inputs gates + +namespace Fragment + +variable {inputs : Nat} + +def empty (inputs : Nat) : Fragment inputs := ⟨[], ordered_nil inputs⟩ + +def evalWires (f : Fragment inputs) (input : Fin inputs → Bool) : Nat → Bool := + run inputs f.gates (inputEnv input) + +theorem evalWires_input (f : Fragment inputs) (input : Fin inputs → Bool) + (j : Fin inputs) : f.evalWires input j.val = input j := by + rw [evalWires, run_eq_of_lt _ _ _ _ j.isLt] + simp [inputEnv, j.isLt] + +theorem evalWires_consistent (f : Fragment inputs) (input : Fin inputs → Bool) : + Consistent inputs f.gates (f.evalWires input) := + run_consistent inputs f.gates (inputEnv input) f.ordered + +def append (f : Fragment inputs) (gs : List Gate) + (hg : Ordered (inputs + f.gates.length) gs) : Fragment inputs := + ⟨f.gates ++ gs, f.ordered.append hg⟩ + +theorem evalWires_append (f : Fragment inputs) (gs : List Gate) + (hg : Ordered (inputs + f.gates.length) gs) (input : Fin inputs → Bool) : + (f.append gs hg).evalWires input = + run (inputs + f.gates.length) gs (f.evalWires input) := + run_append inputs f.gates gs (inputEnv input) + +theorem evalWires_append_old (f : Fragment inputs) (gs : List Gate) + (hg : Ordered (inputs + f.gates.length) gs) (input : Fin inputs → Bool) + (j : Nat) (hj : j < inputs + f.gates.length) : + (f.append gs hg).evalWires input j = f.evalWires input j := by + rw [evalWires_append] + exact run_eq_of_lt _ _ _ j hj + +def toCircuit (f : Fragment inputs) (output : Fin (inputs + f.gates.length)) : Circuit := + ⟨inputs, f.gates, f.ordered, output⟩ + +@[simp] theorem toCircuit_eval (f : Fragment inputs) + (output : Fin (inputs + f.gates.length)) (input : Fin inputs → Bool) : + (f.toCircuit output).eval input = f.evalWires input output.val := rfl + +end Fragment + +structure Frame (inputs width : Nat) where + fragment : Fragment inputs + wires : Fin width → Fin (inputs + fragment.gates.length) + +namespace Frame + +variable {inputs width oldWidth newWidth : Nat} + +def eval (f : Frame inputs width) (input : Fin inputs → Bool) : Fin width → Bool := + fun i => f.fragment.evalWires input (f.wires i).val + +def initial (wire : Fin width → Fin inputs) : Frame inputs width where + fragment := Fragment.empty inputs + wires := wire + +@[simp] theorem initial_eval (wire : Fin width → Fin inputs) (input : Fin inputs → Bool) + (i : Fin width) : (initial wire).eval input i = input (wire i) := + (Fragment.empty inputs).evalWires_input input (wire i) + +def step (f : Frame inputs oldWidth) (es : Fin newWidth → Expr (Fin oldWidth)) : + Frame inputs newWidth where + fragment := f.fragment.append + (Batch.gates (fun i => (f.wires i).val) (inputs + f.fragment.gates.length) (List.ofFn es)) + (Batch.gates_ordered _ _ _ (fun i => (f.wires i).isLt)) + wires := fun i => ⟨Batch.rootAt (inputs + f.fragment.gates.length) (List.ofFn es) + ⟨i.val, by simpa only [List.length_ofFn] using i.isLt⟩, by + have h := Batch.rootAt_lt (inputs + f.fragment.gates.length) (List.ofFn es) + ⟨i.val, by simpa only [List.length_ofFn] using i.isLt⟩ + simpa only [Fragment.append, List.length_append, Batch.gates_length, Nat.add_assoc] using h⟩ + +@[simp] theorem step_gate_count (f : Frame inputs oldWidth) + (es : Fin newWidth → Expr (Fin oldWidth)) : + (f.step es).fragment.gates.length = + f.fragment.gates.length + Batch.cost (List.ofFn es) := by + simp only [step, Fragment.append, List.length_append, Batch.gates_length] + +theorem step_gate_count_sum (f : Frame inputs oldWidth) + (es : Fin newWidth → Expr (Fin oldWidth)) : + (f.step es).fragment.gates.length = f.fragment.gates.length + ∑ i, (es i).size := by + rw [step_gate_count, Batch.cost_ofFn] + +theorem step_gate_count_le (f : Frame inputs oldWidth) + (es : Fin newWidth → Expr (Fin oldWidth)) (D : Nat) (h : ∀ i, (es i).size ≤ D) : + (f.step es).fragment.gates.length ≤ f.fragment.gates.length + newWidth * D := by + rw [step_gate_count] + exact Nat.add_le_add_left (Batch.cost_ofFn_le es D h) _ + +theorem step_eval (f : Frame inputs oldWidth) (es : Fin newWidth → Expr (Fin oldWidth)) + (input : Fin inputs → Bool) (i : Fin newWidth) : + (f.step es).eval input i = (es i).eval (f.eval input) := by + let start := inputs + f.fragment.gates.length + let wire := fun j : Fin oldWidth => (f.wires j).val + let gs := Batch.gates wire start (List.ofFn es) + have hc : Consistent start gs ((f.step es).fragment.evalWires input) := + ((consistent_append inputs f.fragment.gates gs _).mp + ((f.step es).fragment.evalWires_consistent input)).2 + have he := Batch.eval_rootAt wire start (List.ofFn es) + ((f.step es).fragment.evalWires input) hc + ⟨i.val, by simpa only [List.length_ofFn] using i.isLt⟩ + change (f.step es).eval input i = _ at he + rw [he] + simp only [List.getElem_ofFn] + apply Expr.eval_congr + intro j + exact f.fragment.evalWires_append_old gs + (Batch.gates_ordered wire start _ (fun j => (f.wires j).isLt)) + input (f.wires j).val (f.wires j).isLt + +theorem step_eval_fun (f : Frame inputs oldWidth) (es : Fin newWidth → Expr (Fin oldWidth)) + (input : Fin inputs → Bool) : + (f.step es).eval input = fun i => (es i).eval (f.eval input) := by + funext i + exact step_eval f es input i + +def network (es : Fin width → Expr (Fin width)) (state : Fin width → Bool) : + Fin width → Bool := fun i => (es i).eval state + +def «repeat» (f : Frame inputs width) (es : Fin width → Expr (Fin width)) : + Nat → Frame inputs width + | 0 => f + | t + 1 => («repeat» f es t).step es + +theorem repeat_eval (f : Frame inputs width) (es : Fin width → Expr (Fin width)) + (input : Fin inputs → Bool) (T : Nat) : + (f.repeat es T).eval input = (network es)^[T] (f.eval input) := by + induction T with + | zero => rfl + | succ T ih => + rw [«repeat», step_eval_fun, Function.iterate_succ_apply', ← ih] + rfl + +theorem repeat_gate_count (f : Frame inputs width) (es : Fin width → Expr (Fin width)) + (T : Nat) : + (f.repeat es T).fragment.gates.length = + f.fragment.gates.length + T * Batch.cost (List.ofFn es) := by + induction T with + | zero => simp [«repeat»] + | succ T ih => + rw [«repeat», step_gate_count, ih, Nat.succ_mul] + omega + +theorem repeat_gate_count_sum (f : Frame inputs width) (es : Fin width → Expr (Fin width)) + (T : Nat) : + (f.repeat es T).fragment.gates.length = f.fragment.gates.length + T * ∑ i, (es i).size := by + rw [repeat_gate_count, Batch.cost_ofFn] + +theorem repeat_gate_count_le (f : Frame inputs width) (es : Fin width → Expr (Fin width)) + (T D : Nat) (h : ∀ i, (es i).size ≤ D) : + (f.repeat es T).fragment.gates.length ≤ f.fragment.gates.length + T * (width * D) := by + rw [repeat_gate_count] + exact Nat.add_le_add_left (Nat.mul_le_mul_left T (Batch.cost_ofFn_le es D h)) _ + +def toCircuit (f : Frame inputs width) (output : Fin width) : Circuit := + f.fragment.toCircuit (f.wires output) + +@[simp] theorem toCircuit_eval (f : Frame inputs width) (output : Fin width) + (input : Fin inputs → Bool) : (f.toCircuit output).eval input = f.eval input output := rfl + +theorem repeat_toCircuit_eval (f : Frame inputs width) (es : Fin width → Expr (Fin width)) + (T : Nat) (output : Fin width) (input : Fin inputs → Bool) : + ((f.repeat es T).toCircuit output).eval input = + ((network es)^[T] (f.eval input)) output := by + rw [toCircuit_eval, repeat_eval] + +end Frame + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.CircuitBatch + +end + +section + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.ConfigIndex + +open StatementCircuit + +variable {K : Type} (Γ : K → Type) (Λ σ : Type) + +abbrev SymbolBit := Σ k, Option (Γ k) + +structure Indexing where + labelCount : Nat + stateCount : Nat + symbolCount : Nat + labels : Option Λ ≃ Fin labelCount + states : σ ≃ Fin stateCount + symbols : SymbolBit Γ ≃ Fin symbolCount + +variable {Γ Λ σ} + +def Indexing.width (indexing : Indexing Γ Λ σ) (S : Nat) : Nat := + indexing.labelCount + indexing.stateCount + S * indexing.symbolCount + +def cellReorder (S : Nat) : (Σ k, Fin S × Option (Γ k)) ≃ (Fin S × SymbolBit Γ) where + toFun cell := (cell.2.1, ⟨cell.1, cell.2.2⟩) + invFun cell := ⟨cell.2.1, cell.1, cell.2.2⟩ + left_inv cell := by rcases cell with ⟨k, i, a⟩; rfl + right_inv cell := by rcases cell with ⟨i, k, a⟩; rfl + +def Indexing.configIndexEquiv (indexing : Indexing Γ Λ σ) (S : Nat) : + ConfigBit Γ Λ σ S ≃ Fin (indexing.width S) := + (Equiv.sumCongr indexing.labels + (Equiv.sumCongr indexing.states + ((cellReorder S).trans + ((Equiv.prodCongr (Equiv.refl (Fin S)) indexing.symbols).trans finProdFinEquiv)))).trans + ((Equiv.sumAssoc (Fin indexing.labelCount) (Fin indexing.stateCount) + (Fin (S * indexing.symbolCount))).symm.trans + ((Equiv.sumCongr finSumFinEquiv (Equiv.refl (Fin (S * indexing.symbolCount)))).trans + finSumFinEquiv)) + +@[simp] theorem Indexing.configIndex_label (indexing : Indexing Γ Λ σ) + (S : Nat) (label : Option Λ) : + (indexing.configIndexEquiv S (.inl label)).val = (indexing.labels label).val := by + rfl + +@[simp] theorem Indexing.configIndex_state (indexing : Indexing Γ Λ σ) + (S : Nat) (state : σ) : + (indexing.configIndexEquiv S (.inr (.inl state))).val = + indexing.labelCount + (indexing.states state).val := by + rfl + +@[simp] theorem Indexing.configIndex_cell (indexing : Indexing Γ Λ σ) + (S : Nat) (k : K) (i : Fin S) (symbol : Option (Γ k)) : + (indexing.configIndexEquiv S (.inr (.inr ⟨k, i, symbol⟩))).val = + indexing.labelCount + indexing.stateCount + i.val * indexing.symbolCount + + (indexing.symbols ⟨k, symbol⟩).val := by + change indexing.labelCount + indexing.stateCount + + ((indexing.symbols ⟨k, symbol⟩).val + indexing.symbolCount * i.val) = _ + rw [Nat.mul_comm indexing.symbolCount i.val] + omega + +noncomputable def ofMachine (machine : Turing.FinTM2) + [∀ k, Fintype (machine.Γ k)] : Indexing machine.Γ machine.Λ machine.σ := by + letI := machine.kFin + letI := machine.ΛFin + letI := machine.σFin + exact { + labelCount := Fintype.card (Option machine.Λ) + stateCount := Fintype.card machine.σ + symbolCount := Fintype.card (SymbolBit machine.Γ) + labels := Fintype.equivFin (Option machine.Λ) + states := Fintype.equivFin machine.σ + symbols := Fintype.equivFin (SymbolBit machine.Γ) } + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.ConfigIndex + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/CircuitEmission.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/CircuitEmission.lean new file mode 100644 index 0000000000000000000000000000000000000000..243714a4f473b5825808986225409f61e5d901f5 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/CircuitEmission.lean @@ -0,0 +1,418 @@ +import OAI.Computability.PerfectCompleteness.Machines.CircuitLemmas + +namespace OAI + +section + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.CircuitEmission + +open Turing +open UniqueGamesTheorem.Reduction +open CircuitProducerModel + +theorem contextSource_ne_scratch (context : Context) : + contextSource context ≠ Tape.scratch := by + cases context with + | header slot => simp only [contextSource]; split <;> simp + | gate tag position => simp [contextSource] + | output position => simp [contextSource] + +theorem contextSource_ne_reversed (context : Context) : + contextSource context ≠ Tape.reversed := by + cases context with + | header slot => simp only [contextSource]; split <;> simp + | gate tag position => simp [contextSource] + | output position => simp [contextSource] + +def contextOutput (context : Context) (base : Tape → List Bool) : List Bool := + MachineTransducer.output (fun control _ => control) emission + context (base (contextSource context)) + +def contextSteps (context : Context) (base : Tape → List Bool) : Nat := + 3 * (base (contextSource context)).length + 3 + +def contextTapes (context : Context) (base : Tape → List Bool) : Tape → List Bool := + Function.update base .reversed ((contextOutput context base).reverse ++ base .reversed) + +@[simp] theorem contextTapes_other (context : Context) (base : Tape → List Bool) + (tape : Tape) (different : tape ≠ .reversed) : + contextTapes context base tape = base tape := by + simp [contextTapes, different] + +@[simp] theorem contextTapes_source (context other : Context) (base : Tape → List Bool) : + contextTapes context base (contextSource other) = base (contextSource other) := + contextTapes_other context base _ (contextSource_ne_reversed other) + +@[simp] theorem contextTapes_scratch (context : Context) (base : Tape → List Bool) : + contextTapes context base .scratch = base .scratch := + contextTapes_other context base _ (by decide) + +@[simp] theorem contextOutput_update (context : Context) (base : Tape → List Bool) + (out : List Bool) : + contextOutput context (Function.update base .reversed out) = contextOutput context base := by + simp [contextOutput, contextSource_ne_reversed] + +@[simp] theorem contextSteps_update (context : Context) (base : Tape → List Bool) + (out : List Bool) : + contextSteps context (Function.update base .reversed out) = contextSteps context base := by + simp [contextSteps, contextSource_ne_reversed] + +theorem setupStep (context : Context) (base : Tape → List Bool) (state : State) : + TM2.step program ⟨some (.setup context), state, base⟩ = + some ⟨some (.scan context), (((), context), none), base⟩ := rfl + +theorem contextTrace (context : Context) (base : Tape → List Bool) + (scratchEmpty : base .scratch = []) (state : State) : + (MachineComposition.advance (TM2.step program))^[contextSteps context base] + (some ⟨some (.setup context), state, base⟩) = + some ⟨contextNext context, initialState, contextTapes context base⟩ := by + have copied := MachineTransducerCopy.transduceCopyTrace + (contextSource context) Tape.scratch Tape.reversed + (contextSource_ne_scratch context) (contextSource_ne_reversed context) (by decide) + defaultControl (fun control _ => control) emission + (.scan context) (.restore context) (fun control symbol => .emit context control symbol) + (contextNext context) program rfl (by intros; rfl) rfl base scratchEmpty () context none + rw [contextSteps, show 3 * (base (contextSource context)).length + 3 = + (3 * (base (contextSource context)).length + 2) + 1 by omega, + Function.iterate_succ_apply] + change (MachineComposition.advance (TM2.step program))^[ + 3 * (base (contextSource context)).length + 2] + (TM2.step program ⟨some (.setup context), state, base⟩) = _ + rw [setupStep] + exact copied + +def contextInTime (context : Context) (base : Tape → List Bool) + (scratchEmpty : base .scratch = []) (state : State) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (.setup context), state, base⟩ + (some ⟨contextNext context, initialState, contextTapes context base⟩) + (contextSteps context base) where + steps := contextSteps context base + evals_in_steps := contextTrace context base scratchEmpty state + steps_le_m := Nat.le_refl _ + +theorem output_eq_flatMap (context : Context) (input : List Bool) : + MachineTransducer.output (fun control _ => control) emission context input = + input.flatMap (emission context) := by + induction input with + | nil => rfl + | cons symbol input ih => + simp only [MachineTransducer.output, List.flatMap_cons, ih] + +theorem literalEmit_word (positive : Bool) (value : Nat) : + (encodeWord value).flatMap (literalEmit positive) = + encodeWords [value, if positive then 1 else 0] := by + induction value with + | zero => simp [encodeWord, encodeWords, literalEmit] + | succ value ih => + simpa [encodeWord, encodeWords, List.replicate_succ, literalEmit] using + congrArg (List.cons true) ih + +theorem affineEmit_word (scale offset value : Nat) : + (encodeWord value).flatMap (affineEmit scale offset) = + encodeWord (offset + scale * value) := by + have hrep : (List.replicate value true).flatMap (affineEmit scale offset) = + List.replicate (scale * value) true := by + rw [List.flatMap_replicate] + change (List.replicate value (List.replicate scale true)).flatten = _ + rw [List.flatten_replicate_replicate, Nat.mul_comm value scale] + simp only [encodeWord, List.flatMap_append, List.flatMap_cons, List.flatMap_nil, + List.append_nil, hrep, affineEmit] + rw [← List.append_assoc, List.replicate_append_replicate, Nat.add_comm (scale * value) offset] + +def contextWords (context : Context) (value : Nat) : List Nat := + match context with + | .header j => if j.val = 0 then [value] else [3 * value + 1] + | .gate tag j => [value, if (gateTemplate tag j).2 then 1 else 0] + | .output _ => [value, 1] + +theorem output_word (context : Context) (value : Nat) : + MachineTransducer.output (fun control _ => control) emission context (encodeWord value) = + encodeWords (contextWords context value) := by + rw [output_eq_flatMap] + cases context with + | header j => + by_cases hj : j.val = 0 <;> + simp [emission, contextWords, hj, affineEmit_word, encodeWords, Nat.add_comm] + | gate tag j => exact literalEmit_word (gateTemplate tag j).2 value + | output j => simpa [emission, contextWords] using literalEmit_word true value + +theorem contextTrace_word (context : Context) (base : Tape → List Bool) + (scratchEmpty : base .scratch = []) (state : State) (value : Nat) + (cached : base (contextSource context) = encodeWord value) : + (MachineComposition.advance (TM2.step program))^[3 * (value + 1) + 3] + (some ⟨some (.setup context), state, base⟩) = + some ⟨contextNext context, initialState, + Function.update base .reversed + ((encodeWords (contextWords context value)).reverse ++ base .reversed)⟩ := by + simpa only [contextSteps, contextTapes, contextOutput, cached, encodeWord_length, output_word] + using contextTrace context base scratchEmpty state + +def contextListOutput (contexts : List Context) (base : Tape → List Bool) : List Bool := + contexts.flatMap (fun context => contextOutput context base) + +def contextListSteps (contexts : List Context) (base : Tape → List Bool) : Nat := + (contexts.map (fun context => contextSteps context base)).sum + +def contextListStart (contexts : List Context) (exit : Option Label) : Option Label := + match contexts with + | [] => exit + | context :: _ => some (.setup context) + +def ContextListLinked : List Context → Option Label → Prop + | [], _ => True + | context :: rest, exit => + contextNext context = contextListStart rest exit ∧ ContextListLinked rest exit + +@[simp] theorem contextListOutput_update (contexts : List Context) (base : Tape → List Bool) + (out : List Bool) : + contextListOutput contexts (Function.update base .reversed out) = contextListOutput contexts base := by + simp [contextListOutput] + +@[simp] theorem contextListSteps_update (contexts : List Context) (base : Tape → List Bool) + (out : List Bool) : + contextListSteps contexts (Function.update base .reversed out) = contextListSteps contexts base := by + simp [contextListSteps] + +private theorem chain {α : Type*} {f : α → α} {x y z : α} {m n : Nat} + (first : f^[m] x = y) (second : f^[n] y = z) : f^[n + m] x = z := by + rw [Function.iterate_add_apply, first, second] + +theorem contextListTrace (contexts : List Context) (exit : Option Label) + (linked : ContextListLinked contexts exit) (base : Tape → List Bool) + (scratchEmpty : base .scratch = []) (state : State) + (emptyInitial : contexts = [] → state = initialState) : + (MachineComposition.advance (TM2.step program))^[contextListSteps contexts base] + (some ⟨contextListStart contexts exit, state, base⟩) = + some ⟨exit, initialState, Function.update base .reversed + ((contextListOutput contexts base).reverse ++ base .reversed)⟩ := by + induction contexts generalizing base state with + | nil => + rw [emptyInitial rfl] + simp [contextListSteps, contextListOutput, contextListStart] + | cons context rest ih => + let after := contextTapes context base + have first := contextTrace context base scratchEmpty state + have second := ih linked.2 after (by simpa [after] using scratchEmpty) + initialState (by intro _; rfl) + rw [linked.1] at first + have combined := chain first second + simp only [after, contextTapes, contextListSteps_update, contextListOutput_update, + Function.update_self, Function.update_idem] at combined + rw [show contextListSteps (context :: rest) base = + contextListSteps rest base + contextSteps context base by + simp [contextListSteps, Nat.add_comm]] + simpa only [contextListStart, contextListOutput, List.flatMap_cons, + List.reverse_append, List.append_assoc] using combined + +def gateContexts (tag : Fin 5) : List Context := + (List.finRange 9).map (Context.gate tag) + +def outputContexts : List Context := [.output 0, .output 1, .output 2] + +theorem gateContexts_linked (tag : Fin 5) : + ContextListLinked (gateContexts tag) (some (.cleanup 0)) := by + simp [gateContexts, List.finRange, List.ofFn_succ, ContextListLinked, + contextListStart, contextNext] + +theorem outputContexts_linked : + ContextListLinked outputContexts (some .finalCounter) := by + simp [outputContexts, ContextListLinked, contextListStart, contextNext] + +theorem contextOutput_gate_word (record : Record) (position : Fin 9) + (base : Tape → List Bool) + (h1 : base (.field 1) = encodeWord record.output) + (h2 : base (.field 2) = encodeWord record.first) + (h3 : base (.field 3) = encodeWord record.second) : + contextOutput (.gate record.tag position) base = encodeWords + [record.slot (gateTemplate record.tag position).1, + if (gateTemplate record.tag position).2 then 1 else 0] := by + have fields (slot : Fin 3) : + base (.field ⟨slot.val + 1, by omega⟩) = encodeWord (record.slot slot) := by + have slotCases : slot.val = 0 ∨ slot.val = 1 ∨ slot.val = 2 := by omega + rcases slotCases with h | h | h + · simpa [Record.slot, h] using h1 + · simpa [Record.slot, h] using h2 + · simpa [Record.slot, h] using h3 + unfold contextOutput + rw [show base (contextSource (.gate record.tag position)) = + encodeWord (record.slot (gateTemplate record.tag position).1) from fields _] + exact output_word (.gate record.tag position) _ + +theorem encodeWords_flatMap {A : Type*} (items : List A) (words : A → List Nat) : + encodeWords (items.flatMap words) = items.flatMap (fun item => encodeWords (words item)) := by + induction items with + | nil => rfl + | cons item rest ih => simp only [List.flatMap_cons, encodeWords_append, ih] + +theorem gateOutput_words (record : Record) (base : Tape → List Bool) + (h1 : base (.field 1) = encodeWord record.output) + (h2 : base (.field 2) = encodeWord record.first) + (h3 : base (.field 3) = encodeWord record.second) : + contextListOutput (gateContexts record.tag) base = record.outputBits := by + simp only [contextListOutput, gateContexts, List.flatMap_map, + Record.outputBits, Record.outputWords, templateWords, encodeWords_flatMap] + congr 1 + funext position + exact contextOutput_gate_word record position base h1 h2 h3 + +def gateSteps (record : Record) : Nat := + ((List.finRange 9).map fun position => + 3 * (record.slot (gateTemplate record.tag position).1 + 1) + 3).sum + +theorem gateSteps_eq (record : Record) (base : Tape → List Bool) + (h1 : base (.field 1) = encodeWord record.output) + (h2 : base (.field 2) = encodeWord record.first) + (h3 : base (.field 3) = encodeWord record.second) : + contextListSteps (gateContexts record.tag) base = gateSteps record := by + have fields (slot : Fin 3) : + base (.field ⟨slot.val + 1, by omega⟩) = encodeWord (record.slot slot) := by + have slotCases : slot.val = 0 ∨ slot.val = 1 ∨ slot.val = 2 := by omega + rcases slotCases with h | h | h + · simpa [Record.slot, h] using h1 + · simpa [Record.slot, h] using h2 + · simpa [Record.slot, h] using h3 + simp only [contextListSteps, gateContexts, List.map_map, gateSteps] + congr 2 + funext position + simp only [Function.comp_apply, contextSteps, contextSource, fields, encodeWord_length] + +theorem slot_le_sum (record : Record) (slot : Fin 3) : + record.slot slot ≤ record.output + record.first + record.second := by + unfold Record.slot + split <;> omega + +private theorem sum_map_le_length_mul {A : Type*} (items : List A) + (value : A → Nat) (bound : Nat) (bounded : ∀ item ∈ items, value item ≤ bound) : + (items.map value).sum ≤ items.length * bound := by + induction items with + | nil => simp + | cons item rest ih => + have head := bounded item (by simp) + have tail := ih (fun a ha => bounded a (by simp [ha])) + simp only [List.map_cons, List.sum_cons, List.length_cons, Nat.add_mul, Nat.one_mul] + omega + +theorem gateSteps_le (record : Record) : + gateSteps record ≤ 27 * (record.output + record.first + record.second) + 54 := by + have bound := sum_map_le_length_mul (List.finRange 9) + (fun position => 3 * (record.slot (gateTemplate record.tag position).1 + 1) + 3) + (3 * (record.output + record.first + record.second) + 6) (by + intro position _ + have := slot_le_sum record (gateTemplate record.tag position).1 + omega) + simp only [List.length_finRange] at bound + unfold gateSteps + omega + +private theorem length_flatMap_le_length_mul {A : Type*} (items : List A) + (word : A → List Bool) (bound : Nat) (bounded : ∀ item ∈ items, (word item).length ≤ bound) : + (items.flatMap word).length ≤ items.length * bound := by + induction items with + | nil => simp + | cons item rest ih => + have head := bounded item (by simp) + have tail := ih (fun a ha => bounded a (by simp [ha])) + simp only [List.flatMap_cons, List.length_append, List.length_cons, + Nat.add_mul, Nat.one_mul] + omega + +theorem outputBits_length_le (record : Record) : + record.outputBits.length ≤ 9 * (record.output + record.first + record.second) + 27 := by + have bound := length_flatMap_le_length_mul (List.finRange 9) + (fun position => encodeWords + [record.slot (gateTemplate record.tag position).1, + if (gateTemplate record.tag position).2 then 1 else 0]) + (record.output + record.first + record.second + 3) (by + intro position _ + have index := slot_le_sum record (gateTemplate record.tag position).1 + have sign : (if (gateTemplate record.tag position).2 then 1 else 0 : Nat) ≤ 1 := by + split <;> omega + simp only [encodeWords, List.length_append, encodeWord_length, List.length_nil] + omega) + simp only [List.length_finRange] at bound + unfold Record.outputBits Record.outputWords templateWords + rw [encodeWords_flatMap] + omega + +theorem recordBits_length (record : Record) : + record.bits.length = record.tag.val + record.output + record.first + record.second + 4 := by + simp [Record.bits, Record.words, encodeWords_length] + omega + +theorem gateSteps_le_inputSize (record : Record) : + gateSteps record ≤ 27 * record.bits.length := by + have bound := gateSteps_le record + rw [recordBits_length] + omega + +theorem outputBits_length_le_inputSize (record : Record) : + record.outputBits.length ≤ 9 * record.bits.length := by + have bound := outputBits_length_le record + rw [recordBits_length] + omega + +theorem gateTrace (record : Record) (base : Tape → List Bool) + (scratchEmpty : base .scratch = []) (state : State) + (h1 : base (.field 1) = encodeWord record.output) + (h2 : base (.field 2) = encodeWord record.first) + (h3 : base (.field 3) = encodeWord record.second) : + (MachineComposition.advance (TM2.step program))^[gateSteps record] + (some ⟨some (.setup (.gate record.tag 0)), state, base⟩) = + some ⟨some (.cleanup 0), initialState, Function.update base .reversed + (record.outputBits.reverse ++ base .reversed)⟩ := by + have trace := contextListTrace (gateContexts record.tag) (some (.cleanup 0)) + (gateContexts_linked record.tag) base scratchEmpty state + (by intro h; have := congrArg List.length h; simp [gateContexts] at this) + rw [gateSteps_eq record base h1 h2 h3, gateOutput_words record base h1 h2 h3] at trace + simpa [contextListStart, gateContexts, List.finRange] using trace + +def gateInTime (record : Record) (base : Tape → List Bool) + (scratchEmpty : base .scratch = []) (state : State) + (h1 : base (.field 1) = encodeWord record.output) + (h2 : base (.field 2) = encodeWord record.first) + (h3 : base (.field 3) = encodeWord record.second) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (.setup (.gate record.tag 0)), state, base⟩ + (some ⟨some (.cleanup 0), initialState, Function.update base .reversed + (record.outputBits.reverse ++ base .reversed)⟩) + (gateSteps record) where + steps := gateSteps record + evals_in_steps := gateTrace record base scratchEmpty state h1 h2 h3 + steps_le_m := Nat.le_refl _ + +theorem outputTrace (selected : Nat) (base : Tape → List Bool) + (scratchEmpty : base .scratch = []) (state : State) + (cached : base .selected = encodeWord selected) : + (MachineComposition.advance (TM2.step program))^[9 * (selected + 1) + 9] + (some ⟨some (.setup (.output 0)), state, base⟩) = + some ⟨some .finalCounter, initialState, Function.update base .reversed + ((encodeWords (outputWords selected)).reverse ++ base .reversed)⟩ := by + have trace := contextListTrace outputContexts (some .finalCounter) + outputContexts_linked base scratchEmpty state (by simp [outputContexts]) + have steps : contextListSteps outputContexts base = 9 * (selected + 1) + 9 := by + simp [contextListSteps, outputContexts, contextSteps, contextSource, cached] + omega + have out : contextListOutput outputContexts base = encodeWords (outputWords selected) := by + simp [contextListOutput, outputContexts, contextOutput, contextSource, cached, + output_word, contextWords, outputWords, encodeWords, List.append_assoc] + rw [steps, out] at trace + exact trace + +def outputInTime (selected : Nat) (base : Tape → List Bool) + (scratchEmpty : base .scratch = []) (state : State) + (cached : base .selected = encodeWord selected) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (.setup (.output 0)), state, base⟩ + (some ⟨some .finalCounter, initialState, Function.update base .reversed + ((encodeWords (outputWords selected)).reverse ++ base .reversed)⟩) + (9 * (selected + 1) + 9) where + steps := 9 * (selected + 1) + 9 + evals_in_steps := outputTrace selected base scratchEmpty state cached + steps_le_m := Nat.le_refl _ + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.CircuitEmission + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/CircuitEncodingLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/CircuitEncodingLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..973090139b849c05b2451d7264062196abebb01b --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/CircuitEncodingLemmas.lean @@ -0,0 +1,243 @@ +import OAI.Computability.PerfectCompleteness.Machines.CircuitLemmas + +namespace OAI + +section + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin + +open CircuitProducerModel + +def gateRecord (output : Nat) : Gate → Record + | .const false => ⟨0, output, 0, 0⟩ + | .const true => ⟨1, output, 0, 0⟩ + | .not a => ⟨2, output, a, 0⟩ + | .and a b => ⟨3, output, a, b⟩ + | .or a b => ⟨4, output, a, b⟩ + +def gateRecords (start : Nat) : List Gate → List Record + | [] => [] + | g :: gs => gateRecord start g :: gateRecords (start + 1) gs + +def Circuit.records (C : Circuit) : List Record := gateRecords C.inputs C.gates + +def recordsWords (rs : List Record) : List Nat := rs.flatMap Record.words +def recordsBits (rs : List Record) : List Bool := encodeWords (recordsWords rs) + +def circuitWords (C : Circuit) : List Nat := + [C.wires, C.gates.length, C.output.val] ++ recordsWords C.records + +def circuitBits (C : Circuit) : List Bool := encodeWords (circuitWords C) + +@[simp] theorem gateRecords_length (start : Nat) (gs : List Gate) : + (gateRecords start gs).length = gs.length := by + induction gs generalizing start with + | nil => rfl + | cons g gs ih => simp [gateRecords, ih] + +@[simp] theorem Circuit.records_length (C : Circuit) : C.records.length = C.gates.length := + gateRecords_length C.inputs C.gates + +@[simp] theorem recordsWords_cons (r : Record) (rs : List Record) : + recordsWords (r :: rs) = r.words ++ recordsWords rs := rfl + +@[simp] theorem recordsBits_cons (r : Record) (rs : List Record) : + recordsBits (r :: rs) = r.bits ++ recordsBits rs := by + simp [recordsBits, Record.bits] + +@[simp] theorem recordsWords_length (rs : List Record) : + (recordsWords rs).length = 4 * rs.length := by + induction rs with + | nil => rfl + | cons r rs ih => + rw [recordsWords_cons, List.length_append, ih] + simp only [Record.words, List.length_cons, List.length_nil] + omega + +@[simp] theorem circuitWords_length (C : Circuit) : + (circuitWords C).length = 3 + 4 * C.gates.length := by + simp [circuitWords] + omega + +def gateFromFields (tag first second : Nat) : Gate := + match tag with + | 0 => .const false + | 1 => .const true + | 2 => .not first + | 3 => .and first second + | _ => .or first second + +def decodeGateWords : List Nat → List Gate + | tag :: _ :: first :: second :: rest => + gateFromFields tag first second :: decodeGateWords rest + | _ => [] + +theorem decodeGateWords_gateRecord (output : Nat) (g : Gate) (rest : List Nat) : + decodeGateWords ((gateRecord output g).words ++ rest) = + g :: decodeGateWords rest := by + cases g with + | const b => cases b <;> rfl + | not a => rfl + | and a b => rfl + | or a b => rfl + +@[simp] theorem decodeGateWords_gateRecords (start : Nat) (gs : List Gate) : + decodeGateWords (recordsWords (gateRecords start gs)) = gs := by + induction gs generalizing start with + | nil => rfl + | cons g gs ih => + rw [gateRecords, recordsWords_cons, decodeGateWords_gateRecord, ih] + +theorem circuitWords_injective : Function.Injective circuitWords := by + intro C D h + have hh : C.wires = D.wires ∧ C.gates.length = D.gates.length ∧ + C.output.val = D.output.val ∧ recordsWords C.records = recordsWords D.records := by + simpa only [circuitWords, List.cons_append, List.nil_append, List.cons.injEq] using h + have hg : C.gates = D.gates := by + have hd := congrArg decodeGateWords hh.2.2.2 + simpa only [Circuit.records, decodeGateWords_gateRecords] using hd + have hi : C.inputs = D.inputs := by + have hw := hh.1 + simp only [Circuit.wires] at hw + rw [hg] at hw + omega + cases C with + | mk ci cg co cx => + cases D with + | mk di dg dord dx => + dsimp at hi hg hh + subst di + subst dg + have hx : cx = dx := Fin.ext hh.2.2.1 + subst dx + rfl + +theorem circuitBits_injective : Function.Injective circuitBits := by + intro C D h + exact circuitWords_injective (encodeWords_injective h) + +theorem gateRecord_fields_le (start bound : Nat) (g : Gate) + (hs : start ≤ bound) (hg : g.Bounded bound) : + ∀ n ∈ (gateRecord start g).words, n ≤ bound + 4 := by + cases g with + | const b => cases b <;> simp [gateRecord, Record.words] <;> omega + | not a => simp [gateRecord, Record.words, Gate.Bounded] at *; omega + | and a b => simp [gateRecord, Record.words, Gate.Bounded] at *; omega + | or a b => simp [gateRecord, Record.words, Gate.Bounded] at *; omega + +theorem gateRecords_fields_le (start : Nat) (gs : List Gate) (ho : Ordered start gs) : + ∀ n ∈ recordsWords (gateRecords start gs), n ≤ start + gs.length + 4 := by + induction gs generalizing start with + | nil => simp [gateRecords, recordsWords] + | cons g gs ih => + rcases (ordered_cons start g gs).mp ho with ⟨hg, hgs⟩ + intro n hn + rw [gateRecords, recordsWords_cons, List.mem_append] at hn + rcases hn with hn | hn + · have h := gateRecord_fields_le start start g (Nat.le_refl _) hg n hn + simp only [List.length_cons] + omega + · have h := ih (start + 1) hgs n hn + simp only [List.length_cons] + omega + +theorem circuitWords_bounded (C : Circuit) : + ∀ n ∈ circuitWords C, n ≤ C.wires + 4 := by + intro n hn + simp only [circuitWords, List.mem_append, List.mem_cons, List.not_mem_nil, or_false] at hn + rcases hn with (rfl | rfl | rfl) | hn + · omega + · simp only [Circuit.wires]; omega + · have := C.output.isLt + change C.output.val ≤ C.inputs + C.gates.length + 4 + omega + · exact gateRecords_fields_le C.inputs C.gates C.ordered n hn + +theorem circuitBits_length_le (C : Circuit) : + (circuitBits C).length ≤ (3 + 4 * C.gates.length) * (C.wires + 5) := by + have h := encodeWords_length_le (circuitWords C) (C.wires + 4) + (circuitWords_bounded C) + simpa only [circuitBits, circuitWords_length, Nat.add_assoc] using h + +theorem circuit_header_le_length (C : Circuit) : + C.wires + C.gates.length + C.output.val + 3 ≤ (circuitBits C).length := by + simp only [circuitBits, circuitWords, encodeWords_append, List.length_append, + encodeWords, encodeWord_length, List.length_nil] + omega + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin + +end + +section + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin + +open Target CircuitProducerModel + +theorem gateClauses_words {n : Nat} (output : Fin n) (g : Gate) (h : g.Bounded n) : + (gateClauses output g h).flatMap clauseWords = (gateRecord output.val g).outputWords := by + cases g with + | const b => cases b <;> rfl + | not x => rfl + | and x y => rfl + | or x y => rfl + +@[simp] theorem unitClause_words {n : Nat} (output : Fin n) : + clauseWords (unitClause output true) = outputWords output.val := rfl + +theorem gateRecords_outputWords (start : Nat) (gs : List Gate) : + (List.finRange gs.length).flatMap + (fun i => (gateRecord (start + i.val) gs[i.val]).outputWords) = + (gateRecords start gs).flatMap Record.outputWords := by + induction gs generalizing start with + | nil => rfl + | cons g gs ih => + change (List.finRange (gs.length + 1)).flatMap + (fun i => (gateRecord (start + i.val) (g :: gs)[i.val]).outputWords) = _ + rw [List.finRange_succ, List.flatMap_cons, List.flatMap_map] + change (gateRecord start g).outputWords ++ + (List.finRange gs.length).flatMap + (fun i => (gateRecord (start + (i.val + 1)) gs[i.val]).outputWords) = + (gateRecord start g).outputWords ++ + (gateRecords (start + 1) gs).flatMap Record.outputWords + apply congrArg ((gateRecord start g).outputWords ++ ·) + simpa [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using ih (start + 1) + +theorem Circuit.gateBlocks_words (C : Circuit) : + ((List.finRange C.gates.length).flatMap C.gateBlock).flatMap clauseWords = + C.records.flatMap Record.outputWords := by + rw [List.flatMap_assoc] + calc + _ = (List.finRange C.gates.length).flatMap + (fun i => (gateRecord (C.inputs + i.val) C.gates[i.val]).outputWords) := by + apply List.flatMap_congr + intro i _ + exact gateClauses_words (C.gateOutput i) (C.gateAt i) (C.gateBounded i) + _ = C.records.flatMap Record.outputWords := gateRecords_outputWords C.inputs C.gates + +theorem Circuit.formulaWords_eq_records (C : Circuit) : + formulaWords C.toFormula = + [C.wires, 3 * C.gates.length + 1] ++ + C.records.flatMap Record.outputWords ++ outputWords C.output.val := by + unfold formulaWords + change [C.wires, C.toFormula.clauses.length] ++ C.toFormula.clauses.flatMap clauseWords = _ + rw [C.toFormula_clause_count] + change [C.wires, 3 * C.gates.length + 1] ++ + (((List.finRange C.gates.length).flatMap C.gateBlock ++ + [unitClause C.output true]).flatMap clauseWords) = _ + rw [List.flatMap_append, C.gateBlocks_words] + simp only [List.flatMap_cons, List.flatMap_nil, List.append_nil, unitClause_words, + List.append_assoc] + +theorem Circuit.formulaBits_eq_records (C : Circuit) : + formulaBits C.toFormula = + encodeWords ([C.wires, 3 * C.gates.length + 1] ++ + C.records.flatMap Record.outputWords ++ outputWords C.output.val) := + congrArg encodeWords C.formulaWords_eq_records + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/CircuitFinish.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/CircuitFinish.lean new file mode 100644 index 0000000000000000000000000000000000000000..b5c781fe15aa29e308dbd0bdbeba00582bd781ee --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/CircuitFinish.lean @@ -0,0 +1,347 @@ +import Mathlib.Tactic.Ring +import OAI.Computability.PerfectCompleteness.Machines.CircuitEncodingLemmas +import OAI.Computability.UniqueGames.Machines.MachineCloudPadding +import OAI.Computability.UniqueGames.Machines.MachineCopy + +namespace OAI + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.CircuitFinish + +open Turing MachineComposition +open MachineCloudPadding + + +inductive Tape + | current | freeInputs | root | reversedRecords | output | gateCount | scratch + deriving DecidableEq + +/-- A list enumerating every element of the type, which are all zero-argument constructors. (Generated by the `Fintype` deriving handler.)-/ +protected abbrev Tape.enumList : List Tape := [.current, .freeInputs, .root, .reversedRecords, + .output, .gateCount, .scratch] + +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 + +inductive Label + | copyOut | copyBack | cancel | records + | rootOut | rootBack | countOut | countBack | currentOut | currentBack + deriving DecidableEq + +/-- A list enumerating every element of the type, which are all zero-argument constructors. (Generated by the `Fintype` deriving handler.)-/ +protected abbrev Label.enumList : List Label := [.copyOut, .copyBack, .cancel, .records, .rootOut, + .rootBack, .countOut, .countBack, .currentOut, .currentBack] + +protected theorem Label.enumList_getElem?_ctorIdx_eq (x : Label) : + Label.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem Label.enumList_nodup : Label.enumList.Nodup := by decide + +instance : Fintype Label where + elems := ⟨Label.enumList, Label.enumList_nodup⟩ + complete x := by cases x <;> decide + +abbrev Alphabet (_ : Tape) := Bool +abbrev State (σ : Type) := σ × Option Bool + +def memory (current freeInputs root reversedRecords output gateCount scratch : List Bool) : + Tape → List Bool + | .current => current + | .freeInputs => freeInputs + | .root => root + | .reversedRecords => reversedRecords + | .output => output + | .gateCount => gateCount + | .scratch => scratch + +@[simp] theorem update_current (a b c d e f g x : List Bool) : + Function.update (memory a b c d e f g) .current x = memory x b c d e f g := by + funext t; cases t <;> rfl +@[simp] theorem update_freeInputs (a b c d e f g x : List Bool) : + Function.update (memory a b c d e f g) .freeInputs x = memory a x c d e f g := by + funext t; cases t <;> rfl +@[simp] theorem update_root (a b c d e f g x : List Bool) : + Function.update (memory a b c d e f g) .root x = memory a b x d e f g := by + funext t; cases t <;> rfl +@[simp] theorem update_reversedRecords (a b c d e f g x : List Bool) : + Function.update (memory a b c d e f g) .reversedRecords x = memory a b c x e f g := by + funext t; cases t <;> rfl +@[simp] theorem update_output (a b c d e f g x : List Bool) : + Function.update (memory a b c d e f g) .output x = memory a b c d x f g := by + funext t; cases t <;> rfl +@[simp] theorem update_gateCount (a b c d e f g x : List Bool) : + Function.update (memory a b c d e f g) .gateCount x = memory a b c d e x g := by + funext t; cases t <;> rfl +@[simp] theorem update_scratch (a b c d e f g x : List Bool) : + Function.update (memory a b c d e f g) .scratch x = memory a b c d e f x := by + funext t; cases t <;> rfl + +variable {σ : Type} + +def cancelLoop : TM2.Stmt Alphabet Label (State σ) := + .pop .freeInputs (fun state head => (state.1, head)) + (.branch (fun state => state.2.getD false) + (.pop .gateCount (fun state _ => (state.1, none)) (.goto fun _ => .cancel)) + (.load (fun state => (state.1, none)) (.goto fun _ => .records))) + +def program : Label → TM2.Stmt Alphabet Label (State σ) + | .copyOut => Reduction.MachineTransfer.loopAt .current .scratch id false + .copyOut (some .copyBack) + | .copyBack => MachineCopy.forkLoop .scratch .current .gateCount false + .copyBack (some .cancel) + | .cancel => cancelLoop + | .records => Reduction.MachineTransfer.loopAt .reversedRecords .output id false + .records (some .rootOut) + | .rootOut => Reduction.MachineTransfer.loopAt .root .scratch id false + .rootOut (some .rootBack) + | .rootBack => Reduction.MachineTransfer.loopAt .scratch .output id false + .rootBack (some .countOut) + | .countOut => Reduction.MachineTransfer.loopAt .gateCount .scratch id false + .countOut (some .countBack) + | .countBack => Reduction.MachineTransfer.loopAt .scratch .output id false + .countBack (some .currentOut) + | .currentOut => Reduction.MachineTransfer.loopAt .current .scratch id false + .currentOut (some .currentBack) + | .currentBack => Reduction.MachineTransfer.loopAt .scratch .output id false + .currentBack none + +private theorem appendTrace {α : 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 a b, Function.iterate_add_apply, first, second] + +theorem prependTrace {K Λ α : Type} [DecidableEq K] + (source destination scratch : K) + (sourceDestination : source ≠ destination) (sourceScratch : source ≠ scratch) + (destinationScratch : destination ≠ scratch) + (firstLabel secondLabel : Λ) (exit : Option Λ) + (target : Λ → TM2.Stmt (fun _ : K => Bool) Λ (α × Option Bool)) + (atFirst : target firstLabel = Reduction.MachineTransfer.loopAt source scratch id false + firstLabel (some secondLabel)) + (atSecond : target secondLabel = Reduction.MachineTransfer.loopAt scratch destination + id false secondLabel exit) + (base : K → List Bool) (scratchEmpty : base scratch = []) + (ambient : α) (register : Option Bool) : + (advance (TM2.step target))^[2 * ((base source).length + 1)] + (some ⟨some firstLabel, (ambient, register), base⟩) = + some ⟨exit, (ambient, none), + Reduction.MachineTransfer.tapesAt source destination base [] + (base source ++ base destination)⟩ := by + let mid := Reduction.MachineTransfer.tapesAt source scratch base [] (base source).reverse + have first := Reduction.MachineTransfer.transferAt_fromTapes source scratch sourceScratch + id false firstLabel (some secondLabel) target atFirst base ambient register + change (advance (TM2.step target))^[(base source).length + 1] + (some ⟨some firstLabel, (ambient, register), base⟩) = _ at first + simp only [List.map_id, scratchEmpty, List.append_nil] at first + change (advance (TM2.step target))^[(base source).length + 1] + (some ⟨some firstLabel, (ambient, register), base⟩) = + some ⟨some secondLabel, (ambient, none), mid⟩ at first + have hscratch : mid scratch = (base source).reverse := by + simp [mid] + have hdestination : mid destination = base destination := by + simp [mid, Reduction.MachineTransfer.tapesAt, Ne.symm sourceDestination, + destinationScratch] + have second := Reduction.MachineTransfer.transferAt_fromTapes scratch destination + (Ne.symm destinationScratch) id false secondLabel exit target atSecond mid ambient none + change (advance (TM2.step target))^[(mid scratch).length + 1] + (some ⟨some secondLabel, (ambient, none), mid⟩) = _ at second + rw [hscratch, hdestination] at second + simp only [List.length_reverse, List.reverse_reverse, List.map_id] at second + have restored : Reduction.MachineTransfer.tapesAt scratch destination mid [] + (base source ++ base destination) = + Reduction.MachineTransfer.tapesAt source destination base [] + (base source ++ base destination) := by + funext k + by_cases hs : k = source + · subst k + simp [Reduction.MachineTransfer.tapesAt, mid, sourceDestination, sourceScratch] + · by_cases hd : k = destination + · subst k + simp [Reduction.MachineTransfer.tapesAt] + · by_cases ht : k = scratch + · subst k + simp [Reduction.MachineTransfer.tapesAt, Ne.symm sourceScratch, + Ne.symm destinationScratch, scratchEmpty] + · simp [Reduction.MachineTransfer.tapesAt, mid, hs, hd, ht] + rw [restored] at second + have both := appendTrace _ first second + simpa only [show ((base source).length + 1) + ((base source).length + 1) = + 2 * ((base source).length + 1) by omega] using both + +theorem cancelStep_zero (current root reversedRecords output scratch : List Bool) + (g : Nat) (ambient : σ) (register : Option Bool) : + TM2.step program + ⟨some .cancel, (ambient, register), + memory current (encodeWord 0) root reversedRecords output (encodeWord g) scratch⟩ = + some ⟨some .records, (ambient, none), + memory current [] root reversedRecords output (encodeWord g) scratch⟩ := by + change some (TM2.stepAux cancelLoop _ _) = _ + simp [cancelLoop, TM2.stepAux, memory, encodeWord] + +theorem cancelStep_succ (current root reversedRecords output scratch : List Bool) + (f g : Nat) (ambient : σ) (register : Option Bool) : + TM2.step program + ⟨some .cancel, (ambient, register), + memory current (encodeWord (f + 1)) root reversedRecords output + (encodeWord (g + 1)) scratch⟩ = + some ⟨some .cancel, (ambient, none), + memory current (encodeWord f) root reversedRecords output (encodeWord g) scratch⟩ := by + change some (TM2.stepAux cancelLoop _ _) = _ + simp [cancelLoop, TM2.stepAux, memory, encodeWord, List.replicate_succ] + +theorem cancelTrace (current root reversedRecords output scratch : List Bool) + (f g : Nat) (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[f + 1] + (some ⟨some .cancel, (ambient, register), + memory current (encodeWord f) root reversedRecords output + (encodeWord (f + g)) scratch⟩) = + some ⟨some .records, (ambient, none), + memory current [] root reversedRecords output (encodeWord g) scratch⟩ := by + induction f generalizing register with + | zero => + simpa only [Nat.zero_add, Function.iterate_one, advance_some] using + cancelStep_zero current root reversedRecords output scratch g ambient register + | succ f ih => + rw [Function.iterate_succ_apply] + simp only [Nat.succ_add] + change (advance (TM2.step program))^[f + 1] + (TM2.step program + ⟨some .cancel, (ambient, register), + memory current (encodeWord (f + 1)) root reversedRecords output + (encodeWord ((f + g) + 1)) scratch⟩) = _ + rw [cancelStep_succ] + exact ih none + +def initialTapes (n f root : Nat) (records : List Bool) : Tape → List Bool := + memory (encodeWord n) (encodeWord f) (encodeWord root) records.reverse [] [] [] + +def finalTapes (n f root : Nat) (records : List Bool) : Tape → List Bool := + memory [] [] [] [] (encodeWords [n, n - f, root] ++ records) [] [] + +def totalTime (n f root recordLength : Nat) : Nat := + 2 * (n + 2) + (f + 1) + (recordLength + 1) + + 2 * (root + 2) + 2 * (n - f + 2) + 2 * (n + 2) + +theorem finishTrace (n f root : Nat) (records : List Bool) (hf : f ≤ n) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[totalTime n f root records.length] + (some ⟨some .copyOut, (ambient, register), initialTapes n f root records⟩) = + some ⟨none, (ambient, none), finalTapes n f root records⟩ := by + have copy := MachineCopy.copyTrace Tape.current Tape.gateCount Tape.scratch + (by decide) (by decide) (by decide) false Label.copyOut Label.copyBack + (some Label.cancel) program rfl rfl (initialTapes n f root records) rfl ambient register + simp only [initialTapes, memory, encodeWord_length, List.append_nil, update_gateCount] at copy + have cancel := cancelTrace (encodeWord n) (encodeWord root) records.reverse [] [] + f (n - f) ambient none + rw [show f + (n - f) = n by omega] at cancel + have reverse := Reduction.MachineTransfer.transferAt_fromTapes Tape.reversedRecords + Tape.output (by decide) id false Label.records (some Label.rootOut) program rfl + (memory (encodeWord n) [] (encodeWord root) records.reverse [] (encodeWord (n - f)) []) + ambient none + change (advance (TM2.step program))^[_] + (some ⟨some .records, (ambient, none), _⟩) = _ at reverse + simp only [memory, List.length_reverse, List.reverse_reverse, List.map_id, + List.append_nil, Reduction.MachineTransfer.tapesAt, update_reversedRecords, + update_output] at reverse + have rootPhase := prependTrace Tape.root Tape.output Tape.scratch + (by decide) (by decide) (by decide) Label.rootOut Label.rootBack (some Label.countOut) + program rfl rfl + (memory (encodeWord n) [] (encodeWord root) [] records (encodeWord (n - f)) []) + rfl ambient none + simp only [memory, encodeWord_length, Reduction.MachineTransfer.tapesAt, + update_root, update_output] at rootPhase + have countPhase := prependTrace Tape.gateCount Tape.output Tape.scratch + (by decide) (by decide) (by decide) Label.countOut Label.countBack (some Label.currentOut) + program rfl rfl + (memory (encodeWord n) [] [] [] (encodeWord root ++ records) (encodeWord (n - f)) []) + rfl ambient none + simp only [memory, encodeWord_length, Reduction.MachineTransfer.tapesAt, + update_gateCount, update_output] at countPhase + have currentPhase := prependTrace Tape.current Tape.output Tape.scratch + (by decide) (by decide) (by decide) Label.currentOut Label.currentBack none + program rfl rfl + (memory (encodeWord n) [] [] [] + (encodeWord (n - f) ++ (encodeWord root ++ records)) [] []) rfl ambient none + simp only [memory, encodeWord_length, Reduction.MachineTransfer.tapesAt, + update_current, update_output] at currentPhase + have all := appendTrace _ (appendTrace _ (appendTrace _ + (appendTrace _ (appendTrace _ copy cancel) reverse) rootPhase) countPhase) currentPhase + simpa only [totalTime, initialTapes, finalTapes, encodeWords, + List.append_nil, List.append_assoc, Nat.add_assoc] using all + +theorem finalTapes_output (n f root : Nat) (records : List Bool) : + finalTapes n f root records .output = encodeWords [n, n - f, root] ++ records := rfl + +theorem finalTapes_clean (n f root : Nat) (records : List Bool) (tape : Tape) + (h : tape ≠ .output) : finalTapes n f root records tape = [] := by + cases tape <;> simp_all [finalTapes, memory] + +theorem totalTime_eq (n f root recordLength : Nat) : + totalTime n f root recordLength = 4 * n + f + 2 * root + 2 * (n - f) + recordLength + 18 := by + unfold totalTime + ring + +theorem totalTime_le (n f root recordLength : Nat) (hf : f ≤ n) (hr : root < n) : + totalTime n f root recordLength ≤ 9 * n + recordLength + 18 := by + rw [totalTime_eq] + have hg := Nat.sub_le n f + omega + +theorem circuit_finalTapes (C : Circuit) : + finalTapes C.wires C.inputs C.output.val (recordsBits C.records) = + memory [] [] [] [] (circuitBits C) [] [] := by + have hcount : C.wires - C.inputs = C.gates.length := by + simp [Circuit.wires] + simp only [finalTapes, hcount, circuitBits, circuitWords, encodeWords_append, + recordsBits] + +theorem circuitTrace (C : Circuit) (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[ + totalTime C.wires C.inputs C.output.val (recordsBits C.records).length] + (some ⟨some .copyOut, (ambient, register), + initialTapes C.wires C.inputs C.output.val (recordsBits C.records)⟩) = + some ⟨none, (ambient, none), memory [] [] [] [] (circuitBits C) [] []⟩ := by + rw [← circuit_finalTapes] + exact finishTrace C.wires C.inputs C.output.val (recordsBits C.records) + (Nat.le_add_right _ _) ambient register + +def circuitInTime (C : Circuit) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some .copyOut, (ambient, register), + initialTapes C.wires C.inputs C.output.val (recordsBits C.records)⟩ + (some ⟨none, (ambient, none), memory [] [] [] [] (circuitBits C) [] []⟩) + (9 * C.wires + (recordsBits C.records).length + 18) where + steps := totalTime C.wires C.inputs C.output.val (recordsBits C.records).length + evals_in_steps := circuitTrace C ambient register + steps_le_m := totalTime_le _ _ _ _ (Nat.le_add_right _ _) C.output.isLt + +def placedCircuitInTime {K Λ : Type} [DecidableEq K] + (tape : Tape → K) (view : K → Option Tape) + (left : ∀ t, view (tape t) = some t) + (right : ∀ k t, view k = some t → tape t = k) + (labels : Label → Λ) (exit : Option Λ) (extra : K → List Bool) + (target : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State σ)) + (code : ∀ l, target (labels l) = Placement.statement tape labels exit (program l)) + (C : Circuit) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step target) + (Placement.configuration view labels exit extra + ⟨some .copyOut, (ambient, register), + initialTapes C.wires C.inputs C.output.val (recordsBits C.records)⟩) + (some (Placement.configuration view labels exit extra + ⟨none, (ambient, none), memory [] [] [] [] (circuitBits C) [] []⟩)) + (9 * C.wires + (recordsBits C.records).length + 18) := + liftExecutionInTime (TM2.step program) (TM2.step target) + (Placement.configuration view labels exit extra) + (Placement.step_simulation tape view left right labels exit extra program target code) + (circuitInTime C ambient register) + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.CircuitFinish + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/CircuitLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/CircuitLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..e7050a53231dc32c3d57cc9faa065db603d8bae6 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/CircuitLemmas.lean @@ -0,0 +1,848 @@ +import Mathlib.Data.List.FinRange +import Mathlib.Logic.Function.Basic +import Mathlib.Tactic.DeriveFintype +import OAI.Computability.PerfectCompleteness.Machines.BoundedExecution +import OAI.Computability.UniqueGames.Machines.MachineCompositionLemmas +import OAI.Computability.UniqueGames.Machines.MachineLemmas +import OAI.Computability.UniqueGames.Machines.MachineSubroutineLemmas +import OAI.Computability.UniqueGames.Machines.MachineTransducerCopy +import OAI.Computability.UniqueGames.Machines.Runtime +import OAI.Computability.UniqueGames.PCP.SourceMachine + +namespace OAI + +section + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin + +open Target + +inductive Gate where + | const (value : Bool) + | not (input : Nat) + | and (left right : Nat) + | or (left right : Nat) + deriving DecidableEq + +def Gate.Bounded (g : Gate) (bound : Nat) : Prop := + match g with + | .const _ => True + | .not x => x < bound + | .and x y | .or x y => x < bound ∧ y < bound + +def Gate.eval (g : Gate) (wires : Nat → Bool) : Bool := + match g with + | .const b => b + | .not x => !(wires x) + | .and x y => wires x && wires y + | .or x y => wires x || wires y + +theorem Gate.bounded_mono (g : Gate) {a b : Nat} (hab : a ≤ b) + (h : g.Bounded a) : g.Bounded b := by + cases g with + | const _ => trivial + | not _ => exact Nat.lt_of_lt_of_le h hab + | and _ _ => exact ⟨Nat.lt_of_lt_of_le h.1 hab, Nat.lt_of_lt_of_le h.2 hab⟩ + | or _ _ => exact ⟨Nat.lt_of_lt_of_le h.1 hab, Nat.lt_of_lt_of_le h.2 hab⟩ + +theorem Gate.eval_congr (g : Gate) {bound : Nat} (hg : g.Bounded bound) + (A B : Nat → Bool) (h : ∀ j, j < bound → A j = B j) : + g.eval A = g.eval B := by + cases g with + | const b => rfl + | not x => simp only [Gate.eval, h x hg] + | and x y => simp only [Gate.eval, h x hg.1, h y hg.2] + | or x y => simp only [Gate.eval, h x hg.1, h y hg.2] + +def Ordered (start : Nat) (gates : List Gate) : Prop := + ∀ i (hi : i < gates.length), gates[i].Bounded (start + i) + +def Consistent (start : Nat) (gates : List Gate) (wires : Nat → Bool) : Prop := + ∀ i (hi : i < gates.length), wires (start + i) = gates[i].eval wires + +@[simp] theorem ordered_nil (start : Nat) : Ordered start [] := by + intro i hi + simp at hi + +theorem ordered_cons (start : Nat) (g : Gate) (gs : List Gate) : + Ordered start (g :: gs) ↔ g.Bounded start ∧ Ordered (start + 1) gs := by + unfold Ordered + constructor + · intro h + refine ⟨?_, ?_⟩ + · have h0 := h 0 (by simp) + change g.Bounded (start + 0) at h0 + simpa only [Nat.add_zero] using h0 + · intro i hi + have ht := h (i + 1) (by simpa using hi) + change gs[i].Bounded (start + (i + 1)) at ht + simpa [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using ht + · rintro ⟨hg, hgs⟩ i hi + cases i with + | zero => simpa using hg + | succ i => + simpa [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using + hgs i (by simpa using hi) + +@[simp] theorem consistent_nil (start : Nat) (A : Nat → Bool) : + Consistent start [] A := by + intro i hi + simp at hi + +theorem consistent_cons (start : Nat) (g : Gate) (gs : List Gate) (A : Nat → Bool) : + Consistent start (g :: gs) A ↔ A start = g.eval A ∧ Consistent (start + 1) gs A := by + unfold Consistent + constructor + · intro h + refine ⟨?_, ?_⟩ + · have h0 := h 0 (by simp) + change A (start + 0) = g.eval A at h0 + simpa only [Nat.add_zero] using h0 + · intro i hi + have ht := h (i + 1) (by simpa using hi) + change A (start + (i + 1)) = gs[i].eval A at ht + simpa [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using ht + · rintro ⟨hg, hgs⟩ i hi + cases i with + | zero => simpa using hg + | succ i => + simpa [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using + hgs i (by simpa using hi) + +theorem consistent_append (start : Nat) (gs hs : List Gate) (A : Nat → Bool) : + Consistent start (gs ++ hs) A ↔ + Consistent start gs A ∧ Consistent (start + gs.length) hs A := by + induction gs generalizing start with + | nil => simp [Consistent] + | cons g gs ih => + simp only [List.cons_append, consistent_cons, ih, List.length_cons] + simp only [Nat.add_comm, Nat.add_left_comm, and_assoc] + +def run (start : Nat) : List Gate → (Nat → Bool) → (Nat → Bool) + | [], A => A + | g :: gs, A => run (start + 1) gs (Function.update A start (g.eval A)) + +theorem run_eq_of_lt (start : Nat) (gs : List Gate) (A : Nat → Bool) + (j : Nat) (hj : j < start) : run start gs A j = A j := by + induction gs generalizing start A with + | nil => rfl + | cons g gs ih => + rw [run, ih (start + 1) _ (by omega)] + exact Function.update_of_ne (by omega) _ _ + +theorem run_append (start : Nat) (gs hs : List Gate) (A : Nat → Bool) : + run start (gs ++ hs) A = run (start + gs.length) hs (run start gs A) := by + induction gs generalizing start A with + | nil => simp [run] + | cons g gs ih => + simpa [run, Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using + ih (start + 1) (Function.update A start (g.eval A)) + +@[simp] theorem run_singleton (start : Nat) (g : Gate) (A : Nat → Bool) : + run start [g] A = Function.update A start (g.eval A) := rfl + +@[simp] theorem run_singleton_here (start : Nat) (g : Gate) (A : Nat → Bool) : + run start [g] A start = g.eval A := by simp + +theorem run_singleton_other (start : Nat) (g : Gate) (A : Nat → Bool) + (j : Nat) (hj : j ≠ start) : run start [g] A j = A j := by + simp [hj] + +theorem Ordered.append {start : Nat} {gs hs : List Gate} + (hg : Ordered start gs) (hh : Ordered (start + gs.length) hs) : + Ordered start (gs ++ hs) := by + induction gs generalizing start with + | nil => simpa using hh + | cons g gs ih => + rcases (ordered_cons start g gs).mp hg with ⟨h0, ht⟩ + apply (ordered_cons start g (gs ++ hs)).mpr + refine ⟨h0, ih ht ?_⟩ + simpa [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using hh + +theorem run_consistent (start : Nat) (gs : List Gate) (A : Nat → Bool) + (h : Ordered start gs) : Consistent start gs (run start gs A) := by + induction gs generalizing start A with + | nil => exact consistent_nil start A + | cons g gs ih => + rcases (ordered_cons start g gs).mp h with ⟨hg, hgs⟩ + apply (consistent_cons start g gs _).mpr + constructor + · have hout : run start (g :: gs) A start = g.eval A := by + rw [run, run_eq_of_lt (start + 1) gs _ start (by omega)] + exact Function.update_self start _ _ + rw [hout] + exact Gate.eval_congr g hg A (run start (g :: gs) A) + (fun j hj => (run_eq_of_lt start (g :: gs) A j hj).symm) + · exact ih (start + 1) _ hgs + +theorem run_unique (start : Nat) (gs : List Gate) (A B : Nat → Bool) + (ho : Ordered start gs) (hc : Consistent start gs B) + (ha : ∀ j, j < start → A j = B j) : + ∀ j, j < start + gs.length → run start gs A j = B j := by + induction gs generalizing start A with + | nil => + intro j hj + exact ha j (by simpa using hj) + | cons g gs ih => + rcases (ordered_cons start g gs).mp ho with ⟨hg, hgs⟩ + rcases (consistent_cons start g gs B).mp hc with ⟨hb, hbs⟩ + have hnext : ∀ j, j < start + 1 → + Function.update A start (g.eval A) j = B j := by + intro j hj + by_cases heq : j = start + · subst j + rw [Function.update_self] + exact (Gate.eval_congr g hg A B ha).trans hb.symm + · rw [Function.update_of_ne heq] + exact ha j (by omega) + intro j hj + exact ih (start + 1) _ hgs hbs hnext j (by + simpa [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using hj) + +structure Circuit where + inputs : Nat + gates : List Gate + ordered : Ordered inputs gates + output : Fin (inputs + gates.length) + +abbrev Circuit.wires (C : Circuit) : Nat := C.inputs + C.gates.length + +def inputEnv {n : Nat} (input : Fin n → Bool) : Nat → Bool := + fun j => if h : j < n then input ⟨j, h⟩ else false + +def Circuit.evalWires (C : Circuit) (input : Fin C.inputs → Bool) : Nat → Bool := + run C.inputs C.gates (inputEnv input) + +def Circuit.eval (C : Circuit) (input : Fin C.inputs → Bool) : Bool := + C.evalWires input C.output.val + +theorem Circuit.evalWires_input (C : Circuit) (input : Fin C.inputs → Bool) + (j : Fin C.inputs) : C.evalWires input j.val = input j := by + rw [Circuit.evalWires, run_eq_of_lt _ _ _ _ j.isLt] + simp [inputEnv, j.isLt] + +theorem Circuit.evalWires_consistent (C : Circuit) (input : Fin C.inputs → Bool) : + Consistent C.inputs C.gates (C.evalWires input) := + run_consistent C.inputs C.gates (inputEnv input) C.ordered + +theorem Consistent.congr {start : Nat} {gs : List Gate} {A B : Nat → Bool} + (hc : Consistent start gs A) (ho : Ordered start gs) + (hab : ∀ j, j < start + gs.length → A j = B j) : + Consistent start gs B := by + intro i hi + have hbound := Gate.bounded_mono gs[i] (by omega : start + i ≤ start + gs.length) + (ho i hi) + calc + B (start + i) = A (start + i) := (hab _ (by omega)).symm + _ = gs[i].eval A := hc i hi + _ = gs[i].eval B := Gate.eval_congr gs[i] hbound A B hab + +def unitClause {n : Nat} (wire : Fin n) (positive : Bool) : Clause n := + #v[⟨wire, positive⟩, ⟨wire, positive⟩, ⟨wire, positive⟩] + +def gateClauses {n : Nat} (output : Fin n) : (g : Gate) → g.Bounded n → List (Clause n) + | .const b, _ => [unitClause output b, unitClause output b, unitClause output b] + | .not x, h => + let v : Fin n := ⟨x, h⟩ + [#v[⟨output, true⟩, ⟨v, true⟩, ⟨v, true⟩], + #v[⟨output, false⟩, ⟨v, false⟩, ⟨v, false⟩], + #v[⟨output, true⟩, ⟨v, true⟩, ⟨v, true⟩]] + | .and x y, h => + let vx : Fin n := ⟨x, h.1⟩ + let vy : Fin n := ⟨y, h.2⟩ + [#v[⟨output, false⟩, ⟨vx, true⟩, ⟨vx, true⟩], + #v[⟨output, false⟩, ⟨vy, true⟩, ⟨vy, true⟩], + #v[⟨output, true⟩, ⟨vx, false⟩, ⟨vy, false⟩]] + | .or x y, h => + let vx : Fin n := ⟨x, h.1⟩ + let vy : Fin n := ⟨y, h.2⟩ + [#v[⟨output, true⟩, ⟨vx, false⟩, ⟨vx, false⟩], + #v[⟨output, true⟩, ⟨vy, false⟩, ⟨vy, false⟩], + #v[⟨output, false⟩, ⟨vx, true⟩, ⟨vy, true⟩]] + +@[simp] theorem gateClauses_length {n : Nat} (output : Fin n) + (g : Gate) (h : g.Bounded n) : (gateClauses output g h).length = 3 := by + cases g <;> rfl + +theorem gateClauses_correct {n : Nat} (output : Fin n) (g : Gate) + (h : g.Bounded n) (A : Fin n → Bool) : + (∀ c ∈ gateClauses output g h, c.eval A = true) ↔ + A output = g.eval (inputEnv A) := by + cases g with + | const b => + simp only [gateClauses, List.forall_mem_cons] + cases b <;> cases ho : A output <;> + simp [unitClause, Clause.eval, Literal.eval, Gate.eval, ho] + | not x => + change x < n at h + simp only [gateClauses, List.forall_mem_cons] + cases ho : A output <;> cases hx : A ⟨x, h⟩ <;> + simp [Clause.eval, Literal.eval, Gate.eval, inputEnv, h, ho, hx] + | and x y => + change x < n ∧ y < n at h + simp only [gateClauses, List.forall_mem_cons] + cases ho : A output <;> cases hx : A ⟨x, h.1⟩ <;> cases hy : A ⟨y, h.2⟩ <;> + simp [Clause.eval, Literal.eval, Gate.eval, inputEnv, h.1, h.2, + ho, hx, hy] + | or x y => + change x < n ∧ y < n at h + simp only [gateClauses, List.forall_mem_cons] + cases ho : A output <;> cases hx : A ⟨x, h.1⟩ <;> cases hy : A ⟨y, h.2⟩ <;> + simp [Clause.eval, Literal.eval, Gate.eval, inputEnv, h.1, h.2, + ho, hx, hy] + +def Circuit.gateAt (C : Circuit) (i : Fin C.gates.length) : Gate := C.gates[i.val] + +def Circuit.gateOutput (C : Circuit) (i : Fin C.gates.length) : Fin C.wires := + ⟨C.inputs + i.val, by have hi := i.isLt; simp only [Circuit.wires]; omega⟩ + +theorem Circuit.gateBounded (C : Circuit) (i : Fin C.gates.length) : + (C.gateAt i).Bounded C.wires := + Gate.bounded_mono _ (by have hi := i.isLt; simp only [Circuit.wires]; omega) + (C.ordered i.val i.isLt) + +def Circuit.gateBlock (C : Circuit) (i : Fin C.gates.length) : List (Clause C.wires) := + gateClauses (C.gateOutput i) (C.gateAt i) (C.gateBounded i) + +def Circuit.toFormula (C : Circuit) : Formula where + «variables» := C.wires + clauses := (List.finRange C.gates.length).flatMap C.gateBlock ++ [unitClause C.output true] + +@[simp] theorem Circuit.toFormula_variables (C : Circuit) : + C.toFormula.variables = C.inputs + C.gates.length := rfl + +@[simp] theorem Circuit.toFormula_clause_count (C : Circuit) : + C.toFormula.clauses.length = 3 * C.gates.length + 1 := by + have h : ∀ is : List (Fin C.gates.length), + (is.flatMap C.gateBlock).length = 3 * is.length := by + intro is + induction is with + | nil => rfl + | cons i is ih => + simp only [List.flatMap_cons, List.length_append, Circuit.gateBlock, + gateClauses_length, List.length_cons] at * + omega + simp [Circuit.toFormula, h] + +theorem Circuit.toFormula_satisfied_iff (C : Circuit) (A : Fin C.wires → Bool) : + (∀ c ∈ C.toFormula.clauses, c.eval A = true) ↔ + Consistent C.inputs C.gates (inputEnv A) ∧ A C.output = true := by + constructor + · intro h + constructor + · intro i hi + let idx : Fin C.gates.length := ⟨i, hi⟩ + have hblock : ∀ c ∈ C.gateBlock idx, c.eval A = true := by + intro c hc + apply h c + apply List.mem_append.mpr + left + exact List.mem_flatMap.mpr ⟨idx, by simp, hc⟩ + have heq := (gateClauses_correct (C.gateOutput idx) (C.gateAt idx) + (C.gateBounded idx) A).mp hblock + have hlt : C.inputs + i < C.wires := by simp only [Circuit.wires]; omega + simpa [inputEnv, hlt, Circuit.gateOutput, Circuit.gateAt, idx] using heq + · have hu := h (unitClause C.output true) + (List.mem_append.mpr (Or.inr (List.mem_singleton.mpr rfl))) + simpa [unitClause, Clause.eval, Literal.eval] using hu + · rintro ⟨hc, ho⟩ c hmem + rcases List.mem_append.mp hmem with hblock | hunit + · obtain ⟨i, _, hci⟩ := List.mem_flatMap.mp hblock + apply (gateClauses_correct (C.gateOutput i) (C.gateAt i) + (C.gateBounded i) A).mpr ?_ c hci + have heq := hc i.val i.isLt + have hlt : C.inputs + i.val < C.wires := (C.gateOutput i).isLt + simpa [inputEnv, hlt, Circuit.gateOutput, Circuit.gateAt] using heq + · have heq : c = unitClause C.output true := List.mem_singleton.mp hunit + subst c + simpa [unitClause, Clause.eval, Literal.eval] using ho + +def Circuit.restrictAssignment (C : Circuit) (A : Fin C.wires → Bool) : + Fin C.inputs → Bool := fun j => + A ⟨j.val, by have hj := j.isLt; simp only [Circuit.wires]; omega⟩ + +theorem Circuit.toFormula_satisfiable_iff_eval (C : Circuit) : + C.toFormula.Satisfiable ↔ ∃ input : Fin C.inputs → Bool, C.eval input = true := by + constructor + · rintro ⟨A, hA⟩ + rcases (C.toFormula_satisfied_iff A).mp hA with ⟨hc, ho⟩ + refine ⟨C.restrictAssignment A, ?_⟩ + have hinput : ∀ j, j < C.inputs → + inputEnv (C.restrictAssignment A) j = inputEnv A j := by + intro j hj + have ht : j < C.wires := by simp only [Circuit.wires]; omega + simp [inputEnv, hj, ht, Circuit.restrictAssignment] + have hu := run_unique C.inputs C.gates (inputEnv (C.restrictAssignment A)) + (inputEnv A) C.ordered hc hinput C.output.val C.output.isLt + have heval : C.eval (C.restrictAssignment A) = A C.output := by + have hout : C.output.val < C.wires := C.output.isLt + simpa [Circuit.eval, Circuit.evalWires, inputEnv, hout] using hu + exact heval.trans ho + · rintro ⟨input, hinput⟩ + let A : Fin C.wires → Bool := fun j => C.evalWires input j.val + refine ⟨A, (C.toFormula_satisfied_iff A).mpr ⟨?_, hinput⟩⟩ + apply Consistent.congr (C.evalWires_consistent input) C.ordered + intro j hj + have ht : j < C.wires := hj + simp [inputEnv, ht, A] + +theorem Circuit.toFormula_extending_iff_eval (C : Circuit) (input : Fin C.inputs → Bool) : + (∃ A : Fin C.wires → Bool, C.restrictAssignment A = input ∧ + ∀ c ∈ C.toFormula.clauses, c.eval A = true) ↔ C.eval input = true := by + constructor + · rintro ⟨A, hext, hA⟩ + rcases (C.toFormula_satisfied_iff A).mp hA with ⟨hc, ho⟩ + have hinput : ∀ j, j < C.inputs → inputEnv input j = inputEnv A j := by + intro j hj + rw [← hext] + have ht : j < C.wires := by simp only [Circuit.wires]; omega + simp [inputEnv, hj, ht, Circuit.restrictAssignment] + have hu := run_unique C.inputs C.gates (inputEnv input) (inputEnv A) + C.ordered hc hinput C.output.val C.output.isLt + have heval : C.eval input = A C.output := by + have hout : C.output.val < C.wires := C.output.isLt + simpa [Circuit.eval, Circuit.evalWires, inputEnv, hout] using hu + exact heval.trans ho + · intro hinput + let A : Fin C.wires → Bool := fun j => C.evalWires input j.val + refine ⟨A, ?_, (C.toFormula_satisfied_iff A).mpr ⟨?_, hinput⟩⟩ + · funext j + simpa [Circuit.restrictAssignment, A] using C.evalWires_input input j + · apply Consistent.congr (C.evalWires_consistent input) C.ordered + intro j hj + have ht : j < C.wires := hj + simp [inputEnv, ht, A] + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin + +end + +section + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.Bounds + +open Polynomial + +noncomputable def pairLengthPolynomial (q : Polynomial ℕ) : Polynomial ℕ := + C 2 * X + q + 1 + +noncomputable def horizonPolynomial (p q : Polynomial ℕ) : Polynomial ℕ := + p.comp (pairLengthPolynomial q) + +noncomputable def capacityPolynomial (p q : Polynomial ℕ) (pushes : ℕ) : Polynomial ℕ := + pairLengthPolynomial q + C pushes * horizonPolynomial p q + +@[simp] theorem pairLengthPolynomial_eval (q : Polynomial ℕ) (n : ℕ) : + (pairLengthPolynomial q).eval n = 2 * n + q.eval n + 1 := by + simp [pairLengthPolynomial] + +@[simp] theorem horizonPolynomial_eval (p q : Polynomial ℕ) (n : ℕ) : + (horizonPolynomial p q).eval n = p.eval (2 * n + q.eval n + 1) := by + simp [horizonPolynomial, Polynomial.eval_comp] + +@[simp] theorem capacityPolynomial_eval (p q : Polynomial ℕ) (pushes n : ℕ) : + (capacityPolynomial p q pushes).eval n = + 2 * n + q.eval n + 1 + pushes * p.eval (2 * n + q.eval n + 1) := by + simp [capacityPolynomial] + +theorem paired_length_le (q : Polynomial ℕ) (n witnessLength : ℕ) + (hw : witnessLength ≤ q.eval n) : + 2 * n + witnessLength + 1 ≤ (pairLengthPolynomial q).eval n := by + rw [pairLengthPolynomial_eval] + omega + +theorem one_le_pairLength (q : Polynomial ℕ) (n : ℕ) : + 1 ≤ (pairLengthPolynomial q).eval n := by + rw [pairLengthPolynomial_eval] + omega + +theorem pairLength_le_capacity (p q : Polynomial ℕ) (pushes n : ℕ) : + (pairLengthPolynomial q).eval n ≤ (capacityPolynomial p q pushes).eval n := by + simp only [capacityPolynomial, Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_C] + exact Nat.le_add_right _ _ + +theorem one_le_capacity (p q : Polynomial ℕ) (pushes n : ℕ) : + 1 ≤ (capacityPolynomial p q pushes).eval n := + (one_le_pairLength q n).trans (pairLength_le_capacity p q pushes n) + +theorem transition_prefix_le_capacity (p q : Polynomial ℕ) (pushes n inputLength used extra : ℕ) + (hi : inputLength ≤ (pairLengthPolynomial q).eval n) + (ht : used < (horizonPolynomial p q).eval n) (he : extra ≤ pushes) : + inputLength + used * pushes + extra ≤ (capacityPolynomial p q pushes).eval n := by + have hu := Nat.mul_le_mul_right pushes (Nat.succ_le_of_lt ht) + simp only [capacityPolynomial, Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_C] + calc + inputLength + used * pushes + extra ≤ + (pairLengthPolynomial q).eval n + (used + 1) * pushes := by + rw [Nat.add_mul, Nat.one_mul] + omega + _ ≤ (pairLengthPolynomial q).eval n + (horizonPolynomial p q).eval n * pushes := + Nat.add_le_add_left hu _ + _ = _ := by rw [Nat.mul_comm ((horizonPolynomial p q).eval n) pushes] + +theorem verifier_time_le_horizon (p q : Polynomial ℕ) (n witnessLength : ℕ) + (hw : witnessLength ≤ q.eval n) : + p.eval (2 * n + witnessLength + 1) ≤ (horizonPolynomial p q).eval n := by + rw [horizonPolynomial, Polynomial.eval_comp] + exact MachineComposition.natPolynomial_eval_mono p (paired_length_le q n witnessLength hw) + +theorem horizon_monotone (p q : Polynomial ℕ) : + Monotone (fun n => (horizonPolynomial p q).eval n) := + fun _ _ h => MachineComposition.natPolynomial_eval_mono _ h + +theorem capacity_monotone (p q : Polynomial ℕ) (pushes : ℕ) : + Monotone (fun n => (capacityPolynomial p q pushes).eval n) := + fun _ _ h => MachineComposition.natPolynomial_eval_mono _ h + +theorem execution_stack_length_le_capacity (tm : Turing.FinTM2) + (p q : Polynomial ℕ) (n : ℕ) (input : List (tm.Γ tm.k₀)) + (hi : input.length ≤ (pairLengthPolynomial q).eval n) + (finish : tm.Cfg) (budget : ℕ) + (ht : budget ≤ (horizonPolynomial p q).eval n) + (run : StateTransition.EvalsToInTime tm.step (Turing.initList tm input) + (some finish) budget) (k : tm.K) : + (finish.stk k).length ≤ (capacityPolynomial p q (Runtime.programPushBound tm)).eval n := by + have hs := Runtime.executionSizeBound tm.step (fun cfg => (cfg.stk k).length) + (Runtime.programPushBound tm) (Runtime.stepStackLength tm k) run + have hinit := (Runtime.initialStackLength tm input k).trans hi + have hg := Nat.mul_le_mul_right (Runtime.programPushBound tm) ht + calc + (finish.stk k).length ≤ ((Turing.initList tm input).stk k).length + + budget * Runtime.programPushBound tm := hs + _ ≤ (pairLengthPolynomial q).eval n + + (horizonPolynomial p q).eval n * Runtime.programPushBound tm := + Nat.add_le_add hinit hg + _ = _ := by simp [capacityPolynomial, Nat.mul_comm] + +theorem stackCapacity_le_polynomial (tm : Turing.FinTM2) + (p q : Polynomial ℕ) (n : ℕ) (input : List (tm.Γ tm.k₀)) + (hi : input.length ≤ (pairLengthPolynomial q).eval n) : + BoundedExecution.stackCapacity tm input ((horizonPolynomial p q).eval n) ≤ + (capacityPolynomial p q (Runtime.programPushBound tm)).eval n := by + simpa only [BoundedExecution.stackCapacity, capacityPolynomial, + Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_C, Nat.mul_comm] using + Nat.add_le_add_right hi ((horizonPolynomial p q).eval n * Runtime.programPushBound tm) + +theorem run_stack_length_le_capacity (tm : Turing.FinTM2) + (p q : Polynomial ℕ) (n : ℕ) (input : List (tm.Γ tm.k₀)) + (hi : input.length ≤ (pairLengthPolynomial q).eval n) + (time : ℕ) (ht : time ≤ (horizonPolynomial p q).eval n) (k : tm.K) : + ((BoundedExecution.run tm input time).stk k).length ≤ + (capacityPolynomial p q (Runtime.programPushBound tm)).eval n := + (BoundedExecution.run_stack_le tm input _ time ht k).trans + (stackCapacity_le_polynomial tm p q n input hi) + +theorem run_statement_budget_le_capacity (tm : Turing.FinTM2) + (p q : Polynomial ℕ) (n : ℕ) (input : List (tm.Γ tm.k₀)) + (hi : input.length ≤ (pairLengthPolynomial q).eval n) + (time : ℕ) (ht : time < (horizonPolynomial p q).eval n) + (label : tm.Λ) (k : tm.K) : + ((BoundedExecution.run tm input time).stk k).length + + Runtime.statementPushBound (tm.m label) ≤ + (capacityPolynomial p q (Runtime.programPushBound tm)).eval n := + (BoundedExecution.statement_budget tm input _ time ht label k).trans + (stackCapacity_le_polynomial tm p q n input hi) + +noncomputable def configurationWidthPolynomial (p q : Polynomial ℕ) + (pushes controlBits alphabetBits : ℕ) : Polynomial ℕ := + C controlBits + capacityPolynomial p q pushes * C alphabetBits + +noncomputable def transitionGatesPolynomial (p q : Polynomial ℕ) + (pushes controlBits alphabetBits expressionCost : ℕ) : Polynomial ℕ := + C expressionCost * configurationWidthPolynomial p q pushes controlBits alphabetBits + +noncomputable def tableauGatesPolynomial (p q : Polynomial ℕ) + (pushes controlBits alphabetBits expressionCost : ℕ) : Polynomial ℕ := + horizonPolynomial p q * + transitionGatesPolynomial p q pushes controlBits alphabetBits expressionCost + +@[simp] theorem configurationWidthPolynomial_eval (p q : Polynomial ℕ) + (pushes controlBits alphabetBits n : ℕ) : + (configurationWidthPolynomial p q pushes controlBits alphabetBits).eval n = + controlBits + (capacityPolynomial p q pushes).eval n * alphabetBits := by + simp [configurationWidthPolynomial] + +@[simp] theorem transitionGatesPolynomial_eval (p q : Polynomial ℕ) + (pushes controlBits alphabetBits expressionCost n : ℕ) : + (transitionGatesPolynomial p q pushes controlBits alphabetBits expressionCost).eval n = + expressionCost * (controlBits + (capacityPolynomial p q pushes).eval n * alphabetBits) := by + simp [transitionGatesPolynomial] + +@[simp] theorem tableauGatesPolynomial_eval (p q : Polynomial ℕ) + (pushes controlBits alphabetBits expressionCost n : ℕ) : + (tableauGatesPolynomial p q pushes controlBits alphabetBits expressionCost).eval n = + (horizonPolynomial p q).eval n * expressionCost * + (controlBits + (capacityPolynomial p q pushes).eval n * alphabetBits) := by + simp only [tableauGatesPolynomial, Polynomial.eval_mul, transitionGatesPolynomial_eval] + exact (Nat.mul_assoc _ _ _).symm + +noncomputable def formulaBitsPolynomial (varBound clauseBound : Polynomial ℕ) : Polynomial ℕ := + varBound + clauseBound + C 2 + clauseBound * (C 3 * (varBound + C 2)) + +@[simp] theorem formulaBitsPolynomial_eval (varBound clauseBound : Polynomial ℕ) (n : ℕ) : + (formulaBitsPolynomial varBound clauseBound).eval n = + varBound.eval n + clauseBound.eval n + 2 + + clauseBound.eval n * (3 * (varBound.eval n + 2)) := by + simp [formulaBitsPolynomial] + +theorem formulaBits_length_le_polynomial (F : Target.Formula) + (varBound clauseBound : Polynomial ℕ) (n : ℕ) + (hv : F.variables ≤ varBound.eval n) + (hc : F.clauses.length ≤ clauseBound.eval n) : + (formulaBits F).length ≤ (formulaBitsPolynomial varBound clauseBound).eval n := by + refine (formulaBits_length_le F).trans ?_ + rw [formulaBitsPolynomial_eval] + exact Nat.add_le_add + (Nat.add_le_add_right (Nat.add_le_add hv hc) 2) + (Nat.mul_le_mul hc (Nat.mul_le_mul_left 3 (Nat.add_le_add_right hv 2))) + +noncomputable def circuitVariablesPolynomial (inputs gates : Polynomial ℕ) : Polynomial ℕ := + inputs + gates + +noncomputable def circuitClausesPolynomial (gates : Polynomial ℕ) : Polynomial ℕ := + C 3 * gates + 1 + +noncomputable def circuitBitsPolynomial (inputs gates : Polynomial ℕ) : Polynomial ℕ := + formulaBitsPolynomial (circuitVariablesPolynomial inputs gates) + (circuitClausesPolynomial gates) + +@[simp] theorem circuitVariablesPolynomial_eval (inputs gates : Polynomial ℕ) (n : ℕ) : + (circuitVariablesPolynomial inputs gates).eval n = inputs.eval n + gates.eval n := by + simp [circuitVariablesPolynomial] + +@[simp] theorem circuitClausesPolynomial_eval (gates : Polynomial ℕ) (n : ℕ) : + (circuitClausesPolynomial gates).eval n = 3 * gates.eval n + 1 := by + simp [circuitClausesPolynomial] + +@[simp] theorem circuitBitsPolynomial_eval (inputs gates : Polynomial ℕ) (n : ℕ) : + (circuitBitsPolynomial inputs gates).eval n = + (inputs.eval n + gates.eval n) + (3 * gates.eval n + 1) + 2 + + (3 * gates.eval n + 1) * (3 * ((inputs.eval n + gates.eval n) + 2)) := by + simp [circuitBitsPolynomial] + +theorem circuit_formulaBits_length_le (F : Target.Formula) (inputCount gateCount : ℕ) + (hv : F.variables ≤ inputCount + gateCount) + (hc : F.clauses.length ≤ 3 * gateCount + 1) : + (formulaBits F).length ≤ + (inputCount + gateCount) + (3 * gateCount + 1) + 2 + + (3 * gateCount + 1) * (3 * ((inputCount + gateCount) + 2)) := by + exact (formulaBits_length_le F).trans + (Nat.add_le_add (Nat.add_le_add_right (Nat.add_le_add hv hc) 2) + (Nat.mul_le_mul hc (Nat.mul_le_mul_left 3 (Nat.add_le_add_right hv 2)))) + +theorem circuit_formulaBits_length_le_polynomial (F : Target.Formula) + (inputCount gateCount : ℕ) (inputs gates : Polynomial ℕ) (n : ℕ) + (hi : inputCount ≤ inputs.eval n) (hg : gateCount ≤ gates.eval n) + (hv : F.variables ≤ inputCount + gateCount) + (hc : F.clauses.length ≤ 3 * gateCount + 1) : + (formulaBits F).length ≤ (circuitBitsPolynomial inputs gates).eval n := by + apply formulaBits_length_le_polynomial + · simpa using hv.trans (Nat.add_le_add hi hg) + · simpa using hc.trans (Nat.add_le_add_right (Nat.mul_le_mul_left 3 hg) 1) + +theorem toFormula_bits_length_le (circuit : Circuit) : + (formulaBits circuit.toFormula).length ≤ + (circuit.inputs + circuit.gates.length) + (3 * circuit.gates.length + 1) + 2 + + (3 * circuit.gates.length + 1) * + (3 * ((circuit.inputs + circuit.gates.length) + 2)) := + circuit_formulaBits_length_le circuit.toFormula circuit.inputs circuit.gates.length + (Circuit.toFormula_variables circuit).le (Circuit.toFormula_clause_count circuit).le + +theorem toFormula_bits_length_le_polynomial (circuit : Circuit) + (inputs gates : Polynomial ℕ) (n : ℕ) + (hi : circuit.inputs ≤ inputs.eval n) (hg : circuit.gates.length ≤ gates.eval n) : + (formulaBits circuit.toFormula).length ≤ (circuitBitsPolynomial inputs gates).eval n := + circuit_formulaBits_length_le_polynomial circuit.toFormula circuit.inputs circuit.gates.length + inputs gates n hi hg + (Circuit.toFormula_variables circuit).le (Circuit.toFormula_clause_count circuit).le + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.Bounds + +end + +section + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.CircuitProducerModel + +open Turing +open UniqueGamesTheorem.Foundations.Hastad +open UniqueGamesTheorem.Reduction + +def gateTemplate (tag : Fin 5) (position : Fin 9) : Fin 3 × Bool := + match tag.val with + | 0 => (0, false) + | 1 => (0, true) + | 2 => [(0, true), (1, true), (1, true), + (0, false), (1, false), (1, false), + (0, true), (1, true), (1, true)].get position + | 3 => [(0, false), (1, true), (1, true), + (0, false), (2, true), (2, true), + (0, true), (1, false), (2, false)].get position + | _ => [(0, true), (1, false), (1, false), + (0, true), (2, false), (2, false), + (0, false), (1, true), (2, true)].get position + +structure Record where + tag : Fin 5 + output : Nat + first : Nat + second : Nat + deriving DecidableEq + +def Record.slot (r : Record) (j : Fin 3) : Nat := + match j.val with + | 0 => r.output + | 1 => r.first + | _ => r.second + +def Record.words (r : Record) : List Nat := + [r.tag.val, r.output, r.first, r.second] + +def Record.bits (r : Record) : List Bool := encodeWords r.words + +def Record.fieldValue (r : Record) (j : Fin 4) : Nat := + match j.val with + | 0 => r.tag.val + | 1 => r.output + | 2 => r.first + | _ => r.second + +def templateWords (tag : Fin 5) (values : Fin 3 → Nat) : List Nat := + (List.finRange 9).flatMap fun j => + [values (gateTemplate tag j).1, if (gateTemplate tag j).2 then 1 else 0] + +def Record.outputWords (r : Record) : List Nat := templateWords r.tag r.slot +def Record.outputBits (r : Record) : List Bool := encodeWords r.outputWords + +def outputWords (selected : Nat) : List Nat := + [selected, 1, selected, 1, selected, 1] + +inductive Tape where + | input | header | counter | selected | field (slot : Fin 4) + | scratch | reversed | output + deriving DecidableEq, Fintype + +inductive Context where + | header (slot : Fin 2) + | gate (tag : Fin 5) (position : Fin 9) + | output (position : Fin 3) + deriving DecidableEq, Fintype + +abbrev State := (Unit × Context) × Option Bool +abbrev Alphabet (_ : Tape) := Bool + +inductive Label where + | headerStart (slot : Fin 3) + | headerLoop (slot : Fin 3) + | setup (context : Context) + | scan (context : Context) + | emit (context control : Context) (symbol : Bool) + | restore (context : Context) + | clearHeader | guard + | fieldStart (slot : Fin 4) + | fieldLoop (slot : Fin 4) + | decodeTag + | cleanup (slot : Fin 4) + | finalCounter | clearSelected | finalReverse + deriving DecidableEq, Fintype + +def defaultControl : Context := .header 0 +def initialState : State := (((), defaultControl), none) + +def headerTape (slot : Fin 3) : Tape := + match slot.val with + | 0 => .header + | 1 => .counter + | _ => .selected + +def headerNext (slot : Fin 3) : Option Label := + if h : slot.val + 1 < 3 then some (.headerStart ⟨slot.val + 1, h⟩) + else some (.setup (.header 0)) + +def contextSource : Context → Tape + | .header j => if j.val = 0 then .header else .counter + | .gate tag j => .field ⟨(gateTemplate tag j).1.val + 1, by + have := (gateTemplate tag j).1.isLt + omega⟩ + | .output _ => .selected + +def affineEmit (scale offset : Nat) : Bool → List Bool + | true => List.replicate scale true + | false => encodeWord offset + +def literalEmit (positive : Bool) : Bool → List Bool + | true => [true] + | false => [false] ++ encodeWord (if positive then 1 else 0) + +def emission : Context → Bool → List Bool + | .header j => if j.val = 0 then affineEmit 1 0 else affineEmit 3 1 + | .gate tag j => literalEmit (gateTemplate tag j).2 + | .output _ => literalEmit true + +def contextNext : Context → Option Label + | .header j => if j.val = 0 then some (.setup (.header 1)) else some .clearHeader + | .gate tag j => if h : j.val + 1 < 9 then + some (.setup (.gate tag ⟨j.val + 1, h⟩)) else some (.cleanup 0) + | .output j => if h : j.val + 1 < 3 then + some (.setup (.output ⟨j.val + 1, h⟩)) else some .finalCounter + +def cleanupNext (j : Fin 4) : Label := + if h : j.val + 1 < 4 then .cleanup ⟨j.val + 1, h⟩ else .guard + +def drain (tape : Tape) (again next : Label) : TM2.Stmt Alphabet Label State := + .pop tape (fun state head => (state.1, head)) + (.branch (fun state => state.2.isSome) + (.goto fun _ => again) + (.load (fun state => (state.1, none)) (.goto fun _ => next))) + +def resetGoto (next : Label) : TM2.Stmt Alphabet Label State := + .load (fun _ => initialState) (.goto fun _ => next) + +def tagDecoder : Nat → Fin 5 → TM2.Stmt Alphabet Label State + | 0, tag => .pop (.field 0) (fun state head => (state.1, head)) + (.branch (fun state => state.2.getD false) .halt + (resetGoto (.setup (.gate tag 0)))) + | fuel + 1, tag => .pop (.field 0) (fun state head => (state.1, head)) + (.branch (fun state => state.2.getD false) + (tagDecoder fuel ⟨min (tag.val + 1) 4, by omega⟩) + (resetGoto (.setup (.gate tag 0)))) + +def program : Label → TM2.Stmt Alphabet Label State + | .headerStart j => SourceMachine.fieldStart (headerTape j) (.headerLoop j) + | .headerLoop j => SourceMachine.fieldLoop .input (headerTape j) (.headerLoop j) + (headerNext j) + | .setup c => .load (fun _ => (((), c), none)) (.goto fun _ => .scan c) + | .scan c => MachineTransducerCopy.scanLoop (contextSource c) .scratch + defaultControl (fun q b => .emit c q b) (.restore c) + | .emit c q b => MachineTransducerCopy.emitter .reversed (fun q _ => q) + emission (.scan c) q b + | .restore c => MachineTransfer.loopAt .scratch (contextSource c) id false + (.restore c) (contextNext c) + | .clearHeader => drain .header .clearHeader .guard + | .guard => MachineUnaryCounter.guard .counter (.fieldStart 0) (.setup (.output 0)) + | .fieldStart j => SourceMachine.fieldStart (.field j) (.fieldLoop j) + | .fieldLoop j => SourceMachine.fieldLoop .input (.field j) (.fieldLoop j) + (SourceMachine.fieldNext Label.fieldStart (some .decodeTag) j) + | .decodeTag => tagDecoder 4 0 + | .cleanup j => drain (.field j) (.cleanup j) (cleanupNext j) + | .finalCounter => .pop .counter (fun state _ => (state.1, none)) + (.goto fun _ => .clearSelected) + | .clearSelected => drain .selected .clearSelected .finalReverse + | .finalReverse => MachineTransfer.loopAt .reversed .output id false .finalReverse none + +def machine : FinTM2 where + K := Tape + k₀ := .input + k₁ := .output + Γ := Alphabet + Λ := Label + main := .headerStart 0 + σ := State + initialState := initialState + m := program + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.CircuitProducerModel + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/CircuitProducerStagesLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/CircuitProducerStagesLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..d5fd2caaa496dcec59e1b3ded9134f1cc31ab759 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/CircuitProducerStagesLemmas.lean @@ -0,0 +1,904 @@ +import Mathlib.Logic.Function.Basic +import Mathlib.Tactic.FinCases +import OAI.Computability.PerfectCompleteness.Machines.CircuitEmission +import OAI.Computability.PerfectCompleteness.Machines.CircuitEncodingLemmas +import OAI.Computability.PerfectCompleteness.Machines.CircuitLemmas +import OAI.Computability.UniqueGames.Machines.MachineCompositionLemmas + +namespace OAI + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.CircuitProducerStages + +open Turing +open UniqueGamesTheorem.Reduction +open CircuitProducerModel + +theorem drainStep_cons (tape : Tape) (again next : Label) + (atAgain : program again = drain tape again next) + (base : Tape → List Bool) (bit : Bool) (input : List Bool) + (control : Unit × Context) (register : Option Bool) : + TM2.step program + ⟨some again, (control, register), Function.update base tape (bit :: input)⟩ = + some ⟨some again, (control, some bit), Function.update base tape input⟩ := by + change some (TM2.stepAux (program again) (control, register) + (Function.update base tape (bit :: input))) = _ + rw [atAgain] + simp [drain, TM2.stepAux] + +theorem drainStep_nil (tape : Tape) (again next : Label) + (atAgain : program again = drain tape again next) + (base : Tape → List Bool) (control : Unit × Context) (register : Option Bool) : + TM2.step program + ⟨some again, (control, register), Function.update base tape []⟩ = + some ⟨some next, (control, none), Function.update base tape []⟩ := by + change some (TM2.stepAux (program again) (control, register) + (Function.update base tape [])) = _ + rw [atAgain] + simp [drain, TM2.stepAux] + +theorem drainTrace (tape : Tape) (again next : Label) + (atAgain : program again = drain tape again next) + (base : Tape → List Bool) (input : List Bool) + (control : Unit × Context) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[input.length + 1] + (some ⟨some again, (control, register), Function.update base tape input⟩) = + some ⟨some next, (control, none), Function.update base tape []⟩ := by + induction input generalizing register with + | nil => + simpa only [List.length_nil, Nat.zero_add, Function.iterate_one, + MachineComposition.advance_some] using + drainStep_nil tape again next atAgain base control register + | cons bit input ih => + rw [List.length_cons, Function.iterate_succ_apply] + change (MachineComposition.advance (TM2.step program))^[input.length + 1] + (TM2.step program ⟨some again, (control, register), + Function.update base tape (bit :: input)⟩) = _ + rw [drainStep_cons tape again next atAgain, ih] + +theorem drainTrace_base (tape : Tape) (again next : Label) + (atAgain : program again = drain tape again next) + (base : Tape → List Bool) (control : Unit × Context) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[(base tape).length + 1] + (some ⟨some again, (control, register), base⟩) = + some ⟨some next, (control, none), Function.update base tape []⟩ := by + simpa only [Function.update_eq_self] using + drainTrace tape again next atAgain base (base tape) control register + +def drainInTime (tape : Tape) (again next : Label) + (atAgain : program again = drain tape again next) + (base : Tape → List Bool) (control : Unit × Context) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some again, (control, register), base⟩ + (some ⟨some next, (control, none), Function.update base tape []⟩) + ((base tape).length + 1) where + steps := (base tape).length + 1 + evals_in_steps := drainTrace_base tape again next atAgain base control register + steps_le_m := Nat.le_refl _ + +theorem tagStep (tag : Fin 5) (base : Tape → List Bool) (state : State) + (htag : base (.field 0) = encodeWord tag.val) : + TM2.step program ⟨some .decodeTag, state, base⟩ = + some ⟨some (.setup (.gate tag 0)), initialState, + Function.update base (.field 0) []⟩ := by + fin_cases tag <;> + simp [TM2.step, TM2.stepAux, program, tagDecoder, resetGoto, initialState, + encodeWord, htag] + +def tagInTime (tag : Fin 5) (base : Tape → List Bool) (state : State) + (htag : base (.field 0) = encodeWord tag.val) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some .decodeTag, state, base⟩ + (some ⟨some (.setup (.gate tag 0)), initialState, + Function.update base (.field 0) []⟩) 1 where + steps := 1 + evals_in_steps := tagStep tag base state htag + steps_le_m := Nat.le_refl _ + +def clearFields (base : Tape → List Bool) : Tape → List Bool := + Function.update (Function.update (Function.update (Function.update base + (.field 0) []) (.field 1) []) (.field 2) []) (.field 3) [] + +@[simp] theorem clearFields_field (base : Tape → List Bool) (j : Fin 4) : + clearFields base (.field j) = [] := by + fin_cases j <;> simp [clearFields] + +theorem clearFields_other (base : Tape → List Bool) (tape : Tape) + (h : ∀ j, tape ≠ .field j) : clearFields base tape = base tape := by + simp [clearFields, h] + +def cleanupSteps (base : Tape → List Bool) : Nat := + (base (.field 0)).length + (base (.field 1)).length + + (base (.field 2)).length + (base (.field 3)).length + 4 + +theorem cleanupTrace (base : Tape → List Bool) (control : Unit × Context) + (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[cleanupSteps base] + (some ⟨some (.cleanup 0), (control, register), base⟩) = + some ⟨some .guard, (control, none), clearFields base⟩ := by + let b1 := Function.update base (.field 0) [] + let b2 := Function.update b1 (.field 1) [] + let b3 := Function.update b2 (.field 2) [] + have h0 := drainTrace_base (.field 0) (.cleanup 0) (.cleanup 1) rfl + base control register + have h1 := drainTrace_base (.field 1) (.cleanup 1) (.cleanup 2) rfl b1 control none + have h2 := drainTrace_base (.field 2) (.cleanup 2) (.cleanup 3) rfl b2 control none + have h3 := drainTrace_base (.field 3) (.cleanup 3) .guard rfl b3 control none + have hn : cleanupSteps base = ((b3 (.field 3)).length + 1) + + ((b2 (.field 2)).length + 1) + ((b1 (.field 1)).length + 1) + + ((base (.field 0)).length + 1) := by + simp [cleanupSteps, b1, b2, b3] + omega + rw [hn, Function.iterate_add_apply, h0, Function.iterate_add_apply, h1, + Function.iterate_add_apply, h2, h3] + rfl + +def cleanupInTime (base : Tape → List Bool) (control : Unit × Context) + (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (.cleanup 0), (control, register), base⟩ + (some ⟨some .guard, (control, none), clearFields base⟩) + (cleanupSteps base) where + steps := cleanupSteps base + evals_in_steps := cleanupTrace base control register + steps_le_m := Nat.le_refl _ + +def finishTapes (base : Tape → List Bool) : Tape → List Bool := + MachineTransfer.tapesAt .reversed .output + (Function.update (Function.update base .counter []) .selected []) [] + ((base .reversed).reverse ++ base .output) + +theorem counterStep (base : Tape → List Bool) (hcounter : base .counter = [false]) : + TM2.step program ⟨some .finalCounter, initialState, base⟩ = + some ⟨some .clearSelected, initialState, Function.update base .counter []⟩ := by + simp [TM2.step, TM2.stepAux, program, initialState, hcounter] + +theorem finishTrace (base : Tape → List Bool) (hcounter : base .counter = [false]) : + (MachineComposition.advance (TM2.step program))^[ + (base .selected).length + (base .reversed).length + 3] + (some ⟨some .finalCounter, initialState, base⟩) = + some ⟨none, initialState, finishTapes base⟩ := by + let b1 := Function.update base .counter [] + let b2 := Function.update b1 .selected [] + have first := counterStep base hcounter + have second := drainTrace_base .selected .clearSelected .finalReverse rfl + b1 ((), defaultControl) none + have last := MachineTransfer.transferAt_fromTapes Tape.reversed Tape.output + (by decide) id false Label.finalReverse none program rfl b2 + ((), defaultControl) none + have hnext : MachineTransfer.nextAt Tape.output program = + MachineComposition.advance (TM2.step program) := rfl + rw [hnext] at last + have last' : (MachineComposition.advance (TM2.step program))^[(base .reversed).length + 1] + (some ⟨some .finalReverse, initialState, b2⟩) = + some ⟨none, initialState, finishTapes base⟩ := by + simpa [finishTapes, b1, b2, + initialState] using last + have second' : (MachineComposition.advance (TM2.step program))^[(base .selected).length + 1] + (some ⟨some .clearSelected, initialState, b1⟩) = + some ⟨some .finalReverse, initialState, b2⟩ := by + simpa [b1, initialState] using second + rw [show (base .selected).length + (base .reversed).length + 3 = + ((base .reversed).length + 1) + ((base .selected).length + 1) + 1 by omega, + Function.iterate_succ_apply, MachineComposition.advance_some, first, + Function.iterate_add_apply, second', last'] + +def finishInTime (base : Tape → List Bool) (hcounter : base .counter = [false]) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some .finalCounter, initialState, base⟩ + (some ⟨none, initialState, finishTapes base⟩) + ((base .selected).length + (base .reversed).length + 3) where + steps := (base .selected).length + (base .reversed).length + 3 + evals_in_steps := finishTrace base hcounter + steps_le_m := Nat.le_refl _ + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.CircuitProducerStages + + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.CircuitProducerHeaders + +open Turing +open UniqueGamesTheorem.Foundations.Hastad +open CircuitProducerModel CircuitEmission CircuitProducerStages + +def parsedTapes (base : Tape → List Bool) (n m output : Nat) (suffix : List Bool) : + Tape → List Bool + | .input => suffix + | .header => encodeWord n + | .counter => encodeWord m + | .selected => encodeWord output + | tape => base tape + +def resultTapes (base : Tape → List Bool) (n m output : Nat) (suffix : List Bool) : + Tape → List Bool + | .input => suffix + | .header => [] + | .counter => encodeWord m + | .selected => encodeWord output + | .reversed => (encodeWords [n, 3 * m + 1]).reverse + | tape => base tape + +theorem parsedTapes_eq (base : Tape → List Bool) (n m output : Nat) (suffix : List Bool) + (hn : base .header = []) (hm : base .counter = []) (ho : base .selected = []) : + SourceMachine.afterField .input .selected + (SourceMachine.afterField .input .counter + (SourceMachine.afterField .input .header base n + (encodeWords [m, output] ++ suffix)) m (encodeWord output ++ suffix)) + output suffix = parsedTapes base n m output suffix := by + funext tape + cases tape <;> + simp [SourceMachine.afterField, SourceMachine.fieldTapes, parsedTapes, hn, hm, ho] + +theorem headersTrace (base : Tape → List Bool) (n m output : Nat) (suffix : List Bool) + (hinput : base .input = encodeWords [n, m, output] ++ suffix) + (hn : base .header = []) (hm : base .counter = []) (ho : base .selected = []) + (hs : base .scratch = []) (hr : base .reversed = []) : + (MachineComposition.advance (TM2.step program))^[5 * n + 4 * m + output + 20] + (some ⟨some (.headerStart 0), initialState, base⟩) = + some ⟨some .guard, initialState, resultTapes base n m output suffix⟩ := by + let b0 := SourceMachine.afterField .input .header base n + (encodeWords [m, output] ++ suffix) + let b1 := SourceMachine.afterField .input .counter b0 m (encodeWord output ++ suffix) + let b2 := parsedTapes base n m output suffix + let b3 := Function.update b2 .reversed (encodeWord n).reverse + let b4 := Function.update b2 .reversed (encodeWords [n, 3 * m + 1]).reverse + have h0 : base .input = encodeWord n ++ (encodeWords [m, output] ++ suffix) := by + simpa only [encodeWords, List.append_nil, List.append_assoc] using hinput + have h1 : b0 .input = encodeWord m ++ (encodeWord output ++ suffix) := by + simp [b0, SourceMachine.afterField, encodeWords, List.append_assoc] + have h2 : b1 .input = encodeWord output ++ suffix := by + simp [b1, SourceMachine.afterField] + have p0 := (SourceMachine.fieldInTime .input .header (by decide) + (.headerStart 0) (.headerLoop 0) (some (.headerStart 1)) program rfl rfl + base n (encodeWords [m, output] ++ suffix) h0 ((), defaultControl) none).evals_in_steps + have p1 := (SourceMachine.fieldInTime .input .counter (by decide) + (.headerStart 1) (.headerLoop 1) (some (.headerStart 2)) program rfl rfl + b0 m (encodeWord output ++ suffix) h1 ((), defaultControl) none).evals_in_steps + have p2 := (SourceMachine.fieldInTime .input .selected (by decide) + (.headerStart 2) (.headerLoop 2) (some (.setup (.header 0))) program rfl rfl + b1 output suffix h2 ((), defaultControl) none).evals_in_steps + change (MachineComposition.advance (TM2.step program))^[n + 2] + (some ⟨some (.headerStart 0), initialState, base⟩) = + some ⟨some (.headerStart 1), initialState, b0⟩ at p0 + change (MachineComposition.advance (TM2.step program))^[m + 2] + (some ⟨some (.headerStart 1), initialState, b0⟩) = + some ⟨some (.headerStart 2), initialState, b1⟩ at p1 + change (MachineComposition.advance (TM2.step program))^[output + 2] + (some ⟨some (.headerStart 2), initialState, b1⟩) = + some ⟨some (.setup (.header 0)), initialState, + SourceMachine.afterField .input .selected b1 output suffix⟩ at p2 + have hb2 : SourceMachine.afterField .input .selected b1 output suffix = b2 := + parsedTapes_eq base n m output suffix hn hm ho + rw [hb2] at p2 + have p3 : (MachineComposition.advance (TM2.step program))^[3 * (n + 1) + 3] + (some ⟨some (.setup (.header 0)), initialState, b2⟩) = + some ⟨some (.setup (.header 1)), initialState, b3⟩ := by + simpa [contextWords, contextNext, b3, b2, parsedTapes, hr, encodeWords] using + contextTrace_word (.header 0) b2 (by simpa [b2, parsedTapes] using hs) + initialState n rfl + have p4 : (MachineComposition.advance (TM2.step program))^[3 * (m + 1) + 3] + (some ⟨some (.setup (.header 1)), initialState, b3⟩) = + some ⟨some .clearHeader, initialState, b4⟩ := by + have p := contextTrace_word (.header 1) b3 + (by simpa [b3, b2, parsedTapes] using hs) initialState m (by + simp [b3, b2, parsedTapes, contextSource]) + simpa [contextWords, contextNext, b4, b3, encodeWords, List.reverse_append] using p + have p5 : (MachineComposition.advance (TM2.step program))^[n + 2] + (some ⟨some .clearHeader, initialState, b4⟩) = + some ⟨some .guard, initialState, resultTapes base n m output suffix⟩ := by + have p := drainTrace_base .header .clearHeader .guard rfl b4 + ((), defaultControl) none + have he : Function.update b4 .header [] = resultTapes base n m output suffix := by + funext tape + cases tape <;> simp [b4, b2, parsedTapes, resultTapes] + rw [he] at p + simpa [b4, b2, parsedTapes, initialState] using p + rw [show 5 * n + 4 * m + output + 20 = (n + 2) + + (3 * (m + 1) + 3) + (3 * (n + 1) + 3) + (output + 2) + + (m + 2) + (n + 2) by omega, + Function.iterate_add_apply, p0, Function.iterate_add_apply, p1, + Function.iterate_add_apply, p2, Function.iterate_add_apply, p3, + Function.iterate_add_apply, p4, p5] + +def headersInTime (base : Tape → List Bool) (n m output : Nat) (suffix : List Bool) + (hinput : base .input = encodeWords [n, m, output] ++ suffix) + (hn : base .header = []) (hm : base .counter = []) (ho : base .selected = []) + (hs : base .scratch = []) (hr : base .reversed = []) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (.headerStart 0), initialState, base⟩ + (some ⟨some .guard, initialState, resultTapes base n m output suffix⟩) + (5 * n + 4 * m + output + 20) where + steps := 5 * n + 4 * m + output + 20 + evals_in_steps := headersTrace base n m output suffix hinput hn hm ho hs hr + steps_le_m := Nat.le_refl _ + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.CircuitProducerHeaders + + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.CircuitProducerLoop + +open Turing +open UniqueGamesTheorem.Foundations.Hastad +open CircuitProducerModel CircuitEmission CircuitProducerStages + +def recordsInput (rs : List Record) : List Bool := rs.flatMap Record.bits +def recordsOutput (rs : List Record) : List Bool := rs.flatMap Record.outputBits + +def tapes (base : Tape → List Bool) (input counter accumulator : List Bool) + (fields : Fin 4 → List Bool) : Tape → List Bool + | .input => input + | .counter => counter + | .field j => fields j + | .scratch => [] + | .reversed => accumulator + | tape => base tape + +def parsedFields (r : Record) (j : Fin 4) : List Bool := encodeWord (r.fieldValue j) +def decodedFields (r : Record) (j : Fin 4) : List Bool := + if j.val = 0 then [] else parsedFields r j + +theorem update_reversed (base : Tape → List Bool) (input counter acc out : List Bool) + (fields : Fin 4 → List Bool) : + Function.update (tapes base input counter acc fields) .reversed out = + tapes base input counter out fields := by + funext tape + cases tape <;> simp [tapes] + +theorem counterTapes_eq (base : Tape → List Bool) (input counter acc : List Bool) + (fields : Fin 4 → List Bool) (n : Nat) : + MachineUnaryCounter.counterTapes .counter + (tapes base input counter acc fields) n [] = + tapes base input (encodeWord n) acc fields := by + funext tape + cases tape <;> simp [MachineUnaryCounter.counterTapes, tapes] + +theorem fourTapes_eq (base : Tape → List Bool) (input counter acc suffix : List Bool) + (r : Record) : + SourceMachine.fourTapes .input Tape.field + (tapes base input counter acc (fun _ => [])) r.tag.val r.output r.first r.second suffix = + tapes base suffix counter acc (parsedFields r) := by + funext tape + cases tape with + | field j => + fin_cases j <;> + simp [SourceMachine.fourTapes, SourceMachine.afterField, SourceMachine.fieldTapes, + tapes, parsedFields, Record.fieldValue] + | _ => + simp [SourceMachine.fourTapes, SourceMachine.afterField, SourceMachine.fieldTapes, + tapes] + +theorem decodeTapes_eq (base : Tape → List Bool) (input counter acc : List Bool) + (r : Record) : + Function.update (tapes base input counter acc (parsedFields r)) (.field 0) [] = + tapes base input counter acc (decodedFields r) := by + funext tape + cases tape with + | field j => fin_cases j <;> simp [tapes, decodedFields] + | _ => simp [tapes] + +theorem clearFields_eq (base : Tape → List Bool) (input counter acc : List Bool) + (fields : Fin 4 → List Bool) : + clearFields (tapes base input counter acc fields) = + tapes base input counter acc (fun _ => []) := by + funext tape + cases tape with + | field j => simp [tapes] + | _ => simp [tapes, clearFields] + +theorem cleanupSteps_eq (base : Tape → List Bool) (input counter acc : List Bool) + (r : Record) : + cleanupSteps (tapes base input counter acc (decodedFields r)) = + r.output + r.first + r.second + 7 := by + simp [cleanupSteps, tapes, decodedFields, parsedFields, Record.fieldValue] + omega + +theorem recordBits_length (r : Record) : + r.bits.length = r.tag.val + r.output + r.first + r.second + 4 := by + simp [Record.bits, Record.words, encodeWords] + omega + +def bodyCost (r : Record) : Nat := + (r.tag.val + r.output + r.first + r.second + 8) + 1 + + gateSteps r + (r.output + r.first + r.second + 7) + +def bodyInTime (base : Tape → List Bool) (r : Record) (suffix counter acc : List Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (.fieldStart 0), initialState, + tapes base (r.bits ++ suffix) counter acc (fun _ => [])⟩ + (some ⟨some .guard, initialState, + tapes base suffix counter (r.outputBits.reverse ++ acc) (fun _ => [])⟩) + (bodyCost r) := by + let before := tapes base (r.bits ++ suffix) counter acc (fun _ => []) + let parsed := tapes base suffix counter acc (parsedFields r) + let decoded := tapes base suffix counter acc (decodedFields r) + let out := r.outputBits.reverse ++ acc + let emitted := tapes base suffix counter out (decodedFields r) + let parse := SourceMachine.fourFieldsInTime .input Tape.field + (by intro j h; cases h) Label.fieldStart Label.fieldLoop (some .decodeTag) + program (by intro j; rfl) (by intro j; rfl) + before r.tag.val r.output r.first r.second suffix rfl ((), defaultControl) none + have hp : SourceMachine.fourTapes .input Tape.field before + r.tag.val r.output r.first r.second suffix = parsed := fourTapes_eq _ _ _ _ _ _ + rw [hp] at parse + let decode := tagInTime r.tag parsed initialState rfl + have hd : Function.update parsed (.field 0) [] = decoded := decodeTapes_eq _ _ _ _ _ + rw [hd] at decode + let table := gateInTime r decoded rfl initialState rfl rfl rfl + have he : Function.update decoded .reversed (r.outputBits.reverse ++ decoded .reversed) = + emitted := update_reversed _ _ _ _ _ _ + rw [he] at table + let cleanup := cleanupInTime emitted ((), defaultControl) none + have hc : clearFields emitted = tapes base suffix counter out (fun _ => []) := + clearFields_eq _ _ _ _ _ + rw [hc] at cleanup + let p1 := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ parse decode + let p2 := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ p1 table + let p3 := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ p2 cleanup + exact { + toEvalsTo := p3.toEvalsTo + steps_le_m := by + have h := p3.steps_le_m + have hcost : cleanupSteps emitted = r.output + r.first + r.second + 7 := + cleanupSteps_eq _ _ _ _ _ + unfold bodyCost + omega } + +def loopCost : List Record → Nat + | [] => 1 + | r :: rs => (1 + bodyCost r) + loopCost rs + +def loopInTime (base : Tape → List Bool) (suffix : List Bool) + (rs : List Record) (acc : List Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some .guard, initialState, + tapes base (recordsInput rs ++ suffix) (encodeWord rs.length) acc (fun _ => [])⟩ + (some ⟨some (.setup (.output 0)), initialState, + tapes base suffix (encodeWord 0) ((recordsOutput rs).reverse ++ acc) (fun _ => [])⟩) + (loopCost rs) := by + induction rs generalizing acc with + | nil => + let guard := MachineUnaryCounter.guardInTime_zero .counter Label.guard + (.fieldStart 0) (.setup (.output 0)) program rfl + (tapes base suffix (encodeWord 0) acc (fun _ => [])) [] + ((), defaultControl) none + simpa only [counterTapes_eq, loopCost, recordsInput, recordsOutput, + List.flatMap_nil, List.reverse_nil, List.nil_append, List.length_nil, + initialState] using guard + | cons r rs ih => + let before := tapes base (r.bits ++ (recordsInput rs ++ suffix)) + (encodeWord (rs.length + 1)) acc (fun _ => []) + let guard := MachineUnaryCounter.guardInTime_succ .counter Label.guard + (.fieldStart 0) (.setup (.output 0)) program rfl before rs.length [] + ((), defaultControl) none + simp only [before, counterTapes_eq] at guard + let body := bodyInTime base r (recordsInput rs ++ suffix) (encodeWord rs.length) acc + let rest := ih (r.outputBits.reverse ++ acc) + let first := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ guard body + let full := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ first rest + simpa only [loopCost, recordsInput, recordsOutput, List.flatMap_cons, + List.length_cons, List.reverse_append, List.append_assoc, initialState, + Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using full + +theorem bodyCost_le (r : Record) : bodyCost r ≤ 50 * r.bits.length := by + have h := gateSteps_le r + rw [recordBits_length] + unfold bodyCost + omega + +theorem loopCost_le (rs : List Record) : + loopCost rs ≤ 50 * (recordsInput rs).length + rs.length + 1 := by + induction rs with + | nil => simp [loopCost, recordsInput] + | cons r rs ih => + have h := bodyCost_le r + simp only [loopCost, recordsInput, List.flatMap_cons, List.length_append, + List.length_cons] at * + omega + +theorem recordOutput_length_le (r : Record) : r.outputBits.length ≤ 9 * r.bits.length := by + have h := outputBits_length_le r + rw [recordBits_length] + omega + +theorem recordsOutput_length_le (rs : List Record) : + (recordsOutput rs).length ≤ 9 * (recordsInput rs).length := by + induction rs with + | nil => simp [recordsOutput, recordsInput] + | cons r rs ih => + have h := recordOutput_length_le r + simp only [recordsOutput, recordsInput, List.flatMap_cons, List.length_append] at * + omega + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.CircuitProducerLoop + + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.CircuitProducerRuntime + +open Turing +open CircuitProducerModel CircuitProducerLoop + + +structure Input where + wireCount : Nat + selected : Nat + records : List Record + +def inputBits (input : Input) : List Bool := + encodeWords [input.wireCount, input.records.length, input.selected] ++ recordsInput input.records + +def outputHeaders (input : Input) : List Bool := + encodeWords [input.wireCount, 3 * input.records.length + 1] + +def producedBits (input : Input) : List Bool := + outputHeaders input ++ recordsOutput input.records ++ encodeWords (outputWords input.selected) + +def inputTapes (input : Input) : Tape → List Bool := + fun tape => if tape = .input then inputBits input else [] + +def retainedTapes (input : Input) : Tape → List Bool := + fun tape => if tape = .selected then encodeWord input.selected else [] + +def guardTapes (input : Input) : Tape → List Bool := + tapes (retainedTapes input) (recordsInput input.records) (encodeWord input.records.length) + (outputHeaders input).reverse (fun _ => []) + +def afterLoopTapes (input : Input) : Tape → List Bool := + tapes (retainedTapes input) [] (encodeWord 0) + ((recordsOutput input.records).reverse ++ (outputHeaders input).reverse) (fun _ => []) + +def beforeFinishTapes (input : Input) : Tape → List Bool := + tapes (retainedTapes input) [] (encodeWord 0) (producedBits input).reverse (fun _ => []) + +theorem initList_eq (input : Input) : + initList machine (inputBits input) = + ⟨some (.headerStart 0), initialState, inputTapes input⟩ := by + change (⟨some (.headerStart 0), initialState, + (initList machine (inputBits input)).stk⟩ : machine.Cfg) = _ + apply congrArg (fun tapeContents => + (⟨some (.headerStart 0), initialState, tapeContents⟩ : machine.Cfg)) + funext tape + (cases tape <;> simp [initList, machine, inputTapes]); rfl + +theorem headers_result_eq (input : Input) : + CircuitProducerHeaders.resultTapes (inputTapes input) input.wireCount + input.records.length input.selected (recordsInput input.records) = guardTapes input := by + funext tape + cases tape <;> simp [CircuitProducerHeaders.resultTapes, inputTapes, guardTapes, + tapes, retainedTapes, outputHeaders] + +theorem output_result_eq (input : Input) : + Function.update (afterLoopTapes input) .reversed + ((encodeWords (outputWords input.selected)).reverse ++ afterLoopTapes input .reversed) = + beforeFinishTapes input := by + rw [afterLoopTapes, update_reversed] + simp [beforeFinishTapes, producedBits, tapes, List.reverse_append, List.append_assoc] + +theorem finish_eq (input : Input) : + (⟨none, initialState, + CircuitProducerStages.finishTapes (beforeFinishTapes input)⟩ : machine.Cfg) = + haltList machine (producedBits input) := by + apply congrArg (fun tapeContents => (⟨none, initialState, tapeContents⟩ : machine.Cfg)) + funext tape + (cases tape <;> + simp [CircuitProducerStages.finishTapes, Reduction.MachineTransfer.tapesAt, + beforeFinishTapes, tapes, retainedTapes, machine]); rfl + +theorem inputBits_length (input : Input) : + (inputBits input).length = input.wireCount + input.records.length + input.selected + 3 + + (recordsInput input.records).length := by + simp [inputBits, encodeWords] + omega + +theorem producedBits_length_le (input : Input) : + (producedBits input).length ≤ input.wireCount + 3 * input.records.length + + 3 * input.selected + 9 * (recordsInput input.records).length + 12 := by + have h := recordsOutput_length_le input.records + simp only [producedBits, outputHeaders, List.length_append, outputWords, encodeWords, + encodeWord_length, List.length_nil] + omega + +def fullRunInTime (input : Input) : + TM2OutputsInTime machine (inputBits input) (some (producedBits input)) + (100 * (inputBits input).length + 100) := by + let first := CircuitProducerHeaders.headersInTime (inputTapes input) input.wireCount + input.records.length input.selected (recordsInput input.records) rfl rfl rfl rfl rfl rfl + have first' : StateTransition.EvalsToInTime (TM2.step program) + (initList machine (inputBits input)) + (some ⟨some .guard, initialState, guardTapes input⟩) + (5 * input.wireCount + 4 * input.records.length + input.selected + 20) := by + simpa only [initList_eq, headers_result_eq] using! first + let middle := loopInTime (retainedTapes input) [] input.records (outputHeaders input).reverse + have middle' : StateTransition.EvalsToInTime (TM2.step program) + ⟨some .guard, initialState, guardTapes input⟩ + (some ⟨some (.setup (.output 0)), initialState, afterLoopTapes input⟩) + (loopCost input.records) := by + simpa only [List.append_nil, guardTapes, afterLoopTapes] using middle + let unitClause := CircuitEmission.outputInTime input.selected (afterLoopTapes input) + rfl initialState rfl + have unitClause' : StateTransition.EvalsToInTime (TM2.step program) + ⟨some (.setup (.output 0)), initialState, afterLoopTapes input⟩ + (some ⟨some .finalCounter, initialState, beforeFinishTapes input⟩) + (9 * (input.selected + 1) + 9) := by + simpa only [output_result_eq] using unitClause + let last := CircuitProducerStages.finishInTime (beforeFinishTapes input) rfl + have last' : StateTransition.EvalsToInTime (TM2.step program) + ⟨some .finalCounter, initialState, beforeFinishTapes input⟩ + (some (haltList machine (producedBits input))) + (input.selected + (producedBits input).length + 4) := by + erw [finish_eq] at last + convert last using 1 + simp [beforeFinishTapes, tapes, retainedTapes] + omega + let firstTwo := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ first' middle' + let firstThree := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ firstTwo unitClause' + let complete := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ firstThree last' + refine { toEvalsTo := complete.toEvalsTo, steps_le_m := complete.steps_le_m.trans ?_ } + have hlo := loopCost_le input.records + have hout := producedBits_length_le input + rw [inputBits_length] + omega + +noncomputable def computableInPolyTime : + TM2ComputableInPolyTime inputBits (id : List Bool → List Bool) producedBits where + tm := machine + inputAlphabet := Equiv.refl Bool + outputAlphabet := Equiv.refl Bool + time := Polynomial.C 100 * Polynomial.X + Polynomial.C 100 + outputsFun input := by + change TM2OutputsInTime machine ((inputBits input).map id) + (some ((producedBits input).map id)) + ((Polynomial.C 100 * Polynomial.X + Polynomial.C 100).eval (inputBits input).length) + have input_eq : @List.map (machine.Γ machine.k₀) (machine.Γ machine.k₀) + id (inputBits input) = inputBits input := List.map_id _ + have output_eq : @List.map (machine.Γ machine.k₁) (machine.Γ machine.k₁) + id (producedBits input) = producedBits input := List.map_id _ + simpa only [Equiv.refl, input_eq, output_eq, id_eq, + Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_C, Polynomial.eval_X] + using! fullRunInTime input + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.CircuitProducerRuntime + + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.CircuitProducer + +open Turing +open CircuitProducerModel + + +def asInput (C : Circuit) : CircuitProducerRuntime.Input := + ⟨C.wires, C.output.val, C.records⟩ + +theorem recordsInput_eq (rs : List Record) : + CircuitProducerLoop.recordsInput rs = encodeWords (rs.flatMap Record.words) := by + induction rs with + | nil => rfl + | cons r rs ih => + simp only [CircuitProducerLoop.recordsInput, List.flatMap_cons, encodeWords_append] at * + rw [ih] + rfl + +theorem recordsOutput_eq (rs : List Record) : + CircuitProducerLoop.recordsOutput rs = encodeWords (rs.flatMap Record.outputWords) := by + induction rs with + | nil => rfl + | cons r rs ih => + simp only [CircuitProducerLoop.recordsOutput, List.flatMap_cons, encodeWords_append] at * + rw [ih] + rfl + +theorem inputBits_asInput (C : Circuit) : + CircuitProducerRuntime.inputBits (asInput C) = circuitBits C := by + simp only [CircuitProducerRuntime.inputBits, asInput, Circuit.records_length, + recordsInput_eq, circuitBits, circuitWords, encodeWords_append, recordsWords] + +theorem producedBits_asInput (C : Circuit) : + CircuitProducerRuntime.producedBits (asInput C) = formulaBits C.toFormula := by + rw [formulaBits, C.formulaWords_eq_records] + simp only [CircuitProducerRuntime.producedBits, CircuitProducerRuntime.outputHeaders, + asInput, Circuit.records_length, recordsOutput_eq, encodeWords_append] + +def fullRunInTime (C : Circuit) : + TM2OutputsInTime machine (circuitBits C) (some (formulaBits C.toFormula)) + (100 * (circuitBits C).length + 100) := by + simpa only [inputBits_asInput, producedBits_asInput] using + CircuitProducerRuntime.fullRunInTime (asInput C) + +noncomputable def computableInPolyTime : + TM2ComputableInPolyTime circuitBits formulaBits Circuit.toFormula where + tm := machine + inputAlphabet := Equiv.refl Bool + outputAlphabet := Equiv.refl Bool + time := Polynomial.C 100 * Polynomial.X + Polynomial.C 100 + outputsFun C := by + change TM2OutputsInTime machine ((circuitBits C).map id) + (some ((formulaBits C.toFormula).map id)) + ((Polynomial.C 100 * Polynomial.X + Polynomial.C 100).eval (circuitBits C).length) + have input_eq : @List.map (machine.Γ machine.k₀) (machine.Γ machine.k₀) + id (circuitBits C) = circuitBits C := List.map_id _ + have output_eq : @List.map (machine.Γ machine.k₁) (machine.Γ machine.k₁) + id (formulaBits C.toFormula) = formulaBits C.toFormula := List.map_id _ + simpa only [Equiv.refl, input_eq, output_eq, + Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_C, Polynomial.eval_X] + using! fullRunInTime C + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.CircuitProducer + + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.ForestPlacement + +open Turing + + +variable {I J K L Λ σ : Type} + +abbrev Tapes (I : Type) := I → List Bool + +noncomputable def fill (ports : I ↪ K) (base : Tapes K) (contents : Tapes I) : Tapes K := + Function.extend ports contents base + +@[simp] theorem fill_at (ports : I ↪ K) (base : Tapes K) (contents : Tapes I) (i : I) : + fill ports base contents (ports i) = contents i := + ports.injective.extend_apply contents base i + +theorem fill_other (ports : I ↪ K) (base : Tapes K) (contents : Tapes I) (k : K) + (outside : ∀ i, ports i ≠ k) : fill ports base contents k = base k := + Function.extend_apply' contents base k (not_exists.mpr outside) + +theorem fill_self (ports : I ↪ K) (base : Tapes K) : + fill ports base (fun i => base (ports i)) = base := by + classical + funext k + by_cases h : ∃ i, ports i = k + · rcases h with ⟨i, rfl⟩ + exact fill_at ports base _ i + · exact fill_other ports base _ k (not_exists.mp h) + +theorem fill_update [DecidableEq I] [DecidableEq K] (ports : I ↪ K) + (base : Tapes K) (contents : Tapes I) (i : I) (word : List Bool) : + fill ports base (Function.update contents i word) = + Function.update (fill ports base contents) (ports i) word := by + classical + funext k + by_cases hk : k = ports i + · subst k + simp only [fill_at, Function.update_self] + · by_cases hr : ∃ j, ports j = k + · rcases hr with ⟨j, rfl⟩ + have hj : j ≠ i := fun h => hk (congrArg ports h) + rw [fill_at, Function.update_of_ne hj, Function.update_of_ne hk, fill_at] + · rw [fill_other ports base _ k (not_exists.mp hr), Function.update_of_ne hk, + fill_other ports base _ k (not_exists.mp hr)] + +theorem fill_comp (ports : I ↪ K) (innerPorts : J ↪ I) (base : Tapes K) + (outer : Tapes I) (inner : Tapes J) : + fill (innerPorts.trans ports) (fill ports base outer) inner = + fill ports base (fill innerPorts outer inner) := by + classical + funext k + by_cases houter : ∃ i, ports i = k + · rcases houter with ⟨i, rfl⟩ + rw [fill_at] + by_cases hinner : ∃ j, innerPorts j = i + · rcases hinner with ⟨j, rfl⟩ + have h := fill_at (innerPorts.trans ports) (fill ports base outer) inner j + change fill (innerPorts.trans ports) (fill ports base outer) inner + (ports (innerPorts j)) = inner j at h + rw [h, fill_at] + · have outside : ∀ j, (innerPorts.trans ports) j ≠ ports i := by + intro j h + exact hinner ⟨j, ports.injective h⟩ + rw [fill_other _ _ _ _ outside, fill_at, + fill_other innerPorts outer inner i (not_exists.mp hinner)] + · have outside : ∀ j, (innerPorts.trans ports) j ≠ k := by + intro j h + exact houter ⟨innerPorts j, h⟩ + rw [fill_other _ _ _ _ outside, + fill_other ports base outer k (not_exists.mp houter), + fill_other ports base _ k (not_exists.mp houter)] + +def placedLabel (labels : L → Λ) (haltTarget : Option Λ) : Option L → Option Λ + | none => haltTarget + | some label => some (labels label) + +noncomputable def configuration (ports : I ↪ K) (labels : L → Λ) + (haltTarget : Option Λ) (base : Tapes K) + (cfg : TM2.Cfg (fun _ : I => Bool) L σ) : TM2.Cfg (fun _ : K => Bool) Λ σ where + l := placedLabel labels haltTarget cfg.l + var := cfg.var + stk := fill ports base cfg.stk + +def statement (ports : I ↪ K) (labels : L → Λ) (haltTarget : Option Λ) : + TM2.Stmt (fun _ : I => Bool) L σ → TM2.Stmt (fun _ : K => Bool) Λ σ + | .push i value next => .push (ports i) value (statement ports labels haltTarget next) + | .peek i observe next => .peek (ports i) observe (statement ports labels haltTarget next) + | .pop i observe next => .pop (ports i) observe (statement ports labels haltTarget next) + | .load update next => .load update (statement ports labels haltTarget next) + | .branch predicate yes no => .branch predicate + (statement ports labels haltTarget yes) (statement ports labels haltTarget no) + | .goto next => .goto (fun state => labels (next state)) + | .halt => match haltTarget with + | none => .halt + | some label => .goto (fun _ => label) + +variable [DecidableEq I] [DecidableEq K] + +theorem stepAux_simulation (ports : I ↪ K) (labels : L → Λ) (haltTarget : Option Λ) + (base : Tapes K) (q : TM2.Stmt (fun _ : I => Bool) L σ) + (state : σ) (contents : Tapes I) : + TM2.stepAux (statement ports labels haltTarget q) state (fill ports base contents) = + configuration ports labels haltTarget base (TM2.stepAux q state contents) := by + induction q generalizing state contents with + | push i value next ih => + simp only [statement, TM2.stepAux, fill_at] + rw [← fill_update] + exact ih state (Function.update contents i (value state :: contents i)) + | peek i observe next ih => + simpa only [statement, TM2.stepAux, fill_at] using + ih (observe state (contents i).head?) contents + | pop i observe next ih => + simp only [statement, TM2.stepAux, fill_at] + rw [← fill_update] + exact ih (observe state (contents i).head?) (Function.update contents i (contents i).tail) + | load update next ih => + simpa only [statement, TM2.stepAux] using ih (update state) contents + | branch predicate yes no ihYes ihNo => + cases h : predicate state + · simpa only [statement, TM2.stepAux, h, Bool.cond_false] using ihNo state contents + · simpa only [statement, TM2.stepAux, h, Bool.cond_true] using ihYes state contents + | goto next => rfl + | halt => cases haltTarget <;> rfl + +theorem step_simulation (ports : I ↪ K) (labels : L → Λ) (haltTarget : Option Λ) + (base : Tapes K) (source : L → TM2.Stmt (fun _ : I => Bool) L σ) + (ambientProgram : Λ → TM2.Stmt (fun _ : K => Bool) Λ σ) + (atLabels : ∀ l, ambientProgram (labels l) = statement ports labels haltTarget (source l)) + (a b : TM2.Cfg (fun _ : I => Bool) L σ) + (transition : TM2.step source a = some b) : + TM2.step ambientProgram (configuration ports labels haltTarget base a) = + some (configuration ports labels haltTarget base b) := by + cases a with + | mk label state contents => + cases label with + | none => simp [TM2.step] at transition + | some label => + have result : TM2.stepAux (source label) state contents = b := Option.some.inj transition + rw [← result] + change some (TM2.stepAux (ambientProgram (labels label)) state + (fill ports base contents)) = _ + rw [atLabels, stepAux_simulation] + +theorem trace (ports : I ↪ K) (labels : L → Λ) (haltTarget : Option Λ) + (base : Tapes K) (source : L → TM2.Stmt (fun _ : I => Bool) L σ) + (ambientProgram : Λ → TM2.Stmt (fun _ : K => Bool) Λ σ) + (atLabels : ∀ l, ambientProgram (labels l) = statement ports labels haltTarget (source l)) + (steps : Nat) (start finish : TM2.Cfg (fun _ : I => Bool) L σ) + (sourceTrace : (MachineComposition.advance (TM2.step source))^[steps] (some start) = some finish) : + (MachineComposition.advance (TM2.step ambientProgram))^[steps] + (some (configuration ports labels haltTarget base start)) = + some (configuration ports labels haltTarget base finish) := + MachineComposition.liftSuccessfulTrace (TM2.step source) (TM2.step ambientProgram) + (configuration ports labels haltTarget base) + (step_simulation ports labels haltTarget base source ambientProgram atLabels) + steps start finish sourceTrace + +noncomputable def execution (ports : I ↪ K) (labels : L → Λ) (haltTarget : Option Λ) + (base : Tapes K) (source : L → TM2.Stmt (fun _ : I => Bool) L σ) + (ambientProgram : Λ → TM2.Stmt (fun _ : K => Bool) Λ σ) + (atLabels : ∀ l, ambientProgram (labels l) = statement ports labels haltTarget (source l)) + {start finish : TM2.Cfg (fun _ : I => Bool) L σ} {budget : Nat} + (sourceRun : StateTransition.EvalsToInTime (TM2.step source) start (some finish) budget) : + StateTransition.EvalsToInTime (TM2.step ambientProgram) + (configuration ports labels haltTarget base start) + (some (configuration ports labels haltTarget base finish)) budget := + MachineComposition.liftExecutionInTime (TM2.step source) (TM2.step ambientProgram) + (configuration ports labels haltTarget base) + (step_simulation ports labels haltTarget base source ambientProgram atLabels) sourceRun + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.ForestPlacement + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/ClashMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/ClashMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..583524e791ed6168042e42daf3da88703451e5b6 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/ClashMachine.lean @@ -0,0 +1,463 @@ +import Mathlib.Data.Fin.VecNotation +import OAI.Computability.PerfectCompleteness.Machines.PositionLemmas +import OAI.Computability.UniqueGames.Machines.MachineLemmas +import OAI.Computability.UniqueGames.Machines.MachineTransducerCopy +import OAI.Computability.UniqueGames.Machines.MachineUnaryLessAtLemmas + +namespace OAI + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.ClashMachine + +open Turing MachineComposition PostfixModel InitializationTemplate +open Reduction.MachineSubstitution (pushWord stepAux_pushWord) + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool +abbrev State (σ : Type) := (σ × Bool) × Option Bool + +def clean (ambient : σ) : State σ := ((ambient, false), none) + +def emitted (output count : K) (base : K → List Bool) (tokens : List Token) : K → List Bool := + Function.update (Function.update base output ((tokenBits tokens).reverse ++ base output)) + count (List.replicate tokens.length true ++ base count) + +@[simp] theorem emitted_output (output count : K) (hne : output ≠ count) + (base : K → List Bool) (tokens : List Token) : + emitted output count base tokens output = (tokenBits tokens).reverse ++ base output := by + simp [emitted, hne] + +@[simp] theorem emitted_count (output count : K) (base : K → List Bool) (tokens : List Token) : + emitted output count base tokens count = List.replicate tokens.length true ++ base count := by + simp [emitted] + +theorem emitted_other (output count k : K) (ho : k ≠ output) (hc : k ≠ count) + (base : K → List Bool) (tokens : List Token) : emitted output count base tokens k = base k := by + simp [emitted, ho, hc] + +theorem tokenBits_append (first second : List Token) : + tokenBits (first ++ second) = tokenBits first ++ tokenBits second := by + simp [tokenBits, tokenWords] + +theorem emitted_append (output count : K) (hne : output ≠ count) + (base : K → List Bool) (first second : List Token) : + emitted output count (emitted output count base first) second = + emitted output count base (first ++ second) := by + funext k + by_cases ho : k = output + · subst k + simp [emitted, hne, tokenBits_append, List.reverse_append, List.append_assoc] + · by_cases hc : k = count + · subst k + have hr : List.replicate second.length true ++ List.replicate first.length true = + List.replicate (first.length + second.length) true := by + rw [← List.replicate_add, Nat.add_comm] + simp only [emitted_count, List.length_append, ← List.append_assoc, hr] + · simp [emitted, ho, hc] + +@[simp] theorem emitted_nil (output count : K) (base : K → List Bool) : + emitted output count base [] = base := by + simp [emitted, tokenBits, tokenWords, encodeWords] + +theorem chain {A : Type*} {f : A → A} {x y z : A} {n m : Nat} + (first : f^[n] x = y) (second : f^[m] y = z) : f^[n + m] x = z := by + rw [Nat.add_comm n m, Function.iterate_add_apply, first, second] + +def literal (output count : K) (tokens : List Token) + (continuation : TM2.Stmt (Alphabet (K := K)) Λ (State σ)) : + TM2.Stmt (Alphabet (K := K)) Λ (State σ) := + pushWord output (tokenBits tokens) + (pushWord count (List.replicate tokens.length true) continuation) + +theorem stepAux_literal (output count : K) (hne : output ≠ count) + (tokens : List Token) (continuation : TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (state : State σ) (base : K → List Bool) : + TM2.stepAux (literal output count tokens continuation) state base = + TM2.stepAux continuation state (emitted output count base tokens) := by + simp [literal, stepAux_pushWord, emitted, Ne.symm hne] + +namespace Input + +inductive Label where + | tag | scan | emit (b : Bool) | restore + deriving DecidableEq + +instance : Fintype Label where + elems := { .tag, .scan, .emit false, .emit true, .restore } + complete l := by cases l with + | emit b => cases b <;> simp + | tag => simp + | scan => simp + | restore => simp + +def statement (slots : Fin 4 ↪ K) (labels : Label → Λ) (exit : Option Λ) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (State σ) + | .tag => pushWord (slots 2) (encodeWord 5) + (.push (slots 3) (fun _ => true) (.goto fun _ => labels .scan)) + | .scan => MachineTransducerCopy.scanLoop (slots 0) (slots 1) false + (fun _ b => labels (.emit b)) (labels .restore) + | .emit b => MachineTransducerCopy.emitter (slots 2) (fun (_ : Bool) _ => false) + (fun _ b => [b]) (labels .scan) false b + | .restore => Reduction.MachineTransfer.loopAt (slots 1) (slots 0) id false + (labels .restore) exit + +def steps (n : Nat) : Nat := 3 * (n + 1) + 3 + +private theorem identity_output (xs : List Bool) (control : Bool) : + Reduction.MachineTransducer.output (fun (_ : Bool) _ => false) + (fun _ b => [b]) control xs = xs := by + induction xs generalizing control with + | nil => rfl + | cons b xs ih => simp [Reduction.MachineTransducer.output, ih] + +theorem trace (slots : Fin 4 ↪ K) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ l, program (labels l) = statement slots labels exit l) + (base : K → List Bool) (n : Nat) + (sourceWord : base (slots 0) = encodeWord n) (scratchEmpty : base (slots 1) = []) + (ambient : σ) : + (advance (TM2.step program))^[steps n] + (some ⟨some (labels .tag), clean ambient, base⟩) = + some ⟨exit, clean ambient, emitted (slots 2) (slots 3) base [.input n]⟩ := by + let tagged := Function.update (Function.update base (slots 2) + ((encodeWord 5).reverse ++ base (slots 2))) (slots 3) (true :: base (slots 3)) + have htag : (advance (TM2.step program))^[1] + (some ⟨some (labels .tag), clean ambient, base⟩) = + some ⟨some (labels .scan), clean ambient, tagged⟩ := by + change some (TM2.stepAux (program (labels .tag)) _ _) = _ + rw [atLabels, statement, stepAux_pushWord] + simp [TM2.stepAux, tagged, slots.injective.eq_iff] + have hs : tagged (slots 0) = encodeWord n := by + simpa [tagged, slots.injective.eq_iff] using sourceWord + have ht : tagged (slots 1) = [] := by + simpa [tagged, slots.injective.eq_iff] using scratchEmpty + have hcopy := MachineTransducerCopy.transduceCopyTrace (slots 0) (slots 1) (slots 2) + (slots.injective.ne (by decide)) (slots.injective.ne (by decide)) + (slots.injective.ne (by decide)) false (fun (_ : Bool) _ => false) (fun _ b => [b]) + (labels .scan) (labels .restore) (fun _ b => labels (.emit b)) exit program + (atLabels .scan) + (fun (control symbol : Bool) => by + simpa only [statement, MachineTransducerCopy.emitter] using (atLabels (Label.emit symbol))) + (atLabels .restore) tagged ht ambient false none + rw [hs, encodeWord_length, identity_output] at hcopy + have hout : Function.update tagged (slots 2) ((encodeWord n).reverse ++ tagged (slots 2)) = + emitted (slots 2) (slots 3) base [.input n] := by + funext k + by_cases ho : k = slots 2 + · subst k + simp [tagged, emitted, tokenBits, tokenWords, Token.words, encodeWords, + slots.injective.eq_iff, List.reverse_append, List.append_assoc] + · by_cases hc : k = slots 3 + · subst k + simp [tagged, emitted, slots.injective.eq_iff] + · simp [tagged, emitted, ho, hc] + rw [hout] at hcopy + have h := chain htag hcopy + simpa only [steps, clean, Nat.add_comm 1] using h + +end Input + +namespace Pair + +def leftMap : Fin 4 ↪ Fin 6 := ⟨![0, 1, 2, 3], by decide⟩ +def rightMap : Fin 4 ↪ Fin 6 := ⟨![1, 0, 2, 3], by decide⟩ +def inputLeftMap : Fin 4 ↪ Fin 6 := ⟨![0, 2, 4, 5], by decide⟩ +def inputRightMap : Fin 4 ↪ Fin 6 := ⟨![1, 2, 4, 5], by decide⟩ + +inductive Label where + | left (l : MachineUnaryLessAt.Label) + | right (l : MachineUnaryLessAt.Label) + | branchLeft | branchRight | diagonal + | inputLeft (l : Input.Label) + | inputRight (l : Input.Label) + | conjunction + deriving DecidableEq, Fintype + +def choose (yes no : Λ) : TM2.Stmt (Alphabet (K := K)) Λ (State σ) := + .branch (fun s => s.1.2) + (.load (fun s => clean s.1.1) (.goto fun _ => yes)) + (.load (fun s => clean s.1.1) (.goto fun _ => no)) + +theorem stepAux_choose (yes no : Λ) (base : K → List Bool) (ambient : σ) (flag : Bool) : + TM2.stepAux (choose yes no) ((ambient, flag), none) base = + ⟨some (if flag then yes else no), clean ambient, base⟩ := by + cases flag <;> rfl + +def statement (slots : Fin 6 ↪ K) (labels : Label → Λ) (exit : Option Λ) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (State σ) + | .left l => MachineUnaryLessAt.statement (leftMap.trans slots) + (fun l => labels (.left l)) (some (labels .branchLeft)) l + | .right l => MachineUnaryLessAt.statement (rightMap.trans slots) + (fun l => labels (.right l)) (some (labels .branchRight)) l + | .branchLeft => choose (labels (.inputLeft .tag)) (labels (.right .scan)) + | .branchRight => choose (labels (.inputLeft .tag)) (labels .diagonal) + | .diagonal => literal (slots 4) (slots 5) [.const false] + (Reduction.MachineTransfer.exitAt (slots 4) exit) + | .inputLeft l => Input.statement (inputLeftMap.trans slots) + (fun l => labels (.inputLeft l)) (some (labels (.inputRight .tag))) l + | .inputRight l => Input.statement (inputRightMap.trans slots) + (fun l => labels (.inputRight l)) (some (labels .conjunction)) l + | .conjunction => literal (slots 4) (slots 5) [.and] + (Reduction.MachineTransfer.exitAt (slots 4) exit) + +def offSteps (i j : Nat) : Nat := Input.steps i + Input.steps j + 1 + +theorem offTrace (slots : Fin 6 ↪ K) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ l, program (labels l) = statement slots labels exit l) + (base : K → List Bool) (i j : Nat) + (leftWord : base (slots 0) = encodeWord i) (rightWord : base (slots 1) = encodeWord j) + (leftEmpty : base (slots 2) = []) (ambient : σ) : + (advance (TM2.step program))^[offSteps i j] + (some ⟨some (labels (.inputLeft .tag)), clean ambient, base⟩) = + some ⟨exit, clean ambient, emitted (slots 4) (slots 5) base [.input i, .input j, .and]⟩ := by + have hi := Input.trace (inputLeftMap.trans slots) (fun l => labels (.inputLeft l)) + (some (labels (.inputRight .tag))) program (fun _ => atLabels _) + base i leftWord leftEmpty ambient + change (advance (TM2.step program))^[Input.steps i] + (some ⟨some (labels (.inputLeft .tag)), clean ambient, base⟩) = + some ⟨some (labels (.inputRight .tag)), clean ambient, + emitted (slots 4) (slots 5) base [.input i]⟩ at hi + let afterLeft := emitted (slots 4) (slots 5) base [.input i] + have hjWord : afterLeft (slots 1) = encodeWord j := by + simpa [afterLeft, emitted, slots.injective.eq_iff] using rightWord + have hjScratch : afterLeft (slots 2) = [] := by + simpa [afterLeft, emitted, slots.injective.eq_iff] using leftEmpty + have hj := Input.trace (inputRightMap.trans slots) (fun l => labels (.inputRight l)) + (some (labels .conjunction)) program (fun _ => atLabels _) + afterLeft j hjWord hjScratch ambient + change (advance (TM2.step program))^[Input.steps j] + (some ⟨some (labels (.inputRight .tag)), clean ambient, afterLeft⟩) = + some ⟨some (labels .conjunction), clean ambient, + emitted (slots 4) (slots 5) afterLeft [.input j]⟩ at hj + let afterRight := emitted (slots 4) (slots 5) afterLeft [.input j] + have hand : (advance (TM2.step program))^[1] + (some ⟨some (labels .conjunction), clean ambient, afterRight⟩) = + some ⟨exit, clean ambient, emitted (slots 4) (slots 5) afterRight [.and]⟩ := by + change some (TM2.stepAux (program (labels .conjunction)) _ _) = _ + rw [atLabels, statement, stepAux_literal _ _ (slots.injective.ne (by decide))] + cases exit <;> rfl + have h := chain (chain hi hj) hand + simp only [afterRight, afterLeft, + emitted_append (slots 4) (slots 5) (slots.injective.ne (by decide : (4 : Fin 6) ≠ 5)), + List.singleton_append] at h + exact h + +def steps (i j : Nat) : Nat := MachineUnaryLessAt.steps i j + 1 + + if i < j then offSteps i j else + MachineUnaryLessAt.steps j i + 1 + if j < i then offSteps i j else 1 + +theorem trace (slots : Fin 6 ↪ K) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ l, program (labels l) = statement slots labels exit l) + (base : K → List Bool) (i j : Nat) + (leftWord : base (slots 0) = encodeWord i) (rightWord : base (slots 1) = encodeWord j) + (leftEmpty : base (slots 2) = []) (rightEmpty : base (slots 3) = []) (ambient : σ) : + (advance (TM2.step program))^[steps i j] + (some ⟨some (labels (.left .scan)), clean ambient, base⟩) = + some ⟨exit, clean ambient, emitted (slots 4) (slots 5) base (clashPairTokens i j)⟩ := by + have hl := MachineUnaryLessAt.lessThanTrace (leftMap.trans slots) + (fun l => labels (.left l)) (some (labels .branchLeft)) program (fun _ => atLabels _) + base i j [] [] (by simpa [leftMap] using leftWord) (by simpa [leftMap] using rightWord) + leftEmpty rightEmpty ambient false none + change (advance (TM2.step program))^[MachineUnaryLessAt.steps i j] + (some ⟨some (labels (.left .scan)), clean ambient, base⟩) = + some ⟨some (labels .branchLeft), ((ambient, decide (i < j)), none), base⟩ at hl + have hr := MachineUnaryLessAt.lessThanTrace (rightMap.trans slots) + (fun l => labels (.right l)) (some (labels .branchRight)) program (fun _ => atLabels _) + base j i [] [] (by simpa [rightMap] using rightWord) (by simpa [rightMap] using leftWord) + leftEmpty rightEmpty ambient false none + change (advance (TM2.step program))^[MachineUnaryLessAt.steps j i] + (some ⟨some (labels (.right .scan)), clean ambient, base⟩) = + some ⟨some (labels .branchRight), ((ambient, decide (j < i)), none), base⟩ at hr + have hbl : (advance (TM2.step program))^[1] + (some ⟨some (labels .branchLeft), ((ambient, decide (i < j)), none), base⟩) = + some ⟨some (if i < j then labels (.inputLeft .tag) else labels (.right .scan)), + clean ambient, base⟩ := by + change some (TM2.stepAux (program (labels .branchLeft)) _ _) = _ + rw [atLabels, statement, stepAux_choose] + simp + have hbr : (advance (TM2.step program))^[1] + (some ⟨some (labels .branchRight), ((ambient, decide (j < i)), none), base⟩) = + some ⟨some (if j < i then labels (.inputLeft .tag) else labels .diagonal), + clean ambient, base⟩ := by + change some (TM2.stepAux (program (labels .branchRight)) _ _) = _ + rw [atLabels, statement, stepAux_choose] + simp + have hoff := offTrace slots labels exit program atLabels base i j leftWord rightWord leftEmpty ambient + by_cases hij : i < j + · rw [ite_eq_left hij] at hbl + have h := chain (chain hl hbl) hoff + simpa only [steps, ite_eq_left hij, clashPairTokens, ite_eq_right (Nat.ne_of_lt hij)] using h + · rw [ite_eq_right hij] at hbl + by_cases hji : j < i + · rw [ite_eq_left hji] at hbr + have h := chain (chain (chain (chain hl hbl) hr) hbr) hoff + simpa only [steps, ite_eq_right hij, ite_eq_left hji, clashPairTokens, + ite_eq_right (Ne.symm (Nat.ne_of_lt hji)), Nat.add_assoc] using h + · rw [ite_eq_right hji] at hbr + have hd : (advance (TM2.step program))^[1] + (some ⟨some (labels .diagonal), clean ambient, base⟩) = + some ⟨exit, clean ambient, emitted (slots 4) (slots 5) base [.const false]⟩ := by + change some (TM2.stepAux (program (labels .diagonal)) _ _) = _ + rw [atLabels, statement, stepAux_literal _ _ (slots.injective.ne (by decide))] + cases exit <;> rfl + have heq : i = j := by omega + have h := chain (chain (chain (chain hl hbl) hr) hbr) hd + simpa only [steps, ite_eq_right hij, ite_eq_right hji, clashPairTokens, + ite_eq_left heq, Nat.add_assoc] using h + +theorem steps_le (i j : Nat) : steps i j ≤ 12 * (i + j + 2) := by + unfold steps offSteps Input.steps MachineUnaryLessAt.steps + have h₁ := Nat.min_le_left i j + have h₂ := Nat.min_le_left j i + split <;> (try split) <;> omega + +end Pair + +namespace Row + +def pairMap : Fin 6 ↪ Fin 7 := ⟨![1, 2, 3, 4, 5, 6], by decide⟩ + +inductive Label where + | guard + | pair (l : Pair.Label) + | increment + deriving DecidableEq, Fintype + +def statement (slots : Fin 7 ↪ K) (labels : Label → Λ) (done : Λ) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (State σ) + | .guard => MachineUnaryCounter.guard (slots 0) (labels (.pair (.left .scan))) done + | .pair l => Pair.statement (pairMap.trans slots) (fun l => labels (.pair l)) + (some (labels .increment)) l + | .increment => .push (slots 2) (fun _ => true) (.goto fun _ => labels .guard) + +def frame (slots : Fin 7 ↪ K) (base : K → List Bool) (remaining current : Nat) : K → List Bool := + Function.update (Function.update base (slots 0) (encodeWord remaining)) (slots 2) (encodeWord current) + +@[simp] theorem frame_current (slots : Fin 7 ↪ K) (base : K → List Bool) (r j : Nat) : + frame slots base r j (slots 2) = encodeWord j := by simp [frame] + +@[simp] theorem frame_remaining (slots : Fin 7 ↪ K) (base : K → List Bool) (r j : Nat) : + frame slots base r j (slots 0) = encodeWord r := by simp [frame, slots.injective.eq_iff] + +theorem counter_frame (slots : Fin 7 ↪ K) (base : K → List Bool) (r r' j : Nat) : + MachineUnaryCounter.counterTapes (slots 0) (frame slots base r j) r' [] = + frame slots base r' j := by + funext k + by_cases h₀ : k = slots 0 + · subst k; simp [MachineUnaryCounter.counterTapes, frame, slots.injective.eq_iff] + · by_cases h₂ : k = slots 2 <;> simp [MachineUnaryCounter.counterTapes, frame, h₀, h₂] + +theorem emitted_frame (slots : Fin 7 ↪ K) (base : K → List Bool) (r j : Nat) (tokens : List Token) : + emitted (slots 5) (slots 6) (frame slots base r j) tokens = + frame slots (emitted (slots 5) (slots 6) base tokens) r j := by + funext k + by_cases h₀ : k = slots 0 + · subst k; simp [emitted, frame, slots.injective.eq_iff] + · by_cases h₂ : k = slots 2 + · subst k; simp [emitted, frame, slots.injective.eq_iff] + · by_cases h₅ : k = slots 5 + · subst k; simp [emitted, frame, slots.injective.eq_iff] + · by_cases h₆ : k = slots 6 + · subst k; simp [emitted, frame, slots.injective.eq_iff] + · simp [emitted, frame, h₀, h₂, h₅, h₆] + +theorem increment_frame (slots : Fin 7 ↪ K) (base : K → List Bool) (r j : Nat) : + Function.update (frame slots base r j) (slots 2) (true :: encodeWord j) = + frame slots base r (j + 1) := by + simp [frame, encodeWord, List.replicate_succ] + +def tokens (count i start : Nat) : List Token := + forTokens count (fun j => clashPairTokens i (start + j)) + +theorem tokens_zero (i start : Nat) : tokens 0 i start = [] := rfl + +theorem tokens_succ (count i start : Nat) : + tokens (count + 1) i start = clashPairTokens i start ++ tokens count i (start + 1) := by + rw [tokens, forTokens_succ_first] + simp only [Nat.add_zero] + apply congrArg (List.append (clashPairTokens i start)) + apply forTokens_congr + intro j _ + rw [show start + (j + 1) = start + 1 + j by omega] + +def steps : Nat → Nat → Nat → Nat + | 0, _, _ => 1 + | count + 1, i, start => 1 + Pair.steps i start + 1 + steps count i (start + 1) + +theorem trace (slots : Fin 7 ↪ K) (labels : Label → Λ) (done : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ l, program (labels l) = statement slots labels done l) + (base : K → List Bool) (count i start : Nat) + (leftWord : base (slots 1) = encodeWord i) + (leftEmpty : base (slots 3) = []) (rightEmpty : base (slots 4) = []) (ambient : σ) : + (advance (TM2.step program))^[steps count i start] + (some ⟨some (labels .guard), clean ambient, frame slots base count start⟩) = + some ⟨some done, clean ambient, + frame slots (emitted (slots 5) (slots 6) base (tokens count i start)) 0 (start + count)⟩ := by + induction count generalizing base start with + | zero => + have h := MachineUnaryCounter.guardTrace_zero (slots 0) (labels .guard) + (labels (.pair (.left .scan))) done program (atLabels .guard) + (frame slots base 0 start) [] (ambient, false) none + simpa only [counter_frame, steps, tokens_zero, emitted_nil, Nat.add_zero, clean] using h + | succ count ih => + have hg := MachineUnaryCounter.guardTrace_succ (slots 0) (labels .guard) + (labels (.pair (.left .scan))) done program (atLabels .guard) + (frame slots base count start) count [] (ambient, false) none + simp only [counter_frame] at hg + have hiWord : frame slots base count start (slots 1) = encodeWord i := by + simpa [frame, slots.injective.eq_iff] using leftWord + have hsLeft : frame slots base count start (slots 3) = [] := by + simpa [frame, slots.injective.eq_iff] using leftEmpty + have hsRight : frame slots base count start (slots 4) = [] := by + simpa [frame, slots.injective.eq_iff] using rightEmpty + have hp := Pair.trace (pairMap.trans slots) (fun l => labels (.pair l)) + (some (labels .increment)) program (fun _ => atLabels _) + (frame slots base count start) i start hiWord (frame_current slots base count start) + hsLeft hsRight ambient + change (advance (TM2.step program))^[Pair.steps i start] + (some ⟨some (labels (.pair (.left .scan))), clean ambient, frame slots base count start⟩) = + some ⟨some (labels .increment), clean ambient, + emitted (slots 5) (slots 6) (frame slots base count start) (clashPairTokens i start)⟩ at hp + rw [emitted_frame] at hp + let nextBase := emitted (slots 5) (slots 6) base (clashPairTokens i start) + have hn : (advance (TM2.step program))^[1] + (some ⟨some (labels .increment), clean ambient, frame slots nextBase count start⟩) = + some ⟨some (labels .guard), clean ambient, frame slots nextBase count (start + 1)⟩ := by + change some (TM2.stepAux (program (labels .increment)) _ _) = _ + rw [atLabels, statement] + simp only [TM2.stepAux, frame_current, increment_frame] + have hni : nextBase (slots 1) = encodeWord i := by + simpa [nextBase, emitted, slots.injective.eq_iff] using leftWord + have hnl : nextBase (slots 3) = [] := by + simpa [nextBase, emitted, slots.injective.eq_iff] using leftEmpty + have hnr : nextBase (slots 4) = [] := by + simpa [nextBase, emitted, slots.injective.eq_iff] using rightEmpty + have hr := ih nextBase (start + 1) hni hnl hnr + have h := chain (chain (chain hg hp) hn) hr + rw [show start + 1 + count = start + (count + 1) by omega] at h + simp only [nextBase, + emitted_append (slots 5) (slots 6) (slots.injective.ne (by decide : (5 : Fin 7) ≠ 6)), + ← tokens_succ] at h + exact h + +theorem steps_le (count i start B : Nat) (hB : i + start + count ≤ B) : + steps count i start ≤ count * (12 * (B + 2) + 2) + 1 := by + induction count generalizing start with + | zero => simp [steps] + | succ count ih => + have hr := ih (start + 1) (by omega) + have hp := Pair.steps_le i start + have hpos : i + start + 2 ≤ B + 2 := by omega + have hm := Nat.mul_le_mul_left 12 hpos + rw [steps, Nat.succ_mul] + omega + +end Row + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.ClashMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/ClashMachineFull.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/ClashMachineFull.lean new file mode 100644 index 0000000000000000000000000000000000000000..2201a616351361275b64ea5def84899ba45255ab --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/ClashMachineFull.lean @@ -0,0 +1,501 @@ +import OAI.Computability.PerfectCompleteness.Machines.ClashMachine +import OAI.Computability.PerfectCompleteness.Machines.OrClosure +import OAI.Computability.UniqueGames.Machines.MachineLookupDiscard + +namespace OAI + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.ClashMachine + +open Turing MachineComposition PostfixModel InitializationTemplate +open Reduction.MachineSubstitution (pushWord stepAux_pushWord) + +variable {K Λ σ : Type} [DecidableEq K] + +namespace Full + +def rowMap : Fin 7 ↪ Fin 10 := ⟨![2, 3, 4, 5, 6, 7, 8], by decide⟩ + +structure Ready (slots : Fin 10 ↪ K) (base : K → List Bool) (q : Nat) : Prop where + source : base (slots 0) = encodeWord q + empty : ∀ k : Fin 10, k ≠ 0 → k ≠ 7 → k ≠ 8 → base (slots k) = [] + +theorem Ready.emitted {slots : Fin 10 ↪ K} {base : K → List Bool} {q : Nat} + (h : Ready slots base q) (tokens : List Token) : + Ready slots (emitted (slots 7) (slots 8) base tokens) q := by + constructor + · simpa [ClashMachine.emitted, slots.injective.eq_iff] using h.source + · intro k hk ho hc + simpa [ClashMachine.emitted, slots.injective.eq_iff, ho, hc] using h.empty k hk ho hc + +theorem ext_slots {n : Nat} (slots : Fin n ↪ K) (f g : K → List Bool) + (atSlot : ∀ i, f (slots i) = g (slots i)) + (outside : ∀ k, (∀ i, k ≠ slots i) → f k = g k) : f = g := by + classical + funext k + by_cases h : ∃ i, slots i = k + · rcases h with ⟨i, rfl⟩ + exact atSlot i + · exact outside k (fun i hi => h ⟨i, hi.symm⟩) + +def frame (slots : Fin 10 ↪ K) (base : K → List Bool) (remaining current : Nat) : K → List Bool := + Function.update (Function.update base (slots 1) (encodeWord remaining)) (slots 3) (encodeWord current) + +def closurePorts (slots : Fin 10 ↪ K) : OrClosure.Ports K where + remaining := slots 9 + reversed := slots 7 + count := slots 8 + remaining_ne_reversed := slots.injective.ne (by decide) + remaining_ne_count := slots.injective.ne (by decide) + reversed_ne_count := slots.injective.ne (by decide) + +inductive CopyContext where + | outer | inner | rowClose | allClose + deriving DecidableEq + +instance : Fintype CopyContext where + elems := { .outer, .inner, .rowClose, .allClose } + complete c := by cases c <;> simp + +inductive CopyLabel where + | seed | scan | restore + deriving DecidableEq + +instance : Fintype CopyLabel where + elems := { .seed, .scan, .restore } + complete l := by cases l <;> simp + +inductive Label where + | start + | copy (context : CopyContext) (l : CopyLabel) + | outerGuard | rowSeed + | row (l : Row.Label) + | discardInner | afterInner | rowCloseSeed | rowCloseLoop | rowFinish + | allCloseSeed | allCloseLoop | discardOuter | finish + deriving DecidableEq, Fintype + +def copyTarget (slots : Fin 10 ↪ K) : CopyContext → K + | .outer => slots 1 + | .inner => slots 2 + | .rowClose | .allClose => slots 9 + +def copyExit (labels : Label → Λ) : CopyContext → Λ + | .outer => labels .outerGuard + | .inner => labels (.row .guard) + | .rowClose => labels .rowCloseSeed + | .allClose => labels .allCloseSeed + +def statement (slots : Fin 10 ↪ K) (labels : Label → Λ) (exit : Option Λ) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (State σ) + | .start => .push (slots 3) (fun _ => false) (.goto fun _ => labels (.copy .outer .seed)) + | .copy c .seed => MachineUnaryAffineAt.seed (copyTarget slots c) 1 (labels (.copy c .scan)) + | .copy c .scan => MachineUnaryAffineAt.scan (slots 0) (slots 5) (copyTarget slots c) 1 + (labels (.copy c .scan)) (labels (.copy c .restore)) + | .copy c .restore => Reduction.MachineTransfer.loopAt (slots 5) (slots 0) id false + (labels (.copy c .restore)) (some (copyExit labels c)) + | .outerGuard => MachineUnaryCounter.guard (slots 1) (labels .rowSeed) (labels (.copy .allClose .seed)) + | .rowSeed => .push (slots 4) (fun _ => false) (.goto fun _ => labels (.copy .inner .seed)) + | .row l => Row.statement (rowMap.trans slots) (fun l => labels (.row l)) (labels .discardInner) l + | .discardInner => MachineLookup.discard (slots 4) (labels .discardInner) (labels .afterInner) + | .afterInner => .pop (slots 2) (fun s _ => s) (.goto fun _ => labels (.copy .rowClose .seed)) + | .rowCloseSeed => OrClosure.seed (closurePorts slots) (labels .rowCloseLoop) + | .rowCloseLoop => OrClosure.loop (closurePorts slots) (labels .rowCloseLoop) (some (labels .rowFinish)) + | .rowFinish => .pop (slots 9) (fun s _ => s) + (.push (slots 3) (fun _ => true) (.goto fun _ => labels .outerGuard)) + | .allCloseSeed => OrClosure.seed (closurePorts slots) (labels .allCloseLoop) + | .allCloseLoop => OrClosure.loop (closurePorts slots) (labels .allCloseLoop) (some (labels .discardOuter)) + | .discardOuter => MachineLookup.discard (slots 3) (labels .discardOuter) (labels .finish) + | .finish => .pop (slots 1) (fun s _ => s) (.pop (slots 9) (fun s _ => s) + (Reduction.MachineTransfer.exitAt (slots 7) exit)) + +def copySteps (q : Nat) : Nat := 2 * (q + 1) + 1 + +theorem copyTrace (slots : Fin 10 ↪ K) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ l, program (labels l) = statement slots labels exit l) + (context : CopyContext) (base : K → List Bool) (q : Nat) + (sourceWord : base (slots 0) = encodeWord q) (scratchEmpty : base (slots 5) = []) + (targetEmpty : base (copyTarget slots context) = []) (ambient : σ) : + (advance (TM2.step program))^[copySteps q] + (some ⟨some (labels (.copy context .seed)), clean ambient, base⟩) = + some ⟨some (copyExit labels context), clean ambient, + Function.update base (copyTarget slots context) (encodeWord (q + 1))⟩ := by + have hd : slots 0 ≠ copyTarget slots context := by + cases context <;> simp [copyTarget, slots.injective.eq_iff] + have hs : slots 5 ≠ copyTarget slots context := by + cases context <;> simp [copyTarget, slots.injective.eq_iff] + have h := MachineUnaryAffineAt.seededAffineTrace (slots 0) (slots 5) (copyTarget slots context) + (slots.injective.ne (by decide)) hd hs 1 1 (labels (.copy context .seed)) + (labels (.copy context .scan)) (labels (.copy context .restore)) + (some (copyExit labels context)) program (atLabels _) (atLabels _) (atLabels _) + base q [] (by simpa using sourceWord) scratchEmpty (ambient, false) none + simpa only [copySteps, clean, one_mul, targetEmpty, List.append_nil] using h + +theorem closureTrace (slots : Fin 10 ↪ K) (entry again : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atSeed : program entry = OrClosure.seed (closurePorts slots) again) + (atLoop : program again = OrClosure.loop (closurePorts slots) again exit) + (base : K → List Bool) (n : Nat) (word : base (slots 9) = encodeWord n) (ambient : σ) : + (advance (TM2.step program))^[n + 2] + (some ⟨some entry, clean ambient, base⟩) = + some ⟨exit, clean ambient, Function.update + (emitted (slots 7) (slots 8) base (closeOr n)) (slots 9) (encodeWord 0)⟩ := by + have h := OrClosure.closureTrace (closurePorts slots) entry again exit program atSeed atLoop + base n [] (base (slots 7)) (base (slots 8)) (ambient, false) none + have hi : OrClosure.frame (closurePorts slots) base (encodeWord n ++ []) + (base (slots 7)) (base (slots 8)) = base := by + rw [List.append_nil, ← word] + exact OrClosure.frame_self _ _ + have ho : OrClosure.frame (closurePorts slots) base (encodeWord 0 ++ []) + ((tokenBits (closeOr n)).reverse ++ base (slots 7)) + (List.replicate (n + 1) true ++ base (slots 8)) = + Function.update (emitted (slots 7) (slots 8) base (closeOr n)) (slots 9) (encodeWord 0) := by + apply ext_slots slots + · intro i + fin_cases i <;> simp [OrClosure.frame, closurePorts, emitted, closeOr, slots.injective.eq_iff] + · intro k hk + simp [OrClosure.frame, closurePorts, emitted, hk] + rw [hi, ho] at h + exact h + +theorem emitted_frame (slots : Fin 10 ↪ K) (base : K → List Bool) (r i : Nat) (tokens : List Token) : + emitted (slots 7) (slots 8) (frame slots base r i) tokens = + frame slots (emitted (slots 7) (slots 8) base tokens) r i := by + apply ext_slots slots + · intro k + fin_cases k <;> simp [frame, emitted, slots.injective.eq_iff] + · intro k hk + simp [frame, emitted, hk] + +def bodySteps (q i : Nat) : Nat := + 1 + copySteps q + Row.steps (q + 1) i 0 + (q + 2) + 1 + copySteps q + (q + 3) + 1 + +theorem bodySteps_eq (q i : Nat) : bodySteps q i = Row.steps (q + 1) i 0 + 6 * q + 14 := by + unfold bodySteps copySteps + omega + +theorem bodyTrace (slots : Fin 10 ↪ K) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ l, program (labels l) = statement slots labels exit l) + (base : K → List Bool) (q r i : Nat) (ready : Ready slots base q) (ambient : σ) : + (advance (TM2.step program))^[bodySteps q i] + (some ⟨some (labels .rowSeed), clean ambient, frame slots base r i⟩) = + some ⟨some (labels .outerGuard), clean ambient, + frame slots (emitted (slots 7) (slots 8) base (clashRowTokens q i)) r (i + 1)⟩ := by + let initial := frame slots base r i + let seeded := Function.update initial (slots 4) (encodeWord 0) + have hseed : (advance (TM2.step program))^[1] + (some ⟨some (labels .rowSeed), clean ambient, initial⟩) = + some ⟨some (labels (.copy .inner .seed)), clean ambient, seeded⟩ := by + change some (TM2.stepAux (program (labels .rowSeed)) _ _) = _ + rw [atLabels, statement] + simp [TM2.stepAux, seeded, initial, frame, slots.injective.eq_iff, + ready.empty 4 (by decide) (by decide) (by decide), encodeWord] + have hq : seeded (slots 0) = encodeWord q := by + simpa [seeded, initial, frame, slots.injective.eq_iff] using ready.source + have hs : seeded (slots 5) = [] := by + simpa [seeded, initial, frame, slots.injective.eq_iff] using + ready.empty 5 (by decide) (by decide) (by decide) + have ht : seeded (copyTarget slots .inner) = [] := by + simpa [copyTarget, seeded, initial, frame, slots.injective.eq_iff] using + ready.empty 2 (by decide) (by decide) (by decide) + have hcopy := copyTrace slots labels exit program atLabels .inner seeded q hq hs ht ambient + have hstart : Function.update seeded (copyTarget slots .inner) (encodeWord (q + 1)) = + Row.frame (rowMap.trans slots) initial (q + 1) 0 := by + change Function.update (Function.update initial (slots 4) (encodeWord 0)) + (slots 2) (encodeWord (q + 1)) = + Function.update (Function.update initial (slots 2) (encodeWord (q + 1))) + (slots 4) (encodeWord 0) + exact Function.update_comm (slots.injective.ne (by decide : (4 : Fin 10) ≠ 2)) _ _ _ + rw [hstart] at hcopy + have hi : initial (slots 3) = encodeWord i := by simp [initial, frame] + have hsl : initial (slots 5) = [] := by + simpa [initial, frame, slots.injective.eq_iff] using + ready.empty 5 (by decide) (by decide) (by decide) + have hsr : initial (slots 6) = [] := by + simpa [initial, frame, slots.injective.eq_iff] using + ready.empty 6 (by decide) (by decide) (by decide) + have hrow := Row.trace (rowMap.trans slots) (fun l => labels (.row l)) + (labels .discardInner) program (fun _ => atLabels _) initial (q + 1) i 0 hi hsl hsr ambient + simp only [Nat.zero_add] at hrow + let innerTokens := Row.tokens (q + 1) i 0 + let innerBase := emitted (slots 7) (slots 8) base innerTokens + have innerReady : Ready slots innerBase q := ready.emitted innerTokens + let afterRow := Row.frame (rowMap.trans slots) (frame slots innerBase r i) 0 (q + 1) + change (advance (TM2.step program))^[Row.steps (q + 1) i 0] + (some ⟨some (labels (.row .guard)), clean ambient, Row.frame (rowMap.trans slots) initial (q + 1) 0⟩) = + some ⟨some (labels .discardInner), clean ambient, + Row.frame (rowMap.trans slots) (emitted (slots 7) (slots 8) initial innerTokens) 0 (q + 1)⟩ at hrow + have hemit : emitted (slots 7) (slots 8) initial innerTokens = frame slots innerBase r i := + emitted_frame slots base r i innerTokens + rw [hemit] at hrow + have hj : afterRow (slots 4) = encodeWord (q + 1) := by simp [afterRow, Row.frame, rowMap] + have hdiscard := MachineLookup.discardTrace (slots 4) (labels .discardInner) (labels .afterInner) + program (atLabels .discardInner) afterRow (q + 1) [] (by simpa using hj) (ambient, false) none + have hclean : (advance (TM2.step program))^[1] + (some ⟨some (labels .afterInner), clean ambient, Function.update afterRow (slots 4) []⟩) = + some ⟨some (labels (.copy .rowClose .seed)), clean ambient, frame slots innerBase r i⟩ := by + change some (TM2.stepAux (program (labels .afterInner)) _ _) = _ + rw [atLabels, statement] + simp only [TM2.stepAux] + congr 2 + apply ext_slots slots + · intro k + fin_cases k <;> simp [afterRow, Row.frame, rowMap, frame, slots.injective.eq_iff, + encodeWord, innerReady.empty 2 (by decide) (by decide) (by decide), + innerReady.empty 4 (by decide) (by decide) (by decide)] + · intro k hk + simp [afterRow, Row.frame, rowMap, frame, hk] + have hcq : frame slots innerBase r i (slots 0) = encodeWord q := by + simpa [frame, slots.injective.eq_iff] using innerReady.source + have hcs : frame slots innerBase r i (slots 5) = [] := by + simpa [frame, slots.injective.eq_iff] using innerReady.empty 5 (by decide) (by decide) (by decide) + have hct : frame slots innerBase r i (copyTarget slots .rowClose) = [] := by + simpa [frame, copyTarget, slots.injective.eq_iff] using + innerReady.empty 9 (by decide) (by decide) (by decide) + have hcCopy := copyTrace slots labels exit program atLabels .rowClose + (frame slots innerBase r i) q hcq hcs hct ambient + let closeStart := Function.update (frame slots innerBase r i) (slots 9) (encodeWord (q + 1)) + have hclose := closureTrace slots (labels .rowCloseSeed) (labels .rowCloseLoop) + (some (labels .rowFinish)) program (atLabels .rowCloseSeed) (atLabels .rowCloseLoop) + closeStart (q + 1) (by simp [closeStart]) ambient + let closeEnd := Function.update (emitted (slots 7) (slots 8) closeStart (closeOr (q + 1))) + (slots 9) (encodeWord 0) + let closeBase := emitted (slots 7) (slots 8) innerBase (closeOr (q + 1)) + have hfinish : (advance (TM2.step program))^[1] + (some ⟨some (labels .rowFinish), clean ambient, closeEnd⟩) = + some ⟨some (labels .outerGuard), clean ambient, frame slots closeBase r (i + 1)⟩ := by + change some (TM2.stepAux (program (labels .rowFinish)) _ _) = _ + rw [atLabels, statement] + simp only [TM2.stepAux] + congr 2 + apply ext_slots slots + · intro k + fin_cases k <;> simp [closeEnd, closeStart, closeBase, emitted, frame, slots.injective.eq_iff, + encodeWord, List.replicate_succ, innerReady.empty 9 (by decide) (by decide) (by decide)] + · intro k hk + simp [closeEnd, closeStart, closeBase, emitted, frame, hk] + have h := chain (chain (chain (chain (chain (chain (chain hseed hcopy) hrow) hdiscard) hclean) + hcCopy) hclose) hfinish + have hout : closeBase = emitted (slots 7) (slots 8) base (clashRowTokens q i) := by + rw [show closeBase = emitted (slots 7) (slots 8) + (emitted (slots 7) (slots 8) base innerTokens) (closeOr (q + 1)) from rfl, + emitted_append (slots 7) (slots 8) (slots.injective.ne (by decide : (7 : Fin 10) ≠ 8))] + simp [clashRowTokens, innerTokens, Row.tokens] + rw [hout] at h + exact h + +theorem counter_frame (slots : Fin 10 ↪ K) (base : K → List Bool) (r r' i : Nat) : + MachineUnaryCounter.counterTapes (slots 1) (frame slots base r i) r' [] = frame slots base r' i := by + apply ext_slots slots + · intro k + fin_cases k <;> simp [MachineUnaryCounter.counterTapes, frame, slots.injective.eq_iff] + · intro k hk + simp [MachineUnaryCounter.counterTapes, frame, hk] + +def loopTokens (count q start : Nat) : List Token := + forTokens count (fun j => clashRowTokens q (start + j)) + +theorem loopTokens_succ (count q start : Nat) : + loopTokens (count + 1) q start = clashRowTokens q start ++ loopTokens count q (start + 1) := by + rw [loopTokens, forTokens_succ_first] + simp only [Nat.add_zero] + apply congrArg (List.append (clashRowTokens q start)) + apply forTokens_congr + intro j _ + rw [show start + (j + 1) = start + 1 + j by omega] + +def loopSteps : Nat → Nat → Nat → Nat + | 0, _, _ => 1 + | count + 1, q, start => 1 + bodySteps q start + loopSteps count q (start + 1) + +theorem loopTrace (slots : Fin 10 ↪ K) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ l, program (labels l) = statement slots labels exit l) + (base : K → List Bool) (q count start : Nat) (ready : Ready slots base q) (ambient : σ) : + (advance (TM2.step program))^[loopSteps count q start] + (some ⟨some (labels .outerGuard), clean ambient, frame slots base count start⟩) = + some ⟨some (labels (.copy .allClose .seed)), clean ambient, + frame slots (emitted (slots 7) (slots 8) base (loopTokens count q start)) 0 (start + count)⟩ := by + induction count generalizing base start with + | zero => + have h := MachineUnaryCounter.guardTrace_zero (slots 1) (labels .outerGuard) + (labels .rowSeed) (labels (.copy .allClose .seed)) program (atLabels .outerGuard) + (frame slots base 0 start) [] (ambient, false) none + simpa only [counter_frame, loopSteps, loopTokens, forTokens, emitted_nil, Nat.add_zero, clean] using h + | succ count ih => + have hg := MachineUnaryCounter.guardTrace_succ (slots 1) (labels .outerGuard) + (labels .rowSeed) (labels (.copy .allClose .seed)) program (atLabels .outerGuard) + (frame slots base count start) count [] (ambient, false) none + simp only [counter_frame] at hg + have hb := bodyTrace slots labels exit program atLabels base q count start ready ambient + let nextBase := emitted (slots 7) (slots 8) base (clashRowTokens q start) + have hr := ih nextBase (start + 1) (ready.emitted (clashRowTokens q start)) + have h := chain (chain hg hb) hr + rw [show start + 1 + count = start + (count + 1) by omega] at h + simp only [nextBase, + emitted_append (slots 7) (slots 8) (slots.injective.ne (by decide : (7 : Fin 10) ≠ 8)), + ← loopTokens_succ] at h + exact h + +def bodyBudget (q : Nat) : Nat := (q + 1) * (12 * (2 * q + 3) + 2) + 1 + 6 * q + 14 + +theorem bodySteps_le (q i : Nat) (hi : i ≤ q) : bodySteps q i ≤ bodyBudget q := by + have h := Row.steps_le (q + 1) i 0 (2 * q + 1) (by omega) + rw [bodySteps_eq] + unfold bodyBudget + have he : 12 * (2 * q + 1 + 2) + 2 = 12 * (2 * q + 3) + 2 := by omega + rw [he] at h + omega + +theorem loopSteps_le (count q start : Nat) (hbound : start + count ≤ q + 1) : + loopSteps count q start ≤ count * (bodyBudget q + 1) + 1 := by + induction count generalizing start with + | zero => simp [loopSteps] + | succ count ih => + have hr := ih (start + 1) (by omega) + have hb := bodySteps_le q start (by omega) + rw [loopSteps, Nat.succ_mul] + omega + +def steps (q : Nat) : Nat := + 1 + copySteps q + loopSteps (q + 1) q 0 + copySteps q + (q + 3) + (q + 2) + 1 + +theorem trace (slots : Fin 10 ↪ K) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ l, program (labels l) = statement slots labels exit l) + (base : K → List Bool) (q : Nat) (ready : Ready slots base q) (ambient : σ) : + (advance (TM2.step program))^[steps q] + (some ⟨some (labels .start), clean ambient, base⟩) = + some ⟨exit, clean ambient, emitted (slots 7) (slots 8) base (clashTokens q)⟩ := by + let seeded := Function.update base (slots 3) (encodeWord 0) + have hstart : (advance (TM2.step program))^[1] + (some ⟨some (labels .start), clean ambient, base⟩) = + some ⟨some (labels (.copy .outer .seed)), clean ambient, seeded⟩ := by + change some (TM2.stepAux (program (labels .start)) _ _) = _ + rw [atLabels, statement] + simp [TM2.stepAux, seeded, ready.empty 3 (by decide) (by decide) (by decide), encodeWord] + have hs : seeded (slots 0) = encodeWord q := by + simpa [seeded, slots.injective.eq_iff] using ready.source + have hw : seeded (slots 5) = [] := by + simpa [seeded, slots.injective.eq_iff] using ready.empty 5 (by decide) (by decide) (by decide) + have hd : seeded (copyTarget slots .outer) = [] := by + simpa [seeded, copyTarget, slots.injective.eq_iff] using + ready.empty 1 (by decide) (by decide) (by decide) + have hcopy := copyTrace slots labels exit program atLabels .outer seeded q hs hw hd ambient + have hframe : Function.update seeded (copyTarget slots .outer) (encodeWord (q + 1)) = + frame slots base (q + 1) 0 := by + apply ext_slots slots + · intro k + fin_cases k <;> simp [seeded, copyTarget, frame, slots.injective.eq_iff] + · intro k hk + simp [seeded, copyTarget, frame, hk] + rw [hframe] at hcopy + have hloop := loopTrace slots labels exit program atLabels base q (q + 1) 0 ready ambient + simp only [Nat.zero_add] at hloop + let loopBase := emitted (slots 7) (slots 8) base (loopTokens (q + 1) q 0) + have loopReady : Ready slots loopBase q := ready.emitted _ + let afterLoop := frame slots loopBase 0 (q + 1) + have hcq : afterLoop (slots 0) = encodeWord q := by + simpa [afterLoop, frame, slots.injective.eq_iff] using loopReady.source + have hcw : afterLoop (slots 5) = [] := by + simpa [afterLoop, frame, slots.injective.eq_iff] using loopReady.empty 5 (by decide) (by decide) (by decide) + have hcd : afterLoop (copyTarget slots .allClose) = [] := by + simpa [afterLoop, frame, copyTarget, slots.injective.eq_iff] using + loopReady.empty 9 (by decide) (by decide) (by decide) + have hcopyEnd := copyTrace slots labels exit program atLabels .allClose afterLoop q hcq hcw hcd ambient + let closeStart := Function.update afterLoop (slots 9) (encodeWord (q + 1)) + have hclose := closureTrace slots (labels .allCloseSeed) (labels .allCloseLoop) + (some (labels .discardOuter)) program (atLabels .allCloseSeed) (atLabels .allCloseLoop) + closeStart (q + 1) (by simp [closeStart]) ambient + let closeEnd := Function.update (emitted (slots 7) (slots 8) closeStart (closeOr (q + 1))) + (slots 9) (encodeWord 0) + have hi : closeEnd (slots 3) = encodeWord (q + 1) := by + simp [closeEnd, closeStart, afterLoop, frame, emitted, slots.injective.eq_iff] + have hdiscard := MachineLookup.discardTrace (slots 3) (labels .discardOuter) (labels .finish) + program (atLabels .discardOuter) closeEnd (q + 1) [] (by simpa using hi) (ambient, false) none + let finalBase := emitted (slots 7) (slots 8) loopBase (closeOr (q + 1)) + have hfinish : (advance (TM2.step program))^[1] + (some ⟨some (labels .finish), clean ambient, Function.update closeEnd (slots 3) []⟩) = + some ⟨exit, clean ambient, finalBase⟩ := by + change some (TM2.stepAux (program (labels .finish)) _ _) = _ + rw [atLabels, statement] + have ht : Function.update (Function.update (Function.update closeEnd (slots 3) []) + (slots 1) []) (slots 9) [] = finalBase := by + apply ext_slots slots + · intro k + fin_cases k <;> simp [closeEnd, closeStart, afterLoop, finalBase, frame, emitted, + slots.injective.eq_iff, loopReady.empty 1 (by decide) (by decide) (by decide), + loopReady.empty 3 (by decide) (by decide) (by decide), + loopReady.empty 9 (by decide) (by decide) (by decide)] + · intro k hk + simp [closeEnd, closeStart, afterLoop, finalBase, frame, emitted, hk] + have hr : (Function.update closeEnd (slots 3) []) (slots 1) = encodeWord 0 := by + simp [closeEnd, closeStart, afterLoop, frame, emitted, slots.injective.eq_iff] + have hc : (Function.update (Function.update closeEnd (slots 3) []) (slots 1) []) (slots 9) = + encodeWord 0 := by simp [closeEnd, slots.injective.eq_iff] + simp only [TM2.stepAux, hr, hc, encodeWord, List.replicate_zero, + List.nil_append, List.tail_cons, ht] + cases exit <;> rfl + have h := chain (chain (chain (chain (chain (chain hstart hcopy) hloop) hcopyEnd) hclose) hdiscard) hfinish + have hout : finalBase = emitted (slots 7) (slots 8) base (clashTokens q) := by + rw [show finalBase = emitted (slots 7) (slots 8) + (emitted (slots 7) (slots 8) base (loopTokens (q + 1) q 0)) (closeOr (q + 1)) from rfl, + emitted_append (slots 7) (slots 8) (slots.injective.ne (by decide : (7 : Fin 10) ≠ 8))] + simp [clashTokens, loopTokens] + rw [hout] at h + exact h + +noncomputable def bodyPolynomial : Polynomial Nat := + (Polynomial.X + Polynomial.C 1) * + (Polynomial.C 12 * (Polynomial.C 2 * Polynomial.X + Polynomial.C 3) + Polynomial.C 2) + + Polynomial.C 1 + Polynomial.C 6 * Polynomial.X + Polynomial.C 14 + +noncomputable def timePolynomial : Polynomial Nat := + (Polynomial.X + Polynomial.C 1) * (bodyPolynomial + Polynomial.C 1) + + Polynomial.C 1 + Polynomial.C 6 * Polynomial.X + Polynomial.C 13 + +theorem timePolynomial_eval (q : Nat) : + timePolynomial.eval q = (q + 1) * (bodyBudget q + 1) + 1 + 6 * q + 13 := by + simp [timePolynomial, bodyPolynomial, bodyBudget] + +theorem steps_le_time (q : Nat) : steps q ≤ timePolynomial.eval q := by + have h := loopSteps_le (q + 1) q 0 (by omega) + rw [timePolynomial_eval] + unfold steps copySteps + omega + +def inTime (slots : Fin 10 ↪ K) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ l, program (labels l) = statement slots labels exit l) + (base : K → List Bool) (q : Nat) (ready : Ready slots base q) (ambient : σ) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .start), clean ambient, base⟩ + (some ⟨exit, clean ambient, emitted (slots 7) (slots 8) base (clashTokens q)⟩) + (timePolynomial.eval q) where + steps := steps q + evals_in_steps := trace slots labels exit program atLabels base q ready ambient + steps_le_m := steps_le_time q + +abbrev machine : FinTM2 where + K := Fin 10 + k₀ := 0 + k₁ := 7 + Γ _ := Bool + Λ := Label + main := .start + σ := State Unit + initialState := clean () + m := statement (Function.Embedding.refl _) id none + +def machineInTime (base : Fin 10 → List Bool) (q : Nat) + (ready : Ready (Function.Embedding.refl _) base q) : + StateTransition.EvalsToInTime machine.step ⟨some .start, clean (), base⟩ + (some ⟨none, clean (), emitted 7 8 base (clashTokens q)⟩) (timePolynomial.eval q) := + inTime (Function.Embedding.refl _) id none machine.m (fun _ => rfl) base q ready () + +end Full + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.ClashMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/CleanRecordDecoderInput.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/CleanRecordDecoderInput.lean new file mode 100644 index 0000000000000000000000000000000000000000..cfd575f658d30265e022bc16c0698f17156b2a83 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/CleanRecordDecoderInput.lean @@ -0,0 +1,117 @@ +import OAI.Computability.PerfectCompleteness.Decoding.CleanLeftDecoderLemmas +import OAI.Computability.PerfectCompleteness.Repetition.CleanPhysicalReplay +import OAI.Computability.PerfectCompleteness.Repetition.CleanRecordObservation + +namespace OAI + +section + +namespace PerfectCompleteness.CleanRecordDecoderInput + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays + +variable {branch : Nat → Nat} {n h t v m : Nat} [NeZero m] + (rows repeats : Nat → Nat) (upper : Nodes branch n) + (d : HierarchicalFrozenTables.LowerNodes upper (h + 1)) + (cut : OwnInputReference.Cut upper (HierarchicalLeftDecoder.LowerNode upper (h + 1) d)) + +abbrev path := CleanRightDecoder.fullPath upper + (HierarchicalLeftDecoder.LowerNode upper (h + 1) d) cut + (CleanDecoderContext.lowerHeight upper d) + +variable (outside : Slots branch n → Fin t → MixedSupport.Slot) + (placeholder : Slots branch (h + 1) → Fin t → MixedSupport.Slot) + (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch h) → Slots branch h) + +abbrev Record := CleanPhysicalReplay.Record (t := t) rows repeats (path upper d cut) clauses designated +abbrev Sample := CleanPhysicalReplay.Sample (t := t) rows repeats (path upper d cut) clauses designated +abbrev Exterior := CleanPhysicalReplay.Exterior rows repeats (path upper d cut) outside placeholder + +def exposed (record : Record (t := t) rows repeats upper d cut clauses designated) + (external : Exterior rows repeats upper d cut outside placeholder) : + CleanDecoderContext.Exposed branch rows repeats n h t v m upper d where + clauses := clauses + designated := designated + clean := CleanRecordChildBlocks.clean rows clauses designated record + visible := CleanRecordChildBlocks.visible rows clauses designated record + projected := CleanRecordChildBlocks.projected rows clauses designated record + cleanProjected := CleanSourceRecord.clean_projected designated + (SourceChildKernel.Factors (C := WholeCutCalls.Index rows repeats (path upper d cut)) + (t := t) rows clauses designated) record + cut := cut + outside := outside + leftTape := CleanPhysicalReplay.leftRecord rows repeats (path upper d cut) outside placeholder + clauses designated record external + rightTape := CleanPhysicalReplay.rightRecord rows repeats (path upper d cut) outside placeholder + clauses designated record external + +abbrev observe (x : Sample (t := t) rows repeats upper d cut clauses designated) : + Record (t := t) rows repeats upper d cut clauses designated := + CleanRecordObservation.observe rows clauses designated x + +omit [NeZero m] in +@[simp] theorem event_observe (x : Sample (t := t) rows repeats upper d cut clauses designated) : + CleanRecordChildBlocks.event rows clauses designated + (observe rows repeats upper d cut clauses designated x) x = true := + CleanRecordObservation.event_observe rows clauses designated x + +def leftQuestions (record : Record (t := t) rows repeats upper d cut clauses designated) + (x : Sample (t := t) rows repeats upper d cut clauses designated) := + CleanRecordObservation.leftQuestions rows clauses designated record x + +def rightQuestions (record : Record (t := t) rows repeats upper d cut clauses designated) + (x : Sample (t := t) rows repeats upper d cut clauses designated) := + CleanRecordObservation.rightQuestions rows clauses designated record x + +def sources (record : Record (t := t) rows repeats upper d cut clauses designated) + (x : Sample (t := t) rows repeats upper d cut clauses designated) : + {i : Fin (branch h) // CleanRecordChildBlocks.clean rows clauses designated record i} → + SourceOddLists.Occurrences m t := fun i => (x i.val).1 + +omit [NeZero m] in +theorem leftQuestions_sources (record : Record (t := t) rows repeats upper d cut clauses designated) + (x : Sample (t := t) rows repeats upper d cut clauses designated) : + leftQuestions rows repeats upper d cut clauses designated record x = + fun i => SourceOddLists.left (sources rows repeats upper d cut clauses designated record x i) := rfl + +omit [NeZero m] in +theorem rightQuestions_sources (record : Record (t := t) rows repeats upper d cut clauses designated) + (x : Sample (t := t) rows repeats upper d cut clauses designated) : + rightQuestions rows repeats upper d cut clauses designated record x = + fun i => SourceOddLists.right clauses + (sources rows repeats upper d cut clauses designated record x i) := rfl + +theorem leftSlots_eq (record : Record (t := t) rows repeats upper d cut clauses designated) + (external : Exterior rows repeats upper d cut outside placeholder) + (x : Sample (t := t) rows repeats upper d cut clauses designated) + (hevent : CleanRecordChildBlocks.event rows clauses designated record x = true) : + CleanDecoderContext.leftSlots + (exposed rows repeats upper d cut outside placeholder clauses designated record external) + (leftQuestions rows repeats upper d cut clauses designated record x) = + CutSlotAssembly.fill (path upper d cut) outside + (CleanPhysicalReplay.leftInside rows repeats (path upper d cut) clauses designated x) := by + exact congrArg (CutSlotAssembly.fill (path upper d cut) outside) + (CleanRecordObservation.leftInside_eq rows clauses designated record x hevent) + +theorem rightSlots_eq (record : Record (t := t) rows repeats upper d cut clauses designated) + (external : Exterior rows repeats upper d cut outside placeholder) + (x : Sample (t := t) rows repeats upper d cut clauses designated) + (hevent : CleanRecordChildBlocks.event rows clauses designated record x = true) : + CleanDecoderContext.rightSlots + (exposed rows repeats upper d cut outside placeholder clauses designated record external) + (rightQuestions rows repeats upper d cut clauses designated record x) = + CutSlotAssembly.fill (path upper d cut) outside + (CleanPhysicalReplay.rightInside rows repeats (path upper d cut) clauses designated x) := by + exact congrArg (CutSlotAssembly.fill (path upper d cut) outside) + (CleanRecordObservation.rightInside_eq rows clauses designated record x hevent) + +end +end PerfectCompleteness.CleanRecordDecoderInput + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/ClockPreparation.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/ClockPreparation.lean new file mode 100644 index 0000000000000000000000000000000000000000..7698206f6bd554b9c68e2f0587803239c932f95a --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/ClockPreparation.lean @@ -0,0 +1,504 @@ +import OAI.Computability.PerfectCompleteness.Machines.VerifierCircuit +import OAI.Computability.UniqueGames.PCP.SourceHeaderCounts + +namespace OAI + +section + + +noncomputable section +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.ClockPreparation + +open Turing MachineComposition +open UniqueGamesTheorem.Foundations.Hastad.SourceHeaderCounts +open PolynomialMachine + +abbrev PhasePrivate (p : Polynomial Nat) := Fin 5 ⊕ Fin (width p) + +def Private : List (Polynomial Nat) → Type + | [] => Empty + | p :: ps => PhasePrivate p ⊕ Private ps + +abbrev Layout (ps : List (Polynomial Nat)) := Unit ⊕ Private ps + +def Label : List (Polynomial Nat) → Type + | [] => Empty + | p :: ps => Eval.Label p ⊕ Label ps + +def Output : List (Polynomial Nat) → Type + | [] => Empty + | _ :: ps => Unit ⊕ Output ps + +instance privateFintype (ps : List (Polynomial Nat)) : Fintype (Private ps) := by + induction ps with + | nil => exact inferInstanceAs (Fintype Empty) + | cons p ps ih => + letI := ih + exact inferInstanceAs (Fintype (PhasePrivate p ⊕ Private ps)) + +instance privateDecidableEq (ps : List (Polynomial Nat)) : DecidableEq (Private ps) := by + induction ps with + | nil => exact inferInstanceAs (DecidableEq Empty) + | cons p ps ih => + letI := ih + exact inferInstanceAs (DecidableEq (PhasePrivate p ⊕ Private ps)) + +instance labelFintype (ps : List (Polynomial Nat)) : Fintype (Label ps) := by + induction ps with + | nil => exact inferInstanceAs (Fintype Empty) + | cons p ps ih => + letI := ih + exact inferInstanceAs (Fintype (Eval.Label p ⊕ Label ps)) + +instance labelDecidableEq (ps : List (Polynomial Nat)) : DecidableEq (Label ps) := by + induction ps with + | nil => exact inferInstanceAs (DecidableEq Empty) + | cons p ps ih => + letI := ih + exact inferInstanceAs (DecidableEq (Eval.Label p ⊕ Label ps)) + +instance outputFintype (ps : List (Polynomial Nat)) : Fintype (Output ps) := by + induction ps with + | nil => exact inferInstanceAs (Fintype Empty) + | cons p ps ih => + letI := ih + exact inferInstanceAs (Fintype (Unit ⊕ Output ps)) + +def controlSlots (p : Polynomial Nat) (ps : List (Polynomial Nat)) : Fin 6 ↪ Layout (p :: ps) where + toFun i := match i.val with + | 0 => .inl () + | 1 => .inr (.inl (.inl 0)) + | 2 => .inr (.inl (.inl 1)) + | 3 => .inr (.inl (.inl 2)) + | 4 => .inr (.inl (.inl 3)) + | _ => .inr (.inl (.inl 4)) + inj' := by + intro i j h + fin_cases i <;> fin_cases j <;> cases h <;> rfl + +def headLayout (p : Polynomial Nat) (ps : List (Polynomial Nat)) : + MachineHorner.Layout (width p) ↪ Layout (p :: ps) where + toFun + | .inl i => controlSlots p ps i + | .inr i => .inr (.inl (.inr i)) + inj' := by + intro a b h + cases a with + | inl a => + cases b with + | inl b => exact congrArg Sum.inl ((controlSlots p ps).injective h) + | inr b => fin_cases a <;> cases h + | inr a => + cases b with + | inl b => fin_cases b <;> cases h + | inr b => + exact congrArg Sum.inr (Sum.inr.inj (Sum.inl.inj (Sum.inr.inj h))) + +def tailLayout (p : Polynomial Nat) (ps : List (Polynomial Nat)) : + Layout ps ↪ Layout (p :: ps) where + toFun + | .inl _ => .inl () + | .inr i => .inr (.inr i) + inj' := by + intro a b h + cases a with + | inl a => (cases b <;> cases h); rfl + | inr a => + cases b with + | inl b => cases h + | inr b => exact congrArg Sum.inr (Sum.inr.inj (Sum.inr.inj h)) + +variable {K Λ σ : Type} [DecidableEq K] + +def headSlots {p : Polynomial Nat} {ps : List (Polynomial Nat)} + (slots : Layout (p :: ps) ↪ K) : MachineHorner.Layout (width p) ↪ K := + (headLayout p ps).trans slots + +def tailSlots {p : Polynomial Nat} {ps : List (Polynomial Nat)} + (slots : Layout (p :: ps) ↪ K) : Layout ps ↪ K := + (tailLayout p ps).trans slots + +omit [DecidableEq K] in +@[simp] theorem headSlots_input {p : Polynomial Nat} {ps : List (Polynomial Nat)} + (slots : Layout (p :: ps) ↪ K) : headSlots slots (.inl 0) = slots (.inl ()) := rfl + +omit [DecidableEq K] in +@[simp] theorem headSlots_output {p : Polynomial Nat} {ps : List (Polynomial Nat)} + (slots : Layout (p :: ps) ↪ K) : + headSlots slots (.inl 3) = slots (.inr (.inl (.inl 2))) := rfl + +omit [DecidableEq K] in +@[simp] theorem tailSlots_input {p : Polynomial Nat} {ps : List (Polynomial Nat)} + (slots : Layout (p :: ps) ↪ K) : tailSlots slots (.inl ()) = slots (.inl ()) := rfl + +omit [DecidableEq K] in +theorem head_output_ne_tail {p : Polynomial Nat} {ps : List (Polynomial Nat)} + (slots : Layout (p :: ps) ↪ K) (i : Layout ps) : + headSlots slots (.inl 3) ≠ tailSlots slots i := by + have controlPort : controlSlots p ps 3 = (.inr (.inl (.inl 2)) : Layout (p :: ps)) := by + rw [controlSlots.eq_1] + rfl + have headPort : headLayout p ps (.inl 3) = (.inr (.inl (.inl 2)) : Layout (p :: ps)) := by + rw [headLayout.eq_1] + exact controlPort + rw [headSlots.eq_1, tailSlots.eq_1] + change slots (headLayout p ps (.inl 3)) ≠ slots (tailLayout p ps i) + rw [headPort] + cases i with + | inl => + change slots (.inr (.inl (.inl 2))) ≠ slots (.inl ()) + exact slots.injective.ne (by intro h; cases h) + | inr i => + change slots (.inr (.inl (.inl 2))) ≠ slots (.inr (.inr i)) + exact slots.injective.ne (by intro h; cases h) + +def Clean (ps : List (Polynomial Nat)) (slots : Layout ps ↪ K) (base : K → List Bool) : Prop := + ∀ i : Private ps, base (slots (.inr i)) = [] + +omit [DecidableEq K] in +theorem head_clean {p : Polynomial Nat} {ps : List (Polynomial Nat)} + (slots : Layout (p :: ps) ↪ K) (base : K → List Bool) (h : Clean (p :: ps) slots base) : + MachineHorner.Clean (headSlots slots) base := + ⟨h (.inl (.inl 0)), h (.inl (.inl 1)), h (.inl (.inl 3)), h (.inl (.inl 4))⟩ + +omit [DecidableEq K] in +theorem head_coefficients_clean {p : Polynomial Nat} {ps : List (Polynomial Nat)} + (slots : Layout (p :: ps) ↪ K) (base : K → List Bool) (h : Clean (p :: ps) slots base) + (i : Fin (width p)) : base (headSlots slots (.inr i)) = [] := + h (.inl (.inr i)) + +theorem tail_clean_after_head {p : Polynomial Nat} {ps : List (Polynomial Nat)} + (slots : Layout (p :: ps) ↪ K) (base : K → List Bool) + (h : Clean (p :: ps) slots base) (value : Nat) : + Clean ps (tailSlots slots) (MachineHorner.resultTapes (headSlots slots) base value) := by + intro i + rw [MachineHorner.resultTapes, Function.update_of_ne (head_output_ne_tail slots (.inr i)).symm] + exact h (.inr i) + +def entry : (ps : List (Polynomial Nat)) → (Label ps → Λ) → Option Λ → Option Λ + | [], _, exit => exit + | p :: _, labels, _ => some (labels (.inl (Eval.start p))) + +def statement : (ps : List (Polynomial Nat)) → (slots : Layout ps ↪ K) → + (Label ps → Λ) → Option Λ → Label ps → + TM2.Stmt (fun _ : K => Bool) Λ (MachineHorner.State σ) + | [], _, _, _, l => Empty.elim l + | p :: ps, slots, labels, exit, .inl l => + Eval.statement p (headSlots slots) (fun l => labels (.inl l)) + (entry ps (fun l => labels (.inr l)) exit) l + | _ :: ps, slots, labels, exit, .inr l => + statement ps (tailSlots slots) (fun l => labels (.inr l)) exit l + +def resultTapes : (ps : List (Polynomial Nat)) → (Layout ps ↪ K) → + (K → List Bool) → Nat → K → List Bool + | [], _, base, _ => base + | p :: ps, slots, base, n => + resultTapes ps (tailSlots slots) + (MachineHorner.resultTapes (headSlots slots) base (p.eval n)) n + +def steps : List (Polynomial Nat) → Nat → Nat + | [], _ => 0 + | p :: ps, n => Eval.steps p n + steps ps n + +def timePolynomial : List (Polynomial Nat) → Polynomial Nat + | [] => 0 + | p :: ps => PolynomialMachine.timePolynomial p + timePolynomial ps + +theorem steps_le_timePolynomial (ps : List (Polynomial Nat)) (n : Nat) : + steps ps n ≤ (timePolynomial ps).eval n := by + induction ps with + | nil => simp [steps, timePolynomial] + | cons p ps ih => + have hp : Eval.steps p n ≤ (PolynomialMachine.timePolynomial p).eval n := by + rw [PolynomialMachine.timePolynomial_eval] + unfold Eval.steps + omega + simpa only [steps, timePolynomial, Polynomial.eval_add] using Nat.add_le_add hp ih + +private theorem trace_trans {A : Type*} (f : A → A) {a b : Nat} {x y z : A} + (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 trace (ps : List (Polynomial Nat)) (slots : Layout ps ↪ K) + (labels : Label ps → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (MachineHorner.State σ)) + (atLabels : ∀ l, program (labels l) = statement ps slots labels exit l) + (base : K → List Bool) (n : Nat) + (hinput : base (slots (.inl ())) = encodeWord n) (clean : Clean ps slots base) + (ambient : σ) : + (advance (TM2.step program))^[steps ps n] + (some ⟨entry ps labels exit, ((ambient, ()), none), base⟩) = + some ⟨exit, ((ambient, ()), none), resultTapes ps slots base n⟩ := by + induction ps generalizing base with + | nil => rfl + | cons p ps ih => + have first := Eval.trace p (headSlots slots) (fun l => labels (.inl l)) + (entry ps (fun l => labels (.inr l)) exit) program + (fun l => atLabels (.inl l)) base n (by simpa using hinput) + (head_coefficients_clean slots base clean) (head_clean slots base clean) ambient none + have hnext : MachineHorner.resultTapes (headSlots slots) base (p.eval n) + (tailSlots slots (.inl ())) = encodeWord n := by + rw [MachineHorner.resultTapes, + Function.update_of_ne (head_output_ne_tail slots (.inl ())).symm] + exact hinput + have second := ih (tailSlots slots) (fun l => labels (.inr l)) + (fun l => atLabels (.inr l)) + (MachineHorner.resultTapes (headSlots slots) base (p.eval n)) hnext + (tail_clean_after_head slots base clean (p.eval n)) + exact trace_trans _ first second + +def outputSlot : (ps : List (Polynomial Nat)) → Output ps → Layout ps + | [], i => Empty.elim i + | _ :: _, .inl _ => .inr (.inl (.inl 2)) + | p :: ps, .inr i => tailLayout p ps (outputSlot ps i) + +def outputPolynomial : (ps : List (Polynomial Nat)) → Output ps → Polynomial Nat + | [], i => Empty.elim i + | p :: _, .inl _ => p + | _ :: ps, .inr i => outputPolynomial ps i + +theorem outputSlot_private (ps : List (Polynomial Nat)) (i : Output ps) : + ∃ k : Private ps, outputSlot ps i = .inr k := by + induction ps with + | nil => exact Empty.elim i + | cons p ps ih => + cases i with + | inl i => exact ⟨.inl (.inl 2), rfl⟩ + | inr i => + obtain ⟨k, hk⟩ := ih i + refine ⟨.inr k, ?_⟩ + simp only [outputSlot, hk, tailLayout] + rfl + +theorem outputSlot_ne_input (ps : List (Polynomial Nat)) (i : Output ps) : + outputSlot ps i ≠ .inl () := by + obtain ⟨k, hk⟩ := outputSlot_private ps i + rw [hk] + intro h + cases h + +theorem outputSlot_injective (ps : List (Polynomial Nat)) : + Function.Injective (outputSlot ps) := by + induction ps with + | nil => intro i; exact Empty.elim i + | cons p ps ih => + intro i j h + cases i with + | inl i => + cases j with + | inl j => cases i; cases j; rfl + | inr j => + exact False.elim ((head_output_ne_tail (Function.Embedding.refl (Layout (p :: ps))) + (outputSlot ps j)) h) + | inr i => + cases j with + | inl j => + exact False.elim ((head_output_ne_tail (Function.Embedding.refl (Layout (p :: ps))) + (outputSlot ps i)) h.symm) + | inr j => exact congrArg Sum.inr (ih ((tailLayout p ps).injective h)) + +theorem resultTapes_off_outputs (ps : List (Polynomial Nat)) (slots : Layout ps ↪ K) + (base : K → List Bool) (n : Nat) (k : K) + (hk : ∀ i : Output ps, slots (outputSlot ps i) ≠ k) : + resultTapes ps slots base n k = base k := by + induction ps generalizing base with + | nil => rfl + | cons p ps ih => + change resultTapes ps (tailSlots slots) + (MachineHorner.resultTapes (headSlots slots) base (p.eval n)) n k = base k + rw [ih _ _ (fun i => hk (.inr i))] + exact Function.update_of_ne (hk (.inl ())).symm _ _ + +theorem resultTapes_input (ps : List (Polynomial Nat)) (slots : Layout ps ↪ K) + (base : K → List Bool) (n : Nat) : + resultTapes ps slots base n (slots (.inl ())) = base (slots (.inl ())) := by + apply resultTapes_off_outputs + intro i hi + exact outputSlot_ne_input ps i (slots.injective hi) + +theorem resultTapes_output (ps : List (Polynomial Nat)) (slots : Layout ps ↪ K) + (base : K → List Bool) (n : Nat) (clean : Clean ps slots base) (i : Output ps) : + resultTapes ps slots base n (slots (outputSlot ps i)) = + encodeWord ((outputPolynomial ps i).eval n) := by + induction ps generalizing base with + | nil => exact Empty.elim i + | cons p ps ih => + cases i with + | inl i => + change resultTapes ps (tailSlots slots) + (MachineHorner.resultTapes (headSlots slots) base (p.eval n)) n + (headSlots slots (.inl 3)) = encodeWord (p.eval n) + rw [resultTapes_off_outputs _ _ _ _ _ + (fun i => (head_output_ne_tail slots (outputSlot ps i)).symm)] + rw [MachineHorner.resultTapes_output] + simp only [headSlots_output, clean (.inl (.inl 2)), List.append_nil] + | inr i => + exact ih (tailSlots slots) _ (tail_clean_after_head slots base clean _) i + +theorem resultTapes_work_clear (ps : List (Polynomial Nat)) (slots : Layout ps ↪ K) + (base : K → List Bool) (n : Nat) (clean : Clean ps slots base) (k : Private ps) + (hk : ∀ i : Output ps, outputSlot ps i ≠ .inr k) : + resultTapes ps slots base n (slots (.inr k)) = [] := by + rw [resultTapes_off_outputs _ _ _ _ _ (fun i h => hk i (slots.injective h))] + exact clean k + +theorem resultTapes_ambient (ps : List (Polynomial Nat)) (slots : Layout ps ↪ K) + (base : K → List Bool) (n : Nat) (k : K) (hk : k ∉ Set.range slots) : + resultTapes ps slots base n k = base k := by + apply resultTapes_off_outputs + intro i hi + exact hk ⟨outputSlot ps i, hi⟩ + +abbrev ProgramLabel (ps : List (Polynomial Nat)) := Unit ⊕ Label ps + +def program (ps : List (Polynomial Nat)) (slots : Layout ps ↪ K) : + ProgramLabel ps → TM2.Stmt (fun _ : K => Bool) (ProgramLabel ps) (MachineHorner.State σ) + | .inl _ => .load (fun state => (state.1, none)) + (Reduction.MachineTransfer.exitAt (slots (.inl ())) (entry ps Sum.inr none)) + | .inr l => statement ps slots Sum.inr none l + +theorem programTrace (ps : List (Polynomial Nat)) (slots : Layout ps ↪ K) + (base : K → List Bool) (n : Nat) + (hinput : base (slots (.inl ())) = encodeWord n) (clean : Clean ps slots base) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step (program ps slots)))^[1 + steps ps n] + (some ⟨some (.inl ()), ((ambient, ()), register), base⟩) = + some ⟨none, ((ambient, ()), none), resultTapes ps slots base n⟩ := by + have first : (advance (TM2.step (program ps slots)))^[1] + (some ⟨some (.inl ()), ((ambient, ()), register), base⟩) = + some ⟨entry ps Sum.inr none, ((ambient, ()), none), base⟩ := by + change some (TM2.stepAux (program ps slots (.inl ())) _ _) = _ + simp only [program, TM2.stepAux] + cases h : entry ps (Sum.inr : Label ps → ProgramLabel ps) none <;> rfl + have rest := trace ps slots Sum.inr none (program ps slots) (fun _ => rfl) + base n hinput clean ambient + exact trace_trans _ first rest + +def programInTime (ps : List (Polynomial Nat)) (slots : Layout ps ↪ K) + (base : K → List Bool) (n : Nat) + (hinput : base (slots (.inl ())) = encodeWord n) (clean : Clean ps slots base) + (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step (program ps slots)) + ⟨some (.inl ()), ((ambient, ()), register), base⟩ + (some ⟨none, ((ambient, ()), none), resultTapes ps slots base n⟩) + ((1 + timePolynomial ps).eval n) where + steps := 1 + steps ps n + evals_in_steps := programTrace ps slots base n hinput clean ambient register + steps_le_m := by + simp only [Polynomial.eval_add, Polynomial.eval_one] + exact Nat.add_le_add_left (steps_le_timePolynomial ps n) 1 + +abbrev Tape (ps : List (Polynomial Nat)) := Layout ps ⊕ Unit + +def machineSlots (ps : List (Polynomial Nat)) : Layout ps ↪ Tape ps := + ⟨Sum.inl, Sum.inl_injective⟩ + +def machine (ps : List (Polynomial Nat)) : FinTM2 where + K := Tape ps + k₀ := .inr () + k₁ := .inr () + Γ _ := Bool + Λ := ProgramLabel ps + main := .inl () + σ := MachineHorner.State Unit + initialState := (((), ()), none) + m := program ps (machineSlots ps) + +theorem machine_rawInput_preserved (ps : List (Polynomial Nat)) + (base : Tape ps → List Bool) (n : Nat) : + resultTapes ps (machineSlots ps) base n (.inr ()) = base (.inr ()) := by + apply resultTapes_ambient + rintro ⟨i, hi⟩ + cases hi + +def machineInTime (ps : List (Polynomial Nat)) (base : Tape ps → List Bool) (n : Nat) + (hinput : base ((machineSlots ps) (.inl ())) = encodeWord n) + (clean : Clean ps (machineSlots ps) base) (register : Option Bool) : + StateTransition.EvalsToInTime (machine ps).step + ⟨some (.inl ()), (((), ()), register), base⟩ + (some ⟨none, (((), ()), none), resultTapes ps (machineSlots ps) base n⟩) + ((1 + timePolynomial ps).eval n) := + programInTime ps (machineSlots ps) base n hinput clean () register + +inductive Clock + | witness | horizon | capacity | width | frameWidth | inputCount + deriving DecidableEq + +/-- A list enumerating every element of the type, which are all zero-argument constructors. (Generated by the `Fintype` deriving handler.)-/ +protected abbrev Clock.enumList : List Clock := [.witness, .horizon, .capacity, .width, + .frameWidth, .inputCount] + +protected theorem Clock.enumList_getElem?_ctorIdx_eq (x : Clock) : + Clock.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem Clock.enumList_nodup : Clock.enumList.Nodup := by decide + +instance : Fintype Clock where + elems := ⟨Clock.enumList, Clock.enumList_nodup⟩ + complete x := by cases x <;> decide + +def clockPolynomial (V : NPVerifier) : Clock → Polynomial Nat + | .witness => V.witnessBound + | .horizon => Bounds.horizonPolynomial V.computation.time V.witnessBound + | .capacity => Bounds.capacityPolynomial V.computation.time V.witnessBound + (Runtime.programPushBound V.computation.tm) + | .width => VerifierCircuit.widthPolynomial V + | .frameWidth => VerifierCircuit.widthPolynomial V + 1 + | .inputCount => WitnessEncoding.freeInputPolynomial V.witnessBound + +def clockPolynomials (V : NPVerifier) : List (Polynomial Nat) := + [clockPolynomial V .witness, clockPolynomial V .horizon, clockPolynomial V .capacity, + clockPolynomial V .width, clockPolynomial V .frameWidth, clockPolynomial V .inputCount] + +def clockOutput (V : NPVerifier) : Clock → Output (clockPolynomials V) + | .witness => .inl () + | .horizon => .inr (.inl ()) + | .capacity => .inr (.inr (.inl ())) + | .width => .inr (.inr (.inr (.inl ()))) + | .frameWidth => .inr (.inr (.inr (.inr (.inl ())))) + | .inputCount => .inr (.inr (.inr (.inr (.inr (.inl ()))))) + +def clockValue (V : NPVerifier) (n : Nat) : Clock → Nat + | .witness => V.witnessBound.eval n + | .horizon => V.horizon n + | .capacity => VerifierCircuit.capacity V n + | .width => (VerifierCircuit.indexing V).width (VerifierCircuit.capacity V n) + | .frameWidth => (VerifierCircuit.indexing V).width (VerifierCircuit.capacity V n) + 1 + | .inputCount => 2 * V.witnessBound.eval n + 1 + +@[simp] theorem outputPolynomial_clockOutput (V : NPVerifier) (c : Clock) : + outputPolynomial (clockPolynomials V) (clockOutput V c) = clockPolynomial V c := by + cases c <;> rfl + +theorem clockPolynomial_eval (V : NPVerifier) (n : Nat) (c : Clock) : + (clockPolynomial V c).eval n = clockValue V n c := by + cases c <;> + simp [clockPolynomial, clockValue, VerifierCircuit.widthPolynomial, + VerifierCircuit.capacity, NPVerifier.horizon, ConfigIndex.Indexing.width, Nat.mul_comm] + +theorem clockResult_output (V : NPVerifier) (slots : Layout (clockPolynomials V) ↪ K) + (base : K → List Bool) (n : Nat) (clean : Clean (clockPolynomials V) slots base) + (c : Clock) : + resultTapes (clockPolynomials V) slots base n + (slots (outputSlot (clockPolynomials V) (clockOutput V c))) = + encodeWord (clockValue V n c) := by + rw [resultTapes_output _ _ _ _ clean, outputPolynomial_clockOutput, clockPolynomial_eval] + +def clocksInTime (V : NPVerifier) (slots : Layout (clockPolynomials V) ↪ K) + (base : K → List Bool) (n : Nat) + (hinput : base (slots (.inl ())) = encodeWord n) + (clean : Clean (clockPolynomials V) slots base) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step (program (clockPolynomials V) slots)) + ⟨some (.inl ()), ((ambient, ()), register), base⟩ + (some ⟨none, ((ambient, ()), none), resultTapes (clockPolynomials V) slots base n⟩) + ((1 + timePolynomial (clockPolynomials V)).eval n) := + programInTime (clockPolynomials V) slots base n hinput clean ambient register + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.ClockPreparation + +end + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/CompletedEdgeMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/CompletedEdgeMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..3c1de17756cef89ec999f526d483b0813169de33 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/CompletedEdgeMachine.lean @@ -0,0 +1,236 @@ +import OAI.Computability.PerfectCompleteness.Foundations.DescriptorKeyTemplate +import OAI.Computability.PerfectCompleteness.Machines.CanonicalEndpointMachine +import OAI.Computability.PerfectCompleteness.Machines.DescriptorProjectionMachine + +namespace OAI + + +namespace PerfectCompleteness.CompletedEdgeMachine + + +open Turing UniqueGamesTheorem.Foundations.Complexity +open CanonicalKeys +open scoped BigOperators Classical + +noncomputable section + +variable {branch : Nat → Nat} {n t q : Nat} {rows repeats : Nat → Nat} + (hq : 0 < q) + (large : CanonicalKeyEncoding.partitionWidth (TreeCanonical.locationCount branch n t) ≤ q) + +local notation "width" => TreeCanonical.locationCount branch n t + +variable (descriptor : SignedCompletionSchedule.Descriptor + (rows := rows) (repeats := repeats) hq large) + +def key (side : Side) (ids : Fin width → Nat) (vars : Fin width → Fin 3 → Nat) : Key width := + DescriptorKeyTemplate.recover side (DescriptorKeyTemplate.ofDescriptor hq large side descriptor) + ids vars + +def edge (leftPrefix rightPrefix : List (Key width)) + (ids : Fin width → Nat) (vars : Fin width → Fin 3 → Nat) : + Edge (leftPrefix.length + 1) (rightPrefix.length + 1) q where + left := CanonicalOnlineNames.onlineName leftPrefix (key hq large descriptor .left ids vars) + right := CanonicalOnlineNames.onlineName rightPrefix (key hq large descriptor .right ids vars) + projection := DescriptorProjectionMachine.projection hq large descriptor + +def edgeBits (leftPrefix rightPrefix : List (Key width)) + (ids : Fin width → Nat) (vars : Fin width → Fin 3 → Nat) : List Bool := + encodeWords (Encoding.edgeWords (edge hq large descriptor leftPrefix rightPrefix ids vars)) + +theorem edgeBits_eq (leftPrefix rightPrefix : List (Key width)) + (ids : Fin width → Nat) (vars : Fin width → Fin 3 → Nat) : + edgeBits hq large descriptor leftPrefix rightPrefix ids vars = + encodeWord (CanonicalOnlineNames.onlineID leftPrefix (key hq large descriptor .left ids vars)) ++ + encodeWord (CanonicalOnlineNames.onlineID rightPrefix (key hq large descriptor .right ids vars)) ++ + DescriptorProjectionMachine.outputBits hq large descriptor := by + simp only [edgeBits, edge, Encoding.edgeWords, CanonicalOnlineNames.onlineName_val, + encodeWords_append, encodeWords, List.append_nil, DescriptorProjectionMachine.outputBits, + DescriptorProjectionMachine.outputWords, List.append_assoc] + +def leftMap (i : Fin 8) : Fin 10 := ⟨i.val, lt_trans i.isLt (by decide)⟩ + +def rightMap (i : Fin 8) : Fin 10 := if i = 1 then 8 else leftMap i + +theorem leftMap_injective : Function.Injective leftMap := by decide +theorem rightMap_injective : Function.Injective rightMap := by decide + +theorem forward_ne_left : ∀ i, (9 : Fin 10) ≠ leftMap i := by decide +theorem forward_ne_right : ∀ i, (9 : Fin 10) ≠ rightMap i := by decide + +private theorem leftMap_work : ∀ i : Fin 8, 2 ≤ i.val → i.val ≤ 6 → + leftMap i ≠ 1 ∧ leftMap i ≠ 7 ∧ leftMap i ≠ 8 := by decide + +private theorem rightMap_work : ∀ i : Fin 8, 2 ≤ i.val → i.val ≤ 6 → + rightMap i ≠ 1 ∧ rightMap i ≠ 7 ∧ rightMap i ≠ 8 := by decide + +variable {K Λ A : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool +abbrev State (A : Type) := CanonicalEndpointMachine.State A +abbrev clean (ambient : A) : State A := CanonicalEndpointMachine.clean ambient + +def leftTapes (work : Fin 10 → K) : Fin 8 → K := fun i => work (leftMap i) +def rightTapes (work : Fin 10 → K) : Fin 8 → K := fun i => work (rightMap i) + +inductive Label (locations : Nat) + | left (label : CanonicalEndpointMachine.Label locations) + | right (label : CanonicalEndpointMachine.Label locations) + | projection + deriving DecidableEq, Fintype + +def main (locations : Nat) : Label locations := .left (CanonicalEndpointMachine.main locations) + +variable [Fintype A] [DecidableEq A] + +def instruction (source : Fin width → Fin 6 → K) (work : Fin 10 → K) + (labels : Label width → Λ) (done : Λ) (rejected : Option Λ) : + Label width → TM2.Stmt (Alphabet (K := K)) Λ (State A) + | .left label => + let template := DescriptorKeyTemplate.ofDescriptor hq large .left descriptor + CanonicalEndpointMachine.instruction template.shapes template.modes .left template.partition + source (work 9) (leftTapes work) (fun l => labels (.left l)) + (some (labels (.right (CanonicalEndpointMachine.main width)))) rejected label + | .right label => + let template := DescriptorKeyTemplate.ofDescriptor hq large .right descriptor + CanonicalEndpointMachine.instruction template.shapes template.modes .right template.partition + source (work 9) (rightTapes work) (fun l => labels (.right l)) + (some (labels .projection)) rejected label + | .projection => + DescriptorProjectionMachine.reverseStatement hq large + (fun _ : State A => descriptor) (work 7) done + +def finalTapes (work : Fin 10 → K) (base : K → List Bool) + (leftPrefix rightPrefix : List (Key width)) + (ids : Fin width → Nat) (vars : Fin width → Fin 3 → Nat) : K → List Bool := + Function.update + (Function.update + (Function.update base (work 1) (BinaryNameSearch.stream (CanonicalVertexNames.tokens + (leftPrefix ++ [key hq large descriptor .left ids vars])))) + (work 8) (BinaryNameSearch.stream (CanonicalVertexNames.tokens + (rightPrefix ++ [key hq large descriptor .right ids vars])))) + (work 7) ((edgeBits hq large descriptor leftPrefix rightPrefix ids vars).reverse ++ base (work 7)) + +def budget (source : Fin width → Fin 6 → K) (base : K → List Bool) + (leftPrefix rightPrefix : List (Key width)) + (ids : Fin width → Nat) (vars : Fin width → Fin 3 → Nat) : Nat := + CanonicalEndpointMachine.budget source base leftPrefix (key hq large descriptor .left ids vars) + + CanonicalEndpointMachine.budget source base rightPrefix (key hq large descriptor .right ids vars) + 1 + +def edgeInTime (ids : Fin width → Nat) (vars : Fin width → Fin 3 → Nat) + (source : Fin width → Fin 6 → K) (sourceDistinct : ∀ i, Function.Injective (source i)) + (work : Fin 10 → K) (workDistinct : Function.Injective work) + (sharedScratch : ∀ i, source i 4 = work 5) (sharedOutput : ∀ i, source i 5 = work 9) + (sourceAvoid : ∀ i field j, KeyMetadataMachine.idTape (source i) field ≠ work j) + (labels : Label width → Λ) (done : Λ) (rejected : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ l, program (labels l) = instruction hq large descriptor source work labels done rejected l) + (base : K → List Bool) (ambient : A) (leftPrefix rightPrefix : List (Key width)) + (sourceWords : ∀ i field, base (KeyMetadataMachine.idTape (source i) field) = + encodeWord (KeyMetadataMachine.fieldValue (ids i) (vars i) field)) + (leftDictionary : base (work 1) = BinaryNameSearch.stream (CanonicalVertexNames.tokens leftPrefix)) + (rightDictionary : base (work 8) = BinaryNameSearch.stream (CanonicalVertexNames.tokens rightPrefix)) + (empty : ∀ j : Fin 10, j ≠ 1 → j ≠ 7 → j ≠ 8 → base (work j) = []) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels (main width)), clean ambient, base⟩ + (some ⟨some done, clean ambient, + finalTapes hq large descriptor work base leftPrefix rightPrefix ids vars⟩) + (budget hq large descriptor source base leftPrefix rightPrefix ids vars) := by + let leftKey := key hq large descriptor .left ids vars + let rightKey := key hq large descriptor .right ids vars + let leftTemplate := DescriptorKeyTemplate.ofDescriptor hq large .left descriptor + let rightTemplate := DescriptorKeyTemplate.ofDescriptor hq large .right descriptor + let first := CanonicalEndpointMachine.finalTapes (leftTapes work) base leftPrefix leftKey + let second := CanonicalEndpointMachine.finalTapes (rightTapes work) first rightPrefix rightKey + have hd (i j : Fin 10) (different : i ≠ j) : work i ≠ work j := + fun same => different (workDistinct same) + have leftEmpty (i : Fin 8) (lo : 2 ≤ i.val) (hi : i.val ≤ 6) : + base (leftTapes work i) = [] := by + obtain ⟨h1, h7, h8⟩ := leftMap_work i lo hi + exact empty (leftMap i) h1 h7 h8 + have leftRun : StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels (main width)), clean ambient, base⟩ + (some ⟨some (labels (.right (CanonicalEndpointMachine.main width))), clean ambient, first⟩) + (CanonicalEndpointMachine.budget source base leftPrefix leftKey) := by + exact CanonicalEndpointMachine.endpointInTime + leftTemplate.shapes leftTemplate.modes .left leftTemplate.partition ids vars + source sourceDistinct (work 9) (leftTapes work) + (workDistinct.comp leftMap_injective) + (fun i same => forward_ne_left i (workDistinct same)) sharedScratch sharedOutput + (fun l => labels (.left l)) (some (labels (.right (CanonicalEndpointMachine.main width)))) + rejected program (fun l => atLabels (.left l)) base ambient leftPrefix sourceWords + (empty 9 (by decide) (by decide) (by decide)) + (empty 0 (by decide) (by decide) (by decide)) leftDictionary leftEmpty + have firstAt (i : Fin 10) (h1 : i ≠ 1) (h7 : i ≠ 7) : first (work i) = base (work i) := + CanonicalEndpointMachine.finalTapes_frame (leftTapes work) base leftPrefix leftKey + (work i) (hd i 1 h1) (hd i 7 h7) + have firstSource (i : Fin width) (field : Fin 4) : + first (KeyMetadataMachine.idTape (source i) field) = + base (KeyMetadataMachine.idTape (source i) field) := + CanonicalEndpointMachine.finalTapes_sources source (leftTapes work) base leftPrefix leftKey + (fun i field => sourceAvoid i field 1) (fun i field => sourceAvoid i field 7) i field + have rightEmpty (i : Fin 8) (lo : 2 ≤ i.val) (hi : i.val ≤ 6) : + first (rightTapes work i) = [] := by + obtain ⟨h1, h7, h8⟩ := rightMap_work i lo hi + exact (firstAt (rightMap i) h1 h7).trans (empty (rightMap i) h1 h7 h8) + have firstSourceLength : CanonicalKeyMachine.sourceLength source first = + CanonicalKeyMachine.sourceLength source base := by + simp only [CanonicalKeyMachine.sourceLength, KeyMetadataMachine.sourceLength, firstSource] + have rightRun : StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels (.right (CanonicalEndpointMachine.main width))), clean ambient, first⟩ + (some ⟨some (labels .projection), clean ambient, second⟩) + (CanonicalEndpointMachine.budget source base rightPrefix rightKey) := by + have run := CanonicalEndpointMachine.endpointInTime + rightTemplate.shapes rightTemplate.modes .right rightTemplate.partition ids vars + source sourceDistinct (work 9) (rightTapes work) + (workDistinct.comp rightMap_injective) + (fun i same => forward_ne_right i (workDistinct same)) sharedScratch sharedOutput + (fun l => labels (.right l)) (some (labels .projection)) rejected program + (fun l => atLabels (.right l)) first ambient rightPrefix + (fun i field => (firstSource i field).trans (sourceWords i field)) + ((firstAt 9 (by decide) (by decide)).trans (empty 9 (by decide) (by decide) (by decide))) + ((firstAt 0 (by decide) (by decide)).trans (empty 0 (by decide) (by decide) (by decide))) + ((firstAt 8 (by decide) (by decide)).trans rightDictionary) rightEmpty + change StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels (.right (CanonicalEndpointMachine.main width))), clean ambient, first⟩ + (some ⟨some (labels .projection), clean ambient, second⟩) + (CanonicalEndpointMachine.budget source first rightPrefix rightKey) at run + simpa only [CanonicalEndpointMachine.budget, firstSourceLength] using run + have projectionRun := DescriptorProjectionMachine.reverseEmitInTime hq large + (fun _ : State A => descriptor) (work 7) program (labels .projection) done + (atLabels .projection) (clean ambient) second + have finalEq : Function.update second (work 7) + ((DescriptorProjectionMachine.outputBits hq large descriptor).reverse ++ second (work 7)) = + finalTapes hq large descriptor work base leftPrefix rightPrefix ids vars := by + funext k + by_cases hk : k = work 7 + · subst k + simp [first, second, finalTapes, CanonicalEndpointMachine.finalTapes, + edgeBits_eq, leftKey, rightKey, leftTapes, rightTapes, leftMap, rightMap, + List.reverse_append, List.append_assoc] + · simp [first, second, finalTapes, CanonicalEndpointMachine.finalTapes, + leftKey, rightKey, leftTapes, rightTapes, leftMap, rightMap, + Function.update_apply, hk] + rw [finalEq] at projectionRun + have joined := StateTransition.EvalsToInTime.trans (TM2.step program) _ _ _ _ _ + (StateTransition.EvalsToInTime.trans (TM2.step program) _ _ _ _ _ leftRun rightRun) projectionRun + simpa only [budget, Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using joined + +theorem finalTapes_frame (work : Fin 10 → K) (base : K → List Bool) + (leftPrefix rightPrefix : List (Key width)) + (ids : Fin width → Nat) (vars : Fin width → Fin 3 → Nat) (k : K) + (notLeft : k ≠ work 1) (notRight : k ≠ work 8) (notOutput : k ≠ work 7) : + finalTapes hq large descriptor work base leftPrefix rightPrefix ids vars k = base k := by + simp only [finalTapes, Function.update_of_ne notOutput, + Function.update_of_ne notRight, Function.update_of_ne notLeft] + +theorem label_finite : Finite (Label width) := inferInstance +omit [Fintype A] [DecidableEq A] in +theorem state_finite [Finite A] : Finite (State A) := inferInstance +omit [DecidableEq K] in +theorem workAlphabet_finite (k : K) : Finite (Alphabet k) := inferInstance + +end +end PerfectCompleteness.CompletedEdgeMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/Completeness.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/Completeness.lean new file mode 100644 index 0000000000000000000000000000000000000000..119d5c292faada8445559b62069973bdbd7b6bf2 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/Completeness.lean @@ -0,0 +1,48 @@ +import OAI.Computability.PerfectCompleteness.Machines.CircuitProducerStagesLemmas +import OAI.Computability.PerfectCompleteness.Machines.ProducerTimeLemmas +import OAI.Computability.UniqueGames.Machines.GraphCounterStartLemmas +import OAI.Computability.UniqueGames.Machines.MachineFiniteAlphabet + +namespace OAI + +section + +noncomputable section +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.Completeness + +open Turing + +theorem circuitProducerFinite : + MachineFiniteAlphabet.FiniteAlphabet CircuitProducer.computableInPolyTime.tm := by + intro k + change Finite Bool + infer_instance + +def verifierReduction (V : NPVerifier) : PolynomialThreeSATReduction V.Accepts where + reduce input := (VerifierCircuit.circuitOfVerifier V input).toFormula + computation := MachineSequential.composeBits (ProducerMachine.computableInPolyTime V) + CircuitProducer.computableInPolyTime + correct input := (VerifierCircuit.circuitOfVerifier_correct V input).symm + +theorem verifierReduction_finiteAlphabet (V : NPVerifier) : + MachineFiniteAlphabet.FiniteAlphabet (verifierReduction V).computation.tm := + MachineFiniteAlphabet.composeBits (ProducerMachine.computableInPolyTime V) + CircuitProducer.computableInPolyTime (ProducerMachine.finiteAlphabet V) circuitProducerFinite + +theorem threeSATReduction (language : List Bool → Prop) (membership : InNP language) : + ∃ source : PolynomialThreeSATReduction language, + MachineFiniteAlphabet.FiniteAlphabet source.computation.tm := by + obtain ⟨V, recognized⟩ := membership + let source : PolynomialThreeSATReduction language := { + reduce := (verifierReduction V).reduce + computation := (verifierReduction V).computation + correct := fun input => (recognized input).trans ((verifierReduction V).correct input) } + exact ⟨source, verifierReduction_finiteAlphabet V⟩ + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.Completeness + +end + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/DescriptorKeyMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/DescriptorKeyMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..6a6165f44d94e3ae54cd0a99fa81b8a5aa4f9370 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/DescriptorKeyMachine.lean @@ -0,0 +1,132 @@ +import OAI.Computability.PerfectCompleteness.Machines.CanonicalKeyMachine + +namespace OAI + + +namespace PerfectCompleteness.DescriptorKeyMachine + + +open Turing UniqueGamesTheorem.Foundations.Complexity MachineComposition +open CanonicalKeys CanonicalKeyShape ClauseSupport +open scoped Classical + +noncomputable section + +variable {n : Nat} {α K Λ σ : Type} [DecidableEq K] + +inductive Label (α : Type) (n : Nat) + | dispatch + | key (descriptor : α) (localLabel : CanonicalKeyMachine.Label n) + deriving DecidableEq, Fintype + +abbrev Alphabet (_ : K) := Bool +abbrev State (σ : Type) := KeyMetadataMachine.State σ + +def start (n : Nat) : CanonicalKeyMachine.Label n := .inl () + +@[simp] theorem entry_eq (placed : CanonicalKeyMachine.Label n → Λ) (exit : Option Λ) : + CanonicalKeyMachine.entry placed exit = some (placed (start n)) := rfl + +def instruction (select : σ → α) (shapes : α → Fin n → Shape) + (modes : α → Fin n → SupportMode) (side : α → Side) + (partition : α → Set (Set (Fin n → ReducedValue))) + (tape : Fin n → Fin 6 → K) (output : K) + (labels : Label α n → Λ) (exit : Option Λ) : + Label α n → TM2.Stmt (Alphabet (K := K)) Λ (State σ) + | .dispatch => .goto (fun state => labels (.key (select state.1) (start n))) + | .key descriptor localLabel => + CanonicalKeyMachine.instruction (shapes descriptor) (modes descriptor) + (side descriptor) (partition descriptor) tape output + (fun l => labels (.key descriptor l)) exit localLabel + +def payload (select : σ → α) (shapes : α → Fin n → Shape) + (modes : α → Fin n → SupportMode) (side : α → Side) + (partition : α → Set (Set (Fin n → ReducedValue))) + (ambient : σ) (occurrences : Fin n → Nat) (variableIDs : Fin n → Fin 3 → Nat) : List Bool := + CanonicalKeyMachine.payload (shapes (select ambient)) (modes (select ambient)) + (side (select ambient)) (partition (select ambient)) occurrences variableIDs + +theorem dispatch_step (select : σ → α) (shapes : α → Fin n → Shape) + (modes : α → Fin n → SupportMode) (side : α → Side) + (partition : α → Set (Set (Fin n → ReducedValue))) + (tape : Fin n → Fin 6 → K) (output : K) + (labels : Label α n → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atDispatch : program (labels .dispatch) = + instruction select shapes modes side partition tape output labels exit .dispatch) + (base : K → List Bool) (ambient : σ) : + TM2.step program ⟨some (labels .dispatch), KeyMetadataMachine.clean ambient, base⟩ = + some ⟨CanonicalKeyMachine.entry (fun l => labels (.key (select ambient) l)) exit, + KeyMetadataMachine.clean ambient, base⟩ := by + change some (TM2.stepAux (program (labels .dispatch)) + (KeyMetadataMachine.clean ambient) base) = _ + rw [atDispatch] + rfl + +private def prefixOne {X : Type} (step : X → Option X) + {initial middle : X} {final : Option X} {budget : Nat} + (first : step initial = some middle) + (body : StateTransition.EvalsToInTime step middle final budget) : + StateTransition.EvalsToInTime step initial final (1 + budget) := by + refine + { steps := 1 + body.steps + evals_in_steps := ?_ + steps_le_m := Nat.add_le_add_left body.steps_le_m 1 } + change (advance step)^[1 + body.steps] (some initial) = final + rw [Nat.add_comm 1 body.steps, Function.iterate_add_apply, + Function.iterate_one, advance_some, first] + exact body.evals_in_steps + +def keyInTime (select : σ → α) (shapes : α → Fin n → Shape) + (modes : α → Fin n → SupportMode) (side : α → Side) + (partition : α → Set (Set (Fin n → ReducedValue))) + (occurrences : Fin n → Nat) (variableIDs : Fin n → Fin 3 → Nat) + (tape : Fin n → Fin 6 → K) (distinct : ∀ i, Function.Injective (tape i)) + (scratch output : K) (scratchOutput : scratch ≠ output) + (sharedScratch : ∀ i, tape i 4 = scratch) (sharedOutput : ∀ i, tape i 5 = output) + (labels : Label α n → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ label, program (labels label) = + instruction select shapes modes side partition tape output labels exit label) + (base : K → List Bool) + (sourceWords : ∀ i field, base (KeyMetadataMachine.idTape (tape i) field) = + encodeWord (KeyMetadataMachine.fieldValue (occurrences i) (variableIDs i) field)) + (scratchEmpty : base scratch = []) (ambient : σ) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .dispatch), KeyMetadataMachine.clean ambient, base⟩ + (some ⟨exit, KeyMetadataMachine.clean ambient, Function.update base output + (payload select shapes modes side partition ambient occurrences variableIDs ++ base output)⟩) + (1 + (2 * CanonicalKeyMachine.sourceLength tape base + 4 * n + 2)) := by + let body := CanonicalKeyMachine.keyInTime (shapes (select ambient)) (modes (select ambient)) + (side (select ambient)) (partition (select ambient)) occurrences variableIDs + tape distinct scratch output scratchOutput sharedScratch sharedOutput + (fun l => labels (.key (select ambient) l)) exit program + (fun l => atLabels (.key (select ambient) l)) base sourceWords scratchEmpty ambient + exact prefixOne (TM2.step program) + (dispatch_step select shapes modes side partition tape output labels exit program + (atLabels .dispatch) base ambient) body + +theorem output_sources (tape : Fin n → Fin 6 → K) + (distinct : ∀ i, Function.Injective (tape i)) (output : K) + (sharedOutput : ∀ i, tape i 5 = output) (base : K → List Bool) (bits : List Bool) + (i : Fin n) (field : Fin 4) : + Function.update base output (bits ++ base output) (KeyMetadataMachine.idTape (tape i) field) = + base (KeyMetadataMachine.idTape (tape i) field) := + CanonicalKeyMachine.output_sources tape distinct output sharedOutput base bits i field + +theorem output_scratch (scratch output : K) (hne : scratch ≠ output) + (base : K → List Bool) (bits : List Bool) (hempty : base scratch = []) : + Function.update base output (bits ++ base output) scratch = [] := + CanonicalKeyMachine.output_scratch scratch output hne base bits hempty + +theorem label_finite [Fintype α] : Finite (Label α n) := inferInstance + +theorem state_finite [Finite σ] : Finite (State σ) := inferInstance + +omit [DecidableEq K] in +theorem alphabet_finite (k : K) : Finite (Alphabet k) := inferInstance + +end +end PerfectCompleteness.DescriptorKeyMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/DescriptorProjectionMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/DescriptorProjectionMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..3a05239e3f413684f5caee63571806a5469add42 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/DescriptorProjectionMachine.lean @@ -0,0 +1,180 @@ +import OAI.Computability.PerfectCompleteness.Reduction.SignedCompletionSchedule +import OAI.Computability.UniqueGames.Machines.MachineFiniteTable + +namespace OAI + + +namespace PerfectCompleteness.DescriptorProjectionMachine + +open Turing +open UniqueGamesTheorem.Foundations.Complexity +open SignedCompletionSchedule +open scoped Classical + +noncomputable section + +variable {branch : Nat → Nat} {n t q : Nat} {rows repeats : Nat → Nat} + (hq : 0 < q) + (large : CanonicalKeyEncoding.partitionWidth (TreeCanonical.locationCount branch n t) ≤ q) + +def projection (descriptor : Descriptor (rows := rows) (repeats := repeats) hq large) : + ProjectionTable q := + LocalCompletionSerialization.projection + (FiniteConstraintMachine.result_correct hq large ⟨descriptor.1, descriptor.2.1⟩) + descriptor.2.2 + +theorem projection_apply + (descriptor : Descriptor (rows := rows) (repeats := repeats) hq large) + (a : Fin (2 * q)) : + (projection hq large descriptor).images[a] = descriptorTable hq large descriptor a := + (descriptorTable_eq_parsed hq large descriptor.1 descriptor.2 a).symm + +def outputWords (descriptor : Descriptor (rows := rows) (repeats := repeats) hq large) : + List Nat := Encoding.tableWords (projection hq large descriptor) + +theorem outputWords_eq + (descriptor : Descriptor (rows := rows) (repeats := repeats) hq large) : + outputWords hq large descriptor = + List.ofFn (fun a : Fin (2 * q) => (descriptorTable hq large descriptor a).val) := + (LocalCompletionSerialization.rawTableWords_eq + (FiniteConstraintMachine.result_correct hq large ⟨descriptor.1, descriptor.2.1⟩) + descriptor.2.2).symm + +@[simp] theorem outputWords_length + (descriptor : Descriptor (rows := rows) (repeats := repeats) hq large) : + (outputWords hq large descriptor).length = 2 * q := + Encoding.tableWords_length _ + +def outputBits (descriptor : Descriptor (rows := rows) (repeats := repeats) hq large) : + List Bool := encodeWords (outputWords hq large descriptor) + +theorem outputBits_length_le + (descriptor : Descriptor (rows := rows) (repeats := repeats) hq large) : + (outputBits hq large descriptor).length ≤ (2 * q) * (q + 1) := by + have hword : ∀ value ∈ outputWords hq large descriptor, value ≤ q := by + intro value hvalue + rw [outputWords_eq] at hvalue + obtain ⟨a, ha⟩ := List.mem_ofFn.mp hvalue + have hrange := (descriptorTable hq large descriptor a).isLt + omega + simpa only [outputBits, outputWords_length] using + encodeWords_length_le (outputWords hq large descriptor) q hword + +theorem outputBits_parse + (descriptor : Descriptor (rows := rows) (repeats := repeats) hq large) : + decodeWords (outputBits hq large descriptor) >>= Encoding.parseProjection q = + some (projection hq large descriptor) := by + rw [outputBits, decodeWords_encodeWords] + exact Encoding.parseProjection_encoded _ + + +variable {σ : Type} [Fintype σ] [DecidableEq σ] + (select : σ → Descriptor (rows := rows) (repeats := repeats) hq large) + +def keys (σ : Type) [Fintype σ] : List σ := (Finset.univ : Finset σ).toList + +omit [DecidableEq σ] in +theorem keys_complete (state : σ) : state ∈ keys σ := by + simp [keys] + +def pushBound : Nat := + ((keys σ).map (fun state => (outputBits hq large (select state)).length)).sum + +def statement {K Λ : Type} (dst : K) (exit : Λ) : + TM2.Stmt (fun _ : K => Bool) Λ σ := + MachineFiniteTable.emit dst (fun state => outputBits hq large (select state)) (keys σ) + (.goto (fun _ => exit)) + +theorem statement_trace {K Λ : Type} [DecidableEq K] + (dst : K) (exit : Λ) (state : σ) (tapes : K → List Bool) : + TM2.stepAux (statement hq large select dst exit) state tapes = { + l := some exit + var := state + stk := Function.update tapes dst (outputBits hq large (select state) ++ tapes dst) + } := by + rw [statement, MachineFiniteTable.stepAux_emit dst _ (keys σ) (keys_complete)] + rfl + +def emitInTime {K Λ : Type} [DecidableEq K] + (dst : K) (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ σ) + (label exit : Λ) + (atLabel : program label = statement hq large select dst exit) + (state : σ) (tapes : K → List Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some label, state, tapes⟩ + (some ⟨some exit, state, + Function.update tapes dst (outputBits hq large (select state) ++ tapes dst)⟩) 1 := + MachineFiniteTable.emitInTime (Γ := fun _ : K => Bool) + dst (fun state => outputBits hq large (select state)) + (keys σ) keys_complete program label exit + (by simpa only [statement] using atLabel) state tapes + +omit [Fintype σ] [DecidableEq σ] in +theorem output_frame {K : Type} [DecidableEq K] + (dst : K) (state : σ) (tapes : K → List Bool) (k : K) (hne : k ≠ dst) : + (Function.update tapes dst (outputBits hq large (select state) ++ tapes dst)) k = + tapes k := + MachineFiniteTable.output_frame dst (fun state => outputBits hq large (select state)) + state tapes k hne + +theorem statement_pushBound {K Λ : Type} (dst : K) (exit : Λ) : + Runtime.statementPushBound (statement hq large select dst exit) ≤ + pushBound hq large select := by + have h := MachineFiniteTable.emit_push_bound (Γ := fun _ : K => Bool) + dst (fun state => outputBits hq large (select state)) (keys σ) + (.goto (fun _ => exit)) + simpa only [statement, pushBound, MachineFiniteTable.tableBound, + Runtime.statementPushBound, Nat.add_zero] using h + +def reverseStatement {K Λ : Type} (dst : K) (exit : Λ) : + TM2.Stmt (fun _ : K => Bool) Λ σ := + MachineFiniteTable.emit dst (fun state => (outputBits hq large (select state)).reverse) + (keys σ) (.goto (fun _ => exit)) + +theorem reverse_statement_trace {K Λ : Type} [DecidableEq K] + (dst : K) (exit : Λ) (state : σ) (tapes : K → List Bool) : + TM2.stepAux (reverseStatement hq large select dst exit) state tapes = { + l := some exit + var := state + stk := Function.update tapes dst + ((outputBits hq large (select state)).reverse ++ tapes dst) + } := by + rw [reverseStatement, MachineFiniteTable.stepAux_emit dst _ (keys σ) keys_complete] + rfl + +def reverseEmitInTime {K Λ : Type} [DecidableEq K] + (dst : K) (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ σ) + (label exit : Λ) + (atLabel : program label = reverseStatement hq large select dst exit) + (state : σ) (tapes : K → List Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some label, state, tapes⟩ + (some ⟨some exit, state, + Function.update tapes dst + ((outputBits hq large (select state)).reverse ++ tapes dst)⟩) 1 := + MachineFiniteTable.emitInTime (Γ := fun _ : K => Bool) dst + (fun state => (outputBits hq large (select state)).reverse) + (keys σ) keys_complete program label exit + (by simpa only [reverseStatement] using atLabel) state tapes + +omit [Fintype σ] [DecidableEq σ] in +theorem reverse_output_frame {K : Type} [DecidableEq K] + (dst : K) (state : σ) (tapes : K → List Bool) (k : K) (hne : k ≠ dst) : + (Function.update tapes dst + ((outputBits hq large (select state)).reverse ++ tapes dst)) k = tapes k := + MachineFiniteTable.output_frame dst + (fun state => (outputBits hq large (select state)).reverse) state tapes k hne + +theorem reverse_statement_pushBound {K Λ : Type} (dst : K) (exit : Λ) : + Runtime.statementPushBound (reverseStatement hq large select dst exit) ≤ + pushBound hq large select := by + have h := MachineFiniteTable.emit_push_bound (Γ := fun _ : K => Bool) + dst (fun state => (outputBits hq large (select state)).reverse) (keys σ) + (.goto (fun _ => exit)) + simpa only [reverseStatement, pushBound, MachineFiniteTable.tableBound, + List.length_reverse, Runtime.statementPushBound, Nat.add_zero] using h + +end +end PerfectCompleteness.DescriptorProjectionMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/DomainEncoding.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/DomainEncoding.lean new file mode 100644 index 0000000000000000000000000000000000000000..4f79dbb2b2be047d67c8fd9e1b2b2e64b83ececb --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/DomainEncoding.lean @@ -0,0 +1,209 @@ +import OAI.Computability.PerfectCompleteness.Foundations.ReducedDomains + +namespace OAI + +section + +namespace PerfectCompleteness.DomainEncoding + +open ClauseSupport ReducedDomains + +variable {I C Y Z : Type*} + +theorem allowed_dropped_iff (value : ReducedValue) : + Allowed .dropped value ↔ value = .dropped := by + cases value <;> simp [Allowed] + +theorem legalAssignments_all_dropped : + legalAssignments (fun _ : I => .dropped) = {fun _ : I => .dropped} := by + ext values + simp only [mem_legalAssignments, allowed_dropped_iff, Set.mem_singleton_iff] + exact ⟨fun h => funext h, fun h i => congrFun h i⟩ + +theorem localKey_eq_dropped_of_unused (s : MixedSupport.Slot) + (f : C → s.Domain → Y) (h : Unused f) : + MixedSupport.localKey s f = .dropped := by + classical + cases s with + | clause occurrence variableIDs signs => + change clauseKey occurrence variableIDs f = .dropped + simp only [clauseKey, clauseMode_unused f h] + | bit variableID => + change C → Bool → Y at f + change Unused (D := Bool) f at h + change bitKey variableID f = .dropped + simp only [bitKey, ite_eq_left h] + +theorem keyFields_eq_dropped_of_unused [DecidableEq I] + (slots : I → MixedSupport.Slot) (f : MixedSupport.Assignment slots → Y) + (h : ∀ i, Unused (MixedSupport.sectionFunction slots f i)) : + MixedSupport.keyFields slots f = fun _ => .dropped := by + funext i + exact localKey_eq_dropped_of_unused (slots i) + (MixedSupport.sectionFunction slots f i) (h i) + +theorem keyFields_eq_dropped_of_constant [DecidableEq I] + (slots : I → MixedSupport.Slot) (f : MixedSupport.Assignment slots → Y) + (h : ∀ x x', f x = f x') : + MixedSupport.keyFields slots f = fun _ => .dropped := by + apply keyFields_eq_dropped_of_unused slots f + intro i context u v + exact h _ _ + +def retainedFields {n : Nat} (keys : Fin n → SlotKey) : List (Fin n × SlotKey) := + ((List.finRange n).map (fun i => (i, keys i))).filter + (fun entry => decide (entry.2 ≠ .dropped)) + +theorem retainedKeys_eq_retainedFields {n : Nat} (slots : Fin n → MixedSupport.Slot) + (f : MixedSupport.Assignment slots → Y) : + MixedSupport.retainedKeys slots f = retainedFields (MixedSupport.keyFields slots f) := rfl + +theorem mem_retainedFields {n : Nat} (keys : Fin n → SlotKey) (i : Fin n) + (key : SlotKey) : + (i, key) ∈ retainedFields keys ↔ key = keys i ∧ key ≠ .dropped := by + constructor + · intro h + obtain ⟨hm, hretained⟩ := List.mem_filter.mp h + obtain ⟨j, _, hpair⟩ := List.mem_map.mp hm + have hji : j = i := congrArg Prod.fst hpair + subst j + have hkey : keys i = key := congrArg Prod.snd hpair + exact ⟨hkey.symm, of_decide_eq_true hretained⟩ + · rintro ⟨rfl, hretained⟩ + apply List.mem_filter.mpr + refine ⟨List.mem_map.mpr ⟨i, ?_, rfl⟩, ?_⟩ + · simp + · exact decide_eq_true hretained + +def lookupField [DecidableEq I] (fields : List (I × SlotKey)) (i : I) : SlotKey := + match fields with + | [] => .dropped + | (j, key) :: rest => if i = j then key else lookupField rest i + +theorem lookupField_eq_of_mem [DecidableEq I] (fields : List (I × SlotKey)) + (i : I) (key : SlotKey) : + (i, key) ∈ fields → (∀ key', (i, key') ∈ fields → key' = key) → + lookupField fields i = key := by + induction fields with + | nil => simp + | cons head rest ih => + rcases head with ⟨j, k⟩ + intro hmem hunique + by_cases hij : i = j + · subst i + simp only [lookupField] + exact hunique k (by simp) + · simp only [lookupField, ite_eq_right hij] + apply ih + · apply (List.mem_cons.mp hmem).resolve_left + intro hpair + exact hij (congrArg Prod.fst hpair) + · intro key' hkey' + exact hunique key' (List.mem_cons_of_mem _ hkey') + +theorem lookupField_eq_dropped [DecidableEq I] (fields : List (I × SlotKey)) (i : I) : + (∀ key, (i, key) ∉ fields) → lookupField fields i = .dropped := by + induction fields with + | nil => intro _; rfl + | cons head rest ih => + rcases head with ⟨j, k⟩ + intro hnone + have hij : i ≠ j := by + intro hij + subst i + exact hnone k (by simp) + simp only [lookupField, ite_eq_right hij] + apply ih + intro key hkey + exact hnone key (List.mem_cons_of_mem _ hkey) + +theorem lookupField_retainedFields {n : Nat} (keys : Fin n → SlotKey) (i : Fin n) : + lookupField (retainedFields keys) i = keys i := by + by_cases hdropped : keys i = .dropped + · calc + lookupField (retainedFields keys) i = .dropped := by + apply lookupField_eq_dropped + intro key hkey + obtain ⟨hkey, hretained⟩ := (mem_retainedFields keys i key).mp hkey + exact hretained (hkey.trans hdropped) + _ = keys i := hdropped.symm + · apply lookupField_eq_of_mem + · exact (mem_retainedFields keys i (keys i)).mpr ⟨rfl, hdropped⟩ + · intro key hkey + exact ((mem_retainedFields keys i key).mp hkey).1 + +theorem retainedFields_injective {n : Nat} : + Function.Injective (retainedFields (n := n)) := by + intro keys keys' h + funext i + have hlookup := congrArg (fun fields => lookupField fields i) h + simpa only [lookupField_retainedFields] using hlookup + +theorem keyFields_eq_of_retainedKeys_eq {n : Nat} + (slots projected : Fin n → MixedSupport.Slot) + (f : MixedSupport.Assignment slots → Y) + (g : MixedSupport.Assignment projected → Z) + (h : MixedSupport.retainedKeys slots f = MixedSupport.retainedKeys projected g) : + MixedSupport.keyFields slots f = MixedSupport.keyFields projected g := + retainedFields_injective h + +theorem legalAssignments_eq_of_retainedKeys_eq {n : Nat} + (slots projected : Fin n → MixedSupport.Slot) + (f : MixedSupport.Assignment slots → Y) + (g : MixedSupport.Assignment projected → Z) + (h : MixedSupport.retainedKeys slots f = MixedSupport.retainedKeys projected g) : + legalAssignments (MixedSupport.keyFields slots f) = + legalAssignments (MixedSupport.keyFields projected g) := + congrArg legalAssignments (keyFields_eq_of_retainedKeys_eq slots projected f g h) + +abbrev RetainedLocation (keys : I → SlotKey) := {i : I // keys i ≠ .dropped} + +abbrev RetainedAssignment (keys : I → SlotKey) := + (i : RetainedLocation keys) → {value : ReducedValue // Allowed (keys i.val) value} + +def restrictAssignment (keys : I → SlotKey) (values : ↥(legalAssignments keys)) : + RetainedAssignment keys := + fun i => ⟨values.val i.val, values.property i.val⟩ + +noncomputable def extendAssignment (keys : I → SlotKey) (values : RetainedAssignment keys) : + ↥(legalAssignments keys) := by + classical + refine ⟨fun i => if h : keys i = .dropped then .dropped else (values ⟨i, h⟩).val, ?_⟩ + change ∀ i, Allowed (keys i) + (if h : keys i = .dropped then .dropped else (values ⟨i, h⟩).val) + intro i + by_cases h : keys i = .dropped + · rw [dite_eq_left h, h] + trivial + · simpa only [dite_eq_right h] using (values ⟨i, h⟩).property + +noncomputable def legalRetainedEquiv (keys : I → SlotKey) : + ↥(legalAssignments keys) ≃ RetainedAssignment keys := by + classical + refine + { toFun := restrictAssignment keys + invFun := extendAssignment keys + left_inv := ?_ + right_inv := ?_ } + · intro values + apply Subtype.ext + funext i + change (if h : keys i = .dropped then .dropped else values.val i) = values.val i + by_cases h : keys i = .dropped + · simp only [dite_eq_left h] + have hv : Allowed .dropped (values.val i) := by + simpa only [h] using values.property i + exact ((allowed_dropped_iff _).mp hv).symm + · simp only [dite_eq_right h] + · intro values + funext i + apply Subtype.ext + change (if h : keys i.val = .dropped then .dropped + else (values ⟨i.val, h⟩).val) = (values i).val + simp only [dite_eq_right i.property] + +end PerfectCompleteness.DomainEncoding + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/EncodingLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/EncodingLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..06721cf0bdb839987dbc87ee95ebfc0c10e98bd4 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/EncodingLemmas.lean @@ -0,0 +1,231 @@ +import Mathlib.Tactic.Ring +import OAI.Computability.PerfectCompleteness.Model +import OAI.Computability.PerfectCompleteness.Reduction.Target +import OAI.Computability.UniqueGames.Machines.MachineSubroutineLemmas + +namespace OAI + + +namespace PerfectCompleteness.Encoding + +open UniqueGamesTheorem.Foundations.Complexity + +def parseLabel (alphabet value : Nat) : Option (Fin alphabet) := + if bounded : value < alphabet then some ⟨value, bounded⟩ else none + +@[simp] theorem parseLabel_value {q : Nat} (label : Fin q) : + parseLabel q label.val = some label := by + simp [parseLabel, label.isLt] + +@[simp] theorem parseLabels_values {q : Nat} (labels : List (Fin q)) : + (labels.map Fin.val).mapM (parseLabel q) = some labels := by + induction labels with + | nil => rfl + | cons label labels ih => simp [ih] + +def parseImages (alphabet : Nat) (words : List Nat) : + Option (Vector (Fin alphabet) (2 * alphabet)) := do + let labels ← words.mapM (parseLabel alphabet) + if length_ok : labels.length = 2 * alphabet then + some ⟨labels.toArray, by simpa using length_ok⟩ + else none + +@[simp] theorem parseImages_values {q : Nat} + (images : Vector (Fin q) (2 * q)) : + parseImages q (images.toList.map Fin.val) = some images := by + unfold parseImages + rw [parseLabels_values] + simp + exact Vector.toArray_toList + +def parseProjection (alphabet : Nat) (words : List Nat) : + Option (ProjectionTable alphabet) := do + let images ← parseImages alphabet words + if exactlyTwo : ∀ b : Fin alphabet, + ((List.finRange (2 * alphabet)).filter + (fun a => decide (images[a] = b))).length = 2 then + some ⟨images, exactlyTwo⟩ + else none + +@[simp] theorem parseProjection_encoded {q : Nat} (table : ProjectionTable q) : + parseProjection q (tableWords table) = some table := by + simp only [parseProjection, tableWords, parseImages_values] + dsimp only [Bind.bind, Option.bind] + simp only [table.exactlyTwo, implies_true, dite_true] + +@[simp] theorem tableWords_length {q : Nat} (table : ProjectionTable q) : + (tableWords table).length = 2 * q := by + simp [tableWords] + +def parseEdge (leftVertices rightVertices alphabet : Nat) : + List Nat → Option (Edge leftVertices rightVertices alphabet × List Nat) + | left :: right :: words => do + let left ← parseLabel leftVertices left + let right ← parseLabel rightVertices right + let projection ← parseProjection alphabet (words.take (2 * alphabet)) + return (⟨left, right, projection⟩, words.drop (2 * alphabet)) + | _ => none + +@[simp] theorem parseEdge_encoded {l r q : Nat} + (edge : Edge l r q) (rest : List Nat) : + parseEdge l r q (edgeWords edge ++ rest) = some (edge, rest) := by + cases edge with + | mk left right projection => + have taken := List.take_left' (l₂ := rest) (tableWords_length projection) + have dropped := List.drop_left' (l₂ := rest) (tableWords_length projection) + simp [edgeWords, parseEdge, taken, dropped] + +def parseEdges (leftVertices rightVertices alphabet : Nat) : + Nat → List Nat → Option (List (Edge leftVertices rightVertices alphabet) × List Nat) + | 0, words => some ([], words) + | count + 1, words => do + let (edge, words) ← parseEdge leftVertices rightVertices alphabet words + let (edges, words) ← parseEdges leftVertices rightVertices alphabet count words + return (edge :: edges, words) + +@[simp] theorem parseEdges_encoded {l r q : Nat} + (edges : List (Edge l r q)) (rest : List Nat) : + parseEdges l r q edges.length (edges.flatMap edgeWords ++ rest) = + some (edges, rest) := by + induction edges with + | nil => rfl + | cons edge edges ih => simp [parseEdges, List.append_assoc, ih] + +def decodeGameWords (alphabet : Nat) : List Nat → Option (Instance alphabet) + | leftVertices :: rightVertices :: encodedAlphabet :: count :: words => do + if encodedAlphabet = alphabet then + let (edges, trailing) ← parseEdges leftVertices rightVertices alphabet count words + if trailing = [] then + if nonempty : edges ≠ [] then + some ⟨leftVertices, rightVertices, edges, nonempty⟩ + else none + else none + else none + | _ => none + +@[simp] theorem decodeGameWords_encoded {q : Nat} (game : Instance q) : + decodeGameWords q (gameWords game) = some game := by + cases game with + | mk leftVertices rightVertices edges nonempty => + have parsed := parseEdges_encoded edges [] + simp only [List.append_nil] at parsed + simp [decodeGameWords, gameWords, parsed, nonempty] + +def decodeGameBits (alphabet : Nat) (bits : List Bool) : Option (Instance alphabet) := + decodeWords bits >>= decodeGameWords alphabet + +@[simp] theorem decodeGameBits_encoded {q : Nat} (game : Instance q) : + decodeGameBits q (gameBits game) = some game := by + simp [decodeGameBits, gameBits] + +theorem gameBits_injective {q : Nat} {first second : Instance q} + (same : gameBits first = gameBits second) : first = second := by + have parsed := congrArg (decodeGameBits q) same + simpa only [decodeGameBits_encoded, Option.some.injEq] using parsed + +@[simp] theorem edgeWords_length {l r q : Nat} (edge : Edge l r q) : + (edgeWords edge).length = 2 * q + 2 := by + simp [edgeWords] + +theorem edgesWords_length {l r q : Nat} (edges : List (Edge l r q)) : + (edges.flatMap edgeWords).length = edges.length * (2 * q + 2) := by + induction edges with + | nil => simp + | cons edge edges ih => + simp only [List.flatMap_cons, List.length_append, edgeWords_length, + List.length_cons, Nat.add_mul, Nat.one_mul, ih] + omega + +@[simp] theorem gameWords_length {q : Nat} (game : Instance q) : + (gameWords game).length = 4 + game.edges.length * (2 * q + 2) := by + simp only [gameWords, List.length_append, List.length_cons, List.length_nil, + edgesWords_length] + +theorem gameBits_length {q : Nat} (game : Instance q) : + (gameBits game).length = + (gameWords game).sum + 4 + game.edges.length * (2 * q + 2) := by + simp only [gameBits, encodeWords_length, gameWords_length] + omega + +end PerfectCompleteness.Encoding + + +namespace PerfectCompleteness.Encoding + +theorem tableWords_sum_le {q : Nat} (table : ProjectionTable q) : + (tableWords table).sum ≤ 2 * q * q := by + have hsum (labels : List (Fin q)) : + (labels.map Fin.val).sum ≤ labels.length * q := by + induction labels with + | nil => simp + | cons a labels ih => + simp only [List.map_cons, List.sum_cons, List.length_cons, + Nat.add_mul, Nat.one_mul] + calc + _ ≤ q + labels.length * q := + Nat.add_le_add (Nat.le_of_lt a.isLt) ih + _ = labels.length * q + q := Nat.add_comm _ _ + simpa [tableWords] using hsum table.images.toList + +theorem edgeWords_sum_le {l r q : Nat} (edge : Edge l r q) : + (edgeWords edge).sum ≤ l + r + 2 * q * q := by + calc + _ = edge.left.val + edge.right.val + (tableWords edge.projection).sum := by + simp [edgeWords, Nat.add_assoc] + _ ≤ l + r + 2 * q * q := + Nat.add_le_add + (Nat.add_le_add (Nat.le_of_lt edge.left.isLt) (Nat.le_of_lt edge.right.isLt)) + (tableWords_sum_le edge.projection) + +theorem edgesWords_sum_le {l r q : Nat} (edges : List (Edge l r q)) : + (edges.flatMap edgeWords).sum ≤ edges.length * (l + r + 2 * q * q) := by + induction edges with + | nil => simp + | cons edge edges ih => + calc + _ = (edgeWords edge).sum + (edges.flatMap edgeWords).sum := by + rw [List.flatMap_cons, List.sum_append] + _ ≤ (l + r + 2 * q * q) + edges.length * (l + r + 2 * q * q) := + Nat.add_le_add (edgeWords_sum_le edge) ih + _ = (edge :: edges).length * (l + r + 2 * q * q) := by + simp only [List.length_cons, Nat.add_mul, Nat.one_mul] + exact Nat.add_comm _ _ + +theorem gameWords_sum_le {q : Nat} (game : Instance q) : + (gameWords game).sum ≤ + game.leftVertices + game.rightVertices + q + game.edges.length + + game.edges.length * (game.leftVertices + game.rightVertices + 2 * q * q) := by + calc + _ = (game.leftVertices + game.rightVertices + q + game.edges.length) + + (game.edges.flatMap edgeWords).sum := by + simp [gameWords, Nat.add_assoc] + _ ≤ _ := Nat.add_le_add_left (edgesWords_sum_le game.edges) _ + +theorem gameBits_length_le {q : Nat} (game : Instance q) : + (gameBits game).length ≤ + game.leftVertices + game.rightVertices + q + game.edges.length + 4 + + game.edges.length * + (game.leftVertices + game.rightVertices + 2 * q * q + 2 * q + 2) := by + rw [gameBits_length] + calc + _ ≤ (game.leftVertices + game.rightVertices + q + game.edges.length + + game.edges.length * (game.leftVertices + game.rightVertices + 2 * q * q)) + + 4 + game.edges.length * (2 * q + 2) := + Nat.add_le_add_right (Nat.add_le_add_right (gameWords_sum_le game) 4) _ + _ = _ := by ring + +theorem gameBits_length_le_of_edge_count {q : Nat} (game : Instance q) + (M : Nat) (hM : game.edges.length ≤ M) : + (gameBits game).length ≤ + game.leftVertices + game.rightVertices + q + M + 4 + + M * (game.leftVertices + game.rightVertices + 2 * q * q + 2 * q + 2) := by + apply (gameBits_length_le game).trans + exact Nat.add_le_add + (Nat.add_le_add_right + (Nat.add_le_add_left hM (game.leftVertices + game.rightVertices + q)) 4) + (Nat.mul_le_mul_right + (game.leftVertices + game.rightVertices + 2 * q * q + 2 * q + 2) hM) + +end PerfectCompleteness.Encoding + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/ExactTargetOdometer.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/ExactTargetOdometer.lean new file mode 100644 index 0000000000000000000000000000000000000000..6f9d9c7ab4b676e6c9fa4f97ca67483e0ef8d97e --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/ExactTargetOdometer.lean @@ -0,0 +1,990 @@ +import OAI.Computability.PerfectCompleteness.Foundations.SignedTupleSemantics +import OAI.Computability.PerfectCompleteness.Machines.SignedRuntimeBounds +import OAI.Computability.PerfectCompleteness.Machines.SignedTupleBodyMachine +import OAI.Computability.PerfectCompleteness.Machines.SourceOccurrenceProducerLemmas +import OAI.Computability.PerfectCompleteness.Reduction.CompletedVisitOrder +import OAI.Computability.UniqueGames.Machines.MachineTupleOdometer + +namespace OAI + + +namespace PerfectCompleteness.ExactTargetOdometer + + +open UniqueGamesTheorem.Foundations.Complexity +open scoped Classical + +noncomputable section + +variable {width radix : Nat} + +def setCoordinate (digits : Fin width → Fin radix) (depth : Nat) (value : Fin radix) : + Fin width → Fin radix := + fun i => if i.val = depth then value else digits i + +@[simp] theorem setCoordinate_self (digits : Fin width → Fin radix) + (i : Fin width) (value : Fin radix) : + setCoordinate digits i.val value i = value := by + simp [setCoordinate] + +theorem setCoordinate_eq_update (digits : Fin width → Fin radix) + (coordinate : Fin width) (value : Fin radix) : + setCoordinate digits coordinate.val value = Function.update digits coordinate value := by + funext i + by_cases same : i = coordinate + · subst i + simp [setCoordinate] + · have different : i.val ≠ coordinate.val := fun h => same (Fin.ext h) + simp [setCoordinate, same, different] + +theorem setCoordinate_zero (digits : Fin width → Fin radix) (depth : Nat) + (positive : 0 < radix) (zero : ∀ i, i.val = depth → (digits i).val = 0) : + setCoordinate digits depth ⟨0, positive⟩ = digits := by + funext i + by_cases same : i.val = depth + · simp only [setCoordinate, ite_eq_left same] + apply Fin.ext + exact (zero i same).symm + · simp [setCoordinate, same] + +def fillCoordinates (digits : Fin width → Fin radix) {depth : Nat} + (tuple : Fin depth → Fin radix) : Fin width → Fin radix := + fun i => if h : i.val < depth then tuple ⟨i.val, h⟩ else digits i + +@[simp] theorem fillCoordinates_zero (digits : Fin width → Fin radix) + (tuple : Fin 0 → Fin radix) : fillCoordinates digits tuple = digits := by + funext i + simp [fillCoordinates] + +@[simp] theorem fillCoordinates_all (digits : Fin width → Fin radix) + (tuple : Fin width → Fin radix) : fillCoordinates digits tuple = tuple := by + funext i + simp [fillCoordinates, i.isLt] + +theorem fillCoordinates_snoc (digits : Fin width → Fin radix) {depth : Nat} + (tuple : Fin depth → Fin radix) (value : Fin radix) : + fillCoordinates digits (Fin.snoc tuple value) = + fillCoordinates (setCoordinate digits depth value) tuple := by + funext i + by_cases hi : i.val < depth + · have hi' : i.val < depth + 1 := by omega + simp [fillCoordinates, hi, hi', Fin.snoc] + · by_cases same : i.val = depth + · simp [fillCoordinates, Fin.snoc, setCoordinate, same] + · have hi' : ¬ i.val < depth + 1 := by omega + simp [fillCoordinates, hi, hi', setCoordinate, same] + +def visits : Nat → (Fin width → Fin radix) → List (Fin width → Fin radix) + | 0, digits => [digits] + | depth + 1, digits => (List.ofFn (fun value : Fin radix => value)).flatMap + (fun value => visits depth (setCoordinate digits depth value)) + +theorem visits_eq_tupleOrder (depth : Nat) (digits : Fin width → Fin radix) : + visits depth digits = (MachineTupleOdometer.tupleOrder radix depth).map + (fillCoordinates digits) := by + induction depth generalizing digits with + | zero => + simp only [visits, MachineTupleOdometer.tupleOrder_dimension_zero, + List.map_cons, List.map_nil, fillCoordinates_zero] + | succ depth ih => + rw [visits, MachineTupleOdometer.tupleOrder_snoc, List.map_flatMap] + apply List.flatMap_congr + intro value _ + rw [ih, List.map_map] + apply List.map_congr_left + intro tuple _ + exact (fillCoordinates_snoc digits tuple value).symm + +@[simp] theorem visits_all (digits : Fin width → Fin radix) : + visits width digits = MachineTupleOdometer.tupleOrder radix width := by + have identity : fillCoordinates digits = + (id : (Fin width → Fin radix) → (Fin width → Fin radix)) := by + funext tuple + exact fillCoordinates_all digits tuple + rw [visits_eq_tupleOrder, identity, List.map_id] + +def foldVisits {P : Type*} (step : (Fin width → Fin radix) → P → P) + (depth : Nat) (digits : Fin width → Fin radix) (initial : P) : P := + (visits depth digits).foldl (fun data tuple => step tuple data) initial + +@[simp] theorem foldVisits_zero {P : Type*} (step : (Fin width → Fin radix) → P → P) + (digits : Fin width → Fin radix) (initial : P) : + foldVisits step 0 digits initial = step digits initial := rfl + +def blockPrefix {P : Type*} (step : (Fin width → Fin radix) → P → P) + (depth : Nat) (digits : Fin width → Fin radix) (count : Nat) (initial : P) : P := + ((List.ofFn (fun value : Fin radix => value)).take count).foldl + (fun data value => foldVisits step depth (setCoordinate digits depth value) data) initial + +@[simp] theorem blockPrefix_zero {P : Type*} (step : (Fin width → Fin radix) → P → P) + (depth : Nat) (digits : Fin width → Fin radix) (initial : P) : + blockPrefix step depth digits 0 initial = initial := rfl + +theorem blockPrefix_succ {P : Type*} (step : (Fin width → Fin radix) → P → P) + (depth : Nat) (digits : Fin width → Fin radix) (value : Fin radix) (initial : P) : + blockPrefix step depth digits (value.val + 1) initial = + foldVisits step depth (setCoordinate digits depth value) + (blockPrefix step depth digits value.val initial) := by + have inside : value.val < (List.ofFn (fun value : Fin radix => value)).length := by + simpa only [List.length_ofFn] using value.isLt + simp only [blockPrefix, List.take_succ_eq_append_getElem inside, + List.foldl_append, List.foldl_cons, List.foldl_nil, List.getElem_ofFn] + +@[simp] theorem blockPrefix_all {P : Type*} (step : (Fin width → Fin radix) → P → P) + (depth : Nat) (digits : Fin width → Fin radix) (initial : P) : + blockPrefix step depth digits radix initial = foldVisits step (depth + 1) digits initial := by + have complete : (List.ofFn (fun value : Fin radix => value)).take radix = + List.ofFn (fun value : Fin radix => value) := + List.take_of_length_le (by simp) + simp only [blockPrefix, complete, foldVisits, visits, List.foldl_flatMap] + +variable {branch : Nat → Nat} {n t v m : Nat} + +theorem visits_sourceOrder + (digits : Fin (TreeCanonical.locationCount branch n t) → Fin m) : + (visits (TreeCanonical.locationCount branch n t) digits).map + SourceQuestionOrder.tupleToQuestion = SourceVisitOrder.visitOrder branch n t m := by + rw [visits_all, SourceVisitOrder.visitOrder_eq_tupleOrder] + +variable (clauses : Fin m → SourceClause.NormalizedClause v) (rows repeats : Nat → Nat) + [NeZero m] (hn : 0 < n) (hbranch : ∀ k < n, 0 < branch k) + (hrows : ∀ k, 0 < rows (k + 1)) (δ : ℚ) + +theorem visits_completedOrder + (digits : Fin (TreeCanonical.locationCount branch n t) → Fin m) : + (visits (TreeCanonical.locationCount branch n t) digits).flatMap + (fun tuple => CompletedVisitOrder.localOrder clauses rows repeats hn hbranch hrows δ + (SourceQuestionOrder.tupleToQuestion tuple)) = + CompletedVisitOrder.completedOrder (t := t) clauses rows repeats hn hbranch hrows δ := by + rw [CompletedVisitOrder.completedOrder, ← visits_sourceOrder digits, List.flatMap_map] + +end + +noncomputable section + +variable {width : Nat} {Extra : Type} + +def baseTapes (input : NormalizedSourceInput.Input) + (indices : Fin width → Fin (NormalizedSourceInput.clauseCount input)) + (extra : Extra → List Bool) : SignedTupleLayout.Tape width Extra → List Bool + | .source .table => NormalizedSourceInput.bits input + | .current i => encodeWord (indices i).val + | .remaining i => encodeWord (NormalizedSourceInput.clauseCount input - 1 - (indices i).val) + | .extra x => extra x + | _ => [] + +theorem baseTapes_input (input : NormalizedSourceInput.Input) + (indices : Fin width → Fin (NormalizedSourceInput.clauseCount input)) + (extra : Extra → List Bool) : + SignedTupleLayout.Input input.formula indices (baseTapes input indices extra) where + toClear := { + rawDigits := fun _ => rfl + rawVariables := fun _ _ => rfl + sourceWork := fun _ => rfl + encodedVariables := fun _ _ => rfl + scratch := rfl + } + table := rfl + current := fun _ => rfl + +@[simp] theorem baseTapes_edgeWork (input : NormalizedSourceInput.Input) + (indices : Fin width → Fin (NormalizedSourceInput.clauseCount input)) + (extra : Extra → List Bool) (j : Fin 10) : + baseTapes input indices extra (.edgeWork j) = [] := rfl + +theorem baseTapes_emptyWork (input : NormalizedSourceInput.Input) + (indices : Fin width → Fin (NormalizedSourceInput.clauseCount input)) + (extra : Extra → List Bool) : + ∀ j : Fin 10, j ≠ 1 → j ≠ 7 → j ≠ 8 → + baseTapes input indices extra (.edgeWork j) = [] := by + intro j _ _ _ + rfl + + +variable {branch : Nat → Nat} {n t : Nat} [DecidableEq Extra] + +local notation "W" => TreeCanonical.locationCount branch n t + +def nativeTapes (input : NormalizedSourceInput.Input) + (indices : Fin W → Fin (NormalizedSourceInput.clauseCount input)) + (data : SignedTupleBodyMachine.Data W) (extra : Extra → List Bool) : + SignedTupleLayout.Tape W Extra → List Bool := + SignedTupleBodyMachine.tapes (branch := branch) (n := n) (t := t) + SignedTupleLayout.Tape.edgeWork SignedTupleLayout.Tape.edgeCount + (baseTapes input indices extra) data + +@[simp] theorem nativeTapes_table (input : NormalizedSourceInput.Input) + (indices : Fin W → Fin (NormalizedSourceInput.clauseCount input)) + (data : SignedTupleBodyMachine.Data W) (extra : Extra → List Bool) : + nativeTapes input indices data extra (.source .table) = NormalizedSourceInput.bits input := by + simp [nativeTapes, SignedTupleBodyMachine.tapes, baseTapes] + +@[simp] theorem nativeTapes_current (input : NormalizedSourceInput.Input) + (indices : Fin W → Fin (NormalizedSourceInput.clauseCount input)) + (data : SignedTupleBodyMachine.Data W) (extra : Extra → List Bool) (i : Fin W) : + nativeTapes input indices data extra (.current i) = encodeWord (indices i).val := by + simp [nativeTapes, SignedTupleBodyMachine.tapes, baseTapes] + +@[simp] theorem nativeTapes_remaining (input : NormalizedSourceInput.Input) + (indices : Fin W → Fin (NormalizedSourceInput.clauseCount input)) + (data : SignedTupleBodyMachine.Data W) (extra : Extra → List Bool) (i : Fin W) : + nativeTapes input indices data extra (.remaining i) = + encodeWord (NormalizedSourceInput.clauseCount input - 1 - (indices i).val) := by + simp [nativeTapes, SignedTupleBodyMachine.tapes, baseTapes] + +@[simp] theorem nativeTapes_output (input : NormalizedSourceInput.Input) + (indices : Fin W → Fin (NormalizedSourceInput.clauseCount input)) + (data : SignedTupleBodyMachine.Data W) (extra : Extra → List Bool) : + nativeTapes input indices data extra (.edgeWork 7) = data.reversedOutput := by + simp [nativeTapes, SignedTupleBodyMachine.tapes] + +@[simp] theorem nativeTapes_count (input : NormalizedSourceInput.Input) + (indices : Fin W → Fin (NormalizedSourceInput.clauseCount input)) + (data : SignedTupleBodyMachine.Data W) (extra : Extra → List Bool) : + nativeTapes input indices data extra .edgeCount = encodeWord data.count := by + simp [nativeTapes, SignedTupleBodyMachine.tapes] + +@[simp] theorem nativeTapes_extra (input : NormalizedSourceInput.Input) + (indices : Fin W → Fin (NormalizedSourceInput.clauseCount input)) + (data : SignedTupleBodyMachine.Data W) (extra : Extra → List Bool) (x : Extra) : + nativeTapes input indices data extra (.extra x) = extra x := by + simp [nativeTapes, SignedTupleBodyMachine.tapes, baseTapes] + +theorem nativeTapes_input (input : NormalizedSourceInput.Input) + (indices : Fin W → Fin (NormalizedSourceInput.clauseCount input)) + (data : SignedTupleBodyMachine.Data W) (extra : Extra → List Bool) : + SignedTupleLayout.Input input.formula indices (nativeTapes input indices data extra) := by + exact SignedTupleBodyMachine.tapes_input (branch := branch) (n := n) (t := t) + input.formula indices (baseTapes input indices extra) + (baseTapes_input input indices extra) data + +theorem nativeTapes_emptyWork (input : NormalizedSourceInput.Input) + (indices : Fin W → Fin (NormalizedSourceInput.clauseCount input)) + (data : SignedTupleBodyMachine.Data W) (extra : Extra → List Bool) + (j : Fin 10) (h1 : j ≠ 1) (h7 : j ≠ 7) (h8 : j ≠ 8) : + nativeTapes input indices data extra (.edgeWork j) = [] := by + simp [nativeTapes, SignedTupleBodyMachine.tapes, baseTapes, h1, h7, h8] + +theorem digitTapes_nativeTapes (input : NormalizedSourceInput.Input) + (indices : Fin W → Fin (NormalizedSourceInput.clauseCount input)) + (data : SignedTupleBodyMachine.Data W) (extra : Extra → List Bool) + (coordinate : Fin W) (value : Fin (NormalizedSourceInput.clauseCount input)) : + MachineTupleOdometer.digitTapes + (SignedTupleLayout.Tape.current coordinate) + (SignedTupleLayout.Tape.remaining coordinate) + (nativeTapes input indices data extra) + value.val (NormalizedSourceInput.clauseCount input - 1 - value.val) [] [] = + nativeTapes input (Function.update indices coordinate value) data extra := by + funext tape + cases tape with + | source source => + cases source <;> + simp [MachineTupleOdometer.digitTapes, MachineUnaryAddAt.unaryTapes, + UniqueGamesTheorem.Reduction.MachineTransfer.tapesAt, + nativeTapes, SignedTupleBodyMachine.tapes, baseTapes] + | current position => + by_cases same : position = coordinate + · subst position + simp [MachineTupleOdometer.digitTapes, MachineUnaryAddAt.unaryTapes, + UniqueGamesTheorem.Reduction.MachineTransfer.tapesAt, + nativeTapes, SignedTupleBodyMachine.tapes, baseTapes] + · simp [MachineTupleOdometer.digitTapes, MachineUnaryAddAt.unaryTapes, + UniqueGamesTheorem.Reduction.MachineTransfer.tapesAt, + nativeTapes, SignedTupleBodyMachine.tapes, baseTapes, same] + | remaining position => + by_cases same : position = coordinate + · subst position + simp [MachineTupleOdometer.digitTapes, MachineUnaryAddAt.unaryTapes, + UniqueGamesTheorem.Reduction.MachineTransfer.tapesAt, + nativeTapes, SignedTupleBodyMachine.tapes, baseTapes] + · simp [MachineTupleOdometer.digitTapes, MachineUnaryAddAt.unaryTapes, + UniqueGamesTheorem.Reduction.MachineTransfer.tapesAt, + nativeTapes, SignedTupleBodyMachine.tapes, baseTapes, same] + | encodedVariable position slot => + simp [MachineTupleOdometer.digitTapes, MachineUnaryAddAt.unaryTapes, + UniqueGamesTheorem.Reduction.MachineTransfer.tapesAt, + nativeTapes, SignedTupleBodyMachine.tapes, baseTapes] + | adapterScratch => + simp [MachineTupleOdometer.digitTapes, MachineUnaryAddAt.unaryTapes, + UniqueGamesTheorem.Reduction.MachineTransfer.tapesAt, + nativeTapes, SignedTupleBodyMachine.tapes, baseTapes] + | edgeWork j => + simp [MachineTupleOdometer.digitTapes, MachineUnaryAddAt.unaryTapes, + UniqueGamesTheorem.Reduction.MachineTransfer.tapesAt, + nativeTapes, SignedTupleBodyMachine.tapes, baseTapes, Function.update_apply] + | edgeCount => + simp [MachineTupleOdometer.digitTapes, MachineUnaryAddAt.unaryTapes, + UniqueGamesTheorem.Reduction.MachineTransfer.tapesAt, + nativeTapes, SignedTupleBodyMachine.tapes] + | extra x => + simp [MachineTupleOdometer.digitTapes, MachineUnaryAddAt.unaryTapes, + UniqueGamesTheorem.Reduction.MachineTransfer.tapesAt, + nativeTapes, SignedTupleBodyMachine.tapes, baseTapes] + +end + +inductive Label (locations stages : Nat) (Descriptor Extra : Type) + | body (label : SignedTupleBodyMachine.BodyLabel locations stages Descriptor Extra) + | check (coordinate : Fin locations) + | reset (coordinate : Fin locations) + | exit + deriving DecidableEq, Fintype + +noncomputable section Native + +variable {branch : Nat → Nat} {n t : Nat} + (rows repeats : Nat → Nat) (hn : 0 < n) (hbranch : ∀ k < n, 0 < branch k) + (hrows : ∀ k, 0 < rows (k + 1)) (δ : ℚ) + +local notation "width" => TreeCanonical.locationCount branch n t +local notation "q" => FinitePreliminaryCompletion.alphabet branch n t δ +local notation "hq" => CanonicalLocalCompletion.alphabet_positive width δ +local notation "large" => CanonicalLocalCompletion.partitionWidth_le_alphabet width δ +local notation "D" => SignedMultiplicity.denominator branch n t rows repeats hn hbranch hrows q +local notation "Desc" => SignedCompletionSchedule.Descriptor (rows := rows) (repeats := repeats) hq large + +abbrev Control := SignedTupleLayout.State width Unit Desc +abbrev Ambient := (SourceTupleMachine.State width Unit × Option Desc) × (Bool × Option Bool) +abbrev NativeLabel (Extra : Type) := Label width D Desc Extra + +variable {Extra : Type} [DecidableEq Extra] + +local notation "Arena" => SignedTupleLayout.Tape width Extra +local notation "Labels" => NativeLabel (branch := branch) (n := n) (t := t) + rows repeats hn hbranch hrows δ Extra +local notation "Registers" => Control (branch := branch) (n := n) (t := t) rows repeats δ + +def checkAt (depth : Nat) : Labels := + if h : depth < width then .check ⟨depth, h⟩ else .exit + +def resetAt (depth : Nat) : Labels := + if h : depth < width then .reset ⟨depth, h⟩ else .exit + +def currentAt (depth : Nat) : Arena := + if h : depth < width then .current ⟨depth, h⟩ else .adapterScratch + +def remainingAt (depth : Nat) : Arena := + if h : depth < width then .remaining ⟨depth, h⟩ else .edgeCount + +def body : Labels := .body .start + +def program : Labels → Turing.TM2.Stmt (fun _ : Arena => Bool) Labels Registers + | .body label => SignedTupleBodyMachine.bodyInstruction (branch := branch) (n := n) (t := t) + (rows := rows) (repeats := repeats) hq large hn hbranch hrows + Label.body (some (checkAt (branch := branch) (n := n) (t := t) + (Extra := Extra) rows repeats hn hbranch hrows δ 0)) label + | .check i => MachineTupleOdometer.increment (.current i) (.remaining i) + (body (branch := branch) (n := n) (t := t) + (Extra := Extra) rows repeats hn hbranch hrows δ) (.reset i) + | .reset i => MachineTupleOdometer.reset (.current i) (.remaining i) (.reset i) + (checkAt (branch := branch) (n := n) (t := t) + (Extra := Extra) rows repeats hn hbranch hrows δ (i.val + 1)) + | .exit => .halt + +def tupleStep (input : NormalizedSourceInput.Input) + (indices : Fin width → Fin (NormalizedSourceInput.clauseCount input)) + (data : SignedTupleBodyMachine.Data width) : SignedTupleBodyMachine.Data width := + SignedTupleBodyMachine.result (branch := branch) (n := n) (t := t) + (rows := rows) (repeats := repeats) hq large hn hbranch hrows + (MetadataFreeSampler.sourceSigns (NormalizedSourceInput.clauses input) + (SourceQuestionOrder.tupleToQuestion indices)) + (fun i => (indices i).val) + (fun i slot => ((NormalizedSourceInput.clauses input) (indices i)).variable slot |>.val) + (List.ofFn (fun i : Fin D => i)) data + +@[simp] theorem tupleStep_count (input : NormalizedSourceInput.Input) + (indices : Fin width → Fin (NormalizedSourceInput.clauseCount input)) + (data : SignedTupleBodyMachine.Data width) : + (tupleStep rows repeats hn hbranch hrows δ input indices data).count = data.count + D := by + simp only [tupleStep, SignedTupleBodyMachine.result_count, List.length_ofFn] + +theorem tupleStep_eq (input : NormalizedSourceInput.Input) + (indices : Fin width → Fin (NormalizedSourceInput.clauseCount input)) + (data : SignedTupleBodyMachine.Data width) : + tupleStep rows repeats hn hbranch hrows δ input indices data = + SignedTupleBodyMachine.tupleResult (branch := branch) (n := n) (t := t) + (rows := rows) (repeats := repeats) + hq large hn hbranch hrows input.formula indices data := rfl + +local notation "runProgram" => program (branch := branch) (n := n) (t := t) + (Extra := Extra) rows repeats hn hbranch hrows δ +local notation "entry" => body (branch := branch) (n := n) (t := t) + (Extra := Extra) rows repeats hn hbranch hrows δ +local notation "atCheck" => checkAt (branch := branch) (n := n) (t := t) + (Extra := Extra) rows repeats hn hbranch hrows δ +local notation "atReset" => resetAt (branch := branch) (n := n) (t := t) + (Extra := Extra) rows repeats hn hbranch hrows δ +local notation "atCurrent" => currentAt (branch := branch) (n := n) (t := t) (Extra := Extra) +local notation "atRemaining" => remainingAt (branch := branch) (n := n) (t := t) (Extra := Extra) + +def configuration (label : Labels) (input : NormalizedSourceInput.Input) + (indices : Fin width → Fin (NormalizedSourceInput.clauseCount input)) + (data : SignedTupleBodyMachine.Data width) (extra : Extra → List Bool) : + Turing.TM2.Cfg (fun _ : Arena => Bool) Labels Registers := + ⟨some label, SignedTupleLayout.clean (), nativeTapes input indices data extra⟩ + +local notation "cfg" => configuration rows repeats hn hbranch hrows δ + +def leafBudget (input : NormalizedSourceInput.Input) + (indices : Fin width → Fin (NormalizedSourceInput.clauseCount input)) + (data : SignedTupleBodyMachine.Data width) (extra : Extra → List Bool) : Nat := + SignedTupleBodyMachine.bodyBudget (branch := branch) (n := n) (t := t) + (rows := rows) (repeats := repeats) + hq large hn hbranch hrows + input.formula indices (baseTapes input indices extra) data + +def leafInTime (input : NormalizedSourceInput.Input) + (indices : Fin width → Fin (NormalizedSourceInput.clauseCount input)) + (data : SignedTupleBodyMachine.Data width) (extra : Extra → List Bool) : + StateTransition.EvalsToInTime (Turing.TM2.step runProgram) + (cfg entry input indices data extra) + (some (cfg (atCheck 0) input indices + (tupleStep rows repeats hn hbranch hrows δ input indices data) extra)) + (leafBudget rows repeats hn hbranch hrows δ input indices data extra) := by + have run := SignedTupleBodyMachine.bodyInTime (branch := branch) (n := n) (t := t) + (rows := rows) (repeats := repeats) hq large hn hbranch hrows + input.formula indices (baseTapes input indices extra) (baseTapes_input input indices extra) + () data Label.body (some (atCheck 0)) runProgram (fun _ => rfl) + (baseTapes_emptyWork input indices extra) + simpa only [configuration, body, SignedTupleBodyMachine.bodyMain, nativeTapes, + tupleStep_eq, leafBudget] using run + +def maxLeafBudget (input : NormalizedSourceInput.Input) (extra : Extra → List Bool) : + Nat → (Fin width → Fin (NormalizedSourceInput.clauseCount input)) → + SignedTupleBodyMachine.Data width → Nat + | 0, indices, data => leafBudget rows repeats hn hbranch hrows δ input indices data extra + | depth + 1, indices, data => Finset.univ.sup fun value => + maxLeafBudget input extra depth (setCoordinate indices depth value) + (blockPrefix (tupleStep rows repeats hn hbranch hrows δ input) depth indices value.val data) + +def CostsAtMost (input : NormalizedSourceInput.Input) (extra : Extra → List Bool) (B : Nat) : + Nat → (Fin width → Fin (NormalizedSourceInput.clauseCount input)) → + SignedTupleBodyMachine.Data width → Prop + | 0, indices, data => leafBudget rows repeats hn hbranch hrows δ input indices data extra ≤ B + | depth + 1, indices, data => ∀ value, + CostsAtMost input extra B depth (setCoordinate indices depth value) + (blockPrefix (tupleStep rows repeats hn hbranch hrows δ input) depth indices value.val data) + +theorem costsAtMost_of_max (input : NormalizedSourceInput.Input) (extra : Extra → List Bool) + (depth : Nat) (indices : Fin width → Fin (NormalizedSourceInput.clauseCount input)) + (data : SignedTupleBodyMachine.Data width) (B : Nat) + (bounded : maxLeafBudget rows repeats hn hbranch hrows δ input extra depth indices data ≤ B) : + CostsAtMost rows repeats hn hbranch hrows δ input extra B depth indices data := by + induction depth generalizing indices data with + | zero => exact bounded + | succ depth ih => + intro value + apply ih + exact (Finset.le_sup (Finset.mem_univ value)).trans bounded + +private theorem digitTapes_at (input : NormalizedSourceInput.Input) + (indices : Fin width → Fin (NormalizedSourceInput.clauseCount input)) + (data : SignedTupleBodyMachine.Data width) (extra : Extra → List Bool) + (depth remainder : Nat) (inside : depth < width) + (remainingBound : remainder ≤ NormalizedSourceInput.clauseCount input - 1) : + MachineTupleOdometer.digitTapes (atCurrent depth) (atRemaining depth) + (nativeTapes input indices data extra) + (NormalizedSourceInput.clauseCount input - 1 - remainder) remainder [] [] = + nativeTapes input (setCoordinate indices depth + ⟨NormalizedSourceInput.clauseCount input - 1 - remainder, + by have := NormalizedSourceInput.clauseCount_positive input; omega⟩) data extra := by + have positive := NormalizedSourceInput.clauseCount_positive input + have valueBound : NormalizedSourceInput.clauseCount input - 1 - remainder < + NormalizedSourceInput.clauseCount input := by omega + have complement : NormalizedSourceInput.clauseCount input - 1 - + (NormalizedSourceInput.clauseCount input - 1 - remainder) = remainder := by omega + have h := digitTapes_nativeTapes input indices data extra ⟨depth, inside⟩ + ⟨NormalizedSourceInput.clauseCount input - 1 - remainder, valueBound⟩ + simpa only [currentAt, remainingAt, dite_eq_left inside, complement, + ← setCoordinate_eq_update] using h + +theorem existsTree (input : NormalizedSourceInput.Input) (extra : Extra → List Bool) + (B depth : Nat) (inside : depth ≤ width) + (indices : Fin width → Fin (NormalizedSourceInput.clauseCount input)) + (zero : ∀ i, i.val < depth → (indices i).val = 0) + (data : SignedTupleBodyMachine.Data width) + (costs : CostsAtMost rows repeats hn hbranch hrows δ input extra B depth indices data) : + ∃ tree : MachineTupleOdometer.NestedCycle (NormalizedSourceInput.clauseCount input) + atCurrent atRemaining entry atCheck atReset runProgram depth (atCheck depth) + (cfg entry input indices data extra) + (cfg (atCheck depth) input indices + (foldVisits (tupleStep rows repeats hn hbranch hrows δ input) depth indices data) extra), + tree.LeafBound B := by + let m := NormalizedSourceInput.clauseCount input + have positive : 0 < m := NormalizedSourceInput.clauseCount_positive input + let step := tupleStep (branch := branch) (n := n) (t := t) rows repeats hn hbranch hrows δ input + induction depth generalizing indices data with + | zero => + let run := leafInTime rows repeats hn hbranch hrows δ input indices data extra + refine ⟨.leaf (atCheck 0) (cfg entry input indices data extra) + (cfg (atCheck 0) input indices (foldVisits step 0 indices data) extra) + run.steps rfl rfl run.evals_in_steps, ?_⟩ + unfold MachineTupleOdometer.NestedCycle.LeafBound + exact run.steps_le_m.trans costs + | succ depth ih => + have hlt : depth < width := by omega + let accumulated := blockPrefix step depth indices + let schedule : MachineTupleOdometer.CycleSchedule Arena (Ambient (branch := branch) (n := n) (t := t) rows repeats δ) := + { currentSuffix := [] + remainingSuffix := [] + ambient := fun _ => (SignedTupleLayout.clean («width» := width) («Desc» := Desc) ()).1 + register := fun _ => none + base := fun remainder => nativeTapes input indices (accumulated (m - remainder) data) extra } + have children : ∀ r : Fin m, + ∃ tree : MachineTupleOdometer.NestedCycle m atCurrent atRemaining entry atCheck + atReset runProgram depth (atCheck depth) + (MachineTupleOdometer.bodyConfiguration (atCurrent depth) (atRemaining depth) + entry (m - 1) r.val schedule.currentSuffix schedule.remainingSuffix + schedule.ambient schedule.base) + (MachineTupleOdometer.checkConfiguration (atCurrent depth) (atRemaining depth) + (atCheck depth) (m - 1) r.val schedule.currentSuffix schedule.remainingSuffix + schedule.ambient schedule.register schedule.base), tree.LeafBound B := by + intro r + have hr : r.val ≤ m - 1 := by omega + let value : Fin m := ⟨m - 1 - r.val, by omega⟩ + have before : m - (r.val + 1) = value.val := by dsimp [value]; omega + have after : m - r.val = value.val + 1 := by dsimp [value]; omega + have childZero : ∀ i, i.val < depth → + (setCoordinate indices depth value i).val = 0 := by + intro i hi + simp only [setCoordinate, ite_eq_right (by omega : i.val ≠ depth)] + exact zero i (by omega) + have childCosts : CostsAtMost rows repeats hn hbranch hrows δ input extra B depth + (setCoordinate indices depth value) (accumulated (m - (r.val + 1)) data) := by + rw [before] + exact costs value + obtain ⟨child, bounded⟩ := ih (by omega) (setCoordinate indices depth value) + childZero (accumulated (m - (r.val + 1)) data) childCosts + have outputData : foldVisits step depth (setCoordinate indices depth value) + (accumulated (m - (r.val + 1)) data) = accumulated (m - r.val) data := by + rw [before, after] + exact (blockPrefix_succ step depth indices value data).symm + have childExists : + ∃ child : MachineTupleOdometer.NestedCycle m atCurrent atRemaining entry atCheck + atReset runProgram depth (atCheck depth) + (cfg entry input (setCoordinate indices depth value) + (accumulated (m - (r.val + 1)) data) extra) + (cfg (atCheck depth) input (setCoordinate indices depth value) + (foldVisits step depth (setCoordinate indices depth value) + (accumulated (m - (r.val + 1)) data)) extra), child.LeafBound B := + ⟨child, bounded⟩ + rw [outputData] at childExists + have childStart : + cfg entry input (setCoordinate indices depth value) + (accumulated (m - (r.val + 1)) data) extra = + MachineTupleOdometer.bodyConfiguration (atCurrent depth) (atRemaining depth) + entry (m - 1) r.val schedule.currentSuffix schedule.remainingSuffix + schedule.ambient schedule.base := by + dsimp only [MachineTupleOdometer.bodyConfiguration, schedule, configuration] + rw [digitTapes_at input indices _ extra depth r.val hlt hr] + rfl + have childFinish : + cfg (atCheck depth) input (setCoordinate indices depth value) + (accumulated (m - r.val) data) extra = + MachineTupleOdometer.checkConfiguration (atCurrent depth) (atRemaining depth) + (atCheck depth) (m - 1) r.val schedule.currentSuffix schedule.remainingSuffix + schedule.ambient schedule.register schedule.base := by + dsimp only [MachineTupleOdometer.checkConfiguration, schedule, configuration] + rw [digitTapes_at input indices _ extra depth r.val hlt hr] + rfl + rw [childStart, childFinish] at childExists + exact childExists + let chosen := fun r => Classical.choose (children r) + have chosenBound : ∀ r, (chosen r).LeafBound B := + fun r => Classical.choose_spec (children r) + have distinct : atCurrent depth ≠ atRemaining depth := by + simp [currentAt, remainingAt, hlt] + have checkInstruction : runProgram (atCheck depth) = + MachineTupleOdometer.increment (atCurrent depth) (atRemaining depth) entry (atReset depth) := by + simp [program, checkAt, currentAt, remainingAt, resetAt, hlt] + have resetInstruction : runProgram (atReset depth) = + MachineTupleOdometer.reset (atCurrent depth) (atRemaining depth) + (atReset depth) (atCheck (depth + 1)) := by + simp [program, resetAt, currentAt, remainingAt, hlt] + let tree := MachineTupleOdometer.NestedCycle.node depth (atCheck (depth + 1)) + positive distinct checkInstruction resetInstruction schedule chosen + have treeBound : tree.LeafBound B := by + simpa only [tree, MachineTupleOdometer.NestedCycle.LeafBound] using chosenBound + have unchanged : setCoordinate indices depth ⟨0, positive⟩ = indices := + setCoordinate_zero indices depth positive (fun i hi => zero i (by omega)) + have startTapes : MachineTupleOdometer.digitTapes (atCurrent depth) (atRemaining depth) + (nativeTapes input indices (accumulated (m - ((m - 1) + 1)) data) extra) + (m - 1 - (m - 1)) (m - 1) [] [] = nativeTapes input indices data extra := by + rw [digitTapes_at input indices _ extra depth (m - 1) hlt (Nat.le_refl _)] + have full : m - 1 + 1 = m := by omega + dsimp only [m] at full unchanged ⊢ + simp only [Nat.sub_self, unchanged, full, accumulated, blockPrefix_zero] + have finishTapes : MachineTupleOdometer.digitTapes (atCurrent depth) (atRemaining depth) + (nativeTapes input indices (accumulated (m - 0) data) extra) 0 (m - 1) [] [] = + nativeTapes input indices (foldVisits step (depth + 1) indices data) extra := by + have h := digitTapes_at input indices (accumulated m data) extra depth (m - 1) + hlt (Nat.le_refl _) + dsimp only [m] at h unchanged ⊢ + simpa only [Nat.sub_self, Nat.sub_zero, unchanged, accumulated, blockPrefix_all] using h + have nodeExists : + ∃ node : MachineTupleOdometer.NestedCycle m atCurrent atRemaining entry atCheck + atReset runProgram (depth + 1) (atCheck (depth + 1)) + (MachineTupleOdometer.bodyConfiguration (atCurrent depth) (atRemaining depth) + entry (m - 1) (m - 1) schedule.currentSuffix schedule.remainingSuffix + schedule.ambient schedule.base) + (MachineTupleOdometer.cycleExit (atCurrent depth) (atRemaining depth) + (atCheck (depth + 1)) (m - 1) schedule.currentSuffix schedule.remainingSuffix + schedule.ambient schedule.base), node.LeafBound B := ⟨tree, treeBound⟩ + have nodeStart : + MachineTupleOdometer.bodyConfiguration (atCurrent depth) (atRemaining depth) + entry (m - 1) (m - 1) schedule.currentSuffix schedule.remainingSuffix + schedule.ambient schedule.base = cfg entry input indices data extra := by + dsimp only [MachineTupleOdometer.bodyConfiguration, schedule, configuration] + rw [startTapes] + rfl + have nodeFinish : + MachineTupleOdometer.cycleExit (atCurrent depth) (atRemaining depth) + (atCheck (depth + 1)) (m - 1) schedule.currentSuffix schedule.remainingSuffix + schedule.ambient schedule.base = + cfg (atCheck (depth + 1)) input indices (foldVisits step (depth + 1) indices data) extra := by + dsimp only [MachineTupleOdometer.cycleExit, schedule, configuration] + rw [finishTapes] + rfl + rw [nodeStart, nodeFinish] at nodeExists + exact nodeExists + +def result (input : NormalizedSourceInput.Input) (data : SignedTupleBodyMachine.Data width) : + SignedTupleBodyMachine.Data width := + foldVisits (tupleStep rows repeats hn hbranch hrows δ input) width + (fun _ => ⟨0, NormalizedSourceInput.clauseCount_positive input⟩) data + +theorem result_count (input : NormalizedSourceInput.Input) + (data : SignedTupleBodyMachine.Data width) : + (result rows repeats hn hbranch hrows δ input data).count = + data.count + NormalizedSourceInput.clauseCount input ^ width * D := by + have countFold (xs : List (Fin width → Fin (NormalizedSourceInput.clauseCount input))) + (initial : SignedTupleBodyMachine.Data width) : + (xs.foldl (fun current indices => tupleStep rows repeats hn hbranch hrows δ input indices current) + initial).count = initial.count + xs.length * D := by + induction xs generalizing initial with + | nil => simp + | cons indices xs ih => + simp only [List.foldl_cons, ih, tupleStep_count, List.length_cons, Nat.add_mul, Nat.one_mul] + omega + unfold result foldVisits + rw [countFold, visits_all, MachineTupleOdometer.tupleOrder_length] + +def enumerateInTime (input : NormalizedSourceInput.Input) + (data : SignedTupleBodyMachine.Data width) (extra : Extra → List Bool) : + StateTransition.EvalsToInTime (Turing.TM2.step runProgram) + (cfg entry input (fun _ => ⟨0, NormalizedSourceInput.clauseCount_positive input⟩) data extra) + (some (cfg .exit input (fun _ => ⟨0, NormalizedSourceInput.clauseCount_positive input⟩) + (result rows repeats hn hbranch hrows δ input data) extra)) + ((maxLeafBudget rows repeats hn hbranch hrows δ input extra width + (fun _ => ⟨0, NormalizedSourceInput.clauseCount_positive input⟩) data + 2 * width) * + NormalizedSourceInput.clauseCount input ^ width) := by + let indices : Fin width → Fin (NormalizedSourceInput.clauseCount input) := + fun _ => ⟨0, NormalizedSourceInput.clauseCount_positive input⟩ + let B := maxLeafBudget rows repeats hn hbranch hrows δ input extra width indices data + let witness := existsTree rows repeats hn hbranch hrows δ input extra B width (Nat.le_refl _) + indices (fun _ _ => rfl) data + (costsAtMost_of_max rows repeats hn hbranch hrows δ input extra width indices data B (Nat.le_refl _)) + let tree := Classical.choose witness + have bounded := Classical.choose_spec witness + refine { steps := tree.steps, evals_in_steps := ?_, steps_le_m := ?_ } + · change (MachineComposition.advance (Turing.TM2.step runProgram))^[tree.steps] + (some (cfg entry input indices data extra)) = _ + simpa only [checkAt, Nat.lt_irrefl, ↓reduceDIte, result] using tree.trace + · exact tree.steps_le_power (NormalizedSourceInput.clauseCount_positive input) B bounded + +def enumerateInTimeOfBound (input : NormalizedSourceInput.Input) + (data : SignedTupleBodyMachine.Data width) (extra : Extra → List Bool) (B : Nat) + (costs : CostsAtMost rows repeats hn hbranch hrows δ input extra B width + (fun _ => ⟨0, NormalizedSourceInput.clauseCount_positive input⟩) data) : + StateTransition.EvalsToInTime (Turing.TM2.step runProgram) + (cfg entry input (fun _ => ⟨0, NormalizedSourceInput.clauseCount_positive input⟩) data extra) + (some (cfg .exit input (fun _ => ⟨0, NormalizedSourceInput.clauseCount_positive input⟩) + (result rows repeats hn hbranch hrows δ input data) extra)) + ((B + 2 * width) * NormalizedSourceInput.clauseCount input ^ width) := by + let witness := existsTree rows repeats hn hbranch hrows δ input extra B width (Nat.le_refl _) + (fun _ => ⟨0, NormalizedSourceInput.clauseCount_positive input⟩) (fun _ _ => rfl) data costs + let tree := Classical.choose witness + have bounded := Classical.choose_spec witness + refine { steps := tree.steps, evals_in_steps := ?_, steps_le_m := ?_ } + · change (MachineComposition.advance (Turing.TM2.step runProgram))^[tree.steps] + (some (cfg entry input (fun _ => ⟨0, NormalizedSourceInput.clauseCount_positive input⟩) data extra)) = _ + simpa only [checkAt, Nat.lt_irrefl, ↓reduceDIte, result] using tree.trace + · exact tree.steps_le_power (NormalizedSourceInput.clauseCount_positive input) B bounded + +end Native + +noncomputable section Semantics + +theorem foldl_chunks_eq_prefix {α β S : Type*} + (order : List β) (chunk : α → List β) (step : α → S → S) (pack : List β → S) + (hstep : ∀ (a : α) (earlier suffix : List β), + order = earlier ++ chunk a ++ suffix → + step a (pack earlier) = pack (earlier ++ chunk a)) + (xs : List α) (earlier suffix : List β) + (split : order = earlier ++ xs.flatMap chunk ++ suffix) : + xs.foldl (fun state a => step a state) (pack earlier) = + pack (earlier ++ xs.flatMap chunk) := by + induction xs generalizing earlier with + | nil => + simp only [List.foldl_nil, List.flatMap_nil, List.append_nil] + | cons a xs ih => + have currentSplit : order = earlier ++ chunk a ++ (xs.flatMap chunk ++ suffix) := by + simpa only [List.flatMap_cons, List.append_assoc] using split + rw [List.foldl_cons, hstep a earlier (xs.flatMap chunk ++ suffix) currentSplit] + have restSplit : order = (earlier ++ chunk a) ++ xs.flatMap chunk ++ suffix := by + simpa only [List.flatMap_cons, List.append_assoc] using split + simpa only [List.flatMap_cons, List.append_assoc] using + ih (earlier ++ chunk a) restSplit + +variable {branch : Nat → Nat} {n t : Nat} + (rows repeats : Nat → Nat) (hn : 0 < n) (hbranch : ∀ k < n, 0 < branch k) + (hrows : ∀ k, 0 < rows (k + 1)) (δ : ℚ) + (input : NormalizedSourceInput.Input) + +local notation "width" => TreeCanonical.locationCount branch n t +local notation "C" => CompletedSignedLaw.Completed (t := t) (NormalizedSourceInput.clauses input) + rows repeats hn hbranch hrows δ +local notation "order" => CompletedVisitOrder.completedOrder + (t := t) (NormalizedSourceInput.clauses input) rows repeats hn hbranch hrows δ +local notation "localOrder" => CompletedVisitOrder.localOrder + (t := t) (NormalizedSourceInput.clauses input) rows repeats hn hbranch hrows δ +local notation "pack" => SignedTupleSemantics.dataOfPrefix + (t := t) (NormalizedSourceInput.clauses input) rows repeats hn hbranch hrows δ + +theorem tupleStep_dataOfPrefix + (indices : Fin width → Fin (NormalizedSourceInput.clauseCount input)) + (earlier suffix : List C) (tail : List Bool) + (split : order = earlier ++ + localOrder (SourceQuestionOrder.tupleToQuestion (branch := branch) (n := n) (t := t) indices) ++ + suffix) : + ExactTargetOdometer.tupleStep rows repeats hn hbranch hrows δ input indices + (pack earlier tail) = + pack (earlier ++ localOrder + (SourceQuestionOrder.tupleToQuestion (branch := branch) (n := n) (t := t) indices)) tail := by + simpa only [ExactTargetOdometer.tupleStep, List.finRange, + SignedTupleSemantics.sourceIDs_tuple, SignedTupleSemantics.sourceVariables_tuple] using + SignedTupleSemantics.full_result_eq (t := t) + (NormalizedSourceInput.clauses input) rows repeats hn hbranch hrows δ + (SourceQuestionOrder.tupleToQuestion (branch := branch) (n := n) (t := t) indices) + earlier suffix tail split + +theorem fold_tupleSteps_dataOfPrefix + (xs : List (Fin width → Fin (NormalizedSourceInput.clauseCount input))) + (earlier suffix : List C) (tail : List Bool) + (split : order = earlier ++ xs.flatMap + (fun indices => localOrder + (SourceQuestionOrder.tupleToQuestion (branch := branch) (n := n) (t := t) indices)) ++ suffix) : + xs.foldl + (fun data indices => + ExactTargetOdometer.tupleStep rows repeats hn hbranch hrows δ input indices data) + (pack earlier tail) = + pack (earlier ++ xs.flatMap + (fun indices => localOrder + (SourceQuestionOrder.tupleToQuestion (branch := branch) (n := n) (t := t) indices))) tail := by + exact foldl_chunks_eq_prefix order + (fun indices : Fin width → Fin (NormalizedSourceInput.clauseCount input) => + localOrder (SourceQuestionOrder.tupleToQuestion (branch := branch) (n := n) (t := t) indices)) + (ExactTargetOdometer.tupleStep rows repeats hn hbranch hrows δ input) + (fun before => pack before tail) + (fun indices before after hsplit => + tupleStep_dataOfPrefix rows repeats hn hbranch hrows δ input indices before after tail hsplit) + xs earlier suffix split + +theorem result_dataOfPrefix (tail : List Bool) : + ExactTargetOdometer.result rows repeats hn hbranch hrows δ input (pack [] tail) = + pack order tail := by + let digits : Fin width → Fin (NormalizedSourceInput.clauseCount input) := + fun _ => ⟨0, NormalizedSourceInput.clauseCount_positive input⟩ + let xs := ExactTargetOdometer.visits width digits + have chronology : xs.flatMap + (fun indices => localOrder + (SourceQuestionOrder.tupleToQuestion (branch := branch) (n := n) (t := t) indices)) = order := + ExactTargetOdometer.visits_completedOrder (t := t) + (NormalizedSourceInput.clauses input) rows repeats hn hbranch hrows δ digits + have split : order = [] ++ xs.flatMap + (fun indices => localOrder + (SourceQuestionOrder.tupleToQuestion (branch := branch) (n := n) (t := t) indices)) ++ [] := by + simpa only [List.nil_append, List.append_nil] using chronology.symm + have folded := fold_tupleSteps_dataOfPrefix rows repeats hn hbranch hrows δ input + xs [] [] tail split + change xs.foldl + (fun data indices => + ExactTargetOdometer.tupleStep rows repeats hn hbranch hrows δ input indices data) + (pack [] tail) = pack order tail + simpa only [List.nil_append, chronology] using folded + +def targetInTime {Extra : Type} [DecidableEq Extra] (tail : List Bool) + (extra : Extra → List Bool) : + StateTransition.EvalsToInTime + (Turing.TM2.step (program (branch := branch) (n := n) (t := t) + (Extra := Extra) rows repeats hn hbranch hrows δ)) + (configuration rows repeats hn hbranch hrows δ + (body (branch := branch) (n := n) (t := t) (Extra := Extra) rows repeats hn hbranch hrows δ) + input (fun _ => ⟨0, NormalizedSourceInput.clauseCount_positive input⟩) (pack [] tail) extra) + (some (configuration rows repeats hn hbranch hrows δ .exit input + (fun _ => ⟨0, NormalizedSourceInput.clauseCount_positive input⟩) (pack order tail) extra)) + ((maxLeafBudget rows repeats hn hbranch hrows δ input extra width + (fun _ => ⟨0, NormalizedSourceInput.clauseCount_positive input⟩) (pack [] tail) + 2 * width) * + NormalizedSourceInput.clauseCount input ^ width) := by + simpa only [result_dataOfPrefix] using + enumerateInTime rows repeats hn hbranch hrows δ input (pack [] tail) extra + +end Semantics + +noncomputable section ChronologicalCosts + +theorem visits_split_at {width radix : Nat} (depth : Nat) + (indices : Fin width → Fin radix) (value : Fin radix) : + ExactTargetOdometer.visits (depth + 1) indices = + ((List.ofFn (fun a : Fin radix => a)).take value.val).flatMap + (fun a => ExactTargetOdometer.visits depth + (ExactTargetOdometer.setCoordinate indices depth a)) ++ + ExactTargetOdometer.visits depth + (ExactTargetOdometer.setCoordinate indices depth value) ++ + ((List.ofFn (fun a : Fin radix => a)).drop (value.val + 1)).flatMap + (fun a => ExactTargetOdometer.visits depth + (ExactTargetOdometer.setCoordinate indices depth a)) := by + let choices : List (Fin radix) := List.ofFn (fun a : Fin radix => a) + let lower : Fin radix → List (Fin width → Fin radix) := + fun a => ExactTargetOdometer.visits depth (ExactTargetOdometer.setCoordinate indices depth a) + have inside : value.val < choices.length := by + simpa only [choices, List.length_ofFn] using value.isLt + have selected : choices[value.val]'inside = value := by + simp only [choices, List.getElem_ofFn, Fin.eta] + have split : choices = choices.take value.val ++ choices.drop value.val := + (List.take_append_drop value.val choices).symm + rw [List.drop_eq_getElem_cons inside, selected] at split + change choices.flatMap lower = + (choices.take value.val).flatMap lower ++ lower value ++ + (choices.drop (value.val + 1)).flatMap lower + simpa only [List.flatMap_append, List.flatMap_cons, List.append_assoc] using + congrArg (fun xs : List (Fin radix) => xs.flatMap lower) split + +variable {branch : Nat → Nat} {n t : Nat} + (rows repeats : Nat → Nat) (hn : 0 < n) (hbranch : ∀ k < n, 0 < branch k) + (hrows : ∀ k, 0 < rows (k + 1)) (δ : ℚ) + (input : NormalizedSourceInput.Input) + +local notation "width" => TreeCanonical.locationCount branch n t +local notation "Digits" => Fin width → Fin (NormalizedSourceInput.clauseCount input) +local notation "C" => CompletedSignedLaw.Completed (t := t) (NormalizedSourceInput.clauses input) + rows repeats hn hbranch hrows δ +local notation "order" => CompletedVisitOrder.completedOrder + (t := t) (NormalizedSourceInput.clauses input) rows repeats hn hbranch hrows δ +local notation "localOrder" => CompletedVisitOrder.localOrder + (t := t) (NormalizedSourceInput.clauses input) rows repeats hn hbranch hrows δ +local notation "pack" => SignedTupleSemantics.dataOfPrefix + (t := t) (NormalizedSourceInput.clauses input) rows repeats hn hbranch hrows δ +local notation "step" => ExactTargetOdometer.tupleStep rows repeats hn hbranch hrows δ input + +variable {Extra : Type} [DecidableEq Extra] + +theorem costsAtMost_of_chronological (extra : Extra → List Bool) (B : Nat) (tail : List Bool) + (bounded : ∀ (indices : Digits) (before after : List C), + order = before ++ localOrder + (SourceQuestionOrder.tupleToQuestion (branch := branch) (n := n) (t := t) indices) ++ after → + ExactTargetOdometer.leafBudget rows repeats hn hbranch hrows δ input indices + (pack before tail) extra ≤ B) + (depth : Nat) (indices : Digits) (earlier suffix : List C) + (split : order = earlier ++ (ExactTargetOdometer.visits depth indices).flatMap + (fun tuple => localOrder + (SourceQuestionOrder.tupleToQuestion (branch := branch) (n := n) (t := t) tuple)) ++ suffix) : + ExactTargetOdometer.CostsAtMost rows repeats hn hbranch hrows δ input extra B + depth indices (pack earlier tail) := by + let chunk : Digits → List C := fun tuple => localOrder + (SourceQuestionOrder.tupleToQuestion (branch := branch) (n := n) (t := t) tuple) + change order = earlier ++ (ExactTargetOdometer.visits depth indices).flatMap chunk ++ suffix at split + induction depth generalizing indices earlier suffix with + | zero => + change ExactTargetOdometer.leafBudget rows repeats hn hbranch hrows δ input indices + (pack earlier tail) extra ≤ B + apply bounded indices earlier suffix + simpa only [ExactTargetOdometer.visits, List.flatMap_singleton, chunk] using split + | succ depth ih => + intro value + let beforeTuples : List Digits := + ((List.ofFn (fun a : Fin (NormalizedSourceInput.clauseCount input) => a)).take value.val).flatMap + (fun a => ExactTargetOdometer.visits depth + (ExactTargetOdometer.setCoordinate indices depth a)) + let afterTuples : List Digits := + ((List.ofFn (fun a : Fin (NormalizedSourceInput.clauseCount input) => a)).drop + (value.val + 1)).flatMap + (fun a => ExactTargetOdometer.visits depth + (ExactTargetOdometer.setCoordinate indices depth a)) + have decomposition : ExactTargetOdometer.visits (depth + 1) indices = + beforeTuples ++ ExactTargetOdometer.visits depth + (ExactTargetOdometer.setCoordinate indices depth value) ++ afterTuples := + visits_split_at depth indices value + have beforeSplit : order = earlier ++ beforeTuples.flatMap chunk ++ + ((ExactTargetOdometer.visits depth + (ExactTargetOdometer.setCoordinate indices depth value)).flatMap chunk ++ + afterTuples.flatMap chunk ++ suffix) := by + simpa only [decomposition, List.flatMap_append, List.append_assoc] using split + have prefixState : + ExactTargetOdometer.blockPrefix step depth indices value.val (pack earlier tail) = + pack (earlier ++ beforeTuples.flatMap chunk) tail := by + have folded := ExactTargetOdometer.fold_tupleSteps_dataOfPrefix + rows repeats hn hbranch hrows δ input beforeTuples earlier + ((ExactTargetOdometer.visits depth + (ExactTargetOdometer.setCoordinate indices depth value)).flatMap chunk ++ + afterTuples.flatMap chunk ++ suffix) tail beforeSplit + simpa only [beforeTuples, ExactTargetOdometer.blockPrefix, + ExactTargetOdometer.foldVisits, List.foldl_flatMap] using folded + rw [prefixState] + apply ih (ExactTargetOdometer.setCoordinate indices depth value) + (earlier ++ beforeTuples.flatMap chunk) (afterTuples.flatMap chunk ++ suffix) + simpa only [decomposition, List.flatMap_append, List.append_assoc] using split + +theorem costsAtMost_full (extra : Extra → List Bool) (B : Nat) (tail : List Bool) + (bounded : ∀ (indices : Digits) (before after : List C), + order = before ++ localOrder + (SourceQuestionOrder.tupleToQuestion (branch := branch) (n := n) (t := t) indices) ++ after → + ExactTargetOdometer.leafBudget rows repeats hn hbranch hrows δ input indices + (pack before tail) extra ≤ B) : + ExactTargetOdometer.CostsAtMost rows repeats hn hbranch hrows δ input extra B width + (fun _ => ⟨0, NormalizedSourceInput.clauseCount_positive input⟩) (pack [] tail) := by + apply costsAtMost_of_chronological rows repeats hn hbranch hrows δ input extra B tail bounded + width (fun _ => ⟨0, NormalizedSourceInput.clauseCount_positive input⟩) [] [] + simpa only [List.nil_append, List.append_nil] using + (ExactTargetOdometer.visits_completedOrder (t := t) + (NormalizedSourceInput.clauses input) rows repeats hn hbranch hrows δ + (fun _ => ⟨0, NormalizedSourceInput.clauseCount_positive input⟩)).symm + +local notation "q" => FinitePreliminaryCompletion.alphabet branch n t δ +local notation "D" => SignedMultiplicity.denominator branch n t rows repeats hn hbranch hrows q + +def timeBound (size : Nat) : Nat := + (SignedCostEnvelope.bodyCoeff width D + 2 * width) * + (size + 1) ^ (SignedCostEnvelope.degree width + width) + +def targetInTimePolynomial (tail : List Bool) (extra : Extra → List Bool) : + StateTransition.EvalsToInTime + (Turing.TM2.step (program (branch := branch) (n := n) (t := t) + (Extra := Extra) rows repeats hn hbranch hrows δ)) + (configuration rows repeats hn hbranch hrows δ + (body (branch := branch) (n := n) (t := t) (Extra := Extra) rows repeats hn hbranch hrows δ) + input (fun _ => ⟨0, NormalizedSourceInput.clauseCount_positive input⟩) (pack [] tail) extra) + (some (configuration rows repeats hn hbranch hrows δ .exit input + (fun _ => ⟨0, NormalizedSourceInput.clauseCount_positive input⟩) (pack order tail) extra)) + (timeBound (branch := branch) (n := n) (t := t) + rows repeats hn hbranch hrows δ (NormalizedSourceInput.bits input).length) := by + let B := SignedCostEnvelope.bodyCoeff width D * + ((NormalizedSourceInput.bits input).length + 1) ^ SignedCostEnvelope.degree width + have bounded : CostsAtMost rows repeats hn hbranch hrows δ input extra B width + (fun _ => ⟨0, NormalizedSourceInput.clauseCount_positive input⟩) (pack [] tail) := by + apply costsAtMost_full rows repeats hn hbranch hrows δ input extra B tail + intro indices before after split + simpa only [leafBudget] using SignedRuntimeBounds.bodyBudget_le_polynomial (t := t) + input rows repeats hn hbranch hrows δ indices (baseTapes input indices extra) + (baseTapes_input input indices extra) before after tail split + let run := enumerateInTimeOfBound rows repeats hn hbranch hrows δ input + (pack [] tail) extra B bounded + refine { steps := run.steps, evals_in_steps := ?_, steps_le_m := ?_ } + · simpa only [result_dataOfPrefix] using run.evals_in_steps + · exact run.steps_le_m.trans + (SignedRuntimeBounds.outerBudget_le_polynomial (t := t) input rows repeats hn hbranch hrows δ) + +end ChronologicalCosts +end PerfectCompleteness.ExactTargetOdometer + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/ExactTargetOnlineEncoding.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/ExactTargetOnlineEncoding.lean new file mode 100644 index 0000000000000000000000000000000000000000..6b9e173bc383646c53bb8ab2574a006e36f71ebd --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/ExactTargetOnlineEncoding.lean @@ -0,0 +1,102 @@ +import OAI.Computability.PerfectCompleteness.Machines.CanonicalKeyShapeMachineLemmas +import OAI.Computability.PerfectCompleteness.Reduction.ExactPreliminaryTarget + +namespace OAI + +section + +namespace PerfectCompleteness.ExactTargetOnlineEncoding + +open UniqueGamesTheorem.Foundations.Complexity +open scoped Classical + +noncomputable section + +private 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] + +variable {branch : Nat → Nat} {n t v m : Nat} [NeZero m] + (clauses : Fin m → SourceClause.NormalizedClause v) (rows repeats : Nat → Nat) + (hn : 0 < n) (hbranch : ∀ k < n, 0 < branch k) + (hrows : ∀ k, 0 < rows (k + 1)) (δ : ℚ) + +local notation "F" => FinitePreliminaryCompletion.blockFamily clauses branch n t rows repeats +local notation "C" => CompletedSignedLaw.Completed (t := t) clauses rows repeats hn hbranch hrows δ +local notation "order" => CompletedVisitOrder.completedOrder + (t := t) clauses rows repeats hn hbranch hrows δ +local notation "target" => ExactPreliminaryTarget.construct + (t := t) clauses rows repeats hn hbranch hrows δ +local notation "edge" => ExactPreliminaryTarget.entry + (t := t) clauses rows repeats hn hbranch hrows δ + +def leftKeys (occurrences : List C) := occurrences.map (fun e => CanonicalGame.leftKey F e.1) + +def rightKeys (occurrences : List C) := occurrences.map (fun e => CanonicalGame.rightKey F e.1) + +theorem left_online (earlier suffix : List C) (e : C) (split : order = earlier ++ e :: suffix) : + CanonicalOnlineNames.onlineID (leftKeys (t := t) clauses rows repeats hn hbranch hrows δ earlier) + (CanonicalGame.leftKey F e.1) = (edge e).left.val := by + change _ = (BinaryNameSearch.payloads (CanonicalVertexNames.tokens + (((order).map Sigma.fst).map (CanonicalGame.leftKey F)))).idxOf + (CanonicalVertexNames.payload (CanonicalGame.leftKey F e.1)) + rw [List.map_map, split, List.map_append, List.map_cons] + exact CanonicalOnlineNames.onlineID_eq_global _ _ _ + +theorem right_online (earlier suffix : List C) (e : C) (split : order = earlier ++ e :: suffix) : + CanonicalOnlineNames.onlineID (rightKeys (t := t) clauses rows repeats hn hbranch hrows δ earlier) + (CanonicalGame.rightKey F e.1) = (edge e).right.val := by + change _ = (BinaryNameSearch.payloads (CanonicalVertexNames.tokens + (((order).map Sigma.fst).map (CanonicalGame.rightKey F)))).idxOf + (CanonicalVertexNames.payload (CanonicalGame.rightKey F e.1)) + rw [List.map_map, split, List.map_append, List.map_cons] + exact CanonicalOnlineNames.onlineID_eq_global _ _ _ + +def onlineWords (earlier : List C) (e : C) : List Nat := + [CanonicalOnlineNames.onlineID + (leftKeys (t := t) clauses rows repeats hn hbranch hrows δ earlier) + (CanonicalGame.leftKey F e.1), + CanonicalOnlineNames.onlineID + (rightKeys (t := t) clauses rows repeats hn hbranch hrows δ earlier) + (CanonicalGame.rightKey F e.1)] ++ Encoding.tableWords (edge e).projection + +theorem onlineWords_eq (earlier suffix : List C) (e : C) + (split : order = earlier ++ e :: suffix) : + onlineWords (t := t) clauses rows repeats hn hbranch hrows δ earlier e = + Encoding.edgeWords (edge e) := by + unfold onlineWords Encoding.edgeWords + rw [left_online (t := t) clauses rows repeats hn hbranch hrows δ earlier suffix e split, + right_online (t := t) clauses rows repeats hn hbranch hrows δ earlier suffix e split] + +theorem reverse_edge_fields {l r q : Nat} (e : Edge l r q) (tail : List Bool) : + (encodeWords (Encoding.tableWords e.projection)).reverse ++ + ((encodeWord e.right.val).reverse ++ ((encodeWord e.left.val).reverse ++ tail)) = + (encodeWords (Encoding.edgeWords e)).reverse ++ tail := by + simp only [Encoding.edgeWords, encodeWords_append, encodeWords, + List.append_nil, List.reverse_append, List.append_assoc] + +theorem target_gameBits : + Encoding.gameBits target = + encodeWords [(order).length, (order).length, + FinitePreliminaryCompletion.alphabet branch n t δ, (order).length] ++ + (order).flatMap (fun e => encodeWords (Encoding.edgeWords (edge e))) := by + change encodeWords + ([(CompletedVisitOrder.rawOrder (t := t) clauses rows repeats hn hbranch hrows δ).length, + (CompletedVisitOrder.rawOrder (t := t) clauses rows repeats hn hbranch hrows δ).length, + FinitePreliminaryCompletion.alphabet branch n t δ, ((order).map edge).length] ++ + ((order).map edge).flatMap Encoding.edgeWords) = _ + rw [encodeWords_append, encodeWords_flatMap] + apply congrArg₂ List.append + · apply congrArg encodeWords + simp only [List.length_map] + simp only [CompletedVisitOrder.rawOrder, List.length_map] + · simp only [List.flatMap_map] + +end +end PerfectCompleteness.ExactTargetOnlineEncoding + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/FiniteBlockMachineLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/FiniteBlockMachineLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..a13b1c28315969010b3bee2107f77044ca5ad2ac --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/FiniteBlockMachineLemmas.lean @@ -0,0 +1,684 @@ +import Mathlib.Data.Fintype.BigOperators +import Mathlib.Data.Fintype.Powerset +import Mathlib.Data.List.OfFn +import OAI.Computability.PerfectCompleteness.Foundations.CanonicalKeys +import OAI.Computability.UniqueGames.Machines.MachineCompositionLemmas +import OAI.Computability.UniqueGames.Machines.MachineFiniteTable +import OAI.Computability.UniqueGames.Machines.MachineSubroutineLemmas + +namespace OAI + + +namespace PerfectCompleteness.FiniteBlockMachine + + +open Turing +open UniqueGamesTheorem.Foundations.Complexity +open MachineFixedBlockMap +open scoped Classical + +noncomputable section + +variable {α β : Type} {N M : Nat} + +def encode (enum : α ≃ Fin N) (a : α) : Buffer N := + fun i => decide (enum a = i) + +theorem encode_injective (enum : α ≃ Fin N) : Function.Injective (encode enum) := by + intro a b h + have ha : encode enum a (enum a) = true := by simp [encode] + have hb : encode enum b (enum a) = true := by rw [← h]; exact ha + exact enum.injective (of_decide_eq_true hb).symm + +def decode (enum : α ≃ Fin N) (fallback : α) (bits : Buffer N) : α := + if h : ∃ a, encode enum a = bits then Classical.choose h else fallback + +@[simp] theorem decode_encode (enum : α ≃ Fin N) (fallback a : α) : + decode enum fallback (encode enum a) = a := by + have h : ∃ b, encode enum b = encode enum a := ⟨a, rfl⟩ + simp only [decode, dite_eq_left h] + exact encode_injective enum (Classical.choose_spec h) + +def word (enum : α ≃ Fin N) (a : α) : List Bool := List.ofFn (encode enum a) + +@[simp] theorem word_length (enum : α ≃ Fin N) (a : α) : (word enum a).length = N := + List.length_ofFn + +def transform (input : α ≃ Fin N) (output : β ≃ Fin M) (fallback : α) + (f : α → β) : Buffer N → Buffer M := + fun bits => encode output (f (decode input fallback bits)) + +@[simp] theorem transform_encode (input : α ≃ Fin N) (output : β ≃ Fin M) + (fallback a : α) (f : α → β) : + transform input output fallback f (encode input a) = encode output (f a) := by + rw [transform, decode_encode] + +def statement {K Λ A : Type} (src dst : K) (exit : Option Λ) + (input : α ≃ Fin N) (output : β ≃ Fin M) (fallback : α) (f : α → β) : + TM2.Stmt (fun _ : K => Bool) Λ (A × Buffer N) := + blockMapAt src dst (transform input output fallback f) exit + +theorem statement_trace {K Λ A : Type} [DecidableEq K] + (src dst : K) (exit : Option Λ) (hne : src ≠ dst) + (input : α ≃ Fin N) (output : β ≃ Fin M) (fallback a : α) (f : α → β) + (suffix : List Bool) (state : A × Buffer N) (tapes : K → List Bool) + (hinput : tapes src = word input a ++ suffix) : + TM2.stepAux (statement src dst exit input output fallback f) state tapes = + { l := exit, var := (state.1, emptyBuffer N), + stk := Function.update (Function.update tapes src suffix) dst + (word output (f a) ++ tapes dst) } := by + simpa only [statement, transform_encode, word] using + stepAux_blockMapAt src dst (transform input output fallback f) exit hne + (encode input a) suffix state tapes hinput + +theorem statement_pushBound {K Λ A : Type} (src dst : K) (exit : Option Λ) + (input : α ≃ Fin N) (output : β ≃ Fin M) (fallback : α) (f : α → β) : + Runtime.statementPushBound + (statement (A := A) src dst exit input output fallback f) = M := + statementPushBound_blockMapAt src dst (transform input output fallback f) exit + +def machine (input : α ≃ Fin N) (output : β ≃ Fin M) (fallback : α) + (f : α → β) : FinTM2 := + MachineFixedBlockMap.machine (transform input output fallback f) + +theorem machine_step (input : α ≃ Fin N) (output : β ≃ Fin M) + (fallback a : α) (f : α → β) : + (machine input output fallback f).step + (initList (machine input output fallback f) (word input a)) = + some (haltList (machine input output fallback f) (word output (f a))) := by + let tapes : Bool → List Bool := fun k => if k = false then word input a else [] + have hinput : tapes false = List.ofFn (encode input a) ++ [] := by simp [tapes, word] + have hstep := stepAux_blockMapAt (σ := Unit) (Λ := Unit) false true + (transform input output fallback f) none (by decide) + (encode input a) [] ((), emptyBuffer N) tapes hinput + have htapes : Function.update (Function.update tapes false []) true + (List.ofFn (transform input output fallback f (encode input a)) ++ tapes true) = + fun k : Bool => if k = true then word output (f a) else [] := by + funext k + cases k <;> simp [tapes, transform_encode, word] + change some (TM2.stepAux + (blockMapAt false true (transform input output fallback f) none) + ((), emptyBuffer N) tapes) = + some { + l := none + var := ((), emptyBuffer N) + stk := fun k : Bool => if k = true then word output (f a) else [] + } + erw [hstep, htapes] + rfl + +def computation (input : α ≃ Fin N) (output : β ≃ Fin M) (fallback : α) + (f : α → β) : TM2ComputableInPolyTime (word input) (word output) f where + tm := machine input output fallback f + inputAlphabet := Equiv.refl Bool + outputAlphabet := Equiv.refl Bool + time := 1 + outputsFun a := { + steps := 1 + evals_in_steps := by + change (machine input output fallback f).step + (initList (machine input output fallback f) ((word input a).map id)) = + some (haltList (machine input output fallback f) ((word output (f a)).map id)) + erw [List.map_id, List.map_id] + exact machine_step input output fallback a f + steps_le_m := by simp + } + +theorem machine_pushBound (input : α ≃ Fin N) (output : β ≃ Fin M) + (fallback : α) (f : α → β) : + Runtime.statementPushBound ((machine input output fallback f).m ()) = M := + MachineFixedBlockMap.machine_statementPushBound (transform input output fallback f) + +theorem machine_workAlphabet_finite (input : α ≃ Fin N) (output : β ≃ Fin M) + (fallback : α) (f : α → β) (k : (machine input output fallback f).K) : + Finite ((machine input output fallback f).Γ k) := by + change Finite Bool + infer_instance + +end +end PerfectCompleteness.FiniteBlockMachine + + +namespace PerfectCompleteness.FiniteReadMachine + + +open Turing +open UniqueGamesTheorem.Foundations.Complexity +open MachineFixedBlockMap +open scoped Classical + +noncomputable section + +variable {α A K Λ : Type} {N : Nat} + +abbrev State (A : Type) (N : Nat) := A × Buffer N + +theorem state_finite [Finite A] : Finite (State A N) := by + infer_instance + +def saveFinish (exit : Option Λ) (input : α ≃ Fin N) (fallback : α) + (save : A → α → A) : TM2.Stmt (fun _ : K => Bool) Λ (State A N) := + .load (fun state => + (save state.1 (FiniteBlockMachine.decode input fallback state.2), emptyBuffer N)) + (finishAt exit) + +theorem saveFinish_pushBound (exit : Option Λ) (input : α ≃ Fin N) + (fallback : α) (save : A → α → A) : + Runtime.statementPushBound (saveFinish (K := K) exit input fallback save) = 0 := by + cases exit <;> rfl + +theorem stepAux_saveFinish [DecidableEq K] (exit : Option Λ) + (input : α ≃ Fin N) (fallback a : α) (save : A → α → A) + (ambient : A) (tapes : K → List Bool) : + TM2.stepAux (saveFinish exit input fallback save) + (ambient, FiniteBlockMachine.encode input a) tapes = { + l := exit + var := (save ambient a, emptyBuffer N) + stk := tapes + } := by + cases exit <;> + simp only [saveFinish, TM2.stepAux, finishAt, FiniteBlockMachine.decode_encode] + +def statement (src : K) (exit : Option Λ) (input : α ≃ Fin N) + (fallback : α) (save : A → α → A) : + TM2.Stmt (fun _ : K => Bool) Λ (State A N) := + readSlots src (List.ofFn id) (saveFinish exit input fallback save) + +theorem statement_trace [DecidableEq K] (src : K) (exit : Option Λ) + (input : α ≃ Fin N) (fallback a : α) (save : A → α → A) + (suffix : List Bool) (state : State A N) (tapes : K → List Bool) + (hinput : tapes src = FiniteBlockMachine.word input a ++ suffix) : + TM2.stepAux (statement src exit input fallback save) state tapes = { + l := exit + var := (save state.1 a, emptyBuffer N) + stk := Function.update tapes src suffix + } := by + have hin : tapes src = List.ofFn (FiniteBlockMachine.encode input a) ++ suffix := hinput + unfold statement + rw [stepAux_readAll src _ state (FiniteBlockMachine.encode input a) tapes suffix hin] + exact stepAux_saveFinish exit input fallback a save state.1 _ + +theorem statement_pushBound (src : K) (exit : Option Λ) + (input : α ≃ Fin N) (fallback : α) (save : A → α → A) : + Runtime.statementPushBound (statement src exit input fallback save) = 0 := by + rw [statement, statementPushBound_readSlots, saveFinish_pushBound] + +theorem step [DecidableEq K] (src : K) (exit : Option Λ) + (input : α ≃ Fin N) (fallback a : α) (save : A → α → A) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State A N)) + (entry : Λ) (atEntry : program entry = statement src exit input fallback save) + (suffix : List Bool) (state : State A N) (tapes : K → List Bool) + (hinput : tapes src = FiniteBlockMachine.word input a ++ suffix) : + TM2.step program { l := some entry, var := state, stk := tapes } = + some { + l := exit + var := (save state.1 a, emptyBuffer N) + stk := Function.update tapes src suffix + } := by + change some (TM2.stepAux (program entry) state tapes) = _ + rw [atEntry, statement_trace src exit input fallback a save suffix state tapes hinput] + +def inTime [DecidableEq K] (src : K) (exit : Option Λ) + (input : α ≃ Fin N) (fallback a : α) (save : A → α → A) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State A N)) + (entry : Λ) (atEntry : program entry = statement src exit input fallback save) + (suffix : List Bool) (state : State A N) (tapes : K → List Bool) + (hinput : tapes src = FiniteBlockMachine.word input a ++ suffix) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some entry, state, tapes⟩ + (some ⟨exit, (save state.1 a, emptyBuffer N), Function.update tapes src suffix⟩) 1 where + steps := 1 + evals_in_steps := step src exit input fallback a save program entry atEntry + suffix state tapes hinput + steps_le_m := Nat.le_refl 1 + +end +end PerfectCompleteness.FiniteReadMachine + + +namespace PerfectCompleteness.FiniteWordMachine + + +open Turing +open UniqueGamesTheorem.Foundations.Complexity +open MachineFixedBlockMap +open scoped Classical + +noncomputable section + +variable {α : Type} {N : Nat} + +abbrev State (N : Nat) := Unit × Buffer N + +def keys (N : Nat) : List (State N) := (Finset.univ : Finset (State N)).toList + +theorem keys_complete (N : Nat) (state : State N) : state ∈ keys N := by + simp [keys] + +def literalTable (input : α ≃ Fin N) (fallback : α) (emit : α → List Bool) + (state : State N) : List Bool := + emit (FiniteBlockMachine.decode input fallback state.2) + +def cleanFinish {K Λ : Type} (exit : Option Λ) : + TM2.Stmt (fun _ : K => Bool) Λ (State N) := + .load (fun _ => ((), emptyBuffer N)) (finishAt exit) + +theorem cleanFinish_pushBound {K Λ : Type} (exit : Option Λ) : + Runtime.statementPushBound (cleanFinish (K := K) (N := N) exit) = 0 := by + cases exit <;> rfl + +theorem stepAux_cleanFinish {K Λ : Type} [DecidableEq K] + (exit : Option Λ) (state : State N) (tapes : K → List Bool) : + TM2.stepAux (cleanFinish exit) state tapes = { + l := exit + var := ((), emptyBuffer N) + stk := tapes + } := by + cases exit <;> rfl + +def statement {K Λ : Type} (src dst : K) (exit : Option Λ) + (input : α ≃ Fin N) (fallback : α) (emit : α → List Bool) : + TM2.Stmt (fun _ : K => Bool) Λ (State N) := + readSlots src (List.ofFn id) + (MachineFiniteTable.emit dst (literalTable input fallback emit) (keys N) + (cleanFinish exit)) + +theorem statement_trace {K Λ : Type} [DecidableEq K] + (src dst : K) (exit : Option Λ) (hne : src ≠ dst) + (input : α ≃ Fin N) (fallback a : α) (emit : α → List Bool) + (suffix : List Bool) (state : State N) (tapes : K → List Bool) + (hinput : tapes src = FiniteBlockMachine.word input a ++ suffix) : + TM2.stepAux (statement src dst exit input fallback emit) state tapes = { + l := exit + var := ((), emptyBuffer N) + stk := Function.update (Function.update tapes src suffix) dst (emit a ++ tapes dst) + } := by + have hin : tapes src = List.ofFn (FiniteBlockMachine.encode input a) ++ suffix := hinput + unfold statement + rw [stepAux_readAll src _ state (FiniteBlockMachine.encode input a) tapes suffix hin] + rw [MachineFiniteTable.stepAux_emit (Γ := fun _ : K => Bool) (Λ := Λ) (σ := State N) + dst (literalTable input fallback emit) (keys N) (keys_complete N) + (cleanFinish (K := K) (N := N) exit) + (state.1, FiniteBlockMachine.encode input a) (Function.update tapes src suffix)] + rw [stepAux_cleanFinish] + simp only [literalTable, FiniteBlockMachine.decode_encode, + Function.update_of_ne (Ne.symm hne)] + +theorem statement_pushBound {K Λ : Type} (src dst : K) (exit : Option Λ) + (input : α ≃ Fin N) (fallback : α) (emit : α → List Bool) : + Runtime.statementPushBound (statement src dst exit input fallback emit) ≤ + MachineFiniteTable.tableBound (Γ := fun _ : K => Bool) + dst (literalTable input fallback emit) (keys N) := by + have h := MachineFiniteTable.emit_push_bound (Γ := fun _ : K => Bool) + dst (literalTable input fallback emit) (keys N) + (cleanFinish (K := K) (Λ := Λ) (N := N) exit) + simpa only [statement, statementPushBound_readSlots, cleanFinish_pushBound, + Nat.add_zero] using h + +def machine (input : α ≃ Fin N) (fallback : α) (emit : α → List Bool) : FinTM2 where + K := Bool + k₀ := false + k₁ := true + Γ _ := Bool + Λ := Unit + main := () + σ := State N + initialState := ((), emptyBuffer N) + m _ := statement false true none input fallback emit + +theorem machine_step (input : α ≃ Fin N) (fallback a : α) (emit : α → List Bool) : + (machine input fallback emit).step + (initList (machine input fallback emit) (FiniteBlockMachine.word input a)) = + some (haltList (machine input fallback emit) (emit a)) := by + let tapes : Bool → List Bool := + fun k => if k = false then FiniteBlockMachine.word input a else [] + have hinput : tapes false = FiniteBlockMachine.word input a ++ [] := by simp [tapes] + have hstep := statement_trace (Λ := Unit) false true none (by decide) + input fallback a emit [] ((), emptyBuffer N) tapes hinput + have htapes : Function.update (Function.update tapes false []) true (emit a ++ tapes true) = + fun k : Bool => if k = true then emit a else [] := by + funext k + cases k <;> simp [tapes] + change some (TM2.stepAux + (statement false true none input fallback emit) ((), emptyBuffer N) tapes) = + some { + l := none + var := ((), emptyBuffer N) + stk := fun k : Bool => if k = true then emit a else [] + } + erw [hstep, htapes] + rfl + +def computation (input : α ≃ Fin N) (fallback : α) (emit : α → List Bool) : + TM2ComputableInPolyTime (FiniteBlockMachine.word input) (id : List Bool → List Bool) emit where + tm := machine input fallback emit + inputAlphabet := Equiv.refl Bool + outputAlphabet := Equiv.refl Bool + time := 1 + outputsFun a := { + steps := 1 + evals_in_steps := by + change (machine input fallback emit).step + (initList (machine input fallback emit) ((FiniteBlockMachine.word input a).map id)) = + some (haltList (machine input fallback emit) ((emit a).map id)) + erw [List.map_id, List.map_id] + exact machine_step input fallback a emit + steps_le_m := by simp + } + +theorem machine_pushBound (input : α ≃ Fin N) (fallback : α) (emit : α → List Bool) : + Runtime.statementPushBound ((machine input fallback emit).m ()) ≤ + MachineFiniteTable.tableBound (Γ := fun _ : Bool => Bool) + true (literalTable input fallback emit) (keys N) := + statement_pushBound (Λ := Unit) false true none input fallback emit + +theorem machine_workAlphabet_finite (input : α ≃ Fin N) (fallback : α) + (emit : α → List Bool) (k : (machine input fallback emit).K) : + Finite ((machine input fallback emit).Γ k) := by + change Finite Bool + infer_instance + +end +end PerfectCompleteness.FiniteWordMachine + + +namespace PerfectCompleteness.KeyMetadataEncoding + +open ClauseSupport + +variable {n : Nat} + +def bitWord (b : Bool) : Nat := if b then 1 else 0 + +@[simp] theorem bitWord_eq_iff (a b : Bool) : bitWord a = bitWord b ↔ a = b := by + cases a <;> cases b <;> decide + +theorem bitWord_le (b : Bool) : bitWord b ≤ 1 := by + cases b <;> decide + +def entryID : SlotKey → Nat + | .dropped => 0 + | .bit variableID => variableID + | .full occurrence _ => occurrence + +def entryWords (entry : Fin n × SlotKey) : List Nat := + entry.1.val :: match entry.2 with + | .dropped => [0, 0, 0, 0, 0] + | .bit variableID => [1, variableID, 0, 0, 0] + | .full occurrence signs => + [2, occurrence, bitWord signs.1, bitWord signs.2.1, bitWord signs.2.2] + +@[simp] theorem entryWords_length (entry : Fin n × SlotKey) : + (entryWords entry).length = 6 := by + rcases entry with ⟨position, key⟩ + cases key <;> rfl + +theorem entryWords_injective (n : Nat) : + Function.Injective (entryWords (n := n)) := by + rintro ⟨i, a⟩ ⟨j, b⟩ h + have hij : i = j := Fin.ext (List.cons.inj h).1 + subst j + apply congrArg (Prod.mk i) + cases a <;> cases b <;> simp_all [entryWords, Prod.ext_iff] + +def metadataWords (entries : List (Fin n × SlotKey)) : List Nat := + entries.flatMap entryWords + +@[simp] theorem metadataWords_nil : metadataWords ([] : List (Fin n × SlotKey)) = [] := rfl + +@[simp] theorem metadataWords_cons (entry : Fin n × SlotKey) + (entries : List (Fin n × SlotKey)) : + metadataWords (entry :: entries) = entryWords entry ++ metadataWords entries := rfl + +@[simp] theorem metadataWords_length (entries : List (Fin n × SlotKey)) : + (metadataWords entries).length = 6 * entries.length := by + induction entries with + | nil => rfl + | cons entry entries ih => + rw [metadataWords_cons, List.length_append, entryWords_length, ih, + List.length_cons, Nat.mul_add, Nat.mul_one] + omega + +theorem metadataWords_injective (n : Nat) : + Function.Injective (metadataWords (n := n)) := by + intro entries + induction entries with + | nil => + intro other h + have hlength := congrArg List.length h + simp only [metadataWords_length, List.length_nil] at hlength + have hz : other.length = 0 := by omega + cases other with + | nil => rfl + | cons entry entries => simp at hz + | cons entry entries ih => + intro other h + cases other with + | nil => + have hlength := congrArg List.length h + simp only [metadataWords_length, List.length_cons, List.length_nil] at hlength + omega + | cons next rest => + have hblocks : entryWords entry ++ metadataWords entries = + entryWords next ++ metadataWords rest := h + obtain ⟨hhead, htail⟩ := List.append_inj hblocks + ((entryWords_length entry).trans (entryWords_length next).symm) + exact congrArg₂ List.cons (entryWords_injective n hhead) (ih htail) + +theorem entryWords_le (entry : Fin n × SlotKey) (M : Nat) + (hID : entryID entry.2 ≤ M) : + ∀ word ∈ entryWords entry, word ≤ max n (max M 2) := by + rcases entry with ⟨position, key⟩ + have hn : n ≤ max n (max M 2) := le_max_left _ _ + have hM : M ≤ max n (max M 2) := (le_max_left M 2).trans (le_max_right n _) + have htwo : 2 ≤ max n (max M 2) := (le_max_right M 2).trans (le_max_right n _) + have hposition := position.isLt + intro word hw + cases key with + | dropped => + simp only [entryWords, List.mem_cons, List.not_mem_nil, or_false] at hw + rcases hw with rfl | rfl | rfl | rfl | rfl | rfl <;> omega + | bit variableID => + change variableID ≤ M at hID + simp only [entryWords, List.mem_cons, List.not_mem_nil, or_false] at hw + rcases hw with rfl | rfl | rfl | rfl | rfl | rfl <;> omega + | full occurrence signs => + change occurrence ≤ M at hID + have hs₀ := bitWord_le signs.1 + have hs₁ := bitWord_le signs.2.1 + have hs₂ := bitWord_le signs.2.2 + simp only [entryWords, List.mem_cons, List.not_mem_nil, or_false] at hw + rcases hw with rfl | rfl | rfl | rfl | rfl | rfl <;> omega + +theorem metadataWords_le (entries : List (Fin n × SlotKey)) (M : Nat) + (hIDs : ∀ entry ∈ entries, entryID entry.2 ≤ M) : + ∀ word ∈ metadataWords entries, word ≤ max n (max M 2) := by + intro word hw + obtain ⟨entry, hentry, hword⟩ := List.mem_flatMap.mp hw + exact entryWords_le entry M (hIDs entry hentry) word hword + +end PerfectCompleteness.KeyMetadataEncoding + + +namespace PerfectCompleteness.CanonicalKeyEncoding + +open ClauseSupport CanonicalKeys +open UniqueGamesTheorem.Foundations.Complexity +open scoped Classical + +noncomputable section + +def reducedValueEquiv : ReducedValue ≃ Option (Bool ⊕ SourceClause.Triple) where + toFun + | .dropped => none + | .bit b => some (.inl b) + | .full triple => some (.inr triple) + invFun + | none => .dropped + | some (.inl b) => .bit b + | some (.inr triple) => .full triple + left_inv value := by cases value <;> rfl + right_inv value := by + cases value with + | none => rfl + | some value => cases value <;> rfl + +local instance : Fintype ReducedValue := Fintype.ofEquiv _ reducedValueEquiv.symm + +theorem reducedValue_card : Fintype.card ReducedValue = 11 := by + rw [Fintype.card_congr reducedValueEquiv] + simp [SourceClause.Triple] + +abbrev Assignment (n : Nat) := Fin n → ReducedValue + +def partitionWidth (n : Nat) : Nat := Fintype.card (Set (Assignment n)) + +theorem partitionWidth_eq (n : Nat) : partitionWidth n = 2 ^ (11 ^ n) := by + simp only [partitionWidth, Fintype.card_set, Assignment, Fintype.card_fun, + reducedValue_card, Fintype.card_fin] + +def partEnum (n : Nat) : Set (Assignment n) ≃ Fin (partitionWidth n) := + Fintype.equivFin _ + +def partitionMask {n : Nat} (partition : Set (Set (Assignment n))) : + Fin (partitionWidth n) → Bool := + fun i => decide ((partEnum n).symm i ∈ partition) + +def partitionOfMask {n : Nat} (mask : Fin (partitionWidth n) → Bool) : + Set (Set (Assignment n)) := {part | mask (partEnum n part) = true} + +@[simp] theorem partitionOfMask_partitionMask {n : Nat} + (partition : Set (Set (Assignment n))) : + partitionOfMask (partitionMask partition) = partition := by + ext part + simp [partitionOfMask, partitionMask] + +theorem partitionMask_injective (n : Nat) : Function.Injective (partitionMask (n := n)) := by + intro a b h + have hdecoded := congrArg partitionOfMask h + simpa only [partitionOfMask_partitionMask] using hdecoded + +def boolWord (b : Bool) : Nat := if b then 1 else 0 + +theorem boolWord_injective : Function.Injective boolWord := by + intro a b h + cases a <;> cases b <;> simp_all [boolWord] + +theorem boolWord_le_one (b : Bool) : boolWord b ≤ 1 := by + cases b <;> decide + +def partitionWords {n : Nat} (partition : Set (Set (Assignment n))) : List Nat := + List.ofFn (fun i => boolWord (partitionMask partition i)) + +@[simp] theorem partitionWords_length {n : Nat} (partition : Set (Set (Assignment n))) : + (partitionWords partition).length = partitionWidth n := List.length_ofFn + +theorem partitionWords_injective (n : Nat) : + Function.Injective (partitionWords (n := n)) := by + intro a b h + apply partitionMask_injective n + have hfun := List.ofFn_injective h + funext i + exact boolWord_injective (congrFun hfun i) + +def sideWord : Side → Nat + | .left => 0 + | .right => 1 + +theorem sideWord_injective : Function.Injective sideWord := by + intro a b h + cases a <;> cases b <;> simp_all [sideWord] + +def words {n : Nat} (key : Key n) : List Nat := + sideWord key.side :: + (partitionWords key.partition ++ KeyMetadataEncoding.metadataWords key.retained) + +def bits {n : Nat} (key : Key n) : List Bool := encodeWords (words key) + +theorem words_length {n : Nat} (key : Key n) : + (words key).length = 1 + partitionWidth n + 6 * key.retained.length := by + simp only [words, List.length_cons, List.length_append, partitionWords_length, + KeyMetadataEncoding.metadataWords_length] + omega + +theorem bits_length_le {n : Nat} (key : Key n) (bound : Nat) + (hIDs : ∀ entry ∈ key.retained, KeyMetadataEncoding.entryID entry.2 ≤ bound) : + (bits key).length ≤ + (1 + partitionWidth n + 6 * key.retained.length) * (max n (max bound 2) + 1) := by + have htwo : 2 ≤ max n (max bound 2) := (le_max_right bound 2).trans (le_max_right n _) + have hbound : ∀ word ∈ words key, word ≤ max n (max bound 2) := by + intro word hword + rcases List.mem_cons.mp hword with hside | htail + · have hs : sideWord key.side ≤ 1 := by cases key.side <;> decide + omega + · rcases List.mem_append.mp htail with hpart | hmeta + · obtain ⟨i, hi⟩ := List.mem_ofFn.mp hpart + have hb := boolWord_le_one (partitionMask key.partition i) + omega + · exact KeyMetadataEncoding.metadataWords_le key.retained bound hIDs word hmeta + simpa only [bits, words_length] using encodeWords_length_le (words key) _ hbound + +theorem words_injective (n : Nat) : Function.Injective (words (n := n)) := by + intro a b h + have hfields := List.cons.inj h + have hlen : (partitionWords a.partition).length = (partitionWords b.partition).length := by + simp only [partitionWords_length] + have hside := sideWord_injective hfields.1 + have hpart := partitionWords_injective n (List.append_inj_left hfields.2 hlen) + have hmeta := KeyMetadataEncoding.metadataWords_injective n + (List.append_inj_right hfields.2 hlen) + cases a + cases b + cases hside + cases hpart + cases hmeta + rfl + +theorem bits_injective (n : Nat) : Function.Injective (bits (n := n)) := by + intro a b h + exact words_injective n (encodeWords_injective h) + +def sameEncoding {n : Nat} (a b : Key n) : Bool := decide (bits a = bits b) + +theorem sameEncoding_eq_true_iff {n : Nat} (a b : Key n) : + sameEncoding a b = true ↔ a = b := by + simp only [sameEncoding, decide_eq_true_iff] + exact ⟨fun h => bits_injective n h, fun h => congrArg bits h⟩ + +theorem bits_eq_iff {n : Nat} (a b : Key n) : bits a = bits b ↔ a = b := + ⟨fun h => bits_injective n h, fun h => congrArg bits h⟩ + +theorem key_retained_length_le {n : Nat} {Y : Type*} (side : Side) + (slots : Fin n → MixedSupport.Slot) (f : MixedSupport.Assignment slots → Y) : + (CanonicalKeys.key side slots f).retained.length ≤ n := by + change (MixedSupport.retainedKeys slots f).length ≤ n + have h := List.length_filter_le + (fun entry : Fin n × SlotKey => decide (entry.2 ≠ .dropped)) + ((List.finRange n).map (fun i => (i, MixedSupport.keyFields slots f i))) + simpa only [MixedSupport.retainedKeys, List.length_map, List.length_finRange] using h + +theorem key_bits_length_le {n : Nat} {Y : Type*} (side : Side) + (slots : Fin n → MixedSupport.Slot) (f : MixedSupport.Assignment slots → Y) + (bound : Nat) + (hIDs : ∀ entry ∈ (CanonicalKeys.key side slots f).retained, + KeyMetadataEncoding.entryID entry.2 ≤ bound) : + (bits (CanonicalKeys.key side slots f)).length ≤ + (1 + 2 ^ (11 ^ n) + 6 * n) * (max n (max bound 2) + 1) := by + apply (bits_length_le (CanonicalKeys.key side slots f) bound hIDs).trans + apply Nat.mul_le_mul_right + rw [partitionWidth_eq] + exact Nat.add_le_add_left + (Nat.mul_le_mul_left 6 (key_retained_length_le side slots f)) _ + +theorem bits_projection {n : Nat} {Y : Type*} (side : Side) + {slots projected : Fin n → MixedSupport.Slot} + (p : ∀ i, MixedSupport.Projection (slots i) (projected i)) + (f : MixedSupport.Assignment projected → Y) : + bits (CanonicalKeys.key side slots (f ∘ MixedSupport.projectionMap p)) = + bits (CanonicalKeys.key side projected f) := by + rw [CanonicalKeys.key_projection side p f] + +end +end PerfectCompleteness.CanonicalKeyEncoding + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/FiniteConstraintMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/FiniteConstraintMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..51092e055eb70f67965361ab06467f023c176198 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/FiniteConstraintMachine.lean @@ -0,0 +1,130 @@ +import OAI.Computability.PerfectCompleteness.Machines.LocalCompletionMachineLemmas +import OAI.Computability.PerfectCompleteness.Machines.MetadataFreeTapeLemmas +import OAI.Computability.PerfectCompleteness.Reduction.FixedQueryCodec + +namespace OAI + +section + +namespace PerfectCompleteness.FiniteConstraintMachine + +open Turing +open UniqueGamesTheorem.Foundations.Complexity +open MetadataFreeSampler + +noncomputable section + +variable {branch : Nat → Nat} {n t q : Nat} {rows repeats : Nat → Nat} + (hq : 0 < q) + (large : CanonicalKeyEncoding.partitionWidth (TreeCanonical.locationCount branch n t) ≤ q) + +def localInput (data : MetadataFreeTape.Input branch n t rows repeats) : + LocalCompletionFamily.Input q := + CanonicalPartialTable.lookup hq large (FixedQueryCodec.partialInput data) + +def result (data : MetadataFreeTape.Input branch n t rows repeats) : LocalCompletionFamily.Result q := + LocalCompletionFamily.lookup hq (localInput hq large data) + +theorem result_correct (data : MetadataFreeTape.Input branch n t rows repeats) : + LocalCompletionFamily.Correct (localInput hq large data) (result hq large data) := + LocalCompletionFamily.lookup_correct hq _ (FixedQueryCodec.partialInput_admissible hq large data) + +def keyWords (data : MetadataFreeTape.Input branch n t rows repeats) : List Nat := + CanonicalKeyShapeMachine.outputWords (MetadataFreeTape.keyInput data) ++ + CanonicalKeyShapeMachine.outputWords (FixedQueryCodec.rightKeyInput data) + +def keyWidth (branch : Nat → Nat) (n t : Nat) : Nat := + 2 * (TreeCanonical.locationCount branch n t + + CanonicalKeyEncoding.partitionWidth (TreeCanonical.locationCount branch n t)) + +theorem keyWords_length (data : MetadataFreeTape.Input branch n t rows repeats) : + (keyWords data).length = keyWidth branch n t := by + simp only [keyWords, List.length_append, CanonicalKeyShapeMachine.outputWords_length, keyWidth] + omega + +def outputWords (data : MetadataFreeTape.Input branch n t rows repeats) : List Nat := + keyWords data ++ LocalCompletionSerialization.payloadWords (result hq large data) + +def outputBits (data : MetadataFreeTape.Input branch n t rows repeats) : List Bool := + encodeWords (outputWords hq large data) + +theorem outputWords_drop_keys (data : MetadataFreeTape.Input branch n t rows repeats) : + (outputWords hq large data).drop (keyWidth branch n t) = + LocalCompletionSerialization.payloadWords (result hq large data) := by + exact List.drop_left' (keyWords_length data) + +theorem parse_output_payload (data : MetadataFreeTape.Input branch n t rows repeats) : + LocalCompletionSerialization.parsePayload q + ((outputWords hq large data).drop (keyWidth branch n t)) = + some ((List.finRange (LocalCompletionFamily.activeCount (result hq large data))).map + (LocalCompletionSerialization.projection (result_correct hq large data))) := by + rw [outputWords_drop_keys] + exact LocalCompletionSerialization.parse_payload (result_correct hq large data) + +theorem decode_outputBits (data : MetadataFreeTape.Input branch n t rows repeats) : + decodeWords (outputBits hq large data) = some (outputWords hq large data) := + decodeWords_encodeWords _ + +theorem outputWords_length_le (data : MetadataFreeTape.Input branch n t rows repeats) : + (outputWords hq large data).length ≤ keyWidth branch n t + 1 + (2 * q) * (2 * q) := by + rw [outputWords, List.length_append, keyWords_length, LocalCompletionSerialization.payloadWords_length] + have h := Nat.mul_le_mul_right (2 * q) (LocalCompletionFamily.activeCount_le (result hq large data)) + omega + +def emit : MetadataTapeMachine.Symbol branch n t rows repeats → List Bool + | none => [] + | some data => outputBits hq large data + +def computation : + TM2ComputableInPolyTime + (MetadataTapeMachine.inputBits (branch := branch) (n := n) (t := t) + (rows := rows) (repeats := repeats)) id (emit hq large) := + FiniteWordMachine.computation (MetadataTapeMachine.inputEnum branch n t rows repeats) + none (emit hq large) + +def machine_output (data : MetadataFreeTape.Input branch n t rows repeats) : + TM2OutputsInTime (computation (rows := rows) (repeats := repeats) hq large).tm + (MetadataTapeMachine.inputBits (some data)) (some (outputBits hq large data)) 1 := by + have h := (computation (rows := rows) (repeats := repeats) hq large).outputsFun (some data) + change TM2OutputsInTime (computation (rows := rows) (repeats := repeats) hq large).tm + ((MetadataTapeMachine.inputBits (some data)).map id) + (some ((outputBits hq large data).map id)) ((1 : Polynomial Nat).eval _) at h + rw [Polynomial.eval_one] at h + exact Eq.mp (congrArg₂ + (fun (i o : List Bool) => TM2OutputsInTime (computation (rows := rows) (repeats := repeats) hq large).tm i (some o) 1) + (List.map_id (MetadataTapeMachine.inputBits (some data))) + (List.map_id (outputBits hq large data))) h + +variable {v m : Nat} + +theorem recover_right_key (clauses : Fin m → SourceClause.NormalizedClause v) + (e : PreliminarySampler.Raw clauses branch n t rows repeats) : + CanonicalKeyShapeMachine.recoverKey .right + (TreeCanonical.numberedSlots (sourceSlots clauses e.1.1)) + (FixedQueryCodec.rightKeyInput (MetadataFreeTape.encodeRaw clauses rows repeats e)) = + CanonicalKeys.key .right (TreeCanonical.numberedSlots (sourceSlots clauses e.1.1)) + (FixedQueryCodec.project (FixedQueryCodec.rawTestIndex clauses e) ∘ + TreeCanonical.numberedFunction (sourceSlots clauses e.1.1) + (HierarchicalArrays.fullJoint + (WholeArraySampler.evaluate rows repeats (GeometricPath.leafPath e.1.2) + (sourceSlots clauses e.1.1) e.2.1))) := by + rw [FixedQueryCodec.rightKeyInput_encodeRaw, CanonicalKeyShapeMachine.recoverKey_input] + exact FixedQueryCodec.right_key .right _ _ (FixedQueryCodec.rawTestIndex clauses e) + +theorem parsed_projection (data : MetadataFreeTape.Input branch n t rows repeats) + (seed : Fin (LocalCompletionFamily.activeCount (result hq large data))) (a : Fin (2 * q)) : + (LocalCompletionSerialization.projection (result_correct hq large data) seed).images[a] = + LocalCompletionFamily.table (result hq large data) seed a := + LocalCompletionSerialization.projection_apply (result_correct hq large data) seed a + +theorem workAlphabet_finite (tape : (computation (rows := rows) (repeats := repeats) hq large).tm.K) : + Finite ((computation (rows := rows) (repeats := repeats) hq large).tm.Γ tape) := by + change Finite Bool + infer_instance + +end +end PerfectCompleteness.FiniteConstraintMachine + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/FixedBinaryGapReduction.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/FixedBinaryGapReduction.lean new file mode 100644 index 0000000000000000000000000000000000000000..c594cfe5b735b8b46b53c8f19b63e21b329c5faf --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/FixedBinaryGapReduction.lean @@ -0,0 +1,36 @@ +import OAI.Computability.PerfectCompleteness.Machines.BinaryGapReduction +import OAI.Computability.PerfectCompleteness.Reduction.FixedTargetValue + +namespace OAI + +section + +namespace PerfectCompleteness.FixedBinaryGapReduction + +noncomputable section + +variable {δ : ℚ} {hδ : 0 < δ} (p : FixedParameters.Parameters δ hδ) + +def ofPreliminarySoundness + (soundness : ∀ input, ¬BinaryLanguage.language input → + FixedPreliminaryGame.value p input ≤ InitialParameters.epsilon δ) : + BinaryGapReduction δ where + alphabet := FixedTarget.alphabet p + alphabet_ge_two := FixedTarget.alphabet_ge_two p + construct := FixedTarget.construct p + computation := FixedTarget.computation p + finiteAlphabet := FixedTarget.finiteAlphabet p + completeness := FixedTarget.value_eq_one p + soundness input unsat := by + have htarget := FixedTargetValue.value_le p input + have hpreliminary := soundness input unsat + have hpositive : 0 < (δ : ℝ) := by exact_mod_cast hδ + unfold InitialParameters.epsilon at hpreliminary + linarith + +end +end PerfectCompleteness.FixedBinaryGapReduction + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/FixedStoppedNativeTape.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/FixedStoppedNativeTape.lean new file mode 100644 index 0000000000000000000000000000000000000000..9f53440efa62c459c151875ee74fda0d08d000fc --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/FixedStoppedNativeTape.lean @@ -0,0 +1,230 @@ +import OAI.Computability.PerfectCompleteness.Decoding.FixedStoppedNativeProjection +import OAI.Computability.PerfectCompleteness.Foundations.SourcePhysicalExteriorReplay +import OAI.Computability.PerfectCompleteness.Machines.StoppedCleanOwnInputGeometry +import OAI.Computability.PerfectCompleteness.Repetition.StoppedCleanCutEquality + +namespace OAI + +section + +namespace PerfectCompleteness.FixedStoppedNativeTape + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open FixedStoppedPhysicalLaw (clauses designated) +open FixedStoppedNativeProjection (physicalSample innerTag path childSample) + +private theorem cast_trans_toFun_heq {α β γ : Type} + (h : α = β) (e : β ≃ γ) + (he : ∀ b : β, HEq (@Equiv.toFun β γ e b) b) (a : α) : + HEq (@Equiv.toFun α γ ((Equiv.cast h).trans e) a) a := by + cases h + exact he a + +section Transport + +variable {branch : Nat → Nat} {root h t v m : Nat} [NeZero m] + (rows repeats : Nat → Nat) + (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch h) → Slots branch h) + +omit [NeZero m] in +private theorem observeFiber_tape_heq + (p : Path branch root (h + 1)) + (outside : Slots branch root → Fin t → MixedSupport.Slot) + (placeholder : Slots branch (h + 1) → Fin t → MixedSupport.Slot) + (sources : SourceChildKernel.Sources (m := m) (t := t) designated) + (x : CleanPhysicalReplay.Sample (t := t) rows repeats p clauses designated) + (hs : sources = SourcePhysicalTapeLaw.sourceTag rows repeats p clauses designated x) + (external : CleanPhysicalReplay.Exterior rows repeats p outside placeholder) : + HEq (SourcePhysicalTapeLaw.observeFiber rows repeats p outside placeholder clauses designated + sources (external, SourceQuestionRawSwap.raw rows clauses designated x)).2 + (WholeCutSampler.collapse rows repeats p + (CleanPhysicalCanonicalQuery.rightSlots rows repeats p outside clauses designated x) + (CleanPhysicalReplay.rightTape rows repeats p outside placeholder clauses designated + x external)) := by + cases hs + rfl + +omit [NeZero m] in +private theorem collapsedRightTape_heq + {p q : Path branch root (h + 1)} (hp : p = q) + (outside otherOutside : Slots branch root → Fin t → MixedSupport.Slot) + (placeholder otherPlaceholder : Slots branch (h + 1) → Fin t → MixedSupport.Slot) + (x : CleanPhysicalReplay.Sample (t := t) rows repeats p clauses designated) + (y : CleanPhysicalReplay.Sample (t := t) rows repeats q clauses designated) + (hx : HEq x y) + (external : CleanPhysicalReplay.Exterior rows repeats p outside placeholder) + (other : CleanPhysicalReplay.Exterior rows repeats q otherOutside otherPlaceholder) + (hext : HEq external other) + (hslots : CleanPhysicalCanonicalQuery.rightSlots rows repeats p outside clauses designated x = + CleanPhysicalCanonicalQuery.rightSlots rows repeats q otherOutside clauses designated y) : + HEq (WholeCutSampler.collapse rows repeats p + (CleanPhysicalCanonicalQuery.rightSlots rows repeats p outside clauses designated x) + (CleanPhysicalReplay.rightTape rows repeats p outside placeholder clauses designated + x external)) + (WholeCutSampler.collapse rows repeats q + (CleanPhysicalCanonicalQuery.rightSlots rows repeats q otherOutside clauses designated y) + (CleanPhysicalReplay.rightTape rows repeats q otherOutside otherPlaceholder clauses designated + y other)) := by + cases hp + have hxy : x = y := eq_of_heq hx + cases hxy + exact SourcePhysicalExteriorReplay.collapsedTape_heq rows repeats p + outside otherOutside placeholder otherPlaceholder + (CleanPhysicalReplay.rightInside rows repeats p clauses designated x) + hslots external other hext (CleanPhysicalReplay.rightBlocks rows repeats p clauses designated x) + +private theorem joinedExterior_heq + (p : Path branch root (h + 1)) + (inside : PreliminarySampler.Questions branch (h + 1) t m) + (external : SourceQuestionCutSplit.OutsideQuestions p t m) + (exterior : SourcePhysicalExteriorSwap.CanonicalExterior clauses rows repeats p external) : + HEq (@Equiv.toFun + (SourcePhysicalExteriorSwap.CanonicalExterior clauses rows repeats p external) + (SourcePhysicalExteriorSwap.ActualExterior clauses rows repeats p + (SourceQuestionCutSplit.join p inside external)) + (SourcePhysicalSourceSwap.joinedExterior clauses rows repeats p inside external) exterior) + exterior := by + exact cast_trans_toFun_heq + (congrArg (SourcePhysicalExteriorSwap.CanonicalExterior clauses rows repeats p) + (SourcePhysicalSourceSwap.outside_join p inside external).symm) + (SourcePhysicalExteriorSwap.fromCanonical clauses rows repeats p + (SourceQuestionCutSplit.join p inside external)) + (SourcePhysicalExteriorSwap.fromCanonical_heq clauses rows repeats p + (SourceQuestionCutSplit.join p inside external)) exterior + +end Transport + +variable {δ : ℚ} {hδ : 0 < δ} (parameters : FixedParameters.Parameters δ hδ) + (i j : Fin parameters.plan.depth) (hij : i < j) (input : List Bool) + (sample : FixedStoppedNativeLaw.Sample parameters i j hij input) + +local notation "R" => FixedRows.rows parameters.plan +local notation "T" => FixedRows.repeats parameters.plan +local notation "C" => clauses input +local notation "D" => designated parameters i +local notation "hu" => Nat.succ_le_of_lt j.isLt +local notation "P" => physicalSample parameters i j hij input sample +local notation "K" => innerTag parameters i j hij input sample +local notation "S" => FixedStoppedNativeLaw.setup parameters i j hij input (Sigma.fst sample) + +abbrev physicalRead := + StoppedProjectedExperiment.physicalRead C R T hu hij D P.1 P.2.1 + +abbrev experimentRead := + StoppedProjectedExperiment.physicalExperimentRead C R T hu hij D P.1 P.2.1 + +abbrev rawRead := + StoppedProjectedPhysicalAdvice.read C R T hu hij D parameters.plan.order P + +private theorem exterior_heq : HEq (S).exterior P.2.1.2.1 := by + have hclean : HEq (S).exterior sample.1.2.2.2.2 := by + have hfilled : HEq + (StoppedCleanGeometry.filledExteriorEquiv parameters input + (FixedStoppedDecoderContext.upperPath parameters i j sample.1.1) + (FixedStoppedDecoderContext.lowerPath parameters i j hij sample.1.1) + sample.1.2.1 sample.1.2.2.2.2) sample.1.2.2.2.2 := cast_heq _ _ + exact (cast_heq _ _).trans hfilled + have hphysical : HEq P.2.1.2.1 sample.1.2.2.2.2 := by + exact joinedExterior_heq R T C + (path parameters i j hij input sample) + (SourceQuestionRawSwap.insideQuestions R C D (childSample parameters i j hij input sample)) + sample.1.2.1 sample.1.2.2.2.2 + exact hclean.trans hphysical.symm + +theorem physicalRead_tape_heq : + HEq (physicalRead parameters i j hij input sample).2 + (CleanPhysicalDecoderLaw.rightWholeTape S sample.2) := by + have hphysical := observeFiber_tape_heq R T C D + (path parameters i j hij input sample) + (StoppedProjectedExperiment.nativeSlots C P.1) + (SourceProjectedTag.originalSlots C + (StoppedProjectedExperiment.cutQuestions R hu hij P.1 + (StoppedProjectedExperiment.baseTag R P.2.1.1))) + (StoppedProjectedExperiment.physicalSources R hu hij D P.1 P.2.1.1) + (childSample parameters i j hij input sample) + (FixedStoppedNativeProjection.physicalSources_eq parameters i j hij input sample) + P.2.1.2.1 + have hchild : HEq sample.2 (childSample parameters i j hij input sample) := + (cast_heq _ _).symm + have hclean := collapsedRightTape_heq R T C D + (FixedStoppedNativeLaw.path_eq parameters i j hij input sample.1) + (S).outside (StoppedProjectedExperiment.nativeSlots C P.1) + (S).placeholder + (SourceProjectedTag.originalSlots C + (StoppedProjectedExperiment.cutQuestions R hu hij P.1 + (StoppedProjectedExperiment.baseTag R P.2.1.1))) + sample.2 (childSample parameters i j hij input sample) hchild + (S).exterior P.2.1.2.1 (exterior_heq parameters i j hij input sample) + ((FixedStoppedNativeProjection.rightSlots_eq parameters i j hij input sample).trans + (FixedStoppedNativeProjection.physicalRightSlots_eq parameters i j hij input sample)) + exact hphysical.trans hclean.symm + +theorem experimentTape_heq : + HEq (experimentRead parameters i j hij input sample).2 + (CleanPhysicalDecoderLaw.uncastTape (CleanNativeReplay.rightSlots S sample.2) + (FixedStoppedDecoderContext.upperNode parameters i j hij input sample.1) + (CleanPhysicalDecoderLaw.lower S) (S).cut + (CleanDecoderContext.lowerHeight + (FixedStoppedDecoderContext.upperNode parameters i j hij input sample.1) + (FixedStoppedDecoderContext.lowerIndex parameters i j hij input sample.1)) + (CleanPhysicalDecoderLaw.rightWholeTape S sample.2)) := by + have hphysical := StoppedCleanOwnInputGeometry.pathTapeEquiv_heq R T + (StoppedProjectedExperiment.projectedSlots C R hu hij D P.1 K) + (StoppedProjectedExperiment.fullPath_spec R hu hij P.1 K).symm + (physicalRead parameters i j hij input sample).2 + have hclean := StoppedCleanOwnInputGeometry.uncastTape_heq R T + (CleanNativeReplay.rightSlots S sample.2) + (FixedStoppedDecoderContext.upperNode parameters i j hij input sample.1) + (CleanPhysicalDecoderLaw.lower S) (S).cut + (CleanDecoderContext.lowerHeight + (FixedStoppedDecoderContext.upperNode parameters i j hij input sample.1) + (FixedStoppedDecoderContext.lowerIndex parameters i j hij input sample.1)) + (CleanPhysicalDecoderLaw.rightWholeTape S sample.2) + exact hphysical.trans ((physicalRead_tape_heq parameters i j hij input sample).trans hclean.symm) + +theorem rawSample_heq : + HEq (rawRead parameters i j hij input sample).2.2.2 + (CleanPhysicalProjectedMeeting.rawSample S + (LinearMap.ker (FixedStoppedDecoderContext.advice parameters i j hij input sample.1)) + sample.2) := + StoppedCleanOwnInputGeometry.exposedRead_heq R T + (StoppedProjectedExperiment.projectedSlots C R hu hij D P.1 K) + (CleanNativeReplay.rightSlots S sample.2) + (FixedStoppedNativeProjection.rightSlots_eq parameters i j hij input sample).symm + (StoppedProjectedExperiment.upper hu P.1) + (StoppedProjectedExperiment.lower R hu hij P.1 K) (CleanPhysicalDecoderLaw.lower S) + (StoppedCleanCutEquality.stopped_lower_eq R hu hij P.1 K) + (StoppedProjectedExperiment.cut R hu hij P.1 K) (S).cut + (StoppedCleanCutEquality.stopped_cut_heq R hu hij P.1 K) + (LinearMap.ker (FixedStoppedDecoderContext.advice parameters i j hij input sample.1)) + (experimentRead parameters i j hij input sample).2 _ + (experimentTape_heq parameters i j hij input sample) + +theorem visible_heq : + HEq (rawRead parameters i j hij input sample).2.2.2.2 + (CleanPhysicalProjectedMeeting.visible S + (LinearMap.ker (FixedStoppedDecoderContext.advice parameters i j hij input sample.1)) + sample.2) := + StoppedCleanOwnInputGeometry.visibleRead_heq R T + (StoppedProjectedExperiment.projectedSlots C R hu hij D P.1 K) + (CleanNativeReplay.rightSlots S sample.2) + (FixedStoppedNativeProjection.rightSlots_eq parameters i j hij input sample).symm + (StoppedProjectedExperiment.upper hu P.1) + (StoppedProjectedExperiment.lower R hu hij P.1 K) (CleanPhysicalDecoderLaw.lower S) + (StoppedCleanCutEquality.stopped_lower_eq R hu hij P.1 K) + (StoppedProjectedExperiment.cut R hu hij P.1 K) (S).cut + (StoppedCleanCutEquality.stopped_cut_heq R hu hij P.1 K) + (LinearMap.ker (FixedStoppedDecoderContext.advice parameters i j hij input sample.1)) + (experimentRead parameters i j hij input sample).2 _ + (experimentTape_heq parameters i j hij input sample) + +end +end PerfectCompleteness.FixedStoppedNativeTape + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/FixedUnaryRepresentationMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/FixedUnaryRepresentationMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..45390df8f7dc2c4c600169947cd59aab5a94a983 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/FixedUnaryRepresentationMachine.lean @@ -0,0 +1,334 @@ +import Mathlib.Data.List.FinRange +import OAI.Computability.PerfectCompleteness.Machines.UnaryRepresentationMachine +import OAI.Computability.UniqueGames.Machines.MachineDrainManyLemmas + +namespace OAI + + +namespace PerfectCompleteness.FixedUnaryRepresentationMachine + + +open Turing UniqueGamesTheorem.Foundations.Complexity +open MachineComposition + +inductive Mode + | encodedToRaw | rawToEncoded + deriving DecidableEq + +protected abbrev Mode.enumList : List Mode := [.encodedToRaw, .rawToEncoded] + +protected theorem Mode.enumList_getElem?_ctorIdx_eq (x : Mode) : + Mode.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem Mode.enumList_nodup : Mode.enumList.Nodup := by decide + +instance : Fintype Mode where + elems := ⟨Mode.enumList, Mode.enumList_nodup⟩ + complete x := by cases x <;> decide + +inductive Tape (width : Nat) + | source (position : Fin width) + | destination (position : Fin width) + | scratch + deriving DecidableEq, Fintype + +abbrev Alphabet {width : Nat} (_ : Tape width) := Bool +abbrev State (A : Type) := A × Option Bool + +def sourceWord : Mode → Nat → List Bool + | .encodedToRaw, n => encodeWord n + | .rawToEncoded, n => List.replicate n true + +def targetWord : Mode → Nat → List Bool + | .encodedToRaw, n => List.replicate n true + | .rawToEncoded, n => encodeWord n + +def cost : Mode → Nat → Nat + | .encodedToRaw, n => 2 * n + 2 + | .rawToEncoded, n => 1 + 2 * (n + 1) + +theorem cost_le (mode : Mode) (n : Nat) : cost mode n ≤ 2 * n + 3 := by + cases mode <;> simp only [cost] <;> omega + +def LocalLabel : Mode → Type + | .encodedToRaw => UnaryRepresentationMachine.RawLabel + | .rawToEncoded => UnaryRepresentationMachine.EncodedLabel + +instance (mode : Mode) : Fintype (LocalLabel mode) := by + cases mode with + | encodedToRaw => exact inferInstanceAs (Fintype UnaryRepresentationMachine.RawLabel) + | rawToEncoded => exact inferInstanceAs (Fintype UnaryRepresentationMachine.EncodedLabel) + +instance (mode : Mode) : DecidableEq (LocalLabel mode) := by + cases mode with + | encodedToRaw => exact inferInstanceAs (DecidableEq UnaryRepresentationMachine.RawLabel) + | rawToEncoded => exact inferInstanceAs (DecidableEq UnaryRepresentationMachine.EncodedLabel) + +def localMain : (mode : Mode) → LocalLabel mode + | .encodedToRaw => UnaryRepresentationMachine.encodedToRawMain + | .rawToEncoded => UnaryRepresentationMachine.rawToEncodedMain + +variable {width : Nat} {Λ A : Type} + +def localTape (position : Fin width) : Fin 3 → Tape width + | 0 => .source position + | 1 => .scratch + | 2 => .destination position + +theorem localTape_injective (position : Fin width) : + Function.Injective (localTape position) := by + intro first second same + fin_cases first <;> fin_cases second <;> simp_all [localTape] + +def «stacks» (mode : Mode) (values : Fin width → Nat) + (destinations : Fin width → List Bool) : Tape width → List Bool + | .source position => sourceWord mode (values position) + | .destination position => destinations position + | .scratch => [] + +theorem update_destination (mode : Mode) (values : Fin width → Nat) + (destinations : Fin width → List Bool) (position : Fin width) (word : List Bool) : + Function.update («stacks» mode values destinations) (.destination position) word = + «stacks» mode values (Function.update destinations position word) := by + funext tape + cases tape with + | source next => simp [«stacks»] + | scratch => simp [«stacks»] + | destination next => + by_cases same : next = position + · subst next + simp [«stacks»] + · simp [«stacks», same] + +def update (mode : Mode) (values : Fin width → Nat) (position : Fin width) + (destinations : Fin width → List Bool) : Fin width → List Bool := + Function.update destinations position (targetWord mode (values position) ++ destinations position) + +def result (mode : Mode) (values : Fin width → Nat) + (positions : List (Fin width)) (destinations : Fin width → List Bool) := + MachineFiniteSequence.resultOf (update mode values) positions destinations + +def steps (mode : Mode) (values : Fin width → Nat) (positions : List (Fin width)) : Nat := + (positions.map (fun position => cost mode (values position))).sum + +theorem sequence_steps (mode : Mode) (values : Fin width → Nat) + (positions : List (Fin width)) (destinations : Fin width → List Bool) : + MachineFiniteSequence.steps (update mode values) + (fun position _ => cost mode (values position)) positions destinations = + steps mode values positions := by + induction positions generalizing destinations with + | nil => rfl + | cons position positions ih => + simp only [MachineFiniteSequence.steps, steps, List.map_cons, List.sum_cons, ih] + +theorem result_apply (mode : Mode) (values : Fin width → Nat) + (positions : List (Fin width)) (nodup : positions.Nodup) + (destinations : Fin width → List Bool) (position : Fin width) : + result mode values positions destinations position = + if position ∈ positions then targetWord mode (values position) ++ destinations position + else destinations position := by + induction positions generalizing destinations with + | nil => simp [result, MachineFiniteSequence.resultOf] + | cons first positions ih => + have distinct := List.nodup_cons.mp nodup + change result mode values positions (update mode values first destinations) position = _ + rw [ih distinct.2] + by_cases same : position = first + · subst position + simp [update, distinct.1] + · simp [update, same] + +theorem result_finRange (mode : Mode) (values : Fin width → Nat) + (destinations : Fin width → List Bool) : + result mode values (List.finRange width) destinations = + fun position => targetWord mode (values position) ++ destinations position := by + funext position + simp [result_apply mode values _ (List.nodup_finRange width)] + +theorem steps_le (mode : Mode) (values : Fin width → Nat) (positions : List (Fin width)) + (maximum : Nat) (bounded : ∀ position, values position ≤ maximum) : + steps mode values positions ≤ positions.length * (2 * maximum + 3) := by + induction positions with + | nil => simp [steps] + | cons position positions ih => + have head := cost_le mode (values position) + have valueBound := bounded position + have headBound : cost mode (values position) ≤ 2 * maximum + 3 := by omega + simp only [steps, List.map_cons, List.sum_cons, List.length_cons] at ih ⊢ + calc + _ ≤ 2 * maximum + 3 + positions.length * (2 * maximum + 3) := + Nat.add_le_add headBound ih + _ = _ := by rw [Nat.add_mul, Nat.one_mul, Nat.add_comm] + +def localInstruction : (mode : Mode) → (position : Fin width) → + (LocalLabel mode → Λ) → Option Λ → + LocalLabel mode → TM2.Stmt (Alphabet (width := width)) Λ (State A) + | .encodedToRaw, position, labels, done => + UnaryRepresentationMachine.encodedToRawInstruction (localTape position) labels done + | .rawToEncoded, position, labels, done => + UnaryRepresentationMachine.rawToEncodedInstruction (localTape position) labels done + +theorem localTrace (mode : Mode) (values : Fin width → Nat) (position : Fin width) + (labels : LocalLabel mode → Λ) (done : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (width := width)) Λ (State A)) + (atLabels : ∀ label, program (labels label) = localInstruction mode position labels done label) + (destinations : Fin width → List Bool) (ambient : A) : + (advance (TM2.step program))^[cost mode (values position)] + (some ⟨some (labels (localMain mode)), (ambient, none), «stacks» mode values destinations⟩) = + some ⟨done, (ambient, none), «stacks» mode values (update mode values position destinations)⟩ := by + cases mode with + | encodedToRaw => + have run := UnaryRepresentationMachine.encodedToRawTrace (localTape position) + (localTape_injective position) labels done program atLabels + («stacks» .encodedToRaw values destinations) (values position) rfl rfl ambient none + change (advance (TM2.step program))^[cost .encodedToRaw (values position)] + (some ⟨some (labels (localMain .encodedToRaw)), (ambient, none), + «stacks» .encodedToRaw values destinations⟩) = + some ⟨done, (ambient, none), Function.update («stacks» .encodedToRaw values destinations) + (.destination position) (targetWord .encodedToRaw (values position) ++ destinations position)⟩ + at run + rw [update_destination] at run + exact run + | rawToEncoded => + have run := UnaryRepresentationMachine.rawToEncodedTrace (localTape position) + (localTape_injective position) labels done program atLabels + («stacks» .rawToEncoded values destinations) (values position) rfl rfl ambient none + change (advance (TM2.step program))^[cost .rawToEncoded (values position)] + (some ⟨some (labels (localMain .rawToEncoded)), (ambient, none), + «stacks» .rawToEncoded values destinations⟩) = + some ⟨done, (ambient, none), Function.update («stacks» .rawToEncoded values destinations) + (.destination position) (targetWord .rawToEncoded (values position) ++ destinations position)⟩ + at run + rw [update_destination] at run + exact run + +abbrev Label (mode : Mode) (positions : List (Fin width)) := + MachineFiniteSequence.Label (fun _ : Fin width => LocalLabel mode) positions + +def entry (mode : Mode) (positions : List (Fin width)) (labels : Label mode positions → Λ) + (done : Option Λ) : Option Λ := + MachineFiniteSequence.entry (fun _ : Fin width => LocalLabel mode) + (fun _ => localMain mode) positions labels done + +def instruction (mode : Mode) (positions : List (Fin width)) (labels : Label mode positions → Λ) + (done : Option Λ) : Label mode positions → TM2.Stmt (Alphabet (width := width)) Λ (State A) := + MachineFiniteSequence.instruction (fun _ : Fin width => LocalLabel mode) + (fun _ => localMain mode) (localInstruction mode) positions labels done + +theorem sequenceTrace (mode : Mode) (values : Fin width → Nat) (positions : List (Fin width)) + (labels : Label mode positions → Λ) (done : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (width := width)) Λ (State A)) + (atLabels : ∀ label, program (labels label) = instruction mode positions labels done label) + (destinations : Fin width → List Bool) (ambient : A) : + (advance (TM2.step program))^[steps mode values positions] + (some ⟨entry mode positions labels done, (ambient, none), «stacks» mode values destinations⟩) = + some ⟨done, (ambient, none), «stacks» mode values (result mode values positions destinations)⟩ := by + have run := MachineFiniteSequence.trace + (LocalLabel := fun _ : Fin width => LocalLabel mode) (main := fun _ => localMain mode) + (localInstruction := localInstruction mode) (result := update mode values) + (cost := fun position _ => cost mode (values position)) program + (fun _ : Fin width → List Bool => True) (fun _ => (ambient, none)) («stacks» mode values) + positions (by intros; trivial) + (by + intro position _ localLabels localExit atLocal destinationWords _ + exact localTrace mode values position localLabels localExit program atLocal destinationWords ambient) + labels done atLabels destinations trivial + simpa only [sequence_steps, entry, result] using run + +theorem familyTrace (mode : Mode) (values : Fin width → Nat) + (labels : Label mode (List.finRange width) → Λ) (done : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (width := width)) Λ (State A)) + (atLabels : ∀ label, program (labels label) = + instruction mode (List.finRange width) labels done label) + (destinations : Fin width → List Bool) (ambient : A) : + (advance (TM2.step program))^[steps mode values (List.finRange width)] + (some ⟨entry mode (List.finRange width) labels done, (ambient, none), + «stacks» mode values destinations⟩) = + some ⟨done, (ambient, none), «stacks» mode values + (fun position => targetWord mode (values position) ++ destinations position)⟩ := by + simpa only [result_finRange] using + sequenceTrace mode values (List.finRange width) labels done program atLabels destinations ambient + +def familyInTime (mode : Mode) (values : Fin width → Nat) + (labels : Label mode (List.finRange width) → Λ) (done : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (width := width)) Λ (State A)) + (atLabels : ∀ label, program (labels label) = + instruction mode (List.finRange width) labels done label) + (destinations : Fin width → List Bool) (ambient : A) + (maximum : Nat) (bounded : ∀ position, values position ≤ maximum) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨entry mode (List.finRange width) labels done, (ambient, none), «stacks» mode values destinations⟩ + (some ⟨done, (ambient, none), «stacks» mode values + (fun position => targetWord mode (values position) ++ destinations position)⟩) + (width * (2 * maximum + 3)) where + steps := steps mode values (List.finRange width) + evals_in_steps := familyTrace mode values labels done program atLabels destinations ambient + steps_le_m := by + simpa only [List.length_finRange] using + steps_le mode values (List.finRange width) maximum bounded + +def cleanupTapes (width : Nat) : List (Tape width) := + (List.finRange width).map Tape.destination + +@[simp] theorem cleanupTapes_length : (cleanupTapes width).length = width := by + simp [cleanupTapes] + +abbrev CleanupLabel (width : Nat) := MachineDrainMany.Label (cleanupTapes width) + +def cleanupEntry (labels : CleanupLabel width → Λ) (done : Option Λ) : Option Λ := + MachineDrainMany.entry (cleanupTapes width) labels done + +def cleanupInstruction (labels : CleanupLabel width → Λ) (done : Option Λ) : + CleanupLabel width → TM2.Stmt (Alphabet (width := width)) Λ (State A) := + MachineDrainMany.instruction (cleanupTapes width) labels done + +theorem cleanup_finalTapes (mode : Mode) (values : Fin width → Nat) + (destinations : Fin width → List Bool) : + MachineDrainMany.finalTapes (cleanupTapes width) («stacks» mode values destinations) = + «stacks» mode values (fun _ => []) := by + funext tape + cases tape <;> simp [MachineDrainMany.finalTapes_apply, cleanupTapes, «stacks»] + +theorem cleanup_lengthSum (mode : Mode) (values : Fin width → Nat) + (destinations : Fin width → List Bool) : + MachineDrainMany.lengthSum (cleanupTapes width) («stacks» mode values destinations) = + ((List.finRange width).map (fun position => (destinations position).length)).sum := by + simp [MachineDrainMany.lengthSum, cleanupTapes, «stacks», Function.comp_def] + +theorem cleanupTrace (mode : Mode) (values : Fin width → Nat) + (labels : CleanupLabel width → Λ) (done : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (width := width)) Λ (State A)) + (atLabels : ∀ label, program (labels label) = cleanupInstruction labels done label) + (destinations : Fin width → List Bool) (ambient : A) : + (advance (TM2.step program))^[MachineDrainMany.steps (cleanupTapes width) + («stacks» mode values destinations)] + (some ⟨cleanupEntry labels done, (ambient, none), «stacks» mode values destinations⟩) = + some ⟨done, (ambient, none), «stacks» mode values (fun _ => [])⟩ := by + simpa only [MachineDrainMany.finalRegister_none, cleanup_finalTapes, cleanupEntry] using + MachineDrainMany.trace (cleanupTapes width) labels done program atLabels + («stacks» mode values destinations) ambient none + +def cleanupInTime (mode : Mode) (values : Fin width → Nat) + (labels : CleanupLabel width → Λ) (done : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (width := width)) Λ (State A)) + (atLabels : ∀ label, program (labels label) = cleanupInstruction labels done label) + (destinations : Fin width → List Bool) (ambient : A) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨cleanupEntry labels done, (ambient, none), «stacks» mode values destinations⟩ + (some ⟨done, (ambient, none), «stacks» mode values (fun _ => [])⟩) + (((List.finRange width).map (fun position => (destinations position).length)).sum + width) := by + simpa only [MachineDrainMany.finalRegister_none, cleanup_finalTapes, cleanupEntry, + cleanup_lengthSum, cleanupTapes_length] using + MachineDrainMany.execution (cleanupTapes width) labels done program atLabels + («stacks» mode values destinations) ambient none + +theorem finiteState [Finite A] : Finite (State A) := inferInstance + +theorem finiteLabels (mode : Mode) : Finite (Label mode (List.finRange width)) := inferInstance + +theorem finiteAlphabet (tape : Tape width) : Finite (Alphabet tape) := inferInstance + +end PerfectCompleteness.FixedUnaryRepresentationMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/ForestStage.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/ForestStage.lean new file mode 100644 index 0000000000000000000000000000000000000000..05f0c8946babed26a8ab6a08aa41504f43ea7786 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/ForestStage.lean @@ -0,0 +1,519 @@ +import OAI.Computability.PerfectCompleteness.Machines.CircuitProducerStagesLemmas +import OAI.Computability.PerfectCompleteness.Machines.PostfixBounds +import OAI.Computability.PerfectCompleteness.Machines.ProducerBootstrapLemmas +import OAI.Computability.UniqueGames.Machines.MachineControlLemmas +import OAI.Computability.UniqueGames.Machines.MachineSubroutineLemmas + +namespace OAI + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.ForestStage + +open Turing MachineComposition StatementCircuit CircuitBatch CircuitProducerModel +open PostfixModel PostfixAlignment + + +inductive Tape + | lower (tape : PostfixMachine.Tape) + | tokens | records | rootTable + deriving DecidableEq, Fintype + +abbrev Ports (K : Type) := Tape ↪ K +abbrev Alphabet {K : Type} (_ : K) := Bool +abbrev State (σ : Type) := (σ × Bool) × Option Bool + +inductive Label + | reverseTokens + | lower (label : PostfixMachine.Label) + | reverseRecords | drainRoots | rootGuard | rootStart | rootLoop | finish + deriving DecidableEq, Fintype + +def lowerPorts {K : Type} (ports : Ports K) : PostfixMachine.Tape ↪ K := + ⟨fun t => ports (.lower t), by + intro a b h + exact Tape.lower.inj (ports.injective h)⟩ + +def initialLocal (start : Nat) (tokens : List Token) + (oldRecords oldRoots : List Bool) : Tape → List Bool + | .lower .current => encodeWord start + | .lower .remaining => encodeWord tokens.length + | .tokens => (tokenBits tokens).reverse + | .records => oldRecords + | .rootTable => oldRoots + | _ => [] + +def finalLocal (next : Nat) (roots : List Nat) + (newRecords oldRecords : List Bool) : Tape → List Bool + | .lower .current => encodeWord next + | .lower .remaining => encodeWord 0 + | .records => newRecords.reverse ++ oldRecords + | .rootTable => encodeWords roots.reverse + | _ => [] + +def coreBase (tokens : List Token) : PostfixMachine.Tape → List Bool + | .remaining => encodeWord tokens.length + | _ => [] + +def coreInitial (start : Nat) (tokens : List Token) : PostfixMachine.Tape → List Bool := + PostfixMachine.boundaryTapes (coreBase tokens) start [] (tokenBits tokens) + +def coreFinal (next : Nat) (roots : List Nat) (records : List Bool) : + PostfixMachine.Tape → List Bool := + PostfixMachine.finalTapes (fun _ => []) next roots [] records + +private theorem chain {A : Type*} {f : A → A} {x y z : A} {n m : Nat} + (first : f^[n] x = y) (second : f^[m] y = z) : f^[n + m] x = z := by + rw [Nat.add_comm n m, Function.iterate_add_apply, first, second] + +theorem coreTrace (tokens : List Token) (start next : Nat) (roots : List Nat) + (gates : List Gate) + (valid : compileTokens start [] tokens = some (next, roots, gates)) : + (advance (TM2.step PostfixMachine.program))^[ + PostfixMachine.tokensSteps start [] tokens + + (recordsBits (gateRecords start gates)).length + 3] + (some ⟨some .guard, PostfixMachine.initialState, coreInitial start tokens⟩) = + some ⟨none, PostfixMachine.initialState, + coreFinal next roots (recordsBits (gateRecords start gates))⟩ := by + let bits := recordsBits (gateRecords start gates) + let middle := PostfixMachine.boundaryTapes + (PostfixMachine.outputTapes + (Function.update (coreBase tokens) .remaining (encodeWord 0)) bits.reverse) + next roots [] + have first := PostfixMachine.tokensTrace tokens (coreBase tokens) start [] next roots + gates [] valid (by rfl) + simp only [List.append_nil] at first + have second := PostfixMachine.reverseTrace middle bits + (by simp [middle, PostfixMachine.boundaryTapes, PostfixMachine.outputTapes]) + (by simp [middle, PostfixMachine.boundaryTapes, PostfixMachine.outputTapes, coreBase]) + have result := chain first second + have frame : PostfixMachine.reversedTapes middle bits = coreFinal next roots bits := by + funext tape + cases tape <;> simp [PostfixMachine.reversedTapes, middle, coreFinal, + PostfixMachine.finalTapes, PostfixMachine.boundaryTapes, PostfixMachine.outputTapes, + coreBase] + rw [frame] at result + simpa only [coreInitial, bits, Nat.add_assoc] using result + +def stateEquiv (σ : Type) : PostfixMachine.State × (σ × Bool) ≃ State σ where + toFun state := (state.2, state.1.2) + invFun state := (((), state.2), state.1) + left_inv state := by rcases state with ⟨⟨u, register⟩, ambient⟩; cases u; rfl + right_inv _ := rfl + +def framedStatement {σ : Type} + (stmt : TM2.Stmt PostfixMachine.Alphabet PostfixMachine.Label PostfixMachine.State) : + TM2.Stmt PostfixMachine.Alphabet PostfixMachine.Label (State σ) := + MachineControl.statement id (stateEquiv σ) (MachineStateFrame.frameStatement stmt) + +def framedProgram {σ : Type} : + PostfixMachine.Label → TM2.Stmt PostfixMachine.Alphabet PostfixMachine.Label (State σ) := + fun label => framedStatement (PostfixMachine.program label) + +def framedCfg {σ : Type} (ambient : σ × Bool) (cfg : PostfixMachine.machine.Cfg) : + TM2.Cfg PostfixMachine.Alphabet PostfixMachine.Label (State σ) := + MachineControl.configuration id (stateEquiv σ) + (MachineStateFrame.frameConfiguration ambient cfg) + +theorem framed_step {σ : Type} (ambient : σ × Bool) + (a b : PostfixMachine.machine.Cfg) (h : PostfixMachine.machine.step a = some b) : + TM2.step framedProgram (framedCfg ambient a) = some (framedCfg ambient b) := by + cases a with + | mk label state tapes => + cases label with + | none => simp [FinTM2.step, TM2.step] at h + | some label => + have hb : TM2.stepAux (PostfixMachine.program label) state tapes = b := Option.some.inj h + rw [← hb] + change some (TM2.stepAux + (MachineControl.statement id (stateEquiv σ) + (MachineStateFrame.frameStatement (PostfixMachine.program label))) + (stateEquiv σ (state, ambient)) tapes) = _ + erw [MachineControl.stepAux_simulation, MachineStateFrame.frame_stepAux] + rfl + +theorem framed_coreTrace {σ : Type} (ambient : σ × Bool) + (tokens : List Token) (start next : Nat) (roots : List Nat) (gates : List Gate) + (valid : compileTokens start [] tokens = some (next, roots, gates)) : + (advance (TM2.step framedProgram))^[PostfixMachine.tokensSteps start [] tokens + + (recordsBits (gateRecords start gates)).length + 3] + (some ⟨some .guard, (ambient, none), coreInitial start tokens⟩) = + some ⟨none, (ambient, none), coreFinal next roots (recordsBits (gateRecords start gates))⟩ := + liftSuccessfulTrace PostfixMachine.machine.step (TM2.step framedProgram) + (framedCfg ambient) (framed_step ambient) _ _ _ (coreTrace tokens start next roots gates valid) + +def steps (tokens : List Token) (start : Nat) (roots : List Nat) (gates : List Gate) + (oldRoots : List Bool) : Nat := + (tokenBits tokens).length + PostfixMachine.tokensSteps start [] tokens + + 2 * (recordsBits (gateRecords start gates)).length + oldRoots.length + + RootRefresh.steps roots + 7 + +private theorem forest_length_le_cost {ι : Type*} (es : List (Expr ι)) : + es.length ≤ Batch.cost es := by + induction es with + | nil => simp + | cons e es ih => + have hp := e.size_pos + simp only [List.length_cons, Batch.cost_cons] + omega + +private theorem forest_rootsBits_length_le {ι : Type*} + (es : List (Expr ι)) (start : Nat) : + (encodeWords (Batch.roots start es).reverse).length ≤ + Batch.cost es * (start + Batch.cost es + 1) := by + have h := encodeWords_length_le (Batch.roots start es).reverse + (start + Batch.cost es) (by + intro r hr + exact (Batch.roots_bounds start es r (List.mem_reverse.mp hr)).2.le) + have h' : (encodeWords (Batch.roots start es).reverse).length ≤ + es.length * (start + Batch.cost es + 1) := by + simpa only [List.length_reverse, Batch.roots_length] using h + exact h'.trans (Nat.mul_le_mul_right _ (forest_length_le_cost es)) + +private theorem forest_rootRefresh_le {ι : Type*} (es : List (Expr ι)) (start : Nat) : + RootRefresh.steps (Batch.roots start es).reverse ≤ + 3 * (Batch.cost es * (start + Batch.cost es + 1)) + 1 := + (RootRefresh.steps_le_length _).trans + (Nat.add_le_add_right (Nat.mul_le_mul_left 3 (forest_rootsBits_length_le es start)) 1) + +private theorem forest_cost_quadratic (start c T R S G H : Nat) + (hS : S ≤ c * (12 * (start + c) + 25)) + (hG : G ≤ 4 * c * (start + c + 5)) + (hH : H ≤ 3 * (c * (start + c + 1)) + 1) : + let m := start + c + T + R + 1 + T + S + 2 * G + R + H + 7 ≤ 25 * m ^ 2 + 80 * m + 20 := by + dsimp only + let m := start + c + T + R + 1 + change T + S + 2 * G + R + H + 7 ≤ 25 * m ^ 2 + 80 * m + 20 + have hc : c ≤ m := by dsimp only [m]; omega + have hsc : start + c ≤ m := by dsimp only [m]; omega + have hsc1 : start + c + 1 ≤ m := by dsimp only [m]; omega + have hTR : T + R ≤ m := by dsimp only [m]; omega + have hS' : S ≤ m * (12 * m + 25) := hS.trans (Nat.mul_le_mul hc (by omega)) + have hG' : G ≤ 4 * m * (m + 5) := + hG.trans (Nat.mul_le_mul (Nat.mul_le_mul_left 4 hc) (by omega)) + have hr : c * (start + c + 1) ≤ m * m := Nat.mul_le_mul hc hsc1 + have hH' : H ≤ 3 * (m * m) + 1 := + hH.trans (Nat.add_le_add_right (Nat.mul_le_mul_left 3 hr) 1) + calc + _ ≤ (T + R) + m * (12 * m + 25) + + 2 * (4 * m * (m + 5)) + (3 * (m * m) + 1) + 7 := by omega + _ ≤ m + m * (12 * m + 25) + + 2 * (4 * m * (m + 5)) + (3 * (m * m) + 1) + 7 := by omega + _ = 23 * m ^ 2 + 66 * m + 8 := by ring + _ ≤ 25 * m ^ 2 + 80 * m + 20 := by omega + +noncomputable def timePolynomial : Polynomial Nat := + Polynomial.C 25 * Polynomial.X ^ 2 + Polynomial.C 80 * Polynomial.X + Polynomial.C 20 + +theorem forest_steps_le {ι : Type*} (wire : ι → Nat) (es : List (Expr ι)) + (start : Nat) (oldRoots : List Bool) (hw : ∀ i, wire i < start) : + steps (forestTokens wire es) start (Batch.roots start es).reverse + (Batch.gates wire start es) oldRoots ≤ + timePolynomial.eval (start + Batch.cost es + (tokenBits (forestTokens wire es)).length + + oldRoots.length + 1) := by + simp only [steps, timePolynomial, Polynomial.eval_add, Polynomial.eval_mul, + Polynomial.eval_pow, Polynomial.eval_C, Polynomial.eval_X] + exact forest_cost_quadratic start (Batch.cost es) + (tokenBits (forestTokens wire es)).length oldRoots.length + (PostfixMachine.tokensSteps start [] (forestTokens wire es)) + (recordsBits (gateRecords start (Batch.gates wire start es))).length + (RootRefresh.steps (Batch.roots start es).reverse) + (PostfixBounds.forest_tokensSteps_le wire es start [] hw (by intro r hr; simp at hr)) + (PostfixBounds.forest_recordsBits_length_le wire es start hw) + (forest_rootRefresh_le es start) + +def localLowerPorts : PostfixMachine.Tape ↪ Tape := + ⟨Tape.lower, by intro a b h; exact Tape.lower.inj h⟩ + +def lowerFill (base : Tape → List Bool) (inner : PostfixMachine.Tape → List Bool) : + Tape → List Bool + | .lower tape => inner tape + | tape => base tape + +theorem fill_lower_eq (base : Tape → List Bool) (inner : PostfixMachine.Tape → List Bool) : + ForestPlacement.fill localLowerPorts base inner = lowerFill base inner := by + funext tape + cases tape with + | lower tape => exact ForestPlacement.fill_at localLowerPorts base inner tape + | tokens => exact ForestPlacement.fill_other _ _ _ _ (by intro i; simp [localLowerPorts]) + | records => exact ForestPlacement.fill_other _ _ _ _ (by intro i; simp [localLowerPorts]) + | rootTable => exact ForestPlacement.fill_other _ _ _ _ (by intro i; simp [localLowerPorts]) + +def program {σ : Type} : Label → TM2.Stmt (Alphabet (K := Tape)) Label (State σ) + | .reverseTokens => Reduction.MachineTransfer.loopAt .tokens (.lower .input) id false + .reverseTokens (some (.lower .guard)) + | .lower label => ForestPlacement.statement localLowerPorts Label.lower + (some .reverseRecords) (framedProgram label) + | .reverseRecords => Reduction.MachineTransfer.loopAt (.lower .output) .records id false + .reverseRecords (some .drainRoots) + | .drainRoots => MachineDrain.drain .rootTable .drainRoots (some .rootGuard) + | .rootGuard => RootRefresh.guard (.lower .roots) .rootStart (some .finish) + | .rootStart => Hastad.SourceMachine.fieldStart .rootTable .rootLoop + | .rootLoop => Hastad.SourceMachine.fieldLoop (.lower .roots) .rootTable .rootLoop + (some .rootGuard) + | .finish => .push (.lower .remaining) (fun _ => false) + (.load (fun state => (state.1, none)) .halt) + +def extras (oldRecords oldRoots : List Bool) : Tape → List Bool + | .records => oldRecords + | .rootTable => oldRoots + | _ => [] + +def afterRecords (next : Nat) (roots : List Nat) (records oldRoots : List Bool) : + Tape → List Bool + | .lower .current => encodeWord next + | .lower .roots => encodeWords roots + | .records => records + | .rootTable => oldRoots + | _ => [] + +theorem localTrace {σ : Type} (ambient : σ × Bool) + (tokens : List Token) (start next : Nat) (roots : List Nat) (gates : List Gate) + (oldRecords oldRoots : List Bool) + (valid : compileTokens start [] tokens = some (next, roots, gates)) : + (advance (TM2.step program))^[steps tokens start roots gates oldRoots] + (some ⟨some .reverseTokens, (ambient, none), initialLocal start tokens oldRecords oldRoots⟩) = + some ⟨none, (ambient, none), + finalLocal next roots (recordsBits (gateRecords start gates)) oldRecords⟩ := by + let bits := recordsBits (gateRecords start gates) + let initial := initialLocal start tokens oldRecords oldRoots + let ready := lowerFill (extras oldRecords oldRoots) (coreInitial start tokens) + let compiled := lowerFill (extras oldRecords oldRoots) (coreFinal next roots bits) + let merged := afterRecords next roots (bits.reverse ++ oldRecords) oldRoots + let refreshed := afterRecords next roots (bits.reverse ++ oldRecords) [] + let unseeded := Function.update (finalLocal next roots bits oldRecords) (.lower .remaining) [] + have inputTransfer := (Reduction.MachineTransfer.transferAtInTime + Tape.tokens (.lower .input) (by decide) id false .reverseTokens + (some (.lower .guard)) program rfl initial ambient none).evals_in_steps + have inputFrame : Reduction.MachineTransfer.tapesAt Tape.tokens (.lower .input) initial [] + ((initial .tokens).reverse.map id ++ initial (.lower .input)) = ready := by + funext tape + cases tape with + | lower tape => cases tape <;> simp [Reduction.MachineTransfer.tapesAt, initial, + initialLocal, ready, lowerFill, coreInitial, PostfixMachine.boundaryTapes, coreBase, encodeWords] + | tokens => simp [Reduction.MachineTransfer.tapesAt, initial, initialLocal, ready, lowerFill, extras] + | records => simp [Reduction.MachineTransfer.tapesAt, initial, initialLocal, ready, lowerFill, extras] + | rootTable => simp [Reduction.MachineTransfer.tapesAt, initial, initialLocal, ready, lowerFill, extras] + change (advance (TM2.step program))^[(initial .tokens).length + 1] + (some ⟨some .reverseTokens, (ambient, none), initial⟩) = + some ⟨some (.lower .guard), (ambient, none), _⟩ at inputTransfer + rw [inputFrame] at inputTransfer + have hinputLength : (initial .tokens).length = (tokenBits tokens).length := by + simp [initial, initialLocal] + rw [hinputLength] at inputTransfer + have lowering := ForestPlacement.trace localLowerPorts Label.lower (some .reverseRecords) + (extras oldRecords oldRoots) framedProgram program (fun _ => rfl) _ _ _ + (framed_coreTrace ambient tokens start next roots gates valid) + change (advance (TM2.step program))^[PostfixMachine.tokensSteps start [] tokens + bits.length + 3] + (some ⟨some (.lower .guard), (ambient, none), + ForestPlacement.fill localLowerPorts (extras oldRecords oldRoots) (coreInitial start tokens)⟩) = + some ⟨some .reverseRecords, (ambient, none), + ForestPlacement.fill localLowerPorts (extras oldRecords oldRoots) (coreFinal next roots bits)⟩ at lowering + rw [fill_lower_eq, fill_lower_eq] at lowering + have recordTransfer := (Reduction.MachineTransfer.transferAtInTime + (Tape.lower .output) .records (by decide) id false .reverseRecords (some .drainRoots) + program rfl compiled ambient none).evals_in_steps + have recordFrame : Reduction.MachineTransfer.tapesAt (Tape.lower .output) .records compiled [] + ((compiled (.lower .output)).reverse.map id ++ compiled .records) = merged := by + funext tape + cases tape with + | lower tape => cases tape <;> simp [Reduction.MachineTransfer.tapesAt, compiled, + lowerFill, extras, coreFinal, PostfixMachine.finalTapes, merged, afterRecords] + | tokens => simp [Reduction.MachineTransfer.tapesAt, compiled, lowerFill, extras, merged, afterRecords] + | records => simp [Reduction.MachineTransfer.tapesAt, compiled, lowerFill, extras, + coreFinal, PostfixMachine.finalTapes, merged, afterRecords] + | rootTable => simp [Reduction.MachineTransfer.tapesAt, compiled, lowerFill, extras, merged, afterRecords] + change (advance (TM2.step program))^[(compiled (.lower .output)).length + 1] + (some ⟨some .reverseRecords, (ambient, none), compiled⟩) = + some ⟨some .drainRoots, (ambient, none), _⟩ at recordTransfer + rw [recordFrame] at recordTransfer + have hrecordLength : (compiled (.lower .output)).length = bits.length := by + simp [compiled, lowerFill, coreFinal, PostfixMachine.finalTapes] + rw [hrecordLength] at recordTransfer + have draining := MachineDrain.drainTrace Tape.rootTable .drainRoots (some .rootGuard) + program rfl merged (merged .rootTable) ambient none + rw [Function.update_eq_self] at draining + change (advance (TM2.step program))^[(merged .rootTable).length + 1] + (some ⟨some .drainRoots, (ambient, none), merged⟩) = + some ⟨some .rootGuard, (ambient, none), Function.update merged .rootTable []⟩ at draining + have drainFrame : Function.update merged .rootTable [] = refreshed := by + funext tape + cases tape with + | lower tape => cases tape <;> simp [merged, refreshed, afterRecords] + | tokens => simp [merged, refreshed, afterRecords] + | records => simp [merged, refreshed, afterRecords] + | rootTable => simp [merged, refreshed, afterRecords] + rw [drainFrame] at draining + have hrootLength : (merged .rootTable).length = oldRoots.length := rfl + rw [hrootLength] at draining + have refresh := RootRefresh.refreshTrace (Tape.lower .roots) .rootTable (by decide) + .rootGuard .rootStart .rootLoop (some .finish) program rfl rfl rfl + refreshed roots [] ambient none + have refreshInitial : Hastad.SourceMachine.fieldTapes (Tape.lower .roots) .rootTable + refreshed (encodeWords roots) [] = refreshed := by + funext tape + cases tape with + | lower tape => cases tape <;> simp [Hastad.SourceMachine.fieldTapes, refreshed, afterRecords] + | tokens => simp [Hastad.SourceMachine.fieldTapes, refreshed, afterRecords] + | records => simp [Hastad.SourceMachine.fieldTapes, refreshed, afterRecords] + | rootTable => simp [Hastad.SourceMachine.fieldTapes, refreshed, afterRecords] + have refreshFinal : Hastad.SourceMachine.fieldTapes (Tape.lower .roots) .rootTable + refreshed [] (encodeWords roots.reverse ++ []) = unseeded := by + funext tape + cases tape with + | lower tape => cases tape <;> simp [Hastad.SourceMachine.fieldTapes, refreshed, + afterRecords, unseeded, finalLocal] + | tokens => simp [Hastad.SourceMachine.fieldTapes, refreshed, afterRecords, unseeded, finalLocal] + | records => simp [Hastad.SourceMachine.fieldTapes, refreshed, afterRecords, unseeded, finalLocal] + | rootTable => simp [Hastad.SourceMachine.fieldTapes, refreshed, unseeded, finalLocal] + rw [refreshInitial, refreshFinal] at refresh + have finish : (advance (TM2.step program))^[1] + (some ⟨some .finish, (ambient, none), unseeded⟩) = + some ⟨none, (ambient, none), finalLocal next roots bits oldRecords⟩ := by + change some (TM2.stepAux (program .finish) (ambient, none) unseeded) = _ + simp [program, TM2.stepAux, unseeded, finalLocal, encodeWord, Function.update_idem] + have total := chain (chain (chain (chain (chain inputTransfer lowering) recordTransfer) draining) refresh) finish + have cost : (((((tokenBits tokens).length + 1 + + (PostfixMachine.tokensSteps start [] tokens + bits.length + 3)) + + (bits.length + 1)) + (oldRoots.length + 1)) + RootRefresh.steps roots) + 1 = + steps tokens start roots gates oldRoots := by dsimp only [steps, bits]; omega + simpa only [cost, initial, bits] using total + +section Caller + +variable {K Λ σ : Type} [DecidableEq K] + +def statement (ports : Ports K) (labels : Label → Λ) (exit : Option Λ) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (State σ) := + fun label => ForestPlacement.statement ports labels exit (program label) + +theorem traceAt (ports : Ports K) (labels : Label → Λ) (exit : Option Λ) + (target : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ label, target (labels label) = statement ports labels exit label) + (base : K → List Bool) (ambient : σ × Bool) (tokens : List Token) + (start next : Nat) (roots : List Nat) (gates : List Gate) (oldRecords oldRoots : List Bool) + (valid : compileTokens start [] tokens = some (next, roots, gates)) : + (advance (TM2.step target))^[steps tokens start roots gates oldRoots] + (some ⟨some (labels .reverseTokens), (ambient, none), + ForestPlacement.fill ports base (initialLocal start tokens oldRecords oldRoots)⟩) = + some ⟨exit, (ambient, none), ForestPlacement.fill ports base + (finalLocal next roots (recordsBits (gateRecords start gates)) oldRecords)⟩ := + ForestPlacement.trace ports labels exit base program target atLabels _ _ _ + (localTrace ambient tokens start next roots gates oldRecords oldRoots valid) + +theorem forestTraceAt {ι : Type} (ports : Ports K) (labels : Label → Λ) (exit : Option Λ) + (target : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ label, target (labels label) = statement ports labels exit label) + (base : K → List Bool) (ambient : σ × Bool) (wire : ι → Nat) (es : List (Expr ι)) + (start : Nat) (oldRecords oldRoots : List Bool) : + (advance (TM2.step target))^[steps (forestTokens wire es) start + (Batch.roots start es).reverse (Batch.gates wire start es) oldRoots] + (some ⟨some (labels .reverseTokens), (ambient, none), ForestPlacement.fill ports base + (initialLocal start (forestTokens wire es) oldRecords oldRoots)⟩) = + some ⟨exit, (ambient, none), ForestPlacement.fill ports base + (finalLocal (start + Batch.cost es) (Batch.roots start es).reverse + (recordsBits (gateRecords start (Batch.gates wire start es))) oldRecords)⟩ := by + apply traceAt ports labels exit target atLabels base ambient _ _ _ _ _ _ _ + simpa only [List.append_nil] using compile_forestTokens wire es start [] + +noncomputable def forestInPolynomialTime {ι : Type} + (ports : Ports K) (labels : Label → Λ) (exit : Option Λ) + (target : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ label, target (labels label) = statement ports labels exit label) + (base : K → List Bool) (ambient : σ × Bool) (wire : ι → Nat) (es : List (Expr ι)) + (start : Nat) (oldRecords oldRoots : List Bool) (hw : ∀ i, wire i < start) : + StateTransition.EvalsToInTime (TM2.step target) + ⟨some (labels .reverseTokens), (ambient, none), ForestPlacement.fill ports base + (initialLocal start (forestTokens wire es) oldRecords oldRoots)⟩ + (some ⟨exit, (ambient, none), ForestPlacement.fill ports base + (finalLocal (start + Batch.cost es) (Batch.roots start es).reverse + (recordsBits (gateRecords start (Batch.gates wire start es))) oldRecords)⟩) + (timePolynomial.eval (start + Batch.cost es + + (tokenBits (forestTokens wire es)).length + oldRoots.length + 1)) where + steps := steps (forestTokens wire es) start (Batch.roots start es).reverse + (Batch.gates wire start es) oldRoots + evals_in_steps := forestTraceAt ports labels exit target atLabels base ambient wire es + start oldRecords oldRoots + steps_le_m := forest_steps_le wire es start oldRoots hw + +def preparedSize (ports : Ports K) (tapes : K → List Bool) : Nat := + (tapes (ports (.lower .current))).length + + (tapes (ports (.lower .remaining))).length + (tapes (ports .tokens)).length + + (tapes (ports .rootTable)).length + +omit [DecidableEq K] in +theorem preparedSize_initial (ports : Ports K) (base : K → List Bool) + (start : Nat) (tokens : List Token) (oldRecords oldRoots : List Bool) : + preparedSize ports (ForestPlacement.fill ports base + (initialLocal start tokens oldRecords oldRoots)) = + start + tokens.length + (tokenBits tokens).length + oldRoots.length + 2 := by + simp only [preparedSize, ForestPlacement.fill_at, initialLocal, encodeWord_length, + List.length_reverse] + omega + +noncomputable def forestInPreparedTime {ι : Type} + (ports : Ports K) (labels : Label → Λ) (exit : Option Λ) + (target : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ label, target (labels label) = statement ports labels exit label) + (base : K → List Bool) (ambient : σ × Bool) (wire : ι → Nat) (es : List (Expr ι)) + (start : Nat) (oldRecords oldRoots : List Bool) (hw : ∀ i, wire i < start) : + StateTransition.EvalsToInTime (TM2.step target) + ⟨some (labels .reverseTokens), (ambient, none), ForestPlacement.fill ports base + (initialLocal start (forestTokens wire es) oldRecords oldRoots)⟩ + (some ⟨exit, (ambient, none), ForestPlacement.fill ports base + (finalLocal (start + Batch.cost es) (Batch.roots start es).reverse + (recordsBits (gateRecords start (Batch.gates wire start es))) oldRecords)⟩) + (timePolynomial.eval (preparedSize ports (ForestPlacement.fill ports base + (initialLocal start (forestTokens wire es) oldRecords oldRoots)))) := by + let run := forestInPolynomialTime ports labels exit target atLabels base ambient wire es + start oldRecords oldRoots hw + have sizeBound : start + Batch.cost es + (tokenBits (forestTokens wire es)).length + + oldRoots.length + 1 ≤ preparedSize ports (ForestPlacement.fill ports base + (initialLocal start (forestTokens wire es) oldRecords oldRoots)) := by + rw [preparedSize_initial, forestTokens_length] + omega + exact { toEvalsTo := run.toEvalsTo + steps_le_m := run.steps_le_m.trans (natPolynomial_eval_mono timePolynomial sizeBound) } + +omit [DecidableEq K] in +theorem final_other (ports : Ports K) (base : K → List Bool) + (next : Nat) (roots : List Nat) (records oldRecords : List Bool) + (k : K) (outside : ∀ t, ports t ≠ k) : + ForestPlacement.fill ports base (finalLocal next roots records oldRecords) k = base k := + ForestPlacement.fill_other ports base _ k outside + +@[simp] theorem final_counter (next : Nat) (roots : List Nat) (records oldRecords : List Bool) : + finalLocal next roots records oldRecords (.lower .remaining) = encodeWord 0 := rfl + +theorem final_lower_clean (next : Nat) (roots : List Nat) (records oldRecords : List Bool) + (tape : PostfixMachine.Tape) (hc : tape ≠ .current) (hr : tape ≠ .remaining) : + finalLocal next roots records oldRecords (.lower tape) = [] := by + cases tape <;> simp_all [finalLocal] + +@[simp] theorem final_forest_roots {ι : Type} (start : Nat) (es : List (Expr ι)) + (records oldRecords : List Bool) : + finalLocal (start + Batch.cost es) (Batch.roots start es).reverse records oldRecords + .rootTable = encodeWords (Batch.roots start es) := by + simp [finalLocal] + +end Caller + +def machine {σ : Type} [Fintype σ] (ambient : σ × Bool) : FinTM2 where + K := Tape + k₀ := .tokens + k₁ := .records + Γ := Alphabet + Λ := Label + main := .reverseTokens + σ := State σ + initialState := (ambient, none) + m := program + +theorem machine_alphabet_finite {σ : Type} [Fintype σ] (ambient : σ × Bool) : + ∀ k, Finite ((machine ambient).Γ k) := by + intro k + exact inferInstanceAs (Finite Bool) + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.ForestStage + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/HierarchicalLowerMatrixInput.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/HierarchicalLowerMatrixInput.lean new file mode 100644 index 0000000000000000000000000000000000000000..8c10c699570c43a4b04f0edf27808cde3a804516 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/HierarchicalLowerMatrixInput.lean @@ -0,0 +1,110 @@ +import OAI.Computability.PerfectCompleteness.Decoding.HierarchicalAllDecoderTables + +namespace OAI + +section + +namespace PerfectCompleteness.HierarchicalLowerMatrixInput + +noncomputable section + +open scoped Classical +open TreeSourceSpaces HierarchicalArrays + +variable {branch rows : Nat → Nat} {n t : Nat} + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (upper : Nodes branch n) (lowerLevel : Nat) + +abbrev Matrix (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) := + Module.Dual F2 (HierarchicalDecoderTables.LowerH slots upper lowerLevel d) →ₗ[F2] + Block rows (HierarchicalLeftDecoder.LowerNode upper lowerLevel d) + +variable (background : HierarchicalMatrixTable.Background (rows := rows) slots upper) + +def updateBackground (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) + (X : Matrix (rows := rows) slots upper lowerLevel d) : + HierarchicalMatrixTable.Background (rows := rows) slots upper := + Function.update background (HierarchicalFrozenTables.lowerIndex upper lowerLevel d) + (EvaluationMatrix.rows (HierarchicalDecoderTables.LowerH slots upper lowerLevel d) X) + +@[simp] theorem updateBackground_selected + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) + (X : Matrix (rows := rows) slots upper lowerLevel d) : + updateBackground slots upper lowerLevel background d X + (HierarchicalFrozenTables.lowerIndex upper lowerLevel d) = + EvaluationMatrix.rows (HierarchicalDecoderTables.LowerH slots upper lowerLevel d) X := by + simp only [updateBackground, Function.update_self] + +theorem updateBackground_other + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) + (X : Matrix (rows := rows) slots upper lowerLevel d) + (j : {j : Nodes branch n // j ≠ upper}) + (hj : j ≠ HierarchicalFrozenTables.lowerIndex upper lowerLevel d) : + updateBackground slots upper lowerLevel background d X j = background j := by + exact Function.update_of_ne hj _ _ + +@[simp] theorem testedMatrix_update + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) + (X : Matrix (rows := rows) slots upper lowerLevel d) : + HierarchicalLeftDecoder.testedMatrix slots upper lowerLevel + (updateBackground slots upper lowerLevel background d X) d = X := by + unfold HierarchicalLeftDecoder.testedMatrix + rw [updateBackground_selected, EvaluationMatrix.ofRows_rows] + +theorem updateBackground_injective + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) : + Function.Injective (updateBackground slots upper lowerLevel background d) := by + intro X Y h + have heq := congrArg (fun bg => + HierarchicalLeftDecoder.testedMatrix slots upper lowerLevel bg d) h + simpa only [testedMatrix_update] using heq + +def advice {r : Nat} (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) + (upperMatrix : HierarchicalMatrixTable.Matrix (rows := rows) slots upper) + (A : ManyGoodRows.RowMap (Block rows upper) r) + (X : Matrix (rows := rows) slots upper lowerLevel d) : + HierarchicalDecoderTables.Advice slots upper lowerLevel + (updateBackground slots upper lowerLevel background d X) r := + (A, A.comp (MatrixRowQuotient.projectMatrix + (HierarchicalFrozenTables.knownRows slots upper lowerLevel + (updateBackground slots upper lowerLevel background d X)) upperMatrix)) + +def input {r : Nat} (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) + (upperMatrix : HierarchicalMatrixTable.Matrix (rows := rows) slots upper) + (A : ManyGoodRows.RowMap (Block rows upper) r) + (X : Matrix (rows := rows) slots upper lowerLevel d) : + HierarchicalAllDecoderTables.Input (rows := rows) slots upper lowerLevel r := + ⟨updateBackground slots upper lowerLevel background d X, + advice slots upper lowerLevel background d upperMatrix A X⟩ + +@[simp] theorem input_background {r : Nat} + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) + (upperMatrix : HierarchicalMatrixTable.Matrix (rows := rows) slots upper) + (A : ManyGoodRows.RowMap (Block rows upper) r) + (X : Matrix (rows := rows) slots upper lowerLevel d) : + (input slots upper lowerLevel background d upperMatrix A X).1 = + updateBackground slots upper lowerLevel background d X := rfl + +@[simp] theorem input_testedMatrix {r : Nat} + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) + (upperMatrix : HierarchicalMatrixTable.Matrix (rows := rows) slots upper) + (A : ManyGoodRows.RowMap (Block rows upper) r) + (X : Matrix (rows := rows) slots upper lowerLevel d) : + HierarchicalLeftDecoder.testedMatrix slots upper lowerLevel + (input slots upper lowerLevel background d upperMatrix A X).1 d = X := + testedMatrix_update slots upper lowerLevel background d X + +theorem input_injective {r : Nat} + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) + (upperMatrix : HierarchicalMatrixTable.Matrix (rows := rows) slots upper) + (A : ManyGoodRows.RowMap (Block rows upper) r) : + Function.Injective (input slots upper lowerLevel background d upperMatrix A) := by + intro X Y h + exact updateBackground_injective slots upper lowerLevel background d (congrArg Sigma.fst h) + +end +end PerfectCompleteness.HierarchicalLowerMatrixInput + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/InitializationControl.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/InitializationControl.lean new file mode 100644 index 0000000000000000000000000000000000000000..750aa468969bf49d59d941209fe05cf67b33e4b8 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/InitializationControl.lean @@ -0,0 +1,129 @@ +import OAI.Computability.PerfectCompleteness.Machines.InitializationTemplateLemmas +import OAI.Computability.PerfectCompleteness.Machines.OutputOrder +import OAI.Computability.UniqueGames.Machines.MachineCompositionLemmas +import OAI.Computability.UniqueGames.Reduction.MachineSubstitution + +namespace OAI + + +noncomputable section +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.InitializationControl + + +open Turing PostfixModel VerifierCircuit InitializationTemplate +open Reduction.MachineSubstitution + +local instance (V : NPVerifier) : DecidableEq V.computation.tm.Λ := Classical.decEq _ +local instance (V : NPVerifier) : DecidableEq V.computation.tm.σ := Classical.decEq _ +local instance (V : NPVerifier) : ∀ k, DecidableEq (V.computation.tm.Γ k) := + fun _ => Classical.decEq _ + +def tokens (V : NPVerifier) : List Token := + ((List.finRange (indexing V).labelCount).map fun i => + .const (decide (some V.computation.tm.main = (indexing V).labels.symm i))) ++ + ((List.finRange (indexing V).stateCount).map fun i => + .const (decide (V.computation.tm.initialState = (indexing V).states.symm i))) + +@[simp] theorem tokens_length (V : NPVerifier) : + (tokens V).length = (indexing V).labelCount + (indexing V).stateCount := by + simp [tokens] + +def cells (V : NPVerifier) (input : List Bool) (S : Nat) : List Token := + (List.finRange S).flatMap fun i => + (List.finRange (indexing V).symbolCount).flatMap fun j => + let symbol := (indexing V).symbols.symm j + initialCellTokens V input S symbol.1 i symbol.2 + +theorem configurationTokens_eq (V : NPVerifier) (input : List Bool) : + (TransitionTemplate.outputOrder (indexing V) (capacity V input.length)).flatMap + (initTokens V input (capacity V input.length)) = + forTokens (width V input) (configurationBody V input) := by + simp only [TransitionTemplate.outputOrder, List.flatMap_def, + ← List.ofFn_eq_map, List.map_ofFn, Function.comp_def, + forTokens_eq_ofFn, configurationBody, Fin.isLt, dite_eq_left] + rfl + +private theorem flatten_singletons {α β : Type*} (xs : List α) (f : α → β) : + (xs.map fun x => [f x]).flatten = xs.map f := by + induction xs with + | nil => rfl + | cons x xs ih => simp [ih] + +theorem initializationTokens_eq_blocks (V : NPVerifier) (input : List Bool) : + initializationTokens V input = tokens V ++ cells V input (capacity V input.length) ++ + validityTokens (V.witnessBound.eval input.length) := by + rw [initializationTokens, ← configurationTokens_eq, OutputOrder.outputOrder_eq_blocks] + simp [tokens, cells, + initTokens, List.flatMap_def, List.map_map, Function.comp_def, List.append_assoc, + flatten_singletons, List.flatten_flatten] + + +variable {K Λ σ : Type} [DecidableEq K] + +structure Ports (K : Type) where + reversed : K + count : K + distinct : reversed ≠ count + +def emitted (p : Ports K) (base : K → List Bool) (ts : List Token) : K → List Bool := + Function.update + (Function.update base p.reversed ((tokenBits ts).reverse ++ base p.reversed)) + p.count (List.replicate ts.length true ++ base p.count) + +@[simp] theorem emitted_reversed (p : Ports K) (base : K → List Bool) (ts : List Token) : + emitted p base ts p.reversed = (tokenBits ts).reverse ++ base p.reversed := by + simp [emitted, p.distinct] + +@[simp] theorem emitted_count (p : Ports K) (base : K → List Bool) (ts : List Token) : + emitted p base ts p.count = List.replicate ts.length true ++ base p.count := by + simp [emitted] + +theorem emitted_other (p : Ports K) (base : K → List Bool) (ts : List Token) + (k : K) (hr : k ≠ p.reversed) (hc : k ≠ p.count) : emitted p base ts k = base k := by + simp [emitted, hr, hc] + +def exitStatement (exit : Option Λ) : TM2.Stmt (fun _ : K => Bool) Λ σ := + match exit with + | none => .halt + | some label => .goto fun _ => label + +def literalStatement (p : Ports K) (ts : List Token) (exit : Option Λ) : + TM2.Stmt (fun _ : K => Bool) Λ σ := + pushWord p.reversed (tokenBits ts) + (pushWord p.count (List.replicate ts.length true) (exitStatement exit)) + +theorem literalStep (p : Ports K) (ts : List Token) (exit : Option Λ) + (base : K → List Bool) (state : σ) : + TM2.stepAux (literalStatement p ts exit) state base = + ⟨exit, state, emitted p base ts⟩ := by + rw [literalStatement, stepAux_pushWord, stepAux_pushWord] + cases exit <;> + simp [exitStatement, TM2.stepAux, emitted, p.distinct.symm] + +theorem literalTrace (p : Ports K) (ts : List Token) (entry : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ σ) + (code : program entry = literalStatement p ts exit) + (base : K → List Bool) (state : σ) : + (MachineComposition.advance (TM2.step program))^[1] + (some ⟨some entry, state, base⟩) = + some ⟨exit, state, emitted p base ts⟩ := by + simp only [Function.iterate_one, MachineComposition.advance_some, TM2.step, code] + rw [literalStep] + +def statement (V : NPVerifier) (p : Ports K) (exit : Option Λ) : + TM2.Stmt (fun _ : K => Bool) Λ σ := literalStatement p (tokens V) exit + +theorem trace (V : NPVerifier) (p : Ports K) (entry : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ σ) + (code : program entry = statement V p exit) + (base : K → List Bool) (state : σ) : + (MachineComposition.advance (TM2.step program))^[1] + (some ⟨some entry, state, base⟩) = + some ⟨exit, state, emitted p base (tokens V)⟩ := + literalTrace p (tokens V) entry exit program code base state + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.InitializationControl + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/InitializationMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/InitializationMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..8350d0be6c7810132046fcf448e0557028f60a81 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/InitializationMachine.lean @@ -0,0 +1,298 @@ +import OAI.Computability.PerfectCompleteness.Machines.PositionLemmas +import OAI.Computability.UniqueGames.Machines.MachineLemmas +import OAI.Computability.UniqueGames.Machines.MachineTransducerCopy + +namespace OAI + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.InitializationMachine + + +open Turing +open Reduction.MachineSubstitution (pushWord stepAux_pushWord) +open PostfixModel + +inductive Tape where + | remaining | current | threshold | scratch | reversed + | rawInput | witnessBound | capacity | closure + deriving DecidableEq + +protected abbrev Tape.enumList : List Tape := [.remaining, .current, .threshold, .scratch, + .reversed, .rawInput, .witnessBound, .capacity, .closure] + +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 + +inductive Label where + | guard | inputTag | scan | emit (symbol : Bool) | restore | test + | result (value : Bool) | done + deriving DecidableEq, Fintype + +abbrev Alphabet (_ : Tape) := Bool +abbrev State := (Unit × Unit) × Option Bool + +def initialState : State := (((), ()), none) + +def program : Label → TM2.Stmt Alphabet Label State + | .guard => MachineUnaryCounter.guard .remaining .inputTag .done + | .inputTag => pushWord .reversed (encodeWord 5) (.goto fun _ => .scan) + | .scan => MachineTransducerCopy.scanLoop .current .scratch () (fun _ b => .emit b) .restore + | .emit b => MachineTransducerCopy.emitter .reversed (fun _ _ => ()) + (fun _ symbol => [symbol]) .scan () b + | .restore => Reduction.MachineTransfer.loopAt .scratch .current id false .restore (some .test) + | .test => MachineUnaryCounter.guard .threshold (.result false) (.result true) + | .result b => pushWord .reversed (encodeWords [if b then 1 else 0, 3]) + (.push .current (fun _ => true) (.goto fun _ => .guard)) + | .done => .halt + +def machine : FinTM2 where + K := Tape + k₀ := .rawInput + k₁ := .reversed + Γ _ := Bool + Λ := Label + main := .guard + σ := State + initialState := initialState + m := program + +def tapes (base : Tape → List Bool) (remaining current threshold : Nat) + (output : List Bool) : Tape → List Bool + | .remaining => encodeWord remaining + | .current => encodeWord current + | .threshold => encodeWord threshold + | .scratch => [] + | .reversed => output + | tape => base tape + +@[simp] theorem tapes_current (base : Tape → List Bool) (m i d : Nat) (output : List Bool) : + tapes base m i d output .current = encodeWord i := rfl + +@[simp] theorem tapes_reversed (base : Tape → List Bool) (m i d : Nat) (output : List Bool) : + tapes base m i d output .reversed = output := rfl + +theorem update_reversed (base : Tape → List Bool) (m i d : Nat) + (output replacement : List Bool) : + Function.update (tapes base m i d output) .reversed replacement = + tapes base m i d replacement := by + funext tape + cases tape <;> simp [tapes] + +theorem push_current (base : Tape → List Bool) (m i d : Nat) (output : List Bool) : + Function.update (tapes base m i d output) .current (true :: encodeWord i) = + tapes base m (i + 1) d output := by + funext tape + cases tape <;> simp [tapes, encodeWord, List.replicate_succ] + +theorem counterTapes_remaining (base : Tape → List Bool) (m i d r : Nat) + (output : List Bool) : + MachineUnaryCounter.counterTapes .remaining (tapes base m i d output) r [] = + tapes base r i d output := by + funext tape + cases tape <;> simp [MachineUnaryCounter.counterTapes, tapes] + +theorem counterTapes_threshold (base : Tape → List Bool) (m i d r : Nat) + (output : List Bool) : + MachineUnaryCounter.counterTapes .threshold (tapes base m i d output) r [] = + tapes base m i r output := by + funext tape + cases tape <;> simp [MachineUnaryCounter.counterTapes, tapes] + +private theorem chain {α : Type*} {f : α → α} {x y z : α} {m n : Nat} + (first : f^[m] x = y) (second : f^[n] y = z) : f^[m + n] x = z := by + rw [Nat.add_comm m n, Function.iterate_add_apply, first, second] + +theorem inputTagStep (base : Tape → List Bool) (m i d : Nat) (output : List Bool) : + TM2.step program ⟨some .inputTag, initialState, tapes base m i d output⟩ = + some ⟨some .scan, initialState, + tapes base m i d ((encodeWord 5).reverse ++ output)⟩ := by + change some (TM2.stepAux (program .inputTag) initialState (tapes base m i d output)) = _ + rw [program, stepAux_pushWord] + change some (⟨some .scan, initialState, Function.update (tapes base m i d output) + .reversed ((encodeWord 5).reverse ++ output)⟩ : TM2.Cfg Alphabet Label State) = _ + rw [update_reversed] + +private theorem identity_output (input : List Bool) : + Reduction.MachineTransducer.output (fun (_ : Unit) _ => ()) + (fun _ symbol => [symbol]) () input = input := by + induction input with + | nil => rfl + | cons b input ih => simp [Reduction.MachineTransducer.output, ih] + +theorem indexTrace (base : Tape → List Bool) (m i d : Nat) (output : List Bool) : + (MachineComposition.advance (TM2.step program))^[3 * (i + 1) + 2] + (some ⟨some .scan, initialState, tapes base m i d output⟩) = + some ⟨some .test, initialState, + tapes base m i d ((encodeWord i).reverse ++ output)⟩ := by + have h := MachineTransducerCopy.transduceCopyTrace Tape.current Tape.scratch Tape.reversed + (by decide) (by decide) (by decide) () (fun _ _ => ()) (fun _ symbol => [symbol]) + Label.scan Label.restore (fun _ b => Label.emit b) (some Label.test) + program rfl (by intro control symbol; cases control; rfl) rfl + (tapes base m i d output) rfl () () none + simpa only [tapes_current, tapes_reversed, encodeWord_length, identity_output, + update_reversed, initialState] using h + +theorem thresholdStep (base : Tape → List Bool) (m i d : Nat) (output : List Bool) : + TM2.step program ⟨some .test, initialState, tapes base m i d output⟩ = + some ⟨some (.result (decide (d = 0))), initialState, + tapes base m i (d - 1) output⟩ := by + cases d with + | zero => + simpa only [counterTapes_threshold, Nat.zero_sub, decide_true, initialState] using + MachineUnaryCounter.guardStep_zero Tape.threshold Label.test (.result false) (.result true) + program rfl (tapes base m i 0 output) [] ((), ()) none + | succ d => + simpa only [counterTapes_threshold, Nat.add_sub_cancel, Nat.succ_ne_zero, + decide_false, initialState] using + MachineUnaryCounter.guardStep_succ Tape.threshold Label.test (.result false) (.result true) + program rfl (tapes base m i (d + 1) output) d [] ((), ()) none + +theorem resultStep (base : Tape → List Bool) (m i d : Nat) (output : List Bool) (b : Bool) : + TM2.step program ⟨some (.result b), initialState, tapes base m i d output⟩ = + some ⟨some .guard, initialState, tapes base m (i + 1) d + ((encodeWords [if b then 1 else 0, 3]).reverse ++ output)⟩ := by + change some (TM2.stepAux (program (.result b)) initialState (tapes base m i d output)) = _ + rw [program, stepAux_pushWord] + simp only [TM2.stepAux, tapes_reversed] + rw [update_reversed, tapes_current, push_current] + +def termTokens (i d : Nat) : List Token := + [.input i, .const (decide (d = 0)), .and] + +theorem termTokens_bits (i d : Nat) : + tokenBits (termTokens i d) = encodeWord 5 ++ encodeWord i ++ + encodeWords [if decide (d = 0) then 1 else 0, 3] := by + by_cases hd : d = 0 <;> + simp [termTokens, tokenBits, tokenWords, Token.words, hd, encodeWords, List.append_assoc] + +def bodySteps (i : Nat) : Nat := 3 * (i + 1) + 5 + +theorem bodyTrace (base : Tape → List Bool) (m i d : Nat) (output : List Bool) : + (MachineComposition.advance (TM2.step program))^[bodySteps i] + (some ⟨some .inputTag, initialState, tapes base m i d output⟩) = + some ⟨some .guard, initialState, tapes base m (i + 1) (d - 1) + ((tokenBits (termTokens i d)).reverse ++ output)⟩ := by + have tag : (MachineComposition.advance (TM2.step program))^[1] + (some ⟨some .inputTag, initialState, tapes base m i d output⟩) = + some ⟨some .scan, initialState, + tapes base m i d ((encodeWord 5).reverse ++ output)⟩ := by + simpa only [Function.iterate_one, MachineComposition.advance_some] using + inputTagStep base m i d output + have index := indexTrace base m i d ((encodeWord 5).reverse ++ output) + let out := (encodeWord i).reverse ++ ((encodeWord 5).reverse ++ output) + have test : (MachineComposition.advance (TM2.step program))^[1] + (some ⟨some .test, initialState, tapes base m i d out⟩) = + some ⟨some (.result (decide (d = 0))), initialState, + tapes base m i (d - 1) out⟩ := by + simpa only [Function.iterate_one, MachineComposition.advance_some] using + thresholdStep base m i d out + have result : (MachineComposition.advance (TM2.step program))^[1] + (some ⟨some (.result (decide (d = 0))), initialState, + tapes base m i (d - 1) out⟩) = + some ⟨some .guard, initialState, tapes base m (i + 1) (d - 1) + ((encodeWords [if decide (d = 0) then 1 else 0, 3]).reverse ++ out)⟩ := by + simpa only [Function.iterate_one, MachineComposition.advance_some] using + resultStep base m i (d - 1) out (decide (d = 0)) + have whole := chain (chain (chain tag index) test) result + have htime : 1 + (3 * (i + 1) + 2) + 1 + 1 = bodySteps i := by + unfold bodySteps + omega + rw [htime] at whole + simpa only [termTokens_bits, List.reverse_append, List.append_assoc, out] using whole + +theorem guardStep_succ (base : Tape → List Bool) (m i d : Nat) (output : List Bool) : + TM2.step program ⟨some .guard, initialState, tapes base (m + 1) i d output⟩ = + some ⟨some .inputTag, initialState, tapes base m i d output⟩ := by + simpa only [counterTapes_remaining, initialState] using + MachineUnaryCounter.guardStep_succ Tape.remaining Label.guard Label.inputTag Label.done + program rfl (tapes base (m + 1) i d output) m [] ((), ()) none + +theorem guardStep_zero (base : Tape → List Bool) (i d : Nat) (output : List Bool) : + TM2.step program ⟨some .guard, initialState, tapes base 0 i d output⟩ = + some ⟨some .done, initialState, tapes base 0 i d output⟩ := by + simpa only [counterTapes_remaining, initialState] using + MachineUnaryCounter.guardStep_zero Tape.remaining Label.guard Label.inputTag Label.done + program rfl (tapes base 0 i d output) [] ((), ()) none + +theorem tokens_append_bits (xs ys : List Token) : + tokenBits (xs ++ ys) = tokenBits xs ++ tokenBits ys := by + simp [tokenBits, tokenWords, List.flatMap_append] + +def selectorSteps : Nat → Nat → Nat + | _, 0 => 1 + | i, m + 1 => 1 + bodySteps i + selectorSteps (i + 1) m + +theorem selectorTrace (base : Tape → List Bool) (m i d : Nat) (output : List Bool) : + (MachineComposition.advance (TM2.step program))^[selectorSteps i m] + (some ⟨some .guard, initialState, tapes base m i d output⟩) = + some ⟨some .done, initialState, tapes base 0 (i + m) (d - m) + ((tokenBits (InitializationTemplate.selectorLoopTokens m i d)).reverse ++ output)⟩ := by + induction m generalizing i d output with + | zero => + simpa only [selectorSteps, InitializationTemplate.selectorLoopTokens, + InitializationTemplate.forTokens, tokenBits, tokenWords, List.flatMap_nil, + encodeWords, List.reverse_nil, List.nil_append, Nat.add_zero, Nat.sub_zero, + Function.iterate_one, MachineComposition.advance_some] using + guardStep_zero base i d output + | succ m ih => + have guard : (MachineComposition.advance (TM2.step program))^[1] + (some ⟨some .guard, initialState, tapes base (m + 1) i d output⟩) = + some ⟨some .inputTag, initialState, tapes base m i d output⟩ := by + simpa only [Function.iterate_one, MachineComposition.advance_some] using + guardStep_succ base m i d output + have body := bodyTrace base m i d output + have rest := ih (i + 1) (d - 1) ((tokenBits (termTokens i d)).reverse ++ output) + have whole := chain (chain guard body) rest + have hs : InitializationTemplate.selectorLoopTokens (m + 1) i d = + termTokens i d ++ InitializationTemplate.selectorLoopTokens m (i + 1) (d - 1) := + InitializationTemplate.selectorLoopTokens_succ m i d + rw [hs, tokens_append_bits, List.reverse_append, List.append_assoc] + simpa only [selectorSteps, Nat.add_assoc, Nat.add_comm, Nat.add_left_comm, + Nat.sub_sub] using whole + +theorem selectorSteps_le (i m : Nat) : + selectorSteps i m ≤ m * (3 * (i + m) + 6) + 1 := by + induction m generalizing i with + | zero => simp [selectorSteps] + | succ m ih => + let B := 3 * (i + (m + 1)) + 6 + have hbody : 1 + bodySteps i ≤ B := by unfold bodySteps B; omega + have hrest : selectorSteps (i + 1) m ≤ m * B + 1 := by + simpa only [B, Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using ih (i + 1) + calc + selectorSteps i (m + 1) = (1 + bodySteps i) + selectorSteps (i + 1) m := rfl + _ ≤ B + (m * B + 1) := Nat.add_le_add hbody hrest + _ = (m + 1) * B + 1 := by rw [Nat.succ_mul]; omega + +def selectorInTime (base : Tape → List Bool) (m i d : Nat) (output : List Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some .guard, initialState, tapes base m i d output⟩ + (some ⟨some .done, initialState, tapes base 0 (i + m) (d - m) + ((tokenBits (InitializationTemplate.selectorLoopTokens m i d)).reverse ++ output)⟩) + (m * (3 * (i + m) + 6) + 1) where + steps := selectorSteps i m + evals_in_steps := selectorTrace base m i d output + steps_le_m := selectorSteps_le i m + +theorem tapes_rawInput (base : Tape → List Bool) (m i d : Nat) (output : List Bool) : + tapes base m i d output .rawInput = base .rawInput := rfl + +theorem tapes_witnessBound (base : Tape → List Bool) (m i d : Nat) (output : List Bool) : + tapes base m i d output .witnessBound = base .witnessBound := rfl + +theorem tapes_capacity (base : Tape → List Bool) (m i d : Nat) (output : List Bool) : + tapes base m i d output .capacity = base .capacity := rfl + +theorem tapes_closure (base : Tape → List Bool) (m i d : Nat) (output : List Bool) : + tapes base m i d output .closure = base .closure := rfl + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.InitializationMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/InitializationMachineAt.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/InitializationMachineAt.lean new file mode 100644 index 0000000000000000000000000000000000000000..dd41a9cc28491ffade9627b62f373000645aa38b --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/InitializationMachineAt.lean @@ -0,0 +1,420 @@ +import OAI.Computability.PerfectCompleteness.Machines.InitializationMachine +import OAI.Computability.PerfectCompleteness.Machines.OrClosure + +namespace OAI + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.InitializationMachineAt + +open Turing PostfixModel +open Reduction.MachineSubstitution (pushWord stepAux_pushWord) +open InitializationMachine (Label termTokens bodySteps selectorSteps) + + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev Ports (K : Type) := Fin 6 ↪ K +abbrev Alphabet (_ : K) := Bool +abbrev State (σ : Type) := (σ × Bool) × Option Bool + +def initialState (ambient : σ) : State σ := ((ambient, false), none) + +def frame (p : Ports K) (base : K → List Bool) (contents : Fin 6 → List Bool) + (k : K) : List Bool := + if k = p 0 then contents 0 else if k = p 1 then contents 1 + else if k = p 2 then contents 2 else if k = p 3 then contents 3 + else if k = p 4 then contents 4 else if k = p 5 then contents 5 else base k + +@[simp] theorem frame_at (p : Ports K) (base : K → List Bool) + (contents : Fin 6 → List Bool) (j : Fin 6) : frame p base contents (p j) = contents j := by + fin_cases j <;> simp [frame, p.injective.eq_iff] + +theorem frame_other (p : Ports K) (base : K → List Bool) (contents : Fin 6 → List Bool) + (k : K) (hk : ∀ j, k ≠ p j) : frame p base contents k = base k := by + simp [frame, hk] + +theorem update_frame (p : Ports K) (base : K → List Bool) (contents : Fin 6 → List Bool) + (j : Fin 6) (replacement : List Bool) : + Function.update (frame p base contents) (p j) replacement = + frame p base (Function.update contents j replacement) := by + funext k + by_cases hk : ∃ r, p r = k + · obtain ⟨r, rfl⟩ := hk + by_cases hr : r = j + · subst r; simp + · simp [p.injective.ne hr, hr] + · have hn : ∀ r, k ≠ p r := fun r h => hk ⟨r, h.symm⟩ + simp [Function.update_of_ne (hn j), frame_other p base _ k hn] + +def contents (m i d : Nat) (output count : List Bool) (j : Fin 6) : List Bool := + match j.val with + | 0 => encodeWord m + | 1 => encodeWord i + | 2 => encodeWord d + | 3 => [] + | 4 => output + | _ => count + +def tapes (p : Ports K) (base : K → List Bool) (m i d : Nat) + (output count : List Bool) : K → List Bool := frame p base (contents m i d output count) + +@[simp] theorem tapes_at (p : Ports K) (base : K → List Bool) (m i d : Nat) + (output count : List Bool) (j : Fin 6) : + tapes p base m i d output count (p j) = contents m i d output count j := by + exact frame_at p base _ j + +theorem tapes_other (p : Ports K) (base : K → List Bool) (m i d : Nat) + (output count : List Bool) (k : K) (hk : ∀ j, k ≠ p j) : + tapes p base m i d output count k = base k := frame_other p base _ k hk + +theorem update_remaining (p : Ports K) (base : K → List Bool) (m i d r : Nat) + (output count : List Bool) : + Function.update (tapes p base m i d output count) (p 0) (encodeWord r) = + tapes p base r i d output count := by + rw [tapes, update_frame] + congr 1 + funext j + fin_cases j <;> simp [contents] + +theorem update_current (p : Ports K) (base : K → List Bool) (m i d r : Nat) + (output count : List Bool) : + Function.update (tapes p base m i d output count) (p 1) (encodeWord r) = + tapes p base m r d output count := by + rw [tapes, update_frame] + congr 1 + funext j + fin_cases j <;> simp [contents] + +theorem update_threshold (p : Ports K) (base : K → List Bool) (m i d r : Nat) + (output count : List Bool) : + Function.update (tapes p base m i d output count) (p 2) (encodeWord r) = + tapes p base m i r output count := by + rw [tapes, update_frame] + congr 1 + funext j + fin_cases j <;> simp [contents] + +theorem update_reversed (p : Ports K) (base : K → List Bool) (m i d : Nat) + (output count replacement : List Bool) : + Function.update (tapes p base m i d output count) (p 4) replacement = + tapes p base m i d replacement count := by + rw [tapes, update_frame] + congr 1 + funext j + fin_cases j <;> simp [contents] + +theorem update_count (p : Ports K) (base : K → List Bool) (m i d : Nat) + (output count replacement : List Bool) : + Function.update (tapes p base m i d output count) (p 5) replacement = + tapes p base m i d output replacement := by + rw [tapes, update_frame] + congr 1 + funext j + fin_cases j <;> simp [contents] + +theorem push_current (p : Ports K) (base : K → List Bool) (m i d : Nat) + (output count : List Bool) : + Function.update (tapes p base m i d output count) (p 1) (true :: encodeWord i) = + tapes p base m (i + 1) d output count := by + rw [show true :: encodeWord i = encodeWord (i + 1) by + simp [encodeWord, List.replicate_succ]] + exact update_current p base m i d (i + 1) output count + +def statement (p : Ports K) (label : Label ↪ Λ) : Label → TM2.Stmt (Alphabet (K := K)) Λ (State σ) + | .guard => MachineUnaryCounter.guard (p 0) (label .inputTag) (label .done) + | .inputTag => pushWord (p 4) (encodeWord 5) (.goto fun _ => label .scan) + | .scan => MachineTransducerCopy.scanLoop (p 1) (p 3) false + (fun _ b => label (.emit b)) (label .restore) + | .emit b => MachineTransducerCopy.emitter (p 4) (fun _ _ => false) + (fun _ symbol => [symbol]) (label .scan) false b + | .restore => Reduction.MachineTransfer.loopAt (p 3) (p 1) id false + (label .restore) (some (label .test)) + | .test => MachineUnaryCounter.guard (p 2) (label (.result false)) (label (.result true)) + | .result b => pushWord (p 4) (encodeWords [if b then 1 else 0, 3]) + (.push (p 5) (fun _ => true) (.push (p 5) (fun _ => true) + (.push (p 5) (fun _ => true) + (.push (p 1) (fun _ => true) (.goto fun _ => label .guard))))) + | .done => .halt + +def Agrees (p : Ports K) (label : Label ↪ Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) : Prop := + ∀ l, l ≠ .done → program (label l) = statement p label l + +private theorem chain {α : Type*} {f : α → α} {x y z : α} {m n : Nat} + (first : f^[m] x = y) (second : f^[n] y = z) : f^[m + n] x = z := by + rw [Nat.add_comm m n, Function.iterate_add_apply, first, second] + +theorem inputTagStep (p : Ports K) (label : Label ↪ Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) (ha : Agrees p label program) + (base : K → List Bool) (m i d : Nat) (output count : List Bool) (ambient : σ) : + TM2.step program ⟨some (label .inputTag), initialState ambient, tapes p base m i d output count⟩ = + some ⟨some (label .scan), initialState ambient, + tapes p base m i d ((encodeWord 5).reverse ++ output) count⟩ := by + change some (TM2.stepAux (program (label .inputTag)) _ _) = _ + rw [ha .inputTag (by decide), statement, stepAux_pushWord] + simp [TM2.stepAux, contents, update_reversed] + +private theorem identity_output (control : Bool) (input : List Bool) : + Reduction.MachineTransducer.output (fun (_ : Bool) _ => false) + (fun _ symbol => [symbol]) control input = input := by + induction input generalizing control with + | nil => rfl + | cons b input ih => simp [Reduction.MachineTransducer.output, ih] + +theorem indexTrace (p : Ports K) (label : Label ↪ Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) (ha : Agrees p label program) + (base : K → List Bool) (m i d : Nat) (output count : List Bool) (ambient : σ) : + (MachineComposition.advance (TM2.step program))^[3 * (i + 1) + 2] + (some ⟨some (label .scan), initialState ambient, tapes p base m i d output count⟩) = + some ⟨some (label .test), initialState ambient, + tapes p base m i d ((encodeWord i).reverse ++ output) count⟩ := by + have h := MachineTransducerCopy.transduceCopyTrace (p 1) (p 3) (p 4) + (p.injective.ne (by decide)) (p.injective.ne (by decide)) (p.injective.ne (by decide)) + false (fun _ _ => false) (fun _ symbol => [symbol]) + (label .scan) (label .restore) (fun _ b => label (.emit b)) (some (label .test)) program + (ha .scan (by decide)) + (by intro control symbol; exact ha (.emit symbol) (by intro h; cases h)) + (ha .restore (by decide)) (tapes p base m i d output count) + (by simp [contents]) ambient false none + simpa [contents, identity_output, update_reversed, initialState] using h + +theorem thresholdStep (p : Ports K) (label : Label ↪ Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) (ha : Agrees p label program) + (base : K → List Bool) (m i d : Nat) (output count : List Bool) (ambient : σ) : + TM2.step program ⟨some (label .test), initialState ambient, tapes p base m i d output count⟩ = + some ⟨some (label (.result (decide (d = 0)))), initialState ambient, + tapes p base m i (d - 1) output count⟩ := by + change some (TM2.stepAux (program (label .test)) _ _) = _ + rw [ha .test (by decide)] + cases d with + | zero => simp [statement, MachineUnaryCounter.guard, TM2.stepAux, contents, initialState, encodeWord] + | succ d => + simp only [statement, MachineUnaryCounter.guard, TM2.stepAux, initialState, + tapes_at, contents, encodeWord, List.replicate_succ, List.cons_append] + change some (⟨some (label (.result false)), initialState ambient, + Function.update (tapes p base m i (d + 1) output count) (p 2) (encodeWord d)⟩ : + TM2.Cfg (Alphabet (K := K)) Λ (State σ)) = _ + rw [update_threshold] + simp [initialState] + +theorem resultStep (p : Ports K) (label : Label ↪ Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) (ha : Agrees p label program) + (base : K → List Bool) (m i d : Nat) (output count : List Bool) (ambient : σ) (b : Bool) : + TM2.step program ⟨some (label (.result b)), initialState ambient, tapes p base m i d output count⟩ = + some ⟨some (label .guard), initialState ambient, tapes p base m (i + 1) d + ((encodeWords [if b then 1 else 0, 3]).reverse ++ output) (true :: true :: true :: count)⟩ := by + change some (TM2.stepAux (program (label (.result b))) _ _) = _ + rw [ha (.result b) (by intro h; cases h), statement, stepAux_pushWord] + simp [TM2.stepAux, contents, update_reversed, update_count, push_current] + +theorem bodyTrace (p : Ports K) (label : Label ↪ Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) (ha : Agrees p label program) + (base : K → List Bool) (m i d : Nat) (output count : List Bool) (ambient : σ) : + (MachineComposition.advance (TM2.step program))^[bodySteps i] + (some ⟨some (label .inputTag), initialState ambient, tapes p base m i d output count⟩) = + some ⟨some (label .guard), initialState ambient, tapes p base m (i + 1) (d - 1) + ((tokenBits (termTokens i d)).reverse ++ output) (true :: true :: true :: count)⟩ := by + have tag : (MachineComposition.advance (TM2.step program))^[1] + (some ⟨some (label .inputTag), initialState ambient, tapes p base m i d output count⟩) = + some ⟨some (label .scan), initialState ambient, + tapes p base m i d ((encodeWord 5).reverse ++ output) count⟩ := by + simpa only [Function.iterate_one, MachineComposition.advance_some] using + inputTagStep p label program ha base m i d output count ambient + have index := indexTrace p label program ha base m i d + ((encodeWord 5).reverse ++ output) count ambient + let out := (encodeWord i).reverse ++ ((encodeWord 5).reverse ++ output) + have test : (MachineComposition.advance (TM2.step program))^[1] + (some ⟨some (label .test), initialState ambient, tapes p base m i d out count⟩) = + some ⟨some (label (.result (decide (d = 0)))), initialState ambient, + tapes p base m i (d - 1) out count⟩ := by + simpa only [Function.iterate_one, MachineComposition.advance_some] using + thresholdStep p label program ha base m i d out count ambient + have result : (MachineComposition.advance (TM2.step program))^[1] + (some ⟨some (label (.result (decide (d = 0)))), initialState ambient, + tapes p base m i (d - 1) out count⟩) = + some ⟨some (label .guard), initialState ambient, tapes p base m (i + 1) (d - 1) + ((encodeWords [if decide (d = 0) then 1 else 0, 3]).reverse ++ out) + (true :: true :: true :: count)⟩ := by + simpa only [Function.iterate_one, MachineComposition.advance_some] using + resultStep p label program ha base m i (d - 1) out count ambient (decide (d = 0)) + have whole := chain (chain (chain tag index) test) result + have ht : 1 + (3 * (i + 1) + 2) + 1 + 1 = bodySteps i := by + unfold InitializationMachine.bodySteps + omega + rw [ht] at whole + simpa only [InitializationMachine.termTokens_bits, List.reverse_append, + List.append_assoc, out] using whole + +theorem guardStep_zero (p : Ports K) (label : Label ↪ Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) (ha : Agrees p label program) + (base : K → List Bool) (i d : Nat) (output count : List Bool) (ambient : σ) : + TM2.step program ⟨some (label .guard), initialState ambient, tapes p base 0 i d output count⟩ = + some ⟨some (label .done), initialState ambient, tapes p base 0 i d output count⟩ := by + change some (TM2.stepAux (program (label .guard)) _ _) = _ + rw [ha .guard (by decide)] + simp [statement, MachineUnaryCounter.guard, TM2.stepAux, contents, initialState, encodeWord] + +theorem guardStep_succ (p : Ports K) (label : Label ↪ Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) (ha : Agrees p label program) + (base : K → List Bool) (m i d : Nat) (output count : List Bool) (ambient : σ) : + TM2.step program ⟨some (label .guard), initialState ambient, tapes p base (m + 1) i d output count⟩ = + some ⟨some (label .inputTag), initialState ambient, tapes p base m i d output count⟩ := by + change some (TM2.stepAux (program (label .guard)) _ _) = _ + rw [ha .guard (by decide)] + simp only [statement, MachineUnaryCounter.guard, TM2.stepAux, initialState, + tapes_at, contents, encodeWord, List.replicate_succ, List.cons_append] + change some (⟨some (label .inputTag), initialState ambient, + Function.update (tapes p base (m + 1) i d output count) (p 0) (encodeWord m)⟩ : + TM2.Cfg (Alphabet (K := K)) Λ (State σ)) = _ + rw [update_remaining] + rfl + +theorem prepend_three (n : Nat) (count : List Bool) : + List.replicate n true ++ (true :: true :: true :: count) = + List.replicate (n + 3) true ++ count := by + change List.replicate n true ++ (List.replicate 3 true ++ count) = _ + rw [← List.append_assoc, List.replicate_append_replicate] + +theorem selectorTrace (p : Ports K) (label : Label ↪ Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) (ha : Agrees p label program) + (base : K → List Bool) (m i d : Nat) (output count : List Bool) (ambient : σ) : + (MachineComposition.advance (TM2.step program))^[selectorSteps i m] + (some ⟨some (label .guard), initialState ambient, tapes p base m i d output count⟩) = + some ⟨some (label .done), initialState ambient, tapes p base 0 (i + m) (d - m) + ((tokenBits (InitializationTemplate.selectorLoopTokens m i d)).reverse ++ output) + (List.replicate (3 * m) true ++ count)⟩ := by + induction m generalizing i d output count with + | zero => + simpa only [InitializationMachine.selectorSteps, InitializationTemplate.selectorLoopTokens, + InitializationTemplate.forTokens, tokenBits, tokenWords, List.flatMap_nil, + encodeWords, List.reverse_nil, List.nil_append, Nat.add_zero, Nat.sub_zero, + Nat.mul_zero, List.replicate_zero, Function.iterate_one, MachineComposition.advance_some] using + guardStep_zero p label program ha base i d output count ambient + | succ m ih => + have guard : (MachineComposition.advance (TM2.step program))^[1] + (some ⟨some (label .guard), initialState ambient, tapes p base (m + 1) i d output count⟩) = + some ⟨some (label .inputTag), initialState ambient, tapes p base m i d output count⟩ := by + simpa only [Function.iterate_one, MachineComposition.advance_some] using + guardStep_succ p label program ha base m i d output count ambient + have body := bodyTrace p label program ha base m i d output count ambient + have rest := ih (i + 1) (d - 1) ((tokenBits (termTokens i d)).reverse ++ output) + (true :: true :: true :: count) + have whole := chain (chain guard body) rest + rw [prepend_three] at whole + have hs : InitializationTemplate.selectorLoopTokens (m + 1) i d = + termTokens i d ++ InitializationTemplate.selectorLoopTokens m (i + 1) (d - 1) := + InitializationTemplate.selectorLoopTokens_succ m i d + rw [hs, InitializationMachine.tokens_append_bits, List.reverse_append, List.append_assoc] + simpa only [InitializationMachine.selectorSteps, Nat.add_assoc, Nat.add_comm, + Nat.add_left_comm, Nat.sub_sub, Nat.mul_succ] using whole + +def selectorInTime (p : Ports K) (label : Label ↪ Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) (ha : Agrees p label program) + (base : K → List Bool) (m i d : Nat) (output count : List Bool) (ambient : σ) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (label .guard), initialState ambient, tapes p base m i d output count⟩ + (some ⟨some (label .done), initialState ambient, tapes p base 0 (i + m) (d - m) + ((tokenBits (InitializationTemplate.selectorLoopTokens m i d)).reverse ++ output) + (List.replicate (3 * m) true ++ count)⟩) + (m * (3 * (i + m) + 6) + 1) where + steps := selectorSteps i m + evals_in_steps := selectorTrace p label program ha base m i d output count ambient + steps_le_m := InitializationMachine.selectorSteps_le i m + +theorem increment_count (m c : Nat) (suffix : List Bool) : + List.replicate (3 * m) true ++ (encodeWord c ++ suffix) = + encodeWord (c + 3 * m) ++ suffix := by + simp only [encodeWord, ← List.append_assoc, List.replicate_append_replicate] + rw [Nat.add_comm (3 * m) c] + +omit [DecidableEq K] in +theorem standalone_agrees (p : Ports K) : + Agrees (σ := σ) p (Function.Embedding.refl Label) + (statement p (Function.Embedding.refl Label)) := by + intro l _ + rfl + +def machine [Fintype K] [Fintype σ] (p : Ports K) (ambient : σ) : FinTM2 where + K := K + k₀ := p 0 + k₁ := p 4 + Γ _ := Bool + Λ := Label + main := .guard + σ := State σ + initialState := initialState ambient + m := statement p (Function.Embedding.refl Label) + +def closurePorts (p : Ports K) (closing : K) (hc : ∀ j, closing ≠ p j) : OrClosure.Ports K where + remaining := closing + reversed := p 4 + count := p 5 + remaining_ne_reversed := hc 4 + remaining_ne_count := hc 5 + reversed_ne_count := p.injective.ne (by decide) + +theorem presenceTrace (p : Ports K) (label : Label ↪ Λ) + (closing : K) (hc : ∀ j, closing ≠ p j) (again : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) (ha : Agrees p label program) + (atSeed : program (label .done) = OrClosure.seed (closurePorts p closing hc) again) + (atLoop : program again = OrClosure.loop (closurePorts p closing hc) again exit) + (base : K → List Bool) (q n : Nat) (suffix output count : List Bool) + (hclosing : base closing = encodeWord (q + 1) ++ suffix) (ambient : σ) : + let selected := tapes p base 0 (q + 1) (n + 1 - (q + 1)) + ((tokenBits (InitializationTemplate.selectorLoopTokens (q + 1) 0 (n + 1))).reverse ++ output) + (List.replicate (3 * (q + 1)) true ++ count) + (MachineComposition.advance (TM2.step program))^[selectorSteps 0 (q + 1) + (q + 1 + 2)] + (some ⟨some (label .guard), initialState ambient, tapes p base (q + 1) 0 (n + 1) output count⟩) = + some ⟨exit, initialState ambient, + OrClosure.frame (closurePorts p closing hc) selected (encodeWord 0 ++ suffix) + ((tokenBits (InitializationTemplate.presenceTokens q n)).reverse ++ output) + (List.replicate (4 * (q + 1) + 1) true ++ count)⟩ := by + dsimp only + let out := (tokenBits (InitializationTemplate.selectorLoopTokens (q + 1) 0 (n + 1))).reverse ++ output + let cnt := List.replicate (3 * (q + 1)) true ++ count + let selected := tapes p base 0 (q + 1) (n + 1 - (q + 1)) out cnt + have hs := selectorTrace p label program ha base (q + 1) 0 (n + 1) output count ambient + simp only [Nat.zero_add] at hs + have hr : selected closing = encodeWord (q + 1) ++ suffix := + (tapes_other p base _ _ _ out cnt closing hc).trans hclosing + have ho : selected (p 4) = out := by simp [selected, contents] + have hn : selected (p 5) = cnt := by simp [selected, contents] + have hf : OrClosure.frame (closurePorts p closing hc) selected + (encodeWord (q + 1) ++ suffix) out cnt = selected := by + simpa only [closurePorts, hr, ho, hn] using + OrClosure.frame_self (closurePorts p closing hc) selected + have hclose := OrClosure.closureTrace (closurePorts p closing hc) (label .done) again exit + program atSeed atLoop selected (q + 1) suffix out cnt (ambient, false) none + rw [hf] at hclose + have whole := chain hs hclose + have hout : (tokenBits (InitializationTemplate.closeOr (q + 1))).reverse ++ out = + (tokenBits (InitializationTemplate.presenceTokens q n)).reverse ++ output := by + rw [← InitializationTemplate.selectorLoopTokens_presence q n, + InitializationMachine.tokens_append_bits, List.reverse_append, List.append_assoc] + have hcnt : List.replicate (q + 1 + 1) true ++ cnt = + List.replicate (4 * (q + 1) + 1) true ++ count := by + dsimp only [cnt] + rw [← List.append_assoc, List.replicate_append_replicate] + congr 2 + omega + rw [hout, hcnt] at whole + exact whole + +theorem presenceSteps_le (q : Nat) : + selectorSteps 0 (q + 1) + (q + 1 + 2) ≤ + (q + 1) * (3 * (q + 1) + 7) + 3 := by + have h := InitializationMachine.selectorSteps_le 0 (q + 1) + simp only [Nat.zero_add] at h + rw [show 3 * (q + 1) + 7 = (3 * (q + 1) + 6) + 1 by omega, + Nat.mul_add, Nat.mul_one] + omega + +theorem presence_count (q c : Nat) (suffix : List Bool) : + List.replicate (4 * (q + 1) + 1) true ++ (encodeWord c ++ suffix) = + encodeWord (c + (4 * (q + 1) + 1)) ++ suffix := by + simp only [encodeWord, ← List.append_assoc, List.replicate_append_replicate] + rw [Nat.add_comm (4 * (q + 1) + 1) c] + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.InitializationMachineAt + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/InitializationStageLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/InitializationStageLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..867b342e01077a8f6bb902afaa46e8b6065107fe --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/InitializationStageLemmas.lean @@ -0,0 +1,473 @@ +import OAI.Computability.PerfectCompleteness.Machines.CellsTokensAlignmentLemmas +import OAI.Computability.PerfectCompleteness.Machines.ClashMachine +import OAI.Computability.PerfectCompleteness.Machines.ForestStage +import OAI.Computability.PerfectCompleteness.Machines.InitializationTemplateLemmas +import OAI.Computability.PerfectCompleteness.Machines.ProducerInvariant +import OAI.Computability.PerfectCompleteness.Machines.TermMachine + +namespace OAI + + +noncomputable section +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.InitializationStage + +open Turing MachineComposition StatementCircuit CircuitBatch PostfixModel PostfixAlignment + + +abbrev Ports (K : Type) := ForestStage.Ports K +abbrev State (σ : Type) := ForestStage.State σ + +def freeInputs (V : NPVerifier) (input : List Bool) : Nat := + 2 * V.witnessBound.eval input.length + 1 + +def initialGates (V : NPVerifier) (input : List Bool) : List Gate := + Batch.gates Fin.val (freeInputs V input) + (List.ofFn (VerifierCircuit.initialExpressions V input)) + +def preparedLocal (V : NPVerifier) (input : List Bool) : ForestStage.Tape → List Bool := + ForestStage.initialLocal (freeInputs V input) + (InitializationTemplate.initializationTokens V input) [] [] + +def snapshotLocal (s : ProducerInvariant.Snapshot) : ForestStage.Tape → List Bool + | .lower .current => s.currentBits + | .lower .remaining => encodeWord 0 + | .records => s.reversedRecords + | .rootTable => s.rootBits + | _ => [] + +def finishedLocal (V : NPVerifier) (input : List Bool) : ForestStage.Tape → List Bool := + snapshotLocal (ProducerInvariant.snapshot (VerifierCircuit.initialFrame V input)) + +theorem initialCompile (V : NPVerifier) (input : List Bool) : + compileTokens (freeInputs V input) [] + (InitializationTemplate.initializationTokens V input) = + some (ProducerInvariant.next (VerifierCircuit.initialFrame V input), + (ProducerInvariant.rootValues (VerifierCircuit.initialFrame V input)).reverse, + initialGates V input) := by + have h := ProducerInvariant.compile_frameForest + (Frame.initial (id : Fin (freeInputs V input) → Fin (freeInputs V input))) + (VerifierCircuit.initialExpressions V input) + simpa [InitializationTemplate.initializationTokens_eq, freeInputs, initialGates, + ProducerInvariant.next, Frame.initial, Fragment.empty, + VerifierCircuit.initialFrame] using h + +theorem initialRecords (V : NPVerifier) (input : List Bool) : + ProducerInvariant.recordBits (VerifierCircuit.initialFrame V input) = + recordsBits (gateRecords (freeInputs V input) (initialGates V input)) := by + change ProducerInvariant.recordBits + ((Frame.initial (id : Fin (freeInputs V input) → Fin (freeInputs V input))).step + (VerifierCircuit.initialExpressions V input)) = _ + erw [ProducerInvariant.recordBits_step] + simp [ProducerInvariant.recordBits, ProducerInvariant.next, Frame.initial, + Fragment.empty, gateRecords, recordsBits, recordsWords, encodeWords, + freeInputs, initialGates] + +theorem finalLocal_eq (V : NPVerifier) (input : List Bool) : + ForestStage.finalLocal + (ProducerInvariant.next (VerifierCircuit.initialFrame V input)) + (ProducerInvariant.rootValues (VerifierCircuit.initialFrame V input)).reverse + (recordsBits (gateRecords (freeInputs V input) (initialGates V input))) [] = + finishedLocal V input := by + rw [← initialRecords] + funext tape + cases tape with + | lower tape => cases tape <;> + simp [ForestStage.finalLocal, finishedLocal, snapshotLocal, + ProducerInvariant.next, ProducerInvariant.snapshot, + ProducerInvariant.Snapshot.currentBits] + | tokens => rfl + | records => simp [ForestStage.finalLocal, finishedLocal, snapshotLocal, + ProducerInvariant.snapshot, ProducerInvariant.recordBits] + | rootTable => simp [ForestStage.finalLocal, finishedLocal, snapshotLocal, + ProducerInvariant.snapshot, ProducerInvariant.rootValues, + ProducerInvariant.Snapshot.rootBits] + +def lowerSteps (V : NPVerifier) (input : List Bool) : Nat := + ForestStage.steps (InitializationTemplate.initializationTokens V input) + (freeInputs V input) + (ProducerInvariant.rootValues (VerifierCircuit.initialFrame V input)).reverse + (initialGates V input) [] + +variable {K Λ σ : Type} [DecidableEq K] + +def Ready (p : Ports K) (base : K → List Bool) (V : NPVerifier) + (input : List Bool) : Prop := + ∀ t, base (p t) = ForestStage.initialLocal (freeInputs V input) [] [] [] t + +def Prepared (p : Ports K) (base : K → List Bool) (V : NPVerifier) + (input : List Bool) : Prop := + ∀ t, base (p t) = preparedLocal V input t + +def result (p : Ports K) (base : K → List Bool) (V : NPVerifier) + (input : List Bool) : K → List Bool := + ForestPlacement.fill p base (finishedLocal V input) + +theorem prepared_emitted (p : Ports K) (base : K → List Bool) (V : NPVerifier) + (input : List Bool) (ready : Ready p base V input) : + Prepared p + (ClashMachine.emitted (p .tokens) (p (.lower .remaining)) base + (InitializationTemplate.initializationTokens V input)) V input := by + dsimp only [Ready] at ready + intro t + cases t with + | lower t => cases t <;> + simp [ClashMachine.emitted, p.injective.eq_iff, ready, preparedLocal, + ForestStage.initialLocal, encodeWord] + | tokens => simp [ClashMachine.emitted, p.injective.eq_iff, ready, + preparedLocal, ForestStage.initialLocal, tokenBits, tokenWords, encodeWords] + | records => simp [ClashMachine.emitted, p.injective.eq_iff, ready, + preparedLocal, ForestStage.initialLocal] + | rootTable => simp [ClashMachine.emitted, p.injective.eq_iff, ready, + preparedLocal, ForestStage.initialLocal] + +theorem result_emitted (p : Ports K) (base : K → List Bool) (V : NPVerifier) + (input : List Bool) (tokens : List Token) : + result p (ClashMachine.emitted (p .tokens) (p (.lower .remaining)) base tokens) + V input = result p base V input := by + classical + funext k + by_cases inside : ∃ t, p t = k + · obtain ⟨t, rfl⟩ := inside + simp only [result, ForestPlacement.fill_at] + · have outside : ∀ t, p t ≠ k := not_exists.mp inside + rw [result, ForestPlacement.fill_other p _ _ k outside, + result, ForestPlacement.fill_other p _ _ k outside] + exact ClashMachine.emitted_other (p .tokens) (p (.lower .remaining)) k + (Ne.symm (outside .tokens)) (Ne.symm (outside (.lower .remaining))) base tokens + +theorem lowerTrace (p : Ports K) (labels : ForestStage.Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State σ)) + (code : ∀ l, program (labels l) = ForestStage.statement p labels exit l) + (base : K → List Bool) (V : NPVerifier) (input : List Bool) + (ready : Prepared p base V input) (ambient : σ × Bool) : + (advance (TM2.step program))^[lowerSteps V input] + (some ⟨some (labels .reverseTokens), (ambient, none), base⟩) = + some ⟨exit, (ambient, none), result p base V input⟩ := by + have h := ForestStage.traceAt p labels exit program code base ambient + (InitializationTemplate.initializationTokens V input) (freeInputs V input) + (ProducerInvariant.next (VerifierCircuit.initialFrame V input)) + (ProducerInvariant.rootValues (VerifierCircuit.initialFrame V input)).reverse + (initialGates V input) [] [] (initialCompile V input) + have hprepared : ForestPlacement.fill p base (preparedLocal V input) = base := by + rw [show preparedLocal V input = (fun t => base (p t)) from funext fun t => (ready t).symm] + exact ForestPlacement.fill_self p base + rw [finalLocal_eq] at h + change (advance (TM2.step program))^[lowerSteps V input] + (some ⟨some (labels .reverseTokens), (ambient, none), + ForestPlacement.fill p base (preparedLocal V input)⟩) = + some ⟨exit, (ambient, none), result p base V input⟩ at h + simpa only [hprepared] using h + +omit [DecidableEq K] in +theorem result_at (p : Ports K) (base : K → List Bool) (V : NPVerifier) + (input : List Bool) (t : ForestStage.Tape) : + result p base V input (p t) = finishedLocal V input t := + ForestPlacement.fill_at p base _ t + +omit [DecidableEq K] in +theorem result_other (p : Ports K) (base : K → List Bool) (V : NPVerifier) + (input : List Bool) (k : K) (outside : ∀ t, p t ≠ k) : + result p base V input k = base k := + ForestPlacement.fill_other p base _ k outside + +def lowerTimePolynomial (V : NPVerifier) : Polynomial Nat := + ForestStage.timePolynomial.comp + (ProducerInvariant.budgetPolynomial V + ProducerInvariant.tapePolynomial V + 1) + +theorem lowerSteps_le (V : NPVerifier) (input : List Bool) : + lowerSteps V input ≤ (lowerTimePolynomial V).eval input.length := by + have roots := ProducerInvariant.step_roots + (Frame.initial (id : Fin (freeInputs V input) → Fin (freeInputs V input))) + (VerifierCircuit.initialExpressions V input) + have h := ForestStage.forest_steps_le Fin.val + (List.ofFn (VerifierCircuit.initialExpressions V input)) (freeInputs V input) [] + (fun i => i.isLt) + have rootEq : ProducerInvariant.rootValues (VerifierCircuit.initialFrame V input) = + Batch.roots (freeInputs V input) + (List.ofFn (VerifierCircuit.initialExpressions V input)) := by + simpa [ProducerInvariant.snapshot, ProducerInvariant.rootValues, + VerifierCircuit.initialFrame, Frame.initial, Fragment.empty, freeInputs] using roots + have hsteps : lowerSteps V input ≤ ForestStage.timePolynomial.eval + (freeInputs V input + Batch.cost (List.ofFn (VerifierCircuit.initialExpressions V input)) + + (tokenBits (InitializationTemplate.initializationTokens V input)).length + 1) := by + simpa only [lowerSteps, InitializationTemplate.initializationTokens_eq, rootEq, + initialGates, List.length_nil, Nat.add_zero] using h + have hg := VerifierCircuit.circuitOfVerifier_gates_le_polynomial V input + rw [VerifierCircuit.circuitOfVerifier_gate_count] at hg + have hb := ProducerInvariant.budgetPolynomial_eval V input + have ht := ProducerInvariant.initial_tokens_length_le V input + rw [← InitializationTemplate.initializationTokens_eq] at ht + have sizeBound : freeInputs V input + + Batch.cost (List.ofFn (VerifierCircuit.initialExpressions V input)) + + (tokenBits (InitializationTemplate.initializationTokens V input)).length + 1 ≤ + (ProducerInvariant.budgetPolynomial V + ProducerInvariant.tapePolynomial V + 1).eval + input.length := by + simp only [Polynomial.eval_add, Polynomial.eval_one] + dsimp only [freeInputs] + omega + exact hsteps.trans (by + rw [lowerTimePolynomial, Polynomial.eval_comp] + exact natPolynomial_eval_mono ForestStage.timePolynomial sizeBound) + +def lowerInTime (p : Ports K) (labels : ForestStage.Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State σ)) + (code : ∀ l, program (labels l) = ForestStage.statement p labels exit l) + (base : K → List Bool) (V : NPVerifier) (input : List Bool) + (ready : Prepared p base V input) (ambient : σ × Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .reverseTokens), (ambient, none), base⟩ + (some ⟨exit, (ambient, none), result p base V input⟩) + ((lowerTimePolynomial V).eval input.length) where + steps := lowerSteps V input + evals_in_steps := lowerTrace p labels exit program code base V input ready ambient + steps_le_m := lowerSteps_le V input + +structure FullPorts (K : Type) where + emit : InitializationAssembly.Tape 9 ↪ K + lower : ForestStage.Ports K + output_shared : emit .reversed = lower .tokens + count_shared : emit .count = lower (.lower .remaining) + +abbrev Label (V : NPVerifier) := InitializationAssembly.Label V ⊕ ForestStage.Label + +def entry (V : NPVerifier) : Label V := .inl .control + +def emitLabels {V : NPVerifier} (labels : Label V ↪ Λ) : + InitializationAssembly.Label V ↪ Λ := + ⟨fun l => labels (.inl l), fun _ _ h => Sum.inl.inj (labels.injective h)⟩ + +def statement (V : NPVerifier) (p : FullPorts K) (labels : Label V ↪ Λ) + (exit : Option Λ) : Label V → TM2.Stmt (fun _ : K => Bool) Λ (State σ) + | .inl l => InitializationAssembly.statement V p.emit (emitLabels labels) + (some (labels (.inr .reverseTokens))) l + | .inr l => ForestStage.statement p.lower (fun l => labels (.inr l)) exit l + +def Agrees (V : NPVerifier) (p : FullPorts K) (labels : Label V ↪ Λ) + (exit : Option Λ) (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State σ)) : Prop := + ∀ l, program (labels l) = statement V p labels exit l + +structure FullReady (V : NPVerifier) (p : FullPorts K) (base : K → List Bool) + (input : List Bool) : Prop where + emitter : InitializationAssembly.Ready V p.emit base input + lowerer : Ready p.lower base V input + +def steps (V : NPVerifier) (input : List Bool) : Nat := + InitializationAssembly.steps V input + lowerSteps V input + +theorem trace (V : NPVerifier) (p : FullPorts K) (labels : Label V ↪ Λ) + (exit : Option Λ) (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State σ)) + (ha : Agrees V p labels exit program) (base : K → List Bool) (input : List Bool) + (ready : FullReady V p base input) (ambient : σ) : + (advance (TM2.step program))^[steps V input] + (some ⟨some (labels (entry V)), ClashMachine.clean ambient, base⟩) = + some ⟨exit, ClashMachine.clean ambient, result p.lower base V input⟩ := by + have first := InitializationAssembly.trace V p.emit (emitLabels labels) + (some (labels (.inr .reverseTokens))) program (fun l => ha (.inl l)) + base input ready.emitter ambient + rw [p.output_shared, p.count_shared] at first + have second := lowerTrace p.lower (fun l => labels (.inr l)) exit program + (fun l => ha (.inr l)) + (ClashMachine.emitted (p.lower .tokens) (p.lower (.lower .remaining)) base + (InitializationTemplate.initializationTokens V input)) V input + (prepared_emitted p.lower base V input ready.lowerer) (ambient, false) + rw [result_emitted] at second + exact ClashMachine.chain first second + +def program (V : NPVerifier) (p : FullPorts K) : + Label V → TM2.Stmt (fun _ : K => Bool) (Label V) (State Unit) := + statement V p (Function.Embedding.refl _) none + +def machine (V : NPVerifier) [Fintype K] (p : FullPorts K) : FinTM2 where + K := K + k₀ := p.emit .rawInput + k₁ := p.lower .records + Γ := fun _ => Bool + Λ := Label V + main := entry V + σ := State Unit + initialState := ClashMachine.clean () + Γk₀Fin := inferInstance + m := program V p + +theorem machineTrace (V : NPVerifier) [Fintype K] (p : FullPorts K) + (base : K → List Bool) (input : List Bool) (ready : FullReady V p base input) : + (advance (machine V p).step)^[steps V input] + (some ⟨some (entry V), ClashMachine.clean (), base⟩) = + some ⟨none, ClashMachine.clean (), result p.lower base V input⟩ := + trace V p (Function.Embedding.refl _) none (program V p) (fun _ => rfl) + base input ready () + +def timePolynomial (V : NPVerifier) : Polynomial Nat := + InitializationAssembly.timePolynomial V + lowerTimePolynomial V + +theorem steps_le_timePolynomial (V : NPVerifier) (input : List Bool) : + steps V input ≤ (timePolynomial V).eval input.length := by + simpa only [steps, timePolynomial, Polynomial.eval_add] using + Nat.add_le_add (InitializationAssembly.steps_le_timePolynomial V input) + (lowerSteps_le V input) + +def verifierPlacedInPolynomialTime (V : NPVerifier) (p : FullPorts K) + (labels : Label V ↪ Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State σ)) + (ha : Agrees V p labels exit program) (base : K → List Bool) (input : List Bool) + (ready : FullReady V p base input) (ambient : σ) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels (entry V)), ClashMachine.clean ambient, base⟩ + (some ⟨exit, ClashMachine.clean ambient, result p.lower base V input⟩) + ((timePolynomial V).eval input.length) where + steps := steps V input + evals_in_steps := trace V p labels exit program ha base input ready ambient + steps_le_m := steps_le_timePolynomial V input + +def verifierInPolynomialTime (V : NPVerifier) [Fintype K] (p : FullPorts K) + (base : K → List Bool) (input : List Bool) (ready : FullReady V p base input) : + StateTransition.EvalsToInTime (machine V p).step + ⟨some (entry V), ClashMachine.clean (), base⟩ + (some ⟨none, ClashMachine.clean (), result p.lower base V input⟩) + ((timePolynomial V).eval input.length) := + verifierPlacedInPolynomialTime V p (Function.Embedding.refl _) none + (program V p) (fun _ => rfl) base input ready () + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.InitializationStage + +end + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.TransitionArena + + +open Turing MachineComposition + +inductive Extra + | cursor | capacity | position | address | value | scratch | copy | saveLeft | saveRight + | countdown | q | raw + deriving DecidableEq + +/-- A list enumerating every element of the type, which are all zero-argument constructors. (Generated by the `Fintype` deriving handler.)-/ +protected abbrev Extra.enumList : List Extra := [.cursor, .capacity, .position, .address, .value, + .scratch, .copy, .saveLeft, .saveRight, .countdown, .q, .raw] + +protected theorem Extra.enumList_getElem?_ctorIdx_eq (x : Extra) : + Extra.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem Extra.enumList_nodup : Extra.enumList.Nodup := by decide + +instance : Fintype Extra where + elems := ⟨Extra.enumList, Extra.enumList_nodup⟩ + complete x := by cases x <;> decide + +abbrev Tape := ForestStage.Tape ⊕ Extra +abbrev Alphabet (_ : Tape) := Bool +abbrev State := TermMachine.State + +def forestPorts : ForestStage.Tape ↪ Tape := + ⟨Sum.inl, Sum.inl_injective⟩ + +def termTape : TermMachine.Tape → Tape + | .cursor => .inr .cursor + | .capacity => .inr .capacity + | .roots => .inl .rootTable + | .count => .inl (.lower .remaining) + | .reversed => .inl .tokens + | .position => .inr .position + | .address => .inr .address + | .value => .inr .value + | .scratch => .inr .scratch + | .copy => .inr .copy + | .saveLeft => .inr .saveLeft + | .saveRight => .inr .saveRight + +def termPorts : TermMachine.Tape ↪ Tape where + toFun := termTape + inj' := by intro a b h; cases a <;> cases b <;> simp_all [termTape] + +@[simp] theorem termPorts_apply (tape : TermMachine.Tape) : termPorts tape = termTape tape := rfl + +def termInput (S : Nat) (snapshot : ProducerInvariant.Snapshot) : TermMachine.Input := + ⟨0, S, snapshot.roots⟩ + +def tapes (base : Tape → List Bool) (S remaining : Nat) + (snapshot : ProducerInvariant.Snapshot) : Tape → List Bool + | .inl (.lower .current) => encodeWord snapshot.current + | .inl (.lower .remaining) => encodeWord 0 + | .inl (.lower _) => [] + | .inl .tokens => [] + | .inl .records => snapshot.reversedRecords + | .inl .rootTable => encodeWords snapshot.roots + | .inr .cursor => encodeWord 0 + | .inr .capacity => encodeWord S + | .inr .countdown => encodeWord remaining + | .inr .q => base (.inr .q) + | .inr .raw => base (.inr .raw) + | .inr _ => [] + +def finishTapes (base : Tape → List Bool) (S : Nat) + (snapshot : ProducerInvariant.Snapshot) : Tape → List Bool := + Function.update (tapes base S 0 snapshot) (.inr .countdown) [] + +@[simp] theorem tapes_q (base : Tape → List Bool) (S remaining : Nat) + (snapshot : ProducerInvariant.Snapshot) : tapes base S remaining snapshot (.inr .q) = + base (.inr .q) := rfl + +@[simp] theorem tapes_raw (base : Tape → List Bool) (S remaining : Nat) + (snapshot : ProducerInvariant.Snapshot) : tapes base S remaining snapshot (.inr .raw) = + base (.inr .raw) := rfl + +@[simp] theorem tapes_capacity (base : Tape → List Bool) (S remaining : Nat) + (snapshot : ProducerInvariant.Snapshot) : + tapes base S remaining snapshot (.inr .capacity) = encodeWord S := rfl + +theorem termFrame (base : Tape → List Bool) (S remaining : Nat) + (snapshot : ProducerInvariant.Snapshot) : + TermMachine.Frame (termInput S snapshot) + (fun tape => tapes base S remaining snapshot (termPorts tape)) := by + refine ⟨rfl, rfl, rfl, ?_⟩ + intro tape ht + cases tape <;> simp_all [TermMachine.work, termTape, tapes] + +theorem tapes_countdown_tail (base : Tape → List Bool) (S remaining : Nat) + (snapshot : ProducerInvariant.Snapshot) : + Function.update (tapes base S (remaining + 1) snapshot) (.inr .countdown) + (tapes base S (remaining + 1) snapshot (.inr .countdown)).tail = + tapes base S remaining snapshot := by + funext tape + cases tape with + | inl tape => + cases tape with + | lower tape => cases tape <;> simp [tapes] + | tokens => simp [tapes] + | records => simp [tapes] + | rootTable => simp [tapes] + | inr tape => cases tape <;> simp [tapes, encodeWord, List.replicate_succ] + +def preparedTapes (base : Tape → List Bool) (S remaining : Nat) + (snapshot : ProducerInvariant.Snapshot) (tokens : List PostfixModel.Token) : Tape → List Bool := + Function.update + (Function.update (tapes base S remaining snapshot) (.inl .tokens) + (PostfixModel.tokenBits tokens).reverse) + (.inl (.lower .remaining)) (encodeWord tokens.length) + +theorem place_emitTapes (base : Tape → List Bool) (S remaining : Nat) + (snapshot : ProducerInvariant.Snapshot) (tokens : List PostfixModel.Token) : + ForestPlacement.fill termPorts (tapes base S remaining snapshot) + (TermMachine.emitTapes (fun tape => tapes base S remaining snapshot (termPorts tape)) tokens) = + preparedTapes base S remaining snapshot tokens := by + simp only [TermMachine.emitTapes, ForestPlacement.fill_update, ForestPlacement.fill_self] + simp [termTape, tapes, preparedTapes, encodeWord] + +theorem fill_forest (base : Tape → List Bool) (contents : ForestStage.Tape → List Bool) : + ForestPlacement.fill forestPorts base contents = + fun tape => match tape with + | .inl t => contents t + | .inr t => base (.inr t) := by + funext tape + cases tape with + | inl t => exact ForestPlacement.fill_at forestPorts base contents t + | inr t => + exact ForestPlacement.fill_other forestPorts base contents (.inr t) + (by intro i; simp [forestPorts]) + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.TransitionArena + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/InitializationTemplateLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/InitializationTemplateLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..05fda67b257deb2ed24ba4056e3c59d699a14b14 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/InitializationTemplateLemmas.lean @@ -0,0 +1,503 @@ +import OAI.Computability.PerfectCompleteness.Machines.PositionLemmas +import OAI.Computability.PerfectCompleteness.Machines.PostfixAlignment +import OAI.Computability.PerfectCompleteness.Machines.TransitionMachine +import OAI.Computability.PerfectCompleteness.Machines.TransitionTemplate +import OAI.Computability.PerfectCompleteness.Machines.VerifierCircuit + +namespace OAI + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.InitializationTemplate + +open StatementCircuit WitnessCircuit WitnessEncoding PostfixModel PostfixAlignment CircuitBatch + + +theorem exprTokens_disjoin {ι : Type*} (wire : ι → Nat) (es : List (Expr ι)) : + exprTokens wire (Expr.disjoin es) = forestTokens wire es ++ closeOr es.length := by + induction es with + | nil => simp [Expr.disjoin, exprTokens, forestTokens, closeOr] + | cons e es ih => + simp [Expr.disjoin, exprTokens, forestTokens_cons, ih, closeOr, + List.replicate_succ', List.append_assoc] + +theorem forestTokens_ofFn {ι : Type*} (wire : ι → Nat) (n : Nat) (es : Fin n → Expr ι) : + forestTokens wire (List.ofFn es) = (List.ofFn fun i => exprTokens wire (es i)).flatten := by + simp only [forestTokens, List.flatMap_def, List.map_ofFn, Function.comp_def] + +def muxTokens (condition yes no : List Token) : List Token := + condition ++ yes ++ [.and] ++ condition ++ [.not] ++ no ++ [.and, .or] + +theorem exprTokens_mux {ι : Type*} (wire : ι → Nat) (c y n : Expr ι) : + exprTokens wire (Expr.mux c y n) = + muxTokens (exprTokens wire c) (exprTokens wire y) (exprTokens wire n) := by + simp [Expr.mux, exprTokens, muxTokens, List.append_assoc] + +theorem nonemptyTokens_eq (q : Nat) : + nonemptyTokens q = exprTokens Fin.val (nonemptyExpr q) := by + rw [nonemptyExpr, exprTokens_disjoin, forestTokens_ofFn] + simp [nonemptyTokens, forTokens_eq_ofFn, selectorExpr, exprTokens] + +theorem clashPairTokens_eq (q : Nat) (i j : Fin (q + 1)) : + clashPairTokens i.val j.val = exprTokens Fin.val (clashPairExpr q i j) := by + by_cases h : i = j + · subst j; simp [clashPairTokens, clashPairExpr, exprTokens] + · have hv : i.val ≠ j.val := fun hval => h (Fin.ext hval) + simp [clashPairTokens, clashPairExpr, h, hv, selectorExpr, exprTokens] + +theorem clashRowTokens_eq (q : Nat) (i : Fin (q + 1)) : + clashRowTokens q i.val = + exprTokens Fin.val (Expr.disjoin (List.ofFn (clashPairExpr q i))) := by + rw [exprTokens_disjoin, forestTokens_ofFn] + simp only [clashRowTokens, forTokens_eq_ofFn, List.length_ofFn] + apply congrArg (fun xs : List (List Token) => xs.flatten ++ closeOr (q + 1)) + apply congrArg List.ofFn + funext j + exact clashPairTokens_eq q i j + +theorem clashTokens_eq (q : Nat) : + clashTokens q = exprTokens Fin.val (clashExpr q) := by + rw [clashExpr, exprTokens_disjoin, forestTokens_ofFn] + simp only [clashTokens, forTokens_eq_ofFn, List.length_ofFn] + apply congrArg (fun xs : List (List Token) => xs.flatten ++ closeOr (q + 1)) + apply congrArg List.ofFn + funext i + exact clashRowTokens_eq q i + +theorem validityTokens_eq (q : Nat) : + validityTokens q = exprTokens Fin.val (validityExpr q) := by + simp [validityTokens, validityExpr, exprTokens, nonemptyTokens_eq, + clashTokens_eq, List.append_assoc] + +theorem presenceTokens_eq (q n : Nat) : + presenceTokens q n = exprTokens Fin.val (presenceExpr q n) := by + rw [presenceExpr, exprTokens_disjoin, forestTokens_ofFn] + simp [presenceTokens, forTokens_eq_ofFn, selectorExpr, exprTokens] + +section Symbols + +variable {A : Type*} [DecidableEq A] + +def payloadSymbolTokens (q : Nat) (f : Bool → A) (i : Nat) (a : Option A) : List Token := + [.input (q + 1 + i), .const (decide (some (f true) = a)), .and, + .input (q + 1 + i), .not, .const (decide (some (f false) = a)), .and, .or] + +theorem payloadSymbolTokens_eq (q : Nat) (f : Bool → A) (i : Fin q) (a : Option A) : + payloadSymbolTokens q f i.val a = exprTokens Fin.val (payloadSymbolExpr q f i a) := by + simp [payloadSymbolExpr, payloadSymbolTokens, exprTokens_mux, payloadExpr, + exprTokens, muxTokens] + +def inputCellTokens (q : Nat) (input : List Bool) (f : Bool → A) (n : Nat) (a : Option A) : + List Token := + if n < (inputPrefix input).length then [.const (decide (((inputPrefix input)[n]?).map f = a))] + else if n - (inputPrefix input).length < q then + muxTokens (presenceTokens q (n - (inputPrefix input).length)) + (payloadSymbolTokens q f (n - (inputPrefix input).length) a) + [.const (decide ((none : Option A) = a))] + else [.const (decide ((none : Option A) = a))] + +theorem inputCellTokens_eq (q : Nat) (input : List Bool) (f : Bool → A) (n : Nat) (a : Option A) : + inputCellTokens q input f n a = exprTokens Fin.val (inputCellExpr q input f n a) := by + by_cases hp : n < (inputPrefix input).length + · simp only [inputCellTokens, inputCellExpr, ite_eq_left hp, exprTokens] + · by_cases hq : n - (inputPrefix input).length < q + · simp only [inputCellTokens, inputCellExpr, hp, ite_false, hq, ite_true, dite_eq_left] + rw [exprTokens_mux, ← presenceTokens_eq, ← payloadSymbolTokens_eq] + rfl + · simp only [inputCellTokens, inputCellExpr, ite_eq_right hp, ite_eq_right hq, + dite_eq_right hq, exprTokens] + +end Symbols + +section Initial + +variable (V : NPVerifier) +variable [DecidableEq V.computation.tm.Λ] [DecidableEq V.computation.tm.σ] +variable [∀ k, DecidableEq (V.computation.tm.Γ k)] + +def initialCellTokens (input : List Bool) (S : Nat) (k : V.computation.tm.K) + (i : Fin S) (a : Option (V.computation.tm.Γ k)) : List Token := + if h : k = V.computation.tm.k₀ then by + subst k + exact inputCellTokens (V.witnessBound.eval input.length) input + V.computation.inputAlphabet.invFun i.val a + else [.const (decide ((none : Option (V.computation.tm.Γ k)) = a))] + +omit [DecidableEq V.computation.tm.Λ] [DecidableEq V.computation.tm.σ] in +theorem initialCellTokens_eq (input : List Bool) (S : Nat) (k : V.computation.tm.K) + (i : Fin S) (a : Option (V.computation.tm.Γ k)) : + initialCellTokens V input S k i a = exprTokens Fin.val (initialCellExpr V input S k i a) := by + by_cases hk : k = V.computation.tm.k₀ + · subst k + simpa [initialCellTokens, initialCellExpr] using + inputCellTokens_eq (V.witnessBound.eval input.length) input + V.computation.inputAlphabet.invFun i.val a + · simp [initialCellTokens, initialCellExpr, hk, exprTokens] + +def initTokens (input : List Bool) (S : Nat) : + ConfigBit V.computation.tm.Γ V.computation.tm.Λ V.computation.tm.σ S → List Token + | .inl label => [.const (decide (some V.computation.tm.main = label))] + | .inr (.inl state) => [.const (decide (V.computation.tm.initialState = state))] + | .inr (.inr ⟨k, i, a⟩) => initialCellTokens V input S k i a + +theorem initTokens_eq (input : List Bool) (S : Nat) + (bit : ConfigBit V.computation.tm.Γ V.computation.tm.Λ V.computation.tm.σ S) : + initTokens V input S bit = exprTokens Fin.val (initExpr V input S bit) := by + rcases bit with label | (state | ⟨k, i, a⟩) + · rfl + · rfl + · exact initialCellTokens_eq V input S k i a + +theorem initTokens_length_le (input : List Bool) (S : Nat) + (bit : ConfigBit V.computation.tm.Γ V.computation.tm.Λ V.computation.tm.σ S) : + (initTokens V input S bit).length ≤ 8 * (V.witnessBound.eval input.length + 1) + 15 := by + rw [initTokens_eq, exprTokens_length] + exact size_initExpr_le V input S bit + +end Initial + +theorem validityTokens_length_le (q : Nat) : (validityTokens q).length ≤ 12 * (q + 1) ^ 2 := by + rw [validityTokens_eq, exprTokens_length] + exact size_validityExpr_le q + +noncomputable section Frame + +open VerifierCircuit + +local instance labelDecidable (V : NPVerifier) : DecidableEq V.computation.tm.Λ := Classical.decEq _ +local instance stateDecidable (V : NPVerifier) : DecidableEq V.computation.tm.σ := Classical.decEq _ +local instance alphabetDecidable (V : NPVerifier) : ∀ k, DecidableEq (V.computation.tm.Γ k) := + fun _ => Classical.decEq _ + +def configurationBody (V : NPVerifier) (input : List Bool) (j : Nat) : List Token := + if hj : j < width V input then + initTokens V input (capacity V input.length) ((bitEquiv V input).symm ⟨j, hj⟩) + else [] + +theorem configurationBody_index (V : NPVerifier) (input : List Bool) (bit : Bit V input) : + configurationBody V input (bitEquiv V input bit).val = + initTokens V input (capacity V input.length) bit := by + rw [configurationBody, dite_eq_left (bitEquiv V input bit).isLt] + change initTokens V input (capacity V input.length) + ((bitEquiv V input).symm (bitEquiv V input bit)) = _ + rw [Equiv.symm_apply_apply] + +theorem configurationBody_label (V : NPVerifier) (input : List Bool) + (label : Option V.computation.tm.Λ) : + configurationBody V input ((indexing V).labels label).val = + [.const (decide (some V.computation.tm.main = label))] := by + simpa only [bitEquiv, ConfigIndex.Indexing.configIndex_label, initTokens] using + configurationBody_index V input (.inl label) + +theorem configurationBody_state (V : NPVerifier) (input : List Bool) + (state : V.computation.tm.σ) : + configurationBody V input ((indexing V).labelCount + ((indexing V).states state).val) = + [.const (decide (V.computation.tm.initialState = state))] := by + simpa only [bitEquiv, ConfigIndex.Indexing.configIndex_state, initTokens] using + configurationBody_index V input (.inr (.inl state)) + +theorem configurationBody_cell (V : NPVerifier) (input : List Bool) + (k : V.computation.tm.K) (i : Fin (capacity V input.length)) + (a : Option (V.computation.tm.Γ k)) : + configurationBody V input ((indexing V).labelCount + (indexing V).stateCount + + i.val * (indexing V).symbolCount + ((indexing V).symbols ⟨k, a⟩).val) = + initialCellTokens V input (capacity V input.length) k i a := by + simpa only [bitEquiv, ConfigIndex.Indexing.configIndex_cell, initTokens] using + configurationBody_index V input (.inr (.inr ⟨k, i, a⟩)) + +def initializationTokens (V : NPVerifier) (input : List Bool) : List Token := + forTokens (width V input) (configurationBody V input) ++ + validityTokens (V.witnessBound.eval input.length) + +def tokenBound (V : NPVerifier) (input : List Bool) : Nat := + width V input * (8 * (V.witnessBound.eval input.length + 1) + 15) + + 12 * (V.witnessBound.eval input.length + 1) ^ 2 + +theorem initializationTokens_eq (V : NPVerifier) (input : List Bool) : + initializationTokens V input = + forestTokens Fin.val (List.ofFn (initialExpressions V input)) := by + rw [forestTokens_ofFn, List.ofFn_succ'] + simp only [List.concat_eq_append, List.flatten_append, List.flatten_cons, + List.flatten_nil, List.append_nil] + simp only [initialExpressions, Fin.lastCases_castSucc, Fin.lastCases_last] + simp only [initializationTokens, forTokens_eq_ofFn, configurationBody, Fin.isLt, dite_eq_left] + rw [validityTokens_eq] + apply congrArg (fun xs : List (List Token) => xs.flatten ++ + exprTokens Fin.val (validityExpr (V.witnessBound.eval input.length))) + apply congrArg List.ofFn + funext i + exact initTokens_eq V input (capacity V input.length) ((bitEquiv V input).symm i) + +theorem initializationTokens_length (V : NPVerifier) (input : List Bool) : + (initializationTokens V input).length = Batch.cost (List.ofFn (initialExpressions V input)) := by + rw [initializationTokens_eq, forestTokens_length] + +theorem initialization_inputBits (V : NPVerifier) (input : List Bool) (start : Nat) : + PostfixModel.inputBits start (initializationTokens V input) = + encodeWords [start, Batch.cost (List.ofFn (initialExpressions V input))] ++ + tokenBits (initializationTokens V input) := by + simp only [PostfixModel.inputBits, initializationTokens_length] + +theorem initializationTokens_length_le (V : NPVerifier) (input : List Bool) : + (initializationTokens V input).length ≤ tokenBound V input := by + have h := forTokens_length_le (width V input) (configurationBody V input) + (8 * (V.witnessBound.eval input.length + 1) + 15) (by + intro j hj + simp only [configurationBody, dite_eq_left hj] + exact initTokens_length_le V input (capacity V input.length) ((bitEquiv V input).symm ⟨j, hj⟩)) + simpa only [initializationTokens, List.length_append, tokenBound] using + Nat.add_le_add h (validityTokens_length_le (V.witnessBound.eval input.length)) + +theorem initializationTokens_compile (V : NPVerifier) (input : List Bool) (start : Nat) + (roots : List Nat) : + compileTokens start roots (initializationTokens V input) = + some (start + Batch.cost (List.ofFn (initialExpressions V input)), + (Batch.roots start (List.ofFn (initialExpressions V input))).reverse ++ roots, + Batch.gates Fin.val start (List.ofFn (initialExpressions V input))) := by + rw [initializationTokens_eq] + exact compile_forestTokens _ _ _ _ + +theorem initialization_tokenWords_bounded (V : NPVerifier) (input : List Bool) + (word : Nat) (h : word ∈ tokenWords (initializationTokens V input)) : + word ≤ max 5 (2 * V.witnessBound.eval input.length + 1) := by + rw [initializationTokens_eq] at h + exact forest_tokenWords_bounded Fin.val _ _ (fun i => i.isLt) word h + +theorem initialization_tokenBits_length_le (V : NPVerifier) (input : List Bool) : + (tokenBits (initializationTokens V input)).length ≤ + 2 * tokenBound V input * (2 * V.witnessBound.eval input.length + 7) := by + have hw := tokenWords_length_le (initializationTokens V input) + have ht := initializationTokens_length_le V input + have hb := encodeWords_length_le (tokenWords (initializationTokens V input)) + (2 * V.witnessBound.eval input.length + 6) (by + intro word hm + have hh := initialization_tokenWords_bounded V input word hm + have hm' : max 5 (2 * V.witnessBound.eval input.length + 1) ≤ + 2 * V.witnessBound.eval input.length + 6 := by omega + exact hh.trans hm') + have hwords : (tokenWords (initializationTokens V input)).length ≤ 2 * tokenBound V input := + hw.trans (Nat.mul_le_mul_left 2 ht) + exact hb.trans (Nat.mul_le_mul_right _ hwords) + +end Frame + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.InitializationTemplate + + +noncomputable section +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.AcceptanceTemplate + + +open StatementCircuit VerifierCircuit PostfixModel PostfixAlignment InitializationTemplate + +local instance (V : NPVerifier) : DecidableEq V.computation.tm.Λ := Classical.decEq _ +local instance (V : NPVerifier) : DecidableEq V.computation.tm.σ := Classical.decEq _ +local instance (V : NPVerifier) : ∀ k, DecidableEq (V.computation.tm.Γ k) := + fun _ => Classical.decEq _ + +def headMask (V : NPVerifier) (k : V.computation.tm.K) + (symbol : Option (V.computation.tm.Γ k)) : Bool := by + by_cases h : k = V.computation.tm.k₁ + · subst k + exact decide (some (V.computation.outputAlphabet.invFun true) = symbol) + · exact decide ((none : Option (V.computation.tm.Γ k)) = symbol) + +theorem accepting_label (V : NPVerifier) (S : Nat) (label : Option V.computation.tm.Λ) : + configEncoding S (accepting V) (.inl label) = decide (none = label) := rfl + +theorem accepting_state (V : NPVerifier) (S : Nat) (state : V.computation.tm.σ) : + configEncoding S (accepting V) (.inr (.inl state)) = + decide (V.computation.tm.initialState = state) := rfl + +theorem accepting_cell (V : NPVerifier) (S : Nat) (k : V.computation.tm.K) + (i : Fin S) (symbol : Option (V.computation.tm.Γ k)) : + configEncoding S (accepting V) (.inr (.inr ⟨k, i, symbol⟩)) = + if i.val = 0 then headMask V k symbol else decide ((none : Option (V.computation.tm.Γ k)) = symbol) := by + by_cases hk : k = V.computation.tm.k₁ + · subst k + rcases i with ⟨i, hi⟩ + cases i <;> simp [configEncoding, inputEncoding, accepting, Turing.haltList, + StackEncoding.encode, headMask] + · simp [configEncoding, inputEncoding, accepting, Turing.haltList, hk, + StackEncoding.encode, headMask] + +def targetBit (V : NPVerifier) (input : List Bool) (j : Fin (width V input)) : Bool := + configEncoding (capacity V input.length) (accepting V) ((bitEquiv V input).symm j) + +def mismatchTokens (expected : Bool) (wire : Nat) : List Token := + if expected then [.input wire, .not] else [.input wire] + +def tokens (V : NPVerifier) (input : List Bool) + (wire : Fin (width V input + 1) → Nat) : List Token := + [.input (wire (Fin.last (width V input)))] ++ + (List.ofFn fun j : Fin (width V input) => + mismatchTokens (targetBit V input j) (wire j.castSucc)).flatten ++ + closeOr (width V input) ++ [.not, .and] + +theorem mismatchTokens_eq (V : NPVerifier) (input : List Bool) + (wire : Fin (width V input + 1) → Nat) (j : Fin (width V input)) : + mismatchTokens (targetBit V input j) (wire j.castSucc) = + exprTokens wire (mismatchExpr V input j) := by + by_cases h : configEncoding (capacity V input.length) (accepting V) + ((bitEquiv V input).symm j) = true + · simp [mismatchTokens, targetBit, mismatchExpr, exprTokens, h] + · simp [mismatchTokens, targetBit, mismatchExpr, exprTokens, h] + +theorem tokens_eq (V : NPVerifier) (input : List Bool) + (wire : Fin (width V input + 1) → Nat) : + tokens V input wire = exprTokens wire (acceptanceExpr V input) := by + simp only [acceptanceExpr, exprTokens, exprTokens_disjoin, + forestTokens_ofFn, List.length_ofFn] + simp [tokens, mismatchTokens_eq, List.append_assoc] + +theorem compile_tokens (V : NPVerifier) (input : List Bool) + (wire : Fin (width V input + 1) → Nat) (start : Nat) (oldRoots : List Nat) : + compileTokens start oldRoots (tokens V input wire) = + some (start + (acceptanceExpr V input).size, + (acceptanceExpr V input).root start :: oldRoots, + (acceptanceExpr V input).gates wire start) := by + rw [tokens_eq] + exact compile_exprTokens wire (acceptanceExpr V input) start oldRoots + +theorem tokens_length_le (V : NPVerifier) (input : List Bool) + (wire : Fin (width V input + 1) → Nat) : + (tokens V input wire).length ≤ 3 * width V input + 4 := by + rw [tokens_eq, exprTokens_length] + exact acceptanceExpr_size_le V input + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.AcceptanceTemplate + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.AcceptancePlan + + +open StatementCircuit TransitionTemplate AcceptanceTemplate +open PostfixModel VerifierCircuit TermMachine + +local instance (V : NPVerifier) : Fintype V.computation.tm.Λ := V.computation.tm.ΛFin +local instance (V : NPVerifier) : Fintype V.computation.tm.σ := V.computation.tm.σFin +local instance (V : NPVerifier) : ∀ k, Fintype (V.computation.tm.Γ k) := V.finiteAlphabet +local instance (V : NPVerifier) : DecidableEq V.computation.tm.Λ := Classical.decEq _ +local instance (V : NPVerifier) : DecidableEq V.computation.tm.σ := Classical.decEq _ +local instance (V : NPVerifier) : ∀ k, DecidableEq (V.computation.tm.Γ k) := + fun _ => Classical.decEq _ + +def negateIf {K σ : Type} {Γ : K → Type} (condition : Bool) (e : Term Γ σ) : Term Γ σ := + if condition then .not e else e + +def stateTemplate (V : NPVerifier) (state : V.computation.tm.σ) : + Global (Γ := V.computation.tm.Γ) (Λ := V.computation.tm.Λ) (σ := V.computation.tm.σ) := + .data (negateIf (decide (V.computation.tm.initialState = state)) (.state state)) + +def cellTemplate (V : NPVerifier) (k : V.computation.tm.K) + (symbol : Option (V.computation.tm.Γ k)) : + Global (Γ := V.computation.tm.Γ) (Λ := V.computation.tm.Λ) (σ := V.computation.tm.σ) := + .data (.atZero .current + (negateIf (headMask V k symbol) (.cell k .current symbol)) + (negateIf (decide ((none : Option (V.computation.tm.Γ k)) = symbol)) + (.cell k .current symbol))) + +def plan (V : NPVerifier) : + TransitionMachine.Plan (Γ := V.computation.tm.Γ) (Λ := V.computation.tm.Λ) + (σ := V.computation.tm.σ) where + «prefix» := + ((List.finRange (indexing V).labelCount).map fun i => + (Global.label ((indexing V).labels.symm i), + decide ((none : Option V.computation.tm.Λ) = (indexing V).labels.symm i))) ++ + ((List.finRange (indexing V).stateCount).map fun i => + (stateTemplate V ((indexing V).states.symm i), false)) + cells := (List.finRange (indexing V).symbolCount).map fun i => + let symbol := (indexing V).symbols.symm i + cellTemplate V symbol.1 symbol.2 + carry := false + +def mismatchForest (V : NPVerifier) (roots : List Nat) (S : Nat) : List Token := + (outputOrder (indexing V) S).flatMap fun bit => + mismatchTokens (configEncoding S (accepting V) bit) + (configWire (indexing V) roots S bit) + +theorem label_tokens (V : NPVerifier) (roots : List Nat) (S cursor : Nat) + (label : Option V.computation.tm.Λ) : + (Global.label label).tokens (indexing V) roots S cursor ++ + (if decide ((none : Option V.computation.tm.Λ) = label) then [.not] else []) = + mismatchTokens (configEncoding S (accepting V) (.inl label)) + (configWire (indexing V) roots S (.inl label)) := by + rw [accepting_label] + by_cases h : (none : Option V.computation.tm.Λ) = label + · simp [Global.tokens, configWire, mismatchTokens, h] + · simp [Global.tokens, configWire, mismatchTokens, h] + +theorem state_tokens (V : NPVerifier) (roots : List Nat) (S cursor : Nat) + (state : V.computation.tm.σ) : + (stateTemplate V state).tokens (indexing V) roots S cursor = + mismatchTokens (configEncoding S (accepting V) (.inr (.inl state))) + (configWire (indexing V) roots S (.inr (.inl state))) := by + rw [accepting_state] + by_cases h : V.computation.tm.initialState = state + · simp [stateTemplate, negateIf, Global.tokens, Term.tokens, configWire, mismatchTokens, h] + · simp [stateTemplate, negateIf, Global.tokens, Term.tokens, configWire, mismatchTokens, h] + +theorem cell_tokens (V : NPVerifier) (roots : List Nat) (S : Nat) + (i : Fin S) (k : V.computation.tm.K) (symbol : Option (V.computation.tm.Γ k)) : + (cellTemplate V k symbol).tokens (indexing V) roots S i.val = + mismatchTokens (configEncoding S (accepting V) (.inr (.inr ⟨k, i, symbol⟩))) + (configWire (indexing V) roots S (.inr (.inr ⟨k, i, symbol⟩))) := by + rw [accepting_cell] + have hS : 0 < S := lt_of_le_of_lt (Nat.zero_le i.val) i.isLt + by_cases hi : i.val = 0 + · cases hb : headMask V k symbol <;> + simp [cellTemplate, negateIf, Global.tokens, Term.tokens, Position.eval, + hS, hi, hb, mismatchTokens, configWire] + · by_cases hs : (none : Option (V.computation.tm.Γ k)) = symbol + · simp [cellTemplate, negateIf, Global.tokens, Term.tokens, Position.eval, + i.isLt, hi, hs, mismatchTokens, configWire] + · simp [cellTemplate, negateIf, Global.tokens, Term.tokens, Position.eval, + i.isLt, hi, hs, mismatchTokens, configWire] + +theorem outputTokens_eq (V : NPVerifier) (input : TermMachine.Input) : + TransitionMachine.outputTokens (indexing V) (plan V) input = + mismatchForest V input.roots input.capacity := by + rw [TransitionMachine.outputTokens_eq_blocks] + simp only [mismatchForest, OutputOrder.outputOrder_eq_blocks, List.flatMap_append, + List.flatMap_map, List.flatMap_assoc] + simp only [plan, TransitionMachine.prefixTokens, List.flatMap_append, List.flatMap_map, + TransitionMachine.cellTokens, TransitionMachine.listTokens, + TermMachine.globalTokens, TransitionMachine.withCursor_roots, + TransitionMachine.withCursor_capacity, TransitionMachine.withCursor_cursor, + TransitionMachine.carriedTokens, Bool.false_eq_true, ↓reduceIte, List.append_nil] + congr 1 + · congr 1 + · apply List.flatMap_congr + intro i _ + exact label_tokens V input.roots input.capacity 0 ((indexing V).labels.symm i) + · apply List.flatMap_congr + intro i _ + simpa using state_tokens V input.roots input.capacity 0 ((indexing V).states.symm i) + · apply List.flatMap_congr + intro i _ + apply List.flatMap_congr + intro j _ + exact cell_tokens V input.roots input.capacity i + ((indexing V).symbols.symm j).1 ((indexing V).symbols.symm j).2 + +theorem mismatchForest_circuit (V : NPVerifier) (input : List Bool) (roots : List Nat) : + mismatchForest V roots (capacity V input.length) = + (List.ofFn fun j : Fin (width V input) => + mismatchTokens (targetBit V input j) (rootLookup roots j.val)).flatten := by + simp only [mismatchForest, outputOrder, List.flatMap_def, + Function.comp_def, configWire, Equiv.apply_symm_apply, targetBit, + ← List.ofFn_eq_map, List.map_ofFn, bitEquiv] + +theorem fullTokens_eq (V : NPVerifier) (input : List Bool) (roots : List Nat) : + AcceptanceTemplate.tokens V input (fun j => rootLookup roots j.val) = + [.input (rootLookup roots (width V input))] ++ + TransitionMachine.outputTokens (indexing V) (plan V) + ⟨0, capacity V input.length, roots⟩ ++ + InitializationTemplate.closeOr (width V input) ++ [.not, .and] := by + rw [outputTokens_eq, mismatchForest_circuit] + rfl + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.AcceptancePlan + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/InputCellsMachineLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/InputCellsMachineLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..6496918b4dd25c054df61fa5acbd53aa0df01b5a --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/InputCellsMachineLemmas.lean @@ -0,0 +1,763 @@ +import OAI.Computability.PerfectCompleteness.Machines.InitializationTemplateLemmas +import OAI.Computability.UniqueGames.Machines.MachineCopy +import OAI.Computability.UniqueGames.Reduction.MachineSubstitution + +namespace OAI + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.InputCellsMachine + +open Turing PostfixModel InitializationTemplate +open Reduction.MachineSubstitution (pushWord stepAux_pushWord) + + +variable {K Λ σ : Type} [DecidableEq K] {A : Nat} + +abbrev Ports (K : Type) := Fin 3 ↪ K +abbrev Alphabet (_ : K) := Bool + +def tapes (p : Ports K) (base : K → List Bool) (input output count : List Bool) : + K → List Bool := + Function.update (Function.update (Function.update base (p 0) input) (p 1) output) (p 2) count + +@[simp] theorem tapes_input (p : Ports K) (base : K → List Bool) + (input output count : List Bool) : tapes p base input output count (p 0) = input := by + simp [tapes, p.injective.ne (by decide : (0 : Fin 3) ≠ 1), + p.injective.ne (by decide : (0 : Fin 3) ≠ 2)] + +@[simp] theorem tapes_output (p : Ports K) (base : K → List Bool) + (input output count : List Bool) : tapes p base input output count (p 1) = output := by + simp [tapes, p.injective.ne (by decide : (1 : Fin 3) ≠ 2)] + +@[simp] theorem tapes_count (p : Ports K) (base : K → List Bool) + (input output count : List Bool) : tapes p base input output count (p 2) = count := by + simp [tapes] + +theorem tapes_other (p : Ports K) (base : K → List Bool) + (input output count : List Bool) (k : K) (hk : ∀ j, k ≠ p j) : + tapes p base input output count k = base k := by + simp [tapes, hk] + +theorem update_input (p : Ports K) (base : K → List Bool) + (input output count replacement : List Bool) : + Function.update (tapes p base input output count) (p 0) replacement = + tapes p base replacement output count := by + funext k + by_cases hk : ∃ j, p j = k + · obtain ⟨j, rfl⟩ := hk + fin_cases j <;> simp [tapes, p.injective.eq_iff] + · have hn : ∀ j, k ≠ p j := fun j h => hk ⟨j, h.symm⟩ + simp [tapes, hn] + +theorem update_output (p : Ports K) (base : K → List Bool) + (input output count replacement : List Bool) : + Function.update (tapes p base input output count) (p 1) replacement = + tapes p base input replacement count := by + funext k + by_cases hk : ∃ j, p j = k + · obtain ⟨j, rfl⟩ := hk + fin_cases j <;> simp [tapes, p.injective.eq_iff] + · have hn : ∀ j, k ≠ p j := fun j h => hk ⟨j, h.symm⟩ + simp [tapes, hn] + +theorem update_count (p : Ports K) (base : K → List Bool) + (input output count replacement : List Bool) : + Function.update (tapes p base input output count) (p 2) replacement = + tapes p base input output replacement := by + simp [tapes] + +abbrev TruthTable (A : Nat) := Bool → Fin A → Bool + +def tableAt (table : TruthTable A) (bit : Bool) (i : Nat) : Bool := + if hi : i < A then table bit ⟨i, hi⟩ else false + +def rowFrom (table : TruthTable A) (bit : Bool) (start count : Nat) : List Token := + forTokens count (fun j => [.const (tableAt table bit (start + j))]) + +def rowTokens (table : TruthTable A) (bit : Bool) : List Token := rowFrom table bit 0 A + +def streamTokens (table : TruthTable A) (input : List Bool) : List Token := + input.flatMap (rowTokens table) + +theorem rowFrom_succ (table : TruthTable A) (bit : Bool) (start count : Nat) : + rowFrom table bit start (count + 1) = + .const (tableAt table bit start) :: rowFrom table bit (start + 1) count := by + simp only [rowFrom, forTokens_succ_first, Nat.add_zero, List.singleton_append] + congr 1 + apply forTokens_congr + intro j _ + simp only [Nat.add_assoc, Nat.add_comm 1 j] + +@[simp] theorem rowFrom_length (table : TruthTable A) (bit : Bool) (start count : Nat) : + (rowFrom table bit start count).length = count := by + simpa only [rowFrom, Nat.mul_one] using + forTokens_length_eq count (fun j => [.const (tableAt table bit (start + j))]) 1 + (fun _ _ => rfl) + +@[simp] theorem streamTokens_length (table : TruthTable A) (input : List Bool) : + (streamTokens table input).length = A * input.length := by + induction input with + | nil => simp [streamTokens] + | cons bit input ih => + simp only [streamTokens, List.flatMap_cons, List.length_append, rowTokens, + rowFrom_length, List.length_cons] at * + rw [ih, Nat.mul_add, Nat.mul_one] + omega + +theorem streamTokens_eq_rows (table : TruthTable A) (input : List Bool) : + streamTokens table input = + (List.ofFn fun i : Fin input.length => rowTokens table input[i.val]).flatten := by + rw [List.ofFn_getElem_eq_map] + rfl + +theorem tokenBits_cons (token : Token) (tokens : List Token) : + tokenBits (token :: tokens) = token.bits ++ tokenBits tokens := by + simp [tokenBits, tokenWords, Token.bits] + +theorem tokenBits_append (first second : List Token) : + tokenBits (first ++ second) = tokenBits first ++ tokenBits second := by + simp [tokenBits, tokenWords] + +inductive Label (symbols : Nat) + | scan + | emit (bit : Bool) (index : Fin (symbols + 1)) + deriving DecidableEq, Fintype + +def statement (p : Ports K) (label : Label A ↪ Λ) (exit : Option Λ) + (table : TruthTable A) : Label A → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) + | .scan => + .pop (p 0) (fun state head => (state.1, head)) + (.branch (fun state => state.2.isSome) + (.goto fun state => label (.emit (state.2.getD false) 0)) + (.load (fun state => (state.1, none)) + (Reduction.MachineTransfer.exitAt (p 0) exit))) + | .emit bit i => + if hi : i.val < A then + pushWord (p 1) (Token.bits (.const (table bit ⟨i.val, hi⟩))) + (.push (p 2) (fun _ => true) + (.goto fun _ => label (.emit bit ⟨i.val + 1, by omega⟩))) + else .load (fun state => (state.1, none)) (.goto fun _ => label .scan) + +def Agrees (p : Ports K) (label : Label A ↪ Λ) (exit : Option Λ) (table : TruthTable A) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) : Prop := + ∀ l, program (label l) = statement p label exit table l + +def EmitAgrees (p : Ports K) (label : Label A ↪ Λ) (exit : Option Λ) (table : TruthTable A) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) : Prop := + ∀ bit i, program (label (.emit bit i)) = statement p label exit table (.emit bit i) + +theorem scanStep_nil (p : Ports K) (label : Label A ↪ Λ) (exit : Option Λ) (table : TruthTable A) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (ha : Agrees p label exit table program) (base : K → List Bool) + (output count : List Bool) (ambient : σ) (register : Option Bool) : + TM2.step program ⟨some (label .scan), (ambient, register), tapes p base [] output count⟩ = + some ⟨exit, (ambient, none), tapes p base [] output count⟩ := by + change some (TM2.stepAux (program (label .scan)) _ _) = _ + rw [ha .scan] + cases exit <;> simp [statement, TM2.stepAux, Reduction.MachineTransfer.exitAt, update_input] + +theorem scanStep_cons (p : Ports K) (label : Label A ↪ Λ) (exit : Option Λ) (table : TruthTable A) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (ha : Agrees p label exit table program) (base : K → List Bool) + (bit : Bool) (input output count : List Bool) (ambient : σ) (register : Option Bool) : + TM2.step program + ⟨some (label .scan), (ambient, register), tapes p base (bit :: input) output count⟩ = + some ⟨some (label (.emit bit 0)), (ambient, some bit), tapes p base input output count⟩ := by + change some (TM2.stepAux (program (label .scan)) _ _) = _ + rw [ha .scan] + simp [statement, TM2.stepAux, update_input] + +theorem emitStep (p : Ports K) (label : Label A ↪ Λ) (exit : Option Λ) (table : TruthTable A) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (ha : EmitAgrees p label exit table program) (base : K → List Bool) + (bit : Bool) (i : Nat) (hi : i < A) (input output count : List Bool) + (ambient : σ) (register : Option Bool) : + TM2.step program + ⟨some (label (.emit bit ⟨i, by omega⟩)), (ambient, register), tapes p base input output count⟩ = + some ⟨some (label (.emit bit ⟨i + 1, by omega⟩)), (ambient, register), + tapes p base input ((Token.bits (.const (tableAt table bit i))).reverse ++ output) + (true :: count)⟩ := by + change some (TM2.stepAux (program (label (.emit bit ⟨i, by omega⟩))) _ _) = _ + rw [ha bit ⟨i, by omega⟩] + simp only [statement, dite_eq_left hi, stepAux_pushWord, TM2.stepAux, + tapes_output, update_output, tapes_count, update_count, tableAt] + +theorem finishRowStep (p : Ports K) (label : Label A ↪ Λ) (exit : Option Λ) (table : TruthTable A) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (ha : EmitAgrees p label exit table program) (base : K → List Bool) + (bit : Bool) (input output count : List Bool) (ambient : σ) (register : Option Bool) : + TM2.step program + ⟨some (label (.emit bit ⟨A, by omega⟩)), (ambient, register), tapes p base input output count⟩ = + some ⟨some (label .scan), (ambient, none), tapes p base input output count⟩ := by + change some (TM2.stepAux (program (label (.emit bit ⟨A, by omega⟩))) _ _) = _ + rw [ha bit ⟨A, by omega⟩] + simp [statement, TM2.stepAux] + +theorem rowTrace (p : Ports K) (label : Label A ↪ Λ) (exit : Option Λ) (table : TruthTable A) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (ha : EmitAgrees p label exit table program) (base : K → List Bool) + (bit : Bool) (start remaining : Nat) (hr : start + remaining = A) + (input output count : List Bool) (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[remaining + 1] + (some ⟨some (label (.emit bit ⟨start, by omega⟩)), (ambient, register), + tapes p base input output count⟩) = + some ⟨some (label .scan), (ambient, none), tapes p base input + ((tokenBits (rowFrom table bit start remaining)).reverse ++ output) + (List.replicate remaining true ++ count)⟩ := by + induction remaining generalizing start output count register with + | zero => + have hs : start = A := by omega + subst start + simpa only [Nat.zero_add, Function.iterate_one, MachineComposition.advance_some, + rowFrom, forTokens, tokenBits, tokenWords, List.flatMap_nil, encodeWords, + List.reverse_nil, List.replicate_zero, List.nil_append] using + finishRowStep p label exit table program ha base bit input output count ambient register + | succ remaining ih => + have hs : start < A := by omega + rw [Function.iterate_succ_apply] + simp only [MachineComposition.advance_some] + rw [emitStep p label exit table program ha base bit start hs] + rw [ih (start + 1) (by omega)] + rw [rowFrom_succ, tokenBits_cons, List.reverse_append] + simp only [List.append_assoc, List.replicate_succ', List.singleton_append] + +theorem streamTrace (p : Ports K) (label : Label A ↪ Λ) (exit : Option Λ) (table : TruthTable A) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (ha : Agrees p label exit table program) (base : K → List Bool) + (input output count : List Bool) (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[(A + 2) * input.length + 1] + (some ⟨some (label .scan), (ambient, register), tapes p base input output count⟩) = + some ⟨exit, (ambient, none), tapes p base [] + ((tokenBits (streamTokens table input)).reverse ++ output) + (List.replicate (A * input.length) true ++ count)⟩ := by + induction input generalizing output count register with + | nil => + simpa only [List.length_nil, Nat.mul_zero, Nat.zero_add, Function.iterate_one, + MachineComposition.advance_some, streamTokens, List.flatMap_nil, tokenBits, + tokenWords, encodeWords, List.reverse_nil, List.replicate_zero, List.nil_append] using + scanStep_nil p label exit table program ha base output count ambient register + | cons bit input ih => + have hround : + (MachineComposition.advance (TM2.step program))^[A + 2] + (some ⟨some (label .scan), (ambient, register), tapes p base (bit :: input) output count⟩) = + some ⟨some (label .scan), (ambient, none), tapes p base input + ((tokenBits (rowTokens table bit)).reverse ++ output) + (List.replicate A true ++ count)⟩ := by + change (MachineComposition.advance (TM2.step program))^[(A + 1) + 1] _ = _ + rw [Function.iterate_succ_apply] + simp only [MachineComposition.advance_some] + rw [scanStep_cons p label exit table program ha base] + exact rowTrace p label exit table program (fun b i => ha (.emit b i)) base bit 0 A (by omega) + input output count ambient (some bit) + have htime : (A + 2) * (bit :: input).length + 1 = + ((A + 2) * input.length + 1) + (A + 2) := by + rw [List.length_cons, Nat.mul_add, Nat.mul_one] + omega + rw [htime, Function.iterate_add_apply, hround, ih] + simp only [streamTokens, List.flatMap_cons, tokenBits_append, List.reverse_append, + List.append_assoc, List.length_cons, Nat.mul_add, Nat.mul_one] + rw [List.replicate_add] + simp only [List.append_assoc] + +def streamInTime (p : Ports K) (label : Label A ↪ Λ) (exit : Option Λ) (table : TruthTable A) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (ha : Agrees p label exit table program) (base : K → List Bool) + (input output count : List Bool) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (label .scan), (ambient, register), tapes p base input output count⟩ + (some ⟨exit, (ambient, none), tapes p base [] + ((tokenBits (streamTokens table input)).reverse ++ output) + (List.replicate (A * input.length) true ++ count)⟩) + ((A + 2) * input.length + 1) where + steps := (A + 2) * input.length + 1 + evals_in_steps := streamTrace p label exit table program ha base input output count ambient register + steps_le_m := Nat.le_refl _ + +theorem copyAndStreamTrace (p : Ports K) (label : Label A ↪ Λ) (exit : Option Λ) + (table : TruthTable A) (saved scratch : K) + (hSaved : ∀ j, saved ≠ p j) (hScratch : ∀ j, scratch ≠ p j) + (hSep : saved ≠ scratch) (copyFirst copySecond : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (ha : Agrees p label exit table program) + (atFirst : program copyFirst = Reduction.MachineTransfer.loopAt saved scratch + id false copyFirst (some copySecond)) + (atSecond : program copySecond = MachineCopy.forkLoop scratch saved (p 0) + false copySecond (some (label .scan))) + (base : K → List Bool) (input output count : List Bool) + (hinput : base saved = input) (hEmpty : base scratch = []) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[(A + 4) * input.length + 3] + (some ⟨some copyFirst, (ambient, register), tapes p base [] output count⟩) = + some ⟨exit, (ambient, none), tapes p base [] + ((tokenBits (streamTokens table input)).reverse ++ output) + (List.replicate (A * input.length) true ++ count)⟩ := by + have hsource : tapes p base [] output count saved = input := by + rw [tapes_other p base [] output count saved hSaved, hinput] + have hscratch : tapes p base [] output count scratch = [] := by + rw [tapes_other p base [] output count scratch hScratch, hEmpty] + have hc := MachineCopy.copyTrace saved (p 0) scratch (hSaved 0) hSep + (hScratch 0).symm false copyFirst copySecond (some (label .scan)) program + atFirst atSecond (tapes p base [] output count) hscratch ambient register + rw [hsource, tapes_input, List.append_nil, update_input] at hc + have htime : (A + 4) * input.length + 3 = + ((A + 2) * input.length + 1) + 2 * (input.length + 1) := by + simp only [Nat.add_mul, Nat.mul_add, Nat.mul_one] + omega + rw [htime, Function.iterate_add_apply, hc] + exact streamTrace p label exit table program ha base input output count ambient none + +def program (table : TruthTable A) : + Label A → TM2.Stmt (Alphabet (K := Fin 3)) (Label A) (Unit × Option Bool) := + statement (Function.Embedding.refl _) (Function.Embedding.refl _) none table + +abbrev machine (table : TruthTable A) : FinTM2 where + K := Fin 3 + k₀ := 0 + k₁ := 1 + Γ _ := Bool + Λ := Label A + main := .scan + σ := Unit × Option Bool + initialState := ((), none) + m := program table + +def machineInTime (table : TruthTable A) (base : Fin 3 → List Bool) + (input output count : List Bool) : + StateTransition.EvalsToInTime (machine table).step + ⟨some .scan, ((), none), tapes (Function.Embedding.refl _) base input output count⟩ + (some ⟨none, ((), none), tapes (Function.Embedding.refl _) base [] + ((tokenBits (streamTokens table input)).reverse ++ output) + (List.replicate (A * input.length) true ++ count)⟩) + ((A + 2) * input.length + 1) := + streamInTime (Function.Embedding.refl _) (Function.Embedding.refl _) none table + (program table) (fun _ => rfl) base input output count () none + +noncomputable section Verifier + +open VerifierCircuit WitnessEncoding + +local instance alphabetDecidable (V : NPVerifier) : ∀ k, DecidableEq (V.computation.tm.Γ k) := + fun _ => Classical.decEq _ + +def symbolTruth (V : NPVerifier) (bit : Bool) : + (Σ k, Option (V.computation.tm.Γ k)) → Bool + | ⟨k, a⟩ => if h : k = V.computation.tm.k₀ then by + subst k + exact decide (some (V.computation.inputAlphabet.invFun bit) = a) + else decide ((none : Option (V.computation.tm.Γ k)) = a) + +def prefixTruth (V : NPVerifier) : TruthTable (indexing V).symbolCount := fun bit j => + symbolTruth V bit ((indexing V).symbols.symm j) + +theorem symbolTruth_eq_initialCellTokens (V : NPVerifier) (input : List Bool) (S : Nat) + (i : Fin S) (bit : Bool) (hi : i.val < (inputPrefix input).length) + (hbit : (inputPrefix input)[i.val]? = some bit) + (symbol : Σ k, Option (V.computation.tm.Γ k)) : + [.const (symbolTruth V bit symbol)] = initialCellTokens V input S symbol.1 i symbol.2 := by + obtain ⟨k, a⟩ := symbol + by_cases hk : k = V.computation.tm.k₀ + · subst k + simp only [symbolTruth, initialCellTokens, dite_true] + simp only [inputCellTokens, ite_eq_left hi, hbit, Option.map_some] + · simp [symbolTruth, initialCellTokens, hk] + +theorem prefixTruth_eq_initialCellTokens (V : NPVerifier) (input : List Bool) (S : Nat) + (i : Fin S) (bit : Bool) (hi : i.val < (inputPrefix input).length) + (hbit : (inputPrefix input)[i.val]? = some bit) (j : Fin (indexing V).symbolCount) : + [.const (prefixTruth V bit j)] = + initialCellTokens V input S ((indexing V).symbols.symm j).1 i + ((indexing V).symbols.symm j).2 := + symbolTruth_eq_initialCellTokens V input S i bit hi hbit ((indexing V).symbols.symm j) + +theorem prefixRow_eq_initialCellTokens (V : NPVerifier) (input : List Bool) (S : Nat) + (i : Fin S) (bit : Bool) (hi : i.val < (inputPrefix input).length) + (hbit : (inputPrefix input)[i.val]? = some bit) : + rowTokens (prefixTruth V) bit = + (List.ofFn fun j : Fin (indexing V).symbolCount => + initialCellTokens V input S ((indexing V).symbols.symm j).1 i + ((indexing V).symbols.symm j).2).flatten := by + rw [rowTokens, rowFrom, forTokens_eq_ofFn] + apply congrArg List.flatten + apply congrArg List.ofFn + funext j + simp only [Nat.zero_add, tableAt, dite_eq_left j.isLt] + exact prefixTruth_eq_initialCellTokens V input S i bit hi hbit j + +theorem prefixStream_eq_initialCells (V : NPVerifier) (input : List Bool) (S : Nat) + (hS : (inputPrefix input).length ≤ S) : + streamTokens (prefixTruth V) (inputPrefix input) = + (List.ofFn fun i : Fin (inputPrefix input).length => + (List.ofFn fun j : Fin (indexing V).symbolCount => + initialCellTokens V input S ((indexing V).symbols.symm j).1 + ⟨i.val, Nat.lt_of_lt_of_le i.isLt hS⟩ + ((indexing V).symbols.symm j).2).flatten).flatten := by + rw [streamTokens_eq_rows] + apply congrArg List.flatten + apply congrArg List.ofFn + funext i + exact prefixRow_eq_initialCellTokens V input S ⟨i.val, Nat.lt_of_lt_of_le i.isLt hS⟩ + (inputPrefix input)[i.val] i.isLt (List.getElem?_eq_getElem i.isLt) + +end Verifier + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.InputCellsMachine + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.InputCellsCapacity + +open Turing PostfixModel InputCellsMachine + + +variable {K Λ σ : Type} [DecidableEq K] {A : Nat} + +abbrev Ports (K : Type) := Fin 4 ↪ K + +def corePorts (p : Ports K) : InputCellsMachine.Ports K where + toFun j := p j.castSucc + inj' := by + intro i j h + exact Fin.ext (congrArg (fun x : Fin 4 => x.val) (p.injective h)) + +omit [DecidableEq K] in +theorem capacity_distinct (p : Ports K) (j : Fin 3) : p 3 ≠ corePorts p j := by + intro h + have hv := congrArg Fin.val (p.injective h) + change 3 = j.val at hv + omega + +def tapes (p : Ports K) (base : K → List Bool) (remaining : Nat) + (input output count : List Bool) : K → List Bool := + InputCellsMachine.tapes (corePorts p) + (Function.update base (p 3) (encodeWord remaining)) input output count + +@[simp] theorem tapes_input (p : Ports K) (base : K → List Bool) (remaining : Nat) + (input output count : List Bool) : tapes p base remaining input output count (p 0) = input := + InputCellsMachine.tapes_input (corePorts p) _ _ _ _ + +@[simp] theorem tapes_output (p : Ports K) (base : K → List Bool) (remaining : Nat) + (input output count : List Bool) : tapes p base remaining input output count (p 1) = output := + InputCellsMachine.tapes_output (corePorts p) _ _ _ _ + +@[simp] theorem tapes_count (p : Ports K) (base : K → List Bool) (remaining : Nat) + (input output count : List Bool) : tapes p base remaining input output count (p 2) = count := + InputCellsMachine.tapes_count (corePorts p) _ _ _ _ + +@[simp] theorem tapes_capacity (p : Ports K) (base : K → List Bool) (remaining : Nat) + (input output count : List Bool) : + tapes p base remaining input output count (p 3) = encodeWord remaining := by + rw [tapes, InputCellsMachine.tapes_other _ _ _ _ _ _ (capacity_distinct p)] + simp + +theorem tapes_other (p : Ports K) (base : K → List Bool) (remaining : Nat) + (input output count : List Bool) (k : K) (hk : ∀ j, k ≠ p j) : + tapes p base remaining input output count k = base k := by + rw [tapes, InputCellsMachine.tapes_other _ _ _ _ _ _ (fun j => hk j.castSucc)] + simp [hk] + +theorem update_input (p : Ports K) (base : K → List Bool) (remaining : Nat) + (input output count replacement : List Bool) : + Function.update (tapes p base remaining input output count) (p 0) replacement = + tapes p base remaining replacement output count := + InputCellsMachine.update_input (corePorts p) _ _ _ _ _ + +theorem update_capacity (p : Ports K) (base : K → List Bool) (remaining replacement : Nat) + (input output count : List Bool) : + Function.update (tapes p base remaining input output count) (p 3) (encodeWord replacement) = + tapes p base replacement input output count := by + funext k + by_cases hk : ∃ j, p j = k + · obtain ⟨j, rfl⟩ := hk + fin_cases j <;> simp [p.injective.eq_iff] + · have hn : ∀ j, k ≠ p j := fun j h => hk ⟨j, h.symm⟩ + simp [hn, tapes_other p base remaining input output count k hn, + tapes_other p base replacement input output count k hn] + +def statement (p : Ports K) (label : InputCellsMachine.Label A ↪ Λ) (exit : Option Λ) + (table : TruthTable A) : + InputCellsMachine.Label A → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) + | .scan => + .pop (p 0) (fun state head => (state.1, head)) + (.branch (fun state => state.2.isSome) + (.pop (p 3) (fun state _ => state) + (.goto fun state => label (.emit (state.2.getD false) 0))) + (.load (fun state => (state.1, none)) + (Reduction.MachineTransfer.exitAt (p 0) exit))) + | .emit bit i => InputCellsMachine.statement (corePorts p) label exit table (.emit bit i) + +def Agrees (p : Ports K) (label : InputCellsMachine.Label A ↪ Λ) (exit : Option Λ) + (table : TruthTable A) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) : Prop := + ∀ l, program (label l) = statement p label exit table l + +omit [DecidableEq K] in +theorem emitAgrees (p : Ports K) (label : InputCellsMachine.Label A ↪ Λ) (exit : Option Λ) + (table : TruthTable A) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (ha : Agrees p label exit table program) : + InputCellsMachine.EmitAgrees (corePorts p) label exit table program := by + intro bit i + exact ha (.emit bit i) + +theorem scanStep_nil (p : Ports K) (label : InputCellsMachine.Label A ↪ Λ) + (exit : Option Λ) (table : TruthTable A) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (ha : Agrees p label exit table program) (base : K → List Bool) (remaining : Nat) + (output count : List Bool) (ambient : σ) (register : Option Bool) : + TM2.step program + ⟨some (label .scan), (ambient, register), tapes p base remaining [] output count⟩ = + some ⟨exit, (ambient, none), tapes p base remaining [] output count⟩ := by + change some (TM2.stepAux (program (label .scan)) _ _) = _ + rw [ha .scan] + cases exit <;> simp [statement, TM2.stepAux, Reduction.MachineTransfer.exitAt, update_input] + +theorem scanStep_cons (p : Ports K) (label : InputCellsMachine.Label A ↪ Λ) + (exit : Option Λ) (table : TruthTable A) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (ha : Agrees p label exit table program) (base : K → List Bool) (remaining : Nat) + (bit : Bool) (input output count : List Bool) (ambient : σ) (register : Option Bool) : + TM2.step program + ⟨some (label .scan), (ambient, register), tapes p base (remaining + 1) (bit :: input) output count⟩ = + some ⟨some (label (.emit bit 0)), (ambient, some bit), + tapes p base remaining input output count⟩ := by + change some (TM2.stepAux (program (label .scan)) _ _) = _ + rw [ha .scan] + simp [statement, TM2.stepAux, update_input, encodeWord, List.replicate_succ] + exact update_capacity p base (remaining + 1) remaining input output count + +theorem streamTrace_add (p : Ports K) (label : InputCellsMachine.Label A ↪ Λ) + (exit : Option Λ) (table : TruthTable A) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (ha : Agrees p label exit table program) (base : K → List Bool) (remaining : Nat) + (input output count : List Bool) (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[(A + 2) * input.length + 1] + (some ⟨some (label .scan), (ambient, register), + tapes p base (input.length + remaining) input output count⟩) = + some ⟨exit, (ambient, none), tapes p base remaining [] + ((tokenBits (streamTokens table input)).reverse ++ output) + (List.replicate (A * input.length) true ++ count)⟩ := by + induction input generalizing output count register with + | nil => + simpa only [List.length_nil, Nat.mul_zero, Nat.zero_add, Function.iterate_one, + MachineComposition.advance_some, streamTokens, List.flatMap_nil, tokenBits, + tokenWords, encodeWords, List.reverse_nil, List.replicate_zero, List.nil_append] using + scanStep_nil p label exit table program ha base remaining output count ambient register + | cons bit input ih => + have hround : + (MachineComposition.advance (TM2.step program))^[A + 2] + (some ⟨some (label .scan), (ambient, register), + tapes p base ((bit :: input).length + remaining) (bit :: input) output count⟩) = + some ⟨some (label .scan), (ambient, none), + tapes p base (input.length + remaining) input + ((tokenBits (rowTokens table bit)).reverse ++ output) + (List.replicate A true ++ count)⟩ := by + have hn : (bit :: input).length + remaining = (input.length + remaining) + 1 := by + simp only [List.length_cons] + omega + rw [hn] + change (MachineComposition.advance (TM2.step program))^[(A + 1) + 1] _ = _ + rw [Function.iterate_succ_apply] + simp only [MachineComposition.advance_some] + rw [scanStep_cons p label exit table program ha base] + exact rowTrace (corePorts p) label exit table program + (emitAgrees p label exit table program ha) + (Function.update base (p 3) (encodeWord (input.length + remaining))) bit 0 A (by omega) + input output count ambient (some bit) + have htime : (A + 2) * (bit :: input).length + 1 = + ((A + 2) * input.length + 1) + (A + 2) := by + rw [List.length_cons, Nat.mul_add, Nat.mul_one] + omega + rw [htime, Function.iterate_add_apply, hround, ih] + simp only [streamTokens, List.flatMap_cons, tokenBits_append, List.reverse_append, + List.append_assoc, List.length_cons, Nat.mul_add, Nat.mul_one] + rw [List.replicate_add] + simp only [List.append_assoc] + +theorem streamTrace (p : Ports K) (label : InputCellsMachine.Label A ↪ Λ) + (exit : Option Λ) (table : TruthTable A) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (ha : Agrees p label exit table program) (base : K → List Bool) (S : Nat) + (input output count : List Bool) (hS : input.length ≤ S) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[(A + 2) * input.length + 1] + (some ⟨some (label .scan), (ambient, register), tapes p base S input output count⟩) = + some ⟨exit, (ambient, none), tapes p base (S - input.length) [] + ((tokenBits (streamTokens table input)).reverse ++ output) + (List.replicate (A * input.length) true ++ count)⟩ := by + have h := streamTrace_add p label exit table program ha base (S - input.length) + input output count ambient register + rw [Nat.add_sub_of_le hS] at h + exact h + +theorem copyAndStreamTrace (p : Ports K) (label : InputCellsMachine.Label A ↪ Λ) + (exit : Option Λ) (table : TruthTable A) (saved scratch : K) + (hSaved : ∀ j, saved ≠ p j) (hScratch : ∀ j, scratch ≠ p j) + (hSep : saved ≠ scratch) (copyFirst copySecond : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (ha : Agrees p label exit table program) + (atFirst : program copyFirst = Reduction.MachineTransfer.loopAt saved scratch + id false copyFirst (some copySecond)) + (atSecond : program copySecond = MachineCopy.forkLoop scratch saved (p 0) + false copySecond (some (label .scan))) + (base : K → List Bool) (S : Nat) (input output count : List Bool) + (hS : input.length ≤ S) (hinput : base saved = input) (hEmpty : base scratch = []) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[(A + 4) * input.length + 3] + (some ⟨some copyFirst, (ambient, register), tapes p base S [] output count⟩) = + some ⟨exit, (ambient, none), tapes p base (S - input.length) [] + ((tokenBits (streamTokens table input)).reverse ++ output) + (List.replicate (A * input.length) true ++ count)⟩ := by + have hsource : tapes p base S [] output count saved = input := by + rw [tapes_other p base S [] output count saved hSaved, hinput] + have hscratch : tapes p base S [] output count scratch = [] := by + rw [tapes_other p base S [] output count scratch hScratch, hEmpty] + have hc := MachineCopy.copyTrace saved (p 0) scratch (hSaved 0) hSep + (hScratch 0).symm false copyFirst copySecond (some (label .scan)) program + atFirst atSecond (tapes p base S [] output count) hscratch ambient register + rw [hsource, tapes_input, List.append_nil, update_input] at hc + have htime : (A + 4) * input.length + 3 = + ((A + 2) * input.length + 1) + 2 * (input.length + 1) := by + simp only [Nat.add_mul, Nat.mul_add, Nat.mul_one] + omega + rw [htime, Function.iterate_add_apply, hc] + exact streamTrace p label exit table program ha base S input output count hS ambient none + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.InputCellsCapacity + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.CellsPrefixStage + +open Turing PostfixModel InputCellsMachine + + +variable {K Λ σ : Type} [DecidableEq K] {A : Nat} + +abbrev Ports (K : Type) := Fin 7 ↪ K + +def capacityPorts (p : Ports K) : InputCellsCapacity.Ports K where + toFun j := p (![4, 2, 3, 5] j) + inj' := by + intro i j h + have hmap : Function.Injective (fun j : Fin 4 => (![4, 2, 3, 5] j : Fin 7)) := by decide + exact hmap (p.injective h) + +omit [DecidableEq K] in +theorem saved_distinct (p : Ports K) (j : Fin 4) : p 0 ≠ capacityPorts p j := by + change p 0 ≠ p (![4, 2, 3, 5] j) + fin_cases j <;> simp [p.injective.eq_iff] + +omit [DecidableEq K] in +theorem scratch_distinct (p : Ports K) (j : Fin 4) : p 6 ≠ capacityPorts p j := by + change p 6 ≠ p (![4, 2, 3, 5] j) + fin_cases j <;> simp [p.injective.eq_iff] + +theorem prepared_eq (p : Ports K) (base : K → List Bool) (S : Nat) + (hwork : base (p 4) = []) : + InputCellsCapacity.tapes (capacityPorts p) base S [] (base (p 2)) (base (p 3)) = + Function.update base (p 5) (encodeWord S) := by + have hcore (q : InputCellsCapacity.Ports K) (j : Fin 3) : + InputCellsCapacity.corePorts q j = q j.castSucc := by + rw [InputCellsCapacity.corePorts.eq_1] + rfl + have hcapacity (j : Fin 4) : capacityPorts p j = p (![4, 2, 3, 5] j) := by + rw [capacityPorts.eq_1] + rfl + funext k + by_cases hk : ∃ j, p j = k + · obtain ⟨j, rfl⟩ := hk + fin_cases j <;> + simp [InputCellsCapacity.tapes, InputCellsMachine.tapes, + hcore, hcapacity, p.injective.eq_iff, hwork] + change Function.update (_ : K → List Bool) (p 3) (base (p 3)) (p 3) = base (p 3) + simp + · have hn : ∀ j, k ≠ p j := fun j h => hk ⟨j, h.symm⟩ + simp [InputCellsCapacity.tapes, InputCellsMachine.tapes, + hcore, hcapacity, hn] + +inductive Label (symbols : Nat) + | capacityFirst | capacitySecond | prefixFirst | prefixSecond + | stream (entry : InputCellsMachine.Label symbols) + deriving DecidableEq, Fintype + +def streamLabels (label : Label A ↪ Λ) : InputCellsMachine.Label A ↪ Λ where + toFun entry := label (.stream entry) + inj' := by + intro i j h + exact Label.stream.inj (label.injective h) + +def statement (p : Ports K) (label : Label A ↪ Λ) (exit : Option Λ) + (table : TruthTable A) : Label A → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) + | .capacityFirst => Reduction.MachineTransfer.loopAt (p 1) (p 6) id false + (label .capacityFirst) (some (label .capacitySecond)) + | .capacitySecond => MachineCopy.forkLoop (p 6) (p 1) (p 5) false + (label .capacitySecond) (some (label .prefixFirst)) + | .prefixFirst => Reduction.MachineTransfer.loopAt (p 0) (p 6) id false + (label .prefixFirst) (some (label .prefixSecond)) + | .prefixSecond => MachineCopy.forkLoop (p 6) (p 0) (p 4) false + (label .prefixSecond) (some (label (.stream .scan))) + | .stream entry => InputCellsCapacity.statement (capacityPorts p) (streamLabels label) + exit table entry + +def Agrees (p : Ports K) (label : Label A ↪ Λ) (exit : Option Λ) (table : TruthTable A) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) : Prop := + ∀ entry, program (label entry) = statement p label exit table entry + +omit [DecidableEq K] in +theorem stream_agrees (p : Ports K) (label : Label A ↪ Λ) (exit : Option Λ) + (table : TruthTable A) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (ha : Agrees p label exit table program) : + InputCellsCapacity.Agrees (capacityPorts p) (streamLabels label) exit table program := by + intro entry + exact ha (.stream entry) + +theorem trace (p : Ports K) (label : Label A ↪ Λ) (exit : Option Λ) + (table : TruthTable A) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (ha : Agrees p label exit table program) (base : K → List Bool) + (input : List Bool) (S : Nat) (hS : input.length ≤ S) + (hinput : base (p 0) = input) (hcached : base (p 1) = encodeWord S) + (hwork : base (p 4) = []) (hcapacity : base (p 5) = []) (hscratch : base (p 6) = []) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[2 * (S + 2) + ((A + 4) * input.length + 3)] + (some ⟨some (label .capacityFirst), (ambient, register), base⟩) = + some ⟨exit, (ambient, none), InputCellsCapacity.tapes (capacityPorts p) base + (S - input.length) [] + ((tokenBits (streamTokens table input)).reverse ++ base (p 2)) + (List.replicate (A * input.length) true ++ base (p 3))⟩ := by + have hc := MachineCopy.copyTrace (p 1) (p 5) (p 6) + (p.injective.ne (by decide)) (p.injective.ne (by decide)) (p.injective.ne (by decide)) + false (label .capacityFirst) (label .capacitySecond) (some (label .prefixFirst)) + program (ha .capacityFirst) (ha .capacitySecond) base hscratch ambient register + rw [hcached, hcapacity, List.append_nil, encodeWord_length] at hc + have hp := InputCellsCapacity.copyAndStreamTrace (capacityPorts p) (streamLabels label) + exit table (p 0) (p 6) (saved_distinct p) (scratch_distinct p) + (p.injective.ne (by decide)) (label .prefixFirst) (label .prefixSecond) program + (stream_agrees p label exit table program ha) (ha .prefixFirst) (ha .prefixSecond) + base S input (base (p 2)) (base (p 3)) hS hinput hscratch ambient none + rw [prepared_eq p base S hwork] at hp + rw [Nat.add_comm (2 * (S + 2)), Function.iterate_add_apply, hc] + exact hp + +def inTime (p : Ports K) (label : Label A ↪ Λ) (exit : Option Λ) + (table : TruthTable A) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (ha : Agrees p label exit table program) (base : K → List Bool) + (input : List Bool) (S : Nat) (hS : input.length ≤ S) + (hinput : base (p 0) = input) (hcached : base (p 1) = encodeWord S) + (hwork : base (p 4) = []) (hcapacity : base (p 5) = []) (hscratch : base (p 6) = []) + (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (label .capacityFirst), (ambient, register), base⟩ + (some ⟨exit, (ambient, none), InputCellsCapacity.tapes (capacityPorts p) base + (S - input.length) [] + ((tokenBits (streamTokens table input)).reverse ++ base (p 2)) + (List.replicate (A * input.length) true ++ base (p 3))⟩) + (2 * (S + 2) + ((A + 4) * input.length + 3)) where + steps := 2 * (S + 2) + ((A + 4) * input.length + 3) + evals_in_steps := trace p label exit table program ha base input S hS hinput hcached + hwork hcapacity hscratch ambient register + steps_le_m := Nat.le_refl _ + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.CellsPrefixStage + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/InputFrame.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/InputFrame.lean new file mode 100644 index 0000000000000000000000000000000000000000..858514e44adbcbc02f54ab328f69135d081ff6d1 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/InputFrame.lean @@ -0,0 +1,220 @@ +import OAI.Computability.UniqueGames.Machines.MachineCompositionLemmas +import OAI.Computability.UniqueGames.Machines.MachineSubroutineLemmas +import OAI.Computability.UniqueGames.Reduction.MachineTransfer + +namespace OAI + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.InputFrame + + +open Turing MachineComposition +open UniqueGamesTheorem.Reduction.MachineTransfer + +abbrev Tape := Fin 3 +abbrev Label := Fin 5 +abbrev State := Unit × Option Bool +abbrev Alphabet (_ : Tape) := Bool + +def scan : TM2.Stmt Alphabet Label State := + .pop 0 (fun s head => (s.1, head)) + (.branch (fun s => s.2.isSome) + (.push 1 (fun s => s.2.getD false) + (.push 2 (fun _ => true) (.goto fun _ => 1))) + (.goto fun _ => 2)) + +def program (label : Label) : TM2.Stmt Alphabet Label State := + if label = 0 then .push 2 (fun _ => false) (.goto fun _ => 1) + else if label = 1 then scan + else if label = 2 then loopAt 1 0 id false 2 (some 3) + else if label = 3 then loopAt 2 1 id false 3 (some 4) + else loopAt 1 0 id false 4 none + +abbrev machine : FinTM2 where + K := Tape + k₀ := 0 + k₁ := 0 + Γ := Alphabet + Λ := Label + main := 0 + σ := State + initialState := ((), none) + m := program + +def tapes (input saved counter : List Bool) : Tape → List Bool := + fun k => if k = 0 then input else if k = 1 then saved else counter + +def cfg (label : Option Label) (input saved counter : List Bool) + (register : Option Bool := none) : machine.Cfg := + ⟨label, ((), register), tapes input saved counter⟩ + +@[simp] private theorem tapes_zero (input saved counter : List Bool) : + tapes input saved counter 0 = input := rfl + +@[simp] private theorem tapes_one (input saved counter : List Bool) : + tapes input saved counter 1 = saved := rfl + +@[simp] private theorem tapes_two (input saved counter : List Bool) : + tapes input saved counter 2 = counter := rfl + +private theorem update_zero (input saved counter replacement : List Bool) : + Function.update (tapes input saved counter) 0 replacement = + tapes replacement saved counter := by + funext k + fin_cases k <;> simp [tapes] + +private theorem update_one (input saved counter replacement : List Bool) : + Function.update (tapes input saved counter) 1 replacement = + tapes input replacement counter := by + funext k + fin_cases k <;> simp [tapes] + +private theorem update_two (input saved counter replacement : List Bool) : + Function.update (tapes input saved counter) 2 replacement = + tapes input saved replacement := by + funext k + fin_cases k <;> simp [tapes] + +theorem scanStep_nil (saved counter : List Bool) (register : Option Bool) : + machine.step (cfg (some 1) [] saved counter register) = + some (cfg (some 2) [] saved counter) := by + change some (TM2.stepAux (program 1) _ _) = _ + simp [program, scan, cfg, TM2.stepAux, tapes, update_zero] + rfl + +theorem scanStep_cons (bit : Bool) (input saved counter : List Bool) + (register : Option Bool) : + machine.step (cfg (some 1) (bit :: input) saved counter register) = + some (cfg (some 1) input (bit :: saved) (true :: counter) (some bit)) := by + change some (TM2.stepAux (program 1) _ _) = _ + simp [program, scan, cfg, TM2.stepAux, tapes, update_zero, update_one, update_two] + rfl + +theorem scanTrace (input saved counter : List Bool) (register : Option Bool) : + (advance machine.step)^[input.length + 1] + (some (cfg (some 1) input saved counter register)) = + some (cfg (some 2) [] (input.reverse ++ saved) + (List.replicate input.length true ++ counter)) := by + induction input generalizing saved counter register with + | nil => + simpa only [List.length_nil, Nat.zero_add, Function.iterate_one, advance_some, + List.reverse_nil, List.replicate_zero, List.nil_append] using + scanStep_nil saved counter register + | cons bit input ih => + rw [List.length_cons, Function.iterate_succ_apply] + simp only [advance_some] + rw [scanStep_cons, ih] + simp only [List.reverse_cons, List.append_assoc, List.singleton_append] + rw [List.replicate_succ'] + simp only [List.append_assoc, List.singleton_append] + +theorem startStep (input : List Bool) : + machine.step (initList machine input) = some (cfg (some 1) input [] [false]) := by + change some (TM2.stepAux (program 0) ((),none) _) = _ + simp [program, TM2.stepAux, cfg] + exact congrArg (fun stk : Tape → List Bool => + some (⟨some 1, ((), none), stk⟩ : machine.Cfg)) (by + funext k + fin_cases k <;> simp [tapes]) + +theorem restoreTrace (input : List Bool) (n : Nat) : + (advance machine.step)^[input.length + 1] + (some (cfg (some 2) [] input.reverse (encodeWord n))) = + some (cfg (some 3) input [] (encodeWord n)) := by + have h := transferAt_fromTapes (Γ := Alphabet) (σ := Unit) 1 0 (by decide) + id false 2 (some 3) program (by simp [program]) + (tapes [] input.reverse (encodeWord n)) () none + have ht : tapesAt 1 0 (tapes [] input.reverse (encodeWord n)) [] input = + tapes input [] (encodeWord n) := by + funext k + fin_cases k <;> simp [tapesAt, tapes] + change (nextAt 0 program)^[input.length + 1] + (some (cfg (some 2) [] input.reverse (encodeWord n))) = _ + simpa only [tapes_one, tapes_zero, List.length_reverse, List.reverse_reverse, + List.map_id_fun, id_eq, List.append_nil, ht, nextAt, advance, cfg] using! h + +theorem reverseCounterTrace (input : List Bool) (n : Nat) : + (advance machine.step)^[n + 2] + (some (cfg (some 3) input [] (encodeWord n))) = + some (cfg (some 4) input (encodeWord n).reverse []) := by + have h := transferAt_fromTapes (Γ := Alphabet) (σ := Unit) 2 1 (by decide) + id false 3 (some 4) program (by simp [program]) + (tapes input [] (encodeWord n)) () none + have ht : tapesAt 2 1 (tapes input [] (encodeWord n)) [] (encodeWord n).reverse = + tapes input (encodeWord n).reverse [] := by + funext k + fin_cases k <;> simp [tapesAt, tapes] + change (nextAt 1 program)^[n + 2] + (some (cfg (some 3) input [] (encodeWord n))) = _ + simpa only [tapes_two, tapes_one, List.map_id_fun, id_eq, List.append_nil, + encodeWord_length, Nat.add_assoc, ht, nextAt, advance, cfg] using! h + +theorem prependTrace (input : List Bool) (n : Nat) : + (advance machine.step)^[n + 2] + (some (cfg (some 4) input (encodeWord n).reverse [])) = + some (cfg none (encodeWord n ++ input) [] []) := by + have h := transferAt_fromTapes (Γ := Alphabet) (σ := Unit) 1 0 (by decide) + id false 4 none program (by simp [program]) + (tapes input (encodeWord n).reverse []) () none + have ht : tapesAt 1 0 (tapes input (encodeWord n).reverse []) [] (encodeWord n ++ input) = + tapes (encodeWord n ++ input) [] [] := by + funext k + fin_cases k <;> simp [tapesAt, tapes] + change (nextAt 0 program)^[n + 2] + (some (cfg (some 4) input (encodeWord n).reverse [])) = _ + simpa only [tapes_one, tapes_zero, List.length_reverse, List.reverse_reverse, + List.map_id_fun, id_eq, encodeWord_length, Nat.add_assoc, ht, nextAt, advance, cfg] using! h + +theorem stopped_eq_haltList (output : List Bool) : + cfg none output [] [] = haltList machine output := by + unfold cfg haltList + congr 1 + funext k + fin_cases k <;> simp [tapes, machine] + +theorem frameTrace (input : List Bool) : + (advance machine.step)^[4 * input.length + 7] + (some (initList machine input)) = + some (haltList machine (encodeWord input.length ++ input)) := by + have join : + (advance machine.step)^[input.length + 2] + ((advance machine.step)^[input.length + 2] + ((advance machine.step)^[input.length + 1] + ((advance machine.step)^[input.length + 1] + ((advance machine.step)^[1] (some (initList machine input)))))) = + (advance machine.step)^[4 * input.length + 7] + (some (initList machine input)) := by + rw [← Function.iterate_add_apply, ← Function.iterate_add_apply, + ← Function.iterate_add_apply, ← Function.iterate_add_apply] + congr 1 + omega + rw [← join] + simp only [Function.iterate_one, advance_some] + rw [startStep, scanTrace] + simp only [List.append_nil] + change (advance machine.step)^[input.length + 2] + ((advance machine.step)^[input.length + 2] + ((advance machine.step)^[input.length + 1] + (some (cfg (some 2) [] input.reverse (encodeWord input.length))))) = _ + rw [restoreTrace, reverseCounterTrace, prependTrace, stopped_eq_haltList] + +noncomputable def computableInPolyTime : + TM2ComputableInPolyTime (id : List Bool → List Bool) id + (fun input => encodeWord input.length ++ input) where + tm := machine + inputAlphabet := Equiv.refl Bool + outputAlphabet := Equiv.refl Bool + time := 4 * Polynomial.X + 7 + outputsFun input := { + steps := 4 * input.length + 7 + evals_in_steps := by + change (advance machine.step)^[4 * input.length + 7] + (some (initList machine (input.map id))) = + some (haltList machine ((encodeWord input.length ++ input).map id)) + simp only [List.map_id_fun, id_eq] + exact frameTrace input + steps_le_m := by simp } + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.InputFrame + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/KeyMetadataMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/KeyMetadataMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..89bb527262904be98252bd557cc744e27eacef8e --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/KeyMetadataMachine.lean @@ -0,0 +1,348 @@ +import OAI.Computability.PerfectCompleteness.Foundations.CanonicalEdgesLemmas +import OAI.Computability.PerfectCompleteness.Machines.FiniteBlockMachineLemmas +import OAI.Computability.UniqueGames.Machines.MachineCopy +import OAI.Computability.UniqueGames.Machines.MachineSubroutineLemmas +import OAI.Computability.UniqueGames.Reduction.MachineSubstitution + +namespace OAI + + +namespace PerfectCompleteness.KeyMetadataMachine + + +open Turing UniqueGamesTheorem.Foundations.Complexity +open UniqueGamesTheorem.Reduction.MachineSubstitution +open MachineComposition CanonicalKeyShape ClauseSupport MixedSupport +open scoped BigOperators Classical + +noncomputable section + +variable {n : Nat} + +def actualSlot (shape : Shape) (occurrence : Nat) (variableIDs : Fin 3 → Nat) : Slot := + match shape with + | .clause signs => .clause occurrence variableIDs signs + | .bit => .bit (variableIDs 0) + +def fieldValue (occurrence : Nat) (variableIDs : Fin 3 → Nat) : Fin 4 → Nat := + Fin.cases occurrence variableIDs + +def sourceField : Shape → SupportMode → Option (Fin 4) + | .clause _, .full => some 0 + | .clause _, .clauseBit i => some i.succ + | .bit, .bit => some 1 + | _, _ => none + +def prefixWords (position : Fin n) (shape : Shape) (mode : SupportMode) : List Nat := + [position.val, match shape, mode with | .clause _, .full => 2 | _, _ => 1] + +def suffixWords : Shape → SupportMode → List Nat + | .clause signs, .full => + [KeyMetadataEncoding.bitWord signs.1, KeyMetadataEncoding.bitWord signs.2.1, + KeyMetadataEncoding.bitWord signs.2.2] + | _, _ => [0, 0, 0] + +def retainedWords (position : Fin n) (slot : Slot) (mode : SupportMode) : List Nat := + if recover slot mode = .dropped then [] + else KeyMetadataEncoding.entryWords (position, recover slot mode) + +def retainedBits (position : Fin n) (slot : Slot) (mode : SupportMode) : List Bool := + encodeWords (retainedWords position slot mode) + +theorem retainedWords_eq (position : Fin n) (shape : Shape) (mode : SupportMode) + (occurrence : Nat) (variableIDs : Fin 3 → Nat) : + retainedWords position (actualSlot shape occurrence variableIDs) mode = + match sourceField shape mode with + | none => [] + | some field => prefixWords position shape mode ++ + [fieldValue occurrence variableIDs field] ++ suffixWords shape mode := by + cases shape <;> cases mode <;> + simp [retainedWords, actualSlot, sourceField, prefixWords, suffixWords, + fieldValue, recover, KeyMetadataEncoding.entryWords] + rfl + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool +abbrev State (σ : Type) := σ × Option Bool + +def clean (ambient : σ) : State σ := (ambient, none) + +inductive Label + | suffix + | copyOut + | copyBack + | «prefix» + deriving DecidableEq + +protected abbrev Label.enumList : List Label := [.suffix, .copyOut, .copyBack, .«prefix»] + +protected theorem Label.enumList_getElem?_ctorIdx_eq (x : Label) : + Label.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem Label.enumList_nodup : Label.enumList.Nodup := by decide + +instance : Fintype Label where + elems := ⟨Label.enumList, Label.enumList_nodup⟩ + complete x := by cases x <;> decide + +def idIndex (field : Fin 4) : Fin 6 := ⟨field.val, lt_trans field.isLt (by decide)⟩ + +def idTape (tape : Fin 6 → K) (field : Fin 4) : K := tape (idIndex field) + +def finish (exit : Option Λ) : TM2.Stmt (Alphabet (K := K)) Λ (State σ) := + .load (fun state => clean state.1) + (match exit with | none => .halt | some label => .goto (fun _ => label)) + +theorem stepAux_finish (exit : Option Λ) (ambient : σ) (register : Option Bool) + (base : K → List Bool) : + TM2.stepAux (finish exit) (ambient, register) base = ⟨exit, clean ambient, base⟩ := by + cases exit <;> rfl + +omit [DecidableEq K] in +@[simp] theorem finish_pushBound (exit : Option Λ) : + Runtime.statementPushBound (finish (K := K) (σ := σ) exit) = 0 := by + cases exit <;> rfl + +def literal (destination : K) (bits : List Bool) (exit : Option Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (State σ) := + pushWord destination bits.reverse (finish exit) + +omit [DecidableEq K] in +theorem literal_pushBound (destination : K) (bits : List Bool) (exit : Option Λ) : + Runtime.statementPushBound (literal (σ := σ) destination bits exit) = bits.length := by + simp only [literal, statementPushBound_pushWord, List.length_reverse, + finish_pushBound, Nat.add_zero] + +theorem literal_step (destination : K) (bits : List Bool) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) (label : Λ) + (atLabel : program label = literal destination bits exit) + (base : K → List Bool) (ambient : σ) : + TM2.step program ⟨some label, clean ambient, base⟩ = + some ⟨exit, clean ambient, Function.update base destination (bits ++ base destination)⟩ := by + change some (TM2.stepAux (program label) (ambient, none) base) = _ + rw [atLabel] + unfold literal + rw [stepAux_pushWord (Γ := Alphabet (K := K)) (Λ := Λ) (σ := State σ) + destination bits.reverse (finish exit) (ambient, none) base, + List.reverse_reverse, stepAux_finish] + +def instruction (position : Fin n) (shape : Shape) (mode : SupportMode) + (tape : Fin 6 → K) (labels : Label → Λ) (exit : Option Λ) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (State σ) + | .suffix => match sourceField shape mode with + | none => finish exit + | some _ => literal (tape 5) (encodeWords (suffixWords shape mode)) + (some (labels .copyOut)) + | .copyOut => UniqueGamesTheorem.Reduction.MachineTransfer.loopAt + (idTape tape ((sourceField shape mode).getD 0)) (tape 4) id false + (labels .copyOut) (some (labels .copyBack)) + | .copyBack => MachineCopy.forkLoop (tape 4) + (idTape tape ((sourceField shape mode).getD 0)) (tape 5) false + (labels .copyBack) (some (labels .prefix)) + | .prefix => literal (tape 5) (encodeWords (prefixWords position shape mode)) exit + +omit [DecidableEq K] in +theorem instruction_pushBound (position : Fin n) (shape : Shape) (mode : SupportMode) + (tape : Fin 6 → K) (labels : Label → Λ) (exit : Option Λ) (label : Label) : + Runtime.statementPushBound (instruction (σ := σ) position shape mode tape labels exit label) ≤ + (encodeWords (prefixWords position shape mode)).length + + (encodeWords (suffixWords shape mode)).length + 2 := by + cases label with + | suffix => + cases hs : sourceField shape mode <;> + simp only [instruction, hs, finish_pushBound, literal_pushBound] <;> omega + | copyOut => + simp [instruction, UniqueGamesTheorem.Reduction.MachineTransfer.loopAt, + UniqueGamesTheorem.Reduction.MachineTransfer.exitAt, Runtime.statementPushBound] + | copyBack => + simp [instruction, MachineCopy.forkLoop, UniqueGamesTheorem.Reduction.MachineTransfer.exitAt, + Runtime.statementPushBound] + | «prefix» => + rw [instruction, literal_pushBound] + omega + +private theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +theorem droppedTrace (position : Fin n) (shape : Shape) (mode : SupportMode) + (hdrop : sourceField shape mode = none) + (tape : Fin 6 → K) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ label, program (labels label) = + instruction position shape mode tape labels exit label) + (base : K → List Bool) (ambient : σ) : + (advance (TM2.step program))^[1] + (some ⟨some (labels .suffix), clean ambient, base⟩) = + some ⟨exit, clean ambient, base⟩ := by + change some (TM2.stepAux (program (labels .suffix)) (ambient, none) base) = _ + rw [atLabels .suffix] + simp only [instruction, hdrop, stepAux_finish] + +theorem selectedTrace (position : Fin n) (shape : Shape) (mode : SupportMode) + (field : Fin 4) (hfield : sourceField shape mode = some field) + (tape : Fin 6 → K) (distinct : Function.Injective tape) + (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ label, program (labels label) = + instruction position shape mode tape labels exit label) + (base : K → List Bool) (scratchEmpty : base (tape 4) = []) (ambient : σ) : + (advance (TM2.step program))^[2 * ((base (idTape tape field)).length + 1) + 2] + (some ⟨some (labels .suffix), clean ambient, base⟩) = + some ⟨exit, clean ambient, Function.update base (tape 5) + ((encodeWords (prefixWords position shape mode) ++ base (idTape tape field) ++ + encodeWords (suffixWords shape mode)) ++ base (tape 5))⟩ := by + have hd (i j : Fin 6) (h : i ≠ j) : tape i ≠ tape j := fun heq => h (distinct heq) + have hsourceOutput : idTape tape field ≠ tape 5 := by + apply hd + intro h + have heq := congrArg Fin.val h + have hlt := field.isLt + change field.val = 5 at heq + omega + have hsourceScratch : idTape tape field ≠ tape 4 := by + apply hd + intro h + have heq := congrArg Fin.val h + have hlt := field.isLt + change field.val = 4 at heq + omega + have houtputScratch : tape 5 ≠ tape 4 := hd 5 4 (by decide) + let afterSuffix := Function.update base (tape 5) + (encodeWords (suffixWords shape mode) ++ base (tape 5)) + let afterCopy := Function.update base (tape 5) + (base (idTape tape field) ++ encodeWords (suffixWords shape mode) ++ base (tape 5)) + have first : (advance (TM2.step program))^[1] + (some ⟨some (labels .suffix), clean ambient, base⟩) = + some ⟨some (labels .copyOut), clean ambient, afterSuffix⟩ := by + rw [Function.iterate_one, advance_some] + apply literal_step (tape 5) (encodeWords (suffixWords shape mode)) + (some (labels .copyOut)) program (labels .suffix) + rw [atLabels .suffix] + simp only [instruction, hfield] + have hselected : (sourceField shape mode).getD 0 = field := by + rw [hfield] + rfl + have atOut : program (labels .copyOut) = + UniqueGamesTheorem.Reduction.MachineTransfer.loopAt (idTape tape field) (tape 4) id false + (labels .copyOut) (some (labels .copyBack)) := by + rw [atLabels .copyOut] + exact congrArg (fun selected : Fin 4 => + UniqueGamesTheorem.Reduction.MachineTransfer.loopAt (Γ := Alphabet (K := K)) (σ := σ) + (idTape tape selected) (tape 4) id false + (labels .copyOut) (some (labels .copyBack))) hselected + have atBack : program (labels .copyBack) = + MachineCopy.forkLoop (tape 4) (idTape tape field) (tape 5) false + (labels .copyBack) (some (labels .prefix)) := by + rw [atLabels .copyBack] + exact congrArg (fun selected : Fin 4 => + MachineCopy.forkLoop (tape 4) (idTape tape selected) (tape 5) false + (labels .copyBack) (some (labels .prefix))) hselected + have hscratch : afterSuffix (tape 4) = [] := by + simpa only [afterSuffix, Function.update_of_ne (Ne.symm houtputScratch)] using scratchEmpty + have hsource : afterSuffix (idTape tape field) = base (idTape tape field) := by + simp [afterSuffix, hsourceOutput] + have htapes : Function.update afterSuffix (tape 5) + (afterSuffix (idTape tape field) ++ afterSuffix (tape 5)) = afterCopy := by + simp [afterSuffix, afterCopy, hsourceOutput, Function.update_idem, List.append_assoc] + let copied := MachineCopy.copyInTime (idTape tape field) (tape 5) (tape 4) + hsourceOutput hsourceScratch houtputScratch false (labels .copyOut) (labels .copyBack) + (some (labels .prefix)) program atOut atBack afterSuffix hscratch ambient none + have middle := copied.evals_in_steps + change (advance (TM2.step program))^[2 * ((afterSuffix (idTape tape field)).length + 1)] + (some ⟨some (labels .copyOut), clean ambient, afterSuffix⟩) = + some ⟨some (labels .prefix), clean ambient, + Function.update afterSuffix (tape 5) + (afterSuffix (idTape tape field) ++ afterSuffix (tape 5))⟩ at middle + rw [htapes, hsource] at middle + have last : (advance (TM2.step program))^[1] + (some ⟨some (labels .prefix), clean ambient, afterCopy⟩) = + some ⟨exit, clean ambient, Function.update base (tape 5) + ((encodeWords (prefixWords position shape mode) ++ base (idTape tape field) ++ + encodeWords (suffixWords shape mode)) ++ base (tape 5))⟩ := by + rw [Function.iterate_one, advance_some] + have h := literal_step (tape 5) (encodeWords (prefixWords position shape mode)) exit + program (labels .prefix) (atLabels .prefix) afterCopy ambient + simpa only [afterCopy, Function.update_self, Function.update_idem, List.append_assoc] using h + have joined := joinTrace (joinTrace first middle) last + rw [show (1 + 2 * ((base (idTape tape field)).length + 1)) + 1 = + 2 * ((base (idTape tape field)).length + 1) + 2 by omega] at joined + exact joined + +def sourceLength (tape : Fin 6 → K) (base : K → List Bool) : Nat := + ∑ field : Fin 4, (base (idTape tape field)).length + +omit [DecidableEq K] in +theorem selected_length_le (tape : Fin 6 → K) (base : K → List Bool) (field : Fin 4) : + (base (idTape tape field)).length ≤ sourceLength tape base := by + unfold sourceLength + exact Finset.single_le_sum + (f := fun selected : Fin 4 => (base (idTape tape selected)).length) + (fun _ _ => Nat.zero_le _) (Finset.mem_univ field) + +def metadataInTime (position : Fin n) (shape : Shape) (mode : SupportMode) + (occurrence : Nat) (variableIDs : Fin 3 → Nat) + (tape : Fin 6 → K) (distinct : Function.Injective tape) + (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ label, program (labels label) = + instruction position shape mode tape labels exit label) + (base : K → List Bool) + (sourceWords : ∀ field, base (idTape tape field) = encodeWord (fieldValue occurrence variableIDs field)) + (scratchEmpty : base (tape 4) = []) (ambient : σ) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .suffix), clean ambient, base⟩ + (some ⟨exit, clean ambient, Function.update base (tape 5) + (retainedBits position (actualSlot shape occurrence variableIDs) mode ++ base (tape 5))⟩) + (2 * sourceLength tape base + 4) := by + cases hfield : sourceField shape mode with + | none => + refine { + steps := 1 + evals_in_steps := ?_ + steps_le_m := by omega + } + change (advance (TM2.step program))^[1] + (some ⟨some (labels .suffix), clean ambient, base⟩) = + some ⟨exit, clean ambient, Function.update base (tape 5) + (retainedBits position (actualSlot shape occurrence variableIDs) mode ++ base (tape 5))⟩ + have hbits : retainedBits position (actualSlot shape occurrence variableIDs) mode = [] := by + simp only [retainedBits, retainedWords_eq, hfield, encodeWords] + simpa only [hbits, List.nil_append, Function.update_eq_self] using + droppedTrace position shape mode hfield tape labels exit program atLabels base ambient + | some field => + refine { + steps := 2 * ((base (idTape tape field)).length + 1) + 2 + evals_in_steps := ?_ + steps_le_m := ?_ + } + · change (advance (TM2.step program))^[2 * ((base (idTape tape field)).length + 1) + 2] + (some ⟨some (labels .suffix), clean ambient, base⟩) = + some ⟨exit, clean ambient, Function.update base (tape 5) + (retainedBits position (actualSlot shape occurrence variableIDs) mode ++ base (tape 5))⟩ + have hbits : retainedBits position (actualSlot shape occurrence variableIDs) mode = + encodeWords (prefixWords position shape mode) ++ base (idTape tape field) ++ + encodeWords (suffixWords shape mode) := by + rw [sourceWords field] + simp [retainedBits, retainedWords_eq, hfield, encodeWords, List.append_assoc] + rw [hbits] + exact selectedTrace position shape mode field hfield tape distinct labels exit + program atLabels base scratchEmpty ambient + · have hlength := selected_length_le tape base field + omega + +theorem output_frame (tape : Fin 6 → K) (base : K → List Bool) (bits : List Bool) + (k : K) (hne : k ≠ tape 5) : + Function.update base (tape 5) (bits ++ base (tape 5)) k = base k := by + simp [hne] + +theorem label_finite : Finite Label := inferInstance + +theorem state_finite [Finite σ] : Finite (State σ) := inferInstance + +end +end PerfectCompleteness.KeyMetadataMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/LocalCompletionMachineLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/LocalCompletionMachineLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..9348950817b017f14e9769a36afe96265103f4ec --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/LocalCompletionMachineLemmas.lean @@ -0,0 +1,257 @@ +import Mathlib.Data.List.OfFn +import OAI.Computability.PerfectCompleteness.Construction.LocalCompletionFamily +import OAI.Computability.PerfectCompleteness.Decoding.Projection +import OAI.Computability.PerfectCompleteness.Machines.EncodingLemmas +import OAI.Computability.PerfectCompleteness.Machines.FiniteBlockMachineLemmas + +namespace OAI + + +namespace PerfectCompleteness.LocalCompletionMachine + +open Turing +open UniqueGamesTheorem.Foundations.Complexity +open LocalCompletionFamily MachineFixedBlockMap + +noncomputable section + +def inputEnum (q : Nat) : Input q ≃ Fin (Fintype.card (Input q)) := + Fintype.equivFin (Input q) + +def resultEnum (q : Nat) : Result q ≃ Fin (Fintype.card (Result q)) := + Fintype.equivFin (Result q) + +def inputBits {q : Nat} (input : Input q) : List Bool := + FiniteBlockMachine.word (inputEnum q) input + +def resultBits {q : Nat} (result : Result q) : List Bool := + FiniteBlockMachine.word (resultEnum q) result + +@[simp] theorem inputBits_length {q : Nat} (input : Input q) : + (inputBits input).length = Fintype.card (Input q) := + FiniteBlockMachine.word_length (inputEnum q) input + +@[simp] theorem resultBits_length {q : Nat} (result : Result q) : + (resultBits result).length = Fintype.card (Result q) := + FiniteBlockMachine.word_length (resultEnum q) result + +theorem resultBits_injective (q : Nat) : Function.Injective (resultBits (q := q)) := by + intro a b h + exact FiniteBlockMachine.encode_injective (resultEnum q) (List.ofFn_injective h) + +def defaultInput {q : Nat} (hq : 0 < q) : Input q := + (fun _ => false, fun _ => ⟨0, hq⟩) + +def computation {q : Nat} (hq : 0 < q) : + TM2ComputableInPolyTime (inputBits (q := q)) resultBits (lookup hq) := + FiniteBlockMachine.computation (inputEnum q) (resultEnum q) (defaultInput hq) (lookup hq) + +theorem workAlphabet_finite {q : Nat} (hq : 0 < q) (k : (computation hq).tm.K) : + Finite ((computation hq).tm.Γ k) := by + change Finite Bool + infer_instance + +theorem exact_pushBound {q : Nat} (hq : 0 < q) : + Runtime.statementPushBound ((computation hq).tm.m ()) = Fintype.card (Result q) := + FiniteBlockMachine.machine_pushBound (inputEnum q) (resultEnum q) (defaultInput hq) (lookup hq) + +theorem produces_correct_result {q : Nat} (hq : 0 < q) (input : Input q) + (hadmissible : Admissible input) : + ∃ result : Result q, Correct input result ∧ + Nonempty (TM2OutputsInTime (computation hq).tm + (inputBits input) (some (resultBits result)) 1) := by + refine ⟨lookup hq input, lookup_correct hq input hadmissible, ⟨?_⟩⟩ + have h := (computation hq).outputsFun input + change TM2OutputsInTime (computation hq).tm ((inputBits input).map id) + (some ((resultBits (lookup hq input)).map id)) + ((1 : Polynomial Nat).eval (inputBits input).length) at h + rw [Polynomial.eval_one] at h + exact Eq.mp (congrArg₂ + (fun (i o : List Bool) => TM2OutputsInTime (computation hq).tm i (some o) 1) + (List.map_id (inputBits input)) (List.map_id (resultBits (lookup hq input)))) h + +theorem statement_trace {K Λ A : Type} [DecidableEq K] {q : Nat} + (hq : 0 < q) (src dst : K) (exit : Option Λ) (hne : src ≠ dst) + (input : Input q) (suffix : List Bool) + (state : A × Buffer (Fintype.card (Input q))) (tapes : K → List Bool) + (hinput : tapes src = inputBits input ++ suffix) : + TM2.stepAux + (FiniteBlockMachine.statement src dst exit (inputEnum q) (resultEnum q) + (defaultInput hq) (lookup hq)) state tapes = + { l := exit, var := (state.1, emptyBuffer (Fintype.card (Input q))), + stk := Function.update (Function.update tapes src suffix) dst + (resultBits (lookup hq input) ++ tapes dst) } := + FiniteBlockMachine.statement_trace src dst exit hne (inputEnum q) (resultEnum q) + (defaultInput hq) input (lookup hq) suffix state tapes hinput + +end +end PerfectCompleteness.LocalCompletionMachine + + +namespace PerfectCompleteness.LocalCompletionSerialization + +open Turing +open UniqueGamesTheorem.Foundations.Complexity +open LocalCompletionFamily LocalCompletionMachine + +noncomputable section + +def rawTableWords {q : Nat} (result : Result q) (seed : Fin (activeCount result)) : + List Nat := List.ofFn (fun a : Fin (2 * q) => (table result seed a).val) + +@[simp] theorem rawTableWords_length {q : Nat} (result : Result q) + (seed : Fin (activeCount result)) : + (rawTableWords result seed).length = 2 * q := List.length_ofFn + +def payloadWords {q : Nat} (result : Result q) : List Nat := + activeCount result :: (List.finRange (activeCount result)).flatMap (rawTableWords result) + +def payloadBits {q : Nat} (result : Result q) : List Bool := + encodeWords (payloadWords result) + +theorem payloadWords_length {q : Nat} (result : Result q) : + (payloadWords result).length = 1 + activeCount result * (2 * q) := by + have hlen (seeds : List (Fin (activeCount result))) : + (seeds.flatMap (rawTableWords result)).length = seeds.length * (2 * q) := by + induction seeds with + | nil => simp + | cons seed seeds ih => + simp only [List.flatMap_cons, List.length_append, rawTableWords_length, + List.length_cons, ih, Nat.add_mul, Nat.one_mul] + omega + simp only [payloadWords, List.length_cons, hlen, List.length_finRange] + omega + +theorem payloadBits_length_le {q : Nat} (result : Result q) : + (payloadBits result).length ≤ (1 + (2 * q) * (2 * q)) * (2 * q + 1) := by + have hword : ∀ n ∈ payloadWords result, n ≤ 2 * q := by + intro n hn + rcases List.mem_cons.mp hn with h | h + · simpa only [h] using activeCount_le result + · obtain ⟨seed, _, hseed⟩ := List.mem_flatMap.mp h + obtain ⟨a, ha⟩ := List.mem_ofFn.mp hseed + change (table result seed a).val = n at ha + have hrange := (table result seed a).isLt + omega + exact (encodeWords_length_le (payloadWords result) (2 * q) hword).trans + (Nat.mul_le_mul_right (2 * q + 1) (by + rw [payloadWords_length] + exact Nat.add_le_add_left (Nat.mul_le_mul_right (2 * q) (activeCount_le result)) 1)) + +@[simp] theorem decode_payloadBits {q : Nat} (result : Result q) : + decodeWords (payloadBits result) = some (payloadWords result) := + decodeWords_encodeWords _ + +def projection {q : Nat} {input : Input q} {result : Result q} + (correct : Correct input result) (seed : Fin (activeCount result)) : ProjectionTable q := + ProjectionTable.ofMap (table result seed) (by + intro b + simpa only [← Nat.card_eq_fintype_card] using correct.exact_two seed b) + +@[simp] theorem projection_apply {q : Nat} {input : Input q} {result : Result q} + (correct : Correct input result) (seed : Fin (activeCount result)) (a : Fin (2 * q)) : + (projection correct seed).images[a] = table result seed a := by + exact ProjectionTable.ofMap_apply (table result seed) _ a + +theorem rawTableWords_eq {q : Nat} {input : Input q} {result : Result q} + (correct : Correct input result) (seed : Fin (activeCount result)) : + rawTableWords result seed = Encoding.tableWords (projection correct seed) := by + change List.ofFn (fun a => (table result seed a).val) = + (Vector.ofFn (table result seed)).toList.map Fin.val + rw [Vector.toList_ofFn, List.map_ofFn] + rfl + +theorem parse_rawTableWords {q : Nat} {input : Input q} {result : Result q} + (correct : Correct input result) (seed : Fin (activeCount result)) : + Encoding.parseProjection q (rawTableWords result seed) = + some (projection correct seed) := by + rw [rawTableWords_eq correct, Encoding.parseProjection_encoded] + +def parseTables (q : Nat) : Nat → List Nat → Option (List (ProjectionTable q) × List Nat) + | 0, words => some ([], words) + | n + 1, words => do + let head ← Encoding.parseProjection q (words.take (2 * q)) + let (tail, rest) ← parseTables q n (words.drop (2 * q)) + return (head :: tail, rest) + +theorem parseTables_encoded {q : Nat} (tables : List (ProjectionTable q)) + (rest : List Nat) : + parseTables q tables.length (tables.flatMap Encoding.tableWords ++ rest) = + some (tables, rest) := by + induction tables with + | nil => rfl + | cons head tail ih => + have taken := List.take_left' (l₂ := tail.flatMap Encoding.tableWords ++ rest) + (Encoding.tableWords_length head) + have dropped := List.drop_left' (l₂ := tail.flatMap Encoding.tableWords ++ rest) + (Encoding.tableWords_length head) + simp only [List.length_cons, List.flatMap_cons, List.append_assoc, parseTables, + taken, dropped, Encoding.parseProjection_encoded, Option.bind_eq_bind, Option.bind_some, ih] + rfl + +def parsePayload (q : Nat) : List Nat → Option (List (ProjectionTable q)) + | [] => none + | count :: words => do + let (tables, rest) ← parseTables q count words + if rest = [] then some tables else none + +theorem parse_payload {q : Nat} {input : Input q} {result : Result q} + (correct : Correct input result) : + parsePayload q (payloadWords result) = + some ((List.finRange (activeCount result)).map (projection correct)) := by + let seeds := List.finRange (activeCount result) + have hwords : seeds.flatMap (rawTableWords result) = + (seeds.map (projection correct)).flatMap Encoding.tableWords := by + simp only [List.flatMap_map] + congr 1 + funext seed + exact rawTableWords_eq correct seed + have hlen : (seeds.map (projection correct)).length = activeCount result := by + simp [seeds] + have hparse := parseTables_encoded (seeds.map (projection correct)) [] + rw [hlen, List.append_nil] at hparse + change (do + let (tables, rest) ← parseTables q (activeCount result) (seeds.flatMap (rawTableWords result)) + if rest = [] then some tables else none) = _ + rw [hwords, hparse] + rfl + +def emit {q : Nat} (hq : 0 < q) (input : Input q) : List Bool := + payloadBits (lookup hq input) + +def computation {q : Nat} (hq : 0 < q) : + TM2ComputableInPolyTime (inputBits (q := q)) id (emit hq) := + FiniteWordMachine.computation (inputEnum q) (defaultInput hq) (emit hq) + +def machine_output {q : Nat} (hq : 0 < q) (input : Input q) : + TM2OutputsInTime (computation hq).tm (inputBits input) + (some (payloadBits (lookup hq input))) 1 := by + have h := (computation hq).outputsFun input + change TM2OutputsInTime (computation hq).tm ((inputBits input).map id) + (some ((payloadBits (lookup hq input)).map id)) ((1 : Polynomial Nat).eval _) at h + rw [Polynomial.eval_one] at h + exact Eq.mp (congrArg₂ + (fun (i o : List Bool) => TM2OutputsInTime (computation hq).tm i (some o) 1) + (List.map_id (inputBits input)) (List.map_id (payloadBits (lookup hq input)))) h + +theorem machine_output_parses {q : Nat} (hq : 0 < q) (input : Input q) + (hadmissible : Admissible input) : + ∃ result : Result q, ∃ correct : Correct input result, + Nonempty (TM2OutputsInTime (computation hq).tm + (inputBits input) (some (payloadBits result)) 1) ∧ + decodeWords (payloadBits result) >>= parsePayload q = + some ((List.finRange (activeCount result)).map + (projection correct)) := by + refine ⟨lookup hq input, lookup_correct hq input hadmissible, ⟨machine_output hq input⟩, ?_⟩ + rw [decode_payloadBits] + exact parse_payload (lookup_correct hq input hadmissible) + +theorem workAlphabet_finite {q : Nat} (hq : 0 < q) (k : (computation hq).tm.K) : + Finite ((computation hq).tm.Γ k) := by + change Finite Bool + infer_instance + +end +end PerfectCompleteness.LocalCompletionSerialization + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/LowerCutDecoderInput.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/LowerCutDecoderInput.lean new file mode 100644 index 0000000000000000000000000000000000000000..0acf77b4b1efa8b6026a8c110be8e2417e611695 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/LowerCutDecoderInput.lean @@ -0,0 +1,91 @@ +import OAI.Computability.PerfectCompleteness.Machines.HierarchicalLowerMatrixInput + +namespace OAI + +section + +namespace PerfectCompleteness.LowerCutDecoderInput + +noncomputable section + +open scoped Classical +open TreeSourceSpaces HierarchicalArrays + +variable {branch rows : Nat → Nat} {n t : Nat} + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (upper : Nodes branch n) (lowerLevel : Nat) + +abbrev LowerRows (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) := + Fin (rows (Nodes.height (HierarchicalLeftDecoder.LowerNode upper lowerLevel d))) → + HierarchicalDecoderTables.LowerH slots upper lowerLevel d + +theorem backgroundOf_update (arrays : Arrays slots rows) + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) + (fresh : LowerRows (rows := rows) slots upper lowerLevel d) : + HierarchicalMatrixTable.backgroundOf slots upper + (Function.update arrays (HierarchicalLeftDecoder.LowerNode upper lowerLevel d) fresh) = + HierarchicalLowerMatrixInput.updateBackground slots upper lowerLevel + (HierarchicalMatrixTable.backgroundOf slots upper arrays) d + (EvaluationMatrix.ofRows (HierarchicalDecoderTables.LowerH slots upper lowerLevel d) + fresh) := by + funext j + by_cases hj : j = HierarchicalFrozenTables.lowerIndex upper lowerLevel d + · subst j + rw [HierarchicalLowerMatrixInput.updateBackground_selected, + EvaluationMatrix.rows_ofRows] + exact Function.update_self _ _ _ + · have hval : j.val ≠ HierarchicalLeftDecoder.LowerNode upper lowerLevel d := by + intro h + exact hj (Subtype.ext h) + rw [HierarchicalLowerMatrixInput.updateBackground_other slots upper lowerLevel + (HierarchicalMatrixTable.backgroundOf slots upper arrays) d _ j hj] + exact Function.update_of_ne hval _ _ + +theorem upperMatrix_update (arrays : Arrays slots rows) + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) + (fresh : LowerRows (rows := rows) slots upper lowerLevel d) : + NodeEmbedding.matrix + (Function.update arrays (HierarchicalLeftDecoder.LowerNode upper lowerLevel d) fresh) + upper = + NodeEmbedding.matrix arrays upper := by + have hne : upper ≠ HierarchicalLeftDecoder.LowerNode upper lowerLevel d := + (HierarchicalFrozenTables.lowerIndex upper lowerLevel d).property.symm + unfold NodeEmbedding.matrix NodeEmbedding.embeddedRows + rw [Function.update_of_ne hne] + +def actualInput {r : Nat} (arrays : Arrays slots rows) + (A : ManyGoodRows.RowMap (Block rows upper) r) : + HierarchicalAllDecoderTables.Input (rows := rows) slots upper lowerLevel r := + ⟨HierarchicalMatrixTable.backgroundOf slots upper arrays, + (A, A.comp (MatrixRowQuotient.projectMatrix + (HierarchicalFrozenTables.knownRows slots upper lowerLevel + (HierarchicalMatrixTable.backgroundOf slots upper arrays)) + (NodeEmbedding.matrix arrays upper)))⟩ + +theorem actualInput_update {r : Nat} (arrays : Arrays slots rows) + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) + (A : ManyGoodRows.RowMap (Block rows upper) r) + (fresh : LowerRows (rows := rows) slots upper lowerLevel d) : + actualInput slots upper lowerLevel + (Function.update arrays (HierarchicalLeftDecoder.LowerNode upper lowerLevel d) fresh) A = + HierarchicalLowerMatrixInput.input slots upper lowerLevel + (HierarchicalMatrixTable.backgroundOf slots upper arrays) d + (NodeEmbedding.matrix arrays upper) A + (EvaluationMatrix.ofRows (HierarchicalDecoderTables.LowerH slots upper lowerLevel d) + fresh) := by + unfold actualInput + rw [upperMatrix_update slots upper lowerLevel arrays d fresh] + exact congrArg + (fun background : HierarchicalMatrixTable.Background (rows := rows) slots upper => + (⟨background, (A, A.comp (MatrixRowQuotient.projectMatrix + (HierarchicalFrozenTables.knownRows slots upper lowerLevel background) + (NodeEmbedding.matrix arrays upper)))⟩ : + HierarchicalAllDecoderTables.Input (rows := rows) slots upper lowerLevel r)) + (backgroundOf_update slots upper lowerLevel arrays d fresh) + +end +end PerfectCompleteness.LowerCutDecoderInput + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/LowerCutInstalledInput.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/LowerCutInstalledInput.lean new file mode 100644 index 0000000000000000000000000000000000000000..2b091eb33579dc8a064afb0bfb2dcd7ab88e7d6b --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/LowerCutInstalledInput.lean @@ -0,0 +1,188 @@ +import OAI.Computability.PerfectCompleteness.Algebra.LowerCutNodeMatrix +import OAI.Computability.PerfectCompleteness.Decoding.LowerCutPairBackground +import OAI.Computability.PerfectCompleteness.Machines.LowerCutDecoderInput + +namespace OAI + +section + +namespace PerfectCompleteness.LowerCutInstalledInput + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open scoped Classical + +noncomputable section + +variable {branch : Nat → Nat} {n m t : Nat} + +section NodeEquality + +variable (rows : Nat → Nat) (slots : Slots branch n → Fin t → MixedSupport.Slot) + +abbrev NodeRows (node : Nodes branch n) := Fin (rows (Nodes.height node)) → H (nodeSlots slots node) +abbrev NodeMatrix (node : Nodes branch n) := + Module.Dual F2 (H (nodeSlots slots node)) →ₗ[F2] Block rows node + +def rowCast {i j : Nodes branch n} (h : i = j) : + NodeRows rows slots i ≃ₗ[F2] NodeRows rows slots j := by + subst j + exact LinearEquiv.refl F2 _ + +def matrixCast {i j : Nodes branch n} (h : i = j) : + NodeMatrix rows slots i ≃ₗ[F2] NodeMatrix rows slots j := by + subst j + exact LinearEquiv.refl F2 _ + +def scalarCast {i j : Nodes branch n} (h : i = j) : + H (nodeSlots slots i) ≃ₗ[F2] H (nodeSlots slots j) := by + subst j + exact LinearEquiv.refl F2 _ + +def directionCast {i j : Nodes branch n} (h : i = j) : + BucketSampler.Direction (rows (Nodes.height i)) ≃ + BucketSampler.Direction (rows (Nodes.height j)) := by + subst j + exact Equiv.refl _ + +theorem rows_matrixCast {i j : Nodes branch n} (h : i = j) + (X : NodeMatrix rows slots i) : + EvaluationMatrix.rows (H (nodeSlots slots j)) (matrixCast rows slots h X) = + rowCast rows slots h (EvaluationMatrix.rows (H (nodeSlots slots i)) X) := by + subst j + rfl + +theorem shift_matrixCast {i j : Nodes branch n} (h : i = j) + (X : NodeMatrix rows slots i) (a : BucketSampler.Direction (rows (Nodes.height i))) + (v : H (nodeSlots slots i)) : + matrixCast rows slots h (EvaluationMatrix.shift (H (nodeSlots slots i)) X a.val v) = + EvaluationMatrix.shift (H (nodeSlots slots j)) (matrixCast rows slots h X) + (directionCast rows h a).val (scalarCast slots h v) := by + subst j + rfl + +theorem update_rowCast {i j : Nodes branch n} (h : i = j) + (arrays : Arrays slots rows) (S : NodeRows rows slots i) : + Function.update arrays i S = Function.update arrays j (rowCast rows slots h S) := by + subst j + rfl + +end NodeEquality + +variable (rows : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (upper : Nodes branch n) (lowerLevel : Nat) + (d : HierarchicalFrozenTables.LowerNodes upper lowerLevel) + (hnode : WholeArrayInteriorExterior.upperNode p = + HierarchicalLeftDecoder.LowerNode upper lowerLevel d) + +def lowerMatrixEquiv : LowerCutPair.NativeMatrix rows p slots ≃ₗ[F2] + HierarchicalLowerMatrixInput.Matrix (rows := rows) slots upper lowerLevel d := + (LowerCutNodeMatrix.matrixEquiv rows p slots).trans (matrixCast rows slots hnode) + +def lowerScalarEquiv : H (WholeCutGrouping.cutSlots p slots) ≃ₗ[F2] + HierarchicalDecoderTables.LowerH slots upper lowerLevel d := + (LowerCutNodeCoordinates.scalarEquiv p slots).trans (scalarCast slots hnode) + +def lowerDirectionEquiv : BucketSampler.Direction (rows (m + 1)) ≃ + BucketSampler.Direction (rows (Nodes.height (HierarchicalLeftDecoder.LowerNode upper lowerLevel d))) := + (LowerCutNodeCoordinates.directionEquiv rows p).trans (directionCast rows hnode) + +theorem rows_lowerMatrixEquiv (X : LowerCutPair.NativeMatrix rows p slots) : + EvaluationMatrix.rows (HierarchicalDecoderTables.LowerH slots upper lowerLevel d) + (lowerMatrixEquiv rows p slots upper lowerLevel d hnode X) = + rowCast rows slots hnode + (LowerCutNodeCoordinates.rowEquiv rows p slots + (EvaluationMatrix.rows (H (WholeCutGrouping.cutSlots p slots)) X)) := by + change EvaluationMatrix.rows (H (nodeSlots slots (HierarchicalLeftDecoder.LowerNode upper lowerLevel d))) + (matrixCast rows slots hnode (LowerCutNodeMatrix.matrixEquiv rows p slots X)) = _ + rw [rows_matrixCast, LowerCutNodeMatrix.rows_transport] + +theorem shift_lowerMatrixEquiv (X : LowerCutPair.NativeMatrix rows p slots) + (a : BucketSampler.Direction (rows (m + 1))) (v : H (WholeCutGrouping.cutSlots p slots)) : + lowerMatrixEquiv rows p slots upper lowerLevel d hnode + (EvaluationMatrix.shift (H (WholeCutGrouping.cutSlots p slots)) X a.val v) = + EvaluationMatrix.shift (HierarchicalDecoderTables.LowerH slots upper lowerLevel d) + (lowerMatrixEquiv rows p slots upper lowerLevel d hnode X) + (lowerDirectionEquiv rows p upper lowerLevel d hnode a).val + (lowerScalarEquiv p slots upper lowerLevel d hnode v) := by + change matrixCast rows slots hnode + (LowerCutNodeMatrix.matrixEquiv rows p slots + (EvaluationMatrix.shift (H (WholeCutGrouping.cutSlots p slots)) X a.val v)) = _ + rw [LowerCutNodeMatrix.shift_transport] + exact shift_matrixCast rows slots hnode (LowerCutNodeMatrix.matrixEquiv rows p slots X) + (LowerCutNodeCoordinates.directionEquiv rows p a) + (LowerCutNodeCoordinates.scalarEquiv p slots v) + +local instance nativeMatrixFintype : Fintype (LowerCutPair.NativeMatrix rows p slots) := + Fintype.ofEquiv (LowerCutPair.NativeRows rows p slots) + (EvaluationMatrix.rowsEquiv (H (WholeCutGrouping.cutSlots p slots))).symm +local instance lowerMatrixFintype : Fintype + (HierarchicalLowerMatrixInput.Matrix (rows := rows) slots upper lowerLevel d) := + Fintype.ofEquiv + (Fin (rows (Nodes.height (HierarchicalLeftDecoder.LowerNode upper lowerLevel d))) → + HierarchicalDecoderTables.LowerH slots upper lowerLevel d) + (EvaluationMatrix.rowsEquiv (HierarchicalDecoderTables.LowerH slots upper lowerLevel d)).symm + +theorem uniform_lowerMatrixEquiv : + (FiniteDistribution.uniform (LowerCutPair.NativeMatrix rows p slots)).pushforward + (lowerMatrixEquiv rows p slots upper lowerLevel d hnode) = + FiniteDistribution.uniform + (HierarchicalLowerMatrixInput.Matrix (rows := rows) slots upper lowerLevel d) := by + have h := UniformConditioning.uniform_transport + (lowerMatrixEquiv rows p slots upper lowerLevel d hnode).toEquiv + rw [FiniteDistribution.transport_eq_pushforward] at h + exact h + +theorem uniform_lowerMatrix_scalarEquiv : + ((FiniteDistribution.uniform (LowerCutPair.NativeMatrix rows p slots)).product + (FiniteDistribution.uniform (H (WholeCutGrouping.cutSlots p slots)))).pushforward + (fun z => (lowerMatrixEquiv rows p slots upper lowerLevel d hnode z.1, + lowerScalarEquiv p slots upper lowerLevel d hnode z.2)) = + (FiniteDistribution.uniform + (HierarchicalLowerMatrixInput.Matrix (rows := rows) slots upper lowerLevel d)).product + (FiniteDistribution.uniform (HierarchicalDecoderTables.LowerH slots upper lowerLevel d)) := by + have hscalar : + (FiniteDistribution.uniform (H (WholeCutGrouping.cutSlots p slots))).pushforward + (lowerScalarEquiv p slots upper lowerLevel d hnode) = + FiniteDistribution.uniform (HierarchicalDecoderTables.LowerH slots upper lowerLevel d) := by + have h := UniformConditioning.uniform_transport + (lowerScalarEquiv p slots upper lowerLevel d hnode).toEquiv + rw [FiniteDistribution.transport_eq_pushforward] at h + exact h + rw [FiniteDistribution.product_pushforward, uniform_lowerMatrixEquiv, hscalar] + +variable (repeats : Nat → Nat) + +theorem actualInput_installMatrix {r : Nat} + (exterior : WholeCutGrouping.Exterior rows repeats p slots) + (c : LowerCutPairBackground.Complement rows repeats p slots) + (A : ManyGoodRows.RowMap (Block rows upper) r) + (X : LowerCutPair.NativeMatrix rows p slots) : + LowerCutDecoderInput.actualInput slots upper lowerLevel + (LowerCutPairBackground.installMatrix rows repeats p slots exterior c X) A = + HierarchicalLowerMatrixInput.input slots upper lowerLevel + (HierarchicalMatrixTable.backgroundOf slots upper + (LowerCutPairBackground.backgroundArrays rows repeats p slots exterior c)) d + (NodeEmbedding.matrix (LowerCutPairBackground.backgroundArrays rows repeats p slots exterior c) upper) + A (lowerMatrixEquiv rows p slots upper lowerLevel d hnode X) := by + rw [LowerCutPairBackground.installMatrix_eq_update, update_rowCast rows slots hnode] + have h := LowerCutDecoderInput.actualInput_update slots upper lowerLevel + (LowerCutPairBackground.backgroundArrays rows repeats p slots exterior c) d A + (rowCast rows slots hnode (LowerCutNodeCoordinates.rowEquiv rows p slots + (EvaluationMatrix.rows (H (WholeCutGrouping.cutSlots p slots)) X))) + have hX : EvaluationMatrix.ofRows (HierarchicalDecoderTables.LowerH slots upper lowerLevel d) + (rowCast rows slots hnode (LowerCutNodeCoordinates.rowEquiv rows p slots + (EvaluationMatrix.rows (H (WholeCutGrouping.cutSlots p slots)) X))) = + lowerMatrixEquiv rows p slots upper lowerLevel d hnode X := by + rw [← rows_lowerMatrixEquiv rows p slots upper lowerLevel d hnode, + EvaluationMatrix.ofRows_rows] + rw [hX] at h + exact h + +end +end PerfectCompleteness.LowerCutInstalledInput + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/LowerCutOwnInput.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/LowerCutOwnInput.lean new file mode 100644 index 0000000000000000000000000000000000000000..068b5225dfcf2068cf427d77f92e1562e562abd6 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/LowerCutOwnInput.lean @@ -0,0 +1,172 @@ +import OAI.Computability.PerfectCompleteness.Decoding.LowerCutNodeCoordinates +import OAI.Computability.PerfectCompleteness.Decoding.LowerCutPairLemmas +import OAI.Computability.PerfectCompleteness.Machines.OwnInputReferenceLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.LowerCutOwnInput + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open WholeArrayInteriorExterior +open scoped Classical TensorProduct + +noncomputable section + +variable {branch : Nat → Nat} {n t : Nat} + (slots : Slots branch n → Fin t → MixedSupport.Slot) (rows : Nat → Nat) + (upper lower : Nodes branch n) + (W : Submodule F2 (OwnInputReference.UpperVector rows upper)) + +def ofArrays (a : Block rows lower) + (known : HiddenBucketBias.VisibleDirection W → OwnInputReference.UpperSpace slots upper) + (arrays : Arrays slots rows) : OwnInputReference.Input slots rows upper lower W a := + OwnInputReference.readInput slots rows upper lower W a id + (known, OwnInputCanonicalQuery.exteriorOf slots rows upper lower arrays) + +theorem ofArrays_update + (a : BucketSampler.Direction (rows (Nodes.height lower))) + (known : HiddenBucketBias.VisibleDirection W → OwnInputReference.UpperSpace slots upper) + (arrays : Arrays slots rows) (fresh : H (nodeSlots slots lower)) : + ofArrays slots rows upper lower W a.val known + (Function.update arrays lower (LowerDirectionFiber.replace a (arrays lower) fresh)) = + ofArrays slots rows upper lower W a.val known arrays := by + have hother : + (fun node : OwnInputReference.OtherNodes upper lower => + Function.update arrays lower (LowerDirectionFiber.replace a (arrays lower) fresh) node.val) = + (fun node : OwnInputReference.OtherNodes upper lower => arrays node.val) := by + funext node + exact Function.update_of_ne node.property.2 _ _ + change + (OwnInputReference.Input.mk known + (fun node : OwnInputReference.OtherNodes upper lower => + Function.update arrays lower (LowerDirectionFiber.replace a (arrays lower) fresh) node.val) + (LowerDirectionFiber.quotientQuery (H (nodeSlots slots lower)) a + (Function.update arrays lower (LowerDirectionFiber.replace a (arrays lower) fresh) lower))) = + (OwnInputReference.Input.mk known + (fun node : OwnInputReference.OtherNodes upper lower => arrays node.val) + (LowerDirectionFiber.quotientQuery (H (nodeSlots slots lower)) a (arrays lower))) + rw [hother, Function.update_self, LowerDirectionFiber.quotientQuery_replace] + +theorem query_update + (a : BucketSampler.Direction (rows (Nodes.height lower))) + (known : HiddenBucketBias.VisibleDirection W → OwnInputReference.UpperSpace slots upper) + (arrays : Arrays slots rows) (fresh : H (nodeSlots slots lower)) + (hidden : W ⊗[F2] OwnInputReference.UpperSpace slots upper) : + OwnInputReference.query slots rows upper lower W a.val + (ofArrays slots rows upper lower W a.val known + (Function.update arrays lower (LowerDirectionFiber.replace a (arrays lower) fresh))) hidden = + OwnInputReference.query slots rows upper lower W a.val + (ofArrays slots rows upper lower W a.val known arrays) hidden := by + rw [ofArrays_update] + +theorem response_update + (a : BucketSampler.Direction (rows (Nodes.height lower))) + (known : HiddenBucketBias.VisibleDirection W → OwnInputReference.UpperSpace slots upper) + (arrays : Arrays slots rows) (fresh : H (nodeSlots slots lower)) + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (hidden : W ⊗[F2] OwnInputReference.UpperSpace slots upper) : + OwnInputReference.response slots rows upper lower W a.val labeling + (ofArrays slots rows upper lower W a.val known + (Function.update arrays lower (LowerDirectionFiber.replace a (arrays lower) fresh))) hidden = + OwnInputReference.response slots rows upper lower W a.val labeling + (ofArrays slots rows upper lower W a.val known arrays) hidden := by + rw [ofArrays_update] + +theorem quotientFullJoint_update + (a : BucketSampler.Direction (rows (Nodes.height lower))) + (arrays : Arrays slots rows) (fresh : H (nodeSlots slots lower)) : + (BlockQuotient.projectBlock lower a.val ∘ fullJoint + (Function.update arrays lower (LowerDirectionFiber.replace a (arrays lower) fresh))) = + (BlockQuotient.projectBlock lower a.val ∘ fullJoint arrays) := by + funext x + apply Prod.ext + · change LowerDirectionFiber.quotientQuery (H (nodeSlots slots lower)) a + (Function.update arrays lower (LowerDirectionFiber.replace a (arrays lower) fresh) lower) + (restrictNode slots lower x) = + LowerDirectionFiber.quotientQuery (H (nodeSlots slots lower)) a (arrays lower) + (restrictNode slots lower x) + rw [Function.update_self, LowerDirectionFiber.quotientQuery_replace] + · apply Prod.ext + · funext node row + change (Function.update arrays lower (LowerDirectionFiber.replace a (arrays lower) fresh) + node.val row).val (restrictNode slots node.val x) = + (arrays node.val row).val (restrictNode slots node.val x) + rw [Function.update_of_ne node.property] + · rfl + +theorem canonicalQuery_update + (a : BucketSampler.Direction (rows (Nodes.height lower))) + (arrays : Arrays slots rows) (fresh : H (nodeSlots slots lower)) : + OwnInputCanonicalQuery.canonicalQuery slots rows lower a.val + (Function.update arrays lower (LowerDirectionFiber.replace a (arrays lower) fresh)) = + OwnInputCanonicalQuery.canonicalQuery slots rows lower a.val arrays := by + have h := congrArg (TreeCanonical.numberedFunction slots) + (quotientFullJoint_update slots rows lower a arrays fresh) + exact h + +variable {m : Nat} (repeats : Nat → Nat) (p : Path branch n (m + 1)) + +theorem second_eq_update + (exterior : WholeCutGrouping.Exterior rows repeats p slots) + (a : BucketSampler.Direction (rows (m + 1))) + (raw : LowerCutPair.Raw rows repeats p slots) : + LowerCutPair.second rows repeats p slots exterior a raw = + Function.update (LowerCutPair.first rows repeats p slots exterior raw) (upperNode p) + (LowerDirectionFiber.replace (LowerCutNodeCoordinates.directionEquiv rows p a) + (LowerCutPair.first rows repeats p slots exterior raw (upperNode p)) + (LowerCutNodeCoordinates.scalarEquiv p slots (LowerCutPair.fresh rows repeats p slots raw))) := + LowerCutNodeCoordinates.replace_fiber_eq_update rows p slots _ a _ + +theorem ofArrays_second + (exterior : WholeCutGrouping.Exterior rows repeats p slots) + (a : BucketSampler.Direction (rows (m + 1))) + (known : HiddenBucketBias.VisibleDirection W → OwnInputReference.UpperSpace slots upper) + (raw : LowerCutPair.Raw rows repeats p slots) : + ofArrays slots rows upper (upperNode p) W + (LowerCutNodeCoordinates.directionEquiv rows p a).val known + (LowerCutPair.second rows repeats p slots exterior a raw) = + ofArrays slots rows upper (upperNode p) W + (LowerCutNodeCoordinates.directionEquiv rows p a).val known + (LowerCutPair.first rows repeats p slots exterior raw) := by + rw [second_eq_update] + exact ofArrays_update slots rows upper (upperNode p) W _ _ _ _ + +theorem query_second + (exterior : WholeCutGrouping.Exterior rows repeats p slots) + (a : BucketSampler.Direction (rows (m + 1))) + (known : HiddenBucketBias.VisibleDirection W → OwnInputReference.UpperSpace slots upper) + (raw : LowerCutPair.Raw rows repeats p slots) + (hidden : W ⊗[F2] OwnInputReference.UpperSpace slots upper) : + OwnInputReference.query slots rows upper (upperNode p) W + (LowerCutNodeCoordinates.directionEquiv rows p a).val + (ofArrays slots rows upper (upperNode p) W + (LowerCutNodeCoordinates.directionEquiv rows p a).val known + (LowerCutPair.second rows repeats p slots exterior a raw)) hidden = + OwnInputReference.query slots rows upper (upperNode p) W + (LowerCutNodeCoordinates.directionEquiv rows p a).val + (ofArrays slots rows upper (upperNode p) W + (LowerCutNodeCoordinates.directionEquiv rows p a).val known + (LowerCutPair.first rows repeats p slots exterior raw)) hidden := by + rw [ofArrays_second] + +theorem canonicalQuery_second + (exterior : WholeCutGrouping.Exterior rows repeats p slots) + (a : BucketSampler.Direction (rows (m + 1))) + (raw : LowerCutPair.Raw rows repeats p slots) : + OwnInputCanonicalQuery.canonicalQuery slots rows (upperNode p) + (LowerCutNodeCoordinates.directionEquiv rows p a).val + (LowerCutPair.second rows repeats p slots exterior a raw) = + OwnInputCanonicalQuery.canonicalQuery slots rows (upperNode p) + (LowerCutNodeCoordinates.directionEquiv rows p a).val + (LowerCutPair.first rows repeats p slots exterior raw) := by + rw [second_eq_update] + exact canonicalQuery_update slots rows (upperNode p) _ _ _ + +end +end PerfectCompleteness.LowerCutOwnInput + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/MachineCircuit.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/MachineCircuit.lean new file mode 100644 index 0000000000000000000000000000000000000000..a5d19c5815791e1f91628f478e2821f6a0b66743 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/MachineCircuit.lean @@ -0,0 +1,166 @@ +import OAI.Computability.PerfectCompleteness.Machines.StatementCircuit + +namespace OAI + +section + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.MachineCircuit + +open Turing StatementCircuit BoundedExecution +open scoped BigOperators + +variable {K : Type} {Γ : K → Type} {Λ σ : Type} +variable [DecidableEq K] [Fintype Λ] [DecidableEq Λ] +variable [Fintype σ] [DecidableEq σ] +variable [∀ k, Fintype (Γ k)] [∀ k, DecidableEq (Γ k)] + +private theorem bool_ext {a b : Bool} (h : a = true ↔ b = true) : a = b := by + cases a <;> cases b <;> simp_all + +def StepSafe (S : Nat) (program : Λ → TM2.Stmt Γ Λ σ) (cfg : TM2.Cfg Γ Λ σ) : Prop := + ∀ label, cfg.l = some label → StatementSafe S (program label) cfg.var cfg.stk + +noncomputable def liveCase (S : Nat) (program : Λ → TM2.Stmt Γ Λ σ) + (bit : ConfigBit Γ Λ σ S) (label : Λ) : Expr (ConfigBit Γ Λ σ S) := + .and (.input (.inl (some label))) + ((transitionExpr S (program label) bit).rename Sum.inr) + +noncomputable def stickyExpr (S : Nat) (program : Λ → TM2.Stmt Γ Λ σ) + (bit : ConfigBit Γ Λ σ S) : Expr (ConfigBit Γ Λ σ S) := + .or (.and (.input (.inl none)) (.input bit)) + (Expr.disjoin (Finset.univ.toList.map (liveCase S program bit))) + +omit [Fintype Λ] [DecidableEq Λ] [Fintype σ] [DecidableEq σ] + [∀ k, Fintype (Γ k)] [∀ k, DecidableEq (Γ k)] in +theorem absorbing_live (program : Λ → TM2.Stmt Γ Λ σ) (cfg : TM2.Cfg Γ Λ σ) + (label : Λ) (live : cfg.l = some label) : + absorbingNext (TM2.step program) cfg = TM2.stepAux (program label) cfg.var cfg.stk := by + cases cfg with + | mk l v tapes => + change l = some label at live + subst l + rfl + +omit [Fintype Λ] [DecidableEq Λ] [Fintype σ] [DecidableEq σ] + [∀ k, Fintype (Γ k)] [∀ k, DecidableEq (Γ k)] in +theorem absorbing_halted (program : Λ → TM2.Stmt Γ Λ σ) (cfg : TM2.Cfg Γ Λ σ) + (halted : cfg.l = none) : absorbingNext (TM2.step program) cfg = cfg := by + apply absorbingNext_of_none + cases cfg with + | mk l v tapes => + change l = none at halted + subst l + rfl + +omit [Fintype Λ] in +theorem liveCase_eval (S : Nat) (program : Λ → TM2.Stmt Γ Λ σ) + (cfg : TM2.Cfg Γ Λ σ) (safe : StepSafe S program cfg) + (bit : ConfigBit Γ Λ σ S) (label : Λ) : + (liveCase S program bit label).eval (configEncoding S cfg) = + (decide (cfg.l = some label) && + configEncoding S (absorbingNext (TM2.step program) cfg) bit) := by + by_cases live : cfg.l = some label + · simp only [liveCase, Expr.eval, Expr.eval_rename, configEncoding, live, + decide_true, Bool.true_and] + rw [transitionExpr_eval S (program label) cfg.var cfg.stk (safe label live), + absorbing_live program cfg label live] + rfl + · simp [liveCase, Expr.eval, configEncoding, live] + +theorem stickyExpr_eval (S : Nat) (program : Λ → TM2.Stmt Γ Λ σ) + (cfg : TM2.Cfg Γ Λ σ) (safe : StepSafe S program cfg) + (bit : ConfigBit Γ Λ σ S) : + (stickyExpr S program bit).eval (configEncoding S cfg) = + configEncoding S (absorbingNext (TM2.step program) cfg) bit := by + have hactive : + (Expr.disjoin (Finset.univ.toList.map (liveCase S program bit))).eval + (configEncoding S cfg) = true ↔ + ∃ label, cfg.l = some label ∧ + configEncoding S (absorbingNext (TM2.step program) cfg) bit = true := by + rw [Expr.eval_disjoin_true] + simp only [List.mem_map] + constructor + · rintro ⟨e, ⟨label, _, rfl⟩, he⟩ + rw [liveCase_eval S program cfg safe] at he + exact ⟨label, by simpa only [Bool.and_eq_true, decide_eq_true_eq] using he⟩ + · rintro ⟨label, hl, hb⟩ + refine ⟨liveCase S program bit label, ?_, ?_⟩ + · exact ⟨label, by simp, rfl⟩ + · rw [liveCase_eval S program cfg safe] + simp [hl, hb] + apply bool_ext + simp only [stickyExpr, Expr.eval, Bool.or_eq_true, Bool.and_eq_true, hactive] + cases hl : cfg.l with + | none => + rw [absorbing_halted program cfg hl] + simp [configEncoding, hl] + | some label => simp [configEncoding, hl] + +omit [DecidableEq K] [Fintype Λ] [Fintype σ] [∀ k, Fintype (Γ k)] in +theorem configEncoding_injective (S : Nat) (first second : TM2.Cfg Γ Λ σ) + (hfirst : ∀ k, (first.stk k).length ≤ S) + (hsecond : ∀ k, (second.stk k).length ≤ S) + (same : configEncoding S first = configEncoding S second) : first = second := by + have hl : first.l = second.l := by + have h := congrFun same (.inl second.l) + simpa only [configEncoding, decide_true, decide_eq_true_eq] using h + have hv : first.var = second.var := by + have h := congrFun same (.inr (.inl second.var)) + simpa only [configEncoding, inputEncoding, decide_true, decide_eq_true_eq] using h + have ht : first.stk = second.stk := by + funext k + apply StackEncoding.encode_injective (hfirst k) (hsecond k) + funext i + have h := congrFun same (.inr (.inr ⟨k, i, StackEncoding.encode S (second.stk k) i⟩)) + simpa only [configEncoding, inputEncoding, decide_true, decide_eq_true_eq] using h + cases first + cases second + simp only at hl hv ht + cases hl + cases hv + cases ht + rfl + +noncomputable def programCost (program : Λ → TM2.Stmt Γ Λ σ) : Nat := + ∑ label, statementCost (program label) 1 + +omit [DecidableEq K] [DecidableEq Λ] [DecidableEq σ] [∀ k, DecidableEq (Γ k)] in +theorem statementCost_le_programCost (program : Λ → TM2.Stmt Γ Λ σ) (label : Λ) : + statementCost (program label) 1 ≤ programCost program := by + unfold programCost + exact Finset.single_le_sum (f := fun i : Λ => statementCost (program i) 1) + (fun _ _ => Nat.zero_le _) (Finset.mem_univ label) + +noncomputable def expressionCost (program : Λ → TM2.Stmt Γ Λ σ) : Nat := + 5 + Fintype.card Λ * (programCost program + 3) + +omit [DecidableEq K] [DecidableEq Λ] [DecidableEq σ] [∀ k, DecidableEq (Γ k)] in +theorem one_le_expressionCost (program : Λ → TM2.Stmt Γ Λ σ) : + 1 ≤ expressionCost program := by + unfold expressionCost + omega + +theorem stickyExpr_size_le (S : Nat) (program : Λ → TM2.Stmt Γ Λ σ) + (bit : ConfigBit Γ Λ σ S) : + (stickyExpr S program bit).size ≤ expressionCost program := by + have hc : ∀ e ∈ Finset.univ.toList.map (liveCase S program bit), + e.size ≤ programCost program + 2 := by + intro e he + rcases List.mem_map.mp he with ⟨label, _, rfl⟩ + have h := (transitionExpr_size_le S (program label) bit).trans + (statementCost_le_programCost program label) + simp only [liveCase, Expr.size, Expr.size_rename] + omega + have hd := Expr.size_disjoin_le + (Finset.univ.toList.map (liveCase S program bit)) (programCost program + 2) hc + simp only [List.length_map, Finset.length_toList, Finset.card_univ] at hd + simp only [Nat.add_assoc] at hd + rw [show (2 : Nat) + 1 = 3 by decide] at hd + simp only [stickyExpr, Expr.size, expressionCost] + omega + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.MachineCircuit + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/MetadataFreeTapeLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/MetadataFreeTapeLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..9cd894563a5d6fc8e6c581690fc6bf9cef0b94cf --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/MetadataFreeTapeLemmas.lean @@ -0,0 +1,269 @@ +import OAI.Computability.PerfectCompleteness.Machines.CanonicalKeyShapeMachineLemmas +import OAI.Computability.PerfectCompleteness.Sampling.MetadataFreeSampler + +namespace OAI + + +namespace PerfectCompleteness.MetadataFreeTape + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces +open HierarchicalArrays (Arrays Nodes) +open MetadataFreeSampler +open scoped Classical + +noncomputable section + +variable {branch : Nat → Nat} {n d t v m : Nat} + +def tapeEquiv (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (p : Path branch n d) : + ∀ q : PreliminarySampler.Questions branch n t m, + WholeArraySampler.Tape rows repeats p (sourceSlots clauses q) ≃ + WholeArraySampler.Tape rows repeats p (dummyTreeSlots (sourceSigns clauses q)) := by + induction p with + | refl n => + intro q + exact Equiv.refl _ + | @step n d i p ih => + intro q + refine Equiv.piCongrRight (fun k => ?_) + rcases k with u | (u | j) + · exact Equiv.refl _ + · exact ih (fun leaf k => q (i, leaf) k) + · exact Equiv.refl _ + +@[simp] theorem tapeEquiv_root (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (i : Fin (branch n)) (p : Path branch n d) + (q : PreliminarySampler.Questions branch (n + 1) t m) + (ω : WholeArraySampler.Tape rows repeats (.step i p) (sourceSlots clauses q)) : + tapeEquiv clauses rows repeats (.step i p) q ω (.inl ()) = ω (.inl ()) := rfl + +@[simp] theorem tapeEquiv_selected (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (i : Fin (branch n)) (p : Path branch n d) + (q : PreliminarySampler.Questions branch (n + 1) t m) + (ω : WholeArraySampler.Tape rows repeats (.step i p) (sourceSlots clauses q)) : + tapeEquiv clauses rows repeats (.step i p) q ω (.inr (.inl ())) = + tapeEquiv clauses rows repeats p (fun leaf k => q (i, leaf) k) + (ω (.inr (.inl ()))) := rfl + +@[simp] theorem tapeEquiv_ordinary (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (i : Fin (branch n)) (p : Path branch n d) + (q : PreliminarySampler.Questions branch (n + 1) t m) + (ω : WholeArraySampler.Tape rows repeats (.step i p) (sourceSlots clauses q)) + (j : RecursiveSampler.OffPath i) : + tapeEquiv clauses rows repeats (.step i p) q ω (.inr (.inr j)) = + ω (.inr (.inr j)) := rfl + +theorem evaluate_tapeEquiv (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (p : Path branch n d) : + ∀ (q : PreliminarySampler.Questions branch n t m) + (ω : WholeArraySampler.Tape rows repeats p (sourceSlots clauses q)), + WholeArraySampler.evaluate rows repeats p (dummyTreeSlots (sourceSigns clauses q)) + (tapeEquiv clauses rows repeats p q ω) = + WholeArraySampler.evaluate rows repeats p (sourceSlots clauses q) ω := by + induction p with + | refl n => + intro q ω + rfl + | @step n d i p ih => + intro q ω + funext node + rcases node with u | ⟨j, node⟩ + · cases u + rfl + · by_cases hji : j = i + · subst j + have hinner := congrFun + (ih (fun leaf k => q (i, leaf) k) (ω (.inr (.inl ())))) node + exact (WholeArraySampler.evaluate_selected rows repeats i p + (dummyTreeSlots (sourceSigns clauses q)) + (tapeEquiv clauses rows repeats (.step i p) q ω) node).trans + (hinner.trans (WholeArraySampler.evaluate_selected rows repeats i p + (sourceSlots clauses q) ω node).symm) + · let off : RecursiveSampler.OffPath i := ⟨j, hji⟩ + exact (WholeArraySampler.evaluate_ordinary rows repeats i p + (dummyTreeSlots (sourceSigns clauses q)) + (tapeEquiv clauses rows repeats (.step i p) q ω) off node).trans + (WholeArraySampler.evaluate_ordinary rows repeats i p + (sourceSlots clauses q) ω off node).symm + +def evaluateSignedTape (signs : SignTuple branch n t) (rows repeats : Nat → Nat) + (p : Path branch n d) + (ω : WholeArraySampler.Tape rows repeats p (dummyTreeSlots signs)) : + MetadataFreeSampler.Input branch n t rows := + (signs, fun node row x => + HierarchicalArrays.joint + (WholeArraySampler.evaluate rows repeats p (dummyTreeSlots signs) ω) + ((assignmentEquiv signs).symm x) node row) + +theorem evaluateSignedTape_tapeEquiv + (clauses : Fin m → SourceClause.NormalizedClause v) + (q : PreliminarySampler.Questions branch n t m) (rows repeats : Nat → Nat) + (p : Path branch n d) + (ω : WholeArraySampler.Tape rows repeats p (sourceSlots clauses q)) : + evaluateSignedTape (sourceSigns clauses q) rows repeats p + (tapeEquiv clauses rows repeats p q ω) = + MetadataFreeSampler.encodeTape clauses q rows repeats p ω := by + apply Prod.ext + · rfl + · funext node row x + exact congrArg + (fun arrays : Arrays (sourceSlots clauses q) rows => + HierarchicalArrays.joint arrays ((sourceAssignmentEquiv clauses q).symm x) node row) + (evaluate_tapeEquiv clauses rows repeats p q ω) + +abbrev Input (branch : Nat → Nat) (n t : Nat) (rows repeats : Nat → Nat) := + Σ signs : SignTuple branch n t, Σ leaf : Slots branch n, + WholeArraySampler.Tape rows repeats (GeometricPath.leafPath leaf) (dummyTreeSlots signs) × + PreliminarySampler.Choice rows leaf + +instance inputFintype (branch : Nat → Nat) (n t : Nat) (rows repeats : Nat → Nat) : + Fintype (Input branch n t rows repeats) := by + letI : (signs : SignTuple branch n t) → (leaf : Slots branch n) → Fintype + (WholeArraySampler.Tape rows repeats (GeometricPath.leafPath leaf) (dummyTreeSlots signs) × + PreliminarySampler.Choice rows leaf) := fun signs leaf => inferInstance + unfold Input + infer_instance + +def evaluate {rows repeats : Nat → Nat} (data : Input branch n t rows repeats) : + MetadataFreeSampler.Input branch n t rows := + evaluateSignedTape data.1 rows repeats (GeometricPath.leafPath data.2.1) data.2.2.1 + +def encodeRaw (clauses : Fin m → SourceClause.NormalizedClause v) (rows repeats : Nat → Nat) + (e : PreliminarySampler.Raw clauses branch n t rows repeats) : Input branch n t rows repeats := + ⟨sourceSigns clauses e.1.1, e.1.2, + tapeEquiv clauses rows repeats (GeometricPath.leafPath e.1.2) e.1.1 e.2.1, e.2.2⟩ + +theorem evaluate_encodeRaw (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (e : PreliminarySampler.Raw clauses branch n t rows repeats) : + evaluate (encodeRaw clauses rows repeats e) = + MetadataFreeSampler.encodeTape clauses e.1.1 rows repeats + (GeometricPath.leafPath e.1.2) e.2.1 := + evaluateSignedTape_tapeEquiv clauses e.1.1 rows repeats (GeometricPath.leafPath e.1.2) e.2.1 + +def keyInput {rows repeats : Nat → Nat} (data : Input branch n t rows repeats) : + CanonicalKeyShape.Input (TreeCanonical.locationCount branch n t) + (Fintype.card (HierarchicalArrays.Output branch n rows)) := + MetadataFreeSampler.shapeInput (evaluate data) + +theorem keyInput_encodeRaw (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (e : PreliminarySampler.Raw clauses branch n t rows repeats) : + keyInput (encodeRaw clauses rows repeats e) = + CanonicalKeyShape.input (TreeCanonical.numberedSlots (sourceSlots clauses e.1.1)) + (outputEquiv branch n rows ∘ TreeCanonical.numberedFunction (sourceSlots clauses e.1.1) + (HierarchicalArrays.fullJoint + (WholeArraySampler.evaluate rows repeats (GeometricPath.leafPath e.1.2) + (sourceSlots clauses e.1.1) e.2.1))) := by + rw [keyInput, evaluate_encodeRaw] + exact shapeInput_encodeInput clauses e.1.1 _ + +end +end PerfectCompleteness.MetadataFreeTape + + +namespace PerfectCompleteness.MetadataTapeMachine + +open Turing +open UniqueGamesTheorem.Foundations.Complexity +open MetadataFreeTape MetadataFreeSampler + +noncomputable section + +variable {branch : Nat → Nat} {n t : Nat} {rows repeats : Nat → Nat} + +abbrev Symbol (branch : Nat → Nat) (n t : Nat) (rows repeats : Nat → Nat) := + Option (MetadataFreeTape.Input branch n t rows repeats) + +def inputEnum (branch : Nat → Nat) (n t : Nat) (rows repeats : Nat → Nat) : + Symbol branch n t rows repeats ≃ Fin (Fintype.card (Symbol branch n t rows repeats)) := + Fintype.equivFin _ + +def inputBits (data : Symbol branch n t rows repeats) : List Bool := + FiniteBlockMachine.word (inputEnum branch n t rows repeats) data + +def outputBits : Symbol branch n t rows repeats → List Bool + | none => [] + | some data => CanonicalKeyShapeMachine.outputBits (MetadataFreeTape.keyInput data) + +def computation (branch : Nat → Nat) (n t : Nat) (rows repeats : Nat → Nat) : + TM2ComputableInPolyTime + (inputBits (branch := branch) (n := n) (t := t) (rows := rows) (repeats := repeats)) + id outputBits := + FiniteWordMachine.computation (inputEnum branch n t rows repeats) none outputBits + +def machine_output (data : Symbol branch n t rows repeats) : + TM2OutputsInTime (computation branch n t rows repeats).tm + (inputBits data) (some (outputBits data)) 1 := by + have h := (computation branch n t rows repeats).outputsFun data + change TM2OutputsInTime (computation branch n t rows repeats).tm + ((inputBits data).map id) (some ((outputBits data).map id)) + ((1 : Polynomial Nat).eval _) at h + rw [Polynomial.eval_one] at h + exact Eq.mp (congrArg₂ + (fun (i o : List Bool) => + TM2OutputsInTime (computation branch n t rows repeats).tm i (some o) 1) + (List.map_id (inputBits data)) (List.map_id (outputBits data))) h + +theorem statement_trace {K Λ : Type} [DecidableEq K] + (src dst : K) (exit : Option Λ) (hne : src ≠ dst) + (data : Symbol branch n t rows repeats) (suffix : List Bool) + (state : FiniteWordMachine.State (Fintype.card (Symbol branch n t rows repeats))) + (tapes : K → List Bool) (hinput : tapes src = inputBits data ++ suffix) : + TM2.stepAux (FiniteWordMachine.statement src dst exit + (inputEnum branch n t rows repeats) none outputBits) state tapes = { + l := exit + var := ((), UniqueGamesTheorem.Foundations.Complexity.MachineFixedBlockMap.emptyBuffer _) + stk := Function.update (Function.update tapes src suffix) dst + (outputBits data ++ tapes dst) + } := + FiniteWordMachine.statement_trace src dst exit hne + (inputEnum branch n t rows repeats) none data outputBits suffix state tapes hinput + +variable {v m : Nat} + +theorem outputBits_encodeRaw (clauses : Fin m → SourceClause.NormalizedClause v) + (e : PreliminarySampler.Raw clauses branch n t rows repeats) : + outputBits (some (MetadataFreeTape.encodeRaw clauses rows repeats e)) = + CanonicalKeyShapeMachine.outputBits + (CanonicalKeyShape.input + (TreeCanonical.numberedSlots (sourceSlots clauses e.1.1)) + (outputEquiv branch n rows ∘ TreeCanonical.numberedFunction + (sourceSlots clauses e.1.1) (HierarchicalArrays.fullJoint + (WholeArraySampler.evaluate rows repeats (GeometricPath.leafPath e.1.2) + (sourceSlots clauses e.1.1) e.2.1)))) := by + change CanonicalKeyShapeMachine.outputBits + (MetadataFreeTape.keyInput (MetadataFreeTape.encodeRaw clauses rows repeats e)) = _ + rw [MetadataFreeTape.keyInput_encodeRaw] + +theorem recoverKey_encodeRaw (side : CanonicalKeys.Side) + (clauses : Fin m → SourceClause.NormalizedClause v) + (e : PreliminarySampler.Raw clauses branch n t rows repeats) : + CanonicalKeyShapeMachine.recoverKey side + (TreeCanonical.numberedSlots (sourceSlots clauses e.1.1)) + (MetadataFreeTape.keyInput (MetadataFreeTape.encodeRaw clauses rows repeats e)) = + CanonicalKeys.key side (TreeCanonical.numberedSlots (sourceSlots clauses e.1.1)) + (TreeCanonical.numberedFunction (sourceSlots clauses e.1.1) + (HierarchicalArrays.fullJoint + (WholeArraySampler.evaluate rows repeats (GeometricPath.leafPath e.1.2) + (sourceSlots clauses e.1.1) e.2.1))) := by + rw [MetadataFreeTape.keyInput_encodeRaw, CanonicalKeyShapeMachine.recoverKey_input] + exact CanonicalKeys.key_postcomp_equiv side _ _ (outputEquiv branch n rows) + +theorem actual_machine_output (clauses : Fin m → SourceClause.NormalizedClause v) + (e : PreliminarySampler.Raw clauses branch n t rows repeats) : + Nonempty (TM2OutputsInTime (computation branch n t rows repeats).tm + (inputBits (some (MetadataFreeTape.encodeRaw clauses rows repeats e))) + (some (CanonicalKeyShapeMachine.outputBits + (MetadataFreeTape.keyInput (MetadataFreeTape.encodeRaw clauses rows repeats e)))) 1) := + ⟨machine_output (some (MetadataFreeTape.encodeRaw clauses rows repeats e))⟩ + +theorem workAlphabet_finite (branch : Nat → Nat) (n t : Nat) (rows repeats : Nat → Nat) + (tape : (computation branch n t rows repeats).tm.K) : + Finite ((computation branch n t rows repeats).tm.Γ tape) := by + change Finite Bool + infer_instance + +end +end PerfectCompleteness.MetadataTapeMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/NormalizationEmitMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/NormalizationEmitMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..e8c099f9d271896adf7c0463d97b795bad58947d --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/NormalizationEmitMachine.lean @@ -0,0 +1,312 @@ +import OAI.Computability.PerfectCompleteness.Foundations.NormalizationLemmas +import OAI.Computability.UniqueGames.Machines.MachineCompositionLemmas +import OAI.Computability.UniqueGames.Machines.MachineCopy +import OAI.Computability.UniqueGames.Reduction.MachineSubstitution + +namespace OAI + + +namespace PerfectCompleteness.NormalizationEmitMachine + + +open Turing +open UniqueGamesTheorem.Foundations.Complexity +open MachineComposition +open UniqueGamesTheorem.Reduction.MachineTransfer +open UniqueGamesTheorem.Reduction.MachineSubstitution +open NormalizationWords + +variable {K Λ A : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool +abbrev State (A : Type) := (A × Signs) × Option Bool + +def clean (ambient : A) (signs : Signs) : State A := ((ambient, signs), none) + +def sourceIndex : NameRef → Fin 6 + | .old i => ⟨i.val + 1, by have := i.isLt; omega⟩ + | .fresh _ => 0 + +theorem sourceIndex_ne_scratch (name : NameRef) : sourceIndex name ≠ 4 := by + cases name with + | old i => + intro h + have hi := i.isLt + have hv := congrArg Fin.val h + simp only [sourceIndex] at hv + omega + | fresh i => simp [sourceIndex] + +theorem sourceIndex_ne_output (name : NameRef) : sourceIndex name ≠ 5 := by + cases name with + | old i => + intro h + have hi := i.isLt + have hv := congrArg Fin.val h + simp only [sourceIndex] at hv + omega + | fresh i => simp [sourceIndex] + +inductive LocalLabel + | copyOut + | copyBack + | emit + deriving DecidableEq + +protected abbrev LocalLabel.enumList : List LocalLabel := [.copyOut, .copyBack, .emit] + +protected theorem LocalLabel.enumList_getElem?_ctorIdx_eq (x : LocalLabel) : + LocalLabel.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem LocalLabel.enumList_nodup : LocalLabel.enumList.Nodup := by decide + +instance : Fintype LocalLabel where + elems := ⟨LocalLabel.enumList, LocalLabel.enumList_nodup⟩ + complete x := by cases x <;> decide + +def emitSign (output : K) (sign : SignRef) (exit : Option Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (State A) := + .branch (fun state => signValue state.1.2 sign) + (.push output (fun _ => true) + (.push output (fun _ => false) (exitAt output exit))) + (.push output (fun _ => false) (exitAt output exit)) + +def emit (output : K) (literal : LiteralRecipe) (exit : Option Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (State A) := + pushWord output (List.replicate (offset literal.name) true ++ [false]) + (emitSign output literal.sign exit) + +def localInstruction (tape : Fin 6 → K) (literal : LiteralRecipe) + (labels : LocalLabel → Λ) (exit : Option Λ) : + LocalLabel → TM2.Stmt (Alphabet (K := K)) Λ (State A) + | .copyOut => loopAt (tape (sourceIndex literal.name)) (tape 4) id false + (labels .copyOut) (some (labels .copyBack)) + | .copyBack => MachineCopy.forkLoop (tape 4) (tape (sourceIndex literal.name)) + (tape 5) false (labels .copyBack) (some (labels .emit)) + | .emit => emit (tape 5) literal exit + +private theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +theorem stepAux_emit (output : K) (literal : LiteralRecipe) (exit : Option Λ) + (base : K → List Bool) (ambient : A) (signs : Signs) (names : Names) (freshBase : Nat) : + TM2.stepAux (emit output literal exit) (clean ambient signs) + (Function.update base output + (List.replicate (sourceValue names freshBase literal.name) true ++ base output)) = + ⟨exit, clean ambient signs, Function.update base output + ((literalBits signs names freshBase literal).reverse ++ base output)⟩ := by + have nameOrder : nameValue names freshBase literal.name = + offset literal.name + sourceValue names freshBase literal.name := by + exact Nat.add_comm _ _ + have swapped : List.replicate (offset literal.name) true ++ + (List.replicate (sourceValue names freshBase literal.name) true ++ base output) = + List.replicate (sourceValue names freshBase literal.name) true ++ + (List.replicate (offset literal.name) true ++ base output) := by + calc + _ = List.replicate + (offset literal.name + sourceValue names freshBase literal.name) true ++ base output := by + rw [List.replicate_add, List.append_assoc] + _ = List.replicate + (sourceValue names freshBase literal.name + offset literal.name) true ++ base output := by + rw [Nat.add_comm (offset literal.name) (sourceValue names freshBase literal.name)] + _ = _ := by rw [List.replicate_add, List.append_assoc] + unfold emit + rw [stepAux_pushWord] + cases hs : signValue signs literal.sign <;> cases exit <;> + simp [emitSign, clean, TM2.stepAux, exitAt, hs, literalBits, + NormalizationWords.literalWords, encodeWords, encodeWord, nameOrder, + List.reverse_append, List.reverse_replicate, List.replicate_add, List.append_assoc, + -List.replicate_append_replicate] <;> + rw [swapped] + +theorem literalTrace (tape : Fin 6 → K) (distinct : Function.Injective tape) + (literal : LiteralRecipe) (labels : LocalLabel → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ l, program (labels l) = localInstruction tape literal labels exit l) + (base : K → List Bool) (ambient : A) (signs : Signs) (names : Names) (freshBase : Nat) + (sourceWord : base (tape (sourceIndex literal.name)) = + List.replicate (sourceValue names freshBase literal.name) true) + (scratchEmpty : base (tape 4) = []) : + (advance (TM2.step program))^[2 * (sourceValue names freshBase literal.name + 1) + 1] + (some ⟨some (labels .copyOut), clean ambient signs, base⟩) = + some ⟨exit, clean ambient signs, Function.update base (tape 5) + ((literalBits signs names freshBase literal).reverse ++ base (tape 5))⟩ := by + have hd (i j : Fin 6) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + have copied := MachineCopy.copyTrace (tape (sourceIndex literal.name)) (tape 5) (tape 4) + (hd _ _ (sourceIndex_ne_output _)) (hd _ _ (sourceIndex_ne_scratch _)) + (hd 5 4 (by decide)) false (labels .copyOut) (labels .copyBack) + (some (labels .emit)) program (atLabels .copyOut) (atLabels .copyBack) + base scratchEmpty (ambient, signs) none + rw [sourceWord, List.length_replicate] at copied + have emitted : (advance (TM2.step program))^[1] + (some ⟨some (labels .emit), clean ambient signs, + Function.update base (tape 5) + (List.replicate (sourceValue names freshBase literal.name) true ++ base (tape 5))⟩) = + some ⟨exit, clean ambient signs, Function.update base (tape 5) + ((literalBits signs names freshBase literal).reverse ++ base (tape 5))⟩ := by + change some (TM2.stepAux (program (labels .emit)) _ _) = _ + rw [atLabels .emit] + exact congrArg some (stepAux_emit (tape 5) literal exit base ambient signs names freshBase) + exact joinTrace copied emitted + +def result (signs : Signs) (names : Names) (freshBase : Nat) + (literal : LiteralRecipe) (output : List Bool) : List Bool := + (literalBits signs names freshBase literal).reverse ++ output + +def cost (names : Names) (freshBase : Nat) (literal : LiteralRecipe) (_ : List Bool) : Nat := + 2 * (sourceValue names freshBase literal.name + 1) + 1 + +def commandSteps (names : Names) (freshBase : Nat) (commands : List LiteralRecipe) : Nat := + (commands.map (fun literal => 2 * (sourceValue names freshBase literal.name + 1) + 1)).sum + +theorem resultOf_eq (signs : Signs) (names : Names) (freshBase : Nat) + (commands : List LiteralRecipe) (output : List Bool) : + MachineFiniteSequence.resultOf (result signs names freshBase) commands output = + (commands.flatMap (literalBits signs names freshBase)).reverse ++ output := by + induction commands generalizing output with + | nil => rfl + | cons literal commands ih => + simp only [MachineFiniteSequence.resultOf, ih, result, List.flatMap_cons, + List.reverse_append, List.append_assoc] + +theorem sequenceSteps_eq (signs : Signs) (names : Names) (freshBase : Nat) + (commands : List LiteralRecipe) (output : List Bool) : + MachineFiniteSequence.steps (result signs names freshBase) (cost names freshBase) + commands output = commandSteps names freshBase commands := by + induction commands generalizing output with + | nil => rfl + | cons literal commands ih => + simp only [MachineFiniteSequence.steps, ih, commandSteps, List.map_cons, + List.sum_cons, cost] + +theorem sourceValue_le (names : Names) (freshBase maximum : Nat) + (freshBound : freshBase ≤ maximum) (nameBounds : ∀ i, names i ≤ maximum) + (name : NameRef) : sourceValue names freshBase name ≤ maximum := by + cases name with + | old i => exact nameBounds i + | fresh i => exact freshBound + +theorem commandSteps_le (names : Names) (freshBase maximum : Nat) + (freshBound : freshBase ≤ maximum) (nameBounds : ∀ i, names i ≤ maximum) + (commands : List LiteralRecipe) : + commandSteps names freshBase commands ≤ commands.length * (2 * maximum + 3) := by + induction commands with + | nil => simp [commandSteps] + | cons literal commands ih => + have current := sourceValue_le names freshBase maximum freshBound nameBounds literal.name + simp only [commandSteps, List.map_cons, List.sum_cons, List.length_cons, + Nat.add_mul, Nat.one_mul] at ih ⊢ + omega + +abbrev Labels (commands : List LiteralRecipe) := + MachineFiniteSequence.Label (fun _ : LiteralRecipe => LocalLabel) commands + +def sequenceInstruction (tape : Fin 6 → K) (commands : List LiteralRecipe) + (labels : Labels commands → Λ) (exit : Option Λ) : + Labels commands → TM2.Stmt (Alphabet (K := K)) Λ (State A) := + MachineFiniteSequence.instruction (fun _ => LocalLabel) (fun _ => LocalLabel.copyOut) + (localInstruction tape) commands labels exit + +def sequenceEntry (commands : List LiteralRecipe) (labels : Labels commands → Λ) + (exit : Option Λ) : Option Λ := + MachineFiniteSequence.entry (fun _ => LocalLabel) (fun _ => LocalLabel.copyOut) + commands labels exit + +theorem sequenceTrace (tape : Fin 6 → K) (distinct : Function.Injective tape) + (commands : List LiteralRecipe) (labels : Labels commands → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ l, program (labels l) = sequenceInstruction tape commands labels exit l) + (base : K → List Bool) (ambient : A) (signs : Signs) (names : Names) (freshBase : Nat) + (sourceWords : ∀ name, base (tape (sourceIndex name)) = + List.replicate (sourceValue names freshBase name) true) + (scratchEmpty : base (tape 4) = []) : + (advance (TM2.step program))^[commandSteps names freshBase commands] + (some ⟨sequenceEntry commands labels exit, clean ambient signs, base⟩) = + some ⟨exit, clean ambient signs, Function.update base (tape 5) + ((commands.flatMap (literalBits signs names freshBase)).reverse ++ base (tape 5))⟩ := by + have hd (i j : Fin 6) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + have native := MachineFiniteSequence.trace (fun _ : LiteralRecipe => LocalLabel) + (fun _ => LocalLabel.copyOut) (localInstruction tape) + (result signs names freshBase) (cost names freshBase) program + (fun _ => True) (fun _ => clean ambient signs) + (fun output => Function.update base (tape 5) output) commands + (fun _ _ _ _ => True.intro) + (fun literal _ localLabels localExit localEquations output _ => by + have actual := literalTrace tape distinct literal localLabels localExit program + localEquations (Function.update base (tape 5) output) ambient signs names freshBase + (by simp [hd (sourceIndex literal.name) 5 (sourceIndex_ne_output literal.name), sourceWords]) + (by simp [hd 4 5 (by decide), scratchEmpty]) + simpa only [cost, result, Function.update_self, Function.update_idem] using actual) + labels exit atLabels (base (tape 5)) True.intro + simpa only [sequenceSteps_eq, resultOf_eq, Function.update_eq_self, + sequenceEntry] using native + +abbrev Label := Labels recipe + +def main : Label := .inl .copyOut + +def instruction (tape : Fin 6 → K) (labels : Label → Λ) (exit : Option Λ) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (State A) := + sequenceInstruction tape recipe labels exit + +def steps (names : Names) (freshBase : Nat) : Nat := commandSteps names freshBase recipe + +theorem steps_le (names : Names) (freshBase maximum : Nat) + (freshBound : freshBase ≤ maximum) (nameBounds : ∀ i, names i ≤ maximum) : + steps names freshBase ≤ 39 * (2 * maximum + 3) := by + simpa only [steps, recipe_length] using + commandSteps_le names freshBase maximum freshBound nameBounds recipe + +theorem gadgetTrace (tape : Fin 6 → K) (distinct : Function.Injective tape) + (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ l, program (labels l) = instruction tape labels exit l) + (base : K → List Bool) (ambient : A) (signs : Signs) (names : Names) (freshBase : Nat) + (freshWord : base (tape 0) = List.replicate freshBase true) + (oldWords : ∀ i, base (tape (sourceIndex (.old i))) = List.replicate (names i) true) + (scratchEmpty : base (tape 4) = []) : + (advance (TM2.step program))^[steps names freshBase] + (some ⟨some (labels main), clean ambient signs, base⟩) = + some ⟨exit, clean ambient signs, Function.update base (tape 5) + ((bits signs names freshBase).reverse ++ base (tape 5))⟩ := by + have sources : ∀ name, base (tape (sourceIndex name)) = + List.replicate (sourceValue names freshBase name) true := by + intro name + cases name with + | old i => exact oldWords i + | fresh i => exact freshWord + have trace := sequenceTrace tape distinct recipe labels exit program atLabels + base ambient signs names freshBase sources scratchEmpty + have entry : sequenceEntry recipe labels exit = some (labels main) := rfl + rw [← bits_eq_flatMap] at trace + simpa only [steps, entry] using trace + +def gadgetInTime (tape : Fin 6 → K) (distinct : Function.Injective tape) + (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ l, program (labels l) = instruction tape labels exit l) + (base : K → List Bool) (ambient : A) (signs : Signs) (names : Names) + (freshBase maximum : Nat) + (freshWord : base (tape 0) = List.replicate freshBase true) + (oldWords : ∀ i, base (tape (sourceIndex (.old i))) = List.replicate (names i) true) + (scratchEmpty : base (tape 4) = []) + (freshBound : freshBase ≤ maximum) (nameBounds : ∀ i, names i ≤ maximum) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels main), clean ambient signs, base⟩ + (some ⟨exit, clean ambient signs, Function.update base (tape 5) + ((bits signs names freshBase).reverse ++ base (tape 5))⟩) + (39 * (2 * maximum + 3)) where + steps := steps names freshBase + evals_in_steps := gadgetTrace tape distinct labels exit program atLabels base ambient + signs names freshBase freshWord oldWords scratchEmpty + steps_le_m := steps_le names freshBase maximum freshBound nameBounds + +theorem label_finite : Finite Label := inferInstance + +theorem state_finite [Finite A] : Finite (State A) := inferInstance + +end PerfectCompleteness.NormalizationEmitMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/NormalizationLoopMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/NormalizationLoopMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..facc798a8d504174c5d65888b13021c12390e77b --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/NormalizationLoopMachine.lean @@ -0,0 +1,467 @@ +import OAI.Computability.PerfectCompleteness.Foundations.NormalizationLemmas +import OAI.Computability.PerfectCompleteness.Machines.NormalizationEmitMachine +import OAI.Computability.PerfectCompleteness.Machines.NormalizationReadMachine +import OAI.Computability.UniqueGames.Machines.MachineDrain + +namespace OAI + + +namespace PerfectCompleteness.NormalizationLoopMachine + + +open Turing +open UniqueGamesTheorem.Foundations +open Complexity Complexity.MachineComposition +open UniqueGamesTheorem.Reduction.MachineSubstitution +open NormalizationWords + +def nameSum {n : Nat} (clause : Target.Clause n) : Nat := + clause[0].variableIndex.val + clause[1].variableIndex.val + clause[2].variableIndex.val + +def bodySteps {n : Nat} (freshBase : Nat) (clause : Target.Clause n) : Nat := + 1 + (nameSum clause + 6) + NormalizationEmitMachine.steps (clauseNames clause) freshBase + + (clause[0].variableIndex.val + 1) + (clause[1].variableIndex.val + 1) + + (clause[2].variableIndex.val + 1) + 1 + +def steps {n : Nat} (freshBase : Nat) : List (Target.Clause n) → Nat + | [] => 1 + | clause :: clauses => bodySteps freshBase clause + steps (freshBase + 4) clauses + +theorem bodySteps_le {n : Nat} (freshBase maximum : Nat) (clause : Target.Clause n) + (nameBound : n ≤ maximum) (freshBound : freshBase ≤ maximum) : + bodySteps freshBase clause ≤ 84 * maximum + 128 := by + have oldBounds (i : Fin 3) : clauseNames clause i ≤ maximum := + (Nat.le_of_lt clause[i].variableIndex.isLt).trans nameBound + have emitted := NormalizationEmitMachine.steps_le (clauseNames clause) + freshBase maximum freshBound oldBounds + have h0 := oldBounds 0 + have h1 := oldBounds 1 + have h2 := oldBounds 2 + simp only [clauseNames] at h0 h1 h2 + unfold bodySteps nameSum + omega + +theorem steps_le {n : Nat} (freshBase maximum : Nat) (clauses : List (Target.Clause n)) + (nameBound : n ≤ maximum) (freshBound : freshBase + 4 * clauses.length ≤ maximum) : + steps freshBase clauses ≤ clauses.length * (84 * maximum + 128) + 1 := by + induction clauses generalizing freshBase with + | nil => simp [steps] + | cons clause clauses ih => + have head := bodySteps_le freshBase maximum clause nameBound (by + simp only [List.length_cons] at freshBound + omega) + have tail := ih (freshBase + 4) (by + simp only [List.length_cons] at freshBound + omega) + simp only [steps, List.length_cons, Nat.add_mul, Nat.one_mul] + omega + +section Program + +variable {K Λ A : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool +abbrev State (A : Type) := (A × Signs) × Option Bool +abbrev clean (ambient : A) (signs : Signs) : State A := NormalizationEmitMachine.clean ambient signs +def reset (ambient : A) : State A := clean ambient (fun _ => false) + +def readerIndex : Fin 4 → Fin 9 + | 0 => 0 + | 1 => 4 + | 2 => 5 + | 3 => 6 + +def emitterIndex : Fin 6 → Fin 9 + | 0 => 1 + | 1 => 4 + | 2 => 5 + | 3 => 6 + | 4 => 7 + | 5 => 8 + +def oldIndex (slot : Fin 3) : Fin 9 := ⟨slot.val + 4, by have := slot.isLt; omega⟩ + +def readerTapes (tape : Fin 9 → K) : Fin 4 → K := fun i => tape (readerIndex i) +def emitterTapes (tape : Fin 9 → K) : Fin 6 → K := fun i => tape (emitterIndex i) + +omit [DecidableEq K] in +theorem readerTapes_injective (tape : Fin 9 → K) (distinct : Function.Injective tape) : + Function.Injective (readerTapes tape) := + distinct.comp (by decide : Function.Injective readerIndex) + +omit [DecidableEq K] in +theorem emitterTapes_injective (tape : Fin 9 → K) (distinct : Function.Injective tape) : + Function.Injective (emitterTapes tape) := + distinct.comp (by decide : Function.Injective emitterIndex) + +inductive Label + | guard + | read (label : NormalizationReadMachine.Label) + | emit (label : NormalizationEmitMachine.Label) + | drain (slot : Fin 3) + | tally + deriving DecidableEq, Fintype + +def afterDrain (labels : Label → Λ) (slot : Fin 3) : Λ := + if slot = 0 then labels (.drain 1) else if slot = 1 then labels (.drain 2) else labels .tally + +def finish (exit : Option Λ) : TM2.Stmt (Alphabet (K := K)) Λ (State A) := + .load (fun state => reset state.1.1) + (match exit with + | none => .halt + | some label => .goto fun _ => label) + +def instruction (tape : Fin 9 → K) (labels : Label → Λ) (done rejected : Option Λ) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (State A) + | .guard => + .pop (tape 2) (fun state head => (state.1, head)) + (.branch (fun state => state.2.isNone) + (finish done) + (.branch (fun state => state.2.getD false) + (finish (some (labels (.read (.field 0))))) (finish rejected))) + | .read l => NormalizationReadMachine.instruction (readerTapes tape) + (fun l => labels (.read l)) (some (labels (.emit NormalizationEmitMachine.main))) rejected l + | .emit l => NormalizationEmitMachine.instruction (emitterTapes tape) + (fun l => labels (.emit l)) (some (labels (.drain 0))) l + | .drain slot => MachineDrain.drain (tape (oldIndex slot)) (labels (.drain slot)) + (some (afterDrain labels slot)) + | .tally => pushWord (tape 1) (List.replicate 4 true) + (pushWord (tape 3) (List.replicate 13 true) (finish (some (labels .guard)))) + +def loopTapes (tape : Fin 9 → K) (base : K → List Bool) (input : List Bool) + (freshBase remaining : Nat) (clauseCounter output : List Bool) : K → List Bool := + Function.update (Function.update (Function.update (Function.update (Function.update base + (tape 0) input) (tape 1) (List.replicate freshBase true)) + (tape 2) (List.replicate remaining true)) (tape 3) clauseCounter) (tape 8) output + +theorem loopTapes_input (tape : Fin 9 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (input : List Bool) (freshBase remaining : Nat) + (clauseCounter output : List Bool) : + loopTapes tape base input freshBase remaining clauseCounter output (tape 0) = input := by + have hd (i j : Fin 9) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + simp [loopTapes, hd] + +theorem loopTapes_fresh (tape : Fin 9 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (input : List Bool) (freshBase remaining : Nat) + (clauseCounter output : List Bool) : + loopTapes tape base input freshBase remaining clauseCounter output (tape 1) = + List.replicate freshBase true := by + have hd (i j : Fin 9) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + simp [loopTapes, hd] + +theorem loopTapes_remaining (tape : Fin 9 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (input : List Bool) (freshBase remaining : Nat) + (clauseCounter output : List Bool) : + loopTapes tape base input freshBase remaining clauseCounter output (tape 2) = + List.replicate remaining true := by + have hd (i j : Fin 9) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + simp [loopTapes, hd] + +theorem loopTapes_count (tape : Fin 9 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (input : List Bool) (freshBase remaining : Nat) + (clauseCounter output : List Bool) : + loopTapes tape base input freshBase remaining clauseCounter output (tape 3) = + clauseCounter := by + have hd (i j : Fin 9) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + simp [loopTapes, hd] + +theorem loopTapes_output (tape : Fin 9 → K) (base : K → List Bool) (input : List Bool) + (freshBase remaining : Nat) (clauseCounter output : List Bool) : + loopTapes tape base input freshBase remaining clauseCounter output (tape 8) = output := by + simp [loopTapes] + +private theorem update_remaining (tape : Fin 9 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (input : List Bool) (freshBase remaining replacement : Nat) + (clauseCounter output : List Bool) : + Function.update (loopTapes tape base input freshBase remaining clauseCounter output) + (tape 2) (List.replicate replacement true) = + loopTapes tape base input freshBase replacement clauseCounter output := by + have hd (i j : Fin 9) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + funext k + by_cases h : k = tape 2 + · subst k; simp [loopTapes, hd] + · simp [loopTapes, h, Function.update_apply] + +private theorem update_fresh (tape : Fin 9 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (input : List Bool) (freshBase remaining replacement : Nat) + (clauseCounter output : List Bool) : + Function.update (loopTapes tape base input freshBase remaining clauseCounter output) + (tape 1) (List.replicate replacement true) = + loopTapes tape base input replacement remaining clauseCounter output := by + have hd (i j : Fin 9) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + funext k + by_cases h : k = tape 1 + · subst k; simp [loopTapes, hd] + · simp [loopTapes, h, Function.update_apply] + +private theorem update_count (tape : Fin 9 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (input : List Bool) (freshBase remaining : Nat) + (clauseCounter output replacement : List Bool) : + Function.update (loopTapes tape base input freshBase remaining clauseCounter output) + (tape 3) replacement = + loopTapes tape base input freshBase remaining replacement output := by + have hd (i j : Fin 9) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + funext k + by_cases h : k = tape 3 + · subst k; simp [loopTapes, hd] + · simp [loopTapes, h, Function.update_apply] + +@[simp] theorem stepAux_finish (exit : Option Λ) (state : State A) (base : K → List Bool) : + TM2.stepAux (finish exit) state base = ⟨exit, reset state.1.1, base⟩ := by + cases exit <;> rfl + +private theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +variable (tape : Fin 9 → K) (distinct : Function.Injective tape) +variable (labels : Label → Λ) (done rejected : Option Λ) +variable (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) +variable (atLabels : ∀ l, program (labels l) = instruction tape labels done rejected l) +variable (base : K → List Bool) (ambient : A) + +include distinct atLabels + +theorem guardStep (input : List Bool) (freshBase remaining : Nat) + (clauseCounter output : List Bool) : + TM2.step program + ⟨some (labels .guard), reset ambient, + loopTapes tape base input freshBase (remaining + 1) clauseCounter output⟩ = + some ⟨some (labels (.read (.field 0))), reset ambient, + loopTapes tape base input freshBase remaining clauseCounter output⟩ := by + change some (TM2.stepAux (program (labels .guard)) _ _) = _ + rw [atLabels .guard] + simp [instruction, TM2.stepAux, reset, clean, NormalizationEmitMachine.clean, + loopTapes_remaining tape distinct, List.replicate_succ, update_remaining tape distinct] + +theorem emptyStep (input : List Bool) (freshBase : Nat) (clauseCounter output : List Bool) : + TM2.step program + ⟨some (labels .guard), reset ambient, + loopTapes tape base input freshBase 0 clauseCounter output⟩ = + some ⟨done, reset ambient, loopTapes tape base input freshBase 0 clauseCounter output⟩ := by + change some (TM2.stepAux (program (labels .guard)) _ _) = _ + rw [atLabels .guard] + simp [instruction, TM2.stepAux, reset, clean, NormalizationEmitMachine.clean, + loopTapes_remaining tape distinct] + +theorem tallyStep (input : List Bool) (freshBase remaining : Nat) + (clauseCounter output : List Bool) (signs : Signs) : + TM2.step program + ⟨some (labels .tally), clean ambient signs, + loopTapes tape base input freshBase remaining clauseCounter output⟩ = + some ⟨some (labels .guard), reset ambient, + loopTapes tape base input (freshBase + 4) remaining + (List.replicate 13 true ++ clauseCounter) output⟩ := by + have freshEq : List.replicate 4 true ++ List.replicate freshBase true = + List.replicate (freshBase + 4) true := by + rw [← List.replicate_add, Nat.add_comm] + change some (TM2.stepAux (program (labels .tally)) _ _) = _ + rw [atLabels .tally] + simp only [instruction, stepAux_pushWord, List.reverse_replicate, + loopTapes_fresh tape distinct, freshEq, update_fresh tape distinct, + loopTapes_count tape distinct, update_count tape distinct, + stepAux_finish, clean, NormalizationEmitMachine.clean] + +theorem bodyTrace {n : Nat} (clause : Target.Clause n) (suffix : List Bool) + (freshBase remaining : Nat) (clauseCounter output : List Bool) + (empty : ∀ i : Fin 9, 4 ≤ i.val → i.val ≤ 7 → base (tape i) = []) : + (advance (TM2.step program))^[bodySteps freshBase clause] + (some ⟨some (labels .guard), reset ambient, + loopTapes tape base (encodeWords (clauseWords clause) ++ suffix) + freshBase (remaining + 1) clauseCounter output⟩) = + some ⟨some (labels .guard), reset ambient, + loopTapes tape base suffix (freshBase + 4) remaining + (List.replicate 13 true ++ clauseCounter) + ((bits (clauseSigns clause) (clauseNames clause) freshBase).reverse ++ output)⟩ := by + have hd (i j : Fin 9) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + have he (i : Fin 9) (lo : 4 ≤ i.val := by decide) (hi : i.val ≤ 7 := by decide) : + base (tape i) = [] := empty i lo hi + let s₀ := loopTapes tape base (encodeWords (clauseWords clause) ++ suffix) + freshBase remaining clauseCounter output + let s₁ := NormalizationReadMachine.tapes (readerTapes tape) s₀ suffix + (NormalizationReadMachine.clauseCounters clause) + let word := bits (clauseSigns clause) (clauseNames clause) freshBase + let s₂ := Function.update s₁ (tape 8) (word.reverse ++ output) + let s₃ := Function.update s₂ (tape 4) [] + let s₄ := Function.update s₃ (tape 5) [] + let s₅ := Function.update s₄ (tape 6) [] + have guard : (advance (TM2.step program))^[1] + (some ⟨some (labels .guard), reset ambient, + loopTapes tape base (encodeWords (clauseWords clause) ++ suffix) + freshBase (remaining + 1) clauseCounter output⟩) = + some ⟨some (labels (.read (.field 0))), reset ambient, s₀⟩ := by + simpa only [Function.iterate_one, advance_some] using + guardStep tape distinct labels done rejected program atLabels base ambient + (encodeWords (clauseWords clause) ++ suffix) freshBase remaining clauseCounter output + have s₀input : s₀ (tape 0) = encodeWords (clauseWords clause) ++ suffix := by + simp [s₀, loopTapes, hd] + have s₀old (i : Fin 9) (hi : i = 4 ∨ i = 5 ∨ i = 6) : s₀ (tape i) = [] := by + rcases hi with rfl | rfl | rfl <;> simp [s₀, loopTapes, hd, he] + have initialReader : NormalizationReadMachine.tapes (readerTapes tape) s₀ + (encodeWords (clauseWords clause) ++ suffix) (fun _ => []) = s₀ := by + have unchanged (i : Fin 9) (hi : i = 4 ∨ i = 5 ∨ i = 6) : + Function.update s₀ (tape i) [] = s₀ := by + funext k + by_cases hk : k = tape i + · subst k + simp [s₀old i hi] + · simp [hk] + change Function.update (Function.update (Function.update (Function.update s₀ + (tape 0) _) (tape 4) []) (tape 5) []) (tape 6) [] = s₀ + rw [← s₀input, Function.update_eq_self, unchanged 4 (by simp), + unchanged 5 (by simp), unchanged 6 (by simp)] + have read := NormalizationReadMachine.clauseTrace (readerTapes tape) + (readerTapes_injective tape distinct) (fun l => labels (.read l)) + (some (labels (.emit NormalizationEmitMachine.main))) rejected program + (fun l => atLabels (.read l)) s₀ ambient clause suffix (fun _ => false) none + rw [initialReader] at read + have s₁fresh : s₁ (tape 1) = List.replicate freshBase true := by + simp [s₁, NormalizationReadMachine.tapes, readerTapes, readerIndex, s₀, loopTapes, hd] + have s₁old (i : Fin 3) : + s₁ (emitterTapes tape (NormalizationEmitMachine.sourceIndex (.old i))) = + List.replicate (clauseNames clause i) true := by + fin_cases i <;> + simp [s₁, NormalizationReadMachine.tapes, readerTapes, readerIndex, + emitterTapes, emitterIndex, NormalizationEmitMachine.sourceIndex, + NormalizationReadMachine.clauseCounters, clauseNames, hd] + have s₁scratch : s₁ (tape 7) = [] := by + simp [s₁, NormalizationReadMachine.tapes, readerTapes, readerIndex, s₀, loopTapes, hd, he 7] + have s₁output : s₁ (tape 8) = output := by + simp [s₁, NormalizationReadMachine.tapes, readerTapes, readerIndex, s₀, loopTapes, hd] + have emit := NormalizationEmitMachine.gadgetTrace (emitterTapes tape) + (emitterTapes_injective tape distinct) (fun l => labels (.emit l)) + (some (labels (.drain 0))) program (fun l => atLabels (.emit l)) s₁ ambient + (clauseSigns clause) (clauseNames clause) freshBase s₁fresh s₁old s₁scratch + rw [show emitterTapes tape 5 = tape 8 from rfl, s₁output] at emit + have s₂old : s₂ (tape 4) = List.replicate clause[0].variableIndex.val true := by + simpa [s₂, hd 4 8 (by decide), emitterTapes, emitterIndex, + NormalizationEmitMachine.sourceIndex, clauseNames] using s₁old 0 + have drain₀ : (advance (TM2.step program))^[clause[0].variableIndex.val + 1] + (some ⟨some (labels (.drain 0)), clean ambient (clauseSigns clause), s₂⟩) = + some ⟨some (labels (.drain 1)), clean ambient (clauseSigns clause), s₃⟩ := by + have h := MachineDrain.drainTrace (tape 4) (labels (.drain 0)) (some (labels (.drain 1))) + program (atLabels (.drain 0)) s₂ (List.replicate clause[0].variableIndex.val true) + (ambient, clauseSigns clause) none + have initial : Function.update s₂ (tape 4) + (List.replicate clause[0].variableIndex.val true) = s₂ := by + rw [← s₂old]; exact Function.update_eq_self _ _ + simpa only [initial, List.length_replicate, clean, NormalizationEmitMachine.clean, s₃] using h + have s₃old : s₃ (tape 5) = List.replicate clause[1].variableIndex.val true := by + simpa [s₃, s₂, hd 5 4 (by decide), hd 5 8 (by decide), emitterTapes, emitterIndex, + NormalizationEmitMachine.sourceIndex, clauseNames] using s₁old 1 + have drain₁ : (advance (TM2.step program))^[clause[1].variableIndex.val + 1] + (some ⟨some (labels (.drain 1)), clean ambient (clauseSigns clause), s₃⟩) = + some ⟨some (labels (.drain 2)), clean ambient (clauseSigns clause), s₄⟩ := by + have h := MachineDrain.drainTrace (tape 5) (labels (.drain 1)) (some (labels (.drain 2))) + program (atLabels (.drain 1)) s₃ (List.replicate clause[1].variableIndex.val true) + (ambient, clauseSigns clause) none + have initial : Function.update s₃ (tape 5) + (List.replicate clause[1].variableIndex.val true) = s₃ := by + rw [← s₃old]; exact Function.update_eq_self _ _ + simpa only [initial, List.length_replicate, clean, NormalizationEmitMachine.clean, s₄] using h + have s₄old : s₄ (tape 6) = List.replicate clause[2].variableIndex.val true := by + simpa [s₄, s₃, s₂, hd 6 5 (by decide), hd 6 4 (by decide), hd 6 8 (by decide), + emitterTapes, emitterIndex, NormalizationEmitMachine.sourceIndex, clauseNames] using s₁old 2 + have drain₂ : (advance (TM2.step program))^[clause[2].variableIndex.val + 1] + (some ⟨some (labels (.drain 2)), clean ambient (clauseSigns clause), s₄⟩) = + some ⟨some (labels .tally), clean ambient (clauseSigns clause), s₅⟩ := by + have h := MachineDrain.drainTrace (tape 6) (labels (.drain 2)) (some (labels .tally)) + program (atLabels (.drain 2)) s₄ (List.replicate clause[2].variableIndex.val true) + (ambient, clauseSigns clause) none + have initial : Function.update s₄ (tape 6) + (List.replicate clause[2].variableIndex.val true) = s₄ := by + rw [← s₄old]; exact Function.update_eq_self _ _ + simpa only [initial, List.length_replicate, clean, NormalizationEmitMachine.clean, s₅] using h + have restored : s₅ = loopTapes tape base suffix freshBase remaining clauseCounter + (word.reverse ++ output) := by + funext k + by_cases h8 : k = tape 8 + · subst k + simp [s₅, s₄, s₃, s₂, loopTapes, hd] + · by_cases h0 : k = tape 0 + · subst k + simp [s₅, s₄, s₃, s₂, s₁, NormalizationReadMachine.tapes, + readerTapes, readerIndex, loopTapes, hd] + · by_cases h4 : k = tape 4 + · subst k + simp [s₅, s₄, s₃, loopTapes, hd, he 4] + · by_cases h5 : k = tape 5 + · subst k + simp [s₅, s₄, loopTapes, hd, he 5] + · by_cases h6 : k = tape 6 + · subst k + simp [s₅, loopTapes, hd, he 6] + · simp [s₅, s₄, s₃, s₂, s₁, NormalizationReadMachine.tapes, + readerTapes, readerIndex, s₀, loopTapes, h8, h0, h4, h5, h6, + Function.update_apply] + have tally : (advance (TM2.step program))^[1] + (some ⟨some (labels .tally), clean ambient (clauseSigns clause), s₅⟩) = + some ⟨some (labels .guard), reset ambient, + loopTapes tape base suffix (freshBase + 4) remaining + (List.replicate 13 true ++ clauseCounter) (word.reverse ++ output)⟩ := by + rw [restored] + simpa only [Function.iterate_one, advance_some] using + tallyStep tape distinct labels done rejected program atLabels base ambient suffix + freshBase remaining clauseCounter (word.reverse ++ output) (clauseSigns clause) + have full := joinTrace (joinTrace (joinTrace (joinTrace (joinTrace + (joinTrace guard read) emit) drain₀) drain₁) drain₂) tally + simpa only [bodySteps, nameSum, word] using full + +theorem loopTrace {n : Nat} (clauses : List (Target.Clause n)) (suffix : List Bool) + (freshBase : Nat) (clauseCounter output : List Bool) + (empty : ∀ i : Fin 9, 4 ≤ i.val → i.val ≤ 7 → base (tape i) = []) : + (advance (TM2.step program))^[steps freshBase clauses] + (some ⟨some (labels .guard), reset ambient, + loopTapes tape base (encodeWords (clauses.flatMap clauseWords) ++ suffix) + freshBase clauses.length clauseCounter output⟩) = + some ⟨done, reset ambient, + loopTapes tape base suffix (freshBase + 4 * clauses.length) 0 + (List.replicate (13 * clauses.length) true ++ clauseCounter) + ((NormalizationStream.blocks freshBase clauses).reverse ++ output)⟩ := by + induction clauses generalizing freshBase clauseCounter output with + | nil => + simpa only [steps, Function.iterate_one, advance_some, List.flatMap_nil, + encodeWords, List.nil_append, List.length_nil, Nat.mul_zero, Nat.add_zero, + List.replicate_zero, NormalizationStream.blocks, List.reverse_nil] using + emptyStep tape distinct labels done rejected program atLabels base ambient suffix + freshBase clauseCounter output + | cons clause clauses ih => + have first := bodyTrace tape distinct labels done rejected program atLabels base ambient + clause (encodeWords (clauses.flatMap clauseWords) ++ suffix) freshBase clauses.length + clauseCounter output empty + have rest := ih (freshBase + 4) (List.replicate 13 true ++ clauseCounter) + ((bits (clauseSigns clause) (clauseNames clause) freshBase).reverse ++ output) + have full := joinTrace first rest + have freshEq : freshBase + 4 + 4 * clauses.length = + freshBase + 4 * (clauses.length + 1) := by omega + have countEq : List.replicate (13 * clauses.length) true ++ + (List.replicate 13 true ++ clauseCounter) = + List.replicate (13 * (clauses.length + 1)) true ++ clauseCounter := by + rw [Nat.mul_add, Nat.mul_one, List.replicate_add, List.append_assoc] + simpa only [steps, List.flatMap_cons, encodeWords_append, List.append_assoc, + List.length_cons, freshEq, countEq, NormalizationStream.blocks, + List.reverse_append] using full + +def loopInTime {n : Nat} (clauses : List (Target.Clause n)) (suffix : List Bool) + (freshBase maximum : Nat) (clauseCounter output : List Bool) + (empty : ∀ i : Fin 9, 4 ≤ i.val → i.val ≤ 7 → base (tape i) = []) + (nameBound : n ≤ maximum) (freshBound : freshBase + 4 * clauses.length ≤ maximum) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .guard), reset ambient, + loopTapes tape base (encodeWords (clauses.flatMap clauseWords) ++ suffix) + freshBase clauses.length clauseCounter output⟩ + (some ⟨done, reset ambient, + loopTapes tape base suffix (freshBase + 4 * clauses.length) 0 + (List.replicate (13 * clauses.length) true ++ clauseCounter) + ((NormalizationStream.blocks freshBase clauses).reverse ++ output)⟩) + (clauses.length * (84 * maximum + 128) + 1) where + steps := steps freshBase clauses + evals_in_steps := loopTrace tape distinct labels done rejected program atLabels base ambient + clauses suffix freshBase clauseCounter output empty + steps_le_m := steps_le freshBase maximum clauses nameBound freshBound + +end Program + +end PerfectCompleteness.NormalizationLoopMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/NormalizationMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/NormalizationMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..af05d9b7f5c7a9ddb615373375e603009db3f749 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/NormalizationMachine.lean @@ -0,0 +1,283 @@ +import OAI.Computability.PerfectCompleteness.Machines.BinaryHeaderMachine +import OAI.Computability.PerfectCompleteness.Machines.NormalizationLoopMachine +import OAI.Computability.UniqueGames.Machines.MachineFiniteAlphabet + +namespace OAI + + +namespace PerfectCompleteness.NormalizationMachine + + +open Turing UniqueGamesTheorem.Foundations Complexity +open MachineComposition UniqueGamesTheorem.Reduction.MachineTransfer + +abbrev Tape := Fin 10 +abbrev Alphabet (_ : Tape) := Bool +abbrev State := NormalizationLoopMachine.State Unit + +inductive Label + | readVariables | readCount + | loop (label : NormalizationLoopMachine.Label) + | restore | clauseStart | clauseLoop | variableStart | variableLoop | reject + deriving DecidableEq, Fintype + +def loopTapes : Fin 9 → Tape := Fin.castSucc + +theorem loopTapes_injective : Function.Injective loopTapes := by + intro i j h + apply Fin.ext + exact congrArg (fun k : Tape => k.val) h + +def program : Label → TM2.Stmt Alphabet Label State + | .readVariables => Hastad.SourceMachine.fieldLoop 0 1 .readVariables (some .readCount) + | .readCount => Hastad.SourceMachine.fieldLoop 0 2 .readCount (some (.loop .guard)) + | .loop label => NormalizationLoopMachine.instruction loopTapes Label.loop + (some .restore) (some .reject) label + | .restore => loopAt 8 9 id false .restore (some .clauseStart) + | .clauseStart => BinaryHeaderMachine.delimiter 9 .clauseLoop + | .clauseLoop => loopAt 3 9 id false .clauseLoop (some .variableStart) + | .variableStart => BinaryHeaderMachine.delimiter 9 .variableLoop + | .variableLoop => loopAt 1 9 id false .variableLoop none + | .reject => .halt + +abbrev machine : FinTM2 where + K := Tape + k₀ := 0 + k₁ := 9 + Γ := Alphabet + Λ := Label + main := .readVariables + σ := State + initialState := NormalizationLoopMachine.reset () + m := program + +def tapes (input fresh remaining clauseCounter reversed output : List Bool) : Tape → List Bool := + fun k => if k = 0 then input else if k = 1 then fresh else if k = 2 then remaining + else if k = 3 then clauseCounter else if k = 8 then reversed else if k = 9 then output else [] + +def cfg (label : Option Label) (input fresh remaining clauseCounter reversed output : List Bool) : + machine.Cfg := ⟨label, NormalizationLoopMachine.reset (), + tapes input fresh remaining clauseCounter reversed output⟩ + +theorem initList_eq (input : List Bool) : + initList machine input = cfg (some .readVariables) input [] [] [] [] [] := by + unfold initList cfg + congr 1 + funext k + fin_cases k <;> simp [tapes, machine] + +theorem haltList_eq (output : List Bool) : + haltList machine output = cfg none [] [] [] [] [] output := by + unfold haltList cfg + congr 1 + funext k + fin_cases k <;> simp [tapes, machine] + +private theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +theorem readVariablesTrace (n : Nat) (suffix : List Bool) : + (advance machine.step)^[n + 1] + (some (cfg (some .readVariables) (encodeWord n ++ suffix) [] [] [] [] [])) = + some (cfg (some .readCount) suffix (List.replicate n true) [] [] [] []) := by + have updated (input fresh : List Bool) : + Hastad.SourceMachine.fieldTapes (0 : Tape) 1 (tapes [] [] [] [] [] []) input fresh = + tapes input fresh [] [] [] [] := by + funext k + fin_cases k <;> simp [Hastad.SourceMachine.fieldTapes, tapes] + have run := Hastad.SourceMachine.fieldLoopTrace (0 : Tape) 1 (by decide) + .readVariables (some .readCount) program rfl (tapes [] [] [] [] [] []) n suffix [] + (NormalizationLoopMachine.reset ()).1 none + simp only [updated, List.append_nil] at run + exact run + +theorem readCountTrace (n m : Nat) (suffix : List Bool) : + (advance machine.step)^[m + 1] + (some (cfg (some .readCount) (encodeWord m ++ suffix) (List.replicate n true) [] [] [] [])) = + some (cfg (some (.loop .guard)) suffix (List.replicate n true) (List.replicate m true) [] [] []) := by + have updated (input remaining : List Bool) : + Hastad.SourceMachine.fieldTapes (0 : Tape) 2 (tapes [] (List.replicate n true) [] [] [] []) + input remaining = tapes input (List.replicate n true) remaining [] [] [] := by + funext k + fin_cases k <;> simp [Hastad.SourceMachine.fieldTapes, tapes] + have run := Hastad.SourceMachine.fieldLoopTrace (0 : Tape) 2 (by decide) + .readCount (some (.loop .guard)) program rfl + (tapes [] (List.replicate n true) [] [] [] []) m suffix [] + (NormalizationLoopMachine.reset ()).1 none + simp only [updated, List.append_nil] at run + exact run + +theorem headersTrace (n m : Nat) (suffix : List Bool) : + (advance machine.step)^[n + m + 2] + (some (cfg (some .readVariables) (encodeWord n ++ encodeWord m ++ suffix) [] [] [] [] [])) = + some (cfg (some (.loop .guard)) suffix (List.replicate n true) (List.replicate m true) [] [] []) := by + have first := readVariablesTrace n (encodeWord m ++ suffix) + have second := readCountTrace n m suffix + have full := joinTrace first second + have count : n + 1 + (m + 1) = n + m + 2 := by omega + simpa only [count, List.append_assoc] using full + +theorem restoreTrace (fresh clauseCounter body : List Bool) : + (advance machine.step)^[body.length + 1] + (some (cfg (some .restore) [] fresh [] clauseCounter body.reverse [])) = + some (cfg (some .clauseStart) [] fresh [] clauseCounter [] body) := by + change (nextAt (9 : Tape) program)^[body.length + 1] + (some (cfg (some .restore) [] fresh [] clauseCounter body.reverse [])) = _ + have updated : tapesAt (8 : Tape) 9 (tapes [] fresh [] clauseCounter body.reverse []) [] body = + tapes [] fresh [] clauseCounter [] body := by + funext k + fin_cases k <;> simp [tapesAt, tapes] + have run := transferAt_fromTapes (Γ := Alphabet) (8 : Tape) 9 (by decide) id false + .restore (some .clauseStart) program rfl (tapes [] fresh [] clauseCounter body.reverse []) + (NormalizationLoopMachine.reset ()).1 none + have source : tapes [] fresh [] clauseCounter body.reverse [] 8 = body.reverse := rfl + have output : tapes [] fresh [] clauseCounter body.reverse [] 9 = [] := rfl + rw [source, output, List.length_reverse, List.reverse_reverse, List.map_id_fun, + List.append_nil, id_eq, updated] at run + exact run + +theorem headerOutputTrace (n m : Nat) (body : List Bool) : + (advance machine.step)^[n + m + 4] + (some (cfg (some .clauseStart) [] (List.replicate n true) [] + (List.replicate m true) [] body)) = + some (cfg none [] [] [] [] [] (encodeWord n ++ encodeWord m ++ body)) := by + change (advance (TM2.step program))^[n + m + 4] + (some ⟨some .clauseStart, ((NormalizationLoopMachine.reset ()).1, none), + tapes [] (List.replicate n true) [] (List.replicate m true) [] body⟩) = + some ⟨none, ((NormalizationLoopMachine.reset ()).1, none), + tapes [] [] [] [] [] (encodeWord n ++ encodeWord m ++ body)⟩ + have updated (fresh clauses output : List Bool) : + BinaryHeaderMachine.tapes (1 : Tape) 3 9 (tapes [] [] [] [] [] []) fresh clauses output = + tapes [] fresh [] clauses [] output := by + funext k + fin_cases k <;> simp [BinaryHeaderMachine.tapes, tapes] + have run := BinaryHeaderMachine.headerTrace (1 : Tape) 3 9 (by decide) (by decide) (by decide) + .clauseStart .clauseLoop .variableStart .variableLoop none program rfl rfl rfl rfl + (tapes [] [] [] [] [] []) (NormalizationLoopMachine.reset ()).1 n m body none + simp only [updated] at run + exact run + +theorem loopTrace (formula : Target.Formula) : + (advance machine.step)^[NormalizationLoopMachine.steps formula.variables formula.clauses] + (some (cfg (some (.loop .guard)) (encodeWords (formula.clauses.flatMap clauseWords)) + (List.replicate formula.variables true) (List.replicate formula.clauses.length true) + [] [] [])) = + some (cfg (some .restore) [] + (List.replicate (formula.variables + 4 * formula.clauses.length) true) [] + (List.replicate (13 * formula.clauses.length) true) + (NormalizationStream.blocks formula.variables formula.clauses).reverse []) := by + change (advance (TM2.step program))^[NormalizationLoopMachine.steps formula.variables formula.clauses] + (some ⟨some (.loop .guard), NormalizationLoopMachine.reset (), + tapes (encodeWords (formula.clauses.flatMap clauseWords)) + (List.replicate formula.variables true) (List.replicate formula.clauses.length true) + [] [] []⟩) = + some ⟨some .restore, NormalizationLoopMachine.reset (), + tapes [] (List.replicate (formula.variables + 4 * formula.clauses.length) true) [] + (List.replicate (13 * formula.clauses.length) true) + (NormalizationStream.blocks formula.variables formula.clauses).reverse []⟩ + have updated (input : List Bool) (fresh remaining : Nat) (counter output : List Bool) : + NormalizationLoopMachine.loopTapes loopTapes (tapes [] [] [] [] [] []) + input fresh remaining counter output = + tapes input (List.replicate fresh true) (List.replicate remaining true) counter output [] := by + funext k + fin_cases k <;> simp [NormalizationLoopMachine.loopTapes, loopTapes, tapes] + have run := NormalizationLoopMachine.loopTrace loopTapes loopTapes_injective Label.loop + (some .restore) (some .reject) program (fun _ => rfl) + (tapes [] [] [] [] [] []) () formula.clauses [] formula.variables [] [] + (by intros; simp [tapes]) + simp only [updated, List.append_nil, List.replicate_zero] at run + exact run + +theorem formulaBits_eq (formula : Target.Formula) : + formulaBits formula = encodeWord formula.variables ++ encodeWord formula.clauses.length ++ + encodeWords (formula.clauses.flatMap clauseWords) := by + simp only [formulaBits, formulaWords, encodeWords_append, encodeWords, + List.append_nil, List.append_assoc] + +def steps (formula : Target.Formula) : Nat := + (formula.variables + formula.clauses.length + 2) + + NormalizationLoopMachine.steps formula.variables formula.clauses + + ((NormalizationStream.blocks formula.variables formula.clauses).length + 1) + + ((formula.variables + 4 * formula.clauses.length) + 13 * formula.clauses.length + 4) + +theorem normalizationTrace (formula : Target.Formula) : + (advance machine.step)^[steps formula] (some (initList machine (formulaBits formula))) = + some (haltList machine (formulaBits (Normalization.normalize formula))) := by + have first := headersTrace formula.variables formula.clauses.length + (encodeWords (formula.clauses.flatMap clauseWords)) + have second := loopTrace formula + have third := restoreTrace + (List.replicate (formula.variables + 4 * formula.clauses.length) true) + (List.replicate (13 * formula.clauses.length) true) + (NormalizationStream.blocks formula.variables formula.clauses) + have fourth := headerOutputTrace (formula.variables + 4 * formula.clauses.length) + (13 * formula.clauses.length) (NormalizationStream.blocks formula.variables formula.clauses) + have full := joinTrace (joinTrace (joinTrace first second) third) fourth + rw [initList_eq, haltList_eq, NormalizationStream.encoded_normalize, formulaBits_eq] + exact full + +theorem header_counts_le (formula : Target.Formula) : + formula.variables ≤ (formulaBits formula).length ∧ + formula.clauses.length ≤ (formulaBits formula).length := by + rw [formulaBits_eq] + simp only [List.length_append, encodeWord_length] + omega + +noncomputable def timePolynomial : Polynomial Nat := + Polynomial.C 1000 * (Polynomial.X + Polynomial.C 1) ^ 2 + +theorem steps_le (formula : Target.Formula) : + steps formula ≤ timePolynomial.eval (formulaBits formula).length := by + let B := (formulaBits formula).length + let M := formula.variables + 4 * formula.clauses.length + have variablesBound : formula.variables ≤ B := (header_counts_le formula).1 + have clausesBound : formula.clauses.length ≤ B := (header_counts_le formula).2 + have addressBound : M ≤ 5 * B := by dsimp [M]; omega + have loopBound := NormalizationLoopMachine.steps_le formula.variables M formula.clauses + (by dsimp [M]; omega) (Nat.le_refl M) + have loopUniform : NormalizationLoopMachine.steps formula.variables formula.clauses ≤ + B * (420 * B + 128) + 1 := + loopBound.trans (Nat.add_le_add_right + (Nat.mul_le_mul clausesBound (by omega)) 1) + have bodyBound := NormalizationStream.blocks_length_le formula.clauses formula.variables M + (by dsimp [M]; omega) (Nat.le_refl M) + have bodyUniform : (NormalizationStream.blocks formula.variables formula.clauses).length ≤ + B * (39 * (5 * B + 3)) := + bodyBound.trans (Nat.mul_le_mul clausesBound (by omega)) + simp only [timePolynomial, Polynomial.eval_mul, Polynomial.eval_pow, Polynomial.eval_add, + Polynomial.eval_C, Polynomial.eval_X] + change steps formula ≤ 1000 * (B + 1) ^ 2 + unfold steps + nlinarith + +def outputsInTime (formula : Target.Formula) : + TM2OutputsInTime machine (formulaBits formula) + (some (formulaBits (Normalization.normalize formula))) + (timePolynomial.eval (formulaBits formula).length) where + steps := steps formula + evals_in_steps := normalizationTrace formula + steps_le_m := steps_le formula + +noncomputable def computableInPolyTime : + TM2ComputableInPolyTime formulaBits formulaBits Normalization.normalize where + tm := machine + inputAlphabet := Equiv.refl Bool + outputAlphabet := Equiv.refl Bool + time := timePolynomial + outputsFun formula := by + change TM2OutputsInTime machine ((formulaBits formula).map id) + (some ((formulaBits (Normalization.normalize formula)).map id)) + (timePolynomial.eval (formulaBits formula).length) + simpa only [List.map_id_fun, id_eq] using outputsInTime formula + +theorem machine_finiteAlphabet (k : machine.K) : Finite (machine.Γ k) := by + change Finite Bool + infer_instance + +theorem computation_finiteAlphabet : MachineFiniteAlphabet.FiniteAlphabet computableInPolyTime.tm := + machine_finiteAlphabet + +end PerfectCompleteness.NormalizationMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/NormalizationReadMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/NormalizationReadMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..8907828ccb3177b2faab9f5479e5d36c0c610a57 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/NormalizationReadMachine.lean @@ -0,0 +1,306 @@ +import Mathlib.Tactic.DeriveFintype +import OAI.Computability.UniqueGames.PCP.SourceMachine + +namespace OAI + + +namespace PerfectCompleteness.NormalizationReadMachine + + +open Turing +open UniqueGamesTheorem.Foundations +open Complexity Complexity.MachineComposition +open UniqueGamesTheorem.Reduction.MachineTransfer + +abbrev Signs := Fin 3 → Bool +abbrev Counters := Fin 3 → List Bool +abbrev State (A : Type) := (A × Signs) × Option Bool +abbrev Alphabet {K : Type} (_ : K) := Bool + +def clean {A : Type} (ambient : A) (signs : Signs) : State A := ((ambient, signs), none) + +def clauseSigns {n : Nat} (clause : Target.Clause n) : Signs := fun i => clause[i].positive + +def clauseCounters {n : Nat} (clause : Target.Clause n) : Counters := + fun i => List.replicate clause[i].variableIndex.val true + +inductive Label where + | field (slot : Fin 3) + | sign (slot : Fin 3) + deriving DecidableEq, Fintype + +section Placement + +variable {K Λ A : Type} [DecidableEq K] + +def afterSign (labels : Label → Λ) (exit : Option Λ) (slot : Fin 3) : Option Λ := + if slot = 0 then some (labels (.field 1)) + else if slot = 1 then some (labels (.field 2)) else exit + +@[simp] theorem afterSign_zero (labels : Label → Λ) (exit : Option Λ) : + afterSign labels exit 0 = some (labels (.field 1)) := rfl + +@[simp] theorem afterSign_one (labels : Label → Λ) (exit : Option Λ) : + afterSign labels exit 1 = some (labels (.field 2)) := rfl + +@[simp] theorem afterSign_two (labels : Label → Λ) (exit : Option Λ) : + afterSign labels exit 2 = exit := rfl + +def saveSign (source : K) (slot : Fin 3) (bit : Bool) (exit : Option Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (State A) := + .load (fun state => clean state.1.1 (Function.update state.1.2 slot bit)) + (exitAt source exit) + +def rejectSign (source : K) (exit : Option Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (State A) := + .load (fun state => clean state.1.1 state.1.2) (exitAt source exit) + +def signInstruction (source : K) (slot : Fin 3) (exit rejected : Option Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (State A) := + .pop source (fun state head => (state.1, head)) + (.branch (fun state => state.2.isNone) + (rejectSign source rejected) + (.branch (fun state => state.2.getD false) + (.pop source (fun state head => (state.1, head)) + (.branch (fun state => state.2 == some false) + (saveSign source slot true exit) (rejectSign source rejected))) + (saveSign source slot false exit))) + +def instruction (tape : Fin 4 → K) (labels : Label → Λ) (exit rejected : Option Λ) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (State A) + | .field slot => Hastad.SourceMachine.fieldLoop (tape 0) (tape slot.succ) + (labels (.field slot)) (some (labels (.sign slot))) + | .sign slot => signInstruction (tape 0) slot (afterSign labels exit slot) rejected + +def tapes (tape : Fin 4 → K) (base : K → List Bool) (input : List Bool) + (counter : Counters) : K → List Bool := + Function.update (Function.update (Function.update (Function.update base + (tape 0) input) (tape 1) (counter 0)) (tape 2) (counter 1)) (tape 3) (counter 2) + +theorem tapes_input (tape : Fin 4 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (input : List Bool) (counter : Counters) : + tapes tape base input counter (tape 0) = input := by + have hd (i j : Fin 4) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + simp [tapes, hd] + +theorem tapes_counter (tape : Fin 4 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (input : List Bool) (counter : Counters) (slot : Fin 3) : + tapes tape base input counter (tape slot.succ) = counter slot := by + have hd (i j : Fin 4) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + fin_cases slot <;> simp [tapes, hd] + +theorem tapes_other (tape : Fin 4 → K) (base : K → List Bool) + (input : List Bool) (counter : Counters) (k : K) (other : ∀ i, k ≠ tape i) : + tapes tape base input counter k = base k := by + simp [tapes, other] + +theorem update_input (tape : Fin 4 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (input replacement : List Bool) (counter : Counters) : + Function.update (tapes tape base input counter) (tape 0) replacement = + tapes tape base replacement counter := by + have hd (i j : Fin 4) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + funext k + by_cases hk : k = tape 0 + · subst k + simp [tapes, hd] + · simp [tapes, hk, Function.update_apply] + +theorem update_counter (tape : Fin 4 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (input replacement : List Bool) (counter : Counters) (slot : Fin 3) : + Function.update (tapes tape base input counter) (tape slot.succ) replacement = + tapes tape base input (Function.update counter slot replacement) := by + have hd (i j : Fin 4) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + funext k + by_cases hk : k = tape slot.succ + · subst k + fin_cases slot <;> simp [tapes, hd] + · fin_cases slot + · change k ≠ tape 1 at hk + simp [tapes, hk, Function.update_apply] + · change k ≠ tape 2 at hk + simp [tapes, hk, Function.update_apply] + · change k ≠ tape 3 at hk + simp [tapes, hk, Function.update_apply] + +theorem fieldTapes_eq (tape : Fin 4 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (input replacement output : List Bool) + (counter : Counters) (slot : Fin 3) : + Hastad.SourceMachine.fieldTapes (tape 0) (tape slot.succ) + (tapes tape base input counter) replacement output = + tapes tape base replacement (Function.update counter slot output) := by + unfold Hastad.SourceMachine.fieldTapes + rw [update_input tape distinct, update_counter tape distinct] + +variable (tape : Fin 4 → K) (distinct : Function.Injective tape) +variable (labels : Label → Λ) (exit rejected : Option Λ) +variable (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) +variable (atLabels : ∀ label, program (labels label) = instruction tape labels exit rejected label) +variable (base : K → List Bool) (ambient : A) + +include distinct atLabels + +theorem fieldTrace (slot : Fin 3) (value : Nat) (suffix : List Bool) + (counter : Counters) (signs : Signs) (register : Option Bool) : + (advance (TM2.step program))^[value + 1] + (some ⟨some (labels (.field slot)), ((ambient, signs), register), + tapes tape base (encodeWord value ++ suffix) counter⟩) = + some ⟨some (labels (.sign slot)), clean ambient signs, + tapes tape base suffix + (Function.update counter slot (List.replicate value true ++ counter slot))⟩ := by + have distinctSlot : tape 0 ≠ tape slot.succ := by + intro h + have same := congrArg Fin.val (distinct h) + simp only [Fin.val_zero, Fin.val_succ] at same + omega + have h := Hastad.SourceMachine.fieldLoopTrace (tape 0) (tape slot.succ) distinctSlot + (labels (.field slot)) (some (labels (.sign slot))) program (atLabels (.field slot)) + (tapes tape base (encodeWord value ++ suffix) counter) value suffix (counter slot) + (ambient, signs) register + simpa only [fieldTapes_eq tape distinct, Function.update_eq_self, clean] using h + +theorem signStep (slot : Fin 3) (sign : Bool) (suffix : List Bool) + (counter : Counters) (signs : Signs) (register : Option Bool) : + TM2.step program + ⟨some (labels (.sign slot)), ((ambient, signs), register), + tapes tape base (encodeWord (if sign then 1 else 0) ++ suffix) counter⟩ = + some ⟨afterSign labels exit slot, clean ambient (Function.update signs slot sign), + tapes tape base suffix counter⟩ := by + change some (TM2.stepAux (program (labels (.sign slot))) _ _) = _ + rw [atLabels (.sign slot)] + cases sign <;> cases h : afterSign labels exit slot <;> + simp [instruction, signInstruction, saveSign, rejectSign, encodeWord, + TM2.stepAux, exitAt, h, clean, tapes_input tape distinct, update_input tape distinct] + +omit [DecidableEq K] distinct atLabels in +private theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +theorem literalTrace {n : Nat} (slot : Fin 3) (literal : Target.Literal n) + (suffix : List Bool) (counter : Counters) (signs : Signs) (register : Option Bool) : + (advance (TM2.step program))^[literal.variableIndex.val + 2] + (some ⟨some (labels (.field slot)), ((ambient, signs), register), + tapes tape base (encodeWords (literalWords literal) ++ suffix) counter⟩) = + some ⟨afterSign labels exit slot, clean ambient (Function.update signs slot literal.positive), + tapes tape base suffix (Function.update counter slot + (List.replicate literal.variableIndex.val true ++ counter slot))⟩ := by + have first := fieldTrace tape distinct labels exit rejected program atLabels base ambient + slot literal.variableIndex.val (encodeWord (if literal.positive then 1 else 0) ++ suffix) + counter signs register + have second := signStep tape distinct labels exit rejected program atLabels base ambient + slot literal.positive suffix + (Function.update counter slot (List.replicate literal.variableIndex.val true ++ counter slot)) + signs none + change (advance (TM2.step program))^[1] + (some ⟨some (labels (.sign slot)), clean ambient signs, + tapes tape base (encodeWord (if literal.positive then 1 else 0) ++ suffix) + (Function.update counter slot (List.replicate literal.variableIndex.val true ++ counter slot))⟩) = _ + at second + have full := joinTrace first second + simpa only [literalWords, encodeWords, List.append_nil, List.append_assoc, + Nat.add_assoc] using full + +theorem clauseTrace {n : Nat} (clause : Target.Clause n) (suffix : List Bool) + (signs : Signs) (register : Option Bool) : + (advance (TM2.step program))^[clause[0].variableIndex.val + + clause[1].variableIndex.val + clause[2].variableIndex.val + 6] + (some ⟨some (labels (.field 0)), ((ambient, signs), register), + tapes tape base (encodeWords (clauseWords clause) ++ suffix) (fun _ => [])⟩) = + some ⟨exit, clean ambient (clauseSigns clause), + tapes tape base suffix (clauseCounters clause)⟩ := by + let counter₀ : Counters := Function.update (fun _ => []) 0 + (List.replicate clause[0].variableIndex.val true) + let counter₁ : Counters := Function.update counter₀ 1 + (List.replicate clause[1].variableIndex.val true) + let counter₂ : Counters := Function.update counter₁ 2 + (List.replicate clause[2].variableIndex.val true) + let signs₀ := Function.update signs 0 clause[0].positive + let signs₁ := Function.update signs₀ 1 clause[1].positive + let signs₂ := Function.update signs₁ 2 clause[2].positive + have counter₀_one : counter₀ 1 = [] := rfl + have counter₁_two : counter₁ 2 = [] := rfl + have first := literalTrace tape distinct labels exit rejected program atLabels base ambient + 0 clause[0] (encodeWords (literalWords clause[1]) ++ + (encodeWords (literalWords clause[2]) ++ suffix)) (fun _ => []) signs register + have second := literalTrace tape distinct labels exit rejected program atLabels base ambient + 1 clause[1] (encodeWords (literalWords clause[2]) ++ suffix) counter₀ signs₀ none + have third := literalTrace tape distinct labels exit rejected program atLabels base ambient + 2 clause[2] suffix counter₁ signs₁ none + simp only [counter₀_one, counter₁_two, List.append_nil, + afterSign_zero, afterSign_one, afterSign_two] at first second third + have full := joinTrace (joinTrace first second) third + have counters_eq : counter₂ = clauseCounters clause := by + funext i + fin_cases i <;> simp [counter₂, counter₁, counter₀, clauseCounters] + have signs_eq : signs₂ = clauseSigns clause := by + funext i + fin_cases i <;> simp [signs₂, signs₁, signs₀, clauseSigns] + have htime : (clause[0].variableIndex.val + 2 + (clause[1].variableIndex.val + 2)) + + (clause[2].variableIndex.val + 2) = + clause[0].variableIndex.val + clause[1].variableIndex.val + clause[2].variableIndex.val + 6 := by omega + rw [htime] at full + change (advance (TM2.step program))^[_] + (some ⟨some (labels (.field 0)), ((ambient, signs), register), + tapes tape base (encodeWords (literalWords clause[0]) ++ + (encodeWords (literalWords clause[1]) ++ (encodeWords (literalWords clause[2]) ++ suffix))) + (fun _ => [])⟩) = + some ⟨exit, clean ambient signs₂, tapes tape base suffix counter₂⟩ at full + rw [signs_eq, counters_eq] at full + simpa only [clauseWords, encodeWords_append, List.append_assoc] using full + +def clauseInTime {n : Nat} (clause : Target.Clause n) (suffix : List Bool) + (signs : Signs) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels (.field 0)), ((ambient, signs), register), + tapes tape base (encodeWords (clauseWords clause) ++ suffix) (fun _ => [])⟩ + (some ⟨exit, clean ambient (clauseSigns clause), + tapes tape base suffix (clauseCounters clause)⟩) + (clause[0].variableIndex.val + clause[1].variableIndex.val + clause[2].variableIndex.val + 6) where + steps := clause[0].variableIndex.val + clause[1].variableIndex.val + clause[2].variableIndex.val + 6 + evals_in_steps := clauseTrace tape distinct labels exit rejected program atLabels base ambient + clause suffix signs register + steps_le_m := Nat.le_refl _ + +end Placement + +theorem steps_le_encoded_length {n : Nat} (clause : Target.Clause n) : + clause[0].variableIndex.val + clause[1].variableIndex.val + clause[2].variableIndex.val + 6 ≤ + (encodeWords (clauseWords clause)).length := by + simp only [clauseWords, encodeWords_append, List.length_append, + literalWords, encodeWords, List.length_append, encodeWord_length, List.length_nil] + omega + +abbrev ConcreteLabel := Label ⊕ Bool + +def concreteProgram : ConcreteLabel → TM2.Stmt (Alphabet (K := Fin 4)) ConcreteLabel (State Unit) + | .inl label => instruction id Sum.inl (some (.inr true)) (some (.inr false)) label + | .inr _ => .halt + +abbrev machine : FinTM2 where + K := Fin 4 + k₀ := 0 + k₁ := 1 + Γ := Alphabet + Λ := ConcreteLabel + main := .inl (.field 0) + σ := State Unit + initialState := clean () (fun _ => false) + m := concreteProgram + +def machineInTime {n : Nat} (clause : Target.Clause n) (suffix : List Bool) : + StateTransition.EvalsToInTime machine.step + ⟨some (.inl (.field 0)), clean () (fun _ => false), + tapes id (fun _ : Fin 4 => []) (encodeWords (clauseWords clause) ++ suffix) (fun _ => [])⟩ + (some ⟨some (.inr true), clean () (clauseSigns clause), + tapes id (fun _ : Fin 4 => []) suffix (clauseCounters clause)⟩) + (clause[0].variableIndex.val + clause[1].variableIndex.val + clause[2].variableIndex.val + 6) := + clauseInTime id (fun _ _ h => h) Sum.inl (some (.inr true)) (some (.inr false)) + concreteProgram (fun _ => rfl) (fun _ => []) () clause suffix (fun _ => false) none + +theorem machine_finiteAlphabet (k : machine.K) : Finite (machine.Γ k) := by + change Finite Bool + infer_instance + +end PerfectCompleteness.NormalizationReadMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/NormalizedTargetMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/NormalizedTargetMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..4144c2797d8ac682360be2fd16b1384cb4482959 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/NormalizedTargetMachine.lean @@ -0,0 +1,314 @@ +import OAI.Computability.PerfectCompleteness.Machines.NormalizedTargetTapeBound +import OAI.Computability.PerfectCompleteness.Reduction.NormalizedTargetInitialization +import OAI.Computability.PerfectCompleteness.Reduction.TargetFinalizeBound +import OAI.Computability.UniqueGames.Machines.MachineFiniteAlphabet +import OAI.Computability.UniqueGames.Machines.MachineSubroutineLemmas + +namespace OAI + + +namespace PerfectCompleteness.NormalizedTargetMachine + + +open Turing UniqueGamesTheorem.Foundations.Complexity +open scoped Classical + +noncomputable section + +variable {branch : Nat → Nat} {n t : Nat} + +abbrev Tape (branch : Nat → Nat) (n t : Nat) := + SignedTupleLayout.Tape (TreeCanonical.locationCount branch n t) (Fin 4) + +local notation "width" => TreeCanonical.locationCount branch n t +local notation "Arena" => Tape branch n t + +def tapeEnumeration (branch : Nat → Nat) (n t : Nat) : + Fin (Fintype.card (Tape branch n t)) ≃ Tape branch n t := + (Fintype.equivFin (Tape branch n t)).symm + +def finalizerTape (branch : Nat → Nat) (n t : Nat) : Fin 4 → Tape branch n t + | 0 => .edgeWork 7 + | 1 => .edgeCount + | 2 => .extra 2 + | 3 => .extra 3 + +theorem finalizerTape_injective (branch : Nat → Nat) (n t : Nat) : + Function.Injective (finalizerTape branch n t) := by + intro i j same + fin_cases i <;> fin_cases j <;> simp [finalizerTape] at same ⊢ + +variable (rows repeats : Nat → Nat) (hn : 0 < n) (hbranch : ∀ k < n, 0 < branch k) + (hrows : ∀ k, 0 < rows (k + 1)) (δ : ℚ) + +local notation "q" => FinitePreliminaryCompletion.alphabet branch n t δ +local notation "Desc" => SignedCompletionSchedule.Descriptor + (rows := rows) (repeats := repeats) + (CanonicalLocalCompletion.alphabet_positive width δ) + (CanonicalLocalCompletion.partitionWidth_le_alphabet width δ) +local notation "Native" => ExactTargetOdometer.NativeLabel + (branch := branch) (n := n) (t := t) rows repeats hn hbranch hrows δ (Fin 4) +local notation "Final" => TargetFinalizeMachine.Labels + (tapeEnumeration branch n t) (finalizerTape branch n t 3) + +abbrev Control := ExactTargetOdometer.Control (branch := branch) (n := n) (t := t) + rows repeats δ + +abbrev Ambient := ExactTargetOdometer.Ambient (branch := branch) (n := n) (t := t) + rows repeats δ + +abbrev Label := NormalizedTargetInitialization.Label ⊕ (Native ⊕ Final) + +def initialControl : Control (branch := branch) (n := n) (t := t) rows repeats δ := + SignedTupleLayout.clean («width» := width) («Desc» := Desc) () + +def initialAmbient : Ambient (branch := branch) (n := n) (t := t) rows repeats δ := + (initialControl (branch := branch) (n := n) (t := t) rows repeats δ).1 + +local notation "Labels" => Label (branch := branch) (n := n) (t := t) + rows repeats hn hbranch hrows δ +local notation "Registers" => Control (branch := branch) (n := n) (t := t) rows repeats δ +local notation "initial" => initialControl (branch := branch) (n := n) (t := t) rows repeats δ +local notation "ambient" => initialAmbient (branch := branch) (n := n) (t := t) rows repeats δ + +def initLabel (label : NormalizedTargetInitialization.Label) : Labels := .inl label + +def driverLabel (label : Native) : Labels := .inr (.inl label) + +def finalizerLabel (label : Final) : Labels := .inr (.inr label) + +local notation "liftInit" => initLabel (branch := branch) (n := n) (t := t) + rows repeats hn hbranch hrows δ +local notation "liftDriver" => driverLabel (branch := branch) (n := n) (t := t) + rows repeats hn hbranch hrows δ +local notation "liftFinal" => finalizerLabel (branch := branch) (n := n) (t := t) + rows repeats hn hbranch hrows δ +local notation "nativeProgram" => ExactTargetOdometer.program + (branch := branch) (n := n) (t := t) (Extra := Fin 4) + rows repeats hn hbranch hrows δ +local notation "nativeEntry" => ExactTargetOdometer.body + (branch := branch) (n := n) (t := t) (Extra := Fin 4) + rows repeats hn hbranch hrows δ + +def program : Labels → TM2.Stmt (fun _ : Arena => Bool) Labels Registers + | .inl label => NormalizedTargetInitialization.instruction liftInit + (some (liftDriver nativeEntry)) none label + | .inr (.inl label) => MachineSubroutine.statement liftDriver + (some (liftFinal .reverse)) (nativeProgram label) + | .inr (.inr label) => TargetFinalizeMachine.instruction q + (tapeEnumeration branch n t) (finalizerTape branch n t) ambient liftFinal label + +local notation "runProgram" => program (branch := branch) (n := n) (t := t) + rows repeats hn hbranch hrows δ + +def machine : FinTM2 where + K := Arena + k₀ := .source .table + k₁ := .extra 3 + Γ _ := Bool + Λ := Labels + main := liftInit .seed + σ := Registers + initialState := initial + m := runProgram + +local notation "tm" => machine (branch := branch) (n := n) (t := t) + rows repeats hn hbranch hrows δ + +def configuration (label : Option Labels) (tapes : Arena → List Bool) : (tm).Cfg := + ⟨label, initial, tapes⟩ + +local notation "cfg" => configuration (branch := branch) (n := n) (t := t) + rows repeats hn hbranch hrows δ + +def returnInTime (tapes : Arena → List Bool) : + StateTransition.EvalsToInTime (TM2.step runProgram) + (cfg (some (liftDriver .exit)) tapes) + (some (cfg (some (liftFinal .reverse)) tapes)) 1 where + steps := 1 + evals_in_steps := rfl + steps_le_m := Nat.le_refl 1 + +local notation "D" => SignedMultiplicity.denominator branch n t rows repeats hn hbranch hrows q +local notation "finalData" => NormalizedTargetTapeBound.finalData + (t := t) rows repeats hn hbranch hrows δ +local notation "finalTapes" => NormalizedTargetTapeBound.finalTapes + (t := t) rows repeats hn hbranch hrows δ +local notation "output" => NormalizedTarget.outputBits (t := t) rows repeats hn hbranch hrows δ + +theorem header_body_eq_outputBits (input : NormalizedSourceInput.Input) : + encodeWords [(finalData input).count, (finalData input).count, + q, (finalData input).count] ++ (finalData input).reversedOutput.reverse = + output input := by + simpa only [NormalizedTargetTapeBound.finalData, SignedTupleSemantics.dataOfPrefix, + List.append_nil, List.reverse_reverse, NormalizedTarget.outputBits, + NormalizedTarget.construct] using + (ExactTargetOnlineEncoding.target_gameBits (t := t) + (NormalizedSourceInput.clauses input) rows repeats hn hbranch hrows δ).symm + +def initializeInTime (input : NormalizedSourceInput.Input) : + StateTransition.EvalsToInTime (TM2.step runProgram) + (cfg (some (liftInit .seed)) (NormalizedTargetInitialization.inputTapes input)) + (some (cfg (some (liftDriver nativeEntry)) + (NormalizedTargetInitialization.readyTapes input))) + (4 * ((NormalizedSourceInput.bits input).length + 1)) := by + exact NormalizedTargetInitialization.initializeInTime liftInit + (some (liftDriver nativeEntry)) none runProgram (fun _ => rfl) input ambient none + +def enumerateInTime (input : NormalizedSourceInput.Input) : + StateTransition.EvalsToInTime (TM2.step runProgram) + (cfg (some (liftDriver nativeEntry)) (NormalizedTargetInitialization.readyTapes input)) + (some (cfg (some (liftDriver .exit)) (finalTapes input))) + (ExactTargetOdometer.timeBound (t := t) rows repeats hn hbranch hrows δ + (NormalizedSourceInput.bits input).length) := by + have run := MachineSubroutine.execution liftDriver (some (liftFinal .reverse)) + nativeProgram runProgram (fun _ => rfl) + (ExactTargetOdometer.targetInTimePolynomial rows repeats hn hbranch hrows δ input [] + (fun _ : Fin 4 => [])) + rw [NormalizedTargetInitialization.ready_eq_native (branch := branch) (n := n) (t := t) input] + delta NormalizedTargetInitialization.zeroDigits + simpa only [configuration, initialControl, + MachineSubroutine.configuration, MachineSubroutine.label, + ExactTargetOdometer.configuration, NormalizedTargetInitialization.zeroDigits, + NormalizedTargetTapeBound.finalTapes, NormalizedTargetTapeBound.finalData, + SignedTupleSemantics.dataOfPrefix, ExactTargetOnlineEncoding.leftKeys, + ExactTargetOnlineEncoding.rightKeys, List.map_nil, List.flatMap_nil, + List.reverse_nil, List.nil_append, List.length_nil] using! run + +def finalizeBudget (size : Nat) : Nat := + (15 + Fintype.card Arena * (q + 9)) * + (TargetTapeEnvelope.coeff width q D * (size + 1) ^ (2 * width + 2) + 1) + +def finalizeInTime (input : NormalizedSourceInput.Input) : + StateTransition.EvalsToInTime (TM2.step runProgram) + (cfg (some (liftFinal .reverse)) (finalTapes input)) + (some (cfg none (MachineDrainMany.haltTapes (.extra 3) (output input)))) + (finalizeBudget (t := t) rows repeats hn hbranch hrows δ (NormalizedSourceInput.bits input).length) := by + have run := TargetFinalizeBound.finalizeInTime q (tapeEnumeration branch n t) + (finalizerTape branch n t) (finalizerTape_injective branch n t) ambient liftFinal + runProgram (fun _ => rfl) (finalTapes input) ambient none (finalData input).count + (finalData input).reversedOutput.reverse + (by simp only [finalizerTape, NormalizedTargetTapeBound.finalTapes, + ExactTargetOdometer.nativeTapes_output, List.reverse_reverse]) + (by simp only [finalizerTape, NormalizedTargetTapeBound.finalTapes, + ExactTargetOdometer.nativeTapes_count]) + (by simp only [finalizerTape, NormalizedTargetTapeBound.finalTapes, + ExactTargetOdometer.nativeTapes_extra]) + (by simp only [finalizerTape, NormalizedTargetTapeBound.finalTapes, + ExactTargetOdometer.nativeTapes_extra]) + (TargetTapeEnvelope.coeff width q D * + ((NormalizedSourceInput.bits input).length + 1) ^ (2 * width + 2)) + (NormalizedTargetTapeBound.finalTapes_length_le_polynomial + rows repeats hn hbranch hrows δ input) + rw [header_body_eq_outputBits rows repeats hn hbranch hrows δ input] at run + exact run + +def totalBudget (size : Nat) : Nat := + 4 * (size + 1) + ExactTargetOdometer.timeBound (t := t) rows repeats hn hbranch hrows δ size + 1 + + finalizeBudget (t := t) rows repeats hn hbranch hrows δ size + +def totalInTime (input : NormalizedSourceInput.Input) : + StateTransition.EvalsToInTime (TM2.step runProgram) + (cfg (some (liftInit .seed)) (NormalizedTargetInitialization.inputTapes input)) + (some (cfg none (MachineDrainMany.haltTapes (.extra 3) (output input)))) + (totalBudget (t := t) rows repeats hn hbranch hrows δ (NormalizedSourceInput.bits input).length) := by + have first := StateTransition.EvalsToInTime.trans (TM2.step runProgram) _ _ _ _ _ + (initializeInTime rows repeats hn hbranch hrows δ input) + (enumerateInTime rows repeats hn hbranch hrows δ input) + have second := StateTransition.EvalsToInTime.trans (TM2.step runProgram) _ _ _ _ _ + first (returnInTime rows repeats hn hbranch hrows δ (finalTapes input)) + have full := StateTransition.EvalsToInTime.trans (TM2.step runProgram) _ _ _ _ _ + second (finalizeInTime rows repeats hn hbranch hrows δ input) + simpa only [totalBudget, Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using full + +def time : Polynomial Nat := + 4 * (Polynomial.X + 1) + + Polynomial.C (SignedCostEnvelope.bodyCoeff width D + 2 * width) * + (Polynomial.X + 1) ^ (SignedCostEnvelope.degree width + width) + 1 + + Polynomial.C (15 + Fintype.card Arena * (q + 9)) * + (Polynomial.C (TargetTapeEnvelope.coeff width q D) * + (Polynomial.X + 1) ^ (2 * width + 2) + 1) + +theorem time_eval (size : Nat) : + (time (t := t) rows repeats hn hbranch hrows δ).eval size = + totalBudget (t := t) rows repeats hn hbranch hrows δ size := by + simp [time, totalBudget, finalizeBudget, ExactTargetOdometer.timeBound] + +private theorem initList_eq (input : NormalizedSourceInput.Input) : + initList tm (NormalizedSourceInput.bits input) = + cfg (some (liftInit .seed)) (NormalizedTargetInitialization.inputTapes input) := by + unfold initList configuration + congr 1 + funext key + cases key with + | source source => + cases source <;> simp [machine, NormalizedTargetInitialization.inputTapes] + rfl + | current i => simp [machine, NormalizedTargetInitialization.inputTapes] + | remaining i => simp [machine, NormalizedTargetInitialization.inputTapes] + | encodedVariable i j => simp [machine, NormalizedTargetInitialization.inputTapes] + | adapterScratch => simp [machine, NormalizedTargetInitialization.inputTapes] + | edgeWork j => simp [machine, NormalizedTargetInitialization.inputTapes] + | edgeCount => simp [machine, NormalizedTargetInitialization.inputTapes] + | extra j => simp [machine, NormalizedTargetInitialization.inputTapes] + +private theorem haltList_eq (word : List Bool) : + haltList tm word = cfg none (MachineDrainMany.haltTapes (.extra 3) word) := by + unfold haltList configuration + congr 1 + +def outputsInTime (input : NormalizedSourceInput.Input) : + TM2OutputsInTime tm (NormalizedSourceInput.bits input) (some (output input)) + (totalBudget (t := t) rows repeats hn hbranch hrows δ + (NormalizedSourceInput.bits input).length) := by + change StateTransition.EvalsToInTime (TM2.step runProgram) + (initList tm (NormalizedSourceInput.bits input)) + (some (haltList tm (output input))) _ + rw [initList_eq, haltList_eq] + exact totalInTime rows repeats hn hbranch hrows δ input + +def computation : + TM2ComputableInPolyTime NormalizedTarget.inputBits (id : List Bool → List Bool) + (NormalizedTarget.outputBits (t := t) rows repeats hn hbranch hrows δ) where + «tm» := tm + inputAlphabet := Equiv.refl Bool + outputAlphabet := Equiv.refl Bool + time := time (t := t) rows repeats hn hbranch hrows δ + outputsFun input := by + change TM2OutputsInTime tm ((NormalizedTarget.inputBits input).map id) + (some ((output input).map id)) + ((time (t := t) rows repeats hn hbranch hrows δ).eval + (NormalizedTarget.inputBits input).length) + have hi := @List.map_id ((tm).Γ (tm).k₀) (NormalizedSourceInput.bits input) + have ho := @List.map_id ((tm).Γ (tm).k₁) (output input) + simpa only [hi, ho, time_eval, NormalizedTarget.inputBits] using + outputsInTime rows repeats hn hbranch hrows δ input + +def targetComputation : + TM2ComputableInPolyTime NormalizedSourceInput.bits Encoding.gameBits + (NormalizedTarget.construct (t := t) rows repeats hn hbranch hrows δ) where + «tm» := tm + inputAlphabet := Equiv.refl Bool + outputAlphabet := Equiv.refl Bool + time := time (t := t) rows repeats hn hbranch hrows δ + outputsFun input := by + change TM2OutputsInTime tm ((NormalizedSourceInput.bits input).map id) + (some ((output input).map id)) + ((time (t := t) rows repeats hn hbranch hrows δ).eval + (NormalizedSourceInput.bits input).length) + have hi := @List.map_id ((tm).Γ (tm).k₀) (NormalizedSourceInput.bits input) + have ho := @List.map_id ((tm).Γ (tm).k₁) (output input) + simpa only [hi, ho, time_eval] using + outputsInTime (t := t) rows repeats hn hbranch hrows δ input + +theorem workAlphabet_finite (key : (tm).K) : Finite ((tm).Γ key) := by + change Finite Bool + infer_instance + +theorem finiteAlphabet : MachineFiniteAlphabet.FiniteAlphabet tm := + MachineFiniteAlphabet.of_bool tm (fun _ => rfl) + +end +end PerfectCompleteness.NormalizedTargetMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/NormalizedTargetProducer.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/NormalizedTargetProducer.lean new file mode 100644 index 0000000000000000000000000000000000000000..a06d5102d3df621deb40b33589550ed3beec7472 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/NormalizedTargetProducer.lean @@ -0,0 +1,97 @@ +import OAI.Computability.PerfectCompleteness.Machines.NormalizedTargetMachine + +namespace OAI + +section + +namespace PerfectCompleteness.NormalizedTargetProducer + +open Turing UniqueGamesTheorem.Foundations Complexity + +noncomputable section + +variable {branch : Nat → Nat} {n t : Nat} + (rows repeats : Nat → Nat) (hn : 0 < n) (hbranch : ∀ k < n, 0 < branch k) + (hrows : ∀ k, 0 < rows (k + 1)) (δ : ℚ) + +local notation "q" => FinitePreliminaryCompletion.alphabet branch n t δ + +def construct {language : List Bool → Prop} + (source : CookLevin.PolynomialThreeSATReduction language) (input : List Bool) : Instance q := + NormalizedTarget.construct (t := t) rows repeats hn hbranch hrows δ + (NormalizedSourceInput.fromReduction source input) + +def computation {language : List Bool → Prop} + (source : CookLevin.PolynomialThreeSATReduction language) : + TM2ComputableInPolyTime (id : List Bool → List Bool) Encoding.gameBits + (construct (t := t) rows repeats hn hbranch hrows δ source) := by + change TM2ComputableInPolyTime (id : List Bool → List Bool) Encoding.gameBits + (fun input => NormalizedTarget.construct (t := t) rows repeats hn hbranch hrows δ + (NormalizedSourceInput.fromReduction source input)) + exact MachineSequential.composeBits + (f := NormalizedSourceInput.fromReduction source) + (g := NormalizedTarget.construct (t := t) rows repeats hn hbranch hrows δ) + (NormalizedSourceInput.computation source) + (NormalizedTargetMachine.targetComputation (t := t) rows repeats hn hbranch hrows δ) + +theorem finiteAlphabet {language : List Bool → Prop} + (source : CookLevin.PolynomialThreeSATReduction language) + (finiteSource : MachineFiniteAlphabet.FiniteAlphabet source.computation.tm) : + MachineFiniteAlphabet.FiniteAlphabet + (computation (t := t) rows repeats hn hbranch hrows δ source).tm := + MachineFiniteAlphabet.composeBits + (NormalizedSourceInput.computation source) + (NormalizedTargetMachine.targetComputation (t := t) rows repeats hn hbranch hrows δ) + (NormalizedSourceInput.computation_finiteAlphabet source finiteSource) + (NormalizedTargetMachine.finiteAlphabet (t := t) rows repeats hn hbranch hrows δ) + +theorem source_satisfiable_iff {language : List Bool → Prop} + (source : CookLevin.PolynomialThreeSATReduction language) (input : List Bool) : + (NormalizedSourceInput.fromReduction source input).formula.Satisfiable ↔ language input := by + change (PCPSource.normalizedFormula (source.reduce input)).Satisfiable ↔ language input + exact (PCPSource.normalizedFormula_satisfiable_iff (source.reduce input)).trans + (source.correct input).symm + +theorem perfectlyComplete {language : List Bool → Prop} + (source : CookLevin.PolynomialThreeSATReduction language) (input : List Bool) + (accepted : language input) : + PerfectlyComplete (construct (t := t) rows repeats hn hbranch hrows δ source input) := by + apply NormalizedTarget.perfectlyComplete (t := t) rows repeats hn hbranch hrows δ + (NormalizedSourceInput.fromReduction source input) + exact (source_satisfiable_iff source input).mpr accepted + +theorem source_clauseGap {language : List Bool → Prop} + (source : CookLevin.PolynomialThreeSATReduction language) (input : List Bool) + (rejected : ¬language input) : + SourceAmplification.ClauseGap + (NormalizedSourceInput.clauses (NormalizedSourceInput.fromReduction source input)) + PCPSource.sourceGap := + NormalizedSourceInput.normalized_clauseGap (source.reduce input) + (fun satisfiable => rejected ((source.correct input).mpr satisfiable)) + +theorem producer (language : List Bool → Prop) (membership : CookLevin.InNP language) : + ∃ source : CookLevin.PolynomialThreeSATReduction language, + ∃ runtime : TM2ComputableInPolyTime (id : List Bool → List Bool) Encoding.gameBits + (construct (t := t) rows repeats hn hbranch hrows δ source), + MachineFiniteAlphabet.FiniteAlphabet runtime.tm ∧ + ∀ input : List Bool, + ((NormalizedSourceInput.fromReduction source input).formula.Satisfiable ↔ language input) ∧ + (language input → PerfectlyComplete + (construct (t := t) rows repeats hn hbranch hrows δ source input)) ∧ + (¬language input → SourceAmplification.ClauseGap + (NormalizedSourceInput.clauses (NormalizedSourceInput.fromReduction source input)) + PCPSource.sourceGap) := by + obtain ⟨source, finiteSource⟩ := CookLevin.Completeness.threeSATReduction language membership + refine ⟨source, computation (t := t) rows repeats hn hbranch hrows δ source, + finiteAlphabet (t := t) rows repeats hn hbranch hrows δ source finiteSource, ?_⟩ + intro input + exact ⟨source_satisfiable_iff source input, + perfectlyComplete (t := t) rows repeats hn hbranch hrows δ source input, + source_clauseGap source input⟩ + +end +end PerfectCompleteness.NormalizedTargetProducer + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/NormalizedTargetTapeBound.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/NormalizedTargetTapeBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..3d444277cc62242d2faef69131e238ff15a2d38c --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/NormalizedTargetTapeBound.lean @@ -0,0 +1,187 @@ +import OAI.Computability.PerfectCompleteness.Foundations.SourceKeyBoundsLemmas +import OAI.Computability.PerfectCompleteness.Machines.ExactTargetOdometer +import OAI.Computability.PerfectCompleteness.Machines.TargetTapeEnvelope + +namespace OAI + + +namespace PerfectCompleteness.NormalizedTargetTapeBound + + +open UniqueGamesTheorem.Foundations.Complexity +open scoped Classical + +noncomputable section + +variable {branch : Nat → Nat} {n t : Nat} + (rows repeats : Nat → Nat) (hn : 0 < n) (hbranch : ∀ k < n, 0 < branch k) + (hrows : ∀ k, 0 < rows (k + 1)) (δ : ℚ) + (input : NormalizedSourceInput.Input) + +local notation "width" => TreeCanonical.locationCount branch n t +local notation "q" => FinitePreliminaryCompletion.alphabet branch n t δ +local notation "D" => SignedMultiplicity.denominator branch n t rows repeats hn hbranch hrows q +local notation "clauses" => NormalizedSourceInput.clauses input +local notation "order" => CompletedVisitOrder.completedOrder + (t := t) clauses rows repeats hn hbranch hrows δ +local notation "target" => NormalizedTarget.construct (t := t) rows repeats hn hbranch hrows δ input +local notation "T" => List.length (NormalizedSourceInput.bits input) +local notation "E" => List.length order + +def finalData : SignedTupleBodyMachine.Data width := + SignedTupleSemantics.dataOfPrefix (t := t) clauses rows repeats hn hbranch hrows δ order [] + +def finalTapes : SignedTupleLayout.Tape width (Fin 4) → List Bool := + ExactTargetOdometer.nativeTapes (t := t) input + (fun _ => ⟨0, NormalizedSourceInput.clauseCount_positive input⟩) + (finalData (t := t) rows repeats hn hbranch hrows δ input) (fun _ => []) + +theorem order_length_eq_edges : E = (target).edges.length := by + exact (CompletedVisitOrder.completedOrder_length + (t := t) clauses rows repeats hn hbranch hrows δ).trans + (NormalizedTarget.edge_count (t := t) rows repeats hn hbranch hrows δ input).symm + +theorem count_le : E ≤ D * (T + 1) ^ width := by + rw [CompletedVisitOrder.completedOrder_length] + apply Nat.mul_le_mul_left + exact Nat.pow_le_pow_left + ((SourceKeyBounds.clauseCount_le_bits input).trans (Nat.le_succ _)) _ + +theorem leftStream_length_le : + (BinaryNameSearch.stream (CanonicalVertexNames.tokens + (finalData (t := t) rows repeats hn hbranch hrows δ input).leftKeys)).length ≤ + CanonicalDictionaryNames.streamBound width T E := by + change (BinaryNameSearch.stream (CanonicalVertexNames.tokens + ((order).map (fun e => CanonicalGame.leftKey + (FinitePreliminaryCompletion.blockFamily clauses branch n t rows repeats) e.1)))).length ≤ _ + have h := CanonicalVertexNames.stream_length_le + ((order).map (fun e => CanonicalGame.leftKey + (FinitePreliminaryCompletion.blockFamily clauses branch n t rows repeats) e.1)) T + (by + intro key present + obtain ⟨e, _, rfl⟩ := List.mem_map.mp present + exact SourceKeyBounds.left_retained_length input rows repeats e.1) + (by + intro key present entry member + obtain ⟨e, _, rfl⟩ := List.mem_map.mp present + exact SourceKeyBounds.left_entryID_le input rows repeats e.1 entry member) + simpa only [List.length_map, CanonicalDictionaryNames.streamBound] using h + +theorem rightStream_length_le : + (BinaryNameSearch.stream (CanonicalVertexNames.tokens + (finalData (t := t) rows repeats hn hbranch hrows δ input).rightKeys)).length ≤ + CanonicalDictionaryNames.streamBound width T E := by + change (BinaryNameSearch.stream (CanonicalVertexNames.tokens + ((order).map (fun e => CanonicalGame.rightKey + (FinitePreliminaryCompletion.blockFamily clauses branch n t rows repeats) e.1)))).length ≤ _ + have h := CanonicalVertexNames.stream_length_le + ((order).map (fun e => CanonicalGame.rightKey + (FinitePreliminaryCompletion.blockFamily clauses branch n t rows repeats) e.1)) T + (by + intro key present + obtain ⟨e, _, rfl⟩ := List.mem_map.mp present + exact SourceKeyBounds.right_retained_length input rows repeats e.1) + (by + intro key present entry member + obtain ⟨e, _, rfl⟩ := List.mem_map.mp present + exact SourceKeyBounds.right_entryID_le input rows repeats e.1 entry member) + simpa only [List.length_map, CanonicalDictionaryNames.streamBound] using h + +theorem reversedOutput_length_le_output : + (finalData (t := t) rows repeats hn hbranch hrows δ input).reversedOutput.length ≤ + (NormalizedTarget.outputBits (t := t) rows repeats hn hbranch hrows δ input).length := by + have encoded := ExactTargetOnlineEncoding.target_gameBits (t := t) + clauses rows repeats hn hbranch hrows δ + change (Encoding.gameBits target) = _ at encoded + change _ ≤ (Encoding.gameBits target).length + rw [encoded] + simp only [finalData, SignedTupleSemantics.dataOfPrefix, List.append_nil, + List.length_reverse, List.length_append] + omega + +theorem reversedOutput_length_le : + (finalData (t := t) rows repeats hn hbranch hrows δ input).reversedOutput.length ≤ + TargetTapeEnvelope.outputBound q E := by + have h := (reversedOutput_length_le_output (t := t) rows repeats hn hbranch hrows δ input).trans + (NormalizedTarget.outputBits_length_le (t := t) rows repeats hn hbranch hrows δ input) + rw [← order_length_eq_edges (t := t) rows repeats hn hbranch hrows δ input] at h + exact h + +theorem finalTapes_length_le : + ∀ k, (finalTapes (t := t) rows repeats hn hbranch hrows δ input k).length ≤ + TargetTapeEnvelope.bound width q T E := by + have leftBound := leftStream_length_le (t := t) rows repeats hn hbranch hrows δ input + have rightBound := rightStream_length_le (t := t) rows repeats hn hbranch hrows δ input + have outputBound := reversedOutput_length_le (t := t) rows repeats hn hbranch hrows δ input + have countBound := SourceKeyBounds.clauseCount_le_bits input + have sourceLe : T ≤ TargetTapeEnvelope.bound width q T E := by + unfold TargetTapeEnvelope.bound + omega + have currentLe : 1 ≤ TargetTapeEnvelope.bound width q T E := by + unfold TargetTapeEnvelope.bound + omega + have remainingLe : NormalizedSourceInput.clauseCount input - 1 + 1 ≤ + TargetTapeEnvelope.bound width q T E := by + unfold TargetTapeEnvelope.bound + omega + have leftLe := leftBound.trans (show CanonicalDictionaryNames.streamBound width T E ≤ + TargetTapeEnvelope.bound width q T E by unfold TargetTapeEnvelope.bound; omega) + have rightLe := rightBound.trans (show CanonicalDictionaryNames.streamBound width T E ≤ + TargetTapeEnvelope.bound width q T E by unfold TargetTapeEnvelope.bound; omega) + have outputLe := outputBound.trans (show TargetTapeEnvelope.outputBound q E ≤ + TargetTapeEnvelope.bound width q T E by unfold TargetTapeEnvelope.bound; omega) + have encodedCountLe : E + 1 ≤ TargetTapeEnvelope.bound width q T E := by + unfold TargetTapeEnvelope.bound + omega + intro k + cases k with + | source source => + cases source with + | table => simpa [finalTapes, ExactTargetOdometer.nativeTapes, + SignedTupleBodyMachine.tapes, ExactTargetOdometer.baseTapes] using sourceLe + | digit i => simp [finalTapes, ExactTargetOdometer.nativeTapes, + SignedTupleBodyMachine.tapes, ExactTargetOdometer.baseTapes] + | work j => simp [finalTapes, ExactTargetOdometer.nativeTapes, + SignedTupleBodyMachine.tapes, ExactTargetOdometer.baseTapes] + | variableName i j => simp [finalTapes, ExactTargetOdometer.nativeTapes, + SignedTupleBodyMachine.tapes, ExactTargetOdometer.baseTapes] + | current i => simpa [finalTapes, ExactTargetOdometer.nativeTapes, + SignedTupleBodyMachine.tapes, ExactTargetOdometer.baseTapes, encodeWord_length] using currentLe + | remaining i => simpa [finalTapes, ExactTargetOdometer.nativeTapes, + SignedTupleBodyMachine.tapes, ExactTargetOdometer.baseTapes, encodeWord_length] using remainingLe + | encodedVariable i j => simp [finalTapes, ExactTargetOdometer.nativeTapes, + SignedTupleBodyMachine.tapes, ExactTargetOdometer.baseTapes] + | adapterScratch => simp [finalTapes, ExactTargetOdometer.nativeTapes, + SignedTupleBodyMachine.tapes, ExactTargetOdometer.baseTapes] + | edgeCount => simpa [finalTapes, ExactTargetOdometer.nativeTapes, + SignedTupleBodyMachine.tapes, finalData, SignedTupleSemantics.dataOfPrefix, + encodeWord_length] using encodedCountLe + | extra x => simp [finalTapes, ExactTargetOdometer.nativeTapes, + SignedTupleBodyMachine.tapes, ExactTargetOdometer.baseTapes] + | edgeWork j => + by_cases one : j = 1 + · subst j + simpa [finalTapes, ExactTargetOdometer.nativeTapes, SignedTupleBodyMachine.tapes] + using leftLe + · by_cases eight : j = 8 + · subst j + simpa [finalTapes, ExactTargetOdometer.nativeTapes, SignedTupleBodyMachine.tapes] + using rightLe + · by_cases seven : j = 7 + · subst j + simpa [finalTapes, ExactTargetOdometer.nativeTapes, SignedTupleBodyMachine.tapes] + using outputLe + · simp [finalTapes, ExactTargetOdometer.nativeTapes, SignedTupleBodyMachine.tapes, + ExactTargetOdometer.baseTapes, one, eight, seven] + +theorem finalTapes_length_le_polynomial : + ∀ k, (finalTapes (t := t) rows repeats hn hbranch hrows δ input k).length ≤ + TargetTapeEnvelope.coeff width q D * (T + 1) ^ (2 * width + 2) := by + intro k + exact (finalTapes_length_le (t := t) rows repeats hn hbranch hrows δ input k).trans + (TargetTapeEnvelope.bound_le width q D T E (count_le (t := t) rows repeats hn hbranch hrows δ input)) + +end +end PerfectCompleteness.NormalizedTargetTapeBound + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/OrClosure.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/OrClosure.lean new file mode 100644 index 0000000000000000000000000000000000000000..66999124fb455c1f90274ecb3f12481733eb5ffc --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/OrClosure.lean @@ -0,0 +1,269 @@ +import OAI.Computability.PerfectCompleteness.Machines.PositionLemmas +import OAI.Computability.UniqueGames.Machines.MachineCompositionLemmas +import OAI.Computability.UniqueGames.Reduction.MachineSubstitution +import OAI.Computability.UniqueGames.Reduction.MachineTransfer + +namespace OAI + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.OrClosure + +open Turing PostfixModel InitializationTemplate +open Reduction.MachineSubstitution (pushWord stepAux_pushWord) + + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool + +structure Ports (K : Type) where + remaining : K + reversed : K + count : K + remaining_ne_reversed : remaining ≠ reversed + remaining_ne_count : remaining ≠ count + reversed_ne_count : reversed ≠ count + +def frame (ports : Ports K) (base : K → List Bool) + (remaining reversed count : List Bool) : K → List Bool := + Function.update (Function.update (Function.update base ports.remaining remaining) + ports.reversed reversed) ports.count count + +@[simp] theorem frame_remaining (p : Ports K) (base : K → List Bool) + (remaining reversed count : List Bool) : + frame p base remaining reversed count p.remaining = remaining := by + simp [frame, p.remaining_ne_count, p.remaining_ne_reversed] + +@[simp] theorem frame_reversed (p : Ports K) (base : K → List Bool) + (remaining reversed count : List Bool) : + frame p base remaining reversed count p.reversed = reversed := by + simp [frame, p.reversed_ne_count] + +@[simp] theorem frame_count (p : Ports K) (base : K → List Bool) + (remaining reversed count : List Bool) : + frame p base remaining reversed count p.count = count := by + simp [frame] + +theorem frame_other (p : Ports K) (base : K → List Bool) + (remaining reversed count : List Bool) (k : K) + (hr : k ≠ p.remaining) (ho : k ≠ p.reversed) (hc : k ≠ p.count) : + frame p base remaining reversed count k = base k := by + simp [frame, hr, ho, hc] + +@[simp] theorem frame_self (p : Ports K) (base : K → List Bool) : + frame p base (base p.remaining) (base p.reversed) (base p.count) = base := by + simp [frame] + +@[simp] theorem update_remaining (p : Ports K) (base : K → List Bool) + (remaining reversed count replacement : List Bool) : + Function.update (frame p base remaining reversed count) p.remaining replacement = + frame p base replacement reversed count := by + funext k + by_cases hr : k = p.remaining <;> by_cases ho : k = p.reversed <;> + by_cases hc : k = p.count <;> + simp_all [frame, p.remaining_ne_reversed, p.remaining_ne_count, p.reversed_ne_count, + Ne.symm p.remaining_ne_reversed, Ne.symm p.remaining_ne_count, Ne.symm p.reversed_ne_count] + +@[simp] theorem update_reversed (p : Ports K) (base : K → List Bool) + (remaining reversed count replacement : List Bool) : + Function.update (frame p base remaining reversed count) p.reversed replacement = + frame p base remaining replacement count := by + funext k + by_cases hr : k = p.remaining <;> by_cases ho : k = p.reversed <;> + by_cases hc : k = p.count <;> + simp_all [frame, p.remaining_ne_reversed, p.remaining_ne_count, p.reversed_ne_count, + Ne.symm p.remaining_ne_reversed, Ne.symm p.remaining_ne_count, Ne.symm p.reversed_ne_count] + +@[simp] theorem update_count (p : Ports K) (base : K → List Bool) + (remaining reversed count replacement : List Bool) : + Function.update (frame p base remaining reversed count) p.count replacement = + frame p base remaining reversed replacement := by + simp [frame] + +def seed (p : Ports K) (again : Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) := + .push p.reversed (fun _ => false) + (.push p.count (fun _ => true) + (.load (fun state => (state.1, none)) (.goto fun _ => again))) + +def loop (p : Ports K) (again : Λ) (exit : Option Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) := + .pop p.remaining (fun state head => (state.1, head)) + (.branch (fun state => state.2.getD false) + (pushWord p.reversed (encodeWord 4) + (.push p.count (fun _ => true) + (.load (fun state => (state.1, none)) (.goto fun _ => again)))) + (.push p.remaining (fun _ => false) + (.load (fun state => (state.1, none)) + (Reduction.MachineTransfer.exitAt p.remaining exit)))) + +omit [DecidableEq K] in +theorem seedPushBound (p : Ports K) (again : Λ) : + Runtime.statementPushBound (seed (σ := σ) p again) = 2 := rfl + +omit [DecidableEq K] in +theorem loopPushBound (p : Ports K) (again : Λ) (exit : Option Λ) : + Runtime.statementPushBound (loop (σ := σ) p again exit) = 6 := by + cases exit <;> rfl + +theorem seedStep (p : Ports K) (again : Λ) (base : K → List Bool) + (remaining output count : List Bool) (ambient : σ) (register : Option Bool) : + TM2.stepAux (seed p again) (ambient, register) + (frame p base remaining output count) = + ⟨some again, (ambient, none), + frame p base remaining (false :: output) (true :: count)⟩ := by + simp [seed, TM2.stepAux] + +theorem loopStep_zero (p : Ports K) (again : Λ) (exit : Option Λ) + (base : K → List Bool) (suffix output count : List Bool) + (ambient : σ) (register : Option Bool) : + TM2.stepAux (loop p again exit) (ambient, register) + (frame p base (encodeWord 0 ++ suffix) output count) = + ⟨exit, (ambient, none), frame p base (encodeWord 0 ++ suffix) output count⟩ := by + cases exit <;> + simp [loop, TM2.stepAux, encodeWord, Reduction.MachineTransfer.exitAt] + +theorem loopStep_succ (p : Ports K) (again : Λ) (exit : Option Λ) + (base : K → List Bool) (n : Nat) (suffix output count : List Bool) + (ambient : σ) (register : Option Bool) : + TM2.stepAux (loop p again exit) (ambient, register) + (frame p base (encodeWord (n + 1) ++ suffix) output count) = + ⟨some again, (ambient, none), + frame p base (encodeWord n ++ suffix) + ((encodeWord 4).reverse ++ output) (true :: count)⟩ := by + simp [loop, TM2.stepAux, stepAux_pushWord, encodeWord, List.replicate_succ] + +theorem tokenBits_append (first second : List Token) : + tokenBits (first ++ second) = tokenBits first ++ tokenBits second := by + simp [tokenBits, tokenWords, encodeWords_append] + +@[simp] theorem tokenBits_or : tokenBits [Token.or] = encodeWord 4 := rfl + +@[simp] theorem tokenBits_false : tokenBits [Token.const false] = [false] := rfl + +theorem tokenBits_closeOr (n : Nat) : + tokenBits (closeOr n) = [false] ++ tokenBits (List.replicate n Token.or) := by + unfold closeOr + rw [tokenBits_append, tokenBits_false] + +theorem tokenBits_replicate_succ (n : Nat) : + tokenBits (List.replicate (n + 1) Token.or) = + encodeWord 4 ++ tokenBits (List.replicate n Token.or) := by + rw [List.replicate_succ] + change tokenBits ([Token.or] ++ List.replicate n Token.or) = _ + rw [tokenBits_append, tokenBits_or] + +private theorem replicate_push (n : Nat) (count : List Bool) : + List.replicate n true ++ true :: count = + List.replicate (n + 1) true ++ count := by + induction n with + | zero => rfl + | succ n ih => + simpa only [List.replicate_succ, List.cons_append] using (congrArg (List.cons true) ih) + +theorem loopTrace (p : Ports K) (again : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atLoop : program again = loop p again exit) + (base : K → List Bool) (n : Nat) (suffix output count : List Bool) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[n + 1] + (some ⟨some again, (ambient, register), + frame p base (encodeWord n ++ suffix) output count⟩) = + some ⟨exit, (ambient, none), + frame p base (encodeWord 0 ++ suffix) + ((tokenBits (List.replicate n Token.or)).reverse ++ output) + (List.replicate n true ++ count)⟩ := by + induction n generalizing output count register with + | zero => + change some (TM2.stepAux (program again) (ambient, register) + (frame p base (encodeWord 0 ++ suffix) output count)) = _ + rw [atLoop, loopStep_zero] + rfl + | succ n ih => + rw [Function.iterate_succ_apply] + change (MachineComposition.advance (TM2.step program))^[n + 1] + (some (TM2.stepAux (program again) (ambient, register) + (frame p base (encodeWord (n + 1) ++ suffix) output count))) = _ + rw [atLoop, loopStep_succ, ih] + simp only [tokenBits_replicate_succ, List.reverse_append, List.append_assoc] + rw [replicate_push] + +theorem closureTrace (p : Ports K) (entry again : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atSeed : program entry = seed p again) + (atLoop : program again = loop p again exit) + (base : K → List Bool) (n : Nat) (suffix output count : List Bool) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[n + 2] + (some ⟨some entry, (ambient, register), + frame p base (encodeWord n ++ suffix) output count⟩) = + some ⟨exit, (ambient, none), + frame p base (encodeWord 0 ++ suffix) + ((tokenBits (closeOr n)).reverse ++ output) + (List.replicate (n + 1) true ++ count)⟩ := by + rw [Function.iterate_succ_apply] + change (MachineComposition.advance (TM2.step program))^[n + 1] + (some (TM2.stepAux (program entry) (ambient, register) + (frame p base (encodeWord n ++ suffix) output count))) = _ + rw [atSeed, seedStep, loopTrace p again exit program atLoop] + simp only [tokenBits_closeOr, List.singleton_append, List.reverse_cons, List.append_assoc] + rw [replicate_push] + +def closureInTime (p : Ports K) (entry again : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atSeed : program entry = seed p again) + (atLoop : program again = loop p again exit) + (base : K → List Bool) (n : Nat) (suffix output count : List Bool) + (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some entry, (ambient, register), frame p base (encodeWord n ++ suffix) output count⟩ + (some ⟨exit, (ambient, none), + frame p base (encodeWord 0 ++ suffix) + ((tokenBits (closeOr n)).reverse ++ output) + (List.replicate (n + 1) true ++ count)⟩) (n + 2) where + steps := n + 2 + evals_in_steps := by + change (MachineComposition.advance (TM2.step program))^[n + 2] _ = _ + exact closureTrace p entry again exit program atSeed atLoop + base n suffix output count ambient register + steps_le_m := Nat.le_refl _ + +theorem increment_count (n c : Nat) (suffix : List Bool) : + List.replicate (n + 1) true ++ (encodeWord c ++ suffix) = + encodeWord (c + n + 1) ++ suffix := by + simp only [encodeWord, ← List.append_assoc, List.replicate_append_replicate] + rw [show n + 1 + c = c + n + 1 by omega] + +section FiniteMachine + +variable [Fintype K] [Fintype σ] + +def machine (p : Ports K) (ambient : σ) : FinTM2 where + K := K + k₀ := p.remaining + k₁ := p.reversed + Γ := Alphabet + Λ := Bool + main := false + σ := σ × Option Bool + initialState := (ambient, none) + Γk₀Fin := inferInstance + m label := if label then loop p true none else seed p true + +theorem machineTrace (p : Ports K) (base : K → List Bool) (n : Nat) + (suffix output count : List Bool) (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (machine p ambient).step)^[n + 2] + (some ⟨some false, (ambient, register), + frame p base (encodeWord n ++ suffix) output count⟩) = + some ⟨none, (ambient, none), + frame p base (encodeWord 0 ++ suffix) + ((tokenBits (closeOr n)).reverse ++ output) + (List.replicate (n + 1) true ++ count)⟩ := by + exact closureTrace p false true none (machine p ambient).m rfl rfl + base n suffix output count ambient register + +end FiniteMachine + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.OrClosure + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/OriginalWholeCutTape.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/OriginalWholeCutTape.lean new file mode 100644 index 0000000000000000000000000000000000000000..2815da6f1d5fc9650d76e3cbd19b9f01e6b63ce0 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/OriginalWholeCutTape.lean @@ -0,0 +1,239 @@ +import OAI.Computability.PerfectCompleteness.Foundations.OriginalTerminalSplitLemmas +import OAI.Computability.PerfectCompleteness.Foundations.WholeArraySubtreeSplit +import OAI.Computability.PerfectCompleteness.Foundations.WholeCutCallsLemmas +import OAI.Computability.PerfectCompleteness.Sampling.WholeCutSampler + +namespace OAI + +section + +namespace PerfectCompleteness.OriginalWholeCutTape + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open scoped Classical + +noncomputable section + +section Rearrangement + +variable {D T C S E L O B : Type*} + +def regroupStep : + ((D → ((T → S) × E)) × ((L × ((C → S) × B)) × O)) ≃ + (((D → E) × (L × O)) × (((D × T ⊕ C) → S) × B)) where + toFun x := + ((fun d => (x.1 d).2, (x.2.1.1, x.2.2)), + (fun call => match call with + | .inl dt => (x.1 dt.1).1 dt.2 + | .inr c => x.2.1.2.1 c, + x.2.1.2.2)) + invFun x := + ((fun d => (fun terminal => x.2.1 (.inl (d, terminal)), x.1.1 d)), + ((x.1.2.1, (fun c => x.2.1 (.inr c), x.2.2)), x.1.2.2)) + left_inv x := rfl + right_inv x := by + apply Prod.ext + · rfl + · apply Prod.ext + · funext call + cases call <;> rfl + · rfl + +def prependUnit (A : Type*) : A ≃ Unit × A where + toFun x := ((), x) + invFun := Prod.snd + left_inv _ := rfl + right_inv x := by rcases x with ⟨u, x⟩; cases u; rfl + +end Rearrangement + +variable {branch : Nat → Nat} {n m k t : Nat} + +abbrev cutSlots (p : Path branch n m) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Slots branch m → Fin t → MixedSupport.Slot := + fun s => slots (p.slotEmbedding s) + +def Exterior (rows repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n (m + 1)) → + (Slots branch n → Fin t → MixedSupport.Slot) → Type + | _, _, .refl _, _ => Unit + | n + 1, _, .step i p, slots => + (BucketSampler.Direction (rows (n + 1)) → + OriginalTerminalSplit.ExteriorTape F2 repeats (.step i p) (LeafDomain slots)) × + (Exterior rows repeats p (childSlots slots i) × + ((j : RecursiveSampler.OffPath i) → Arrays (childSlots slots j.val) rows)) + +@[instance_reducible] def exteriorFintypeAux (rows repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n (m + 1)) → + (slots : Slots branch n → Fin t → MixedSupport.Slot) → + Fintype (Exterior rows repeats p slots) + | _, _, .refl _, _ => inferInstanceAs (Fintype Unit) + | n + 1, _, .step i p, slots => + letI : Fintype (Exterior rows repeats p (childSlots slots i)) := + exteriorFintypeAux rows repeats p (childSlots slots i) + inferInstanceAs (Fintype + ((BucketSampler.Direction (rows (n + 1)) → + OriginalTerminalSplit.ExteriorTape F2 repeats (.step i p) (LeafDomain slots)) × + (Exterior rows repeats p (childSlots slots i) × + ((j : RecursiveSampler.OffPath i) → Arrays (childSlots slots j.val) rows)))) + +instance exteriorFintype (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Fintype (Exterior rows repeats p slots) := exteriorFintypeAux rows repeats p slots + +def exteriorZero (rows repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n (m + 1)) → + (slots : Slots branch n → Fin t → MixedSupport.Slot) → Exterior rows repeats p slots + | _, _, .refl _, _ => () + | _, _, .step i p, slots => + ((fun _ j => RecursiveSampler.zeroDraw F2 repeats (.step i p) (LeafDomain slots) j.val), + (exteriorZero rows repeats p (childSlots slots i), fun _ _ _ => 0)) + +instance exteriorNonempty (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Nonempty (Exterior rows repeats p slots) := ⟨exteriorZero rows repeats p slots⟩ + +abbrev BelowTape (rows repeats : Nat → Nat) (chosen : Fin (branch m)) + (q : Path branch m k) (slots : Slots branch (m + 1) → Fin t → MixedSupport.Slot) := + WholeArraySampler.Tape rows repeats q (childSlots slots chosen) × + ((j : RecursiveSampler.OffPath chosen) → Arrays (childSlots slots j.val) rows) + +abbrev Calls (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (chosen : Fin (branch m)) (q : Path branch m k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) := + OriginalCutCalls.Index rows repeats p → + RecursiveSampler.Tape F2 repeats (.step chosen q) (LeafDomain (cutSlots p slots)) + +def splitTape (rows repeats : Nat → Nat) : + {n m k : Nat} → (p : Path branch n (m + 1)) → (chosen : Fin (branch m)) → + (q : Path branch m k) → (slots : Slots branch n → Fin t → MixedSupport.Slot) → + WholeArraySampler.Tape rows repeats (p.append (.step chosen q)) slots ≃ + Exterior rows repeats p slots × + (Calls rows repeats p chosen q slots × + BelowTape rows repeats chosen q (cutSlots p slots)) + | _, _, _, .refl _, chosen, q, slots => + (WholeCutSampler.stepEquiv chosen + (WholeArraySampler.RootTape rows repeats (.step chosen q) slots) + (WholeArraySampler.Tape rows repeats q (childSlots slots chosen)) + (fun j => Arrays (childSlots slots j.val) rows)).symm.trans (prependUnit _) + | n + 1, _, _, .step i p, chosen, q, slots => + (WholeCutSampler.stepEquiv i + (WholeArraySampler.RootTape rows repeats (.step i (p.append (.step chosen q))) slots) + (WholeArraySampler.Tape rows repeats (p.append (.step chosen q)) (childSlots slots i)) + (fun j => Arrays (childSlots slots j.val) rows)).symm.trans + ((Equiv.prodCongr + (Equiv.piCongrRight (fun _ : BucketSampler.Direction (rows (n + 1)) => + OriginalTerminalSplit.splitTape F2 repeats (.step i p) (.step chosen q) + (LeafDomain slots))) + (Equiv.prodCongr (splitTape rows repeats p chosen q (childSlots slots i)) + (Equiv.refl _))).trans regroupStep) + +@[simp] theorem splitTape_refl (rows repeats : Nat → Nat) (chosen : Fin (branch m)) + (q : Path branch m k) (slots : Slots branch (m + 1) → Fin t → MixedSupport.Slot) + (ω : WholeArraySampler.Tape rows repeats (.step chosen q) slots) : + splitTape rows repeats (.refl (m + 1)) chosen q slots ω = + ((), (ω (.inl ()), (ω (.inr (.inl ())), fun j => ω (.inr (.inr j))))) := rfl + +@[simp] theorem splitTape_step_exterior (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n (m + 1)) (chosen : Fin (branch m)) (q : Path branch m k) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ω : WholeArraySampler.Tape rows repeats ((Path.step i p).append (.step chosen q)) slots) : + (splitTape rows repeats (.step i p) chosen q slots ω).1 = + ((fun v => (OriginalTerminalSplit.splitTape F2 repeats (.step i p) (.step chosen q) + (LeafDomain slots) (ω (.inl ()) v)).2), + ((splitTape rows repeats p chosen q (childSlots slots i) (ω (.inr (.inl ())))).1, + fun j => ω (.inr (.inr j)))) := rfl + +@[simp] theorem splitTape_step_rootCall (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n (m + 1)) (chosen : Fin (branch m)) (q : Path branch m k) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ω : WholeArraySampler.Tape rows repeats ((Path.step i p).append (.step chosen q)) slots) + (v : BucketSampler.Direction (rows (n + 1))) + (terminal : TerminalCalls.TerminalIndex repeats (.step i p)) : + (splitTape rows repeats (.step i p) chosen q slots ω).2.1 + (OriginalCutCalls.rootCall rows repeats i p (v, terminal)) = + (OriginalTerminalSplit.splitTape F2 repeats (.step i p) (.step chosen q) + (LeafDomain slots) (ω (.inl ()) v)).1 terminal := rfl + +@[simp] theorem splitTape_step_lowerCall (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n (m + 1)) (chosen : Fin (branch m)) (q : Path branch m k) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ω : WholeArraySampler.Tape rows repeats ((Path.step i p).append (.step chosen q)) slots) + (call : OriginalCutCalls.Index rows repeats p) : + (splitTape rows repeats (.step i p) chosen q slots ω).2.1 + (OriginalCutCalls.lowerCall rows repeats i p call) = + (splitTape rows repeats p chosen q (childSlots slots i) (ω (.inr (.inl ())))).2.1 call := rfl + +@[simp] theorem splitTape_step_below (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n (m + 1)) (chosen : Fin (branch m)) (q : Path branch m k) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ω : WholeArraySampler.Tape rows repeats ((Path.step i p).append (.step chosen q)) slots) : + (splitTape rows repeats (.step i p) chosen q slots ω).2.2 = + (splitTape rows repeats p chosen q (childSlots slots i) (ω (.inr (.inl ())))).2.2 := rfl + +def exteriorLaw (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + FiniteDistribution (Exterior rows repeats p slots) := FiniteDistribution.uniform _ + +def callsLaw (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (chosen : Fin (branch m)) (q : Path branch m k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + FiniteDistribution (Calls rows repeats p chosen q slots) := + FiniteProduct.law (fun _ : OriginalCutCalls.Index rows repeats p => + RecursiveSampler.tapeLaw F2 repeats (.step chosen q) (LeafDomain (cutSlots p slots))) + +def belowLaw (rows repeats : Nat → Nat) (chosen : Fin (branch m)) (q : Path branch m k) + (slots : Slots branch (m + 1) → Fin t → MixedSupport.Slot) : + FiniteDistribution (BelowTape rows repeats chosen q slots) := + (WholeArraySampler.tapeLaw rows repeats q (childSlots slots chosen)).product + (FiniteProduct.law (fun j : RecursiveSampler.OffPath chosen => + FiniteDistribution.uniform (Arrays (childSlots slots j.val) rows))) + +theorem callsLaw_uniform (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (chosen : Fin (branch m)) (q : Path branch m k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + callsLaw rows repeats p chosen q slots = + FiniteDistribution.uniform (Calls rows repeats p chosen q slots) := by + simp only [callsLaw, RecursiveSampler.tapeLaw_eq_uniform, UniformLinearImage.law_uniform] + +theorem belowLaw_uniform (rows repeats : Nat → Nat) (chosen : Fin (branch m)) + (q : Path branch m k) (slots : Slots branch (m + 1) → Fin t → MixedSupport.Slot) : + belowLaw rows repeats chosen q slots = + FiniteDistribution.uniform (BelowTape rows repeats chosen q slots) := by + rw [belowLaw, WholeArraySubtreeSplit.tapeLaw_eq_uniform, UniformLinearImage.law_uniform] + apply FiniteDistribution.eq_of_weight_eq + intro x + simp only [FiniteDistribution.product, FiniteDistribution.uniform, + Fintype.card_prod, Nat.cast_mul, one_div_mul_one_div] + +theorem split_tapeLaw (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (chosen : Fin (branch m)) (q : Path branch m k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + (WholeArraySampler.tapeLaw rows repeats (p.append (.step chosen q)) slots).pushforward + (splitTape rows repeats p chosen q slots) = + (exteriorLaw rows repeats p slots).product + ((callsLaw rows repeats p chosen q slots).product + (belowLaw rows repeats chosen q (cutSlots p slots))) := by + rw [WholeArraySubtreeSplit.tapeLaw_eq_uniform, FiniteDistribution.pushforward_equiv, + callsLaw_uniform, belowLaw_uniform] + unfold exteriorLaw + apply FiniteDistribution.eq_of_weight_eq + intro x + change 1 / (Fintype.card + (WholeArraySampler.Tape rows repeats (p.append (.step chosen q)) slots) : ℝ) = + (1 / (Fintype.card (Exterior rows repeats p slots) : ℝ)) * + ((1 / (Fintype.card (Calls rows repeats p chosen q slots) : ℝ)) * + (1 / (Fintype.card (BelowTape rows repeats chosen q (cutSlots p slots)) : ℝ))) + rw [Fintype.card_congr (splitTape rows repeats p chosen q slots), + Fintype.card_prod, Fintype.card_prod] + simp only [Nat.cast_mul, one_div, mul_inv] + +end + +end PerfectCompleteness.OriginalWholeCutTape + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/OutputOrder.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/OutputOrder.lean new file mode 100644 index 0000000000000000000000000000000000000000..270b5f8cfdf91cd8934ab2f58b9ea019c35c3526 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/OutputOrder.lean @@ -0,0 +1,86 @@ +import Mathlib.Data.List.OfFn +import OAI.Computability.PerfectCompleteness.Machines.TransitionTemplate + +namespace OAI + +section + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.OutputOrder + +open StatementCircuit + +variable {K : Type} {Γ : K → Type} {Λ σ : Type} + +private theorem unindex_label (indexing : ConfigIndex.Indexing Γ Λ σ) (S : Nat) + (label : Fin indexing.labelCount) (j : Fin (indexing.width S)) + (hj : j.val = label.val) : + (indexing.configIndexEquiv S).symm j = + (Sum.inl (indexing.labels.symm label) : ConfigBit Γ Λ σ S) := by + apply (indexing.configIndexEquiv S).injective + rw [Equiv.apply_symm_apply] + apply Fin.ext + simpa only [ConfigIndex.Indexing.configIndex_label, Equiv.apply_symm_apply] using hj + +private theorem unindex_state (indexing : ConfigIndex.Indexing Γ Λ σ) (S : Nat) + (state : Fin indexing.stateCount) (j : Fin (indexing.width S)) + (hj : j.val = indexing.labelCount + state.val) : + (indexing.configIndexEquiv S).symm j = + (Sum.inr (Sum.inl (indexing.states.symm state)) : ConfigBit Γ Λ σ S) := by + apply (indexing.configIndexEquiv S).injective + rw [Equiv.apply_symm_apply] + apply Fin.ext + simpa only [ConfigIndex.Indexing.configIndex_state, Equiv.apply_symm_apply] using hj + +private theorem unindex_cell (indexing : ConfigIndex.Indexing Γ Λ σ) (S : Nat) + (cursor : Fin S) (symbol : Fin indexing.symbolCount) (j : Fin (indexing.width S)) + (hj : j.val = indexing.labelCount + indexing.stateCount + + cursor.val * indexing.symbolCount + symbol.val) : + (indexing.configIndexEquiv S).symm j = + (let a := indexing.symbols.symm symbol + Sum.inr (Sum.inr ⟨a.1, cursor, a.2⟩) : ConfigBit Γ Λ σ S) := by + dsimp only + apply (indexing.configIndexEquiv S).injective + rw [Equiv.apply_symm_apply] + apply Fin.ext + rw [ConfigIndex.Indexing.configIndex_cell] + simpa only [Sigma.eta, Equiv.apply_symm_apply] using hj + +theorem outputOrder_eq_blocks (indexing : ConfigIndex.Indexing Γ Λ σ) (S : Nat) : + TransitionTemplate.outputOrder indexing S = + ((List.finRange indexing.labelCount).map fun i => + (Sum.inl (indexing.labels.symm i) : ConfigBit Γ Λ σ S)) ++ + ((List.finRange indexing.stateCount).map fun i => + (Sum.inr (Sum.inl (indexing.states.symm i)) : ConfigBit Γ Λ σ S)) ++ + ((List.finRange S).flatMap fun cursor => + (List.finRange indexing.symbolCount).map fun j => + let a := indexing.symbols.symm j + (Sum.inr (Sum.inr ⟨a.1, cursor, a.2⟩) : ConfigBit Γ Λ σ S)) := by + simp only [TransitionTemplate.outputOrder, List.flatMap_def, ← List.ofFn_eq_map] + change List.ofFn (fun j : Fin (indexing.labelCount + indexing.stateCount + + S * indexing.symbolCount) => (indexing.configIndexEquiv S).symm j) = _ + rw [List.ofFn_add (n := indexing.labelCount + indexing.stateCount) + (m := S * indexing.symbolCount)] + rw [List.ofFn_add (n := indexing.labelCount) (m := indexing.stateCount)] + rw [List.ofFn_mul (m := S) (n := indexing.symbolCount)] + congr 1 + · congr 1 + · apply congrArg List.ofFn + funext i + exact unindex_label indexing S i _ rfl + · apply congrArg List.ofFn + funext i + exact unindex_state indexing S i _ rfl + · apply congrArg List.flatten + apply congrArg List.ofFn + funext cursor + apply congrArg List.ofFn + funext symbol + apply unindex_cell indexing S cursor symbol + simp only [Fin.val_natAdd] + omega + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.OutputOrder + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/OwnInputAffineSliceLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/OwnInputAffineSliceLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..fa897bad80aaef81a8535e3900de64720570cb0d --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/OwnInputAffineSliceLemmas.lean @@ -0,0 +1,431 @@ +import OAI.Computability.PerfectCompleteness.Algebra.TensorAffineHeavyWitness +import OAI.Computability.PerfectCompleteness.Algebra.TensorBucketEvaluationLemmas +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalPrediction +import OAI.Computability.PerfectCompleteness.Machines.OwnInputReferenceLemmas + +namespace OAI + + +namespace PerfectCompleteness.OwnInputAffineSlice + +noncomputable section + +open scoped BigOperators TensorProduct Classical +open UniqueGamesTheorem.Foundations.Games +open TreeSourceSpaces HierarchicalArrays OwnInputReference + +abbrev F2 := ZMod 2 + +section FiniteLaws + +variable {A B T : Type*} [Fintype A] [Fintype B] [Fintype T] + +theorem probability_product_and (μ : FiniteDistribution A) (ν : FiniteDistribution B) + (hidden : A → Bool) (visible : B → Bool) : + (μ.product ν).probability (fun x => hidden x.1 && visible x.2) = + μ.probability hidden * ν.probability visible := by + simp only [FiniteDistribution.probability, FiniteDistribution.product, + Fintype.sum_prod_type] + rw [Finset.sum_mul] + simp only [Finset.mul_sum] + apply Finset.sum_congr rfl + intro h _ + apply Finset.sum_congr rfl + intro v _ + cases hidden h <;> cases visible v <;> simp + +theorem product_slice_positive (μ : FiniteDistribution A) (ν : FiniteDistribution B) + (g : A → T) (slice : T → Bool) (visible : B → Bool) + (positive : 0 < (μ.product ν).probability + (fun x => slice (g x.1) && visible x.2)) : + 0 < (μ.pushforward g).probability slice := by + rw [FiniteDistribution.probability_pushforward] + by_contra hn + have hz : μ.probability (fun h => slice (g h)) = 0 := + le_antisymm (le_of_not_gt hn) (μ.probability_nonnegative _) + have hp := positive + rw [probability_product_and μ ν (fun h : A => slice (g h)) visible, hz, zero_mul] at hp + exact (lt_irrefl 0) hp + +theorem condition_product_hidden (μ : FiniteDistribution A) (ν : FiniteDistribution B) + (g : A → T) (slice : T → Bool) (visible : B → Bool) + (positive : 0 < (μ.product ν).probability + (fun x => slice (g x.1) && visible x.2)) : + ((μ.product ν).condition (fun x => slice (g x.1) && visible x.2) positive).pushforward + (fun x => g x.1) = + (μ.pushforward g).condition slice (product_slice_positive μ ν g slice visible positive) := by + have hv : ν.probability visible ≠ 0 := by + intro hv + have hp := positive + rw [probability_product_and μ ν (fun h : A => slice (g h)) visible, hv, mul_zero] at hp + exact (lt_irrefl 0) hp + apply FiniteDistribution.eq_of_weight_eq + intro t + rw [FiniteDistribution.weight_eq_probability_singleton, + FiniteDistribution.weight_eq_probability_singleton] + simp only [FiniteDistribution.probability_pushforward, + FiniteDistribution.probability_condition] + have hevent : + (fun x : A × B => (slice (g x.1) && visible x.2) && decide (g x.1 = t)) = + (fun x : A × B => (slice (g x.1) && decide (g x.1 = t)) && visible x.2) := by + funext x + cases hs : slice (g x.1) <;> cases he : visible x.2 <;> + cases ht : decide (g x.1 = t) <;> rfl + rw [hevent, + probability_product_and μ ν (fun h : A => slice (g h) && decide (g h = t)) visible, + probability_product_and μ ν (fun h : A => slice (g h)) visible] + exact mul_div_mul_right _ _ hv + +theorem probability_condition_congr (μ : FiniteDistribution A) + (given event event' : A → Bool) (positive : 0 < μ.probability given) + (agree : ∀ x, given x = true → event x = event' x) : + (μ.condition given positive).probability event = + (μ.condition given positive).probability event' := by + rw [FiniteDistribution.probability_condition, FiniteDistribution.probability_condition] + congr 1 + congr 1 + funext x + by_cases hx : given x = true + · rw [agree x hx] + · simp [hx] + +end FiniteLaws + +section TensorMatch + +variable {ℓ : Nat} {H : Type*} [AddCommGroup H] [Module F2 H] + [Finite H] [FiniteDimensional F2 H] + +def tensorSlice (W : Submodule F2 (Fin ℓ → F2)) + (Q : Submodule F2 (Module.Dual F2 H)) (target : Q →ₗ[F2] W) + (X : W ⊗[F2] H) : Bool := + decide (TensorRestriction.restrictionMap Q X = target) + +theorem probability_condition_eq_conditionalMatch + (W : Submodule F2 (Fin ℓ → F2)) (μ : FiniteDistribution (W ⊗[F2] H)) + (G : (W ⊗[F2] H) → (Fin ℓ → F2)) + (Q : Submodule F2 (Module.Dual F2 H)) (target : Q →ₗ[F2] W) + (z : Module.Dual F2 H) (offset : Fin ℓ → F2) + (positive : 0 < μ.probability (tensorSlice W Q target)) : + (μ.condition (tensorSlice W Q target) positive).probability + (fun X => decide (G X = offset + TensorBucketEvaluation.tensorOutputLinear W z X)) = + TensorAffineHeavyWitness.conditionalMatch W μ G Q target z offset := by + rw [FiniteDistribution.probability_condition] + unfold TensorAffineHeavyWitness.conditionalMatch AffineLinearHeavyWitness.conditionalMatch + congr 1 + · unfold FiniteDistribution.probability FiniteDistribution.expectation + apply Finset.sum_congr rfl + intro X _ + by_cases hslice : TensorRestriction.restrictionMap Q X = target <;> + by_cases hmatch : G X = offset + TensorBucketEvaluation.tensorOutputLinear W z X <;> + simp [tensorSlice, hslice, hmatch] + · simp only [FiniteDistribution.probability, FiniteDistribution.expectation, + tensorSlice, decide_eq_true_eq, mul_ite, mul_one, mul_zero] + +end TensorMatch + +variable {branch : Nat → Nat} {n t : Nat} + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (rows : Nat → Nat) (upper lower : Nodes branch n) + (W : Submodule F2 (UpperVector rows upper)) + +abbrev VisibleSample (repeats : Nat → Nat) (cut : Cut upper lower) := + HiddenBucketBias.VisibleTape W (ScalarSample slots upper lower repeats cut) × + Exterior slots rows upper lower + +def visibleLaw (repeats : Nat → Nat) (cut : Cut upper lower) + (externalLaw : FiniteDistribution (Exterior slots rows upper lower)) : + FiniteDistribution (VisibleSample slots rows upper lower W repeats cut) := + (HiddenBucketBias.visibleTapeLaw W + (RecursiveSampler.tapeLaw F2 repeats cut.path (LeafDomain (nodeSlots slots upper)))).product + externalLaw + +def hiddenOutput (repeats : Nat → Nat) (cut : Cut upper lower) + (sample : RawSample slots rows upper lower W repeats cut) : + W ⊗[F2] UpperSpace slots upper := + HiddenBucketBias.hiddenSum W + (RecursiveSampler.evaluate F2 repeats cut.path (LeafDomain (nodeSlots slots upper))) sample.1 + +def jointEvent (repeats : Nat → Nat) (cut : Cut upper lower) + (visible : VisibleSample slots rows upper lower W repeats cut → Bool) + (Q : Submodule F2 (Module.Dual F2 (UpperSpace slots upper))) (target : Q →ₗ[F2] W) + (sample : RawSample slots rows upper lower W repeats cut) : Bool := + tensorSlice W Q target (hiddenOutput slots rows upper lower W repeats cut sample) && + visible sample.2 + +theorem joint_probability (repeats : Nat → Nat) (cut : Cut upper lower) + (externalLaw : FiniteDistribution (Exterior slots rows upper lower)) + (visible : VisibleSample slots rows upper lower W repeats cut → Bool) + (Q : Submodule F2 (Module.Dual F2 (UpperSpace slots upper))) (target : Q →ₗ[F2] W) : + (rawLaw slots rows upper lower W repeats cut externalLaw).probability + (jointEvent slots rows upper lower W repeats cut visible Q target) = + (referenceLaw slots rows upper lower W repeats cut).probability (tensorSlice W Q target) * + (visibleLaw slots rows upper lower W repeats cut externalLaw).probability visible := by + exact (probability_product_and + (HiddenBucketBias.hiddenTapeLaw W + (RecursiveSampler.tapeLaw F2 repeats cut.path (LeafDomain (nodeSlots slots upper)))) + (visibleLaw slots rows upper lower W repeats cut externalLaw) + (fun h => tensorSlice W Q target (HiddenBucketBias.hiddenSum W + (RecursiveSampler.evaluate F2 repeats cut.path (LeafDomain (nodeSlots slots upper))) h)) + visible).trans (by rw [referenceLaw, HiddenBucketBias.recursiveLaw, + HiddenBucketBias.law, FiniteDistribution.probability_pushforward]) + +theorem slice_probability_pos (repeats : Nat → Nat) (cut : Cut upper lower) + (externalLaw : FiniteDistribution (Exterior slots rows upper lower)) + (visible : VisibleSample slots rows upper lower W repeats cut → Bool) + (Q : Submodule F2 (Module.Dual F2 (UpperSpace slots upper))) (target : Q →ₗ[F2] W) + (positive : 0 < (rawLaw slots rows upper lower W repeats cut externalLaw).probability + (jointEvent slots rows upper lower W repeats cut visible Q target)) : + 0 < (referenceLaw slots rows upper lower W repeats cut).probability (tensorSlice W Q target) := by + exact product_slice_positive + (HiddenBucketBias.hiddenTapeLaw W + (RecursiveSampler.tapeLaw F2 repeats cut.path (LeafDomain (nodeSlots slots upper)))) + (visibleLaw slots rows upper lower W repeats cut externalLaw) + (HiddenBucketBias.hiddenSum W + (RecursiveSampler.evaluate F2 repeats cut.path (LeafDomain (nodeSlots slots upper)))) + (tensorSlice W Q target) visible positive + +theorem conditional_referenceLaw (repeats : Nat → Nat) (cut : Cut upper lower) + (externalLaw : FiniteDistribution (Exterior slots rows upper lower)) + (visible : VisibleSample slots rows upper lower W repeats cut → Bool) + (Q : Submodule F2 (Module.Dual F2 (UpperSpace slots upper))) (target : Q →ₗ[F2] W) + (positive : 0 < (rawLaw slots rows upper lower W repeats cut externalLaw).probability + (jointEvent slots rows upper lower W repeats cut visible Q target)) : + ((rawLaw slots rows upper lower W repeats cut externalLaw).condition + (jointEvent slots rows upper lower W repeats cut visible Q target) positive).pushforward + (hiddenOutput slots rows upper lower W repeats cut) = + (referenceLaw slots rows upper lower W repeats cut).condition (tensorSlice W Q target) + (slice_probability_pos slots rows upper lower W repeats cut externalLaw + visible Q target positive) := by + exact condition_product_hidden + (HiddenBucketBias.hiddenTapeLaw W + (RecursiveSampler.tapeLaw F2 repeats cut.path (LeafDomain (nodeSlots slots upper)))) + (visibleLaw slots rows upper lower W repeats cut externalLaw) + (HiddenBucketBias.hiddenSum W + (RecursiveSampler.evaluate F2 repeats cut.path (LeafDomain (nodeSlots slots upper)))) + (tensorSlice W Q target) visible positive + +theorem conditional_observed_response_probability + (a : LowerVector rows lower) (repeats : Nat → Nat) (cut : Cut upper lower) + (externalLaw : FiniteDistribution (Exterior slots rows upper lower)) + (visible : VisibleSample slots rows upper lower W repeats cut → Bool) + (Q : Submodule F2 (Module.Dual F2 (UpperSpace slots upper))) (target : Q →ₗ[F2] W) + (positive : 0 < (rawLaw slots rows upper lower W repeats cut externalLaw).probability + (jointEvent slots rows upper lower W repeats cut visible Q target)) + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (observed : Input slots rows upper lower W a) + (z : Module.Dual F2 (UpperSpace slots upper)) (offset : UpperVector rows upper) : + ((rawLaw slots rows upper lower W repeats cut externalLaw).condition + (jointEvent slots rows upper lower W repeats cut visible Q target) positive).probability + (fun x => decide (response slots rows upper lower W a labeling observed + (hiddenOutput slots rows upper lower W repeats cut x) = + offset + TensorBucketEvaluation.tensorOutputLinear W z + (hiddenOutput slots rows upper lower W repeats cut x))) = + TensorAffineHeavyWitness.conditionalMatch W + (referenceLaw slots rows upper lower W repeats cut) + (response slots rows upper lower W a labeling observed) Q target z offset := by + have h := congrArg (fun μ : FiniteDistribution (W ⊗[F2] UpperSpace slots upper) => + μ.probability (fun X => decide (response slots rows upper lower W a labeling observed X = + offset + TensorBucketEvaluation.tensorOutputLinear W z X))) + (conditional_referenceLaw slots rows upper lower W repeats cut externalLaw + visible Q target positive) + rw [FiniteDistribution.probability_pushforward] at h + exact h.trans (probability_condition_eq_conditionalMatch W + (referenceLaw slots rows upper lower W repeats cut) + (response slots rows upper lower W a labeling observed) Q target z offset + (slice_probability_pos slots rows upper lower W repeats cut externalLaw visible Q target positive)) + +theorem conditional_response_probability + (a : LowerVector rows lower) (repeats : Nat → Nat) (cut : Cut upper lower) + (externalLaw : FiniteDistribution (Exterior slots rows upper lower)) + (visible : VisibleSample slots rows upper lower W repeats cut → Bool) + (Q : Submodule F2 (Module.Dual F2 (UpperSpace slots upper))) (target : Q →ₗ[F2] W) + (positive : 0 < (rawLaw slots rows upper lower W repeats cut externalLaw).probability + (jointEvent slots rows upper lower W repeats cut visible Q target)) + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (observed : Input slots rows upper lower W a) + (fixes_input : ∀ data, visible data = true → + readInput slots rows upper lower W a + (RecursiveSampler.evaluate F2 repeats cut.path (LeafDomain (nodeSlots slots upper))) + data = observed) + (z : Module.Dual F2 (UpperSpace slots upper)) (offset : UpperVector rows upper) : + ((rawLaw slots rows upper lower W repeats cut externalLaw).condition + (jointEvent slots rows upper lower W repeats cut visible Q target) positive).probability + (fun x => decide (response slots rows upper lower W a labeling + (readInput slots rows upper lower W a + (RecursiveSampler.evaluate F2 repeats cut.path (LeafDomain (nodeSlots slots upper))) x.2) + (hiddenOutput slots rows upper lower W repeats cut x) = + offset + TensorBucketEvaluation.tensorOutputLinear W z + (hiddenOutput slots rows upper lower W repeats cut x))) = + TensorAffineHeavyWitness.conditionalMatch W + (referenceLaw slots rows upper lower W repeats cut) + (response slots rows upper lower W a labeling observed) Q target z offset := by + trans ((rawLaw slots rows upper lower W repeats cut externalLaw).condition + (jointEvent slots rows upper lower W repeats cut visible Q target) positive).probability + (fun x => decide (response slots rows upper lower W a labeling observed + (hiddenOutput slots rows upper lower W repeats cut x) = + offset + TensorBucketEvaluation.tensorOutputLinear W z + (hiddenOutput slots rows upper lower W repeats cut x))) + · apply probability_condition_congr + intro x hx + have hv : visible x.2 = true := (Bool.and_eq_true_iff.mp hx).2 + rw [fixes_input x.2 hv] + · exact conditional_observed_response_probability slots rows upper lower W a repeats cut + externalLaw visible Q target positive labeling observed z offset + +end +end PerfectCompleteness.OwnInputAffineSlice + + +namespace PerfectCompleteness.OwnInputRawAssembly + +noncomputable section + +open scoped Classical TensorProduct +open TreeSourceSpaces HierarchicalArrays +open OwnInputReference (RawSample ScalarSample UpperSpace UpperVector Cut) + +variable {branch : Nat → Nat} {n t : Nat} + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (rows : Nat → Nat) (upper lower : Nodes branch n) + +theorem backgroundOf_assemble + (upperRows : Fin (rows (Nodes.height upper)) → H (nodeSlots slots upper)) + (external : OwnInputReference.Exterior slots rows upper lower) : + HierarchicalMatrixTable.backgroundOf slots upper + (OwnInputCanonicalQuery.assemble slots rows upper lower upperRows external) = + HierarchicalMatrixTable.backgroundOf slots upper + (OwnInputCanonicalQuery.assemble slots rows upper lower 0 external) := by + funext node + simp only [HierarchicalMatrixTable.backgroundOf, OwnInputCanonicalQuery.assemble, + dite_eq_right node.property] + +def exteriorBackground (external : OwnInputReference.Exterior slots rows upper lower) : + HierarchicalMatrixTable.Background (rows := rows) slots upper := + HierarchicalMatrixTable.backgroundOf slots upper + (OwnInputCanonicalQuery.assemble slots rows upper lower 0 external) + +variable (W : Submodule F2 (UpperVector rows upper)) + (repeats : Nat → Nat) (cut : Cut upper lower) + +def scalarEval : ScalarSample slots upper lower repeats cut → UpperSpace slots upper := + RecursiveSampler.evaluate F2 repeats cut.path (LeafDomain (nodeSlots slots upper)) + +def mergedTape (sample : RawSample slots rows upper lower W repeats cut) : + BucketSampler.Tape (rows (Nodes.height upper)) (ScalarSample slots upper lower repeats cut) := + (HiddenBucketBias.splitTape W (ScalarSample slots upper lower repeats cut)).symm + (sample.1, sample.2.1) + +theorem split_mergedTape (sample : RawSample slots rows upper lower W repeats cut) : + HiddenBucketBias.splitTape W (ScalarSample slots upper lower repeats cut) + (mergedTape slots rows upper lower W repeats cut sample) = (sample.1, sample.2.1) := + (HiddenBucketBias.splitTape W (ScalarSample slots upper lower repeats cut)).apply_symm_apply _ + +def arrays (sample : RawSample slots rows upper lower W repeats cut) : Arrays slots rows := + OwnInputCanonicalQuery.assemble slots rows upper lower + (BucketSampler.evaluate (rows (Nodes.height upper)) (scalarEval slots upper lower repeats cut) + (mergedTape slots rows upper lower W repeats cut sample)) sample.2.2 + +def background (visible : OwnInputAffineSlice.VisibleSample slots rows upper lower W repeats cut) : + HierarchicalMatrixTable.Background (rows := rows) slots upper := + exteriorBackground slots rows upper lower visible.2 + +def knownVisible (visible : OwnInputAffineSlice.VisibleSample slots rows upper lower W repeats cut) : + HiddenBucketBias.VisibleDirection W → UpperSpace slots upper := + fun v => scalarEval slots upper lower repeats cut (visible.1 v) + +theorem readInput_knownBuckets (a : Block rows lower) + (visible : OwnInputAffineSlice.VisibleSample slots rows upper lower W repeats cut) : + (OwnInputReference.readInput slots rows upper lower W a + (scalarEval slots upper lower repeats cut) visible).knownBuckets = + knownVisible slots rows upper lower W repeats cut visible := rfl + +theorem arrays_upper (sample : RawSample slots rows upper lower W repeats cut) : + arrays slots rows upper lower W repeats cut sample upper = + BucketSampler.evaluate (rows (Nodes.height upper)) (scalarEval slots upper lower repeats cut) + (mergedTape slots rows upper lower W repeats cut sample) := + OwnInputCanonicalQuery.assemble_upper slots rows upper lower _ _ + +theorem background_arrays (sample : RawSample slots rows upper lower W repeats cut) : + HierarchicalMatrixTable.backgroundOf slots upper + (arrays slots rows upper lower W repeats cut sample) = + background slots rows upper lower W repeats cut sample.2 := + backgroundOf_assemble slots rows upper lower _ sample.2.2 + +theorem arrays_eq_matrix_assemble (sample : RawSample slots rows upper lower W repeats cut) : + arrays slots rows upper lower W repeats cut sample = + HierarchicalMatrixTable.assemble slots upper + (background slots rows upper lower W repeats cut sample.2) + (NodeEmbedding.matrix (arrays slots rows upper lower W repeats cut sample) upper) := by + have h := HierarchicalMatrixTable.assemble_original slots upper + (arrays slots rows upper lower W repeats cut sample) + rw [background_arrays] at h + exact h.symm + +theorem matrix_arrays (sample : RawSample slots rows upper lower W repeats cut) : + NodeEmbedding.matrix (arrays slots rows upper lower W repeats cut sample) upper = + TensorProjectedSlice.totalMatrix (NodeEmbedding.embed slots upper) W + (HierarchicalTensorMatrix.visibleMatrix slots upper W + (knownVisible slots rows upper lower W repeats cut sample.2)) + (OwnInputAffineSlice.hiddenOutput slots rows upper lower W repeats cut sample) := by + have h := HierarchicalTensorMatrix.matrix_eq_totalMatrix slots upper W + (scalarEval slots upper lower repeats cut) + (mergedTape slots rows upper lower W repeats cut sample) + (arrays slots rows upper lower W repeats cut sample) + (arrays_upper slots rows upper lower W repeats cut sample).symm + rw [split_mergedTape] at h + exact h + +theorem response_eq_canonical (a : Block rows lower) + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (sample : RawSample slots rows upper lower W repeats cut) : + OwnInputReference.response slots rows upper lower W a labeling + (OwnInputReference.readInput slots rows upper lower W a + (scalarEval slots upper lower repeats cut) sample.2) + (OwnInputAffineSlice.hiddenOutput slots rows upper lower W repeats cut sample) = + (KeyStrategy.response labeling .right (TreeCanonical.numberedSlots slots) + (OwnInputCanonicalQuery.canonicalQuery slots rows lower a + (arrays slots rows upper lower W repeats cut sample))).2.1 + ⟨upper, cut.upper_ne_lower⟩ := by + have h := OwnInputCanonicalQuery.response_readInput_hidden_eq slots rows upper lower + cut.upper_ne_lower W a labeling (scalarEval slots upper lower repeats cut) + (mergedTape slots rows upper lower W repeats cut sample) sample.2.2 + rw [split_mergedTape] at h + exact h + +theorem response_eq_rightUpper (a : Block rows lower) + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (sample : RawSample slots rows upper lower W repeats cut) : + OwnInputReference.response slots rows upper lower W a labeling + (OwnInputReference.readInput slots rows upper lower W a + (scalarEval slots upper lower repeats cut) sample.2) + (OwnInputAffineSlice.hiddenOutput slots rows upper lower W repeats cut sample) = + HierarchicalPrediction.rightUpper slots upper + (background slots rows upper lower W repeats cut sample.2) + labeling lower cut.upper_ne_lower a + (NodeEmbedding.matrix (arrays slots rows upper lower W repeats cut sample) upper) := by + rw [← background_arrays slots rows upper lower W repeats cut sample, + HierarchicalPrediction.rightUpper, HierarchicalMatrixTable.displayed_original] + exact response_eq_canonical slots rows upper lower W repeats cut a labeling sample + +theorem response_eq_rightUpper_totalMatrix (a : Block rows lower) + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (sample : RawSample slots rows upper lower W repeats cut) : + OwnInputReference.response slots rows upper lower W a labeling + (OwnInputReference.readInput slots rows upper lower W a + (scalarEval slots upper lower repeats cut) sample.2) + (OwnInputAffineSlice.hiddenOutput slots rows upper lower W repeats cut sample) = + HierarchicalPrediction.rightUpper slots upper + (background slots rows upper lower W repeats cut sample.2) + labeling lower cut.upper_ne_lower a + (TensorProjectedSlice.totalMatrix (NodeEmbedding.embed slots upper) W + (HierarchicalTensorMatrix.visibleMatrix slots upper W + (knownVisible slots rows upper lower W repeats cut sample.2)) + (OwnInputAffineSlice.hiddenOutput slots rows upper lower W repeats cut sample)) := by + rw [← matrix_arrays slots rows upper lower W repeats cut sample] + exact response_eq_rightUpper slots rows upper lower W repeats cut a labeling sample + +end +end PerfectCompleteness.OwnInputRawAssembly + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/OwnInputHeavyBounds.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/OwnInputHeavyBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..7069b59019c91d22434358bfb244002c385d1b2b --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/OwnInputHeavyBounds.lean @@ -0,0 +1,133 @@ +import OAI.Computability.PerfectCompleteness.Foundations.RecursiveSpaceEquivLemmas +import OAI.Computability.PerfectCompleteness.Machines.OwnInputReferenceLemmas +import OAI.Computability.PerfectCompleteness.Sampling.UniformLatentSupportLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.OwnInputHeavyBounds + +open scoped TensorProduct Classical +open TreeSourceSpaces HierarchicalArrays OwnInputReference + +abbrev F2 := ZMod 2 + +noncomputable section + +theorem sign_sq (b : F2) : QuarterBalance.sign b ^ 2 = 1 := by + by_cases hb : b = 0 <;> simp [QuarterBalance.sign, hb] + +theorem frequency_add_ne_zero {V : Type*} [AddCommGroup V] [Module F2 V] + (Φ Ψ : Module.Dual F2 V) (hne : Φ ≠ Ψ) : Φ + Ψ ≠ 0 := by + intro hzero + apply hne + ext X + have hsum : Φ X + Ψ X = 0 := by + simpa only [LinearMap.add_apply, LinearMap.zero_apply] using + LinearMap.congr_fun hzero X + exact add_right_cancel (hsum.trans (CharTwo.add_self_eq_zero (Ψ X)).symm) + +theorem character_mul {V : Type*} [AddCommGroup V] [Module F2 V] + (Φ Ψ : Module.Dual F2 V) (X : V) : + QuarterBalance.sign (Φ X) * QuarterBalance.sign (Ψ X) = + QuarterBalance.sign ((Φ + Ψ) X) := + (QuarterBalance.sign_add (Φ X) (Ψ X)).symm + +variable {branch : Nat → Nat} {n t : Nat} + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (rows : Nat → Nat) (upper lower : Nodes branch n) + (W : Submodule F2 (UpperVector rows upper)) + +local instance upperSpaceFintype : Fintype (UpperSpace slots upper) := + Fintype.ofFinite _ + +theorem referenceLaw_sign_bias_le (repeats : Nat → Nat) (cut : Cut upper lower) + (bound : ℝ) + (scalar_bias : ∀ f : Module.Dual F2 (UpperSpace slots upper), f ≠ 0 → + |(RecursiveSampler.law F2 repeats cut.path (LeafDomain (nodeSlots slots upper))).expectation + (fun h => QuarterBalance.sign (f h))| ≤ bound) + (Φ : Module.Dual F2 (W ⊗[F2] UpperSpace slots upper)) (hΦ : Φ ≠ 0) : + |(referenceLaw slots rows upper lower W repeats cut).expectation + (fun X => QuarterBalance.sign (Φ X))| ≤ bound := + HiddenBucketBias.recursive_law_sign_bias_le W repeats cut.path + (LeafDomain (nodeSlots slots upper)) bound scalar_bias Φ hΦ + +theorem referenceLaw_pair_bias_le (repeats : Nat → Nat) (cut : Cut upper lower) + (bound : ℝ) + (scalar_bias : ∀ f : Module.Dual F2 (UpperSpace slots upper), f ≠ 0 → + |(RecursiveSampler.law F2 repeats cut.path (LeafDomain (nodeSlots slots upper))).expectation + (fun h => QuarterBalance.sign (f h))| ≤ bound) + (Φ Ψ : Module.Dual F2 (W ⊗[F2] UpperSpace slots upper)) (hne : Φ ≠ Ψ) : + |(referenceLaw slots rows upper lower W repeats cut).expectation + (fun X => QuarterBalance.sign (Φ X) * QuarterBalance.sign (Ψ X))| ≤ bound := by + simp_rw [← QuarterBalance.sign_add] + exact referenceLaw_sign_bias_le slots rows upper lower W repeats cut bound + scalar_bias (Φ + Ψ) + (frequency_add_ne_zero (V := W ⊗[F2] UpperSpace slots upper) Φ Ψ hne) + +theorem heavyList_card_le (a : LowerVector rows lower) + (repeats : Nat → Nat) (cut : Cut upper lower) + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (input : Input slots rows upper lower W a) + (σ : Module.Dual F2 (UpperVector rows upper)) (threshold bound : ℝ) + (hthreshold : 0 < threshold) (hbound : 0 ≤ bound) + (hsmall : bound ≤ threshold ^ 2 / 2) + (scalar_bias : ∀ f : Module.Dual F2 (UpperSpace slots upper), f ≠ 0 → + |(RecursiveSampler.law F2 repeats cut.path (LeafDomain (nodeSlots slots upper))).expectation + (fun h => QuarterBalance.sign (f h))| ≤ bound) : + ((heavyList slots rows upper lower W a repeats cut labeling input σ threshold).card : ℝ) ≤ + 2 / threshold ^ 2 := by + let μ : UniqueGamesTheorem.Foundations.Games.FiniteDistribution + (W ⊗[F2] UpperSpace slots upper) := + referenceLaw slots rows upper lower W repeats cut + let chars : Module.Dual F2 (W ⊗[F2] UpperSpace slots upper) → + (W ⊗[F2] UpperSpace slots upper) → ℝ := + fun Φ X => QuarterBalance.sign (Φ X) + let target : (W ⊗[F2] UpperSpace slots upper) → ℝ := + fun X => QuarterBalance.sign (σ (response slots rows upper lower W a labeling input X)) + have htarget : ∀ X, target X ^ 2 ≤ 1 := by + intro X + exact (sign_sq _).le + have hchars : ∀ Φ X, chars Φ X ^ 2 ≤ 1 := by + intro Φ X + exact (sign_sq _).le + have hpair : ∀ Φ Ψ : Module.Dual F2 (W ⊗[F2] UpperSpace slots upper), Φ ≠ Ψ → + |μ.expectation (fun X => chars Φ X * chars Ψ X)| ≤ bound := by + intro Φ Ψ hne + exact referenceLaw_pair_bias_le slots rows upper lower W repeats cut bound + scalar_bias Φ Ψ hne + exact SmallBias.heavySet_card_le + (Ω := W ⊗[F2] UpperSpace slots upper) + (I := Module.Dual F2 (W ⊗[F2] UpperSpace slots upper)) + μ chars target threshold bound hthreshold hbound hsmall htarget hchars hpair + +theorem heavyList_card_le_of_balanced (a : LowerVector rows lower) + (repeats : Nat → Nat) (cut : Cut upper lower) + (hrep : RecursiveSamplerBias.RepetitionsBalanced repeats) + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (input : Input slots rows upper lower W a) + (σ : Module.Dual F2 (UpperVector rows upper)) (threshold : ℝ) + (hthreshold : 0 < threshold) + (hsmall : (7 / 8 : ℝ) ^ repeats (Nodes.height upper) ≤ threshold ^ 2 / 2) : + ((heavyList slots rows upper lower W a repeats cut labeling input σ threshold).card : ℝ) ≤ + 2 / threshold ^ 2 := by + have scalar_bias : ∀ f : Module.Dual F2 (UpperSpace slots upper), f ≠ 0 → + |(RecursiveSampler.law F2 repeats cut.path (LeafDomain (nodeSlots slots upper))).expectation + (fun h => QuarterBalance.sign (f h))| ≤ + (7 / 8 : ℝ) ^ repeats (Nodes.height upper) := by + intro f hf + exact RecursiveSamplerBias.law_bias_le_height + (branch := branch) (n := Nodes.height upper) (m := Nodes.height lower) + repeats hrep cut.path (LeafDomain (nodeSlots slots upper)) f hf + exact heavyList_card_le slots rows upper lower W a repeats cut labeling input σ + threshold ((7 / 8 : ℝ) ^ repeats (Nodes.height upper)) hthreshold + (pow_nonneg (by norm_num) _) hsmall scalar_bias + +end + +end PerfectCompleteness.OwnInputHeavyBounds + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/OwnInputReferenceLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/OwnInputReferenceLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..33ab1d1e128348c82b52e4849bd0c914a8729287 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/OwnInputReferenceLemmas.lean @@ -0,0 +1,454 @@ +import OAI.Computability.PerfectCompleteness.Algebra.TensorBucketEvaluationLemmas +import OAI.Computability.PerfectCompleteness.Construction.HiddenBucketBias +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalArrays +import OAI.Computability.PerfectCompleteness.Foundations.QuotientTableAgreementLemmas +import OAI.Computability.PerfectCompleteness.Foundations.RecursiveSpaceEquivLemmas + +namespace OAI + + +namespace PerfectCompleteness.OwnInputReference + +open scoped BigOperators TensorProduct Classical +open UniqueGamesTheorem.Foundations.Games +open TreeSourceSpaces HierarchicalArrays + +abbrev F2 := ZMod 2 + +noncomputable section + +variable {branch : Nat → Nat} {n t : Nat} + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (rows : Nat → Nat) (upper lower : Nodes branch n) + +abbrev UpperSpace := H (nodeSlots slots upper) +abbrev UpperVector := Block rows upper +abbrev LowerVector := Block rows lower +abbrev OtherNodes := {node : Nodes branch n // node ≠ upper ∧ node ≠ lower} + +structure Cut where + proper : Nodes.height lower < Nodes.height upper + path : DescendantSpaces.Path branch (Nodes.height upper) (Nodes.height lower) + slots_agree : ∀ s, + (Nodes.path upper).slotEmbedding (path.slotEmbedding s) = + (Nodes.path lower).slotEmbedding s + +theorem Cut.upper_ne_lower (cut : Cut upper lower) : upper ≠ lower := by + intro h + have hlt := cut.proper + rw [h] at hlt + exact (Nat.lt_irrefl _) hlt + +theorem Cut.family_eq (cut : Cut upper lower) : + cut.path.family (LeafDomain (nodeSlots slots upper)) = LeafDomain (nodeSlots slots lower) := by + funext s + change ((k : Fin t) → + (slots ((Nodes.path upper).slotEmbedding (cut.path.slotEmbedding s)) k).Domain) = + ((k : Fin t) → (slots ((Nodes.path lower).slotEmbedding s) k).Domain) + rw [cut.slots_agree] + +abbrev OtherArrays := + (node : OtherNodes upper lower) → + Fin (rows (Nodes.height node.1)) → H (nodeSlots slots node.1) + +structure Exterior where + otherArrays : OtherArrays slots rows upper lower + lowerRows : Fin (rows (Nodes.height lower)) → H (nodeSlots slots lower) + +instance exteriorFinite : Finite (Exterior slots rows upper lower) := by + let f : Exterior slots rows upper lower → + OtherArrays slots rows upper lower × + (Fin (rows (Nodes.height lower)) → H (nodeSlots slots lower)) := + fun x => (x.otherArrays, x.lowerRows) + exact Finite.of_injective f (by intro x y h; cases x; cases y; cases h; rfl) + +instance exteriorFintype : Fintype (Exterior slots rows upper lower) := Fintype.ofFinite _ + +variable (W : Submodule F2 (UpperVector rows upper)) (a : LowerVector rows lower) + +structure Input where + knownBuckets : HiddenBucketBias.VisibleDirection W → UpperSpace slots upper + otherArrays : OtherArrays slots rows upper lower + lowerQuotient : Domain (nodeSlots slots lower) → DirectionQuotient.Space a + +def readInput {Ω : Type*} (eval : Ω → UpperSpace slots upper) + (data : HiddenBucketBias.VisibleTape W Ω × Exterior slots rows upper lower) : + Input slots rows upper lower W a where + knownBuckets v := eval (data.1 v) + otherArrays := data.2.otherArrays + lowerQuotient x := DirectionQuotient.proj a + (fun i => (data.2.lowerRows i).val x) + +abbrev SideOutput := DirectionQuotient.Space a × + ((node : OtherNodes upper lower) → Block rows node.1) + +def sideFunction (input : Input slots rows upper lower W a) : + Domain slots → SideOutput rows upper lower a := + fun x => + (input.lowerQuotient (restrictNode slots lower x), + fun node row => (input.otherArrays node row).val (restrictNode slots node.1 x)) + +def knownOutput (input : Input slots rows upper lower W a) + (x : Domain (nodeSlots slots upper)) : UpperVector rows upper := + ∑ v : HiddenBucketBias.VisibleDirection W, + (input.knownBuckets v).val x • v.val.val + +def query (input : Input slots rows upper lower W a) + (X : W ⊗[F2] UpperSpace slots upper) : + Domain slots → UpperVector rows upper × SideOutput rows upper lower a := + fun x => + (knownOutput slots rows upper lower W a input (restrictNode slots upper x) + + TensorBucketEvaluation.tensorOutput W + (EvaluationMatrix.evaluation (UpperSpace slots upper) (restrictNode slots upper x)) X, + sideFunction slots rows upper lower W a input x) + +def sampledQuery {Ω : Type*} (eval : Ω → UpperSpace slots upper) + (tape : BucketSampler.Tape (rows (Nodes.height upper)) Ω) + (external : Exterior slots rows upper lower) : + Domain slots → UpperVector rows upper × SideOutput rows upper lower a := + fun x => + ((fun i => (BucketSampler.evaluate (rows (Nodes.height upper)) eval tape i).val + (restrictNode slots upper x)), + (DirectionQuotient.proj a + (fun i => (external.lowerRows i).val (restrictNode slots lower x)), + fun node row => (external.otherArrays node row).val (restrictNode slots node.1 x))) + +theorem query_readInput_hidden {Ω : Type*} (eval : Ω → UpperSpace slots upper) + (tape : BucketSampler.Tape (rows (Nodes.height upper)) Ω) + (external : Exterior slots rows upper lower) : + query slots rows upper lower W a + (readInput slots rows upper lower W a eval + ((HiddenBucketBias.splitTape W Ω tape).2, external)) + (HiddenBucketBias.hiddenSum W eval (HiddenBucketBias.splitTape W Ω tape).1) = + sampledQuery slots rows upper lower a eval tape external := by + funext x + apply Prod.ext + · exact (TensorBucketEvaluation.evaluate_apply_split W (UpperSpace slots upper) + eval tape (restrictNode slots upper x)).symm + · rfl + +def response (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (input : Input slots rows upper lower W a) + (X : W ⊗[F2] UpperSpace slots upper) : UpperVector rows upper := + (KeyStrategy.response labeling .right (TreeCanonical.numberedSlots slots) + (TreeCanonical.numberedFunction slots (query slots rows upper lower W a input X))).1 + +theorem response_readInput_hidden {Ω : Type*} + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (eval : Ω → UpperSpace slots upper) + (tape : BucketSampler.Tape (rows (Nodes.height upper)) Ω) + (external : Exterior slots rows upper lower) : + response slots rows upper lower W a labeling + (readInput slots rows upper lower W a eval + ((HiddenBucketBias.splitTape W Ω tape).2, external)) + (HiddenBucketBias.hiddenSum W eval (HiddenBucketBias.splitTape W Ω tape).1) = + (KeyStrategy.response labeling .right (TreeCanonical.numberedSlots slots) + (TreeCanonical.numberedFunction slots + (sampledQuery slots rows upper lower a eval tape external))).1 := by + unfold response + rw [query_readInput_hidden] + +def referenceLaw (repeats : Nat → Nat) (cut : Cut upper lower) : + FiniteDistribution (W ⊗[F2] UpperSpace slots upper) := + HiddenBucketBias.recursiveLaw W repeats cut.path (LeafDomain (nodeSlots slots upper)) + +abbrev ScalarSample (repeats : Nat → Nat) (cut : Cut upper lower) := + RecursiveSampler.Tape F2 repeats cut.path (LeafDomain (nodeSlots slots upper)) + +instance scalarSampleFintype (repeats : Nat → Nat) (cut : Cut upper lower) : + Fintype (ScalarSample slots upper lower repeats cut) := by + change Fintype ((j : RecursiveSampler.DrawIndex repeats cut.path) → + RecursiveSampler.DrawSpace F2 repeats cut.path (LeafDomain (nodeSlots slots upper)) j) + infer_instance + +abbrev RawSample (repeats : Nat → Nat) (cut : Cut upper lower) := + HiddenBucketBias.HiddenTape W (ScalarSample slots upper lower repeats cut) × + (HiddenBucketBias.VisibleTape W (ScalarSample slots upper lower repeats cut) × + Exterior slots rows upper lower) + +instance rawSampleFintype (repeats : Nat → Nat) (cut : Cut upper lower) : + Fintype (RawSample slots rows upper lower W repeats cut) := by + change Fintype + ((HiddenBucketBias.HiddenDirection W → ScalarSample slots upper lower repeats cut) × + ((HiddenBucketBias.VisibleDirection W → ScalarSample slots upper lower repeats cut) × + Exterior slots rows upper lower)) + infer_instance + +def rawLaw (repeats : Nat → Nat) (cut : Cut upper lower) + (externalLaw : FiniteDistribution (Exterior slots rows upper lower)) : + FiniteDistribution (RawSample slots rows upper lower W repeats cut) := + HiddenBucketBias.exposedLaw W + (RecursiveSampler.tapeLaw F2 repeats cut.path (LeafDomain (nodeSlots slots upper))) externalLaw + +def inputEvent (repeats : Nat → Nat) (cut : Cut upper lower) + (observed : Input slots rows upper lower W a) : + RawSample slots rows upper lower W repeats cut → Bool := + fun x => decide (readInput slots rows upper lower W a + (RecursiveSampler.evaluate F2 repeats cut.path (LeafDomain (nodeSlots slots upper))) + x.2 = observed) + +theorem conditional_referenceLaw (repeats : Nat → Nat) (cut : Cut upper lower) + (externalLaw : FiniteDistribution (Exterior slots rows upper lower)) + (observed : Input slots rows upper lower W a) + (positive : 0 < (rawLaw slots rows upper lower W repeats cut externalLaw).probability + (inputEvent slots rows upper lower W a repeats cut observed)) : + ((rawLaw slots rows upper lower W repeats cut externalLaw).condition + (inputEvent slots rows upper lower W a repeats cut observed) positive).pushforward + (fun x => HiddenBucketBias.hiddenSum W + (RecursiveSampler.evaluate F2 repeats cut.path (LeafDomain (nodeSlots slots upper))) x.1) = + referenceLaw slots rows upper lower W repeats cut := by + exact HiddenBucketBias.law_condition_exterior W + (RecursiveSampler.tapeLaw F2 repeats cut.path (LeafDomain (nodeSlots slots upper))) + externalLaw + (RecursiveSampler.evaluate F2 repeats cut.path (LeafDomain (nodeSlots slots upper))) + (fun x => decide (readInput slots rows upper lower W a + (RecursiveSampler.evaluate F2 repeats cut.path (LeafDomain (nodeSlots slots upper))) x = observed)) + positive + +instance frequencyFintype : Fintype (Module.Dual F2 (W ⊗[F2] UpperSpace slots upper)) := + Fintype.ofInjective + (fun f : Module.Dual F2 (W ⊗[F2] UpperSpace slots upper) => + (f : (W ⊗[F2] UpperSpace slots upper) → F2)) DFunLike.coe_injective + +def heavyList (repeats : Nat → Nat) (cut : Cut upper lower) + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (input : Input slots rows upper lower W a) + (σ : Module.Dual F2 (UpperVector rows upper)) (threshold : ℝ) : + Finset (Module.Dual F2 (W ⊗[F2] UpperSpace slots upper)) := + SmallBias.heavySet (referenceLaw slots rows upper lower W repeats cut) + (fun Φ X => QuarterBalance.sign (Φ X)) + (fun X => QuarterBalance.sign (σ (response slots rows upper lower W a labeling input X))) + threshold + +theorem mem_heavyList (repeats : Nat → Nat) (cut : Cut upper lower) + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (input : Input slots rows upper lower W a) + (σ : Module.Dual F2 (UpperVector rows upper)) (threshold : ℝ) + (Φ : Module.Dual F2 (W ⊗[F2] UpperSpace slots upper)) : + Φ ∈ heavyList slots rows upper lower W a repeats cut labeling input σ threshold ↔ + threshold ≤ |(referenceLaw slots rows upper lower W repeats cut).expectation + (fun X => QuarterBalance.sign (σ (response slots rows upper lower W a labeling input X)) * + QuarterBalance.sign (Φ X))| := by + simp only [heavyList, SmallBias.heavySet, Finset.mem_filter, Finset.mem_univ, true_and] + +end +end PerfectCompleteness.OwnInputReference + + + +namespace PerfectCompleteness.OwnInputCanonicalQuery + +open scoped Classical +open TreeSourceSpaces HierarchicalArrays + +abbrev F2 := ZMod 2 + +noncomputable section + +variable {branch : Nat → Nat} {n t : Nat} + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (rows : Nat → Nat) (upper lower : Nodes branch n) + +abbrev CanonicalOutput (a : Block rows lower) := + DirectionQuotient.Space a × + (BlockQuotient.OtherBlocks (fun node : Nodes branch n => Block rows node) lower × PUnit.{1}) + +def reorder (hne : upper ≠ lower) (a : Block rows lower) : + CanonicalOutput rows lower a → + OwnInputReference.UpperVector rows upper × OwnInputReference.SideOutput rows upper lower a := + fun x => (x.2.1 ⟨upper, hne⟩, + (x.1, fun node => x.2.1 ⟨node.val, node.property.2⟩)) + +theorem reorder_injective (hne : upper ≠ lower) (a : Block rows lower) : + Function.Injective (reorder rows upper lower hne a) := by + intro x y h + apply Prod.ext + · exact congrArg (fun z => z.2.1) h + · apply Prod.ext + · funext node + rcases node with ⟨node, hn⟩ + by_cases hu : node = upper + · subst node + exact congrArg Prod.fst h + · exact congrFun (congrArg (fun z => z.2.2) h) ⟨node, hu, hn⟩ + · exact Subsingleton.elim _ _ + +def unreorder (a : Block rows lower) : + OwnInputReference.UpperVector rows upper × OwnInputReference.SideOutput rows upper lower a → + CanonicalOutput rows lower a := + fun y => (y.2.1, + ((fun node => if h : node.val = upper then h.symm ▸ y.1 + else y.2.2 ⟨node.val, h, node.property⟩), PUnit.unit)) + +theorem reorder_unreorder (hne : upper ≠ lower) (a : Block rows lower) + (y : OwnInputReference.UpperVector rows upper × + OwnInputReference.SideOutput rows upper lower a) : + reorder rows upper lower hne a (unreorder rows upper lower a y) = y := by + apply Prod.ext + · simp [reorder, unreorder] + · apply Prod.ext + · rfl + · funext node + simp only [reorder, unreorder, dite_eq_right node.property.1] + +def outputEquiv (hne : upper ≠ lower) (a : Block rows lower) : + CanonicalOutput rows lower a ≃ + OwnInputReference.UpperVector rows upper × OwnInputReference.SideOutput rows upper lower a where + toFun := reorder rows upper lower hne a + invFun := unreorder rows upper lower a + left_inv _ := reorder_injective rows upper lower hne a (reorder_unreorder rows upper lower hne a _) + right_inv := reorder_unreorder rows upper lower hne a + +def exteriorOf (arrays : Arrays slots rows) : OwnInputReference.Exterior slots rows upper lower where + otherArrays node := arrays node.val + lowerRows := arrays lower + +def assemble (upperRows : Fin (rows (Nodes.height upper)) → H (nodeSlots slots upper)) + (external : OwnInputReference.Exterior slots rows upper lower) : Arrays slots rows := + fun node => if hu : node = upper then hu.symm ▸ upperRows + else if hl : node = lower then hl.symm ▸ external.lowerRows + else external.otherArrays ⟨node, hu, hl⟩ + +@[simp] theorem assemble_upper + (upperRows : Fin (rows (Nodes.height upper)) → H (nodeSlots slots upper)) + (external : OwnInputReference.Exterior slots rows upper lower) : + assemble slots rows upper lower upperRows external upper = upperRows := by + simp [assemble] + +@[simp] theorem assemble_lower (hne : upper ≠ lower) + (upperRows : Fin (rows (Nodes.height upper)) → H (nodeSlots slots upper)) + (external : OwnInputReference.Exterior slots rows upper lower) : + assemble slots rows upper lower upperRows external lower = external.lowerRows := by + simp [assemble, Ne.symm hne] + +@[simp] theorem assemble_other + (upperRows : Fin (rows (Nodes.height upper)) → H (nodeSlots slots upper)) + (external : OwnInputReference.Exterior slots rows upper lower) + (node : OwnInputReference.OtherNodes upper lower) : + assemble slots rows upper lower upperRows external node.val = external.otherArrays node := by + simp only [assemble, dite_eq_right node.property.1, dite_eq_right node.property.2] + +theorem assemble_original (arrays : Arrays slots rows) : + assemble slots rows upper lower (arrays upper) (exteriorOf slots rows upper lower arrays) = arrays := by + funext node + by_cases hu : node = upper + · subst node + exact assemble_upper slots rows upper lower _ _ + · by_cases hl : node = lower + · subst node + simp only [assemble, dite_eq_right hu, dite_eq_left rfl, exteriorOf] + · simp only [assemble, dite_eq_right hu, dite_eq_right hl, exteriorOf] + +def canonicalQuery (a : Block rows lower) (arrays : Arrays slots rows) := + BlockQuotient.projectBlock lower a ∘ TreeCanonical.numberedFunction slots (fullJoint arrays) + +theorem sampledQuery_eq_reorder (hne : upper ≠ lower) (a : Block rows lower) + {Ω : Type*} (eval : Ω → OwnInputReference.UpperSpace slots upper) + (tape : BucketSampler.Tape (rows (Nodes.height upper)) Ω) + (external : OwnInputReference.Exterior slots rows upper lower) : + OwnInputReference.sampledQuery slots rows upper lower a eval tape external = + reorder rows upper lower hne a ∘ BlockQuotient.projectBlock lower a ∘ + fullJoint (assemble slots rows upper lower + (BucketSampler.evaluate (rows (Nodes.height upper)) eval tape) external) := by + funext x + apply Prod.ext + · change (fun row => (BucketSampler.evaluate (rows (Nodes.height upper)) eval tape row).val + (restrictNode slots upper x)) = + fun row => ((assemble slots rows upper lower + (BucketSampler.evaluate (rows (Nodes.height upper)) eval tape) external) upper row).val + (restrictNode slots upper x) + rw [assemble_upper] + · apply Prod.ext + · change DirectionQuotient.proj a + (fun row => (external.lowerRows row).val (restrictNode slots lower x)) = + DirectionQuotient.proj a + (fun row => ((assemble slots rows upper lower + (BucketSampler.evaluate (rows (Nodes.height upper)) eval tape) external) lower row).val + (restrictNode slots lower x)) + rw [assemble_lower slots rows upper lower hne] + · funext node row + change (external.otherArrays node row).val (restrictNode slots node.val x) = + ((assemble slots rows upper lower + (BucketSampler.evaluate (rows (Nodes.height upper)) eval tape) external) node.val row).val + (restrictNode slots node.val x) + rw [assemble_other] + +theorem numbered_sampledQuery_eq (hne : upper ≠ lower) (a : Block rows lower) + {Ω : Type*} (eval : Ω → OwnInputReference.UpperSpace slots upper) + (tape : BucketSampler.Tape (rows (Nodes.height upper)) Ω) + (external : OwnInputReference.Exterior slots rows upper lower) : + TreeCanonical.numberedFunction slots + (OwnInputReference.sampledQuery slots rows upper lower a eval tape external) = + reorder rows upper lower hne a ∘ canonicalQuery slots rows lower a + (assemble slots rows upper lower + (BucketSampler.evaluate (rows (Nodes.height upper)) eval tape) external) := by + rw [sampledQuery_eq_reorder slots rows upper lower hne a eval tape external] + rfl + +theorem sampled_key_eq (hne : upper ≠ lower) (a : Block rows lower) + {Ω : Type*} (eval : Ω → OwnInputReference.UpperSpace slots upper) + (tape : BucketSampler.Tape (rows (Nodes.height upper)) Ω) + (external : OwnInputReference.Exterior slots rows upper lower) : + TreeCanonical.key .right slots + (OwnInputReference.sampledQuery slots rows upper lower a eval tape external) = + CanonicalKeys.key .right (TreeCanonical.numberedSlots slots) + (canonicalQuery slots rows lower a (assemble slots rows upper lower + (BucketSampler.evaluate (rows (Nodes.height upper)) eval tape) external)) := by + unfold TreeCanonical.key + rw [numbered_sampledQuery_eq slots rows upper lower hne a eval tape external] + exact CanonicalKeys.key_postcomp_injective .right (TreeCanonical.numberedSlots slots) _ + (reorder rows upper lower hne a) (reorder_injective rows upper lower hne a) + +theorem sampled_response_eq (hne : upper ≠ lower) (a : Block rows lower) + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + {Ω : Type*} (eval : Ω → OwnInputReference.UpperSpace slots upper) + (tape : BucketSampler.Tape (rows (Nodes.height upper)) Ω) + (external : OwnInputReference.Exterior slots rows upper lower) : + KeyStrategy.response labeling .right (TreeCanonical.numberedSlots slots) + (TreeCanonical.numberedFunction slots + (OwnInputReference.sampledQuery slots rows upper lower a eval tape external)) = + reorder rows upper lower hne a + (KeyStrategy.response labeling .right (TreeCanonical.numberedSlots slots) + (canonicalQuery slots rows lower a (assemble slots rows upper lower + (BucketSampler.evaluate (rows (Nodes.height upper)) eval tape) external))) := by + rw [numbered_sampledQuery_eq slots rows upper lower hne a eval tape external] + exact KeyStrategy.response_postcomp_injective labeling .right + (TreeCanonical.numberedSlots slots) _ (reorder rows upper lower hne a) + (reorder_injective rows upper lower hne a) + +theorem response_readInput_hidden_eq (hne : upper ≠ lower) + (W : Submodule F2 (OwnInputReference.UpperVector rows upper)) (a : Block rows lower) + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + {Ω : Type*} (eval : Ω → OwnInputReference.UpperSpace slots upper) + (tape : BucketSampler.Tape (rows (Nodes.height upper)) Ω) + (external : OwnInputReference.Exterior slots rows upper lower) : + OwnInputReference.response slots rows upper lower W a labeling + (OwnInputReference.readInput slots rows upper lower W a eval + ((HiddenBucketBias.splitTape W Ω tape).2, external)) + (HiddenBucketBias.hiddenSum W eval (HiddenBucketBias.splitTape W Ω tape).1) = + (KeyStrategy.response labeling .right (TreeCanonical.numberedSlots slots) + (canonicalQuery slots rows lower a (assemble slots rows upper lower + (BucketSampler.evaluate (rows (Nodes.height upper)) eval tape) external))).2.1 + ⟨upper, hne⟩ := by + rw [OwnInputReference.response_readInput_hidden] + exact congrArg Prod.fst (sampled_response_eq slots rows upper lower hne a labeling eval tape external) + +theorem response_readInput_hidden_arrays (hne : upper ≠ lower) + (W : Submodule F2 (OwnInputReference.UpperVector rows upper)) (a : Block rows lower) + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + {Ω : Type*} (eval : Ω → OwnInputReference.UpperSpace slots upper) + (tape : BucketSampler.Tape (rows (Nodes.height upper)) Ω) (arrays : Arrays slots rows) + (hupper : BucketSampler.evaluate (rows (Nodes.height upper)) eval tape = arrays upper) : + OwnInputReference.response slots rows upper lower W a labeling + (OwnInputReference.readInput slots rows upper lower W a eval + ((HiddenBucketBias.splitTape W Ω tape).2, exteriorOf slots rows upper lower arrays)) + (HiddenBucketBias.hiddenSum W eval (HiddenBucketBias.splitTape W Ω tape).1) = + (KeyStrategy.response labeling .right (TreeCanonical.numberedSlots slots) + (canonicalQuery slots rows lower a arrays)).2.1 ⟨upper, hne⟩ := by + rw [response_readInput_hidden_eq slots rows upper lower hne W a labeling eval tape] + rw [hupper, assemble_original] + +end +end PerfectCompleteness.OwnInputCanonicalQuery + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/PaddingCellsMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/PaddingCellsMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..f699a4bac6cb6b21cf3d1648b9b0c2a6479ee142 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/PaddingCellsMachine.lean @@ -0,0 +1,319 @@ +import OAI.Computability.PerfectCompleteness.Machines.InitializationControl +import OAI.Computability.PerfectCompleteness.Machines.InputCellsMachineLemmas +import OAI.Computability.PerfectCompleteness.Machines.OrClosure + +namespace OAI + + +noncomputable section +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.PaddingCellsMachine + + +open Turing PostfixModel InitializationTemplate VerifierCircuit WitnessEncoding + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev Ports (K : Type) := Fin 4 ↪ K + +def corePorts (p : Ports K) : OrClosure.Ports K where + remaining := p 3 + reversed := p 1 + count := p 2 + remaining_ne_reversed := fun h => by have := p.injective h; omega + remaining_ne_count := fun h => by have := p.injective h; omega + reversed_ne_count := fun h => by have := p.injective h; omega + +def literalPorts (p : Ports K) : InitializationControl.Ports K := + ⟨p 1, p 2, (corePorts p).reversed_ne_count⟩ + +abbrev frame (p : Ports K) (base : K → List Bool) + (remaining output count : List Bool) : K → List Bool := + OrClosure.frame (corePorts p) base remaining output count + +@[simp] theorem frame_remaining (p : Ports K) (base : K → List Bool) + (remaining output count : List Bool) : + frame p base remaining output count (p 3) = remaining := by + exact OrClosure.frame_remaining (corePorts p) base remaining output count + +@[simp] theorem frame_output (p : Ports K) (base : K → List Bool) + (remaining output count : List Bool) : + frame p base remaining output count (p 1) = output := by + exact OrClosure.frame_reversed (corePorts p) base remaining output count + +@[simp] theorem frame_count (p : Ports K) (base : K → List Bool) + (remaining output count : List Bool) : + frame p base remaining output count (p 2) = count := by + exact OrClosure.frame_count (corePorts p) base remaining output count + +theorem frame_other (p : Ports K) (base : K → List Bool) + (remaining output count : List Bool) (k : K) + (hr : k ≠ p 3) (ho : k ≠ p 1) (hc : k ≠ p 2) : + frame p base remaining output count k = base k := + OrClosure.frame_other (corePorts p) base remaining output count k hr ho hc + +@[simp] theorem frame_input (p : Ports K) (base : K → List Bool) + (remaining output count : List Bool) : + frame p base remaining output count (p 0) = base (p 0) := by + apply frame_other <;> intro h <;> have := p.injective h <;> omega + +@[simp] theorem update_remaining (p : Ports K) (base : K → List Bool) + (remaining output count replacement : List Bool) : + Function.update (frame p base remaining output count) (p 3) replacement = + frame p base replacement output count := + OrClosure.update_remaining (corePorts p) base remaining output count replacement + +@[simp] theorem literal_emitted (p : Ports K) (base : K → List Bool) + (remaining output count : List Bool) (row : List Token) : + InitializationControl.emitted (literalPorts p) + (frame p base remaining output count) row = + frame p base remaining ((tokenBits row).reverse ++ output) + (List.replicate row.length true ++ count) := by + simp only [InitializationControl.emitted, literalPorts, frame_output, frame_count] + exact (OrClosure.update_reversed (corePorts p) base remaining output count + ((tokenBits row).reverse ++ output)).symm ▸ + OrClosure.update_count (corePorts p) base remaining + ((tokenBits row).reverse ++ output) count (List.replicate row.length true ++ count) + +def repeatedRows (row : List Token) (n : Nat) : List Token := + (List.replicate n row).flatten + +@[simp] theorem repeatedRows_zero (row : List Token) : repeatedRows row 0 = [] := rfl + +@[simp] theorem repeatedRows_succ (row : List Token) (n : Nat) : + repeatedRows row (n + 1) = row ++ repeatedRows row n := by + simp [repeatedRows, List.replicate_succ] + +@[simp] theorem repeatedRows_length (row : List Token) (n : Nat) : + (repeatedRows row n).length = n * row.length := by + induction n with + | zero => simp + | succ n ih => simp [ih, Nat.succ_mul, Nat.add_comm] + +def statement (p : Ports K) (row : List Token) (again : Λ) (exit : Option Λ) : + TM2.Stmt (fun _ : K => Bool) Λ (σ × Option Bool) := + .pop (p 3) (fun state head => (state.1, head)) + (.branch (fun state => state.2.getD false) + (.load (fun state => (state.1, none)) + (InitializationControl.literalStatement (literalPorts p) row (some again))) + (.push (p 3) (fun _ => false) + (.load (fun state => (state.1, none)) + (InitializationControl.exitStatement exit)))) + +theorem step_zero (p : Ports K) (row : List Token) (again : Λ) (exit : Option Λ) + (base : K → List Bool) (suffix output count : List Bool) + (ambient : σ) (register : Option Bool) : + TM2.stepAux (statement p row again exit) (ambient, register) + (frame p base (encodeWord 0 ++ suffix) output count) = + ⟨exit, (ambient, none), frame p base (encodeWord 0 ++ suffix) output count⟩ := by + cases exit <;> + simp [statement, TM2.stepAux, encodeWord, InitializationControl.exitStatement] + +theorem step_succ (p : Ports K) (row : List Token) (again : Λ) (exit : Option Λ) + (base : K → List Bool) (n : Nat) (suffix output count : List Bool) + (ambient : σ) (register : Option Bool) : + TM2.stepAux (statement p row again exit) (ambient, register) + (frame p base (encodeWord (n + 1) ++ suffix) output count) = + ⟨some again, (ambient, none), frame p base (encodeWord n ++ suffix) + ((tokenBits row).reverse ++ output) (List.replicate row.length true ++ count)⟩ := by + simp [statement, TM2.stepAux, encodeWord, List.replicate_succ, + InitializationControl.literalStep] + +theorem trace (p : Ports K) (row : List Token) (again : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (σ × Option Bool)) + (code : program again = statement p row again exit) + (base : K → List Bool) (n : Nat) (suffix output count : List Bool) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[n + 1] + (some ⟨some again, (ambient, register), + frame p base (encodeWord n ++ suffix) output count⟩) = + some ⟨exit, (ambient, none), frame p base (encodeWord 0 ++ suffix) + ((tokenBits (repeatedRows row n)).reverse ++ output) + (List.replicate (n * row.length) true ++ count)⟩ := by + induction n generalizing output count register with + | zero => + change some (TM2.stepAux (program again) (ambient, register) + (frame p base (encodeWord 0 ++ suffix) output count)) = _ + rw [code, step_zero] + simp [tokenBits, tokenWords, encodeWords] + | succ n ih => + rw [Function.iterate_succ_apply] + change (MachineComposition.advance (TM2.step program))^[n + 1] + (some (TM2.stepAux (program again) (ambient, register) + (frame p base (encodeWord (n + 1) ++ suffix) output count))) = _ + rw [code, step_succ, ih] + simp only [repeatedRows_succ, OrClosure.tokenBits_append, List.reverse_append, + List.append_assoc] + have hc : List.replicate (n * row.length) true ++ + (List.replicate row.length true ++ count) = + List.replicate ((n + 1) * row.length) true ++ count := by + rw [← List.append_assoc, List.replicate_append_replicate, Nat.succ_mul] + rw [hc] + +theorem frame_eq_capacityTapes (p : Ports K) (base : K → List Bool) + (remaining : Nat) (input output count : List Bool) : + frame p (Function.update base (p 0) input) (encodeWord remaining) output count = + InputCellsCapacity.tapes p base remaining input output count := by + funext k + by_cases hk : ∃ j, p j = k + · obtain ⟨j, rfl⟩ := hk + fin_cases j <;> + simp [frame, OrClosure.frame, corePorts, p.injective.eq_iff] + · have hn : ∀ j, k ≠ p j := fun j h => hk ⟨j, h.symm⟩ + simp [frame, OrClosure.frame, corePorts, hn, + InputCellsCapacity.tapes_other p base remaining input output count k hn] + +theorem capacityTrace (p : Ports K) (row : List Token) (again : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (σ × Option Bool)) + (code : program again = statement p row again exit) + (base : K → List Bool) (n : Nat) (input output count : List Bool) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[n + 1] + (some ⟨some again, (ambient, register), + InputCellsCapacity.tapes p base n input output count⟩) = + some ⟨exit, (ambient, none), InputCellsCapacity.tapes p base 0 input + ((tokenBits (repeatedRows row n)).reverse ++ output) + (List.replicate (n * row.length) true ++ count)⟩ := by + simpa only [List.append_nil, frame_eq_capacityTapes] using + trace p row again exit program code (Function.update base (p 0) input) + n [] output count ambient register + +def inTime (p : Ports K) (row : List Token) (again : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (σ × Option Bool)) + (code : program again = statement p row again exit) + (base : K → List Bool) (n : Nat) (suffix output count : List Bool) + (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some again, (ambient, register), frame p base (encodeWord n ++ suffix) output count⟩ + (some ⟨exit, (ambient, none), frame p base (encodeWord 0 ++ suffix) + ((tokenBits (repeatedRows row n)).reverse ++ output) + (List.replicate (n * row.length) true ++ count)⟩) (n + 1) where + steps := n + 1 + evals_in_steps := by + change (MachineComposition.advance (TM2.step program))^[n + 1] _ = _ + exact trace p row again exit program code base n suffix output count ambient register + steps_le_m := Nat.le_refl _ + +section FixedVerifier + +local instance (V : NPVerifier) : DecidableEq V.computation.tm.Λ := Classical.decEq _ +local instance (V : NPVerifier) : DecidableEq V.computation.tm.σ := Classical.decEq _ +local instance (V : NPVerifier) : ∀ k, DecidableEq (V.computation.tm.Γ k) := + fun _ => Classical.decEq _ + +def blankRow (V : NPVerifier) : List Token := + (List.finRange (indexing V).symbolCount).map fun j => + let symbol := (indexing V).symbols.symm j + .const (decide ((none : Option (V.computation.tm.Γ symbol.1)) = symbol.2)) + +@[simp] theorem blankRow_length (V : NPVerifier) : + (blankRow V).length = (indexing V).symbolCount := by simp [blankRow] + +theorem initialCellTokens_padding (V : NPVerifier) (input : List Bool) (S : Nat) + (k : V.computation.tm.K) (i : Fin S) (a : Option (V.computation.tm.Γ k)) + (padding : (inputPrefix input).length + V.witnessBound.eval input.length ≤ i.val) : + initialCellTokens V input S k i a = [.const (decide ((none : Option _) = a))] := by + have hp : ¬ i.val < (inputPrefix input).length := by omega + have hq : ¬ i.val - (inputPrefix input).length < V.witnessBound.eval input.length := by omega + by_cases hk : k = V.computation.tm.k₀ + · subst k + simp only [initialCellTokens, inputCellTokens, ite_eq_right hp, ite_eq_right hq, dite_eq_ite, ite_self] + · simp [initialCellTokens, hk] + +theorem cellRow_padding (V : NPVerifier) (input : List Bool) (S : Nat) (i : Fin S) + (padding : (inputPrefix input).length + V.witnessBound.eval input.length ≤ i.val) : + ((List.finRange (indexing V).symbolCount).flatMap fun j => + let symbol := (indexing V).symbols.symm j + initialCellTokens V input S symbol.1 i symbol.2) = blankRow V := by + simp only [initialCellTokens_padding V input S _ i _ padding] + exact List.map_eq_flatMap.symm + +def cellsInterval (V : NPVerifier) (input : List Bool) (S start n : Nat) + (within : start + n ≤ S) : List Token := + (List.finRange n).flatMap fun i => + (List.finRange (indexing V).symbolCount).flatMap fun j => + let symbol := (indexing V).symbols.symm j + initialCellTokens V input S symbol.1 ⟨start + i.val, by omega⟩ symbol.2 + +theorem cellsInterval_padding (V : NPVerifier) (input : List Bool) (S start n : Nat) + (within : start + n ≤ S) + (padding : (inputPrefix input).length + V.witnessBound.eval input.length ≤ start) : + cellsInterval V input S start n within = repeatedRows (blankRow V) n := by + unfold cellsInterval + have hrow (i : Fin n) : + ((List.finRange (indexing V).symbolCount).flatMap fun j => + let symbol := (indexing V).symbols.symm j + initialCellTokens V input S symbol.1 ⟨start + i.val, by omega⟩ symbol.2) = + blankRow V := cellRow_padding V input S _ (by + change (inputPrefix input).length + V.witnessBound.eval input.length ≤ start + i.val + omega) + simp_rw [hrow] + simp [List.flatMap_def, repeatedRows] + +def verifierStatement (V : NPVerifier) (p : Ports K) (again : Λ) (exit : Option Λ) : + TM2.Stmt (fun _ : K => Bool) Λ (σ × Option Bool) := + statement p (blankRow V) again exit + +theorem verifierTrace (V : NPVerifier) (p : Ports K) (again : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (σ × Option Bool)) + (code : program again = verifierStatement V p again exit) + (base : K → List Bool) (n : Nat) (suffix output count : List Bool) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[n + 1] + (some ⟨some again, (ambient, register), + frame p base (encodeWord n ++ suffix) output count⟩) = + some ⟨exit, (ambient, none), frame p base (encodeWord 0 ++ suffix) + ((tokenBits (repeatedRows (blankRow V) n)).reverse ++ output) + (List.replicate (n * (indexing V).symbolCount) true ++ count)⟩ := by + simpa only [blankRow_length] using + trace p (blankRow V) again exit program code base n suffix output count ambient register + +theorem paddingCellsTrace (V : NPVerifier) (input : List Bool) (S start n : Nat) + (within : start + n ≤ S) + (padding : (inputPrefix input).length + V.witnessBound.eval input.length ≤ start) + (p : Ports K) (again : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (σ × Option Bool)) + (code : program again = verifierStatement V p again exit) + (base : K → List Bool) (work output count : List Bool) + (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (TM2.step program))^[n + 1] + (some ⟨some again, (ambient, register), + InputCellsCapacity.tapes p base n work output count⟩) = + some ⟨exit, (ambient, none), InputCellsCapacity.tapes p base 0 work + ((tokenBits (cellsInterval V input S start n within)).reverse ++ output) + (List.replicate (n * (indexing V).symbolCount) true ++ count)⟩ := by + rw [cellsInterval_padding V input S start n within padding] + simpa only [blankRow_length] using + capacityTrace p (blankRow V) again exit program code base n work output count ambient register + +end FixedVerifier + +variable [Fintype K] [Fintype σ] + +def machine (p : Ports K) (row : List Token) (ambient : σ) : FinTM2 where + K := K + k₀ := p 3 + k₁ := p 1 + Γ := fun _ => Bool + Λ := Unit + main := () + σ := σ × Option Bool + initialState := (ambient, none) + Γk₀Fin := inferInstance + m _ := statement p row () none + +theorem machineTrace (p : Ports K) (row : List Token) (base : K → List Bool) + (n : Nat) (suffix output count : List Bool) (ambient : σ) (register : Option Bool) : + (MachineComposition.advance (machine p row ambient).step)^[n + 1] + (some ⟨some (), (ambient, register), + frame p base (encodeWord n ++ suffix) output count⟩) = + some ⟨none, (ambient, none), frame p base (encodeWord 0 ++ suffix) + ((tokenBits (repeatedRows row n)).reverse ++ output) + (List.replicate (n * row.length) true ++ count)⟩ := + trace p row () none (machine p row ambient).m rfl + base n suffix output count ambient register + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.PaddingCellsMachine + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/PayloadCellsAlignment.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/PayloadCellsAlignment.lean new file mode 100644 index 0000000000000000000000000000000000000000..61892127b1ce11dc783c0f2c558733602e3778f3 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/PayloadCellsAlignment.lean @@ -0,0 +1,68 @@ +import OAI.Computability.PerfectCompleteness.Machines.PayloadCellsMachine + +namespace OAI + +section + +noncomputable section + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.PayloadCellsMachine + +open InitializationTemplate WitnessEncoding + +local instance alphabetDecidable (V : NPVerifier) : ∀ k, DecidableEq (V.computation.tm.Γ k) := + fun _ => Classical.decEq _ + +def symbolSpec (V : NPVerifier) (k : V.computation.tm.K) + (a : Option (V.computation.tm.Γ k)) : SymbolSpec := + if h : k = V.computation.tm.k₀ then by + subst k + exact ⟨true, decide (some (V.computation.inputAlphabet.invFun true) = a), + decide (some (V.computation.inputAlphabet.invFun false) = a), decide (none = a)⟩ + else ⟨false, false, false, decide (none = a)⟩ + +def symbolTable (V : NPVerifier) : Fin (VerifierCircuit.indexing V).symbolCount → SymbolSpec := + fun j => let symbol := (VerifierCircuit.indexing V).symbols.symm j + symbolSpec V symbol.1 symbol.2 + +def payloadRowTokens (V : NPVerifier) (q i : Nat) : List PostfixModel.Token := + Row.tokens (symbolTable V) q i + +theorem symbolTokens_eq_initialCellTokens (V : NPVerifier) (input : List Bool) (S i : Nat) + (hi : i < V.witnessBound.eval input.length) + (hS : (inputPrefix input).length + i < S) (k : V.computation.tm.K) + (a : Option (V.computation.tm.Γ k)) : + symbolTokens (symbolSpec V k a) (V.witnessBound.eval input.length) i = + initialCellTokens V input S k ⟨(inputPrefix input).length + i, hS⟩ a := by + by_cases hk : k = V.computation.tm.k₀ + · subst k + have hp : ¬ (inputPrefix input).length + i < (inputPrefix input).length := by omega + have hn : (inputPrefix input).length + i - (inputPrefix input).length = i := by omega + have hcell : inputCellTokens (V.witnessBound.eval input.length) input + V.computation.inputAlphabet.invFun ((inputPrefix input).length + i) a = + muxTokens (presenceTokens (V.witnessBound.eval input.length) i) + (payloadSymbolTokens (V.witnessBound.eval input.length) + V.computation.inputAlphabet.invFun i a) [.const (decide (none = a))] := by + simp only [inputCellTokens, ite_eq_right hp, hn, ite_eq_left hi] + simpa [symbolTokens, symbolSpec, initialCellTokens, payloadTokens, payloadSymbolTokens] using hcell.symm + · simp [symbolSpec, symbolTokens, initialCellTokens, hk] + +theorem payloadRowTokens_eq (V : NPVerifier) (input : List Bool) (S i : Nat) + (hi : i < V.witnessBound.eval input.length) (hS : (inputPrefix input).length + i < S) : + payloadRowTokens V (V.witnessBound.eval input.length) i = + (List.ofFn fun j : Fin (VerifierCircuit.indexing V).symbolCount => + let symbol := (VerifierCircuit.indexing V).symbols.symm j + initialCellTokens V input S symbol.1 ⟨(inputPrefix input).length + i, hS⟩ symbol.2).flatten := by + rw [payloadRowTokens, Row.tokens_eq_ofFn] + congr 1 + congr 1 + funext j + exact symbolTokens_eq_initialCellTokens V input S i hi hS _ _ + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.PayloadCellsMachine + +end + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/PayloadCellsMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/PayloadCellsMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..3015e1496f9abf3fefe491d7d46d8dfb89f3018f --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/PayloadCellsMachine.lean @@ -0,0 +1,438 @@ +import OAI.Computability.PerfectCompleteness.Machines.InitializationTemplateLemmas +import OAI.Computability.PerfectCompleteness.Machines.PayloadPresenceMachine + +namespace OAI + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.PayloadCellsMachine + +open Turing MachineComposition PostfixModel InitializationTemplate +open ClashMachine (State clean emitted) +open PayloadPresenceMachine (Ports Ready) + + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool + +private theorem chain {A : Type*} {f : A → A} {x y z : A} {n m : Nat} + (first : f^[n] x = y) (second : f^[m] y = z) : f^[n + m] x = z := by + rw [Nat.add_comm n m, Function.iterate_add_apply, first, second] + +structure SymbolSpec where + isInput : Bool + trueValue : Bool + falseValue : Bool + absentValue : Bool + deriving DecidableEq, Fintype + +def payloadTokens (address : Nat) (yes no : Bool) : List Token := + [.input address, .const yes, .and, .input address, .not, .const no, .and, .or] + +def symbolTokens (spec : SymbolSpec) (q i : Nat) : List Token := + if spec.isInput then + muxTokens (presenceTokens q i) (payloadTokens (q + 1 + i) spec.trueValue spec.falseValue) + [.const spec.absentValue] + else [.const spec.absentValue] + +namespace Payload + +def inputMap : Fin 4 ↪ Fin 9 := ⟨![3, 5, 7, 8], by decide⟩ + +inductive Label where + | seed | scanQ | restoreQ | scanI | restoreI + | inputTrue (l : ClashMachine.Input.Label) + | middle + | inputFalse (l : ClashMachine.Input.Label) + | suffix | drain + deriving DecidableEq, Fintype + +def statement (slots : Ports K) (labels : Label → Λ) (exit : Option Λ) (yes no : Bool) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (State σ) + | .seed => MachineUnaryAffineAt.seed (slots 3) 1 (labels .scanQ) + | .scanQ => MachineUnaryAffineAt.scan (slots 0) (slots 5) (slots 3) 1 + (labels .scanQ) (labels .restoreQ) + | .restoreQ => Reduction.MachineTransfer.loopAt (slots 5) (slots 0) id false + (labels .restoreQ) (some (labels .scanI)) + | .scanI => MachineUnaryAffineAt.scan (slots 1) (slots 5) (slots 3) 1 + (labels .scanI) (labels .restoreI) + | .restoreI => Reduction.MachineTransfer.loopAt (slots 5) (slots 1) id false + (labels .restoreI) (some (labels (.inputTrue .tag))) + | .inputTrue l => ClashMachine.Input.statement (inputMap.trans slots) + (fun l => labels (.inputTrue l)) (some (labels .middle)) l + | .middle => ClashMachine.literal (slots 7) (slots 8) [.const yes, .and] + (.goto fun _ => labels (.inputFalse .tag)) + | .inputFalse l => ClashMachine.Input.statement (inputMap.trans slots) + (fun l => labels (.inputFalse l)) (some (labels .suffix)) l + | .suffix => ClashMachine.literal (slots 7) (slots 8) [.not, .const no, .and, .or] + (.goto fun _ => labels .drain) + | .drain => MachineDrain.drain (slots 3) (labels .drain) exit + +def addressSteps (q i : Nat) := (2 * (q + 1) + 1) + 2 * (i + 1) + +theorem addressTrace (slots : Ports K) (labels : Label → Λ) (exit : Option Λ) (yes no : Bool) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ l, program (labels l) = statement slots labels exit yes no l) + (base : K → List Bool) (q i : Nat) (ready : Ready slots base q i) (ambient : σ) : + (advance (TM2.step program))^[addressSteps q i] + (some ⟨some (labels .seed), clean ambient, base⟩) = + some ⟨some (labels (.inputTrue .tag)), clean ambient, + Function.update base (slots 3) (encodeWord (q + 1 + i))⟩ := by + have e₃ := ready.empty 3 (by decide) (by decide) (by decide) (by decide) + have e₅ := ready.empty 5 (by decide) (by decide) (by decide) (by decide) + have hq := MachineUnaryAffineAt.seededAffineTrace (slots 0) (slots 5) (slots 3) + (slots.injective.ne (by decide)) (slots.injective.ne (by decide)) + (slots.injective.ne (by decide)) 1 1 (labels .seed) (labels .scanQ) (labels .restoreQ) + (some (labels .scanI)) program (atLabels .seed) (atLabels .scanQ) (atLabels .restoreQ) + base q [] (by simpa using ready.boundWord) e₅ (ambient, false) none + simp only [Nat.one_mul, e₃, List.append_nil] at hq + let addressed := Function.update base (slots 3) (encodeWord (q + 1)) + have hi := MachineUnaryAffineAt.affineTrace (slots 1) (slots 5) (slots 3) + (slots.injective.ne (by decide)) (slots.injective.ne (by decide)) + (slots.injective.ne (by decide)) 1 (labels .scanI) (labels .restoreI) + (some (labels (.inputTrue .tag))) program (atLabels .scanI) (atLabels .restoreI) + addressed i (q + 1) [] [] (ambient, false) none + have hframe (n : Nat) : MachineUnaryAffineAt.tapes (slots 1) (slots 5) (slots 3) + addressed (encodeWord i ++ []) [] (encodeWord n ++ []) = + Function.update base (slots 3) (encodeWord n) := by + simp only [MachineUnaryAffineAt.tapes, MachineCopy.forkTapes, List.append_nil] + apply ClashMachine.Full.ext_slots slots + · intro j + fin_cases j <;> simp [addressed, slots.injective.eq_iff, ready.indexWord, e₅] + · intro k hk + simp [addressed, hk] + rw [hframe, hframe] at hi + rw [show 1 * i + (q + 1) = q + 1 + i by omega] at hi + exact chain hq hi + +def steps (q i : Nat) : Nat := addressSteps q i + ClashMachine.Input.steps (q + 1 + i) + 1 + + ClashMachine.Input.steps (q + 1 + i) + 1 + (q + 1 + i + 2) + +theorem trace (slots : Ports K) (labels : Label → Λ) (exit : Option Λ) (yes no : Bool) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ l, program (labels l) = statement slots labels exit yes no l) + (base : K → List Bool) (q i : Nat) (ready : Ready slots base q i) (ambient : σ) : + (advance (TM2.step program))^[steps q i] + (some ⟨some (labels .seed), clean ambient, base⟩) = + some ⟨exit, clean ambient, + emitted (slots 7) (slots 8) base (payloadTokens (q + 1 + i) yes no)⟩ := by + have e₃ := ready.empty 3 (by decide) (by decide) (by decide) (by decide) + have e₅ := ready.empty 5 (by decide) (by decide) (by decide) (by decide) + let address := q + 1 + i + let b₀ := Function.update base (slots 3) (encodeWord address) + have ha := addressTrace slots labels exit yes no program atLabels base q i ready ambient + have ht := ClashMachine.Input.trace (inputMap.trans slots) (fun l => labels (.inputTrue l)) + (some (labels .middle)) program (fun _ => atLabels _) b₀ address + (by simp [b₀, inputMap]) (by simpa [b₀, inputMap, slots.injective.eq_iff] using e₅) ambient + let b₁ := emitted (slots 7) (slots 8) b₀ [.input address] + have hm : (advance (TM2.step program))^[1] + (some ⟨some (labels .middle), clean ambient, b₁⟩) = + some ⟨some (labels (.inputFalse .tag)), clean ambient, + emitted (slots 7) (slots 8) b₁ [.const yes, .and]⟩ := by + change some (TM2.stepAux (program (labels .middle)) _ _) = _ + rw [atLabels, statement, ClashMachine.stepAux_literal (slots 7) (slots 8) + (slots.injective.ne (by decide : (7 : Fin 9) ≠ 8))] + rfl + let b₂ := emitted (slots 7) (slots 8) b₁ [.const yes, .and] + have hf := ClashMachine.Input.trace (inputMap.trans slots) (fun l => labels (.inputFalse l)) + (some (labels .suffix)) program (fun _ => atLabels _) b₂ address + (by simp [b₂, b₁, b₀, inputMap, emitted, slots.injective.eq_iff]) + (by simpa [b₂, b₁, b₀, inputMap, emitted, slots.injective.eq_iff] using e₅) ambient + let b₃ := emitted (slots 7) (slots 8) b₂ [.input address] + have hs : (advance (TM2.step program))^[1] + (some ⟨some (labels .suffix), clean ambient, b₃⟩) = + some ⟨some (labels .drain), clean ambient, + emitted (slots 7) (slots 8) b₃ [.not, .const no, .and, .or]⟩ := by + change some (TM2.stepAux (program (labels .suffix)) _ _) = _ + rw [atLabels, statement, ClashMachine.stepAux_literal (slots 7) (slots 8) + (slots.injective.ne (by decide : (7 : Fin 9) ≠ 8))] + rfl + let b₄ := emitted (slots 7) (slots 8) b₃ [.not, .const no, .and, .or] + have hword : b₄ (slots 3) = encodeWord address := by + simp [b₄, b₃, b₂, b₁, b₀, emitted, slots.injective.eq_iff] + have hd := MachineDrain.drainTrace (slots 3) (labels .drain) exit program (atLabels .drain) + b₄ (encodeWord address) (ambient, false) none + rw [← hword, Function.update_eq_self] at hd + rw [hword, encodeWord_length] at hd + have hfinish : Function.update b₄ (slots 3) [] = + emitted (slots 7) (slots 8) base (payloadTokens address yes no) := by + have hb : b₄ = emitted (slots 7) (slots 8) b₀ (payloadTokens address yes no) := by + simp only [b₄, b₃, b₂, b₁, ClashMachine.emitted_append (slots 7) (slots 8) + (slots.injective.ne (by decide : (7 : Fin 9) ≠ 8))] + rfl + rw [hb] + apply ClashMachine.Full.ext_slots slots + · intro j + fin_cases j <;> simp [b₀, emitted, slots.injective.eq_iff, e₃] + · intro k hk + simp [b₀, emitted, hk] + rw [hfinish] at hd + exact chain (chain (chain (chain (chain ha ht) hm) hf) hs) hd + +theorem steps_le (q i : Nat) (hi : i < q) : steps q i ≤ 40 * (q + 2) := by + unfold steps addressSteps ClashMachine.Input.steps + omega + +end Payload + +namespace Symbol + +inductive Label where + | start + | first (l : PayloadPresenceMachine.Label) + | payload (l : Payload.Label) + | conjunction + | second (l : PayloadPresenceMachine.Label) + | suffix + deriving DecidableEq, Fintype + +def firstLabels : PayloadPresenceMachine.Label ↪ Label := ⟨.first, fun _ _ h => by cases h; rfl⟩ +def secondLabels : PayloadPresenceMachine.Label ↪ Label := ⟨.second, fun _ _ h => by cases h; rfl⟩ + +def statement (slots : Ports K) (labels : Label ↪ Λ) (exit : Option Λ) (spec : SymbolSpec) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (State σ) + | .start => if spec.isInput then .goto fun _ => labels (.first .initialize) + else ClashMachine.literal (slots 7) (slots 8) [.const spec.absentValue] + (Reduction.MachineTransfer.exitAt (slots 7) exit) + | .first l => PayloadPresenceMachine.statement slots (firstLabels.trans labels) + (some (labels (.payload .seed))) l + | .payload l => Payload.statement slots (fun l => labels (.payload l)) + (some (labels .conjunction)) spec.trueValue spec.falseValue l + | .conjunction => ClashMachine.literal (slots 7) (slots 8) [.and] + (.goto fun _ => labels (.second .initialize)) + | .second l => PayloadPresenceMachine.statement slots (secondLabels.trans labels) + (some (labels .suffix)) l + | .suffix => ClashMachine.literal (slots 7) (slots 8) [.not, .const spec.absentValue, .and, .or] + (Reduction.MachineTransfer.exitAt (slots 7) exit) + +def steps (spec : SymbolSpec) (q i : Nat) : Nat := + if spec.isInput then + 1 + PayloadPresenceMachine.steps q i + Payload.steps q i + 1 + PayloadPresenceMachine.steps q i + 1 + else 1 + +theorem trace (slots : Ports K) (labels : Label ↪ Λ) (exit : Option Λ) (spec : SymbolSpec) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ l, program (labels l) = statement slots labels exit spec l) + (base : K → List Bool) (q i : Nat) (hi : i < q) + (ready : Ready slots base q i) (ambient : σ) : + (advance (TM2.step program))^[steps spec q i] + (some ⟨some (labels .start), clean ambient, base⟩) = + some ⟨exit, clean ambient, emitted (slots 7) (slots 8) base (symbolTokens spec q i)⟩ := by + cases hspec : spec.isInput with + | false => + simp only [steps, hspec, Bool.false_eq_true, ↓reduceIte] + change some (TM2.stepAux (program (labels .start)) _ _) = _ + rw [atLabels, statement, hspec] + simp only [Bool.false_eq_true, ↓reduceIte] + rw [ClashMachine.stepAux_literal (slots 7) (slots 8) + (slots.injective.ne (by decide : (7 : Fin 9) ≠ 8))] + cases exit <;> simp [Reduction.MachineTransfer.exitAt, TM2.stepAux, symbolTokens, hspec] + | true => + have hs : (advance (TM2.step program))^[1] + (some ⟨some (labels .start), clean ambient, base⟩) = + some ⟨some (labels (.first .initialize)), clean ambient, base⟩ := by + change some (TM2.stepAux (program (labels .start)) _ _) = _ + rw [atLabels, statement, hspec] + rfl + have h₁ := PayloadPresenceMachine.trace slots (firstLabels.trans labels) + (some (labels (.payload .seed))) program (fun _ => atLabels _) base q i hi ready ambient + let b₁ := emitted (slots 7) (slots 8) base (presenceTokens q i) + have hp := Payload.trace slots (fun l => labels (.payload l)) (some (labels .conjunction)) + spec.trueValue spec.falseValue program (fun _ => atLabels _) + b₁ q i (ready.emitted (presenceTokens q i)) ambient + let b₂ := emitted (slots 7) (slots 8) b₁ (payloadTokens (q + 1 + i) spec.trueValue spec.falseValue) + have hc : (advance (TM2.step program))^[1] + (some ⟨some (labels .conjunction), clean ambient, b₂⟩) = + some ⟨some (labels (.second .initialize)), clean ambient, + emitted (slots 7) (slots 8) b₂ [.and]⟩ := by + change some (TM2.stepAux (program (labels .conjunction)) _ _) = _ + rw [atLabels, statement, ClashMachine.stepAux_literal (slots 7) (slots 8) + (slots.injective.ne (by decide : (7 : Fin 9) ≠ 8))] + rfl + let b₃ := emitted (slots 7) (slots 8) b₂ [.and] + have r₃ : Ready slots b₃ q i := + ((ready.emitted (presenceTokens q i)).emitted + (payloadTokens (q + 1 + i) spec.trueValue spec.falseValue)).emitted [.and] + have h₂ := PayloadPresenceMachine.trace slots (secondLabels.trans labels) + (some (labels .suffix)) program (fun _ => atLabels _) b₃ q i hi r₃ ambient + let b₄ := emitted (slots 7) (slots 8) b₃ (presenceTokens q i) + have hf : (advance (TM2.step program))^[1] + (some ⟨some (labels .suffix), clean ambient, b₄⟩) = + some ⟨exit, clean ambient, + emitted (slots 7) (slots 8) b₄ [.not, .const spec.absentValue, .and, .or]⟩ := by + change some (TM2.stepAux (program (labels .suffix)) _ _) = _ + rw [atLabels, statement, ClashMachine.stepAux_literal (slots 7) (slots 8) + (slots.injective.ne (by decide : (7 : Fin 9) ≠ 8))] + cases exit <;> rfl + have h := chain (chain (chain (chain (chain hs h₁) hp) hc) h₂) hf + simpa only [steps, hspec, ↓reduceIte, b₄, b₃, b₂, b₁, + ClashMachine.emitted_append (slots 7) (slots 8) + (slots.injective.ne (by decide : (7 : Fin 9) ≠ 8)), symbolTokens, muxTokens, + List.append_assoc, List.singleton_append, List.cons_append, List.nil_append] using h + +theorem steps_le (spec : SymbolSpec) (q i : Nat) (hi : i < q) : + steps spec q i ≤ 120 * (q + 2) ^ 2 := by + have hsquare : q + 2 ≤ (q + 2) ^ 2 := by nlinarith + have hp := Payload.steps_le q i hi + have hc := PayloadPresenceMachine.steps_le q i hi + unfold steps + split <;> omega + +end Symbol + +namespace Row + +variable {A : Nat} + +def tableAt (table : Fin A → SymbolSpec) (j : Nat) : SymbolSpec := + if hj : j < A then table ⟨j, hj⟩ else ⟨false, false, false, false⟩ + +def tokensFrom (table : Fin A → SymbolSpec) (q i start count : Nat) : List Token := + forTokens count (fun j => symbolTokens (tableAt table (start + j)) q i) + +def tokens (table : Fin A → SymbolSpec) (q i : Nat) : List Token := tokensFrom table q i 0 A + +theorem tokensFrom_succ (table : Fin A → SymbolSpec) (q i start count : Nat) : + tokensFrom table q i start (count + 1) = + symbolTokens (tableAt table start) q i ++ tokensFrom table q i (start + 1) count := by + rw [tokensFrom, forTokens_succ_first] + simp only [Nat.add_zero] + apply congrArg (List.append (symbolTokens (tableAt table start) q i)) + apply forTokens_congr + intro j _ + rw [show start + (j + 1) = start + 1 + j by omega] + +theorem tokens_eq_ofFn (table : Fin A → SymbolSpec) (q i : Nat) : + tokens table q i = (List.ofFn fun j : Fin A => symbolTokens (table j) q i).flatten := by + rw [tokens, tokensFrom, forTokens_eq_ofFn] + congr 1 + congr 1 + funext j + simp [tableAt, j.isLt] + +inductive Label (A : Nat) where + | visit (j : Fin (A + 1)) + | symbol (j : Fin A) (l : Symbol.Label) + deriving DecidableEq, Fintype + +def symbolLabels (j : Fin A) : Symbol.Label ↪ Label A := + ⟨Label.symbol j, fun _ _ h => by cases h; rfl⟩ + +def statement (slots : Ports K) (labels : Label A ↪ Λ) (exit : Option Λ) + (table : Fin A → SymbolSpec) : Label A → TM2.Stmt (Alphabet (K := K)) Λ (State σ) + | .visit j => if hj : j.val < A then .goto fun _ => labels (.symbol ⟨j.val, hj⟩ .start) + else Reduction.MachineTransfer.exitAt (slots 7) exit + | .symbol j l => Symbol.statement slots ((symbolLabels j).trans labels) + (some (labels (.visit ⟨j.val + 1, by omega⟩))) (table j) l + +def stepsFrom (table : Fin A → SymbolSpec) (q i : Nat) : Nat → Nat → Nat + | _, 0 => 1 + | start, count + 1 => 1 + Symbol.steps (tableAt table start) q i + stepsFrom table q i (start + 1) count + +def steps (table : Fin A → SymbolSpec) (q i : Nat) : Nat := stepsFrom table q i 0 A + +theorem traceFrom (slots : Ports K) (labels : Label A ↪ Λ) (exit : Option Λ) + (table : Fin A → SymbolSpec) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ l, program (labels l) = statement slots labels exit table l) + (base : K → List Bool) (q i : Nat) (hi : i < q) (ready : Ready slots base q i) + (ambient : σ) (start count : Nat) (hfinish : start + count = A) : + (advance (TM2.step program))^[stepsFrom table q i start count] + (some ⟨some (labels (.visit ⟨start, by omega⟩)), clean ambient, base⟩) = + some ⟨exit, clean ambient, emitted (slots 7) (slots 8) base (tokensFrom table q i start count)⟩ := by + induction count generalizing start base with + | zero => + have hstart : start = A := by omega + change some (TM2.stepAux (program (labels (.visit ⟨start, by omega⟩))) _ _) = _ + rw [atLabels, statement, dite_eq_right (show ¬ start < A by omega)] + cases exit <;> simp [TM2.stepAux, Reduction.MachineTransfer.exitAt, + tokensFrom, forTokens, ClashMachine.emitted_nil] + | succ count ih => + have hstart : start < A := by omega + let j : Fin A := ⟨start, hstart⟩ + have hv : (advance (TM2.step program))^[1] + (some ⟨some (labels (.visit ⟨start, by omega⟩)), clean ambient, base⟩) = + some ⟨some (labels (.symbol j .start)), clean ambient, base⟩ := by + change some (TM2.stepAux (program (labels (.visit ⟨start, by omega⟩))) _ _) = _ + rw [atLabels, statement, dite_eq_left hstart] + rfl + have hs := Symbol.trace slots ((symbolLabels j).trans labels) + (some (labels (.visit ⟨start + 1, by omega⟩))) (table j) program + (fun l => atLabels (.symbol j l)) base q i hi ready ambient + let nextBase := emitted (slots 7) (slots 8) base (symbolTokens (table j) q i) + have hn := ih nextBase (ready.emitted (symbolTokens (table j) q i)) (start + 1) (by omega) + have h := chain (chain hv hs) hn + have ht : tableAt table start = table j := dite_eq_left hstart + simpa only [stepsFrom, tokensFrom_succ, ht, nextBase, + ClashMachine.emitted_append (slots 7) (slots 8) + (slots.injective.ne (by decide : (7 : Fin 9) ≠ 8))] using h + +theorem trace (slots : Ports K) (labels : Label A ↪ Λ) (exit : Option Λ) + (table : Fin A → SymbolSpec) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ l, program (labels l) = statement slots labels exit table l) + (base : K → List Bool) (q i : Nat) (hi : i < q) (ready : Ready slots base q i) (ambient : σ) : + (advance (TM2.step program))^[steps table q i] + (some ⟨some (labels (.visit 0)), clean ambient, base⟩) = + some ⟨exit, clean ambient, emitted (slots 7) (slots 8) base (tokens table q i)⟩ := by + exact traceFrom slots labels exit table program atLabels base q i hi ready ambient 0 A (by omega) + +theorem stepsFrom_le (table : Fin A → SymbolSpec) (q i start count : Nat) (hi : i < q) : + stepsFrom table q i start count ≤ count * (120 * (q + 2) ^ 2 + 1) + 1 := by + induction count generalizing start with + | zero => simp [stepsFrom] + | succ count ih => + have hs := Symbol.steps_le (tableAt table start) q i hi + have hr := ih (start + 1) + rw [stepsFrom, Nat.succ_mul] + omega + +theorem steps_le (table : Fin A → SymbolSpec) (q i : Nat) (hi : i < q) : + steps table q i ≤ A * (120 * (q + 2) ^ 2 + 1) + 1 := stepsFrom_le table q i 0 A hi + +def inTime (slots : Ports K) (labels : Label A ↪ Λ) (exit : Option Λ) + (table : Fin A → SymbolSpec) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ l, program (labels l) = statement slots labels exit table l) + (base : K → List Bool) (q i : Nat) (hi : i < q) (ready : Ready slots base q i) (ambient : σ) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels (.visit 0)), clean ambient, base⟩ + (some ⟨exit, clean ambient, emitted (slots 7) (slots 8) base (tokens table q i)⟩) + (A * (120 * (q + 2) ^ 2 + 1) + 1) where + steps := steps table q i + evals_in_steps := by + change (advance (TM2.step program))^[steps table q i] _ = _ + exact trace slots labels exit table program atLabels base q i hi ready ambient + steps_le_m := steps_le table q i hi + + +variable [Fintype K] [Fintype σ] + +def machine (slots : Ports K) (table : Fin A → SymbolSpec) (ambient : σ) : FinTM2 where + K := K + k₀ := slots 0 + k₁ := slots 7 + Γ := Alphabet + Λ := Label A + main := .visit 0 + σ := State σ + initialState := clean ambient + Γk₀Fin := inferInstance + m := statement slots (Function.Embedding.refl _) none table + +def machineInTime (slots : Ports K) (table : Fin A → SymbolSpec) + (base : K → List Bool) (q i : Nat) (hi : i < q) + (ready : Ready slots base q i) (ambient : σ) : + StateTransition.EvalsToInTime (machine slots table ambient).step + ⟨some (.visit 0), clean ambient, base⟩ + (some ⟨none, clean ambient, emitted (slots 7) (slots 8) base (tokens table q i)⟩) + (A * (120 * (q + 2) ^ 2 + 1) + 1) := + inTime slots (Function.Embedding.refl _) none table (machine slots table ambient).m + (fun _ => rfl) base q i hi ready ambient + + +end Row + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.PayloadCellsMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/PayloadPresenceMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/PayloadPresenceMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..d5742e0d6cfc292211369883a27a298d1ed12d01 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/PayloadPresenceMachine.lean @@ -0,0 +1,269 @@ +import OAI.Computability.PerfectCompleteness.Machines.InitializationMachineAt +import OAI.Computability.PerfectCompleteness.Machines.ValidityComposition + +namespace OAI + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.PayloadPresenceMachine + +open Turing MachineComposition PostfixModel InitializationTemplate +open ClashMachine (State clean emitted) + + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool +abbrev Ports (K : Type) := Fin 9 ↪ K + +def presenceMap : Fin 6 ↪ Fin 9 := ⟨![2, 3, 4, 5, 7, 8], by decide⟩ + +omit [DecidableEq K] in +theorem closing_distinct (slots : Ports K) (j : Fin 6) : slots 6 ≠ (presenceMap.trans slots) j := by + apply slots.injective.ne + fin_cases j <;> decide + +def closurePorts (slots : Ports K) : OrClosure.Ports K := + InitializationMachineAt.closurePorts (presenceMap.trans slots) (slots 6) (closing_distinct slots) + +inductive CopyContext where + | remaining | threshold | closing + deriving DecidableEq + +/-- A list enumerating every element of the type, which are all zero-argument constructors. (Generated by the `Fintype` deriving handler.)-/ +protected abbrev CopyContext.enumList : List CopyContext := [.remaining, .threshold, .closing] + +protected theorem CopyContext.enumList_getElem?_ctorIdx_eq (x : CopyContext) : + CopyContext.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem CopyContext.enumList_nodup : CopyContext.enumList.Nodup := by decide + +instance : Fintype CopyContext where + elems := ⟨CopyContext.enumList, CopyContext.enumList_nodup⟩ + complete x := by cases x <;> decide + +inductive Label where + | initialize + | copy (context : CopyContext) (l : MachineUnaryAffineAt.Label) + | presence (l : InitializationMachine.Label) + | orLoop | cleanup | drain + deriving DecidableEq, Fintype + +def presenceLabels : InitializationMachine.Label ↪ Label := + ⟨Label.presence, fun _ _ h => by cases h; rfl⟩ + +def copySource (slots : Ports K) : CopyContext → K + | .remaining | .closing => slots 0 + | .threshold => slots 1 + +def copyTarget (slots : Ports K) : CopyContext → K + | .remaining => slots 2 + | .threshold => slots 4 + | .closing => slots 6 + +def copyExit (labels : Label ↪ Λ) : CopyContext → Λ + | .remaining => labels (.copy .threshold .seed) + | .threshold => labels (.copy .closing .seed) + | .closing => labels (.presence .guard) + +def statement (slots : Ports K) (labels : Label ↪ Λ) (exit : Option Λ) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (State σ) + | .initialize => .push (slots 3) (fun _ => false) (.goto fun _ => labels (.copy .remaining .seed)) + | .copy context l => ValidityMachine.Nonempty.copyStatement (copySource slots context) (slots 5) + (copyTarget slots context) (fun l => labels (.copy context l)) (some (copyExit labels context)) l + | .presence .done => OrClosure.seed (closurePorts slots) (labels .orLoop) + | .presence l => InitializationMachineAt.statement (presenceMap.trans slots) + (presenceLabels.trans labels) l + | .orLoop => OrClosure.loop (closurePorts slots) (labels .orLoop) (some (labels .cleanup)) + | .cleanup => .pop (slots 2) (fun s _ => s) + (.pop (slots 4) (fun s _ => s) (.pop (slots 6) (fun s _ => s) (.goto fun _ => labels .drain))) + | .drain => MachineDrain.drain (slots 3) (labels .drain) exit + +structure Ready (slots : Ports K) (base : K → List Bool) (q i : Nat) : Prop where + boundWord : base (slots 0) = encodeWord q + indexWord : base (slots 1) = encodeWord i + empty : ∀ j : Fin 9, j ≠ 0 → j ≠ 1 → j ≠ 7 → j ≠ 8 → base (slots j) = [] + +theorem Ready.emitted {slots : Ports K} {base : K → List Bool} {q i : Nat} + (h : Ready slots base q i) (tokens : List Token) : + Ready slots (emitted (slots 7) (slots 8) base tokens) q i := by + constructor + · simpa [ClashMachine.emitted, slots.injective.eq_iff] using h.boundWord + · simpa [ClashMachine.emitted, slots.injective.eq_iff] using h.indexWord + · intro j h₀ h₁ h₇ h₈ + simpa [ClashMachine.emitted, slots.injective.eq_iff, h₇, h₈] using h.empty j h₀ h₁ h₇ h₈ + +def working (slots : Ports K) (base : K → List Bool) (r j d c : Nat) : K → List Bool := + Function.update (Function.update (Function.update (Function.update base + (slots 2) (encodeWord r)) (slots 3) (encodeWord j)) (slots 4) (encodeWord d)) + (slots 6) (encodeWord c) + +def steps (q i : Nat) : Nat := + 1 + (2 * (q + 1) + 1) + (2 * (i + 1) + 1) + (2 * (q + 1) + 1) + + (InitializationMachine.selectorSteps 0 (q + 1) + (q + 1 + 2)) + 1 + (q + 3) + +private theorem chain {A : Type*} {f : A → A} {x y z : A} {n m : Nat} + (first : f^[n] x = y) (second : f^[m] y = z) : f^[n + m] x = z := by + rw [Nat.add_comm n m, Function.iterate_add_apply, first, second] + +theorem copyTrace (slots : Ports K) (labels : Label ↪ Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ l, program (labels l) = statement slots labels exit l) + (context : CopyContext) (base : K → List Bool) (n : Nat) + (sourceWord : base (copySource slots context) = encodeWord n) + (scratchEmpty : base (slots 5) = []) (targetEmpty : base (copyTarget slots context) = []) + (ambient : σ) : + (advance (TM2.step program))^[2 * (n + 1) + 1] + (some ⟨some (labels (.copy context .seed)), clean ambient, base⟩) = + some ⟨some (copyExit labels context), clean ambient, + Function.update base (copyTarget slots context) (encodeWord (n + 1))⟩ := by + have hs : copySource slots context ≠ slots 5 := by + cases context <;> exact slots.injective.ne (by decide) + have hd : copySource slots context ≠ copyTarget slots context := by + cases context <;> exact slots.injective.ne (by decide) + have hsd : slots 5 ≠ copyTarget slots context := by + cases context <;> exact slots.injective.ne (by decide) + have h := MachineUnaryAffineAt.seededAffineTrace (copySource slots context) (slots 5) + (copyTarget slots context) hs hd hsd 1 1 + (labels (.copy context .seed)) (labels (.copy context .scan)) (labels (.copy context .restore)) + (some (copyExit labels context)) program + (atLabels (.copy context .seed)) (atLabels (.copy context .scan)) (atLabels (.copy context .restore)) + base n [] (by simpa using sourceWord) scratchEmpty (ambient, false) none + simpa only [Nat.one_mul, targetEmpty, List.append_nil, clean] using h + +theorem trace (slots : Ports K) (labels : Label ↪ Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ l, program (labels l) = statement slots labels exit l) + (base : K → List Bool) (q i : Nat) (hi : i < q) + (ready : Ready slots base q i) (ambient : σ) : + (advance (TM2.step program))^[steps q i] + (some ⟨some (labels .initialize), clean ambient, base⟩) = + some ⟨exit, clean ambient, emitted (slots 7) (slots 8) base (presenceTokens q i)⟩ := by + have e₂ := ready.empty 2 (by decide) (by decide) (by decide) (by decide) + have e₃ := ready.empty 3 (by decide) (by decide) (by decide) (by decide) + have e₄ := ready.empty 4 (by decide) (by decide) (by decide) (by decide) + have e₅ := ready.empty 5 (by decide) (by decide) (by decide) (by decide) + have e₆ := ready.empty 6 (by decide) (by decide) (by decide) (by decide) + let b₀ := Function.update base (slots 3) (encodeWord 0) + let b₁ := Function.update b₀ (slots 2) (encodeWord (q + 1)) + let b₂ := Function.update b₁ (slots 4) (encodeWord (i + 1)) + let b₃ := Function.update b₂ (slots 6) (encodeWord (q + 1)) + have hinit : (advance (TM2.step program))^[1] + (some ⟨some (labels .initialize), clean ambient, base⟩) = + some ⟨some (labels (.copy .remaining .seed)), clean ambient, b₀⟩ := by + change some (TM2.stepAux (program (labels .initialize)) _ _) = _ + rw [atLabels, statement] + simp [TM2.stepAux, e₃, b₀, encodeWord] + have hr := copyTrace slots labels exit program atLabels .remaining b₀ q + (by simpa [b₀, copySource, slots.injective.eq_iff] using ready.boundWord) + (by simpa [b₀, slots.injective.eq_iff] using e₅) + (by simpa [b₀, copyTarget, slots.injective.eq_iff] using e₂) ambient + have ht := copyTrace slots labels exit program atLabels .threshold b₁ i + (by simpa [b₁, b₀, copySource, slots.injective.eq_iff] using ready.indexWord) + (by simpa [b₁, b₀, slots.injective.eq_iff] using e₅) + (by simpa [b₁, b₀, copyTarget, slots.injective.eq_iff] using e₄) ambient + have hc := copyTrace slots labels exit program atLabels .closing b₂ q + (by simpa [b₂, b₁, b₀, copySource, slots.injective.eq_iff] using ready.boundWord) + (by simpa [b₂, b₁, b₀, slots.injective.eq_iff] using e₅) + (by simpa [b₂, b₁, b₀, copyTarget, slots.injective.eq_iff] using e₆) ambient + let loopBase := Function.update base (slots 6) (encodeWord (q + 1)) + have hprepared : b₃ = InitializationMachineAt.tapes (presenceMap.trans slots) + loopBase (q + 1) 0 (i + 1) (base (slots 7)) (base (slots 8)) := by + apply ClashMachine.Full.ext_slots slots + · intro j + fin_cases j <;> simp [b₃, b₂, b₁, b₀, loopBase, InitializationMachineAt.tapes, + InitializationMachineAt.frame, InitializationMachineAt.contents, presenceMap, + slots.injective.eq_iff, e₅] + · intro k hk + simp [b₃, b₂, b₁, b₀, loopBase, InitializationMachineAt.tapes, + InitializationMachineAt.frame, presenceMap, hk] + have agrees : InitializationMachineAt.Agrees (presenceMap.trans slots) + (presenceLabels.trans labels) program := by + intro l hl + change program (labels (.presence l)) = + InitializationMachineAt.statement (presenceMap.trans slots) (presenceLabels.trans labels) l + have h := atLabels (.presence l) + cases l <;> try contradiction + all_goals simpa only [statement] using h + have hp := InitializationMachineAt.presenceTrace (presenceMap.trans slots) (presenceLabels.trans labels) + (slots 6) (closing_distinct slots) (labels .orLoop) (some (labels .cleanup)) program agrees + (atLabels (.presence .done)) (atLabels .orLoop) loopBase q i [] + (base (slots 7)) (base (slots 8)) (by simp [loopBase]) ambient + dsimp only at hp + let selected := InitializationMachineAt.tapes (presenceMap.trans slots) loopBase + 0 (q + 1) (i + 1 - (q + 1)) + ((tokenBits (selectorLoopTokens (q + 1) 0 (i + 1))).reverse ++ base (slots 7)) + (List.replicate (3 * (q + 1)) true ++ base (slots 8)) + let result := emitted (slots 7) (slots 8) base (presenceTokens q i) + let produced := working slots result 0 (q + 1) 0 0 + have hsub : i + 1 - (q + 1) = 0 := by omega + have hproduced : OrClosure.frame (closurePorts slots) selected (encodeWord 0 ++ []) + ((tokenBits (presenceTokens q i)).reverse ++ base (slots 7)) + (List.replicate (4 * (q + 1) + 1) true ++ base (slots 8)) = produced := by + apply ClashMachine.Full.ext_slots slots + · intro j + fin_cases j <;> simp [produced, working, result, emitted, OrClosure.frame, + selected, closurePorts, InitializationMachineAt.closurePorts, + InitializationMachineAt.tapes, InitializationMachineAt.frame, + InitializationMachineAt.contents, presenceMap, loopBase, hsub, + slots.injective.eq_iff, presenceTokens_length, e₅] + · intro k hk + simp [produced, working, result, emitted, OrClosure.frame, + selected, closurePorts, InitializationMachineAt.closurePorts, + InitializationMachineAt.tapes, InitializationMachineAt.frame, presenceMap, loopBase, hk] + change (advance (TM2.step program))^[InitializationMachine.selectorSteps 0 (q + 1) + (q + 1 + 2)] + (some ⟨some (labels (.presence .guard)), clean ambient, + InitializationMachineAt.tapes (presenceMap.trans slots) loopBase + (q + 1) 0 (i + 1) (base (slots 7)) (base (slots 8))⟩) = + some ⟨some (labels .cleanup), clean ambient, + OrClosure.frame (closurePorts slots) selected (encodeWord 0 ++ []) + ((tokenBits (presenceTokens q i)).reverse ++ base (slots 7)) + (List.replicate (4 * (q + 1) + 1) true ++ base (slots 8))⟩ at hp + rw [← hprepared, hproduced] at hp + let cleared := Function.update (Function.update (Function.update produced (slots 2) []) + (slots 4) []) (slots 6) [] + have hcleanup : (advance (TM2.step program))^[1] + (some ⟨some (labels .cleanup), clean ambient, produced⟩) = + some ⟨some (labels .drain), clean ambient, cleared⟩ := by + change some (TM2.stepAux (program (labels .cleanup)) _ _) = _ + rw [atLabels, statement] + simp [TM2.stepAux, produced, working, encodeWord, cleared, slots.injective.eq_iff] + have hcurrent : cleared (slots 3) = encodeWord (q + 1) := by + simp [cleared, produced, working, slots.injective.eq_iff] + have hd := MachineDrain.drainTrace (slots 3) (labels .drain) exit program (atLabels .drain) + cleared (encodeWord (q + 1)) (ambient, false) none + rw [← hcurrent, Function.update_eq_self] at hd + rw [hcurrent, encodeWord_length] at hd + have hfinish : Function.update cleared (slots 3) [] = result := by + apply ClashMachine.Full.ext_slots slots + · intro j + fin_cases j <;> simp [cleared, produced, working, result, emitted, + slots.injective.eq_iff, e₂, e₃, e₄, e₆] + · intro k hk + simp [cleared, produced, working, hk] + rw [hfinish] at hd + exact chain (chain (chain (chain (chain (chain hinit hr) ht) hc) hp) hcleanup) hd + +theorem steps_le (q i : Nat) (hi : i < q) : steps q i ≤ 30 * (q + 2) ^ 2 := by + have h := InitializationMachineAt.presenceSteps_le q + unfold steps + nlinarith + +def inTime (slots : Ports K) (labels : Label ↪ Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ l, program (labels l) = statement slots labels exit l) + (base : K → List Bool) (q i : Nat) (hi : i < q) + (ready : Ready slots base q i) (ambient : σ) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .initialize), clean ambient, base⟩ + (some ⟨exit, clean ambient, emitted (slots 7) (slots 8) base (presenceTokens q i)⟩) + (30 * (q + 2) ^ 2) where + steps := steps q i + evals_in_steps := by + change (advance (TM2.step program))^[steps q i] _ = _ + exact trace slots labels exit program atLabels base q i hi ready ambient + steps_le_m := steps_le q i hi + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.PayloadPresenceMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/PayloadRowsLoop.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/PayloadRowsLoop.lean new file mode 100644 index 0000000000000000000000000000000000000000..9c21439861becd6735c7f7f6f1b22a6f469a9bcd --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/PayloadRowsLoop.lean @@ -0,0 +1,240 @@ +import OAI.Computability.PerfectCompleteness.Machines.PayloadCellsMachine + +namespace OAI + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.PayloadRowsLoop + +open Turing MachineComposition PostfixModel InitializationTemplate +open ClashMachine (State clean emitted emitted_append) +open PayloadCellsMachine (SymbolSpec) + + +variable {K Λ σ : Type} [DecidableEq K] {A : Nat} + +abbrev Ports (K : Type) := Fin 11 ↪ K +abbrev Alphabet (_ : K) := Bool + +def rowMap : Fin 9 ↪ Fin 11 where + toFun i := ⟨i.val, by omega⟩ + inj' := by + intro i j h + exact Fin.ext (congrArg (fun x : Fin 11 => x.val) h) + +def rowPorts (p : Ports K) : PayloadPresenceMachine.Ports K := rowMap.trans p + +def frame (p : Ports K) (base : K → List Bool) (remaining index capacity : Nat) : K → List Bool := + Function.update (Function.update (Function.update base (p 1) (encodeWord index)) + (p 9) (encodeWord remaining)) (p 10) (encodeWord capacity) + +@[simp] theorem frame_index (p : Ports K) (base : K → List Bool) (m i c : Nat) : + frame p base m i c (p 1) = encodeWord i := by simp [frame, p.injective.eq_iff] + +@[simp] theorem frame_remaining (p : Ports K) (base : K → List Bool) (m i c : Nat) : + frame p base m i c (p 9) = encodeWord m := by simp [frame, p.injective.eq_iff] + +@[simp] theorem frame_capacity (p : Ports K) (base : K → List Bool) (m i c : Nat) : + frame p base m i c (p 10) = encodeWord c := by simp [frame] + +private theorem ext_ports (p : Ports K) {f g : K → List Bool} + (atPorts : ∀ j, f (p j) = g (p j)) + (outside : ∀ k, (∀ j, k ≠ p j) → f k = g k) : f = g := by + funext k + by_cases hk : ∃ j, p j = k + · obtain ⟨j, rfl⟩ := hk + exact atPorts j + · exact outside k (fun j h => hk ⟨j, h.symm⟩) + +theorem update_remaining (p : Ports K) (base : K → List Bool) (m i c r : Nat) : + Function.update (frame p base m i c) (p 9) (encodeWord r) = frame p base r i c := by + apply ext_ports p + · intro j + fin_cases j <;> simp [frame, p.injective.eq_iff] + · intro k hk + simp [frame, hk] + +theorem update_index (p : Ports K) (base : K → List Bool) (m i c r : Nat) : + Function.update (frame p base m i c) (p 1) (encodeWord r) = frame p base m r c := by + apply ext_ports p + · intro j + fin_cases j <;> simp [frame, p.injective.eq_iff] + · intro k hk + simp [frame, hk] + +theorem update_capacity (p : Ports K) (base : K → List Bool) (m i c r : Nat) : + Function.update (frame p base m i c) (p 10) (encodeWord r) = frame p base m i r := by + simp [frame] + +theorem frame_emitted (p : Ports K) (base : K → List Bool) (m i c : Nat) (tokens : List Token) : + emitted (p 7) (p 8) (frame p base m i c) tokens = + frame p (emitted (p 7) (p 8) base tokens) m i c := by + apply ext_ports p + · intro j + fin_cases j <;> simp [frame, emitted, p.injective.eq_iff] + · intro k hk + simp [frame, emitted, hk] + +theorem frame_ready (p : Ports K) (base : K → List Bool) (q m i c : Nat) + (ready : PayloadPresenceMachine.Ready (rowPorts p) base q 0) : + PayloadPresenceMachine.Ready (rowPorts p) (frame p base m i c) q i := by + constructor + · have rowPort : rowPorts p 0 = p 0 := by + change p (rowMap 0) = p 0 + rw [rowMap.eq_1] + rfl + have boundWord : base (p 0) = encodeWord q := by + simpa only [rowPort] using ready.boundWord + change frame p base m i c (p 0) = encodeWord q + simpa [frame, p.injective.eq_iff] using boundWord + · exact frame_index p base m i c + · intro j h₀ h₁ h₇ h₈ + have h1 : rowMap j ≠ (1 : Fin 11) := by + intro h + apply h₁ + exact Fin.ext (congrArg (fun x : Fin 11 => x.val) h) + have h9 : rowMap j ≠ (9 : Fin 11) := by + intro h + have hv := congrArg (fun x : Fin 11 => x.val) h + change j.val = 9 at hv + omega + have h10 : rowMap j ≠ (10 : Fin 11) := by + intro h + have hv := congrArg (fun x : Fin 11 => x.val) h + change j.val = 10 at hv + omega + simpa only [rowPorts, Function.Embedding.trans_apply, frame, + Function.update_of_ne (p.injective.ne h10), Function.update_of_ne (p.injective.ne h9), + Function.update_of_ne (p.injective.ne h1)] using ready.empty j h₀ h₁ h₇ h₈ + +inductive Label (symbols : Nat) + | guard | next + | row (entry : PayloadCellsMachine.Row.Label symbols) + deriving DecidableEq, Fintype + +def rowLabels (label : Label A ↪ Λ) : PayloadCellsMachine.Row.Label A ↪ Λ where + toFun entry := label (.row entry) + inj' := by intro i j h; exact Label.row.inj (label.injective h) + +def statement (p : Ports K) (label : Label A ↪ Λ) (exit : Λ) + (table : Fin A → SymbolSpec) : Label A → TM2.Stmt (Alphabet (K := K)) Λ (State σ) + | .guard => MachineUnaryCounter.guard (p 9) (label (.row (.visit 0))) exit + | .next => .pop (p 10) (fun state _ => state) + (.push (p 1) (fun _ => true) (.goto fun _ => label .guard)) + | .row entry => PayloadCellsMachine.Row.statement (rowPorts p) (rowLabels label) + (some (label .next)) table entry + +def Agrees (p : Ports K) (label : Label A ↪ Λ) (exit : Λ) (table : Fin A → SymbolSpec) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) : Prop := + ∀ entry, program (label entry) = statement p label exit table entry + +theorem guardStep_zero (p : Ports K) (label : Label A ↪ Λ) (exit : Λ) + (table : Fin A → SymbolSpec) (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (ha : Agrees p label exit table program) (base : K → List Bool) (i c : Nat) (ambient : σ) : + TM2.step program ⟨some (label .guard), clean ambient, frame p base 0 i c⟩ = + some ⟨some exit, clean ambient, frame p base 0 i c⟩ := by + change some (TM2.stepAux (program (label .guard)) _ _) = _ + rw [ha .guard] + simp [statement, MachineUnaryCounter.guard, TM2.stepAux, clean, encodeWord] + +theorem guardStep_succ (p : Ports K) (label : Label A ↪ Λ) (exit : Λ) + (table : Fin A → SymbolSpec) (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (ha : Agrees p label exit table program) (base : K → List Bool) (m i c : Nat) (ambient : σ) : + TM2.step program ⟨some (label .guard), clean ambient, frame p base (m + 1) i c⟩ = + some ⟨some (label (.row (.visit 0))), clean ambient, frame p base m i c⟩ := by + change some (TM2.stepAux (program (label .guard)) _ _) = _ + rw [ha .guard] + simp [statement, MachineUnaryCounter.guard, TM2.stepAux, clean, encodeWord, List.replicate_succ] + exact update_remaining p base (m + 1) i c m + +theorem nextStep (p : Ports K) (label : Label A ↪ Λ) (exit : Λ) + (table : Fin A → SymbolSpec) (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (ha : Agrees p label exit table program) (base : K → List Bool) (m i c : Nat) (ambient : σ) : + TM2.step program ⟨some (label .next), clean ambient, frame p base m i (c + 1)⟩ = + some ⟨some (label .guard), clean ambient, frame p base m (i + 1) c⟩ := by + change some (TM2.stepAux (program (label .next)) _ _) = _ + rw [ha .next] + simp only [statement, TM2.stepAux, frame_capacity, encodeWord, List.replicate_succ, + List.cons_append, List.tail_cons] + rw [Function.update_of_ne (p.injective.ne (by decide : (1 : Fin 11) ≠ 10))] + change some (⟨some (label .guard), clean ambient, + Function.update (Function.update (frame p base m i (c + 1)) (p 10) (encodeWord c)) + (p 1) (true :: frame p base m i (c + 1) (p 1))⟩ : TM2.Cfg (Alphabet (K := K)) Λ (State σ)) = _ + rw [update_capacity, frame_index] + rw [show true :: encodeWord i = encodeWord (i + 1) by simp [encodeWord, List.replicate_succ]] + rw [update_index] + +def tokens (table : Fin A → SymbolSpec) (q : Nat) : Nat → Nat → List Token + | _, 0 => [] + | i, m + 1 => PayloadCellsMachine.Row.tokens table q i ++ tokens table q (i + 1) m + +def steps (table : Fin A → SymbolSpec) (q : Nat) : Nat → Nat → Nat + | _, 0 => 1 + | i, m + 1 => 1 + PayloadCellsMachine.Row.steps table q i + 1 + steps table q (i + 1) m + +theorem trace (p : Ports K) (label : Label A ↪ Λ) (exit : Λ) (table : Fin A → SymbolSpec) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (ha : Agrees p label exit table program) (base : K → List Bool) (q i m c : Nat) + (hbound : i + m ≤ q) (ready : PayloadPresenceMachine.Ready (rowPorts p) base q 0) + (ambient : σ) : + (advance (TM2.step program))^[steps table q i m] + (some ⟨some (label .guard), clean ambient, frame p base m i (c + m)⟩) = + some ⟨some exit, clean ambient, + emitted (p 7) (p 8) (frame p base 0 (i + m) c) (tokens table q i m)⟩ := by + induction m generalizing base i with + | zero => + simpa only [steps, Function.iterate_one, advance_some, Nat.add_zero, + tokens, ClashMachine.emitted_nil] using guardStep_zero p label exit table program ha base i c ambient + | succ m ih => + have hi : i < q := by omega + have hguard : (advance (TM2.step program))^[1] + (some ⟨some (label .guard), clean ambient, frame p base (m + 1) i (c + (m + 1))⟩) = + some ⟨some (label (.row (.visit 0))), clean ambient, frame p base m i (c + (m + 1))⟩ := by + simpa only [Function.iterate_one, advance_some] using + guardStep_succ p label exit table program ha base m i (c + (m + 1)) ambient + have hrow := PayloadCellsMachine.Row.trace (rowPorts p) (rowLabels label) + (some (label .next)) table program (fun entry => ha (.row entry)) + (frame p base m i (c + (m + 1))) q i hi (frame_ready p base q m i _ ready) ambient + change (advance (TM2.step program))^[PayloadCellsMachine.Row.steps table q i] + (some ⟨some (label (.row (.visit 0))), clean ambient, frame p base m i (c + (m + 1))⟩) = + some ⟨some (label .next), clean ambient, + emitted (p 7) (p 8) (frame p base m i (c + (m + 1))) + (PayloadCellsMachine.Row.tokens table q i)⟩ at hrow + rw [frame_emitted] at hrow + let nextBase := emitted (p 7) (p 8) base (PayloadCellsMachine.Row.tokens table q i) + have hnext : (advance (TM2.step program))^[1] + (some ⟨some (label .next), clean ambient, frame p nextBase m i (c + (m + 1))⟩) = + some ⟨some (label .guard), clean ambient, frame p nextBase m (i + 1) (c + m)⟩ := by + simpa only [Function.iterate_one, advance_some, Nat.add_assoc] using + nextStep p label exit table program ha nextBase m i (c + m) ambient + have hn : PayloadPresenceMachine.Ready (rowPorts p) nextBase q 0 := + ready.emitted (PayloadCellsMachine.Row.tokens table q i) + have htail := ih nextBase (i + 1) (by omega) hn + have h := ClashMachine.chain (ClashMachine.chain (ClashMachine.chain hguard hrow) hnext) htail + have hend : i + 1 + m = i + (m + 1) := by omega + simpa only [steps, tokens, hend, nextBase, ← frame_emitted, + emitted_append (p 7) (p 8) (p.injective.ne (by decide : (7 : Fin 11) ≠ 8))] using h + +theorem steps_le (table : Fin A → SymbolSpec) (q i m : Nat) (hbound : i + m ≤ q) : + steps table q i m ≤ m * (A * (120 * (q + 2) ^ 2 + 1) + 3) + 1 := by + induction m generalizing i with + | zero => simp [steps] + | succ m ih => + have ht := ih (i + 1) (by omega) + have hr := PayloadCellsMachine.Row.steps_le table q i (by omega) + rw [steps, Nat.succ_mul] + omega + +theorem tokens_eq_forTokens (table : Fin A → SymbolSpec) (q i m : Nat) : + tokens table q i m = forTokens m (fun j => PayloadCellsMachine.Row.tokens table q (i + j)) := by + induction m generalizing i with + | zero => rfl + | succ m ih => + rw [tokens, forTokens_succ_first, Nat.add_zero, ih] + apply congrArg (List.append (PayloadCellsMachine.Row.tokens table q i)) + apply forTokens_congr + intro j _ + rw [show i + 1 + j = i + (j + 1) by omega] + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.PayloadRowsLoop + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/PositionLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/PositionLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..ac155fd203ceca34fdc8e0ef73c7640362105034 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/PositionLemmas.lean @@ -0,0 +1,433 @@ +import Mathlib.Data.List.OfFn +import Mathlib.Data.Nat.Basic +import OAI.Computability.PerfectCompleteness.Machines.CircuitEncodingLemmas +import OAI.Computability.UniqueGames.Machines.MachineUnaryAffineAt + +namespace OAI + +section + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.TransitionTemplate + +inductive Position where + | current + | zero + | succ (p : Position) + | pred (p : Position) + deriving DecidableEq + +def Position.eval (cursor : Nat) : Position → Nat + | .current => cursor + | .zero => 0 + | .succ p => p.eval cursor + 1 + | .pred p => p.eval cursor - 1 + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.TransitionTemplate + +end + +section + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.PositionMachine + +open Turing MachineComposition TransitionTemplate + +def usesCurrent : Position → Bool + | .current => true + | .zero => false + | .succ p => usesCurrent p + | .pred p => usesCurrent p + +def initialValue (p : Position) (cursor : Nat) : Nat := + if usesCurrent p then cursor else 0 + +def transform : Position → Nat → Nat + | .current, n => n + | .zero, n => n + | .succ p, n => transform p n + 1 + | .pred p, n => transform p n - 1 + +theorem transform_initialValue (p : Position) (cursor : Nat) : + transform p (initialValue p cursor) = p.eval cursor := by + induction p with + | current => rfl + | zero => rfl + | succ p ih => + change transform p (initialValue p cursor) + 1 = p.eval cursor + 1 + exact congrArg (fun n : Nat => n + 1) ih + | pred p ih => + change transform p (initialValue p cursor) - 1 = p.eval cursor - 1 + exact congrArg (fun n : Nat => n - 1) ih + +section Statements + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool +abbrev State (σ : Type) := σ × Option Bool + +def decrement (destination : K) + (continuation : TM2.Stmt (Alphabet (K := K)) Λ (State σ)) : + TM2.Stmt (Alphabet (K := K)) Λ (State σ) := + .peek destination (fun s head => (s.1, head)) + (.branch (fun s => s.2.getD false) + (.pop destination (fun s _ => (s.1, none)) continuation) + (.load (fun s => (s.1, none)) continuation)) + +theorem stepAux_decrement (destination : K) + (continuation : TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (base : K → List Bool) (n : Nat) (suffix : List Bool) + (ambient : σ) (register : Option Bool) : + TM2.stepAux (decrement destination continuation) (ambient, register) + (Function.update base destination (encodeWord n ++ suffix)) = + TM2.stepAux continuation (ambient, none) + (Function.update base destination (encodeWord (n - 1) ++ suffix)) := by + cases n <;> simp [decrement, TM2.stepAux, encodeWord, List.replicate_succ] + +def suffixStatement (destination : K) : Position → + TM2.Stmt (Alphabet (K := K)) Λ (State σ) → + TM2.Stmt (Alphabet (K := K)) Λ (State σ) + | .current, continuation => .load (fun s => (s.1, none)) continuation + | .zero, continuation => .load (fun s => (s.1, none)) continuation + | .succ p, continuation => + suffixStatement destination p (.push destination (fun _ => true) continuation) + | .pred p, continuation => suffixStatement destination p (decrement destination continuation) + +theorem stepAux_suffixStatement (destination : K) (p : Position) + (continuation : TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (base : K → List Bool) (n : Nat) (suffix : List Bool) + (ambient : σ) (register : Option Bool) : + TM2.stepAux (suffixStatement destination p continuation) (ambient, register) + (Function.update base destination (encodeWord n ++ suffix)) = + TM2.stepAux continuation (ambient, none) + (Function.update base destination (encodeWord (transform p n) ++ suffix)) := by + induction p generalizing continuation with + | current => rfl + | zero => rfl + | succ p ih => + rw [suffixStatement, ih] + simp [TM2.stepAux, transform, encodeWord, List.replicate_succ] + | pred p ih => + rw [suffixStatement, ih, stepAux_decrement] + rfl + +inductive Label where + | start + | scan + | restore + | finish + deriving DecidableEq + +instance : Fintype Label where + elems := { .start, .scan, .restore, .finish } + complete l := by cases l <;> simp + +def statement (source scratch destination : K) (p : Position) + (labels : Label → Λ) (exit : Option Λ) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (State σ) + | .start => if usesCurrent p then + MachineUnaryAffineAt.seed destination 0 (labels .scan) + else .push destination (fun _ => false) (.goto fun _ => labels .finish) + | .scan => MachineUnaryAffineAt.scan source scratch destination 1 + (labels .scan) (labels .restore) + | .restore => Reduction.MachineTransfer.loopAt scratch source id false + (labels .restore) (some (labels .finish)) + | .finish => suffixStatement destination p (Reduction.MachineTransfer.exitAt destination exit) + +def seedSteps (p : Position) (cursor : Nat) : Nat := + if usesCurrent p then 2 * (cursor + 1) + 1 else 1 + +def steps (p : Position) (cursor : Nat) : Nat := seedSteps p cursor + 1 + +theorem seedTrace (source scratch destination : K) + (hs : source ≠ scratch) (hd : source ≠ destination) (hsd : scratch ≠ destination) + (p : Position) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ l, program (labels l) = statement source scratch destination p labels exit l) + (base : K → List Bool) (cursor : Nat) (suffix : List Bool) + (sourceWord : base source = encodeWord cursor ++ suffix) (scratchEmpty : base scratch = []) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[seedSteps p cursor] + (some ⟨some (labels .start), (ambient, register), base⟩) = + some ⟨some (labels .finish), (ambient, if usesCurrent p then none else register), + Function.update base destination (encodeWord (initialValue p cursor) ++ base destination)⟩ := by + cases hc : usesCurrent p with + | false => + simp only [seedSteps, initialValue, hc, Bool.false_eq_true, ↓reduceIte, + Function.iterate_one, advance_some] + change some (TM2.stepAux (program (labels .start)) (ambient, register) base) = _ + rw [atLabels] + simp [statement, hc, TM2.stepAux, encodeWord] + | true => + have h := MachineUnaryAffineAt.seededAffineTrace source scratch destination hs hd hsd + 1 0 (labels .start) (labels .scan) (labels .restore) (some (labels .finish)) + program (by simpa [statement, hc] using atLabels .start) + (atLabels .scan) (atLabels .restore) base cursor suffix sourceWord scratchEmpty + ambient register + simpa only [seedSteps, initialValue, hc, ↓reduceIte, one_mul, add_zero] using h + +theorem finishTrace (source scratch destination : K) + (p : Position) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atFinish : program (labels .finish) = statement source scratch destination p labels exit .finish) + (base : K → List Bool) (n : Nat) (suffix : List Bool) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[1] + (some ⟨some (labels .finish), (ambient, register), + Function.update base destination (encodeWord n ++ suffix)⟩) = + some ⟨exit, (ambient, none), + Function.update base destination (encodeWord (transform p n) ++ suffix)⟩ := by + change some (TM2.stepAux (program (labels .finish)) _ _) = _ + rw [atFinish, statement, stepAux_suffixStatement] + cases exit <;> rfl + +theorem positionTrace (source scratch destination : K) + (hs : source ≠ scratch) (hd : source ≠ destination) (hsd : scratch ≠ destination) + (p : Position) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ l, program (labels l) = statement source scratch destination p labels exit l) + (base : K → List Bool) (cursor : Nat) (suffix : List Bool) + (sourceWord : base source = encodeWord cursor ++ suffix) (scratchEmpty : base scratch = []) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[steps p cursor] + (some ⟨some (labels .start), (ambient, register), base⟩) = + some ⟨exit, (ambient, none), + Function.update base destination (encodeWord (p.eval cursor) ++ base destination)⟩ := by + rw [steps, Nat.add_comm (seedSteps p cursor) 1, Function.iterate_add_apply, + seedTrace source scratch destination hs hd hsd p labels exit program atLabels + base cursor suffix sourceWord scratchEmpty ambient register, + finishTrace source scratch destination p labels exit program (atLabels .finish), + transform_initialValue] + +noncomputable def timePolynomial : Polynomial Nat := Polynomial.C 2 * Polynomial.X + Polynomial.C 4 + +theorem steps_le_time (p : Position) (cursor : Nat) : + steps p cursor ≤ timePolynomial.eval cursor := by + simp only [timePolynomial, Polynomial.eval_add, Polynomial.eval_mul, + Polynomial.eval_C, Polynomial.eval_X, steps, seedSteps] + split <;> omega + +def positionInPolynomialTime (source scratch destination : K) + (hs : source ≠ scratch) (hd : source ≠ destination) (hsd : scratch ≠ destination) + (p : Position) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ l, program (labels l) = statement source scratch destination p labels exit l) + (base : K → List Bool) (cursor : Nat) (suffix : List Bool) + (sourceWord : base source = encodeWord cursor ++ suffix) (scratchEmpty : base scratch = []) + (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .start), (ambient, register), base⟩ + (some ⟨exit, (ambient, none), + Function.update base destination (encodeWord (p.eval cursor) ++ base destination)⟩) + (timePolynomial.eval cursor) where + steps := steps p cursor + evals_in_steps := positionTrace source scratch destination hs hd hsd p labels exit + program atLabels base cursor suffix sourceWord scratchEmpty ambient register + steps_le_m := steps_le_time p cursor + +end Statements + +abbrev machine (p : Position) : Turing.FinTM2 where + K := Fin 3 + k₀ := 0 + k₁ := 2 + Γ _ := Bool + Λ := Label + main := .start + σ := State Unit + initialState := ((), none) + m := statement 0 1 2 p id none + +def machineInPolynomialTime (p : Position) (base : Fin 3 → List Bool) + (cursor : Nat) (suffix : List Bool) + (sourceWord : base 0 = encodeWord cursor ++ suffix) (scratchEmpty : base 1 = []) : + StateTransition.EvalsToInTime (machine p).step + ⟨some .start, ((), none), base⟩ + (some ⟨none, ((), none), Function.update base 2 (encodeWord (p.eval cursor) ++ base 2)⟩) + (timePolynomial.eval cursor) := + positionInPolynomialTime 0 1 2 (by decide) (by decide) (by decide) p id none + (statement 0 1 2 p id none) (fun _ => rfl) base cursor suffix sourceWord scratchEmpty () none + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.PositionMachine + +end + +section + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.PostfixModel + +inductive Token where + | const (value : Bool) + | not | and | or + | input (wire : Nat) + deriving DecidableEq + +namespace Token + +def tag : Token → Fin 6 + | .const false => 0 + | .const true => 1 + | .not => 2 + | .and => 3 + | .or => 4 + | .input _ => 5 + +def words : Token → List Nat + | .const false => [0] + | .const true => [1] + | .not => [2] + | .and => [3] + | .or => [4] + | .input wire => [5, wire] + +def bits (token : Token) : List Bool := encodeWords token.words + +def takeGate : Token → List Nat → Option (Gate × List Nat) + | .const value, roots => some (.const value, roots) + | .input wire, roots => some (.or wire wire, roots) + | .not, arg :: roots => some (.not arg, roots) + | .and, right :: left :: roots => some (.and left right, roots) + | .or, right :: left :: roots => some (.or left right, roots) + | _, _ => none + +end Token + +def tokenWords (tokens : List Token) : List Nat := tokens.flatMap Token.words +def tokenBits (tokens : List Token) : List Bool := encodeWords (tokenWords tokens) + +def compileTokens (start : Nat) (roots : List Nat) : + List Token → Option (Nat × List Nat × List Gate) + | [] => some (start, roots, []) + | token :: tokens => do + let (gate, remaining) ← token.takeGate roots + let (next, finalRoots, gates) ← compileTokens (start + 1) (start :: remaining) tokens + pure (next, finalRoots, gate :: gates) + +def inputBits (start : Nat) (tokens : List Token) : List Bool := + encodeWords [start, tokens.length] ++ tokenBits tokens + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.PostfixModel + +end + +section + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.InitializationTemplate + +open PostfixModel + +def forTokens : Nat → (Nat → List Token) → List Token + | 0, _ => [] + | count + 1, body => forTokens count body ++ body count + +theorem forTokens_eq_flatMap_range (count : Nat) (body : Nat → List Token) : + forTokens count body = (List.range count).flatMap body := by + induction count with + | zero => rfl + | succ count ih => simp [forTokens, List.range_succ, ih] + +theorem forTokens_eq_ofFn (count : Nat) (body : Nat → List Token) : + forTokens count body = (List.ofFn fun i : Fin count => body i.val).flatten := by + induction count with + | zero => simp [forTokens] + | succ count ih => + rw [forTokens, ih, List.ofFn_succ'] + simp [List.concat_eq_append] + +theorem forTokens_succ_first (count : Nat) (body : Nat → List Token) : + forTokens (count + 1) body = body 0 ++ forTokens count (fun j => body (j + 1)) := by + simp [forTokens_eq_flatMap_range, List.range_succ_eq_map, List.flatMap_map] + +theorem forTokens_congr (count : Nat) (first second : Nat → List Token) + (h : ∀ i, i < count → first i = second i) : + forTokens count first = forTokens count second := by + induction count with + | zero => rfl + | succ count ih => + rw [forTokens, forTokens, ih (fun i hi => h i (by omega)), h count (by omega)] + +theorem forTokens_length_le (count : Nat) (body : Nat → List Token) (cost : Nat) + (h : ∀ i, i < count → (body i).length ≤ cost) : + (forTokens count body).length ≤ count * cost := by + induction count with + | zero => simp [forTokens] + | succ count ih => + have hp := ih (fun i hi => h i (by omega)) + have hl := h count (by omega) + simp only [forTokens, List.length_append, Nat.succ_mul] + omega + +theorem forTokens_length_eq (count : Nat) (body : Nat → List Token) (cost : Nat) + (h : ∀ i, i < count → (body i).length = cost) : + (forTokens count body).length = count * cost := by + induction count with + | zero => simp [forTokens] + | succ count ih => + rw [forTokens, List.length_append, ih (fun i hi => h i (by omega)), h count (by omega)] + exact (Nat.succ_mul count cost).symm + +def closeOr (count : Nat) : List Token := [.const false] ++ List.replicate count .or + +def nonemptyTokens (q : Nat) : List Token := + forTokens (q + 1) (fun i => [.input i]) ++ closeOr (q + 1) + +def clashPairTokens (i j : Nat) : List Token := + if i = j then [.const false] else [.input i, .input j, .and] + +def clashRowTokens (q i : Nat) : List Token := + forTokens (q + 1) (clashPairTokens i) ++ closeOr (q + 1) + +def clashTokens (q : Nat) : List Token := + forTokens (q + 1) (clashRowTokens q) ++ closeOr (q + 1) + +def validityTokens (q : Nat) : List Token := + nonemptyTokens q ++ clashTokens q ++ [.not, .and] + +def presenceTokens (q n : Nat) : List Token := + forTokens (q + 1) (fun length => [.input length, .const (decide (n < length)), .and]) ++ + closeOr (q + 1) + +def selectorLoopTokens (count start threshold : Nat) : List Token := + forTokens count (fun j => [.input (start + j), .const (decide (threshold ≤ j)), .and]) + +theorem threshold_zero_iff (threshold used : Nat) : + threshold - used = 0 ↔ threshold ≤ used := Nat.sub_eq_zero_iff_le + +theorem selectorLoopTokens_length (count start threshold : Nat) : + (selectorLoopTokens count start threshold).length = 3 * count := by + simpa only [selectorLoopTokens, Nat.mul_comm] using + forTokens_length_eq count + (fun j => [.input (start + j), .const (decide (threshold ≤ j)), .and]) 3 + (fun _ _ => rfl) + +theorem selectorLoopTokens_succ (count start threshold : Nat) : + selectorLoopTokens (count + 1) start threshold = + [.input start, .const (decide (threshold = 0)), .and] ++ + selectorLoopTokens count (start + 1) (threshold - 1) := by + rw [selectorLoopTokens, forTokens_succ_first] + simp only [Nat.add_zero, Nat.le_zero] + apply congrArg (List.append [Token.input start, Token.const (decide (threshold = 0)), Token.and]) + apply forTokens_congr + intro j _ + have ha : start + (j + 1) = start + 1 + j := by omega + have ht : (threshold ≤ j + 1) = (threshold - 1 ≤ j) := propext (by omega) + simp only [ha, ht] + +theorem selectorLoopTokens_presence (q n : Nat) : + selectorLoopTokens (q + 1) 0 (n + 1) ++ closeOr (q + 1) = presenceTokens q n := by + simp only [selectorLoopTokens, presenceTokens] + apply congrArg (fun xs : List Token => xs ++ closeOr (q + 1)) + apply forTokens_congr + intro j _ + simp only [Nat.zero_add, Nat.succ_le_iff] + +theorem presenceTokens_length (q n : Nat) : (presenceTokens q n).length = 4 * (q + 1) + 1 := by + rw [← selectorLoopTokens_presence q n, List.length_append, selectorLoopTokens_length] + simp only [closeOr, List.length_append, List.length_cons, List.length_nil, List.length_replicate] + omega + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.InitializationTemplate + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/PostfixAlignment.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/PostfixAlignment.lean new file mode 100644 index 0000000000000000000000000000000000000000..c0309ac40817684e0f984851dc18426bba5bae20 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/PostfixAlignment.lean @@ -0,0 +1,249 @@ +import OAI.Computability.PerfectCompleteness.Machines.CircuitBatchLemmas +import OAI.Computability.PerfectCompleteness.Machines.PositionLemmas + +namespace OAI + +section + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.PostfixAlignment + +open StatementCircuit CircuitBatch PostfixModel + +variable {ι : Type*} + +def exprTokens (wire : ι → Nat) : Expr ι → List Token + | .input i => [.input (wire i)] + | .const b => [.const b] + | .not e => exprTokens wire e ++ [.not] + | .and e f => exprTokens wire e ++ exprTokens wire f ++ [.and] + | .or e f => exprTokens wire e ++ exprTokens wire f ++ [.or] + +def forestTokens (wire : ι → Nat) (es : List (Expr ι)) : List Token := + es.flatMap (exprTokens wire) + +@[simp] theorem exprTokens_length (wire : ι → Nat) (e : Expr ι) : + (exprTokens wire e).length = e.size := by + induction e <;> simp_all [exprTokens, Expr.size, Nat.add_assoc] + +@[simp] theorem exprTokens_rename {κ : Type*} (f : ι → κ) (wire : κ → Nat) (e : Expr ι) : + exprTokens wire (e.rename f) = exprTokens (fun i => wire (f i)) e := by + induction e <;> simp_all [Expr.rename, exprTokens] + +@[simp] theorem forestTokens_nil (wire : ι → Nat) : + forestTokens wire ([] : List (Expr ι)) = [] := rfl + +@[simp] theorem forestTokens_cons (wire : ι → Nat) (e : Expr ι) (es : List (Expr ι)) : + forestTokens wire (e :: es) = exprTokens wire e ++ forestTokens wire es := rfl + +@[simp] theorem forestTokens_length (wire : ι → Nat) (es : List (Expr ι)) : + (forestTokens wire es).length = Batch.cost es := by + induction es with + | nil => rfl + | cons e es ih => simp only [forestTokens_cons, List.length_append, exprTokens_length, + ih, Batch.cost_cons] + +theorem compileTokens_append + (start : Nat) (roots : List Nat) (first rest : List Token) + (middle : Nat) (middleRoots : List Nat) (firstGates : List Gate) + (finish : Nat) (finalRoots : List Nat) (lastGates : List Gate) + (hfirst : compileTokens start roots first = some (middle, middleRoots, firstGates)) + (hrest : compileTokens middle middleRoots rest = some (finish, finalRoots, lastGates)) : + compileTokens start roots (first ++ rest) = + some (finish, finalRoots, firstGates ++ lastGates) := by + induction first generalizing start roots middle middleRoots firstGates with + | nil => + simp only [compileTokens, Option.some.injEq, Prod.mk.injEq] at hfirst + rcases hfirst with ⟨rfl, rfl, rfl⟩ + simpa only [List.nil_append] using hrest + | cons token tokens ih => + cases hg : token.takeGate roots with + | none => simp [compileTokens, hg] at hfirst + | some pair => + rcases pair with ⟨gate, remaining⟩ + cases ht : compileTokens (start + 1) (start :: remaining) tokens with + | none => simp [compileTokens, hg, ht] at hfirst + | some triple => + rcases triple with ⟨next, afterRoots, tailGates⟩ + simp [compileTokens, hg, ht] at hfirst + rcases hfirst with ⟨rfl, rfl, rfl⟩ + have hi := ih (start + 1) (start :: remaining) next afterRoots tailGates ht hrest + simp [List.cons_append, compileTokens, hg, hi] + +theorem compile_exprTokens (wire : ι → Nat) (e : Expr ι) + (start : Nat) (roots : List Nat) : + compileTokens start roots (exprTokens wire e) = + some (start + e.size, e.root start :: roots, e.gates wire start) := by + induction e generalizing start roots with + | input i => simp [exprTokens, compileTokens, Token.takeGate, Expr.root, Expr.size, Expr.gates] + | const b => simp [exprTokens, compileTokens, Token.takeGate, Expr.root, Expr.size, Expr.gates] + | not e ih => + have hop : compileTokens (start + e.size) (e.root start :: roots) [.not] = + some (start + e.size + 1, (start + e.size) :: roots, [.not (e.root start)]) := rfl + have he := compileTokens_append start roots (exprTokens wire e) [.not] + _ _ _ _ _ _ (ih start roots) hop + simpa only [exprTokens, Expr.gates, Expr.size, Expr.root_not, Nat.add_assoc] using he + | and e f ihe ihf => + have hop : compileTokens (start + e.size + f.size) + (f.root (start + e.size) :: e.root start :: roots) [.and] = + some (start + e.size + f.size + 1, (start + e.size + f.size) :: roots, + [.and (e.root start) (f.root (start + e.size))]) := rfl + have hf := compileTokens_append (start + e.size) (e.root start :: roots) + (exprTokens wire f) [.and] _ _ _ _ _ _ (ihf _ _) hop + have he := compileTokens_append start roots (exprTokens wire e) + (exprTokens wire f ++ [.and]) _ _ _ _ _ _ (ihe _ _) hf + simpa only [exprTokens, Expr.gates, Expr.size, Expr.root_and, Nat.add_assoc, + List.append_assoc] using he + | or e f ihe ihf => + have hop : compileTokens (start + e.size + f.size) + (f.root (start + e.size) :: e.root start :: roots) [.or] = + some (start + e.size + f.size + 1, (start + e.size + f.size) :: roots, + [.or (e.root start) (f.root (start + e.size))]) := rfl + have hf := compileTokens_append (start + e.size) (e.root start :: roots) + (exprTokens wire f) [.or] _ _ _ _ _ _ (ihf _ _) hop + have he := compileTokens_append start roots (exprTokens wire e) + (exprTokens wire f ++ [.or]) _ _ _ _ _ _ (ihe _ _) hf + simpa only [exprTokens, Expr.gates, Expr.size, Expr.root_or, Nat.add_assoc, + List.append_assoc] using he + +theorem compile_forestTokens (wire : ι → Nat) (es : List (Expr ι)) + (start : Nat) (roots : List Nat) : + compileTokens start roots (forestTokens wire es) = + some (start + Batch.cost es, (Batch.roots start es).reverse ++ roots, + Batch.gates wire start es) := by + induction es generalizing start roots with + | nil => simp [forestTokens, compileTokens, Batch.cost, Batch.roots, Batch.gates] + | cons e es ih => + have h := compileTokens_append start roots (exprTokens wire e) (forestTokens wire es) + _ _ _ _ _ _ (compile_exprTokens wire e start roots) + (ih (start + e.size) (e.root start :: roots)) + simpa only [forestTokens_cons, Batch.cost_cons, Batch.roots, Batch.gates, + List.reverse_cons, List.append_assoc, List.singleton_append, Nat.add_assoc] using h + +theorem exprTokens_lowered_ordered (wire : ι → Nat) (e : Expr ι) (start : Nat) + (hw : ∀ i, wire i < start) : Ordered start (e.gates wire start) := + e.gates_ordered wire start hw + +theorem forestTokens_lowered_ordered (wire : ι → Nat) (es : List (Expr ι)) (start : Nat) + (hw : ∀ i, wire i < start) : Ordered start (Batch.gates wire start es) := + Batch.gates_ordered wire start es hw + +theorem forestTokens_preserves_root_suffix (wire : ι → Nat) (es : List (Expr ι)) + (start : Nat) (roots : List Nat) : + ∃ fresh : List Nat, + compileTokens start roots (forestTokens wire es) = + some (start + Batch.cost es, fresh ++ roots, Batch.gates wire start es) ∧ + fresh.length = es.length ∧ + ∀ r ∈ fresh, start ≤ r ∧ r < start + Batch.cost es := by + refine ⟨(Batch.roots start es).reverse, compile_forestTokens wire es start roots, ?_, ?_⟩ + · simp only [List.length_reverse, Batch.roots_length] + · intro r hr + exact Batch.roots_bounds start es r (List.mem_reverse.mp hr) + +theorem expr_inputBits (wire : ι → Nat) (e : Expr ι) (start : Nat) : + PostfixModel.inputBits start (exprTokens wire e) = + encodeWords [start, e.size] ++ tokenBits (exprTokens wire e) := by + simp only [PostfixModel.inputBits, exprTokens_length] + +theorem forest_inputBits (wire : ι → Nat) (es : List (Expr ι)) (start : Nat) : + PostfixModel.inputBits start (forestTokens wire es) = + encodeWords [start, Batch.cost es] ++ tokenBits (forestTokens wire es) := by + simp only [PostfixModel.inputBits, forestTokens_length] + +theorem forest_gateRecords_alignment (wire : ι → Nat) (es : List (Expr ι)) + (start : Nat) (roots : List Nat) : + (compileTokens start roots (forestTokens wire es)).map + (fun result => gateRecords start result.2.2) = + some (gateRecords start (Batch.gates wire start es)) := by + rw [compile_forestTokens] + rfl + +theorem tokenWords_length_le (tokens : List Token) : + (tokenWords tokens).length ≤ 2 * tokens.length := by + induction tokens with + | nil => simp [tokenWords] + | cons t ts ih => + have ht : t.words.length ≤ 2 := by + cases t with + | const b => cases b <;> decide + | not => decide + | and => decide + | or => decide + | input w => simp [Token.words] + simp only [tokenWords, List.flatMap_cons, List.length_append] at ih ⊢ + simp only [List.length_cons] + omega + +private theorem exprTokens_member (wire : ι → Nat) (e : Expr ι) (t : Token) + (h : t ∈ exprTokens wire e) : + (∃ b, t = .const b) ∨ t = .not ∨ t = .and ∨ t = .or ∨ + ∃ i, t = .input (wire i) := by + induction e with + | input i => + have ht : t = .input (wire i) := by simpa only [exprTokens, List.mem_singleton] using h + exact Or.inr (Or.inr (Or.inr (Or.inr ⟨i, ht⟩))) + | const b => + have ht : t = .const b := by simpa only [exprTokens, List.mem_singleton] using h + exact Or.inl ⟨b, ht⟩ + | not e ih => + simp only [exprTokens, List.mem_append, List.mem_singleton] at h + rcases h with h | rfl + · exact ih h + · exact Or.inr (Or.inl rfl) + | and e f ihe ihf => + simp only [exprTokens, List.mem_append, List.mem_singleton, or_assoc] at h + rcases h with h | h | rfl + · exact ihe h + · exact ihf h + · exact Or.inr (Or.inr (Or.inl rfl)) + | or e f ihe ihf => + simp only [exprTokens, List.mem_append, List.mem_singleton, or_assoc] at h + rcases h with h | h | rfl + · exact ihe h + · exact ihf h + · exact Or.inr (Or.inr (Or.inr (Or.inl rfl))) + +theorem expr_tokenWords_bounded (wire : ι → Nat) (e : Expr ι) (start : Nat) + (hw : ∀ i, wire i < start) (word : Nat) (h : word ∈ tokenWords (exprTokens wire e)) : + word ≤ max 5 start := by + obtain ⟨t, ht, hword⟩ := List.mem_flatMap.mp h + rcases exprTokens_member wire e t ht with ⟨b, rfl⟩ | rfl | rfl | rfl | ⟨i, rfl⟩ + · cases b <;> simp only [Token.words, List.mem_singleton] at hword <;> omega + · simp only [Token.words, List.mem_singleton] at hword; omega + · simp only [Token.words, List.mem_singleton] at hword; omega + · simp only [Token.words, List.mem_singleton] at hword; omega + · simp only [Token.words, List.mem_cons, List.not_mem_nil, or_false] at hword + have hi := hw i + rcases hword with rfl | rfl <;> omega + +theorem forest_tokenWords_bounded (wire : ι → Nat) (es : List (Expr ι)) (start : Nat) + (hw : ∀ i, wire i < start) (word : Nat) (h : word ∈ tokenWords (forestTokens wire es)) : + word ≤ max 5 start := by + obtain ⟨t, ht, hword⟩ := List.mem_flatMap.mp h + obtain ⟨e, he, htoken⟩ := List.mem_flatMap.mp ht + exact expr_tokenWords_bounded wire e start hw word + (List.mem_flatMap.mpr ⟨t, htoken, hword⟩) + +theorem forest_tokenBits_length_le (wire : ι → Nat) (es : List (Expr ι)) (start : Nat) + (hw : ∀ i, wire i < start) : + (tokenBits (forestTokens wire es)).length ≤ + 2 * Batch.cost es * (max 5 start + 1) := by + have hb := encodeWords_length_le (tokenWords (forestTokens wire es)) (max 5 start) + (forest_tokenWords_bounded wire es start hw) + have hc : (tokenWords (forestTokens wire es)).length ≤ 2 * Batch.cost es := by + simpa only [forestTokens_length] using tokenWords_length_le (forestTokens wire es) + exact hb.trans (Nat.mul_le_mul_right _ hc) + +theorem forest_inputBits_length_le (wire : ι → Nat) (es : List (Expr ι)) (start : Nat) + (hw : ∀ i, wire i < start) : + (PostfixModel.inputBits start (forestTokens wire es)).length ≤ + start + Batch.cost es + 2 + 2 * Batch.cost es * (max 5 start + 1) := by + rw [forest_inputBits, List.length_append] + have hb := forest_tokenBits_length_le wire es start hw + simp only [encodeWords, List.length_append, encodeWord_length, List.length_nil] + omega + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.PostfixAlignment + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/PostfixBounds.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/PostfixBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..1fc845dbb6cd9051582b7edb0966ed08ecd1f6f8 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/PostfixBounds.lean @@ -0,0 +1,235 @@ +import Mathlib.Tactic.Ring +import OAI.Computability.PerfectCompleteness.Machines.PostfixAlignment +import OAI.Computability.PerfectCompleteness.Machines.PostfixMachine + +namespace OAI + +section + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.PostfixBounds + +open StatementCircuit CircuitBatch PostfixModel PostfixMachine PostfixAlignment +open CircuitProducerModel + +def RootsBounded (R : Nat) (roots : List Nat) : Prop := ∀ r ∈ roots, r ≤ R + +def TokenBounded (R : Nat) : Token → Prop + | .input wire => wire ≤ R + | _ => True + +theorem fieldSteps_le (tag : Fin 6) (slot : Fin 3) (value R : Nat) (h : value ≤ R) : + fieldSteps tag slot value ≤ 2 * R + 3 := by + unfold fieldSteps + split <;> omega + +theorem recordSteps_le (tag : Fin 6) (values : Fin 3 → Nat) (R : Nat) + (h : ∀ slot, values slot ≤ R) : recordSteps tag values ≤ 6 * R + 10 := by + have h0 := fieldSteps_le tag 0 (values 0) R (h 0) + have h1 := fieldSteps_le tag 1 (values 1) R (h 1) + have h2 := fieldSteps_le tag 2 (values 2) R (h 2) + unfold recordSteps + omega + +theorem gateRecord_slot_le (current R : Nat) (gate : Gate) (hq : current ≤ R) + (hg : gate.Bounded (R + 1)) (slot : Fin 3) : + (gateRecord current gate).slot slot ≤ R := by + cases gate with + | const b => cases b <;> fin_cases slot <;> simp [gateRecord, Record.slot] <;> omega + | not a => fin_cases slot <;> simp [gateRecord, Record.slot] <;> simp [Gate.Bounded] at hg <;> omega + | and a b => fin_cases slot <;> simp [gateRecord, Record.slot] <;> simp [Gate.Bounded] at hg <;> omega + | or a b => fin_cases slot <;> simp [gateRecord, Record.slot] <;> simp [Gate.Bounded] at hg <;> omega + +theorem operandSteps_le (token : Token) (gate : Gate) (R : Nat) + (ht : TokenBounded R token) (hg : gate.Bounded (R + 1)) : + operandSteps token gate ≤ 2 * R + 4 := by + cases token <;> cases gate <;> + simp_all [operandSteps, TokenBounded, Gate.Bounded] <;> omega + +theorem operandFields_length_le (token : Token) (gate : Gate) (R : Nat) + (ht : TokenBounded R token) (hg : gate.Bounded (R + 1)) : + (operandFields token gate).1.length + (operandFields token gate).2.length ≤ 2 * R + 2 := by + cases token <;> cases gate <;> + simp_all [operandFields, TokenBounded, Gate.Bounded] <;> omega + +theorem tokenSteps_le (current R : Nat) (token : Token) (gate : Gate) + (hq : current ≤ R) (ht : TokenBounded R token) (hg : gate.Bounded (R + 1)) : + tokenSteps current token gate ≤ 12 * R + 24 := by + have ho := operandSteps_le token gate R ht hg + have hf := operandFields_length_le token gate R ht hg + have hr := recordSteps_le token.tag (gateRecord current gate).slot R + (gateRecord_slot_le current R gate hq hg) + unfold tokenSteps + omega + +theorem takeGate_bounds (token : Token) (roots : List Nat) (gate : Gate) (rest : List Nat) + (R : Nat) (ht : TokenBounded R token) (hr : RootsBounded R roots) + (htake : token.takeGate roots = some (gate, rest)) : + gate.Bounded (R + 1) ∧ RootsBounded R rest := by + cases token with + | const b => + simp only [Token.takeGate, Option.some.injEq, Prod.mk.injEq] at htake + rcases htake with ⟨rfl, rfl⟩ + exact ⟨trivial, hr⟩ + | input wire => + simp only [Token.takeGate, Option.some.injEq, Prod.mk.injEq] at htake + rcases htake with ⟨rfl, rfl⟩ + exact ⟨⟨by change wire ≤ R at ht; omega, by change wire ≤ R at ht; omega⟩, hr⟩ + | not => + cases roots with + | nil => simp [Token.takeGate] at htake + | cons a roots => + simp only [Token.takeGate, Option.some.injEq, Prod.mk.injEq] at htake + rcases htake with ⟨rfl, rfl⟩ + have ha := hr a (by simp) + exact ⟨by change a < R + 1; omega, fun r h => hr r (by simp [h])⟩ + | and => + cases roots with + | nil => simp [Token.takeGate] at htake + | cons right roots => + cases roots with + | nil => simp [Token.takeGate] at htake + | cons left roots => + simp only [Token.takeGate, Option.some.injEq, Prod.mk.injEq] at htake + rcases htake with ⟨rfl, rfl⟩ + have hl := hr left (by simp) + have hr' := hr right (by simp) + exact ⟨⟨by omega, by omega⟩, fun r h => hr r (by simp [h])⟩ + | or => + cases roots with + | nil => simp [Token.takeGate] at htake + | cons right roots => + cases roots with + | nil => simp [Token.takeGate] at htake + | cons left roots => + simp only [Token.takeGate, Option.some.injEq, Prod.mk.injEq] at htake + rcases htake with ⟨rfl, rfl⟩ + have hl := hr left (by simp) + have hr' := hr right (by simp) + exact ⟨⟨by omega, by omega⟩, fun r h => hr r (by simp [h])⟩ + +theorem tokensSteps_le (tokens : List Token) (current : Nat) (roots : List Nat) (R : Nat) + (hq : current + tokens.length ≤ R) (hr : RootsBounded R roots) + (ht : ∀ token ∈ tokens, TokenBounded R token) : + tokensSteps current roots tokens ≤ tokens.length * (12 * R + 25) := by + induction tokens generalizing current roots with + | nil => simp [tokensSteps] + | cons token tokens ih => + cases htake : token.takeGate roots with + | none => simp [tokensSteps, htake] + | some pair => + rcases pair with ⟨gate, rest⟩ + have hc : current ≤ R := by simp only [List.length_cons] at hq; omega + have hb := takeGate_bounds token roots gate rest R (ht token (by simp)) hr htake + have hs := tokenSteps_le current R token gate hc (ht token (by simp)) hb.1 + have hroots : RootsBounded R (current :: rest) := by + intro r h + rcases List.mem_cons.mp h with rfl | h + · exact hc + · exact hb.2 r h + have hi := ih (current + 1) (current :: rest) (by + simp only [List.length_cons] at hq + omega) hroots (fun t h => ht t (by simp [h])) + simp only [tokensSteps, htake, List.length_cons] + calc + _ ≤ (1 + (12 * R + 24)) + tokens.length * (12 * R + 25) := + Nat.add_le_add (Nat.add_le_add_left hs 1) hi + _ = _ := by ring + +theorem exprTokens_bounded {ι : Type*} (wire : ι → Nat) (e : Expr ι) (R : Nat) + (hw : ∀ i, wire i ≤ R) : ∀ token ∈ exprTokens wire e, TokenBounded R token := by + induction e with + | input i => simp [exprTokens, TokenBounded, hw] + | const b => simp [exprTokens, TokenBounded] + | not e ih => + intro token ht + simp only [exprTokens, List.mem_append, List.mem_singleton] at ht + rcases ht with ht | rfl + · exact ih token ht + · trivial + | and e f ihe ihf => + intro token ht + simp only [exprTokens, List.mem_append, List.mem_singleton, or_assoc] at ht + rcases ht with ht | ht | rfl + · exact ihe token ht + · exact ihf token ht + · trivial + | or e f ihe ihf => + intro token ht + simp only [exprTokens, List.mem_append, List.mem_singleton, or_assoc] at ht + rcases ht with ht | ht | rfl + · exact ihe token ht + · exact ihf token ht + · trivial + +theorem forestTokens_bounded {ι : Type*} (wire : ι → Nat) (es : List (Expr ι)) (R : Nat) + (hw : ∀ i, wire i ≤ R) : ∀ token ∈ forestTokens wire es, TokenBounded R token := by + intro token ht + obtain ⟨e, _, he⟩ := List.mem_flatMap.mp ht + exact exprTokens_bounded wire e R hw token he + +theorem forest_tokensSteps_le {ι : Type*} (wire : ι → Nat) (es : List (Expr ι)) + (start : Nat) (roots : List Nat) (hw : ∀ i, wire i < start) + (hr : RootsBounded (start + Batch.cost es) roots) : + tokensSteps start roots (forestTokens wire es) ≤ + Batch.cost es * (12 * (start + Batch.cost es) + 25) := by + have h := tokensSteps_le (forestTokens wire es) start roots (start + Batch.cost es) + (by simpa only [forestTokens_length] using Nat.le_refl (start + Batch.cost es)) hr + (forestTokens_bounded wire es _ (fun i => by have := hw i; omega)) + simpa only [forestTokens_length] using h + +theorem forest_recordsBits_length_le {ι : Type*} (wire : ι → Nat) (es : List (Expr ι)) + (start : Nat) (hw : ∀ i, wire i < start) : + (recordsBits (gateRecords start (Batch.gates wire start es))).length ≤ + 4 * Batch.cost es * (start + Batch.cost es + 5) := by + have h := encodeWords_length_le + (recordsWords (gateRecords start (Batch.gates wire start es))) + (start + (Batch.gates wire start es).length + 4) + (gateRecords_fields_le start _ (Batch.gates_ordered wire start es hw)) + simpa only [recordsBits, recordsWords_length, gateRecords_length, Batch.gates_length, + Nat.add_assoc] using h + +theorem forest_phases_le {ι : Type*} (wire : ι → Nat) (es : List (Expr ι)) + (start : Nat) (roots : List Nat) (hw : ∀ i, wire i < start) + (hr : RootsBounded (start + Batch.cost es) roots) : + start + (forestTokens wire es).length + 4 + + tokensSteps start roots (forestTokens wire es) + + (recordsBits (gateRecords start (Batch.gates wire start es))).length + 3 ≤ + start + Batch.cost es + 7 + Batch.cost es * (16 * (start + Batch.cost es) + 45) := by + have ht := forest_tokensSteps_le wire es start roots hw hr + have hg := forest_recordsBits_length_le wire es start hw + rw [forestTokens_length] + calc + _ ≤ start + Batch.cost es + 4 + + (Batch.cost es * (12 * (start + Batch.cost es) + 25)) + + (4 * Batch.cost es * (start + Batch.cost es + 5)) + 3 := by omega + _ = _ := by ring + +theorem forest_header_le_input_length {ι : Type*} (wire : ι → Nat) (es : List (Expr ι)) + (start : Nat) : + start + Batch.cost es + 2 ≤ (PostfixModel.inputBits start (forestTokens wire es)).length := by + rw [forest_inputBits, List.length_append] + simp only [encodeWords, List.length_append, encodeWord_length, List.length_nil] + omega + +theorem forest_phases_le_input_quadratic {ι : Type*} (wire : ι → Nat) (es : List (Expr ι)) + (start : Nat) (roots : List Nat) (hw : ∀ i, wire i < start) + (hr : RootsBounded (start + Batch.cost es) roots) : + let m := (PostfixModel.inputBits start (forestTokens wire es)).length + start + (forestTokens wire es).length + 4 + + tokensSteps start roots (forestTokens wire es) + + (recordsBits (gateRecords start (Batch.gates wire start es))).length + 3 ≤ + m + 7 + m * (16 * m + 45) := by + dsimp only + have hm := forest_header_le_input_length wire es start + apply (forest_phases_le wire es start roots hw hr).trans + apply Nat.add_le_add + · omega + · apply Nat.mul_le_mul + · omega + · omega + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.PostfixBounds + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/PostfixMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/PostfixMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..ca86f924af8aece81063be192b1db2c631ced434 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/PostfixMachine.lean @@ -0,0 +1,868 @@ +import Mathlib.Tactic.DeriveFintype +import Mathlib.Tactic.FinCases +import OAI.Computability.PerfectCompleteness.Machines.PositionLemmas +import OAI.Computability.UniqueGames.Machines.MachineCopy +import OAI.Computability.UniqueGames.Machines.MachineDrain +import OAI.Computability.UniqueGames.Machines.MachineInitialHeaders +import OAI.Computability.UniqueGames.Machines.MachineLemmas +import OAI.Computability.UniqueGames.PCP.SourceMachine + +namespace OAI + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.PostfixMachine + +open Turing PostfixModel Hastad + + +inductive Tape + | input | current | remaining | roots | left | right | reversed | output | scratch + deriving DecidableEq + +protected abbrev Tape.enumList : List Tape := [.input, .current, .remaining, .roots, .left, + .right, .reversed, .output, .scratch] + +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 + +abbrev Alphabet (_ : Tape) := Bool +abbrev State := Unit × Option Bool + +inductive Label + | headerStart (slot : Fin 2) | headerLoop (slot : Fin 2) + | guard | decode + | readStart (tag : Fin 6) (pass : Fin 2) | readLoop (tag : Fin 6) (pass : Fin 2) + | emitTag (tag : Fin 6) + | field (tag : Fin 6) (slot : Fin 3) + | restore (tag : Fin 6) (slot : Fin 3) + | closeField (tag : Fin 6) (slot : Fin 3) + | rootDrain | rootFork | increment | clearLeft | clearRight | finish | finalReverse + deriving DecidableEq, Fintype + +def initialState : State := ((), none) + +def headerTape (slot : Fin 2) : Tape := if slot.val = 0 then .current else .remaining + +def binary (tag : Fin 6) : Bool := decide (tag.val = 3 ∨ tag.val = 4) + +def readSource (tag : Fin 6) : Tape := if tag.val = 5 then .input else .roots + +def readDestination (tag : Fin 6) (pass : Fin 2) : Tape := + if binary tag && decide (pass.val = 0) then .right else .left + +def readNext (tag : Fin 6) (pass : Fin 2) : Label := + if binary tag && decide (pass.val = 0) then .readStart tag 1 else .emitTag tag + +def prepare (tag : Fin 6) : Label := + if tag.val < 2 then .emitTag tag else .readStart tag 0 + +def gateTag (tag : Fin 6) : Nat := if tag.val = 5 then 4 else tag.val + +def fieldSource (tag : Fin 6) (slot : Fin 3) : Tape := + if slot.val = 0 then .current + else if slot.val = 1 ∨ tag.val = 5 then .left else .right + +def fieldUnused (tag : Fin 6) (slot : Fin 3) : Bool := + decide (slot.val ≠ 0 ∧ (tag.val < 2 ∨ (tag.val = 2 ∧ slot.val = 2))) + +def fieldNext (tag : Fin 6) (slot : Fin 3) : Label := + if h : slot.val + 1 < 3 then .field tag ⟨slot.val + 1, h⟩ else .rootDrain + +def resetGoto (label : Label) : TM2.Stmt Alphabet Label State := + .load (fun _ => initialState) (.goto fun _ => label) + +def tagDecoder : Nat → Fin 6 → TM2.Stmt Alphabet Label State + | 0, tag => .pop .input (fun state head => (state.1, head)) + (.branch (fun state => state.2.getD false) (.halt) (resetGoto (prepare tag))) + | fuel + 1, tag => .pop .input (fun state head => (state.1, head)) + (.branch (fun state => state.2.getD false) + (tagDecoder fuel ⟨min (tag.val + 1) 5, by omega⟩) (resetGoto (prepare tag))) + +def program : Label → TM2.Stmt Alphabet Label State + | .headerStart slot => SourceMachine.fieldStart (headerTape slot) (.headerLoop slot) + | .headerLoop slot => SourceMachine.fieldLoop .input (headerTape slot) (.headerLoop slot) + (some (if slot.val = 0 then .headerStart 1 else .guard)) + | .guard => MachineUnaryCounter.guard .remaining .decode .finish + | .decode => tagDecoder 5 0 + | .readStart tag pass => SourceMachine.fieldStart (readDestination tag pass) (.readLoop tag pass) + | .readLoop tag pass => SourceMachine.fieldLoop (readSource tag) (readDestination tag pass) + (.readLoop tag pass) (some (readNext tag pass)) + | .emitTag tag => Reduction.MachineSubstitution.pushWord .reversed (encodeWord (gateTag tag)) + (.goto fun _ => .field tag 0) + | .field tag slot => + if fieldUnused tag slot then + .push .reversed (fun _ => false) (.goto fun _ => fieldNext tag slot) + else MachineInitialHeaders.prefixScan (fieldSource tag slot) .scratch .reversed 1 + (.field tag slot) (.restore tag slot) + | .restore tag slot => Reduction.MachineTransfer.loopAt .scratch (fieldSource tag slot) + id false (.restore tag slot) (some (.closeField tag slot)) + | .closeField tag slot => .push .reversed (fun _ => false) (.goto fun _ => fieldNext tag slot) + | .rootDrain => Reduction.MachineTransfer.loopAt .current .scratch id false + .rootDrain (some .rootFork) + | .rootFork => MachineCopy.forkLoop .scratch .current .roots false .rootFork (some .increment) + | .increment => .push .current (fun _ => true) (.goto fun _ => .clearLeft) + | .clearLeft => MachineDrain.drain .left .clearLeft (some .clearRight) + | .clearRight => MachineDrain.drain .right .clearRight (some .guard) + | .finish => .pop .remaining (fun _ _ => initialState) (.goto fun _ => .finalReverse) + | .finalReverse => Reduction.MachineTransfer.loopAt .reversed .output id false .finalReverse none + +def machine : FinTM2 where + K := Tape + k₀ := .input + k₁ := .output + Γ := Alphabet + Λ := Label + main := .headerStart 0 + σ := State + initialState := initialState + m := program + +private abbrev advance := MachineComposition.advance (TM2.step program) + +def outputTapes (base : Tape → List Bool) (bits : List Bool) : Tape → List Bool := + Function.update base .reversed (bits ++ base .reversed) + +@[simp] theorem outputTapes_reversed (base : Tape → List Bool) (bits : List Bool) : + outputTapes base bits .reversed = bits ++ base .reversed := by simp [outputTapes] + +theorem outputTapes_other (base : Tape → List Bool) (bits : List Bool) (tape : Tape) + (h : tape ≠ .reversed) : outputTapes base bits tape = base tape := by + simp [outputTapes, h] + +@[simp] theorem outputTapes_twice (base : Tape → List Bool) (first second : List Bool) : + outputTapes (outputTapes base first) second = outputTapes base (second ++ first) := by + funext tape + by_cases h : tape = .reversed + · subst tape; simp [List.append_assoc] + · simp [outputTapes, h] + +private theorem trace_trans {α : Type*} (f : α → α) {a b : ℕ} {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 readSource_ne_destination (tag : Fin 6) (pass : Fin 2) : + readSource tag ≠ readDestination tag pass := by + unfold readSource readDestination + split <;> split <;> decide + +theorem fieldSource_ne_scratch (tag : Fin 6) (slot : Fin 3) : + fieldSource tag slot ≠ .scratch := by + unfold fieldSource + split <;> first | decide | (split <;> decide) + +theorem fieldSource_ne_reversed (tag : Fin 6) (slot : Fin 3) : + fieldSource tag slot ≠ .reversed := by + unfold fieldSource + split <;> first | decide | (split <;> decide) + +theorem decodeTrace (tag : Fin 6) (base : Tape → List Bool) (suffix : List Bool) + (hinput : base .input = encodeWord tag.val ++ suffix) : + advance^[1] (some ⟨some .decode, initialState, base⟩) = + some ⟨some (prepare tag), initialState, Function.update base .input suffix⟩ := by + change some (TM2.stepAux (program .decode) initialState base) = _ + fin_cases tag <;> + simp [program, tagDecoder, TM2.stepAux, hinput, encodeWord, resetGoto, initialState] + +theorem readTrace (tag : Fin 6) (pass : Fin 2) (base : Tape → List Bool) + (value : Nat) (suffix : List Bool) + (hinput : base (readSource tag) = encodeWord value ++ suffix) : + advance^[value + 2] (some ⟨some (.readStart tag pass), initialState, base⟩) = + some ⟨some (readNext tag pass), initialState, + SourceMachine.fieldTapes (readSource tag) (readDestination tag pass) base suffix + (encodeWord value ++ base (readDestination tag pass))⟩ := by + have h := (SourceMachine.fieldInTime (K := Tape) (Λ := Label) (σ := Unit) + (readSource tag) (readDestination tag pass) + (readSource_ne_destination tag pass) (.readStart tag pass) (.readLoop tag pass) + (some (readNext tag pass)) program rfl rfl base value suffix hinput () none).evals_in_steps + change advance^[value + 2] + (some ⟨some (.readStart tag pass), initialState, base⟩) = + some ⟨some (readNext tag pass), initialState, + SourceMachine.fieldTapes (readSource tag) (readDestination tag pass) base suffix + (encodeWord value ++ base (readDestination tag pass))⟩ at h + exact h + +theorem emitTagTrace (tag : Fin 6) (base : Tape → List Bool) : + advance^[1] (some ⟨some (.emitTag tag), initialState, base⟩) = + some ⟨some (.field tag 0), initialState, + outputTapes base (encodeWord (gateTag tag)).reverse⟩ := + MachineInitialHeaders.literalTrace .reversed (encodeWord (gateTag tag)) + (.emitTag tag) (some (.field tag 0)) program rfl base () none + +def FieldReady (tag : Fin 6) (slot : Fin 3) (base : Tape → List Bool) (value : Nat) : Prop := + (fieldUnused tag slot = true → value = 0) ∧ + (fieldUnused tag slot = false → base (fieldSource tag slot) = encodeWord value) + +theorem FieldReady.output (tag : Fin 6) (slot : Fin 3) (base : Tape → List Bool) + (value : Nat) (h : FieldReady tag slot base value) (bits : List Bool) : + FieldReady tag slot (outputTapes base bits) value := by + refine ⟨h.1, ?_⟩ + intro used + rw [outputTapes_other base bits _ (fieldSource_ne_reversed tag slot)] + exact h.2 used + +def fieldSteps (tag : Fin 6) (slot : Fin 3) (value : Nat) : Nat := + if fieldUnused tag slot then 1 else 2 * value + 3 + +theorem fieldTrace (tag : Fin 6) (slot : Fin 3) (base : Tape → List Bool) + (value : Nat) (ready : FieldReady tag slot base value) (hscratch : base .scratch = []) : + advance^[fieldSteps tag slot value] + (some ⟨some (.field tag slot), initialState, base⟩) = + some ⟨some (fieldNext tag slot), initialState, + outputTapes base (encodeWord value).reverse⟩ := by + cases hu : fieldUnused tag slot with + | true => + have hz := ready.1 hu + subst value + simp only [fieldSteps, hu, ↓reduceIte] + change some (TM2.stepAux (program (.field tag slot)) initialState base) = _ + simp only [program, hu, ↓reduceIte, TM2.stepAux, encodeWord, List.replicate_zero, + List.nil_append, List.reverse_singleton, outputTapes, List.singleton_append] + | false => + have hcopy := (MachineInitialHeaders.prefixInTime (fieldSource tag slot) .scratch .reversed + (fieldSource_ne_scratch tag slot) (fieldSource_ne_reversed tag slot) (by decide) + 1 (.field tag slot) (.restore tag slot) (some (.closeField tag slot)) program + (by simp only [program, hu, Bool.false_eq_true, ↓reduceIte]) rfl base value [] + (by simpa using ready.2 hu) hscratch () none).evals_in_steps + let copied := outputTapes base (List.replicate value true) + change advance^[2 * value + 2] + (some ⟨some (.field tag slot), initialState, base⟩) = + some ⟨some (.closeField tag slot), initialState, + outputTapes base (List.replicate (1 * value) true)⟩ at hcopy + simp only [Nat.one_mul] at hcopy + have hclose : advance^[1] + (some ⟨some (.closeField tag slot), initialState, copied⟩) = + some ⟨some (fieldNext tag slot), initialState, outputTapes copied [false]⟩ := by + change some (TM2.stepAux (program (.closeField tag slot)) initialState copied) = _ + rfl + have total := trace_trans _ hcopy hclose + simpa only [fieldSteps, hu, Bool.false_eq_true, ↓reduceIte, copied, outputTapes_twice, + encodeWord, List.reverse_append, List.reverse_singleton, List.reverse_replicate, + show 2 * value + 2 + 1 = 2 * value + 3 by omega] using total + +theorem rootPushTrace (base : Tape → List Bool) (current : Nat) + (hcurrent : base .current = encodeWord current) (hscratch : base .scratch = []) : + advance^[2 * current + 4] + (some ⟨some .rootDrain, initialState, base⟩) = + some ⟨some .increment, initialState, + Function.update base .roots (encodeWord current ++ base .roots)⟩ := by + have h := MachineCopy.copyTrace Tape.current Tape.roots Tape.scratch + (by decide) (by decide) (by decide) false .rootDrain .rootFork (some .increment) + program rfl rfl base hscratch () none + simpa only [hcurrent, encodeWord_length, advance, initialState, + show 2 * (current + 1 + 1) = 2 * current + 4 by omega] using h + +theorem incrementTrace (base : Tape → List Bool) (current : Nat) + (hcurrent : base .current = encodeWord current) : + advance^[1] (some ⟨some .increment, initialState, base⟩) = + some ⟨some .clearLeft, initialState, + Function.update base .current (encodeWord (current + 1))⟩ := by + change some (TM2.stepAux (program .increment) initialState base) = _ + simp only [program, TM2.stepAux, hcurrent, encodeWord, List.replicate_succ, + List.cons_append] + +def recordSteps (tag : Fin 6) (values : Fin 3 → Nat) : Nat := + 1 + fieldSteps tag 0 (values 0) + fieldSteps tag 1 (values 1) + fieldSteps tag 2 (values 2) + +theorem recordTrace (tag : Fin 6) (base : Tape → List Bool) (values : Fin 3 → Nat) + (ready : ∀ slot, FieldReady tag slot base (values slot)) (hscratch : base .scratch = []) : + advance^[recordSteps tag values] + (some ⟨some (.emitTag tag), initialState, base⟩) = + some ⟨some .rootDrain, initialState, + outputTapes base (encodeWords [gateTag tag, values 0, values 1, values 2]).reverse⟩ := by + let first := outputTapes base (encodeWord (gateTag tag)).reverse + let second := outputTapes first (encodeWord (values 0)).reverse + let third := outputTapes second (encodeWord (values 1)).reverse + have readyFirst : ∀ slot, FieldReady tag slot first (values slot) := + fun slot => FieldReady.output tag slot base (values slot) (ready slot) + (encodeWord (gateTag tag)).reverse + have readySecond : ∀ slot, FieldReady tag slot second (values slot) := + fun slot => FieldReady.output tag slot first (values slot) (readyFirst slot) + (encodeWord (values 0)).reverse + have readyThird : ∀ slot, FieldReady tag slot third (values slot) := + fun slot => FieldReady.output tag slot second (values slot) (readySecond slot) + (encodeWord (values 1)).reverse + have ht := emitTagTrace tag base + have h0 := fieldTrace tag 0 first (values 0) (readyFirst 0) + (by simpa [first, outputTapes] using hscratch) + have h1 := fieldTrace tag 1 second (values 1) (readySecond 1) + (by simpa [second, first, outputTapes] using hscratch) + have h2 := fieldTrace tag 2 third (values 2) (readyThird 2) + (by simpa [third, second, first, outputTapes] using hscratch) + change advance^[fieldSteps tag 0 (values 0)] + (some ⟨some (.field tag 0), initialState, first⟩) = + some ⟨some (.field tag 1), initialState, second⟩ at h0 + change advance^[fieldSteps tag 1 (values 1)] + (some ⟨some (.field tag 1), initialState, second⟩) = + some ⟨some (.field tag 2), initialState, third⟩ at h1 + change advance^[fieldSteps tag 2 (values 2)] + (some ⟨some (.field tag 2), initialState, third⟩) = + some ⟨some .rootDrain, initialState, + outputTapes third (encodeWord (values 2)).reverse⟩ at h2 + have total := trace_trans _ (trace_trans _ (trace_trans _ ht h0) h1) h2 + simpa only [recordSteps, third, second, first, outputTapes_twice, encodeWords, + List.append_nil, List.reverse_append, List.append_assoc] using total + +def clearTapes (base : Tape → List Bool) : Tape → List Bool := + Function.update (Function.update base .left []) .right [] + +theorem clearTrace (base : Tape → List Bool) : + advance^[(base .left).length + (base .right).length + 2] + (some ⟨some .clearLeft, initialState, base⟩) = + some ⟨some .guard, initialState, clearTapes base⟩ := by + let first := Function.update base .left [] + have h1 := (MachineDrain.drainInTime Tape.left .clearLeft (some .clearRight) + program rfl base () none).evals_in_steps + have h2 := (MachineDrain.drainInTime Tape.right .clearRight (some .guard) + program rfl first () none).evals_in_steps + change advance^[(base .left).length + 1] + (some ⟨some .clearLeft, initialState, base⟩) = + some ⟨some .clearRight, initialState, first⟩ at h1 + change advance^[(first .right).length + 1] + (some ⟨some .clearRight, initialState, first⟩) = + some ⟨some .guard, initialState, clearTapes base⟩ at h2 + have total := trace_trans _ h1 h2 + simpa only [first, Function.update_of_ne (by decide : Tape.right ≠ .left), + show (base .left).length + 1 + ((base .right).length + 1) = + (base .left).length + (base .right).length + 2 by omega] using total + +def finishTapes (base : Tape → List Bool) (current : Nat) : Tape → List Bool := + clearTapes (Function.update + (Function.update base .roots (encodeWord current ++ base .roots)) + .current (encodeWord (current + 1))) + +theorem finishNodeTrace (base : Tape → List Bool) (current : Nat) + (hcurrent : base .current = encodeWord current) (hscratch : base .scratch = []) : + advance^[2 * current + (base .left).length + (base .right).length + 7] + (some ⟨some .rootDrain, initialState, base⟩) = + some ⟨some .guard, initialState, finishTapes base current⟩ := by + let pushed := Function.update base .roots (encodeWord current ++ base .roots) + let incremented := Function.update pushed .current (encodeWord (current + 1)) + have h1 := rootPushTrace base current hcurrent hscratch + have h2 := incrementTrace pushed current (by simpa [pushed] using hcurrent) + have h3 := clearTrace incremented + have total := trace_trans _ (trace_trans _ h1 h2) h3 + simpa only [finishTapes, incremented, pushed, + Function.update_of_ne (by decide : Tape.left ≠ .current), + Function.update_of_ne (by decide : Tape.right ≠ .current), + Function.update_of_ne (by decide : Tape.left ≠ .roots), + Function.update_of_ne (by decide : Tape.right ≠ .roots), + show (2 * current + 4) + 1 + ((base .left).length + (base .right).length + 2) = + 2 * current + (base .left).length + (base .right).length + 7 by omega] using total + +theorem emitPreparedTrace (tag : Fin 6) (base : Tape → List Bool) + (current : Nat) (gate : Gate) + (htag : gateTag tag = (gateRecord current gate).tag.val) + (ready : ∀ slot, FieldReady tag slot base ((gateRecord current gate).slot slot)) + (hcurrent : base .current = encodeWord current) (hscratch : base .scratch = []) : + advance^[recordSteps tag (gateRecord current gate).slot + + (2 * current + (base .left).length + (base .right).length + 7)] + (some ⟨some (.emitTag tag), initialState, base⟩) = + some ⟨some .guard, initialState, + finishTapes (outputTapes base (gateRecord current gate).bits.reverse) current⟩ := by + have hrecord := recordTrace tag base (gateRecord current gate).slot ready hscratch + have hwords : [gateTag tag, (gateRecord current gate).slot 0, + (gateRecord current gate).slot 1, (gateRecord current gate).slot 2] = + (gateRecord current gate).words := by + rw [htag] + rfl + rw [hwords] at hrecord + let emitted := outputTapes base (gateRecord current gate).bits.reverse + have hfinish := finishNodeTrace emitted current + (by simpa [emitted, outputTapes] using hcurrent) + (by simpa [emitted, outputTapes] using hscratch) + have total := trace_trans _ hrecord hfinish + simpa only [emitted, outputTapes_other base _ .left (by decide), + outputTapes_other base _ .right (by decide)] using total + +def boundaryTapes (base : Tape → List Bool) (current : Nat) + (roots : List Nat) (input : List Bool) : Tape → List Bool + | .input => input + | .current => encodeWord current + | .roots => encodeWords roots + | .left | .right | .scratch => [] + | tape => base tape + +def preparedTapes (base : Tape → List Bool) (current : Nat) + (roots : List Nat) (input left right : List Bool) : Tape → List Bool + | .input => input + | .current => encodeWord current + | .roots => encodeWords roots + | .left => left + | .right => right + | .scratch => [] + | tape => base tape + +def operandFields : Token → Gate → List Bool × List Bool + | .const _, _ => ([], []) + | .input wire, _ => (encodeWord wire, []) + | .not, .not arg => (encodeWord arg, []) + | .and, .and left right | .or, .or left right => (encodeWord left, encodeWord right) + | _, _ => ([], []) + +def operandSteps : Token → Gate → Nat + | .const _, _ => 0 + | .input wire, _ => wire + 2 + | .not, .not arg => arg + 2 + | .and, .and left right | .or, .or left right => left + right + 4 + | _, _ => 0 + +def tokenSteps (current : Nat) (token : Token) (gate : Gate) : Nat := + 1 + operandSteps token gate + recordSteps token.tag (gateRecord current gate).slot + + (2 * current + (operandFields token gate).1.length + + (operandFields token gate).2.length + 7) + +def tokensSteps (current : Nat) (roots : List Nat) : List Token → Nat + | [] => 0 + | token :: tokens => match token.takeGate roots with + | none => 0 + | some (gate, rest) => + 1 + tokenSteps current token gate + tokensSteps (current + 1) (current :: rest) tokens + +def argumentBits : Token → List Bool + | .input wire => encodeWord wire + | _ => [] + +theorem token_bits (token : Token) : token.bits = encodeWord token.tag.val ++ argumentBits token := by + cases token with + | const value => cases value <;> simp [Token.bits, Token.words, Token.tag, argumentBits, encodeWords] + | not | and | or | input _ => simp [Token.bits, Token.words, Token.tag, argumentBits, encodeWords] + +theorem prepareInputTrace (base : Tape → List Bool) (current wire : Nat) + (roots : List Nat) (suffix : List Bool) : + advance^[wire + 2] + (some ⟨some (.readStart 5 0), initialState, + boundaryTapes base current roots (encodeWord wire ++ suffix)⟩) = + some ⟨some (.emitTag 5), initialState, + preparedTapes base current roots suffix (encodeWord wire) []⟩ := by + let first := boundaryTapes base current roots (encodeWord wire ++ suffix) + have h := readTrace 5 0 first wire suffix rfl + have hout : SourceMachine.fieldTapes (readSource 5) (readDestination 5 0) first suffix + (encodeWord wire ++ first (readDestination 5 0)) = + preparedTapes base current roots suffix (encodeWord wire) [] := by + funext tape + cases tape <;> simp [SourceMachine.fieldTapes, first, boundaryTapes, preparedTapes, + readSource, readDestination, binary] + rw [hout] at h + exact h + +theorem prepareUnaryTrace (base : Tape → List Bool) (current arg : Nat) + (roots : List Nat) (suffix : List Bool) : + advance^[arg + 2] + (some ⟨some (.readStart 2 0), initialState, + boundaryTapes base current (arg :: roots) suffix⟩) = + some ⟨some (.emitTag 2), initialState, + preparedTapes base current roots suffix (encodeWord arg) []⟩ := by + let first := boundaryTapes base current (arg :: roots) suffix + have h := readTrace 2 0 first arg (encodeWords roots) rfl + have hout : SourceMachine.fieldTapes (readSource 2) (readDestination 2 0) first + (encodeWords roots) (encodeWord arg ++ first (readDestination 2 0)) = + preparedTapes base current roots suffix (encodeWord arg) [] := by + funext tape + cases tape <;> simp [SourceMachine.fieldTapes, first, boundaryTapes, preparedTapes, + readSource, readDestination, binary] + rw [hout] at h + exact h + +theorem prepareBinaryTrace (tag : Fin 6) (hb : binary tag = true) (hinput : tag.val ≠ 5) + (base : Tape → List Bool) (current left right : Nat) (roots : List Nat) (suffix : List Bool) : + advance^[left + right + 4] + (some ⟨some (.readStart tag 0), initialState, + boundaryTapes base current (right :: left :: roots) suffix⟩) = + some ⟨some (.emitTag tag), initialState, + preparedTapes base current roots suffix (encodeWord left) (encodeWord right)⟩ := by + let first := boundaryTapes base current (right :: left :: roots) suffix + let second := preparedTapes base current (left :: roots) suffix [] (encodeWord right) + have h1 := readTrace tag 0 first right (encodeWords (left :: roots)) + (by simp [first, readSource, hinput, boundaryTapes, encodeWords]) + have frame1 : SourceMachine.fieldTapes (readSource tag) (readDestination tag 0) first + (encodeWords (left :: roots)) (encodeWord right ++ first (readDestination tag 0)) = second := by + funext tape + cases tape <;> simp [SourceMachine.fieldTapes, first, second, boundaryTapes, preparedTapes, + readSource, readDestination, hb, hinput] + rw [frame1] at h1 + have h2 := readTrace tag 1 second left (encodeWords roots) + (by simp [second, readSource, hinput, preparedTapes, encodeWords]) + have frame2 : SourceMachine.fieldTapes (readSource tag) (readDestination tag 1) second + (encodeWords roots) (encodeWord left ++ second (readDestination tag 1)) = + preparedTapes base current roots suffix (encodeWord left) (encodeWord right) := by + funext tape + cases tape <;> simp [SourceMachine.fieldTapes, second, preparedTapes, + readSource, readDestination, hb, hinput] + rw [frame2] at h2 + simp only [readNext, hb, Fin.val_zero, Fin.val_one, decide_true, Bool.and_true, + Nat.one_ne_zero, decide_false, Bool.and_false, Bool.false_eq_true, ↓reduceIte] at h1 h2 + have total := trace_trans _ h1 h2 + simpa only [show (right + 2) + (left + 2) = left + right + 4 by omega] using total + +theorem prepareTrace (base : Tape → List Bool) (current : Nat) (token : Token) + (roots rest : List Nat) (gate : Gate) (suffix : List Bool) + (htake : token.takeGate roots = some (gate, rest)) : + advance^[operandSteps token gate] + (some ⟨some (prepare token.tag), initialState, + boundaryTapes base current roots (argumentBits token ++ suffix)⟩) = + some ⟨some (.emitTag token.tag), initialState, + preparedTapes base current rest suffix + (operandFields token gate).1 (operandFields token gate).2⟩ := by + cases token with + | const value => + simp only [Token.takeGate, Option.some.injEq, Prod.mk.injEq] at htake + rcases htake with ⟨rfl, rfl⟩ + cases value <;> + simp [Token.tag, operandSteps, operandFields, argumentBits, prepare] <;> + funext tape <;> cases tape <;> rfl + | input wire => + simp only [Token.takeGate, Option.some.injEq, Prod.mk.injEq] at htake + rcases htake with ⟨rfl, rfl⟩ + simpa [Token.tag, operandSteps, operandFields, argumentBits, prepare] using + prepareInputTrace base current wire roots suffix + | not => + cases roots with + | nil => simp [Token.takeGate] at htake + | cons arg roots => + simp only [Token.takeGate, Option.some.injEq, Prod.mk.injEq] at htake + rcases htake with ⟨rfl, rfl⟩ + simpa [Token.tag, operandSteps, operandFields, argumentBits, prepare] using + prepareUnaryTrace base current arg roots suffix + | and => + cases roots with + | nil => simp [Token.takeGate] at htake + | cons right roots => + cases roots with + | nil => simp [Token.takeGate] at htake + | cons left roots => + simp only [Token.takeGate, Option.some.injEq, Prod.mk.injEq] at htake + rcases htake with ⟨rfl, rfl⟩ + simpa [Token.tag, operandSteps, operandFields, argumentBits, prepare] using + prepareBinaryTrace 3 (by decide) (by decide) base current left right roots suffix + | or => + cases roots with + | nil => simp [Token.takeGate] at htake + | cons right roots => + cases roots with + | nil => simp [Token.takeGate] at htake + | cons left roots => + simp only [Token.takeGate, Option.some.injEq, Prod.mk.injEq] at htake + rcases htake with ⟨rfl, rfl⟩ + simpa [Token.tag, operandSteps, operandFields, argumentBits, prepare] using + prepareBinaryTrace 4 (by decide) (by decide) base current left right roots suffix + +theorem preparedReady (base : Tape → List Bool) (current : Nat) (token : Token) + (roots rest : List Nat) (gate : Gate) (suffix : List Bool) + (htake : token.takeGate roots = some (gate, rest)) : + gateTag token.tag = (gateRecord current gate).tag.val ∧ + ∀ slot, FieldReady token.tag slot + (preparedTapes base current rest suffix + (operandFields token gate).1 (operandFields token gate).2) + ((gateRecord current gate).slot slot) := by + cases token with + | const value => + simp only [Token.takeGate, Option.some.injEq, Prod.mk.injEq] at htake + rcases htake with ⟨rfl, rfl⟩ + cases value <;> refine ⟨rfl, ?_⟩ <;> intro slot <;> fin_cases slot <;> + simp [FieldReady, Token.tag, fieldUnused, fieldSource, preparedTapes, operandFields, + gateRecord, CircuitProducerModel.Record.slot] + | input wire => + simp only [Token.takeGate, Option.some.injEq, Prod.mk.injEq] at htake + rcases htake with ⟨rfl, rfl⟩ + refine ⟨rfl, ?_⟩ + intro slot + fin_cases slot <;> simp [FieldReady, Token.tag, fieldUnused, fieldSource, preparedTapes, + operandFields, gateRecord, CircuitProducerModel.Record.slot] + | not => + cases roots with + | nil => simp [Token.takeGate] at htake + | cons arg roots => + simp only [Token.takeGate, Option.some.injEq, Prod.mk.injEq] at htake + rcases htake with ⟨rfl, rfl⟩ + refine ⟨rfl, ?_⟩ + intro slot + fin_cases slot <;> simp [FieldReady, Token.tag, fieldUnused, fieldSource, preparedTapes, + operandFields, gateRecord, CircuitProducerModel.Record.slot] + | and => + cases roots with + | nil => simp [Token.takeGate] at htake + | cons right roots => + cases roots with + | nil => simp [Token.takeGate] at htake + | cons left roots => + simp only [Token.takeGate, Option.some.injEq, Prod.mk.injEq] at htake + rcases htake with ⟨rfl, rfl⟩ + refine ⟨rfl, ?_⟩ + intro slot + fin_cases slot <;> simp [FieldReady, Token.tag, fieldUnused, fieldSource, preparedTapes, + operandFields, gateRecord, CircuitProducerModel.Record.slot] + | or => + cases roots with + | nil => simp [Token.takeGate] at htake + | cons right roots => + cases roots with + | nil => simp [Token.takeGate] at htake + | cons left roots => + simp only [Token.takeGate, Option.some.injEq, Prod.mk.injEq] at htake + rcases htake with ⟨rfl, rfl⟩ + refine ⟨rfl, ?_⟩ + intro slot + fin_cases slot <;> simp [FieldReady, Token.tag, fieldUnused, fieldSource, preparedTapes, + operandFields, gateRecord, CircuitProducerModel.Record.slot] + +theorem tokenTrace (base : Tape → List Bool) (current : Nat) (token : Token) + (roots rest : List Nat) (gate : Gate) (suffix : List Bool) + (htake : token.takeGate roots = some (gate, rest)) : + advance^[tokenSteps current token gate] + (some ⟨some .decode, initialState, + boundaryTapes base current roots (token.bits ++ suffix)⟩) = + some ⟨some .guard, initialState, + boundaryTapes (outputTapes base (gateRecord current gate).bits.reverse) + (current + 1) (current :: rest) suffix⟩ := by + let first := boundaryTapes base current roots (token.bits ++ suffix) + let decoded := boundaryTapes base current roots (argumentBits token ++ suffix) + let prepared := preparedTapes base current rest suffix + (operandFields token gate).1 (operandFields token gate).2 + have hd := decodeTrace token.tag first (argumentBits token ++ suffix) + (by simp only [first, boundaryTapes, token_bits, List.append_assoc]) + have decodedFrame : Function.update first .input (argumentBits token ++ suffix) = decoded := by + funext tape + cases tape <;> simp [first, decoded, boundaryTapes] + rw [decodedFrame] at hd + have hp := prepareTrace base current token roots rest gate suffix htake + have ready := preparedReady base current token roots rest gate suffix htake + have he := emitPreparedTrace token.tag prepared current gate ready.1 ready.2 rfl rfl + have total := trace_trans _ (trace_trans _ hd hp) he + have finishedFrame : finishTapes (outputTapes prepared (gateRecord current gate).bits.reverse) + current = boundaryTapes (outputTapes base (gateRecord current gate).bits.reverse) + (current + 1) (current :: rest) suffix := by + funext tape + cases tape <;> simp [finishTapes, clearTapes, prepared, preparedTapes, boundaryTapes, + outputTapes, encodeWords] + rw [finishedFrame] at total + simpa only [tokenSteps, first, prepared, preparedTapes, Nat.add_assoc] using total + +theorem tokenBits_cons (token : Token) (tokens : List Token) : + tokenBits (token :: tokens) = token.bits ++ tokenBits tokens := by + simp [tokenBits, tokenWords, Token.bits] + +theorem boundary_remaining (base : Tape → List Bool) (current : Nat) + (roots : List Nat) (input : List Bool) (count : Nat) : + Function.update (boundaryTapes base current roots input) .remaining (encodeWord count) = + boundaryTapes (Function.update base .remaining (encodeWord count)) current roots input := by + funext tape + cases tape <;> simp [boundaryTapes] + +theorem guardPositiveTrace (base : Tape → List Bool) (count : Nat) + (hcount : base .remaining = encodeWord (count + 1)) : + advance^[1] (some ⟨some .guard, initialState, base⟩) = + some ⟨some .decode, initialState, Function.update base .remaining (encodeWord count)⟩ := by + change some (TM2.stepAux (program .guard) initialState base) = _ + simp [program, MachineUnaryCounter.guard, TM2.stepAux, hcount, encodeWord, + List.replicate_succ, initialState] + +theorem tokensTrace (tokens : List Token) (base : Tape → List Bool) (current : Nat) + (roots : List Nat) (next : Nat) (finalRoots : List Nat) (gates : List Gate) + (suffix : List Bool) + (hcompile : compileTokens current roots tokens = some (next, finalRoots, gates)) + (hcount : base .remaining = encodeWord tokens.length) : + advance^[tokensSteps current roots tokens] + (some ⟨some .guard, initialState, + boundaryTapes base current roots (tokenBits tokens ++ suffix)⟩) = + some ⟨some .guard, initialState, + boundaryTapes + (outputTapes (Function.update base .remaining (encodeWord 0)) + (recordsBits (gateRecords current gates)).reverse) + next finalRoots suffix⟩ := by + induction tokens generalizing base current roots next finalRoots gates with + | nil => + simp only [compileTokens, Option.some.injEq, Prod.mk.injEq] at hcompile + rcases hcompile with ⟨rfl, rfl, rfl⟩ + have hsame : Function.update base .remaining (encodeWord 0) = base := by + change base .remaining = encodeWord 0 at hcount + rw [← hcount] + exact Function.update_eq_self _ _ + simp [tokensSteps, tokenBits, tokenWords, gateRecords, recordsBits, recordsWords, + encodeWords, hsame, outputTapes] + | cons token tokens ih => + cases htake : token.takeGate roots with + | none => simp [compileTokens, htake] at hcompile + | some result => + rcases result with ⟨gate, rest⟩ + cases htail : compileTokens (current + 1) (current :: rest) tokens with + | none => simp [compileTokens, htake, htail] at hcompile + | some result => + rcases result with ⟨next', finalRoots', gates'⟩ + simp [compileTokens, htake, htail] at hcompile + obtain ⟨hnext, hroots, hgates⟩ := hcompile + subst next + subst finalRoots + subst gates + let decremented := Function.update base .remaining (encodeWord tokens.length) + let following := outputTapes decremented (gateRecord current gate).bits.reverse + have hg := guardPositiveTrace + (boundaryTapes base current roots (tokenBits (token :: tokens) ++ suffix)) + tokens.length (by simpa [boundaryTapes] using hcount) + rw [boundary_remaining] at hg + have ht := tokenTrace decremented current token roots rest gate + (tokenBits tokens ++ suffix) htake + have hi := ih following (current + 1) (current :: rest) + next' finalRoots' gates' htail + (by simp [following, decremented, outputTapes]) + have hg' : advance^[1] + (some ⟨some .guard, initialState, + boundaryTapes base current roots (tokenBits (token :: tokens) ++ suffix)⟩) = + some ⟨some .decode, initialState, + boundaryTapes decremented current roots (token.bits ++ (tokenBits tokens ++ suffix))⟩ := by + simpa only [tokenBits_cons, List.append_assoc] using hg + have total := trace_trans _ (trace_trans _ hg' ht) hi + have frame : + outputTapes (Function.update following .remaining (encodeWord 0)) + (recordsBits (gateRecords (current + 1) gates')).reverse = + outputTapes (Function.update base .remaining (encodeWord 0)) + (recordsBits (gateRecords current (gate :: gates'))).reverse := by + funext tape + cases tape <;> + simp [following, decremented, outputTapes, gateRecords, recordsBits_cons, + List.reverse_append, List.append_assoc] + rw [frame] at total + simpa only [tokensSteps, htake] using total + +def initialTapes (base : Tape → List Bool) (roots : List Nat) + (input : List Bool) : Tape → List Bool + | .input => input + | .roots => encodeWords roots + | .current | .remaining | .left | .right | .scratch => [] + | tape => base tape + +theorem headersTrace (base : Tape → List Bool) (roots : List Nat) + (start count : Nat) (suffix : List Bool) : + advance^[start + count + 4] + (some ⟨some (.headerStart 0), initialState, + initialTapes base roots (encodeWords [start, count] ++ suffix)⟩) = + some ⟨some .guard, initialState, + boundaryTapes (Function.update base .remaining (encodeWord count)) start roots suffix⟩ := by + let first := initialTapes base roots (encodeWords [start, count] ++ suffix) + let second := Function.update + (Function.update first .input (encodeWord count ++ suffix)) .current (encodeWord start) + have h1 := (SourceMachine.fieldInTime Tape.input Tape.current (by decide) + (.headerStart 0) (.headerLoop 0) (some (.headerStart 1)) program rfl rfl + first start (encodeWord count ++ suffix) + (by simp [first, initialTapes, encodeWords, List.append_assoc]) () none).evals_in_steps + have frame1 : SourceMachine.fieldTapes Tape.input Tape.current first + (encodeWord count ++ suffix) (encodeWord start ++ first .current) = second := by + simp [SourceMachine.fieldTapes, first, initialTapes, second] + change advance^[start + 2] + (some ⟨some (.headerStart 0), initialState, first⟩) = + some ⟨some (.headerStart 1), initialState, + SourceMachine.fieldTapes Tape.input Tape.current first + (encodeWord count ++ suffix) (encodeWord start ++ first .current)⟩ at h1 + rw [frame1] at h1 + have h2 := (SourceMachine.fieldInTime Tape.input Tape.remaining (by decide) + (.headerStart 1) (.headerLoop 1) (some .guard) program rfl rfl + second count suffix (by simp [second]) () none).evals_in_steps + have frame2 : SourceMachine.fieldTapes Tape.input Tape.remaining second suffix + (encodeWord count ++ second .remaining) = + boundaryTapes (Function.update base .remaining (encodeWord count)) start roots suffix := by + funext tape + cases tape <;> simp [SourceMachine.fieldTapes, second, first, initialTapes, boundaryTapes] + change advance^[count + 2] + (some ⟨some (.headerStart 1), initialState, second⟩) = + some ⟨some .guard, initialState, + SourceMachine.fieldTapes Tape.input Tape.remaining second suffix + (encodeWord count ++ second .remaining)⟩ at h2 + rw [frame2] at h2 + have total := trace_trans _ h1 h2 + simpa only [show (start + 2) + (count + 2) = start + count + 4 by omega] using total + +def reversedTapes (base : Tape → List Bool) (bits : List Bool) : Tape → List Bool := + Function.update (Function.update (Function.update base .remaining []) .reversed []) + .output (bits ++ base .output) + +theorem reverseTrace (base : Tape → List Bool) (bits : List Bool) + (hzero : base .remaining = encodeWord 0) (hbits : base .reversed = bits.reverse) : + advance^[bits.length + 3] (some ⟨some .guard, initialState, base⟩) = + some ⟨none, initialState, reversedTapes base bits⟩ := by + have hguard : advance^[1] (some ⟨some .guard, initialState, base⟩) = + some ⟨some .finish, initialState, base⟩ := by + change some (TM2.stepAux (program .guard) initialState base) = _ + simp [program, MachineUnaryCounter.guard, TM2.stepAux, hzero, encodeWord, initialState] + let cleared := Function.update base .remaining [] + have hclear : advance^[1] (some ⟨some .finish, initialState, base⟩) = + some ⟨some .finalReverse, initialState, cleared⟩ := by + change some (TM2.stepAux (program .finish) initialState base) = _ + simp [program, TM2.stepAux, hzero, encodeWord, cleared, initialState] + have htransfer := (Reduction.MachineTransfer.transferAtInTime + Tape.reversed Tape.output (by decide) id false .finalReverse none program rfl + cleared () none).evals_in_steps + change advance^[(cleared .reversed).length + 1] + (some ⟨some .finalReverse, initialState, cleared⟩) = + some ⟨none, initialState, + Reduction.MachineTransfer.tapesAt .reversed .output cleared [] + ((cleared .reversed).reverse.map id ++ cleared .output)⟩ at htransfer + have hlength : (cleared .reversed).length = bits.length := by + simp [cleared, hbits] + have frame : Reduction.MachineTransfer.tapesAt Tape.reversed Tape.output cleared [] + ((cleared .reversed).reverse.map id ++ cleared .output) = reversedTapes base bits := by + simp [Reduction.MachineTransfer.tapesAt, cleared, reversedTapes, hbits] + rw [hlength, frame] at htransfer + have total := trace_trans _ (trace_trans _ hguard hclear) htransfer + simpa only [show 1 + 1 + (bits.length + 1) = bits.length + 3 by omega] using total + +def finalTapes (base : Tape → List Bool) (next : Nat) (roots : List Nat) + (suffix output : List Bool) : Tape → List Bool + | .input => suffix + | .current => encodeWord next + | .roots => encodeWords roots + | .output => output ++ base .output + | _ => [] + +theorem compileTrace (tokens : List Token) (base : Tape → List Bool) (start : Nat) + (roots : List Nat) (next : Nat) (finalRoots : List Nat) (gates : List Gate) + (suffix : List Bool) + (hcompile : compileTokens start roots tokens = some (next, finalRoots, gates)) : + advance^[start + tokens.length + 4 + tokensSteps start roots tokens + + (base .reversed).length + (recordsBits (gateRecords start gates)).length + 3] + (some ⟨some (.headerStart 0), initialState, + initialTapes base roots (inputBits start tokens ++ suffix)⟩) = + some ⟨none, initialState, finalTapes base next finalRoots suffix + ((base .reversed).reverse ++ recordsBits (gateRecords start gates))⟩ := by + let headerBase := Function.update base .remaining (encodeWord tokens.length) + let finished := boundaryTapes + (outputTapes (Function.update headerBase .remaining (encodeWord 0)) + (recordsBits (gateRecords start gates)).reverse) next finalRoots suffix + let emitted := (base .reversed).reverse ++ recordsBits (gateRecords start gates) + have hh := headersTrace base roots start tokens.length (tokenBits tokens ++ suffix) + have ht := tokensTrace tokens headerBase start roots next finalRoots gates suffix hcompile + (by simp [headerBase]) + have hr := reverseTrace finished emitted + (by simp [finished, boundaryTapes, outputTapes]) + (by simp [finished, emitted, boundaryTapes, outputTapes, headerBase, List.reverse_append]) + have total := trace_trans _ (trace_trans _ hh ht) hr + have frame : reversedTapes finished emitted = finalTapes base next finalRoots suffix emitted := by + funext tape + cases tape <;> simp [reversedTapes, finished, finalTapes, boundaryTapes, outputTapes, headerBase] + rw [frame] at total + simpa only [inputBits, List.append_assoc, emitted, List.length_append, List.length_reverse, + Nat.add_assoc] using total + +def compileInTime (tokens : List Token) (base : Tape → List Bool) (start : Nat) + (roots : List Nat) (next : Nat) (finalRoots : List Nat) (gates : List Gate) + (suffix : List Bool) + (hcompile : compileTokens start roots tokens = some (next, finalRoots, gates)) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (.headerStart 0), initialState, initialTapes base roots (inputBits start tokens ++ suffix)⟩ + (some ⟨none, initialState, finalTapes base next finalRoots suffix + ((base .reversed).reverse ++ recordsBits (gateRecords start gates))⟩) + (start + tokens.length + 4 + tokensSteps start roots tokens + + (base .reversed).length + (recordsBits (gateRecords start gates)).length + 3) where + steps := start + tokens.length + 4 + tokensSteps start roots tokens + + (base .reversed).length + (recordsBits (gateRecords start gates)).length + 3 + evals_in_steps := compileTrace tokens base start roots next finalRoots gates suffix hcompile + steps_le_m := Nat.le_refl _ + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.PostfixMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/PreprocessingMachineLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/PreprocessingMachineLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..848cf707f1f79ea39098777093064d99af42d7d2 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/PreprocessingMachineLemmas.lean @@ -0,0 +1,110 @@ +import OAI.Computability.PerfectCompleteness.Foundations.PCPSource +import OAI.Computability.PerfectCompleteness.Machines.BinaryInputReduction +import OAI.Computability.PerfectCompleteness.Machines.NormalizationMachine +import OAI.Computability.UniqueGames.Machines.GraphIterationBoundsLemmas +import OAI.Computability.UniqueGames.PCP.LoopInitializationLemmas + +namespace OAI + + +namespace PerfectCompleteness.PreprocessingMachine + +open Turing UniqueGamesTheorem.Foundations +open Complexity PCP Target + +noncomputable section + +def preprocessing : RoundComputation.PreprocessingCertificate PCPSource.baseTable := + PreprocessingRuntime.tablePolynomialTime PCPSource.baseTable + +theorem preprocessing_finite_alphabet : + MachineFiniteAlphabet.FiniteAlphabet preprocessing.tm := + PreprocessingRuntime.finiteAlphabet PCPSource.baseTable + +def round : + TM2ComputableInPolyTime GraphTables.tableBits GraphTables.tableBits + (RoundTables.build PCPSource.baseTable) := + RoundComputation.tablePolynomialTime PCPSource.baseTable preprocessing + +theorem round_finite_alphabet : MachineFiniteAlphabet.FiniteAlphabet round.tm := + RoundComputation.tablePolynomialTime_finite_alphabet PCPSource.baseTable + preprocessing preprocessing_finite_alphabet + +def computableInPolyTime : + TM2ComputableInPolyTime formulaBits formulaBits PCPSource.rawFormula := + MachineTableIteration.gapMapCertificate PCPSource.baseTable round + +theorem finite_alphabet : + MachineFiniteAlphabet.FiniteAlphabet computableInPolyTime.tm := + TableIterationFiniteAlphabet.gapMap PCPSource.baseTable round round_finite_alphabet + +end +end PerfectCompleteness.PreprocessingMachine + + +namespace PerfectCompleteness.PCPSourceMachine + +open Turing UniqueGamesTheorem.Foundations Complexity Target + +noncomputable section + +def normalizedComputation : + TM2ComputableInPolyTime formulaBits formulaBits PCPSource.normalizedFormula := by + change TM2ComputableInPolyTime formulaBits formulaBits + (fun formula => Normalization.normalize (PCPSource.rawFormula formula)) + exact MachineSequential.composeBits PreprocessingMachine.computableInPolyTime + NormalizationMachine.computableInPolyTime + +theorem normalized_finiteAlphabet : + MachineFiniteAlphabet.FiniteAlphabet normalizedComputation.tm := + MachineFiniteAlphabet.composeBits PreprocessingMachine.computableInPolyTime + NormalizationMachine.computableInPolyTime PreprocessingMachine.finite_alphabet + NormalizationMachine.computation_finiteAlphabet + +def rawSource (input : List Bool) : Formula := + PCPSource.normalizedFormula (BinaryLanguage.totalRename input) + +def rawComputation : TM2ComputableInPolyTime (id : List Bool → List Bool) formulaBits rawSource := by + change TM2ComputableInPolyTime (id : List Bool → List Bool) formulaBits + (fun input => PCPSource.normalizedFormula (BinaryLanguage.totalRename input)) + exact MachineSequential.composeBits BinaryInputReduction.computation normalizedComputation + +theorem raw_finiteAlphabet : MachineFiniteAlphabet.FiniteAlphabet rawComputation.tm := + MachineFiniteAlphabet.composeBits BinaryInputReduction.computation normalizedComputation + BinaryInputReduction.computation_finiteAlphabet normalized_finiteAlphabet + +theorem rawSource_nonempty (input : List Bool) : (rawSource input).clauses ≠ [] := + PCPSource.normalizedFormula_nonempty _ + +theorem rawSource_satisfiable_iff (input : List Bool) : + (rawSource input).Satisfiable ↔ BinaryLanguage.language input := + (PCPSource.normalizedFormula_satisfiable_iff (BinaryLanguage.totalRename input)).trans + (BinaryLanguage.totalRename_satisfiable_iff input) + +theorem rawSource_distinct (input : List Bool) (clause : Clause (rawSource input).variables) + (mem : clause ∈ (rawSource input).clauses) (i j : Fin 3) + (same : clause[i].variableIndex = clause[j].variableIndex) : i = j := + PCPSource.normalizedFormula_distinct (BinaryLanguage.totalRename input) clause mem i j same + +theorem rawSource_clauseGap (input : List Bool) (unsat : ¬BinaryLanguage.language input) : + SourceAmplification.ClauseGap (PCPSource.clauseFamily (BinaryLanguage.totalRename input)) + PCPSource.sourceGap := + PCPSource.clauseGap (BinaryLanguage.totalRename input) + (fun sat => unsat ((BinaryLanguage.totalRename_satisfiable_iff input).mp sat)) + +theorem amplifiedSource_complete (input : List Bool) (sat : BinaryLanguage.language input) + (σ : ℚ) (hσ : 0 < σ) : + (PCPSource.amplifiedSource (BinaryLanguage.totalRename input) σ hσ).value = 1 := + PCPSource.amplifiedSource_complete (BinaryLanguage.totalRename input) + ((BinaryLanguage.totalRename_satisfiable_iff input).mpr sat) σ hσ + +theorem amplifiedSource_sound (input : List Bool) (unsat : ¬BinaryLanguage.language input) + (σ : ℚ) (hσ : 0 < σ) : + (PCPSource.amplifiedSource (BinaryLanguage.totalRename input) σ hσ).value < (σ : ℝ) := + PCPSource.amplifiedSource_sound (BinaryLanguage.totalRename input) + (fun sat => unsat ((BinaryLanguage.totalRename_satisfiable_iff input).mp sat)) σ hσ + +end +end PerfectCompleteness.PCPSourceMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/ProducerArenaLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/ProducerArenaLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..fd65c7445e6662bcff938bf1376c967561773c5b --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/ProducerArenaLemmas.lean @@ -0,0 +1,754 @@ +import OAI.Computability.PerfectCompleteness.Machines.AcceptanceStage +import OAI.Computability.PerfectCompleteness.Machines.CellsTokensAlignmentLemmas +import OAI.Computability.PerfectCompleteness.Machines.CircuitFinish +import OAI.Computability.PerfectCompleteness.Machines.InitializationStageLemmas +import OAI.Computability.PerfectCompleteness.Machines.ProducerBootstrapLemmas +import OAI.Computability.PerfectCompleteness.Machines.VerifierFront + +namespace OAI + + +noncomputable section +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.ProducerArena + + +open Turing + +inductive Work + | transition (tape : TransitionArena.Tape) + | validity (index : Fin 7) + | cells (index : Fin 9) + | finish (tape : CircuitFinish.Tape) + | bootstrap + deriving DecidableEq, Fintype + +abbrev Tape (V : NPVerifier) := VerifierFront.Tape V ⊕ Work +abbrev Alphabet (V : NPVerifier) (_ : Tape V) := Bool +abbrev State := TermMachine.State +abbrev initialState : State := TermMachine.initialState + +def frontPorts (V : NPVerifier) : VerifierFront.Tape V ↪ Tape V := + ⟨Sum.inl, Sum.inl_injective⟩ + +def raw (V : NPVerifier) : Tape V := .inl (VerifierFront.raw V) +def framed (V : NPVerifier) : Tape V := .inl (VerifierFront.stream V) +def clock (V : NPVerifier) (c : ClockPreparation.Clock) : Tape V := + .inl (VerifierFront.clockTape V c) +def q (V : NPVerifier) : Tape V := clock V .witness +def capacity (V : NPVerifier) : Tape V := clock V .capacity +def countdown (V : NPVerifier) : Tape V := clock V .horizon +def freeInputs (V : NPVerifier) : Tape V := clock V .inputCount + +def shared (V : NPVerifier) (t : ForestStage.Tape) : Tape V := + .inr (.transition (.inl t)) +def current (V : NPVerifier) : Tape V := shared V (.lower .current) +def roots (V : NPVerifier) : Tape V := shared V .rootTable +def records (V : NPVerifier) : Tape V := shared V .records +def tokens (V : NPVerifier) : Tape V := shared V .tokens +def count (V : NPVerifier) : Tape V := shared V (.lower .remaining) +def cursor (V : NPVerifier) : Tape V := .inr (.transition (.inr .cursor)) +def output (V : NPVerifier) : Tape V := .inr (.finish .output) + +theorem clock_injective (V : NPVerifier) : Function.Injective (clock V) := by + intro a b h + have hs := (VerifierFront.clockSlots V).injective (Sum.inl.inj h) + have ho := ClockPreparation.outputSlot_injective _ hs + cases a <;> cases b <;> simp_all [ClockPreparation.clockOutput] <;> cases ho + +@[simp] theorem clock_eq_iff (V : NPVerifier) (a b : ClockPreparation.Clock) : + clock V a = clock V b ↔ a = b := (clock_injective V).eq_iff + +@[simp] theorem clock_ne_raw (V : NPVerifier) (c : ClockPreparation.Clock) : + clock V c ≠ raw V := by + simp [clock, raw, VerifierFront.clockTape, VerifierFront.clockSlots, VerifierFront.raw] + +@[simp] theorem raw_ne_clock (V : NPVerifier) (c : ClockPreparation.Clock) : + raw V ≠ clock V c := (clock_ne_raw V c).symm + +@[simp] theorem clock_ne_framed (V : NPVerifier) (c : ClockPreparation.Clock) : + clock V c ≠ framed V := by + simp [clock, framed, VerifierFront.clockTape, VerifierFront.clockSlots, VerifierFront.stream] + +@[simp] theorem framed_ne_clock (V : NPVerifier) (c : ClockPreparation.Clock) : + framed V ≠ clock V c := (clock_ne_framed V c).symm + +@[simp] theorem raw_ne_framed (V : NPVerifier) : raw V ≠ framed V := by + simp [raw, framed, VerifierFront.raw, VerifierFront.stream] + +def transitionTape (V : NPVerifier) : TransitionArena.Tape → Tape V + | .inr .raw => raw V + | .inr .q => q V + | .inr .capacity => capacity V + | .inr .countdown => countdown V + | t => .inr (.transition t) + +def transitionPorts (V : NPVerifier) : TransitionArena.Tape ↪ Tape V where + toFun := transitionTape V + inj' := by + intro a b h + cases a with + | inl a => + cases b with + | inl b => simpa [transitionTape] using h + | inr b => + cases b <;> + simp_all [transitionTape, raw, q, capacity, countdown, clock] + | inr a => + cases b with + | inl b => + cases a <;> + simp_all [transitionTape, raw, q, capacity, countdown, clock] + | inr b => + cases a <;> cases b <;> + simp_all [transitionTape, q, capacity, countdown, raw, clock, + VerifierFront.raw, VerifierFront.clockTape, VerifierFront.clockSlots, + ClockPreparation.clockOutput] <;> + cases h + +@[simp] theorem transitionPorts_apply (V : NPVerifier) (t : TransitionArena.Tape) : + transitionPorts V t = transitionTape V t := rfl + +def forestPorts (V : NPVerifier) : ForestStage.Tape ↪ Tape V := + TransitionArena.forestPorts.trans (transitionPorts V) + +def termPorts (V : NPVerifier) : TermMachine.Tape ↪ Tape V := + TransitionArena.termPorts.trans (transitionPorts V) + +def initializationTape (V : NPVerifier) : InitializationAssembly.Tape 9 → Tape V + | .rawInput => raw V + | .framedInput => framed V + | .witnessBound => q V + | .capacity => capacity V + | .reversed => tokens V + | .count => count V + | .validityWork j => .inr (.validity j) + | .cellWork j => .inr (.cells j) + +def initializationPorts (V : NPVerifier) : InitializationAssembly.Tape 9 ↪ Tape V where + toFun := initializationTape V + inj' := by + intro a b h + cases a <;> cases b <;> + simp_all [initializationTape, q, capacity, tokens, count, shared, + raw, framed, clock, VerifierFront.raw, VerifierFront.stream, + VerifierFront.clockTape, VerifierFront.clockSlots, + ClockPreparation.clockOutput] + all_goals + have ho := ClockPreparation.outputSlot_injective (ClockPreparation.clockPolynomials V) h + cases ho + +@[simp] theorem initializationPorts_apply (V : NPVerifier) (t : InitializationAssembly.Tape 9) : + initializationPorts V t = initializationTape V t := rfl + +def finishTape (V : NPVerifier) : CircuitFinish.Tape → Tape V + | .current => current V + | .freeInputs => freeInputs V + | .root => roots V + | .reversedRecords => records V + | .output => output V + | .gateCount => .inr (.finish .gateCount) + | .scratch => .inr (.finish .scratch) + +def finishPorts (V : NPVerifier) : CircuitFinish.Tape ↪ Tape V where + toFun := finishTape V + inj' := by + intro a b h + cases a <;> cases b <;> + simp_all [finishTape, current, freeInputs, roots, records, output, shared, clock] + +@[simp] theorem finishPorts_apply (V : NPVerifier) (t : CircuitFinish.Tape) : + finishPorts V t = finishTape V t := rfl + +def bootstrapPorts (V : NPVerifier) : ProducerBootstrap.Ports (Tape V) where + toFun := ![freeInputs V, current V, .inr .bootstrap, count V, cursor V] + inj' := by + intro a b h + fin_cases a <;> fin_cases b <;> + simp_all [freeInputs, current, count, cursor, shared, clock] + +@[simp] theorem bootstrap_source (V : NPVerifier) : bootstrapPorts V 0 = freeInputs V := rfl +@[simp] theorem bootstrap_current (V : NPVerifier) : bootstrapPorts V 1 = current V := rfl +@[simp] theorem bootstrap_scratch (V : NPVerifier) : + bootstrapPorts V 2 = .inr .bootstrap := rfl +@[simp] theorem bootstrap_count (V : NPVerifier) : bootstrapPorts V 3 = count V := rfl +@[simp] theorem bootstrap_cursor (V : NPVerifier) : bootstrapPorts V 4 = cursor V := rfl + +def empty (V : NPVerifier) : Tape V → List Bool := fun _ => [] + +def frontTapes (V : NPVerifier) (contents : VerifierFront.Tape V → List Bool) : + Tape V → List Bool + | .inl t => contents t + | .inr _ => [] + +@[simp] theorem frontTapes_at (V : NPVerifier) + (contents : VerifierFront.Tape V → List Bool) (t : VerifierFront.Tape V) : + frontTapes V contents (frontPorts V t) = contents t := rfl + +@[simp] theorem frontTapes_work (V : NPVerifier) + (contents : VerifierFront.Tape V → List Bool) (t : Work) : + frontTapes V contents (.inr t) = [] := rfl + +theorem front_fill (V : NPVerifier) (contents : VerifierFront.Tape V → List Bool) : + ForestPlacement.fill (frontPorts V) (empty V) contents = frontTapes V contents := by + funext t + cases t with + | inl t => exact ForestPlacement.fill_at (frontPorts V) (empty V) contents t + | inr t => + exact ForestPlacement.fill_other (frontPorts V) (empty V) contents _ + (by intro i; simp [frontPorts]) + +def initialTapes (V : NPVerifier) (input : List Bool) : Tape V → List Bool := + frontTapes V (VerifierFront.frameTapes V input) + +theorem initialTapes_eq (V : NPVerifier) (input : List Bool) : + initialTapes V input = fun t => if t = raw V then input else [] := by + funext t + cases t with + | inl t => + cases t with + | inl i => fin_cases i <;> simp [initialTapes, frontTapes, VerifierFront.frameTapes, + raw, VerifierFront.raw] + | inr t => simp [initialTapes, frontTapes, VerifierFront.frameTapes, raw, VerifierFront.raw] + | inr t => simp [initialTapes, frontTapes, raw] + +def frontendPrepared (V : NPVerifier) (input : List Bool) : Tape V → List Bool := + frontTapes V (VerifierFront.preparedTapes V input) + +@[simp] theorem frontendPrepared_raw (V : NPVerifier) (input : List Bool) : + frontendPrepared V input (raw V) = input := VerifierFront.prepared_raw V input + +@[simp] theorem frontendPrepared_framed (V : NPVerifier) (input : List Bool) : + frontendPrepared V input (framed V) = encodeWord input.length ++ input := + VerifierFront.prepared_stream V input + +@[simp] theorem frontendPrepared_clock (V : NPVerifier) (input : List Bool) + (c : ClockPreparation.Clock) : frontendPrepared V input (clock V c) = + encodeWord (ClockPreparation.clockValue V input.length c) := + VerifierFront.prepared_clock V input c + +@[simp] theorem frontendPrepared_work (V : NPVerifier) (input : List Bool) (t : Work) : + frontendPrepared V input (.inr t) = [] := rfl + +theorem bootstrapReady (V : NPVerifier) (input : List Bool) : + ProducerBootstrap.Ready (bootstrapPorts V) (frontendPrepared V input) + (2 * V.witnessBound.eval input.length + 1) := by + exact ⟨frontendPrepared_clock V input .inputCount, rfl, rfl, rfl, rfl⟩ + +def bootstrapPrepared (V : NPVerifier) (input : List Bool) : Tape V → List Bool := + ProducerBootstrap.prepared (bootstrapPorts V) (frontendPrepared V input) + +@[simp] theorem bootstrapPrepared_front (V : NPVerifier) (input : List Bool) + (t : VerifierFront.Tape V) : + bootstrapPrepared V input (frontPorts V t) = VerifierFront.preparedTapes V input t := by + apply ProducerBootstrap.prepared_other + all_goals simp [frontPorts, bootstrapPorts, current, count, cursor, shared] + +@[simp] theorem bootstrapPrepared_current (V : NPVerifier) (input : List Bool) : + bootstrapPrepared V input (current V) = + encodeWord (2 * V.witnessBound.eval input.length + 1) := + ProducerBootstrap.prepared_current (bootstrapPorts V) (frontendPrepared V input) _ + (bootstrapReady V input) + +@[simp] theorem bootstrapPrepared_count (V : NPVerifier) (input : List Bool) : + bootstrapPrepared V input (count V) = encodeWord 0 := + ProducerBootstrap.prepared_count (bootstrapPorts V) (frontendPrepared V input) _ + (bootstrapReady V input) + +@[simp] theorem bootstrapPrepared_cursor (V : NPVerifier) (input : List Bool) : + bootstrapPrepared V input (cursor V) = encodeWord 0 := + ProducerBootstrap.prepared_cursor (bootstrapPorts V) (frontendPrepared V input) _ + (bootstrapReady V input) + +theorem bootstrapPrepared_other (V : NPVerifier) (input : List Bool) (t : Tape V) + (hc : t ≠ current V) (ht : t ≠ count V) (hz : t ≠ cursor V) : + bootstrapPrepared V input t = frontendPrepared V input t := + ProducerBootstrap.prepared_other (bootstrapPorts V) (frontendPrepared V input) t hc ht hz + +def initializationBase (V : NPVerifier) (input : List Bool) : + InitializationAssembly.Tape 9 → List Bool + | .rawInput => input + | .framedInput => encodeWord input.length ++ input + | .witnessBound => encodeWord (V.witnessBound.eval input.length) + | .capacity => encodeWord (VerifierCircuit.capacity V input.length) + | .count => encodeWord 0 + | _ => [] + +theorem bootstrap_initialization_view (V : NPVerifier) (input : List Bool) : + (fun t => bootstrapPrepared V input (initializationPorts V t)) = + initializationBase V input := by + funext t + cases t <;> + simp [initializationTape, initializationBase, bootstrapPrepared, + ProducerBootstrap.prepared, ProducerBootstrap.copied, + frontendPrepared, frontTapes, current, count, cursor, tokens, shared, + raw, framed, q, capacity, freeInputs, clock, + VerifierFront.prepared_raw, VerifierFront.prepared_stream, VerifierFront.prepared_clock, + ClockPreparation.clockValue, encodeWord] + +theorem initializationValidityReady (V : NPVerifier) (input : List Bool) : + ClashMachine.Full.Ready (InitializationAssembly.validitySlots 9) + (fun t => bootstrapPrepared V input (initializationPorts V t)) + (V.witnessBound.eval input.length) := by + rw [bootstrap_initialization_view] + exact InitializationAssembly.validityReady _ _ rfl (fun _ => rfl) + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.ProducerArena + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.ProducerFrontStage + +open Turing ProducerArena + +abbrev Label (V : NPVerifier) := VerifierFront.Label V ⊕ ProducerBootstrap.Label + +def entry (V : NPVerifier) : Label V := .inl (.inl 0) + +def statement {Λ : Type} (V : NPVerifier) (labels : Label V → Λ) (exit : Option Λ) : + Label V → TM2.Stmt (Alphabet V) Λ State + | .inl l => ForestPlacement.statement (frontPorts V) (fun l => labels (.inl l)) + (some (labels (.inr .copy))) (VerifierFront.program (A := Unit × Bool) V l) + | .inr l => ProducerBootstrap.statement (bootstrapPorts V) (fun l => labels (.inr l)) exit l + +def timePolynomial (V : NPVerifier) : Polynomial Nat := + VerifierFront.timePolynomial V + + Polynomial.C 2 * WitnessEncoding.freeInputPolynomial V.witnessBound + Polynomial.C 5 + +theorem timePolynomial_eval (V : NPVerifier) (n : Nat) : + (timePolynomial V).eval n = (VerifierFront.timePolynomial V).eval n + + (2 * (2 * V.witnessBound.eval n + 1) + 5) := by + simp [timePolynomial, Nat.add_assoc] + +def inTime {Λ : Type} (V : NPVerifier) (labels : Label V → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet V) Λ State) + (code : ∀ l, program (labels l) = statement V labels exit l) + (input : List Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels (entry V)), initialState, initialTapes V input⟩ + (some ⟨exit, initialState, bootstrapPrepared V input⟩) + ((timePolynomial V).eval input.length) := by + have front := ForestPlacement.execution (frontPorts V) + (fun l => labels (.inl l)) (some (labels (.inr .copy))) (empty V) + (VerifierFront.program (A := Unit × Bool) V) program (fun l => code (.inl l)) + (VerifierFront.prepareInTime V input ((), false)) + have front' : StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels (entry V)), initialState, initialTapes V input⟩ + (some ⟨some (labels (.inr .copy)), initialState, frontendPrepared V input⟩) + ((VerifierFront.timePolynomial V).eval input.length) := by + simpa only [ForestPlacement.configuration, ForestPlacement.placedLabel, + front_fill, entry, initialTapes, frontendPrepared, initialState, + TermMachine.initialState] using front + have boot := ProducerBootstrap.inTime (bootstrapPorts V) (fun l => labels (.inr l)) + exit program (fun l => code (.inr l)) (frontendPrepared V input) + (2 * V.witnessBound.eval input.length + 1) (bootstrapReady V input) ((), false) none + have combined := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ front' boot + simpa only [timePolynomial_eval, bootstrapPrepared, initialState, + TermMachine.initialState, Nat.add_comm] using combined + +def program (V : NPVerifier) : Label V → TM2.Stmt (Alphabet V) (Label V) State := + statement V id none + +def programInTime (V : NPVerifier) (input : List Bool) : + StateTransition.EvalsToInTime (TM2.step (program V)) + ⟨some (entry V), initialState, initialTapes V input⟩ + (some ⟨none, initialState, bootstrapPrepared V input⟩) + ((timePolynomial V).eval input.length) := + inTime V id none (program V) (fun _ => rfl) input + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.ProducerFrontStage + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.ProducerHandoffs + +open ProducerInvariant ProducerArena + + +def localBase (V : NPVerifier) (input : List Bool) : TransitionArena.Tape → List Bool := + fun t => bootstrapPrepared V input (transitionPorts V t) + +def boundary (V : NPVerifier) (input : List Bool) (remaining : Nat) (s : Snapshot) : Tape V → List Bool := + ForestPlacement.fill (transitionPorts V) (bootstrapPrepared V input) + (TransitionArena.tapes (localBase V input) (VerifierCircuit.capacity V input.length) remaining s) + +def finished (V : NPVerifier) (input : List Bool) (s : Snapshot) : Tape V → List Bool := + ForestPlacement.fill (transitionPorts V) (bootstrapPrepared V input) + (TransitionArena.finishTapes (localBase V input) (VerifierCircuit.capacity V input.length) s) + +theorem fill_fill {I K : Type} (ports : I ↪ K) (base : K → List Bool) + (first second : I → List Bool) : + ForestPlacement.fill ports (ForestPlacement.fill ports base first) second = + ForestPlacement.fill ports base second := by + classical + funext k + by_cases hin : ∃ i, ports i = k + · obtain ⟨i, rfl⟩ := hin + simp only [ForestPlacement.fill_at] + · rw [ForestPlacement.fill_other ports _ _ k (not_exists.mp hin), + ForestPlacement.fill_other ports _ _ k (not_exists.mp hin), + ForestPlacement.fill_other ports _ _ k (not_exists.mp hin)] + +theorem boundary_view (V : NPVerifier) (input : List Bool) (remaining : Nat) (s : Snapshot) : + (fun t => boundary V input remaining s (transitionPorts V t)) = + TransitionArena.tapes (localBase V input) (VerifierCircuit.capacity V input.length) remaining s := by + funext t + exact ForestPlacement.fill_at _ _ _ t + +theorem finished_view (V : NPVerifier) (input : List Bool) (s : Snapshot) : + (fun t => finished V input s (transitionPorts V t)) = + TransitionArena.finishTapes (localBase V input) (VerifierCircuit.capacity V input.length) s := by + funext t + exact ForestPlacement.fill_at _ _ _ t + +theorem boundary_other (V : NPVerifier) (input : List Bool) (remaining : Nat) (s : Snapshot) + (k : Tape V) (outside : ∀ t, transitionPorts V t ≠ k) : + boundary V input remaining s k = bootstrapPrepared V input k := + ForestPlacement.fill_other _ _ _ k outside + +theorem finished_other (V : NPVerifier) (input : List Bool) (s : Snapshot) + (k : Tape V) (outside : ∀ t, transitionPorts V t ≠ k) : + finished V input s k = bootstrapPrepared V input k := + ForestPlacement.fill_other _ _ _ k outside + +theorem fill_boundary (V : NPVerifier) (input : List Bool) (remaining : Nat) (s : Snapshot) + (contents : TransitionArena.Tape → List Bool) : + ForestPlacement.fill (transitionPorts V) (boundary V input remaining s) contents = + ForestPlacement.fill (transitionPorts V) (bootstrapPrepared V input) contents := + fill_fill _ _ _ _ + +theorem fill_finished (V : NPVerifier) (input : List Bool) (s : Snapshot) + (contents : TransitionArena.Tape → List Bool) : + ForestPlacement.fill (transitionPorts V) (finished V input s) contents = + ForestPlacement.fill (transitionPorts V) (bootstrapPrepared V input) contents := + fill_fill _ _ _ _ + +theorem iteration_handoff (V : NPVerifier) (input : List Bool) (remaining : Nat) (s next : Snapshot) : + ForestPlacement.fill (transitionPorts V) (boundary V input remaining s) + (TransitionArena.finishTapes (localBase V input) (VerifierCircuit.capacity V input.length) next) = + finished V input next := fill_boundary V input remaining s _ + +theorem acceptance_handoff (V : NPVerifier) (input : List Bool) (s next : Snapshot) : + ForestPlacement.fill (transitionPorts V) (finished V input s) + (TransitionArena.finishTapes (localBase V input) (VerifierCircuit.capacity V input.length) next) = + finished V input next := fill_finished V input s _ + +@[simp] theorem boundary_current (V : NPVerifier) (input : List Bool) (remaining : Nat) (s : Snapshot) : + boundary V input remaining s (current V) = s.currentBits := by + change ForestPlacement.fill (transitionPorts V) _ _ + (transitionPorts V (.inl (.lower .current))) = _ + rw [ForestPlacement.fill_at] + rfl + +@[simp] theorem boundary_roots (V : NPVerifier) (input : List Bool) (remaining : Nat) (s : Snapshot) : + boundary V input remaining s (roots V) = s.rootBits := by + change ForestPlacement.fill (transitionPorts V) _ _ (transitionPorts V (.inl .rootTable)) = _ + rw [ForestPlacement.fill_at] + rfl + +@[simp] theorem boundary_records (V : NPVerifier) (input : List Bool) (remaining : Nat) (s : Snapshot) : + boundary V input remaining s (records V) = s.reversedRecords := by + change ForestPlacement.fill (transitionPorts V) _ _ (transitionPorts V (.inl .records)) = _ + rw [ForestPlacement.fill_at] + rfl + +@[simp] theorem boundary_countdown (V : NPVerifier) (input : List Bool) (remaining : Nat) (s : Snapshot) : + boundary V input remaining s (countdown V) = encodeWord remaining := by + change ForestPlacement.fill (transitionPorts V) _ _ (transitionPorts V (.inr .countdown)) = _ + rw [ForestPlacement.fill_at] + rfl + +@[simp] theorem finished_current (V : NPVerifier) (input : List Bool) (s : Snapshot) : + finished V input s (current V) = s.currentBits := by + change ForestPlacement.fill (transitionPorts V) _ _ + (transitionPorts V (.inl (.lower .current))) = _ + rw [ForestPlacement.fill_at] + rfl + +@[simp] theorem finished_roots (V : NPVerifier) (input : List Bool) (s : Snapshot) : + finished V input s (roots V) = s.rootBits := by + change ForestPlacement.fill (transitionPorts V) _ _ (transitionPorts V (.inl .rootTable)) = _ + rw [ForestPlacement.fill_at] + rfl + +@[simp] theorem finished_records (V : NPVerifier) (input : List Bool) (s : Snapshot) : + finished V input s (records V) = s.reversedRecords := by + change ForestPlacement.fill (transitionPorts V) _ _ (transitionPorts V (.inl .records)) = _ + rw [ForestPlacement.fill_at] + rfl + +@[simp] theorem finished_countdown (V : NPVerifier) (input : List Bool) (s : Snapshot) : + finished V input s (countdown V) = [] := by + change ForestPlacement.fill (transitionPorts V) _ _ (transitionPorts V (.inr .countdown)) = _ + rw [ForestPlacement.fill_at] + simp [TransitionArena.finishTapes] + +theorem boundary_private (V : NPVerifier) (input : List Bool) (remaining : Nat) (s : Snapshot) + (w : Work) (outside : ∀ t, transitionPorts V t ≠ .inr w) : + boundary V input remaining s (.inr w) = [] := by + rw [boundary_other V input remaining s _ outside, + bootstrapPrepared_other V input _ + (Ne.symm (outside (.inl (.lower .current)))) + (Ne.symm (outside (.inl (.lower .remaining)))) + (Ne.symm (outside (.inr .cursor)))] + rfl + +theorem finished_private (V : NPVerifier) (input : List Bool) (s : Snapshot) + (w : Work) (outside : ∀ t, transitionPorts V t ≠ .inr w) : + finished V input s (.inr w) = [] := by + rw [finished_other V input s _ outside, + bootstrapPrepared_other V input _ + (Ne.symm (outside (.inl (.lower .current)))) + (Ne.symm (outside (.inl (.lower .remaining)))) + (Ne.symm (outside (.inr .cursor)))] + rfl + +theorem private_finish_outside (V : NPVerifier) (f : CircuitFinish.Tape) : + ∀ t, transitionPorts V t ≠ .inr (.finish f) := by + intro t + cases t with + | inl t => simp [transitionTape] + | inr t => cases t <;> simp [transitionTape, raw, q, capacity, countdown, clock] + +theorem private_validity_outside (V : NPVerifier) (j : Fin 7) : + ∀ t, transitionPorts V t ≠ .inr (.validity j) := by + intro t + cases t with + | inl t => simp [transitionTape] + | inr t => cases t <;> simp [transitionTape, raw, q, capacity, countdown, clock] + +theorem private_cells_outside (V : NPVerifier) (j : Fin 9) : + ∀ t, transitionPorts V t ≠ .inr (.cells j) := by + intro t + cases t with + | inl t => simp [transitionTape] + | inr t => cases t <;> simp [transitionTape, raw, q, capacity, countdown, clock] + +theorem bootstrap_clock (V : NPVerifier) (input : List Bool) (c : ClockPreparation.Clock) : + bootstrapPrepared V input (clock V c) = encodeWord (ClockPreparation.clockValue V input.length c) := by + change bootstrapPrepared V input (frontPorts V (VerifierFront.clockTape V c)) = _ + rw [bootstrapPrepared_front] + exact VerifierFront.prepared_clock V input c + +theorem bootstrap_raw (V : NPVerifier) (input : List Bool) : + bootstrapPrepared V input (raw V) = input := by + change bootstrapPrepared V input (frontPorts V (VerifierFront.raw V)) = _ + rw [bootstrapPrepared_front] + exact VerifierFront.prepared_raw V input + +theorem bootstrap_work (V : NPVerifier) (input : List Bool) (w : Work) + (hc : (.inr w : Tape V) ≠ current V) (hn : (.inr w : Tape V) ≠ count V) + (hz : (.inr w : Tape V) ≠ cursor V) : bootstrapPrepared V input (.inr w) = [] := by + rw [bootstrapPrepared_other V input _ hc hn hz] + rfl + +theorem bootstrap_extra (V : NPVerifier) (input : List Bool) (s : Snapshot) + (e : TransitionArena.Extra) : + localBase V input (.inr e) = + TransitionArena.tapes (localBase V input) (VerifierCircuit.capacity V input.length) + (V.horizon input.length) s (.inr e) := by + cases e <;> simp only [TransitionArena.tapes] + all_goals first + | rfl + | exact bootstrapPrepared_cursor V input + | exact bootstrap_clock V input .capacity + | exact bootstrap_clock V input .horizon + +@[simp] theorem boundary_raw (V : NPVerifier) (input : List Bool) (remaining : Nat) (s : Snapshot) : + boundary V input remaining s (raw V) = input := by + change ForestPlacement.fill (transitionPorts V) _ _ (transitionPorts V (.inr .raw)) = _ + rw [ForestPlacement.fill_at] + exact bootstrap_raw V input + +@[simp] theorem boundary_q (V : NPVerifier) (input : List Bool) (remaining : Nat) (s : Snapshot) : + boundary V input remaining s (q V) = encodeWord (V.witnessBound.eval input.length) := by + change ForestPlacement.fill (transitionPorts V) _ _ (transitionPorts V (.inr .q)) = _ + rw [ForestPlacement.fill_at] + exact bootstrap_clock V input .witness + +@[simp] theorem boundary_capacity (V : NPVerifier) (input : List Bool) (remaining : Nat) (s : Snapshot) : + boundary V input remaining s (capacity V) = encodeWord (VerifierCircuit.capacity V input.length) := by + change ForestPlacement.fill (transitionPorts V) _ _ (transitionPorts V (.inr .capacity)) = _ + rw [ForestPlacement.fill_at] + rfl + +theorem initial_result_view (V : NPVerifier) (input : List Bool) : + (fun t => InitializationStage.result (forestPorts V) (bootstrapPrepared V input) V input + (transitionPorts V t)) = + TransitionArena.tapes (localBase V input) (VerifierCircuit.capacity V input.length) + (V.horizon input.length) (snapshot (VerifierCircuit.initialFrame V input)) := by + funext t + cases t with + | inl t => + change InitializationStage.result (forestPorts V) _ V input (forestPorts V t) = _ + rw [InitializationStage.result_at] + cases t with + | lower t => cases t <;> rfl + | tokens => rfl + | records => rfl + | rootTable => rfl + | inr e => + have outside : ∀ t, forestPorts V t ≠ transitionPorts V (.inr e) := by + intro t h + change transitionPorts V (.inl t) = transitionPorts V (.inr e) at h + have impossible := (transitionPorts V).injective h + cases impossible + rw [InitializationStage.result_other _ _ _ _ _ outside] + exact bootstrap_extra V input _ e + +theorem initial_result_eq_boundary (V : NPVerifier) (input : List Bool) : + InitializationStage.result (forestPorts V) (bootstrapPrepared V input) V input = + boundary V input (V.horizon input.length) (snapshot (VerifierCircuit.initialFrame V input)) := by + classical + funext k + by_cases inside : ∃ t, transitionPorts V t = k + · obtain ⟨t, rfl⟩ := inside + exact (congrFun (initial_result_view V input) t).trans + (congrFun (boundary_view V input _ _) t).symm + · have outside := not_exists.mp inside + have outsideForest : ∀ t, forestPorts V t ≠ k := fun t => outside (.inl t) + rw [InitializationStage.result_other _ _ _ _ _ outsideForest, + boundary_other V input _ _ _ outside] + +theorem initialization_emitted_fill (V : NPVerifier) (input : List Bool) : + ForestPlacement.fill (initializationPorts V) (bootstrapPrepared V input) + (ClashMachine.emitted InitializationAssembly.Tape.reversed InitializationAssembly.Tape.count + (initializationBase V input) (InitializationTemplate.initializationTokens V input)) = + ClashMachine.emitted (tokens V) (count V) (bootstrapPrepared V input) + (InitializationTemplate.initializationTokens V input) := by + rw [← bootstrap_initialization_view V input] + simp only [ClashMachine.emitted, ForestPlacement.fill_update, ForestPlacement.fill_self] + rfl + +theorem initialization_lowering_handoff (V : NPVerifier) (input : List Bool) : + InitializationStage.result (forestPorts V) + (ForestPlacement.fill (initializationPorts V) (bootstrapPrepared V input) + (ClashMachine.emitted InitializationAssembly.Tape.reversed InitializationAssembly.Tape.count + (initializationBase V input) (InitializationTemplate.initializationTokens V input))) V input = + boundary V input (V.horizon input.length) (snapshot (VerifierCircuit.initialFrame V input)) := by + rw [initialization_emitted_fill] + change InitializationStage.result (forestPorts V) + (ClashMachine.emitted (forestPorts V .tokens) (forestPorts V (.lower .remaining)) + (bootstrapPrepared V input) (InitializationTemplate.initializationTokens V input)) V input = _ + rw [InitializationStage.result_emitted, initial_result_eq_boundary] + +theorem clock_outside (V : NPVerifier) (c : ClockPreparation.Clock) + (hq : c ≠ .witness) (hS : c ≠ .capacity) (hT : c ≠ .horizon) : + ∀ t, transitionPorts V t ≠ clock V c := by + intro t + cases t with + | inl t => simp [transitionTape, clock] + | inr e => + cases e with + | q => change clock V .witness ≠ clock V c; simpa only [ne_eq, clock_eq_iff] using Ne.symm hq + | capacity => change clock V .capacity ≠ clock V c; simpa only [ne_eq, clock_eq_iff] using Ne.symm hS + | countdown => change clock V .horizon ≠ clock V c; simpa only [ne_eq, clock_eq_iff] using Ne.symm hT + | raw => exact raw_ne_clock V c + | cursor | position | address | value | scratch | copy | saveLeft | saveRight => + simp [transitionTape, clock] + +theorem freeInputs_outside (V : NPVerifier) : ∀ t, transitionPorts V t ≠ freeInputs V := + clock_outside V .inputCount (by decide) (by decide) (by decide) + +theorem framed_outside (V : NPVerifier) : ∀ t, transitionPorts V t ≠ framed V := by + intro t + cases t with + | inl t => simp [transitionTape, framed] + | inr e => + cases e with + | q => exact clock_ne_framed V .witness + | capacity => exact clock_ne_framed V .capacity + | countdown => exact clock_ne_framed V .horizon + | raw => exact raw_ne_framed V + | cursor | position | address | value | scratch | copy | saveLeft | saveRight => + simp [transitionTape, framed] + +theorem boundary_clock (V : NPVerifier) (input : List Bool) (remaining : Nat) (s : Snapshot) + (c : ClockPreparation.Clock) (hq : c ≠ .witness) (hS : c ≠ .capacity) (hT : c ≠ .horizon) : + boundary V input remaining s (clock V c) = encodeWord (ClockPreparation.clockValue V input.length c) := by + rw [boundary_other V input remaining s _ (clock_outside V c hq hS hT)] + exact bootstrap_clock V input c + +theorem finished_clock (V : NPVerifier) (input : List Bool) (s : Snapshot) + (c : ClockPreparation.Clock) (hq : c ≠ .witness) (hS : c ≠ .capacity) (hT : c ≠ .horizon) : + finished V input s (clock V c) = encodeWord (ClockPreparation.clockValue V input.length c) := by + rw [finished_other V input s _ (clock_outside V c hq hS hT)] + exact bootstrap_clock V input c + +theorem boundary_framed (V : NPVerifier) (input : List Bool) (remaining : Nat) (s : Snapshot) : + boundary V input remaining s (framed V) = encodeWord input.length ++ input := by + rw [boundary_other V input remaining s _ (framed_outside V)] + change bootstrapPrepared V input (frontPorts V (VerifierFront.stream V)) = _ + rw [bootstrapPrepared_front] + exact VerifierFront.prepared_stream V input + +theorem finished_framed (V : NPVerifier) (input : List Bool) (s : Snapshot) : + finished V input s (framed V) = encodeWord input.length ++ input := by + rw [finished_other V input s _ (framed_outside V)] + change bootstrapPrepared V input (frontPorts V (VerifierFront.stream V)) = _ + rw [bootstrapPrepared_front] + exact VerifierFront.prepared_stream V input + +@[simp] theorem finished_freeInputs (V : NPVerifier) (input : List Bool) (s : Snapshot) : + finished V input s (freeInputs V) = encodeWord (2 * V.witnessBound.eval input.length + 1) := by + rw [finished_other V input s _ (freeInputs_outside V)] + exact bootstrap_clock V input .inputCount + +theorem finish_view (V : NPVerifier) (input : List Bool) (s : Snapshot) : + (fun t => finished V input s (finishPorts V t)) = + CircuitFinish.memory s.currentBits + (encodeWord (2 * V.witnessBound.eval input.length + 1)) s.rootBits s.reversedRecords [] [] [] := by + funext t + cases t with + | current => exact finished_current V input s + | freeInputs => exact finished_freeInputs V input s + | root => exact finished_roots V input s + | reversedRecords => exact finished_records V input s + | output => exact finished_private V input s _ (private_finish_outside V .output) + | gateCount => exact finished_private V input s _ (private_finish_outside V .gateCount) + | scratch => exact finished_private V input s _ (private_finish_outside V .scratch) + +theorem circuitFinish_view (V : NPVerifier) (input : List Bool) : + (fun t => finished V input (snapshot (finalFrame V input)) (finishPorts V t)) = + CircuitFinish.initialTapes (VerifierCircuit.circuitOfVerifier V input).wires + (VerifierCircuit.circuitOfVerifier V input).inputs + (VerifierCircuit.circuitOfVerifier V input).output.val + (recordsBits (VerifierCircuit.circuitOfVerifier V input).records) := by + rw [finish_view] + rw [← finalFrame_circuit V input] + simp [CircuitFinish.initialTapes, snapshot, Snapshot.currentBits, Snapshot.rootBits, + CircuitBatch.Frame.toCircuit, CircuitBatch.Fragment.toCircuit, Circuit.wires, + List.ofFn_succ, Circuit.records, encodeWords] + +theorem bootstrap_emitter_ready (V : NPVerifier) (input : List Bool) : + InitializationAssembly.Ready V (initializationPorts V) + (bootstrapPrepared V input) input := by + constructor + · exact congrFun (bootstrap_initialization_view V input) .rawInput + · exact congrFun (bootstrap_initialization_view V input) .framedInput + · exact congrFun (bootstrap_initialization_view V input) .witnessBound + · exact congrFun (bootstrap_initialization_view V input) .capacity + · intro j + exact congrFun (bootstrap_initialization_view V input) (.cellWork j) + · intro j + exact congrFun (bootstrap_initialization_view V input) (.validityWork j) + +theorem bootstrap_lowerer_ready (V : NPVerifier) (input : List Bool) : + InitializationStage.Ready (forestPorts V) (bootstrapPrepared V input) V input := by + intro t + cases t with + | lower t => + cases t <;> simp only [ForestStage.initialLocal] + all_goals first + | exact bootstrapPrepared_current V input + | exact bootstrapPrepared_count V input + | apply bootstrap_work <;> simp [current, count, cursor, shared, TransitionArena.forestPorts] + | tokens => + apply bootstrap_work <;> simp [current, count, cursor, shared, TransitionArena.forestPorts] + | records => + apply bootstrap_work <;> simp [current, count, cursor, shared, TransitionArena.forestPorts] + | rootTable => + apply bootstrap_work <;> simp [current, count, cursor, shared, TransitionArena.forestPorts] + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.ProducerHandoffs + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/ProducerBootstrapLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/ProducerBootstrapLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..27005368269ed5a0b2069a0810ad28e730c4471f --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/ProducerBootstrapLemmas.lean @@ -0,0 +1,521 @@ +import Mathlib.Data.Fintype.Option +import Mathlib.Data.Fintype.Pi +import Mathlib.Data.List.Basic +import OAI.Computability.UniqueGames.Machines.MachineCopy +import OAI.Computability.UniqueGames.Machines.MachineSubroutineLemmas +import OAI.Computability.UniqueGames.Machines.Runtime +import OAI.Computability.UniqueGames.PCP.SourceMachine + +namespace OAI + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.ProducerBootstrap + +open Turing MachineComposition + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev Ports (K : Type) := Fin 5 ↪ K + +inductive Label + | copy | restore | seed + deriving DecidableEq + +protected abbrev Label.enumList : List Label := [.copy, .restore, .seed] + +protected theorem Label.enumList_getElem?_ctorIdx_eq (x : Label) : + Label.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem Label.enumList_nodup : Label.enumList.Nodup := by decide + +instance : Fintype Label where + elems := ⟨Label.enumList, Label.enumList_nodup⟩ + complete x := by cases x <;> decide + +abbrev State (σ : Type) := σ × Option Bool + +structure Ready (p : Ports K) (base : K → List Bool) (free : Nat) : Prop where + source : base (p 0) = encodeWord free + current : base (p 1) = [] + scratch : base (p 2) = [] + count : base (p 3) = [] + cursor : base (p 4) = [] + +def copied (p : Ports K) (base : K → List Bool) : K → List Bool := + Function.update base (p 1) (base (p 0) ++ base (p 1)) + +def prepared (p : Ports K) (base : K → List Bool) : K → List Bool := + Function.update (Function.update (copied p base) (p 3) (false :: copied p base (p 3))) + (p 4) (false :: copied p base (p 4)) + +def statement (p : Ports K) (labels : Label → Λ) (exit : Option Λ) : + Label → TM2.Stmt (fun _ : K => Bool) Λ (State σ) + | .copy => Reduction.MachineTransfer.loopAt (p 0) (p 2) id false + (labels .copy) (some (labels .restore)) + | .restore => MachineCopy.forkLoop (p 2) (p 0) (p 1) false + (labels .restore) (some (labels .seed)) + | .seed => .push (p 3) (fun _ => false) + (.push (p 4) (fun _ => false) (Reduction.MachineTransfer.exitAt (p 4) exit)) + +theorem prepared_current (p : Ports K) (base : K → List Bool) (free : Nat) + (ready : Ready p base free) : prepared p base (p 1) = encodeWord free := by + simp [prepared, copied, p.injective.eq_iff, ready.source, ready.current] + +theorem prepared_source (p : Ports K) (base : K → List Bool) (free : Nat) + (ready : Ready p base free) : prepared p base (p 0) = encodeWord free := by + simp [prepared, copied, p.injective.eq_iff, ready.source] + +theorem prepared_count (p : Ports K) (base : K → List Bool) (free : Nat) + (ready : Ready p base free) : prepared p base (p 3) = encodeWord 0 := by + simp [prepared, copied, p.injective.eq_iff, ready.count, encodeWord] + +theorem prepared_cursor (p : Ports K) (base : K → List Bool) (free : Nat) + (ready : Ready p base free) : prepared p base (p 4) = encodeWord 0 := by + simp [prepared, copied, p.injective.eq_iff, ready.cursor, encodeWord] + +theorem prepared_scratch (p : Ports K) (base : K → List Bool) (free : Nat) + (ready : Ready p base free) : prepared p base (p 2) = [] := by + simp [prepared, copied, p.injective.eq_iff, ready.scratch] + +theorem prepared_other (p : Ports K) (base : K → List Bool) (k : K) + (hc : k ≠ p 1) (ht : k ≠ p 3) (hz : k ≠ p 4) : prepared p base k = base k := by + simp [prepared, copied, hc, ht, hz] + +theorem seedTrace (p : Ports K) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State σ)) + (code : program (labels .seed) = statement p labels exit .seed) + (base : K → List Bool) (ambient : σ) : + (advance (TM2.step program))^[1] + (some ⟨some (labels .seed), (ambient, none), copied p base⟩) = + some ⟨exit, (ambient, none), prepared p base⟩ := by + change some (TM2.stepAux (program (labels .seed)) _ _) = _ + rw [code] + cases exit <;> + simp [statement, TM2.stepAux, Reduction.MachineTransfer.exitAt, prepared, + p.injective.eq_iff] + +theorem trace (p : Ports K) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State σ)) + (code : ∀ l, program (labels l) = statement p labels exit l) + (base : K → List Bool) (free : Nat) (ready : Ready p base free) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[2 * free + 5] + (some ⟨some (labels .copy), (ambient, register), base⟩) = + some ⟨exit, (ambient, none), prepared p base⟩ := by + have hc := MachineCopy.copyTrace (p 0) (p 1) (p 2) + (p.injective.ne (by decide : (0 : Fin 5) ≠ 1)) + (p.injective.ne (by decide : (0 : Fin 5) ≠ 2)) + (p.injective.ne (by decide : (1 : Fin 5) ≠ 2)) + false (labels .copy) (labels .restore) (some (labels .seed)) + program (code .copy) (code .restore) base ready.scratch ambient register + have hs := seedTrace p labels exit program (code .seed) base ambient + have time : 2 * free + 5 = 1 + 2 * ((base (p 0)).length + 1) := by + rw [ready.source, encodeWord_length] + omega + rw [time, Function.iterate_add_apply, hc] + exact hs + +def inTime (p : Ports K) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State σ)) + (code : ∀ l, program (labels l) = statement p labels exit l) + (base : K → List Bool) (free : Nat) (ready : Ready p base free) + (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .copy), (ambient, register), base⟩ + (some ⟨exit, (ambient, none), prepared p base⟩) (2 * free + 5) where + steps := 2 * free + 5 + evals_in_steps := by + change (advance (TM2.step program))^[2 * free + 5] _ = _ + exact trace p labels exit program code base free ready ambient register + steps_le_m := le_rfl + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.ProducerBootstrap + + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.RootRefresh + + +open Turing MachineComposition +open UniqueGamesTheorem.Foundations.Hastad + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool + +def guard (source : K) (start : Λ) (exit : Option Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool) := + .peek source (fun state head => (state.1, head)) + (.branch (fun state => state.2.isSome) + (.goto fun _ => start) + (.load (fun state => (state.1, none)) + (Reduction.MachineTransfer.exitAt source exit))) + +theorem guardStep_nil (source : K) (again start : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atGuard : program again = guard source start exit) + (base : K → List Bool) (hinput : base source = []) + (ambient : σ) (register : Option Bool) : + TM2.step program ⟨some again, (ambient, register), base⟩ = + some ⟨exit, (ambient, none), base⟩ := by + change some (TM2.stepAux (program again) (ambient, register) base) = _ + rw [atGuard] + cases exit <;> simp [guard, TM2.stepAux, hinput, Reduction.MachineTransfer.exitAt] + +theorem guardStep_nonempty (source : K) (again start : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atGuard : program again = guard source start exit) + (base : K → List Bool) (hinput : base source ≠ []) + (ambient : σ) (register : Option Bool) : + TM2.step program ⟨some again, (ambient, register), base⟩ = + some ⟨some start, (ambient, (base source).head?), base⟩ := by + change some (TM2.stepAux (program again) (ambient, register) base) = _ + rw [atGuard] + cases hs : base source with + | nil => exact False.elim (hinput hs) + | cons bit rest => simp [guard, TM2.stepAux, hs] + +theorem fieldTapes_overwrite (source destination : K) (hne : source ≠ destination) + (base : K → List Bool) (input output input' output' : List Bool) : + SourceMachine.fieldTapes source destination + (SourceMachine.fieldTapes source destination base input output) input' output' = + SourceMachine.fieldTapes source destination base input' output' := by + funext k + by_cases hs : k = source + · subst k + simp [SourceMachine.fieldTapes, hne] + · by_cases hd : k = destination + · subst k + simp [SourceMachine.fieldTapes] + · simp [SourceMachine.fieldTapes, hs, hd] + +def steps (values : List Nat) : Nat := values.sum + 3 * values.length + 1 + +@[simp] theorem steps_nil : steps [] = 1 := rfl + +theorem steps_cons (n : Nat) (values : List Nat) : + steps (n :: values) = steps values + (n + 3) := by + simp only [steps, List.sum_cons, List.length_cons] + omega + +theorem steps_le_length (values : List Nat) : + steps values ≤ 3 * (encodeWords values).length + 1 := by + rw [encodeWords_length] + unfold steps + omega + +theorem refreshTrace (source destination : K) (hne : source ≠ destination) + (again start loopLabel : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atGuard : program again = guard source start exit) + (atStart : program start = SourceMachine.fieldStart destination loopLabel) + (atLoop : program loopLabel = + SourceMachine.fieldLoop source destination loopLabel (some again)) + (base : K → List Bool) (values : List Nat) (output : List Bool) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[steps values] + (some ⟨some again, (ambient, register), + SourceMachine.fieldTapes source destination base (encodeWords values) output⟩) = + some ⟨exit, (ambient, none), + SourceMachine.fieldTapes source destination base [] (encodeWords values.reverse ++ output)⟩ := by + induction values generalizing output register with + | nil => + simpa only [steps_nil, Function.iterate_one, advance_some, encodeWords, + List.reverse_nil, List.nil_append] using + guardStep_nil source again start exit program atGuard + (SourceMachine.fieldTapes source destination base [] output) + (SourceMachine.fieldTapes_source source destination hne base [] output) ambient register + | cons n values ih => + let initial := SourceMachine.fieldTapes source destination base + (encodeWords (n :: values)) output + have hinput : initial source = encodeWord n ++ encodeWords values := by + simp only [initial, SourceMachine.fieldTapes_source source destination hne, encodeWords] + have hnonempty : initial source ≠ [] := by + intro h + have hl := congrArg List.length h + rw [hinput, List.length_append, encodeWord_length] at hl + simp only [List.length_nil] at hl + omega + have hfield := (SourceMachine.fieldInTime source destination hne start loopLabel + (some again) program atStart atLoop initial n (encodeWords values) hinput ambient + (initial source).head?).evals_in_steps + change (advance (TM2.step program))^[n + 2] + (some ⟨some start, (ambient, (initial source).head?), initial⟩) = + some ⟨some again, (ambient, none), + SourceMachine.fieldTapes source destination initial (encodeWords values) + (encodeWord n ++ initial destination)⟩ at hfield + have hround : + (advance (TM2.step program))^[n + 3] + (some ⟨some again, (ambient, register), initial⟩) = + some ⟨some again, (ambient, none), + SourceMachine.fieldTapes source destination base (encodeWords values) + (encodeWord n ++ output)⟩ := by + change (advance (TM2.step program))^[(n + 2) + 1] _ = _ + rw [Function.iterate_succ_apply] + simp only [advance_some] + rw [guardStep_nonempty source again start exit program atGuard initial hnonempty] + simpa only [initial, SourceMachine.fieldTapes_destination, + fieldTapes_overwrite source destination hne] using hfield + rw [steps_cons, Function.iterate_add_apply, hround, ih] + simp only [List.reverse_cons, encodeWords_append, encodeWords, + List.append_nil, List.append_assoc] + +def refreshInTime (source destination : K) (hne : source ≠ destination) + (again start loopLabel : Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (σ × Option Bool)) + (atGuard : program again = guard source start exit) + (atStart : program start = SourceMachine.fieldStart destination loopLabel) + (atLoop : program loopLabel = + SourceMachine.fieldLoop source destination loopLabel (some again)) + (base : K → List Bool) (values : List Nat) (hinput : base source = encodeWords values) + (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some again, (ambient, register), base⟩ + (some ⟨exit, (ambient, none), SourceMachine.fieldTapes source destination base [] + (encodeWords values.reverse ++ base destination)⟩) + (3 * (encodeWords values).length + 1) where + steps := steps values + evals_in_steps := by + have h := refreshTrace source destination hne again start loopLabel exit program + atGuard atStart atLoop base values (base destination) ambient register + rw [← hinput, SourceMachine.fieldTapes_self] at h + exact h + steps_le_m := steps_le_length values + +theorem refresh_other (source destination other : K) (hs : other ≠ source) + (hd : other ≠ destination) (base : K → List Bool) (values : List Nat) : + SourceMachine.fieldTapes source destination base [] + (encodeWords values.reverse ++ base destination) other = base other := + SourceMachine.fieldTapes_other source destination other hs hd base _ _ + +inductive Label + | guard | start | loop + deriving DecidableEq + +protected abbrev Label.enumList : List Label := [.guard, .start, .loop] + +protected theorem Label.enumList_getElem?_ctorIdx_eq (x : Label) : + Label.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem Label.enumList_nodup : Label.enumList.Nodup := by decide + +instance : Fintype Label where + elems := ⟨Label.enumList, Label.enumList_nodup⟩ + complete x := by cases x <;> decide + +def program (source destination : K) : + Label → TM2.Stmt (Alphabet (K := K)) Label (σ × Option Bool) + | .guard => guard source .start none + | .start => SourceMachine.fieldStart destination .loop + | .loop => SourceMachine.fieldLoop source destination .loop (some .guard) + +abbrev machine : FinTM2 where + K := Fin 2 + k₀ := 0 + k₁ := 1 + Γ _ := Bool + Λ := Label + main := .guard + σ := Unit × Option Bool + initialState := ((), none) + m := program 0 1 + +theorem machineTrace (values : List Nat) : + (advance machine.step)^[steps values] + (some (initList machine (encodeWords values))) = + some (haltList machine (encodeWords values.reverse)) := by + let base : Fin 2 → List Bool := fun _ => [] + have h := refreshTrace (σ := Unit) 0 1 (by decide) .guard .start .loop none + (program 0 1) rfl rfl rfl base values [] () none + have hinit : SourceMachine.fieldTapes 0 1 base (encodeWords values) [] = + (initList machine (encodeWords values)).stk := by + funext k + fin_cases k <;> simp [SourceMachine.fieldTapes, base, initList, machine] + have hhalt : SourceMachine.fieldTapes 0 1 base [] (encodeWords values.reverse ++ []) = + (haltList machine (encodeWords values.reverse)).stk := by + funext k + fin_cases k <;> simp [SourceMachine.fieldTapes, base, haltList, machine] + rw [hinit, hhalt] at h + exact h + +noncomputable def computableInPolyTime : + TM2ComputableInPolyTime encodeWords encodeWords (List.reverse : List Nat → List Nat) where + tm := machine + inputAlphabet := Equiv.refl Bool + outputAlphabet := Equiv.refl Bool + time := 3 * Polynomial.X + 1 + outputsFun values := { + steps := steps values + evals_in_steps := by + change (advance machine.step)^[steps values] + (some (initList machine ((encodeWords values).map id))) = + some (haltList machine ((encodeWords values.reverse).map id)) + simp only [List.map_id_fun] + exact machineTrace values + steps_le_m := by simpa using steps_le_length values } + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.RootRefresh + + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.StackEncoding + +variable {Γ : Type*} + +abbrev Cells (Γ : Type*) (S : Nat) := Fin S → Option Γ + +def encode (S : Nat) (xs : List Γ) : Cells Γ S := fun i => xs[i.val]? + +def read {S : Nat} (cells : Cells Γ S) (n : Nat) : Option Γ := + if h : n < S then cells ⟨n, h⟩ else none + +def head {S : Nat} (cells : Cells Γ S) : Option Γ := read cells 0 + +def isEmpty {S : Nat} (cells : Cells Γ S) : Bool := (head cells).isNone + +def popShift {S : Nat} (cells : Cells Γ S) : Cells Γ S := + fun i => read cells (i.val + 1) + +def pushShift {S : Nat} (a : Γ) (cells : Cells Γ S) : Cells Γ S := + fun i => if h : i.val = 0 then some a else cells ⟨i.val - 1, by omega⟩ + +@[simp] theorem encode_apply (S : Nat) (xs : List Γ) (i : Fin S) : + encode S xs i = xs[i.val]? := rfl + +@[simp] theorem encode_nil (S : Nat) : encode S ([] : List Γ) = fun _ => none := by + funext i + simp [encode] + +@[simp] theorem read_at {S : Nat} (cells : Cells Γ S) (i : Fin S) : + read cells i.val = cells i := by + simp [read, i.isLt] + +theorem read_of_capacity_le {S : Nat} (cells : Cells Γ S) (n : Nat) (h : S ≤ n) : + read cells n = none := by + simp [read, Nat.not_lt.mpr h] + +theorem read_encode {S : Nat} (xs : List Γ) (hlen : xs.length ≤ S) (n : Nat) : + read (encode S xs) n = xs[n]? := by + by_cases hn : n < S + · simp [read, encode, hn] + · have hx : xs.length ≤ n := by omega + simp [read, hn, List.getElem?_eq_none hx] + +theorem head_encode {S : Nat} (xs : List Γ) (hlen : xs.length ≤ S) : + head (encode S xs) = xs.head? := by + rw [head, read_encode xs hlen, List.head?_eq_getElem?] + +theorem head_encode_eq_none_iff {S : Nat} (xs : List Γ) (hlen : xs.length ≤ S) : + head (encode S xs) = none ↔ xs = [] := by + rw [head_encode xs hlen, List.head?_eq_none_iff] + +theorem isEmpty_encode {S : Nat} (xs : List Γ) (hlen : xs.length ≤ S) : + isEmpty (encode S xs) = xs.isEmpty := by + rw [isEmpty, head_encode xs hlen] + cases xs <;> rfl + +theorem isEmpty_encode_eq_true_iff {S : Nat} (xs : List Γ) (hlen : xs.length ≤ S) : + isEmpty (encode S xs) = true ↔ xs = [] := by + rw [isEmpty_encode xs hlen] + cases xs <;> simp + +theorem encode_tail {S : Nat} (xs : List Γ) (hlen : xs.length ≤ S) : + encode S xs.tail = popShift (encode S xs) := by + funext i + change xs.tail[i.val]? = read (encode S xs) (i.val + 1) + rw [read_encode xs hlen, List.getElem?_tail] + +theorem encode_cons {S : Nat} (a : Γ) (xs : List Γ) : + encode S (a :: xs) = pushShift a (encode S xs) := by + funext i + by_cases hi : i.val = 0 <;> simp [encode, pushShift, List.getElem?_cons, hi] + +theorem tail_length_le {S : Nat} (xs : List Γ) (hlen : xs.length ≤ S) : + xs.tail.length ≤ S := by + have ht : xs.tail.length ≤ xs.length := by simp + omega + +theorem cons_length_le {S : Nat} (a : Γ) (xs : List Γ) (hroom : xs.length < S) : + (a :: xs).length ≤ S := by + simp only [List.length_cons] + omega + +theorem encode_injective {S : Nat} {xs ys : List Γ} + (hx : xs.length ≤ S) (hy : ys.length ≤ S) + (h : encode S xs = encode S ys) : xs = ys := by + apply List.ext_getElem? + intro n + rw [← read_encode xs hx n, ← read_encode ys hy n, h] + +theorem encode_eq_iff {S : Nat} {xs ys : List Γ} + (hx : xs.length ≤ S) (hy : ys.length ≤ S) : + encode S xs = encode S ys ↔ xs = ys := + ⟨encode_injective hx hy, fun h => congrArg (encode S) h⟩ + +abbrev BoundedStack (Γ : Type*) (S : Nat) := {xs : List Γ // xs.length ≤ S} + +def boundedEncoding (S : Nat) : BoundedStack Γ S ↪ Cells Γ S where + toFun xs := encode S xs.val + inj' := by + intro xs ys h + apply Subtype.ext + exact encode_injective xs.property ys.property h + +def boundedPop {S : Nat} (xs : BoundedStack Γ S) : BoundedStack Γ S := + ⟨xs.val.tail, tail_length_le xs.val xs.property⟩ + +def boundedPush {S : Nat} (a : Γ) (xs : BoundedStack Γ S) + (hroom : xs.val.length < S) : BoundedStack Γ S := + ⟨a :: xs.val, cons_length_le a xs.val hroom⟩ + +theorem boundedPop_correct {S : Nat} (xs : BoundedStack Γ S) : + boundedEncoding S (boundedPop xs) = popShift (boundedEncoding S xs) := + encode_tail xs.val xs.property + +theorem boundedPush_correct {S : Nat} (a : Γ) (xs : BoundedStack Γ S) + (hroom : xs.val.length < S) : + boundedEncoding S (boundedPush a xs hroom) = pushShift a (boundedEncoding S xs) := + encode_cons a xs.val + +section Tapes + +variable {K : Type} {Alphabet : K → Type} [DecidableEq K] + +def encodeTapes (S : Nat) (tapes : ∀ k, List (Alphabet k)) : + ∀ k, Cells (Alphabet k) S := fun k => encode S (tapes k) + +theorem encodeTapes_update (S : Nat) (tapes : ∀ k, List (Alphabet k)) + (k : K) (replacement : List (Alphabet k)) : + encodeTapes S (Function.update tapes k replacement) = + Function.update (encodeTapes S tapes) k (encode S replacement) := by + funext j + by_cases h : j = k + · subst j; simp [encodeTapes] + · simp [encodeTapes, h] + +theorem encodeTapes_pop {S : Nat} (tapes : ∀ k, List (Alphabet k)) (k : K) + (hlen : (tapes k).length ≤ S) : + encodeTapes S (Function.update tapes k (tapes k).tail) = + Function.update (encodeTapes S tapes) k (popShift (encode S (tapes k))) := by + rw [encodeTapes_update, encode_tail (tapes k) hlen] + +theorem encodeTapes_push (S : Nat) (tapes : ∀ k, List (Alphabet k)) (k : K) + (a : Alphabet k) : + encodeTapes S (Function.update tapes k (a :: tapes k)) = + Function.update (encodeTapes S tapes) k (pushShift a (encode S (tapes k))) := by + rw [encodeTapes_update, encode_cons] + +omit [DecidableEq K] in +theorem encodeTapes_injective {S : Nat} {tapes other : ∀ k, List (Alphabet k)} + (h : ∀ k, (tapes k).length ≤ S) (ho : ∀ k, (other k).length ≤ S) + (heq : encodeTapes S tapes = encodeTapes S other) : tapes = other := by + funext k + exact encode_injective (h k) (ho k) (congrFun heq k) + +end Tapes + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.StackEncoding + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/ProducerInvariant.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/ProducerInvariant.lean new file mode 100644 index 0000000000000000000000000000000000000000..3ba977a4db3bc999b1244f8020f258dc8bfe32eb --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/ProducerInvariant.lean @@ -0,0 +1,520 @@ +import OAI.Computability.PerfectCompleteness.Machines.PostfixBounds +import OAI.Computability.PerfectCompleteness.Machines.TransitionTemplate +import OAI.Computability.PerfectCompleteness.Machines.VerifierCircuit + +namespace OAI + + +noncomputable section +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.ProducerInvariant + +open StatementCircuit CircuitBatch PostfixModel PostfixAlignment + +structure Snapshot where + current : Nat + roots : List Nat + reversedRecords : List Bool + deriving DecidableEq + +private theorem snapshot_ext {s t : Snapshot} (hc : s.current = t.current) + (hr : s.roots = t.roots) (hg : s.reversedRecords = t.reversedRecords) : s = t := by + cases s + cases t + simp_all + +variable {inputs oldWidth newWidth width : Nat} + +def snapshot (f : Frame inputs width) : Snapshot where + current := inputs + f.fragment.gates.length + roots := List.ofFn (fun i => (f.wires i).val) + reversedRecords := (recordsBits (gateRecords inputs f.fragment.gates)).reverse + +def next (f : Frame inputs width) : Nat := inputs + f.fragment.gates.length +def rootValues (f : Frame inputs width) : List Nat := List.ofFn (fun i => (f.wires i).val) +def recordBits (f : Frame inputs width) : List Bool := + recordsBits (gateRecords inputs f.fragment.gates) + +def Snapshot.currentBits (s : Snapshot) : List Bool := encodeWord s.current +def Snapshot.rootBits (s : Snapshot) : List Bool := encodeWords s.roots + +def lowerStage (s : Snapshot) (tokens : List Token) : Option Snapshot := do + let (next, reversedRoots, gates) ← compileTokens s.current [] tokens + pure ⟨next, reversedRoots.reverse, + (recordsBits (gateRecords s.current gates)).reverse ++ s.reversedRecords⟩ + +def stage (es : Fin newWidth → Expr (Fin oldWidth)) (s : Snapshot) : Option Snapshot := + lowerStage s (forestTokens (fun i => s.roots[i.val]?.getD 0) (List.ofFn es)) + +theorem gateRecords_append (start : Nat) (first rest : List Gate) : + gateRecords start (first ++ rest) = + gateRecords start first ++ gateRecords (start + first.length) rest := by + induction first generalizing start with + | nil => simp [gateRecords] + | cons g gs ih => + simp [gateRecords, ih, Nat.add_comm, Nat.add_left_comm] + +theorem recordsBits_append (first rest : List CircuitProducerModel.Record) : + recordsBits (first ++ rest) = recordsBits first ++ recordsBits rest := by + simp only [recordsBits, recordsWords, List.flatMap_append, encodeWords_append] + +theorem step_roots (f : Frame inputs oldWidth) (es : Fin newWidth → Expr (Fin oldWidth)) : + (snapshot (f.step es)).roots = + Batch.roots (snapshot f).current (List.ofFn es) := by + apply List.ext_getElem + · simp [snapshot] + · intro i hi hj + simp only [snapshot, List.getElem_ofFn, Frame.step, Batch.rootAt] + +theorem lowerStage_snapshot (f : Frame inputs oldWidth) + (es : Fin newWidth → Expr (Fin oldWidth)) : + lowerStage (snapshot f) + (forestTokens (fun i => (f.wires i).val) (List.ofFn es)) = + some (snapshot (f.step es)) := by + rw [lowerStage, compile_forestTokens] + simp only [List.append_nil] + change some (Snapshot.mk ((snapshot f).current + Batch.cost (List.ofFn es)) + (Batch.roots (snapshot f).current (List.ofFn es)).reverse.reverse + ((recordsBits (gateRecords (snapshot f).current + (Batch.gates (fun i => (f.wires i).val) (snapshot f).current (List.ofFn es)))).reverse ++ + (snapshot f).reversedRecords)) = some (snapshot (f.step es)) + rw [List.reverse_reverse] + apply congrArg some + apply snapshot_ext + · simp [snapshot, Frame.step_gate_count, Nat.add_assoc] + · exact (step_roots f es).symm + · simp only [snapshot, Frame.step, Fragment.append, gateRecords_append, + recordsBits_append, List.reverse_append] + +theorem stage_snapshot (f : Frame inputs oldWidth) + (es : Fin newWidth → Expr (Fin oldWidth)) : + stage es (snapshot f) = some (snapshot (f.step es)) := by + have hw : (fun i : Fin oldWidth => (snapshot f).roots[i.val]?.getD 0) = + (fun i => (f.wires i).val) := by + funext i + simp [snapshot, i.isLt] + unfold stage + rw [hw] + exact lowerStage_snapshot f es + +def stages (es : Fin width → Expr (Fin width)) : Nat → Snapshot → Option Snapshot + | 0, s => some s + | t + 1, s => do + let previous ← stages es t s + stage es previous + +theorem stages_snapshot (f : Frame inputs width) + (es : Fin width → Expr (Fin width)) (t : Nat) : + stages es t (snapshot f) = some (snapshot (f.repeat es t)) := by + induction t with + | zero => rfl + | succ t ih => + simp only [stages, ih, Frame.repeat] + exact stage_snapshot _ _ + +theorem compile_frameForest (f : Frame inputs oldWidth) + (es : Fin newWidth → Expr (Fin oldWidth)) : + compileTokens (next f) [] + (forestTokens (fun i => (f.wires i).val) (List.ofFn es)) = + some (next (f.step es), (rootValues (f.step es)).reverse, + Batch.gates (fun i => (f.wires i).val) (next f) (List.ofFn es)) := by + have hr : rootValues (f.step es) = Batch.roots (next f) (List.ofFn es) := + step_roots f es + rw [compile_forestTokens, hr] + simp only [List.append_nil, next, Frame.step_gate_count, Nat.add_assoc] + +theorem recordBits_step (f : Frame inputs oldWidth) + (es : Fin newWidth → Expr (Fin oldWidth)) : + recordBits (f.step es) = recordBits f ++ + recordsBits (gateRecords (next f) + (Batch.gates (fun i => (f.wires i).val) (next f) (List.ofFn es))) := by + simp only [recordBits, Frame.step, Fragment.append, gateRecords_append, + recordsBits_append, next] + +theorem step_repeat (f : Frame inputs width) + (es : Fin width → Expr (Fin width)) (n : Nat) : + (f.step es).repeat es n = f.repeat es (n + 1) := by + induction n with + | zero => rfl + | succ n ih => simp only [Frame.repeat, ih] + +def circuitOutput (inputs : Nat) (s : Snapshot) : List Bool := + encodeWords [s.current, s.current - inputs, s.roots.headD 0] ++ + s.reversedRecords.reverse + +theorem circuitOutput_snapshot (f : Frame inputs 1) : + circuitOutput inputs (snapshot f) = circuitBits (f.toCircuit 0) := by + simp [circuitOutput, snapshot, circuitBits, circuitWords, Circuit.records, + Frame.toCircuit, Fragment.toCircuit, Circuit.wires, List.ofFn_succ, + recordsBits, encodeWords, List.append_assoc] + +def finalFrame (V : NPVerifier) (input : List Bool) : + Frame (2 * V.witnessBound.eval input.length + 1) 1 := + (VerifierCircuit.timeFrame V input (V.horizon input.length)).step + (fun _ : Fin 1 => VerifierCircuit.acceptanceExpr V input) + +theorem finalFrame_circuit (V : NPVerifier) (input : List Bool) : + (finalFrame V input).toCircuit 0 = VerifierCircuit.circuitOfVerifier V input := rfl + +theorem verifier_stages (V : NPVerifier) (input : List Bool) : + (do + let initialized ← stage (VerifierCircuit.initialExpressions V input) + (snapshot (Frame.initial (id : Fin (2 * V.witnessBound.eval input.length + 1) → + Fin (2 * V.witnessBound.eval input.length + 1)))) + let timed ← stages (VerifierCircuit.stepExpressions V input) + (V.horizon input.length) initialized + stage (fun _ : Fin 1 => VerifierCircuit.acceptanceExpr V input) timed) = + some (snapshot (finalFrame V input)) := by + rw [stage_snapshot] + change (do + let timed ← stages (VerifierCircuit.stepExpressions V input) + (V.horizon input.length) (snapshot (VerifierCircuit.initialFrame V input)) + stage (fun _ : Fin 1 => VerifierCircuit.acceptanceExpr V input) timed) = _ + rw [stages_snapshot] + change stage (fun _ : Fin 1 => VerifierCircuit.acceptanceExpr V input) + (snapshot (VerifierCircuit.timeFrame V input (V.horizon input.length))) = _ + exact stage_snapshot _ _ + +theorem verifier_output (V : NPVerifier) (input : List Bool) : + circuitOutput (2 * V.witnessBound.eval input.length + 1) + (snapshot (finalFrame V input)) = + circuitBits (VerifierCircuit.circuitOfVerifier V input) := + circuitOutput_snapshot (finalFrame V input) + +theorem snapshot_root_mem_lt (f : Frame inputs width) (r : Nat) + (hr : r ∈ (snapshot f).roots) : r < (snapshot f).current := by + obtain ⟨i, rfl⟩ := List.mem_ofFn.mp hr + exact (f.wires i).isLt + +theorem snapshot_rootBits_length_le (f : Frame inputs width) : + (snapshot f).rootBits.length ≤ width * ((snapshot f).current + 1) := by + have h := encodeWords_length_le (snapshot f).roots (snapshot f).current + (fun r hr => Nat.le_of_lt (snapshot_root_mem_lt f r hr)) + simpa only [Snapshot.rootBits, snapshot, List.length_ofFn] using h + +theorem snapshot_records_length_le (f : Frame inputs width) : + (snapshot f).reversedRecords.length ≤ + 4 * f.fragment.gates.length * ((snapshot f).current + 5) := by + have h := encodeWords_length_le + (recordsWords (gateRecords inputs f.fragment.gates)) + (inputs + f.fragment.gates.length + 4) + (gateRecords_fields_le inputs f.fragment.gates f.fragment.ordered) + simpa only [snapshot, List.length_reverse, recordsBits, recordsWords_length, + gateRecords_length, Nat.add_assoc] using h + +theorem snapshot_lengths_le (f : Frame inputs width) (B : Nat) + (hc : (snapshot f).current ≤ B) (hg : f.fragment.gates.length ≤ B) + (hw : width ≤ B) : + (snapshot f).currentBits.length ≤ 4 * (B + 6)^2 ∧ + (snapshot f).rootBits.length ≤ 4 * (B + 6)^2 ∧ + (snapshot f).reversedRecords.length ≤ 4 * (B + 6)^2 := by + refine ⟨?_, ?_, ?_⟩ + · simp only [Snapshot.currentBits, encodeWord_length] + nlinarith + · apply (snapshot_rootBits_length_le f).trans + have hm := Nat.mul_le_mul hw (Nat.add_le_add_right hc 1) + nlinarith + · apply (snapshot_records_length_le f).trans + have hm := Nat.mul_le_mul (Nat.mul_le_mul_left 4 hg) (Nat.add_le_add_right hc 5) + nlinarith + +theorem stage_tokenBits_length_le (f : Frame inputs oldWidth) + (es : Fin newWidth → Expr (Fin oldWidth)) (B : Nat) + (hc : (snapshot f).current ≤ B) (he : Batch.cost (List.ofFn es) ≤ B) : + (tokenBits (forestTokens (fun i => (f.wires i).val) (List.ofFn es))).length ≤ + 4 * (B + 6)^2 := by + apply (forest_tokenBits_length_le _ _ (snapshot f).current + (fun i => (f.wires i).isLt)).trans + have hmax : max 5 (snapshot f).current + 1 ≤ B + 6 := by omega + have hm := Nat.mul_le_mul (Nat.mul_le_mul_left 2 he) hmax + nlinarith + +theorem stage_countBits_length_le (f : Frame inputs oldWidth) + (es : Fin newWidth → Expr (Fin oldWidth)) (B : Nat) + (he : Batch.cost (List.ofFn es) ≤ B) : + (encodeWord ((forestTokens (fun i => (f.wires i).val) (List.ofFn es)).length)).length ≤ + 4 * (B + 6)^2 := by + simp only [encodeWord_length, forestTokens_length] + nlinarith + +def budgetPolynomial (V : NPVerifier) : Polynomial Nat := + WitnessEncoding.freeInputPolynomial V.witnessBound + VerifierCircuit.gatePolynomial V + + VerifierCircuit.widthPolynomial V + 1 + +def tapePolynomial (V : NPVerifier) : Polynomial Nat := + 4 * (budgetPolynomial V + 6)^2 + +theorem budgetPolynomial_eval (V : NPVerifier) (input : List Bool) : + (budgetPolynomial V).eval input.length = + (2 * V.witnessBound.eval input.length + 1) + + (VerifierCircuit.gatePolynomial V).eval input.length + + VerifierCircuit.width V input + 1 := by + simp only [budgetPolynomial, Polynomial.eval_add, Polynomial.eval_one, + WitnessEncoding.freeInputPolynomial_eval, VerifierCircuit.widthPolynomial_eval] + +theorem tapePolynomial_eval (V : NPVerifier) (n : Nat) : + (tapePolynomial V).eval n = 4 * ((budgetPolynomial V).eval n + 6)^2 := by + simp [tapePolynomial] + +theorem freeFrame_lengths_le (V : NPVerifier) (input : List Bool) : + let s := snapshot (Frame.initial (id : Fin (2 * V.witnessBound.eval input.length + 1) → + Fin (2 * V.witnessBound.eval input.length + 1))) + s.currentBits.length ≤ (tapePolynomial V).eval input.length ∧ + s.rootBits.length ≤ (tapePolynomial V).eval input.length ∧ + s.reversedRecords.length ≤ (tapePolynomial V).eval input.length := by + dsimp only + rw [tapePolynomial_eval] + have hb := budgetPolynomial_eval V input + apply snapshot_lengths_le + · change _ + 0 ≤ _ + omega + · change 0 ≤ _ + omega + · omega + +theorem timeFrame_gate_count (V : NPVerifier) (input : List Bool) (t : Nat) : + (VerifierCircuit.timeFrame V input t).fragment.gates.length = + Batch.cost (List.ofFn (VerifierCircuit.initialExpressions V input)) + + t * Batch.cost (List.ofFn (VerifierCircuit.stepExpressions V input)) := by + simp only [VerifierCircuit.timeFrame, Frame.repeat_gate_count, + VerifierCircuit.initialFrame, Frame.step_gate_count, Frame.initial, + Fragment.empty, List.length_nil, Nat.zero_add] + +theorem timeFrame_gates_le (V : NPVerifier) (input : List Bool) (t : Nat) + (ht : t ≤ V.horizon input.length) : + (VerifierCircuit.timeFrame V input t).fragment.gates.length ≤ + (VerifierCircuit.gatePolynomial V).eval input.length := by + apply le_trans ?_ (VerifierCircuit.circuitOfVerifier_gates_le_polynomial V input) + rw [timeFrame_gate_count, VerifierCircuit.circuitOfVerifier_gate_count] + have hm := Nat.mul_le_mul_right + (Batch.cost (List.ofFn (VerifierCircuit.stepExpressions V input))) ht + omega + +theorem timeFrame_current_le (V : NPVerifier) (input : List Bool) (t : Nat) + (ht : t ≤ V.horizon input.length) : + next (VerifierCircuit.timeFrame V input t) ≤ (budgetPolynomial V).eval input.length := by + have hg := timeFrame_gates_le V input t ht + have hb := budgetPolynomial_eval V input + unfold next + omega + +theorem transition_cost_le_budget (V : NPVerifier) (input : List Bool) + (hT : 0 < V.horizon input.length) : + Batch.cost (List.ofFn (VerifierCircuit.stepExpressions V input)) ≤ + (budgetPolynomial V).eval input.length := by + have hg := VerifierCircuit.circuitOfVerifier_gates_le_polynomial V input + rw [VerifierCircuit.circuitOfVerifier_gate_count] at hg + have hb := budgetPolynomial_eval V input + have hm := Nat.mul_le_mul_right + (Batch.cost (List.ofFn (VerifierCircuit.stepExpressions V input))) + (show 1 ≤ V.horizon input.length by omega) + omega + +theorem timeFrame_lengths_le (V : NPVerifier) (input : List Bool) (t : Nat) + (ht : t ≤ V.horizon input.length) : + let s := snapshot (VerifierCircuit.timeFrame V input t) + s.currentBits.length ≤ (tapePolynomial V).eval input.length ∧ + s.rootBits.length ≤ (tapePolynomial V).eval input.length ∧ + s.reversedRecords.length ≤ (tapePolynomial V).eval input.length := by + dsimp only + rw [tapePolynomial_eval] + have hg := timeFrame_gates_le V input t ht + have hb := budgetPolynomial_eval V input + apply snapshot_lengths_le + · change _ + _ ≤ _ + omega + · omega + · omega + +theorem initial_tokens_length_le (V : NPVerifier) (input : List Bool) : + (tokenBits (forestTokens (fun i : Fin (2 * V.witnessBound.eval input.length + 1) => i.val) + (List.ofFn (VerifierCircuit.initialExpressions V input)))).length ≤ + (tapePolynomial V).eval input.length := by + rw [tapePolynomial_eval] + have hg := VerifierCircuit.circuitOfVerifier_gates_le_polynomial V input + rw [VerifierCircuit.circuitOfVerifier_gate_count] at hg + have hb := budgetPolynomial_eval V input + apply stage_tokenBits_length_le (Frame.initial id) + · change _ + 0 ≤ _ + omega + · omega + +theorem transition_tokens_length_le (V : NPVerifier) (input : List Bool) (t : Nat) + (ht : t < V.horizon input.length) : + (tokenBits (forestTokens + (fun i => ((VerifierCircuit.timeFrame V input t).wires i).val) + (List.ofFn (VerifierCircuit.stepExpressions V input)))).length ≤ + (tapePolynomial V).eval input.length := by + rw [tapePolynomial_eval] + have hg := VerifierCircuit.circuitOfVerifier_gates_le_polynomial V input + rw [VerifierCircuit.circuitOfVerifier_gate_count] at hg + have hp := timeFrame_gates_le V input t (Nat.le_of_lt ht) + have hb := budgetPolynomial_eval V input + have hm := Nat.mul_le_mul_right + (Batch.cost (List.ofFn (VerifierCircuit.stepExpressions V input))) + (show 1 ≤ V.horizon input.length by omega) + apply stage_tokenBits_length_le (VerifierCircuit.timeFrame V input t) + · change _ + _ ≤ _ + omega + · omega + +theorem acceptance_tokens_length_le (V : NPVerifier) (input : List Bool) : + (tokenBits (forestTokens + (fun i => ((VerifierCircuit.timeFrame V input (V.horizon input.length)).wires i).val) + (List.ofFn (fun _ : Fin 1 => VerifierCircuit.acceptanceExpr V input)))).length ≤ + (tapePolynomial V).eval input.length := by + rw [tapePolynomial_eval] + have hg := VerifierCircuit.circuitOfVerifier_gates_le_polynomial V input + rw [VerifierCircuit.circuitOfVerifier_gate_count] at hg + have hp := timeFrame_gates_le V input (V.horizon input.length) le_rfl + have hb := budgetPolynomial_eval V input + apply stage_tokenBits_length_le + · change _ + _ ≤ _ + omega + · simp only [List.ofFn_succ, List.ofFn_zero, Batch.cost_cons, Batch.cost_nil, + Nat.add_zero] + omega + +theorem finalFrame_lengths_le (V : NPVerifier) (input : List Bool) : + let s := snapshot (finalFrame V input) + s.currentBits.length ≤ (tapePolynomial V).eval input.length ∧ + s.rootBits.length ≤ (tapePolynomial V).eval input.length ∧ + s.reversedRecords.length ≤ (tapePolynomial V).eval input.length := by + dsimp only + rw [tapePolynomial_eval] + have hg := VerifierCircuit.circuitOfVerifier_gates_le_polynomial V input + change (finalFrame V input).fragment.gates.length ≤ _ at hg + have hb := budgetPolynomial_eval V input + apply snapshot_lengths_le + · change _ + _ ≤ _ + omega + · omega + · omega + +def stageEnvelopePolynomial (V : NPVerifier) : Polynomial Nat := + Bounds.capacityPolynomial V.computation.time V.witnessBound + (Runtime.programPushBound V.computation.tm) + budgetPolynomial V + tapePolynomial V + 1 + +theorem stageEnvelopePolynomial_eval (V : NPVerifier) (input : List Bool) : + (stageEnvelopePolynomial V).eval input.length = + VerifierCircuit.capacity V input.length + (budgetPolynomial V).eval input.length + + (tapePolynomial V).eval input.length + 1 := by + simp [stageEnvelopePolynomial, VerifierCircuit.capacity, NPVerifier.horizon, Nat.mul_comm] + +theorem timeFrame_stageEnvelope (V : NPVerifier) (input : List Bool) (t : Nat) + (ht : t < V.horizon input.length) : + let B := (stageEnvelopePolynomial V).eval input.length + let f := VerifierCircuit.timeFrame V input t + VerifierCircuit.capacity V input.length ≤ B ∧ next f ≤ B ∧ + Batch.cost (List.ofFn (VerifierCircuit.stepExpressions V input)) ≤ B ∧ + (snapshot f).rootBits.length ≤ B ∧ + (tokenBits (forestTokens (fun i => (f.wires i).val) + (List.ofFn (VerifierCircuit.stepExpressions V input)))).length ≤ B := by + dsimp only + have hc := timeFrame_current_le V input t (Nat.le_of_lt ht) + have hcost := transition_cost_le_budget V input (by omega) + have hr := (timeFrame_lengths_le V input t (Nat.le_of_lt ht)).2.1 + have htoks := transition_tokens_length_le V input t ht + rw [stageEnvelopePolynomial_eval] + exact ⟨by omega, by omega, by omega, by omega, by omega⟩ + +theorem verifier_circuitBits_length_le (V : NPVerifier) (input : List Bool) : + (circuitBits (VerifierCircuit.circuitOfVerifier V input)).length ≤ + (tapePolynomial V).eval input.length := by + rw [tapePolynomial_eval] + apply (circuitBits_length_le (VerifierCircuit.circuitOfVerifier V input)).trans + have hg := VerifierCircuit.circuitOfVerifier_gates_le_polynomial V input + have hb := budgetPolynomial_eval V input + have hc : (VerifierCircuit.circuitOfVerifier V input).wires ≤ + (budgetPolynomial V).eval input.length := by + simp only [Circuit.wires, VerifierCircuit.circuitOfVerifier_inputs] + omega + have hgb : (VerifierCircuit.circuitOfVerifier V input).gates.length ≤ + (budgetPolynomial V).eval input.length := by omega + have hm := Nat.mul_le_mul (Nat.add_le_add_left (Nat.mul_le_mul_left 4 hgb) 3) + (Nat.add_le_add_right hc 5) + nlinarith + +section GenericTransition + +variable {K Λ σ : Type} {Γ : K → Type} + [DecidableEq K] [DecidableEq Λ] [DecidableEq σ] + [Fintype Λ] [Fintype σ] [∀ k, Fintype (Γ k)] [∀ k, DecidableEq (Γ k)] + +def stepExpressions (indexing : ConfigIndex.Indexing Γ Λ σ) + (program : Λ → Turing.TM2.Stmt Γ Λ σ) (S : Nat) : + Fin (indexing.width S + 1) → Expr (Fin (indexing.width S + 1)) := + Fin.lastCases (.input (Fin.last (indexing.width S))) + (fun j => (MachineCircuit.stickyExpr S program + ((indexing.configIndexEquiv S).symm j)).rename + (fun b => (indexing.configIndexEquiv S b).castSucc)) + +def transitionTokens (indexing : ConfigIndex.Indexing Γ Λ σ) + (program : Λ → Turing.TM2.Stmt Γ Λ σ) (S : Nat) (roots : List Nat) : List Token := + TransitionTemplate.forestTokens indexing roots S program ++ + [.input (TransitionTemplate.rootLookup roots (indexing.width S))] + +theorem transitionTokens_eq (indexing : ConfigIndex.Indexing Γ Λ σ) + (program : Λ → Turing.TM2.Stmt Γ Λ σ) (S : Nat) (roots : List Nat) : + transitionTokens indexing program S roots = + forestTokens (fun i => roots[i.val]?.getD 0) + (List.ofFn (stepExpressions indexing program S)) := by + rw [List.ofFn_succ'] + simp only [stepExpressions, Fin.lastCases_castSucc, Fin.lastCases_last, + List.concat_eq_append, forestTokens, List.flatMap_append, List.flatMap_cons, + List.flatMap_nil, exprTokens, List.append_nil] + unfold transitionTokens + rw [TransitionTemplate.forestTokens_eq] + congr 1 + simp only [TransitionTemplate.outputOrder, List.map_map, List.ofFn_eq_map, + forestTokens, List.flatMap_map] + apply List.flatMap_congr + intro i _ + rw [exprTokens_rename] + rfl + +theorem compile_transitionTokens (indexing : ConfigIndex.Indexing Γ Λ σ) + (program : Λ → Turing.TM2.Stmt Γ Λ σ) (S : Nat) + (f : Frame inputs (indexing.width S + 1)) : + compileTokens (next f) [] (transitionTokens indexing program S (rootValues f)) = + some (next (f.step (stepExpressions indexing program S)), + (rootValues (f.step (stepExpressions indexing program S))).reverse, + Batch.gates (fun i => (f.wires i).val) (next f) + (List.ofFn (stepExpressions indexing program S))) := by + rw [transitionTokens_eq] + have hw : (fun i : Fin (indexing.width S + 1) => (rootValues f)[i.val]?.getD 0) = + (fun i => (f.wires i).val) := by + funext i + unfold rootValues + rw [List.getElem?_eq_getElem (by simpa only [List.length_ofFn] using i.isLt), + List.getElem_ofFn] + rfl + rw [hw] + exact compile_frameForest f _ + +end GenericTransition + + +local instance alphabetFinite (V : NPVerifier) : ∀ k, Fintype (V.computation.tm.Γ k) := + V.finiteAlphabet +local instance labelFinite (V : NPVerifier) : Fintype V.computation.tm.Λ := + V.computation.tm.ΛFin +local instance stateFinite (V : NPVerifier) : Fintype V.computation.tm.σ := + V.computation.tm.σFin +local instance labelDecidable (V : NPVerifier) : DecidableEq V.computation.tm.Λ := + Classical.decEq _ +local instance stateDecidable (V : NPVerifier) : DecidableEq V.computation.tm.σ := + Classical.decEq _ +local instance alphabetDecidable (V : NPVerifier) : ∀ k, DecidableEq (V.computation.tm.Γ k) := + fun _ => Classical.decEq _ + +theorem stepExpressions_verifier (V : NPVerifier) (input : List Bool) : + stepExpressions (VerifierCircuit.indexing V) V.computation.tm.m + (VerifierCircuit.capacity V input.length) = + VerifierCircuit.stepExpressions V input := rfl + + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.ProducerInvariant + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/ProducerTimeLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/ProducerTimeLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..2ef756c7e5f183c3d4970840749bdb4e7ee62934 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/ProducerTimeLemmas.lean @@ -0,0 +1,843 @@ +import OAI.Computability.PerfectCompleteness.Machines.AcceptanceMachine +import OAI.Computability.PerfectCompleteness.Machines.AcceptanceStage +import OAI.Computability.PerfectCompleteness.Machines.CircuitFinish +import OAI.Computability.PerfectCompleteness.Machines.CircuitProducerStagesLemmas +import OAI.Computability.PerfectCompleteness.Machines.ForestStage +import OAI.Computability.PerfectCompleteness.Machines.ProducerArenaLemmas +import OAI.Computability.PerfectCompleteness.Machines.ProducerBootstrapLemmas +import OAI.Computability.PerfectCompleteness.Machines.ProducerInvariant +import OAI.Computability.PerfectCompleteness.Machines.TransitionIteration +import OAI.Computability.PerfectCompleteness.Machines.ValidityComposition +import OAI.Computability.PerfectCompleteness.Machines.VerifierFront +import OAI.Computability.UniqueGames.Machines.MachineCanonicalOutputLemmas + +namespace OAI + + +noncomputable section +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.ProducerTime + +open CircuitBatch StatementCircuit PostfixModel PostfixAlignment ProducerInvariant +open MachineComposition VerifierCircuit +open scoped BigOperators + +local instance (V : NPVerifier) : Fintype V.computation.tm.Λ := V.computation.tm.ΛFin +local instance (V : NPVerifier) : Fintype V.computation.tm.σ := V.computation.tm.σFin +local instance (V : NPVerifier) : ∀ k, Fintype (V.computation.tm.Γ k) := V.finiteAlphabet +local instance (V : NPVerifier) : DecidableEq V.computation.tm.Λ := Classical.decEq _ +local instance (V : NPVerifier) : DecidableEq V.computation.tm.σ := Classical.decEq _ +local instance (V : NPVerifier) : ∀ k, DecidableEq (V.computation.tm.Γ k) := + fun _ => Classical.decEq _ + +def bootstrapPolynomial (V : NPVerifier) : Polynomial Nat := + 2 * WitnessEncoding.freeInputPolynomial V.witnessBound + 5 + +def validityPolynomial (V : NPVerifier) : Polynomial Nat := + ValidityMachine.Full.timePolynomial.comp V.witnessBound + +def loweringPolynomial (V : NPVerifier) : Polynomial Nat := + ForestStage.timePolynomial.comp (4 * stageEnvelopePolynomial V + 1) + +def transitionEmissionPolynomial (V : NPVerifier) : Polynomial Nat := + (TransitionMachine.timePolynomial (indexing V) + (TransitionMachine.transitionPlan (indexing V) V.computation.tm.m)).comp + (2 * stageEnvelopePolynomial V) + +def acceptanceEmissionPolynomial (V : NPVerifier) : Polynomial Nat := + (AcceptanceMachine.timePolynomial (indexing V) (AcceptancePlan.plan V)).comp + (2 * stageEnvelopePolynomial V) + +def finishPolynomial (V : NPVerifier) : Polynomial Nat := + 9 * budgetPolynomial V + tapePolynomial V + 18 + +def iterationPolynomial (V : NPVerifier) : Polynomial Nat := + Bounds.horizonPolynomial V.computation.time V.witnessBound * + (1 + transitionEmissionPolynomial V + loweringPolynomial V) + 1 + +def knownPhasePolynomial (V : NPVerifier) : Polynomial Nat := + VerifierFront.timePolynomial V + bootstrapPolynomial V + 1 + validityPolynomial V + + loweringPolynomial V + iterationPolynomial V + acceptanceEmissionPolynomial V + + loweringPolynomial V + finishPolynomial V + +def producerPolynomial (V : NPVerifier) (cellTime : Polynomial Nat) : Polynomial Nat := + knownPhasePolynomial V + cellTime + +theorem bootstrapPolynomial_eval (V : NPVerifier) (n : Nat) : + (bootstrapPolynomial V).eval n = 2 * (2 * V.witnessBound.eval n + 1) + 5 := by + simp [bootstrapPolynomial] + +theorem validity_steps_le (V : NPVerifier) (n : Nat) : + ValidityMachine.Full.steps (V.witnessBound.eval n) ≤ (validityPolynomial V).eval n := by + simpa only [validityPolynomial, Polynomial.eval_comp] using + ValidityMachine.Full.steps_le_time (V.witnessBound.eval n) + +theorem front_steps_le (V : NPVerifier) (input : List Bool) : + (VerifierFront.prepareInTime V input ()).steps ≤ + (VerifierFront.timePolynomial V).eval input.length := + (VerifierFront.prepareInTime V input ()).steps_le_m + +theorem loweringPolynomial_eval (V : NPVerifier) (n : Nat) : + (loweringPolynomial V).eval n = + 25 * (4 * (stageEnvelopePolynomial V).eval n + 1)^2 + + 80 * (4 * (stageEnvelopePolynomial V).eval n + 1) + 20 := by + simp [loweringPolynomial, ForestStage.timePolynomial] + +theorem transitionEmissionPolynomial_eval (V : NPVerifier) (n : Nat) : + (transitionEmissionPolynomial V).eval n = + TransitionMachine.timeConstant (indexing V) + (TransitionMachine.transitionPlan (indexing V) V.computation.tm.m) * + (2 * (stageEnvelopePolynomial V).eval n + 1)^2 := by + simp [transitionEmissionPolynomial, TransitionMachine.timePolynomial] + +theorem acceptanceEmissionPolynomial_eval (V : NPVerifier) (n : Nat) : + (acceptanceEmissionPolynomial V).eval n = + AcceptanceMachine.timeConstant (indexing V) (AcceptancePlan.plan V) * + (2 * (stageEnvelopePolynomial V).eval n + 1)^2 := by + simp [acceptanceEmissionPolynomial, AcceptanceMachine.timePolynomial] + +variable {inputs oldWidth newWidth : Nat} + +def forestSteps (f : Frame inputs oldWidth) (es : Fin newWidth → Expr (Fin oldWidth)) + (oldRoots : List Bool) : Nat := + ForestStage.steps (forestTokens (fun i => (f.wires i).val) (List.ofFn es)) + (next f) (Batch.roots (next f) (List.ofFn es)).reverse + (Batch.gates (fun i => (f.wires i).val) (next f) (List.ofFn es)) oldRoots + +theorem forestSteps_le (V : NPVerifier) (input : List Bool) + (f : Frame inputs oldWidth) (es : Fin newWidth → Expr (Fin oldWidth)) + (oldRoots : List Bool) + (hc : next f ≤ (stageEnvelopePolynomial V).eval input.length) + (he : Batch.cost (List.ofFn es) ≤ (stageEnvelopePolynomial V).eval input.length) + (ht : (tokenBits (forestTokens (fun i => (f.wires i).val) (List.ofFn es))).length ≤ + (stageEnvelopePolynomial V).eval input.length) + (hr : oldRoots.length ≤ (stageEnvelopePolynomial V).eval input.length) : + forestSteps f es oldRoots ≤ (loweringPolynomial V).eval input.length := by + have h := ForestStage.forest_steps_le (fun i => (f.wires i).val) + (List.ofFn es) (next f) oldRoots (fun i => (f.wires i).isLt) + change ForestStage.steps _ _ _ _ _ ≤ _ + apply h.trans + rw [loweringPolynomial, Polynomial.eval_comp] + apply natPolynomial_eval_mono + simp only [Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_ofNat, + Polynomial.eval_one] + omega + +def initialForestSteps (V : NPVerifier) (input : List Bool) : Nat := + forestSteps (Frame.initial (id : Fin (2 * V.witnessBound.eval input.length + 1) → + Fin (2 * V.witnessBound.eval input.length + 1))) (initialExpressions V input) [] + +theorem initialForestSteps_le (V : NPVerifier) (input : List Bool) : + initialForestSteps V input ≤ (loweringPolynomial V).eval input.length := by + have hg := circuitOfVerifier_gates_le_polynomial V input + rw [circuitOfVerifier_gate_count] at hg + have hb := budgetPolynomial_eval V input + have hE := stageEnvelopePolynomial_eval V input + have ht := initial_tokens_length_le V input + apply forestSteps_le + · change _ + 0 ≤ _ + omega + · omega + · exact ht.trans (by omega) + · simp + +def transitionForestSteps (V : NPVerifier) (input : List Bool) (t : Nat) : Nat := + forestSteps (timeFrame V input t) (VerifierCircuit.stepExpressions V input) + (snapshot (timeFrame V input t)).rootBits + +theorem transitionForestSteps_le (V : NPVerifier) (input : List Bool) (t : Nat) + (ht : t < V.horizon input.length) : + transitionForestSteps V input t ≤ (loweringPolynomial V).eval input.length := by + obtain ⟨_, hc, he, hr, htok⟩ := timeFrame_stageEnvelope V input t ht + exact forestSteps_le V input _ _ _ hc he htok hr + +def acceptanceForestSteps (V : NPVerifier) (input : List Bool) : Nat := + forestSteps (timeFrame V input (V.horizon input.length)) + (fun _ : Fin 1 => acceptanceExpr V input) + (snapshot (timeFrame V input (V.horizon input.length))).rootBits + +theorem acceptanceForestSteps_le (V : NPVerifier) (input : List Bool) : + acceptanceForestSteps V input ≤ (loweringPolynomial V).eval input.length := by + have hg := circuitOfVerifier_gates_le_polynomial V input + rw [circuitOfVerifier_gate_count] at hg + have hb := budgetPolynomial_eval V input + have hE := stageEnvelopePolynomial_eval V input + have hc := timeFrame_current_le V input (V.horizon input.length) le_rfl + have hr := (timeFrame_lengths_le V input (V.horizon input.length) le_rfl).2.1 + have htok := acceptance_tokens_length_le V input + apply forestSteps_le + · omega + · simp only [List.ofFn_succ, List.ofFn_zero, Batch.cost_cons, Batch.cost_nil, Nat.add_zero] + omega + · exact htok.trans (by omega) + · exact hr.trans (by omega) + +def frameInput (V : NPVerifier) (input : List Bool) (t : Nat) : TermMachine.Input := + AcceptanceMachine.verifierInput V input (fun i => ((timeFrame V input t).wires i).val) + +theorem frameInput_dataSize_le (V : NPVerifier) (input : List Bool) (t : Nat) + (ht : t ≤ V.horizon input.length) : + TransitionMachine.dataSize (frameInput V input t) ≤ + 2 * (stageEnvelopePolynomial V).eval input.length := by + have hE := stageEnvelopePolynomial_eval V input + have hr := (timeFrame_lengths_le V input t ht).2.1 + change capacity V input.length + (snapshot (timeFrame V input t)).rootBits.length ≤ _ + omega + +def transitionEmissionSteps (V : NPVerifier) (input : List Bool) (t : Nat) : Nat := + TransitionMachine.steps (indexing V) (TransitionMachine.transitionPlan (indexing V) + V.computation.tm.m) (frameInput V input t) + +theorem transitionEmissionSteps_le (V : NPVerifier) (input : List Bool) (t : Nat) + (ht : t ≤ V.horizon input.length) : + transitionEmissionSteps V input t ≤ (transitionEmissionPolynomial V).eval input.length := by + have hv : TransitionMachine.Valid (indexing V) + (TransitionMachine.transitionPlan (indexing V) V.computation.tm.m) + (frameInput V input t) := by + simp [TransitionMachine.Valid, TransitionMachine.transitionPlan, frameInput, + AcceptanceMachine.verifierInput, width] + have h := TransitionMachine.steps_le (indexing V) + (TransitionMachine.transitionPlan (indexing V) V.computation.tm.m) (frameInput V input t) hv + change TransitionMachine.steps _ _ _ ≤ _ + have he : TransitionMachine.timeConstant (indexing V) + (TransitionMachine.transitionPlan (indexing V) V.computation.tm.m) * + (TransitionMachine.dataSize (frameInput V input t) + 1)^2 = + (TransitionMachine.timePolynomial (indexing V) + (TransitionMachine.transitionPlan (indexing V) V.computation.tm.m)).eval + (TransitionMachine.dataSize (frameInput V input t)) := by + simp [TransitionMachine.timePolynomial] + rw [he] at h + apply h.trans + rw [transitionEmissionPolynomial, Polynomial.eval_comp] + apply natPolynomial_eval_mono + simpa using frameInput_dataSize_le V input t ht + +def acceptanceEmissionSteps (V : NPVerifier) (input : List Bool) : Nat := + AcceptanceMachine.steps (indexing V) (AcceptancePlan.plan V) + (frameInput V input (V.horizon input.length)) + +theorem acceptanceEmissionSteps_le (V : NPVerifier) (input : List Bool) : + acceptanceEmissionSteps V input ≤ (acceptanceEmissionPolynomial V).eval input.length := by + have hv := AcceptanceMachine.verifierInput_valid V input + (fun i => ((timeFrame V input (V.horizon input.length)).wires i).val) + have h := AcceptanceMachine.steps_le (indexing V) (AcceptancePlan.plan V) + (frameInput V input (V.horizon input.length)) hv + change AcceptanceMachine.steps _ _ _ ≤ _ + have he : AcceptanceMachine.timeConstant (indexing V) (AcceptancePlan.plan V) * + (TransitionMachine.dataSize (frameInput V input (V.horizon input.length)) + 1)^2 = + (AcceptanceMachine.timePolynomial (indexing V) (AcceptancePlan.plan V)).eval + (TransitionMachine.dataSize (frameInput V input (V.horizon input.length))) := by + simp [AcceptanceMachine.timePolynomial] + rw [he] at h + apply h.trans + rw [acceptanceEmissionPolynomial, Polynomial.eval_comp] + apply natPolynomial_eval_mono + simpa using frameInput_dataSize_le V input (V.horizon input.length) le_rfl + +def finishSteps (V : NPVerifier) (input : List Bool) : Nat := + let C := circuitOfVerifier V input + CircuitFinish.totalTime C.wires C.inputs C.output.val (recordsBits C.records).length + +theorem finishSteps_le (V : NPVerifier) (input : List Bool) : + finishSteps V input ≤ (finishPolynomial V).eval input.length := by + let C := circuitOfVerifier V input + have hf : C.inputs ≤ C.wires := Nat.le_add_right _ _ + have h := CircuitFinish.totalTime_le C.wires C.inputs C.output.val + (recordsBits C.records).length hf C.output.isLt + have hg := circuitOfVerifier_gates_le_polynomial V input + have hb := budgetPolynomial_eval V input + have hr := (finalFrame_lengths_le V input).2.2 + have hr' : (recordsBits C.records).length ≤ (tapePolynomial V).eval input.length := by + simpa only [snapshot, List.length_reverse, Circuit.records, finalFrame, C, + circuitOfVerifier, Frame.toCircuit, Fragment.toCircuit] using hr + have hc : C.wires ≤ (budgetPolynomial V).eval input.length := by + change (2 * V.witnessBound.eval input.length + 1) + + (circuitOfVerifier V input).gates.length ≤ _ + omega + unfold finishSteps + apply h.trans + simp only [finishPolynomial, Polynomial.eval_add, Polynomial.eval_mul, + Polynomial.eval_ofNat] + omega + +theorem iterationPolynomial_eval (V : NPVerifier) (input : List Bool) : + (iterationPolynomial V).eval input.length = V.horizon input.length * + (1 + (transitionEmissionPolynomial V).eval input.length + + (loweringPolynomial V).eval input.length) + 1 := by + simp [iterationPolynomial, NPVerifier.horizon] + +def iterationSteps (V : NPVerifier) (input : List Bool) : Nat := + (∑ t ∈ Finset.range (V.horizon input.length), + (1 + transitionEmissionSteps V input t + transitionForestSteps V input t)) + 1 + +theorem iterationSteps_le (V : NPVerifier) (input : List Bool) : + iterationSteps V input ≤ (iterationPolynomial V).eval input.length := by + rw [iterationPolynomial_eval] + unfold iterationSteps + apply Nat.add_le_add_right + calc + _ ≤ ∑ _t ∈ Finset.range (V.horizon input.length), + (1 + (transitionEmissionPolynomial V).eval input.length + + (loweringPolynomial V).eval input.length) := by + apply Finset.sum_le_sum + intro t ht + have hlt := Finset.mem_range.mp ht + exact Nat.add_le_add + (Nat.add_le_add_left (transitionEmissionSteps_le V input t (Nat.le_of_lt hlt)) 1) + (transitionForestSteps_le V input t hlt) + _ = _ := by simp + +def knownPhaseSteps (V : NPVerifier) (input : List Bool) : Nat := + (VerifierFront.prepareInTime V input ()).steps + + (2 * (2 * V.witnessBound.eval input.length + 1) + 5) + 1 + + ValidityMachine.Full.steps (V.witnessBound.eval input.length) + initialForestSteps V input + + iterationSteps V input + acceptanceEmissionSteps V input + acceptanceForestSteps V input + + finishSteps V input + +theorem knownPhaseSteps_le (V : NPVerifier) (input : List Bool) : + knownPhaseSteps V input ≤ (knownPhasePolynomial V).eval input.length := by + have hf := front_steps_le V input + have hb := bootstrapPolynomial_eval V input.length + have hv := validity_steps_le V input.length + have hi := initialForestSteps_le V input + have ht := iterationSteps_le V input + have ha := acceptanceEmissionSteps_le V input + have hl := acceptanceForestSteps_le V input + have he := finishSteps_le V input + simp only [knownPhasePolynomial, Polynomial.eval_add, Polynomial.eval_one] + unfold knownPhaseSteps + omega + +theorem producerPolynomial_eval (V : NPVerifier) (cellTime : Polynomial Nat) (n : Nat) : + (producerPolynomial V cellTime).eval n = + (knownPhasePolynomial V).eval n + cellTime.eval n := by + simp only [producerPolynomial, Polynomial.eval_add] + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.ProducerTime + +end + + +noncomputable section +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.AcceptanceStage + +open Turing MachineComposition StatementCircuit CircuitBatch TransitionArena +open ProducerInvariant VerifierCircuit + + +local instance (V : NPVerifier) : Fintype V.computation.tm.Λ := V.computation.tm.ΛFin +local instance (V : NPVerifier) : Fintype V.computation.tm.σ := V.computation.tm.σFin +local instance (V : NPVerifier) : ∀ k, Fintype (V.computation.tm.Γ k) := V.finiteAlphabet +local instance (V : NPVerifier) : DecidableEq V.computation.tm.Λ := Classical.decEq _ +local instance (V : NPVerifier) : DecidableEq V.computation.tm.σ := Classical.decEq _ +local instance (V : NPVerifier) : ∀ k, DecidableEq (V.computation.tm.Γ k) := + fun _ => Classical.decEq _ + +theorem loweringSteps_eq_forestSteps (V : NPVerifier) (input : List Bool) {inputs : Nat} + (frame : Frame inputs (width V input + 1)) : + loweringSteps V input frame = + ProducerTime.forestSteps frame (expressions V input) (encodeWords (rootValues frame)) := by + unfold loweringSteps ProducerTime.forestSteps + rw [tokens_eq_forest] + have roots := step_roots frame (expressions V input) + change rootValues (frame.step (expressions V input)) = + Batch.roots (next frame) (List.ofFn (expressions V input)) at roots + rw [roots] + rfl + +theorem verifier_steps_eq (V : NPVerifier) (input : List Bool) : + steps V input (timeFrame V input (V.horizon input.length)) = + ProducerTime.acceptanceEmissionSteps V input + + ProducerTime.acceptanceForestSteps V input := by + rw [steps, loweringSteps_eq_forestSteps] + rfl + +theorem verifier_steps_le (V : NPVerifier) (input : List Bool) : + steps V input (timeFrame V input (V.horizon input.length)) ≤ + (ProducerTime.acceptanceEmissionPolynomial V + ProducerTime.loweringPolynomial V).eval + input.length := by + rw [verifier_steps_eq, Polynomial.eval_add] + exact Nat.add_le_add (ProducerTime.acceptanceEmissionSteps_le V input) + (ProducerTime.acceptanceForestSteps_le V input) + +def verifierInPolynomialTime (V : NPVerifier) (input : List Bool) + (base : Tape → List Bool) : + StateTransition.EvalsToInTime (machine V).step + ⟨some (entry V), TermMachine.initialState, + finishTapes base (capacity V input.length) + (snapshot (timeFrame V input (V.horizon input.length)))⟩ + (some ⟨none, TermMachine.initialState, + finishTapes base (capacity V input.length) (snapshot (finalFrame V input))⟩) + ((ProducerTime.acceptanceEmissionPolynomial V + ProducerTime.loweringPolynomial V).eval + input.length) where + steps := steps V input (timeFrame V input (V.horizon input.length)) + evals_in_steps := verifierTrace V input base + steps_le_m := verifier_steps_le V input + +def verifierPlacedInPolynomialTime {CallerTape CallerLabel : Type} + [DecidableEq CallerTape] (V : NPVerifier) (input : List Bool) + (ports : Tape ↪ CallerTape) (labels : Label V → CallerLabel) (exit : Option CallerLabel) + (target : CallerLabel → TM2.Stmt (fun _ : CallerTape => Bool) CallerLabel State) + (code : ∀ label, target (labels label) = + ForestPlacement.statement ports labels exit (program V label)) + (ambient : CallerTape → List Bool) (base : Tape → List Bool) : + StateTransition.EvalsToInTime (TM2.step target) + ⟨some (labels (entry V)), TermMachine.initialState, + ForestPlacement.fill ports ambient + (finishTapes base (capacity V input.length) + (snapshot (timeFrame V input (V.horizon input.length))))⟩ + (some ⟨exit, TermMachine.initialState, + ForestPlacement.fill ports ambient + (finishTapes base (capacity V input.length) (snapshot (finalFrame V input)))⟩) + ((ProducerTime.acceptanceEmissionPolynomial V + ProducerTime.loweringPolynomial V).eval + input.length) := by + simpa only [ForestPlacement.configuration, ForestPlacement.placedLabel] using + ForestPlacement.execution ports labels exit ambient (program V) target code + (verifierInPolynomialTime V input base) + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.AcceptanceStage + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.CircuitFinish + +open Turing + +variable {σ : Type} + +def verifierInitialTapes (V : NPVerifier) (input : List Bool) : Tape → List Bool := + let C := VerifierCircuit.circuitOfVerifier V input + initialTapes C.wires C.inputs C.output.val (recordsBits C.records) + +def verifierFinalTapes (V : NPVerifier) (input : List Bool) : Tape → List Bool := + memory [] [] [] [] (circuitBits (VerifierCircuit.circuitOfVerifier V input)) [] [] + +def verifierInPolynomialTime (V : NPVerifier) (input : List Bool) + (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some .copyOut, (ambient, register), verifierInitialTapes V input⟩ + (some ⟨none, (ambient, none), verifierFinalTapes V input⟩) + ((ProducerTime.finishPolynomial V).eval input.length) := by + let run := circuitInTime (VerifierCircuit.circuitOfVerifier V input) ambient register + exact { + steps := run.steps + evals_in_steps := run.evals_in_steps + steps_le_m := ProducerTime.finishSteps_le V input } + +theorem verifierInPolynomialTime_steps (V : NPVerifier) (input : List Bool) + (ambient : σ) (register : Option Bool) : + (verifierInPolynomialTime V input ambient register).steps = + ProducerTime.finishSteps V input := rfl + +def verifierPlacedInPolynomialTime {K Λ : Type} [DecidableEq K] + (ports : Tape ↪ K) (labels : Label → Λ) (exit : Option Λ) + (base : K → List Bool) + (target : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State σ)) + (code : ∀ l, target (labels l) = ForestPlacement.statement ports labels exit (program l)) + (V : NPVerifier) (input : List Bool) (ambient : σ) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step target) + ⟨some (labels .copyOut), (ambient, register), + ForestPlacement.fill ports base (verifierInitialTapes V input)⟩ + (some ⟨exit, (ambient, none), ForestPlacement.fill ports base (verifierFinalTapes V input)⟩) + ((ProducerTime.finishPolynomial V).eval input.length) := + ForestPlacement.execution ports labels exit base program target code + (verifierInPolynomialTime V input ambient register) + +theorem verifierFinal_output (V : NPVerifier) (input : List Bool) : + verifierFinalTapes V input .output = + circuitBits (VerifierCircuit.circuitOfVerifier V input) := rfl + +theorem verifierFinal_clean (V : NPVerifier) (input : List Bool) (tape : Tape) + (h : tape ≠ .output) : verifierFinalTapes V input tape = [] := by + cases tape <;> simp_all [verifierFinalTapes, memory] + +theorem verifierPlaced_output {K : Type} (ports : Tape ↪ K) (base : K → List Bool) + (V : NPVerifier) (input : List Bool) : + ForestPlacement.fill ports base (verifierFinalTapes V input) (ports .output) = + circuitBits (VerifierCircuit.circuitOfVerifier V input) := by + rw [ForestPlacement.fill_at, verifierFinal_output] + +theorem verifierPlaced_clean {K : Type} (ports : Tape ↪ K) (base : K → List Bool) + (V : NPVerifier) (input : List Bool) (tape : Tape) (h : tape ≠ .output) : + ForestPlacement.fill ports base (verifierFinalTapes V input) (ports tape) = [] := by + rw [ForestPlacement.fill_at, verifierFinal_clean V input tape h] + +theorem verifierPlaced_other {K : Type} (ports : Tape ↪ K) (base : K → List Bool) + (V : NPVerifier) (input : List Bool) (k : K) (outside : ∀ tape, ports tape ≠ k) : + ForestPlacement.fill ports base (verifierFinalTapes V input) k = base k := + ForestPlacement.fill_other ports base _ k outside + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.CircuitFinish + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.TransitionIteration + + +open Turing MachineComposition StatementCircuit CircuitBatch TransitionArena +open scoped BigOperators + +section Generic +variable {K Λ σ : Type} {Γ : K → Type} +variable [DecidableEq K] [Fintype σ] [DecidableEq σ] +variable [∀ k, DecidableEq (Γ k)] [∀ k, Fintype (Γ k)] [DecidableEq Λ] [Fintype Λ] +variable {inputs : Nat} + +theorem steps_eq_sum (indexing : ConfigIndex.Indexing Γ Λ σ) + (machineProgram : Λ → TM2.Stmt Γ Λ σ) (S : Nat) + (frame : Frame inputs (indexing.width S + 1)) (remaining : Nat) : + steps indexing machineProgram S frame remaining = + (∑ t ∈ Finset.range remaining, + (1 + stageSteps indexing machineProgram S + (frame.repeat (ProducerInvariant.stepExpressions indexing machineProgram S) t))) + 1 := by + induction remaining generalizing frame with + | zero => simp [steps] + | succ remaining ih => + rw [steps, ih, Finset.sum_range_succ'] + simp only [ProducerInvariant.step_repeat, Frame.repeat] + omega + +theorem tokens_frame_eq_forest (indexing : ConfigIndex.Indexing Γ Λ σ) + (machineProgram : Λ → TM2.Stmt Γ Λ σ) (S : Nat) + (frame : Frame inputs (indexing.width S + 1)) : + tokens indexing machineProgram S (ProducerInvariant.snapshot frame) = + PostfixAlignment.forestTokens (fun i => (frame.wires i).val) + (List.ofFn (ProducerInvariant.stepExpressions indexing machineProgram S)) := by + rw [tokens, ProducerInvariant.transitionTokens_eq] + have hw : (fun i : Fin (indexing.width S + 1) => + (ProducerInvariant.snapshot frame).roots[i.val]?.getD 0) = + (fun i => (frame.wires i).val) := by + funext i + change (List.ofFn (fun i => (frame.wires i).val))[i.val]?.getD 0 = _ + rw [List.getElem?_eq_getElem (by simpa only [List.length_ofFn] using i.isLt), List.getElem_ofFn] + rfl + rw [hw] + +theorem lowerSteps_eq_forestSteps (indexing : ConfigIndex.Indexing Γ Λ σ) + (machineProgram : Λ → TM2.Stmt Γ Λ σ) (S : Nat) + (frame : Frame inputs (indexing.width S + 1)) : + lowerSteps indexing machineProgram S frame = + ProducerTime.forestSteps frame (ProducerInvariant.stepExpressions indexing machineProgram S) + (encodeWords (ProducerInvariant.rootValues frame)) := by + unfold lowerSteps ProducerTime.forestSteps + rw [tokens_frame_eq_forest] + have roots := ProducerInvariant.step_roots frame (ProducerInvariant.stepExpressions indexing machineProgram S) + change ProducerInvariant.rootValues (frame.step (ProducerInvariant.stepExpressions indexing machineProgram S)) = _ at roots + rw [roots] + rfl + +end Generic + +local instance (V : NPVerifier) : Fintype V.computation.tm.Λ := V.computation.tm.ΛFin +local instance (V : NPVerifier) : Fintype V.computation.tm.σ := V.computation.tm.σFin +local instance (V : NPVerifier) : ∀ k, Fintype (V.computation.tm.Γ k) := V.finiteAlphabet +local instance (V : NPVerifier) : DecidableEq V.computation.tm.Λ := Classical.decEq _ +local instance (V : NPVerifier) : DecidableEq V.computation.tm.σ := Classical.decEq _ +local instance (V : NPVerifier) : ∀ k, DecidableEq (V.computation.tm.Γ k) := + fun _ => Classical.decEq _ + +theorem stageSteps_verifier (V : NPVerifier) (input : List Bool) (t : Nat) : + stageSteps (VerifierCircuit.indexing V) V.computation.tm.m + (VerifierCircuit.capacity V input.length) (VerifierCircuit.timeFrame V input t) = + ProducerTime.transitionEmissionSteps V input t + ProducerTime.transitionForestSteps V input t := by + rw [stageSteps, lowerSteps_eq_forestSteps, ProducerInvariant.stepExpressions_verifier] + rfl + +theorem verifier_steps_eq (V : NPVerifier) (input : List Bool) : + steps (VerifierCircuit.indexing V) V.computation.tm.m + (VerifierCircuit.capacity V input.length) (VerifierCircuit.initialFrame V input) + (V.horizon input.length) = ProducerTime.iterationSteps V input := by + rw [steps_eq_sum, ProducerInvariant.stepExpressions_verifier] + unfold ProducerTime.iterationSteps + congr 1 + apply Finset.sum_congr rfl + intro t _ + change 1 + stageSteps (VerifierCircuit.indexing V) V.computation.tm.m + (VerifierCircuit.capacity V input.length) (VerifierCircuit.timeFrame V input t) = _ + rw [stageSteps_verifier] + omega + +theorem verifier_steps_le (V : NPVerifier) (input : List Bool) : + steps (VerifierCircuit.indexing V) V.computation.tm.m + (VerifierCircuit.capacity V input.length) (VerifierCircuit.initialFrame V input) + (V.horizon input.length) ≤ (ProducerTime.iterationPolynomial V).eval input.length := by + rw [verifier_steps_eq] + exact ProducerTime.iterationSteps_le V input + +noncomputable def verifierInPolynomialTime (V : NPVerifier) (input : List Bool) + (base : Tape → List Bool) : + StateTransition.EvalsToInTime + (machine (VerifierCircuit.indexing V) V.computation.tm.m).step + ⟨some (entry (VerifierCircuit.indexing V) V.computation.tm.m), TermMachine.initialState, + tapes base (VerifierCircuit.capacity V input.length) (V.horizon input.length) + (ProducerInvariant.snapshot (VerifierCircuit.initialFrame V input))⟩ + (some ⟨none, TermMachine.initialState, + finishTapes base (VerifierCircuit.capacity V input.length) + (ProducerInvariant.snapshot (VerifierCircuit.timeFrame V input (V.horizon input.length)))⟩) + ((ProducerTime.iterationPolynomial V).eval input.length) where + steps := steps (VerifierCircuit.indexing V) V.computation.tm.m + (VerifierCircuit.capacity V input.length) (VerifierCircuit.initialFrame V input) (V.horizon input.length) + evals_in_steps := repeatTrace (VerifierCircuit.indexing V) V.computation.tm.m base + (VerifierCircuit.capacity V input.length) (VerifierCircuit.initialFrame V input) (V.horizon input.length) + steps_le_m := verifier_steps_le V input + +noncomputable def verifierPlacedInPolynomialTime {CallerTape CallerLabel : Type} + [DecidableEq CallerTape] (V : NPVerifier) (input : List Bool) + (ports : Tape ↪ CallerTape) + (labels : Label (VerifierCircuit.indexing V) V.computation.tm.m → CallerLabel) + (exit : Option CallerLabel) + (target : CallerLabel → TM2.Stmt (fun _ : CallerTape => Bool) CallerLabel State) + (code : ∀ label, target (labels label) = ForestPlacement.statement ports labels exit + (program (VerifierCircuit.indexing V) V.computation.tm.m label)) + (ambient : CallerTape → List Bool) (base : Tape → List Bool) : + StateTransition.EvalsToInTime (TM2.step target) + ⟨some (labels (entry (VerifierCircuit.indexing V) V.computation.tm.m)), TermMachine.initialState, + ForestPlacement.fill ports ambient + (tapes base (VerifierCircuit.capacity V input.length) (V.horizon input.length) + (ProducerInvariant.snapshot (VerifierCircuit.initialFrame V input)))⟩ + (some ⟨exit, TermMachine.initialState, + ForestPlacement.fill ports ambient (finishTapes base (VerifierCircuit.capacity V input.length) + (ProducerInvariant.snapshot (VerifierCircuit.timeFrame V input (V.horizon input.length))))⟩) + ((ProducerTime.iterationPolynomial V).eval input.length) := by + simpa only [ForestPlacement.configuration, ForestPlacement.placedLabel] using + ForestPlacement.execution ports labels exit ambient + (program (VerifierCircuit.indexing V) V.computation.tm.m) target code + (verifierInPolynomialTime V input base) + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.TransitionIteration + +end + + +noncomputable section +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.ProducerTailStage + +open Turing ProducerArena ProducerInvariant ProducerHandoffs + +local instance (V : NPVerifier) : Fintype V.computation.tm.Λ := V.computation.tm.ΛFin +local instance (V : NPVerifier) : Fintype V.computation.tm.σ := V.computation.tm.σFin +local instance (V : NPVerifier) : ∀ k, Fintype (V.computation.tm.Γ k) := V.finiteAlphabet +local instance (V : NPVerifier) : DecidableEq V.computation.tm.Λ := Classical.decEq _ +local instance (V : NPVerifier) : DecidableEq V.computation.tm.σ := Classical.decEq _ +local instance (V : NPVerifier) : ∀ k, DecidableEq (V.computation.tm.Γ k) := + fun _ => Classical.decEq _ + +abbrev IterateLabel (V : NPVerifier) := + TransitionIteration.Label (VerifierCircuit.indexing V) V.computation.tm.m +abbrev Label (V : NPVerifier) := + IterateLabel V ⊕ (AcceptanceStage.Label V ⊕ CircuitFinish.Label) + +def entry (V : NPVerifier) : Label V := + .inl (TransitionIteration.entry (VerifierCircuit.indexing V) V.computation.tm.m) + +def statement {Λ : Type} (V : NPVerifier) (labels : Label V → Λ) (exit : Option Λ) : + Label V → TM2.Stmt (Alphabet V) Λ State + | .inl l => ForestPlacement.statement (transitionPorts V) + (fun l => labels (.inl l)) (some (labels (.inr (.inl (AcceptanceStage.entry V))))) + (TransitionIteration.program (VerifierCircuit.indexing V) V.computation.tm.m l) + | .inr (.inl l) => ForestPlacement.statement (transitionPorts V) + (fun l => labels (.inr (.inl l))) (some (labels (.inr (.inr .copyOut)))) + (AcceptanceStage.program V l) + | .inr (.inr l) => ForestPlacement.statement (finishPorts V) + (fun l => labels (.inr (.inr l))) exit (CircuitFinish.program (σ := Unit × Bool) l) + +def initial (V : NPVerifier) (input : List Bool) : Tape V → List Bool := + boundary V input (V.horizon input.length) (snapshot (VerifierCircuit.initialFrame V input)) + +def afterIteration (V : NPVerifier) (input : List Bool) : Tape V → List Bool := + finished V input (snapshot (VerifierCircuit.timeFrame V input (V.horizon input.length))) + +def afterAcceptance (V : NPVerifier) (input : List Bool) : Tape V → List Bool := + finished V input (snapshot (ProducerInvariant.finalFrame V input)) + +def terminal (V : NPVerifier) (input : List Bool) : Tape V → List Bool := + ForestPlacement.fill (finishPorts V) (afterAcceptance V input) + (CircuitFinish.verifierFinalTapes V input) + +def timePolynomial (V : NPVerifier) : Polynomial Nat := + ProducerTime.iterationPolynomial V + + (ProducerTime.acceptanceEmissionPolynomial V + ProducerTime.loweringPolynomial V) + + ProducerTime.finishPolynomial V + +theorem finish_entry (V : NPVerifier) (input : List Bool) : + ForestPlacement.fill (finishPorts V) (afterAcceptance V input) + (CircuitFinish.verifierInitialTapes V input) = afterAcceptance V input := by + have h := circuitFinish_view V input + change (fun t => afterAcceptance V input (finishPorts V t)) = + CircuitFinish.verifierInitialTapes V input at h + rw [← h, ForestPlacement.fill_self] + +def inTime {Λ : Type} (V : NPVerifier) (labels : Label V → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet V) Λ State) + (code : ∀ l, program (labels l) = statement V labels exit l) + (input : List Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels (entry V)), initialState, initial V input⟩ + (some ⟨exit, initialState, terminal V input⟩) + ((timePolynomial V).eval input.length) := by + have iter := TransitionIteration.verifierPlacedInPolynomialTime V input + (transitionPorts V) (fun l => labels (.inl l)) + (some (labels (.inr (.inl (AcceptanceStage.entry V))))) program + (fun l => code (.inl l)) (bootstrapPrepared V input) (localBase V input) + have iter' : StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels (entry V)), initialState, initial V input⟩ + (some ⟨some (labels (.inr (.inl (AcceptanceStage.entry V)))), initialState, + afterIteration V input⟩) + ((ProducerTime.iterationPolynomial V).eval input.length) := iter + have accept := AcceptanceStage.verifierPlacedInPolynomialTime V input + (transitionPorts V) (fun l => labels (.inr (.inl l))) + (some (labels (.inr (.inr .copyOut)))) program + (fun l => code (.inr (.inl l))) (bootstrapPrepared V input) (localBase V input) + have accept' : StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels (.inr (.inl (AcceptanceStage.entry V)))), initialState, + afterIteration V input⟩ + (some ⟨some (labels (.inr (.inr .copyOut))), initialState, + afterAcceptance V input⟩) + ((ProducerTime.acceptanceEmissionPolynomial V + ProducerTime.loweringPolynomial V).eval + input.length) := accept + have finish := CircuitFinish.verifierPlacedInPolynomialTime (finishPorts V) + (fun l => labels (.inr (.inr l))) exit (afterAcceptance V input) program + (fun l => code (.inr (.inr l))) V input ((), false) none + rw [finish_entry] at finish + have combined := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ + (StateTransition.EvalsToInTime.trans _ _ _ _ _ _ iter' accept') finish + simpa only [timePolynomial, Polynomial.eval_add, terminal, initialState, + TermMachine.initialState, Nat.add_comm, Nat.add_left_comm, Nat.add_assoc] using combined + +def program (V : NPVerifier) : Label V → TM2.Stmt (Alphabet V) (Label V) State := + statement V id none + +def programInTime (V : NPVerifier) (input : List Bool) : + StateTransition.EvalsToInTime (TM2.step (program V)) + ⟨some (entry V), initialState, initial V input⟩ + (some ⟨none, initialState, terminal V input⟩) + ((timePolynomial V).eval input.length) := + inTime V id none (program V) (fun _ => rfl) input + +theorem terminal_output (V : NPVerifier) (input : List Bool) : + terminal V input (output V) = circuitBits (VerifierCircuit.circuitOfVerifier V input) := by + change ForestPlacement.fill (finishPorts V) _ _ (finishPorts V .output) = _ + rw [ForestPlacement.fill_at, CircuitFinish.verifierFinal_output] + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.ProducerTailStage + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.ProducerMachine + +open Turing ProducerArena + +local instance (V : NPVerifier) : Fintype V.computation.tm.Λ := V.computation.tm.ΛFin +local instance (V : NPVerifier) : Fintype V.computation.tm.σ := V.computation.tm.σFin +local instance (V : NPVerifier) : ∀ k, Fintype (V.computation.tm.Γ k) := V.finiteAlphabet +local instance (V : NPVerifier) : DecidableEq V.computation.tm.Λ := Classical.decEq _ +local instance (V : NPVerifier) : DecidableEq V.computation.tm.σ := Classical.decEq _ +local instance (V : NPVerifier) : ∀ k, DecidableEq (V.computation.tm.Γ k) := + fun _ => Classical.decEq _ + +abbrev Label (V : NPVerifier) := + ProducerFrontStage.Label V ⊕ (InitializationStage.Label V ⊕ ProducerTailStage.Label V) + +def initPorts (V : NPVerifier) : InitializationStage.FullPorts (Tape V) where + emit := initializationPorts V + lower := forestPorts V + output_shared := rfl + count_shared := rfl + +def initLabels (V : NPVerifier) : InitializationStage.Label V ↪ Label V := + ⟨fun l => .inr (.inl l), by intro a b h; exact Sum.inl.inj (Sum.inr.inj h)⟩ + +def entry (V : NPVerifier) : Label V := .inl (ProducerFrontStage.entry V) + +def program (V : NPVerifier) : Label V → TM2.Stmt (Alphabet V) (Label V) State + | .inl l => ProducerFrontStage.statement V Sum.inl + (some (initLabels V (InitializationStage.entry V))) l + | .inr (.inl l) => InitializationStage.statement V (initPorts V) (initLabels V) + (some (.inr (.inr (ProducerTailStage.entry V)))) l + | .inr (.inr l) => ProducerTailStage.statement V (fun l => .inr (.inr l)) none l + +def timePolynomial (V : NPVerifier) : Polynomial Nat := + ProducerFrontStage.timePolynomial V + InitializationStage.timePolynomial V + + ProducerTailStage.timePolynomial V + +theorem initializerReady (V : NPVerifier) (input : List Bool) : + InitializationStage.FullReady V (initPorts V) (bootstrapPrepared V input) input := + ⟨ProducerHandoffs.bootstrap_emitter_ready V input, + ProducerHandoffs.bootstrap_lowerer_ready V input⟩ + +def inTime (V : NPVerifier) (input : List Bool) : + StateTransition.EvalsToInTime (TM2.step (program V)) + ⟨some (entry V), initialState, initialTapes V input⟩ + (some ⟨none, initialState, ProducerTailStage.terminal V input⟩) + ((timePolynomial V).eval input.length) := by + have front := ProducerFrontStage.inTime V Sum.inl + (some (initLabels V (InitializationStage.entry V))) (program V) + (fun _ => rfl) input + have init := InitializationStage.verifierPlacedInPolynomialTime V (initPorts V) + (initLabels V) (some (.inr (.inr (ProducerTailStage.entry V)))) + (program V) (fun _ => rfl) (bootstrapPrepared V input) input + (initializerReady V input) () + have init' : StateTransition.EvalsToInTime (TM2.step (program V)) + ⟨some (initLabels V (InitializationStage.entry V)), initialState, bootstrapPrepared V input⟩ + (some ⟨some (.inr (.inr (ProducerTailStage.entry V))), initialState, + ProducerTailStage.initial V input⟩) + ((InitializationStage.timePolynomial V).eval input.length) := by + simpa only [initPorts, ProducerHandoffs.initial_result_eq_boundary, + ProducerTailStage.initial, initialState, TermMachine.initialState, + ClashMachine.clean] using init + have tail := ProducerTailStage.inTime V (fun l => .inr (.inr l)) none + (program V) (fun _ => rfl) input + have combined := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ + (StateTransition.EvalsToInTime.trans _ _ _ _ _ _ front init') tail + simpa only [entry, timePolynomial, Polynomial.eval_add, + Nat.add_comm, Nat.add_left_comm, Nat.add_assoc] using combined + +def rawProgram (V : NPVerifier) : MachineCanonicalOutput.Program (Tape V) (Label V) State where + input := raw V + output := output V + main := entry V + initial := initialState + code := program V + +theorem initialCfg (V : NPVerifier) (input : List Bool) : + initList (MachineCanonicalOutput.sourceMachine (rawProgram V)) input = + (⟨some (entry V), initialState, initialTapes V input⟩ : + (MachineCanonicalOutput.sourceMachine (rawProgram V)).Cfg) := by + unfold initList + congr 1 + funext k + rw [initialTapes_eq] + by_cases h : k = raw V <;> + simp [MachineCanonicalOutput.sourceMachine, rawProgram, h] <;> rfl + +def terminalRun (V : NPVerifier) (input : List Bool) : + MachineCanonicalOutput.TerminalRun (rawProgram V) input + (circuitBits (VerifierCircuit.circuitOfVerifier V input)) + ((timePolynomial V).eval input.length) where + state := initialState + tapes := ProducerTailStage.terminal V input + execution := by + rw [initialCfg] + exact inTime V input + output_eq := ProducerTailStage.terminal_output V input + +def cleanupTapes (V : NPVerifier) : List (Tape V) := + (Finset.univ.erase (output V)).toList + +theorem cleanup_complete (V : NPVerifier) (k : Tape V) : + k ∈ cleanupTapes V ↔ k ≠ (rawProgram V).output := by + simp [cleanupTapes, rawProgram] + +def computableInPolyTime (V : NPVerifier) : + TM2ComputableInPolyTime id circuitBits (VerifierCircuit.circuitOfVerifier V) := + MachineCanonicalOutput.computableInPolyTime (rawProgram V) (cleanupTapes V) + (cleanup_complete V) id circuitBits (VerifierCircuit.circuitOfVerifier V) + (timePolynomial V) (terminalRun V) + +theorem finiteAlphabet (V : NPVerifier) : + MachineFiniteAlphabet.FiniteAlphabet (computableInPolyTime V).tm := + MachineCanonicalOutput.computableInPolyTime_finite_alphabet + (rawProgram V) (cleanupTapes V) (cleanup_complete V) + id circuitBits (VerifierCircuit.circuitOfVerifier V) (timePolynomial V) (terminalRun V) + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.ProducerMachine + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/ScalarTapeCardinality.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/ScalarTapeCardinality.lean new file mode 100644 index 0000000000000000000000000000000000000000..2dafda1ea40836d01ab142832c1efa783cb04da6 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/ScalarTapeCardinality.lean @@ -0,0 +1,67 @@ +import OAI.Computability.PerfectCompleteness.Construction.SourceQuestionOrderLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.ScalarTapeCardinality + +open TreeSourceSpaces TreeCardinality RecursiveSampler DescendantSpaces +open scoped BigOperators + +noncomputable section + +variable {branch : Nat → Nat} {n m t : Nat} + +def drawHeight (repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n m) → DrawIndex repeats p → Nat + | n, _, .refl _, _ => n + | n + 1, _, .step _ p, j => + match j with + | Sum.inl _ => n + | Sum.inr j => drawHeight repeats p j.2 + +def tapeBound (repeats : Nat → Nat) (p : Path branch n m) (t : Nat) : Nat := + ∏ j : DrawIndex repeats p, functionBound branch (drawHeight repeats p j) t + +theorem drawSpace_card_le (repeats : Nat → Nat) (p : Path branch n m) : + ∀ (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (j : DrawIndex repeats p), + Nat.card (DrawSpace F2 repeats p (LeafDomain slots) j) ≤ + functionBound branch (drawHeight repeats p j) t := by + induction p with + | refl n => + intro slots j + exact H_card_le slots + | @step n m i p ih => + intro slots j + cases j with + | inl j => exact square_card_le (childSlots slots j.val) + | inr j => exact ih (childSlots slots i) j.2 + +theorem tape_card_le (repeats : Nat → Nat) (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) : + Nat.card (Tape F2 repeats p (LeafDomain slots)) ≤ tapeBound repeats p t := by + change Nat.card (∀ j : DrawIndex repeats p, + DrawSpace F2 repeats p (LeafDomain slots) j) ≤ _ + rw [Nat.card_pi] + exact Finset.prod_le_prod (fun j _ => drawSpace_card_le repeats p slots j) + +def bucketBound (rows repeats : Nat → Nat) (p : Path branch n m) (t : Nat) : Nat := + tapeBound repeats p t ^ Nat.card (BucketSampler.Direction (rows n)) + +theorem bucket_card_le (rows repeats : Nat → Nat) (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) : + Nat.card (BucketSampler.RecursiveTape (rows n) repeats p (LeafDomain slots)) ≤ + bucketBound rows repeats p t := by + change Nat.card (BucketSampler.Direction (rows n) → + Tape F2 repeats p (LeafDomain slots)) ≤ _ + rw [Nat.card_fun] + exact pow_le_pow_left₀ (Nat.zero_le _) (tape_card_le repeats p slots) _ + +end +end PerfectCompleteness.ScalarTapeCardinality + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/SignedDescriptorStageMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/SignedDescriptorStageMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..dbe194edb8377efd67a4c4900f66bbf6f0fcf4d6 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/SignedDescriptorStageMachine.lean @@ -0,0 +1,271 @@ +import OAI.Computability.PerfectCompleteness.Foundations.SignedScheduleIndex +import OAI.Computability.PerfectCompleteness.Machines.CompletedEdgeMachine + +namespace OAI + + +namespace PerfectCompleteness.SignedDescriptorStageMachine + + +open Turing UniqueGamesTheorem.Foundations.Complexity +open CanonicalKeys MetadataFreeSampler +open scoped Classical + +noncomputable section + +variable {branch : Nat → Nat} {n t q : Nat} {rows repeats : Nat → Nat} + (hq : 0 < q) + (large : CanonicalKeyEncoding.partitionWidth (TreeCanonical.locationCount branch n t) ≤ q) + +local notation "width" => TreeCanonical.locationCount branch n t + +abbrev Descriptor := SignedCompletionSchedule.Descriptor (rows := rows) (repeats := repeats) hq large + +abbrev Context (A : Type) := A × Option (Descriptor (rows := rows) (repeats := repeats) hq large) + +abbrev State (A : Type) := + CompletedEdgeMachine.State (Context (rows := rows) (repeats := repeats) hq large A) + +def clean {A : Type} (ambient : A) : State (rows := rows) (repeats := repeats) hq large A := + CompletedEdgeMachine.clean (ambient, none) + +def loaded {A : Type} (ambient : A) + (descriptor : Descriptor (rows := rows) (repeats := repeats) hq large) : + State (rows := rows) (repeats := repeats) hq large A := + CompletedEdgeMachine.clean (ambient, some descriptor) + +def save {A : Type} (state : State (rows := rows) (repeats := repeats) hq large A) + (descriptor : Descriptor (rows := rows) (repeats := repeats) hq large) : + State (rows := rows) (repeats := repeats) hq large A := loaded hq large state.1.1.1 descriptor + +inductive Label (α : Type) (locations : Nat) + | load + | dispatch + | edge (descriptor : α) (localLabel : CompletedEdgeMachine.Label locations) + | finish + deriving DecidableEq, Fintype + +theorem state_finite {A : Type} [Finite A] : + Finite (State (rows := rows) (repeats := repeats) hq large A) := inferInstance + +theorem label_finite : + Finite (Label (Descriptor (rows := rows) (repeats := repeats) hq large) width) := inferInstance + +variable (hn : 0 < n) (hbranch : ∀ k < n, 0 < branch k) + (hrows : ∀ k, 0 < rows (k + 1)) + +local notation "D" => SignedMultiplicity.denominator branch n t rows repeats hn hbranch hrows q +local notation "StageLabel" => Label (Descriptor (rows := rows) (repeats := repeats) hq large) width + +variable {K Λ A : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool + +def selected (selectSigns : A → SignTuple branch n t) (i : Fin D) + (state : State (rows := rows) (repeats := repeats) hq large A) : + Descriptor (rows := rows) (repeats := repeats) hq large := + state.1.1.2.getD + (SignedScheduleIndex.atIndex (branch := branch) (n := n) (t := t) + (rows := rows) (repeats := repeats) hq large hn hbranch hrows (selectSigns state.1.1.1) i) + +def finish (count : K) (exit : Option Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (State (rows := rows) (repeats := repeats) hq large A) := + .push count (fun _ => true) + (.load (fun state => clean hq large state.1.1.1) + (match exit with | none => .halt | some label => .goto (fun _ => label))) + +theorem finish_trace (count : K) (exit : Option Λ) + (state : State (rows := rows) (repeats := repeats) hq large A) + (base : K → List Bool) : + TM2.stepAux (finish hq large count exit) state base = + ⟨exit, clean hq large state.1.1.1, Function.update base count (true :: base count)⟩ := by + cases exit <;> rfl + +omit [DecidableEq K] in +theorem finish_pushBound (count : K) (exit : Option Λ) : + Runtime.statementPushBound + (finish (rows := rows) (repeats := repeats) (A := A) hq large count exit) = 1 := by + cases exit <;> rfl + +variable [Fintype A] [DecidableEq A] + +def instruction (selectSigns : A → SignTuple branch n t) (i : Fin D) + (source : Fin width → Fin 6 → K) (work : Fin 10 → K) (count : K) + (labels : StageLabel → Λ) (exit rejected : Option Λ) : + StageLabel → TM2.Stmt (Alphabet (K := K)) Λ (State (rows := rows) (repeats := repeats) hq large A) + | .load => SignedScheduleIndex.instruction hq large hn hbranch hrows + (fun state : State (rows := rows) (repeats := repeats) hq large A => selectSigns state.1.1.1) + (save hq large) i (labels .dispatch) + | .dispatch => .goto (fun state => + labels (.edge (selected hq large hn hbranch hrows selectSigns i state) + (CompletedEdgeMachine.main width))) + | .edge descriptor localLabel => CompletedEdgeMachine.instruction hq large descriptor + source work (fun l => labels (.edge descriptor l)) (labels .finish) rejected localLabel + | .finish => finish hq large count exit + +def finalTapes (descriptor : Descriptor (rows := rows) (repeats := repeats) hq large) + (work : Fin 10 → K) (count : K) + (base : K → List Bool) (leftPrefix rightPrefix : List (Key width)) + (ids : Fin width → Nat) (vars : Fin width → Fin 3 → Nat) : K → List Bool := + let edgeTapes : K → List Bool := CompletedEdgeMachine.finalTapes hq large descriptor work base + leftPrefix rightPrefix ids vars + Function.update edgeTapes count (true :: edgeTapes count) + +theorem finalTapes_frame (descriptor : Descriptor (rows := rows) (repeats := repeats) hq large) + (work : Fin 10 → K) (count : K) (base : K → List Bool) + (leftPrefix rightPrefix : List (Key width)) + (ids : Fin width → Nat) (vars : Fin width → Fin 3 → Nat) (k : K) + (notLeft : k ≠ work 1) (notRight : k ≠ work 8) + (notOutput : k ≠ work 7) (notCount : k ≠ count) : + finalTapes hq large descriptor work count base leftPrefix rightPrefix ids vars k = base k := by + simp only [finalTapes, Function.update_of_ne notCount] + exact CompletedEdgeMachine.finalTapes_frame hq large descriptor work base + leftPrefix rightPrefix ids vars k notLeft notRight notOutput + +theorem finalTapes_count (descriptor : Descriptor (rows := rows) (repeats := repeats) hq large) + (work : Fin 10 → K) (count : K) (base : K → List Bool) + (leftPrefix rightPrefix : List (Key width)) + (ids : Fin width → Nat) (vars : Fin width → Fin 3 → Nat) + (notLeft : count ≠ work 1) (notRight : count ≠ work 8) (notOutput : count ≠ work 7) : + finalTapes hq large descriptor work count base leftPrefix rightPrefix ids vars count = + true :: base count := by + simp only [finalTapes, Function.update_self] + rw [CompletedEdgeMachine.finalTapes_frame hq large descriptor work base + leftPrefix rightPrefix ids vars count notLeft notRight notOutput] + +private theorem stageBudget (cost : Nat) : 1 + (cost + (1 + 1)) ≤ cost + 3 := by + omega + +private def stageInTimeForDescriptor (selectSigns : A → SignTuple branch n t) (i : Fin D) + (descriptor : Descriptor (branch := branch) (n := n) (t := t) + (rows := rows) (repeats := repeats) hq large) + (ids : Fin width → Nat) (vars : Fin width → Fin 3 → Nat) + (source : Fin width → Fin 6 → K) (sourceDistinct : ∀ j, Function.Injective (source j)) + (work : Fin 10 → K) (workDistinct : Function.Injective work) + (sharedScratch : ∀ j, source j 4 = work 5) (sharedOutput : ∀ j, source j 5 = work 9) + (sourceAvoid : ∀ j field k, KeyMetadataMachine.idTape (source j) field ≠ work k) + (count : K) (labels : StageLabel → Λ) (exit rejected : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State (rows := rows) (repeats := repeats) hq large A)) + (atLabels : ∀ label, program (labels label) = + instruction (branch := branch) (n := n) (t := t) (q := q) + (rows := rows) (repeats := repeats) hq large hn hbranch hrows + selectSigns i source work count labels exit rejected label) + (base : K → List Bool) (ambient : A) (leftPrefix rightPrefix : List (Key width)) + (sourceWords : ∀ j field, base (KeyMetadataMachine.idTape (source j) field) = + encodeWord (KeyMetadataMachine.fieldValue (ids j) (vars j) field)) + (leftDictionary : base (work 1) = BinaryNameSearch.stream (CanonicalVertexNames.tokens leftPrefix)) + (rightDictionary : base (work 8) = BinaryNameSearch.stream (CanonicalVertexNames.tokens rightPrefix)) + (empty : ∀ j : Fin 10, j ≠ 1 → j ≠ 7 → j ≠ 8 → base (work j) = []) + (selectedEq : SignedScheduleIndex.atIndex (branch := branch) (n := n) (t := t) + (rows := rows) (repeats := repeats) hq large hn hbranch hrows (selectSigns ambient) i = descriptor) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .load), clean hq large ambient, base⟩ + (some ⟨exit, clean hq large ambient, + finalTapes hq large descriptor work count base leftPrefix rightPrefix ids vars⟩) + (CompletedEdgeMachine.budget (branch := branch) (n := n) (t := t) + (rows := rows) (repeats := repeats) hq large descriptor source base leftPrefix rightPrefix ids vars + 3) := by + let edgeTapes : K → List Bool := CompletedEdgeMachine.finalTapes + (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) + hq large descriptor work base + leftPrefix rightPrefix ids vars + have loadRun : StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .load), clean hq large ambient, base⟩ + (some ⟨some (labels .dispatch), loaded hq large ambient descriptor, base⟩) 1 := by + have run := SignedScheduleIndex.inTime (branch := branch) (n := n) (t := t) (q := q) + (rows := rows) (repeats := repeats) hq large hn hbranch hrows + (fun state : State (rows := rows) (repeats := repeats) hq large A => selectSigns state.1.1.1) + (save hq large) i (labels .dispatch) program (labels .load) + (atLabels .load) (clean hq large ambient) base + change StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .load), clean hq large ambient, base⟩ + (some ⟨some (labels .dispatch), loaded hq large ambient + (SignedScheduleIndex.atIndex (branch := branch) (n := n) (t := t) + (rows := rows) (repeats := repeats) hq large hn hbranch hrows (selectSigns ambient) i), + base⟩) 1 at run + rw [selectedEq] at run + exact run + have dispatchRun : StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .dispatch), loaded hq large ambient descriptor, base⟩ + (some ⟨some (labels (.edge descriptor (CompletedEdgeMachine.main width))), + loaded hq large ambient descriptor, base⟩) 1 := by + refine { steps := 1, evals_in_steps := ?_, steps_le_m := Nat.le_refl 1 } + change some (TM2.stepAux (program (labels .dispatch)) + (loaded hq large ambient descriptor) base) = _ + rw [atLabels .dispatch] + rfl + have edgeRun : StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels (.edge descriptor (CompletedEdgeMachine.main width))), + loaded hq large ambient descriptor, base⟩ + (some ⟨some (labels .finish), loaded hq large ambient descriptor, edgeTapes⟩) + (CompletedEdgeMachine.budget (branch := branch) (n := n) (t := t) + (rows := rows) (repeats := repeats) hq large descriptor + source base leftPrefix rightPrefix ids vars) := + CompletedEdgeMachine.edgeInTime (branch := branch) (n := n) (t := t) (q := q) + (rows := rows) (repeats := repeats) hq large descriptor ids vars source sourceDistinct + work workDistinct sharedScratch sharedOutput sourceAvoid + (fun l => labels (.edge descriptor l)) (labels .finish) rejected program + (fun l => atLabels (.edge descriptor l)) base (ambient, some descriptor) + leftPrefix rightPrefix sourceWords leftDictionary rightDictionary empty + have finishRun : StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .finish), loaded hq large ambient descriptor, edgeTapes⟩ + (some ⟨exit, clean hq large ambient, + finalTapes hq large descriptor work count base leftPrefix rightPrefix ids vars⟩) 1 := by + refine { steps := 1, evals_in_steps := ?_, steps_le_m := Nat.le_refl 1 } + change some (TM2.stepAux (program (labels .finish)) + (loaded hq large ambient descriptor) edgeTapes) = _ + rw [atLabels .finish] + change some (TM2.stepAux (finish hq large count exit) + (loaded hq large ambient descriptor) edgeTapes) = _ + rw [finish_trace] + rfl + have joined := StateTransition.EvalsToInTime.trans (TM2.step program) _ _ _ _ _ + (StateTransition.EvalsToInTime.trans (TM2.step program) _ _ _ _ _ + (StateTransition.EvalsToInTime.trans (TM2.step program) _ _ _ _ _ loadRun dispatchRun) + edgeRun) finishRun + exact + { steps := joined.steps + evals_in_steps := joined.evals_in_steps + steps_le_m := joined.steps_le_m.trans (stageBudget _) } + +def stageInTime (selectSigns : A → SignTuple branch n t) (i : Fin D) + (ids : Fin width → Nat) (vars : Fin width → Fin 3 → Nat) + (source : Fin width → Fin 6 → K) (sourceDistinct : ∀ j, Function.Injective (source j)) + (work : Fin 10 → K) (workDistinct : Function.Injective work) + (sharedScratch : ∀ j, source j 4 = work 5) (sharedOutput : ∀ j, source j 5 = work 9) + (sourceAvoid : ∀ j field k, KeyMetadataMachine.idTape (source j) field ≠ work k) + (count : K) (labels : StageLabel → Λ) (exit rejected : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State (rows := rows) (repeats := repeats) hq large A)) + (atLabels : ∀ label, program (labels label) = + instruction (branch := branch) (n := n) (t := t) (q := q) + (rows := rows) (repeats := repeats) hq large hn hbranch hrows + selectSigns i source work count labels exit rejected label) + (base : K → List Bool) (ambient : A) (leftPrefix rightPrefix : List (Key width)) + (sourceWords : ∀ j field, base (KeyMetadataMachine.idTape (source j) field) = + encodeWord (KeyMetadataMachine.fieldValue (ids j) (vars j) field)) + (leftDictionary : base (work 1) = BinaryNameSearch.stream (CanonicalVertexNames.tokens leftPrefix)) + (rightDictionary : base (work 8) = BinaryNameSearch.stream (CanonicalVertexNames.tokens rightPrefix)) + (empty : ∀ j : Fin 10, j ≠ 1 → j ≠ 7 → j ≠ 8 → base (work j) = []) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .load), clean hq large ambient, base⟩ + (some ⟨exit, clean hq large ambient, + finalTapes hq large + (SignedScheduleIndex.atIndex (branch := branch) (n := n) (t := t) + (rows := rows) (repeats := repeats) hq large hn hbranch hrows (selectSigns ambient) i) + work count base leftPrefix rightPrefix ids vars⟩) + (CompletedEdgeMachine.budget (branch := branch) (n := n) (t := t) + (rows := rows) (repeats := repeats) hq large + (SignedScheduleIndex.atIndex (branch := branch) (n := n) (t := t) + (rows := rows) (repeats := repeats) hq large hn hbranch hrows (selectSigns ambient) i) + source base leftPrefix rightPrefix ids vars + 3) := + stageInTimeForDescriptor (branch := branch) (n := n) (t := t) (q := q) + (rows := rows) (repeats := repeats) hq large hn hbranch hrows selectSigns i + (SignedScheduleIndex.atIndex (branch := branch) (n := n) (t := t) + (rows := rows) (repeats := repeats) hq large hn hbranch hrows (selectSigns ambient) i) + ids vars source sourceDistinct work workDistinct sharedScratch sharedOutput sourceAvoid + count labels exit rejected program atLabels base ambient leftPrefix rightPrefix + sourceWords leftDictionary rightDictionary empty rfl + +end +end PerfectCompleteness.SignedDescriptorStageMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/SignedRuntimeBounds.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/SignedRuntimeBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..2586b4b73ebd69b6f4700c21c169351ed8414c74 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/SignedRuntimeBounds.lean @@ -0,0 +1,319 @@ +import OAI.Computability.PerfectCompleteness.Foundations.SignedCostEnvelope +import OAI.Computability.PerfectCompleteness.Foundations.SignedTupleSemantics +import OAI.Computability.PerfectCompleteness.Foundations.SourceKeyBoundsLemmas + +namespace OAI + + +namespace PerfectCompleteness.SignedRuntimeBounds + + +open CanonicalKeys MetadataFreeSampler +open UniqueGamesTheorem.Foundations.Complexity +open scoped BigOperators Classical + +noncomputable section + +def KeyBound {width : Nat} (T : Nat) (key : Key width) : Prop := + key.retained.length ≤ width ∧ + ∀ entry ∈ key.retained, KeyMetadataEncoding.entryID entry.2 ≤ T + +def KeysBound {width : Nat} (T : Nat) (keys : List (Key width)) : Prop := + ∀ key ∈ keys, KeyBound T key + +theorem keysBound_append {width T : Nat} {keys : List (Key width)} {key : Key width} + (earlier : KeysBound T keys) (last : KeyBound T key) : + KeysBound T (keys ++ [key]) := by + intro candidate present + rcases List.mem_append.mp present with present | present + · exact earlier candidate present + · have same : candidate = key := by simpa using present + simpa only [same] using last + +theorem endpoint_budget_le {width T count : Nat} {K : Type} [DecidableEq K] + (source : Fin width → Fin 6 → K) (base : K → List Bool) + (earlier : List (Key width)) (key : Key width) + (sourceBound : CanonicalKeyMachine.sourceLength source base ≤ 4 * width * (T + 1)) + (earlierBound : KeysBound T earlier) (keyBound : KeyBound T key) + (countBound : earlier.length + 1 ≤ count) : + CanonicalEndpointMachine.budget source base earlier key ≤ + SignedCostEnvelope.endpointBound width T count := by + have allBound := keysBound_append earlierBound keyBound + have payloadBound := CanonicalVertexNames.payload_length_le key T keyBound.1 keyBound.2 + have streamBound : + (BinaryNameSearch.stream (CanonicalVertexNames.tokens (earlier ++ [key]))).length ≤ + CanonicalDictionaryNames.streamBound width T count := by + have h := CanonicalVertexNames.stream_length_le (earlier ++ [key]) T + (fun candidate present => (allBound candidate present).1) + (fun candidate present => (allBound candidate present).2) + apply h.trans + apply Nat.mul_le_mul_left + simpa only [List.length_append, List.length_singleton] using countBound + have squareBound := Nat.pow_le_pow_left streamBound 2 + unfold CanonicalEndpointMachine.budget SignedCostEnvelope.endpointBound + nlinarith + +section Fold + +variable {branch : Nat → Nat} {n t q : Nat} {rows repeats : Nat → Nat} + (hq : 0 < q) + (large : CanonicalKeyEncoding.partitionWidth (TreeCanonical.locationCount branch n t) ≤ q) + (hn : 0 < n) (hbranch : ∀ k < n, 0 < branch k) + (hrows : ∀ k, 0 < rows (k + 1)) + +local notation "width" => TreeCanonical.locationCount branch n t +local notation "D" => SignedMultiplicity.denominator branch n t rows repeats hn hbranch hrows q + +theorem fold_budget_le {K : Type} [DecidableEq K] (T count : Nat) + (signs : SignTuple branch n t) (ids : Fin width → Nat) + (vars : Fin width → Fin 3 → Nat) (source : Fin width → Fin 6 → K) + (work : Fin 10 → K) (countTape : K) (base : K → List Bool) + (sourceBound : ∀ data : SignedTupleBodyMachine.Data width, + CanonicalKeyMachine.sourceLength source + (SignedTupleBodyMachine.tapes work countTape base data) ≤ 4 * width * (T + 1)) + (leftBound : ∀ i : Fin D, KeyBound T (CompletedEdgeMachine.key hq large + (SignedScheduleIndex.atIndex hq large hn hbranch hrows signs i) .left ids vars)) + (rightBound : ∀ i : Fin D, KeyBound T (CompletedEdgeMachine.key hq large + (SignedScheduleIndex.atIndex hq large hn hbranch hrows signs i) .right ids vars)) + (indices : List (Fin D)) (data : SignedTupleBodyMachine.Data width) + (leftEarlier : KeysBound T data.leftKeys) (rightEarlier : KeysBound T data.rightKeys) + (leftCount : data.leftKeys.length + indices.length ≤ count) + (rightCount : data.rightKeys.length + indices.length ≤ count) : + SignedTupleBodyMachine.budget hq large hn hbranch hrows signs ids vars + source work countTape base indices data ≤ + indices.length * (2 * SignedCostEnvelope.endpointBound width T count + 4) := by + induction indices generalizing data with + | nil => simp only [SignedTupleBodyMachine.budget, List.length_nil, Nat.zero_mul, le_refl] + | cons i indices ih => + let descriptor := SignedScheduleIndex.atIndex hq large hn hbranch hrows signs i + have leftCount' : data.leftKeys.length + 1 ≤ count := by + simp only [List.length_cons] at leftCount + omega + have rightCount' : data.rightKeys.length + 1 ≤ count := by + simp only [List.length_cons] at rightCount + omega + have leftCost := endpoint_budget_le source + (SignedTupleBodyMachine.tapes work countTape base data) data.leftKeys + (CompletedEdgeMachine.key hq large descriptor .left ids vars) + (sourceBound data) leftEarlier (leftBound i) leftCount' + have rightCost := endpoint_budget_le source + (SignedTupleBodyMachine.tapes work countTape base data) data.rightKeys + (CompletedEdgeMachine.key hq large descriptor .right ids vars) + (sourceBound data) rightEarlier (rightBound i) rightCount' + have edgeCost : CompletedEdgeMachine.budget hq large descriptor source + (SignedTupleBodyMachine.tapes work countTape base data) + data.leftKeys data.rightKeys ids vars ≤ + 2 * SignedCostEnvelope.endpointBound width T count + 1 := by + unfold CompletedEdgeMachine.budget + omega + have nextLeft : KeysBound T + (SignedTupleBodyMachine.next hq large descriptor ids vars data).leftKeys := + keysBound_append leftEarlier (leftBound i) + have nextRight : KeysBound T + (SignedTupleBodyMachine.next hq large descriptor ids vars data).rightKeys := + keysBound_append rightEarlier (rightBound i) + have nextLeftCount : + (SignedTupleBodyMachine.next hq large descriptor ids vars data).leftKeys.length + + indices.length ≤ count := by + simpa only [SignedTupleBodyMachine.next, List.length_append, List.length_singleton, + List.length_cons, List.length_nil, Nat.add_zero, Nat.zero_add, + Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using leftCount + have nextRightCount : + (SignedTupleBodyMachine.next hq large descriptor ids vars data).rightKeys.length + + indices.length ≤ count := by + simpa only [SignedTupleBodyMachine.next, List.length_append, List.length_singleton, + List.length_cons, List.length_nil, Nat.add_zero, Nat.zero_add, + Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using rightCount + have rest := ih (SignedTupleBodyMachine.next hq large descriptor ids vars data) + nextLeft nextRight nextLeftCount nextRightCount + change CompletedEdgeMachine.budget hq large descriptor source + (SignedTupleBodyMachine.tapes work countTape base data) + data.leftKeys data.rightKeys ids vars + 3 + + SignedTupleBodyMachine.budget hq large hn hbranch hrows signs ids vars + source work countTape base indices + (SignedTupleBodyMachine.next hq large descriptor ids vars data) ≤ _ + calc + _ ≤ (2 * SignedCostEnvelope.endpointBound width T count + 1) + 3 + + indices.length * (2 * SignedCostEnvelope.endpointBound width T count + 4) := + Nat.add_le_add (Nat.add_le_add_right edgeCost 3) rest + _ = (i :: indices).length * + (2 * SignedCostEnvelope.endpointBound width T count + 4) := by + simp only [List.length_cons] + ring + +end Fold + + +variable {branch : Nat → Nat} {n t : Nat} + (input : NormalizedSourceInput.Input) (rows repeats : Nat → Nat) + (hn : 0 < n) (hbranch : ∀ k < n, 0 < branch k) + (hrows : ∀ k, 0 < rows (k + 1)) (δ : ℚ) + +local notation "width" => TreeCanonical.locationCount branch n t +local notation "clauses" => NormalizedSourceInput.clauses input +local notation "T" => List.length (NormalizedSourceInput.bits input) +local notation "q" => FinitePreliminaryCompletion.alphabet branch n t δ +local notation "hq" => CanonicalLocalCompletion.alphabet_positive width δ +local notation "large" => CanonicalLocalCompletion.partitionWidth_le_alphabet width δ +local notation "D" => SignedMultiplicity.denominator branch n t rows repeats hn hbranch hrows q +local notation "C" => CompletedSignedLaw.Completed (t := t) clauses rows repeats hn hbranch hrows δ +local notation "order" => CompletedVisitOrder.completedOrder + (t := t) clauses rows repeats hn hbranch hrows δ +local notation "localOrder" => CompletedVisitOrder.localOrder + (t := t) clauses rows repeats hn hbranch hrows δ +local notation "dataOfPrefix" => SignedTupleSemantics.dataOfPrefix + (t := t) clauses rows repeats hn hbranch hrows δ + +theorem completedOrder_length_le : (order).length ≤ D * (T + 1) ^ width := by + rw [CompletedVisitOrder.completedOrder_length] + exact Nat.mul_le_mul_left D + (Nat.pow_le_pow_left ((SourceKeyBounds.clauseCount_le_bits input).trans (Nat.le_succ T)) width) + +theorem left_atIndex_bound + (source : PreliminarySampler.Questions branch n t (NormalizedSourceInput.clauseCount input)) + (i : Fin D) : + KeyBound T (CompletedEdgeMachine.key hq large + (SignedScheduleIndex.atIndex hq large hn hbranch hrows (sourceSigns clauses source) i) + .left (SignedTupleSemantics.sourceIDs source) + (SignedTupleSemantics.sourceVariables clauses source)) := by + let e := SignedTupleSemantics.occurrenceAt clauses rows repeats hn hbranch hrows δ source i + have same := SignedTupleSemantics.left_key clauses rows repeats hn hbranch hrows δ e + simp only [e, SignedTupleSemantics.descriptorOf_occurrenceAt, + SignedTupleSemantics.occurrenceAt_source] at same + rw [same] + exact ⟨SourceKeyBounds.left_retained_length input rows repeats e.1, + SourceKeyBounds.left_entryID_le input rows repeats e.1⟩ + +theorem right_atIndex_bound + (source : PreliminarySampler.Questions branch n t (NormalizedSourceInput.clauseCount input)) + (i : Fin D) : + KeyBound T (CompletedEdgeMachine.key hq large + (SignedScheduleIndex.atIndex hq large hn hbranch hrows (sourceSigns clauses source) i) + .right (SignedTupleSemantics.sourceIDs source) + (SignedTupleSemantics.sourceVariables clauses source)) := by + let e := SignedTupleSemantics.occurrenceAt clauses rows repeats hn hbranch hrows δ source i + have same := SignedTupleSemantics.right_key clauses rows repeats hn hbranch hrows δ e + simp only [e, SignedTupleSemantics.descriptorOf_occurrenceAt, + SignedTupleSemantics.occurrenceAt_source] at same + rw [same] + exact ⟨SourceKeyBounds.right_retained_length input rows repeats e.1, + SourceKeyBounds.right_entryID_le input rows repeats e.1⟩ + +theorem left_prefix_bound (earlier : List C) (tail : List Bool) : + KeysBound T (dataOfPrefix earlier tail).leftKeys := by + intro key present + change key ∈ earlier.map _ at present + obtain ⟨e, _, rfl⟩ := List.mem_map.mp present + exact ⟨SourceKeyBounds.left_retained_length input rows repeats e.1, + SourceKeyBounds.left_entryID_le input rows repeats e.1⟩ + +theorem right_prefix_bound (earlier : List C) (tail : List Bool) : + KeysBound T (dataOfPrefix earlier tail).rightKeys := by + intro key present + change key ∈ earlier.map _ at present + obtain ⟨e, _, rfl⟩ := List.mem_map.mp present + exact ⟨SourceKeyBounds.right_retained_length input rows repeats e.1, + SourceKeyBounds.right_entryID_le input rows repeats e.1⟩ + +theorem bodyBudget_le_envelope {Extra : Type} [DecidableEq Extra] + (indices : NormalizedTarget.SourceTuple (branch := branch) (n := n) (t := t) input) + (base : SignedTupleLayout.Tape width Extra → List Bool) + (physical : SignedTupleLayout.Input input.formula indices base) + (earlier suffix : List C) (tail : List Bool) + (split : order = earlier ++ localOrder (NormalizedTarget.tupleQuestion input indices) ++ suffix) : + SignedTupleBodyMachine.bodyBudget + (branch := branch) (n := n) (t := t) («q» := q) (rows := rows) (repeats := repeats) + hq large hn hbranch hrows input.formula indices base + (dataOfPrefix earlier tail) ≤ SignedCostEnvelope.bodyBound width D T := by + let source := NormalizedTarget.tupleQuestion input indices + have countBound : earlier.length + D ≤ D * (T + 1) ^ width := by + have total := completedOrder_length_le (t := t) input rows repeats hn hbranch hrows δ + rw [split, List.length_append, List.length_append, + CompletedVisitOrder.localOrder_length] at total + omega + have ids_eq : SignedTupleLayout.ids input.formula indices = + SignedTupleSemantics.sourceIDs source := by + simp only [source, NormalizedTarget.tupleQuestion, SignedTupleSemantics.sourceIDs_tuple] + rfl + have vars_eq : SignedTupleLayout.vars input.formula indices = + SignedTupleSemantics.sourceVariables clauses source := by + simp only [source, NormalizedTarget.tupleQuestion, SignedTupleSemantics.sourceVariables_tuple] + rfl + have selectedLeft (i : Fin D) : KeyBound T (CompletedEdgeMachine.key hq large + (SignedScheduleIndex.atIndex hq large hn hbranch hrows + (SourceTupleScheduleMachine.sourceSigns input.formula indices) i) + .left (SignedTupleLayout.ids input.formula indices) (SignedTupleLayout.vars input.formula indices)) := by + rw [NormalizedTarget.sourceSigns_eq, ids_eq, vars_eq] + exact left_atIndex_bound input rows repeats hn hbranch hrows δ source i + have selectedRight (i : Fin D) : KeyBound T (CompletedEdgeMachine.key hq large + (SignedScheduleIndex.atIndex hq large hn hbranch hrows + (SourceTupleScheduleMachine.sourceSigns input.formula indices) i) + .right (SignedTupleLayout.ids input.formula indices) (SignedTupleLayout.vars input.formula indices)) := by + rw [NormalizedTarget.sourceSigns_eq, ids_eq, vars_eq] + exact right_atIndex_bound input rows repeats hn hbranch hrows δ source i + have leftCount : (dataOfPrefix earlier tail).leftKeys.length + + (SignedTupleBodyMachine.allStages (t := t) («q» := q) (rows := rows) (repeats := repeats) + hn hbranch hrows).length ≤ D * (T + 1) ^ width := by + simpa only [SignedTupleSemantics.dataOfPrefix, ExactTargetOnlineEncoding.leftKeys, + List.length_map, SignedTupleBodyMachine.allStages, List.length_ofFn] using countBound + have rightCount : (dataOfPrefix earlier tail).rightKeys.length + + (SignedTupleBodyMachine.allStages (t := t) («q» := q) (rows := rows) (repeats := repeats) + hn hbranch hrows).length ≤ D * (T + 1) ^ width := by + simpa only [SignedTupleSemantics.dataOfPrefix, ExactTargetOnlineEncoding.rightKeys, + List.length_map, SignedTupleBodyMachine.allStages, List.length_ofFn] using countBound + have folded := fold_budget_le hq large hn hbranch hrows T (D * (T + 1) ^ width) + (SourceTupleScheduleMachine.sourceSigns input.formula indices) + (SignedTupleLayout.ids input.formula indices) (SignedTupleLayout.vars input.formula indices) + SignedTupleLayout.metadata SignedTupleLayout.Tape.edgeWork SignedTupleLayout.Tape.edgeCount + (SignedTupleLayout.preparedTapes input.formula indices base) + (SignedSourceCost.prepared_sourceLength_le input indices base physical) + selectedLeft selectedRight (SignedTupleBodyMachine.allStages hn hbranch hrows) + (dataOfPrefix earlier tail) + (left_prefix_bound input rows repeats hn hbranch hrows δ earlier tail) + (right_prefix_bound input rows repeats hn hbranch hrows δ earlier tail) leftCount rightCount + have preparation := SignedTuplePreparationMachine.budget_le width T + unfold SignedTupleBodyMachine.bodyBudget SignedCostEnvelope.bodyBound + change 1 + SignedTuplePreparationMachine.budget width T + _ + 7 * width * (T + 2) + 1 ≤ _ + simp only [SignedTupleBodyMachine.allStages, List.length_ofFn] at folded ⊢ + change _ ≤ D * (2 * SignedCostEnvelope.endpointBound width T (D * (T + 1) ^ width) + 4) + at folded + omega + +theorem bodyBudget_le_polynomial {Extra : Type} [DecidableEq Extra] + (indices : NormalizedTarget.SourceTuple (branch := branch) (n := n) (t := t) input) + (base : SignedTupleLayout.Tape width Extra → List Bool) + (physical : SignedTupleLayout.Input input.formula indices base) + (earlier suffix : List C) (tail : List Bool) + (split : order = earlier ++ localOrder (NormalizedTarget.tupleQuestion input indices) ++ suffix) : + SignedTupleBodyMachine.bodyBudget + (branch := branch) (n := n) (t := t) («q» := q) (rows := rows) (repeats := repeats) + hq large hn hbranch hrows input.formula indices base + (dataOfPrefix earlier tail) ≤ + SignedCostEnvelope.bodyCoeff width D * (T + 1) ^ SignedCostEnvelope.degree width := + (bodyBudget_le_envelope input rows repeats hn hbranch hrows δ + indices base physical earlier suffix tail split).trans (SignedCostEnvelope.bodyBound_le width D T) + +theorem outerBudget_le_polynomial : + (SignedCostEnvelope.bodyCoeff width D * (T + 1) ^ SignedCostEnvelope.degree width + + 2 * width) * (NormalizedSourceInput.clauseCount input) ^ width ≤ + (SignedCostEnvelope.bodyCoeff width D + 2 * width) * + (T + 1) ^ (SignedCostEnvelope.degree width + width) := by + have visits : (NormalizedSourceInput.clauseCount input) ^ width ≤ (T + 1) ^ width := + Nat.pow_le_pow_left ((SourceKeyBounds.clauseCount_le_bits input).trans (Nat.le_succ T)) width + have positive : 1 ≤ (T + 1) ^ SignedCostEnvelope.degree width := + Nat.one_le_pow _ _ (Nat.succ_pos T) + have overhead : 2 * width ≤ 2 * width * (T + 1) ^ SignedCostEnvelope.degree width := by + simpa only [Nat.mul_one] using Nat.mul_le_mul_left (2 * width) positive + calc + _ ≤ ((SignedCostEnvelope.bodyCoeff width D + 2 * width) * + (T + 1) ^ SignedCostEnvelope.degree width) * (T + 1) ^ width := by + apply Nat.mul_le_mul _ visits + rw [Nat.add_mul] + exact Nat.add_le_add_left overhead _ + _ = _ := by rw [Nat.pow_add]; ring + +end + +end PerfectCompleteness.SignedRuntimeBounds + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/SignedTupleBodyMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/SignedTupleBodyMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..ecb1e99ceed1ce3ab85d3e8f32fd60e8945bf06f --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/SignedTupleBodyMachine.lean @@ -0,0 +1,504 @@ +import OAI.Computability.PerfectCompleteness.Foundations.SignedTupleLayout +import OAI.Computability.PerfectCompleteness.Machines.SignedDescriptorStageMachine +import OAI.Computability.PerfectCompleteness.Machines.SignedTupleCleanupMachineLemmas +import OAI.Computability.UniqueGames.Machines.MachineCompositionLemmas + +namespace OAI + + +namespace PerfectCompleteness.SignedTupleBodyMachine + + +open Turing UniqueGamesTheorem.Foundations.Complexity +open MachineComposition CanonicalKeys MetadataFreeSampler +open scoped Classical + +noncomputable section + +abbrev Tape (width : Nat) (Extra : Type) := SignedTupleLayout.Tape width Extra + +inductive BodyLabel (locations steps : Nat) (Descriptor Extra : Type) where + | start + | prepare (label : SignedTuplePreparationMachine.Label locations) + | edges (label : MachineFiniteSequence.Label + (fun _ : Fin steps => SignedDescriptorStageMachine.Label Descriptor locations) (List.ofFn id)) + | cleanup (label : SignedTupleCleanupMachine.Label locations Extra) + | reset + deriving DecidableEq, Fintype + +structure Data (width : Nat) where + leftKeys : List (Key width) + rightKeys : List (Key width) + reversedOutput : List Bool + count : Nat + +variable {branch : Nat → Nat} {n t q : Nat} {rows repeats : Nat → Nat} + (hq : 0 < q) + (large : CanonicalKeyEncoding.partitionWidth (TreeCanonical.locationCount branch n t) ≤ q) + (hn : 0 < n) (hbranch : ∀ k < n, 0 < branch k) + (hrows : ∀ k, 0 < rows (k + 1)) + +local notation "width" => TreeCanonical.locationCount branch n t +local notation "D" => SignedMultiplicity.denominator branch n t rows repeats hn hbranch hrows q +local notation "Desc" => SignedDescriptorStageMachine.Descriptor + (rows := rows) (repeats := repeats) hq large + +variable {K Λ A : Type} [DecidableEq K] + +def tapes (work : Fin 10 → K) (countTape : K) (base : K → List Bool) + (data : Data width) : K → List Bool := + Function.update + (Function.update + (Function.update + (Function.update base (work 1) + (BinaryNameSearch.stream (CanonicalVertexNames.tokens data.leftKeys))) + (work 8) (BinaryNameSearch.stream (CanonicalVertexNames.tokens data.rightKeys))) + (work 7) data.reversedOutput) + countTape (encodeWord data.count) + +def next (descriptor : Desc) (ids : Fin width → Nat) (vars : Fin width → Fin 3 → Nat) + (data : Data width) : Data width where + leftKeys := data.leftKeys ++ [CompletedEdgeMachine.key hq large descriptor .left ids vars] + rightKeys := data.rightKeys ++ [CompletedEdgeMachine.key hq large descriptor .right ids vars] + reversedOutput := + (CompletedEdgeMachine.edgeBits hq large descriptor data.leftKeys data.rightKeys ids vars).reverse ++ + data.reversedOutput + count := data.count + 1 + +theorem finalTapes_eq (descriptor : Desc) (ids : Fin width → Nat) + (vars : Fin width → Fin 3 → Nat) (work : Fin 10 → K) + (distinct : Function.Injective work) (countTape : K) + (countAvoid : ∀ j, countTape ≠ work j) (base : K → List Bool) (data : Data width) : + SignedDescriptorStageMachine.finalTapes hq large descriptor work countTape + (tapes work countTape base data) data.leftKeys data.rightKeys ids vars = + tapes work countTape base (next hq large descriptor ids vars data) := by + have hd (i j : Fin 10) (hne : i ≠ j) : work i ≠ work j := + fun h => hne (distinct h) + funext k + by_cases hc : k = countTape + · subst k + simp [SignedDescriptorStageMachine.finalTapes, CompletedEdgeMachine.finalTapes, + tapes, next, countAvoid, encodeWord, List.replicate_succ] + · by_cases hl : k = work 1 + · subst k + simp [SignedDescriptorStageMachine.finalTapes, CompletedEdgeMachine.finalTapes, + tapes, next, hc, hd 1 8 (by decide), hd 1 7 (by decide)] + · by_cases hr : k = work 8 + · subst k + simp [SignedDescriptorStageMachine.finalTapes, CompletedEdgeMachine.finalTapes, + tapes, next, hc, hd 8 7 (by decide)] + · by_cases ho : k = work 7 + · subst k + simp [SignedDescriptorStageMachine.finalTapes, CompletedEdgeMachine.finalTapes, + tapes, next, hc] + · simp only [SignedDescriptorStageMachine.finalTapes, CompletedEdgeMachine.finalTapes, + tapes, Function.update_of_ne hc, Function.update_of_ne hl, + Function.update_of_ne hr, Function.update_of_ne ho] + +theorem tapes_frame (work : Fin 10 → K) (countTape : K) (base : K → List Bool) + (data : Data width) (k : K) (hc : k ≠ countTape) + (hl : k ≠ work 1) (hr : k ≠ work 8) (ho : k ≠ work 7) : + tapes work countTape base data k = base k := by + simp only [tapes, Function.update_of_ne hc, Function.update_of_ne hl, + Function.update_of_ne hr, Function.update_of_ne ho] + +variable [Fintype A] [DecidableEq A] + +abbrev StageLabel := SignedDescriptorStageMachine.Label Desc width +abbrev LocalLabel (_ : Fin D) := StageLabel (rows := rows) (repeats := repeats) hq large +abbrev Label (indices : List (Fin D)) := + MachineFiniteSequence.Label (LocalLabel (repeats := repeats) hq large hn hbranch hrows) indices +abbrev State := SignedDescriptorStageMachine.State (rows := rows) (repeats := repeats) hq large A + +abbrev BodyState (U : Type) := + SignedDescriptorStageMachine.State (rows := rows) (repeats := repeats) hq large + (SourceTupleMachine.State width U) + +def localMain (_ : Fin D) : StageLabel (rows := rows) (repeats := repeats) hq large := .load + +def localInstruction (selectSigns : A → SignTuple branch n t) + (source : Fin width → Fin 6 → K) (work : Fin 10 → K) (countTape : K) + (rejected : Option Λ) (i : Fin D) + (labels : StageLabel (rows := rows) (repeats := repeats) hq large → Λ) (exit : Option Λ) : + StageLabel (rows := rows) (repeats := repeats) hq large → + TM2.Stmt (fun _ : K => Bool) Λ (State (rows := rows) (repeats := repeats) (A := A) hq large) := + SignedDescriptorStageMachine.instruction (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows selectSigns i + source work countTape labels exit rejected + +def instruction (selectSigns : A → SignTuple branch n t) + (source : Fin width → Fin 6 → K) (work : Fin 10 → K) (countTape : K) + (indices : List (Fin D)) + (labels : Label (repeats := repeats) hq large hn hbranch hrows indices → Λ) + (exit rejected : Option Λ) : + Label (repeats := repeats) hq large hn hbranch hrows indices → + TM2.Stmt (fun _ : K => Bool) Λ (State (rows := rows) (repeats := repeats) (A := A) hq large) := + MachineFiniteSequence.instruction _ (localMain (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows) + (localInstruction (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows selectSigns source work countTape rejected) + indices labels exit + +def entry (indices : List (Fin D)) + (labels : Label (repeats := repeats) hq large hn hbranch hrows indices → Λ) + (exit : Option Λ) : Option Λ := + MachineFiniteSequence.entry _ (localMain (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows) indices labels exit + +def result (signs : SignTuple branch n t) (ids : Fin width → Nat) + (vars : Fin width → Fin 3 → Nat) : List (Fin D) → Data width → Data width + | [], data => data + | i :: indices, data => result signs ids vars indices + (next hq large (SignedScheduleIndex.atIndex (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows signs i) ids vars data) + +def budget (signs : SignTuple branch n t) (ids : Fin width → Nat) + (vars : Fin width → Fin 3 → Nat) (source : Fin width → Fin 6 → K) + (work : Fin 10 → K) (countTape : K) (base : K → List Bool) : + List (Fin D) → Data width → Nat + | [], _ => 0 + | i :: indices, data => + let descriptor := SignedScheduleIndex.atIndex (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows signs i + CompletedEdgeMachine.budget hq large descriptor source (tapes work countTape base data) + data.leftKeys data.rightKeys ids vars + 3 + + budget signs ids vars source work countTape base indices (next hq large descriptor ids vars data) + +def sequenceInTime (selectSigns : A → SignTuple branch n t) + (ids : Fin width → Nat) (vars : Fin width → Fin 3 → Nat) + (source : Fin width → Fin 6 → K) (sourceDistinct : ∀ i, Function.Injective (source i)) + (work : Fin 10 → K) (workDistinct : Function.Injective work) + (sharedScratch : ∀ i, source i 4 = work 5) (sharedOutput : ∀ i, source i 5 = work 9) + (sourceAvoid : ∀ i field j, KeyMetadataMachine.idTape (source i) field ≠ work j) + (countTape : K) (countAvoid : ∀ j, countTape ≠ work j) + (sourceCount : ∀ i field, KeyMetadataMachine.idTape (source i) field ≠ countTape) + (indices : List (Fin D)) + (labels : Label (repeats := repeats) hq large hn hbranch hrows indices → Λ) + (exit rejected : Option Λ) + (program : Λ → TM2.Stmt (fun _ : K => Bool) Λ (State (rows := rows) (repeats := repeats) (A := A) hq large)) + (atLabels : ∀ l, program (labels l) = + instruction (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows selectSigns source work countTape + indices labels exit rejected l) + (base : K → List Bool) (ambient : A) + (sourceWords : ∀ i field, base (KeyMetadataMachine.idTape (source i) field) = + encodeWord (KeyMetadataMachine.fieldValue (ids i) (vars i) field)) + (empty : ∀ j : Fin 10, j ≠ 1 → j ≠ 7 → j ≠ 8 → base (work j) = []) + (data : Data width) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨entry (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows indices labels exit, + SignedDescriptorStageMachine.clean hq large ambient, tapes work countTape base data⟩ + (some ⟨exit, SignedDescriptorStageMachine.clean hq large ambient, + tapes work countTape base + (result (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows (selectSigns ambient) ids vars indices data)⟩) + (budget (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows (selectSigns ambient) ids vars source work countTape base + indices data) := by + induction indices generalizing data with + | nil => + exact { + steps := 0 + evals_in_steps := rfl + steps_le_m := Nat.le_refl _ + } + | cons i indices ih => + let descriptor := SignedScheduleIndex.atIndex (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows (selectSigns ambient) i + have hd (j k : Fin 10) (hne : j ≠ k) : work j ≠ work k := + fun h => hne (workDistinct h) + have currentSource (position : Fin width) (field : Fin 4) : + tapes work countTape base data (KeyMetadataMachine.idTape (source position) field) = + encodeWord (KeyMetadataMachine.fieldValue (ids position) (vars position) field) := by + rw [tapes_frame work countTape base data _ (sourceCount position field) + (sourceAvoid position field 1) (sourceAvoid position field 8) (sourceAvoid position field 7)] + exact sourceWords position field + have currentEmpty (j : Fin 10) (h1 : j ≠ 1) (h7 : j ≠ 7) (h8 : j ≠ 8) : + tapes work countTape base data (work j) = [] := by + rw [tapes_frame work countTape base data _ (Ne.symm (countAvoid j)) + (hd j 1 h1) (hd j 8 h8) (hd j 7 h7)] + exact empty j h1 h7 h8 + have leftDictionary : tapes work countTape base data (work 1) = + BinaryNameSearch.stream (CanonicalVertexNames.tokens data.leftKeys) := by + simp [tapes, Ne.symm (countAvoid 1), hd 1 8 (by decide), hd 1 7 (by decide)] + have rightDictionary : tapes work countTape base data (work 8) = + BinaryNameSearch.stream (CanonicalVertexNames.tokens data.rightKeys) := by + simp [tapes, Ne.symm (countAvoid 8), hd 8 7 (by decide)] + have first := SignedDescriptorStageMachine.stageInTime (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows selectSigns i + ids vars source sourceDistinct work workDistinct sharedScratch sharedOutput sourceAvoid + countTape (fun l => labels (.inl l)) + (entry (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows indices (fun l => labels (.inr l)) exit) rejected + program (fun l => atLabels (.inl l)) (tapes work countTape base data) ambient + data.leftKeys data.rightKeys currentSource leftDictionary rightDictionary currentEmpty + rw [finalTapes_eq hq large descriptor ids vars work workDistinct countTape countAvoid base data] + at first + have rest := ih (fun l => labels (.inr l)) (fun l => atLabels (.inr l)) + (next hq large descriptor ids vars data) + have joined := StateTransition.EvalsToInTime.trans (TM2.step program) _ _ _ _ _ first rest + refine { steps := joined.steps, evals_in_steps := ?_, steps_le_m := ?_ } + · simpa only [entry, MachineFiniteSequence.entry, localMain, result] + using joined.evals_in_steps + · change joined.steps ≤ + (CompletedEdgeMachine.budget hq large descriptor source (tapes work countTape base data) + data.leftKeys data.rightKeys ids vars + 3) + + budget (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows (selectSigns ambient) + ids vars source work countTape base indices (next hq large descriptor ids vars data) + exact joined.steps_le_m.trans (Nat.le_of_eq (Nat.add_comm _ _)) + +theorem result_count (signs : SignTuple branch n t) (ids : Fin width → Nat) + (vars : Fin width → Fin 3 → Nat) (indices : List (Fin D)) (data : Data width) : + (result (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows signs ids vars indices data).count = + data.count + indices.length := by + induction indices generalizing data with + | nil => simp [result] + | cons i indices ih => + simp only [result, ih, next, List.length_cons] + omega + +theorem result_leftKeys (signs : SignTuple branch n t) (ids : Fin width → Nat) + (vars : Fin width → Fin 3 → Nat) (indices : List (Fin D)) (data : Data width) : + (result (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows signs ids vars indices data).leftKeys = + data.leftKeys ++ indices.map (fun i => CompletedEdgeMachine.key hq large + (SignedScheduleIndex.atIndex (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows signs i) .left ids vars) := by + induction indices generalizing data with + | nil => simp [result] + | cons i indices ih => simp only [result, ih, next, List.map_cons, List.append_assoc, List.cons_append, + List.nil_append] + +theorem result_rightKeys (signs : SignTuple branch n t) (ids : Fin width → Nat) + (vars : Fin width → Fin 3 → Nat) (indices : List (Fin D)) (data : Data width) : + (result (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows signs ids vars indices data).rightKeys = + data.rightKeys ++ indices.map (fun i => CompletedEdgeMachine.key hq large + (SignedScheduleIndex.atIndex (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows signs i) .right ids vars) := by + induction indices generalizing data with + | nil => simp [result] + | cons i indices ih => simp only [result, ih, next, List.map_cons, List.append_assoc, List.cons_append, + List.nil_append] + +def blocks (signs : SignTuple branch n t) (ids : Fin width → Nat) + (vars : Fin width → Fin 3 → Nat) : List (Fin D) → Data width → List (List Bool) + | [], _ => [] + | i :: indices, data => + let descriptor := SignedScheduleIndex.atIndex (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows signs i + CompletedEdgeMachine.edgeBits hq large descriptor data.leftKeys data.rightKeys ids vars :: + blocks signs ids vars indices (next hq large descriptor ids vars data) + +theorem result_output (signs : SignTuple branch n t) (ids : Fin width → Nat) + (vars : Fin width → Fin 3 → Nat) (indices : List (Fin D)) (data : Data width) : + (result (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows signs ids vars indices data).reversedOutput = + ((blocks hq large hn hbranch hrows signs ids vars indices data).flatten).reverse ++ + data.reversedOutput := by + induction indices generalizing data with + | nil => simp [result, blocks] + | cons i indices ih => + simp only [result, ih, blocks, next, List.flatten_cons, List.reverse_append, + List.append_assoc] + +def allStages : List (Fin D) := List.ofFn id + +def tupleResult (formula : UniqueGamesTheorem.Foundations.Target.Formula) + (indices : Fin width → Fin formula.clauses.length) (data : Data width) : Data width := + result (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows (SourceTupleScheduleMachine.sourceSigns formula indices) + (SignedTupleLayout.ids formula indices) (SignedTupleLayout.vars formula indices) + (allStages (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hn hbranch hrows) data + +private theorem bodyBudgetOrder (preparation edges cleanup : Nat) : + 1 + (cleanup + (edges + (preparation + 1))) ≤ + 1 + preparation + edges + cleanup + 1 := by + omega + +section WholeBody + +variable {Extra U : Type} [DecidableEq Extra] [Fintype U] [DecidableEq U] + +local notation "Arena" => Tape width Extra +local notation "Control" => BodyState (rows := rows) (repeats := repeats) hq large U +local notation "WholeLabel" => BodyLabel width D Desc Extra + +def bodyMain : WholeLabel := .start + +def bodySigns (control : SourceTupleMachine.State width U) : SignTuple branch n t := + SourceTupleScheduleMachine.signTuple control.1.1.2 + +omit [Fintype U] [DecidableEq U] in +@[simp] theorem bodySigns_prepared + (formula : UniqueGamesTheorem.Foundations.Target.Formula) + (indices : Fin width → Fin formula.clauses.length) (ambient : U) : + bodySigns (SignedTupleLayout.preparedSource formula indices ambient) = + SourceTupleScheduleMachine.sourceSigns formula indices := rfl + +def bodyExit (exit : Option Λ) : TM2.Stmt (fun _ : Arena => Bool) Λ Control := + match exit with + | none => .halt + | some label => .goto (fun _ => label) + +def cleanupEntry (labels : WholeLabel → Λ) : Option Λ := + SignedTupleCleanupMachine.entry (fun l => labels (.cleanup l)) (some (labels .reset)) + +def edgesEntry (labels : WholeLabel → Λ) : Option Λ := + entry (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows (allStages (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hn hbranch hrows) + (fun l => labels (.edges l)) (cleanupEntry (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows labels) + +def bodyInstruction (labels : WholeLabel → Λ) (exit : Option Λ) : + WholeLabel → TM2.Stmt (fun _ : Arena => Bool) Λ Control + | .start => bodyExit hq large + (SignedTuplePreparationMachine.entry (fun l => labels (.prepare l)) + (edgesEntry (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows labels)) + | .prepare label => SignedTuplePreparationMachine.instruction + (fun l => labels (.prepare l)) (edgesEntry (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows labels) label + | .edges label => instruction (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows bodySigns + SignedTupleLayout.metadata SignedTupleLayout.Tape.edgeWork SignedTupleLayout.Tape.edgeCount (allStages (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hn hbranch hrows) + (fun l => labels (.edges l)) (cleanupEntry (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows labels) none label + | .cleanup label => SignedTupleCleanupMachine.instruction + (fun l => labels (.cleanup l)) (some (labels .reset)) label + | .reset => .load (fun control => SignedTupleLayout.clean control.1.1.1.1.1.1) + (bodyExit hq large exit) + +def nativeProgram : WholeLabel → TM2.Stmt (fun _ : Arena => Bool) WholeLabel Control := + bodyInstruction (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows id none + +theorem tapes_input (formula : UniqueGamesTheorem.Foundations.Target.Formula) + (indices : Fin width → Fin formula.clauses.length) (base : Arena → List Bool) + (input : SignedTupleLayout.Input formula indices base) (data : Data width) : + SignedTupleLayout.Input formula indices (tapes SignedTupleLayout.Tape.edgeWork SignedTupleLayout.Tape.edgeCount base data) := by + refine { + toClear := { + rawDigits := ?_ + rawVariables := ?_ + sourceWork := ?_ + encodedVariables := ?_ + scratch := ?_ + } + table := ?_ + current := ?_ + } + · intro i + simpa [tapes] using input.rawDigits i + · intro i j + simpa [tapes] using input.rawVariables i j + · intro j + simpa [tapes] using input.sourceWork j + · intro i j + simpa [tapes] using input.encodedVariables i j + · simpa [tapes] using input.scratch + · simpa [tapes] using input.table + · intro i + simpa [tapes] using input.current i + +theorem prepared_tapes_commute (formula : UniqueGamesTheorem.Foundations.Target.Formula) + (indices : Fin width → Fin formula.clauses.length) (base : Arena → List Bool) + (data : Data width) : + SignedTupleLayout.preparedTapes formula indices (tapes SignedTupleLayout.Tape.edgeWork SignedTupleLayout.Tape.edgeCount base data) = + tapes SignedTupleLayout.Tape.edgeWork SignedTupleLayout.Tape.edgeCount (SignedTupleLayout.preparedTapes formula indices base) data := by + funext tape + cases tape with + | source source => cases source <;> simp [SignedTupleLayout.preparedTapes, tapes] + | current i => simp [SignedTupleLayout.preparedTapes, tapes] + | remaining i => simp [SignedTupleLayout.preparedTapes, tapes] + | encodedVariable i j => simp [SignedTupleLayout.preparedTapes, tapes] + | adapterScratch => simp [SignedTupleLayout.preparedTapes, tapes] + | edgeWork j => simp [SignedTupleLayout.preparedTapes, tapes, Function.update_apply] + | edgeCount => simp [SignedTupleLayout.preparedTapes, tapes] + | extra value => simp [SignedTupleLayout.preparedTapes, tapes] + +def bodyBudget (formula : UniqueGamesTheorem.Foundations.Target.Formula) + (indices : Fin width → Fin formula.clauses.length) (base : Arena → List Bool) + (data : Data width) : Nat := + 1 + SignedTuplePreparationMachine.budget width (SourceOccurrenceEncoding.bits formula).length + + budget (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows (SourceTupleScheduleMachine.sourceSigns formula indices) + (SignedTupleLayout.ids formula indices) (SignedTupleLayout.vars formula indices) + SignedTupleLayout.metadata SignedTupleLayout.Tape.edgeWork SignedTupleLayout.Tape.edgeCount + (SignedTupleLayout.preparedTapes formula indices base) (allStages (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hn hbranch hrows) data + + 7 * width * ((SourceOccurrenceEncoding.bits formula).length + 2) + 1 + +def bodyInTime (formula : UniqueGamesTheorem.Foundations.Target.Formula) + (indices : Fin width → Fin formula.clauses.length) (base : Arena → List Bool) + (input : SignedTupleLayout.Input formula indices base) (ambient : U) (data : Data width) + (labels : WholeLabel → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : Arena => Bool) Λ Control) + (atLabels : ∀ label, program (labels label) = bodyInstruction (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows labels exit label) + (empty : ∀ j : Fin 10, j ≠ 1 → j ≠ 7 → j ≠ 8 → base (.edgeWork j) = []) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels (bodyMain (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows)), SignedTupleLayout.clean ambient, + tapes SignedTupleLayout.Tape.edgeWork SignedTupleLayout.Tape.edgeCount base data⟩ + (some ⟨exit, SignedTupleLayout.clean ambient, + tapes SignedTupleLayout.Tape.edgeWork SignedTupleLayout.Tape.edgeCount base (tupleResult (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows formula indices data)⟩) + (bodyBudget (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows formula indices base data) := by + let initialTapes := tapes SignedTupleLayout.Tape.edgeWork SignedTupleLayout.Tape.edgeCount base data + let finalData := tupleResult (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows formula indices data + let finalTapes := tapes SignedTupleLayout.Tape.edgeWork SignedTupleLayout.Tape.edgeCount base finalData + let prepared := SignedTupleLayout.preparedTapes formula indices base + let sourceControl := SignedTupleLayout.preparedSource formula indices ambient + have startRun : StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .start), SignedTupleLayout.clean ambient, initialTapes⟩ + (some ⟨SignedTuplePreparationMachine.entry (fun l => labels (.prepare l)) + (edgesEntry (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows labels), + SignedTupleLayout.clean ambient, initialTapes⟩) 1 := by + refine { steps := 1, evals_in_steps := ?_, steps_le_m := Nat.le_refl 1 } + change some (TM2.stepAux (program (labels .start)) (SignedTupleLayout.clean ambient) initialTapes) = _ + rw [atLabels .start] + change some (TM2.stepAux (bodyExit hq large _) (SignedTupleLayout.clean ambient) initialTapes) = _ + cases SignedTuplePreparationMachine.entry (fun l => labels (.prepare l)) + (edgesEntry (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows labels) <;> rfl + have prepareRun := SignedTuplePreparationMachine.prepareInTime formula indices initialTapes + (tapes_input formula indices base input data) ambient + (fun l => labels (.prepare l)) (edgesEntry (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows labels) + program (fun l => atLabels (.prepare l)) + dsimp only [initialTapes] at prepareRun + rw [prepared_tapes_commute] at prepareRun + have sourceAvoid : ∀ (i : Fin width) (field : Fin 4) (j : Fin 10), + KeyMetadataMachine.idTape (SignedTupleLayout.metadata (Extra := Extra) i) field ≠ SignedTupleLayout.Tape.edgeWork j := by + intro i field j + fin_cases field <;> simp [KeyMetadataMachine.idTape, KeyMetadataMachine.idIndex, SignedTupleLayout.metadata] + have sourceCount : ∀ (i : Fin width) (field : Fin 4), + KeyMetadataMachine.idTape (SignedTupleLayout.metadata (Extra := Extra) i) field ≠ SignedTupleLayout.Tape.edgeCount := by + intro i field + fin_cases field <;> simp [KeyMetadataMachine.idTape, KeyMetadataMachine.idIndex, SignedTupleLayout.metadata] + have edgesRun := sequenceInTime (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows bodySigns + (SignedTupleLayout.ids formula indices) (SignedTupleLayout.vars formula indices) + SignedTupleLayout.metadata SignedTupleLayout.metadata_injective + SignedTupleLayout.Tape.edgeWork (by intro i j h; cases h; rfl) (fun _ => rfl) (fun _ => rfl) sourceAvoid + SignedTupleLayout.Tape.edgeCount (by intro j; simp) sourceCount + (allStages (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hn hbranch hrows) (fun l => labels (.edges l)) + (cleanupEntry (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) hq large hn hbranch hrows labels) none program + (fun l => atLabels (.edges l)) prepared sourceControl + (SignedTupleLayout.prepared_metadata formula indices base input) + (by intro j h1 h7 h8; exact empty j h1 h7 h8) data + have signsEq : bodySigns (branch := branch) (n := n) (t := t) sourceControl = + SourceTupleScheduleMachine.sourceSigns (branch := branch) (n := n) (t := t) formula indices := + bodySigns_prepared (branch := branch) (n := n) (t := t) formula indices ambient + have resultEq : + result (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) + hq large hn hbranch hrows (bodySigns sourceControl) + (SignedTupleLayout.ids formula indices) (SignedTupleLayout.vars formula indices) + (allStages (branch := branch) (n := n) (t := t) (q := q) (rows := rows) (repeats := repeats) + hn hbranch hrows) data = finalData := by + rw [signsEq] + rfl + have stateEq : SignedDescriptorStageMachine.clean (branch := branch) (n := n) (t := t) + (q := q) (rows := rows) (repeats := repeats) hq large sourceControl = + SignedTupleLayout.preparedState («Desc» := Desc) formula indices ambient := rfl + rw [stateEq, resultEq] at edgesRun + have cleanupRun := SignedTupleCleanupMachine.cleanupInTime formula indices finalTapes + (tapes_input formula indices base input finalData) ambient + (fun l => labels (.cleanup l)) (some (labels .reset)) program (fun l => atLabels (.cleanup l)) + have cleanupDecider : (fun a b : Extra => Classical.propDecidable (a = b)) = + (inferInstance : DecidableEq Extra) := Subsingleton.elim _ _ + rw [cleanupDecider] at cleanupRun + dsimp only [finalTapes] at cleanupRun + rw [prepared_tapes_commute] at cleanupRun + have resetRun : StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .reset), SignedTupleLayout.preparedState formula indices ambient, finalTapes⟩ + (some ⟨exit, SignedTupleLayout.clean ambient, finalTapes⟩) 1 := by + refine { steps := 1, evals_in_steps := ?_, steps_le_m := Nat.le_refl 1 } + change some (TM2.stepAux (program (labels .reset)) + (SignedTupleLayout.preparedState formula indices ambient) finalTapes) = _ + rw [atLabels .reset] + cases exit <;> rfl + have joined := StateTransition.EvalsToInTime.trans (TM2.step program) _ _ _ _ _ + (StateTransition.EvalsToInTime.trans (TM2.step program) _ _ _ _ _ + (StateTransition.EvalsToInTime.trans (TM2.step program) _ _ _ _ _ + (StateTransition.EvalsToInTime.trans (TM2.step program) _ _ _ _ _ startRun prepareRun) + edgesRun) cleanupRun) resetRun + refine { steps := joined.steps, evals_in_steps := ?_, steps_le_m := ?_ } + · simpa only [bodyMain, tupleResult, finalData, finalTapes, initialTapes, + prepared, sourceControl, bodySigns_prepared] using joined.evals_in_steps + · have bounded := joined.steps_le_m.trans (bodyBudgetOrder _ _ _) + simpa only [bodyBudget, prepared, sourceControl, bodySigns_prepared] using bounded + +end WholeBody + +end +end PerfectCompleteness.SignedTupleBodyMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/SignedTupleCleanupMachineLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/SignedTupleCleanupMachineLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..3dc3f5396fa7499b167334b4cc8725273f62ac07 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/SignedTupleCleanupMachineLemmas.lean @@ -0,0 +1,638 @@ +import Mathlib.Logic.Equiv.Fin.Basic +import OAI.Computability.PerfectCompleteness.Foundations.SignedTupleLayout +import OAI.Computability.PerfectCompleteness.Machines.SourceTupleMachine +import OAI.Computability.PerfectCompleteness.Reduction.CompletionLemmas +import OAI.Computability.PerfectCompleteness.Reduction.SignedCompletionSchedule +import OAI.Computability.UniqueGames.Machines.MachineDrainManyLemmas +import OAI.Computability.UniqueGames.Machines.MachineFiniteTable + +namespace OAI + + +namespace PerfectCompleteness.SignedTupleCleanupMachine + + +open Turing UniqueGamesTheorem.Foundations Complexity Target +open MachineComposition +open scoped Classical + +noncomputable section + +abbrev Tape (width : Nat) (Extra : Type) := SignedTupleLayout.Tape width Extra +abbrev State (width : Nat) (U Desc : Type) := SignedTupleLayout.State width U Desc +abbrev Alphabet {width : Nat} {Extra : Type} (_ : Tape width Extra) := Bool + +variable {width : Nat} {Extra U Desc Λ : Type} + +def localTapes (position : Fin width) : List (Tape width Extra) := + [.source (.digit position), + .source (.variableName position 0), .source (.variableName position 1), + .source (.variableName position 2), + .encodedVariable position 0, .encodedVariable position 1, .encodedVariable position 2] + +def chosen (width : Nat) (Extra : Type) : List (Tape width Extra) := + (List.finRange width).flatMap localTapes + +def selected : Tape width Extra → Bool + | .source (.digit _) => true + | .source (.variableName _ _) => true + | .encodedVariable _ _ => true + | _ => false + +@[simp] theorem chosen_length (width : Nat) (Extra : Type) : + (chosen width Extra).length = 7 * width := by + have lengthFor (positions : List (Fin width)) : + (positions.flatMap (localTapes (Extra := Extra))).length = 7 * positions.length := by + induction positions with + | nil => rfl + | cons position positions ih => + simp only [List.flatMap_cons, List.length_append, localTapes, List.length_cons, + List.length_nil, ih] + omega + simpa only [chosen, List.length_finRange] using lengthFor (List.finRange width) + +@[simp] theorem mem_chosen (tape : Tape width Extra) : + tape ∈ chosen width Extra ↔ selected tape = true := by + cases tape with + | source source => + cases source with + | table => simp [chosen, localTapes, selected] + | digit position => simp [chosen, localTapes, selected] + | work slot => simp [chosen, localTapes, selected] + | variableName position slot => + fin_cases slot <;> simp [chosen, localTapes, selected] + | encodedVariable position slot => + fin_cases slot <;> simp [chosen, localTapes, selected] + | current position => simp [chosen, localTapes, selected] + | remaining position => simp [chosen, localTapes, selected] + | adapterScratch => simp [chosen, localTapes, selected] + | edgeWork slot => simp [chosen, localTapes, selected] + | edgeCount => simp [chosen, localTapes, selected] + | extra value => simp [chosen, localTapes, selected] + +theorem finalTapes_eq (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) (base : Tape width Extra → List Bool) + (clear : SignedTupleLayout.Clear base) : + MachineDrainMany.finalTapes (chosen width Extra) + (SignedTupleLayout.preparedTapes formula indices base) = base := by + funext tape + simp only [MachineDrainMany.finalTapes_apply, mem_chosen] + cases tape with + | source source => + cases source with + | table => simp [selected, SignedTupleLayout.preparedTapes] + | digit position => simp [selected, clear.rawDigits] + | work slot => simp [selected, SignedTupleLayout.preparedTapes] + | variableName position slot => simp [selected, clear.rawVariables] + | encodedVariable position slot => simp [selected, clear.encodedVariables] + | current position => simp [selected, SignedTupleLayout.preparedTapes] + | remaining position => simp [selected, SignedTupleLayout.preparedTapes] + | adapterScratch => simp [selected, SignedTupleLayout.preparedTapes] + | edgeWork slot => simp [selected, SignedTupleLayout.preparedTapes] + | edgeCount => simp [selected, SignedTupleLayout.preparedTapes] + | extra value => simp [selected, SignedTupleLayout.preparedTapes] + +theorem selected_length_le (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) (base : Tape width Extra → List Bool) + (tape : Tape width Extra) (h : selected tape = true) : + (SignedTupleLayout.preparedTapes formula indices base tape).length ≤ + (SourceOccurrenceEncoding.bits formula).length + 1 := by + cases tape with + | source source => + cases source with + | table => simp [selected] at h + | digit position => + have bounded := (indices position).isLt + have tableBound := SourceTupleResetMachine.clause_count_le_table formula + simp only [SignedTupleLayout.preparedTapes, List.length_replicate] + omega + | work slot => simp [selected] at h + | variableName position slot => + have bounded := + (SourceTupleData.selectedClause formula indices position)[slot].variableIndex.isLt + have tableBound := SourceTupleResetMachine.variable_count_le_table formula + simp only [SignedTupleLayout.preparedTapes, List.length_replicate, + SignedTupleLayout.vars] + omega + | encodedVariable position slot => + have bounded := + (SourceTupleData.selectedClause formula indices position)[slot].variableIndex.isLt + have tableBound := SourceTupleResetMachine.variable_count_le_table formula + simp only [SignedTupleLayout.preparedTapes, encodeWord_length, SignedTupleLayout.vars] + omega + | current position => simp [selected] at h + | remaining position => simp [selected] at h + | adapterScratch => simp [selected] at h + | edgeWork slot => simp [selected] at h + | edgeCount => simp [selected] at h + | extra value => simp [selected] at h + +def steps (formula : Formula) (indices : Fin width → Fin formula.clauses.length) + (base : Tape width Extra → List Bool) : Nat := + MachineDrainMany.steps (chosen width Extra) (SignedTupleLayout.preparedTapes formula indices base) + +theorem steps_le (formula : Formula) (indices : Fin width → Fin formula.clauses.length) + (base : Tape width Extra → List Bool) : + steps formula indices base ≤ + 7 * width * ((SourceOccurrenceEncoding.bits formula).length + 2) := by + let tapes := SignedTupleLayout.preparedTapes formula indices base + let bound := (SourceOccurrenceEncoding.bits formula).length + 1 + have sumBound : ∀ keys : List (Tape width Extra), + (∀ tape ∈ keys, (tapes tape).length ≤ bound) → + MachineDrainMany.lengthSum keys tapes ≤ keys.length * bound := by + intro keys + induction keys with + | nil => intro _; simp [MachineDrainMany.lengthSum] + | cons tape keys ih => + intro bounded + have first := bounded tape (by simp) + have rest := ih (fun other member => bounded other (List.mem_cons_of_mem tape member)) + simp only [MachineDrainMany.lengthSum, List.map_cons, List.sum_cons, + List.length_cons, Nat.add_mul, Nat.one_mul] at rest ⊢ + omega + have bounded := sumBound (chosen width Extra) (fun tape member => + selected_length_le formula indices base tape ((mem_chosen tape).mp member)) + have drains := MachineDrainMany.steps_le (chosen width Extra) tapes + rw [chosen_length] at bounded drains + change MachineDrainMany.steps (chosen width Extra) tapes ≤ _ + dsimp only [bound] at bounded + calc + MachineDrainMany.steps (chosen width Extra) tapes ≤ + 7 * width * ((SourceOccurrenceEncoding.bits formula).length + 1) + 7 * width := by omega + _ = 7 * width * ((SourceOccurrenceEncoding.bits formula).length + 2) := by + simp only [Nat.mul_add, Nat.mul_one] + omega + +abbrev Label (width : Nat) (Extra : Type) := MachineDrainMany.Label (chosen width Extra) + +def instruction (labels : Label width Extra → Λ) (exit : Option Λ) : + Label width Extra → TM2.Stmt (Alphabet (width := width) (Extra := Extra)) Λ + (State width U Desc) := + MachineDrainMany.instruction (chosen width Extra) labels exit + +def entry (labels : Label width Extra → Λ) (exit : Option Λ) : Option Λ := + MachineDrainMany.entry (chosen width Extra) labels exit + +theorem cleanupTrace (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) (base : Tape width Extra → List Bool) + (input : SignedTupleLayout.Input formula indices base) (ambient : U) + (labels : Label width Extra → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (width := width) (Extra := Extra)) Λ + (State width U Desc)) + (atLabels : ∀ label, program (labels label) = + instruction (width := width) (Extra := Extra) labels exit label) : + (advance (TM2.step program))^[steps formula indices base] + (some ⟨entry (width := width) (Extra := Extra) labels exit, + SignedTupleLayout.preparedState formula indices ambient, + SignedTupleLayout.preparedTapes formula indices base⟩) = + some ⟨exit, SignedTupleLayout.preparedState formula indices ambient, base⟩ := by + have run := MachineDrainMany.trace (chosen width Extra) labels exit program atLabels + (SignedTupleLayout.preparedTapes formula indices base) + (SignedTupleLayout.preparedState (Desc := Desc) formula indices ambient).1 none + rw [MachineDrainMany.finalRegister_none, finalTapes_eq formula indices base input.toClear] at run + exact run + +def cleanupInTime (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) (base : Tape width Extra → List Bool) + (input : SignedTupleLayout.Input formula indices base) (ambient : U) + (labels : Label width Extra → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (width := width) (Extra := Extra)) Λ + (State width U Desc)) + (atLabels : ∀ label, program (labels label) = + instruction (width := width) (Extra := Extra) labels exit label) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨entry (width := width) (Extra := Extra) labels exit, + SignedTupleLayout.preparedState formula indices ambient, + SignedTupleLayout.preparedTapes formula indices base⟩ + (some ⟨exit, SignedTupleLayout.preparedState formula indices ambient, base⟩) + (7 * width * ((SourceOccurrenceEncoding.bits formula).length + 2)) where + steps := steps formula indices base + evals_in_steps := cleanupTrace formula indices base input ambient labels exit program atLabels + steps_le_m := steps_le formula indices base + +theorem finiteLabels : Finite (Label width Extra) := inferInstance + +end +end PerfectCompleteness.SignedTupleCleanupMachine + + +namespace PerfectCompleteness.SignedTuplePreparationMachine + + +open Turing UniqueGamesTheorem.Foundations Complexity Target +open MachineComposition MachineCloudPadding +open SignedTupleLayout +open scoped Classical + +noncomputable section + +abbrev Tape (width : Nat) (Extra : Type) := SignedTupleLayout.Tape width Extra +abbrev State (width : Nat) (U Desc : Type) := SignedTupleLayout.State width U Desc +abbrev Alphabet {width : Nat} {Extra : Type} (_ : Tape width Extra) := Bool + +variable {width : Nat} {Extra U Desc Λ : Type} + +def variableEquiv (width : Nat) : Fin (width * 3) ≃ Fin width × Fin 3 := finProdFinEquiv.symm + +def digitTape : FixedUnaryRepresentationPlacement.Tape width → Tape width Extra + | .source i => .current i + | .destination i => .source (.digit i) + | .scratch => .adapterScratch + +def digitView : Tape width Extra → Option (FixedUnaryRepresentationPlacement.Tape width) + | .current i => some (.source i) + | .source (.digit i) => some (.destination i) + | .adapterScratch => some .scratch + | _ => none + +theorem digitView_left (k : FixedUnaryRepresentationPlacement.Tape width) : + digitView (digitTape (Extra := Extra) k) = some k := by + cases k <;> rfl + +theorem digitView_right (j : Tape width Extra) (k : FixedUnaryRepresentationPlacement.Tape width) + (h : digitView j = some k) : digitTape k = j := by + cases j with + | source localTape => + cases localTape <;> simp_all [digitView, digitTape] + subst k + rfl + | current i => + simp only [digitView, Option.some.injEq] at h + subst k + rfl + | remaining i => simp_all [digitView] + | encodedVariable i s => simp_all [digitView] + | adapterScratch => + simp only [digitView, Option.some.injEq] at h + subst k + rfl + | edgeWork s => simp_all [digitView] + | edgeCount => simp_all [digitView] + | extra v => simp_all [digitView] + +def variableTape : FixedUnaryRepresentationPlacement.Tape (width * 3) → Tape width Extra + | .source i => .source (.variableName ((variableEquiv width) i).1 ((variableEquiv width) i).2) + | .destination i => .encodedVariable ((variableEquiv width) i).1 ((variableEquiv width) i).2 + | .scratch => .adapterScratch + +def variableView : Tape width Extra → Option (FixedUnaryRepresentationPlacement.Tape (width * 3)) + | .source (.variableName i s) => some (.source ((variableEquiv width).symm (i, s))) + | .encodedVariable i s => some (.destination ((variableEquiv width).symm (i, s))) + | .adapterScratch => some .scratch + | _ => none + +theorem variableView_left (k : FixedUnaryRepresentationPlacement.Tape (width * 3)) : + variableView (variableTape (Extra := Extra) k) = some k := by + cases k <;> simp [variableView, variableTape] + +theorem variableView_right (j : Tape width Extra) + (k : FixedUnaryRepresentationPlacement.Tape (width * 3)) + (h : variableView j = some k) : variableTape k = j := by + cases j with + | source localTape => + cases localTape <;> simp_all [variableView, variableTape] + subst k + simp + | current i => simp_all [variableView] + | remaining i => simp_all [variableView] + | encodedVariable i s => + simp only [variableView, Option.some.injEq] at h + subst k + simp [variableTape] + | adapterScratch => + simp only [variableView, Option.some.injEq] at h + subst k + rfl + | edgeWork s => simp_all [variableView] + | edgeCount => simp_all [variableView] + | extra v => simp_all [variableView] + +def variableValues (formula : Formula) (indices : Fin width → Fin formula.clauses.length) : + Fin (width * 3) → Nat := + fun i => vars formula indices ((variableEquiv width) i).1 ((variableEquiv width) i).2 + +inductive Label (width : Nat) + | digits (label : FixedUnaryRepresentationPlacement.Label .encodedToRaw width) + | extract (label : SourceTupleBodyPlacement.Label width) + | variableCopies (label : FixedUnaryRepresentationPlacement.Label .rawToEncoded (width * 3)) + deriving DecidableEq, Fintype + +def variableEntry (labels : Label width → Λ) (exit : Option Λ) : Option Λ := + FixedUnaryRepresentationPlacement.entry .rawToEncoded (fun l => labels (.variableCopies l)) exit + +def sourceEntry (labels : Label width → Λ) (exit : Option Λ) : Option Λ := + SourceTuplePlacement.entry (fun l => labels (.extract l)) (variableEntry labels exit) + +def entry (labels : Label width → Λ) (exit : Option Λ) : Option Λ := + FixedUnaryRepresentationPlacement.entry .encodedToRaw (fun l => labels (.digits l)) + (sourceEntry labels exit) + +def instruction (labels : Label width → Λ) (exit : Option Λ) : + Label width → TM2.Stmt (Alphabet (width := width) (Extra := Extra)) Λ (State width U Desc) + | .digits label => FixedUnaryRepresentationPlacement.instruction .encodedToRaw digitTape + (fun l => labels (.digits l)) (sourceEntry labels exit) label + | .extract label => SourceTupleBodyPlacement.instruction SignedTupleLayout.Tape.source + (fun l => labels (.extract l)) (variableEntry labels exit) label + | .variableCopies label => FixedUnaryRepresentationPlacement.instruction .rawToEncoded variableTape + (fun l => labels (.variableCopies l)) exit label + +theorem digit_initial_eq (formula : Formula) (indices : Fin width → Fin formula.clauses.length) + (base : Tape width Extra → List Bool) (input : Input formula indices base) : + FixedUnaryRepresentationPlacement.tapes digitView base .encodedToRaw + (ids formula indices) (fun _ => []) = base := by + apply FixedUnaryRepresentationPlacement.tapes_eq_base digitTape digitView digitView_right + intro k + cases k with + | source i => exact input.current i + | destination i => exact input.rawDigits i + | scratch => exact input.scratch + +theorem digit_final_eq (formula : Formula) (indices : Fin width → Fin formula.clauses.length) + (base : Tape width Extra → List Bool) (input : Input formula indices base) : + FixedUnaryRepresentationPlacement.tapes digitView base .encodedToRaw + (ids formula indices) + (fun i => FixedUnaryRepresentationMachine.targetWord .encodedToRaw (ids formula indices i) ++ []) = + digitTapes formula indices base := by + funext k + cases k with + | source localTape => cases localTape <;> simp [FixedUnaryRepresentationPlacement.tapes, + Placement.tapes, digitView, FixedUnaryRepresentationMachine.stacks, + FixedUnaryRepresentationMachine.targetWord, digitTapes, ids] + | current i => simp [FixedUnaryRepresentationPlacement.tapes, Placement.tapes, digitView, + FixedUnaryRepresentationMachine.stacks, FixedUnaryRepresentationMachine.sourceWord, + digitTapes, ids, input.current] + | remaining i => rfl + | encodedVariable i s => rfl + | adapterScratch => simp [FixedUnaryRepresentationPlacement.tapes, Placement.tapes, digitView, + FixedUnaryRepresentationMachine.stacks, digitTapes, input.scratch] + | edgeWork s => rfl + | edgeCount => rfl + | extra v => rfl + +theorem source_initial_eq (formula : Formula) (indices : Fin width → Fin formula.clauses.length) + (base : Tape width Extra → List Bool) (input : Input formula indices base) : + SourceTuplePlacement.tapes sourceView (digitTapes formula indices base) + formula indices (fun _ => false) = digitTapes formula indices base := by + apply SourceTuplePlacement.tapes_eq_base SignedTupleLayout.Tape.source sourceView sourceView_right + intro k + cases k with + | table => exact input.table + | digit i => rfl + | work s => exact input.sourceWork s + | variableName i s => exact input.rawVariables i s + +theorem source_final_eq (formula : Formula) (indices : Fin width → Fin formula.clauses.length) + (base : Tape width Extra → List Bool) (input : Input formula indices base) : + SourceTuplePlacement.tapes sourceView (digitTapes formula indices base) + formula indices (fun _ => true) = rawTapes formula indices base := by + funext k + cases k with + | source localTape => cases localTape <;> simp [SourceTuplePlacement.tapes, Placement.tapes, + sourceView, SourceTupleData.stacks, NormalizationReadMachine.clauseCounters, + rawTapes, vars, input.table, input.sourceWork] + | current i => rfl + | remaining i => rfl + | encodedVariable i s => rfl + | adapterScratch => rfl + | edgeWork s => rfl + | edgeCount => rfl + | extra v => rfl + +theorem variable_initial_eq (formula : Formula) (indices : Fin width → Fin formula.clauses.length) + (base : Tape width Extra → List Bool) (input : Input formula indices base) : + FixedUnaryRepresentationPlacement.tapes variableView (rawTapes formula indices base) .rawToEncoded + (variableValues formula indices) (fun _ => []) = rawTapes formula indices base := by + apply FixedUnaryRepresentationPlacement.tapes_eq_base variableTape variableView variableView_right + intro k + cases k <;> simp [variableTape, FixedUnaryRepresentationMachine.stacks, + FixedUnaryRepresentationMachine.sourceWord, rawTapes, variableValues, + input.encodedVariables, input.scratch] + +theorem variable_final_eq (formula : Formula) (indices : Fin width → Fin formula.clauses.length) + (base : Tape width Extra → List Bool) (input : Input formula indices base) : + FixedUnaryRepresentationPlacement.tapes variableView (rawTapes formula indices base) .rawToEncoded + (variableValues formula indices) + (fun i => FixedUnaryRepresentationMachine.targetWord .rawToEncoded + (variableValues formula indices i) ++ []) = preparedTapes formula indices base := by + funext k + cases k with + | source localTape => cases localTape <;> simp [FixedUnaryRepresentationPlacement.tapes, + Placement.tapes, variableView, FixedUnaryRepresentationMachine.stacks, + FixedUnaryRepresentationMachine.sourceWord, variableValues, rawTapes, preparedTapes] + | current i => rfl + | remaining i => rfl + | encodedVariable i s => simp [FixedUnaryRepresentationPlacement.tapes, Placement.tapes, + variableView, FixedUnaryRepresentationMachine.stacks, FixedUnaryRepresentationMachine.targetWord, + variableValues, preparedTapes] + | adapterScratch => simp [FixedUnaryRepresentationPlacement.tapes, Placement.tapes, + variableView, FixedUnaryRepresentationMachine.stacks, preparedTapes, input.scratch] + | edgeWork s => rfl + | edgeCount => rfl + | extra v => rfl + +def budget (width tableLength : Nat) : Nat := + width * (2 * tableLength + 3) + width * (60 * (tableLength + 1)) + + (width * 3) * (2 * tableLength + 3) + +theorem budget_le (width tableLength : Nat) : + budget width tableLength ≤ 72 * width * (tableLength + 1) := by + unfold budget + nlinarith [Nat.zero_le (width * tableLength)] + +variable [DecidableEq Extra] + +def prepareInTime (formula : Formula) (indices : Fin width → Fin formula.clauses.length) + (base : Tape width Extra → List Bool) (input : Input formula indices base) (ambient : U) + (labels : Label width → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (width := width) (Extra := Extra)) Λ (State width U Desc)) + (atLabels : ∀ l, program (labels l) = instruction labels exit l) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨entry labels exit, clean ambient, base⟩ + (some ⟨exit, preparedState formula indices ambient, preparedTapes formula indices base⟩) + (budget width (SourceOccurrenceEncoding.bits formula).length) := by + have idsBound (i : Fin width) : ids formula indices i ≤ (SourceOccurrenceEncoding.bits formula).length := + Nat.le_trans (Nat.le_of_lt (indices i).isLt) (SourceTupleResetMachine.clause_count_le_table formula) + have varsBound (i : Fin (width * 3)) : + variableValues formula indices i ≤ (SourceOccurrenceEncoding.bits formula).length := by + let position := ((variableEquiv width) i).1 + let slot := ((variableEquiv width) i).2 + have bounded := (SourceTupleData.selectedClause formula indices position)[slot].variableIndex.isLt + exact Nat.le_trans (Nat.le_of_lt bounded) + (SourceTupleResetMachine.variable_count_le_table formula) + have digitsRun := FixedUnaryRepresentationPlacement.familyInTime .encodedToRaw + (digitTape (Extra := Extra)) digitView digitView_left digitView_right + (fun l => labels (.digits l)) (sourceEntry labels exit) program (fun l => atLabels (.digits l)) + base (ids formula indices) (fun _ => []) (clean (Desc := Desc) ambient).1 + (SourceOccurrenceEncoding.bits formula).length idsBound + rw [digit_initial_eq formula indices base input, digit_final_eq formula indices base input] at digitsRun + have sourceRun := SourceTupleBodyPlacement.tupleInTime (SignedTupleLayout.Tape.source (Extra := Extra)) sourceView + sourceView_left sourceView_right (fun l => labels (.extract l)) (variableEntry labels exit) + program (fun l => atLabels (.extract l)) (digitTapes formula indices base) formula indices ambient + (fun _ => CanonicalKeyShape.Shape.bit) (fun _ => false) (frame Desc) + rw [source_initial_eq formula indices base input, source_final_eq formula indices base input] at sourceRun + have variablesRun := FixedUnaryRepresentationPlacement.familyInTime .rawToEncoded + (variableTape (Extra := Extra)) variableView variableView_left variableView_right + (fun l => labels (.variableCopies l)) exit program (fun l => atLabels (.variableCopies l)) + (rawTapes formula indices base) (variableValues formula indices) (fun _ => []) + (preparedState (Desc := Desc) formula indices ambient).1 + (SourceOccurrenceEncoding.bits formula).length varsBound + rw [variable_initial_eq formula indices base input, variable_final_eq formula indices base input] at variablesRun + have joined := StateTransition.EvalsToInTime.trans (TM2.step program) _ _ _ _ _ + (StateTransition.EvalsToInTime.trans (TM2.step program) _ _ _ _ _ digitsRun sourceRun) variablesRun + have cleanEta : ((clean (width := width) (Desc := Desc) ambient).1, (none : Option Bool)) = + clean (width := width) (Desc := Desc) ambient := rfl + have preparedEta : ((preparedState (Desc := Desc) formula indices ambient).1, (none : Option Bool)) = + preparedState (Desc := Desc) formula indices ambient := rfl + simpa only [entry, sourceEntry, variableEntry, cleanEta, preparedEta, + budget, Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using joined + +theorem finiteLabels : Finite (Label width) := inferInstance + +end +end PerfectCompleteness.SignedTuplePreparationMachine + + +namespace PerfectCompleteness.SourceTupleScheduleMachine + + +open Turing UniqueGamesTheorem.Foundations Complexity Target +open MachineComposition MetadataFreeSampler +open scoped Classical + +noncomputable section + +def shapeSigns : CanonicalKeyShape.Shape → SourceClause.Triple + | .clause signs => signs + | .bit => (false, false, false) + +def signTuple {branch : Nat → Nat} {n t : Nat} + (shapes : Fin (TreeCanonical.locationCount branch n t) → CanonicalKeyShape.Shape) : + SignTuple branch n t := + fun leaf slot => shapeSigns (shapes (TreeCanonical.numbering branch n t (leaf, slot))) + +def sourceSigns {branch : Nat → Nat} {n t : Nat} (formula : Formula) + (indices : Fin (TreeCanonical.locationCount branch n t) → Fin formula.clauses.length) : + SignTuple branch n t := + fun leaf slot => + let clause := SourceTupleData.selectedClause formula indices + (TreeCanonical.numbering branch n t (leaf, slot)) + (clause[0].positive, clause[1].positive, clause[2].positive) + +theorem signTuple_source {branch : Nat → Nat} {n t : Nat} (formula : Formula) + (indices : Fin (TreeCanonical.locationCount branch n t) → Fin formula.clauses.length) : + signTuple (fun position => SourceClauseReaderMachine.clauseShape + (SourceTupleData.selectedClause formula indices position)) = sourceSigns formula indices := by + rfl + +variable {branch : Nat → Nat} {n t q : Nat} {rows repeats : Nat → Nat} + (hq : 0 < q) + (large : CanonicalKeyEncoding.partitionWidth (TreeCanonical.locationCount branch n t) ≤ q) + (hn : 0 < n) (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) + +abbrev State (branch : Nat → Nat) (n t : Nat) (A : Type) := + SourceTupleMachine.State (TreeCanonical.locationCount branch n t) A + +def table {A : Type} (control : State branch n t A) : List Bool := + SignedCompletionSchedule.outputBits (repeats := repeats) hq large hn hbranch hrows + (signTuple control.1.1.2) + +def keys {A : Type} [Fintype A] : List (State branch n t A) := Finset.univ.toList + +theorem mem_keys {A : Type} [Fintype A] (control : State branch n t A) : + control ∈ keys (branch := branch) (n := n) (t := t) := by + simp [keys] + +variable {K Λ A : Type} [DecidableEq K] [Fintype A] + +abbrev Alphabet (_ : K) := Bool + +def exitAt (exit : Option Λ) : TM2.Stmt (Alphabet (K := K)) Λ (State branch n t A) := + match exit with + | none => .halt + | some label => .goto (fun _ => label) + +def instruction (destination : K) (exit : Option Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (State branch n t A) := + MachineFiniteTable.emit destination (table (repeats := repeats) hq large hn hbranch hrows) + keys (exitAt exit) + +def pushBound (destination : K) : Nat := + MachineFiniteTable.tableBound (Γ := Alphabet (K := K)) destination + (table (A := A) (repeats := repeats) hq large hn hbranch hrows) keys + +omit [DecidableEq K] in +theorem instruction_pushBound (destination : K) (exit : Option Λ) : + Runtime.statementPushBound (instruction (A := A) (repeats := repeats) hq large hn hbranch hrows destination exit) ≤ + pushBound (A := A) (repeats := repeats) hq large hn hbranch hrows destination := by + have bound := MachineFiniteTable.emit_push_bound destination + (table (A := A) (repeats := repeats) hq large hn hbranch hrows) keys (exitAt exit) + cases exit <;> simpa only [instruction, pushBound, exitAt, + Runtime.statementPushBound, Nat.add_zero] using bound + +theorem scheduleStep (destination : K) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State branch n t A)) (label : Λ) + (atLabel : program label = instruction (repeats := repeats) hq large hn hbranch hrows destination exit) + (control : State branch n t A) (base : K → List Bool) : + TM2.step program ⟨some label, control, base⟩ = + some ⟨exit, control, Function.update base destination + (table (repeats := repeats) hq large hn hbranch hrows control ++ base destination)⟩ := by + change some (TM2.stepAux (program label) control base) = _ + rw [atLabel] + unfold instruction + rw [MachineFiniteTable.stepAux_emit (Γ := fun _ : K => Bool) + (Λ := Λ) (σ := State branch n t A) destination + (table (A := A) (repeats := repeats) hq large hn hbranch hrows) + (keys (branch := branch) (n := n) (t := t) (A := A)) + (mem_keys (branch := branch) (n := n) (t := t) (A := A)) + (exitAt (K := K) (branch := branch) (n := n) (t := t) (A := A) exit) + control base] + cases exit <;> rfl + +theorem sourceTrace (destination : K) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State branch n t A)) (label : Λ) + (atLabel : program label = instruction (repeats := repeats) hq large hn hbranch hrows destination exit) + (formula : Formula) + (indices : Fin (TreeCanonical.locationCount branch n t) → Fin formula.clauses.length) + (ambient : A) (signs : NormalizationReadMachine.Signs) (base : K → List Bool) : + (advance (TM2.step program))^[1] + (some ⟨some label, SourceClauseReaderMachine.clean + (ambient, fun position => SourceClauseReaderMachine.clauseShape + (SourceTupleData.selectedClause formula indices position)) signs, base⟩) = + some ⟨exit, SourceClauseReaderMachine.clean + (ambient, fun position => SourceClauseReaderMachine.clauseShape + (SourceTupleData.selectedClause formula indices position)) signs, + Function.update base destination + (SignedCompletionSchedule.outputBits (repeats := repeats) hq large hn hbranch hrows + (sourceSigns formula indices) ++ base destination)⟩ := by + simpa only [Function.iterate_one, advance_some, table, + SourceClauseReaderMachine.clean, NormalizationReadMachine.clean, signTuple_source] + using scheduleStep (repeats := repeats) hq large hn hbranch hrows destination exit program label atLabel + (SourceClauseReaderMachine.clean + (ambient, fun position => SourceClauseReaderMachine.clauseShape + (SourceTupleData.selectedClause formula indices position)) signs) base + +def sourceInTime (destination : K) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State branch n t A)) (label : Λ) + (atLabel : program label = instruction (repeats := repeats) hq large hn hbranch hrows destination exit) + (formula : Formula) + (indices : Fin (TreeCanonical.locationCount branch n t) → Fin formula.clauses.length) + (ambient : A) (signs : NormalizationReadMachine.Signs) (base : K → List Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some label, SourceClauseReaderMachine.clean + (ambient, fun position => SourceClauseReaderMachine.clauseShape + (SourceTupleData.selectedClause formula indices position)) signs, base⟩ + (some ⟨exit, SourceClauseReaderMachine.clean + (ambient, fun position => SourceClauseReaderMachine.clauseShape + (SourceTupleData.selectedClause formula indices position)) signs, + Function.update base destination + (SignedCompletionSchedule.outputBits (repeats := repeats) hq large hn hbranch hrows + (sourceSigns formula indices) ++ base destination)⟩) 1 where + steps := 1 + evals_in_steps := sourceTrace (repeats := repeats) hq large hn hbranch hrows destination exit program label atLabel + formula indices ambient signs base + steps_le_m := Nat.le_refl _ + +end +end PerfectCompleteness.SourceTupleScheduleMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/SourceClauseCountMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/SourceClauseCountMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..7a3970953385308cbcaef49df5a8e591b75c54b0 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/SourceClauseCountMachine.lean @@ -0,0 +1,202 @@ +import Mathlib.Tactic.DeriveFintype +import OAI.Computability.PerfectCompleteness.Machines.SourceClauseReaderMachineLemmas +import OAI.Computability.PerfectCompleteness.Machines.UnaryBlockSkipMachine +import OAI.Computability.UniqueGames.Machines.MachineCopy +import OAI.Computability.UniqueGames.Machines.MachineDrain +import OAI.Computability.UniqueGames.PCP.SourceMachine + +namespace OAI + + +namespace PerfectCompleteness.SourceClauseCountMachine + + +open Turing UniqueGamesTheorem.Foundations Complexity Target +open MachineComposition UniqueGamesTheorem.Reduction.MachineTransfer + +abbrev Alphabet {K : Type} (_ : K) := Bool +abbrev State (A : Type) := A × Option Bool +def clean {A : Type} (ambient : A) : State A := (ambient, none) + +inductive Label + | tableOut | tableBack + | skip (slot : Fin 1) + | readCount | drain + deriving DecidableEq, Fintype + +def main : Label := .tableOut + +def steps (formula : Formula) : Nat := + 2 * ((SourceOccurrenceEncoding.bits formula).length + 1) + + (formula.variables + 1) + (formula.clauses.length + 1) + + ((SourceOccurrenceEncoding.body 0 formula.clauses).length + 1) + +theorem steps_eq (formula : Formula) : + steps formula = 3 * ((SourceOccurrenceEncoding.bits formula).length + 1) := by + have tableLength : (SourceOccurrenceEncoding.bits formula).length = + formula.variables + formula.clauses.length + 2 + + (SourceOccurrenceEncoding.body 0 formula.clauses).length := by + rw [SourceOccurrenceEncoding.bits_eq] + simp only [List.length_append, encodeWord_length] + omega + unfold steps + omega + +variable {K Λ A : Type} [DecidableEq K] + +def instruction (tape : Fin 4 → K) (labels : Label → Λ) (done rejected : Option Λ) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (State A) + | .tableOut => loopAt (tape 0) (tape 2) id false + (labels .tableOut) (some (labels .tableBack)) + | .tableBack => MachineCopy.forkLoop (tape 2) (tape 0) (tape 1) false + (labels .tableBack) (some (labels (.skip 0))) + | .skip slot => UnaryBlockSkipMachine.instruction (tape 1) (labels (.skip slot)) + (UnaryBlockSkipMachine.nextField (fun slot => labels (.skip slot)) + (some (labels .readCount)) slot) rejected + | .readCount => Hastad.SourceMachine.fieldLoop (tape 1) (tape 3) + (labels .readCount) (some (labels .drain)) + | .drain => MachineDrain.drain (tape 1) (labels .drain) done + +def workTapes (tape : Fin 4 → K) (base : K → List Bool) + (input output : List Bool) : K → List Bool := + Function.update (Function.update base (tape 1) input) (tape 3) output + +theorem workTapes_input (tape : Fin 4 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (input output : List Bool) : + workTapes tape base input output (tape 1) = input := by + have different : tape 1 ≠ tape 3 := fun h => (by decide : (1 : Fin 4) ≠ 3) (distinct h) + simp [workTapes, different] + +@[simp] theorem workTapes_output (tape : Fin 4 → K) (base : K → List Bool) + (input output : List Bool) : workTapes tape base input output (tape 3) = output := by + simp [workTapes] + +private theorem update_input (tape : Fin 4 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (input output replacement : List Bool) : + Function.update (workTapes tape base input output) (tape 1) replacement = + workTapes tape base replacement output := by + have different : tape 1 ≠ tape 3 := fun h => (by decide : (1 : Fin 4) ≠ 3) (distinct h) + funext k + by_cases h : k = tape 1 + · subst k; simp [workTapes, different] + · simp [workTapes, h, Function.update_apply] + +theorem workTapes_empty (tape : Fin 4 → K) (base : K → List Bool) (output : List Bool) + (copyEmpty : base (tape 1) = []) : + workTapes tape base [] output = Function.update base (tape 3) output := by + have copySelf := Function.update_eq_self (tape 1) base + rw [copyEmpty] at copySelf + simp only [workTapes, copySelf] + +private theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +variable (tape : Fin 4 → K) (distinct : Function.Injective tape) +variable (labels : Label → Λ) (done rejected : Option Λ) +variable (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) +variable (atLabels : ∀ l, program (labels l) = instruction tape labels done rejected l) +variable (base : K → List Bool) (ambient : A) + +include distinct atLabels + +theorem copyTrace (table output : List Bool) + (tableWord : base (tape 0) = table) (scratchEmpty : base (tape 2) = []) : + (advance (TM2.step program))^[2 * (table.length + 1)] + (some ⟨some (labels .tableOut), clean ambient, workTapes tape base [] output⟩) = + some ⟨some (labels (.skip 0)), clean ambient, workTapes tape base table output⟩ := by + have hd (i j : Fin 4) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + have source : workTapes tape base [] output (tape 0) = table := by + simp [workTapes, hd, tableWord] + have scratch : workTapes tape base [] output (tape 2) = [] := by + simp [workTapes, hd, scratchEmpty] + have run := MachineCopy.copyTrace (tape 0) (tape 1) (tape 2) + (hd 0 1 (by decide)) (hd 0 2 (by decide)) (hd 1 2 (by decide)) false + (labels .tableOut) (labels .tableBack) (some (labels (.skip 0))) program + (atLabels .tableOut) (atLabels .tableBack) (workTapes tape base [] output) + scratch ambient none + rw [source, workTapes_input tape distinct, List.append_nil, update_input tape distinct] at run + exact run + +theorem skipTrace (formula : Formula) (output : List Bool) : + (advance (TM2.step program))^[formula.variables + 1] + (some ⟨some (labels (.skip 0)), clean ambient, + workTapes tape base (SourceOccurrenceEncoding.bits formula) output⟩) = + some ⟨some (labels .readCount), clean ambient, + workTapes tape base (encodeWord formula.clauses.length ++ + SourceOccurrenceEncoding.body 0 formula.clauses) output⟩ := by + have run := UnaryBlockSkipMachine.listTrace (tape 1) (fun slot => labels (.skip slot)) + (some (labels .readCount)) rejected program (fun slot => atLabels (.skip slot)) + (workTapes tape base [] output) ambient [formula.variables] rfl + (encodeWord formula.clauses.length ++ SourceOccurrenceEncoding.body 0 formula.clauses) none + have headerLength : (encodeWords [formula.variables]).length = formula.variables + 1 := by + simp [encodeWords, encodeWord_length] + have headerInput : encodeWords [formula.variables] ++ + (encodeWord formula.clauses.length ++ SourceOccurrenceEncoding.body 0 formula.clauses) = + SourceOccurrenceEncoding.bits formula := by + rw [SourceOccurrenceEncoding.bits_eq] + simp [encodeWords, List.append_assoc] + rw [headerLength, headerInput, update_input tape distinct, update_input tape distinct] at run + exact run + +theorem readTrace (m : Nat) (body output : List Bool) : + (advance (TM2.step program))^[m + 1] + (some ⟨some (labels .readCount), clean ambient, + workTapes tape base (encodeWord m ++ body) output⟩) = + some ⟨some (labels .drain), clean ambient, + workTapes tape base body (List.replicate m true ++ output)⟩ := by + have different : tape 1 ≠ tape 3 := fun h => (by decide : (1 : Fin 4) ≠ 3) (distinct h) + exact Hastad.SourceMachine.fieldLoopTrace (tape 1) (tape 3) different + (labels .readCount) (some (labels .drain)) program (atLabels .readCount) + base m body output ambient none + +theorem drainTrace (body output : List Bool) : + (advance (TM2.step program))^[body.length + 1] + (some ⟨some (labels .drain), clean ambient, workTapes tape base body output⟩) = + some ⟨done, clean ambient, workTapes tape base [] output⟩ := by + have run := MachineDrain.drainTrace (tape 1) (labels .drain) done program + (atLabels .drain) (workTapes tape base [] output) body ambient none + rw [update_input tape distinct, update_input tape distinct] at run + exact run + +theorem countTrace (formula : Formula) + (tableWord : base (tape 0) = SourceOccurrenceEncoding.bits formula) + (copyEmpty : base (tape 1) = []) (scratchEmpty : base (tape 2) = []) : + (advance (TM2.step program))^[steps formula] + (some ⟨some (labels main), clean ambient, base⟩) = + some ⟨done, clean ambient, Function.update base (tape 3) + (List.replicate formula.clauses.length true ++ base (tape 3))⟩ := by + have first := copyTrace tape distinct labels done rejected program atLabels base ambient + (SourceOccurrenceEncoding.bits formula) (base (tape 3)) tableWord scratchEmpty + have second := skipTrace tape distinct labels done rejected program atLabels base ambient + formula (base (tape 3)) + have third := readTrace tape distinct labels done rejected program atLabels base ambient + formula.clauses.length (SourceOccurrenceEncoding.body 0 formula.clauses) (base (tape 3)) + have fourth := drainTrace tape distinct labels done rejected program atLabels base ambient + (SourceOccurrenceEncoding.body 0 formula.clauses) + (List.replicate formula.clauses.length true ++ base (tape 3)) + have full := joinTrace (joinTrace (joinTrace first second) third) fourth + have empty (output : List Bool) : + workTapes tape base [] output = Function.update base (tape 3) output := + workTapes_empty tape base output copyEmpty + simpa only [steps, main, empty, Function.update_eq_self] using full + +def countInTime (formula : Formula) + (tableWord : base (tape 0) = SourceOccurrenceEncoding.bits formula) + (copyEmpty : base (tape 1) = []) (scratchEmpty : base (tape 2) = []) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels main), clean ambient, base⟩ + (some ⟨done, clean ambient, Function.update base (tape 3) + (List.replicate formula.clauses.length true ++ base (tape 3))⟩) + (3 * ((SourceOccurrenceEncoding.bits formula).length + 1)) where + steps := steps formula + evals_in_steps := countTrace tape distinct labels done rejected program atLabels base ambient + formula tableWord copyEmpty scratchEmpty + steps_le_m := (steps_eq formula).le + +omit [DecidableEq K] distinct atLabels in +theorem label_finite : Finite Label := inferInstance + +end PerfectCompleteness.SourceClauseCountMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/SourceClauseLookupMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/SourceClauseLookupMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..fcf00faed5238bc287f2b500967e0eeb9dbfb183 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/SourceClauseLookupMachine.lean @@ -0,0 +1,300 @@ +import OAI.Computability.PerfectCompleteness.Machines.SourceClauseSelectMachine +import OAI.Computability.PerfectCompleteness.Machines.UnaryBlockSkipMachine +import OAI.Computability.UniqueGames.Machines.MachineCopy +import OAI.Computability.UniqueGames.Machines.MachineDrain + +namespace OAI + + +namespace PerfectCompleteness.SourceClauseLookupMachine + + +open Turing UniqueGamesTheorem.Foundations Complexity Target +open MachineComposition UniqueGamesTheorem.Reduction.MachineTransfer + +abbrev Alphabet {K : Type} (_ : K) := Bool +abbrev State (A : Type) := A × Option Bool +def clean {A : Type} (ambient : A) : State A := (ambient, none) + +inductive Label + | tableOut | tableBack | indexOut | indexBack + | header (slot : Fin 2) + | select (label : SourceClauseSelectMachine.Label) + | drain + deriving DecidableEq, Fintype + +def main : Label := .tableOut + +def selectMap : Fin 3 → Fin 6 + | 0 => 2 + | 1 => 3 + | 2 => 5 + +theorem body_drop_length_le {n : Nat} (clauses : List (Clause n)) (first k : Nat) : + (SourceOccurrenceEncoding.body (first + k) (clauses.drop k)).length ≤ + (SourceOccurrenceEncoding.body first clauses).length := by + induction clauses generalizing first k with + | nil => simp + | cons clause clauses ih => + cases k with + | zero => simp + | succ k => + rw [List.drop_succ_cons, SourceOccurrenceEncoding.body_cons, List.length_append] + have tail := ih (first + 1) k + have indexEq : first + (k + 1) = first + 1 + k := by omega + rw [indexEq] + omega + +def suffix (formula : Formula) (k : Nat) : List Bool := + SourceOccurrenceEncoding.body (k + 1) (formula.clauses.drop (k + 1)) + +def steps (formula : Formula) (k : Nat) : Nat := + 2 * ((SourceOccurrenceEncoding.bits formula).length + 1) + 2 * (k + 1) + + (formula.variables + formula.clauses.length + 2) + + SourceClauseSelectMachine.steps 0 formula.clauses k + (suffix formula k).length + 1 + +theorem steps_le (formula : Formula) (k : Nat) (bound : k < formula.clauses.length) : + steps formula k ≤ 10 * ((SourceOccurrenceEncoding.bits formula).length + k + 1) := by + have tableLength : (SourceOccurrenceEncoding.bits formula).length = + formula.variables + formula.clauses.length + 2 + + (SourceOccurrenceEncoding.body 0 formula.clauses).length := by + rw [SourceOccurrenceEncoding.bits_eq] + simp only [List.length_append, encodeWord_length] + omega + have selectBound := SourceClauseSelectMachine.steps_le formula.clauses 0 k bound + have suffixBound : (suffix formula k).length ≤ + (SourceOccurrenceEncoding.body 0 formula.clauses).length := by + simpa only [suffix, Nat.zero_add] using body_drop_length_le formula.clauses 0 (k + 1) + unfold steps + omega + +variable {K Λ A : Type} [DecidableEq K] + +def selectTapes (tape : Fin 6 → K) : Fin 3 → K := fun i => tape (selectMap i) + +omit [DecidableEq K] in +theorem selectTapes_injective (tape : Fin 6 → K) (distinct : Function.Injective tape) : + Function.Injective (selectTapes tape) := + distinct.comp (by decide : Function.Injective selectMap) + +def instruction (tape : Fin 6 → K) (labels : Label → Λ) (done rejected : Option Λ) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (State A) + | .tableOut => loopAt (tape 0) (tape 4) id false + (labels .tableOut) (some (labels .tableBack)) + | .tableBack => MachineCopy.forkLoop (tape 4) (tape 0) (tape 2) false + (labels .tableBack) (some (labels .indexOut)) + | .indexOut => loopAt (tape 1) (tape 4) id false + (labels .indexOut) (some (labels .indexBack)) + | .indexBack => MachineCopy.forkLoop (tape 4) (tape 1) (tape 3) false + (labels .indexBack) (some (labels (.header 0))) + | .header slot => UnaryBlockSkipMachine.instruction (tape 2) (labels (.header slot)) + (UnaryBlockSkipMachine.nextField (fun slot => labels (.header slot)) + (some (labels (.select .guard))) slot) rejected + | .select label => SourceClauseSelectMachine.instruction (selectTapes tape) + (fun label => labels (.select label)) (some (labels .drain)) rejected label + | .drain => MachineDrain.drain (tape 2) (labels .drain) done + +def workTapes (tape : Fin 6 → K) (base : K → List Bool) + (input counter output : List Bool) : K → List Bool := + Function.update (Function.update (Function.update base (tape 2) input) + (tape 3) counter) (tape 5) output + +@[simp] theorem workTapes_output (tape : Fin 6 → K) (base : K → List Bool) + (input counter output : List Bool) : + workTapes tape base input counter output (tape 5) = output := by + simp [workTapes] + +theorem workTapes_input (tape : Fin 6 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (input counter output : List Bool) : + workTapes tape base input counter output (tape 2) = input := by + have hd (i j : Fin 6) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + simp [workTapes, hd] + +theorem workTapes_counter (tape : Fin 6 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (input counter output : List Bool) : + workTapes tape base input counter output (tape 3) = counter := by + have hd (i j : Fin 6) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + simp [workTapes, hd] + +private theorem update_input (tape : Fin 6 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (input counter output replacement : List Bool) : + Function.update (workTapes tape base input counter output) (tape 2) replacement = + workTapes tape base replacement counter output := by + have hd (i j : Fin 6) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + funext k + by_cases h : k = tape 2 + · subst k; simp [workTapes, hd] + · simp [workTapes, h, Function.update_apply] + +private theorem update_counter (tape : Fin 6 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (input counter output replacement : List Bool) : + Function.update (workTapes tape base input counter output) (tape 3) replacement = + workTapes tape base input replacement output := by + have hd (i j : Fin 6) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + funext k + by_cases h : k = tape 3 + · subst k; simp [workTapes, hd] + · simp [workTapes, h, Function.update_apply] + +theorem workTapes_empty (tape : Fin 6 → K) (base : K → List Bool) (output : List Bool) + (tableCopyEmpty : base (tape 2) = []) (indexCopyEmpty : base (tape 3) = []) : + workTapes tape base [] [] output = Function.update base (tape 5) output := by + have tableSelf := Function.update_eq_self (tape 2) base + have indexSelf := Function.update_eq_self (tape 3) base + rw [tableCopyEmpty] at tableSelf + rw [indexCopyEmpty] at indexSelf + simp only [workTapes, tableSelf, indexSelf] + +private theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +variable (tape : Fin 6 → K) (distinct : Function.Injective tape) +variable (labels : Label → Λ) (done rejected : Option Λ) +variable (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) +variable (atLabels : ∀ l, program (labels l) = instruction tape labels done rejected l) +variable (base : K → List Bool) (ambient : A) + +include distinct atLabels + +theorem copyTableTrace (table output : List Bool) + (tableWord : base (tape 0) = table) (scratchEmpty : base (tape 4) = []) : + (advance (TM2.step program))^[2 * (table.length + 1)] + (some ⟨some (labels .tableOut), clean ambient, workTapes tape base [] [] output⟩) = + some ⟨some (labels .indexOut), clean ambient, workTapes tape base table [] output⟩ := by + have hd (i j : Fin 6) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + have source : workTapes tape base [] [] output (tape 0) = table := by + simp [workTapes, hd, tableWord] + have scratch : workTapes tape base [] [] output (tape 4) = [] := by + simp [workTapes, hd, scratchEmpty] + have run := MachineCopy.copyTrace (tape 0) (tape 2) (tape 4) + (hd 0 2 (by decide)) (hd 0 4 (by decide)) (hd 2 4 (by decide)) false + (labels .tableOut) (labels .tableBack) (some (labels .indexOut)) program + (atLabels .tableOut) (atLabels .tableBack) (workTapes tape base [] [] output) + scratch ambient none + rw [source, workTapes_input tape distinct, List.append_nil, update_input tape distinct] at run + exact run + +theorem copyIndexTrace (table output : List Bool) (k : Nat) + (indexWord : base (tape 1) = List.replicate k true) (scratchEmpty : base (tape 4) = []) : + (advance (TM2.step program))^[2 * (k + 1)] + (some ⟨some (labels .indexOut), clean ambient, workTapes tape base table [] output⟩) = + some ⟨some (labels (.header 0)), clean ambient, + workTapes tape base table (List.replicate k true) output⟩ := by + have hd (i j : Fin 6) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + have source : workTapes tape base table [] output (tape 1) = List.replicate k true := by + simp [workTapes, hd, indexWord] + have scratch : workTapes tape base table [] output (tape 4) = [] := by + simp [workTapes, hd, scratchEmpty] + have run := MachineCopy.copyTrace (tape 1) (tape 3) (tape 4) + (hd 1 3 (by decide)) (hd 1 4 (by decide)) (hd 3 4 (by decide)) false + (labels .indexOut) (labels .indexBack) (some (labels (.header 0))) program + (atLabels .indexOut) (atLabels .indexBack) (workTapes tape base table [] output) + scratch ambient none + rw [source, List.length_replicate, workTapes_counter tape distinct, + List.append_nil, update_counter tape distinct] at run + exact run + +theorem headerTrace (formula : Formula) (k : Nat) (output : List Bool) : + (advance (TM2.step program))^[formula.variables + formula.clauses.length + 2] + (some ⟨some (labels (.header 0)), clean ambient, + workTapes tape base (SourceOccurrenceEncoding.bits formula) (List.replicate k true) output⟩) = + some ⟨some (labels (.select .guard)), clean ambient, + workTapes tape base (SourceOccurrenceEncoding.body 0 formula.clauses) + (List.replicate k true) output⟩ := by + have run := UnaryBlockSkipMachine.listTrace (tape 2) (fun slot => labels (.header slot)) + (some (labels (.select .guard))) rejected program (fun slot => atLabels (.header slot)) + (workTapes tape base [] (List.replicate k true) output) ambient + [formula.variables, formula.clauses.length] rfl + (SourceOccurrenceEncoding.body 0 formula.clauses) none + have headerLength : (encodeWords [formula.variables, formula.clauses.length]).length = + formula.variables + formula.clauses.length + 2 := by + simp [encodeWords_length] + have headerInput : encodeWords [formula.variables, formula.clauses.length] ++ + SourceOccurrenceEncoding.body 0 formula.clauses = SourceOccurrenceEncoding.bits formula := by + rw [SourceOccurrenceEncoding.bits_eq] + simp [encodeWords, List.append_assoc] + rw [headerLength, headerInput, update_input tape distinct, update_input tape distinct] at run + exact run + +theorem drainTrace (input output : List Bool) : + (advance (TM2.step program))^[input.length + 1] + (some ⟨some (labels .drain), clean ambient, workTapes tape base input [] output⟩) = + some ⟨done, clean ambient, workTapes tape base [] [] output⟩ := by + have run := MachineDrain.drainTrace (tape 2) (labels .drain) done program + (atLabels .drain) (workTapes tape base [] [] output) input ambient none + rw [update_input tape distinct, update_input tape distinct] at run + exact run + +theorem selectTrace (formula : Formula) (k : Nat) (bound : k < formula.clauses.length) + (output : List Bool) : + (advance (TM2.step program))^[SourceClauseSelectMachine.steps 0 formula.clauses k] + (some ⟨some (labels (.select .guard)), clean ambient, + workTapes tape base (SourceOccurrenceEncoding.body 0 formula.clauses) + (List.replicate k true) output⟩) = + some ⟨some (labels .drain), clean ambient, + workTapes tape base (suffix formula k) [] + ((encodeWords (clauseWords formula.clauses[k])).reverse ++ output)⟩ := by + have updated (input : List Bool) (index : Nat) (out : List Bool) : + SourceClauseSelectMachine.selectTapes (selectTapes tape) base input index out = + workTapes tape base input (List.replicate index true) out := rfl + have run := SourceClauseSelectMachine.selectTrace (selectTapes tape) + (selectTapes_injective tape distinct) (fun label => labels (.select label)) + (some (labels .drain)) rejected program (fun label => atLabels (.select label)) + base ambient formula.clauses 0 k bound [] output + simp only [updated, List.append_nil, List.replicate_zero, Nat.zero_add] at run + exact run + +theorem lookupTrace (formula : Formula) (k : Nat) (bound : k < formula.clauses.length) + (tableWord : base (tape 0) = SourceOccurrenceEncoding.bits formula) + (indexWord : base (tape 1) = List.replicate k true) + (tableCopyEmpty : base (tape 2) = []) (indexCopyEmpty : base (tape 3) = []) + (scratchEmpty : base (tape 4) = []) : + (advance (TM2.step program))^[steps formula k] + (some ⟨some (labels main), clean ambient, base⟩) = + some ⟨done, clean ambient, Function.update base (tape 5) + ((encodeWords (clauseWords formula.clauses[k])).reverse ++ base (tape 5))⟩ := by + have first := copyTableTrace tape distinct labels done rejected program atLabels base ambient + (SourceOccurrenceEncoding.bits formula) (base (tape 5)) tableWord scratchEmpty + have second := copyIndexTrace tape distinct labels done rejected program atLabels base ambient + (SourceOccurrenceEncoding.bits formula) (base (tape 5)) k indexWord scratchEmpty + have third := headerTrace tape distinct labels done rejected program atLabels base ambient + formula k (base (tape 5)) + have fourth := selectTrace tape distinct labels done rejected program atLabels base ambient + formula k bound (base (tape 5)) + have fifth := drainTrace tape distinct labels done rejected program atLabels base ambient + (suffix formula k) ((encodeWords (clauseWords formula.clauses[k])).reverse ++ base (tape 5)) + have full := joinTrace (joinTrace (joinTrace (joinTrace first second) third) fourth) fifth + have count : + ((2 * ((SourceOccurrenceEncoding.bits formula).length + 1) + 2 * (k + 1) + + (formula.variables + formula.clauses.length + 2)) + + SourceClauseSelectMachine.steps 0 formula.clauses k) + + ((suffix formula k).length + 1) = steps formula k := by + unfold steps + omega + have empty (output : List Bool) : + workTapes tape base [] [] output = Function.update base (tape 5) output := + workTapes_empty tape base output tableCopyEmpty indexCopyEmpty + simpa only [count, main, empty, Function.update_eq_self] using full + +def lookupInTime (formula : Formula) (k : Nat) (bound : k < formula.clauses.length) + (tableWord : base (tape 0) = SourceOccurrenceEncoding.bits formula) + (indexWord : base (tape 1) = List.replicate k true) + (tableCopyEmpty : base (tape 2) = []) (indexCopyEmpty : base (tape 3) = []) + (scratchEmpty : base (tape 4) = []) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels main), clean ambient, base⟩ + (some ⟨done, clean ambient, Function.update base (tape 5) + ((encodeWords (clauseWords formula.clauses[k])).reverse ++ base (tape 5))⟩) + (10 * ((SourceOccurrenceEncoding.bits formula).length + k + 1)) where + steps := steps formula k + evals_in_steps := lookupTrace tape distinct labels done rejected program atLabels base ambient + formula k bound tableWord indexWord tableCopyEmpty indexCopyEmpty scratchEmpty + steps_le_m := steps_le formula k bound + +omit [DecidableEq K] distinct atLabels in +theorem label_finite : Finite Label := inferInstance + +end PerfectCompleteness.SourceClauseLookupMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/SourceClauseReaderMachineLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/SourceClauseReaderMachineLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..89f017d0334c66eb80b67f06a109c690beca5c5c --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/SourceClauseReaderMachineLemmas.lean @@ -0,0 +1,261 @@ +import Mathlib.Data.List.FinRange +import Mathlib.Tactic.Linarith +import OAI.Computability.PerfectCompleteness.Foundations.CanonicalEdgesLemmas +import OAI.Computability.PerfectCompleteness.Machines.NormalizationReadMachine +import OAI.Computability.UniqueGames.Machines.MachineSubroutineLemmas + +namespace OAI + + +namespace PerfectCompleteness.SourceClauseReaderMachine + + +open Turing +open UniqueGamesTheorem.Foundations +open Complexity Complexity.MachineComposition +open UniqueGamesTheorem.Reduction.MachineTransfer + +abbrev Signs := NormalizationReadMachine.Signs +abbrev State (A : Type) := NormalizationReadMachine.State A +abbrev Alphabet {K : Type} (_ : K) := Bool +abbrev clean {A : Type} (ambient : A) (signs : Signs) : State A := + NormalizationReadMachine.clean ambient signs + +def shape (signs : Signs) : CanonicalKeyShape.Shape := + .clause (signs 0, signs 1, signs 2) + +def clauseShape {n : Nat} (clause : Target.Clause n) : CanonicalKeyShape.Shape := + shape (NormalizationReadMachine.clauseSigns clause) + +@[simp] theorem clauseShape_eq {n : Nat} (clause : Target.Clause n) : + clauseShape clause = .clause (clause[0].positive, clause[1].positive, clause[2].positive) := rfl + +def steps {n : Nat} (clause : Target.Clause n) : Nat := + clause[0].variableIndex.val + clause[1].variableIndex.val + clause[2].variableIndex.val + 7 + +inductive Label where + | read (label : NormalizationReadMachine.Label) + | publish + deriving DecidableEq, Fintype + +def main : Label := .read (.field 0) + +section Placement + +variable {K Λ A : Type} [DecidableEq K] + +def instruction (tape : Fin 4 → K) (labels : Label → Λ) (done rejected : Option Λ) + (save : A → CanonicalKeyShape.Shape → A) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (State A) + | .read label => NormalizationReadMachine.instruction tape + (fun label => labels (.read label)) (some (labels .publish)) rejected label + | .publish => + .load (fun state => clean (save state.1.1 (shape state.1.2)) state.1.2) + (exitAt (tape 0) done) + +variable (tape : Fin 4 → K) (distinct : Function.Injective tape) +variable (labels : Label → Λ) (done rejected : Option Λ) +variable (save : A → CanonicalKeyShape.Shape → A) +variable (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) +variable (atLabels : ∀ label, program (labels label) = instruction tape labels done rejected save label) +variable (base : K → List Bool) (ambient : A) + +include atLabels in +theorem publishStep (signs : Signs) (register : Option Bool) (tapeValues : K → List Bool) : + TM2.step program ⟨some (labels .publish), ((ambient, signs), register), tapeValues⟩ = + some ⟨done, clean (save ambient (shape signs)) signs, tapeValues⟩ := by + change some (TM2.stepAux (program (labels .publish)) _ _) = _ + rw [atLabels .publish] + cases done <;> rfl + +include distinct atLabels + +theorem readTrace {n : Nat} (clause : Target.Clause n) (suffix : List Bool) + (signs : Signs) (register : Option Bool) : + (advance (TM2.step program))^[steps clause] + (some ⟨some (labels main), ((ambient, signs), register), + NormalizationReadMachine.tapes tape base + (encodeWords (clauseWords clause) ++ suffix) (fun _ => [])⟩) = + some ⟨done, clean (save ambient (clauseShape clause)) + (NormalizationReadMachine.clauseSigns clause), + NormalizationReadMachine.tapes tape base suffix + (NormalizationReadMachine.clauseCounters clause)⟩ := by + have first := NormalizationReadMachine.clauseTrace tape distinct + (fun label => labels (.read label)) (some (labels .publish)) rejected program + (fun label => atLabels (.read label)) base ambient clause suffix signs register + have second := publishStep tape labels done rejected save program atLabels ambient + (NormalizationReadMachine.clauseSigns clause) none + (NormalizationReadMachine.tapes tape base suffix + (NormalizationReadMachine.clauseCounters clause)) + rw [show steps clause = + (clause[0].variableIndex.val + clause[1].variableIndex.val + clause[2].variableIndex.val + 6) + 1 by + unfold steps + omega, + Function.iterate_succ_apply'] + change advance (TM2.step program) + ((advance (TM2.step program))^[clause[0].variableIndex.val + + clause[1].variableIndex.val + clause[2].variableIndex.val + 6] + (some ⟨some (labels (.read (.field 0))), ((ambient, signs), register), + NormalizationReadMachine.tapes tape base + (encodeWords (clauseWords clause) ++ suffix) (fun _ => [])⟩)) = _ + rw [first, advance_some] + exact second + +def readInTime {n : Nat} (clause : Target.Clause n) (suffix : List Bool) + (signs : Signs) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels main), ((ambient, signs), register), + NormalizationReadMachine.tapes tape base + (encodeWords (clauseWords clause) ++ suffix) (fun _ => [])⟩ + (some ⟨done, clean (save ambient (clauseShape clause)) + (NormalizationReadMachine.clauseSigns clause), + NormalizationReadMachine.tapes tape base suffix + (NormalizationReadMachine.clauseCounters clause)⟩) + (steps clause) where + steps := steps clause + evals_in_steps := readTrace tape distinct labels done rejected save program atLabels + base ambient clause suffix signs register + steps_le_m := Nat.le_refl _ + +end Placement + +theorem steps_le_encoded_length {n : Nat} (clause : Target.Clause n) : + steps clause ≤ (encodeWords (clauseWords clause)).length + 1 := by + have bound := NormalizationReadMachine.steps_le_encoded_length clause + unfold steps + omega + +theorem finiteState {A : Type} [Finite A] : Finite (State A) := inferInstance + +theorem finiteAlphabet {K : Type} (k : K) : Finite (Alphabet k) := by + change Finite Bool + infer_instance + +end PerfectCompleteness.SourceClauseReaderMachine + + +namespace PerfectCompleteness.SourceOccurrenceEncoding + +open UniqueGamesTheorem.Foundations Complexity Target + +def recordWords {n : Nat} (index : Nat) (clause : Clause n) : List Nat := + index :: clauseWords clause + +def records {n : Nat} (first : Nat) : List (Clause n) → List Nat + | [] => [] + | clause :: clauses => recordWords first clause ++ records (first + 1) clauses + +def recordBits {n : Nat} (index : Nat) (clause : Clause n) : List Bool := + encodeWords (recordWords index clause) + +def body {n : Nat} (first : Nat) (clauses : List (Clause n)) : List Bool := + encodeWords (records first clauses) + +def words (formula : Formula) : List Nat := + [formula.variables, formula.clauses.length] ++ records 0 formula.clauses + +def bits (formula : Formula) : List Bool := encodeWords (words formula) + +@[simp] theorem recordWords_length {n : Nat} (index : Nat) (clause : Clause n) : + (recordWords index clause).length = 7 := by simp [recordWords] + +@[simp] theorem records_length {n : Nat} (first : Nat) (clauses : List (Clause n)) : + (records first clauses).length = 7 * clauses.length := by + induction clauses generalizing first with + | nil => rfl + | cons clause clauses ih => simp [records, ih, Nat.mul_add]; omega + +@[simp] theorem words_length (formula : Formula) : + (words formula).length = 2 + 7 * formula.clauses.length := by simp [words]; omega + +theorem records_eq_finRange {n : Nat} (clauses : List (Clause n)) (first : Nat) : + records first clauses = (List.finRange clauses.length).flatMap (fun i => + recordWords (first + i.val) clauses[i.val]) := by + induction clauses generalizing first with + | nil => simp [records] + | cons clause clauses ih => + simp only [records, List.length_cons, List.finRange_succ, List.flatMap_cons, + List.flatMap_map, List.getElem_cons_zero, Fin.val_zero, Nat.add_zero] + apply congrArg (fun rest => recordWords first clause ++ rest) + rw [ih] + apply List.flatMap_congr + intro i _ + simp only [Fin.val_succ, List.getElem_cons_succ] + congr 1 + omega + +@[simp] theorem body_nil {n : Nat} (first : Nat) : body first ([] : List (Clause n)) = [] := rfl + +theorem body_cons {n : Nat} (first : Nat) (clause : Clause n) (clauses : List (Clause n)) : + body first (clause :: clauses) = recordBits first clause ++ body (first + 1) clauses := by + exact encodeWords_append _ _ + +theorem recordBits_eq {n : Nat} (index : Nat) (clause : Clause n) : + recordBits index clause = encodeWord index ++ encodeWords (clauseWords clause) := rfl + +theorem bits_eq (formula : Formula) : + bits formula = encodeWord formula.variables ++ encodeWord formula.clauses.length ++ + body 0 formula.clauses := by + simp only [bits, words, encodeWords_append, encodeWords, List.append_nil, + body, List.append_assoc] + +def parseRecords (variableCount : Nat) : Nat → Nat → List Nat → + Option (List (Clause variableCount) × List Nat) + | _, 0, remaining => some ([], remaining) + | first, count + 1, index :: remaining => do + if index = first then + let (clause, remaining) ← parseClause variableCount remaining + let (clauses, remaining) ← parseRecords variableCount (first + 1) count remaining + return (clause :: clauses, remaining) + else none + | _, _ + 1, [] => none + +@[simp] theorem parseRecords_encoded {n : Nat} (clauses : List (Clause n)) + (first : Nat) (suffix : List Nat) : + parseRecords n first clauses.length (records first clauses ++ suffix) = + some (clauses, suffix) := by + induction clauses generalizing first with + | nil => rfl + | cons clause clauses ih => + simp [records, recordWords, List.append_assoc, parseRecords, parseClause_encoded, ih] + +def decodeWords : List Nat → Option Formula + | variableCount :: count :: remaining => do + let (clauses, remaining) ← parseRecords variableCount 0 count remaining + if remaining = [] then some ⟨variableCount, clauses⟩ else none + | _ => none + +def decode (input : List Bool) : Option Formula := + Complexity.decodeWords input >>= decodeWords + +@[simp] theorem decodeWords_words (formula : Formula) : + decodeWords (words formula) = some formula := by + cases formula with + | mk variableCount clauses => + have parsed := parseRecords_encoded clauses 0 [] + simp only [List.append_nil] at parsed + simp [words, decodeWords, parsed] + +@[simp] theorem decode_bits (formula : Formula) : decode (bits formula) = some formula := by + simp [decode, bits] + +theorem bits_injective : Function.Injective bits := by + intro first second same + have parsed := congrArg decode same + simpa only [decode_bits, Option.some.injEq] using parsed + +theorem body_length_le {n : Nat} (clauses : List (Clause n)) (first maximum : Nat) + (indices : first + clauses.length ≤ maximum) : + (body first clauses).length ≤ clauses.length * (maximum + 1 + 3 * (n + 2)) := by + induction clauses generalizing first with + | nil => simp + | cons clause clauses ih => + have tail := ih (first + 1) (by simp only [List.length_cons] at indices; omega) + have head := clauseBits_length_le clause + rw [body_cons, recordBits_eq] + simp only [List.length_append, encodeWord_length, List.length_cons] + nlinarith + +end PerfectCompleteness.SourceOccurrenceEncoding + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/SourceClauseSelectMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/SourceClauseSelectMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..7804e18e7f4b6cb7b56324ddfff909fbafd1777d --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/SourceClauseSelectMachine.lean @@ -0,0 +1,283 @@ +import Mathlib.Tactic.DeriveFintype +import OAI.Computability.PerfectCompleteness.Machines.SourceClauseReaderMachineLemmas +import OAI.Computability.PerfectCompleteness.Machines.UnaryBlockCopyMachine +import OAI.Computability.PerfectCompleteness.Machines.UnaryBlockSkipMachine + +namespace OAI + + +namespace PerfectCompleteness.SourceClauseSelectMachine + + +open Turing +open UniqueGamesTheorem.Foundations +open Complexity Complexity.MachineComposition +open UniqueGamesTheorem.Reduction.MachineTransfer + +def steps {n : Nat} (first : Nat) : List (Target.Clause n) → Nat → Nat + | [], _ => 0 + | clause :: _, 0 => 1 + (SourceOccurrenceEncoding.recordBits first clause).length + | clause :: clauses, offset + 1 => + 1 + (SourceOccurrenceEncoding.recordBits first clause).length + steps (first + 1) clauses offset + +theorem steps_le {n : Nat} (clauses : List (Target.Clause n)) (first offset : Nat) + (bound : offset < clauses.length) : + steps first clauses offset ≤ (SourceOccurrenceEncoding.body first clauses).length + offset + 1 := by + induction offset generalizing clauses first with + | zero => + cases clauses with + | nil => simp at bound + | cons clause clauses => + simp only [steps, SourceOccurrenceEncoding.body_cons, List.length_append] + omega + | succ offset ih => + cases clauses with + | nil => simp at bound + | cons clause clauses => + have tail := ih clauses (first + 1) (by + simp only [List.length_cons] at bound + omega) + simp only [steps, SourceOccurrenceEncoding.body_cons, List.length_append] + omega + +section Program + +variable {K Λ A : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool +abbrev State (A : Type) := A × Option Bool +def clean (ambient : A) : State A := (ambient, none) + +inductive Label + | guard + | skip (slot : Fin 7) + | index (slot : Fin 1) + | copy (slot : Fin 6) + deriving DecidableEq, Fintype + +def finish (exit : Option Λ) : TM2.Stmt (Alphabet (K := K)) Λ (State A) := + .load (fun state => clean state.1) + (match exit with + | none => .halt + | some label => .goto fun _ => label) + +def instruction (tape : Fin 3 → K) (labels : Label → Λ) (done rejected : Option Λ) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (State A) + | .guard => + .pop (tape 1) (fun state head => (state.1, head)) + (.branch (fun state => state.2.isNone) + (finish (some (labels (.index 0)))) + (.branch (fun state => state.2.getD false) + (finish (some (labels (.skip 0)))) (finish rejected))) + | .skip slot => UnaryBlockSkipMachine.instruction (tape 0) (labels (.skip slot)) + (UnaryBlockSkipMachine.nextField (fun slot => labels (.skip slot)) + (some (labels .guard)) slot) rejected + | .index slot => UnaryBlockSkipMachine.instruction (tape 0) (labels (.index slot)) + (UnaryBlockSkipMachine.nextField (fun slot => labels (.index slot)) + (some (labels (.copy 0))) slot) rejected + | .copy slot => UnaryBlockCopyMachine.instruction (tape 0) (tape 2) (labels (.copy slot)) + (UnaryBlockCopyMachine.nextField (fun slot => labels (.copy slot)) done slot) rejected + +def selectTapes (tape : Fin 3 → K) (base : K → List Bool) (input : List Bool) + (offset : Nat) (output : List Bool) : K → List Bool := + Function.update (Function.update (Function.update base (tape 0) input) + (tape 1) (List.replicate offset true)) (tape 2) output + +theorem selectTapes_input (tape : Fin 3 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (input : List Bool) (offset : Nat) (output : List Bool) : + selectTapes tape base input offset output (tape 0) = input := by + have hd (i j : Fin 3) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + simp [selectTapes, hd] + +theorem selectTapes_offset (tape : Fin 3 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (input : List Bool) (offset : Nat) (output : List Bool) : + selectTapes tape base input offset output (tape 1) = List.replicate offset true := by + have hd (i j : Fin 3) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + simp [selectTapes, hd] + +theorem selectTapes_output (tape : Fin 3 → K) (base : K → List Bool) (input : List Bool) + (offset : Nat) (output : List Bool) : + selectTapes tape base input offset output (tape 2) = output := by + simp [selectTapes] + +private theorem update_input (tape : Fin 3 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (input replacement : List Bool) (offset : Nat) (output : List Bool) : + Function.update (selectTapes tape base input offset output) (tape 0) replacement = + selectTapes tape base replacement offset output := by + have hd (i j : Fin 3) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + funext k + by_cases h : k = tape 0 + · subst k; simp [selectTapes, hd] + · simp [selectTapes, h, Function.update_apply] + +private theorem update_offset (tape : Fin 3 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (input : List Bool) (offset replacement : Nat) (output : List Bool) : + Function.update (selectTapes tape base input offset output) + (tape 1) (List.replicate replacement true) = + selectTapes tape base input replacement output := by + have hd (i j : Fin 3) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + funext k + by_cases h : k = tape 1 + · subst k; simp [selectTapes, hd] + · simp [selectTapes, h, Function.update_apply] + +private theorem update_output (tape : Fin 3 → K) (base : K → List Bool) + (input : List Bool) (offset : Nat) (output replacement : List Bool) : + Function.update (selectTapes tape base input offset output) (tape 2) replacement = + selectTapes tape base input offset replacement := by + simp [selectTapes] + +private theorem tapesAt_select (tape : Fin 3 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (input replacement : List Bool) (offset : Nat) + (output newOutput : List Bool) : + tapesAt (tape 0) (tape 2) (selectTapes tape base input offset output) replacement newOutput = + selectTapes tape base replacement offset newOutput := by + unfold tapesAt + rw [update_input tape distinct, update_output] + +@[simp] theorem stepAux_finish (exit : Option Λ) (state : State A) (base : K → List Bool) : + TM2.stepAux (finish exit) state base = ⟨exit, clean state.1, base⟩ := by + cases exit <;> rfl + +private theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +variable (tape : Fin 3 → K) (distinct : Function.Injective tape) +variable (labels : Label → Λ) (done rejected : Option Λ) +variable (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) +variable (atLabels : ∀ l, program (labels l) = instruction tape labels done rejected l) +variable (base : K → List Bool) (ambient : A) + +include distinct atLabels + +theorem guardStep (input : List Bool) (offset : Nat) (output : List Bool) : + TM2.step program + ⟨some (labels .guard), clean ambient, selectTapes tape base input (offset + 1) output⟩ = + some ⟨some (labels (.skip 0)), clean ambient, selectTapes tape base input offset output⟩ := by + change some (TM2.stepAux (program (labels .guard)) _ _) = _ + rw [atLabels .guard] + simp [instruction, TM2.stepAux, clean, selectTapes_offset tape distinct, + List.replicate_succ, update_offset tape distinct] + +theorem zeroStep (input output : List Bool) : + TM2.step program + ⟨some (labels .guard), clean ambient, selectTapes tape base input 0 output⟩ = + some ⟨some (labels (.index 0)), clean ambient, selectTapes tape base input 0 output⟩ := by + have unchanged : Function.update (selectTapes tape base input 0 output) (tape 1) [] = + selectTapes tape base input 0 output := by + simpa only [List.replicate_zero] using update_offset tape distinct base input 0 0 output + change some (TM2.stepAux (program (labels .guard)) _ _) = _ + rw [atLabels .guard] + simp [instruction, TM2.stepAux, clean, selectTapes_offset tape distinct, unchanged] + +theorem skipTrace {n : Nat} (first : Nat) (clause : Target.Clause n) + (suffix : List Bool) (offset : Nat) (output : List Bool) : + (advance (TM2.step program))^[1 + (SourceOccurrenceEncoding.recordBits first clause).length] + (some ⟨some (labels .guard), clean ambient, + selectTapes tape base (SourceOccurrenceEncoding.recordBits first clause ++ suffix) + (offset + 1) output⟩) = + some ⟨some (labels .guard), clean ambient, selectTapes tape base suffix offset output⟩ := by + let input := SourceOccurrenceEncoding.recordBits first clause ++ suffix + have guard : (advance (TM2.step program))^[1] + (some ⟨some (labels .guard), clean ambient, selectTapes tape base input (offset + 1) output⟩) = + some ⟨some (labels (.skip 0)), clean ambient, selectTapes tape base input offset output⟩ := by + simpa only [Function.iterate_one, advance_some] using + guardStep tape distinct labels done rejected program atLabels base ambient input offset output + have skip := UnaryBlockSkipMachine.listTrace (count := 6) (tape 0) + (fun slot => labels (.skip slot)) (some (labels .guard)) rejected program + (fun slot => atLabels (.skip slot)) (selectTapes tape base input offset output) ambient + (SourceOccurrenceEncoding.recordWords first clause) (by simp) suffix none + simp only [update_input tape distinct] at skip + exact joinTrace guard skip + +theorem zeroTrace {n : Nat} (first : Nat) (clause : Target.Clause n) + (suffix output : List Bool) : + (advance (TM2.step program))^[1 + (SourceOccurrenceEncoding.recordBits first clause).length] + (some ⟨some (labels .guard), clean ambient, + selectTapes tape base (SourceOccurrenceEncoding.recordBits first clause ++ suffix) 0 output⟩) = + some ⟨done, clean ambient, selectTapes tape base suffix 0 + ((encodeWords (clauseWords clause)).reverse ++ output)⟩ := by + have hd : tape 0 ≠ tape 2 := fun h => (by decide : (0 : Fin 3) ≠ 2) (distinct h) + let input := SourceOccurrenceEncoding.recordBits first clause ++ suffix + let clauseInput := encodeWords (clauseWords clause) ++ suffix + have guard : (advance (TM2.step program))^[1] + (some ⟨some (labels .guard), clean ambient, selectTapes tape base input 0 output⟩) = + some ⟨some (labels (.index 0)), clean ambient, selectTapes tape base input 0 output⟩ := by + simpa only [Function.iterate_one, advance_some] using + zeroStep tape distinct labels done rejected program atLabels base ambient input output + have index : (advance (TM2.step program))^[(encodeWord first).length] + (some ⟨some (labels (.index 0)), clean ambient, selectTapes tape base input 0 output⟩) = + some ⟨some (labels (.copy 0)), clean ambient, selectTapes tape base clauseInput 0 output⟩ := by + have h := UnaryBlockSkipMachine.listTrace (count := 0) (tape 0) + (fun slot => labels (.index slot)) (some (labels (.copy 0))) rejected program + (fun slot => atLabels (.index slot)) (selectTapes tape base input 0 output) ambient + [first] (by simp) clauseInput none + simpa only [encodeWords, List.append_nil, update_input tape distinct, input, clauseInput, + SourceOccurrenceEncoding.recordBits_eq, List.append_assoc, clean] using h + have copy : (advance (TM2.step program))^[(encodeWords (clauseWords clause)).length] + (some ⟨some (labels (.copy 0)), clean ambient, selectTapes tape base clauseInput 0 output⟩) = + some ⟨done, clean ambient, selectTapes tape base suffix 0 + ((encodeWords (clauseWords clause)).reverse ++ output)⟩ := by + have h := UnaryBlockCopyMachine.listTrace (tape 0) (tape 2) hd + (fun slot => labels (.copy slot)) done rejected program + (fun slot => atLabels (.copy slot)) (selectTapes tape base clauseInput 0 output) ambient + (clauseWords clause) (by simp) suffix output none + simpa only [tapesAt_select tape distinct, clauseInput, clean] using h + have full := joinTrace (joinTrace guard index) copy + simpa only [input, SourceOccurrenceEncoding.recordBits_eq, List.length_append, + List.append_assoc, Nat.add_assoc] using full + +theorem selectTrace {n : Nat} (clauses : List (Target.Clause n)) (first offset : Nat) + (bound : offset < clauses.length) (suffix output : List Bool) : + (advance (TM2.step program))^[steps first clauses offset] + (some ⟨some (labels .guard), clean ambient, + selectTapes tape base (SourceOccurrenceEncoding.body first clauses ++ suffix) offset output⟩) = + some ⟨done, clean ambient, + selectTapes tape base + (SourceOccurrenceEncoding.body (first + offset + 1) (clauses.drop (offset + 1)) ++ suffix) 0 + ((encodeWords (clauseWords clauses[offset])).reverse ++ output)⟩ := by + induction offset generalizing clauses first with + | zero => + cases clauses with + | nil => simp at bound + | cons clause clauses => + have h := zeroTrace tape distinct labels done rejected program atLabels base ambient + first clause (SourceOccurrenceEncoding.body (first + 1) clauses ++ suffix) output + simpa only [steps, SourceOccurrenceEncoding.body_cons, List.append_assoc, + Nat.add_zero, List.drop_succ_cons, List.drop_zero, List.getElem_cons_zero] using h + | succ offset ih => + cases clauses with + | nil => simp at bound + | cons clause clauses => + have tailBound : offset < clauses.length := by + simp only [List.length_cons] at bound + omega + have skip := skipTrace tape distinct labels done rejected program atLabels base ambient + first clause (SourceOccurrenceEncoding.body (first + 1) clauses ++ suffix) offset output + have tail := ih clauses (first + 1) tailBound + have full := joinTrace skip tail + have address : first + 1 + offset + 1 = first + (offset + 1) + 1 := by omega + simpa only [steps, SourceOccurrenceEncoding.body_cons, List.append_assoc, + List.drop_succ_cons, List.getElem_cons_succ, address] using full + +def selectInTime {n : Nat} (clauses : List (Target.Clause n)) (first offset : Nat) + (bound : offset < clauses.length) (suffix output : List Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .guard), clean ambient, + selectTapes tape base (SourceOccurrenceEncoding.body first clauses ++ suffix) offset output⟩ + (some ⟨done, clean ambient, + selectTapes tape base + (SourceOccurrenceEncoding.body (first + offset + 1) (clauses.drop (offset + 1)) ++ suffix) 0 + ((encodeWords (clauseWords clauses[offset])).reverse ++ output)⟩) + ((SourceOccurrenceEncoding.body first clauses).length + offset + 1) where + steps := steps first clauses offset + evals_in_steps := selectTrace tape distinct labels done rejected program atLabels base ambient + clauses first offset bound suffix output + steps_le_m := steps_le clauses first offset bound + +end Program + +end PerfectCompleteness.SourceClauseSelectMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/SourceCoordinateMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/SourceCoordinateMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..9661243a52f4523e3c3503a0a5ec6a8906d4fff7 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/SourceCoordinateMachine.lean @@ -0,0 +1,212 @@ +import OAI.Computability.PerfectCompleteness.Machines.SourceClauseLookupMachine +import OAI.Computability.PerfectCompleteness.Machines.SourceClauseReaderMachineLemmas + +namespace OAI + + +namespace PerfectCompleteness.SourceCoordinateMachine + + +open Turing UniqueGamesTheorem.Foundations Complexity Target +open MachineComposition UniqueGamesTheorem.Reduction.MachineTransfer + +variable {K Λ A : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool +abbrev State (A : Type) := SourceClauseReaderMachine.State A +abbrev Signs := NormalizationReadMachine.Signs + +def lookupMap (i : Fin 6) : Fin 10 := ⟨i.val, lt_trans i.isLt (by decide)⟩ +def readerMap (i : Fin 4) : Fin 10 := ⟨i.val + 6, by have := i.isLt; omega⟩ + +def lookupTapes (tape : Fin 10 → K) : Fin 6 → K := fun i => tape (lookupMap i) +def readerTapes (tape : Fin 10 → K) : Fin 4 → K := fun i => tape (readerMap i) + +omit [DecidableEq K] in +theorem lookupTapes_injective (tape : Fin 10 → K) (distinct : Function.Injective tape) : + Function.Injective (lookupTapes tape) := by + intro i j h + have hv := congrArg (fun x : Fin 10 => x.val) (distinct h) + exact Fin.ext hv + +omit [DecidableEq K] in +theorem readerTapes_injective (tape : Fin 10 → K) (distinct : Function.Injective tape) : + Function.Injective (readerTapes tape) := by + intro i j h + have hv := congrArg (fun x : Fin 10 => x.val) (distinct h) + apply Fin.ext + dsimp [readerMap] at hv + omega + +inductive Label + | lookup (label : SourceClauseLookupMachine.Label) + | restore + | read (label : SourceClauseReaderMachine.Label) + deriving DecidableEq, Fintype + +def main : Label := .lookup SourceClauseLookupMachine.main + +def instruction (tape : Fin 10 → K) (labels : Label → Λ) (done rejected : Option Λ) + (save : A → CanonicalKeyShape.Shape → A) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (State A) + | .lookup l => SourceClauseLookupMachine.instruction (lookupTapes tape) + (fun l => labels (.lookup l)) (some (labels .restore)) rejected l + | .restore => loopAt (tape 5) (tape 6) id false (labels .restore) + (some (labels (.read SourceClauseReaderMachine.main))) + | .read l => SourceClauseReaderMachine.instruction (readerTapes tape) + (fun l => labels (.read l)) done rejected save l + +def resultTapes {n : Nat} (tape : Fin 10 → K) (base : K → List Bool) + (clause : Clause n) : K → List Bool := + NormalizationReadMachine.tapes (readerTapes tape) base [] + (NormalizationReadMachine.clauseCounters clause) + +theorem result_variable {n : Nat} (tape : Fin 10 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (clause : Clause n) (slot : Fin 3) : + resultTapes tape base clause (readerTapes tape slot.succ) = + List.replicate clause[slot].variableIndex.val true := + NormalizationReadMachine.tapes_counter (readerTapes tape) + (readerTapes_injective tape distinct) base [] _ slot + +theorem result_original {n : Nat} (tape : Fin 10 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (clause : Clause n) (i : Fin 10) (original : i.val < 6) : + resultTapes tape base clause (tape i) = base (tape i) := by + apply NormalizationReadMachine.tapes_other + intro j same + have hv := congrArg (fun x : Fin 10 => x.val) (distinct same) + dsimp [readerTapes, readerMap] at hv + omega + +def steps (formula : Formula) (index : Fin formula.clauses.length) : Nat := + SourceClauseLookupMachine.steps formula index.val + + ((encodeWords (clauseWords formula.clauses[index.val])).length + 1) + + SourceClauseReaderMachine.steps formula.clauses[index.val] + +theorem steps_le (formula : Formula) (index : Fin formula.clauses.length) : + steps formula index ≤ + 30 * ((SourceOccurrenceEncoding.bits formula).length + index.val + 1) := by + have lookupBound := SourceClauseLookupMachine.steps_le formula index.val index.isLt + have readerBound := SourceClauseReaderMachine.steps_le_encoded_length formula.clauses[index.val] + have clauseBound := clauseBits_length_le formula.clauses[index.val] + have variableBound : formula.variables ≤ (SourceOccurrenceEncoding.bits formula).length := by + rw [SourceOccurrenceEncoding.bits_eq] + simp only [List.length_append, encodeWord_length] + omega + unfold steps + omega + +private theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +variable (tape : Fin 10 → K) (distinct : Function.Injective tape) +variable (labels : Label → Λ) (done rejected : Option Λ) +variable (save : A → CanonicalKeyShape.Shape → A) +variable (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) +variable (atLabels : ∀ l, program (labels l) = instruction tape labels done rejected save l) +variable (base : K → List Bool) (ambient : A) + +include distinct atLabels + +theorem coordinateTrace (formula : Formula) (index : Fin formula.clauses.length) + (signs : Signs) + (tableWord : base (tape 0) = SourceOccurrenceEncoding.bits formula) + (indexWord : base (tape 1) = List.replicate index.val true) + (empty : ∀ i : Fin 10, 2 ≤ i.val → base (tape i) = []) : + (advance (TM2.step program))^[steps formula index] + (some ⟨some (labels main), SourceClauseReaderMachine.clean ambient signs, base⟩) = + some ⟨done, + SourceClauseReaderMachine.clean + (save ambient (SourceClauseReaderMachine.clauseShape formula.clauses[index.val])) + (NormalizationReadMachine.clauseSigns formula.clauses[index.val]), + resultTapes tape base formula.clauses[index.val]⟩ := by + have hd (i j : Fin 10) (different : i ≠ j) : tape i ≠ tape j := + fun same => different (distinct same) + let clause := formula.clauses[index.val] + let word := encodeWords (clauseWords clause) + let reversed := Function.update base (tape 5) word.reverse + let forward := Function.update base (tape 6) word + have looked := SourceClauseLookupMachine.lookupTrace (lookupTapes tape) + (lookupTapes_injective tape distinct) (fun l => labels (.lookup l)) + (some (labels .restore)) rejected program (fun l => atLabels (.lookup l)) + base (ambient, signs) formula index.val index.isLt tableWord indexWord + (empty 2 (by decide)) (empty 3 (by decide)) (empty 4 (by decide)) + change (advance (TM2.step program))^[SourceClauseLookupMachine.steps formula index.val] + (some ⟨some (labels main), SourceClauseReaderMachine.clean ambient signs, base⟩) = + some ⟨some (labels .restore), SourceClauseReaderMachine.clean ambient signs, + Function.update base (tape 5) (word.reverse ++ base (tape 5))⟩ at looked + rw [empty 5 (by decide), List.append_nil] at looked + have restored : (advance (TM2.step program))^[word.length + 1] + (some ⟨some (labels .restore), SourceClauseReaderMachine.clean ambient signs, reversed⟩) = + some ⟨some (labels (.read SourceClauseReaderMachine.main)), + SourceClauseReaderMachine.clean ambient signs, forward⟩ := by + change (nextAt (tape 6) program)^[word.length + 1] + (some ⟨some (labels .restore), ((ambient, signs), none), reversed⟩) = + some ⟨some (labels (.read SourceClauseReaderMachine.main)), + ((ambient, signs), none), forward⟩ + have source : reversed (tape 5) = word.reverse := by simp [reversed] + have dest : reversed (tape 6) = [] := by simp [reversed, hd, empty 6 (by decide)] + have updated : tapesAt (tape 5) (tape 6) reversed [] word = forward := by + funext k + by_cases h5 : k = tape 5 + · subst k; simp [tapesAt, reversed, forward, hd, empty 5 (by decide)] + · by_cases h6 : k = tape 6 + · subst k; simp [tapesAt, reversed, forward] + · simp [tapesAt, reversed, forward, h5, h6] + have native := transferAt_fromTapes (Γ := Alphabet (K := K)) (tape 5) (tape 6) + (hd 5 6 (by decide)) id false (labels .restore) + (some (labels (.read SourceClauseReaderMachine.main))) program (atLabels .restore) + reversed (ambient, signs) none + rw [source, dest, List.length_reverse, List.reverse_reverse, List.map_id_fun, + List.append_nil, id_eq, updated] at native + exact native + have initialReader : NormalizationReadMachine.tapes (readerTapes tape) base word + (fun _ => []) = forward := by + funext k + by_cases h7 : k = tape 7 + · subst k; simp [NormalizationReadMachine.tapes, readerTapes, readerMap, forward, hd, + empty 7 (by decide)] + · by_cases h8 : k = tape 8 + · subst k; simp [NormalizationReadMachine.tapes, readerTapes, readerMap, forward, hd, + empty 8 (by decide)] + · by_cases h9 : k = tape 9 + · subst k; simp [NormalizationReadMachine.tapes, readerTapes, readerMap, forward, hd, + empty 9 (by decide)] + · simp [NormalizationReadMachine.tapes, readerTapes, readerMap, forward, + Function.update_apply, h7, h8, h9] + have read := SourceClauseReaderMachine.readTrace (readerTapes tape) + (readerTapes_injective tape distinct) (fun l => labels (.read l)) done rejected save + program (fun l => atLabels (.read l)) base ambient clause [] signs none + simp only [List.append_nil] at read + change (advance (TM2.step program))^[SourceClauseReaderMachine.steps clause] + (some ⟨some (labels (.read SourceClauseReaderMachine.main)), + SourceClauseReaderMachine.clean ambient signs, + NormalizationReadMachine.tapes (readerTapes tape) base word (fun _ => [])⟩) = + some ⟨done, + SourceClauseReaderMachine.clean (save ambient (SourceClauseReaderMachine.clauseShape clause)) + (NormalizationReadMachine.clauseSigns clause), + resultTapes tape base clause⟩ at read + rw [initialReader] at read + exact joinTrace (joinTrace looked restored) read + +def coordinateInTime (formula : Formula) (index : Fin formula.clauses.length) + (signs : Signs) + (tableWord : base (tape 0) = SourceOccurrenceEncoding.bits formula) + (indexWord : base (tape 1) = List.replicate index.val true) + (empty : ∀ i : Fin 10, 2 ≤ i.val → base (tape i) = []) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels main), SourceClauseReaderMachine.clean ambient signs, base⟩ + (some ⟨done, + SourceClauseReaderMachine.clean + (save ambient (SourceClauseReaderMachine.clauseShape formula.clauses[index.val])) + (NormalizationReadMachine.clauseSigns formula.clauses[index.val]), + resultTapes tape base formula.clauses[index.val]⟩) + (30 * ((SourceOccurrenceEncoding.bits formula).length + index.val + 1)) where + steps := steps formula index + evals_in_steps := coordinateTrace tape distinct labels done rejected save program atLabels + base ambient formula index signs tableWord indexWord empty + steps_le_m := steps_le formula index + +end PerfectCompleteness.SourceCoordinateMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/SourceOccurrenceIndexMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/SourceOccurrenceIndexMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..f76e9fb0a349e956ca6ea32853cac965bbf6c389 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/SourceOccurrenceIndexMachine.lean @@ -0,0 +1,110 @@ +import Mathlib.Tactic.DeriveFintype +import OAI.Computability.UniqueGames.Machines.MachineCopy +import OAI.Computability.UniqueGames.Machines.MachineSubroutineLemmas + +namespace OAI + + +namespace PerfectCompleteness.SourceOccurrenceIndexMachine + + +open Turing +open UniqueGamesTheorem.Foundations.Complexity +open MachineComposition +open UniqueGamesTheorem.Reduction.MachineTransfer + +variable {K Λ A : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool +abbrev State (A : Type) := A × Option Bool + +def clean (ambient : A) : State A := (ambient, none) + +inductive Label + | copyOut + | copyBack + | delimiter + deriving DecidableEq + +/-- A list enumerating every element of the type, which are all zero-argument constructors. (Generated by the `Fintype` deriving handler.)-/ +protected abbrev Label.enumList : List Label := [.copyOut, .copyBack, .delimiter] + +protected theorem Label.enumList_getElem?_ctorIdx_eq (x : Label) : + Label.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem Label.enumList_nodup : Label.enumList.Nodup := by decide + +instance : Fintype Label where + elems := ⟨Label.enumList, Label.enumList_nodup⟩ + complete x := by cases x <;> decide + +def main : Label := .copyOut + +def instruction (tape : Fin 3 → K) (labels : Label → Λ) (exit : Option Λ) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (State A) + | .copyOut => loopAt (tape 0) (tape 1) id false + (labels .copyOut) (some (labels .copyBack)) + | .copyBack => MachineCopy.forkLoop (tape 1) (tape 0) (tape 2) false + (labels .copyBack) (some (labels .delimiter)) + | .delimiter => .push (tape 2) (fun _ => false) (exitAt (tape 2) exit) + +def steps (index : Nat) : Nat := 2 * (index + 1) + 1 + +private theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +theorem indexTrace (tape : Fin 3 → K) (distinct : Function.Injective tape) + (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ l, program (labels l) = instruction tape labels exit l) + (base : K → List Bool) (ambient : A) (index : Nat) + (counterWord : base (tape 0) = List.replicate index true) + (scratchEmpty : base (tape 1) = []) : + (advance (TM2.step program))^[steps index] + (some ⟨some (labels main), clean ambient, base⟩) = + some ⟨exit, clean ambient, Function.update base (tape 2) + ((encodeWord index).reverse ++ base (tape 2))⟩ := by + have hd (i j : Fin 3) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + have copied := MachineCopy.copyTrace (tape 0) (tape 2) (tape 1) + (hd 0 2 (by decide)) (hd 0 1 (by decide)) (hd 2 1 (by decide)) false + (labels .copyOut) (labels .copyBack) (some (labels .delimiter)) program + (atLabels .copyOut) (atLabels .copyBack) base scratchEmpty ambient none + rw [counterWord, List.length_replicate] at copied + have emitted : (advance (TM2.step program))^[1] + (some ⟨some (labels .delimiter), clean ambient, + Function.update base (tape 2) (List.replicate index true ++ base (tape 2))⟩) = + some ⟨exit, clean ambient, Function.update base (tape 2) + ((encodeWord index).reverse ++ base (tape 2))⟩ := by + change some (TM2.stepAux (program (labels .delimiter)) _ _) = _ + rw [atLabels .delimiter] + cases exit <;> + simp [instruction, TM2.stepAux, exitAt, encodeWord, List.reverse_append, + List.reverse_replicate] + exact joinTrace copied emitted + +def indexInTime (tape : Fin 3 → K) (distinct : Function.Injective tape) + (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ l, program (labels l) = instruction tape labels exit l) + (base : K → List Bool) (ambient : A) (index : Nat) + (counterWord : base (tape 0) = List.replicate index true) + (scratchEmpty : base (tape 1) = []) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels main), clean ambient, base⟩ + (some ⟨exit, clean ambient, Function.update base (tape 2) + ((encodeWord index).reverse ++ base (tape 2))⟩) + (2 * (index + 1) + 1) where + steps := steps index + evals_in_steps := indexTrace tape distinct labels exit program atLabels base ambient index + counterWord scratchEmpty + steps_le_m := Nat.le_refl _ + +theorem label_finite : Finite Label := inferInstance + +theorem state_finite [Finite A] : Finite (State A) := inferInstance + +end PerfectCompleteness.SourceOccurrenceIndexMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/SourceOccurrenceLoopMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/SourceOccurrenceLoopMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..884504e0b338a653617c83123381c6ca7cdd6853 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/SourceOccurrenceLoopMachine.lean @@ -0,0 +1,323 @@ +import Mathlib.Tactic.DeriveFintype +import OAI.Computability.PerfectCompleteness.Machines.SourceClauseReaderMachineLemmas +import OAI.Computability.PerfectCompleteness.Machines.SourceOccurrenceIndexMachine +import OAI.Computability.PerfectCompleteness.Machines.UnaryBlockCopyMachine + +namespace OAI + + +namespace PerfectCompleteness.SourceOccurrenceLoopMachine + + +open Turing +open UniqueGamesTheorem.Foundations +open Complexity Complexity.MachineComposition +open UniqueGamesTheorem.Reduction.MachineTransfer + +def bodySteps {n : Nat} (first : Nat) (clause : Target.Clause n) : Nat := + 1 + SourceOccurrenceIndexMachine.steps first + (encodeWords (clauseWords clause)).length + 1 + +def steps {n : Nat} (first : Nat) : List (Target.Clause n) → Nat + | [] => 1 + | clause :: clauses => bodySteps first clause + steps (first + 1) clauses + +theorem bodySteps_le {n : Nat} (first maximum : Nat) (clause : Target.Clause n) + (indexBound : first ≤ maximum) : + bodySteps first clause ≤ 2 * maximum + 3 + 3 * (n + 2) + 2 := by + have encoded := clauseBits_length_le clause + unfold bodySteps SourceOccurrenceIndexMachine.steps + omega + +theorem steps_le {n : Nat} (first maximum : Nat) (clauses : List (Target.Clause n)) + (indexBound : first + clauses.length ≤ maximum) : + steps first clauses ≤ clauses.length * (2 * maximum + 3 + 3 * (n + 2) + 2) + 1 := by + induction clauses generalizing first with + | nil => simp [steps] + | cons clause clauses ih => + have head := bodySteps_le first maximum clause (by + simp only [List.length_cons] at indexBound + omega) + have tail := ih (first + 1) (by + simp only [List.length_cons] at indexBound + omega) + simp only [steps, List.length_cons, Nat.add_mul, Nat.one_mul] + omega + +section Program + +variable {K Λ A : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool +abbrev State (A : Type) := A × Option Bool +abbrev clean (ambient : A) : State A := SourceOccurrenceIndexMachine.clean ambient + +def indexMap : Fin 3 → Fin 5 + | 0 => 2 + | 1 => 3 + | 2 => 4 + +def indexTapes (tape : Fin 5 → K) : Fin 3 → K := fun i => tape (indexMap i) + +omit [DecidableEq K] in +theorem indexTapes_injective (tape : Fin 5 → K) (distinct : Function.Injective tape) : + Function.Injective (indexTapes tape) := + distinct.comp (by decide : Function.Injective indexMap) + +inductive Label + | guard + | index (label : SourceOccurrenceIndexMachine.Label) + | field (slot : Fin 6) + | tally + deriving DecidableEq, Fintype + +def finish (exit : Option Λ) : TM2.Stmt (Alphabet (K := K)) Λ (State A) := + .load (fun state => clean state.1) + (match exit with + | none => .halt + | some label => .goto fun _ => label) + +def instruction (tape : Fin 5 → K) (labels : Label → Λ) (done rejected : Option Λ) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (State A) + | .guard => + .pop (tape 1) (fun state head => (state.1, head)) + (.branch (fun state => state.2.isNone) (finish done) + (.branch (fun state => state.2.getD false) + (finish (some (labels (.index SourceOccurrenceIndexMachine.main)))) (finish rejected))) + | .index l => SourceOccurrenceIndexMachine.instruction (indexTapes tape) + (fun l => labels (.index l)) (some (labels (.field 0))) l + | .field slot => UnaryBlockCopyMachine.instruction (tape 0) (tape 4) (labels (.field slot)) + (UnaryBlockCopyMachine.nextField (fun slot => labels (.field slot)) + (some (labels .tally)) slot) rejected + | .tally => .push (tape 2) (fun _ => true) (finish (some (labels .guard))) + +def loopTapes (tape : Fin 5 → K) (base : K → List Bool) (input : List Bool) + (remaining first : Nat) (output : List Bool) : K → List Bool := + Function.update (Function.update (Function.update (Function.update base + (tape 0) input) (tape 1) (List.replicate remaining true)) + (tape 2) (List.replicate first true)) (tape 4) output + +theorem loopTapes_input (tape : Fin 5 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (input : List Bool) (remaining first : Nat) (output : List Bool) : + loopTapes tape base input remaining first output (tape 0) = input := by + have hd (i j : Fin 5) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + simp [loopTapes, hd] + +theorem loopTapes_remaining (tape : Fin 5 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (input : List Bool) (remaining first : Nat) (output : List Bool) : + loopTapes tape base input remaining first output (tape 1) = List.replicate remaining true := by + have hd (i j : Fin 5) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + simp [loopTapes, hd] + +theorem loopTapes_index (tape : Fin 5 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (input : List Bool) (remaining first : Nat) (output : List Bool) : + loopTapes tape base input remaining first output (tape 2) = List.replicate first true := by + have hd (i j : Fin 5) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + simp [loopTapes, hd] + +theorem loopTapes_scratch (tape : Fin 5 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (input : List Bool) (remaining first : Nat) (output : List Bool) : + loopTapes tape base input remaining first output (tape 3) = base (tape 3) := by + have hd (i j : Fin 5) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + simp [loopTapes, hd] + +theorem loopTapes_output (tape : Fin 5 → K) (base : K → List Bool) (input : List Bool) + (remaining first : Nat) (output : List Bool) : + loopTapes tape base input remaining first output (tape 4) = output := by + simp [loopTapes] + +private theorem update_input (tape : Fin 5 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (input replacement : List Bool) (remaining first : Nat) + (output : List Bool) : + Function.update (loopTapes tape base input remaining first output) (tape 0) replacement = + loopTapes tape base replacement remaining first output := by + have hd (i j : Fin 5) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + funext k + by_cases h : k = tape 0 + · subst k; simp [loopTapes, hd] + · simp [loopTapes, h, Function.update_apply] + +private theorem update_remaining (tape : Fin 5 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (input : List Bool) (remaining first replacement : Nat) + (output : List Bool) : + Function.update (loopTapes tape base input remaining first output) + (tape 1) (List.replicate replacement true) = + loopTapes tape base input replacement first output := by + have hd (i j : Fin 5) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + funext k + by_cases h : k = tape 1 + · subst k; simp [loopTapes, hd] + · simp [loopTapes, h, Function.update_apply] + +private theorem update_index (tape : Fin 5 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (input : List Bool) (remaining first replacement : Nat) + (output : List Bool) : + Function.update (loopTapes tape base input remaining first output) + (tape 2) (List.replicate replacement true) = + loopTapes tape base input remaining replacement output := by + have hd (i j : Fin 5) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + funext k + by_cases h : k = tape 2 + · subst k; simp [loopTapes, hd] + · simp [loopTapes, h, Function.update_apply] + +private theorem update_output (tape : Fin 5 → K) (base : K → List Bool) (input : List Bool) + (remaining first : Nat) (output replacement : List Bool) : + Function.update (loopTapes tape base input remaining first output) (tape 4) replacement = + loopTapes tape base input remaining first replacement := by + simp [loopTapes] + +private theorem tapesAt_loop (tape : Fin 5 → K) (distinct : Function.Injective tape) + (base : K → List Bool) (input replacement : List Bool) (remaining first : Nat) + (output newOutput : List Bool) : + tapesAt (tape 0) (tape 4) (loopTapes tape base input remaining first output) + replacement newOutput = loopTapes tape base replacement remaining first newOutput := by + unfold tapesAt + rw [update_input tape distinct, update_output] + +@[simp] theorem stepAux_finish (exit : Option Λ) (state : State A) (base : K → List Bool) : + TM2.stepAux (finish exit) state base = ⟨exit, clean state.1, base⟩ := by + cases exit <;> rfl + +private theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +variable (tape : Fin 5 → K) (distinct : Function.Injective tape) +variable (labels : Label → Λ) (done rejected : Option Λ) +variable (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) +variable (atLabels : ∀ l, program (labels l) = instruction tape labels done rejected l) +variable (base : K → List Bool) (ambient : A) + +include distinct atLabels + +theorem guardStep (input : List Bool) (remaining first : Nat) (output : List Bool) : + TM2.step program + ⟨some (labels .guard), clean ambient, + loopTapes tape base input (remaining + 1) first output⟩ = + some ⟨some (labels (.index SourceOccurrenceIndexMachine.main)), clean ambient, + loopTapes tape base input remaining first output⟩ := by + change some (TM2.stepAux (program (labels .guard)) _ _) = _ + rw [atLabels .guard] + simp [instruction, TM2.stepAux, clean, SourceOccurrenceIndexMachine.clean, + loopTapes_remaining tape distinct, List.replicate_succ, update_remaining tape distinct] + +theorem emptyStep (input : List Bool) (first : Nat) (output : List Bool) : + TM2.step program + ⟨some (labels .guard), clean ambient, loopTapes tape base input 0 first output⟩ = + some ⟨done, clean ambient, loopTapes tape base input 0 first output⟩ := by + have unchanged : Function.update (loopTapes tape base input 0 first output) (tape 1) [] = + loopTapes tape base input 0 first output := by + simpa only [List.replicate_zero] using + update_remaining tape distinct base input 0 first 0 output + change some (TM2.stepAux (program (labels .guard)) _ _) = _ + rw [atLabels .guard] + simp [instruction, TM2.stepAux, clean, SourceOccurrenceIndexMachine.clean, + loopTapes_remaining tape distinct, unchanged] + +theorem tallyStep (input : List Bool) (remaining first : Nat) (output : List Bool) : + TM2.step program + ⟨some (labels .tally), clean ambient, loopTapes tape base input remaining first output⟩ = + some ⟨some (labels .guard), clean ambient, loopTapes tape base input remaining (first + 1) output⟩ := by + change some (TM2.stepAux (program (labels .tally)) _ _) = _ + rw [atLabels .tally] + simp [instruction, TM2.stepAux, clean, SourceOccurrenceIndexMachine.clean, + loopTapes_index tape distinct, ← List.replicate_succ, update_index tape distinct] + +theorem bodyTrace {n : Nat} (clause : Target.Clause n) (suffix : List Bool) + (remaining first : Nat) (output : List Bool) (scratchEmpty : base (tape 3) = []) : + (advance (TM2.step program))^[bodySteps first clause] + (some ⟨some (labels .guard), clean ambient, + loopTapes tape base (encodeWords (clauseWords clause) ++ suffix) + (remaining + 1) first output⟩) = + some ⟨some (labels .guard), clean ambient, + loopTapes tape base suffix remaining (first + 1) + ((SourceOccurrenceEncoding.recordBits first clause).reverse ++ output)⟩ := by + have hd (i j : Fin 5) (hne : i ≠ j) : tape i ≠ tape j := fun h => hne (distinct h) + let input := encodeWords (clauseWords clause) ++ suffix + let indexOutput := (encodeWord first).reverse ++ output + let clauseOutput := (encodeWords (clauseWords clause)).reverse ++ indexOutput + have guard : (advance (TM2.step program))^[1] + (some ⟨some (labels .guard), clean ambient, + loopTapes tape base input (remaining + 1) first output⟩) = + some ⟨some (labels (.index SourceOccurrenceIndexMachine.main)), clean ambient, + loopTapes tape base input remaining first output⟩ := by + simpa only [Function.iterate_one, advance_some] using + guardStep tape distinct labels done rejected program atLabels base ambient + input remaining first output + have index := SourceOccurrenceIndexMachine.indexTrace (indexTapes tape) + (indexTapes_injective tape distinct) (fun l => labels (.index l)) + (some (labels (.field 0))) program (fun l => atLabels (.index l)) + (loopTapes tape base input remaining first output) ambient first + (by simp [indexTapes, indexMap, loopTapes, hd]) + (by simp [indexTapes, indexMap, loopTapes, hd, scratchEmpty]) + rw [show indexTapes tape 2 = tape 4 from rfl, loopTapes_output, update_output] at index + have copied : (advance (TM2.step program))^[(encodeWords (clauseWords clause)).length] + (some ⟨some (labels (.field 0)), clean ambient, + loopTapes tape base input remaining first indexOutput⟩) = + some ⟨some (labels .tally), clean ambient, + loopTapes tape base suffix remaining first clauseOutput⟩ := by + have h := UnaryBlockCopyMachine.listTrace (tape 0) (tape 4) (hd 0 4 (by decide)) + (fun slot => labels (.field slot)) (some (labels .tally)) rejected program + (fun slot => atLabels (.field slot)) + (loopTapes tape base input remaining first indexOutput) ambient + (clauseWords clause) (by simp) suffix indexOutput none + simpa only [tapesAt_loop tape distinct, clean, SourceOccurrenceIndexMachine.clean, + input, clauseOutput] using h + have tally : (advance (TM2.step program))^[1] + (some ⟨some (labels .tally), clean ambient, + loopTapes tape base suffix remaining first clauseOutput⟩) = + some ⟨some (labels .guard), clean ambient, + loopTapes tape base suffix remaining (first + 1) clauseOutput⟩ := by + simpa only [Function.iterate_one, advance_some] using + tallyStep tape distinct labels done rejected program atLabels base ambient + suffix remaining first clauseOutput + have full := joinTrace (joinTrace (joinTrace guard index) copied) tally + simpa only [bodySteps, input, clauseOutput, indexOutput, + SourceOccurrenceEncoding.recordBits_eq, List.reverse_append, List.append_assoc] using full + +theorem loopTrace {n : Nat} (clauses : List (Target.Clause n)) (suffix : List Bool) + (first : Nat) (output : List Bool) (scratchEmpty : base (tape 3) = []) : + (advance (TM2.step program))^[steps first clauses] + (some ⟨some (labels .guard), clean ambient, + loopTapes tape base (encodeWords (clauses.flatMap clauseWords) ++ suffix) + clauses.length first output⟩) = + some ⟨done, clean ambient, + loopTapes tape base suffix 0 (first + clauses.length) + ((SourceOccurrenceEncoding.body first clauses).reverse ++ output)⟩ := by + induction clauses generalizing first output with + | nil => + simpa only [steps, Function.iterate_one, advance_some, List.flatMap_nil, encodeWords, + List.nil_append, List.length_nil, Nat.add_zero, SourceOccurrenceEncoding.body_nil, + List.reverse_nil] using + emptyStep tape distinct labels done rejected program atLabels base ambient suffix first output + | cons clause clauses ih => + have head := bodyTrace tape distinct labels done rejected program atLabels base ambient clause + (encodeWords (clauses.flatMap clauseWords) ++ suffix) clauses.length first output scratchEmpty + have tail := ih (first + 1) + ((SourceOccurrenceEncoding.recordBits first clause).reverse ++ output) + have full := joinTrace head tail + have indexEq : first + 1 + clauses.length = first + (clauses.length + 1) := by omega + simpa only [steps, List.flatMap_cons, encodeWords_append, List.append_assoc, + List.length_cons, indexEq, SourceOccurrenceEncoding.body_cons, List.reverse_append] using full + +def loopInTime {n : Nat} (clauses : List (Target.Clause n)) (suffix : List Bool) + (first maximum : Nat) (output : List Bool) (scratchEmpty : base (tape 3) = []) + (indexBound : first + clauses.length ≤ maximum) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .guard), clean ambient, + loopTapes tape base (encodeWords (clauses.flatMap clauseWords) ++ suffix) + clauses.length first output⟩ + (some ⟨done, clean ambient, + loopTapes tape base suffix 0 (first + clauses.length) + ((SourceOccurrenceEncoding.body first clauses).reverse ++ output)⟩) + (clauses.length * (2 * maximum + 3 + 3 * (n + 2) + 2) + 1) where + steps := steps first clauses + evals_in_steps := loopTrace tape distinct labels done rejected program atLabels base ambient + clauses suffix first output scratchEmpty + steps_le_m := steps_le first maximum clauses indexBound + +end Program + +end PerfectCompleteness.SourceOccurrenceLoopMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/SourceOccurrenceMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/SourceOccurrenceMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..718d7e6165f442f1f9f86d0c1a1dcfe86f39bd8f --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/SourceOccurrenceMachine.lean @@ -0,0 +1,290 @@ +import OAI.Computability.PerfectCompleteness.Machines.BinaryHeaderMachine +import OAI.Computability.PerfectCompleteness.Machines.SourceOccurrenceLoopMachine +import OAI.Computability.UniqueGames.Machines.MachineFiniteAlphabet +import OAI.Computability.UniqueGames.PCP.SourceMachine + +namespace OAI + + +namespace PerfectCompleteness.SourceOccurrenceMachine + + +open Turing UniqueGamesTheorem.Foundations Complexity Target +open MachineComposition UniqueGamesTheorem.Reduction.MachineTransfer + +abbrev Tape := Fin 7 +abbrev Alphabet (_ : Tape) := Bool +abbrev State := Unit × Option Bool + +def clean : State := ((), none) + +inductive Label + | readVariables | readCount + | loop (label : SourceOccurrenceLoopMachine.Label) + | restore | clauseStart | clauseLoop | variableStart | variableLoop | reject + deriving DecidableEq, Fintype + +def loopTapes : Fin 5 → Tape + | 0 => 0 + | 1 => 2 + | 2 => 3 + | 3 => 4 + | 4 => 5 + +theorem loopTapes_injective : Function.Injective loopTapes := by decide + +def program : Label → TM2.Stmt Alphabet Label State + | .readVariables => Hastad.SourceMachine.fieldLoop 0 1 .readVariables (some .readCount) + | .readCount => Hastad.SourceMachine.fieldLoop 0 2 .readCount (some (.loop .guard)) + | .loop label => SourceOccurrenceLoopMachine.instruction loopTapes Label.loop + (some .restore) (some .reject) label + | .restore => loopAt 5 6 id false .restore (some .clauseStart) + | .clauseStart => BinaryHeaderMachine.delimiter 6 .clauseLoop + | .clauseLoop => loopAt 3 6 id false .clauseLoop (some .variableStart) + | .variableStart => BinaryHeaderMachine.delimiter 6 .variableLoop + | .variableLoop => loopAt 1 6 id false .variableLoop none + | .reject => .halt + +abbrev machine : FinTM2 where + K := Tape + k₀ := 0 + k₁ := 6 + Γ := Alphabet + Λ := Label + main := .readVariables + σ := State + initialState := clean + m := program + +def tapes (input variableCounter remaining index reversed output : List Bool) : Tape → List Bool := + fun k => if k = 0 then input else if k = 1 then variableCounter else if k = 2 then remaining + else if k = 3 then index else if k = 5 then reversed else if k = 6 then output else [] + +def cfg (label : Option Label) (input variableCounter remaining index reversed output : List Bool) : + machine.Cfg := ⟨label, clean, tapes input variableCounter remaining index reversed output⟩ + +theorem initList_eq (input : List Bool) : + initList machine input = cfg (some .readVariables) input [] [] [] [] [] := by + unfold initList cfg + congr 1 + funext k + fin_cases k <;> simp [tapes, machine] + +theorem haltList_eq (output : List Bool) : + haltList machine output = cfg none [] [] [] [] [] output := by + unfold haltList cfg + congr 1 + funext k + fin_cases k <;> simp [tapes, machine] + +private theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +theorem readVariablesTrace (n : Nat) (suffix : List Bool) : + (advance machine.step)^[n + 1] + (some (cfg (some .readVariables) (encodeWord n ++ suffix) [] [] [] [] [])) = + some (cfg (some .readCount) suffix (List.replicate n true) [] [] [] []) := by + change (advance (TM2.step program))^[n + 1] + (some ⟨some .readVariables, ((), none), + tapes (encodeWord n ++ suffix) [] [] [] [] []⟩) = + some ⟨some .readCount, ((), none), tapes suffix (List.replicate n true) [] [] [] []⟩ + have updated (input variableCounter : List Bool) : + Hastad.SourceMachine.fieldTapes (0 : Tape) 1 (tapes [] [] [] [] [] []) input variableCounter = + tapes input variableCounter [] [] [] [] := by + funext k + fin_cases k <;> simp [Hastad.SourceMachine.fieldTapes, tapes] + have run := Hastad.SourceMachine.fieldLoopTrace (0 : Tape) 1 (by decide) + .readVariables (some .readCount) program rfl (tapes [] [] [] [] [] []) n suffix [] () none + simp only [updated, List.append_nil] at run + exact run + +theorem readCountTrace (n m : Nat) (suffix : List Bool) : + (advance machine.step)^[m + 1] + (some (cfg (some .readCount) (encodeWord m ++ suffix) (List.replicate n true) [] [] [] [])) = + some (cfg (some (.loop .guard)) suffix (List.replicate n true) + (List.replicate m true) [] [] []) := by + change (advance (TM2.step program))^[m + 1] + (some ⟨some .readCount, ((), none), + tapes (encodeWord m ++ suffix) (List.replicate n true) [] [] [] []⟩) = + some ⟨some (.loop .guard), ((), none), + tapes suffix (List.replicate n true) (List.replicate m true) [] [] []⟩ + have updated (input remaining : List Bool) : + Hastad.SourceMachine.fieldTapes (0 : Tape) 2 (tapes [] (List.replicate n true) [] [] [] []) + input remaining = tapes input (List.replicate n true) remaining [] [] [] := by + funext k + fin_cases k <;> simp [Hastad.SourceMachine.fieldTapes, tapes] + have run := Hastad.SourceMachine.fieldLoopTrace (0 : Tape) 2 (by decide) + .readCount (some (.loop .guard)) program rfl + (tapes [] (List.replicate n true) [] [] [] []) m suffix [] () none + simp only [updated, List.append_nil] at run + exact run + +theorem headersTrace (n m : Nat) (suffix : List Bool) : + (advance machine.step)^[n + m + 2] + (some (cfg (some .readVariables) (encodeWord n ++ encodeWord m ++ suffix) [] [] [] [] [])) = + some (cfg (some (.loop .guard)) suffix (List.replicate n true) + (List.replicate m true) [] [] []) := by + have first := readVariablesTrace n (encodeWord m ++ suffix) + have second := readCountTrace n m suffix + have full := joinTrace first second + have count : n + 1 + (m + 1) = n + m + 2 := by omega + simpa only [count, List.append_assoc] using full + +theorem restoreTrace (variableCounter index body : List Bool) : + (advance machine.step)^[body.length + 1] + (some (cfg (some .restore) [] variableCounter [] index body.reverse [])) = + some (cfg (some .clauseStart) [] variableCounter [] index [] body) := by + change (nextAt (6 : Tape) program)^[body.length + 1] + (some (cfg (some .restore) [] variableCounter [] index body.reverse [])) = _ + have updated : tapesAt (5 : Tape) 6 (tapes [] variableCounter [] index body.reverse []) [] body = + tapes [] variableCounter [] index [] body := by + funext k + fin_cases k <;> simp [tapesAt, tapes] + have run := transferAt_fromTapes (Γ := Alphabet) (5 : Tape) 6 (by decide) id false + .restore (some .clauseStart) program rfl (tapes [] variableCounter [] index body.reverse []) () none + have source : tapes [] variableCounter [] index body.reverse [] 5 = body.reverse := rfl + have output : tapes [] variableCounter [] index body.reverse [] 6 = [] := rfl + rw [source, output, List.length_reverse, List.reverse_reverse, List.map_id_fun, + List.append_nil, id_eq, updated] at run + exact run + +theorem headerOutputTrace (n m : Nat) (body : List Bool) : + (advance machine.step)^[n + m + 4] + (some (cfg (some .clauseStart) [] (List.replicate n true) [] + (List.replicate m true) [] body)) = + some (cfg none [] [] [] [] [] (encodeWord n ++ encodeWord m ++ body)) := by + change (advance (TM2.step program))^[n + m + 4] + (some ⟨some .clauseStart, ((), none), + tapes [] (List.replicate n true) [] (List.replicate m true) [] body⟩) = + some ⟨none, ((), none), tapes [] [] [] [] [] (encodeWord n ++ encodeWord m ++ body)⟩ + have updated (variableCounter clauses output : List Bool) : + BinaryHeaderMachine.tapes (1 : Tape) 3 6 (tapes [] [] [] [] [] []) variableCounter clauses output = + tapes [] variableCounter [] clauses [] output := by + funext k + fin_cases k <;> simp [BinaryHeaderMachine.tapes, tapes] + have run := BinaryHeaderMachine.headerTrace (1 : Tape) 3 6 (by decide) (by decide) (by decide) + .clauseStart .clauseLoop .variableStart .variableLoop none program rfl rfl rfl rfl + (tapes [] [] [] [] [] []) () n m body none + simp only [updated] at run + exact run + +theorem formulaBits_eq (formula : Formula) : + formulaBits formula = encodeWord formula.variables ++ encodeWord formula.clauses.length ++ + encodeWords (formula.clauses.flatMap clauseWords) := by + simp only [formulaBits, formulaWords, encodeWords_append, encodeWords, + List.append_nil, List.append_assoc] + +theorem header_counts_le (formula : Formula) : + formula.variables ≤ (formulaBits formula).length ∧ + formula.clauses.length ≤ (formulaBits formula).length := by + rw [formulaBits_eq] + simp only [List.length_append, encodeWord_length] + omega + +theorem loopTrace (formula : Formula) : + (advance machine.step)^[SourceOccurrenceLoopMachine.steps 0 formula.clauses] + (some (cfg (some (.loop .guard)) (encodeWords (formula.clauses.flatMap clauseWords)) + (List.replicate formula.variables true) (List.replicate formula.clauses.length true) + [] [] [])) = + some (cfg (some .restore) [] (List.replicate formula.variables true) [] + (List.replicate formula.clauses.length true) + (SourceOccurrenceEncoding.body 0 formula.clauses).reverse []) := by + change (advance (TM2.step program))^[SourceOccurrenceLoopMachine.steps 0 formula.clauses] + (some ⟨some (.loop .guard), ((), none), + tapes (encodeWords (formula.clauses.flatMap clauseWords)) + (List.replicate formula.variables true) (List.replicate formula.clauses.length true) + [] [] []⟩) = + some ⟨some .restore, ((), none), + tapes [] (List.replicate formula.variables true) [] + (List.replicate formula.clauses.length true) + (SourceOccurrenceEncoding.body 0 formula.clauses).reverse []⟩ + have updated (input : List Bool) (remaining first : Nat) (output : List Bool) : + SourceOccurrenceLoopMachine.loopTapes loopTapes + (tapes [] (List.replicate formula.variables true) [] [] [] []) + input remaining first output = + tapes input (List.replicate formula.variables true) (List.replicate remaining true) + (List.replicate first true) output [] := by + funext k + fin_cases k <;> simp [SourceOccurrenceLoopMachine.loopTapes, loopTapes, tapes] + have run := SourceOccurrenceLoopMachine.loopTrace loopTapes loopTapes_injective Label.loop + (some .restore) (some .reject) program (fun _ => rfl) + (tapes [] (List.replicate formula.variables true) [] [] [] []) () formula.clauses [] 0 [] rfl + simp only [updated, List.append_nil, List.replicate_zero, Nat.zero_add] at run + exact run + +def steps (formula : Formula) : Nat := + (formula.variables + formula.clauses.length + 2) + + SourceOccurrenceLoopMachine.steps 0 formula.clauses + + ((SourceOccurrenceEncoding.body 0 formula.clauses).length + 1) + + (formula.variables + formula.clauses.length + 4) + +theorem occurrenceTrace (formula : Formula) : + (advance machine.step)^[steps formula] (some (initList machine (formulaBits formula))) = + some (haltList machine (SourceOccurrenceEncoding.bits formula)) := by + have first := headersTrace formula.variables formula.clauses.length + (encodeWords (formula.clauses.flatMap clauseWords)) + have second := loopTrace formula + have third := restoreTrace (List.replicate formula.variables true) + (List.replicate formula.clauses.length true) (SourceOccurrenceEncoding.body 0 formula.clauses) + have fourth := headerOutputTrace formula.variables formula.clauses.length + (SourceOccurrenceEncoding.body 0 formula.clauses) + have full := joinTrace (joinTrace (joinTrace first second) third) fourth + simpa only [steps, initList_eq, haltList_eq, formulaBits_eq, + SourceOccurrenceEncoding.bits_eq] using full + +noncomputable def timePolynomial : Polynomial Nat := + Polynomial.C 100 * (Polynomial.X + Polynomial.C 1) ^ 2 + +theorem steps_le (formula : Formula) : + steps formula ≤ timePolynomial.eval (formulaBits formula).length := by + let B := (formulaBits formula).length + have variablesBound : formula.variables ≤ B := (header_counts_le formula).1 + have clausesBound : formula.clauses.length ≤ B := (header_counts_le formula).2 + have loopBound := SourceOccurrenceLoopMachine.steps_le 0 formula.clauses.length + formula.clauses (by omega) + have loopUniform : SourceOccurrenceLoopMachine.steps 0 formula.clauses ≤ + B * (5 * B + 11) + 1 := + loopBound.trans (Nat.add_le_add_right + (Nat.mul_le_mul clausesBound (by omega)) 1) + have bodyBound := SourceOccurrenceEncoding.body_length_le formula.clauses 0 + formula.clauses.length (by omega) + have bodyUniform : (SourceOccurrenceEncoding.body 0 formula.clauses).length ≤ + B * (4 * B + 7) := + bodyBound.trans (Nat.mul_le_mul clausesBound (by omega)) + simp only [timePolynomial, Polynomial.eval_mul, Polynomial.eval_pow, Polynomial.eval_add, + Polynomial.eval_C, Polynomial.eval_X] + change steps formula ≤ 100 * (B + 1) ^ 2 + unfold steps + nlinarith + +def outputsInTime (formula : Formula) : + TM2OutputsInTime machine (formulaBits formula) + (some (SourceOccurrenceEncoding.bits formula)) + (timePolynomial.eval (formulaBits formula).length) where + steps := steps formula + evals_in_steps := occurrenceTrace formula + steps_le_m := steps_le formula + +noncomputable def computableInPolyTime : + TM2ComputableInPolyTime formulaBits SourceOccurrenceEncoding.bits (id : Formula → Formula) where + tm := machine + inputAlphabet := Equiv.refl Bool + outputAlphabet := Equiv.refl Bool + time := timePolynomial + outputsFun formula := by + change TM2OutputsInTime machine ((formulaBits formula).map id) + (some ((SourceOccurrenceEncoding.bits formula).map id)) + (timePolynomial.eval (formulaBits formula).length) + simpa only [List.map_id_fun, id_eq] using outputsInTime formula + +theorem machine_finiteAlphabet (k : machine.K) : Finite (machine.Γ k) := by + change Finite Bool + infer_instance + +theorem computation_finiteAlphabet : MachineFiniteAlphabet.FiniteAlphabet computableInPolyTime.tm := + machine_finiteAlphabet + +end PerfectCompleteness.SourceOccurrenceMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/SourceOccurrenceProducerLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/SourceOccurrenceProducerLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..7a85e9e63058e7cc36e79ae8af65d3779391b6e4 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/SourceOccurrenceProducerLemmas.lean @@ -0,0 +1,250 @@ +import OAI.Computability.PerfectCompleteness.Foundations.PCPSourceHardness +import OAI.Computability.PerfectCompleteness.Machines.SourceOccurrenceMachine + +namespace OAI + + +namespace PerfectCompleteness.SourceOccurrenceProducer + +open Turing UniqueGamesTheorem.Foundations Complexity + +noncomputable section + +def normalizedComputation : + TM2ComputableInPolyTime formulaBits SourceOccurrenceEncoding.bits + PCPSource.normalizedFormula := by + change TM2ComputableInPolyTime formulaBits SourceOccurrenceEncoding.bits + (fun formula => id (PCPSource.normalizedFormula formula)) + exact MachineSequential.composeBits (f := PCPSource.normalizedFormula) (g := id) + PCPSourceMachine.normalizedComputation + SourceOccurrenceMachine.computableInPolyTime + +theorem normalized_finiteAlphabet : + MachineFiniteAlphabet.FiniteAlphabet normalizedComputation.tm := + MachineFiniteAlphabet.composeBits PCPSourceMachine.normalizedComputation + SourceOccurrenceMachine.computableInPolyTime PCPSourceMachine.normalized_finiteAlphabet + SourceOccurrenceMachine.computation_finiteAlphabet + +def rawComputation : + TM2ComputableInPolyTime (id : List Bool → List Bool) SourceOccurrenceEncoding.bits + PCPSourceMachine.rawSource := by + change TM2ComputableInPolyTime (id : List Bool → List Bool) SourceOccurrenceEncoding.bits + (fun input => id (PCPSourceMachine.rawSource input)) + exact MachineSequential.composeBits (f := PCPSourceMachine.rawSource) (g := id) + PCPSourceMachine.rawComputation + SourceOccurrenceMachine.computableInPolyTime + +theorem raw_finiteAlphabet : MachineFiniteAlphabet.FiniteAlphabet rawComputation.tm := + MachineFiniteAlphabet.composeBits PCPSourceMachine.rawComputation + SourceOccurrenceMachine.computableInPolyTime PCPSourceMachine.raw_finiteAlphabet + SourceOccurrenceMachine.computation_finiteAlphabet + +def computation {language : List Bool → Prop} + (source : CookLevin.PolynomialThreeSATReduction language) : + TM2ComputableInPolyTime (id : List Bool → List Bool) SourceOccurrenceEncoding.bits + (PCPSourceHardness.formula source) := by + change TM2ComputableInPolyTime (id : List Bool → List Bool) SourceOccurrenceEncoding.bits + (fun input => id (PCPSourceHardness.formula source input)) + exact MachineSequential.composeBits (f := PCPSourceHardness.formula source) (g := id) + (PCPSourceHardness.computation source) + SourceOccurrenceMachine.computableInPolyTime + +theorem computation_finiteAlphabet {language : List Bool → Prop} + (source : CookLevin.PolynomialThreeSATReduction language) + (finiteSource : MachineFiniteAlphabet.FiniteAlphabet source.computation.tm) : + MachineFiniteAlphabet.FiniteAlphabet (computation source).tm := + MachineFiniteAlphabet.composeBits (PCPSourceHardness.computation source) + SourceOccurrenceMachine.computableInPolyTime + (PCPSourceHardness.computation_finiteAlphabet source finiteSource) + SourceOccurrenceMachine.computation_finiteAlphabet + +end +end PerfectCompleteness.SourceOccurrenceProducer + + +namespace PerfectCompleteness.NormalizedSourceInput + + +open Turing UniqueGamesTheorem.Foundations Complexity Target + +structure Input where + formula : Formula + nonempty : formula.clauses ≠ [] + distinct : ∀ clause ∈ formula.clauses, ∀ i j : Fin 3, + clause[i].variableIndex = clause[j].variableIndex → i = j + +def bits (input : Input) : List Bool := SourceOccurrenceEncoding.bits input.formula + +def variableCount (input : Input) : Nat := input.formula.variables +def clauseCount (input : Input) : Nat := input.formula.clauses.length + +theorem clauseCount_positive (input : Input) : 0 < clauseCount input := + List.length_pos_iff.mpr input.nonempty + +instance clauseCount_neZero (input : Input) : NeZero (clauseCount input) := + ⟨Nat.ne_of_gt (clauseCount_positive input)⟩ + +def clauses (input : Input) : Fin (clauseCount input) → SourceClause.NormalizedClause (variableCount input) := + fun index => + { clause := input.formula.clauses[index.val] + distinct := input.distinct _ (List.getElem_mem index.isLt) } + +@[simp] theorem clause_eq (input : Input) (index : Fin (clauseCount input)) : + (clauses input index).clause = input.formula.clauses[index.val] := rfl + +@[simp] theorem variable_eq (input : Input) (index : Fin (clauseCount input)) (slot : Fin 3) : + (clauses input index).variable slot = input.formula.clauses[index.val][slot].variableIndex := rfl + +@[simp] theorem signs_eq (input : Input) (index : Fin (clauseCount input)) : + (clauses input index).signs = + (input.formula.clauses[index.val][0].positive, + input.formula.clauses[index.val][1].positive, + input.formula.clauses[index.val][2].positive) := rfl + +theorem bits_eq (input : Input) : + bits input = encodeWord (variableCount input) ++ encodeWord (clauseCount input) ++ + SourceOccurrenceEncoding.body 0 input.formula.clauses := + SourceOccurrenceEncoding.bits_eq input.formula + +theorem decode_bits (input : Input) : + SourceOccurrenceEncoding.decode (bits input) = some input.formula := + SourceOccurrenceEncoding.decode_bits input.formula + +theorem ext (first second : Input) (same : first.formula = second.formula) : first = second := by + cases first + cases second + cases same + rfl + +theorem bits_injective : Function.Injective bits := by + intro first second same + exact ext first second (SourceOccurrenceEncoding.bits_injective same) + +noncomputable section + +def normalized (formula : Formula) : Input where + formula := PCPSource.normalizedFormula formula + nonempty := PCPSource.normalizedFormula_nonempty formula + distinct := PCPSource.normalizedFormula_distinct formula + +@[simp] theorem normalized_formula (formula : Formula) : + (normalized formula).formula = PCPSource.normalizedFormula formula := rfl + +@[simp] theorem normalized_bits (formula : Formula) : + bits (normalized formula) = SourceOccurrenceEncoding.bits (PCPSource.normalizedFormula formula) := rfl + +theorem violatedCount_eq_failedCount (input : Input) + (assignment : Fin input.formula.variables → Bool) : + SourceGame.violatedCount (clauses input) assignment = + PCP.NameCompaction.failedCount input.formula assignment := by + rw [PCPSource.failedCount_eq_fin_sum] + rfl + +theorem clauseGap_of_count (input : Input) (denominator : Nat) + (positive : 0 < denominator) + (countGap : ∀ assignment : Fin input.formula.variables → Bool, + input.formula.clauses.length ≤ + denominator * PCP.NameCompaction.failedCount input.formula assignment) : + SourceAmplification.ClauseGap (clauses input) (1 / (denominator : ℚ)) := by + intro assignment + have hnat := countGap assignment + have hq : (input.formula.clauses.length : ℚ) ≤ + (denominator : ℚ) * (PCP.NameCompaction.failedCount input.formula assignment : ℚ) := by + exact_mod_cast hnat + change (1 / (denominator : ℚ)) * (input.formula.clauses.length : ℚ) ≤ _ + erw [violatedCount_eq_failedCount] + rw [one_div_mul_eq_div] + have hden : (0 : ℚ) < denominator := by exact_mod_cast positive + exact (div_le_iff₀ hden).mpr (by simpa only [mul_comm] using hq) + +theorem clauseGap_mk (formula : Formula) (nonempty : formula.clauses ≠ []) + (distinct : ∀ clause ∈ formula.clauses, ∀ i j : Fin 3, + clause[i].variableIndex = clause[j].variableIndex → i = j) + (denominator : Nat) (positive : 0 < denominator) + (countGap : ∀ assignment : Fin formula.variables → Bool, + formula.clauses.length ≤ denominator * PCP.NameCompaction.failedCount formula assignment) : + SourceAmplification.ClauseGap (clauses ⟨formula, nonempty, distinct⟩) + (1 / (denominator : ℚ)) := + clauseGap_of_count ⟨formula, nonempty, distinct⟩ denominator positive countGap + +theorem normalized_clauseGap (formula : Formula) (unsatisfiable : ¬formula.Satisfiable) : + SourceAmplification.ClauseGap (clauses (normalized formula)) PCPSource.sourceGap := + clauseGap_mk (PCPSource.normalizedFormula formula) + (PCPSource.normalizedFormula_nonempty formula) (PCPSource.normalizedFormula_distinct formula) + PCPSource.sourceDenominator PCPSource.sourceDenominator_pos + (PCPSource.normalizedFormula_count_gap formula unsatisfiable) + +def normalizedComputation : TM2ComputableInPolyTime formulaBits bits normalized where + toTM2ComputableAux := SourceOccurrenceProducer.normalizedComputation.toTM2ComputableAux + time := SourceOccurrenceProducer.normalizedComputation.time + outputsFun formula := SourceOccurrenceProducer.normalizedComputation.outputsFun formula + +theorem normalized_finiteAlphabet : + MachineFiniteAlphabet.FiniteAlphabet normalizedComputation.tm := + SourceOccurrenceProducer.normalized_finiteAlphabet + +def raw (input : List Bool) : Input := normalized (BinaryLanguage.totalRename input) + +@[simp] theorem raw_formula (input : List Bool) : + (raw input).formula = PCPSourceMachine.rawSource input := rfl + +def rawComputation : TM2ComputableInPolyTime (id : List Bool → List Bool) bits raw where + toTM2ComputableAux := SourceOccurrenceProducer.rawComputation.toTM2ComputableAux + time := SourceOccurrenceProducer.rawComputation.time + outputsFun input := SourceOccurrenceProducer.rawComputation.outputsFun input + +theorem raw_finiteAlphabet : MachineFiniteAlphabet.FiniteAlphabet rawComputation.tm := + SourceOccurrenceProducer.raw_finiteAlphabet + +theorem raw_satisfiable_iff (input : List Bool) : + (raw input).formula.Satisfiable ↔ BinaryLanguage.language input := + PCPSourceMachine.rawSource_satisfiable_iff input + +theorem raw_clauseGap (input : List Bool) (rejected : ¬BinaryLanguage.language input) : + SourceAmplification.ClauseGap (clauses (raw input)) PCPSource.sourceGap := + normalized_clauseGap (BinaryLanguage.totalRename input) + (fun satisfiable => rejected ((BinaryLanguage.totalRename_satisfiable_iff input).mp satisfiable)) + +def fromReduction {language : List Bool → Prop} + (source : CookLevin.PolynomialThreeSATReduction language) (input : List Bool) : Input := + normalized (source.reduce input) + +@[simp] theorem fromReduction_formula {language : List Bool → Prop} + (source : CookLevin.PolynomialThreeSATReduction language) (input : List Bool) : + (fromReduction source input).formula = PCPSourceHardness.formula source input := rfl + +def computation {language : List Bool → Prop} + (source : CookLevin.PolynomialThreeSATReduction language) : + TM2ComputableInPolyTime (id : List Bool → List Bool) bits (fromReduction source) where + toTM2ComputableAux := (SourceOccurrenceProducer.computation source).toTM2ComputableAux + time := (SourceOccurrenceProducer.computation source).time + outputsFun input := (SourceOccurrenceProducer.computation source).outputsFun input + +theorem computation_finiteAlphabet {language : List Bool → Prop} + (source : CookLevin.PolynomialThreeSATReduction language) + (finiteSource : MachineFiniteAlphabet.FiniteAlphabet source.computation.tm) : + MachineFiniteAlphabet.FiniteAlphabet (computation source).tm := + SourceOccurrenceProducer.computation_finiteAlphabet source finiteSource + +theorem producer (language : List Bool → Prop) (membership : CookLevin.InNP language) : + ∃ source : CookLevin.PolynomialThreeSATReduction language, + ∃ runtime : TM2ComputableInPolyTime (id : List Bool → List Bool) bits (fromReduction source), + MachineFiniteAlphabet.FiniteAlphabet runtime.tm ∧ + ∀ input : List Bool, + ((fromReduction source input).formula.Satisfiable ↔ language input) ∧ + (¬language input → SourceAmplification.ClauseGap + (clauses (fromReduction source input)) PCPSource.sourceGap) := by + obtain ⟨source, finiteSource⟩ := CookLevin.Completeness.threeSATReduction language membership + refine ⟨source, computation source, computation_finiteAlphabet source finiteSource, ?_⟩ + intro input + constructor + · exact (PCPSource.normalizedFormula_satisfiable_iff (source.reduce input)).trans + (source.correct input).symm + · intro rejected + exact normalized_clauseGap (source.reduce input) + (fun sat => rejected ((source.correct input).mpr sat)) + +end +end PerfectCompleteness.NormalizedSourceInput + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/SourcePhysicalTapeFiber.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/SourcePhysicalTapeFiber.lean new file mode 100644 index 0000000000000000000000000000000000000000..e4a5077b0762e644303f976a934c9eeaad5db0e8 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/SourcePhysicalTapeFiber.lean @@ -0,0 +1,41 @@ +import OAI.Computability.PerfectCompleteness.Repetition.CleanPhysicalReplayLaw + +namespace OAI + +section + +namespace PerfectCompleteness.SourcePhysicalTapeFiber + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +noncomputable section + +variable {branch : Nat → Nat} {root h t : Nat} + +theorem collapse_physicalTape_law (rows repeats : Nat → Nat) + (p : Path branch root (h + 1)) + (outside : Slots branch root → Fin t → MixedSupport.Slot) + (placeholder inside : Slots branch (h + 1) → Fin t → MixedSupport.Slot) : + ((FiniteDistribution.uniform + (CleanPhysicalReplay.Exterior rows repeats p outside placeholder)).product + (CutChildGrouping.rawLaw (C := WholeCutCalls.Index rows repeats p) inside rows)).pushforward + (fun x => WholeCutSampler.collapse rows repeats p (CutSlotAssembly.fill p outside inside) + (CleanPhysicalReplay.physicalTape rows repeats p outside placeholder inside x.1 x.2)) = + WholeArraySampler.tapeLaw rows repeats p (CutSlotAssembly.fill p outside inside) := by + rw [← FiniteDistribution.pushforward_comp + ((FiniteDistribution.uniform + (CleanPhysicalReplay.Exterior rows repeats p outside placeholder)).product + (CutChildGrouping.rawLaw (C := WholeCutCalls.Index rows repeats p) inside rows)) + (fun x => CleanPhysicalReplay.physicalTape rows repeats p outside placeholder inside x.1 x.2) + (WholeCutSampler.collapse rows repeats p (CutSlotAssembly.fill p outside inside)), + CleanPhysicalReplayLaw.physicalTape_law] + exact WholeCutSampler.collapse_tapeLaw rows repeats p (CutSlotAssembly.fill p outside inside) + +end +end PerfectCompleteness.SourcePhysicalTapeFiber + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/SourcePhysicalTapeLaw.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/SourcePhysicalTapeLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..c1c8014522a6de1e6572b502ae95e2c628959b17 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/SourcePhysicalTapeLaw.lean @@ -0,0 +1,238 @@ +import OAI.Computability.PerfectCompleteness.Construction.SourceChildKernelLemmas +import OAI.Computability.PerfectCompleteness.Construction.SourcePhysicalTaggedChildren +import OAI.Computability.PerfectCompleteness.Machines.SourcePhysicalTapeFiber +import OAI.Computability.PerfectCompleteness.Repetition.CleanPhysicalCanonicalQuery +import OAI.Computability.PerfectCompleteness.Sampling.SourceChildQuestionLaw +import OAI.Computability.PerfectCompleteness.Sampling.SourcePhysicalWholeLaw +import OAI.Computability.PerfectCompleteness.Sampling.TaggedKernelRebuildLaw + +namespace OAI + +section + +namespace PerfectCompleteness.SourcePhysicalTapeLaw + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +noncomputable section + +variable {branch : Nat → Nat} {root h t v m : Nat} [NeZero m] + (rows repeats : Nat → Nat) (p : Path branch root (h + 1)) + (outside : Slots branch root → Fin t → MixedSupport.Slot) + (placeholder : Slots branch (h + 1) → Fin t → MixedSupport.Slot) + (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch h) → Slots branch h) + +abbrev Tag := SourceChildKernel.Sources (m := m) (t := t) designated × + (Fin (branch h) → Bool) + +def insideSlots (tag : Tag (m := m) (t := t) designated) : + Slots branch (h + 1) → Fin t → MixedSupport.Slot := + SourcePhysicalTaggedChildren.slots clauses designated tag.1 tag.2 + +def nativeSlots (sources : SourceChildKernel.Sources (m := m) (t := t) designated) : + Slots branch root → Fin t → MixedSupport.Slot := + CutSlotAssembly.fill p outside (SourceChildKernel.parentLeftSlots clauses designated sources) + +def projectedSlots (tag : Tag (m := m) (t := t) designated) : + Slots branch root → Fin t → MixedSupport.Slot := + CutSlotAssembly.fill p outside (insideSlots clauses designated tag) + +def fullProjection (tag : Tag (m := m) (t := t) designated) : + ∀ s k, MixedSupport.Projection + (nativeSlots p outside clauses designated tag.1 s k) + (projectedSlots p outside clauses designated tag s k) := + CutProjectionAssembly.fillProjection p outside _ _ + (fun leaf k => SourceChildKernel.projection clauses designated leaf.1 + (tag.1 leaf.1) (tag.2 leaf.1) leaf.2 k) + +abbrev Sample := CleanPhysicalReplay.Sample (t := t) rows repeats p clauses designated + +abbrev Exterior := CleanPhysicalReplay.Exterior rows repeats p outside placeholder + +abbrev Record := Σ tag : Tag (m := m) (t := t) designated, + WholeArraySampler.Tape rows repeats p (projectedSlots p outside clauses designated tag) + +def rebuild (tag : Tag (m := m) (t := t) designated) + (external : Exterior rows repeats p outside placeholder) + (children : CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) + (insideSlots clauses designated tag) rows) : + WholeArraySampler.Tape rows repeats p (projectedSlots p outside clauses designated tag) := + WholeCutSampler.collapse rows repeats p (projectedSlots p outside clauses designated tag) + (CleanPhysicalReplay.physicalTape rows repeats p outside placeholder + (insideSlots clauses designated tag) external children) + +def sourceTag (sample : Sample (t := t) rows repeats p clauses designated) : + SourceChildKernel.Sources (m := m) (t := t) designated := + (SourceChildKernelJoint.groupEquiv rows clauses designated sample).1 + +def tag (sample : Sample (t := t) rows repeats p clauses designated) : + Tag (m := m) (t := t) designated := + (sourceTag rows repeats p clauses designated sample, + fun i => SourceChildKernel.rawProjected rows clauses designated i (sample i).2.2) + +def observe + (sample : Sample (t := t) rows repeats p clauses designated × + Exterior rows repeats p outside placeholder) : + Record rows repeats p outside clauses designated := + ⟨tag rows repeats p clauses designated sample.1, + rebuild rows repeats p outside placeholder clauses designated + (tag rows repeats p clauses designated sample.1) sample.2 + (SourceChildKernel.rightChildren rows clauses designated + (sourceTag rows repeats p clauses designated sample.1) (fun i => (sample.1 i).2.2))⟩ + +def observeFiber (sources : SourceChildKernel.Sources (m := m) (t := t) designated) + (sample : SourcePhysicalWholeLaw.Raw rows repeats p outside placeholder clauses designated) : + Σ flags : Fin (branch h) → Bool, + WholeArraySampler.Tape rows repeats p + (projectedSlots p outside clauses designated (sources, flags)) := + let decoded := SourcePhysicalTaggedChildren.observe rows clauses designated sources sample.2 + ⟨decoded.1, rebuild rows repeats p outside placeholder clauses designated + (sources, decoded.1) sample.1 decoded.2⟩ + +omit [NeZero m] in +theorem rebuild_law (tag : Tag (m := m) (t := t) designated) : + ((FiniteDistribution.uniform (Exterior rows repeats p outside placeholder)).product + (CutChildGrouping.rawLaw (C := WholeCutCalls.Index rows repeats p) + (insideSlots clauses designated tag) rows)).pushforward + (fun x => rebuild rows repeats p outside placeholder clauses designated tag x.1 x.2) = + WholeArraySampler.tapeLaw rows repeats p (projectedSlots p outside clauses designated tag) := + SourcePhysicalTapeFiber.collapse_physicalTape_law rows repeats p outside placeholder + (insideSlots clauses designated tag) + +omit [NeZero m] in +theorem observeFiber_law (flag : Fin (branch h) → FiniteDistribution Bool) + (sources : SourceChildKernel.Sources (m := m) (t := t) designated) : + (SourcePhysicalWholeLaw.rawLaw rows repeats p outside placeholder clauses designated + flag sources).pushforward + (observeFiber rows repeats p outside placeholder clauses designated sources) = + CompletionSoundness.sigmaLaw (FiniteProduct.law flag) (fun flags => + WholeArraySampler.tapeLaw rows repeats p + (projectedSlots p outside clauses designated (sources, flags))) := by + exact TaggedKernelRebuildLaw.fiber_rebuild_law + (FiniteProduct.law flag) + (FiniteDistribution.uniform (Exterior rows repeats p outside placeholder)) + (FiniteProduct.law (fun i => SourceChildKernel.kernel + (C := WholeCutCalls.Index rows repeats p) (t := t) rows clauses designated flag i (sources i))) + (fun flags => CutChildGrouping.rawLaw (C := WholeCutCalls.Index rows repeats p) + (insideSlots clauses designated (sources, flags)) rows) + (fun flags => WholeArraySampler.tapeLaw rows repeats p + (projectedSlots p outside clauses designated (sources, flags))) + (SourcePhysicalTaggedChildren.observe rows clauses designated sources) + (fun flags => rebuild rows repeats p outside placeholder clauses designated (sources, flags)) + (SourcePhysicalTaggedChildren.kernels_tagged rows clauses designated flag sources) + (fun flags => rebuild_law rows repeats p outside placeholder clauses designated (sources, flags)) + +def law (flag : Fin (branch h) → FiniteDistribution Bool) : + FiniteDistribution (Sample (t := t) rows repeats p clauses designated × + Exterior rows repeats p outside placeholder) := + (SourceChildKernel.originalLaw (C := WholeCutCalls.Index rows repeats p) + (t := t) rows clauses designated flag).product + (FiniteDistribution.uniform (Exterior rows repeats p outside placeholder)) + +def tagLaw (flag : Fin (branch h) → FiniteDistribution Bool) : + FiniteDistribution (Tag (m := m) (t := t) designated) := + (SourceChildQuestionLaw.sourceLaw m t designated).product (FiniteProduct.law flag) + +theorem observe_law (flag : Fin (branch h) → FiniteDistribution Bool) : + (law rows repeats p outside placeholder clauses designated flag).pushforward + (observe rows repeats p outside placeholder clauses designated) = + CompletionSoundness.sigmaLaw (tagLaw (m := m) (t := t) designated flag) (fun tag => + WholeArraySampler.tapeLaw rows repeats p (projectedSlots p outside clauses designated tag)) := by + let group := fun sample : Sample (t := t) rows repeats p clauses designated × + Exterior rows repeats p outside placeholder => + (SourceChildKernelJoint.groupEquiv rows clauses designated sample.1, sample.2) + let decode := SourcePhysicalTaggedChildren.observe + (C := WholeCutCalls.Index rows repeats p) (t := t) rows clauses designated + let rebuildTag := fun sample : + (SourceChildKernel.Sources (m := m) (t := t) designated × + SourceChildKernelJoint.RawTuple (C := WholeCutCalls.Index rows repeats p) + (t := t) rows clauses designated) × Exterior rows repeats p outside placeholder => + (⟨(sample.1.1, (decode sample.1.1 sample.1.2).1), + rebuild rows repeats p outside placeholder clauses designated + (sample.1.1, (decode sample.1.1 sample.1.2).1) sample.2 + (decode sample.1.1 sample.1.2).2⟩ : Record rows repeats p outside clauses designated) + have hgroup : (law rows repeats p outside placeholder clauses designated flag).pushforward group = + (CleanConditioning.kernelJoint (SourceChildQuestionLaw.sourceLaw m t designated) + (fun sources => FiniteProduct.law (fun i => SourceChildKernel.kernel + (C := WholeCutCalls.Index rows repeats p) (t := t) + rows clauses designated flag i (sources i)))).product + (FiniteDistribution.uniform (Exterior rows repeats p outside placeholder)) := by + change ((SourceChildKernel.originalLaw (C := WholeCutCalls.Index rows repeats p) + (t := t) rows clauses designated flag).product + (FiniteDistribution.uniform (Exterior rows repeats p outside placeholder))).pushforward + (fun x => (SourceChildKernelJoint.groupEquiv rows clauses designated x.1, id x.2)) = _ + rw [FiniteDistribution.product_pushforward, SourceChildKernelJoint.originalLaw_group, + FiniteDistribution.pushforward_id, SourceChildQuestionLaw.sourceLaw] + calc + _ = ((law rows repeats p outside placeholder clauses designated flag).pushforward group).pushforward + rebuildTag := by + rw [FiniteDistribution.pushforward_comp] + rfl + _ = _ := by + rw [hgroup] + exact TaggedKernelRebuildLaw.rebuild_law + (SourceChildQuestionLaw.sourceLaw m t designated) (FiniteProduct.law flag) + (FiniteDistribution.uniform (Exterior rows repeats p outside placeholder)) + (fun sources => FiniteProduct.law (fun i => SourceChildKernel.kernel + (C := WholeCutCalls.Index rows repeats p) (t := t) + rows clauses designated flag i (sources i))) + (fun sources flags => CutChildGrouping.rawLaw (C := WholeCutCalls.Index rows repeats p) + (insideSlots clauses designated (sources, flags)) rows) + (fun sources flags => WholeArraySampler.tapeLaw rows repeats p + (projectedSlots p outside clauses designated (sources, flags))) decode + (fun sources flags => rebuild rows repeats p outside placeholder clauses designated (sources, flags)) + (fun sources => SourcePhysicalTaggedChildren.kernels_tagged rows clauses designated flag sources) + (fun sources flags => rebuild_law rows repeats p outside placeholder clauses designated (sources, flags)) + +omit [NeZero m] in +theorem observe_tape + (sample : Sample (t := t) rows repeats p clauses designated × + Exterior rows repeats p outside placeholder) : + (observe rows repeats p outside placeholder clauses designated sample).2 = + WholeCutSampler.collapse rows repeats p + (CutSlotAssembly.fill p outside + (CleanPhysicalReplay.rightInside rows repeats p clauses designated sample.1)) + (CleanPhysicalReplay.rightTape rows repeats p outside placeholder clauses designated + sample.1 sample.2) := rfl + +omit [NeZero m] in +theorem observe_native_arrays + (sample : Sample (t := t) rows repeats p clauses designated × + Exterior rows repeats p outside placeholder) : + ChildBlockProjection.arraysPullback rows + (fullProjection p outside clauses designated (tag rows repeats p clauses designated sample.1)) + (WholeArraySampler.evaluate rows repeats p + (projectedSlots p outside clauses designated (tag rows repeats p clauses designated sample.1)) + (observe rows repeats p outside placeholder clauses designated sample).2) = + CleanPhysicalCanonicalQuery.leftArrays rows repeats p outside placeholder clauses designated + sample.1 sample.2 := + (CleanPhysicalCanonicalQuery.arrays_pullback rows repeats p outside placeholder clauses designated + sample.1 sample.2).symm + +omit [NeZero m] in +theorem observeFiber_native_arrays + (sources : SourceChildKernel.Sources (m := m) (t := t) designated) + (sample : SourcePhysicalWholeLaw.Raw rows repeats p outside placeholder clauses designated) : + ChildBlockProjection.arraysPullback rows + (fullProjection p outside clauses designated + (sources, (observeFiber rows repeats p outside placeholder clauses designated sources sample).1)) + (WholeArraySampler.evaluate rows repeats p + (projectedSlots p outside clauses designated + (sources, (observeFiber rows repeats p outside placeholder clauses designated sources sample).1)) + (observeFiber rows repeats p outside placeholder clauses designated sources sample).2) = + SourcePhysicalWholeLaw.observeLeft rows repeats p outside placeholder clauses designated sources sample := + (WholeCutGroupedProjection.physicalTape_pullback rows repeats p outside placeholder + (SourceChildKernel.parentLeftSlots clauses designated sources) + (SourceChildKernel.parentRightSlots rows clauses designated sources sample.2) + (SourceChildKernel.parentProjection rows clauses designated sources sample.2) sample.1 + (SourceChildKernel.rightChildren rows clauses designated sources sample.2)).symm + +end +end PerfectCompleteness.SourcePhysicalTapeLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/SourceTupleMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/SourceTupleMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..19ae0d5429130faeba0ffa3a5b8b08ef934c500f --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/SourceTupleMachine.lean @@ -0,0 +1,249 @@ +import OAI.Computability.PerfectCompleteness.Foundations.SourceTupleData +import OAI.Computability.UniqueGames.Machines.MachineCompositionLemmas + +namespace OAI + + +namespace PerfectCompleteness.SourceTupleMachine + + +open Turing UniqueGamesTheorem.Foundations Complexity Target +open MachineComposition +open SourceTupleData + +abbrev Signs := NormalizationReadMachine.Signs +abbrev Shape := CanonicalKeyShape.Shape +abbrev Alphabet {width : Nat} (_ : Tape width) := Bool +abbrev State (width : Nat) (A : Type) := SourceCoordinateMachine.State (A × (Fin width → Shape)) + +structure Data (width : Nat) where + prepared : Fin width → Bool + shapes : Fin width → Shape + signs : Signs + +def state {width : Nat} {A : Type} (ambient : A) (data : Data width) : State width A := + SourceClauseReaderMachine.clean (ambient, data.shapes) data.signs + +def initial {width : Nat} (shapes : Fin width → Shape) (signs : Signs) : Data width := + ⟨fun _ => false, shapes, signs⟩ + +def update {width : Nat} (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) (position : Fin width) + (data : Data width) : Data width where + prepared := Function.update data.prepared position true + shapes := Function.update data.shapes position + (SourceClauseReaderMachine.clauseShape (selectedClause formula indices position)) + signs := NormalizationReadMachine.clauseSigns (selectedClause formula indices position) + +def result {width : Nat} (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) : List (Fin width) → Data width → Data width + | [], data => data + | position :: positions, data => result formula indices positions (update formula indices position data) + +def cost {width : Nat} (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) (position : Fin width) : Nat := + SourceCoordinateMachine.steps formula (indices position) + +def steps {width : Nat} (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) (positions : List (Fin width)) : Nat := + (positions.map (cost formula indices)).sum + +theorem result_prepared {width : Nat} (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) (positions : List (Fin width)) + (data : Data width) (position : Fin width) : + (result formula indices positions data).prepared position = + if position ∈ positions then true else data.prepared position := by + induction positions generalizing data with + | nil => rfl + | cons first positions ih => + rw [result, ih] + by_cases here : position = first + · subst position + simp [update] + · simp [update, here] + +theorem result_shapes {width : Nat} (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) (positions : List (Fin width)) + (data : Data width) (position : Fin width) : + (result formula indices positions data).shapes position = + if position ∈ positions then + SourceClauseReaderMachine.clauseShape (selectedClause formula indices position) + else data.shapes position := by + induction positions generalizing data with + | nil => rfl + | cons first positions ih => + rw [result, ih] + by_cases here : position = first + · subst position + simp [update] + · simp [update, here] + +theorem result_finRange_prepared {width : Nat} (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) (data : Data width) : + (result formula indices (List.finRange width) data).prepared = fun _ => true := by + funext position + simp [result_prepared] + +theorem result_finRange_shapes {width : Nat} (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) (data : Data width) : + (result formula indices (List.finRange width) data).shapes = + fun position => SourceClauseReaderMachine.clauseShape + (selectedClause formula indices position) := by + funext position + simp [result_shapes] + +theorem cost_le {width : Nat} (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) (position : Fin width) : + cost formula indices position ≤ 60 * ((SourceOccurrenceEncoding.bits formula).length + 1) := by + have bound := SourceCoordinateMachine.steps_le formula (indices position) + have indexBound := (indices position).isLt + have countBound : formula.clauses.length ≤ (SourceOccurrenceEncoding.bits formula).length := by + rw [SourceOccurrenceEncoding.bits_eq] + simp only [List.length_append, encodeWord_length] + omega + unfold cost + omega + +theorem steps_le {width : Nat} (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) (positions : List (Fin width)) : + steps formula indices positions ≤ + positions.length * (60 * ((SourceOccurrenceEncoding.bits formula).length + 1)) := by + induction positions with + | nil => simp [steps] + | cons position positions ih => + have head := cost_le formula indices position + simp only [steps, List.map_cons, List.sum_cons, List.length_cons] at * + calc + _ ≤ 60 * ((SourceOccurrenceEncoding.bits formula).length + 1) + + positions.length * (60 * ((SourceOccurrenceEncoding.bits formula).length + 1)) := + Nat.add_le_add head ih + _ = _ := by rw [Nat.add_mul, Nat.one_mul, Nat.add_comm] + +abbrev LocalLabel {width : Nat} (_ : Fin width) := SourceCoordinateMachine.Label +abbrev Label {width : Nat} (positions : List (Fin width)) := + MachineFiniteSequence.Label LocalLabel positions + +def localMain {width : Nat} (_ : Fin width) : SourceCoordinateMachine.Label := + SourceCoordinateMachine.main + +def save {width : Nat} {A : Type} (position : Fin width) + (ambient : A × (Fin width → Shape)) (shape : Shape) : A × (Fin width → Shape) := + (ambient.1, Function.update ambient.2 position shape) + +variable {width : Nat} {Λ A : Type} + +def localInstruction (rejected : Option Λ) (position : Fin width) + (labels : SourceCoordinateMachine.Label → Λ) (done : Option Λ) : + SourceCoordinateMachine.Label → TM2.Stmt (Alphabet (width := width)) Λ (State width A) := + SourceCoordinateMachine.instruction (localTape position) labels done rejected (save position) + +def instruction (positions : List (Fin width)) (labels : Label positions → Λ) + (done rejected : Option Λ) : + Label positions → TM2.Stmt (Alphabet (width := width)) Λ (State width A) := + MachineFiniteSequence.instruction LocalLabel localMain + (localInstruction rejected) positions labels done + +def entry (positions : List (Fin width)) (labels : Label positions → Λ) (done : Option Λ) : + Option Λ := MachineFiniteSequence.entry LocalLabel localMain positions labels done + +theorem sequenceTrace (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) (positions : List (Fin width)) + (nodup : positions.Nodup) (labels : Label positions → Λ) (done rejected : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (width := width)) Λ (State width A)) + (atLabels : ∀ label, program (labels label) = instruction positions labels done rejected label) + (ambient : A) (data : Data width) + (fresh : ∀ position ∈ positions, data.prepared position = false) : + (advance (TM2.step program))^[steps formula indices positions] + (some ⟨entry positions labels done, state ambient data, + «stacks» formula indices data.prepared⟩) = + some ⟨done, state ambient (result formula indices positions data), + «stacks» formula indices (result formula indices positions data).prepared⟩ := by + induction positions generalizing data with + | nil => rfl + | cons position positions ih => + have distinct := List.nodup_cons.mp nodup + have headFresh := fresh position (by simp) + let tailEntry := entry positions (fun label => labels (.inr label)) done + have first := SourceCoordinateMachine.coordinateTrace (localTape position) + (localTape_injective position) (fun label => labels (.inl label)) tailEntry rejected + (save position) program (fun label => atLabels (.inl label)) + («stacks» formula indices data.prepared) (ambient, data.shapes) + formula (indices position) data.signs rfl rfl + (coordinate_initial_empty formula indices data.prepared position headFresh) + have outputTapes := resultTapes_eq formula indices data.prepared position headFresh + dsimp only [selectedClause] at outputTapes + rw [outputTapes] at first + change (advance (TM2.step program))^[cost formula indices position] + (some ⟨some (labels (.inl SourceCoordinateMachine.main)), state ambient data, + «stacks» formula indices data.prepared⟩) = + some ⟨tailEntry, state ambient (update formula indices position data), + «stacks» formula indices (update formula indices position data).prepared⟩ at first + have tailFresh : ∀ next ∈ positions, + (update formula indices position data).prepared next = false := by + intro next member + have different : next ≠ position := by + intro same + subst next + exact distinct.1 member + simpa only [update, Function.update_of_ne different] using + fresh next (List.mem_cons_of_mem position member) + have rest := ih distinct.2 (fun label => labels (.inr label)) + (fun label => atLabels (.inr label)) (update formula indices position data) tailFresh + rw [steps, List.map_cons, List.sum_cons, Nat.add_comm, Function.iterate_add_apply] + change (advance (TM2.step program))^[steps formula indices positions] + ((advance (TM2.step program))^[cost formula indices position] + (some ⟨some (labels (.inl SourceCoordinateMachine.main)), state ambient data, + «stacks» formula indices data.prepared⟩)) = _ + rw [first] + exact rest + +theorem tupleTrace (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) + (labels : Label (List.finRange width) → Λ) (done rejected : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (width := width)) Λ (State width A)) + (atLabels : ∀ label, program (labels label) = + instruction (List.finRange width) labels done rejected label) + (ambient : A) (shapes : Fin width → Shape) (signs : Signs) : + (advance (TM2.step program))^[steps formula indices (List.finRange width)] + (some ⟨entry (List.finRange width) labels done, state ambient (initial shapes signs), + «stacks» formula indices (fun _ => false)⟩) = + some ⟨done, + SourceClauseReaderMachine.clean + (ambient, fun position => SourceClauseReaderMachine.clauseShape + (selectedClause formula indices position)) + (result formula indices (List.finRange width) (initial shapes signs)).signs, + «stacks» formula indices (fun _ => true)⟩ := by + have traced := sequenceTrace formula indices (List.finRange width) (List.nodup_finRange width) + labels done rejected program atLabels ambient (initial shapes signs) (by intros; rfl) + simpa only [state, initial, result_finRange_prepared, result_finRange_shapes] using traced + +def tupleInTime (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) + (labels : Label (List.finRange width) → Λ) (done rejected : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (width := width)) Λ (State width A)) + (atLabels : ∀ label, program (labels label) = + instruction (List.finRange width) labels done rejected label) + (ambient : A) (shapes : Fin width → Shape) (signs : Signs) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨entry (List.finRange width) labels done, state ambient (initial shapes signs), + «stacks» formula indices (fun _ => false)⟩ + (some ⟨done, + SourceClauseReaderMachine.clean + (ambient, fun position => SourceClauseReaderMachine.clauseShape + (selectedClause formula indices position)) + (result formula indices (List.finRange width) (initial shapes signs)).signs, + «stacks» formula indices (fun _ => true)⟩) + (width * (60 * ((SourceOccurrenceEncoding.bits formula).length + 1))) where + steps := steps formula indices (List.finRange width) + evals_in_steps := tupleTrace formula indices labels done rejected program atLabels ambient shapes signs + steps_le_m := by + simpa only [List.length_finRange] using + (steps_le formula indices (List.finRange width)) + +theorem finiteState [Finite A] : Finite (State width A) := inferInstance + +theorem finiteLabels : Finite (Label (List.finRange width)) := inferInstance + +end PerfectCompleteness.SourceTupleMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/SourceTupleResetMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/SourceTupleResetMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..8c7f07e07493ff0a308ec38854b5f70e0c7f4c8f --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/SourceTupleResetMachine.lean @@ -0,0 +1,154 @@ +import OAI.Computability.PerfectCompleteness.Foundations.SourceTupleData +import OAI.Computability.UniqueGames.Machines.MachineDrainManyLemmas + +namespace OAI + + +namespace PerfectCompleteness.SourceTupleResetMachine + + +open Turing +open UniqueGamesTheorem.Foundations Complexity Target +open MachineComposition +open SourceTupleData + +abbrev Alphabet {width : Nat} (_ : Tape width) := Bool +abbrev State (σ : Type) := σ × Option Bool + +def chosen (width : Nat) : List (Tape width) := + (List.finRange width).flatMap (fun position => + [.variableName position 0, .variableName position 1, .variableName position 2]) + +@[simp] theorem chosen_length (width : Nat) : (chosen width).length = 3 * width := by + have lengthFor (positions : List (Fin width)) : + (positions.flatMap (fun position => + [Tape.variableName position 0, .variableName position 1, .variableName position 2])).length = + 3 * positions.length := by + induction positions with + | nil => rfl + | cons position positions ih => + simp only [List.flatMap_cons, List.length_append, List.length_cons, + List.length_nil, ih] + omega + simpa only [chosen, List.length_finRange] using lengthFor (List.finRange width) + +@[simp] theorem table_not_mem_chosen (width : Nat) : Tape.table ∉ chosen width := by + simp [chosen] + +@[simp] theorem digit_not_mem_chosen {width : Nat} (position : Fin width) : + Tape.digit position ∉ chosen width := by + simp [chosen] + +@[simp] theorem work_not_mem_chosen {width : Nat} (slot : Fin 5) : + Tape.work slot ∉ chosen width := by + simp [chosen] + +@[simp] theorem variable_mem_chosen {width : Nat} (position : Fin width) (slot : Fin 3) : + Tape.variableName position slot ∈ chosen width := by + apply List.mem_flatMap.mpr + refine ⟨position, by simp, ?_⟩ + fin_cases slot <;> simp + +theorem finalTapes_eq {width : Nat} (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) : + MachineDrainMany.finalTapes (chosen width) («stacks» formula indices (fun _ => true)) = + «stacks» formula indices (fun _ => false) := by + funext key + rw [MachineDrainMany.finalTapes_apply] + cases key with + | table => simp [«stacks»] + | digit position => simp [«stacks»] + | work slot => simp [«stacks»] + | variableName position slot => simp [«stacks»] + +theorem variable_count_le_table (formula : Formula) : + formula.variables ≤ (SourceOccurrenceEncoding.bits formula).length := by + rw [SourceOccurrenceEncoding.bits_eq] + simp only [List.length_append, encodeWord_length] + omega + +theorem clause_count_le_table (formula : Formula) : + formula.clauses.length ≤ (SourceOccurrenceEncoding.bits formula).length := by + rw [SourceOccurrenceEncoding.bits_eq] + simp only [List.length_append, encodeWord_length] + omega + +theorem stack_length_le {width : Nat} (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) (key : Tape width) : + («stacks» formula indices (fun _ => true) key).length ≤ + (SourceOccurrenceEncoding.bits formula).length := by + cases key with + | table => exact Nat.le_refl _ + | digit position => + have bounded := (indices position).isLt + have countBound := clause_count_le_table formula + simp only [«stacks», List.length_replicate] + omega + | work slot => simp [«stacks»] + | variableName position slot => + have bounded := (selectedClause formula indices position)[slot].variableIndex.isLt + have countBound := variable_count_le_table formula + have bound : (selectedClause formula indices position)[slot].variableIndex.val ≤ + (SourceOccurrenceEncoding.bits formula).length := by omega + simpa [«stacks», NormalizationReadMachine.clauseCounters] using bound + +def steps {width : Nat} (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) : Nat := + MachineDrainMany.steps (chosen width) («stacks» formula indices (fun _ => true)) + +theorem steps_le {width : Nat} (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) : + steps formula indices ≤ 3 * width * ((SourceOccurrenceEncoding.bits formula).length + 1) := by + have bound := MachineDrainMany.steps_le_uniform (chosen width) + («stacks» formula indices (fun _ => true)) (SourceOccurrenceEncoding.bits formula).length + (stack_length_le formula indices) + simpa only [steps, chosen_length] using bound + +abbrev Label (width : Nat) := MachineDrainMany.Label (chosen width) + +variable {width : Nat} {Λ σ : Type} + +def instruction (labels : Label width → Λ) (done : Option Λ) : + Label width → TM2.Stmt (Alphabet (width := width)) Λ (State σ) := + MachineDrainMany.instruction (chosen width) labels done + +def entry (labels : Label width → Λ) (done : Option Λ) : Option Λ := + MachineDrainMany.entry (chosen width) labels done + +theorem resetTrace (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) + (labels : Label width → Λ) (done : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (width := width)) Λ (State σ)) + (atLabels : ∀ label, program (labels label) = instruction labels done label) + (ambient : σ) : + (advance (TM2.step program))^[steps formula indices] + (some ⟨entry labels done, (ambient, none), «stacks» formula indices (fun _ => true)⟩) = + some ⟨done, (ambient, none), «stacks» formula indices (fun _ => false)⟩ := by + have h := MachineDrainMany.trace (chosen width) labels done program atLabels + («stacks» formula indices (fun _ => true)) ambient none + rw [MachineDrainMany.finalRegister_none, finalTapes_eq] at h + exact h + +def resetInTime (formula : Formula) + (indices : Fin width → Fin formula.clauses.length) + (labels : Label width → Λ) (done : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (width := width)) Λ (State σ)) + (atLabels : ∀ label, program (labels label) = instruction labels done label) + (ambient : σ) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨entry labels done, (ambient, none), «stacks» formula indices (fun _ => true)⟩ + (some ⟨done, (ambient, none), «stacks» formula indices (fun _ => false)⟩) + (3 * width * ((SourceOccurrenceEncoding.bits formula).length + 1)) where + steps := steps formula indices + evals_in_steps := resetTrace formula indices labels done program atLabels ambient + steps_le_m := steps_le formula indices + +theorem finiteState [Finite σ] : Finite (State σ) := inferInstance + +theorem finiteAlphabet (key : Tape width) : Finite (Alphabet key) := by + change Finite Bool + infer_instance + +end PerfectCompleteness.SourceTupleResetMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/StatementCircuit.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/StatementCircuit.lean new file mode 100644 index 0000000000000000000000000000000000000000..bd139eaec6b63ad69b8fe2b4a7434dff903797fe --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/StatementCircuit.lean @@ -0,0 +1,676 @@ +import Mathlib.Data.Fintype.Sigma +import Mathlib.Data.Fintype.Sum +import OAI.Computability.PerfectCompleteness.Machines.BoundedExecution +import OAI.Computability.PerfectCompleteness.Machines.CircuitLemmas +import OAI.Computability.PerfectCompleteness.Machines.ProducerBootstrapLemmas + +namespace OAI + +section + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.StatementCircuit + +open Turing +open StackEncoding BoundedExecution + +inductive Expr (ι : Type*) where + | input (index : ι) + | const (value : Bool) + | not (arg : Expr ι) + | and (left right : Expr ι) + | or (left right : Expr ι) + +namespace Expr + +variable {ι : Type*} + +def eval (input : ι → Bool) : Expr ι → Bool + | .input i => input i + | .const b => b + | .not e => !(eval input e) + | .and e f => eval input e && eval input f + | .or e f => eval input e || eval input f + +theorem eval_congr (e : Expr ι) (u v : ι → Bool) (h : ∀ i, u i = v i) : + e.eval u = e.eval v := by + have : u = v := funext h + rw [this] + +def rename {κ : Type*} (f : ι → κ) : Expr ι → Expr κ + | .input i => .input (f i) + | .const b => .const b + | .not e => .not (e.rename f) + | .and e g => .and (e.rename f) (g.rename f) + | .or e g => .or (e.rename f) (g.rename f) + +@[simp] theorem eval_rename {κ : Type*} (f : ι → κ) (e : Expr ι) (input : κ → Bool) : + (e.rename f).eval input = e.eval (fun i => input (f i)) := by + induction e <;> simp_all [rename, eval] + +def size : Expr ι → Nat + | .input _ | .const _ => 1 + | .not e => e.size + 1 + | .and e f | .or e f => e.size + f.size + 1 + +theorem size_pos (e : Expr ι) : 0 < e.size := by + cases e <;> simp [size] + +@[simp] theorem size_rename {κ : Type*} (f : ι → κ) (e : Expr ι) : + (e.rename f).size = e.size := by + induction e <;> simp_all [rename, size] + +def root (start : Nat) (e : Expr ι) : Nat := start + e.size - 1 + +theorem root_lt (start : Nat) (e : Expr ι) : e.root start < start + e.size := by + have := e.size_pos + unfold root + omega + +@[simp] theorem root_not (start : Nat) (e : Expr ι) : + (Expr.not e).root start = start + e.size := by + simp only [root, size] + omega + +@[simp] theorem root_and (start : Nat) (e f : Expr ι) : + (Expr.and e f).root start = start + (e.size + f.size) := by + simp only [root, size] + omega + +@[simp] theorem root_or (start : Nat) (e f : Expr ι) : + (Expr.or e f).root start = start + (e.size + f.size) := by + simp only [root, size] + omega + +def gates (wire : ι → Nat) (start : Nat) : Expr ι → List Gate + | .input i => [.or (wire i) (wire i)] + | .const b => [.const b] + | .not e => e.gates wire start ++ [.not (e.root start)] + | .and e f => e.gates wire start ++ f.gates wire (start + e.size) ++ + [.and (e.root start) (f.root (start + e.size))] + | .or e f => e.gates wire start ++ f.gates wire (start + e.size) ++ + [.or (e.root start) (f.root (start + e.size))] + +@[simp] theorem gates_length (e : Expr ι) (wire : ι → Nat) (start : Nat) : + (e.gates wire start).length = e.size := by + induction e generalizing start <;> simp_all [gates, size, Nat.add_assoc] + +private theorem ordered_singleton (start : Nat) (g : Gate) (h : g.Bounded start) : + Ordered start [g] := by + exact (ordered_cons start g []).mpr ⟨h, ordered_nil _⟩ + +theorem gates_ordered (e : Expr ι) (wire : ι → Nat) (start : Nat) + (hw : ∀ i, wire i < start) : Ordered start (e.gates wire start) := by + induction e generalizing start with + | input i => exact ordered_singleton start _ ⟨hw i, hw i⟩ + | const b => exact ordered_singleton start _ trivial + | not e ih => + apply (ih start hw).append + simpa only [gates_length] using + ordered_singleton (start + e.size) (.not (e.root start)) (e.root_lt start) + | and e f ihe ihf => + have hf := ihf (start + e.size) (fun i => lt_of_lt_of_le (hw i) (by omega)) + have hp : Ordered start (e.gates wire start ++ f.gates wire (start + e.size)) := + (ihe start hw).append (by simpa only [gates_length] using hf) + apply hp.append + simp only [List.length_append, gates_length] + apply ordered_singleton + exact ⟨lt_of_lt_of_le (e.root_lt start) (by omega), by + simpa only [Nat.add_assoc] using f.root_lt (start + e.size)⟩ + | or e f ihe ihf => + have hf := ihf (start + e.size) (fun i => lt_of_lt_of_le (hw i) (by omega)) + have hp : Ordered start (e.gates wire start ++ f.gates wire (start + e.size)) := + (ihe start hw).append (by simpa only [gates_length] using hf) + apply hp.append + simp only [List.length_append, gates_length] + apply ordered_singleton + exact ⟨lt_of_lt_of_le (e.root_lt start) (by omega), by + simpa only [Nat.add_assoc] using f.root_lt (start + e.size)⟩ + +private theorem consistent_singleton (start : Nat) (g : Gate) (A : Nat → Bool) + (h : Consistent start [g] A) : A start = g.eval A := by + exact ((consistent_cons start g [] A).mp h).1 + +theorem eval_of_consistent (e : Expr ι) (wire : ι → Nat) (start : Nat) + (A : Nat → Bool) (h : Consistent start (e.gates wire start) A) : + A (e.root start) = e.eval (fun i => A (wire i)) := by + induction e generalizing start with + | input i => + simpa [gates, root, size, Gate.eval, eval] using + consistent_singleton start (.or (wire i) (wire i)) A h + | const b => + simpa [gates, root, size, Gate.eval, eval] using + consistent_singleton start (.const b) A h + | not e ih => + obtain ⟨he, hg⟩ := (consistent_append start _ _ A).mp h + simp only [gates_length] at hg + have hg' := consistent_singleton _ _ _ hg + simpa only [root_not, Gate.eval, eval, ih start he] using hg' + | and e f ihe ihf => + obtain ⟨hef, hg⟩ := (consistent_append start _ _ A).mp h + obtain ⟨he, hf⟩ := (consistent_append start _ _ A).mp hef + simp only [gates_length] at hf + simp only [List.length_append, gates_length] at hg + have hg' := consistent_singleton _ _ _ hg + have he' := ihe start he + have hf' := ihf (start + e.size) hf + simpa only [root_and, Gate.eval, eval, + he', hf'] using hg' + | or e f ihe ihf => + obtain ⟨hef, hg⟩ := (consistent_append start _ _ A).mp h + obtain ⟨he, hf⟩ := (consistent_append start _ _ A).mp hef + simp only [gates_length] at hf + simp only [List.length_append, gates_length] at hg + have hg' := consistent_singleton _ _ _ hg + have he' := ihe start he + have hf' := ihf (start + e.size) hf + simpa only [root_or, Gate.eval, eval, + he', hf'] using hg' + +def circuit {n : Nat} (wire : ι → Fin n) (e : Expr ι) : Circuit where + inputs := n + gates := e.gates (fun i => (wire i).val) n + ordered := e.gates_ordered _ _ (fun i => (wire i).isLt) + output := ⟨e.root n, by simpa only [gates_length] using e.root_lt n⟩ + +theorem circuit_eval {n : Nat} (wire : ι → Fin n) (e : Expr ι) (input : Fin n → Bool) : + (e.circuit wire).eval input = e.eval (fun i => input (wire i)) := by + have h := e.eval_of_consistent (fun i => (wire i).val) n + ((e.circuit wire).evalWires input) ((e.circuit wire).evalWires_consistent input) + change (e.circuit wire).eval input = _ at h + rw [h] + apply eval_congr + intro i + exact (e.circuit wire).evalWires_input input (wire i) + +def mux (condition yes no : Expr ι) : Expr ι := + .or (.and condition yes) (.and (.not condition) no) + +@[simp] theorem eval_mux (input : ι → Bool) (c x y : Expr ι) : + (mux c x y).eval input = if c.eval input then x.eval input else y.eval input := by + cases hc : c.eval input <;> simp [mux, eval, hc] + +def disjoin : List (Expr ι) → Expr ι + | [] => .const false + | e :: rest => .or e (disjoin rest) + +theorem eval_disjoin_true (input : ι → Bool) (es : List (Expr ι)) : + (disjoin es).eval input = true ↔ ∃ e ∈ es, e.eval input = true := by + induction es with + | nil => simp [disjoin, eval] + | cons e es ih => simp [disjoin, eval, ih] + +theorem size_disjoin_le (es : List (Expr ι)) (C : Nat) + (h : ∀ e ∈ es, e.size ≤ C) : (disjoin es).size ≤ es.length * (C + 1) + 1 := by + induction es generalizing C with + | nil => simp [disjoin, size] + | cons e es ih => + have he := h e (by simp) + have ht := ih C (fun f hf => h f (by simp [hf])) + simp only [disjoin, size, List.length_cons, Nat.succ_mul] + omega + +end Expr + +private theorem bool_ext {a b : Bool} (h : a = true ↔ b = true) : a = b := by + cases a <;> cases b <;> simp_all + +noncomputable def table {ι A B : Type*} [Fintype A] [DecidableEq B] + (f : A → B) (x : A → Expr ι) (b : B) : Expr ι := + Expr.disjoin (Finset.univ.toList.map (fun a => .and (x a) (.const (decide (f a = b))))) + +theorem eval_table {ι A B : Type*} [Fintype A] [DecidableEq A] [DecidableEq B] + (input : ι → Bool) (f : A → B) (x : A → Expr ι) (a : A) + (hx : ∀ z, (x z).eval input = decide (a = z)) (b : B) : + (table f x b).eval input = decide (f a = b) := by + apply bool_ext + simp only [table, Expr.eval_disjoin_true, List.mem_map] + constructor + · rintro ⟨_, ⟨z, _, rfl⟩, hz⟩ + simp only [Expr.eval, hx, Bool.and_eq_true, decide_eq_true_eq] at hz + rcases hz with ⟨rfl, hz⟩ + exact decide_eq_true hz + · intro h + refine ⟨.and (x a) (.const (decide (f a = b))), ?_, ?_⟩ + · exact ⟨a, by simp, rfl⟩ + · simp [Expr.eval, hx, h] + +noncomputable def table₂ {ι A B C : Type*} [Fintype A] [Fintype B] [DecidableEq C] + (f : A → B → C) (x : A → Expr ι) (y : B → Expr ι) (c : C) : Expr ι := + table (fun p : A × B => f p.1 p.2) (fun p => .and (x p.1) (y p.2)) c + +theorem eval_table₂ {ι A B C : Type*} [Fintype A] [Fintype B] + [DecidableEq A] [DecidableEq B] [DecidableEq C] + (input : ι → Bool) (f : A → B → C) (x : A → Expr ι) (y : B → Expr ι) + (a : A) (b : B) (hx : ∀ z, (x z).eval input = decide (a = z)) + (hy : ∀ z, (y z).eval input = decide (b = z)) (c : C) : + (table₂ f x y c).eval input = decide (f a b = c) := by + apply eval_table input _ _ (a, b) + rintro ⟨za, zb⟩ + simp [Expr.eval, hx, hy, Prod.mk.injEq] + +theorem size_table_le {ι A B : Type*} [Fintype A] [DecidableEq B] + (f : A → B) (x : A → Expr ι) (b : B) (C : Nat) (h : ∀ a, (x a).size ≤ C) : + (table f x b).size ≤ Fintype.card A * (C + 3) + 1 := by + unfold table + have hb : ∀ e ∈ Finset.univ.toList.map (fun a => Expr.and (x a) + (.const (decide (f a = b)))), e.size ≤ C + 2 := by + intro e he + obtain ⟨a, _, rfl⟩ := List.mem_map.mp he + simpa only [Expr.size, Nat.add_assoc] using Nat.add_le_add_right (h a) 2 + simpa [Nat.add_assoc] using Expr.size_disjoin_le _ (C + 2) hb + +theorem size_table₂_le {ι A B D : Type*} [Fintype A] [Fintype B] [DecidableEq D] + (f : A → B → D) (x : A → Expr ι) (y : B → Expr ι) (d : D) (C : Nat) + (hx : ∀ a, (x a).size ≤ C) (hy : ∀ b, (y b).size ≤ C) : + (table₂ f x y d).size ≤ (Fintype.card A * Fintype.card B) * (2 * C + 4) + 1 := by + have h := size_table_le (fun p : A × B => f p.1 p.2) + (fun p => Expr.and (x p.1) (y p.2)) d (2 * C + 1) (fun p => by + have := hx p.1 + have := hy p.2 + simp only [Expr.size] + omega) + simpa only [table₂, Fintype.card_prod, Nat.add_assoc] using h + +section Statements + +variable {K : Type} {Γ : K → Type} {Λ σ ι : Type} +variable [DecidableEq K] [Fintype σ] [DecidableEq σ] +variable [∀ k, Fintype (Γ k)] [∀ k, DecidableEq (Γ k)] [DecidableEq Λ] + +structure DataBits (ι : Type) (Γ : K → Type) (σ : Type) (S : Nat) where + state : σ → Expr ι + cells : ∀ k, Fin S → Option (Γ k) → Expr ι + +structure ResultBits (ι : Type) (Γ : K → Type) (Λ σ : Type) (S : Nat) + extends DataBits ι Γ σ S where + label : Option Λ → Expr ι + +def DataBits.Realizes {S : Nat} (bits : DataBits ι Γ σ S) (input : ι → Bool) + (state : σ) (tapes : ∀ k, List (Γ k)) : Prop := + (∀ v, (bits.state v).eval input = decide (state = v)) ∧ + ∀ k i a, (bits.cells k i a).eval input = decide (encode S (tapes k) i = a) + +def ResultBits.Realizes {S : Nat} (bits : ResultBits ι Γ Λ σ S) (input : ι → Bool) + (cfg : TM2.Cfg Γ Λ σ) : Prop := + bits.toDataBits.Realizes input cfg.var cfg.stk ∧ + ∀ label, (bits.label label).eval input = decide (cfg.l = label) + +def readBits {A : Type} [DecidableEq A] {S : Nat} + (cells : Fin S → Option A → Expr ι) (n : Nat) (a : Option A) : Expr ι := + if h : n < S then cells ⟨n, h⟩ a else .const (decide ((none : Option A) = a)) + +theorem eval_readBits {A : Type} [DecidableEq A] {S : Nat} + (input : ι → Bool) (bits : Fin S → Option A → Expr ι) (xs : List A) + (hlen : xs.length ≤ S) + (hbits : ∀ i a, (bits i a).eval input = decide (encode S xs i = a)) + (n : Nat) (a : Option A) : + (readBits bits n a).eval input = decide (xs[n]? = a) := by + by_cases hn : n < S + · simp only [readBits, dite_eq_left hn] + exact hbits ⟨n, hn⟩ a + · have hx : xs[n]? = none := List.getElem?_eq_none (by omega) + simp only [readBits, dite_eq_right hn, Expr.eval, hx] + +noncomputable def pushBits {S : Nat} (bits : DataBits ι Γ σ S) (k : K) + (f : σ → Γ k) : DataBits ι Γ σ S where + state := bits.state + cells := Function.update bits.cells k (fun i a => + if h : i.val = 0 then table (fun v => some (f v)) bits.state a + else bits.cells k ⟨i.val - 1, by omega⟩ a) + +noncomputable def peekBits {S : Nat} (bits : DataBits ι Γ σ S) (k : K) + (f : σ → Option (Γ k) → σ) : DataBits ι Γ σ S where + state := table₂ f bits.state (readBits (bits.cells k) 0) + cells := bits.cells + +noncomputable def popBits {S : Nat} (bits : DataBits ι Γ σ S) (k : K) + (f : σ → Option (Γ k) → σ) : DataBits ι Γ σ S where + state := table₂ f bits.state (readBits (bits.cells k) 0) + cells := Function.update bits.cells k (fun i a => readBits (bits.cells k) (i.val + 1) a) + +noncomputable def loadBits {S : Nat} (bits : DataBits ι Γ σ S) + (f : σ → σ) : DataBits ι Γ σ S where + state := table f bits.state + cells := bits.cells + +def muxResult {S : Nat} (condition : Expr ι) (yes no : ResultBits ι Γ Λ σ S) : + ResultBits ι Γ Λ σ S where + state := fun v => .mux condition (yes.state v) (no.state v) + cells := fun k i a => .mux condition (yes.cells k i a) (no.cells k i a) + label := fun l => .mux condition (yes.label l) (no.label l) + +omit [(k : K) → Fintype (Γ k)] in +theorem realizes_pushBits {S : Nat} (bits : DataBits ι Γ σ S) (input : ι → Bool) + (v : σ) (tapes : ∀ k, List (Γ k)) (h : bits.Realizes input v tapes) + (k : K) (f : σ → Γ k) : + (pushBits bits k f).Realizes input v (Function.update tapes k (f v :: tapes k)) := by + refine ⟨h.1, ?_⟩ + intro j i a + by_cases hj : j = k + · subst j + simp only [pushBits, Function.update_self] + by_cases hi : i.val = 0 + · rw [dite_eq_left hi, eval_table input _ _ v h.1] + simp [encode, hi] + · rw [dite_eq_right hi, h.2] + apply bool_ext + simp [encode, List.getElem?_cons, hi] + exact ⟨of_decide_eq_true, decide_eq_true⟩ + · simpa only [pushBits, Function.update_of_ne hj] using h.2 j i a + +omit [DecidableEq K] in +theorem realizes_peekBits {S : Nat} (bits : DataBits ι Γ σ S) (input : ι → Bool) + (v : σ) (tapes : ∀ k, List (Γ k)) (h : bits.Realizes input v tapes) + (k : K) (f : σ → Option (Γ k) → σ) (hlen : (tapes k).length ≤ S) : + (peekBits bits k f).Realizes input (f v (tapes k).head?) tapes := by + refine ⟨?_, h.2⟩ + intro w + apply eval_table₂ input _ _ _ v (tapes k).head? h.1 + intro a + simpa [List.head?_eq_getElem?] using + eval_readBits input (bits.cells k) (tapes k) hlen (h.2 k) 0 a + +theorem realizes_popBits {S : Nat} (bits : DataBits ι Γ σ S) (input : ι → Bool) + (v : σ) (tapes : ∀ k, List (Γ k)) (h : bits.Realizes input v tapes) + (k : K) (f : σ → Option (Γ k) → σ) (hlen : (tapes k).length ≤ S) : + (popBits bits k f).Realizes input (f v (tapes k).head?) + (Function.update tapes k (tapes k).tail) := by + refine ⟨(realizes_peekBits bits input v tapes h k f hlen).1, ?_⟩ + intro j i a + by_cases hj : j = k + · subst j + simp only [popBits, Function.update_self] + rw [eval_readBits input (bits.cells k) (tapes k) hlen (h.2 k)] + simp [encode, List.getElem?_tail] + · simpa only [popBits, Function.update_of_ne hj] using h.2 j i a + +omit [DecidableEq K] [(k : K) → Fintype (Γ k)] in +theorem realizes_loadBits {S : Nat} (bits : DataBits ι Γ σ S) (input : ι → Bool) + (v : σ) (tapes : ∀ k, List (Γ k)) (h : bits.Realizes input v tapes) + (f : σ → σ) : (loadBits bits f).Realizes input (f v) tapes := by + exact ⟨fun w => eval_table input f bits.state v h.1 w, h.2⟩ + +omit [DecidableEq K] [Fintype σ] [(k : K) → Fintype (Γ k)] in +theorem realizes_muxResult {S : Nat} (input : ι → Bool) (condition : Expr ι) + (yes no : ResultBits ι Γ Λ σ S) (decision : Bool) (hc : condition.eval input = decision) + (yesCfg noCfg : TM2.Cfg Γ Λ σ) + (hy : decision = true → yes.Realizes input yesCfg) + (hn : decision = false → no.Realizes input noCfg) : + (muxResult condition yes no).Realizes input (if decision then yesCfg else noCfg) := by + cases decision with + | false => + rcases hn rfl with ⟨⟨hv, hs⟩, hl⟩ + refine ⟨⟨?_, ?_⟩, ?_⟩ + · intro v; simpa only [muxResult, Expr.eval_mux, hc, Bool.false_eq_true, ite_false, ite_true] using hv v + · intro k i a; simpa only [muxResult, Expr.eval_mux, hc, Bool.false_eq_true, ite_false, ite_true] using hs k i a + · intro l; simpa only [muxResult, Expr.eval_mux, hc, Bool.false_eq_true, ite_false, ite_true] using hl l + | true => + rcases hy rfl with ⟨⟨hv, hs⟩, hl⟩ + refine ⟨⟨?_, ?_⟩, ?_⟩ + · intro v; simpa only [muxResult, Expr.eval_mux, hc, Bool.false_eq_true, ite_false, ite_true] using hv v + · intro k i a; simpa only [muxResult, Expr.eval_mux, hc, Bool.false_eq_true, ite_false, ite_true] using hs k i a + · intro l; simpa only [muxResult, Expr.eval_mux, hc, Bool.false_eq_true, ite_false, ite_true] using hl l + +noncomputable def compileAux {S : Nat} : + TM2.Stmt Γ Λ σ → DataBits ι Γ σ S → ResultBits ι Γ Λ σ S + | .push k f next, bits => compileAux next (pushBits bits k f) + | .peek k f next, bits => compileAux next (peekBits bits k f) + | .pop k f next, bits => compileAux next (popBits bits k f) + | .load f next, bits => compileAux next (loadBits bits f) + | .branch guard yes no, bits => + muxResult (table guard bits.state true) (compileAux yes bits) (compileAux no bits) + | .goto label, bits => + { toDataBits := bits, label := table (fun v => some (label v)) bits.state } + | .halt, bits => + { toDataBits := bits, label := fun l => .const (decide ((none : Option Λ) = l)) } + +theorem compileAux_correct {S : Nat} (stmt : TM2.Stmt Γ Λ σ) + (bits : DataBits ι Γ σ S) (input : ι → Bool) (v : σ) (tapes : ∀ k, List (Γ k)) + (safe : StatementSafe S stmt v tapes) (h : bits.Realizes input v tapes) : + (compileAux stmt bits).Realizes input (TM2.stepAux stmt v tapes) := by + induction stmt generalizing bits v tapes with + | push k f next ih => + exact ih _ _ _ safe.2.2 (realizes_pushBits bits input v tapes h k f) + | peek k f next ih => + exact ih _ _ _ safe.2 (realizes_peekBits bits input v tapes h k f (safe.1 k)) + | pop k f next ih => + exact ih _ _ _ safe.2 (realizes_popBits bits input v tapes h k f (safe.1 k)) + | load f next ih => + exact ih _ _ _ safe.2 (realizes_loadBits bits input v tapes h f) + | branch guard yes no ihy ihn => + have hc : (table guard bits.state true).eval input = guard v := by + rw [eval_table input guard bits.state v h.1] + cases guard v <;> rfl + have hy : guard v = true → (compileAux yes bits).Realizes input (TM2.stepAux yes v tapes) := by + intro hg + apply ihy bits v tapes _ h + simpa [StatementSafe, hg] using safe.2 + have hn : guard v = false → (compileAux no bits).Realizes input (TM2.stepAux no v tapes) := by + intro hg + apply ihn bits v tapes _ h + simpa [StatementSafe, hg] using safe.2 + have hm := realizes_muxResult input _ _ _ (guard v) hc _ _ hy hn + cases hg : guard v <;> simpa [compileAux, TM2.stepAux, hg] using hm + | goto label => + exact ⟨h, fun l => eval_table input _ bits.state v h.1 l⟩ + | halt => exact ⟨h, fun _ => rfl⟩ + +end Statements + +section Encoding + +variable {K : Type} {Γ : K → Type} {Λ σ : Type} +variable [DecidableEq K] [Fintype σ] [DecidableEq σ] +variable [∀ k, Fintype (Γ k)] [∀ k, DecidableEq (Γ k)] [DecidableEq Λ] + +abbrev InputBit (Γ : K → Type) (σ : Type) (S : Nat) := + σ ⊕ (Σ k, Fin S × Option (Γ k)) + +abbrev ConfigBit (Γ : K → Type) (Λ σ : Type) (S : Nat) := + Option Λ ⊕ InputBit Γ σ S + +def inputBits (S : Nat) : DataBits (InputBit Γ σ S) Γ σ S where + state := fun v => .input (.inl v) + cells := fun k i a => .input (.inr ⟨k, i, a⟩) + +def inputEncoding (S : Nat) (v : σ) (tapes : ∀ k, List (Γ k)) : InputBit Γ σ S → Bool + | .inl w => decide (v = w) + | .inr ⟨k, i, a⟩ => decide (encode S (tapes k) i = a) + +def configEncoding (S : Nat) (cfg : TM2.Cfg Γ Λ σ) : ConfigBit Γ Λ σ S → Bool + | .inl label => decide (cfg.l = label) + | .inr i => inputEncoding S cfg.var cfg.stk i + +def resultExpr {ι : Type} {S : Nat} (bits : ResultBits ι Γ Λ σ S) : + ConfigBit Γ Λ σ S → Expr ι + | .inl label => bits.label label + | .inr (.inl v) => bits.state v + | .inr (.inr ⟨k, i, a⟩) => bits.cells k i a + +omit [DecidableEq K] [Fintype σ] [(k : K) → Fintype (Γ k)] in +theorem inputBits_realizes (S : Nat) (v : σ) (tapes : ∀ k, List (Γ k)) : + (inputBits S).Realizes (inputEncoding S v tapes) v tapes := by + exact ⟨fun _ => rfl, fun _ _ _ => rfl⟩ + +omit [DecidableEq K] [Fintype σ] [(k : K) → Fintype (Γ k)] in +theorem resultExpr_eval {ι : Type} {S : Nat} (bits : ResultBits ι Γ Λ σ S) + (input : ι → Bool) (cfg : TM2.Cfg Γ Λ σ) (h : bits.Realizes input cfg) + (bit : ConfigBit Γ Λ σ S) : + (resultExpr bits bit).eval input = configEncoding S cfg bit := by + rcases bit with label | (v | ⟨k, i, a⟩) + · exact h.2 label + · exact h.1.1 v + · exact h.1.2 k i a + +noncomputable def transitionExpr (S : Nat) (stmt : TM2.Stmt Γ Λ σ) : + ConfigBit Γ Λ σ S → Expr (InputBit Γ σ S) := + resultExpr (compileAux stmt (inputBits S)) + +theorem transitionExpr_eval (S : Nat) (stmt : TM2.Stmt Γ Λ σ) + (v : σ) (tapes : ∀ k, List (Γ k)) (safe : StatementSafe S stmt v tapes) + (bit : ConfigBit Γ Λ σ S) : + (transitionExpr S stmt bit).eval (inputEncoding S v tapes) = + configEncoding S (TM2.stepAux stmt v tapes) bit := + resultExpr_eval _ _ _ (compileAux_correct stmt _ _ v tapes safe + (inputBits_realizes S v tapes)) bit + +noncomputable def outputCircuit [Fintype K] (S : Nat) (stmt : TM2.Stmt Γ Λ σ) + (bit : ConfigBit Γ Λ σ S) : Circuit := + (transitionExpr S stmt bit).circuit (Fintype.equivFin (InputBit Γ σ S)) + +theorem outputCircuit_eval [Fintype K] (S : Nat) (stmt : TM2.Stmt Γ Λ σ) + (v : σ) (tapes : ∀ k, List (Γ k)) (safe : StatementSafe S stmt v tapes) + (bit : ConfigBit Γ Λ σ S) : + (outputCircuit S stmt bit).eval (fun i => inputEncoding S v tapes + ((Fintype.equivFin (InputBit Γ σ S)).symm i)) = + configEncoding S (TM2.stepAux stmt v tapes) bit := by + have he := Expr.circuit_eval (Fintype.equivFin (InputBit Γ σ S)) + (transitionExpr S stmt bit) + (fun (i : Fin (Fintype.card (InputBit Γ σ S))) => inputEncoding S v tapes + ((Fintype.equivFin (InputBit Γ σ S)).symm i)) + apply he.trans + simpa only [Equiv.symm_apply_apply] using transitionExpr_eval S stmt v tapes safe bit + +end Encoding + +section Size + +variable {K : Type} {Γ : K → Type} {Λ σ ι : Type} +variable [DecidableEq K] [Fintype σ] [DecidableEq σ] +variable [∀ k, Fintype (Γ k)] [∀ k, DecidableEq (Γ k)] [DecidableEq Λ] + +def DataBits.Bounded {S : Nat} (bits : DataBits ι Γ σ S) (C : Nat) : Prop := + (∀ v, (bits.state v).size ≤ C) ∧ ∀ k i a, (bits.cells k i a).size ≤ C + +def ResultBits.Bounded {S : Nat} (bits : ResultBits ι Γ Λ σ S) (C : Nat) : Prop := + bits.toDataBits.Bounded C ∧ ∀ l, (bits.label l).size ≤ C + +theorem size_readBits_le {A : Type} [DecidableEq A] {S : Nat} + (bits : Fin S → Option A → Expr ι) (C : Nat) (hC : 1 ≤ C) + (h : ∀ i a, (bits i a).size ≤ C) (n : Nat) (a : Option A) : + (readBits bits n a).size ≤ C := by + unfold readBits + split + · exact h _ _ + · exact hC + +noncomputable def unaryCost (σ : Type) [Fintype σ] (C : Nat) : Nat := + Fintype.card σ * (C + 3) + 1 + +noncomputable def headCost (σ A : Type) [Fintype σ] [Fintype A] (C : Nat) : Nat := + (Fintype.card σ * Fintype.card (Option A)) * (2 * C + 4) + 1 + +noncomputable def statementCost : TM2.Stmt Γ Λ σ → Nat → Nat + | .push _ _ next, C => statementCost next (max C (unaryCost σ C)) + | .peek k _ next, C => statementCost next (max C (headCost σ (Γ k) C)) + | .pop k _ next, C => statementCost next (max C (headCost σ (Γ k) C)) + | .load _ next, C => statementCost next (max C (unaryCost σ C)) + | .branch _ yes no, C => + 2 * unaryCost σ C + statementCost yes C + statementCost no C + 4 + | .goto _, C => max C (unaryCost σ C) + | .halt, C => max C 1 + +omit [DecidableEq σ] [(k : K) → Fintype (Γ k)] in +theorem pushBits_bounded {S : Nat} (bits : DataBits ι Γ σ S) (C : Nat) + (h : bits.Bounded C) (k : K) (f : σ → Γ k) : + (pushBits bits k f).Bounded (max C (unaryCost σ C)) := by + refine ⟨fun v => (h.1 v).trans (Nat.le_max_left _ _), ?_⟩ + intro j i a + by_cases hj : j = k + · subst j + simp only [pushBits, Function.update_self] + split + · exact (size_table_le _ _ _ C h.1).trans (Nat.le_max_right _ _) + · exact (h.2 _ _ _).trans (Nat.le_max_left _ _) + · simpa only [pushBits, Function.update_of_ne hj] using + (h.2 j i a).trans (Nat.le_max_left C (unaryCost σ C)) + +omit [DecidableEq K] in +theorem peekBits_bounded {S : Nat} (bits : DataBits ι Γ σ S) (C : Nat) (hC : 1 ≤ C) + (h : bits.Bounded C) (k : K) (f : σ → Option (Γ k) → σ) : + (peekBits bits k f).Bounded (max C (headCost σ (Γ k) C)) := by + refine ⟨?_, fun j i a => (h.2 j i a).trans (Nat.le_max_left _ _)⟩ + intro v + exact (size_table₂_le _ _ _ v C h.1 + (fun a => size_readBits_le _ C hC (h.2 k) 0 a)).trans (Nat.le_max_right _ _) + +theorem popBits_bounded {S : Nat} (bits : DataBits ι Γ σ S) (C : Nat) (hC : 1 ≤ C) + (h : bits.Bounded C) (k : K) (f : σ → Option (Γ k) → σ) : + (popBits bits k f).Bounded (max C (headCost σ (Γ k) C)) := by + refine ⟨(peekBits_bounded bits C hC h k f).1, ?_⟩ + intro j i a + by_cases hj : j = k + · subst j + simpa only [popBits, Function.update_self] using + (size_readBits_le _ C hC (h.2 k) (i.val + 1) a).trans + (Nat.le_max_left C (headCost σ (Γ k) C)) + · simpa only [popBits, Function.update_of_ne hj] using + (h.2 j i a).trans (Nat.le_max_left C (headCost σ (Γ k) C)) + +omit [DecidableEq K] [(k : K) → Fintype (Γ k)] [(k : K) → DecidableEq (Γ k)] in +theorem loadBits_bounded {S : Nat} (bits : DataBits ι Γ σ S) (C : Nat) + (h : bits.Bounded C) (f : σ → σ) : + (loadBits bits f).Bounded (max C (unaryCost σ C)) := by + exact ⟨fun v => (size_table_le f bits.state v C h.1).trans (Nat.le_max_right _ _), + fun k i a => (h.2 k i a).trans (Nat.le_max_left _ _)⟩ + +omit [DecidableEq K] [Fintype σ] [DecidableEq σ] [(k : K) → Fintype (Γ k)] + [(k : K) → DecidableEq (Γ k)] [DecidableEq Λ] in +theorem muxResult_bounded {S : Nat} (condition : Expr ι) (yes no : ResultBits ι Γ Λ σ S) + (G Y N : Nat) (hc : condition.size ≤ G) (hy : yes.Bounded Y) (hn : no.Bounded N) : + (muxResult condition yes no).Bounded (2 * G + Y + N + 4) := by + have hm (x y : Expr ι) (hx : x.size ≤ Y) (hy : y.size ≤ N) : + (Expr.mux condition x y).size ≤ 2 * G + Y + N + 4 := by + simp only [Expr.mux, Expr.size] + omega + exact ⟨⟨fun v => hm _ _ (hy.1.1 v) (hn.1.1 v), + fun k i a => hm _ _ (hy.1.2 k i a) (hn.1.2 k i a)⟩, + fun l => hm _ _ (hy.2 l) (hn.2 l)⟩ + +theorem compileAux_bounded {S : Nat} (stmt : TM2.Stmt Γ Λ σ) + (bits : DataBits ι Γ σ S) (C : Nat) (hC : 1 ≤ C) (h : bits.Bounded C) : + (compileAux stmt bits).Bounded (statementCost stmt C) := by + induction stmt generalizing bits C with + | push k f next ih => + exact ih _ _ (hC.trans (Nat.le_max_left _ _)) (pushBits_bounded bits C h k f) + | peek k f next ih => + exact ih _ _ (hC.trans (Nat.le_max_left _ _)) (peekBits_bounded bits C hC h k f) + | pop k f next ih => + exact ih _ _ (hC.trans (Nat.le_max_left _ _)) (popBits_bounded bits C hC h k f) + | load f next ih => + exact ih _ _ (hC.trans (Nat.le_max_left _ _)) (loadBits_bounded bits C h f) + | branch guard yes no ihy ihn => + exact muxResult_bounded _ _ _ _ _ _ (size_table_le guard bits.state true C h.1) + (ihy bits C hC h) (ihn bits C hC h) + | goto label => + exact ⟨⟨fun v => (h.1 v).trans (Nat.le_max_left _ _), + fun k i a => (h.2 k i a).trans (Nat.le_max_left _ _)⟩, + fun l => (size_table_le _ _ l C h.1).trans (Nat.le_max_right _ _)⟩ + | halt => + exact ⟨⟨fun v => (h.1 v).trans (Nat.le_max_left _ _), + fun k i a => (h.2 k i a).trans (Nat.le_max_left _ _)⟩, + fun _ => Nat.le_max_right _ _⟩ + +theorem transitionExpr_size_le (S : Nat) (stmt : TM2.Stmt Γ Λ σ) + (bit : ConfigBit Γ Λ σ S) : + (transitionExpr S stmt bit).size ≤ statementCost stmt 1 := by + have h := compileAux_bounded stmt (inputBits S) 1 (by decide) + ⟨fun _ => Nat.le_refl _, fun _ _ _ => Nat.le_refl _⟩ + rcases bit with label | (v | ⟨k, i, a⟩) + · exact h.2 label + · exact h.1.1 v + · exact h.1.2 k i a + +theorem outputCircuit_gates_le [Fintype K] (S : Nat) (stmt : TM2.Stmt Γ Λ σ) + (bit : ConfigBit Γ Λ σ S) : + (outputCircuit S stmt bit).gates.length ≤ statementCost stmt 1 := by + simpa only [outputCircuit, Expr.circuit, Expr.gates_length] using + transitionExpr_size_le S stmt bit + +end Size + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.StatementCircuit + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/StoppedCleanOwnInputGeometry.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/StoppedCleanOwnInputGeometry.lean new file mode 100644 index 0000000000000000000000000000000000000000..63ae35e983add0edb25c23b4a2604943c2854881 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/StoppedCleanOwnInputGeometry.lean @@ -0,0 +1,78 @@ +import OAI.Computability.PerfectCompleteness.Machines.StoppedOwnInputGeometry +import OAI.Computability.PerfectCompleteness.Repetition.CleanPhysicalProjectedMeeting + +namespace OAI + +section + +namespace PerfectCompleteness.StoppedCleanOwnInputGeometry + +noncomputable section + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays + +abbrev F2 := ZMod 2 + +variable {branch : Nat → Nat} {n t : Nat} (rows repeats : Nat → Nat) + +theorem pathTapeEquiv_heq + (slots : Slots branch n → Fin t → MixedSupport.Slot) + {p q : Σ height, Path branch n height} (hp : p = q) + (tape : WholeArraySampler.Tape rows repeats p.2 slots) : + HEq (StoppedOwnInputGeometry.pathTapeEquiv rows repeats slots hp tape) tape := + cast_heq _ _ + +theorem uncastTape_heq + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (upper lower : Nodes branch n) (cut : OwnInputReference.Cut upper lower) + {k : Nat} (hk : Nodes.height lower = k) + (tape : WholeArraySampler.Tape rows repeats + ((Nodes.path upper).append (hk ▸ cut.path)) slots) : + HEq (CleanPhysicalDecoderLaw.uncastTape slots upper lower cut hk tape) tape := by + cases hk + rfl + +variable (slots target : Slots branch n → Fin t → MixedSupport.Slot) + (hslots : slots = target) (upper lower otherLower : Nodes branch n) + (hlower : lower = otherLower) + (cut : OwnInputReference.Cut upper lower) + (otherCut : OwnInputReference.Cut upper otherLower) (hcut : HEq cut otherCut) + (W : Submodule F2 (Block rows upper)) + (tape : WholeArraySampler.Tape rows repeats + (WholeArrayInteriorOwnInputLaw.fullPath upper lower cut) slots) + (otherTape : WholeArraySampler.Tape rows repeats + (WholeArrayInteriorOwnInputLaw.fullPath upper otherLower otherCut) target) + (htape : HEq tape otherTape) + +include hslots hlower hcut htape + +theorem exposedRead_heq : + HEq (WholeArrayInteriorOwnInputLaw.exposedRead rows repeats slots upper lower cut W tape) + (WholeArrayInteriorOwnInputLaw.exposedRead rows repeats target upper otherLower + otherCut W otherTape) := by + cases hslots + cases hlower + have hc : cut = otherCut := eq_of_heq hcut + cases hc + have ht : tape = otherTape := eq_of_heq htape + cases ht + rfl + +theorem visibleRead_heq : + HEq (WholeArrayInteriorOwnInputLaw.exposedRead rows repeats slots upper lower cut W tape).2 + (WholeArrayInteriorOwnInputLaw.exposedRead rows repeats target upper otherLower + otherCut W otherTape).2 := by + cases hslots + cases hlower + have hc : cut = otherCut := eq_of_heq hcut + cases hc + have ht : tape = otherTape := eq_of_heq htape + cases ht + rfl + +end +end PerfectCompleteness.StoppedCleanOwnInputGeometry + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/StoppedOwnInputGeometry.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/StoppedOwnInputGeometry.lean new file mode 100644 index 0000000000000000000000000000000000000000..41615897ce95a28decba037c0cfea0e17baf3edf --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/StoppedOwnInputGeometry.lean @@ -0,0 +1,248 @@ +import OAI.Computability.PerfectCompleteness.Construction.RelativeDescendantProductsLemmas +import OAI.Computability.PerfectCompleteness.Foundations.StoppedSharedEvents +import OAI.Computability.PerfectCompleteness.Machines.WholeArrayInteriorOwnInputLaw + +namespace OAI + +section + +namespace PerfectCompleteness.StoppedOwnInputGeometry + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open RelativeDescendantProducts +open UniqueGamesTheorem.Foundations.Games + +noncomputable section + +variable {branch : Nat → Nat} {n : Nat} + +theorem exists_relativePath {upper lower : Nodes branch n} + (h : Below branch upper lower) : + ∃ p : Path branch (Nodes.height upper) (Nodes.height lower), + (Nodes.path upper).append p = Nodes.path lower := by + induction h with + | root i lower => exact ⟨.step i (Nodes.path lower), rfl⟩ + | child i h ih => + obtain ⟨p, hp⟩ := ih + exact ⟨p, congrArg (Path.step i) hp⟩ + +def cutOfBelow {upper lower : Nodes branch n} (h : Below branch upper lower) : + OwnInputReference.Cut upper lower where + proper := h.height_lt + path := Classical.choose (exists_relativePath h) + slots_agree := by + intro s + rw [← Path.slotEmbedding_append, Classical.choose_spec (exists_relativePath h)] + +theorem fullPath_cutOfBelow {upper lower : Nodes branch n} + (h : Below branch upper lower) : + WholeArrayInteriorOwnInputLaw.fullPath upper lower (cutOfBelow h) = + Nodes.path lower := + Classical.choose_spec (exists_relativePath h) + +theorem nodeAtLevel_endpoint : {n k : Nat} → (p : Path branch n (k + 1)) → + (suffix : Slots branch (k + 1)) → + GeometricPath.nodeAtLevel (p.slotEmbedding suffix) + ⟨k, Nat.lt_of_lt_of_le (Nat.lt_succ_self k) p.height_le⟩ = + WholeArrayInteriorExterior.upperNode p + | _, _, .refl _, suffix => GeometricPath.nodeAtLevel_last suffix + | N + 1, k, .step i p, suffix => by + change GeometricPath.nodeAtLevel (branch := branch) (n := N + 1) (i, p.slotEmbedding suffix) + (⟨k, Nat.lt_of_lt_of_le (Nat.lt_succ_self k) p.height_le⟩ : Fin N).castSucc = + Sum.inr (i, WholeArrayInteriorExterior.upperNode p) + exact (GeometricPath.nodeAtLevel_castSucc (branch := branch) (n := N) + (i, p.slotEmbedding suffix) + (⟨k, Nat.lt_of_lt_of_le (Nat.lt_succ_self k) p.height_le⟩ : Fin N)).trans + (congrArg (fun node : Nodes branch N => + (Sum.inr (i, node) : Nodes branch (N + 1))) (nodeAtLevel_endpoint p suffix)) + +theorem nodeAtLevel_endpoint_spec {k : Nat} (p : Path branch n (k + 1)) + (suffix : Slots branch (k + 1)) : + (⟨Nodes.height (GeometricPath.nodeAtLevel (p.slotEmbedding suffix) + ⟨k, Nat.lt_of_lt_of_le (Nat.lt_succ_self k) p.height_le⟩), + Nodes.path (GeometricPath.nodeAtLevel (p.slotEmbedding suffix) + ⟨k, Nat.lt_of_lt_of_le (Nat.lt_succ_self k) p.height_le⟩)⟩ : + Σ height, Path branch n height) = ⟨k + 1, p⟩ := by + rw [nodeAtLevel_endpoint] + exact WholeArrayInteriorExterior.upperNode_spec p + +def pathTapeEquiv {t : Nat} (rows repeats : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + {p q : Σ height, Path branch n height} (h : p = q) : + WholeArraySampler.Tape rows repeats p.2 slots ≃ + WholeArraySampler.Tape rows repeats q.2 slots := + Equiv.cast (congrArg + (fun path : Σ height, Path branch n height => + WholeArraySampler.Tape rows repeats path.2 slots) h) + +theorem pathTapeEquiv_law {t : Nat} (rows repeats : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + {p q : Σ height, Path branch n height} (h : p = q) : + (WholeArraySampler.tapeLaw rows repeats p.2 slots).pushforward + (pathTapeEquiv rows repeats slots h) = + WholeArraySampler.tapeLaw rows repeats q.2 slots := by + cases h + exact FiniteDistribution.pushforward_id _ + +theorem evaluate_pathTapeEquiv {t : Nat} (rows repeats : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + {p q : Σ height, Path branch n height} (h : p = q) + (ω : WholeArraySampler.Tape rows repeats p.2 slots) : + WholeArraySampler.evaluate rows repeats q.2 slots + (pathTapeEquiv rows repeats slots h ω) = + WholeArraySampler.evaluate rows repeats p.2 slots ω := by + cases h + rfl + +variable {m t cut : Nat} {rows : Nat → Nat} + +def lowerLevel (hcut : cut + 1 ≤ n) : Fin n := + ⟨cut, Nat.lt_of_lt_of_le (Nat.lt_succ_self cut) hcut⟩ + +def upperNode (hcut : cut + 1 ≤ n) (hbranch : ∀ k < n, 0 < branch k) + (context : StoppedSharedSampler.Context branch n t m cut rows) (level : Fin n) : + Nodes branch n := + GeometricPath.nodeAtLevel (StoppedSharedEvents.representativeLeaf hcut hbranch context) level + +def lowerNode (hcut : cut + 1 ≤ n) (hbranch : ∀ k < n, 0 < branch k) + (context : StoppedSharedSampler.Context branch n t m cut rows) : Nodes branch n := + GeometricPath.nodeAtLevel (StoppedSharedEvents.representativeLeaf hcut hbranch context) + (lowerLevel hcut) + +@[simp] theorem upperNode_height (hcut : cut + 1 ≤ n) + (hbranch : ∀ k < n, 0 < branch k) + (context : StoppedSharedSampler.Context branch n t m cut rows) (level : Fin n) : + Nodes.height (upperNode hcut hbranch context level) = level.val + 1 := + GeometricPath.nodeAtLevel_height _ _ + +@[simp] theorem lowerNode_height (hcut : cut + 1 ≤ n) + (hbranch : ∀ k < n, 0 < branch k) + (context : StoppedSharedSampler.Context branch n t m cut rows) : + Nodes.height (lowerNode hcut hbranch context) = cut + 1 := + GeometricPath.nodeAtLevel_height _ _ + +def ownCut (hcut : cut + 1 ≤ n) (hbranch : ∀ k < n, 0 < branch k) + (context : StoppedSharedSampler.Context branch n t m cut rows) + (level : Fin n) (hlevel : cut < level.val) : + OwnInputReference.Cut (upperNode hcut hbranch context level) + (lowerNode hcut hbranch context) := + cutOfBelow (GeometricDescendants.below_nodeAtLevel + (StoppedSharedEvents.representativeLeaf hcut hbranch context) level + (lowerLevel hcut) hlevel) + +theorem lowerNode_path_spec (hcut : cut + 1 ≤ n) + (hbranch : ∀ k < n, 0 < branch k) + (context : StoppedSharedSampler.Context branch n t m cut rows) : + (⟨Nodes.height (lowerNode hcut hbranch context), + Nodes.path (lowerNode hcut hbranch context)⟩ : Σ height, Path branch n height) = + ⟨cut + 1, GeometricCutSplit.prefixPath hcut context.2.1⟩ := + nodeAtLevel_endpoint_spec (GeometricCutSplit.prefixPath hcut context.2.1) + (StoppedSharedEvents.referenceSuffix hcut hbranch) + +theorem fullPath_spec (hcut : cut + 1 ≤ n) + (hbranch : ∀ k < n, 0 < branch k) + (context : StoppedSharedSampler.Context branch n t m cut rows) + (level : Fin n) (hlevel : cut < level.val) : + (⟨Nodes.height (lowerNode hcut hbranch context), + WholeArrayInteriorOwnInputLaw.fullPath (upperNode hcut hbranch context level) + (lowerNode hcut hbranch context) (ownCut hcut hbranch context level hlevel)⟩ : + Σ height, Path branch n height) = + ⟨cut + 1, GeometricCutSplit.prefixPath hcut context.2.1⟩ := by + have hpath : + WholeArrayInteriorOwnInputLaw.fullPath (upperNode hcut hbranch context level) + (lowerNode hcut hbranch context) (ownCut hcut hbranch context level hlevel) = + Nodes.path (lowerNode hcut hbranch context) := + fullPath_cutOfBelow (GeometricDescendants.below_nodeAtLevel + (StoppedSharedEvents.representativeLeaf hcut hbranch context) level + (lowerLevel hcut) hlevel) + exact (congrArg (fun p : Path branch n (Nodes.height (lowerNode hcut hbranch context)) => + (⟨Nodes.height (lowerNode hcut hbranch context), p⟩ : Σ height, Path branch n height)) + hpath).trans (lowerNode_path_spec hcut hbranch context) + +theorem arrayLaw_eq (repeats : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (hcut : cut + 1 ≤ n) (hbranch : ∀ k < n, 0 < branch k) + (context : StoppedSharedSampler.Context branch n t m cut rows) + (level : Fin n) (hlevel : cut < level.val) : + WholeArraySampler.law rows repeats + (WholeArrayInteriorOwnInputLaw.fullPath (upperNode hcut hbranch context level) + (lowerNode hcut hbranch context) (ownCut hcut hbranch context level hlevel)) slots = + WholeArraySampler.law rows repeats (GeometricCutSplit.prefixPath hcut context.2.1) slots := + congrArg (fun path : Σ height, Path branch n height => + WholeArraySampler.law rows repeats path.2 slots) + (fullPath_spec hcut hbranch context level hlevel) + +def tapeEquiv (repeats : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (hcut : cut + 1 ≤ n) (hbranch : ∀ k < n, 0 < branch k) + (context : StoppedSharedSampler.Context branch n t m cut rows) + (level : Fin n) (hlevel : cut < level.val) : + WholeArraySampler.Tape rows repeats (GeometricCutSplit.prefixPath hcut context.2.1) slots ≃ + WholeArraySampler.Tape rows repeats + (WholeArrayInteriorOwnInputLaw.fullPath (upperNode hcut hbranch context level) + (lowerNode hcut hbranch context) (ownCut hcut hbranch context level hlevel)) slots := + pathTapeEquiv rows repeats slots (fullPath_spec hcut hbranch context level hlevel).symm + +theorem tapeEquiv_law (repeats : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (hcut : cut + 1 ≤ n) (hbranch : ∀ k < n, 0 < branch k) + (context : StoppedSharedSampler.Context branch n t m cut rows) + (level : Fin n) (hlevel : cut < level.val) : + (WholeArraySampler.tapeLaw rows repeats + (GeometricCutSplit.prefixPath hcut context.2.1) slots).pushforward + (tapeEquiv repeats slots hcut hbranch context level hlevel) = + WholeArraySampler.tapeLaw rows repeats + (WholeArrayInteriorOwnInputLaw.fullPath (upperNode hcut hbranch context level) + (lowerNode hcut hbranch context) (ownCut hcut hbranch context level hlevel)) slots := + pathTapeEquiv_law rows repeats slots (fullPath_spec hcut hbranch context level hlevel).symm + +theorem evaluate_tapeEquiv (repeats : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (hcut : cut + 1 ≤ n) (hbranch : ∀ k < n, 0 < branch k) + (context : StoppedSharedSampler.Context branch n t m cut rows) + (level : Fin n) (hlevel : cut < level.val) + (ω : WholeArraySampler.Tape rows repeats + (GeometricCutSplit.prefixPath hcut context.2.1) slots) : + WholeArraySampler.evaluate rows repeats + (WholeArrayInteriorOwnInputLaw.fullPath (upperNode hcut hbranch context level) + (lowerNode hcut hbranch context) (ownCut hcut hbranch context level hlevel)) slots + (tapeEquiv repeats slots hcut hbranch context level hlevel ω) = + WholeArraySampler.evaluate rows repeats (GeometricCutSplit.prefixPath hcut context.2.1) + slots ω := + evaluate_pathTapeEquiv rows repeats slots + (fullPath_spec hcut hbranch context level hlevel).symm ω + +theorem exposedRead_law (repeats : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (hcut : cut + 1 ≤ n) (hbranch : ∀ k < n, 0 < branch k) + (context : StoppedSharedSampler.Context branch n t m cut rows) + (level : Fin n) (hlevel : cut < level.val) + (W : Submodule (ZMod 2) (Block rows (upperNode hcut hbranch context level))) : + (WholeArraySampler.tapeLaw rows repeats + (GeometricCutSplit.prefixPath hcut context.2.1) slots).pushforward + (fun ω => WholeArrayInteriorOwnInputLaw.exposedRead rows repeats slots + (upperNode hcut hbranch context level) (lowerNode hcut hbranch context) + (ownCut hcut hbranch context level hlevel) W + (tapeEquiv repeats slots hcut hbranch context level hlevel ω)) = + OwnInputReference.rawLaw slots rows (upperNode hcut hbranch context level) + (lowerNode hcut hbranch context) W repeats (ownCut hcut hbranch context level hlevel) + (WholeArrayInteriorOwnInputLaw.exteriorLaw rows repeats slots + (upperNode hcut hbranch context level) (lowerNode hcut hbranch context) + (ownCut hcut hbranch context level hlevel)) := by + rw [← FiniteDistribution.pushforward_comp + (WholeArraySampler.tapeLaw rows repeats (GeometricCutSplit.prefixPath hcut context.2.1) slots) + (tapeEquiv repeats slots hcut hbranch context level hlevel) + (WholeArrayInteriorOwnInputLaw.exposedRead rows repeats slots + (upperNode hcut hbranch context level) (lowerNode hcut hbranch context) + (ownCut hcut hbranch context level hlevel) W)] + rw [tapeEquiv_law] + exact WholeArrayInteriorOwnInputLaw.exposedRead_law rows repeats slots + (upperNode hcut hbranch context level) (lowerNode hcut hbranch context) + (ownCut hcut hbranch context level hlevel) W + +end +end PerfectCompleteness.StoppedOwnInputGeometry + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/TargetFinalizeMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/TargetFinalizeMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..cff181ce646baaf8cd48b71dd69c2bd405203a3d --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/TargetFinalizeMachine.lean @@ -0,0 +1,145 @@ +import OAI.Computability.PerfectCompleteness.Machines.TargetHeaderMachine +import OAI.Computability.UniqueGames.Machines.MachineDrainManyLemmas + +namespace OAI + + +namespace PerfectCompleteness.TargetFinalizeMachine + + +open Turing UniqueGamesTheorem.Foundations.Complexity +open UniqueGamesTheorem.Reduction.MachineTransfer +open MachineComposition + +variable {K Λ A : Type} [DecidableEq K] {stackCount : Nat} + +abbrev Alphabet (_ : K) := Bool +abbrev State (A : Type) := A × Option Bool + +def headerTape (tape : Fin 4 → K) : Fin 3 → K + | 0 => tape 1 + | 1 => tape 2 + | 2 => tape 3 + +omit [DecidableEq K] in +theorem headerTape_injective (tape : Fin 4 → K) (distinct : Function.Injective tape) : + Function.Injective (headerTape tape) := by + intro i j same + fin_cases i <;> fin_cases j <;> simp only [headerTape] at same ⊢ <;> + first | rfl | exact False.elim (by simpa using distinct same) + +abbrev WorkLabel (enumeration : Fin stackCount ≃ K) (output : K) := + MachineDrainMany.Label (MachineDrainMany.workTapes enumeration output) + +inductive Label (Cleanup : Type) + | reverse + | header (label : TargetHeaderMachine.Label) + | cleanup (label : Cleanup) + | finish + deriving DecidableEq, Fintype + +abbrev Labels (enumeration : Fin stackCount ≃ K) (output : K) := + Label (WorkLabel enumeration output) + +def instruction (q : Nat) (enumeration : Fin stackCount ≃ K) (tape : Fin 4 → K) + (initial : A) (labels : Labels enumeration (tape 3) → Λ) : + Labels enumeration (tape 3) → TM2.Stmt (Alphabet (K := K)) Λ (State A) + | .reverse => loopAt (tape 0) (tape 3) id false (labels .reverse) + (some (labels (.header TargetHeaderMachine.main))) + | .header label => TargetHeaderMachine.instruction q (headerTape tape) + (fun l => labels (.header l)) + (MachineDrainMany.entry (MachineDrainMany.workTapes enumeration (tape 3)) + (fun l => labels (.cleanup l)) (some (labels .finish))) label + | .cleanup label => MachineDrainMany.instruction + (MachineDrainMany.workTapes enumeration (tape 3)) + (fun l => labels (.cleanup l)) (some (labels .finish)) label + | .finish => .load (fun _ => (initial, none)) .halt + +def bodyTapes (tape : Fin 4 → K) (base : K → List Bool) (body : List Bool) : K → List Bool := + Function.update (Function.update base (tape 0) []) (tape 3) body + +def headerTapes (q count : Nat) (tape : Fin 4 → K) (base : K → List Bool) + (body : List Bool) : K → List Bool := + Function.update (bodyTapes tape base body) (tape 3) + (encodeWords [count, count, q, count] ++ body) + +def budget (q count : Nat) (enumeration : Fin stackCount ≃ K) (tape : Fin 4 → K) + (base : K → List Bool) (body : List Bool) : Nat := + body.length + 1 + (6 * (count + 2) + 1) + + (MachineDrainMany.lengthSum (MachineDrainMany.workTapes enumeration (tape 3)) + (headerTapes q count tape base body) + + (MachineDrainMany.workTapes enumeration (tape 3)).length) + 1 + +def finalizeInTime (q : Nat) (enumeration : Fin stackCount ≃ K) (tape : Fin 4 → K) + (distinct : Function.Injective tape) (initial : A) + (labels : Labels enumeration (tape 3) → Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ l, program (labels l) = instruction q enumeration tape initial labels l) + (base : K → List Bool) (ambient : A) (register : Option Bool) + (count : Nat) (body : List Bool) + (reversed : base (tape 0) = body.reverse) + (countWord : base (tape 1) = encodeWord count) + (scratchEmpty : base (tape 2) = []) (outputEmpty : base (tape 3) = []) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .reverse), (ambient, register), base⟩ + (some ⟨none, (initial, none), MachineDrainMany.haltTapes (tape 3) + (encodeWords [count, count, q, count] ++ body)⟩) + (budget q count enumeration tape base body) := by + have different (i j : Fin 4) (h : i ≠ j) : tape i ≠ tape j := + fun same => h (distinct same) + have transferTapes : tapesAt (tape 0) (tape 3) base [] + ((base (tape 0)).reverse.map id ++ base (tape 3)) = bodyTapes tape base body := by + simp only [reversed, List.reverse_reverse, List.map_id, outputEmpty, List.append_nil] + rfl + have transferred : StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .reverse), (ambient, register), base⟩ + (some ⟨some (labels (.header TargetHeaderMachine.main)), (ambient, none), + bodyTapes tape base body⟩) (body.length + 1) := by + have run := transferAtInTime (Γ := Alphabet (K := K)) (σ := A) (tape 0) (tape 3) (different 0 3 (by decide)) + id false (labels .reverse) (some (labels (.header TargetHeaderMachine.main))) + program (by simpa only [instruction] using atLabels .reverse) base ambient register + rw [transferTapes] at run + simpa only [reversed, List.length_reverse] using run + have bodyCount : bodyTapes tape base body (headerTape tape 0) = encodeWord count := by + simp [bodyTapes, headerTape, different 1 3 (by decide), different 1 0 (by decide), countWord] + have bodyScratch : bodyTapes tape base body (headerTape tape 1) = [] := by + simp [bodyTapes, headerTape, different 2 3 (by decide), different 2 0 (by decide), scratchEmpty] + have bodyOutput : bodyTapes tape base body (headerTape tape 2) = body := by + simp [bodyTapes, headerTape] + have emitted := TargetHeaderMachine.headerInTime q (headerTape tape) + (headerTape_injective tape distinct) (fun l => labels (.header l)) + (MachineDrainMany.entry (MachineDrainMany.workTapes enumeration (tape 3)) + (fun l => labels (.cleanup l)) (some (labels .finish))) + program (fun l => atLabels (.header l)) (bodyTapes tape base body) + count bodyCount bodyScratch ambient none + rw [bodyOutput] at emitted + change StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels (.header TargetHeaderMachine.main)), (ambient, none), bodyTapes tape base body⟩ + (some ⟨MachineDrainMany.entry (MachineDrainMany.workTapes enumeration (tape 3)) + (fun l => labels (.cleanup l)) (some (labels .finish)), (ambient, none), + headerTapes q count tape base body⟩) (6 * (count + 2) + 1) at emitted + have cleaned := MachineDrainMany.execution + (MachineDrainMany.workTapes enumeration (tape 3)) (fun l => labels (.cleanup l)) + (some (labels .finish)) program (fun l => atLabels (.cleanup l)) + (headerTapes q count tape base body) ambient none + rw [MachineDrainMany.finalRegister_none, MachineDrainMany.finalTapes_workTapes] at cleaned + have headerOutput : headerTapes q count tape base body (tape 3) = + encodeWords [count, count, q, count] ++ body := by simp [headerTapes] + rw [headerOutput] at cleaned + have reset : StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .finish), (ambient, none), MachineDrainMany.haltTapes (tape 3) + (encodeWords [count, count, q, count] ++ body)⟩ + (some ⟨none, (initial, none), MachineDrainMany.haltTapes (tape 3) + (encodeWords [count, count, q, count] ++ body)⟩) 1 := by + refine { steps := 1, evals_in_steps := ?_, steps_le_m := Nat.le_refl 1 } + change some (TM2.stepAux (program (labels .finish)) _ _) = _ + rw [atLabels] + rfl + have first := StateTransition.EvalsToInTime.trans (TM2.step program) _ _ _ _ _ transferred emitted + have second := StateTransition.EvalsToInTime.trans (TM2.step program) _ _ _ _ _ first cleaned + have third := StateTransition.EvalsToInTime.trans (TM2.step program) _ _ _ _ _ second reset + simpa only [budget, Nat.add_assoc, Nat.add_left_comm, Nat.add_comm] using third + +end PerfectCompleteness.TargetFinalizeMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/TargetHeaderMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/TargetHeaderMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..dfbcd612e254278c16b4d3c96f0d562f97d4dccc --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/TargetHeaderMachine.lean @@ -0,0 +1,187 @@ +import OAI.Computability.UniqueGames.Machines.MachineCopy +import OAI.Computability.UniqueGames.Machines.MachineSubroutineLemmas +import OAI.Computability.UniqueGames.Reduction.MachineSubstitution + +namespace OAI + + +namespace PerfectCompleteness.TargetHeaderMachine + + +open Turing +open UniqueGamesTheorem.Foundations.Complexity +open MachineComposition +open UniqueGamesTheorem.Reduction.MachineTransfer (loopAt exitAt) +open UniqueGamesTheorem.Reduction.MachineSubstitution + +abbrev Alphabet {K : Type} (_ : K) := Bool +abbrev State (A : Type) := A × Option Bool + +inductive Label + | copyLast | restoreLast | pushAlphabet + | copyRight | restoreRight | copyLeft | restoreLeft + deriving DecidableEq + +/-- A list enumerating every element of the type, which are all zero-argument constructors. (Generated by the `Fintype` deriving handler.)-/ +protected abbrev Label.enumList : List Label := [.copyLast, .restoreLast, .pushAlphabet, + .copyRight, .restoreRight, .copyLeft, .restoreLeft] + +protected theorem Label.enumList_getElem?_ctorIdx_eq (x : Label) : + Label.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem Label.enumList_nodup : Label.enumList.Nodup := by decide + +instance : Fintype Label where + elems := ⟨Label.enumList, Label.enumList_nodup⟩ + complete x := by cases x <;> decide + +def main : Label := .copyLast + +variable {K Λ A : Type} [DecidableEq K] + +def instruction (q : Nat) (tape : Fin 3 → K) (labels : Label → Λ) + (done : Option Λ) : Label → TM2.Stmt (Alphabet (K := K)) Λ (State A) + | .copyLast => loopAt (tape 0) (tape 1) id false (labels .copyLast) + (some (labels .restoreLast)) + | .restoreLast => MachineCopy.forkLoop (tape 1) (tape 0) (tape 2) false + (labels .restoreLast) (some (labels .pushAlphabet)) + | .pushAlphabet => pushWord (tape 2) (encodeWord q).reverse + (.goto fun _ => labels .copyRight) + | .copyRight => loopAt (tape 0) (tape 1) id false (labels .copyRight) + (some (labels .restoreRight)) + | .restoreRight => MachineCopy.forkLoop (tape 1) (tape 0) (tape 2) false + (labels .restoreRight) (some (labels .copyLeft)) + | .copyLeft => loopAt (tape 0) (tape 1) id false (labels .copyLeft) + (some (labels .restoreLeft)) + | .restoreLeft => MachineCopy.forkLoop (tape 1) (tape 0) (tape 2) false + (labels .restoreLeft) done + +omit [DecidableEq K] in +theorem instruction_pushBound (q : Nat) (tape : Fin 3 → K) (labels : Label → Λ) + (done : Option Λ) (label : Label) : + Runtime.statementPushBound (instruction (A := A) q tape labels done label) ≤ q + 2 := by + cases label <;> cases done <;> + simp [instruction, loopAt, MachineCopy.forkLoop, exitAt, + statementPushBound_pushWord, Runtime.statementPushBound] + +theorem pushAlphabetStep (q : Nat) (tape : Fin 3 → K) (labels : Label → Λ) + (done : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabel : program (labels .pushAlphabet) = instruction q tape labels done .pushAlphabet) + (base : K → List Bool) (ambient : A) (register : Option Bool) : + TM2.step program ⟨some (labels .pushAlphabet), (ambient, register), base⟩ = + some ⟨some (labels .copyRight), (ambient, register), + Function.update base (tape 2) (encodeWord q ++ base (tape 2))⟩ := by + change some (TM2.stepAux (program (labels .pushAlphabet)) (ambient, register) base) = _ + rw [atLabel] + simp only [instruction, stepAux_pushWord, List.reverse_reverse, TM2.stepAux] + +private theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +theorem headerTrace (q : Nat) (tape : Fin 3 → K) (distinct : Function.Injective tape) + (labels : Label → Λ) (done : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ label, program (labels label) = instruction q tape labels done label) + (base : K → List Bool) (N : Nat) (sourceWord : base (tape 0) = encodeWord N) + (scratchEmpty : base (tape 1) = []) (ambient : A) (register : Option Bool) : + (advance (TM2.step program))^[6 * (N + 2) + 1] + (some ⟨some (labels main), (ambient, register), base⟩) = + some ⟨done, (ambient, none), + Function.update base (tape 2) (encodeWords [N, N, q, N] ++ base (tape 2))⟩ := by + have h02 : tape 0 ≠ tape 2 := fun h => (by decide : (0 : Fin 3) ≠ 2) (distinct h) + have h01 : tape 0 ≠ tape 1 := fun h => (by decide : (0 : Fin 3) ≠ 1) (distinct h) + have h21 : tape 2 ≠ tape 1 := fun h => (by decide : (2 : Fin 3) ≠ 1) (distinct h) + let firstTapes := Function.update base (tape 2) (encodeWord N ++ base (tape 2)) + let literalTapes := Function.update firstTapes (tape 2) + (encodeWord q ++ firstTapes (tape 2)) + let secondTapes := Function.update literalTapes (tape 2) + (encodeWord N ++ literalTapes (tape 2)) + have first := MachineCopy.copyTrace (tape 0) (tape 2) (tape 1) h02 h01 h21 false + (labels .copyLast) (labels .restoreLast) (some (labels .pushAlphabet)) program + (atLabels .copyLast) (atLabels .restoreLast) base scratchEmpty ambient register + rw [sourceWord, encodeWord_length] at first + have literal : (advance (TM2.step program))^[1] + (some ⟨some (labels .pushAlphabet), (ambient, none), firstTapes⟩) = + some ⟨some (labels .copyRight), (ambient, none), literalTapes⟩ := by + exact pushAlphabetStep q tape labels done program (atLabels .pushAlphabet) + firstTapes ambient none + have literalSource : literalTapes (tape 0) = encodeWord N := by + simp [literalTapes, firstTapes, h02, sourceWord] + have literalScratch : literalTapes (tape 1) = [] := by + simp [literalTapes, firstTapes, Ne.symm h21, scratchEmpty] + have second := MachineCopy.copyTrace (tape 0) (tape 2) (tape 1) h02 h01 h21 false + (labels .copyRight) (labels .restoreRight) (some (labels .copyLeft)) program + (atLabels .copyRight) (atLabels .restoreRight) literalTapes literalScratch ambient none + rw [literalSource, encodeWord_length] at second + have secondSource : secondTapes (tape 0) = encodeWord N := by + simp [secondTapes, h02, literalSource] + have secondScratch : secondTapes (tape 1) = [] := by + simp [secondTapes, Ne.symm h21, literalScratch] + have third := MachineCopy.copyTrace (tape 0) (tape 2) (tape 1) h02 h01 h21 false + (labels .copyLeft) (labels .restoreLeft) done program + (atLabels .copyLeft) (atLabels .restoreLeft) secondTapes secondScratch ambient none + rw [secondSource, encodeWord_length] at third + have all := joinTrace (joinTrace (joinTrace first literal) second) third + have count : ((2 * (N + 1 + 1) + 1) + 2 * (N + 1 + 1)) + + 2 * (N + 1 + 1) = 6 * (N + 2) + 1 := by omega + rw [count] at all + simpa only [main, secondTapes, literalTapes, firstTapes, + Function.update_self, Function.update_idem, encodeWords, List.append_nil, + List.append_assoc] using all + +def headerInTime (q : Nat) (tape : Fin 3 → K) (distinct : Function.Injective tape) + (labels : Label → Λ) (done : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ label, program (labels label) = instruction q tape labels done label) + (base : K → List Bool) (N : Nat) (sourceWord : base (tape 0) = encodeWord N) + (scratchEmpty : base (tape 1) = []) (ambient : A) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels main), (ambient, register), base⟩ + (some ⟨done, (ambient, none), + Function.update base (tape 2) (encodeWords [N, N, q, N] ++ base (tape 2))⟩) + (6 * (N + 2) + 1) where + steps := 6 * (N + 2) + 1 + evals_in_steps := headerTrace q tape distinct labels done program atLabels base N + sourceWord scratchEmpty ambient register + steps_le_m := Nat.le_refl _ + +def increment (count : K) (done : Option Λ) : TM2.Stmt (Alphabet (K := K)) Λ (State A) := + .push count (fun _ => true) (exitAt count done) + +@[simp] theorem encodeWord_zero : encodeWord 0 = [false] := rfl + +theorem incrementStep (count : K) (label : Λ) (done : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabel : program label = increment count done) (base : K → List Bool) + (N : Nat) (sourceWord : base count = encodeWord N) (state : State A) : + TM2.step program ⟨some label, state, base⟩ = + some ⟨done, state, Function.update base count (encodeWord (N + 1))⟩ := by + change some (TM2.stepAux (program label) state base) = _ + rw [atLabel] + cases done <;> + simp [increment, exitAt, TM2.stepAux, sourceWord, encodeWord, + List.replicate_succ] + +def incrementInTime (count : K) (label : Λ) (done : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabel : program label = increment count done) (base : K → List Bool) + (N : Nat) (sourceWord : base count = encodeWord N) (state : State A) : + StateTransition.EvalsToInTime (TM2.step program) ⟨some label, state, base⟩ + (some ⟨done, state, Function.update base count (encodeWord (N + 1))⟩) 1 where + steps := 1 + evals_in_steps := incrementStep count label done program atLabel base N sourceWord state + steps_le_m := Nat.le_refl _ + +theorem finiteState [Finite A] : Finite (State A) := inferInstance + +omit [DecidableEq K] in +theorem finiteAlphabet (key : K) : Finite (Alphabet key) := by + change Finite Bool + infer_instance + +end PerfectCompleteness.TargetHeaderMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/TargetTapeEnvelope.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/TargetTapeEnvelope.lean new file mode 100644 index 0000000000000000000000000000000000000000..1e42b28f1ba6db3a6c07efb6b804af88cfedd53b --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/TargetTapeEnvelope.lean @@ -0,0 +1,73 @@ +import OAI.Computability.PerfectCompleteness.Foundations.SignedCostEnvelope + +namespace OAI + +section + +namespace PerfectCompleteness.TargetTapeEnvelope + +def outputBound (q E : Nat) : Nat := + 2 * E + q + E + 4 + E * (2 * E + 2 * q * q + 2 * q + 2) + +def bound (w q T E : Nat) : Nat := + T + 1 + CanonicalDictionaryNames.streamBound w T E + + outputBound q E + (E + 1) + +def coeff (w q D : Nat) : Nat := + SignedCostEnvelope.streamCoeff w D + 2 * D ^ 2 + + (2 * q * q + 2 * q + 6) * D + q + 6 + +private theorem le_scaled (a : Nat) {b : Nat} (hb : 1 ≤ b) : a ≤ a * b := by + simpa only [Nat.mul_one] using Nat.mul_le_mul_left a hb + +theorem bound_le (w q D T E : Nat) (hcount : E ≤ D * (T + 1) ^ w) : + bound w q T E ≤ coeff w q D * (T + 1) ^ (2 * w + 2) := by + have hone : 1 ≤ (T + 1) ^ (2 * w + 2) := + Nat.one_le_pow (2 * w + 2) (T + 1) (Nat.zero_lt_succ T) + have hinput : T + 1 ≤ (T + 1) ^ (2 * w + 2) := + Nat.le_pow (show 0 < 2 * w + 2 by omega) + have hcountLinear : E ≤ D * (T + 1) ^ (2 * w + 2) := + hcount.trans (Nat.mul_le_mul_left D + (Nat.pow_le_pow_right (Nat.zero_lt_succ T) (by omega))) + have hstream : CanonicalDictionaryNames.streamBound w T E ≤ + SignedCostEnvelope.streamCoeff w D * (T + 1) ^ (2 * w + 2) := by + calc + CanonicalDictionaryNames.streamBound w T E ≤ + CanonicalDictionaryNames.streamBound w T (D * (T + 1) ^ w) := + Nat.mul_le_mul_left _ hcount + _ ≤ SignedCostEnvelope.streamCoeff w D * (T + 1) ^ (w + 1) := + SignedCostEnvelope.streamBound_le w D T + _ ≤ SignedCostEnvelope.streamCoeff w D * (T + 1) ^ (2 * w + 2) := + Nat.mul_le_mul_left _ + (Nat.pow_le_pow_right (Nat.zero_lt_succ T) (by omega)) + have hsquare : E ^ 2 ≤ D ^ 2 * (T + 1) ^ (2 * w + 2) := by + calc + E ^ 2 ≤ (D * (T + 1) ^ w) ^ 2 := Nat.pow_le_pow_left hcount 2 + _ = D ^ 2 * (T + 1) ^ (w * 2) := by rw [Nat.mul_pow, ← Nat.pow_mul] + _ ≤ D ^ 2 * (T + 1) ^ (2 * w + 2) := + Nat.mul_le_mul_left _ + (Nat.pow_le_pow_right (Nat.zero_lt_succ T) (by omega)) + calc + bound w q T E = (T + 1) + CanonicalDictionaryNames.streamBound w T E + + 2 * E ^ 2 + (2 * q * q + 2 * q + 6) * E + (q + 5) := by + unfold bound outputBound + ring + _ ≤ (T + 1) ^ (2 * w + 2) + + SignedCostEnvelope.streamCoeff w D * (T + 1) ^ (2 * w + 2) + + 2 * (D ^ 2 * (T + 1) ^ (2 * w + 2)) + + (2 * q * q + 2 * q + 6) * (D * (T + 1) ^ (2 * w + 2)) + + (q + 5) * (T + 1) ^ (2 * w + 2) := + Nat.add_le_add + (Nat.add_le_add + (Nat.add_le_add (Nat.add_le_add hinput hstream) (Nat.mul_le_mul_left 2 hsquare)) + (Nat.mul_le_mul_left (2 * q * q + 2 * q + 6) hcountLinear)) + (le_scaled (q + 5) hone) + _ = coeff w q D * (T + 1) ^ (2 * w + 2) := by + unfold coeff + ring + +end PerfectCompleteness.TargetTapeEnvelope + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/TermMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/TermMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..7316c3ebf68869bffa8008e0649846131771ee9b --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/TermMachine.lean @@ -0,0 +1,792 @@ +import Mathlib.Tactic.DeriveFintype +import Mathlib.Tactic.Linarith +import OAI.Computability.PerfectCompleteness.Machines.PositionLemmas +import OAI.Computability.PerfectCompleteness.Machines.TransitionTemplate +import OAI.Computability.UniqueGames.Machines.MachineProductGatherBoundsLemmas +import OAI.Computability.UniqueGames.Machines.MachineUnaryLessAtLemmas + +namespace OAI + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.TermMachine + +open Turing MachineComposition TransitionTemplate PostfixModel + + +inductive Tape + | cursor | capacity | roots | count | reversed + | position | address | value | scratch | copy | saveLeft | saveRight + deriving DecidableEq + +protected abbrev Tape.enumList : List Tape := [.cursor, .capacity, .roots, .count, .reversed, + .position, .address, .value, .scratch, .copy, .saveLeft, .saveRight] + +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 + +abbrev Alphabet (_ : Tape) := Bool +abbrev State := (Unit × Bool) × Option Bool + +def initialState : State := (((), false), none) + +structure Input where + cursor : Nat + capacity : Nat + roots : List Nat + +def Input.size (input : Input) : Nat := + input.cursor + input.capacity + (encodeWords input.roots).length + +def work : Tape → Bool + | .cursor | .capacity | .roots | .count | .reversed => false + | _ => true + +structure Frame (input : Input) (base : Tape → List Bool) : Prop where + cursorWord : base .cursor = encodeWord input.cursor + capacityWord : base .capacity = encodeWord input.capacity + rootsWord : base .roots = encodeWords input.roots + clean : ∀ tape, work tape = true → base tape = [] + +def emitTapes (base : Tape → List Bool) (tokens : List Token) : Tape → List Bool := + Function.update + (Function.update base .reversed ((tokenBits tokens).reverse ++ base .reversed)) + .count (List.replicate tokens.length true ++ base .count) + +@[simp] theorem emitTapes_reversed (base : Tape → List Bool) (tokens : List Token) : + emitTapes base tokens .reversed = (tokenBits tokens).reverse ++ base .reversed := by + simp [emitTapes] + +@[simp] theorem emitTapes_count (base : Tape → List Bool) (tokens : List Token) : + emitTapes base tokens .count = List.replicate tokens.length true ++ base .count := by + simp [emitTapes] + +theorem emitTapes_other (base : Tape → List Bool) (tokens : List Token) (tape : Tape) + (hc : tape ≠ .count) (ho : tape ≠ .reversed) : + emitTapes base tokens tape = base tape := by + simp [emitTapes, hc, ho] + +theorem Frame.emit {input : Input} {base : Tape → List Bool} + (frame : Frame input base) (tokens : List Token) : Frame input (emitTapes base tokens) := by + refine ⟨?_, ?_, ?_, ?_⟩ + · simpa [emitTapes] using frame.cursorWord + · simpa [emitTapes] using frame.capacityWord + · simpa [emitTapes] using frame.rootsWord + · intro tape ht + have hc : tape ≠ .count := by intro h; subst tape; simp [work] at ht + have ho : tape ≠ .reversed := by intro h; subst tape; simp [work] at ht + rw [emitTapes_other base tokens tape hc ho] + exact frame.clean tape ht + +@[simp] theorem tokenBits_append (first second : List Token) : + tokenBits (first ++ second) = tokenBits first ++ tokenBits second := by + simp [tokenBits, tokenWords, List.flatMap_append, encodeWords_append] + +theorem emitTapes_append (base : Tape → List Bool) (first second : List Token) : + emitTapes (emitTapes base first) second = emitTapes base (first ++ second) := by + funext tape + by_cases hc : tape = .count + · subst tape + simp only [emitTapes_count, List.length_append] + rw [← List.append_assoc, ← List.replicate_add, Nat.add_comm second.length first.length] + · cases tape <;> + simp [emitTapes, List.length_append, List.reverse_append, List.append_assoc] at * + +theorem emitTapes_count_word (base : Tape → List Bool) (tokens : List Token) + (count : Nat) (suffix : List Bool) (h : base .count = encodeWord count ++ suffix) : + emitTapes base tokens .count = encodeWord (count + tokens.length) ++ suffix := by + rw [emitTapes_count, h] + simpa only [Nat.add_comm] using + MachineUnaryAffineAt.prepend_replicate_word tokens.length count suffix + +structure Emitter (valid : Input → Prop) (output : Input → List Token) where + Label : Type + finite : Fintype Label + entry : Label + program : Label → TM2.Stmt Alphabet Label State + steps : Input → Nat + constant : Nat + trace : ∀ (input : Input), valid input → ∀ (base : Tape → List Bool), Frame input base → + (advance (TM2.step program))^[steps input] + (some ⟨some entry, initialState, base⟩) = + some ⟨none, initialState, emitTapes base (output input)⟩ + bound : ∀ input, valid input → steps input ≤ constant * (input.size + 1) + +attribute [instance] Emitter.finite + +namespace Emitter + +variable {valid : Input → Prop} {output first second : Input → List Token} + +def machine (emitter : Emitter valid output) : FinTM2 where + K := Tape + k₀ := .cursor + k₁ := .reversed + Γ := Alphabet + Λ := emitter.Label + main := emitter.entry + σ := State + initialState := initialState + m := emitter.program + +def literalProgram (tokens : List Token) : Unit → TM2.Stmt Alphabet Unit State := + fun _ => Reduction.MachineSubstitution.pushWord .reversed (tokenBits tokens) + (Reduction.MachineSubstitution.pushWord .count (List.replicate tokens.length true) + (.load (fun _ => initialState) .halt)) + +theorem literalTrace (tokens : List Token) (base : Tape → List Bool) : + (advance (TM2.step (literalProgram tokens)))^[1] + (some ⟨some (), initialState, base⟩) = + some ⟨none, initialState, emitTapes base tokens⟩ := by + change some (TM2.stepAux (literalProgram tokens ()) initialState base) = _ + simp [literalProgram, Reduction.MachineSubstitution.stepAux_pushWord, + TM2.stepAux, emitTapes] + +def literal (valid : Input → Prop) (tokens : List Token) : + Emitter valid (fun _ => tokens) where + Label := Unit + finite := inferInstance + entry := () + program := literalProgram tokens + steps := fun _ => 1 + constant := 1 + trace _ _ base _ := literalTrace tokens base + bound input _ := by simp + +def seqProgram (left : Emitter valid first) (right : Emitter valid second) : + left.Label ⊕ right.Label → TM2.Stmt Alphabet (left.Label ⊕ right.Label) State + | .inl l => MachineSubroutine.statement Sum.inl (some (.inr right.entry)) (left.program l) + | .inr l => MachineSubroutine.statement Sum.inr none (right.program l) + +def seq (left : Emitter valid first) (right : Emitter valid second) : + Emitter valid (fun input => first input ++ second input) where + Label := left.Label ⊕ right.Label + finite := inferInstance + entry := .inl left.entry + program := seqProgram left right + steps input := left.steps input + right.steps input + constant := left.constant + right.constant + trace input hv base frame := by + have hl := MachineSubroutine.trace Sum.inl (some (.inr right.entry)) + left.program (seqProgram left right) (fun _ => rfl) + (left.steps input) _ _ (left.trace input hv base frame) + have hr := MachineSubroutine.trace Sum.inr none + right.program (seqProgram left right) (fun _ => rfl) + (right.steps input) _ _ (right.trace input hv (emitTapes base (first input)) + (frame.emit (first input))) + simp only [MachineSubroutine.configuration, MachineSubroutine.label] at hl hr + rw [Nat.add_comm (left.steps input), Function.iterate_add_apply, hl, hr, + emitTapes_append] + bound input hv := by + have h := Nat.add_le_add (left.bound input hv) (right.bound input hv) + simpa only [Nat.add_mul] using h + +def congr (emitter : Emitter valid first) (equality : ∀ input, first input = second input) : + Emitter valid second where + Label := emitter.Label + finite := emitter.finite + entry := emitter.entry + program := emitter.program + steps := emitter.steps + constant := emitter.constant + trace input hv base frame := by + simpa only [equality input] using emitter.trace input hv base frame + bound := emitter.bound + +theorem traceAt {Λ' : Type} (emitter : Emitter valid output) + (labels : emitter.Label → Λ') (exit : Option Λ') + (target : Λ' → TM2.Stmt Alphabet Λ' State) + (code : ∀ label, target (labels label) = + MachineSubroutine.statement labels exit (emitter.program label)) + (input : Input) (hv : valid input) (base : Tape → List Bool) (frame : Frame input base) : + (advance (TM2.step target))^[emitter.steps input] + (some ⟨some (labels emitter.entry), initialState, base⟩) = + some ⟨exit, initialState, emitTapes base (output input)⟩ := by + have h := MachineSubroutine.trace labels exit emitter.program target code + (emitter.steps input) _ _ (emitter.trace input hv base frame) + simpa only [MachineSubroutine.configuration, MachineSubroutine.label] using h + +end Emitter + +def lookupTapes : Fin 5 → Tape + | 0 => .roots + | 1 => .address + | 2 => .copy + | 3 => .value + | 4 => .scratch + +theorem lookupTapes_injective : Function.Injective lookupTapes := by + intro a b h + fin_cases a <;> fin_cases b <;> simp_all [lookupTapes] + +inductive LookupLabel + | start + | lookup (label : MachinePreservingLookupClean.Label) + | tag | move | finish + deriving DecidableEq, Fintype + +def lookupProgram (address : Nat) : LookupLabel → TM2.Stmt Alphabet LookupLabel State + | .start => Reduction.MachineSubstitution.pushWord .address (encodeWord address).reverse + (.goto fun _ => .lookup (.run .copyFirst)) + | .lookup label => MachinePreservingLookupClean.statement lookupTapes LookupLabel.lookup + (some .tag) label + | .tag => Reduction.MachineSubstitution.pushWord .reversed (encodeWord 5) + (.goto fun _ => .move) + | .move => Reduction.MachineTransfer.loopAt .value .reversed id false .move (some .finish) + | .finish => .pop .address (fun _ _ => initialState) + (.push .count (fun _ => true) .halt) + +def lookupSteps (input : Input) (address : Nat) : Nat := + MachinePreservingLookupClean.steps input.roots address + + (rootLookup input.roots address) + 5 + +private 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 lookupTailTrace (seedAddress : Nat) (input : Input) (address : Nat) + (selected : input.roots[address]? = some (rootLookup input.roots address)) + (base : Tape → List Bool) (frame : Frame input base) : + (advance (TM2.step (lookupProgram seedAddress)))^[ + MachinePreservingLookupClean.steps input.roots address + + rootLookup input.roots address + 4] + (some ⟨some (.lookup (.run .copyFirst)), initialState, + Function.update base .address (encodeWord address)⟩) = + some ⟨none, initialState, + emitTapes base [.input (rootLookup input.roots address)]⟩ := by + let wire := rootLookup input.roots address + let seeded := Function.update base .address (encodeWord address) + let found := Function.update (Function.update base .address (encodeWord 0)) + .value (encodeWord wire) + let tagged := Function.update found .reversed ((encodeWord 5).reverse ++ base .reversed) + let moved := Function.update (Function.update base .address (encodeWord 0)) + .reversed ((encodeWord wire).reverse ++ (encodeWord 5).reverse ++ base .reversed) + have haddress := frame.clean .address (by rfl) + have hvalue := frame.clean .value (by rfl) + have hcopy := frame.clean .copy (by rfl) + have hscratch := frame.clean .scratch (by rfl) + have lookup := MachinePreservingLookupClean.traceAt_fromTapes + lookupTapes lookupTapes_injective LookupLabel.lookup (some .tag) + (lookupProgram seedAddress) (fun _ => rfl) seeded input.roots + (by simpa [seeded, lookupTapes] using frame.rootsWord) + (by simpa [seeded, lookupTapes] using hscratch) + address wire selected [] + (by simp [seeded, lookupTapes]) + (by simpa [seeded, lookupTapes] using hcopy) ((), false) none + have lookupFrame : MachinePreservingLookup.initialTapes lookupTapes seeded 0 [] [] + (encodeWord wire ++ seeded (lookupTapes 3)) = found := by + funext tape + cases tape <;> simp [MachinePreservingLookup.initialTapes, MachineLookup.tapes, + lookupTapes, seeded, found, hvalue, hcopy] + rw [lookupFrame] at lookup + have tag : (advance (TM2.step (lookupProgram seedAddress)))^[1] + (some ⟨some .tag, initialState, found⟩) = + some ⟨some .move, initialState, tagged⟩ := by + change some (TM2.stepAux (lookupProgram seedAddress .tag) initialState found) = _ + simp [lookupProgram, Reduction.MachineSubstitution.stepAux_pushWord, + TM2.stepAux, tagged, found] + have move := Reduction.MachineTransfer.transferAt_fromTapes + (Γ := Alphabet) .value .reversed (by decide) id false LookupLabel.move + (some LookupLabel.finish) (lookupProgram seedAddress) rfl tagged ((), false) none + have valueWord : tagged .value = encodeWord wire := by simp [tagged, found] + have moveFrame : Reduction.MachineTransfer.tapesAt .value .reversed tagged [] + ((tagged .value).reverse.map id ++ tagged .reversed) = moved := by + funext tape + cases tape <;> simp [Reduction.MachineTransfer.tapesAt, tagged, found, moved, + hvalue, List.append_assoc] + rw [moveFrame, valueWord, encodeWord_length] at move + have finish : (advance (TM2.step (lookupProgram seedAddress)))^[1] + (some ⟨some .finish, initialState, moved⟩) = + some ⟨none, initialState, emitTapes base [.input wire]⟩ := by + change some (TM2.stepAux (lookupProgram seedAddress .finish) initialState moved) = _ + simp only [lookupProgram, TM2.stepAux] + congr 2 + funext tape + cases tape <;> simp [moved, emitTapes, tokenBits, tokenWords, Token.words, + encodeWords, encodeWord, haddress, List.reverse_append, List.append_assoc] + have total := trace_trans _ (trace_trans _ lookup tag) move + have result := trace_trans _ total finish + have time : ((MachinePreservingLookupClean.steps input.roots address + 1) + + (wire + 1 + 1)) + 1 = + MachinePreservingLookupClean.steps input.roots address + rootLookup input.roots address + 4 := by + dsimp [wire] + omega + rw [time] at result + exact result + +theorem lookupTrace (input : Input) (address : Nat) + (selected : input.roots[address]? = some (rootLookup input.roots address)) + (base : Tape → List Bool) (frame : Frame input base) : + (advance (TM2.step (lookupProgram address)))^[lookupSteps input address] + (some ⟨some .start, initialState, base⟩) = + some ⟨none, initialState, + emitTapes base [.input (rootLookup input.roots address)]⟩ := by + have haddress := frame.clean .address (by rfl) + have start : (advance (TM2.step (lookupProgram address)))^[1] + (some ⟨some .start, initialState, base⟩) = + some ⟨some (.lookup (.run .copyFirst)), initialState, + Function.update base .address (encodeWord address)⟩ := by + change some (TM2.stepAux (lookupProgram address .start) initialState base) = _ + simp [lookupProgram, Reduction.MachineSubstitution.stepAux_pushWord, + TM2.stepAux, haddress] + have tail := lookupTailTrace address input address selected base frame + have h := trace_trans _ start tail + have time : 1 + (MachinePreservingLookupClean.steps input.roots address + + rootLookup input.roots address + 4) = lookupSteps input address := by + unfold lookupSteps + omega + rw [time] at h + exact h + +theorem lookupSteps_le (input : Input) (address : Nat) + (selected : input.roots[address]? = some (rootLookup input.roots address)) : + lookupSteps input address ≤ 10 * (input.size + 1) := by + have hl := MachinePreservingLookupClean.steps_le input.roots address _ selected + have hw := MachineLookupSpec.output_length_le input.roots address _ selected + rw [encodeWord_length] at hw + unfold lookupSteps Input.size + omega + +def Emitter.root (valid : Input → Prop) (address : Nat) + (present : ∀ input, valid input → + input.roots[address]? = some (rootLookup input.roots address)) : + Emitter valid (fun input => [.input (rootLookup input.roots address)]) where + Label := LookupLabel + finite := inferInstance + entry := .start + program := lookupProgram address + steps input := lookupSteps input address + constant := 10 + trace input hv base frame := lookupTrace input address (present input hv) base frame + bound input hv := lookupSteps_le input address (present input hv) + +def positionDepth : Position → Nat + | .current | .zero => 0 + | .succ p | .pred p => positionDepth p + 1 + +theorem position_le (p : Position) (cursor : Nat) : + p.eval cursor ≤ cursor + positionDepth p := by + induction p with + | current => simp [Position.eval, positionDepth] + | zero => simp [Position.eval, positionDepth] + | succ p ih => simp only [Position.eval, positionDepth]; omega + | pred p ih => simp only [Position.eval, positionDepth]; omega + +structure Selector (predicate : Input → Bool) where + Label : Type + finite : Fintype Label + entry : Label + program : Label → TM2.Stmt Alphabet Label State + steps : Input → Nat + constant : Nat + trace : ∀ (input : Input) (base : Tape → List Bool), Frame input base → + (advance (TM2.step program))^[steps input] + (some ⟨some entry, initialState, base⟩) = + some ⟨none, (((), predicate input), none), base⟩ + bound : ∀ input, steps input ≤ constant * (input.size + 1) + +attribute [instance] Selector.finite + +def compareTape : Fin 4 → Tape + | 0 => .position + | 1 => .capacity + | 2 => .saveLeft + | 3 => .saveRight + +def compareSlots : Fin 4 ↪ Tape where + toFun := compareTape + inj' := by intro a b h; fin_cases a <;> fin_cases b <;> simp_all [compareTape] + +@[simp] theorem compareSlots_apply (i : Fin 4) : compareSlots i = compareTape i := rfl + +inductive TestLabel + | position (label : PositionMachine.Label) + | compare (label : MachineUnaryLessAt.Label) + | atZero | drain + deriving DecidableEq, Fintype + +def testPredicate (within : Bool) (p : Position) (input : Input) : Bool := + if within then decide (p.eval input.cursor < input.capacity) + else decide (p.eval input.cursor = 0) + +def testProgram (within : Bool) (p : Position) : + TestLabel → TM2.Stmt Alphabet TestLabel State + | .position label => PositionMachine.statement .cursor .scratch .position p + TestLabel.position (some (if within then .compare .scan else .atZero)) label + | .compare label => MachineUnaryLessAt.statement compareSlots TestLabel.compare + (some .drain) label + | .atZero => .peek .position (fun _ head => (((), !(head.getD false)), none)) + (.goto fun _ => .drain) + | .drain => MachineDrain.drain .position .drain none + +def testSteps (within : Bool) (p : Position) (input : Input) : Nat := + PositionMachine.steps p input.cursor + + (if within then MachineUnaryLessAt.steps (p.eval input.cursor) input.capacity else 1) + + (p.eval input.cursor + 2) + +theorem testTrace (within : Bool) (p : Position) (input : Input) + (base : Tape → List Bool) (frame : Frame input base) : + (advance (TM2.step (testProgram within p)))^[testSteps within p input] + (some ⟨some (.position .start), initialState, base⟩) = + some ⟨none, (((), testPredicate within p input), none), base⟩ := by + let prepared := Function.update base .position (encodeWord (p.eval input.cursor)) + have hp := frame.clean .position (by rfl) + have hs := frame.clean .scratch (by rfl) + have position := PositionMachine.positionTrace .cursor .scratch .position + (by decide) (by decide) (by decide) p TestLabel.position + (some (if within then .compare .scan else .atZero)) (testProgram within p) + (fun _ => rfl) base input.cursor [] (by simpa using frame.cursorWord) hs ((), false) none + simp only [hp, List.append_nil] at position + have test : (advance (TM2.step (testProgram within p)))^[ + if within then MachineUnaryLessAt.steps (p.eval input.cursor) input.capacity else 1] + (some ⟨some (if within then .compare .scan else .atZero), initialState, prepared⟩) = + some ⟨some .drain, (((), testPredicate within p input), none), prepared⟩ := by + cases within with + | false => + change some (TM2.stepAux (testProgram false p .atZero) initialState prepared) = _ + cases hv : p.eval input.cursor <;> + simp [testProgram, testPredicate, TM2.stepAux, prepared, hv, encodeWord, + List.replicate_succ] + | true => + have hl := frame.clean .saveLeft (by rfl) + have hr := frame.clean .saveRight (by rfl) + have cmp := MachineUnaryLessAt.lessThanTrace compareSlots TestLabel.compare + (some TestLabel.drain) (testProgram true p) (fun _ => rfl) prepared + (p.eval input.cursor) input.capacity [] [] + (by simp [prepared, compareSlots_apply, compareTape]) + (by simpa [prepared, compareSlots_apply, compareTape] using frame.capacityWord) + (by simpa [prepared, compareSlots_apply, compareTape] using hl) + (by simpa [prepared, compareSlots_apply, compareTape] using hr) () false none + simpa [testPredicate, initialState] using cmp + have drain := MachineDrain.drainTrace .position TestLabel.drain none + (testProgram within p) rfl base (encodeWord (p.eval input.cursor)) + ((), testPredicate within p input) none + have finish : Function.update base .position [] = base := by + rw [← hp, Function.update_eq_self] + rw [encodeWord_length, finish] at drain + exact trace_trans _ (trace_trans _ position test) drain + +theorem testSteps_le (within : Bool) (p : Position) (input : Input) : + testSteps within p input ≤ (10 + 4 * positionDepth p) * (input.size + 1) := by + have he := PositionMachine.steps_le_time p input.cursor + simp only [PositionMachine.timePolynomial, Polynomial.eval_add, + Polynomial.eval_mul, Polynomial.eval_C, Polynomial.eval_X] at he + have hp := position_le p input.cursor + have hn := Nat.min_le_left (p.eval input.cursor) input.capacity + have hs : input.cursor ≤ input.size := by simp [Input.size]; omega + have hd : positionDepth p ≤ positionDepth p * (input.size + 1) := by + exact Nat.le_mul_of_pos_right _ (Nat.succ_pos _) + cases within <;> simp only [testSteps, Bool.false_eq_true, + ite_false, ite_true, MachineUnaryLessAt.steps] <;> nlinarith + +def Selector.positionTest (within : Bool) (p : Position) : Selector (testPredicate within p) where + Label := TestLabel + finite := inferInstance + entry := .position .start + program := testProgram within p + steps := testSteps within p + constant := 10 + 4 * positionDepth p + trace := testTrace within p + bound := testSteps_le within p + +inductive AffineLabel + | position (label : PositionMachine.Label) + | seed | scan | restore | drain + | lookup (label : LookupLabel) + deriving DecidableEq, Fintype + +def affineProgram (p : Position) (coefficient offset : Nat) : + AffineLabel → TM2.Stmt Alphabet AffineLabel State + | .position label => PositionMachine.statement .cursor .scratch .position p + AffineLabel.position (some .seed) label + | .seed => MachineUnaryAffineAt.seed .address offset .scan + | .scan => MachineUnaryAffineAt.scan .position .scratch .address coefficient .scan .restore + | .restore => Reduction.MachineTransfer.loopAt .scratch .position id false .restore (some .drain) + | .drain => MachineDrain.drain .position .drain (some (.lookup (.lookup (.run .copyFirst)))) + | .lookup label => MachineSubroutine.statement AffineLabel.lookup none (lookupProgram 0 label) + +def affineAddress (p : Position) (coefficient offset : Nat) (input : Input) : Nat := + coefficient * p.eval input.cursor + offset + +def affineSteps (p : Position) (coefficient offset : Nat) (input : Input) : Nat := + PositionMachine.steps p input.cursor + (2 * (p.eval input.cursor + 1) + 1) + + (p.eval input.cursor + 2) + + (MachinePreservingLookupClean.steps input.roots (affineAddress p coefficient offset input) + + rootLookup input.roots (affineAddress p coefficient offset input) + 4) + +theorem affineTrace (p : Position) (coefficient offset : Nat) (input : Input) + (present : input.roots[affineAddress p coefficient offset input]? = + some (rootLookup input.roots (affineAddress p coefficient offset input))) + (base : Tape → List Bool) (frame : Frame input base) : + (advance (TM2.step (affineProgram p coefficient offset)))^[affineSteps p coefficient offset input] + (some ⟨some (.position .start), initialState, base⟩) = + some ⟨none, initialState, emitTapes base + [.input (rootLookup input.roots (affineAddress p coefficient offset input))]⟩ := by + let pos := p.eval input.cursor + let addr := affineAddress p coefficient offset input + let prepared := Function.update base .position (encodeWord pos) + let addressed := Function.update base .address (encodeWord addr) + have hp := frame.clean .position (by rfl) + have ha := frame.clean .address (by rfl) + have hs := frame.clean .scratch (by rfl) + have position := PositionMachine.positionTrace .cursor .scratch .position + (by decide) (by decide) (by decide) p AffineLabel.position (some .seed) + (affineProgram p coefficient offset) (fun _ => rfl) base input.cursor [] + (by simpa using frame.cursorWord) hs ((), false) none + simp only [hp, List.append_nil] at position + have address := MachineUnaryAffineAt.seededAffineTrace .position .scratch .address + (by decide) (by decide) (by decide) coefficient offset AffineLabel.seed + AffineLabel.scan AffineLabel.restore (some AffineLabel.drain) + (affineProgram p coefficient offset) rfl rfl rfl prepared pos [] + (by simp [prepared]) (by simpa [prepared] using hs) ((), false) none + have haddressed : Function.update prepared .address + (encodeWord (coefficient * pos + offset) ++ prepared .address) = + Function.update addressed .position (encodeWord pos) := by + funext tape + cases tape <;> simp [prepared, addressed, addr, affineAddress, pos, ha] + rw [haddressed] at address + have drain := MachineDrain.drainTrace .position AffineLabel.drain + (some (.lookup (.lookup (.run .copyFirst)))) (affineProgram p coefficient offset) + rfl addressed (encodeWord pos) ((), false) none + have hclean : Function.update addressed .position [] = addressed := by + have h : addressed .position = [] := by simpa [addressed] using hp + rw [← h, Function.update_eq_self] + rw [encodeWord_length, hclean] at drain + have source := lookupTailTrace 0 input addr present base frame + have lookup := MachineSubroutine.trace AffineLabel.lookup none (lookupProgram 0) + (affineProgram p coefficient offset) (fun _ => rfl) + (MachinePreservingLookupClean.steps input.roots addr + rootLookup input.roots addr + 4) + _ _ source + simp only [MachineSubroutine.configuration, MachineSubroutine.label] at lookup + exact trace_trans _ (trace_trans _ (trace_trans _ position address) drain) lookup + +theorem affineSteps_le (p : Position) (coefficient offset : Nat) (input : Input) + (present : input.roots[affineAddress p coefficient offset input]? = + some (rootLookup input.roots (affineAddress p coefficient offset input))) : + affineSteps p coefficient offset input ≤ (30 + 3 * positionDepth p) * (input.size + 1) := by + have he := PositionMachine.steps_le_time p input.cursor + simp only [PositionMachine.timePolynomial, Polynomial.eval_add, + Polynomial.eval_mul, Polynomial.eval_C, Polynomial.eval_X] at he + have hp := position_le p input.cursor + have hl := MachinePreservingLookupClean.steps_le input.roots + (affineAddress p coefficient offset input) _ present + have hw := MachineLookupSpec.output_length_le input.roots + (affineAddress p coefficient offset input) _ present + rw [encodeWord_length] at hw + have hs : input.cursor + (encodeWords input.roots).length ≤ input.size := by + simp [Input.size] + have hd : positionDepth p ≤ positionDepth p * (input.size + 1) := + Nat.le_mul_of_pos_right _ (Nat.succ_pos _) + unfold affineSteps + nlinarith + +def Emitter.affineRoot (valid : Input → Prop) (p : Position) (coefficient offset : Nat) + (present : ∀ input, valid input → + input.roots[affineAddress p coefficient offset input]? = + some (rootLookup input.roots (affineAddress p coefficient offset input))) : + Emitter valid (fun input => [.input + (rootLookup input.roots (affineAddress p coefficient offset input))]) where + Label := AffineLabel + finite := inferInstance + entry := .position .start + program := affineProgram p coefficient offset + steps := affineSteps p coefficient offset + constant := 30 + 3 * positionDepth p + trace input hv base frame := affineTrace p coefficient offset input (present input hv) base frame + bound input hv := affineSteps_le p coefficient offset input (present input hv) + +namespace Emitter + +variable {valid validLeft validRight : Input → Prop} +variable {yes no : Input → List Token} {predicate : Input → Bool} + +abbrev ChoiceLabel (test : Selector predicate) (left : Emitter validLeft yes) + (right : Emitter validRight no) := test.Label ⊕ (Unit ⊕ (left.Label ⊕ right.Label)) + +def choiceProgram (test : Selector predicate) (left : Emitter validLeft yes) + (right : Emitter validRight no) : ChoiceLabel test left right → + TM2.Stmt Alphabet (ChoiceLabel test left right) State + | .inl l => MachineSubroutine.statement Sum.inl (some (.inr (.inl ()))) (test.program l) + | .inr (.inl _) => .branch (fun s => s.1.2) + (.load (fun _ => initialState) (.goto fun _ => .inr (.inr (.inl left.entry)))) + (.load (fun _ => initialState) (.goto fun _ => .inr (.inr (.inr right.entry)))) + | .inr (.inr (.inl l)) => MachineSubroutine.statement + (fun label => .inr (.inr (.inl label))) none (left.program l) + | .inr (.inr (.inr l)) => MachineSubroutine.statement + (fun label => .inr (.inr (.inr label))) none (right.program l) + +def choice (test : Selector predicate) (left : Emitter validLeft yes) + (right : Emitter validRight no) + (leftValid : ∀ input, valid input → predicate input = true → validLeft input) + (rightValid : ∀ input, valid input → predicate input = false → validRight input) : + Emitter valid (fun input => if predicate input then yes input else no input) where + Label := ChoiceLabel test left right + finite := inferInstance + entry := .inl test.entry + program := choiceProgram test left right + steps input := test.steps input + 1 + + (if predicate input then left.steps input else right.steps input) + constant := test.constant + 1 + left.constant + right.constant + trace input hv base frame := by + have ht := MachineSubroutine.trace Sum.inl (some (.inr (.inl ()))) + test.program (choiceProgram test left right) (fun _ => rfl) + (test.steps input) _ _ (test.trace input base frame) + simp only [MachineSubroutine.configuration, MachineSubroutine.label] at ht + cases hpred : predicate input with + | false => + have dispatch : (advance (TM2.step (choiceProgram test left right)))^[1] + (some ⟨some (.inr (.inl ())), (((), predicate input), none), base⟩) = + some ⟨some (.inr (.inr (.inr right.entry))), initialState, base⟩ := by + change some (TM2.stepAux _ _ _) = _ + simp [choiceProgram, TM2.stepAux, hpred] + have body := MachineSubroutine.trace (fun label => .inr (.inr (.inr label))) none + right.program (choiceProgram test left right) (fun _ => rfl) + (right.steps input) _ _ (right.trace input (rightValid input hv hpred) base frame) + simp only [MachineSubroutine.configuration, MachineSubroutine.label] at body + simpa only [hpred, Bool.false_eq_true, ite_false] using + trace_trans _ (trace_trans _ ht dispatch) body + | true => + have dispatch : (advance (TM2.step (choiceProgram test left right)))^[1] + (some ⟨some (.inr (.inl ())), (((), predicate input), none), base⟩) = + some ⟨some (.inr (.inr (.inl left.entry))), initialState, base⟩ := by + change some (TM2.stepAux _ _ _) = _ + simp [choiceProgram, TM2.stepAux, hpred] + have body := MachineSubroutine.trace (fun label => .inr (.inr (.inl label))) none + left.program (choiceProgram test left right) (fun _ => rfl) + (left.steps input) _ _ (left.trace input (leftValid input hv hpred) base frame) + simp only [MachineSubroutine.configuration, MachineSubroutine.label] at body + simpa only [hpred, ite_true] using + trace_trans _ (trace_trans _ ht dispatch) body + bound input hv := by + have ht := test.bound input + have hs : 0 < input.size + 1 := Nat.succ_pos _ + cases hpred : predicate input with + | false => + have hr := right.bound input (rightValid input hv hpred) + simp only [Bool.false_eq_true, ite_false] + nlinarith + | true => + have hl := left.bound input (leftValid input hv hpred) + simp only [ite_true] + nlinarith + +end Emitter + + +variable {K Λ σ : Type} {Γ : K → Type} [∀ k, DecidableEq (Γ k)] +variable [DecidableEq K] [Fintype σ] [DecidableEq σ] +variable [∀ k, Fintype (Γ k)] [DecidableEq Λ] [Fintype Λ] + +def RootsValid (indexing : ConfigIndex.Indexing Γ Λ σ) (input : Input) : Prop := + indexing.width input.capacity ≤ input.roots.length + +def termTokens (indexing : ConfigIndex.Indexing Γ Λ σ) (term : Term Γ σ) + (input : Input) : List Token := + term.tokens indexing input.roots input.capacity input.cursor + +def compileCell (indexing : ConfigIndex.Indexing Γ Λ σ) (k : K) (p : Position) + (symbol : Option (Γ k)) : + Emitter (RootsValid indexing) (termTokens indexing (.cell k p symbol)) := by + let leftValid : Input → Prop := fun input => + RootsValid indexing input ∧ p.eval input.cursor < input.capacity + let addressOffset := indexing.labelCount + indexing.stateCount + (indexing.symbols ⟨k, symbol⟩).val + let left := Emitter.affineRoot leftValid p indexing.symbolCount addressOffset (by + intro input hv + apply rootLookup_present indexing input.roots input.capacity hv.1 + simpa only [affineAddress, addressOffset, Nat.mul_comm, Nat.add_assoc, + Nat.add_left_comm, Nat.add_comm] using + cellAddress_lt_width indexing input.capacity k (p.eval input.cursor) symbol hv.2) + let right := Emitter.literal (RootsValid indexing) [.const (decide ((none : Option (Γ k)) = symbol))] + let branch := Emitter.choice (Selector.positionTest true p) left right + (valid := RootsValid indexing) + (fun input hv ht => ⟨hv, by simpa [testPredicate] using ht⟩) + (fun _ hv _ => hv) + exact branch.congr (fun input => by + by_cases hp : p.eval input.cursor < input.capacity <;> + simp [termTokens, Term.tokens, testPredicate, hp, affineAddress, addressOffset, + Nat.mul_comm, Nat.add_assoc, Nat.add_left_comm]) + +def compile (indexing : ConfigIndex.Indexing Γ Λ σ) : + (term : Term Γ σ) → Emitter (RootsValid indexing) (termTokens indexing term) + | .state v => Emitter.root (RootsValid indexing) (indexing.labelCount + (indexing.states v).val) + (fun input hv => rootLookup_present indexing input.roots input.capacity hv _ + (stateAddress_lt_width indexing input.capacity v)) + | .cell k p a => compileCell indexing k p a + | .const b => Emitter.literal (RootsValid indexing) [.const b] + | .not e => ((compile indexing e).seq (Emitter.literal (RootsValid indexing) [.not])).congr + (fun input => rfl) + | .and e f => ((compile indexing e).seq + ((compile indexing f).seq (Emitter.literal (RootsValid indexing) [.and]))).congr + (fun input => by simp [termTokens, Term.tokens, List.append_assoc]) + | .or e f => ((compile indexing e).seq + ((compile indexing f).seq (Emitter.literal (RootsValid indexing) [.or]))).congr + (fun input => by simp [termTokens, Term.tokens, List.append_assoc]) + | .atZero p yes no => + (Emitter.choice (Selector.positionTest false p) (compile indexing yes) (compile indexing no) + (fun _ hv _ => hv) (fun _ hv _ => hv)).congr + (fun input => by simp [termTokens, Term.tokens, testPredicate]) + | .within p yes no => + (Emitter.choice (Selector.positionTest true p) (compile indexing yes) (compile indexing no) + (fun _ hv _ => hv) (fun _ hv _ => hv)).congr + (fun input => by simp [termTokens, Term.tokens, testPredicate]) + +noncomputable def timePolynomial (indexing : ConfigIndex.Indexing Γ Λ σ) (term : Term Γ σ) : + Polynomial Nat := Polynomial.C (compile indexing term).constant * (Polynomial.X + 1) + +def termInPolynomialTime (indexing : ConfigIndex.Indexing Γ Λ σ) (term : Term Γ σ) + (input : Input) (valid : RootsValid indexing input) (base : Tape → List Bool) + (frame : Frame input base) : + StateTransition.EvalsToInTime (compile indexing term).machine.step + ⟨some (compile indexing term).entry, initialState, base⟩ + (some ⟨none, initialState, emitTapes base + (term.tokens indexing input.roots input.capacity input.cursor)⟩) + ((timePolynomial indexing term).eval input.size) where + steps := (compile indexing term).steps input + evals_in_steps := (compile indexing term).trace input valid base frame + steps_le_m := by + simpa only [timePolynomial, Polynomial.eval_mul, Polynomial.eval_C, + Polynomial.eval_add, Polynomial.eval_X, Polynomial.eval_one] using + (compile indexing term).bound input valid + +def globalTokens (indexing : ConfigIndex.Indexing Γ Λ σ) + (term : Global (Γ := Γ) (Λ := Λ) (σ := σ)) (input : Input) : List Token := + term.tokens indexing input.roots input.capacity input.cursor + +def compileGlobal (indexing : ConfigIndex.Indexing Γ Λ σ) : + (term : Global (Γ := Γ) (Λ := Λ) (σ := σ)) → + Emitter (RootsValid indexing) (globalTokens indexing term) + | .label label => Emitter.root (RootsValid indexing) (indexing.labels label).val + (fun input hv => rootLookup_present indexing input.roots input.capacity hv _ + (labelAddress_lt_width indexing input.capacity label)) + | .data term => compile indexing term + | .const b => Emitter.literal (RootsValid indexing) [.const b] + | .and e f => ((compileGlobal indexing e).seq + ((compileGlobal indexing f).seq (Emitter.literal (RootsValid indexing) [.and]))).congr + (fun input => by simp [globalTokens, Global.tokens, List.append_assoc]) + | .or e f => ((compileGlobal indexing e).seq + ((compileGlobal indexing f).seq (Emitter.literal (RootsValid indexing) [.or]))).congr + (fun input => by simp [globalTokens, Global.tokens, List.append_assoc]) + +def globalInLinearTime (indexing : ConfigIndex.Indexing Γ Λ σ) + (term : Global (Γ := Γ) (Λ := Λ) (σ := σ)) + (input : Input) (valid : RootsValid indexing input) (base : Tape → List Bool) + (frame : Frame input base) : + StateTransition.EvalsToInTime (compileGlobal indexing term).machine.step + ⟨some (compileGlobal indexing term).entry, initialState, base⟩ + (some ⟨none, initialState, emitTapes base + (term.tokens indexing input.roots input.capacity input.cursor)⟩) + ((compileGlobal indexing term).constant * (input.size + 1)) where + steps := (compileGlobal indexing term).steps input + evals_in_steps := (compileGlobal indexing term).trace input valid base frame + steps_le_m := (compileGlobal indexing term).bound input valid + + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.TermMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/TransitionIteration.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/TransitionIteration.lean new file mode 100644 index 0000000000000000000000000000000000000000..f43db0be1d5014a801a322a87753cba7baaac87f --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/TransitionIteration.lean @@ -0,0 +1,307 @@ +import OAI.Computability.PerfectCompleteness.Machines.ForestStage +import OAI.Computability.PerfectCompleteness.Machines.InitializationStageLemmas +import OAI.Computability.PerfectCompleteness.Machines.ProducerInvariant +import OAI.Computability.PerfectCompleteness.Machines.TransitionMachine + +namespace OAI + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.TransitionIteration + + +open Turing MachineComposition StatementCircuit CircuitBatch TransitionTemplate + +open TransitionArena + +section Transition + +variable {K Λ σ : Type} {Γ : K → Type} +variable [DecidableEq K] [Fintype σ] [DecidableEq σ] +variable [∀ k, DecidableEq (Γ k)] [∀ k, Fintype (Γ k)] [DecidableEq Λ] [Fintype Λ] + +noncomputable def tokens (indexing : ConfigIndex.Indexing Γ Λ σ) + (machineProgram : Λ → TM2.Stmt Γ Λ σ) (S : Nat) + (snapshot : ProducerInvariant.Snapshot) : List PostfixModel.Token := + ProducerInvariant.transitionTokens indexing machineProgram S snapshot.roots + +noncomputable def emitSteps (indexing : ConfigIndex.Indexing Γ Λ σ) + (machineProgram : Λ → TM2.Stmt Γ Λ σ) (S : Nat) + (snapshot : ProducerInvariant.Snapshot) : Nat := + TransitionMachine.steps indexing (TransitionMachine.transitionPlan indexing machineProgram) + (termInput S snapshot) + +theorem emitTraceAt {Caller : Type} (indexing : ConfigIndex.Indexing Γ Λ σ) + (machineProgram : Λ → TM2.Stmt Γ Λ σ) + (labels : TransitionMachine.Label indexing (TransitionMachine.transitionPlan indexing machineProgram) → Caller) + (exit : Option Caller) (target : Caller → TM2.Stmt Alphabet Caller State) + (code : ∀ label, target (labels label) = ForestPlacement.statement termPorts labels exit + (TransitionMachine.program indexing (TransitionMachine.transitionPlan indexing machineProgram) label)) + (base : Tape → List Bool) (S remaining : Nat) (snapshot : ProducerInvariant.Snapshot) + (valid : indexing.width S + 1 ≤ snapshot.roots.length) : + (advance (TM2.step target))^[emitSteps indexing machineProgram S snapshot] + (some ⟨some (labels (.prefix (TransitionMachine.compilePrefix indexing + (TransitionMachine.transitionPlan indexing machineProgram).prefix).entry)), + TermMachine.initialState, tapes base S remaining snapshot⟩) = + some ⟨exit, TermMachine.initialState, + preparedTapes base S remaining snapshot (tokens indexing machineProgram S snapshot)⟩ := by + let input := termInput S snapshot + let plan := TransitionMachine.transitionPlan indexing machineProgram + have hv : TransitionMachine.Valid indexing plan input := by + simpa [TransitionMachine.Valid, plan, TransitionMachine.transitionPlan, input, termInput] using valid + have sourceTrace := TransitionMachine.fullTrace indexing plan input hv + (fun tape => tapes base S remaining snapshot (termPorts tape)) + (termFrame base S remaining snapshot) + have placed := ForestPlacement.trace termPorts labels exit (tapes base S remaining snapshot) + (TransitionMachine.program indexing plan) target code + (TransitionMachine.steps indexing plan input) _ _ sourceTrace + simp only [ForestPlacement.configuration, ForestPlacement.placedLabel, + ForestPlacement.fill_self] at placed + rw [TransitionMachine.transition_outputTokens, place_emitTapes] at placed + simpa only [emitSteps, tokens, ProducerInvariant.transitionTokens, input, termInput, plan] + using placed + +abbrev Label (indexing : ConfigIndex.Indexing Γ Λ σ) + (machineProgram : Λ → TM2.Stmt Γ Λ σ) := + Unit ⊕ (TransitionMachine.Label indexing + (TransitionMachine.transitionPlan indexing machineProgram) ⊕ ForestStage.Label) + +def entry (indexing : ConfigIndex.Indexing Γ Λ σ) + (machineProgram : Λ → TM2.Stmt Γ Λ σ) : Label indexing machineProgram := .inl () + +def emitLabel (indexing : ConfigIndex.Indexing Γ Λ σ) + (machineProgram : Λ → TM2.Stmt Γ Λ σ) + (label : TransitionMachine.Label indexing (TransitionMachine.transitionPlan indexing machineProgram)) : + Label indexing machineProgram := .inr (.inl label) + +def lowerLabel (indexing : ConfigIndex.Indexing Γ Λ σ) + (machineProgram : Λ → TM2.Stmt Γ Λ σ) (label : ForestStage.Label) : + Label indexing machineProgram := .inr (.inr label) + +noncomputable def emitEntry (indexing : ConfigIndex.Indexing Γ Λ σ) + (machineProgram : Λ → TM2.Stmt Γ Λ σ) : Label indexing machineProgram := + emitLabel indexing machineProgram (.prefix (TransitionMachine.compilePrefix indexing + (TransitionMachine.transitionPlan indexing machineProgram).prefix).entry) + +def countdownStatement {Caller : Type} (next : Caller) : TM2.Stmt Alphabet Caller State := + .peek (.inr .countdown) (fun _ head => (((), head.getD false), none)) + (.branch (fun state => state.1.2) + (.pop (.inr .countdown) (fun _ _ => TermMachine.initialState) (.goto fun _ => next)) + (.pop (.inr .countdown) (fun _ _ => TermMachine.initialState) .halt)) + +noncomputable def program (indexing : ConfigIndex.Indexing Γ Λ σ) + (machineProgram : Λ → TM2.Stmt Γ Λ σ) : + Label indexing machineProgram → TM2.Stmt Alphabet (Label indexing machineProgram) State + | .inl _ => countdownStatement (emitEntry indexing machineProgram) + | .inr (.inl label) => ForestPlacement.statement termPorts (emitLabel indexing machineProgram) + (some (lowerLabel indexing machineProgram .reverseTokens)) + (TransitionMachine.program indexing (TransitionMachine.transitionPlan indexing machineProgram) label) + | .inr (.inr label) => ForestStage.statement (σ := Unit) forestPorts + (lowerLabel indexing machineProgram) (some (entry indexing machineProgram)) label + +noncomputable def machine (indexing : ConfigIndex.Indexing Γ Λ σ) + (machineProgram : Λ → TM2.Stmt Γ Λ σ) : FinTM2 where + K := Tape + k₀ := .inr .raw + k₁ := .inl .records + Γ := Alphabet + Λ := Label indexing machineProgram + main := entry indexing machineProgram + σ := State + initialState := TermMachine.initialState + m := program indexing machineProgram + +theorem guardZero (indexing : ConfigIndex.Indexing Γ Λ σ) + (machineProgram : Λ → TM2.Stmt Γ Λ σ) (base : Tape → List Bool) + (S : Nat) (snapshot : ProducerInvariant.Snapshot) : + (advance (TM2.step (program indexing machineProgram)))^[1] + (some ⟨some (entry indexing machineProgram), TermMachine.initialState, tapes base S 0 snapshot⟩) = + some ⟨none, TermMachine.initialState, finishTapes base S snapshot⟩ := by + change some (TM2.stepAux (program indexing machineProgram (entry indexing machineProgram)) + TermMachine.initialState (tapes base S 0 snapshot)) = _ + simp [program, entry, countdownStatement, TM2.stepAux, tapes, encodeWord, finishTapes] + +theorem guardSucc (indexing : ConfigIndex.Indexing Γ Λ σ) + (machineProgram : Λ → TM2.Stmt Γ Λ σ) (base : Tape → List Bool) + (S remaining : Nat) (snapshot : ProducerInvariant.Snapshot) : + (advance (TM2.step (program indexing machineProgram)))^[1] + (some ⟨some (entry indexing machineProgram), TermMachine.initialState, + tapes base S (remaining + 1) snapshot⟩) = + some ⟨some (emitEntry indexing machineProgram), TermMachine.initialState, + tapes base S remaining snapshot⟩ := by + change some (TM2.stepAux (program indexing machineProgram (entry indexing machineProgram)) + TermMachine.initialState (tapes base S (remaining + 1) snapshot)) = _ + simp only [program, entry, countdownStatement, TM2.stepAux] + have hhead : (tapes base S (remaining + 1) snapshot (.inr .countdown)).head? = some true := by + simp [tapes, encodeWord, List.replicate_succ] + rw [hhead] + simpa only [Option.getD_some, Bool.cond_true] using + congrArg (fun stack => some (TM2.Cfg.mk (some (emitEntry indexing machineProgram)) + TermMachine.initialState stack)) (tapes_countdown_tail base S remaining snapshot) + +variable {inputs : Nat} + +noncomputable def stageGates (indexing : ConfigIndex.Indexing Γ Λ σ) + (machineProgram : Λ → TM2.Stmt Γ Λ σ) (S : Nat) + (frame : CircuitBatch.Frame inputs (indexing.width S + 1)) : List Gate := + Batch.gates (fun i => (frame.wires i).val) (ProducerInvariant.next frame) + (List.ofFn (ProducerInvariant.stepExpressions indexing machineProgram S)) + +noncomputable def lowerSteps (indexing : ConfigIndex.Indexing Γ Λ σ) + (machineProgram : Λ → TM2.Stmt Γ Λ σ) (S : Nat) + (frame : CircuitBatch.Frame inputs (indexing.width S + 1)) : Nat := + ForestStage.steps (tokens indexing machineProgram S (ProducerInvariant.snapshot frame)) + (ProducerInvariant.next frame) + (ProducerInvariant.rootValues + (frame.step (ProducerInvariant.stepExpressions indexing machineProgram S))).reverse + (stageGates indexing machineProgram S frame) (encodeWords (ProducerInvariant.rootValues frame)) + +noncomputable def stageSteps (indexing : ConfigIndex.Indexing Γ Λ σ) + (machineProgram : Λ → TM2.Stmt Γ Λ σ) (S : Nat) + (frame : CircuitBatch.Frame inputs (indexing.width S + 1)) : Nat := + emitSteps indexing machineProgram S (ProducerInvariant.snapshot frame) + + lowerSteps indexing machineProgram S frame + +noncomputable def steps (indexing : ConfigIndex.Indexing Γ Λ σ) + (machineProgram : Λ → TM2.Stmt Γ Λ σ) (S : Nat) : + CircuitBatch.Frame inputs (indexing.width S + 1) → Nat → Nat + | _, 0 => 1 + | frame, remaining + 1 => 1 + stageSteps indexing machineProgram S frame + + steps indexing machineProgram S + (frame.step (ProducerInvariant.stepExpressions indexing machineProgram S)) remaining + +private theorem chain {A : Type*} {f : A → A} {x y z : A} {n m : Nat} + (first : f^[n] x = y) (second : f^[m] y = z) : f^[n + m] x = z := by + rw [Nat.add_comm n m, Function.iterate_add_apply, first, second] + +theorem place_forest_initial (base : Tape → List Bool) (S remaining : Nat) + (snapshot : ProducerInvariant.Snapshot) (ts : List PostfixModel.Token) : + ForestPlacement.fill forestPorts (tapes base S remaining snapshot) + (ForestStage.initialLocal snapshot.current ts snapshot.reversedRecords + (encodeWords snapshot.roots)) = preparedTapes base S remaining snapshot ts := by + rw [fill_forest] + funext tape + cases tape with + | inl tape => + cases tape with + | lower tape => cases tape <;> simp [ForestStage.initialLocal, preparedTapes, tapes] + | tokens => simp [ForestStage.initialLocal, preparedTapes] + | records => simp [ForestStage.initialLocal, preparedTapes, tapes] + | rootTable => simp [ForestStage.initialLocal, preparedTapes, tapes] + | inr tape => cases tape <;> simp [preparedTapes, tapes] + +theorem place_forest_final {oldWidth newWidth : Nat} + (base : Tape → List Bool) (S remaining : Nat) (frame : Frame inputs oldWidth) + (es : Fin newWidth → Expr (Fin oldWidth)) : + ForestPlacement.fill forestPorts (tapes base S remaining (ProducerInvariant.snapshot frame)) + (ForestStage.finalLocal (ProducerInvariant.next (frame.step es)) + (ProducerInvariant.rootValues (frame.step es)).reverse + (recordsBits (gateRecords + (ProducerInvariant.next frame) + (Batch.gates (fun i => (frame.wires i).val) (ProducerInvariant.next frame) (List.ofFn es)))) + (ProducerInvariant.snapshot frame).reversedRecords) = + tapes base S remaining (ProducerInvariant.snapshot (frame.step es)) := by + have hr := congrArg List.reverse (ProducerInvariant.recordBits_step frame es) + rw [List.reverse_append] at hr + rw [fill_forest] + funext tape + cases tape with + | inl tape => + cases tape with + | lower tape => cases tape <;> rfl + | tokens => rfl + | rootTable => simp only [ForestStage.finalLocal, List.reverse_reverse]; rfl + | records => exact hr.symm + | inr tape => cases tape <;> rfl + +theorem stageTrace (indexing : ConfigIndex.Indexing Γ Λ σ) + (machineProgram : Λ → TM2.Stmt Γ Λ σ) (base : Tape → List Bool) + (S remaining : Nat) (frame : Frame inputs (indexing.width S + 1)) : + (advance (TM2.step (program indexing machineProgram)))^[ + stageSteps indexing machineProgram S frame] + (some ⟨some (emitEntry indexing machineProgram), TermMachine.initialState, + tapes base S remaining (ProducerInvariant.snapshot frame)⟩) = + some ⟨some (entry indexing machineProgram), TermMachine.initialState, + tapes base S remaining (ProducerInvariant.snapshot + (frame.step (ProducerInvariant.stepExpressions indexing machineProgram S)))⟩ := by + let es := ProducerInvariant.stepExpressions indexing machineProgram S + have emitted := emitTraceAt indexing machineProgram (emitLabel indexing machineProgram) + (some (lowerLabel indexing machineProgram .reverseTokens)) (program indexing machineProgram) + (fun _ => rfl) base S remaining (ProducerInvariant.snapshot frame) + (by simp only [ProducerInvariant.snapshot, List.length_ofFn]; exact le_rfl) + have compiled := ForestStage.traceAt (σ := Unit) forestPorts (lowerLabel indexing machineProgram) + (some (entry indexing machineProgram)) (program indexing machineProgram) (fun _ => rfl) + (tapes base S remaining (ProducerInvariant.snapshot frame)) ((), false) + (tokens indexing machineProgram S (ProducerInvariant.snapshot frame)) + (ProducerInvariant.next frame) (ProducerInvariant.next (frame.step es)) + (ProducerInvariant.rootValues (frame.step es)).reverse (stageGates indexing machineProgram S frame) + (ProducerInvariant.snapshot frame).reversedRecords (encodeWords (ProducerInvariant.rootValues frame)) + (ProducerInvariant.compile_transitionTokens indexing machineProgram S frame) + have initial := place_forest_initial base S remaining (ProducerInvariant.snapshot frame) + (tokens indexing machineProgram S (ProducerInvariant.snapshot frame)) + change ForestPlacement.fill forestPorts (tapes base S remaining (ProducerInvariant.snapshot frame)) + (ForestStage.initialLocal (ProducerInvariant.next frame) + (tokens indexing machineProgram S (ProducerInvariant.snapshot frame)) + (ProducerInvariant.snapshot frame).reversedRecords (encodeWords (ProducerInvariant.rootValues frame))) = _ at initial + rw [initial] at compiled + have final := place_forest_final base S remaining frame es + change ForestPlacement.fill forestPorts (tapes base S remaining (ProducerInvariant.snapshot frame)) + (ForestStage.finalLocal (ProducerInvariant.next (frame.step es)) + (ProducerInvariant.rootValues (frame.step es)).reverse + (recordsBits (gateRecords (ProducerInvariant.next frame) (stageGates indexing machineProgram S frame))) + (ProducerInvariant.snapshot frame).reversedRecords) = _ at final + rw [final] at compiled + simpa only [stageSteps, lowerSteps, emitEntry, es, TermMachine.initialState] + using chain emitted compiled + +theorem repeatTrace (indexing : ConfigIndex.Indexing Γ Λ σ) + (machineProgram : Λ → TM2.Stmt Γ Λ σ) (base : Tape → List Bool) + (S : Nat) (frame : Frame inputs (indexing.width S + 1)) (remaining : Nat) : + (advance (TM2.step (program indexing machineProgram)))^[steps indexing machineProgram S frame remaining] + (some ⟨some (entry indexing machineProgram), TermMachine.initialState, + tapes base S remaining (ProducerInvariant.snapshot frame)⟩) = + some ⟨none, TermMachine.initialState, finishTapes base S (ProducerInvariant.snapshot + (frame.repeat (ProducerInvariant.stepExpressions indexing machineProgram S) remaining))⟩ := by + induction remaining generalizing frame with + | zero => exact guardZero indexing machineProgram base S (ProducerInvariant.snapshot frame) + | succ remaining ih => + have first := chain (guardSucc indexing machineProgram base S remaining (ProducerInvariant.snapshot frame)) + (stageTrace indexing machineProgram base S remaining frame) + have result := chain first (ih (frame.step (ProducerInvariant.stepExpressions indexing machineProgram S))) + simpa only [steps, ProducerInvariant.step_repeat] using result + +noncomputable def repeatInTime (indexing : ConfigIndex.Indexing Γ Λ σ) + (machineProgram : Λ → TM2.Stmt Γ Λ σ) (base : Tape → List Bool) + (S : Nat) (frame : Frame inputs (indexing.width S + 1)) (remaining : Nat) : + StateTransition.EvalsToInTime (machine indexing machineProgram).step + ⟨some (entry indexing machineProgram), TermMachine.initialState, + tapes base S remaining (ProducerInvariant.snapshot frame)⟩ + (some ⟨none, TermMachine.initialState, finishTapes base S (ProducerInvariant.snapshot + (frame.repeat (ProducerInvariant.stepExpressions indexing machineProgram S) remaining))⟩) + (steps indexing machineProgram S frame remaining) where + steps := steps indexing machineProgram S frame remaining + evals_in_steps := repeatTrace indexing machineProgram base S frame remaining + steps_le_m := le_rfl + +theorem repeatTraceAt {Caller : Type} (indexing : ConfigIndex.Indexing Γ Λ σ) + (machineProgram : Λ → TM2.Stmt Γ Λ σ) + (labels : Label indexing machineProgram → Caller) (exit : Option Caller) + (target : Caller → TM2.Stmt Alphabet Caller State) + (code : ∀ label, target (labels label) = + MachineSubroutine.statement labels exit (program indexing machineProgram label)) + (base : Tape → List Bool) (S : Nat) + (frame : Frame inputs (indexing.width S + 1)) (remaining : Nat) : + (advance (TM2.step target))^[steps indexing machineProgram S frame remaining] + (some ⟨some (labels (entry indexing machineProgram)), TermMachine.initialState, + tapes base S remaining (ProducerInvariant.snapshot frame)⟩) = + some ⟨exit, TermMachine.initialState, finishTapes base S (ProducerInvariant.snapshot + (frame.repeat (ProducerInvariant.stepExpressions indexing machineProgram S) remaining))⟩ := by + simpa only [MachineSubroutine.configuration, MachineSubroutine.label] using + MachineSubroutine.trace labels exit (program indexing machineProgram) target code + (steps indexing machineProgram S frame remaining) _ _ + (repeatTrace indexing machineProgram base S frame remaining) + +end Transition + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.TransitionIteration + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/TransitionMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/TransitionMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..faaadfad0c30110e403d11ea2980a42112f5733d --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/TransitionMachine.lean @@ -0,0 +1,552 @@ +import OAI.Computability.PerfectCompleteness.Machines.OutputOrder +import OAI.Computability.PerfectCompleteness.Machines.TermMachine + +namespace OAI + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.TransitionMachine + + +open Turing MachineComposition TransitionTemplate TermMachine PostfixModel + +variable {K Λ σ : Type} {Γ : K → Type} +variable [DecidableEq K] [Fintype σ] [DecidableEq σ] +variable [∀ k, DecidableEq (Γ k)] [∀ k, Fintype (Γ k)] [DecidableEq Λ] [Fintype Λ] + +abbrev Template := Global (Γ := Γ) (Λ := Λ) (σ := σ) + +def listTokens (indexing : ConfigIndex.Indexing Γ Λ σ) + (terms : List (Template (Γ := Γ) (Λ := Λ) (σ := σ))) (input : Input) : List Token := + terms.flatMap fun term => globalTokens indexing term input + +def compileList (indexing : ConfigIndex.Indexing Γ Λ σ) : + (terms : List (Template (Γ := Γ) (Λ := Λ) (σ := σ))) → + Emitter (RootsValid indexing) (listTokens indexing terms) + | [] => (Emitter.literal (RootsValid indexing) []).congr (fun _ => rfl) + | term :: terms => ((compileGlobal indexing term).seq (compileList indexing terms)).congr + (fun _ => rfl) + +def prefixTokens (indexing : ConfigIndex.Indexing Γ Λ σ) + (terms : List (Template (Γ := Γ) (Λ := Λ) (σ := σ) × Bool)) + (input : Input) : List Token := + terms.flatMap fun term => globalTokens indexing term.1 input ++ + (if term.2 then [.not] else []) + +def compilePrefix (indexing : ConfigIndex.Indexing Γ Λ σ) : + (terms : List (Template (Γ := Γ) (Λ := Λ) (σ := σ) × Bool)) → + Emitter (RootsValid indexing) (prefixTokens indexing terms) + | [] => (Emitter.literal (RootsValid indexing) []).congr (fun _ => rfl) + | term :: terms => + (((compileGlobal indexing term.1).seq + (Emitter.literal (RootsValid indexing) (if term.2 then [.not] else []))).seq + (compilePrefix indexing terms)).congr (fun _ => rfl) + +def withCursor (input : Input) (cursor : Nat) : Input := { input with cursor := cursor } + +def cursorTapes (base : Tape → List Bool) (cursor : Nat) : Tape → List Bool := + Function.update base .cursor (encodeWord cursor) + +@[simp] theorem withCursor_cursor (input : Input) (cursor : Nat) : + (withCursor input cursor).cursor = cursor := rfl + +@[simp] theorem withCursor_capacity (input : Input) (cursor : Nat) : + (withCursor input cursor).capacity = input.capacity := rfl + +@[simp] theorem withCursor_roots (input : Input) (cursor : Nat) : + (withCursor input cursor).roots = input.roots := rfl + +@[simp] theorem withCursor_withCursor (input : Input) (first second : Nat) : + withCursor (withCursor input first) second = withCursor input second := rfl + +theorem Frame.cursor {input : Input} {base : Tape → List Bool} + (frame : Frame input base) (cursor : Nat) : + Frame (withCursor input cursor) (cursorTapes base cursor) := by + refine ⟨by simp [cursorTapes], ?_, ?_, ?_⟩ + · simpa [cursorTapes] using frame.capacityWord + · simpa [cursorTapes] using frame.rootsWord + · intro tape ht + have hc : tape ≠ .cursor := by intro h; subst tape; simp [work] at ht + simpa [cursorTapes, hc] using frame.clean tape ht + +@[simp] theorem cursorTapes_same {input : Input} {base : Tape → List Bool} + (frame : Frame input base) : cursorTapes base input.cursor = base := by + simp only [cursorTapes, ← frame.cursorWord, Function.update_eq_self] + +@[simp] theorem cursorTapes_twice (base : Tape → List Bool) (first second : Nat) : + cursorTapes (cursorTapes base first) second = cursorTapes base second := by + simp [cursorTapes] + +theorem emitTapes_cursor (base : Tape → List Bool) (cursor : Nat) (tokens : List Token) : + emitTapes (cursorTapes base cursor) tokens = cursorTapes (emitTapes base tokens) cursor := by + funext tape + cases tape <;> simp [cursorTapes, emitTapes] + +structure Plan where + «prefix» : List (Template (Γ := Γ) (Λ := Λ) (σ := σ) × Bool) + cells : List (Template (Γ := Γ) (Λ := Λ) (σ := σ)) + carry : Bool + +def Valid (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : Plan (Γ := Γ) (Λ := Λ) (σ := σ)) (input : Input) : Prop := + indexing.width input.capacity + (if plan.carry then 1 else 0) ≤ input.roots.length + +omit [DecidableEq K] [Fintype σ] [DecidableEq σ] [∀ index, DecidableEq (Γ index)] + [∀ index, Fintype (Γ index)] [DecidableEq Λ] [Fintype Λ] in +theorem Valid.roots {indexing : ConfigIndex.Indexing Γ Λ σ} + {plan : Plan (Γ := Γ) (Λ := Λ) (σ := σ)} {input : Input} + (h : Valid indexing plan input) : RootsValid indexing input := by + unfold Valid at h + unfold RootsValid + omega + +omit [DecidableEq K] [Fintype σ] [DecidableEq σ] [∀ index, DecidableEq (Γ index)] + [∀ index, Fintype (Γ index)] [DecidableEq Λ] [Fintype Λ] in +theorem Valid.withCursor {indexing : ConfigIndex.Indexing Γ Λ σ} + {plan : Plan (Γ := Γ) (Λ := Λ) (σ := σ)} {input : Input} + (h : Valid indexing plan input) (cursor : Nat) : + Valid indexing plan (withCursor input cursor) := h + +def finalValid (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : Plan (Γ := Γ) (Λ := Λ) (σ := σ)) (input : Input) : Prop := + Valid indexing plan input ∧ input.cursor = input.capacity + +def finalTokens (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : Plan (Γ := Γ) (Λ := Λ) (σ := σ)) (input : Input) : List Token := + if plan.carry then [.input (rootLookup input.roots + (affineAddress .current indexing.symbolCount (indexing.labelCount + indexing.stateCount) input))] + else [] + +def finalEmitter (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : Plan (Γ := Γ) (Λ := Λ) (σ := σ)) : + Emitter (finalValid indexing plan) (finalTokens indexing plan) := by + cases hc : plan.carry with + | false => + exact (Emitter.literal (finalValid indexing plan) []).congr (fun input => by + simp [finalTokens, hc]) + | true => + let emitter := Emitter.affineRoot (finalValid indexing plan) .current indexing.symbolCount + (indexing.labelCount + indexing.stateCount) (by + intro input hv + have haddr : affineAddress .current indexing.symbolCount + (indexing.labelCount + indexing.stateCount) input = indexing.width input.capacity := by + simp [affineAddress, Position.eval, hv.2, ConfigIndex.Indexing.width, + Nat.mul_comm, Nat.add_comm, Nat.add_assoc] + have hlt : indexing.width input.capacity < input.roots.length := by + have h := hv.1 + simp only [Valid, hc, ite_true] at h + omega + rw [haddr] + simp only [rootLookup, List.getElem?_eq_getElem hlt, Option.getD_some]) + exact emitter.congr (fun input => by simp [finalTokens, hc]) + +def guard : Selector (testPredicate true .current) := Selector.positionTest true .current + +inductive Label (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : Plan (Γ := Γ) (Λ := Λ) (σ := σ)) + | prefix (label : (compilePrefix indexing plan.prefix).Label) + | test (label : guard.Label) + | dispatch + | cells (label : (compileList indexing plan.cells).Label) + | increment + | finishTokens (label : (finalEmitter indexing plan).Label) + | drain | finish + deriving Fintype + +attribute [-instance] instFintypeLabel + +instance labelFintype (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : Plan (Γ := Γ) (Λ := Λ) (σ := σ)) : Fintype (Label indexing plan) := + Fintype.ofEquiv + ((compilePrefix indexing plan.prefix).Label ⊕ guard.Label ⊕ Unit ⊕ + (compileList indexing plan.cells).Label ⊕ Unit ⊕ (finalEmitter indexing plan).Label ⊕ Unit ⊕ Unit) + (Label.proxyTypeEquiv indexing plan) + +def program (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : Plan (Γ := Γ) (Λ := Λ) (σ := σ)) : + Label indexing plan → TM2.Stmt Alphabet (Label indexing plan) State + | .prefix label => MachineSubroutine.statement Label.prefix (some (.test guard.entry)) + ((compilePrefix indexing plan.prefix).program label) + | .test label => MachineSubroutine.statement Label.test (some .dispatch) (guard.program label) + | .dispatch => .branch (fun state => state.1.2) + (.load (fun _ => initialState) (.goto fun _ => .cells (compileList indexing plan.cells).entry)) + (.load (fun _ => initialState) (.goto fun _ => .finishTokens (finalEmitter indexing plan).entry)) + | .cells label => MachineSubroutine.statement Label.cells (some .increment) + ((compileList indexing plan.cells).program label) + | .increment => .push .cursor (fun _ => true) (.goto fun _ => .test guard.entry) + | .finishTokens label => MachineSubroutine.statement Label.finishTokens (some .drain) + ((finalEmitter indexing plan).program label) + | .drain => MachineDrain.drain .cursor .drain (some .finish) + | .finish => .push .cursor (fun _ => false) (.load (fun _ => initialState) .halt) + +def machine (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : Plan (Γ := Γ) (Λ := Λ) (σ := σ)) : FinTM2 := by + letI := (compilePrefix indexing plan.prefix).finite + letI := guard.finite + letI := (compileList indexing plan.cells).finite + letI := (finalEmitter indexing plan).finite + exact { + K := Tape + k₀ := .cursor + k₁ := .reversed + Γ := Alphabet + Λ := Label indexing plan + main := .prefix (compilePrefix indexing plan.prefix).entry + σ := State + initialState := initialState + m := program indexing plan } + +def cellTokens (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : Plan (Γ := Γ) (Λ := Λ) (σ := σ)) (input : Input) (cursor : Nat) : List Token := + listTokens indexing plan.cells (withCursor input cursor) + +def remainingTokens (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : Plan (Γ := Γ) (Λ := Λ) (σ := σ)) (input : Input) : Nat → Nat → List Token + | cursor, 0 => finalTokens indexing plan (withCursor input cursor) + | cursor, remaining + 1 => cellTokens indexing plan input cursor ++ + remainingTokens indexing plan input (cursor + 1) remaining + +def loopSteps (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : Plan (Γ := Γ) (Λ := Λ) (σ := σ)) (input : Input) : Nat → Nat → Nat + | cursor, 0 => guard.steps (withCursor input cursor) + 1 + + (finalEmitter indexing plan).steps (withCursor input cursor) + (cursor + 2) + 1 + | cursor, remaining + 1 => guard.steps (withCursor input cursor) + 1 + + (compileList indexing plan.cells).steps (withCursor input cursor) + 1 + + loopSteps indexing plan input (cursor + 1) remaining + +private 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] + +omit [DecidableEq K] [Fintype σ] [DecidableEq σ] [∀ index, DecidableEq (Γ index)] + [∀ index, Fintype (Γ index)] [DecidableEq Λ] [Fintype Λ] in +theorem guardTrace (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : Plan (Γ := Γ) (Λ := Λ) (σ := σ)) (input : Input) + (base : Tape → List Bool) (frame : Frame input base) : + (advance (TM2.step (program indexing plan)))^[guard.steps input] + (some ⟨some (.test guard.entry), initialState, base⟩) = + some ⟨some .dispatch, (((), decide (input.cursor < input.capacity)), none), base⟩ := by + have h := MachineSubroutine.trace Label.test (some Label.dispatch) guard.program + (program indexing plan) (fun _ => rfl) (guard.steps input) _ _ + (guard.trace input base frame) + simpa [MachineSubroutine.configuration, MachineSubroutine.label, testPredicate, Position.eval] + using! h + +omit [DecidableEq K] [Fintype σ] [DecidableEq σ] [∀ index, DecidableEq (Γ index)] + [∀ index, Fintype (Γ index)] [DecidableEq Λ] [Fintype Λ] in +theorem dispatchTrace (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : Plan (Γ := Γ) (Λ := Λ) (σ := σ)) (base : Tape → List Bool) (decision : Bool) : + (advance (TM2.step (program indexing plan)))^[1] + (some ⟨some .dispatch, (((), decision), none), base⟩) = + some ⟨some (if decision then .cells (compileList indexing plan.cells).entry + else .finishTokens (finalEmitter indexing plan).entry), initialState, base⟩ := by + cases decision <;> rfl + +omit [DecidableEq K] [Fintype σ] [DecidableEq σ] [∀ index, DecidableEq (Γ index)] + [∀ index, Fintype (Γ index)] [DecidableEq Λ] [Fintype Λ] in +theorem incrementTrace (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : Plan (Γ := Γ) (Λ := Λ) (σ := σ)) (input : Input) + (base : Tape → List Bool) (frame : Frame input base) : + (advance (TM2.step (program indexing plan)))^[1] + (some ⟨some .increment, initialState, base⟩) = + some ⟨some (.test guard.entry), initialState, cursorTapes base (input.cursor + 1)⟩ := by + have hw : true :: base .cursor = encodeWord (input.cursor + 1) := by + rw [frame.cursorWord] + simp [encodeWord, List.replicate_succ] + change some (TM2.stepAux (program indexing plan .increment) initialState base) = _ + simp [program, TM2.stepAux, cursorTapes, hw] + +omit [DecidableEq K] [Fintype σ] [DecidableEq σ] [∀ index, DecidableEq (Γ index)] + [∀ index, Fintype (Γ index)] [DecidableEq Λ] [Fintype Λ] in +theorem resetTrace (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : Plan (Γ := Γ) (Λ := Λ) (σ := σ)) (input : Input) + (base : Tape → List Bool) (frame : Frame input base) : + (advance (TM2.step (program indexing plan)))^[input.cursor + 3] + (some ⟨some .drain, initialState, base⟩) = + some ⟨none, initialState, cursorTapes base 0⟩ := by + have drain := MachineDrain.drainTrace .cursor Label.drain (some Label.finish) + (program indexing plan) rfl base (encodeWord input.cursor) ((), false) none + have heq : Function.update base .cursor (encodeWord input.cursor) = base := by + rw [← frame.cursorWord, Function.update_eq_self] + rw [heq, encodeWord_length] at drain + have finish : (advance (TM2.step (program indexing plan)))^[1] + (some ⟨some .finish, initialState, Function.update base .cursor []⟩) = + some ⟨none, initialState, cursorTapes base 0⟩ := by + change some (TM2.stepAux (program indexing plan .finish) initialState _) = _ + simp [program, TM2.stepAux, cursorTapes, encodeWord] + simpa [Nat.add_assoc, initialState] using trace_trans _ drain finish + +omit [DecidableEq K] [Fintype σ] [DecidableEq σ] [∀ index, DecidableEq (Γ index)] + [∀ index, Fintype (Γ index)] [DecidableEq Λ] [Fintype Λ] in +theorem loopTrace (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : Plan (Γ := Γ) (Λ := Λ) (σ := σ)) (input : Input) + (valid : Valid indexing plan input) (cursor remaining : Nat) + (hcapacity : cursor + remaining = input.capacity) + (base : Tape → List Bool) (frame : Frame (withCursor input cursor) base) : + (advance (TM2.step (program indexing plan)))^[loopSteps indexing plan input cursor remaining] + (some ⟨some (.test guard.entry), initialState, base⟩) = + some ⟨none, initialState, + cursorTapes (emitTapes base (remainingTokens indexing plan input cursor remaining)) 0⟩ := by + induction remaining generalizing cursor base with + | zero => + have hc : cursor = input.capacity := by omega + have hg := guardTrace indexing plan (withCursor input cursor) base frame + have hd := dispatchTrace indexing plan base false + have hfalse : decide ((withCursor input cursor).cursor < + (withCursor input cursor).capacity) = false := by simp [hc] + rw [hfalse] at hg + simp only [Bool.false_eq_true, ite_false] at hd + have hv : finalValid indexing plan (withCursor input cursor) := ⟨valid.withCursor cursor, hc⟩ + have hf := (finalEmitter indexing plan).traceAt Label.finishTokens (some Label.drain) + (program indexing plan) (fun _ => rfl) (withCursor input cursor) hv base frame + have hr := resetTrace indexing plan (withCursor input cursor) + (emitTapes base (finalTokens indexing plan (withCursor input cursor))) + (frame.emit (finalTokens indexing plan (withCursor input cursor))) + have total := trace_trans _ (trace_trans _ (trace_trans _ hg hd) hf) hr + simpa only [loopSteps, remainingTokens, withCursor_cursor, Nat.add_assoc] using total + | succ remaining ih => + have hc : cursor < input.capacity := by omega + have hg := guardTrace indexing plan (withCursor input cursor) base frame + have hd := dispatchTrace indexing plan base true + have htrue : decide ((withCursor input cursor).cursor < + (withCursor input cursor).capacity) = true := by simp [hc] + rw [htrue] at hg + simp only [ite_true] at hd + have hb := (compileList indexing plan.cells).traceAt Label.cells (some Label.increment) + (program indexing plan) (fun _ => rfl) (withCursor input cursor) + (valid.withCursor cursor).roots base frame + have hi := incrementTrace indexing plan (withCursor input cursor) + (emitTapes base (cellTokens indexing plan input cursor)) + (frame.emit (cellTokens indexing plan input cursor)) + have hn := ih (cursor + 1) (by omega) + (cursorTapes (emitTapes base (cellTokens indexing plan input cursor)) (cursor + 1)) + (by simpa only [withCursor_withCursor] using + Frame.cursor (frame.emit (cellTokens indexing plan input cursor)) (cursor + 1)) + have total := trace_trans _ (trace_trans _ (trace_trans _ (trace_trans _ hg hd) hb) hi) hn + simpa only [loopSteps, remainingTokens, cellTokens, withCursor_cursor, + emitTapes_cursor, cursorTapes_twice, emitTapes_append, Nat.add_assoc] using total + +def outputTokens (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : Plan (Γ := Γ) (Λ := Λ) (σ := σ)) (input : Input) : List Token := + prefixTokens indexing plan.prefix (withCursor input 0) ++ + remainingTokens indexing plan input 0 input.capacity + +def steps (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : Plan (Γ := Γ) (Λ := Λ) (σ := σ)) (input : Input) : Nat := + (compilePrefix indexing plan.prefix).steps (withCursor input 0) + + loopSteps indexing plan input 0 input.capacity + +omit [DecidableEq K] [Fintype σ] [DecidableEq σ] [∀ index, DecidableEq (Γ index)] + [∀ index, Fintype (Γ index)] [DecidableEq Λ] [Fintype Λ] in +theorem fullTrace (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : Plan (Γ := Γ) (Λ := Λ) (σ := σ)) (input : Input) + (valid : Valid indexing plan input) (base : Tape → List Bool) + (frame : Frame (withCursor input 0) base) : + (advance (TM2.step (program indexing plan)))^[steps indexing plan input] + (some ⟨some (.prefix (compilePrefix indexing plan.prefix).entry), initialState, base⟩) = + some ⟨none, initialState, emitTapes base (outputTokens indexing plan input)⟩ := by + have hp := (compilePrefix indexing plan.prefix).traceAt Label.prefix (some (.test guard.entry)) + (program indexing plan) (fun _ => rfl) (withCursor input 0) + (valid.withCursor 0).roots base frame + have hl := loopTrace indexing plan input valid 0 input.capacity (by omega) + (emitTapes base (prefixTokens indexing plan.prefix (withCursor input 0))) + (frame.emit (prefixTokens indexing plan.prefix (withCursor input 0))) + have hc : cursorTapes base 0 = base := cursorTapes_same frame + simpa only [steps, emitTapes_append, ← emitTapes_cursor, hc, outputTokens] + using trace_trans _ hp hl + +omit [DecidableEq K] [Fintype σ] [DecidableEq σ] [∀ index, DecidableEq (Γ index)] + [∀ index, Fintype (Γ index)] [DecidableEq Λ] [Fintype Λ] in +theorem traceAt {Caller : Type} (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : Plan (Γ := Γ) (Λ := Λ) (σ := σ)) + (labels : Label indexing plan → Caller) (exit : Option Caller) + (target : Caller → TM2.Stmt Alphabet Caller State) + (code : ∀ label, target (labels label) = + MachineSubroutine.statement labels exit (program indexing plan label)) + (input : Input) (valid : Valid indexing plan input) (base : Tape → List Bool) + (frame : Frame (withCursor input 0) base) : + (advance (TM2.step target))^[steps indexing plan input] + (some ⟨some (labels (.prefix (compilePrefix indexing plan.prefix).entry)), initialState, base⟩) = + some ⟨exit, initialState, emitTapes base (outputTokens indexing plan input)⟩ := by + have h := MachineSubroutine.trace labels exit (program indexing plan) target code + (steps indexing plan input) _ _ (fullTrace indexing plan input valid base frame) + simpa only [MachineSubroutine.configuration, MachineSubroutine.label] using h + +def loopConstant (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : Plan (Γ := Γ) (Λ := Λ) (σ := σ)) : Nat := + guard.constant + (compileList indexing plan.cells).constant + + (finalEmitter indexing plan).constant + 5 + +def dataSize (input : Input) : Nat := input.capacity + (encodeWords input.roots).length + +omit [DecidableEq K] [Fintype σ] [DecidableEq σ] [∀ index, DecidableEq (Γ index)] + [∀ index, Fintype (Γ index)] [DecidableEq Λ] [Fintype Λ] in +theorem loopSteps_le (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : Plan (Γ := Γ) (Λ := Λ) (σ := σ)) (input : Input) + (valid : Valid indexing plan input) (cursor remaining : Nat) + (hcapacity : cursor + remaining = input.capacity) : + loopSteps indexing plan input cursor remaining ≤ + (remaining + 1) * loopConstant indexing plan * + (2 * input.capacity + (encodeWords input.roots).length + 1) := by + let B := 2 * input.capacity + (encodeWords input.roots).length + 1 + have hB : 1 ≤ B := by dsimp [B]; omega + induction remaining generalizing cursor with + | zero => + have hc : cursor = input.capacity := by omega + have hs : (withCursor input cursor).size + 1 ≤ B := by simp [Input.size, B]; omega + have hg := guard.bound (withCursor input cursor) + have hf := (finalEmitter indexing plan).bound (withCursor input cursor) + ⟨valid.withCursor cursor, hc⟩ + have hg' := hg.trans (Nat.mul_le_mul_left guard.constant hs) + have hf' := hf.trans (Nat.mul_le_mul_left (finalEmitter indexing plan).constant hs) + have hcB : cursor ≤ B := by dsimp [B]; omega + simp only [loopSteps, Nat.zero_add, Nat.one_mul] + change _ ≤ loopConstant indexing plan * B + dsimp [loopConstant] + nlinarith [Nat.zero_le ((compileList indexing plan.cells).constant * B)] + | succ remaining ih => + have hc : cursor ≤ input.capacity := by omega + have hs : (withCursor input cursor).size + 1 ≤ B := by simp [Input.size, B]; omega + have hg := guard.bound (withCursor input cursor) + have hb := (compileList indexing plan.cells).bound (withCursor input cursor) + (valid.withCursor cursor).roots + have hg' := hg.trans (Nat.mul_le_mul_left guard.constant hs) + have hb' := hb.trans (Nat.mul_le_mul_left (compileList indexing plan.cells).constant hs) + have hi := ih (cursor + 1) (by omega) + simp only [loopSteps] + have hstep : guard.steps (withCursor input cursor) + 1 + + (compileList indexing plan.cells).steps (withCursor input cursor) + 1 ≤ + loopConstant indexing plan * B := by + dsimp [loopConstant] + nlinarith [Nat.zero_le ((finalEmitter indexing plan).constant * B)] + calc + _ ≤ loopConstant indexing plan * B + (remaining + 1) * loopConstant indexing plan * B := + Nat.add_le_add hstep hi + _ = _ := by dsimp [B]; ring + +def timeConstant (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : Plan (Γ := Γ) (Λ := Λ) (σ := σ)) : Nat := + 2 * ((compilePrefix indexing plan.prefix).constant + loopConstant indexing plan) + +noncomputable def timePolynomial (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : Plan (Γ := Γ) (Λ := Λ) (σ := σ)) : Polynomial Nat := + Polynomial.C (timeConstant indexing plan) * (Polynomial.X + 1)^2 + +omit [DecidableEq K] [Fintype σ] [DecidableEq σ] [∀ index, DecidableEq (Γ index)] + [∀ index, Fintype (Γ index)] [DecidableEq Λ] [Fintype Λ] in +theorem steps_le (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : Plan (Γ := Γ) (Λ := Λ) (σ := σ)) (input : Input) + (valid : Valid indexing plan input) : + steps indexing plan input ≤ timeConstant indexing plan * (dataSize input + 1)^2 := by + have hp := (compilePrefix indexing plan.prefix).bound (withCursor input 0) + (valid.withCursor 0).roots + have hl := loopSteps_le indexing plan input valid 0 input.capacity (by omega) + have hcap : input.capacity + 1 ≤ dataSize input + 1 := by simp [dataSize] + have hdata : 2 * input.capacity + (encodeWords input.roots).length + 1 ≤ + 2 * (dataSize input + 1) := by unfold dataSize; omega + have hmul := Nat.mul_le_mul hcap hdata + have hp' : (compilePrefix indexing plan.prefix).steps (withCursor input 0) ≤ + (compilePrefix indexing plan.prefix).constant * (dataSize input + 1) := by + simpa [withCursor, Input.size, dataSize] using hp + have hprod := Nat.mul_le_mul_left (loopConstant indexing plan) hmul + have hsq : dataSize input + 1 ≤ (dataSize input + 1)^2 := by nlinarith + have hprefix := Nat.mul_le_mul_left (compilePrefix indexing plan.prefix).constant hsq + unfold steps timeConstant + nlinarith + +def inPolynomialTime (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : Plan (Γ := Γ) (Λ := Λ) (σ := σ)) (input : Input) + (valid : Valid indexing plan input) (base : Tape → List Bool) + (frame : Frame (withCursor input 0) base) : + StateTransition.EvalsToInTime (machine indexing plan).step + ⟨some (Label.prefix (compilePrefix indexing plan.prefix).entry), initialState, base⟩ + (some ⟨none, initialState, emitTapes base (outputTokens indexing plan input)⟩) + ((timePolynomial indexing plan).eval (dataSize input)) where + steps := steps indexing plan input + evals_in_steps := fullTrace indexing plan input valid base frame + steps_le_m := by + simpa only [timePolynomial, Polynomial.eval_mul, Polynomial.eval_C, + Polynomial.eval_pow, Polynomial.eval_add, Polynomial.eval_X, Polynomial.eval_one] + using steps_le indexing plan input valid + +omit [DecidableEq K] [Fintype σ] [DecidableEq σ] [∀ index, DecidableEq (Γ index)] + [∀ index, Fintype (Γ index)] [DecidableEq Λ] [Fintype Λ] in +theorem remainingTokens_eq_range (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : Plan (Γ := Γ) (Λ := Λ) (σ := σ)) (input : Input) (cursor remaining : Nat) : + remainingTokens indexing plan input cursor remaining = + ((List.range' cursor remaining).flatMap (cellTokens indexing plan input)) ++ + finalTokens indexing plan (withCursor input (cursor + remaining)) := by + induction remaining generalizing cursor with + | zero => simp [remainingTokens] + | succ remaining ih => + simp [remainingTokens, List.range'_succ, ih, List.append_assoc, + Nat.add_comm, Nat.add_left_comm] + +def carriedTokens (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : Plan (Γ := Γ) (Λ := Λ) (σ := σ)) (input : Input) : List Token := + if plan.carry then [.input (rootLookup input.roots (indexing.width input.capacity))] else [] + +omit [DecidableEq K] [Fintype σ] [DecidableEq σ] [∀ index, DecidableEq (Γ index)] + [∀ index, Fintype (Γ index)] [DecidableEq Λ] [Fintype Λ] in +theorem finalTokens_at_capacity (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : Plan (Γ := Γ) (Λ := Λ) (σ := σ)) (input : Input) : + finalTokens indexing plan (withCursor input input.capacity) = carriedTokens indexing plan input := by + simp [finalTokens, carriedTokens, affineAddress, Position.eval, + ConfigIndex.Indexing.width, Nat.mul_comm, Nat.add_comm, Nat.add_assoc] + +omit [DecidableEq K] [Fintype σ] [DecidableEq σ] [∀ index, DecidableEq (Γ index)] + [∀ index, Fintype (Γ index)] [DecidableEq Λ] [Fintype Λ] in +theorem outputTokens_eq_blocks (indexing : ConfigIndex.Indexing Γ Λ σ) + (plan : Plan (Γ := Γ) (Λ := Λ) (σ := σ)) (input : Input) : + outputTokens indexing plan input = + prefixTokens indexing plan.prefix (withCursor input 0) ++ + ((List.finRange input.capacity).flatMap fun cursor => + cellTokens indexing plan input cursor.val) ++ carriedTokens indexing plan input := by + rw [outputTokens, remainingTokens_eq_range] + simp only [Nat.zero_add, finalTokens_at_capacity] + rw [← List.range_eq_range', ← List.map_coe_finRange_eq_range, List.flatMap_map] + simp only [List.append_assoc] + +def transitionPrefixKinds (indexing : ConfigIndex.Indexing Γ Λ σ) : List (OutputKind Γ Λ σ) := + ((List.finRange indexing.labelCount).map fun i => .inl (indexing.labels.symm i)) ++ + ((List.finRange indexing.stateCount).map fun i => .inr (.inl (indexing.states.symm i))) + +def transitionCellKinds (indexing : ConfigIndex.Indexing Γ Λ σ) : List (OutputKind Γ Λ σ) := + (List.finRange indexing.symbolCount).map fun i => .inr (.inr (indexing.symbols.symm i)) + +noncomputable def transitionPlan (indexing : ConfigIndex.Indexing Γ Λ σ) + (machineProgram : Λ → TM2.Stmt Γ Λ σ) : Plan (Γ := Γ) (Λ := Λ) (σ := σ) where + «prefix» := (transitionPrefixKinds indexing).map fun kind => (sticky machineProgram kind, false) + cells := (transitionCellKinds indexing).map (sticky machineProgram) + carry := true + +theorem transition_outputTokens (indexing : ConfigIndex.Indexing Γ Λ σ) + (machineProgram : Λ → TM2.Stmt Γ Λ σ) (input : Input) : + outputTokens indexing (transitionPlan indexing machineProgram) input = + TransitionTemplate.forestTokens indexing input.roots input.capacity machineProgram ++ + [.input (rootLookup input.roots (indexing.width input.capacity))] := by + rw [outputTokens_eq_blocks] + simp [transitionPlan, transitionPrefixKinds, transitionCellKinds, + prefixTokens, listTokens, cellTokens, globalTokens, carriedTokens, + TransitionTemplate.forestTokens, OutputOrder.outputOrder_eq_blocks, + List.flatMap_append, List.flatMap_map, List.flatMap_assoc, withCursor, bitKind, bitCursor, + List.append_assoc] + +noncomputable def transitionInPolynomialTime (indexing : ConfigIndex.Indexing Γ Λ σ) + (machineProgram : Λ → TM2.Stmt Γ Λ σ) (input : Input) + (valid : indexing.width input.capacity + 1 ≤ input.roots.length) + (base : Tape → List Bool) (frame : Frame (withCursor input 0) base) : + StateTransition.EvalsToInTime (machine indexing (transitionPlan indexing machineProgram)).step + ⟨some (Label.prefix (compilePrefix indexing (transitionPlan indexing machineProgram).prefix).entry), + initialState, base⟩ + (some ⟨none, initialState, emitTapes base + (TransitionTemplate.forestTokens indexing input.roots input.capacity machineProgram ++ + [.input (rootLookup input.roots (indexing.width input.capacity))])⟩) + ((timePolynomial indexing (transitionPlan indexing machineProgram)).eval (dataSize input)) := by + have hv : Valid indexing (transitionPlan indexing machineProgram) input := by + simpa only [Valid, transitionPlan, ite_true] using valid + simpa only [transition_outputTokens] using + inPolynomialTime indexing (transitionPlan indexing machineProgram) input hv base frame + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.TransitionMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/TransitionTemplate.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/TransitionTemplate.lean new file mode 100644 index 0000000000000000000000000000000000000000..8ad21e4a3d741a509dfaf839ad0b987683ad2d96 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/TransitionTemplate.lean @@ -0,0 +1,584 @@ +import OAI.Computability.PerfectCompleteness.Machines.CircuitBatchLemmas +import OAI.Computability.PerfectCompleteness.Machines.MachineCircuit +import OAI.Computability.PerfectCompleteness.Machines.PositionLemmas +import OAI.Computability.PerfectCompleteness.Machines.PostfixAlignment + +namespace OAI + +section + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.TransitionTemplate + +open Turing StatementCircuit + +variable {K : Type} (Γ : K → Type) (σ : Type) + +inductive Term where + | state (v : σ) + | cell (k : K) (position : Position) (symbol : Option (Γ k)) + | const (value : Bool) + | not (arg : Term) + | and (left right : Term) + | or (left right : Term) + | atZero (position : Position) (yes no : Term) + | within (position : Position) (yes no : Term) + +variable {Γ σ} [∀ k, DecidableEq (Γ k)] + +def Term.instantiate (S cursor : Nat) : Term Γ σ → Expr (InputBit Γ σ S) + | .state v => .input (.inl v) + | .cell k p a => if h : p.eval cursor < S then .input (.inr ⟨k, ⟨p.eval cursor, h⟩, a⟩) + else .const (decide ((none : Option (Γ k)) = a)) + | .const b => .const b + | .not e => .not (e.instantiate S cursor) + | .and e f => .and (e.instantiate S cursor) (f.instantiate S cursor) + | .or e f => .or (e.instantiate S cursor) (f.instantiate S cursor) + | .atZero p yes no => if p.eval cursor = 0 then yes.instantiate S cursor + else no.instantiate S cursor + | .within p yes no => if p.eval cursor < S then yes.instantiate S cursor + else no.instantiate S cursor + +def Term.nodeCount : Term Γ σ → Nat + | .state _ | .cell _ _ _ | .const _ => 1 + | .not e => e.nodeCount + 1 + | .and e f | .or e f | .atZero _ e f | .within _ e f => + e.nodeCount + f.nodeCount + 1 + +omit [∀ k, DecidableEq (Γ k)] in +theorem Term.instantiate_size_le (S cursor : Nat) (term : Term Γ σ) : + (term.instantiate S cursor).size ≤ term.nodeCount := by + induction term with + | state v => simp [instantiate, nodeCount, Expr.size] + | cell k p a => + by_cases h : p.eval cursor < S <;> simp [instantiate, nodeCount, h, Expr.size] + | const b => simp [instantiate, nodeCount, Expr.size] + | not e ih => simpa only [instantiate, nodeCount, Expr.size] using Nat.add_le_add_right ih 1 + | and e f ihe ihf | or e f ihe ihf => + simpa only [instantiate, nodeCount, Expr.size] using + Nat.add_le_add_right (Nat.add_le_add ihe ihf) 1 + | atZero p e f ihe ihf => + by_cases h : p.eval cursor = 0 <;> simp only [instantiate, nodeCount, h, ite_true, ite_false] <;> omega + | within p e f ihe ihf => + by_cases h : p.eval cursor < S <;> simp only [instantiate, nodeCount, h, ite_true, ite_false] <;> omega + +def Term.disjoin : List (Term Γ σ) → Term Γ σ + | [] => .const false + | e :: rest => .or e (disjoin rest) + +def Term.mux (condition yes no : Term Γ σ) : Term Γ σ := + .or (.and condition yes) (.and (.not condition) no) + +omit [∀ k, DecidableEq (Γ k)] in +@[simp] theorem instantiate_disjoin (S cursor : Nat) (es : List (Term Γ σ)) : + (Term.disjoin es).instantiate S cursor = + Expr.disjoin (es.map (Term.instantiate S cursor)) := by + induction es <;> simp_all [Term.disjoin, Term.instantiate, Expr.disjoin] + +omit [∀ k, DecidableEq (Γ k)] in +@[simp] theorem instantiate_mux (S cursor : Nat) (c x y : Term Γ σ) : + (Term.mux c x y).instantiate S cursor = + Expr.mux (c.instantiate S cursor) (x.instantiate S cursor) (y.instantiate S cursor) := rfl + +noncomputable def finiteTable {A B : Type} [Fintype A] [DecidableEq B] + (f : A → B) (x : A → Term Γ σ) (b : B) : Term Γ σ := + Term.disjoin (Finset.univ.toList.map fun a => .and (x a) (.const (decide (f a = b)))) + +noncomputable def finiteTable₂ {A B C : Type} [Fintype A] [Fintype B] [DecidableEq C] + (f : A → B → C) (x : A → Term Γ σ) (y : B → Term Γ σ) (c : C) : Term Γ σ := + finiteTable (fun p : A × B => f p.1 p.2) (fun p => .and (x p.1) (y p.2)) c + +omit [∀ k, DecidableEq (Γ k)] in +@[simp] theorem instantiate_table {A B : Type} [Fintype A] [DecidableEq B] + (S cursor : Nat) (f : A → B) (x : A → Term Γ σ) (b : B) : + (finiteTable f x b).instantiate S cursor = + table f (fun a => (x a).instantiate S cursor) b := by + simp [finiteTable, table, List.map_map, Term.instantiate, Function.comp_def] + +omit [∀ k, DecidableEq (Γ k)] in +@[simp] theorem instantiate_table₂ {A B C : Type} [Fintype A] [Fintype B] [DecidableEq C] + (S cursor : Nat) (f : A → B → C) (x : A → Term Γ σ) (y : B → Term Γ σ) (c : C) : + (finiteTable₂ f x y c).instantiate S cursor = + table₂ f (fun a => (x a).instantiate S cursor) + (fun b => (y b).instantiate S cursor) c := by + simp [finiteTable₂, table₂, Term.instantiate] + +structure Data where + state : σ → Term Γ σ + cells : ∀ k, Position → Option (Γ k) → Term Γ σ + +structure Result (Λ : Type) extends Data (Γ := Γ) (σ := σ) where + label : Option Λ → Term Γ σ + +def Data.Matches (S cursor : Nat) (bits : Data (Γ := Γ) (σ := σ)) + (actual : DataBits (InputBit Γ σ S) Γ σ S) : Prop := + (∀ v, (bits.state v).instantiate S cursor = actual.state v) ∧ + ∀ k p a (h : p.eval cursor < S), + (bits.cells k p a).instantiate S cursor = actual.cells k ⟨p.eval cursor, h⟩ a + +def Result.Matches {Λ : Type} (S cursor : Nat) (bits : Result (Γ := Γ) (σ := σ) Λ) + (actual : ResultBits (InputBit Γ σ S) Γ Λ σ S) : Prop := + bits.toData.Matches S cursor actual.toDataBits ∧ + ∀ label, (bits.label label).instantiate S cursor = actual.label label + +def initial : Data (Γ := Γ) (σ := σ) where + state := Term.state + cells := Term.cell + +omit [∀ k, DecidableEq (Γ k)] in +theorem initial_matches (S cursor : Nat) : + (initial : Data (Γ := Γ) (σ := σ)).Matches S cursor (inputBits S) := by + refine ⟨fun _ => rfl, ?_⟩ + intro k p a hp + simp [initial, Term.instantiate, hp, inputBits] + +def read (bits : Data (Γ := Γ) (σ := σ)) (k : K) (p : Position) (a : Option (Γ k)) : + Term Γ σ := + .within p (bits.cells k p a) (.const (decide ((none : Option (Γ k)) = a))) + +theorem instantiate_read (S cursor : Nat) (bits : Data (Γ := Γ) (σ := σ)) + (actual : DataBits (InputBit Γ σ S) Γ σ S) (h : bits.Matches S cursor actual) + (k : K) (p : Position) (a : Option (Γ k)) : + (read bits k p a).instantiate S cursor = readBits (actual.cells k) (p.eval cursor) a := by + by_cases hp : p.eval cursor < S + · simpa [read, Term.instantiate, readBits, hp] using h.2 k p a hp + · simp [read, Term.instantiate, readBits, hp] + +variable {Λ : Type} [DecidableEq K] [Fintype σ] [DecidableEq σ] +variable [∀ k, Fintype (Γ k)] [DecidableEq Λ] + +noncomputable def push (bits : Data (Γ := Γ) (σ := σ)) (k : K) (f : σ → Γ k) : + Data (Γ := Γ) (σ := σ) where + state := bits.state + cells := Function.update bits.cells k (fun p a => + .atZero p (finiteTable (fun v => some (f v)) bits.state a) (bits.cells k (.pred p) a)) + +noncomputable def peek (bits : Data (Γ := Γ) (σ := σ)) (k : K) + (f : σ → Option (Γ k) → σ) : Data (Γ := Γ) (σ := σ) where + state := finiteTable₂ f bits.state (read bits k .zero) + cells := bits.cells + +noncomputable def pop (bits : Data (Γ := Γ) (σ := σ)) (k : K) + (f : σ → Option (Γ k) → σ) : Data (Γ := Γ) (σ := σ) where + state := finiteTable₂ f bits.state (read bits k .zero) + cells := Function.update bits.cells k (fun p a => read bits k (.succ p) a) + +noncomputable def load (bits : Data (Γ := Γ) (σ := σ)) (f : σ → σ) : + Data (Γ := Γ) (σ := σ) where + state := finiteTable f bits.state + cells := bits.cells + +def mux (condition : Term Γ σ) (yes no : Result (Γ := Γ) (σ := σ) Λ) : + Result (Γ := Γ) (σ := σ) Λ where + state := fun v => .mux condition (yes.state v) (no.state v) + cells := fun k p a => .mux condition (yes.cells k p a) (no.cells k p a) + label := fun l => .mux condition (yes.label l) (no.label l) + +omit [DecidableEq σ] [∀ k, Fintype (Γ k)] in +theorem push_matches (S cursor : Nat) (bits : Data (Γ := Γ) (σ := σ)) + (actual : DataBits (InputBit Γ σ S) Γ σ S) (h : bits.Matches S cursor actual) + (k : K) (f : σ → Γ k) : + (push bits k f).Matches S cursor (pushBits actual k f) := by + refine ⟨h.1, ?_⟩ + intro j p a hp + by_cases hj : j = k + · subst j + simp only [push, pushBits, Function.update_self] + by_cases hz : p.eval cursor = 0 + · simp [Term.instantiate, hz, h.1] + · have hpred : (Position.pred p).eval cursor < S := by + simp only [Position.eval] + omega + simpa [Term.instantiate, Position.eval, hz] using h.2 k (.pred p) a hpred + · simpa [push, pushBits, Function.update_of_ne hj] using h.2 j p a hp + +omit [DecidableEq K] in +theorem peek_matches (S cursor : Nat) (bits : Data (Γ := Γ) (σ := σ)) + (actual : DataBits (InputBit Γ σ S) Γ σ S) (h : bits.Matches S cursor actual) + (k : K) (f : σ → Option (Γ k) → σ) : + (peek bits k f).Matches S cursor (peekBits actual k f) := by + refine ⟨?_, h.2⟩ + intro v + simp only [peek, peekBits, instantiate_table₂] + have hs : (fun a => (bits.state a).instantiate S cursor) = actual.state := funext h.1 + have hc : (fun a => (read bits k .zero a).instantiate S cursor) = + readBits (actual.cells k) 0 := by + funext a + exact instantiate_read S cursor bits actual h k .zero a + rw [hs, hc] + +theorem pop_matches (S cursor : Nat) (bits : Data (Γ := Γ) (σ := σ)) + (actual : DataBits (InputBit Γ σ S) Γ σ S) (h : bits.Matches S cursor actual) + (k : K) (f : σ → Option (Γ k) → σ) : + (pop bits k f).Matches S cursor (popBits actual k f) := by + refine ⟨(peek_matches S cursor bits actual h k f).1, ?_⟩ + intro j p a hp + by_cases hj : j = k + · subst j + simpa [pop, popBits, Position.eval] using instantiate_read S cursor bits actual h k (.succ p) a + · simpa [pop, popBits, Function.update_of_ne hj] using h.2 j p a hp + +omit [∀ k, DecidableEq (Γ k)] [DecidableEq K] [∀ k, Fintype (Γ k)] in +theorem load_matches (S cursor : Nat) (bits : Data (Γ := Γ) (σ := σ)) + (actual : DataBits (InputBit Γ σ S) Γ σ S) (h : bits.Matches S cursor actual) + (f : σ → σ) : (load bits f).Matches S cursor (loadBits actual f) := by + refine ⟨?_, h.2⟩ + intro v + simp [load, loadBits, h.1] + +omit [∀ k, DecidableEq (Γ k)] [DecidableEq K] [Fintype σ] [DecidableEq σ] + [∀ k, Fintype (Γ k)] [DecidableEq Λ] in +theorem mux_matches (S cursor : Nat) (condition : Term Γ σ) + (yes no : Result (Γ := Γ) (σ := σ) Λ) + (actualYes actualNo : ResultBits (InputBit Γ σ S) Γ Λ σ S) + (hy : yes.Matches S cursor actualYes) (hn : no.Matches S cursor actualNo) : + (mux condition yes no).Matches S cursor + (muxResult (condition.instantiate S cursor) actualYes actualNo) := by + refine ⟨⟨?_, ?_⟩, ?_⟩ + · intro v + simp [mux, muxResult, hy.1.1, hn.1.1] + · intro k p a hp + simp [mux, muxResult, hy.1.2 k p a hp, hn.1.2 k p a hp] + · intro l + simp [mux, muxResult, hy.2, hn.2] + +noncomputable def compile : TM2.Stmt Γ Λ σ → Data (Γ := Γ) (σ := σ) → + Result (Γ := Γ) (σ := σ) Λ + | .push k f next, bits => compile next (push bits k f) + | .peek k f next, bits => compile next (peek bits k f) + | .pop k f next, bits => compile next (pop bits k f) + | .load f next, bits => compile next (load bits f) + | .branch guard yes no, bits => + mux (finiteTable guard bits.state true) (compile yes bits) (compile no bits) + | .goto label, bits => + { toData := bits, label := finiteTable (fun v => some (label v)) bits.state } + | .halt, bits => + { toData := bits, label := fun l => .const (decide ((none : Option Λ) = l)) } + +theorem compile_matches (S cursor : Nat) (stmt : TM2.Stmt Γ Λ σ) + (bits : Data (Γ := Γ) (σ := σ)) (actual : DataBits (InputBit Γ σ S) Γ σ S) + (h : bits.Matches S cursor actual) : + (compile stmt bits).Matches S cursor (compileAux stmt actual) := by + induction stmt generalizing bits actual with + | push k f next ih => + exact ih (push bits k f) (pushBits actual k f) (push_matches S cursor bits actual h k f) + | peek k f next ih => + exact ih (peek bits k f) (peekBits actual k f) (peek_matches S cursor bits actual h k f) + | pop k f next ih => + exact ih (pop bits k f) (popBits actual k f) (pop_matches S cursor bits actual h k f) + | load f next ih => + exact ih (load bits f) (loadBits actual f) (load_matches S cursor bits actual h f) + | branch guard yes no ihy ihn => + have hm := mux_matches S cursor (finiteTable guard bits.state true) + (compile yes bits) (compile no bits) (compileAux yes actual) (compileAux no actual) + (ihy bits actual h) (ihn bits actual h) + simpa [compile, compileAux, h.1] using hm + | goto label => + refine ⟨h, ?_⟩ + intro l + simp [compile, compileAux, h.1] + | halt => exact ⟨h, fun _ => rfl⟩ + +abbrev OutputKind (Γ : K → Type) (Λ σ : Type) := + Option Λ ⊕ (σ ⊕ (Σ k, Option (Γ k))) + +def bitKind {S : Nat} : ConfigBit Γ Λ σ S → OutputKind Γ Λ σ + | .inl l => .inl l + | .inr (.inl v) => .inr (.inl v) + | .inr (.inr ⟨k, _, a⟩) => .inr (.inr ⟨k, a⟩) + +def bitCursor {S : Nat} : ConfigBit Γ Λ σ S → Nat + | .inl _ | .inr (.inl _) => 0 + | .inr (.inr ⟨_, i, _⟩) => i.val + +def select (bits : Result (Γ := Γ) (σ := σ) Λ) : OutputKind Γ Λ σ → Term Γ σ + | .inl l => bits.label l + | .inr (.inl v) => bits.state v + | .inr (.inr ⟨k, a⟩) => bits.cells k .current a + +noncomputable def transition (stmt : TM2.Stmt Γ Λ σ) (kind : OutputKind Γ Λ σ) : Term Γ σ := + select (compile stmt initial) kind + +theorem transition_instantiate (S : Nat) (stmt : TM2.Stmt Γ Λ σ) + (bit : ConfigBit Γ Λ σ S) : + (transition stmt (bitKind bit)).instantiate S (bitCursor bit) = transitionExpr S stmt bit := by + have h := compile_matches S (bitCursor bit) stmt initial (inputBits S) + (initial_matches S (bitCursor bit)) + rcases bit with l | (v | ⟨k, i, a⟩) + · exact h.2 l + · exact h.1.1 v + · exact h.1.2 k .current a i.isLt + +inductive Global where + | label (value : Option Λ) + | data (term : Term Γ σ) + | const (value : Bool) + | and (left right : Global) + | or (left right : Global) + +def Global.instantiate (S cursor : Nat) : Global (Γ := Γ) (Λ := Λ) (σ := σ) → + Expr (ConfigBit Γ Λ σ S) + | .label l => .input (.inl l) + | .data e => (e.instantiate S cursor).rename Sum.inr + | .const b => .const b + | .and e f => .and (e.instantiate S cursor) (f.instantiate S cursor) + | .or e f => .or (e.instantiate S cursor) (f.instantiate S cursor) + +def Global.nodeCount : Global (Γ := Γ) (Λ := Λ) (σ := σ) → Nat + | .label _ | .const _ => 1 + | .data e => e.nodeCount + | .and e f | .or e f => e.nodeCount + f.nodeCount + 1 + +omit [∀ k, DecidableEq (Γ k)] [DecidableEq K] [Fintype σ] [DecidableEq σ] + [∀ k, Fintype (Γ k)] [DecidableEq Λ] in +theorem Global.instantiate_size_le (S cursor : Nat) + (term : Global (Γ := Γ) (Λ := Λ) (σ := σ)) : + (term.instantiate S cursor).size ≤ term.nodeCount := by + induction term with + | label l => simp [instantiate, nodeCount, Expr.size] + | data e => simpa only [instantiate, nodeCount, Expr.size_rename] using e.instantiate_size_le S cursor + | const b => simp [instantiate, nodeCount, Expr.size] + | and e f ihe ihf | or e f ihe ihf => + simpa only [instantiate, nodeCount, Expr.size] using + Nat.add_le_add_right (Nat.add_le_add ihe ihf) 1 + +def Global.disjoin : List (Global (Γ := Γ) (Λ := Λ) (σ := σ)) → + Global (Γ := Γ) (Λ := Λ) (σ := σ) + | [] => .const false + | e :: es => .or e (disjoin es) + +omit [∀ k, DecidableEq (Γ k)] [DecidableEq K] [Fintype σ] [DecidableEq σ] + [∀ k, Fintype (Γ k)] [DecidableEq Λ] in +@[simp] theorem instantiate_global_disjoin (S cursor : Nat) + (es : List (Global (Γ := Γ) (Λ := Λ) (σ := σ))) : + (Global.disjoin es).instantiate S cursor = + Expr.disjoin (es.map (Global.instantiate S cursor)) := by + induction es <;> simp_all [Global.disjoin, Global.instantiate, Expr.disjoin] + +def self : OutputKind Γ Λ σ → Global (Γ := Γ) (Λ := Λ) (σ := σ) + | .inl l => .label l + | .inr (.inl v) => .data (.state v) + | .inr (.inr ⟨k, a⟩) => .data (.cell k .current a) + +omit [∀ k, DecidableEq (Γ k)] [DecidableEq K] [Fintype σ] [DecidableEq σ] + [∀ k, Fintype (Γ k)] [DecidableEq Λ] in +theorem self_instantiate (S : Nat) (bit : ConfigBit Γ Λ σ S) : + (self (bitKind bit)).instantiate S (bitCursor bit) = .input bit := by + rcases bit with l | (v | ⟨k, i, a⟩) + · rfl + · rfl + · simp [self, bitKind, bitCursor, Global.instantiate, Term.instantiate, + Position.eval, i.isLt, Expr.rename] + +variable [Fintype Λ] + +noncomputable def sticky (program : Λ → TM2.Stmt Γ Λ σ) (kind : OutputKind Γ Λ σ) : + Global (Γ := Γ) (Λ := Λ) (σ := σ) := + .or (.and (.label none) (self kind)) + (Global.disjoin (Finset.univ.toList.map fun l => + .and (.label (some l)) (.data (transition (program l) kind)))) + +theorem sticky_instantiate (S : Nat) (program : Λ → TM2.Stmt Γ Λ σ) + (bit : ConfigBit Γ Λ σ S) : + (sticky program (bitKind bit)).instantiate S (bitCursor bit) = + MachineCircuit.stickyExpr S program bit := by + simp only [sticky, Global.instantiate, instantiate_global_disjoin, List.map_map, + Function.comp_def, self_instantiate, transition_instantiate, + MachineCircuit.stickyExpr] + rfl + +def kindIndexEquiv (indexing : ConfigIndex.Indexing Γ Λ σ) : + OutputKind Γ Λ σ ≃ + Fin (indexing.labelCount + indexing.stateCount + indexing.symbolCount) := + (Equiv.sumCongr indexing.labels (Equiv.sumCongr indexing.states indexing.symbols)).trans + ((Equiv.sumAssoc (Fin indexing.labelCount) (Fin indexing.stateCount) + (Fin indexing.symbolCount)).symm.trans + ((Equiv.sumCongr finSumFinEquiv (Equiv.refl (Fin indexing.symbolCount))).trans + finSumFinEquiv)) + +noncomputable def templateBank (indexing : ConfigIndex.Indexing Γ Λ σ) + (program : Λ → TM2.Stmt Γ Λ σ) + (i : Fin (indexing.labelCount + indexing.stateCount + indexing.symbolCount)) : + Global (Γ := Γ) (Λ := Λ) (σ := σ) := + sticky program ((kindIndexEquiv indexing).symm i) + +@[simp] theorem templateBank_select (indexing : ConfigIndex.Indexing Γ Λ σ) + (program : Λ → TM2.Stmt Γ Λ σ) (kind : OutputKind Γ Λ σ) : + templateBank indexing program (kindIndexEquiv indexing kind) = sticky program kind := by + simp [templateBank] + +def rootLookup (roots : List Nat) (address : Nat) : Nat := roots[address]?.getD 0 + +def configWire (indexing : ConfigIndex.Indexing Γ Λ σ) (roots : List Nat) (S : Nat) + (bit : ConfigBit Γ Λ σ S) : Nat := + rootLookup roots (indexing.configIndexEquiv S bit).val + +omit [∀ k, DecidableEq (Γ k)] [DecidableEq K] [Fintype σ] [DecidableEq σ] + [∀ k, Fintype (Γ k)] [DecidableEq Λ] [Fintype Λ] in +theorem labelAddress_lt_width (indexing : ConfigIndex.Indexing Γ Λ σ) + (S : Nat) (label : Option Λ) : + (indexing.labels label).val < indexing.width S := by + simpa only [ConfigIndex.Indexing.configIndex_label] using + (indexing.configIndexEquiv S (.inl label)).isLt + +omit [∀ k, DecidableEq (Γ k)] [DecidableEq K] [Fintype σ] [DecidableEq σ] + [∀ k, Fintype (Γ k)] [DecidableEq Λ] [Fintype Λ] in +theorem stateAddress_lt_width (indexing : ConfigIndex.Indexing Γ Λ σ) + (S : Nat) (state : σ) : + indexing.labelCount + (indexing.states state).val < indexing.width S := by + simpa only [ConfigIndex.Indexing.configIndex_state] using + (indexing.configIndexEquiv S (.inr (.inl state))).isLt + +omit [∀ k, DecidableEq (Γ k)] [DecidableEq K] [Fintype σ] [DecidableEq σ] + [∀ k, Fintype (Γ k)] [DecidableEq Λ] [Fintype Λ] in +theorem cellAddress_lt_width (indexing : ConfigIndex.Indexing Γ Λ σ) + (S : Nat) (k : K) (position : Nat) (symbol : Option (Γ k)) (hp : position < S) : + indexing.labelCount + indexing.stateCount + position * indexing.symbolCount + + (indexing.symbols ⟨k, symbol⟩).val < indexing.width S := by + simpa only [ConfigIndex.Indexing.configIndex_cell] using + (indexing.configIndexEquiv S (.inr (.inr ⟨k, ⟨position, hp⟩, symbol⟩))).isLt + +omit [∀ k, DecidableEq (Γ k)] [DecidableEq K] [Fintype σ] [DecidableEq σ] + [∀ k, Fintype (Γ k)] [DecidableEq Λ] [Fintype Λ] in +theorem rootLookup_present (indexing : ConfigIndex.Indexing Γ Λ σ) (roots : List Nat) + (S : Nat) (hroots : indexing.width S ≤ roots.length) + (address : Nat) (haddress : address < indexing.width S) : + roots[address]? = some (rootLookup roots address) := by + have h : address < roots.length := haddress.trans_le hroots + simp only [rootLookup, List.getElem?_eq_getElem h, Option.getD_some] + +omit [∀ k, DecidableEq (Γ k)] [DecidableEq K] [Fintype σ] [DecidableEq σ] + [∀ k, Fintype (Γ k)] [DecidableEq Λ] [Fintype Λ] in +theorem configWire_present (indexing : ConfigIndex.Indexing Γ Λ σ) (roots : List Nat) + (S : Nat) (hroots : indexing.width S ≤ roots.length) (bit : ConfigBit Γ Λ σ S) : + roots[(indexing.configIndexEquiv S bit).val]? = some (configWire indexing roots S bit) := + rootLookup_present indexing roots S hroots _ (indexing.configIndexEquiv S bit).isLt + +def Term.tokens (indexing : ConfigIndex.Indexing Γ Λ σ) (roots : List Nat) + (S cursor : Nat) : Term Γ σ → List PostfixModel.Token + | .state v => [.input (rootLookup roots + (indexing.labelCount + (indexing.states v).val))] + | .cell k p a => if p.eval cursor < S then + [.input (rootLookup roots (indexing.labelCount + indexing.stateCount + + p.eval cursor * indexing.symbolCount + (indexing.symbols ⟨k, a⟩).val))] + else [.const (decide ((none : Option (Γ k)) = a))] + | .const b => [.const b] + | .not e => e.tokens indexing roots S cursor ++ [.not] + | .and e f => e.tokens indexing roots S cursor ++ f.tokens indexing roots S cursor ++ [.and] + | .or e f => e.tokens indexing roots S cursor ++ f.tokens indexing roots S cursor ++ [.or] + | .atZero p yes no => if p.eval cursor = 0 then yes.tokens indexing roots S cursor + else no.tokens indexing roots S cursor + | .within p yes no => if p.eval cursor < S then yes.tokens indexing roots S cursor + else no.tokens indexing roots S cursor + +omit [∀ k, DecidableEq (Γ k)] [DecidableEq K] [Fintype σ] [DecidableEq σ] + [∀ k, Fintype (Γ k)] [DecidableEq Λ] [Fintype Λ] in +theorem Term.tokens_eq (indexing : ConfigIndex.Indexing Γ Λ σ) (roots : List Nat) + (S cursor : Nat) (term : Term Γ σ) : + term.tokens indexing roots S cursor = + PostfixAlignment.exprTokens (fun bit => configWire indexing roots S (.inr bit)) + (term.instantiate S cursor) := by + induction term with + | state v => simp [tokens, instantiate, PostfixAlignment.exprTokens, configWire] + | cell k p a => + by_cases h : p.eval cursor < S <;> + simp [tokens, instantiate, h, PostfixAlignment.exprTokens, configWire] + | const b => rfl + | not e ih => simp only [tokens, instantiate, PostfixAlignment.exprTokens, ih] + | and e f ihe ihf => simp only [tokens, instantiate, PostfixAlignment.exprTokens, ihe, ihf] + | or e f ihe ihf => simp only [tokens, instantiate, PostfixAlignment.exprTokens, ihe, ihf] + | atZero p e f ihe ihf => + by_cases h : p.eval cursor = 0 <;> simp [tokens, instantiate, h, ihe, ihf] + | within p e f ihe ihf => + by_cases h : p.eval cursor < S <;> simp [tokens, instantiate, h, ihe, ihf] + +def Global.tokens (indexing : ConfigIndex.Indexing Γ Λ σ) (roots : List Nat) + (S cursor : Nat) : Global (Γ := Γ) (Λ := Λ) (σ := σ) → List PostfixModel.Token + | .label l => [.input (rootLookup roots (indexing.labels l).val)] + | .data e => e.tokens indexing roots S cursor + | .const b => [.const b] + | .and e f => e.tokens indexing roots S cursor ++ f.tokens indexing roots S cursor ++ [.and] + | .or e f => e.tokens indexing roots S cursor ++ f.tokens indexing roots S cursor ++ [.or] + +omit [∀ k, DecidableEq (Γ k)] [DecidableEq K] [Fintype σ] [DecidableEq σ] + [∀ k, Fintype (Γ k)] [DecidableEq Λ] [Fintype Λ] in +theorem Global.tokens_eq (indexing : ConfigIndex.Indexing Γ Λ σ) (roots : List Nat) + (S cursor : Nat) (term : Global (Γ := Γ) (Λ := Λ) (σ := σ)) : + term.tokens indexing roots S cursor = + PostfixAlignment.exprTokens (configWire indexing roots S) (term.instantiate S cursor) := by + induction term with + | label l => simp [tokens, instantiate, PostfixAlignment.exprTokens, configWire] + | data e => + simp only [tokens, instantiate, PostfixAlignment.exprTokens_rename] + exact e.tokens_eq indexing roots S cursor + | const b => rfl + | and e f ihe ihf => simp only [tokens, instantiate, PostfixAlignment.exprTokens, ihe, ihf] + | or e f ihe ihf => simp only [tokens, instantiate, PostfixAlignment.exprTokens, ihe, ihf] + +theorem sticky_tokens_eq (indexing : ConfigIndex.Indexing Γ Λ σ) (roots : List Nat) + (S : Nat) (program : Λ → TM2.Stmt Γ Λ σ) (bit : ConfigBit Γ Λ σ S) : + (sticky program (bitKind bit)).tokens indexing roots S (bitCursor bit) = + PostfixAlignment.exprTokens (configWire indexing roots S) + (MachineCircuit.stickyExpr S program bit) := by + rw [Global.tokens_eq, sticky_instantiate] + +omit [∀ k, DecidableEq (Γ k)] [DecidableEq K] [Fintype σ] [DecidableEq σ] + [∀ k, Fintype (Γ k)] [DecidableEq Λ] [Fintype Λ] in +theorem Global.tokens_length_le (indexing : ConfigIndex.Indexing Γ Λ σ) (roots : List Nat) + (S cursor : Nat) (term : Global (Γ := Γ) (Λ := Λ) (σ := σ)) : + (term.tokens indexing roots S cursor).length ≤ term.nodeCount := by + rw [term.tokens_eq, PostfixAlignment.exprTokens_length] + exact term.instantiate_size_le S cursor + +theorem sticky_tokens_length_le (indexing : ConfigIndex.Indexing Γ Λ σ) (roots : List Nat) + (S : Nat) (program : Λ → TM2.Stmt Γ Λ σ) (bit : ConfigBit Γ Λ σ S) : + ((sticky program (bitKind bit)).tokens indexing roots S (bitCursor bit)).length ≤ + MachineCircuit.expressionCost program := by + rw [sticky_tokens_eq, PostfixAlignment.exprTokens_length] + exact MachineCircuit.stickyExpr_size_le S program bit + +def outputOrder (indexing : ConfigIndex.Indexing Γ Λ σ) (S : Nat) : + List (ConfigBit Γ Λ σ S) := + (List.finRange (indexing.width S)).map (indexing.configIndexEquiv S).symm + +noncomputable def forestTokens (indexing : ConfigIndex.Indexing Γ Λ σ) (roots : List Nat) + (S : Nat) (program : Λ → TM2.Stmt Γ Λ σ) : List PostfixModel.Token := + (outputOrder indexing S).flatMap fun bit => + (sticky program (bitKind bit)).tokens indexing roots S (bitCursor bit) + +theorem forestTokens_eq (indexing : ConfigIndex.Indexing Γ Λ σ) (roots : List Nat) + (S : Nat) (program : Λ → TM2.Stmt Γ Λ σ) : + forestTokens indexing roots S program = + PostfixAlignment.forestTokens (configWire indexing roots S) + ((outputOrder indexing S).map (MachineCircuit.stickyExpr S program)) := by + simp only [forestTokens, PostfixAlignment.forestTokens, List.flatMap_map] + apply List.flatMap_congr + intro bit _ + exact sticky_tokens_eq indexing roots S program bit + +omit [∀ k, DecidableEq (Γ k)] [DecidableEq K] [Fintype σ] [DecidableEq σ] + [∀ k, Fintype (Γ k)] [DecidableEq Λ] [Fintype Λ] in +@[simp] theorem outputOrder_length (indexing : ConfigIndex.Indexing Γ Λ σ) (S : Nat) : + (outputOrder indexing S).length = indexing.width S := by + simp [outputOrder] + +theorem forestTokens_length_le (indexing : ConfigIndex.Indexing Γ Λ σ) (roots : List Nat) + (S : Nat) (program : Λ → TM2.Stmt Γ Λ σ) : + (forestTokens indexing roots S program).length ≤ + indexing.width S * MachineCircuit.expressionCost program := by + have h (bits : List (ConfigBit Γ Λ σ S)) : + (bits.flatMap fun bit => + (sticky program (bitKind bit)).tokens indexing roots S (bitCursor bit)).length ≤ + bits.length * MachineCircuit.expressionCost program := by + induction bits with + | nil => simp + | cons bit bits ih => + have hb := sticky_tokens_length_le indexing roots S program bit + simp only [List.flatMap_cons, List.length_append, List.length_cons, Nat.succ_mul] + omega + simpa only [forestTokens, outputOrder_length] using h (outputOrder indexing S) + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.TransitionTemplate + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/TupleEnumerationMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/TupleEnumerationMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..fc818c49eb72f0d30bf545f0d8866ac51cf57a7a --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/TupleEnumerationMachine.lean @@ -0,0 +1,419 @@ +import OAI.Computability.PerfectCompleteness.Foundations.TupleIndexEmitterLemmas +import OAI.Computability.UniqueGames.Machines.MachineTupleOdometer + +namespace OAI + + +namespace PerfectCompleteness.TupleEnumerationMachine + +open Turing UniqueGamesTheorem.Foundations.Complexity +open scoped BigOperators + + +abbrev Tape (width : Nat) (Extra : Type) := TupleIndexEmitter.Tape width (Fin width ⊕ Extra) + +inductive Label (width : Nat) + | emit (label : TupleIndexEmitter.Label width) + | check (coordinate : Fin width) + | reset (coordinate : Fin width) + | exit + deriving DecidableEq, Fintype + +variable {width : Nat} {Extra : Type} [DecidableEq Extra] + +abbrev Alphabet (_ : Tape width Extra) := Bool +abbrev Register := Unit × Option Bool +abbrev Configuration := TM2.Cfg (Alphabet (width := width) (Extra := Extra)) + (Label width) Register + +def checkAt (depth : Nat) : Label width := + if h : depth < width then .check ⟨depth, h⟩ else .exit + +def currentAt (depth : Nat) : Tape width Extra := + if h : depth < width then .current ⟨depth, h⟩ else .scratch + +def remainingAt (depth : Nat) : Tape width Extra := + if h : depth < width then .extra (.inl ⟨depth, h⟩) else .output + +def body : Label width := .emit (TupleIndexEmitter.labelAt width) + +def program : Label width → + TM2.Stmt (Alphabet (width := width) (Extra := Extra)) (Label width) Register + | .emit l => MachineSubroutine.statement Label.emit (some (checkAt 0)) (TupleIndexEmitter.program l) + | .check i => MachineTupleOdometer.increment (.current i) (.extra (.inl i)) body (.reset i) + | .reset i => MachineTupleOdometer.reset (.current i) (.extra (.inl i)) (.reset i) (checkAt (i.val + 1)) + | .exit => .halt + +def resetAt (depth : Nat) : Label width := + if h : depth < width then .reset ⟨depth, h⟩ else .exit + +def tapes (radix : Nat) (digits : Fin width → Nat) (output : List Bool) + (extra : Extra → List Bool) : Tape width Extra → List Bool + | .current i => encodeWord (digits i) + | .scratch => [] + | .output => output + | .extra (.inl i) => encodeWord (radix - 1 - digits i) + | .extra (.inr x) => extra x + +def configuration (label : Label width) (radix : Nat) (digits : Fin width → Nat) + (output : List Bool) (extra : Extra → List Bool) : + Configuration (width := width) (Extra := Extra) := + ⟨some label, ((), none), tapes radix digits output extra⟩ + +def setDigit (digits : Fin width → Nat) (depth value : Nat) : Fin width → Nat := + fun i => if i.val = depth then value else digits i + +@[simp] theorem setDigit_self (digits : Fin width → Nat) (i : Fin width) (value : Nat) : + setDigit digits i.val value i = value := by simp [setDigit] + +theorem setDigit_zero (digits : Fin width → Nat) (depth : Nat) + (hzero : ∀ i, i.val = depth → digits i = 0) : setDigit digits depth 0 = digits := by + funext i + by_cases hi : i.val = depth + · simp [setDigit, hi, hzero i hi] + · simp [setDigit, hi] + +def prependBlocks (blocks : Nat → List Bool) : Nat → List Bool + | 0 => [] + | count + 1 => blocks count ++ prependBlocks blocks count + +theorem prependBlocks_eq (blocks : Nat → List Bool) (count : Nat) : + prependBlocks blocks count = (List.range count).reverse.flatMap blocks := by + induction count with + | zero => simp [prependBlocks] + | succ count ih => simp [prependBlocks, List.range_succ, ih] + +def outputBlock (radix : Nat) : Nat → (Fin width → Nat) → List Bool + | 0, digits => encodeWords (List.ofFn digits) + | depth + 1, digits => + prependBlocks (fun value => outputBlock radix depth (setDigit digits depth value)) radix + +@[simp] theorem outputBlock_zero (radix : Nat) (digits : Fin width → Nat) : + outputBlock radix 0 digits = encodeWords (List.ofFn digits) := rfl + +theorem outputBlock_succ (radix depth : Nat) (digits : Fin width → Nat) : + outputBlock radix (depth + 1) digits = (List.range radix).reverse.flatMap + (fun value => outputBlock radix depth (setDigit digits depth value)) := by + exact prependBlocks_eq _ _ + +def fillDigits (digits : Fin width → Nat) {radix depth : Nat} + (tuple : Fin depth → Fin radix) : Fin width → Nat := + fun i => if h : i.val < depth then (tuple ⟨i.val, h⟩).val else digits i + +private theorem fillDigits_snoc (digits : Fin width → Nat) {radix depth : Nat} + (tuple : Fin depth → Fin radix) (value : Fin radix) : + fillDigits digits (Fin.snoc tuple value) = + fillDigits (setDigit digits depth value.val) tuple := by + funext i + by_cases hi : i.val < depth + · have hi' : i.val < depth + 1 := by omega + simp [fillDigits, hi, hi', Fin.snoc] + · by_cases heq : i.val = depth + · simp [fillDigits, Fin.snoc, setDigit, heq] + · have hi' : ¬i.val < depth + 1 := by omega + simp [fillDigits, hi, hi', setDigit, heq] + +private theorem range_eq_ofFn (radix : Nat) : + List.range radix = (List.ofFn (fun i : Fin radix => i)).map Fin.val := by + apply List.ext_getElem + · simp + · intro i hi hj + simp + +theorem outputBlock_eq_tupleOrder (radix depth : Nat) (digits : Fin width → Nat) : + outputBlock radix depth digits = + (MachineTupleOdometer.tupleOrder radix depth).reverse.flatMap + (fun tuple => encodeWords (List.ofFn (fillDigits digits tuple))) := by + induction depth generalizing digits with + | zero => + rw [outputBlock_zero, MachineTupleOdometer.tupleOrder_dimension_zero] + simp only [List.reverse_singleton, List.flatMap_singleton] + apply congrArg encodeWords + apply congrArg List.ofFn + funext i + simp [fillDigits] + | succ depth ih => + rw [outputBlock_succ, range_eq_ofFn, ← List.map_reverse, List.flatMap_map, + MachineTupleOdometer.tupleOrder_snoc, List.reverse_flatMap, List.flatMap_assoc] + apply List.flatMap_congr + intro value _ + change outputBlock radix depth (setDigit digits depth value.val) = + ((MachineTupleOdometer.tupleOrder radix depth).map + (fun tuple => Fin.snoc tuple value)).reverse.flatMap + (fun tuple => encodeWords (List.ofFn (fillDigits digits tuple))) + rw [← List.map_reverse, List.flatMap_map, ih] + apply List.flatMap_congr + intro tuple _ + change encodeWords (List.ofFn (fillDigits (setDigit digits depth value.val) tuple)) = + encodeWords (List.ofFn (fillDigits digits (Fin.snoc tuple value))) + rw [fillDigits_snoc] + +@[simp] theorem fillDigits_all (digits : Fin width → Nat) {radix : Nat} + (tuple : Fin width → Fin radix) : fillDigits digits tuple = fun i => (tuple i).val := by + funext i + simp [fillDigits, i.isLt] + +theorem outputBlock_all (radix : Nat) : + outputBlock radix width (fun _ : Fin width => 0) = + (MachineTupleOdometer.tupleOrder radix width).reverse.flatMap + (fun tuple => encodeWords (List.ofFn (fun i => (tuple i).val))) := by + simpa only [fillDigits_all] using + outputBlock_eq_tupleOrder radix width (fun _ : Fin width => 0) + +private theorem tapes_output (radix : Nat) (digits : Fin width → Nat) + (output bits : List Bool) (extra : Extra → List Bool) : + TupleIndexEmitter.outputTapes (tapes radix digits output extra) bits = + tapes radix digits (bits ++ output) extra := by + funext tape + cases tape with + | current i => simp [TupleIndexEmitter.outputTapes, tapes] + | scratch => simp [TupleIndexEmitter.outputTapes, tapes] + | output => simp [TupleIndexEmitter.outputTapes, tapes] + | extra x => cases x <;> simp [TupleIndexEmitter.outputTapes, tapes] + +private theorem tapes_digit (radix depth remainder : Nat) (hdepth : depth < width) + (hremainder : remainder ≤ radix - 1) (digits : Fin width → Nat) + (output : List Bool) (extra : Extra → List Bool) : + MachineTupleOdometer.digitTapes (currentAt depth) (remainingAt depth) + (tapes radix digits output extra) (radix - 1 - remainder) remainder [] [] = + tapes radix (setDigit digits depth (radix - 1 - remainder)) output extra := by + have hsub : radix - 1 - (radix - 1 - remainder) = remainder := by omega + funext tape + cases tape with + | current i => + by_cases hi : i.val = depth + · have heq : i = (⟨depth, hdepth⟩ : Fin width) := Fin.ext hi + subst i + simp [MachineTupleOdometer.digitTapes, MachineUnaryAddAt.unaryTapes, + UniqueGamesTheorem.Reduction.MachineTransfer.tapesAt, currentAt, remainingAt, + hdepth, tapes, setDigit] + · have heq : i ≠ (⟨depth, hdepth⟩ : Fin width) := fun h => hi (congrArg Fin.val h) + simp [MachineTupleOdometer.digitTapes, MachineUnaryAddAt.unaryTapes, + UniqueGamesTheorem.Reduction.MachineTransfer.tapesAt, currentAt, remainingAt, + hdepth, tapes, setDigit, hi, heq] + | scratch => + simp [MachineTupleOdometer.digitTapes, MachineUnaryAddAt.unaryTapes, + UniqueGamesTheorem.Reduction.MachineTransfer.tapesAt, currentAt, remainingAt, hdepth, tapes] + | output => + simp [MachineTupleOdometer.digitTapes, MachineUnaryAddAt.unaryTapes, + UniqueGamesTheorem.Reduction.MachineTransfer.tapesAt, currentAt, remainingAt, hdepth, tapes] + | extra x => + cases x with + | inl i => + by_cases hi : i.val = depth + · have heq : i = (⟨depth, hdepth⟩ : Fin width) := Fin.ext hi + subst i + simp [MachineTupleOdometer.digitTapes, MachineUnaryAddAt.unaryTapes, + UniqueGamesTheorem.Reduction.MachineTransfer.tapesAt, currentAt, remainingAt, + hdepth, tapes, setDigit, hsub] + · have heq : i ≠ (⟨depth, hdepth⟩ : Fin width) := fun h => hi (congrArg Fin.val h) + simp [MachineTupleOdometer.digitTapes, MachineUnaryAddAt.unaryTapes, + UniqueGamesTheorem.Reduction.MachineTransfer.tapesAt, currentAt, remainingAt, + hdepth, tapes, setDigit, hi, heq] + | inr x => + simp [MachineTupleOdometer.digitTapes, MachineUnaryAddAt.unaryTapes, + UniqueGamesTheorem.Reduction.MachineTransfer.tapesAt, currentAt, remainingAt, hdepth, tapes] + +noncomputable def leafInTime (radix : Nat) (digits : Fin width → Nat) + (output : List Bool) (extra : Extra → List Bool) : + StateTransition.EvalsToInTime (TM2.step program) + (configuration body radix digits output extra) + (some (configuration (checkAt 0) radix digits + (outputBlock radix 0 digits ++ output) extra)) + ((∑ i, 2 * (digits i + 2)) + 1) := by + have copied := TupleIndexEmitter.placedEmitInTime Label.emit (some (checkAt 0)) program + (fun _ => rfl) digits (tapes radix digits output extra) (fun _ => rfl) rfl () + have returned : StateTransition.EvalsToInTime (TM2.step program) + ⟨some (.emit .done), ((), none), + TupleIndexEmitter.outputTapes (tapes radix digits output extra) (encodeWords (List.ofFn digits))⟩ + (some ⟨some (checkAt 0), ((), none), + TupleIndexEmitter.outputTapes (tapes radix digits output extra) (encodeWords (List.ofFn digits))⟩) 1 := + { steps := 1, evals_in_steps := rfl, steps_le_m := Nat.le_refl _ } + have joined := StateTransition.EvalsToInTime.trans (TM2.step program) _ _ _ _ _ copied returned + simpa only [configuration, body, outputBlock_zero, tapes_output, Nat.add_comm] using joined + +def leafBound (width radix : Nat) := 2 * width * (radix + 1) + 1 + +private theorem leafBudget_le (radix : Nat) (digits : Fin width → Nat) + (bounded : ∀ i, digits i < radix) : + (∑ i, 2 * (digits i + 2)) + 1 ≤ leafBound width radix := by + have hsum : (∑ i, 2 * (digits i + 2)) ≤ ∑ _i : Fin width, 2 * (radix + 1) := by + apply Finset.sum_le_sum + intro i _ + exact Nat.mul_le_mul_left 2 (by have := bounded i; omega) + simpa [leafBound, Nat.mul_assoc, Nat.mul_left_comm, Nat.mul_comm] using + Nat.add_le_add_right hsum 1 + +theorem existsTree (radix : Nat) (positive : 0 < radix) (depth : Nat) (hdepth : depth ≤ width) + (digits : Fin width → Nat) (zero : ∀ i, i.val < depth → digits i = 0) + (bounded : ∀ i, digits i < radix) (output : List Bool) (extra : Extra → List Bool) : + ∃ tree : MachineTupleOdometer.NestedCycle radix currentAt remainingAt body checkAt resetAt program depth + (checkAt depth) (configuration body radix digits output extra) + (configuration (checkAt depth) radix digits (outputBlock radix depth digits ++ output) extra), + tree.LeafBound (leafBound width radix) := by + induction depth generalizing digits output with + | zero => + let run := leafInTime radix digits output extra + refine ⟨.leaf (checkAt 0) + (configuration body radix digits output extra) + (configuration (checkAt 0) radix digits (outputBlock radix 0 digits ++ output) extra) + run.steps rfl rfl run.evals_in_steps, ?_⟩ + erw [MachineTupleOdometer.NestedCycle.LeafBound] + exact run.steps_le_m.trans (leafBudget_le radix digits bounded) + | succ depth ih => + have hlt : depth < width := by omega + let blocks := fun value => outputBlock radix depth (setDigit digits depth value) + let emittedPrefix := prependBlocks blocks + let schedule : MachineTupleOdometer.CycleSchedule (Tape width Extra) Unit := + { + currentSuffix := [] + remainingSuffix := [] + ambient := fun _ => () + register := fun _ => none + base := fun r => tapes radix digits (emittedPrefix (radix - r) ++ output) extra + } + have children : ∀ r : Fin radix, + ∃ tree : MachineTupleOdometer.NestedCycle radix currentAt remainingAt body checkAt resetAt program depth + (checkAt depth) + (MachineTupleOdometer.bodyConfiguration (currentAt depth) (remainingAt depth) body (radix - 1) r.val + schedule.currentSuffix schedule.remainingSuffix schedule.ambient schedule.base) + (MachineTupleOdometer.checkConfiguration (currentAt depth) (remainingAt depth) (checkAt depth) + (radix - 1) r.val schedule.currentSuffix schedule.remainingSuffix + schedule.ambient schedule.register schedule.base), + tree.LeafBound (leafBound width radix) := by + intro r + have hr : r.val ≤ radix - 1 := by omega + have hvalue : radix - 1 - r.val < radix := by omega + have hbefore : radix - (r.val + 1) = radix - 1 - r.val := by omega + have hafter : radix - r.val = (radix - 1 - r.val) + 1 := by omega + have hz : ∀ i, i.val < depth → setDigit digits depth (radix - 1 - r.val) i = 0 := by + intro i hi + simp only [setDigit, ite_eq_right (by omega : i.val ≠ depth)] + exact zero i (by omega) + have hb : ∀ i, setDigit digits depth (radix - 1 - r.val) i < radix := by + intro i + by_cases hi : i.val = depth + · simpa [setDigit, hi] using hvalue + · simpa [setDigit, hi] using bounded i + obtain ⟨tree, ht⟩ := ih (by omega) (setDigit digits depth (radix - 1 - r.val)) hz hb + (emittedPrefix (radix - (r.val + 1)) ++ output) + have hout : outputBlock radix depth (setDigit digits depth (radix - 1 - r.val)) ++ + (emittedPrefix (radix - (r.val + 1)) ++ output) = emittedPrefix (radix - r.val) ++ output := by + rw [hbefore, hafter] + simp only [emittedPrefix, prependBlocks, blocks, List.append_assoc] + have childExists : + ∃ child : MachineTupleOdometer.NestedCycle radix currentAt remainingAt body + checkAt resetAt program depth (checkAt depth) + (configuration body radix (setDigit digits depth (radix - 1 - r.val)) + (emittedPrefix (radix - (r.val + 1)) ++ output) extra) + (configuration (checkAt depth) radix (setDigit digits depth (radix - 1 - r.val)) + (outputBlock radix depth (setDigit digits depth (radix - 1 - r.val)) ++ + (emittedPrefix (radix - (r.val + 1)) ++ output)) extra), + child.LeafBound (leafBound width radix) := ⟨tree, ht⟩ + rw [hout] at childExists + have childStart : + configuration body radix (setDigit digits depth (radix - 1 - r.val)) + (emittedPrefix (radix - (r.val + 1)) ++ output) extra = + MachineTupleOdometer.bodyConfiguration (currentAt depth) (remainingAt depth) body + (radix - 1) r.val schedule.currentSuffix schedule.remainingSuffix + schedule.ambient schedule.base := by + dsimp only [MachineTupleOdometer.bodyConfiguration, schedule, configuration] + rw [tapes_digit radix depth r.val hlt hr] + have childFinish : + configuration (checkAt depth) radix (setDigit digits depth (radix - 1 - r.val)) + (emittedPrefix (radix - r.val) ++ output) extra = + MachineTupleOdometer.checkConfiguration (currentAt depth) (remainingAt depth) + (checkAt depth) (radix - 1) r.val schedule.currentSuffix schedule.remainingSuffix + schedule.ambient schedule.register schedule.base := by + dsimp only [MachineTupleOdometer.checkConfiguration, schedule, configuration] + rw [tapes_digit radix depth r.val hlt hr] + rw [childStart, childFinish] at childExists + exact childExists + let chosen := fun r => Classical.choose (children r) + have chosenBound : ∀ r, (chosen r).LeafBound (leafBound width radix) := + fun r => Classical.choose_spec (children r) + have distinct : currentAt (width := width) (Extra := Extra) depth ≠ remainingAt depth := by + simp [currentAt, remainingAt, hlt] + have atCheck : program (width := width) (Extra := Extra) (checkAt depth) = + MachineTupleOdometer.increment (currentAt depth) (remainingAt depth) body (resetAt depth) := by + simp [program, checkAt, currentAt, remainingAt, resetAt, hlt] + have atReset : program (width := width) (Extra := Extra) (resetAt depth) = + MachineTupleOdometer.reset (currentAt depth) (remainingAt depth) (resetAt depth) (checkAt (depth + 1)) := by + simp [program, resetAt, currentAt, remainingAt, hlt] + let tree := MachineTupleOdometer.NestedCycle.node depth (checkAt (depth + 1)) positive distinct + atCheck atReset schedule chosen + have treeBound : tree.LeafBound (leafBound width radix) := by + simpa only [tree, MachineTupleOdometer.NestedCycle.LeafBound] using chosenBound + have hz : setDigit digits depth 0 = digits := + setDigit_zero digits depth (fun i hi => zero i (by omega)) + have startTape : MachineTupleOdometer.digitTapes (currentAt depth) (remainingAt depth) + (tapes radix digits (emittedPrefix (radix - ((radix - 1) + 1)) ++ output) extra) + (radix - 1 - (radix - 1)) (radix - 1) [] [] = tapes radix digits output extra := by + rw [tapes_digit radix depth (radix - 1) hlt (Nat.le_refl _)] + simp only [Nat.sub_self, hz] + have hn : radix - 1 + 1 = radix := by omega + simp [hn, emittedPrefix, prependBlocks] + have finishTape : MachineTupleOdometer.digitTapes (currentAt depth) (remainingAt depth) + (tapes radix digits (emittedPrefix (radix - 0) ++ output) extra) 0 (radix - 1) [] [] = + tapes radix digits (outputBlock radix (depth + 1) digits ++ output) extra := by + have h := tapes_digit radix depth (radix - 1) hlt (Nat.le_refl _) + digits (emittedPrefix radix ++ output) extra + simpa only [Nat.sub_self, Nat.sub_zero, hz, outputBlock, emittedPrefix, blocks] using h + have nodeExists : + ∃ node : MachineTupleOdometer.NestedCycle radix currentAt remainingAt body + checkAt resetAt program (depth + 1) (checkAt (depth + 1)) + (MachineTupleOdometer.bodyConfiguration (currentAt depth) (remainingAt depth) body + (radix - 1) (radix - 1) schedule.currentSuffix schedule.remainingSuffix + schedule.ambient schedule.base) + (MachineTupleOdometer.cycleExit (currentAt depth) (remainingAt depth) + (checkAt (depth + 1)) (radix - 1) schedule.currentSuffix schedule.remainingSuffix + schedule.ambient schedule.base), + node.LeafBound (leafBound width radix) := ⟨tree, treeBound⟩ + have nodeStart : + MachineTupleOdometer.bodyConfiguration (currentAt depth) (remainingAt depth) body + (radix - 1) (radix - 1) schedule.currentSuffix schedule.remainingSuffix + schedule.ambient schedule.base = configuration body radix digits output extra := by + dsimp only [MachineTupleOdometer.bodyConfiguration, schedule, configuration] + rw [startTape] + have nodeFinish : + MachineTupleOdometer.cycleExit (currentAt depth) (remainingAt depth) + (checkAt (depth + 1)) (radix - 1) schedule.currentSuffix schedule.remainingSuffix + schedule.ambient schedule.base = + configuration (checkAt (depth + 1)) radix digits + (outputBlock radix (depth + 1) digits ++ output) extra := by + dsimp only [MachineTupleOdometer.cycleExit, schedule, configuration] + rw [finishTape] + rw [nodeStart, nodeFinish] at nodeExists + exact nodeExists + +noncomputable def enumerateInTime (radix : Nat) (positive : 0 < radix) + (output : List Bool) (extra : Extra → List Bool) : + StateTransition.EvalsToInTime (TM2.step (program (width := width) (Extra := Extra))) + (configuration body radix (fun _ : Fin width => 0) output extra) + (some (configuration .exit radix (fun _ : Fin width => 0) + (outputBlock radix width (fun _ : Fin width => 0) ++ output) extra)) + ((leafBound width radix + 2 * width) * radix ^ width) := by + let witness := existsTree radix positive width (Nat.le_refl _) + (fun _ => 0) (fun _ _ => rfl) (fun _ => positive) output extra + let tree := Classical.choose witness + have bounded := Classical.choose_spec witness + refine { steps := tree.steps, evals_in_steps := ?_, steps_le_m := ?_ } + · change (MachineComposition.advance (TM2.step program))^[tree.steps] + (some (configuration body radix (fun _ : Fin width => 0) output extra)) = _ + simpa only [checkAt, Nat.lt_irrefl, ↓reduceDIte] using tree.trace + · exact tree.steps_le_power positive (leafBound width radix) bounded + +def machine (width : Nat) (Extra : Type) [DecidableEq Extra] [Fintype Extra] : FinTM2 where + K := Tape width Extra + k₀ := .scratch + k₁ := .output + Γ _ := Bool + Λ := Label width + main := body + σ := Register + initialState := ((), none) + m := program + +end PerfectCompleteness.TupleEnumerationMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/TupleIndexMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/TupleIndexMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..d2b9e294c3cc28487223b87a5000ab079b2082e9 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/TupleIndexMachine.lean @@ -0,0 +1,303 @@ +import OAI.Computability.PerfectCompleteness.Machines.TupleEnumerationMachine +import OAI.Computability.PerfectCompleteness.Machines.TupleInitializationMachine +import OAI.Computability.UniqueGames.Machines.MachineDrainManyLemmas + +namespace OAI + + +namespace PerfectCompleteness.TupleIndexMachine + + +open Turing UniqueGamesTheorem.Foundations.Complexity +open MachineComposition +open scoped BigOperators + +abbrev Tape (width : Nat) := TupleEnumerationMachine.Tape width Unit +abbrev Register := Unit × Option Bool + +def source {width : Nat} : Tape width := .extra (.inr ()) + +def cleanupTapes (width : Nat) : List (Tape width) := + [.scratch, source] ++ TupleInitializationMachine.currentDestinations width Unit ++ + TupleInitializationMachine.remainingDestinations width Unit + +abbrev Label (width : Nat) := TupleInitializationMachine.Label ⊕ + (TupleEnumerationMachine.Label width ⊕ MachineDrainMany.Label (cleanupTapes width)) + +variable {width : Nat} + +def initLabel (label : TupleInitializationMachine.Label) : Label width := .inl label + +def enumerationLabel (label : TupleEnumerationMachine.Label width) : Label width := + .inr (.inl label) + +def cleanupLabel (label : MachineDrainMany.Label (cleanupTapes width)) : Label width := + .inr (.inr label) + +def cleanupEntry : Option (Label width) := + MachineDrainMany.entry (cleanupTapes width) cleanupLabel none + +def program : Label width → TM2.Stmt (fun _ : Tape width => Bool) (Label width) Register + | .inl label => TupleInitializationMachine.arenaInstruction () initLabel + (some (enumerationLabel TupleEnumerationMachine.body)) label + | .inr (.inl label) => MachineSubroutine.statement enumerationLabel cleanupEntry + (TupleEnumerationMachine.program label) + | .inr (.inr label) => MachineDrainMany.instruction (cleanupTapes width) cleanupLabel none label + +def machine (width : Nat) : FinTM2 where + K := Tape width + k₀ := source + k₁ := .output + Γ _ := Bool + Λ := Label width + main := initLabel .seed + σ := Register + initialState := ((), none) + m := program + +def cfg (label : Option (Label width)) (tapes : Tape width → List Bool) : + (machine width).Cfg := ⟨label, ((), none), tapes⟩ + +def inputTapes (radix : Nat) : Tape width → List Bool := + fun tape => if tape = source then encodeWord radix else [] + +def output (width radix : Nat) : List Bool := + TupleEnumerationMachine.outputBlock radix width (fun _ : Fin width => 0) + +def readyTapes (radix : Nat) : Tape width → List Bool := + TupleEnumerationMachine.tapes radix (fun _ => 0) [] (fun _ => []) + +def emittedTapes (radix : Nat) : Tape width → List Bool := + TupleEnumerationMachine.tapes radix (fun _ => 0) (output width radix) (fun _ => []) + +theorem output_eq (width radix : Nat) : + output width radix = + (MachineTupleOdometer.tupleOrder radix width).reverse.flatMap + (fun tuple => encodeWords (List.ofFn (fun i => (tuple i).val))) := + TupleEnumerationMachine.outputBlock_all (width := width) radix + +private theorem initialized_eq (radix : Nat) : + TupleInitializationMachine.arenaInitializedTapes () (inputTapes (width := width) radix) + (radix - 1) [] = readyTapes radix := by + funext tape + cases tape with + | current i => + rw [TupleInitializationMachine.arenaInitializedTapes_current] + · rfl + · simp [inputTapes, source] + | scratch => + rw [TupleInitializationMachine.arenaInitializedTapes_scratch] + simp [inputTapes, source, readyTapes, TupleEnumerationMachine.tapes] + | output => + rw [TupleInitializationMachine.arenaInitializedTapes_output] + simp [inputTapes, source, readyTapes, TupleEnumerationMachine.tapes] + | extra value => + cases value with + | inl i => + rw [TupleInitializationMachine.arenaInitializedTapes_remaining] + · simp only [readyTapes, TupleEnumerationMachine.tapes, Nat.sub_zero] + · simp [inputTapes, source] + | inr value => + cases value + rw [TupleInitializationMachine.arenaInitializedTapes_source] + rfl + +def initializeInTime (radix : Nat) (positive : 0 < radix) : + StateTransition.EvalsToInTime (TM2.step (program (width := width))) + (cfg (some (initLabel .seed)) (inputTapes radix)) + (some (cfg (some (enumerationLabel TupleEnumerationMachine.body)) (readyTapes radix))) + (radix + 1) := by + have run := TupleInitializationMachine.arenaInitializeInTime (width := width) (Λ := Label width) () initLabel + (some (enumerationLabel TupleEnumerationMachine.body)) program (fun _ => rfl) + (inputTapes radix) () radix positive [] + (by simp [inputTapes, source]) + simpa only [cfg, TupleInitializationMachine.clean, initialized_eq] using! run + +def enumerationBudget (width radix : Nat) : Nat := + (TupleEnumerationMachine.leafBound width radix + 2 * width) * radix ^ width + +noncomputable def enumerationInTime (radix : Nat) (positive : 0 < radix) : + StateTransition.EvalsToInTime (TM2.step (program (width := width))) + (cfg (some (enumerationLabel TupleEnumerationMachine.body)) (readyTapes radix)) + (some (cfg (some (enumerationLabel .exit)) (emittedTapes radix))) + (enumerationBudget width radix) := by + have run := MachineSubroutine.execution (enumerationLabel (width := width)) cleanupEntry + TupleEnumerationMachine.program program (fun _ => rfl) + (TupleEnumerationMachine.enumerateInTime (width := width) radix positive [] (fun _ : Unit => [])) + simpa only [MachineSubroutine.configuration, MachineSubroutine.label, + TupleEnumerationMachine.configuration, cfg, readyTapes, emittedTapes, output, + List.append_nil, enumerationBudget] using! run + +def returnInTime (radix : Nat) : + StateTransition.EvalsToInTime (TM2.step (program (width := width))) + (cfg (some (enumerationLabel .exit)) (emittedTapes radix)) + (some (cfg cleanupEntry (emittedTapes radix))) 1 where + steps := 1 + evals_in_steps := rfl + steps_le_m := Nat.le_refl _ + +@[simp] theorem mem_cleanupTapes (tape : Tape width) : + tape ∈ cleanupTapes width ↔ tape ≠ .output := by + cases tape with + | current i => + simp [cleanupTapes, source, TupleInitializationMachine.currentDestinations, + TupleInitializationMachine.remainingDestinations, List.mem_ofFn] + | scratch => + simp [cleanupTapes, source] + | output => + simp [cleanupTapes, source, TupleInitializationMachine.currentDestinations, + TupleInitializationMachine.remainingDestinations, List.mem_ofFn] + | extra x => + cases x with + | inl i => + simp [cleanupTapes, source, TupleInitializationMachine.currentDestinations, + TupleInitializationMachine.remainingDestinations, List.mem_ofFn] + | inr x => + cases x + simp [cleanupTapes, source] + +@[simp] theorem cleanupTapes_length : + (cleanupTapes width).length = 2 * width + 2 := by + simp only [cleanupTapes, List.length_append, List.length_cons, List.length_nil, + TupleInitializationMachine.currentDestinations, + TupleInitializationMachine.remainingDestinations, List.length_ofFn] + omega + +theorem finalTapes_cleanup (m : Nat) : + MachineDrainMany.finalTapes (cleanupTapes width) (emittedTapes (width := width) m) = + MachineDrainMany.haltTapes .output + (output width m) := by + funext tape + rw [MachineDrainMany.finalTapes_apply] + simp only [mem_cleanupTapes] + by_cases htape : tape = .output + · subst tape + simp [MachineDrainMany.haltTapes, emittedTapes, output, TupleEnumerationMachine.tapes] + · simp [MachineDrainMany.haltTapes, htape] + +theorem cleanup_lengthSum (m : Nat) (hm : 0 < m) : + MachineDrainMany.lengthSum (cleanupTapes width) (emittedTapes (width := width) m) = + width * m + width := by + have hm' : m - 1 + 1 = m := by omega + simp [MachineDrainMany.lengthSum, cleanupTapes, source, emittedTapes, + TupleInitializationMachine.currentDestinations, TupleInitializationMachine.remainingDestinations, + TupleEnumerationMachine.tapes, + List.map_ofFn, Function.comp_def, hm', Nat.add_comm] + +theorem cleanup_budget (m : Nat) (hm : 0 < m) : + MachineDrainMany.lengthSum (cleanupTapes width) (emittedTapes (width := width) m) + + (cleanupTapes width).length = width * (m + 3) + 2 := by + rw [cleanup_lengthSum m hm, cleanupTapes_length] + ring + +theorem cleanup_steps_le (m : Nat) (hm : 0 < m) : + MachineDrainMany.steps (cleanupTapes width) (emittedTapes (width := width) m) ≤ + width * (m + 3) + 2 := by + rw [← cleanup_budget m hm] + exact MachineDrainMany.steps_le _ _ + +def cleanupInTime (radix : Nat) (positive : 0 < radix) : + StateTransition.EvalsToInTime (TM2.step (program (width := width))) + (cfg cleanupEntry (emittedTapes radix)) + (some (cfg none (MachineDrainMany.haltTapes .output (output width radix)))) + (width * (radix + 3) + 2) := by + have run := MachineDrainMany.execution (cleanupTapes width) cleanupLabel none program + (fun _ => rfl) (emittedTapes radix) () none + simpa only [cfg, cleanupEntry, MachineDrainMany.finalRegister_none, + finalTapes_cleanup, cleanup_budget radix positive] using! run + +def totalBudget (width radix : Nat) : Nat := + ((radix + 1 + enumerationBudget width radix) + 1) + (width * (radix + 3) + 2) + +noncomputable def totalInTime (radix : Nat) (positive : 0 < radix) : + StateTransition.EvalsToInTime (TM2.step (program (width := width))) + (cfg (some (initLabel .seed)) (inputTapes radix)) + (some (cfg none (MachineDrainMany.haltTapes .output (output width radix)))) + (totalBudget width radix) := by + have first := StateTransition.EvalsToInTime.trans (TM2.step (program (width := width))) _ _ _ _ _ + (initializeInTime radix positive) (enumerationInTime radix positive) + have second := StateTransition.EvalsToInTime.trans (TM2.step (program (width := width))) _ _ _ _ _ + first (returnInTime radix) + simpa only [totalBudget, Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using + StateTransition.EvalsToInTime.trans (TM2.step program) _ _ _ _ _ + second (cleanupInTime radix positive) + +private theorem initList_eq (radix : Nat) : + initList (machine width) (encodeWord radix) = + cfg (some (initLabel .seed)) (inputTapes radix) := by + unfold initList cfg + congr 1 + +private theorem haltList_eq (word : List Bool) : + haltList (machine width) word = + cfg none (MachineDrainMany.haltTapes .output word) := by + unfold haltList cfg + congr 1 + +noncomputable def outputsInTime (radix : Nat) (positive : 0 < radix) : + TM2OutputsInTime (machine width) (encodeWord radix) (some (output width radix)) + (totalBudget width radix) := by + change StateTransition.EvalsToInTime (TM2.step program) + (initList (machine width) (encodeWord radix)) + (some (haltList (machine width) (output width radix))) (totalBudget width radix) + rw [initList_eq, haltList_eq] + exact totalInTime radix positive + +noncomputable def time (width : Nat) : Polynomial Nat := + (Polynomial.X + 1) + + ((Polynomial.C (2 * width) * (Polynomial.X + 1) + 1 + Polynomial.C (2 * width)) * + Polynomial.X ^ width) + 1 + (Polynomial.C width * (Polynomial.X + 3) + 2) + +theorem time_eval (width radix : Nat) : + (time width).eval radix = totalBudget width radix := by + simp [time, totalBudget, enumerationBudget, TupleEnumerationMachine.leafBound] + +theorem totalBudget_mono (width : Nat) {first second : Nat} (h : first ≤ second) : + totalBudget width first ≤ totalBudget width second := by + have coefficient : TupleEnumerationMachine.leafBound width first + 2 * width ≤ + TupleEnumerationMachine.leafBound width second + 2 * width := by + exact Nat.add_le_add_right + (Nat.add_le_add_right + (Nat.mul_le_mul_left (2 * width) (Nat.add_le_add_right h 1)) 1) (2 * width) + have enumeration : enumerationBudget width first ≤ enumerationBudget width second := + Nat.mul_le_mul coefficient (Nat.pow_le_pow_left h width) + have cleanup : width * (first + 3) + 2 ≤ width * (second + 3) + 2 := + Nat.add_le_add_right (Nat.mul_le_mul_left width (Nat.add_le_add_right h 3)) 2 + exact Nat.add_le_add + (Nat.add_le_add_right (Nat.add_le_add (Nat.add_le_add_right h 1) enumeration) 1) cleanup + +abbrev PositiveNat := {radix : Nat // 0 < radix} + +def input (radix : PositiveNat) : List Bool := encodeWord radix.val + +def tuples (width : Nat) (radix : PositiveNat) : List Bool := output width radix.val + +noncomputable def computation (width : Nat) : + TM2ComputableInPolyTime input (id : List Bool → List Bool) (tuples width) where + tm := machine width + inputAlphabet := Equiv.refl Bool + outputAlphabet := Equiv.refl Bool + time := time width + outputsFun radix := by + change TM2OutputsInTime (machine width) ((input radix).map id) + (some ((tuples width radix).map id)) ((time width).eval (input radix).length) + have input_eq : @List.map ((machine width).Γ (machine width).k₀) + ((machine width).Γ (machine width).k₀) id (input radix) = input radix := List.map_id _ + have output_eq : @List.map ((machine width).Γ (machine width).k₁) + ((machine width).Γ (machine width).k₁) id (tuples width radix) = tuples width radix := + List.map_id _ + simp only [input_eq, output_eq] + let run := outputsInTime (width := width) radix.val radix.property + refine { steps := run.steps, evals_in_steps := run.evals_in_steps, steps_le_m := ?_ } + apply run.steps_le_m.trans + rw [time_eval] + exact totalBudget_mono width (by simp [input]) + +theorem workAlphabet_finite (width : Nat) (tape : (machine width).K) : + Finite ((machine width).Γ tape) := by + change Finite Bool + infer_instance + +end PerfectCompleteness.TupleIndexMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/TupleInitializationMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/TupleInitializationMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..14aedf652e9879841658a04e56480aad5b138750 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/TupleInitializationMachine.lean @@ -0,0 +1,411 @@ +import Mathlib.Data.List.FinRange +import OAI.Computability.PerfectCompleteness.Foundations.TupleIndexEmitterLemmas + +namespace OAI + + +namespace PerfectCompleteness.TupleInitializationMachine + + +open Turing UniqueGamesTheorem.Foundations.Complexity +open MachineComposition + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool +abbrev State (σ : Type) := σ × Option Bool + +def clean (ambient : σ) : State σ := (ambient, none) + +inductive Label + | seed + | scan + deriving DecidableEq + +protected abbrev Label.enumList : List Label := [.seed, .scan] + +protected theorem Label.enumList_getElem?_ctorIdx_eq (x : Label) : + Label.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem Label.enumList_nodup : Label.enumList.Nodup := by decide + +instance : Fintype Label where + elems := ⟨Label.enumList, Label.enumList_nodup⟩ + complete x := by cases x <;> decide + +def prefixOn (destinations : List K) (addedBits : List Bool) (base : K → List Bool) : + K → List Bool := + fun k => if k ∈ destinations then addedBits ++ base k else base k + +@[simp] theorem prefixOn_nil (destinations : List K) (base : K → List Bool) : + prefixOn destinations [] base = base := by + funext k + simp [prefixOn] + +theorem prefixOn_comp (destinations : List K) (first second : List Bool) + (base : K → List Bool) : + prefixOn destinations first (prefixOn destinations second base) = + prefixOn destinations (first ++ second) base := by + funext k + by_cases hk : k ∈ destinations <;> simp [prefixOn, hk, List.append_assoc] + +theorem prefixOn_update (destinations : List K) (src : K) + (hsrc : src ∉ destinations) (addedBits rest : List Bool) (base : K → List Bool) : + prefixOn destinations addedBits (Function.update base src rest) = + Function.update (prefixOn destinations addedBits base) src rest := by + funext k + by_cases hk : k = src + · subst k + simp [prefixOn, hsrc] + · simp [prefixOn, hk] + +def pushEach (destinations : List K) (bit : Bool) + (next : TM2.Stmt (Alphabet (K := K)) Λ (State σ)) : + TM2.Stmt (Alphabet (K := K)) Λ (State σ) := + match destinations with + | [] => next + | dst :: rest => .push dst (fun _ => bit) (pushEach rest bit next) + +theorem stepAux_pushEach (destinations : List K) (hn : destinations.Nodup) (bit : Bool) + (next : TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (state : State σ) (tapes : K → List Bool) : + TM2.stepAux (pushEach destinations bit next) state tapes = + TM2.stepAux next state (prefixOn destinations [bit] tapes) := by + induction destinations generalizing tapes with + | nil => + have emptyDest : prefixOn [] [bit] tapes = tapes := by + funext k + simp [prefixOn] + simp only [pushEach, emptyDest] + | cons dst rest ih => + obtain ⟨hdst, hrest⟩ := List.nodup_cons.mp hn + simp only [pushEach, TM2.stepAux] + rw [ih hrest] + apply congrArg (TM2.stepAux next state) + funext k + by_cases hk : k = dst + · subst k + simp [prefixOn, hdst] + · simp [prefixOn, hk] + +omit [DecidableEq K] in +theorem pushEach_pushBound (destinations : List K) (bit : Bool) + (next : TM2.Stmt (Alphabet (K := K)) Λ (State σ)) : + Runtime.statementPushBound (pushEach destinations bit next) = + destinations.length + Runtime.statementPushBound next := by + induction destinations with + | nil => simp [pushEach] + | cons dst rest ih => + simp only [pushEach, Runtime.statementPushBound, ih, List.length_cons] + omega + +def finish (exit : Option Λ) : TM2.Stmt (Alphabet (K := K)) Λ (State σ) := + .load (fun state => clean state.1) + (match exit with | none => .halt | some label => .goto (fun _ => label)) + +theorem stepAux_finish (exit : Option Λ) (ambient : σ) (register : Option Bool) + (tapes : K → List Bool) : + TM2.stepAux (finish exit) (ambient, register) tapes = ⟨exit, clean ambient, tapes⟩ := by + cases exit <;> rfl + +omit [DecidableEq K] in +@[simp] theorem finish_pushBound (exit : Option Λ) : + Runtime.statementPushBound (finish (K := K) (σ := σ) exit) = 0 := by + cases exit <;> rfl + +def instruction (src : K) (currents remaining : List K) + (labels : Label → Λ) (exit : Option Λ) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (State σ) + | .seed => pushEach (currents ++ remaining) false + (.pop src (fun state _ => clean state.1) (.goto (fun _ => labels .scan))) + | .scan => .pop src (fun state head => (state.1, head)) + (.branch (fun state => state.2.getD false) + (pushEach remaining true (finish (some (labels .scan)))) (finish exit)) + +omit [DecidableEq K] in +theorem instruction_pushBound (src : K) (currents remaining : List K) + (labels : Label → Λ) (exit : Option Λ) (label : Label) : + Runtime.statementPushBound (instruction (σ := σ) src currents remaining labels exit label) ≤ + currents.length + remaining.length := by + cases label with + | seed => + simp [instruction, pushEach_pushBound, Runtime.statementPushBound] + | scan => + change max + (Runtime.statementPushBound + (pushEach remaining true (finish (K := K) (σ := σ) (some (labels .scan))))) + (Runtime.statementPushBound (finish (K := K) (σ := σ) exit)) ≤ _ + rw [pushEach_pushBound, finish_pushBound, finish_pushBound] + omega + +theorem scanStep_false (src : K) (currents remaining : List K) + (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atScan : program (labels .scan) = instruction src currents remaining labels exit .scan) + (base : K → List Bool) (suffix : List Bool) (ambient : σ) (register : Option Bool) : + TM2.step program + ⟨some (labels .scan), (ambient, register), Function.update base src (false :: suffix)⟩ = + some ⟨exit, clean ambient, Function.update base src suffix⟩ := by + change some (TM2.stepAux (program (labels .scan)) _ _) = _ + rw [atScan] + cases exit <;> simp [instruction, TM2.stepAux, finish, clean] + +theorem scanStep_true (src : K) (currents remaining : List K) + (hn : remaining.Nodup) (hsrc : src ∉ remaining) + (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atScan : program (labels .scan) = instruction src currents remaining labels exit .scan) + (base : K → List Bool) (rest : List Bool) (ambient : σ) (register : Option Bool) : + TM2.step program + ⟨some (labels .scan), (ambient, register), Function.update base src (true :: rest)⟩ = + some ⟨some (labels .scan), clean ambient, + Function.update (prefixOn remaining [true] base) src rest⟩ := by + change some (TM2.stepAux (program (labels .scan)) _ _) = _ + rw [atScan] + simp only [instruction, TM2.stepAux.eq_3, TM2.stepAux.eq_5, Function.update_self, + List.head?_cons, List.tail_cons, Option.getD_some, Bool.cond_true, Function.update_idem] + rw [stepAux_pushEach remaining hn, stepAux_finish, + prefixOn_update remaining src hsrc] + +theorem scanTrace (src : K) (currents remaining : List K) + (hn : remaining.Nodup) (hsrc : src ∉ remaining) + (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atScan : program (labels .scan) = instruction src currents remaining labels exit .scan) + (base : K → List Bool) (count : Nat) (suffix : List Bool) + (ambient : σ) (register : Option Bool) : + (advance (TM2.step program))^[count + 1] + (some ⟨some (labels .scan), (ambient, register), + Function.update base src (encodeWord count ++ suffix)⟩) = + some ⟨exit, clean ambient, + Function.update (prefixOn remaining (List.replicate count true) base) src suffix⟩ := by + induction count generalizing base register with + | zero => + simpa [encodeWord] using + scanStep_false src currents remaining labels exit program atScan base suffix ambient register + | succ count ih => + rw [Function.iterate_succ_apply] + change (advance (TM2.step program))^[count + 1] + (TM2.step program ⟨some (labels .scan), (ambient, register), + Function.update base src (encodeWord (count + 1) ++ suffix)⟩) = _ + rw [show encodeWord (count + 1) ++ suffix = + true :: (encodeWord count ++ suffix) by + simp [encodeWord, List.replicate_succ, List.append_assoc]] + rw [scanStep_true src currents remaining hn hsrc labels exit program atScan] + change (advance (TM2.step program))^[count + 1] + (some ⟨some (labels .scan), (ambient, none), + Function.update (prefixOn remaining [true] base) src (encodeWord count ++ suffix)⟩) = _ + rw [ih, prefixOn_comp] + simp only [List.replicate_succ'] + +theorem seedStep (src : K) (currents remaining : List K) + (hn : (currents ++ remaining).Nodup) (hsrc : src ∉ currents ++ remaining) + (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atSeed : program (labels .seed) = instruction src currents remaining labels exit .seed) + (base : K → List Bool) (rest : List Bool) (ambient : σ) (register : Option Bool) + (sourceWord : base src = true :: rest) : + TM2.step program ⟨some (labels .seed), (ambient, register), base⟩ = + some ⟨some (labels .scan), clean ambient, + Function.update (prefixOn (currents ++ remaining) [false] base) src rest⟩ := by + change some (TM2.stepAux (program (labels .seed)) _ _) = _ + rw [atSeed] + simp only [instruction] + rw [stepAux_pushEach (currents ++ remaining) hn] + simp [TM2.stepAux, prefixOn, hsrc, sourceWord, clean] + +def initializedTapes (src : K) (currents remaining : List K) (base : K → List Bool) + (last : Nat) (suffix : List Bool) : K → List Bool := + Function.update + (prefixOn remaining (List.replicate last true) + (prefixOn (currents ++ remaining) [false] base)) src suffix + +private theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +theorem initializeTrace (src : K) (currents remaining : List K) + (hn : (currents ++ remaining).Nodup) (hsrc : src ∉ currents ++ remaining) + (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ label, program (labels label) = instruction src currents remaining labels exit label) + (base : K → List Bool) (ambient : σ) (m : Nat) (hm : 0 < m) (suffix : List Bool) + (sourceWord : base src = encodeWord m ++ suffix) : + (advance (TM2.step program))^[m + 1] + (some ⟨some (labels .seed), clean ambient, base⟩) = + some ⟨exit, clean ambient, initializedTapes src currents remaining base (m - 1) suffix⟩ := by + have hrem : remaining.Nodup := (List.nodup_append.mp hn).2.1 + have hsrem : src ∉ remaining := fun h => hsrc (List.mem_append_right _ h) + cases m with + | zero => omega + | succ n => + have first : (advance (TM2.step program))^[1] + (some ⟨some (labels .seed), clean ambient, base⟩) = + some ⟨some (labels .scan), clean ambient, + Function.update (prefixOn (currents ++ remaining) [false] base) src + (encodeWord n ++ suffix)⟩ := by + rw [Function.iterate_one, advance_some] + apply seedStep src currents remaining hn hsrc labels exit program (atLabels .seed) + simpa [encodeWord, List.replicate_succ, List.append_assoc] using sourceWord + have rest := scanTrace src currents remaining hrem hsrem labels exit program (atLabels .scan) + (prefixOn (currents ++ remaining) [false] base) n suffix ambient none + have joined := joinTrace first rest + rw [show 1 + (n + 1) = n + 1 + 1 by omega] at joined + simpa only [initializedTapes, Nat.add_sub_cancel] using joined + +def initializeInTime (src : K) (currents remaining : List K) + (hn : (currents ++ remaining).Nodup) (hsrc : src ∉ currents ++ remaining) + (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ label, program (labels label) = instruction src currents remaining labels exit label) + (base : K → List Bool) (ambient : σ) (m : Nat) (hm : 0 < m) (suffix : List Bool) + (sourceWord : base src = encodeWord m ++ suffix) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .seed), clean ambient, base⟩ + (some ⟨exit, clean ambient, initializedTapes src currents remaining base (m - 1) suffix⟩) + (m + 1) where + steps := m + 1 + evals_in_steps := initializeTrace src currents remaining hn hsrc labels exit program atLabels + base ambient m hm suffix sourceWord + steps_le_m := Nat.le_refl _ + +@[simp] theorem initializedTapes_source (src : K) (currents remaining : List K) + (base : K → List Bool) (last : Nat) (suffix : List Bool) : + initializedTapes src currents remaining base last suffix src = suffix := by + simp [initializedTapes] + +theorem initializedTapes_current (src : K) (currents remaining : List K) + (base : K → List Bool) (last : Nat) (suffix : List Bool) (k : K) + (hcurrent : k ∈ currents) (hremaining : k ∉ remaining) (hsrc : k ≠ src) + (hempty : base k = []) : + initializedTapes src currents remaining base last suffix k = encodeWord 0 := by + simp [initializedTapes, prefixOn, hcurrent, hremaining, hsrc, hempty, encodeWord] + +theorem initializedTapes_remaining (src : K) (currents remaining : List K) + (base : K → List Bool) (last : Nat) (suffix : List Bool) (k : K) + (hremaining : k ∈ remaining) (hsrc : k ≠ src) (hempty : base k = []) : + initializedTapes src currents remaining base last suffix k = encodeWord last := by + simp [initializedTapes, prefixOn, hremaining, hsrc, hempty, encodeWord] + +theorem initializedTapes_frame (src : K) (currents remaining : List K) + (base : K → List Bool) (last : Nat) (suffix : List Bool) (k : K) + (hcurrent : k ∉ currents) (hremaining : k ∉ remaining) (hsrc : k ≠ src) : + initializedTapes src currents remaining base last suffix k = base k := by + simp [initializedTapes, prefixOn, hcurrent, hremaining, hsrc] + +section Arena + +variable {width : Nat} {Extra : Type} + +abbrev Arena (width : Nat) (Extra : Type) := TupleIndexEmitter.Tape width (Fin width ⊕ Extra) + +def currentDestinations (width : Nat) (Extra : Type) : List (Arena width Extra) := + List.ofFn (fun i : Fin width => TupleIndexEmitter.Tape.current i) + +def remainingDestinations (width : Nat) (Extra : Type) : List (Arena width Extra) := + List.ofFn (fun i : Fin width => TupleIndexEmitter.Tape.extra (Sum.inl i)) + +theorem destinations_nodup (width : Nat) (Extra : Type) : + (currentDestinations width Extra ++ remainingDestinations width Extra).Nodup := by + unfold currentDestinations remainingDestinations + apply List.nodup_append.mpr + refine ⟨?_, ?_, ?_⟩ + · apply List.nodup_ofFn.mpr + intro i j h + simpa using h + · apply List.nodup_ofFn.mpr + intro i j h + simpa using h + · intro a ha b hb + obtain ⟨i, rfl⟩ := List.mem_ofFn.mp ha + obtain ⟨j, rfl⟩ := List.mem_ofFn.mp hb + intro h + cases h + +theorem source_not_destination (src : Extra) : + (TupleIndexEmitter.Tape.extra (Sum.inr src) : Arena width Extra) ∉ + currentDestinations width Extra ++ remainingDestinations width Extra := by + simp [currentDestinations, remainingDestinations, List.mem_ofFn] + +variable [DecidableEq Extra] + +def arenaInstruction (src : Extra) (labels : Label → Λ) (exit : Option Λ) : + Label → TM2.Stmt (fun _ : Arena width Extra => Bool) Λ (State σ) := + instruction (.extra (.inr src)) (currentDestinations width Extra) + (remainingDestinations width Extra) labels exit + +omit [DecidableEq Extra] in +theorem arenaInstruction_pushBound (src : Extra) (labels : Label → Λ) (exit : Option Λ) + (label : Label) : + Runtime.statementPushBound (arenaInstruction (width := width) (σ := σ) src labels exit label) ≤ + 2 * width := by + simpa only [arenaInstruction, currentDestinations, remainingDestinations, + List.length_ofFn, two_mul] using + instruction_pushBound (σ := σ) (.extra (.inr src) : Arena width Extra) + (currentDestinations width Extra) (remainingDestinations width Extra) labels exit label + +def arenaInitializedTapes (src : Extra) (base : Arena width Extra → List Bool) + (last : Nat) (suffix : List Bool) : Arena width Extra → List Bool := + initializedTapes (.extra (.inr src)) (currentDestinations width Extra) + (remainingDestinations width Extra) base last suffix + +@[simp] theorem arenaInitializedTapes_source (src : Extra) + (base : Arena width Extra → List Bool) (last : Nat) (suffix : List Bool) : + arenaInitializedTapes src base last suffix (.extra (.inr src)) = suffix := by + simp [arenaInitializedTapes] + +theorem arenaInitializedTapes_current (src : Extra) (base : Arena width Extra → List Bool) + (last : Nat) (suffix : List Bool) (i : Fin width) (hempty : base (.current i) = []) : + arenaInitializedTapes src base last suffix (.current i) = encodeWord 0 := by + simp [arenaInitializedTapes, initializedTapes, prefixOn, currentDestinations, + remainingDestinations, List.mem_ofFn, hempty, encodeWord] + +theorem arenaInitializedTapes_remaining (src : Extra) (base : Arena width Extra → List Bool) + (last : Nat) (suffix : List Bool) (i : Fin width) + (hempty : base (.extra (.inl i)) = []) : + arenaInitializedTapes src base last suffix (.extra (.inl i)) = encodeWord last := by + simp [arenaInitializedTapes, initializedTapes, prefixOn, currentDestinations, + remainingDestinations, List.mem_ofFn, hempty, encodeWord] + +@[simp] theorem arenaInitializedTapes_scratch (src : Extra) + (base : Arena width Extra → List Bool) (last : Nat) (suffix : List Bool) : + arenaInitializedTapes src base last suffix .scratch = base .scratch := by + simp [arenaInitializedTapes, initializedTapes, prefixOn, currentDestinations, + remainingDestinations, List.mem_ofFn] + +@[simp] theorem arenaInitializedTapes_output (src : Extra) + (base : Arena width Extra → List Bool) (last : Nat) (suffix : List Bool) : + arenaInitializedTapes src base last suffix .output = base .output := by + simp [arenaInitializedTapes, initializedTapes, prefixOn, currentDestinations, + remainingDestinations, List.mem_ofFn] + +theorem arenaInitializedTapes_other (src x : Extra) (hx : x ≠ src) + (base : Arena width Extra → List Bool) (last : Nat) (suffix : List Bool) : + arenaInitializedTapes src base last suffix (.extra (.inr x)) = base (.extra (.inr x)) := by + simp [arenaInitializedTapes, initializedTapes, prefixOn, currentDestinations, + remainingDestinations, List.mem_ofFn, hx] + +def arenaInitializeInTime (src : Extra) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (fun _ : Arena width Extra => Bool) Λ (State σ)) + (atLabels : ∀ label, program (labels label) = arenaInstruction src labels exit label) + (base : Arena width Extra → List Bool) (ambient : σ) + (m : Nat) (hm : 0 < m) (suffix : List Bool) + (sourceWord : base (.extra (.inr src)) = encodeWord m ++ suffix) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .seed), clean ambient, base⟩ + (some ⟨exit, clean ambient, arenaInitializedTapes src base (m - 1) suffix⟩) (m + 1) := + initializeInTime (K := Arena width Extra) (.extra (.inr src)) (currentDestinations width Extra) + (remainingDestinations width Extra) (destinations_nodup width Extra) + (source_not_destination src) labels exit program + (fun label => by simpa only [arenaInstruction] using atLabels label) + base ambient m hm suffix sourceWord + +omit [DecidableEq Extra] in +theorem arena_finite [Fintype Extra] : Finite (Arena width Extra) := inferInstance + +end Arena + +end PerfectCompleteness.TupleInitializationMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/UnaryBlockCopyMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/UnaryBlockCopyMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..076e8e131e80a9a48ba03a6af3771f056be3b7a0 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/UnaryBlockCopyMachine.lean @@ -0,0 +1,270 @@ +import Mathlib.Data.List.OfFn +import OAI.Computability.UniqueGames.Machines.MachineCompositionLemmas +import OAI.Computability.UniqueGames.Machines.MachineSubroutineLemmas +import OAI.Computability.UniqueGames.Reduction.MachineTransfer + +namespace OAI + + +namespace PerfectCompleteness.UnaryBlockCopyMachine + + +open Turing +open UniqueGamesTheorem.Foundations.Complexity +open MachineComposition +open UniqueGamesTheorem.Reduction.MachineTransfer + +abbrev Alphabet {K : Type} (_ : K) := Bool +abbrev State (A : Type) := A × Option Bool + +def blockWords (values : Fin 6 → Nat) : List Nat := + [values 0, values 1, values 2, values 3, values 4, values 5] + +def listValues (words : List Nat) (length_eq : words.length = 6) : Fin 6 → Nat := + fun i => words.get (Fin.cast length_eq.symm i) + +theorem blockWords_listValues (words : List Nat) (length_eq : words.length = 6) : + blockWords (listValues words length_eq) = words := by + have h := (List.ofFn_congr length_eq words.get).symm + rw [List.ofFn_get] at h + change List.ofFn (listValues words length_eq) = words at h + simp only [List.ofFn_succ, List.ofFn_zero] at h + change blockWords (listValues words length_eq) = words at h + exact h + +section Placement + +variable {K Λ A : Type} [DecidableEq K] + +def nextField (labels : Fin 6 → Λ) (exit : Option Λ) (slot : Fin 6) : Option Λ := + if h : slot.val + 1 < 6 then some (labels ⟨slot.val + 1, h⟩) else exit + +@[simp] theorem nextField_zero (labels : Fin 6 → Λ) (exit : Option Λ) : + nextField labels exit 0 = some (labels 1) := rfl +@[simp] theorem nextField_one (labels : Fin 6 → Λ) (exit : Option Λ) : + nextField labels exit 1 = some (labels 2) := rfl +@[simp] theorem nextField_two (labels : Fin 6 → Λ) (exit : Option Λ) : + nextField labels exit 2 = some (labels 3) := rfl +@[simp] theorem nextField_three (labels : Fin 6 → Λ) (exit : Option Λ) : + nextField labels exit 3 = some (labels 4) := rfl +@[simp] theorem nextField_four (labels : Fin 6 → Λ) (exit : Option Λ) : + nextField labels exit 4 = some (labels 5) := rfl +@[simp] theorem nextField_five (labels : Fin 6 → Λ) (exit : Option Λ) : + nextField labels exit 5 = exit := rfl + +def finish (destination : K) (exit : Option Λ) : TM2.Stmt (Alphabet (K := K)) Λ (State A) := + .load (fun state => (state.1, none)) (exitAt destination exit) + +def instruction (source destination : K) (again : Λ) (next rejected : Option Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (State A) := + .pop source (fun state head => (state.1, head)) + (.branch (fun state => state.2.isSome) + (.push destination (fun state => state.2.getD false) + (.branch (fun state => state.2.getD false) + (finish destination (some again)) (finish destination next))) + (finish destination rejected)) + +private theorem update_source (source destination : K) (distinct : source ≠ destination) + (base : K → List Bool) (input output replacement : List Bool) : + Function.update (tapesAt source destination base input output) source replacement = + tapesAt source destination base replacement output := by + funext k + by_cases hs : k = source + · subst k + simp [tapesAt, distinct] + · by_cases hd : k = destination + · subst k + simp [tapesAt, Ne.symm distinct] + · simp [tapesAt, hs, hd] + +private theorem update_destination (source destination : K) + (base : K → List Bool) (input output replacement : List Bool) : + Function.update (tapesAt source destination base input output) destination replacement = + tapesAt source destination base input replacement := by + simp [tapesAt] + +variable (source destination : K) (distinct : source ≠ destination) +variable (labels : Fin 6 → Λ) (exit rejected : Option Λ) +variable (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) +variable (atLabels : ∀ slot, program (labels slot) = + instruction source destination (labels slot) (nextField labels exit slot) rejected) +variable (base : K → List Bool) (ambient : A) + +include distinct atLabels + +theorem step_true (slot : Fin 6) (input output : List Bool) (register : Option Bool) : + TM2.step program + ⟨some (labels slot), (ambient, register), + tapesAt source destination base (true :: input) output⟩ = + some ⟨some (labels slot), (ambient, none), + tapesAt source destination base input (true :: output)⟩ := by + change some (TM2.stepAux (program (labels slot)) _ _) = _ + rw [atLabels slot] + simp [instruction, finish, exitAt, TM2.stepAux, distinct, + update_source, update_destination] + +theorem step_false (slot : Fin 6) (input output : List Bool) (register : Option Bool) : + TM2.step program + ⟨some (labels slot), (ambient, register), + tapesAt source destination base (false :: input) output⟩ = + some ⟨nextField labels exit slot, (ambient, none), + tapesAt source destination base input (false :: output)⟩ := by + change some (TM2.stepAux (program (labels slot)) _ _) = _ + rw [atLabels slot] + cases h : nextField labels exit slot <;> + simp [instruction, finish, exitAt, TM2.stepAux, distinct, + update_source, update_destination] + +theorem step_empty (slot : Fin 6) (output : List Bool) (register : Option Bool) : + TM2.step program + ⟨some (labels slot), (ambient, register), tapesAt source destination base [] output⟩ = + some ⟨rejected, (ambient, none), tapesAt source destination base [] output⟩ := by + change some (TM2.stepAux (program (labels slot)) _ _) = _ + rw [atLabels slot] + cases rejected <;> + simp [instruction, finish, exitAt, TM2.stepAux, distinct, update_source] + +theorem fieldTrace (slot : Fin 6) (value : Nat) (suffix output : List Bool) + (register : Option Bool) : + (advance (TM2.step program))^[value + 1] + (some ⟨some (labels slot), (ambient, register), + tapesAt source destination base (encodeWord value ++ suffix) output⟩) = + some ⟨nextField labels exit slot, (ambient, none), + tapesAt source destination base suffix ((encodeWord value).reverse ++ output)⟩ := by + induction value generalizing output register with + | zero => + simpa only [Nat.zero_add, Function.iterate_one, advance_some, encodeWord, + List.replicate_zero, List.nil_append, List.reverse_singleton, List.singleton_append] using + step_false source destination distinct labels exit rejected program atLabels base ambient + slot suffix output register + | succ value ih => + rw [Function.iterate_succ_apply] + simp only [encodeWord, List.replicate_succ, List.cons_append, advance_some] + rw [step_true source destination distinct labels exit rejected program atLabels] + change (advance (TM2.step program))^[value + 1] + (some ⟨some (labels slot), (ambient, none), + tapesAt source destination base (encodeWord value ++ suffix) (true :: output)⟩) = _ + rw [ih] + simp only [encodeWord, List.reverse_cons, List.append_assoc, List.singleton_append] + +omit [DecidableEq K] distinct atLabels in +private theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +theorem blockTrace (values : Fin 6 → Nat) (suffix output : List Bool) + (register : Option Bool) : + (advance (TM2.step program))^[(encodeWords (blockWords values)).length] + (some ⟨some (labels 0), (ambient, register), + tapesAt source destination base (encodeWords (blockWords values) ++ suffix) output⟩) = + some ⟨exit, (ambient, none), tapesAt source destination base suffix + ((encodeWords (blockWords values)).reverse ++ output)⟩ := by + have first := fieldTrace source destination distinct labels exit rejected program atLabels base ambient + 0 (values 0) (encodeWords [values 1, values 2, values 3, values 4, values 5] ++ suffix) + output register + have second := fieldTrace source destination distinct labels exit rejected program atLabels base ambient + 1 (values 1) (encodeWords [values 2, values 3, values 4, values 5] ++ suffix) + ((encodeWord (values 0)).reverse ++ output) none + have third := fieldTrace source destination distinct labels exit rejected program atLabels base ambient + 2 (values 2) (encodeWords [values 3, values 4, values 5] ++ suffix) + ((encodeWord (values 1)).reverse ++ ((encodeWord (values 0)).reverse ++ output)) none + have fourth := fieldTrace source destination distinct labels exit rejected program atLabels base ambient + 3 (values 3) (encodeWords [values 4, values 5] ++ suffix) + ((encodeWord (values 2)).reverse ++ ((encodeWord (values 1)).reverse ++ + ((encodeWord (values 0)).reverse ++ output))) none + have fifth := fieldTrace source destination distinct labels exit rejected program atLabels base ambient + 4 (values 4) (encodeWords [values 5] ++ suffix) + ((encodeWord (values 3)).reverse ++ ((encodeWord (values 2)).reverse ++ + ((encodeWord (values 1)).reverse ++ ((encodeWord (values 0)).reverse ++ output)))) none + have sixth := fieldTrace source destination distinct labels exit rejected program atLabels base ambient + 5 (values 5) suffix + ((encodeWord (values 4)).reverse ++ ((encodeWord (values 3)).reverse ++ + ((encodeWord (values 2)).reverse ++ ((encodeWord (values 1)).reverse ++ + ((encodeWord (values 0)).reverse ++ output))))) none + simp only [nextField_zero, nextField_one, nextField_two, nextField_three, + nextField_four, nextField_five, encodeWords, List.append_nil, List.append_assoc] + at first second third fourth fifth sixth + have full := joinTrace (joinTrace (joinTrace (joinTrace (joinTrace first second) third) fourth) fifth) sixth + have htime : ((((values 0 + 1 + (values 1 + 1)) + (values 2 + 1)) + + (values 3 + 1)) + (values 4 + 1)) + (values 5 + 1) = + (encodeWords (blockWords values)).length := by + simp only [encodeWords_length, blockWords, List.sum_cons, List.sum_nil, + List.length_cons, List.length_nil] + omega + rw [htime] at full + simpa only [blockWords, encodeWords, List.append_nil, List.reverse_append, + List.reverse_nil, List.nil_append, List.append_assoc] using full + +def blockInTime (values : Fin 6 → Nat) (suffix output : List Bool) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels 0), (ambient, register), + tapesAt source destination base (encodeWords (blockWords values) ++ suffix) output⟩ + (some ⟨exit, (ambient, none), tapesAt source destination base suffix + ((encodeWords (blockWords values)).reverse ++ output)⟩) + (encodeWords (blockWords values)).length where + steps := (encodeWords (blockWords values)).length + evals_in_steps := blockTrace source destination distinct labels exit rejected program atLabels + base ambient values suffix output register + steps_le_m := Nat.le_refl _ + +theorem listTrace (words : List Nat) (length_eq : words.length = 6) + (suffix output : List Bool) (register : Option Bool) : + (advance (TM2.step program))^[(encodeWords words).length] + (some ⟨some (labels 0), (ambient, register), + tapesAt source destination base (encodeWords words ++ suffix) output⟩) = + some ⟨exit, (ambient, none), tapesAt source destination base suffix + ((encodeWords words).reverse ++ output)⟩ := by + simpa only [blockWords_listValues] using + blockTrace source destination distinct labels exit rejected program atLabels + base ambient (listValues words length_eq) suffix output register + +def listInTime (words : List Nat) (length_eq : words.length = 6) + (suffix output : List Bool) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels 0), (ambient, register), + tapesAt source destination base (encodeWords words ++ suffix) output⟩ + (some ⟨exit, (ambient, none), tapesAt source destination base suffix + ((encodeWords words).reverse ++ output)⟩) + (encodeWords words).length where + steps := (encodeWords words).length + evals_in_steps := listTrace source destination distinct labels exit rejected program atLabels + base ambient words length_eq suffix output register + steps_le_m := Nat.le_refl _ + +end Placement + +abbrev ConcreteLabel := Fin 6 ⊕ Bool + +def concreteProgram : ConcreteLabel → TM2.Stmt (Alphabet (K := Bool)) ConcreteLabel (State Unit) + | .inl slot => instruction false true (.inl slot) + (nextField Sum.inl (some (.inr true)) slot) (some (.inr false)) + | .inr _ => .halt + +abbrev machine : FinTM2 where + K := Bool + k₀ := false + k₁ := true + Γ := Alphabet + Λ := ConcreteLabel + main := .inl 0 + σ := State Unit + initialState := ((), none) + m := concreteProgram + +def machineInTime (values : Fin 6 → Nat) (suffix output : List Bool) : + StateTransition.EvalsToInTime machine.step + ⟨some (.inl 0), ((), none), tapesAt false true (fun _ : Bool => []) + (encodeWords (blockWords values) ++ suffix) output⟩ + (some ⟨some (.inr true), ((), none), tapesAt false true (fun _ : Bool => []) suffix + ((encodeWords (blockWords values)).reverse ++ output)⟩) + (encodeWords (blockWords values)).length := + blockInTime false true (by decide) Sum.inl (some (.inr true)) (some (.inr false)) + concreteProgram (fun _ => rfl) (fun _ => []) () values suffix output none + +theorem machine_finiteAlphabet (k : machine.K) : Finite (machine.Γ k) := by + change Finite Bool + infer_instance + +end PerfectCompleteness.UnaryBlockCopyMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/UnaryBlockSkipMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/UnaryBlockSkipMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..cc87c762f3f226537f628d486c56c61df41a0efe --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/UnaryBlockSkipMachine.lean @@ -0,0 +1,194 @@ +import OAI.Computability.UniqueGames.Machines.MachineCompositionLemmas +import OAI.Computability.UniqueGames.Machines.MachineSubroutineLemmas +import OAI.Computability.UniqueGames.Reduction.MachineTransfer + +namespace OAI + + +namespace PerfectCompleteness.UnaryBlockSkipMachine + + +open Turing +open UniqueGamesTheorem.Foundations.Complexity +open MachineComposition +open UniqueGamesTheorem.Reduction.MachineTransfer + +abbrev Alphabet {K : Type} (_ : K) := Bool +abbrev State (A : Type) := A × Option Bool + +section Placement + +variable {K Λ A : Type} [DecidableEq K] + +def nextField {count : Nat} (labels : Fin (count + 1) → Λ) (exit : Option Λ) + (slot : Fin (count + 1)) : Option Λ := + if h : slot.val + 1 < count + 1 then some (labels ⟨slot.val + 1, h⟩) else exit + +def finish (source : K) (exit : Option Λ) : TM2.Stmt (Alphabet (K := K)) Λ (State A) := + .load (fun state => (state.1, none)) (exitAt source exit) + +def instruction (source : K) (again : Λ) (next rejected : Option Λ) : + TM2.Stmt (Alphabet (K := K)) Λ (State A) := + .pop source (fun state head => (state.1, head)) + (.branch (fun state => state.2.isSome) + (.branch (fun state => state.2.getD false) + (finish source (some again)) (finish source next)) + (finish source rejected)) + +variable (source : K) {count : Nat} (labels : Fin (count + 1) → Λ) +variable (exit rejected : Option Λ) +variable (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) +variable (atLabels : ∀ slot, program (labels slot) = + instruction source (labels slot) (nextField labels exit slot) rejected) +variable (base : K → List Bool) (ambient : A) + +include atLabels + +theorem step_true (slot : Fin (count + 1)) (input : List Bool) (register : Option Bool) : + TM2.step program + ⟨some (labels slot), (ambient, register), Function.update base source (true :: input)⟩ = + some ⟨some (labels slot), (ambient, none), Function.update base source input⟩ := by + change some (TM2.stepAux (program (labels slot)) _ _) = _ + rw [atLabels slot] + simp [instruction, finish, exitAt, TM2.stepAux] + +theorem step_false (slot : Fin (count + 1)) (input : List Bool) (register : Option Bool) : + TM2.step program + ⟨some (labels slot), (ambient, register), Function.update base source (false :: input)⟩ = + some ⟨nextField labels exit slot, (ambient, none), Function.update base source input⟩ := by + change some (TM2.stepAux (program (labels slot)) _ _) = _ + rw [atLabels slot] + cases nextField labels exit slot <;> + simp [instruction, finish, exitAt, TM2.stepAux] + +theorem step_empty (slot : Fin (count + 1)) (register : Option Bool) : + TM2.step program + ⟨some (labels slot), (ambient, register), Function.update base source []⟩ = + some ⟨rejected, (ambient, none), Function.update base source []⟩ := by + change some (TM2.stepAux (program (labels slot)) _ _) = _ + rw [atLabels slot] + cases rejected <;> simp [instruction, finish, exitAt, TM2.stepAux] + +theorem fieldTrace (slot : Fin (count + 1)) (value : Nat) (suffix : List Bool) + (register : Option Bool) : + (advance (TM2.step program))^[value + 1] + (some ⟨some (labels slot), (ambient, register), + Function.update base source (encodeWord value ++ suffix)⟩) = + some ⟨nextField labels exit slot, (ambient, none), Function.update base source suffix⟩ := by + induction value generalizing register with + | zero => + simpa only [Nat.zero_add, Function.iterate_one, advance_some, encodeWord, + List.replicate_zero, List.nil_append, List.singleton_append] using + step_false source labels exit rejected program atLabels base ambient slot suffix register + | succ value ih => + rw [Function.iterate_succ_apply] + simp only [encodeWord, List.replicate_succ, List.cons_append, advance_some] + rw [step_true source labels exit rejected program atLabels] + exact ih none + +omit [DecidableEq K] atLabels in +private theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +private theorem fromTrace (suffix : List Bool) (words : List Nat) : + ∀ (slot : Fin (count + 1)), words ≠ [] → slot.val + words.length = count + 1 → + ∀ register : Option Bool, + (advance (TM2.step program))^[(encodeWords words).length] + (some ⟨some (labels slot), (ambient, register), + Function.update base source (encodeWords words ++ suffix)⟩) = + some ⟨exit, (ambient, none), Function.update base source suffix⟩ := by + induction words with + | nil => + intro slot nonempty _ _ + exact (nonempty rfl).elim + | cons value words ih => + intro slot _ remaining register + cases words with + | nil => + have last : ¬slot.val + 1 < count + 1 := by + simp only [List.length_cons, List.length_nil, Nat.zero_add] at remaining + omega + have h := fieldTrace source labels exit rejected program atLabels base ambient + slot value suffix register + simpa only [nextField, dite_eq_right last, encodeWords, List.append_nil, + encodeWord_length] using h + | cons next words => + have more : slot.val + 1 < count + 1 := by + simp only [List.length_cons] at remaining + omega + let following : Fin (count + 1) := ⟨slot.val + 1, more⟩ + have tailCount : following.val + (next :: words).length = count + 1 := by + simp only [following, List.length_cons] at remaining ⊢ + omega + have first := fieldTrace source labels exit rejected program atLabels base ambient + slot value (encodeWords (next :: words) ++ suffix) register + have second := ih following (by simp) tailCount none + rw [nextField, dite_eq_left more] at first + have full := joinTrace first second + simpa only [encodeWords, List.length_append, encodeWord_length, List.append_assoc] + using full + +theorem listTrace (words : List Nat) (length_eq : words.length = count + 1) + (suffix : List Bool) (register : Option Bool) : + (advance (TM2.step program))^[(encodeWords words).length] + (some ⟨some (labels 0), (ambient, register), + Function.update base source (encodeWords words ++ suffix)⟩) = + some ⟨exit, (ambient, none), Function.update base source suffix⟩ := by + have nonempty : words ≠ [] := by + intro h + simp [h] at length_eq + exact fromTrace source labels exit rejected program atLabels base ambient suffix words 0 + nonempty (by simpa only [Fin.val_zero, Nat.zero_add] using length_eq) register + +def listInTime (words : List Nat) (length_eq : words.length = count + 1) + (suffix : List Bool) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels 0), (ambient, register), + Function.update base source (encodeWords words ++ suffix)⟩ + (some ⟨exit, (ambient, none), Function.update base source suffix⟩) + (encodeWords words).length where + steps := (encodeWords words).length + evals_in_steps := listTrace source labels exit rejected program atLabels base ambient + words length_eq suffix register + steps_le_m := Nat.le_refl _ + +end Placement + +abbrev ConcreteLabel (count : Nat) := Fin (count + 1) ⊕ Bool + +def concreteProgram (count : Nat) : + ConcreteLabel count → TM2.Stmt (Alphabet (K := Bool)) (ConcreteLabel count) (State Unit) + | .inl slot => instruction false (.inl slot) + (nextField Sum.inl (some (.inr true)) slot) (some (.inr false)) + | .inr _ => .halt + +abbrev machine (count : Nat) : FinTM2 where + K := Bool + k₀ := false + k₁ := true + Γ := Alphabet + Λ := ConcreteLabel count + main := .inl 0 + σ := State Unit + initialState := ((), none) + m := concreteProgram count + +def machineInTime (count : Nat) (words : List Nat) (length_eq : words.length = count + 1) + (suffix : List Bool) : + StateTransition.EvalsToInTime (machine count).step + ⟨some (.inl 0), ((), none), + Function.update (fun _ : Bool => []) false (encodeWords words ++ suffix)⟩ + (some ⟨some (.inr true), ((), none), Function.update (fun _ : Bool => []) false suffix⟩) + (encodeWords words).length := + listInTime false Sum.inl (some (.inr true)) (some (.inr false)) + (concreteProgram count) (fun _ => rfl) (fun _ => []) () words length_eq suffix none + +theorem machine_finiteAlphabet (count : Nat) (k : (machine count).K) : + Finite ((machine count).Γ k) := by + change Finite Bool + infer_instance + +end PerfectCompleteness.UnaryBlockSkipMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/UnaryRepresentationMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/UnaryRepresentationMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..572578945986367c511d697b35eba3176fe3d1e4 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/UnaryRepresentationMachine.lean @@ -0,0 +1,188 @@ +import OAI.Computability.UniqueGames.Machines.MachineInitialHeaders + +namespace OAI + + +namespace PerfectCompleteness.UnaryRepresentationMachine + + +open Turing +open UniqueGamesTheorem.Foundations.Complexity +open MachineComposition +open UniqueGamesTheorem.Reduction.MachineTransfer (loopAt exitAt) + +abbrev Alphabet {K : Type} (_ : K) := Bool +abbrev State (A : Type) := A × Option Bool + +inductive RawLabel + | scan | restore + deriving DecidableEq + +protected abbrev RawLabel.enumList : List RawLabel := [.scan, .restore] + +protected theorem RawLabel.enumList_getElem?_ctorIdx_eq (x : RawLabel) : + RawLabel.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem RawLabel.enumList_nodup : RawLabel.enumList.Nodup := by decide + +instance : Fintype RawLabel where + elems := ⟨RawLabel.enumList, RawLabel.enumList_nodup⟩ + complete x := by cases x <;> decide + +inductive EncodedLabel + | seed | copy | restore + deriving DecidableEq + +protected abbrev EncodedLabel.enumList : List EncodedLabel := [.seed, .copy, .restore] + +protected theorem EncodedLabel.enumList_getElem?_ctorIdx_eq (x : EncodedLabel) : + EncodedLabel.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem EncodedLabel.enumList_nodup : EncodedLabel.enumList.Nodup := by decide + +instance : Fintype EncodedLabel where + elems := ⟨EncodedLabel.enumList, EncodedLabel.enumList_nodup⟩ + complete x := by cases x <;> decide + +def encodedToRawMain : RawLabel := .scan +def rawToEncodedMain : EncodedLabel := .seed + +variable {K Λ A : Type} [DecidableEq K] + +def encodedToRawInstruction (tape : Fin 3 → K) (labels : RawLabel → Λ) + (done : Option Λ) : RawLabel → TM2.Stmt (Alphabet (K := K)) Λ (State A) + | .scan => MachineInitialHeaders.prefixScan (tape 0) (tape 1) (tape 2) 1 + (labels .scan) (labels .restore) + | .restore => loopAt (tape 1) (tape 0) id false (labels .restore) done + +def rawToEncodedInstruction (tape : Fin 3 → K) (labels : EncodedLabel → Λ) + (done : Option Λ) : EncodedLabel → TM2.Stmt (Alphabet (K := K)) Λ (State A) + | .seed => .push (tape 2) (fun _ => false) (.goto fun _ => labels .copy) + | .copy => loopAt (tape 0) (tape 1) id false (labels .copy) (some (labels .restore)) + | .restore => MachineCopy.forkLoop (tape 1) (tape 0) (tape 2) false + (labels .restore) done + +omit [DecidableEq K] in +theorem encodedToRaw_pushBound (tape : Fin 3 → K) (labels : RawLabel → Λ) + (done : Option Λ) (label : RawLabel) : + Runtime.statementPushBound (encodedToRawInstruction (A := A) tape labels done label) ≤ 2 := by + cases label with + | scan => + simpa only [encodedToRawInstruction, MachineInitialHeaders.prefixScan_pushBound] + using (Nat.le_refl 2) + | restore => cases done <;> + simp [encodedToRawInstruction, loopAt, exitAt, Runtime.statementPushBound] + +omit [DecidableEq K] in +theorem rawToEncoded_pushBound (tape : Fin 3 → K) (labels : EncodedLabel → Λ) + (done : Option Λ) (label : EncodedLabel) : + Runtime.statementPushBound (rawToEncodedInstruction (A := A) tape labels done label) ≤ 2 := by + cases label <;> cases done <;> + simp [rawToEncodedInstruction, loopAt, MachineCopy.forkLoop, exitAt, + Runtime.statementPushBound] + +theorem encodedToRawTrace (tape : Fin 3 → K) (distinct : Function.Injective tape) + (labels : RawLabel → Λ) (done : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ label, program (labels label) = encodedToRawInstruction tape labels done label) + (base : K → List Bool) (n : Nat) (sourceWord : base (tape 0) = encodeWord n) + (scratchEmpty : base (tape 1) = []) (ambient : A) (register : Option Bool) : + (advance (TM2.step program))^[2 * n + 2] + (some ⟨some (labels encodedToRawMain), (ambient, register), base⟩) = + some ⟨done, (ambient, none), + Function.update base (tape 2) (List.replicate n true ++ base (tape 2))⟩ := by + have h01 : tape 0 ≠ tape 1 := fun h => (by decide : (0 : Fin 3) ≠ 1) (distinct h) + have h02 : tape 0 ≠ tape 2 := fun h => (by decide : (0 : Fin 3) ≠ 2) (distinct h) + have h12 : tape 1 ≠ tape 2 := fun h => (by decide : (1 : Fin 3) ≠ 2) (distinct h) + have trace := MachineInitialHeaders.prefixTrace (tape 0) (tape 1) (tape 2) + h01 h02 h12 1 (labels .scan) (labels .restore) done program + (atLabels .scan) (atLabels .restore) base n [] + (by simpa only [List.append_nil] using sourceWord) scratchEmpty ambient register + simpa only [encodedToRawMain, Nat.one_mul] using trace + +def encodedToRawInTime (tape : Fin 3 → K) (distinct : Function.Injective tape) + (labels : RawLabel → Λ) (done : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ label, program (labels label) = encodedToRawInstruction tape labels done label) + (base : K → List Bool) (n : Nat) (sourceWord : base (tape 0) = encodeWord n) + (scratchEmpty : base (tape 1) = []) (ambient : A) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels encodedToRawMain), (ambient, register), base⟩ + (some ⟨done, (ambient, none), + Function.update base (tape 2) (List.replicate n true ++ base (tape 2))⟩) (2 * n + 2) where + steps := 2 * n + 2 + evals_in_steps := encodedToRawTrace tape distinct labels done program atLabels base n + sourceWord scratchEmpty ambient register + steps_le_m := Nat.le_refl _ + +theorem seedStep (tape : Fin 3 → K) (labels : EncodedLabel → Λ) (done : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atSeed : program (labels .seed) = rawToEncodedInstruction tape labels done .seed) + (base : K → List Bool) (state : State A) : + TM2.step program ⟨some (labels .seed), state, base⟩ = + some ⟨some (labels .copy), state, Function.update base (tape 2) (false :: base (tape 2))⟩ := by + change some (TM2.stepAux (program (labels .seed)) state base) = _ + rw [atSeed] + rfl + +private theorem joinTrace {X : Type*} {f : X → X} {a b c : X} {n m : Nat} + (first : f^[n] a = b) (second : f^[m] b = c) : f^[n + m] a = c := by + rw [Nat.add_comm, Function.iterate_add_apply, first, second] + +theorem rawToEncodedTrace (tape : Fin 3 → K) (distinct : Function.Injective tape) + (labels : EncodedLabel → Λ) (done : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ label, program (labels label) = rawToEncodedInstruction tape labels done label) + (base : K → List Bool) (n : Nat) (sourceWord : base (tape 0) = List.replicate n true) + (scratchEmpty : base (tape 1) = []) (ambient : A) (register : Option Bool) : + (advance (TM2.step program))^[1 + 2 * (n + 1)] + (some ⟨some (labels rawToEncodedMain), (ambient, register), base⟩) = + some ⟨done, (ambient, none), + Function.update base (tape 2) (encodeWord n ++ base (tape 2))⟩ := by + have h02 : tape 0 ≠ tape 2 := fun h => (by decide : (0 : Fin 3) ≠ 2) (distinct h) + have h01 : tape 0 ≠ tape 1 := fun h => (by decide : (0 : Fin 3) ≠ 1) (distinct h) + have h21 : tape 2 ≠ tape 1 := fun h => (by decide : (2 : Fin 3) ≠ 1) (distinct h) + let seeded := Function.update base (tape 2) (false :: base (tape 2)) + have seededSource : seeded (tape 0) = List.replicate n true := by + simp [seeded, h02, sourceWord] + have seededScratch : seeded (tape 1) = [] := by + simp [seeded, Ne.symm h21, scratchEmpty] + have first : (advance (TM2.step program))^[1] + (some ⟨some (labels .seed), (ambient, register), base⟩) = + some ⟨some (labels .copy), (ambient, register), seeded⟩ := + seedStep tape labels done program (atLabels .seed) base (ambient, register) + have second := MachineCopy.copyTrace (tape 0) (tape 2) (tape 1) h02 h01 h21 false + (labels .copy) (labels .restore) done program (atLabels .copy) (atLabels .restore) + seeded seededScratch ambient register + rw [seededSource, List.length_replicate] at second + have full := joinTrace first second + simpa only [rawToEncodedMain, seeded, Function.update_self, Function.update_idem, + encodeWord, List.append_assoc, List.singleton_append] using full + +def rawToEncodedInTime (tape : Fin 3 → K) (distinct : Function.Injective tape) + (labels : EncodedLabel → Λ) (done : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ label, program (labels label) = rawToEncodedInstruction tape labels done label) + (base : K → List Bool) (n : Nat) (sourceWord : base (tape 0) = List.replicate n true) + (scratchEmpty : base (tape 1) = []) (ambient : A) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels rawToEncodedMain), (ambient, register), base⟩ + (some ⟨done, (ambient, none), + Function.update base (tape 2) (encodeWord n ++ base (tape 2))⟩) (1 + 2 * (n + 1)) where + steps := 1 + 2 * (n + 1) + evals_in_steps := rawToEncodedTrace tape distinct labels done program atLabels base n + sourceWord scratchEmpty ambient register + steps_le_m := Nat.le_refl _ + +theorem finiteState [Finite A] : Finite (State A) := inferInstance + +omit [DecidableEq K] in +theorem finiteAlphabet (key : K) : Finite (Alphabet key) := by + change Finite Bool + infer_instance + +end PerfectCompleteness.UnaryRepresentationMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/ValidityComposition.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/ValidityComposition.lean new file mode 100644 index 0000000000000000000000000000000000000000..6a5a80b3813de80929b489b4c7ae0e362120930b --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/ValidityComposition.lean @@ -0,0 +1,135 @@ +import OAI.Computability.PerfectCompleteness.Machines.ClashMachineFull +import OAI.Computability.PerfectCompleteness.Machines.ValidityMachine + +namespace OAI + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.ValidityMachine.Full + +open Turing MachineComposition PostfixModel InitializationTemplate +open ClashMachine (State clean emitted) + + +variable {K Λ σ : Type} [DecidableEq K] + +def nonemptyMap : Fin 7 ↪ Fin 10 := ⟨![0, 1, 3, 5, 9, 7, 8], by decide⟩ + +inductive Label where + | nonempty (l : Nonempty.Label) + | clash (l : ClashMachine.Full.Label) + | finish + deriving DecidableEq, Fintype + +def statement (slots : Fin 10 ↪ K) (labels : Label → Λ) (exit : Option Λ) : + Label → TM2.Stmt (ValidityMachine.Alphabet (K := K)) Λ (State σ) + | .nonempty l => Nonempty.statement (nonemptyMap.trans slots) + (fun l => labels (.nonempty l)) (some (labels (.clash .start))) l + | .clash l => ClashMachine.Full.statement slots (fun l => labels (.clash l)) + (some (labels .finish)) l + | .finish => ClashMachine.literal (slots 7) (slots 8) [.not, .and] + (Reduction.MachineTransfer.exitAt (slots 7) exit) + +def steps (q : Nat) : Nat := Nonempty.steps q + ClashMachine.Full.steps q + 1 + +noncomputable def timePolynomial : Polynomial Nat := + Polynomial.C 20 * (Polynomial.X + Polynomial.C 2) ^ 2 + + ClashMachine.Full.timePolynomial + Polynomial.C 1 + +theorem timePolynomial_eval (q : Nat) : + timePolynomial.eval q = 20 * (q + 2) ^ 2 + ClashMachine.Full.timePolynomial.eval q + 1 := by + simp [timePolynomial] + +theorem steps_le_time (q : Nat) : steps q ≤ timePolynomial.eval q := by + rw [timePolynomial_eval] + exact Nat.add_le_add_right + (Nat.add_le_add (Nonempty.steps_le q) (ClashMachine.Full.steps_le_time q)) 1 + +private theorem chain {A : Type*} {f : A → A} {x y z : A} {n m : Nat} + (first : f^[n] x = y) (second : f^[m] y = z) : f^[n + m] x = z := by + rw [Nat.add_comm n m, Function.iterate_add_apply, first, second] + +theorem trace (slots : Fin 10 ↪ K) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (ValidityMachine.Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ l, program (labels l) = statement slots labels exit l) + (base : K → List Bool) (q : Nat) (ready : ClashMachine.Full.Ready slots base q) (ambient : σ) : + (advance (TM2.step program))^[steps q] + (some ⟨some (labels (.nonempty .initialize)), clean ambient, base⟩) = + some ⟨exit, clean ambient, emitted (slots 7) (slots 8) base (validityTokens q)⟩ := by + have nr : Nonempty.Ready (nonemptyMap.trans slots) base q := { + boundWord := ready.source + remainingEmpty := ready.empty 1 (by decide) (by decide) (by decide) + currentEmpty := ready.empty 3 (by decide) (by decide) (by decide) + scratchEmpty := ready.empty 5 (by decide) (by decide) (by decide) + closureEmpty := ready.empty 9 (by decide) (by decide) (by decide) } + have hn := Nonempty.trace (nonemptyMap.trans slots) (fun l => labels (.nonempty l)) + (some (labels (.clash .start))) program (fun _ => atLabels _) base q nr ambient + let afterNonempty := emitted (slots 7) (slots 8) base (nonemptyTokens q) + change (advance (TM2.step program))^[Nonempty.steps q] + (some ⟨some (labels (.nonempty .initialize)), clean ambient, base⟩) = + some ⟨some (labels (.clash .start)), clean ambient, afterNonempty⟩ at hn + have hc := ClashMachine.Full.trace slots (fun l => labels (.clash l)) + (some (labels .finish)) program (fun _ => atLabels _) + afterNonempty q (ready.emitted (nonemptyTokens q)) ambient + let afterClash := emitted (slots 7) (slots 8) afterNonempty (clashTokens q) + have hf : (advance (TM2.step program))^[1] + (some ⟨some (labels .finish), clean ambient, afterClash⟩) = + some ⟨exit, clean ambient, emitted (slots 7) (slots 8) afterClash [.not, .and]⟩ := by + change some (TM2.stepAux (program (labels .finish)) _ _) = _ + rw [atLabels, statement, ClashMachine.stepAux_literal (slots 7) (slots 8) + (slots.injective.ne (by decide : (7 : Fin 10) ≠ 8))] + cases exit <;> rfl + have h := chain (chain hn hc) hf + simpa only [steps, afterClash, afterNonempty, + ClashMachine.emitted_append (slots 7) (slots 8) + (slots.injective.ne (by decide : (7 : Fin 10) ≠ 8)), validityTokens] using h + +def inTime (slots : Fin 10 ↪ K) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (ValidityMachine.Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ l, program (labels l) = statement slots labels exit l) + (base : K → List Bool) (q : Nat) (ready : ClashMachine.Full.Ready slots base q) (ambient : σ) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels (.nonempty .initialize)), clean ambient, base⟩ + (some ⟨exit, clean ambient, emitted (slots 7) (slots 8) base (validityTokens q)⟩) + (timePolynomial.eval q) where + steps := steps q + evals_in_steps := by + change (advance (TM2.step program))^[steps q] _ = _ + exact trace slots labels exit program atLabels base q ready ambient + steps_le_m := steps_le_time q + +section FiniteMachine + +variable [Fintype K] [Fintype σ] + +def machine (slots : Fin 10 ↪ K) (ambient : σ) : FinTM2 where + K := K + k₀ := slots 0 + k₁ := slots 7 + Γ := ValidityMachine.Alphabet + Λ := Label + main := .nonempty .initialize + σ := State σ + initialState := clean ambient + Γk₀Fin := inferInstance + m := statement slots id none + +theorem machineTrace (slots : Fin 10 ↪ K) (base : K → List Bool) (q : Nat) + (ready : ClashMachine.Full.Ready slots base q) (ambient : σ) : + (advance (machine slots ambient).step)^[steps q] + (some ⟨some (.nonempty .initialize), clean ambient, base⟩) = + some ⟨none, clean ambient, emitted (slots 7) (slots 8) base (validityTokens q)⟩ := by + exact trace slots id none (machine slots ambient).m (fun _ => rfl) base q ready ambient + +def machineInTime (slots : Fin 10 ↪ K) (base : K → List Bool) (q : Nat) + (ready : ClashMachine.Full.Ready slots base q) (ambient : σ) : + StateTransition.EvalsToInTime (machine slots ambient).step + ⟨some (.nonempty .initialize), clean ambient, base⟩ + (some ⟨none, clean ambient, emitted (slots 7) (slots 8) base (validityTokens q)⟩) + (timePolynomial.eval q) := + inTime slots id none (machine slots ambient).m (fun _ => rfl) base q ready ambient + +end FiniteMachine + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.ValidityMachine.Full + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/ValidityMachine.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/ValidityMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..5628535aef1303c2594b598ae885e987412673ca --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/ValidityMachine.lean @@ -0,0 +1,424 @@ +import Mathlib.Tactic.Linarith +import OAI.Computability.PerfectCompleteness.Machines.ClashMachine +import OAI.Computability.PerfectCompleteness.Machines.OrClosure +import OAI.Computability.UniqueGames.Machines.MachineDrain +import OAI.Computability.UniqueGames.Machines.MachineUnaryAffineAt + +namespace OAI + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.ValidityMachine + +open Turing MachineComposition PostfixModel InitializationTemplate +open ClashMachine (State clean emitted emitted_append emitted_other emitted_nil) + + +variable {K Λ σ : Type} [DecidableEq K] + +abbrev Alphabet (_ : K) := Bool + +private theorem chain {A : Type*} {f : A → A} {x y z : A} {n m : Nat} + (first : f^[n] x = y) (second : f^[m] y = z) : f^[n + m] x = z := by + rw [Nat.add_comm n m, Function.iterate_add_apply, first, second] + +namespace SelectorLoop + +def inputMap : Fin 4 ↪ Fin 5 := ⟨![1, 2, 3, 4], by decide⟩ + +inductive Label where + | guard | input (l : ClashMachine.Input.Label) | increment + deriving DecidableEq, Fintype + +def statement (slots : Fin 5 ↪ K) (labels : Label → Λ) (done : Λ) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (State σ) + | .guard => MachineUnaryCounter.guard (slots 0) (labels (.input .tag)) done + | .input l => ClashMachine.Input.statement (inputMap.trans slots) + (fun l => labels (.input l)) (some (labels .increment)) l + | .increment => .push (slots 1) (fun _ => true) (.goto fun _ => labels .guard) + +def frame (slots : Fin 5 ↪ K) (base : K → List Bool) (remaining current : Nat) : K → List Bool := + Function.update (Function.update base (slots 0) (encodeWord remaining)) (slots 1) (encodeWord current) + +@[simp] theorem frame_current (slots : Fin 5 ↪ K) (base : K → List Bool) (r j : Nat) : + frame slots base r j (slots 1) = encodeWord j := by simp [frame] + +@[simp] theorem frame_remaining (slots : Fin 5 ↪ K) (base : K → List Bool) (r j : Nat) : + frame slots base r j (slots 0) = encodeWord r := by simp [frame, slots.injective.eq_iff] + +theorem counter_frame (slots : Fin 5 ↪ K) (base : K → List Bool) (r r' j : Nat) : + MachineUnaryCounter.counterTapes (slots 0) (frame slots base r j) r' [] = + frame slots base r' j := by + funext k + by_cases h₀ : k = slots 0 + · subst k; simp [MachineUnaryCounter.counterTapes, frame, slots.injective.eq_iff] + · by_cases h₁ : k = slots 1 <;> simp [MachineUnaryCounter.counterTapes, frame, h₀, h₁] + +theorem emitted_frame (slots : Fin 5 ↪ K) (base : K → List Bool) (r j : Nat) (tokens : List Token) : + emitted (slots 3) (slots 4) (frame slots base r j) tokens = + frame slots (emitted (slots 3) (slots 4) base tokens) r j := by + funext k + by_cases h₀ : k = slots 0 + · subst k; simp [emitted, frame, slots.injective.eq_iff] + · by_cases h₁ : k = slots 1 + · subst k; simp [emitted, frame, slots.injective.eq_iff] + · by_cases h₃ : k = slots 3 + · subst k; simp [emitted, frame, slots.injective.eq_iff] + · by_cases h₄ : k = slots 4 + · subst k; simp [emitted, frame, slots.injective.eq_iff] + · simp [emitted, frame, h₀, h₁, h₃, h₄] + +theorem increment_frame (slots : Fin 5 ↪ K) (base : K → List Bool) (r j : Nat) : + Function.update (frame slots base r j) (slots 1) (true :: encodeWord j) = + frame slots base r (j + 1) := by + simp [frame, encodeWord, List.replicate_succ] + +def tokens (count start : Nat) : List Token := + forTokens count (fun j => [.input (start + j)]) + +theorem tokens_zero (start : Nat) : tokens 0 start = [] := rfl + +theorem tokens_succ (count start : Nat) : + tokens (count + 1) start = [.input start] ++ tokens count (start + 1) := by + rw [tokens, forTokens_succ_first] + simp only [Nat.add_zero] + apply congrArg (List.append [Token.input start]) + apply forTokens_congr + intro j _ + rw [show start + (j + 1) = start + 1 + j by omega] + +def steps : Nat → Nat → Nat + | 0, _ => 1 + | count + 1, start => 1 + ClashMachine.Input.steps start + 1 + steps count (start + 1) + +theorem trace (slots : Fin 5 ↪ K) (labels : Label → Λ) (done : Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ l, program (labels l) = statement slots labels done l) + (base : K → List Bool) (count start : Nat) + (scratchEmpty : base (slots 2) = []) (ambient : σ) : + (advance (TM2.step program))^[steps count start] + (some ⟨some (labels .guard), clean ambient, frame slots base count start⟩) = + some ⟨some done, clean ambient, + frame slots (emitted (slots 3) (slots 4) base (tokens count start)) 0 (start + count)⟩ := by + induction count generalizing base start with + | zero => + have h := MachineUnaryCounter.guardTrace_zero (slots 0) (labels .guard) + (labels (.input .tag)) done program (atLabels .guard) + (frame slots base 0 start) [] (ambient, false) none + simpa only [counter_frame, steps, tokens_zero, emitted_nil, Nat.add_zero, clean] using h + | succ count ih => + have hg := MachineUnaryCounter.guardTrace_succ (slots 0) (labels .guard) + (labels (.input .tag)) done program (atLabels .guard) + (frame slots base count start) count [] (ambient, false) none + simp only [counter_frame] at hg + have hs : frame slots base count start (slots 2) = [] := by + simpa [frame, slots.injective.eq_iff] using scratchEmpty + have hp := ClashMachine.Input.trace (inputMap.trans slots) (fun l => labels (.input l)) + (some (labels .increment)) program (fun _ => atLabels _) + (frame slots base count start) start (frame_current slots base count start) hs ambient + change (advance (TM2.step program))^[ClashMachine.Input.steps start] + (some ⟨some (labels (.input .tag)), clean ambient, frame slots base count start⟩) = + some ⟨some (labels .increment), clean ambient, + emitted (slots 3) (slots 4) (frame slots base count start) [.input start]⟩ at hp + rw [emitted_frame] at hp + let nextBase := emitted (slots 3) (slots 4) base [.input start] + have hn : (advance (TM2.step program))^[1] + (some ⟨some (labels .increment), clean ambient, frame slots nextBase count start⟩) = + some ⟨some (labels .guard), clean ambient, frame slots nextBase count (start + 1)⟩ := by + change some (TM2.stepAux (program (labels .increment)) _ _) = _ + rw [atLabels, statement] + simp only [TM2.stepAux, frame_current, increment_frame] + have hns : nextBase (slots 2) = [] := by + simpa [nextBase, emitted, slots.injective.eq_iff] using scratchEmpty + have hr := ih nextBase (start + 1) hns + have h := chain (chain (chain hg hp) hn) hr + rw [show start + 1 + count = start + (count + 1) by omega] at h + simp only [nextBase, emitted_append (slots 3) (slots 4) + (slots.injective.ne (by decide : (3 : Fin 5) ≠ 4)), ← tokens_succ] at h + exact h + +theorem steps_le (count start : Nat) : + steps count start ≤ count * (3 * (start + count + 1) + 5) + 1 := by + induction count generalizing start with + | zero => simp [steps] + | succ count ih => + have hr := ih (start + 1) + have he : start + 1 + count + 1 = start + (count + 1) + 1 := by omega + rw [he] at hr + rw [steps, Nat.succ_mul] + unfold ClashMachine.Input.steps + omega + +end SelectorLoop + +namespace Nonempty + +def loopMap : Fin 5 ↪ Fin 7 := ⟨![1, 2, 3, 5, 6], by decide⟩ + +def closurePorts (slots : Fin 7 ↪ K) : OrClosure.Ports K where + remaining := slots 4 + reversed := slots 5 + count := slots 6 + remaining_ne_reversed := slots.injective.ne (by decide) + remaining_ne_count := slots.injective.ne (by decide) + reversed_ne_count := slots.injective.ne (by decide) + +inductive Label where + | initialize + | remaining (l : MachineUnaryAffineAt.Label) + | closure (l : MachineUnaryAffineAt.Label) + | selector (l : SelectorLoop.Label) + | orSeed | orLoop | cleanup | drain + deriving DecidableEq, Fintype + +def copyStatement (source scratch destination : K) + (labels : MachineUnaryAffineAt.Label → Λ) (exit : Option Λ) : + MachineUnaryAffineAt.Label → TM2.Stmt (Alphabet (K := K)) Λ (State σ) + | .seed => MachineUnaryAffineAt.seed destination 1 (labels .scan) + | .scan => MachineUnaryAffineAt.scan source scratch destination 1 (labels .scan) (labels .restore) + | .restore => Reduction.MachineTransfer.loopAt scratch source id false (labels .restore) exit + +def statement (slots : Fin 7 ↪ K) (labels : Label → Λ) (exit : Option Λ) : + Label → TM2.Stmt (Alphabet (K := K)) Λ (State σ) + | .initialize => .push (slots 2) (fun _ => false) (.goto fun _ => labels (.remaining .seed)) + | .remaining l => copyStatement (slots 0) (slots 3) (slots 1) + (fun l => labels (.remaining l)) (some (labels (.closure .seed))) l + | .closure l => copyStatement (slots 0) (slots 3) (slots 4) + (fun l => labels (.closure l)) (some (labels (.selector .guard))) l + | .selector l => SelectorLoop.statement (loopMap.trans slots) + (fun l => labels (.selector l)) (labels .orSeed) l + | .orSeed => OrClosure.seed (closurePorts slots) (labels .orLoop) + | .orLoop => OrClosure.loop (closurePorts slots) (labels .orLoop) (some (labels .cleanup)) + | .cleanup => .pop (slots 1) (fun s _ => s) + (.pop (slots 4) (fun s _ => s) (.goto fun _ => labels .drain)) + | .drain => MachineDrain.drain (slots 2) (labels .drain) exit + +def steps (q : Nat) : Nat := + 1 + (2 * (q + 1) + 1) + (2 * (q + 1) + 1) + + SelectorLoop.steps (q + 1) 0 + (q + 3) + 1 + (q + 3) + +structure Ready (slots : Fin 7 ↪ K) (base : K → List Bool) (q : Nat) : Prop where + boundWord : base (slots 0) = encodeWord q + remainingEmpty : base (slots 1) = [] + currentEmpty : base (slots 2) = [] + scratchEmpty : base (slots 3) = [] + closureEmpty : base (slots 4) = [] + +private theorem emitted_update (output count work : K) (ho : work ≠ output) (hc : work ≠ count) + (base : K → List Bool) (replacement : List Bool) (tokens : List Token) : + emitted output count (Function.update base work replacement) tokens = + Function.update (emitted output count base tokens) work replacement := by + funext k + by_cases hw : k = work + · subst k; simp [emitted, ho, hc] + · by_cases houtput : k = output + · subst k + by_cases hoc : output = count + · subst count; simp [emitted, Ne.symm ho] + · simp [emitted, Ne.symm ho, Ne.symm hc, hoc] + · by_cases hcount : k = count + · subst k; simp [emitted, Ne.symm hc] + · simp [emitted, hw, houtput, hcount] + +private theorem frame_updates (slots : Fin 7 ↪ K) (base : K → List Bool) (r i : Nat) : + SelectorLoop.frame (loopMap.trans slots) base r i = + Function.update (Function.update base (slots 1) (encodeWord r)) (slots 2) (encodeWord i) := rfl + +private theorem tokens_nonempty (q : Nat) : + SelectorLoop.tokens (q + 1) 0 ++ closeOr (q + 1) = nonemptyTokens q := by + simp [SelectorLoop.tokens, nonemptyTokens] + +private theorem closed_frame (p : OrClosure.Ports K) (base : K → List Bool) (n : Nat) : + OrClosure.frame p base (encodeWord 0) + ((tokenBits (closeOr n)).reverse ++ base p.reversed) + (List.replicate (n + 1) true ++ base p.count) = + emitted p.reversed p.count (Function.update base p.remaining (encodeWord 0)) (closeOr n) := by + simp only [OrClosure.frame, emitted, closeOr, List.length_append, List.length_singleton, + List.length_replicate] + rw [Nat.add_comm 1 n] + simp only [Function.update_of_ne (Ne.symm p.remaining_ne_reversed), + Function.update_of_ne (Ne.symm p.remaining_ne_count)] + +theorem trace (slots : Fin 7 ↪ K) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ l, program (labels l) = statement slots labels exit l) + (base : K → List Bool) (q : Nat) (ready : Ready slots base q) (ambient : σ) : + (advance (TM2.step program))^[steps q] + (some ⟨some (labels .initialize), clean ambient, base⟩) = + some ⟨exit, clean ambient, emitted (slots 5) (slots 6) base (nonemptyTokens q)⟩ := by + let started := Function.update base (slots 2) (encodeWord 0) + let remaining := Function.update started (slots 1) (encodeWord (q + 1)) + let prepared := Function.update remaining (slots 4) (encodeWord (q + 1)) + have hi : (advance (TM2.step program))^[1] + (some ⟨some (labels .initialize), clean ambient, base⟩) = + some ⟨some (labels (.remaining .seed)), clean ambient, started⟩ := by + change some (TM2.stepAux (program (labels .initialize)) _ _) = _ + rw [atLabels, statement] + simp [TM2.stepAux, started, ready.currentEmpty, encodeWord] + have hsq : started (slots 0) = encodeWord q := by + simpa [started, slots.injective.eq_iff] using ready.boundWord + have hss : started (slots 3) = [] := by + simpa [started, slots.injective.eq_iff] using ready.scratchEmpty + have hr := MachineUnaryAffineAt.seededAffineTrace (slots 0) (slots 3) (slots 1) + (slots.injective.ne (by decide)) (slots.injective.ne (by decide)) + (slots.injective.ne (by decide)) 1 1 + (labels (.remaining .seed)) (labels (.remaining .scan)) (labels (.remaining .restore)) + (some (labels (.closure .seed))) program + (atLabels (.remaining .seed)) (atLabels (.remaining .scan)) (atLabels (.remaining .restore)) + started q [] (by simpa using hsq) hss (ambient, false) none + have hrs : started (slots 1) = [] := by + simpa [started, slots.injective.eq_iff] using ready.remainingEmpty + simp only [Nat.one_mul, hrs, List.append_nil] at hr + change (advance (TM2.step program))^[2 * (q + 1) + 1] + (some ⟨some (labels (.remaining .seed)), clean ambient, started⟩) = + some ⟨some (labels (.closure .seed)), clean ambient, remaining⟩ at hr + have hrq : remaining (slots 0) = encodeWord q := by + simpa [remaining, slots.injective.eq_iff] using hsq + have hsc : remaining (slots 3) = [] := by + simpa [remaining, slots.injective.eq_iff] using hss + have hc := MachineUnaryAffineAt.seededAffineTrace (slots 0) (slots 3) (slots 4) + (slots.injective.ne (by decide)) (slots.injective.ne (by decide)) + (slots.injective.ne (by decide)) 1 1 + (labels (.closure .seed)) (labels (.closure .scan)) (labels (.closure .restore)) + (some (labels (.selector .guard))) program + (atLabels (.closure .seed)) (atLabels (.closure .scan)) (atLabels (.closure .restore)) + remaining q [] (by simpa using hrq) hsc (ambient, false) none + have hrc : remaining (slots 4) = [] := by + simpa [remaining, started, slots.injective.eq_iff] using ready.closureEmpty + simp only [Nat.one_mul, hrc, List.append_nil] at hc + change (advance (TM2.step program))^[2 * (q + 1) + 1] + (some ⟨some (labels (.closure .seed)), clean ambient, remaining⟩) = + some ⟨some (labels (.selector .guard)), clean ambient, prepared⟩ at hc + let loopBase := Function.update base (slots 4) (encodeWord (q + 1)) + have hprepared : prepared = SelectorLoop.frame (loopMap.trans slots) loopBase (q + 1) 0 := by + funext k + by_cases h₁ : k = slots 1 + · subst k; simp [prepared, remaining, started, frame_updates, loopBase, slots.injective.eq_iff] + · by_cases h₂ : k = slots 2 + · subst k; simp [prepared, remaining, started, frame_updates, loopBase, slots.injective.eq_iff] + · by_cases h₄ : k = slots 4 + · subst k; simp [prepared, remaining, started, frame_updates, loopBase, slots.injective.eq_iff] + · simp [prepared, remaining, started, frame_updates, loopBase, h₁, h₂, h₄] + have hls : loopBase ((loopMap.trans slots) 2) = [] := by + simpa [loopBase, loopMap, slots.injective.eq_iff] using ready.scratchEmpty + have hl := SelectorLoop.trace (loopMap.trans slots) (fun l => labels (.selector l)) + (labels .orSeed) program (fun _ => atLabels _) loopBase (q + 1) 0 hls ambient + let afterLoop := SelectorLoop.frame (loopMap.trans slots) + (emitted (slots 5) (slots 6) loopBase (SelectorLoop.tokens (q + 1) 0)) 0 (q + 1) + rw [Nat.zero_add] at hl + change (advance (TM2.step program))^[SelectorLoop.steps (q + 1) 0] + (some ⟨some (labels (.selector .guard)), clean ambient, + SelectorLoop.frame (loopMap.trans slots) loopBase (q + 1) 0⟩) = + some ⟨some (labels .orSeed), clean ambient, afterLoop⟩ at hl + rw [← hprepared] at hl + have hac : afterLoop (slots 4) = encodeWord (q + 1) := by + simp [afterLoop, frame_updates, loopBase, emitted, slots.injective.eq_iff] + have hstart : OrClosure.frame (closurePorts slots) afterLoop (encodeWord (q + 1) ++ []) + (afterLoop (slots 5)) (afterLoop (slots 6)) = afterLoop := by + rw [List.append_nil, ← hac] + change OrClosure.frame (closurePorts slots) afterLoop + (afterLoop (closurePorts slots).remaining) (afterLoop (closurePorts slots).reversed) + (afterLoop (closurePorts slots).count) = afterLoop + exact OrClosure.frame_self (closurePorts slots) afterLoop + have ho := OrClosure.closureTrace (closurePorts slots) (labels .orSeed) (labels .orLoop) + (some (labels .cleanup)) program (atLabels .orSeed) (atLabels .orLoop) + afterLoop (q + 1) [] (afterLoop (slots 5)) (afterLoop (slots 6)) (ambient, false) none + rw [hstart, List.append_nil] at ho + have hclosed := closed_frame (closurePorts slots) afterLoop (q + 1) + change OrClosure.frame (closurePorts slots) afterLoop (encodeWord 0) + ((tokenBits (closeOr (q + 1))).reverse ++ afterLoop (slots 5)) + (List.replicate (q + 1 + 1) true ++ afterLoop (slots 6)) = + emitted (slots 5) (slots 6) (Function.update afterLoop (slots 4) (encodeWord 0)) + (closeOr (q + 1)) at hclosed + rw [hclosed] at ho + let closed := emitted (slots 5) (slots 6) + (Function.update afterLoop (slots 4) (encodeWord 0)) (closeOr (q + 1)) + change (advance (TM2.step program))^[q + 3] + (some ⟨some (labels .orSeed), clean ambient, afterLoop⟩) = + some ⟨some (labels .cleanup), clean ambient, closed⟩ at ho + have hcr : closed (slots 1) = encodeWord 0 := by + simp [closed, afterLoop, frame_updates, emitted, slots.injective.eq_iff] + have hcc : closed (slots 4) = encodeWord 0 := by + simp [closed, emitted, slots.injective.eq_iff] + let cleared := Function.update (Function.update closed (slots 1) []) (slots 4) [] + have hcleanup : (advance (TM2.step program))^[1] + (some ⟨some (labels .cleanup), clean ambient, closed⟩) = + some ⟨some (labels .drain), clean ambient, cleared⟩ := by + change some (TM2.stepAux (program (labels .cleanup)) _ _) = _ + rw [atLabels, statement] + simp [TM2.stepAux, hcr, hcc, encodeWord, cleared, slots.injective.eq_iff] + have hcur : cleared (slots 2) = encodeWord (q + 1) := by + simp [cleared, closed, afterLoop, frame_updates, emitted, slots.injective.eq_iff] + have hd := MachineDrain.drainTrace (slots 2) (labels .drain) exit program (atLabels .drain) + cleared (encodeWord (q + 1)) (ambient, false) none + rw [← hcur, Function.update_eq_self] at hd + rw [hcur, encodeWord_length] at hd + have hfinish : Function.update cleared (slots 2) [] = + emitted (slots 5) (slots 6) base (nonemptyTokens q) := by + have hmove (k : Fin 7) (hk₅ : k ≠ 5) (hk₆ : k ≠ 6) + (b : K → List Bool) (word : List Bool) (ts : List Token) := + emitted_update (slots 5) (slots 6) (slots k) + (slots.injective.ne hk₅) (slots.injective.ne hk₆) b word ts + simp only [cleared, closed, afterLoop, frame_updates, loopBase, + hmove 1 (by decide) (by decide), hmove 2 (by decide) (by decide), + hmove 4 (by decide) (by decide), + emitted_append (slots 5) (slots 6) + (slots.injective.ne (by decide : (5 : Fin 7) ≠ 6)), tokens_nonempty] + funext k + by_cases h₁ : k = slots 1 + · subst k; simp [emitted, slots.injective.eq_iff, ready.remainingEmpty] + · by_cases h₂ : k = slots 2 + · subst k; simp [emitted, slots.injective.eq_iff, ready.currentEmpty] + · by_cases h₄ : k = slots 4 + · subst k; simp [emitted, slots.injective.eq_iff, ready.closureEmpty] + · simp [h₁, h₂, h₄] + rw [hfinish] at hd + exact chain (chain (chain (chain (chain (chain hi hr) hc) hl) ho) hcleanup) hd + +theorem steps_le (q : Nat) : steps q ≤ 20 * (q + 2) ^ 2 := by + have h := SelectorLoop.steps_le (q + 1) 0 + simp only [Nat.zero_add] at h + unfold steps + nlinarith + +def inTime (slots : Fin 7 ↪ K) (labels : Label → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State σ)) + (atLabels : ∀ l, program (labels l) = statement slots labels exit l) + (base : K → List Bool) (q : Nat) (ready : Ready slots base q) (ambient : σ) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .initialize), clean ambient, base⟩ + (some ⟨exit, clean ambient, emitted (slots 5) (slots 6) base (nonemptyTokens q)⟩) + (20 * (q + 2) ^ 2) where + steps := steps q + evals_in_steps := by + change (advance (TM2.step program))^[steps q] _ = _ + exact trace slots labels exit program atLabels base q ready ambient + steps_le_m := steps_le q + + +variable [Fintype K] [Fintype σ] + +def machine (slots : Fin 7 ↪ K) (ambient : σ) : FinTM2 where + K := K + k₀ := slots 0 + k₁ := slots 5 + Γ := Alphabet + Λ := Label + main := .initialize + σ := State σ + initialState := clean ambient + Γk₀Fin := inferInstance + m := statement slots id none + +theorem machineTrace (slots : Fin 7 ↪ K) (base : K → List Bool) (q : Nat) + (ready : Ready slots base q) (ambient : σ) : + (advance (machine slots ambient).step)^[steps q] + (some ⟨some .initialize, clean ambient, base⟩) = + some ⟨none, clean ambient, emitted (slots 5) (slots 6) base (nonemptyTokens q)⟩ := by + exact trace slots id none (machine slots ambient).m (fun _ => rfl) base q ready ambient + + +end Nonempty + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.ValidityMachine + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/VerifierCircuit.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/VerifierCircuit.lean new file mode 100644 index 0000000000000000000000000000000000000000..a124e3276dbd5db19fd118c36d84b6c3916dc117 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/VerifierCircuit.lean @@ -0,0 +1,441 @@ +import OAI.Computability.PerfectCompleteness.Machines.CircuitBatchLemmas +import OAI.Computability.PerfectCompleteness.Machines.MachineCircuit +import OAI.Computability.PerfectCompleteness.Machines.WitnessCircuit +import OAI.Computability.PerfectCompleteness.Machines.WitnessEncodingLemmas + +namespace OAI + +section + +noncomputable section +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.VerifierCircuit + +open Turing StatementCircuit CircuitBatch +open scoped BigOperators + +local instance alphabetFinite (V : NPVerifier) : ∀ k, Fintype (V.computation.tm.Γ k) := + V.finiteAlphabet +local instance labelFinite (V : NPVerifier) : Fintype V.computation.tm.Λ := + V.computation.tm.ΛFin +local instance stateFinite (V : NPVerifier) : Fintype V.computation.tm.σ := + V.computation.tm.σFin +local instance labelDecidable (V : NPVerifier) : DecidableEq V.computation.tm.Λ := + Classical.decEq _ +local instance stateDecidable (V : NPVerifier) : DecidableEq V.computation.tm.σ := + Classical.decEq _ +local instance alphabetDecidable (V : NPVerifier) : ∀ k, DecidableEq (V.computation.tm.Γ k) := + fun _ => Classical.decEq _ + +def capacity (V : NPVerifier) (n : Nat) : Nat := + 2 * n + V.witnessBound.eval n + 1 + V.horizon n * Runtime.programPushBound V.computation.tm + +theorem capacity_pos (V : NPVerifier) (n : Nat) : 1 ≤ capacity V n := by + unfold capacity + omega + +abbrev FreeBits (V : NPVerifier) (input : List Bool) := + WitnessEncoding.Bits (V.witnessBound.eval input.length) + +def machineInput (V : NPVerifier) (input : List Bool) (bits : FreeBits V input) := + (pairBits (input, WitnessEncoding.decode bits)).map V.computation.inputAlphabet.invFun + +def actualRun (V : NPVerifier) (input : List Bool) (bits : FreeBits V input) (t : Nat) : + V.computation.tm.Cfg := BoundedExecution.run V.computation.tm (machineInput V input bits) t + +def accepting (V : NPVerifier) : V.computation.tm.Cfg := + haltList V.computation.tm ([true].map V.computation.outputAlphabet.invFun) + +theorem stackCapacity_le (V : NPVerifier) (input : List Bool) (bits : FreeBits V input) : + BoundedExecution.stackCapacity V.computation.tm (machineInput V input bits) + (V.horizon input.length) ≤ capacity V input.length := by + have h := WitnessEncoding.pairBits_decode_length_le input bits + simp only [BoundedExecution.stackCapacity, machineInput, List.length_map, capacity] + omega + +theorem actualRun_stack_le (V : NPVerifier) (input : List Bool) (bits : FreeBits V input) + (t : Nat) (ht : t ≤ V.horizon input.length) (k : V.computation.tm.K) : + ((actualRun V input bits t).stk k).length ≤ capacity V input.length := + (BoundedExecution.run_stack_le V.computation.tm (machineInput V input bits) + (V.horizon input.length) t ht k).trans (stackCapacity_le V input bits) + +theorem actualRun_stepSafe (V : NPVerifier) (input : List Bool) (bits : FreeBits V input) + (t : Nat) (ht : t < V.horizon input.length) : + MachineCircuit.StepSafe (capacity V input.length) V.computation.tm.m + (actualRun V input bits t) := by + intro label _ + apply BoundedExecution.statementSafe_of_budget + intro k + exact (BoundedExecution.statement_budget V.computation.tm (machineInput V input bits) + (V.horizon input.length) t ht label k).trans (stackCapacity_le V input bits) + +theorem accepting_stack_le (V : NPVerifier) (input : List Bool) (k : V.computation.tm.K) : + ((accepting V).stk k).length ≤ capacity V input.length := by + by_cases hk : k = V.computation.tm.k₁ + · subst k + simpa [accepting, haltList] using capacity_pos V input.length + · simp [accepting, haltList, hk] + +theorem actualRun_accepting_iff (V : NPVerifier) (input : List Bool) (bits : FreeBits V input) : + actualRun V input bits (V.horizon input.length) = accepting V ↔ + V.verify (input, WitnessEncoding.decode bits) = true := by + have hr := BoundedExecution.run_eq_halt_of_outputs V.computation.tm + (machineInput V input bits) + ([V.verify (input, WitnessEncoding.decode bits)].map V.computation.outputAlphabet.invFun) + (V.horizon input.length) + (V.runWithinHorizon input (WitnessEncoding.decode bits) (WitnessEncoding.decode_length_le bits)) + change actualRun V input bits (V.horizon input.length) = _ at hr + rw [hr] + constructor + · intro h + have hs := congrArg (fun c : V.computation.tm.Cfg => c.stk V.computation.tm.k₁) h + have he : V.computation.outputAlphabet.invFun (V.verify (input, WitnessEncoding.decode bits)) = + V.computation.outputAlphabet.invFun true := by + simpa [accepting, haltList] using hs + exact V.computation.outputAlphabet.symm.injective he + · intro h + simp [h, accepting] + +abbrev Bit (V : NPVerifier) (input : List Bool) := + ConfigBit V.computation.tm.Γ V.computation.tm.Λ V.computation.tm.σ (capacity V input.length) + +def indexing (V : NPVerifier) : + ConfigIndex.Indexing V.computation.tm.Γ V.computation.tm.Λ V.computation.tm.σ := + ConfigIndex.ofMachine V.computation.tm + +abbrev width (V : NPVerifier) (input : List Bool) : Nat := + (indexing V).width (capacity V input.length) + +def bitEquiv (V : NPVerifier) (input : List Bool) : Bit V input ≃ Fin (width V input) := + (indexing V).configIndexEquiv (capacity V input.length) + +def bitWire (V : NPVerifier) (input : List Bool) (b : Bit V input) : Fin (width V input + 1) := + (bitEquiv V input b).castSucc + +def stateEncoding (V : NPVerifier) (input : List Bool) (cfg : V.computation.tm.Cfg) + (valid : Bool) : Fin (width V input + 1) → Bool := + Fin.lastCases valid (fun j => configEncoding (capacity V input.length) cfg + ((bitEquiv V input).symm j)) + +@[simp] theorem stateEncoding_last (V : NPVerifier) (input : List Bool) + (cfg : V.computation.tm.Cfg) (valid : Bool) : + stateEncoding V input cfg valid (Fin.last (width V input)) = valid := by + simp [stateEncoding] + +@[simp] theorem stateEncoding_bitWire (V : NPVerifier) (input : List Bool) + (cfg : V.computation.tm.Cfg) (valid : Bool) (b : Bit V input) : + stateEncoding V input cfg valid (bitWire V input b) = + configEncoding (capacity V input.length) cfg b := by + simp [stateEncoding, bitWire] + +def initialExpressions (V : NPVerifier) (input : List Bool) : + Fin (width V input + 1) → Expr (Fin (2 * V.witnessBound.eval input.length + 1)) := + Fin.lastCases (WitnessCircuit.validityExpr (V.witnessBound.eval input.length)) + (fun j => WitnessCircuit.initExpr V input (capacity V input.length) + ((bitEquiv V input).symm j)) + +def stepExpressions (V : NPVerifier) (input : List Bool) : + Fin (width V input + 1) → Expr (Fin (width V input + 1)) := + Fin.lastCases (.input (Fin.last (width V input))) + (fun j => (MachineCircuit.stickyExpr (capacity V input.length) V.computation.tm.m + ((bitEquiv V input).symm j)).rename (bitWire V input)) + +theorem initialExpressions_eval (V : NPVerifier) (input : List Bool) (bits : FreeBits V input) + (hv : WitnessEncoding.Valid bits) : + (fun j => (initialExpressions V input j).eval bits) = + stateEncoding V input (WitnessEncoding.initial V input bits) + ((WitnessCircuit.validityExpr _).eval bits) := by + funext j + refine Fin.lastCases ?_ (fun i => ?_) j + · simp [initialExpressions, stateEncoding] + · simpa [initialExpressions, stateEncoding] using + WitnessCircuit.eval_initExpr V input (capacity V input.length) bits hv + ((bitEquiv V input).symm i) + +theorem stepExpressions_eval (V : NPVerifier) (input : List Bool) (cfg : V.computation.tm.Cfg) + (safe : MachineCircuit.StepSafe (capacity V input.length) V.computation.tm.m cfg) + (valid : Bool) : + Frame.network (stepExpressions V input) (stateEncoding V input cfg valid) = + stateEncoding V input (BoundedExecution.stickyNext V.computation.tm cfg) valid := by + funext j + refine Fin.lastCases ?_ (fun i => ?_) j + · simp [Frame.network, stepExpressions, Expr.eval, stateEncoding] + · simp only [Frame.network, stepExpressions, Fin.lastCases_castSucc, Expr.eval_rename] + have he : (fun b => stateEncoding V input cfg valid (bitWire V input b)) = + configEncoding (capacity V input.length) cfg := by funext b; simp + rw [he, MachineCircuit.stickyExpr_eval _ _ cfg safe] + simp only [stateEncoding, Fin.lastCases_castSucc] + rfl + +def initialFrame (V : NPVerifier) (input : List Bool) : + Frame (2 * V.witnessBound.eval input.length + 1) (width V input + 1) := + (Frame.initial id).step (initialExpressions V input) + +def timeFrame (V : NPVerifier) (input : List Bool) (t : Nat) : + Frame (2 * V.witnessBound.eval input.length + 1) (width V input + 1) := + (initialFrame V input).repeat (stepExpressions V input) t + +theorem initialFrame_eval (V : NPVerifier) (input : List Bool) (bits : FreeBits V input) + (hv : WitnessEncoding.Valid bits) : + (initialFrame V input).eval bits = stateEncoding V input + (WitnessEncoding.initial V input bits) ((WitnessCircuit.validityExpr _).eval bits) := by + rw [initialFrame, Frame.step_eval_fun] + have hi : (Frame.initial id).eval bits = bits := by funext i; simp + rw [hi] + exact initialExpressions_eval V input bits hv + +theorem timeFrame_validity (V : NPVerifier) (input : List Bool) (bits : FreeBits V input) + (t : Nat) : + (timeFrame V input t).eval bits (Fin.last (width V input)) = + (WitnessCircuit.validityExpr (V.witnessBound.eval input.length)).eval bits := by + induction t with + | zero => + simp only [timeFrame, Frame.repeat, initialFrame, Frame.step_eval, + initialExpressions, Fin.lastCases_last] + apply Expr.eval_congr + intro i + exact Frame.initial_eval id bits i + | succ t ih => + simpa only [timeFrame, Frame.repeat, Frame.step_eval, stepExpressions, + Fin.lastCases_last, Expr.eval] using ih + +theorem timeFrame_eval (V : NPVerifier) (input : List Bool) (bits : FreeBits V input) + (hv : WitnessEncoding.Valid bits) (t : Nat) (ht : t ≤ V.horizon input.length) : + (timeFrame V input t).eval bits = stateEncoding V input (actualRun V input bits t) + ((WitnessCircuit.validityExpr _).eval bits) := by + induction t with + | zero => exact initialFrame_eval V input bits hv + | succ t ih => + have hprev := ih (by omega) + change ((timeFrame V input t).step (stepExpressions V input)).eval bits = _ + rw [Frame.step_eval_fun, hprev] + have hs := stepExpressions_eval V input (actualRun V input bits t) + (actualRun_stepSafe V input bits t (by omega)) + ((WitnessCircuit.validityExpr _).eval bits) + change (fun i => (stepExpressions V input i).eval + (stateEncoding V input (actualRun V input bits t) + ((WitnessCircuit.validityExpr _).eval bits))) = _ at hs + simpa only [actualRun, BoundedExecution.run_succ] using hs + +def mismatchExpr (V : NPVerifier) (input : List Bool) (j : Fin (width V input)) : + Expr (Fin (width V input + 1)) := + if configEncoding (capacity V input.length) (accepting V) ((bitEquiv V input).symm j) + then .not (.input j.castSucc) else .input j.castSucc + +def acceptanceExpr (V : NPVerifier) (input : List Bool) : Expr (Fin (width V input + 1)) := + .and (.input (Fin.last (width V input))) + (.not (Expr.disjoin (List.ofFn (mismatchExpr V input)))) + +theorem mismatchExpr_eval (V : NPVerifier) (input : List Bool) + (state : Fin (width V input + 1) → Bool) (j : Fin (width V input)) : + (mismatchExpr V input j).eval state = true ↔ + state j.castSucc ≠ configEncoding (capacity V input.length) (accepting V) + ((bitEquiv V input).symm j) := by + cases ht : configEncoding (capacity V input.length) (accepting V) + ((bitEquiv V input).symm j) <;> cases hs : state j.castSucc <;> + simp [mismatchExpr, Expr.eval, ht, hs] + +theorem acceptanceExpr_eval (V : NPVerifier) (input : List Bool) + (state : Fin (width V input + 1) → Bool) : + (acceptanceExpr V input).eval state = true ↔ + state (Fin.last (width V input)) = true ∧ + ∀ j : Fin (width V input), state j.castSucc = + configEncoding (capacity V input.length) (accepting V) ((bitEquiv V input).symm j) := by + have hd : (Expr.disjoin (List.ofFn (mismatchExpr V input))).eval state = true ↔ + ∃ j : Fin (width V input), state j.castSucc ≠ + configEncoding (capacity V input.length) (accepting V) ((bitEquiv V input).symm j) := by + rw [Expr.eval_disjoin_true] + constructor + · rintro ⟨e, he, hv⟩ + obtain ⟨j, rfl⟩ := List.mem_ofFn.mp he + exact ⟨j, (mismatchExpr_eval V input state j).mp hv⟩ + · rintro ⟨j, hj⟩ + exact ⟨_, List.mem_ofFn.mpr ⟨j, rfl⟩, (mismatchExpr_eval V input state j).mpr hj⟩ + have hz : (Expr.disjoin (List.ofFn (mismatchExpr V input))).eval state = false ↔ + ∀ j : Fin (width V input), state j.castSucc = + configEncoding (capacity V input.length) (accepting V) ((bitEquiv V input).symm j) := by + constructor + · intro h j + by_contra hj + have ht := hd.mpr ⟨j, hj⟩ + rw [h] at ht + contradiction + · intro h + cases ht : (Expr.disjoin (List.ofFn (mismatchExpr V input))).eval state with + | false => rfl + | true => + obtain ⟨j, hj⟩ := hd.mp ht + exact False.elim (hj (h j)) + simp only [acceptanceExpr, Expr.eval, Bool.and_eq_true, Bool.not_eq_true_eq_eq_false] + exact and_congr_right (fun _ => hz) + +theorem acceptanceExpr_stateEncoding (V : NPVerifier) (input : List Bool) + (cfg : V.computation.tm.Cfg) (valid : Bool) + (hcfg : ∀ k, (cfg.stk k).length ≤ capacity V input.length) : + (acceptanceExpr V input).eval (stateEncoding V input cfg valid) = true ↔ + valid = true ∧ cfg = accepting V := by + rw [acceptanceExpr_eval] + constructor + · rintro ⟨hv, hbits⟩ + refine ⟨by simpa using hv, ?_⟩ + apply MachineCircuit.configEncoding_injective (capacity V input.length) + cfg (accepting V) hcfg (accepting_stack_le V input) + funext b + have h := hbits (bitEquiv V input b) + simpa [stateEncoding] using h + · rintro ⟨hv, rfl⟩ + simp [stateEncoding, hv] + +def circuitOfVerifier (V : NPVerifier) (input : List Bool) : Circuit := + ((timeFrame V input (V.horizon input.length)).step + (fun _ : Fin 1 => acceptanceExpr V input)).toCircuit 0 + +@[simp] theorem circuitOfVerifier_inputs (V : NPVerifier) (input : List Bool) : + (circuitOfVerifier V input).inputs = 2 * V.witnessBound.eval input.length + 1 := rfl + +theorem circuitOfVerifier_eval (V : NPVerifier) (input : List Bool) (bits : FreeBits V input) : + (circuitOfVerifier V input).eval bits = + (acceptanceExpr V input).eval ((timeFrame V input (V.horizon input.length)).eval bits) := by + change (((timeFrame V input (V.horizon input.length)).step + (fun _ : Fin 1 => acceptanceExpr V input)).toCircuit 0).eval bits = _ + rw [Frame.toCircuit_eval, Frame.step_eval] + +theorem circuitOfVerifier_accepts_iff (V : NPVerifier) (input : List Bool) + (bits : FreeBits V input) : + (circuitOfVerifier V input).eval bits = true ↔ + WitnessEncoding.Valid bits ∧ V.verify (input, WitnessEncoding.decode bits) = true := by + rw [circuitOfVerifier_eval] + constructor + · intro h + have hvalid := ((acceptanceExpr_eval V input _).mp h).1 + rw [timeFrame_validity] at hvalid + have hv : WitnessEncoding.Valid bits := (WitnessCircuit.eval_validityExpr bits).mp hvalid + rw [timeFrame_eval V input bits hv _ le_rfl] at h + have he := (acceptanceExpr_stateEncoding V input + (actualRun V input bits (V.horizon input.length)) _ + (actualRun_stack_le V input bits _ le_rfl)).mp h + exact ⟨hv, (actualRun_accepting_iff V input bits).mp he.2⟩ + · rintro ⟨hv, hverify⟩ + rw [timeFrame_eval V input bits hv _ le_rfl] + apply (acceptanceExpr_stateEncoding V input + (actualRun V input bits (V.horizon input.length)) _ + (actualRun_stack_le V input bits _ le_rfl)).mpr + exact ⟨(WitnessCircuit.eval_validityExpr bits).mpr hv, + (actualRun_accepting_iff V input bits).mpr hverify⟩ + +theorem circuitOfVerifier_correct (V : NPVerifier) (input : List Bool) : + (circuitOfVerifier V input).toFormula.Satisfiable ↔ V.Accepts input := by + rw [Circuit.toFormula_satisfiable_iff_eval, WitnessEncoding.accepts_iff_valid_assignment] + change (∃ bits : FreeBits V input, (circuitOfVerifier V input).eval bits = true) ↔ _ + exact exists_congr (fun bits => circuitOfVerifier_accepts_iff V input bits) + +theorem mismatchExpr_size_le (V : NPVerifier) (input : List Bool) (j : Fin (width V input)) : + (mismatchExpr V input j).size ≤ 2 := by + unfold mismatchExpr + split <;> simp [Expr.size] + +theorem acceptanceExpr_size_le (V : NPVerifier) (input : List Bool) : + (acceptanceExpr V input).size ≤ 3 * width V input + 4 := by + have h := Expr.size_disjoin_le (List.ofFn (mismatchExpr V input)) 2 (by + intro e he + obtain ⟨j, rfl⟩ := List.mem_ofFn.mp he + exact mismatchExpr_size_le V input j) + simp only [List.length_ofFn] at h + simp only [acceptanceExpr, Expr.size] + omega + +theorem stepExpressions_size_le (V : NPVerifier) (input : List Bool) + (j : Fin (width V input + 1)) : + (stepExpressions V input j).size ≤ MachineCircuit.expressionCost V.computation.tm.m := by + refine Fin.lastCases ?_ (fun i => ?_) j + · simp only [stepExpressions, Fin.lastCases_last, Expr.size, MachineCircuit.expressionCost] + omega + · simpa [stepExpressions] using MachineCircuit.stickyExpr_size_le + (capacity V input.length) V.computation.tm.m ((bitEquiv V input).symm i) + +theorem initialExpressions_cost_le (V : NPVerifier) (input : List Bool) : + Batch.cost (List.ofFn (initialExpressions V input)) ≤ + width V input * (8 * (V.witnessBound.eval input.length + 1) + 15) + + 12 * (V.witnessBound.eval input.length + 1) ^ 2 := by + rw [Batch.cost_ofFn, Fin.sum_univ_castSucc] + simp only [initialExpressions, Fin.lastCases_castSucc, Fin.lastCases_last] + apply Nat.add_le_add + · calc + _ ≤ ∑ _ : Fin (width V input), (8 * (V.witnessBound.eval input.length + 1) + 15) := by + apply Finset.sum_le_sum + intro i _ + exact WitnessCircuit.size_initExpr_le V input (capacity V input.length) + ((bitEquiv V input).symm i) + _ = _ := by simp + · exact WitnessCircuit.size_validityExpr_le _ + +theorem circuitOfVerifier_gate_count (V : NPVerifier) (input : List Bool) : + (circuitOfVerifier V input).gates.length = + Batch.cost (List.ofFn (initialExpressions V input)) + + V.horizon input.length * Batch.cost (List.ofFn (stepExpressions V input)) + + (acceptanceExpr V input).size := by + change ((timeFrame V input (V.horizon input.length)).step + (fun _ : Fin 1 => acceptanceExpr V input)).fragment.gates.length = _ + rw [Frame.step_gate_count] + simp only [timeFrame, Frame.repeat_gate_count, initialFrame, Frame.step_gate_count, + Frame.initial, Fragment.empty, List.length_nil, Nat.zero_add] + have hsingle : Batch.cost (List.ofFn (fun _ : Fin 1 => acceptanceExpr V input)) = + (acceptanceExpr V input).size := by simp [Batch.cost] + rw [hsingle] + +theorem circuitOfVerifier_gates_le (V : NPVerifier) (input : List Bool) : + (circuitOfVerifier V input).gates.length ≤ + width V input * (8 * (V.witnessBound.eval input.length + 1) + 15) + + 12 * (V.witnessBound.eval input.length + 1) ^ 2 + + V.horizon input.length * ((width V input + 1) * + MachineCircuit.expressionCost V.computation.tm.m) + (3 * width V input + 4) := by + rw [circuitOfVerifier_gate_count] + exact Nat.add_le_add + (Nat.add_le_add (initialExpressions_cost_le V input) + (Nat.mul_le_mul_left _ (Batch.cost_ofFn_le _ _ (stepExpressions_size_le V input)))) + (acceptanceExpr_size_le V input) + +def widthPolynomial (V : NPVerifier) : Polynomial Nat := + Bounds.configurationWidthPolynomial V.computation.time V.witnessBound + (Runtime.programPushBound V.computation.tm) + ((indexing V).labelCount + (indexing V).stateCount) (indexing V).symbolCount + +theorem widthPolynomial_eval (V : NPVerifier) (input : List Bool) : + (widthPolynomial V).eval input.length = width V input := by + simp [widthPolynomial, width, ConfigIndex.Indexing.width, capacity, + NPVerifier.horizon, Nat.mul_comm] + +def gatePolynomial (V : NPVerifier) : Polynomial Nat := + VerifierBounds.machineGatesPolynomial V.computation.time V.witnessBound + (Runtime.programPushBound V.computation.tm) + ((indexing V).labelCount + (indexing V).stateCount) (indexing V).symbolCount + (MachineCircuit.expressionCost V.computation.tm.m) + +def formulaPolynomial (V : NPVerifier) : Polynomial Nat := + VerifierBounds.machineBitsPolynomial V.computation.time V.witnessBound + (Runtime.programPushBound V.computation.tm) + ((indexing V).labelCount + (indexing V).stateCount) (indexing V).symbolCount + (MachineCircuit.expressionCost V.computation.tm.m) + +theorem circuitOfVerifier_gates_le_polynomial (V : NPVerifier) (input : List Bool) : + (circuitOfVerifier V input).gates.length ≤ (gatePolynomial V).eval input.length := by + have hw := widthPolynomial_eval V input + unfold widthPolynomial at hw + simpa only [gatePolynomial, VerifierBounds.machineGatesPolynomial_eval, hw, + Bounds.horizonPolynomial_eval, NPVerifier.horizon] using + circuitOfVerifier_gates_le V input + +theorem circuitOfVerifier_formulaBits_length_le (V : NPVerifier) (input : List Bool) : + (formulaBits (circuitOfVerifier V input).toFormula).length ≤ + (formulaPolynomial V).eval input.length := by + unfold formulaPolynomial + apply VerifierBounds.toFormula_bits_le_machinePolynomial + · exact Nat.le_refl _ + · exact circuitOfVerifier_gates_le_polynomial V input + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.VerifierCircuit + +end + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/VerifierFront.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/VerifierFront.lean new file mode 100644 index 0000000000000000000000000000000000000000..4e1b5e0e8ccf14a8cf0da316db5714ef2958f29e --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/VerifierFront.lean @@ -0,0 +1,336 @@ +import OAI.Computability.PerfectCompleteness.Machines.ClockPreparation +import OAI.Computability.PerfectCompleteness.Machines.InputFrame +import OAI.Computability.UniqueGames.Machines.MachineCompositionLemmas +import OAI.Computability.UniqueGames.Machines.MachineCopy +import OAI.Computability.UniqueGames.Machines.MachineSubroutineLemmas +import OAI.Computability.UniqueGames.PCP.SourceMachine + +namespace OAI + +section + +noncomputable section +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.VerifierFront +open Turing MachineComposition +open UniqueGamesTheorem.Foundations.Hastad + +abbrev Tape (V : NPVerifier) := Fin 3 ⊕ ClockPreparation.Layout (ClockPreparation.clockPolynomials V) +abbrev ExtraLabel (V : NPVerifier) := Fin 4 ⊕ ClockPreparation.ProgramLabel (ClockPreparation.clockPolynomials V) +abbrev Label (V : NPVerifier) := InputFrame.Label ⊕ ExtraLabel V +abbrev State (A : Type) := A × Option Bool +abbrev EmbeddedAlphabet (V : NPVerifier) := MachineEmbedding.Alphabet InputFrame.Alphabet + (fun _ : ClockPreparation.Layout (ClockPreparation.clockPolynomials V) => Bool) + +def raw (V : NPVerifier) : Tape V := .inl 0 +def stream (V : NPVerifier) : Tape V := .inl 1 +def scratch (V : NPVerifier) : Tape V := .inl 2 +def clockSlots (V : NPVerifier) : ClockPreparation.Layout (ClockPreparation.clockPolynomials V) ↪ Tape V := + ⟨Sum.inr, Sum.inr_injective⟩ +def lengthTape (V : NPVerifier) : Tape V := clockSlots V (.inl ()) +def clockTape (V : NPVerifier) (c : ClockPreparation.Clock) : Tape V := + clockSlots V (ClockPreparation.outputSlot _ (ClockPreparation.clockOutput V c)) +def phase (V : NPVerifier) (i : Fin 4) : Label V := .inr (.inl i) +def clockLabel (V : NPVerifier) (l : ClockPreparation.ProgramLabel (ClockPreparation.clockPolynomials V)) : Label V := + .inr (.inr l) + +def frameStates (A : Type) : (InputFrame.State × A) ≃ State A where + toFun s := (s.2, s.1.2) + invFun s := (((), s.2), s.1) + left_inv := by rintro ⟨⟨⟨⟩, r⟩, a⟩; rfl + right_inv _ := rfl + +def clockStates (A : Type) : MachineHorner.State A ≃ State A where + toFun s := (s.1.1, s.2) + invFun s := ((s.1, ()), s.2) + left_inv := by rintro ⟨⟨a, ⟨⟩⟩, r⟩; rfl + right_inv _ := rfl + +theorem alphabet_eq (V : NPVerifier) : EmbeddedAlphabet V = (fun _ : Tape V => Bool) := by + funext k + cases k <;> rfl + +variable {A : Type} + +def extraProgram (V : NPVerifier) : ExtraLabel V → TM2.Stmt (fun _ : Tape V => Bool) (Label V) (State A) + | .inl i => if i = 0 then + Reduction.MachineTransfer.loopAt (raw V) (scratch V) id false (phase V 0) (some (phase V 1)) + else if i = 1 then + MachineCopy.forkLoop (scratch V) (raw V) (stream V) false (phase V 1) (some (phase V 2)) + else if i = 2 then SourceMachine.fieldStart (lengthTape V) (phase V 3) + else SourceMachine.fieldLoop (raw V) (lengthTape V) (phase V 3) (some (clockLabel V (.inl ()))) + | .inr l => MachineSubroutine.statement (clockLabel V) none + (MachineStateEquiv.statement (clockStates A) + (ClockPreparation.program (ClockPreparation.clockPolynomials V) (clockSlots V) l)) + +def innerExtra (V : NPVerifier) : ExtraLabel V → + TM2.Stmt (EmbeddedAlphabet V) (Label V) (InputFrame.State × A) := fun l => + MachineStateEquiv.statement (frameStates A).symm + (MachineAlphabetTransport.statement (alphabet_eq V).symm (extraProgram V l)) + +def embeddedProgram (V : NPVerifier) : Label V → + TM2.Stmt (EmbeddedAlphabet V) (Label V) (InputFrame.State × A) := + MachineEmbedding.program (some (phase V 0)) InputFrame.program (innerExtra V) + +def program (V : NPVerifier) : Label V → TM2.Stmt (fun _ : Tape V => Bool) (Label V) (State A) := + MachineAlphabetTransport.program (alphabet_eq V) + (MachineStateEquiv.program (frameStates A) (embeddedProgram V)) + +@[simp] theorem program_extra (V : NPVerifier) (l : ExtraLabel V) : + program (A := A) V (.inr l) = extraProgram V l := by + simp only [program, MachineAlphabetTransport.program, MachineStateEquiv.program, + embeddedProgram, MachineEmbedding.program, innerExtra] + have h := MachineStateEquiv.statement_symm_statement (frameStates A).symm + (MachineAlphabetTransport.statement (alphabet_eq V).symm (extraProgram (A := A) V l)) + simp only [Equiv.symm_symm] at h + rw [h] + exact MachineAlphabetTransport.statement_roundtrip _ _ + +def frameTapes (V : NPVerifier) (word : List Bool) : Tape V → List Bool + | .inl i => if i = 0 then word else [] + | .inr _ => [] + +def framedTapes (V : NPVerifier) (input : List Bool) : Tape V → List Bool := + frameTapes V (encodeWord input.length ++ input) + +def copiedTapes (V : NPVerifier) (input : List Bool) : Tape V → List Bool := + Function.update (framedTapes V input) (stream V) (encodeWord input.length ++ input) + +def seedTapes (V : NPVerifier) (input : List Bool) : Tape V → List Bool := + Function.update (Function.update (copiedTapes V input) (raw V) input) + (lengthTape V) (encodeWord input.length) + +def preparedTapes (V : NPVerifier) (input : List Bool) : Tape V → List Bool := + ClockPreparation.resultTapes (ClockPreparation.clockPolynomials V) (clockSlots V) + (seedTapes V input) input.length + +private theorem alphabet_tapes_apply {K : Type} {Γ Δ : K → Type} + (h : Γ = Δ) (base : ∀ k, List (Γ k)) (k : K) : + MachineAlphabetTransport.tapes h base k = + Eq.mp (congrArg (fun alphabet => List (alphabet k)) h) (base k) := by + cases h + rfl + +theorem uniform_frame_tapes (V : NPVerifier) (word : List Bool) : + MachineAlphabetTransport.tapes (alphabet_eq V) + (MachineEmbedding.tapes (InputFrame.tapes word [] []) (fun _ => [])) = frameTapes V word := by + funext k + rw [alphabet_tapes_apply] + cases k with + | inl i => fin_cases i <;> rfl + | inr k => rfl + +def frameInTime (V : NPVerifier) (input : List Bool) (ambient : A) : + StateTransition.EvalsToInTime (TM2.step (program V)) + ⟨some (.inl 0), (ambient, none), frameTapes V input⟩ + (some ⟨some (phase V 0), (ambient, none), framedTapes V input⟩) + (4 * input.length + 7) := by + have hi : initList InputFrame.machine input = InputFrame.cfg (some 0) input [] [] := by + unfold initList InputFrame.cfg + congr 1 + funext i + fin_cases i <;> simp [InputFrame.machine, InputFrame.tapes] + let original : StateTransition.EvalsToInTime (TM2.step InputFrame.program) + (InputFrame.cfg (some 0) input [] []) + (some (InputFrame.cfg none (encodeWord input.length ++ input) [] [])) + (4 * input.length + 7) := { + steps := 4 * input.length + 7 + evals_in_steps := by + rw [← hi, InputFrame.stopped_eq_haltList] + exact InputFrame.frameTrace input + steps_le_m := le_rfl } + have em := embeddedExecution (some (phase V 0)) ambient (fun _ => []) + InputFrame.program (innerExtra V) original + have st := MachineStateEquiv.execution (frameStates A) (embeddedProgram V) em + have result := MachineAlphabetTransport.executionInTime (alphabet_eq V) + (MachineStateEquiv.program (frameStates A) (embeddedProgram V)) st + simpa only [program, InputFrame.cfg, MachineAlphabetTransport.configuration_mk, + MachineStateEquiv.configuration, MachineEmbedding.configuration, MachineEmbedding.label, + Option.map_some, frameStates, Equiv.coe_fn_mk, uniform_frame_tapes, framedTapes] using result + +def copyInTime (V : NPVerifier) (input : List Bool) (ambient : A) : + StateTransition.EvalsToInTime (TM2.step (program V)) + ⟨some (phase V 0), (ambient, none), framedTapes V input⟩ + (some ⟨some (phase V 2), (ambient, none), copiedTapes V input⟩) + (4 * input.length + 4) := by + have run := MachineCopy.copyInTime (raw V) (stream V) (scratch V) + (by simp [raw, stream]) (by simp [raw, scratch]) (by simp [stream, scratch]) + false (phase V 0) (phase V 1) (some (phase V 2)) (program V) + (by simp [phase, extraProgram]) (by simp [phase, extraProgram]) + (framedTapes V input) (by simp [framedTapes, frameTapes, scratch]) ambient none + have hb : 2 * ((framedTapes V input (raw V)).length + 1) = 4 * input.length + 4 := by + simp only [framedTapes, frameTapes, raw, ite_true, List.length_append, encodeWord_length] + omega + rw [hb] at run + simpa [framedTapes, frameTapes, raw, stream, copiedTapes] using run + +def fieldInTime (V : NPVerifier) (input : List Bool) (ambient : A) : + StateTransition.EvalsToInTime (TM2.step (program V)) + ⟨some (phase V 2), (ambient, none), copiedTapes V input⟩ + (some ⟨some (clockLabel V (.inl ())), (ambient, none), seedTapes V input⟩) + (input.length + 2) := by + have run := SourceMachine.fieldInTime (raw V) (lengthTape V) + (by simp [raw, lengthTape, clockSlots]) (phase V 2) (phase V 3) + (some (clockLabel V (.inl ()))) (program V) + (by simp [phase, extraProgram]) (by simp [phase, extraProgram]) + (copiedTapes V input) input.length input + (by simp [copiedTapes, raw, stream, framedTapes, frameTapes]) ambient none + simpa [SourceMachine.fieldTapes, seedTapes, copiedTapes, lengthTape, clockSlots, + stream, framedTapes, frameTapes] using run + +theorem seed_input (V : NPVerifier) (input : List Bool) : + seedTapes V input (clockSlots V (.inl ())) = encodeWord input.length := by + simp [seedTapes, lengthTape] + +theorem seed_clean (V : NPVerifier) (input : List Bool) : + ClockPreparation.Clean (ClockPreparation.clockPolynomials V) (clockSlots V) (seedTapes V input) := by + intro i + simp [seedTapes, copiedTapes, framedTapes, frameTapes, lengthTape, raw, stream, clockSlots] + +def clocksInTime (V : NPVerifier) (input : List Bool) (ambient : A) : + StateTransition.EvalsToInTime (TM2.step (program V)) + ⟨some (clockLabel V (.inl ())), (ambient, none), seedTapes V input⟩ + (some ⟨none, (ambient, none), preparedTapes V input⟩) + ((1 + ClockPreparation.timePolynomial (ClockPreparation.clockPolynomials V)).eval input.length) := by + have original := ClockPreparation.clocksInTime V (clockSlots V) (seedTapes V input) + input.length (seed_input V input) (seed_clean V input) ambient none + have st := MachineStateEquiv.execution (clockStates A) + (ClockPreparation.program (ClockPreparation.clockPolynomials V) (clockSlots V)) original + have sub := MachineSubroutine.execution (clockLabel V) none + (MachineStateEquiv.program (clockStates A) + (ClockPreparation.program (ClockPreparation.clockPolynomials V) (clockSlots V))) + (program V) (by intro l; simp [clockLabel, extraProgram, MachineStateEquiv.program]) st + simpa only [MachineSubroutine.configuration, MachineSubroutine.label, + MachineStateEquiv.configuration, Option.map_some, clockStates, Equiv.coe_fn_mk, + preparedTapes] using sub + +def timePolynomial (V : NPVerifier) : Polynomial Nat := + Polynomial.C 9 * Polynomial.X + Polynomial.C 14 + ClockPreparation.timePolynomial (ClockPreparation.clockPolynomials V) + +def prepareInTime (V : NPVerifier) (input : List Bool) (ambient : A) : + StateTransition.EvalsToInTime (TM2.step (program V)) + ⟨some (.inl 0), (ambient, none), frameTapes V input⟩ + (some ⟨none, (ambient, none), preparedTapes V input⟩) + ((timePolynomial V).eval input.length) := by + let one := frameInTime V input ambient + let two := copyInTime V input ambient + let three := fieldInTime V input ambient + let four := clocksInTime V input ambient + let a := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ one two + let b := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ a three + let c := StateTransition.EvalsToInTime.trans _ _ _ _ _ _ b four + exact { + toEvalsTo := c.toEvalsTo + steps_le_m := by + have h := c.steps_le_m + simp only [timePolynomial, Polynomial.eval_add, Polynomial.eval_mul, Polynomial.eval_C, + Polynomial.eval_X, Polynomial.eval_one] at * + omega } + +def callerInTime {Λ : Type} (V : NPVerifier) (labels : Label V → Λ) (exit : Option Λ) + (caller : Λ → TM2.Stmt (fun _ : Tape V => Bool) Λ (State A)) + (atLabels : ∀ l, caller (labels l) = MachineSubroutine.statement labels exit (program V l)) + (input : List Bool) (ambient : A) : + StateTransition.EvalsToInTime (TM2.step caller) + ⟨some (labels (.inl 0)), (ambient, none), frameTapes V input⟩ + (some ⟨exit, (ambient, none), preparedTapes V input⟩) + ((timePolynomial V).eval input.length) := by + exact MachineSubroutine.execution labels exit (program V) caller atLabels + (prepareInTime V input ambient) + +theorem prepared_raw (V : NPVerifier) (input : List Bool) : + preparedTapes V input (raw V) = input := by + rw [preparedTapes, ClockPreparation.resultTapes_ambient] + · simp [seedTapes, lengthTape, clockSlots, raw] + · rintro ⟨i, hi⟩ + cases hi + +theorem prepared_stream (V : NPVerifier) (input : List Bool) : + preparedTapes V input (stream V) = encodeWord input.length ++ input := by + rw [preparedTapes, ClockPreparation.resultTapes_ambient] + · simp [seedTapes, lengthTape, clockSlots, raw, stream, copiedTapes] + · rintro ⟨i, hi⟩ + cases hi + +theorem prepared_length (V : NPVerifier) (input : List Bool) : + preparedTapes V input (lengthTape V) = encodeWord input.length := by + rw [preparedTapes, ClockPreparation.resultTapes_off_outputs] + · exact seed_input V input + · intro i h + exact ClockPreparation.outputSlot_ne_input _ i ((clockSlots V).injective h) + +theorem prepared_clock (V : NPVerifier) (input : List Bool) (c : ClockPreparation.Clock) : + preparedTapes V input (clockTape V c) = + encodeWord (ClockPreparation.clockValue V input.length c) := + ClockPreparation.clockResult_output V (clockSlots V) (seedTapes V input) input.length + (seed_clean V input) c + +theorem clockOutput_surjective (V : NPVerifier) : + Function.Surjective (ClockPreparation.clockOutput V) := by + intro i + rcases i with (⟨⟩ | (⟨⟩ | (⟨⟩ | (⟨⟩ | (⟨⟩ | (⟨⟩ | i)))))) + · exact ⟨.witness, rfl⟩ + · exact ⟨.horizon, rfl⟩ + · exact ⟨.capacity, rfl⟩ + · exact ⟨.width, rfl⟩ + · exact ⟨.frameWidth, rfl⟩ + · exact ⟨.inputCount, rfl⟩ + · exact Empty.elim i + +theorem prepared_work_clear (V : NPVerifier) (input : List Bool) (k : Tape V) + (hr : k ≠ raw V) (hs : k ≠ stream V) (hn : k ≠ lengthTape V) + (hc : ∀ c, k ≠ clockTape V c) : preparedTapes V input k = [] := by + rw [preparedTapes, ClockPreparation.resultTapes_off_outputs] + · simp only [seedTapes, Function.update_of_ne hn, Function.update_of_ne hr, + copiedTapes, Function.update_of_ne hs, framedTapes] + cases k with + | inl i => + have hi : i ≠ 0 := by intro h; exact hr (congrArg Sum.inl h) + simp [frameTapes, hi] + | inr i => rfl + · intro i h + obtain ⟨c, rfl⟩ := clockOutput_surjective V i + exact hc c h.symm + +def machine (V : NPVerifier) : FinTM2 where + K := Tape V + k₀ := raw V + k₁ := stream V + Γ _ := Bool + Λ := Label V + main := .inl 0 + σ := State Unit + initialState := ((), none) + m := program V + +theorem initial_configuration (V : NPVerifier) (input : List Bool) : + initList (machine V) input = + (⟨some (.inl 0), ((), none), frameTapes V input⟩ : (machine V).Cfg) := by + unfold initList + congr 1 + funext k + cases k with + | inl i => + by_cases hi : i = 0 + · simp [machine, raw, frameTapes, hi] + rfl + · simp [machine, raw, frameTapes, hi] + | inr i => simp [machine, raw, frameTapes] + +def machineInTime (V : NPVerifier) (input : List Bool) : + StateTransition.EvalsToInTime (machine V).step (initList (machine V) input) + (some ⟨none, ((), none), preparedTapes V input⟩) + ((timePolynomial V).eval input.length) := by + rw [initial_configuration] + exact prepareInTime V input () + +theorem finite_work_alphabets (V : NPVerifier) (k : (machine V).K) : + Finite ((machine V).Γ k) := by + change Finite Bool + infer_instance + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.VerifierFront +end + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/WholeArrayInteriorOwnInputLaw.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/WholeArrayInteriorOwnInputLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..060a890949e9bde113e99e5c615cd6f3dbcea48f --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/WholeArrayInteriorOwnInputLaw.lean @@ -0,0 +1,209 @@ +import OAI.Computability.PerfectCompleteness.Foundations.WholeArrayPositiveSplit +import OAI.Computability.PerfectCompleteness.Machines.WholeArrayOwnInputLaw + +namespace OAI + +section + +namespace PerfectCompleteness.WholeArrayInteriorOwnInputLaw + +open scoped BigOperators TensorProduct Classical +open UniqueGamesTheorem.Foundations.Games +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays + +abbrev F2 := ZMod 2 + +noncomputable section + +private theorem pushforward_eq_of_readout_weights {A B : Type*} [iA : Fintype A] + {i j : Fintype B} (μ : FiniteDistribution A) (f g : A → B) + (ν : @FiniteDistribution B i) (ν' : @FiniteDistribution B j) + (h : @FiniteDistribution.pushforward A B iA i μ f = ν) + (hread : ∀ a, f a = g a) + (hweight : ∀ b, @FiniteDistribution.weight B i ν b = @FiniteDistribution.weight B j ν' b) : + @FiniteDistribution.pushforward A B iA j μ g = ν' := by + have hfg : f = g := funext hread + cases hfg + apply @FiniteDistribution.eq_of_weight_eq B j + intro b + calc + @FiniteDistribution.weight B j (@FiniteDistribution.pushforward A B iA j μ f) b = + @FiniteDistribution.weight B i (@FiniteDistribution.pushforward A B iA i μ f) b := rfl + _ = @FiniteDistribution.weight B i ν b := + congrFun (congrArg (@FiniteDistribution.weight B i) h) b + _ = @FiniteDistribution.weight B j ν' b := hweight b + +variable {branch : Nat → Nat} {N t : Nat} + +abbrev fullPath (upper lower : Nodes branch N) (cut : OwnInputReference.Cut upper lower) := + (Nodes.path upper).append cut.path + +abbrev RawExterior (rows repeats : Nat → Nat) + (slots : Slots branch N → Fin t → MixedSupport.Slot) + (upper lower : Nodes branch N) (cut : OwnInputReference.Cut upper lower) := + WholeArrayPositiveSplit.Exterior rows repeats (Nodes.path upper) cut.path slots + +def exterior (rows repeats : Nat → Nat) + (slots : Slots branch N → Fin t → MixedSupport.Slot) + (upper lower : Nodes branch N) (cut : OwnInputReference.Cut upper lower) + (raw : RawExterior rows repeats slots upper lower cut) : + OwnInputReference.Exterior slots rows upper lower where + otherArrays node := WholeArrayPositiveSplit.nodeArray rows repeats + (Nodes.path upper) cut.path cut.proper slots raw node.val (by + simpa only [WholeArrayInteriorExterior.selectedNode_nodePath] using node.property.1) + lowerRows := WholeArrayPositiveSplit.nodeArray rows repeats + (Nodes.path upper) cut.path cut.proper slots raw lower (by + simpa only [WholeArrayInteriorExterior.selectedNode_nodePath] using cut.upper_ne_lower.symm) + +def readExterior (rows repeats : Nat → Nat) + (slots : Slots branch N → Fin t → MixedSupport.Slot) + (upper lower : Nodes branch N) (cut : OwnInputReference.Cut upper lower) + (ω : WholeArraySampler.Tape rows repeats (fullPath upper lower cut) slots) : + OwnInputReference.Exterior slots rows upper lower where + otherArrays node := WholeArraySampler.evaluate rows repeats (fullPath upper lower cut) slots ω node.val + lowerRows := WholeArraySampler.evaluate rows repeats (fullPath upper lower cut) slots ω lower + +theorem exterior_split (rows repeats : Nat → Nat) + (slots : Slots branch N → Fin t → MixedSupport.Slot) + (upper lower : Nodes branch N) (cut : OwnInputReference.Cut upper lower) + (W : Submodule F2 (Block rows upper)) + (ω : WholeArraySampler.Tape rows repeats (fullPath upper lower cut) slots) : + exterior rows repeats slots upper lower cut + (WholeArrayPositiveSplit.split rows repeats (Nodes.path upper) cut.path + cut.proper slots W ω).2.2 = + readExterior rows repeats slots upper lower cut ω := by + unfold exterior readExterior + congr 1 + · funext node + exact WholeArrayPositiveSplit.nodeArray_split rows repeats + (Nodes.path upper) cut.path cut.proper slots W ω node.val (by + simpa only [WholeArrayInteriorExterior.selectedNode_nodePath] using node.property.1) + · exact WholeArrayPositiveSplit.nodeArray_split rows repeats + (Nodes.path upper) cut.path cut.proper slots W ω lower (by + simpa only [WholeArrayInteriorExterior.selectedNode_nodePath] using cut.upper_ne_lower.symm) + +def exteriorLaw (rows repeats : Nat → Nat) + (slots : Slots branch N → Fin t → MixedSupport.Slot) + (upper lower : Nodes branch N) (cut : OwnInputReference.Cut upper lower) : + FiniteDistribution (OwnInputReference.Exterior slots rows upper lower) := + (WholeArrayPositiveSplit.exteriorLaw rows repeats (Nodes.path upper) cut.path slots).pushforward + (exterior rows repeats slots upper lower cut) + +def exposedRead (rows repeats : Nat → Nat) + (slots : Slots branch N → Fin t → MixedSupport.Slot) + (upper lower : Nodes branch N) (cut : OwnInputReference.Cut upper lower) + (W : Submodule F2 (Block rows upper)) + (ω : WholeArraySampler.Tape rows repeats (fullPath upper lower cut) slots) : + OwnInputReference.RawSample slots rows upper lower W repeats cut := + let parts := WholeArrayPositiveSplit.split rows repeats (Nodes.path upper) cut.path cut.proper slots W ω + (parts.1, (parts.2.1, readExterior rows repeats slots upper lower cut ω)) + +theorem exposedRead_law (rows repeats : Nat → Nat) + (slots : Slots branch N → Fin t → MixedSupport.Slot) + (upper lower : Nodes branch N) (cut : OwnInputReference.Cut upper lower) + (W : Submodule F2 (Block rows upper)) : + (WholeArraySampler.tapeLaw rows repeats (fullPath upper lower cut) slots).pushforward + (exposedRead rows repeats slots upper lower cut W) = + OwnInputReference.rawLaw slots rows upper lower W repeats cut + (exteriorLaw rows repeats slots upper lower cut) := by + have hsplit := WholeArrayPositiveSplit.split_readout_law rows repeats + (Nodes.path upper) cut.path cut.proper slots W + (exterior rows repeats slots upper lower cut) + refine pushforward_eq_of_readout_weights _ _ _ _ _ hsplit ?_ ?_ + · intro ω + exact congrArg + (fun external => + ((WholeArrayPositiveSplit.split rows repeats (Nodes.path upper) cut.path + cut.proper slots W ω).1, + ((WholeArrayPositiveSplit.split rows repeats (Nodes.path upper) cut.path + cut.proper slots W ω).2.1, external))) + (exterior_split rows repeats slots upper lower cut W ω) + · intro x + rfl + +def readInput (rows repeats : Nat → Nat) + (slots : Slots branch N → Fin t → MixedSupport.Slot) + (upper lower : Nodes branch N) (cut : OwnInputReference.Cut upper lower) + (W : Submodule F2 (Block rows upper)) (a : Block rows lower) + (data : HiddenBucketBias.VisibleTape W + (OwnInputReference.ScalarSample slots upper lower repeats cut) × + RawExterior rows repeats slots upper lower cut) : + OwnInputReference.Input slots rows upper lower W a := + OwnInputReference.readInput slots rows upper lower W a + (RecursiveSampler.evaluate F2 repeats cut.path (LeafDomain (nodeSlots slots upper))) + (data.1, exterior rows repeats slots upper lower cut data.2) + +def ownInput (rows repeats : Nat → Nat) + (slots : Slots branch N → Fin t → MixedSupport.Slot) + (upper lower : Nodes branch N) (cut : OwnInputReference.Cut upper lower) + (W : Submodule F2 (Block rows upper)) (a : Block rows lower) + (ω : WholeArraySampler.Tape rows repeats (fullPath upper lower cut) slots) : + OwnInputReference.Input slots rows upper lower W a := + OwnInputReference.readInput slots rows upper lower W a + (RecursiveSampler.evaluate F2 repeats cut.path (LeafDomain (nodeSlots slots upper))) + (exposedRead rows repeats slots upper lower cut W ω).2 + +theorem readInput_split (rows repeats : Nat → Nat) + (slots : Slots branch N → Fin t → MixedSupport.Slot) + (upper lower : Nodes branch N) (cut : OwnInputReference.Cut upper lower) + (W : Submodule F2 (Block rows upper)) (a : Block rows lower) + (ω : WholeArraySampler.Tape rows repeats (fullPath upper lower cut) slots) : + readInput rows repeats slots upper lower cut W a + (WholeArrayPositiveSplit.split rows repeats (Nodes.path upper) cut.path cut.proper slots W ω).2 = + ownInput rows repeats slots upper lower cut W a ω := by + unfold readInput ownInput exposedRead + rw [exterior_split] + +def hiddenOutput (rows repeats : Nat → Nat) + (slots : Slots branch N → Fin t → MixedSupport.Slot) + (upper lower : Nodes branch N) (cut : OwnInputReference.Cut upper lower) + (W : Submodule F2 (Block rows upper)) + (ω : WholeArraySampler.Tape rows repeats (fullPath upper lower cut) slots) : + W ⊗[F2] OwnInputReference.UpperSpace slots upper := + HiddenBucketBias.hiddenSum W + (RecursiveSampler.evaluate F2 repeats cut.path (LeafDomain (nodeSlots slots upper))) + (exposedRead rows repeats slots upper lower cut W ω).1 + +theorem conditional_referenceLaw (rows repeats : Nat → Nat) + (slots : Slots branch N → Fin t → MixedSupport.Slot) + (upper lower : Nodes branch N) (cut : OwnInputReference.Cut upper lower) + (W : Submodule F2 (Block rows upper)) (a : Block rows lower) + (observed : OwnInputReference.Input slots rows upper lower W a) + (positive : 0 < + (WholeArraySampler.tapeLaw rows repeats (fullPath upper lower cut) slots).probability + (fun ω => decide (ownInput rows repeats slots upper lower cut W a ω = observed))) : + ((WholeArraySampler.tapeLaw rows repeats (fullPath upper lower cut) slots).condition + (fun ω => decide (ownInput rows repeats slots upper lower cut W a ω = observed)) positive).pushforward + (hiddenOutput rows repeats slots upper lower cut W) = + OwnInputReference.referenceLaw slots rows upper lower W repeats cut := by + let μ := WholeArraySampler.tapeLaw rows repeats (fullPath upper lower cut) slots + let read := exposedRead rows repeats slots upper lower cut W + let ν := OwnInputReference.rawLaw slots rows upper lower W repeats cut + (exteriorLaw rows repeats slots upper lower cut) + let event := OwnInputReference.inputEvent slots rows upper lower W a repeats cut observed + let eval := RecursiveSampler.evaluate F2 repeats cut.path (LeafDomain (nodeSlots slots upper)) + have hread : μ.pushforward read = ν := exposedRead_law rows repeats slots upper lower cut W + have positive' : 0 < ν.probability event := by + rw [← hread, FiniteDistribution.probability_pushforward] + exact positive + have hcondition : + (μ.condition (fun ω => event (read ω)) positive).pushforward read = + ν.condition event positive' := by + simpa only [hread] using + WholeArrayOwnInputLaw.condition_pushforward μ read event positive + calc + _ = ((μ.condition (fun ω => event (read ω)) positive).pushforward read).pushforward + (fun z => HiddenBucketBias.hiddenSum W eval z.1) := + (FiniteDistribution.pushforward_comp _ read + (fun z => HiddenBucketBias.hiddenSum W eval z.1)).symm + _ = _ := by + rw [hcondition] + exact OwnInputReference.conditional_referenceLaw slots rows upper lower W a repeats cut + (exteriorLaw rows repeats slots upper lower cut) observed positive' + +end +end PerfectCompleteness.WholeArrayInteriorOwnInputLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/WholeArrayOwnInputLaw.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/WholeArrayOwnInputLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..0c78243cfb9f9c4bd91b71fb6c543a668b27c7d1 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/WholeArrayOwnInputLaw.lean @@ -0,0 +1,187 @@ +import OAI.Computability.PerfectCompleteness.Sampling.WholeArrayExteriorLaw + +namespace OAI + +section + +namespace PerfectCompleteness.WholeArrayOwnInputLaw + +open scoped BigOperators TensorProduct Classical +open UniqueGamesTheorem.Foundations.Games +open TreeSourceSpaces HierarchicalArrays DescendantSpaces WholeArraySampler +open WholeArrayHiddenLaw WholeArrayExteriorLaw + +noncomputable section + +theorem condition_pushforward {A B : Type*} [Fintype A] [Fintype B] + (μ : FiniteDistribution A) (f : A → B) (event : B → Bool) + (positive : 0 < μ.probability (fun x => event (f x))) : + (μ.condition (fun x => event (f x)) positive).pushforward f = + (μ.pushforward f).condition event + (by simpa only [FiniteDistribution.probability_pushforward] using positive) := by + apply FiniteDistribution.eq_of_weight_eq + intro b + rw [FiniteDistribution.weight_eq_probability_singleton, + FiniteDistribution.weight_eq_probability_singleton] + simp only [FiniteDistribution.probability_pushforward, + FiniteDistribution.probability_condition] + +variable {branch : Nat → Nat} {n t : Nat} + +theorem lower_ne_root (lower : Nodes branch (n + 1)) + (p : Path branch n (Nodes.height lower)) : lower ≠ Sum.inl () := by + intro h + have hp := p.height_le + rw [h] at hp + exact Nat.not_succ_le_self n hp + +def rootCut (i : Fin (branch n)) (lower : Nodes branch (n + 1)) + (p : Path branch n (Nodes.height lower)) + (agree : ∀ s, (Path.step i p).slotEmbedding s = (Nodes.path lower).slotEmbedding s) : + OwnInputReference.Cut (branch := branch) (n := n + 1) (Sum.inl ()) lower where + proper := Nat.lt_succ_of_le p.height_le + path := .step i p + slots_agree := agree + +def nodeCut (i : Fin (branch n)) (lower : Nodes branch n) : + OwnInputReference.Cut (branch := branch) (n := n + 1) + (Sum.inl ()) (Sum.inr (i, lower)) := + rootCut i (Sum.inr (i, lower)) (Nodes.path lower) (fun _ => rfl) + +def exposedRead (rows repeats : Nat → Nat) (i : Fin (branch n)) + (lower : Nodes branch (n + 1)) (p : Path branch n (Nodes.height lower)) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (W : Submodule F2 (Fin (rows (n + 1)) → F2)) + (ω : Tape rows repeats (.step i p) slots) : + HiddenBucketBias.HiddenTape W (ScalarTape repeats i p slots) × + (HiddenBucketBias.VisibleTape W (ScalarTape repeats i p slots) × + OwnInputReference.Exterior slots rows (Sum.inl ()) lower) := + ((split rows repeats i p slots W ω).1, + ((split rows repeats i p slots W ω).2.1, readExterior rows repeats i p slots lower ω)) + +theorem exposedRead_law (rows repeats : Nat → Nat) (i : Fin (branch n)) + (lower : Nodes branch (n + 1)) (p : Path branch n (Nodes.height lower)) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (W : Submodule F2 (Fin (rows (n + 1)) → F2)) : + (WholeArraySampler.tapeLaw rows repeats (.step i p) slots).pushforward + (exposedRead rows repeats i lower p slots W) = + HiddenBucketBias.exposedLaw W (scalarLaw repeats i p slots) + (exteriorLaw rows repeats i p slots lower (lower_ne_root lower p)) := + split_exterior_law rows repeats i p slots lower (lower_ne_root lower p) W + +def ownInput (rows repeats : Nat → Nat) (i : Fin (branch n)) + (lower : Nodes branch (n + 1)) (p : Path branch n (Nodes.height lower)) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (W : Submodule F2 (Fin (rows (n + 1)) → F2)) (a : Block rows lower) + (ω : Tape rows repeats (.step i p) slots) : + OwnInputReference.Input slots rows (Sum.inl ()) lower W a := + OwnInputReference.readInput slots rows (Sum.inl ()) lower W a + (RecursiveSampler.evaluate F2 repeats (.step i p) (LeafDomain slots)) + (exposedRead rows repeats i lower p slots W ω).2 + +def hiddenOutput (rows repeats : Nat → Nat) (i : Fin (branch n)) + (lower : Nodes branch (n + 1)) (p : Path branch n (Nodes.height lower)) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (W : Submodule F2 (Fin (rows (n + 1)) → F2)) + (ω : Tape rows repeats (.step i p) slots) : W ⊗[F2] H slots := + HiddenBucketBias.hiddenSum W + (RecursiveSampler.evaluate F2 repeats (.step i p) (LeafDomain slots)) + (exposedRead rows repeats i lower p slots W ω).1 + +theorem conditional_referenceLaw (rows repeats : Nat → Nat) (i : Fin (branch n)) + (lower : Nodes branch (n + 1)) (p : Path branch n (Nodes.height lower)) + (agree : ∀ s, (Path.step i p).slotEmbedding s = (Nodes.path lower).slotEmbedding s) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (W : Submodule F2 (Fin (rows (n + 1)) → F2)) (a : Block rows lower) + (observed : OwnInputReference.Input slots rows (Sum.inl ()) lower W a) + (positive : 0 < (WholeArraySampler.tapeLaw rows repeats (.step i p) slots).probability + (fun ω => decide (ownInput rows repeats i lower p slots W a ω = observed))) : + ((WholeArraySampler.tapeLaw rows repeats (.step i p) slots).condition + (fun ω => decide (ownInput rows repeats i lower p slots W a ω = observed)) positive).pushforward + (hiddenOutput rows repeats i lower p slots W) = + OwnInputReference.referenceLaw slots rows (Sum.inl ()) lower W repeats + (rootCut i lower p agree) := by + let eval : ScalarTape repeats i p slots → H slots := + RecursiveSampler.evaluate F2 repeats (.step i p) (LeafDomain slots) + let observe := fun z : + HiddenBucketBias.VisibleTape W (ScalarTape repeats i p slots) × + OwnInputReference.Exterior slots rows (Sum.inl ()) lower => + decide (OwnInputReference.readInput slots rows (Sum.inl ()) lower W a eval z = observed) + let event := fun z : + HiddenBucketBias.HiddenTape W (ScalarTape repeats i p slots) × + (HiddenBucketBias.VisibleTape W (ScalarTape repeats i p slots) × + OwnInputReference.Exterior slots rows (Sum.inl ()) lower) => + observe z.2 + have hevent : + (fun ω => decide (ownInput rows repeats i lower p slots W a ω = observed)) = + (fun ω => event (exposedRead rows repeats i lower p slots W ω)) := by + funext ω + exact Bool.decide_congr Iff.rfl + have positiveRead : 0 < + (WholeArraySampler.tapeLaw rows repeats (.step i p) slots).probability + (fun ω => event (exposedRead rows repeats i lower p slots W ω)) := by + rw [← hevent] + exact positive + have positive' : 0 < + (HiddenBucketBias.exposedLaw W (scalarLaw repeats i p slots) + (exteriorLaw rows repeats i p slots lower (lower_ne_root lower p))).probability event := by + rw [← exposedRead_law rows repeats i lower p slots W, + FiniteDistribution.probability_pushforward] + exact positiveRead + have hcondition : + (((WholeArraySampler.tapeLaw rows repeats (.step i p) slots).condition + (fun ω => decide (ownInput rows repeats i lower p slots W a ω = observed)) positive).pushforward + (exposedRead rows repeats i lower p slots W)) = + (HiddenBucketBias.exposedLaw W (scalarLaw repeats i p slots) + (exteriorLaw rows repeats i p slots lower (lower_ne_root lower p))).condition + event positive' := by + have h := condition_pushforward + (WholeArraySampler.tapeLaw rows repeats (.step i p) slots) + (exposedRead rows repeats i lower p slots W) event positiveRead + simpa only [← hevent, exposedRead_law] using h + have href : + ((HiddenBucketBias.exposedLaw W (scalarLaw repeats i p slots) + (exteriorLaw rows repeats i p slots lower (lower_ne_root lower p))).condition + event positive').pushforward + (fun z => HiddenBucketBias.hiddenSum W eval z.1) = + HiddenBucketBias.law W (scalarLaw repeats i p slots) eval := + HiddenBucketBias.law_condition_exterior W (scalarLaw repeats i p slots) + (exteriorLaw rows repeats i p slots lower (lower_ne_root lower p)) + eval observe positive' + calc + _ = (((WholeArraySampler.tapeLaw rows repeats (.step i p) slots).condition + (fun ω => decide (ownInput rows repeats i lower p slots W a ω = observed)) positive).pushforward + (exposedRead rows repeats i lower p slots W)).pushforward + (fun z => HiddenBucketBias.hiddenSum W eval z.1) := + (FiniteDistribution.pushforward_comp _ (exposedRead rows repeats i lower p slots W) + (fun z => HiddenBucketBias.hiddenSum W eval z.1)).symm + _ = HiddenBucketBias.law W (scalarLaw repeats i p slots) eval := by + rw [hcondition] + exact href + _ = _ := rfl + +theorem conditional_referenceLaw_node (rows repeats : Nat → Nat) (i : Fin (branch n)) + (lower : Nodes branch n) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (W : Submodule F2 (Fin (rows (n + 1)) → F2)) + (a : Block (branch := branch) (n := n + 1) rows (Sum.inr (i, lower))) + (observed : OwnInputReference.Input slots rows (Sum.inl ()) (Sum.inr (i, lower)) W a) + (positive : 0 < + (WholeArraySampler.tapeLaw rows repeats (.step i (Nodes.path lower)) slots).probability + (fun ω => decide (ownInput rows repeats i (Sum.inr (i, lower)) (Nodes.path lower) + slots W a ω = observed))) : + ((WholeArraySampler.tapeLaw rows repeats (.step i (Nodes.path lower)) slots).condition + (fun ω => decide (ownInput rows repeats i (Sum.inr (i, lower)) (Nodes.path lower) + slots W a ω = observed)) positive).pushforward + (hiddenOutput rows repeats i (Sum.inr (i, lower)) (Nodes.path lower) slots W) = + OwnInputReference.referenceLaw slots rows (Sum.inl ()) (Sum.inr (i, lower)) W repeats + (nodeCut i lower) := + conditional_referenceLaw rows repeats i (Sum.inr (i, lower)) (Nodes.path lower) + (fun _ => rfl) slots W a observed positive + +end +end PerfectCompleteness.WholeArrayOwnInputLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/WitnessCircuit.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/WitnessCircuit.lean new file mode 100644 index 0000000000000000000000000000000000000000..6b29b9383327a56f711294b86b03aa776e978ca4 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/WitnessCircuit.lean @@ -0,0 +1,294 @@ +import OAI.Computability.PerfectCompleteness.Machines.StatementCircuit +import OAI.Computability.PerfectCompleteness.Machines.WitnessEncodingLemmas + +namespace OAI + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.WitnessCircuit + +open StatementCircuit WitnessEncoding + + +private theorem bool_ext {a b : Bool} (h : a = true ↔ b = true) : a = b := by + cases a <;> cases b <;> simp_all + +private theorem eval_disjoin_ofFn_true {ι : Type*} {n : Nat} + (input : ι → Bool) (es : Fin n → Expr ι) : + (Expr.disjoin (List.ofFn es)).eval input = true ↔ ∃ i, (es i).eval input = true := by + rw [Expr.eval_disjoin_true] + constructor + · rintro ⟨e, he, h⟩ + obtain ⟨i, rfl⟩ := List.mem_ofFn.mp he + exact ⟨i, h⟩ + · rintro ⟨i, h⟩ + exact ⟨es i, List.mem_ofFn.mpr ⟨i, rfl⟩, h⟩ + +def selectorExpr (q : Nat) (i : Fin (q + 1)) : Expr (Fin (2 * q + 1)) := + .input ⟨i.val, by omega⟩ + +def payloadExpr (q : Nat) (i : Fin q) : Expr (Fin (2 * q + 1)) := + .input ⟨q + 1 + i.val, by omega⟩ + +@[simp] theorem eval_selectorExpr {q : Nat} (bits : Bits q) (i : Fin (q + 1)) : + (selectorExpr q i).eval bits = selector bits i := rfl + +@[simp] theorem eval_payloadExpr {q : Nat} (bits : Bits q) (i : Fin q) : + (payloadExpr q i).eval bits = payload bits i := rfl + +def nonemptyExpr (q : Nat) : Expr (Fin (2 * q + 1)) := + .disjoin (List.ofFn (selectorExpr q)) + +def clashPairExpr (q : Nat) (i j : Fin (q + 1)) : Expr (Fin (2 * q + 1)) := + if i = j then .const false else .and (selectorExpr q i) (selectorExpr q j) + +def clashExpr (q : Nat) : Expr (Fin (2 * q + 1)) := + .disjoin (List.ofFn fun i => .disjoin (List.ofFn (clashPairExpr q i))) + +def validityExpr (q : Nat) : Expr (Fin (2 * q + 1)) := + .and (nonemptyExpr q) (.not (clashExpr q)) + +theorem eval_nonemptyExpr {q : Nat} (bits : Bits q) : + (nonemptyExpr q).eval bits = true ↔ ∃ i, selector bits i = true := by + simp only [nonemptyExpr, eval_disjoin_ofFn_true, eval_selectorExpr] + +theorem eval_clashPairExpr {q : Nat} (bits : Bits q) (i j : Fin (q + 1)) : + (clashPairExpr q i j).eval bits = true ↔ + i ≠ j ∧ selector bits i = true ∧ selector bits j = true := by + by_cases h : i = j <;> simp [clashPairExpr, h, Expr.eval] + +theorem eval_clashExpr {q : Nat} (bits : Bits q) : + (clashExpr q).eval bits = true ↔ + ∃ i j, i ≠ j ∧ selector bits i = true ∧ selector bits j = true := by + simp only [clashExpr, eval_disjoin_ofFn_true, eval_clashPairExpr] + +theorem eval_validityExpr {q : Nat} (bits : Bits q) : + (validityExpr q).eval bits = true ↔ Valid bits := by + rw [valid_iff_local] + simp only [validityExpr, Expr.eval, Bool.and_eq_true, Bool.not_eq_true'] + rw [eval_nonemptyExpr] + have hc := eval_clashExpr bits + constructor + · rintro ⟨hne, hclash⟩ + refine ⟨hne, fun i j hi hj => ?_⟩ + by_contra hij + have ht := hc.mpr ⟨i, j, hij, hi, hj⟩ + simp [hclash] at ht + · rintro ⟨hne, hu⟩ + refine ⟨hne, ?_⟩ + cases hb : (clashExpr q).eval bits + · rfl + · obtain ⟨i, j, hij, hi, hj⟩ := hc.mp hb + exact False.elim (hij (hu i j hi hj)) + +def presenceExpr (q n : Nat) : Expr (Fin (2 * q + 1)) := + .disjoin (List.ofFn fun length : Fin (q + 1) => + .and (selectorExpr q length) (.const (decide (n < length.val)))) + +theorem eval_presenceExpr {q : Nat} (bits : Bits q) (n : Nat) : + (presenceExpr q n).eval bits = present bits n := by + apply bool_ext + simp only [presenceExpr, eval_disjoin_ofFn_true, Expr.eval, eval_selectorExpr, + Bool.and_eq_true, present, decide_eq_true_eq] + +section Symbols + +variable {A : Type*} [DecidableEq A] + +def payloadSymbolExpr (q : Nat) (f : Bool → A) (i : Fin q) (a : Option A) : + Expr (Fin (2 * q + 1)) := + .mux (payloadExpr q i) + (.const (decide (some (f true) = a))) (.const (decide (some (f false) = a))) + +theorem eval_payloadSymbolExpr {q : Nat} (bits : Bits q) (f : Bool → A) + (i : Fin q) (a : Option A) : + (payloadSymbolExpr q f i a).eval bits = decide (some (f (payload bits i)) = a) := by + rw [payloadSymbolExpr, Expr.eval_mux, eval_payloadExpr] + cases payload bits i <;> simp [Expr.eval] + +def inputCellExpr (q : Nat) (input : List Bool) (f : Bool → A) (n : Nat) (a : Option A) : + Expr (Fin (2 * q + 1)) := + if n < (inputPrefix input).length then + .const (decide (((inputPrefix input)[n]?).map f = a)) + else if h : n - (inputPrefix input).length < q then + .mux (presenceExpr q (n - (inputPrefix input).length)) + (payloadSymbolExpr q f ⟨n - (inputPrefix input).length, h⟩ a) + (.const (decide ((none : Option A) = a))) + else .const (decide ((none : Option A) = a)) + +theorem eval_inputCellExpr {q : Nat} (bits : Bits q) (input : List Bool) + (f : Bool → A) (n : Nat) (a : Option A) : + (inputCellExpr q input f n a).eval bits = decide ((pairCell input bits n).map f = a) := by + by_cases hp : n < (inputPrefix input).length + · simp only [inputCellExpr, pairCell, ite_eq_left hp, Expr.eval] + · by_cases hq : n - (inputPrefix input).length < q + · simp only [inputCellExpr, hp, ite_false, hq, dite_eq_left, Expr.eval_mux, + eval_presenceExpr, eval_payloadSymbolExpr, Expr.eval, pairCell, witnessCell] + cases present bits (n - (inputPrefix input).length) <;> simp + · simp only [inputCellExpr, pairCell, witnessCell, ite_eq_right hp, dite_eq_right hq, + Expr.eval, Option.map_none] + +end Symbols + +section Size + +@[simp] theorem size_selectorExpr (q : Nat) (i : Fin (q + 1)) : + (selectorExpr q i).size = 1 := rfl + +@[simp] theorem size_payloadExpr (q : Nat) (i : Fin q) : + (payloadExpr q i).size = 1 := rfl + +theorem size_mux {ι : Type*} (c y n : Expr ι) : + (Expr.mux c y n).size = 2 * c.size + y.size + n.size + 4 := by + simp only [Expr.mux, Expr.size] + omega + +theorem size_nonemptyExpr_le (q : Nat) : + (nonemptyExpr q).size ≤ 2 * (q + 1) + 1 := by + have h := Expr.size_disjoin_le (List.ofFn (selectorExpr q)) 1 (by + intro e he + obtain ⟨i, rfl⟩ := List.mem_ofFn.mp he + simp) + simpa [nonemptyExpr, Nat.mul_comm] using h + +theorem size_clashPairExpr_le (q : Nat) (i j : Fin (q + 1)) : + (clashPairExpr q i j).size ≤ 3 := by + by_cases h : i = j <;> simp [clashPairExpr, h, Expr.size, selectorExpr] + +theorem size_clashExpr_le (q : Nat) : + (clashExpr q).size ≤ (q + 1) * (4 * (q + 1) + 2) + 1 := by + have hi (i : Fin (q + 1)) : + (Expr.disjoin (List.ofFn (clashPairExpr q i))).size ≤ 4 * (q + 1) + 1 := by + have h := Expr.size_disjoin_le (List.ofFn (clashPairExpr q i)) 3 (by + intro e he + obtain ⟨j, rfl⟩ := List.mem_ofFn.mp he + exact size_clashPairExpr_le q i j) + simpa [Nat.mul_comm] using h + have h := Expr.size_disjoin_le + (List.ofFn fun i => Expr.disjoin (List.ofFn (clashPairExpr q i))) + (4 * (q + 1) + 1) (by + intro e he + obtain ⟨i, rfl⟩ := List.mem_ofFn.mp he + exact hi i) + simpa [clashExpr, Nat.add_assoc] using h + +theorem size_validityExpr_le (q : Nat) : (validityExpr q).size ≤ 12 * (q + 1) ^ 2 := by + have hn := size_nonemptyExpr_le q + have hc := size_clashExpr_le q + simp only [validityExpr, Expr.size] + nlinarith + +theorem size_presenceExpr_le (q n : Nat) : (presenceExpr q n).size ≤ 4 * (q + 1) + 1 := by + have h := Expr.size_disjoin_le + (List.ofFn fun length : Fin (q + 1) => + Expr.and (selectorExpr q length) (.const (decide (n < length.val)))) 3 (by + intro e he + obtain ⟨i, rfl⟩ := List.mem_ofFn.mp he + simp [Expr.size]) + simpa [presenceExpr, Nat.mul_comm] using h + +theorem size_payloadSymbolExpr {A : Type*} [DecidableEq A] + (q : Nat) (f : Bool → A) (i : Fin q) (a : Option A) : + (payloadSymbolExpr q f i a).size = 8 := by + simp [payloadSymbolExpr, size_mux, Expr.size] + +theorem size_inputCellExpr_le {A : Type*} [DecidableEq A] + (q : Nat) (input : List Bool) (f : Bool → A) (n : Nat) (a : Option A) : + (inputCellExpr q input f n a).size ≤ 8 * (q + 1) + 15 := by + unfold inputCellExpr + split + · simp [Expr.size] + · split + · rw [size_mux, size_payloadSymbolExpr] + have h := size_presenceExpr_le q (n - (inputPrefix input).length) + simp only [Expr.size] + omega + · simp [Expr.size] + +end Size + +section Initial + +variable (verifier : NPVerifier) +variable [DecidableEq verifier.computation.tm.Λ] +variable [DecidableEq verifier.computation.tm.σ] +variable [∀ k, DecidableEq (verifier.computation.tm.Γ k)] + +def initialCellExpr (input : List Bool) (S : Nat) + (k : verifier.computation.tm.K) (i : Fin S) (a : Option (verifier.computation.tm.Γ k)) : + Expr (Fin (2 * verifier.witnessBound.eval input.length + 1)) := + if h : k = verifier.computation.tm.k₀ then by + subst k + exact inputCellExpr _ input verifier.computation.inputAlphabet.invFun i.val a + else .const (decide ((none : Option (verifier.computation.tm.Γ k)) = a)) + +omit [DecidableEq verifier.computation.tm.Λ] [DecidableEq verifier.computation.tm.σ] in +theorem eval_initialCellExpr (input : List Bool) (S : Nat) + (bits : Bits (verifier.witnessBound.eval input.length)) (hv : Valid bits) + (k : verifier.computation.tm.K) (i : Fin S) (a : Option (verifier.computation.tm.Γ k)) : + (initialCellExpr verifier input S k i a).eval bits = + decide (StackEncoding.encode S ((initial verifier input bits).stk k) i = a) := by + by_cases hk : k = verifier.computation.tm.k₀ + · subst k + simpa [initialCellExpr, StackEncoding.encode, + pairCell_eq_getElem? input bits hv i.val] using + eval_inputCellExpr bits input verifier.computation.inputAlphabet.invFun i.val a + · simp [initialCellExpr, hk, initial_other_stack verifier input bits k hk, + StackEncoding.encode, Expr.eval] + +def initExpr (input : List Bool) (S : Nat) : + ConfigBit verifier.computation.tm.Γ verifier.computation.tm.Λ verifier.computation.tm.σ S → + Expr (Fin (2 * verifier.witnessBound.eval input.length + 1)) + | .inl label => .const (decide (some verifier.computation.tm.main = label)) + | .inr (.inl state) => .const (decide (verifier.computation.tm.initialState = state)) + | .inr (.inr ⟨k, i, a⟩) => initialCellExpr verifier input S k i a + +theorem eval_initExpr (input : List Bool) (S : Nat) + (bits : Bits (verifier.witnessBound.eval input.length)) (hv : Valid bits) + (bit : ConfigBit verifier.computation.tm.Γ verifier.computation.tm.Λ + verifier.computation.tm.σ S) : + (initExpr verifier input S bit).eval bits = + configEncoding S (initial verifier input bits) bit := by + rcases bit with label | (state | ⟨k, i, a⟩) + · rfl + · rfl + · exact eval_initialCellExpr verifier input S bits hv k i a + +omit [DecidableEq verifier.computation.tm.Λ] [DecidableEq verifier.computation.tm.σ] in +theorem size_initialCellExpr_le (input : List Bool) (S : Nat) + (k : verifier.computation.tm.K) (i : Fin S) (a : Option (verifier.computation.tm.Γ k)) : + (initialCellExpr verifier input S k i a).size ≤ + 8 * (verifier.witnessBound.eval input.length + 1) + 15 := by + by_cases hk : k = verifier.computation.tm.k₀ + · subst k + simpa [initialCellExpr] using + size_inputCellExpr_le (verifier.witnessBound.eval input.length) input + verifier.computation.inputAlphabet.invFun i.val a + · simp [initialCellExpr, hk, Expr.size] + +theorem size_initExpr_le (input : List Bool) (S : Nat) + (bit : ConfigBit verifier.computation.tm.Γ verifier.computation.tm.Λ + verifier.computation.tm.σ S) : + (initExpr verifier input S bit).size ≤ + 8 * (verifier.witnessBound.eval input.length + 1) + 15 := by + rcases bit with label | (state | ⟨k, i, a⟩) + · simp [initExpr, Expr.size] + · simp [initExpr, Expr.size] + · exact size_initialCellExpr_le verifier input S k i a + +end Initial + +def validityCircuit (q : Nat) : Circuit := (validityExpr q).circuit id + +theorem validityCircuit_eval {q : Nat} (bits : Bits q) : + (validityCircuit q).eval bits = true ↔ Valid bits := by + change ((validityExpr q).circuit id).eval bits = true ↔ Valid bits + rw [Expr.circuit_eval] + exact eval_validityExpr bits + +theorem validityCircuit_gates_le (q : Nat) : + (validityCircuit q).gates.length ≤ 12 * (q + 1) ^ 2 := by + simpa only [validityCircuit, Expr.circuit, Expr.gates_length] using size_validityExpr_le q + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.WitnessCircuit + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Machines/WitnessEncodingLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Machines/WitnessEncodingLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..35d68b1ef5dd8cffacdeab5c2147a15b7058a764 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Machines/WitnessEncodingLemmas.lean @@ -0,0 +1,364 @@ +import Mathlib.Algebra.BigOperators.Group.Finset.Basic +import Mathlib.Data.List.OfFn +import Mathlib.Tactic.Linarith +import OAI.Computability.PerfectCompleteness.Machines.CircuitLemmas +import OAI.Computability.PerfectCompleteness.Machines.ProducerBootstrapLemmas +import OAI.Computability.UniqueGames.Machines.MachineLemmas + +namespace OAI + + +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.WitnessEncoding + +open scoped BigOperators + +abbrev Bits (q : Nat) := Fin (2 * q + 1) → Bool + +def selector {q : Nat} (bits : Bits q) (i : Fin (q + 1)) : Bool := + bits ⟨i.val, by omega⟩ + +def payload {q : Nat} (bits : Bits q) (i : Fin q) : Bool := + bits ⟨q + 1 + i.val, by omega⟩ + +def pack {q : Nat} (lengthBits : Fin (q + 1) → Bool) + (payloadBits : Fin q → Bool) : Bits q := fun i => + if h : i.val < q + 1 then lengthBits ⟨i.val, h⟩ + else payloadBits ⟨i.val - (q + 1), by omega⟩ + +@[simp] theorem selector_pack {q : Nat} (lengthBits : Fin (q + 1) → Bool) + (payloadBits : Fin q → Bool) (i : Fin (q + 1)) : + selector (pack lengthBits payloadBits) i = lengthBits i := by + simp [selector, pack, i.isLt] + +@[simp] theorem payload_pack {q : Nat} (lengthBits : Fin (q + 1) → Bool) + (payloadBits : Fin q → Bool) (i : Fin q) : + payload (pack lengthBits payloadBits) i = payloadBits i := by + have outside : ¬q + 1 + i.val < q + 1 := by omega + simp [payload, pack, outside] + +def Valid {q : Nat} (bits : Bits q) : Prop := + ∃ length : Fin (q + 1), ∀ i, selector bits i = decide (i = length) + +theorem valid_iff_local {q : Nat} (bits : Bits q) : + Valid bits ↔ + (∃ i, selector bits i = true) ∧ + (∀ i j, selector bits i = true → selector bits j = true → i = j) := by + constructor + · rintro ⟨length, h⟩ + refine ⟨⟨length, by simp [h]⟩, ?_⟩ + intro i j hi hj + have hil : i = length := by simpa [h] using hi + have hjl : j = length := by simpa [h] using hj + exact hil.trans hjl.symm + · rintro ⟨⟨length, hl⟩, hu⟩ + refine ⟨length, fun i => ?_⟩ + by_cases hi : i = length + · subst i; simp [hl] + · have hf : selector bits i = false := by + cases hbi : selector bits i + · rfl + · exact False.elim (hi (hu i length hbi hl)) + simp [hi, hf] + +def selectedLength {q : Nat} (bits : Bits q) : Nat := + ∑ i : Fin (q + 1), if selector bits i then i.val else 0 + +theorem selectedLength_eq {q : Nat} (bits : Bits q) (length : Fin (q + 1)) + (h : ∀ i, selector bits i = decide (i = length)) : + selectedLength bits = length.val := by + simp [selectedLength, h] + +def decode {q : Nat} (bits : Bits q) : List Bool := + (List.ofFn (payload bits)).take (selectedLength bits) + +theorem decode_length_le {q : Nat} (bits : Bits q) : (decode bits).length ≤ q := by + simp [decode] + +theorem decode_length_eq {q : Nat} (bits : Bits q) (length : Fin (q + 1)) + (h : ∀ i, selector bits i = decide (i = length)) : + (decode bits).length = length.val := by + simp [decode, selectedLength_eq bits length h, Nat.min_eq_left (by omega : length.val ≤ q)] + +def encode (q : Nat) (witness : List Bool) (h : witness.length ≤ q) : Bits q := + pack (fun i => decide (i = ⟨witness.length, by omega⟩)) + (fun i => witness[i.val]?.getD false) + +@[simp] theorem selector_encode (q : Nat) (witness : List Bool) + (h : witness.length ≤ q) (i : Fin (q + 1)) : + selector (encode q witness h) i = + decide (i = ⟨witness.length, by omega⟩) := by + simp [encode] + +@[simp] theorem payload_encode (q : Nat) (witness : List Bool) + (h : witness.length ≤ q) (i : Fin q) : + payload (encode q witness h) i = witness[i.val]?.getD false := by + simp [encode] + +theorem encode_valid (q : Nat) (witness : List Bool) (h : witness.length ≤ q) : + Valid (encode q witness h) := + ⟨⟨witness.length, by omega⟩, selector_encode q witness h⟩ + +@[simp] theorem selectedLength_encode (q : Nat) (witness : List Bool) + (h : witness.length ≤ q) : selectedLength (encode q witness h) = witness.length := + selectedLength_eq _ ⟨witness.length, by omega⟩ (selector_encode q witness h) + +@[simp] theorem decode_encode (q : Nat) (witness : List Bool) (h : witness.length ≤ q) : + decode (encode q witness h) = witness := by + unfold decode + rw [selectedLength_encode] + apply List.ext_getElem? + intro n + by_cases hn : n < witness.length + · have hnq : n < q := Nat.lt_of_lt_of_le hn h + simp [hn, hnq] + · simp [hn] + +theorem exists_valid_iff (q : Nat) (P : List Bool → Prop) : + (∃ bits : Bits q, Valid bits ∧ P (decode bits)) ↔ + ∃ witness : List Bool, witness.length ≤ q ∧ P witness := by + constructor + · rintro ⟨bits, _, hp⟩ + exact ⟨decode bits, decode_length_le bits, hp⟩ + · rintro ⟨witness, h, hp⟩ + exact ⟨encode q witness h, encode_valid q witness h, by simpa using hp⟩ + +def present {q : Nat} (bits : Bits q) (n : Nat) : Bool := + decide (∃ length : Fin (q + 1), selector bits length = true ∧ n < length.val) + +theorem present_eq {q : Nat} (bits : Bits q) (length : Fin (q + 1)) + (h : ∀ i, selector bits i = decide (i = length)) (n : Nat) : + present bits n = decide (n < length.val) := by + simp [present, h] + +def witnessCell {q : Nat} (bits : Bits q) (n : Nat) : Option Bool := + if h : n < q then + if present bits n then some (payload bits ⟨n, h⟩) else none + else none + +theorem witnessCell_eq_getElem? {q : Nat} (bits : Bits q) (hv : Valid bits) (n : Nat) : + witnessCell bits n = (decode bits)[n]? := by + obtain ⟨length, h⟩ := hv + simp only [witnessCell, decode, selectedLength_eq bits length h, + present_eq bits length h, List.getElem?_take, List.getElem?_ofFn] + by_cases hnq : n < q <;> by_cases hnl : n < length.val <;> simp [hnq, hnl] + +theorem witnessCell_end {q : Nat} (bits : Bits q) (hv : Valid bits) + (n : Nat) (hn : (decode bits).length ≤ n) : witnessCell bits n = none := by + rw [witnessCell_eq_getElem? bits hv, List.getElem?_eq_none hn] + +def inputPrefix (input : List Bool) : List Bool := encodeWord input.length ++ input + +@[simp] theorem inputPrefix_length (input : List Bool) : + (inputPrefix input).length = 2 * input.length + 1 := by + simp only [inputPrefix, List.length_append, encodeWord_length] + omega + +def pairCell {q : Nat} (input : List Bool) (bits : Bits q) (n : Nat) : Option Bool := + if n < (inputPrefix input).length then (inputPrefix input)[n]? + else witnessCell bits (n - (inputPrefix input).length) + +theorem pairCell_eq_getElem? {q : Nat} (input : List Bool) (bits : Bits q) + (hv : Valid bits) (n : Nat) : + pairCell input bits n = (pairBits (input, decode bits))[n]? := by + rw [pairBits] + change pairCell input bits n = (inputPrefix input ++ decode bits)[n]? + rw [List.getElem?_append] + simp only [pairCell, witnessCell_eq_getElem? bits hv] + +theorem pairBits_decode_length_le {q : Nat} (input : List Bool) (bits : Bits q) : + (pairBits (input, decode bits)).length ≤ 2 * input.length + q + 1 := by + rw [pairBits_length] + change 2 * input.length + (decode bits).length + 1 ≤ 2 * input.length + q + 1 + have h := decode_length_le bits + omega + +theorem pairCells_eq_stackEncoding {q : Nat} (input : List Bool) (bits : Bits q) + (hv : Valid bits) (capacity : Nat) : + (fun i : Fin capacity => pairCell input bits i.val) = + StackEncoding.encode capacity (pairBits (input, decode bits)) := by + funext i + exact pairCell_eq_getElem? input bits hv i.val + +noncomputable def freeInputPolynomial (q : Polynomial Nat) : Polynomial Nat := 2 * q + 1 + +@[simp] theorem freeInputPolynomial_eval (q : Polynomial Nat) (n : Nat) : + (freeInputPolynomial q).eval n = 2 * q.eval n + 1 := by + simp [freeInputPolynomial] + +def localConstraintSites (q : Nat) : Nat := (q + 1) + (q + 1) ^ 2 + q * (q + 1) + +theorem localConstraintSites_le (q : Nat) : localConstraintSites q ≤ 3 * (q + 1) ^ 2 := by + unfold localConstraintSites + nlinarith + +noncomputable def localConstraintPolynomial (q : Polynomial Nat) : Polynomial Nat := 3 * (q + 1) ^ 2 + +theorem localConstraintSites_le_eval (q : Polynomial Nat) (n : Nat) : + localConstraintSites (q.eval n) ≤ (localConstraintPolynomial q).eval n := by + simpa [localConstraintPolynomial] using localConstraintSites_le (q.eval n) + + +variable (verifier : NPVerifier) (input : List Bool) + +def initial (bits : Bits (verifier.witnessBound.eval input.length)) : + verifier.computation.tm.Cfg := + Turing.initList verifier.computation.tm + ((pairBits (input, decode bits)).map verifier.computation.inputAlphabet.invFun) + +@[simp] theorem initial_control (bits : Bits (verifier.witnessBound.eval input.length)) : + (initial verifier input bits).l = some verifier.computation.tm.main := rfl + +@[simp] theorem initial_state (bits : Bits (verifier.witnessBound.eval input.length)) : + (initial verifier input bits).var = verifier.computation.tm.initialState := rfl + +@[simp] theorem initial_input_stack (bits : Bits (verifier.witnessBound.eval input.length)) : + (initial verifier input bits).stk verifier.computation.tm.k₀ = + (pairBits (input, decode bits)).map verifier.computation.inputAlphabet.invFun := by + simp [initial, Turing.initList] + +theorem initial_other_stack (bits : Bits (verifier.witnessBound.eval input.length)) + (k : verifier.computation.tm.K) (hk : k ≠ verifier.computation.tm.k₀) : + (initial verifier input bits).stk k = [] := by + simp [initial, Turing.initList, hk] + +theorem initial_input_cell (bits : Bits (verifier.witnessBound.eval input.length)) + (hv : Valid bits) (n : Nat) : + ((initial verifier input bits).stk verifier.computation.tm.k₀)[n]? = + (pairCell input bits n).map verifier.computation.inputAlphabet.invFun := by + rw [initial_input_stack, List.getElem?_map, pairCell_eq_getElem? input bits hv] + +theorem initial_input_end (bits : Bits (verifier.witnessBound.eval input.length)) + (n : Nat) (hn : 2 * input.length + (decode bits).length + 1 ≤ n) : + ((initial verifier input bits).stk verifier.computation.tm.k₀)[n]? = none := by + rw [initial_input_stack] + apply List.getElem?_eq_none + simpa only [List.length_map, pairBits_length] using hn + +theorem initial_stack_length_le (bits : Bits (verifier.witnessBound.eval input.length)) + (k : verifier.computation.tm.K) : + ((initial verifier input bits).stk k).length ≤ + 2 * input.length + verifier.witnessBound.eval input.length + 1 := by + by_cases hk : k = verifier.computation.tm.k₀ + · subst k + rw [initial_input_stack, List.length_map] + exact pairBits_decode_length_le input bits + · rw [initial_other_stack verifier input bits k hk] + simp + +theorem initial_encode (witness : List Bool) + (h : witness.length ≤ verifier.witnessBound.eval input.length) : + initial verifier input (encode _ witness h) = + Turing.initList verifier.computation.tm + ((pairBits (input, witness)).map verifier.computation.inputAlphabet.invFun) := by + simp [initial] + +theorem accepts_iff_valid_assignment : + verifier.Accepts input ↔ + ∃ bits : Bits (verifier.witnessBound.eval input.length), + Valid bits ∧ verifier.verify (input, decode bits) = true := by + exact (exists_valid_iff _ (fun witness => verifier.verify (input, witness) = true)).symm + + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.WitnessEncoding + + +noncomputable section +namespace UniqueGamesTheorem.Foundations.Complexity.CookLevin.VerifierBounds + +open Polynomial + +def initializationPolynomial (q : Polynomial ℕ) : Polynomial ℕ := + C 8 * (q + 1) + C 15 + +def validationPolynomial (q : Polynomial ℕ) : Polynomial ℕ := + C 12 * (q + 1) ^ 2 + +@[simp] theorem initializationPolynomial_eval (q : Polynomial ℕ) (n : ℕ) : + (initializationPolynomial q).eval n = 8 * (q.eval n + 1) + 15 := by + simp [initializationPolynomial] + +@[simp] theorem validationPolynomial_eval (q : Polynomial ℕ) (n : ℕ) : + (validationPolynomial q).eval n = 12 * (q.eval n + 1) ^ 2 := by + simp [validationPolynomial] + +def gatesPolynomial (p q : Polynomial ℕ) + (pushes controlBits alphabetBits expressionCost : ℕ) + (initialization validation : Polynomial ℕ) : Polynomial ℕ := + let W := Bounds.configurationWidthPolynomial p q pushes controlBits alphabetBits + W * initialization + validation + + Bounds.horizonPolynomial p q * ((W + 1) * C expressionCost) + + (C 3 * W + C 4) + +@[simp] theorem gatesPolynomial_eval (p q : Polynomial ℕ) + (pushes controlBits alphabetBits expressionCost : ℕ) + (initialization validation : Polynomial ℕ) (n : ℕ) : + (gatesPolynomial p q pushes controlBits alphabetBits expressionCost initialization validation).eval n = + (Bounds.configurationWidthPolynomial p q pushes controlBits alphabetBits).eval n * + initialization.eval n + validation.eval n + + (Bounds.horizonPolynomial p q).eval n * + (((Bounds.configurationWidthPolynomial p q pushes controlBits alphabetBits).eval n + 1) * + expressionCost) + + (3 * (Bounds.configurationWidthPolynomial p q pushes controlBits alphabetBits).eval n + 4) := by + simp [gatesPolynomial] + +def bitsPolynomial (p q : Polynomial ℕ) + (pushes controlBits alphabetBits expressionCost : ℕ) + (initialization validation : Polynomial ℕ) : Polynomial ℕ := + Bounds.circuitBitsPolynomial (WitnessEncoding.freeInputPolynomial q) + (gatesPolynomial p q pushes controlBits alphabetBits expressionCost initialization validation) + +def machineGatesPolynomial (p q : Polynomial ℕ) + (pushes controlBits alphabetBits expressionCost : ℕ) : Polynomial ℕ := + gatesPolynomial p q pushes controlBits alphabetBits expressionCost + (initializationPolynomial q) (validationPolynomial q) + +def machineBitsPolynomial (p q : Polynomial ℕ) + (pushes controlBits alphabetBits expressionCost : ℕ) : Polynomial ℕ := + bitsPolynomial p q pushes controlBits alphabetBits expressionCost + (initializationPolynomial q) (validationPolynomial q) + +@[simp] theorem machineGatesPolynomial_eval (p q : Polynomial ℕ) + (pushes controlBits alphabetBits expressionCost n : ℕ) : + (machineGatesPolynomial p q pushes controlBits alphabetBits expressionCost).eval n = + (Bounds.configurationWidthPolynomial p q pushes controlBits alphabetBits).eval n * + (8 * (q.eval n + 1) + 15) + 12 * (q.eval n + 1) ^ 2 + + (Bounds.horizonPolynomial p q).eval n * + (((Bounds.configurationWidthPolynomial p q pushes controlBits alphabetBits).eval n + 1) * + expressionCost) + + (3 * (Bounds.configurationWidthPolynomial p q pushes controlBits alphabetBits).eval n + 4) := by + simp only [machineGatesPolynomial, gatesPolynomial_eval, + initializationPolynomial_eval, validationPolynomial_eval] + +theorem toFormula_bits_le (circuit : Circuit) (p q : Polynomial ℕ) + (pushes controlBits alphabetBits expressionCost : ℕ) + (initialization validation : Polynomial ℕ) (n : ℕ) + (hi : circuit.inputs ≤ 2 * q.eval n + 1) + (hg : circuit.gates.length ≤ + (Bounds.configurationWidthPolynomial p q pushes controlBits alphabetBits).eval n * + initialization.eval n + validation.eval n + + (Bounds.horizonPolynomial p q).eval n * + (((Bounds.configurationWidthPolynomial p q pushes controlBits alphabetBits).eval n + 1) * + expressionCost) + + (3 * (Bounds.configurationWidthPolynomial p q pushes controlBits alphabetBits).eval n + 4)) : + (formulaBits circuit.toFormula).length ≤ + (bitsPolynomial p q pushes controlBits alphabetBits expressionCost initialization validation).eval n := by + apply Bounds.toFormula_bits_length_le_polynomial + · simpa only [WitnessEncoding.freeInputPolynomial_eval] using hi + · simpa only [gatesPolynomial_eval] using hg + +theorem toFormula_bits_le_machinePolynomial (circuit : Circuit) (p q : Polynomial ℕ) + (pushes controlBits alphabetBits expressionCost n : ℕ) + (hi : circuit.inputs ≤ 2 * q.eval n + 1) + (hg : circuit.gates.length ≤ + (machineGatesPolynomial p q pushes controlBits alphabetBits expressionCost).eval n) : + (formulaBits circuit.toFormula).length ≤ + (machineBitsPolynomial p q pushes controlBits alphabetBits expressionCost).eval n := by + apply Bounds.toFormula_bits_length_le_polynomial + · simpa only [WitnessEncoding.freeInputPolynomial_eval] using hi + · exact hg + +end UniqueGamesTheorem.Foundations.Complexity.CookLevin.VerifierBounds + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Main.lean b/lean/OAI/Computability/PerfectCompleteness/Main.lean new file mode 100644 index 0000000000000000000000000000000000000000..7528c382cdba29c525d629974a05a1bbfdfedca8 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Main.lean @@ -0,0 +1,18 @@ +import OAI.Computability.PerfectCompleteness.Construction.LocalCompletionSerializedOutput +import OAI.Computability.PerfectCompleteness.Construction.MixedSourceLocalOddLists +import OAI.Computability.PerfectCompleteness.Decoding.CanonicalBucketCollision +import OAI.Computability.PerfectCompleteness.Decoding.FixedSourceProjectionComparison +import OAI.Computability.PerfectCompleteness.Decoding.UpperScalarCutComparison +import OAI.Computability.PerfectCompleteness.Foundations.DummyEliminationWeighted +import OAI.Computability.PerfectCompleteness.Foundations.ProjectedPrefixConditional +import OAI.Computability.PerfectCompleteness.Foundations.SourcePhysicalCallExtension +import OAI.Computability.PerfectCompleteness.Foundations.SourcePrefixComparison +import OAI.Computability.PerfectCompleteness.Foundations.WholeArrayComposition +import OAI.Computability.PerfectCompleteness.Machines.BinaryPairMachine +import OAI.Computability.PerfectCompleteness.Machines.DescriptorKeyMachine +import OAI.Computability.PerfectCompleteness.Machines.NormalizedTargetProducer +import OAI.Computability.PerfectCompleteness.Reduction.CompletedOccurrenceOrder +import OAI.Computability.PerfectCompleteness.Repetition.AmplifiedCleanRateLemmas +import OAI.Computability.PerfectCompleteness.Sampling.HierarchicalArrayLaw +import OAI.Computability.PerfectCompleteness.Sampling.OriginalUsefulPairLaw +import OAI.Computability.PerfectCompleteness.Theorem11 diff --git a/lean/OAI/Computability/PerfectCompleteness/Model.lean b/lean/OAI/Computability/PerfectCompleteness/Model.lean new file mode 100644 index 0000000000000000000000000000000000000000..16dc06a18059444afdd8c4a87bd50aaf8625e5cf --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Model.lean @@ -0,0 +1,160 @@ +import Mathlib +import OAI.Computability.UniqueGames.Model + +namespace OAI + +namespace PerfectCompleteness.BinaryFormula + +structure Literal where + name : Nat + positive : Bool + deriving DecidableEq + +def Literal.eval (literal : Literal) (assignment : Nat → Bool) : Bool := + if literal.positive then assignment literal.name else !(assignment literal.name) + +abbrev Clause := Vector Literal 3 + +def Clause.eval (clause : Clause) (assignment : Nat → Bool) : Bool := + (clause[0].eval assignment || clause[1].eval assignment) || clause[2].eval assignment + +structure Formula where + clauses : List Clause + +def Formula.Satisfiable (F : Formula) : Prop := + ∃ assignment : Nat → Bool, ∀ clause ∈ F.clauses, clause.eval assignment = true + +end PerfectCompleteness.BinaryFormula + +namespace PerfectCompleteness.BinaryEncoding + +open PerfectCompleteness.BinaryFormula + +def bitsValue : List Bool → Nat + | [] => 0 + | b :: bits => Nat.bit b (bitsValue bits) + +def parseFrame : List Bool → Option (List Bool × List Bool) + | false :: rest => some ([], rest) + | true :: b :: rest => do + let (bits, trailing) ← parseFrame rest + return (b :: bits, trailing) + | _ => none + +def parseName (input : List Bool) : Option (Nat × List Bool) := do + let (digits, rest) ← parseFrame input + let name := bitsValue digits + if digits = name.bits then some (name, rest) else none + +def parseLiteral : List Bool → Option (Literal × List Bool) + | sign :: input => do + let (name, rest) ← parseName input + return (⟨name, sign⟩, rest) + | [] => none + +def parseClause (input : List Bool) : Option (Clause × List Bool) := do + let (a, input) ← parseLiteral input + let (b, input) ← parseLiteral input + let (c, rest) ← parseLiteral input + return (#v[a, b, c], rest) + +def parseClauses : Nat → List Bool → Option (List Clause × List Bool) + | 0, _ => none + | _ + 1, false :: rest => some ([], rest) + | fuel + 1, true :: input => do + let (clause, input) ← parseClause input + let (clauses, rest) ← parseClauses fuel input + return (clause :: clauses, rest) + | _ + 1, [] => none + +def decodeFormula (input : List Bool) : Option Formula := do + let (clauses, rest) ← parseClauses (input.length + 1) input + if rest = [] then some ⟨clauses⟩ else none + +end PerfectCompleteness.BinaryEncoding + +namespace PerfectCompleteness.BinaryLanguage + +def language (input : List Bool) : Prop := + ∃ formula, BinaryEncoding.decodeFormula input = some formula ∧ formula.Satisfiable + +end PerfectCompleteness.BinaryLanguage + +namespace PerfectCompleteness + +structure ProjectionTable (q : Nat) where + images : Vector (Fin q) (2 * q) + exactlyTwo : ∀ b : Fin q, + ((List.finRange (2 * q)).filter (fun a => decide (images[a] = b))).length = 2 + +structure Edge (leftVertices rightVertices q : Nat) where + left : Fin leftVertices + right : Fin rightVertices + projection : ProjectionTable q + +structure Instance (q : Nat) where + leftVertices : Nat + rightVertices : Nat + edges : List (Edge leftVertices rightVertices q) + nonempty : edges ≠ [] + +abbrev Labeling {q : Nat} (G : Instance q) := + (Fin G.leftVertices → Fin (2 * q)) × (Fin G.rightVertices → Fin q) + +def Edge.satisfied {l r q : Nat} (e : Edge l r q) + (a : Fin l → Fin (2 * q)) (b : Fin r → Fin q) : Bool := + decide (e.projection.images[a e.left] = b e.right) + +def countSatisfied {l r q : Nat} (a : Fin l → Fin (2 * q)) + (b : Fin r → Fin q) : List (Edge l r q) → Nat + | [] => 0 + | e :: es => (if e.satisfied a b then 1 else 0) + countSatisfied a b es + +end PerfectCompleteness + +namespace PerfectCompleteness.Instance + +def maxSatisfied {q : Nat} (G : Instance q) : Nat := + Finset.univ.sup (fun s : Labeling G => countSatisfied s.1 s.2 G.edges) + +noncomputable def value {q : Nat} (G : Instance q) : ℝ := + (G.maxSatisfied : ℝ) / G.edges.length + +end PerfectCompleteness.Instance + +namespace PerfectCompleteness.Encoding + +open UniqueGamesTheorem.Foundations.Complexity + +def tableWords {q : Nat} (table : ProjectionTable q) : List Nat := + table.images.toList.map Fin.val + +def edgeWords {l r q : Nat} (edge : Edge l r q) : List Nat := + [edge.left.val, edge.right.val] ++ tableWords edge.projection + +def gameWords {q : Nat} (game : Instance q) : List Nat := + [game.leftVertices, game.rightVertices, q, game.edges.length] ++ + game.edges.flatMap edgeWords + +def gameBits {q : Nat} (game : Instance q) : List Bool := + encodeWords (gameWords game) + +end PerfectCompleteness.Encoding + +namespace PerfectCompleteness + +open Turing UniqueGamesTheorem.Foundations.Complexity + +structure BinaryGapReduction (δ : ℚ) where + alphabet : Nat + alphabet_ge_two : 2 ≤ alphabet + construct : List Bool → Instance alphabet + computation : TM2ComputableInPolyTime (id : List Bool → List Bool) + Encoding.gameBits construct + finiteAlphabet : MachineFiniteAlphabet.FiniteAlphabet computation.tm + completeness : ∀ input, BinaryLanguage.language input → (construct input).value = 1 + soundness : ∀ input, ¬BinaryLanguage.language input → (construct input).value ≤ (δ : ℝ) + +end PerfectCompleteness + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/CanonicalGameLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/CanonicalGameLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..2553dfffcbde4f46e43a1f1ed1dfe54fd55ac17f --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/CanonicalGameLemmas.lean @@ -0,0 +1,557 @@ +import OAI.Computability.PerfectCompleteness.Decoding.Projection +import OAI.Computability.PerfectCompleteness.Foundations.KeyFiniteness +import OAI.Computability.PerfectCompleteness.Foundations.LinearEvaluationLemmas +import OAI.Computability.PerfectCompleteness.Foundations.QuotientTableAgreementLemmas +import OAI.Computability.PerfectCompleteness.Reduction.CompletionSoundness +import OAI.Computability.PerfectCompleteness.Reduction.SourceCompleteness +import OAI.Computability.PerfectCompleteness.Reduction.TargetGameLemmas + +namespace OAI + + +namespace PerfectCompleteness.CanonicalGame + +open SourceClause MixedSupport CanonicalKeys BlockQuotient SourceCompleteness +open UniqueGamesTheorem.Foundations.Games CompletionSoundness + +noncomputable section + +variable {v m n : Nat} {E I B : Type*} {V : I → Type*} + [DecidableEq I] [∀ i, AddCommGroup (V i)] [∀ i, Module DirectionQuotient.F2 (V i)] + +structure BlockFamily (clauses : Fin m → NormalizedClause v) (n : Nat) + (E I : Type*) (V : I → Type*) (B : Type*) + [∀ i, AddCommGroup (V i)] [∀ i, Module DirectionQuotient.F2 (V i)] where + presentation : E → Presentation clauses n (JointOutput V B) + selected : E → I + direction : ∀ e, V (selected e) + nonzero : ∀ e, direction e ≠ 0 + +variable {clauses : Fin m → NormalizedClause v} + (F : BlockFamily clauses n E I V B) + +abbrev RightOutput (e : E) := + DirectionQuotient.Space (F.direction e) × (OtherBlocks V (F.selected e) × B) + +def rightPresentation (e : E) : Presentation clauses n (RightOutput F e) := + (F.presentation e).postcompose (projectBlock (F.selected e) (F.direction e)) + +def leftKey (e : E) : Key n := presentationKey .left (F.presentation e) + +def rightKey (e : E) : Key n := presentationKey .right (rightPresentation F e) + +abbrev LeftVertex := ↥(Set.range (leftKey F)) +abbrev RightVertex := ↥(Set.range (rightKey F)) + +def leftAt (e : E) : LeftVertex F := ⟨leftKey F e, ⟨e, rfl⟩⟩ +def rightAt (e : E) : RightVertex F := ⟨rightKey F e, ⟨e, rfl⟩⟩ + +abbrev LeftLabel (q : LeftVertex F) := KeyLabel q.val +abbrev RightLabel (q : RightVertex F) := KeyLabel q.val + +instance leftVertex_finite [Finite E] : Finite (LeftVertex F) := by + apply Finite.of_surjective (leftAt F) + rintro ⟨k, e, rfl⟩ + exact ⟨e, rfl⟩ + +instance rightVertex_finite [Finite E] : Finite (RightVertex F) := by + apply Finite.of_surjective (rightAt F) + rintro ⟨k, e, rfl⟩ + exact ⟨e, rfl⟩ + +instance leftLabel_nonempty (q : LeftVertex F) : Nonempty (LeftLabel F q) := by + rcases q with ⟨k, e, rfl⟩ + exact keyLabel_nonempty .left _ (F.presentation e).joint + +instance rightLabel_nonempty (q : RightVertex F) : Nonempty (RightLabel F q) := by + rcases q with ⟨k, e, rfl⟩ + exact keyLabel_nonempty .right _ (rightPresentation F e).joint + +def edge (e : E) (P : LeftLabel F (leftAt F e)) : RightLabel F (rightAt F e) := + CanonicalEdges.coarsen + (SourceKeys.slot clauses ∘ (F.presentation e).endpoints) (F.presentation e).joint + (projectBlock (F.selected e) (F.direction e)) P + +theorem edge_at_most_two [Finite I] [∀ i, Finite (V i)] [Finite B] + (e : E) (Q : RightLabel F (rightAt F e)) : + Nat.card {P : LeftLabel F (leftAt F e) // edge F e P = Q} ≤ 2 := + coarsenBlock_at_most_two + (SourceKeys.slot clauses ∘ (F.presentation e).endpoints) (F.presentation e).joint + (F.selected e) (F.direction e) (F.nonzero e) Q + +def game [Fintype E] (μ : FiniteDistribution E) : + LegalProjectionGame E (LeftVertex F) (RightVertex F) (LeftLabel F) (RightLabel F) where + occurrences := μ + left := leftAt F + right := rightAt F + projection := edge F + +def leftAmbientVertex (q : LeftVertex F) : + SourceCompleteness.Vertex .left clauses n (JointOutput V B) := + ⟨q.val, by + obtain ⟨e, he⟩ := q.property + exact ⟨F.presentation e, he⟩⟩ + +def rightAmbientVertex (q : RightVertex F) : + SourceCompleteness.Vertex .right clauses n (RightOutput F q.property.choose) := + ⟨q.val, ⟨rightPresentation F q.property.choose, q.property.choose_spec⟩⟩ + +def leftStrategy (assignment : Fin v → Bool) + (hsat : ∀ c, (clauses c).clause.eval assignment = true) (q : LeftVertex F) : LeftLabel F q := + SourceCompleteness.strategy assignment hsat (leftAmbientVertex F q) + +def rightStrategy (assignment : Fin v → Bool) + (hsat : ∀ c, (clauses c).clause.eval assignment = true) (q : RightVertex F) : RightLabel F q := + SourceCompleteness.strategy assignment hsat (rightAmbientVertex F q) + +omit [DecidableEq I] in +theorem leftStrategy_at (assignment : Fin v → Bool) + (hsat : ∀ c, (clauses c).clause.eval assignment = true) (e : E) : + leftStrategy F assignment hsat (leftAt F e) = + SourceCompleteness.evaluatedLabel assignment hsat (F.presentation e) := by + apply Subtype.ext + exact SourceCompleteness.strategy_value_eq assignment hsat + (leftAmbientVertex F (leftAt F e)) (F.presentation e) rfl + +theorem rightStrategy_at (assignment : Fin v → Bool) + (hsat : ∀ c, (clauses c).clause.eval assignment = true) (e : E) : + rightStrategy F assignment hsat (rightAt F e) = + SourceCompleteness.evaluatedLabel assignment hsat (rightPresentation F e) := by + apply Subtype.ext + exact SourceCompleteness.strategy_value_eq assignment hsat + (rightAmbientVertex F (rightAt F e)) (rightPresentation F e) rfl + +def satisfyingStrategy (assignment : Fin v → Bool) + (hsat : ∀ c, (clauses c).clause.eval assignment = true) : + LegalStrategy (LeftLabel F) (RightLabel F) := + ⟨leftStrategy F assignment hsat, rightStrategy F assignment hsat⟩ + +theorem edge_strategy (assignment : Fin v → Bool) + (hsat : ∀ c, (clauses c).clause.eval assignment = true) (e : E) : + edge F e (leftStrategy F assignment hsat (leftAt F e)) = + rightStrategy F assignment hsat (rightAt F e) := by + apply Subtype.ext + have hc := CanonicalEdges.coarsen_evaluateLabel + (SourceKeys.slot clauses ∘ (F.presentation e).endpoints) (F.presentation e).joint + (projectBlock (F.selected e) (F.direction e)) + (SourceKeys.realizingAssignment clauses assignment hsat (F.presentation e).endpoints) + calc + (edge F e (leftStrategy F assignment hsat (leftAt F e))).val = + (edge F e (SourceCompleteness.evaluatedLabel assignment hsat (F.presentation e))).val := + congrArg (fun P : LeftLabel F (leftAt F e) => (edge F e P).val) + (leftStrategy_at F assignment hsat e) + _ = (SourceCompleteness.evaluatedLabel assignment hsat (rightPresentation F e)).val := + congrArg (fun P : RightLabel F (rightAt F e) => P.val) hc + _ = (rightStrategy F assignment hsat (rightAt F e)).val := + congrArg (fun P : RightLabel F (rightAt F e) => P.val) + (rightStrategy_at F assignment hsat e).symm + +theorem success_satisfyingStrategy [Fintype E] (μ : FiniteDistribution E) + (assignment : Fin v → Bool) (hsat : ∀ c, (clauses c).clause.eval assignment = true) : + (game F μ).success (satisfyingStrategy F assignment hsat) = 1 := by + have hw : (game F μ).wins (satisfyingStrategy F assignment hsat) = fun _ => true := by + funext e + change @decide (edge F e (leftStrategy F assignment hsat (leftAt F e)) = + rightStrategy F assignment hsat (rightAt F e)) (Classical.propDecidable _) = true + exact (@decide_eq_true_iff _ (Classical.propDecidable _)).mpr + (edge_strategy F assignment hsat e) + change μ.probability ((game F μ).wins (satisfyingStrategy F assignment hsat)) = 1 + rw [hw] + exact μ.probability_true + +end + +end PerfectCompleteness.CanonicalGame + + +namespace PerfectCompleteness.CanonicalGameStrategy + +open SourceClause MixedSupport CanonicalKeys BlockQuotient CanonicalGame +open CompletionSoundness +open scoped Classical + +noncomputable section + +variable {v m n : Nat} {E I B : Type*} {V : I → Type*} + [DecidableEq I] [∀ i, AddCommGroup (V i)] [∀ i, Module DirectionQuotient.F2 (V i)] + {clauses : Fin m → NormalizedClause v} (F : BlockFamily clauses n E I V B) + +theorem left_right_disjoint : Disjoint (Set.range (leftKey F)) (Set.range (rightKey F)) := by + apply Set.disjoint_left.mpr + rintro k ⟨e, he⟩ ⟨e', he'⟩ + have hs : Side.left = Side.right := + congrArg (fun q : Key n => q.side) (he.trans he'.symm) + cases hs + +def support : Set (Key n) := Set.range (leftKey F) ∪ Set.range (rightKey F) + +def onSupport (s : LegalStrategy (LeftLabel F) (RightLabel F)) + (k : ↥(support F)) : KeyLabel k.val := + if h : k.val ∈ Set.range (leftKey F) then s.1 ⟨k.val, h⟩ + else s.2 ⟨k.val, k.property.resolve_left h⟩ + +def extend (s : LegalStrategy (LeftLabel F) (RightLabel F)) : KeyStrategy.Strategy n := + KeyStrategy.extend (support F) (onSupport F s) + +theorem extend_left_val (s : LegalStrategy (LeftLabel F) (RightLabel F)) + (q : LeftVertex F) (k : KeyStrategy.NonemptyKey n) (hk : k.val = q.val) : + (extend F s k).val = (s.1 q).val := by + have hL : k.val ∈ Set.range (leftKey F) := by + rw [hk] + exact q.property + have h := KeyStrategy.extend_val (support F) (onSupport F s) k (Or.inl hL) + have hs : (onSupport F s ⟨k.val, Or.inl hL⟩).val = + (s.1 ⟨k.val, hL⟩).val := by + simp only [onSupport, dite_eq_left hL] + exact h.trans (hs.trans (congrArg (fun q : LeftVertex F => (s.1 q).val) (Subtype.ext hk))) + +theorem extend_right_val (s : LegalStrategy (LeftLabel F) (RightLabel F)) + (q : RightVertex F) (k : KeyStrategy.NonemptyKey n) (hk : k.val = q.val) : + (extend F s k).val = (s.2 q).val := by + have hR : k.val ∈ Set.range (rightKey F) := by + rw [hk] + exact q.property + have hL : k.val ∉ Set.range (leftKey F) := by + intro h + exact (Set.disjoint_left.mp (left_right_disjoint F)) h hR + have h := KeyStrategy.extend_val (support F) (onSupport F s) k (Or.inr hR) + have hs : (onSupport F s ⟨k.val, Or.inr hR⟩).val = + (s.2 ⟨k.val, hR⟩).val := by + simp only [onSupport, dite_eq_right hL] + exact h.trans (hs.trans (congrArg (fun q : RightVertex F => (s.2 q).val) (Subtype.ext hk))) + +theorem label_extend_left (s : LegalStrategy (LeftLabel F) (RightLabel F)) (e : E) : + KeyStrategy.label (extend F s) .left + (SourceKeys.slot clauses ∘ (F.presentation e).endpoints) (F.presentation e).joint = + s.1 (leftAt F e) := by + apply Subtype.ext + exact extend_left_val F s (leftAt F e) _ rfl + +theorem label_extend_right (s : LegalStrategy (LeftLabel F) (RightLabel F)) (e : E) : + KeyStrategy.label (extend F s) .right + (SourceKeys.slot clauses ∘ (rightPresentation F e).endpoints) + (rightPresentation F e).joint = s.2 (rightAt F e) := by + apply Subtype.ext + exact extend_right_val F s (rightAt F e) _ rfl + +theorem response_extend_left (s : LegalStrategy (LeftLabel F) (RightLabel F)) (e : E) : + KeyStrategy.response (extend F s) .left + (SourceKeys.slot clauses ∘ (F.presentation e).endpoints) (F.presentation e).joint = + restore (SourceKeys.slot clauses ∘ (F.presentation e).endpoints) + (F.presentation e).joint (s.1 (leftAt F e)) := + congrArg (restore (SourceKeys.slot clauses ∘ (F.presentation e).endpoints) + (F.presentation e).joint) (label_extend_left F s e) + +theorem response_extend_right (s : LegalStrategy (LeftLabel F) (RightLabel F)) (e : E) : + KeyStrategy.response (extend F s) .right + (SourceKeys.slot clauses ∘ (rightPresentation F e).endpoints) + (rightPresentation F e).joint = + restore (SourceKeys.slot clauses ∘ (rightPresentation F e).endpoints) + (rightPresentation F e).joint (s.2 (rightAt F e)) := + congrArg (restore (SourceKeys.slot clauses ∘ (rightPresentation F e).endpoints) + (rightPresentation F e).joint) (label_extend_right F s e) + +theorem accepts_extend_iff (s : LegalStrategy (LeftLabel F) (RightLabel F)) (e : E) : + CanonicalEdges.coarsen + (SourceKeys.slot clauses ∘ (F.presentation e).endpoints) (F.presentation e).joint + (projectBlock (F.selected e) (F.direction e)) + (KeyStrategy.label (extend F s) .left + (SourceKeys.slot clauses ∘ (F.presentation e).endpoints) (F.presentation e).joint) = + KeyStrategy.label (extend F s) .right + (SourceKeys.slot clauses ∘ (rightPresentation F e).endpoints) + (rightPresentation F e).joint ↔ + edge F e (s.1 (leftAt F e)) = s.2 (rightAt F e) := by + rw [label_extend_left F s e, label_extend_right F s e] + rfl + +end + +end PerfectCompleteness.CanonicalGameStrategy + + +namespace PerfectCompleteness.CompletionRounding + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games +open WeightRounding CompletionSoundness +open CompletionSoundness.LegalProjectionGame + +noncomputable section + +abbrev SeededOccurrences {m : Nat} (n : Fin m → Nat) := Σ e : Fin m, Fin (n e) + +theorem seeded_weights_total {m : Nat} (w : PositiveWeights m) + (n : Fin m → Nat) (hn : ∀ e, 0 < n e) : + (∑ s : SeededOccurrences n, w.weight s.1 / (n s.1 : ℚ)) = 1 := by + rw [Fintype.sum_sigma] + calc + _ = ∑ e, w.weight e := by + apply Finset.sum_congr rfl + intro e _ + change (∑ seed : Fin (n e), w.weight e / (n e : ℚ)) = w.weight e + have hne : (n e : ℚ) ≠ 0 := Nat.cast_ne_zero.mpr (Nat.ne_of_gt (hn e)) + simp only [Finset.sum_const, Finset.card_univ, Fintype.card_fin, nsmul_eq_mul] + exact mul_div_cancel₀ (w.weight e) hne + _ = 1 := w.total + +def enumeratedWeights {m : Nat} (w : PositiveWeights m) + (n : Fin m → Nat) (hn : ∀ e, 0 < n e) + (enum : SeededOccurrences n ≃ Fin (Fintype.card (SeededOccurrences n))) : + PositiveWeights (Fintype.card (SeededOccurrences n)) where + weight i := w.weight (enum.symm i).1 / (n (enum.symm i).1 : ℚ) + positive i := div_pos (w.positive _) (by exact_mod_cast hn (enum.symm i).1) + total := (enum.symm.sum_comp + (fun s : SeededOccurrences n => w.weight s.1 / (n s.1 : ℚ))).trans + (seeded_weights_total w n hn) + +theorem probability_one_forall_of_positive {Ω : Type*} [Fintype Ω] + (μ : FiniteDistribution Ω) (hpositive : ∀ x, 0 < μ.weight x) + (event : Ω → Bool) (hone : μ.probability event = 1) : ∀ x, event x = true := by + intro x + by_contra hx + have hle (y : Ω) : (if event y then μ.weight y else 0) ≤ μ.weight y := by + split + · exact le_rfl + · exact μ.nonnegative y + have hlt : μ.probability event < ∑ y, μ.weight y := by + unfold FiniteDistribution.probability + apply Finset.sum_lt_sum (fun y _ => hle y) + refine ⟨x, Finset.mem_univ _, ?_⟩ + simpa only [ite_eq_right hx] using hpositive x + have hbad : (1 : ℝ) < 1 := by simpa only [hone, μ.normalized] using hlt + exact (lt_irrefl (1 : ℝ)) hbad + +variable {m l r q : Nat} {L : Fin l → Type*} {R : Fin r → Type*} + [∀ x, Fintype (L x)] + {G : LegalProjectionGame (Fin m) (Fin l) (Fin r) L R} + {legalL : ∀ x, L x ↪ Fin (2 * q)} {legalR : ∀ y, R y ↪ Fin q} + +abbrev CompletedOccurrence (F : G.CompletionFamily legalL legalR) := + SeededOccurrences F.size + +def enumeration (F : G.CompletionFamily legalL legalR) : + CompletedOccurrence F ≃ Fin (Fintype.card (CompletedOccurrence F)) := + Fintype.equivFin (CompletedOccurrence F) + +def weights (w : PositiveWeights m) (F : G.CompletionFamily legalL legalR) : + PositiveWeights (Fintype.card (CompletedOccurrence F)) := + enumeratedWeights w F.size F.positive (enumeration F) + +def entries (F : G.CompletionFamily legalL legalR) + (i : Fin (Fintype.card (CompletedOccurrence F))) : Edge l r q := + let es := (enumeration F).symm i + { left := G.left es.1 + right := G.right es.1 + projection := ProjectionTable.ofMap (F.map es.1 es.2) (by + simpa only [← Nat.card_eq_fintype_card] using F.exact_two es.1 es.2) } + +theorem entries_satisfied (F : G.CompletionFamily legalL legalR) + (i : Fin (Fintype.card (CompletedOccurrence F))) + (a : Fin l → Fin (2 * q)) (b : Fin r → Fin q) : + (entries F i).satisfied a b = F.game.wins (a, b) ((enumeration F).symm i) := by + simp only [entries, Edge.satisfied, ProjectionTable.ofMap_apply, + CompletionFamily.game, completedGame, OccurrenceGame.wins, OccurrenceGame.ofProjection] + exact decide_eq_decide.mpr Iff.rfl + +theorem weight_cast (w : PositiveWeights m) (F : G.CompletionFamily legalL legalR) + (hweights : ∀ e, G.occurrences.weight e = (w.weight e : ℝ)) + (i : Fin (Fintype.card (CompletedOccurrence F))) : + ((weights w F).weight i : ℝ) = + (sigmaLaw G.occurrences F.seedLaw).weight ((enumeration F).symm i) := by + simp only [weights, enumeratedWeights, sigmaLaw, CompletionFamily.seedLaw, + FiniteDistribution.uniform, Fintype.card_fin, hweights, div_eq_mul_inv, + Rat.cast_mul, Rat.cast_inv, Rat.cast_natCast, one_mul] + +theorem weightedSuccess_eq_completed (w : PositiveWeights m) + (F : G.CompletionFamily legalL legalR) + (hweights : ∀ e, G.occurrences.weight e = (w.weight e : ℝ)) + (a : Fin l → Fin (2 * q)) (b : Fin r → Fin q) : + (RoundedTarget.weightedSuccess (weights w F) (entries F) a b : ℝ) = + F.game.success (a, b) := by + unfold RoundedTarget.weightedSuccess PositiveWeights.weightedAcceptance + rw [Rat.cast_sum] + calc + _ = ∑ i, if F.game.wins (a, b) ((enumeration F).symm i) then + (sigmaLaw G.occurrences F.seedLaw).weight ((enumeration F).symm i) else 0 := by + apply Finset.sum_congr rfl + intro i _ + rw [← entries_satisfied F i a b] + by_cases hi : (entries F i).satisfied a b = true + · simp only [ite_eq_left hi] + exact weight_cast w F hweights i + · simp only [ite_eq_right hi, Rat.cast_zero] + _ = ∑ es : CompletedOccurrence F, if F.game.wins (a, b) es then + (sigmaLaw G.occurrences F.seedLaw).weight es else 0 := by + simpa only using (enumeration F).symm.sum_comp + (fun es : CompletedOccurrence F => if F.game.wins (a, b) es = true then + (sigmaLaw G.occurrences F.seedLaw).weight es else (0 : ℝ)) + _ = F.game.success (a, b) := rfl + +def output (w : PositiveWeights m) (F : G.CompletionFamily legalL legalR) + (δ : ℚ) (hδ : 0 < δ) : Instance q := + RoundedTarget.paper (weights w F) (entries F) δ hδ + +theorem support_card (F : G.CompletionFamily legalL legalR) : + Fintype.card (CompletedOccurrence F) = ∑ e, F.size e := by + simp only [CompletedOccurrence, SeededOccurrences, Fintype.card_sigma, Fintype.card_fin] + +theorem output_edge_count (w : PositiveWeights m) (F : G.CompletionFamily legalL legalR) + (δ : ℚ) (hδ : 0 < δ) : + (output w F δ hδ).edges.length = paperScale (∑ e, F.size e) δ := by + rw [output, RoundedTarget.paper_edge_length, support_card] + +theorem output_edge_count_le (w : PositiveWeights m) (F : G.CompletionFamily legalL legalR) + (δ : ℚ) (hδ : 0 < δ) : + (output w F δ hδ).edges.length ≤ ⌈(3 : ℚ) / δ⌉₊ * ∑ e, F.size e := by + simpa only [output, support_card] using + RoundedTarget.paper_edge_length_le_linear (weights w F) (entries F) δ hδ + +variable [∀ y, Fintype (R y)] [∀ x, Nonempty (L x)] [∀ y, Nonempty (R y)] + +theorem output_value_le (w : PositiveWeights m) (F : G.CompletionFamily legalL legalR) + (hweights : ∀ e, G.occurrences.weight e = (w.weight e : ℝ)) + (δ : ℚ) (hδ : 0 < δ) (hq : 0 < q) : + (output w F δ hδ).value ≤ + G.value + G.occurrences.expectation + (fun e => 2 / (2 * q - Fintype.card (L (G.left e)) : Nat)) + (δ : ℝ) / 3 := by + let : Nonempty (Fin q) := ⟨⟨0, hq⟩⟩ + let : Nonempty (Fin (2 * q)) := ⟨⟨0, Nat.mul_pos (by decide) hq⟩⟩ + have hround := RoundedTarget.paper_value_le (weights w F) (entries F) δ hδ hq + F.game.value (fun a b => by + rw [weightedSuccess_eq_completed w F hweights] + exact F.game.success_le_value (a, b)) + have hcomplete := F.value_le + simp only [Fintype.card_fin] at hcomplete + exact hround.trans (add_le_add hcomplete (le_refl _)) + +theorem output_value_le_of_residual_bound (w : PositiveWeights m) + (F : G.CompletionFamily legalL legalR) + (hweights : ∀ e, G.occurrences.weight e = (w.weight e : ℝ)) + (δ : ℚ) (hδ : 0 < δ) (hq : 0 < q) (η : ℝ) + (hη : ∀ e, 2 / (2 * q - Fintype.card (L (G.left e)) : Nat) ≤ η) : + (output w F δ hδ).value ≤ G.value + η + (δ : ℝ) / 3 := by + let : Nonempty (Fin q) := ⟨⟨0, hq⟩⟩ + let : Nonempty (Fin (2 * q)) := ⟨⟨0, Nat.mul_pos (by decide) hq⟩⟩ + have hround := RoundedTarget.paper_value_le (weights w F) (entries F) δ hδ hq + F.game.value (fun a b => by + rw [weightedSuccess_eq_completed w F hweights] + exact F.game.success_le_value (a, b)) + have hcomplete := F.value_le_of_bound η (by simpa only [Fintype.card_fin] using hη) + exact hround.trans (add_le_add hcomplete (le_refl _)) + +theorem output_value_eq_one (w : PositiveWeights m) (F : G.CompletionFamily legalL legalR) + (hweights : ∀ e, G.occurrences.weight e = (w.weight e : ℝ)) + (δ : ℚ) (hδ : 0 < δ) (hq : 0 < q) (hcomplete : G.value = 1) : + (output w F δ hδ).value = 1 := by + obtain ⟨s, hs⟩ := G.exists_optimal_strategy + have hpositive : ∀ e, 0 < G.occurrences.weight e := by + intro e + rw [hweights] + exact_mod_cast w.positive e + have hwins := probability_one_forall_of_positive G.occurrences hpositive + (G.wins s) (hs.trans hcomplete) + apply RoundedTarget.paper_complete_value_eq_one (weights w F) (entries F) δ hδ hq + refine ⟨liftStrategy legalL legalR s, ?_⟩ + intro i + rw [entries_satisfied] + let es : CompletedOccurrence F := (enumeration F).symm i + simp only [CompletionFamily.game, completedGame, OccurrenceGame.wins, + OccurrenceGame.ofProjection, liftStrategy] + apply (@decide_eq_true_iff _ (Classical.propDecidable _)).mpr + change F.map es.1 es.2 (legalL (G.left es.1) (s.1 (G.left es.1))) = + legalR (G.right es.1) (s.2 (G.right es.1)) + rw [F.agrees] + exact congrArg (legalR (G.right es.1)) (of_decide_eq_true (hwins es.1)) + + +end +end PerfectCompleteness.CompletionRounding + + +noncomputable section + +open scoped Classical + +namespace PerfectCompleteness.CompletionProbability + +variable {L A B : Type*} + +theorem exists_completion_sampler_bounded [Fintype L] [Fintype A] [Fintype B] + (legal : L ↪ A) (p : L → B) + (hsmall : ∀ b, Fintype.card {l : L // p l = b} ≤ 2) + (hcard : Fintype.card A = 2 * Fintype.card B) : + ∃ n : ℕ, 0 < n ∧ n ≤ max 1 (Fintype.card A - Fintype.card L) ∧ + ∃ sampler : Fin n → A → B, + (∀ seed l, sampler seed (legal l) = p l) ∧ + (∀ seed b, Fintype.card {a : A // sampler seed a = b} = 2) ∧ + ∀ (a : Illegal legal) (b : B), + uniformProbability (fun seed => sampler seed a.val = b) = + ((2 - Fintype.card {l : L // p l = b} : ℕ) : ℝ) / + (Fintype.card A - Fintype.card L : ℕ) ∧ + uniformProbability (fun seed => sampler seed a.val = b) ≤ + 2 / (Fintype.card A - Fintype.card L : ℕ) := by + obtain ⟨pHat, hext, hexact⟩ := + Completion.exists_exact_two_completion legal p hsmall hcard + by_cases hz : Fintype.card (Illegal legal) = 0 + · refine ⟨1, Nat.zero_lt_one, + le_max_left 1 (Fintype.card A - Fintype.card L), (fun _ => pHat), ?_, ?_, ?_⟩ + · intro seed l + exact hext l + · intro seed b + exact hexact b + · intro a b + have hp : 0 < Fintype.card (Illegal legal) := Fintype.card_pos_iff.mpr ⟨a⟩ + exact False.elim (Nat.ne_of_gt hp hz) + · let : NeZero (Fintype.card (Illegal legal)) := ⟨hz⟩ + let enum := Fintype.equivFin (Illegal legal) + refine ⟨Fintype.card (Illegal legal), Nat.pos_of_ne_zero hz, + (card_illegal legal).le.trans + (le_max_right 1 (Fintype.card A - Fintype.card L)), + sample legal pHat enum, ?_, ?_, ?_⟩ + · intro seed l + simpa only [sample_legal] using hext l + · intro seed b + exact sample_exact_two legal pHat enum hexact seed b + · intro a b + exact ⟨sample_probability_residual legal p pHat enum hext hexact a b, + sample_probability_le legal pHat enum hexact a b⟩ + +end PerfectCompleteness.CompletionProbability + +namespace PerfectCompleteness.CompletionSoundness.LegalProjectionGame + +open CompletionProbability + +variable {E Q₁ Q₂ : Type*} {L : Q₁ → Type*} {R : Q₂ → Type*} + [Fintype E] [Fintype Q₁] [Fintype Q₂] [∀ x, Fintype (L x)] + {A B : Type*} [Fintype A] [Fintype B] + (G : LegalProjectionGame E Q₁ Q₂ L R) + +omit [Fintype Q₁] [Fintype Q₂] in +theorem exists_completionFamily_bounded + (legalL : ∀ x, L x ↪ A) (legalR : ∀ y, R y ↪ B) + (hsmall : ∀ e b, Fintype.card {l : L (G.left e) // G.projection e l = b} ≤ 2) + (hcard : Fintype.card A = 2 * Fintype.card B) : + ∃ F : G.CompletionFamily legalL legalR, + ∀ e, F.size e ≤ max 1 (Fintype.card A - Fintype.card (L (G.left e))) := by + have hexists (e : E) := exists_completion_sampler_bounded (legalL (G.left e)) + (fun l => legalR (G.right e) (G.projection e l)) + (embedded_fiber_le_two (legalR (G.right e)) (G.projection e) (hsmall e)) hcard + choose n hn hsize sampler hext hexact hprob using hexists + let F : G.CompletionFamily legalL legalR := { + size := n + positive := hn + map := sampler + agrees := hext + exact_two := hexact + illegal_probability := by + intro e a b + simpa only [← Nat.card_eq_fintype_card] using (hprob e a b).2 + } + exact ⟨F, hsize⟩ + +end PerfectCompleteness.CompletionSoundness.LegalProjectionGame + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/CanonicalNamedGame.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/CanonicalNamedGame.lean new file mode 100644 index 0000000000000000000000000000000000000000..091a7e26b0eea3105d434f7e760a6b469bbe38a7 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/CanonicalNamedGame.lean @@ -0,0 +1,175 @@ +import OAI.Computability.PerfectCompleteness.Construction.CanonicalLocalCompletion +import OAI.Computability.PerfectCompleteness.Foundations.CanonicalVertexNames +import OAI.Computability.PerfectCompleteness.Foundations.OccurrenceStochasticLemmas + +namespace OAI + + +namespace PerfectCompleteness.CanonicalNamedGame + +open CanonicalGame CanonicalKeys +open UniqueGamesTheorem.Foundations.Games + +noncomputable section + +variable {v m n : Nat} {E I B : Type*} {V : I → Type*} + [DecidableEq I] [∀ i, AddCommGroup (V i)] + [∀ i, Module DirectionQuotient.F2 (V i)] + {clauses : Fin m → SourceClause.NormalizedClause v} + (F : BlockFamily clauses n E I V B) + (occurrences : List E) (coverage : ∀ e, e ∈ occurrences) + +def leftKeys : List (Key n) := occurrences.map (leftKey F) + +def rightKeys : List (Key n) := occurrences.map (rightKey F) + +omit [DecidableEq I] in +@[simp] theorem leftKeys_length : (leftKeys F occurrences).length = occurrences.length := by + simp only [leftKeys, List.length_map] + +@[simp] theorem rightKeys_length : (rightKeys F occurrences).length = occurrences.length := by + simp only [rightKeys, List.length_map] + +omit [DecidableEq I] in +include coverage in +theorem left_mem (x : LeftVertex F) : x.val ∈ leftKeys F occurrences := by + obtain ⟨e, he⟩ := x.property + exact List.mem_map.mpr ⟨e, coverage e, he⟩ + +include coverage in +theorem right_mem (y : RightVertex F) : y.val ∈ rightKeys F occurrences := by + obtain ⟨e, he⟩ := y.property + exact List.mem_map.mpr ⟨e, coverage e, he⟩ + +def leftEmbedding : LeftVertex F ↪ Fin occurrences.length where + toFun x := + let named := CanonicalVertexNames.name (leftKeys F occurrences) x.val + (left_mem F occurrences coverage x) + ⟨named.val, by simpa only [leftKeys_length] using named.isLt⟩ + inj' := by + intro x y h + apply Subtype.ext + apply (CanonicalVertexNames.name_eq_iff (leftKeys F occurrences) x.val y.val + (left_mem F occurrences coverage x) (left_mem F occurrences coverage y)).mp + apply Fin.ext + exact congrArg (fun i : Fin occurrences.length => i.val) h + +def rightEmbedding : RightVertex F ↪ Fin occurrences.length where + toFun y := + let named := CanonicalVertexNames.name (rightKeys F occurrences) y.val + (right_mem F occurrences coverage y) + ⟨named.val, by simpa only [rightKeys_length] using named.isLt⟩ + inj' := by + intro x y h + apply Subtype.ext + apply (CanonicalVertexNames.name_eq_iff (rightKeys F occurrences) x.val y.val + (right_mem F occurrences coverage x) (right_mem F occurrences coverage y)).mp + apply Fin.ext + exact congrArg (fun i : Fin occurrences.length => i.val) h + +omit [DecidableEq I] in +@[simp] theorem leftEmbedding_at_val (e : E) : + (leftEmbedding F occurrences coverage (leftAt F e)).val = + (BinaryNameSearch.payloads (CanonicalVertexNames.tokens (leftKeys F occurrences))).idxOf + (CanonicalVertexNames.payload (leftKey F e)) := rfl + +@[simp] theorem rightEmbedding_at_val (e : E) : + (rightEmbedding F occurrences coverage (rightAt F e)).val = + (BinaryNameSearch.payloads (CanonicalVertexNames.tokens (rightKeys F occurrences))).idxOf + (CanonicalVertexNames.payload (rightKey F e)) := rfl + +omit [DecidableEq I] in +theorem leftEmbedding_at_eq_iff (e e' : E) : + leftEmbedding F occurrences coverage (leftAt F e) = + leftEmbedding F occurrences coverage (leftAt F e') ↔ leftKey F e = leftKey F e' := by + constructor + · intro h + exact congrArg Subtype.val ((leftEmbedding F occurrences coverage).injective h) + · intro h + exact congrArg (leftEmbedding F occurrences coverage) (Subtype.ext h) + +theorem rightEmbedding_at_eq_iff (e e' : E) : + rightEmbedding F occurrences coverage (rightAt F e) = + rightEmbedding F occurrences coverage (rightAt F e') ↔ rightKey F e = rightKey F e' := by + constructor + · intro h + exact congrArg Subtype.val ((rightEmbedding F occurrences coverage).injective h) + · intro h + exact congrArg (rightEmbedding F occurrences coverage) (Subtype.ext h) + +section CommonAlphabet + +variable {E' A₁ A₂ : Type*} [Fintype E'] + [Fintype (LeftVertex F)] [Fintype (RightVertex F)] [Fintype A₁] [Fintype A₂] + +def rename (G : OccurrenceGame E' (LeftVertex F) (RightVertex F) A₁ A₂) : + OccurrenceGame E' (Fin occurrences.length) (Fin occurrences.length) A₁ A₂ := + OccurrenceVertexEmbedding.rename G + (leftEmbedding F occurrences coverage) (rightEmbedding F occurrences coverage) + +@[simp] theorem rename_occurrences + (G : OccurrenceGame E' (LeftVertex F) (RightVertex F) A₁ A₂) : + (rename F occurrences coverage G).occurrences = G.occurrences := rfl + +@[simp] theorem rename_accepts + (G : OccurrenceGame E' (LeftVertex F) (RightVertex F) A₁ A₂) : + (rename F occurrences coverage G).accepts = G.accepts := rfl + +theorem rename_value_eq [Nonempty A₁] [Nonempty A₂] + (G : OccurrenceGame E' (LeftVertex F) (RightVertex F) A₁ A₂) : + (rename F occurrences coverage G).value = G.value := + OccurrenceVertexEmbedding.value_eq G + (leftEmbedding F occurrences coverage) (rightEmbedding F occurrences coverage) + +end CommonAlphabet + + +variable [Finite I] [∀ i, Finite (V i)] [Finite B] + [Fintype E] [Fintype (LeftVertex F)] [Fintype (RightVertex F)] + [∀ x, Fintype (LeftLabel F x)] [∀ y, Fintype (RightLabel F y)] + +local instance rightAlphabet_nonempty (δ : ℚ) : + Nonempty (Fin (CanonicalLocalCompletion.alphabet n δ)) := + ⟨⟨0, CanonicalLocalCompletion.alphabet_positive n δ⟩⟩ + +local instance leftAlphabet_nonempty (δ : ℚ) : + Nonempty (Fin (2 * CanonicalLocalCompletion.alphabet n δ)) := + ⟨⟨0, Nat.mul_pos (by decide) (CanonicalLocalCompletion.alphabet_positive n δ)⟩⟩ + +def completed (μ : FiniteDistribution E) (δ : ℚ) := + rename F occurrences coverage (CanonicalLocalCompletion.family F μ δ).game + +omit [∀ y, Fintype (RightLabel F y)] in +@[simp] theorem completed_left (μ : FiniteDistribution E) (δ : ℚ) + (e : E) (seed : Fin ((CanonicalLocalCompletion.family F μ δ).size e)) : + (completed F occurrences coverage μ δ).left ⟨e, seed⟩ = + leftEmbedding F occurrences coverage (leftAt F e) := rfl + +omit [∀ y, Fintype (RightLabel F y)] in +@[simp] theorem completed_right (μ : FiniteDistribution E) (δ : ℚ) + (e : E) (seed : Fin ((CanonicalLocalCompletion.family F μ δ).size e)) : + (completed F occurrences coverage μ δ).right ⟨e, seed⟩ = + rightEmbedding F occurrences coverage (rightAt F e) := rfl + +omit [∀ y, Fintype (RightLabel F y)] in +theorem completed_value_eq (μ : FiniteDistribution E) (δ : ℚ) : + (completed F occurrences coverage μ δ).value = + (CanonicalLocalCompletion.family F μ δ).game.value := + rename_value_eq F occurrences coverage _ + +theorem completed_value_le (μ : FiniteDistribution E) (δ : ℚ) (hδ : 0 < δ) : + (completed F occurrences coverage μ δ).value ≤ + (CanonicalGame.game F μ).value + (δ : ℝ) / 3 := by + rw [completed_value_eq] + exact CanonicalLocalCompletion.family_value_le F μ δ hδ + +theorem completed_value_of_satisfying (μ : FiniteDistribution E) (δ : ℚ) + (assignment : Fin v → Bool) (hsat : ∀ c, (clauses c).clause.eval assignment = true) : + (completed F occurrences coverage μ δ).value = 1 := by + rw [completed_value_eq] + exact CanonicalLocalCompletion.family_value_of_satisfying F μ δ assignment hsat + +end +end PerfectCompleteness.CanonicalNamedGame + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/CompletedOccurrenceOrder.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/CompletedOccurrenceOrder.lean new file mode 100644 index 0000000000000000000000000000000000000000..238a43c8d440f40dd87b0a69bdf6355839ef09b9 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/CompletedOccurrenceOrder.lean @@ -0,0 +1,148 @@ +import OAI.Computability.PerfectCompleteness.Construction.SourceQuestionOrderLemmas +import OAI.Computability.PerfectCompleteness.Sampling.CompletedSignedLaw + +namespace OAI + +section + +namespace PerfectCompleteness.CompletedOccurrenceOrder + +open MetadataFreeSampler +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +noncomputable section + +variable {branch : Nat → Nat} {n t v m : Nat} + (clauses : Fin m → SourceClause.NormalizedClause v) (rows repeats : Nat → Nat) + [NeZero m] (hn : 0 < n) (hbranch : ∀ k < n, 0 < branch k) + (hrows : ∀ k, 0 < rows (k + 1)) (δ : ℚ) + +local notation "locationCount" => TreeCanonical.locationCount branch n t +local notation "hq" => CanonicalLocalCompletion.alphabet_positive locationCount δ +local notation "large" => CanonicalLocalCompletion.partitionWidth_le_alphabet locationCount δ +local notation "D" => SignedMultiplicity.denominator branch n t rows repeats hn hbranch hrows + (FinitePreliminaryCompletion.alphabet branch n t δ) +local notation "F" => FinitePreliminaryCompletion.blockFamily clauses branch n t rows repeats + +local instance leftVertex_fintype : Fintype (CanonicalGame.LeftVertex F) := Fintype.ofFinite _ +local instance rightVertex_fintype : Fintype (CanonicalGame.RightVertex F) := Fintype.ofFinite _ +local instance leftLabel_fintype (x : CanonicalGame.LeftVertex F) : + Fintype (CanonicalGame.LeftLabel F x) := Fintype.ofFinite _ +local instance rightLabel_fintype (y : CanonicalGame.RightVertex F) : + Fintype (CanonicalGame.RightLabel F y) := Fintype.ofFinite _ + +local notation "C" => + FinitePreliminaryCompletion.actualFamily (t := t) clauses rows repeats hn hbranch hrows δ +local notation "Completed" => CompletedSignedLaw.Completed (t := t) clauses rows repeats hn hbranch hrows δ +local notation "transport" => + Equiv.symm (CompletedSignedLaw.completedEquiv (t := t) clauses rows repeats hn hbranch hrows δ) + +def localOrder (source : PreliminarySampler.Questions branch n t m) : List Completed := + (SignedCompletionSchedule.schedule (branch := branch) (n := n) (t := t) + (rows := rows) (repeats := repeats) hq large hn hbranch hrows + (sourceSigns clauses source)).map (fun outcome => transport ⟨source, outcome⟩) + +def completedOrder : List Completed := + (SourceQuestionOrder.sourceOrder branch n t m).flatMap + (localOrder (t := t) clauses rows repeats hn hbranch hrows δ) + +theorem localOrder_length (source : PreliminarySampler.Questions branch n t m) : + (localOrder (t := t) clauses rows repeats hn hbranch hrows δ source).length = D := by + rw [localOrder, List.length_map, SignedCompletionSchedule.schedule_length] + +theorem completedOrder_length : + (completedOrder (t := t) clauses rows repeats hn hbranch hrows δ).length = + D * m ^ locationCount := by + change (ExactConditionalOutput.output + (SignedCompletionSchedule.count (branch := branch) (n := n) (t := t) + (rows := rows) (repeats := repeats) hq large hn hbranch hrows) (sourceSigns clauses) + (fun source outcome => transport ⟨source, outcome⟩) + (SourceQuestionOrder.sourceOrder branch n t m)).length = _ + rw [ExactConditionalOutput.output_length _ _ _ D + (SignedCompletionSchedule.count_total (branch := branch) (n := n) (t := t) + (rows := rows) (repeats := repeats) hq large hn hbranch hrows), + SourceQuestionOrder.sourceOrder_length] + +theorem completedOrder_nonempty : + completedOrder (t := t) clauses rows repeats hn hbranch hrows δ ≠ [] := by + intro hempty + have h := completedOrder_length (t := t) clauses rows repeats hn hbranch hrows δ + rw [hempty, List.length_nil] at h + exact (Nat.ne_of_gt (Nat.mul_pos + (SignedMultiplicity.denominator_positive branch n t rows repeats hn hbranch hrows _) + (Nat.pow_pos (NeZero.pos m)))) h.symm + +private theorem mem_copies {S : Type*} {E : S → Type*} + [Fintype S] [∀ s, Fintype (E s)] (count : ∀ s, E s → Nat) + (s : S) (e : E s) (positive : 0 < count s e) : + e ∈ ExactConditionalOutput.copies count s := by + unfold ExactConditionalOutput.copies + refine List.mem_flatten.mpr ⟨List.replicate (count s e) e, ?_, ?_⟩ + · refine List.mem_ofFn.mpr ⟨ExactConditionalOutput.enumeration s e, ?_⟩ + simp only [Equiv.symm_apply_apply] + · exact List.mem_replicate.mpr ⟨Nat.ne_of_gt positive, rfl⟩ + +theorem mem_completedOrder (e : Completed) : + e ∈ completedOrder (t := t) clauses rows repeats hn hbranch hrows δ := by + let descriptor := CompletedSignedLaw.completedEquiv (t := t) clauses rows repeats hn hbranch hrows δ e + apply List.mem_flatMap.mpr + refine ⟨descriptor.1, SourceQuestionOrder.mem_sourceOrder descriptor.1, ?_⟩ + apply List.mem_map.mpr + refine ⟨descriptor.2, ?_, ?_⟩ + · exact mem_copies (SignedCompletionSchedule.count (branch := branch) (n := n) (t := t) + (rows := rows) (repeats := repeats) hq large hn hbranch hrows) + (sourceSigns clauses descriptor.1) descriptor.2 + (SignedCompletionSchedule.count_positive (branch := branch) (n := n) (t := t) + (rows := rows) (repeats := repeats) hq large hn hbranch hrows _ _) + · exact (CompletedSignedLaw.completedEquiv (t := t) clauses rows repeats hn hbranch hrows δ).symm_apply_apply e + +def rawOrder : List (PreliminarySampler.Raw clauses branch n t rows repeats) := + (completedOrder (t := t) clauses rows repeats hn hbranch hrows δ).map Sigma.fst + +theorem mem_rawOrder (e : PreliminarySampler.Raw clauses branch n t rows repeats) : + e ∈ rawOrder (t := t) clauses rows repeats hn hbranch hrows δ := by + apply List.mem_map.mpr + refine ⟨⟨e, ⟨0, (C).positive e⟩⟩, + mem_completedOrder (t := t) clauses rows repeats hn hbranch hrows δ _, rfl⟩ + +theorem rawOrder_length : + (rawOrder (t := t) clauses rows repeats hn hbranch hrows δ).length = D * m ^ locationCount := by + rw [rawOrder, List.length_map, + completedOrder_length (t := t) clauses rows repeats hn hbranch hrows δ] + +theorem completedOrder_filter_length (event : Completed → Bool) : + ((completedOrder (t := t) clauses rows repeats hn hbranch hrows δ).filter event).length = + ∑ source : PreliminarySampler.Questions branch n t m, + ((SignedCompletionSchedule.schedule (branch := branch) (n := n) (t := t) + (rows := rows) (repeats := repeats) hq large hn hbranch hrows + (sourceSigns clauses source)).filter + (fun outcome => event (transport ⟨source, outcome⟩))).length := by + rw [completedOrder, List.filter_flatMap, List.length_flatMap] + simp only [localOrder, List.filter_map, List.length_map, Function.comp_def] + exact SourceQuestionOrder.sum_map_sourceOrder _ + +theorem completedOrder_probability (event : Completed → Bool) : + (((completedOrder (t := t) clauses rows repeats hn hbranch hrows δ).filter event).length : ℝ) / + (completedOrder (t := t) clauses rows repeats hn hbranch hrows δ).length = + (C).game.occurrences.probability event := by + have hcard : Fintype.card (PreliminarySampler.Questions branch n t m) = + m ^ locationCount := by + rw [Fintype.card_congr (SourceQuestionOrder.questionTupleEquiv branch n t m)] + simp only [Fintype.card_fun, Fintype.card_fin] + rw [completedOrder_filter_length (t := t) clauses rows repeats hn hbranch hrows δ event, + Nat.cast_sum, completedOrder_length (t := t) clauses rows repeats hn hbranch hrows δ, + Nat.cast_mul, + CompletedSignedLaw.probability_schedule (t := t) clauses rows repeats hn hbranch hrows δ event] + simp only [FiniteDistribution.expectation, PreliminarySampler.questionsLaw, + FiniteDistribution.uniform, SignedCompletionSchedule.schedule_length] + rw [← Finset.mul_sum, ← Finset.sum_div, hcard] + simp only [div_eq_mul_inv, mul_inv_rev] + ring + +end +end PerfectCompleteness.CompletedOccurrenceOrder + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/CompletedVisitOrder.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/CompletedVisitOrder.lean new file mode 100644 index 0000000000000000000000000000000000000000..4ae5c744c5feb0c63a8402b210f10ee0dd3fd6b4 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/CompletedVisitOrder.lean @@ -0,0 +1,148 @@ +import OAI.Computability.PerfectCompleteness.Foundations.SourceVisitOrder +import OAI.Computability.PerfectCompleteness.Sampling.CompletedSignedLaw + +namespace OAI + +section + +namespace PerfectCompleteness.CompletedVisitOrder + +open MetadataFreeSampler +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +noncomputable section + +variable {branch : Nat → Nat} {n t v m : Nat} + (clauses : Fin m → SourceClause.NormalizedClause v) (rows repeats : Nat → Nat) + [NeZero m] (hn : 0 < n) (hbranch : ∀ k < n, 0 < branch k) + (hrows : ∀ k, 0 < rows (k + 1)) (δ : ℚ) + +local notation "locationCount" => TreeCanonical.locationCount branch n t +local notation "hq" => CanonicalLocalCompletion.alphabet_positive locationCount δ +local notation "large" => CanonicalLocalCompletion.partitionWidth_le_alphabet locationCount δ +local notation "D" => SignedMultiplicity.denominator branch n t rows repeats hn hbranch hrows + (FinitePreliminaryCompletion.alphabet branch n t δ) +local notation "F" => FinitePreliminaryCompletion.blockFamily clauses branch n t rows repeats + +local instance leftVertex_fintype : Fintype (CanonicalGame.LeftVertex F) := Fintype.ofFinite _ +local instance rightVertex_fintype : Fintype (CanonicalGame.RightVertex F) := Fintype.ofFinite _ +local instance leftLabel_fintype (x : CanonicalGame.LeftVertex F) : + Fintype (CanonicalGame.LeftLabel F x) := Fintype.ofFinite _ +local instance rightLabel_fintype (y : CanonicalGame.RightVertex F) : + Fintype (CanonicalGame.RightLabel F y) := Fintype.ofFinite _ + +local notation "C" => + FinitePreliminaryCompletion.actualFamily (t := t) clauses rows repeats hn hbranch hrows δ +local notation "Completed" => CompletedSignedLaw.Completed (t := t) clauses rows repeats hn hbranch hrows δ +local notation "transport" => + Equiv.symm (CompletedSignedLaw.completedEquiv (t := t) clauses rows repeats hn hbranch hrows δ) + +def localOrder (source : PreliminarySampler.Questions branch n t m) : List Completed := + (SignedCompletionSchedule.schedule (branch := branch) (n := n) (t := t) + (rows := rows) (repeats := repeats) hq large hn hbranch hrows + (sourceSigns clauses source)).map (fun outcome => transport ⟨source, outcome⟩) + +def completedOrder : List Completed := + (SourceVisitOrder.visitOrder branch n t m).flatMap + (localOrder (t := t) clauses rows repeats hn hbranch hrows δ) + +theorem localOrder_length (source : PreliminarySampler.Questions branch n t m) : + (localOrder (t := t) clauses rows repeats hn hbranch hrows δ source).length = D := by + rw [localOrder, List.length_map, SignedCompletionSchedule.schedule_length] + +theorem completedOrder_length : + (completedOrder (t := t) clauses rows repeats hn hbranch hrows δ).length = + D * m ^ locationCount := by + change (ExactConditionalOutput.output + (SignedCompletionSchedule.count (branch := branch) (n := n) (t := t) + (rows := rows) (repeats := repeats) hq large hn hbranch hrows) (sourceSigns clauses) + (fun source outcome => transport ⟨source, outcome⟩) + (SourceVisitOrder.visitOrder branch n t m)).length = _ + rw [ExactConditionalOutput.output_length _ _ _ D + (SignedCompletionSchedule.count_total (branch := branch) (n := n) (t := t) + (rows := rows) (repeats := repeats) hq large hn hbranch hrows), + SourceVisitOrder.visitOrder_length] + +theorem completedOrder_nonempty : + completedOrder (t := t) clauses rows repeats hn hbranch hrows δ ≠ [] := by + intro hempty + have h := completedOrder_length (t := t) clauses rows repeats hn hbranch hrows δ + rw [hempty, List.length_nil] at h + exact (Nat.ne_of_gt (Nat.mul_pos + (SignedMultiplicity.denominator_positive branch n t rows repeats hn hbranch hrows _) + (Nat.pow_pos (NeZero.pos m)))) h.symm + +private theorem mem_copies {S : Type*} {E : S → Type*} + [Fintype S] [∀ s, Fintype (E s)] (count : ∀ s, E s → Nat) + (s : S) (e : E s) (positive : 0 < count s e) : + e ∈ ExactConditionalOutput.copies count s := by + unfold ExactConditionalOutput.copies + refine List.mem_flatten.mpr ⟨List.replicate (count s e) e, ?_, ?_⟩ + · refine List.mem_ofFn.mpr ⟨ExactConditionalOutput.enumeration s e, ?_⟩ + simp only [Equiv.symm_apply_apply] + · exact List.mem_replicate.mpr ⟨Nat.ne_of_gt positive, rfl⟩ + +theorem mem_completedOrder (e : Completed) : + e ∈ completedOrder (t := t) clauses rows repeats hn hbranch hrows δ := by + let descriptor := CompletedSignedLaw.completedEquiv (t := t) clauses rows repeats hn hbranch hrows δ e + apply List.mem_flatMap.mpr + refine ⟨descriptor.1, SourceVisitOrder.mem_visitOrder descriptor.1, ?_⟩ + apply List.mem_map.mpr + refine ⟨descriptor.2, ?_, ?_⟩ + · exact mem_copies (SignedCompletionSchedule.count (branch := branch) (n := n) (t := t) + (rows := rows) (repeats := repeats) hq large hn hbranch hrows) + (sourceSigns clauses descriptor.1) descriptor.2 + (SignedCompletionSchedule.count_positive (branch := branch) (n := n) (t := t) + (rows := rows) (repeats := repeats) hq large hn hbranch hrows _ _) + · exact (CompletedSignedLaw.completedEquiv (t := t) clauses rows repeats hn hbranch hrows δ).symm_apply_apply e + +def rawOrder : List (PreliminarySampler.Raw clauses branch n t rows repeats) := + (completedOrder (t := t) clauses rows repeats hn hbranch hrows δ).map Sigma.fst + +theorem mem_rawOrder (e : PreliminarySampler.Raw clauses branch n t rows repeats) : + e ∈ rawOrder (t := t) clauses rows repeats hn hbranch hrows δ := by + apply List.mem_map.mpr + refine ⟨⟨e, ⟨0, (C).positive e⟩⟩, + mem_completedOrder (t := t) clauses rows repeats hn hbranch hrows δ _, rfl⟩ + +theorem rawOrder_length : + (rawOrder (t := t) clauses rows repeats hn hbranch hrows δ).length = D * m ^ locationCount := by + rw [rawOrder, List.length_map, + completedOrder_length (t := t) clauses rows repeats hn hbranch hrows δ] + +theorem completedOrder_filter_length (event : Completed → Bool) : + ((completedOrder (t := t) clauses rows repeats hn hbranch hrows δ).filter event).length = + ∑ source : PreliminarySampler.Questions branch n t m, + ((SignedCompletionSchedule.schedule (branch := branch) (n := n) (t := t) + (rows := rows) (repeats := repeats) hq large hn hbranch hrows + (sourceSigns clauses source)).filter + (fun outcome => event (transport ⟨source, outcome⟩))).length := by + rw [completedOrder, List.filter_flatMap, List.length_flatMap] + simp only [localOrder, List.filter_map, List.length_map, Function.comp_def] + exact SourceVisitOrder.sum_map_visitOrder _ + +theorem completedOrder_probability (event : Completed → Bool) : + (((completedOrder (t := t) clauses rows repeats hn hbranch hrows δ).filter event).length : ℝ) / + (completedOrder (t := t) clauses rows repeats hn hbranch hrows δ).length = + (C).game.occurrences.probability event := by + have hcard : Fintype.card (PreliminarySampler.Questions branch n t m) = + m ^ locationCount := by + rw [Fintype.card_congr (SourceQuestionOrder.questionTupleEquiv branch n t m)] + simp only [Fintype.card_fun, Fintype.card_fin] + rw [completedOrder_filter_length (t := t) clauses rows repeats hn hbranch hrows δ event, + Nat.cast_sum, completedOrder_length (t := t) clauses rows repeats hn hbranch hrows δ, + Nat.cast_mul, + CompletedSignedLaw.probability_schedule (t := t) clauses rows repeats hn hbranch hrows δ event] + simp only [FiniteDistribution.expectation, PreliminarySampler.questionsLaw, + FiniteDistribution.uniform, SignedCompletionSchedule.schedule_length] + rw [← Finset.mul_sum, ← Finset.sum_div, hcard] + simp only [div_eq_mul_inv, mul_inv_rev] + ring + +end +end PerfectCompleteness.CompletedVisitOrder + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/CompletionAlphabetLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/CompletionAlphabetLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..73796a8547b4559abd26cea9d83049e4c1d47dda --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/CompletionAlphabetLemmas.lean @@ -0,0 +1,252 @@ +import OAI.Computability.PerfectCompleteness.Algebra.HierarchicalMatrixTable +import OAI.Computability.PerfectCompleteness.Decoding.Projection +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalArrays +import OAI.Computability.PerfectCompleteness.Machines.EncodingLemmas +import OAI.Computability.PerfectCompleteness.Reduction.CanonicalGameLemmas +import OAI.Computability.PerfectCompleteness.Reduction.CompletionOutputLemmas +import OAI.Computability.PerfectCompleteness.Sampling.CompletionProbability + +namespace OAI + + +namespace PerfectCompleteness.CompletionAlphabet + +open scoped Classical +open UniqueGamesTheorem.Foundations.Games +open WeightRounding CompletionSoundness CompletionParameters + +def size (cap : Nat) (δ : ℚ) : Nat := max (cap + 1) ⌈(6 : ℚ) / δ⌉₊ + +theorem size_positive (cap : Nat) (δ : ℚ) : 0 < size cap δ := by + have h : cap + 1 ≤ size cap δ := le_max_left _ _ + omega + +theorem cap_le_size (cap : Nat) (δ : ℚ) : cap ≤ size cap δ := + (Nat.le_succ cap).trans (le_max_left _ _) + +theorem size_budget (cap : Nat) (δ : ℚ) (hδ : 0 < δ) : + (6 : ℝ) ≤ (δ : ℝ) * size cap δ := by + have hceil : (6 : ℚ) / δ ≤ (⌈(6 : ℚ) / δ⌉₊ : ℚ) := Nat.le_ceil _ + have hsize : (⌈(6 : ℚ) / δ⌉₊ : ℚ) ≤ (size cap δ : ℚ) := by + exact_mod_cast (le_max_right (cap + 1) ⌈(6 : ℚ) / δ⌉₊) + have hprod : (6 : ℚ) ≤ δ * size cap δ := by + have h := (div_le_iff₀ hδ).1 (hceil.trans hsize) + simpa only [mul_comm] using h + exact_mod_cast hprod + +theorem exists_target {m l r : Nat} {L : Fin l → Type*} {R : Fin r → Type*} + [∀ x, Fintype (L x)] [∀ y, Fintype (R y)] + [∀ x, Nonempty (L x)] [∀ y, Nonempty (R y)] + (G : LegalProjectionGame (Fin m) (Fin l) (Fin r) L R) + (w : PositiveWeights m) + (hweights : ∀ e, G.occurrences.weight e = (w.weight e : ℝ)) + (hsmall : ∀ e b, Fintype.card {a : L (G.left e) // G.projection e a = b} ≤ 2) + (cap : Nat) (hleft : ∀ x, Fintype.card (L x) ≤ cap) + (hright : ∀ y, Fintype.card (R y) ≤ cap) + (δ : ℚ) (hδ : 0 < δ) : + let q := size cap δ + let M := ⌈(3 : ℚ) / δ⌉₊ * m * (2 * q) + ∃ target : Instance q, + target.leftVertices = l ∧ target.rightVertices = r ∧ + target.edges.length ≤ M ∧ + (Encoding.gameBits target).length ≤ + l + r + q + M + 4 + M * (l + r + 2 * q * q + 2 * q + 2) ∧ + (G.value = 1 → PerfectlyComplete target) ∧ + (G.value ≤ (δ : ℝ) / 3 → target.value ≤ (δ : ℝ)) := by + let q := size cap δ + let M := ⌈(3 : ℚ) / δ⌉₊ * m * (2 * q) + have hleftq : ∀ x, Fintype.card (L x) ≤ q := + fun x => (hleft x).trans (cap_le_size cap δ) + have hrightq : ∀ y, Fintype.card (R y) ≤ q := + fun y => (hright y).trans (cap_le_size cap δ) + obtain ⟨target, hl, hr, he, hc, hs⟩ := CompletionParameters.exists_target + G w hweights hsmall hleftq hrightq δ hδ (size_positive cap δ) (size_budget cap δ hδ) + refine ⟨target, hl, hr, he, ?_, hc, hs⟩ + have hb := Encoding.gameBits_length_le_of_edge_count target M he + simpa only [hl, hr] using hb + +end PerfectCompleteness.CompletionAlphabet + + +namespace PerfectCompleteness +open CompletionProbability + +theorem exists_completion_tables {l q : Nat} + (legal : Fin l ↪ Fin (2 * q)) (p : Fin l → Fin q) + (hsmall : ∀ b, Fintype.card {a : Fin l // p a = b} ≤ 2) : + ∃ n : Nat, 0 < n ∧ ∃ tables : Fin n → ProjectionTable q, + (∀ seed a, (tables seed).images[legal a] = p a) ∧ + ∀ (a : Illegal legal) (b : Fin q), + uniformProbability (fun seed => (tables seed).images[a.val] = b) ≤ + 2 / (2 * q - l : Nat) := by + classical + obtain ⟨n, hn, sampler, hext, hexact, hprob⟩ := + exists_completion_sampler legal p + (by intro b; simpa only [← Nat.card_eq_fintype_card] using hsmall b) (by simp) + let tables : Fin n → ProjectionTable q := fun seed => + ProjectionTable.ofMap (sampler seed) (by + simpa only [← Nat.card_eq_fintype_card] using hexact seed) + refine ⟨n, hn, tables, ?_, ?_⟩ + · intro seed a + simpa [tables, ProjectionTable.ofMap] using hext seed a + · intro a b + simpa [tables, ProjectionTable.ofMap] using (hprob a b).2 + +end PerfectCompleteness + + +namespace PerfectCompleteness.HierarchicalGame + +open HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +structure Family {v m : Nat} (clauses : Fin m → SourceClause.NormalizedClause v) + (branch : Nat → Nat) (n t : Nat) (rows : Nat → Nat) (E : Type*) where + endpoints : E → RecursiveSpaces.Slots branch n → Fin t → SourceKeys.Endpoint v m + arrays : ∀ e, Arrays (sourceSlots clauses (endpoints e)) rows + selected : E → Nodes branch n + direction : ∀ e, Block rows (selected e) + nonzero : ∀ e, direction e ≠ 0 + +noncomputable section + +variable {v m n t : Nat} {clauses : Fin m → SourceClause.NormalizedClause v} + {branch rows : Nat → Nat} {E : Type*} + (F : Family clauses branch n t rows E) + +def toBlockFamily : CanonicalGame.BlockFamily clauses + (TreeCanonical.locationCount branch n t) E (Nodes branch n) + (fun node : Nodes branch n => Block rows node) PUnit.{1} where + presentation e := HierarchicalArrays.presentation clauses (F.endpoints e) rows (F.arrays e) + selected := F.selected + direction := F.direction + nonzero := F.nonzero + +abbrev LeftVertex := CanonicalGame.LeftVertex (toBlockFamily F) +abbrev RightVertex := CanonicalGame.RightVertex (toBlockFamily F) +abbrev LeftLabel (q : LeftVertex F) := CanonicalGame.LeftLabel (toBlockFamily F) q +abbrev RightLabel (q : RightVertex F) := CanonicalGame.RightLabel (toBlockFamily F) q + +abbrev leftAt (e : E) : LeftVertex F := CanonicalGame.leftAt (toBlockFamily F) e +abbrev rightAt (e : E) : RightVertex F := CanonicalGame.rightAt (toBlockFamily F) e + +theorem leftVertex_finite [Finite E] : Finite (LeftVertex F) := by infer_instance +theorem rightVertex_finite [Finite E] : Finite (RightVertex F) := by infer_instance +theorem leftLabel_finite (q : LeftVertex F) : Finite (LeftLabel F q) := by infer_instance +theorem rightLabel_finite (q : RightVertex F) : Finite (RightLabel F q) := by infer_instance + +theorem leftKey_eq (e : E) : + CanonicalGame.leftKey (toBlockFamily F) e = + TreeCanonical.key .left (sourceSlots clauses (F.endpoints e)) (fullJoint (F.arrays e)) := rfl + +theorem rightKey_eq (e : E) : + CanonicalGame.rightKey (toBlockFamily F) e = + TreeCanonical.key .right (sourceSlots clauses (F.endpoints e)) + (BlockQuotient.projectBlock (F.selected e) (F.direction e) ∘ fullJoint (F.arrays e)) := rfl + +abbrev edge (e : E) (P : LeftLabel F (leftAt F e)) : RightLabel F (rightAt F e) := + CanonicalGame.edge (toBlockFamily F) e P + +theorem edge_eq_iff (e : E) (P : LeftLabel F (leftAt F e)) + (Q : RightLabel F (rightAt F e)) : + edge F e P = Q ↔ + BlockQuotient.projectBlock (F.selected e) (F.direction e) + (TreeCanonical.restore (sourceSlots clauses (F.endpoints e)) (fullJoint (F.arrays e)) P) = + TreeCanonical.restore (sourceSlots clauses (F.endpoints e)) + (BlockQuotient.projectBlock (F.selected e) (F.direction e) ∘ fullJoint (F.arrays e)) Q := by + change CanonicalKeys.Label + (TreeCanonical.numberedSlots (sourceSlots clauses (F.endpoints e))) + (BlockQuotient.projectBlock (F.selected e) (F.direction e) ∘ + TreeCanonical.numberedFunction (sourceSlots clauses (F.endpoints e)) + (fullJoint (F.arrays e))) at Q + exact CanonicalEdges.coarsen_eq_iff + (TreeCanonical.numberedSlots (sourceSlots clauses (F.endpoints e))) + (TreeCanonical.numberedFunction (sourceSlots clauses (F.endpoints e)) (fullJoint (F.arrays e))) + (BlockQuotient.projectBlock (F.selected e) (F.direction e)) P Q + +theorem edge_at_most_two (e : E) (Q : RightLabel F (rightAt F e)) : + Nat.card {P : LeftLabel F (leftAt F e) // edge F e P = Q} ≤ 2 := + CanonicalGame.edge_at_most_two (toBlockFamily F) e Q + +def game [Fintype E] (μ : FiniteDistribution E) : + CompletionSoundness.LegalProjectionGame E (LeftVertex F) (RightVertex F) + (LeftLabel F) (RightLabel F) := + CanonicalGame.game (toBlockFamily F) μ + +def satisfyingStrategy (assignment : Fin v → Bool) + (hsat : ∀ c, (clauses c).clause.eval assignment = true) : + CompletionSoundness.LegalStrategy (LeftLabel F) (RightLabel F) := + CanonicalGame.satisfyingStrategy (toBlockFamily F) assignment hsat + +theorem edge_satisfyingStrategy (assignment : Fin v → Bool) + (hsat : ∀ c, (clauses c).clause.eval assignment = true) (e : E) : + edge F e ((satisfyingStrategy F assignment hsat).1 (leftAt F e)) = + (satisfyingStrategy F assignment hsat).2 (rightAt F e) := + CanonicalGame.edge_strategy (toBlockFamily F) assignment hsat e + +theorem success_satisfyingStrategy [Fintype E] (μ : FiniteDistribution E) + (assignment : Fin v → Bool) (hsat : ∀ c, (clauses c).clause.eval assignment = true) : + (game F μ).success (satisfyingStrategy F assignment hsat) = 1 := + CanonicalGame.success_satisfyingStrategy (toBlockFamily F) μ assignment hsat + +theorem value_eq_one [Fintype E] + [Fintype (LeftVertex F)] [Fintype (RightVertex F)] + [∀ q, Fintype (LeftLabel F q)] [∀ q, Fintype (RightLabel F q)] + (μ : FiniteDistribution E) (assignment : Fin v → Bool) + (hsat : ∀ c, (clauses c).clause.eval assignment = true) : (game F μ).value = 1 := by + apply le_antisymm + · obtain ⟨strategy, hs⟩ := (game F μ).exists_optimal_strategy + rw [← hs] + exact (game F μ).occurrences.probability_le_one _ + · have h := (game F μ).success_le_value (satisfyingStrategy F assignment hsat) + simpa only [success_satisfyingStrategy F μ assignment hsat] using h + +end + +end PerfectCompleteness.HierarchicalGame + + +namespace PerfectCompleteness.HierarchicalGameTable + +noncomputable section + +open HierarchicalArrays + +variable {v m n t : Nat} {clauses : Fin m → SourceClause.NormalizedClause v} + {branch rows : Nat → Nat} {E : Type*} + (F : HierarchicalGame.Family clauses branch n t rows E) + (s : CompletionSoundness.LegalStrategy (HierarchicalGame.LeftLabel F) + (HierarchicalGame.RightLabel F)) + +def strategy : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t) := + CanonicalGameStrategy.extend (HierarchicalGame.toBlockFamily F) s + +def background (e : E) : + HierarchicalMatrixTable.Background (rows := rows) + (sourceSlots clauses (F.endpoints e)) (F.selected e) := + HierarchicalMatrixTable.backgroundOf (sourceSlots clauses (F.endpoints e)) + (F.selected e) (F.arrays e) + +def matrix (e : E) : + HierarchicalMatrixTable.Matrix (rows := rows) + (sourceSlots clauses (F.endpoints e)) (F.selected e) := + NodeEmbedding.matrix (F.arrays e) (F.selected e) + +theorem accepts_iff (e : E) : + CanonicalMatrixTable.Accepts + (TreeCanonical.numberedSlots (sourceSlots clauses (F.endpoints e))) + (NodeEmbedding.RowSpace (sourceSlots clauses (F.endpoints e)) (F.selected e)) + (HierarchicalMatrixTable.other (sourceSlots clauses (F.endpoints e)) + (F.selected e) (background F e)) + (strategy F s) (F.direction e) (matrix F e) ↔ + HierarchicalGame.edge F e (s.1 (HierarchicalGame.leftAt F e)) = + s.2 (HierarchicalGame.rightAt F e) := by + unfold background matrix + rw [HierarchicalMatrixTable.accepts_iff_canonical, + HierarchicalMatrixTable.displayed_original] + exact CanonicalGameStrategy.accepts_extend_iff (HierarchicalGame.toBlockFamily F) s e + +end +end PerfectCompleteness.HierarchicalGameTable + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/CompletionLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/CompletionLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..7cbbd808510f649917197a9256c02cdd8bf51e51 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/CompletionLemmas.lean @@ -0,0 +1,255 @@ +import Mathlib.Data.Fintype.Prod +import Mathlib.Logic.Equiv.Fintype +import Mathlib.Logic.Equiv.Sum +import OAI.Computability.PerfectCompleteness.Algebra.MatrixInverseConstantsLemmas +import OAI.Computability.PerfectCompleteness.Machines.FixedUnaryRepresentationMachine +import OAI.Computability.UniqueGames.Machines.MachineCloudPadding + +namespace OAI + + +namespace PerfectCompleteness.Completion + +variable {L A B : Type*} + +def fiberEquivTwo (e : A ≃ B × Fin 2) (b : B) : + {a : A // (e a).1 = b} ≃ Fin 2 where + toFun a := (e a.val).2 + invFun j := ⟨e.symm (b, j), by simp⟩ + left_inv a := by + apply Subtype.ext + apply e.injective + simp only [Equiv.apply_symm_apply] + exact Prod.ext a.property.symm rfl + right_inv j := by simp + +theorem exists_slot_embedding [Fintype L] [Fintype B] [DecidableEq B] + (p : L → B) (hsmall : ∀ b, Fintype.card {l : L // p l = b} ≤ 2) : + ∃ slots : L ↪ B × Fin 2, ∀ l, (slots l).1 = p l := by + classical + have hslots (b : B) : Nonempty ({l : L // p l = b} ↪ Fin 2) := + Function.Embedding.nonempty_of_card_le (by simpa using hsmall b) + let fiberSlots (b : B) : {l : L // p l = b} ↪ Fin 2 := + Classical.choice (hslots b) + let fiberMap : (Σ b : B, {l : L // p l = b}) ↪ Σ _ : B, Fin 2 := + Function.Embedding.sigmaMap (Function.Embedding.refl B) fiberSlots + let slots : L ↪ B × Fin 2 := + (Equiv.sigmaFiberEquiv p).symm.toEmbedding.trans + (fiberMap.trans (Equiv.sigmaEquivProd B (Fin 2)).toEmbedding) + exact ⟨slots, fun _ => rfl⟩ + +theorem exists_exact_two_completion [Fintype L] [Fintype A] [Fintype B] + [DecidableEq B] (legal : L ↪ A) (p : L → B) + (hsmall : ∀ b, Fintype.card {l : L // p l = b} ≤ 2) + (hcard : Fintype.card A = 2 * Fintype.card B) : + ∃ pHat : A → B, + (∀ l, pHat (legal l) = p l) ∧ + ∀ b, Fintype.card {a : A // pHat a = b} = 2 := by + classical + obtain ⟨slots, hslots⟩ := exists_slot_embedding p hsmall + have hcardSlots : Fintype.card A = Fintype.card (B × Fin 2) := by + rw [Fintype.card_prod, Fintype.card_fin, Nat.mul_comm] + exact hcard + let base : A ≃ B × Fin 2 := Fintype.equivOfCardEq hcardSlots + obtain ⟨σ, hσ⟩ := Equiv.Perm.exists_extending_pair + (fun l : L => base (legal l)) (fun l : L => slots l) + (base.injective.comp legal.injective) slots.injective + let e : A ≃ B × Fin 2 := base.trans σ + refine ⟨fun a => (e a).1, ?_, ?_⟩ + · intro l + change (σ (base (legal l))).1 = p l + rw [hσ l] + exact hslots l + · intro b + exact (Fintype.card_congr (fiberEquivTwo e b)).trans (Fintype.card_fin 2) + +end PerfectCompleteness.Completion + + + +namespace PerfectCompleteness.FixedUnaryRepresentationPlacement + + +open Turing UniqueGamesTheorem.Foundations.Complexity +open MachineComposition MachineCloudPadding + +abbrev Mode := FixedUnaryRepresentationMachine.Mode +abbrev Tape (width : Nat) := FixedUnaryRepresentationMachine.Tape width +abbrev Label (mode : Mode) (width : Nat) := + FixedUnaryRepresentationMachine.Label mode (List.finRange width) +abbrev CleanupLabel (width : Nat) := FixedUnaryRepresentationMachine.CleanupLabel width +abbrev State (A : Type) := A × Option Bool +abbrev Alphabet {K : Type} (_ : K) := Bool + +variable {width : Nat} {K Λ A : Type} + +def nativeProgram (mode : Mode) : Label mode width → + TM2.Stmt (Alphabet (K := Tape width)) (Label mode width) (State A) := + FixedUnaryRepresentationMachine.instruction mode (List.finRange width) id none + +def instruction (mode : Mode) (tape : Tape width → K) + (labels : Label mode width → Λ) (exit : Option Λ) : + Label mode width → TM2.Stmt (Alphabet (K := K)) Λ (State A) := + fun label => Placement.statement tape labels exit (nativeProgram mode label) + +def entry (mode : Mode) (labels : Label mode width → Λ) (exit : Option Λ) : Option Λ := + Placement.label labels exit + (FixedUnaryRepresentationMachine.entry mode (List.finRange width) id none) + +def tapes (view : K → Option (Tape width)) (extra : K → List Bool) + (mode : Mode) (values : Fin width → Nat) (destinations : Fin width → List Bool) : + K → List Bool := + Placement.tapes view (FixedUnaryRepresentationMachine.stacks mode values destinations) extra + +theorem tapes_eq_base (tape : Tape width → K) (view : K → Option (Tape width)) + (right : ∀ j k, view j = some k → tape k = j) (base : K → List Bool) + (mode : Mode) (values : Fin width → Nat) (destinations : Fin width → List Bool) + (contents : ∀ k, base (tape k) = + FixedUnaryRepresentationMachine.stacks mode values destinations k) : + tapes view base mode values destinations = base := by + funext j + cases viewed : view j with + | none => simp only [tapes, Placement.tapes, viewed] + | some k => + simp only [tapes, Placement.tapes, viewed] + rw [← right j k viewed] + exact (contents k).symm + +def cleanupNativeProgram : CleanupLabel width → + TM2.Stmt (Alphabet (K := Tape width)) (CleanupLabel width) (State A) := + FixedUnaryRepresentationMachine.cleanupInstruction id none + +def cleanupInstruction (tape : Tape width → K) + (labels : CleanupLabel width → Λ) (exit : Option Λ) : + CleanupLabel width → TM2.Stmt (Alphabet (K := K)) Λ (State A) := + fun label => Placement.statement tape labels exit (cleanupNativeProgram label) + +def cleanupEntry (labels : CleanupLabel width → Λ) (exit : Option Λ) : Option Λ := + Placement.label labels exit (FixedUnaryRepresentationMachine.cleanupEntry id none) + +variable [DecidableEq K] + +theorem familyTrace (mode : Mode) (tape : Tape width → K) (view : K → Option (Tape width)) + (left : ∀ k, view (tape k) = some k) + (right : ∀ j k, view j = some k → tape k = j) + (labels : Label mode width → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ label, program (labels label) = instruction mode tape labels exit label) + (extra : K → List Bool) (values : Fin width → Nat) + (destinations : Fin width → List Bool) (ambient : A) : + (advance (TM2.step program))^[FixedUnaryRepresentationMachine.steps mode values (List.finRange width)] + (some ⟨entry mode labels exit, (ambient, none), tapes view extra mode values destinations⟩) = + some ⟨exit, (ambient, none), tapes view extra mode values + (fun position => FixedUnaryRepresentationMachine.targetWord mode (values position) ++ + destinations position)⟩ := by + have native := FixedUnaryRepresentationMachine.familyTrace mode values id none + (nativeProgram (width := width) (A := A) mode) (fun _ => rfl) destinations ambient + have placed := Placement.trace tape view left right labels exit extra + (nativeProgram (width := width) (A := A) mode) program atLabels _ _ _ native + simpa only [Placement.configuration, Placement.label, entry, tapes] using placed + +def familyInTime (mode : Mode) (tape : Tape width → K) (view : K → Option (Tape width)) + (left : ∀ k, view (tape k) = some k) + (right : ∀ j k, view j = some k → tape k = j) + (labels : Label mode width → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ label, program (labels label) = instruction mode tape labels exit label) + (extra : K → List Bool) (values : Fin width → Nat) + (destinations : Fin width → List Bool) (ambient : A) + (maximum : Nat) (bounded : ∀ position, values position ≤ maximum) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨entry mode labels exit, (ambient, none), tapes view extra mode values destinations⟩ + (some ⟨exit, (ambient, none), tapes view extra mode values + (fun position => FixedUnaryRepresentationMachine.targetWord mode (values position) ++ + destinations position)⟩) + (width * (2 * maximum + 3)) where + steps := FixedUnaryRepresentationMachine.steps mode values (List.finRange width) + evals_in_steps := familyTrace mode tape view left right labels exit program atLabels extra + values destinations ambient + steps_le_m := by + simpa only [List.length_finRange] using + FixedUnaryRepresentationMachine.steps_le mode values (List.finRange width) maximum bounded + +theorem cleanupTrace (mode : Mode) (tape : Tape width → K) (view : K → Option (Tape width)) + (left : ∀ k, view (tape k) = some k) + (right : ∀ j k, view j = some k → tape k = j) + (labels : CleanupLabel width → Λ) (exit : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ label, program (labels label) = cleanupInstruction tape labels exit label) + (extra : K → List Bool) (values : Fin width → Nat) + (destinations : Fin width → List Bool) (ambient : A) : + (advance (TM2.step program))^[MachineDrainMany.steps + (FixedUnaryRepresentationMachine.cleanupTapes width) + (FixedUnaryRepresentationMachine.stacks mode values destinations)] + (some ⟨cleanupEntry labels exit, (ambient, none), tapes view extra mode values destinations⟩) = + some ⟨exit, (ambient, none), tapes view extra mode values (fun _ => [])⟩ := by + have native := FixedUnaryRepresentationMachine.cleanupTrace mode values id none + (cleanupNativeProgram (width := width) (A := A)) (fun _ => rfl) destinations ambient + have placed := Placement.trace tape view left right labels exit extra + (cleanupNativeProgram (width := width) (A := A)) program atLabels _ _ _ native + simpa only [Placement.configuration, Placement.label, cleanupEntry, tapes] using placed + +end PerfectCompleteness.FixedUnaryRepresentationPlacement + + + +namespace PerfectCompleteness.InitialParameters + +open UniqueGamesTheorem.Appendix UniqueGamesTheorem.Fourier + +noncomputable section + +def epsilon (δ : ℚ) : ℝ := (δ : ℝ) / 3 +def simultaneous (δ : ℚ) : ℝ := epsilon δ ^ 2 / 2 +def useful (δ : ℚ) : ℝ := simultaneous δ / 2 +def inverse (δ : ℚ) : ℝ := simultaneous δ ^ 2 / 32 + +theorem epsilon_pos {δ : ℚ} (hδ : 0 < δ) : 0 < epsilon δ := by + have : (0 : ℝ) < δ := by exact_mod_cast hδ + unfold epsilon + positivity + +theorem simultaneous_pos {δ : ℚ} (hδ : 0 < δ) : 0 < simultaneous δ := by + have := epsilon_pos hδ + unfold simultaneous + positivity + +theorem useful_pos {δ : ℚ} (hδ : 0 < δ) : 0 < useful δ := by + have := simultaneous_pos hδ + unfold useful + positivity + +theorem inverse_pos {δ : ℚ} (hδ : 0 < δ) : 0 < inverse δ := by + have := simultaneous_pos hδ + unfold inverse + positivity + +theorem epsilon_lt_one {δ : ℚ} (hδ : δ < 1) : epsilon δ < 1 := by + have : (δ : ℝ) < 1 := by exact_mod_cast hδ + unfold epsilon + linarith + +theorem exists_initial {δ : ℚ} (hδ : 0 < δ) (hδ' : δ < 1) : + ∃ depth r : Nat, 2 ≤ depth ∧ 4 ≤ (depth : ℝ) * epsilon δ ∧ + 1 ≤ r ∧ ∃ α : ℝ, 0 < α ∧ α < 1 ∧ + MatrixLevelBridge.levelCutoffConstant r α + RankLevelFilter.node (r + 1) < + inverse δ / 2 := by + have hε := epsilon_pos hδ + have hε' := epsilon_lt_one hδ' + obtain ⟨depth, hdepth⟩ := exists_nat_gt (4 / epsilon δ + 2) + have hd2 : (2 : ℝ) < depth := by + have := div_pos (by norm_num : (0 : ℝ) < 4) hε + linarith + have hd : 2 ≤ depth := by exact_mod_cast hd2.le + have hmul : 4 ≤ (depth : ℝ) * epsilon δ := by + have hdiv : 4 / epsilon δ < (depth : ℝ) := by linarith + exact ((div_lt_iff₀ hε).mp hdiv).le + obtain ⟨r, hr, α, hα, hα', hcut⟩ := + MatrixInverseConstants.exists_cutoff_density + (show 0 < inverse δ / 2 by have := inverse_pos hδ; positivity) + exact ⟨depth, r, hd, hmul, hr, α, hα, hα', hcut⟩ + +end +end PerfectCompleteness.InitialParameters + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/CompletionOutputLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/CompletionOutputLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..6af9735af5c23d608e596037e9e066133ac568b8 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/CompletionOutputLemmas.lean @@ -0,0 +1,193 @@ +import Mathlib.Data.Fin.Embedding +import Mathlib.Tactic.Linarith +import OAI.Computability.PerfectCompleteness.Machines.EncodingLemmas +import OAI.Computability.PerfectCompleteness.Reduction.CanonicalGameLemmas + +namespace OAI + + +namespace PerfectCompleteness.CompletionOutput + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games +open WeightRounding CompletionSoundness CompletionRounding +open CompletionSoundness.LegalProjectionGame + +noncomputable section + +variable {m l r q : Nat} {L : Fin l → Type*} {R : Fin r → Type*} + [∀ x, Fintype (L x)] + (G : LegalProjectionGame (Fin m) (Fin l) (Fin r) L R) + (legalL : ∀ x, L x ↪ Fin (2 * q)) (legalR : ∀ y, R y ↪ Fin q) + (hsmall : ∀ e b, Fintype.card {a : L (G.left e) // G.projection e a = b} ≤ 2) + +def family : G.CompletionFamily legalL legalR := + Classical.choose (G.exists_completionFamily_bounded legalL legalR hsmall (by simp)) + +theorem family_size (e : Fin m) : + (family G legalL legalR hsmall).size e ≤ + max 1 (2 * q - Fintype.card (L (G.left e))) := by + simpa only [family, Fintype.card_fin] using + Classical.choose_spec + (G.exists_completionFamily_bounded legalL legalR hsmall (by simp)) e + +theorem family_total_size (hq : 0 < q) : + (∑ e, (family G legalL legalR hsmall).size e) ≤ m * (2 * q) := by + calc + _ ≤ ∑ _e : Fin m, 2 * q := by + apply Finset.sum_le_sum + intro e _ + exact (family_size G legalL legalR hsmall e).trans + (max_le (by omega) (Nat.sub_le _ _)) + _ = m * (2 * q) := by simp + +def construct (w : PositiveWeights m) (δ : ℚ) (hδ : 0 < δ) : Instance q := + CompletionRounding.output w (family G legalL legalR hsmall) δ hδ + +@[simp] theorem construct_leftVertices (w : PositiveWeights m) (δ : ℚ) (hδ : 0 < δ) : + (construct G legalL legalR hsmall w δ hδ).leftVertices = l := rfl + +@[simp] theorem construct_rightVertices (w : PositiveWeights m) (δ : ℚ) (hδ : 0 < δ) : + (construct G legalL legalR hsmall w δ hδ).rightVertices = r := rfl + +theorem construct_edge_count (w : PositiveWeights m) (δ : ℚ) (hδ : 0 < δ) + (hq : 0 < q) : + (construct G legalL legalR hsmall w δ hδ).edges.length ≤ + ⌈(3 : ℚ) / δ⌉₊ * m * (2 * q) := by + exact (output_edge_count_le w (family G legalL legalR hsmall) δ hδ).trans + (by simpa only [Nat.mul_assoc] using + Nat.mul_le_mul_left ⌈(3 : ℚ) / δ⌉₊ (family_total_size G legalL legalR hsmall hq)) + +theorem construct_word_count (w : PositiveWeights m) (δ : ℚ) (hδ : 0 < δ) + (hq : 0 < q) : + (Encoding.gameWords (construct G legalL legalR hsmall w δ hδ)).length ≤ + 4 + (⌈(3 : ℚ) / δ⌉₊ * m * (2 * q)) * (2 * q + 2) := by + rw [Encoding.gameWords_length] + exact Nat.add_le_add_left + (Nat.mul_le_mul_right (2 * q + 2) (construct_edge_count G legalL legalR hsmall w δ hδ hq)) 4 + +variable [∀ y, Fintype (R y)] [∀ x, Nonempty (L x)] [∀ y, Nonempty (R y)] + +theorem construct_value_le (w : PositiveWeights m) + (hweights : ∀ e, G.occurrences.weight e = (w.weight e : ℝ)) + (δ : ℚ) (hδ : 0 < δ) (hq : 0 < q) : + (construct G legalL legalR hsmall w δ hδ).value ≤ + G.value + G.occurrences.expectation + (fun e => 2 / (2 * q - Fintype.card (L (G.left e)) : Nat)) + (δ : ℝ) / 3 := + output_value_le w (family G legalL legalR hsmall) hweights δ hδ hq + +theorem construct_value_le_of_residual_bound (w : PositiveWeights m) + (hweights : ∀ e, G.occurrences.weight e = (w.weight e : ℝ)) + (δ : ℚ) (hδ : 0 < δ) (hq : 0 < q) (η : ℝ) + (hη : ∀ e, 2 / (2 * q - Fintype.card (L (G.left e)) : Nat) ≤ η) : + (construct G legalL legalR hsmall w δ hδ).value ≤ G.value + η + (δ : ℝ) / 3 := + output_value_le_of_residual_bound w (family G legalL legalR hsmall) hweights δ hδ hq η hη + +theorem construct_perfectlyComplete (w : PositiveWeights m) + (hweights : ∀ e, G.occurrences.weight e = (w.weight e : ℝ)) + (δ : ℚ) (hδ : 0 < δ) (hq : 0 < q) (hcomplete : G.value = 1) : + PerfectlyComplete (construct G legalL legalR hsmall w δ hδ) := by + apply ((construct G legalL legalR hsmall w δ hδ).perfectlyComplete_iff_value_eq_one hq).2 + exact output_value_eq_one w (family G legalL legalR hsmall) hweights δ hδ hq hcomplete + +theorem construct_soundAt (w : PositiveWeights m) + (hweights : ∀ e, G.occurrences.weight e = (w.weight e : ℝ)) + (δ : ℚ) (hδ : 0 < δ) (hq : 0 < q) (η : ℝ) + (hη : ∀ e, 2 / (2 * q - Fintype.card (L (G.left e)) : Nat) ≤ η) + (d : RationalThreshold) + (hbudget : G.value + η + (δ : ℝ) / 3 ≤ (d.numerator : ℝ) / d.denominator) : + SoundAt d (construct G legalL legalR hsmall w δ hδ) := by + apply ((construct G legalL legalR hsmall w δ hδ).soundAt_iff_value_le hq d).2 + exact (construct_value_le_of_residual_bound G legalL legalR hsmall w hweights + δ hδ hq η hη).trans hbudget + +end +end PerfectCompleteness.CompletionOutput + + +namespace PerfectCompleteness.CompletionParameters + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games +open WeightRounding CompletionSoundness CompletionOutput + +noncomputable section + +theorem residual_le_third {q n : Nat} {δ : ℝ} (hq : 0 < q) + (hn : n ≤ q) (hδ : 0 < δ) (hbudget : 6 ≤ δ * q) : + 2 / (2 * q - n : Nat) ≤ δ / 3 := by + have hden : q ≤ 2 * q - n := by omega + have hden_real : (q : ℝ) ≤ (2 * q - n : Nat) := by exact_mod_cast hden + have hpos : (0 : ℝ) < (2 * q - n : Nat) := by + exact_mod_cast lt_of_lt_of_le hq hden + rw [div_le_iff₀ hpos] + have hmul := mul_le_mul_of_nonneg_left hden_real (le_of_lt hδ) + nlinarith + +def embedFin (T : Type*) [Fintype T] (n : Nat) (h : Fintype.card T ≤ n) : T ↪ Fin n := + (Fintype.equivFin T).toEmbedding.trans (Fin.castLEEmb h) + +section Game +variable {m l r q : Nat} {L : Fin l → Type*} {R : Fin r → Type*} + [∀ x, Fintype (L x)] [∀ y, Fintype (R y)] + [∀ x, Nonempty (L x)] [∀ y, Nonempty (R y)] + (G : LegalProjectionGame (Fin m) (Fin l) (Fin r) L R) + (legalL : ∀ x, L x ↪ Fin (2 * q)) (legalR : ∀ y, R y ↪ Fin q) + (hsmall : ∀ e b, Fintype.card {a : L (G.left e) // G.projection e a = b} ≤ 2) + +theorem construct_value_le_delta (w : PositiveWeights m) + (hweights : ∀ e, G.occurrences.weight e = (w.weight e : ℝ)) + (δ : ℚ) (hδ : 0 < δ) (hq : 0 < q) + (hleft : ∀ x, Fintype.card (L x) ≤ q) + (hbudget : (6 : ℝ) ≤ (δ : ℝ) * q) + (hsound : G.value ≤ (δ : ℝ) / 3) : + (construct G legalL legalR hsmall w δ hδ).value ≤ (δ : ℝ) := by + have hδreal : (0 : ℝ) < (δ : ℝ) := by exact_mod_cast hδ + have hres : ∀ e, 2 / (2 * q - Fintype.card (L (G.left e)) : Nat) ≤ (δ : ℝ) / 3 := + fun e => residual_le_third hq (hleft (G.left e)) hδreal hbudget + have h := construct_value_le_of_residual_bound G legalL legalR hsmall + w hweights δ hδ hq ((δ : ℝ) / 3) hres + linarith + +theorem construct_soundAt_of_budget (w : PositiveWeights m) + (hweights : ∀ e, G.occurrences.weight e = (w.weight e : ℝ)) + (δ : ℚ) (hδ : 0 < δ) (hq : 0 < q) + (hleft : ∀ x, Fintype.card (L x) ≤ q) + (hbudget : (6 : ℝ) ≤ (δ : ℝ) * q) + (hsound : G.value ≤ (δ : ℝ) / 3) (d : RationalThreshold) + (hthreshold : (δ : ℝ) ≤ (d.numerator : ℝ) / d.denominator) : + SoundAt d (construct G legalL legalR hsmall w δ hδ) := by + apply ((construct G legalL legalR hsmall w δ hδ).soundAt_iff_value_le hq d).2 + exact (construct_value_le_delta G legalL legalR hsmall w hweights + δ hδ hq hleft hbudget hsound).trans hthreshold + +end Game + +theorem exists_target {m l r q : Nat} {L : Fin l → Type*} {R : Fin r → Type*} + [∀ x, Fintype (L x)] [∀ y, Fintype (R y)] + [∀ x, Nonempty (L x)] [∀ y, Nonempty (R y)] + (G : LegalProjectionGame (Fin m) (Fin l) (Fin r) L R) + (w : PositiveWeights m) + (hweights : ∀ e, G.occurrences.weight e = (w.weight e : ℝ)) + (hsmall : ∀ e b, Fintype.card {a : L (G.left e) // G.projection e a = b} ≤ 2) + (hleft : ∀ x, Fintype.card (L x) ≤ q) + (hright : ∀ y, Fintype.card (R y) ≤ q) + (δ : ℚ) (hδ : 0 < δ) (hq : 0 < q) + (hbudget : (6 : ℝ) ≤ (δ : ℝ) * q) : + ∃ target : Instance q, + target.leftVertices = l ∧ target.rightVertices = r ∧ + target.edges.length ≤ ⌈(3 : ℚ) / δ⌉₊ * m * (2 * q) ∧ + (G.value = 1 → PerfectlyComplete target) ∧ + (G.value ≤ (δ : ℝ) / 3 → target.value ≤ (δ : ℝ)) := by + let legalL : ∀ x, L x ↪ Fin (2 * q) := + fun x => embedFin (L x) (2 * q) ((hleft x).trans (by omega)) + let legalR : ∀ y, R y ↪ Fin q := fun y => embedFin (R y) q (hright y) + refine ⟨construct G legalL legalR hsmall w δ hδ, rfl, rfl, + construct_edge_count G legalL legalR hsmall w δ hδ hq, ?_, ?_⟩ + · exact construct_perfectlyComplete G legalL legalR hsmall w hweights δ hδ hq + · exact construct_value_le_delta G legalL legalR hsmall w hweights δ hδ hq hleft hbudget + +end +end PerfectCompleteness.CompletionParameters + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/CompletionSoundness.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/CompletionSoundness.lean new file mode 100644 index 0000000000000000000000000000000000000000..a387c0aea87df7618f0a3caded58bd5ec2443e1e --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/CompletionSoundness.lean @@ -0,0 +1,393 @@ +import Mathlib.Data.Fintype.BigOperators +import Mathlib.Data.Fintype.Sigma +import Mathlib.Tactic.Choose +import Mathlib.Tactic.NormNum +import OAI.Computability.PerfectCompleteness.Reduction.OccurrenceGame +import OAI.Computability.PerfectCompleteness.Sampling.CompletionProbability + +namespace OAI + + +namespace PerfectCompleteness.CompletionSoundness + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games +open CompletionProbability + +noncomputable section + +section SeedLaws +variable {E : Type*} {Seed : E → Type*} + [Fintype E] [∀ e, Fintype (Seed e)] + +def sigmaLaw (μ : FiniteDistribution E) (ν : ∀ e, FiniteDistribution (Seed e)) : + FiniteDistribution (Σ e, Seed e) where + weight es := μ.weight es.1 * (ν es.1).weight es.2 + nonnegative es := mul_nonneg (μ.nonnegative es.1) ((ν es.1).nonnegative es.2) + normalized := by + rw [Fintype.sum_sigma] + calc + _ = ∑ e, μ.weight e := by + apply Finset.sum_congr rfl + intro e _ + change (∑ seed : Seed e, μ.weight e * (ν e).weight seed) = μ.weight e + rw [← Finset.mul_sum, (ν e).normalized, mul_one] + _ = 1 := μ.normalized + +theorem sigmaLaw_probability (μ : FiniteDistribution E) + (ν : ∀ e, FiniteDistribution (Seed e)) (event : (Σ e, Seed e) → Bool) : + (sigmaLaw μ ν).probability event = + μ.expectation (fun e => (ν e).probability (fun seed => event ⟨e, seed⟩)) := by + simp only [FiniteDistribution.probability, FiniteDistribution.expectation, + sigmaLaw, Fintype.sum_sigma, Finset.mul_sum, mul_ite, mul_zero] + +theorem sigmaLaw_probability_first (μ : FiniteDistribution E) + (ν : ∀ e, FiniteDistribution (Seed e)) (event : E → Bool) : + (sigmaLaw μ ν).probability (fun es => event es.1) = μ.probability event := by + rw [sigmaLaw_probability] + simp only [FiniteDistribution.expectation, FiniteDistribution.probability] + apply Finset.sum_congr rfl + intro e _ + by_cases he : event e = true <;> simp [he, (ν e).normalized] + +end SeedLaws + +theorem probability_uniform_eq_uniformProbability {Ω : Type*} + [Fintype Ω] [Nonempty Ω] (event : Ω → Prop) : + (FiniteDistribution.uniform Ω).probability (fun x => decide (event x)) = + uniformProbability event := by + calc + _ = (FiniteDistribution.uniform Ω).expectation + (fun x => if event x then (1 : ℝ) else 0) := by + unfold FiniteDistribution.probability FiniteDistribution.expectation + apply Finset.sum_congr rfl + intro x _ + by_cases hx : event x <;> simp [hx] + _ = (∑ x, if event x then (1 : ℝ) else 0) / (Fintype.card Ω : ℝ) := + FiniteDistribution.expectation_uniform _ + _ = uniformProbability event := by + simp only [uniformProbability, Fintype.card_subtype, Finset.sum_boole] + +theorem probability_decide_const {Ω : Type*} [Fintype Ω] + (μ : FiniteDistribution Ω) (P : Prop) : + μ.probability (fun _ => decide P) = if P then 1 else 0 := by + by_cases h : P <;> simp [h] + +def roundLabel {L A : Type*} (legal : L ↪ A) (default : L) (a : A) : L := + if h : ∃ l, legal l = a then Classical.choose h else default + +@[simp] theorem roundLabel_legal {L A : Type*} (legal : L ↪ A) + (default l : L) : roundLabel legal default (legal l) = l := by + have h : ∃ l', legal l' = legal l := ⟨l, rfl⟩ + simp only [roundLabel, dite_eq_left h] + exact legal.injective (Classical.choose_spec h) + +theorem seed_acceptance_le {L R A B Ω : Type*} [Fintype Ω] + (ν : FiniteDistribution Ω) (legalL : L ↪ A) (legalR : R ↪ B) + (defaultL : L) (defaultR : R) (p : L → R) (complete : Ω → A → B) + (agrees : ∀ seed l, complete seed (legalL l) = legalR (p l)) + (ε : ℝ) (hε : 0 ≤ ε) + (marginal : ∀ a, a ∉ Set.range legalL → ∀ b, + ν.probability (fun seed => decide (complete seed a = b)) ≤ ε) + (a : A) (b : B) : + ν.probability (fun seed => decide (complete seed a = b)) ≤ + (if p (roundLabel legalL defaultL a) = roundLabel legalR defaultR b then 1 else 0) + ε := by + by_cases ha : a ∈ Set.range legalL + · obtain ⟨l, rfl⟩ := ha + have hdom : ν.probability (fun seed => decide (complete seed (legalL l) = b)) ≤ + ν.probability (fun _ => + decide (p (roundLabel legalL defaultL (legalL l)) = + roundLabel legalR defaultR b)) := by + apply ν.probability_mono + intro seed hwin + have hw : complete seed (legalL l) = b := of_decide_eq_true hwin + have hb : legalR (p l) = b := (agrees seed l).symm.trans hw + apply decide_eq_true_iff.mpr + rw [roundLabel_legal, ← hb, roundLabel_legal] + rw [probability_decide_const] at hdom + exact hdom.trans (le_add_of_nonneg_right hε) + · have h := marginal a ha b + have hind : (0 : ℝ) ≤ + if p (roundLabel legalL defaultL a) = roundLabel legalR defaultR b then 1 else 0 := by + split <;> norm_num + exact h.trans (le_add_of_nonneg_left hind) + +structure LegalProjectionGame (E Q₁ Q₂ : Type*) + (L : Q₁ → Type*) (R : Q₂ → Type*) [Fintype E] where + occurrences : FiniteDistribution E + left : E → Q₁ + right : E → Q₂ + projection : ∀ e, L (left e) → R (right e) + +abbrev LegalStrategy {Q₁ Q₂ : Type*} (L : Q₁ → Type*) (R : Q₂ → Type*) := + (∀ x, L x) × (∀ y, R y) + +namespace LegalProjectionGame + +variable {E Q₁ Q₂ : Type*} {L : Q₁ → Type*} {R : Q₂ → Type*} + [Fintype E] (G : LegalProjectionGame E Q₁ Q₂ L R) + +def wins (s : LegalStrategy L R) (e : E) : Bool := + decide (G.projection e (s.1 (G.left e)) = s.2 (G.right e)) + +def success (s : LegalStrategy L R) : ℝ := G.occurrences.probability (G.wins s) + +section Value +variable [Fintype Q₁] [Fintype Q₂] [∀ x, Fintype (L x)] [∀ y, Fintype (R y)] + [∀ x, Nonempty (L x)] [∀ y, Nonempty (R y)] + +def value : ℝ := Finset.univ.sup' Finset.univ_nonempty G.success + +theorem success_le_value (s : LegalStrategy L R) : G.success s ≤ G.value := + Finset.le_sup' G.success (Finset.mem_univ s) + +theorem exists_optimal_strategy : ∃ s : LegalStrategy L R, G.success s = G.value := by + obtain ⟨s, _, hs⟩ := Finset.exists_mem_eq_sup' + (s := (Finset.univ : Finset (LegalStrategy L R))) Finset.univ_nonempty G.success + exact ⟨s, hs.symm⟩ + +end Value + +section Completion +variable [Fintype Q₁] [Fintype Q₂] + {A B : Type*} [Fintype A] [Fintype B] + {Seed : E → Type*} [∀ e, Fintype (Seed e)] + +def completedGame (ν : ∀ e, FiniteDistribution (Seed e)) + (complete : ∀ e, Seed e → A → B) : + OccurrenceGame (Σ e, Seed e) Q₁ Q₂ A B := + OccurrenceGame.ofProjection (sigmaLaw G.occurrences ν) + (fun es => G.left es.1) (fun es => G.right es.1) + (fun es => complete es.1 es.2) + +theorem completed_success (ν : ∀ e, FiniteDistribution (Seed e)) + (complete : ∀ e, Seed e → A → B) (s : Strategy Q₁ Q₂ A B) : + (G.completedGame ν complete).success s = + G.occurrences.expectation (fun e => (ν e).probability + (fun seed => decide (complete e seed (s.1 (G.left e)) = s.2 (G.right e)))) := by + change (sigmaLaw G.occurrences ν).probability _ = _ + exact sigmaLaw_probability G.occurrences ν _ + +def roundStrategy (legalL : ∀ x, L x ↪ A) (legalR : ∀ y, R y ↪ B) + (defaultL : ∀ x, L x) (defaultR : ∀ y, R y) + (s : Strategy Q₁ Q₂ A B) : LegalStrategy L R := + (fun x => roundLabel (legalL x) (defaultL x) (s.1 x), + fun y => roundLabel (legalR y) (defaultR y) (s.2 y)) + +def liftStrategy (legalL : ∀ x, L x ↪ A) (legalR : ∀ y, R y ↪ B) + (s : LegalStrategy L R) : Strategy Q₁ Q₂ A B := + (fun x => legalL x (s.1 x), fun y => legalR y (s.2 y)) + +theorem completed_success_le (ν : ∀ e, FiniteDistribution (Seed e)) + (complete : ∀ e, Seed e → A → B) + (legalL : ∀ x, L x ↪ A) (legalR : ∀ y, R y ↪ B) + (defaultL : ∀ x, L x) (defaultR : ∀ y, R y) + (agrees : ∀ e seed l, complete e seed (legalL (G.left e) l) = + legalR (G.right e) (G.projection e l)) + (ε : E → ℝ) (hε : ∀ e, 0 ≤ ε e) + (marginal : ∀ e a, a ∉ Set.range (legalL (G.left e)) → ∀ b, + (ν e).probability (fun seed => decide (complete e seed a = b)) ≤ ε e) + (s : Strategy Q₁ Q₂ A B) : + (G.completedGame ν complete).success s ≤ + G.success (roundStrategy legalL legalR defaultL defaultR s) + G.occurrences.expectation ε := by + rw [G.completed_success] + unfold FiniteDistribution.expectation success wins FiniteDistribution.probability + calc + _ ≤ ∑ e, G.occurrences.weight e * + ((if G.projection e (roundLabel (legalL (G.left e)) (defaultL (G.left e)) + (s.1 (G.left e))) = roundLabel (legalR (G.right e)) (defaultR (G.right e)) + (s.2 (G.right e)) then 1 else 0) + ε e) := by + apply Finset.sum_le_sum + intro e _ + exact mul_le_mul_of_nonneg_left + (seed_acceptance_le (ν e) (legalL (G.left e)) (legalR (G.right e)) + (defaultL (G.left e)) (defaultR (G.right e)) (G.projection e) (complete e) + (agrees e) (ε e) (hε e) (marginal e) _ _) (G.occurrences.nonnegative e) + _ = _ := by + simp only [roundStrategy, mul_add, Finset.sum_add_distrib, mul_ite, + mul_one, mul_zero] + apply congrArg (fun z : ℝ => z + ∑ e, G.occurrences.weight e * ε e) + apply Finset.sum_congr rfl + intro e _ + by_cases h : G.projection e + (roundLabel (legalL (G.left e)) (defaultL (G.left e)) (s.1 (G.left e))) = + roundLabel (legalR (G.right e)) (defaultR (G.right e)) (s.2 (G.right e)) + · simp [h] + · simp [h] + +theorem completed_success_lift (ν : ∀ e, FiniteDistribution (Seed e)) + (complete : ∀ e, Seed e → A → B) + (legalL : ∀ x, L x ↪ A) (legalR : ∀ y, R y ↪ B) + (agrees : ∀ e seed l, complete e seed (legalL (G.left e) l) = + legalR (G.right e) (G.projection e l)) + (s : LegalStrategy L R) : + (G.completedGame ν complete).success (liftStrategy legalL legalR s) = G.success s := by + change (sigmaLaw G.occurrences ν).probability + (fun es => decide (complete es.1 es.2 (legalL (G.left es.1) (s.1 (G.left es.1))) = + legalR (G.right es.1) (s.2 (G.right es.1)))) = G.success s + have hpoint : (fun es : Σ e, Seed e => + decide (complete es.1 es.2 (legalL (G.left es.1) (s.1 (G.left es.1))) = + legalR (G.right es.1) (s.2 (G.right es.1)))) = + (fun es => G.wins s es.1) := by + funext es + simp only [agrees, wins, (legalR (G.right es.1)).injective.eq_iff] + rw [hpoint, sigmaLaw_probability_first] + rfl + +variable [∀ x, Fintype (L x)] [∀ y, Fintype (R y)] + [∀ x, Nonempty (L x)] [∀ y, Nonempty (R y)] [Nonempty A] [Nonempty B] + +theorem completed_value_le (ν : ∀ e, FiniteDistribution (Seed e)) + (complete : ∀ e, Seed e → A → B) + (legalL : ∀ x, L x ↪ A) (legalR : ∀ y, R y ↪ B) + (agrees : ∀ e seed l, complete e seed (legalL (G.left e) l) = + legalR (G.right e) (G.projection e l)) + (ε : E → ℝ) (hε : ∀ e, 0 ≤ ε e) + (marginal : ∀ e a, a ∉ Set.range (legalL (G.left e)) → ∀ b, + (ν e).probability (fun seed => decide (complete e seed a = b)) ≤ ε e) : + (G.completedGame ν complete).value ≤ G.value + G.occurrences.expectation ε := by + apply ((G.completedGame ν complete).value_le_iff _).2 + intro s + let defaultL : ∀ x, L x := fun x => Classical.choice inferInstance + let defaultR : ∀ y, R y := fun y => Classical.choice inferInstance + exact (G.completed_success_le ν complete legalL legalR defaultL defaultR agrees ε hε marginal s).trans + (add_le_add (G.success_le_value _) (le_refl _)) + +theorem completed_value_le_of_bound (ν : ∀ e, FiniteDistribution (Seed e)) + (complete : ∀ e, Seed e → A → B) + (legalL : ∀ x, L x ↪ A) (legalR : ∀ y, R y ↪ B) + (agrees : ∀ e seed l, complete e seed (legalL (G.left e) l) = + legalR (G.right e) (G.projection e l)) + (ε : E → ℝ) (hε : ∀ e, 0 ≤ ε e) + (marginal : ∀ e a, a ∉ Set.range (legalL (G.left e)) → ∀ b, + (ν e).probability (fun seed => decide (complete e seed a = b)) ≤ ε e) + (δ : ℝ) (hδ : ∀ e, ε e ≤ δ) : + (G.completedGame ν complete).value ≤ G.value + δ := by + apply (G.completed_value_le ν complete legalL legalR agrees ε hε marginal).trans + apply add_le_add (le_refl G.value) + unfold FiniteDistribution.expectation + calc + _ ≤ ∑ e, G.occurrences.weight e * δ := by + apply Finset.sum_le_sum + intro e _ + exact mul_le_mul_of_nonneg_left (hδ e) (G.occurrences.nonnegative e) + _ = δ := by rw [← Finset.sum_mul, G.occurrences.normalized, one_mul] + +theorem completed_value_eq_one (ν : ∀ e, FiniteDistribution (Seed e)) + (complete : ∀ e, Seed e → A → B) + (legalL : ∀ x, L x ↪ A) (legalR : ∀ y, R y ↪ B) + (agrees : ∀ e seed l, complete e seed (legalL (G.left e) l) = + legalR (G.right e) (G.projection e l)) + (hcomplete : G.value = 1) : (G.completedGame ν complete).value = 1 := by + apply le_antisymm (G.completedGame ν complete).value_le_one + obtain ⟨s, hs⟩ := G.exists_optimal_strategy + calc + 1 = G.success s := (hs.trans hcomplete).symm + _ = (G.completedGame ν complete).success (liftStrategy legalL legalR s) := + (G.completed_success_lift ν complete legalL legalR agrees s).symm + _ ≤ _ := (G.completedGame ν complete).success_le_value _ + +end Completion + +variable [Fintype Q₁] [Fintype Q₂] [∀ x, Fintype (L x)] + {A B : Type*} [Fintype A] [Fintype B] + +theorem embedded_fiber_le_two {L₀ R₀ B₀ : Type*} [Fintype L₀] + (j : R₀ ↪ B₀) (p : L₀ → R₀) + (hsmall : ∀ r, Fintype.card {l : L₀ // p l = r} ≤ 2) (b : B₀) : + Fintype.card {l : L₀ // j (p l) = b} ≤ 2 := by + by_cases hb : ∃ r : R₀, j r = b + · obtain ⟨r, rfl⟩ := hb + let e : {l : L₀ // j (p l) = j r} ≃ {l : L₀ // p l = r} := + Equiv.subtypeEquivRight (fun l => + ⟨fun h => j.injective h, fun h => congrArg j h⟩) + exact (Fintype.card_congr e).le.trans (hsmall r) + · have hzero : Fintype.card {l : L₀ // j (p l) = b} = 0 := + Fintype.card_eq_zero_iff.mpr ⟨fun l => hb ⟨p l.val, l.property⟩⟩ + rw [hzero] + exact Nat.zero_le 2 + +structure CompletionFamily (legalL : ∀ x, L x ↪ A) (legalR : ∀ y, R y ↪ B) where + size : E → Nat + positive : ∀ e, 0 < size e + map : ∀ e, Fin (size e) → A → B + agrees : ∀ e seed l, map e seed (legalL (G.left e) l) = + legalR (G.right e) (G.projection e l) + exact_two : ∀ e seed b, Fintype.card {a : A // map e seed a = b} = 2 + illegal_probability : ∀ e (a : Illegal (legalL (G.left e))) (b : B), + uniformProbability (fun seed => map e seed a.val = b) ≤ + 2 / (Fintype.card A - Fintype.card (L (G.left e)) : Nat) + +omit [Fintype Q₁] [Fintype Q₂] in +theorem completionFamily_nonempty + (legalL : ∀ x, L x ↪ A) (legalR : ∀ y, R y ↪ B) + (hsmall : ∀ e b, Fintype.card {l : L (G.left e) // G.projection e l = b} ≤ 2) + (hcard : Fintype.card A = 2 * Fintype.card B) : + Nonempty (G.CompletionFamily legalL legalR) := by + have hexists (e : E) := exists_completion_sampler (legalL (G.left e)) + (fun l => legalR (G.right e) (G.projection e l)) + (embedded_fiber_le_two (legalR (G.right e)) (G.projection e) (hsmall e)) hcard + choose n hn sampler hext hexact hprob using hexists + refine ⟨{ + size := n + positive := hn + map := sampler + agrees := hext + exact_two := hexact + illegal_probability := ?_ }⟩ + intro e a b + simpa only [← Nat.card_eq_fintype_card] using (hprob e a b).2 + +namespace CompletionFamily +variable {G} {legalL : ∀ x, L x ↪ A} {legalR : ∀ y, R y ↪ B} + +def seedLaw (F : G.CompletionFamily legalL legalR) (e : E) : + FiniteDistribution (Fin (F.size e)) := by + letI : Nonempty (Fin (F.size e)) := ⟨⟨0, F.positive e⟩⟩ + exact FiniteDistribution.uniform (Fin (F.size e)) + +def game (F : G.CompletionFamily legalL legalR) : + OccurrenceGame (Σ e, Fin (F.size e)) Q₁ Q₂ A B := + G.completedGame F.seedLaw F.map + +omit [Fintype Q₁] [Fintype Q₂] [Fintype B] in +theorem marginal (F : G.CompletionFamily legalL legalR) (e : E) + (a : A) (ha : a ∉ Set.range (legalL (G.left e))) (b : B) : + (F.seedLaw e).probability (fun seed => decide (F.map e seed a = b)) ≤ + 2 / (Fintype.card A - Fintype.card (L (G.left e)) : Nat) := by + let : Nonempty (Fin (F.size e)) := ⟨⟨0, F.positive e⟩⟩ + change (FiniteDistribution.uniform (Fin (F.size e))).probability _ ≤ _ + rw [probability_uniform_eq_uniformProbability] + exact F.illegal_probability e ⟨a, ha⟩ b + +variable [∀ y, Fintype (R y)] [∀ x, Nonempty (L x)] [∀ y, Nonempty (R y)] + [Nonempty A] [Nonempty B] + +theorem value_le (F : G.CompletionFamily legalL legalR) : + F.game.value ≤ G.value + G.occurrences.expectation + (fun e => 2 / (Fintype.card A - Fintype.card (L (G.left e)) : Nat)) := by + apply G.completed_value_le F.seedLaw F.map legalL legalR F.agrees + · intro e + exact div_nonneg (by norm_num) (Nat.cast_nonneg _) + · exact F.marginal + +theorem value_le_of_bound (F : G.CompletionFamily legalL legalR) + (δ : ℝ) (hδ : ∀ e, + 2 / (Fintype.card A - Fintype.card (L (G.left e)) : Nat) ≤ δ) : + F.game.value ≤ G.value + δ := by + apply G.completed_value_le_of_bound F.seedLaw F.map legalL legalR F.agrees + (fun e => 2 / (Fintype.card A - Fintype.card (L (G.left e)) : Nat)) + (fun e => div_nonneg (by norm_num) (Nat.cast_nonneg _)) F.marginal δ hδ + +theorem value_eq_one (F : G.CompletionFamily legalL legalR) (hcomplete : G.value = 1) : + F.game.value = 1 := + G.completed_value_eq_one F.seedLaw F.map legalL legalR F.agrees hcomplete + +end CompletionFamily + +end LegalProjectionGame + +end +end PerfectCompleteness.CompletionSoundness + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/ExactPreliminaryTarget.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/ExactPreliminaryTarget.lean new file mode 100644 index 0000000000000000000000000000000000000000..777d07bfa00bfcf3a328e39d90ac790d7fff7878 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/ExactPreliminaryTarget.lean @@ -0,0 +1,178 @@ +import OAI.Computability.PerfectCompleteness.Machines.EncodingLemmas +import OAI.Computability.PerfectCompleteness.Reduction.CanonicalNamedGame +import OAI.Computability.PerfectCompleteness.Reduction.CompletedVisitOrder +import OAI.Computability.PerfectCompleteness.Reduction.TargetGameLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.ExactPreliminaryTarget + +open UniqueGamesTheorem.Foundations.Games +open CompletionSoundness CompletionSoundness.LegalProjectionGame +open scoped Classical + +noncomputable section + +variable {branch : Nat → Nat} {n t v m : Nat} [NeZero m] + (clauses : Fin m → SourceClause.NormalizedClause v) (rows repeats : Nat → Nat) + (hn : 0 < n) (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) (δ : ℚ) + +local notation "F" => FinitePreliminaryCompletion.blockFamily clauses branch n t rows repeats +local notation "q" => FinitePreliminaryCompletion.alphabet branch n t δ +local notation "family" => FinitePreliminaryCompletion.actualFamily + (t := t) clauses rows repeats hn hbranch hrows δ +local notation "order" => CompletedVisitOrder.completedOrder + (t := t) clauses rows repeats hn hbranch hrows δ +local notation "rawOrder" => CompletedVisitOrder.rawOrder + (t := t) clauses rows repeats hn hbranch hrows δ +local notation "coverage" => CompletedVisitOrder.mem_rawOrder + (t := t) clauses rows repeats hn hbranch hrows δ + +local instance leftVertex_fintype : Fintype (CanonicalGame.LeftVertex F) := Fintype.ofFinite _ +local instance rightVertex_fintype : Fintype (CanonicalGame.RightVertex F) := Fintype.ofFinite _ +local instance leftLabel_fintype (x : CanonicalGame.LeftVertex F) : + Fintype (CanonicalGame.LeftLabel F x) := Fintype.ofFinite _ +local instance rightLabel_fintype (y : CanonicalGame.RightVertex F) : + Fintype (CanonicalGame.RightLabel F y) := Fintype.ofFinite _ +local instance rightAlphabet_nonempty : Nonempty (Fin q) := + ⟨⟨0, CanonicalLocalCompletion.alphabet_positive (TreeCanonical.locationCount branch n t) δ⟩⟩ +local instance leftAlphabet_nonempty : Nonempty (Fin (2 * q)) := + ⟨⟨0, Nat.mul_pos (by decide) + (CanonicalLocalCompletion.alphabet_positive (TreeCanonical.locationCount branch n t) δ)⟩⟩ + +def namedGame := CanonicalNamedGame.rename F rawOrder coverage (family).game + +def entry (e : CompletedSignedLaw.Completed (t := t) clauses rows repeats hn hbranch hrows δ) : + Edge (rawOrder).length (rawOrder).length q where + left := (namedGame (t := t) clauses rows repeats hn hbranch hrows δ).left e + right := (namedGame (t := t) clauses rows repeats hn hbranch hrows δ).right e + projection := ProjectionTable.ofMap ((family).map e.1 e.2) (by + intro b + rw [Fintype.card_eq_nat_card] + have h := (family).exact_two e.1 e.2 b + rw [Fintype.card_eq_nat_card] at h + exact h) + +theorem entry_satisfied (e : CompletedSignedLaw.Completed (t := t) clauses rows repeats hn hbranch hrows δ) + (a : Fin (rawOrder).length → Fin (2 * q)) (b : Fin (rawOrder).length → Fin q) : + (entry (t := t) clauses rows repeats hn hbranch hrows δ e).satisfied a b = + (namedGame (t := t) clauses rows repeats hn hbranch hrows δ).wins (a, b) e := by + simp only [Edge.satisfied, entry, ProjectionTable.ofMap_apply] + exact decide_eq_decide.mpr Iff.rfl + +def construct : Instance q where + leftVertices := (rawOrder).length + rightVertices := (rawOrder).length + edges := (order).map (entry (t := t) clauses rows repeats hn hbranch hrows δ) + nonempty := by + intro hempty + have h := List.map_eq_nil_iff.mp hempty + exact CompletedVisitOrder.completedOrder_nonempty + (t := t) clauses rows repeats hn hbranch hrows δ h + +theorem edge_count : + (construct (t := t) clauses rows repeats hn hbranch hrows δ).edges.length = + SignedMultiplicity.denominator branch n t rows repeats hn hbranch hrows q * + m ^ TreeCanonical.locationCount branch n t := by + change ((order).map (entry (t := t) clauses rows repeats hn hbranch hrows δ)).length = _ + rw [List.length_map] + exact CompletedVisitOrder.completedOrder_length + (t := t) clauses rows repeats hn hbranch hrows δ + +theorem leftVertices_eq_edges : + (construct (t := t) clauses rows repeats hn hbranch hrows δ).leftVertices = + (construct (t := t) clauses rows repeats hn hbranch hrows δ).edges.length := by + exact (CompletedVisitOrder.rawOrder_length + (t := t) clauses rows repeats hn hbranch hrows δ).trans + (edge_count (t := t) clauses rows repeats hn hbranch hrows δ).symm + +theorem rightVertices_eq_edges : + (construct (t := t) clauses rows repeats hn hbranch hrows δ).rightVertices = + (construct (t := t) clauses rows repeats hn hbranch hrows δ).edges.length := + leftVertices_eq_edges (t := t) clauses rows repeats hn hbranch hrows δ + +theorem rate_eq (a : Fin (rawOrder).length → Fin (2 * q)) (b : Fin (rawOrder).length → Fin q) : + (countSatisfied a b (construct (t := t) clauses rows repeats hn hbranch hrows δ).edges : ℝ) / + (construct (t := t) clauses rows repeats hn hbranch hrows δ).edges.length = + (namedGame (t := t) clauses rows repeats hn hbranch hrows δ).success (a, b) := by + change (countSatisfied a b + ((order).map (entry (t := t) clauses rows repeats hn hbranch hrows δ)) : ℝ) / + ((order).map (entry (t := t) clauses rows repeats hn hbranch hrows δ)).length = _ + rw [RoundedTarget.countSatisfied_eq_filter] + simp only [List.filter_map, List.length_map, Function.comp_def] + have h := CompletedVisitOrder.completedOrder_probability + (t := t) clauses rows repeats hn hbranch hrows δ + (fun e => (entry (t := t) clauses rows repeats hn hbranch hrows δ e).satisfied a b) + simpa only [Function.comp_def, entry_satisfied, OccurrenceGame.success, + namedGame, CanonicalNamedGame.rename_occurrences] using h + +theorem value_eq : + (construct (t := t) clauses rows repeats hn hbranch hrows δ).value = + FinitePreliminaryCompletion.actualValue + (t := t) clauses rows repeats hn hbranch hrows δ := by + have hq : 0 < q := + CanonicalLocalCompletion.alphabet_positive (TreeCanonical.locationCount branch n t) δ + have hnamed : (construct (t := t) clauses rows repeats hn hbranch hrows δ).value = + (namedGame (t := t) clauses rows repeats hn hbranch hrows δ).value := by + apply le_antisymm + · obtain ⟨s, hs⟩ := + (construct (t := t) clauses rows repeats hn hbranch hrows δ).maxSatisfied_attained hq + unfold Instance.value + rw [← hs] + exact (rate_eq (t := t) clauses rows repeats hn hbranch hrows δ s.1 s.2).le.trans + ((namedGame (t := t) clauses rows repeats hn hbranch hrows δ).success_le_value s) + · obtain ⟨s, hs⟩ := + (namedGame (t := t) clauses rows repeats hn hbranch hrows δ).exists_optimal_strategy + calc + (namedGame (t := t) clauses rows repeats hn hbranch hrows δ).value = + (namedGame (t := t) clauses rows repeats hn hbranch hrows δ).success s := hs.symm + _ = (countSatisfied s.1 s.2 + (construct (t := t) clauses rows repeats hn hbranch hrows δ).edges : ℝ) / + (construct (t := t) clauses rows repeats hn hbranch hrows δ).edges.length := + (rate_eq (t := t) clauses rows repeats hn hbranch hrows δ s.1 s.2).symm + _ ≤ (construct (t := t) clauses rows repeats hn hbranch hrows δ).value := + (construct (t := t) clauses rows repeats hn hbranch hrows δ).rate_le_value s + exact hnamed.trans (CanonicalNamedGame.rename_value_eq F rawOrder coverage (family).game) + +theorem value_le (hδ : 0 < δ) : + (construct (t := t) clauses rows repeats hn hbranch hrows δ).value ≤ + (PreliminarySampler.game clauses branch n t rows repeats hn hbranch hrows).value + + (δ : ℝ) / 3 := by + rw [value_eq] + exact FinitePreliminaryCompletion.actualValue_le + (t := t) clauses rows repeats hn hbranch hrows δ hδ + +theorem perfectlyComplete (assignment : Fin v → Bool) + (hsat : ∀ c, (clauses c).clause.eval assignment = true) : + PerfectlyComplete (construct (t := t) clauses rows repeats hn hbranch hrows δ) := by + apply ((construct (t := t) clauses rows repeats hn hbranch hrows δ).perfectlyComplete_iff_value_eq_one + (CanonicalLocalCompletion.alphabet_positive (TreeCanonical.locationCount branch n t) δ)).2 + rw [value_eq] + exact FinitePreliminaryCompletion.actualValue_of_satisfying + (t := t) clauses rows repeats hn hbranch hrows δ assignment hsat + +theorem encoding_length_le : + let target := construct (t := t) clauses rows repeats hn hbranch hrows δ + let N := target.edges.length + (Encoding.gameBits target).length ≤ + 2 * N + q + N + 4 + N * (2 * N + 2 * q * q + 2 * q + 2) := by + dsimp only + have h := Encoding.gameBits_length_le_of_edge_count + (construct (t := t) clauses rows repeats hn hbranch hrows δ) + (construct (t := t) clauses rows repeats hn hbranch hrows δ).edges.length le_rfl + have arithmetic (l r N : Nat) (hl : l = N) (hr : r = N) : + l + r + q + N + 4 + N * (l + r + 2 * q * q + 2 * q + 2) = + 2 * N + q + N + 4 + N * (2 * N + 2 * q * q + 2 * q + 2) := by + simp only [hl, hr, two_mul] + exact h.trans_eq (arithmetic _ _ _ + (leftVertices_eq_edges (t := t) clauses rows repeats hn hbranch hrows δ) + (rightVertices_eq_edges (t := t) clauses rows repeats hn hbranch hrows δ)) + +end +end PerfectCompleteness.ExactPreliminaryTarget + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/FinitePreliminaryCompletion.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/FinitePreliminaryCompletion.lean new file mode 100644 index 0000000000000000000000000000000000000000..b104314c0ece8f5fb80e758247cb35fccbccfa9d --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/FinitePreliminaryCompletion.lean @@ -0,0 +1,222 @@ +import OAI.Computability.PerfectCompleteness.Construction.CanonicalLocalCompletion +import OAI.Computability.PerfectCompleteness.Construction.FlexibleLocalCompletionLemmas +import OAI.Computability.PerfectCompleteness.Reduction.FixedQueryCodec + +namespace OAI + +section + +namespace PerfectCompleteness.FinitePreliminaryCompletion + +open MixedSupport CanonicalKeys CanonicalEdges CanonicalLabelEncoding +open UniqueGamesTheorem.Foundations.Games +open CompletionSoundness CompletionSoundness.LegalProjectionGame +open scoped Classical + +noncomputable section + +variable {branch : Nat → Nat} {n t v m : Nat} {rows repeats : Nat → Nat} + +abbrev alphabet (branch : Nat → Nat) (n t : Nat) (δ : ℚ) : Nat := + CanonicalLocalCompletion.alphabet (TreeCanonical.locationCount branch n t) δ + +def finiteInput (δ : ℚ) (data : MetadataFreeTape.Input branch n t rows repeats) : + LocalCompletionFamily.Input (alphabet branch n t δ) := + CanonicalPartialTable.lookup + (CanonicalLocalCompletion.alphabet_positive (TreeCanonical.locationCount branch n t) δ) + (CanonicalLocalCompletion.partitionWidth_le_alphabet + (TreeCanonical.locationCount branch n t) δ) + (FixedQueryCodec.partialInput data) + +def finiteResult (δ : ℚ) (data : MetadataFreeTape.Input branch n t rows repeats) : + LocalCompletionFamily.Result (alphabet branch n t δ) := + LocalCompletionFamily.lookup + (CanonicalLocalCompletion.alphabet_positive (TreeCanonical.locationCount branch n t) δ) + (finiteInput δ data) + +theorem finiteResult_correct (δ : ℚ) + (data : MetadataFreeTape.Input branch n t rows repeats) : + LocalCompletionFamily.Correct (finiteInput δ data) (finiteResult δ data) := + LocalCompletionFamily.lookup_correct + (CanonicalLocalCompletion.alphabet_positive (TreeCanonical.locationCount branch n t) δ) + (finiteInput δ data) + (FixedQueryCodec.partialInput_admissible + (CanonicalLocalCompletion.alphabet_positive (TreeCanonical.locationCount branch n t) δ) + (CanonicalLocalCompletion.partitionWidth_le_alphabet + (TreeCanonical.locationCount branch n t) δ) data) + +abbrev blockFamily (clauses : Fin m → SourceClause.NormalizedClause v) + (branch : Nat → Nat) (n t : Nat) (rows repeats : Nat → Nat) := + HierarchicalGame.toBlockFamily + (PreliminarySampler.family clauses branch n t rows repeats) + +variable (clauses : Fin m → SourceClause.NormalizedClause v) + +local notation "F" => blockFamily clauses branch n t rows repeats + +def rawInput (δ : ℚ) (e : PreliminarySampler.Raw clauses branch n t rows repeats) : + LocalCompletionFamily.Input (alphabet branch n t δ) := + finiteInput δ (MetadataFreeTape.encodeRaw clauses rows repeats e) + +theorem rawInput_mask (δ : ℚ) + (e : PreliminarySampler.Raw clauses branch n t rows repeats) : + (rawInput clauses δ e).1 = paddedMask (CanonicalGame.leftKey F e) := by + unfold rawInput finiteInput + rw [FixedQueryCodec.partialInput_encodeRaw, CanonicalPartialTable.lookup_mask_actual, + FixedQueryCodec.leftTable_key] + rfl + +theorem rawInput_image_legal (δ : ℚ) + (e : PreliminarySampler.Raw clauses branch n t rows repeats) + (P : CanonicalGame.LeftLabel F (CanonicalGame.leftAt F e)) : + (rawInput clauses δ e).2 + (CanonicalLocalCompletion.legalL F δ (CanonicalGame.leftAt F e) P) = + CanonicalLocalCompletion.legalR F δ (CanonicalGame.rightAt F e) + (CanonicalGame.edge F e P) := by + let slots := MetadataFreeSampler.sourceSlots clauses e.1.1 + let arrays := WholeArraySampler.evaluate rows repeats + (GeometricPath.leafPath e.1.2) slots e.2.1 + let S := TreeCanonical.numberedSlots slots + let f := TreeCanonical.numberedFunction slots (HierarchicalArrays.fullJoint arrays) + let θ := FixedQueryCodec.rawTestIndex clauses e + let Pencoded : Label S (FixedQueryCodec.leftEncode branch n rows ∘ f) := + CanonicalCoarseningEncoding.transportFine S f + (FixedQueryCodec.leftEncode branch n rows) + (FixedQueryCodec.leftEncode_injective branch n rows) P + have hfinite := CanonicalPartialTable.image_actual_legal + (CanonicalLocalCompletion.alphabet_positive (TreeCanonical.locationCount branch n t) δ) + (CanonicalLocalCompletion.partitionWidth_le_alphabet + (TreeCanonical.locationCount branch n t) δ) + S (FixedQueryCodec.leftTable arrays) (FixedQueryCodec.outputMap θ) Pencoded + have hcoarse := CanonicalCoarseningEncoding.labelEmbedding_coarsen .right + (CanonicalLocalCompletion.partitionWidth_le_alphabet + (TreeCanonical.locationCount branch n t) δ) + S f (FixedQueryCodec.project θ) (FixedQueryCodec.leftEncode branch n rows) + (FixedQueryCodec.rightEncode θ) (FixedQueryCodec.outputMap θ) + (FixedQueryCodec.leftEncode_injective branch n rows) + (FixedQueryCodec.rightEncode_injective θ) (FixedQueryCodec.outputMap_leftEncode θ) P + unfold rawInput finiteInput + rw [FixedQueryCodec.partialInput_encodeRaw] + exact hfinite.trans hcoarse.symm + +local instance leftVertex_fintype : Fintype (CanonicalGame.LeftVertex F) := + Fintype.ofFinite _ + +local instance rightVertex_fintype : Fintype (CanonicalGame.RightVertex F) := + Fintype.ofFinite _ + +local instance leftLabel_fintype (x : CanonicalGame.LeftVertex F) : + Fintype (CanonicalGame.LeftLabel F x) := Fintype.ofFinite _ + +local instance rightLabel_fintype (y : CanonicalGame.RightVertex F) : + Fintype (CanonicalGame.RightLabel F y) := Fintype.ofFinite _ + +local instance rightAlphabet_nonempty (δ : ℚ) : Nonempty (Fin (alphabet branch n t δ)) := + ⟨⟨0, CanonicalLocalCompletion.alphabet_positive (TreeCanonical.locationCount branch n t) δ⟩⟩ + +local instance leftAlphabet_nonempty (δ : ℚ) : Nonempty (Fin (2 * alphabet branch n t δ)) := + ⟨⟨0, Nat.mul_pos (by decide) + (CanonicalLocalCompletion.alphabet_positive (TreeCanonical.locationCount branch n t) δ)⟩⟩ + +theorem compatible (μ : FiniteDistribution (PreliminarySampler.Raw clauses branch n t rows repeats)) + (δ : ℚ) : + FlexibleLocalCompletion.Compatible (CanonicalGame.game F μ) + (CanonicalLocalCompletion.legalL F δ) (CanonicalLocalCompletion.legalR F δ) + (rawInput clauses δ) where + mask e a := by + rw [rawInput_mask] + exact paddedMask_eq_true_iff (CanonicalGame.leftKey F e) + (CanonicalLocalCompletion.partitionWidth_le_leftAlphabet + (TreeCanonical.locationCount branch n t) δ) a + image e P := rawInput_image_legal clauses δ e P + +def family (μ : FiniteDistribution (PreliminarySampler.Raw clauses branch n t rows repeats)) + (δ : ℚ) : + (CanonicalGame.game F μ).CompletionFamily + (CanonicalLocalCompletion.legalL F δ) (CanonicalLocalCompletion.legalR F δ) := + FlexibleLocalCompletion.family (CanonicalGame.game F μ) + (CanonicalLocalCompletion.legalL F δ) (CanonicalLocalCompletion.legalR F δ) + (rawInput clauses δ) (compatible clauses μ δ) + (CanonicalLocalCompletion.alphabet_positive (TreeCanonical.locationCount branch n t) δ) + (by + intro e b + rw [Fintype.card_eq_nat_card] + have h := CanonicalLocalCompletion.small F μ e b + rw [Fintype.card_eq_nat_card] at h + exact h) + +@[simp] theorem family_size + (μ : FiniteDistribution (PreliminarySampler.Raw clauses branch n t rows repeats)) + (δ : ℚ) (e : PreliminarySampler.Raw clauses branch n t rows repeats) : + (family clauses μ δ).size e = LocalCompletionFamily.activeCount + (finiteResult δ (MetadataFreeTape.encodeRaw clauses rows repeats e)) := rfl + +@[simp] theorem family_map + (μ : FiniteDistribution (PreliminarySampler.Raw clauses branch n t rows repeats)) + (δ : ℚ) (e : PreliminarySampler.Raw clauses branch n t rows repeats) : + (family clauses μ δ).map e = LocalCompletionFamily.table + (finiteResult δ (MetadataFreeTape.encodeRaw clauses rows repeats e)) := rfl + +theorem family_size_le + (μ : FiniteDistribution (PreliminarySampler.Raw clauses branch n t rows repeats)) + (δ : ℚ) (e : PreliminarySampler.Raw clauses branch n t rows repeats) : + (family clauses μ δ).size e ≤ 2 * alphabet branch n t δ := + LocalCompletionFamily.activeCount_le _ + +theorem family_value_le + (μ : FiniteDistribution (PreliminarySampler.Raw clauses branch n t rows repeats)) + (δ : ℚ) (hδ : 0 < δ) : + (family clauses μ δ).game.value ≤ (CanonicalGame.game F μ).value + (δ : ℝ) / 3 := by + apply (family clauses μ δ).value_le_of_bound ((δ : ℝ) / 3) + intro e + have hδreal : (0 : ℝ) < (δ : ℝ) := by exact_mod_cast hδ + have h := CompletionParameters.residual_le_third + (CanonicalLocalCompletion.alphabet_positive (TreeCanonical.locationCount branch n t) δ) + (CanonicalLocalCompletion.leftLabel_card_le F δ (CanonicalGame.leftAt F e)) hδreal + (CompletionAlphabet.size_budget + (CanonicalKeyEncoding.partitionWidth (TreeCanonical.locationCount branch n t)) δ hδ) + simp only [Fintype.card_fin] + rw [Fintype.card_eq_nat_card] + rw [Fintype.card_eq_nat_card] at h + simpa only [CanonicalGame.game] using h + +theorem family_value_of_satisfying + (μ : FiniteDistribution (PreliminarySampler.Raw clauses branch n t rows repeats)) + (δ : ℚ) (assignment : Fin v → Bool) + (hsat : ∀ c, (clauses c).clause.eval assignment = true) : + (family clauses μ δ).game.value = 1 := by + apply (family clauses μ δ).value_eq_one + exact HierarchicalGame.value_eq_one + (PreliminarySampler.family clauses branch n t rows repeats) μ assignment hsat + +def actualFamily [NeZero m] (rows repeats : Nat → Nat) (hn : 0 < n) + (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) (δ : ℚ) := + family clauses (PreliminarySampler.law (t := t) clauses rows repeats hn hbranch hrows) δ + +def actualValue [NeZero m] (rows repeats : Nat → Nat) (hn : 0 < n) + (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) (δ : ℚ) : ℝ := + (actualFamily (t := t) clauses rows repeats hn hbranch hrows δ).game.value + +theorem actualValue_le [NeZero m] (rows repeats : Nat → Nat) (hn : 0 < n) + (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) + (δ : ℚ) (hδ : 0 < δ) : + actualValue (t := t) clauses rows repeats hn hbranch hrows δ ≤ + (PreliminarySampler.game clauses branch n t rows repeats hn hbranch hrows).value + + (δ : ℝ) / 3 := by + exact family_value_le clauses + (PreliminarySampler.law (t := t) clauses rows repeats hn hbranch hrows) δ hδ + +theorem actualValue_of_satisfying [NeZero m] (rows repeats : Nat → Nat) (hn : 0 < n) + (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) + (δ : ℚ) (assignment : Fin v → Bool) + (hsat : ∀ c, (clauses c).clause.eval assignment = true) : + actualValue (t := t) clauses rows repeats hn hbranch hrows δ = 1 := + family_value_of_satisfying clauses + (PreliminarySampler.law (t := t) clauses rows repeats hn hbranch hrows) δ assignment hsat + +end +end PerfectCompleteness.FinitePreliminaryCompletion + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedCallBudgetLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedCallBudgetLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..00cb1a3aaea6380f74d263e5cbeb00090317e966 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedCallBudgetLemmas.lean @@ -0,0 +1,163 @@ +import OAI.Computability.PerfectCompleteness.Construction.OriginalChildScalarAssemblyLemmas +import OAI.Computability.PerfectCompleteness.Foundations.CommonAccuracy +import OAI.Computability.PerfectCompleteness.Foundations.WholeCutCallsLemmas + +namespace OAI + + +namespace PerfectCompleteness.FixedCallBudget + +open RecursiveSpaces DescendantSpaces +open scoped BigOperators + +noncomputable section + +def pairCount (rows repeats : Nat → Nat) (root cutoff : Nat) : Nat := + rows cutoff + OriginalCutCalls.count rows repeats root cutoff + +def budget (depth : Nat) (rows repeats : Nat → Nat) : Nat := + 1 + ∑ root : Fin (depth + 1), ∑ cutoff : Fin (depth + 1), + pairCount rows repeats root.val cutoff.val + +theorem budget_pos (depth : Nat) (rows repeats : Nat → Nat) : + 0 < budget depth rows repeats := by + unfold budget + omega + +theorem pairCount_le {depth root cutoff : Nat} (rows repeats : Nat → Nat) + (hroot : root ≤ depth) (hcutoff : cutoff ≤ depth) : + pairCount rows repeats root cutoff ≤ budget depth rows repeats := by + let a : Fin (depth + 1) := ⟨root, Nat.lt_succ_of_le hroot⟩ + let b : Fin (depth + 1) := ⟨cutoff, Nat.lt_succ_of_le hcutoff⟩ + have hinner : pairCount rows repeats root cutoff ≤ + ∑ j : Fin (depth + 1), pairCount rows repeats a.val j.val := + Finset.single_le_sum (fun j _ => Nat.zero_le + (pairCount rows repeats a.val j.val)) (Finset.mem_univ b) + have houter : (∑ j : Fin (depth + 1), pairCount rows repeats a.val j.val) ≤ + ∑ i : Fin (depth + 1), ∑ j : Fin (depth + 1), + pairCount rows repeats i.val j.val := + Finset.single_le_sum (fun i _ => Nat.zero_le + (∑ j : Fin (depth + 1), pairCount rows repeats i.val j.val)) + (Finset.mem_univ a) + unfold budget + omega + +theorem original_calls_le {depth root cutoff : Nat} {branch : Nat → Nat} + (rows repeats : Nat → Nat) (p : Path branch root cutoff) + (hroot : root ≤ depth) : + Fintype.card (OriginalCutCalls.Index rows repeats p) ≤ budget depth rows repeats := by + rw [OriginalCutCalls.card_eq_count] + have h := pairCount_le rows repeats hroot (p.height_le.trans hroot) + unfold pairCount at h + omega + +theorem modified_calls_le {depth root cutoff : Nat} {branch : Nat → Nat} + (rows repeats : Nat → Nat) (p : Path branch root cutoff) + (hroot : root ≤ depth) : + Fintype.card (WholeCutCalls.Index rows repeats p) ≤ budget depth rows repeats := by + rw [WholeCutCalls.card_eq_formula] + have h := pairCount_le rows repeats hroot (p.height_le.trans hroot) + unfold pairCount OriginalCutCalls.count at h + omega + +theorem copied_calls_le {calls copies depth : Nat} (rows repeats : Nat → Nat) + (hcalls : calls ≤ budget depth rows repeats) : + Fintype.card (Fin copies × Fin calls) ≤ copies * budget depth rows repeats := by + simpa only [Fintype.card_prod, Fintype.card_fin] using + Nat.mul_le_mul_left copies hcalls + +theorem child_bound_mono {calls calls' : Nat} (hcalls : calls ≤ calls') + (branch : Nat → Nat) (height sourceLength : Nat) (rows : Nat → Nat) : + ChildBlockCardinality.bound branch height sourceLength calls rows ≤ + ChildBlockCardinality.bound branch height sourceLength calls' rows := by + apply Nat.mul_le_mul_right + apply pow_le_pow_right₀ _ hcalls + unfold TreeCardinality.functionBound + exact one_le_pow₀ (by decide : (1 : Nat) ≤ 2) + +theorem copied_calls_with_extra_le {calls copies extra depth : Nat} + (rows repeats : Nat → Nat) (hcalls : calls ≤ budget depth rows repeats) : + Fintype.card ((Fin copies × Fin calls) ⊕ Fin extra) ≤ + copies * budget depth rows repeats + extra := by + simpa only [Fintype.card_sum, Fintype.card_prod, Fintype.card_fin] using + Nat.add_le_add_right (Nat.mul_le_mul_left copies hcalls) extra + +end +end PerfectCompleteness.FixedCallBudget + + +namespace PerfectCompleteness.FixedParameters + +open FixedRows AscendingBranching + +noncomputable section + +def calls {δ : ℚ} (plan : Plan δ) : Nat := + 2 * FixedCallBudget.budget plan.depth (rows plan) (repeats plan) + 1 + +structure Parameters (δ : ℚ) (positive : 0 < δ) where + plan : Plan δ + accuracy : ℝ + accuracy_pos : 0 < accuracy + accuracy_small : ∀ j ≤ plan.depth, accuracy < CommonAccuracy.tolerance plan j + alphabetCost : Nat + alphabetCost_pos : 0 < alphabetCost + alphabetCost_bound : SourceOddLists.alphabetLog (cutoff plan positive) + (sourceLength plan positive) ≤ alphabetCost + cubeSize : Nat → Nat + cube_errors : ∀ n, + CubeErrors + (ChildBlockCardinality.bound (fun k => cubeSize k ^ 3) n + (sourceLength plan positive) (calls plan) (rows plan) : ℝ) + (FixedBranching.cleanRate alphabetCost + (ChildBlockCardinality.bound (fun k => cubeSize k ^ 3) n + (sourceLength plan positive) (calls plan) (rows plan) : ℝ)) + accuracy (cubeSize n) + +theorem exists_parameters {δ : ℚ} (hδ : 0 < δ) (hδ' : δ < 1) : + Nonempty (Parameters δ hδ) := by + obtain ⟨plan⟩ := exists_plan hδ hδ' + obtain ⟨accuracy, haccuracy, hsmall⟩ := CommonAccuracy.exists_accuracy plan hδ + obtain ⟨cost, hcost, hcostBound, size, hsize⟩ := + FixedSourceBranching.exists_source_branching plan hδ + (fun _ => calls plan) haccuracy + refine ⟨{ + plan := plan + accuracy := accuracy + accuracy_pos := haccuracy + accuracy_small := ?_ + alphabetCost := cost + alphabetCost_pos := hcost + alphabetCost_bound := hcostBound + cubeSize := size + cube_errors := hsize }⟩ + intro j hj + simpa only [CommonAccuracy.tolerance, lt_min_iff] using hsmall j hj + +variable {δ : ℚ} {hδ : 0 < δ} (p : Parameters δ hδ) + +def branch (n : Nat) : Nat := p.cubeSize n ^ 3 +def projectionProbability (n : Nat) : ℚ := 1 / (p.cubeSize n : ℚ) ^ 2 + +theorem branch_pos (n : Nat) : 0 < branch p n := by + have h := (p.cube_errors n).1 + unfold branch + positivity + +theorem projectionProbability_bounds (n : Nat) : + 0 < projectionProbability p n ∧ projectionProbability p n < 1 := + FixedBranching.rational_probability (p.cube_errors n).1 + +theorem source_rate (input : List Bool) (unsat : ¬BinaryLanguage.language input) + (k : Nat) : + ((SourceOddLists.game (cutoff p.plan hδ) + (PCPSource.clauseFamily (BinaryLanguage.totalRename input)) + (sourceLength p.plan hδ)).repetition k).value ≤ + (RepetitionRate.halfRate p.alphabetCost : ℝ) ^ k := + FixedSourceBranching.source_rate p.plan hδ p.alphabetCost + p.alphabetCost_pos p.alphabetCost_bound input unsat k + +end +end PerfectCompleteness.FixedParameters + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedComparisonErrorsLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedComparisonErrorsLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..aa8a8da77d00fd6f6b1021207012e2b188c55cfe --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedComparisonErrorsLemmas.lean @@ -0,0 +1,287 @@ +import Mathlib.Tactic.Ring +import OAI.Computability.PerfectCompleteness.Construction.HierarchicalAdviceFromBuckets +import OAI.Computability.PerfectCompleteness.Decoding.HierarchicalDecoderMeetingLemmas +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalProjectedSliceLemmas +import OAI.Computability.PerfectCompleteness.Reduction.FixedCallBudgetLemmas + +namespace OAI + + +namespace PerfectCompleteness.FixedComparisonErrors + +open FixedParameters ChildBlockCardinality + +noncomputable section + +variable {δ : ℚ} {hδ : 0 < δ} (p : Parameters δ hδ) + +theorem comparison_errors {retained : Nat} (hcalls : retained ≤ calls p.plan) + (height : Nat) : + let L : ℝ := bound (branch p) height (FixedRows.sourceLength p.plan hδ) + retained (FixedRows.rows p.plan) + let m := p.cubeSize height + Real.sqrt (L ^ 2 / (m : ℝ) ^ 3) / 2 < p.accuracy ∧ + Real.sqrt ((1 + L ^ 2 / (m : ℝ) ^ 4) ^ (m ^ 3) - 1) / 2 < p.accuracy ∧ + 2 * ((1 / (m : ℝ) ^ 2) * L / (1 - 1 / (m : ℝ) ^ 2)) < p.accuracy := by + let L : ℝ := bound (branch p) height (FixedRows.sourceLength p.plan hδ) + retained (FixedRows.rows p.plan) + let B : ℝ := bound (branch p) height (FixedRows.sourceLength p.plan hδ) + (calls p.plan) (FixedRows.rows p.plan) + let m := p.cubeSize height + have hL : 0 ≤ L := Nat.cast_nonneg _ + have hB : 0 ≤ B := Nat.cast_nonneg _ + have hLB : L ≤ B := by + dsimp only [L, B] + exact_mod_cast FixedCallBudget.child_bound_mono hcalls (branch p) height + (FixedRows.sourceLength p.plan hδ) (FixedRows.rows p.plan) + have hsq : L ^ 2 ≤ B ^ 2 := (sq_le_sq₀ hL hB).mpr hLB + have hm : (2 : ℝ) ≤ m := by exact_mod_cast (p.cube_errors height).1 + have hm2 : (0 : ℝ) < (m : ℝ) ^ 2 := by positivity + have hprob : (1 : ℝ) / (m : ℝ) ^ 2 < 1 := by + apply (div_lt_one hm2).mpr + nlinarith + have hfixed := (p.cube_errors height).2 + change Real.sqrt (L ^ 2 / (m : ℝ) ^ 3) / 2 < p.accuracy ∧ + Real.sqrt ((1 + L ^ 2 / (m : ℝ) ^ 4) ^ (m ^ 3) - 1) / 2 < p.accuracy ∧ + 2 * ((1 / (m : ℝ) ^ 2) * L / (1 - 1 / (m : ℝ) ^ 2)) < p.accuracy + refine ⟨?_, ?_, ?_⟩ + · apply lt_of_le_of_lt _ hfixed.1 + apply div_le_div_of_nonneg_right _ (by norm_num : (0 : ℝ) ≤ 2) + apply Real.sqrt_le_sqrt + exact div_le_div_of_nonneg_right hsq (by positivity) + · apply lt_of_le_of_lt _ hfixed.2.1 + apply div_le_div_of_nonneg_right _ (by norm_num : (0 : ℝ) ≤ 2) + apply Real.sqrt_le_sqrt + apply sub_le_sub_right + apply pow_le_pow_left₀ (by positivity) + exact add_le_add_right + (div_le_div_of_nonneg_right hsq + (by positivity : (0 : ℝ) ≤ (m : ℝ) ^ 4)) 1 + · apply lt_of_le_of_lt _ hfixed.2.2.1 + apply mul_le_mul_of_nonneg_left _ (by norm_num : (0 : ℝ) ≤ 2) + apply div_le_div_of_nonneg_right _ (by linarith) + exact mul_le_mul_of_nonneg_left hLB (by positivity) + +end +end PerfectCompleteness.FixedComparisonErrors + + +namespace PerfectCompleteness.HierarchicalFixedAdvice + +noncomputable section + +open scoped Classical +open TreeSourceSpaces HierarchicalArrays +open InitialParameters UpperParameterScalars +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype + +variable {δ : ℚ} {hδ : 0 < δ} (p : FixedParameters.Parameters δ hδ) + {branch : Nat → Nat} {t : Nat} {Ω P : Type*} [Fintype Ω] [Fintype P] + (S : HierarchicalAdviceExperiment.Experiment branch (FixedRows.rows p.plan) p.plan.depth t Ω) + +local instance backgroundFintype : Fintype (HierarchicalAdviceExperiment.Background S) := + Fintype.ofFinite _ + +local instance rowSpaceFintype : Fintype (NodeEmbedding.RowSpace S.slots S.upper) := + Fintype.ofFinite _ + +local instance inputFintype : + (b : HierarchicalAdviceExperiment.Background S) → Fintype (HierarchicalAdviceExperiment.Input S b) := + HierarchicalAdviceExperiment.inputFintype S + +local instance inputFiniteDimensional : + (b : HierarchicalAdviceExperiment.Background S) → + FiniteDimensional F2 (HierarchicalAdviceExperiment.Input S b) := + HierarchicalAdviceExperiment.inputFiniteDimensional S + +theorem rows_positive : 0 < FixedRows.rows p.plan (Nodes.height S.upper) := by + exact p.plan.rows_pos (p.plan.depth - Nodes.height S.upper) + +theorem adviceFactor_eq : + HierarchicalAdviceFromBuckets.adviceFactor S p.plan.order (inverse δ) = + q (inverse δ) p.plan.order (FixedRows.rows p.plan (Nodes.height S.upper)) := by + simp only [HierarchicalAdviceFromBuckets.adviceFactor, q, g, h, + div_eq_mul_inv, pow_two] + ring + +theorem paired_error_small : 10 * p.accuracy ≤ simultaneous δ ^ 2 / 16 := by + have hs := p.accuracy_small 0 (Nat.zero_le _) + simp only [CommonAccuracy.tolerance, lt_min_iff] at hs + linarith [hs.2.1] + +theorem coarse_error_small : + 10 * p.accuracy ≤ p.plan.density * + HierarchicalAdviceFromBuckets.adviceFactor S p.plan.order (inverse δ) / 16 := by + rw [adviceFactor_eq p S] + have hs := p.accuracy_small (Nodes.height S.upper) (Nodes.height_le S.upper) + simp only [CommonAccuracy.tolerance, lt_min_iff] at hs + linarith [hs.2.2.1] + +variable (externalLaw : FiniteDistribution P) + (background : P → HierarchicalAdviceExperiment.Background S) + (scalarLaw : P → FiniteDistribution (NodeEmbedding.RowSpace S.slots S.upper)) + +theorem prediction_difference + (hmass : simultaneous δ / 2 ≤ HierarchicalAdviceFromBuckets.usefulProbability + S (useful δ) externalLaw background scalarLaw (rows_positive p S)) + (hpaired : (HierarchicalAdviceFromBuckets.pairedLaw S externalLaw background + scalarLaw (rows_positive p S)).totalVariation + (HierarchicalAgreementMean.referenceLaw S.slots S.upper + (HierarchicalAdviceFromBuckets.backgroundLaw S externalLaw background) + (rows_positive p S)) ≤ 10 * p.accuracy) + (hcoarse : ((HierarchicalAdviceExperiment.originalLaw S p.plan.order).pushforward + (HierarchicalAdviceExperiment.observe S p.plan.order)).totalVariation + ((HierarchicalAdviceExperiment.referenceLaw S + (HierarchicalAdviceFromBuckets.backgroundLaw S externalLaw background) p.plan.order).pushforward (HierarchicalAdviceExperiment.referenceObserve S p.plan.order)) ≤ + 10 * p.accuracy) : + b (useful δ) p.plan.density (inverse δ) p.plan.order + (FixedRows.rows p.plan (Nodes.height S.upper)) ≤ + (HierarchicalAdviceExperiment.originalLaw S p.plan.order).probability + (HierarchicalAdviceExperiment.prediction S (useful δ) p.plan.order p.plan.density) - + rhoPred (useful δ) p.plan.density * + (HierarchicalAdviceExperiment.originalLaw S p.plan.order).probability + (fun x => HierarchicalAdviceExperiment.J S (useful δ) p.plan.order p.plan.density + (HierarchicalAdviceExperiment.observe S p.plan.order x)) := by + have hbound := HierarchicalAdviceFromBuckets.prediction_difference S (useful δ) + externalLaw background scalarLaw (rows_positive p S) (useful_pos hδ).le + (simultaneous δ) (simultaneous_pos hδ).le hmass + (hpaired.trans (paired_error_small p)) + p.plan.order p.plan.density (inverse δ) (10 * p.accuracy) + (inverse_pos hδ) (by unfold inverse; linarith) + p.plan.density_pos p.plan.density_lt p.plan.spectral + (by have := p.accuracy_pos; positivity) (coarse_error_small p S) hcoarse + rw [adviceFactor_eq p S] at hbound + have hfactor : useful δ * p.plan.density * + q (inverse δ) p.plan.order (FixedRows.rows p.plan (Nodes.height S.upper)) / 4 = + b (useful δ) p.plan.density (inverse δ) p.plan.order + (FixedRows.rows p.plan (Nodes.height S.upper)) := by + unfold b rhoPred + ring + rw [hfactor] at hbound + exact hbound + +theorem good_record_mass_ge {R : Type*} [Fintype R] + (hmass : simultaneous δ / 2 ≤ HierarchicalAdviceFromBuckets.usefulProbability + S (useful δ) externalLaw background scalarLaw (rows_positive p S)) + (hpaired : (HierarchicalAdviceFromBuckets.pairedLaw S externalLaw background + scalarLaw (rows_positive p S)).totalVariation + (HierarchicalAgreementMean.referenceLaw S.slots S.upper + (HierarchicalAdviceFromBuckets.backgroundLaw S externalLaw background) + (rows_positive p S)) ≤ 10 * p.accuracy) + (hcoarse : ((HierarchicalAdviceExperiment.originalLaw S p.plan.order).pushforward + (HierarchicalAdviceExperiment.observe S p.plan.order)).totalVariation + ((HierarchicalAdviceExperiment.referenceLaw S + (HierarchicalAdviceFromBuckets.backgroundLaw S externalLaw background) p.plan.order).pushforward (HierarchicalAdviceExperiment.referenceObserve S p.plan.order)) ≤ + 10 * p.accuracy) + (record : Ω × HierarchicalAdviceExperiment.Advice S p.plan.order → R) : + b (useful δ) p.plan.density (inverse δ) p.plan.order + (FixedRows.rows p.plan (Nodes.height S.upper)) ≤ + (HierarchicalAdviceExperiment.originalLaw S p.plan.order).probability + (fun x => HierarchicalAdviceExperiment.J S (useful δ) p.plan.order p.plan.density + (HierarchicalAdviceExperiment.observe S p.plan.order x) && + PositiveFiberMass.goodRecord (HierarchicalAdviceExperiment.originalLaw S p.plan.order) record + (fun y => HierarchicalAdviceExperiment.J S (useful δ) p.plan.order p.plan.density + (HierarchicalAdviceExperiment.observe S p.plan.order y)) + (HierarchicalAdviceExperiment.prediction S (useful δ) p.plan.order p.plan.density) + (rhoPred (useful δ) p.plan.density) (record x)) := + (prediction_difference p S externalLaw background scalarLaw hmass hpaired hcoarse).trans + (HierarchicalAdviceExperiment.prediction_difference_le_good_mass S (useful δ) + (useful_pos hδ).le p.plan.order p.plan.density p.plan.density_pos.le record) + +end +end PerfectCompleteness.HierarchicalFixedAdvice + + +namespace PerfectCompleteness.HierarchicalFixedProjectedMeeting + +noncomputable section + +open scoped Classical TensorProduct +open TreeSourceSpaces HierarchicalArrays HierarchicalProjectedSlice +open UpperParameterScalars +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype +attribute [local instance] RightDecoder.characterFintype RightDecoder.scalarFintype + +variable {δ : ℚ} (plan : FixedRows.Plan δ) (hδ : 0 < δ) + {branch : Nat → Nat} {t : Nat} + (slots projected : RecursiveSpaces.Slots branch plan.depth → Fin t → MixedSupport.Slot) + (projection : ∀ s j, MixedSupport.Projection (slots s j) (projected s j)) + (upper : Nodes branch plan.depth) (lowerLevel : Nat) + (background : HierarchicalMatrixTable.Background + (rows := FixedRows.rows plan) slots upper) + +local instance rowSpaceFintype : Fintype (NodeEmbedding.RowSpace slots upper) := + Fintype.ofFinite _ + +local instance valueFintype : Fintype + (Block (FixedRows.rows plan) upper × + HierarchicalMatrixTable.SideOutput (rows := FixedRows.rows plan) upper) := + Fintype.ofFinite _ + +local instance upperDualFintype : Fintype (Module.Dual F2 (NodeEmbedding.RowSpace slots upper)) := + LeftDecoder.dualFintype (V := NodeEmbedding.RowSpace slots upper) + +variable {Ω : Type*} [Fintype Ω] + (original : FiniteDistribution Ω) (arrays : Ω → Arrays slots (FixedRows.rows plan)) + (lowerEvent : Ω → Bool) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch plan.depth t)) + (A : ManyGoodRows.RowMap (Block (FixedRows.rows plan) upper) plan.order) + (known : HiddenBucketBias.VisibleDirection (LinearMap.ker A) → NodeEmbedding.NodeH projected upper) + (lower : Nodes branch plan.depth) (a : Block (FixedRows.rows plan) lower) + (cut : OwnInputReference.Cut upper lower) + (input : OwnInputReference.Input projected (FixedRows.rows plan) upper lower (LinearMap.ker A) a) + +include hδ + +theorem meeting_probability_lower + (hgood : VisibleGood slots projected projection upper lowerLevel background + original arrays lowerEvent (InitialParameters.useful δ) σ plan.density A known) + (hne : ∃ T, J slots projected projection upper lowerLevel background + original arrays lowerEvent (InitialParameters.useful δ) σ plan.density A known T = true) + (hmatch : rhoPred (InitialParameters.useful δ) plan.density ≤ + RightDecoderWitness.conditionalMatch projected (FixedRows.rows plan) upper lower + (LinearMap.ker A) a (FixedRows.repeats plan) cut σ input + (columnSpace slots projected projection upper lowerLevel background + original arrays lowerEvent (InitialParameters.useful δ) σ plan.density A known hgood) + (target slots projected projection upper lowerLevel background + original arrays lowerEvent (InitialParameters.useful δ) σ plan.density A known hgood hne) + (nativeCorrection slots projected projection upper lowerLevel background + original arrays lowerEvent (InitialParameters.useful δ) σ plan.density A known hgood) + (visibleOffset slots projected projection upper lowerLevel background + original arrays lowerEvent (InitialParameters.useful δ) σ plan.density A known hgood)) : + (1 / (2 : ℝ) ^ plan.order) * + (tau (InitialParameters.useful δ) plan.density plan.order + (FixedRows.rows plan (Nodes.height upper)) ^ 2 / + (2 * (2 : ℝ) ^ FixedRows.rows plan (Nodes.height upper))) ≤ + ((HierarchicalProjectedMeeting.leftLaw slots projected projection upper lowerLevel + background original arrays lowerEvent (InitialParameters.useful δ) σ plan.density A known).product + (RightDecoder.law projected (FixedRows.rows plan) upper lower (LinearMap.ker A) a + (FixedRows.repeats plan) cut σ input + (tau (InitialParameters.useful δ) plan.density plan.order + (FixedRows.rows plan (Nodes.height upper))))).probability + (fun pair => decide ((ProjectedNodeEmbedding.intoOriginal projection upper).dualMap + pair.1 = pair.2)) := by + simpa only [UpperParameterScalars.tau] using + (HierarchicalProjectedMeeting.meeting_probability_lower slots projected projection upper lowerLevel + background original arrays lowerEvent (InitialParameters.useful δ) σ plan.density A known + lower a (FixedRows.repeats plan) cut input hgood hne + (rhoPred (InitialParameters.useful δ) plan.density) + (h plan.order (FixedRows.rows plan (Nodes.height upper))) + (rhoPred_pos (InitialParameters.useful_pos hδ) plan.density_pos) + (h_pos plan.order (FixedRows.rows plan (Nodes.height upper))) + (HierarchicalFixedDecoderMeeting.repetitionsBalanced plan) + (HierarchicalFixedDecoderMeeting.slice_error plan (Nodes.height upper)) + (HierarchicalFixedDecoderMeeting.list_error plan (Nodes.height upper)) + (HierarchicalFixedDecoderMeeting.kernel_excluded plan (Nodes.height upper) A) + le_rfl hmatch) + +end +end PerfectCompleteness.HierarchicalFixedProjectedMeeting + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedNativeHigh.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedNativeHigh.lean new file mode 100644 index 0000000000000000000000000000000000000000..ddf204f75e90ecd5a1ce452f37df173cbaa62126 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedNativeHigh.lean @@ -0,0 +1,102 @@ +import OAI.Computability.PerfectCompleteness.Decoding.FixedDecoderCleanRateLemmas +import OAI.Computability.PerfectCompleteness.Reduction.FixedSourcePhysicalHighLemmas +import OAI.Computability.PerfectCompleteness.Repetition.CleanPhysicalHighAverage + +namespace OAI + +section + +namespace PerfectCompleteness.FixedNativeHigh + +noncomputable section + +open scoped Classical +open FixedParameters FixedRows RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +variable {δ : ℚ} {hδ : 0 < δ} (parameters : Parameters δ hδ) + {height v m : Nat} [NeZero m] + {upper : Nodes (branch parameters) parameters.plan.depth} + {d : HierarchicalFrozenTables.LowerNodes upper (height + 1)} + (S : CleanDecoderRate.Setup (branch parameters) (rows parameters.plan) (repeats parameters.plan) + parameters.plan.depth height (sourceLength parameters.plan hδ) v m upper d) + (hnode : WholeArrayInteriorExterior.upperNode (CleanDecoderRate.path S) = + HierarchicalLeftDecoder.LowerNode upper (height + 1) d) + {Original : OriginalDecoderMark.SlotFamily (branch parameters) parameters.plan.depth + (sourceLength parameters.plan hδ) → Type*} + [∀ slots, Fintype (Original slots)] + (F : OriginalDecoderMark.Family (branch parameters) (rows parameters.plan) + parameters.plan.depth (sourceLength parameters.plan hδ) Original) + (κ : ℝ) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount (branch parameters) parameters.plan.depth + (sourceLength parameters.plan hδ))) + (r : Nat) (density : ℝ) + (A : ManyGoodRows.RowMap (Block (rows parameters.plan) upper) r) + (threshold : ℝ) + +local instance directionNonempty : + Nonempty (BucketSampler.Direction (rows parameters.plan (height + 1))) := + ⟨BucketUniform.coordinateDirection ⟨0, lt_of_lt_of_le Nat.zero_lt_one + (parameters.plan.rows_pos (parameters.plan.depth - (height + 1)))⟩⟩ + +theorem flag_eq (h : Nat) : + FixedSourceGlobalCollision.flag parameters (height := h) = + fun _ : Fin (branch parameters h) => + ProjectedCleanRate.projectionFlag (parameters.cubeSize h) + (FixedDecoderCleanRate.cubePositive parameters h) := by + funext child + apply FiniteDistribution.eq_of_weight_eq + intro b + cases b <;> + simp [FixedSourceGlobalCollision.flag, ProjectedCleanRate.projectionFlag, + ProjectionPosterior.bernoulli, RepetitionRate.bernoulli, + FixedParameters.projectionProbability, ProjectedCleanRate.projectionDensity] + +def questionUseful + (q : FixedSourceGlobalCollision.Questions (m := m) parameters (height := height)) := + OriginalDecoderMark.mark F upper (height + 1) κ + (SourceQuestionLowerForms.slots (CleanDecoderRate.path S) S.outside S.clauses q) + +def probability : ℝ := + (FiniteDistribution.uniform (BucketSampler.Direction (rows parameters.plan (height + 1)))).expectation + (fun direction => + (CleanDecoderPairLaw.pairLaw S σ (CleanPhysicalDecoderLaw.useful S F κ) + r density A (LinearMap.ker A) (CleanPhysicalHighAverage.nativeDirection S hnode direction) + threshold (parameters.cubeSize height) (FixedDecoderCleanRate.cubePositive parameters height)).probability + (fun z => DecoderRankSplit.highAgrees S (FixedLowerRawCollision.branchPositive parameters) + (cutoff parameters.plan hδ) z.1 z.2)) + +theorem probability_eq_physical : + probability parameters S hnode F κ σ r density A threshold = + FixedSourcePhysicalHigh.probability parameters S.outside S.placeholder S.clauses S.designated + upper (CleanPhysicalHighAverage.suffix S) (CleanPhysicalHighAverage.suffix_proper S) + d hnode A S.cut S.exterior σ (questionUseful parameters S F κ) density threshold := by + unfold probability FixedSourcePhysicalHigh.probability + apply FiniteDistribution.expectation_congr + intro direction + rw [CleanPhysicalHighAverage.probability_eq_tag_average S + (FixedLowerRawCollision.branchPositive parameters) hnode F κ σ r density A direction + threshold (cutoff parameters.plan hδ) (parameters.cubeSize height) + (FixedDecoderCleanRate.cubePositive parameters height)] + simp only [FixedSourcePhysicalHigh.tagLaw, flag_eq] + apply FiniteDistribution.expectation_congr + intro q + apply FiniteDistribution.expectation_congr + intro tag + rfl + +theorem probability_square_le (hdensity : 0 < density) : + probability parameters S hnode F κ σ r density A threshold ^ 2 ≤ + FixedRankContradiction.gamma parameters (Nodes.height upper) ^ 2 / 8 + + 2 * parameters.accuracy := by + rw [probability_eq_physical] + exact FixedSourceHighBound.probability_square_le parameters S.outside S.placeholder S.clauses + S.designated upper (CleanPhysicalHighAverage.suffix S) (CleanPhysicalHighAverage.suffix_proper S) + d hnode A S.cut S.exterior σ (questionUseful parameters S F κ) density threshold hdensity + +end +end PerfectCompleteness.FixedNativeHigh + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedPhysicalStoppedComparison.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedPhysicalStoppedComparison.lean new file mode 100644 index 0000000000000000000000000000000000000000..9394d620745eea337fdc53ba1c1952f99de50cff --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedPhysicalStoppedComparison.lean @@ -0,0 +1,87 @@ +import OAI.Computability.PerfectCompleteness.Decoding.FixedProjectionErrorLemmas +import OAI.Computability.PerfectCompleteness.Foundations.SourcePhysicalSourceSwapLemmas +import OAI.Computability.PerfectCompleteness.Reduction.FixedCallBudgetLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.FixedPhysicalStoppedComparison + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces FixedParameters FixedRows +open UniqueGamesTheorem.Foundations.Games + +variable {δ : ℚ} {hδ : 0 < δ} (params : Parameters δ hδ) + {root h v m : Nat} (p : Path (branch params) root (h + 1)) + (outside : Slots (branch params) root → Fin (sourceLength params.plan hδ) → MixedSupport.Slot) + (placeholder : Slots (branch params) (h + 1) → Fin (sourceLength params.plan hδ) → MixedSupport.Slot) + (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch params h) → Slots (branch params) h) + +theorem beta_nonneg : 0 ≤ (projectionProbability params h : ℝ) := by + exact_mod_cast (projectionProbability_bounds params h).1.le + +theorem beta_le_one : (projectionProbability params h : ℝ) ≤ 1 := by + exact_mod_cast (projectionProbability_bounds params h).2.le + +theorem calls_le (hroot : root ≤ params.plan.depth) : + Fintype.card (WholeCutCalls.Index (rows params.plan) (repeats params.plan) p) ≤ + calls params.plan := by + have hactual := FixedCallBudget.modified_calls_le (rows params.plan) + (repeats params.plan) p hroot + apply hactual.trans + unfold calls + omega + +variable (source : FiniteDistribution + (SourceChildKernel.Sources (m := m) (t := sourceLength params.plan hδ) designated)) + +abbrev modifiedLaw := + SourcePhysicalStoppedComparison.sourceModifiedLaw (rows params.plan) (repeats params.plan) + p outside placeholder clauses designated source (projectionProbability params h : ℝ) + (beta_nonneg params) (beta_le_one params) + +abbrev stoppedLaw := + SourcePhysicalStoppedComparison.sourceStoppedLaw (rows params.plan) (repeats params.plan) + p outside clauses designated source + +theorem variation_lt_accuracy (hroot : root ≤ params.plan.depth) : + (modifiedLaw params p outside placeholder clauses designated source).totalVariation + (stoppedLaw params p outside clauses designated source) < params.accuracy := by + have htv := SourcePhysicalStoppedComparison.source_variation + (rows params.plan) (repeats params.plan) p outside placeholder clauses designated + source (branch_pos params h) (projectionProbability params h : ℝ) + (beta_nonneg params) (beta_le_one params) + apply htv.trans_lt + simpa only [SourceChildProjectionComparison.error] using + FixedProjectionError.sparse_error_lt params (calls_le params p hroot) h + +theorem probability_gt_sub_accuracy (hroot : root ≤ params.plan.depth) + (event : SourcePhysicalStoppedComparison.Observation (rows params.plan) p outside clauses designated → Bool) : + (stoppedLaw params p outside clauses designated source).probability event - params.accuracy < + (modifiedLaw params p outside placeholder clauses designated source).probability event := by + have htv := variation_lt_accuracy params p outside placeholder clauses designated source hroot + have hp := FiniteDistribution.probability_le_add_totalVariation + (stoppedLaw params p outside clauses designated source) + (modifiedLaw params p outside placeholder clauses designated source) event + rw [FiniteDistribution.totalVariation_comm] at hp + linarith + +theorem probability_gt_of_reserve (hroot : root ≤ params.plan.depth) + (event : SourcePhysicalStoppedComparison.Observation (rows params.plan) p outside clauses designated → Bool) + (c : ℝ) + (hreserve : c + params.accuracy ≤ + (stoppedLaw params p outside clauses designated source).probability event) : + c < (modifiedLaw params p outside placeholder clauses designated source).probability event := by + have h := probability_gt_sub_accuracy params p outside placeholder clauses designated source hroot event + linarith + +end +end PerfectCompleteness.FixedPhysicalStoppedComparison + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedPreliminarySoundness.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedPreliminarySoundness.lean new file mode 100644 index 0000000000000000000000000000000000000000..5656ebf5684348170fe833d0ddc324da95b1085d --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedPreliminarySoundness.lean @@ -0,0 +1,32 @@ +import OAI.Computability.PerfectCompleteness.Decoding.FixedStoppedUpperProbability +import OAI.Computability.PerfectCompleteness.Reduction.FixedStoppedContradiction +import OAI.Computability.PerfectCompleteness.Reduction.FixedStoppedPair + +namespace OAI + +section + +namespace PerfectCompleteness.FixedPreliminarySoundness + +noncomputable section + +variable {δ : ℚ} {hδ : 0 < δ} (parameters : FixedParameters.Parameters δ hδ) + +theorem no_large_strategy (input : List Bool) + (unsat : ¬ BinaryLanguage.language input) + (strategy : FixedPreliminaryGame.Strategy parameters input) + (hsuccess : InitialParameters.epsilon δ ≤ + (FixedPreliminaryGame.game parameters input).success strategy) : False := by + obtain ⟨i, j, hij, hreserve⟩ := FixedStoppedPair.exists_pair parameters input strategy hsuccess + have hupper := FixedStoppedUpperProbability.meeting_ge_gamma + parameters i j hij input strategy hreserve + have hsmall := FixedStoppedContradiction.meeting_lt_gamma + parameters i j hij input strategy unsat + exact (not_lt_of_ge hupper) hsmall + +end +end PerfectCompleteness.FixedPreliminarySoundness + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedQueryCodec.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedQueryCodec.lean new file mode 100644 index 0000000000000000000000000000000000000000..eefb7709417a05cbabd16a0b5d1fc84a6326ce30 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedQueryCodec.lean @@ -0,0 +1,244 @@ +import OAI.Computability.PerfectCompleteness.Foundations.CanonicalPartialTable +import OAI.Computability.PerfectCompleteness.Machines.CanonicalCoarseningEncoding +import OAI.Computability.PerfectCompleteness.Machines.MetadataFreeTapeLemmas + +namespace OAI + + +namespace PerfectCompleteness.FixedQueryCodec + +open HierarchicalArrays (Nodes Block) +open MixedSupport +open scoped Classical + +noncomputable section + +abbrev LeftOutput (branch : Nat → Nat) (n : Nat) (rows : Nat → Nat) := + HierarchicalArrays.Output branch n rows + +def leftCount (branch : Nat → Nat) (n : Nat) (rows : Nat → Nat) : Nat := + Fintype.card (LeftOutput branch n rows) + +def leftEquiv (branch : Nat → Nat) (n : Nat) (rows : Nat → Nat) : + LeftOutput branch n rows ≃ Fin (leftCount branch n rows) := + MetadataFreeSampler.outputEquiv branch n rows + +def leftEncode (branch : Nat → Nat) (n : Nat) (rows : Nat → Nat) : + LeftOutput branch n rows → Fin (leftCount branch n rows) := + leftEquiv branch n rows + +theorem leftEncode_injective (branch : Nat → Nat) (n : Nat) (rows : Nat → Nat) : + Function.Injective (leftEncode branch n rows) := + (leftEquiv branch n rows).injective + +abbrev TestIndex (branch : Nat → Nat) (n : Nat) (rows : Nat → Nat) := + Σ node : Nodes branch n, BucketSampler.Direction (rows (Nodes.height node)) + +instance testIndexFintype (branch : Nat → Nat) (n : Nat) (rows : Nat → Nat) : + Fintype (TestIndex branch n rows) := by + unfold TestIndex + infer_instance + +variable {branch : Nat → Nat} {n t v m : Nat} {rows repeats : Nat → Nat} + +abbrev RightOutput (θ : TestIndex branch n rows) : Type := + DirectionQuotient.Space θ.2.val × + (BlockQuotient.OtherBlocks (fun node : Nodes branch n => Block rows node) θ.1 × PUnit.{1}) + +instance rightOutputFintype (θ : TestIndex branch n rows) : Fintype (RightOutput θ) := + Fintype.ofFinite _ + +def project (θ : TestIndex branch n rows) : LeftOutput branch n rows → RightOutput θ := + BlockQuotient.projectBlock (I := Nodes branch n) + (V := fun node : Nodes branch n => Block rows node) (B := PUnit.{1}) θ.1 θ.2.val + +abbrev TaggedRight (branch : Nat → Nat) (n : Nat) (rows : Nat → Nat) : Type := + Σ θ : TestIndex branch n rows, RightOutput θ + +instance taggedRightFintype (branch : Nat → Nat) (n : Nat) (rows : Nat → Nat) : + Fintype (TaggedRight branch n rows) := by + letI : (θ : TestIndex branch n rows) → Fintype (RightOutput θ) := + fun θ => rightOutputFintype θ + unfold TaggedRight + infer_instance + +def rightCount (branch : Nat → Nat) (n : Nat) (rows : Nat → Nat) : Nat := + Fintype.card (TaggedRight branch n rows) + +def rightEquiv (branch : Nat → Nat) (n : Nat) (rows : Nat → Nat) : + TaggedRight branch n rows ≃ Fin (rightCount branch n rows) := + Fintype.equivFin _ + +def rightEncode (θ : TestIndex branch n rows) : + RightOutput θ → Fin (rightCount branch n rows) := + fun z => rightEquiv branch n rows ⟨θ, z⟩ + +theorem rightEncode_injective (θ : TestIndex branch n rows) : + Function.Injective (rightEncode θ) := + (rightEquiv branch n rows).injective.comp (sigma_mk_injective (i := θ)) + +def outputMap (θ : TestIndex branch n rows) : + Fin (leftCount branch n rows) → Fin (rightCount branch n rows) := + fun a => rightEncode θ (project θ ((leftEquiv branch n rows).symm a)) + +@[simp] theorem outputMap_leftEncode (θ : TestIndex branch n rows) + (y : LeftOutput branch n rows) : + outputMap θ (leftEncode branch n rows y) = rightEncode θ (project θ y) := by + change rightEncode θ (project θ + ((leftEquiv branch n rows).symm (leftEquiv branch n rows y))) = _ + rw [(leftEquiv branch n rows).symm_apply_apply] + +def decodedFiberEquiv (θ : TestIndex branch n rows) (z : RightOutput θ) : + {a : Fin (leftCount branch n rows) // + project θ ((leftEquiv branch n rows).symm a) = z} ≃ + {y : LeftOutput branch n rows // project θ y = z} := + Equiv.subtypeEquivOfSubtype (p := fun y : LeftOutput branch n rows => project θ y = z) + (leftEquiv branch n rows).symm + +theorem outputMap_fiber_le_two (θ : TestIndex branch n rows) + (b : Fin (rightCount branch n rows)) : + Nat.card {a : Fin (leftCount branch n rows) // outputMap θ a = b} ≤ 2 := by + have hsmall : ∀ z : RightOutput θ, + Nat.card {a : Fin (leftCount branch n rows) // + project θ ((leftEquiv branch n rows).symm a) = z} ≤ 2 := by + intro z + have hc := (Nat.card_congr (decodedFiberEquiv θ z)).trans + (BlockQuotient.card_projectBlock_fiber (I := Nodes branch n) + (V := fun node : Nodes branch n => Block rows node) (B := PUnit.{1}) + θ.1 θ.2.val θ.2.property z) + exact hc.le + by_cases hb : ∃ z : RightOutput θ, rightEncode θ z = b + · obtain ⟨z, rfl⟩ := hb + let e : + {a : Fin (leftCount branch n rows) // outputMap θ a = rightEncode θ z} ≃ + {a : Fin (leftCount branch n rows) // + project θ ((leftEquiv branch n rows).symm a) = z} := + Equiv.subtypeEquivRight (fun a => by + change (rightEncode θ (project θ ((leftEquiv branch n rows).symm a)) = + rightEncode θ z) ↔ _ + exact ⟨fun h => (rightEncode_injective θ) h, + fun h => congrArg (rightEncode θ) h⟩) + exact (Nat.card_congr e).le.trans (hsmall z) + · let : IsEmpty {a : Fin (leftCount branch n rows) // outputMap θ a = b} := + ⟨fun a => hb + ⟨project θ ((leftEquiv branch n rows).symm a.val), a.property⟩⟩ + rw [Nat.card_of_isEmpty] + exact Nat.zero_le 2 + +section Keys + +variable {k : Nat} + +theorem left_key (side : CanonicalKeys.Side) (slots : Fin k → Slot) + (f : Assignment slots → LeftOutput branch n rows) : + CanonicalKeys.key side slots (leftEncode branch n rows ∘ f) = + CanonicalKeys.key side slots f := + CanonicalCoarseningEncoding.key_fine side slots f + (leftEncode branch n rows) (leftEncode_injective branch n rows) + +theorem right_key (side : CanonicalKeys.Side) (slots : Fin k → Slot) + (f : Assignment slots → LeftOutput branch n rows) (θ : TestIndex branch n rows) : + CanonicalKeys.key side slots (outputMap θ ∘ (leftEncode branch n rows ∘ f)) = + CanonicalKeys.key side slots (project θ ∘ f) := + CanonicalCoarseningEncoding.key_coarse side slots f (project θ) + (leftEncode branch n rows) (rightEncode θ) (outputMap θ) + (rightEncode_injective θ) (outputMap_leftEncode θ) + +theorem right_kernel (slots : Fin k → Slot) + (f : Assignment slots → LeftOutput branch n rows) (θ : TestIndex branch n rows) : + ∀ x x', (project θ ∘ f) x = (project θ ∘ f) x' ↔ + (outputMap θ ∘ (leftEncode branch n rows ∘ f)) x = + (outputMap θ ∘ (leftEncode branch n rows ∘ f)) x' := + CanonicalCoarseningEncoding.coarseKernel slots f (project θ) + (leftEncode branch n rows) (rightEncode θ) (outputMap θ) + (rightEncode_injective θ) (outputMap_leftEncode θ) + +end Keys + +def leftTable {slots : RecursiveSpaces.Slots branch n → Fin t → Slot} + (arrays : HierarchicalArrays.Arrays slots rows) : + Assignment (TreeCanonical.numberedSlots slots) → Fin (leftCount branch n rows) := + leftEncode branch n rows ∘ + TreeCanonical.numberedFunction slots (HierarchicalArrays.fullJoint arrays) + +theorem leftTable_key (side : CanonicalKeys.Side) + {slots : RecursiveSpaces.Slots branch n → Fin t → Slot} + (arrays : HierarchicalArrays.Arrays slots rows) : + CanonicalKeys.key side (TreeCanonical.numberedSlots slots) (leftTable arrays) = + TreeCanonical.key side slots (HierarchicalArrays.fullJoint arrays) := + left_key side (TreeCanonical.numberedSlots slots) + (TreeCanonical.numberedFunction slots (HierarchicalArrays.fullJoint arrays)) + +theorem rightTable_key (side : CanonicalKeys.Side) + {slots : RecursiveSpaces.Slots branch n → Fin t → Slot} + (arrays : HierarchicalArrays.Arrays slots rows) (θ : TestIndex branch n rows) : + CanonicalKeys.key side (TreeCanonical.numberedSlots slots) (outputMap θ ∘ leftTable arrays) = + TreeCanonical.key side slots (project θ ∘ HierarchicalArrays.fullJoint arrays) := + right_key side (TreeCanonical.numberedSlots slots) + (TreeCanonical.numberedFunction slots (HierarchicalArrays.fullJoint arrays)) θ + +def testIndex (data : MetadataFreeTape.Input branch n t rows repeats) : + TestIndex branch n rows := + ⟨GeometricPath.nodeAtLevel data.2.1 data.2.2.2.1, data.2.2.2.2⟩ + +def rawTestIndex (clauses : Fin m → SourceClause.NormalizedClause v) + (e : PreliminarySampler.Raw clauses branch n t rows repeats) : TestIndex branch n rows := + ⟨GeometricPath.nodeAtLevel e.1.2 e.2.2.1, e.2.2.2⟩ + +@[simp] theorem testIndex_encodeRaw (clauses : Fin m → SourceClause.NormalizedClause v) + (e : PreliminarySampler.Raw clauses branch n t rows repeats) : + testIndex (MetadataFreeTape.encodeRaw clauses rows repeats e) = rawTestIndex clauses e := rfl + +def withProjection {a k l : Nat} (fine : CanonicalKeyShape.Input a k) + (p : Fin k → Fin l) : CanonicalPartialTable.Input a k l := + ⟨fine.1, fine.2, p⟩ + +def partialInput (data : MetadataFreeTape.Input branch n t rows repeats) : + CanonicalPartialTable.Input (TreeCanonical.locationCount branch n t) + (leftCount branch n rows) (rightCount branch n rows) := + withProjection (MetadataFreeTape.keyInput data) (outputMap (testIndex data)) + +theorem partialInput_encodeRaw (clauses : Fin m → SourceClause.NormalizedClause v) + (e : PreliminarySampler.Raw clauses branch n t rows repeats) : + partialInput (MetadataFreeTape.encodeRaw clauses rows repeats e) = + CanonicalPartialTable.input + (TreeCanonical.numberedSlots (MetadataFreeSampler.sourceSlots clauses e.1.1)) + (leftTable (WholeArraySampler.evaluate rows repeats (GeometricPath.leafPath e.1.2) + (MetadataFreeSampler.sourceSlots clauses e.1.1) e.2.1)) + (outputMap (rawTestIndex clauses e)) := by + unfold partialInput + rw [MetadataFreeTape.keyInput_encodeRaw, testIndex_encodeRaw] + rfl + +def rightInputOfPartial {a k l : Nat} (data : CanonicalPartialTable.Input a k l) : + CanonicalKeyShape.Input a l := + ⟨data.1, data.2.2 ∘ data.2.1⟩ + +def rightKeyInput (data : MetadataFreeTape.Input branch n t rows repeats) : + CanonicalKeyShape.Input (TreeCanonical.locationCount branch n t) + (rightCount branch n rows) := + rightInputOfPartial (partialInput data) + +theorem rightKeyInput_encodeRaw (clauses : Fin m → SourceClause.NormalizedClause v) + (e : PreliminarySampler.Raw clauses branch n t rows repeats) : + rightKeyInput (MetadataFreeTape.encodeRaw clauses rows repeats e) = + CanonicalKeyShape.input + (TreeCanonical.numberedSlots (MetadataFreeSampler.sourceSlots clauses e.1.1)) + (outputMap (rawTestIndex clauses e) ∘ + leftTable (WholeArraySampler.evaluate rows repeats (GeometricPath.leafPath e.1.2) + (MetadataFreeSampler.sourceSlots clauses e.1.1) e.2.1)) := by + rw [rightKeyInput, partialInput_encodeRaw] + rfl + +theorem partialInput_admissible {q : Nat} (hq : 0 < q) + (large : CanonicalKeyEncoding.partitionWidth (TreeCanonical.locationCount branch n t) ≤ q) + (data : MetadataFreeTape.Input branch n t rows repeats) : + LocalCompletionFamily.Admissible + (CanonicalPartialTable.lookup hq large (partialInput data)) := + CanonicalPartialTable.admissible_of_output_fibers hq large (partialInput data) + (outputMap_fiber_le_two (testIndex data)) + +end +end PerfectCompleteness.FixedQueryCodec + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedRows.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedRows.lean new file mode 100644 index 0000000000000000000000000000000000000000..575e6df3986ba6228ec5af0c9c2f7eaafc457401 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedRows.lean @@ -0,0 +1,115 @@ +import OAI.Computability.PerfectCompleteness.Construction.AscendingBranchingLemmas +import OAI.Computability.PerfectCompleteness.Foundations.SourceOddListsLemmas +import OAI.Computability.PerfectCompleteness.Machines.PreprocessingMachineLemmas +import OAI.Computability.PerfectCompleteness.Reduction.CompletionLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.FixedRows + +open InitialParameters UpperParameterScalars +open UniqueGamesTheorem.Appendix UniqueGamesTheorem.Fourier + +noncomputable section + +structure Plan (δ : ℚ) where + depth : Nat + depth_ge : 2 ≤ depth + depth_mass : 4 ≤ (depth : ℝ) * epsilon δ + order : Nat + order_pos : 1 ≤ order + density : ℝ + density_pos : 0 < density + density_lt : density < 1 + spectral : MatrixLevelBridge.levelCutoffConstant order density + + RankLevelFilter.node (order + 1) < inverse δ / 2 + rootFirstRows : Nat → Nat + rows_order : ∀ k, order ≤ rootFirstRows k + rows_pos : ∀ k, 1 ≤ rootFirstRows k + rows_correction : ∀ k, 1 / (2 : ℝ) ^ (rootFirstRows k - order) < + rhoPred (useful δ) density / 8 + repeatCount : Nat → Nat + repeats_min : ∀ ℓ, 6 ≤ repeatCount ℓ + repeats_error : ∀ ℓ, (7 / 8 : ℝ) ^ repeatCount ℓ ≤ + min (h order ℓ / 2) (tau (useful δ) density order ℓ ^ 2 / 2) + lowerRequirements : ∀ (hδ : 0 < δ) k (i : Fin k), + (DescendingRows.lowerChoice (useful_pos hδ) density_pos (inverse_pos hδ) + order (rootFirstRows i.val)).minimumRows ≤ rootFirstRows k + +theorem exists_plan {δ : ℚ} (hδ : 0 < δ) (hδ' : δ < 1) : Nonempty (Plan δ) := by + obtain ⟨depth, r, hd, hmass, hr, α, hα, hα', hspectral⟩ := + exists_initial hδ hδ' + obtain ⟨rows, hrows⟩ := DescendingRows.exists_rows + (useful_pos hδ) hα (inverse_pos hδ) r 1 + have hreps : ∀ ℓ : Nat, ∃ R : Nat, 6 ≤ R ∧ (7 / 8 : ℝ) ^ R ≤ + min (h r ℓ / 2) (tau (useful δ) α r ℓ ^ 2 / 2) := + fun ℓ => exists_upper_repeats (useful_pos hδ) hα r ℓ + choose repeats hrepeats using hreps + exact ⟨{ + depth := depth + depth_ge := hd + depth_mass := hmass + order := r + order_pos := hr + density := α + density_pos := hα + density_lt := hα' + spectral := hspectral + rootFirstRows := rows + rows_order := fun k => (hrows k).2.1 + rows_pos := fun k => (hrows k).2.2.1 + rows_correction := fun k => (hrows k).2.2.2.1 + repeatCount := repeats + repeats_min := fun ℓ => (hrepeats ℓ).1 + repeats_error := fun ℓ => (hrepeats ℓ).2 + lowerRequirements := fun _ k => (hrows k).2.2.2.2 }⟩ + +variable {δ : ℚ} (plan : Plan δ) + +def rows : Nat → Nat := DescendingRows.treeRows plan.depth plan.rootFirstRows +def repeats : Nat → Nat := fun height => plan.repeatCount (rows plan height) + +def cutoff (hδ : 0 < δ) : Nat := + DescendingRows.commonCutoff (useful_pos hδ) plan.density_pos (inverse_pos hδ) + plan.order plan.depth plan.rootFirstRows + +theorem cutoff_pos (hδ : 0 < δ) : 0 < cutoff plan hδ := + DescendingRows.commonCutoff_pos (useful_pos hδ) plan.density_pos (inverse_pos hδ) + plan.order plan.depth plan.rootFirstRows + +instance cutoff_neZero (hδ : 0 < δ) : NeZero (cutoff plan hδ) := + ⟨Nat.ne_of_gt (cutoff_pos plan hδ)⟩ + +def sourceLength (hδ : 0 < δ) : Nat := + SourceOddLists.repetitionLength PCPSource.sourceGap (cutoff plan hδ) + PCPSource.sourceGap_pos PCPSource.sourceGap_le_one + +theorem sourceLength_pos (hδ : 0 < δ) : 0 < sourceLength plan hδ := + SourceOddLists.repetitionLength_positive PCPSource.sourceGap (cutoff plan hδ) + PCPSource.sourceGap_pos PCPSource.sourceGap_le_one + +theorem source_oddList_value_le_half (hδ : 0 < δ) + (input : List Bool) (unsat : ¬BinaryLanguage.language input) : + (SourceOddLists.game (cutoff plan hδ) + (PCPSource.clauseFamily (BinaryLanguage.totalRename input)) + (sourceLength plan hδ)).value ≤ 1 / 2 := + SourceOddLists.value_le_half + (PCPSource.clauseFamily (BinaryLanguage.totalRename input)) + PCPSource.sourceGap PCPSource.sourceGap_pos PCPSource.sourceGap_le_one + (PCPSourceMachine.rawSource_clauseGap input unsat) + +theorem lower_row_requirement (hδ : 0 < δ) {i j : Nat} + (hij : i < j) (hj : j ≤ plan.depth) : + (DescendingRows.lowerChoice (useful_pos hδ) plan.density_pos (inverse_pos hδ) + plan.order (rows plan j)).minimumRows ≤ rows plan i := + DescendingRows.tree_pair_requirement (useful_pos hδ) plan.density_pos (inverse_pos hδ) + plan.order plan.depth plan.rootFirstRows (plan.lowerRequirements hδ) hij hj + +end +end PerfectCompleteness.FixedRows + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedSourcePhysicalHighLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedSourcePhysicalHighLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..dfd9ea48789745f49001a87d93b9a4626c40e437 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedSourcePhysicalHighLemmas.lean @@ -0,0 +1,218 @@ +import OAI.Computability.PerfectCompleteness.Construction.SourceQuestionPhysicalHigh +import OAI.Computability.PerfectCompleteness.Decoding.SourceQuestionCollisionTransportLemmas +import OAI.Computability.PerfectCompleteness.Decoding.SourceQuestionPhysicalCollision + +namespace OAI + +section + +namespace PerfectCompleteness.FixedSourcePhysicalHigh + +noncomputable section + +open scoped Classical BigOperators +open FixedParameters FixedRows RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +variable {δ : ℚ} {hδ : 0 < δ} (parameters : Parameters δ hδ) + {height v m : Nat} [NeZero m] + (outside : Slots (branch parameters) parameters.plan.depth → + Fin (sourceLength parameters.plan hδ) → MixedSupport.Slot) + (placeholder : Slots (branch parameters) (height + 1) → + Fin (sourceLength parameters.plan hδ) → MixedSupport.Slot) + (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch parameters height) → Slots (branch parameters) height) + (upper : Nodes (branch parameters) parameters.plan.depth) + (pDown : Path (branch parameters) (Nodes.height upper) (height + 1)) + (hproper : height + 1 < Nodes.height upper) + (d : HierarchicalFrozenTables.LowerNodes upper (height + 1)) + (hnode : WholeArrayInteriorExterior.upperNode ((Nodes.path upper).append pDown) = + HierarchicalLeftDecoder.LowerNode upper (height + 1) d) + {adviceRows : Nat} + (A : ManyGoodRows.RowMap (Block (rows parameters.plan) upper) adviceRows) + (cut : OwnInputReference.Cut upper (ProjectedLowerFiber.lower upper (height + 1) d)) + (exterior : CleanPhysicalReplay.Exterior (rows parameters.plan) (repeats parameters.plan) + ((Nodes.path upper).append pDown) outside placeholder) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount (branch parameters) parameters.plan.depth + (sourceLength parameters.plan hδ))) + (useful : (q : FixedSourceGlobalCollision.Questions (m := m) parameters (height := height)) → + (bg : HierarchicalMatrixTable.Background (rows := rows parameters.plan) + (SourceQuestionLowerForms.slots ((Nodes.path upper).append pDown) outside clauses q) upper) → + HierarchicalFrozenTables.QuotientMatrix + (SourceQuestionLowerForms.slots ((Nodes.path upper).append pDown) outside clauses q) + upper (height + 1) bg → Prop) + (density threshold : ℝ) + +local instance rowSpaceFintype (q : FixedSourceGlobalCollision.Questions + (m := m) parameters (height := height)) : + Fintype (NodeEmbedding.RowSpace + (SourceQuestionLowerForms.slots ((Nodes.path upper).append pDown) outside clauses q) upper) := + Fintype.ofFinite _ + +local instance upperAnswerFintype (q : FixedSourceGlobalCollision.Questions + (m := m) parameters (height := height)) : + Fintype (HierarchicalAllDecoderTables.UpperAnswer + (SourceQuestionLowerForms.slots ((Nodes.path upper).append pDown) outside clauses q) upper) := + LeftDecoder.dualFintype + (V := NodeEmbedding.RowSpace + (SourceQuestionLowerForms.slots ((Nodes.path upper).append pDown) outside clauses q) upper) + +local instance directionNonempty : + Nonempty (BucketSampler.Direction (rows parameters.plan (height + 1))) := + ⟨BucketUniform.coordinateDirection ⟨0, lt_of_lt_of_le Nat.zero_lt_one + (parameters.plan.rows_pos (parameters.plan.depth - (height + 1)))⟩⟩ + +def tagLaw : FiniteDistribution + (SourceProjectedTag.Tag (branch := branch parameters) (n := height) + (t := sourceLength parameters.plan hδ)) := + SourceProjectedTag.law (FixedSourceGlobalCollision.flag parameters) + +def success (direction : BucketSampler.Direction (rows parameters.plan (height + 1))) + (q : FixedSourceGlobalCollision.Questions (m := m) parameters (height := height)) + (tag : SourceProjectedTag.Tag (branch := branch parameters) (n := height) + (t := sourceLength parameters.plan hδ)) : ℝ := + SourceQuestionPhysicalHigh.success outside placeholder clauses designated q tag.1 tag.2 upper pDown + hproper (height + 1) (FixedLowerRawCollision.branchPositive parameters) d hnode A cut σ (useful q) + density threshold exterior direction (cutoff parameters.plan hδ) + +def probability : ℝ := + (FiniteDistribution.uniform (BucketSampler.Direction (rows parameters.plan (height + 1)))).expectation + (fun direction => (PreliminarySampler.questionsLaw (branch := branch parameters) (n := height + 1) + (t := sourceLength parameters.plan hδ) (m := m)).expectation (fun q => + (tagLaw parameters).expectation + (success parameters outside placeholder clauses designated upper pDown hproper d hnode A cut + exterior σ useful density threshold direction q))) + +theorem probability_square_le_collision : + probability parameters outside placeholder clauses designated upper pDown hproper d hnode A cut + exterior σ useful density threshold ^ 2 ≤ + (FiniteDistribution.uniform (BucketSampler.Direction (rows parameters.plan (height + 1)))).expectation + (fun direction => (PreliminarySampler.questionsLaw (branch := branch parameters) (n := height + 1) + (t := sourceLength parameters.plan hδ) (m := m)).expectation (fun q => + (HierarchicalAllDecoderTables.upperTableLaw + (SourceQuestionLowerForms.slots ((Nodes.path upper).append pDown) outside clauses q) + upper (height + 1) σ (useful q) adviceRows density).expectation (fun table => + (tagLaw parameters).expectation (fun tag => + SourceQuestionPhysicalHigh.collision ((Nodes.path upper).append pDown) outside placeholder + clauses designated q tag.1 tag.2 upper (height + 1) d + (FixedLowerRawCollision.branchPositive parameters) A exterior direction + (cutoff parameters.plan hδ) table)))) := by + unfold probability + apply (CollisionAveraging.mean_square_le _ _).trans + apply SmallBias.expectation_mono + intro direction + apply (CollisionAveraging.mean_square_le _ _).trans + apply SmallBias.expectation_mono + intro q + apply (CollisionAveraging.mean_square_le _ _).trans + rw [FiniteDistribution.expectation_comm] + apply SmallBias.expectation_mono + intro tag + exact SourceQuestionPhysicalHigh.success_square_le outside placeholder clauses designated q tag.1 tag.2 + upper pDown hproper (height + 1) (FixedLowerRawCollision.branchPositive parameters) d hnode A cut + σ (useful q) density threshold exterior direction (cutoff parameters.plan hδ) + +end +end PerfectCompleteness.FixedSourcePhysicalHigh + +end + +section + +namespace PerfectCompleteness.FixedSourceHighBound + +noncomputable section + +open scoped Classical BigOperators +open FixedParameters FixedRows RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +variable {δ : ℚ} {hδ : 0 < δ} (parameters : Parameters δ hδ) + {height v m : Nat} [NeZero m] + (outside : Slots (branch parameters) parameters.plan.depth → + Fin (sourceLength parameters.plan hδ) → MixedSupport.Slot) + (placeholder : Slots (branch parameters) (height + 1) → + Fin (sourceLength parameters.plan hδ) → MixedSupport.Slot) + (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch parameters height) → Slots (branch parameters) height) + (upper : Nodes (branch parameters) parameters.plan.depth) + (pDown : Path (branch parameters) (Nodes.height upper) (height + 1)) + (hproper : height + 1 < Nodes.height upper) + (d : HierarchicalFrozenTables.LowerNodes upper (height + 1)) + (hnode : WholeArrayInteriorExterior.upperNode ((Nodes.path upper).append pDown) = + HierarchicalLeftDecoder.LowerNode upper (height + 1) d) + {adviceRows : Nat} + (A : ManyGoodRows.RowMap (Block (rows parameters.plan) upper) adviceRows) + (cut : OwnInputReference.Cut upper (ProjectedLowerFiber.lower upper (height + 1) d)) + (exterior : CleanPhysicalReplay.Exterior (rows parameters.plan) (repeats parameters.plan) + ((Nodes.path upper).append pDown) outside placeholder) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount (branch parameters) parameters.plan.depth + (sourceLength parameters.plan hδ))) + (useful : (q : FixedSourceGlobalCollision.Questions (m := m) parameters (height := height)) → + (bg : HierarchicalMatrixTable.Background (rows := rows parameters.plan) + (SourceQuestionLowerForms.slots ((Nodes.path upper).append pDown) outside clauses q) upper) → + HierarchicalFrozenTables.QuotientMatrix + (SourceQuestionLowerForms.slots ((Nodes.path upper).append pDown) outside clauses q) + upper (height + 1) bg → Prop) + (density threshold : ℝ) + +local instance rowSpaceFintype (q : FixedSourceGlobalCollision.Questions + (m := m) parameters (height := height)) : + Fintype (NodeEmbedding.RowSpace + (SourceQuestionLowerForms.slots ((Nodes.path upper).append pDown) outside clauses q) upper) := + Fintype.ofFinite _ + +local instance upperAnswerFintype (q : FixedSourceGlobalCollision.Questions + (m := m) parameters (height := height)) : + Fintype (HierarchicalAllDecoderTables.UpperAnswer + (SourceQuestionLowerForms.slots ((Nodes.path upper).append pDown) outside clauses q) upper) := + LeftDecoder.dualFintype + (V := NodeEmbedding.RowSpace + (SourceQuestionLowerForms.slots ((Nodes.path upper).append pDown) outside clauses q) upper) + +local instance directionNonempty : + Nonempty (BucketSampler.Direction (rows parameters.plan (height + 1))) := + ⟨BucketUniform.coordinateDirection ⟨0, lt_of_lt_of_le Nat.zero_lt_one + (parameters.plan.rows_pos (parameters.plan.depth - (height + 1)))⟩⟩ + +omit [NeZero m] in +theorem tag_collision_eq + (direction : BucketSampler.Direction (rows parameters.plan (height + 1))) + (q : FixedSourceGlobalCollision.Questions (m := m) parameters (height := height)) + (table : SourceQuestionLowerForms.UpperTable (rows := rows parameters.plan) + ((Nodes.path upper).append pDown) outside clauses upper (height + 1) + (adviceRows := adviceRows) q) : + (FixedSourcePhysicalHigh.tagLaw parameters).expectation (fun tag => + SourceQuestionPhysicalHigh.collision ((Nodes.path upper).append pDown) outside placeholder + clauses designated q tag.1 tag.2 upper (height + 1) d + (FixedLowerRawCollision.branchPositive parameters) A exterior direction + (cutoff parameters.plan hδ) table) = + FixedSourceGlobalCollision.localProbability parameters ((Nodes.path upper).append pDown) + outside placeholder clauses designated upper d A exterior q table direction := by + simpa only [FixedSourcePhysicalHigh.tagLaw, SourceProjectedTag.law, + FiniteDistribution.expectation_product, FixedSourceGlobalCollision.localProbability, + FixedSourceGlobalCollision.localTables, Function.update_self] using + (SourceQuestionPhysicalCollision.mean_collision_eq ((Nodes.path upper).append pDown) + outside placeholder clauses designated upper (height + 1) d + (FixedLowerRawCollision.branchPositive parameters) A exterior q direction + (cutoff parameters.plan hδ) + (FixedSourceGlobalCollision.localTables parameters ((Nodes.path upper).append pDown) + outside clauses upper q table) (FixedSourceGlobalCollision.flag parameters)) + +theorem probability_square_le (hdensity : 0 < density) : + FixedSourcePhysicalHigh.probability parameters outside placeholder clauses designated upper pDown + hproper d hnode A cut exterior σ useful density threshold ^ 2 ≤ + FixedRankContradiction.gamma parameters (Nodes.height upper) ^ 2 / 8 + + 2 * parameters.accuracy := by + have h := FixedSourcePhysicalHigh.probability_square_le_collision parameters outside placeholder + clauses designated upper pDown hproper d hnode A cut exterior σ useful density threshold + simp_rw [tag_collision_eq] at h + exact h.trans (FixedSourceGlobalCollision.mean_local_le parameters ((Nodes.path upper).append pDown) + outside placeholder clauses designated upper d hnode A exterior σ useful density hdensity) + +end +end PerfectCompleteness.FixedSourceHighBound + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedStoppedActualBounds.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedStoppedActualBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..39ef4572a61d3bd968b6f64271a5b16a886ebe6e --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedStoppedActualBounds.lean @@ -0,0 +1,79 @@ +import OAI.Computability.PerfectCompleteness.Foundations.StoppedProjectedCoarseLemmas +import OAI.Computability.PerfectCompleteness.Reduction.FixedStoppedInverseBound +import OAI.Computability.PerfectCompleteness.Reduction.FixedStoppedUsefulMass +import OAI.Computability.PerfectCompleteness.Sampling.StoppedProjectedUsefulProbability + +namespace OAI + +section + +namespace PerfectCompleteness.FixedStoppedActualBounds + +noncomputable section + +open scoped Classical +open RecursiveSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype + +variable {δ : ℚ} {hδ : 0 < δ} (parameters : FixedParameters.Parameters δ hδ) + (i j : Fin parameters.plan.depth) (hij : i < j) (input : List Bool) + (strategy : FixedPreliminaryGame.Strategy parameters input) + +theorem usefulMass_ge + (hreserve : InitialParameters.simultaneous δ + 2 * parameters.accuracy ≤ + (StoppedSharedSampler.stoppedLaw + (PCPSource.clauseFamily (BinaryLanguage.totalRename input)) + (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (Nat.succ_le_of_lt i.isLt) (fun k _ => FixedParameters.branch_pos parameters k) + (fun k => FixedPreliminaryGame.rows_pos parameters (k + 1))).probability + (StoppedSharedEvents.pair (PCPSource.clauseFamily (BinaryLanguage.totalRename input)) + strategy (Nat.succ_le_of_lt i.isLt) + (fun k _ => FixedParameters.branch_pos parameters k) i j)) : + InitialParameters.simultaneous δ / 2 ≤ + FixedStoppedInverseBound.usefulMass parameters i j hij input strategy := by + have heq := StoppedProjectedUsefulProbability.usefulMass_eq_original + (PCPSource.clauseFamily (BinaryLanguage.totalRename input)) + (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij (FixedStoppedPhysicalLaw.designated parameters i) + (fun k _ => FixedParameters.branch_pos parameters k) + (StoppedProjectedMeetingLaw.rows_positive parameters.plan) + (FixedStoppedDecoderLaw.flag parameters i) + (FixedStoppedDecoderLaw.labeling parameters input strategy) + (InitialParameters.useful δ) (FixedStoppedInverseBound.outerLaw parameters j input) + change FixedStoppedInverseBound.usefulMass parameters i j hij input strategy = + (FixedStoppedUsefulMass.originalLaw parameters i j hij input + (FixedStoppedPhysicalLaw.designated parameters i) strategy).probability + (HierarchicalUsefulFamily.usefulEvent + (FixedStoppedUsefulMass.experiment parameters i j hij input + (FixedStoppedPhysicalLaw.designated parameters i) strategy) + (InitialParameters.useful δ) + (FixedStoppedUsefulMass.upperEvent parameters i j hij input + (FixedStoppedPhysicalLaw.designated parameters i) strategy)) at heq + rw [heq] + exact FixedStoppedUsefulMass.useful_probability_ge_of_reserve parameters i j hij input + (FixedStoppedPhysicalLaw.designated parameters i) strategy hreserve + +theorem coarseVariation_le_pairedVariation : + FixedStoppedInverseBound.coarseVariation parameters i j hij input strategy ≤ + FixedStoppedInverseBound.pairedVariation parameters i j hij input strategy := + StoppedProjectedCoarse.totalVariation_le_pair + (PCPSource.clauseFamily (BinaryLanguage.totalRename input)) + (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij (FixedStoppedPhysicalLaw.designated parameters i) + (fun k _ => FixedParameters.branch_pos parameters k) + (StoppedProjectedMeetingLaw.rows_positive parameters.plan) + (FixedStoppedDecoderLaw.flag parameters i) + (FixedStoppedDecoderLaw.labeling parameters input strategy) + (FixedStoppedInverseBound.outerLaw parameters j input) + (FixedStoppedInverseBound.backgrounds parameters i j hij input strategy) + parameters.plan.order + +end +end PerfectCompleteness.FixedStoppedActualBounds + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedStoppedContradiction.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedStoppedContradiction.lean new file mode 100644 index 0000000000000000000000000000000000000000..893b6331ba0d91e383c222103e1d0acde4cee62a --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedStoppedContradiction.lean @@ -0,0 +1,44 @@ +import OAI.Computability.PerfectCompleteness.Decoding.DecoderFamilyLawLemmas +import OAI.Computability.PerfectCompleteness.Reduction.FixedStoppedHighBound + +namespace OAI + +section + +namespace PerfectCompleteness.FixedStoppedContradiction + +noncomputable section + +attribute [local instance] FixedStoppedDecoderLaw.sampleFintype + UniqueGamesTheorem.Appendix.RankLevelFilter.linearMapFintype + +variable {δ : ℚ} {hδ : 0 < δ} (parameters : FixedParameters.Parameters δ hδ) + (i j : Fin parameters.plan.depth) (hij : i < j) (input : List Bool) + +theorem meeting_lt_gamma + (strategy : FixedPreliminaryGame.Strategy parameters input) + (unsat : ¬BinaryLanguage.language input) : + (FixedStoppedDecoderLaw.law parameters i j hij input strategy).probability + (FixedStoppedDecoderLaw.meeting parameters i j hij input) < + FixedRankContradiction.gamma parameters (j.val + 1) := by + apply lt_of_not_ge + intro hupper + exact FixedDecoderFamilyContradiction.impossible parameters + (FixedStoppedDecoderContext.geometry parameters i j hij input) input + (FixedStoppedDecoderLaw.labeling parameters input strategy) + (FixedStoppedDecoderLaw.useful parameters i j hij input strategy) + parameters.plan.order parameters.plan.density + (FixedStoppedDecoderContext.advice parameters i j hij input) + (FixedStoppedDecoderContext.direction parameters i j hij input) + (FixedStoppedDecoderLaw.threshold parameters j) + (FixedStoppedDecoderContext.law parameters i j hij input) + unsat (le_refl _) parameters.plan.density_pos + (j.val + 1) (Nat.succ_le_of_lt j.isLt) hupper + (FixedStoppedHighBound.probability_square_le parameters i j hij input strategy) + +end +end PerfectCompleteness.FixedStoppedContradiction + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedStoppedDirections.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedStoppedDirections.lean new file mode 100644 index 0000000000000000000000000000000000000000..42e2cdc2f1893a6ef9c389b3c0aac401c11129d4 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedStoppedDirections.lean @@ -0,0 +1,197 @@ +import OAI.Computability.PerfectCompleteness.Decoding.FixedStoppedDecoderContext +import OAI.Computability.PerfectCompleteness.Sampling.CandidateCoupling + +namespace OAI + +section + +namespace PerfectCompleteness.FixedStoppedDirections + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype + +variable {δ : ℚ} {hδ : 0 < δ} (parameters : FixedParameters.Parameters δ hδ) + (i j : Fin parameters.plan.depth) (hij : i < j) + +abbrev lowerNode (pref : FixedStoppedDecoderContext.Prefixes parameters i j) := + HierarchicalLeftDecoder.LowerNode (FixedStoppedDecoderContext.upper parameters i j pref) + (i.val + 1) (FixedStoppedDecoderContext.lower parameters i j hij pref) + +@[simp] theorem lowerNode_height (pref : FixedStoppedDecoderContext.Prefixes parameters i j) : + Nodes.height (lowerNode parameters i j hij pref) = i.val + 1 := + CleanDecoderContext.lowerHeight (FixedStoppedDecoderContext.upper parameters i j pref) + (FixedStoppedDecoderContext.lower parameters i j hij pref) + +abbrev LowerDirection (pref : FixedStoppedDecoderContext.Prefixes parameters i j) := + BucketSampler.Direction + (FixedRows.rows parameters.plan (Nodes.height (lowerNode parameters i j hij pref))) + +instance lowerDirectionNonempty (pref : FixedStoppedDecoderContext.Prefixes parameters i j) : + Nonempty (LowerDirection parameters i j hij pref) := + PreliminarySampler.directionNonempty _ (by + rw [lowerNode_height] + exact parameters.plan.rows_pos (parameters.plan.depth - (i.val + 1))) + +def lowerDirectionEquiv (pref : FixedStoppedDecoderContext.Prefixes parameters i j) : + PrefixTests.LevelDirection (FixedRows.rows parameters.plan) i ≃ + LowerDirection parameters i j hij pref := + (Equiv.cast (congrArg (fun height => + BucketSampler.Direction (FixedRows.rows parameters.plan height)) + (lowerNode_height parameters i j hij pref))).symm + +def lowerDirection (pref : FixedStoppedDecoderContext.Prefixes parameters i j) + (directions : FixedStoppedDecoderContext.Directions parameters) : + LowerDirection parameters i j hij pref := + PrefixTests.nodeDirection (FixedRows.rows parameters.plan) i + ⟨lowerNode parameters i j hij pref, lowerNode_height parameters i j hij pref⟩ (directions i) + +theorem lowerDirection_eq_equiv (pref : FixedStoppedDecoderContext.Prefixes parameters i j) + (directions : FixedStoppedDecoderContext.Directions parameters) : + lowerDirection parameters i j hij pref directions = + lowerDirectionEquiv parameters i j hij pref (directions i) := rfl + +def lowerLaw (pref : FixedStoppedDecoderContext.Prefixes parameters i j) : + FiniteDistribution (LowerDirection parameters i j hij pref) := + FiniteDistribution.uniform _ + +theorem coordinate_law (level : Fin parameters.plan.depth) : + (FixedStoppedDecoderContext.directionLaw parameters).pushforward + (fun directions => directions level) = + CanonicalDirections.levelLaw (FixedRows.rows parameters.plan) + (fun k => parameters.plan.rows_pos (parameters.plan.depth - (k + 1))) level := + FiniteProduct.eval_pushforward + (CanonicalDirections.levelLaw (FixedRows.rows parameters.plan) + (fun k => parameters.plan.rows_pos (parameters.plan.depth - (k + 1)))) level + +theorem lowerDirection_law (pref : FixedStoppedDecoderContext.Prefixes parameters i j) : + (FixedStoppedDecoderContext.directionLaw parameters).pushforward + (lowerDirection parameters i j hij pref) = lowerLaw parameters i j hij pref := by + let : Nonempty (PrefixTests.LevelDirection (FixedRows.rows parameters.plan) i) := + PreliminarySampler.directionNonempty _ + (parameters.plan.rows_pos (parameters.plan.depth - (i.val + 1))) + change (FixedStoppedDecoderContext.directionLaw parameters).pushforward + (fun directions => lowerDirectionEquiv parameters i j hij pref (directions i)) = _ + rw [← FiniteDistribution.pushforward_comp (FixedStoppedDecoderContext.directionLaw parameters) + (fun directions => directions i) (lowerDirectionEquiv parameters i j hij pref), coordinate_law] + change (FiniteDistribution.uniform (PrefixTests.LevelDirection (FixedRows.rows parameters.plan) i)).pushforward + (lowerDirectionEquiv parameters i j hij pref) = + FiniteDistribution.uniform (LowerDirection parameters i j hij pref) + rw [← FiniteDistribution.transport_eq_pushforward] + exact UniformConditioning.uniform_transport (lowerDirectionEquiv parameters i j hij pref) + +theorem lowerDirection_expectation (pref : FixedStoppedDecoderContext.Prefixes parameters i j) + (f : LowerDirection parameters i j hij pref → ℝ) : + (FixedStoppedDecoderContext.directionLaw parameters).expectation + (fun directions => f (lowerDirection parameters i j hij pref directions)) = + (lowerLaw parameters i j hij pref).expectation f := by + rw [← lowerDirection_law, FiniteDistribution.expectation_pushforward] + +variable (input : List Bool) + +theorem direction_eq (context : FixedStoppedDecoderContext.Context parameters i j hij input) : + FixedStoppedDecoderContext.direction parameters i j hij input context = + (lowerDirection parameters i j hij context.1 context.2.2.2.1).val := rfl + +theorem expectation_coordinate + (f : (pref : FixedStoppedDecoderContext.Prefixes parameters i j) → + (external : FixedStoppedDecoderContext.OutsideQuestions parameters i j hij input pref) → + FixedStoppedDecoderContext.Advice parameters i j pref → + FixedStoppedDecoderContext.Exterior parameters i j hij input pref external → + PrefixTests.LevelDirection (FixedRows.rows parameters.plan) i → ℝ) : + (FixedStoppedDecoderContext.law parameters i j hij input).expectation (fun context => + f context.1 context.2.1 context.2.2.1 context.2.2.2.2 (context.2.2.2.1 i)) = + (FixedStoppedDecoderContext.prefixLaw parameters i j hij).expectation (fun pref => + (FiniteDistribution.uniform + (FixedStoppedDecoderContext.OutsideQuestions parameters i j hij input pref)).expectation + (fun external => + (FiniteDistribution.uniform (FixedStoppedDecoderContext.Advice parameters i j pref)).expectation + (fun A => + (FiniteDistribution.uniform + (FixedStoppedDecoderContext.Exterior parameters i j hij input pref external)).expectation + (fun exterior => + (CanonicalDirections.levelLaw (FixedRows.rows parameters.plan) + (fun k => parameters.plan.rows_pos (parameters.plan.depth - (k + 1))) i).expectation + (fun direction => f pref external A exterior direction))))) := by + rw [FixedStoppedDecoderContext.law, CandidateCoupling.expectation_sigmaLaw] + apply FiniteDistribution.expectation_congr + intro pref + rw [CandidateCoupling.expectation_sigmaLaw] + apply FiniteDistribution.expectation_congr + intro external + rw [FixedStoppedDecoderContext.fiberLaw, FiniteDistribution.expectation_product] + apply FiniteDistribution.expectation_congr + intro A + rw [FiniteDistribution.expectation_product, FiniteDistribution.expectation_comm] + apply FiniteDistribution.expectation_congr + intro exterior + rw [← coordinate_law parameters i, FiniteDistribution.expectation_pushforward] + +theorem expectation_lowerDirection + (f : (pref : FixedStoppedDecoderContext.Prefixes parameters i j) → + (external : FixedStoppedDecoderContext.OutsideQuestions parameters i j hij input pref) → + FixedStoppedDecoderContext.Advice parameters i j pref → + FixedStoppedDecoderContext.Exterior parameters i j hij input pref external → + LowerDirection parameters i j hij pref → ℝ) : + (FixedStoppedDecoderContext.law parameters i j hij input).expectation (fun context => + f context.1 context.2.1 context.2.2.1 context.2.2.2.2 + (lowerDirection parameters i j hij context.1 context.2.2.2.1)) = + (FixedStoppedDecoderContext.prefixLaw parameters i j hij).expectation (fun pref => + (FiniteDistribution.uniform + (FixedStoppedDecoderContext.OutsideQuestions parameters i j hij input pref)).expectation + (fun external => + (FiniteDistribution.uniform (FixedStoppedDecoderContext.Advice parameters i j pref)).expectation + (fun A => + (FiniteDistribution.uniform + (FixedStoppedDecoderContext.Exterior parameters i j hij input pref external)).expectation + (fun exterior => + (lowerLaw parameters i j hij pref).expectation + (fun direction => f pref external A exterior direction))))) := by + rw [FixedStoppedDecoderContext.law, CandidateCoupling.expectation_sigmaLaw] + apply FiniteDistribution.expectation_congr + intro pref + rw [CandidateCoupling.expectation_sigmaLaw] + apply FiniteDistribution.expectation_congr + intro external + rw [FixedStoppedDecoderContext.fiberLaw, FiniteDistribution.expectation_product] + apply FiniteDistribution.expectation_congr + intro A + rw [FiniteDistribution.expectation_product, FiniteDistribution.expectation_comm] + apply FiniteDistribution.expectation_congr + intro exterior + exact lowerDirection_expectation parameters i j hij pref (f pref external A exterior) + +theorem expectation_direction + (f : (pref : FixedStoppedDecoderContext.Prefixes parameters i j) → + (external : FixedStoppedDecoderContext.OutsideQuestions parameters i j hij input pref) → + FixedStoppedDecoderContext.Advice parameters i j pref → + FixedStoppedDecoderContext.Exterior parameters i j hij input pref external → + Block (FixedRows.rows parameters.plan) (lowerNode parameters i j hij pref) → ℝ) : + (FixedStoppedDecoderContext.law parameters i j hij input).expectation (fun context => + f context.1 context.2.1 context.2.2.1 context.2.2.2.2 + (FixedStoppedDecoderContext.direction parameters i j hij input context)) = + (FixedStoppedDecoderContext.prefixLaw parameters i j hij).expectation (fun pref => + (FiniteDistribution.uniform + (FixedStoppedDecoderContext.OutsideQuestions parameters i j hij input pref)).expectation + (fun external => + (FiniteDistribution.uniform (FixedStoppedDecoderContext.Advice parameters i j pref)).expectation + (fun A => + (FiniteDistribution.uniform + (FixedStoppedDecoderContext.Exterior parameters i j hij input pref external)).expectation + (fun exterior => + (lowerLaw parameters i j hij pref).expectation + (fun direction => f pref external A exterior direction.val))))) := + expectation_lowerDirection parameters i j hij input + (fun pref external A exterior direction => f pref external A exterior direction.val) + +end +end PerfectCompleteness.FixedStoppedDirections + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedStoppedError.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedStoppedError.lean new file mode 100644 index 0000000000000000000000000000000000000000..0e8c3535ebb96d64f6a9a15bfbbd7b1afe64d0ad --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedStoppedError.lean @@ -0,0 +1,58 @@ +import OAI.Computability.PerfectCompleteness.Foundations.StoppedSharedComparison +import OAI.Computability.PerfectCompleteness.Reduction.FixedComparisonErrorsLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.FixedStoppedError + +open FixedParameters FixedRows + +noncomputable section + +variable {δ : ℚ} {hδ : 0 < δ} (p : Parameters δ hδ) + +theorem original_calls_le {root cutoff : Nat} + (hroot : root ≤ p.plan.depth) (hcut : cutoff ≤ root) : + OriginalCutCalls.count (rows p.plan) (repeats p.plan) root cutoff ≤ calls p.plan := by + have h := FixedCallBudget.pairCount_le (rows p.plan) (repeats p.plan) + hroot (hcut.trans hroot) + unfold FixedCallBudget.pairCount at h + unfold calls + omega + +theorem original_calls_add_one_le {root cutoff : Nat} + (hroot : root ≤ p.plan.depth) (hcut : cutoff ≤ root) : + OriginalCutCalls.count (rows p.plan) (repeats p.plan) root cutoff + 1 ≤ calls p.plan := by + have h := FixedCallBudget.pairCount_le (rows p.plan) (repeats p.plan) + hroot (hcut.trans hroot) + unfold FixedCallBudget.pairCount at h + unfold calls + omega + +theorem hidden_error_lt {retained : Nat} (hcalls : retained ≤ calls p.plan) (height : Nat) : + Real.sqrt ((ChildBlockCardinality.bound (branch p) height (sourceLength p.plan hδ) + retained (rows p.plan) : ℝ) ^ 2 / branch p height) / 2 < p.accuracy := by + have h := (FixedComparisonErrors.comparison_errors p hcalls height).1 + simpa only [branch, Nat.cast_pow] using h + +theorem stopped_error_lt {root cut : Nat} + (hroot : root ≤ p.plan.depth) (hcut : cut + 1 ≤ root) : + StoppedSharedComparison.error (branch p) (rows p.plan) (repeats p.plan) + root cut (sourceLength p.plan hδ) < p.accuracy := + hidden_error_lt p (original_calls_le p hroot hcut) cut + +theorem collision_error_lt {root cut : Nat} + (hroot : root ≤ p.plan.depth) (hcut : cut + 1 ≤ root) : + Real.sqrt ((ChildBlockCardinality.bound (branch p) cut (sourceLength p.plan hδ) + (OriginalCutCalls.count (rows p.plan) (repeats p.plan) root (cut + 1) + 1) + (rows p.plan) : ℝ) ^ 2 / branch p cut) / 2 < p.accuracy := + hidden_error_lt p (original_calls_add_one_le p hroot hcut) cut + +end +end PerfectCompleteness.FixedStoppedError + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedStoppedHighBound.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedStoppedHighBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..b6fffe830d84ef4946670e1fa2e2daa8caafa3d8 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedStoppedHighBound.lean @@ -0,0 +1,200 @@ +import OAI.Computability.PerfectCompleteness.Decoding.FixedStoppedDecoderLaw +import OAI.Computability.PerfectCompleteness.Machines.LowerCutInstalledInput +import OAI.Computability.PerfectCompleteness.Reduction.FixedNativeHigh +import OAI.Computability.PerfectCompleteness.Reduction.FixedStoppedDirections + +namespace OAI + +section + +namespace PerfectCompleteness.FixedStoppedHighBound + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype + +variable {δ : ℚ} {hδ : 0 < δ} (parameters : FixedParameters.Parameters δ hδ) + (i j : Fin parameters.plan.depth) (hij : i < j) (input : List Bool) + +abbrev Prefixes := FixedStoppedDecoderContext.Prefixes parameters i j + +def setup (pref : Prefixes parameters i j) + (external : FixedStoppedDecoderContext.OutsideQuestions parameters i j hij input pref) + (exterior : FixedStoppedDecoderContext.Exterior parameters i j hij input pref external) := + FixedDecoderCleanRate.setup parameters + (StoppedCleanGeometry.geometry parameters input + (FixedStoppedDecoderContext.upperPath parameters i j pref) + (FixedStoppedDecoderContext.lowerPath parameters i j hij pref) hij external exterior) input + +theorem setup_node (pref : Prefixes parameters i j) + (external : FixedStoppedDecoderContext.OutsideQuestions parameters i j hij input pref) + (exterior : FixedStoppedDecoderContext.Exterior parameters i j hij input pref external) : + WholeArrayInteriorExterior.upperNode + (CleanDecoderRate.path (setup parameters i j hij input pref external exterior)) = + FixedStoppedDirections.lowerNode parameters i j hij pref := by + change WholeArrayInteriorExterior.upperNode + (CleanRecordDecoderInput.path _ _ + (StoppedCleanGeometry.geometry parameters input + (FixedStoppedDecoderContext.upperPath parameters i j pref) + (FixedStoppedDecoderContext.lowerPath parameters i j hij pref) hij external exterior).cut) = _ + rw [StoppedCleanGeometry.geometry_path] + exact (StoppedCleanGeometry.lowerNode_descendant + (FixedStoppedDecoderContext.upperPath parameters i j pref) + (FixedStoppedDecoderContext.lowerPath parameters i j hij pref) hij).symm + +def highProbability (strategy : FixedPreliminaryGame.Strategy parameters input) + (pref : Prefixes parameters i j) + (external : FixedStoppedDecoderContext.OutsideQuestions parameters i j hij input pref) + (A : FixedStoppedDecoderContext.Advice parameters i j pref) + (exterior : FixedStoppedDecoderContext.Exterior parameters i j hij input pref external) + (a : Block (FixedRows.rows parameters.plan) + (FixedStoppedDirections.lowerNode parameters i j hij pref)) : ℝ := + (CleanDecoderPairLaw.pairLaw (setup parameters i j hij input pref external exterior) + (FixedStoppedDecoderLaw.labeling parameters input strategy) + (CleanPhysicalDecoderLaw.useful (setup parameters i j hij input pref external exterior) + (FixedStoppedDecoderLaw.markFamily parameters i j hij input strategy pref) + (InitialParameters.useful δ)) parameters.plan.order parameters.plan.density A + (LinearMap.ker A) a (FixedStoppedDecoderLaw.threshold parameters j) + (parameters.cubeSize i.val) (FixedDecoderCleanRate.cubePositive parameters i.val)).probability + (fun z => DecoderRankSplit.highAgrees + (setup parameters i j hij input pref external exterior) + (FixedDecoderCleanRate.branchPositive parameters) + (FixedRows.cutoff parameters.plan hδ) z.1 z.2) + +def directionMean (strategy : FixedPreliminaryGame.Strategy parameters input) + (pref : Prefixes parameters i j) + (external : FixedStoppedDecoderContext.OutsideQuestions parameters i j hij input pref) + (A : FixedStoppedDecoderContext.Advice parameters i j pref) + (exterior : FixedStoppedDecoderContext.Exterior parameters i j hij input pref external) : ℝ := + (FixedStoppedDirections.lowerLaw parameters i j hij pref).expectation + (fun a => highProbability parameters i j hij input strategy pref external A exterior a.val) + +private theorem castDirection_eq {branch rows : Nat → Nat} {n : Nat} + {node node' : Nodes branch n} (h : node = node') + (a : BucketSampler.Direction (rows (Nodes.height node))) : + ProjectedFiberRawPair.castDirection h a = + LowerCutInstalledInput.directionCast rows h a := by + cases h + rfl + +theorem directionMean_eq_native + (strategy : FixedPreliminaryGame.Strategy parameters input) + (pref : Prefixes parameters i j) + (external : FixedStoppedDecoderContext.OutsideQuestions parameters i j hij input pref) + (A : FixedStoppedDecoderContext.Advice parameters i j pref) + (exterior : FixedStoppedDecoderContext.Exterior parameters i j hij input pref external) : + directionMean parameters i j hij input strategy pref external A exterior = + FixedNativeHigh.probability parameters (setup parameters i j hij input pref external exterior) + (setup_node parameters i j hij input pref external exterior) + (FixedStoppedDecoderLaw.markFamily parameters i j hij input strategy pref) + (InitialParameters.useful δ) (FixedStoppedDecoderLaw.labeling parameters input strategy) + parameters.plan.order parameters.plan.density A + (FixedStoppedDecoderLaw.threshold parameters j) := by + let : Nonempty (BucketSampler.Direction (FixedRows.rows parameters.plan (i.val + 1))) := + PreliminarySampler.directionNonempty _ + (parameters.plan.rows_pos (parameters.plan.depth - (i.val + 1))) + let e := LowerCutInstalledInput.lowerDirectionEquiv (FixedRows.rows parameters.plan) + (CleanDecoderRate.path (setup parameters i j hij input pref external exterior)) + (FixedStoppedDecoderContext.upper parameters i j pref) (i.val + 1) + (FixedStoppedDecoderContext.lower parameters i j hij pref) + (setup_node parameters i j hij input pref external exterior) + have htransport : + (FiniteDistribution.uniform + (BucketSampler.Direction (FixedRows.rows parameters.plan (i.val + 1)))).pushforward e = + FixedStoppedDirections.lowerLaw parameters i j hij pref := by + rw [← FiniteDistribution.transport_eq_pushforward] + exact UniformConditioning.uniform_transport e + unfold directionMean + rw [← htransport, FiniteDistribution.expectation_pushforward] + unfold FixedNativeHigh.probability + apply FiniteDistribution.expectation_congr + intro a + have hdirection : e a = + ProjectedFiberRawPair.direction + (CleanDecoderRate.path (setup parameters i j hij input pref external exterior)) + (FixedStoppedDecoderContext.upper parameters i j pref) (i.val + 1) + (FixedStoppedDecoderContext.lower parameters i j hij pref) + (setup_node parameters i j hij input pref external exterior) a := by + unfold e LowerCutInstalledInput.lowerDirectionEquiv ProjectedFiberRawPair.direction + exact (castDirection_eq _ _).symm + rw [hdirection] + rfl + +theorem directionMean_square_le + (strategy : FixedPreliminaryGame.Strategy parameters input) + (pref : Prefixes parameters i j) + (external : FixedStoppedDecoderContext.OutsideQuestions parameters i j hij input pref) + (A : FixedStoppedDecoderContext.Advice parameters i j pref) + (exterior : FixedStoppedDecoderContext.Exterior parameters i j hij input pref external) : + directionMean parameters i j hij input strategy pref external A exterior ^ 2 ≤ + FixedRankContradiction.gamma parameters (j.val + 1) ^ 2 / 8 + 2 * parameters.accuracy := by + rw [directionMean_eq_native] + simpa only [WholeArrayInteriorExterior.upperNode_height] using + FixedNativeHigh.probability_square_le parameters + (setup parameters i j hij input pref external exterior) + (setup_node parameters i j hij input pref external exterior) + (FixedStoppedDecoderLaw.markFamily parameters i j hij input strategy pref) + (InitialParameters.useful δ) (FixedStoppedDecoderLaw.labeling parameters input strategy) + parameters.plan.order parameters.plan.density A + (FixedStoppedDecoderLaw.threshold parameters j) parameters.plan.density_pos + +theorem probability_eq_mean (strategy : FixedPreliminaryGame.Strategy parameters input) : + (FixedStoppedDecoderLaw.law parameters i j hij input strategy).probability + (FixedStoppedDecoderLaw.highAgreement parameters i j hij input) = + (FixedStoppedDecoderContext.prefixLaw parameters i j hij).expectation (fun pref => + (FiniteDistribution.uniform + (FixedStoppedDecoderContext.OutsideQuestions parameters i j hij input pref)).expectation + (fun external => + (FiniteDistribution.uniform + (FixedStoppedDecoderContext.Advice parameters i j pref)).expectation (fun A => + (FiniteDistribution.uniform + (FixedStoppedDecoderContext.Exterior parameters i j hij input pref external)).expectation + (directionMean parameters i j hij input strategy pref external A)))) := by + exact (DecoderFamilyLaw.probability_eq_expectation + (FixedStoppedDecoderLaw.setups parameters i j hij input) + (FixedStoppedDecoderLaw.labeling parameters input strategy) + (FixedStoppedDecoderLaw.useful parameters i j hij input strategy) + parameters.plan.order parameters.plan.density + (FixedStoppedDecoderContext.advice parameters i j hij input) + (FixedStoppedDecoderContext.direction parameters i j hij input) + (FixedStoppedDecoderLaw.threshold parameters j) + (FixedStoppedDecoderContext.law parameters i j hij input) + (parameters.cubeSize i.val) (FixedDecoderCleanRate.cubePositive parameters i.val) + (FixedStoppedDecoderLaw.highAgreement parameters i j hij input)).trans + (FixedStoppedDirections.expectation_direction parameters i j hij input + (highProbability parameters i j hij input strategy)) + +private theorem mean_square_le_const {Ω : Type*} [Fintype Ω] + (μ : FiniteDistribution Ω) (f : Ω → ℝ) (bound : ℝ) + (hbound : ∀ x, f x ^ 2 ≤ bound) : μ.expectation f ^ 2 ≤ bound := by + calc + _ ≤ μ.expectation (fun x => f x ^ 2) := CollisionAveraging.mean_square_le μ f + _ ≤ μ.expectation (fun _ => bound) := SmallBias.expectation_mono μ hbound + _ = bound := SmallBias.expectation_const μ bound + +theorem probability_square_le (strategy : FixedPreliminaryGame.Strategy parameters input) : + (FixedStoppedDecoderLaw.law parameters i j hij input strategy).probability + (FixedStoppedDecoderLaw.highAgreement parameters i j hij input) ^ 2 ≤ + FixedRankContradiction.gamma parameters (j.val + 1) ^ 2 / 8 + 2 * parameters.accuracy := by + rw [probability_eq_mean] + apply mean_square_le_const + intro pref + apply mean_square_le_const + intro external + apply mean_square_le_const + intro A + apply mean_square_le_const + intro exterior + exact directionMean_square_le parameters i j hij input strategy pref external A exterior + +end +end PerfectCompleteness.FixedStoppedHighBound + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedStoppedInverseBound.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedStoppedInverseBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..6df25e4eaf9aaa954e9cb02c07649505cf9fafbf --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedStoppedInverseBound.lean @@ -0,0 +1,267 @@ +import OAI.Computability.PerfectCompleteness.Construction.StoppedProjectedBuckets +import OAI.Computability.PerfectCompleteness.Decoding.FixedStoppedDecoderLaw +import OAI.Computability.PerfectCompleteness.Reduction.HierarchicalFixedAdviceFamilyLemmas +import OAI.Computability.PerfectCompleteness.Sampling.FixedStoppedPhysicalLawLemmas +import OAI.Computability.PerfectCompleteness.Sampling.StoppedProjectedMeetingLaw + +namespace OAI + +section + +namespace PerfectCompleteness.FixedStoppedInverseBound + +noncomputable section + +open scoped Classical +open RecursiveSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype + +variable {δ : ℚ} {hδ : 0 < δ} (parameters : FixedParameters.Parameters δ hδ) + (i j : Fin parameters.plan.depth) (hij : i < j) (input : List Bool) + +abbrev clauses := PCPSource.clauseFamily (BinaryLanguage.totalRename input) + +abbrev Outer := StoppedProjectedExperiment.Outer + (branch := FixedParameters.branch parameters) (n := parameters.plan.depth) + (j := j.val) (t := FixedRows.sourceLength parameters.plan hδ) + (m := (PCPSource.normalizedFormula (BinaryLanguage.totalRename input)).clauses.length) + +abbrev designated := FixedStoppedPhysicalLaw.designated parameters i + +abbrev experiment (strategy : FixedPreliminaryGame.Strategy parameters input) + (o : Outer parameters j input) := + StoppedProjectedExperiment.experiment (clauses input) + (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij (designated parameters i) + (fun k _ => FixedParameters.branch_pos parameters k) + (StoppedProjectedMeetingLaw.rows_positive parameters.plan) + (FixedStoppedDecoderLaw.flag parameters i) + (FixedStoppedDecoderLaw.labeling parameters input strategy) o + +abbrev outerLaw : FiniteDistribution (Outer parameters j input) := + StoppedProjectedExperiment.outerLaw (Nat.succ_le_of_lt j.isLt) + (fun k _ => FixedParameters.branch_pos parameters k) + +abbrev externalLaw (o : Outer parameters j input) := + StoppedProjectedBuckets.externalLaw (clauses input) + (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij (designated parameters i) + (StoppedProjectedMeetingLaw.rows_positive parameters.plan) o + (fun k _ => FixedParameters.branch_pos parameters k) + (FixedStoppedDecoderLaw.flag parameters i) + +abbrev background (o : Outer parameters j input) := + StoppedProjectedBuckets.background (clauses input) + (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij (designated parameters i) + (StoppedProjectedMeetingLaw.rows_positive parameters.plan) o + +abbrev scalarLaw (o : Outer parameters j input) := + StoppedProjectedBuckets.scalarLaw (clauses input) + (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij (designated parameters i) + (StoppedProjectedMeetingLaw.rows_positive parameters.plan) o + +variable (strategy : FixedPreliminaryGame.Strategy parameters input) + +local notation "S" => experiment parameters i j hij input strategy + +local instance nativeBackgroundFintype (o : Outer parameters j input) : + Fintype (HierarchicalMatrixTable.Background (rows := FixedRows.rows parameters.plan) + (StoppedProjectedExperiment.nativeSlots (clauses input) o) + (StoppedProjectedExperiment.upper (Nat.succ_le_of_lt j.isLt) o)) := + HierarchicalUsefulCollision.backgroundFintype (rows := FixedRows.rows parameters.plan) + (StoppedProjectedExperiment.nativeSlots (clauses input) o) + (StoppedProjectedExperiment.upper (Nat.succ_le_of_lt j.isLt) o) + +local instance nativeRowSpaceFintype (o : Outer parameters j input) : + Fintype (NodeEmbedding.RowSpace + (StoppedProjectedExperiment.nativeSlots (clauses input) o) + (StoppedProjectedExperiment.upper (Nat.succ_le_of_lt j.isLt) o)) := + HierarchicalUsefulCollision.rowSpaceFintype + (StoppedProjectedExperiment.nativeSlots (clauses input) o) + (StoppedProjectedExperiment.upper (Nat.succ_le_of_lt j.isLt) o) + +abbrev PairFiber (o : Outer parameters j input) := + HierarchicalAgreementMean.PairRecord (rows := FixedRows.rows parameters.plan) + (StoppedProjectedExperiment.nativeSlots (clauses input) o) + (StoppedProjectedExperiment.upper (Nat.succ_le_of_lt j.isLt) o) + +abbrev PairSample := (o : Outer parameters j input) × PairFiber parameters j input o + +local instance pairFiberFintype (o : Outer parameters j input) : + Fintype (PairFiber parameters j input o) := by + unfold PairFiber HierarchicalAgreementMean.PairRecord + infer_instance + +local instance pairSampleFintype : Fintype (PairSample parameters j input) := + Sigma.instFintype + +local instance backgroundFintype (o : Outer parameters j input) : + Fintype (HierarchicalAdviceExperiment.Background (S o)) := + HierarchicalAdviceExperiment.backgroundFintype (S o) + +local instance coarseFintype (o : Outer parameters j input) : + Fintype (HierarchicalAdviceExperiment.Coarse (S o)) := + HierarchicalAdviceFamily.coarseFintype S o + +local instance inputFintype (o : Outer parameters j input) + (bg : HierarchicalAdviceExperiment.Background (S o)) : + Fintype (HierarchicalAdviceExperiment.Input (S o) bg) := + HierarchicalAdviceExperiment.inputFintype (S o) bg + +local instance inputFiniteDimensional (o : Outer parameters j input) + (bg : HierarchicalAdviceExperiment.Background (S o)) : + FiniteDimensional F2 (HierarchicalAdviceExperiment.Input (S o) bg) := + HierarchicalAdviceExperiment.inputFiniteDimensional (S o) bg + +local instance projectedSampleFintype (o : Outer parameters j input) : + Fintype (HierarchicalProjectedExperiment.Sample + (rows := FixedRows.rows parameters.plan) (repeats := FixedRows.repeats parameters.plan) + (StoppedProjectedExperiment.projectedSlots (clauses input) (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij (designated parameters i) o) + (StoppedProjectedExperiment.upper (Nat.succ_le_of_lt j.isLt) o) + (StoppedProjectedExperiment.lower (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij o) + (StoppedProjectedExperiment.cut (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij o)) := by + letI : (k : StoppedProjectedExperiment.Inner + (branch := FixedParameters.branch parameters) (n := parameters.plan.depth) + (i := i.val) (j := j.val) (t := FixedRows.sourceLength parameters.plan hδ) + (FixedRows.rows parameters.plan)) → + Fintype (WholeArraySampler.Tape (FixedRows.rows parameters.plan) + (FixedRows.repeats parameters.plan) + (WholeArrayInteriorOwnInputLaw.fullPath + (StoppedProjectedExperiment.upper (Nat.succ_le_of_lt j.isLt) o) + (StoppedProjectedExperiment.lower (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij o k) + (StoppedProjectedExperiment.cut (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij o k)) + (StoppedProjectedExperiment.projectedSlots (clauses input) (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij (designated parameters i) o k)) := + fun k => WholeArraySampler.tapeFintype _ _ _ _ + exact Sigma.instFintype + +local instance adviceFintype (o : Outer parameters j input) (r : Nat) : + Fintype (HierarchicalAdviceExperiment.Advice (S o) r) := linearMapFintype + +local instance originalFiberFintype (o : Outer parameters j input) (r : Nat) : + Fintype (HierarchicalProjectedExperiment.Sample + (rows := FixedRows.rows parameters.plan) (repeats := FixedRows.repeats parameters.plan) + (StoppedProjectedExperiment.projectedSlots (clauses input) (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij (designated parameters i) o) + (StoppedProjectedExperiment.upper (Nat.succ_le_of_lt j.isLt) o) + (StoppedProjectedExperiment.lower (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij o) + (StoppedProjectedExperiment.cut (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij o) × + HierarchicalAdviceExperiment.Advice (S o) r) := by + infer_instance + +abbrev backgrounds := + HierarchicalBucketFamily.actualBackgrounds (experiment parameters i j hij input strategy) + (externalLaw parameters i j hij input) (background parameters i j hij input) + +abbrev usefulMass : ℝ := + HierarchicalBucketFamily.usefulMass (experiment parameters i j hij input strategy) + (InitialParameters.useful δ) (outerLaw parameters j input) + (externalLaw parameters i j hij input) (background parameters i j hij input) + (scalarLaw parameters i j hij input) + (HierarchicalFixedAdviceFamily.rows_positive parameters + (experiment parameters i j hij input strategy)) + +abbrev actualPairs : FiniteDistribution (PairSample parameters j input) := + HierarchicalBucketFamily.actualPairLaw (experiment parameters i j hij input strategy) + (outerLaw parameters j input) (externalLaw parameters i j hij input) + (background parameters i j hij input) (scalarLaw parameters i j hij input) + (HierarchicalFixedAdviceFamily.rows_positive parameters + (experiment parameters i j hij input strategy)) + +abbrev referencePairs : FiniteDistribution (PairSample parameters j input) := + HierarchicalBucketFamily.referencePairLaw (experiment parameters i j hij input strategy) + (outerLaw parameters j input) (backgrounds parameters i j hij input strategy) + (HierarchicalFixedAdviceFamily.rows_positive parameters + (experiment parameters i j hij input strategy)) + +abbrev pairedVariation : ℝ := + (actualPairs parameters i j hij input strategy).totalVariation + (referencePairs parameters i j hij input strategy) + +abbrev coarseVariation : ℝ := + ((HierarchicalAdviceFamily.originalLaw (experiment parameters i j hij input strategy) + (outerLaw parameters j input) parameters.plan.order).pushforward + (HierarchicalAdviceFamily.observe (experiment parameters i j hij input strategy) + parameters.plan.order)).totalVariation + ((HierarchicalAdviceFamily.referenceLaw (experiment parameters i j hij input strategy) + (outerLaw parameters j input) (backgrounds parameters i j hij input strategy) + parameters.plan.order).pushforward + (HierarchicalAdviceFamily.referenceObserve + (experiment parameters i j hij input strategy) parameters.plan.order)) + +abbrev expectedMeeting : ℝ := + StoppedProjectedMeetingLaw.expectedMeeting parameters.plan (clauses input) + (Nat.succ_le_of_lt j.isLt) hij (designated parameters i) + (fun k _ => FixedParameters.branch_pos parameters k) + (FixedStoppedDecoderLaw.flag parameters i) + (FixedStoppedDecoderLaw.labeling parameters input strategy) + +theorem expectedMeeting_ge_gamma + (hmass : InitialParameters.simultaneous δ / 2 ≤ + usefulMass parameters i j hij input strategy) + (hpaired : pairedVariation parameters i j hij input strategy ≤ 10 * parameters.accuracy) + (hcoarse : coarseVariation parameters i j hij input strategy ≤ 10 * parameters.accuracy) : + FixedRankContradiction.gamma parameters (j.val + 1) ≤ + expectedMeeting parameters i j hij input strategy := by + have hheight (o : Outer parameters j input) : + Nodes.height (experiment parameters i j hij input strategy o).upper = j.val + 1 := + StoppedProjectedExperiment.upper_height (Nat.succ_le_of_lt j.isLt) o + have hbound := HierarchicalFixedAdviceFamily.prediction_difference parameters + (experiment parameters i j hij input strategy) (outerLaw parameters j input) + (externalLaw parameters i j hij input) (background parameters i j hij input) + (scalarLaw parameters i j hij input) (backgrounds parameters i j hij input strategy) + (j.val + 1) (Nat.succ_le_of_lt j.isLt) hheight hmass hpaired hcoarse + have hmeeting := HierarchicalProjectedOuterAverage.expectedMeeting_ge_prediction_difference + parameters.plan (StoppedProjectedExperiment.nativeSlots (clauses input)) + (StoppedProjectedExperiment.projectedSlots (clauses input) (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij (designated parameters i)) + (StoppedProjectedExperiment.projection (clauses input) (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij (designated parameters i)) + (StoppedProjectedExperiment.upper (Nat.succ_le_of_lt j.isLt)) (i.val + 1) + (StoppedProjectedExperiment.lower (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij) + (StoppedProjectedExperiment.cut (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij) + (StoppedProjectedExperiment.direction (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij) + (fun _ => StoppedProjectedExperiment.innerLaw (FixedRows.rows parameters.plan) hij + (fun k _ => FixedParameters.branch_pos parameters k) + (StoppedProjectedMeetingLaw.rows_positive parameters.plan) + (FixedStoppedDecoderLaw.flag parameters i)) + (outerLaw parameters j input) (FixedStoppedDecoderLaw.labeling parameters input strategy) + hδ (FixedRows.rows parameters.plan (j.val + 1)) + (fun o => congrArg (FixedRows.rows parameters.plan) + (StoppedProjectedExperiment.upper_height (Nat.succ_le_of_lt j.isLt) o)) + calc + _ = HierarchicalProjectedOuterAverage.factor parameters.plan + (FixedRows.rows parameters.plan (j.val + 1)) * + UpperParameterScalars.b (InitialParameters.useful δ) parameters.plan.density + (InitialParameters.inverse δ) parameters.plan.order + (FixedRows.rows parameters.plan (j.val + 1)) := + (HierarchicalProjectedOuterAverage.factor_mul_b_eq_gamma parameters.plan _).symm + _ ≤ HierarchicalProjectedOuterAverage.factor parameters.plan + (FixedRows.rows parameters.plan (j.val + 1)) * + HierarchicalFixedAdviceFamily.predictionDifference parameters + (experiment parameters i j hij input strategy) (outerLaw parameters j input) := + mul_le_mul_of_nonneg_left hbound + (HierarchicalProjectedOuterAverage.factor_nonneg parameters.plan _) + _ ≤ _ := hmeeting + +end +end PerfectCompleteness.FixedStoppedInverseBound + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedStoppedMeetingEquality.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedStoppedMeetingEquality.lean new file mode 100644 index 0000000000000000000000000000000000000000..2e0c89a0ad1c3415bb5a872cdc9025fe295dd640 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedStoppedMeetingEquality.lean @@ -0,0 +1,392 @@ +import OAI.Computability.PerfectCompleteness.Decoding.FixedStoppedDecoderLaw +import OAI.Computability.PerfectCompleteness.Decoding.FixedStoppedNativeProjection +import OAI.Computability.PerfectCompleteness.Foundations.ProjectedMeetingTransport +import OAI.Computability.PerfectCompleteness.Machines.FixedStoppedNativeTape +import OAI.Computability.PerfectCompleteness.Repetition.CleanPhysicalProjectedMeeting +import OAI.Computability.PerfectCompleteness.Repetition.StoppedCleanCutEquality +import OAI.Computability.PerfectCompleteness.Sampling.FixedStoppedPhysicalLawLemmas +import OAI.Computability.PerfectCompleteness.Sampling.StoppedProjectedMeetingLaw + +namespace OAI + +section + +namespace PerfectCompleteness.FixedStoppedMeetingEquality + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) +attribute [local instance] linearMapFintype +attribute [local instance] RightDecoder.scalarFintype + +local instance physicalLeftFintype {branch : Nat → Nat} {n t : Nat} + (slots : Slots branch n → Fin t → MixedSupport.Slot) (upper : Nodes branch n) : + Fintype (Module.Dual (ZMod 2) (NodeEmbedding.RowSpace slots upper)) := + LeftDecoder.dualFintype (V := NodeEmbedding.RowSpace slots upper) + +private theorem expectation_congr_on_support {X : Type*} [Fintype X] + (μ : FiniteDistribution X) (f g : X → ℝ) + (h : ∀ x, μ.weight x ≠ 0 → f x = g x) : + μ.expectation f = μ.expectation g := by + unfold FiniteDistribution.expectation + apply Finset.sum_congr rfl + intro x _ + by_cases hx : μ.weight x = 0 + · simp only [hx, zero_mul] + · rw [h x hx] + +private theorem nodeDirection_val_heq {branch rows : Nat → Nat} {n : Nat} + (level : Fin n) (node other : PrefixTests.LevelNode branch level) + (hn : node = other) (direction : PrefixTests.LevelDirection rows level) : + HEq (PrefixTests.nodeDirection rows level node direction).val + (PrefixTests.nodeDirection rows level other direction).val := by + cases hn + rfl + +private theorem familyMeetingProbability_eq_of_useful + {δ : ℚ} (plan : FixedRows.Plan δ) {branch : Nat → Nat} {t : Nat} + {Sample : OriginalDecoderMark.SlotFamily branch plan.depth t → Type*} + [∀ slots, Fintype (Sample slots)] + (F : OriginalDecoderMark.Family branch (FixedRows.rows plan) plan.depth t Sample) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch plan.depth t)) + (slots projected : Slots branch plan.depth → Fin t → MixedSupport.Slot) + (projection : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) + (upper lower : Nodes branch plan.depth) (lowerLevel : Nat) + {Ω : Type*} [Fintype Ω] (original : FiniteDistribution Ω) + (arrays : Ω → Arrays slots (FixedRows.rows plan)) (lowerEvent : Ω → Bool) + (A : ManyGoodRows.RowMap (Block (FixedRows.rows plan) upper) plan.order) + (a : Block (FixedRows.rows plan) lower) (cut : OwnInputReference.Cut upper lower) + (threshold : ℝ) + (visible : HierarchicalProjectedRawPrediction.Visible projected (FixedRows.rows plan) + upper lower A (FixedRows.repeats plan) cut) + (huseful : ∀ background : HierarchicalMatrixTable.Background + (rows := FixedRows.rows plan) slots upper, + HierarchicalProjectedMeeting.useful slots upper lowerLevel background + (F.original slots) (F.arrays slots) (F.lowerEvent slots) (InitialParameters.useful δ) = + HierarchicalProjectedMeeting.useful slots upper lowerLevel background + original arrays lowerEvent (InitialParameters.useful δ)) + (hthreshold : threshold = UpperParameterScalars.tau (InitialParameters.useful δ) + plan.density plan.order (FixedRows.rows plan (Nodes.height upper))) : + ProjectedMeetingTransport.familyMeetingProbability plan F σ slots projected projection + upper lower lowerLevel A a cut threshold visible = + HierarchicalProjectedRawMeeting.meetingProbability plan slots projected projection + upper lower lowerLevel original arrays lowerEvent σ A a cut visible := by + unfold ProjectedMeetingTransport.familyMeetingProbability + HierarchicalProjectedRawMeeting.meetingProbability HierarchicalProjectedMeeting.leftLaw + rw [huseful, hthreshold] + +variable {δ : ℚ} {hδ : 0 < δ} (parameters : FixedParameters.Parameters δ hδ) + (i j : Fin parameters.plan.depth) (hij : i < j) (input : List Bool) + +theorem flag_eq : + FixedStoppedDecoderLaw.flag parameters i = FixedStoppedPhysicalLaw.flag parameters i := by + funext child + apply FiniteDistribution.eq_of_weight_eq + intro b + cases b <;> simp [FixedStoppedDecoderLaw.flag, FixedStoppedPhysicalLaw.flag, + ProjectionPosterior.bernoulli, ProjectedCleanRate.projectionFlag, + RepetitionRate.bernoulli, ProjectedCleanRate.projectionDensity, + FixedParameters.projectionProbability] + +variable (strategy : FixedPreliminaryGame.Strategy parameters input) + +private abbrev OriginalRaw := StoppedProjectedMeetingLaw.RawSample + (t := FixedRows.sourceLength parameters.plan hδ) parameters.plan + (FixedStoppedPhysicalLaw.clauses input) (Nat.succ_le_of_lt j.isLt) hij + (FixedStoppedPhysicalLaw.designated parameters i) + +private def familyMeetingOnRaw (sample : OriginalRaw parameters i j hij input) : ℝ := + ProjectedMeetingTransport.familyMeetingProbability parameters.plan + (FixedStoppedDecoderLaw.markFamily parameters i j hij input strategy + (sample.1.2, sample.2.2.1.1)) + (FixedStoppedDecoderLaw.labeling parameters input strategy) + (StoppedProjectedExperiment.nativeSlots (FixedStoppedPhysicalLaw.clauses input) sample.1) + (StoppedProjectedExperiment.projectedSlots (FixedStoppedPhysicalLaw.clauses input) + (FixedRows.rows parameters.plan) (Nat.succ_le_of_lt j.isLt) hij + (FixedStoppedPhysicalLaw.designated parameters i) sample.1 sample.2.2.1) + (StoppedProjectedExperiment.projection (FixedStoppedPhysicalLaw.clauses input) + (FixedRows.rows parameters.plan) (Nat.succ_le_of_lt j.isLt) hij + (FixedStoppedPhysicalLaw.designated parameters i) sample.1 sample.2.2.1) + (StoppedProjectedExperiment.upper (Nat.succ_le_of_lt j.isLt) sample.1) + (StoppedProjectedExperiment.lower (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij sample.1 sample.2.2.1) (i.val + 1) + sample.2.1 + (StoppedProjectedExperiment.direction (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij sample.1 sample.2.2.1) + (StoppedProjectedExperiment.cut (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij sample.1 sample.2.2.1) + (FixedStoppedDecoderLaw.threshold parameters j) sample.2.2.2.2 + +private theorem familyMeetingOnRaw_eq + (sample : OriginalRaw parameters i j hij input) : + familyMeetingOnRaw parameters i j hij input strategy sample = + StoppedProjectedMeetingLaw.rawMeetingProbability parameters.plan + (branch := FixedParameters.branch parameters) + (t := FixedRows.sourceLength parameters.plan hδ) + (FixedStoppedPhysicalLaw.clauses input) (Nat.succ_le_of_lt j.isLt) hij + (FixedStoppedPhysicalLaw.designated parameters i) + (fun k _ => FixedParameters.branch_pos parameters k) + (FixedStoppedDecoderLaw.flag parameters i) + (FixedStoppedDecoderLaw.labeling parameters input strategy) sample := by + let F := FixedStoppedDecoderLaw.markFamily parameters i j hij input strategy + (sample.1.2, sample.2.2.1.1) + let S := StoppedProjectedExperiment.experiment + (FixedStoppedPhysicalLaw.clauses input) (FixedRows.rows parameters.plan) + (FixedRows.repeats parameters.plan) (Nat.succ_le_of_lt j.isLt) hij + (FixedStoppedPhysicalLaw.designated parameters i) + (fun k _ => FixedParameters.branch_pos parameters k) + (StoppedProjectedMeetingLaw.rows_positive parameters.plan) + (FixedStoppedDecoderLaw.flag parameters i) + (FixedStoppedDecoderLaw.labeling parameters input strategy) sample.1 + have hmark (background : HierarchicalMatrixTable.Background + (rows := FixedRows.rows parameters.plan) S.slots S.upper) : + HierarchicalProjectedMeeting.useful S.slots S.upper (i.val + 1) background + (F.original S.slots) (F.arrays S.slots) (F.lowerEvent S.slots) + (InitialParameters.useful δ) = + HierarchicalProjectedMeeting.useful S.slots S.upper (i.val + 1) background + S.original S.arrays (HierarchicalAdviceExperiment.lowerEvent S) + (InitialParameters.useful δ) := by + funext X + exact propext (SlotProjectedExperiment.mark_source + (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij sample.1.2 + (fun k _ => FixedParameters.branch_pos parameters k) + (StoppedProjectedMeetingLaw.rows_positive parameters.plan) + (FixedStoppedDecoderLaw.flag parameters i) + (FixedStoppedDecoderLaw.labeling parameters input strategy) + (FixedStoppedPhysicalLaw.clauses input) (FixedStoppedPhysicalLaw.designated parameters i) + sample.1.1 (InitialParameters.useful δ) background X) + have hthreshold : FixedStoppedDecoderLaw.threshold parameters j = + UpperParameterScalars.tau (InitialParameters.useful δ) parameters.plan.density + parameters.plan.order (FixedRows.rows parameters.plan (Nodes.height S.upper)) := by + simp only [FixedStoppedDecoderLaw.threshold, S, + HierarchicalProjectedExperiment.experiment, StoppedProjectedExperiment.upper_height] + exact familyMeetingProbability_eq_of_useful parameters.plan F + (FixedStoppedDecoderLaw.labeling parameters input strategy) S.slots + (StoppedProjectedExperiment.projectedSlots (FixedStoppedPhysicalLaw.clauses input) + (FixedRows.rows parameters.plan) (Nat.succ_le_of_lt j.isLt) hij + (FixedStoppedPhysicalLaw.designated parameters i) sample.1 sample.2.2.1) + (StoppedProjectedExperiment.projection (FixedStoppedPhysicalLaw.clauses input) + (FixedRows.rows parameters.plan) (Nat.succ_le_of_lt j.isLt) hij + (FixedStoppedPhysicalLaw.designated parameters i) sample.1 sample.2.2.1) + S.upper + (StoppedProjectedExperiment.lower (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij sample.1 sample.2.2.1) (i.val + 1) + S.original S.arrays (HierarchicalAdviceExperiment.lowerEvent S) sample.2.1 + (StoppedProjectedExperiment.direction (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij sample.1 sample.2.2.1) + (StoppedProjectedExperiment.cut (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij sample.1 sample.2.2.1) + (FixedStoppedDecoderLaw.threshold parameters j) sample.2.2.2.2 hmark hthreshold + +def nativeMeetingProbability + (sample : FixedStoppedNativeLaw.Sample parameters i j hij input) : ℝ := + (CleanDecoderPairLaw.pairKernel + (FixedStoppedDecoderLaw.setups parameters i j hij input sample.1) + (FixedStoppedDecoderLaw.labeling parameters input strategy) + (FixedStoppedDecoderLaw.useful parameters i j hij input strategy sample.1) + parameters.plan.order parameters.plan.density + (FixedStoppedDecoderContext.advice parameters i j hij input sample.1) + (LinearMap.ker (FixedStoppedDecoderContext.advice parameters i j hij input sample.1)) + (FixedStoppedDecoderContext.direction parameters i j hij input sample.1) + (FixedStoppedDecoderLaw.threshold parameters j) sample.2).probability + (DecoderRankSplit.meeting + (FixedStoppedDecoderLaw.setups parameters i j hij input sample.1) sample.2) + +def physicalMeetingProbability + (sample : FixedStoppedNativeLaw.Sample parameters i j hij input) : ℝ := + StoppedProjectedMeetingLaw.meetingProbability parameters.plan + (FixedStoppedPhysicalLaw.clauses input) (Nat.succ_le_of_lt j.isLt) hij + (FixedStoppedPhysicalLaw.designated parameters i) + (fun k _ => FixedParameters.branch_pos parameters k) + (FixedStoppedDecoderLaw.flag parameters i) + (FixedStoppedDecoderLaw.labeling parameters input strategy) + (FixedStoppedNativeLaw.read parameters i j hij input sample) + +def cleanMeetingProbability + (sample : FixedStoppedNativeLaw.Sample parameters i j hij input) : ℝ := + (CleanPhysicalProjectedMeeting.visiblePairKernel + (FixedStoppedNativeLaw.setup parameters i j hij input sample.1) + (FixedStoppedDecoderLaw.markFamily parameters i j hij input strategy sample.1.1) + (InitialParameters.useful δ) + (FixedStoppedDecoderLaw.labeling parameters input strategy) + parameters.plan.order parameters.plan.density + (FixedStoppedDecoderContext.advice parameters i j hij input sample.1) + (FixedStoppedDecoderContext.direction parameters i j hij input sample.1) + (FixedStoppedDecoderLaw.threshold parameters j) sample.2).probability + (fun answer => decide ((ProjectedNodeEmbedding.intoOriginal + (CleanPhysicalDecoderLaw.physicalProjection + (FixedStoppedNativeLaw.setup parameters i j hij input sample.1) sample.2) + (FixedStoppedDecoderContext.upperNode parameters i j hij input sample.1)).dualMap + answer.1 = answer.2)) + +private theorem direction_heq + (sample : FixedStoppedNativeLaw.Sample parameters i j hij input) : + HEq (FixedStoppedDecoderContext.direction parameters i j hij input sample.1) + (StoppedProjectedExperiment.direction (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij + (FixedStoppedNativeProjection.physicalSample parameters i j hij input sample).1 + (FixedStoppedNativeProjection.innerTag parameters i j hij input sample)) := by + let physical := FixedStoppedNativeProjection.physicalSample parameters i j hij input sample + let tag := FixedStoppedNativeProjection.innerTag parameters i j hij input sample + have hlower := (StoppedCleanCutEquality.stopped_lower_eq (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij physical.1 tag).symm + have hnodes : + (⟨CleanPhysicalDecoderLaw.lower + (FixedStoppedNativeLaw.setup parameters i j hij input sample.1), + CleanDecoderContext.lowerHeight + (FixedStoppedDecoderContext.upperNode parameters i j hij input sample.1) + (FixedStoppedDecoderContext.lowerIndex parameters i j hij input sample.1)⟩ : + PrefixTests.LevelNode (FixedParameters.branch parameters) i) = + ⟨StoppedProjectedExperiment.lower (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij physical.1 tag, + StoppedProjectedExperiment.lower_height (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij physical.1 tag⟩ := + Subtype.ext hlower + exact nodeDirection_val_heq (rows := FixedRows.rows parameters.plan) i _ _ hnodes + (sample.1.2.2.2.1 i) + +private theorem cleanMeetingProbability_eq_familyOnRaw + (sample : FixedStoppedNativeLaw.Sample parameters i j hij input) : + cleanMeetingProbability parameters i j hij input strategy sample = + familyMeetingOnRaw parameters i j hij input strategy + (StoppedProjectedPhysicalAdvice.read + (FixedStoppedPhysicalLaw.clauses input) (FixedRows.rows parameters.plan) + (FixedRows.repeats parameters.plan) (Nat.succ_le_of_lt j.isLt) hij + (FixedStoppedPhysicalLaw.designated parameters i) parameters.plan.order + (FixedStoppedNativeLaw.read parameters i j hij input sample)) := by + let S := FixedStoppedNativeLaw.setup parameters i j hij input sample.1 + let physical := FixedStoppedNativeProjection.physicalSample parameters i j hij input sample + let tag := FixedStoppedNativeProjection.innerTag parameters i j hij input sample + let record := StoppedProjectedPhysicalAdvice.read + (FixedStoppedPhysicalLaw.clauses input) (FixedRows.rows parameters.plan) + (FixedRows.repeats parameters.plan) (Nat.succ_le_of_lt j.isLt) hij + (FixedStoppedPhysicalLaw.designated parameters i) parameters.plan.order physical + exact ProjectedMeetingTransport.familyMeetingProbability_congr parameters.plan + (FixedStoppedDecoderLaw.markFamily parameters i j hij input strategy sample.1.1) + (FixedStoppedDecoderLaw.labeling parameters input strategy) + (CleanNativeReplay.leftSlots S sample.2) (CleanNativeReplay.rightSlots S sample.2) + (CleanPhysicalDecoderLaw.physicalProjection S sample.2) + (FixedStoppedDecoderContext.upperNode parameters i j hij input sample.1) + (CleanPhysicalDecoderLaw.lower S) (i.val + 1) + (FixedStoppedDecoderContext.advice parameters i j hij input sample.1) + (FixedStoppedDecoderContext.direction parameters i j hij input sample.1) S.cut + (FixedStoppedDecoderLaw.threshold parameters j) + (CleanPhysicalProjectedMeeting.visible S + (LinearMap.ker (FixedStoppedDecoderContext.advice parameters i j hij input sample.1)) sample.2) + (StoppedProjectedExperiment.nativeSlots (FixedStoppedPhysicalLaw.clauses input) physical.1) + (StoppedProjectedExperiment.projectedSlots (FixedStoppedPhysicalLaw.clauses input) + (FixedRows.rows parameters.plan) (Nat.succ_le_of_lt j.isLt) hij + (FixedStoppedPhysicalLaw.designated parameters i) physical.1 tag) + (StoppedProjectedExperiment.lower (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij physical.1 tag) + (StoppedProjectedExperiment.projection (FixedStoppedPhysicalLaw.clauses input) + (FixedRows.rows parameters.plan) (Nat.succ_le_of_lt j.isLt) hij + (FixedStoppedPhysicalLaw.designated parameters i) physical.1 tag) + (StoppedProjectedExperiment.direction (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij physical.1 tag) + (StoppedProjectedExperiment.cut (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij physical.1 tag) record.2.2.2.2 + (FixedStoppedNativeProjection.leftSlots_eq parameters i j hij input sample) + (FixedStoppedNativeProjection.rightSlots_eq parameters i j hij input sample) + (StoppedCleanCutEquality.stopped_lower_eq (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij physical.1 tag).symm + (FixedStoppedNativeProjection.projection_heq parameters i j hij input sample) + (direction_heq parameters i j hij input sample) + (StoppedCleanCutEquality.stopped_cut_heq (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij physical.1 tag).symm + (FixedStoppedNativeTape.visible_heq parameters i j hij input sample).symm + +private theorem cleanMeetingProbability_eq_physical + (sample : FixedStoppedNativeLaw.Sample parameters i j hij input) : + cleanMeetingProbability parameters i j hij input strategy sample = + physicalMeetingProbability parameters i j hij input strategy sample := + (cleanMeetingProbability_eq_familyOnRaw parameters i j hij input strategy sample).trans + (familyMeetingOnRaw_eq parameters i j hij input strategy _) + +theorem cleanMeetingProbability_eq_native + (context : FixedStoppedNativeLaw.Context parameters i j hij input) + (x : CleanDecoderRate.Sample (FixedStoppedNativeLaw.setup parameters i j hij input context)) + (hx : (CleanDecoderRate.rawLaw (FixedStoppedNativeLaw.setup parameters i j hij input context) + (parameters.cubeSize i.val) (FixedDecoderCleanRate.cubePositive parameters i.val)).weight x ≠ 0) : + cleanMeetingProbability parameters i j hij input strategy ⟨context, x⟩ = + nativeMeetingProbability parameters i j hij input strategy ⟨context, x⟩ := + CleanPhysicalProjectedMeeting.meeting_probability_eq + (FixedStoppedNativeLaw.setup parameters i j hij input context) + (FixedStoppedDecoderLaw.markFamily parameters i j hij input strategy context.1) + (InitialParameters.useful δ) + (FixedStoppedDecoderLaw.labeling parameters input strategy) + parameters.plan.order parameters.plan.density + (FixedStoppedDecoderContext.advice parameters i j hij input context) + (FixedStoppedDecoderContext.direction parameters i j hij input context) + (FixedStoppedDecoderLaw.threshold parameters j) + (parameters.cubeSize i.val) (FixedDecoderCleanRate.cubePositive parameters i.val) x hx + +abbrev expectedMeeting : ℝ := + StoppedProjectedMeetingLaw.expectedMeeting parameters.plan + (FixedStoppedPhysicalLaw.clauses input) (Nat.succ_le_of_lt j.isLt) hij + (FixedStoppedPhysicalLaw.designated parameters i) + (fun k _ => FixedParameters.branch_pos parameters k) + (FixedStoppedDecoderLaw.flag parameters i) + (FixedStoppedDecoderLaw.labeling parameters input strategy) + +theorem native_probability_eq_expectation : + (FixedStoppedDecoderLaw.law parameters i j hij input strategy).probability + (FixedStoppedDecoderLaw.meeting parameters i j hij input) = + (FixedStoppedNativeLaw.law parameters i j hij input).expectation + (nativeMeetingProbability parameters i j hij input strategy) := by + simp only [FixedStoppedDecoderLaw.law, DecoderFamilyLaw.law, + DecoderFamilyLaw.fiberLaw, CleanDecoderPairLaw.pairLaw, + CompletionSoundness.sigmaLaw_probability, FixedStoppedNativeLaw.law, + CandidateCoupling.expectation_sigmaLaw, nativeMeetingProbability, + FixedStoppedDecoderLaw.meeting, DecoderFamilyLaw.meeting] + rfl + +theorem native_expectation_eq_cleanMeeting : + (FixedStoppedNativeLaw.law parameters i j hij input).expectation + (nativeMeetingProbability parameters i j hij input strategy) = + (FixedStoppedNativeLaw.law parameters i j hij input).expectation + (cleanMeetingProbability parameters i j hij input strategy) := by + simp only [FixedStoppedNativeLaw.law, CandidateCoupling.expectation_sigmaLaw] + apply FiniteDistribution.expectation_congr + intro context + apply expectation_congr_on_support + intro x hx + exact (cleanMeetingProbability_eq_native parameters i j hij input strategy context x hx).symm + +theorem physical_expectation_eq_expectedMeeting : + (FixedStoppedNativeLaw.law parameters i j hij input).expectation + (physicalMeetingProbability parameters i j hij input strategy) = + expectedMeeting parameters i j hij input strategy := by + unfold physicalMeetingProbability + rw [FixedStoppedNativeLaw.expectation_read] + unfold expectedMeeting + rw [flag_eq parameters i] + exact StoppedProjectedMeetingLaw.expectation_meetingProbability parameters.plan + (FixedStoppedPhysicalLaw.clauses input) (Nat.succ_le_of_lt j.isLt) hij + (FixedStoppedPhysicalLaw.designated parameters i) + (fun k _ => FixedParameters.branch_pos parameters k) + (FixedStoppedPhysicalLaw.flag parameters i) + (FixedStoppedDecoderLaw.labeling parameters input strategy) + +theorem meeting_probability_eq_expectedMeeting : + (FixedStoppedDecoderLaw.law parameters i j hij input strategy).probability + (FixedStoppedDecoderLaw.meeting parameters i j hij input) = + expectedMeeting parameters i j hij input strategy := by + rw [native_probability_eq_expectation, native_expectation_eq_cleanMeeting] + calc + _ = (FixedStoppedNativeLaw.law parameters i j hij input).expectation + (physicalMeetingProbability parameters i j hij input strategy) := + FiniteDistribution.expectation_congr _ + (cleanMeetingProbability_eq_physical parameters i j hij input strategy) + _ = _ := physical_expectation_eq_expectedMeeting parameters i j hij input strategy + +end +end PerfectCompleteness.FixedStoppedMeetingEquality + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedStoppedPair.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedStoppedPair.lean new file mode 100644 index 0000000000000000000000000000000000000000..5ba67c967689e11d43b897245c9e7fe3b0a089f4 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedStoppedPair.lean @@ -0,0 +1,46 @@ +import OAI.Computability.PerfectCompleteness.Reduction.FixedStoppedError +import OAI.Computability.PerfectCompleteness.Reduction.PreliminaryOutputLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.FixedStoppedPair + +open FixedParameters FixedRows + +noncomputable section + +variable {δ : ℚ} {hδ : 0 < δ} (p : Parameters δ hδ) + +theorem exists_pair (input : List Bool) (strategy : FixedPreliminaryGame.Strategy p input) + (hsuccess : InitialParameters.epsilon δ ≤ + (FixedPreliminaryGame.game p input).success strategy) : + ∃ i j : Fin p.plan.depth, i < j ∧ + InitialParameters.simultaneous δ + 2 * p.accuracy ≤ + (StoppedSharedSampler.stoppedLaw + (PCPSource.clauseFamily (BinaryLanguage.totalRename input)) + (rows p.plan) (repeats p.plan) (cut := i.val) + (Nat.succ_le_of_lt i.isLt) (fun k _ => branch_pos p k) + (fun k => FixedPreliminaryGame.rows_pos p (k + 1))).probability + (StoppedSharedEvents.pair + (PCPSource.clauseFamily (BinaryLanguage.totalRename input)) strategy + (Nat.succ_le_of_lt i.isLt) (fun k _ => branch_pos p k) i j) := by + obtain ⟨i, j, hij, hmass⟩ := PreliminaryPairReserve.exists_pair p input strategy hsuccess + have hcut : i.val + 1 ≤ p.plan.depth := Nat.succ_le_of_lt i.isLt + have hi : i.val + 1 ≤ i.val + 1 := le_refl _ + have hj : i.val + 1 ≤ j.val + 1 := Nat.add_le_add_right (Nat.le_of_lt hij) 1 + have htransfer := StoppedSharedComparison.pair_probability_lower + (PCPSource.clauseFamily (BinaryLanguage.totalRename input)) strategy + hcut (fun k _ => branch_pos p k) + (fun k => FixedPreliminaryGame.rows_pos p (k + 1)) i j hi hj hmass + have herror := FixedStoppedError.stopped_error_lt p (le_refl p.plan.depth) hcut + refine ⟨i, j, hij, ?_⟩ + linarith + +end +end PerfectCompleteness.FixedStoppedPair + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedStoppedUsefulMass.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedStoppedUsefulMass.lean new file mode 100644 index 0000000000000000000000000000000000000000..0f9df606ccbc7cb5abd7393bd39df29c3c5adc55 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedStoppedUsefulMass.lean @@ -0,0 +1,484 @@ +import OAI.Computability.PerfectCompleteness.Algebra.PrefixMatrixAcceptance +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalAdviceExperimentLemmas +import OAI.Computability.PerfectCompleteness.Reduction.FixedPhysicalStoppedComparison +import OAI.Computability.PerfectCompleteness.Reduction.FixedStoppedPair +import OAI.Computability.PerfectCompleteness.Repetition.CutChildCleanLawLemmas +import OAI.Computability.PerfectCompleteness.Sampling.StoppedProjectedGlobalLawLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.FixedStoppedUsefulMass + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +private theorem probability_cast_array_law + {branch : Nat → Nat} {n h t : Nat} (rows repeats : Nat → Nat) + (p : Path branch n (h + 1)) + {slots slots' : Slots branch n → Fin t → MixedSupport.Slot} + (hs : slots = slots') (event : Arrays slots' rows → Bool) : + (WholeArraySampler.law rows repeats p slots).probability + (fun arrays => event (cast (congrArg (fun s => Arrays s rows) hs) arrays)) = + (WholeArraySampler.law rows repeats p slots').probability event := by + cases hs + rfl + +variable {δ : ℚ} {hδ : 0 < δ} (parameters : FixedParameters.Parameters δ hδ) + (i j : Fin parameters.plan.depth) (hij : i < j) (input : List Bool) + +abbrev clauses := PCPSource.clauseFamily (BinaryLanguage.totalRename input) + +abbrev Outer := StoppedProjectedExperiment.Outer + (branch := FixedParameters.branch parameters) (n := parameters.plan.depth) + (j := j.val) (t := FixedRows.sourceLength parameters.plan hδ) + (m := (PCPSource.normalizedFormula (BinaryLanguage.totalRename input)).clauses.length) + +abbrev Base := StoppedProjectedExperiment.PhysicalBase + (branch := FixedParameters.branch parameters) (n := parameters.plan.depth) + (i := i.val) (j := j.val) (t := FixedRows.sourceLength parameters.plan hδ) + (FixedRows.rows parameters.plan) + +def flags : Fin (FixedParameters.branch parameters i.val) → FiniteDistribution Bool := + fun _ => ProjectionPosterior.bernoulli (FixedParameters.projectionProbability parameters i.val : ℝ) + (FixedPhysicalStoppedComparison.beta_nonneg parameters) + (FixedPhysicalStoppedComparison.beta_le_one parameters) + +theorem flags_eq_projectionFlag (hcube : 0 < parameters.cubeSize i.val) : + flags parameters i = fun _ => + ProjectedCleanRate.projectionFlag (parameters.cubeSize i.val) hcube := by + have hprob : (FixedParameters.projectionProbability parameters i.val : ℝ) = + ProjectedCleanRate.projectionDensity (parameters.cubeSize i.val) := by + simp [FixedParameters.projectionProbability, ProjectedCleanRate.projectionDensity] + funext child + apply FiniteDistribution.eq_of_weight_eq + intro b + cases b <;> simp [flags, ProjectionPosterior.bernoulli, + ProjectedCleanRate.projectionFlag, RepetitionRate.bernoulli, hprob] + +def outerLaw : FiniteDistribution (Outer parameters j input) := + StoppedProjectedExperiment.outerLaw (Nat.succ_le_of_lt j.isLt) + (fun k _ => FixedParameters.branch_pos parameters k) + +def baseLaw : FiniteDistribution (Base parameters i j) := + StoppedProjectedExperiment.physicalBaseLaw (FixedRows.rows parameters.plan) hij + (fun k _ => FixedParameters.branch_pos parameters k) + (fun k => FixedPreliminaryGame.rows_pos parameters (k + 1)) + +def record (o : Outer parameters j input) + (pref : GeometricCutSplit.Prefix (FixedParameters.branch parameters) (j.val + 1) (i.val + 1)) + (directions : CanonicalDirections.Tuple (FixedRows.rows parameters.plan) parameters.plan.depth) + (arrays : Arrays (StoppedProjectedExperiment.nativeSlots (clauses input) o) + (FixedRows.rows parameters.plan)) : + StoppedSharedSampler.Record (clauses input) (FixedParameters.branch parameters) + parameters.plan.depth (FixedRows.sourceLength parameters.plan hδ) i.val + (FixedRows.rows parameters.plan) := + ⟨(o.1, (GeometricPrefixSplit.joinEquiv (Nat.succ_le_succ hij.le) + (Nat.succ_le_of_lt j.isLt) (o.2, pref), directions)), arrays⟩ + +variable (designated : Fin (FixedParameters.branch parameters i.val) → + Slots (FixedParameters.branch parameters) i.val) + +abbrev PhysicalSample := StoppedProjectedPhysicalLaw.Sample + (t := FixedRows.sourceLength parameters.plan hδ) + (clauses input) (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij designated + +abbrev OriginalSample := StoppedProjectedGlobalLaw.ExperimentSample + (t := FixedRows.sourceLength parameters.plan hδ) + (clauses input) (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij designated + +def physicalLaw : FiniteDistribution (PhysicalSample parameters i j hij input designated) := + StoppedProjectedPhysicalLaw.law + (clauses input) (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij designated + (fun k _ => FixedParameters.branch_pos parameters k) + (fun k => FixedPreliminaryGame.rows_pos parameters (k + 1)) (flags parameters i) + +def physicalRecord (sample : PhysicalSample parameters i j hij input designated) := + record parameters i j hij input sample.1 sample.2.1.1 sample.2.1.2.2 + (cast (congrArg (fun slots => Arrays slots (FixedRows.rows parameters.plan)) + (StoppedProjectedArrays.nativeSlots_eq (clauses input) (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij designated sample.1 sample.2.1)) + (StoppedProjectedArrays.physicalArrays (clauses input) (FixedRows.rows parameters.plan) + (FixedRows.repeats parameters.plan) (Nat.succ_le_of_lt j.isLt) hij designated + sample.1 sample.2)) + +def referenceMass (event : StoppedSharedSampler.Record (clauses input) + (FixedParameters.branch parameters) parameters.plan.depth + (FixedRows.sourceLength parameters.plan hδ) i.val (FixedRows.rows parameters.plan) → Bool) : ℝ := + (outerLaw parameters j input).expectation (fun o => + (baseLaw parameters i j hij).expectation (fun base => + (WholeArraySampler.law (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (StoppedProjectedExperiment.stoppedPath (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij o + (StoppedProjectedExperiment.baseTag (FixedRows.rows parameters.plan) base)) + (StoppedProjectedExperiment.nativeSlots (clauses input) o)).probability + (fun arrays => event (record parameters i j hij input o base.1 base.2.2 arrays)))) + +theorem physical_fiber_probability_lower + (o : Outer parameters j input) (base : Base parameters i j) + (event : StoppedSharedSampler.Record (clauses input) (FixedParameters.branch parameters) + parameters.plan.depth (FixedRows.sourceLength parameters.plan hδ) i.val + (FixedRows.rows parameters.plan) → Bool) : + (WholeArraySampler.law (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (StoppedProjectedExperiment.stoppedPath (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij o + (StoppedProjectedExperiment.baseTag (FixedRows.rows parameters.plan) base)) + (StoppedProjectedExperiment.nativeSlots (clauses input) o)).probability + (fun arrays => event (record parameters i j hij input o base.1 base.2.2 arrays)) - + parameters.accuracy ≤ + (StoppedProjectedExperiment.physicalFiberLaw (clauses input) (FixedRows.rows parameters.plan) + (FixedRows.repeats parameters.plan) (Nat.succ_le_of_lt j.isLt) hij designated + (flags parameters i) o base).probability + (fun raw => event (physicalRecord parameters i j hij input designated ⟨o, ⟨base, raw⟩⟩)) := by + let p := StoppedProjectedExperiment.stoppedPath (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij o + (StoppedProjectedExperiment.baseTag (FixedRows.rows parameters.plan) base) + let outside := StoppedProjectedExperiment.nativeSlots (clauses input) o + let placeholder := SourceProjectedTag.originalSlots (clauses input) + (StoppedProjectedExperiment.cutQuestions (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij o + (StoppedProjectedExperiment.baseTag (FixedRows.rows parameters.plan) base)) + let sources := StoppedProjectedExperiment.physicalSources (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij designated o base + have hslots : CutSlotAssembly.fill p outside + (SourceChildKernel.parentLeftSlots (clauses input) designated sources) = outside := by + simpa only [p, outside, sources, SourcePhysicalTapeLaw.nativeSlots] using + (StoppedProjectedArrays.nativeSlots_eq (clauses input) (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij designated o base) + let observed := fun arrays : SourcePhysicalStoppedComparison.NativeArrays + (FixedRows.rows parameters.plan) p outside (clauses input) designated sources => + event (record parameters i j hij input o base.1 base.2.2 + (cast (congrArg (fun slots => Arrays slots (FixedRows.rows parameters.plan)) hslots) arrays)) + have htv := SourcePhysicalStoppedComparison.conditional_variation + (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) p outside placeholder + (clauses input) designated (FixedParameters.branch_pos parameters i.val) sources + (FixedParameters.projectionProbability parameters i.val : ℝ) + (FixedPhysicalStoppedComparison.beta_nonneg parameters) + (FixedPhysicalStoppedComparison.beta_le_one parameters) + have herror : SourceChildProjectionComparison.error (FixedParameters.branch parameters) + i.val (FixedRows.sourceLength parameters.plan hδ) + (Fintype.card (WholeCutCalls.Index (FixedRows.rows parameters.plan) + (FixedRows.repeats parameters.plan) p)) (FixedRows.rows parameters.plan) + (FixedParameters.projectionProbability parameters i.val : ℝ) < parameters.accuracy := by + simpa only [SourceChildProjectionComparison.error] using + FixedProjectionError.sparse_error_lt parameters + (FixedPhysicalStoppedComparison.calls_le parameters p (le_refl _)) i.val + have hp := FiniteDistribution.probability_le_add_totalVariation + (SourcePhysicalStoppedComparison.stoppedLaw (FixedRows.rows parameters.plan) + (FixedRows.repeats parameters.plan) p outside (clauses input) designated sources) + (SourcePhysicalStoppedComparison.modifiedLaw (FixedRows.rows parameters.plan) + (FixedRows.repeats parameters.plan) p outside placeholder (clauses input) designated + (FixedParameters.projectionProbability parameters i.val : ℝ) + (FixedPhysicalStoppedComparison.beta_nonneg parameters) + (FixedPhysicalStoppedComparison.beta_le_one parameters) sources) observed + rw [FiniteDistribution.totalVariation_comm] at hp + have hreference : + (SourcePhysicalStoppedComparison.stoppedLaw (FixedRows.rows parameters.plan) + (FixedRows.repeats parameters.plan) p outside (clauses input) designated sources).probability + observed = + (WholeArraySampler.law (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + p outside).probability + (fun arrays => event (record parameters i j hij input o base.1 base.2.2 arrays)) := by + simpa only [SourcePhysicalStoppedComparison.stoppedLaw, observed] using + (probability_cast_array_law (FixedRows.rows parameters.plan) + (FixedRows.repeats parameters.plan) p + (slots := CutSlotAssembly.fill p outside + (SourceChildKernel.parentLeftSlots (clauses input) designated sources)) + (slots' := outside) hslots + (fun arrays => event (record parameters i j hij input o base.1 base.2.2 arrays))) + have hstrict := htv.trans_lt herror + have hbound : + (SourcePhysicalStoppedComparison.stoppedLaw (FixedRows.rows parameters.plan) + (FixedRows.repeats parameters.plan) p outside (clauses input) designated sources).probability + observed - parameters.accuracy ≤ + (SourcePhysicalStoppedComparison.modifiedLaw (FixedRows.rows parameters.plan) + (FixedRows.repeats parameters.plan) p outside placeholder (clauses input) designated + (FixedParameters.projectionProbability parameters i.val : ℝ) + (FixedPhysicalStoppedComparison.beta_nonneg parameters) + (FixedPhysicalStoppedComparison.beta_le_one parameters) sources).probability observed := + sub_le_iff_le_add.mpr (hp.trans (add_le_add (le_refl _) hstrict.le)) + rw [hreference, SourcePhysicalStoppedComparison.modifiedLaw, + FiniteDistribution.probability_pushforward] at hbound + change (WholeArraySampler.law (FixedRows.rows parameters.plan) + (FixedRows.repeats parameters.plan) p outside).probability + (fun arrays => event (record parameters i j hij input o base.1 base.2.2 arrays)) - + parameters.accuracy ≤ + (SourcePhysicalWholeLaw.rawLaw (FixedRows.rows parameters.plan) + (FixedRows.repeats parameters.plan) p outside placeholder (clauses input) designated + (fun _ => ProjectionPosterior.bernoulli + (FixedParameters.projectionProbability parameters i.val : ℝ) + (FixedPhysicalStoppedComparison.beta_nonneg parameters) + (FixedPhysicalStoppedComparison.beta_le_one parameters)) sources).probability + (fun raw => observed (SourcePhysicalWholeLaw.observeLeft (FixedRows.rows parameters.plan) + (FixedRows.repeats parameters.plan) p outside placeholder (clauses input) designated sources raw)) + exact hbound + +theorem physical_probability_lower + (event : StoppedSharedSampler.Record (clauses input) (FixedParameters.branch parameters) + parameters.plan.depth (FixedRows.sourceLength parameters.plan hδ) i.val + (FixedRows.rows parameters.plan) → Bool) : + referenceMass parameters i j hij input event - parameters.accuracy ≤ + (physicalLaw parameters i j hij input designated).probability + (fun sample => event (physicalRecord parameters i j hij input designated sample)) := by + have hmean := SmallBias.expectation_mono (outerLaw parameters j input) (fun o => + SmallBias.expectation_mono (baseLaw parameters i j hij) (fun base => + physical_fiber_probability_lower parameters i j hij input designated o base event)) + simp only [DensityVariation.expectation_sub, SmallBias.expectation_const] at hmean + simpa only [referenceMass, physicalLaw, StoppedProjectedPhysicalLaw.law, + StoppedProjectedExperiment.physicalLaw, CompletionSoundness.sigmaLaw_probability, + outerLaw, baseLaw] using hmean + +theorem referenceMass_eq_stopped + (event : StoppedSharedSampler.Record (clauses input) + (FixedParameters.branch parameters) parameters.plan.depth + (FixedRows.sourceLength parameters.plan hδ) i.val + (FixedRows.rows parameters.plan) → Bool) : + referenceMass parameters i j hij input event = + (StoppedSharedSampler.stoppedLaw (clauses input) + (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (Nat.succ_le_of_lt i.isLt) + (fun k _ => FixedParameters.branch_pos parameters k) + (fun k => FixedPreliminaryGame.rows_pos parameters (k + 1))).probability event := by + simp only [referenceMass, outerLaw, baseLaw, + StoppedProjectedExperiment.outerLaw, StoppedProjectedExperiment.physicalBaseLaw, + StoppedSharedSampler.stoppedLaw, CompletionSoundness.sigmaLaw_probability, + StoppedSharedSampler.contextLaw, FiniteDistribution.expectation_product] + apply FiniteDistribution.expectation_congr + intro questions + simp only [record, StoppedProjectedExperiment.stoppedPath, + StoppedProjectedExperiment.upperPath, StoppedProjectedExperiment.lowerPath, + StoppedProjectedExperiment.baseTag, StoppedProjectedExperiment.withFlags, + StoppedProjectedExperiment.nativeSlots, SmallBias.expectation_const] + let value := fun + (upper : GeometricCutSplit.Prefix (FixedParameters.branch parameters) + parameters.plan.depth (j.val + 1)) + (lower : GeometricCutSplit.Prefix (FixedParameters.branch parameters) + (j.val + 1) (i.val + 1)) => + (CanonicalDirections.law (FixedRows.rows parameters.plan) parameters.plan.depth + (fun k => FixedPreliminaryGame.rows_pos parameters (k + 1))).expectation + (fun directions => + (WholeArraySampler.law (FixedRows.rows parameters.plan) + (FixedRows.repeats parameters.plan) + ((GeometricCutSplit.prefixPath (Nat.succ_le_of_lt j.isLt) upper).append + (GeometricCutSplit.prefixPath (Nat.succ_le_succ hij.le) lower)) + (sourceSlots (clauses input) (PreliminarySampler.endpoints questions))).probability + (fun arrays => event + ⟨(questions, (GeometricPrefixSplit.joinEquiv (Nat.succ_le_succ hij.le) + (Nat.succ_le_of_lt j.isLt) (upper, lower), directions)), arrays⟩)) + calc + _ = (GeometricCutSplit.prefixLaw (Nat.succ_le_of_lt i.isLt) + (fun k _ => FixedParameters.branch_pos parameters k)).expectation + (fun pref => value + (GeometricPrefixSplit.splitEquiv (Nat.succ_le_succ hij.le) + (Nat.succ_le_of_lt j.isLt) pref).1 + (GeometricPrefixSplit.splitEquiv (Nat.succ_le_succ hij.le) + (Nat.succ_le_of_lt j.isLt) pref).2) := + (GeometricPrefixSplit.expectation_split (Nat.succ_le_succ hij.le) + (Nat.succ_le_of_lt j.isLt) + (fun k _ => FixedParameters.branch_pos parameters k) value).symm + _ = _ := by + apply FiniteDistribution.expectation_congr + intro pref + dsimp only [value] + rw [← GeometricPrefixSplit.prefixPath_split (Nat.succ_le_succ hij.le) + (Nat.succ_le_of_lt j.isLt) pref, GeometricPrefixSplit.join_split] + +theorem stopped_probability_lower + (event : StoppedSharedSampler.Record (clauses input) (FixedParameters.branch parameters) + parameters.plan.depth (FixedRows.sourceLength parameters.plan hδ) i.val + (FixedRows.rows parameters.plan) → Bool) : + (StoppedSharedSampler.stoppedLaw (clauses input) + (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (Nat.succ_le_of_lt i.isLt) (fun k _ => FixedParameters.branch_pos parameters k) + (fun k => FixedPreliminaryGame.rows_pos parameters (k + 1))).probability event - + parameters.accuracy ≤ + (physicalLaw parameters i j hij input designated).probability + (fun sample => event (physicalRecord parameters i j hij input designated sample)) := by + rw [← referenceMass_eq_stopped parameters i j hij input event] + exact physical_probability_lower parameters i j hij input designated event + +variable (strategy : FixedPreliminaryGame.Strategy parameters input) + +abbrev canonicalStrategy := PreliminaryStrategy.extend (clauses input) + (FixedParameters.branch parameters) parameters.plan.depth + (FixedRows.sourceLength parameters.plan hδ) (FixedRows.rows parameters.plan) + (FixedRows.repeats parameters.plan) strategy + +abbrev experiment (o : Outer parameters j input) := + StoppedProjectedGlobalLaw.experiment (clauses input) (FixedRows.rows parameters.plan) + (FixedRows.repeats parameters.plan) (Nat.succ_le_of_lt j.isLt) hij designated + (fun k _ => FixedParameters.branch_pos parameters k) + (fun k => FixedPreliminaryGame.rows_pos parameters (k + 1)) (flags parameters i) + (canonicalStrategy parameters input strategy) o + +abbrev OriginalFiber (o : Outer parameters j input) := + HierarchicalProjectedExperiment.Sample (rows := FixedRows.rows parameters.plan) + (repeats := FixedRows.repeats parameters.plan) + (StoppedProjectedExperiment.projectedSlots (clauses input) (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij designated o) + (StoppedProjectedExperiment.upper (Nat.succ_le_of_lt j.isLt) o) + (StoppedProjectedExperiment.lower (FixedRows.rows parameters.plan) (Nat.succ_le_of_lt j.isLt) hij o) + (StoppedProjectedExperiment.cut (FixedRows.rows parameters.plan) (Nat.succ_le_of_lt j.isLt) hij o) + +def originalLaw : FiniteDistribution (OriginalSample parameters i j hij input designated) := + StoppedProjectedGlobalLaw.experimentLaw (clauses input) (FixedRows.rows parameters.plan) + (FixedRows.repeats parameters.plan) (Nat.succ_le_of_lt j.isLt) hij designated + (fun k _ => FixedParameters.branch_pos parameters k) + (fun k => FixedPreliminaryGame.rows_pos parameters (k + 1)) (flags parameters i) + (canonicalStrategy parameters input strategy) + +def originalRecord (sample : OriginalSample parameters i j hij input designated) := + record parameters i j hij input sample.1 sample.2.1.1 sample.2.1.2.2 + ((experiment parameters i j hij input designated strategy sample.1).arrays sample.2) + +def upperEvent (o : Outer parameters j input) + (x : OriginalFiber parameters i j hij input designated o) : Bool := + PrefixTests.observeAtLevelNode (clauses input) (canonicalStrategy parameters input strategy) + o.1 ((experiment parameters i j hij input designated strategy o).arrays x) j + ⟨StoppedProjectedExperiment.upper (Nat.succ_le_of_lt j.isLt) o, + StoppedProjectedExperiment.upper_height (Nat.succ_le_of_lt j.isLt) o⟩ + (x.1.2.2 j) + +theorem lowerEvent_eq_win (o : Outer parameters j input) + (x : OriginalFiber parameters i j hij input designated o) : + HierarchicalAdviceExperiment.lowerEvent + (experiment parameters i j hij input designated strategy o) x = + StoppedSharedEvents.win (clauses input) strategy (Nat.succ_le_of_lt i.isLt) + (fun k _ => FixedParameters.branch_pos parameters k) i + (originalRecord parameters i j hij input designated strategy ⟨o, x⟩) := by + symm + unfold StoppedSharedEvents.win StoppedSharedEvents.representativeLeaf originalRecord record + dsimp only + rw [GeometricPrefixSplit.prefixPath_join] + exact (PrefixMatrixAcceptance.observe_endpoint (clauses input) + (canonicalStrategy parameters input strategy) o.1 + (StoppedProjectedExperiment.stoppedPath (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij o x.1) + (StoppedSharedEvents.referenceSuffix (Nat.succ_le_of_lt i.isLt) + (fun k _ => FixedParameters.branch_pos parameters k)) + ((experiment parameters i j hij input designated strategy o).arrays x) + (x.1.2.2 i)).trans + (PrefixMatrixAcceptance.observe_eq_lower (clauses input) + (canonicalStrategy parameters input strategy) o.1 + ((experiment parameters i j hij input designated strategy o).arrays x) i + ⟨StoppedProjectedExperiment.lower (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij o x.1, + StoppedProjectedExperiment.lower_height (FixedRows.rows parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij o x.1⟩ (x.1.2.2 i) + (StoppedProjectedExperiment.upper (Nat.succ_le_of_lt j.isLt) o)) + +theorem upperEvent_eq_win (o : Outer parameters j input) + (x : OriginalFiber parameters i j hij input designated o) : + upperEvent parameters i j hij input designated strategy o x = + StoppedSharedEvents.win (clauses input) strategy (Nat.succ_le_of_lt i.isLt) + (fun k _ => FixedParameters.branch_pos parameters k) j + (originalRecord parameters i j hij input designated strategy ⟨o, x⟩) := by + symm + unfold StoppedSharedEvents.win StoppedSharedEvents.representativeLeaf originalRecord record + dsimp only + rw [GeometricPrefixSplit.prefixPath_join, Path.slotEmbedding_append] + exact PrefixMatrixAcceptance.observe_endpoint (clauses input) + (canonicalStrategy parameters input strategy) o.1 + (StoppedProjectedExperiment.upperPath (Nat.succ_le_of_lt j.isLt) o) + ((StoppedProjectedExperiment.lowerPath (FixedRows.rows parameters.plan) hij x.1).slotEmbedding + (StoppedSharedEvents.referenceSuffix (Nat.succ_le_of_lt i.isLt) + (fun k _ => FixedParameters.branch_pos parameters k))) + ((experiment parameters i j hij input designated strategy o).arrays x) (x.1.2.2 j) + +theorem originalRecord_physicalRead + (sample : PhysicalSample parameters i j hij input designated) : + originalRecord parameters i j hij input designated strategy + (StoppedProjectedPhysicalLaw.read (clauses input) (FixedRows.rows parameters.plan) + (FixedRows.repeats parameters.plan) (Nat.succ_le_of_lt j.isLt) hij designated sample) = + physicalRecord parameters i j hij input designated sample := by + exact congrArg (record parameters i j hij input sample.1 sample.2.1.1 sample.2.1.2.2) + (StoppedProjectedArrays.arrays_physicalExperimentRead_eq (clauses input) + (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij designated + (fun k _ => FixedParameters.branch_pos parameters k) + (fun k => FixedPreliminaryGame.rows_pos parameters (k + 1)) (flags parameters i) + (canonicalStrategy parameters input strategy) sample.1 sample.2) + +theorem joint_probability_eq_physical : + (originalLaw parameters i j hij input designated strategy).probability + (HierarchicalUsefulFamily.jointEvent + (experiment parameters i j hij input designated strategy) + (upperEvent parameters i j hij input designated strategy)) = + (physicalLaw parameters i j hij input designated).probability (fun sample => + StoppedSharedEvents.pair (clauses input) strategy (Nat.succ_le_of_lt i.isLt) + (fun k _ => FixedParameters.branch_pos parameters k) i j + (physicalRecord parameters i j hij input designated sample)) := by + have hevent : HierarchicalUsefulFamily.jointEvent + (experiment parameters i j hij input designated strategy) + (upperEvent parameters i j hij input designated strategy) = + (fun sample => StoppedSharedEvents.pair (clauses input) strategy + (Nat.succ_le_of_lt i.isLt) (fun k _ => FixedParameters.branch_pos parameters k) i j + (originalRecord parameters i j hij input designated strategy sample)) := by + funext sample + exact congrArg₂ Bool.and + (lowerEvent_eq_win parameters i j hij input designated strategy sample.1 sample.2) + (upperEvent_eq_win parameters i j hij input designated strategy sample.1 sample.2) + rw [hevent] + have hread := StoppedProjectedPhysicalLaw.probability_read (clauses input) + (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij designated + (fun k _ => FixedParameters.branch_pos parameters k) + (fun k => FixedPreliminaryGame.rows_pos parameters (k + 1)) (flags parameters i) + (canonicalStrategy parameters input strategy) + (fun sample => StoppedSharedEvents.pair (clauses input) strategy + (Nat.succ_le_of_lt i.isLt) (fun k _ => FixedParameters.branch_pos parameters k) i j + (originalRecord parameters i j hij input designated strategy sample)) + simpa only [originalRecord_physicalRead, originalLaw, physicalLaw] using hread.symm + +theorem joint_probability_ge_of_reserve + (hreserve : InitialParameters.simultaneous δ + 2 * parameters.accuracy ≤ + (StoppedSharedSampler.stoppedLaw (clauses input) + (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (Nat.succ_le_of_lt i.isLt) (fun k _ => FixedParameters.branch_pos parameters k) + (fun k => FixedPreliminaryGame.rows_pos parameters (k + 1))).probability + (StoppedSharedEvents.pair (clauses input) strategy (Nat.succ_le_of_lt i.isLt) + (fun k _ => FixedParameters.branch_pos parameters k) i j)) : + InitialParameters.simultaneous δ ≤ + (originalLaw parameters i j hij input designated strategy).probability + (HierarchicalUsefulFamily.jointEvent + (experiment parameters i j hij input designated strategy) + (upperEvent parameters i j hij input designated strategy)) := by + rw [joint_probability_eq_physical] + have hcompare := stopped_probability_lower parameters i j hij input designated + (StoppedSharedEvents.pair (clauses input) strategy (Nat.succ_le_of_lt i.isLt) + (fun k _ => FixedParameters.branch_pos parameters k) i j) + have haccuracy := parameters.accuracy_pos + linarith + +theorem useful_probability_ge_of_reserve + (hreserve : InitialParameters.simultaneous δ + 2 * parameters.accuracy ≤ + (StoppedSharedSampler.stoppedLaw (clauses input) + (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (Nat.succ_le_of_lt i.isLt) (fun k _ => FixedParameters.branch_pos parameters k) + (fun k => FixedPreliminaryGame.rows_pos parameters (k + 1))).probability + (StoppedSharedEvents.pair (clauses input) strategy (Nat.succ_le_of_lt i.isLt) + (fun k _ => FixedParameters.branch_pos parameters k) i j)) : + InitialParameters.simultaneous δ / 2 ≤ + (originalLaw parameters i j hij input designated strategy).probability + (HierarchicalUsefulFamily.usefulEvent + (experiment parameters i j hij input designated strategy) (InitialParameters.useful δ) + (upperEvent parameters i j hij input designated strategy)) := by + exact HierarchicalUsefulFamily.useful_probability_ge_half + (experiment parameters i j hij input designated strategy) (outerLaw parameters j input) + (upperEvent parameters i j hij input designated strategy) (InitialParameters.simultaneous δ) + (InitialParameters.simultaneous_pos hδ).le + (joint_probability_ge_of_reserve parameters i j hij input designated strategy hreserve) + +end +end PerfectCompleteness.FixedStoppedUsefulMass + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedTarget.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedTarget.lean new file mode 100644 index 0000000000000000000000000000000000000000..d834657b483d1937a68d3220f3126a823ca7943d --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedTarget.lean @@ -0,0 +1,78 @@ +import OAI.Computability.PerfectCompleteness.Machines.NormalizedTargetMachine +import OAI.Computability.PerfectCompleteness.Reduction.PreliminaryOutputLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.FixedTarget + +open Turing UniqueGamesTheorem.Foundations.Complexity +open FixedParameters FixedRows FixedPreliminaryGame + +noncomputable section + +variable {δ : ℚ} {hδ : 0 < δ} (p : Parameters δ hδ) + +def alphabet : Nat := + FinitePreliminaryCompletion.alphabet (branch p) p.plan.depth + (sourceLength p.plan hδ) δ + +theorem alphabet_ge_two : 2 ≤ alphabet p := + CanonicalLocalCompletion.alphabet_ge_two + (TreeCanonical.locationCount (branch p) p.plan.depth (sourceLength p.plan hδ)) δ + +theorem alphabet_pos : 0 < alphabet p := + lt_of_lt_of_le (by decide : 0 < 2) (alphabet_ge_two p) + +def construct (input : List Bool) : Instance (alphabet p) := + NormalizedTarget.construct (branch := branch p) (n := p.plan.depth) + (t := sourceLength p.plan hδ) (rows p.plan) (repeats p.plan) + (depth_pos p) (fun k _ => branch_pos p k) (fun k => rows_pos p (k + 1)) δ + (NormalizedSourceInput.raw input) + +def computation : + TM2ComputableInPolyTime (id : List Bool → List Bool) Encoding.gameBits + (construct p) := by + change TM2ComputableInPolyTime (id : List Bool → List Bool) Encoding.gameBits + (fun input => NormalizedTarget.construct (branch := branch p) (n := p.plan.depth) + (t := sourceLength p.plan hδ) (rows p.plan) (repeats p.plan) + (depth_pos p) (fun k _ => branch_pos p k) (fun k => rows_pos p (k + 1)) δ + (NormalizedSourceInput.raw input)) + exact MachineSequential.composeBits + NormalizedSourceInput.rawComputation + (NormalizedTargetMachine.targetComputation (branch := branch p) (n := p.plan.depth) + (t := sourceLength p.plan hδ) (rows p.plan) (repeats p.plan) + (depth_pos p) (fun k _ => branch_pos p k) (fun k => rows_pos p (k + 1)) δ) + +theorem finiteAlphabet : + MachineFiniteAlphabet.FiniteAlphabet (computation p).tm := + MachineFiniteAlphabet.composeBits + NormalizedSourceInput.rawComputation + (NormalizedTargetMachine.targetComputation (branch := branch p) (n := p.plan.depth) + (t := sourceLength p.plan hδ) (rows p.plan) (repeats p.plan) + (depth_pos p) (fun k _ => branch_pos p k) (fun k => rows_pos p (k + 1)) δ) + NormalizedSourceInput.raw_finiteAlphabet + (NormalizedTargetMachine.finiteAlphabet (branch := branch p) (n := p.plan.depth) + (t := sourceLength p.plan hδ) (rows p.plan) (repeats p.plan) + (depth_pos p) (fun k _ => branch_pos p k) (fun k => rows_pos p (k + 1)) δ) + +theorem perfectlyComplete (input : List Bool) (accepted : BinaryLanguage.language input) : + PerfectlyComplete (construct p input) := + NormalizedTarget.perfectlyComplete (branch := branch p) (n := p.plan.depth) + (t := sourceLength p.plan hδ) (rows p.plan) (repeats p.plan) + (depth_pos p) (fun k _ => branch_pos p k) (fun k => rows_pos p (k + 1)) δ + (NormalizedSourceInput.raw input) + ((NormalizedSourceInput.raw_satisfiable_iff input).mpr accepted) + +theorem value_eq_one (input : List Bool) (accepted : BinaryLanguage.language input) : + (construct p input).value = 1 := + ((construct p input).perfectlyComplete_iff_value_eq_one (alphabet_pos p)).mp + (perfectlyComplete p input accepted) + +end +end PerfectCompleteness.FixedTarget + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedTargetValue.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedTargetValue.lean new file mode 100644 index 0000000000000000000000000000000000000000..2c98619627935e1e9ba6fdd5f9a95220fab80782 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/FixedTargetValue.lean @@ -0,0 +1,63 @@ +import OAI.Computability.PerfectCompleteness.Reduction.FixedTarget + +namespace OAI + + +namespace PerfectCompleteness.FixedTargetValue + + +open UniqueGamesTheorem.Foundations Target +open FixedParameters FixedRows FixedPreliminaryGame +open scoped Classical + +noncomputable section + +private theorem packed_value_le (formula : Formula) [NeZero formula.clauses.length] + (nonempty : formula.clauses ≠ []) + (distinct : ∀ clause ∈ formula.clauses, ∀ i j : Fin 3, + clause[i].variableIndex = clause[j].variableIndex → i = j) + (branch : Nat → Nat) (n t : Nat) (rows repeats : Nat → Nat) + (hn : 0 < n) (hbranch : ∀ k < n, 0 < branch k) + (hrows : ∀ k, 0 < rows (k + 1)) (δ : ℚ) (hδ : 0 < δ) : + (NormalizedTarget.construct (branch := branch) (n := n) (t := t) + rows repeats hn hbranch hrows δ ⟨formula, nonempty, distinct⟩).value ≤ + PreliminaryOutput.value + (fun index : Fin formula.clauses.length => + ({ clause := PCP.clauseAt formula index + distinct := fun i j same => distinct _ (List.getElem_mem index.isLt) i j same } : + SourceClause.NormalizedClause formula.variables)) + branch n t rows repeats hn hbranch hrows + (δ : ℝ) / 3 := by + have clauses_eq : + NormalizedSourceInput.clauses ⟨formula, nonempty, distinct⟩ = + (fun index : Fin formula.clauses.length => + ({ clause := PCP.clauseAt formula index + distinct := fun i j same => distinct _ (List.getElem_mem index.isLt) i j same } : + SourceClause.NormalizedClause formula.variables)) := by + funext index + rfl + have native : + (NormalizedTarget.construct (branch := branch) (n := n) (t := t) + rows repeats hn hbranch hrows δ ⟨formula, nonempty, distinct⟩).value ≤ + PreliminaryOutput.value (NormalizedSourceInput.clauses ⟨formula, nonempty, distinct⟩) + branch n t rows repeats hn hbranch hrows + (δ : ℝ) / 3 := by + simpa only [PreliminaryOutput.value] using + (NormalizedTarget.value_le (branch := branch) (n := n) (t := t) + rows repeats hn hbranch hrows δ ⟨formula, nonempty, distinct⟩ hδ) + rw [clauses_eq] at native + exact native + +variable {δ : ℚ} {hδ : 0 < δ} (p : Parameters δ hδ) + +theorem value_le (input : List Bool) : + (FixedTarget.construct p input).value ≤ + FixedPreliminaryGame.value p input + (δ : ℝ) / 3 := + packed_value_le (PCPSource.normalizedFormula (BinaryLanguage.totalRename input)) + (PCPSource.normalizedFormula_nonempty (BinaryLanguage.totalRename input)) + (PCPSource.normalizedFormula_distinct (BinaryLanguage.totalRename input)) + (branch p) p.plan.depth (sourceLength p.plan hδ) (rows p.plan) (repeats p.plan) + (depth_pos p) (fun k _ => branch_pos p k) (fun k => rows_pos p (k + 1)) δ hδ + +end +end PerfectCompleteness.FixedTargetValue + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/HierarchicalFixedAdviceFamilyLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/HierarchicalFixedAdviceFamilyLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..55f64e4d4b3b13f617653fffca80538c281ac9a0 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/HierarchicalFixedAdviceFamilyLemmas.lean @@ -0,0 +1,233 @@ +import OAI.Computability.PerfectCompleteness.Construction.HierarchicalBucketFamily +import OAI.Computability.PerfectCompleteness.Reduction.CanonicalGameLemmas +import OAI.Computability.PerfectCompleteness.Reduction.FixedComparisonErrorsLemmas +import OAI.Computability.PerfectCompleteness.Sampling.CandidateCoupling + +namespace OAI + + +namespace PerfectCompleteness.HierarchicalFixedAdviceFamily + +noncomputable section + +open scoped Classical +open TreeSourceSpaces HierarchicalArrays +open InitialParameters UpperParameterScalars +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype + +variable {δ : ℚ} {hδ : 0 < δ} (p : FixedParameters.Parameters δ hδ) + +theorem inverse_factor_eq_q (level : Nat) : + ((inverse δ) ^ 2 / 4) / + ((2 : ℝ) ^ (p.plan.order * FixedRows.rows p.plan level)) ^ 2 = + q (inverse δ) p.plan.order (FixedRows.rows p.plan level) := by + simp only [q, g, h, div_eq_mul_inv, pow_two] + ring + +theorem coarse_error_small (level : Nat) (hlevel : level ≤ p.plan.depth) : + 10 * p.accuracy ≤ p.plan.density * + (((inverse δ) ^ 2 / 4) / + ((2 : ℝ) ^ (p.plan.order * FixedRows.rows p.plan level)) ^ 2) / 16 := by + rw [inverse_factor_eq_q p level] + have hs := p.accuracy_small level hlevel + simp only [CommonAccuracy.tolerance, lt_min_iff] at hs + linarith [hs.2.2.1] + +variable {branch : Nat → Nat} {t : Nat} {O : Type*} [Fintype O] + {Ω : O → Type*} [∀ o, Fintype (Ω o)] + (S : (o : O) → HierarchicalAdviceExperiment.Experiment + branch (FixedRows.rows p.plan) p.plan.depth t (Ω o)) + +local instance backgroundFiberFintype (o : O) : + Fintype (HierarchicalAdviceExperiment.Background (S o)) := + HierarchicalAdviceExperiment.backgroundFintype (S o) + +local instance rowSpaceFintype (o : O) : + Fintype (NodeEmbedding.RowSpace (S o).slots (S o).upper) := Fintype.ofFinite _ + +local instance inputFintype (z : HierarchicalAdviceFamily.Background S) : + Fintype (HierarchicalAdviceFamily.Input S z) := + HierarchicalAdviceFamily.inputFintype S z + +local instance inputFiniteDimensional (z : HierarchicalAdviceFamily.Background S) : + FiniteDimensional F2 (HierarchicalAdviceFamily.Input S z) := + HierarchicalAdviceFamily.inputFiniteDimensional S z + +local instance valueFintype (z : HierarchicalAdviceFamily.Background S) : + Fintype (HierarchicalAdviceFamily.Value S z) := + HierarchicalAdviceFamily.valueFintype S z + +local instance coarseFintype (o : O) : + Fintype (HierarchicalAdviceExperiment.Coarse (S o)) := + HierarchicalAdviceFamily.coarseFintype S o + +omit [Fintype O] in +theorem rows_positive (o : O) : + 0 < FixedRows.rows p.plan (Nodes.height (S o).upper) := + HierarchicalFixedAdvice.rows_positive p (S o) + +def predictionDifference (outer : FiniteDistribution O) : ℝ := + (HierarchicalAdviceFamily.originalLaw S outer p.plan.order).probability + (HierarchicalAdviceFamily.prediction S (useful δ) p.plan.order p.plan.density) - + rhoPred (useful δ) p.plan.density * + (HierarchicalAdviceFamily.originalLaw S outer p.plan.order).probability + (fun x => HierarchicalAdviceFamily.J S (useful δ) p.plan.order p.plan.density + (HierarchicalAdviceFamily.observe S p.plan.order x)) + +variable {P : O → Type*} [∀ o, Fintype (P o)] + (outer : FiniteDistribution O) + (externalLaw : (o : O) → FiniteDistribution (P o)) + (background : (o : O) → P o → HierarchicalAdviceExperiment.Background (S o)) + (scalarLaw : (o : O) → P o → + FiniteDistribution (NodeEmbedding.RowSpace (S o).slots (S o).upper)) + (backgrounds : (o : O) → FiniteDistribution (HierarchicalAdviceExperiment.Background (S o))) + +theorem mean_agreement_ge + (hmass : simultaneous δ / 2 ≤ HierarchicalBucketFamily.usefulMass S (useful δ) + outer externalLaw background scalarLaw (rows_positive p S)) + (hpaired : (HierarchicalBucketFamily.actualPairLaw S outer externalLaw background + scalarLaw (rows_positive p S)).totalVariation + (HierarchicalBucketFamily.referencePairLaw S outer backgrounds (rows_positive p S)) ≤ + 10 * p.accuracy) : + 2 * inverse δ ≤ (HierarchicalAdviceFamily.backgroundLaw S outer backgrounds).expectation + (fun z => PartialTableInverse.nonzeroAgreement (HierarchicalAdviceFamily.table S (useful δ) z)) := by + calc + 2 * inverse δ = simultaneous δ ^ 2 / 16 := by unfold inverse; ring + _ ≤ _ := HierarchicalBucketFamily.mean_agreement_ge S (useful δ) outer externalLaw + background scalarLaw (rows_positive p S) backgrounds (simultaneous δ) + (simultaneous_pos hδ).le hmass (hpaired.trans (HierarchicalFixedAdvice.paired_error_small p)) + +theorem prediction_difference (level : Nat) (hlevel : level ≤ p.plan.depth) + (hheight : ∀ o, Nodes.height (S o).upper = level) + (hmass : simultaneous δ / 2 ≤ HierarchicalBucketFamily.usefulMass S (useful δ) + outer externalLaw background scalarLaw (rows_positive p S)) + (hpaired : (HierarchicalBucketFamily.actualPairLaw S outer externalLaw background + scalarLaw (rows_positive p S)).totalVariation + (HierarchicalBucketFamily.referencePairLaw S outer backgrounds (rows_positive p S)) ≤ + 10 * p.accuracy) + (hcoarse : ((HierarchicalAdviceFamily.originalLaw S outer p.plan.order).pushforward + (HierarchicalAdviceFamily.observe S p.plan.order)).totalVariation + ((HierarchicalAdviceFamily.referenceLaw S outer backgrounds p.plan.order).pushforward + (HierarchicalAdviceFamily.referenceObserve S p.plan.order)) ≤ 10 * p.accuracy) : + b (useful δ) p.plan.density (inverse δ) p.plan.order (FixedRows.rows p.plan level) ≤ + predictionDifference p S outer := by + have hdim (o : O) : + FixedRows.rows p.plan (Nodes.height (S o).upper) ≤ FixedRows.rows p.plan level := by + rw [hheight o] + have hbound := HierarchicalAdviceFamily.prediction_difference S (useful δ) + (useful_pos hδ).le outer backgrounds (rows_positive p S) + (FixedRows.rows p.plan level) hdim p.plan.order p.plan.density (inverse δ) + (10 * p.accuracy) (inverse_pos hδ) p.plan.density_pos p.plan.density_lt p.plan.spectral + (mean_agreement_ge p S outer externalLaw background scalarLaw backgrounds hmass hpaired) + (by have := p.accuracy_pos; positivity) (coarse_error_small p level hlevel) hcoarse + rw [inverse_factor_eq_q p level] at hbound + have hfactor : useful δ * p.plan.density * + q (inverse δ) p.plan.order (FixedRows.rows p.plan level) / 4 = + b (useful δ) p.plan.density (inverse δ) p.plan.order (FixedRows.rows p.plan level) := by + unfold b rhoPred + ring + rw [hfactor] at hbound + exact hbound + +end +end PerfectCompleteness.HierarchicalFixedAdviceFamily + + +namespace PerfectCompleteness.PreliminaryStrategy + +open PreliminarySampler TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open scoped Classical + +noncomputable section + +variable {v m n t : Nat} {branch rows repeats : Nat → Nat} + +def observe (clauses : Fin m → SourceClause.NormalizedClause v) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (b : Base branch n t m) + (arrays : Arrays (sourceSlots clauses (endpoints b.1)) rows) + (choice : Choice rows b.2) : Bool := + let P := HierarchicalArrays.presentation clauses (endpoints b.1) rows arrays + let slots := SourceKeys.slot clauses ∘ P.endpoints + let projection := BlockQuotient.projectBlock + (V := fun node : Nodes branch n => Block rows node) (B := PUnit.{1}) + (GeometricPath.nodeAtLevel b.2 choice.1) choice.2.val + decide (CanonicalEdges.coarsen slots P.joint projection + (KeyStrategy.label σ .left slots P.joint) = + KeyStrategy.label σ .right slots (projection ∘ P.joint)) + +abbrev Strategy (clauses : Fin m → SourceClause.NormalizedClause v) + (branch : Nat → Nat) (n t : Nat) (rows repeats : Nat → Nat) := + CompletionSoundness.LegalStrategy + (HierarchicalGame.LeftLabel (family clauses branch n t rows repeats)) + (HierarchicalGame.RightLabel (family clauses branch n t rows repeats)) + +def extend (clauses : Fin m → SourceClause.NormalizedClause v) + (branch : Nat → Nat) (n t : Nat) (rows repeats : Nat → Nat) + (strategy : Strategy clauses branch n t rows repeats) : + KeyStrategy.Strategy (TreeCanonical.locationCount branch n t) := + CanonicalGameStrategy.extend + (HierarchicalGame.toBlockFamily (family clauses branch n t rows repeats)) strategy + +theorem observe_extend_iff (clauses : Fin m → SourceClause.NormalizedClause v) + (branch : Nat → Nat) (n t : Nat) (rows repeats : Nat → Nat) + (strategy : Strategy clauses branch n t rows repeats) + (e : Raw clauses branch n t rows repeats) : + observe clauses (extend clauses branch n t rows repeats strategy) e.1 + (WholeArraySampler.evaluate rows repeats (GeometricPath.leafPath e.1.2) + (sourceSlots clauses (endpoints e.1.1)) e.2.1) e.2.2 = true ↔ + HierarchicalGame.edge (family clauses branch n t rows repeats) e + (strategy.1 (HierarchicalGame.leftAt (family clauses branch n t rows repeats) e)) = + strategy.2 (HierarchicalGame.rightAt (family clauses branch n t rows repeats) e) := by + simp only [observe, decide_eq_true_eq] + exact CanonicalGameStrategy.accepts_extend_iff + (HierarchicalGame.toBlockFamily (family clauses branch n t rows repeats)) strategy e + +theorem wins_eq_observe [NeZero m] + (clauses : Fin m → SourceClause.NormalizedClause v) + (branch : Nat → Nat) (n t : Nat) (rows repeats : Nat → Nat) (hn : 0 < n) + (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) + (strategy : Strategy clauses branch n t rows repeats) + (e : Raw clauses branch n t rows repeats) : + (game clauses branch n t rows repeats hn hbranch hrows).wins strategy e = + observe clauses (extend clauses branch n t rows repeats strategy) e.1 + (WholeArraySampler.evaluate rows repeats (GeometricPath.leafPath e.1.2) + (sourceSlots clauses (endpoints e.1.1)) e.2.1) e.2.2 := by + apply Bool.eq_iff_iff.mpr + change @decide + (HierarchicalGame.edge (family clauses branch n t rows repeats) e + (strategy.1 (HierarchicalGame.leftAt (family clauses branch n t rows repeats) e)) = + strategy.2 (HierarchicalGame.rightAt (family clauses branch n t rows repeats) e)) + (Classical.propDecidable _) = true ↔ _ + exact (@decide_eq_true_iff _ (Classical.propDecidable _)).trans + (observe_extend_iff clauses branch n t rows repeats strategy e).symm + +theorem success_eq_shared_candidate_mean [NeZero m] + (clauses : Fin m → SourceClause.NormalizedClause v) + (branch : Nat → Nat) (n t : Nat) (rows repeats : Nat → Nat) (hn : 0 < n) + (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) + (strategy : Strategy clauses branch n t rows repeats) : + (game clauses branch n t rows repeats hn hbranch hrows).success strategy = + (CandidateCoupling.sharedLaw clauses rows repeats hbranch hrows).expectation + (fun e => CandidateCoupling.candidateFraction e.1.2 + (observe clauses (extend clauses branch n t rows repeats strategy) e.1 e.2.1) e.2.2) := by + change (law clauses rows repeats hn hbranch hrows).probability + ((game clauses branch n t rows repeats hn hbranch hrows).wins strategy) = _ + have hw : (game clauses branch n t rows repeats hn hbranch hrows).wins strategy = + fun sample : Raw clauses branch n t rows repeats => + observe clauses (extend clauses branch n t rows repeats strategy) sample.1 + (WholeArraySampler.evaluate rows repeats (GeometricPath.leafPath sample.1.2) + (sourceSlots clauses (endpoints sample.1.1)) sample.2.1) sample.2.2 := + funext (wins_eq_observe clauses branch n t rows repeats hn hbranch hrows strategy) + rw [hw] + exact CandidateCoupling.candidate_average_shared clauses rows repeats hn hbranch hrows + (observe clauses (extend clauses branch n t rows repeats strategy)) + +end +end PerfectCompleteness.PreliminaryStrategy + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/NormalizedTarget.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/NormalizedTarget.lean new file mode 100644 index 0000000000000000000000000000000000000000..5d44a8333d3d6e1e4f1bed8e97f1bb27968d81f9 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/NormalizedTarget.lean @@ -0,0 +1,182 @@ +import OAI.Computability.PerfectCompleteness.Construction.SourceQuestionOrderLemmas +import OAI.Computability.PerfectCompleteness.Machines.KeyMetadataMachine +import OAI.Computability.PerfectCompleteness.Machines.SignedTupleCleanupMachineLemmas +import OAI.Computability.PerfectCompleteness.Machines.SourceOccurrenceProducerLemmas +import OAI.Computability.PerfectCompleteness.Reduction.ExactPreliminaryTarget + +namespace OAI + + +namespace PerfectCompleteness.NormalizedTarget + + +open UniqueGamesTheorem.Foundations.Complexity +open scoped Classical + +noncomputable section + +variable {branch : Nat → Nat} {n t : Nat} + +def inputBits (input : NormalizedSourceInput.Input) : List Bool := + NormalizedSourceInput.bits input + +@[simp] theorem inputBits_eq (input : NormalizedSourceInput.Input) : + inputBits input = SourceOccurrenceEncoding.bits input.formula := rfl + +theorem decode_inputBits (input : NormalizedSourceInput.Input) : + SourceOccurrenceEncoding.decode (inputBits input) = some input.formula := + NormalizedSourceInput.decode_bits input + +theorem inputBits_injective : Function.Injective inputBits := + NormalizedSourceInput.bits_injective + +abbrev SourceTuple (input : NormalizedSourceInput.Input) := + Fin (TreeCanonical.locationCount branch n t) → + Fin (NormalizedSourceInput.clauseCount input) + +def tupleQuestion (input : NormalizedSourceInput.Input) + (indices : SourceTuple (branch := branch) (n := n) (t := t) input) : + PreliminarySampler.Questions branch n t (NormalizedSourceInput.clauseCount input) := + SourceQuestionOrder.tupleToQuestion indices + +@[simp] theorem tupleQuestion_digits (input : NormalizedSourceInput.Input) + (indices : SourceTuple (branch := branch) (n := n) (t := t) input) : + SourceQuestionOrder.questionToTuple (tupleQuestion input indices) = indices := + SourceQuestionOrder.questionToTuple_tupleToQuestion indices + +def sourceShapes (input : NormalizedSourceInput.Input) + (indices : SourceTuple (branch := branch) (n := n) (t := t) input) : + Fin (TreeCanonical.locationCount branch n t) → CanonicalKeyShape.Shape := + fun position => SourceClauseReaderMachine.clauseShape + (SourceTupleData.selectedClause input.formula indices position) + +def parsedVariableIDs (input : NormalizedSourceInput.Input) + (indices : SourceTuple (branch := branch) (n := n) (t := t) input) + (position : Fin (TreeCanonical.locationCount branch n t)) (slot : Fin 3) : Nat := + (SourceTupleData.selectedClause input.formula indices position)[slot].variableIndex.val + +@[simp] theorem parsedVariableIDs_eq (input : NormalizedSourceInput.Input) + (indices : SourceTuple (branch := branch) (n := n) (t := t) input) + (position : Fin (TreeCanonical.locationCount branch n t)) (slot : Fin 3) : + parsedVariableIDs input indices position slot = + ((NormalizedSourceInput.clauses input (indices position)).variable slot).val := rfl + +theorem sourceSigns_eq (input : NormalizedSourceInput.Input) + (indices : SourceTuple (branch := branch) (n := n) (t := t) input) : + SourceTupleScheduleMachine.sourceSigns input.formula indices = + MetadataFreeSampler.sourceSigns (NormalizedSourceInput.clauses input) + (tupleQuestion input indices) := by + funext leaf coordinate + rfl + +theorem signTuple_eq (input : NormalizedSourceInput.Input) + (indices : SourceTuple (branch := branch) (n := n) (t := t) input) : + SourceTupleScheduleMachine.signTuple (sourceShapes input indices) = + MetadataFreeSampler.sourceSigns (NormalizedSourceInput.clauses input) + (tupleQuestion input indices) := + sourceSigns_eq input indices + +theorem numberedSlots_eq (input : NormalizedSourceInput.Input) + (indices : SourceTuple (branch := branch) (n := n) (t := t) input) + (position : Fin (TreeCanonical.locationCount branch n t)) : + TreeCanonical.numberedSlots + (MetadataFreeSampler.sourceSlots (NormalizedSourceInput.clauses input) + (tupleQuestion input indices)) position = + KeyMetadataMachine.actualSlot (sourceShapes input indices position) + (indices position).val (parsedVariableIDs input indices position) := by + change SourceKeys.slot (NormalizedSourceInput.clauses input) + (.clause (SourceQuestionOrder.questionToTuple + (SourceQuestionOrder.tupleToQuestion + (branch := branch) (n := n) (t := t) indices) position)) = _ + simp only [SourceQuestionOrder.questionToTuple_tupleToQuestion]; rfl + +theorem sourceTable_eq (input : NormalizedSourceInput.Input) + (indices : SourceTuple (branch := branch) (n := n) (t := t) input) + (prepared : Fin (TreeCanonical.locationCount branch n t) → Bool) : + SourceTupleData.stacks input.formula indices prepared .table = inputBits input := rfl + +theorem digit_counter (input : NormalizedSourceInput.Input) + (indices : SourceTuple (branch := branch) (n := n) (t := t) input) + (prepared : Fin (TreeCanonical.locationCount branch n t) → Bool) + (position : Fin (TreeCanonical.locationCount branch n t)) : + SourceTupleData.stacks input.formula indices prepared (.digit position) = + List.replicate (indices position).val true := rfl + +theorem variable_counter (input : NormalizedSourceInput.Input) + (indices : SourceTuple (branch := branch) (n := n) (t := t) input) + (position : Fin (TreeCanonical.locationCount branch n t)) (slot : Fin 3) : + SourceTupleData.stacks input.formula indices (fun _ => true) (.variableName position slot) = + List.replicate (parsedVariableIDs input indices position slot) true := rfl + +variable (rows repeats : Nat → Nat) + (hn : 0 < n) (hbranch : ∀ k < n, 0 < branch k) + (hrows : ∀ k, 0 < rows (k + 1)) (δ : ℚ) + +local notation "q" => FinitePreliminaryCompletion.alphabet branch n t δ + +def construct (input : NormalizedSourceInput.Input) : Instance q := + ExactPreliminaryTarget.construct (t := t) (NormalizedSourceInput.clauses input) + rows repeats hn hbranch hrows δ + +def outputBits (input : NormalizedSourceInput.Input) : List Bool := + Encoding.gameBits (construct (t := t) rows repeats hn hbranch hrows δ input) + +@[simp] theorem construct_eq (input : NormalizedSourceInput.Input) : + construct (t := t) rows repeats hn hbranch hrows δ input = + ExactPreliminaryTarget.construct (t := t) (NormalizedSourceInput.clauses input) + rows repeats hn hbranch hrows δ := rfl + +theorem edge_count (input : NormalizedSourceInput.Input) : + (construct (t := t) rows repeats hn hbranch hrows δ input).edges.length = + SignedMultiplicity.denominator branch n t rows repeats hn hbranch hrows q * + (NormalizedSourceInput.clauseCount input) ^ TreeCanonical.locationCount branch n t := + ExactPreliminaryTarget.edge_count (t := t) (NormalizedSourceInput.clauses input) + rows repeats hn hbranch hrows δ + +local instance leftVertex_fintype (input : NormalizedSourceInput.Input) : + Fintype (CanonicalGame.LeftVertex (FinitePreliminaryCompletion.blockFamily + (NormalizedSourceInput.clauses input) branch n t rows repeats)) := Fintype.ofFinite _ + +local instance rightVertex_fintype (input : NormalizedSourceInput.Input) : + Fintype (CanonicalGame.RightVertex (FinitePreliminaryCompletion.blockFamily + (NormalizedSourceInput.clauses input) branch n t rows repeats)) := Fintype.ofFinite _ + +local instance leftLabel_fintype (input : NormalizedSourceInput.Input) + (x : CanonicalGame.LeftVertex (FinitePreliminaryCompletion.blockFamily + (NormalizedSourceInput.clauses input) branch n t rows repeats)) : + Fintype (CanonicalGame.LeftLabel (FinitePreliminaryCompletion.blockFamily + (NormalizedSourceInput.clauses input) branch n t rows repeats) x) := Fintype.ofFinite _ + +local instance rightLabel_fintype (input : NormalizedSourceInput.Input) + (y : CanonicalGame.RightVertex (FinitePreliminaryCompletion.blockFamily + (NormalizedSourceInput.clauses input) branch n t rows repeats)) : + Fintype (CanonicalGame.RightLabel (FinitePreliminaryCompletion.blockFamily + (NormalizedSourceInput.clauses input) branch n t rows repeats) y) := Fintype.ofFinite _ + +theorem value_le (input : NormalizedSourceInput.Input) (hδ : 0 < δ) : + (construct (t := t) rows repeats hn hbranch hrows δ input).value ≤ + (PreliminarySampler.game (NormalizedSourceInput.clauses input) + branch n t rows repeats hn hbranch hrows).value + (δ : ℝ) / 3 := + ExactPreliminaryTarget.value_le (t := t) (NormalizedSourceInput.clauses input) + rows repeats hn hbranch hrows δ hδ + +theorem perfectlyComplete (input : NormalizedSourceInput.Input) + (satisfiable : input.formula.Satisfiable) : + PerfectlyComplete (construct (t := t) rows repeats hn hbranch hrows δ input) := by + obtain ⟨assignment, satisfies⟩ := satisfiable + apply ExactPreliminaryTarget.perfectlyComplete (t := t) + (NormalizedSourceInput.clauses input) rows repeats hn hbranch hrows δ assignment + intro occurrence + exact satisfies _ (List.getElem_mem occurrence.isLt) + +theorem outputBits_length_le (input : NormalizedSourceInput.Input) : + let N := (construct (t := t) rows repeats hn hbranch hrows δ input).edges.length + (outputBits (t := t) rows repeats hn hbranch hrows δ input).length ≤ + 2 * N + q + N + 4 + N * (2 * N + 2 * q * q + 2 * q + 2) := + ExactPreliminaryTarget.encoding_length_le (t := t) (NormalizedSourceInput.clauses input) + rows repeats hn hbranch hrows δ + +end +end PerfectCompleteness.NormalizedTarget + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/NormalizedTargetInitialization.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/NormalizedTargetInitialization.lean new file mode 100644 index 0000000000000000000000000000000000000000..c2958c7d20e0ad7b64ec6f0eea36dea55af61f10 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/NormalizedTargetInitialization.lean @@ -0,0 +1,299 @@ +import OAI.Computability.PerfectCompleteness.Machines.ExactTargetOdometer +import OAI.Computability.PerfectCompleteness.Machines.SourceClauseCountMachine +import OAI.Computability.PerfectCompleteness.Machines.TupleInitializationMachine + +namespace OAI + + +namespace PerfectCompleteness.NormalizedTargetInitialization + + +open Turing UniqueGamesTheorem.Foundations.Complexity +open MachineComposition +open scoped Classical + +noncomputable section + +abbrev Tape (width : Nat) := SignedTupleLayout.Tape width (Fin 4) +abbrev Alphabet {width : Nat} (_ : Tape width) := Bool +abbrev State (A : Type) := A × Option Bool + +def clean {A : Type} (ambient : A) : State A := (ambient, none) + +variable {width : Nat} + +def countTape : Fin 4 → Tape width + | 0 => .source .table + | 1 => .extra 1 + | 2 => .extra 2 + | 3 => .extra 0 + +theorem countTape_injective : Function.Injective (countTape (width := width)) := by + intro i j same + fin_cases i <;> fin_cases j <;> simp [countTape] at same ⊢ + +def currents (width : Nat) : List (Tape width) := List.ofFn SignedTupleLayout.Tape.current +def remaining (width : Nat) : List (Tape width) := List.ofFn SignedTupleLayout.Tape.remaining + +theorem destinations_nodup (width : Nat) : (currents width ++ remaining width).Nodup := by + unfold currents remaining + apply List.nodup_append.mpr + refine ⟨?_, ?_, ?_⟩ + · apply List.nodup_ofFn.mpr + intro i j same + simpa using same + · apply List.nodup_ofFn.mpr + intro i j same + simpa using same + · intro a ha b hb + obtain ⟨i, rfl⟩ := List.mem_ofFn.mp ha + obtain ⟨j, rfl⟩ := List.mem_ofFn.mp hb + intro same + cases same + +theorem count_not_destination : + (SignedTupleLayout.Tape.extra 0 : Tape width) ∉ currents width ++ remaining width := by + simp [currents, remaining, List.mem_ofFn] + +inductive Label + | seed + | count (label : SourceClauseCountMachine.Label) + | tuple (label : TupleInitializationMachine.Label) + deriving DecidableEq, Fintype + +variable {Λ A : Type} + +def instruction (labels : Label → Λ) (done rejected : Option Λ) : + Label → TM2.Stmt (Alphabet (width := width)) Λ (State A) + | .seed => .push (.extra 0) (fun _ => false) + (.push .edgeCount (fun _ => false) + (.load (fun state => clean state.1) + (.goto (fun _ => labels (.count SourceClauseCountMachine.main))))) + | .count label => SourceClauseCountMachine.instruction countTape + (fun l => labels (.count l)) (some (labels (.tuple .seed))) rejected label + | .tuple label => TupleInitializationMachine.instruction (.extra 0) + (currents width) (remaining width) (fun l => labels (.tuple l)) done label + +theorem instruction_pushBound (labels : Label → Λ) (done rejected : Option Λ) (label : Label) : + Runtime.statementPushBound (instruction (width := width) (A := A) labels done rejected label) ≤ + 2 * width + 2 := by + have exitBound (destination : Tape width) (exit : Option Λ) : + Runtime.statementPushBound + (UniqueGamesTheorem.Reduction.MachineTransfer.exitAt + (Γ := Alphabet (width := width)) (σ := A) destination exit) = 0 := by + cases exit <;> rfl + cases label with + | seed => simp [instruction, Runtime.statementPushBound] + | count label => + cases label <;> + simp [instruction, SourceClauseCountMachine.instruction, + UniqueGamesTheorem.Reduction.MachineTransfer.loopAt, MachineCopy.forkLoop, + UnaryBlockSkipMachine.instruction, UnaryBlockSkipMachine.finish, + UniqueGamesTheorem.Foundations.Hastad.SourceMachine.fieldLoop, + MachineDrain.drain, Runtime.statementPushBound, exitBound] + | tuple label => + have bound := TupleInitializationMachine.instruction_pushBound + (σ := A) (SignedTupleLayout.Tape.extra 0 : Tape width) + (currents width) (remaining width) (fun l => labels (.tuple l)) done label + change Runtime.statementPushBound + (TupleInitializationMachine.instruction (.extra 0) + (currents width) (remaining width) (fun l => labels (.tuple l)) done label) ≤ _ + refine bound.trans ?_ + simp only [currents, remaining, List.length_ofFn] + omega + +def inputTapes (input : NormalizedSourceInput.Input) : Tape width → List Bool + | .source .table => NormalizedSourceInput.bits input + | _ => [] + +def seededTapes (input : NormalizedSourceInput.Input) : Tape width → List Bool := + Function.update (Function.update (inputTapes input) (.extra 0) [false]) .edgeCount [false] + +def countedTapes (input : NormalizedSourceInput.Input) : Tape width → List Bool := + Function.update (seededTapes input) (.extra 0) + (encodeWord (NormalizedSourceInput.clauseCount input)) + +def zeroDigits (input : NormalizedSourceInput.Input) : + Fin width → Fin (NormalizedSourceInput.clauseCount input) := + fun _ => ⟨0, NormalizedSourceInput.clauseCount_positive input⟩ + +def readyTapes (input : NormalizedSourceInput.Input) : Tape width → List Bool := + Function.update (ExactTargetOdometer.baseTapes input (zeroDigits input) (fun _ => [])) + .edgeCount (encodeWord 0) + +@[simp] theorem seeded_count (input : NormalizedSourceInput.Input) : + seededTapes (width := width) input (.extra 0) = [false] := by + simp [seededTapes] + +@[simp] theorem counted_count (input : NormalizedSourceInput.Input) : + countedTapes (width := width) input (.extra 0) = + encodeWord (NormalizedSourceInput.clauseCount input) := by + simp [countedTapes] + +theorem initializedTapes_eq_ready (input : NormalizedSourceInput.Input) : + TupleInitializationMachine.initializedTapes (.extra 0) (currents width) (remaining width) + (countedTapes input) (NormalizedSourceInput.clauseCount input - 1) [] = + readyTapes input := by + funext key + cases key with + | source source => + cases source <;> + simp [TupleInitializationMachine.initializedTapes, TupleInitializationMachine.prefixOn, + currents, remaining, List.mem_ofFn, countedTapes, seededTapes, inputTapes, + readyTapes, ExactTargetOdometer.baseTapes] + | current position => + simp [TupleInitializationMachine.initializedTapes, TupleInitializationMachine.prefixOn, + currents, remaining, List.mem_ofFn, countedTapes, seededTapes, inputTapes, + readyTapes, ExactTargetOdometer.baseTapes, zeroDigits, encodeWord] + | remaining position => + simp [TupleInitializationMachine.initializedTapes, TupleInitializationMachine.prefixOn, + currents, remaining, List.mem_ofFn, countedTapes, seededTapes, inputTapes, + readyTapes, ExactTargetOdometer.baseTapes, zeroDigits, encodeWord] + | encodedVariable position slot => + simp [TupleInitializationMachine.initializedTapes, TupleInitializationMachine.prefixOn, + currents, remaining, List.mem_ofFn, countedTapes, seededTapes, inputTapes, + readyTapes, ExactTargetOdometer.baseTapes] + | adapterScratch => + simp [TupleInitializationMachine.initializedTapes, TupleInitializationMachine.prefixOn, + currents, remaining, List.mem_ofFn, countedTapes, seededTapes, inputTapes, + readyTapes, ExactTargetOdometer.baseTapes] + | edgeWork slot => + simp [TupleInitializationMachine.initializedTapes, TupleInitializationMachine.prefixOn, + currents, remaining, List.mem_ofFn, countedTapes, seededTapes, inputTapes, + readyTapes, ExactTargetOdometer.baseTapes] + | edgeCount => + simp [TupleInitializationMachine.initializedTapes, TupleInitializationMachine.prefixOn, + currents, remaining, List.mem_ofFn, countedTapes, seededTapes, + readyTapes, encodeWord] + | extra slot => + fin_cases slot <;> + simp [TupleInitializationMachine.initializedTapes, TupleInitializationMachine.prefixOn, + currents, remaining, List.mem_ofFn, countedTapes, seededTapes, inputTapes, + readyTapes, ExactTargetOdometer.baseTapes] + +@[simp] theorem ready_table (input : NormalizedSourceInput.Input) : + readyTapes (width := width) input (.source .table) = NormalizedSourceInput.bits input := by + simp [readyTapes, ExactTargetOdometer.baseTapes] + +@[simp] theorem ready_current (input : NormalizedSourceInput.Input) (position : Fin width) : + readyTapes input (.current position) = encodeWord 0 := by + simp [readyTapes, ExactTargetOdometer.baseTapes, zeroDigits] + +@[simp] theorem ready_remaining (input : NormalizedSourceInput.Input) (position : Fin width) : + readyTapes input (.remaining position) = + encodeWord (NormalizedSourceInput.clauseCount input - 1) := by + simp [readyTapes, ExactTargetOdometer.baseTapes, zeroDigits] + +@[simp] theorem ready_extra (input : NormalizedSourceInput.Input) (slot : Fin 4) : + readyTapes (width := width) input (.extra slot) = [] := by + simp [readyTapes, ExactTargetOdometer.baseTapes] + +theorem ready_eq_native {branch : Nat → Nat} {n t : Nat} + (input : NormalizedSourceInput.Input) : + readyTapes (width := TreeCanonical.locationCount branch n t) input = + ExactTargetOdometer.nativeTapes (branch := branch) (n := n) (t := t) + input (zeroDigits input) ⟨[], [], [], 0⟩ (fun _ : Fin 4 => []) := by + funext key + cases key with + | source source => + cases source <;> + simp [readyTapes, ExactTargetOdometer.nativeTapes, SignedTupleBodyMachine.tapes, + ExactTargetOdometer.baseTapes] + | current position => + simp [readyTapes, ExactTargetOdometer.nativeTapes, SignedTupleBodyMachine.tapes] + | remaining position => + simp [readyTapes, ExactTargetOdometer.nativeTapes, SignedTupleBodyMachine.tapes] + | encodedVariable position slot => + simp [readyTapes, ExactTargetOdometer.nativeTapes, SignedTupleBodyMachine.tapes] + | adapterScratch => + simp [readyTapes, ExactTargetOdometer.nativeTapes, SignedTupleBodyMachine.tapes] + | edgeWork slot => + fin_cases slot <;> + simp [readyTapes, ExactTargetOdometer.nativeTapes, SignedTupleBodyMachine.tapes, + ExactTargetOdometer.baseTapes, CanonicalVertexNames.tokens] + | edgeCount => + simp [readyTapes, ExactTargetOdometer.nativeTapes, SignedTupleBodyMachine.tapes] + | extra slot => + simp [readyTapes, ExactTargetOdometer.nativeTapes, SignedTupleBodyMachine.tapes] + +variable (labels : Label → Λ) (done rejected : Option Λ) + (program : Λ → TM2.Stmt (Alphabet (width := width)) Λ (State A)) + (atLabels : ∀ label, program (labels label) = instruction labels done rejected label) + +include atLabels in +theorem seedStep (input : NormalizedSourceInput.Input) (ambient : A) (register : Option Bool) : + TM2.step program ⟨some (labels .seed), (ambient, register), inputTapes input⟩ = + some ⟨some (labels (.count SourceClauseCountMachine.main)), clean ambient, seededTapes input⟩ := by + change some (TM2.stepAux (program (labels .seed)) _ _) = _ + rw [atLabels .seed] + simp [instruction, TM2.stepAux, seededTapes, inputTapes, clean] + +def initializeExactInTime (input : NormalizedSourceInput.Input) + (ambient : A) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .seed), (ambient, register), inputTapes input⟩ + (some ⟨done, clean ambient, readyTapes input⟩) + (1 + 3 * ((NormalizedSourceInput.bits input).length + 1) + + (NormalizedSourceInput.clauseCount input + 1)) := by + have seeded : StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .seed), (ambient, register), inputTapes input⟩ + (some ⟨some (labels (.count SourceClauseCountMachine.main)), + clean ambient, seededTapes input⟩) 1 := by + refine { steps := 1, evals_in_steps := ?_, steps_le_m := Nat.le_refl 1 } + exact seedStep labels done rejected program atLabels input ambient register + have counted : StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels (.count SourceClauseCountMachine.main)), clean ambient, seededTapes input⟩ + (some ⟨some (labels (.tuple .seed)), clean ambient, countedTapes input⟩) + (3 * ((NormalizedSourceInput.bits input).length + 1)) := by + have run := SourceClauseCountMachine.countInTime countTape countTape_injective + (fun label => labels (.count label)) (some (labels (.tuple .seed))) rejected + program (fun label => atLabels (.count label)) (seededTapes input) ambient input.formula + (by simp [countTape, seededTapes, inputTapes, NormalizedSourceInput.bits]) + (by simp [countTape, seededTapes, inputTapes]) + (by simp [countTape, seededTapes, inputTapes]) + simpa only [SourceClauseCountMachine.clean, clean, countTape, countedTapes, seeded_count, + NormalizedSourceInput.bits, NormalizedSourceInput.clauseCount, encodeWord] using run + have initialized : StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels (.tuple .seed)), clean ambient, countedTapes input⟩ + (some ⟨done, clean ambient, readyTapes input⟩) + (NormalizedSourceInput.clauseCount input + 1) := by + have run := TupleInitializationMachine.initializeInTime (σ := A) + (SignedTupleLayout.Tape.extra 0 : Tape width) + (currents width) (remaining width) (destinations_nodup width) count_not_destination + (fun label => labels (.tuple label)) done program + (fun label => by simpa only [instruction] using atLabels (.tuple label)) + (countedTapes input) ambient (NormalizedSourceInput.clauseCount input) + (NormalizedSourceInput.clauseCount_positive input) [] + (by simp only [counted_count, List.append_nil]) + simpa only [TupleInitializationMachine.clean, clean, initializedTapes_eq_ready] using run + have first := StateTransition.EvalsToInTime.trans (TM2.step program) _ _ _ _ _ seeded counted + have full := StateTransition.EvalsToInTime.trans (TM2.step program) _ _ _ _ _ first initialized + simpa only [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using full + +theorem count_length_le (input : NormalizedSourceInput.Input) : + NormalizedSourceInput.clauseCount input + 1 ≤ (NormalizedSourceInput.bits input).length := by + rw [NormalizedSourceInput.bits_eq] + simp only [List.length_append, encodeWord_length] + omega + +def initializeInTime (input : NormalizedSourceInput.Input) (ambient : A) (register : Option Bool) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .seed), (ambient, register), inputTapes input⟩ + (some ⟨done, clean ambient, readyTapes input⟩) + (4 * ((NormalizedSourceInput.bits input).length + 1)) := by + let run := initializeExactInTime labels done rejected program atLabels input ambient register + refine + { steps := run.steps + evals_in_steps := run.evals_in_steps + steps_le_m := run.steps_le_m.trans ?_ } + have bounded := count_length_le input + omega + +theorem finite_tapes : Finite (Tape width) := inferInstance +theorem finite_state [Finite A] : Finite (State A) := inferInstance +theorem finite_alphabet (key : Tape width) : Finite (Alphabet key) := inferInstance + +end +end PerfectCompleteness.NormalizedTargetInitialization + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/OccurrenceGame.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/OccurrenceGame.lean new file mode 100644 index 0000000000000000000000000000000000000000..8fcdc7e08bf59f9fa5616005536466bad9ad15a1 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/OccurrenceGame.lean @@ -0,0 +1,214 @@ +import OAI.Computability.UniqueGames.Foundations.SamplingLemmas +import OAI.Computability.UniqueGames.Foundations.ValueLemmas +import OAI.Computability.UniqueGames.Games.FinishBoundsLemmas + +namespace OAI + + +namespace PerfectCompleteness + +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators + +noncomputable section + +structure OccurrenceGame (E Q₁ Q₂ A₁ A₂ : Type*) + [Fintype E] [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂] where + occurrences : FiniteDistribution E + left : E → Q₁ + right : E → Q₂ + accepts : E → A₁ → A₂ → Bool + +namespace OccurrenceGame + +variable {E Q₁ Q₂ A₁ A₂ : Type*} + [Fintype E] [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂] + +def ofProjection (μ : FiniteDistribution E) (left : E → Q₁) (right : E → Q₂) + (projection : E → A₁ → A₂) : OccurrenceGame E Q₁ Q₂ A₁ A₂ := by + classical + exact + { occurrences := μ + left := left + right := right + accepts := fun e a b => decide (projection e a = b) } + +def endpoints (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) (e : E) : Q₁ × Q₂ := + (G.left e, G.right e) + +def wins (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) + (strategy : Strategy Q₁ Q₂ A₁ A₂) (e : E) : Bool := + G.accepts e (strategy.1 (G.left e)) (strategy.2 (G.right e)) + +def success (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) + (strategy : Strategy Q₁ Q₂ A₁ A₂) : ℝ := + G.occurrences.probability (G.wins strategy) + +theorem success_nonnegative (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) + (strategy : Strategy Q₁ Q₂ A₁ A₂) : 0 ≤ G.success strategy := + G.occurrences.probability_nonnegative _ + +theorem success_le_one (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) + (strategy : Strategy Q₁ Q₂ A₁ A₂) : G.success strategy ≤ 1 := + G.occurrences.probability_le_one _ + +structure EndpointPresentation (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) where + predicate : Q₁ → Q₂ → A₁ → A₂ → Bool + agrees : ∀ e a b, G.accepts e a b = predicate (G.left e) (G.right e) a b + +def EndpointDetermined (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) : Prop := + ∀ e e', G.left e = G.left e' → G.right e = G.right e' → + ∀ a b, G.accepts e a b = G.accepts e' a b + +private def chosenEndpointPredicate (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) + (x : Q₁) (y : Q₂) (a : A₁) (b : A₂) : Bool := by + classical + exact if h : ∃ e, G.left e = x ∧ G.right e = y then + G.accepts (Classical.choose h) a b + else false + +def presentationOfDetermined (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) + (h : G.EndpointDetermined) : G.EndpointPresentation where + predicate := chosenEndpointPredicate G + agrees e a b := by + have hex : ∃ e', G.left e' = G.left e ∧ G.right e' = G.right e := + ⟨e, rfl, rfl⟩ + simp only [chosenEndpointPredicate, dite_eq_left hex] + exact h e (Classical.choose hex) (Classical.choose_spec hex).1.symm + (Classical.choose_spec hex).2.symm a b + +theorem EndpointPresentation.determined (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) + (p : G.EndpointPresentation) : G.EndpointDetermined := by + intro e e' hl hr a b + rw [p.agrees, p.agrees, hl, hr] + +def toGame (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) + (p : G.EndpointPresentation) : Game Q₁ Q₂ A₁ A₂ where + questions := G.occurrences.pushforward G.endpoints + accepts := p.predicate + +@[simp] theorem toGame_success (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) + (p : G.EndpointPresentation) (strategy : Strategy Q₁ Q₂ A₁ A₂) : + (G.toGame p).success strategy = G.success strategy := by + unfold Game.success OccurrenceGame.success toGame + rw [FiniteDistribution.probability_pushforward] + congr 1 + funext e + exact (p.agrees e (strategy.1 (G.left e)) (strategy.2 (G.right e))).symm + +def repetition (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) (n : Nat) : + OccurrenceGame (Fin n → E) (Fin n → Q₁) (Fin n → Q₂) + (Fin n → A₁) (Fin n → A₂) := by + classical + exact + { occurrences := G.occurrences.iid n + left := fun e i => G.left (e i) + right := fun e i => G.right (e i) + accepts := fun e a b => decide (∀ i, G.accepts (e i) (a i) (b i) = true) } + +def EndpointPresentation.repetition (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) + (p : G.EndpointPresentation) (n : Nat) : (G.repetition n).EndpointPresentation := by + classical + exact + { predicate := fun x y a b => decide (∀ i, p.predicate (x i) (y i) (a i) (b i) = true) + agrees := by + intro e a b + simp only [OccurrenceGame.repetition, p.agrees] } + +theorem toGame_repetition_questions (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) + (p : G.EndpointPresentation) (n : Nat) : + ((G.toGame p).repetition n).questions = + (G.occurrences.iid n).pushforward (G.repetition n).endpoints := by + change ((G.occurrences.pushforward G.endpoints).iid n).transport + (Game.tupleQuestionEquiv n) = _ + rw [FiniteDistribution.iid_pushforward, FiniteDistribution.transport_eq_pushforward, + FiniteDistribution.pushforward_comp] + rfl + +theorem toGame_repetition_success (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) + (p : G.EndpointPresentation) (n : Nat) + (strategy : Strategy (Fin n → Q₁) (Fin n → Q₂) (Fin n → A₁) (Fin n → A₂)) : + ((G.toGame p).repetition n).success strategy = (G.repetition n).success strategy := by + classical + unfold Game.success OccurrenceGame.success + rw [G.toGame_repetition_questions p n, FiniteDistribution.probability_pushforward] + congr 1 + funext e + simp only [Game.wins, Game.repetition, toGame, OccurrenceGame.repetition, + endpoints, wins, p.agrees] + rfl + + +variable [Nonempty A₁] [Nonempty A₂] + +def value (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) : ℝ := by + classical + exact Finset.univ.sup' Finset.univ_nonempty G.success + +theorem success_le_value (G : OccurrenceGame E 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 : OccurrenceGame E 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 : OccurrenceGame E 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 : OccurrenceGame E 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 : OccurrenceGame E Q₁ Q₂ A₁ A₂) : G.value ≤ 1 := + (G.value_le_iff 1).2 G.success_le_one + +theorem randomized_success_le_value (G : OccurrenceGame E 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] + +@[simp] theorem toGame_value (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) + (p : G.EndpointPresentation) : (G.toGame p).value = G.value := by + apply le_antisymm + · apply ((G.toGame p).value_le_iff _).2 + intro strategy + rw [G.toGame_success p strategy] + exact G.success_le_value strategy + · apply (G.value_le_iff _).2 + intro strategy + rw [← G.toGame_success p strategy] + exact (G.toGame p).success_le_value strategy + +theorem toGame_repetition_value (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) + (p : G.EndpointPresentation) (n : Nat) : + ((G.toGame p).repetition n).value = (G.repetition n).value := by + apply le_antisymm + · apply (((G.toGame p).repetition n).value_le_iff _).2 + intro strategy + rw [G.toGame_repetition_success p n strategy] + exact (G.repetition n).success_le_value strategy + · apply ((G.repetition n).value_le_iff _).2 + intro strategy + rw [← G.toGame_repetition_success p n strategy] + exact ((G.toGame p).repetition n).success_le_value strategy + +end OccurrenceGame +end +end PerfectCompleteness + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/OddListGame.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/OddListGame.lean new file mode 100644 index 0000000000000000000000000000000000000000..913015406a86091dd8057d0ebf6dd4564f39cd9a --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/OddListGame.lean @@ -0,0 +1,147 @@ +import OAI.Computability.PerfectCompleteness.Foundations.OddLists +import OAI.Computability.PerfectCompleteness.Foundations.RecursiveSpaceEquivLemmas +import OAI.Computability.PerfectCompleteness.Repetition.RepetitionRateLemmas +import OAI.Computability.PerfectCompleteness.Sampling.FiniteListSampling + +namespace OAI + +section + +namespace PerfectCompleteness.OddListGame + +open scoped BigOperators +open UniqueGamesTheorem.Foundations.Games +open OddLists FiniteListSampling + +noncomputable section + +variable {E Q₁ Q₂ A₁ A₂ : Type*} + [Fintype E] [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂] + [DecidableEq Q₁] [DecidableEq Q₂] [DecidableEq A₁] [DecidableEq A₂] + +def base (μ : FiniteDistribution E) (left : E → Q₁) (right : E → Q₂) + (projection : E → A₁ → A₂) : OccurrenceGame E Q₁ Q₂ A₁ A₂ := + OccurrenceGame.ofProjection μ left right projection + +def game (s : Nat) (μ : FiniteDistribution E) (left : E → Q₁) (right : E → Q₂) + (projection : E → A₁ → A₂) : + OccurrenceGame E Q₁ Q₂ (OddList s A₁) (OddList s A₂) := + OccurrenceGame.ofProjection μ left right (fun e => OddList.map (projection e)) + +def responses {Q A : Type*} [Fintype A] [DecidableEq A] {s : Nat} + (lists : Q → OddList s A) (q : Q) : FiniteDistribution A := + uniformList (lists q).val (lists q).nonempty + +omit [DecidableEq Q₁] [DecidableEq Q₂] [DecidableEq A₁] in +theorem accepted_pair {s : Nat} (μ : FiniteDistribution E) + (left : E → Q₁) (right : E → Q₂) (projection : E → A₁ → A₂) + (strategy : Strategy Q₁ Q₂ (OddList s A₁) (OddList s A₂)) (e : E) + (accepted : (game s μ left right projection).wins strategy e = true) : + ∃ a ∈ (strategy.1 (left e)).val, ∃ b ∈ (strategy.2 (right e)).val, + (base μ left right projection).accepts e a b = true := by + have hmap : OddList.map (projection e) (strategy.1 (left e)) = strategy.2 (right e) := by + simpa only [game, OccurrenceGame.wins, OccurrenceGame.ofProjection, decide_eq_true_eq] + using accepted + obtain ⟨a, ha, b, hb, hab⟩ := OddList.exists_accepting_pair_of_eq + (projection e) (strategy.1 (left e)) (strategy.2 (right e)) hmap + exact ⟨a, ha, b, hb, by simpa [base, OccurrenceGame.ofProjection] using hab⟩ + +omit [DecidableEq Q₁] [DecidableEq Q₂] in +theorem success_le_randomized {s : Nat} [NeZero s] (μ : FiniteDistribution E) + (left : E → Q₁) (right : E → Q₂) (projection : E → A₁ → A₂) + (strategy : Strategy Q₁ Q₂ (OddList s A₁) (OddList s A₂)) : + (game s μ left right projection).success strategy ≤ + (s : ℝ) ^ 2 * (base μ left right projection).stochasticSuccess + (responses strategy.1) (responses strategy.2) := by + let G := base μ left right projection + let pair := fun e => pairAcceptance (responses strategy.1 (left e)) + (responses strategy.2 (right e)) (G.accepts e) + have hs : 0 < (s : ℝ) ^ 2 := pow_pos (Nat.cast_pos.mpr (Nat.pos_of_neZero s)) 2 + have hpoint (e : E) : + (if (game s μ left right projection).wins strategy e then (1 : ℝ) else 0) ≤ + (s : ℝ) ^ 2 * pair e := by + by_cases hwin : (game s μ left right projection).wins strategy e = true + · simp only [hwin, ite_true] + have h := bounded_uniform_pair_lower + (strategy.1 (left e)).val (strategy.2 (right e)).val + (strategy.1 (left e)).nonempty (strategy.2 (right e)).nonempty s + (strategy.1 (left e)).card_le (strategy.2 (right e)).card_le (G.accepts e) + (accepted_pair μ left right projection strategy e hwin) + have hscaled := (div_le_iff₀ hs).mp h + change 1 ≤ (s : ℝ) ^ 2 * + pairAcceptance (uniformList (strategy.1 (left e)).val (strategy.1 (left e)).nonempty) + (uniformList (strategy.2 (right e)).val (strategy.2 (right e)).nonempty) (G.accepts e) + exact hscaled.trans_eq (mul_comm _ _) + · simp only [hwin] + exact mul_nonneg (sq_nonneg _) (pairAcceptance_nonnegative _ _ _) + have hpair : μ.expectation pair = G.stochasticSuccess + (responses strategy.1) (responses strategy.2) := by + unfold OccurrenceGame.stochasticSuccess + apply FiniteDistribution.expectation_congr + intro e + exact pairAcceptance_eq_expectation _ _ _ + calc + _ = μ.expectation + (fun e => if (game s μ left right projection).wins strategy e then 1 else 0) := + (game s μ left right projection).success_eq_occurrence_expectation strategy + _ ≤ μ.expectation (fun e => (s : ℝ) ^ 2 * pair e) := + SmallBias.expectation_mono μ hpoint + _ = (s : ℝ) ^ 2 * μ.expectation pair := by + simp only [FiniteDistribution.expectation, Finset.mul_sum] + apply Finset.sum_congr rfl + intro e _ + ring + _ = _ := by rw [hpair] + +theorem value_le {s : Nat} [NeZero s] [Nonempty A₁] [Nonempty A₂] + (μ : FiniteDistribution E) (left : E → Q₁) (right : E → Q₂) + (projection : E → A₁ → A₂) : + (game s μ left right projection).value ≤ + (s : ℝ) ^ 2 * (base μ left right projection).value := by + apply ((game s μ left right projection).value_le_iff _).mpr + intro strategy + exact (success_le_randomized μ left right projection strategy).trans + (mul_le_mul_of_nonneg_left + ((base μ left right projection).stochasticSuccess_le_value + (responses strategy.1) (responses strategy.2)) (sq_nonneg _)) + +omit [DecidableEq Q₁] [DecidableEq Q₂] [DecidableEq A₁] in +theorem endpointDetermined {s : Nat} (μ : FiniteDistribution E) + (left : E → Q₁) (right : E → Q₂) (projection : E → A₁ → A₂) + (determined : (base μ left right projection).EndpointDetermined) : + (game s μ left right projection).EndpointDetermined := by + intro e e' hl hr L R + have hprojection : projection e = projection e' := by + funext a + have h := determined e e' hl hr a (projection e a) + have htrue : (base μ left right projection).accepts e' a (projection e a) = true := by + rw [← h] + simp [base, OccurrenceGame.ofProjection] + have heq : projection e' a = projection e a := by + simpa only [base, OccurrenceGame.ofProjection, decide_eq_true_eq] using htrue + exact heq.symm + simp only [game, OccurrenceGame.ofProjection, hprojection] + by_cases h : OddList.map (projection e') L = R <;> simp only [h, decide_true, decide_false] + +theorem repetition_halfRate {s L : Nat} [NeZero s] [Nonempty A₁] [Nonempty A₂] + (μ : FiniteDistribution E) (left : E → Q₁) (right : E → Q₂) + (projection : E → A₁ → A₂) + (determined : (base μ left right projection).EndpointDetermined) + (gap : (s : ℝ) ^ 2 * (base μ left right projection).value ≤ 1 / 2) + (hL : 0 < L) + (alphabet : UniqueGamesTheorem.Foundations.Repetition.logTwo + ((Fintype.card (OddList s A₁) : ℝ) * (Fintype.card (OddList s A₂) : ℝ)) ≤ L) + (n : Nat) : + ((game s μ left right projection).repetition n).value ≤ + (RepetitionRate.halfRate L : ℝ) ^ n := by + exact RepetitionRate.occurrence_repetition_halfRate (game s μ left right projection) + ((game s μ left right projection).presentationOfDetermined + (endpointDetermined μ left right projection determined)) hL alphabet + ((value_le μ left right projection).trans gap) n + +end +end PerfectCompleteness.OddListGame + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/PreliminaryAveraging.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/PreliminaryAveraging.lean new file mode 100644 index 0000000000000000000000000000000000000000..8e90a2a48ade5d4e474fe694465dbd9253306964 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/PreliminaryAveraging.lean @@ -0,0 +1,91 @@ +import OAI.Computability.PerfectCompleteness.Sampling.PreliminarySampler + +namespace OAI + +section + +namespace PerfectCompleteness.PreliminaryAveraging + +open PreliminarySampler TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +noncomputable section + +theorem probability_product {X Y : Type*} [Fintype X] [Fintype Y] + (μ : FiniteDistribution X) (ν : FiniteDistribution Y) (event : X × Y → Bool) : + (μ.product ν).probability event = + μ.expectation (fun x => ν.probability (fun y => event (x, y))) := by + simp only [FiniteDistribution.probability, FiniteDistribution.expectation, + FiniteDistribution.product, Fintype.sum_prod_type, Finset.mul_sum, mul_ite, mul_zero] + +variable {v m n t : Nat} {branch rows repeats : Nat → Nat} + +def directionLaw (leaf : RecursiveSpaces.Slots branch n) (level : Fin n) + (hrows : ∀ k, 0 < rows (k + 1)) : + FiniteDistribution (BucketSampler.Direction + (rows (Nodes.height (GeometricPath.nodeAtLevel leaf level)))) := by + letI : Nonempty (BucketSampler.Direction + (rows (Nodes.height (GeometricPath.nodeAtLevel leaf level)))) := + directionNonempty _ (by rw [GeometricPath.nodeAtLevel_height]; exact hrows level.val) + exact FiniteDistribution.uniform _ + +theorem choice_probability (leaf : RecursiveSpaces.Slots branch n) (hn : 0 < n) + (hrows : ∀ k, 0 < rows (k + 1)) (event : Choice rows leaf → Bool) : + (choiceLaw leaf hn hrows).probability event = + (∑ level : Fin n, (directionLaw leaf level hrows).probability + (fun direction => event ⟨level, direction⟩)) / (n : ℝ) := by + let : Nonempty (Fin n) := ⟨⟨0, hn⟩⟩ + change (CompletionSoundness.sigmaLaw (FiniteDistribution.uniform (Fin n)) + (fun level => directionLaw leaf level hrows)).probability event = _ + rw [CompletionSoundness.sigmaLaw_probability, FiniteDistribution.expectation_uniform] + simp only [Fintype.card_fin] + +theorem array_observation_probability [NeZero m] + (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hn : 0 < n) + (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) + (observe : ∀ b : Base branch n t m, + Arrays (sourceSlots clauses (endpoints b.1)) rows → Choice rows b.2 → Bool) : + (law clauses rows repeats hn hbranch hrows).probability + (fun e => observe e.1 + (WholeArraySampler.evaluate rows repeats (GeometricPath.leafPath e.1.2) + (sourceSlots clauses (endpoints e.1.1)) e.2.1) e.2.2) = + (baseLaw hbranch).expectation (fun b => + (WholeArraySampler.law rows repeats (GeometricPath.leafPath b.2) + (sourceSlots clauses (endpoints b.1))).expectation + (fun arrays => (choiceLaw b.2 hn hrows).probability (observe b arrays))) := by + rw [law_probability] + apply FiniteDistribution.expectation_congr + intro b + rw [conditionalLaw, probability_product] + rw [WholeArraySampler.law, FiniteDistribution.expectation_pushforward] + +theorem candidate_average [NeZero m] + (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hn : 0 < n) + (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) + (observe : ∀ b : Base branch n t m, + Arrays (sourceSlots clauses (endpoints b.1)) rows → Choice rows b.2 → Bool) : + (law clauses rows repeats hn hbranch hrows).probability + (fun e => observe e.1 + (WholeArraySampler.evaluate rows repeats (GeometricPath.leafPath e.1.2) + (sourceSlots clauses (endpoints e.1.1)) e.2.1) e.2.2) = + (baseLaw hbranch).expectation (fun b => + (WholeArraySampler.law rows repeats (GeometricPath.leafPath b.2) + (sourceSlots clauses (endpoints b.1))).expectation (fun arrays => + (∑ level : Fin n, (directionLaw b.2 level hrows).probability + (fun direction => observe b arrays ⟨level, direction⟩)) / (n : ℝ))) := by + rw [array_observation_probability clauses rows repeats hn hbranch hrows observe] + apply FiniteDistribution.expectation_congr + intro b + apply FiniteDistribution.expectation_congr + intro arrays + exact choice_probability b.2 hn hrows (observe b arrays) + +end +end PerfectCompleteness.PreliminaryAveraging + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/PreliminaryLevelPair.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/PreliminaryLevelPair.lean new file mode 100644 index 0000000000000000000000000000000000000000..c66c5af4cd888d43aae235ad47697760c9e81c1a --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/PreliminaryLevelPair.lean @@ -0,0 +1,63 @@ +import OAI.Computability.PerfectCompleteness.Foundations.DualQuotientRowsLemmas +import OAI.Computability.PerfectCompleteness.Reduction.HierarchicalFixedAdviceFamilyLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.PreliminaryLevelPair + +open PreliminarySampler PreliminaryStrategy CandidateCoupling +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators + +noncomputable section + +variable {v m n t : Nat} {branch rows repeats : Nat → Nat} + +def win (clauses : Fin m → SourceClause.NormalizedClause v) + (strategy : Strategy clauses branch n t rows repeats) + (level : Fin n) (e : Shared clauses branch n t rows) : Bool := + observe clauses (extend clauses branch n t rows repeats strategy) + e.1 e.2.1 ⟨level, e.2.2 level⟩ + +theorem success_eq_mean [NeZero m] + (clauses : Fin m → SourceClause.NormalizedClause v) + (hn : 0 < n) (hbranch : ∀ k < n, 0 < branch k) + (hrows : ∀ k, 0 < rows (k + 1)) + (strategy : Strategy clauses branch n t rows repeats) : + (game clauses branch n t rows repeats hn hbranch hrows).success strategy = + 𝔼 level : Fin n, + (sharedLaw clauses rows repeats hbranch hrows).probability + (win clauses strategy level) := by + rw [success_eq_shared_candidate_mean clauses branch n t rows repeats + hn hbranch hrows strategy] + simp only [candidateFraction, expectation_div, SmallBias.expectation_sum, + Fintype.expect_eq_sum_div_card, Fintype.card_fin] + congr 1 + apply Finset.sum_congr rfl + intro level _ + exact (probability_eq_expectation _ (win clauses strategy level)).symm + +theorem exists_pair [NeZero m] + (clauses : Fin m → SourceClause.NormalizedClause v) + (hn : 0 < n) (hbranch : ∀ k < n, 0 < branch k) + (hrows : ∀ k, 0 < rows (k + 1)) + (strategy : Strategy clauses branch n t rows repeats) + {ε : ℝ} (hε : 0 < ε) (hsize : 4 ≤ (n : ℝ) * ε) + (hsuccess : ε ≤ + (game clauses branch n t rows repeats hn hbranch hrows).success strategy) : + ∃ i j : Fin n, i < j ∧ ε ^ 2 / 2 ≤ + (sharedLaw clauses rows repeats hbranch hrows).probability + (fun e => win clauses strategy i e && win clauses strategy j e) := by + apply LevelPairCounting.exists_level_pair + (sharedLaw clauses rows repeats hbranch hrows) (win clauses strategy) ε hε + · rwa [success_eq_mean clauses hn hbranch hrows strategy] at hsuccess + · exact hsize + +end +end PerfectCompleteness.PreliminaryLevelPair + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/PreliminaryOutputLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/PreliminaryOutputLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..465ffc1b7fac88a0683dac2c42a365d1502225f1 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/PreliminaryOutputLemmas.lean @@ -0,0 +1,271 @@ +import OAI.Computability.PerfectCompleteness.Foundations.DualQuotientRowsLemmas +import OAI.Computability.PerfectCompleteness.Foundations.LegalRationalOutputLemmas +import OAI.Computability.PerfectCompleteness.Reduction.FixedCallBudgetLemmas +import OAI.Computability.PerfectCompleteness.Reduction.PreliminaryLevelPair +import OAI.Computability.PerfectCompleteness.Sampling.SamplerCardinalityLemmas + +namespace OAI + + +namespace PerfectCompleteness.PreliminaryOutput + +open HierarchicalArrays +open scoped Classical + +noncomputable section + +variable {v m : Nat} [NeZero m] + +def value (clauses : Fin m → SourceClause.NormalizedClause v) + (branch : Nat → Nat) (n t : Nat) (rows repeats : Nat → Nat) (hn : 0 < n) + (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) : ℝ := by + let F := PreliminarySampler.family clauses branch n t rows repeats + let : Fintype (HierarchicalGame.LeftVertex F) := Fintype.ofFinite _ + let : Fintype (HierarchicalGame.RightVertex F) := Fintype.ofFinite _ + let : ∀ x, Fintype (HierarchicalGame.LeftLabel F x) := fun _ => Fintype.ofFinite _ + let : ∀ y, Fintype (HierarchicalGame.RightLabel F y) := fun _ => Fintype.ofFinite _ + exact (PreliminarySampler.game clauses branch n t rows repeats hn hbranch hrows).value + +theorem exists_target (clauses : Fin m → SourceClause.NormalizedClause v) + (branch : Nat → Nat) (n t : Nat) (rows repeats : Nat → Nat) (hn : 0 < n) + (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) + (δ : ℚ) (hδ : 0 < δ) : + let F := PreliminarySampler.family clauses branch n t rows repeats + let q := CompletionAlphabet.size (Nat.card (Output branch n rows)) δ + let M := ⌈(3 : ℚ) / δ⌉₊ * + Nat.card (PreliminarySampler.Raw clauses branch n t rows repeats) * (2 * q) + ∃ target : Instance q, + 2 ≤ q ∧ + target.leftVertices = Nat.card (HierarchicalGame.LeftVertex F) ∧ + target.rightVertices = Nat.card (HierarchicalGame.RightVertex F) ∧ + target.edges.length ≤ M ∧ + (Encoding.gameBits target).length ≤ + Nat.card (HierarchicalGame.LeftVertex F) + Nat.card (HierarchicalGame.RightVertex F) + + q + M + 4 + M * + (Nat.card (HierarchicalGame.LeftVertex F) + + Nat.card (HierarchicalGame.RightVertex F) + 2 * q * q + 2 * q + 2) ∧ + ((∃ assignment : Fin v → Bool, + ∀ c, (clauses c).clause.eval assignment = true) → PerfectlyComplete target) ∧ + (value clauses branch n t rows repeats hn hbranch hrows ≤ (δ : ℝ) / 3 → + target.value ≤ (δ : ℝ)) := by + let F := PreliminarySampler.family clauses branch n t rows repeats + let : Nonempty (PreliminarySampler.Raw clauses branch n t rows repeats) := + SamplerRationality.raw_nonempty (t := t) clauses rows repeats hn hbranch hrows + let : Fintype (HierarchicalGame.LeftVertex F) := Fintype.ofFinite _ + let : Fintype (HierarchicalGame.RightVertex F) := Fintype.ofFinite _ + let : ∀ x, Fintype (HierarchicalGame.LeftLabel F x) := fun _ => Fintype.ofFinite _ + let : ∀ y, Fintype (HierarchicalGame.RightLabel F y) := fun _ => Fintype.ofFinite _ + let μ := PreliminarySampler.law (t := t) clauses rows repeats hn hbranch hrows + let rational := SamplerRationality.preliminaryLaw (t := t) + clauses rows repeats hn hbranch hrows + have h := CanonicalRationalOutput.exists_target (HierarchicalGame.toBlockFamily F) + μ rational.weights rational.positive rational.total rational.cast_weight δ hδ + simpa only [← Nat.card_eq_fintype_card, value, PreliminarySampler.game, + HierarchicalGame.game, F, μ] using h + +theorem exists_target_size_bound (clauses : Fin m → SourceClause.NormalizedClause v) + (branch : Nat → Nat) (n t : Nat) (rows repeats : Nat → Nat) (hn : 0 < n) + (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) + (δ : ℚ) (hδ : 0 < δ) : + let q := CompletionAlphabet.size (Nat.card (Output branch n rows)) δ + let R := SamplerCardinality.occurrenceConstant branch n t rows repeats * + m ^ (t * Fintype.card (RecursiveSpaces.Slots branch n)) + let M := ⌈(3 : ℚ) / δ⌉₊ * R * (2 * q) + ∃ target : Instance q, + 2 ≤ q ∧ target.leftVertices ≤ R ∧ target.rightVertices ≤ R ∧ + target.edges.length ≤ M ∧ + (Encoding.gameBits target).length ≤ + 2 * R + q + M + 4 + M * (2 * R + 2 * q * q + 2 * q + 2) ∧ + ((∃ assignment : Fin v → Bool, + ∀ c, (clauses c).clause.eval assignment = true) → PerfectlyComplete target) ∧ + (value clauses branch n t rows repeats hn hbranch hrows ≤ (δ : ℝ) / 3 → + target.value ≤ (δ : ℝ)) := by + let F := PreliminarySampler.family clauses branch n t rows repeats + let q := CompletionAlphabet.size (Nat.card (Output branch n rows)) δ + let R := SamplerCardinality.occurrenceConstant branch n t rows repeats * + m ^ (t * Fintype.card (RecursiveSpaces.Slots branch n)) + let M := ⌈(3 : ℚ) / δ⌉₊ * R * (2 * q) + obtain ⟨target, hq, htL, htR, htE, _htBits, hc, hs⟩ := + exists_target clauses branch n t rows repeats hn hbranch hrows δ hδ + have hraw : Nat.card (PreliminarySampler.Raw clauses branch n t rows repeats) ≤ R := + SamplerCardinality.raw_card_le clauses branch n t rows repeats + have hlraw : Nat.card (HierarchicalGame.LeftVertex F) ≤ + Nat.card (PreliminarySampler.Raw clauses branch n t rows repeats) := by + apply Nat.card_le_card_of_surjective (HierarchicalGame.leftAt F) + rintro ⟨key, e, rfl⟩ + exact ⟨e, rfl⟩ + have hrraw : Nat.card (HierarchicalGame.RightVertex F) ≤ + Nat.card (PreliminarySampler.Raw clauses branch n t rows repeats) := by + apply Nat.card_le_card_of_surjective (HierarchicalGame.rightAt F) + rintro ⟨key, e, rfl⟩ + exact ⟨e, rfl⟩ + have hl : target.leftVertices ≤ R := htL.le.trans (hlraw.trans hraw) + have hr : target.rightVertices ≤ R := htR.le.trans (hrraw.trans hraw) + have he : target.edges.length ≤ M := + htE.trans (Nat.mul_le_mul_right (2 * q) + (Nat.mul_le_mul_left ⌈(3 : ℚ) / δ⌉₊ hraw)) + refine ⟨target, hq, hl, hr, he, ?_, hc, hs⟩ + apply (Encoding.gameBits_length_le_of_edge_count target M he).trans + have hvertices : target.leftVertices + target.rightVertices ≤ 2 * R := by omega + have hheader := Nat.add_le_add_right + (Nat.add_le_add_right (Nat.add_le_add_right hvertices q) M) 4 + have hbody := Nat.add_le_add_right + (Nat.add_le_add_right (Nat.add_le_add_right hvertices (2 * q * q)) (2 * q)) 2 + exact Nat.add_le_add hheader (Nat.mul_le_mul_left M hbody) + +end +end PerfectCompleteness.PreliminaryOutput + + +namespace PerfectCompleteness.FixedPreliminaryGame + +open FixedParameters FixedRows + +noncomputable section + +variable {δ : ℚ} {hδ : 0 < δ} (p : Parameters δ hδ) + +theorem depth_pos : 0 < p.plan.depth := by have := p.plan.depth_ge; omega + +theorem rows_pos (height : Nat) : 0 < rows p.plan height := + lt_of_lt_of_le Nat.zero_lt_one (p.plan.rows_pos (p.plan.depth - height)) + +def game (input : List Bool) := + PreliminarySampler.game (PCPSource.clauseFamily (BinaryLanguage.totalRename input)) + (branch p) p.plan.depth (sourceLength p.plan hδ) (rows p.plan) (repeats p.plan) + (depth_pos p) (fun k _ => branch_pos p k) (fun k => rows_pos p (k + 1)) + +abbrev Strategy (input : List Bool) := + PreliminaryStrategy.Strategy (PCPSource.clauseFamily (BinaryLanguage.totalRename input)) + (branch p) p.plan.depth (sourceLength p.plan hδ) (rows p.plan) (repeats p.plan) + +def value (input : List Bool) : ℝ := + PreliminaryOutput.value (PCPSource.clauseFamily (BinaryLanguage.totalRename input)) + (branch p) p.plan.depth (sourceLength p.plan hδ) (rows p.plan) (repeats p.plan) + (depth_pos p) (fun k _ => branch_pos p k) (fun k => rows_pos p (k + 1)) + +theorem completeness (input : List Bool) (accepted : BinaryLanguage.language input) : + value p input = 1 := by + obtain ⟨assignment, satisfies⟩ := + (PCPSourceMachine.rawSource_satisfiable_iff input).mpr accepted + let F := PreliminarySampler.family (PCPSource.clauseFamily (BinaryLanguage.totalRename input)) + (branch p) p.plan.depth (sourceLength p.plan hδ) (rows p.plan) (repeats p.plan) + let : Fintype (HierarchicalGame.LeftVertex F) := Fintype.ofFinite _ + let : Fintype (HierarchicalGame.RightVertex F) := Fintype.ofFinite _ + let : ∀ x, Fintype (HierarchicalGame.LeftLabel F x) := fun _ => Fintype.ofFinite _ + let : ∀ y, Fintype (HierarchicalGame.RightLabel F y) := fun _ => Fintype.ofFinite _ + unfold value PreliminaryOutput.value + apply HierarchicalGame.value_eq_one F _ assignment + intro occurrence + exact satisfies _ (List.getElem_mem occurrence.isLt) + +theorem exists_level_pair (input : List Bool) (strategy : Strategy p input) + (hsuccess : InitialParameters.epsilon δ ≤ (game p input).success strategy) : + ∃ i j : Fin p.plan.depth, i < j ∧ InitialParameters.simultaneous δ ≤ + (CandidateCoupling.sharedLaw + (PCPSource.clauseFamily (BinaryLanguage.totalRename input)) + (rows p.plan) (repeats p.plan) + (fun k _ => branch_pos p k) (fun k => rows_pos p (k + 1))).probability + (fun e => PreliminaryLevelPair.win + (PCPSource.clauseFamily (BinaryLanguage.totalRename input)) strategy i e && + PreliminaryLevelPair.win + (PCPSource.clauseFamily (BinaryLanguage.totalRename input)) strategy j e) := + PreliminaryLevelPair.exists_pair + (PCPSource.clauseFamily (BinaryLanguage.totalRename input)) + (depth_pos p) (fun k _ => branch_pos p k) (fun k => rows_pos p (k + 1)) + strategy (InitialParameters.epsilon_pos hδ) p.plan.depth_mass hsuccess + +end +end PerfectCompleteness.FixedPreliminaryGame + + +namespace PerfectCompleteness.FixedPreliminaryValue + +open FixedParameters FixedRows FixedPreliminaryGame + +noncomputable section + +variable {δ : ℚ} {hδ : 0 < δ} (p : Parameters δ hδ) + +theorem exists_optimal_strategy (input : List Bool) : + ∃ strategy : Strategy p input, + (game p input).success strategy = value p input := by + let F := PreliminarySampler.family (PCPSource.clauseFamily (BinaryLanguage.totalRename input)) + (branch p) p.plan.depth (sourceLength p.plan hδ) (rows p.plan) (repeats p.plan) + let : Fintype (HierarchicalGame.LeftVertex F) := Fintype.ofFinite _ + let : Fintype (HierarchicalGame.RightVertex F) := Fintype.ofFinite _ + let : ∀ x, Fintype (HierarchicalGame.LeftLabel F x) := fun _ => Fintype.ofFinite _ + let : ∀ y, Fintype (HierarchicalGame.RightLabel F y) := fun _ => Fintype.ofFinite _ + exact (game p input).exists_optimal_strategy + +theorem value_lt_of_strategy_lt (input : List Bool) (bound : ℝ) + (hbound : ∀ strategy : Strategy p input, (game p input).success strategy < bound) : + value p input < bound := by + obtain ⟨strategy, hs⟩ := exists_optimal_strategy p input + rw [← hs] + exact hbound strategy + +theorem value_le_of_no_large_strategy (input : List Bool) (bound : ℝ) + (hbound : ∀ strategy : Strategy p input, ¬bound ≤ (game p input).success strategy) : + value p input ≤ bound := + le_of_lt (value_lt_of_strategy_lt p input bound (fun strategy => + lt_of_not_ge (hbound strategy))) + +end +end PerfectCompleteness.FixedPreliminaryValue + + +namespace PerfectCompleteness.PreliminaryPairReserve + +open FixedParameters FixedRows +open scoped BigOperators + +noncomputable section + +variable {δ : ℚ} {hδ : 0 < δ} (p : Parameters δ hδ) + +theorem exists_pair (input : List Bool) (strategy : FixedPreliminaryGame.Strategy p input) + (hsuccess : InitialParameters.epsilon δ ≤ + (FixedPreliminaryGame.game p input).success strategy) : + ∃ i j : Fin p.plan.depth, i < j ∧ + InitialParameters.simultaneous δ + 3 * p.accuracy ≤ + (CandidateCoupling.sharedLaw + (PCPSource.clauseFamily (BinaryLanguage.totalRename input)) + (rows p.plan) (repeats p.plan) + (fun k _ => branch_pos p k) + (fun k => FixedPreliminaryGame.rows_pos p (k + 1))).probability + (fun e => PreliminaryLevelPair.win + (PCPSource.clauseFamily (BinaryLanguage.totalRename input)) strategy i e && + PreliminaryLevelPair.win + (PCPSource.clauseFamily (BinaryLanguage.totalRename input)) strategy j e) := by + have hmean : InitialParameters.epsilon δ ≤ + 𝔼 level : Fin p.plan.depth, + (CandidateCoupling.sharedLaw + (PCPSource.clauseFamily (BinaryLanguage.totalRename input)) + (rows p.plan) (repeats p.plan) + (fun k _ => branch_pos p k) + (fun k => FixedPreliminaryGame.rows_pos p (k + 1))).probability + (PreliminaryLevelPair.win + (PCPSource.clauseFamily (BinaryLanguage.totalRename input)) strategy level) := by + rw [← PreliminaryLevelPair.success_eq_mean + (PCPSource.clauseFamily (BinaryLanguage.totalRename input)) + (FixedPreliminaryGame.depth_pos p) (fun k _ => branch_pos p k) + (fun k => FixedPreliminaryGame.rows_pos p (k + 1)) strategy] + exact hsuccess + obtain ⟨i, j, hij, hprob⟩ := LevelPairReserve.exists_pair _ _ + (InitialParameters.epsilon δ) (InitialParameters.epsilon_pos hδ) + hmean p.plan.depth_mass + refine ⟨i, j, hij, ?_⟩ + have hsmall := p.accuracy_small 0 (Nat.zero_le _) + simp only [CommonAccuracy.tolerance, lt_min_iff] at hsmall + have hε := InitialParameters.epsilon_pos hδ + have hreserved : InitialParameters.simultaneous δ + 3 * p.accuracy ≤ + 2 * InitialParameters.epsilon δ ^ 2 / 3 := by + unfold InitialParameters.simultaneous + nlinarith [hsmall.1, sq_pos_of_pos hε] + exact hreserved.trans hprob + +end +end PerfectCompleteness.PreliminaryPairReserve + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/SignedCompletionSchedule.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/SignedCompletionSchedule.lean new file mode 100644 index 0000000000000000000000000000000000000000..1ac42f9dd8652e9eb62de784da449346e4d4c04c --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/SignedCompletionSchedule.lean @@ -0,0 +1,188 @@ +import OAI.Computability.PerfectCompleteness.Foundations.ExactConditionalOutput +import OAI.Computability.PerfectCompleteness.Foundations.RawOccurrenceOrderLemmas +import OAI.Computability.PerfectCompleteness.Machines.FiniteConstraintMachine + +namespace OAI + + +namespace PerfectCompleteness.SignedCompletionSchedule + + +open MetadataFreeSampler MetadataFreeLaw +open UniqueGamesTheorem.Foundations.Games +open Turing UniqueGamesTheorem.Foundations.Complexity +open scoped BigOperators Classical + +noncomputable section + +variable {branch : Nat → Nat} {n t q : Nat} {rows repeats : Nat → Nat} + (hq : 0 < q) + (large : CanonicalKeyEncoding.partitionWidth (TreeCanonical.locationCount branch n t) ≤ q) + +def result (signs : SignTuple branch n t) (e : SignedOutcome signs rows repeats) : + LocalCompletionFamily.Result q := FiniteConstraintMachine.result hq large ⟨signs, e⟩ + +def active (signs : SignTuple branch n t) (e : SignedOutcome signs rows repeats) : Nat := + LocalCompletionFamily.activeCount (result (rows := rows) (repeats := repeats) hq large signs e) + +theorem active_positive (signs : SignTuple branch n t) (e : SignedOutcome signs rows repeats) : + 0 < active (rows := rows) (repeats := repeats) hq large signs e := LocalCompletionFamily.activeCount_positive _ + +theorem active_le (signs : SignTuple branch n t) (e : SignedOutcome signs rows repeats) : + active (rows := rows) (repeats := repeats) hq large signs e ≤ 2 * q := LocalCompletionFamily.activeCount_le _ + +abbrev Completed (signs : SignTuple branch n t) := + Σ e : SignedOutcome signs rows repeats, Fin (active (rows := rows) (repeats := repeats) hq large signs e) + +abbrev Descriptor := Σ signs : SignTuple branch n t, Completed (rows := rows) (repeats := repeats) hq large signs + +def descriptorTable (descriptor : Descriptor (rows := rows) (repeats := repeats) hq large) : Fin (2 * q) → Fin q := + LocalCompletionFamily.table (result (rows := rows) (repeats := repeats) hq large descriptor.1 descriptor.2.1) descriptor.2.2 + +theorem descriptorTable_eq_parsed (signs : SignTuple branch n t) + (e : Completed (rows := rows) (repeats := repeats) hq large signs) (a : Fin (2 * q)) : + descriptorTable (rows := rows) (repeats := repeats) hq large ⟨signs, e⟩ a = + (LocalCompletionSerialization.projection + (FiniteConstraintMachine.result_correct (rows := rows) (repeats := repeats) hq large ⟨signs, e.1⟩) e.2).images[a] := + (FiniteConstraintMachine.parsed_projection (rows := rows) (repeats := repeats) hq large ⟨signs, e.1⟩ e.2 a).symm + +def seedLaw (signs : SignTuple branch n t) (e : SignedOutcome signs rows repeats) : + FiniteDistribution (Fin (active (rows := rows) (repeats := repeats) hq large signs e)) := by + letI : Nonempty (Fin (active (rows := rows) (repeats := repeats) hq large signs e)) := ⟨⟨0, active_positive (rows := rows) (repeats := repeats) hq large signs e⟩⟩ + exact FiniteDistribution.uniform _ + +variable (hn : 0 < n) (hbranch : ∀ k < n, 0 < branch k) + (hrows : ∀ k, 0 < rows (k + 1)) + +def law (signs : SignTuple branch n t) : FiniteDistribution (Completed (rows := rows) (repeats := repeats) hq large signs) := + CompletionSoundness.sigmaLaw (signedLaw signs rows repeats hn hbranch hrows) + (seedLaw (rows := rows) (repeats := repeats) hq large signs) + +theorem law_weight (signs : SignTuple branch n t) (e : Completed (rows := rows) (repeats := repeats) hq large signs) : + (law (rows := rows) (repeats := repeats) hq large hn hbranch hrows signs).weight e = + (signedLaw signs rows repeats hn hbranch hrows).weight e.1 / + active (rows := rows) (repeats := repeats) hq large signs e.1 := by + change (signedLaw signs rows repeats hn hbranch hrows).weight e.1 * + (1 / (Fintype.card (Fin (active (rows := rows) (repeats := repeats) hq large signs e.1)) : ℝ)) = _ + simp only [Fintype.card_fin, div_eq_mul_inv, one_mul] + +def count (signs : SignTuple branch n t) (e : Completed (rows := rows) (repeats := repeats) hq large signs) : Nat := + ExactSeedMultiplicity.perSeed (2 * q) (active (rows := rows) (repeats := repeats) hq large signs e.1) + (SignedMultiplicity.baseCopies branch n t rows repeats hn hbranch hrows signs e.1) + +theorem count_positive (signs : SignTuple branch n t) (e : Completed (rows := rows) (repeats := repeats) hq large signs) : + 0 < count (rows := rows) (repeats := repeats) hq large hn hbranch hrows signs e := + ExactSeedMultiplicity.perSeed_positive (active_positive (rows := rows) (repeats := repeats) hq large signs e.1) + (active_le (rows := rows) (repeats := repeats) hq large signs e.1) + (SignedMultiplicity.baseCopies_positive branch n t rows repeats hn hbranch hrows signs e.1) + +theorem count_total (signs : SignTuple branch n t) : + (∑ e, count (rows := rows) (repeats := repeats) hq large hn hbranch hrows signs e) = + SignedMultiplicity.denominator branch n t rows repeats hn hbranch hrows q := + ExactSeedMultiplicity.sum_multiplicity + (SignedMultiplicity.baseCopies branch n t rows repeats hn hbranch hrows signs) + (active (rows := rows) (repeats := repeats) hq large signs) (active_positive (rows := rows) (repeats := repeats) hq large signs) (active_le (rows := rows) (repeats := repeats) hq large signs) + (SignedMultiplicity.baseCopies_total branch n t rows repeats hn hbranch hrows signs) + +theorem count_ratio (signs : SignTuple branch n t) (e : Completed (rows := rows) (repeats := repeats) hq large signs) : + (count (rows := rows) (repeats := repeats) hq large hn hbranch hrows signs e : ℚ) / + SignedMultiplicity.denominator branch n t rows repeats hn hbranch hrows q = + SignedMultiplicity.weights branch n t rows repeats hn hbranch hrows signs e.1 / + active (rows := rows) (repeats := repeats) hq large signs e.1 := by + change (ExactSeedMultiplicity.perSeed (2 * q) (active (rows := rows) (repeats := repeats) hq large signs e.1) + (SignedMultiplicity.baseCopies branch n t rows repeats hn hbranch hrows signs e.1) : ℚ) / + ExactSeedMultiplicity.denominator + (SignedMultiplicity.baseDenominator branch n t rows repeats hn hbranch hrows) (2 * q) = _ + rw [ExactSeedMultiplicity.perSeed_ratio + (SignedMultiplicity.baseDenominator_positive branch n t rows repeats hn hbranch hrows) + (active_positive (rows := rows) (repeats := repeats) hq large signs e.1) (active_le (rows := rows) (repeats := repeats) hq large signs e.1), + SignedMultiplicity.baseCopies_ratio] + +theorem count_mass (signs : SignTuple branch n t) (e : Completed (rows := rows) (repeats := repeats) hq large signs) : + (count (rows := rows) (repeats := repeats) hq large hn hbranch hrows signs e : ℝ) / + SignedMultiplicity.denominator branch n t rows repeats hn hbranch hrows q = + (law (rows := rows) (repeats := repeats) hq large hn hbranch hrows signs).weight e := by + have h := congrArg (fun z : ℚ => (z : ℝ)) (count_ratio (rows := rows) (repeats := repeats) hq large hn hbranch hrows signs e) + simp only [Rat.cast_div, Rat.cast_natCast] at h + rw [law_weight, (signedRationalLaw signs rows repeats hn hbranch hrows).cast_weight] + exact h + +def schedule (signs : SignTuple branch n t) : List (Completed (rows := rows) (repeats := repeats) hq large signs) := + ExactConditionalOutput.copies (count (rows := rows) (repeats := repeats) hq large hn hbranch hrows) signs + +theorem schedule_length (signs : SignTuple branch n t) : + (schedule (rows := rows) (repeats := repeats) hq large hn hbranch hrows signs).length = + SignedMultiplicity.denominator branch n t rows repeats hn hbranch hrows q := by + rw [schedule, ExactConditionalOutput.copies_length, count_total] + +theorem schedule_nonempty (signs : SignTuple branch n t) : + schedule (rows := rows) (repeats := repeats) hq large hn hbranch hrows signs ≠ [] := by + intro hempty + have h := schedule_length (rows := rows) (repeats := repeats) hq large hn hbranch hrows signs + rw [hempty, List.length_nil] at h + exact (Nat.ne_of_gt + (SignedMultiplicity.denominator_positive branch n t rows repeats hn hbranch hrows q)) h.symm + +theorem schedule_acceptance (signs : SignTuple branch n t) + (accepts : Completed (rows := rows) (repeats := repeats) hq large signs → Bool) : + (((schedule (rows := rows) (repeats := repeats) hq large hn hbranch hrows signs).filter accepts).length : ℝ) / + (schedule (rows := rows) (repeats := repeats) hq large hn hbranch hrows signs).length = + (law (rows := rows) (repeats := repeats) hq large hn hbranch hrows signs).probability accepts := by + rw [schedule_length] + change (((ExactConditionalOutput.copies (count (rows := rows) (repeats := repeats) hq large hn hbranch hrows) signs).filter + accepts).length : ℝ) / _ = _ + rw [ExactConditionalOutput.copies_filter_length, Nat.cast_sum, Finset.sum_div, + FiniteDistribution.probability] + apply Finset.sum_congr rfl + intro e _ + cases accepts e <;> simp [count_mass] + +def descriptorEnum : Descriptor (rows := rows) (repeats := repeats) hq large ≃ Fin (Fintype.card (Descriptor (rows := rows) (repeats := repeats) hq large)) := + Fintype.equivFin _ + +def descriptorBits (descriptor : Descriptor (rows := rows) (repeats := repeats) hq large) : List Bool := + FiniteBlockMachine.word (descriptorEnum (rows := rows) (repeats := repeats) hq large) descriptor + +@[simp] theorem descriptorBits_length (descriptor : Descriptor (rows := rows) (repeats := repeats) hq large) : + (descriptorBits (rows := rows) (repeats := repeats) hq large descriptor).length = Fintype.card (Descriptor (rows := rows) (repeats := repeats) hq large) := + FiniteBlockMachine.word_length _ _ + +def outputBits (signs : SignTuple branch n t) : List Bool := + (schedule (rows := rows) (repeats := repeats) hq large hn hbranch hrows signs).flatMap + (fun e => descriptorBits (rows := rows) (repeats := repeats) hq large ⟨signs, e⟩) + +def signsEnum (branch : Nat → Nat) (n t : Nat) : + SignTuple branch n t ≃ Fin (Fintype.card (SignTuple branch n t)) := Fintype.equivFin _ + +def inputBits (signs : SignTuple branch n t) : List Bool := + FiniteBlockMachine.word (signsEnum branch n t) signs + +def computation : + TM2ComputableInPolyTime (inputBits (branch := branch) (n := n) (t := t)) + id (outputBits (rows := rows) (repeats := repeats) hq large hn hbranch hrows) := + FiniteWordMachine.computation (signsEnum branch n t) (fun _ _ => (false, false, false)) + (outputBits (rows := rows) (repeats := repeats) hq large hn hbranch hrows) + +def machine_output (signs : SignTuple branch n t) : + TM2OutputsInTime (computation (rows := rows) (repeats := repeats) hq large hn hbranch hrows).tm (inputBits signs) + (some (outputBits (rows := rows) (repeats := repeats) hq large hn hbranch hrows signs)) 1 := by + have h := (computation (rows := rows) (repeats := repeats) hq large hn hbranch hrows).outputsFun signs + change TM2OutputsInTime (computation (rows := rows) (repeats := repeats) hq large hn hbranch hrows).tm + ((inputBits signs).map id) (some ((outputBits (rows := rows) (repeats := repeats) hq large hn hbranch hrows signs).map id)) + ((1 : Polynomial Nat).eval _) at h + rw [Polynomial.eval_one] at h + exact Eq.mp (congrArg₂ + (fun (i o : List Bool) => + TM2OutputsInTime (computation (rows := rows) (repeats := repeats) hq large hn hbranch hrows).tm i (some o) 1) + (List.map_id (inputBits signs)) + (List.map_id (outputBits (rows := rows) (repeats := repeats) hq large hn hbranch hrows signs))) h + +theorem workAlphabet_finite (tape : (computation (rows := rows) (repeats := repeats) hq large hn hbranch hrows).tm.K) : + Finite ((computation (rows := rows) (repeats := repeats) hq large hn hbranch hrows).tm.Γ tape) := by + change Finite Bool + infer_instance + +end +end PerfectCompleteness.SignedCompletionSchedule + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/SourceCompleteness.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/SourceCompleteness.lean new file mode 100644 index 0000000000000000000000000000000000000000..53f39702a8c8f32980529dac7c77827efa56aacc --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/SourceCompleteness.lean @@ -0,0 +1,138 @@ +import OAI.Computability.PerfectCompleteness.Foundations.SourceStrategy + +namespace OAI + +section + +namespace PerfectCompleteness.SourceCompleteness + +open SourceClause ClauseSupport MixedSupport CanonicalKeys SourceKeys + +variable {v m n : Nat} {Y Z : Type*} + +structure Presentation (clauses : Fin m → NormalizedClause v) (n : Nat) (Y : Type*) where + endpoints : Fin n → Endpoint v m + joint : Assignment (slot clauses ∘ endpoints) → Y + +variable {clauses : Fin m → NormalizedClause v} {side : Side} + +noncomputable def presentationKey (side : Side) (P : Presentation clauses n Y) : Key n := + key side (slot clauses ∘ P.endpoints) P.joint + +noncomputable def generatedKeys (side : Side) (clauses : Fin m → NormalizedClause v) + (n : Nat) (Y : Type*) : Set (Key n) := + Set.range (presentationKey (clauses := clauses) (n := n) (Y := Y) side) + +abbrev Vertex (side : Side) (clauses : Fin m → NormalizedClause v) (n : Nat) (Y : Type*) := + ↥(generatedKeys side clauses n Y) + +noncomputable def vertexOf (side : Side) (P : Presentation clauses n Y) : + Vertex side clauses n Y := + ⟨presentationKey side P, ⟨P, rfl⟩⟩ + +abbrev VertexLabel (vertex : Vertex side clauses n Y) := + {part : Set (Fin n → ReducedValue) // part ∈ vertex.val.partition} + +noncomputable def representation (vertex : Vertex side clauses n Y) : + Presentation clauses n Y := + vertex.property.choose + +theorem representation_key (vertex : Vertex side clauses n Y) : + presentationKey side (representation vertex) = vertex.val := + vertex.property.choose_spec + +noncomputable def evaluatedLabel (assignment : Fin v → Bool) + (hsat : ∀ c, (clauses c).clause.eval assignment = true) + (P : Presentation clauses n Y) : Label (slot clauses ∘ P.endpoints) P.joint := + evaluateLabel (slot clauses ∘ P.endpoints) P.joint + (realizingAssignment clauses assignment hsat P.endpoints) + +noncomputable def strategy (assignment : Fin v → Bool) + (hsat : ∀ c, (clauses c).clause.eval assignment = true) + (vertex : Vertex side clauses n Y) : VertexLabel vertex := by + refine ⟨(evaluatedLabel assignment hsat (representation vertex)).val, ?_⟩ + rw [← representation_key vertex] + exact (evaluatedLabel assignment hsat (representation vertex)).property + +theorem strategy_value_eq (assignment : Fin v → Bool) + (hsat : ∀ c, (clauses c).clause.eval assignment = true) + (vertex : Vertex side clauses n Y) (P : Presentation clauses n Z) + (hkey : presentationKey side P = vertex.val) : + (strategy assignment hsat vertex).val = (evaluatedLabel assignment hsat P).val := by + change (evaluatedLabel assignment hsat (representation vertex)).val = + (evaluatedLabel assignment hsat P).val + exact evaluated_label_eq_of_key_eq clauses assignment hsat side side + (representation vertex).endpoints P.endpoints + (representation vertex).joint P.joint + ((representation_key vertex).trans hkey.symm) + +def labelInPresentation (vertex : Vertex side clauses n Y) + (P : Presentation clauses n Z) (hkey : presentationKey side P = vertex.val) + (label : VertexLabel vertex) : Label (slot clauses ∘ P.endpoints) P.joint := + ⟨label.val, by + change label.val ∈ (presentationKey side P).partition + rw [hkey] + exact label.property⟩ + +theorem strategy_in_presentation (assignment : Fin v → Bool) + (hsat : ∀ c, (clauses c).clause.eval assignment = true) + (vertex : Vertex side clauses n Y) (P : Presentation clauses n Z) + (hkey : presentationKey side P = vertex.val) : + labelInPresentation vertex P hkey (strategy assignment hsat vertex) = + evaluatedLabel assignment hsat P := by + apply Subtype.ext + exact strategy_value_eq assignment hsat vertex P hkey + +theorem restore_strategy_in_presentation (assignment : Fin v → Bool) + (hsat : ∀ c, (clauses c).clause.eval assignment = true) + (vertex : Vertex side clauses n Y) (P : Presentation clauses n Z) + (hkey : presentationKey side P = vertex.val) : + restore (slot clauses ∘ P.endpoints) P.joint + (labelInPresentation vertex P hkey (strategy assignment hsat vertex)) = + P.joint (realizingAssignment clauses assignment hsat P.endpoints) := by + rw [strategy_in_presentation] + exact restore_evaluateLabel _ _ _ + +def Presentation.postcompose (P : Presentation clauses n Y) (p : Y → Z) : + Presentation clauses n Z where + endpoints := P.endpoints + joint := p ∘ P.joint + +noncomputable def coarseningEdge (sourceSide targetSide : Side) + (P : Presentation clauses n Y) (p : Y → Z) + (label : VertexLabel (vertexOf sourceSide P)) : + VertexLabel (vertexOf targetSide (P.postcompose p)) := by + let original := labelInPresentation (vertexOf sourceSide P) P rfl label + let coarse := CanonicalEdges.coarsen (slot clauses ∘ P.endpoints) P.joint p original + exact ⟨coarse.val, coarse.property⟩ + +theorem coarseningEdge_strategy (assignment : Fin v → Bool) + (hsat : ∀ c, (clauses c).clause.eval assignment = true) + (sourceSide targetSide : Side) (P : Presentation clauses n Y) (p : Y → Z) : + coarseningEdge sourceSide targetSide P p + (strategy assignment hsat (vertexOf sourceSide P)) = + strategy assignment hsat (vertexOf targetSide (P.postcompose p)) := by + have hsource : presentationKey sourceSide P = (vertexOf sourceSide P).val := rfl + have htarget : presentationKey targetSide (P.postcompose p) = + (vertexOf targetSide (P.postcompose p)).val := rfl + have hlabel : labelInPresentation (vertexOf sourceSide P) P hsource + (strategy assignment hsat (vertexOf sourceSide P)) = evaluatedLabel assignment hsat P := + strategy_in_presentation assignment hsat (vertexOf sourceSide P) P hsource + apply Subtype.ext + calc + _ = (CanonicalEdges.coarsen (slot clauses ∘ P.endpoints) P.joint p + (evaluatedLabel assignment hsat P)).val := + congrArg (fun L : Label (slot clauses ∘ P.endpoints) P.joint => + (CanonicalEdges.coarsen (slot clauses ∘ P.endpoints) P.joint p L).val) hlabel + _ = (evaluatedLabel assignment hsat (P.postcompose p)).val := + congrArg (fun L : Label (slot clauses ∘ P.endpoints) (p ∘ P.joint) => L.val) + (CanonicalEdges.coarsen_evaluateLabel (slot clauses ∘ P.endpoints) P.joint p + (realizingAssignment clauses assignment hsat P.endpoints)) + _ = _ := (strategy_value_eq assignment hsat (vertexOf targetSide (P.postcompose p)) + (P.postcompose p) htarget).symm + +end PerfectCompleteness.SourceCompleteness + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/SourceGame.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/SourceGame.lean new file mode 100644 index 0000000000000000000000000000000000000000..01e4834f6ef32187a4239c559fdcbf7d4967e0e1 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/SourceGame.lean @@ -0,0 +1,233 @@ +import Mathlib.Algebra.BigOperators.Field +import Mathlib.Algebra.BigOperators.Fin +import Mathlib.Tactic.FieldSimp +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.NormNum +import OAI.Computability.PerfectCompleteness.Foundations.SourceClause +import OAI.Computability.PerfectCompleteness.Reduction.OccurrenceGame + +namespace OAI + +section + +namespace PerfectCompleteness.SourceGame + +open SourceClause UniqueGamesTheorem.Foundations.Games +open scoped BigOperators + +def decodeLabel (signs : Triple) (label : Fin 7) : Triple := + (satisfyingTriples signs)[label.val]'(by + rw [satisfyingTriples_length] + exact label.isLt) + +theorem decodeLabel_mem (signs : Triple) (label : Fin 7) : + decodeLabel signs label ∈ satisfyingTriples signs := by + exact List.getElem_mem _ + +theorem decodeLabel_legal (signs : Triple) (label : Fin 7) : + localEval signs (decodeLabel signs label) = true := + (mem_satisfyingTriples signs _).mp (decodeLabel_mem signs label) + +theorem decodeLabel_injective (signs : Triple) : Function.Injective (decodeLabel signs) := by + intro a b same + apply Fin.ext + exact (List.Nodup.getElem_inj (satisfyingTriples_nodup signs)).mp same + +def encodeLabel (signs label : Triple) (legal : localEval signs label = true) : Fin 7 := + ⟨(satisfyingTriples signs).idxOf label, by + have h := List.idxOf_lt_length_of_mem ((mem_satisfyingTriples signs label).mpr legal) + simpa using h⟩ + +@[simp] theorem decodeLabel_encodeLabel (signs label : Triple) + (legal : localEval signs label = true) : + decodeLabel signs (encodeLabel signs label legal) = label := by + exact List.getElem_idxOf _ + +def projection {n m : Nat} (clauses : Fin m → NormalizedClause n) + (e : Occurrence m) (answer : Fin 7) : Bool := + (decodeLabel (clauses e.1).signs answer).at e.2 + +theorem projection_surjective {n m : Nat} (clauses : Fin m → NormalizedClause n) + (e : Occurrence m) (answer : Bool) : + ∃ label : Fin 7, projection clauses e label = answer := by + obtain ⟨t, legal, ht⟩ := coordinate_surjective (clauses e.1).signs e.2 answer + refine ⟨encodeLabel (clauses e.1).signs t + ((mem_satisfyingTriples _ _).mp legal), ?_⟩ + simpa [projection] using ht + +theorem projection_pair_surjective {n m : Nat} (clauses : Fin m → NormalizedClause n) + (c : Fin m) (i j : Fin 3) (different : i ≠ j) (first second : Bool) : + ∃ label : Fin 7, + projection clauses (c, i) label = first ∧ projection clauses (c, j) label = second := by + obtain ⟨t, legal, ht⟩ := pair_surjective (clauses c).signs i j different first second + refine ⟨encodeLabel (clauses c).signs t ((mem_satisfyingTriples _ _).mp legal), ?_⟩ + simpa [projection] using ht + +theorem leftAlphabet_card : Fintype.card (Fin 7) = 7 := by simp +theorem rightAlphabet_card : Fintype.card Bool = 2 := by decide + +noncomputable section + +def game {n m : Nat} [NeZero m] (clauses : Fin m → NormalizedClause n) : + OccurrenceGame (Occurrence m) (Fin m) (Fin n) (Fin 7) Bool := + OccurrenceGame.ofProjection (FiniteDistribution.uniform (Occurrence m)) + Prod.fst (occurrenceVariable clauses) (projection clauses) + +theorem endpointDetermined {n m : Nat} [NeZero m] + (clauses : Fin m → NormalizedClause n) : (game clauses).EndpointDetermined := by + intro e e' sameClause sameVariable a b + have same := occurrence_determined_by_endpoints clauses e e' sameClause sameVariable + subst e' + rfl + +def endpointPredicate {n m : Nat} (clauses : Fin m → NormalizedClause n) + (c : Fin m) (v : Fin n) (a : Fin 7) (b : Bool) : Bool := + decide (∃ i : Fin 3, (clauses c).variable i = v ∧ + (decodeLabel (clauses c).signs a).at i = b) + +theorem endpointPredicate_eq_true {n m : Nat} (clauses : Fin m → NormalizedClause n) + (c : Fin m) (v : Fin n) (a : Fin 7) (b : Bool) : + endpointPredicate clauses c v a b = true ↔ + ∃ i : Fin 3, (clauses c).variable i = v ∧ + (decodeLabel (clauses c).signs a).at i = b := by + exact decide_eq_true_iff + +def presentation {n m : Nat} [NeZero m] + (clauses : Fin m → NormalizedClause n) : (game clauses).EndpointPresentation where + predicate := endpointPredicate clauses + agrees e a b := by + apply Bool.eq_iff_iff.mpr + rw [endpointPredicate_eq_true] + simp only [game, OccurrenceGame.ofProjection, occurrenceVariable, decide_eq_true_eq] + constructor + · intro h + exact ⟨e.2, rfl, h⟩ + · rintro ⟨i, sameVariable, h⟩ + have samePosition : i = e.2 := (clauses e.1).distinct i e.2 sameVariable + simpa [projection, samePosition] using h + +def questionGame {n m : Nat} [NeZero m] (clauses : Fin m → NormalizedClause n) : + Game (Fin m) (Fin n) (Fin 7) Bool := + (game clauses).toGame (presentation clauses) + +@[simp] theorem questionGame_success {n m : Nat} [NeZero m] + (clauses : Fin m → NormalizedClause n) (strategy : Strategy (Fin m) (Fin n) (Fin 7) Bool) : + (questionGame clauses).success strategy = (game clauses).success strategy := + (game clauses).toGame_success (presentation clauses) strategy + +theorem restrict_at {n : Nat} (c : NormalizedClause n) + (assignment : Fin n → Bool) (i : Fin 3) : + (c.restrict assignment).at i = assignment (c.variable i) := by + have cases_three : ∀ i : Fin 3, i = 0 ∨ i = 1 ∨ i = 2 := by decide + rcases cases_three i with rfl | rfl | rfl <;> rfl + +def completenessStrategy {n m : Nat} (clauses : Fin m → NormalizedClause n) + (assignment : Fin n → Bool) (satisfying : ∀ c, (clauses c).clause.eval assignment = true) : + Strategy (Fin m) (Fin n) (Fin 7) Bool := + (fun c => encodeLabel (clauses c).signs ((clauses c).restrict assignment) + (by simpa using satisfying c), assignment) + +theorem completeness_wins {n m : Nat} [NeZero m] + (clauses : Fin m → NormalizedClause n) (assignment : Fin n → Bool) + (satisfying : ∀ c, (clauses c).clause.eval assignment = true) (e : Occurrence m) : + (game clauses).wins (completenessStrategy clauses assignment satisfying) e = true := by + simp only [game, OccurrenceGame.ofProjection, OccurrenceGame.wins, completenessStrategy, + projection, decodeLabel_encodeLabel, decide_eq_true_eq] + exact restrict_at (clauses e.1) assignment e.2 + +theorem completeness_success {n m : Nat} [NeZero m] + (clauses : Fin m → NormalizedClause n) (assignment : Fin n → Bool) + (satisfying : ∀ c, (clauses c).clause.eval assignment = true) : + (game clauses).success (completenessStrategy clauses assignment satisfying) = 1 := by + have h : (game clauses).wins (completenessStrategy clauses assignment satisfying) = + fun _ => true := funext (completeness_wins clauses assignment satisfying) + unfold OccurrenceGame.success + rw [h, FiniteDistribution.probability_true] + +theorem completeness_value {n m : Nat} [NeZero m] + (clauses : Fin m → NormalizedClause n) (assignment : Fin n → Bool) + (satisfying : ∀ c, (clauses c).clause.eval assignment = true) : + (game clauses).value = 1 := by + apply le_antisymm (game clauses).value_le_one + rw [← completeness_success clauses assignment satisfying] + exact (game clauses).success_le_value _ + +def winCount {n m : Nat} (clauses : Fin m → NormalizedClause n) + (strategy : Strategy (Fin m) (Fin n) (Fin 7) Bool) : Nat := + ∑ c, agreementCount (clauses c) (decodeLabel (clauses c).signs (strategy.1 c)) strategy.2 + +def violatedCount {n m : Nat} (clauses : Fin m → NormalizedClause n) + (assignment : Fin n → Bool) : Nat := + ∑ c, if (clauses c).clause.eval assignment then 0 else 1 + +theorem winCount_add_violated_le {n m : Nat} (clauses : Fin m → NormalizedClause n) + (strategy : Strategy (Fin m) (Fin n) (Fin 7) Bool) : + winCount clauses strategy + violatedCount clauses strategy.2 ≤ 3 * m := by + unfold winCount violatedCount + rw [← Finset.sum_add_distrib] + calc + _ ≤ ∑ _c : Fin m, 3 := by + apply Finset.sum_le_sum + intro c _ + have h := agreementCount_le_two_add_satisfied (clauses c) + (decodeLabel (clauses c).signs (strategy.1 c)) strategy.2 + (decodeLabel_legal _ _) + cases heval : (clauses c).clause.eval strategy.2 <;> + simp [heval] at h ⊢ <;> omega + _ = 3 * m := by simp [Nat.mul_comm] + +private theorem probability_uniform {E : Type*} [Fintype E] [Nonempty E] + (event : E → Bool) : + (FiniteDistribution.uniform E).probability event = + (∑ e, if event e then (1 : ℝ) else 0) / (Fintype.card E : ℝ) := by + unfold FiniteDistribution.probability FiniteDistribution.uniform + rw [Finset.sum_div] + apply Finset.sum_congr rfl + intro e _ + cases event e <;> simp + +theorem success_eq_winCount_div {n m : Nat} [NeZero m] + (clauses : Fin m → NormalizedClause n) + (strategy : Strategy (Fin m) (Fin n) (Fin 7) Bool) : + (game clauses).success strategy = (winCount clauses strategy : ℝ) / (3 * (m : ℝ)) := by + have hsum : + (∑ e : Occurrence m, if (game clauses).wins strategy e then (1 : ℝ) else 0) = + (winCount clauses strategy : ℝ) := by + rw [Fintype.sum_prod_type] + simp only [winCount, Nat.cast_sum] + apply Finset.sum_congr rfl + intro c _ + rw [Fin.sum_univ_three] + simp [game, OccurrenceGame.ofProjection, OccurrenceGame.wins, projection, + occurrenceVariable, agreementCount, Triple.at, Nat.cast_add, Nat.cast_ite] + change (FiniteDistribution.uniform (Occurrence m)).probability + ((game clauses).wins strategy) = _ + rw [probability_uniform, hsum] + congr 1 + simp [Occurrence, mul_comm] + +theorem success_le_one_sub_third_violations {n m : Nat} [NeZero m] + (clauses : Fin m → NormalizedClause n) + (strategy : Strategy (Fin m) (Fin n) (Fin 7) Bool) : + (game clauses).success strategy ≤ + 1 - ((violatedCount clauses strategy.2 : ℝ) / (m : ℝ)) / 3 := by + have hm : (0 : ℝ) < m := by exact_mod_cast Nat.pos_of_neZero m + have hden : (0 : ℝ) < 3 * (m : ℝ) := mul_pos (by norm_num) hm + have hcount : (winCount clauses strategy : ℝ) + + (violatedCount clauses strategy.2 : ℝ) ≤ 3 * (m : ℝ) := by + exact_mod_cast winCount_add_violated_le clauses strategy + rw [success_eq_winCount_div] + apply (div_le_iff₀ hden).mpr + have hidentity : + (1 - ((violatedCount clauses strategy.2 : ℝ) / (m : ℝ)) / 3) * (3 * (m : ℝ)) = + 3 * (m : ℝ) - (violatedCount clauses strategy.2 : ℝ) := by + field_simp [ne_of_gt hm] + rw [hidentity] + linarith + +end +end PerfectCompleteness.SourceGame + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/Target.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/Target.lean new file mode 100644 index 0000000000000000000000000000000000000000..327956206e26e2b6cefbfca5d4a5208ab08ea0f5 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/Target.lean @@ -0,0 +1,52 @@ +import Std +import OAI.Computability.PerfectCompleteness.Model + +namespace OAI + +section + +namespace PerfectCompleteness + +theorem countSatisfied_le_length {l r q : Nat} (a : Fin l → Fin (2 * q)) + (b : Fin r → Fin q) (es : List (Edge l r q)) : + countSatisfied a b es ≤ es.length := by + induction es with + | nil => simp [countSatisfied] + | cons e es ih => + simp only [countSatisfied, List.length_cons] + split <;> omega + +theorem countSatisfied_eq_length_iff {l r q : Nat} (a : Fin l → Fin (2 * q)) + (b : Fin r → Fin q) (es : List (Edge l r q)) : + countSatisfied a b es = es.length ↔ ∀ e ∈ es, e.satisfied a b = true := by + induction es with + | nil => simp [countSatisfied] + | cons e es ih => + have bound := countSatisfied_le_length a b es + cases h : e.satisfied a b <;> simp_all [countSatisfied, Nat.add_comm] + omega + +theorem Instance.edgeCount_positive {q : Nat} (G : Instance q) : + 0 < G.edges.length := by + cases h : G.edges with + | nil => exact False.elim (G.nonempty h) + | cons e es => simp + +def PerfectlyComplete {q : Nat} (G : Instance q) : Prop := + ∃ s : Labeling G, ∀ e ∈ G.edges, e.satisfied s.1 s.2 = true + +structure RationalThreshold where + numerator : Nat + denominator : Nat + positive : 0 < numerator + belowOne : numerator < denominator + +def SoundAt {q : Nat} (d : RationalThreshold) (G : Instance q) : Prop := + ∀ s : Labeling G, + d.denominator * countSatisfied s.1 s.2 G.edges ≤ d.numerator * G.edges.length + +end PerfectCompleteness + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/TargetFinalizeBound.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/TargetFinalizeBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..257dbda8a34206dd9585dcfdf578591bdc059fe0 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/TargetFinalizeBound.lean @@ -0,0 +1,111 @@ +import OAI.Computability.PerfectCompleteness.Machines.TargetFinalizeMachine + +namespace OAI + +section + +namespace PerfectCompleteness.TargetFinalizeBound + +open Turing UniqueGamesTheorem.Foundations.Complexity +open TargetFinalizeMachine + +variable {K Λ A : Type} [DecidableEq K] {stackCount : Nat} + +omit [DecidableEq K] in +private theorem lengthSum_le (chosen : List K) (base : K → List Bool) (B : Nat) + (bounded : ∀ k, (base k).length ≤ B) : + MachineDrainMany.lengthSum chosen base ≤ chosen.length * B := by + induction chosen with + | nil => simp [MachineDrainMany.lengthSum] + | cons k chosen ih => + simp only [MachineDrainMany.lengthSum, List.map_cons, List.sum_cons, + List.length_cons, Nat.add_mul, Nat.one_mul] at * + have hk := bounded k + omega + +theorem header_length (q count : Nat) (body : List Bool) : + (encodeWords [count, count, q, count] ++ body).length = + 3 * (count + 1) + (q + 1) + body.length := by + simp only [encodeWords, List.length_append, encodeWord_length, List.length_nil] + omega + +theorem headerTapes_length_le (q count : Nat) (tape : Fin 4 → K) + (base : K → List Bool) (body : List Bool) (B : Nat) + (bounded : ∀ k, (base k).length ≤ B) (bodyBound : body.length ≤ B) + (countBound : count ≤ B) : + ∀ k, (headerTapes q count tape base body k).length ≤ 4 * B + q + 4 := by + intro k + by_cases output : k = tape 3 + · subst k + simp only [headerTapes, Function.update_self, header_length] + omega + · by_cases accumulator : k = tape 0 + · subst k + simp [headerTapes, bodyTapes, output] + · have hk := bounded k + simp only [headerTapes, bodyTapes, Function.update_of_ne output, + Function.update_of_ne accumulator] + omega + +theorem budget_le (q count : Nat) (enumeration : Fin stackCount ≃ K) (tape : Fin 4 → K) + (base : K → List Bool) (body : List Bool) (B : Nat) + (bounded : ∀ k, (base k).length ≤ B) (bodyBound : body.length ≤ B) + (countBound : count ≤ B) : + budget q count enumeration tape base body ≤ + (15 + stackCount * (q + 9)) * (B + 1) := by + let chosen := MachineDrainMany.workTapes enumeration (tape 3) + have hlength : chosen.length ≤ stackCount := MachineDrainMany.workTapes_length_le _ _ + have hsum := lengthSum_le chosen (headerTapes q count tape base body) (4 * B + q + 4) + (headerTapes_length_le q count tape base body B bounded bodyBound countBound) + have hsum' := hsum.trans (Nat.mul_le_mul_right (4 * B + q + 4) hlength) + have hsmall : 4 * B + q + 5 ≤ (q + 9) * (B + 1) := by + rw [Nat.mul_add, Nat.mul_one, Nat.add_mul] + omega + have hscaled := Nat.mul_le_mul_left stackCount hsmall + have hfirst : body.length + 1 + (6 * (count + 2) + 1) + 1 ≤ 15 * (B + 1) := by + omega + calc + budget q count enumeration tape base body ≤ + 15 * (B + 1) + stackCount * (4 * B + q + 5) := by + unfold budget + dsimp only [chosen] at hsum' hlength + rw [Nat.mul_add stackCount (4 * B + q + 4) 1, Nat.mul_one] + omega + _ ≤ 15 * (B + 1) + stackCount * ((q + 9) * (B + 1)) := Nat.add_le_add_left hscaled _ + _ = _ := by simp only [Nat.add_mul, Nat.mul_assoc] + +def finalizeInTime (q : Nat) (enumeration : Fin stackCount ≃ K) (tape : Fin 4 → K) + (distinct : Function.Injective tape) (initial : A) + (labels : Labels enumeration (tape 3) → Λ) + (program : Λ → TM2.Stmt (Alphabet (K := K)) Λ (State A)) + (atLabels : ∀ l, program (labels l) = instruction q enumeration tape initial labels l) + (base : K → List Bool) (ambient : A) (register : Option Bool) + (count : Nat) (body : List Bool) + (reversed : base (tape 0) = body.reverse) + (countWord : base (tape 1) = encodeWord count) + (scratchEmpty : base (tape 2) = []) (outputEmpty : base (tape 3) = []) + (B : Nat) (bounded : ∀ k, (base k).length ≤ B) : + StateTransition.EvalsToInTime (TM2.step program) + ⟨some (labels .reverse), (ambient, register), base⟩ + (some ⟨none, (initial, none), MachineDrainMany.haltTapes (tape 3) + (encodeWords [count, count, q, count] ++ body)⟩) + ((15 + stackCount * (q + 9)) * (B + 1)) := by + let run := TargetFinalizeMachine.finalizeInTime q enumeration tape distinct initial labels + program atLabels base ambient register count body reversed countWord scratchEmpty outputEmpty + have bodyBound : body.length ≤ B := by simpa only [reversed, List.length_reverse] using bounded (tape 0) + have countBound : count ≤ B := by + have h := bounded (tape 1) + rw [countWord, encodeWord_length] at h + omega + exact { + steps := run.steps + evals_in_steps := run.evals_in_steps + steps_le_m := run.steps_le_m.trans (budget_le q count enumeration tape base body B + bounded bodyBound countBound) + } + +end PerfectCompleteness.TargetFinalizeBound + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/TargetGameLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/TargetGameLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..bf768e501c0a4e9794632fc92ec0ad6b392fcbbc --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/TargetGameLemmas.lean @@ -0,0 +1,602 @@ +import Mathlib.Algebra.BigOperators.Field +import Mathlib.Algebra.BigOperators.Fin +import Mathlib.Algebra.Order.BigOperators.Group.Finset +import Mathlib.Data.Fintype.Fin +import Mathlib.Data.Rat.BigOperators +import Mathlib.Data.Rat.Cast.Order +import Mathlib.Data.Rat.Floor +import Mathlib.Tactic.FieldSimp +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.Positivity +import Mathlib.Tactic.Ring +import OAI.Computability.PerfectCompleteness.Reduction.OccurrenceGame +import OAI.Computability.PerfectCompleteness.Reduction.Value + +namespace OAI + + +namespace PerfectCompleteness +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators + +namespace Instance + +noncomputable def occurrenceGame {q : Nat} (G : Instance q) : + OccurrenceGame (Fin G.edges.length) (Fin G.leftVertices) (Fin G.rightVertices) + (Fin (2 * q)) (Fin q) where + occurrences := + { weight := fun _ => (G.edges.length : ℝ)⁻¹ + nonnegative := fun _ => inv_nonneg.mpr (Nat.cast_nonneg _) + normalized := by + have h : (G.edges.length : ℝ) ≠ 0 := by + exact_mod_cast G.edgeCount_positive.ne' + simp [h] } + left := fun i => G.edges[i].left + right := fun i => G.edges[i].right + accepts := fun i a b => decide (G.edges[i].projection.images[a] = b) + +theorem countSatisfied_eq_sum {l r q : Nat} (a : Fin l → Fin (2 * q)) + (b : Fin r → Fin q) (es : List (Edge l r q)) : + (countSatisfied a b es : ℝ) = + ∑ i : Fin es.length, if es[i].satisfied a b then (1 : ℝ) else 0 := by + induction es with + | nil => simp [countSatisfied] + | cons e es ih => + simp only [List.length_cons, Fin.sum_univ_succ] + cases h : e.satisfied a b <;> simp [countSatisfied, ih, h] + +theorem occurrenceGame_success {q : Nat} (G : Instance q) (s : Labeling G) : + G.occurrenceGame.success s = + (countSatisfied s.1 s.2 G.edges : ℝ) / G.edges.length := by + rw [countSatisfied_eq_sum, div_eq_mul_inv, Finset.sum_mul] + unfold OccurrenceGame.success FiniteDistribution.probability + apply Finset.sum_congr rfl + intro i _ + change (if G.edges[i].satisfied s.1 s.2 then (G.edges.length : ℝ)⁻¹ else 0) = _ + cases h : G.edges[i].satisfied s.1 s.2 <;> simp + +theorem occurrenceGame_value {q : Nat} (G : Instance q) [Nonempty (Fin q)] : + letI : Nonempty (Fin (2 * q)) := ⟨⟨0, by + have hq : 0 < q := Fin.pos_iff_nonempty.mpr (inferInstance : Nonempty (Fin q)) + omega⟩⟩ + G.occurrenceGame.value = G.value := by + have hq : 0 < q := Fin.pos_iff_nonempty.mpr inferInstance + let : Nonempty (Fin (2 * q)) := ⟨⟨0, by omega⟩⟩ + apply le_antisymm + · apply (G.occurrenceGame.value_le_iff _).2 + intro s + rw [G.occurrenceGame_success] + exact G.rate_le_value s + · obtain ⟨s, hs⟩ := G.maxSatisfied_attained hq + have h := G.occurrenceGame.success_le_value s + rw [G.occurrenceGame_success, hs] at h + exact h + +end Instance +end PerfectCompleteness + + + +namespace PerfectCompleteness.WeightRounding + +open scoped BigOperators + +def paperScale (m : Nat) (δ : ℚ) : Nat := ⌈3 * (m : ℚ) / δ⌉₊ + +theorem paperScale_positive {m : Nat} (hm : 0 < m) {δ : ℚ} (hδ : 0 < δ) : + 0 < paperScale m δ := by + have hm' : (0 : ℚ) < m := by exact_mod_cast hm + have h : 1 ≤ paperScale m δ := (Nat.one_le_ceil_iff).2 (by positivity) + omega + +theorem paperScale_error {m : Nat} (hm : 0 < m) {δ : ℚ} (hδ : 0 < δ) : + (m : ℚ) / paperScale m δ ≤ δ / 3 := by + have hK : (0 : ℚ) < paperScale m δ := by + exact_mod_cast paperScale_positive hm hδ + have hceil : 3 * (m : ℚ) / δ ≤ (paperScale m δ : ℚ) := Nat.le_ceil _ + have hprod := (div_le_iff₀ hδ).1 hceil + apply (div_le_div_iff₀ hK (by norm_num : (0 : ℚ) < 3)).2 + nlinarith + +theorem paperScale_lt (m : Nat) {δ : ℚ} (hδ : 0 < δ) : + (paperScale m δ : ℚ) < 3 * (m : ℚ) / δ + 1 := + Nat.ceil_lt_add_one (by positivity) + +theorem paperScale_le_linear (m : Nat) (δ : ℚ) : + paperScale m δ ≤ ⌈(3 : ℚ) / δ⌉₊ * m := by + unfold paperScale + apply Nat.ceil_le.mpr + calc + 3 * (m : ℚ) / δ = ((3 : ℚ) / δ) * m := by ring + _ ≤ (⌈(3 : ℚ) / δ⌉₊ : ℚ) * m := + mul_le_mul_of_nonneg_right (Nat.le_ceil _) (Nat.cast_nonneg m) + _ = ((⌈(3 : ℚ) / δ⌉₊ * m : Nat) : ℚ) := by rw [Nat.cast_mul] + +structure PositiveWeights (m : Nat) where + weight : Fin m → ℚ + positive : ∀ i, 0 < weight i + total : ∑ i, weight i = 1 + +namespace PositiveWeights + +variable {m : Nat} (w : PositiveWeights m) + +include w in +theorem size_positive : 0 < m := by + by_contra h + have hm : m = 0 := by omega + subst m + have ht := w.total + simp at ht + +def floorCopies (K : Nat) (i : Fin m) : Nat := ⌊(K : ℚ) * w.weight i⌋₊ + +def floorTotal (K : Nat) : Nat := ∑ i, w.floorCopies K i + +def remainder (K : Nat) : Nat := K - w.floorTotal K + +def multiplicity (K : Nat) (i : Fin m) : Nat := + w.floorCopies K i + if i.val < w.remainder K then 1 else 0 + +theorem floorCopies_le_scaled (K : Nat) (i : Fin m) : + (w.floorCopies K i : ℚ) ≤ (K : ℚ) * w.weight i := + Nat.floor_le (mul_nonneg (Nat.cast_nonneg K) (w.positive i).le) + +theorem scaled_lt_floorCopies_add_one (K : Nat) (i : Fin m) : + (K : ℚ) * w.weight i < (w.floorCopies K i : ℚ) + 1 := + Nat.lt_floor_add_one _ + +theorem floorTotal_le (K : Nat) : w.floorTotal K ≤ K := by + have h : (w.floorTotal K : ℚ) ≤ K := by + calc + (w.floorTotal K : ℚ) = ∑ i, (w.floorCopies K i : ℚ) := by + simp [floorTotal] + _ ≤ ∑ i, (K : ℚ) * w.weight i := + Finset.sum_le_sum fun i _ => w.floorCopies_le_scaled K i + _ = (K : ℚ) := by rw [← Finset.mul_sum, w.total, mul_one] + exact_mod_cast h + +theorem remainder_lt (K : Nat) : w.remainder K < m := by + have hnonempty : (Finset.univ : Finset (Fin m)).Nonempty := + ⟨⟨0, w.size_positive⟩, Finset.mem_univ _⟩ + have hsum := Finset.sum_lt_sum_of_nonempty hnonempty + (fun i _ => w.scaled_lt_floorCopies_add_one K i) + have h : (K : ℚ) < (w.floorTotal K : ℚ) + m := by + calc + (K : ℚ) = ∑ i, (K : ℚ) * w.weight i := by + rw [← Finset.mul_sum, w.total, mul_one] + _ < ∑ i, ((w.floorCopies K i : ℚ) + 1) := hsum + _ = (w.floorTotal K : ℚ) + m := by + simp [floorTotal, Finset.sum_add_distrib] + have hn : K < w.floorTotal K + m := by exact_mod_cast h + have hfloor := w.floorTotal_le K + unfold remainder + omega + +theorem sum_multiplicity (K : Nat) : ∑ i, w.multiplicity K i = K := by + have hones : (∑ i : Fin m, if i.val < w.remainder K then (1 : Nat) else 0) = + w.remainder K := by + rw [Finset.sum_boole, Fin.card_filter_val_lt, Nat.min_eq_right (w.remainder_lt K).le] + rfl + simp only [multiplicity, Finset.sum_add_distrib, hones] + change w.floorTotal K + w.remainder K = K + have hfloor := w.floorTotal_le K + unfold remainder + omega + +theorem multiplicity_error_scaled (K : Nat) (i : Fin m) : + |(w.multiplicity K i : ℚ) - (K : ℚ) * w.weight i| ≤ 1 := by + have hlo := w.floorCopies_le_scaled K i + have hhi := w.scaled_lt_floorCopies_add_one K i + apply abs_le.mpr + by_cases h : i.val < w.remainder K + · simp only [multiplicity, ite_eq_left h, Nat.cast_add, Nat.cast_one] + constructor <;> linarith + · simp only [multiplicity, ite_eq_right h, Nat.add_zero] + constructor <;> linarith + +theorem multiplicity_error (K : Nat) (hK : 0 < K) (i : Fin m) : + |(w.multiplicity K i : ℚ) / K - w.weight i| ≤ 1 / (K : ℚ) := by + have hKq : (0 : ℚ) < K := by exact_mod_cast hK + calc + |(w.multiplicity K i : ℚ) / K - w.weight i| = + |((w.multiplicity K i : ℚ) - (K : ℚ) * w.weight i) / K| := by + congr 1 + field_simp [ne_of_gt hKq] + _ = |(w.multiplicity K i : ℚ) - (K : ℚ) * w.weight i| / K := by + rw [abs_div, abs_of_pos hKq] + _ ≤ 1 / (K : ℚ) := + div_le_div_of_nonneg_right (w.multiplicity_error_scaled K i) hKq.le + +theorem sum_rounded_weights (K : Nat) (hK : 0 < K) : + (∑ i, (w.multiplicity K i : ℚ) / K) = 1 := by + rw [← Finset.sum_div, ← Nat.cast_sum, w.sum_multiplicity] + exact div_self (Nat.cast_ne_zero.mpr (ne_of_gt hK)) + +theorem l1_error (K : Nat) (hK : 0 < K) : + (∑ i, |(w.multiplicity K i : ℚ) / K - w.weight i|) ≤ (m : ℚ) / K := by + calc + _ ≤ ∑ _i : Fin m, (1 : ℚ) / K := + Finset.sum_le_sum fun i _ => w.multiplicity_error K hK i + _ = (m : ℚ) / K := by simp [div_eq_mul_inv] + +def copies (K : Nat) : List (Fin m) := + (List.ofFn fun i => List.replicate (w.multiplicity K i) i).flatten + +theorem copies_length (K : Nat) : (w.copies K).length = K := by + simpa [copies, List.map_ofFn, List.sum_ofFn] using w.sum_multiplicity K + +theorem copies_nonempty (K : Nat) (hK : 0 < K) : w.copies K ≠ [] := by + intro h + have hlen := w.copies_length K + rw [h] at hlen + simp at hlen + omega + +theorem copies_positive_support (K : Nat) (i : Fin m) (_hi : i ∈ w.copies K) : + 0 < w.weight i := w.positive i + +theorem copies_filter_length (K : Nat) (keep : Fin m → Bool) : + ((w.copies K).filter keep).length = + ∑ i, if keep i then w.multiplicity K i else 0 := by + simp only [copies, List.filter_flatten, List.length_flatten, List.map_ofFn, + List.sum_ofFn] + apply Finset.sum_congr rfl + intro i _ + cases h : keep i <;> simp [h] + +def weightedAcceptance (keep : Fin m → Bool) : ℚ := + ∑ i, if keep i then w.weight i else 0 + +def unweightedAcceptance (K : Nat) (keep : Fin m → Bool) : ℚ := + (((w.copies K).filter keep).length : ℚ) / (w.copies K).length + +theorem unweightedAcceptance_eq (K : Nat) (keep : Fin m → Bool) : + w.unweightedAcceptance K keep = + ∑ i, if keep i then (w.multiplicity K i : ℚ) / K else 0 := by + rw [unweightedAcceptance, w.copies_length, w.copies_filter_length] + rw [Nat.cast_sum, Finset.sum_div] + apply Finset.sum_congr rfl + intro i _ + cases keep i <;> simp + +theorem acceptance_error (K : Nat) (hK : 0 < K) (keep : Fin m → Bool) : + |w.unweightedAcceptance K keep - w.weightedAcceptance keep| ≤ (m : ℚ) / K := by + rw [w.unweightedAcceptance_eq, weightedAcceptance, ← Finset.sum_sub_distrib] + calc + _ ≤ ∑ i, |(if keep i then (w.multiplicity K i : ℚ) / K else 0) - + (if keep i then w.weight i else 0)| := Finset.abs_sum_le_sum_abs _ _ + _ ≤ ∑ i, |(w.multiplicity K i : ℚ) / K - w.weight i| := by + apply Finset.sum_le_sum + intro i _ + cases keep i <;> simp + _ ≤ (m : ℚ) / K := w.l1_error K hK + +theorem perfectCompleteness_preserved (K : Nat) (hK : 0 < K) + (keep : Fin m → Bool) (hkeep : ∀ i, keep i = true) : + w.unweightedAcceptance K keep = 1 := by + rw [w.unweightedAcceptance_eq] + simpa only [hkeep, ite_true] using w.sum_rounded_weights K hK + +def output {α : Type*} (K : Nat) (entries : Fin m → α) : List α := + (w.copies K).map entries + +theorem output_length {α : Type*} (K : Nat) (entries : Fin m → α) : + (w.output K entries).length = K := by + simp [output, w.copies_length] + +theorem output_nonempty {α : Type*} (K : Nat) (hK : 0 < K) + (entries : Fin m → α) : w.output K entries ≠ [] := by + intro h + change (w.copies K).map entries = [] at h + exact w.copies_nonempty K hK (List.map_eq_nil_iff.mp h) + +theorem output_support {α : Type*} (K : Nat) (entries : Fin m → α) + (e : α) (he : e ∈ w.output K entries) : + ∃ i : Fin m, entries i = e ∧ 0 < w.weight i := by + obtain ⟨i, _, hi⟩ := List.mem_map.mp he + exact ⟨i, hi, w.positive i⟩ + +theorem output_acceptance_error {α : Type*} (K : Nat) (hK : 0 < K) + (entries : Fin m → α) (accepts : α → Bool) : + |(((w.output K entries).filter accepts).length : ℚ) / (w.output K entries).length - + (∑ i, if accepts (entries i) then w.weight i else 0)| ≤ (m : ℚ) / K := by + simpa only [unweightedAcceptance, weightedAcceptance, output, List.filter_map, + List.length_map, Function.comp_def] using + w.acceptance_error K hK (fun i => accepts (entries i)) + +def paperOutput {α : Type*} (δ : ℚ) (entries : Fin m → α) : List α := + w.output (paperScale m δ) entries + +theorem paperOutput_length {α : Type*} (δ : ℚ) (entries : Fin m → α) : + (w.paperOutput δ entries).length = paperScale m δ := + w.output_length _ entries + +theorem paperOutput_nonempty {α : Type*} {δ : ℚ} (hδ : 0 < δ) + (entries : Fin m → α) : w.paperOutput δ entries ≠ [] := + w.output_nonempty _ (paperScale_positive w.size_positive hδ) entries + +theorem paperOutput_length_lt {α : Type*} {δ : ℚ} (hδ : 0 < δ) + (entries : Fin m → α) : + ((w.paperOutput δ entries).length : ℚ) < 3 * (m : ℚ) / δ + 1 := by + rw [w.paperOutput_length] + exact paperScale_lt m hδ + +theorem paperOutput_length_le_linear {α : Type*} (δ : ℚ) + (entries : Fin m → α) : + (w.paperOutput δ entries).length ≤ ⌈(3 : ℚ) / δ⌉₊ * m := by + rw [w.paperOutput_length] + exact paperScale_le_linear m δ + +theorem paperOutput_acceptance_error {α : Type*} {δ : ℚ} (hδ : 0 < δ) + (entries : Fin m → α) (accepts : α → Bool) : + |(((w.paperOutput δ entries).filter accepts).length : ℚ) / + (w.paperOutput δ entries).length - + (∑ i, if accepts (entries i) then w.weight i else 0)| ≤ δ / 3 := + (w.output_acceptance_error _ (paperScale_positive w.size_positive hδ) entries accepts).trans + (paperScale_error w.size_positive hδ) + +theorem paperOutput_perfectCompleteness {α : Type*} {δ : ℚ} (hδ : 0 < δ) + (entries : Fin m → α) (accepts : α → Bool) + (haccepts : ∀ i, accepts (entries i) = true) : + (((w.paperOutput δ entries).filter accepts).length : ℚ) / + (w.paperOutput δ entries).length = 1 := by + simpa only [paperOutput, output, List.filter_map, List.length_map, Function.comp_def, + unweightedAcceptance] using + w.perfectCompleteness_preserved _ (paperScale_positive w.size_positive hδ) + (fun i => accepts (entries i)) haccepts + +end PositiveWeights +end PerfectCompleteness.WeightRounding + + + +namespace PerfectCompleteness.RoundedTarget + +open scoped BigOperators +open WeightRounding +open UniqueGamesTheorem.Foundations.Games + +variable {m l r q : Nat} + +abbrev EndpointLabeling (l r q : Nat) := + (Fin l → Fin (2 * q)) × (Fin r → Fin q) + +def construct (w : PositiveWeights m) (entries : Fin m → Edge l r q) + (K : Nat) (hK : 0 < K) : Instance q where + leftVertices := l + rightVertices := r + edges := w.output K entries + nonempty := w.output_nonempty K hK entries + +theorem edge_length (w : PositiveWeights m) (entries : Fin m → Edge l r q) + (K : Nat) (hK : 0 < K) : (construct w entries K hK).edges.length = K := + w.output_length K entries + +theorem edge_support (w : PositiveWeights m) (entries : Fin m → Edge l r q) + (K : Nat) (hK : 0 < K) (e : Edge l r q) + (he : e ∈ (construct w entries K hK).edges) : + ∃ i : Fin m, entries i = e ∧ 0 < w.weight i := + w.output_support K entries e he + +theorem countSatisfied_eq_filter (a : Fin l → Fin (2 * q)) (b : Fin r → Fin q) + (es : List (Edge l r q)) : + countSatisfied a b es = (es.filter fun e => e.satisfied a b).length := by + induction es with + | nil => simp [countSatisfied] + | cons e es ih => + cases h : e.satisfied a b <;> simp [countSatisfied, h, ih, Nat.add_comm] + +theorem count_eq (w : PositiveWeights m) (entries : Fin m → Edge l r q) + (K : Nat) (hK : 0 < K) (a : Fin l → Fin (2 * q)) (b : Fin r → Fin q) : + countSatisfied a b (construct w entries K hK).edges = + ∑ i, if (entries i).satisfied a b then w.multiplicity K i else 0 := by + change countSatisfied a b (w.output K entries) = _ + rw [countSatisfied_eq_filter] + simpa only [PositiveWeights.output, List.filter_map, List.length_map, + Function.comp_def] using w.copies_filter_length K (fun i => (entries i).satisfied a b) + +def weightedSuccess (w : PositiveWeights m) (entries : Fin m → Edge l r q) + (a : Fin l → Fin (2 * q)) (b : Fin r → Fin q) : ℚ := + w.weightedAcceptance fun i => (entries i).satisfied a b + +theorem rate_eq (w : PositiveWeights m) (entries : Fin m → Edge l r q) + (K : Nat) (hK : 0 < K) (a : Fin l → Fin (2 * q)) (b : Fin r → Fin q) : + (countSatisfied a b (construct w entries K hK).edges : ℚ) / + (construct w entries K hK).edges.length = + w.unweightedAcceptance K (fun i => (entries i).satisfied a b) := by + change (countSatisfied a b (w.output K entries) : ℚ) / (w.output K entries).length = _ + rw [countSatisfied_eq_filter] + simp only [PositiveWeights.output, PositiveWeights.unweightedAcceptance, + List.filter_map, List.length_map, Function.comp_def] + +theorem rate_error (w : PositiveWeights m) (entries : Fin m → Edge l r q) + (K : Nat) (hK : 0 < K) (a : Fin l → Fin (2 * q)) (b : Fin r → Fin q) : + |(countSatisfied a b (construct w entries K hK).edges : ℚ) / + (construct w entries K hK).edges.length - weightedSuccess w entries a b| ≤ + (m : ℚ) / K := by + rw [rate_eq] + exact w.acceptance_error K hK (fun i => (entries i).satisfied a b) + +theorem real_rate_error (w : PositiveWeights m) (entries : Fin m → Edge l r q) + (K : Nat) (hK : 0 < K) (a : Fin l → Fin (2 * q)) (b : Fin r → Fin q) : + |(countSatisfied a b (construct w entries K hK).edges : ℝ) / + (construct w entries K hK).edges.length - (weightedSuccess w entries a b : ℝ)| ≤ + (m : ℝ) / K := by + have h := rate_error w entries K hK a b + change |(countSatisfied a b (w.output K entries) : ℚ) / + (w.output K entries).length - weightedSuccess w entries a b| ≤ (m : ℚ) / K at h + change |(countSatisfied a b (w.output K entries) : ℝ) / + (w.output K entries).length - (weightedSuccess w entries a b : ℝ)| ≤ (m : ℝ) / K + have hc := (Rat.cast_le (K := ℝ)).2 h + simpa only [Rat.cast_abs, Rat.cast_sub, Rat.cast_div, Rat.cast_natCast] using hc + +noncomputable def weightedGame (w : PositiveWeights m) (entries : Fin m → Edge l r q) : + OccurrenceGame (Fin m) (Fin l) (Fin r) (Fin (2 * q)) (Fin q) where + occurrences := + { weight := fun i => (w.weight i : ℝ) + nonnegative := fun i => by exact_mod_cast (w.positive i).le + normalized := by exact_mod_cast w.total } + left := fun i => (entries i).left + right := fun i => (entries i).right + accepts := fun i a b => decide ((entries i).projection.images[a] = b) + +theorem weightedGame_success (w : PositiveWeights m) (entries : Fin m → Edge l r q) + (s : EndpointLabeling l r q) : + (weightedGame w entries).success s = (weightedSuccess w entries s.1 s.2 : ℝ) := by + change (∑ i, if (entries i).satisfied s.1 s.2 then (w.weight i : ℝ) else 0) = + ((∑ i, if (entries i).satisfied s.1 s.2 then w.weight i else 0 : ℚ) : ℝ) + rw [Rat.cast_sum] + apply Finset.sum_congr rfl + intro i _ + cases h : (entries i).satisfied s.1 s.2 <;> simp + +noncomputable def weightedValue (w : PositiveWeights m) (entries : Fin m → Edge l r q) + (hq : 0 < q) : ℝ := by + letI : Nonempty (Fin q) := ⟨⟨0, hq⟩⟩ + letI : Nonempty (Fin (2 * q)) := ⟨⟨0, by omega⟩⟩ + exact (weightedGame w entries).value + +theorem weightedSuccess_le_value (w : PositiveWeights m) (entries : Fin m → Edge l r q) + (hq : 0 < q) (a : Fin l → Fin (2 * q)) (b : Fin r → Fin q) : + (weightedSuccess w entries a b : ℝ) ≤ weightedValue w entries hq := by + let : Nonempty (Fin q) := ⟨⟨0, hq⟩⟩ + let : Nonempty (Fin (2 * q)) := ⟨⟨0, by omega⟩⟩ + rw [← weightedGame_success w entries (a, b)] + exact (weightedGame w entries).success_le_value (a, b) + +theorem weightedValue_attained (w : PositiveWeights m) (entries : Fin m → Edge l r q) + (hq : 0 < q) : + ∃ s : EndpointLabeling l r q, + (weightedSuccess w entries s.1 s.2 : ℝ) = weightedValue w entries hq := by + let : Nonempty (Fin q) := ⟨⟨0, hq⟩⟩ + let : Nonempty (Fin (2 * q)) := ⟨⟨0, by omega⟩⟩ + obtain ⟨s, hs⟩ := (weightedGame w entries).exists_optimal_strategy + rw [weightedGame_success] at hs + exact ⟨s, hs⟩ + +theorem completeness_preserved (w : PositiveWeights m) (entries : Fin m → Edge l r q) + (K : Nat) (hK : 0 < K) + (hcomplete : ∃ s : EndpointLabeling l r q, + ∀ i, (entries i).satisfied s.1 s.2 = true) : + PerfectlyComplete (construct w entries K hK) := by + obtain ⟨s, hs⟩ := hcomplete + refine ⟨s, ?_⟩ + intro e he + obtain ⟨i, hi, _⟩ := edge_support w entries K hK e he + rw [← hi] + exact hs i + +theorem complete_value_eq_one (w : PositiveWeights m) (entries : Fin m → Edge l r q) + (K : Nat) (hK : 0 < K) (hq : 0 < q) + (hcomplete : ∃ s : EndpointLabeling l r q, + ∀ i, (entries i).satisfied s.1 s.2 = true) : + (construct w entries K hK).value = 1 := + ((construct w entries K hK).perfectlyComplete_iff_value_eq_one hq).1 + (completeness_preserved w entries K hK hcomplete) + +theorem value_le (w : PositiveWeights m) (entries : Fin m → Edge l r q) + (K : Nat) (hK : 0 < K) (hq : 0 < q) (bound : ℝ) + (hsound : ∀ a : Fin l → Fin (2 * q), ∀ b : Fin r → Fin q, + (weightedSuccess w entries a b : ℝ) ≤ bound) : + (construct w entries K hK).value ≤ bound + (m : ℝ) / K := by + obtain ⟨s, hs⟩ := (construct w entries K hK).maxSatisfied_attained hq + have he := (abs_le.mp (real_rate_error w entries K hK s.1 s.2)).2 + have hw := hsound s.1 s.2 + unfold Instance.value + rw [← hs] + change (countSatisfied s.1 s.2 (w.output K entries) : ℝ) / + (w.output K entries).length ≤ bound + (m : ℝ) / K + change (countSatisfied s.1 s.2 (w.output K entries) : ℝ) / + (w.output K entries).length - (weightedSuccess w entries s.1 s.2 : ℝ) ≤ + (m : ℝ) / K at he + calc + _ = ((countSatisfied s.1 s.2 (w.output K entries) : ℝ) / + (w.output K entries).length - (weightedSuccess w entries s.1 s.2 : ℝ)) + + (weightedSuccess w entries s.1 s.2 : ℝ) := by ring + _ ≤ (m : ℝ) / K + bound := add_le_add he hw + _ = bound + (m : ℝ) / K := add_comm _ _ + +theorem value_distance (w : PositiveWeights m) (entries : Fin m → Edge l r q) + (K : Nat) (hK : 0 < K) (hq : 0 < q) : + |(construct w entries K hK).value - weightedValue w entries hq| ≤ (m : ℝ) / K := by + have hu := value_le w entries K hK hq (weightedValue w entries hq) + (weightedSuccess_le_value w entries hq) + obtain ⟨s, hs⟩ := weightedValue_attained w entries hq + have he := (abs_le.mp (real_rate_error w entries K hK s.1 s.2)).1 + rw [hs] at he + have hl := (construct w entries K hK).rate_le_value s + change -((m : ℝ) / K) ≤ (countSatisfied s.1 s.2 (w.output K entries) : ℝ) / + (w.output K entries).length - weightedValue w entries hq at he + change (countSatisfied s.1 s.2 (w.output K entries) : ℝ) / + (w.output K entries).length ≤ (construct w entries K hK).value at hl + apply abs_le.mpr + constructor + · exact he.trans (sub_le_sub hl (le_refl (weightedValue w entries hq))) + · calc + _ ≤ (weightedValue w entries hq + (m : ℝ) / K) - weightedValue w entries hq := + sub_le_sub hu (le_refl (weightedValue w entries hq)) + _ = (m : ℝ) / K := by ring + +theorem soundAt_of_weighted_bound (w : PositiveWeights m) (entries : Fin m → Edge l r q) + (K : Nat) (hK : 0 < K) (hq : 0 < q) (d : RationalThreshold) (bound : ℝ) + (hsound : ∀ a : Fin l → Fin (2 * q), ∀ b : Fin r → Fin q, + (weightedSuccess w entries a b : ℝ) ≤ bound) + (hbudget : bound + (m : ℝ) / K ≤ (d.numerator : ℝ) / d.denominator) : + SoundAt d (construct w entries K hK) := + ((construct w entries K hK).soundAt_iff_value_le hq d).2 + ((value_le w entries K hK hq bound hsound).trans hbudget) + +def paper (w : PositiveWeights m) (entries : Fin m → Edge l r q) + (δ : ℚ) (hδ : 0 < δ) : Instance q := + construct w entries (paperScale m δ) (paperScale_positive w.size_positive hδ) + +theorem paper_edge_length (w : PositiveWeights m) (entries : Fin m → Edge l r q) + (δ : ℚ) (hδ : 0 < δ) : (paper w entries δ hδ).edges.length = paperScale m δ := + edge_length w entries _ _ + +theorem paper_edge_length_le_linear (w : PositiveWeights m) (entries : Fin m → Edge l r q) + (δ : ℚ) (hδ : 0 < δ) : + (paper w entries δ hδ).edges.length ≤ ⌈(3 : ℚ) / δ⌉₊ * m := by + rw [paper_edge_length] + exact paperScale_le_linear m δ + +theorem paper_value_distance (w : PositiveWeights m) (entries : Fin m → Edge l r q) + (δ : ℚ) (hδ : 0 < δ) (hq : 0 < q) : + |(paper w entries δ hδ).value - weightedValue w entries hq| ≤ (δ : ℝ) / 3 := by + have hbudget : (m : ℝ) / paperScale m δ ≤ (δ : ℝ) / 3 := by + have h := (Rat.cast_le (K := ℝ)).2 (paperScale_error w.size_positive hδ) + simpa only [Rat.cast_div, Rat.cast_natCast, Rat.cast_ofNat] using h + exact (value_distance w entries _ (paperScale_positive w.size_positive hδ) hq).trans hbudget + +theorem paper_value_le (w : PositiveWeights m) (entries : Fin m → Edge l r q) + (δ : ℚ) (hδ : 0 < δ) (hq : 0 < q) (bound : ℝ) + (hsound : ∀ a : Fin l → Fin (2 * q), ∀ b : Fin r → Fin q, + (weightedSuccess w entries a b : ℝ) ≤ bound) : + (paper w entries δ hδ).value ≤ bound + (δ : ℝ) / 3 := by + have hbudget : (m : ℝ) / paperScale m δ ≤ (δ : ℝ) / 3 := by + have h := (Rat.cast_le (K := ℝ)).2 (paperScale_error w.size_positive hδ) + simpa only [Rat.cast_div, Rat.cast_natCast, Rat.cast_ofNat] using h + exact (value_le w entries _ (paperScale_positive w.size_positive hδ) hq bound hsound).trans + (add_le_add (le_refl bound) hbudget) + +theorem paper_soundAt_of_weighted_bound (w : PositiveWeights m) + (entries : Fin m → Edge l r q) (δ : ℚ) (hδ : 0 < δ) (hq : 0 < q) + (d : RationalThreshold) (bound : ℝ) + (hsound : ∀ a : Fin l → Fin (2 * q), ∀ b : Fin r → Fin q, + (weightedSuccess w entries a b : ℝ) ≤ bound) + (hbudget : bound + (δ : ℝ) / 3 ≤ (d.numerator : ℝ) / d.denominator) : + SoundAt d (paper w entries δ hδ) := + ((paper w entries δ hδ).soundAt_iff_value_le hq d).2 + ((paper_value_le w entries δ hδ hq bound hsound).trans hbudget) + +theorem paper_complete_value_eq_one (w : PositiveWeights m) (entries : Fin m → Edge l r q) + (δ : ℚ) (hδ : 0 < δ) (hq : 0 < q) + (hcomplete : ∃ s : EndpointLabeling l r q, + ∀ i, (entries i).satisfied s.1 s.2 = true) : + (paper w entries δ hδ).value = 1 := + complete_value_eq_one w entries _ (paperScale_positive w.size_positive hδ) hq hcomplete + +end PerfectCompleteness.RoundedTarget + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Reduction/Value.lean b/lean/OAI/Computability/PerfectCompleteness/Reduction/Value.lean new file mode 100644 index 0000000000000000000000000000000000000000..b31a0cdedfbfb4decb78551ddf9a13e9214b98ef --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Reduction/Value.lean @@ -0,0 +1,95 @@ +import Mathlib.Data.Finset.Lattice.Fold +import Mathlib.Data.Fintype.Pi +import Mathlib.Data.Fintype.Prod +import Mathlib.Basic.Real.Basic +import Mathlib.Tactic.NormNum +import OAI.Computability.PerfectCompleteness.Model +import OAI.Computability.PerfectCompleteness.Reduction.Target + +namespace OAI + +section + +namespace PerfectCompleteness + +namespace Instance + +theorem countSatisfied_le_maxSatisfied {q : Nat} (G : Instance q) (s : Labeling G) : + countSatisfied s.1 s.2 G.edges ≤ G.maxSatisfied := by + exact Finset.le_sup (f := fun s : Labeling G => countSatisfied s.1 s.2 G.edges) + (Finset.mem_univ s) + +theorem maxSatisfied_le_length {q : Nat} (G : Instance q) : + G.maxSatisfied ≤ G.edges.length := by + apply Finset.sup_le + intro s _ + exact countSatisfied_le_length s.1 s.2 G.edges + +theorem maxSatisfied_attained {q : Nat} (G : Instance q) (hq : 0 < q) : + ∃ s : Labeling G, countSatisfied s.1 s.2 G.edges = G.maxSatisfied := by + have hne : (Finset.univ : Finset (Labeling G)).Nonempty := + ⟨(fun _ => ⟨0, by omega⟩, fun _ => ⟨0, hq⟩), Finset.mem_univ _⟩ + obtain ⟨s, _, h⟩ := Finset.exists_mem_eq_sup Finset.univ hne + (fun s : Labeling G => countSatisfied s.1 s.2 G.edges) + exact ⟨s, h.symm⟩ + +theorem value_nonneg {q : Nat} (G : Instance q) : 0 ≤ G.value := + div_nonneg (Nat.cast_nonneg _) (Nat.cast_nonneg _) + +theorem value_le_one {q : Nat} (G : Instance q) : G.value ≤ 1 := by + have hlen : (0 : ℝ) < G.edges.length := by exact_mod_cast G.edgeCount_positive + rw [value, div_le_iff₀ hlen, one_mul] + exact_mod_cast G.maxSatisfied_le_length + +theorem rate_le_value {q : Nat} (G : Instance q) (s : Labeling G) : + (countSatisfied s.1 s.2 G.edges : ℝ) / G.edges.length ≤ G.value := by + apply div_le_div_of_nonneg_right + · exact_mod_cast G.countSatisfied_le_maxSatisfied s + · exact Nat.cast_nonneg _ + +theorem perfectlyComplete_iff_value_eq_one {q : Nat} (G : Instance q) (hq : 0 < q) : + PerfectlyComplete G ↔ G.value = 1 := by + have hlen : (0 : ℝ) < G.edges.length := by exact_mod_cast G.edgeCount_positive + constructor + · rintro ⟨s, hs⟩ + have hc := (countSatisfied_eq_length_iff s.1 s.2 G.edges).2 hs + have hm : G.maxSatisfied = G.edges.length := + le_antisymm G.maxSatisfied_le_length (hc ▸ G.countSatisfied_le_maxSatisfied s) + simp [value, hm, ne_of_gt hlen] + · intro hv + obtain ⟨s, hs⟩ := G.maxSatisfied_attained hq + have hm : G.maxSatisfied = G.edges.length := by + have hreal : (G.maxSatisfied : ℝ) = G.edges.length := by + have := (div_eq_one_iff_eq (ne_of_gt hlen)).1 hv + exact this + exact_mod_cast hreal + exact ⟨s, (countSatisfied_eq_length_iff s.1 s.2 G.edges).1 (hs.trans hm)⟩ + +theorem soundAt_iff_value_le {q : Nat} (G : Instance q) (hq : 0 < q) + (d : RationalThreshold) : + SoundAt d G ↔ G.value ≤ (d.numerator : ℝ) / d.denominator := by + have hlen : (0 : ℝ) < G.edges.length := by exact_mod_cast G.edgeCount_positive + have hd : (0 : ℝ) < d.denominator := by + exact_mod_cast (lt_trans d.positive d.belowOne) + have hrat : ∀ s : Labeling G, + d.denominator * countSatisfied s.1 s.2 G.edges ≤ d.numerator * G.edges.length ↔ + (countSatisfied s.1 s.2 G.edges : ℝ) / G.edges.length ≤ + (d.numerator : ℝ) / d.denominator := by + intro s + rw [div_le_div_iff₀ hlen hd] + norm_cast + rw [Nat.mul_comm (countSatisfied _ _ _) d.denominator] + constructor + · intro h + obtain ⟨s, hs⟩ := G.maxSatisfied_attained hq + have := (hrat s).1 (h s) + simpa [value, hs] using this + · intro h s + exact (hrat s).2 ((G.rate_le_value s).trans h) + +end Instance +end PerfectCompleteness + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Repetition/AmplifiedCleanRateLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Repetition/AmplifiedCleanRateLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..abc61803f63938fb6de68b2c28c6179f555a95c4 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Repetition/AmplifiedCleanRateLemmas.lean @@ -0,0 +1,135 @@ +import OAI.Computability.PerfectCompleteness.Reduction.OddListGame +import OAI.Computability.PerfectCompleteness.Repetition.CutChildCleanLawLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.ProjectedCleanRate + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games +open RecursiveSpaces ProjectedCardinality CleanTreeFactors UniformCleanSources + +noncomputable section + +section + +variable {v m s L cube : Nat} [NeZero m] [NeZero s] + (clauses : Fin m → SourceClause.NormalizedClause v) (γ : ℚ) + (hγ : 0 < γ) (hγ1 : γ ≤ 1) + {R D : Fin (cube ^ 3) → Type*} + [∀ i, Fintype (R i)] [∀ i, DecidableEq (R i)] + [∀ i, Fintype (D i)] [∀ i, DecidableEq (D i)] + (branch : Nat → Nat) (height calls : Nat) (rows : Nat → Nat) + +variable (ids : (i : Fin (cube ^ 3)) → + SourceOddLists.Occurrences m (SourceOddLists.repetitionLength γ s hγ hγ1) × R i → Slots branch height → Fin (SourceOddLists.repetitionLength γ s hγ hγ1) → Nat) + +local notation "Ωsource" => Factors branch height (SourceOddLists.repetitionLength γ s hγ hγ1) calls rows ids +local notation "zsource" => zeros branch height (SourceOddLists.repetitionLength γ s hγ hγ1) calls rows ids + +omit [∀ index, DecidableEq (D index)] in +theorem amplified_source_bound (hcube : 0 < cube) + (gap : SourceAmplification.ClauseGap clauses γ) + (hL : 0 < L) (alphabet : SourceOddLists.alphabetLog s (SourceOddLists.repetitionLength γ s hγ hγ1) ≤ L) + (ν : (i : Fin (cube ^ 3)) → FiniteDistribution (R i)) + (nonprojected : (i : Fin (cube ^ 3)) → + SourceOddLists.Occurrences m (SourceOddLists.repetitionLength γ s hγ hγ1) × R i → FiniteDistribution (D i)) + (event : UniformCleanSoundness.Sample (D := D) Ωsource → Bool) + (strategies : (record : UniformCleanSoundness.FullRecord (D := D) Ωsource) → + Strategy (CleanIndices Ωsource record → Fin (SourceOddLists.repetitionLength γ s hγ hγ1) → Fin m) + (CleanIndices Ωsource record → Fin (SourceOddLists.repetitionLength γ s hγ hγ1) → Fin v) + (CleanIndices Ωsource record → OddLists.OddList s (SourceOddLists.LeftLabels (SourceOddLists.repetitionLength γ s hγ hγ1))) + (CleanIndices Ωsource record → OddLists.OddList s (SourceOddLists.RightLabels (SourceOddLists.repetitionLength γ s hγ hγ1)))) + (inclusion : ∀ record x, recordEvent (D := D) Ωsource zsource record x = true → + event x = true → + (IndexedRepetition.game (SourceOddLists.game s clauses (SourceOddLists.repetitionLength γ s hγ hγ1)) + (CleanIndices Ωsource record)).wins (strategies record) + (fun i => (x i.1).1) = true) : + (childrenLaw Ωsource (fun _ => SourceOddLists.tupleLaw m (SourceOddLists.repetitionLength γ s hγ hγ1)) ν + (fun _ => projectionFlag cube hcube) nonprojected).probability event ≤ + (1 - coefficient L branch height (SourceOddLists.repetitionLength γ s hγ hγ1) calls rows / (cube : ℝ) ^ 2) ^ (cube ^ 3) := by + exact bound_from_repetition branch height (SourceOddLists.repetitionLength γ s hγ hγ1) calls rows ids hcube + (SourceOddLists.game s clauses (SourceOddLists.repetitionLength γ s hγ hγ1)) + (SourceOddLists.repetition_halfRate clauses γ hγ hγ1 gap hL alphabet) + ν nonprojected event strategies inclusion + +end + +end +end PerfectCompleteness.ProjectedCleanRate + +end + +section + +namespace PerfectCompleteness.ProjectedCleanSoundness + +open scoped BigOperators +open UniqueGamesTheorem.Foundations.Games +open ProjectedCardinality ProjectedCleanLaw UniformCleanSources UniformCleanSoundness +open OddLists + +noncomputable section + +attribute [local instance] Classical.propDecidable + +variable {I E : Type*} [Fintype I] [DecidableEq I] [Fintype E] [DecidableEq E] + {R J D : I → Type*} + [∀ i, Fintype (R i)] [∀ i, Fintype (J i)] [∀ i, Fintype (D i)] + [∀ i, DecidableEq (R i)] [∀ i, DecidableEq (J i)] [∀ i, DecidableEq (D i)] + (branch : I → Nat → Nat) (t : I → Nat) + (height : (i : I) → J i → Nat) (square : (i : I) → J i → Bool) + (ids : (i : I) → (E × R i) → (j : J i) → + RecursiveSpaces.Slots (branch i) (height i j) → Fin (t i) → Nat) + +local notation "Ωtree" => treeFactors branch t height square ids +local notation "ztree" => treeZeros branch t height square ids + +variable {Q₁ Q₂ A₁ A₂ : Type*} + [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂] + [DecidableEq Q₁] [DecidableEq Q₂] [DecidableEq A₁] [DecidableEq A₂] + [Nonempty A₁] [Nonempty A₂] + +omit [∀ index, DecidableEq (D index)] in +theorem odd_list_bound {s L : Nat} [NeZero s] + (μ : FiniteDistribution E) (left : E → Q₁) (right : E → Q₂) + (projection : E → A₁ → A₂) + (determined : (OddListGame.base μ left right projection).EndpointDetermined) + (gap : (s : ℝ) ^ 2 * (OddListGame.base μ left right projection).value ≤ 1 / 2) + (hL : 0 < L) + (alphabet : UniqueGamesTheorem.Foundations.Repetition.logTwo + ((Fintype.card (OddList s A₁) : ℝ) * (Fintype.card (OddList s A₂) : ℝ)) ≤ L) + (ν : (i : I) → FiniteDistribution (R i)) + (flag : (i : I) → FiniteDistribution Bool) + (nonprojected : (i : I) → E × R i → FiniteDistribution (D i)) + (event : Sample (D := D) Ωtree → Bool) + (strategies : (record : FullRecord (D := D) Ωtree) → + Strategy (CleanIndices Ωtree record → Q₁) (CleanIndices Ωtree record → Q₂) + (CleanIndices Ωtree record → OddList s A₁) + (CleanIndices Ωtree record → OddList s A₂)) + (inclusion : ∀ record x, recordEvent (D := D) Ωtree ztree record x = true → + event x = true → + (IndexedRepetition.game (OddListGame.game s μ left right projection) + (CleanIndices Ωtree record)).wins (strategies record) + (fun i => (x i.1).1) = true) : + (childrenLaw Ωtree (fun _ => μ) ν flag nonprojected).probability event ≤ + ∏ i : I, (1 - (1 - (RepetitionRate.halfRate L : ℝ)) * + ((flag i).weight true * ∏ j : J i, + 1 / (shapeCardinality (branch i) (t i) (height i) (square i) j : ℝ))) := by + apply source_soundness Ωtree (OddListGame.game s μ left right projection) + ν flag nonprojected ztree + (fun i => shapeCardinality (branch i) (t i) (height i) (square i)) _ + event (RepetitionRate.halfRate L : ℝ) _ strategies inclusion + · intro i e j + exact factor_card_eq (square i j) (ids i e j) (fun _ _ => 0) + · intro n + exact OddListGame.repetition_halfRate μ left right projection determined gap hL alphabet n + +end +end PerfectCompleteness.ProjectedCleanSoundness + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanConditioning.lean b/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanConditioning.lean new file mode 100644 index 0000000000000000000000000000000000000000..82d0d0f68a59dbb3a75c9facd6131d417ca29482 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanConditioning.lean @@ -0,0 +1,191 @@ +import OAI.Computability.PerfectCompleteness.Foundations.FiniteProduct +import OAI.Computability.UniqueGames.Foundations.Conditioning +import OAI.Computability.UniqueGames.Games.FinishBoundsLemmas + +namespace OAI + + +namespace PerfectCompleteness.CleanConditioning + +open scoped BigOperators +open UniqueGamesTheorem.Foundations.Games +open FiniteProduct + +noncomputable section + +section Product + +variable {I : Type*} [Fintype I] [DecidableEq I] + {Ω : I → Type*} [∀ i, Fintype (Ω i)] + +def allEvent (event : (i : I) → Ω i → Bool) (x : (i : I) → Ω i) : Bool := + decide (∀ i, event i (x i) = true) + +omit [DecidableEq I] in +theorem product_filter (a : I → ℝ) (event : I → Bool) : + (if ∀ i, event i = true then ∏ i, a i else 0) = + ∏ i, if event i then a i else 0 := by + classical + by_cases h : ∀ i, event i = true + · simp [h] + · rw [ite_eq_right h] + obtain ⟨i, hi⟩ := not_forall.mp h + symm + exact Finset.prod_eq_zero (Finset.mem_univ i) (by simp [hi]) + +theorem probability_law_all (P : (i : I) → FiniteDistribution (Ω i)) + (event : (i : I) → Ω i → Bool) : + (law P).probability (allEvent event) = ∏ i, (P i).probability (event i) := by + classical + unfold FiniteDistribution.probability law allEvent + rw [Fintype.prod_sum] + apply Finset.sum_congr rfl + intro x _ + simp only [decide_eq_true_eq] + exact product_filter (fun i => (P i).weight (x i)) (fun i => event i (x i)) + +theorem coordinate_probability_positive (P : (i : I) → FiniteDistribution (Ω i)) + (event : (i : I) → Ω i → Bool) + (positive : 0 < (law P).probability (allEvent event)) (i : I) : + 0 < (P i).probability (event i) := by + have hne : (P i).probability (event i) ≠ 0 := by + intro hz + have hzprod : (∏ j, (P j).probability (event j)) = 0 := + Finset.prod_eq_zero (Finset.mem_univ i) hz + rw [probability_law_all, hzprod] at positive + exact (lt_irrefl 0) positive + exact lt_of_le_of_ne ((P i).probability_nonnegative _) hne.symm + +theorem condition_law_all (P : (i : I) → FiniteDistribution (Ω i)) + (event : (i : I) → Ω i → Bool) + (positive : 0 < (law P).probability (allEvent event)) : + (law P).condition (allEvent event) positive = + law (fun i => (P i).condition (event i) + (coordinate_probability_positive P event positive i)) := by + classical + apply FiniteDistribution.eq_of_weight_eq + intro x + change (if allEvent event x then + (∏ i, (P i).weight (x i)) / (law P).probability (allEvent event) else 0) = + ∏ i, if event i (x i) then + (P i).weight (x i) / (P i).probability (event i) else 0 + rw [← product_filter] + simp only [allEvent, decide_eq_true_eq, probability_law_all, + Finset.prod_div_distrib] + +theorem pushforward_law {Γ : I → Type*} [∀ i, Fintype (Γ i)] + (P : (i : I) → FiniteDistribution (Ω i)) (f : (i : I) → Ω i → Γ i) : + (law P).pushforward (fun x i => f i (x i)) = + law (fun i => (P i).pushforward (f i)) := by + classical + apply FiniteDistribution.eq_of_weight_eq + intro y + symm + simp only [law, FiniteDistribution.pushforward] + rw [Fintype.prod_sum] + apply Finset.sum_congr rfl + intro x _ + by_cases h : (fun i => f i (x i)) = y + · have hp : ∀ i, f i (x i) = y i := congrFun h + simp [hp] + · rw [ite_eq_right h] + have hn : ¬ ∀ i, f i (x i) = y i := fun hp => h (funext hp) + obtain ⟨i, hi⟩ := not_forall.mp hn + exact Finset.prod_eq_zero (Finset.mem_univ i) (by simp [hi]) + +theorem condition_clean_mask (P : (i : I) → FiniteDistribution (Ω i)) + (clean : (i : I) → Ω i → Bool) (mask : I → Bool) + (positive : 0 < (law P).probability + (allEvent (fun i x => decide (clean i x = mask i)))) : + (law P).condition (allEvent (fun i x => decide (clean i x = mask i))) positive = + law (fun i => (P i).condition (fun x => decide (clean i x = mask i)) + (coordinate_probability_positive P _ positive i)) := + condition_law_all P _ positive + +end Product + + +variable {E T R : Type*} [Fintype E] [Fintype T] [Fintype R] + +def kernelJoint (μ : FiniteDistribution E) (kernel : E → FiniteDistribution T) : + FiniteDistribution (E × T) where + weight x := μ.weight x.1 * (kernel x.1).weight x.2 + nonnegative x := mul_nonneg (μ.nonnegative _) ((kernel x.1).nonnegative _) + normalized := by + rw [Fintype.sum_prod_type] + simp_rw [← Finset.mul_sum, FiniteDistribution.normalized, mul_one] + exact μ.normalized + +theorem probability_kernelJoint (μ : FiniteDistribution E) + (kernel : E → FiniteDistribution T) (event : E × T → Bool) : + (kernelJoint μ kernel).probability event = + ∑ e, μ.weight e * (kernel e).probability (fun t => event (e, t)) := by + simp only [FiniteDistribution.probability, kernelJoint, Fintype.sum_prod_type, + Finset.mul_sum] + apply Finset.sum_congr rfl + intro e _ + apply Finset.sum_congr rfl + intro t _ + by_cases h : event (e, t) = true <;> simp [h] + +theorem probability_kernelJoint_fiber [DecidableEq E] (μ : FiniteDistribution E) + (kernel : E → FiniteDistribution T) (event : E × T → Bool) (e : E) : + (kernelJoint μ kernel).probability + (fun x => decide (x.1 = e) && event x) = + μ.weight e * (kernel e).probability (fun t => event (e, t)) := by + rw [probability_kernelJoint] + rw [Finset.sum_eq_single e] + · simp + · intro e' _ hne + simp [hne, FiniteDistribution.probability] + · simp + +theorem probability_kernelJoint_constant (μ : FiniteDistribution E) + (kernel : E → FiniteDistribution T) (event : E × T → Bool) (p : ℝ) + (constant : ∀ e, (kernel e).probability (fun t => event (e, t)) = p) : + (kernelJoint μ kernel).probability event = p := by + rw [probability_kernelJoint] + simp_rw [constant] + rw [← Finset.sum_mul, μ.normalized, one_mul] + +theorem source_condition_of_constant [DecidableEq E] (μ : FiniteDistribution E) + (kernel : E → FiniteDistribution T) (event : E × T → Bool) (p : ℝ) + (constant : ∀ e, (kernel e).probability (fun t => event (e, t)) = p) + (positive : 0 < (kernelJoint μ kernel).probability event) : + ((kernelJoint μ kernel).condition event positive).pushforward Prod.fst = μ := by + classical + have hp : 0 < p := by + rwa [probability_kernelJoint_constant μ kernel event p constant] at positive + apply FiniteDistribution.eq_of_weight_eq + intro e + rw [FiniteDistribution.weight_eq_probability_singleton, + FiniteDistribution.probability_pushforward, FiniteDistribution.probability_condition] + have hevent : (fun x : E × T => event x && decide (x.1 = e)) = + (fun x => decide (x.1 = e) && event x) := by + funext x + exact Bool.and_comm _ _ + rw [hevent, probability_kernelJoint_fiber, constant, + probability_kernelJoint_constant μ kernel event p constant] + exact mul_div_cancel_right₀ _ (ne_of_gt hp) + +theorem designated_source_condition [DecidableEq E] [DecidableEq R] + (μ : FiniteDistribution E) (ν : FiniteDistribution R) + (kernel : E → R → FiniteDistribution T) (clean : E → R → T → Bool) + (p : ℝ) (constant : ∀ e r, (kernel e r).probability (clean e r) = p) + (record : R) + (positive : 0 < + (kernelJoint μ (fun e => kernelJoint ν (kernel e))).probability + (fun x => decide (x.2.1 = record) && clean x.1 x.2.1 x.2.2)) : + ((kernelJoint μ (fun e => kernelJoint ν (kernel e))).condition + (fun x => decide (x.2.1 = record) && clean x.1 x.2.1 x.2.2) positive).pushforward + Prod.fst = μ := by + apply source_condition_of_constant μ _ _ (ν.weight record * p) _ positive + intro e + rw [probability_kernelJoint_fiber] + rw [constant] + + +end +end PerfectCompleteness.CleanConditioning + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanCountingLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanCountingLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..7df77bdf36cd9bd57149aa7dad2364c71ce4c614 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanCountingLemmas.lean @@ -0,0 +1,448 @@ +import OAI.Computability.PerfectCompleteness.Construction.FactoredFunctionsLemmas +import OAI.Computability.PerfectCompleteness.Foundations.CanonicalKeys +import OAI.Computability.PerfectCompleteness.Foundations.ClauseSupportLemmas +import OAI.Computability.PerfectCompleteness.Foundations.QuotientTableAgreementLemmas +import OAI.Computability.PerfectCompleteness.Repetition.CleanConditioning + +namespace OAI + + +namespace PerfectCompleteness.CleanCounting + +open scoped BigOperators +open UniqueGamesTheorem.Foundations.Games +open FiniteProduct CleanConditioning + +noncomputable section + +theorem expectation_event_factor {A : Type*} [Fintype A] + (μ : FiniteDistribution A) (event : A → Bool) (a : ℝ) : + μ.expectation (fun x => if event x then a else 1) = + 1 - (1 - a) * μ.probability event := by + have hpoint (x : A) : μ.weight x * (if event x then a else 1) = + μ.weight x - (1 - a) * (if event x then μ.weight x else 0) := by + cases event x <;> simp + ring + change (∑ x, μ.weight x * (if event x then a else 1)) = _ + simp_rw [hpoint] + rw [Finset.sum_sub_distrib, ← Finset.mul_sum, μ.normalized] + rfl + +variable {I : Type*} [Fintype I] [DecidableEq I] + {Ω : I → Type*} [∀ i, Fintype (Ω i)] + +def cleanCount (clean : (i : I) → Ω i → Bool) (x : (i : I) → Ω i) : Nat := + (Finset.univ.filter fun i => clean i (x i) = true).card + +omit [DecidableEq I] [∀ i, Fintype (Ω i)] in +theorem power_cleanCount (clean : (i : I) → Ω i → Bool) + (x : (i : I) → Ω i) (a : ℝ) : + a ^ cleanCount clean x = ∏ i, if clean i (x i) = true then a else 1 := by + rw [← Finset.prod_filter] + simp [cleanCount] + +theorem cleanCount_moment (P : (i : I) → FiniteDistribution (Ω i)) + (clean : (i : I) → Ω i → Bool) (a : ℝ) : + (law P).expectation (fun x => a ^ cleanCount clean x) = + ∏ i : I, (1 - (1 - a) * (P i).probability (clean i)) := by + calc + _ = (law P).expectation (fun x => ∏ i : I, if clean i (x i) then a else 1) := + FiniteDistribution.expectation_congr _ + (fun x => power_cleanCount (I := I) (Ω := Ω) clean x a) + _ = ∏ i : I, (P i).expectation (fun x => if clean i x then a else 1) := + expectation_product (I := I) (Ω := Ω) P + (fun (i : I) (x : Ω i) => if clean i x then a else 1) + _ = _ := by + apply Finset.prod_congr rfl + intro i _ + exact expectation_event_factor (P i) (clean i) a + +theorem cleanCount_moment_le (P : (i : I) → FiniteDistribution (Ω i)) + (clean : (i : I) → Ω i → Bool) (a p₀ : ℝ) + (ha : 0 ≤ a) (ha' : a ≤ 1) + (lower : ∀ i, p₀ ≤ (P i).probability (clean i)) : + (law P).expectation (fun x => a ^ cleanCount clean x) ≤ + (1 - (1 - a) * p₀) ^ Fintype.card I := by + rw [cleanCount_moment] + calc + _ ≤ ∏ _i : I, (1 - (1 - a) * p₀) := by + apply Finset.prod_le_prod₀ + · intro i _ + have h := mul_le_mul_of_nonneg_left ((P i).probability_le_one (clean i)) + (sub_nonneg.mpr ha') + nlinarith + · intro i _ + have h := mul_le_mul_of_nonneg_left (lower i) (sub_nonneg.mpr ha') + linarith + _ = _ := by simp + + +variable {E R T : I → Type*} + [∀ i, Fintype (E i)] [∀ i, Fintype (R i)] [∀ i, Fintype (T i)] + +omit [Fintype I] [DecidableEq I] in +theorem kernel_clean_probability + (μ : (i : I) → FiniteDistribution (E i)) + (ν : (i : I) → FiniteDistribution (R i)) + (kernel : (i : I) → E i → R i → FiniteDistribution (T i)) + (clean : (i : I) → E i → R i → T i → Bool) (p : I → ℝ) + (constant : ∀ i e r, (kernel i e r).probability (clean i e r) = p i) (i : I) : + (kernelJoint (μ i) (fun e => kernelJoint (ν i) (kernel i e))).probability + (fun x => clean i x.1 x.2.1 x.2.2) = p i := by + apply probability_kernelJoint_constant (μ i) _ _ (p i) + intro e + apply probability_kernelJoint_constant (ν i) _ _ (p i) + intro r + exact constant i e r + +theorem kernel_cleanCount_moment + (μ : (i : I) → FiniteDistribution (E i)) + (ν : (i : I) → FiniteDistribution (R i)) + (kernel : (i : I) → E i → R i → FiniteDistribution (T i)) + (clean : (i : I) → E i → R i → T i → Bool) (p : I → ℝ) + (constant : ∀ i e r, (kernel i e r).probability (clean i e r) = p i) (a : ℝ) : + (law (fun i => kernelJoint (μ i) (fun e => kernelJoint (ν i) (kernel i e)))).expectation + (fun x => a ^ cleanCount (I := I) (Ω := fun i => E i × (R i × T i)) + (fun i y => clean i y.1 y.2.1 y.2.2) x) = + ∏ i : I, (1 - (1 - a) * p i) := by + rw [cleanCount_moment] + simp only [kernel_clean_probability μ ν kernel clean p constant] + + +end +end PerfectCompleteness.CleanCounting + + +section + +namespace PerfectCompleteness.MixedSupport + +open ClauseSupport + +variable {C Y : Type*} + +theorem localKey_unused (s : Slot) (f : C → s.Domain → Y) (unused : Unused f) : + localKey s f = .dropped := by + classical + cases s with + | clause occurrence variableIDs signs => + change clauseKey occurrence variableIDs f = .dropped + simp only [clauseKey, clauseMode_unused f unused] + | bit variableID => + change (if Unused f then SlotKey.dropped else SlotKey.bit variableID) = SlotKey.dropped + exact ite_eq_left unused + +theorem localReduction_unused (s : Slot) (f : C → s.Domain → Y) + (unused : Unused f) (u : s.Domain) : localReduction s f u = .dropped := by + classical + cases s with + | clause occurrence variableIDs signs => + change clauseReduction f u = .dropped + simp only [clauseReduction, clauseMode_unused f unused, reduceByMode] + | bit variableID => + change (if Unused f then ReducedValue.dropped else ReducedValue.bit u) = ReducedValue.dropped + exact ite_eq_left unused + +end PerfectCompleteness.MixedSupport + +namespace PerfectCompleteness.CleanKeyErasure + +open ClauseSupport MixedSupport FactoredFunctions + +variable {I Y : Type*} [DecidableEq I] + +abbrev Retained (slots : I → Slot) (keep : I → Prop) := + (i : {i : I // keep i}) → (slots i.val).Domain + +def retain (slots : I → Slot) (keep : I → Prop) : + Assignment slots → Retained slots keep := fun x i => x i.val + +theorem retain_update_of_not_kept (slots : I → Slot) (keep : I → Prop) + (x : Assignment slots) (i : I) (not_kept : ¬ keep i) (u : (slots i).Domain) : + retain slots keep (Function.update x i u) = retain slots keep x := by + funext j + have hji : j.val ≠ i := by + intro h + exact not_kept (h ▸ j.property) + simp only [retain, Function.update_of_ne hji] + +theorem section_unused_of_retained (slots : I → Slot) (keep : I → Prop) + (f : Assignment slots → Y) + (constant : ∀ x y, retain slots keep x = retain slots keep y → f x = f y) + (i : I) (not_kept : ¬ keep i) : Unused (sectionFunction slots f i) := by + intro context u v + apply constant + exact (retain_update_of_not_kept slots keep context i not_kept u).trans + (retain_update_of_not_kept slots keep context i not_kept v).symm + +theorem section_unused_of_factor (slots : I → Slot) (keep : I → Prop) + (f : Retained slots keep → Y) (i : I) (not_kept : ¬ keep i) : + Unused (sectionFunction slots (f ∘ retain slots keep) i) := by + apply section_unused_of_retained slots keep (f ∘ retain slots keep) + (fun x y h => congrArg f h) i not_kept + +theorem keyFields_dropped_of_retained (slots : I → Slot) (keep : I → Prop) + (f : Assignment slots → Y) + (constant : ∀ x y, retain slots keep x = retain slots keep y → f x = f y) + (i : I) (not_kept : ¬ keep i) : keyFields slots f i = .dropped := + localKey_unused (slots i) (sectionFunction slots f i) + (section_unused_of_retained slots keep f constant i not_kept) + +theorem reduction_dropped_of_retained (slots : I → Slot) (keep : I → Prop) + (f : Assignment slots → Y) + (constant : ∀ x y, retain slots keep x = retain slots keep y → f x = f y) + (i : I) (not_kept : ¬ keep i) (x : Assignment slots) : + reduction slots f x i = .dropped := + localReduction_unused (slots i) (sectionFunction slots f i) + (section_unused_of_retained slots keep f constant i not_kept) (x i) + +section Scalar + +variable {𝕜 : Type*} [Field 𝕜] + +theorem section_unused_of_factoring (slots : I → Slot) (keep : I → Prop) + (f : Assignment slots → 𝕜) (factors : f ∈ factoringSpace (retain slots keep)) + (i : I) (not_kept : ¬ keep i) : Unused (sectionFunction slots f i) := + section_unused_of_retained slots keep f factors i not_kept + +theorem keyFields_dropped_of_factoring (slots : I → Slot) (keep : I → Prop) + (f : Assignment slots → 𝕜) (factors : f ∈ factoringSpace (retain slots keep)) + (i : I) (not_kept : ¬ keep i) : keyFields slots f i = .dropped := + keyFields_dropped_of_retained slots keep f factors i not_kept + +theorem reduction_dropped_of_factoring (slots : I → Slot) (keep : I → Prop) + (f : Assignment slots → 𝕜) (factors : f ∈ factoringSpace (retain slots keep)) + (i : I) (not_kept : ¬ keep i) (x : Assignment slots) : + reduction slots f x i = .dropped := + reduction_dropped_of_retained slots keep f factors i not_kept x + +end Scalar + + +variable {n : Nat} + +theorem retainedKeys_only_kept (slots : Fin n → Slot) (keep : Fin n → Prop) + (f : Assignment slots → Y) + (constant : ∀ x y, retain slots keep x = retain slots keep y → f x = f y) + (entry : Fin n × SlotKey) (present : entry ∈ retainedKeys slots f) : keep entry.1 := by + classical + unfold retainedKeys at present + obtain ⟨in_map, not_dropped⟩ := List.mem_filter.mp present + obtain ⟨i, _, rfl⟩ := List.mem_map.mp in_map + by_contra not_kept + exact (of_decide_eq_true not_dropped) + (keyFields_dropped_of_retained slots keep f constant i not_kept) + +theorem not_mem_retainedKeys_of_not_kept (slots : Fin n → Slot) (keep : Fin n → Prop) + (f : Assignment slots → Y) + (constant : ∀ x y, retain slots keep x = retain slots keep y → f x = f y) + (i : Fin n) (not_kept : ¬ keep i) (metadata : SlotKey) : + (i, metadata) ∉ retainedKeys slots f := by + intro present + exact not_kept (retainedKeys_only_kept slots keep f constant (i, metadata) present) + +theorem keyFields_const (slots : Fin n → Slot) (value : Y) (i : Fin n) : + keyFields slots (fun _ => value) i = .dropped := + localKey_unused (slots i) (sectionFunction slots (fun _ => value) i) + (fun _ _ _ => rfl) + +theorem retainedKeys_const (slots : Fin n → Slot) (value : Y) : + retainedKeys slots (fun _ => value) = [] := by + apply List.eq_nil_iff_forall_not_mem.mpr + intro entry present + exact retainedKeys_only_kept slots (fun _ => False) (fun _ => value) + (fun _ _ _ => rfl) entry present + +end PerfectCompleteness.CleanKeyErasure + +end + + +namespace PerfectCompleteness.CleanKeyFactorization + +open ClauseSupport MixedSupport CanonicalKeys CleanKeyErasure +open scoped Classical + +noncomputable section + +variable {I Y : Type*} [DecidableEq I] + +abbrev retainedSlots (slots : I → Slot) (keep : I → Prop) : {i : I // keep i} → Slot := + fun i => slots i.val + +def fill (slots : I → Slot) (keep : I → Prop) + (x : Assignment (retainedSlots slots keep)) : Assignment slots := + fun i => if h : keep i then x ⟨i, h⟩ else Classical.choice (inferInstance : Nonempty (slots i).Domain) + +omit [DecidableEq I] in +theorem retain_fill (slots : I → Slot) (keep : I → Prop) + (x : Assignment (retainedSlots slots keep)) : retain slots keep (fill slots keep x) = x := by + funext i + simp only [retain, fill, dite_eq_left i.property] + +omit [DecidableEq I] in +theorem retain_surjective (slots : I → Slot) (keep : I → Prop) : + Function.Surjective (retain slots keep) := + fun x => ⟨fill slots keep x, retain_fill slots keep x⟩ + +theorem retain_update (slots : I → Slot) (keep : I → Prop) + (x : Assignment slots) (i : {i : I // keep i}) (u : (slots i.val).Domain) : + retain slots keep (Function.update x i.val u) = + Function.update (retain slots keep x) i u := + Function.update_comp_eq_of_injective' x Subtype.val_injective i u + +theorem sectionFunction_factor (slots : I → Slot) (keep : I → Prop) + (g : Assignment (retainedSlots slots keep) → Y) (i : {i : I // keep i}) : + sectionFunction slots (g ∘ retain slots keep) i.val = + pull (sectionFunction (retainedSlots slots keep) g i) (retain slots keep) id := by + funext context u + change g (retain slots keep (Function.update context i.val u)) = + g (Function.update (retain slots keep context) i u) + rw [retain_update] + +theorem keyFields_kept (slots : I → Slot) (keep : I → Prop) + (g : Assignment (retainedSlots slots keep) → Y) (i : {i : I // keep i}) : + keyFields slots (g ∘ retain slots keep) i.val = + keyFields (retainedSlots slots keep) g i := by + change localKey (slots i.val) (sectionFunction slots (g ∘ retain slots keep) i.val) = _ + rw [sectionFunction_factor] + exact localKey_projection (Projection.keep (slots i.val)) + (sectionFunction (retainedSlots slots keep) g i) + (retain slots keep) (retain_surjective slots keep) + +theorem reduction_kept (slots : I → Slot) (keep : I → Prop) + (g : Assignment (retainedSlots slots keep) → Y) (i : {i : I // keep i}) + (x : Assignment slots) : + reduction slots (g ∘ retain slots keep) x i.val = + reduction (retainedSlots slots keep) g (retain slots keep x) i := by + change localReduction (slots i.val) + (sectionFunction slots (g ∘ retain slots keep) i.val) (x i.val) = _ + rw [sectionFunction_factor] + exact localReduction_projection (Projection.keep (slots i.val)) + (sectionFunction (retainedSlots slots keep) g i) + (retain slots keep) (retain_surjective slots keep) (x i.val) + +def embeddedFields (keep : I → Prop) (slots : {i : I // keep i} → Slot) + (g : Assignment slots → Y) (i : I) : SlotKey := + if h : keep i then keyFields slots g ⟨i, h⟩ else .dropped + +def embeddedReduction (keep : I → Prop) (slots : {i : I // keep i} → Slot) + (g : Assignment slots → Y) (x : Assignment slots) (i : I) : ReducedValue := + if h : keep i then reduction slots g x ⟨i, h⟩ else .dropped + +theorem keyFields_factor (slots : I → Slot) (keep : I → Prop) + (g : Assignment (retainedSlots slots keep) → Y) : + keyFields slots (g ∘ retain slots keep) = embeddedFields keep (retainedSlots slots keep) g := by + funext i + by_cases hi : keep i + · simpa only [embeddedFields, dite_eq_left hi] using keyFields_kept slots keep g ⟨i, hi⟩ + · rw [embeddedFields, dite_eq_right hi] + exact keyFields_dropped_of_retained slots keep (g ∘ retain slots keep) + (fun x y h => congrArg g h) i hi + +theorem reduction_factor (slots : I → Slot) (keep : I → Prop) + (g : Assignment (retainedSlots slots keep) → Y) (x : Assignment slots) : + reduction slots (g ∘ retain slots keep) x = + embeddedReduction keep (retainedSlots slots keep) g (retain slots keep x) := by + funext i + by_cases hi : keep i + · simpa only [embeddedReduction, dite_eq_left hi] using reduction_kept slots keep g ⟨i, hi⟩ x + · rw [embeddedReduction, dite_eq_right hi] + exact reduction_dropped_of_retained slots keep (g ∘ retain slots keep) + (fun x y h => congrArg g h) i hi x + +theorem embeddedReduction_constant [Finite I] + (keep : I → Prop) (slots : {i : I // keep i} → Slot) (g : Assignment slots → Y) : + ReducedPartition.ConstantOnFibers (embeddedReduction keep slots g) g := by + intro x y h + apply constant_on_reduction_fibers slots g + funext i + have hi := congrFun h i.val + simpa only [embeddedReduction, dite_eq_left i.property] using hi + + +variable {n : Nat} + +def retainedMetadata (keep : Fin n → Prop) (slots : {i : Fin n // keep i} → Slot) + (g : Assignment slots → Y) : List (Fin n × SlotKey) := + ((List.finRange n).map (fun i => (i, embeddedFields keep slots g i))).filter + (fun entry => decide (entry.2 ≠ .dropped)) + +def retainedKey (side : Side) (keep : Fin n → Prop) + (slots : {i : Fin n // keep i} → Slot) (g : Assignment slots → Y) : Key n where + side := side + retained := retainedMetadata keep slots g + partition := ReducedPartition.parts (embeddedReduction keep slots g) g + +theorem retainedKeys_factor (slots : Fin n → Slot) (keep : Fin n → Prop) + (g : Assignment (retainedSlots slots keep) → Y) : + retainedKeys slots (g ∘ retain slots keep) = + retainedMetadata keep (retainedSlots slots keep) g := by + simp only [retainedKeys, retainedMetadata, keyFields_factor] + +theorem partition_factor (slots : Fin n → Slot) (keep : Fin n → Prop) + (g : Assignment (retainedSlots slots keep) → Y) : + CanonicalKeys.partition slots (g ∘ retain slots keep) = + ReducedPartition.parts (embeddedReduction keep (retainedSlots slots keep) g) g := + ReducedPartition.parts_eq_of_pullback (retain slots keep) (retain_surjective slots keep) + (reduction slots (g ∘ retain slots keep)) + (embeddedReduction keep (retainedSlots slots keep) g) + (g ∘ retain slots keep) g (reduction_factor slots keep g) (fun _ => rfl) + +theorem key_factor (side : Side) (slots : Fin n → Slot) (keep : Fin n → Prop) + (g : Assignment (retainedSlots slots keep) → Y) : + key side slots (g ∘ retain slots keep) = + retainedKey side keep (retainedSlots slots keep) g := by + simp only [key, retainedKey, retainedKeys_factor, partition_factor] + +theorem retainedKey_nonempty (side : Side) (keep : Fin n → Prop) + (slots : {i : Fin n // keep i} → Slot) (g : Assignment slots → Y) : + (retainedKey side keep slots g).partition.Nonempty := by + obtain ⟨x⟩ := (inferInstance : Nonempty (Assignment slots)) + exact ⟨ReducedPartition.fiber (embeddedReduction keep slots g) g x, ⟨x, rfl⟩⟩ + +def retainedQueryKey (side : Side) (keep : Fin n → Prop) + (slots : {i : Fin n // keep i} → Slot) (g : Assignment slots → Y) : + KeyStrategy.NonemptyKey n := + ⟨retainedKey side keep slots g, retainedKey_nonempty side keep slots g⟩ + +theorem queryKey_factor (side : Side) (slots : Fin n → Slot) (keep : Fin n → Prop) + (g : Assignment (retainedSlots slots keep) → Y) : + KeyStrategy.queryKey side slots (g ∘ retain slots keep) = + retainedQueryKey side keep (retainedSlots slots keep) g := by + apply Subtype.ext + exact key_factor side slots keep g + +theorem label_factor (labeling : KeyStrategy.Strategy n) (side : Side) + (slots : Fin n → Slot) (keep : Fin n → Prop) + (g : Assignment (retainedSlots slots keep) → Y) : + (KeyStrategy.label labeling side slots (g ∘ retain slots keep)).val = + (labeling (retainedQueryKey side keep (retainedSlots slots keep) g)).val := + congrArg (fun k : KeyStrategy.NonemptyKey n => (labeling k).val) + (queryKey_factor side slots keep g) + +def retainedResponse (labeling : KeyStrategy.Strategy n) (side : Side) + (keep : Fin n → Prop) (slots : {i : Fin n // keep i} → Slot) + (g : Assignment slots → Y) : Y := + ReducedPartition.output (embeddedReduction keep slots g) g + (labeling (retainedQueryKey side keep slots g)) + +theorem response_factor (labeling : KeyStrategy.Strategy n) (side : Side) + (slots : Fin n → Slot) (keep : Fin n → Prop) + (g : Assignment (retainedSlots slots keep) → Y) : + KeyStrategy.response labeling side slots (g ∘ retain slots keep) = + retainedResponse labeling side keep (retainedSlots slots keep) g := + ReducedPartition.output_eq_of_shared_part (retain slots keep) + (reduction slots (g ∘ retain slots keep)) + (embeddedReduction keep (retainedSlots slots keep) g) + (g ∘ retain slots keep) g (reduction_factor slots keep g) (fun _ => rfl) + (embeddedReduction_constant keep (retainedSlots slots keep) g) + (KeyStrategy.label labeling side slots (g ∘ retain slots keep)) + (labeling (retainedQueryKey side keep (retainedSlots slots keep) g)) + (label_factor labeling side slots keep g) + + +end +end PerfectCompleteness.CleanKeyFactorization + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanEndpointSlots.lean b/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanEndpointSlots.lean new file mode 100644 index 0000000000000000000000000000000000000000..f1a7a8c5b3c09290a9222493fb6715546255168e --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanEndpointSlots.lean @@ -0,0 +1,118 @@ +import OAI.Computability.PerfectCompleteness.Construction.SourceQuestionReconstruction +import OAI.Computability.PerfectCompleteness.Foundations.CutSlotAssembly + +namespace OAI + +section + +namespace PerfectCompleteness.CleanEndpointSlots + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces +open SourceQuestionReconstruction + +variable {branch : Nat → Nat} {n h t v m : Nat} [NeZero m] + (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch h) → Slots branch h) + (clean : Fin (branch h) → Prop) + (visible : Visible (E := SourceTuple m t) designated clean) + +def leftInside (own : {i : Fin (branch h) // clean i} → Fin t → Fin m) : + Slots branch (h + 1) → Fin t → MixedSupport.Slot := + fun s k => SourceKeys.slot clauses + (reconstructLeft designated clean visible own s.1 s.2 k) + +def rightInside (projected : Fin (branch h) → Bool) + (own : {i : Fin (branch h) // clean i} → Fin t → Fin v) : + Slots branch (h + 1) → Fin t → MixedSupport.Slot := + fun s k => SourceKeys.slot clauses + (reconstructRight designated clean clauses projected visible own s.1 s.2 k) + +omit [NeZero m] in +theorem leftInside_nonclean + (own other : {i : Fin (branch h) // clean i} → Fin t → Fin m) + (i : Fin (branch h)) (hi : ¬ clean i) (s : Slots branch h) : + leftInside clauses designated clean visible own (i, s) = + leftInside clauses designated clean visible other (i, s) := by + funext k + have hn : ¬ (clean i ∧ s = designated i) := fun h => hi h.1 + simp only [leftInside, reconstructLeft, reconstruct, dite_eq_right hn] + +omit [NeZero m] in +theorem rightInside_nonclean (projected : Fin (branch h) → Bool) + (own other : {i : Fin (branch h) // clean i} → Fin t → Fin v) + (i : Fin (branch h)) (hi : ¬ clean i) (s : Slots branch h) : + rightInside clauses designated clean visible projected own (i, s) = + rightInside clauses designated clean visible projected other (i, s) := by + funext k + have hn : ¬ (clean i ∧ s = designated i) := fun h => hi h.1 + simp only [rightInside, reconstructRight, reconstruct, dite_eq_right hn] + +def leftReference : Slots branch (h + 1) → Fin t → MixedSupport.Slot := + leftInside clauses designated clean visible (fun _ _ => 0) + +def rightReference (projected : Fin (branch h) → Bool) : + Slots branch (h + 1) → Fin t → MixedSupport.Slot := + rightInside clauses designated clean visible projected + (fun _ _ => (clauses 0).variable 0) + +variable (rows repeats : Nat → Nat) (p : Path branch n (h + 1)) + (outside : Slots branch n → Fin t → MixedSupport.Slot) + +def leftSlots (own : {i : Fin (branch h) // clean i} → Fin t → Fin m) := + CutSlotAssembly.fill p outside (leftInside clauses designated clean visible own) + +def rightSlots (projected : Fin (branch h) → Bool) + (own : {i : Fin (branch h) // clean i} → Fin t → Fin v) := + CutSlotAssembly.fill p outside (rightInside clauses designated clean visible projected own) + +omit [NeZero m] in +theorem leftSlots_kept_eq + (own other : {i : Fin (branch h) // clean i} → Fin t → Fin m) + (s : Slots branch n) (hs : CutSamplerKeyLocality.keptLeaf p clean s) : + leftSlots clauses designated clean visible p outside own s = + leftSlots clauses designated clean visible p outside other s := + CutSlotAssembly.fill_kept_eq p outside _ _ clean + (leftInside_nonclean clauses designated clean visible own other) s hs + +omit [NeZero m] in +theorem rightSlots_kept_eq (projected : Fin (branch h) → Bool) + (own other : {i : Fin (branch h) // clean i} → Fin t → Fin v) + (s : Slots branch n) (hs : CutSamplerKeyLocality.keptLeaf p clean s) : + rightSlots clauses designated clean visible p outside projected own s = + rightSlots clauses designated clean visible p outside projected other s := + CutSlotAssembly.fill_kept_eq p outside _ _ clean + (rightInside_nonclean clauses designated clean visible projected own other) s hs + +def leftReplay + (record : WholeCutReplay.Tape rows repeats p + (CutSlotAssembly.fill p outside (leftReference clauses designated clean visible)) clean) + (own : {i : Fin (branch h) // clean i} → Fin t → Fin m) : + WholeCutReplay.Tape rows repeats p + (leftSlots clauses designated clean visible p outside own) clean := + CutSlotAssembly.transport rows repeats p outside + (leftReference clauses designated clean visible) + (leftInside clauses designated clean visible own) clean + (leftInside_nonclean clauses designated clean visible (fun _ _ => 0) own) record + +def rightReplay (projected : Fin (branch h) → Bool) + (record : WholeCutReplay.Tape rows repeats p + (CutSlotAssembly.fill p outside + (rightReference clauses designated clean visible projected)) clean) + (own : {i : Fin (branch h) // clean i} → Fin t → Fin v) : + WholeCutReplay.Tape rows repeats p + (rightSlots clauses designated clean visible p outside projected own) clean := + CutSlotAssembly.transport rows repeats p outside + (rightReference clauses designated clean visible projected) + (rightInside clauses designated clean visible projected own) clean + (rightInside_nonclean clauses designated clean visible projected + (fun _ _ => (clauses 0).variable 0) own) record + +end +end PerfectCompleteness.CleanEndpointSlots + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanNativeReplay.lean b/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanNativeReplay.lean new file mode 100644 index 0000000000000000000000000000000000000000..c95c1fe5d83f6fd4939ac230f28002e95c23fc03 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanNativeReplay.lean @@ -0,0 +1,198 @@ +import OAI.Computability.PerfectCompleteness.Decoding.CleanDecoderRateLemmas +import OAI.Computability.PerfectCompleteness.Repetition.CleanPhysicalCanonicalQuery + +namespace OAI + +section + +namespace PerfectCompleteness.CleanNativeReplay + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +section Transport + +variable {branch : Nat → Nat} {n h t : Nat} + +private theorem transport_target_heq (rows repeats : Nat → Nat) + (p : Path branch n (h + 1)) + (reference target other : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch h) → Prop) (heq : target = other) + (hs : ∀ s, CutSamplerKeyLocality.keptLeaf p clean s → reference s = target s) + (hs' : ∀ s, CutSamplerKeyLocality.keptLeaf p clean s → reference s = other s) + (tape : WholeCutReplay.Tape rows repeats p reference clean) : + HEq (WholeCutReplayKeys.transportTape rows repeats p reference target clean hs tape) + (WholeCutReplayKeys.transportTape rows repeats p reference other clean hs' tape) := by + cases heq + rfl + +private theorem evaluateArrays_heq (rows repeats : Nat → Nat) + (p : Path branch n (h + 1)) + (slots target : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch h) → Prop) (hs : slots = target) + (tape : WholeCutReplay.Tape rows repeats p slots clean) + (other : WholeCutReplay.Tape rows repeats p target clean) (htape : HEq tape other) : + HEq (WholeCutReplay.evaluateArrays rows repeats p slots clean tape) + (WholeCutReplay.evaluateArrays rows repeats p target clean other) := by + cases hs + cases htape + rfl + +end Transport + +variable {branch rows repeats : Nat → Nat} {n h t v m : Nat} [NeZero m] + {upper : Nodes branch n} {d : HierarchicalFrozenTables.LowerNodes upper (h + 1)} + (S : CleanDecoderRate.Setup branch rows repeats n h t v m upper d) + +abbrev context (x : CleanDecoderRate.Sample S) := CleanDecoderPairLaw.context S x +abbrev leftOwn (x : CleanDecoderRate.Sample S) := CleanDecoderPairLaw.leftOwn S x +abbrev rightOwn (x : CleanDecoderRate.Sample S) := CleanDecoderPairLaw.rightOwn S x + +abbrev leftSlots (x : CleanDecoderRate.Sample S) := + CleanPhysicalCanonicalQuery.leftSlots rows repeats (CleanDecoderRate.path S) + S.outside S.clauses S.designated x + +abbrev rightSlots (x : CleanDecoderRate.Sample S) := + CleanPhysicalCanonicalQuery.rightSlots rows repeats (CleanDecoderRate.path S) + S.outside S.clauses S.designated x + +abbrev leftTape (x : CleanDecoderRate.Sample S) := + CleanPhysicalReplay.leftTape rows repeats (CleanDecoderRate.path S) + S.outside S.placeholder S.clauses S.designated x S.exterior + +abbrev rightTape (x : CleanDecoderRate.Sample S) := + CleanPhysicalReplay.rightTape rows repeats (CleanDecoderRate.path S) + S.outside S.placeholder S.clauses S.designated x S.exterior + +theorem leftSlots_eq (x : CleanDecoderRate.Sample S) : + CleanDecoderContext.leftSlots (context S x) (leftOwn S x) = leftSlots S x := + CleanRecordDecoderInput.leftSlots_eq rows repeats upper d S.cut S.outside S.placeholder + S.clauses S.designated (CleanDecoderRate.observations S x) S.exterior x + (CleanRecordDecoderInput.event_observe rows repeats upper d S.cut S.clauses S.designated x) + +theorem rightSlots_eq (x : CleanDecoderRate.Sample S) : + CleanDecoderContext.rightSlots (context S x) (rightOwn S x) = rightSlots S x := + CleanRecordDecoderInput.rightSlots_eq rows repeats upper d S.cut S.outside S.placeholder + S.clauses S.designated (CleanDecoderRate.observations S x) S.exterior x + (CleanRecordDecoderInput.event_observe rows repeats upper d S.cut S.clauses S.designated x) + +theorem leftReplay_heq (x : CleanDecoderRate.Sample S) : + HEq (CleanLeftDecoder.replay (CleanDecoderContext.leftExposed (context S x)) (leftOwn S x)) + (WholeCutReplay.erase rows repeats (CleanDecoderRate.path S) (leftSlots S x) + (context S x).clean (leftTape S x)) := by + let record := CleanDecoderRate.observations S x + have hevent := CleanRecordDecoderInput.event_observe + rows repeats upper d S.cut S.clauses S.designated x + have hrecord := CleanPhysicalReplay.leftRecord_eq_erase + rows repeats (CleanDecoderRate.path S) S.outside S.placeholder S.clauses S.designated + record x hevent S.exterior + have htransport := transport_target_heq rows repeats (CleanDecoderRate.path S) + (CutSlotAssembly.fill (CleanDecoderRate.path S) S.outside + (CleanRecordChildBlocks.leftRef rows S.clauses S.designated record)) + (CleanDecoderContext.leftSlots (context S x) (leftOwn S x)) (leftSlots S x) + (context S x).clean (leftSlots_eq S x) + (CleanEndpointSlots.leftSlots_kept_eq S.clauses S.designated (context S x).clean + (context S x).visible (CleanDecoderRate.path S) S.outside (fun _ _ => 0) (leftOwn S x)) + (CutSlotAssembly.fill_kept_eq (CleanDecoderRate.path S) S.outside _ _ _ + (CleanPhysicalReplay.leftInside_nonclean rows repeats (CleanDecoderRate.path S) + S.clauses S.designated record x hevent)) + (CleanPhysicalReplay.leftRecord rows repeats (CleanDecoderRate.path S) + S.outside S.placeholder S.clauses S.designated record S.exterior) + exact htransport.trans (heq_of_eq hrecord) + +theorem rightReplay_heq (x : CleanDecoderRate.Sample S) : + HEq (CleanRightDecoder.replay (context S x).clauses (context S x).designated + (context S x).clean (context S x).visible (context S x).projected upper + (CleanDecoderContext.lower (context S x)) (context S x).cut + (CleanDecoderContext.lowerHeight upper d) (context S x).outside rows repeats + (context S x).rightTape (rightOwn S x)) + (WholeCutReplay.erase rows repeats (CleanDecoderRate.path S) (rightSlots S x) + (context S x).clean (rightTape S x)) := by + let record := CleanDecoderRate.observations S x + have hevent := CleanRecordDecoderInput.event_observe + rows repeats upper d S.cut S.clauses S.designated x + have hrecord := CleanPhysicalReplay.rightRecord_eq_erase + rows repeats (CleanDecoderRate.path S) S.outside S.placeholder S.clauses S.designated + record x hevent S.exterior + have htransport := transport_target_heq rows repeats (CleanDecoderRate.path S) + (CutSlotAssembly.fill (CleanDecoderRate.path S) S.outside + (CleanRecordChildBlocks.rightRef rows S.clauses S.designated record)) + (CleanDecoderContext.rightSlots (context S x) (rightOwn S x)) (rightSlots S x) + (context S x).clean (rightSlots_eq S x) + (CleanEndpointSlots.rightSlots_kept_eq S.clauses S.designated (context S x).clean + (context S x).visible (CleanDecoderRate.path S) S.outside (context S x).projected + (fun _ _ => (S.clauses 0).variable 0) (rightOwn S x)) + (CutSlotAssembly.fill_kept_eq (CleanDecoderRate.path S) S.outside _ _ _ + (CleanPhysicalReplay.rightInside_nonclean rows repeats (CleanDecoderRate.path S) + S.clauses S.designated record x hevent)) + (CleanPhysicalReplay.rightRecord rows repeats (CleanDecoderRate.path S) + S.outside S.placeholder S.clauses S.designated record S.exterior) + exact htransport.trans (heq_of_eq hrecord) + +variable (cube : Nat) (hcube : 0 < cube) + +theorem left_grouped_zero (x : CleanDecoderRate.Sample S) + (hx : (CleanDecoderRate.rawLaw S cube hcube).weight x ≠ 0) : + WholeCutZero.GroupedAtClean rows repeats (CleanDecoderRate.path S) (leftSlots S x) + (context S x).clean (leftTape S x) := + CleanPhysicalReplay.leftTape_grouped_zero rows repeats (CleanDecoderRate.path S) + S.outside S.placeholder S.clauses S.designated + (fun _ => SourceOddLists.tupleLaw m t) + (fun i => FiniteProduct.law + (fun _ : {leaf : Slots branch h // leaf ≠ S.designated i} => SourceOddLists.tupleLaw m t)) + (fun _ => ProjectedCleanRate.projectionFlag cube hcube) + (CleanDecoderRate.observations S x) x hx + (CleanRecordDecoderInput.event_observe rows repeats upper d S.cut S.clauses S.designated x) + S.exterior + +theorem right_grouped_zero (x : CleanDecoderRate.Sample S) + (hx : (CleanDecoderRate.rawLaw S cube hcube).weight x ≠ 0) : + WholeCutZero.GroupedAtClean rows repeats (CleanDecoderRate.path S) (rightSlots S x) + (context S x).clean (rightTape S x) := + CleanPhysicalReplay.rightTape_grouped_zero rows repeats (CleanDecoderRate.path S) + S.outside S.placeholder S.clauses S.designated + (fun _ => SourceOddLists.tupleLaw m t) + (fun i => FiniteProduct.law + (fun _ : {leaf : Slots branch h // leaf ≠ S.designated i} => SourceOddLists.tupleLaw m t)) + (fun _ => ProjectedCleanRate.projectionFlag cube hcube) + (CleanDecoderRate.observations S x) x hx + (CleanRecordDecoderInput.event_observe rows repeats upper d S.cut S.clauses S.designated x) + S.exterior + +theorem leftArrays_heq (x : CleanDecoderRate.Sample S) + (hx : (CleanDecoderRate.rawLaw S cube hcube).weight x ≠ 0) : + HEq (CleanLeftDecoder.arrays (CleanDecoderContext.leftExposed (context S x)) (leftOwn S x)) + (WholeCutSampler.evaluate rows repeats (CleanDecoderRate.path S) (leftSlots S x) + (leftTape S x)) := by + have h := evaluateArrays_heq rows repeats (CleanDecoderRate.path S) + (CleanDecoderContext.leftSlots (context S x) (leftOwn S x)) (leftSlots S x) + (context S x).clean (leftSlots_eq S x) _ _ (leftReplay_heq S x) + exact h.trans (heq_of_eq (WholeCutReplay.evaluateArrays_erase_of_grouped_zero + rows repeats (CleanDecoderRate.path S) (leftSlots S x) (context S x).clean + (leftTape S x) (left_grouped_zero S cube hcube x hx))) + +theorem rightArrays_heq (x : CleanDecoderRate.Sample S) + (hx : (CleanDecoderRate.rawLaw S cube hcube).weight x ≠ 0) : + HEq (CleanRightDecoder.arrays (context S x).clauses (context S x).designated + (context S x).clean (context S x).visible (context S x).projected upper + (CleanDecoderContext.lower (context S x)) (context S x).cut + (CleanDecoderContext.lowerHeight upper d) (context S x).outside rows repeats + (context S x).rightTape (rightOwn S x)) + (WholeCutSampler.evaluate rows repeats (CleanDecoderRate.path S) (rightSlots S x) + (rightTape S x)) := by + have h := evaluateArrays_heq rows repeats (CleanDecoderRate.path S) + (CleanDecoderContext.rightSlots (context S x) (rightOwn S x)) (rightSlots S x) + (context S x).clean (rightSlots_eq S x) _ _ (rightReplay_heq S x) + exact h.trans (heq_of_eq (WholeCutReplay.evaluateArrays_erase_of_grouped_zero + rows repeats (CleanDecoderRate.path S) (rightSlots S x) (context S x).clean + (rightTape S x) (right_grouped_zero S cube hcube x hx))) + +end +end PerfectCompleteness.CleanNativeReplay + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanPhysicalCanonicalQuery.lean b/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanPhysicalCanonicalQuery.lean new file mode 100644 index 0000000000000000000000000000000000000000..22a18d37913f7bd52e402464c1ca8c8d04c16284 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanPhysicalCanonicalQuery.lean @@ -0,0 +1,153 @@ +import OAI.Computability.PerfectCompleteness.Decoding.WholeCutGroupedProjection +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalProjectedSliceLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.CleanPhysicalCanonicalQuery + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays + +noncomputable section + +variable {branch : Nat → Nat} {root h t v m : Nat} [NeZero m] + (rows repeats : Nat → Nat) (p : Path branch root (h + 1)) + (outside : Slots branch root → Fin t → MixedSupport.Slot) + (placeholder : Slots branch (h + 1) → Fin t → MixedSupport.Slot) + (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch h) → Slots branch h) + +abbrev Sample := CleanPhysicalReplay.Sample (t := t) rows repeats p clauses designated + +def leftSlots (x : Sample (t := t) rows repeats p clauses designated) : + Slots branch root → Fin t → MixedSupport.Slot := + CutSlotAssembly.fill p outside (CleanPhysicalReplay.leftInside rows repeats p clauses designated x) + +def rightSlots (x : Sample (t := t) rows repeats p clauses designated) : + Slots branch root → Fin t → MixedSupport.Slot := + CutSlotAssembly.fill p outside (CleanPhysicalReplay.rightInside rows repeats p clauses designated x) + +def projection (x : Sample (t := t) rows repeats p clauses designated) : + ∀ s k, MixedSupport.Projection + (leftSlots rows repeats p outside clauses designated x s k) + (rightSlots rows repeats p outside clauses designated x s k) := + CutProjectionAssembly.fillProjection p outside _ _ + (SourceChildKernel.parentProjection rows clauses designated + (fun i => ((x i).1, (x i).2.1)) (fun i => (x i).2.2)) + +def leftArrays (x : Sample (t := t) rows repeats p clauses designated) + (external : CleanPhysicalReplay.Exterior rows repeats p outside placeholder) : + Arrays (leftSlots rows repeats p outside clauses designated x) rows := + WholeCutSampler.evaluate rows repeats p _ + (CleanPhysicalReplay.leftTape rows repeats p outside placeholder clauses designated x external) + +def rightArrays (x : Sample (t := t) rows repeats p clauses designated) + (external : CleanPhysicalReplay.Exterior rows repeats p outside placeholder) : + Arrays (rightSlots rows repeats p outside clauses designated x) rows := + WholeCutSampler.evaluate rows repeats p _ + (CleanPhysicalReplay.rightTape rows repeats p outside placeholder clauses designated x external) + +omit [NeZero m] in +theorem arrays_pullback (x : Sample (t := t) rows repeats p clauses designated) + (external : CleanPhysicalReplay.Exterior rows repeats p outside placeholder) : + leftArrays rows repeats p outside placeholder clauses designated x external = + ChildBlockProjection.arraysPullback rows + (projection rows repeats p outside clauses designated x) + (rightArrays rows repeats p outside placeholder clauses designated x external) := + WholeCutGroupedProjection.physicalTape_pullback rows repeats p outside placeholder + (CleanPhysicalReplay.leftInside rows repeats p clauses designated x) + (CleanPhysicalReplay.rightInside rows repeats p clauses designated x) + (SourceChildKernel.parentProjection rows clauses designated + (fun i => ((x i).1, (x i).2.1)) (fun i => (x i).2.2)) external + (CleanPhysicalReplay.rightBlocks rows repeats p clauses designated x) + +omit [NeZero m] in +theorem query_pullback {Y : Type*} + (x : Sample (t := t) rows repeats p clauses designated) + (external : CleanPhysicalReplay.Exterior rows repeats p outside placeholder) + (post : Output branch root rows → Y) : + WholeCutKeyLocality.query rows repeats p + (leftSlots rows repeats p outside clauses designated x) + (CleanPhysicalReplay.leftTape rows repeats p outside placeholder clauses designated x external) post = + WholeCutKeyLocality.query rows repeats p + (rightSlots rows repeats p outside clauses designated x) + (CleanPhysicalReplay.rightTape rows repeats p outside placeholder clauses designated x external) post ∘ + MixedSupport.projectionMap (TreeCanonical.numberedProjection + (projection rows repeats p outside clauses designated x)) := by + change SourceProjectedCanonicalQuery.query rows + (leftArrays rows repeats p outside placeholder clauses designated x external) post = + SourceProjectedCanonicalQuery.query rows + (rightArrays rows repeats p outside placeholder clauses designated x external) post ∘ _ + rw [arrays_pullback] + exact SourceProjectedCanonicalQuery.query_pullback rows + (projection rows repeats p outside clauses designated x) + (rightArrays rows repeats p outside placeholder clauses designated x external) post + +omit [NeZero m] in +theorem key_eq {Y : Type*} + (x : Sample (t := t) rows repeats p clauses designated) + (external : CleanPhysicalReplay.Exterior rows repeats p outside placeholder) + (post : Output branch root rows → Y) (side : CanonicalKeys.Side) : + CanonicalKeys.key side (TreeCanonical.numberedSlots + (leftSlots rows repeats p outside clauses designated x)) + (WholeCutKeyLocality.query rows repeats p + (leftSlots rows repeats p outside clauses designated x) + (CleanPhysicalReplay.leftTape rows repeats p outside placeholder clauses designated x external) post) = + CanonicalKeys.key side (TreeCanonical.numberedSlots + (rightSlots rows repeats p outside clauses designated x)) + (WholeCutKeyLocality.query rows repeats p + (rightSlots rows repeats p outside clauses designated x) + (CleanPhysicalReplay.rightTape rows repeats p outside placeholder clauses designated x external) post) := by + rw [query_pullback] + exact CanonicalKeys.key_projection side + (TreeCanonical.numberedProjection (projection rows repeats p outside clauses designated x)) _ + +omit [NeZero m] in +theorem label_val_eq {Y : Type*} + (x : Sample (t := t) rows repeats p clauses designated) + (external : CleanPhysicalReplay.Exterior rows repeats p outside placeholder) + (post : Output branch root rows → Y) + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch root t)) + (side : CanonicalKeys.Side) : + (KeyStrategy.label labeling side (TreeCanonical.numberedSlots + (leftSlots rows repeats p outside clauses designated x)) + (WholeCutKeyLocality.query rows repeats p + (leftSlots rows repeats p outside clauses designated x) + (CleanPhysicalReplay.leftTape rows repeats p outside placeholder clauses designated x external) post)).val = + (KeyStrategy.label labeling side (TreeCanonical.numberedSlots + (rightSlots rows repeats p outside clauses designated x)) + (WholeCutKeyLocality.query rows repeats p + (rightSlots rows repeats p outside clauses designated x) + (CleanPhysicalReplay.rightTape rows repeats p outside placeholder clauses designated x external) post)).val := + KeyStrategy.label_val_eq_of_key_eq labeling side side _ _ _ _ + (key_eq rows repeats p outside placeholder clauses designated x external post side) + +omit [NeZero m] in +theorem response_eq {Y : Type*} + (x : Sample (t := t) rows repeats p clauses designated) + (external : CleanPhysicalReplay.Exterior rows repeats p outside placeholder) + (post : Output branch root rows → Y) + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch root t)) + (side : CanonicalKeys.Side) : + KeyStrategy.response labeling side (TreeCanonical.numberedSlots + (leftSlots rows repeats p outside clauses designated x)) + (WholeCutKeyLocality.query rows repeats p + (leftSlots rows repeats p outside clauses designated x) + (CleanPhysicalReplay.leftTape rows repeats p outside placeholder clauses designated x external) post) = + KeyStrategy.response labeling side (TreeCanonical.numberedSlots + (rightSlots rows repeats p outside clauses designated x)) + (WholeCutKeyLocality.query rows repeats p + (rightSlots rows repeats p outside clauses designated x) + (CleanPhysicalReplay.rightTape rows repeats p outside placeholder clauses designated x external) post) := by + rw [query_pullback] + exact KeyStrategy.response_projection labeling side + (TreeCanonical.numberedProjection (projection rows repeats p outside clauses designated x)) _ + +end +end PerfectCompleteness.CleanPhysicalCanonicalQuery + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanPhysicalHighAverage.lean b/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanPhysicalHighAverage.lean new file mode 100644 index 0000000000000000000000000000000000000000..d005787495636575696dd627055444cf01483577 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanPhysicalHighAverage.lean @@ -0,0 +1,280 @@ +import OAI.Computability.PerfectCompleteness.Construction.SourcePhysicalChildExpectation +import OAI.Computability.PerfectCompleteness.Construction.SourceQuestionPhysicalHigh +import OAI.Computability.PerfectCompleteness.Repetition.CleanPhysicalHighEvent +import OAI.Computability.PerfectCompleteness.Repetition.CleanPhysicalRawChildren + +namespace OAI + +section + +namespace PerfectCompleteness.CleanPhysicalHighAverage + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +private theorem mpr_heq {α β : Sort _} (h : α = β) (x : β) : + HEq (Eq.mpr h x) x := by + cases h + rfl + +variable {branch rows repeats : Nat → Nat} {n h t v m : Nat} [NeZero m] + {upper : Nodes branch n} {d : HierarchicalFrozenTables.LowerNodes upper (h + 1)} + (S : CleanDecoderRate.Setup branch rows repeats n h t v m upper d) + +abbrev suffix := CleanRightDecoder.suffix upper (CleanPhysicalDecoderLaw.lower S) + S.cut (CleanDecoderContext.lowerHeight upper d) + +include S in +theorem suffix_proper : h + 1 < Nodes.height upper := + CleanRightDecoder.suffix_proper upper (CleanPhysicalDecoderLaw.lower S) + S.cut (CleanDecoderContext.lowerHeight upper d) + +variable (hbranch : ∀ k < n, 0 < branch k) + (hnode : WholeArrayInteriorExterior.upperNode (CleanDecoderRate.path S) = + HierarchicalLeftDecoder.LowerNode upper (h + 1) d) + {Original : OriginalDecoderMark.SlotFamily branch n t → Type*} + [∀ slots, Fintype (Original slots)] + (F : OriginalDecoderMark.Family branch rows n t Original) (κ : ℝ) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (r : Nat) (ρ : ℝ) (A : ManyGoodRows.RowMap (Block rows upper) r) + (direction : BucketSampler.Direction (rows (h + 1))) (threshold : ℝ) (s : Nat) + +abbrev nativeDirection := + (ProjectedFiberRawPair.direction (CleanDecoderRate.path S) upper (h + 1) d hnode direction).val + +def tapeStatistic + (left right : Slots branch (h + 1) → Fin t → MixedSupport.Slot) + (projection : ∀ leaf k, MixedSupport.Projection (left leaf k) (right leaf k)) + (tape : WholeCutSampler.Tape rows repeats (CleanDecoderRate.path S) + (CutSlotAssembly.fill (CleanDecoderRate.path S) S.outside right)) : ℝ := + LowerProjectedOriginalSuccess.kernelSuccess (repeats := repeats) (CleanDecoderRate.path S) + (CutSlotAssembly.fill (CleanDecoderRate.path S) S.outside left) + (CutSlotAssembly.fill (CleanDecoderRate.path S) S.outside right) + (CutProjectionAssembly.fillProjection (CleanDecoderRate.path S) S.outside left right projection) + upper (h + 1) hbranch d hnode direction A S.cut σ + (OriginalDecoderMark.mark F upper (h + 1) κ + (CutSlotAssembly.fill (CleanDecoderRate.path S) S.outside left)) ρ threshold s + (WholeCutSubtree.knownBucketsAtNode rows repeats + (CutSlotAssembly.fill (CleanDecoderRate.path S) S.outside right) + upper (suffix S) (suffix_proper S) (LinearMap.ker A) tape) + (WholeCutSampler.evaluate rows repeats (CleanDecoderRate.path S) + (CutSlotAssembly.fill (CleanDecoderRate.path S) S.outside right) tape) + +def childStatistic + (left right : Slots branch (h + 1) → Fin t → MixedSupport.Slot) + (projection : ∀ leaf k, MixedSupport.Projection (left leaf k) (right leaf k)) + (children : CutChildGrouping.Raw (C := CleanDecoderRate.Calls S) right rows) : ℝ := + tapeStatistic S hbranch hnode F κ σ r ρ A direction threshold s left right projection + (CleanPhysicalReplay.physicalTape rows repeats (CleanDecoderRate.path S) + S.outside S.placeholder right S.exterior children) + +private theorem childStatistic_congr + (left left' right : Slots branch (h + 1) → Fin t → MixedSupport.Slot) + (hl : left = left') + (projection : ∀ leaf k, MixedSupport.Projection (left leaf k) (right leaf k)) + (projection' : ∀ leaf k, MixedSupport.Projection (left' leaf k) (right leaf k)) + (hp : ∀ leaf k, HEq (projection leaf k) (projection' leaf k)) + (children : CutChildGrouping.Raw (C := CleanDecoderRate.Calls S) right rows) : + childStatistic S hbranch hnode F κ σ r ρ A direction threshold s + left right projection children = + childStatistic S hbranch hnode F κ σ r ρ A direction threshold s + left' right projection' children := by + cases hl + have he : projection = projection' := + funext (fun leaf => funext (fun k => eq_of_heq (hp leaf k))) + cases he + rfl + +theorem rightInput_eq (x : CleanDecoderRate.Sample S) : + CleanPhysicalDecoderLaw.rightInput S (LinearMap.ker A) + (nativeDirection S hnode direction) x = + LowerCutOwnInput.ofArrays (CleanNativeReplay.rightSlots S x) rows upper + (CleanPhysicalDecoderLaw.lower S) (LinearMap.ker A) + (nativeDirection S hnode direction) + (WholeCutSubtree.knownBucketsAtNode rows repeats (CleanNativeReplay.rightSlots S x) + upper (suffix S) (suffix_proper S) (LinearMap.ker A) + (CleanNativeReplay.rightTape S x)) + (CleanPhysicalDecoderLaw.rightArrays S x) := by + have hk := WholeCutSubtree.knownBuckets_eq_original rows repeats (Nodes.path upper) + (suffix S) (suffix_proper S) (CleanNativeReplay.rightSlots S x) + (LinearMap.ker A) (CleanNativeReplay.rightTape S x) + exact congrArg + (fun known : HiddenBucketBias.VisibleDirection (LinearMap.ker A) → + OwnInputReference.UpperSpace (CleanNativeReplay.rightSlots S x) upper => + CleanPhysicalDecoderLaw.inputOfArrays (CleanNativeReplay.rightSlots S x) + upper (CleanPhysicalDecoderLaw.lower S) (LinearMap.ker A) + (nativeDirection S hnode direction) known (CleanPhysicalDecoderLaw.rightArrays S x)) + hk.symm + +theorem physical_probability_eq (x : CleanDecoderRate.Sample S) : + (CleanPhysicalDecoderLaw.pairKernel S F κ σ r ρ A (LinearMap.ker A) + (nativeDirection S hnode direction) threshold x).probability + (CleanPhysicalHighEvent.highEvent S hbranch s x) = + childStatistic S hbranch hnode F κ σ r ρ A direction threshold s + (CleanPhysicalReplay.leftInside rows repeats (CleanDecoderRate.path S) + S.clauses S.designated x) + (CleanPhysicalReplay.rightInside rows repeats (CleanDecoderRate.path S) + S.clauses S.designated x) + (SourceChildKernel.parentProjection rows S.clauses S.designated + (fun i => ((x i).1, (x i).2.1)) (fun i => (x i).2.2)) + (CleanPhysicalReplay.rightBlocks rows repeats (CleanDecoderRate.path S) + S.clauses S.designated x) := by + have ha := CleanPhysicalCanonicalQuery.arrays_pullback rows repeats (CleanDecoderRate.path S) + S.outside S.placeholder S.clauses S.designated x S.exterior + change CleanPhysicalDecoderLaw.leftArrays S x = _ at ha + unfold childStatistic tapeStatistic LowerProjectedOriginalSuccess.kernelSuccess + unfold CleanPhysicalDecoderLaw.pairKernel CleanPhysicalDecoderLaw.leftLaw + CleanPhysicalDecoderLaw.rightLaw + rw [rightInput_eq S hnode r A direction x] + unfold CleanPhysicalDecoderLaw.adviceLaw + rw [ha] + rfl + +def sourceStatistic + (sources : SourceChildKernel.Sources (m := m) (t := t) S.designated) + (observed : Σ flags : SourceProjectedTag.Flags (branch := branch) (n := h), + CutChildGrouping.Raw (C := CleanDecoderRate.Calls S) + (SourcePhysicalTaggedChildren.slots S.clauses S.designated sources flags) rows) : ℝ := + childStatistic S hbranch hnode F κ σ r ρ A direction threshold s + (SourceChildKernel.parentLeftSlots S.clauses S.designated sources) + (SourcePhysicalTaggedChildren.slots S.clauses S.designated sources observed.1) + (fun leaf k => SourceChildKernel.projection S.clauses S.designated leaf.1 + (sources leaf.1) (observed.1 leaf.1) leaf.2 k) observed.2 + +def questionStatistic + (q : PreliminarySampler.Questions branch (h + 1) t m) + (choices : SourceQuestionKernelJoint.ChoiceTuple (branch := branch) (n := h) (t := t)) + (flags : SourceProjectedTag.Flags (branch := branch) (n := h)) + (children : CutChildGrouping.Raw (C := CleanDecoderRate.Calls S) + (SourceProjectedTag.mixedInside S.clauses S.designated q choices flags) rows) : ℝ := + childStatistic S hbranch hnode F κ σ r ρ A direction threshold s + (SourceProjectedTag.originalSlots S.clauses q) + (SourceProjectedTag.mixedInside S.clauses S.designated q choices flags) + (SourceProjectedTag.projection S.clauses S.designated q choices flags) children + +private theorem sourceStatistic_eq_question + (q : PreliminarySampler.Questions branch (h + 1) t m) + (choices : SourceQuestionKernelJoint.ChoiceTuple (branch := branch) (n := h) (t := t)) + (observed : Σ flags : SourceProjectedTag.Flags (branch := branch) (n := h), + CutChildGrouping.Raw (C := CleanDecoderRate.Calls S) + (SourceProjectedTag.mixedInside S.clauses S.designated q choices flags) rows) : + sourceStatistic S hbranch hnode F κ σ r ρ A direction threshold s + (SourceQuestionKernelJoint.sources S.designated q choices) observed = + questionStatistic S hbranch hnode F κ σ r ρ A direction threshold s + q choices observed.1 observed.2 := by + apply childStatistic_congr S hbranch hnode F κ σ r ρ A direction threshold s + _ _ _ (SourceProjectedTag.parentLeftSlots_sources S.clauses S.designated q choices) + intro leaf k + symm + unfold SourceProjectedTag.projection + dsimp only [id] + exact mpr_heq _ _ + +theorem physical_probability_eq_observed (x : CleanDecoderRate.Sample S) : + (CleanPhysicalDecoderLaw.pairKernel S F κ σ r ρ A (LinearMap.ker A) + (nativeDirection S hnode direction) threshold x).probability + (CleanPhysicalHighEvent.highEvent S hbranch s x) = + let q := SourceQuestionRawSwap.insideQuestions rows S.clauses S.designated x + let choices := SourceQuestionRawSwap.positions rows S.clauses S.designated x + let observed := SourcePhysicalChildExpectation.observe rows S.clauses S.designated q choices + (SourceQuestionRawSwap.raw rows S.clauses S.designated x) + questionStatistic S hbranch hnode F κ σ r ρ A direction threshold s + q choices observed.1 observed.2 := by + let q := SourceQuestionRawSwap.insideQuestions rows S.clauses S.designated x + let choices := SourceQuestionRawSwap.positions rows S.clauses S.designated x + let observed := SourcePhysicalChildExpectation.observe rows S.clauses S.designated q choices + (SourceQuestionRawSwap.raw rows S.clauses S.designated x) + have hread := congrArg + (fun sources : SourceChildKernel.Sources (m := m) (t := t) S.designated => + sourceStatistic S hbranch hnode F κ σ r ρ A direction threshold s sources + (SourcePhysicalTaggedChildren.observe rows S.clauses S.designated sources + (SourceQuestionRawSwap.raw rows S.clauses S.designated x))) + (SourceQuestionRawSwap.sources_insideQuestions_positions rows S.clauses S.designated x) + exact (physical_probability_eq S hbranch hnode F κ σ r ρ A direction threshold s x).trans + (hread.symm.trans (sourceStatistic_eq_question S hbranch hnode F κ σ r ρ A + direction threshold s q choices observed)) + +theorem questionStatistic_expectation + (q : PreliminarySampler.Questions branch (h + 1) t m) + (choices : SourceQuestionKernelJoint.ChoiceTuple (branch := branch) (n := h) (t := t)) + (flags : SourceProjectedTag.Flags (branch := branch) (n := h)) : + (CutChildGrouping.rawLaw (C := CleanDecoderRate.Calls S) + (SourceProjectedTag.mixedInside S.clauses S.designated q choices flags) rows).expectation + (questionStatistic S hbranch hnode F κ σ r ρ A direction threshold s q choices flags) = + SourceQuestionPhysicalHigh.success S.outside S.placeholder S.clauses S.designated + q choices flags upper (suffix S) (suffix_proper S) (h + 1) hbranch d hnode A S.cut σ + (OriginalDecoderMark.mark F upper (h + 1) κ + (SourceQuestionPhysicalHigh.originalSlots (CleanDecoderRate.path S) S.outside S.clauses q)) + ρ threshold S.exterior direction s := by + exact CleanPhysicalRawChildren.expectation_lowerTape rows repeats S.outside S.placeholder + (SourceProjectedTag.mixedInside S.clauses S.designated q choices flags) + upper (suffix S) S.exterior + (tapeStatistic S hbranch hnode F κ σ r ρ A direction threshold s + (SourceProjectedTag.originalSlots S.clauses q) + (SourceProjectedTag.mixedInside S.clauses S.designated q choices flags) + (SourceProjectedTag.projection S.clauses S.designated q choices flags)) + +theorem mean_probability_eq (cube : Nat) (hcube : 0 < cube) : + (CleanDecoderPairLaw.pairLaw S σ (CleanPhysicalDecoderLaw.useful S F κ) + r ρ A (LinearMap.ker A) (nativeDirection S hnode direction) threshold cube hcube).probability + (fun z => DecoderRankSplit.highAgrees S hbranch s z.1 z.2) = + (PreliminarySampler.questionsLaw + (branch := branch) (n := h + 1) (t := t) (m := m)).expectation + (fun q => (SourceProjectedTag.positionLaw + (branch := branch) (n := h) (t := t)).expectation + (fun choices => (SourceProjectedTag.flagLaw + (fun _ : Fin (branch h) => ProjectedCleanRate.projectionFlag cube hcube)).expectation + (fun flags => SourceQuestionPhysicalHigh.success + S.outside S.placeholder S.clauses S.designated q choices flags + upper (suffix S) (suffix_proper S) (h + 1) hbranch d hnode A S.cut σ + (OriginalDecoderMark.mark F upper (h + 1) κ + (SourceQuestionPhysicalHigh.originalSlots + (CleanDecoderRate.path S) S.outside S.clauses q)) + ρ threshold S.exterior direction s))) := by + rw [← CleanPhysicalHighEvent.mean_probability_eq S hbranch F κ σ r ρ A + (LinearMap.ker A) (nativeDirection S hnode direction) threshold cube hcube s] + have hsample := FiniteDistribution.expectation_congr (CleanDecoderRate.rawLaw S cube hcube) + (physical_probability_eq_observed S hbranch hnode F κ σ r ρ A direction threshold s) + refine hsample.trans ?_ + rw [show CleanDecoderRate.rawLaw S cube hcube = + SourceChildKernel.originalLaw (C := CleanDecoderRate.Calls S) (t := t) + rows S.clauses S.designated + (fun _ => ProjectedCleanRate.projectionFlag cube hcube) from rfl] + rw [SourcePhysicalChildExpectation.originalLaw_expectation rows S.clauses S.designated + (fun _ => ProjectedCleanRate.projectionFlag cube hcube) + (questionStatistic S hbranch hnode F κ σ r ρ A direction threshold s)] + apply FiniteDistribution.expectation_congr + intro q + apply FiniteDistribution.expectation_congr + intro choices + apply FiniteDistribution.expectation_congr + intro flags + exact questionStatistic_expectation S hbranch hnode F κ σ r ρ A direction threshold s q choices flags + +theorem probability_eq_tag_average (cube : Nat) (hcube : 0 < cube) : + (CleanDecoderPairLaw.pairLaw S σ (CleanPhysicalDecoderLaw.useful S F κ) + r ρ A (LinearMap.ker A) (nativeDirection S hnode direction) threshold cube hcube).probability + (fun z => DecoderRankSplit.highAgrees S hbranch s z.1 z.2) = + (PreliminarySampler.questionsLaw + (branch := branch) (n := h + 1) (t := t) (m := m)).expectation + (fun q => (SourceProjectedTag.law (t := t) + (fun _ : Fin (branch h) => ProjectedCleanRate.projectionFlag cube hcube)).expectation + (fun tag => SourceQuestionPhysicalHigh.success + S.outside S.placeholder S.clauses S.designated q tag.1 tag.2 + upper (suffix S) (suffix_proper S) (h + 1) hbranch d hnode A S.cut σ + (OriginalDecoderMark.mark F upper (h + 1) κ + (SourceQuestionPhysicalHigh.originalSlots + (CleanDecoderRate.path S) S.outside S.clauses q)) + ρ threshold S.exterior direction s)) := by + simpa only [SourceProjectedTag.law, FiniteDistribution.expectation_product] using + mean_probability_eq S hbranch hnode F κ σ r ρ A direction threshold s cube hcube + +end +end PerfectCompleteness.CleanPhysicalHighAverage + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanPhysicalHighEvent.lean b/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanPhysicalHighEvent.lean new file mode 100644 index 0000000000000000000000000000000000000000..85361c7bc39c112fd7984fe5069cc065b59b5200 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanPhysicalHighEvent.lean @@ -0,0 +1,137 @@ +import OAI.Computability.PerfectCompleteness.Decoding.CleanPhysicalDecoderLaw +import OAI.Computability.PerfectCompleteness.Decoding.DecoderFamilyLawLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.CleanPhysicalHighEvent + +noncomputable section + +open scoped Classical +open TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +section NativeTransport + +variable {branch : Nat → Nat} {n t : Nat} + (slots projected target other : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (hs : slots = target) (hp : projected = other) + (upper : Nodes branch n) (level : Nat) (hbranch : ∀ k < n, 0 < branch k) + (d : HierarchicalFrozenTables.LowerNodes upper level) + +theorem output_answerEquiv + (answer : CleanPhysicalDecoderLaw.Answers slots projected upper) : + HEq + (HierarchicalLeftDecoder.output target upper level hbranch d + (CleanPhysicalDecoderLaw.answerEquiv slots projected target other hs hp upper answer).1) + (HierarchicalLeftDecoder.output slots upper level hbranch d answer.1) := by + cases hs + cases hp + rfl + +theorem fullRank_answerEquiv + (answer : CleanPhysicalDecoderLaw.Answers slots projected upper) : + HierarchicalDecoderTables.fullRank target upper level d + (HierarchicalLeftDecoder.output target upper level hbranch d + (CleanPhysicalDecoderLaw.answerEquiv slots projected target other hs hp upper answer).1) = + HierarchicalDecoderTables.fullRank slots upper level d + (HierarchicalLeftDecoder.output slots upper level hbranch d answer.1) := by + cases hs + cases hp + rfl + +theorem highMeeting_answerEquiv + (q : ∀ leaf k, MixedSupport.Projection (slots leaf k) (projected leaf k)) + (q' : ∀ leaf k, MixedSupport.Projection (target leaf k) (other leaf k)) + (hq : ∀ leaf k, HEq (q leaf k) (q' leaf k)) (s : Nat) + (answer : CleanPhysicalDecoderLaw.Answers slots projected upper) : + ProjectedFiberSquare.highMeeting target other q' upper level hbranch d s + (CleanPhysicalDecoderLaw.answerEquiv slots projected target other hs hp upper answer).1 + (CleanPhysicalDecoderLaw.answerEquiv slots projected target other hs hp upper answer).2 = + ProjectedFiberSquare.highMeeting slots projected q upper level hbranch d s + answer.1 answer.2 := by + cases hs + cases hp + have hqq : q = q' := funext (fun leaf => funext (fun k => eq_of_heq (hq leaf k))) + cases hqq + rfl + +end NativeTransport + +variable {branch rows repeats : Nat → Nat} {n h t v m : Nat} [NeZero m] + {upper : Nodes branch n} {d : HierarchicalFrozenTables.LowerNodes upper (h + 1)} + (S : CleanDecoderRate.Setup branch rows repeats n h t v m upper d) + (hbranch : ∀ k < n, 0 < branch k) + +def highEvent (s : Nat) (x : CleanDecoderRate.Sample S) + (answer : CleanPhysicalDecoderLaw.Answers + (CleanNativeReplay.leftSlots S x) (CleanNativeReplay.rightSlots S x) upper) : Bool := + ProjectedFiberSquare.highMeeting + (CleanNativeReplay.leftSlots S x) (CleanNativeReplay.rightSlots S x) + (CleanPhysicalDecoderLaw.physicalProjection S x) upper (h + 1) hbranch d s + answer.1 answer.2 + +theorem physical_fullRank (x : CleanDecoderRate.Sample S) + (answer : CleanDecoderPairLaw.Pair S x) : + HierarchicalDecoderTables.fullRank (CleanNativeReplay.leftSlots S x) upper (h + 1) d + (HierarchicalLeftDecoder.output (CleanNativeReplay.leftSlots S x) upper (h + 1) + hbranch d (CleanPhysicalDecoderLaw.physicalAnswerEquiv S x answer).1) = + DecoderRankSplit.nativeRank S hbranch x answer := by + exact (fullRank_answerEquiv _ _ _ _ (CleanNativeReplay.leftSlots_eq S x) + (CleanNativeReplay.rightSlots_eq S x) upper (h + 1) hbranch d answer).trans + (DecoderPairHighOutput.nativeRank_eq_fullRank S hbranch x answer).symm + +theorem highEvent_physicalAnswerEquiv (s : Nat) (x : CleanDecoderRate.Sample S) + (answer : CleanDecoderPairLaw.Pair S x) : + highEvent S hbranch s x (CleanPhysicalDecoderLaw.physicalAnswerEquiv S x answer) = + DecoderRankSplit.highAgrees S hbranch s x answer := by + exact (highMeeting_answerEquiv _ _ _ _ (CleanNativeReplay.leftSlots_eq S x) + (CleanNativeReplay.rightSlots_eq S x) upper (h + 1) hbranch d _ _ + (CleanPhysicalDecoderLaw.projection_heq S x) s answer).trans + (DecoderPairHighOutput.highAgrees_eq_highMeeting S hbranch s x answer).symm + +variable {Sample : OriginalDecoderMark.SlotFamily branch n t → Type*} + [∀ slots, Fintype (Sample slots)] + (F : OriginalDecoderMark.Family branch rows n t Sample) (κ : ℝ) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (r : Nat) (ρ : ℝ) (A : ManyGoodRows.RowMap (Block rows upper) r) + (W : Submodule (ZMod 2) (Block rows upper)) + (a : Block rows (CleanPhysicalDecoderLaw.lower S)) (threshold : ℝ) + (cube : Nat) (hcube : 0 < cube) + +theorem probability_pairKernel (s : Nat) (x : CleanDecoderRate.Sample S) + (hx : (CleanDecoderRate.rawLaw S cube hcube).weight x ≠ 0) : + (CleanPhysicalDecoderLaw.pairKernel S F κ σ r ρ A W a threshold x).probability + (highEvent S hbranch s x) = + (CleanDecoderPairLaw.pairKernel S σ (CleanPhysicalDecoderLaw.useful S F κ) + r ρ A W a threshold x).probability (DecoderRankSplit.highAgrees S hbranch s x) := by + rw [CleanPhysicalDecoderLaw.probability_pairKernel S F κ σ r ρ A W a threshold + cube hcube x hx] + congr 1 + funext answer + exact highEvent_physicalAnswerEquiv S hbranch s x answer + +theorem mean_probability_eq (s : Nat) : + (CleanDecoderRate.rawLaw S cube hcube).expectation (fun x => + (CleanPhysicalDecoderLaw.pairKernel S F κ σ r ρ A W a threshold x).probability + (highEvent S hbranch s x)) = + (CleanDecoderPairLaw.pairLaw S σ (CleanPhysicalDecoderLaw.useful S F κ) + r ρ A W a threshold cube hcube).probability + (fun z => DecoderRankSplit.highAgrees S hbranch s z.1 z.2) := by + rw [CleanDecoderPairLaw.pairLaw, CompletionSoundness.sigmaLaw_probability] + unfold FiniteDistribution.expectation + apply Finset.sum_congr rfl + intro x _ + by_cases hx : (CleanDecoderRate.rawLaw S cube hcube).weight x = 0 + · simp only [hx, zero_mul] + · exact congrArg (fun prob : ℝ => (CleanDecoderRate.rawLaw S cube hcube).weight x * prob) + (probability_pairKernel S hbranch F κ σ r ρ A W a threshold cube hcube s x hx) + +end +end PerfectCompleteness.CleanPhysicalHighEvent + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanPhysicalProjectedMeeting.lean b/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanPhysicalProjectedMeeting.lean new file mode 100644 index 0000000000000000000000000000000000000000..59dd371995ad7a76ffd35cbedb5b05916415006b --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanPhysicalProjectedMeeting.lean @@ -0,0 +1,174 @@ +import OAI.Computability.PerfectCompleteness.Decoding.CleanPhysicalDecoderLaw +import OAI.Computability.PerfectCompleteness.Decoding.ProjectedRawDecoderLaw +import OAI.Computability.PerfectCompleteness.Foundations.WholeArrayRawAssembly + +namespace OAI + +section + +namespace PerfectCompleteness.CleanPhysicalProjectedMeeting + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +abbrev F2 := ZMod 2 + +attribute [local instance] CleanPhysicalDecoderLaw.nativeLeftFintype RightDecoder.scalarFintype + +section TapeCast + +variable {branch rows repeats : Nat → Nat} {n t : Nat} + +private theorem evaluate_uncastTape + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (upper lower : Nodes branch n) (cut : OwnInputReference.Cut upper lower) + {k : Nat} (hk : Nodes.height lower = k) + (tape : WholeArraySampler.Tape rows repeats + ((Nodes.path upper).append (hk ▸ cut.path)) slots) : + WholeArraySampler.evaluate rows repeats ((Nodes.path upper).append cut.path) slots + (CleanPhysicalDecoderLaw.uncastTape slots upper lower cut hk tape) = + WholeArraySampler.evaluate rows repeats ((Nodes.path upper).append (hk ▸ cut.path)) slots tape := by + cases hk + rfl + +end TapeCast + +variable {branch rows repeats : Nat → Nat} {n h t v m : Nat} [NeZero m] + {upper : Nodes branch n} {d : HierarchicalFrozenTables.LowerNodes upper (h + 1)} + (S : CleanDecoderRate.Setup branch rows repeats n h t v m upper d) + +abbrev lower := CleanPhysicalDecoderLaw.lower S + +def rawSample (W : Submodule F2 (Block rows upper)) (x : CleanDecoderRate.Sample S) : + OwnInputReference.RawSample (CleanNativeReplay.rightSlots S x) rows upper (lower S) W repeats S.cut := + WholeArrayInteriorOwnInputLaw.exposedRead rows repeats (CleanNativeReplay.rightSlots S x) + upper (lower S) S.cut W + (CleanPhysicalDecoderLaw.uncastTape (CleanNativeReplay.rightSlots S x) upper (lower S) S.cut + (CleanDecoderContext.lowerHeight upper d) (CleanPhysicalDecoderLaw.rightWholeTape S x)) + +abbrev visible (W : Submodule F2 (Block rows upper)) (x : CleanDecoderRate.Sample S) := + (rawSample S W x).2 + +theorem raw_arrays (W : Submodule F2 (Block rows upper)) (x : CleanDecoderRate.Sample S) : + OwnInputRawAssembly.arrays (CleanNativeReplay.rightSlots S x) rows upper (lower S) W + repeats S.cut (rawSample S W x) = CleanPhysicalDecoderLaw.rightArrays S x := by + have hraw := WholeArrayRawAssembly.arrays_exposedRead rows repeats + (CleanNativeReplay.rightSlots S x) upper (lower S) S.cut W + (CleanPhysicalDecoderLaw.uncastTape (CleanNativeReplay.rightSlots S x) upper (lower S) S.cut + (CleanDecoderContext.lowerHeight upper d) (CleanPhysicalDecoderLaw.rightWholeTape S x)) + exact hraw.trans (evaluate_uncastTape (CleanNativeReplay.rightSlots S x) upper (lower S) S.cut + (CleanDecoderContext.lowerHeight upper d) (CleanPhysicalDecoderLaw.rightWholeTape S x)) + +theorem projected_raw_arrays (W : Submodule F2 (Block rows upper)) + (x : CleanDecoderRate.Sample S) : + ProjectedRawAssembly.arrays (CleanNativeReplay.leftSlots S x) (CleanNativeReplay.rightSlots S x) + (CleanPhysicalDecoderLaw.physicalProjection S x) rows upper (lower S) W repeats S.cut + (rawSample S W x) = CleanPhysicalDecoderLaw.leftArrays S x := by + unfold ProjectedRawAssembly.arrays + rw [raw_arrays] + exact (CleanPhysicalCanonicalQuery.arrays_pullback rows repeats (CleanDecoderRate.path S) + S.outside S.placeholder S.clauses S.designated x S.exterior).symm + +theorem rightInput_eq_readInput (W : Submodule F2 (Block rows upper)) + (a : Block rows (lower S)) (x : CleanDecoderRate.Sample S) : + CleanPhysicalDecoderLaw.rightInput S W a x = + OwnInputReference.readInput (CleanNativeReplay.rightSlots S x) rows upper (lower S) W a + (OwnInputRawAssembly.scalarEval (CleanNativeReplay.rightSlots S x) upper (lower S) + repeats S.cut) (visible S W x) := + CleanPhysicalDecoderLaw.rightInput_eq_ownInput S W a x + +variable {Sample : OriginalDecoderMark.SlotFamily branch n t → Type*} + [∀ slots, Fintype (Sample slots)] + (F : OriginalDecoderMark.Family branch rows n t Sample) (κ : ℝ) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (r : Nat) (ρ : ℝ) (A : ManyGoodRows.RowMap (Block rows upper) r) + (a : Block rows (lower S)) (threshold : ℝ) + +theorem leftLaw_eq_visible (x : CleanDecoderRate.Sample S) : + CleanPhysicalDecoderLaw.leftLaw S F κ σ r ρ A x = + HierarchicalProjectedMeeting.leftLaw + (CleanNativeReplay.leftSlots S x) (CleanNativeReplay.rightSlots S x) + (CleanPhysicalDecoderLaw.physicalProjection S x) upper (h + 1) + (HierarchicalProjectedRawPrediction.visibleBackground + (CleanNativeReplay.leftSlots S x) (CleanNativeReplay.rightSlots S x) + (CleanPhysicalDecoderLaw.physicalProjection S x) rows upper (lower S) A repeats S.cut + (visible S (LinearMap.ker A) x)) + (F.original (CleanNativeReplay.leftSlots S x)) + (F.arrays (CleanNativeReplay.leftSlots S x)) + (F.lowerEvent (CleanNativeReplay.leftSlots S x)) κ σ ρ A + (HierarchicalProjectedRawPrediction.known (CleanNativeReplay.rightSlots S x) + rows upper (lower S) A repeats S.cut (visible S (LinearMap.ker A) x)) := by + change CleanPhysicalDecoderLaw.adviceLaw F (CleanNativeReplay.leftSlots S x) upper (h + 1) κ + (CleanPhysicalDecoderLaw.leftArrays S x) σ r ρ A = _ + rw [← projected_raw_arrays S (LinearMap.ker A) x] + exact ProjectedRawDecoderLaw.adviceLaw_eq_leftLaw + (CleanNativeReplay.leftSlots S x) (CleanNativeReplay.rightSlots S x) + (CleanPhysicalDecoderLaw.physicalProjection S x) rows upper (lower S) (h + 1) + (F.original (CleanNativeReplay.leftSlots S x)) + (F.arrays (CleanNativeReplay.leftSlots S x)) + (F.lowerEvent (CleanNativeReplay.leftSlots S x)) κ σ ρ A repeats S.cut + (rawSample S (LinearMap.ker A) x) + +def visiblePairKernel (x : CleanDecoderRate.Sample S) := + (HierarchicalProjectedMeeting.leftLaw + (CleanNativeReplay.leftSlots S x) (CleanNativeReplay.rightSlots S x) + (CleanPhysicalDecoderLaw.physicalProjection S x) upper (h + 1) + (HierarchicalProjectedRawPrediction.visibleBackground + (CleanNativeReplay.leftSlots S x) (CleanNativeReplay.rightSlots S x) + (CleanPhysicalDecoderLaw.physicalProjection S x) rows upper (lower S) A repeats S.cut + (visible S (LinearMap.ker A) x)) + (F.original (CleanNativeReplay.leftSlots S x)) + (F.arrays (CleanNativeReplay.leftSlots S x)) + (F.lowerEvent (CleanNativeReplay.leftSlots S x)) κ σ ρ A + (HierarchicalProjectedRawPrediction.known (CleanNativeReplay.rightSlots S x) + rows upper (lower S) A repeats S.cut (visible S (LinearMap.ker A) x))).product + (RightDecoder.law (CleanNativeReplay.rightSlots S x) rows upper (lower S) + (LinearMap.ker A) a repeats S.cut σ + (OwnInputReference.readInput (CleanNativeReplay.rightSlots S x) rows upper (lower S) + (LinearMap.ker A) a + (OwnInputRawAssembly.scalarEval (CleanNativeReplay.rightSlots S x) upper (lower S) + repeats S.cut) (visible S (LinearMap.ker A) x)) threshold) + +theorem pairKernel_eq_visible (x : CleanDecoderRate.Sample S) : + CleanPhysicalDecoderLaw.pairKernel S F κ σ r ρ A (LinearMap.ker A) a threshold x = + visiblePairKernel S F κ σ r ρ A a threshold x := by + unfold CleanPhysicalDecoderLaw.pairKernel visiblePairKernel + rw [leftLaw_eq_visible] + unfold CleanPhysicalDecoderLaw.rightLaw + rw [rightInput_eq_readInput] + +theorem meeting_probability_eq (cube : Nat) (hcube : 0 < cube) + (x : CleanDecoderRate.Sample S) + (hx : (CleanDecoderRate.rawLaw S cube hcube).weight x ≠ 0) : + (visiblePairKernel S F κ σ r ρ A a threshold x).probability + (fun answer => decide ((ProjectedNodeEmbedding.intoOriginal + (CleanPhysicalDecoderLaw.physicalProjection S x) upper).dualMap answer.1 = answer.2)) = + (CleanDecoderPairLaw.pairKernel S σ (CleanPhysicalDecoderLaw.useful S F κ) + r ρ A (LinearMap.ker A) a threshold x).probability + (fun answer => decide (answer.2 = DecoderSourcePullback.upperTarget + (CleanDecoderOddLists.fullProjection (CleanDecoderPairLaw.context S x) + (CleanDecoderPairLaw.occurrences S x)) upper answer.1)) := by + rw [← pairKernel_eq_visible] + have hevent : + (fun answer : CleanPhysicalDecoderLaw.Answers + (CleanNativeReplay.leftSlots S x) (CleanNativeReplay.rightSlots S x) upper => + decide ((ProjectedNodeEmbedding.intoOriginal + (CleanPhysicalDecoderLaw.physicalProjection S x) upper).dualMap answer.1 = answer.2)) = + (fun answer => decide (answer.2 = DecoderSourcePullback.upperTarget + (CleanPhysicalDecoderLaw.physicalProjection S x) upper answer.1)) := by + funext answer + rw [ProjectedNodeEmbedding.dualMap_eq_upperTarget] + exact decide_eq_decide.mpr eq_comm + rw [hevent] + exact CleanPhysicalDecoderLaw.meeting_probability_eq S F κ σ r ρ A (LinearMap.ker A) + a threshold cube hcube x hx + +end +end PerfectCompleteness.CleanPhysicalProjectedMeeting + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanPhysicalRawChildren.lean b/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanPhysicalRawChildren.lean new file mode 100644 index 0000000000000000000000000000000000000000..cc7d1e151f37cfab9fb32a7a47bd68cd6b8054dd --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanPhysicalRawChildren.lean @@ -0,0 +1,101 @@ +import OAI.Computability.PerfectCompleteness.Decoding.LowerProjectedOriginalSuccessLemmas +import OAI.Computability.PerfectCompleteness.Repetition.CleanPhysicalReplayLaw + +namespace OAI + +section + +namespace PerfectCompleteness.CleanPhysicalRawChildren + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +variable {branch : Nat → Nat} {n m t : Nat} + (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (outside : Slots branch n → Fin t → MixedSupport.Slot) + (placeholder inside : Slots branch (m + 1) → Fin t → MixedSupport.Slot) + +def fillChildren + (children : CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) inside rows) : + CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) + (WholeCutGrouping.cutSlots p (CutSlotAssembly.fill p outside inside)) rows := + fun i => CleanPhysicalReplay.fillChild rows repeats p outside inside i (children i) + +theorem fillChildren_eq_childrenEquiv : + fillChildren rows repeats p outside inside = + (FilledUniformSampler.childrenEquiv rows repeats p outside inside : _ → _) := by + funext children i + exact eq_of_heq ((CleanPhysicalReplay.fillChild_heq rows repeats p outside inside i + (children i)).trans + (FilledUniformSampler.childrenEquiv_heq rows repeats p outside inside children i).symm) + +theorem fillChildren_law : + (CutChildGrouping.rawLaw (C := WholeCutCalls.Index rows repeats p) inside rows).pushforward + (fillChildren rows repeats p outside inside) = + CutChildGrouping.rawLaw (C := WholeCutCalls.Index rows repeats p) + (WholeCutGrouping.cutSlots p (CutSlotAssembly.fill p outside inside)) rows := by + rw [fillChildren_eq_childrenEquiv] + simp only [CutChildGrouping.rawLaw, UniformLinearImage.law_uniform] + rw [FiniteDistribution.pushforward_equiv] + apply FiniteDistribution.eq_of_weight_eq + intro children + change 1 / (Fintype.card + (CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) inside rows) : ℝ) = + 1 / (Fintype.card (CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) + (WholeCutGrouping.cutSlots p (CutSlotAssembly.fill p outside inside)) rows) : ℝ) + rw [Fintype.card_congr (FilledUniformSampler.childrenEquiv rows repeats p outside inside)] + +theorem expectation_physicalTape + (external : CleanPhysicalReplay.Exterior rows repeats p outside placeholder) + (statistic : WholeCutSampler.Tape rows repeats p (CutSlotAssembly.fill p outside inside) → ℝ) : + (CutChildGrouping.rawLaw (C := WholeCutCalls.Index rows repeats p) inside rows).expectation + (fun children => statistic + (CleanPhysicalReplay.physicalTape rows repeats p outside placeholder inside external children)) = + (CutChildGrouping.rawLaw (C := WholeCutCalls.Index rows repeats p) + (WholeCutGrouping.cutSlots p (CutSlotAssembly.fill p outside inside)) rows).expectation + (fun children => statistic + ((WholeCutGrouping.splitTape rows repeats p (CutSlotAssembly.fill p outside inside)).symm + (CleanPhysicalReplay.exteriorAt rows repeats p outside placeholder inside external, + children))) := by + have h := congrArg + (fun law : FiniteDistribution (CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) + (WholeCutGrouping.cutSlots p (CutSlotAssembly.fill p outside inside)) rows) => + law.expectation (fun children => statistic + ((WholeCutGrouping.splitTape rows repeats p (CutSlotAssembly.fill p outside inside)).symm + (CleanPhysicalReplay.exteriorAt rows repeats p outside placeholder inside external, + children)))) + (fillChildren_law rows repeats p outside inside) + rw [FiniteDistribution.expectation_pushforward] at h + exact h + +theorem expectation_lowerTape (upper : Nodes branch n) + (pDown : Path branch (Nodes.height upper) (m + 1)) + (external : CleanPhysicalReplay.Exterior rows repeats + ((Nodes.path upper).append pDown) outside placeholder) + (statistic : WholeCutSampler.Tape rows repeats ((Nodes.path upper).append pDown) + (CutSlotAssembly.fill ((Nodes.path upper).append pDown) outside inside) → ℝ) : + (CutChildGrouping.rawLaw (C := WholeCutCalls.Index rows repeats ((Nodes.path upper).append pDown)) + inside rows).expectation (fun children => statistic + (CleanPhysicalReplay.physicalTape rows repeats ((Nodes.path upper).append pDown) + outside placeholder inside external children)) = + (CutChildGrouping.rawLaw + (C := LowerCutPair.Calls rows repeats ((Nodes.path upper).append pDown)) + (WholeCutGrouping.cutSlots ((Nodes.path upper).append pDown) + (CutSlotAssembly.fill ((Nodes.path upper).append pDown) outside inside)) rows).expectation + (fun children => statistic + (LowerPhysicalFiberSuccess.tape + (CutSlotAssembly.fill ((Nodes.path upper).append pDown) outside inside) upper pDown + (CleanPhysicalReplay.exteriorAt rows repeats ((Nodes.path upper).append pDown) + outside placeholder inside external) children)) := + expectation_physicalTape rows repeats ((Nodes.path upper).append pDown) + outside placeholder inside external statistic + +end +end PerfectCompleteness.CleanPhysicalRawChildren + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanPhysicalReplay.lean b/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanPhysicalReplay.lean new file mode 100644 index 0000000000000000000000000000000000000000..35b6d30fa5c4271026680eb84cebe7906a7cb9de --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanPhysicalReplay.lean @@ -0,0 +1,483 @@ +import OAI.Computability.PerfectCompleteness.Construction.SourceChildKernelLemmas +import OAI.Computability.PerfectCompleteness.Foundations.CutSlotOutside +import OAI.Computability.PerfectCompleteness.Foundations.WholeCutExteriorTransportLemmas +import OAI.Computability.PerfectCompleteness.Foundations.WholeCutReplayGroupingTransport +import OAI.Computability.PerfectCompleteness.Foundations.WholeCutReplayLemmas +import OAI.Computability.PerfectCompleteness.Repetition.CleanEndpointSlots +import OAI.Computability.PerfectCompleteness.Repetition.CleanRecordChildBlocks + +namespace OAI + +section + +namespace PerfectCompleteness.CleanPhysicalReplay + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +noncomputable section + +variable {branch : Nat → Nat} {root h t : Nat} + (rows repeats : Nat → Nat) (p : Path branch root (h + 1)) + (outside : Slots branch root → Fin t → MixedSupport.Slot) + (placeholder : Slots branch (h + 1) → Fin t → MixedSupport.Slot) + +abbrev Exterior := WholeCutGrouping.Exterior rows repeats p + (CutSlotAssembly.fill p outside placeholder) + +def exteriorAt (inside : Slots branch (h + 1) → Fin t → MixedSupport.Slot) + (external : Exterior rows repeats p outside placeholder) : + WholeCutGrouping.Exterior rows repeats p (CutSlotAssembly.fill p outside inside) := + WholeCutExteriorTransport.equiv rows repeats p + (CutSlotAssembly.fill p outside placeholder) (CutSlotAssembly.fill p outside inside) + (CutSlotAssembly.fill_outside_eq p outside placeholder inside) external + +theorem cutSlots_fill (inside : Slots branch (h + 1) → Fin t → MixedSupport.Slot) : + WholeCutGrouping.cutSlots p (CutSlotAssembly.fill p outside inside) = inside := by + funext s + exact CutSlotAssembly.fill_at_cut p outside inside s + +theorem childSlots_fill (inside : Slots branch (h + 1) → Fin t → MixedSupport.Slot) + (i : Fin (branch h)) : + childSlots (WholeCutGrouping.cutSlots p (CutSlotAssembly.fill p outside inside)) i = + childSlots inside i := + congrArg (fun ss => childSlots ss i) (cutSlots_fill p outside inside) + +def fillChild (inside : Slots branch (h + 1) → Fin t → MixedSupport.Slot) + (i : Fin (branch h)) + (block : CutChildGrouping.Child (C := WholeCutCalls.Index rows repeats p) inside rows i) : + CutChildGrouping.Child (C := WholeCutCalls.Index rows repeats p) + (WholeCutGrouping.cutSlots p (CutSlotAssembly.fill p outside inside)) rows i := + cast (congrArg (SourceChildKernel.Block (WholeCutCalls.Index rows repeats p) rows) + (childSlots_fill p outside inside i).symm) block + +theorem fillChild_heq (inside : Slots branch (h + 1) → Fin t → MixedSupport.Slot) + (i : Fin (branch h)) + (block : CutChildGrouping.Child (C := WholeCutCalls.Index rows repeats p) inside rows i) : + HEq (fillChild rows repeats p outside inside i block) block := + cast_heq _ _ + +private theorem cast_zeroBlock {n : Nat} {C : Type*} [Fintype C] + (slots target : Slots branch n → Fin t → MixedSupport.Slot) (hs : slots = target) : + cast (congrArg (SourceChildKernel.Block C rows) hs) + (SourceChildKernel.zeroBlock (C := C) rows slots) = + SourceChildKernel.zeroBlock rows target := by + cases hs + rfl + +theorem fillChild_zero (inside : Slots branch (h + 1) → Fin t → MixedSupport.Slot) + (i : Fin (branch h)) : + fillChild rows repeats p outside inside i + (SourceChildKernel.zeroBlock rows (childSlots inside i)) = + SourceChildKernel.zeroBlock rows + (childSlots (WholeCutGrouping.cutSlots p (CutSlotAssembly.fill p outside inside)) i) := + cast_zeroBlock rows _ _ (childSlots_fill p outside inside i).symm + +def retainedAt (inside : Slots branch (h + 1) → Fin t → MixedSupport.Slot) + (clean : Fin (branch h) → Prop) + (children : (i : {i : Fin (branch h) // ¬ clean i}) → + CutChildGrouping.Child (C := WholeCutCalls.Index rows repeats p) inside rows i.val) : + WholeCutReplayGrouping.RetainedChildren rows repeats p + (CutSlotAssembly.fill p outside inside) clean := + fun i => fillChild rows repeats p outside inside i.val (children i) + +def assembleAt (inside : Slots branch (h + 1) → Fin t → MixedSupport.Slot) + (clean : Fin (branch h) → Prop) + (external : Exterior rows repeats p outside placeholder) + (children : (i : {i : Fin (branch h) // ¬ clean i}) → + CutChildGrouping.Child (C := WholeCutCalls.Index rows repeats p) inside rows i.val) : + WholeCutReplay.Tape rows repeats p (CutSlotAssembly.fill p outside inside) clean := + WholeCutReplayGrouping.assemble rows repeats p (CutSlotAssembly.fill p outside inside) clean + (exteriorAt rows repeats p outside placeholder inside external) + (retainedAt rows repeats p outside inside clean children) + +def physicalTape (inside : Slots branch (h + 1) → Fin t → MixedSupport.Slot) + (external : Exterior rows repeats p outside placeholder) + (children : CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) inside rows) : + WholeCutSampler.Tape rows repeats p (CutSlotAssembly.fill p outside inside) := + (WholeCutGrouping.splitTape rows repeats p (CutSlotAssembly.fill p outside inside)).symm + (exteriorAt rows repeats p outside placeholder inside external, + fun i => fillChild rows repeats p outside inside i (children i)) + +theorem assembleAt_eq_erase (inside : Slots branch (h + 1) → Fin t → MixedSupport.Slot) + (clean : Fin (branch h) → Prop) + (external : Exterior rows repeats p outside placeholder) + (children : CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) inside rows) : + assembleAt rows repeats p outside placeholder inside clean external (fun i => children i.val) = + WholeCutReplay.erase rows repeats p (CutSlotAssembly.fill p outside inside) clean + (physicalTape rows repeats p outside placeholder inside external children) := by + have h := WholeCutReplayGrouping.assemble_splitTape rows repeats p + (CutSlotAssembly.fill p outside inside) clean + (physicalTape rows repeats p outside placeholder inside external children) + change WholeCutReplayGrouping.assemble rows repeats p (CutSlotAssembly.fill p outside inside) clean + (exteriorAt rows repeats p outside placeholder inside external) + (fun child => fillChild rows repeats p outside inside child.val (children child.val)) = + WholeCutReplay.erase rows repeats p (CutSlotAssembly.fill p outside inside) clean + (physicalTape rows repeats p outside placeholder inside external children) + simpa only [physicalTape, Equiv.apply_symm_apply] using h + +theorem physicalTape_grouped_zero + (inside : Slots branch (h + 1) → Fin t → MixedSupport.Slot) + (clean : Fin (branch h) → Prop) + (external : Exterior rows repeats p outside placeholder) + (children : CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) inside rows) + (hzero : ∀ i, clean i → children i = + SourceChildKernel.zeroBlock rows (childSlots inside i)) : + WholeCutZero.GroupedAtClean rows repeats p (CutSlotAssembly.fill p outside inside) clean + (physicalTape rows repeats p outside placeholder inside external children) := by + intro i hi + have hz : fillChild rows repeats p outside inside i (children i) = + SourceChildKernel.zeroBlock rows + (childSlots (WholeCutGrouping.cutSlots p (CutSlotAssembly.fill p outside inside)) i) := by + rw [hzero i hi] + exact fillChild_zero rows repeats p outside inside i + change (∀ q, ((WholeCutGrouping.splitTape rows repeats p + (CutSlotAssembly.fill p outside inside) + (physicalTape rows repeats p outside placeholder inside external children)).2 i).1 q = 0) ∧ _ + simp only [physicalTape, Equiv.apply_symm_apply] + rw [hz] + exact ⟨fun _ => rfl, fun _ _ => rfl⟩ + +private theorem exteriorAt_heq + (inside : Slots branch (h + 1) → Fin t → MixedSupport.Slot) + (external : Exterior rows repeats p outside placeholder) : + HEq (exteriorAt rows repeats p outside placeholder inside external) external := + cast_heq _ _ + +theorem transport_assembleAt + (inside target : Slots branch (h + 1) → Fin t → MixedSupport.Slot) + (clean : Fin (branch h) → Prop) + (hs : ∀ i, ¬ clean i → ∀ s, inside (i, s) = target (i, s)) + (external : Exterior rows repeats p outside placeholder) + (children : (i : {i : Fin (branch h) // ¬ clean i}) → + CutChildGrouping.Child (C := WholeCutCalls.Index rows repeats p) inside rows i.val) + (other : (i : {i : Fin (branch h) // ¬ clean i}) → + CutChildGrouping.Child (C := WholeCutCalls.Index rows repeats p) target rows i.val) + (hc : ∀ i, HEq (children i) (other i)) : + WholeCutReplayKeys.transportTape rows repeats p + (CutSlotAssembly.fill p outside inside) (CutSlotAssembly.fill p outside target) clean + (CutSlotAssembly.fill_kept_eq p outside inside target clean hs) + (assembleAt rows repeats p outside placeholder inside clean external children) = + assembleAt rows repeats p outside placeholder target clean external other := by + unfold assembleAt + rw [WholeCutReplayGroupingTransport.transport_assemble] + apply congrArg₂ (WholeCutReplayGrouping.assemble rows repeats p + (CutSlotAssembly.fill p outside target) clean) + · apply eq_of_heq + exact (cast_heq _ _).trans + ((exteriorAt_heq rows repeats p outside placeholder inside external).trans + (exteriorAt_heq rows repeats p outside placeholder target external).symm) + · funext i + apply eq_of_heq + exact (WholeCutReplayGroupingTransport.castChildren_apply_heq rows repeats p + (CutSlotAssembly.fill p outside inside) (CutSlotAssembly.fill p outside target) clean + (CutSlotAssembly.fill_kept_eq p outside inside target clean hs) + (retainedAt rows repeats p outside inside clean children) i).trans + ((fillChild_heq rows repeats p outside inside i.val (children i)).trans + ((hc i).trans (fillChild_heq rows repeats p outside target i.val (other i)).symm)) + +section Source + +variable {v m : Nat} [NeZero m] + (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch h) → Slots branch h) + +abbrev Record := CleanRecordChildBlocks.Record + (C := WholeCutCalls.Index rows repeats p) (t := t) rows clauses designated + +abbrev Sample := SourceChildKernel.Sample + (C := WholeCutCalls.Index rows repeats p) (t := t) rows clauses designated + +def leftRecord (record : Record (t := t) rows repeats p clauses designated) + (external : Exterior rows repeats p outside placeholder) : + WholeCutReplay.Tape rows repeats p + (CutSlotAssembly.fill p outside (CleanRecordChildBlocks.leftRef rows clauses designated record)) + (CleanRecordChildBlocks.clean rows clauses designated record) := + assembleAt rows repeats p outside placeholder + (CleanRecordChildBlocks.leftRef rows clauses designated record) + (CleanRecordChildBlocks.clean rows clauses designated record) external + (CleanRecordChildBlocks.leftChild rows clauses designated record) + +def rightRecord (record : Record (t := t) rows repeats p clauses designated) + (external : Exterior rows repeats p outside placeholder) : + WholeCutReplay.Tape rows repeats p + (CutSlotAssembly.fill p outside (CleanRecordChildBlocks.rightRef rows clauses designated record)) + (CleanRecordChildBlocks.clean rows clauses designated record) := + assembleAt rows repeats p outside placeholder + (CleanRecordChildBlocks.rightRef rows clauses designated record) + (CleanRecordChildBlocks.clean rows clauses designated record) external + (CleanRecordChildBlocks.rightChild rows clauses designated record) + +def leftInside (x : Sample (t := t) rows repeats p clauses designated) : + Slots branch (h + 1) → Fin t → MixedSupport.Slot := + SourceChildKernel.parentLeftSlots clauses designated (fun i => ((x i).1, (x i).2.1)) + +def rightInside (x : Sample (t := t) rows repeats p clauses designated) : + Slots branch (h + 1) → Fin t → MixedSupport.Slot := + SourceChildKernel.parentRightSlots rows clauses designated + (fun i => ((x i).1, (x i).2.1)) (fun i => (x i).2.2) + +def leftBlocks (x : Sample (t := t) rows repeats p clauses designated) : + CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) + (leftInside rows repeats p clauses designated x) rows := + SourceChildKernel.leftChildren rows clauses designated + (fun i => ((x i).1, (x i).2.1)) (fun i => (x i).2.2) + +def rightBlocks (x : Sample (t := t) rows repeats p clauses designated) : + CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) + (rightInside rows repeats p clauses designated x) rows := + SourceChildKernel.rightChildren rows clauses designated + (fun i => ((x i).1, (x i).2.1)) (fun i => (x i).2.2) + +def leftTape (x : Sample (t := t) rows repeats p clauses designated) + (external : Exterior rows repeats p outside placeholder) : + WholeCutSampler.Tape rows repeats p + (CutSlotAssembly.fill p outside (leftInside rows repeats p clauses designated x)) := + physicalTape rows repeats p outside placeholder (leftInside rows repeats p clauses designated x) + external (leftBlocks rows repeats p clauses designated x) + +def rightTape (x : Sample (t := t) rows repeats p clauses designated) + (external : Exterior rows repeats p outside placeholder) : + WholeCutSampler.Tape rows repeats p + (CutSlotAssembly.fill p outside (rightInside rows repeats p clauses designated x)) := + physicalTape rows repeats p outside placeholder (rightInside rows repeats p clauses designated x) + external (rightBlocks rows repeats p clauses designated x) + +theorem leftInside_nonclean (record : Record (t := t) rows repeats p clauses designated) + (x : Sample (t := t) rows repeats p clauses designated) + (hevent : CleanRecordChildBlocks.event rows clauses designated record x = true) + (i : Fin (branch h)) (hi : ¬ CleanRecordChildBlocks.clean rows clauses designated record i) + (s : Slots branch h) : + CleanRecordChildBlocks.leftRef rows clauses designated record (i, s) = + leftInside rows repeats p clauses designated x (i, s) := + congrFun (CleanRecordChildBlocks.leftRef_childSlots_event + rows clauses designated record x hevent ⟨i, hi⟩) s + +theorem rightInside_nonclean (record : Record (t := t) rows repeats p clauses designated) + (x : Sample (t := t) rows repeats p clauses designated) + (hevent : CleanRecordChildBlocks.event rows clauses designated record x = true) + (i : Fin (branch h)) (hi : ¬ CleanRecordChildBlocks.clean rows clauses designated record i) + (s : Slots branch h) : + CleanRecordChildBlocks.rightRef rows clauses designated record (i, s) = + rightInside rows repeats p clauses designated x (i, s) := + congrFun (CleanRecordChildBlocks.rightRef_childSlots_event + rows clauses designated record x hevent ⟨i, hi⟩) s + +theorem leftRecord_eq_erase (record : Record (t := t) rows repeats p clauses designated) + (x : Sample (t := t) rows repeats p clauses designated) + (hevent : CleanRecordChildBlocks.event rows clauses designated record x = true) + (external : Exterior rows repeats p outside placeholder) : + WholeCutReplayKeys.transportTape rows repeats p + (CutSlotAssembly.fill p outside (CleanRecordChildBlocks.leftRef rows clauses designated record)) + (CutSlotAssembly.fill p outside (leftInside rows repeats p clauses designated x)) + (CleanRecordChildBlocks.clean rows clauses designated record) + (CutSlotAssembly.fill_kept_eq p outside _ _ _ + (leftInside_nonclean rows repeats p clauses designated record x hevent)) + (leftRecord rows repeats p outside placeholder clauses designated record external) = + WholeCutReplay.erase rows repeats p + (CutSlotAssembly.fill p outside (leftInside rows repeats p clauses designated x)) + (CleanRecordChildBlocks.clean rows clauses designated record) + (leftTape rows repeats p outside placeholder clauses designated x external) := by + exact (transport_assembleAt rows repeats p outside placeholder _ _ _ + (leftInside_nonclean rows repeats p clauses designated record x hevent) external _ _ + (CleanRecordChildBlocks.leftChild_event_heq rows clauses designated record x hevent)).trans + (assembleAt_eq_erase rows repeats p outside placeholder _ _ external + (leftBlocks rows repeats p clauses designated x)) + +theorem rightRecord_eq_erase (record : Record (t := t) rows repeats p clauses designated) + (x : Sample (t := t) rows repeats p clauses designated) + (hevent : CleanRecordChildBlocks.event rows clauses designated record x = true) + (external : Exterior rows repeats p outside placeholder) : + WholeCutReplayKeys.transportTape rows repeats p + (CutSlotAssembly.fill p outside (CleanRecordChildBlocks.rightRef rows clauses designated record)) + (CutSlotAssembly.fill p outside (rightInside rows repeats p clauses designated x)) + (CleanRecordChildBlocks.clean rows clauses designated record) + (CutSlotAssembly.fill_kept_eq p outside _ _ _ + (rightInside_nonclean rows repeats p clauses designated record x hevent)) + (rightRecord rows repeats p outside placeholder clauses designated record external) = + WholeCutReplay.erase rows repeats p + (CutSlotAssembly.fill p outside (rightInside rows repeats p clauses designated x)) + (CleanRecordChildBlocks.clean rows clauses designated record) + (rightTape rows repeats p outside placeholder clauses designated x external) := by + exact (transport_assembleAt rows repeats p outside placeholder _ _ _ + (rightInside_nonclean rows repeats p clauses designated record x hevent) external _ _ + (CleanRecordChildBlocks.rightChild_event_heq rows clauses designated record x hevent)).trans + (assembleAt_eq_erase rows repeats p outside placeholder _ _ external + (rightBlocks rows repeats p clauses designated x)) + +variable + (μ : Fin (branch h) → FiniteDistribution (SourceQuestionReconstruction.SourceTuple m t)) + (ν : (i : Fin (branch h)) → FiniteDistribution + (SourceChildKernel.Rest (m := m) (t := t) designated i)) + (flag : Fin (branch h) → FiniteDistribution Bool) + +omit [NeZero m] in +theorem rightBlocks_zero (record : Record (t := t) rows repeats p clauses designated) + (x : Sample (t := t) rows repeats p clauses designated) + (hx : (SourceChildKernel.childrenLaw rows clauses designated μ ν flag).weight x ≠ 0) + (hevent : CleanRecordChildBlocks.event rows clauses designated record x = true) + (i : Fin (branch h)) (hi : CleanRecordChildBlocks.clean rows clauses designated record i) : + rightBlocks rows repeats p clauses designated x i = + SourceChildKernel.zeroBlock rows + (childSlots (rightInside rows repeats p clauses designated x) i) := + SourceChildKernel.childrenLaw_clean_zero rows clauses designated μ ν flag x hx i + (CleanRecordChildBlocks.childClean_of_clean rows clauses designated record x hevent i hi) + +omit [NeZero m] in +theorem leftBlocks_zero (record : Record (t := t) rows repeats p clauses designated) + (x : Sample (t := t) rows repeats p clauses designated) + (hx : (SourceChildKernel.childrenLaw rows clauses designated μ ν flag).weight x ≠ 0) + (hevent : CleanRecordChildBlocks.event rows clauses designated record x = true) + (i : Fin (branch h)) (hi : CleanRecordChildBlocks.clean rows clauses designated record i) : + leftBlocks rows repeats p clauses designated x i = + SourceChildKernel.zeroBlock rows + (childSlots (leftInside rows repeats p clauses designated x) i) := by + have hz := rightBlocks_zero rows repeats p clauses designated μ ν flag record x hx hevent i hi + change ChildAssemblyProjection.childPullback rows + (SourceChildKernel.parentProjection rows clauses designated + (fun j => ((x j).1, (x j).2.1)) (fun j => (x j).2.2)) i + (rightBlocks rows repeats p clauses designated x i) = _ + rw [hz] + exact map_zero _ + +omit [NeZero m] in +theorem rightTape_grouped_zero (record : Record (t := t) rows repeats p clauses designated) + (x : Sample (t := t) rows repeats p clauses designated) + (hx : (SourceChildKernel.childrenLaw rows clauses designated μ ν flag).weight x ≠ 0) + (hevent : CleanRecordChildBlocks.event rows clauses designated record x = true) + (external : Exterior rows repeats p outside placeholder) : + WholeCutZero.GroupedAtClean rows repeats p + (CutSlotAssembly.fill p outside (rightInside rows repeats p clauses designated x)) + (CleanRecordChildBlocks.clean rows clauses designated record) + (rightTape rows repeats p outside placeholder clauses designated x external) := + physicalTape_grouped_zero rows repeats p outside placeholder _ _ external _ + (rightBlocks_zero rows repeats p clauses designated μ ν flag record x hx hevent) + +omit [NeZero m] in +theorem leftTape_grouped_zero (record : Record (t := t) rows repeats p clauses designated) + (x : Sample (t := t) rows repeats p clauses designated) + (hx : (SourceChildKernel.childrenLaw rows clauses designated μ ν flag).weight x ≠ 0) + (hevent : CleanRecordChildBlocks.event rows clauses designated record x = true) + (external : Exterior rows repeats p outside placeholder) : + WholeCutZero.GroupedAtClean rows repeats p + (CutSlotAssembly.fill p outside (leftInside rows repeats p clauses designated x)) + (CleanRecordChildBlocks.clean rows clauses designated record) + (leftTape rows repeats p outside placeholder clauses designated x external) := + physicalTape_grouped_zero rows repeats p outside placeholder _ _ external _ + (leftBlocks_zero rows repeats p clauses designated μ ν flag record x hx hevent) + +private theorem response_of_erase {Y : Type*} + (slots target : Slots branch root → Fin t → MixedSupport.Slot) + (clean : Fin (branch h) → Prop) + (hs : ∀ s, CutSamplerKeyLocality.keptLeaf p clean s → slots s = target s) + (reference : WholeCutReplay.Tape rows repeats p slots clean) + (tape : WholeCutSampler.Tape rows repeats p target) + (htape : WholeCutReplayKeys.transportTape rows repeats p slots target clean hs reference = + WholeCutReplay.erase rows repeats p target clean tape) + (hzero : WholeCutZero.GroupedAtClean rows repeats p target clean tape) + (post : Output branch root rows → Y) + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch root t)) + (side : CanonicalKeys.Side) : + KeyStrategy.response labeling side (TreeCanonical.numberedSlots slots) + (WholeCutReplayKeys.query rows repeats p slots clean reference post) = + KeyStrategy.response labeling side (TreeCanonical.numberedSlots target) + (WholeCutKeyLocality.query rows repeats p target tape post) := by + have h := WholeCutReplayKeys.response_eq_transport rows repeats p slots target clean hs + reference post labeling side + rw [htape, WholeCutReplayKeys.query_erase rows repeats p target clean tape post hzero] at h + exact h + +theorem leftRecord_response_eq {Y : Type*} + (record : Record (t := t) rows repeats p clauses designated) + (x : Sample (t := t) rows repeats p clauses designated) + (hx : (SourceChildKernel.childrenLaw rows clauses designated μ ν flag).weight x ≠ 0) + (hevent : CleanRecordChildBlocks.event rows clauses designated record x = true) + (external : Exterior rows repeats p outside placeholder) + (post : Output branch root rows → Y) + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch root t)) + (side : CanonicalKeys.Side) : + KeyStrategy.response labeling side + (TreeCanonical.numberedSlots + (CutSlotAssembly.fill p outside (CleanRecordChildBlocks.leftRef rows clauses designated record))) + (WholeCutReplayKeys.query rows repeats p + (CutSlotAssembly.fill p outside (CleanRecordChildBlocks.leftRef rows clauses designated record)) + (CleanRecordChildBlocks.clean rows clauses designated record) + (leftRecord rows repeats p outside placeholder clauses designated record external) post) = + KeyStrategy.response labeling side + (TreeCanonical.numberedSlots + (CutSlotAssembly.fill p outside (leftInside rows repeats p clauses designated x))) + (WholeCutKeyLocality.query rows repeats p + (CutSlotAssembly.fill p outside (leftInside rows repeats p clauses designated x)) + (leftTape rows repeats p outside placeholder clauses designated x external) post) := + response_of_erase rows repeats p _ _ _ + (CutSlotAssembly.fill_kept_eq p outside _ _ _ + (leftInside_nonclean rows repeats p clauses designated record x hevent)) _ _ + (leftRecord_eq_erase rows repeats p outside placeholder clauses designated record x hevent external) + (leftTape_grouped_zero rows repeats p outside placeholder clauses designated μ ν flag + record x hx hevent external) post labeling side + +theorem rightRecord_response_eq {Y : Type*} + (record : Record (t := t) rows repeats p clauses designated) + (x : Sample (t := t) rows repeats p clauses designated) + (hx : (SourceChildKernel.childrenLaw rows clauses designated μ ν flag).weight x ≠ 0) + (hevent : CleanRecordChildBlocks.event rows clauses designated record x = true) + (external : Exterior rows repeats p outside placeholder) + (post : Output branch root rows → Y) + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch root t)) + (side : CanonicalKeys.Side) : + KeyStrategy.response labeling side + (TreeCanonical.numberedSlots + (CutSlotAssembly.fill p outside (CleanRecordChildBlocks.rightRef rows clauses designated record))) + (WholeCutReplayKeys.query rows repeats p + (CutSlotAssembly.fill p outside (CleanRecordChildBlocks.rightRef rows clauses designated record)) + (CleanRecordChildBlocks.clean rows clauses designated record) + (rightRecord rows repeats p outside placeholder clauses designated record external) post) = + KeyStrategy.response labeling side + (TreeCanonical.numberedSlots + (CutSlotAssembly.fill p outside (rightInside rows repeats p clauses designated x))) + (WholeCutKeyLocality.query rows repeats p + (CutSlotAssembly.fill p outside (rightInside rows repeats p clauses designated x)) + (rightTape rows repeats p outside placeholder clauses designated x external) post) := + response_of_erase rows repeats p _ _ _ + (CutSlotAssembly.fill_kept_eq p outside _ _ _ + (rightInside_nonclean rows repeats p clauses designated record x hevent)) _ _ + (rightRecord_eq_erase rows repeats p outside placeholder clauses designated record x hevent external) + (rightTape_grouped_zero rows repeats p outside placeholder clauses designated μ ν flag + record x hx hevent external) post labeling side + +end Source + +section OwnReplay + +variable {v m : Nat} [NeZero m] + (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch h) → Slots branch h) + (record : Record (t := t) rows repeats p clauses designated) + (external : Exterior rows repeats p outside placeholder) + +def leftReplay + (own : {i : Fin (branch h) // CleanRecordChildBlocks.clean rows clauses designated record i} → + Fin t → Fin m) := + CleanEndpointSlots.leftReplay clauses designated + (CleanRecordChildBlocks.clean rows clauses designated record) + (CleanRecordChildBlocks.visible rows clauses designated record) rows repeats p outside + (leftRecord rows repeats p outside placeholder clauses designated record external) own + +def rightReplay + (own : {i : Fin (branch h) // CleanRecordChildBlocks.clean rows clauses designated record i} → + Fin t → Fin v) := + CleanEndpointSlots.rightReplay clauses designated + (CleanRecordChildBlocks.clean rows clauses designated record) + (CleanRecordChildBlocks.visible rows clauses designated record) rows repeats p outside + (CleanRecordChildBlocks.projected rows clauses designated record) + (rightRecord rows repeats p outside placeholder clauses designated record external) own + +end OwnReplay + +end +end PerfectCompleteness.CleanPhysicalReplay + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanPhysicalReplayLaw.lean b/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanPhysicalReplayLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..f9fc7f5d601e107a5cff40642a72d034ce0d87e2 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanPhysicalReplayLaw.lean @@ -0,0 +1,75 @@ +import OAI.Computability.PerfectCompleteness.Repetition.CleanPhysicalReplay +import OAI.Computability.PerfectCompleteness.Sampling.FilledUniformSampler + +namespace OAI + +section + +namespace PerfectCompleteness.CleanPhysicalReplayLaw + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +noncomputable section + +variable {branch : Nat → Nat} {root h t : Nat} + (rows repeats : Nat → Nat) (p : Path branch root (h + 1)) + (outside : Slots branch root → Fin t → MixedSupport.Slot) + (placeholder inside : Slots branch (h + 1) → Fin t → MixedSupport.Slot) + +theorem physicalTape_eq_filledSplitEquiv + (external : CleanPhysicalReplay.Exterior rows repeats p outside placeholder) + (children : CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) inside rows) : + CleanPhysicalReplay.physicalTape rows repeats p outside placeholder inside external children = + FilledUniformSampler.filledSplitEquiv rows repeats p outside placeholder inside + (external, children) := by + apply congrArg (WholeCutGrouping.splitTape rows repeats p + (CutSlotAssembly.fill p outside inside)).symm + apply Prod.ext + · rfl + · funext i + exact eq_of_heq ((CleanPhysicalReplay.fillChild_heq rows repeats p outside inside i + (children i)).trans + (FilledUniformSampler.childrenEquiv_heq rows repeats p outside inside children i).symm) + +theorem physicalTape_law : + ((FiniteDistribution.uniform + (CleanPhysicalReplay.Exterior rows repeats p outside placeholder)).product + (CutChildGrouping.rawLaw (C := WholeCutCalls.Index rows repeats p) inside rows)).pushforward + (fun x => CleanPhysicalReplay.physicalTape rows repeats p outside placeholder inside x.1 x.2) = + WholeCutSampler.tapeLaw rows repeats p (CutSlotAssembly.fill p outside inside) := by + have hmap : (fun x : CleanPhysicalReplay.Exterior rows repeats p outside placeholder × + CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) inside rows => + CleanPhysicalReplay.physicalTape rows repeats p outside placeholder inside + x.1 x.2) = FilledUniformSampler.filledSplitEquiv rows repeats p outside placeholder inside := by + funext x + exact physicalTape_eq_filledSplitEquiv rows repeats p outside placeholder inside x.1 x.2 + rw [hmap] + exact FilledUniformSampler.filledSplitEquiv_tapeLaw rows repeats p outside placeholder inside + +theorem evaluate_physicalTape_law : + ((FiniteDistribution.uniform + (CleanPhysicalReplay.Exterior rows repeats p outside placeholder)).product + (CutChildGrouping.rawLaw (C := WholeCutCalls.Index rows repeats p) inside rows)).pushforward + (fun x => WholeCutSampler.evaluate rows repeats p (CutSlotAssembly.fill p outside inside) + (CleanPhysicalReplay.physicalTape rows repeats p outside placeholder inside x.1 x.2)) = + WholeArraySampler.law rows repeats p (CutSlotAssembly.fill p outside inside) := by + have hmap : (fun x : CleanPhysicalReplay.Exterior rows repeats p outside placeholder × + CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) inside rows => + WholeCutSampler.evaluate rows repeats p + (CutSlotAssembly.fill p outside inside) + (CleanPhysicalReplay.physicalTape rows repeats p outside placeholder inside x.1 x.2)) = + FilledUniformSampler.evaluate rows repeats p outside placeholder inside := by + funext x + exact congrArg (WholeCutSampler.evaluate rows repeats p (CutSlotAssembly.fill p outside inside)) + (physicalTape_eq_filledSplitEquiv rows repeats p outside placeholder inside x.1 x.2) + rw [hmap] + exact FilledUniformSampler.evaluate_law rows repeats p outside placeholder inside + +end +end PerfectCompleteness.CleanPhysicalReplayLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanRecordChildBlocks.lean b/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanRecordChildBlocks.lean new file mode 100644 index 0000000000000000000000000000000000000000..3a9c60b8516a8f5a178ede77efc31870e1bdb997 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanRecordChildBlocks.lean @@ -0,0 +1,305 @@ +import OAI.Computability.PerfectCompleteness.Construction.SourceChildKernelLemmas +import OAI.Computability.PerfectCompleteness.Repetition.CleanEndpointSlots + +namespace OAI + +section + +namespace PerfectCompleteness.CleanRecordChildBlocks + +noncomputable section + +open scoped Classical +open UniqueGamesTheorem.Foundations.Games +open RecursiveSpaces TreeSourceSpaces HierarchicalArrays +open SourceQuestionReconstruction + +variable {branch : Nat → Nat} {h t v m : Nat} {C : Type*} [Fintype C] + (rows : Nat → Nat) (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch h) → Slots branch h) + +abbrev Record := + CleanSourceRecord.Record + (D := SourceChildKernel.D (C := C) (t := t) rows clauses designated) designated + (SourceChildKernel.Factors (C := C) (t := t) rows clauses designated) + +abbrev Sample := SourceChildKernel.Sample (C := C) (t := t) rows clauses designated + +abbrev Row (i : Fin (branch h)) := SourceTuple m t × + (SourceChildKernel.Rest (m := m) (t := t) designated i × + SourceChildKernel.Raw (C := C) (t := t) rows clauses designated i) + +def clean (record : Record (C := C) (t := t) rows clauses designated) : + Fin (branch h) → Prop := + CleanSourceRecord.clean designated + (SourceChildKernel.Factors (C := C) (t := t) rows clauses designated) record + +def visible (record : Record (C := C) (t := t) rows clauses designated) : + Visible (E := SourceTuple m t) designated (clean rows clauses designated record) := + CleanSourceRecord.visible designated + (SourceChildKernel.Factors (C := C) (t := t) rows clauses designated) record + +def projected (record : Record (C := C) (t := t) rows clauses designated) : + Fin (branch h) → Bool := + CleanSourceRecord.projected designated + (SourceChildKernel.Factors (C := C) (t := t) rows clauses designated) record + +def event (record : Record (C := C) (t := t) rows clauses designated) : + Sample (C := C) (t := t) rows clauses designated → Bool := + UniformCleanSources.recordEvent + (SourceChildKernel.Factors (C := C) (t := t) rows clauses designated) + (SourceChildKernel.zero (C := C) (t := t) rows clauses designated) record + +abbrev Nonclean (record : Record (C := C) (t := t) rows clauses designated) := + {i : Fin (branch h) // ¬ clean rows clauses designated record i} + +def extract (record : Record (C := C) (t := t) rows clauses designated) + (i : Nonclean rows clauses designated record) : Row (C := C) (t := t) rows clauses designated i.val := + match hr : record i.val with + | .inl row => row + | .inr _ => False.elim (i.property (by + simp only [clean, CleanSourceRecord.clean, hr, UniformCleanSources.cleanRecord])) + +theorem record_extract (record : Record (C := C) (t := t) rows clauses designated) + (i : Nonclean rows clauses designated record) : + record i.val = .inl (extract rows clauses designated record i) := by + unfold extract + split + · rename_i row hr + exact hr + · rename_i rest hr + exact False.elim (i.property (by + simp only [clean, CleanSourceRecord.clean, hr, UniformCleanSources.cleanRecord])) + +theorem extract_eq (record : Record (C := C) (t := t) rows clauses designated) + (x : Sample (C := C) (t := t) rows clauses designated) + (hevent : event rows clauses designated record x = true) + (i : Nonclean rows clauses designated record) : + extract rows clauses designated record i = x i.val := by + have obs := CleanSourceRecord.observation_eq designated + (SourceChildKernel.Factors (C := C) (t := t) rows clauses designated) + (SourceChildKernel.zero (C := C) (t := t) rows clauses designated) record x hevent i.val + cases hc : UniformCleanSources.childClean + (SourceChildKernel.Factors (C := C) (t := t) rows clauses designated) + (SourceChildKernel.zero (C := C) (t := t) rows clauses designated) + i.val (x i.val).1 (x i.val).2.1 (x i.val).2.2 with + | false => + have hr : record i.val = .inl (x i.val) := by + simpa only [SelectedSources.childObservation, hc, Bool.false_eq_true, ite_false] + using obs.symm + exact Sum.inl.inj ((record_extract rows clauses designated record i).symm.trans hr) + | true => + have hr : record i.val = .inr (x i.val).2.1 := by + simpa only [SelectedSources.childObservation, hc, ite_true] using obs.symm + exact False.elim (i.property (by + simp only [clean, CleanSourceRecord.clean, hr, UniformCleanSources.cleanRecord])) + +def source (record : Record (C := C) (t := t) rows clauses designated) + (i : Nonclean rows clauses designated record) : + SourceChildKernel.Source (m := m) (t := t) designated i.val := + ((extract rows clauses designated record i).1, (extract rows clauses designated record i).2.1) + +def raw (record : Record (C := C) (t := t) rows clauses designated) + (i : Nonclean rows clauses designated record) : + SourceChildKernel.Raw (C := C) (t := t) rows clauses designated i.val := + (extract rows clauses designated record i).2.2 + +theorem visible_nonclean (record : Record (C := C) (t := t) rows clauses designated) + (i : Nonclean rows clauses designated record) (leaf : Slots branch h) + (hleaf : ¬ (clean rows clauses designated record i.val ∧ leaf = designated i.val)) : + visible rows clauses designated record i.val ⟨leaf, hleaf⟩ = + SourceChildKernel.tree designated i.val (source rows clauses designated record i) leaf := by + dsimp only [visible, CleanSourceRecord.visible] + split + · rename_i row hr + have hrow : row = extract rows clauses designated record i := + Sum.inl.inj (hr.symm.trans (record_extract rows clauses designated record i)) + rw [hrow] + rfl + · rename_i rest hr + have hbad := hr.symm.trans (record_extract rows clauses designated record i) + cases hbad + +theorem projected_nonclean (record : Record (C := C) (t := t) rows clauses designated) + (i : Nonclean rows clauses designated record) : + projected rows clauses designated record i.val = + SourceChildKernel.rawProjected rows clauses designated i.val + (raw rows clauses designated record i) := by + simp only [projected, CleanSourceRecord.projected, + record_extract rows clauses designated record i, raw, + CleanSourceRecord.rawProjected, SourceChildKernel.rawProjected] + cases (extract rows clauses designated record i).2.2 <;> rfl + +variable [NeZero m] + +def leftRef (record : Record (C := C) (t := t) rows clauses designated) : + Slots branch (h + 1) → Fin t → MixedSupport.Slot := + CleanEndpointSlots.leftReference clauses designated (clean rows clauses designated record) + (visible rows clauses designated record) + +def rightRef (record : Record (C := C) (t := t) rows clauses designated) : + Slots branch (h + 1) → Fin t → MixedSupport.Slot := + CleanEndpointSlots.rightReference clauses designated (clean rows clauses designated record) + (visible rows clauses designated record) (projected rows clauses designated record) + +theorem leftRef_childSlots (record : Record (C := C) (t := t) rows clauses designated) + (i : Nonclean rows clauses designated record) : + childSlots (leftRef rows clauses designated record) i.val = + SourceChildKernel.nativeSlots clauses designated i.val (source rows clauses designated record i) := by + funext leaf k + have hn : ¬ (clean rows clauses designated record i.val ∧ leaf = designated i.val) := + fun h => i.property h.1 + simp only [leftRef, CleanEndpointSlots.leftReference, CleanEndpointSlots.leftInside, + childSlots, reconstructLeft, reconstruct, dite_eq_right hn] + rw [visible_nonclean rows clauses designated record i leaf hn] + rfl + +theorem rightRef_childSlots (record : Record (C := C) (t := t) rows clauses designated) + (i : Nonclean rows clauses designated record) : + childSlots (rightRef rows clauses designated record) i.val = + SourceChildKernel.mixedSlots clauses designated i.val (source rows clauses designated record i) + (SourceChildKernel.rawProjected rows clauses designated i.val (raw rows clauses designated record i)) := by + funext leaf k + have hn : ¬ (clean rows clauses designated record i.val ∧ leaf = designated i.val) := + fun h => i.property h.1 + simp only [rightRef, CleanEndpointSlots.rightReference, CleanEndpointSlots.rightInside, + childSlots, reconstructRight, reconstruct, dite_eq_right hn] + rw [visible_nonclean rows clauses designated record i leaf hn, + projected_nonclean rows clauses designated record i] + exact (SourceChildKernel.mixedSlots_eq_rightTuple clauses designated i.val + (source rows clauses designated record i) + (SourceChildKernel.rawProjected rows clauses designated i.val (raw rows clauses designated record i)) + leaf k).symm + +theorem leftRef_childSlots_event (record : Record (C := C) (t := t) rows clauses designated) + (x : Sample (C := C) (t := t) rows clauses designated) + (hevent : event rows clauses designated record x = true) + (i : Nonclean rows clauses designated record) : + childSlots (leftRef rows clauses designated record) i.val = + childSlots (SourceChildKernel.parentLeftSlots clauses designated + (fun j => ((x j).1, (x j).2.1))) i.val := + (leftRef_childSlots rows clauses designated record i).trans + (congrArg (fun y : Row (C := C) (t := t) rows clauses designated i.val => + SourceChildKernel.nativeSlots clauses designated i.val (y.1, y.2.1)) + (extract_eq rows clauses designated record x hevent i)) + +theorem rightRef_childSlots_event (record : Record (C := C) (t := t) rows clauses designated) + (x : Sample (C := C) (t := t) rows clauses designated) + (hevent : event rows clauses designated record x = true) + (i : Nonclean rows clauses designated record) : + childSlots (rightRef rows clauses designated record) i.val = + childSlots (SourceChildKernel.parentRightSlots rows clauses designated + (fun j => ((x j).1, (x j).2.1)) (fun j => (x j).2.2)) i.val := + (rightRef_childSlots rows clauses designated record i).trans + (congrArg (fun y : Row (C := C) (t := t) rows clauses designated i.val => + SourceChildKernel.mixedSlots clauses designated i.val (y.1, y.2.1) + (SourceChildKernel.rawProjected rows clauses designated i.val y.2.2)) + (extract_eq rows clauses designated record x hevent i)) + +def physicalRight (i : Fin (branch h)) (row : Row (C := C) (t := t) rows clauses designated i) : + SourceChildKernel.Block C rows (SourceChildKernel.mixedSlots clauses designated i (row.1, row.2.1) + (SourceChildKernel.rawProjected rows clauses designated i row.2.2)) := + SourceChildKernel.decodeRight rows clauses designated i (row.1, row.2.1) row.2.2 + +def physicalLeft (i : Fin (branch h)) (row : Row (C := C) (t := t) rows clauses designated i) : + SourceChildKernel.Block C rows (SourceChildKernel.nativeSlots clauses designated i (row.1, row.2.1)) := + let p := SourceChildKernel.projection clauses designated i (row.1, row.2.1) + (SourceChildKernel.rawProjected rows clauses designated i row.2.2) + let block := physicalRight rows clauses designated i row + (fun call => ChildBlockProjection.squarePullback p (block.1 call), + ChildBlockProjection.arraysPullback rows p block.2) + +omit [NeZero m] in +theorem physicalLeft_eq_leftChildren + (x : Sample (C := C) (t := t) rows clauses designated) (i : Fin (branch h)) : + physicalLeft rows clauses designated i (x i) = + SourceChildKernel.leftChildren rows clauses designated + (fun j => ((x j).1, (x j).2.1)) (fun j => (x j).2.2) i := by + rw [SourceChildKernel.leftChildren_apply] + rfl + +def rightChild (record : Record (C := C) (t := t) rows clauses designated) + (i : Nonclean rows clauses designated record) : + SourceChildKernel.Block C rows (childSlots (rightRef rows clauses designated record) i.val) := + cast (congrArg (SourceChildKernel.Block C rows) (rightRef_childSlots rows clauses designated record i).symm) + (physicalRight rows clauses designated i.val (extract rows clauses designated record i)) + +def leftChild (record : Record (C := C) (t := t) rows clauses designated) + (i : Nonclean rows clauses designated record) : + SourceChildKernel.Block C rows (childSlots (leftRef rows clauses designated record) i.val) := + cast (congrArg (SourceChildKernel.Block C rows) (leftRef_childSlots rows clauses designated record i).symm) + (physicalLeft rows clauses designated i.val (extract rows clauses designated record i)) + +theorem rightChild_heq (record : Record (C := C) (t := t) rows clauses designated) + (i : Nonclean rows clauses designated record) : + HEq (rightChild rows clauses designated record i) + (physicalRight rows clauses designated i.val (extract rows clauses designated record i)) := + cast_heq _ _ + +theorem leftChild_heq (record : Record (C := C) (t := t) rows clauses designated) + (i : Nonclean rows clauses designated record) : + HEq (leftChild rows clauses designated record i) + (physicalLeft rows clauses designated i.val (extract rows clauses designated record i)) := + cast_heq _ _ + +private theorem dependent_congr {A : Sort*} {B : A → Sort*} (f : (a : A) → B a) + {a b : A} (h : a = b) : HEq (f a) (f b) := by + cases h + rfl + +theorem rightChild_event_heq (record : Record (C := C) (t := t) rows clauses designated) + (x : Sample (C := C) (t := t) rows clauses designated) + (hevent : event rows clauses designated record x = true) + (i : Nonclean rows clauses designated record) : + HEq (rightChild rows clauses designated record i) + (SourceChildKernel.rightChildren rows clauses designated + (fun j => ((x j).1, (x j).2.1)) (fun j => (x j).2.2) i.val) := + (rightChild_heq rows clauses designated record i).trans + (dependent_congr (physicalRight rows clauses designated i.val) + (extract_eq rows clauses designated record x hevent i)) + +theorem leftChild_event_heq (record : Record (C := C) (t := t) rows clauses designated) + (x : Sample (C := C) (t := t) rows clauses designated) + (hevent : event rows clauses designated record x = true) + (i : Nonclean rows clauses designated record) : + HEq (leftChild rows clauses designated record i) + (SourceChildKernel.leftChildren rows clauses designated + (fun j => ((x j).1, (x j).2.1)) (fun j => (x j).2.2) i.val) := by + have hphysical : + HEq (physicalLeft rows clauses designated i.val (extract rows clauses designated record i)) + (physicalLeft rows clauses designated i.val (x i.val)) := + dependent_congr (physicalLeft rows clauses designated i.val) + (extract_eq rows clauses designated record x hevent i) + exact (leftChild_heq rows clauses designated record i).trans + (hphysical.trans (heq_of_eq (physicalLeft_eq_leftChildren rows clauses designated x i.val))) + +omit [NeZero m] in +theorem childClean_of_clean (record : Record (C := C) (t := t) rows clauses designated) + (x : Sample (C := C) (t := t) rows clauses designated) + (hevent : event rows clauses designated record x = true) (i : Fin (branch h)) + (hi : clean rows clauses designated record i) : + UniformCleanSources.childClean + (SourceChildKernel.Factors (C := C) (t := t) rows clauses designated) + (SourceChildKernel.zero (C := C) (t := t) rows clauses designated) + i (x i).1 (x i).2.1 (x i).2.2 = true := by + have obs := CleanSourceRecord.observation_eq designated + (SourceChildKernel.Factors (C := C) (t := t) rows clauses designated) + (SourceChildKernel.zero (C := C) (t := t) rows clauses designated) record x hevent i + cases hc : UniformCleanSources.childClean + (SourceChildKernel.Factors (C := C) (t := t) rows clauses designated) + (SourceChildKernel.zero (C := C) (t := t) rows clauses designated) + i (x i).1 (x i).2.1 (x i).2.2 with + | false => + have hr : record i = .inl (x i) := by + simpa only [SelectedSources.childObservation, hc, Bool.false_eq_true, ite_false] + using obs.symm + simp only [clean, CleanSourceRecord.clean, hr, UniformCleanSources.cleanRecord, + Bool.false_eq_true] at hi + | true => rfl + +end +end PerfectCompleteness.CleanRecordChildBlocks + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanRecordObservation.lean b/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanRecordObservation.lean new file mode 100644 index 0000000000000000000000000000000000000000..d64ce5289929bd987f9e8e633e924655eb874865 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanRecordObservation.lean @@ -0,0 +1,110 @@ +import OAI.Computability.PerfectCompleteness.Repetition.CleanRecordChildBlocks +import OAI.Computability.PerfectCompleteness.Repetition.CutChildCleanLawLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.CleanRecordObservation + +noncomputable section + +open scoped Classical +open RecursiveSpaces TreeSourceSpaces SourceQuestionReconstruction + +variable {branch : Nat → Nat} {h t v m : Nat} {C : Type*} [Fintype C] + (rows : Nat → Nat) (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch h) → Slots branch h) + +abbrev Record := CleanRecordChildBlocks.Record (C := C) (t := t) rows clauses designated +abbrev Sample := SourceChildKernel.Sample (C := C) (t := t) rows clauses designated + +def observe (x : Sample (C := C) (t := t) rows clauses designated) : + Record (C := C) (t := t) rows clauses designated := + UniformCleanSoundness.observations + (D := SourceChildKernel.D (C := C) (t := t) rows clauses designated) + (SourceChildKernel.Factors (C := C) (t := t) rows clauses designated) + (SourceChildKernel.zero (C := C) (t := t) rows clauses designated) x + +theorem event_eq (record : Record (C := C) (t := t) rows clauses designated) + (x : Sample (C := C) (t := t) rows clauses designated) : + CleanRecordChildBlocks.event rows clauses designated record x = + decide (observe rows clauses designated x = record) := + congrFun (UniformCleanSoundness.recordEvent_eq + (D := SourceChildKernel.D (C := C) (t := t) rows clauses designated) + (SourceChildKernel.Factors (C := C) (t := t) rows clauses designated) + (SourceChildKernel.zero (C := C) (t := t) rows clauses designated) record) x + +@[simp] theorem event_observe (x : Sample (C := C) (t := t) rows clauses designated) : + CleanRecordChildBlocks.event rows clauses designated + (observe rows clauses designated x) x = true := by + rw [event_eq] + exact decide_eq_true rfl + +def leftQuestions (record : Record (C := C) (t := t) rows clauses designated) + (x : Sample (C := C) (t := t) rows clauses designated) : + {i : Fin (branch h) // CleanRecordChildBlocks.clean rows clauses designated record i} → + Fin t → Fin m := + fun i k => ((x i.val).1 k).1 + +def rightQuestions (record : Record (C := C) (t := t) rows clauses designated) + (x : Sample (C := C) (t := t) rows clauses designated) : + {i : Fin (branch h) // CleanRecordChildBlocks.clean rows clauses designated record i} → + Fin t → Fin v := + fun i k => SourceClause.occurrenceVariable clauses ((x i.val).1 k) + +theorem leftInside_eq (record : Record (C := C) (t := t) rows clauses designated) + (x : Sample (C := C) (t := t) rows clauses designated) + (hevent : CleanRecordChildBlocks.event rows clauses designated record x = true) : + CleanEndpointSlots.leftInside clauses designated + (CleanRecordChildBlocks.clean rows clauses designated record) + (CleanRecordChildBlocks.visible rows clauses designated record) + (leftQuestions rows clauses designated record x) = + SourceChildKernel.parentLeftSlots clauses designated + (fun i => ((x i).1, (x i).2.1)) := by + have h := CleanSourceRecord.reconstructLeft_eq designated + (D := SourceChildKernel.D (C := C) (t := t) rows clauses designated) + (SourceChildKernel.Factors (C := C) (t := t) rows clauses designated) + (SourceChildKernel.zero (C := C) (t := t) rows clauses designated) + (v := v) record x hevent + funext s k + exact congrArg (fun f => SourceKeys.slot clauses (f s.1 s.2 k)) h + +theorem rightInside_eq (record : Record (C := C) (t := t) rows clauses designated) + (x : Sample (C := C) (t := t) rows clauses designated) + (hevent : CleanRecordChildBlocks.event rows clauses designated record x = true) : + CleanEndpointSlots.rightInside clauses designated + (CleanRecordChildBlocks.clean rows clauses designated record) + (CleanRecordChildBlocks.visible rows clauses designated record) + (CleanRecordChildBlocks.projected rows clauses designated record) + (rightQuestions rows clauses designated record x) = + SourceChildKernel.parentRightSlots rows clauses designated + (fun i => ((x i).1, (x i).2.1)) (fun i => (x i).2.2) := by + have h := CleanSourceRecord.reconstructRight_eq designated + (D := SourceChildKernel.D (C := C) (t := t) rows clauses designated) + (SourceChildKernel.Factors (C := C) (t := t) rows clauses designated) + (SourceChildKernel.zero (C := C) (t := t) rows clauses designated) + clauses record x hevent + funext s k + refine (congrArg (fun f => SourceKeys.slot clauses (f s.1 s.2 k)) h).trans ?_ + have hflag : CleanSourceRecord.rawProjected designated + (D := SourceChildKernel.D (C := C) (t := t) rows clauses designated) + (SourceChildKernel.Factors (C := C) (t := t) rows clauses designated) + s.1 (x s.1).2.2 = + SourceChildKernel.rawProjected rows clauses designated s.1 (x s.1).2.2 := by + cases (x s.1).2.2 <;> rfl + exact (congrArg (fun projected : Bool => SourceKeys.slot clauses + (rightTuple clauses projected + (CleanSourceRecord.sourceTree designated + (D := SourceChildKernel.D (C := C) (t := t) rows clauses designated) + (SourceChildKernel.Factors (C := C) (t := t) rows clauses designated) x s.1 s.2) k)) hflag).trans + (SourceChildKernel.mixedSlots_eq_rightTuple clauses designated s.1 + ((x s.1).1, (x s.1).2.1) + (SourceChildKernel.rawProjected rows clauses designated s.1 (x s.1).2.2) s.2 k).symm + +end +end PerfectCompleteness.CleanRecordObservation + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanTreeFactors.lean b/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanTreeFactors.lean new file mode 100644 index 0000000000000000000000000000000000000000..abb8a5a7fa211f565c2baeac1ffd28a3c01a8251 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Repetition/CleanTreeFactors.lean @@ -0,0 +1,141 @@ +import OAI.Computability.PerfectCompleteness.Algebra.UniformLinearImage +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalArrays +import OAI.Computability.PerfectCompleteness.Foundations.ProjectedCardinality +import OAI.Computability.UniqueGames.Foundations.SamplingLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.CleanTreeFactors + +open scoped BigOperators +open UniqueGamesTheorem.Foundations.Games +open RecursiveSpaces TreeSourceSpaces PointwiseSpaces HierarchicalArrays +open ProjectedCardinality FiniteProduct CleanConditioning + +noncomputable section + +variable {branch : Nat → Nat} {n t : Nat} + +abbrev Index (branch : Nat → Nat) (n calls : Nat) (rows : Nat → Nat) := + Fin calls ⊕ (Σ node : Nodes branch n, Fin (rows (Nodes.height node))) + +def height (calls : Nat) (rows : Nat → Nat) : Index branch n calls rows → Nat + | .inl _ => n + | .inr p => Nodes.height p.1 + +def square (calls : Nat) (rows : Nat → Nat) : Index branch n calls rows → Bool + | .inl _ => true + | .inr _ => false + +def factorIds (calls : Nat) (rows : Nat → Nat) + (ids : Slots branch n → Fin t → Nat) : + (j : Index branch n calls rows) → Slots branch (height calls rows j) → Fin t → Nat + | .inl _, s, k => ids s k + | .inr p, s, k => ids ((Nodes.path p.1).slotEmbedding s) k + +abbrev Factors (calls : Nat) (rows : Nat → Nat) + (ids : Slots branch n → Fin t → Nat) (j : Index branch n calls rows) := + Factor (square calls rows j) (factorIds calls rows ids j) + +abbrev Raw (calls : Nat) (rows : Nat → Nat) + (ids : Slots branch n → Fin t → Nat) := + (Fin calls → squareSpace (H (projectedSlots ids))) × Arrays (projectedSlots ids) rows + +instance rawFintype (calls : Nat) (rows : Nat → Nat) + (ids : Slots branch n → Fin t → Nat) : Fintype (Raw calls rows ids) := + Fintype.ofFinite _ + +def zeroRaw (calls : Nat) (rows : Nat → Nat) + (ids : Slots branch n → Fin t → Nat) : Raw calls rows ids := + (fun _ => 0, fun _ _ => 0) + +instance rawNonempty (calls : Nat) (rows : Nat → Nat) + (ids : Slots branch n → Fin t → Nat) : Nonempty (Raw calls rows ids) := + ⟨zeroRaw calls rows ids⟩ + +def rawEquiv (calls : Nat) (rows : Nat → Nat) + (ids : Slots branch n → Fin t → Nat) : + ((j : Index branch n calls rows) → Factors calls rows ids j) ≃ Raw calls rows ids where + toFun x := (fun q => x (.inl q), fun node row => x (.inr ⟨node, row⟩)) + invFun x j := match j with + | .inl q => x.1 q + | .inr p => x.2 p.1 p.2 + left_inv x := by + funext j + cases j <;> rfl + right_inv x := by + cases x + rfl + +theorem rawEquiv_zero (calls : Nat) (rows : Nat → Nat) + (ids : Slots branch n → Fin t → Nat) : + rawEquiv calls rows ids + (fun j => factorZero (square calls rows j) (factorIds calls rows ids j)) = + zeroRaw calls rows ids := rfl + +def rawLaw (calls : Nat) (rows : Nat → Nat) + (ids : Slots branch n → Fin t → Nat) : FiniteDistribution (Raw calls rows ids) := + (law (fun j : Index branch n calls rows => + FiniteDistribution.uniform (Factors calls rows ids j))).pushforward (rawEquiv calls rows ids) + +theorem rawLaw_uniform (calls : Nat) (rows : Nat → Nat) + (ids : Slots branch n → Fin t → Nat) : + rawLaw calls rows ids = FiniteDistribution.uniform (Raw calls rows ids) := by + unfold rawLaw + rw [UniformLinearImage.law_uniform, FiniteDistribution.pushforward_equiv] + apply FiniteDistribution.eq_of_weight_eq + intro x + change 1 / (Fintype.card ((j : Index branch n calls rows) → Factors calls rows ids j) : ℝ) = + 1 / (Fintype.card (Raw calls rows ids) : ℝ) + rw [Fintype.card_congr (rawEquiv calls rows ids)] + +def allZero (calls : Nat) (rows : Nat → Nat) + (ids : Slots branch n → Fin t → Nat) (x : Raw calls rows ids) : Bool := by + classical + exact decide ((∀ q, x.1 q = 0) ∧ ∀ node row, x.2 node row = 0) + +theorem allZero_rawEquiv (calls : Nat) (rows : Nat → Nat) + (ids : Slots branch n → Fin t → Nat) + (x : (j : Index branch n calls rows) → Factors calls rows ids j) : + allZero calls rows ids (rawEquiv calls rows ids x) = + allEvent (fun j y => decide (y = factorZero + (square calls rows j) (factorIds calls rows ids j))) x := by + classical + apply Bool.eq_iff_iff.mpr + simp only [allZero, allEvent, decide_eq_true_eq] + constructor + · rintro ⟨hc, ha⟩ j + cases j with + | inl q => exact hc q + | inr p => exact ha p.1 p.2 + · intro h + exact ⟨fun q => h (.inl q), fun node row => h (.inr ⟨node, row⟩)⟩ + +theorem probability_allZero (calls : Nat) (rows : Nat → Nat) + (ids : Slots branch n → Fin t → Nat) : + (rawLaw calls rows ids).probability (allZero calls rows ids) = + ∏ j : Index branch n calls rows, + 1 / (shapeCardinality branch t (height calls rows) (square calls rows) j : ℝ) := by + rw [rawLaw, FiniteDistribution.probability_pushforward] + simp_rw [allZero_rawEquiv] + rw [probability_law_all] + apply Finset.prod_congr rfl + intro j _ + rw [UniformLatent.probability_uniform_singleton] + rw [factor_card_eq (square calls rows j) (factorIds calls rows ids j) (fun _ _ => 0)] + rfl + +theorem probability_allZero_pos (calls : Nat) (rows : Nat → Nat) + (ids : Slots branch n → Fin t → Nat) : + 0 < (rawLaw calls rows ids).probability (allZero calls rows ids) := by + rw [probability_allZero] + exact shape_zero_probability_pos branch t (height calls rows) (square calls rows) + +end +end PerfectCompleteness.CleanTreeFactors + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Repetition/CutChildCleanLawLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Repetition/CutChildCleanLawLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..91e9a6279bd04202d3bde4acd54952fa28b5c4e6 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Repetition/CutChildCleanLawLemmas.lean @@ -0,0 +1,859 @@ +import Mathlib.Data.Fintype.EquivFin +import OAI.Computability.PerfectCompleteness.Construction.SourceQuestionReconstruction +import OAI.Computability.PerfectCompleteness.Foundations.CoordinateReplacementLemmas +import OAI.Computability.PerfectCompleteness.Foundations.DesignatedLeavesLemmas +import OAI.Computability.PerfectCompleteness.Foundations.ProjectedCardinality +import OAI.Computability.PerfectCompleteness.Foundations.QuarterBalanceLemmas +import OAI.Computability.PerfectCompleteness.Foundations.SourceOddListsLemmas +import OAI.Computability.PerfectCompleteness.Foundations.WholeCutCallsLemmas +import OAI.Computability.PerfectCompleteness.Repetition.CleanTreeFactors +import OAI.Computability.PerfectCompleteness.Sampling.UniformLatent + +namespace OAI + + +namespace PerfectCompleteness.CutChildCleanLaw + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games +open RecursiveSpaces TreeSourceSpaces PointwiseSpaces HierarchicalArrays ProjectedCardinality + +noncomputable section + +variable {branch : Nat → Nat} {n t : Nat} {C : Type*} [Fintype C] + (rows : Nat → Nat) (ids : Slots branch n → Fin t → Nat) + +abbrev Raw := + (C → squareSpace (H (projectedSlots ids))) × Arrays (projectedSlots ids) rows + +instance rawFintype : Fintype (Raw (C := C) rows ids) := Fintype.ofFinite _ + +def zeroRaw : Raw (C := C) rows ids := (fun _ => 0, fun _ _ => 0) + +instance rawNonempty : Nonempty (Raw (C := C) rows ids) := ⟨zeroRaw rows ids⟩ + +def rawEquiv : Raw (C := C) rows ids ≃ CleanTreeFactors.Raw (Fintype.card C) rows ids where + toFun x := (fun q => x.1 ((Fintype.equivFin C).symm q), x.2) + invFun x := (fun q => x.1 (Fintype.equivFin C q), x.2) + left_inv x := by + apply Prod.ext + · funext q + exact congrArg x.1 ((Fintype.equivFin C).symm_apply_apply q) + · rfl + right_inv x := by + apply Prod.ext + · funext q + exact congrArg x.1 ((Fintype.equivFin C).apply_symm_apply q) + · rfl + +def allZero (x : Raw (C := C) rows ids) : Bool := + decide ((∀ q, x.1 q = 0) ∧ ∀ node row, x.2 node row = 0) + +theorem allZero_rawEquiv (x : Raw (C := C) rows ids) : + CleanTreeFactors.allZero (Fintype.card C) rows ids (rawEquiv rows ids x) = + allZero rows ids x := by + apply Bool.eq_iff_iff.mpr + simp only [CleanTreeFactors.allZero, allZero, decide_eq_true_eq] + change ((∀ q, x.1 ((Fintype.equivFin C).symm q) = 0) ∧ + ∀ node row, x.2 node row = 0) ↔ + ((∀ q, x.1 q = 0) ∧ ∀ node row, x.2 node row = 0) + constructor + · rintro ⟨hc, ha⟩ + refine ⟨fun q => ?_, ha⟩ + simpa only [Equiv.symm_apply_apply] using hc (Fintype.equivFin C q) + · rintro ⟨hc, ha⟩ + exact ⟨fun q => hc ((Fintype.equivFin C).symm q), ha⟩ + +def rawLaw : FiniteDistribution (Raw (C := C) rows ids) := + FiniteDistribution.uniform (Raw (C := C) rows ids) + +theorem rawLaw_reindex : + (rawLaw (C := C) rows ids).pushforward (rawEquiv rows ids) = + CleanTreeFactors.rawLaw (Fintype.card C) rows ids := by + rw [CleanTreeFactors.rawLaw_uniform, rawLaw, FiniteDistribution.pushforward_equiv] + apply FiniteDistribution.eq_of_weight_eq + intro x + change 1 / (Fintype.card (Raw (C := C) rows ids) : ℝ) = + 1 / (Fintype.card (CleanTreeFactors.Raw (Fintype.card C) rows ids) : ℝ) + rw [Fintype.card_congr (rawEquiv (C := C) rows ids)] + +def shapeProbability (branch : Nat → Nat) (n t calls : Nat) (rows : Nat → Nat) : ℝ := + ∏ j : CleanTreeFactors.Index branch n calls rows, + 1 / (shapeCardinality branch t + (CleanTreeFactors.height calls rows) (CleanTreeFactors.square calls rows) j : ℝ) + +theorem probability_allZero_eq_cleanTree : + (rawLaw (C := C) rows ids).probability (allZero rows ids) = + (CleanTreeFactors.rawLaw (Fintype.card C) rows ids).probability + (CleanTreeFactors.allZero (Fintype.card C) rows ids) := by + have h := congrArg + (fun μ : FiniteDistribution (CleanTreeFactors.Raw (Fintype.card C) rows ids) => + μ.probability (CleanTreeFactors.allZero (Fintype.card C) rows ids)) + (rawLaw_reindex (C := C) rows ids) + rw [FiniteDistribution.probability_pushforward] at h + simpa only [allZero_rawEquiv] using h + +theorem probability_allZero : + (rawLaw (C := C) rows ids).probability (allZero rows ids) = + shapeProbability branch n t (Fintype.card C) rows := by + rw [probability_allZero_eq_cleanTree] + exact CleanTreeFactors.probability_allZero (Fintype.card C) rows ids + +theorem probability_allZero_pos : + 0 < (rawLaw (C := C) rows ids).probability (allZero rows ids) := by + rw [probability_allZero_eq_cleanTree] + exact CleanTreeFactors.probability_allZero_pos (Fintype.card C) rows ids + +theorem probability_allZero_eq_of_card_eq {D : Type*} [Fintype D] + (ids' : Slots branch n → Fin t → Nat) (hcard : Fintype.card C = Fintype.card D) : + (rawLaw (C := C) rows ids).probability (allZero rows ids) = + (rawLaw (C := D) rows ids').probability (allZero rows ids') := by + rw [probability_allZero, probability_allZero, hcard] + + +variable {root : Nat} (repeats : Nat → Nat) + (p : DescendantSpaces.Path branch root (n + 1)) + +theorem probability_wholeCalls : + (rawLaw (C := WholeCutCalls.Index rows repeats p) rows ids).probability (allZero rows ids) = + shapeProbability branch n t + (rows (n + 1) + ∑ h ∈ Finset.Ioc (n + 1) root, + (2 ^ rows h - 1) * ∏ k ∈ Finset.Ioc (n + 1) h, 2 * repeats k) rows := by + rw [probability_allZero, WholeCutCalls.card_eq_formula] + +theorem probability_wholeCalls_eq {ancestorBranch : Nat → Nat} + (p' : DescendantSpaces.Path ancestorBranch root (n + 1)) + (ids' : Slots branch n → Fin t → Nat) : + (rawLaw (C := WholeCutCalls.Index rows repeats p) rows ids).probability (allZero rows ids) = + (rawLaw (C := WholeCutCalls.Index rows repeats p') rows ids').probability + (allZero rows ids') := by + apply probability_allZero_eq_of_card_eq rows ids ids' + rw [WholeCutCalls.card_eq_formula, WholeCutCalls.card_eq_formula] + + +end +end PerfectCompleteness.CutChildCleanLaw + + + +namespace PerfectCompleteness.UniformCleanSources + +open scoped BigOperators +open UniqueGamesTheorem.Foundations.Games +open FiniteProduct CleanConditioning SelectedSources UniformLatent + +noncomputable section + +attribute [local instance] Classical.propDecidable + +variable {I : Type*} [Fintype I] [DecidableEq I] + {E R J D : I → Type*} + [∀ i, Fintype (E i)] [∀ i, Fintype (R i)] [∀ i, Fintype (J i)] [∀ i, Fintype (D i)] + [∀ i, DecidableEq (E i)] [∀ i, DecidableEq (R i)] + [∀ i, DecidableEq (J i)] [∀ i, DecidableEq (D i)] + (Ω : (i : I) → (E i × R i) → J i → Type*) + [∀ i s j, Fintype (Ω i s j)] [∀ i s j, Nonempty (Ω i s j)] + [∀ i s j, DecidableEq (Ω i s j)] + +abbrev ChildRaw (i : I) := Sum (D i) (UniformLatent.Raw (Ω i)) + +def childKernel (flag : (i : I) → FiniteDistribution Bool) + (nonprojected : (i : I) → E i × R i → FiniteDistribution (D i)) + (i : I) (e : E i) (r : R i) : FiniteDistribution (ChildRaw (D := D) Ω i) := + projectedKernel (Ω i) (flag i) (nonprojected i) (e, r) + +def childClean (zero : (i : I) → (s : E i × R i) → (j : J i) → Ω i s j) + (i : I) (_ : E i) (_ : R i) : ChildRaw (D := D) Ω i → Bool := + projectedZero (Ω i) (zero i) + +def childrenLaw (μ : (i : I) → FiniteDistribution (E i)) + (ν : (i : I) → FiniteDistribution (R i)) + (flag : (i : I) → FiniteDistribution Bool) + (nonprojected : (i : I) → E i × R i → FiniteDistribution (D i)) : + FiniteDistribution ((i : I) → E i × (R i × ChildRaw (D := D) Ω i)) := + law (fun i => kernelJoint (μ i) (fun e => + kernelJoint (ν i) (childKernel Ω flag nonprojected i e))) + +abbrev Record (i : I) := Sum (E i × (R i × ChildRaw (D := D) Ω i)) (R i) + +def cleanRecord {i : I} : Record (D := D) Ω i → Bool + | Sum.inl _ => false + | Sum.inr _ => true + +abbrev CleanIndices (record : (i : I) → Record (D := D) Ω i) := + {i : I // cleanRecord Ω (record i) = true} + +def rowEvent + (zero : (i : I) → (s : E i × R i) → (j : J i) → Ω i s j) + (record : (i : I) → Record (D := D) Ω i) + (i : I) (x : E i × (R i × ChildRaw (D := D) Ω i)) : Bool := by + classical + exact decide (childObservation (childClean (D := D) Ω zero i) x = record i) + +def recordEvent + (zero : (i : I) → (s : E i × R i) → (j : J i) → Ω i s j) + (record : (i : I) → Record (D := D) Ω i) : + ((i : I) → E i × (R i × ChildRaw (D := D) Ω i)) → Bool := + allEvent (rowEvent Ω zero record) + +omit [∀ index, DecidableEq (D index)] in +theorem clean_source_law + (μ : (i : I) → FiniteDistribution (E i)) + (ν : (i : I) → FiniteDistribution (R i)) + (flag : (i : I) → FiniteDistribution Bool) + (nonprojected : (i : I) → E i × R i → FiniteDistribution (D i)) + (zero : (i : I) → (s : E i × R i) → (j : J i) → Ω i s j) + (cardinality : (i : I) → J i → Nat) + (same_cardinality : ∀ i s j, Fintype.card (Ω i s j) = cardinality i j) + (record : (i : I) → Record (D := D) Ω i) + (positive : 0 < (childrenLaw Ω μ ν flag nonprojected).probability + (recordEvent (D := D) Ω zero record)) : + ((childrenLaw Ω μ ν flag nonprojected).condition (recordEvent (D := D) Ω zero record) + positive).pushforward (Γ := (i : CleanIndices Ω record) → E i.1) + (fun x (i : CleanIndices Ω record) => (x i.1).1) = + law (I := CleanIndices Ω record) (Ω := fun i : CleanIndices Ω record => E i.1) + (fun i : CleanIndices Ω record => μ i.1) := by + classical + let P := fun i => kernelJoint (μ i) (fun e => + kernelJoint (ν i) (childKernel Ω flag nonprojected i e)) + let event := rowEvent Ω zero record + have hpositive : 0 < (law P).probability (allEvent event) := positive + apply selected_sources_conditioned (I := I) + (Ω := fun i => E i × (R i × ChildRaw (D := D) Ω i)) P event hpositive + (fun i => cleanRecord Ω (record i) = true) + (fun _ x => x.1) (fun i => μ i.1) + intro i + have hr : ∃ r, record i.1 = Sum.inr r := by + have hi := i.property + cases hrec : record i.1 with + | inl raw => simp [cleanRecord, hrec] at hi + | inr r => exact ⟨r, rfl⟩ + obtain ⟨r, hr⟩ := hr + have hevent : event i.1 = + (fun x => decide (x.2.1 = r) && childClean (D := D) Ω zero i.1 x.1 x.2.1 x.2.2) := by + funext x + cases hclean : childClean (D := D) Ω zero i.1 x.1 x.2.1 x.2.2 <;> + simp [event, rowEvent, hr, childObservation, hclean] + have hp := coordinate_probability_positive P event hpositive i.1 + rw [hevent] at hp + have hconst : ∀ e r, (childKernel Ω flag nonprojected i.1 e r).probability + (childClean (D := D) Ω zero i.1 e r) = + (flag i.1).weight true * ∏ j, 1 / (cardinality i.1 j : ℝ) := by + intro e r + exact probability_projectedKernel_zero_constant (Ω i.1) (flag i.1) (nonprojected i.1) + (zero i.1) (cardinality i.1) (same_cardinality i.1) (e, r) + simpa only [hevent] using + designated_source_condition (μ i.1) (ν i.1) (childKernel Ω flag nonprojected i.1) + (childClean (D := D) Ω zero i.1) + ((flag i.1).weight true * ∏ j, 1 / (cardinality i.1 j : ℝ)) hconst r hp + +end +end PerfectCompleteness.UniformCleanSources + + + +namespace PerfectCompleteness.CleanSourceRecord + +open scoped Classical +open SourceQuestionReconstruction + +noncomputable section + +variable {I : Type*} [Fintype I] [DecidableEq I] + {Leaf : I → Type*} [∀ i, Fintype (Leaf i)] [∀ i, DecidableEq (Leaf i)] + (designated : (i : I) → Leaf i) {m t : Nat} + +abbrev Rest (i : I) := {leaf : Leaf i // leaf ≠ designated i} → SourceTuple m t + +def assemble (i : I) (e : SourceTuple m t) (r : Rest designated (m := m) (t := t) i) : + Leaf i → SourceTuple m t := + (Equiv.piSplitAt (designated i) (fun _ : Leaf i => SourceTuple m t)).symm (e, r) + +omit [Fintype I] [DecidableEq I] [∀ index, Fintype (Leaf index)] in +@[simp] theorem assemble_designated (i : I) (e : SourceTuple m t) + (r : Rest designated (m := m) (t := t) i) : + assemble designated i e r (designated i) = e := by + simp [assemble, Equiv.piSplitAt] + +omit [Fintype I] [DecidableEq I] [∀ index, Fintype (Leaf index)] in +@[simp] theorem assemble_other (i : I) (e : SourceTuple m t) + (r : Rest designated (m := m) (t := t) i) (leaf : {leaf : Leaf i // leaf ≠ designated i}) : + assemble designated i e r leaf.val = r leaf := by + simp [assemble, Equiv.piSplitAt, leaf.property] + +variable {J D : I → Type*} + [∀ i, Fintype (J i)] [∀ i, Fintype (D i)] + [∀ i, DecidableEq (J i)] [∀ i, DecidableEq (D i)] + (Ω : (i : I) → (SourceTuple m t × Rest designated (m := m) (t := t) i) → J i → Type*) + [∀ i q j, Fintype (Ω i q j)] [∀ i q j, Nonempty (Ω i q j)] + [∀ i q j, DecidableEq (Ω i q j)] + +abbrev Sample := (i : I) → SourceTuple m t × + (Rest designated (m := m) (t := t) i × UniformCleanSources.ChildRaw (D := D) Ω i) + +abbrev Record := (i : I) → UniformCleanSources.Record (D := D) Ω i + +def clean (record : Record (D := D) designated Ω) (i : I) : Prop := + UniformCleanSources.cleanRecord Ω (record i) = true + +def sourceTree (x : Sample (D := D) designated Ω) : (i : I) → Leaf i → SourceTuple m t := + fun i => assemble designated i (x i).1 (x i).2.1 + +omit [∀ index, Fintype (J index)] [∀ index, Fintype (D index)] + [∀ index, DecidableEq (J index)] [∀ index, DecidableEq (D index)] + [∀ index seed coord, Fintype (Ω index seed coord)] + [∀ index seed coord, Nonempty (Ω index seed coord)] + [∀ index seed coord, DecidableEq (Ω index seed coord)] in +omit [Fintype I] [DecidableEq I] [∀ index, Fintype (Leaf index)] in +@[simp] theorem sourceTree_designated (x : Sample (D := D) designated Ω) (i : I) : + sourceTree designated Ω x i (designated i) = (x i).1 := + assemble_designated designated i _ _ + +def visible (record : Record (D := D) designated Ω) : + Visible (E := SourceTuple m t) designated (clean designated Ω record) := + fun i leaf => + match hrecord : record i with + | .inl x => assemble designated i x.1 x.2.1 leaf.val + | .inr r => r ⟨leaf.val, by + intro heq + apply leaf.property + exact ⟨by simp only [clean, hrecord, UniformCleanSources.cleanRecord], heq⟩⟩ + +def rawProjected (i : I) : UniformCleanSources.ChildRaw (D := D) Ω i → Bool + | .inl _ => false + | .inr _ => true + +def projected (record : Record (D := D) designated Ω) (i : I) : Bool := + match record i with + | .inl x => rawProjected designated Ω i x.2.2 + | .inr _ => true + +omit [Fintype I] [DecidableEq I] [∀ index, Fintype (Leaf index)] + [∀ index, DecidableEq (Leaf index)] + [∀ index, Fintype (J index)] [∀ index, Fintype (D index)] + [∀ index, DecidableEq (J index)] [∀ index, DecidableEq (D index)] + [∀ index seed coord, Fintype (Ω index seed coord)] + [∀ index seed coord, Nonempty (Ω index seed coord)] + [∀ index seed coord, DecidableEq (Ω index seed coord)] in +theorem clean_projected (record : Record (D := D) designated Ω) (i : I) + (hc : clean designated Ω record i) : projected designated Ω record i = true := by + cases hrecord : record i with + | inl x => simp only [clean, hrecord, UniformCleanSources.cleanRecord, Bool.false_eq_true] at hc + | inr r => simp only [projected, hrecord] + +variable (zero : (i : I) → (q : SourceTuple m t × Rest designated (m := m) (t := t) i) → + (j : J i) → Ω i q j) + +omit [DecidableEq I] [∀ index, Fintype (D index)] + [∀ index, DecidableEq (J index)] [∀ index, DecidableEq (D index)] + [∀ index seed coord, Fintype (Ω index seed coord)] + [∀ index seed coord, Nonempty (Ω index seed coord)] in +theorem observation_eq (record : Record (D := D) designated Ω) (x : Sample (D := D) designated Ω) + (hevent : UniformCleanSources.recordEvent (D := D) Ω zero record x = true) (i : I) : + SelectedSources.childObservation (UniformCleanSources.childClean (D := D) Ω zero i) (x i) = + record i := by + have hall : ∀ j, UniformCleanSources.rowEvent (D := D) Ω zero record j (x j) = true := by + simpa only [UniformCleanSources.recordEvent, CleanConditioning.allEvent, decide_eq_true_eq] using hevent + simpa only [UniformCleanSources.rowEvent, decide_eq_true_eq] using hall i + +omit [DecidableEq I] [∀ index, Fintype (D index)] + [∀ index, DecidableEq (J index)] [∀ index, DecidableEq (D index)] + [∀ index seed coord, Fintype (Ω index seed coord)] + [∀ index seed coord, Nonempty (Ω index seed coord)] in +theorem visible_eq_reveal (record : Record (D := D) designated Ω) (x : Sample (D := D) designated Ω) + (hevent : UniformCleanSources.recordEvent (D := D) Ω zero record x = true) : + visible designated Ω record = + reveal designated (clean designated Ω record) (sourceTree designated Ω x) := by + funext i leaf + have hi := observation_eq designated Ω zero record x hevent i + cases hc : UniformCleanSources.childClean (D := D) Ω zero i (x i).1 (x i).2.1 (x i).2.2 with + | false => + have hr : record i = .inl (x i) := by + simpa only [SelectedSources.childObservation, hc, Bool.false_eq_true, ite_false] using hi.symm + dsimp only [visible, reveal, sourceTree] + split + · rename_i y hy + have hyx : y = x i := Sum.inl.inj (hy.symm.trans hr) + exact congrArg (fun z => assemble designated i z.1 z.2.1 leaf.val) hyx + · rename_i r hy + have hbad := hy.symm.trans hr + cases hbad + | true => + have hr : record i = .inr (x i).2.1 := by + simpa only [SelectedSources.childObservation, hc, ite_true] using hi.symm + have hn : leaf.val ≠ designated i := by + intro heq + apply leaf.property + exact ⟨by simp only [clean, hr, UniformCleanSources.cleanRecord], heq⟩ + dsimp only [visible, reveal, sourceTree] + split + · rename_i y hy + have hbad := hy.symm.trans hr + cases hbad + · rename_i r hy + have hrx : r = (x i).2.1 := Sum.inr.inj (hy.symm.trans hr) + exact (congrFun hrx ⟨leaf.val, hn⟩).trans + (assemble_other designated i (x i).1 (x i).2.1 ⟨leaf.val, hn⟩).symm + +omit [DecidableEq I] [∀ index, Fintype (D index)] + [∀ index, DecidableEq (J index)] [∀ index, DecidableEq (D index)] + [∀ index seed coord, Fintype (Ω index seed coord)] + [∀ index seed coord, Nonempty (Ω index seed coord)] in +theorem projected_eq_raw (record : Record (D := D) designated Ω) (x : Sample (D := D) designated Ω) + (hevent : UniformCleanSources.recordEvent (D := D) Ω zero record x = true) : + projected designated Ω record = fun i => rawProjected designated Ω i (x i).2.2 := by + funext i + have hi := observation_eq designated Ω zero record x hevent i + cases hc : UniformCleanSources.childClean (D := D) Ω zero i (x i).1 (x i).2.1 (x i).2.2 with + | false => + have hr : record i = .inl (x i) := by + simpa only [SelectedSources.childObservation, hc, Bool.false_eq_true, ite_false] using hi.symm + simp only [projected, hr] + | true => + have hr : record i = .inr (x i).2.1 := by + simpa only [SelectedSources.childObservation, hc, ite_true] using hi.symm + rw [projected, hr] + cases hraw : (x i).2.2 with + | inl d => + simp only [UniformCleanSources.childClean, UniformLatent.projectedZero, + hraw, Bool.false_eq_true] at hc + | inr raw => rfl + +omit [DecidableEq I] [∀ index, Fintype (D index)] + [∀ index, DecidableEq (J index)] [∀ index, DecidableEq (D index)] + [∀ index seed coord, Fintype (Ω index seed coord)] + [∀ index seed coord, Nonempty (Ω index seed coord)] in +theorem clean_projected_raw (record : Record (D := D) designated Ω) + (x : Sample (D := D) designated Ω) + (hevent : UniformCleanSources.recordEvent (D := D) Ω zero record x = true) + (i : I) (hc : clean designated Ω record i) : + rawProjected designated Ω i (x i).2.2 = true := + (congrFun (projected_eq_raw designated Ω zero record x hevent) i).symm.trans + (clean_projected designated Ω record i hc) + +variable {v : Nat} (clauses : Fin m → SourceClause.NormalizedClause v) + +omit [DecidableEq I] [∀ index, Fintype (D index)] + [∀ index, DecidableEq (J index)] [∀ index, DecidableEq (D index)] + [∀ index seed coord, Fintype (Ω index seed coord)] + [∀ index seed coord, Nonempty (Ω index seed coord)] in +theorem reconstructLeft_eq (record : Record (D := D) designated Ω) (x : Sample (D := D) designated Ω) + (hevent : UniformCleanSources.recordEvent (D := D) Ω zero record x = true) : + SourceQuestionReconstruction.reconstructLeft designated (clean designated Ω record) + (v := v) (visible designated Ω record) + (fun i k => ((x i.val).1 k).1) = + fun i leaf => leftTuple (v := v) (sourceTree designated Ω x i leaf) := by + rw [visible_eq_reveal designated Ω zero record x hevent] + simpa only [sourceTree_designated] using + SourceQuestionReconstruction.reconstructLeft_eq designated (clean designated Ω record) + (v := v) (sourceTree designated Ω x) + +omit [DecidableEq I] [∀ index, Fintype (D index)] + [∀ index, DecidableEq (J index)] [∀ index, DecidableEq (D index)] + [∀ index seed coord, Fintype (Ω index seed coord)] + [∀ index seed coord, Nonempty (Ω index seed coord)] in +theorem reconstructRight_eq (record : Record (D := D) designated Ω) (x : Sample (D := D) designated Ω) + (hevent : UniformCleanSources.recordEvent (D := D) Ω zero record x = true) : + SourceQuestionReconstruction.reconstructRight designated (clean designated Ω record) clauses + (projected designated Ω record) (visible designated Ω record) + (fun i k => SourceClause.occurrenceVariable clauses ((x i.val).1 k)) = + fun i leaf => rightTuple clauses (rawProjected designated Ω i (x i).2.2) + (sourceTree designated Ω x i leaf) := by + rw [visible_eq_reveal designated Ω zero record x hevent] + have h := SourceQuestionReconstruction.reconstructRight_eq designated (clean designated Ω record) + clauses (projected designated Ω record) (clean_projected designated Ω record) + (sourceTree designated Ω x) + simpa only [sourceTree_designated, projected_eq_raw designated Ω zero record x hevent] using h + +omit [DecidableEq I] [∀ index, Fintype (D index)] + [∀ index, DecidableEq (J index)] [∀ index, DecidableEq (D index)] + [∀ index seed coord, Fintype (Ω index seed coord)] + [∀ index seed coord, Nonempty (Ω index seed coord)] in +theorem reconstructRight_slots (record : Record (D := D) designated Ω) (x : Sample (D := D) designated Ω) + (hevent : UniformCleanSources.recordEvent (D := D) Ω zero record x = true) : + (fun i leaf k => SourceKeys.slot clauses + (SourceQuestionReconstruction.reconstructRight designated (clean designated Ω record) clauses + (projected designated Ω record) (visible designated Ω record) + (fun j q => SourceClause.occurrenceVariable clauses ((x j.val).1 q)) i leaf k)) = + fun i leaf k => SourceKeys.slot clauses + (rightTuple clauses (rawProjected designated Ω i (x i).2.2) + (sourceTree designated Ω x i leaf) k) := by + rw [reconstructRight_eq designated Ω zero clauses record x hevent] + +end +end PerfectCompleteness.CleanSourceRecord + + + +namespace PerfectCompleteness.ProjectedCleanLaw + +open UniqueGamesTheorem.Foundations.Games +open FiniteProduct ProjectedCardinality UniformCleanSources + +noncomputable section + +attribute [local instance] Classical.propDecidable + +variable {I : Type*} [Fintype I] [DecidableEq I] + {E R J D : I → Type*} + [∀ i, Fintype (E i)] [∀ i, Fintype (R i)] [∀ i, Fintype (J i)] [∀ i, Fintype (D i)] + [∀ i, DecidableEq (E i)] [∀ i, DecidableEq (R i)] + [∀ i, DecidableEq (J i)] [∀ i, DecidableEq (D i)] + (branch : I → Nat → Nat) (t : I → Nat) + (height : (i : I) → J i → Nat) (square : (i : I) → J i → Bool) + (ids : (i : I) → (E i × R i) → (j : J i) → + RecursiveSpaces.Slots (branch i) (height i j) → Fin (t i) → Nat) + +abbrev treeFactors (i : I) (s : E i × R i) (j : J i) : Type := + Factor (square i j) (ids i s j) + +def treeZeros (i : I) (s : E i × R i) (j : J i) : + treeFactors branch t height square ids i s j := + factorZero (square i j) (ids i s j) + +local notation "Ωtree" => treeFactors branch t height square ids +local notation "ztree" => treeZeros branch t height square ids + +omit [∀ index, DecidableEq (D index)] in +theorem designated_source_law + (μ : (i : I) → FiniteDistribution (E i)) + (ν : (i : I) → FiniteDistribution (R i)) + (flag : (i : I) → FiniteDistribution Bool) + (nonprojected : (i : I) → E i × R i → FiniteDistribution (D i)) + (record : (i : I) → UniformCleanSources.Record (D := D) Ωtree i) + (positive : 0 < (childrenLaw Ωtree μ ν flag nonprojected).probability + (recordEvent (D := D) Ωtree ztree record)) : + ((childrenLaw Ωtree μ ν flag nonprojected).condition (recordEvent (D := D) Ωtree ztree record) + positive).pushforward (Γ := (i : CleanIndices Ωtree record) → E i.1) + (fun x (i : CleanIndices Ωtree record) => (x i.1).1) = + law (I := CleanIndices Ωtree record) (Ω := fun i : CleanIndices Ωtree record => E i.1) + (fun i : CleanIndices Ωtree record => μ i.1) := by + classical + apply clean_source_law Ωtree μ ν flag nonprojected ztree + (fun i => shapeCardinality (branch i) (t i) (height i) (square i)) _ record positive + intro i s j + exact factor_card_eq (square i j) (ids i s j) (fun _ _ => 0) + +end +end PerfectCompleteness.ProjectedCleanLaw + + + +namespace PerfectCompleteness.UniformCleanSoundness + +open scoped BigOperators +open UniqueGamesTheorem.Foundations.Games +open FiniteProduct CleanConditioning SelectedSources UniformLatent UniformCleanSources +open FiniteConditioningBounds + +noncomputable section + +attribute [local instance] Classical.propDecidable + +variable {I E : Type*} [Fintype I] [DecidableEq I] [Fintype E] [DecidableEq E] + {R J D : I → Type*} + [∀ i, Fintype (R i)] [∀ i, Fintype (J i)] [∀ i, Fintype (D i)] + [∀ i, DecidableEq (R i)] [∀ i, DecidableEq (J i)] [∀ i, DecidableEq (D i)] + (Ω : (i : I) → (E × R i) → J i → Type*) + [∀ i s j, Fintype (Ω i s j)] [∀ i s j, Nonempty (Ω i s j)] + [∀ i s j, DecidableEq (Ω i s j)] + +abbrev Sample := (i : I) → E × (R i × ChildRaw (D := D) Ω i) +abbrev FullRecord := (i : I) → Record (D := D) Ω i + +def observations (zero : (i : I) → (s : E × R i) → (j : J i) → Ω i s j) + (x : Sample (D := D) Ω) : FullRecord (D := D) Ω := + fun i => childObservation (childClean (D := D) Ω zero i) (x i) + +omit [DecidableEq I] [Fintype E] [DecidableEq E] + [∀ index, Fintype (R index)] [∀ index, Fintype (D index)] + [∀ index, DecidableEq (J index)] [∀ index, DecidableEq (D index)] + [∀ index seed coord, Fintype (Ω index seed coord)] + [∀ index seed coord, Nonempty (Ω index seed coord)] in +theorem recordEvent_eq + (zero : (i : I) → (s : E × R i) → (j : J i) → Ω i s j) + (record : FullRecord (D := D) Ω) : + recordEvent (D := D) Ω zero record = + (fun x => decide (observations (D := D) Ω zero x = record)) := by + funext x + apply Bool.eq_iff_iff.mpr + simp only [recordEvent, rowEvent, allEvent, decide_eq_true_eq, + observations, funext_iff] + +omit [DecidableEq I] [Fintype E] [DecidableEq E] + [∀ index, Fintype (R index)] [∀ index, Fintype (D index)] + [∀ index, DecidableEq (R index)] [∀ index, DecidableEq (J index)] + [∀ index, DecidableEq (D index)] + [∀ index seed coord, Fintype (Ω index seed coord)] + [∀ index seed coord, Nonempty (Ω index seed coord)] in +theorem observed_clean_count + (zero : (i : I) → (s : E × R i) → (j : J i) → Ω i s j) + (x : Sample (D := D) Ω) : + Fintype.card (CleanIndices Ω (observations (D := D) Ω zero x)) = + CleanCounting.cleanCount + (fun i y => childClean (D := D) Ω zero i y.1 y.2.1 y.2.2) x := by + classical + change Fintype.card {i : I // + cleanRecord Ω (observations (D := D) Ω zero x i) = true} = _ + rw [Fintype.card_subtype] + unfold CleanCounting.cleanCount + congr 1 + ext i + cases h : childClean (D := D) Ω zero i (x i).1 (x i).2.1 (x i).2.2 <;> + simp [observations, childObservation, cleanRecord, h] + +variable {Q₁ Q₂ A₁ A₂ : Type*} + [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂] + [Nonempty A₁] [Nonempty A₂] + +omit [∀ index, DecidableEq (D index)] in +theorem conditional_source_bound + (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) + (ν : (i : I) → FiniteDistribution (R i)) + (flag : (i : I) → FiniteDistribution Bool) + (nonprojected : (i : I) → E × R i → FiniteDistribution (D i)) + (zero : (i : I) → (s : E × R i) → (j : J i) → Ω i s j) + (cardinality : (i : I) → J i → Nat) + (same_cardinality : ∀ i s j, Fintype.card (Ω i s j) = cardinality i j) + (record : FullRecord (D := D) Ω) + (positive : 0 < (childrenLaw Ω (fun _ => G.occurrences) ν flag nonprojected).probability + (recordEvent (D := D) Ω zero record)) + (event : Sample (D := D) Ω → Bool) + (strategy : Strategy (CleanIndices Ω record → Q₁) (CleanIndices Ω record → Q₂) + (CleanIndices Ω record → A₁) (CleanIndices Ω record → A₂)) + (inclusion : ∀ x, recordEvent (D := D) Ω zero record x = true → event x = true → + (IndexedRepetition.game G (CleanIndices Ω record)).wins strategy + (fun i => (x i.1).1) = true) : + ((childrenLaw Ω (fun _ => G.occurrences) ν flag nonprojected).condition + (recordEvent (D := D) Ω zero record) positive).probability event ≤ + (G.repetition (Fintype.card (CleanIndices Ω record))).value := by + apply conditioned_source_success + (childrenLaw Ω (fun _ => G.occurrences) ν flag nonprojected) + (recordEvent (D := D) Ω zero record) event positive G + (fun x (i : CleanIndices Ω record) => (x i.1).1) _ strategy inclusion + exact clean_source_law Ω (fun _ => G.occurrences) ν flag nonprojected zero + cardinality same_cardinality record positive + +omit [∀ index, DecidableEq (D index)] in +theorem source_soundness + (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) + (ν : (i : I) → FiniteDistribution (R i)) + (flag : (i : I) → FiniteDistribution Bool) + (nonprojected : (i : I) → E × R i → FiniteDistribution (D i)) + (zero : (i : I) → (s : E × R i) → (j : J i) → Ω i s j) + (cardinality : (i : I) → J i → Nat) + (same_cardinality : ∀ i s j, Fintype.card (Ω i s j) = cardinality i j) + (event : Sample (D := D) Ω → Bool) (a : ℝ) + (repetition : ∀ n, (G.repetition n).value ≤ a ^ n) + (strategies : (record : FullRecord (D := D) Ω) → + Strategy (CleanIndices Ω record → Q₁) (CleanIndices Ω record → Q₂) + (CleanIndices Ω record → A₁) (CleanIndices Ω record → A₂)) + (inclusion : ∀ record x, recordEvent (D := D) Ω zero record x = true → event x = true → + (IndexedRepetition.game G (CleanIndices Ω record)).wins (strategies record) + (fun i => (x i.1).1) = true) : + (childrenLaw Ω (fun _ => G.occurrences) ν flag nonprojected).probability event ≤ + ∏ i : I, (1 - (1 - a) * + ((flag i).weight true * ∏ j : J i, 1 / (cardinality i j : ℝ))) := by + classical + let P := fun i => kernelJoint G.occurrences (fun e => + kernelJoint (ν i) (childKernel Ω flag nonprojected i e)) + let clean := fun i (y : E × (R i × ChildRaw (D := D) Ω i)) => + childClean (D := D) Ω zero i y.1 y.2.1 y.2.2 + have conditional : ∀ record (positive : 0 < (law P).probability + (fun x => decide (observations (D := D) Ω zero x = record))), + ((law P).condition (fun x => decide (observations (D := D) Ω zero x = record)) + positive).probability event ≤ a ^ Fintype.card (CleanIndices Ω record) := by + intro record positive + have hp' : 0 < (childrenLaw Ω (fun _ => G.occurrences) ν flag nonprojected).probability + (recordEvent (D := D) Ω zero record) := by + simpa only [childrenLaw, P, recordEvent_eq] using positive + have bound := (conditional_source_bound Ω G ν flag nonprojected zero cardinality + same_cardinality record hp' event (strategies record) (inclusion record)).trans + (repetition _) + simpa only [childrenLaw, P, recordEvent_eq] using bound + have h := independent_clean_bound P clean (observations (D := D) Ω zero) + (fun record => Fintype.card (CleanIndices Ω record)) + (observed_clean_count Ω zero) event a conditional + have hp (i : I) : (P i).probability (clean i) = + (flag i).weight true * ∏ j : J i, 1 / (cardinality i j : ℝ) := by + apply CleanCounting.kernel_clean_probability + (fun _ => G.occurrences) ν (childKernel Ω flag nonprojected) + (childClean (D := D) Ω zero) + (fun i => (flag i).weight true * ∏ j : J i, 1 / (cardinality i j : ℝ)) _ i + intro k e r + exact probability_projectedKernel_zero_constant (Ω k) (flag k) (nonprojected k) + (zero k) (cardinality k) (same_cardinality k) (e, r) + change (law P).probability event ≤ _ + simpa only [hp] using h + +end +end PerfectCompleteness.UniformCleanSoundness + + + +namespace PerfectCompleteness.ProjectedCleanRate + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games +open RecursiveSpaces ProjectedCardinality CleanTreeFactors UniformCleanSources + +noncomputable section + +def zeroProbability (branch : Nat → Nat) (height t calls : Nat) (rows : Nat → Nat) : ℝ := + ∏ j : CleanTreeFactors.Index branch height calls rows, + 1 / (shapeCardinality branch t + (CleanTreeFactors.height calls rows) (CleanTreeFactors.square calls rows) j : ℝ) + +theorem zeroProbability_positive (branch : Nat → Nat) (height t calls : Nat) + (rows : Nat → Nat) : 0 < zeroProbability branch height t calls rows := + shape_zero_probability_pos branch t + (CleanTreeFactors.height calls rows) (CleanTreeFactors.square calls rows) + +theorem zeroProbability_le_one (branch : Nat → Nat) (height t calls : Nat) + (rows : Nat → Nat) : zeroProbability branch height t calls rows ≤ 1 := by + change (∏ j : CleanTreeFactors.Index branch height calls rows, + 1 / (shapeCardinality branch t + (CleanTreeFactors.height calls rows) (CleanTreeFactors.square calls rows) j : ℝ)) ≤ 1 + rw [← CleanTreeFactors.probability_allZero calls rows + (fun (_ : Slots branch height) (_ : Fin t) => 0)] + exact FiniteDistribution.probability_le_one _ _ + +theorem raw_zero_probability (branch : Nat → Nat) (height t calls : Nat) + (rows : Nat → Nat) (ids : Slots branch height → Fin t → Nat) : + (CleanTreeFactors.rawLaw calls rows ids).probability + (CleanTreeFactors.allZero calls rows ids) = + zeroProbability branch height t calls rows := + CleanTreeFactors.probability_allZero calls rows ids + +def coefficient (L : Nat) (branch : Nat → Nat) (height t calls : Nat) + (rows : Nat → Nat) : ℝ := + zeroProbability branch height t calls rows / (48000 * (L : ℝ)) + +theorem coefficient_eq (L : Nat) (branch : Nat → Nat) (height t calls : Nat) + (rows : Nat → Nat) : + coefficient L branch height t calls rows = + (1 - (RepetitionRate.halfRate L : ℝ)) * zeroProbability branch height t calls rows := by + rw [RepetitionRate.halfRate_cast] + unfold coefficient + ring + +theorem coefficient_bounds {L : Nat} (hL : 0 < L) (branch : Nat → Nat) + (height t calls : Nat) (rows : Nat → Nat) : + 0 < coefficient L branch height t calls rows ∧ + coefficient L branch height t calls rows ≤ 1 := by + have hLr : (1 : ℝ) ≤ L := by exact_mod_cast hL + have hden : (0 : ℝ) < 48000 * L := by positivity + have hp := zeroProbability_positive branch height t calls rows + have hp1 := zeroProbability_le_one branch height t calls rows + constructor + · exact div_pos hp hden + · apply (div_le_one hden).2 + linarith + +def projectionDensity (cube : Nat) : ℝ := 1 / (cube : ℝ) ^ 2 + +theorem projectionDensity_bounds {cube : Nat} (hcube : 0 < cube) : + 0 ≤ projectionDensity cube ∧ projectionDensity cube ≤ 1 := by + have hc : (1 : ℝ) ≤ cube := by exact_mod_cast hcube + have hsq : (1 : ℝ) ≤ (cube : ℝ) ^ 2 := by nlinarith + constructor + · exact one_div_nonneg.mpr (sq_nonneg _) + · exact (div_le_one (by positivity)).2 hsq + +def projectionFlag (cube : Nat) (hcube : 0 < cube) : FiniteDistribution Bool := + RepetitionRate.bernoulli (projectionDensity cube) + (projectionDensity_bounds hcube).1 (projectionDensity_bounds hcube).2 + +@[simp] theorem projectionFlag_true (cube : Nat) (hcube : 0 < cube) : + (projectionFlag cube hcube).weight true = projectionDensity cube := by + simp [projectionFlag, RepetitionRate.bernoulli] + +theorem cube_product {L cube : Nat} (branch : Nat → Nat) (height t calls : Nat) + (rows : Nat → Nat) : + (∏ _i : Fin (cube ^ 3), + (1 - (1 - (RepetitionRate.halfRate L : ℝ)) * + (projectionDensity cube * zeroProbability branch height t calls rows))) = + (1 - coefficient L branch height t calls rows / (cube : ℝ) ^ 2) ^ (cube ^ 3) := by + have hbase : 1 - (1 - (RepetitionRate.halfRate L : ℝ)) * + (projectionDensity cube * zeroProbability branch height t calls rows) = + 1 - coefficient L branch height t calls rows / (cube : ℝ) ^ 2 := by + rw [coefficient_eq] + unfold projectionDensity + ring + simp only [hbase, Finset.prod_const, Finset.card_univ, Fintype.card_fin] + +section ActualLaw + +variable {E : Type*} [Fintype E] [DecidableEq E] + {cube : Nat} {R D : Fin (cube ^ 3) → Type*} + [∀ i, Fintype (R i)] [∀ i, DecidableEq (R i)] + [∀ i, Fintype (D i)] [∀ i, DecidableEq (D i)] + (branch : Nat → Nat) (height t calls : Nat) (rows : Nat → Nat) + (ids : (i : Fin (cube ^ 3)) → E × R i → Slots branch height → Fin t → Nat) + +abbrev Factors (i : Fin (cube ^ 3)) (source : E × R i) + (j : CleanTreeFactors.Index branch height calls rows) := + CleanTreeFactors.Factors calls rows (ids i source) j + +def zeros (i : Fin (cube ^ 3)) (source : E × R i) + (j : CleanTreeFactors.Index branch height calls rows) : + Factors branch height t calls rows ids i source j := + factorZero (CleanTreeFactors.square calls rows j) + (CleanTreeFactors.factorIds calls rows (ids i source) j) + +local notation "Ω" => Factors branch height t calls rows ids +local notation "z" => zeros branch height t calls rows ids + +variable {Q₁ Q₂ A₁ A₂ : Type*} + [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂] + [Nonempty A₁] [Nonempty A₂] + +omit [∀ index, DecidableEq (D index)] in +theorem bound_from_repetition {L : Nat} (hcube : 0 < cube) + (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) + (repetition : ∀ k, (G.repetition k).value ≤ (RepetitionRate.halfRate L : ℝ) ^ k) + (ν : (i : Fin (cube ^ 3)) → FiniteDistribution (R i)) + (nonprojected : (i : Fin (cube ^ 3)) → E × R i → FiniteDistribution (D i)) + (event : UniformCleanSoundness.Sample (D := D) Ω → Bool) + (strategies : (record : UniformCleanSoundness.FullRecord (D := D) Ω) → + Strategy (CleanIndices Ω record → Q₁) (CleanIndices Ω record → Q₂) + (CleanIndices Ω record → A₁) (CleanIndices Ω record → A₂)) + (inclusion : ∀ record x, recordEvent (D := D) Ω z record x = true → + event x = true → + (IndexedRepetition.game G (CleanIndices Ω record)).wins (strategies record) + (fun i => (x i.1).1) = true) : + (childrenLaw Ω (fun _ => G.occurrences) ν (fun _ => projectionFlag cube hcube) + nonprojected).probability event ≤ + (1 - coefficient L branch height t calls rows / (cube : ℝ) ^ 2) ^ (cube ^ 3) := by + have bound := UniformCleanSoundness.source_soundness Ω G ν + (fun _ => projectionFlag cube hcube) nonprojected z + (fun _ => shapeCardinality branch t + (CleanTreeFactors.height calls rows) (CleanTreeFactors.square calls rows)) + (fun i source j => factor_card_eq (CleanTreeFactors.square calls rows j) + (CleanTreeFactors.factorIds calls rows (ids i source) j) (fun _ _ => 0)) + event (RepetitionRate.halfRate L : ℝ) repetition strategies inclusion + calc + _ ≤ ∏ _i : Fin (cube ^ 3), + (1 - (1 - (RepetitionRate.halfRate L : ℝ)) * + (projectionDensity cube * zeroProbability branch height t calls rows)) := by + simpa only [projectionFlag_true, zeroProbability] using bound + _ = _ := cube_product branch height t calls rows + +end ActualLaw + +theorem exists_cube_errors_lt {L : Nat} (hL : 0 < L) + (branch : Nat → Nat) (height t calls : Nat) (rows : Nat → Nat) + {likelihood ε : ℝ} (hlikelihood : 0 ≤ likelihood) (hε : 0 < ε) : + ∃ cube : Nat, 2 ≤ cube ∧ + Real.sqrt (likelihood ^ 2 / (cube : ℝ) ^ 3) / 2 < ε ∧ + Real.sqrt ((1 + likelihood ^ 2 / (cube : ℝ) ^ 4) ^ (cube ^ 3) - 1) / 2 < ε ∧ + 2 * ((1 / (cube : ℝ) ^ 2) * likelihood / (1 - 1 / (cube : ℝ) ^ 2)) < ε ∧ + (1 - coefficient L branch height t calls rows / (cube : ℝ) ^ 2) ^ (cube ^ 3) < ε := + CubicErrorSchedule.exists_cube_errors_lt hlikelihood + (coefficient_bounds hL branch height t calls rows).1 + (coefficient_bounds hL branch height t calls rows).2 hε + +end +end PerfectCompleteness.ProjectedCleanRate + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Repetition/FixedCleanRate.lean b/lean/OAI/Computability/PerfectCompleteness/Repetition/FixedCleanRate.lean new file mode 100644 index 0000000000000000000000000000000000000000..d06b27803a21130cc71e89b0b1ac87db7ae22130 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Repetition/FixedCleanRate.lean @@ -0,0 +1,83 @@ +import OAI.Computability.PerfectCompleteness.Construction.OriginalChildScalarAssemblyLemmas +import OAI.Computability.PerfectCompleteness.Reduction.FixedCallBudgetLemmas +import OAI.Computability.PerfectCompleteness.Repetition.CutChildCleanLawLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.FixedCleanRate + +open ChildBlockCardinality ProjectedCleanRate + +noncomputable section + +theorem zeroProbability_lower (branch : Nat → Nat) (height t calls : Nat) + (rows : Nat → Nat) : + 1 / (bound branch height t calls rows : ℝ) ≤ + zeroProbability branch height t calls rows := by + let ids : RecursiveSpaces.Slots branch height → Fin t → Nat := fun _ _ => 0 + rw [← raw_zero_probability branch height t calls rows ids, + CleanTreeFactors.rawLaw_uniform] + exact cleanLowerBound_le_probability + (slots := ProjectedCardinality.projectedSlots ids) + +theorem conservative_coefficient_le {calls budget cost : Nat} + (hcalls : calls ≤ budget) (hcost : 0 < cost) + (branch : Nat → Nat) (height t : Nat) (rows : Nat → Nat) : + FixedBranching.cleanRate cost (bound branch height t budget rows : ℝ) ≤ + coefficient cost branch height t calls rows := by + have hbound : (bound branch height t calls rows : ℝ) ≤ + (bound branch height t budget rows : ℝ) := by + exact_mod_cast FixedCallBudget.child_bound_mono hcalls branch height t rows + have hpositive : (0 : ℝ) < bound branch height t calls rows := + Nat.cast_pos.mpr (shape_bound_pos branch height t calls rows) + have hzero : 1 / (bound branch height t budget rows : ℝ) ≤ + zeroProbability branch height t calls rows := + (one_div_le_one_div_of_le hpositive hbound).trans + (zeroProbability_lower branch height t calls rows) + have hden : (0 : ℝ) < 48000 * cost := by + have : (0 : ℝ) < cost := by exact_mod_cast hcost + positivity + calc + _ = (1 / (bound branch height t budget rows : ℝ)) / (48000 * cost) := by + unfold FixedBranching.cleanRate + ring + _ ≤ _ := div_le_div_of_nonneg_right hzero hden.le + +theorem decay_le_conservative {calls budget cost cube : Nat} + (hcalls : calls ≤ budget) (hcost : 0 < cost) (hcube : 2 ≤ cube) + (branch : Nat → Nat) (height t : Nat) (rows : Nat → Nat) : + (1 - coefficient cost branch height t calls rows / (cube : ℝ) ^ 2) ^ (cube ^ 3) ≤ + (1 - FixedBranching.cleanRate cost + (bound branch height t budget rows : ℝ) / (cube : ℝ) ^ 2) ^ (cube ^ 3) := by + have hc : (2 : ℝ) ≤ cube := by exact_mod_cast hcube + have hsquare : (1 : ℝ) ≤ (cube : ℝ) ^ 2 := by nlinarith + have hden : (0 : ℝ) < (cube : ℝ) ^ 2 := by positivity + have hcoef := (coefficient_bounds hcost branch height t calls rows).2 + have hbase : 0 ≤ 1 - coefficient cost branch height t calls rows / (cube : ℝ) ^ 2 := by + have := (div_le_one hden).mpr (hcoef.trans hsquare) + linarith + apply pow_le_pow_left₀ hbase + have h := div_le_div_of_nonneg_right + (conservative_coefficient_le hcalls hcost branch height t rows) hden.le + linarith + +variable {δ : ℚ} {hδ : 0 < δ} (p : FixedParameters.Parameters δ hδ) + +theorem actual_clean_error {calls : Nat} (hcalls : calls ≤ FixedParameters.calls p.plan) + (height : Nat) : + (1 - coefficient p.alphabetCost (FixedParameters.branch p) height + (FixedRows.sourceLength p.plan hδ) calls (FixedRows.rows p.plan) / + (p.cubeSize height : ℝ) ^ 2) ^ (p.cubeSize height ^ 3) < p.accuracy := by + have hdecay := decay_le_conservative hcalls p.alphabetCost_pos + (p.cube_errors height).1 (FixedParameters.branch p) height + (FixedRows.sourceLength p.plan hδ) (FixedRows.rows p.plan) + exact hdecay.trans_lt (p.cube_errors height).2.2.2.2 + +end +end PerfectCompleteness.FixedCleanRate + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Repetition/RepetitionRateLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Repetition/RepetitionRateLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..0f7d2b7d5c3844aa08fd70f32e66b298ec048331 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Repetition/RepetitionRateLemmas.lean @@ -0,0 +1,289 @@ +import OAI.Computability.PerfectCompleteness.Foundations.FiniteProduct +import OAI.Computability.PerfectCompleteness.Reduction.OccurrenceGame +import OAI.Computability.UniqueGames.Foundations.SamplingLemmas +import OAI.Computability.UniqueGames.Games.CompletedSamplingLemmas +import OAI.Computability.UniqueGames.Soundness.PartnerLinearLemmas + +namespace OAI + + +namespace PerfectCompleteness.RepetitionRate + +open scoped BigOperators +open UniqueGamesTheorem.Foundations Games + +def halfRate (L : Nat) : ℚ := 1 - 1 / (48000 * (L : ℚ)) + +theorem halfRate_bounds {L : Nat} (hL : 0 < L) : + 0 < halfRate L ∧ halfRate L < 1 := by + have hLq : (1 : ℚ) ≤ L := by exact_mod_cast hL + have hden : (0 : ℚ) < 48000 * L := by positivity + have hpos : (0 : ℚ) < 1 / (48000 * L) := div_pos zero_lt_one hden + have hlt : (1 : ℚ) / (48000 * L) < 1 := + (div_lt_one hden).2 (by linarith) + constructor <;> unfold halfRate <;> linarith + +theorem halfRate_cast (L : Nat) : + (halfRate L : ℝ) = 1 - 1 / (48000 * (L : ℝ)) := by + simp only [halfRate, Rat.cast_sub, Rat.cast_one, Rat.cast_div, + Rat.cast_mul, Rat.cast_ofNat, Rat.cast_natCast] + +theorem halfRate_power_comparison {L : Nat} (hL : 0 < L) : + (1 - 1 / 48000 : ℝ) ≤ (halfRate L : ℝ) ^ L := by + have hLr : (1 : ℝ) ≤ L := by exact_mod_cast hL + have hLpos : (0 : ℝ) < L := by exact_mod_cast hL + have hden : (0 : ℝ) < 48000 * L := by positivity + have hfrac : (1 : ℝ) / (48000 * L) ≤ 1 := + (div_le_one hden).2 (by linarith) + have h := one_add_mul_le_pow + (a := -((1 : ℝ) / (48000 * L))) (by linarith : + (-2 : ℝ) ≤ -((1 : ℝ) / (48000 * L))) L + rw [halfRate_cast] + calc + (1 - 1 / 48000 : ℝ) = + 1 + (L : ℝ) * (-((1 : ℝ) / (48000 * L))) := by + field_simp [ne_of_gt hLpos] + ring + _ ≤ (1 + -((1 : ℝ) / (48000 * L))) ^ L := h + _ = (1 - 1 / (48000 * (L : ℝ))) ^ L := by rw [sub_eq_add_neg] + +theorem halfRate_rpow_comparison {L : Nat} (hL : 0 < L) (n : Nat) : + (1 - 1 / 48000 : ℝ) ^ ((n : ℝ) / L) ≤ (halfRate L : ℝ) ^ n := by + have hLpos : (0 : ℝ) < L := by exact_mod_cast hL + have hr : (0 : ℝ) ≤ halfRate L := by + exact_mod_cast (halfRate_bounds hL).1.le + calc + _ ≤ ((halfRate L : ℝ) ^ L) ^ ((n : ℝ) / L) := + Real.rpow_le_rpow (by norm_num) (halfRate_power_comparison hL) (by positivity) + _ = (halfRate L : ℝ) ^ ((L : ℝ) * ((n : ℝ) / L)) := + (Real.rpow_natCast_mul hr L ((n : ℝ) / L)).symm + _ = (halfRate L : ℝ) ^ (n : ℝ) := by + congr 1 + field_simp [ne_of_gt hLpos] + _ = (halfRate L : ℝ) ^ n := Real.rpow_natCast _ _ + +theorem game_repetition_halfRate {Q₁ Q₂ A₁ A₂ : Type*} + [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂] + [Nonempty A₁] [Nonempty A₂] [DecidableEq Q₁] [DecidableEq Q₂] + (G : Game Q₁ Q₂ A₁ A₂) {L : Nat} (hL : 0 < L) + (halphabet : Repetition.logTwo + ((Fintype.card A₁ : ℝ) * (Fintype.card A₂ : ℝ)) ≤ L) + (hvalue : G.value ≤ 1 / 2) (n : Nat) : + (G.repetition n).value ≤ (halfRate L : ℝ) ^ n := by + have hell : (1 : ℝ) ≤ L := by exact_mod_cast hL + have h := Repetition.holenstein_repetition_value G n hvalue + (by norm_num : (1 / 2 : ℝ) < 1) hell halphabet + have hbase : (1 - (1 - (1 / 2 : ℝ)) ^ 3 / 6000) = 1 - 1 / 48000 := by + norm_num + rw [hbase] at h + exact h.trans (halfRate_rpow_comparison hL n) + +theorem occurrence_repetition_halfRate {E Q₁ Q₂ A₁ A₂ : Type*} + [Fintype E] [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂] + [Nonempty A₁] [Nonempty A₂] [DecidableEq Q₁] [DecidableEq Q₂] + (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) (p : G.EndpointPresentation) + {L : Nat} (hL : 0 < L) + (halphabet : Repetition.logTwo + ((Fintype.card A₁ : ℝ) * (Fintype.card A₂ : ℝ)) ≤ L) + (hvalue : G.value ≤ 1 / 2) (n : Nat) : + (G.repetition n).value ≤ (halfRate L : ℝ) ^ n := by + have hv : (G.toGame p).value ≤ 1 / 2 := by + simpa only [G.toGame_value p] using hvalue + have h := game_repetition_halfRate (G.toGame p) hL halphabet hv n + simpa only [G.toGame_repetition_value p n] using h + +noncomputable section + +def bernoulli (p : ℝ) (hp : 0 ≤ p) (hp' : p ≤ 1) : FiniteDistribution Bool where + weight b := if b = true then p else 1 - p + nonnegative b := by + cases b + · simpa using sub_nonneg.mpr hp' + · simpa using hp + normalized := by simp + +def cleanCount {n : Nat} (mask : Fin n → Bool) : Nat := + (Finset.univ.filter fun i => mask i = true).card + +theorem pow_cleanCount_eq_prod {n : Nat} (a : ℝ) (mask : Fin n → Bool) : + a ^ cleanCount mask = ∏ i, if mask i = true then a else 1 := by + rw [← Finset.prod_filter] + simp [cleanCount] + +theorem cleanMask_moment (p : ℝ) (hp : 0 ≤ p) (hp' : p ≤ 1) + (a : ℝ) (n : Nat) : + ((bernoulli p hp hp').iid n).expectation (fun mask => a ^ cleanCount mask) = + (1 - p * (1 - a)) ^ n := by + unfold FiniteDistribution.expectation FiniteDistribution.iid + simp_rw [pow_cleanCount_eq_prod, ← Finset.prod_mul_distrib] + rw [← Fintype.sum_pow + (fun b : Bool => (bernoulli p hp hp').weight b * (if b = true then a else 1)) n] + congr 1 + simp [bernoulli] + ring + +end + +theorem cube_decay_bound {c : ℚ} (hc : 0 ≤ c) (hc' : c ≤ 1) + {m : Nat} (hm : 0 < m) : + (1 - c / (m : ℚ) ^ 2) ^ (m ^ 3) ≤ 1 / (1 + c * m) := by + have hmone : (1 : ℚ) ≤ m := by exact_mod_cast hm + have hmpos : (0 : ℚ) < m := by exact_mod_cast hm + have hmsq : (1 : ℚ) ≤ (m : ℚ) ^ 2 := by nlinarith + have hsqpos : (0 : ℚ) < (m : ℚ) ^ 2 := pow_pos hmpos _ + have hfrac0 : (0 : ℚ) ≤ c / (m : ℚ) ^ 2 := div_nonneg hc hsqpos.le + have hfrac1 : c / (m : ℚ) ^ 2 ≤ 1 := (div_le_one hsqpos).2 (hc'.trans hmsq) + have h := UniqueGamesTheorem.Soundness.RepetitionUpper.power_mul_growth_le_one + (1 - c / (m : ℚ) ^ 2) (by linarith) (by linarith) (m ^ 3) + have hfactor : 1 + ((m ^ 3 : Nat) : ℚ) * (1 - (1 - c / (m : ℚ) ^ 2)) = + 1 + c * m := by + push_cast + field_simp [ne_of_gt hmpos] + ring + rw [hfactor] at h + have hden : (0 : ℚ) < 1 + c * m := by positivity + exact (le_div_iff₀ hden).2 h + +theorem exists_cube_decay_lt {c threshold : ℚ} + (hc : 0 < c) (hc' : c ≤ 1) (hthreshold : 0 < threshold) : + ∃ m : Nat, 0 < m ∧ + (1 - c / (m : ℚ) ^ 2) ^ (m ^ 3) < threshold := by + obtain ⟨m, hm, hlarge⟩ := + UniqueGamesTheorem.Soundness.RepetitionUpper.exists_pos_nat_gt (1 / (c * threshold)) + refine ⟨m, hm, (cube_decay_bound hc.le hc' hm).trans_lt ?_⟩ + have hlarge' : (1 : ℚ) < (m : ℚ) * (c * threshold) := + (div_lt_iff₀ (mul_pos hc hthreshold)).1 hlarge + have hden : (0 : ℚ) < 1 + c * m := by positivity + apply (div_lt_iff₀ hden).2 + nlinarith + +theorem exists_clean_branching {L : Nat} (hL : 0 < L) {p0 threshold : ℚ} + (hp0 : 0 < p0) (hp0' : p0 ≤ 1) (hthreshold : 0 < threshold) : + ∃ m : Nat, 0 < m ∧ + (1 - ((1 - halfRate L) * p0) / (m : ℚ) ^ 2) ^ (m ^ 3) < threshold := by + have hr := halfRate_bounds hL + have hc : (0 : ℚ) < (1 - halfRate L) * p0 := + mul_pos (sub_pos.mpr hr.2) hp0 + have hc' : (1 - halfRate L) * p0 ≤ 1 := by + have h := mul_le_mul_of_nonneg_left hp0' (sub_nonneg.mpr hr.2.le) + nlinarith + exact exists_cube_decay_lt hc hc' hthreshold + +end PerfectCompleteness.RepetitionRate + + + +namespace PerfectCompleteness.IndexedRepetition + +open UniqueGamesTheorem.Foundations.Games +open FiniteProduct + +noncomputable section + +variable {E Q₁ Q₂ A₁ A₂ : Type*} + [Fintype E] [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂] + +def game (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) (I : Type*) + [Fintype I] [DecidableEq I] : + OccurrenceGame (I → E) (I → Q₁) (I → Q₂) (I → A₁) (I → A₂) := by + classical + exact + { occurrences := law (fun _ : I => G.occurrences) + left := fun x i => G.left (x i) + right := fun x i => G.right (x i) + accepts := fun x a b => decide (∀ i, G.accepts (x i) (a i) (b i) = true) } + +def reindexStrategy {I J : Type*} (e : J ≃ I) + (s : Strategy (I → Q₁) (I → Q₂) (I → A₁) (I → A₂)) : + Strategy (J → Q₁) (J → Q₂) (J → A₁) (J → A₂) := + (fun x j => s.1 (x ∘ e.symm) (e j), + fun y j => s.2 (y ∘ e.symm) (e j)) + +theorem law_const_fin (μ : FiniteDistribution E) (n : Nat) : + law (fun _ : Fin n => μ) = μ.iid n := by + apply FiniteDistribution.eq_of_weight_eq + intro x + rfl + +theorem game_fin (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) (n : Nat) : + game G (Fin n) = G.repetition n := by + unfold game OccurrenceGame.repetition + simp only [law_const_fin] + congr 1 + funext x a b + by_cases h : ∀ i : Fin n, G.accepts (x i) (a i) (b i) = true <;> + simp only [h, decide_false] + +theorem reindex_law {I J : Type*} [Fintype I] [Fintype J] + [DecidableEq I] [DecidableEq J] + (μ : FiniteDistribution E) (e : J ≃ I) : + (law (fun _ : I => μ)).pushforward (fun x => x ∘ e) = + law (fun _ : J => μ) := + FiniteDistribution.table_const_reindex μ e + +theorem reindex_success {I J : Type*} [Fintype I] [Fintype J] + [DecidableEq I] [DecidableEq J] + (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) (e : J ≃ I) + (s : Strategy (I → Q₁) (I → Q₂) (I → A₁) (I → A₂)) : + (game G J).success (reindexStrategy e s) = (game G I).success s := by + classical + change (law (fun _ : J => G.occurrences)).probability _ = + (law (fun _ : I => G.occurrences)).probability _ + rw [← reindex_law G.occurrences e, FiniteDistribution.probability_pushforward] + apply congrArg (law (fun _ : I => G.occurrences)).probability + funext x + have hl : (fun j => G.left ((x ∘ e) j)) ∘ e.symm = fun i => G.left (x i) := by + funext i + simp only [Function.comp_apply, e.apply_symm_apply] + have hr : (fun j => G.right ((x ∘ e) j)) ∘ e.symm = fun i => G.right (x i) := by + funext i + simp only [Function.comp_apply, e.apply_symm_apply] + change decide (∀ j, G.accepts ((x ∘ e) j) + (s.1 ((fun j => G.left ((x ∘ e) j)) ∘ e.symm) (e j)) + (s.2 ((fun j => G.right ((x ∘ e) j)) ∘ e.symm) (e j)) = true) = + decide (∀ i, G.accepts (x i) + (s.1 (fun i => G.left (x i)) i) (s.2 (fun i => G.right (x i)) i) = true) + rw [hl, hr] + congr 1 + apply propext + constructor + · intro h i + simpa only [Function.comp_apply, e.apply_symm_apply] using h (e.symm i) + · intro h j + exact h (e j) + +theorem success_le_repetition_value {I : Type*} [Fintype I] [DecidableEq I] + [Nonempty A₁] [Nonempty A₂] + (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) + (s : Strategy (I → Q₁) (I → Q₂) (I → A₁) (I → A₂)) : + (game G I).success s ≤ (G.repetition (Fintype.card I)).value := by + rw [← reindex_success G (Fintype.equivFin I).symm s, game_fin] + exact (G.repetition (Fintype.card I)).success_le_value _ + +theorem value_eq_repetition {I : Type*} [Fintype I] [DecidableEq I] + [Nonempty A₁] [Nonempty A₂] (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) : + (game G I).value = (G.repetition (Fintype.card I)).value := by + apply le_antisymm + · exact ((game G I).value_le_iff _).2 (success_le_repetition_value G) + · apply ((G.repetition (Fintype.card I)).value_le_iff _).2 + intro s + have h := reindex_success G (Fintype.equivFin I) s + rw [game_fin] at h + rw [← h] + exact (game G I).success_le_value (reindexStrategy (Fintype.equivFin I) s) + +theorem halfRate {I : Type*} [Fintype I] [DecidableEq I] + [Nonempty A₁] [Nonempty A₂] [DecidableEq Q₁] [DecidableEq Q₂] + (G : OccurrenceGame E Q₁ Q₂ A₁ A₂) (p : G.EndpointPresentation) + {L : Nat} (hL : 0 < L) + (alphabet : UniqueGamesTheorem.Foundations.Repetition.logTwo + ((Fintype.card A₁ : ℝ) * (Fintype.card A₂ : ℝ)) ≤ L) + (gap : G.value ≤ 1 / 2) : + (game G I).value ≤ (RepetitionRate.halfRate L : ℝ) ^ Fintype.card I := by + rw [value_eq_repetition] + exact RepetitionRate.occurrence_repetition_halfRate G p hL alphabet gap _ + +end +end PerfectCompleteness.IndexedRepetition + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Repetition/SourceAmplification.lean b/lean/OAI/Computability/PerfectCompleteness/Repetition/SourceAmplification.lean new file mode 100644 index 0000000000000000000000000000000000000000..cec6aae828ea5f26edb377bd1ef858dc4505375e --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Repetition/SourceAmplification.lean @@ -0,0 +1,121 @@ +import OAI.Computability.PerfectCompleteness.Reduction.SourceGame +import OAI.Computability.UniqueGames.Reduction.FinalParametersLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.SourceAmplification + +open SourceClause UniqueGamesTheorem.Foundations Games +open UniqueGamesTheorem.Integration + +theorem logTwo_le_four {x : ℝ} (hx : 0 < x) (hbound : x ≤ 16) : + Repetition.logTwo x ≤ 4 := by + calc + Repetition.logTwo x ≤ Repetition.logTwo 16 := by + unfold Repetition.logTwo + exact div_le_div_of_nonneg_right (Real.log_le_log hx hbound) + (Real.log_pos (by norm_num : (1 : ℝ) < 2)).le + _ = 4 := SourceParameters.logTwo_sixteen + +theorem game_repetition_rate_le_sixteen {Q₁ Q₂ A₁ A₂ : Type*} + [Fintype Q₁] [Fintype Q₂] [Fintype A₁] [Fintype A₂] + [Nonempty A₁] [Nonempty A₂] [DecidableEq Q₁] [DecidableEq Q₂] + (G : 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 : ℝ)) (k : Nat) : + (G.repetition k).value ≤ (SourceParameters.rate gap : ℝ) ^ k := by + have hg : (0 : ℝ) < gap := by exact_mod_cast hgap + have ha : (0 : ℝ) < Fintype.card A₁ := by exact_mod_cast Fintype.card_pos (α := A₁) + have hb : (0 : ℝ) < Fintype.card A₂ := by exact_mod_cast Fintype.card_pos (α := A₂) + have hbound : (Fintype.card A₁ : ℝ) * (Fintype.card A₂ : ℝ) ≤ 16 := by + exact_mod_cast hcards + have halphabet := logTwo_le_four (mul_pos ha hb) hbound + have h := Repetition.holenstein_repetition_value G k hvalue + (by linarith) (by norm_num : (1 : ℝ) ≤ 4) halphabet + simp only [sub_sub_cancel] at h + exact h.trans (SourceParameters.four_bit_rate_comparison hgap hgap1 k) + +def ClauseGap {n m : Nat} (clauses : Fin m → NormalizedClause n) (γ : ℚ) : Prop := + ∀ assignment : Fin n → Bool, + γ * (m : ℚ) ≤ (SourceGame.violatedCount clauses assignment : ℚ) + +theorem source_value_le {n m : Nat} [NeZero m] + (clauses : Fin m → NormalizedClause n) {γ : ℚ} (gap : ClauseGap clauses γ) : + (SourceGame.game clauses).value ≤ 1 - ((γ / 3 : ℚ) : ℝ) := by + apply ((SourceGame.game clauses).value_le_iff _).mpr + intro strategy + have hm : (0 : ℝ) < m := by exact_mod_cast Nat.pos_of_neZero m + have hcount : (γ : ℝ) * (m : ℝ) ≤ + (SourceGame.violatedCount clauses strategy.2 : ℝ) := by + exact_mod_cast gap strategy.2 + have hfrac := (le_div_iff₀ hm).mpr hcount + have h := SourceGame.success_le_one_sub_third_violations clauses strategy + push_cast + linarith + +theorem source_repetition_rate {n m : Nat} [NeZero m] + (clauses : Fin m → NormalizedClause n) {γ : ℚ} + (hγ : 0 < γ) (hγ1 : γ ≤ 1) (gap : ClauseGap clauses γ) (k : Nat) : + ((SourceGame.game clauses).repetition k).value ≤ + (SourceParameters.rate (γ / 3) : ℝ) ^ k := by + have hthird : (0 : ℚ) < γ / 3 := div_pos hγ (by norm_num) + have hthird1 : γ / 3 ≤ (1 : ℚ) := by linarith + have hv : (SourceGame.questionGame clauses).value ≤ 1 - ((γ / 3 : ℚ) : ℝ) := by + simpa only [SourceGame.questionGame, OccurrenceGame.toGame_value] using + source_value_le clauses gap + have h := game_repetition_rate_le_sixteen (SourceGame.questionGame clauses) + hthird hthird1 (by decide) hv k + simpa only [SourceGame.questionGame, OccurrenceGame.toGame_repetition_value] using h + +theorem exists_repetition_length {γ σ : ℚ} + (hγ : 0 < γ) (hγ1 : γ ≤ 1) (hσ : 0 < σ) : + ∃ k : Nat, 0 < k ∧ SourceParameters.rate (γ / 3) ^ k < σ := by + have hthird : (0 : ℚ) < γ / 3 := div_pos hγ (by norm_num) + have hthird1 : γ / 3 ≤ (1 : ℚ) := by linarith + have hr := SourceParameters.rate_bounds hthird hthird1 + exact UniqueGamesTheorem.Soundness.RepetitionUpper.exists_power_lt + (SourceParameters.rate (γ / 3)) σ hr.1.le hr.2 hσ + +def repetitionLength (γ σ : ℚ) (hγ : 0 < γ) (hγ1 : γ ≤ 1) (hσ : 0 < σ) : Nat := + Nat.find (exists_repetition_length hγ hγ1 hσ) + +theorem repetitionLength_spec (γ σ : ℚ) (hγ : 0 < γ) (hγ1 : γ ≤ 1) (hσ : 0 < σ) : + 0 < repetitionLength γ σ hγ hγ1 hσ ∧ + SourceParameters.rate (γ / 3) ^ repetitionLength γ σ hγ hγ1 hσ < σ := + Nat.find_spec (exists_repetition_length hγ hγ1 hσ) + +theorem repeated_source_value_lt {n m : Nat} [NeZero m] + (clauses : Fin m → NormalizedClause n) (γ σ : ℚ) + (hγ : 0 < γ) (hγ1 : γ ≤ 1) (hσ : 0 < σ) (gap : ClauseGap clauses γ) : + ((SourceGame.game clauses).repetition (repetitionLength γ σ hγ hγ1 hσ)).value < (σ : ℝ) := by + have hsmall : (SourceParameters.rate (γ / 3) : ℝ) ^ + repetitionLength γ σ hγ hγ1 hσ < (σ : ℝ) := by + exact_mod_cast (repetitionLength_spec γ σ hγ hγ1 hσ).2 + exact (source_repetition_rate clauses hγ hγ1 gap _).trans_lt hsmall + +theorem repeated_completeness_success {n m : Nat} [NeZero m] + (clauses : Fin m → NormalizedClause n) (assignment : Fin n → Bool) + (satisfying : ∀ c, (clauses c).clause.eval assignment = true) (k : Nat) : + ((SourceGame.game clauses).repetition k).success + (Game.repeatStrategy (SourceGame.completenessStrategy clauses assignment satisfying) k) = 1 := by + rw [← (SourceGame.game clauses).toGame_repetition_success (SourceGame.presentation clauses)] + change ((SourceGame.questionGame clauses).repetition k).success + (Game.repeatStrategy (SourceGame.completenessStrategy clauses assignment satisfying) k) = 1 + rw [Game.success_repeatStrategy, SourceGame.questionGame_success, + SourceGame.completeness_success, one_pow] + +theorem repeated_completeness_value {n m : Nat} [NeZero m] + (clauses : Fin m → NormalizedClause n) (assignment : Fin n → Bool) + (satisfying : ∀ c, (clauses c).clause.eval assignment = true) (k : Nat) : + ((SourceGame.game clauses).repetition k).value = 1 := by + apply le_antisymm ((SourceGame.game clauses).repetition k).value_le_one + rw [← repeated_completeness_success clauses assignment satisfying k] + exact ((SourceGame.game clauses).repetition k).success_le_value _ + +end PerfectCompleteness.SourceAmplification + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Repetition/StoppedCleanCutEquality.lean b/lean/OAI/Computability/PerfectCompleteness/Repetition/StoppedCleanCutEquality.lean new file mode 100644 index 0000000000000000000000000000000000000000..230773aab068f550983e5cfc11d2fd24c7d4a713 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Repetition/StoppedCleanCutEquality.lean @@ -0,0 +1,82 @@ +import OAI.Computability.PerfectCompleteness.Foundations.StoppedProjectedExperiment +import OAI.Computability.PerfectCompleteness.Repetition.StoppedCleanGeometry + +namespace OAI + +section + +namespace PerfectCompleteness.StoppedCleanCutEquality + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays + +variable {branch : Nat → Nat} + +theorem append_left_injective {N M K : Nat} (pref : Path branch N M) : + Function.Injective (fun suff : Path branch M K => pref.append suff) := by + induction pref with + | refl _ => intro a b hab; exact hab + | step child pref ih => + intro a b hab + apply ih + change Path.step child (pref.append a) = Path.step child (pref.append b) at hab + injection hab + +theorem cut_eq_of_path_eq {N : Nat} {upper lower : Nodes branch N} + (left right : OwnInputReference.Cut upper lower) (hpath : left.path = right.path) : + left = right := by + cases left + cases right + cases hpath + rfl + +theorem cut_heq_of_fullPath_heq {N : Nat} {upper lower₁ lower₂ : Nodes branch N} + (hlower : lower₁ = lower₂) + (left : OwnInputReference.Cut upper lower₁) (right : OwnInputReference.Cut upper lower₂) + (hpath : HEq (WholeArrayInteriorOwnInputLaw.fullPath upper lower₁ left) + (WholeArrayInteriorOwnInputLaw.fullPath upper lower₂ right)) : HEq left right := by + cases hlower + apply heq_of_eq + apply cut_eq_of_path_eq + exact append_left_injective (Nodes.path upper) (eq_of_heq hpath) + +theorem cutOfBelow_heq_selectedCut {N i j : Nat} + (p : Path branch N (j + 1)) (q : Path branch (j + 1) (i + 1)) (hij : i < j) : + HEq (StoppedOwnInputGeometry.cutOfBelow (StoppedProjectedExperiment.below_append hij p q)) + (StoppedCleanGeometry.cut p q hij) := by + refine cut_heq_of_fullPath_heq (StoppedCleanGeometry.lowerNode_descendant p q hij).symm + _ _ ?_ + have hphysical : HEq + (WholeArrayInteriorOwnInputLaw.fullPath (WholeArrayInteriorExterior.upperNode p) + (WholeArrayInteriorExterior.upperNode (p.append q)) + (StoppedOwnInputGeometry.cutOfBelow (StoppedProjectedExperiment.below_append hij p q))) + (p.append q) := by + rw [StoppedOwnInputGeometry.fullPath_cutOfBelow] + exact WholeArrayInteriorExterior.upperNode_path_heq (p.append q) + exact hphysical.trans ((Sigma.mk.inj (StoppedCleanGeometry.fullPath_spec p q hij)).2.symm) + +variable {n i j t m : Nat} (rows : Nat → Nat) (hupper : j + 1 ≤ n) (hij : i < j) + (o : StoppedProjectedExperiment.Outer + (branch := branch) (n := n) (j := j) (t := t) (m := m)) + (k : StoppedProjectedExperiment.Inner + (branch := branch) (n := n) (i := i) (j := j) (t := t) rows) + +theorem stopped_lower_eq : + StoppedProjectedExperiment.lower rows hupper hij o k = + HierarchicalLeftDecoder.LowerNode (StoppedProjectedExperiment.upper hupper o) (i + 1) + (StoppedCleanGeometry.descendant (StoppedProjectedExperiment.upperPath hupper o) + (StoppedProjectedExperiment.lowerPath rows hij k) hij) := + (StoppedCleanGeometry.lowerNode_descendant (StoppedProjectedExperiment.upperPath hupper o) + (StoppedProjectedExperiment.lowerPath rows hij k) hij).symm + +theorem stopped_cut_heq : + HEq (StoppedProjectedExperiment.cut rows hupper hij o k) + (StoppedCleanGeometry.cut (StoppedProjectedExperiment.upperPath hupper o) + (StoppedProjectedExperiment.lowerPath rows hij k) hij) := + cutOfBelow_heq_selectedCut (StoppedProjectedExperiment.upperPath hupper o) + (StoppedProjectedExperiment.lowerPath rows hij k) hij + +end PerfectCompleteness.StoppedCleanCutEquality + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Repetition/StoppedCleanGeometry.lean b/lean/OAI/Computability/PerfectCompleteness/Repetition/StoppedCleanGeometry.lean new file mode 100644 index 0000000000000000000000000000000000000000..6d4d384e42f4d0af78f232cc7b6965671c6848c1 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Repetition/StoppedCleanGeometry.lean @@ -0,0 +1,172 @@ +import OAI.Computability.PerfectCompleteness.Construction.SourceQuestionCutSplit +import OAI.Computability.PerfectCompleteness.Decoding.DecoderSourcePullback +import OAI.Computability.PerfectCompleteness.Decoding.FixedDecoderCleanRateLemmas +import OAI.Computability.PerfectCompleteness.Foundations.WholeArrayInteriorExteriorLemmas +import OAI.Computability.PerfectCompleteness.Machines.WholeArrayInteriorOwnInputLaw +import OAI.Computability.PerfectCompleteness.Sampling.CutSamplerReplayTransportLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.StoppedCleanGeometry + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +variable {branch : Nat → Nat} + +def descendant : {N j i : Nat} → (p : Path branch N (j + 1)) → + (q : Path branch (j + 1) (i + 1)) → i < j → + HierarchicalFrozenTables.LowerNodes (WholeArrayInteriorExterior.upperNode p) (i + 1) + | _, _, _, .refl _, q, hij => + ⟨⟨WholeArrayInteriorExterior.upperNode q, + (WholeArrayInteriorExterior.upperNode_height q).trans_lt (Nat.succ_lt_succ hij)⟩, + WholeArrayInteriorExterior.upperNode_height q⟩ + | _, _, _, .step _ p, q, hij => descendant p q hij + +theorem lowerNode_descendant : {N j i : Nat} → (p : Path branch N (j + 1)) → + (q : Path branch (j + 1) (i + 1)) → (hij : i < j) → + HierarchicalLeftDecoder.LowerNode (WholeArrayInteriorExterior.upperNode p) (i + 1) + (descendant p q hij) = WholeArrayInteriorExterior.upperNode (p.append q) + | _, _, _, .refl _, _, _ => rfl + | N + 1, _, _, .step child p, q, hij => + congrArg (fun node : Nodes branch N => + (Sum.inr (child, node) : Nodes branch (N + 1))) (lowerNode_descendant p q hij) + +variable {N j i : Nat} (p : Path branch N (j + 1)) + (q : Path branch (j + 1) (i + 1)) (hij : i < j) + +def cut : OwnInputReference.Cut (WholeArrayInteriorExterior.upperNode p) + (HierarchicalLeftDecoder.LowerNode (WholeArrayInteriorExterior.upperNode p) (i + 1) + (descendant p q hij)) := + DecoderSourcePullback.selectedCut (WholeArrayInteriorExterior.upperNode p) (i + 1) + (descendant p q hij) + +@[simp] theorem lowerHeight : + Nodes.height (HierarchicalLeftDecoder.LowerNode + (WholeArrayInteriorExterior.upperNode p) (i + 1) (descendant p q hij)) = i + 1 := + CleanDecoderContext.lowerHeight (WholeArrayInteriorExterior.upperNode p) (descendant p q hij) + +theorem fullPath_spec : {N j i : Nat} → (p : Path branch N (j + 1)) → + (q : Path branch (j + 1) (i + 1)) → (hij : i < j) → + (⟨Nodes.height (HierarchicalLeftDecoder.LowerNode + (WholeArrayInteriorExterior.upperNode p) (i + 1) (descendant p q hij)), + WholeArrayInteriorOwnInputLaw.fullPath (WholeArrayInteriorExterior.upperNode p) + (HierarchicalLeftDecoder.LowerNode (WholeArrayInteriorExterior.upperNode p) (i + 1) + (descendant p q hij)) (cut p q hij)⟩ : Σ height, Path branch N height) = + ⟨i + 1, p.append q⟩ + | _, _, _, .refl _, q, _ => WholeArrayInteriorExterior.upperNode_spec q + | N + 1, _, _, .step child p, q, hij => + congrArg (fun z : Σ height, Path branch N height => + (⟨z.1, Path.step child z.2⟩ : Σ height, Path branch (N + 1) height)) + (fullPath_spec p q hij) + +private theorem append_cast_heq {N a b c : Nat} (pref : Path branch N a) + (suffix : Path branch a b) (h : b = c) : + HEq (pref.append (h ▸ suffix)) (pref.append suffix) := by + cases h + rfl + +theorem cleanPath_eq : + CleanRecordDecoderInput.path (WholeArrayInteriorExterior.upperNode p) + (descendant p q hij) (cut p q hij) = p.append q := by + apply eq_of_heq + exact (append_cast_heq (Nodes.path (WholeArrayInteriorExterior.upperNode p)) + (cut p q hij).path + (CleanDecoderContext.lowerHeight (WholeArrayInteriorExterior.upperNode p) + (descendant p q hij))).trans ((Sigma.mk.inj (fullPath_spec p q hij)).2) + +def firstLeaf (hbranch : ∀ k, 0 < branch k) : (height : Nat) → Slots branch height + | 0 => () + | height + 1 => (⟨0, hbranch height⟩, firstLeaf hbranch height) + +section Fixed + +variable {δ : ℚ} {hδ : 0 < δ} (parameters : FixedParameters.Parameters δ hδ) + (input : List Bool) {N j i : Nat} + (p : Path (FixedParameters.branch parameters) N (j + 1)) + (q : Path (FixedParameters.branch parameters) (j + 1) (i + 1)) + +abbrev OutsideQuestions := SourceQuestionCutSplit.OutsideQuestions (p.append q) + (FixedRows.sourceLength parameters.plan hδ) + (PCPSource.normalizedFormula (BinaryLanguage.totalRename input)).clauses.length + +def fixedOutside (external : OutsideQuestions parameters input p q) := + sourceSlots (PCPSource.clauseFamily (BinaryLanguage.totalRename input)) + (PreliminarySampler.endpoints + (SourceQuestionCutSplit.join (p.append q) (fun _ _ => 0) external)) + +def placeholder : Slots (FixedParameters.branch parameters) (i + 1) → + Fin (FixedRows.sourceLength parameters.plan hδ) → MixedSupport.Slot := + fun _ _ => SourceKeys.slot (PCPSource.clauseFamily (BinaryLanguage.totalRename input)) (.clause 0) + +theorem fixedOutside_at (external : OutsideQuestions parameters input p q) + (leaf : SourceQuestionCutSplit.OutsideLeaf (p.append q)) + (coordinate : Fin (FixedRows.sourceLength parameters.plan hδ)) : + fixedOutside parameters input p q external leaf.val coordinate = + SourceKeys.slot (PCPSource.clauseFamily (BinaryLanguage.totalRename input)) + (.clause (external leaf coordinate)) := by + unfold fixedOutside sourceSlots PreliminarySampler.endpoints + rw [SourceQuestionCutSplit.join_outside] + +abbrev Exterior (external : OutsideQuestions parameters input p q) := + WholeCutGrouping.Exterior (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (p.append q) (fixedOutside parameters input p q external) + +variable (hij : i < j) (external : OutsideQuestions parameters input p q) + +def filledExteriorEquiv : Exterior parameters input p q external ≃ + CleanPhysicalReplay.Exterior (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (p.append q) (fixedOutside parameters input p q external) + (placeholder parameters input (i := i)) := + WholeCutExteriorTransport.equiv (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (p.append q) (fixedOutside parameters input p q external) + (CutSlotAssembly.fill (p.append q) (fixedOutside parameters input p q external) + (placeholder parameters input (i := i))) + (fun leaf hleaf => (CutSlotAssembly.fill_outside (p.append q) + (fixedOutside parameters input p q external) (placeholder parameters input (i := i)) + leaf hleaf).symm) + +def exteriorEquiv : Exterior parameters input p q external ≃ + CleanPhysicalReplay.Exterior (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (CleanRecordDecoderInput.path (WholeArrayInteriorExterior.upperNode p) + (descendant p q hij) (cut p q hij)) (fixedOutside parameters input p q external) + (placeholder parameters input (i := i)) := + (filledExteriorEquiv parameters input p q external).trans + (Equiv.cast (congrArg (fun path : Path (FixedParameters.branch parameters) N (i + 1) => + CleanPhysicalReplay.Exterior (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + path (fixedOutside parameters input p q external) + (placeholder parameters input (i := i))) + (cleanPath_eq p q hij).symm)) + +theorem exteriorEquiv_law : + (FiniteDistribution.uniform (Exterior parameters input p q external)).pushforward + (exteriorEquiv parameters input p q hij external) = FiniteDistribution.uniform _ := by + rw [← FiniteDistribution.transport_eq_pushforward] + exact UniformConditioning.uniform_transport (exteriorEquiv parameters input p q hij external) + +def geometry (exterior : Exterior parameters input p q external) : + FixedDecoderCleanRate.Geometry parameters N i (WholeArrayInteriorExterior.upperNode p) + (descendant p q hij) where + designated := fun _ => firstLeaf (FixedParameters.branch_pos parameters) i + cut := cut p q hij + outside := fixedOutside parameters input p q external + placeholder := placeholder parameters input + exterior := exteriorEquiv parameters input p q hij external exterior + +theorem geometry_path (exterior : Exterior parameters input p q external) : + CleanRecordDecoderInput.path (WholeArrayInteriorExterior.upperNode p) (descendant p q hij) + (geometry parameters input p q hij external exterior).cut = p.append q := + cleanPath_eq p q hij + +end Fixed +end +end PerfectCompleteness.StoppedCleanGeometry + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/BoundedListSamplingLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/BoundedListSamplingLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..158aff763495cfaff14d912da2e1a6815c5d63b1 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/BoundedListSamplingLemmas.lean @@ -0,0 +1,243 @@ +import Mathlib.Data.Rat.Cast.Order +import OAI.Computability.PerfectCompleteness.Reduction.CompletionSoundness +import OAI.Computability.PerfectCompleteness.Reduction.TargetGameLemmas +import OAI.Computability.PerfectCompleteness.Repetition.CleanConditioning +import OAI.Computability.PerfectCompleteness.Sampling.FiniteListSampling +import OAI.Computability.UniqueGames.Foundations.SamplingLemmas + +namespace OAI + + +namespace PerfectCompleteness.BoundedListSampling + +noncomputable section + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games + +variable {Index A : Type*} [Fintype A] + +def listLaw (L : Finset A) (default : A) : FiniteDistribution A := + if h : L.Nonempty then FiniteListSampling.uniformList L h + else FiniteListSampling.uniformList {default} (Finset.singleton_nonempty default) + +theorem listLaw_of_nonempty (L : Finset A) (default : A) (h : L.Nonempty) : + listLaw L default = FiniteListSampling.uniformList L h := by + simp [listLaw, h] + +@[simp] theorem listLaw_empty_weight (default a : A) : + (listLaw ∅ default).weight a = if a = default then 1 else 0 := by + simp [listLaw, FiniteListSampling.uniformList] + +theorem listLaw_weight_mem (L : Finset A) (default a : A) (ha : a ∈ L) : + (listLaw L default).weight a = 1 / (L.card : ℝ) := by + rw [listLaw_of_nonempty L default ⟨a, ha⟩] + exact FiniteListSampling.uniformList_weight_mem L ⟨a, ha⟩ a ha + +theorem listLaw_weight_lower (L : Finset A) (default : A) (M : ℝ) + (hM : 0 < M) (hcard : (L.card : ℝ) ≤ M) (a : A) (ha : a ∈ L) : + 1 / M ≤ (listLaw L default).weight a := by + rw [listLaw_weight_mem L default a ha] + have hcardPos : 0 < (L.card : ℝ) := Nat.cast_pos.mpr (Finset.Nonempty.card_pos ⟨a, ha⟩) + apply (div_le_div_iff₀ hM hcardPos).mpr + simpa only [one_mul] using hcard + +theorem list_success_lower (L : Finset A) (default : A) (M : ℝ) + (hM : 0 < M) (hcard : (L.card : ℝ) ≤ M) (event : A → Bool) + (witness : ∃ a ∈ L, event a = true) : + 1 / M ≤ (listLaw L default).probability event := by + obtain ⟨a, ha, hevent⟩ := witness + exact (listLaw_weight_lower L default M hM hcard a ha).trans + (FiniteListSampling.probability_ge_weight (listLaw L default) event a hevent) + +variable [Fintype Index] [Nonempty Index] + +def jointLaw (L : Index → Finset A) (default : A) : FiniteDistribution (Index × A) := + CleanConditioning.kernelJoint (FiniteDistribution.uniform Index) (fun σ => listLaw (L σ) default) + +@[simp] theorem jointLaw_weight (L : Index → Finset A) (default : A) (σ : Index) (a : A) : + (jointLaw L default).weight (σ, a) = + (1 / (Fintype.card Index : ℝ)) * (listLaw (L σ) default).weight a := rfl + +theorem jointLaw_probability (L : Index → Finset A) (default : A) (event : Index × A → Bool) : + (jointLaw L default).probability event = + ∑ σ, (1 / (Fintype.card Index : ℝ)) * + (listLaw (L σ) default).probability (fun a => event (σ, a)) := + CleanConditioning.probability_kernelJoint _ _ _ + +theorem jointLaw_index_law (L : Index → Finset A) (default : A) : + (jointLaw L default).pushforward Prod.fst = FiniteDistribution.uniform Index := by + apply FiniteDistribution.eq_of_weight_eq + intro σ + change (∑ p : Index × A, if p.1 = σ then + (FiniteDistribution.uniform Index).weight p.1 * (listLaw (L p.1) default).weight p.2 else 0) = + (FiniteDistribution.uniform Index).weight σ + rw [Fintype.sum_prod_type] + calc + _ = ∑ τ, if τ = σ then (FiniteDistribution.uniform Index).weight τ else 0 := by + apply Finset.sum_congr rfl + intro τ _ + by_cases hτ : τ = σ + · simp only [ite_eq_left hτ, ← Finset.mul_sum, FiniteDistribution.normalized, mul_one] + · simp only [ite_eq_right hτ, Finset.sum_const_zero] + _ = _ := by simp + +theorem jointLaw_weight_ge_of_mem (L : Index → Finset A) (default : A) (M : ℝ) + (hM : 0 < M) (hcard : ∀ σ, ((L σ).card : ℝ) ≤ M) + (σ : Index) (a : A) (ha : a ∈ L σ) : + 1 / ((Fintype.card Index : ℝ) * M) ≤ (jointLaw L default).weight (σ, a) := by + rw [jointLaw_weight, ← one_div_mul_one_div] + exact mul_le_mul_of_nonneg_left (listLaw_weight_lower (L σ) default M hM (hcard σ) a ha) + (one_div_nonneg.mpr (Nat.cast_nonneg _)) + +theorem joint_success_lower (L : Index → Finset A) (default : A) (M : ℝ) + (hM : 0 < M) (hcard : ∀ σ, ((L σ).card : ℝ) ≤ M) + (event : Index × A → Bool) (witness : ∃ σ a, a ∈ L σ ∧ event (σ, a) = true) : + 1 / ((Fintype.card Index : ℝ) * M) ≤ (jointLaw L default).probability event := by + obtain ⟨σ, a, ha, hevent⟩ := witness + exact (jointLaw_weight_ge_of_mem L default M hM hcard σ a ha).trans + (FiniteListSampling.probability_ge_weight (jointLaw L default) event (σ, a) hevent) + +theorem joint_success_lower_of_indices (L : Index → Finset A) (default : A) (M : ℝ) + (hM : 0 < M) (hcard : ∀ σ, ((L σ).card : ℝ) ≤ M) + (event : Index × A → Bool) (good : Index → Bool) + (witness : ∀ σ, good σ = true → ∃ a ∈ L σ, event (σ, a) = true) : + (FiniteDistribution.uniform Index).probability good / M ≤ + (jointLaw L default).probability event := by + have hstep : ∀ σ, (if good σ then 1 / M else 0) ≤ + (listLaw (L σ) default).probability (fun a => event (σ, a)) := by + intro σ + by_cases hgood : good σ = true + · simpa only [hgood, ite_true] using + list_success_lower (L σ) default M hM (hcard σ) _ (witness σ hgood) + · simpa [hgood] using + (listLaw (L σ) default).probability_nonnegative (fun a => event (σ, a)) + calc + _ = ∑ σ, (FiniteDistribution.uniform Index).weight σ * (if good σ then 1 / M else 0) := by + simp only [FiniteDistribution.probability, Finset.sum_div, ite_div, zero_div, + mul_ite, mul_one_div, mul_zero] + _ ≤ ∑ σ, (FiniteDistribution.uniform Index).weight σ * + (listLaw (L σ) default).probability (fun a => event (σ, a)) := + Finset.sum_le_sum (fun σ _ => mul_le_mul_of_nonneg_left (hstep σ) + ((FiniteDistribution.uniform Index).nonnegative σ)) + _ = _ := (jointLaw_probability L default event).symm + +def outputLaw {B : Type*} [Fintype B] (L : Index → Finset A) (default : A) + (decode : Index → A → B) : FiniteDistribution B := + (jointLaw L default).pushforward (fun p => decode p.1 p.2) + +theorem outputLaw_probability {B : Type*} [Fintype B] + (L : Index → Finset A) (default : A) (decode : Index → A → B) (event : B → Bool) : + (outputLaw L default decode).probability event = + (jointLaw L default).probability (fun p => event (decode p.1 p.2)) := + FiniteDistribution.probability_pushforward _ _ _ + +theorem output_success_lower {B : Type*} [Fintype B] + (L : Index → Finset A) (default : A) (decode : Index → A → B) + (M : ℝ) (hM : 0 < M) (hcard : ∀ σ, ((L σ).card : ℝ) ≤ M) + (event : B → Bool) + (witness : ∃ σ a, a ∈ L σ ∧ event (decode σ a) = true) : + 1 / ((Fintype.card Index : ℝ) * M) ≤ (outputLaw L default decode).probability event := by + rw [outputLaw_probability] + exact joint_success_lower L default M hM hcard _ witness + +theorem output_weight_ge_of_mem {B : Type*} [Fintype B] + (L : Index → Finset A) (default : A) (decode : Index → A → B) + (M : ℝ) (hM : 0 < M) (hcard : ∀ σ, ((L σ).card : ℝ) ≤ M) + (σ : Index) (a : A) (ha : a ∈ L σ) : + 1 / ((Fintype.card Index : ℝ) * M) ≤ (outputLaw L default decode).weight (decode σ a) := by + have h := output_success_lower L default decode M hM hcard + (fun b => decide (b = decode σ a)) ⟨σ, a, ha, by simp⟩ + simpa [FiniteDistribution.probability] using h + +theorem independent_match_lower {B C : Type*} [Fintype B] [Fintype C] [Nonempty C] + (L : Index → Finset A) (default : A) (decode : Index → A → B) + (M : ℝ) (hM : 0 < M) (hcard : ∀ σ, ((L σ).card : ℝ) ≤ M) + (accepts : C → B → Bool) + (witness : ∃ σ a, a ∈ L σ ∧ ∃ c, accepts c (decode σ a) = true) : + 1 / ((Fintype.card C : ℝ) * (Fintype.card Index : ℝ) * M) ≤ + ((FiniteDistribution.uniform C).product (outputLaw L default decode)).probability + (fun p => accepts p.1 p.2) := by + obtain ⟨σ, a, ha, c, haccept⟩ := witness + have hright := output_weight_ge_of_mem L default decode M hM hcard σ a ha + calc + _ = (1 / (Fintype.card C : ℝ)) * (1 / ((Fintype.card Index : ℝ) * M)) := by + simp only [one_div_mul_one_div, mul_assoc] + _ ≤ ((FiniteDistribution.uniform C).product (outputLaw L default decode)).weight + (c, decode σ a) := + mul_le_mul_of_nonneg_left hright ((FiniteDistribution.uniform C).nonnegative c) + _ ≤ _ := FiniteListSampling.probability_ge_weight _ _ (c, decode σ a) haccept + +end +end PerfectCompleteness.BoundedListSampling + + + +namespace PerfectCompleteness.LegalUniform + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games +open WeightRounding + +noncomputable section + +def enumeratedWeights {E : Type*} [Fintype E] + (f : E → ℚ) (hpositive : ∀ e, 0 < f e) (htotal : ∑ e, f e = 1) + (enum : E ≃ Fin (Fintype.card E)) : PositiveWeights (Fintype.card E) where + weight i := f (enum.symm i) + positive i := hpositive (enum.symm i) + total := (enum.symm.sum_comp f).trans htotal + +theorem transport_weight_eq_enumerated {E : Type*} [Fintype E] + (μ : FiniteDistribution E) (f : E → ℚ) + (hpositive : ∀ e, 0 < f e) (htotal : ∑ e, f e = 1) + (hweights : ∀ e, μ.weight e = (f e : ℝ)) + (enum : E ≃ Fin (Fintype.card E)) (i : Fin (Fintype.card E)) : + (μ.transport enum).weight i = + ((enumeratedWeights f hpositive htotal enum).weight i : ℝ) := + hweights (enum.symm i) + +def uniformWeights (E : Type*) [Fintype E] [Nonempty E] : + PositiveWeights (Fintype.card E) where + weight _ := 1 / (Fintype.card E : ℚ) + positive _ := by + have hcard : (0 : ℚ) < Fintype.card E := by + exact_mod_cast (Fintype.card_pos : 0 < Fintype.card E) + exact div_pos zero_lt_one hcard + total := by + have hcard : (Fintype.card E : ℚ) ≠ 0 := + Nat.cast_ne_zero.mpr Fintype.card_ne_zero + simp only [Finset.sum_const, Finset.card_univ, Fintype.card_fin, + nsmul_eq_mul, one_div] + exact mul_inv_cancel₀ hcard + +@[simp] theorem uniformWeights_weight (E : Type*) [Fintype E] [Nonempty E] + (i : Fin (Fintype.card E)) : + (uniformWeights E).weight i = 1 / (Fintype.card E : ℚ) := rfl + +theorem transport_uniform_weight {E : Type*} [Fintype E] [Nonempty E] + (μ : FiniteDistribution E) (huniform : μ = FiniteDistribution.uniform E) + (enum : E ≃ Fin (Fintype.card E)) (i : Fin (Fintype.card E)) : + (μ.transport enum).weight i = ((uniformWeights E).weight i : ℝ) := by + rw [huniform] + change (1 / (Fintype.card E : ℝ)) = ((1 / (Fintype.card E : ℚ) : ℚ) : ℝ) + simp only [Rat.cast_div, Rat.cast_one, Rat.cast_natCast] + +theorem equivFin_uniform_weight {E : Type*} [Fintype E] [Nonempty E] + (μ : FiniteDistribution E) (huniform : μ = FiniteDistribution.uniform E) + (i : Fin (Fintype.card E)) : + (μ.transport (Fintype.equivFin E)).weight i = + ((uniformWeights E).weight i : ℝ) := + transport_uniform_weight μ huniform (Fintype.equivFin E) i + +theorem exists_uniform_weights {E : Type*} [Fintype E] [Nonempty E] + (μ : FiniteDistribution E) (huniform : μ = FiniteDistribution.uniform E) : + ∃ w : PositiveWeights (Fintype.card E), + (∀ i, w.weight i = 1 / (Fintype.card E : ℚ)) ∧ + ∀ i, (μ.transport (Fintype.equivFin E)).weight i = (w.weight i : ℝ) := by + exact ⟨uniformWeights E, uniformWeights_weight E, equivFin_uniform_weight μ huniform⟩ + +end +end PerfectCompleteness.LegalUniform + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/BucketDescriptorLaw.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/BucketDescriptorLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..290b8e2c95400ce77d2f3e87603c3caa39785342 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/BucketDescriptorLaw.lean @@ -0,0 +1,158 @@ +import OAI.Computability.PerfectCompleteness.Foundations.DependentPredictionDifferenceLemmas +import OAI.Computability.PerfectCompleteness.Foundations.FiniteProduct +import OAI.Computability.PerfectCompleteness.Sampling.RationalFiniteLawLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.BucketDescriptorLaw + +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +noncomputable section + +abbrev Buckets (D V : Type*) := D → V + +abbrev Record (E D V : Type*) := Σ _ : E, D × (Buckets D V × V) + +variable {D E T V : Type*} [Fintype D] [Fintype E] [Fintype T] [Fintype V] + +def bucketLaw (D : Type*) [Fintype D] (ρ : FiniteDistribution V) : + FiniteDistribution (Buckets D V) := + FiniteProduct.law (fun _ : D => ρ) + +def sampleLaw (δ : FiniteDistribution D) (ρ : FiniteDistribution V) : + FiniteDistribution (D × (Buckets D V × V)) := + δ.product ((bucketLaw D ρ).product ρ) + +def observe (read : T → E × Buckets D V) (z : D × (T × V)) : Record E D V := + ⟨(read z.2.1).1, (z.1, ((read z.2.1).2, z.2.2))⟩ + +private def reorder (D E B V : Type*) : + D × ((E × B) × V) ≃ Σ _ : E, D × (B × V) where + toFun z := ⟨z.2.1.1, (z.1, (z.2.1.2, z.2.2))⟩ + invFun z := (z.2.1, ((z.1, z.2.2.1), z.2.2.2)) + left_inv _ := rfl + right_inv _ := rfl + +theorem reorder_law {B : Type*} [Fintype B] + (δ : FiniteDistribution D) (ν : FiniteDistribution E) + (κ : FiniteDistribution B) (ρ : FiniteDistribution V) : + (δ.product ((ν.product κ).product ρ)).pushforward + (fun z => (⟨z.2.1.1, (z.1, (z.2.1.2, z.2.2))⟩ : Σ _ : E, D × (B × V))) = + CompletionSoundness.sigmaLaw ν (fun _ => δ.product (κ.product ρ)) := by + change (δ.product ((ν.product κ).product ρ)).pushforward (reorder D E B V) = _ + rw [← FiniteDistribution.transport_eq_pushforward] + apply FiniteDistribution.eq_of_weight_eq + intro z + change δ.weight z.2.1 * ((ν.weight z.1 * κ.weight z.2.2.1) * ρ.weight z.2.2.2) = + ν.weight z.1 * (δ.weight z.2.1 * (κ.weight z.2.2.1 * ρ.weight z.2.2.2)) + rw [mul_assoc] + exact mul_left_comm _ _ _ + +theorem observe_law (μ : FiniteDistribution T) (ν : FiniteDistribution E) + (ρ : FiniteDistribution V) (δ : FiniteDistribution D) + (read : T → E × Buckets D V) + (hread : μ.pushforward read = ν.product (bucketLaw D ρ)) : + (δ.product (μ.product ρ)).pushforward (observe read) = + CompletionSoundness.sigmaLaw ν (fun _ => sampleLaw δ ρ) := by + have hinner : (μ.product ρ).pushforward (fun z => (read z.1, z.2)) = + (ν.product (bucketLaw D ρ)).product ρ := by + simpa only [id_eq, FiniteDistribution.pushforward_id, hread] using + FiniteDistribution.product_pushforward μ ρ read (id : V → V) + have houter : (δ.product (μ.product ρ)).pushforward + (fun z => (z.1, (read z.2.1, z.2.2))) = + δ.product ((ν.product (bucketLaw D ρ)).product ρ) := by + simpa only [id_eq, FiniteDistribution.pushforward_id, hinner] using + FiniteDistribution.product_pushforward δ (μ.product ρ) (id : D → D) + (fun z : T × V => (read z.1, z.2)) + calc + _ = ((δ.product (μ.product ρ)).pushforward + (fun z => (z.1, (read z.2.1, z.2.2)))).pushforward + (reorder D E (Buckets D V) V) := + (FiniteDistribution.pushforward_comp _ _ _).symm + _ = (δ.product ((ν.product (bucketLaw D ρ)).product ρ)).pushforward + (reorder D E (Buckets D V) V) := + congrArg (fun η : FiniteDistribution (D × ((E × Buckets D V) × V)) => + η.pushforward (reorder D E (Buckets D V) V)) houter + _ = _ := reorder_law δ ν (bucketLaw D ρ) ρ + +variable {D' V' : Type*} [Fintype D'] [Fintype V'] + +def sampleEquiv (eD : D ≃ D') (eV : V ≃ V') : + (D × (Buckets D V × V)) ≃ (D' × (Buckets D' V' × V')) := + Equiv.prodCongr eD (Equiv.prodCongr (Equiv.arrowCongr eD eV) eV) + +def recordEquiv (eD : D ≃ D') (eV : V ≃ V') : Record E D V ≃ Record E D' V' := + Equiv.sigmaCongrRight (fun _ => sampleEquiv eD eV) + +theorem bucketLaw_equiv (ρ : FiniteDistribution V) (eD : D ≃ D') (eV : V ≃ V') : + (bucketLaw D ρ).pushforward (Equiv.arrowCongr eD eV) = + bucketLaw D' (ρ.pushforward eV) := by + rw [← FiniteDistribution.transport_eq_pushforward (bucketLaw D ρ) (Equiv.arrowCongr eD eV), + ← FiniteDistribution.transport_eq_pushforward ρ eV] + apply FiniteDistribution.eq_of_weight_eq + intro buckets + change (∏ d : D, ρ.weight (eV.symm (buckets (eD d)))) = + ∏ d : D', ρ.weight (eV.symm (buckets d)) + exact eD.prod_comp (fun d => ρ.weight (eV.symm (buckets d))) + +theorem sampleLaw_equiv (δ : FiniteDistribution D) (ρ : FiniteDistribution V) + (eD : D ≃ D') (eV : V ≃ V') : + (sampleLaw δ ρ).pushforward (sampleEquiv eD eV) = + sampleLaw (δ.pushforward eD) (ρ.pushforward eV) := by + have hinner : ((bucketLaw D ρ).product ρ).pushforward + (Equiv.prodCongr (Equiv.arrowCongr eD eV) eV) = + (bucketLaw D' (ρ.pushforward eV)).product (ρ.pushforward eV) := by + exact (FiniteDistribution.product_pushforward (bucketLaw D ρ) ρ + (Equiv.arrowCongr eD eV) eV).trans + (congrArg (fun η : FiniteDistribution (Buckets D' V') => η.product (ρ.pushforward eV)) + (bucketLaw_equiv ρ eD eV)) + exact (FiniteDistribution.product_pushforward δ ((bucketLaw D ρ).product ρ) + eD (Equiv.prodCongr (Equiv.arrowCongr eD eV) eV)).trans + (congrArg (fun η : FiniteDistribution (Buckets D' V' × V') => + (δ.pushforward eD).product η) hinner) + +theorem reference_equiv (ν : FiniteDistribution E) (δ : FiniteDistribution D) + (ρ : FiniteDistribution V) (eD : D ≃ D') (eV : V ≃ V') : + (CompletionSoundness.sigmaLaw ν (fun _ => sampleLaw δ ρ)).pushforward + (recordEquiv (E := E) eD eV) = + CompletionSoundness.sigmaLaw ν + (fun _ => sampleLaw (δ.pushforward eD) (ρ.pushforward eV)) := by + have hmap : (⇑(recordEquiv (E := E) eD eV) : Record E D V → Record E D' V') = + (fun z => ⟨z.1, sampleEquiv eD eV z.2⟩) := by + funext z + cases z + rfl + rw [hmap] + have h := SigmaObservation.pushforward_fiber ν (fun _ => sampleLaw δ ρ) + (fun _ => ⇑(sampleEquiv eD eV)) + simpa only [sampleLaw_equiv] using h + +theorem observe_equiv_law (μ : FiniteDistribution T) (ν : FiniteDistribution E) + (ρ : FiniteDistribution V) (δ : FiniteDistribution D) + (read : T → E × Buckets D V) + (hread : μ.pushforward read = ν.product (bucketLaw D ρ)) + (eD : D ≃ D') (eV : V ≃ V') : + (δ.product (μ.product ρ)).pushforward + (fun z => recordEquiv (E := E) eD eV (observe read z)) = + CompletionSoundness.sigmaLaw ν + (fun _ => sampleLaw (δ.pushforward eD) (ρ.pushforward eV)) := by + calc + _ = ((δ.product (μ.product ρ)).pushforward (observe read)).pushforward + (recordEquiv (E := E) eD eV) := + (FiniteDistribution.pushforward_comp _ _ _).symm + _ = (CompletionSoundness.sigmaLaw ν (fun _ => sampleLaw δ ρ)).pushforward + (recordEquiv (E := E) eD eV) := + congrArg (fun η : FiniteDistribution (Record E D V) => + η.pushforward (recordEquiv (E := E) eD eV)) (observe_law μ ν ρ δ read hread) + _ = _ := reference_equiv ν δ ρ eD eV + +end +end PerfectCompleteness.BucketDescriptorLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/BucketResamplingLaw.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/BucketResamplingLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..5ca419cceec78fa66f8cd5a8a78b56adedd6f494 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/BucketResamplingLaw.lean @@ -0,0 +1,70 @@ +import OAI.Computability.PerfectCompleteness.Sampling.BucketSampler +import OAI.Computability.PerfectCompleteness.Sampling.UniformDifference + +namespace OAI + +section + +namespace PerfectCompleteness.BucketResamplingLaw + +noncomputable section + +open scoped Classical +open UniqueGamesTheorem.Foundations.Games +open BucketSampler (F2 Direction Tape) + +variable {H : Type*} [AddCommGroup H] [Module F2 H] [Fintype H] + +private theorem pushforward_id {A : Type*} [Fintype A] (μ : FiniteDistribution A) : + μ.pushforward (fun a => a) = μ := by + apply FiniteDistribution.eq_of_weight_eq + intro a + simp [FiniteDistribution.pushforward] + +theorem assembled_difference_law (ℓ : Nat) (μ : FiniteDistribution (Tape ℓ H)) + (a : Direction ℓ) : + (μ.product (FiniteDistribution.uniform H)).pushforward + (fun p => (BucketSampler.evaluate ℓ id p.1, p.2 - p.1 a)) = + (μ.pushforward (BucketSampler.evaluate ℓ id)).product (FiniteDistribution.uniform H) := by + rw [UniformDifference.observed_difference_law μ (fun t => t a) + (BucketSampler.evaluate ℓ id)] + have hp := FiniteDistribution.product_pushforward μ (FiniteDistribution.uniform H) + (BucketSampler.evaluate ℓ (id : H → H)) (id : H → H) + have hi : (FiniteDistribution.uniform H).pushforward (id : H → H) = + FiniteDistribution.uniform H := pushforward_id (FiniteDistribution.uniform H) + rw [hi] at hp + simpa only [id_eq] using hp + +theorem resampled_array_pair_law (ℓ : Nat) (μ : FiniteDistribution (Tape ℓ H)) + (a : Direction ℓ) : + (μ.product (FiniteDistribution.uniform H)).pushforward + (fun p => (BucketSampler.evaluate ℓ id p.1, + BucketSampler.evaluate ℓ id (Function.update p.1 a p.2))) = + ((μ.pushforward (BucketSampler.evaluate ℓ id)).product + (FiniteDistribution.uniform H)).pushforward + (fun p => (p.1, p.1 + BucketSampler.rankOne a.val p.2)) := by + have h := congrArg + (fun ν : FiniteDistribution ((Fin ℓ → H) × H) => ν.pushforward + (fun p => (p.1, p.1 + BucketSampler.rankOne a.val p.2))) + (assembled_difference_law ℓ μ a) + rw [FiniteDistribution.pushforward_comp] at h + simpa only [BucketSampler.evaluate_update, id_eq] using h + +theorem resampled_event_probability (ℓ : Nat) (μ : FiniteDistribution (Tape ℓ H)) + (a : Direction ℓ) (event : (Fin ℓ → H) × (Fin ℓ → H) → Bool) : + (μ.product (FiniteDistribution.uniform H)).probability + (fun p => event (BucketSampler.evaluate ℓ id p.1, + BucketSampler.evaluate ℓ id (Function.update p.1 a p.2))) = + ((μ.pushforward (BucketSampler.evaluate ℓ id)).product + (FiniteDistribution.uniform H)).probability + (fun p => event (p.1, p.1 + BucketSampler.rankOne a.val p.2)) := by + have h := congrArg (fun ν => FiniteDistribution.probability ν event) + (resampled_array_pair_law ℓ μ a) + simpa only [FiniteDistribution.probability_pushforward] using h + +end +end PerfectCompleteness.BucketResamplingLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/BucketSampler.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/BucketSampler.lean new file mode 100644 index 0000000000000000000000000000000000000000..149d81815095e0e80352b3e3ab5fe5e1a0404574 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/BucketSampler.lean @@ -0,0 +1,204 @@ +import Mathlib.Algebra.Field.ZMod +import OAI.Computability.PerfectCompleteness.Algebra.EvaluationMatrix +import OAI.Computability.PerfectCompleteness.Sampling.RecordSeedSamplingLemmas + +namespace OAI + + +namespace PerfectCompleteness.BucketSampler + +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +noncomputable section + +abbrev F2 := ZMod 2 + +abbrev Direction (ℓ : Nat) := {v : Fin ℓ → F2 // v ≠ 0} + +abbrev Tape (ℓ : Nat) (Ω : Type*) := Direction ℓ → Ω + +variable {Ω H : Type*} [AddCommGroup H] [Module F2 H] + +def rankOne {ℓ : Nat} (v : Fin ℓ → F2) (h : H) : Fin ℓ → H := + fun i => v i • h + +def evaluate (ℓ : Nat) (eval : Ω → H) (t : Tape ℓ Ω) : Fin ℓ → H := + fun i => ∑ v : Direction ℓ, v.val i • eval (t v) + +theorem evaluate_eq_sum (ℓ : Nat) (eval : Ω → H) (t : Tape ℓ Ω) : + evaluate ℓ eval t = ∑ v : Direction ℓ, rankOne v.val (eval (t v)) := by + funext i + simp only [evaluate, Finset.sum_apply, rankOne] + +theorem evaluate_update (ℓ : Nat) (eval : Ω → H) (t : Tape ℓ Ω) + (a : Direction ℓ) (new : Ω) : + evaluate ℓ eval (Function.update t a new) = + evaluate ℓ eval t + rankOne a.val (eval new - eval (t a)) := by + funext i + let S : H := ∑ v : Direction ℓ, v.val i • eval (t v) + let S' : H := ∑ v : Direction ℓ, v.val i • eval (Function.update t a new v) + have hd : S' - S = a.val i • (eval new - eval (t a)) := by + dsimp only [S', S] + rw [← Finset.sum_sub_distrib, Finset.sum_eq_single a] + · rw [Function.update_self, smul_sub] + · intro b _ hba + simp only [Function.update_of_ne hba, sub_self] + · intro ha + exact (ha (Finset.mem_univ a)).elim + change S' = S + a.val i • (eval new - eval (t a)) + simpa only [sub_add_cancel] using + (congrArg (fun z : H => z + S) hd).trans (add_comm _ _) + +theorem linearMap_evaluate (ℓ : Nat) (eval : Ω → H) (t : Tape ℓ Ω) + (q : H →ₗ[F2] F2) (i : Fin ℓ) : + q (evaluate ℓ eval t i) = ∑ v : Direction ℓ, v.val i * q (eval (t v)) := by + simp only [evaluate, map_sum, map_smul, smul_eq_mul] + +theorem evaluate_apply {X : Type*} (ℓ : Nat) (V : Submodule F2 (X → F2)) + (eval : Ω → V) (t : Tape ℓ Ω) (i : Fin ℓ) (x : X) : + (evaluate ℓ eval t i).val x = + ∑ v : Direction ℓ, v.val i * (eval (t v)).val x := + linearMap_evaluate ℓ eval t (EvaluationMatrix.evaluation V x) i + +instance directionZero_isEmpty : IsEmpty (Direction 0) where + false v := v.property (funext fun i => Fin.elim0 i) + +@[simp] theorem evaluate_zero_width (eval : Ω → H) (t : Tape 0 Ω) : + evaluate 0 eval t = 0 := by + funext i + exact Fin.elim0 i + +section Laws + +variable [Fintype Ω] + +def tapeLaw (ℓ : Nat) (μ : FiniteDistribution Ω) : FiniteDistribution (Tape ℓ Ω) := + FiniteProduct.law (fun _ : Direction ℓ => μ) + +@[simp] theorem tapeLaw_weight (ℓ : Nat) (μ : FiniteDistribution Ω) (t : Tape ℓ Ω) : + (tapeLaw ℓ μ).weight t = ∏ v : Direction ℓ, μ.weight (t v) := rfl + +theorem tapeLaw_marginal (ℓ : Nat) (μ : FiniteDistribution Ω) (v : Direction ℓ) : + (tapeLaw ℓ μ).pushforward (fun t => t v) = μ := + FiniteProduct.eval_pushforward (fun _ : Direction ℓ => μ) v + +theorem expectation_product (ℓ : Nat) (μ : FiniteDistribution Ω) + (f : Direction ℓ → Ω → ℝ) : + (tapeLaw ℓ μ).expectation (fun t => ∏ v, f v (t v)) = + ∏ v, μ.expectation (f v) := + FiniteProduct.expectation_product (fun _ : Direction ℓ => μ) f + +omit [AddCommGroup H] [Module F2 H] in +theorem expectation_bucket_mul (ℓ : Nat) (μ : FiniteDistribution Ω) + (eval : Ω → H) (v w : Direction ℓ) (hvw : v ≠ w) (f g : H → ℝ) : + (tapeLaw ℓ μ).expectation (fun t => f (eval (t v)) * g (eval (t w))) = + μ.expectation (fun t => f (eval t)) * μ.expectation (fun t => g (eval t)) := + FiniteProduct.expectation_eval_mul (fun _ : Direction ℓ => μ) v w hvw + (fun t => f (eval t)) (fun t => g (eval t)) + +@[simp] theorem tapeLaw_zero_width_weight (μ : FiniteDistribution Ω) (t : Tape 0 Ω) : + (tapeLaw 0 μ).weight t = 1 := by + simp [tapeLaw, FiniteProduct.law] + +variable [Fintype H] + +omit [AddCommGroup H] [Module F2 H] in +theorem bucket_marginal (ℓ : Nat) (μ : FiniteDistribution Ω) (eval : Ω → H) + (v : Direction ℓ) : + (tapeLaw ℓ μ).pushforward (fun t => eval (t v)) = μ.pushforward eval := by + apply FiniteDistribution.eq_of_weight_eq + intro h + calc + _ = (tapeLaw ℓ μ).expectation (fun t => if eval (t v) = h then 1 else 0) := by + simp [FiniteDistribution.pushforward, FiniteDistribution.expectation, mul_ite] + _ = μ.expectation (fun t => if eval t = h then 1 else 0) := + FiniteProduct.expectation_eval (fun _ : Direction ℓ => μ) v + (fun t : Ω => if eval t = h then (1 : ℝ) else 0) + _ = _ := by + simp [FiniteDistribution.pushforward, FiniteDistribution.expectation, mul_ite] + +def law (ℓ : Nat) (μ : FiniteDistribution Ω) (eval : Ω → H) : + FiniteDistribution (Fin ℓ → H) := + (tapeLaw ℓ μ).pushforward (evaluate ℓ eval) + +theorem probability_law (ℓ : Nat) (μ : FiniteDistribution Ω) (eval : Ω → H) + (event : (Fin ℓ → H) → Bool) : + (law ℓ μ eval).probability event = + (tapeLaw ℓ μ).probability (fun t => event (evaluate ℓ eval t)) := + FiniteDistribution.probability_pushforward _ _ _ + +end Laws + +section FreshArrays + +variable {J : Type*} [Fintype J] [DecidableEq J] [Fintype Ω] + +abbrev FreshTape (J : Type*) (ℓ : Nat) (Ω : Type*) := J → Tape ℓ Ω + +def freshTapeLaw (J : Type*) [Fintype J] [DecidableEq J] (ℓ : Nat) + (μ : FiniteDistribution Ω) : FiniteDistribution (FreshTape J ℓ Ω) := + FiniteProduct.law (fun _ : J => tapeLaw ℓ μ) + +theorem freshTapeLaw_marginal (ℓ : Nat) (μ : FiniteDistribution Ω) (j : J) : + (freshTapeLaw J ℓ μ).pushforward (fun t => t j) = tapeLaw ℓ μ := + FiniteProduct.eval_pushforward (fun _ : J => tapeLaw ℓ μ) j + +theorem freshArrays_expectation_product (ℓ : Nat) (μ : FiniteDistribution Ω) + (eval : Ω → H) (f : J → (Fin ℓ → H) → ℝ) : + (freshTapeLaw J ℓ μ).expectation + (fun t => ∏ j, f j (evaluate ℓ eval (t j))) = + ∏ j, (tapeLaw ℓ μ).expectation (fun t => f j (evaluate ℓ eval t)) := + FiniteProduct.expectation_product (fun _ : J => tapeLaw ℓ μ) + (fun j t => f j (evaluate ℓ eval t)) + +end FreshArrays + + +open PointwiseSpaces RecursiveSpaces DescendantSpaces + +universe u +variable {branch : Nat → Nat} {n m : Nat} + +abbrev RecursiveTape (ℓ : Nat) (repeats : Nat → Nat) (p : Path branch n m) + (A : Slots branch n → Type u) := + Tape ℓ (RecursiveSampler.Tape F2 repeats p A) + +def recursiveEvaluate (ℓ : Nat) (repeats : Nat → Nat) (p : Path branch n m) + (A : Slots branch n → Type u) (t : RecursiveTape ℓ repeats p A) : + Fin ℓ → space F2 branch n A := + evaluate ℓ (RecursiveSampler.evaluate F2 repeats p A) t + +def recursiveTapeLaw (ℓ : Nat) (repeats : Nat → Nat) (p : Path branch n m) + (A : Slots branch n → Type u) [∀ s, Finite (A s)] : + FiniteDistribution (RecursiveTape ℓ repeats p A) := + tapeLaw ℓ (RecursiveSampler.tapeLaw F2 repeats p A) + +theorem recursiveTapeLaw_marginal (ℓ : Nat) (repeats : Nat → Nat) + (p : Path branch n m) (A : Slots branch n → Type u) [∀ s, Finite (A s)] + (v : Direction ℓ) : + (recursiveTapeLaw ℓ repeats p A).pushforward (fun t => t v) = + RecursiveSampler.tapeLaw F2 repeats p A := + tapeLaw_marginal ℓ (RecursiveSampler.tapeLaw F2 repeats p A) v + +theorem recursiveBucket_marginal (ℓ : Nat) (repeats : Nat → Nat) + (p : Path branch n m) (A : Slots branch n → Type u) [∀ s, Finite (A s)] + [Fintype (space F2 branch n A)] (v : Direction ℓ) : + (recursiveTapeLaw ℓ repeats p A).pushforward + (fun t => RecursiveSampler.evaluate F2 repeats p A (t v)) = + RecursiveSampler.law F2 repeats p A := + bucket_marginal ℓ (RecursiveSampler.tapeLaw F2 repeats p A) + (RecursiveSampler.evaluate F2 repeats p A) v + +theorem recursiveEvaluate_apply (ℓ : Nat) (repeats : Nat → Nat) + (p : Path branch n m) (A : Slots branch n → Type u) + (t : RecursiveTape ℓ repeats p A) (i : Fin ℓ) (x : Assignment A) : + (recursiveEvaluate ℓ repeats p A t i).val x = + ∑ v : Direction ℓ, v.val i * + (RecursiveSampler.evaluate F2 repeats p A (t v)).val x := + evaluate_apply ℓ (space F2 branch n A) (RecursiveSampler.evaluate F2 repeats p A) t i x + +end +end PerfectCompleteness.BucketSampler + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/BucketUniformLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/BucketUniformLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..0d850b8eab46c2acdb7e10e299c4fd85392e46d9 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/BucketUniformLemmas.lean @@ -0,0 +1,515 @@ +import Mathlib.Algebra.BigOperators.Pi +import Mathlib.LinearAlgebra.BilinearMap +import Mathlib.SetTheory.Cardinal.Finite +import OAI.Computability.PerfectCompleteness.Algebra.UniformLinearImage +import OAI.Computability.PerfectCompleteness.Sampling.BucketSampler +import OAI.Computability.PerfectCompleteness.Sampling.RationalFiniteLawLemmas +import OAI.Computability.PerfectCompleteness.Sampling.RecordSeedSamplingLemmas +import OAI.Computability.UniqueGames.Games.FinishBoundsLemmas + +namespace OAI + + +namespace PerfectCompleteness.BucketUniform + +noncomputable section + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games +open BucketSampler (F2 Direction) + +variable {H : Type*} [AddCommGroup H] [Module F2 H] + +def coordinateDirection {ℓ : Nat} (i : Fin ℓ) : Direction ℓ := + ⟨Pi.single i (1 : F2), by + intro h + have hi := congrFun h i + simp at hi⟩ + +def evaluateLinear (ℓ : Nat) : (Direction ℓ → H) →ₗ[F2] (Fin ℓ → H) where + toFun := BucketSampler.evaluate ℓ (id : H → H) + map_add' t u := by + funext i + simp only [BucketSampler.evaluate, id_eq, Pi.add_apply, smul_add, + Finset.sum_add_distrib] + map_smul' a t := by + funext i + change (∑ v : Direction ℓ, v.val i • (a • t v)) = + a • ∑ v : Direction ℓ, v.val i • t v + rw [Finset.smul_sum] + exact Finset.sum_congr rfl (fun v _ => smul_comm _ _ _) + +@[simp] theorem evaluateLinear_apply (ℓ : Nat) (t : Direction ℓ → H) : + evaluateLinear ℓ t = BucketSampler.evaluate ℓ (id : H → H) t := rfl + +theorem evaluate_single {ℓ : Nat} (v : Direction ℓ) (h : H) : + evaluateLinear ℓ (Pi.single v h) = BucketSampler.rankOne v.val h := by + funext i + change (∑ w : Direction ℓ, w.val i • (Pi.single v h) w) = v.val i • h + rw [Finset.sum_eq_single v] + · simp + · intro w _ hw + simp [hw] + · intro hv + exact (hv (Finset.mem_univ v)).elim + +theorem evaluate_coordinate_bucket {ℓ : Nat} (i : Fin ℓ) (h : H) : + evaluateLinear ℓ (Pi.single (coordinateDirection i) h) = Pi.single i h := by + rw [evaluate_single] + funext j + by_cases hij : i = j + · subst j + simp [BucketSampler.rankOne, coordinateDirection] + · simp [BucketSampler.rankOne, coordinateDirection, Ne.symm hij] + +def coordinateTape {ℓ : Nat} (rows : Fin ℓ → H) : Direction ℓ → H := + ∑ i : Fin ℓ, Pi.single (coordinateDirection i) (rows i) + +theorem evaluate_coordinateTape {ℓ : Nat} (rows : Fin ℓ → H) : + evaluateLinear ℓ (coordinateTape rows) = rows := by + unfold coordinateTape + rw [map_sum] + simp only [evaluate_coordinate_bucket, Finset.univ_sum_single] + +theorem evaluateLinear_surjective (ℓ : Nat) : + Function.Surjective (evaluateLinear (H := H) ℓ) := + fun rows => ⟨coordinateTape rows, evaluate_coordinateTape rows⟩ + +theorem evaluate_surjective (ℓ : Nat) : + Function.Surjective (BucketSampler.evaluate ℓ (id : H → H)) := + evaluateLinear_surjective ℓ + +theorem uniform_evaluate_law [Fintype H] (ℓ : Nat) : + (BucketSampler.tapeLaw ℓ (FiniteDistribution.uniform H)).pushforward + (BucketSampler.evaluate ℓ (id : H → H)) = + FiniteDistribution.uniform (Fin ℓ → H) := + UniformLinearImage.product_uniform_linear_image + (I := Direction ℓ) (Ω := fun _ => H) (R := F2) (V := Fin ℓ → H) + (evaluateLinear (H := H) ℓ) (evaluateLinear_surjective (H := H) ℓ) + +theorem uniform_array_law [Fintype H] (ℓ : Nat) : + BucketSampler.law ℓ (FiniteDistribution.uniform H) (id : H → H) = + FiniteDistribution.uniform (Fin ℓ → H) := + uniform_evaluate_law ℓ + + +variable {Ω : Type*} (V : Submodule F2 (Ω → F2)) + +def ofRowsLinear (ℓ : Nat) : + (Fin ℓ → V) →ₗ[F2] (Module.Dual F2 V →ₗ[F2] (Fin ℓ → F2)) where + toFun := EvaluationMatrix.ofRows V + map_add' rows rows' := by + apply LinearMap.ext + intro q + funext i + exact map_add q (rows i) (rows' i) + map_smul' a rows := by + apply LinearMap.ext + intro q + funext i + exact map_smul q a (rows i) + +theorem ofRowsLinear_surjective [FiniteDimensional F2 V] (ℓ : Nat) : + Function.Surjective (ofRowsLinear V ℓ) := + fun X => ⟨EvaluationMatrix.rows V X, EvaluationMatrix.ofRows_rows V X⟩ + +theorem uniform_matrix_law (ℓ : Nat) [Fintype V] [FiniteDimensional F2 V] + [Fintype (Module.Dual F2 V →ₗ[F2] (Fin ℓ → F2))] : + (BucketSampler.tapeLaw ℓ (FiniteDistribution.uniform V)).pushforward + (fun t => EvaluationMatrix.ofRows V (BucketSampler.evaluate ℓ (id : V → V) t)) = + FiniteDistribution.uniform (Module.Dual F2 V →ₗ[F2] (Fin ℓ → F2)) := by + calc + _ = ((BucketSampler.tapeLaw ℓ (FiniteDistribution.uniform V)).pushforward + (BucketSampler.evaluate ℓ (id : V → V))).pushforward + (EvaluationMatrix.ofRows V) := + (FiniteDistribution.pushforward_comp _ _ _).symm + _ = (FiniteDistribution.uniform (Fin ℓ → V)).pushforward + (EvaluationMatrix.ofRows V) := by rw [uniform_evaluate_law] + _ = _ := UniformLinearImage.uniform_pushforward_linearMap + (ofRowsLinear V ℓ) (ofRowsLinear_surjective V ℓ) + +end +end PerfectCompleteness.BucketUniform + + + +namespace PerfectCompleteness.RecursiveSamplerBiasAlgebra + +open PointwiseSpaces RecursiveSpaces RecursiveSampler +open scoped BigOperators + +universe u w + +variable (𝕜 : Type w) [Field 𝕜] + +def squareProduct {X : Type u} (H : Submodule 𝕜 (X → 𝕜)) : + H →ₗ[𝕜] H →ₗ[𝕜] squareSpace H := + LinearMap.mk₂ 𝕜 + (fun g h => ⟨g.val * h.val, mul_mem_squareSpace H g.property h.property⟩) + (fun g g' h => Subtype.ext (add_mul g.val g'.val h.val)) + (fun c g h => Subtype.ext (smul_mul_assoc c g.val h.val)) + (fun g h h' => Subtype.ext (mul_add g.val h.val h'.val)) + (fun c g h => Subtype.ext (mul_smul_comm c g.val h.val)) + +@[simp] theorem squareProduct_val {X : Type u} (H : Submodule 𝕜 (X → 𝕜)) + (g h : H) : (squareProduct 𝕜 H g h).val = g.val * h.val := rfl + +theorem square_functional_eq_zero_of_products {X : Type u} + (H : Submodule 𝕜 (X → 𝕜)) (L : squareSpace H →ₗ[𝕜] 𝕜) + (hL : ∀ g h : H, L (squareProduct 𝕜 H g h) = 0) : L = 0 := by + apply LinearMap.ext + rintro ⟨x, hx⟩ + change L ⟨x, hx⟩ = 0 + refine Submodule.span_induction + (p := fun y hy => L ⟨y, hy⟩ = 0) ?_ ?_ ?_ ?_ hx + · rintro y ⟨g, hg, h, hh, rfl⟩ + exact hL ⟨g, hg⟩ ⟨h, hh⟩ + · exact map_zero L + · intro y z hy hz hLy hLz + change L ((⟨y, hy⟩ : squareSpace H) + ⟨z, hz⟩) = 0 + rw [map_add, hLy, hLz, add_zero] + · intro c y hy hLy + change L (c • (⟨y, hy⟩ : squareSpace H)) = 0 + rw [map_smul, hLy, smul_zero] + +variable {branch : Nat → Nat} {n : Nat} + +def childSquareLift (A : Slots branch (n + 1) → Type u) (i : Fin (branch n)) : + squareSpace (space 𝕜 branch n (childFamily A i)) →ₗ[𝕜] + space 𝕜 branch (n + 1) A where + toFun g := ⟨pullback 𝕜 (childRestriction A i) g.val, + child_square_le_space A i (Submodule.mem_map_of_mem g.property)⟩ + map_add' _ _ := Subtype.ext rfl + map_smul' _ _ := Subtype.ext rfl + +@[simp] theorem childSquareLift_val (A : Slots branch (n + 1) → Type u) + (i : Fin (branch n)) (g : squareSpace (space 𝕜 branch n (childFamily A i))) : + (childSquareLift 𝕜 A i g).val = pullback 𝕜 (childRestriction A i) g.val := rfl + +def childProduct (A : Slots branch (n + 1) → Type u) (i : Fin (branch n)) : + space 𝕜 branch n (childFamily A i) →ₗ[𝕜] + space 𝕜 branch n (childFamily A i) →ₗ[𝕜] space 𝕜 branch (n + 1) A := + (squareProduct 𝕜 (space 𝕜 branch n (childFamily A i))).compr₂ + (childSquareLift 𝕜 A i) + +@[simp] theorem childProduct_val (A : Slots branch (n + 1) → Type u) + (i : Fin (branch n)) (g h : space 𝕜 branch n (childFamily A i)) : + (childProduct 𝕜 A i g h).val = + pullback 𝕜 (childRestriction A i) (g.val * h.val) := rfl + +def childBilinear (A : Slots branch (n + 1) → Type u) (i : Fin (branch n)) + (f : space 𝕜 branch (n + 1) A →ₗ[𝕜] 𝕜) : + space 𝕜 branch n (childFamily A i) →ₗ[𝕜] + space 𝕜 branch n (childFamily A i) →ₗ[𝕜] 𝕜 := + (childProduct 𝕜 A i).compr₂ f + +@[simp] theorem childBilinear_apply (A : Slots branch (n + 1) → Type u) + (i : Fin (branch n)) (f : space 𝕜 branch (n + 1) A →ₗ[𝕜] 𝕜) + (g h : space 𝕜 branch n (childFamily A i)) : + childBilinear 𝕜 A i f g h = + f (childSquareLift 𝕜 A i + (squareProduct 𝕜 (space 𝕜 branch n (childFamily A i)) g h)) := rfl + +theorem eq_zero_of_child_restrictions (A : Slots branch (n + 1) → Type u) + (f : space 𝕜 branch (n + 1) A →ₗ[𝕜] 𝕜) + (hzero : ∀ i : Fin (branch n), f.comp (childSquareLift 𝕜 A i) = 0) : f = 0 := by + apply LinearMap.ext + rintro ⟨x, hx⟩ + change f ⟨x, hx⟩ = 0 + refine Submodule.iSup_induction' + (fun i : Fin (branch n) => + (squareSpace (space 𝕜 branch n (childFamily A i))).map + (pullback 𝕜 (childRestriction A i))) + (motive := fun y hy => f ⟨y, hy⟩ = 0) ?_ ?_ ?_ hx + · intro i y hy + obtain ⟨g, hg, rfl⟩ := Submodule.mem_map.mp hy + exact LinearMap.congr_fun (hzero i) ⟨g, hg⟩ + · exact map_zero f + · intro y z hy hz hfy hfz + change f ((⟨y, hy⟩ : space 𝕜 branch (n + 1) A) + ⟨z, hz⟩) = 0 + rw [map_add, hfy, hfz, add_zero] + +theorem exists_child_restriction_ne_zero (A : Slots branch (n + 1) → Type u) + (f : space 𝕜 branch (n + 1) A →ₗ[𝕜] 𝕜) (hf : f ≠ 0) : + ∃ i : Fin (branch n), f.comp (childSquareLift 𝕜 A i) ≠ 0 := by + classical + by_contra h + apply hf + apply eq_zero_of_child_restrictions 𝕜 A f + intro i + by_contra hi + exact h ⟨i, hi⟩ + +theorem childBilinear_ne_zero (A : Slots branch (n + 1) → Type u) + (i : Fin (branch n)) (f : space 𝕜 branch (n + 1) A →ₗ[𝕜] 𝕜) + (hchild : f.comp (childSquareLift 𝕜 A i) ≠ 0) : + childBilinear 𝕜 A i f ≠ 0 := by + intro hzero + apply hchild + apply square_functional_eq_zero_of_products 𝕜 _ _ + intro g h + exact LinearMap.congr_fun₂ hzero g h + +theorem ordinary_or_bilinear_ne_zero (A : Slots branch (n + 1) → Type u) + (i : Fin (branch n)) (f : space 𝕜 branch (n + 1) A →ₗ[𝕜] 𝕜) (hf : f ≠ 0) : + (∃ j : OffPath i, f.comp (childSquareLift 𝕜 A j.val) ≠ 0) ∨ + childBilinear 𝕜 A i f ≠ 0 := by + classical + obtain ⟨j, hj⟩ := exists_child_restriction_ne_zero 𝕜 A f hf + by_cases hji : j = i + · subst j + exact Or.inr (childBilinear_ne_zero 𝕜 A i f hj) + · exact Or.inl ⟨⟨j, hji⟩, hj⟩ + +noncomputable section + +theorem combine_eq (A : Slots branch (n + 1) → Type u) (i : Fin (branch n)) + (r : Nat) + (ordinary : (j : OffPath i) → squareSpace (space 𝕜 branch n (childFamily A j.val))) + (left right : Fin r → space 𝕜 branch n (childFamily A i)) : + combine 𝕜 A i r ordinary left right = + (∑ j : OffPath i, childSquareLift 𝕜 A j.val (ordinary j)) + + ∑ h : Fin r, childProduct 𝕜 A i (left h) (right h) := by + apply Subtype.ext + change combineFunction 𝕜 A i r ordinary left right = + (space 𝕜 branch (n + 1) A).subtype + ((∑ j : OffPath i, childSquareLift 𝕜 A j.val (ordinary j)) + + ∑ h : Fin r, childProduct 𝕜 A i (left h) (right h)) + rw [map_add, map_sum, map_sum] + rfl + +theorem map_combine (A : Slots branch (n + 1) → Type u) (i : Fin (branch n)) + (r : Nat) (f : space 𝕜 branch (n + 1) A →ₗ[𝕜] 𝕜) + (ordinary : (j : OffPath i) → squareSpace (space 𝕜 branch n (childFamily A j.val))) + (left right : Fin r → space 𝕜 branch n (childFamily A i)) : + f (combine 𝕜 A i r ordinary left right) = + (∑ j : OffPath i, (f.comp (childSquareLift 𝕜 A j.val)) (ordinary j)) + + ∑ h : Fin r, childBilinear 𝕜 A i f (left h) (right h) := by + rw [combine_eq, map_add, map_sum, map_sum] + rfl + +end +end PerfectCompleteness.RecursiveSamplerBiasAlgebra + + + +namespace PerfectCompleteness.RecursiveSampler + +open PointwiseSpaces RecursiveSpaces DescendantSpaces +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators + +universe u w + +variable {branch : Nat → Nat} {n m : Nat} + +abbrev CallIndex (repeats : Nat → Nat) (n : Nat) := Fin (repeats (n + 1)) × Bool + +variable (𝕜 : Type w) [Field 𝕜] + +abbrev OrdinaryTape (repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) (A : Slots branch (n + 1) → Type u) := + (j : OffPath i) → DrawSpace 𝕜 repeats (.step i p) A (.inl j) + +abbrev CallTapes (repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) (A : Slots branch (n + 1) → Type u) := + CallIndex repeats n → Tape 𝕜 repeats p (childFamily A i) + +def splitTapeEquiv (repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) (A : Slots branch (n + 1) → Type u) : + Tape 𝕜 repeats (.step i p) A ≃ + OrdinaryTape 𝕜 repeats i p A × CallTapes 𝕜 repeats i p A where + toFun t := (fun j => t (.inl j), fun hb => subTape 𝕜 repeats i p A t hb.1 hb.2) + invFun z j := match j with + | .inl j => z.1 j + | .inr j => z.2 j.1 j.2 + left_inv t := by + funext j + cases j <;> rfl + right_inv z := by + apply Prod.ext + · funext j + rfl + · funext hb j + rfl + +noncomputable def evaluateCalls (repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) (A : Slots branch (n + 1) → Type u) + (calls : CallTapes 𝕜 repeats i p A) : + CallIndex repeats n → space 𝕜 branch n (childFamily A i) := + fun hb => evaluate 𝕜 repeats p (childFamily A i) (calls hb) + +noncomputable def splitEvaluatedTape (repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) (A : Slots branch (n + 1) → Type u) + (t : Tape 𝕜 repeats (.step i p) A) : + OrdinaryTape 𝕜 repeats i p A × + (CallIndex repeats n → space 𝕜 branch n (childFamily A i)) := + ((splitTapeEquiv 𝕜 repeats i p A t).1, + evaluateCalls 𝕜 repeats i p A (splitTapeEquiv 𝕜 repeats i p A t).2) + +noncomputable def stepCombine (repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) (A : Slots branch (n + 1) → Type u) + (z : OrdinaryTape 𝕜 repeats i p A × + (CallIndex repeats n → space 𝕜 branch n (childFamily A i))) : + space 𝕜 branch (n + 1) A := + combine 𝕜 A i (repeats (n + 1)) z.1 + (fun h => z.2 (h, false)) (fun h => z.2 (h, true)) + +theorem stepCombine_splitEvaluatedTape (repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) (A : Slots branch (n + 1) → Type u) + (t : Tape 𝕜 repeats (.step i p) A) : + stepCombine 𝕜 repeats i p A (splitEvaluatedTape 𝕜 repeats i p A t) = + evaluate 𝕜 repeats (.step i p) A t := rfl + +noncomputable section + +variable [Finite 𝕜] + +instance childFamilyFinite (A : Slots branch (n + 1) → Type u) + [hA : ∀ s, Finite (A s)] (i : Fin (branch n)) : + ∀ s, Finite (childFamily A i s) := fun s => hA (i, s) + +instance childSquareFintype (A : Slots branch (n + 1) → Type u) + [hA : ∀ s, Finite (A s)] (i : Fin (branch n)) : + Fintype (squareSpace (space 𝕜 branch n (childFamily A i))) := by + letI : ∀ s, Finite (childFamily A i s) := fun s => hA (i, s) + exact Fintype.ofFinite _ + +instance ordinaryDrawFintype (repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) (A : Slots branch (n + 1) → Type u) + [∀ s, Finite (A s)] (j : OffPath i) : + Fintype (DrawSpace 𝕜 repeats (.step i p) A (.inl j)) := + drawSpaceFintype 𝕜 repeats (.step i p) A (.inl j) + +instance ordinaryTapeFintype (repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) (A : Slots branch (n + 1) → Type u) + [∀ s, Finite (A s)] : Fintype (OrdinaryTape 𝕜 repeats i p A) := by + letI : ∀ j : OffPath i, Fintype (DrawSpace 𝕜 repeats (.step i p) A (.inl j)) := + fun j => drawSpaceFintype 𝕜 repeats (.step i p) A (.inl j) + exact Pi.instFintype + +instance callTapesFintype (repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) (A : Slots branch (n + 1) → Type u) + [hA : ∀ s, Finite (A s)] : Fintype (CallTapes 𝕜 repeats i p A) := by + letI : ∀ s, Finite (childFamily A i s) := fun s => hA (i, s) + letI : Fintype (Tape 𝕜 repeats p (childFamily A i)) := + @Pi.instFintype (DrawIndex repeats p) + (DrawSpace 𝕜 repeats p (childFamily A i)) + (drawIndexDecidableEq repeats p) (drawIndexFintype repeats p) + (fun j => drawSpaceFintype 𝕜 repeats p (childFamily A i) j) + exact Pi.instFintype + +def ordinaryLaw (𝕜 : Type w) [Field 𝕜] [Finite 𝕜] + (repeats : Nat → Nat) (i : Fin (branch n)) (p : Path branch n m) + (A : Slots branch (n + 1) → Type u) [∀ s, Finite (A s)] : + FiniteDistribution (OrdinaryTape 𝕜 repeats i p A) := by + letI : ∀ j : OffPath i, Fintype (DrawSpace 𝕜 repeats (.step i p) A (.inl j)) := + fun j => drawSpaceFintype 𝕜 repeats (.step i p) A (.inl j) + letI : ∀ j : OffPath i, Nonempty (DrawSpace 𝕜 repeats (.step i p) A (.inl j)) := + fun j => ⟨zeroDraw 𝕜 repeats (.step i p) A (.inl j)⟩ + exact FiniteProduct.law (fun j : OffPath i => + FiniteDistribution.uniform (DrawSpace 𝕜 repeats (.step i p) A (.inl j))) + +def callTapeLaw (𝕜 : Type w) [Field 𝕜] [Finite 𝕜] + (repeats : Nat → Nat) (i : Fin (branch n)) (p : Path branch n m) + (A : Slots branch (n + 1) → Type u) [hA : ∀ s, Finite (A s)] : + FiniteDistribution (CallTapes 𝕜 repeats i p A) := by + letI : ∀ s, Finite (childFamily A i s) := fun s => hA (i, s) + exact FiniteProduct.law (fun _ : CallIndex repeats n => + tapeLaw 𝕜 repeats p (childFamily A i)) + +theorem splitTape_law (repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) (A : Slots branch (n + 1) → Type u) + [∀ s, Finite (A s)] : + (tapeLaw 𝕜 repeats (.step i p) A).pushforward (splitTapeEquiv 𝕜 repeats i p A) = + (ordinaryLaw 𝕜 repeats i p A).product (callTapeLaw 𝕜 repeats i p A) := by + rw [← FiniteDistribution.transport_eq_pushforward] + apply FiniteDistribution.eq_of_weight_eq + intro z + let : ∀ j : OffPath i ⊕ (CallIndex repeats n × DrawIndex repeats p), + Fintype (DrawSpace 𝕜 repeats (.step i p) A j) := + fun j => drawSpaceFintype 𝕜 repeats (.step i p) A j + change + (∏ j : OffPath i ⊕ (CallIndex repeats n × DrawIndex repeats p), + 1 / (Fintype.card (DrawSpace 𝕜 repeats (.step i p) A j) : ℝ)) = + (∏ j : OffPath i, + 1 / (Fintype.card (DrawSpace 𝕜 repeats (.step i p) A (.inl j)) : ℝ)) * + ∏ _hb : CallIndex repeats n, ∏ j : DrawIndex repeats p, + 1 / (Fintype.card (DrawSpace 𝕜 repeats p (childFamily A i) j) : ℝ) + rw [Fintype.prod_sum_type, Fintype.prod_prod_type] + simp only [Fintype.card_eq_nat_card] + rfl + +theorem subTape_tuple_law (repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) (A : Slots branch (n + 1) → Type u) + [∀ s, Finite (A s)] : + (tapeLaw 𝕜 repeats (.step i p) A).pushforward + (fun t (hb : CallIndex repeats n) => subTape 𝕜 repeats i p A t hb.1 hb.2) = + callTapeLaw 𝕜 repeats i p A := by + calc + _ = ((tapeLaw 𝕜 repeats (.step i p) A).pushforward + (splitTapeEquiv 𝕜 repeats i p A)).pushforward Prod.snd := + (FiniteDistribution.pushforward_comp _ _ Prod.snd).symm + _ = _ := by + rw [splitTape_law, FiniteDistribution.product_pushforward_snd] + +def callScalarLaw (𝕜 : Type w) [Field 𝕜] [Finite 𝕜] + (repeats : Nat → Nat) (i : Fin (branch n)) (p : Path branch n m) + (A : Slots branch (n + 1) → Type u) [hA : ∀ s, Finite (A s)] + [Fintype (space 𝕜 branch n (childFamily A i))] : + FiniteDistribution (CallIndex repeats n → space 𝕜 branch n (childFamily A i)) := by + letI : ∀ s, Finite (childFamily A i s) := fun s => hA (i, s) + exact FiniteProduct.law (fun _ : CallIndex repeats n => + law 𝕜 repeats p (childFamily A i)) + +theorem evaluateCalls_law (repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) (A : Slots branch (n + 1) → Type u) + [∀ s, Finite (A s)] [Fintype (space 𝕜 branch n (childFamily A i))] : + (callTapeLaw 𝕜 repeats i p A).pushforward (evaluateCalls 𝕜 repeats i p A) = + callScalarLaw 𝕜 repeats i p A := + FiniteProduct.pushforward_map _ (fun _ => evaluate 𝕜 repeats p (childFamily A i)) + +theorem splitEvaluatedTape_law (repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) (A : Slots branch (n + 1) → Type u) + [∀ s, Finite (A s)] [Fintype (space 𝕜 branch n (childFamily A i))] : + (tapeLaw 𝕜 repeats (.step i p) A).pushforward + (splitEvaluatedTape 𝕜 repeats i p A) = + (ordinaryLaw 𝕜 repeats i p A).product (callScalarLaw 𝕜 repeats i p A) := by + calc + _ = ((tapeLaw 𝕜 repeats (.step i p) A).pushforward + (splitTapeEquiv 𝕜 repeats i p A)).pushforward + (fun z => (z.1, evaluateCalls 𝕜 repeats i p A z.2)) := + (FiniteDistribution.pushforward_comp _ _ _).symm + _ = ((ordinaryLaw 𝕜 repeats i p A).product + (callTapeLaw 𝕜 repeats i p A)).pushforward + (fun z => (z.1, evaluateCalls 𝕜 repeats i p A z.2)) := by + rw [splitTape_law] + _ = (ordinaryLaw 𝕜 repeats i p A).product + ((callTapeLaw 𝕜 repeats i p A).pushforward + (evaluateCalls 𝕜 repeats i p A)) := by + simpa only [id_eq, FiniteDistribution.pushforward_id] using + (FiniteDistribution.product_pushforward + (ordinaryLaw 𝕜 repeats i p A) (callTapeLaw 𝕜 repeats i p A) + (id : OrdinaryTape 𝕜 repeats i p A → OrdinaryTape 𝕜 repeats i p A) + (evaluateCalls 𝕜 repeats i p A)) + _ = _ := by rw [evaluateCalls_law] + +theorem law_step (repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) (A : Slots branch (n + 1) → Type u) + [∀ s, Finite (A s)] [Fintype (space 𝕜 branch n (childFamily A i))] + [Fintype (space 𝕜 branch (n + 1) A)] : + law 𝕜 repeats (.step i p) A = + ((ordinaryLaw 𝕜 repeats i p A).product + (callScalarLaw 𝕜 repeats i p A)).pushforward + (stepCombine 𝕜 repeats i p A) := by + calc + _ = ((tapeLaw 𝕜 repeats (.step i p) A).pushforward + (splitEvaluatedTape 𝕜 repeats i p A)).pushforward + (stepCombine 𝕜 repeats i p A) := + (FiniteDistribution.pushforward_comp _ _ _).symm + _ = _ := by rw [splitEvaluatedTape_law] + +end +end PerfectCompleteness.RecursiveSampler + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/CandidateCoupling.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/CandidateCoupling.lean new file mode 100644 index 0000000000000000000000000000000000000000..05d5c072fb268f97346291090eafff006321b32c --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/CandidateCoupling.lean @@ -0,0 +1,172 @@ +import OAI.Computability.PerfectCompleteness.Reduction.PreliminaryAveraging + +namespace OAI + + +namespace PerfectCompleteness.CandidateCoupling + +open PreliminarySampler PreliminaryAveraging TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +noncomputable section + +section Selection + +variable {I : Type*} [Fintype I] [DecidableEq I] + {D : I → Type*} [∀ i, Fintype (D i)] + +theorem selected_probability (μ : FiniteDistribution I) + (ν : ∀ i, FiniteDistribution (D i)) (event : (Σ i, D i) → Bool) : + (μ.product (FiniteProduct.law ν)).probability + (fun z => event ⟨z.1, z.2 z.1⟩) = + (CompletionSoundness.sigmaLaw μ ν).probability event := by + rw [probability_product, CompletionSoundness.sigmaLaw_probability] + apply FiniteDistribution.expectation_congr + intro i + have h := FiniteDistribution.probability_pushforward + (FiniteProduct.law ν) (fun directions => directions i) + (fun direction => event ⟨i, direction⟩) + rw [FiniteProduct.eval_pushforward] at h + exact h.symm + +theorem selected_pushforward (μ : FiniteDistribution I) + (ν : ∀ i, FiniteDistribution (D i)) : + (μ.product (FiniteProduct.law ν)).pushforward + (fun z => (⟨z.1, z.2 z.1⟩ : Σ i, D i)) = + CompletionSoundness.sigmaLaw μ ν := by + apply FiniteDistribution.eq_of_weight_eq + intro choice + rw [FiniteDistribution.weight_eq_probability_singleton, + FiniteDistribution.weight_eq_probability_singleton, + FiniteDistribution.probability_pushforward] + exact selected_probability μ ν (fun c => decide (c = choice)) + +omit [DecidableEq I] in +theorem expectation_sigmaLaw (μ : FiniteDistribution I) + (ν : ∀ i, FiniteDistribution (D i)) (f : (Σ i, D i) → ℝ) : + (CompletionSoundness.sigmaLaw μ ν).expectation f = + μ.expectation (fun i => (ν i).expectation (fun d => f ⟨i, d⟩)) := by + simp only [FiniteDistribution.expectation, CompletionSoundness.sigmaLaw, + Fintype.sum_sigma, Finset.mul_sum, mul_assoc] + +end Selection + +theorem probability_eq_expectation {X : Type*} [Fintype X] + (μ : FiniteDistribution X) (event : X → Bool) : + μ.probability event = μ.expectation (fun x => if event x then 1 else 0) := by + simp only [FiniteDistribution.probability, FiniteDistribution.expectation, + mul_ite, mul_one, mul_zero] + +theorem expectation_div {X : Type*} [Fintype X] + (μ : FiniteDistribution X) (f : X → ℝ) (c : ℝ) : + μ.expectation (fun x => f x / c) = μ.expectation f / c := by + simp only [FiniteDistribution.expectation, mul_div_assoc, Finset.sum_div] + +variable {v m n t : Nat} {branch rows repeats : Nat → Nat} + +abbrev DirectionTuple (rows : Nat → Nat) (leaf : RecursiveSpaces.Slots branch n) := + (level : Fin n) → BucketSampler.Direction + (rows (Nodes.height (GeometricPath.nodeAtLevel leaf level))) + +def directionsLaw (leaf : RecursiveSpaces.Slots branch n) + (hrows : ∀ k, 0 < rows (k + 1)) : FiniteDistribution (DirectionTuple rows leaf) := + FiniteProduct.law (fun level => directionLaw leaf level hrows) + +theorem directions_marginal (leaf : RecursiveSpaces.Slots branch n) + (hrows : ∀ k, 0 < rows (k + 1)) (level : Fin n) : + (directionsLaw leaf hrows).pushforward (fun directions => directions level) = + directionLaw leaf level hrows := + FiniteProduct.eval_pushforward _ level + +theorem directions_expectation_product (leaf : RecursiveSpaces.Slots branch n) + (hrows : ∀ k, 0 < rows (k + 1)) + (f : (level : Fin n) → BucketSampler.Direction + (rows (Nodes.height (GeometricPath.nodeAtLevel leaf level))) → ℝ) : + (directionsLaw leaf hrows).expectation (fun directions => ∏ level, f level (directions level)) = + ∏ level, (directionLaw leaf level hrows).expectation (f level) := + FiniteProduct.expectation_product _ f + +def selectedTupleLaw (leaf : RecursiveSpaces.Slots branch n) (hn : 0 < n) + (hrows : ∀ k, 0 < rows (k + 1)) : + FiniteDistribution (Fin n × DirectionTuple rows leaf) := by + letI : Nonempty (Fin n) := ⟨⟨0, hn⟩⟩ + exact (FiniteDistribution.uniform (Fin n)).product (directionsLaw leaf hrows) + +theorem selectedTupleLaw_pushforward (leaf : RecursiveSpaces.Slots branch n) + (hn : 0 < n) (hrows : ∀ k, 0 < rows (k + 1)) : + (selectedTupleLaw leaf hn hrows).pushforward + (fun z => (⟨z.1, z.2 z.1⟩ : Choice rows leaf)) = choiceLaw leaf hn hrows := by + let : Nonempty (Fin n) := ⟨⟨0, hn⟩⟩ + exact selected_pushforward (FiniteDistribution.uniform (Fin n)) + (fun level => directionLaw leaf level hrows) + +def candidateFraction (leaf : RecursiveSpaces.Slots branch n) + (event : Choice rows leaf → Bool) (directions : DirectionTuple rows leaf) : ℝ := + (∑ level : Fin n, if event ⟨level, directions level⟩ then 1 else 0) / (n : ℝ) + +theorem choice_probability_candidateFraction (leaf : RecursiveSpaces.Slots branch n) + (hn : 0 < n) (hrows : ∀ k, 0 < rows (k + 1)) + (event : Choice rows leaf → Bool) : + (choiceLaw leaf hn hrows).probability event = + (directionsLaw leaf hrows).expectation (candidateFraction leaf event) := by + rw [choice_probability] + change (∑ level : Fin n, (directionLaw leaf level hrows).probability + (fun direction => event ⟨level, direction⟩)) / (n : ℝ) = + (directionsLaw leaf hrows).expectation + (fun directions => (∑ level : Fin n, + if event ⟨level, directions level⟩ then 1 else 0) / (n : ℝ)) + rw [expectation_div, SmallBias.expectation_sum] + congr 1 + apply Finset.sum_congr rfl + intro level _ + rw [probability_eq_expectation] + exact (FiniteProduct.expectation_eval + (fun level => directionLaw leaf level hrows) level + (fun direction => if event ⟨level, direction⟩ then (1 : ℝ) else 0)).symm + +abbrev Shared (clauses : Fin m → SourceClause.NormalizedClause v) + (branch : Nat → Nat) (n t : Nat) (rows : Nat → Nat) := + (b : Base branch n t m) × + (Arrays (sourceSlots clauses (endpoints b.1)) rows × DirectionTuple rows b.2) + +def conditionalSharedLaw (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hrows : ∀ k, 0 < rows (k + 1)) + (b : Base branch n t m) : + FiniteDistribution + (Arrays (sourceSlots clauses (endpoints b.1)) rows × DirectionTuple rows b.2) := + (WholeArraySampler.law rows repeats (GeometricPath.leafPath b.2) + (sourceSlots clauses (endpoints b.1))).product (directionsLaw b.2 hrows) + +def sharedLaw [NeZero m] (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hbranch : ∀ k < n, 0 < branch k) + (hrows : ∀ k, 0 < rows (k + 1)) : + FiniteDistribution (Shared clauses branch n t rows) := + CompletionSoundness.sigmaLaw (baseLaw hbranch) + (conditionalSharedLaw clauses rows repeats hrows) + +theorem candidate_average_shared [NeZero m] + (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hn : 0 < n) + (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) + (observe : ∀ b : Base branch n t m, + Arrays (sourceSlots clauses (endpoints b.1)) rows → Choice rows b.2 → Bool) : + (PreliminarySampler.law clauses rows repeats hn hbranch hrows).probability + (fun e => observe e.1 + (WholeArraySampler.evaluate rows repeats (GeometricPath.leafPath e.1.2) + (sourceSlots clauses (endpoints e.1.1)) e.2.1) e.2.2) = + (sharedLaw clauses rows repeats hbranch hrows).expectation + (fun e => candidateFraction e.1.2 (observe e.1 e.2.1) e.2.2) := by + rw [array_observation_probability clauses rows repeats hn hbranch hrows observe, + sharedLaw, expectation_sigmaLaw] + apply FiniteDistribution.expectation_congr + intro b + rw [conditionalSharedLaw, FiniteDistribution.expectation_product] + apply FiniteDistribution.expectation_congr + intro arrays + exact choice_probability_candidateFraction b.2 hn hrows (observe b arrays) + +end +end PerfectCompleteness.CandidateCoupling + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/ChildCallNumberingLaws.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/ChildCallNumberingLaws.lean new file mode 100644 index 0000000000000000000000000000000000000000..03a607911a9909198244eaa088e7d753640ff231 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/ChildCallNumberingLaws.lean @@ -0,0 +1,164 @@ +import OAI.Computability.PerfectCompleteness.Construction.ChildCallNumbering +import OAI.Computability.PerfectCompleteness.Foundations.DependentPredictionDifferenceLemmas +import OAI.Computability.PerfectCompleteness.Foundations.MultiplicationFormInjectiveLemmas +import OAI.Computability.PerfectCompleteness.Sampling.RationalFiniteLawLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.ChildCallNumberingLaws + +noncomputable section + +open scoped BigOperators Classical +open RecursiveSpaces TreeSourceSpaces +open UniqueGamesTheorem.Foundations.Games + +variable {branch : Nat → Nat} {n t : Nat} {C : Type*} [Fintype C] + +def liftedLaw (rows : Nat → Nat) + {slots projected : Slots branch n → Fin t → MixedSupport.Slot} + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) : + FiniteDistribution (ChildCallNumbering.Raw (C := C) rows slots) := + (FiniteDistribution.uniform (ChildCallNumbering.Raw (C := C) rows projected)).pushforward + (ChildCallNumbering.pullback rows p) + +theorem liftedLaw_numbered (rows : Nat → Nat) + {slots projected : Slots branch n → Fin t → MixedSupport.Slot} + (p : ∀ s k, MixedSupport.Projection (slots s k) (projected s k)) : + (liftedLaw (C := C) rows p).pushforward (ChildCallNumbering.equiv rows slots) = + ChildBlockProjection.liftedLaw (Fintype.card C) rows p := by + unfold liftedLaw ChildBlockProjection.liftedLaw + rw [← ChildCallNumbering.uniform_equiv (C := C) rows projected] + rw [FiniteDistribution.pushforward_comp, FiniteDistribution.pushforward_comp] + congr 1 + +def mixtureLaw {Z : Type*} [Fintype Z] (rows : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (projected : Z → Slots branch n → Fin t → MixedSupport.Slot) + (p : ∀ z s k, MixedSupport.Projection (slots s k) (projected z s k)) + (choiceLaw : FiniteDistribution Z) : + FiniteDistribution (ChildCallNumbering.Raw (C := C) rows slots) := + choiceLaw.mixture (fun z => liftedLaw rows (p z)) + +theorem mixtureLaw_numbered {Z : Type*} [Fintype Z] (rows : Nat → Nat) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (projected : Z → Slots branch n → Fin t → MixedSupport.Slot) + (p : ∀ z s k, MixedSupport.Projection (slots s k) (projected z s k)) + (choiceLaw : FiniteDistribution Z) : + (mixtureLaw (C := C) rows slots projected p choiceLaw).pushforward + (ChildCallNumbering.equiv rows slots) = + ChildBlockProjection.mixtureLaw (Fintype.card C) rows slots projected p choiceLaw := by + simp only [mixtureLaw, FiniteDistribution.pushforward_mixture, + liftedLaw_numbered, ChildBlockProjection.mixtureLaw] + +variable {I : Type*} [Fintype I] [DecidableEq I] + {Z : I → Type*} [∀ i, Fintype (Z i)] + +def replacementLaws (rows : Nat → Nat) + (slots : I → Slots branch n → Fin t → MixedSupport.Slot) + (projected : (i : I) → Z i → Slots branch n → Fin t → MixedSupport.Slot) + (p : ∀ i z s k, MixedSupport.Projection (slots i s k) (projected i z s k)) + (choiceLaw : (i : I) → FiniteDistribution (Z i)) : + (i : I) → FiniteDistribution (ChildCallNumbering.Raw (C := C) rows (slots i)) := + fun i => mixtureLaw rows (slots i) (projected i) (p i) (choiceLaw i) + +def number (rows : Nat → Nat) + (slots : I → Slots branch n → Fin t → MixedSupport.Slot) + (x : (i : I) → ChildCallNumbering.Raw (C := C) rows (slots i)) : + (i : I) → ChildBlockCardinality.Raw (Fintype.card C) rows (slots i) := + fun i => ChildCallNumbering.equiv rows (slots i) (x i) + +def unnumber (rows : Nat → Nat) + (slots : I → Slots branch n → Fin t → MixedSupport.Slot) + (x : (i : I) → ChildBlockCardinality.Raw (Fintype.card C) rows (slots i)) : + (i : I) → ChildCallNumbering.Raw (C := C) rows (slots i) := + fun i => (ChildCallNumbering.equiv rows (slots i)).symm (x i) + +omit [Fintype I] [DecidableEq I] in +@[simp] theorem unnumber_number (rows : Nat → Nat) + (slots : I → Slots branch n → Fin t → MixedSupport.Slot) + (x : (i : I) → ChildCallNumbering.Raw (C := C) rows (slots i)) : + unnumber rows slots (number rows slots x) = x := by + funext i + exact (ChildCallNumbering.equiv rows (slots i)).symm_apply_apply (x i) + +omit [Fintype I] [DecidableEq I] in +@[simp] theorem number_unnumber (rows : Nat → Nat) + (slots : I → Slots branch n → Fin t → MixedSupport.Slot) + (x : (i : I) → ChildBlockCardinality.Raw (Fintype.card C) rows (slots i)) : + number rows slots (unnumber (C := C) rows slots x) = x := by + funext i + exact (ChildCallNumbering.equiv rows (slots i)).apply_symm_apply (x i) + +theorem uniform_product_numbered (rows : Nat → Nat) + (slots : I → Slots branch n → Fin t → MixedSupport.Slot) : + (FiniteProduct.law (fun i => FiniteDistribution.uniform + (ChildCallNumbering.Raw (C := C) rows (slots i)))).pushforward (number rows slots) = + FiniteProduct.law (fun i => FiniteDistribution.uniform + (ChildBlockCardinality.Raw (Fintype.card C) rows (slots i))) := by + unfold number + rw [FiniteProduct.pushforward_map] + congr 1 + funext i + exact ChildCallNumbering.uniform_equiv rows (slots i) + +theorem conditional_product_numbered (rows : Nat → Nat) + (slots : I → Slots branch n → Fin t → MixedSupport.Slot) + (projected : (i : I) → Z i → Slots branch n → Fin t → MixedSupport.Slot) + (p : ∀ i z s k, MixedSupport.Projection (slots i s k) (projected i z s k)) + (choiceLaw : (i : I) → FiniteDistribution (Z i)) (mask : I → Bool) : + (FiniteProduct.law (fun i => if mask i then + replacementLaws (C := C) rows slots projected p choiceLaw i else + FiniteDistribution.uniform (ChildCallNumbering.Raw (C := C) rows (slots i)))).pushforward + (number rows slots) = + FiniteProduct.law (fun i => if mask i then + ChildBlockProjection.replacementLaws (Fintype.card C) rows slots projected p choiceLaw i else + FiniteDistribution.uniform (ChildBlockCardinality.Raw (Fintype.card C) rows (slots i))) := by + unfold number + rw [FiniteProduct.pushforward_map] + congr 1 + funext i + cases mask i with + | false => + simp only [Bool.false_eq_true, ite_false] + exact ChildCallNumbering.uniform_equiv rows (slots i) + | true => + simp only [ite_true] + exact mixtureLaw_numbered rows (slots i) (projected i) (p i) (choiceLaw i) + +theorem markedLaw_numbered (rows : Nat → Nat) + (slots : I → Slots branch n → Fin t → MixedSupport.Slot) + (projected : (i : I) → Z i → Slots branch n → Fin t → MixedSupport.Slot) + (p : ∀ i z s k, MixedSupport.Projection (slots i s k) (projected i z s k)) + (choiceLaw : (i : I) → FiniteDistribution (Z i)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) : + (SparseReplacement.markedLaw + (fun i => FiniteDistribution.uniform (ChildCallNumbering.Raw (C := C) rows (slots i))) + (replacementLaws rows slots projected p choiceLaw) β hβ hβ').pushforward + (fun z => (z.1, number rows slots z.2)) = + SparseReplacement.markedLaw + (fun i => FiniteDistribution.uniform + (ChildBlockCardinality.Raw (Fintype.card C) rows (slots i))) + (ChildBlockProjection.replacementLaws (Fintype.card C) rows slots projected p choiceLaw) + β hβ hβ' := by + apply SigmaObservation.eq_of_probability_eq + intro event + rw [FiniteDistribution.probability_pushforward] + unfold SparseReplacement.markedLaw + rw [CleanConditioning.probability_kernelJoint, CleanConditioning.probability_kernelJoint] + apply Finset.sum_congr rfl + intro mask _ + apply congrArg (fun x : ℝ => + (FiniteProduct.law (fun _ : I => ProjectionPosterior.bernoulli β hβ hβ')).weight mask * x) + have h := congrArg (fun μ => μ.probability (fun x => event (mask, x))) + (conditional_product_numbered (C := C) rows slots projected p choiceLaw mask) + simpa only [FiniteDistribution.probability_pushforward] using h + +end +end PerfectCompleteness.ChildCallNumberingLaws + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/CommonProductVariationLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/CommonProductVariationLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..ea71fc96c5d8cf1f6d8145c44c5bf682f1cca56f --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/CommonProductVariationLemmas.lean @@ -0,0 +1,162 @@ +import Mathlib.Algebra.BigOperators.Expect +import Mathlib.Basic.Real.Basic +import OAI.Computability.PerfectCompleteness.Foundations.DummyEliminationLemmas +import OAI.Computability.PerfectCompleteness.Reduction.CompletionSoundness +import OAI.Computability.PerfectCompleteness.Sampling.DensityVariation + +namespace OAI + + +namespace PerfectCompleteness.CommonProductVariation + +open scoped BigOperators +open UniqueGamesTheorem.Foundations.Games + +noncomputable section + +variable {S A Γ : Type*} [Fintype S] [Fintype A] [Fintype Γ] + +theorem product_totalVariation (μ : FiniteDistribution S) + (P Q : FiniteDistribution A) : + (μ.product P).totalVariation (μ.product Q) = P.totalVariation Q := by + change (∑ z : S × A, + |μ.weight z.1 * P.weight z.2 - μ.weight z.1 * Q.weight z.2|) / 2 = + (∑ a : A, |P.weight a - Q.weight a|) / 2 + rw [Fintype.sum_prod_type] + simp_rw [← mul_sub, abs_mul, abs_of_nonneg (μ.nonnegative _), ← Finset.mul_sum] + rw [← Finset.sum_mul, μ.normalized, one_mul] + +theorem observed_product_le (μ : FiniteDistribution S) + (P Q : FiniteDistribution A) (observe : S × A → Γ) : + ((μ.product P).pushforward observe).totalVariation + ((μ.product Q).pushforward observe) ≤ P.totalVariation Q := + (DensityVariation.variation_pushforward_le _ _ observe).trans_eq + (product_totalVariation μ P Q) + +theorem observed_product_le_of_bound (μ : FiniteDistribution S) + (P Q : FiniteDistribution A) (observe : S × A → Γ) + {error : ℝ} (herror : P.totalVariation Q ≤ error) : + ((μ.product P).pushforward observe).totalVariation + ((μ.product Q).pushforward observe) ≤ error := + (observed_product_le μ P Q observe).trans herror + +end +end PerfectCompleteness.CommonProductVariation + + +namespace PerfectCompleteness.ConditionalVariation + +open scoped BigOperators +open UniqueGamesTheorem.Foundations.Games +open CompletionSoundness + +noncomputable section + +variable {S : Type*} [Fintype S] {Ω : S → Type*} [∀ s, Fintype (Ω s)] + +theorem sigma_totalVariation (μ : FiniteDistribution S) + (P Q : (s : S) → FiniteDistribution (Ω s)) : + (sigmaLaw μ P).totalVariation (sigmaLaw μ Q) = + μ.expectation (fun s => (P s).totalVariation (Q s)) := by + change (∑ z : Σ s, Ω s, + |μ.weight z.1 * (P z.1).weight z.2 - μ.weight z.1 * (Q z.1).weight z.2|) / 2 = + ∑ s, μ.weight s * ((∑ x : Ω s, |(P s).weight x - (Q s).weight x|) / 2) + rw [Fintype.sum_sigma, div_eq_mul_inv, Finset.sum_mul] + apply Finset.sum_congr rfl + intro s _ + simp_rw [← mul_sub, abs_mul, abs_of_nonneg (μ.nonnegative s)] + rw [← Finset.mul_sum] + simp only [div_eq_mul_inv, mul_assoc] + +theorem observed_sigma_le {Γ : Type*} [Fintype Γ] + (μ : FiniteDistribution S) (P Q : (s : S) → FiniteDistribution (Ω s)) + (observe : (Σ s, Ω s) → Γ) : + ((sigmaLaw μ P).pushforward observe).totalVariation + ((sigmaLaw μ Q).pushforward observe) ≤ + μ.expectation (fun s => (P s).totalVariation (Q s)) := by + rw [← sigma_totalVariation μ P Q] + exact DensityVariation.variation_pushforward_le _ _ observe + +theorem observed_sigma_le_of_bound {Γ : Type*} [Fintype Γ] + (μ : FiniteDistribution S) (P Q : (s : S) → FiniteDistribution (Ω s)) + (error : S → ℝ) (bound : ∀ s, (P s).totalVariation (Q s) ≤ error s) + (observe : (Σ s, Ω s) → Γ) : + ((sigmaLaw μ P).pushforward observe).totalVariation + ((sigmaLaw μ Q).pushforward observe) ≤ μ.expectation error := + (observed_sigma_le μ P Q observe).trans (SmallBias.expectation_mono μ bound) + +theorem observed_sigma_le_const {Γ : Type*} [Fintype Γ] + (μ : FiniteDistribution S) (P Q : (s : S) → FiniteDistribution (Ω s)) + (error : ℝ) (bound : ∀ s, (P s).totalVariation (Q s) ≤ error) + (observe : (Σ s, Ω s) → Γ) : + ((sigmaLaw μ P).pushforward observe).totalVariation + ((sigmaLaw μ Q).pushforward observe) ≤ error := by + simpa only [SmallBias.expectation_const] using + observed_sigma_le_of_bound μ P Q (fun _ => error) bound observe + +end +end PerfectCompleteness.ConditionalVariation + + +namespace PerfectCompleteness.DummyElimination.Slice + +noncomputable section + +open scoped BigOperators Classical + +variable {𝕜 H D K R C : Type*} [Field 𝕜] + [AddCommGroup H] [Module 𝕜 H] [AddCommGroup D] [Module 𝕜 D] + [AddCommGroup K] [Module 𝕜 K] [AddCommGroup R] [Module 𝕜 R] + [AddCommGroup C] [Module 𝕜 C] + (S : DummyElimination.Slice 𝕜 H D K R C) + +abbrev Lifted := {p : (H →ₗ[𝕜] K) × (D →ₗ[𝕜] K) // S.IsLift p.1 p.2} +abbrev ProjectedMatrices := {X : H →ₗ[𝕜] K // S.Projected X} +abbrev HomogeneousMaps := {Z : D →ₗ[𝕜] K // S.Homogeneous Z} + +def chosenLift (hne : ∃ X Y, S.IsLift X Y) (X : S.ProjectedMatrices) : + {Y : D →ₗ[𝕜] K // S.IsLift X.val Y} := + ⟨Classical.choose ((S.exists_lift_iff hne X.val).mpr X.property), + Classical.choose_spec ((S.exists_lift_iff hne X.val).mpr X.property)⟩ + +def liftedEquivProduct (hne : ∃ X Y, S.IsLift X Y) : + S.Lifted ≃ S.ProjectedMatrices × S.HomogeneousMaps where + toFun p := + let X : S.ProjectedMatrices := ⟨p.val.1, IsLift.projected S p.property⟩ + (X, S.fiberEquivHomogeneous (S.chosenLift hne X).property ⟨p.val.2, p.property⟩) + invFun p := + let Y := (S.fiberEquivHomogeneous (S.chosenLift hne p.1).property).symm p.2 + ⟨(p.1.val, Y.val), Y.property⟩ + left_inv p := by + apply Subtype.ext + apply Prod.ext + · rfl + · exact congrArg Subtype.val + ((S.fiberEquivHomogeneous + (S.chosenLift hne ⟨p.val.1, IsLift.projected S p.property⟩).property).symm_apply_apply + ⟨p.val.2, p.property⟩) + right_inv p := by + apply Prod.ext + · rfl + · exact (S.fiberEquivHomogeneous (S.chosenLift hne p.1).property).apply_symm_apply p.2 + +@[simp] theorem liftedEquivProduct_fst (hne : ∃ X Y, S.IsLift X Y) (p : S.Lifted) : + (S.liftedEquivProduct hne p).1.val = p.val.1 := rfl + +theorem expect_projected [Fintype (H →ₗ[𝕜] K)] [Fintype (D →ₗ[𝕜] K)] + (hne : ∃ X Y, S.IsLift X Y) (g : (H →ₗ[𝕜] K) → ℝ) : + (𝔼 p : S.Lifted, g p.val.1) = (𝔼 X : S.ProjectedMatrices, g X.val) := by + let : Nonempty S.HomogeneousMaps := ⟨⟨0, by simp [Homogeneous]⟩⟩ + calc + _ = 𝔼 p : S.ProjectedMatrices × S.HomogeneousMaps, g p.1.val := + Fintype.expect_equiv (S.liftedEquivProduct hne) _ _ (fun _ => rfl) + _ = 𝔼 X : S.ProjectedMatrices, 𝔼 _Z : S.HomogeneousMaps, g X.val := by + simpa only [Finset.univ_product_univ] using + (Finset.expect_product (Finset.univ : Finset S.ProjectedMatrices) + (Finset.univ : Finset S.HomogeneousMaps) (fun p => g p.1.val)) + _ = _ := by simp only [Fintype.expect_const] + +end +end PerfectCompleteness.DummyElimination.Slice + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/CompletedSignedLaw.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/CompletedSignedLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..bb83a48d771d11087d7cfd262ef4e27eb0f06efe --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/CompletedSignedLaw.lean @@ -0,0 +1,197 @@ +import OAI.Computability.PerfectCompleteness.Reduction.FinitePreliminaryCompletion +import OAI.Computability.PerfectCompleteness.Reduction.SignedCompletionSchedule +import OAI.Computability.PerfectCompleteness.Sampling.MetadataFreeLaw + +namespace OAI + +section + +namespace PerfectCompleteness.CompletedSignedLaw + +open MetadataFreeSampler MetadataFreeLaw +open UniqueGamesTheorem.Foundations.Games +open CompletionSoundness CompletionSoundness.LegalProjectionGame +open scoped BigOperators Classical + +noncomputable section + +variable {branch : Nat → Nat} {n t v m : Nat} + (clauses : Fin m → SourceClause.NormalizedClause v) (rows repeats : Nat → Nat) + +local notation "locationCount" => TreeCanonical.locationCount branch n t +local notation "hq" δ => CanonicalLocalCompletion.alphabet_positive locationCount δ +local notation "large" δ => CanonicalLocalCompletion.partitionWidth_le_alphabet locationCount δ + +local notation "F" => FinitePreliminaryCompletion.blockFamily clauses branch n t rows repeats + +local instance leftVertex_fintype : Fintype (CanonicalGame.LeftVertex F) := Fintype.ofFinite _ + +local instance rightVertex_fintype : Fintype (CanonicalGame.RightVertex F) := Fintype.ofFinite _ + +local instance leftLabel_fintype (x : CanonicalGame.LeftVertex F) : + Fintype (CanonicalGame.LeftLabel F x) := Fintype.ofFinite _ + +local instance rightLabel_fintype (y : CanonicalGame.RightVertex F) : + Fintype (CanonicalGame.RightLabel F y) := Fintype.ofFinite _ + +abbrev SignedCompleted (δ : ℚ) := + Σ source : PreliminarySampler.Questions branch n t m, + SignedCompletionSchedule.Completed (rows := rows) (repeats := repeats) + (hq δ) (large δ) (sourceSigns clauses source) + +variable [NeZero m] (hn : 0 < n) (hbranch : ∀ k < n, 0 < branch k) + (hrows : ∀ k, 0 < rows (k + 1)) (δ : ℚ) + +abbrev Completed := + Σ raw : PreliminarySampler.Raw clauses branch n t rows repeats, + Fin ((FinitePreliminaryCompletion.actualFamily (t := t) + clauses rows repeats hn hbranch hrows δ).size raw) + +theorem size_eq_active (e : PreliminarySampler.Raw clauses branch n t rows repeats) : + (FinitePreliminaryCompletion.actualFamily (t := t) + clauses rows repeats hn hbranch hrows δ).size e = + SignedCompletionSchedule.active (hq δ) (large δ) + (sourceSigns clauses e.1.1) (encodeOutcome clauses rows repeats e) := rfl + +def completedEquiv : + Completed (t := t) clauses rows repeats hn hbranch hrows δ ≃ + SignedCompleted (branch := branch) (n := n) (t := t) clauses rows repeats δ := + (Equiv.sigmaCongrLeft + (β := fun y : (Σ source : PreliminarySampler.Questions branch n t m, + SignedOutcome (sourceSigns clauses source) rows repeats) => + Fin (SignedCompletionSchedule.active (hq δ) (large δ) + (sourceSigns clauses y.1) y.2)) + (rawEquiv clauses rows repeats)).trans + (Equiv.sigmaAssoc (fun source outcome => + Fin (SignedCompletionSchedule.active (hq δ) (large δ) + (sourceSigns clauses source) outcome))) + +@[simp] theorem completedEquiv_apply + (e : PreliminarySampler.Raw clauses branch n t rows repeats) + (seed : Fin ((FinitePreliminaryCompletion.actualFamily (t := t) + clauses rows repeats hn hbranch hrows δ).size e)) : + completedEquiv (t := t) clauses rows repeats hn hbranch hrows δ ⟨e, seed⟩ = + ⟨e.1.1, encodeOutcome clauses rows repeats e, seed⟩ := rfl + +@[simp] theorem completedEquiv_source + (e : Completed (t := t) clauses rows repeats hn hbranch hrows δ) : + (completedEquiv (t := t) clauses rows repeats hn hbranch hrows δ e).1 = e.1.1.1 := rfl + +theorem completedEquiv_symm_source + (e : SignedCompleted (branch := branch) (n := n) (t := t) clauses rows repeats δ) : + ((completedEquiv (t := t) clauses rows repeats hn hbranch hrows δ).symm e).1.1.1 = e.1 := by + have h := congrArg Sigma.fst + ((completedEquiv (t := t) clauses rows repeats hn hbranch hrows δ).apply_symm_apply e) + exact h + +theorem descriptorTable_eq_map + (e : Completed (t := t) clauses rows repeats hn hbranch hrows δ) + (a : Fin (2 * FinitePreliminaryCompletion.alphabet branch n t δ)) : + SignedCompletionSchedule.descriptorTable (hq δ) (large δ) + ⟨sourceSigns clauses (completedEquiv (t := t) clauses rows repeats hn hbranch hrows δ e).1, + (completedEquiv (t := t) clauses rows repeats hn hbranch hrows δ e).2⟩ a = + (FinitePreliminaryCompletion.actualFamily (t := t) + clauses rows repeats hn hbranch hrows δ).map e.1 e.2 a := rfl + +def law : FiniteDistribution + (SignedCompleted (branch := branch) (n := n) (t := t) clauses rows repeats δ) := + sigmaLaw PreliminarySampler.questionsLaw (fun source => + SignedCompletionSchedule.law (rows := rows) (repeats := repeats) + (hq δ) (large δ) hn hbranch hrows (sourceSigns clauses source)) + +theorem completed_weight (e : Completed (t := t) clauses rows repeats hn hbranch hrows δ) : + (FinitePreliminaryCompletion.actualFamily (t := t) + clauses rows repeats hn hbranch hrows δ).game.occurrences.weight e = + (law (t := t) clauses rows repeats hn hbranch hrows δ).weight + (completedEquiv (t := t) clauses rows repeats hn hbranch hrows δ e) := by + rcases e with ⟨raw, seed⟩ + change (PreliminarySampler.law (t := t) clauses rows repeats hn hbranch hrows).weight raw * + (1 / (Fintype.card (Fin ((FinitePreliminaryCompletion.actualFamily (t := t) + clauses rows repeats hn hbranch hrows δ).size raw)) : ℝ)) = + (1 / (Fintype.card (PreliminarySampler.Questions branch n t m) : ℝ)) * + (SignedCompletionSchedule.law (rows := rows) (repeats := repeats) + (hq δ) (large δ) hn hbranch hrows + (sourceSigns clauses raw.1.1)).weight + ⟨encodeOutcome clauses rows repeats raw, seed⟩ + rw [Fintype.card_fin, raw_weight_eq, SignedCompletionSchedule.law_weight] + rw [size_eq_active (t := t) clauses rows repeats hn hbranch hrows δ raw] + simp only [div_eq_mul_inv, one_mul, mul_assoc] + +theorem actualcompletedLaw_transport : + (FinitePreliminaryCompletion.actualFamily (t := t) + clauses rows repeats hn hbranch hrows δ).game.occurrences.transport + (completedEquiv (t := t) clauses rows repeats hn hbranch hrows δ) = + sigmaLaw PreliminarySampler.questionsLaw (fun source => + SignedCompletionSchedule.law (rows := rows) (repeats := repeats) + (hq δ) (large δ) hn hbranch hrows + (sourceSigns clauses source)) := by + apply FiniteDistribution.eq_of_weight_eq + intro e + change (FinitePreliminaryCompletion.actualFamily (t := t) + clauses rows repeats hn hbranch hrows δ).game.occurrences.weight + ((completedEquiv (t := t) clauses rows repeats hn hbranch hrows δ).symm e) = + (law (t := t) clauses rows repeats hn hbranch hrows δ).weight e + simpa only [Equiv.apply_symm_apply] using + completed_weight (t := t) clauses rows repeats hn hbranch hrows δ + ((completedEquiv (t := t) clauses rows repeats hn hbranch hrows δ).symm e) + +theorem probability_reindex + (event : SignedCompleted (branch := branch) (n := n) (t := t) clauses rows repeats δ → Bool) : + (FinitePreliminaryCompletion.actualFamily (t := t) + clauses rows repeats hn hbranch hrows δ).game.occurrences.probability + (fun e => event (completedEquiv (t := t) clauses rows repeats hn hbranch hrows δ e)) = + (law (t := t) clauses rows repeats hn hbranch hrows δ).probability event := by + rw [← FiniteDistribution.probability_transport] + rw [actualcompletedLaw_transport] + rfl + +theorem probability_eq + (event : Completed (t := t) clauses rows repeats hn hbranch hrows δ → Bool) : + (FinitePreliminaryCompletion.actualFamily (t := t) + clauses rows repeats hn hbranch hrows δ).game.occurrences.probability event = + (law (t := t) clauses rows repeats hn hbranch hrows δ).probability + (fun e => event ((completedEquiv (t := t) clauses rows repeats hn hbranch hrows δ).symm e)) := by + simpa only [Equiv.symm_apply_apply] using + probability_reindex (t := t) clauses rows repeats hn hbranch hrows δ + (fun e => event ((completedEquiv (t := t) clauses rows repeats hn hbranch hrows δ).symm e)) + +theorem probability_iterated + (event : Completed (t := t) clauses rows repeats hn hbranch hrows δ → Bool) : + (FinitePreliminaryCompletion.actualFamily (t := t) + clauses rows repeats hn hbranch hrows δ).game.occurrences.probability event = + PreliminarySampler.questionsLaw.expectation (fun source => + (SignedCompletionSchedule.law (rows := rows) (repeats := repeats) + (hq δ) (large δ) hn hbranch hrows + (sourceSigns clauses source)).probability (fun outcome => + event ((completedEquiv (t := t) clauses rows repeats hn hbranch hrows δ).symm + ⟨source, outcome⟩))) := by + rw [probability_eq] + exact sigmaLaw_probability _ _ _ + +theorem probability_schedule + (event : Completed (t := t) clauses rows repeats hn hbranch hrows δ → Bool) : + (FinitePreliminaryCompletion.actualFamily (t := t) + clauses rows repeats hn hbranch hrows δ).game.occurrences.probability event = + PreliminarySampler.questionsLaw.expectation (fun source => + (((SignedCompletionSchedule.schedule (rows := rows) (repeats := repeats) + (hq δ) (large δ) hn hbranch hrows + (sourceSigns clauses source)).filter (fun outcome => + event ((completedEquiv (t := t) clauses rows repeats hn hbranch hrows δ).symm + ⟨source, outcome⟩))).length : ℝ) / + (SignedCompletionSchedule.schedule (rows := rows) (repeats := repeats) + (hq δ) (large δ) hn hbranch hrows + (sourceSigns clauses source)).length) := by + rw [probability_iterated] + congr 1 + funext source + exact (SignedCompletionSchedule.schedule_acceptance (hq δ) (large δ) hn hbranch hrows + (sourceSigns clauses source) (fun outcome => + event ((completedEquiv (t := t) clauses rows repeats hn hbranch hrows δ).symm + ⟨source, outcome⟩))).symm + +end +end PerfectCompleteness.CompletedSignedLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/CompletionProbability.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/CompletionProbability.lean new file mode 100644 index 0000000000000000000000000000000000000000..b617c447058e1b7daa65f6ceca6708f58c74862e --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/CompletionProbability.lean @@ -0,0 +1,213 @@ +import Mathlib.Algebra.Group.Fin.Basic +import Mathlib.Basic.Real.Basic +import Mathlib.SetTheory.Cardinal.Finite +import OAI.Computability.PerfectCompleteness.Reduction.CompletionLemmas + +namespace OAI + +section + +noncomputable section + +open scoped Classical + +namespace PerfectCompleteness.CompletionProbability + +variable {L A B : Type*} + +abbrev Illegal (legal : L ↪ A) := {a : A // a ∉ Set.range legal} + +def uniformProbability {Ω : Type*} [Fintype Ω] (event : Ω → Prop) : ℝ := + (Fintype.card {ω : Ω // event ω} : ℝ) / Fintype.card Ω + +theorem card_illegal [Fintype L] [Fintype A] (legal : L ↪ A) : + Fintype.card (Illegal legal) = Fintype.card A - Fintype.card L := by + rw [Fintype.card_subtype_compl, Fintype.card_range legal] + +def rotate {n : ℕ} [NeZero n] (legal : L ↪ A) + (enum : Illegal legal ≃ Fin n) (seed : Fin n) : Equiv.Perm (Illegal legal) where + toFun a := enum.symm (seed + enum a) + invFun a := enum.symm (-seed + enum a) + left_inv a := by simp [← add_assoc] + right_inv a := by simp [← add_assoc] + +def rotateAll {n : ℕ} [NeZero n] (legal : L ↪ A) + (enum : Illegal legal ≃ Fin n) (seed : Fin n) : Equiv.Perm A := + (Equiv.refl {a : A // a ∈ Set.range legal}).subtypeCongr (rotate legal enum seed) + +def sample {n : ℕ} [NeZero n] (legal : L ↪ A) (pHat : A → B) + (enum : Illegal legal ≃ Fin n) (seed : Fin n) (a : A) : B := + pHat (rotateAll legal enum seed a) + +@[simp] theorem sample_legal {n : ℕ} [NeZero n] (legal : L ↪ A) + (pHat : A → B) (enum : Illegal legal ≃ Fin n) (seed : Fin n) (l : L) : + sample legal pHat enum seed (legal l) = pHat (legal l) := by + have hl : legal l ∈ Set.range legal := ⟨l, rfl⟩ + exact congrArg pHat (Equiv.Perm.subtypeCongr.left_apply + (Equiv.refl {a : A // a ∈ Set.range legal}) (rotate legal enum seed) hl) + +theorem sample_exact_two [Fintype A] {n : ℕ} [NeZero n] + (legal : L ↪ A) (pHat : A → B) (enum : Illegal legal ≃ Fin n) + (hexact : ∀ b, Fintype.card {a : A // pHat a = b} = 2) (seed : Fin n) (b : B) : + Fintype.card {a : A // sample legal pHat enum seed a = b} = 2 := by + exact (Fintype.card_congr ((rotateAll legal enum seed).subtypeEquivOfSubtype + (p := fun a : A => pHat a = b))).trans (hexact b) + +def seedEquiv {n : ℕ} [NeZero n] (legal : L ↪ A) + (enum : Illegal legal ≃ Fin n) (a : Illegal legal) : Fin n ≃ Illegal legal where + toFun seed := enum.symm (seed + enum a) + invFun j := enum j - enum a + left_inv seed := by simp + right_inv j := by simp + +@[simp] theorem sample_illegal {n : ℕ} [NeZero n] (legal : L ↪ A) + (pHat : A → B) (enum : Illegal legal ≃ Fin n) (seed : Fin n) (a : Illegal legal) : + sample legal pHat enum seed a.val = pHat ((seedEquiv legal enum a) seed).val := by + exact congrArg pHat (Equiv.Perm.subtypeCongr.right_apply + (Equiv.refl {a : A // a ∈ Set.range legal}) (rotate legal enum seed) a.property) + +theorem sample_event_card [Fintype A] {n : ℕ} [NeZero n] + (legal : L ↪ A) (pHat : A → B) (enum : Illegal legal ≃ Fin n) + (a : Illegal legal) (b : B) : + Fintype.card {seed : Fin n // sample legal pHat enum seed a.val = b} = + Fintype.card {j : Illegal legal // pHat j.val = b} := by + exact Fintype.card_congr ((seedEquiv legal enum a).subtypeEquiv + (fun seed => by simp)) + +theorem sample_probability [Fintype A] {n : ℕ} [NeZero n] + (legal : L ↪ A) (pHat : A → B) (enum : Illegal legal ≃ Fin n) + (a : Illegal legal) (b : B) : + uniformProbability (fun seed : Fin n => sample legal pHat enum seed a.val = b) = + (Fintype.card {j : Illegal legal // pHat j.val = b} : ℝ) / n := by + rw [uniformProbability, sample_event_card, Fintype.card_fin] + +theorem residual_fiber_le_two [Fintype A] (legal : L ↪ A) (pHat : A → B) + (hexact : ∀ b, Fintype.card {a : A // pHat a = b} = 2) (b : B) : + Fintype.card {j : Illegal legal // pHat j.val = b} ≤ 2 := by + let incl : {j : Illegal legal // pHat j.val = b} ↪ {a : A // pHat a = b} := + ⟨fun j => ⟨j.val.val, j.property⟩, by + intro j k h + apply Subtype.ext + apply Subtype.ext + exact congrArg (fun z : {a : A // pHat a = b} => z.val) h⟩ + exact (Fintype.card_le_of_embedding incl).trans (le_of_eq (hexact b)) + +theorem residual_fiber_card [Fintype L] [Fintype A] + (legal : L ↪ A) (p : L → B) (pHat : A → B) + (hext : ∀ l, pHat (legal l) = p l) + (hexact : ∀ b, Fintype.card {a : A // pHat a = b} = 2) (b : B) : + Fintype.card {a : Illegal legal // pHat a.val = b} = + 2 - Fintype.card {l : L // p l = b} := by + let F := {a : A // pHat a = b} + let P : F → Prop := fun a => a.val ∈ Set.range legal + let eLegal : {l : L // p l = b} ≃ {a : F // P a} := by + refine Equiv.ofBijective + (fun l : {l : L // p l = b} => + (⟨⟨legal l.val, (hext l.val).trans l.property⟩, + ⟨l.val, rfl⟩⟩ : {a : F // P a})) ⟨?_, ?_⟩ + · intro x y h + apply Subtype.ext + apply legal.injective + exact congrArg (fun a : {a : F // P a} => a.val.val) h + · intro a + obtain ⟨l, hl⟩ := (a.property : a.val.val ∈ Set.range legal) + have hpl : p l = b := + (hext l).symm.trans ((congrArg pHat hl).trans a.val.property) + refine ⟨⟨l, hpl⟩, ?_⟩ + apply Subtype.ext + apply Subtype.ext + exact hl + let eResidual : {a : Illegal legal // pHat a.val = b} ≃ {a : F // ¬P a} := { + toFun := fun a => ⟨⟨a.val.val, a.property⟩, a.val.property⟩ + invFun := fun a => ⟨⟨a.val.val, a.property⟩, a.val.property⟩ + left_inv := fun a => by + apply Subtype.ext + apply Subtype.ext + rfl + right_inv := fun a => by + apply Subtype.ext + apply Subtype.ext + rfl + } + have hF : Fintype.card F = 2 := hexact b + calc + _ = Fintype.card {a : F // ¬P a} := Fintype.card_congr eResidual + _ = Fintype.card F - Fintype.card {a : F // P a} := + Fintype.card_subtype_compl P + _ = 2 - Fintype.card {l : L // p l = b} := by + rw [hF, ← Fintype.card_congr eLegal] + +theorem sample_probability_residual [Fintype L] [Fintype A] {n : ℕ} [NeZero n] + (legal : L ↪ A) (p : L → B) (pHat : A → B) (enum : Illegal legal ≃ Fin n) + (hext : ∀ l, pHat (legal l) = p l) + (hexact : ∀ b, Fintype.card {a : A // pHat a = b} = 2) + (a : Illegal legal) (b : B) : + uniformProbability (fun seed : Fin n => sample legal pHat enum seed a.val = b) = + ((2 - Fintype.card {l : L // p l = b} : ℕ) : ℝ) / + (Fintype.card A - Fintype.card L : ℕ) := by + rw [sample_probability] + have hn : n = Fintype.card A - Fintype.card L := by + rw [← card_illegal legal] + simpa only [Fintype.card_fin] using (Fintype.card_congr enum).symm + rw [← hn] + simpa only [← Nat.card_eq_fintype_card] using + congrArg (fun k : ℕ => (k : ℝ) / (n : ℝ)) + (residual_fiber_card legal p pHat hext hexact b) + +theorem sample_probability_le [Fintype L] [Fintype A] {n : ℕ} [NeZero n] + (legal : L ↪ A) (pHat : A → B) (enum : Illegal legal ≃ Fin n) + (hexact : ∀ b, Fintype.card {a : A // pHat a = b} = 2) + (a : Illegal legal) (b : B) : + uniformProbability (fun seed : Fin n => sample legal pHat enum seed a.val = b) ≤ + 2 / (Fintype.card A - Fintype.card L : ℕ) := by + have hn : n = Fintype.card A - Fintype.card L := by + rw [← card_illegal legal] + simpa only [Fintype.card_fin] using (Fintype.card_congr enum).symm + rw [sample_probability, hn] + apply div_le_div_of_nonneg_right + · exact Nat.cast_le.mpr (residual_fiber_le_two legal pHat hexact b) + · exact Nat.cast_nonneg _ + +theorem exists_completion_sampler [Fintype L] [Fintype A] [Fintype B] + (legal : L ↪ A) (p : L → B) + (hsmall : ∀ b, Fintype.card {l : L // p l = b} ≤ 2) + (hcard : Fintype.card A = 2 * Fintype.card B) : + ∃ n : ℕ, 0 < n ∧ ∃ sampler : Fin n → A → B, + (∀ seed l, sampler seed (legal l) = p l) ∧ + (∀ seed b, Fintype.card {a : A // sampler seed a = b} = 2) ∧ + ∀ (a : Illegal legal) (b : B), + uniformProbability (fun seed => sampler seed a.val = b) = + ((2 - Fintype.card {l : L // p l = b} : ℕ) : ℝ) / + (Fintype.card A - Fintype.card L : ℕ) ∧ + uniformProbability (fun seed => sampler seed a.val = b) ≤ + 2 / (Fintype.card A - Fintype.card L : ℕ) := by + obtain ⟨pHat, hext, hexact⟩ := + Completion.exists_exact_two_completion legal p hsmall hcard + by_cases hz : Fintype.card (Illegal legal) = 0 + · refine ⟨1, Nat.zero_lt_one, (fun _ => pHat), ?_, ?_, ?_⟩ + · intro seed l + exact hext l + · intro seed b + exact hexact b + · intro a b + have hp : 0 < Fintype.card (Illegal legal) := Fintype.card_pos_iff.mpr ⟨a⟩ + exact False.elim (Nat.ne_of_gt hp hz) + · let : NeZero (Fintype.card (Illegal legal)) := ⟨hz⟩ + let enum := Fintype.equivFin (Illegal legal) + refine ⟨Fintype.card (Illegal legal), Nat.pos_of_ne_zero hz, + sample legal pHat enum, ?_, ?_, ?_⟩ + · intro seed l + simpa only [sample_legal] using hext l + · intro seed b + exact sample_exact_two legal pHat enum hexact seed b + · intro a b + exact ⟨sample_probability_residual legal p pHat enum hext hexact a b, + sample_probability_le legal pHat enum hexact a b⟩ + +end PerfectCompleteness.CompletionProbability + +end + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/CutCallOriginalLaw.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/CutCallOriginalLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..5bebcb9ac32174b1c1aabb0155eaf300a85c5b47 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/CutCallOriginalLaw.lean @@ -0,0 +1,89 @@ +import OAI.Computability.PerfectCompleteness.Decoding.LowerCutPairLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.CutCallOriginalLaw + +open RecursiveSpaces TreeSourceSpaces HierarchicalArrays WholeCutGrouping +open UniqueGamesTheorem.Foundations.Games +open scoped Classical + +noncomputable section + +section Original + +variable {branch : Nat → Nat} {n t : Nat} {C : Type*} [Fintype C] + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (rows : Nat → Nat) + +def originalLinear : CutCallExtension.Extended (C := C) slots rows →ₗ[ZMod 2] + CutChildGrouping.Raw (C := C) slots rows where + toFun := CutCallExtension.original slots rows + map_add' _ _ := rfl + map_smul' _ _ := rfl + +omit [Fintype C] in +theorem originalLinear_surjective : Function.Surjective + (originalLinear (C := C) slots rows) := by + intro old + refine ⟨fun i => (fun c => match c with + | none => 0 + | some c => (old i).1 c, (old i).2), ?_⟩ + rfl + +theorem original_law : + (CutChildGrouping.rawLaw (C := Option C) slots rows).pushforward + (CutCallExtension.original slots rows) = + CutChildGrouping.rawLaw (C := C) slots rows := by + unfold CutChildGrouping.rawLaw + rw [UniformLinearImage.law_uniform, UniformLinearImage.law_uniform] + exact UniformLinearImage.uniform_pushforward_linearMap + (originalLinear slots rows) (originalLinear_surjective slots rows) + +theorem original_probability (event : CutChildGrouping.Raw (C := C) slots rows → Bool) : + (CutChildGrouping.rawLaw (C := Option C) slots rows).probability + (fun raw => event (CutCallExtension.original slots rows raw)) = + (CutChildGrouping.rawLaw (C := C) slots rows).probability event := by + rw [← FiniteDistribution.probability_pushforward, original_law] + +end Original + +section First + +variable {branch : Nat → Nat} {n m t : Nat} + (rows repeats : Nat → Nat) (p : DescendantSpaces.Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + +theorem first_law (exterior : Exterior rows repeats p slots) : + (CutChildGrouping.rawLaw (C := Option (LowerCutPair.Calls rows repeats p)) + (cutSlots p slots) rows).pushforward + (LowerCutPair.first rows repeats p slots exterior) = + (CutChildGrouping.rawLaw (C := LowerCutPair.Calls rows repeats p) + (cutSlots p slots) rows).pushforward + (LowerCutRows.reconstruct rows repeats p slots exterior) := by + change (CutChildGrouping.rawLaw + (C := Option (LowerCutPair.Calls rows repeats p)) (cutSlots p slots) rows).pushforward + (fun raw => LowerCutRows.reconstruct rows repeats p slots exterior + (CutCallExtension.original (cutSlots p slots) rows raw)) = _ + rw [← FiniteDistribution.pushforward_comp, original_law] + +theorem first_probability (exterior : Exterior rows repeats p slots) + (event : Arrays slots rows → Bool) : + (CutChildGrouping.rawLaw (C := Option (LowerCutPair.Calls rows repeats p)) + (cutSlots p slots) rows).probability + (fun raw => event (LowerCutPair.first rows repeats p slots exterior raw)) = + (CutChildGrouping.rawLaw (C := LowerCutPair.Calls rows repeats p) + (cutSlots p slots) rows).probability + (fun raw => event (LowerCutRows.reconstruct rows repeats p slots exterior raw)) := by + exact original_probability (cutSlots p slots) rows + (fun raw => event (LowerCutRows.reconstruct rows repeats p slots exterior raw)) + +end First +end +end PerfectCompleteness.CutCallOriginalLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/CutSamplerKeyLocalityLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/CutSamplerKeyLocalityLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..ca20e595796a12b1b318f7a00881d65bb7ad97a0 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/CutSamplerKeyLocalityLemmas.lean @@ -0,0 +1,437 @@ +import OAI.Computability.PerfectCompleteness.Construction.TreeCanonical +import OAI.Computability.PerfectCompleteness.Foundations.CutTerminalZero +import OAI.Computability.PerfectCompleteness.Repetition.CleanCountingLemmas +import OAI.Computability.PerfectCompleteness.Sampling.CutSamplerLocality + +namespace OAI + + +namespace PerfectCompleteness.CutSamplerKeyLocality + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces +open CutSamplerLocality + +abbrev F2 := ZMod 2 + +noncomputable section + +universe u + +variable {branch : Nat → Nat} {n m t : Nat} + +def keptLeaf : {n m : Nat} → Path branch n (m + 1) → + (Fin (branch m) → Prop) → Slots branch n → Prop + | _, _, .refl _, clean, s => ¬ clean s.1 + | _, _, .step i p, clean, s => s.1 ≠ i ∨ keptLeaf p clean s.2 + +theorem view_eq_of_keptLeaf (p : Path branch n (m + 1)) : + ∀ (A : Slots branch n → Type u) (clean : Fin (branch m) → Prop) + (x y : Assignment A), + (∀ s, keptLeaf p clean s → x s = y s) → view p A clean x = view p A clean y := by + induction n generalizing m with + | zero => + have h := p.height_le + omega + | succ n ih => + cases p with + | refl => + intro A clean x y hagree + funext i s + exact hagree (i.val, s) i.property + | step i p => + intro A clean x y hagree + apply Prod.ext + · funext j s + exact hagree (j.val, s) (Or.inl j.property) + · apply ih p (childFamily A i) clean + (childRestriction A i x) (childRestriction A i y) + intro s hs + exact hagree (i, s) (Or.inr hs) + +theorem keptLeaf_at_cut (p : Path branch n (m + 1)) + (clean : Fin (branch m) → Prop) (i : Fin (branch m)) (s : Slots branch m) : + keptLeaf p clean (p.slotEmbedding (i, s)) ↔ ¬ clean i := by + induction n generalizing m with + | zero => + have h := p.height_le + omega + | succ n ih => + cases p with + | refl => rfl + | step j p => + change (j ≠ j ∨ keptLeaf p clean (p.slotEmbedding (i, s))) ↔ ¬ clean i + simpa only [ne_self_iff_false, false_or] using ih p clean i s + +def numberedKeep (p : Path branch n (m + 1)) (clean : Fin (branch m) → Prop) : + Fin (TreeCanonical.locationCount branch n t) → Prop := + fun j => keptLeaf p clean ((TreeCanonical.numbering branch n t).symm j).1 + +theorem not_numberedKeep_clean (p : Path branch n (m + 1)) + (clean : Fin (branch m) → Prop) (i : Fin (branch m)) (hi : clean i) + (s : Slots branch m) (k : Fin t) : + ¬ numberedKeep p clean + (TreeCanonical.numbering branch n t (p.slotEmbedding (i, s), k)) := by + intro h + have hkeep : keptLeaf p clean (p.slotEmbedding (i, s)) := by + simpa only [numberedKeep, Equiv.symm_apply_apply] using h + exact (keptLeaf_at_cut p clean i s).mp hkeep hi + +theorem view_eq_of_numbered_retained (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) (clean : Fin (branch m) → Prop) + (x y : Domain slots) + (hret : CleanKeyErasure.retain (TreeCanonical.numberedSlots slots) (numberedKeep p clean) + (TreeCanonical.assignmentEquiv slots x) = + CleanKeyErasure.retain (TreeCanonical.numberedSlots slots) (numberedKeep p clean) + (TreeCanonical.assignmentEquiv slots y)) : + view p (LeafDomain slots) clean x = view p (LeafDomain slots) clean y := by + apply view_eq_of_keptLeaf p (LeafDomain slots) clean x y + intro s hs + funext k + let j := TreeCanonical.numbering branch n t (s, k) + have hj : numberedKeep p clean j := by + simpa only [numberedKeep, j, Equiv.symm_apply_apply] using hs + have hvalue := congrFun hret ⟨j, hj⟩ + exact Eq.mp (congrArg (fun sk : TreeCanonical.Location branch n t => + x sk.1 sk.2 = y sk.1 sk.2) + ((TreeCanonical.numbering branch n t).symm_apply_apply (s, k))) hvalue + +theorem view_eq_of_retained (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) (clean : Fin (branch m) → Prop) + (x y : MixedSupport.Assignment (TreeCanonical.numberedSlots slots)) + (hret : CleanKeyErasure.retain (TreeCanonical.numberedSlots slots) (numberedKeep p clean) x = + CleanKeyErasure.retain (TreeCanonical.numberedSlots slots) (numberedKeep p clean) y) : + view p (LeafDomain slots) clean ((TreeCanonical.assignmentEquiv slots).symm x) = + view p (LeafDomain slots) clean ((TreeCanonical.assignmentEquiv slots).symm y) := by + apply view_eq_of_numbered_retained p slots clean + simpa only [Equiv.apply_symm_apply] using hret + + +variable {J : Type*} + (repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) (clean : Fin (branch m) → Prop) + (tapes : J → CutSamplerRefinement.Tape F2 repeats p (LeafDomain slots)) + +def rowQuery : Domain slots → J → F2 := + fun x j => (CutSamplerRefinement.evaluate F2 repeats p (LeafDomain slots) (tapes j)).val x + +def numberedRows : MixedSupport.Assignment (TreeCanonical.numberedSlots slots) → J → F2 := + TreeCanonical.numberedFunction slots (rowQuery repeats p slots tapes) + +def allRowsZero : Prop := + ∀ j, ZeroAtClean F2 repeats p (LeafDomain slots) clean (tapes j) + +theorem numberedRows_constant (hzero : allRowsZero repeats p slots clean tapes) + (x y : MixedSupport.Assignment (TreeCanonical.numberedSlots slots)) + (hret : CleanKeyErasure.retain (TreeCanonical.numberedSlots slots) (numberedKeep p clean) x = + CleanKeyErasure.retain (TreeCanonical.numberedSlots slots) (numberedKeep p clean) y) : + numberedRows repeats p slots tapes x = numberedRows repeats p slots tapes y := by + funext j + exact evaluate_eq_of_view_eq F2 repeats p (LeafDomain slots) clean (tapes j) (hzero j) + _ _ (view_eq_of_retained p slots clean x y hret) + +def retainedRows : CleanKeyErasure.Retained (TreeCanonical.numberedSlots slots) + (numberedKeep p clean) → J → F2 := + numberedRows repeats p slots tapes ∘ + CleanKeyFactorization.fill (TreeCanonical.numberedSlots slots) (numberedKeep p clean) + +theorem retainedRows_eq_of_extension (hzero : allRowsZero repeats p slots clean tapes) + (x : CleanKeyErasure.Retained (TreeCanonical.numberedSlots slots) (numberedKeep p clean)) + (y : MixedSupport.Assignment (TreeCanonical.numberedSlots slots)) + (hy : CleanKeyErasure.retain (TreeCanonical.numberedSlots slots) (numberedKeep p clean) y = x) : + retainedRows repeats p slots clean tapes x = numberedRows repeats p slots tapes y := by + apply numberedRows_constant repeats p slots clean tapes hzero + exact (CleanKeyFactorization.retain_fill (TreeCanonical.numberedSlots slots) + (numberedKeep p clean) x).trans hy.symm + +theorem numberedRows_factor (hzero : allRowsZero repeats p slots clean tapes) : + numberedRows repeats p slots tapes = retainedRows repeats p slots clean tapes ∘ + CleanKeyErasure.retain (TreeCanonical.numberedSlots slots) (numberedKeep p clean) := by + funext x + exact (retainedRows_eq_of_extension repeats p slots clean tapes hzero _ x rfl).symm + +theorem clean_position_dropped (hzero : allRowsZero repeats p slots clean tapes) + (i : Fin (branch m)) (hi : clean i) (s : Slots branch m) (k : Fin t) : + MixedSupport.keyFields (TreeCanonical.numberedSlots slots) (numberedRows repeats p slots tapes) + (TreeCanonical.numbering branch n t (p.slotEmbedding (i, s), k)) = .dropped := + CleanKeyErasure.keyFields_dropped_of_retained (TreeCanonical.numberedSlots slots) + (numberedKeep p clean) (numberedRows repeats p slots tapes) + (numberedRows_constant repeats p slots clean tapes hzero) _ + (not_numberedKeep_clean p clean i hi s k) + +theorem key_eq_retained (hzero : allRowsZero repeats p slots clean tapes) + (side : CanonicalKeys.Side) : + CanonicalKeys.key side (TreeCanonical.numberedSlots slots) (numberedRows repeats p slots tapes) = + CleanKeyFactorization.retainedKey side (numberedKeep p clean) + (CleanKeyFactorization.retainedSlots (TreeCanonical.numberedSlots slots) (numberedKeep p clean)) + (retainedRows repeats p slots clean tapes) := by + rw [numberedRows_factor repeats p slots clean tapes hzero] + exact CleanKeyFactorization.key_factor side (TreeCanonical.numberedSlots slots) + (numberedKeep p clean) (retainedRows repeats p slots clean tapes) + +theorem label_eq_retained (hzero : allRowsZero repeats p slots clean tapes) + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (side : CanonicalKeys.Side) : + (KeyStrategy.label labeling side (TreeCanonical.numberedSlots slots) + (numberedRows repeats p slots tapes)).val = + (labeling (CleanKeyFactorization.retainedQueryKey side (numberedKeep p clean) + (CleanKeyFactorization.retainedSlots (TreeCanonical.numberedSlots slots) (numberedKeep p clean)) + (retainedRows repeats p slots clean tapes))).val := by + rw [numberedRows_factor repeats p slots clean tapes hzero] + exact CleanKeyFactorization.label_factor labeling side (TreeCanonical.numberedSlots slots) + (numberedKeep p clean) (retainedRows repeats p slots clean tapes) + +theorem response_eq_retained (hzero : allRowsZero repeats p slots clean tapes) + (labeling : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + (side : CanonicalKeys.Side) : + KeyStrategy.response labeling side (TreeCanonical.numberedSlots slots) + (numberedRows repeats p slots tapes) = + CleanKeyFactorization.retainedResponse labeling side (numberedKeep p clean) + (CleanKeyFactorization.retainedSlots (TreeCanonical.numberedSlots slots) (numberedKeep p clean)) + (retainedRows repeats p slots clean tapes) := by + rw [numberedRows_factor repeats p slots clean tapes hzero] + exact CleanKeyFactorization.response_factor labeling side (TreeCanonical.numberedSlots slots) + (numberedKeep p clean) (retainedRows repeats p slots clean tapes) + + +end +end PerfectCompleteness.CutSamplerKeyLocality + + + +namespace PerfectCompleteness.CutSamplerReplay + +open scoped BigOperators Classical +open RecursiveSpaces DescendantSpaces RecursiveSampler PointwiseSpaces + +noncomputable section + +universe u w + +variable {branch : Nat → Nat} {n m : Nat} + +def Tape (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n (m + 1)) → (A : Slots branch n → Type u) → + (clean : Fin (branch m) → Prop) → Type (max u w) + | _, m, .refl _, A, clean => + (i : {i : Fin (branch m) // ¬ clean i}) → + squareSpace (space 𝕜 branch m (childFamily A i.val)) + | n + 1, _, .step i p, A, clean => + ((j : OffPath i) → squareSpace (space 𝕜 branch n (childFamily A j.val))) × + ((call : Fin (repeats (n + 1)) × Bool) → Tape 𝕜 repeats p (childFamily A i) clean) + +def erase (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n (m + 1)) → (A : Slots branch n → Type u) → + (clean : Fin (branch m) → Prop) → CutSamplerRefinement.Tape 𝕜 repeats p A → + Tape 𝕜 repeats p A clean + | _, _, .refl _, _, _, tape => fun i => tape () i.val + | _, _, .step i p, A, clean, tape => + (fun j => tape (.inl j), fun call => erase 𝕜 repeats p (childFamily A i) clean + (CutSamplerLocality.subTape 𝕜 repeats i p A tape call.1 call.2)) + +def evaluate (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n (m + 1)) → (A : Slots branch n → Type u) → + (clean : Fin (branch m) → Prop) → Tape 𝕜 repeats p A clean → Assignment A → 𝕜 + | _, m, .refl _, A, clean, tape, x => + ∑ i : {i : Fin (branch m) // ¬ clean i}, (tape i).val (childRestriction A i.val x) + | n + 1, _, .step i p, A, clean, tape, x => + (∑ j : OffPath i, (tape.1 j).val (childRestriction A j.val x)) + + ∑ h : Fin (repeats (n + 1)), + evaluate 𝕜 repeats p (childFamily A i) clean (tape.2 (h, false)) (childRestriction A i x) * + evaluate 𝕜 repeats p (childFamily A i) clean (tape.2 (h, true)) (childRestriction A i x) + +theorem evaluate_refl (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) + (A : Slots branch (m + 1) → Type u) (clean : Fin (branch m) → Prop) + (tape : Tape 𝕜 repeats (.refl (m + 1)) A clean) (x : Assignment A) : + evaluate 𝕜 repeats (.refl (m + 1)) A clean tape x = + ∑ i : {i : Fin (branch m) // ¬ clean i}, (tape i).val (childRestriction A i.val x) := rfl + +theorem evaluate_step (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) + (i : Fin (branch n)) (p : Path branch n (m + 1)) + (A : Slots branch (n + 1) → Type u) (clean : Fin (branch m) → Prop) + (tape : Tape 𝕜 repeats (.step i p) A clean) (x : Assignment A) : + evaluate 𝕜 repeats (.step i p) A clean tape x = + (∑ j : OffPath i, (tape.1 j).val (childRestriction A j.val x)) + + ∑ h : Fin (repeats (n + 1)), + evaluate 𝕜 repeats p (childFamily A i) clean (tape.2 (h, false)) (childRestriction A i x) * + evaluate 𝕜 repeats p (childFamily A i) clean (tape.2 (h, true)) + (childRestriction A i x) := rfl + +theorem evaluate_erase (𝕜 : Type w) [Field 𝕜] + (repeats : Nat → Nat) (p : Path branch n (m + 1)) : + ∀ (A : Slots branch n → Type u) (clean : Fin (branch m) → Prop) + (tape : CutSamplerRefinement.Tape 𝕜 repeats p A), + CutSamplerLocality.ZeroAtClean 𝕜 repeats p A clean tape → + ∀ x : Assignment A, + evaluate 𝕜 repeats p A clean (erase 𝕜 repeats p A clean tape) x = + (CutSamplerRefinement.evaluate 𝕜 repeats p A tape).val x := by + induction n generalizing m with + | zero => + have h := p.height_le + omega + | succ n ih => + cases p with + | refl => + intro A clean tape hzero x + have heval : + (UniformChildSum.recursiveSum (𝕜 := 𝕜) A (tape ())).val x = + ∑ i : Fin (branch n), (tape () i).val (childRestriction A i x) := by + have hsum := congrFun + (UniformChildSum.childSum_apply (𝕜 := 𝕜) (childRestriction A) + (fun i => space 𝕜 branch n (childFamily A i)) (tape ())) x + simp only [Finset.sum_apply, PointwiseSpaces.pullback_apply] at hsum + refine hsum.trans ?_ + refine Finset.sum_congr (ι := Fin (branch n)) ?_ ?_ + · ext i + simp only [Finset.mem_univ] + · intro i _ + rfl + rw [evaluate_refl, CutSamplerLocality.evaluate_refl, heval] + simp only [erase] + rw [← Fintype.sum_subtype_add_sum_subtype clean + (fun i => (tape () i).val (childRestriction A i x))] + have hz : (∑ i : {i : Fin (branch n) // clean i}, + (tape () i.val).val (childRestriction A i.val x)) = 0 := by + apply Finset.sum_eq_zero + intro i _ + rw [hzero i.val i.property] + rfl + rw [hz, zero_add] + | step i p => + intro A clean tape hzero x + rw [evaluate_step, CutSamplerLocality.evaluate_step] + simp only [erase, RecursiveSampler.combine, RecursiveSampler.combineFunction, + Finset.sum_apply, Pi.add_apply, Pi.mul_apply, PointwiseSpaces.pullback_apply] + apply congrArg (fun z => + (∑ j : OffPath i, (tape (.inl j)).val (childRestriction A j.val x)) + z) + apply Finset.sum_congr rfl + intro h _ + rw [ih p (childFamily A i) clean + (CutSamplerLocality.subTape 𝕜 repeats i p A tape h false) (hzero h false), + ih p (childFamily A i) clean + (CutSamplerLocality.subTape 𝕜 repeats i p A tape h true) (hzero h true)] + +theorem evaluate_erase_of_split_zero (𝕜 : Type w) [Field 𝕜] + (repeats : Nat → Nat) (p : Path branch n (m + 1)) + (A : Slots branch n → Type u) (clean : Fin (branch m) → Prop) + (tape : CutSamplerRefinement.Tape 𝕜 repeats p A) + (hzero : ∀ terminal i, clean i → + (CutTerminalSplit.splitTape 𝕜 repeats p A tape).1 terminal i = 0) + (x : Assignment A) : + evaluate 𝕜 repeats p A clean (erase 𝕜 repeats p A clean tape) x = + (CutSamplerRefinement.evaluate 𝕜 repeats p A tape).val x := + evaluate_erase 𝕜 repeats p A clean tape + ((CutTerminalZero.zeroAtClean_iff 𝕜 repeats p A clean tape).mp hzero) x + +end +end PerfectCompleteness.CutSamplerReplay + + + +namespace PerfectCompleteness.CutSamplerReplayGrouping + +open RecursiveSpaces DescendantSpaces RecursiveSampler TerminalCalls PointwiseSpaces + +noncomputable section + +universe u w + +variable {branch : Nat → Nat} {n m : Nat} + +abbrev RetainedTerminal (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) + (p : Path branch n (m + 1)) (A : Slots branch n → Type u) + (clean : Fin (branch m) → Prop) := + TerminalIndex repeats p → (i : {i : Fin (branch m) // ¬ clean i}) → + squareSpace (space 𝕜 branch m (childFamily (p.family A) i.val)) + +def exteriorStepIndex (repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n (m + 1)) (call : Fin (repeats (n + 1)) × Bool) + (j : CutTerminalSplit.ExteriorIndex repeats p) : + CutTerminalSplit.ExteriorIndex repeats (.step i p) := + ⟨.inr (call, j.val), j.property⟩ + +def subExterior (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) + (i : Fin (branch n)) (p : Path branch n (m + 1)) + (A : Slots branch (n + 1) → Type u) (call : Fin (repeats (n + 1)) × Bool) + (exterior : CutTerminalSplit.ExteriorTape 𝕜 repeats (.step i p) A) : + CutTerminalSplit.ExteriorTape 𝕜 repeats p (childFamily A i) := + fun j => exterior (exteriorStepIndex repeats i p call j) + +theorem subExterior_splitTape (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) + (i : Fin (branch n)) (p : Path branch n (m + 1)) + (A : Slots branch (n + 1) → Type u) + (tape : CutSamplerRefinement.Tape 𝕜 repeats (.step i p) A) + (h : Fin (repeats (n + 1))) (b : Bool) : + subExterior 𝕜 repeats i p A (h, b) + (CutTerminalSplit.splitTape 𝕜 repeats (.step i p) A tape).2 = + (CutTerminalSplit.splitTape 𝕜 repeats p (childFamily A i) + (CutSamplerLocality.subTape 𝕜 repeats i p A tape h b)).2 := by + funext j + rfl + +def assemble (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n (m + 1)) → (A : Slots branch n → Type u) → + (clean : Fin (branch m) → Prop) → + CutTerminalSplit.ExteriorTape 𝕜 repeats p A → + RetainedTerminal 𝕜 repeats p A clean → CutSamplerReplay.Tape 𝕜 repeats p A clean + | _, _, .refl _, _, _, _, terminal => terminal () + | _, _, .step i p, A, clean, exterior, terminal => + (fun j => exterior ⟨.inl j, not_isTerminal_ordinary repeats i p j⟩, + fun call => assemble 𝕜 repeats p (childFamily A i) clean + (subExterior 𝕜 repeats i p A call exterior) + (fun location child => terminal (call, location) child)) + +theorem assemble_splitTape (𝕜 : Type w) [Field 𝕜] + (repeats : Nat → Nat) (p : Path branch n (m + 1)) : + ∀ (A : Slots branch n → Type u) (clean : Fin (branch m) → Prop) + (tape : CutSamplerRefinement.Tape 𝕜 repeats p A), + assemble 𝕜 repeats p A clean (CutTerminalSplit.splitTape 𝕜 repeats p A tape).2 + (fun terminal child => + (CutTerminalSplit.splitTape 𝕜 repeats p A tape).1 terminal child.val) = + CutSamplerReplay.erase 𝕜 repeats p A clean tape := by + induction n generalizing m with + | zero => + have h := p.height_le + omega + | succ n ih => + cases p with + | refl => + intro A clean tape + rfl + | step i p => + intro A clean tape + apply Prod.ext + · funext j + rfl + · funext call + rcases call with ⟨h, b⟩ + change assemble 𝕜 repeats p (childFamily A i) clean + (subExterior 𝕜 repeats i p A (h, b) + (CutTerminalSplit.splitTape 𝕜 repeats (.step i p) A tape).2) + (fun terminal child => + (CutTerminalSplit.splitTape 𝕜 repeats (.step i p) A tape).1 + ((h, b), terminal) child.val) = + CutSamplerReplay.erase 𝕜 repeats p (childFamily A i) clean + (CutSamplerLocality.subTape 𝕜 repeats i p A tape h b) + rw [subExterior_splitTape] + simp_rw [CutTerminalZero.splitTape_terminal_step] + exact ih p (childFamily A i) clean + (CutSamplerLocality.subTape 𝕜 repeats i p A tape h b) + +theorem evaluate_assemble_splitTape (𝕜 : Type w) [Field 𝕜] + (repeats : Nat → Nat) (p : Path branch n (m + 1)) + (A : Slots branch n → Type u) (clean : Fin (branch m) → Prop) + (tape : CutSamplerRefinement.Tape 𝕜 repeats p A) + (hzero : CutSamplerLocality.ZeroAtClean 𝕜 repeats p A clean tape) (x : Assignment A) : + CutSamplerReplay.evaluate 𝕜 repeats p A clean + (assemble 𝕜 repeats p A clean (CutTerminalSplit.splitTape 𝕜 repeats p A tape).2 + (fun terminal child => + (CutTerminalSplit.splitTape 𝕜 repeats p A tape).1 terminal child.val)) x = + (CutSamplerRefinement.evaluate 𝕜 repeats p A tape).val x := by + rw [assemble_splitTape] + exact CutSamplerReplay.evaluate_erase 𝕜 repeats p A clean tape hzero x + +end +end PerfectCompleteness.CutSamplerReplayGrouping + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/CutSamplerLocality.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/CutSamplerLocality.lean new file mode 100644 index 0000000000000000000000000000000000000000..99f749fe078758cd9754c8e067bc979f8953d08c --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/CutSamplerLocality.lean @@ -0,0 +1,150 @@ +import OAI.Computability.PerfectCompleteness.Construction.FactoredFunctionsLemmas +import OAI.Computability.PerfectCompleteness.Sampling.CutSamplerRefinement + +namespace OAI + +section + +namespace PerfectCompleteness.CutSamplerLocality + +open scoped BigOperators Classical +open RecursiveSpaces DescendantSpaces RecursiveSampler PointwiseSpaces +open CutSamplerRefinement + +noncomputable section + +universe u w + +variable {branch : Nat → Nat} {n m : Nat} + +def View : {n m : Nat} → (p : Path branch n (m + 1)) → + (A : Slots branch n → Type u) → (clean : Fin (branch m) → Prop) → Type u + | _, m, .refl _, A, clean => + (i : {i : Fin (branch m) // ¬ clean i}) → Assignment (childFamily A i.val) + | _, _, .step i p, A, clean => + ((j : OffPath i) → Assignment (childFamily A j.val)) × + View p (childFamily A i) clean + +def view : {n m : Nat} → (p : Path branch n (m + 1)) → + (A : Slots branch n → Type u) → (clean : Fin (branch m) → Prop) → + Assignment A → View p A clean + | _, _, .refl _, A, _, x => fun i => childRestriction A i.val x + | _, _, .step i p, A, clean, x => + (fun j => childRestriction A j.val x, + view p (childFamily A i) clean (childRestriction A i x)) + +def subTape (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) + (i : Fin (branch n)) (p : Path branch n m) + (A : Slots branch (n + 1) → Type u) + (tape : CutSamplerRefinement.Tape 𝕜 repeats (.step i p) A) + (h : Fin (repeats (n + 1))) (b : Bool) : + CutSamplerRefinement.Tape 𝕜 repeats p (childFamily A i) := + fun j => tape (Sum.inr ((h, b), j)) + +def ZeroAtClean (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n (m + 1)) → (A : Slots branch n → Type u) → + (clean : Fin (branch m) → Prop) → CutSamplerRefinement.Tape 𝕜 repeats p A → Prop + | _, _, .refl _, _, clean, tape => ∀ i, clean i → tape () i = 0 + | _ + 1, _, .step i p, A, clean, tape => + ∀ h b, ZeroAtClean 𝕜 repeats p (childFamily A i) clean + (subTape 𝕜 repeats i p A tape h b) + +theorem evaluate_refl (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) + (A : Slots branch (m + 1) → Type u) + (tape : CutSamplerRefinement.Tape 𝕜 repeats (.refl (m + 1)) A) : + CutSamplerRefinement.evaluate 𝕜 repeats (.refl (m + 1)) A tape = + UniformChildSum.recursiveSum A (tape ()) := rfl + +theorem evaluate_step (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) + (i : Fin (branch n)) (p : Path branch n m) + (A : Slots branch (n + 1) → Type u) + (tape : CutSamplerRefinement.Tape 𝕜 repeats (.step i p) A) : + CutSamplerRefinement.evaluate 𝕜 repeats (.step i p) A tape = + RecursiveSampler.combine 𝕜 A i (repeats (n + 1)) + (fun j => tape (Sum.inl j)) + (fun h => CutSamplerRefinement.evaluate 𝕜 repeats p (childFamily A i) + (subTape 𝕜 repeats i p A tape h false)) + (fun h => CutSamplerRefinement.evaluate 𝕜 repeats p (childFamily A i) + (subTape 𝕜 repeats i p A tape h true)) := rfl + +theorem evaluate_eq_of_view_eq (𝕜 : Type w) [Field 𝕜] + (repeats : Nat → Nat) (p : Path branch n (m + 1)) : + ∀ (A : Slots branch n → Type u) (clean : Fin (branch m) → Prop) + (tape : CutSamplerRefinement.Tape 𝕜 repeats p A), + ZeroAtClean 𝕜 repeats p A clean tape → + ∀ x y : Assignment A, view p A clean x = view p A clean y → + (CutSamplerRefinement.evaluate 𝕜 repeats p A tape).val x = + (CutSamplerRefinement.evaluate 𝕜 repeats p A tape).val y := by + induction n generalizing m with + | zero => + have h := p.height_le + omega + | succ n ih => + cases p with + | refl => + intro A clean tape hzero x y hview + have heval (z : Assignment A) : + (UniformChildSum.recursiveSum (𝕜 := 𝕜) A (tape ())).val z = + ∑ i : Fin (branch n), (tape () i).val (childRestriction A i z) := by + have hsum := congrFun + (UniformChildSum.childSum_apply (𝕜 := 𝕜) (childRestriction A) + (fun i => space 𝕜 branch n (childFamily A i)) (tape ())) z + simp only [Finset.sum_apply, PointwiseSpaces.pullback_apply] at hsum + refine hsum.trans ?_ + refine Finset.sum_congr (ι := Fin (branch n)) ?_ ?_ + · ext i + simp only [Finset.mem_univ] + · intro i _ + rfl + rw [evaluate_refl, heval x, heval y] + apply Finset.sum_congr rfl + intro i _ + by_cases hi : clean i + · rw [hzero i hi] + rfl + · exact congrArg (tape () i).val (congrFun hview ⟨i, hi⟩) + | step i p => + intro A clean tape hzero x y hview + have hout : ∀ j : OffPath i, childRestriction A j.val x = childRestriction A j.val y := + congrFun (congrArg Prod.fst hview) + have hin : view p (childFamily A i) clean (childRestriction A i x) = + view p (childFamily A i) clean (childRestriction A i y) := + congrArg Prod.snd hview + rw [evaluate_step] + simp only [RecursiveSampler.combine, RecursiveSampler.combineFunction, + Finset.sum_apply, Pi.add_apply, Pi.mul_apply, PointwiseSpaces.pullback_apply] + change + (∑ j : OffPath i, (tape (Sum.inl j)).val (childRestriction A j.val x)) + + (∑ h, (CutSamplerRefinement.evaluate 𝕜 repeats p (childFamily A i) + (subTape 𝕜 repeats i p A tape h false)).val (childRestriction A i x) * + (CutSamplerRefinement.evaluate 𝕜 repeats p (childFamily A i) + (subTape 𝕜 repeats i p A tape h true)).val (childRestriction A i x)) = + (∑ j : OffPath i, (tape (Sum.inl j)).val (childRestriction A j.val y)) + + (∑ h, (CutSamplerRefinement.evaluate 𝕜 repeats p (childFamily A i) + (subTape 𝕜 repeats i p A tape h false)).val (childRestriction A i y) * + (CutSamplerRefinement.evaluate 𝕜 repeats p (childFamily A i) + (subTape 𝕜 repeats i p A tape h true)).val (childRestriction A i y)) + congr 1 + · exact Finset.sum_congr rfl (fun j _ => congrArg (tape (Sum.inl j)).val (hout j)) + · apply Finset.sum_congr rfl + intro h _ + rw [ih p (childFamily A i) clean (subTape 𝕜 repeats i p A tape h false) + (hzero h false) _ _ hin, + ih p (childFamily A i) clean (subTape 𝕜 repeats i p A tape h true) + (hzero h true) _ _ hin] + +theorem evaluate_factors (𝕜 : Type w) [Field 𝕜] + (repeats : Nat → Nat) (p : Path branch n (m + 1)) + (A : Slots branch n → Type u) (clean : Fin (branch m) → Prop) + (tape : CutSamplerRefinement.Tape 𝕜 repeats p A) + (hzero : ZeroAtClean 𝕜 repeats p A clean tape) : + (CutSamplerRefinement.evaluate 𝕜 repeats p A tape).val ∈ + FactoredFunctions.factoringSpace (view p A clean) := + evaluate_eq_of_view_eq 𝕜 repeats p A clean tape hzero + +end +end PerfectCompleteness.CutSamplerLocality + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/CutSamplerRefinement.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/CutSamplerRefinement.lean new file mode 100644 index 0000000000000000000000000000000000000000..fd0f1638c6eba155030efd8060c31beee478b3b0 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/CutSamplerRefinement.lean @@ -0,0 +1,198 @@ +import OAI.Computability.PerfectCompleteness.Repetition.CleanConditioning +import OAI.Computability.PerfectCompleteness.Sampling.RecordSeedSamplingLemmas +import OAI.Computability.PerfectCompleteness.Sampling.UniformChildSum +import OAI.Computability.UniqueGames.Foundations.SamplingLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.CutSamplerRefinement + +open PointwiseSpaces RecursiveSpaces DescendantSpaces RecursiveSampler +open UniqueGamesTheorem.Foundations.Games +open scoped Classical + +noncomputable section + +universe u w + +variable {branch : Nat → Nat} {n m : Nat} + +def RefinedSpace (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n m) → (A : Slots branch n → Type u) → + DrawIndex repeats p → Type (max u w) + | 0, _, .refl _, A, _ => space 𝕜 branch 0 A + | n + 1, _, .refl _, A, _ => + (i : Fin (branch n)) → squareSpace (space 𝕜 branch n (childFamily A i)) + | n + 1, _, .step i p, A, j => + match j with + | Sum.inl j => squareSpace (space 𝕜 branch n (childFamily A j.val)) + | Sum.inr j => RefinedSpace 𝕜 repeats p (childFamily A i) j.2 + +def zeroFactor (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n m) → (A : Slots branch n → Type u) → + (j : DrawIndex repeats p) → RefinedSpace 𝕜 repeats p A j + | 0, _, .refl _, A, _ => (0 : space 𝕜 branch 0 A) + | n + 1, _, .refl _, A, _ => + fun i => (0 : squareSpace (space 𝕜 branch n (childFamily A i))) + | n + 1, _, .step i p, A, j => + match j with + | Sum.inl j => (0 : squareSpace (space 𝕜 branch n (childFamily A j.val))) + | Sum.inr j => zeroFactor 𝕜 repeats p (childFamily A i) j.2 + +instance refinedNonempty (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) + (p : Path branch n m) (A : Slots branch n → Type u) (j : DrawIndex repeats p) : + Nonempty (RefinedSpace 𝕜 repeats p A j) := ⟨zeroFactor 𝕜 repeats p A j⟩ + +theorem refined_finite (𝕜 : Type w) [Field 𝕜] [Finite 𝕜] + (repeats : Nat → Nat) (p : Path branch n m) : + ∀ (A : Slots branch n → Type u), (∀ s, Finite (A s)) → + ∀ j : DrawIndex repeats p, Finite (RefinedSpace 𝕜 repeats p A j) := by + induction p with + | refl n => + intro A hA j + let : ∀ s, Finite (A s) := hA + cases n with + | zero => + change Finite (space 𝕜 branch 0 A) + infer_instance + | succ n => + change Finite ((i : Fin (branch n)) → + squareSpace (space 𝕜 branch n (childFamily A i))) + let : ∀ i : Fin (branch n), + Finite (squareSpace (space 𝕜 branch n (childFamily A i))) := fun i => by + let : ∀ s, Finite ((childFamily A i) s) := fun s => hA (i, s) + infer_instance + infer_instance + | @step n m i p ih => + intro A hA j + cases j with + | inl j => + let : ∀ s, Finite ((childFamily A j.val) s) := fun s => hA (j.val, s) + change Finite (squareSpace (space 𝕜 branch n (childFamily A j.val))) + infer_instance + | inr j => + exact ih (childFamily A i) (fun s => hA (i, s)) j.2 + +instance refinedFinite (𝕜 : Type w) [Field 𝕜] [Finite 𝕜] + (repeats : Nat → Nat) (p : Path branch n m) + (A : Slots branch n → Type u) [∀ s, Finite (A s)] (j : DrawIndex repeats p) : + Finite (RefinedSpace 𝕜 repeats p A j) := + refined_finite 𝕜 repeats p A (fun _ => inferInstance) j + +instance refinedFintype (𝕜 : Type w) [Field 𝕜] [Finite 𝕜] + (repeats : Nat → Nat) (p : Path branch n m) + (A : Slots branch n → Type u) [∀ s, Finite (A s)] (j : DrawIndex repeats p) : + Fintype (RefinedSpace 𝕜 repeats p A j) := Fintype.ofFinite _ + +def collapseFactor (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n m) → (A : Slots branch n → Type u) → + (j : DrawIndex repeats p) → RefinedSpace 𝕜 repeats p A j → DrawSpace 𝕜 repeats p A j + | 0, _, .refl _, _, _, x => x + | _ + 1, _, .refl _, A, _, x => UniformChildSum.recursiveSum A x + | _ + 1, _, .step i p, A, j, x => + match j with + | Sum.inl _ => x + | Sum.inr j => collapseFactor 𝕜 repeats p (childFamily A i) j.2 x + +abbrev Tape (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) + (p : Path branch n m) (A : Slots branch n → Type u) := + (j : DrawIndex repeats p) → RefinedSpace 𝕜 repeats p A j + +def collapse (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) + (p : Path branch n m) (A : Slots branch n → Type u) : + Tape 𝕜 repeats p A → RecursiveSampler.Tape 𝕜 repeats p A := + fun x j => collapseFactor 𝕜 repeats p A j (x j) + +def tapeLaw (𝕜 : Type w) [Field 𝕜] [Finite 𝕜] (repeats : Nat → Nat) + (p : Path branch n m) (A : Slots branch n → Type u) [∀ s, Finite (A s)] : + FiniteDistribution (Tape 𝕜 repeats p A) := + FiniteProduct.law (fun j => FiniteDistribution.uniform (RefinedSpace 𝕜 repeats p A j)) + +private theorem pushforward_identity {Ω : Type*} [Fintype Ω] (μ : FiniteDistribution Ω) : + μ.pushforward (fun x => x) = μ := by + change μ.pushforward (Equiv.refl Ω) = μ + rw [FiniteDistribution.pushforward_equiv] + exact FiniteDistribution.eq_of_weight_eq (fun _ => rfl) + +theorem collapseFactor_uniform (𝕜 : Type w) [Field 𝕜] [Finite 𝕜] + (repeats : Nat → Nat) (p : Path branch n m) : + ∀ (A : Slots branch n → Type u) [∀ s, Finite (A s)] (j : DrawIndex repeats p), + (FiniteDistribution.uniform (RefinedSpace 𝕜 repeats p A j)).pushforward + (collapseFactor 𝕜 repeats p A j) = + FiniteDistribution.uniform (DrawSpace 𝕜 repeats p A j) := by + induction p with + | refl n => + intro A hA j + cases n with + | zero => + let : ∀ s, Finite (A s) := hA + let : Fintype (space 𝕜 branch 0 A) := Fintype.ofFinite _ + change (FiniteDistribution.uniform (space 𝕜 branch 0 A)).pushforward + (fun x => x) = FiniteDistribution.uniform (space 𝕜 branch 0 A) + exact pushforward_identity _ + | succ n => + let : Fintype ((i : Fin (branch n)) → + squareSpace (space 𝕜 branch n (childFamily A i))) := + refinedFintype 𝕜 repeats (.refl (n + 1)) A j + let : Fintype (space 𝕜 branch (n + 1) A) := + RecursiveSampler.drawSpaceFintype 𝕜 repeats (.refl (n + 1)) A j + exact UniformLinearImage.uniform_pushforward_linearMap + (UniformChildSum.recursiveSum (𝕜 := 𝕜) A) + (UniformChildSum.recursiveSum_surjective (𝕜 := 𝕜) A) + | @step n m i p ih => + intro A hA j + cases j with + | inl j => + let : ∀ s, Finite ((childFamily A j.val) s) := fun s => hA (j.val, s) + let : Fintype (squareSpace (space 𝕜 branch n (childFamily A j.val))) := + Fintype.ofFinite _ + change (FiniteDistribution.uniform + (squareSpace (space 𝕜 branch n (childFamily A j.val)))).pushforward + (fun x => x) = FiniteDistribution.uniform + (squareSpace (space 𝕜 branch n (childFamily A j.val))) + apply FiniteDistribution.eq_of_weight_eq + intro x + simp [FiniteDistribution.pushforward] + | inr j => + let : ∀ s, Finite ((childFamily A i) s) := fun s => hA (i, s) + exact ih (childFamily A i) j.2 + +theorem collapse_tapeLaw (𝕜 : Type w) [Field 𝕜] [Finite 𝕜] + (repeats : Nat → Nat) (p : Path branch n m) + (A : Slots branch n → Type u) [∀ s, Finite (A s)] : + (tapeLaw 𝕜 repeats p A).pushforward (collapse 𝕜 repeats p A) = + RecursiveSampler.tapeLaw 𝕜 repeats p A := by + unfold tapeLaw collapse + rw [CleanConditioning.pushforward_law] + simp_rw [collapseFactor_uniform] + rfl + +def evaluate (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) + (p : Path branch n m) (A : Slots branch n → Type u) (x : Tape 𝕜 repeats p A) : + space 𝕜 branch n A := + RecursiveSampler.evaluate 𝕜 repeats p A (collapse 𝕜 repeats p A x) + +theorem evaluate_law (𝕜 : Type w) [Field 𝕜] [Finite 𝕜] + (repeats : Nat → Nat) (p : Path branch n m) + (A : Slots branch n → Type u) [∀ s, Finite (A s)] [Fintype (space 𝕜 branch n A)] : + (tapeLaw 𝕜 repeats p A).pushforward (evaluate 𝕜 repeats p A) = + RecursiveSampler.law 𝕜 repeats p A := by + change (tapeLaw 𝕜 repeats p A).pushforward + ((RecursiveSampler.evaluate 𝕜 repeats p A) ∘ collapse 𝕜 repeats p A) = _ + calc + _ = ((tapeLaw 𝕜 repeats p A).pushforward (collapse 𝕜 repeats p A)).pushforward + (RecursiveSampler.evaluate 𝕜 repeats p A) := + (FiniteDistribution.pushforward_comp (tapeLaw 𝕜 repeats p A) + (collapse 𝕜 repeats p A) (RecursiveSampler.evaluate 𝕜 repeats p A)).symm + _ = _ := by + rw [collapse_tapeLaw] + rfl + +end +end PerfectCompleteness.CutSamplerRefinement + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/CutSamplerReplayGroupingTransport.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/CutSamplerReplayGroupingTransport.lean new file mode 100644 index 0000000000000000000000000000000000000000..19f05f93aea70d965d16c72339470614396dac31 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/CutSamplerReplayGroupingTransport.lean @@ -0,0 +1,208 @@ +import OAI.Computability.PerfectCompleteness.Foundations.WholeCutExteriorTransportLemmas +import OAI.Computability.PerfectCompleteness.Foundations.WholeCutReplayKeys +import OAI.Computability.PerfectCompleteness.Sampling.CutSamplerKeyLocalityLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.CutSamplerReplayGroupingTransport + +open PointwiseSpaces RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open RecursiveSampler TerminalCalls CutSamplerKeyLocality +open scoped Classical + +abbrev F2 := ZMod 2 + +noncomputable section + +universe u v + +theorem cast_pi_apply {I : Type u} {A B : I → Type v} + (h : ((i : I) → A i) = ((i : I) → B i)) (hA : ∀ i, A i = B i) + (f : (i : I) → A i) (i : I) : + (cast h f) i = cast (hA i) (f i) := by + have hAB : A = B := funext hA + cases hAB + rfl + +theorem cast_prod_fst {A A' : Type u} {B B' : Type v} + (h : (A × B) = (A' × B')) (hA : A = A') (hB : B = B') (x : A × B) : + (cast h x).1 = cast hA x.1 := by + cases hA + cases hB + rfl + +theorem cast_prod_snd {A A' : Type u} {B B' : Type v} + (h : (A × B) = (A' × B')) (hA : A = A') (hB : B = B') (x : A × B) : + (cast h x).2 = cast hB x.2 := by + cases hA + cases hB + rfl + +variable {branch : Nat → Nat} {n m t : Nat} + +theorem outside_kept (p : Path branch n (m + 1)) (clean : Fin (branch m) → Prop) : + ∀ s, WholeCutExteriorTransport.Outside p s → keptLeaf p clean s := by + induction n generalizing m with + | zero => + have h := p.height_le + omega + | succ n ih => + cases p with + | refl => + intro s hs + exact False.elim (hs ⟨s, rfl⟩) + | step i p => + rintro ⟨j, s⟩ hs + by_cases hji : j = i + · subst j + apply Or.inr + apply ih p clean s + rintro ⟨z, hz⟩ + exact hs ⟨z, congrArg (fun a => (i, a)) hz⟩ + · exact Or.inl hji + +theorem outside_eq (p : Path branch n (m + 1)) + (slots target : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (hs : ∀ s, keptLeaf p clean s → slots s = target s) : + ∀ s, WholeCutExteriorTransport.Outside p s → slots s = target s := + fun s hout => hs s (outside_kept p clean s hout) + +theorem retainedChildSlots_eq (p : Path branch n (m + 1)) + (slots target : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (hs : ∀ s, keptLeaf p clean s → slots s = target s) + (i : {i : Fin (branch m) // ¬ clean i}) : + childSlots (WholeCutGrouping.cutSlots p slots) i.val = + childSlots (WholeCutGrouping.cutSlots p target) i.val := by + funext s + exact hs (p.slotEmbedding (i.val, s)) ((keptLeaf_at_cut p clean i.val s).mpr i.property) + +theorem squareEquiv_eq_cast + (slots target : Slots branch n → Fin t → MixedSupport.Slot) (hs : slots = target) + (f : squareSpace (H slots)) : + (RecursiveSpaceEquiv.squareEquiv (𝕜 := F2) + (fun s => Equiv.cast (congrArg MixedSupport.Assignment (congrFun hs s)))).symm f = + cast (congrArg + (fun ss : Slots branch n → Fin t → MixedSupport.Slot => (squareSpace (H ss) : Type)) + hs) f := by + cases hs + apply Subtype.ext + funext x + rfl + +def castTerminal (repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots target : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (hs : ∀ s, keptLeaf p clean s → slots s = target s) + (terminal : CutSamplerReplayGrouping.RetainedTerminal F2 repeats p (LeafDomain slots) clean) : + CutSamplerReplayGrouping.RetainedTerminal F2 repeats p (LeafDomain target) clean := + fun call child => cast (congrArg + (fun ss : Slots branch m → Fin t → MixedSupport.Slot => (squareSpace (H ss) : Type)) + (retainedChildSlots_eq p slots target clean hs child)) (terminal call child) + +theorem subExterior_cast (repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n (m + 1)) + (slots target : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (hs : ∀ s, keptLeaf (.step i p) clean s → slots s = target s) + (call : Fin (repeats (n + 1)) × Bool) + (exterior : CutTerminalSplit.ExteriorTape F2 repeats (.step i p) (LeafDomain slots)) : + CutSamplerReplayGrouping.subExterior F2 repeats i p (LeafDomain target) call + (cast (WholeCutExteriorTransport.scalarExterior_eq repeats (.step i p) slots target + (outside_eq (.step i p) slots target clean hs)) exterior) = + cast (WholeCutExteriorTransport.scalarExterior_eq repeats p + (childSlots slots i) (childSlots target i) + (outside_eq p (childSlots slots i) (childSlots target i) clean + (fun s h => hs (i, s) (Or.inr h)))) + (CutSamplerReplayGrouping.subExterior F2 repeats i p (LeafDomain slots) call exterior) := by + funext j + let hext := WholeCutExteriorTransport.scalarExterior_eq repeats (.step i p) slots target + (outside_eq (.step i p) slots target clean hs) + let hsub := WholeCutExteriorTransport.scalarExterior_eq repeats p + (childSlots slots i) (childSlots target i) + (outside_eq p (childSlots slots i) (childSlots target i) clean + (fun s h => hs (i, s) (Or.inr h))) + change (cast hext exterior) (CutSamplerReplayGrouping.exteriorStepIndex repeats i p call j) = + (cast hsub + (CutSamplerReplayGrouping.subExterior F2 repeats i p (LeafDomain slots) call exterior)) j + rw [cast_pi_apply hext + (fun j => WholeCutExteriorTransport.factor_eq repeats (.step i p) slots target + (outside_eq (.step i p) slots target clean hs) j.val j.property)] + rw [cast_pi_apply hsub + (fun j => WholeCutExteriorTransport.factor_eq repeats p (childSlots slots i) + (childSlots target i) + (outside_eq p (childSlots slots i) (childSlots target i) clean + (fun s h => hs (i, s) (Or.inr h))) j.val j.property)] + rfl + +theorem transport_assemble (repeats : Nat → Nat) (p : Path branch n (m + 1)) : + ∀ (slots target : Slots branch n → Fin t → MixedSupport.Slot) + (clean : Fin (branch m) → Prop) + (hs : ∀ s, keptLeaf p clean s → slots s = target s) + (exterior : CutTerminalSplit.ExteriorTape F2 repeats p (LeafDomain slots)) + (terminal : CutSamplerReplayGrouping.RetainedTerminal F2 repeats p (LeafDomain slots) clean), + CutSamplerReplayTransport.transport F2 repeats p (LeafDomain slots) (LeafDomain target) + clean (WholeCutReplayKeys.leafEquiv p slots target clean hs) + (CutSamplerReplayGrouping.assemble F2 repeats p (LeafDomain slots) clean exterior terminal) = + CutSamplerReplayGrouping.assemble F2 repeats p (LeafDomain target) clean + (cast (WholeCutExteriorTransport.scalarExterior_eq repeats p slots target + (outside_eq p slots target clean hs)) exterior) + (castTerminal repeats p slots target clean hs terminal) := by + induction n generalizing m with + | zero => + have h := p.height_le + omega + | succ n ih => + cases p with + | refl => + intro slots target clean hs exterior terminal + funext child + exact squareEquiv_eq_cast (childSlots slots child.val) (childSlots target child.val) + (retainedChildSlots_eq (.refl (n + 1)) slots target clean hs child) (terminal () child) + | step i p => + intro slots target clean hs exterior terminal + apply Prod.ext + · funext j + let hext := WholeCutExteriorTransport.scalarExterior_eq repeats (.step i p) + slots target (outside_eq (.step i p) slots target clean hs) + let hslots := WholeCutExteriorTransport.ordinarySlots_eq i p slots target + (outside_eq (.step i p) slots target clean hs) j + change (RecursiveSpaceEquiv.squareEquiv (𝕜 := F2) + (fun s => WholeCutReplayKeys.leafEquiv (.step i p) slots target clean hs + (j.val, s) (Or.inl j.property))).symm + (exterior ⟨.inl j, not_isTerminal_ordinary repeats i p j⟩) = + (cast hext exterior) ⟨.inl j, not_isTerminal_ordinary repeats i p j⟩ + rw [cast_pi_apply hext + (fun j => WholeCutExteriorTransport.factor_eq repeats (.step i p) slots target + (outside_eq (.step i p) slots target clean hs) j.val j.property)] + exact squareEquiv_eq_cast (childSlots slots j.val) (childSlots target j.val) hslots + (exterior ⟨.inl j, not_isTerminal_ordinary repeats i p j⟩) + · funext call + change CutSamplerReplayTransport.transport F2 repeats p + (LeafDomain (childSlots slots i)) (LeafDomain (childSlots target i)) clean + (WholeCutReplayKeys.leafEquiv p (childSlots slots i) (childSlots target i) clean + (fun s h => hs (i, s) (Or.inr h))) + (CutSamplerReplayGrouping.assemble F2 repeats p (LeafDomain (childSlots slots i)) + clean (CutSamplerReplayGrouping.subExterior F2 repeats i p (LeafDomain slots) + call exterior) (fun location child => terminal (call, location) child)) = + CutSamplerReplayGrouping.assemble F2 repeats p (LeafDomain (childSlots target i)) + clean (CutSamplerReplayGrouping.subExterior F2 repeats i p (LeafDomain target) call + (cast (WholeCutExteriorTransport.scalarExterior_eq repeats (.step i p) slots target + (outside_eq (.step i p) slots target clean hs)) exterior)) + (fun location child => castTerminal repeats (.step i p) slots target clean hs + terminal (call, location) child) + rw [subExterior_cast repeats i p slots target clean hs call exterior] + exact ih p (childSlots slots i) (childSlots target i) clean + (fun s h => hs (i, s) (Or.inr h)) + (CutSamplerReplayGrouping.subExterior F2 repeats i p (LeafDomain slots) call exterior) + (fun location child => terminal (call, location) child) + +end +end PerfectCompleteness.CutSamplerReplayGroupingTransport + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/CutSamplerReplayTransportLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/CutSamplerReplayTransportLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..f54e5f348a771f4d875de77e017c6bec347297bf --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/CutSamplerReplayTransportLemmas.lean @@ -0,0 +1,324 @@ +import OAI.Computability.PerfectCompleteness.Construction.LocalReconstruction +import OAI.Computability.PerfectCompleteness.Foundations.RecursiveSpaceEquivLemmas +import OAI.Computability.PerfectCompleteness.Sampling.CutSamplerKeyLocalityLemmas +import OAI.Computability.PerfectCompleteness.Sampling.RecordSeedSamplingLemmas +import OAI.Computability.UniqueGames.Foundations.Conditioning +import OAI.Computability.UniqueGames.Foundations.SamplingLemmas + +namespace OAI + + +namespace PerfectCompleteness.CutSamplerReplayTransport + +open PointwiseSpaces RecursiveSpaces DescendantSpaces RecursiveSampler +open CutSamplerKeyLocality +open scoped BigOperators Classical + +noncomputable section + +universe u v w + +variable {branch : Nat → Nat} {n m : Nat} + (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) + +theorem squareEquiv_symm_apply + {A : Slots branch n → Type u} {B : Slots branch n → Type v} + (e : ∀ s, A s ≃ B s) (f : squareSpace (space 𝕜 branch n A)) + (y : Assignment B) : + ((RecursiveSpaceEquiv.squareEquiv (𝕜 := 𝕜) e).symm f).val y = + f.val (project (fun s => (e s).symm) y) := rfl + +theorem squareEquiv_symm_eval_of_agree + {A : Slots branch n → Type u} {B : Slots branch n → Type v} + (e : ∀ s, A s ≃ B s) (f : squareSpace (space 𝕜 branch n A)) + (x : Assignment A) (y : Assignment B) + (hagree : ∀ s, e s (x s) = y s) : + ((RecursiveSpaceEquiv.squareEquiv (𝕜 := 𝕜) e).symm f).val y = f.val x := by + rw [squareEquiv_symm_apply] + apply congrArg f.val + funext s + exact (congrArg (e s).symm (hagree s)).symm.trans ((e s).symm_apply_apply (x s)) + +def transport (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n (m + 1)) → + (A : Slots branch n → Type u) → (B : Slots branch n → Type v) → + (clean : Fin (branch m) → Prop) → + (∀ s, keptLeaf p clean s → A s ≃ B s) → + CutSamplerReplay.Tape 𝕜 repeats p A clean → + CutSamplerReplay.Tape 𝕜 repeats p B clean + | _, _, .refl _, _, _, _, e, tape => + fun i => (RecursiveSpaceEquiv.squareEquiv (𝕜 := 𝕜) + (fun s => e (i.val, s) i.property)).symm (tape i) + | _, _, .step i p, A, B, clean, e, tape => + (fun j => (RecursiveSpaceEquiv.squareEquiv (𝕜 := 𝕜) + (fun s => e (j.val, s) (Or.inl j.property))).symm (tape.1 j), + fun call => transport 𝕜 repeats p (childFamily A i) (childFamily B i) clean + (fun s hs => e (i, s) (Or.inr hs)) (tape.2 call)) + +theorem evaluate_transport (p : Path branch n (m + 1)) : + ∀ (A : Slots branch n → Type u) (B : Slots branch n → Type v) + (clean : Fin (branch m) → Prop) + (e : ∀ s, keptLeaf p clean s → A s ≃ B s) + (tape : CutSamplerReplay.Tape 𝕜 repeats p A clean) + (x : Assignment A) (y : Assignment B), + (∀ s hs, e s hs (x s) = y s) → + CutSamplerReplay.evaluate 𝕜 repeats p B clean + (transport 𝕜 repeats p A B clean e tape) y = + CutSamplerReplay.evaluate 𝕜 repeats p A clean tape x := by + induction n generalizing m with + | zero => + have h := p.height_le + omega + | succ n ih => + cases p with + | refl => + intro A B clean e tape x y hagree + simp only [CutSamplerReplay.evaluate_refl] + apply Finset.sum_congr rfl + intro i _ + exact squareEquiv_symm_eval_of_agree 𝕜 + (fun s => e (i.val, s) i.property) (tape i) + (childRestriction A i.val x) (childRestriction B i.val y) + (fun s => hagree (i.val, s) i.property) + | step i p => + intro A B clean e tape x y hagree + simp only [CutSamplerReplay.evaluate_step] + apply congrArg₂ (fun a b : 𝕜 => a + b) + · apply Finset.sum_congr rfl + intro j _ + exact squareEquiv_symm_eval_of_agree 𝕜 + (fun s => e (j.val, s) (Or.inl j.property)) (tape.1 j) + (childRestriction A j.val x) (childRestriction B j.val y) + (fun s => hagree (j.val, s) (Or.inl j.property)) + · apply Finset.sum_congr rfl + intro h _ + apply congrArg₂ (fun a b : 𝕜 => a * b) + · exact ih p (childFamily A i) (childFamily B i) clean + (fun s hs => e (i, s) (Or.inr hs)) (tape.2 (h, false)) + (childRestriction A i x) (childRestriction B i y) + (fun s hs => hagree (i, s) (Or.inr hs)) + · exact ih p (childFamily A i) (childFamily B i) clean + (fun s hs => e (i, s) (Or.inr hs)) (tape.2 (h, true)) + (childRestriction A i x) (childRestriction B i y) + (fun s hs => hagree (i, s) (Or.inr hs)) + +end +end PerfectCompleteness.CutSamplerReplayTransport + + +section + +namespace PerfectCompleteness.LocalReconstruction.Recipe + +open scoped BigOperators + +variable {𝕜 Atom Atom' X J : Type*} [Field 𝕜] + +def map (f : Atom → Atom') : Recipe 𝕜 Atom → Recipe 𝕜 Atom' + | .constant c => .constant c + | .atom a => .atom (f a) + | .add r s => .add (map f r) (map f s) + | .mul r s => .mul (map f r) (map f s) + +theorem evaluate_map (f : Atom → Atom') (atoms : Atom' → X → 𝕜) + (r : Recipe 𝕜 Atom) : + (r.map f).evaluate atoms = r.evaluate (fun a => atoms (f a)) := by + induction r with + | constant c => rfl + | atom a => rfl + | add r s hr hs => simp only [map, evaluate, hr, hs] + | mul r s hr hs => simp only [map, evaluate, hr, hs] + +def sumList (f : J → Recipe 𝕜 Atom) : List J → Recipe 𝕜 Atom + | [] => .constant 0 + | j :: js => .add (f j) (sumList f js) + +theorem evaluate_sumList (f : J → Recipe 𝕜 Atom) (js : List J) + (atoms : Atom → X → 𝕜) : + (sumList f js).evaluate atoms = (js.map fun j => (f j).evaluate atoms).sum := by + induction js with + | nil => rfl + | cons j js ih => simp only [sumList, evaluate, List.map_cons, List.sum_cons, ih] + +noncomputable def sumIndexed [Fintype J] (f : J → Recipe 𝕜 Atom) : Recipe 𝕜 Atom := + sumList f Finset.univ.toList + +theorem evaluate_sumIndexed [Fintype J] (f : J → Recipe 𝕜 Atom) + (atoms : Atom → X → 𝕜) : + (sumIndexed f).evaluate atoms = ∑ j, (f j).evaluate atoms := by + rw [sumIndexed, evaluate_sumList, Finset.sum_map_toList] + +end PerfectCompleteness.LocalReconstruction.Recipe + +namespace PerfectCompleteness.StoppedSamplerRecipe + +open scoped BigOperators +open PointwiseSpaces RecursiveSpaces DescendantSpaces RecursiveSampler +open LocalReconstruction + +noncomputable section + +universe u w + +variable {branch : Nat → Nat} {n m : Nat} + +def ordinaryTag (repeats : Nat → Nat) (i : Fin (branch n)) (p : Path branch n m) + (j : OffPath i) : DrawIndex repeats (.step i p) := Sum.inl j + +def factorTag (repeats : Nat → Nat) (i : Fin (branch n)) (p : Path branch n m) + (h : Fin (repeats (n + 1))) (b : Bool) (j : DrawIndex repeats p) : + DrawIndex repeats (.step i p) := Sum.inr ((h, b), j) + +def recipe (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n m) → Recipe 𝕜 (DrawIndex repeats p) + | _, _, .refl _ => .atom () + | n + 1, _, .step i p => + .add + (Recipe.sumIndexed (fun j : OffPath i => .atom (ordinaryTag repeats i p j))) + (Recipe.sumIndexed (fun h : Fin (repeats (n + 1)) => + .mul + ((recipe 𝕜 repeats p).map (factorTag repeats i p h false)) + ((recipe 𝕜 repeats p).map (factorTag repeats i p h true)))) + +def atoms (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n m) → (A : Slots branch n → Type u) → + Tape 𝕜 repeats p A → DrawIndex repeats p → Assignment A → 𝕜 + | _, _, .refl _, _, t, j => (t j).val + | _, _, .step i p, A, t, j => + match j with + | Sum.inl j => pullback 𝕜 (childRestriction A j.val) (t (Sum.inl j)).val + | Sum.inr j => + pullback 𝕜 (childRestriction A i) + (atoms 𝕜 repeats p (childFamily A i) + (subTape 𝕜 repeats i p A t j.1.1 j.1.2) j.2) + +variable (𝕜 : Type w) [Field 𝕜] + +theorem evaluate_recipe (repeats : Nat → Nat) (p : Path branch n m) : + ∀ (A : Slots branch n → Type u) (t : Tape 𝕜 repeats p A), + (recipe 𝕜 repeats p).evaluate (atoms 𝕜 repeats p A t) = + (RecursiveSampler.evaluate 𝕜 repeats p A t).val := by + induction p with + | refl n => + intro A t + rfl + | @step n m i p ih => + intro A t + have child (h : Fin (repeats (n + 1))) (b : Bool) : + ((recipe 𝕜 repeats p).map (factorTag repeats i p h b)).evaluate + (atoms 𝕜 repeats (.step i p) A t) = + (RecursiveSampler.evaluate 𝕜 repeats p (childFamily A i) + (subTape 𝕜 repeats i p A t h b)).val ∘ childRestriction A i := by + rw [Recipe.evaluate_map] + change (recipe 𝕜 repeats p).evaluate (fun j => + atoms 𝕜 repeats p (childFamily A i) (subTape 𝕜 repeats i p A t h b) j ∘ + childRestriction A i) = _ + rw [Recipe.evaluate_pullback, ih] + simp only [recipe, Recipe.evaluate, Recipe.evaluate_sumIndexed, child] + funext x + simp only [RecursiveSampler.evaluate, combine, combineFunction, + Finset.sum_apply, Pi.add_apply, Pi.mul_apply, Function.comp_apply, + atoms, ordinaryTag, PointwiseSpaces.pullback_apply] + +theorem evaluate_factors {Z : Type*} (repeats : Nat → Nat) (p : Path branch n m) + (A : Slots branch n → Type u) (t : Tape 𝕜 repeats p A) (other : Assignment A → Z) + (known : ∀ j, atoms 𝕜 repeats p A t j ∈ FactoredFunctions.factoringSpace other) : + (RecursiveSampler.evaluate 𝕜 repeats p A t).val ∈ + FactoredFunctions.factoringSpace other := by + rw [← evaluate_recipe 𝕜 repeats p A t] + exact Recipe.evaluate_factors other (atoms 𝕜 repeats p A t) known (recipe 𝕜 repeats p) + +end +end PerfectCompleteness.StoppedSamplerRecipe + +end + + +namespace PerfectCompleteness.UniformConditioning + +noncomputable section + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games + +variable {Ω Γ : Type*} [Fintype Ω] [Fintype Γ] [Nonempty Ω] [Nonempty Γ] + +theorem uniform_transport (e : Ω ≃ Γ) : + (FiniteDistribution.uniform Ω).transport e = FiniteDistribution.uniform Γ := by + apply FiniteDistribution.eq_of_weight_eq + intro y + change 1 / (Fintype.card Ω : ℝ) = 1 / (Fintype.card Γ : ℝ) + rw [Fintype.card_congr e] + +theorem uniform_probability_equiv (e : Ω ≃ Γ) (event : Γ → Bool) : + (FiniteDistribution.uniform Ω).probability (fun x => event (e x)) = + (FiniteDistribution.uniform Γ).probability event := by + rw [← uniform_transport e, FiniteDistribution.probability_transport] + +theorem uniform_probability (T : Ω → Prop) : + (FiniteDistribution.uniform Ω).probability (fun x => decide (T x)) = + (Fintype.card {x : Ω // T x} : ℝ) / (Fintype.card Ω : ℝ) := by + calc + _ = (∑ x : Ω, if T x then (1 : ℝ) else 0) / (Fintype.card Ω : ℝ) := by + change (∑ x : Ω, if decide (T x) then 1 / (Fintype.card Ω : ℝ) else 0) = _ + simp only [div_eq_mul_inv, Finset.sum_mul] + apply Finset.sum_congr rfl + intro x _ + by_cases hx : T x <;> simp [hx] + _ = _ := by simp only [Fintype.card_subtype, Finset.sum_boole] + +theorem uniform_probability_pos (T : Ω → Prop) [Nonempty {x : Ω // T x}] : + 0 < (FiniteDistribution.uniform Ω).probability (fun x => decide (T x)) := by + rw [uniform_probability] + exact div_pos (Nat.cast_pos.mpr Fintype.card_pos) (Nat.cast_pos.mpr Fintype.card_pos) + +omit [Nonempty Ω] in +theorem uniform_subtype_pushforward_weight (T : Ω → Prop) + [Nonempty {x : Ω // T x}] (x : Ω) : + ((FiniteDistribution.uniform {x : Ω // T x}).pushforward Subtype.val).weight x = + if T x then 1 / (Fintype.card {x : Ω // T x} : ℝ) else 0 := by + change (∑ y : {x : Ω // T x}, + if y.val = x then 1 / (Fintype.card {x : Ω // T x} : ℝ) else 0) = _ + by_cases hx : T x + · rw [ite_eq_left hx] + rw [Finset.sum_eq_single (⟨x, hx⟩ : {x : Ω // T x})] + · simp + · intro y _ hy + have hne : y.val ≠ x := fun heq => hy (Subtype.ext heq) + simp [hne] + · simp + · rw [ite_eq_right hx] + apply Finset.sum_eq_zero + intro y _ + have hne : y.val ≠ x := fun heq => hx (heq ▸ y.property) + simp [hne] + +theorem condition_uniform (T : Ω → Prop) [Nonempty {x : Ω // T x}] + (positive : 0 < (FiniteDistribution.uniform Ω).probability (fun x => decide (T x))) : + (FiniteDistribution.uniform Ω).condition (fun x => decide (T x)) positive = + (FiniteDistribution.uniform {x : Ω // T x}).pushforward Subtype.val := by + apply FiniteDistribution.eq_of_weight_eq + intro x + rw [uniform_subtype_pushforward_weight] + change (if decide (T x) then + (1 / (Fintype.card Ω : ℝ)) / + (FiniteDistribution.uniform Ω).probability (fun x => decide (T x)) else 0) = _ + rw [uniform_probability] + have hcard : (Fintype.card Ω : ℝ) ≠ 0 := Nat.cast_ne_zero.mpr Fintype.card_ne_zero + by_cases hx : T x + · simpa [hx] using + div_div_div_cancel_right₀ hcard (1 : ℝ) (Fintype.card {x : Ω // T x} : ℝ) + · simp [hx] + +theorem probability_condition_uniform (T : Ω → Prop) [Nonempty {x : Ω // T x}] + (positive : 0 < (FiniteDistribution.uniform Ω).probability (fun x => decide (T x))) + (event : Ω → Bool) : + ((FiniteDistribution.uniform Ω).condition (fun x => decide (T x)) positive).probability + event = + (FiniteDistribution.uniform {x : Ω // T x}).probability (fun x => event x.val) := by + rw [condition_uniform, FiniteDistribution.probability_pushforward] + +end +end PerfectCompleteness.UniformConditioning + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/DensityVariation.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/DensityVariation.lean new file mode 100644 index 0000000000000000000000000000000000000000..a0833986fffe02acaecc7fefdecd61471807f321 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/DensityVariation.lean @@ -0,0 +1,102 @@ +import Mathlib.Analysis.Real.Sqrt +import OAI.Computability.PerfectCompleteness.Foundations.RecursiveSpaceEquivLemmas +import OAI.Computability.UniqueGames.Foundations.MixtureLemmas +import OAI.Computability.UniqueGames.Foundations.ValueLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.DensityVariation + +open scoped BigOperators +open UniqueGamesTheorem.Foundations.Games +open PerfectCompleteness.SmallBias + +noncomputable section + +variable {Ω Γ : Type*} [Fintype Ω] [Fintype Γ] + +theorem expectation_sub (μ : FiniteDistribution Ω) (f g : Ω → ℝ) : + μ.expectation (fun x => f x - g x) = μ.expectation f - μ.expectation g := by + simp only [FiniteDistribution.expectation, mul_sub, Finset.sum_sub_distrib] + +theorem expectation_mul_const (μ : FiniteDistribution Ω) (f : Ω → ℝ) (c : ℝ) : + μ.expectation (fun x => f x * c) = μ.expectation f * c := by + simp only [FiniteDistribution.expectation, ← mul_assoc, Finset.sum_mul] + +theorem expectation_div (μ : FiniteDistribution Ω) (f : Ω → ℝ) (c : ℝ) : + μ.expectation (fun x => f x / c) = μ.expectation f / c := by + simpa only [div_eq_mul_inv] using expectation_mul_const μ f c⁻¹ + +def reweight (μ : FiniteDistribution Ω) (density : Ω → ℝ) + (nonnegative : ∀ x, 0 ≤ density x) (mean_one : μ.expectation density = 1) : + FiniteDistribution Ω where + weight x := μ.weight x * density x + nonnegative x := mul_nonneg (μ.nonnegative x) (nonnegative x) + normalized := mean_one + +theorem variation_eq_density (μ ν : FiniteDistribution Ω) (density : Ω → ℝ) + (h : ∀ x, ν.weight x = μ.weight x * density x) : + ν.totalVariation μ = μ.expectation (fun x => |density x - 1|) / 2 := by + unfold FiniteDistribution.totalVariation FiniteDistribution.expectation + congr 1 + apply Finset.sum_congr rfl + intro x _ + rw [h x, show μ.weight x * density x - μ.weight x = + μ.weight x * (density x - 1) by ring, abs_mul, + abs_of_nonneg (μ.nonnegative x)] + +theorem variation_le_sqrt (μ ν : FiniteDistribution Ω) (density : Ω → ℝ) + (h : ∀ x, ν.weight x = μ.weight x * density x) (v : ℝ) + (hv : μ.expectation (fun x => (density x - 1) ^ 2) ≤ v) : + ν.totalVariation μ ≤ Real.sqrt v / 2 := by + rw [variation_eq_density μ ν density h] + apply div_le_div_of_nonneg_right _ (by norm_num : (0 : ℝ) ≤ 2) + apply Real.le_sqrt_of_sq_le + have hcs := UniqueGamesTheorem.Foundations.Information.weighted_sum_sq_le μ.weight + (fun x => |density x - 1|) ⟨μ.nonnegative, μ.normalized⟩ + change μ.expectation (fun x => |density x - 1|) ^ 2 ≤ + μ.expectation (fun x => |density x - 1| ^ 2) at hcs + simpa only [sq_abs] using hcs.trans (by simpa only [sq_abs] using hv) + +theorem variation_pushforward_le (μ ν : FiniteDistribution Ω) (observe : Ω → Γ) : + (μ.pushforward observe).totalVariation (ν.pushforward observe) ≤ + μ.totalVariation ν := by + classical + unfold FiniteDistribution.totalVariation + apply div_le_div_of_nonneg_right _ (by norm_num : (0 : ℝ) ≤ 2) + have hdiff (y : Γ) : + (μ.pushforward observe).weight y - (ν.pushforward observe).weight y = + ∑ x, if observe x = y then μ.weight x - ν.weight x else 0 := by + simp only [FiniteDistribution.pushforward, ← Finset.sum_sub_distrib] + apply Finset.sum_congr rfl + intro x _ + by_cases hx : observe x = y <;> simp [hx] + calc + _ ≤ ∑ y, ∑ x, if observe x = y then |μ.weight x - ν.weight x| else 0 := by + apply Finset.sum_le_sum + intro y _ + rw [hdiff] + calc + _ ≤ ∑ x, |if observe x = y then μ.weight x - ν.weight x else 0| := + Finset.abs_sum_le_sum_abs _ _ + _ = _ := by + apply Finset.sum_congr rfl + intro x _ + split <;> simp + _ = _ := by rw [Finset.sum_comm]; simp + +theorem observed_variation_le_sqrt (μ ν : FiniteDistribution Ω) (density : Ω → ℝ) + (h : ∀ x, ν.weight x = μ.weight x * density x) (v : ℝ) + (hv : μ.expectation (fun x => (density x - 1) ^ 2) ≤ v) + (observe : Ω → Γ) : + (ν.pushforward observe).totalVariation (μ.pushforward observe) ≤ Real.sqrt v / 2 := + (variation_pushforward_le ν μ observe).trans (variation_le_sqrt μ ν density h v hv) + +end +end PerfectCompleteness.DensityVariation + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/FilledUniformSampler.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/FilledUniformSampler.lean new file mode 100644 index 0000000000000000000000000000000000000000..24e9709829bc8a6dda02b7b18af38a54afbfe2aa --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/FilledUniformSampler.lean @@ -0,0 +1,121 @@ +import OAI.Computability.PerfectCompleteness.Foundations.CutSlotOutside +import OAI.Computability.PerfectCompleteness.Foundations.WholeCutExteriorTransportLemmas +import OAI.Computability.PerfectCompleteness.Foundations.WholeCutGrouping + +namespace OAI + +section + +namespace PerfectCompleteness.FilledUniformSampler + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open scoped Classical + +noncomputable section + +variable {branch : Nat → Nat} {n m t : Nat} + (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (outside : Slots branch n → Fin t → MixedSupport.Slot) + (placeholder : Slots branch (m + 1) → Fin t → MixedSupport.Slot) + +abbrev Exterior := WholeCutGrouping.Exterior rows repeats p + (CutSlotAssembly.fill p outside placeholder) + +theorem cutSlots_fill (inside : Slots branch (m + 1) → Fin t → MixedSupport.Slot) : + WholeCutGrouping.cutSlots p (CutSlotAssembly.fill p outside inside) = inside := by + funext s + exact CutSlotAssembly.fill_at_cut p outside inside s + +def exteriorEquiv (inside : Slots branch (m + 1) → Fin t → MixedSupport.Slot) : + Exterior rows repeats p outside placeholder ≃ + WholeCutGrouping.Exterior rows repeats p (CutSlotAssembly.fill p outside inside) := + WholeCutExteriorTransport.equiv rows repeats p + (CutSlotAssembly.fill p outside placeholder) (CutSlotAssembly.fill p outside inside) + (CutSlotAssembly.fill_outside_eq p outside placeholder inside) + +def childrenEquiv (inside : Slots branch (m + 1) → Fin t → MixedSupport.Slot) : + CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) inside rows ≃ + CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) + (WholeCutGrouping.cutSlots p (CutSlotAssembly.fill p outside inside)) rows := + Equiv.piCongrRight (fun i => Equiv.cast (congrArg + (fun slots => CutChildGrouping.Child (C := WholeCutCalls.Index rows repeats p) slots rows i) + (cutSlots_fill p outside inside).symm)) + +@[simp] theorem childrenEquiv_apply + (inside : Slots branch (m + 1) → Fin t → MixedSupport.Slot) + (children : CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) inside rows) + (i : Fin (branch m)) : + childrenEquiv rows repeats p outside inside children i = + cast (congrArg + (fun slots => CutChildGrouping.Child (C := WholeCutCalls.Index rows repeats p) slots rows i) + (cutSlots_fill p outside inside).symm) (children i) := rfl + +theorem childrenEquiv_heq + (inside : Slots branch (m + 1) → Fin t → MixedSupport.Slot) + (children : CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) inside rows) + (i : Fin (branch m)) : + HEq (childrenEquiv rows repeats p outside inside children i) (children i) := + cast_heq _ _ + +def filledSplitEquiv (inside : Slots branch (m + 1) → Fin t → MixedSupport.Slot) : + (Exterior rows repeats p outside placeholder × + CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) inside rows) ≃ + WholeCutSampler.Tape rows repeats p (CutSlotAssembly.fill p outside inside) := + (Equiv.prodCongr (exteriorEquiv rows repeats p outside placeholder inside) + (childrenEquiv rows repeats p outside inside)).trans + (WholeCutGrouping.splitTape rows repeats p (CutSlotAssembly.fill p outside inside)).symm + +theorem filledSplitEquiv_apply + (inside : Slots branch (m + 1) → Fin t → MixedSupport.Slot) + (external : Exterior rows repeats p outside placeholder) + (children : CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) inside rows) : + filledSplitEquiv rows repeats p outside placeholder inside (external, children) = + (WholeCutGrouping.splitTape rows repeats p (CutSlotAssembly.fill p outside inside)).symm + (exteriorEquiv rows repeats p outside placeholder inside external, + childrenEquiv rows repeats p outside inside children) := rfl + +theorem filledSplitEquiv_tapeLaw + (inside : Slots branch (m + 1) → Fin t → MixedSupport.Slot) : + ((FiniteDistribution.uniform (Exterior rows repeats p outside placeholder)).product + (CutChildGrouping.rawLaw (C := WholeCutCalls.Index rows repeats p) inside rows)).pushforward + (filledSplitEquiv rows repeats p outside placeholder inside) = + WholeCutSampler.tapeLaw rows repeats p (CutSlotAssembly.fill p outside inside) := by + unfold CutChildGrouping.rawLaw + rw [UniformLinearImage.law_uniform, WholeCutSampler.uniform_product, + WholeCutSampler.tapeLaw_eq_uniform, FiniteDistribution.pushforward_equiv] + apply FiniteDistribution.eq_of_weight_eq + intro x + change 1 / (Fintype.card (Exterior rows repeats p outside placeholder × + CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) inside rows) : ℝ) = + 1 / (Fintype.card + (WholeCutSampler.Tape rows repeats p (CutSlotAssembly.fill p outside inside)) : ℝ) + rw [Fintype.card_congr (filledSplitEquiv rows repeats p outside placeholder inside)] + +def evaluate (inside : Slots branch (m + 1) → Fin t → MixedSupport.Slot) + (x : Exterior rows repeats p outside placeholder × + CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) inside rows) : + Arrays (CutSlotAssembly.fill p outside inside) rows := + WholeCutSampler.evaluate rows repeats p (CutSlotAssembly.fill p outside inside) + (filledSplitEquiv rows repeats p outside placeholder inside x) + +theorem evaluate_law (inside : Slots branch (m + 1) → Fin t → MixedSupport.Slot) : + ((FiniteDistribution.uniform (Exterior rows repeats p outside placeholder)).product + (CutChildGrouping.rawLaw (C := WholeCutCalls.Index rows repeats p) inside rows)).pushforward + (evaluate rows repeats p outside placeholder inside) = + WholeArraySampler.law rows repeats p (CutSlotAssembly.fill p outside inside) := by + unfold evaluate + rw [← FiniteDistribution.pushforward_comp + ((FiniteDistribution.uniform (Exterior rows repeats p outside placeholder)).product + (CutChildGrouping.rawLaw (C := WholeCutCalls.Index rows repeats p) inside rows)) + (filledSplitEquiv rows repeats p outside placeholder inside) + (WholeCutSampler.evaluate rows repeats p (CutSlotAssembly.fill p outside inside)), + filledSplitEquiv_tapeLaw] + exact WholeCutSampler.evaluate_law rows repeats p (CutSlotAssembly.fill p outside inside) + +end +end PerfectCompleteness.FilledUniformSampler + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/FiniteListSampling.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/FiniteListSampling.lean new file mode 100644 index 0000000000000000000000000000000000000000..4afd6bb2238ca48814bbca9ed0c39df6cadfe1f6 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/FiniteListSampling.lean @@ -0,0 +1,105 @@ +import Mathlib.Algebra.BigOperators.Field +import OAI.Computability.PerfectCompleteness.Foundations.OccurrenceStochasticLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.FiniteListSampling + +open scoped BigOperators +open UniqueGamesTheorem.Foundations.Games + +noncomputable section + +variable {A B : Type*} [Fintype A] [Fintype B] [DecidableEq A] [DecidableEq B] + +def uniformList (L : Finset A) (nonempty : L.Nonempty) : FiniteDistribution A where + weight a := if a ∈ L then 1 / (L.card : ℝ) else 0 + nonnegative a := by + split + · exact one_div_nonneg.mpr (Nat.cast_nonneg _) + · exact le_rfl + normalized := by + have hcard : (L.card : ℝ) ≠ 0 := Nat.cast_ne_zero.mpr (ne_of_gt nonempty.card_pos) + simp only [Finset.sum_ite_mem_eq, Finset.sum_const, nsmul_eq_mul, mul_one_div] + exact div_self hcard + +@[simp] theorem uniformList_weight_mem (L : Finset A) (hne : L.Nonempty) + (a : A) (ha : a ∈ L) : (uniformList L hne).weight a = 1 / (L.card : ℝ) := by + simp [uniformList, ha] + +omit [DecidableEq A] in +theorem probability_ge_weight (μ : FiniteDistribution A) (event : A → Bool) + (a : A) (ha : event a = true) : μ.weight a ≤ μ.probability event := by + change μ.weight a ≤ ∑ x, if event x then μ.weight x else 0 + have h := Finset.single_le_sum + (f := fun x : A => if event x then μ.weight x else 0) + (fun x _ => by split; exact μ.nonnegative x; exact le_rfl) (Finset.mem_univ a) + simpa only [ha, ite_true] using h + +def pairAcceptance (μ : FiniteDistribution A) (ν : FiniteDistribution B) + (accepts : A → B → Bool) : ℝ := + μ.expectation (fun a => ν.probability (accepts a)) + +omit [DecidableEq A] [DecidableEq B] in +theorem pairAcceptance_nonnegative (μ : FiniteDistribution A) (ν : FiniteDistribution B) + (accepts : A → B → Bool) : 0 ≤ pairAcceptance μ ν accepts := by + apply Finset.sum_nonneg + intro a _ + exact mul_nonneg (μ.nonnegative a) (ν.probability_nonnegative _) + +omit [DecidableEq A] [DecidableEq B] in +theorem pair_weight_le_acceptance (μ : FiniteDistribution A) (ν : FiniteDistribution B) + (accepts : A → B → Bool) (a : A) (b : B) (accepted : accepts a b = true) : + μ.weight a * ν.weight b ≤ pairAcceptance μ ν accepts := by + have hinner := probability_ge_weight ν (accepts a) b accepted + calc + _ ≤ μ.weight a * ν.probability (accepts a) := + mul_le_mul_of_nonneg_left hinner (μ.nonnegative a) + _ ≤ _ := Finset.single_le_sum + (fun x _ => mul_nonneg (μ.nonnegative x) (ν.probability_nonnegative _)) + (Finset.mem_univ a) + +theorem uniform_pair_lower (L : Finset A) (R : Finset B) + (hL : L.Nonempty) (hR : R.Nonempty) (accepts : A → B → Bool) + (witness : ∃ a ∈ L, ∃ b ∈ R, accepts a b = true) : + 1 / ((L.card : ℝ) * (R.card : ℝ)) ≤ + pairAcceptance (uniformList L hL) (uniformList R hR) accepts := by + obtain ⟨a, ha, b, hb, hab⟩ := witness + have h := pair_weight_le_acceptance (uniformList L hL) (uniformList R hR) accepts a b hab + simpa only [uniformList_weight_mem L hL a ha, uniformList_weight_mem R hR b hb, + ← one_div_mul_one_div] using h + +theorem bounded_uniform_pair_lower (L : Finset A) (R : Finset B) + (hL : L.Nonempty) (hR : R.Nonempty) (s : Nat) + (hLs : L.card ≤ s) (hRs : R.card ≤ s) (accepts : A → B → Bool) + (witness : ∃ a ∈ L, ∃ b ∈ R, accepts a b = true) : + 1 / (s : ℝ) ^ 2 ≤ + pairAcceptance (uniformList L hL) (uniformList R hR) accepts := by + have hLc : 0 < (L.card : ℝ) := Nat.cast_pos.mpr hL.card_pos + have hRc : 0 < (R.card : ℝ) := Nat.cast_pos.mpr hR.card_pos + have hLs' : (L.card : ℝ) ≤ s := by exact_mod_cast hLs + have hRs' : (R.card : ℝ) ≤ s := by exact_mod_cast hRs + have hprod : (L.card : ℝ) * (R.card : ℝ) ≤ (s : ℝ) ^ 2 := by + simpa only [pow_two] using + mul_le_mul hLs' hRs' (Nat.cast_nonneg R.card) (Nat.cast_nonneg s) + exact (one_div_le_one_div_of_le (mul_pos hLc hRc) hprod).trans + (uniform_pair_lower L R hL hR accepts witness) + +omit [DecidableEq A] [DecidableEq B] in +theorem pairAcceptance_eq_expectation (μ : FiniteDistribution A) (ν : FiniteDistribution B) + (accepts : A → B → Bool) : + pairAcceptance μ ν accepts = μ.expectation + (fun a => ν.expectation (fun b => if accepts a b then 1 else 0)) := by + unfold pairAcceptance + apply FiniteDistribution.expectation_congr + intro a + simp [FiniteDistribution.probability, FiniteDistribution.expectation, mul_ite] + +end +end PerfectCompleteness.FiniteListSampling + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/FixedSourcePairVariation.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/FixedSourcePairVariation.lean new file mode 100644 index 0000000000000000000000000000000000000000..8462c41712c9fc254a34ac3791be7c5be6c6206e --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/FixedSourcePairVariation.lean @@ -0,0 +1,219 @@ +import OAI.Computability.PerfectCompleteness.Construction.HierarchicalBucketFamily +import OAI.Computability.PerfectCompleteness.Decoding.FixedUpperPairErrorLemmas +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalUsefulBackground +import OAI.Computability.PerfectCompleteness.Sampling.CommonProductVariationLemmas +import OAI.Computability.PerfectCompleteness.Sampling.StoppedSourcePairLaw + +namespace OAI + +section + +namespace PerfectCompleteness.FixedSourcePairVariation + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCutTape WholeArrayInteriorExterior +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) +open scoped Classical + +noncomputable section + +attribute [local instance] linearMapFintype +attribute [local instance 2000] HierarchicalUsefulCollision.backgroundFintype + HierarchicalUsefulCollision.rowSpaceFintype + +private theorem sigma_variation_le_const + {O : Type*} [Fintype O] {R : O → Type*} [∀ o, Fintype (R o)] + (outer : FiniteDistribution O) + (P Q : (o : O) → FiniteDistribution (R o)) + (error : ℝ) (bound : ∀ o, (P o).totalVariation (Q o) ≤ error) : + (CompletionSoundness.sigmaLaw outer P).totalVariation + (CompletionSoundness.sigmaLaw outer Q) ≤ error := by + rw [ConditionalVariation.sigma_totalVariation outer P Q] + calc + outer.expectation (fun o => (P o).totalVariation (Q o)) ≤ + outer.expectation (fun _ => error) := + SmallBias.expectation_mono outer bound + _ = error := SmallBias.expectation_const outer error + +variable {δ : ℚ} {hδ : 0 < δ} (parameters : FixedParameters.Parameters δ hδ) + {n i j v m : Nat} + +abbrev Outer := StoppedProjectedExperiment.Outer + (branch := FixedParameters.branch parameters) (n := n) (j := j) + (t := FixedRows.sourceLength parameters.plan hδ) (m := m) + +def flags : Fin (FixedParameters.branch parameters i) → FiniteDistribution Bool := + fun _ => ProjectionPosterior.bernoulli (FixedParameters.projectionProbability parameters i : ℝ) + (by exact_mod_cast (FixedParameters.projectionProbability_bounds parameters i).1.le) + (by exact_mod_cast (FixedParameters.projectionProbability_bounds parameters i).2.le) + +abbrev positiveRows (height : Nat) : 0 < FixedRows.rows parameters.plan (height + 1) := + FixedUpperCutTriangle.rows_positive parameters (height + 1) + +variable (clauses : Fin m → SourceClause.NormalizedClause v) + (hupper : j + 1 ≤ n) (hij : i < j) + (designated : Fin (FixedParameters.branch parameters i) → Slots (FixedParameters.branch parameters) i) + +abbrev experiment + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount (FixedParameters.branch parameters) n + (FixedRows.sourceLength parameters.plan hδ))) + (o : Outer (n := n) (j := j) (m := m) parameters) := + StoppedProjectedBuckets.experiment clauses (FixedRows.rows parameters.plan) + (FixedRows.repeats parameters.plan) hupper hij designated (positiveRows parameters) o + (fun k _ => FixedParameters.branch_pos parameters k) (flags (i := i) parameters) σ + +abbrev Descriptor (o : Outer (n := n) (j := j) (m := m) parameters) := + StoppedProjectedBuckets.Descriptor clauses (FixedRows.rows parameters.plan) + (FixedRows.repeats parameters.plan) hupper hij designated (positiveRows parameters) o + +def externalLaw (o : Outer (n := n) (j := j) (m := m) parameters) : + FiniteDistribution (Descriptor parameters clauses hupper hij designated o) := + StoppedProjectedBuckets.externalLaw clauses (FixedRows.rows parameters.plan) + (FixedRows.repeats parameters.plan) hupper hij designated (positiveRows parameters) o + (fun k _ => FixedParameters.branch_pos parameters k) (flags (i := i) parameters) + +abbrev background (o : Outer (n := n) (j := j) (m := m) parameters) := + StoppedProjectedBuckets.background clauses (FixedRows.rows parameters.plan) + (FixedRows.repeats parameters.plan) hupper hij designated (positiveRows parameters) o + +abbrev scalarLaw (o : Outer (n := n) (j := j) (m := m) parameters) := + StoppedProjectedBuckets.scalarLaw clauses (FixedRows.rows parameters.plan) + (FixedRows.repeats parameters.plan) hupper hij designated (positiveRows parameters) o + +abbrev upperRows (o : Outer (n := n) (j := j) (m := m) parameters) := + StoppedProjectedBuckets.rows_positive (FixedRows.rows parameters.plan) hupper (positiveRows parameters) o + +variable (σ : KeyStrategy.Strategy (TreeCanonical.locationCount (FixedParameters.branch parameters) n + (FixedRows.sourceLength parameters.plan hδ))) + +local instance backgroundFintype (o : Outer (n := n) (j := j) (m := m) parameters) : + Fintype (HierarchicalAgreementMean.Background (rows := FixedRows.rows parameters.plan) + (StoppedProjectedExperiment.nativeSlots clauses o) + (StoppedProjectedExperiment.upper hupper o)) := Fintype.ofFinite _ + +local instance rowSpaceFintype (o : Outer (n := n) (j := j) (m := m) parameters) : + Fintype (NodeEmbedding.RowSpace (StoppedProjectedExperiment.nativeSlots clauses o) + (StoppedProjectedExperiment.upper hupper o)) := Fintype.ofFinite _ + +abbrev PairFiber (o : Outer (n := n) (j := j) (m := m) parameters) := + HierarchicalAgreementMean.PairRecord (rows := FixedRows.rows parameters.plan) + (StoppedProjectedExperiment.nativeSlots clauses o) + (StoppedProjectedExperiment.upper hupper o) + +abbrev PairRecord := + (o : Outer (n := n) (j := j) (m := m) parameters) × PairFiber parameters clauses hupper o + +theorem fiber_lt_six (hroot : n ≤ parameters.plan.depth) + (o : Outer (n := n) (j := j) (m := m) parameters) : + (HierarchicalAdviceFromBuckets.pairedLaw (experiment parameters clauses hupper hij designated σ o) + (externalLaw parameters clauses hupper hij designated o) + (background parameters clauses hupper hij designated o) + (scalarLaw parameters clauses hupper hij designated o) (upperRows parameters hupper o)).totalVariation + (HierarchicalAgreementMean.referenceLaw + (StoppedProjectedExperiment.nativeSlots clauses o) (StoppedProjectedExperiment.upper hupper o) + ((externalLaw parameters clauses hupper hij designated o).pushforward + (background parameters clauses hupper hij designated o)) (upperRows parameters hupper o)) < + 6 * parameters.accuracy := by + let pref := StoppedProjectedExperiment.upperPath hupper o + let slots := StoppedProjectedExperiment.nativeSlots clauses o + let projected := SourceProjectedWholeChoices.projected clauses hupper hij o + let projection := SourceProjectedWholeChoices.projection clauses hupper hij o + let choiceLaw := fun _ : UpperCutTriangle.Prefix (FixedParameters.branch parameters) j i => + SourceProjectedChoices.choiceLaw + (branch := FixedParameters.branch parameters) (n := i) + (t := FixedRows.sourceLength parameters.plan hδ) + have hpair := StoppedSourcePairLaw.pairedLaw_eq_modified clauses + (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) hupper hij designated + (positiveRows parameters) o (fun k _ => FixedParameters.branch_pos parameters k) + (FixedParameters.projectionProbability parameters i : ℝ) + (by exact_mod_cast (FixedParameters.projectionProbability_bounds parameters i).1.le) + (by exact_mod_cast (FixedParameters.projectionProbability_bounds parameters i).2.le) σ + change HierarchicalAdviceFromBuckets.pairedLaw + (experiment parameters clauses hupper hij designated σ o) + (externalLaw parameters clauses hupper hij designated o) + (background parameters clauses hupper hij designated o) + (scalarLaw parameters clauses hupper hij designated o) (upperRows parameters hupper o) = + FixedUpperCutTriangle.modifiedPairLaw parameters pref (Nat.succ_le_succ hij.le) slots + projected projection choiceLaw at hpair + have h := FixedUpperCutTriangle.original_reference_lt parameters pref + (Nat.succ_le_succ hij.le) slots projected projection choiceLaw hroot + change (FixedUpperCutTriangle.modifiedPairLaw parameters pref (Nat.succ_le_succ hij.le) slots + projected projection choiceLaw).totalVariation + (HierarchicalAgreementMean.referenceLaw slots (upperNode pref) + ((FixedUpperCutTriangle.modifiedPairLaw parameters pref (Nat.succ_le_succ hij.le) slots + projected projection choiceLaw).pushforward Prod.fst) (upperRows parameters hupper o)) < + 6 * parameters.accuracy at h + rw [← hpair] at h + have hbackground : + (HierarchicalAdviceFromBuckets.pairedLaw + (experiment parameters clauses hupper hij designated σ o) + (externalLaw parameters clauses hupper hij designated o) + (background parameters clauses hupper hij designated o) + (scalarLaw parameters clauses hupper hij designated o) + (upperRows parameters hupper o)).pushforward Prod.fst = + (externalLaw parameters clauses hupper hij designated o).pushforward + (background parameters clauses hupper hij designated o) := + HierarchicalUsefulBackground.pairLaw_background slots (upperNode pref) + (externalLaw parameters clauses hupper hij designated o) + (background parameters clauses hupper hij designated o) + (scalarLaw parameters clauses hupper hij designated o) (upperRows parameters hupper o) + have hvariation := congrArg + (fun backgroundLaw : FiniteDistribution + (HierarchicalAgreementMean.Background (rows := FixedRows.rows parameters.plan) + slots (upperNode pref)) => + (HierarchicalUsefulCollision.pairLaw slots (upperNode pref) + (externalLaw parameters clauses hupper hij designated o) + (background parameters clauses hupper hij designated o) + (scalarLaw parameters clauses hupper hij designated o) + (upperRows parameters hupper o)).totalVariation + (HierarchicalAgreementMean.referenceLaw slots (upperNode pref) + backgroundLaw (upperRows parameters hupper o))) hbackground + exact lt_of_eq_of_lt hvariation.symm h + +def actualLaw (outer : FiniteDistribution (Outer (n := n) (j := j) (m := m) parameters)) : + FiniteDistribution (PairRecord parameters clauses hupper) := + HierarchicalBucketFamily.actualPairLaw (experiment parameters clauses hupper hij designated σ) outer + (externalLaw parameters clauses hupper hij designated) + (background parameters clauses hupper hij designated) + (scalarLaw parameters clauses hupper hij designated) (upperRows parameters hupper) + +def referenceLaw (outer : FiniteDistribution (Outer (n := n) (j := j) (m := m) parameters)) : + FiniteDistribution (PairRecord parameters clauses hupper) := + HierarchicalBucketFamily.referencePairLaw (experiment parameters clauses hupper hij designated σ) outer + (HierarchicalBucketFamily.actualBackgrounds (experiment parameters clauses hupper hij designated σ) + (externalLaw parameters clauses hupper hij designated) + (background parameters clauses hupper hij designated)) (upperRows parameters hupper) + +theorem totalVariation_le_six (hroot : n ≤ parameters.plan.depth) + (outer : FiniteDistribution (Outer (n := n) (j := j) (m := m) parameters)) : + (actualLaw parameters clauses hupper hij designated σ outer).totalVariation + (referenceLaw parameters clauses hupper hij designated σ outer) ≤ 6 * parameters.accuracy := by + exact sigma_variation_le_const + (R := PairFiber parameters clauses hupper) outer + (fun o => HierarchicalAdviceFromBuckets.pairedLaw + (experiment parameters clauses hupper hij designated σ o) + (externalLaw parameters clauses hupper hij designated o) + (background parameters clauses hupper hij designated o) + (scalarLaw parameters clauses hupper hij designated o) (upperRows parameters hupper o)) + (fun o => HierarchicalAgreementMean.referenceLaw + (StoppedProjectedExperiment.nativeSlots clauses o) (StoppedProjectedExperiment.upper hupper o) + ((externalLaw parameters clauses hupper hij designated o).pushforward + (background parameters clauses hupper hij designated o)) (upperRows parameters hupper o)) + (6 * parameters.accuracy) + (fun o => (fiber_lt_six parameters clauses hupper hij designated σ hroot o).le) + +theorem totalVariation_le_ten (hroot : n ≤ parameters.plan.depth) + (outer : FiniteDistribution (Outer (n := n) (j := j) (m := m) parameters)) : + (actualLaw parameters clauses hupper hij designated σ outer).totalVariation + (referenceLaw parameters clauses hupper hij designated σ outer) ≤ 10 * parameters.accuracy := by + have h := totalVariation_le_six parameters clauses hupper hij designated σ hroot outer + have hpositive := parameters.accuracy_pos + linarith + +end +end PerfectCompleteness.FixedSourcePairVariation + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/FixedStoppedPhysicalLawLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/FixedStoppedPhysicalLawLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..8fb8de956e437ac24b65924598bee4c550f594b7 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/FixedStoppedPhysicalLawLemmas.lean @@ -0,0 +1,319 @@ +import OAI.Computability.PerfectCompleteness.Decoding.FixedStoppedDecoderContext +import OAI.Computability.PerfectCompleteness.Foundations.SourcePhysicalSourceSwapLemmas +import OAI.Computability.PerfectCompleteness.Foundations.StoppedPhysicalPrefixSwap + +namespace OAI + +section + +namespace PerfectCompleteness.FixedStoppedPhysicalLaw + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) +attribute [local instance] linearMapFintype +attribute [local instance] StoppedProjectedPhysicalAdvice.adviceFintype + StoppedProjectedPhysicalAdvice.physicalAdviceFintype + +variable {δ : ℚ} {hδ : 0 < δ} (parameters : FixedParameters.Parameters δ hδ) + (i j : Fin parameters.plan.depth) (hij : i < j) (input : List Bool) + +abbrev clauses := PCPSource.clauseFamily (BinaryLanguage.totalRename input) + +def designated : Fin (FixedParameters.branch parameters i.val) → + Slots (FixedParameters.branch parameters) i.val := + fun _ => StoppedCleanGeometry.firstLeaf (FixedParameters.branch_pos parameters) i.val + +def flag : Fin (FixedParameters.branch parameters i.val) → FiniteDistribution Bool := + fun _ => ProjectedCleanRate.projectionFlag (parameters.cubeSize i.val) + (FixedDecoderCleanRate.cubePositive parameters i.val) + +abbrev Prefixes := FixedStoppedDecoderContext.Prefixes parameters i j +abbrev Context := FixedStoppedDecoderContext.Context parameters i j hij input + +def path (pref : Prefixes parameters i j) := + (FixedStoppedDecoderContext.upperPath parameters i j pref).append + (FixedStoppedDecoderContext.lowerPath parameters i j hij pref) + +abbrev ChildSample (pref : Prefixes parameters i j) := + SourceChildKernel.Sample + (C := WholeCutCalls.Index (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (path parameters i j hij pref)) + (t := FixedRows.sourceLength parameters.plan hδ) + (FixedRows.rows parameters.plan) (clauses input) (designated parameters i) + +abbrev Sample := (context : Context parameters i j hij input) × + ChildSample parameters i j hij input context.1 + +abbrev PhysicalSample := StoppedProjectedPhysicalAdvice.Sample + (t := FixedRows.sourceLength parameters.plan hδ) + (clauses input) (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij (designated parameters i) parameters.plan.order + +def childLaw (pref : Prefixes parameters i j) : + FiniteDistribution (ChildSample parameters i j hij input pref) := + SourceChildKernel.originalLaw + (C := WholeCutCalls.Index (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (path parameters i j hij pref)) + (t := FixedRows.sourceLength parameters.plan hδ) + (FixedRows.rows parameters.plan) (clauses input) (designated parameters i) (flag parameters i) + +def law : FiniteDistribution (Sample parameters i j hij input) := + CompletionSoundness.sigmaLaw (FixedStoppedDecoderContext.law parameters i j hij input) + (fun context => childLaw parameters i j hij input context.1) + +def read (sample : Sample parameters i j hij input) : + PhysicalSample parameters i j hij input := + let context := sample.1 + let inside := SourceQuestionRawSwap.insideQuestions (FixedRows.rows parameters.plan) + (clauses input) (designated parameters i) sample.2 + let questions := SourceQuestionCutSplit.join (path parameters i j hij context.1) + inside context.2.1 + let positions := SourceQuestionRawSwap.positions (FixedRows.rows parameters.plan) + (clauses input) (designated parameters i) sample.2 + let exterior := SourcePhysicalSourceSwap.joinedExterior (clauses input) + (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (path parameters i j hij context.1) inside context.2.1 context.2.2.2.2 + let raw := SourceQuestionRawSwap.raw (FixedRows.rows parameters.plan) + (clauses input) (designated parameters i) sample.2 + ⟨(questions, context.1.1), + (⟨(context.1.2, (positions, context.2.2.2.1)), (exterior, raw)⟩, context.2.2.1)⟩ + +abbrev physicalLaw := StoppedProjectedPhysicalAdvice.law + (t := FixedRows.sourceLength parameters.plan hδ) + (clauses input) (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij (designated parameters i) + (fun k _ => FixedParameters.branch_pos parameters k) + (fun k => parameters.plan.rows_pos (parameters.plan.depth - (k + 1))) + (flag parameters i) parameters.plan.order + +theorem expectation_read (value : PhysicalSample parameters i j hij input → ℝ) : + (physicalLaw parameters i j hij input).expectation value = + (law parameters i j hij input).expectation + (fun sample => value (read parameters i j hij input sample)) := by + refine (StoppedPhysicalPrefixSwap.expectation_prefixes + (t := FixedRows.sourceLength parameters.plan hδ) + (clauses input) (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij (designated parameters i) + (fun k _ => FixedParameters.branch_pos parameters k) + (fun k => parameters.plan.rows_pos (parameters.plan.depth - (k + 1))) + (flag parameters i) parameters.plan.order value).trans ?_ + simp only [law, FixedStoppedDecoderContext.law, CandidateCoupling.expectation_sigmaLaw, + FixedStoppedDecoderContext.fiberLaw] + apply FiniteDistribution.expectation_congr + intro pref + simp only [FiniteDistribution.expectation_product] + let questionLaw := PreliminarySampler.questionsLaw + (branch := FixedParameters.branch parameters) (n := parameters.plan.depth) + (t := FixedRows.sourceLength parameters.plan hδ) + (m := (PCPSource.normalizedFormula (BinaryLanguage.totalRename input)).clauses.length) + let adviceLaw := FiniteDistribution.uniform (FixedStoppedDecoderContext.Advice parameters i j pref) + let directionsLaw := FixedStoppedDecoderContext.directionLaw parameters + let outsideLaw := FiniteDistribution.uniform + (FixedStoppedDecoderContext.OutsideQuestions parameters i j hij input pref) + let statistic := fun + (questions : PreliminarySampler.Questions (FixedParameters.branch parameters) + parameters.plan.depth (FixedRows.sourceLength parameters.plan hδ) + (PCPSource.normalizedFormula (BinaryLanguage.totalRename input)).clauses.length) + (A : FixedStoppedDecoderContext.Advice parameters i j pref) + (directions : FixedStoppedDecoderContext.Directions parameters) => + (SourceProjectedTag.positionLaw (branch := FixedParameters.branch parameters) + (n := i.val) (t := FixedRows.sourceLength parameters.plan hδ)).expectation + (fun positions => (StoppedProjectedExperiment.physicalFiberLaw + (clauses input) (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (Nat.succ_le_of_lt j.isLt) hij (designated parameters i) (flag parameters i) + (questions, pref.1) (pref.2, (positions, directions))).expectation + (fun raw => value ⟨(questions, pref.1), (⟨(pref.2, (positions, directions)), raw⟩, A)⟩)) + let rebuilt := fun (external : FixedStoppedDecoderContext.OutsideQuestions parameters i j hij input pref) + (A : FixedStoppedDecoderContext.Advice parameters i j pref) + (directions : FixedStoppedDecoderContext.Directions parameters) => + (FiniteDistribution.uniform + (FixedStoppedDecoderContext.Exterior parameters i j hij input pref external)).expectation + (fun exterior => (childLaw parameters i j hij input pref).expectation + (fun sample => value (read parameters i j hij input + ⟨⟨pref, external, A, directions, exterior⟩, sample⟩))) + change questionLaw.expectation (fun questions => adviceLaw.expectation (fun A => + directionsLaw.expectation (fun directions => statistic questions A directions))) = + outsideLaw.expectation (fun external => adviceLaw.expectation (fun A => + directionsLaw.expectation (fun directions => rebuilt external A directions))) + calc + _ = adviceLaw.expectation (fun A => directionsLaw.expectation (fun directions => + questionLaw.expectation (fun questions => statistic questions A directions))) := by + rw [FiniteDistribution.expectation_comm] + apply FiniteDistribution.expectation_congr + intro A + exact FiniteDistribution.expectation_comm _ _ _ + _ = adviceLaw.expectation (fun A => directionsLaw.expectation (fun directions => + outsideLaw.expectation (fun external => rebuilt external A directions))) := by + apply FiniteDistribution.expectation_congr + intro A + apply FiniteDistribution.expectation_congr + intro directions + exact SourcePhysicalSourceSwap.expectation_swap (clauses input) + (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (path parameters i j hij pref) (designated parameters i) (flag parameters i) + (fun questions positions exterior raw => + value ⟨(questions, pref.1), (⟨(pref.2, (positions, directions)), (exterior, raw)⟩, A)⟩) + _ = _ := by + calc + _ = adviceLaw.expectation (fun A => outsideLaw.expectation (fun external => + directionsLaw.expectation (fun directions => rebuilt external A directions))) := by + apply FiniteDistribution.expectation_congr + intro A + exact FiniteDistribution.expectation_comm _ _ _ + _ = _ := FiniteDistribution.expectation_comm _ _ _ + +theorem read_law : + (law parameters i j hij input).pushforward (read parameters i j hij input) = + physicalLaw parameters i j hij input := by + apply SigmaObservation.eq_of_probability_eq + intro event + rw [FiniteDistribution.probability_pushforward, + CandidateCoupling.probability_eq_expectation, CandidateCoupling.probability_eq_expectation] + exact (expectation_read parameters i j hij input (fun sample => if event sample then 1 else 0)).symm + +end +end PerfectCompleteness.FixedStoppedPhysicalLaw + +end + +section + +namespace PerfectCompleteness.FixedStoppedNativeLaw + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +attribute [local instance] StoppedProjectedPhysicalAdvice.adviceFintype + StoppedProjectedPhysicalAdvice.physicalAdviceFintype + +section PathTransport + +variable {branch : Nat → Nat} {root h t v m : Nat} + (rows repeats : Nat → Nat) (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch h) → Slots branch h) + {p q : Path branch root (h + 1)} + +def sourceSampleEquiv (hp : p = q) : + SourceChildKernel.Sample (C := WholeCutCalls.Index rows repeats p) (t := t) + rows clauses designated ≃ + SourceChildKernel.Sample (C := WholeCutCalls.Index rows repeats q) (t := t) + rows clauses designated := + Equiv.cast (congrArg (fun path : Path branch root (h + 1) => + SourceChildKernel.Sample (C := WholeCutCalls.Index rows repeats path) (t := t) + rows clauses designated) hp) + +theorem sourceSampleEquiv_law [NeZero m] (hp : p = q) + (flag : Fin (branch h) → FiniteDistribution Bool) : + (SourceChildKernel.originalLaw (C := WholeCutCalls.Index rows repeats p) (t := t) + rows clauses designated flag).pushforward + (sourceSampleEquiv rows repeats clauses designated hp) = + SourceChildKernel.originalLaw (C := WholeCutCalls.Index rows repeats q) (t := t) + rows clauses designated flag := by + cases hp + exact FiniteDistribution.pushforward_id _ + +end PathTransport + +variable {δ : ℚ} {hδ : 0 < δ} (parameters : FixedParameters.Parameters δ hδ) + (i j : Fin parameters.plan.depth) (hij : i < j) (input : List Bool) + +local instance contextAdviceFintype + (pref : FixedStoppedDecoderContext.Prefixes parameters i j) : + Fintype (FixedStoppedDecoderContext.Advice parameters i j pref) := + UniqueGamesTheorem.Appendix.RankLevelFilter.linearMapFintype + +abbrev Context := FixedStoppedDecoderContext.Context parameters i j hij input + +abbrev setup (context : Context parameters i j hij input) := + FixedDecoderCleanRate.setup parameters + (FixedStoppedDecoderContext.geometry parameters i j hij input context) input + +abbrev Sample := (context : Context parameters i j hij input) × + CleanDecoderRate.Sample (setup parameters i j hij input context) + +theorem path_eq (context : Context parameters i j hij input) : + CleanDecoderRate.path (setup parameters i j hij input context) = + FixedStoppedPhysicalLaw.path parameters i j hij context.1 := + StoppedCleanGeometry.geometry_path parameters input + (FixedStoppedDecoderContext.upperPath parameters i j context.1) + (FixedStoppedDecoderContext.lowerPath parameters i j hij context.1) hij + context.2.1 context.2.2.2.2 + +def childRead (context : Context parameters i j hij input) : + CleanDecoderRate.Sample (setup parameters i j hij input context) ≃ + FixedStoppedPhysicalLaw.ChildSample parameters i j hij input context.1 := + sourceSampleEquiv (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (FixedStoppedPhysicalLaw.clauses input) (FixedStoppedPhysicalLaw.designated parameters i) + (path_eq parameters i j hij input context) + +theorem childRead_law (context : Context parameters i j hij input) : + (CleanDecoderRate.rawLaw (setup parameters i j hij input context) + (parameters.cubeSize i.val) (FixedDecoderCleanRate.cubePositive parameters i.val)).pushforward + (childRead parameters i j hij input context) = + FixedStoppedPhysicalLaw.childLaw parameters i j hij input context.1 := + sourceSampleEquiv_law (FixedRows.rows parameters.plan) (FixedRows.repeats parameters.plan) + (FixedStoppedPhysicalLaw.clauses input) (FixedStoppedPhysicalLaw.designated parameters i) + (path_eq parameters i j hij input context) (FixedStoppedPhysicalLaw.flag parameters i) + +def law : FiniteDistribution (Sample parameters i j hij input) := + CompletionSoundness.sigmaLaw (FixedStoppedDecoderContext.law parameters i j hij input) + (fun context => CleanDecoderRate.rawLaw (setup parameters i j hij input context) + (parameters.cubeSize i.val) (FixedDecoderCleanRate.cubePositive parameters i.val)) + +def sourceRead (sample : Sample parameters i j hij input) : + FixedStoppedPhysicalLaw.Sample parameters i j hij input := + ⟨sample.1, childRead parameters i j hij input sample.1 sample.2⟩ + +theorem sourceRead_law : + (law parameters i j hij input).pushforward (sourceRead parameters i j hij input) = + FixedStoppedPhysicalLaw.law parameters i j hij input := by + have hsplit := SigmaObservation.pushforward_fiber + (X := fun context : Context parameters i j hij input => + CleanDecoderRate.Sample (setup parameters i j hij input context)) + (Y := fun context : Context parameters i j hij input => + FixedStoppedPhysicalLaw.ChildSample parameters i j hij input context.1) + (FixedStoppedDecoderContext.law parameters i j hij input) + (fun context => CleanDecoderRate.rawLaw (setup parameters i j hij input context) + (parameters.cubeSize i.val) (FixedDecoderCleanRate.cubePositive parameters i.val)) + (fun context => childRead parameters i j hij input context) + exact hsplit.trans (congrArg + (fun P : (context : Context parameters i j hij input) → + FiniteDistribution (FixedStoppedPhysicalLaw.ChildSample parameters i j hij input + context.1) => + CompletionSoundness.sigmaLaw (FixedStoppedDecoderContext.law parameters i j hij input) P) + (funext (fun context => childRead_law parameters i j hij input context))) + +def read (sample : Sample parameters i j hij input) : + FixedStoppedPhysicalLaw.PhysicalSample parameters i j hij input := + FixedStoppedPhysicalLaw.read parameters i j hij input + (sourceRead parameters i j hij input sample) + +theorem read_law : + (law parameters i j hij input).pushforward (read parameters i j hij input) = + FixedStoppedPhysicalLaw.physicalLaw parameters i j hij input := by + change (law parameters i j hij input).pushforward + (fun sample => FixedStoppedPhysicalLaw.read parameters i j hij input + (sourceRead parameters i j hij input sample)) = _ + rw [← FiniteDistribution.pushforward_comp, sourceRead_law] + exact FixedStoppedPhysicalLaw.read_law parameters i j hij input + +theorem expectation_read + (value : FixedStoppedPhysicalLaw.PhysicalSample parameters i j hij input → ℝ) : + (law parameters i j hij input).expectation + (fun sample => value (read parameters i j hij input sample)) = + (FixedStoppedPhysicalLaw.physicalLaw parameters i j hij input).expectation value := by + rw [← read_law parameters i j hij input, FiniteDistribution.expectation_pushforward] + +end +end PerfectCompleteness.FixedStoppedNativeLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/GoodRowSampling.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/GoodRowSampling.lean new file mode 100644 index 0000000000000000000000000000000000000000..04685467641b381a2d87dba839b5412683d07a2c --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/GoodRowSampling.lean @@ -0,0 +1,109 @@ +import OAI.Computability.PerfectCompleteness.Foundations.ManyGoodRowsLemmas +import OAI.Computability.PerfectCompleteness.Foundations.RecursiveSpaceEquivLemmas +import OAI.Computability.PerfectCompleteness.Sampling.CutSamplerReplayTransportLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.GoodRowSampling + +noncomputable section + +open scoped BigOperators Classical +open UniqueGamesTheorem.Fourier.MatrixCharacters (F2) +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) +open PerfectCompleteness.ManyGoodRows + +attribute [local instance] linearMapFintype + +variable {E F Y : Type*} + [AddCommGroup E] [Module F2 E] [AddCommGroup F] [Module F2 F] + [FiniteDimensional F2 E] [FiniteDimensional F2 F] + [Fintype E] [Fintype F] [Fintype Y] + +abbrev RowFiber {r : Nat} (A : RowMap F r) (U : E →ₗ[F2] (Fin r → F2)) := + {X : E →ₗ[F2] F // A.comp X = U} + +def rowFiberEquiv {r : Nat} (A : RowMap F r) (U : E →ₗ[F2] (Fin r → F2)) + (T : E →ₗ[F2] F) (hT : A.comp T = U) : + MatrixSlice.Slice (⊥ : Submodule F2 E) (LinearMap.ker A) T ≃ RowFiber A U where + toFun X := ⟨X.val, (RowAdvice.slice_row_eq ⊥ A T X).trans hT⟩ + invFun X := ⟨X.val, by + apply LinearMap.ext + intro x + have hx : (x : E) = 0 := (Submodule.mem_bot F2).mp x.property + simp [hx], (RowAdvice.comp_eq_iff_ker_quotient A X.val T).mp (X.property.trans hT.symm)⟩ + left_inv X := by apply Subtype.ext; rfl + right_inv X := by apply Subtype.ext; rfl + +omit [FiniteDimensional F2 E] [FiniteDimensional F2 F] [Fintype E] [Fintype F] in +@[simp] theorem rowFiberEquiv_val {r : Nat} (A : RowMap F r) + (U : E →ₗ[F2] (Fin r → F2)) (T : E →ₗ[F2] F) (hT : A.comp T = U) + (X : MatrixSlice.Slice (⊥ : Submodule F2 E) (LinearMap.ker A) T) : + (rowFiberEquiv A U T hT X).val = X.val := rfl + +omit [FiniteDimensional F2 E] [FiniteDimensional F2 F] [Fintype Y] in +theorem witness_rowFiber_nonempty {f : (E →ₗ[F2] F) → Option Y} + {r : Nat} {ρ : ℝ} {A : RowMap F r} {U : E →ₗ[F2] (Fin r → F2)} + (w : Witness f r ρ A U) : Nonempty (RowFiber A U) := + ⟨⟨w.base, w.row_value⟩⟩ + +omit [Fintype Y] in +theorem witness_column_probability {f : (E →ₗ[F2] F) → Option Y} + {r : Nat} {ρ : ℝ} {A : RowMap F r} {U : E →ₗ[F2] (Fin r → F2)} + (w : Witness f r ρ A U) : + letI : Nonempty (RowFiber A U) := witness_rowFiber_nonempty w + 1 / (2 : ℝ) ^ (r * Module.finrank F2 F) ≤ + (FiniteDistribution.uniform (RowFiber A U)).probability + (fun X => decide (X.val.domRestrict w.columnSpace = w.base.domRestrict w.columnSpace)) := by + let : Nonempty (RowFiber A U) := witness_rowFiber_nonempty w + have h := SliceMass.probability_columnConstraint_ge_of_finrank_le + w.columnSpace (LinearMap.ker A) w.base r w.column_count + have he := UniformConditioning.uniform_probability_equiv + (rowFiberEquiv A U w.base w.row_value) + (fun X : RowFiber A U => + decide (X.val.domRestrict w.columnSpace = w.base.domRestrict w.columnSpace)) + apply h.trans_eq + refine Eq.trans ?_ he + congr 1 + funext X + exact decide_eq_decide.mpr Iff.rfl + +omit [FiniteDimensional F2 E] [FiniteDimensional F2 F] [Fintype Y] in +theorem witness_row_probability_pos {f : (E →ₗ[F2] F) → Option Y} + {r : Nat} {ρ : ℝ} {A : RowMap F r} {U : E →ₗ[F2] (Fin r → F2)} + (w : Witness f r ρ A U) : + 0 < (FiniteDistribution.uniform (E →ₗ[F2] F)).probability + (fun X => decide (A.comp X = U)) := by + let : Nonempty (RowFiber A U) := witness_rowFiber_nonempty w + apply lt_of_lt_of_eq + (UniformConditioning.uniform_probability_pos (fun X : E →ₗ[F2] F => A.comp X = U)) + congr 1 + funext X + exact decide_eq_decide.mpr Iff.rfl + +omit [Fintype Y] in +theorem witness_conditional_probability {f : (E →ₗ[F2] F) → Option Y} + {r : Nat} {ρ : ℝ} {A : RowMap F r} {U : E →ₗ[F2] (Fin r → F2)} + (w : Witness f r ρ A U) : + 1 / (2 : ℝ) ^ (r * Module.finrank F2 F) ≤ + ((FiniteDistribution.uniform (E →ₗ[F2] F)).condition + (fun X => decide (A.comp X = U)) (witness_row_probability_pos w)).probability + (fun X => decide (X.domRestrict w.columnSpace = w.base.domRestrict w.columnSpace)) := by + let : Nonempty (RowFiber A U) := witness_rowFiber_nonempty w + have hevent : (fun X : E →ₗ[F2] F => decide (A.comp X = U)) = + (fun X : E →ₗ[F2] F => @decide (A.comp X = U) (Classical.propDecidable _)) := by + funext X + exact decide_eq_decide.mpr Iff.rfl + simp only [hevent, UniformConditioning.probability_condition_uniform] + convert witness_column_probability w using 1 + congr! + +end +end PerfectCompleteness.GoodRowSampling + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/HierarchicalArrayLaw.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/HierarchicalArrayLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..047add85ea39d4ea1ddd018fd08aa0f12369971f --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/HierarchicalArrayLaw.lean @@ -0,0 +1,153 @@ +import OAI.Computability.PerfectCompleteness.Algebra.HierarchicalMatrixTable +import OAI.Computability.PerfectCompleteness.Foundations.QuarterBalanceLemmas +import OAI.Computability.PerfectCompleteness.Sampling.BucketUniformLemmas +import OAI.Computability.PerfectCompleteness.Sampling.WholeArraySampler + +namespace OAI + +section + +namespace PerfectCompleteness.HierarchicalArrayLaw + +noncomputable section + +open scoped Classical +open TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +variable {branch : Nat → Nat} {n t : Nat} + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (rows : Nat → Nat) + +abbrev NativeRows (node : Nodes branch n) := + Fin (rows (Nodes.height node)) → NodeEmbedding.NodeH slots node + +def law (μ : (node : Nodes branch n) → FiniteDistribution (NativeRows slots rows node)) : + FiniteDistribution (Arrays slots rows) := + FiniteProduct.law μ + +def otherLaw (μ : (node : Nodes branch n) → FiniteDistribution (NativeRows slots rows node)) + (node : Nodes branch n) : + FiniteDistribution (HierarchicalMatrixTable.Background (rows := rows) slots node) := + FiniteProductSplit.otherLaw μ node + +def nativeToMatrix (node : Nodes branch n) (v : NativeRows slots rows node) : + HierarchicalMatrixTable.Matrix (rows := rows) slots node := + EvaluationMatrix.ofRows (NodeEmbedding.RowSpace slots node) + (NodeEmbedding.rowsEquiv slots node (rows (Nodes.height node)) v) + +@[simp] theorem nativeToMatrix_selected (arrays : Arrays slots rows) (node : Nodes branch n) : + nativeToMatrix slots rows node (arrays node) = NodeEmbedding.matrix arrays node := rfl + +private theorem pushforward_id {A : Type*} [Fintype A] (μ : FiniteDistribution A) : + μ.pushforward (fun a => a) = μ := by + apply FiniteDistribution.eq_of_weight_eq + intro a + simp [FiniteDistribution.pushforward] + +theorem matrix_background_law + (μ : (node : Nodes branch n) → FiniteDistribution (NativeRows slots rows node)) + (node : Nodes branch n) + [Fintype (HierarchicalMatrixTable.Matrix (rows := rows) slots node)] : + (law slots rows μ).pushforward (fun arrays => + (NodeEmbedding.matrix arrays node, HierarchicalMatrixTable.backgroundOf slots node arrays)) = + ((μ node).pushforward (nativeToMatrix slots rows node)).product + (otherLaw slots rows μ node) := by + have h := congrArg + (fun ν : FiniteDistribution (NativeRows slots rows node × + HierarchicalMatrixTable.Background (rows := rows) slots node) => + ν.pushforward (fun p => (nativeToMatrix slots rows node p.1, p.2))) + (FiniteProductSplit.split_law μ node) + rw [FiniteDistribution.pushforward_comp] at h + have hp := FiniteDistribution.product_pushforward + (μ node) (FiniteProductSplit.otherLaw μ node) (nativeToMatrix slots rows node) + (id : HierarchicalMatrixTable.Background (rows := rows) slots node → + HierarchicalMatrixTable.Background (rows := rows) slots node) + have hi : (FiniteProductSplit.otherLaw μ node).pushforward + (id : HierarchicalMatrixTable.Background (rows := rows) slots node → + HierarchicalMatrixTable.Background (rows := rows) slots node) = + FiniteProductSplit.otherLaw μ node := pushforward_id (FiniteProductSplit.otherLaw μ node) + rw [hi] at hp + exact h.trans (by simpa only [id_eq, otherLaw] using hp) + +theorem uniform_nativeToMatrix (node : Nodes branch n) + [Fintype (HierarchicalMatrixTable.Matrix (rows := rows) slots node)] : + (FiniteDistribution.uniform (NativeRows slots rows node)).pushforward + (nativeToMatrix slots rows node) = + FiniteDistribution.uniform (HierarchicalMatrixTable.Matrix (rows := rows) slots node) := by + let : Fintype (NodeEmbedding.RowSpace slots node) := Fintype.ofFinite _ + calc + _ = ((FiniteDistribution.uniform (NativeRows slots rows node)).pushforward + (NodeEmbedding.rowsEquiv slots node (rows (Nodes.height node)))).pushforward + (EvaluationMatrix.ofRows (NodeEmbedding.RowSpace slots node)) := + (FiniteDistribution.pushforward_comp _ _ _).symm + _ = (FiniteDistribution.uniform + (Fin (rows (Nodes.height node)) → NodeEmbedding.RowSpace slots node)).pushforward + (EvaluationMatrix.ofRows (NodeEmbedding.RowSpace slots node)) := by + rw [NodeEmbedding.uniform_rowsEquiv] + _ = _ := UniformLinearImage.uniform_pushforward_linearMap + (BucketUniform.ofRowsLinear (NodeEmbedding.RowSpace slots node) (rows (Nodes.height node))) + (BucketUniform.ofRowsLinear_surjective + (NodeEmbedding.RowSpace slots node) (rows (Nodes.height node))) + +theorem uniform_matrix_background_law + (μ : (node : Nodes branch n) → FiniteDistribution (NativeRows slots rows node)) + (node : Nodes branch n) + [Fintype (HierarchicalMatrixTable.Matrix (rows := rows) slots node)] + (hselected : μ node = FiniteDistribution.uniform (NativeRows slots rows node)) : + (law slots rows μ).pushforward (fun arrays => + (NodeEmbedding.matrix arrays node, HierarchicalMatrixTable.backgroundOf slots node arrays)) = + (FiniteDistribution.uniform + (HierarchicalMatrixTable.Matrix (rows := rows) slots node)).product + (otherLaw slots rows μ node) := by + rw [matrix_background_law, hselected, uniform_nativeToMatrix] + +theorem matrix_coarse_background_law + (μ : (node : Nodes branch n) → FiniteDistribution (NativeRows slots rows node)) + (node : Nodes branch n) + [Fintype (HierarchicalMatrixTable.Matrix (rows := rows) slots node)] + {B : Type*} [Fintype B] + (record : HierarchicalMatrixTable.Background (rows := rows) slots node → B) : + (law slots rows μ).pushforward (fun arrays => + (NodeEmbedding.matrix arrays node, record (HierarchicalMatrixTable.backgroundOf slots node arrays))) = + ((μ node).pushforward (nativeToMatrix slots rows node)).product + ((otherLaw slots rows μ node).pushforward record) := by + have h := congrArg + (fun ν : FiniteDistribution + (HierarchicalMatrixTable.Matrix (rows := rows) slots node × + HierarchicalMatrixTable.Background (rows := rows) slots node) => + ν.pushforward (fun p => (p.1, record p.2))) + (matrix_background_law slots rows μ node) + rw [FiniteDistribution.pushforward_comp] at h + have hp := FiniteDistribution.product_pushforward + ((μ node).pushforward (nativeToMatrix slots rows node)) (otherLaw slots rows μ node) + (id : HierarchicalMatrixTable.Matrix (rows := rows) slots node → + HierarchicalMatrixTable.Matrix (rows := rows) slots node) record + have hi : ((μ node).pushforward (nativeToMatrix slots rows node)).pushforward + (id : HierarchicalMatrixTable.Matrix (rows := rows) slots node → + HierarchicalMatrixTable.Matrix (rows := rows) slots node) = + (μ node).pushforward (nativeToMatrix slots rows node) := + pushforward_id ((μ node).pushforward (nativeToMatrix slots rows node)) + rw [hi] at hp + exact h.trans (by simpa only [id_eq] using hp) + +theorem uniform_matrix_coarse_background_law + (μ : (node : Nodes branch n) → FiniteDistribution (NativeRows slots rows node)) + (node : Nodes branch n) + [Fintype (HierarchicalMatrixTable.Matrix (rows := rows) slots node)] + (hselected : μ node = FiniteDistribution.uniform (NativeRows slots rows node)) + {B : Type*} [Fintype B] + (record : HierarchicalMatrixTable.Background (rows := rows) slots node → B) : + (law slots rows μ).pushforward (fun arrays => + (NodeEmbedding.matrix arrays node, record (HierarchicalMatrixTable.backgroundOf slots node arrays))) = + (FiniteDistribution.uniform + (HierarchicalMatrixTable.Matrix (rows := rows) slots node)).product + ((otherLaw slots rows μ node).pushforward record) := by + rw [matrix_coarse_background_law, hselected, uniform_nativeToMatrix] + +end +end PerfectCompleteness.HierarchicalArrayLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/HierarchicalBackgroundVariation.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/HierarchicalBackgroundVariation.lean new file mode 100644 index 0000000000000000000000000000000000000000..40f561d08af7895c01df3d8b2959ae4259689d4c --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/HierarchicalBackgroundVariation.lean @@ -0,0 +1,106 @@ +import OAI.Computability.PerfectCompleteness.Construction.HiddenBucketBias +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalAgreementMean + +namespace OAI + +section + +namespace PerfectCompleteness.HierarchicalBackgroundVariation + +open TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) +open scoped BigOperators Classical + +noncomputable section + +attribute [local instance] linearMapFintype + +private theorem common_right_variation {A B : Type*} [Fintype A] [Fintype B] + (P Q : FiniteDistribution A) (ν : FiniteDistribution B) : + (P.product ν).totalVariation (Q.product ν) = P.totalVariation Q := by + change (∑ z : A × B, + |P.weight z.1 * ν.weight z.2 - Q.weight z.1 * ν.weight z.2|) / 2 = + (∑ a : A, |P.weight a - Q.weight a|) / 2 + rw [Fintype.sum_prod_type] + simp_rw [← sub_mul, abs_mul, abs_of_nonneg (ν.nonnegative _), ← Finset.mul_sum, + ν.normalized, mul_one] + +private theorem variation_triangle {A : Type*} [Fintype A] + (P U Q : FiniteDistribution A) : + P.totalVariation Q ≤ P.totalVariation U + U.totalVariation Q := by + unfold FiniteDistribution.totalVariation + have h := Finset.sum_le_sum (s := Finset.univ) + (fun x _ => abs_sub_le (P.weight x) (U.weight x) (Q.weight x)) + rw [Finset.sum_add_distrib] at h + linarith + +variable {branch rows : Nat → Nat} {n t : Nat} + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (upper : Nodes branch n) + +local instance backgroundFintype : + Fintype (HierarchicalAgreementMean.Background (rows := rows) slots upper) := Fintype.ofFinite _ + +local instance rowSpaceFintype : Fintype (NodeEmbedding.RowSpace slots upper) := Fintype.ofFinite _ + +theorem reference_background + (backgroundLaw : FiniteDistribution (HierarchicalAgreementMean.Background (rows := rows) slots upper)) + (hrows : 0 < rows (Nodes.height upper)) : + (HierarchicalAgreementMean.referenceLaw slots upper backgroundLaw hrows).pushforward Prod.fst = + backgroundLaw := by + unfold HierarchicalAgreementMean.referenceLaw + rw [FiniteDistribution.pushforward_comp] + change (backgroundLaw.product (HierarchicalAgreementMean.bucketLaw slots upper hrows)).pushforward + Prod.fst = backgroundLaw + exact HiddenBucketBias.product_fst _ _ + +theorem reference_variation + (P Q : FiniteDistribution (HierarchicalAgreementMean.Background (rows := rows) slots upper)) + (hrows : 0 < rows (Nodes.height upper)) : + (HierarchicalAgreementMean.referenceLaw slots upper P hrows).totalVariation + (HierarchicalAgreementMean.referenceLaw slots upper Q hrows) ≤ P.totalVariation Q := + (DensityVariation.variation_pushforward_le + (P.product (HierarchicalAgreementMean.bucketLaw slots upper hrows)) + (Q.product (HierarchicalAgreementMean.bucketLaw slots upper hrows)) + (HierarchicalAgreementMean.pairRecord slots upper)).trans_eq + (common_right_variation P Q (HierarchicalAgreementMean.bucketLaw slots upper hrows)) + +theorem original_background_variation + (P : FiniteDistribution (HierarchicalAgreementMean.PairRecord (rows := rows) slots upper)) + (referenceBackground : FiniteDistribution + (HierarchicalAgreementMean.Background (rows := rows) slots upper)) + (hrows : 0 < rows (Nodes.height upper)) : + P.totalVariation + (HierarchicalAgreementMean.referenceLaw slots upper (P.pushforward Prod.fst) hrows) ≤ + 2 * P.totalVariation + (HierarchicalAgreementMean.referenceLaw slots upper referenceBackground hrows) := by + have hmarginal := DensityVariation.variation_pushforward_le P + (HierarchicalAgreementMean.referenceLaw slots upper referenceBackground hrows) Prod.fst + rw [reference_background] at hmarginal + have href := reference_variation slots upper (P.pushforward Prod.fst) referenceBackground hrows + rw [FiniteDistribution.totalVariation_comm] at href + have htriangle := variation_triangle P + (HierarchicalAgreementMean.referenceLaw slots upper referenceBackground hrows) + (HierarchicalAgreementMean.referenceLaw slots upper (P.pushforward Prod.fst) hrows) + linarith + +theorem original_background_le_of_bound + (P : FiniteDistribution (HierarchicalAgreementMean.PairRecord (rows := rows) slots upper)) + (referenceBackground : FiniteDistribution + (HierarchicalAgreementMean.Background (rows := rows) slots upper)) + (hrows : 0 < rows (Nodes.height upper)) {error : ℝ} + (herror : P.totalVariation + (HierarchicalAgreementMean.referenceLaw slots upper referenceBackground hrows) ≤ error) : + P.totalVariation + (HierarchicalAgreementMean.referenceLaw slots upper (P.pushforward Prod.fst) hrows) ≤ + 2 * error := by + have h := original_background_variation slots upper P referenceBackground hrows + linarith + +end +end PerfectCompleteness.HierarchicalBackgroundVariation + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/MetadataFreeLaw.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/MetadataFreeLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..36ecbb48d9f3a023ddfd86de5ea0b75cb81335d6 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/MetadataFreeLaw.lean @@ -0,0 +1,166 @@ +import OAI.Computability.PerfectCompleteness.Machines.MetadataFreeTapeLemmas +import OAI.Computability.PerfectCompleteness.Sampling.SamplerCardinalityLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.MetadataFreeLaw + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces +open MetadataFreeSampler MetadataFreeTape +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +noncomputable section + +variable {branch : Nat → Nat} {n d t v m : Nat} + +theorem tape_weight_eq (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (p : Path branch n d) : + ∀ (q : PreliminarySampler.Questions branch n t m) + (ω : WholeArraySampler.Tape rows repeats p (sourceSlots clauses q)), + (WholeArraySampler.tapeLaw rows repeats p (sourceSlots clauses q)).weight ω = + (WholeArraySampler.tapeLaw rows repeats p (dummyTreeSlots (sourceSigns clauses q))).weight + (tapeEquiv clauses rows repeats p q ω) := by + induction p with + | refl n => + intro q ω + rfl + | @step n d i p ih => + intro q ω + change (∏ k : WholeArraySampler.StepIndex i, + (WholeArraySampler.componentLaw rows repeats i p (sourceSlots clauses q) k).weight (ω k)) = + ∏ k : WholeArraySampler.StepIndex i, + (WholeArraySampler.componentLaw rows repeats i p + (dummyTreeSlots (sourceSigns clauses q)) k).weight + (tapeEquiv clauses rows repeats (.step i p) q ω k) + apply Finset.prod_congr rfl + intro k _ + rcases k with u | (u | j) + · rfl + · cases u + exact ih (fun leaf k => q (i, leaf) k) (ω (.inr (.inl ()))) + · rfl + +theorem tapeLaw_transport (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (p : Path branch n d) + (q : PreliminarySampler.Questions branch n t m) : + (WholeArraySampler.tapeLaw rows repeats p (sourceSlots clauses q)).transport + (tapeEquiv clauses rows repeats p q) = + WholeArraySampler.tapeLaw rows repeats p (dummyTreeSlots (sourceSigns clauses q)) := by + apply FiniteDistribution.eq_of_weight_eq + intro ω + change (WholeArraySampler.tapeLaw rows repeats p (sourceSlots clauses q)).weight + ((tapeEquiv clauses rows repeats p q).symm ω) = _ + simpa only [Equiv.apply_symm_apply] using + tape_weight_eq clauses rows repeats p q ((tapeEquiv clauses rows repeats p q).symm ω) + +abbrev SignedOutcome (signs : SignTuple branch n t) (rows repeats : Nat → Nat) := + Σ leaf : Slots branch n, + WholeArraySampler.Tape rows repeats (GeometricPath.leafPath leaf) (dummyTreeSlots signs) × + PreliminarySampler.Choice rows leaf + +def signedLaw (signs : SignTuple branch n t) (rows repeats : Nat → Nat) + (hn : 0 < n) (hbranch : ∀ k < n, 0 < branch k) + (hrows : ∀ k, 0 < rows (k + 1)) : FiniteDistribution (SignedOutcome signs rows repeats) := + CompletionSoundness.sigmaLaw (GeometricPath.law n hbranch) fun leaf => + (WholeArraySampler.tapeLaw rows repeats (GeometricPath.leafPath leaf) (dummyTreeSlots signs)).product + (PreliminarySampler.choiceLaw leaf hn hrows) + +def signedRationalLaw (signs : SignTuple branch n t) (rows repeats : Nat → Nat) + (hn : 0 < n) (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) : + RationalFiniteLaw.RationalLaw (signedLaw signs rows repeats hn hbranch hrows) := + RationalFiniteLaw.sigma (SamplerRationality.pathLaw hbranch) fun leaf => + RationalFiniteLaw.product + (SamplerRationality.wholeArrayTapeLaw rows repeats (GeometricPath.leafPath leaf) + (dummyTreeSlots signs)) + (SamplerRationality.choiceLaw leaf hn hrows) + +theorem signedLaw_positive (signs : SignTuple branch n t) (rows repeats : Nat → Nat) + (hn : 0 < n) (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) + (e : SignedOutcome signs rows repeats) : + 0 < (signedLaw signs rows repeats hn hbranch hrows).weight e := + RationalFiniteLaw.real_positive (signedRationalLaw signs rows repeats hn hbranch hrows) e + +def encodeOutcome (clauses : Fin m → SourceClause.NormalizedClause v) (rows repeats : Nat → Nat) + (e : PreliminarySampler.Raw clauses branch n t rows repeats) : + SignedOutcome (sourceSigns clauses e.1.1) rows repeats := + ⟨e.1.2, tapeEquiv clauses rows repeats (GeometricPath.leafPath e.1.2) e.1.1 e.2.1, e.2.2⟩ + +theorem raw_weight_eq [NeZero m] (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hn : 0 < n) + (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) + (e : PreliminarySampler.Raw clauses branch n t rows repeats) : + (PreliminarySampler.law clauses rows repeats hn hbranch hrows).weight e = + (1 / (Fintype.card (PreliminarySampler.Questions branch n t m) : ℝ)) * + (signedLaw (sourceSigns clauses e.1.1) rows repeats hn hbranch hrows).weight + (encodeOutcome clauses rows repeats e) := by + change ((1 / (Fintype.card (PreliminarySampler.Questions branch n t m) : ℝ)) * + (GeometricPath.law n hbranch).weight e.1.2) * + ((WholeArraySampler.tapeLaw rows repeats (GeometricPath.leafPath e.1.2) + (sourceSlots clauses e.1.1)).weight e.2.1 * + (PreliminarySampler.choiceLaw e.1.2 hn hrows).weight e.2.2) = + (1 / (Fintype.card (PreliminarySampler.Questions branch n t m) : ℝ)) * + ((GeometricPath.law n hbranch).weight e.1.2 * + ((WholeArraySampler.tapeLaw rows repeats (GeometricPath.leafPath e.1.2) + (dummyTreeSlots (sourceSigns clauses e.1.1))).weight + (tapeEquiv clauses rows repeats (GeometricPath.leafPath e.1.2) e.1.1 e.2.1) * + (PreliminarySampler.choiceLaw e.1.2 hn hrows).weight e.2.2)) + rw [tape_weight_eq clauses rows repeats (GeometricPath.leafPath e.1.2) e.1.1 e.2.1] + exact mul_assoc _ _ _ + +theorem raw_weight_rational [NeZero m] (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hn : 0 < n) + (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) + (e : PreliminarySampler.Raw clauses branch n t rows repeats) : + (PreliminarySampler.law clauses rows repeats hn hbranch hrows).weight e = + (1 / (Fintype.card (PreliminarySampler.Questions branch n t m) : ℝ)) * + ((signedRationalLaw (sourceSigns clauses e.1.1) rows repeats hn hbranch hrows).weights + (encodeOutcome clauses rows repeats e) : ℝ) := by + rw [raw_weight_eq, (signedRationalLaw (sourceSigns clauses e.1.1) + rows repeats hn hbranch hrows).cast_weight] + +def rawEquiv (clauses : Fin m → SourceClause.NormalizedClause v) (rows repeats : Nat → Nat) : + PreliminarySampler.Raw clauses branch n t rows repeats ≃ + (Σ q : PreliminarySampler.Questions branch n t m, + SignedOutcome (sourceSigns clauses q) rows repeats) where + toFun e := ⟨e.1.1, encodeOutcome clauses rows repeats e⟩ + invFun y := ⟨(y.1, y.2.1), + (tapeEquiv clauses rows repeats (GeometricPath.leafPath y.2.1) y.1).symm y.2.2.1, + y.2.2.2⟩ + left_inv := by + rintro ⟨⟨q, leaf⟩, ω, choice⟩ + simp only [encodeOutcome] + exact congrArg + (fun tape : WholeArraySampler.Tape rows repeats (GeometricPath.leafPath leaf) + (sourceSlots clauses q) => + (⟨(q, leaf), tape, choice⟩ : PreliminarySampler.Raw clauses branch n t rows repeats)) + ((tapeEquiv clauses rows repeats (GeometricPath.leafPath leaf) q).symm_apply_apply ω) + right_inv := by + rintro ⟨q, leaf, ω, choice⟩ + simp only [encodeOutcome, Equiv.apply_symm_apply] + +theorem rawLaw_transport [NeZero m] (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hn : 0 < n) + (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) : + (PreliminarySampler.law (t := t) clauses rows repeats hn hbranch hrows).transport + (rawEquiv clauses rows repeats) = + CompletionSoundness.sigmaLaw PreliminarySampler.questionsLaw + (fun q => signedLaw (sourceSigns clauses q) rows repeats hn hbranch hrows) := by + apply FiniteDistribution.eq_of_weight_eq + rintro ⟨q, leaf, ω, choice⟩ + change (PreliminarySampler.law clauses rows repeats hn hbranch hrows).weight + ⟨(q, leaf), (tapeEquiv clauses rows repeats (GeometricPath.leafPath leaf) q).symm ω, + choice⟩ = + (1 / (Fintype.card (PreliminarySampler.Questions branch n t m) : ℝ)) * + (signedLaw (sourceSigns clauses q) rows repeats hn hbranch hrows).weight ⟨leaf, ω, choice⟩ + rw [raw_weight_eq] + simp only [encodeOutcome, Equiv.apply_symm_apply] + +end +end PerfectCompleteness.MetadataFreeLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/MetadataFreeSampler.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/MetadataFreeSampler.lean new file mode 100644 index 0000000000000000000000000000000000000000..2a9df3b1f02d1e8cee9b58d7bffba96568bb9c5c --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/MetadataFreeSampler.lean @@ -0,0 +1,225 @@ +import OAI.Computability.PerfectCompleteness.Foundations.CanonicalEdgesLemmas +import OAI.Computability.PerfectCompleteness.Foundations.KeyFiniteness +import OAI.Computability.PerfectCompleteness.Foundations.QuotientTableAgreementLemmas +import OAI.Computability.PerfectCompleteness.Sampling.PreliminarySampler + +namespace OAI + + +namespace PerfectCompleteness.MetadataFreeSampler + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open scoped Classical + +noncomputable section + +abbrev SignTuple (branch : Nat → Nat) (n t : Nat) := + Slots branch n → Fin t → SourceClause.Triple + +abbrev EncodedAssignment (branch : Nat → Nat) (n t : Nat) := + Slots branch n → Fin t → Fin 7 + +variable {branch : Nat → Nat} {n t : Nat} + +abbrev SignedLeaf (signs : SignTuple branch n t) (leaf : Slots branch n) := + (k : Fin t) → ClauseSupport.Answer (signs leaf k) + +abbrev SignedDomain (signs : SignTuple branch n t) := Assignment (SignedLeaf signs) + +abbrev SignedH (signs : SignTuple branch n t) : + Submodule F2 (SignedDomain signs → F2) := + space F2 branch n (SignedLeaf signs) + +def nodeSigns (signs : SignTuple branch n t) (node : Nodes branch n) : + SignTuple branch (Nodes.height node) t := + fun leaf k => signs ((Nodes.path node).slotEmbedding leaf) k + +abbrev SignedArrays (signs : SignTuple branch n t) (rows : Nat → Nat) := + (node : Nodes branch n) → Fin (rows (Nodes.height node)) → SignedH (nodeSigns signs node) + +def assignmentEquiv (signs : SignTuple branch n t) : + SignedDomain signs ≃ EncodedAssignment branch n t := + Equiv.piCongrRight (fun leaf => Equiv.piCongrRight (fun k => + CanonicalKeys.answerEquivFinSeven (signs leaf k))) + +abbrev ArrayTables (branch : Nat → Nat) (n t : Nat) (rows : Nat → Nat) := + (node : Nodes branch n) → Fin (rows (Nodes.height node)) → + EncodedAssignment branch n t → F2 + +abbrev Input (branch : Nat → Nat) (n t : Nat) (rows : Nat → Nat) := + SignTuple branch n t × ArrayTables branch n t rows + +instance inputFintype (branch : Nat → Nat) (n t : Nat) (rows : Nat → Nat) : + Fintype (Input branch n t rows) := by + unfold Input ArrayTables SignTuple EncodedAssignment + infer_instance + +def tableJoint {rows : Nat → Nat} (tables : ArrayTables branch n t rows) + (x : EncodedAssignment branch n t) : Output branch n rows := + (fun node row => tables node row x, PUnit.unit) + +section Source + +variable {v m : Nat} + +def sourceSigns (clauses : Fin m → SourceClause.NormalizedClause v) + (q : PreliminarySampler.Questions branch n t m) : SignTuple branch n t := + fun leaf k => (clauses (q leaf k)).signs + +abbrev sourceSlots (clauses : Fin m → SourceClause.NormalizedClause v) + (q : PreliminarySampler.Questions branch n t m) := + HierarchicalArrays.sourceSlots clauses (PreliminarySampler.endpoints q) + +theorem sourceLeaf_eq (clauses : Fin m → SourceClause.NormalizedClause v) + (q : PreliminarySampler.Questions branch n t m) : + LeafDomain (sourceSlots clauses q) = SignedLeaf (sourceSigns clauses q) := rfl + +theorem sourceDomain_eq (clauses : Fin m → SourceClause.NormalizedClause v) + (q : PreliminarySampler.Questions branch n t m) : + Domain (sourceSlots clauses q) = SignedDomain (sourceSigns clauses q) := rfl + +theorem sourceH_eq (clauses : Fin m → SourceClause.NormalizedClause v) + (q : PreliminarySampler.Questions branch n t m) : + H (sourceSlots clauses q) = SignedH (sourceSigns clauses q) := rfl + +theorem sourceNodeH_eq (clauses : Fin m → SourceClause.NormalizedClause v) + (q : PreliminarySampler.Questions branch n t m) (node : Nodes branch n) : + H (nodeSlots (sourceSlots clauses q) node) = + SignedH (nodeSigns (sourceSigns clauses q) node) := rfl + +theorem sourceArrays_eq (clauses : Fin m → SourceClause.NormalizedClause v) + (q : PreliminarySampler.Questions branch n t m) (rows : Nat → Nat) : + Arrays (sourceSlots clauses q) rows = SignedArrays (sourceSigns clauses q) rows := rfl + +def sourceAssignmentEquiv (clauses : Fin m → SourceClause.NormalizedClause v) + (q : PreliminarySampler.Questions branch n t m) : + Domain (sourceSlots clauses q) ≃ EncodedAssignment branch n t := + assignmentEquiv (sourceSigns clauses q) + +def numberedAssignmentEquiv (clauses : Fin m → SourceClause.NormalizedClause v) + (q : PreliminarySampler.Questions branch n t m) : + MixedSupport.Assignment (TreeCanonical.numberedSlots (sourceSlots clauses q)) ≃ + EncodedAssignment branch n t := + (TreeCanonical.assignmentEquiv (sourceSlots clauses q)).symm.trans + (sourceAssignmentEquiv clauses q) + +def encodeArrays (clauses : Fin m → SourceClause.NormalizedClause v) + (q : PreliminarySampler.Questions branch n t m) {rows : Nat → Nat} + (arrays : Arrays (sourceSlots clauses q) rows) : ArrayTables branch n t rows := + fun node row x => joint arrays ((sourceAssignmentEquiv clauses q).symm x) node row + +theorem tableJoint_encodeArrays (clauses : Fin m → SourceClause.NormalizedClause v) + (q : PreliminarySampler.Questions branch n t m) {rows : Nat → Nat} + (arrays : Arrays (sourceSlots clauses q) rows) (x : EncodedAssignment branch n t) : + tableJoint (encodeArrays clauses q arrays) x = + fullJoint arrays ((sourceAssignmentEquiv clauses q).symm x) := rfl + +theorem tableJoint_at_assignment (clauses : Fin m → SourceClause.NormalizedClause v) + (q : PreliminarySampler.Questions branch n t m) {rows : Nat → Nat} + (arrays : Arrays (sourceSlots clauses q) rows) (x : Domain (sourceSlots clauses q)) : + tableJoint (encodeArrays clauses q arrays) (sourceAssignmentEquiv clauses q x) = + fullJoint arrays x := by + rw [tableJoint_encodeArrays, Equiv.symm_apply_apply] + +theorem numberedFunction_eq (clauses : Fin m → SourceClause.NormalizedClause v) + (q : PreliminarySampler.Questions branch n t m) {rows : Nat → Nat} + (arrays : Arrays (sourceSlots clauses q) rows) : + TreeCanonical.numberedFunction (sourceSlots clauses q) (fullJoint arrays) = + tableJoint (encodeArrays clauses q arrays) ∘ numberedAssignmentEquiv clauses q := by + funext x + exact (tableJoint_at_assignment clauses q arrays + ((TreeCanonical.assignmentEquiv (sourceSlots clauses q)).symm x)).symm + +def encodeInput (clauses : Fin m → SourceClause.NormalizedClause v) + (q : PreliminarySampler.Questions branch n t m) {rows : Nat → Nat} + (arrays : Arrays (sourceSlots clauses q) rows) : Input branch n t rows := + (sourceSigns clauses q, encodeArrays clauses q arrays) + +def encodeTape (clauses : Fin m → SourceClause.NormalizedClause v) + (q : PreliminarySampler.Questions branch n t m) (rows repeats : Nat → Nat) + {d : Nat} (p : Path branch n d) + (tape : WholeArraySampler.Tape rows repeats p (sourceSlots clauses q)) : + Input branch n t rows := + encodeInput clauses q (WholeArraySampler.evaluate rows repeats p (sourceSlots clauses q) tape) + +theorem numberedFunction_encodeTape (clauses : Fin m → SourceClause.NormalizedClause v) + (q : PreliminarySampler.Questions branch n t m) (rows repeats : Nat → Nat) + {d : Nat} (p : Path branch n d) + (tape : WholeArraySampler.Tape rows repeats p (sourceSlots clauses q)) : + TreeCanonical.numberedFunction (sourceSlots clauses q) + (fullJoint (WholeArraySampler.evaluate rows repeats p (sourceSlots clauses q) tape)) = + tableJoint (encodeTape clauses q rows repeats p tape).2 ∘ numberedAssignmentEquiv clauses q := + numberedFunction_eq clauses q _ + +end Source + +def outputEquiv (branch : Nat → Nat) (n : Nat) (rows : Nat → Nat) : + Output branch n rows ≃ Fin (Fintype.card (Output branch n rows)) := + Fintype.equivFin _ + +def numberedShapes (signs : SignTuple branch n t) : + Fin (TreeCanonical.locationCount branch n t) → CanonicalKeyShape.Shape := + fun j => .clause (signs ((TreeCanonical.numbering branch n t).symm j).1 + ((TreeCanonical.numbering branch n t).symm j).2) + +def dummyTreeSlots (signs : SignTuple branch n t) : + Slots branch n → Fin t → MixedSupport.Slot := + fun leaf k => CanonicalKeyShape.dummy (.clause (signs leaf k)) + +def dummyNumberedEquiv (signs : SignTuple branch n t) : + MixedSupport.Assignment (CanonicalKeyShape.dummySlots (numberedShapes signs)) ≃ + EncodedAssignment branch n t := + (TreeCanonical.assignmentEquiv (dummyTreeSlots signs)).symm.trans (assignmentEquiv signs) + +def shapeInput {rows : Nat → Nat} (data : Input branch n t rows) : + CanonicalKeyShape.Input (TreeCanonical.locationCount branch n t) + (Fintype.card (Output branch n rows)) := + ⟨numberedShapes data.1, + fun x => outputEquiv branch n rows (tableJoint data.2 (dummyNumberedEquiv data.1 x))⟩ + + +variable {v m : Nat} + (clauses : Fin m → SourceClause.NormalizedClause v) + (q : PreliminarySampler.Questions branch n t m) {rows : Nat → Nat} + (arrays : Arrays (sourceSlots clauses q) rows) + +theorem shapeInput_encodeInput : + shapeInput (encodeInput clauses q arrays) = + CanonicalKeyShape.input (TreeCanonical.numberedSlots (sourceSlots clauses q)) + (outputEquiv branch n rows ∘ + TreeCanonical.numberedFunction (sourceSlots clauses q) (fullJoint arrays)) := by + apply Sigma.ext + · rfl + · apply heq_of_eq + funext x + change outputEquiv branch n rows + (fullJoint arrays ((sourceAssignmentEquiv clauses q).symm + (sourceAssignmentEquiv clauses q + ((TreeCanonical.assignmentEquiv (sourceSlots clauses q)).symm x)))) = + outputEquiv branch n rows + (fullJoint arrays ((TreeCanonical.assignmentEquiv (sourceSlots clauses q)).symm x)) + rw [Equiv.symm_apply_apply] + +theorem shapeInput_partition : + CanonicalKeyShape.inputPartition (shapeInput (encodeInput clauses q arrays)) = + CanonicalKeys.partition (TreeCanonical.numberedSlots (sourceSlots clauses q)) + (TreeCanonical.numberedFunction (sourceSlots clauses q) (fullJoint arrays)) := by + rw [shapeInput_encodeInput, CanonicalKeyShape.inputPartition_eq] + apply CanonicalKeys.partition_kernel_invariant + intro x y + exact (outputEquiv branch n rows).injective.eq_iff + +theorem shapeInput_retained : + CanonicalKeyShape.retained (TreeCanonical.numberedSlots (sourceSlots clauses q)) + (CanonicalKeyShape.inputModes (shapeInput (encodeInput clauses q arrays))) = + MixedSupport.retainedKeys (TreeCanonical.numberedSlots (sourceSlots clauses q)) + (TreeCanonical.numberedFunction (sourceSlots clauses q) (fullJoint arrays)) := by + rw [shapeInput_encodeInput, CanonicalKeyShape.inputModes_recover] + apply MixedSupport.retainedKeys_kernel_invariant + intro x y + exact (outputEquiv branch n rows).injective.eq_iff + +end +end PerfectCompleteness.MetadataFreeSampler + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/NumberedUniformCut.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/NumberedUniformCut.lean new file mode 100644 index 0000000000000000000000000000000000000000..d488f878b4fec861d477ed15ab8bf7d6cdc8d18d --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/NumberedUniformCut.lean @@ -0,0 +1,93 @@ +import OAI.Computability.PerfectCompleteness.Foundations.OriginalWholeCutBridge +import OAI.Computability.PerfectCompleteness.Reduction.CompletionSoundness +import OAI.Computability.PerfectCompleteness.Sampling.OriginalUniformCut + +namespace OAI + +section + +namespace PerfectCompleteness.NumberedUniformCut + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCutTape OriginalWholeCut +open UniqueGamesTheorem.Foundations.Games +open scoped Classical + +noncomputable section + +attribute [local instance 2000] OriginalWholeCutLaw.valuesBelowFintype + +private theorem sigma_product_pushforward {E A Γ : Type*} + [Fintype E] [Fintype A] [Fintype Γ] + (μ : FiniteDistribution E) (ν : FiniteDistribution A) (f : E × A → Γ) : + (CompletionSoundness.sigmaLaw μ (fun _ => ν)).pushforward + (fun z => f (z.1, z.2)) = + (μ.product ν).pushforward f := by + apply FiniteDistribution.eq_of_weight_eq + intro z + simp only [FiniteDistribution.pushforward, CompletionSoundness.sigmaLaw, + FiniteDistribution.product, Fintype.sum_sigma, Fintype.sum_prod_type] + +variable {branch : Nat → Nat} {n m t : Nat} + +def numberRecordEquiv (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Record rows repeats p slots ≃ OriginalWholeCutBridge.NumberedRecord rows repeats p slots := + Equiv.prodCongr (Equiv.refl (Exterior rows repeats p slots)) + ((Equiv.prodCongr + (Equiv.arrowCongr (callNumbering rows repeats p) (Equiv.refl (H (cutSlots p slots)))) + (Equiv.refl (BelowArrays rows p slots))).trans + (OriginalWholeCutBridge.assembledEquiv + (OriginalCutCalls.count rows repeats n (m + 1)) rows (cutSlots p slots))) + +@[simp] theorem numberRecordEquiv_apply (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : Record rows repeats p slots) : + numberRecordEquiv rows repeats p slots record = + OriginalWholeCutBridge.numberRecord rows repeats p slots record := rfl + +theorem reference_numberRecord_law (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) : + (OriginalUniformCut.referenceLaw rows repeats p slots).pushforward + (OriginalWholeCutBridge.numberRecord rows repeats p slots) = + (exteriorLaw rows repeats p slots).product + (FiniteDistribution.uniform (CutChildGrouping.Assembled + (C := Fin (OriginalCutCalls.count rows repeats n (m + 1))) (cutSlots p slots) rows)) := by + rw [OriginalUniformCut.referenceLaw_uniform] + change (FiniteDistribution.uniform (Record rows repeats p slots)).pushforward + (numberRecordEquiv rows repeats p slots) = _ + rw [← FiniteDistribution.transport_eq_pushforward, UniformConditioning.uniform_transport] + exact WholeCutSampler.uniform_product.symm + +theorem reconstruct_product_uniform (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) : + ((exteriorLaw rows repeats p slots).product + (FiniteDistribution.uniform (CutChildGrouping.Assembled + (C := Fin (OriginalCutCalls.count rows repeats n (m + 1))) (cutSlots p slots) rows))).pushforward + (OriginalWholeCutBridge.reconstruct rows repeats p slots) = + WholeArraySampler.law rows repeats p slots := by + rw [← reference_numberRecord_law rows repeats p slots, FiniteDistribution.pushforward_comp] + have hmap : (fun record : Record rows repeats p slots => + OriginalWholeCutBridge.reconstruct rows repeats p slots + (OriginalWholeCutBridge.numberRecord rows repeats p slots record)) = + reconstructRecord rows repeats p slots := + funext (OriginalWholeCutBridge.reconstruct_numberRecord rows repeats p slots) + rw [hmap] + exact OriginalUniformCut.reconstruct_referenceLaw rows repeats p slots + +theorem reconstruct_sigma_uniform (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) : + (CompletionSoundness.sigmaLaw (exteriorLaw rows repeats p slots) (fun _ => + FiniteDistribution.uniform (CutChildGrouping.Assembled + (C := Fin (OriginalCutCalls.count rows repeats n (m + 1))) (cutSlots p slots) rows))).pushforward + (fun z => OriginalWholeCutBridge.reconstruct rows repeats p slots (z.1, z.2)) = + WholeArraySampler.law rows repeats p slots := by + rw [sigma_product_pushforward] + exact reconstruct_product_uniform rows repeats p slots + +end +end PerfectCompleteness.NumberedUniformCut + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/OriginalCutBucketLaw.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/OriginalCutBucketLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..928a26837a05e5d0d608e3924107e3078daa75ad --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/OriginalCutBucketLaw.lean @@ -0,0 +1,214 @@ +import OAI.Computability.PerfectCompleteness.Construction.OriginalOwnBucketSplit +import OAI.Computability.PerfectCompleteness.Decoding.OriginalCutCollision + +namespace OAI + +section + +namespace PerfectCompleteness.OriginalCutBucketLaw + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCutTape +open UniqueGamesTheorem.Foundations.Games +open scoped Classical + +noncomputable section + +attribute [local instance 2000] OriginalWholeCutLaw.valuesBelowFintype + +section Regrouping + +private def reorder (D U B F : Type*) : + D × ((U × B) × F) ≃ B × (D × (U × F)) where + toFun z := (z.2.1.2, (z.1, (z.2.1.1, z.2.2))) + invFun z := (z.2.1, ((z.2.2.1, z.1), z.2.2.2)) + left_inv _ := rfl + right_inv _ := rfl + +private theorem reorder_law {D U B F : Type*} + [Fintype D] [Fintype U] [Fintype B] [Fintype F] + (directions : FiniteDistribution D) (own : FiniteDistribution U) + (background : FiniteDistribution B) (fresh : FiniteDistribution F) : + (directions.product ((own.product background).product fresh)).pushforward (reorder D U B F) = + background.product (directions.product (own.product fresh)) := by + rw [← FiniteDistribution.transport_eq_pushforward] + apply FiniteDistribution.eq_of_weight_eq + intro z + change directions.weight z.2.1 * + ((own.weight z.2.2.1 * background.weight z.1) * fresh.weight z.2.2.2) = + background.weight z.1 * + (directions.weight z.2.1 * (own.weight z.2.2.1 * fresh.weight z.2.2.2)) + ring + +private theorem map_middle {D R S F : Type*} + [Fintype D] [Fintype R] [Fintype S] [Fintype F] + (directions : FiniteDistribution D) (records : FiniteDistribution R) + (fresh : FiniteDistribution F) (read : R → S) : + (directions.product (records.product fresh)).pushforward + (fun z => (z.1, (read z.2.1, z.2.2))) = + directions.product ((records.pushforward read).product fresh) := by + have hinner : (records.product fresh).pushforward (fun z => (read z.1, z.2)) = + (records.pushforward read).product fresh := by + simpa only [id_eq, FiniteDistribution.pushforward_id] using + FiniteDistribution.product_pushforward records fresh read (id : F → F) + calc + _ = (directions.pushforward id).product + ((records.product fresh).pushforward (fun z => (read z.1, z.2))) := + FiniteDistribution.product_pushforward directions (records.product fresh) id + (fun z => (read z.1, z.2)) + _ = _ := by rw [FiniteDistribution.pushforward_id, hinner] + +private theorem read_product_of_split {D R U B F : Type*} + [Fintype D] [Fintype R] [Fintype U] [Fintype B] [Fintype F] + (directions : FiniteDistribution D) (records : FiniteDistribution R) + (fresh : FiniteDistribution F) (own : FiniteDistribution U) + (background : FiniteDistribution B) (split : R → U × B) + (hsplit : records.pushforward split = own.product background) : + (directions.product (records.product fresh)).pushforward + (fun z => ((split z.2.1).2, (z.1, ((split z.2.1).1, z.2.2)))) = + background.product (directions.product (own.product fresh)) := by + calc + _ = ((directions.product (records.product fresh)).pushforward + (fun z => (z.1, (split z.2.1, z.2.2)))).pushforward (reorder D U B F) := + (FiniteDistribution.pushforward_comp _ _ _).symm + _ = (directions.product ((own.product background).product fresh)).pushforward + (reorder D U B F) := by + rw [map_middle, hsplit] + _ = _ := reorder_law directions own background fresh + +end Regrouping + +variable {branch : Nat → Nat} {n m k t : Nat} + +abbrev Background (rows : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) := + HierarchicalMatrixTable.Background (rows := rows) slots (WholeArrayInteriorExterior.upperNode p) + +local instance backgroundFintype (rows : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Fintype (Background rows p slots) := Fintype.ofFinite _ + +abbrev NativeSample (rows : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) := + Background rows p slots × + (BucketSampler.Direction (rows (m + 1)) × + (OriginalOwnBucketSplit.BucketTape rows p slots × H (cutSlots p slots))) + +def read (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (sample : BucketSampler.Direction (rows (m + 1)) × + OriginalExtraCutComparison.Record rows repeats p slots) : NativeSample rows p slots := + (HierarchicalMatrixTable.backgroundOf slots (WholeArrayInteriorExterior.upperNode p) + (OriginalCutCollision.oldArrays rows repeats p slots sample.2), + (sample.1, + (OriginalCutBucketReplacement.ownValues rows repeats p slots + (OriginalCutCollision.oldRecord rows repeats p slots sample.2).2.1, sample.2.2))) + +def recordRead (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : OriginalWholeCut.Record rows repeats p slots) : + OriginalOwnBucketSplit.BucketTape rows p slots × Background rows p slots := + ((OriginalOwnBucketSplit.recordEquiv rows repeats p slots record).1, + HierarchicalMatrixTable.backgroundOf slots (WholeArrayInteriorExterior.upperNode p) + (OriginalWholeCut.reconstructRecord rows repeats p slots record)) + +@[simp] theorem oldRecord_numberRecord (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : OriginalWholeCut.Record rows repeats p slots) (fresh : H (cutSlots p slots)) : + OriginalCutCollision.oldRecord rows repeats p slots + (OriginalWholeCutBridge.numberRecord rows repeats p slots record, fresh) = record := + (NumberedUniformCut.numberRecordEquiv rows repeats p slots).symm_apply_apply record + +theorem read_numberRecord (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (direction : BucketSampler.Direction (rows (m + 1))) + (record : OriginalWholeCut.Record rows repeats p slots) (fresh : H (cutSlots p slots)) : + read rows repeats p slots + (direction, (OriginalWholeCutBridge.numberRecord rows repeats p slots record, fresh)) = + ((recordRead rows repeats p slots record).2, + (direction, ((recordRead rows repeats p slots record).1, fresh))) := by + unfold read OriginalCutCollision.oldArrays + simp only [oldRecord_numberRecord] + apply Prod.ext + · rfl + · apply Prod.ext + · rfl + · apply Prod.ext + · funext a + exact (OriginalOwnBucketSplit.recordEquiv_own rows repeats p slots record a).symm + · rfl + +private theorem numbered_read_of_split (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (directions : FiniteDistribution (BucketSampler.Direction (rows (m + 1)))) + (records : FiniteDistribution (OriginalWholeCut.Record rows repeats p slots)) + (fresh : FiniteDistribution (H (cutSlots p slots))) + (own : FiniteDistribution (OriginalOwnBucketSplit.BucketTape rows p slots)) + (background : FiniteDistribution (Background rows p slots)) + (hsplit : records.pushforward (recordRead rows repeats p slots) = own.product background) : + (directions.product ((records.pushforward + (OriginalWholeCutBridge.numberRecord rows repeats p slots)).product fresh)).pushforward + (read rows repeats p slots) = + background.product (directions.product (own.product fresh)) := by + calc + _ = (directions.product (records.product fresh)).pushforward + (fun z => read rows repeats p slots + (z.1, (OriginalWholeCutBridge.numberRecord rows repeats p slots z.2.1, z.2.2))) := by + rw [← map_middle directions records fresh + (OriginalWholeCutBridge.numberRecord rows repeats p slots), + FiniteDistribution.pushforward_comp] + _ = (directions.product (records.product fresh)).pushforward + (fun z => ((recordRead rows repeats p slots z.2.1).2, + (z.1, ((recordRead rows repeats p slots z.2.1).1, z.2.2)))) := by + apply congrArg (directions.product (records.product fresh)).pushforward + funext z + exact read_numberRecord rows repeats p slots z.1 z.2.1 z.2.2 + _ = _ := read_product_of_split directions records fresh own background + (recordRead rows repeats p slots) hsplit + +theorem reference_read_law (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) (slots : Slots branch n → Fin t → MixedSupport.Slot) + (directions : FiniteDistribution (BucketSampler.Direction (rows (m + 1)))) : + (directions.product (OriginalExtraCutComparison.referenceLaw rows repeats p slots)).pushforward + (read rows repeats p slots) = + (OriginalOwnBucketSplit.backgroundLaw rows repeats p slots).product + (directions.product + ((FiniteDistribution.uniform (OriginalOwnBucketSplit.BucketTape rows p slots)).product + (FiniteDistribution.uniform (H (cutSlots p slots))))) := by + unfold OriginalExtraCutComparison.referenceLaw + rw [OriginalUniformCut.referenceLaw_uniform] + exact numbered_read_of_split rows repeats p slots directions + (FiniteDistribution.uniform (OriginalWholeCut.Record rows repeats p slots)) + (FiniteDistribution.uniform (H (cutSlots p slots))) + (FiniteDistribution.uniform (OriginalOwnBucketSplit.BucketTape rows p slots)) + (OriginalOwnBucketSplit.backgroundLaw rows repeats p slots) + (OriginalOwnBucketSplit.uniform_own_background rows repeats p slots) + +theorem record_fresh_read_law (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) (chosen : Fin (branch m)) (q : Path branch m k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (directions : FiniteDistribution (BucketSampler.Direction (rows (m + 1)))) : + (directions.product + (((OriginalWholeCutLaw.recordLaw rows repeats p chosen q slots).pushforward + (OriginalWholeCutBridge.numberRecord rows repeats p slots)).product + (RecursiveSampler.law F2 repeats (.step chosen q) (LeafDomain (cutSlots p slots))))).pushforward + (read rows repeats p slots) = + (OriginalOwnBucketSplit.actualBackgroundLaw rows repeats p chosen q slots).product + (directions.product + ((BucketSampler.tapeLaw (rows (m + 1)) + (RecursiveSampler.law F2 repeats (.step chosen q) (LeafDomain (cutSlots p slots)))).product + (RecursiveSampler.law F2 repeats (.step chosen q) (LeafDomain (cutSlots p slots))))) := + numbered_read_of_split rows repeats p slots directions + (OriginalWholeCutLaw.recordLaw rows repeats p chosen q slots) + (RecursiveSampler.law F2 repeats (.step chosen q) (LeafDomain (cutSlots p slots))) + (BucketSampler.tapeLaw (rows (m + 1)) + (RecursiveSampler.law F2 repeats (.step chosen q) (LeafDomain (cutSlots p slots)))) + (OriginalOwnBucketSplit.actualBackgroundLaw rows repeats p chosen q slots) + (OriginalOwnBucketSplit.recordLaw_own_background rows repeats p chosen q slots) + +end +end PerfectCompleteness.OriginalCutBucketLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/OriginalCutPairLaw.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/OriginalCutPairLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..cdd7f33c2c047027afb785b9ab38ac29061586d5 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/OriginalCutPairLaw.lean @@ -0,0 +1,169 @@ +import OAI.Computability.PerfectCompleteness.Construction.CutBucketTransportLemmas +import OAI.Computability.PerfectCompleteness.Sampling.OriginalCutBucketLaw + +namespace OAI + +section + +namespace PerfectCompleteness.OriginalCutPairLaw + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCutTape WholeArrayInteriorExterior +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) +open scoped Classical + +noncomputable section + +attribute [local instance] linearMapFintype + +variable {branch : Nat → Nat} {n m k t : Nat} + +local instance backgroundFintype (rows : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Fintype (HierarchicalMatrixTable.Background (rows := rows) slots (upperNode p)) := + Fintype.ofFinite _ + +local instance rowSpaceFintype (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Fintype (NodeEmbedding.RowSpace slots (upperNode p)) := Fintype.ofFinite _ + +theorem matrix_reconstruct (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : OriginalWholeCut.Record rows repeats p slots) : + NodeEmbedding.matrix (OriginalWholeCut.reconstructRecord rows repeats p slots record) + (upperNode p) = + BucketMatrixResampling.assembledMatrix (NodeEmbedding.RowSpace slots (upperNode p)) + (rows (Nodes.height (upperNode p))) + (CutNodeRows.bucketTapeEquiv rows p slots + (OriginalCutBucketReplacement.ownValues rows repeats p slots record.2.1)) := by + rw [← CutNodeRows.matrixOfRows_selectedRows] + change CutNodeRows.matrixOfRows rows p slots + (SelectedArrayReplacement.selectedRows rows p slots + (OriginalWholeCut.reconstruct rows repeats p slots record.1 record.2.1 record.2.2)) = _ + rw [OriginalCutBucketReplacement.selectedRows_reconstruct] + exact CutNodeRows.matrixOfRows_evaluate rows p slots _ + +def transportPair (rows : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (sample : OriginalCutBucketLaw.NativeSample rows p slots) : + OriginalCutCollision.PairRecord rows p slots := + HierarchicalAgreementMean.pairRecord slots (upperNode p) + (sample.1, CutNodeRows.bucketSampleEquiv rows p slots sample.2) + +private theorem transportPair_law (rows : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (μ : FiniteDistribution (HierarchicalMatrixTable.Background (rows := rows) slots (upperNode p))) + (ν : FiniteDistribution (BucketSampler.Direction (rows (m + 1)) × + (BucketSampler.Tape (rows (m + 1)) (H (cutSlots p slots)) × H (cutSlots p slots)))) : + (μ.product ν).pushforward (transportPair rows p slots) = + ((μ.product ν).pushforward + (fun z : OriginalCutBucketLaw.NativeSample rows p slots => + (z.1, CutNodeRows.bucketSampleEquiv rows p slots z.2))).pushforward + (HierarchicalAgreementMean.pairRecord slots (upperNode p)) := by + exact (FiniteDistribution.pushforward_comp (μ.product ν) + (fun z : OriginalCutBucketLaw.NativeSample rows p slots => + (z.1, CutNodeRows.bucketSampleEquiv rows p slots z.2)) + (HierarchicalAgreementMean.pairRecord slots (upperNode p))).symm + +theorem pairRecord_eq (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (sample : BucketSampler.Direction (rows (m + 1)) × + OriginalExtraCutComparison.Record rows repeats p slots) : + OriginalCutCollision.pairRecord rows repeats p slots sample = + transportPair rows p slots (OriginalCutBucketLaw.read rows repeats p slots sample) := by + apply Prod.ext + · rfl + · apply Prod.ext + · change NodeEmbedding.matrix + (OriginalWholeCut.reconstructRecord rows repeats p slots + (OriginalCutCollision.oldRecord rows repeats p slots sample.2)) (upperNode p) = _ + rw [matrix_reconstruct] + rfl + · change NodeEmbedding.matrix + (OriginalWholeCut.reconstructRecord rows repeats p slots + (OriginalCutBucketReplacement.replaceRecord rows repeats p slots + (OriginalCutCollision.oldRecord rows repeats p slots sample.2) sample.1 sample.2.2)) + (upperNode p) = _ + rw [matrix_reconstruct] + change BucketMatrixResampling.assembledMatrix (NodeEmbedding.RowSpace slots (upperNode p)) + (rows (Nodes.height (upperNode p))) + (CutNodeRows.bucketTapeEquiv rows p slots + (OriginalCutBucketReplacement.ownValues rows repeats p slots + (OriginalCutBucketReplacement.replaceValues rows repeats p slots + (OriginalCutCollision.oldRecord rows repeats p slots sample.2).2.1 + sample.1 sample.2.2))) = _ + rw [OriginalCutBucketReplacement.ownValues_replaceValues, + CutNodeRows.bucketTapeEquiv_update] + rfl + +def directionsLaw (rows : Nat → Nat) (m : Nat) (hrows : 0 < rows (m + 1)) : + FiniteDistribution (BucketSampler.Direction (rows (m + 1))) := by + letI : Nonempty (BucketSampler.Direction (rows (m + 1))) := + ⟨BucketUniform.coordinateDirection ⟨0, hrows⟩⟩ + exact FiniteDistribution.uniform _ + +theorem reference_pair_law (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) (hrows : 0 < rows (m + 1)) : + ((directionsLaw rows m hrows).product + (OriginalExtraCutComparison.referenceLaw rows repeats p slots)).pushforward + (OriginalCutCollision.pairRecord rows repeats p slots) = + HierarchicalAgreementMean.referenceLaw slots (upperNode p) + (OriginalOwnBucketSplit.backgroundLaw rows repeats p slots) + (by simpa only [upperNode_height] using hrows) := by + let μ := OriginalOwnBucketSplit.backgroundLaw rows repeats p slots + have hread := OriginalCutBucketLaw.reference_read_law rows repeats p slots + (directionsLaw rows m hrows) + have hnative : + ((directionsLaw rows m hrows).product + (OriginalExtraCutComparison.referenceLaw rows repeats p slots)).pushforward + (OriginalCutBucketLaw.read rows repeats p slots) = + μ.product (CutBucketTransport.nativeLaw rows p slots hrows) := by + simpa only [μ, CutBucketTransport.nativeLaw, directionsLaw, + BucketSampler.tapeLaw, UniformLinearImage.law_uniform] using hread + have htransport := FiniteDistribution.product_pushforward μ + (CutBucketTransport.nativeLaw rows p slots hrows) id + (CutNodeRows.bucketSampleEquiv rows p slots) + simp only [id_eq, FiniteDistribution.pushforward_id] at htransport + calc + _ = (((directionsLaw rows m hrows).product + (OriginalExtraCutComparison.referenceLaw rows repeats p slots)).pushforward + (OriginalCutBucketLaw.read rows repeats p slots)).pushforward + (transportPair rows p slots) := by + rw [FiniteDistribution.pushforward_comp] + congr 1 + funext sample + exact pairRecord_eq rows repeats p slots sample + _ = (μ.product (CutBucketTransport.nativeLaw rows p slots hrows)).pushforward + (transportPair rows p slots) := by rw [hnative] + _ = ((μ.product (CutBucketTransport.nativeLaw rows p slots hrows)).pushforward + (fun z => (z.1, CutNodeRows.bucketSampleEquiv rows p slots z.2))).pushforward + (HierarchicalAgreementMean.pairRecord slots (upperNode p)) := + transportPair_law rows p slots μ (CutBucketTransport.nativeLaw rows p slots hrows) + _ = _ := by + rw [htransport, CutBucketTransport.nativeLaw_pushforward] + rfl + +theorem actual_pair_totalVariation_le {K : Type*} [Fintype K] + (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (ν : FiniteDistribution K) (q : K → Path branch m k) (hbranch : 0 < branch m) + (hrows : 0 < rows (m + 1)) : + (((directionsLaw rows m hrows).product + (OriginalExtraCutComparison.actualLaw rows repeats p slots ν q hbranch)).pushforward + (OriginalCutCollision.pairRecord rows repeats p slots)).totalVariation + (HierarchicalAgreementMean.referenceLaw slots (upperNode p) + (OriginalOwnBucketSplit.backgroundLaw rows repeats p slots) + (by simpa only [upperNode_height] using hrows)) ≤ + Real.sqrt ((ChildBlockCardinality.bound branch m t + (OriginalCutCalls.count rows repeats n (m + 1) + 1) rows : ℝ) ^ 2 / branch m) / 2 := by + rw [← reference_pair_law rows repeats p slots hrows] + exact OriginalCutCollision.pair_totalVariation_le rows repeats p slots ν q hbranch + (directionsLaw rows m hrows) + +end +end PerfectCompleteness.OriginalCutPairLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/OriginalUniformCut.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/OriginalUniformCut.lean new file mode 100644 index 0000000000000000000000000000000000000000..6461d83f905d650366cbc6aa7e0dc24bd0c39c69 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/OriginalUniformCut.lean @@ -0,0 +1,185 @@ +import OAI.Computability.PerfectCompleteness.Sampling.OriginalUniformCutBase + +namespace OAI + +section + +namespace PerfectCompleteness.OriginalUniformCut + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCut OriginalWholeCutTape +open UniqueGamesTheorem.Foundations.Games +open scoped Classical + +noncomputable section + +attribute [local instance 2000] OriginalUniformCutBase.valuesChildrenFintype + +private theorem uniform_equiv {A B : Type*} [Fintype A] [Fintype B] + [Nonempty A] [Nonempty B] (e : A ≃ B) : + (FiniteDistribution.uniform A).pushforward e = FiniteDistribution.uniform B := by + rw [← FiniteDistribution.transport_eq_pushforward] + exact UniformConditioning.uniform_transport e + +private theorem uniform_map_product {A B C D : Type*} + [Fintype A] [Fintype B] [Fintype C] [Fintype D] + [Nonempty A] [Nonempty B] [Nonempty C] [Nonempty D] + (f : A → C) (g : B → D) + (hf : (FiniteDistribution.uniform A).pushforward f = FiniteDistribution.uniform C) + (hg : (FiniteDistribution.uniform B).pushforward g = FiniteDistribution.uniform D) : + (FiniteDistribution.uniform (A × B)).pushforward + (fun x => (f x.1, g x.2)) = FiniteDistribution.uniform (C × D) := by + rw [← WholeCutSampler.uniform_product, FiniteDistribution.product_pushforward, + hf, hg, WholeCutSampler.uniform_product] + +variable {branch : Nat → Nat} {n m t : Nat} + +def recordStepEquiv (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n (m + 1)) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) : + Record rows repeats (.step i p) slots ≃ + WholeArraySampler.RootTape rows repeats (.step i p) slots × + (Record rows repeats p (childSlots slots i) × + ((j : RecursiveSampler.OffPath i) → Arrays (childSlots slots j.val) rows)) := + (OriginalWholeCutTape.regroupStep + (D := BucketSampler.Direction (rows (n + 1))) + (T := TerminalCalls.TerminalIndex repeats (.step i p)) + (C := OriginalCutCalls.Index rows repeats p) + (S := H (cutSlots (.step i p) slots)) + (E := OriginalTerminalSplit.ExteriorTape F2 repeats (.step i p) (LeafDomain slots)) + (L := Exterior rows repeats p (childSlots slots i)) + (O := (j : RecursiveSampler.OffPath i) → Arrays (childSlots slots j.val) rows) + (B := BelowArrays rows p (childSlots slots i))).symm.trans + (Equiv.prodCongr + (Equiv.piCongrRight (fun _ : BucketSampler.Direction (rows (n + 1)) => + (OriginalScalarReconstruction.prefixSplit F2 repeats (.step i p) + (LeafDomain slots)).symm)) + (Equiv.refl _)) + +def toStoppedTape (rows repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n (m + 1)) → + (slots : Slots branch n → Fin t → MixedSupport.Slot) → + Record rows repeats p slots → WholeArraySampler.Tape rows repeats p slots + | _, _, .refl _, slots, record => + reconstructRecord rows repeats (.refl _) slots record + | _, _, .step i p, slots, record => + let split := recordStepEquiv rows repeats i p slots record + WholeCutSampler.stepEquiv i + (WholeArraySampler.RootTape rows repeats (.step i p) slots) + (WholeArraySampler.Tape rows repeats p (childSlots slots i)) + (fun j => Arrays (childSlots slots j.val) rows) + (split.1, (toStoppedTape rows repeats p (childSlots slots i) split.2.1, + split.2.2)) + +theorem evaluate_toStoppedTape (rows repeats : Nat → Nat) : + ∀ {n m : Nat} (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (record : Record rows repeats p slots), + WholeArraySampler.evaluate rows repeats p slots + (toStoppedTape rows repeats p slots record) = + reconstructRecord rows repeats p slots record := by + intro n + induction n with + | zero => intro m p; cases p + | succ n ih => + intro m p slots record + cases p with + | refl => rfl + | step i p => + exact congrArg₂ (WholeArraySampler.assemble slots rows) rfl + (congrArg (fun selected : Arrays (childSlots slots i) rows => + WholeArraySampler.childrenAt slots rows i selected record.1.2.2) + (ih p (childSlots slots i) + (record.1.2.1, ((fun call => record.2.1 (.inr call)), record.2.2)))) + +theorem uniform_toStoppedTape (rows repeats : Nat → Nat) : + ∀ {n m : Nat} (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot), + (FiniteDistribution.uniform (Record rows repeats p slots)).pushforward + (toStoppedTape rows repeats p slots) = + FiniteDistribution.uniform (WholeArraySampler.Tape rows repeats p slots) := by + intro n + induction n with + | zero => intro m p; cases p + | succ n ih => + intro m p slots + cases p with + | refl => + exact OriginalUniformCutBase.uniform_reconstructRecord_refl rows repeats slots + | step i p => + let R := WholeArraySampler.RootTape rows repeats (.step i p) slots + let L := Record rows repeats p (childSlots slots i) + let S := WholeArraySampler.Tape rows repeats p (childSlots slots i) + let O := (j : RecursiveSampler.OffPath i) → Arrays (childSlots slots j.val) rows + let e := recordStepEquiv rows repeats i p slots + let finish := WholeCutSampler.stepEquiv i R S + (fun j => Arrays (childSlots slots j.val) rows) + let : Fintype (WholeArraySampler.StepTape (i := i) R S + (fun j => Arrays (childSlots slots j.val) rows)) := + WholeArraySampler.tapeFintype rows repeats (.step i p) slots + let : Nonempty (WholeArraySampler.StepTape (i := i) R S + (fun j => Arrays (childSlots slots j.val) rows)) := + ⟨WholeArraySampler.zeroTape rows repeats (.step i p) slots⟩ + let middle : R × (L × O) → R × (S × O) := + fun z => (z.1, + (toStoppedTape rows repeats p (childSlots slots i) z.2.1, z.2.2)) + have hinner : (FiniteDistribution.uniform (L × O)).pushforward + (fun z => (toStoppedTape rows repeats p (childSlots slots i) z.1, z.2)) = + FiniteDistribution.uniform (S × O) := + uniform_map_product (toStoppedTape rows repeats p (childSlots slots i)) + (id : O → O) (ih p (childSlots slots i)) + (FiniteDistribution.pushforward_id _) + have hmiddle : (FiniteDistribution.uniform (R × (L × O))).pushforward middle = + FiniteDistribution.uniform (R × (S × O)) := + uniform_map_product (id : R → R) + (fun z : L × O => + (toStoppedTape rows repeats p (childSlots slots i) z.1, z.2)) + (FiniteDistribution.pushforward_id _) hinner + calc + _ = (((FiniteDistribution.uniform (Record rows repeats (.step i p) slots)).pushforward + e).pushforward middle).pushforward finish := by + rw [FiniteDistribution.pushforward_comp, FiniteDistribution.pushforward_comp] + rfl + _ = (FiniteDistribution.uniform (R × (S × O))).pushforward finish := by + rw [uniform_equiv e, hmiddle] + _ = _ := uniform_equiv finish + +def referenceLaw (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + FiniteDistribution (Record rows repeats p slots) := + (exteriorLaw rows repeats p slots).product + ((FiniteProduct.law (fun _ : OriginalCutCalls.Index rows repeats p => + FiniteDistribution.uniform (H (cutSlots p slots)))).product + (FiniteProduct.law (fun child : Fin (branch m) => + FiniteDistribution.uniform (Arrays (childSlots (cutSlots p slots) child) rows)))) + +theorem referenceLaw_uniform (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + referenceLaw rows repeats p slots = FiniteDistribution.uniform (Record rows repeats p slots) := by + unfold referenceLaw exteriorLaw + rw [UniformLinearImage.law_uniform, UniformLinearImage.law_uniform, + WholeCutSampler.uniform_product, WholeCutSampler.uniform_product] + +theorem reconstruct_referenceLaw (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + (referenceLaw rows repeats p slots).pushforward (reconstructRecord rows repeats p slots) = + WholeArraySampler.law rows repeats p slots := by + rw [referenceLaw_uniform] + calc + _ = ((FiniteDistribution.uniform (Record rows repeats p slots)).pushforward + (toStoppedTape rows repeats p slots)).pushforward + (WholeArraySampler.evaluate rows repeats p slots) := by + rw [FiniteDistribution.pushforward_comp] + congr 1 + funext record + exact (evaluate_toStoppedTape rows repeats p slots record).symm + _ = (FiniteDistribution.uniform (WholeArraySampler.Tape rows repeats p slots)).pushforward + (WholeArraySampler.evaluate rows repeats p slots) := by rw [uniform_toStoppedTape] + _ = _ := by rw [← WholeArraySubtreeSplit.tapeLaw_eq_uniform]; rfl + +end +end PerfectCompleteness.OriginalUniformCut + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/OriginalUniformCutBase.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/OriginalUniformCutBase.lean new file mode 100644 index 0000000000000000000000000000000000000000..286c7e14c9c849e946f11bfc2a0e4991f91d17e4 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/OriginalUniformCutBase.lean @@ -0,0 +1,160 @@ +import OAI.Computability.PerfectCompleteness.Foundations.OriginalWholeCut +import OAI.Computability.PerfectCompleteness.Sampling.BucketUniformLemmas +import OAI.Computability.PerfectCompleteness.Sampling.CutSamplerReplayTransportLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.OriginalUniformCutBase + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCut +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +noncomputable section + +variable {branch : Nat → Nat} {n t : Nat} + +@[instance_reducible] def valuesChildrenFintype (C : Type*) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) (rows : Nat → Nat) + [hValues : Fintype (C → H slots)] [hChildren : Fintype (ChildArrays rows slots)] : + Fintype ((C → H slots) × ChildArrays rows slots) := + @instFintypeProd (C → H slots) (ChildArrays rows slots) hValues hChildren + +attribute [local instance 2000] instFintypeProd + +def assembleEquiv + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) (rows : Nat → Nat) : + ((Fin (rows (n + 1)) → H slots) × ChildArrays rows slots) ≃ Arrays slots rows where + toFun z := WholeArraySampler.assemble slots rows z.1 z.2 + invFun arrays := (arrays (.inl ()), fun child node => arrays (.inr (child, node))) + left_inv z := by + rcases z with ⟨root, children⟩ + rfl + right_inv arrays := by + funext node + rcases node with u | ⟨child, node⟩ + · cases u + rfl + · rfl + +theorem uniform_assemble_law + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) (rows : Nat → Nat) : + ((FiniteDistribution.uniform (Fin (rows (n + 1)) → H slots)).product + (FiniteDistribution.uniform (ChildArrays rows slots))).pushforward + (fun z => WholeArraySampler.assemble slots rows z.1 z.2) = + FiniteDistribution.uniform (Arrays slots rows) := by + rw [WholeCutSampler.uniform_product] + change (FiniteDistribution.uniform + ((Fin (rows (n + 1)) → H slots) × ChildArrays rows slots)).pushforward + (assembleEquiv slots rows) = _ + rw [← FiniteDistribution.transport_eq_pushforward] + exact UniformConditioning.uniform_transport (assembleEquiv slots rows) + +theorem uniform_bucket_assemble_law + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) (rows : Nat → Nat) : + ((BucketSampler.tapeLaw (rows (n + 1)) (FiniteDistribution.uniform (H slots))).product + (FiniteDistribution.uniform (ChildArrays rows slots))).pushforward + (fun z => WholeArraySampler.assemble slots rows + (BucketSampler.evaluate (rows (n + 1)) (id : H slots → H slots) z.1) z.2) = + FiniteDistribution.uniform (Arrays slots rows) := by + calc + _ = (((BucketSampler.tapeLaw (rows (n + 1)) + (FiniteDistribution.uniform (H slots))).product + (FiniteDistribution.uniform (ChildArrays rows slots))).pushforward + (fun z => + (BucketSampler.evaluate (rows (n + 1)) (id : H slots → H slots) z.1, + z.2))).pushforward + (fun z => WholeArraySampler.assemble slots rows z.1 z.2) := + (FiniteDistribution.pushforward_comp _ _ _).symm + _ = ((FiniteDistribution.uniform (Fin (rows (n + 1)) → H slots)).product + (FiniteDistribution.uniform (ChildArrays rows slots))).pushforward + (fun z => WholeArraySampler.assemble slots rows z.1 z.2) := by + apply congrArg (fun μ : FiniteDistribution + ((Fin (rows (n + 1)) → H slots) × ChildArrays rows slots) => + μ.pushforward (fun z => WholeArraySampler.assemble slots rows z.1 z.2)) + have h := FiniteDistribution.product_pushforward + (BucketSampler.tapeLaw (rows (n + 1)) (FiniteDistribution.uniform (H slots))) + (FiniteDistribution.uniform (ChildArrays rows slots)) + (BucketSampler.evaluate (rows (n + 1)) (id : H slots → H slots)) + (id : ChildArrays rows slots → ChildArrays rows slots) + simpa only [id_eq, FiniteDistribution.pushforward_id, + BucketUniform.uniform_evaluate_law] using h + _ = _ := uniform_assemble_law slots rows + +private theorem uniform_pushforward_reindex {A B C : Type*} + [Fintype A] [Fintype B] [Fintype C] [Nonempty A] [Nonempty B] + (e : A ≃ B) (f : A → C) (g : B → C) (h : ∀ x, g (e x) = f x) : + (FiniteDistribution.uniform A).pushforward f = + (FiniteDistribution.uniform B).pushforward g := by + calc + _ = (FiniteDistribution.uniform A).pushforward (fun x => g (e x)) := + congrArg (fun map : A → C => (FiniteDistribution.uniform A).pushforward map) + (funext (fun x => (h x).symm)) + _ = ((FiniteDistribution.uniform A).pushforward e).pushforward g := + (FiniteDistribution.pushforward_comp (FiniteDistribution.uniform A) e g).symm + _ = (FiniteDistribution.uniform B).pushforward g := + congrArg (fun μ : FiniteDistribution B => μ.pushforward g) + ((FiniteDistribution.transport_eq_pushforward + (FiniteDistribution.uniform A) e).symm.trans + (UniformConditioning.uniform_transport e)) + +private abbrev ReflRecord (rows : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) := + Unit × ((BucketSampler.Direction (rows (n + 1)) → H slots) × ChildArrays rows slots) + +private def reflRecordEquiv (rows repeats : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) : + OriginalWholeCut.Record rows repeats (.refl (n + 1)) slots ≃ ReflRecord rows slots := + Equiv.refl _ + +private def renderRecord (rows : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (record : ReflRecord rows slots) : Arrays slots rows := + WholeArraySampler.assemble slots rows + (BucketSampler.evaluate (rows (n + 1)) (id : H slots → H slots) record.2.1) record.2.2 + +private theorem renderRecord_equiv (rows repeats : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (record : OriginalWholeCut.Record rows repeats (.refl (n + 1)) slots) : + renderRecord rows slots (reflRecordEquiv rows repeats slots record) = + OriginalWholeCut.reconstructRecord rows repeats (.refl (n + 1)) slots record := rfl + +private theorem uniform_renderRecord (rows : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) : + (FiniteDistribution.uniform (ReflRecord rows slots)).pushforward (renderRecord rows slots) = + FiniteDistribution.uniform (Arrays slots rows) := by + have hdrop : (FiniteDistribution.uniform (ReflRecord rows slots)).pushforward Prod.snd = + (BucketSampler.tapeLaw (rows (n + 1)) (FiniteDistribution.uniform (H slots))).product + (FiniteDistribution.uniform (ChildArrays rows slots)) := by + rw [← WholeCutSampler.uniform_product, FiniteDistribution.product_pushforward_snd] + rw [BucketSampler.tapeLaw, UniformLinearImage.law_uniform, WholeCutSampler.uniform_product] + calc + _ = ((FiniteDistribution.uniform (ReflRecord rows slots)).pushforward Prod.snd).pushforward + (fun z => WholeArraySampler.assemble slots rows + (BucketSampler.evaluate (rows (n + 1)) (id : H slots → H slots) z.1) z.2) := + (FiniteDistribution.pushforward_comp _ _ _).symm + _ = _ := by rw [hdrop]; exact uniform_bucket_assemble_law slots rows + +theorem uniform_reconstructRecord_refl (rows repeats : Nat → Nat) + (slots : Slots branch (n + 1) → Fin t → MixedSupport.Slot) : + (FiniteDistribution.uniform + (OriginalWholeCut.Record rows repeats (.refl (n + 1)) slots)).pushforward + (OriginalWholeCut.reconstructRecord rows repeats (.refl (n + 1)) slots) = + FiniteDistribution.uniform (Arrays slots rows) := + (uniform_pushforward_reindex + (A := OriginalWholeCut.Record rows repeats (.refl (n + 1)) slots) + (B := ReflRecord rows slots) (C := Arrays slots rows) + (reflRecordEquiv rows repeats slots) + (OriginalWholeCut.reconstructRecord rows repeats (.refl (n + 1)) slots) + (renderRecord rows slots) (renderRecord_equiv rows repeats slots)).trans + (uniform_renderRecord rows slots) + +end +end PerfectCompleteness.OriginalUniformCutBase + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/OriginalUsefulPairLaw.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/OriginalUsefulPairLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..5a3fd6aafd66a532b9808aafc420b4c68cd532ec --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/OriginalUsefulPairLaw.lean @@ -0,0 +1,195 @@ +import OAI.Computability.PerfectCompleteness.Construction.CutBucketTransportLemmas +import OAI.Computability.PerfectCompleteness.Sampling.OriginalCutPairLaw + +namespace OAI + +section + +namespace PerfectCompleteness.OriginalUsefulPairLaw + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCutTape WholeArrayInteriorExterior +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) +open scoped BigOperators Classical + +noncomputable section + +attribute [local instance] linearMapFintype + +private theorem product_mixture_pushforward {E A B Γ : Type*} + [Fintype E] [Fintype A] [Fintype B] [Fintype Γ] + (μ : FiniteDistribution A) (κ : FiniteDistribution E) + (ν : E → FiniteDistribution B) (f : A × B → Γ) : + (μ.product (κ.mixture ν)).pushforward f = + κ.mixture (fun e => (μ.product (ν e)).pushforward f) := by + have hp : μ.product (κ.mixture ν) = κ.mixture (fun e => μ.product (ν e)) := by + apply FiniteDistribution.eq_of_weight_eq + intro x + simp only [FiniteDistribution.product, FiniteDistribution.mixture, Finset.mul_sum] + apply Finset.sum_congr rfl + intro e _ + exact mul_left_comm _ _ _ + rw [hp, FiniteDistribution.pushforward_mixture] + +private theorem nested_sigma_product_pushforward {Tag Bg Buck Γ : Type*} + [Fintype Tag] [Fintype Bg] [Fintype Buck] [Fintype Γ] + (μ : FiniteDistribution Tag) (β : Tag → FiniteDistribution Bg) + (γ : Tag → FiniteDistribution Buck) (f : Bg × Buck → Γ) : + (CompletionSoundness.sigmaLaw (CompletionSoundness.sigmaLaw μ β) + (fun d : Σ _ : Tag, Bg => γ d.1)).pushforward + (fun z => f (z.1.2, z.2)) = + μ.mixture (fun tag => ((β tag).product (γ tag)).pushforward f) := by + apply FiniteDistribution.eq_of_weight_eq + intro x + simp only [FiniteDistribution.pushforward, CompletionSoundness.sigmaLaw, + FiniteDistribution.mixture, FiniteDistribution.product, Fintype.sum_sigma, + Fintype.sum_prod_type, Finset.mul_sum, mul_ite, mul_zero, mul_assoc] + +variable {branch : Nat → Nat} {n m k t : Nat} + +local instance backgroundFintype (rows : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Fintype (HierarchicalMatrixTable.Background (rows := rows) slots (upperNode p)) := + Fintype.ofFinite _ + +local instance rowSpaceFintype (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Fintype (NodeEmbedding.RowSpace slots (upperNode p)) := Fintype.ofFinite _ + +attribute [local instance 2000] OriginalWholeCutLaw.valuesBelowFintype + +private theorem transportPair_law (rows : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (μ : FiniteDistribution (HierarchicalMatrixTable.Background (rows := rows) slots (upperNode p))) + (ν : FiniteDistribution (BucketSampler.Direction (rows (m + 1)) × + (BucketSampler.Tape (rows (m + 1)) (H (cutSlots p slots)) × H (cutSlots p slots)))) : + (μ.product ν).pushforward (OriginalCutPairLaw.transportPair rows p slots) = + ((μ.product ν).pushforward + (fun z : OriginalCutBucketLaw.NativeSample rows p slots => + (z.1, CutNodeRows.bucketSampleEquiv rows p slots z.2))).pushforward + (HierarchicalAgreementMean.pairRecord slots (upperNode p)) := by + exact (FiniteDistribution.pushforward_comp (μ.product ν) + (fun z : OriginalCutBucketLaw.NativeSample rows p slots => + (z.1, CutNodeRows.bucketSampleEquiv rows p slots z.2)) + (HierarchicalAgreementMean.pairRecord slots (upperNode p))).symm + +theorem record_fresh_pair_law (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) (chosen : Fin (branch m)) (q : Path branch m k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) (hrows : 0 < rows (m + 1)) : + ((OriginalCutPairLaw.directionsLaw rows m hrows).product + (((OriginalWholeCutLaw.recordLaw rows repeats p chosen q slots).pushforward + (OriginalWholeCutBridge.numberRecord rows repeats p slots)).product + (RecursiveSampler.law F2 repeats (.step chosen q) (LeafDomain (cutSlots p slots))))).pushforward + (OriginalCutCollision.pairRecord rows repeats p slots) = + ((OriginalOwnBucketSplit.actualBackgroundLaw rows repeats p chosen q slots).product + (HierarchicalUsefulCollision.bucketLaw slots (upperNode p) + ((RecursiveSampler.law F2 repeats (.step chosen q) (LeafDomain (cutSlots p slots))).pushforward + (CutNodeRows.cutRowEquiv p slots)) + (by simpa only [upperNode_height] using hrows))).pushforward + (HierarchicalAgreementMean.pairRecord slots (upperNode p)) := by + let μ := OriginalOwnBucketSplit.actualBackgroundLaw rows repeats p chosen q slots + let scalar := RecursiveSampler.law F2 repeats (.step chosen q) (LeafDomain (cutSlots p slots)) + let records := ((OriginalWholeCutLaw.recordLaw rows repeats p chosen q slots).pushforward + (OriginalWholeCutBridge.numberRecord rows repeats p slots)).product scalar + let directions := OriginalCutPairLaw.directionsLaw rows m hrows + have hread := OriginalCutBucketLaw.record_fresh_read_law rows repeats p chosen q slots directions + have hnative : + (directions.product records).pushforward (OriginalCutBucketLaw.read rows repeats p slots) = + μ.product (CutBucketTransportActual.nativeLaw rows p slots scalar hrows) := by + simpa only [μ, scalar, records, directions, CutBucketTransportActual.nativeLaw, + OriginalCutPairLaw.directionsLaw] using hread + have htransport := FiniteDistribution.product_pushforward μ + (CutBucketTransportActual.nativeLaw rows p slots scalar hrows) id + (CutNodeRows.bucketSampleEquiv rows p slots) + simp only [id_eq, FiniteDistribution.pushforward_id] at htransport + calc + _ = ((directions.product records).pushforward + (OriginalCutBucketLaw.read rows repeats p slots)).pushforward + (OriginalCutPairLaw.transportPair rows p slots) := by + rw [FiniteDistribution.pushforward_comp] + congr 1 + funext sample + exact OriginalCutPairLaw.pairRecord_eq rows repeats p slots sample + _ = (μ.product (CutBucketTransportActual.nativeLaw rows p slots scalar hrows)).pushforward + (OriginalCutPairLaw.transportPair rows p slots) := by rw [hnative] + _ = ((μ.product (CutBucketTransportActual.nativeLaw rows p slots scalar hrows)).pushforward + (fun z => (z.1, CutNodeRows.bucketSampleEquiv rows p slots z.2))).pushforward + (HierarchicalAgreementMean.pairRecord slots (upperNode p)) := + transportPair_law rows p slots μ (CutBucketTransportActual.nativeLaw rows p slots scalar hrows) + _ = _ := by + rw [htransport, CutBucketTransportActual.nativeLaw_pushforward] + +abbrev Descriptor (rows : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) (K : Type*) := + Σ _ : Fin (branch m) × K, + HierarchicalMatrixTable.Background (rows := rows) slots (upperNode p) + +variable {K : Type*} [Fintype K] + +def externalLaw (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (ν : FiniteDistribution K) (q : K → Path branch m k) (hbranch : 0 < branch m) : + FiniteDistribution (Descriptor rows p slots K) := + CompletionSoundness.sigmaLaw (OriginalPrefixContinuation.tagLaw ν hbranch) + (fun tag => OriginalOwnBucketSplit.actualBackgroundLaw rows repeats p tag.1 (q tag.2) slots) + +def background (rows : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (descriptor : Descriptor rows p slots K) : + HierarchicalMatrixTable.Background (rows := rows) slots (upperNode p) := descriptor.2 + +def scalarLaw (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) (q : K → Path branch m k) + (descriptor : Descriptor rows p slots K) : + FiniteDistribution (NodeEmbedding.RowSpace slots (upperNode p)) := + (RecursiveSampler.law F2 repeats (.step descriptor.1.1 (q descriptor.1.2)) + (LeafDomain (cutSlots p slots))).pushforward (CutNodeRows.cutRowEquiv p slots) + +theorem useful_pairLaw_eq_mixture (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (ν : FiniteDistribution K) (q : K → Path branch m k) (hbranch : 0 < branch m) + (hrows : 0 < rows (m + 1)) : + HierarchicalUsefulCollision.pairLaw slots (upperNode p) + (externalLaw rows repeats p slots ν q hbranch) (background rows p slots) + (scalarLaw rows repeats p slots q) + (by simpa only [upperNode_height] using hrows) = + (OriginalPrefixContinuation.tagLaw ν hbranch).mixture (fun tag => + ((OriginalOwnBucketSplit.actualBackgroundLaw rows repeats p tag.1 (q tag.2) slots).product + (HierarchicalUsefulCollision.bucketLaw slots (upperNode p) + ((RecursiveSampler.law F2 repeats (.step tag.1 (q tag.2)) + (LeafDomain (cutSlots p slots))).pushforward (CutNodeRows.cutRowEquiv p slots)) + (by simpa only [upperNode_height] using hrows))).pushforward + (HierarchicalAgreementMean.pairRecord slots (upperNode p))) := by + exact nested_sigma_product_pushforward + (OriginalPrefixContinuation.tagLaw ν hbranch) + (fun tag => OriginalOwnBucketSplit.actualBackgroundLaw rows repeats p tag.1 (q tag.2) slots) + (fun tag => HierarchicalUsefulCollision.bucketLaw slots (upperNode p) + ((RecursiveSampler.law F2 repeats (.step tag.1 (q tag.2)) + (LeafDomain (cutSlots p slots))).pushforward (CutNodeRows.cutRowEquiv p slots)) + (by simpa only [upperNode_height] using hrows)) + (HierarchicalAgreementMean.pairRecord slots (upperNode p)) + +theorem actual_pair_law (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) + (ν : FiniteDistribution K) (q : K → Path branch m k) (hbranch : 0 < branch m) + (hrows : 0 < rows (m + 1)) : + ((OriginalCutPairLaw.directionsLaw rows m hrows).product + (OriginalExtraCutComparison.actualLaw rows repeats p slots ν q hbranch)).pushforward + (OriginalCutCollision.pairRecord rows repeats p slots) = + HierarchicalUsefulCollision.pairLaw slots (upperNode p) + (externalLaw rows repeats p slots ν q hbranch) (background rows p slots) + (scalarLaw rows repeats p slots q) + (by simpa only [upperNode_height] using hrows) := by + rw [OriginalExtraCutComparison.actualLaw_eq_mixture, product_mixture_pushforward, + useful_pairLaw_eq_mixture rows repeats p slots ν q hbranch hrows] + apply congrArg ((OriginalPrefixContinuation.tagLaw ν hbranch).mixture) + funext tag + exact record_fresh_pair_law rows repeats p tag.1 (q tag.2) slots hrows + +end +end PerfectCompleteness.OriginalUsefulPairLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/OriginalWholeCutLaw.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/OriginalWholeCutLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..44e2a954181431dba5a9f2d59f364fb1894296f8 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/OriginalWholeCutLaw.lean @@ -0,0 +1,243 @@ +import OAI.Computability.PerfectCompleteness.Construction.OriginalChildBlockProducts +import OAI.Computability.PerfectCompleteness.Construction.SourceQuestionOrderLemmas +import OAI.Computability.PerfectCompleteness.Foundations.OriginalWholeCut + +namespace OAI + +section + +namespace PerfectCompleteness.OriginalWholeCutLaw + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +noncomputable section + +private theorem product_map_record {E A B V D : Type*} + [Fintype E] [Fintype A] [Fintype B] [Fintype V] [Fintype D] + (exterior : FiniteDistribution E) (calls : FiniteDistribution A) + (below : FiniteDistribution B) (values : A → V) (arrays : B → D) : + (exterior.product (calls.product below)).pushforward + (fun z => (z.1, (values z.2.1, arrays z.2.2))) = + exterior.product ((calls.pushforward values).product (below.pushforward arrays)) := by + calc + _ = (exterior.pushforward id).product + ((calls.product below).pushforward (fun z => (values z.1, arrays z.2))) := + FiniteDistribution.product_pushforward exterior (calls.product below) id + (fun z => (values z.1, arrays z.2)) + _ = _ := by rw [FiniteDistribution.pushforward_id, FiniteDistribution.product_pushforward] + +variable {branch : Nat → Nat} {n m k t : Nat} + +@[instance_reducible] def valuesBelowFintype (rows repeats : Nat → Nat) + (p : Path branch n (m + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Fintype (OriginalWholeCut.Values rows repeats p slots × + OriginalWholeCut.BelowArrays rows p slots) := + @instFintypeProd (OriginalWholeCut.Values rows repeats p slots) + (OriginalWholeCut.BelowArrays rows p slots) inferInstance inferInstance + +attribute [local instance 2000] valuesBelowFintype + +theorem childrenAt_law (rows : Nat → Nat) + (slots : Slots branch (m + 1) → Fin t → MixedSupport.Slot) + (chosen : Fin (branch m)) + (Q : (child : Fin (branch m)) → + FiniteDistribution (Arrays (childSlots slots child) rows)) : + ((Q chosen).product (FiniteProduct.law + (fun child : RecursiveSampler.OffPath chosen => + FiniteDistribution.uniform (Arrays (childSlots slots child.val) rows)))).pushforward + (fun z => WholeArraySampler.childrenAt slots rows chosen z.1 z.2) = + FiniteProduct.law (ChildBlockMixture.component Q chosen) := by + have hselected : ChildBlockMixture.component Q chosen chosen = Q chosen := dite_eq_left rfl + have hother : FiniteProductSplit.otherLaw (ChildBlockMixture.component Q chosen) chosen = + FiniteProduct.law (fun child : RecursiveSampler.OffPath chosen => + FiniteDistribution.uniform (Arrays (childSlots slots child.val) rows)) := by + apply congrArg (fun laws : (child : RecursiveSampler.OffPath chosen) → + FiniteDistribution (Arrays (childSlots slots child.val) rows) => FiniteProduct.law laws) + funext child + exact dite_eq_right (Ne.symm child.property) + have h := OriginalChildBlockProducts.merge_law (ChildBlockMixture.component Q chosen) chosen + rw [hselected, hother] at h + exact h + +def belowArraysLaw (rows repeats : Nat → Nat) (chosen : Fin (branch m)) + (q : Path branch m k) (slots : Slots branch (m + 1) → Fin t → MixedSupport.Slot) : + FiniteDistribution ((child : Fin (branch m)) → Arrays (childSlots slots child) rows) := + FiniteProduct.law (ChildBlockMixture.component + (fun child => WholeArraySampler.law rows repeats q (childSlots slots child)) chosen) + +theorem below_product_law (rows repeats : Nat → Nat) (chosen : Fin (branch m)) + (q : Path branch m k) (slots : Slots branch (m + 1) → Fin t → MixedSupport.Slot) : + ((WholeArraySampler.tapeLaw rows repeats q (childSlots slots chosen)).product + (FiniteProduct.law (fun child : RecursiveSampler.OffPath chosen => + FiniteDistribution.uniform (Arrays (childSlots slots child.val) rows)))).pushforward + (fun z => WholeArraySampler.childrenAt slots rows chosen + (WholeArraySampler.evaluate rows repeats q (childSlots slots chosen) z.1) z.2) = + belowArraysLaw rows repeats chosen q slots := by + let ordinary := FiniteProduct.law (fun child : RecursiveSampler.OffPath chosen => + FiniteDistribution.uniform (Arrays (childSlots slots child.val) rows)) + calc + _ = (((WholeArraySampler.tapeLaw rows repeats q (childSlots slots chosen)).product + ordinary).pushforward (fun z => + (WholeArraySampler.evaluate rows repeats q (childSlots slots chosen) z.1, + z.2))).pushforward + (fun z => WholeArraySampler.childrenAt slots rows chosen z.1 z.2) := + (FiniteDistribution.pushforward_comp _ _ _).symm + _ = ((WholeArraySampler.law rows repeats q (childSlots slots chosen)).product + ordinary).pushforward + (fun z => WholeArraySampler.childrenAt slots rows chosen z.1 z.2) := by + apply congrArg (fun μ : FiniteDistribution + (Arrays (childSlots slots chosen) rows × + ((child : RecursiveSampler.OffPath chosen) → + Arrays (childSlots slots child.val) rows)) => + μ.pushforward (fun z => WholeArraySampler.childrenAt slots rows chosen z.1 z.2)) + apply FiniteDistribution.eq_of_weight_eq + rintro ⟨a, b⟩ + simp only [WholeArraySampler.law, FiniteDistribution.pushforward, + FiniteDistribution.product] + rw [Fintype.sum_prod_type, Finset.sum_mul] + apply Finset.sum_congr rfl + intro ω _ + by_cases h : WholeArraySampler.evaluate rows repeats q + (childSlots slots chosen) ω = a <;> simp [h] + _ = _ := childrenAt_law rows slots chosen + (fun child => WholeArraySampler.law rows repeats q (childSlots slots child)) + +theorem belowEvaluate_law (rows repeats : Nat → Nat) (chosen : Fin (branch m)) + (q : Path branch m k) (slots : Slots branch (m + 1) → Fin t → MixedSupport.Slot) : + (OriginalWholeCutTape.belowLaw rows repeats chosen q slots).pushforward + (OriginalWholeCut.belowEvaluate rows repeats chosen q slots) = + belowArraysLaw rows repeats chosen q slots := + below_product_law rows repeats chosen q slots + +def valuesLaw (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (chosen : Fin (branch m)) (q : Path branch m k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + FiniteDistribution (OriginalWholeCut.Values rows repeats p slots) := + FiniteProduct.law (fun _ : OriginalCutCalls.Index rows repeats p => + RecursiveSampler.law F2 repeats (.step chosen q) + (LeafDomain (OriginalWholeCutTape.cutSlots p slots))) + +theorem callsEvaluate_law (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (chosen : Fin (branch m)) (q : Path branch m k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + (OriginalWholeCutTape.callsLaw rows repeats p chosen q slots).pushforward + (fun calls call => RecursiveSampler.evaluate F2 repeats (.step chosen q) + (LeafDomain (OriginalWholeCutTape.cutSlots p slots)) (calls call)) = + valuesLaw rows repeats p chosen q slots := + FiniteProduct.pushforward_map + (fun _ : OriginalCutCalls.Index rows repeats p => + RecursiveSampler.tapeLaw F2 repeats (.step chosen q) + (LeafDomain (OriginalWholeCutTape.cutSlots p slots))) + (fun _ => RecursiveSampler.evaluate F2 repeats (.step chosen q) + (LeafDomain (OriginalWholeCutTape.cutSlots p slots))) + +theorem numberedValues_law (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (chosen : Fin (branch m)) (q : Path branch m k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + (valuesLaw rows repeats p chosen q slots).pushforward + (OriginalWholeCut.numberedValues rows repeats p slots) = + FiniteProduct.law (fun _ : Fin (OriginalCutCalls.count rows repeats n (m + 1)) => + RecursiveSampler.law F2 repeats (.step chosen q) + (LeafDomain (OriginalWholeCutTape.cutSlots p slots))) := by + change (valuesLaw rows repeats p chosen q slots).pushforward + (Equiv.arrowCongr (OriginalWholeCut.callNumbering rows repeats p) + (Equiv.refl (H (OriginalWholeCutTape.cutSlots p slots)))) = _ + rw [← FiniteDistribution.transport_eq_pushforward] + apply FiniteDistribution.eq_of_weight_eq + intro values + change (∏ call : OriginalCutCalls.Index rows repeats p, + (RecursiveSampler.law F2 repeats (.step chosen q) + (LeafDomain (OriginalWholeCutTape.cutSlots p slots))).weight + (values (OriginalWholeCut.callNumbering rows repeats p call))) = + ∏ call : Fin (OriginalCutCalls.count rows repeats n (m + 1)), + (RecursiveSampler.law F2 repeats (.step chosen q) + (LeafDomain (OriginalWholeCutTape.cutSlots p slots))).weight (values call) + exact (OriginalWholeCut.callNumbering rows repeats p).prod_comp + (fun call : Fin (OriginalCutCalls.count rows repeats n (m + 1)) => + (RecursiveSampler.law F2 repeats (.step chosen q) + (LeafDomain (OriginalWholeCutTape.cutSlots p slots))).weight (values call)) + +def recordLaw (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (chosen : Fin (branch m)) (q : Path branch m k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + FiniteDistribution (OriginalWholeCut.Record rows repeats p slots) := + (OriginalWholeCutTape.exteriorLaw rows repeats p slots).product + ((valuesLaw rows repeats p chosen q slots).product + (belowArraysLaw rows repeats chosen q (OriginalWholeCutTape.cutSlots p slots))) + +theorem readRecord_law (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (chosen : Fin (branch m)) (q : Path branch m k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + (WholeArraySampler.tapeLaw rows repeats (p.append (.step chosen q)) slots).pushforward + (OriginalWholeCut.readRecord rows repeats p chosen q slots) = + recordLaw rows repeats p chosen q slots := by + let values : OriginalWholeCutTape.Calls rows repeats p chosen q slots → + OriginalWholeCut.Values rows repeats p slots := + fun calls call => RecursiveSampler.evaluate F2 repeats (.step chosen q) + (LeafDomain (OriginalWholeCutTape.cutSlots p slots)) (calls call) + let arrays : OriginalWholeCutTape.BelowTape rows repeats chosen q + (OriginalWholeCutTape.cutSlots p slots) → OriginalWholeCut.BelowArrays rows p slots := + OriginalWholeCut.belowEvaluate rows repeats chosen q (OriginalWholeCutTape.cutSlots p slots) + let observe : OriginalWholeCutTape.Exterior rows repeats p slots × + (OriginalWholeCutTape.Calls rows repeats p chosen q slots × + OriginalWholeCutTape.BelowTape rows repeats chosen q (OriginalWholeCutTape.cutSlots p slots)) → + OriginalWholeCut.Record rows repeats p slots := + fun z => (z.1, (values z.2.1, arrays z.2.2)) + change (WholeArraySampler.tapeLaw rows repeats (p.append (.step chosen q)) slots).pushforward + (fun ω => observe (OriginalWholeCutTape.splitTape rows repeats p chosen q slots ω)) = _ + rw [← FiniteDistribution.pushforward_comp + (WholeArraySampler.tapeLaw rows repeats (p.append (.step chosen q)) slots) + (OriginalWholeCutTape.splitTape rows repeats p chosen q slots) observe, + OriginalWholeCutTape.split_tapeLaw] + apply Eq.trans (product_map_record + (E := OriginalWholeCutTape.Exterior rows repeats p slots) + (A := OriginalWholeCutTape.Calls rows repeats p chosen q slots) + (B := OriginalWholeCutTape.BelowTape rows repeats chosen q (OriginalWholeCutTape.cutSlots p slots)) + (V := OriginalWholeCut.Values rows repeats p slots) + (D := OriginalWholeCut.BelowArrays rows p slots) + (OriginalWholeCutTape.exteriorLaw rows repeats p slots) + (OriginalWholeCutTape.callsLaw rows repeats p chosen q slots) + (OriginalWholeCutTape.belowLaw rows repeats chosen q (OriginalWholeCutTape.cutSlots p slots)) + values arrays) + exact congrArg + (fun μ : FiniteDistribution + (OriginalWholeCut.Values rows repeats p slots × OriginalWholeCut.BelowArrays rows p slots) => + (OriginalWholeCutTape.exteriorLaw rows repeats p slots).product μ) + (congrArg₂ + (fun (μ : FiniteDistribution (OriginalWholeCut.Values rows repeats p slots)) + (ν : FiniteDistribution (OriginalWholeCut.BelowArrays rows p slots)) => μ.product ν) + (callsEvaluate_law rows repeats p chosen q slots) + (belowEvaluate_law rows repeats chosen q (OriginalWholeCutTape.cutSlots p slots))) + +theorem reconstruct_law (rows repeats : Nat → Nat) (p : Path branch n (m + 1)) + (chosen : Fin (branch m)) (q : Path branch m k) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + (recordLaw rows repeats p chosen q slots).pushforward + (OriginalWholeCut.reconstructRecord rows repeats p slots) = + WholeArraySampler.law rows repeats (p.append (.step chosen q)) slots := by + calc + _ = ((WholeArraySampler.tapeLaw rows repeats (p.append (.step chosen q)) slots).pushforward + (OriginalWholeCut.readRecord rows repeats p chosen q slots)).pushforward + (OriginalWholeCut.reconstructRecord rows repeats p slots) := + congrArg (fun μ : FiniteDistribution (OriginalWholeCut.Record rows repeats p slots) => + μ.pushforward (OriginalWholeCut.reconstructRecord rows repeats p slots)) + (readRecord_law rows repeats p chosen q slots).symm + _ = (WholeArraySampler.tapeLaw rows repeats (p.append (.step chosen q)) slots).pushforward + (fun ω => OriginalWholeCut.reconstructRecord rows repeats p slots + (OriginalWholeCut.readRecord rows repeats p chosen q slots ω)) := + FiniteDistribution.pushforward_comp _ _ _ + _ = _ := congrArg + (fun f : WholeArraySampler.Tape rows repeats (p.append (.step chosen q)) slots → + Arrays slots rows => + (WholeArraySampler.tapeLaw rows repeats (p.append (.step chosen q)) slots).pushforward f) + (funext (fun ω => OriginalWholeCut.reconstruct_original rows repeats p chosen q slots ω)) + +end +end PerfectCompleteness.OriginalWholeCutLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/OwnLawHeavyList.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/OwnLawHeavyList.lean new file mode 100644 index 0000000000000000000000000000000000000000..6b8405d56a61b065cacdbd46be72581acefad9a1 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/OwnLawHeavyList.lean @@ -0,0 +1,79 @@ +import OAI.Computability.PerfectCompleteness.Construction.OwnBucketBias + +namespace OAI + +section + +namespace PerfectCompleteness.OwnLawHeavyList + +open QuarterBalance +open HiddenBucketBias (recursiveLaw) +open UniqueGamesTheorem.Foundations.Games +open scoped TensorProduct Classical + +noncomputable section + +variable {V : Type*} [AddCommGroup V] [Module F2 V] [Fintype V] + +local instance dualFintype : Fintype (Module.Dual F2 V) := + Fintype.ofInjective (fun f : Module.Dual F2 V => (f : V → F2)) DFunLike.coe_injective + +def character (f : Module.Dual F2 V) (x : V) : ℝ := sign (f x) + +omit [Fintype V] in +theorem character_sq (f : Module.Dual F2 V) (x : V) : character f x ^ 2 = 1 := by + unfold character sign + split <;> norm_num + +omit [Fintype V] in +theorem character_pair (f g : Module.Dual F2 V) (x : V) : + character f x * character g x = character (f - g) x := by + simp only [character, sub_eq_add_neg, + LinearMap.add_apply, LinearMap.neg_apply, ZMod.neg_eq_self_mod_two, sign_add] + +def heavyList (μ : FiniteDistribution V) (target : V → ℝ) (threshold : ℝ) : + Finset (Module.Dual F2 V) := + SmallBias.heavySet μ character target threshold + +theorem mem_heavyList (μ : FiniteDistribution V) (target : V → ℝ) (threshold : ℝ) + (f : Module.Dual F2 V) : + f ∈ heavyList μ target threshold ↔ + threshold ≤ |μ.expectation (fun x => target x * character f x)| := by + simp only [heavyList, SmallBias.heavySet, Finset.mem_filter, Finset.mem_univ, true_and] + +theorem heavyList_card_le (μ : FiniteDistribution V) (target : V → ℝ) + (threshold bias : ℝ) (hthreshold : 0 < threshold) (hbias : 0 ≤ bias) + (hsmall : bias ≤ threshold ^ 2 / 2) (htarget : ∀ x, target x ^ 2 ≤ 1) + (hdual : ∀ f : Module.Dual F2 V, f ≠ 0 → + |μ.expectation (fun x => sign (f x))| ≤ bias) : + ((heavyList μ target threshold).card : ℝ) ≤ 2 / threshold ^ 2 := by + apply SmallBias.heavySet_card_le μ character target threshold bias + hthreshold hbias hsmall htarget (fun f x => (character_sq f x).le) + intro f g hfg + simp only [character_pair] + exact hdual (f - g) (sub_ne_zero.mpr hfg) + +universe u +variable {branch : Nat → Nat} {n m width : Nat} + +theorem own_heavyList_card_le (W : Submodule F2 (Fin width → F2)) + (repeats : Nat → Nat) (hrep : RecursiveSamplerBias.RepetitionsBalanced repeats) + (p : DescendantSpaces.Path branch n m) + (A : RecursiveSpaces.Slots branch n → Type u) [∀ s, Finite (A s)] + (target : (W ⊗[F2] RecursiveSpaces.space F2 branch n A) → ℝ) + (threshold : ℝ) (hthreshold : 0 < threshold) + (hsmall : (7 / 8 : ℝ) ^ repeats n ≤ threshold ^ 2 / 2) + (htarget : ∀ x, target x ^ 2 ≤ 1) : + ((heavyList (recursiveLaw W repeats p A) target threshold).card : ℝ) ≤ + 2 / threshold ^ 2 := by + let : Fintype (RecursiveSpaces.space F2 branch n A) := Fintype.ofFinite _ + apply heavyList_card_le (recursiveLaw W repeats p A) target threshold + ((7 / 8 : ℝ) ^ repeats n) hthreshold (pow_nonneg (by norm_num) _) hsmall htarget + exact fun f hf => OwnBucketBias.bias_le W repeats hrep p A f hf + +end +end PerfectCompleteness.OwnLawHeavyList + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/PreliminarySampler.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/PreliminarySampler.lean new file mode 100644 index 0000000000000000000000000000000000000000..7579d9b508567e9af163f39ea7c52a312471a752 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/PreliminarySampler.lean @@ -0,0 +1,159 @@ +import OAI.Computability.PerfectCompleteness.Foundations.GeometricPathLemmas +import OAI.Computability.PerfectCompleteness.Reduction.CompletionAlphabetLemmas +import OAI.Computability.PerfectCompleteness.Sampling.WholeArraySampler + +namespace OAI + +section + +namespace PerfectCompleteness.PreliminarySampler + +open RecursiveSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open scoped Classical + +noncomputable section + +variable {v m n t : Nat} {branch rows repeats : Nat → Nat} + +abbrev Questions (branch : Nat → Nat) (n t m : Nat) := + Slots branch n → Fin t → Fin m + +def endpoints (E : Questions branch n t m) : + Slots branch n → Fin t → SourceKeys.Endpoint v m := + fun leaf coordinate => .clause (E leaf coordinate) + +abbrev Base (branch : Nat → Nat) (n t m : Nat) := + Questions branch n t m × Slots branch n + +abbrev ArrayTape (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (b : Base branch n t m) := + WholeArraySampler.Tape rows repeats (GeometricPath.leafPath b.2) + (sourceSlots clauses (endpoints b.1)) + +abbrev Choice (rows : Nat → Nat) (leaf : Slots branch n) := + (level : Fin n) × BucketSampler.Direction + (rows (Nodes.height (GeometricPath.nodeAtLevel leaf level))) + +abbrev Raw (clauses : Fin m → SourceClause.NormalizedClause v) + (branch : Nat → Nat) (n t : Nat) (rows repeats : Nat → Nat) := + (b : Base branch n t m) × (ArrayTape clauses rows repeats b × Choice rows b.2) + +theorem directionNonempty (width : Nat) (positive : 0 < width) : + Nonempty (BucketSampler.Direction width) := by + refine ⟨⟨fun _ => 1, ?_⟩⟩ + intro hz + have h := congrFun hz ⟨0, positive⟩ + change (1 : BucketSampler.F2) = 0 at h + exact one_ne_zero h + +def questionsLaw [NeZero m] : FiniteDistribution (Questions branch n t m) := + FiniteDistribution.uniform _ + +theorem questionsLaw_eq_product [NeZero m] : + questionsLaw (branch := branch) (n := n) (t := t) (m := m) = + FiniteProduct.law (fun _ : Slots branch n => + FiniteProduct.law (fun _ : Fin t => FiniteDistribution.uniform (Fin m))) := by + simp only [UniformLinearImage.law_uniform] + rfl + +def baseLaw [NeZero m] (hbranch : ∀ k < n, 0 < branch k) : + FiniteDistribution (Base branch n t m) := + questionsLaw.product (GeometricPath.law n hbranch) + +def choiceLaw (leaf : Slots branch n) (hn : 0 < n) + (hrows : ∀ k, 0 < rows (k + 1)) : FiniteDistribution (Choice rows leaf) := by + letI : Nonempty (Fin n) := ⟨⟨0, hn⟩⟩ + exact CompletionSoundness.sigmaLaw (FiniteDistribution.uniform (Fin n)) fun level => by + letI : Nonempty (BucketSampler.Direction + (rows (Nodes.height (GeometricPath.nodeAtLevel leaf level)))) := + directionNonempty _ (by rw [GeometricPath.nodeAtLevel_height]; exact hrows level.val) + exact FiniteDistribution.uniform _ + +theorem choiceLaw_level (leaf : Slots branch n) (hn : 0 < n) + (hrows : ∀ k, 0 < rows (k + 1)) (event : Fin n → Bool) : + (choiceLaw leaf hn hrows).probability (fun c => event c.1) = + (by + letI : Nonempty (Fin n) := ⟨⟨0, hn⟩⟩ + exact (FiniteDistribution.uniform (Fin n)).probability event) := by + exact CompletionSoundness.sigmaLaw_probability_first _ _ event + +def conditionalLaw (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hn : 0 < n) + (hrows : ∀ k, 0 < rows (k + 1)) (b : Base branch n t m) : + FiniteDistribution (ArrayTape clauses rows repeats b × Choice rows b.2) := + (WholeArraySampler.tapeLaw rows repeats (GeometricPath.leafPath b.2) + (sourceSlots clauses (endpoints b.1))).product (choiceLaw b.2 hn hrows) + +def law [NeZero m] (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hn : 0 < n) + (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) : + FiniteDistribution (Raw clauses branch n t rows repeats) := + CompletionSoundness.sigmaLaw (baseLaw hbranch) + (conditionalLaw clauses rows repeats hn hrows) + +theorem law_base [NeZero m] (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hn : 0 < n) + (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) + (event : Base branch n t m → Bool) : + (law clauses rows repeats hn hbranch hrows).probability (fun e => event e.1) = + (baseLaw hbranch).probability event := + CompletionSoundness.sigmaLaw_probability_first _ _ event + +theorem law_probability [NeZero m] (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hn : 0 < n) + (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) + (event : Raw clauses branch n t rows repeats → Bool) : + (law clauses rows repeats hn hbranch hrows).probability event = + (baseLaw hbranch).expectation (fun b => + (conditionalLaw clauses rows repeats hn hrows b).probability + (fun tapeAndChoice => event ⟨b, tapeAndChoice⟩)) := + CompletionSoundness.sigmaLaw_probability _ _ event + +def family (clauses : Fin m → SourceClause.NormalizedClause v) + (branch : Nat → Nat) (n t : Nat) (rows repeats : Nat → Nat) : + HierarchicalGame.Family clauses branch n t rows (Raw clauses branch n t rows repeats) where + endpoints e := endpoints e.1.1 + arrays e := WholeArraySampler.evaluate rows repeats (GeometricPath.leafPath e.1.2) + (sourceSlots clauses (endpoints e.1.1)) e.2.1 + selected e := GeometricPath.nodeAtLevel e.1.2 e.2.2.1 + direction e := e.2.2.2.val + nonzero e := e.2.2.2.property + +theorem family_selected_height (clauses : Fin m → SourceClause.NormalizedClause v) + (branch : Nat → Nat) (n t : Nat) (rows repeats : Nat → Nat) + (e : Raw clauses branch n t rows repeats) : + Nodes.height ((family clauses branch n t rows repeats).selected e) = e.2.2.1.val + 1 := + GeometricPath.nodeAtLevel_height _ _ + +def game [NeZero m] (clauses : Fin m → SourceClause.NormalizedClause v) + (branch : Nat → Nat) (n t : Nat) (rows repeats : Nat → Nat) (hn : 0 < n) + (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) := + HierarchicalGame.game (family clauses branch n t rows repeats) + (law clauses rows repeats hn hbranch hrows) + +theorem edge_at_most_two (clauses : Fin m → SourceClause.NormalizedClause v) + (branch : Nat → Nat) (n t : Nat) (rows repeats : Nat → Nat) + (e : Raw clauses branch n t rows repeats) + (Q : HierarchicalGame.RightLabel (family clauses branch n t rows repeats) + (HierarchicalGame.rightAt (family clauses branch n t rows repeats) e)) : + Nat.card {P : HierarchicalGame.LeftLabel (family clauses branch n t rows repeats) + (HierarchicalGame.leftAt (family clauses branch n t rows repeats) e) // + HierarchicalGame.edge (family clauses branch n t rows repeats) e P = Q} ≤ 2 := + HierarchicalGame.edge_at_most_two _ e Q + +theorem completeness [NeZero m] (clauses : Fin m → SourceClause.NormalizedClause v) + (branch : Nat → Nat) (n t : Nat) (rows repeats : Nat → Nat) (hn : 0 < n) + (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) + (assignment : Fin v → Bool) (hsat : ∀ c, (clauses c).clause.eval assignment = true) : + (game clauses branch n t rows repeats hn hbranch hrows).success + (HierarchicalGame.satisfyingStrategy (family clauses branch n t rows repeats) + assignment hsat) = 1 := + HierarchicalGame.success_satisfyingStrategy _ _ assignment hsat + +end +end PerfectCompleteness.PreliminarySampler + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/RationalFiniteLawLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/RationalFiniteLawLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..fb07f3550a7354ab8709bb968e4efc7b8191180d --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/RationalFiniteLawLemmas.lean @@ -0,0 +1,223 @@ +import Mathlib.Algebra.BigOperators.GroupWithZero.Finset +import Mathlib.Data.Rat.BigOperators +import Mathlib.Data.Rat.Cast.Order +import OAI.Computability.PerfectCompleteness.Foundations.FiniteProduct +import OAI.Computability.PerfectCompleteness.Reduction.CompletionSoundness +import OAI.Computability.UniqueGames.Games.FinishBoundsLemmas + +namespace OAI + + +namespace PerfectCompleteness.RationalFiniteLaw + +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +noncomputable section + +structure RationalLaw {E : Type*} [Fintype E] (μ : FiniteDistribution E) where + weights : E → ℚ + positive : ∀ e, 0 < weights e + total : ∑ e, weights e = 1 + cast_weight : ∀ e, μ.weight e = (weights e : ℝ) + +def uniform (E : Type*) [Fintype E] [Nonempty E] : + RationalLaw (FiniteDistribution.uniform E) where + weights _ := 1 / (Fintype.card E : ℚ) + positive _ := div_pos zero_lt_one (Nat.cast_pos.mpr Fintype.card_pos) + total := by + have hn : (Fintype.card E : ℚ) ≠ 0 := + Nat.cast_ne_zero.mpr Fintype.card_ne_zero + simp only [Finset.sum_const, Finset.card_univ, nsmul_eq_mul, one_div] + exact mul_inv_cancel₀ hn + cast_weight _ := by + change (1 / (Fintype.card E : ℝ)) = ((1 / (Fintype.card E : ℚ) : ℚ) : ℝ) + simp only [Rat.cast_div, Rat.cast_one, Rat.cast_natCast] + +def pi {I : Type*} [Fintype I] [DecidableEq I] + {E : I → Type*} [∀ i, Fintype (E i)] + (P : (i : I) → FiniteDistribution (E i)) (r : ∀ i, RationalLaw (P i)) : + RationalLaw (FiniteProduct.law P) where + weights x := ∏ i, (r i).weights (x i) + positive x := Finset.prod_pos (fun i _ => (r i).positive (x i)) + total := by + rw [← Fintype.prod_sum] + simp only [RationalLaw.total, Finset.prod_const_one] + cast_weight x := by + change (∏ i, (P i).weight (x i)) = ((∏ i, (r i).weights (x i) : ℚ) : ℝ) + rw [Rat.cast_prod] + exact Finset.prod_congr rfl (fun i _ => (r i).cast_weight (x i)) + +def product {E F : Type*} [Fintype E] [Fintype F] + {μ : FiniteDistribution E} {ν : FiniteDistribution F} + (r : RationalLaw μ) (s : RationalLaw ν) : RationalLaw (μ.product ν) where + weights x := r.weights x.1 * s.weights x.2 + positive x := mul_pos (r.positive x.1) (s.positive x.2) + total := by + rw [Fintype.sum_prod_type] + simp_rw [← Finset.mul_sum, s.total, mul_one] + exact r.total + cast_weight x := by + change μ.weight x.1 * ν.weight x.2 = ((r.weights x.1 * s.weights x.2 : ℚ) : ℝ) + rw [Rat.cast_mul, r.cast_weight, s.cast_weight] + +def sigma {E : Type*} {F : E → Type*} [Fintype E] [∀ e, Fintype (F e)] + {μ : FiniteDistribution E} {ν : ∀ e, FiniteDistribution (F e)} + (r : RationalLaw μ) (s : ∀ e, RationalLaw (ν e)) : + RationalLaw (CompletionSoundness.sigmaLaw μ ν) where + weights x := r.weights x.1 * (s x.1).weights x.2 + positive x := mul_pos (r.positive x.1) ((s x.1).positive x.2) + total := by + rw [Fintype.sum_sigma] + calc + _ = ∑ e, r.weights e := by + apply Finset.sum_congr rfl + intro e _ + change (∑ f : F e, r.weights e * (s e).weights f) = r.weights e + rw [← Finset.mul_sum, (s e).total, mul_one] + _ = 1 := r.total + cast_weight x := by + change μ.weight x.1 * (ν x.1).weight x.2 = + ((r.weights x.1 * (s x.1).weights x.2 : ℚ) : ℝ) + rw [Rat.cast_mul, r.cast_weight, (s x.1).cast_weight] + +def transport {E F : Type*} [Fintype E] [Fintype F] + {μ : FiniteDistribution E} (r : RationalLaw μ) (e : E ≃ F) : + RationalLaw (μ.transport e) where + weights f := r.weights (e.symm f) + positive f := r.positive (e.symm f) + total := (e.symm.sum_comp r.weights).trans r.total + cast_weight f := r.cast_weight (e.symm f) + +theorem real_positive {E : Type*} [Fintype E] {μ : FiniteDistribution E} + (r : RationalLaw μ) (e : E) : 0 < μ.weight e := by + rw [r.cast_weight] + exact Rat.cast_pos.mpr (r.positive e) + +end +end PerfectCompleteness.RationalFiniteLaw + + + +namespace PerfectCompleteness.RecursiveSamplerBiasProducts + +open scoped BigOperators +open UniqueGamesTheorem.Foundations.Games + +def pairTapeEquiv (R : Nat) (V : Type*) : + ((Fin R × Bool) → V) ≃ (Fin R → V × V) where + toFun x h := (x (h, false), x (h, true)) + invFun y hb := if hb.2 then (y hb.1).2 else (y hb.1).1 + left_inv x := by + funext hb + rcases hb with ⟨h, b⟩ + cases b <;> rfl + right_inv y := by + funext h + rfl + +noncomputable section + +variable {V W : Type*} [Fintype V] [Fintype W] + +theorem pairTape_law (R : Nat) (μ : FiniteDistribution V) : + (FiniteProduct.law (fun _ : Fin R × Bool => μ)).pushforward (pairTapeEquiv R V) = + FiniteProduct.law (fun _ : Fin R => μ.product μ) := by + rw [← FiniteDistribution.transport_eq_pushforward] + apply FiniteDistribution.eq_of_weight_eq + intro y + change (∏ hb : Fin R × Bool, + μ.weight (if hb.2 then (y hb.1).2 else (y hb.1).1)) = + ∏ h : Fin R, μ.weight (y h).1 * μ.weight (y h).2 + rw [Fintype.prod_prod_type] + apply Finset.prod_congr rfl + intro h _ + simp [mul_comm] + +theorem expectation_pairs (R : Nat) (μ : FiniteDistribution V) (φ : V × V → ℝ) : + (FiniteProduct.law (fun _ : Fin R × Bool => μ)).expectation + (fun x => ∏ h : Fin R, φ (x (h, false), x (h, true))) = + ((μ.product μ).expectation φ) ^ R := by + calc + _ = ((FiniteProduct.law (fun _ : Fin R × Bool => μ)).pushforward + (pairTapeEquiv R V)).expectation (fun y => ∏ h : Fin R, φ (y h)) := + (FiniteDistribution.expectation_pushforward _ _ _).symm + _ = (FiniteProduct.law (fun _ : Fin R => μ.product μ)).expectation + (fun y => ∏ h : Fin R, φ (y h)) := by rw [pairTape_law] + _ = ∏ _h : Fin R, (μ.product μ).expectation φ := + FiniteProduct.expectation_product _ (fun _ => φ) + _ = _ := by simp + +theorem expectation_product_mul (μ : FiniteDistribution V) (ν : FiniteDistribution W) + (f : V → ℝ) (g : W → ℝ) : + (μ.product ν).expectation (fun z => f z.1 * g z.2) = + μ.expectation f * ν.expectation g := by + change (∑ z : V × W, (μ.weight z.1 * ν.weight z.2) * (f z.1 * g z.2)) = + (∑ v : V, μ.weight v * f v) * (∑ w : W, ν.weight w * g w) + rw [Fintype.sum_prod_type, Finset.sum_mul_sum] + apply Finset.sum_congr rfl + intro v _ + apply Finset.sum_congr rfl + intro w _ + exact mul_mul_mul_comm _ _ _ _ + +end +end PerfectCompleteness.RecursiveSamplerBiasProducts + + + +noncomputable section + +open scoped BigOperators +open UniqueGamesTheorem.Foundations.Games + +namespace PerfectCompleteness.FiniteProduct + +variable {I : Type*} [Fintype I] [DecidableEq I] + {Ω Γ : I → Type*} [∀ i, Fintype (Ω i)] [∀ i, Fintype (Γ i)] + +theorem pushforward_map (P : (i : I) → FiniteDistribution (Ω i)) + (f : (i : I) → Ω i → Γ i) : + (law P).pushforward (fun x i => f i (x i)) = + law (fun i => (P i).pushforward (f i)) := by + classical + apply FiniteDistribution.eq_of_weight_eq + intro y + simp only [FiniteDistribution.pushforward, law] + rw [Fintype.prod_sum] + apply Finset.sum_congr rfl + intro x _ + rw [Fintype.prod_ite_zero] + simp only [funext_iff] + +end PerfectCompleteness.FiniteProduct + +namespace UniqueGamesTheorem.Foundations.Games.FiniteDistribution + +@[simp] theorem pushforward_id {A : Type*} [Fintype A] + (μ : FiniteDistribution A) : μ.pushforward id = μ := by + classical + apply eq_of_weight_eq + intro a + simp [pushforward] + +theorem product_pushforward_snd {A B : Type*} [Fintype A] [Fintype B] + (μ : FiniteDistribution A) (ν : FiniteDistribution B) : + (μ.product ν).pushforward Prod.snd = ν := by + classical + apply eq_of_weight_eq + intro b + change (∑ z : A × B, + if z.2 = b then μ.weight z.1 * ν.weight z.2 else 0) = ν.weight b + calc + _ = ∑ a : A, μ.weight a * ν.weight b := by + rw [Fintype.sum_prod_type] + simp + _ = (∑ a : A, μ.weight a) * ν.weight b := (Finset.sum_mul _ _ _).symm + _ = _ := by rw [μ.normalized, one_mul] + +end UniqueGamesTheorem.Foundations.Games.FiniteDistribution + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/RecordSeedSamplingLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/RecordSeedSamplingLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..7ee1ca0c80430dcd293ac10f6c3fdc8cdaa8ac03 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/RecordSeedSamplingLemmas.lean @@ -0,0 +1,325 @@ +import Mathlib.Data.Fintype.EquivFin +import Mathlib.Data.Fintype.Sum +import OAI.Computability.PerfectCompleteness.Construction.DescendantSpacesLemmas +import OAI.Computability.PerfectCompleteness.Decoding.DependentDecoderSampling +import OAI.Computability.PerfectCompleteness.Sampling.RecursiveSamplerLaws + +namespace OAI + + +namespace PerfectCompleteness.RecordSeedSampling + +noncomputable section + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games + +variable {X R : Type*} [Fintype X] [Fintype R] [DecidableEq R] + {Seed : R → Type*} [∀ r, Fintype (Seed r)] + +def freshLaw (P : FiniteDistribution X) (record : X → R) + (kernel : (r : R) → FiniteDistribution (Seed r)) : + FiniteDistribution (Σ x : X, Seed (record x)) := + CompletionSoundness.sigmaLaw P (fun x => kernel (record x)) + +theorem probability_eq_table_mean (P : FiniteDistribution X) (record : X → R) + (kernel : (r : R) → FiniteDistribution (Seed r)) + (event : (x : X) → Seed (record x) → Bool) : + (freshLaw P record kernel).probability (fun z => event z.1 z.2) = + (FiniteProduct.law kernel).expectation + (fun table => P.probability (fun x => event x (table (record x)))) := by + rw [freshLaw, CompletionSoundness.sigmaLaw_probability] + calc + _ = P.expectation (fun x => (FiniteProduct.law kernel).probability + (fun table => event x (table (record x)))) := by + apply FiniteDistribution.expectation_congr + intro x + have h := FiniteDistribution.probability_pushforward + (FiniteProduct.law kernel) (fun table => table (record x)) (event x) + rw [FiniteProduct.eval_pushforward] at h + exact h + _ = P.expectation (fun x => (FiniteProduct.law kernel).expectation + (fun table => if event x (table (record x)) then 1 else 0)) := by + simp only [FiniteDistribution.probability, FiniteDistribution.expectation, + mul_ite, mul_one, mul_zero] + _ = (FiniteProduct.law kernel).expectation (fun table => P.expectation + (fun x => if event x (table (record x)) then 1 else 0)) := + FiniteDistribution.expectation_comm P (FiniteProduct.law kernel) _ + _ = _ := by + simp only [FiniteDistribution.probability, FiniteDistribution.expectation, + mul_ite, mul_one, mul_zero] + +theorem supported_row (kernel : (r : R) → FiniteDistribution (Seed r)) + (table : (r : R) → Seed r) + (hs : (FiniteProduct.law kernel).weight table ≠ 0) (r : R) : + (kernel r).weight (table r) ≠ 0 := by + intro hr + exact hs (Finset.prod_eq_zero (Finset.mem_univ r) hr) + +theorem probability_supported_guard (P : FiniteDistribution X) (event : X → Bool) : + P.probability (fun x => decide (P.weight x ≠ 0) && event x) = P.probability event := by + unfold FiniteDistribution.probability + apply Finset.sum_congr rfl + intro x _ + by_cases hx : P.weight x = 0 + · simp only [hx, ne_eq, not_true_eq_false, decide_false, Bool.false_and, + ite_self] + · simp only [decide_eq_true hx, Bool.true_and] + +theorem probability_le_of_supported_tables (P : FiniteDistribution X) (record : X → R) + (kernel : (r : R) → FiniteDistribution (Seed r)) + (event : (x : X) → Seed (record x) → Bool) (bound : ℝ) + (hbound : ∀ table, (FiniteProduct.law kernel).weight table ≠ 0 → + P.probability (fun x => decide (P.weight x ≠ 0) && event x (table (record x))) ≤ bound) : + (freshLaw P record kernel).probability (fun z => event z.1 z.2) ≤ bound := by + rw [probability_eq_table_mean] + apply DecoderTableAdmissibility.expectation_le_of_support + intro table hs + rw [← probability_supported_guard P (fun x => event x (table (record x)))] + exact hbound table hs + +end +end PerfectCompleteness.RecordSeedSampling + + + +namespace PerfectCompleteness.RecursiveSampler + +open PointwiseSpaces RecursiveSpaces DescendantSpaces +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators + +universe u w + +variable {branch : Nat → Nat} {n m : Nat} + +abbrev OffPath (i : Fin (branch n)) := {j : Fin (branch n) // j ≠ i} + +def DrawIndex (repeats : Nat → Nat) : {n m : Nat} → Path branch n m → Type + | _, _, .refl _ => Unit + | n + 1, _, .step i p => + OffPath i ⊕ ((Fin (repeats (n + 1)) × Bool) × DrawIndex repeats p) + +noncomputable instance drawIndexFintype (repeats : Nat → Nat) (p : Path branch n m) : + Fintype (DrawIndex repeats p) := by + induction p with + | refl n => exact inferInstanceAs (Fintype Unit) + | @step n m i p ih => + letI : Fintype (DrawIndex repeats p) := ih + exact inferInstanceAs (Fintype + (OffPath i ⊕ ((Fin (repeats (n + 1)) × Bool) × DrawIndex repeats p))) + +noncomputable instance drawIndexDecidableEq (repeats : Nat → Nat) (p : Path branch n m) : + DecidableEq (DrawIndex repeats p) := by + induction p with + | refl n => exact inferInstanceAs (DecidableEq Unit) + | @step n m i p ih => + letI : DecidableEq (DrawIndex repeats p) := ih + exact inferInstanceAs (DecidableEq + (OffPath i ⊕ ((Fin (repeats (n + 1)) × Bool) × DrawIndex repeats p))) + +variable (𝕜 : Type w) [Field 𝕜] + +def DrawSpace (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n m) → (A : Slots branch n → Type u) → + DrawIndex repeats p → Type (max u w) + | n, _, .refl _, A, _ => space 𝕜 branch n A + | n + 1, _, .step i p, A, j => + match j with + | Sum.inl j => squareSpace (space 𝕜 branch n (childFamily A j.val)) + | Sum.inr j => DrawSpace 𝕜 repeats p (childFamily A i) j.2 + +abbrev Tape (repeats : Nat → Nat) (p : Path branch n m) + (A : Slots branch n → Type u) := + (j : DrawIndex repeats p) → DrawSpace 𝕜 repeats p A j + +def zeroDraw (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n m) → (A : Slots branch n → Type u) → + (j : DrawIndex repeats p) → DrawSpace 𝕜 repeats p A j + | n, _, .refl _, A, _ => (0 : space 𝕜 branch n A) + | n + 1, _, .step i p, A, j => + match j with + | Sum.inl j => (0 : squareSpace (space 𝕜 branch n (childFamily A j.val))) + | Sum.inr j => zeroDraw 𝕜 repeats p (childFamily A i) j.2 + +def zeroTape (repeats : Nat → Nat) (p : Path branch n m) + (A : Slots branch n → Type u) : Tape 𝕜 repeats p A := + zeroDraw 𝕜 repeats p A + +instance drawSpaceNonempty (repeats : Nat → Nat) (p : Path branch n m) + (A : Slots branch n → Type u) (j : DrawIndex repeats p) : + Nonempty (DrawSpace 𝕜 repeats p A j) := + ⟨zeroDraw 𝕜 repeats p A j⟩ + +instance tapeNonempty (repeats : Nat → Nat) (p : Path branch n m) + (A : Slots branch n → Type u) : Nonempty (Tape 𝕜 repeats p A) := + ⟨zeroTape 𝕜 repeats p A⟩ + +theorem drawSpace_finite [Finite 𝕜] (repeats : Nat → Nat) (p : Path branch n m) : + ∀ (A : Slots branch n → Type u), (∀ s, Finite (A s)) → + ∀ j : DrawIndex repeats p, Finite (DrawSpace 𝕜 repeats p A j) := by + induction p with + | refl n => + intro A hA j + let : ∀ s, Finite (A s) := hA + change Finite (space 𝕜 branch n A) + infer_instance + | @step n m i p ih => + intro A hA j + cases j with + | inl j => + let : ∀ s, Finite ((childFamily A j.val) s) := fun s => hA (j.val, s) + change Finite (squareSpace (space 𝕜 branch n (childFamily A j.val))) + infer_instance + | inr j => + exact ih (childFamily A i) (fun s => hA (i, s)) j.2 + +instance drawSpaceFinite [Finite 𝕜] (repeats : Nat → Nat) (p : Path branch n m) + (A : Slots branch n → Type u) [∀ s, Finite (A s)] (j : DrawIndex repeats p) : + Finite (DrawSpace 𝕜 repeats p A j) := + drawSpace_finite 𝕜 repeats p A (fun _ => inferInstance) j + +noncomputable instance drawSpaceFintype [Finite 𝕜] (repeats : Nat → Nat) + (p : Path branch n m) (A : Slots branch n → Type u) [∀ s, Finite (A s)] + (j : DrawIndex repeats p) : Fintype (DrawSpace 𝕜 repeats p A j) := + Fintype.ofFinite _ + +def subTape (repeats : Nat → Nat) (i : Fin (branch n)) (p : Path branch n m) + (A : Slots branch (n + 1) → Type u) (t : Tape 𝕜 repeats (.step i p) A) + (h : Fin (repeats (n + 1))) (b : Bool) : + Tape 𝕜 repeats p (childFamily A i) := + fun j => t (.inr ((h, b), j)) + +theorem recursive_locations_distinct (repeats : Nat → Nat) + (i : Fin (branch n)) (p : Path branch n m) + (h h' : Fin (repeats (n + 1))) (b b' : Bool) + (j j' : DrawIndex repeats p) (hne : (h, b) ≠ (h', b')) : + (Sum.inr ((h, b), j) : DrawIndex repeats (.step i p)) ≠ + Sum.inr ((h', b'), j') := by + intro heq + exact hne (congrArg Prod.fst (Sum.inr.inj heq)) + +noncomputable section + +def combineFunction (A : Slots branch (n + 1) → Type u) (i : Fin (branch n)) + (r : Nat) + (ordinary : (j : OffPath i) → squareSpace (space 𝕜 branch n (childFamily A j.val))) + (left right : Fin r → space 𝕜 branch n (childFamily A i)) : Assignment A → 𝕜 := + (∑ j : OffPath i, pullback 𝕜 (childRestriction A j.val) (ordinary j).val) + + ∑ h : Fin r, pullback 𝕜 (childRestriction A i) ((left h).val * (right h).val) + +theorem combineFunction_mem (A : Slots branch (n + 1) → Type u) + (i : Fin (branch n)) (r : Nat) + (ordinary : (j : OffPath i) → squareSpace (space 𝕜 branch n (childFamily A j.val))) + (left right : Fin r → space 𝕜 branch n (childFamily A i)) : + combineFunction 𝕜 A i r ordinary left right ∈ space 𝕜 branch (n + 1) A := by + apply (space 𝕜 branch (n + 1) A).add_mem + · apply (space 𝕜 branch (n + 1) A).sum_mem + intro j _ + exact child_square_le_space A j.val (Submodule.mem_map_of_mem (ordinary j).property) + · apply (space 𝕜 branch (n + 1) A).sum_mem + intro h _ + exact child_square_le_space A i (Submodule.mem_map_of_mem + (mul_mem_squareSpace _ (left h).property (right h).property)) + +def combine (A : Slots branch (n + 1) → Type u) (i : Fin (branch n)) (r : Nat) + (ordinary : (j : OffPath i) → squareSpace (space 𝕜 branch n (childFamily A j.val))) + (left right : Fin r → space 𝕜 branch n (childFamily A i)) : + space 𝕜 branch (n + 1) A := + ⟨combineFunction 𝕜 A i r ordinary left right, + combineFunction_mem 𝕜 A i r ordinary left right⟩ + +@[simp] theorem combine_zero (A : Slots branch (n + 1) → Type u) + (i : Fin (branch n)) (r : Nat) : + combine 𝕜 A i r (fun _ => 0) (fun _ => 0) (fun _ => 0) = 0 := by + apply Subtype.ext + funext x + simp [combine, combineFunction, PointwiseSpaces.pullback] + +def evaluate (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n m) → (A : Slots branch n → Type u) → + Tape 𝕜 repeats p A → space 𝕜 branch n A + | _, _, .refl _, _, t => t () + | n + 1, _, .step i p, A, t => + combine 𝕜 A i (repeats (n + 1)) (fun j => t (.inl j)) + (fun h => evaluate 𝕜 repeats p (childFamily A i) + (subTape 𝕜 repeats i p A t h false)) + (fun h => evaluate 𝕜 repeats p (childFamily A i) + (subTape 𝕜 repeats i p A t h true)) + +@[simp] theorem evaluate_refl (repeats : Nat → Nat) + (A : Slots branch n → Type u) (t : Tape 𝕜 repeats (.refl n) A) : + evaluate 𝕜 repeats (.refl n) A t = t () := rfl + +theorem evaluate_step (repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) (A : Slots branch (n + 1) → Type u) + (t : Tape 𝕜 repeats (.step i p) A) : + evaluate 𝕜 repeats (.step i p) A t = + combine 𝕜 A i (repeats (n + 1)) (fun j => t (.inl j)) + (fun h => evaluate 𝕜 repeats p (childFamily A i) + (subTape 𝕜 repeats i p A t h false)) + (fun h => evaluate 𝕜 repeats p (childFamily A i) + (subTape 𝕜 repeats i p A t h true)) := rfl + +theorem evaluate_mem (repeats : Nat → Nat) (p : Path branch n m) + (A : Slots branch n → Type u) (t : Tape 𝕜 repeats p A) : + (evaluate 𝕜 repeats p A t).val ∈ space 𝕜 branch n A := + (evaluate 𝕜 repeats p A t).property + +@[simp] theorem evaluate_zeroTape (repeats : Nat → Nat) (p : Path branch n m) : + ∀ (A : Slots branch n → Type u), + evaluate 𝕜 repeats p A (zeroTape 𝕜 repeats p A) = 0 := by + induction p with + | refl n => + intro A + rfl + | @step n m i p ih => + intro A + change combine 𝕜 A i (repeats (n + 1)) (fun _ => 0) + (fun _ => evaluate 𝕜 repeats p (childFamily A i) + (zeroTape 𝕜 repeats p (childFamily A i))) + (fun _ => evaluate 𝕜 repeats p (childFamily A i) + (zeroTape 𝕜 repeats p (childFamily A i))) = 0 + simp only [ih, combine_zero] + +variable [Finite 𝕜] + +def tapeLaw (repeats : Nat → Nat) (p : Path branch n m) + (A : Slots branch n → Type u) [∀ s, Finite (A s)] : + FiniteDistribution (Tape 𝕜 repeats p A) := + FiniteProduct.law (fun j => FiniteDistribution.uniform (DrawSpace 𝕜 repeats p A j)) + +theorem tapeLaw_eq_uniform (repeats : Nat → Nat) (p : Path branch n m) + (A : Slots branch n → Type u) [∀ s, Finite (A s)] : + tapeLaw 𝕜 repeats p A = FiniteDistribution.uniform (Tape 𝕜 repeats p A) := + UniformLinearImage.law_uniform + +theorem tapeLaw_marginal (repeats : Nat → Nat) (p : Path branch n m) + (A : Slots branch n → Type u) [∀ s, Finite (A s)] (j : DrawIndex repeats p) : + (tapeLaw 𝕜 repeats p A).pushforward (fun t => t j) = + FiniteDistribution.uniform (DrawSpace 𝕜 repeats p A j) := + FiniteProduct.eval_pushforward _ j + +def law (repeats : Nat → Nat) (p : Path branch n m) + (A : Slots branch n → Type u) [∀ s, Finite (A s)] + [Fintype (space 𝕜 branch n A)] : FiniteDistribution (space 𝕜 branch n A) := + (tapeLaw 𝕜 repeats p A).pushforward (evaluate 𝕜 repeats p A) + +theorem law_refl_uniform (repeats : Nat → Nat) (A : Slots branch n → Type u) + [∀ s, Finite (A s)] [out : Fintype (space 𝕜 branch n A)] : + law 𝕜 repeats (.refl n) A = FiniteDistribution.uniform (space 𝕜 branch n A) := by + have hout : out = drawSpaceFintype 𝕜 repeats (.refl n) A () := Subsingleton.elim _ _ + cases hout + exact tapeLaw_marginal 𝕜 repeats (.refl n) A () + +theorem probability_law (repeats : Nat → Nat) (p : Path branch n m) + (A : Slots branch n → Type u) [∀ s, Finite (A s)] + [Fintype (space 𝕜 branch n A)] (event : space 𝕜 branch n A → Bool) : + (law 𝕜 repeats p A).probability event = + (tapeLaw 𝕜 repeats p A).probability (fun t => event (evaluate 𝕜 repeats p A t)) := + FiniteDistribution.probability_pushforward _ _ _ + +end +end PerfectCompleteness.RecursiveSampler + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/RecursiveSamplerLaws.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/RecursiveSamplerLaws.lean new file mode 100644 index 0000000000000000000000000000000000000000..d3594ef2f2a95f92ae7fa74cf68ac34210bccfc8 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/RecursiveSamplerLaws.lean @@ -0,0 +1,33 @@ +import OAI.Computability.PerfectCompleteness.Algebra.UniformLinearImage + +namespace OAI + +section + +namespace PerfectCompleteness.FiniteProduct + +open UniqueGamesTheorem.Foundations.Games + +noncomputable section + +variable {I : Type*} [Fintype I] [DecidableEq I] + {Ω : I → Type*} [∀ i, Fintype (Ω i)] + +theorem eval_pushforward (P : (i : I) → FiniteDistribution (Ω i)) (i : I) : + (law P).pushforward (fun x => x i) = P i := by + classical + apply FiniteDistribution.eq_of_weight_eq + intro a + calc + _ = (law P).expectation (fun x => if x i = a then 1 else 0) := by + simp [FiniteDistribution.pushforward, FiniteDistribution.expectation, mul_ite] + _ = (P i).expectation (fun b => if b = a then 1 else 0) := + expectation_eval P i (fun b => if b = a then (1 : ℝ) else 0) + _ = _ := by simp [FiniteDistribution.expectation, mul_ite] + +end +end PerfectCompleteness.FiniteProduct + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/RestrictionCrossLaw.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/RestrictionCrossLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..4f4fe05bf56ef88c13a370d5302a7f4fe2621c2d --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/RestrictionCrossLaw.lean @@ -0,0 +1,131 @@ +import OAI.Computability.PerfectCompleteness.Algebra.LowerCrossRank +import OAI.Computability.PerfectCompleteness.Foundations.DualQuotientRowsLemmas +import OAI.Computability.PerfectCompleteness.Sampling.RestrictionRowsLaw + +namespace OAI + +section + +namespace PerfectCompleteness.RestrictionCrossLaw + +noncomputable section + +open UniqueGamesTheorem.Integration.BinaryLinear (F2) +open UniqueGamesTheorem.Fourier.MatrixRestrictions +open UniqueGamesTheorem.Foundations.Games +open RestrictionRowsLaw DualQuotientRows + +variable {E C I : Type*} [AddCommGroup E] [Module F2 E] + [AddCommGroup C] [Module F2 C] [Fintype I] + (W : Submodule F2 E) (C' : Submodule F2 C) (b : Module.Basis I F2 C') + +def rowPairEquiv (m : Nat) : + ((Fin m ⊕ Fin m) → Module.Dual F2 (E ⧸ W)) ≃ₗ[F2] + ((Fin m → W.dualAnnihilator) × (Fin m → W.dualAnnihilator)) := + (LinearEquiv.piCongrRight + (fun _ : Fin m ⊕ Fin m => quotientRowEquiv W)).trans + (LinearEquiv.sumArrowLequivProdArrow + (Fin m) (Fin m) F2 W.dualAnnihilator) + +variable {m : Nat} (sel : (Fin m ⊕ Fin m) → I) + +def selectedPair : Parameter W C' →ₗ[F2] + ((Fin m → W.dualAnnihilator) × (Fin m → W.dualAnnihilator)) := + (rowPairEquiv W m).toLinearMap.comp (selectedRowsLinear W C' b sel) + +omit [Fintype I] in +@[simp] theorem selectedPair_fst (A : Parameter W C') (i : Fin m) : + (selectedPair W C' b sel A).1 i = + quotientRowEquiv W (rowsLinear W C' b A (sel (Sum.inl i))) := rfl + +omit [Fintype I] in +@[simp] theorem selectedPair_snd (A : Parameter W C') (j : Fin m) : + (selectedPair W C' b sel A).2 j = + quotientRowEquiv W (rowsLinear W C' b A (sel (Sum.inr j))) := rfl + +theorem selectedPair_surjective (hsel : Function.Injective sel) : + Function.Surjective (selectedPair W C' b sel) := + (rowPairEquiv W m).surjective.comp (selectedRowsLinear_surjective W C' b sel hsel) + +private theorem uniform_product {A B : Type*} [Fintype A] [Fintype B] + [Nonempty A] [Nonempty B] : + (FiniteDistribution.uniform A).product (FiniteDistribution.uniform B) = + FiniteDistribution.uniform (A × B) := by + apply FiniteDistribution.eq_of_weight_eq + intro p + change (1 / (Fintype.card A : ℝ)) * (1 / (Fintype.card B : ℝ)) = + 1 / (Fintype.card (A × B) : ℝ) + simp only [Fintype.card_prod, Nat.cast_mul, one_div, mul_inv] + +theorem selectedPair_law [Fintype (Parameter W C')] [Fintype W.dualAnnihilator] + (hsel : Function.Injective sel) : + (FiniteDistribution.uniform (Parameter W C')).pushforward (selectedPair W C' b sel) = + (FiniteDistribution.uniform (Fin m → W.dualAnnihilator)).product + (FiniteDistribution.uniform (Fin m → W.dualAnnihilator)) := by + rw [uniform_product] + exact UniformLinearImage.uniform_pushforward_linearMap + (selectedPair W C' b sel) (selectedPair_surjective W C' b sel hsel) + +omit [Fintype I] in +theorem coordinate_translate_left (coordinates : I → Module.Dual F2 C) + (hcoordinates : ∀ i, (coordinates i).comp C'.subtype = b.coord i) + (X : E →ₗ[F2] C) (A : Parameter W C') (i : Fin m) : + (coordinates (sel (Sum.inl i))).comp (translate W C' X A) = + (coordinates (sel (Sum.inl i))).comp X + + ((selectedPair W C' b sel A).1 i : Module.Dual F2 E) := by + simpa only [affineRow, selectedPair_fst, quotientRowEquiv_val] using + coordinate_translate W C' b coordinates hcoordinates X A (sel (Sum.inl i)) + +omit [Fintype I] in +theorem coordinate_translate_right (coordinates : I → Module.Dual F2 C) + (hcoordinates : ∀ i, (coordinates i).comp C'.subtype = b.coord i) + (X : E →ₗ[F2] C) (A : Parameter W C') (j : Fin m) : + (coordinates (sel (Sum.inr j))).comp (translate W C' X A) = + (coordinates (sel (Sum.inr j))).comp X + + ((selectedPair W C' b sel A).2 j : Module.Dual F2 E) := by + simpa only [affineRow, selectedPair_snd, quotientRowEquiv_val] using + coordinate_translate W C' b coordinates hcoordinates X A (sel (Sum.inr j)) + +theorem crossMatrix_law [Fintype (Parameter W C')] [Fintype W.dualAnnihilator] + (hsel : Function.Injective sel) + (coordinates : I → Module.Dual F2 C) + (hcoordinates : ∀ i, (coordinates i).comp C'.subtype = b.coord i) + (X : E →ₗ[F2] C) + (F : Module.Dual F2 E →ₗ[F2] Module.Dual F2 (Module.Dual F2 E)) : + (FiniteDistribution.uniform (Parameter W C')).pushforward + (Γ := Matrix (Fin m) (Fin m) F2) + (fun A i j => + F ((coordinates (sel (Sum.inl i))).comp (translate W C' X A)) + ((coordinates (sel (Sum.inr j))).comp (translate W C' X A))) = + ((FiniteDistribution.uniform (Fin m → W.dualAnnihilator)).product + (FiniteDistribution.uniform (Fin m → W.dualAnnihilator))).pushforward + (Γ := Matrix (Fin m) (Fin m) F2) + (fun p => LowerCrossRank.crossMatrix F W.dualAnnihilator + (fun i => (coordinates (sel (Sum.inl i))).comp X) + (fun j => (coordinates (sel (Sum.inr j))).comp X) p.1 p.2) := by + have hcross : + (fun (A : Parameter W C') => + (fun i j => F ((coordinates (sel (Sum.inl i))).comp (translate W C' X A)) + ((coordinates (sel (Sum.inr j))).comp (translate W C' X A)) : + Matrix (Fin m) (Fin m) F2)) = + (fun A => LowerCrossRank.crossMatrix F W.dualAnnihilator + (fun i => (coordinates (sel (Sum.inl i))).comp X) + (fun j => (coordinates (sel (Sum.inr j))).comp X) + (selectedPair W C' b sel A).1 (selectedPair W C' b sel A).2) := by + funext A i j + rw [coordinate_translate_left W C' b sel coordinates hcoordinates X A i, + coordinate_translate_right W C' b sel coordinates hcoordinates X A j] + rfl + rw [hcross, ← FiniteDistribution.pushforward_comp + (FiniteDistribution.uniform (Parameter W C')) (selectedPair W C' b sel) + (fun p => LowerCrossRank.crossMatrix F W.dualAnnihilator + (fun i => (coordinates (sel (Sum.inl i))).comp X) + (fun j => (coordinates (sel (Sum.inr j))).comp X) p.1 p.2), + selectedPair_law W C' b sel hsel] + +end +end PerfectCompleteness.RestrictionCrossLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/RestrictionRowsLaw.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/RestrictionRowsLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..5229cc1b5cccc4cf77505c256ab9785994e1791c --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/RestrictionRowsLaw.lean @@ -0,0 +1,211 @@ +import Mathlib.LinearAlgebra.Basis.Defs +import OAI.Computability.PerfectCompleteness.Algebra.UniformLinearImage +import OAI.Computability.PerfectCompleteness.Sampling.RationalFiniteLawLemmas +import OAI.Computability.UniqueGames.Analysis.MatrixRestrictions +import OAI.Computability.UniqueGames.Foundations.SamplingLemmas + +namespace OAI + + +namespace PerfectCompleteness.RestrictionRowsLaw + +noncomputable section + +open UniqueGamesTheorem.Integration.BinaryLinear +open UniqueGamesTheorem.Fourier.MatrixRestrictions +open UniqueGamesTheorem.Foundations.Games +open scoped Classical + +variable {E C I : Type*} [AddCommGroup E] [Module F2 E] + [AddCommGroup C] [Module F2 C] [Fintype I] + (W : Submodule F2 E) (C' : Submodule F2 C) (b : Module.Basis I F2 C') + +def rowsLinear : Parameter W C' →ₗ[F2] (I → Module.Dual F2 (E ⧸ W)) where + toFun A i := (b.coord i).comp A + map_add' A B := by + funext i + apply LinearMap.ext + intro x + exact map_add (b.coord i) (A x) (B x) + map_smul' a A := by + funext i + apply LinearMap.ext + intro x + exact map_smul (b.coord i) a (A x) + +omit [Fintype I] in +@[simp] theorem rowsLinear_apply (A : Parameter W C') (i : I) : + rowsLinear W C' b A i = (b.coord i).comp A := rfl + +def fromRows (rows : I → Module.Dual F2 (E ⧸ W)) : Parameter W C' := + b.equivFun.symm.toLinearMap.comp (LinearMap.pi rows) + +@[simp] theorem rowsLinear_fromRows (rows : I → Module.Dual F2 (E ⧸ W)) : + rowsLinear W C' b (fromRows W C' b rows) = rows := by + funext i + apply LinearMap.ext + intro x + exact b.coord_equivFun_symm i (fun j => rows j x) + +theorem rowsLinear_surjective : Function.Surjective (rowsLinear W C' b) := + fun rows => ⟨fromRows W C' b rows, rowsLinear_fromRows W C' b rows⟩ + +omit [Fintype I] in +theorem rowsLinear_injective : Function.Injective (rowsLinear W C' b) := by + intro A B h + apply LinearMap.ext + intro x + apply b.repr.injective + ext i + exact congrArg (fun rows : I → Module.Dual F2 (E ⧸ W) => rows i x) h + +def rowsEquiv : Parameter W C' ≃ₗ[F2] (I → Module.Dual F2 (E ⧸ W)) := + LinearEquiv.ofBijective (rowsLinear W C' b) + ⟨rowsLinear_injective W C' b, rowsLinear_surjective W C' b⟩ + +section Selection + +variable {J : Type*} (sel : J → I) + +def selectLinear : (I → Module.Dual F2 (E ⧸ W)) →ₗ[F2] + (J → Module.Dual F2 (E ⧸ W)) := + LinearMap.pi (fun j => LinearMap.proj (sel j)) + +omit [Fintype I] in +theorem selectLinear_surjective (hsel : Function.Injective sel) : + Function.Surjective (selectLinear W sel) := + hsel.surjective_comp_right + +def selectedRowsLinear : Parameter W C' →ₗ[F2] (J → Module.Dual F2 (E ⧸ W)) := + (selectLinear W sel).comp (rowsLinear W C' b) + +omit [Fintype I] in +@[simp] theorem selectedRowsLinear_apply (A : Parameter W C') (j : J) : + selectedRowsLinear W C' b sel A j = (b.coord (sel j)).comp A := rfl + +theorem selectedRowsLinear_surjective (hsel : Function.Injective sel) : + Function.Surjective (selectedRowsLinear W C' b sel) := + (selectLinear_surjective W sel hsel).comp (rowsLinear_surjective W C' b) + +end Selection + +section Uniform + +variable [Fintype (Parameter W C')] [Fintype (Module.Dual F2 (E ⧸ W))] + +theorem uniform_rowsLinear : + (FiniteDistribution.uniform (Parameter W C')).pushforward (rowsLinear W C' b) = + FiniteDistribution.uniform (I → Module.Dual F2 (E ⧸ W)) := + UniformLinearImage.uniform_pushforward_linearMap + (rowsLinear W C' b) (rowsLinear_surjective W C' b) + +theorem uniform_rows_law [DecidableEq I] : + (FiniteDistribution.uniform (Parameter W C')).pushforward (rowsLinear W C' b) = + FiniteProduct.law (fun _ : I => FiniteDistribution.uniform + (Module.Dual F2 (E ⧸ W))) := by + rw [UniformLinearImage.law_uniform] + exact UniformLinearImage.uniform_pushforward_linearMap + (rowsLinear W C' b) (rowsLinear_surjective W C' b) + +private theorem uniform_add_left {V : Type*} [AddGroup V] [Fintype V] (offset : V) : + (FiniteDistribution.uniform V).pushforward (fun x => offset + x) = + FiniteDistribution.uniform V := by + change (FiniteDistribution.uniform V).pushforward (Equiv.addLeft offset) = _ + rw [FiniteDistribution.pushforward_equiv] + apply FiniteDistribution.eq_of_weight_eq + intro x + rfl + +theorem uniform_translated_rows (offsets : I → Module.Dual F2 (E ⧸ W)) : + (FiniteDistribution.uniform (Parameter W C')).pushforward + (fun A => offsets + rowsLinear W C' b A) = + FiniteDistribution.uniform (I → Module.Dual F2 (E ⧸ W)) := by + rw [← FiniteDistribution.pushforward_comp + (FiniteDistribution.uniform (Parameter W C')) (rowsLinear W C' b) + (fun rows => offsets + rows), uniform_rowsLinear] + exact uniform_add_left offsets + +variable {J : Type*} [Fintype J] (sel : J → I) + +theorem uniform_selectedRowsLinear (hsel : Function.Injective sel) : + (FiniteDistribution.uniform (Parameter W C')).pushforward + (selectedRowsLinear W C' b sel) = + FiniteDistribution.uniform (J → Module.Dual F2 (E ⧸ W)) := + UniformLinearImage.uniform_pushforward_linearMap + (selectedRowsLinear W C' b sel) (selectedRowsLinear_surjective W C' b sel hsel) + +theorem uniform_selected_rows_law [DecidableEq J] (hsel : Function.Injective sel) : + (FiniteDistribution.uniform (Parameter W C')).pushforward + (selectedRowsLinear W C' b sel) = + FiniteProduct.law (fun _ : J => FiniteDistribution.uniform + (Module.Dual F2 (E ⧸ W))) := by + rw [UniformLinearImage.law_uniform] + exact UniformLinearImage.uniform_pushforward_linearMap + (selectedRowsLinear W C' b sel) (selectedRowsLinear_surjective W C' b sel hsel) + +end Uniform + +def affineRow (offset : Module.Dual F2 E) (row : Module.Dual F2 (E ⧸ W)) : + Module.Dual F2 E := offset + row.comp W.mkQ + +omit [Fintype I] in +theorem coordinate_translate (coordinates : I → Module.Dual F2 C) + (hcoordinates : ∀ i, (coordinates i).comp C'.subtype = b.coord i) + (X : E →ₗ[F2] C) (A : Parameter W C') (i : I) : + (coordinates i).comp (translate W C' X A) = + affineRow W ((coordinates i).comp X) (rowsLinear W C' b A i) := by + apply LinearMap.ext + intro x + change coordinates i (X x + (A (W.mkQ x) : C)) = + coordinates i (X x) + b.coord i (A (W.mkQ x)) + rw [map_add] + congr 1 + exact congrArg (fun f : C' →ₗ[F2] F2 => f (A (W.mkQ x))) (hcoordinates i) + + +variable [Fintype (Parameter W C')] [Fintype (Module.Dual F2 (E ⧸ W))] + [Fintype (Module.Dual F2 E)] + +def affineRowLaw (offset : Module.Dual F2 E) : FiniteDistribution (Module.Dual F2 E) := + (FiniteDistribution.uniform (Module.Dual F2 (E ⧸ W))).pushforward (affineRow W offset) + +theorem uniform_affine_rows_law [DecidableEq I] (offsets : I → Module.Dual F2 E) : + (FiniteDistribution.uniform (Parameter W C')).pushforward + (fun A i => affineRow W (offsets i) (rowsLinear W C' b A i)) = + FiniteProduct.law (fun i => affineRowLaw W (offsets i)) := by + rw [← FiniteDistribution.pushforward_comp + (FiniteDistribution.uniform (Parameter W C')) (rowsLinear W C' b) + (fun rows i => affineRow W (offsets i) (rows i)), uniform_rows_law] + exact FiniteProduct.pushforward_map _ (fun i => affineRow W (offsets i)) + +theorem uniform_coordinate_translate_law [DecidableEq I] + (coordinates : I → Module.Dual F2 C) + (hcoordinates : ∀ i, (coordinates i).comp C'.subtype = b.coord i) + (X : E →ₗ[F2] C) : + (FiniteDistribution.uniform (Parameter W C')).pushforward + (fun A i => (coordinates i).comp (translate W C' X A)) = + FiniteProduct.law (fun i => affineRowLaw W ((coordinates i).comp X)) := by + have hrows : (fun A i => (coordinates i).comp (translate W C' X A)) = + (fun A i => affineRow W ((coordinates i).comp X) (rowsLinear W C' b A i)) := by + funext A i + exact coordinate_translate W C' b coordinates hcoordinates X A i + rw [hrows] + exact uniform_affine_rows_law W C' b (fun i => (coordinates i).comp X) + +variable {J : Type*} [Fintype J] [DecidableEq J] + +theorem uniform_selected_affine_rows_law (sel : J → I) + (hsel : Function.Injective sel) (offsets : J → Module.Dual F2 E) : + (FiniteDistribution.uniform (Parameter W C')).pushforward + (fun A j => affineRow W (offsets j) (selectedRowsLinear W C' b sel A j)) = + FiniteProduct.law (fun j => affineRowLaw W (offsets j)) := by + rw [← FiniteDistribution.pushforward_comp + (FiniteDistribution.uniform (Parameter W C')) (selectedRowsLinear W C' b sel) + (fun rows j => affineRow W (offsets j) (rows j)), + uniform_selected_rows_law W C' b sel hsel] + exact FiniteProduct.pushforward_map _ (fun j => affineRow W (offsets j)) + +end +end PerfectCompleteness.RestrictionRowsLaw + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/SamplerCardinalityLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/SamplerCardinalityLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..87ddfaf5a2c28dbf34259a5f6b28007107d03a00 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/SamplerCardinalityLemmas.lean @@ -0,0 +1,227 @@ +import OAI.Computability.PerfectCompleteness.Machines.ScalarTapeCardinality +import OAI.Computability.PerfectCompleteness.Sampling.PreliminarySampler +import OAI.Computability.PerfectCompleteness.Sampling.RationalFiniteLawLemmas + +namespace OAI + + +namespace PerfectCompleteness.SamplerCardinality + +open TreeSourceSpaces TreeCardinality ScalarTapeCardinality +open RecursiveSpaces DescendantSpaces HierarchicalArrays +open scoped BigOperators Classical + +noncomputable section + +variable {branch : Nat → Nat} {n m t : Nat} + +theorem stepTape_card {i : Fin (branch n)} (Root Selected : Type) + (Ordinary : RecursiveSampler.OffPath i → Type) + [Fintype Root] [Fintype Selected] [∀ j, Fintype (Ordinary j)] : + Nat.card (WholeArraySampler.StepTape Root Selected Ordinary) = + Nat.card Root * (Nat.card Selected * ∏ j, Nat.card (Ordinary j)) := by + rw [Nat.card_pi] + simp [WholeArraySampler.StepIndex, WholeArraySampler.StepFactor, Fintype.prod_sum_type] + +def wholeTapeBound (rows repeats : Nat → Nat) (t : Nat) : + {n m : Nat} → Path branch n m → Nat + | n, _, .refl _ => arraysBound branch n t rows + | n + 1, _, .step i p => + bucketBound rows repeats (.step i p) t * + (wholeTapeBound rows repeats t p * + arraysBound branch n t rows ^ Nat.card (RecursiveSampler.OffPath i)) + +theorem wholeTape_card_le (rows repeats : Nat → Nat) (p : Path branch n m) : + ∀ (slots : Slots branch n → Fin t → MixedSupport.Slot), + Nat.card (WholeArraySampler.Tape rows repeats p slots) ≤ + wholeTapeBound rows repeats t p := by + induction p with + | refl n => + intro slots + exact arrays_card_le slots rows + | @step n m i p ih => + intro slots + change Nat.card (WholeArraySampler.StepTape + (WholeArraySampler.RootTape rows repeats (.step i p) slots) + (WholeArraySampler.Tape rows repeats p (childSlots slots i)) + (fun j : RecursiveSampler.OffPath i => Arrays (childSlots slots j.val) rows)) ≤ _ + rw [stepTape_card] + apply Nat.mul_le_mul (bucket_card_le rows repeats (.step i p) slots) + apply Nat.mul_le_mul (ih (childSlots slots i)) + calc + _ ≤ ∏ _j : RecursiveSampler.OffPath i, arraysBound branch n t rows := + Finset.prod_le_prod (fun j _ => arrays_card_le (childSlots slots j.val) rows) + _ = arraysBound branch n t rows ^ Nat.card (RecursiveSampler.OffPath i) := by + simp [Nat.card_eq_fintype_card] + +def treeTapeBound (branch : Nat → Nat) (n t : Nat) (rows repeats : Nat → Nat) : Nat := + ∑ leaf : Slots branch n, wholeTapeBound rows repeats t (GeometricPath.leafPath leaf) + +theorem leafTape_card_le (rows repeats : Nat → Nat) (leaf : Slots branch n) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Nat.card (WholeArraySampler.Tape rows repeats (GeometricPath.leafPath leaf) slots) ≤ + treeTapeBound branch n t rows repeats := by + apply (wholeTape_card_le rows repeats (GeometricPath.leafPath leaf) slots).trans + change wholeTapeBound rows repeats t (GeometricPath.leafPath leaf) ≤ + ∑ other : Slots branch n, wholeTapeBound rows repeats t (GeometricPath.leafPath other) + exact Finset.single_le_sum + (fun other _ => Nat.zero_le (wholeTapeBound rows repeats t (GeometricPath.leafPath other))) + (Finset.mem_univ leaf) + +def testBound (n : Nat) (rows : Nat → Nat) : Nat := + ∑ level : Fin n, Nat.card (BucketSampler.Direction (rows (level.val + 1))) + +theorem choice_card (rows : Nat → Nat) (leaf : Slots branch n) : + Nat.card (PreliminarySampler.Choice rows leaf) = testBound n rows := by + rw [Nat.card_sigma] + simp only [GeometricPath.nodeAtLevel_height, testBound] + +def occurrenceConstant (branch : Nat → Nat) (n t : Nat) (rows repeats : Nat → Nat) : Nat := + Fintype.card (Slots branch n) * treeTapeBound branch n t rows repeats * testBound n rows + +theorem raw_card_le {v clausesCount : Nat} + (clauses : Fin clausesCount → SourceClause.NormalizedClause v) + (branch : Nat → Nat) (n t : Nat) (rows repeats : Nat → Nat) : + Nat.card (PreliminarySampler.Raw clauses branch n t rows repeats) ≤ + occurrenceConstant branch n t rows repeats * + clausesCount ^ (t * Fintype.card (Slots branch n)) := by + rw [Nat.card_sigma] + calc + _ ≤ ∑ _b : PreliminarySampler.Base branch n t clausesCount, + treeTapeBound branch n t rows repeats * testBound n rows := by + apply Finset.sum_le_sum + intro b _ + rw [Nat.card_prod, choice_card] + exact Nat.mul_le_mul_right _ (leafTape_card_le rows repeats b.2 + (sourceSlots clauses (PreliminarySampler.endpoints b.1))) + _ = Nat.card (PreliminarySampler.Base branch n t clausesCount) * + (treeTapeBound branch n t rows repeats * testBound n rows) := by + simp [Nat.card_eq_fintype_card] + _ = occurrenceConstant branch n t rows repeats * + clausesCount ^ (t * Fintype.card (Slots branch n)) := by + rw [source_base_card] + simp only [occurrenceConstant] + ac_rfl + +end +end PerfectCompleteness.SamplerCardinality + + +namespace PerfectCompleteness.SamplerRationality + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open RationalFiniteLaw +open scoped BigOperators Classical + +noncomputable section + +universe u w + +variable {branch : Nat → Nat} {n m t : Nat} + +def recursiveTapeLaw (𝕜 : Type w) [Field 𝕜] [Finite 𝕜] + (repeats : Nat → Nat) (p : Path branch n m) (A : Slots branch n → Type u) + [∀ s, Finite (A s)] : RationalLaw (RecursiveSampler.tapeLaw 𝕜 repeats p A) := by + rw [RecursiveSampler.tapeLaw_eq_uniform] + exact RationalFiniteLaw.uniform (RecursiveSampler.Tape 𝕜 repeats p A) + +def bucketTapeLaw (ℓ : Nat) (repeats : Nat → Nat) (p : Path branch n m) + (A : Slots branch n → Type u) [∀ s, Finite (A s)] : + RationalLaw (BucketSampler.recursiveTapeLaw ℓ repeats p A) := + RationalFiniteLaw.pi + (fun _ : BucketSampler.Direction ℓ => RecursiveSampler.tapeLaw F2 repeats p A) + (fun _ => recursiveTapeLaw F2 repeats p A) + +def wholeArrayTapeLaw (rows repeats : Nat → Nat) (p : Path branch n m) : + ∀ (slots : Slots branch n → Fin t → MixedSupport.Slot), + RationalLaw (WholeArraySampler.tapeLaw rows repeats p slots) := by + induction p with + | refl n => + intro slots + exact RationalFiniteLaw.uniform (Arrays slots rows) + | @step n m i p ih => + intro slots + letI : (k : WholeArraySampler.StepIndex i) → Fintype + (WholeArraySampler.StepFactor + (WholeArraySampler.RootTape rows repeats (.step i p) slots) + (WholeArraySampler.Tape rows repeats p (childSlots slots i)) + (fun j => Arrays (childSlots slots j.val) rows) k) := + fun k => WholeArraySampler.stepFactorFintype _ _ _ k + change RationalLaw (FiniteProduct.law (WholeArraySampler.componentLaw rows repeats i p slots)) + refine RationalFiniteLaw.pi (WholeArraySampler.componentLaw rows repeats i p slots) ?_ + intro k + rcases k with u | (u | j) + · exact bucketTapeLaw (rows (n + 1)) repeats (.step i p) (LeafDomain slots) + · exact ih (childSlots slots i) + · exact RationalFiniteLaw.uniform (Arrays (childSlots slots j.val) rows) + + +variable {v : Nat} {rows repeats : Nat → Nat} + +def questionsLaw [NeZero m] : + RationalLaw (PreliminarySampler.questionsLaw + (branch := branch) (n := n) (t := t) (m := m)) := + RationalFiniteLaw.uniform (PreliminarySampler.Questions branch n t m) + +def pathLaw (hbranch : ∀ k < n, 0 < branch k) : + RationalLaw (GeometricPath.law n hbranch) := by + letI := GeometricPath.slots_nonempty n hbranch + exact RationalFiniteLaw.uniform (Slots branch n) + +def baseLaw [NeZero m] (hbranch : ∀ k < n, 0 < branch k) : + RationalLaw (PreliminarySampler.baseLaw (t := t) (m := m) hbranch) := + RationalFiniteLaw.product questionsLaw (pathLaw hbranch) + +def choiceLaw (leaf : Slots branch n) (hn : 0 < n) + (hrows : ∀ k, 0 < rows (k + 1)) : + RationalLaw (PreliminarySampler.choiceLaw leaf hn hrows) := by + letI : Nonempty (Fin n) := ⟨⟨0, hn⟩⟩ + apply RationalFiniteLaw.sigma (RationalFiniteLaw.uniform (Fin n)) + intro level + letI : Nonempty (BucketSampler.Direction + (rows (Nodes.height (GeometricPath.nodeAtLevel leaf level)))) := + PreliminarySampler.directionNonempty _ (by + rw [GeometricPath.nodeAtLevel_height] + exact hrows level.val) + exact RationalFiniteLaw.uniform _ + +def conditionalLaw (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hn : 0 < n) + (hrows : ∀ k, 0 < rows (k + 1)) (b : PreliminarySampler.Base branch n t m) : + RationalLaw (PreliminarySampler.conditionalLaw clauses rows repeats hn hrows b) := + RationalFiniteLaw.product + (wholeArrayTapeLaw rows repeats (GeometricPath.leafPath b.2) + (sourceSlots clauses (PreliminarySampler.endpoints b.1))) + (choiceLaw b.2 hn hrows) + +def preliminaryLaw [NeZero m] (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hn : 0 < n) + (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) : + RationalLaw (PreliminarySampler.law (t := t) clauses rows repeats hn hbranch hrows) := + RationalFiniteLaw.sigma (baseLaw hbranch) + (conditionalLaw clauses rows repeats hn hrows) + +theorem preliminary_positive [NeZero m] + (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hn : 0 < n) + (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) + (e : PreliminarySampler.Raw clauses branch n t rows repeats) : + 0 < (PreliminarySampler.law clauses rows repeats hn hbranch hrows).weight e := + RationalFiniteLaw.real_positive + (preliminaryLaw clauses rows repeats hn hbranch hrows) e + +theorem raw_nonempty [NeZero m] (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hn : 0 < n) + (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) : + Nonempty (PreliminarySampler.Raw clauses branch n t rows repeats) := by + let μ := PreliminarySampler.law (t := t) clauses rows repeats hn hbranch hrows + by_contra h + have hz : (∑ e, μ.weight e) = 0 := + Finset.sum_eq_zero (fun e _ => (h ⟨e⟩).elim) + exact zero_ne_one (hz.symm.trans μ.normalized) + +end +end PerfectCompleteness.SamplerRationality + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/SamplerComposition.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/SamplerComposition.lean new file mode 100644 index 0000000000000000000000000000000000000000..78ab04db76854a3c7d478c135cfb6d575af61174 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/SamplerComposition.lean @@ -0,0 +1,170 @@ +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalFrozenTablesLemmas +import OAI.Computability.PerfectCompleteness.Sampling.BucketUniformLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.SamplerComposition + +open PointwiseSpaces RecursiveSpaces DescendantSpaces RecursiveSampler + +noncomputable section + +universe u w + +variable {branch : Nat → Nat} {n m k : Nat} + +def ExpansionSpace (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) : + {n m k : Nat} → (p : Path branch n m) → (q : Path branch m k) → + (A : Slots branch n → Type u) → DrawIndex repeats p → Type (max u w) + | _, _, _, .refl _, q, A, _ => RecursiveSampler.Tape 𝕜 repeats q A + | n + 1, _, _, .step i p, q, A, j => + match j with + | Sum.inl j => squareSpace (space 𝕜 branch n (childFamily A j.val)) + | Sum.inr j => ExpansionSpace 𝕜 repeats p q (childFamily A i) j.2 + +abbrev ExpandedTape (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) + (p : Path branch n m) (q : Path branch m k) (A : Slots branch n → Type u) := + (j : DrawIndex repeats p) → ExpansionSpace 𝕜 repeats p q A j + +def zeroFactor (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) : + {n m k : Nat} → (p : Path branch n m) → (q : Path branch m k) → + (A : Slots branch n → Type u) → (j : DrawIndex repeats p) → + ExpansionSpace 𝕜 repeats p q A j + | _, _, _, .refl _, q, A, _ => zeroTape 𝕜 repeats q A + | n + 1, _, _, .step i p, q, A, j => + match j with + | Sum.inl j => (0 : squareSpace (space 𝕜 branch n (childFamily A j.val))) + | Sum.inr j => zeroFactor 𝕜 repeats p q (childFamily A i) j.2 + +def zeroExpandedTape (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) + (p : Path branch n m) (q : Path branch m k) (A : Slots branch n → Type u) : + ExpandedTape 𝕜 repeats p q A := zeroFactor 𝕜 repeats p q A + +def expandedSubTape (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) + (i : Fin (branch n)) (p : Path branch n m) (q : Path branch m k) + (A : Slots branch (n + 1) → Type u) + (t : ExpandedTape 𝕜 repeats (.step i p) q A) + (h : Fin (repeats (n + 1))) (b : Bool) : + ExpandedTape 𝕜 repeats p q (childFamily A i) := fun j => t (.inr ((h, b), j)) + +def expand (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) : + {n m k : Nat} → (p : Path branch n m) → (q : Path branch m k) → + (A : Slots branch n → Type u) → RecursiveSampler.Tape 𝕜 repeats (p.append q) A → + ExpandedTape 𝕜 repeats p q A + | _, _, _, .refl _, _, _, t => fun _ => t + | _n + 1, _, _, .step i p, q, A, t => fun j => + match j with + | Sum.inl j => t (.inl j) + | Sum.inr j => expand 𝕜 repeats p q (childFamily A i) + (subTape 𝕜 repeats i (p.append q) A t j.1.1 j.1.2) j.2 + +def flatten (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) : + {n m k : Nat} → (p : Path branch n m) → (q : Path branch m k) → + (A : Slots branch n → Type u) → ExpandedTape 𝕜 repeats p q A → + RecursiveSampler.Tape 𝕜 repeats (p.append q) A + | _, _, _, .refl _, _, _, t => t () + | _n + 1, _, _, .step i p, q, A, t => fun j => + match j with + | Sum.inl j => t (.inl j) + | Sum.inr j => flatten 𝕜 repeats p q (childFamily A i) + (expandedSubTape 𝕜 repeats i p q A t j.1.1 j.1.2) j.2 + +theorem flatten_expand (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) + (p : Path branch n m) : + ∀ (q : Path branch m k) (A : Slots branch n → Type u) + (t : RecursiveSampler.Tape 𝕜 repeats (p.append q) A), + flatten 𝕜 repeats p q A (expand 𝕜 repeats p q A t) = t := by + induction p with + | refl n => intro q A t; rfl + | @step n m i p ih => + intro q A t + funext j + cases j with + | inl j => rfl + | inr j => + exact congrFun + (ih q (childFamily A i) (subTape 𝕜 repeats i (p.append q) A t j.1.1 j.1.2)) j.2 + +theorem expand_flatten (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) + (p : Path branch n m) : + ∀ (q : Path branch m k) (A : Slots branch n → Type u) + (t : ExpandedTape 𝕜 repeats p q A), + expand 𝕜 repeats p q A (flatten 𝕜 repeats p q A t) = t := by + induction p with + | refl n => + intro q A t + funext j + cases j + rfl + | @step n m i p ih => + intro q A t + funext j + cases j with + | inl j => rfl + | inr j => + exact congrFun + (ih q (childFamily A i) (expandedSubTape 𝕜 repeats i p q A t j.1.1 j.1.2)) j.2 + +def expandEquiv (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) + (p : Path branch n m) (q : Path branch m k) (A : Slots branch n → Type u) : + RecursiveSampler.Tape 𝕜 repeats (p.append q) A ≃ ExpandedTape 𝕜 repeats p q A where + toFun := expand 𝕜 repeats p q A + invFun := flatten 𝕜 repeats p q A + left_inv := flatten_expand 𝕜 repeats p q A + right_inv := expand_flatten 𝕜 repeats p q A + +def collapseFactor (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) : + {n m k : Nat} → (p : Path branch n m) → (q : Path branch m k) → + (A : Slots branch n → Type u) → (j : DrawIndex repeats p) → + ExpansionSpace 𝕜 repeats p q A j → DrawSpace 𝕜 repeats p A j + | _, _, _, .refl _, q, A, _ => RecursiveSampler.evaluate 𝕜 repeats q A + | _, _, _, .step i p, q, A, j => + match j with + | Sum.inl _ => fun t => t + | Sum.inr j => collapseFactor 𝕜 repeats p q (childFamily A i) j.2 + +def collapseExpanded (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) + (p : Path branch n m) (q : Path branch m k) (A : Slots branch n → Type u) : + ExpandedTape 𝕜 repeats p q A → RecursiveSampler.Tape 𝕜 repeats p A := + fun t j => collapseFactor 𝕜 repeats p q A j (t j) + +def collapseSuffix (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) + (p : Path branch n m) (q : Path branch m k) (A : Slots branch n → Type u) : + RecursiveSampler.Tape 𝕜 repeats (p.append q) A → RecursiveSampler.Tape 𝕜 repeats p A := + collapseExpanded 𝕜 repeats p q A ∘ expandEquiv 𝕜 repeats p q A + +theorem evaluate_collapseExpanded (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) + (p : Path branch n m) : + ∀ (q : Path branch m k) (A : Slots branch n → Type u) + (t : ExpandedTape 𝕜 repeats p q A), + RecursiveSampler.evaluate 𝕜 repeats p A (collapseExpanded 𝕜 repeats p q A t) = + RecursiveSampler.evaluate 𝕜 repeats (p.append q) A (flatten 𝕜 repeats p q A t) := by + induction p with + | refl n => intro q A t; rfl + | @step n m i p ih => + intro q A t + have hl := funext fun h : Fin (repeats (n + 1)) => + ih q (childFamily A i) (expandedSubTape 𝕜 repeats i p q A t h false) + have hr := funext fun h : Fin (repeats (n + 1)) => + ih q (childFamily A i) (expandedSubTape 𝕜 repeats i p q A t h true) + exact congrArg₂ + (fun (left right : Fin (repeats (n + 1)) → space 𝕜 branch n (childFamily A i)) => + combine 𝕜 A i (repeats (n + 1)) (fun j => t (.inl j)) left right) hl hr + +theorem evaluate_collapseSuffix (𝕜 : Type w) [Field 𝕜] (repeats : Nat → Nat) + (p : Path branch n m) (q : Path branch m k) (A : Slots branch n → Type u) + (t : RecursiveSampler.Tape 𝕜 repeats (p.append q) A) : + RecursiveSampler.evaluate 𝕜 repeats p A (collapseSuffix 𝕜 repeats p q A t) = + RecursiveSampler.evaluate 𝕜 repeats (p.append q) A t := + (evaluate_collapseExpanded 𝕜 repeats p q A (expand 𝕜 repeats p q A t)).trans + (congrArg (RecursiveSampler.evaluate 𝕜 repeats (p.append q) A) + (flatten_expand 𝕜 repeats p q A t)) + +end +end PerfectCompleteness.SamplerComposition + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/SamplerCompositionLaws.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/SamplerCompositionLaws.lean new file mode 100644 index 0000000000000000000000000000000000000000..4dfd3a25b2b85f01faa0078c1e4ba92fa83ae73f --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/SamplerCompositionLaws.lean @@ -0,0 +1,145 @@ +import OAI.Computability.PerfectCompleteness.Sampling.CutSamplerReplayTransportLemmas +import OAI.Computability.PerfectCompleteness.Sampling.SamplerComposition + +namespace OAI + +section + +namespace PerfectCompleteness.SamplerComposition + +open PointwiseSpaces RecursiveSpaces DescendantSpaces RecursiveSampler +open UniqueGamesTheorem.Foundations.Games + +noncomputable section + +universe u w + +variable {branch : Nat → Nat} {n m k : Nat} +variable (𝕜 : Type w) [Field 𝕜] + +instance expansionSpaceNonempty (repeats : Nat → Nat) (p : Path branch n m) + (q : Path branch m k) (A : Slots branch n → Type u) (j : DrawIndex repeats p) : + Nonempty (ExpansionSpace 𝕜 repeats p q A j) := + ⟨zeroFactor 𝕜 repeats p q A j⟩ + +instance expandedTapeNonempty (repeats : Nat → Nat) (p : Path branch n m) + (q : Path branch m k) (A : Slots branch n → Type u) : + Nonempty (ExpandedTape 𝕜 repeats p q A) := + ⟨zeroExpandedTape 𝕜 repeats p q A⟩ + +variable [Finite 𝕜] + +theorem expansionSpace_finite (repeats : Nat → Nat) (p : Path branch n m) : + ∀ (q : Path branch m k) (A : Slots branch n → Type u), + (∀ s, Finite (A s)) → ∀ j : DrawIndex repeats p, + Finite (ExpansionSpace 𝕜 repeats p q A j) := by + induction p with + | refl n => + intro q A hA j + let : ∀ s, Finite (A s) := hA + let : ∀ d : DrawIndex repeats q, Fintype (DrawSpace 𝕜 repeats q A d) := + fun d => drawSpaceFintype 𝕜 repeats q A d + change Finite (RecursiveSampler.Tape 𝕜 repeats q A) + infer_instance + | @step n m i p ih => + intro q A hA j + cases j with + | inl j => + let : ∀ s, Finite (childFamily A j.val s) := fun s => hA (j.val, s) + change Finite (squareSpace (space 𝕜 branch n (childFamily A j.val))) + infer_instance + | inr j => + exact ih q (childFamily A i) (fun s => hA (i, s)) j.2 + +instance expansionSpaceFinite (repeats : Nat → Nat) (p : Path branch n m) + (q : Path branch m k) (A : Slots branch n → Type u) [∀ s, Finite (A s)] + (j : DrawIndex repeats p) : Finite (ExpansionSpace 𝕜 repeats p q A j) := + expansionSpace_finite 𝕜 repeats p q A (fun _ => inferInstance) j + +instance expansionSpaceFintype (repeats : Nat → Nat) (p : Path branch n m) + (q : Path branch m k) (A : Slots branch n → Type u) [∀ s, Finite (A s)] + (j : DrawIndex repeats p) : Fintype (ExpansionSpace 𝕜 repeats p q A j) := + Fintype.ofFinite _ + +instance expandedTapeFintype (repeats : Nat → Nat) (p : Path branch n m) + (q : Path branch m k) (A : Slots branch n → Type u) [∀ s, Finite (A s)] : + Fintype (ExpandedTape 𝕜 repeats p q A) := + @Pi.instFintype (DrawIndex repeats p) (ExpansionSpace 𝕜 repeats p q A) + (drawIndexDecidableEq repeats p) (drawIndexFintype repeats p) + (fun j => expansionSpaceFintype 𝕜 repeats p q A j) + +def expandedTapeLaw (repeats : Nat → Nat) (p : Path branch n m) + (q : Path branch m k) (A : Slots branch n → Type u) [∀ s, Finite (A s)] : + FiniteDistribution (ExpandedTape 𝕜 repeats p q A) := by + letI : ∀ j : DrawIndex repeats p, Fintype (ExpansionSpace 𝕜 repeats p q A j) := + fun j => expansionSpaceFintype 𝕜 repeats p q A j + letI : ∀ j : DrawIndex repeats p, Nonempty (ExpansionSpace 𝕜 repeats p q A j) := + fun j => expansionSpaceNonempty 𝕜 repeats p q A j + exact FiniteProduct.law (fun j => FiniteDistribution.uniform (ExpansionSpace 𝕜 repeats p q A j)) + +theorem expandedTapeLaw_eq_uniform (repeats : Nat → Nat) (p : Path branch n m) + (q : Path branch m k) (A : Slots branch n → Type u) [∀ s, Finite (A s)] : + expandedTapeLaw 𝕜 repeats p q A = FiniteDistribution.uniform (ExpandedTape 𝕜 repeats p q A) := by + let : ∀ j : DrawIndex repeats p, Fintype (ExpansionSpace 𝕜 repeats p q A j) := + fun j => expansionSpaceFintype 𝕜 repeats p q A j + let : ∀ j : DrawIndex repeats p, Nonempty (ExpansionSpace 𝕜 repeats p q A j) := + fun j => expansionSpaceNonempty 𝕜 repeats p q A j + exact UniformLinearImage.law_uniform + +theorem expand_tapeLaw (repeats : Nat → Nat) (p : Path branch n m) + (q : Path branch m k) (A : Slots branch n → Type u) [∀ s, Finite (A s)] : + (tapeLaw 𝕜 repeats (p.append q) A).pushforward (expandEquiv 𝕜 repeats p q A) = + expandedTapeLaw 𝕜 repeats p q A := by + rw [tapeLaw_eq_uniform, expandedTapeLaw_eq_uniform, + ← FiniteDistribution.transport_eq_pushforward] + exact UniformConditioning.uniform_transport (expandEquiv 𝕜 repeats p q A) + +def factorLaw (repeats : Nat → Nat) (p : Path branch n m) + (q : Path branch m k) (A : Slots branch n → Type u) [∀ s, Finite (A s)] + (j : DrawIndex repeats p) : FiniteDistribution (DrawSpace 𝕜 repeats p A j) := + (FiniteDistribution.uniform (ExpansionSpace 𝕜 repeats p q A j)).pushforward + (collapseFactor 𝕜 repeats p q A j) + +theorem collapseExpanded_expandedTapeLaw (repeats : Nat → Nat) (p : Path branch n m) + (q : Path branch m k) (A : Slots branch n → Type u) [∀ s, Finite (A s)] : + (expandedTapeLaw 𝕜 repeats p q A).pushforward (collapseExpanded 𝕜 repeats p q A) = + FiniteProduct.law (factorLaw 𝕜 repeats p q A) := by + let : ∀ j : DrawIndex repeats p, Fintype (ExpansionSpace 𝕜 repeats p q A j) := + fun j => expansionSpaceFintype 𝕜 repeats p q A j + let : ∀ j : DrawIndex repeats p, Nonempty (ExpansionSpace 𝕜 repeats p q A j) := + fun j => expansionSpaceNonempty 𝕜 repeats p q A j + exact FiniteProduct.pushforward_map _ (collapseFactor 𝕜 repeats p q A) + +theorem collapseSuffix_tapeLaw (repeats : Nat → Nat) (p : Path branch n m) + (q : Path branch m k) (A : Slots branch n → Type u) [∀ s, Finite (A s)] : + (tapeLaw 𝕜 repeats (p.append q) A).pushforward (collapseSuffix 𝕜 repeats p q A) = + FiniteProduct.law (factorLaw 𝕜 repeats p q A) := by + calc + _ = ((tapeLaw 𝕜 repeats (p.append q) A).pushforward + (expandEquiv 𝕜 repeats p q A)).pushforward (collapseExpanded 𝕜 repeats p q A) := + (FiniteDistribution.pushforward_comp _ _ _).symm + _ = _ := by rw [expand_tapeLaw, collapseExpanded_expandedTapeLaw] + +theorem law_append (repeats : Nat → Nat) (p : Path branch n m) + (q : Path branch m k) (A : Slots branch n → Type u) [∀ s, Finite (A s)] + [Fintype (space 𝕜 branch n A)] : + RecursiveSampler.law 𝕜 repeats (p.append q) A = + (FiniteProduct.law (factorLaw 𝕜 repeats p q A)).pushforward + (RecursiveSampler.evaluate 𝕜 repeats p A) := by + calc + _ = ((tapeLaw 𝕜 repeats (p.append q) A).pushforward + (collapseSuffix 𝕜 repeats p q A)).pushforward + (RecursiveSampler.evaluate 𝕜 repeats p A) := by + rw [FiniteDistribution.pushforward_comp] + unfold RecursiveSampler.law + congr 1 + funext t + exact (evaluate_collapseSuffix 𝕜 repeats p q A t).symm + _ = _ := by rw [collapseSuffix_tapeLaw] + +end +end PerfectCompleteness.SamplerComposition + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/SourceChildKernelLaw.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/SourceChildKernelLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..d34cffda23c630085c38cae8c1bb631ff5038f06 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/SourceChildKernelLaw.lean @@ -0,0 +1,109 @@ +import OAI.Computability.PerfectCompleteness.Construction.SourceChildKernelLemmas +import OAI.Computability.PerfectCompleteness.Sampling.RationalFiniteLawLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.SourceChildKernelLaw + +open UniqueGamesTheorem.Foundations.Games +open RecursiveSpaces TreeSourceSpaces SourceChildKernel +open scoped Classical + +noncomputable section + +variable {branch : Nat → Nat} {n t v m : Nat} {C : Type*} [Fintype C] + +variable (rows : Nat → Nat) (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch n) → Slots branch n) + +abbrev Physical (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) := + Σ b : Bool, Block C rows (mixedSlots clauses designated i s b) + +def physical (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) + (raw : Raw (C := C) (t := t) rows clauses designated i) : + Physical (C := C) (t := t) rows clauses designated i s := + ⟨rawProjected rows clauses designated i raw, + decodeRight rows clauses designated i s raw⟩ + +@[simp] theorem physical_inl (i : Fin (branch n)) + (s : Source (m := m) (t := t) designated i) + (raw : D (C := C) (t := t) rows clauses designated i) : + physical rows clauses designated i s (.inl raw) = + (⟨false, decodeNative rows clauses designated i s raw⟩ : + Physical (C := C) (t := t) rows clauses designated i s) := rfl + +@[simp] theorem physical_inr (i : Fin (branch n)) + (s : Source (m := m) (t := t) designated i) + (raw : UniformLatent.Raw (Factors (C := C) (t := t) rows clauses designated i)) : + physical rows clauses designated i s (.inr raw) = + (⟨true, decodeProjected rows clauses designated i s raw⟩ : + Physical (C := C) (t := t) rows clauses designated i s) := rfl + +def physicalLaw (flag : Fin (branch n) → FiniteDistribution Bool) + (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) : + FiniteDistribution (Physical (C := C) (t := t) rows clauses designated i s) := + (flag i).mixture (fun b => + (FiniteDistribution.uniform (Block C rows (mixedSlots clauses designated i s b))).pushforward + (fun block => (⟨b, block⟩ : Physical (C := C) (t := t) rows clauses designated i s))) + +theorem kernel_physical (flag : Fin (branch n) → FiniteDistribution Bool) + (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) : + (kernel (C := C) (t := t) rows clauses designated flag i s).pushforward + (physical rows clauses designated i s) = + physicalLaw (C := C) (t := t) rows clauses designated flag i s := by + unfold kernel UniformLatent.projectedKernel physicalLaw + rw [FiniteDistribution.pushforward_mixture] + apply congrArg (fun laws : Bool → + FiniteDistribution (Physical (C := C) (t := t) rows clauses designated i s) => + (flag i).mixture laws) + funext b + cases b with + | false => + change ((nonprojected (C := C) (t := t) rows clauses designated i s).pushforward + Sum.inl).pushforward (physical rows clauses designated i s) = + (FiniteDistribution.uniform (Native (C := C) (t := t) rows clauses designated i s)).pushforward + (fun block => (⟨false, block⟩ : Physical (C := C) (t := t) rows clauses designated i s)) + rw [FiniteDistribution.pushforward_comp] + calc + _ = ((nonprojected (C := C) (t := t) rows clauses designated i s).pushforward + (decodeNative rows clauses designated i s)).pushforward + (fun block => (⟨false, block⟩ : + Physical (C := C) (t := t) rows clauses designated i s)) := + (FiniteDistribution.pushforward_comp _ _ _).symm + _ = _ := by rw [decodeNative_law] + | true => + change ((UniformLatent.latentKernel + (Factors (C := C) (t := t) rows clauses designated i) s).pushforward + Sum.inr).pushforward (physical rows clauses designated i s) = + (FiniteDistribution.uniform + (Projected (C := C) (t := t) rows clauses designated i s)).pushforward + (fun block => (⟨true, block⟩ : Physical (C := C) (t := t) rows clauses designated i s)) + rw [FiniteDistribution.pushforward_comp] + calc + _ = ((UniformLatent.latentKernel + (Factors (C := C) (t := t) rows clauses designated i) s).pushforward + (decodeProjected rows clauses designated i s)).pushforward + (fun block => (⟨true, block⟩ : + Physical (C := C) (t := t) rows clauses designated i s)) := + (FiniteDistribution.pushforward_comp _ _ _).symm + _ = _ := by rw [decodeProjected_law] + +theorem kernels_physical (flag : Fin (branch n) → FiniteDistribution Bool) + (sources : Sources (m := m) (t := t) designated) : + (FiniteProduct.law (fun i => + kernel (C := C) (t := t) rows clauses designated flag i (sources i))).pushforward + (fun raw i => physical rows clauses designated i (sources i) (raw i)) = + FiniteProduct.law (fun i => + physicalLaw (C := C) (t := t) rows clauses designated flag i (sources i)) := by + rw [FiniteProduct.pushforward_map] + exact congrArg FiniteProduct.law + (funext fun i => kernel_physical rows clauses designated flag i (sources i)) + +end +end PerfectCompleteness.SourceChildKernelLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/SourceChildKernelMarginalLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/SourceChildKernelMarginalLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..a090404d7dc8483a52a191885f563092b1b45b9a --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/SourceChildKernelMarginalLemmas.lean @@ -0,0 +1,239 @@ +import OAI.Computability.PerfectCompleteness.Construction.SourceChildKernelLemmas +import OAI.Computability.PerfectCompleteness.Decoding.ChildAssemblyProjection +import OAI.Computability.PerfectCompleteness.Sampling.RationalFiniteLawLemmas +import OAI.Computability.PerfectCompleteness.Sampling.SourceChildKernelLaw + +namespace OAI + +section + +namespace PerfectCompleteness.SourceChildKernelMarginal + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games +open RecursiveSpaces SourceQuestionReconstruction + +noncomputable section + +theorem nestedKernel_sources {E R T : Type*} [Fintype E] [Fintype R] [Fintype T] + (μ : FiniteDistribution E) (ν : FiniteDistribution R) + (kernel : E → R → FiniteDistribution T) : + (CleanConditioning.kernelJoint μ (fun e => CleanConditioning.kernelJoint ν (kernel e))).pushforward + (fun x => (x.1, x.2.1)) = μ.product ν := by + apply FiniteDistribution.eq_of_weight_eq + rintro ⟨e, r⟩ + simp only [FiniteDistribution.pushforward, CleanConditioning.kernelJoint, + FiniteDistribution.product, Fintype.sum_prod_type, Prod.mk.injEq] + rw [Finset.sum_eq_single e] + · rw [Finset.sum_eq_single r] + · simp [← Finset.mul_sum, FiniteDistribution.normalized] + · intro r' _ hne + simp [hne] + · simp + · intro e' _ hne + simp [hne] + · simp + +variable {branch : Nat → Nat} {n t v m : Nat} {C : Type*} [Fintype C] + +def sources (rows : Nat → Nat) (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch n) → Slots branch n) + (sample : SourceChildKernel.Sample (C := C) (t := t) rows clauses designated) : + SourceChildKernel.Sources (m := m) (t := t) designated := + fun i => ((sample i).1, (sample i).2.1) + +theorem childrenLaw_sources (rows : Nat → Nat) + (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch n) → Slots branch n) + (μ : Fin (branch n) → FiniteDistribution (SourceTuple m t)) + (ν : (i : Fin (branch n)) → + FiniteDistribution (SourceChildKernel.Rest (m := m) (t := t) designated i)) + (flag : Fin (branch n) → FiniteDistribution Bool) : + (SourceChildKernel.childrenLaw (C := C) rows clauses designated μ ν flag).pushforward + (sources rows clauses designated) = + FiniteProduct.law (fun i => (μ i).product (ν i)) := by + let P (i : Fin (branch n)) : FiniteDistribution + (SourceTuple m t × (SourceChildKernel.Rest (m := m) (t := t) designated i × + SourceChildKernel.Raw (C := C) (t := t) rows clauses designated i)) := + CleanConditioning.kernelJoint (μ i) (fun e => CleanConditioning.kernelJoint (ν i) + (fun r => SourceChildKernel.kernel rows clauses designated flag i (e, r))) + let f (i : Fin (branch n)) + (x : SourceTuple m t × (SourceChildKernel.Rest (m := m) (t := t) designated i × + SourceChildKernel.Raw (C := C) (t := t) rows clauses designated i)) : + SourceChildKernel.Source (m := m) (t := t) designated i := (x.1, x.2.1) + change (FiniteProduct.law P).pushforward (fun sample i => f i (sample i)) = _ + refine (CleanConditioning.pushforward_law P f).trans ?_ + apply congrArg (fun laws : (i : Fin (branch n)) → + FiniteDistribution (SourceChildKernel.Source (m := m) (t := t) designated i) => + FiniteProduct.law laws) + funext i + exact nestedKernel_sources (μ i) (ν i) + (fun e r => SourceChildKernel.kernel rows clauses designated flag i (e, r)) + +theorem originalLaw_sources [NeZero m] (rows : Nat → Nat) + (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch n) → Slots branch n) + (flag : Fin (branch n) → FiniteDistribution Bool) : + (SourceChildKernel.originalLaw (C := C) (t := t) rows clauses designated flag).pushforward + (sources rows clauses designated) = + FiniteProduct.law (fun i : Fin (branch n) => + (SourceOddLists.tupleLaw m t).product + (FiniteProduct.law (fun _ : {leaf : Slots branch n // leaf ≠ designated i} => + SourceOddLists.tupleLaw m t))) := + childrenLaw_sources rows clauses designated _ _ flag + +end +end PerfectCompleteness.SourceChildKernelMarginal + +end + +section + +namespace PerfectCompleteness.SourceChildNativeLaw + +open UniqueGamesTheorem.Foundations.Games +open RecursiveSpaces TreeSourceSpaces SourceChildKernel +open scoped Classical + +noncomputable section + +def falseFlag : FiniteDistribution Bool where + weight b := if b then 0 else 1 + nonnegative b := by cases b <;> simp + normalized := by simp + +variable {branch : Nat → Nat} {n t v m : Nat} {C : Type*} [Fintype C] + (rows : Nat → Nat) (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch n) → Slots branch n) + +def pullback (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) (b : Bool) + (block : Block C rows (mixedSlots clauses designated i s b)) : + Native (C := C) (t := t) rows clauses designated i s := + (fun call => ChildBlockProjection.squarePullback (projection clauses designated i s b) + (block.1 call), + ChildBlockProjection.arraysPullback rows (projection clauses designated i s b) block.2) + +omit [Fintype C] in +@[simp] theorem pullback_false (i : Fin (branch n)) + (s : Source (m := m) (t := t) designated i) + (block : Native (C := C) (t := t) rows clauses designated i s) : + pullback rows clauses designated i s false block = block := by + apply Prod.ext + · funext call + apply Subtype.ext + funext x + rfl + · funext node row + apply Subtype.ext + funext x + rfl + +def physicalLeft (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) + (x : SourceChildKernelLaw.Physical (C := C) (t := t) rows clauses designated i s) : + Native (C := C) (t := t) rows clauses designated i s := + pullback rows clauses designated i s x.1 x.2 + +def decodeLeft (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) + (raw : Raw (C := C) (t := t) rows clauses designated i) : + Native (C := C) (t := t) rows clauses designated i s := + physicalLeft rows clauses designated i s + (SourceChildKernelLaw.physical rows clauses designated i s raw) + +theorem decodeLeft_eq_leftChildren (sources : Sources (m := m) (t := t) designated) + (raw : (i : Fin (branch n)) → Raw (C := C) (t := t) rows clauses designated i) + (i : Fin (branch n)) : + decodeLeft rows clauses designated i (sources i) (raw i) = + leftChildren rows clauses designated sources raw i := rfl + +def leftLaw (flag : Fin (branch n) → FiniteDistribution Bool) + (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) : + FiniteDistribution (Native (C := C) (t := t) rows clauses designated i s) := + (flag i).mixture (fun b => if b then + (FiniteDistribution.uniform (Projected (C := C) (t := t) rows clauses designated i s)).pushforward + (pullback rows clauses designated i s true) + else FiniteDistribution.uniform (Native (C := C) (t := t) rows clauses designated i s)) + +theorem physicalLaw_left (flag : Fin (branch n) → FiniteDistribution Bool) + (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) : + (SourceChildKernelLaw.physicalLaw (C := C) (t := t) rows clauses designated flag i s).pushforward + (physicalLeft rows clauses designated i s) = + leftLaw (C := C) (t := t) rows clauses designated flag i s := by + unfold SourceChildKernelLaw.physicalLaw leftLaw + rw [FiniteDistribution.pushforward_mixture] + apply congrArg (fun laws : Bool → + FiniteDistribution (Native (C := C) (t := t) rows clauses designated i s) => + (flag i).mixture laws) + funext b + cases b with + | false => + rw [FiniteDistribution.pushforward_comp] + calc + _ = (FiniteDistribution.uniform (Native (C := C) (t := t) rows clauses designated i s)).pushforward + (id : Native (C := C) (t := t) rows clauses designated i s → _) := by + apply congrArg (fun f : Native (C := C) (t := t) rows clauses designated i s → + Native (C := C) (t := t) rows clauses designated i s => + (FiniteDistribution.uniform (Native (C := C) (t := t) rows clauses designated i s)).pushforward f) + funext block + exact pullback_false rows clauses designated i s block + _ = _ := UniqueGamesTheorem.Foundations.Games.FiniteDistribution.pushforward_id + (FiniteDistribution.uniform (Native (C := C) (t := t) rows clauses designated i s)) + | true => + exact FiniteDistribution.pushforward_comp _ _ _ + +theorem kernel_decodeLeft (flag : Fin (branch n) → FiniteDistribution Bool) + (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) : + (kernel (C := C) (t := t) rows clauses designated flag i s).pushforward + (decodeLeft rows clauses designated i s) = + leftLaw (C := C) (t := t) rows clauses designated flag i s := by + calc + _ = ((kernel (C := C) (t := t) rows clauses designated flag i s).pushforward + (SourceChildKernelLaw.physical rows clauses designated i s)).pushforward + (physicalLeft rows clauses designated i s) := + (FiniteDistribution.pushforward_comp _ _ _).symm + _ = _ := by rw [SourceChildKernelLaw.kernel_physical, physicalLaw_left] + +theorem leftLaw_false (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) : + leftLaw (C := C) (t := t) rows clauses designated (fun _ => falseFlag) i s = + FiniteDistribution.uniform (Native (C := C) (t := t) rows clauses designated i s) := by + apply FiniteDistribution.eq_of_weight_eq + intro block + simp [leftLaw, falseFlag, FiniteDistribution.mixture] + +theorem kernel_decodeLeft_false (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) : + (kernel (C := C) (t := t) rows clauses designated (fun _ => falseFlag) i s).pushforward + (decodeLeft rows clauses designated i s) = + FiniteDistribution.uniform (Native (C := C) (t := t) rows clauses designated i s) := by + rw [kernel_decodeLeft, leftLaw_false] + +theorem kernels_decodeLeft (flag : Fin (branch n) → FiniteDistribution Bool) + (sources : Sources (m := m) (t := t) designated) : + (FiniteProduct.law (fun i => kernel (C := C) (t := t) rows clauses designated flag i (sources i))).pushforward + (fun raw i => decodeLeft rows clauses designated i (sources i) (raw i)) = + FiniteProduct.law (fun i => leftLaw (C := C) (t := t) rows clauses designated flag i (sources i)) := by + rw [FiniteProduct.pushforward_map] + exact congrArg FiniteProduct.law + (funext fun i => kernel_decodeLeft rows clauses designated flag i (sources i)) + +theorem kernels_leftChildren (flag : Fin (branch n) → FiniteDistribution Bool) + (sources : Sources (m := m) (t := t) designated) : + (FiniteProduct.law (fun i => kernel (C := C) (t := t) rows clauses designated flag i (sources i))).pushforward + (leftChildren rows clauses designated sources) = + FiniteProduct.law (fun i => leftLaw (C := C) (t := t) rows clauses designated flag i (sources i)) := + kernels_decodeLeft rows clauses designated flag sources + +theorem kernels_leftChildren_false (sources : Sources (m := m) (t := t) designated) : + (FiniteProduct.law (fun i => kernel (C := C) (t := t) rows clauses designated + (fun _ => falseFlag) i (sources i))).pushforward + (leftChildren rows clauses designated sources) = + FiniteProduct.law (fun i => + FiniteDistribution.uniform (Native (C := C) (t := t) rows clauses designated i (sources i))) := by + rw [kernels_leftChildren] + exact congrArg FiniteProduct.law + (funext fun i => leftLaw_false rows clauses designated i (sources i)) + +end +end PerfectCompleteness.SourceChildNativeLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/SourceChildMarkedLaw.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/SourceChildMarkedLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..8bed57f2ec8ecd225d103517805ee4956c048e01 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/SourceChildMarkedLaw.lean @@ -0,0 +1,418 @@ +import OAI.Computability.PerfectCompleteness.Construction.SourceQuestionKernelJoint +import OAI.Computability.PerfectCompleteness.Foundations.MultiplicationFormInjectiveLemmas +import OAI.Computability.PerfectCompleteness.Foundations.WholeCutCallsLemmas +import OAI.Computability.PerfectCompleteness.Sampling.ChildCallNumberingLaws +import OAI.Computability.PerfectCompleteness.Sampling.SourceChildKernelMarginalLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.SourceChildMarkedLaw + +open UniqueGamesTheorem.Foundations.Games +open RecursiveSpaces TreeSourceSpaces HierarchicalArrays SourceChildKernel +open scoped Classical + +noncomputable section + +private theorem uniform_equiv {A B : Type*} + [Fintype A] [Fintype B] [Nonempty A] [Nonempty B] (e : A ≃ B) : + (FiniteDistribution.uniform A).pushforward e = FiniteDistribution.uniform B := by + rw [FiniteDistribution.pushforward_equiv] + apply FiniteDistribution.eq_of_weight_eq + intro x + change 1 / (Fintype.card A : ℝ) = 1 / (Fintype.card B : ℝ) + rw [Fintype.card_congr e] + +private theorem kernelJoint_map {S A B : Type*} + [Fintype S] [Fintype A] [Fintype B] + (μ : FiniteDistribution S) (P : S → FiniteDistribution A) (f : A → B) : + (CleanConditioning.kernelJoint μ P).pushforward (fun x => (x.1, f x.2)) = + CleanConditioning.kernelJoint μ (fun s => (P s).pushforward f) := by + apply SigmaObservation.eq_of_probability_eq + intro event + rw [FiniteDistribution.probability_pushforward, CleanConditioning.probability_kernelJoint, + CleanConditioning.probability_kernelJoint] + simp only [FiniteDistribution.probability_pushforward] + +private theorem kernelJoint_observe {S A B : Type*} + [Fintype S] [Fintype A] [Fintype B] + (μ : FiniteDistribution S) (P : S → FiniteDistribution A) (f : S × A → B) : + (CleanConditioning.kernelJoint μ P).pushforward f = + μ.mixture (fun s => (P s).pushforward (fun a => f (s, a))) := by + apply SigmaObservation.eq_of_probability_eq + intro event + rw [FiniteDistribution.probability_pushforward, CleanConditioning.probability_kernelJoint, + FiniteDistribution.probability_mixture] + simp only [FiniteDistribution.probability_pushforward] + +private theorem joint_product_observe {S Z A : Type*} {Y : S → Type*} + [Fintype S] [Fintype Z] [Fintype A] [∀ s, Fintype (Y s)] + (μ : FiniteDistribution S) (ν : FiniteDistribution Z) + (P : S → Z → FiniteDistribution A) (f : (s : S) → Z × A → Y s) : + (CleanConditioning.kernelJoint (μ.product ν) (fun x => P x.1 x.2)).pushforward + (fun x => (⟨x.1.1, f x.1.1 (x.1.2, x.2)⟩ : Σ s, Y s)) = + CompletionSoundness.sigmaLaw μ + (fun s => (CleanConditioning.kernelJoint ν (P s)).pushforward (f s)) := by + apply SigmaObservation.eq_of_probability_eq + intro event + rw [FiniteDistribution.probability_pushforward, CleanConditioning.probability_kernelJoint, + CompletionSoundness.sigmaLaw_probability] + simp only [FiniteDistribution.product, FiniteDistribution.expectation, Fintype.sum_prod_type] + apply Finset.sum_congr rfl + intro s _ + rw [FiniteDistribution.probability_pushforward, CleanConditioning.probability_kernelJoint, + Finset.mul_sum] + apply Finset.sum_congr rfl + intro z _ + exact mul_assoc _ _ _ + +variable {branch : Nat → Nat} {n t v m : Nat} {C : Type*} [Fintype C] + (rows : Nat → Nat) (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch n) → Slots branch n) + +def projectedLaw (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) : + FiniteDistribution (Native (C := C) (t := t) rows clauses designated i s) := + (FiniteDistribution.uniform (Projected (C := C) (t := t) rows clauses designated i s)).pushforward + (SourceChildNativeLaw.pullback rows clauses designated i s true) + +def markedChild (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) + (raw : Raw (C := C) (t := t) rows clauses designated i) : + Bool × Native (C := C) (t := t) rows clauses designated i s := + (rawProjected rows clauses designated i raw, + SourceChildNativeLaw.decodeLeft rows clauses designated i s raw) + +theorem kernel_markedChild (flag : Fin (branch n) → FiniteDistribution Bool) + (i : Fin (branch n)) (s : Source (m := m) (t := t) designated i) : + (kernel (C := C) (t := t) rows clauses designated flag i s).pushforward + (markedChild rows clauses designated i s) = + CleanConditioning.kernelJoint (flag i) (fun b => if b then + projectedLaw (C := C) (t := t) rows clauses designated i s + else FiniteDistribution.uniform (Native (C := C) (t := t) rows clauses designated i s)) := by + calc + _ = ((kernel (C := C) (t := t) rows clauses designated flag i s).pushforward + (SourceChildKernelLaw.physical rows clauses designated i s)).pushforward + (fun x => (x.1, SourceChildNativeLaw.physicalLeft rows clauses designated i s x)) := + (FiniteDistribution.pushforward_comp _ _ _).symm + _ = CleanConditioning.kernelJoint (flag i) (fun b => + (FiniteDistribution.uniform (Block C rows (mixedSlots clauses designated i s b))).pushforward + (SourceChildNativeLaw.pullback rows clauses designated i s b)) := by + rw [SourceChildKernelLaw.kernel_physical] + exact MarkedKernelProduct.physical_marked (flag i) + (fun b => FiniteDistribution.uniform (Block C rows (mixedSlots clauses designated i s b))) + (SourceChildNativeLaw.pullback rows clauses designated i s) + _ = _ := by + apply congrArg (CleanConditioning.kernelJoint (flag i)) + funext b + cases b with + | false => + have hf : SourceChildNativeLaw.pullback (C := C) rows clauses designated i s false = + (id : Native (C := C) (t := t) rows clauses designated i s → _) := + funext (SourceChildNativeLaw.pullback_false rows clauses designated i s) + change (FiniteDistribution.uniform + (Native (C := C) (t := t) rows clauses designated i s)).pushforward + (SourceChildNativeLaw.pullback rows clauses designated i s false) = _ + rw [hf, FiniteDistribution.pushforward_id] + rfl + | true => rfl + +abbrev Questions := SourceQuestionPositionSplit.Questions + (branch := branch) (n := n) (t := t) (m := m) + +abbrev Choice := SourceQuestionPositionSplit.ChildPositions (branch := branch) (n := n) (t := t) + +def childSource (q : Questions (branch := branch) (n := n) (t := t) (m := m)) + (i : Fin (branch n)) (z : Choice (branch := branch) (n := n) (t := t)) : + Source (m := m) (t := t) designated i := + SourceQuestionPositionSplit.join designated q (fun leaf k => z leaf.2 k) i + +def questionSlots (q : Questions (branch := branch) (n := n) (t := t) (m := m)) : + Slots branch (n + 1) → Fin t → MixedSupport.Slot := + sourceSlots clauses (PreliminarySampler.endpoints q) + +theorem nativeSlots_childSource + (q : Questions (branch := branch) (n := n) (t := t) (m := m)) + (i : Fin (branch n)) (z : Choice (branch := branch) (n := n) (t := t)) : + nativeSlots clauses designated i (childSource designated q i z) = + childSlots (questionSlots clauses q) i := + congrArg (fun slots => childSlots slots i) + (SourceQuestionPositionSplit.parentLeftSlots_join clauses designated q (fun leaf k => z leaf.2 k)) + +theorem childSource_sources + (q : Questions (branch := branch) (n := n) (t := t) (m := m)) + (zs : SourceQuestionKernelJoint.ChoiceTuple (branch := branch) (n := n) (t := t)) + (i : Fin (branch n)) : + childSource designated q i (zs i) = SourceQuestionKernelJoint.sources designated q zs i := rfl + +def nativeEquiv (q : Questions (branch := branch) (n := n) (t := t) (m := m)) + (i : Fin (branch n)) (z : Choice (branch := branch) (n := n) (t := t)) : + Native (C := C) (t := t) rows clauses designated i (childSource designated q i z) ≃ + CutChildGrouping.Child (C := C) (questionSlots clauses q) rows i := + Equiv.cast (congrArg (Block C rows) (nativeSlots_childSource clauses designated q i z)) + +def projectedSlots (q : Questions (branch := branch) (n := n) (t := t) (m := m)) + (i : Fin (branch n)) (z : Choice (branch := branch) (n := n) (t := t)) : + Slots branch n → Fin t → MixedSupport.Slot := + mixedSlots clauses designated i (childSource designated q i z) true + +def questionProjection + (q : Questions (branch := branch) (n := n) (t := t) (m := m)) + (i : Fin (branch n)) (z : Choice (branch := branch) (n := n) (t := t)) : + ∀ leaf k, MixedSupport.Projection (childSlots (questionSlots clauses q) i leaf k) + (projectedSlots clauses designated q i z leaf k) := + cast (congrArg + (fun slots : Slots branch n → Fin t → MixedSupport.Slot => + ∀ leaf k, MixedSupport.Projection (slots leaf k) + (projectedSlots clauses designated q i z leaf k)) + (nativeSlots_childSource clauses designated q i z)) + (projection clauses designated i (childSource designated q i z) true) + +omit [Fintype C] in +theorem nativeEquiv_pullback + (q : Questions (branch := branch) (n := n) (t := t) (m := m)) + (i : Fin (branch n)) (z : Choice (branch := branch) (n := n) (t := t)) + (block : Projected (C := C) (t := t) rows clauses designated i (childSource designated q i z)) : + nativeEquiv rows clauses designated q i z + (SourceChildNativeLaw.pullback rows clauses designated i (childSource designated q i z) true block) = + ChildCallNumbering.pullback rows (questionProjection clauses designated q i z) block := + ChildCallNumbering.pullback_cast rows (nativeSlots_childSource clauses designated q i z) + (projection clauses designated i (childSource designated q i z) true) block + +omit [Fintype C] in +theorem nativeEquiv_pullback_call + (q : Questions (branch := branch) (n := n) (t := t) (m := m)) + (i : Fin (branch n)) (z : Choice (branch := branch) (n := n) (t := t)) + (block : Projected (C := C) (t := t) rows clauses designated i (childSource designated q i z)) + (call : C) (x : Domain (childSlots (questionSlots clauses q) i)) : + ((nativeEquiv rows clauses designated q i z + (SourceChildNativeLaw.pullback rows clauses designated i (childSource designated q i z) true block)).1 call).val x = + (block.1 call).val (sourceProjection (questionProjection clauses designated q i z) x) := by + rw [nativeEquiv_pullback]; rfl + +omit [Fintype C] in +theorem nativeEquiv_pullback_arrays + (q : Questions (branch := branch) (n := n) (t := t) (m := m)) + (i : Fin (branch n)) (z : Choice (branch := branch) (n := n) (t := t)) + (block : Projected (C := C) (t := t) rows clauses designated i (childSource designated q i z)) + (x : Domain (childSlots (questionSlots clauses q) i)) : + fullJoint (nativeEquiv rows clauses designated q i z + (SourceChildNativeLaw.pullback rows clauses designated i (childSource designated q i z) true block)).2 x = + fullJoint block.2 (sourceProjection (questionProjection clauses designated q i z) x) := by + rw [nativeEquiv_pullback]; rfl + +def replacementAt (q : Questions (branch := branch) (n := n) (t := t) (m := m)) + (i : Fin (branch n)) (z : Choice (branch := branch) (n := n) (t := t)) : + FiniteDistribution (CutChildGrouping.Child (C := C) (questionSlots clauses q) rows i) := + (projectedLaw (C := C) (t := t) rows clauses designated i (childSource designated q i z)).pushforward + (nativeEquiv rows clauses designated q i z) + +def replacementLaws (q : Questions (branch := branch) (n := n) (t := t) (m := m)) + (i : Fin (branch n)) : + FiniteDistribution (CutChildGrouping.Child (C := C) (questionSlots clauses q) rows i) := + (FiniteDistribution.uniform (Choice (branch := branch) (n := n) (t := t))).mixture + (replacementAt rows clauses designated q i) + +theorem replacementAt_eq_liftedLaw + (q : Questions (branch := branch) (n := n) (t := t) (m := m)) + (i : Fin (branch n)) (z : Choice (branch := branch) (n := n) (t := t)) : + replacementAt (C := C) rows clauses designated q i z = + ChildCallNumberingLaws.liftedLaw (C := C) rows (questionProjection clauses designated q i z) := by + let μ : FiniteDistribution + (Projected (C := C) (t := t) rows clauses designated i (childSource designated q i z)) := + FiniteDistribution.uniform _ + let f : Projected (C := C) (t := t) rows clauses designated i (childSource designated q i z) → + Native (C := C) (t := t) rows clauses designated i (childSource designated q i z) := + fun block => SourceChildNativeLaw.pullback rows clauses designated i + (childSource designated q i z) true block + let g : Native (C := C) (t := t) rows clauses designated i (childSource designated q i z) → + CutChildGrouping.Child (C := C) (questionSlots clauses q) rows i := + nativeEquiv rows clauses designated q i z + exact (FiniteDistribution.pushforward_comp μ f g).trans + (congrArg (fun k : Projected (C := C) (t := t) rows clauses designated i + (childSource designated q i z) → + CutChildGrouping.Child (C := C) (questionSlots clauses q) rows i => μ.pushforward k) + (funext fun block => nativeEquiv_pullback rows clauses designated q i z block)) + +theorem replacementLaws_eq + (q : Questions (branch := branch) (n := n) (t := t) (m := m)) : + replacementLaws (C := C) rows clauses designated q = + ChildCallNumberingLaws.replacementLaws (C := C) rows (childSlots (questionSlots clauses q)) + (projectedSlots clauses designated q) (questionProjection clauses designated q) + (fun _ => FiniteDistribution.uniform (Choice (branch := branch) (n := n) (t := t))) := by + funext i + unfold replacementLaws ChildCallNumberingLaws.replacementLaws ChildCallNumberingLaws.mixtureLaw + apply congrArg (FiniteDistribution.mixture + (FiniteDistribution.uniform (Choice (branch := branch) (n := n) (t := t)))) + funext z + exact replacementAt_eq_liftedLaw rows clauses designated q i z + +def questionMarkedChild + (q : Questions (branch := branch) (n := n) (t := t) (m := m)) + (i : Fin (branch n)) (z : Choice (branch := branch) (n := n) (t := t)) + (raw : Raw (C := C) (t := t) rows clauses designated i) : + Bool × CutChildGrouping.Child (C := C) (questionSlots clauses q) rows i := + (rawProjected rows clauses designated i raw, + nativeEquiv rows clauses designated q i z + (SourceChildNativeLaw.decodeLeft rows clauses designated i (childSource designated q i z) raw)) + +theorem kernel_questionMarkedChild + (flag : Fin (branch n) → FiniteDistribution Bool) + (q : Questions (branch := branch) (n := n) (t := t) (m := m)) + (i : Fin (branch n)) (z : Choice (branch := branch) (n := n) (t := t)) : + (kernel (C := C) (t := t) rows clauses designated flag i (childSource designated q i z)).pushforward + (questionMarkedChild rows clauses designated q i z) = + CleanConditioning.kernelJoint (flag i) (fun b => if b then + replacementAt (C := C) rows clauses designated q i z + else FiniteDistribution.uniform (CutChildGrouping.Child (C := C) (questionSlots clauses q) rows i)) := by + calc + _ = ((kernel (C := C) (t := t) rows clauses designated flag i (childSource designated q i z)).pushforward + (markedChild rows clauses designated i (childSource designated q i z))).pushforward + (fun x => (x.1, nativeEquiv rows clauses designated q i z x.2)) := + (FiniteDistribution.pushforward_comp _ _ _).symm + _ = _ := by + rw [kernel_markedChild, kernelJoint_map] + apply congrArg (CleanConditioning.kernelJoint (flag i)) + funext b + cases b with + | false => exact uniform_equiv (nativeEquiv rows clauses designated q i z) + | true => rfl + +abbrev Marked (q : Questions (branch := branch) (n := n) (t := t) (m := m)) := + (Fin (branch n) → Bool) × CutChildGrouping.Raw (C := C) (questionSlots clauses q) rows + +def markedBlocks (q : Questions (branch := branch) (n := n) (t := t) (m := m)) + (zs : SourceQuestionKernelJoint.ChoiceTuple (branch := branch) (n := n) (t := t)) + (raw : SourceChildKernelJoint.RawTuple (C := C) (t := t) rows clauses designated) : + Marked (C := C) rows clauses q := + MarkedKernelProduct.markEquiv (fun i => questionMarkedChild rows clauses designated q i (zs i) (raw i)) + +theorem kernels_markedBlocks + (q : Questions (branch := branch) (n := n) (t := t) (m := m)) + (zs : SourceQuestionKernelJoint.ChoiceTuple (branch := branch) (n := n) (t := t)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) : + (FiniteProduct.law (fun i => kernel (C := C) (t := t) rows clauses designated + (fun _ => ProjectionPosterior.bernoulli β hβ hβ') i + (SourceQuestionKernelJoint.sources designated q zs i))).pushforward + (markedBlocks rows clauses designated q zs) = + SparseReplacement.markedLaw + (fun i => FiniteDistribution.uniform (CutChildGrouping.Child (C := C) (questionSlots clauses q) rows i)) + (fun i => replacementAt rows clauses designated q i (zs i)) β hβ hβ' := by + let P : (i : Fin (branch n)) → FiniteDistribution (Raw (C := C) (t := t) rows clauses designated i) := + fun i => kernel rows clauses designated + (fun _ => ProjectionPosterior.bernoulli β hβ hβ') i + (SourceQuestionKernelJoint.sources designated q zs i) + let f : (i : Fin (branch n)) → Raw (C := C) (t := t) rows clauses designated i → + Bool × CutChildGrouping.Child (C := C) (questionSlots clauses q) rows i := + fun i => questionMarkedChild rows clauses designated q i (zs i) + let e : ((i : Fin (branch n)) → + Bool × CutChildGrouping.Child (C := C) (questionSlots clauses q) rows i) ≃ + Marked (C := C) rows clauses q := MarkedKernelProduct.markEquiv + calc + _ = ((FiniteProduct.law P).pushforward (fun raw i => f i (raw i))).pushforward e := + (FiniteDistribution.pushforward_comp (FiniteProduct.law P) + (fun raw i => f i (raw i)) e).symm + _ = (FiniteProduct.law (fun i => (P i).pushforward (f i))).pushforward e := + congrArg (fun law : FiniteDistribution ((i : Fin (branch n)) → + Bool × CutChildGrouping.Child (C := C) (questionSlots clauses q) rows i) => + law.pushforward e) + (FiniteProduct.pushforward_map P f) + _ = (FiniteProduct.law (fun i => CleanConditioning.kernelJoint + (ProjectionPosterior.bernoulli β hβ hβ') (fun b => if b then + replacementAt (C := C) rows clauses designated q i (zs i) + else FiniteDistribution.uniform + (CutChildGrouping.Child (C := C) (questionSlots clauses q) rows i)))).pushforward e := + congrArg (fun laws : (i : Fin (branch n)) → FiniteDistribution + (Bool × CutChildGrouping.Child (C := C) (questionSlots clauses q) rows i) => + (FiniteProduct.law laws).pushforward e) + (funext fun i => kernel_questionMarkedChild rows clauses designated + (fun _ => ProjectionPosterior.bernoulli β hβ hβ') q i (zs i)) + _ = _ := MarkedKernelProduct.marked_product _ _ β hβ hβ' + +theorem conditional_markedLaw + (q : Questions (branch := branch) (n := n) (t := t) (m := m)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) : + (CleanConditioning.kernelJoint + (FiniteProduct.law (fun _ : Fin (branch n) => + FiniteDistribution.uniform (Choice (branch := branch) (n := n) (t := t)))) + (fun zs => FiniteProduct.law (fun i => kernel (C := C) (t := t) rows clauses designated + (fun _ => ProjectionPosterior.bernoulli β hβ hβ') i + (SourceQuestionKernelJoint.sources designated q zs i)))).pushforward + (fun x => markedBlocks rows clauses designated q x.1 x.2) = + SparseReplacement.markedLaw + (fun i => FiniteDistribution.uniform (CutChildGrouping.Child (C := C) (questionSlots clauses q) rows i)) + (replacementLaws rows clauses designated q) β hβ hβ' := by + rw [kernelJoint_observe] + simp only [kernels_markedBlocks] + exact MarkedKernelProduct.mixture_markedLaw _ _ _ β hβ hβ' + +abbrev Observation := + Σ q : Questions (branch := branch) (n := n) (t := t) (m := m), + Marked (C := C) rows clauses q + +def observe (sample : Sample (C := C) (t := t) rows clauses designated) : + Observation (branch := branch) (n := n) (C := C) (t := t) rows clauses := + let grouped := SourceQuestionKernelJoint.groupEquiv rows clauses designated sample + ⟨grouped.1.1, markedBlocks rows clauses designated grouped.1.1 grouped.1.2 grouped.2⟩ + +@[simp] theorem observe_mask + (sample : Sample (C := C) (t := t) rows clauses designated) (i : Fin (branch n)) : + (observe rows clauses designated sample).2.1 i = + rawProjected rows clauses designated i (sample i).2.2 := rfl + +theorem original_marked_law [NeZero m] + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) : + (originalLaw (C := C) (t := t) rows clauses designated + (fun _ => ProjectionPosterior.bernoulli β hβ hβ')).pushforward + (observe rows clauses designated) = + CompletionSoundness.sigmaLaw + (PreliminarySampler.questionsLaw (branch := branch) (n := n + 1) (t := t) (m := m)) + (fun q => SparseReplacement.markedLaw + (fun i => FiniteDistribution.uniform + (CutChildGrouping.Child (C := C) (questionSlots clauses q) rows i)) + (replacementLaws rows clauses designated q) β hβ hβ') := by + unfold observe + rw [← FiniteDistribution.pushforward_comp + (originalLaw (C := C) (t := t) rows clauses designated + (fun _ => ProjectionPosterior.bernoulli β hβ hβ')) + (SourceQuestionKernelJoint.groupEquiv rows clauses designated) + (fun x => (⟨x.1.1, markedBlocks rows clauses designated x.1.1 x.1.2 x.2⟩ : + Observation (branch := branch) (n := n) (C := C) (t := t) rows clauses)), + SourceQuestionKernelJoint.originalLaw_group] + exact (joint_product_observe + (S := Questions (branch := branch) (n := n) (t := t) (m := m)) + (Z := SourceQuestionKernelJoint.ChoiceTuple (branch := branch) (n := n) (t := t)) + (A := SourceChildKernelJoint.RawTuple (C := C) (t := t) rows clauses designated) + (Y := fun q => Marked (C := C) rows clauses q) + (PreliminarySampler.questionsLaw (branch := branch) (n := n + 1) (t := t) (m := m)) + (FiniteProduct.law (fun _ : Fin (branch n) => + FiniteDistribution.uniform (Choice (branch := branch) (n := n) (t := t)))) + (fun q zs => FiniteProduct.law (fun i => kernel (C := C) (t := t) rows clauses designated + (fun _ => ProjectionPosterior.bernoulli β hβ hβ') i + (SourceQuestionKernelJoint.sources designated q zs i))) + (fun q x => markedBlocks rows clauses designated q x.1 x.2)).trans + (congrArg (CompletionSoundness.sigmaLaw + (PreliminarySampler.questionsLaw (branch := branch) (n := n + 1) (t := t) (m := m))) + (funext fun q => conditional_markedLaw rows clauses designated q β hβ hβ')) + +theorem original_extended_marked_law [NeZero m] {root : Nat} + (repeats : Nat → Nat) (p : DescendantSpaces.Path branch root (n + 1)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) : + (originalLaw (C := Option (WholeCutCalls.Index rows repeats p)) (t := t) + rows clauses designated (fun _ => ProjectionPosterior.bernoulli β hβ hβ')).pushforward + (observe rows clauses designated) = + CompletionSoundness.sigmaLaw + (PreliminarySampler.questionsLaw (branch := branch) (n := n + 1) (t := t) (m := m)) + (fun q => SparseReplacement.markedLaw + (fun i => FiniteDistribution.uniform + (CutChildGrouping.Child (C := Option (WholeCutCalls.Index rows repeats p)) + (questionSlots clauses q) rows i)) + (replacementLaws rows clauses designated q) β hβ hβ') := + original_marked_law rows clauses designated β hβ hβ' + +end +end PerfectCompleteness.SourceChildMarkedLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/SourceChildQuestionLaw.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/SourceChildQuestionLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..af93eb425abf43aadeb8b4f340c10b0d47816ef1 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/SourceChildQuestionLaw.lean @@ -0,0 +1,153 @@ +import OAI.Computability.PerfectCompleteness.Construction.HiddenBucketBias +import OAI.Computability.PerfectCompleteness.Sampling.PreliminarySampler +import OAI.Computability.PerfectCompleteness.Sampling.RationalFiniteLawLemmas +import OAI.Computability.PerfectCompleteness.Sampling.SourceChildKernelMarginalLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.SourceChildQuestionLaw + +open RecursiveSpaces TreeSourceSpaces HierarchicalArrays SourceQuestionReconstruction +open UniqueGamesTheorem.Foundations.Games +open scoped Classical + +noncomputable section + +variable {branch : Nat → Nat} {n m t v : Nat} + +def sourceLaw (m t : Nat) [NeZero m] (designated : Fin (branch n) → Slots branch n) : + FiniteDistribution (SourceChildKernel.Sources (m := m) (t := t) designated) := + FiniteProduct.law (fun i => (SourceOddLists.tupleLaw m t).product + (FiniteProduct.law (fun _ : {leaf : Slots branch n // leaf ≠ designated i} => + SourceOddLists.tupleLaw m t))) + +def assembleEquiv (designated : Fin (branch n) → Slots branch n) : + SourceChildKernel.Sources (m := m) (t := t) designated ≃ + (Slots branch (n + 1) → SourceTuple m t) where + toFun sources leaf := CleanSourceRecord.assemble designated leaf.1 + (sources leaf.1).1 (sources leaf.1).2 leaf.2 + invFun tree i := (Equiv.piSplitAt (designated i) (fun _ : Slots branch n => SourceTuple m t)) + (fun leaf => tree (i, leaf)) + left_inv sources := by + funext i + exact (Equiv.piSplitAt (designated i) (fun _ : Slots branch n => SourceTuple m t)).apply_symm_apply + (sources i) + right_inv tree := by + funext leaf + exact congrFun + ((Equiv.piSplitAt (designated leaf.1) (fun _ : Slots branch n => SourceTuple m t)).symm_apply_apply + (fun s => tree (leaf.1, s))) leaf.2 + +theorem assemble_child_law (designated : Fin (branch n) → Slots branch n) + (μ : FiniteDistribution (SourceTuple m t)) (i : Fin (branch n)) : + (μ.product (FiniteProduct.law + (fun _ : {leaf : Slots branch n // leaf ≠ designated i} => μ))).pushforward + (fun source => CleanSourceRecord.assemble designated i source.1 source.2) = + FiniteProduct.law (fun _ : Slots branch n => μ) := by + let split := Equiv.piSplitAt (designated i) (fun _ : Slots branch n => SourceTuple m t) + have hsplit : (FiniteProduct.law (fun _ : Slots branch n => μ)).pushforward split = + μ.product (FiniteProduct.law + (fun _ : {leaf : Slots branch n // leaf ≠ designated i} => μ)) := + SourceCoordinateSplit.coordinate_split_pushforward (fun _ : Slots branch n => μ) (designated i) + change (μ.product (FiniteProduct.law + (fun _ : {leaf : Slots branch n // leaf ≠ designated i} => μ))).pushforward split.symm = _ + rw [← hsplit, FiniteDistribution.pushforward_comp] + simp only [Equiv.symm_apply_apply] + exact UniqueGamesTheorem.Foundations.Games.FiniteDistribution.pushforward_id + (FiniteProduct.law (fun _ : Slots branch n => μ)) + +private theorem uniform_product {A B : Type*} [Fintype A] [Fintype B] + [Nonempty A] [Nonempty B] : + (FiniteDistribution.uniform A).product (FiniteDistribution.uniform B) = + FiniteDistribution.uniform (A × B) := by + apply FiniteDistribution.eq_of_weight_eq + intro x + simp only [FiniteDistribution.product, FiniteDistribution.uniform, + Fintype.card_prod, Nat.cast_mul, one_div_mul_one_div] + +private theorem uniform_equiv {A B : Type*} [Fintype A] [Fintype B] + [Nonempty A] [Nonempty B] (e : A ≃ B) : + (FiniteDistribution.uniform A).pushforward e = FiniteDistribution.uniform B := by + rw [FiniteDistribution.pushforward_equiv] + apply FiniteDistribution.eq_of_weight_eq + intro x + change 1 / (Fintype.card A : ℝ) = 1 / (Fintype.card B : ℝ) + rw [Fintype.card_congr e] + +theorem sourceLaw_uniform [NeZero m] (designated : Fin (branch n) → Slots branch n) : + sourceLaw m t designated = + FiniteDistribution.uniform (SourceChildKernel.Sources (m := m) (t := t) designated) := by + simp only [sourceLaw, SourceOddLists.tupleLaw, FiniteDistribution.iid_uniform, + UniformLinearImage.law_uniform, uniform_product] + +theorem assemble_law [NeZero m] (designated : Fin (branch n) → Slots branch n) : + (sourceLaw m t designated).pushforward (assembleEquiv (m := m) (t := t) designated) = + FiniteDistribution.uniform (Slots branch (n + 1) → SourceTuple m t) := by + rw [sourceLaw_uniform] + exact uniform_equiv _ + +def questions (designated : Fin (branch n) → Slots branch n) + (sources : SourceChildKernel.Sources (m := m) (t := t) designated) : + PreliminarySampler.Questions branch (n + 1) t m := + fun leaf k => (assembleEquiv designated sources leaf k).1 + +private def splitPositions : + (Slots branch (n + 1) → SourceTuple m t) ≃ + (PreliminarySampler.Questions branch (n + 1) t m × + (Slots branch (n + 1) → Fin t → Fin 3)) where + toFun tree := (fun leaf k => (tree leaf k).1, fun leaf k => (tree leaf k).2) + invFun parts leaf k := (parts.1 leaf k, parts.2 leaf k) + left_inv _ := rfl + right_inv _ := rfl + +theorem questions_law [NeZero m] (designated : Fin (branch n) → Slots branch n) : + (sourceLaw m t designated).pushforward (questions designated) = + PreliminarySampler.questionsLaw (branch := branch) (n := n + 1) (t := t) (m := m) := by + let e := splitPositions (branch := branch) (n := n) (m := m) (t := t) + calc + _ = (((sourceLaw m t designated).pushforward + (assembleEquiv (m := m) (t := t) designated)).pushforward e).pushforward Prod.fst := by + rw [FiniteDistribution.pushforward_comp, FiniteDistribution.pushforward_comp]; rfl + _ = ((FiniteDistribution.uniform (Slots branch (n + 1) → SourceTuple m t)).pushforward e).pushforward + Prod.fst := by rw [assemble_law] + _ = (FiniteDistribution.uniform + (PreliminarySampler.Questions branch (n + 1) t m × + (Slots branch (n + 1) → Fin t → Fin 3))).pushforward Prod.fst := by + rw [uniform_equiv] + _ = _ := by + rw [← uniform_product, HiddenBucketBias.product_fst]; rfl + +theorem parentLeftSlots_eq (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch n) → Slots branch n) + (sources : SourceChildKernel.Sources (m := m) (t := t) designated) : + SourceChildKernel.parentLeftSlots clauses designated sources = + HierarchicalArrays.sourceSlots clauses (PreliminarySampler.endpoints (questions designated sources)) := rfl + +theorem originalLaw_sources {C : Type*} [Fintype C] [NeZero m] + (rows : Nat → Nat) (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch n) → Slots branch n) + (flag : Fin (branch n) → FiniteDistribution Bool) : + (SourceChildKernel.originalLaw (C := C) (t := t) rows clauses designated flag).pushforward + (SourceChildKernelMarginal.sources rows clauses designated) = sourceLaw m t designated := + SourceChildKernelMarginal.originalLaw_sources rows clauses designated flag + +theorem originalLaw_questions {C : Type*} [Fintype C] [NeZero m] + (rows : Nat → Nat) (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch n) → Slots branch n) + (flag : Fin (branch n) → FiniteDistribution Bool) : + (SourceChildKernel.originalLaw (C := C) (t := t) rows clauses designated flag).pushforward + (fun sample => questions designated (SourceChildKernelMarginal.sources rows clauses designated sample)) = + PreliminarySampler.questionsLaw (branch := branch) (n := n + 1) (t := t) (m := m) := by + rw [← FiniteDistribution.pushforward_comp + (SourceChildKernel.originalLaw (C := C) (t := t) rows clauses designated flag) + (SourceChildKernelMarginal.sources rows clauses designated) (questions designated), originalLaw_sources] + exact questions_law designated + +end +end PerfectCompleteness.SourceChildQuestionLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/SourcePhysicalAssemblyLaw.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/SourcePhysicalAssemblyLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..03692ad349b76d78420606013bfdbe3a54eae23f --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/SourcePhysicalAssemblyLaw.lean @@ -0,0 +1,147 @@ +import OAI.Computability.PerfectCompleteness.Construction.SourceChildKernelLemmas +import OAI.Computability.PerfectCompleteness.Foundations.DependentPredictionDifferenceLemmas +import OAI.Computability.PerfectCompleteness.Sampling.SourceChildKernelMarginalLemmas +import OAI.Computability.PerfectCompleteness.Sampling.SourceChildQuestionLaw + +namespace OAI + +section + +namespace PerfectCompleteness.SourcePhysicalAssemblyLaw + +open UniqueGamesTheorem.Foundations.Games +open RecursiveSpaces TreeSourceSpaces SourceChildKernel +open scoped Classical + +noncomputable section + +private theorem kernelJoint_pushforward_sigma {S R : Type*} {Y : S → Type*} + [Fintype S] [Fintype R] [∀ s, Fintype (Y s)] + (μ : FiniteDistribution S) (P : S → FiniteDistribution R) + (f : (s : S) → R → Y s) : + (CleanConditioning.kernelJoint μ P).pushforward + (fun x => (⟨x.1, f x.1 x.2⟩ : Σ s, Y s)) = + CompletionSoundness.sigmaLaw μ (fun s => (P s).pushforward (f s)) := by + apply SigmaObservation.eq_of_probability_eq + intro event + rw [FiniteDistribution.probability_pushforward, CleanConditioning.probability_kernelJoint, + CompletionSoundness.sigmaLaw_probability] + simp only [FiniteDistribution.expectation, FiniteDistribution.probability_pushforward] + +variable {branch : Nat → Nat} {n t v m : Nat} {C : Type*} [Fintype C] + (rows : Nat → Nat) (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch n) → Slots branch n) + +def assembleLeft (sources : Sources (m := m) (t := t) designated) + (raw : (i : Fin (branch n)) → Raw (C := C) (t := t) rows clauses designated i) : + CutChildGrouping.Assembled (C := C) (parentLeftSlots clauses designated sources) rows := + CutChildGrouping.assemble (parentLeftSlots clauses designated sources) rows + (leftChildren rows clauses designated sources raw) + +theorem assembleLeft_eq_sourcePullback + (sources : Sources (m := m) (t := t) designated) + (raw : (i : Fin (branch n)) → Raw (C := C) (t := t) rows clauses designated i) : + assembleLeft rows clauses designated sources raw = + ChildAssemblyProjection.assembledPullback rows + (parentProjection rows clauses designated sources raw) + (CutChildGrouping.assemble (parentRightSlots rows clauses designated sources raw) rows + (rightChildren rows clauses designated sources raw)) := + SourceChildKernel.assemble_leftChildren rows clauses designated sources raw + +theorem kernels_assembleLeft (flag : Fin (branch n) → FiniteDistribution Bool) + (sources : Sources (m := m) (t := t) designated) : + (FiniteProduct.law (fun i => + kernel (C := C) (t := t) rows clauses designated flag i (sources i))).pushforward + (assembleLeft rows clauses designated sources) = + (FiniteProduct.law (fun i => + SourceChildNativeLaw.leftLaw (C := C) (t := t) rows clauses designated flag i (sources i))).pushforward + (CutChildGrouping.assemble (C := C) (parentLeftSlots clauses designated sources) rows) := by + unfold assembleLeft + rw [← FiniteDistribution.pushforward_comp + (FiniteProduct.law (fun i => + kernel (C := C) (t := t) rows clauses designated flag i (sources i))) + (leftChildren rows clauses designated sources) + (CutChildGrouping.assemble (C := C) (parentLeftSlots clauses designated sources) rows), + SourceChildNativeLaw.kernels_leftChildren] + rfl + +theorem kernels_assembleLeft_false + (sources : Sources (m := m) (t := t) designated) : + (FiniteProduct.law (fun i => + kernel (C := C) (t := t) rows clauses designated + (fun _ => SourceChildNativeLaw.falseFlag) i (sources i))).pushforward + (assembleLeft rows clauses designated sources) = + FiniteDistribution.uniform + (CutChildGrouping.Assembled (C := C) (parentLeftSlots clauses designated sources) rows) := by + unfold assembleLeft + rw [← FiniteDistribution.pushforward_comp + (FiniteProduct.law (fun i => + kernel (C := C) (t := t) rows clauses designated + (fun _ => SourceChildNativeLaw.falseFlag) i (sources i))) + (leftChildren rows clauses designated sources) + (CutChildGrouping.assemble (C := C) (parentLeftSlots clauses designated sources) rows), + SourceChildNativeLaw.kernels_leftChildren_false] + exact CutChildGrouping.assemble_law (C := C) (parentLeftSlots clauses designated sources) rows + +abbrev Observation := + Σ sources : Sources (m := m) (t := t) designated, + CutChildGrouping.Assembled (C := C) (parentLeftSlots clauses designated sources) rows + +def observe (sample : Sample (C := C) (t := t) rows clauses designated) : + Observation (C := C) (t := t) rows clauses designated := + ⟨(SourceChildKernelJoint.groupEquiv rows clauses designated sample).1, + assembleLeft rows clauses designated + (SourceChildKernelJoint.groupEquiv rows clauses designated sample).1 + (SourceChildKernelJoint.groupEquiv rows clauses designated sample).2⟩ + +private theorem original_observe_kernel_law [NeZero m] + (flag : Fin (branch n) → FiniteDistribution Bool) : + (originalLaw (C := C) (t := t) rows clauses designated flag).pushforward + (observe rows clauses designated) = + CompletionSoundness.sigmaLaw (SourceChildQuestionLaw.sourceLaw m t designated) + (fun sources => + (FiniteProduct.law (fun i => + kernel (C := C) (t := t) rows clauses designated flag i (sources i))).pushforward + (assembleLeft rows clauses designated sources)) := by + unfold observe + rw [← FiniteDistribution.pushforward_comp + (originalLaw (C := C) (t := t) rows clauses designated flag) + (SourceChildKernelJoint.groupEquiv rows clauses designated) + (fun x => (⟨x.1, assembleLeft rows clauses designated x.1 x.2⟩ : + Observation (C := C) (t := t) rows clauses designated)), + SourceChildKernelJoint.originalLaw_group] + exact kernelJoint_pushforward_sigma (SourceChildQuestionLaw.sourceLaw m t designated) + (fun sources => FiniteProduct.law (fun i => + kernel (C := C) (t := t) rows clauses designated flag i (sources i))) + (assembleLeft rows clauses designated) + +theorem original_assembleLeft_law [NeZero m] + (flag : Fin (branch n) → FiniteDistribution Bool) : + (originalLaw (C := C) (t := t) rows clauses designated flag).pushforward + (observe rows clauses designated) = + CompletionSoundness.sigmaLaw (SourceChildQuestionLaw.sourceLaw m t designated) + (fun sources => + (FiniteProduct.law (fun i => SourceChildNativeLaw.leftLaw (C := C) (t := t) + rows clauses designated flag i (sources i))).pushforward + (CutChildGrouping.assemble (C := C) (parentLeftSlots clauses designated sources) rows)) := by + rw [original_observe_kernel_law] + exact congrArg (CompletionSoundness.sigmaLaw (SourceChildQuestionLaw.sourceLaw m t designated)) + (funext fun sources => kernels_assembleLeft rows clauses designated flag sources) + +theorem original_assembleLeft_false_law [NeZero m] : + (originalLaw (C := C) (t := t) rows clauses designated + (fun _ => SourceChildNativeLaw.falseFlag)).pushforward + (observe rows clauses designated) = + CompletionSoundness.sigmaLaw (SourceChildQuestionLaw.sourceLaw m t designated) + (fun sources => FiniteDistribution.uniform + (CutChildGrouping.Assembled (C := C) (parentLeftSlots clauses designated sources) rows)) := by + rw [original_observe_kernel_law] + exact congrArg (CompletionSoundness.sigmaLaw (SourceChildQuestionLaw.sourceLaw m t designated)) + (funext fun sources => kernels_assembleLeft_false (C := C) rows clauses designated sources) + +end +end PerfectCompleteness.SourcePhysicalAssemblyLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/SourcePhysicalWholeLaw.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/SourcePhysicalWholeLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..0c8974643c731d12956e2cae6795854fae6e86a0 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/SourcePhysicalWholeLaw.lean @@ -0,0 +1,119 @@ +import OAI.Computability.PerfectCompleteness.Repetition.CleanPhysicalReplayLaw +import OAI.Computability.PerfectCompleteness.Sampling.RationalFiniteLawLemmas +import OAI.Computability.PerfectCompleteness.Sampling.SourceChildKernelMarginalLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.SourcePhysicalWholeLaw + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +noncomputable section + +variable {branch : Nat → Nat} {root h t v m : Nat} + (rows repeats : Nat → Nat) (p : Path branch root (h + 1)) + (outside : Slots branch root → Fin t → MixedSupport.Slot) + (placeholder : Slots branch (h + 1) → Fin t → MixedSupport.Slot) + (clauses : Fin m → SourceClause.NormalizedClause v) + (designated : Fin (branch h) → Slots branch h) + +abbrev Raw := CleanPhysicalReplay.Exterior rows repeats p outside placeholder × + ((i : Fin (branch h)) → SourceChildKernel.Raw + (C := WholeCutCalls.Index rows repeats p) (t := t) rows clauses designated i) + +def rawLaw (flag : Fin (branch h) → FiniteDistribution Bool) + (sources : SourceChildKernel.Sources (m := m) (t := t) designated) : + FiniteDistribution (Raw rows repeats p outside placeholder clauses designated) := + (FiniteDistribution.uniform (CleanPhysicalReplay.Exterior rows repeats p outside placeholder)).product + (FiniteProduct.law (fun i => SourceChildKernel.kernel + (C := WholeCutCalls.Index rows repeats p) (t := t) rows clauses designated flag i (sources i))) + +def nativeBlockLaw (flag : Fin (branch h) → FiniteDistribution Bool) + (sources : SourceChildKernel.Sources (m := m) (t := t) designated) : + FiniteDistribution (CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) + (SourceChildKernel.parentLeftSlots clauses designated sources) rows) := + FiniteProduct.law (fun i => SourceChildNativeLaw.leftLaw + (C := WholeCutCalls.Index rows repeats p) (t := t) rows clauses designated flag i (sources i)) + +def observeLeft (sources : SourceChildKernel.Sources (m := m) (t := t) designated) + (sample : Raw rows repeats p outside placeholder clauses designated) : + Arrays (CutSlotAssembly.fill p outside (SourceChildKernel.parentLeftSlots clauses designated sources)) rows := + WholeCutSampler.evaluate rows repeats p + (CutSlotAssembly.fill p outside (SourceChildKernel.parentLeftSlots clauses designated sources)) + (CleanPhysicalReplay.physicalTape rows repeats p outside placeholder + (SourceChildKernel.parentLeftSlots clauses designated sources) sample.1 + (SourceChildKernel.leftChildren rows clauses designated sources sample.2)) + +theorem observeLeft_law (flag : Fin (branch h) → FiniteDistribution Bool) + (sources : SourceChildKernel.Sources (m := m) (t := t) designated) : + (rawLaw rows repeats p outside placeholder clauses designated flag sources).pushforward + (observeLeft rows repeats p outside placeholder clauses designated sources) = + ((FiniteDistribution.uniform (CleanPhysicalReplay.Exterior rows repeats p outside placeholder)).product + (nativeBlockLaw rows repeats p clauses designated flag sources)).pushforward + (fun x => WholeCutSampler.evaluate rows repeats p + (CutSlotAssembly.fill p outside (SourceChildKernel.parentLeftSlots clauses designated sources)) + (CleanPhysicalReplay.physicalTape rows repeats p outside placeholder + (SourceChildKernel.parentLeftSlots clauses designated sources) x.1 x.2)) := by + let decode := fun sample : Raw rows repeats p outside placeholder clauses designated => + (sample.1, SourceChildKernel.leftChildren rows clauses designated sources sample.2) + let evaluate := fun x : CleanPhysicalReplay.Exterior rows repeats p outside placeholder × + CutChildGrouping.Raw (C := WholeCutCalls.Index rows repeats p) + (SourceChildKernel.parentLeftSlots clauses designated sources) rows => + WholeCutSampler.evaluate rows repeats p + (CutSlotAssembly.fill p outside (SourceChildKernel.parentLeftSlots clauses designated sources)) + (CleanPhysicalReplay.physicalTape rows repeats p outside placeholder + (SourceChildKernel.parentLeftSlots clauses designated sources) x.1 x.2) + calc + _ = ((rawLaw rows repeats p outside placeholder clauses designated flag sources).pushforward + decode).pushforward evaluate := (FiniteDistribution.pushforward_comp _ _ _).symm + _ = _ := by + have hdecode : (rawLaw rows repeats p outside placeholder clauses designated flag sources).pushforward + decode = + (FiniteDistribution.uniform (CleanPhysicalReplay.Exterior rows repeats p outside placeholder)).product + (nativeBlockLaw rows repeats p clauses designated flag sources) := by + unfold rawLaw + change ((FiniteDistribution.uniform + (CleanPhysicalReplay.Exterior rows repeats p outside placeholder)).product + (FiniteProduct.law (fun i => SourceChildKernel.kernel + (C := WholeCutCalls.Index rows repeats p) (t := t) rows clauses designated flag i (sources i)))).pushforward + (fun sample => ((id : CleanPhysicalReplay.Exterior rows repeats p outside placeholder → + CleanPhysicalReplay.Exterior rows repeats p outside placeholder) sample.1, + SourceChildKernel.leftChildren rows clauses designated sources sample.2)) = _ + rw [FiniteDistribution.product_pushforward, + UniqueGamesTheorem.Foundations.Games.FiniteDistribution.pushforward_id + (FiniteDistribution.uniform (CleanPhysicalReplay.Exterior rows repeats p outside placeholder)), + SourceChildNativeLaw.kernels_leftChildren] + rfl + rw [hdecode] + +theorem nativeBlockLaw_false + (sources : SourceChildKernel.Sources (m := m) (t := t) designated) : + nativeBlockLaw rows repeats p clauses designated (fun _ => SourceChildNativeLaw.falseFlag) sources = + CutChildGrouping.rawLaw (C := WholeCutCalls.Index rows repeats p) + (SourceChildKernel.parentLeftSlots clauses designated sources) rows := by + unfold nativeBlockLaw CutChildGrouping.rawLaw + apply congrArg FiniteProduct.law + funext i + exact SourceChildNativeLaw.leftLaw_false rows clauses designated i (sources i) + +theorem observeLeft_false_law + (sources : SourceChildKernel.Sources (m := m) (t := t) designated) : + (rawLaw rows repeats p outside placeholder clauses designated + (fun _ => SourceChildNativeLaw.falseFlag) sources).pushforward + (observeLeft rows repeats p outside placeholder clauses designated sources) = + WholeArraySampler.law rows repeats p + (CutSlotAssembly.fill p outside (SourceChildKernel.parentLeftSlots clauses designated sources)) := by + rw [observeLeft_law, nativeBlockLaw_false] + exact CleanPhysicalReplayLaw.evaluate_physicalTape_law rows repeats p outside placeholder + (SourceChildKernel.parentLeftSlots clauses designated sources) + +end +end PerfectCompleteness.SourcePhysicalWholeLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/StoppedBucketUsefulProbability.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/StoppedBucketUsefulProbability.lean new file mode 100644 index 0000000000000000000000000000000000000000..0f3b7d6cedaef0de25e4b8009fad9654a3e93c84 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/StoppedBucketUsefulProbability.lean @@ -0,0 +1,100 @@ +import OAI.Computability.PerfectCompleteness.Construction.HiddenBucketBias +import OAI.Computability.PerfectCompleteness.Reduction.PreliminaryAveraging +import OAI.Computability.PerfectCompleteness.Sampling.StoppedUsefulPairLaw + +namespace OAI + +section + +namespace PerfectCompleteness.StoppedBucketUsefulProbability + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCutTape WholeArrayInteriorExterior +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype + +private theorem probability_product_fst {A B : Type*} [Fintype A] [Fintype B] + (μ : FiniteDistribution A) (ν : FiniteDistribution B) (event : A → Bool) : + (μ.product ν).probability (fun z => event z.1) = μ.probability event := by + have h := FiniteDistribution.probability_pushforward (μ.product ν) Prod.fst event + rw [HiddenBucketBias.product_fst] at h + exact h.symm + +variable {branch : Nat → Nat} {N j i t : Nat} + (rows repeats : Nat → Nat) (p : Path branch N (j + 1)) + (chosen : Fin (branch j)) (q : Path branch j i) + (native right : Slots branch N → Fin t → MixedSupport.Slot) + (projection : ∀ s a, MixedSupport.Projection (native s a) (right s a)) + +local instance rowSpaceFintype : Fintype (NodeEmbedding.RowSpace native (upperNode p)) := + Fintype.ofFinite _ + +local instance backgroundFintype : + Fintype (HierarchicalMatrixTable.Background (rows := rows) native (upperNode p)) := + Fintype.ofFinite _ + +variable (hrows : 0 < rows (j + 1)) (lowerLevel : Nat) {Ω : Type*} [Fintype Ω] + (original : FiniteDistribution Ω) (arrays : Ω → Arrays native rows) + (lowerEvent : Ω → Bool) (κ : ℝ) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch N t)) + +theorem usefulEvent_observe + (sample : StoppedUsefulPairLaw.Sample rows repeats p chosen q right) : + HierarchicalUsefulCollision.usefulEvent native (upperNode p) lowerLevel + original arrays lowerEvent κ σ + (StoppedUsefulPairLaw.background rows repeats p chosen q native right projection) + (StoppedUsefulPairLaw.observe rows repeats p chosen q native right projection sample) = + HierarchicalUsefulCollision.usefulAccepted native (upperNode p) lowerLevel + original arrays lowerEvent κ σ + (StoppedUsefulPairLaw.background rows repeats p chosen q native right projection + (StoppedUsefulPairLaw.readout rows repeats p chosen q native right projection sample.2.1).1) + (CutNodeRows.directionEquiv rows p sample.1) + (CutNodeRows.bucketTapeEquiv rows p native + (StoppedUsefulPairLaw.readout rows repeats p chosen q native right projection sample.2.1).2) := + rfl + +theorem useful_probability_eq : + (HierarchicalUsefulCollision.law native (upperNode p) + (StoppedUsefulPairLaw.externalLaw rows repeats p chosen q right) + (StoppedUsefulPairLaw.scalarLaw rows repeats p chosen q native right projection) + (by simpa only [upperNode_height] using hrows)).probability + (HierarchicalUsefulCollision.usefulEvent native (upperNode p) lowerLevel + original arrays lowerEvent κ σ + (StoppedUsefulPairLaw.background rows repeats p chosen q native right projection)) = + (StoppedUsefulPairLaw.directionLaw rows j hrows).expectation (fun a => + (WholeArraySampler.tapeLaw rows repeats (p.append (.step chosen q)) right).probability + (fun tape => HierarchicalUsefulCollision.usefulAccepted native (upperNode p) lowerLevel + original arrays lowerEvent κ σ + (StoppedUsefulPairLaw.background rows repeats p chosen q native right projection + (StoppedUsefulPairLaw.readout rows repeats p chosen q native right projection tape).1) + (CutNodeRows.directionEquiv rows p a) + (CutNodeRows.bucketTapeEquiv rows p native + (StoppedUsefulPairLaw.readout rows repeats p chosen q native right projection tape).2))) := by + rw [← StoppedUsefulPairLaw.observe_law rows repeats p chosen q native right projection hrows, + FiniteDistribution.probability_pushforward] + simp_rw [usefulEvent_observe] + rw [StoppedUsefulPairLaw.actualLaw, PreliminaryAveraging.probability_product] + apply FiniteDistribution.expectation_congr + intro a + exact probability_product_fst + (WholeArraySampler.tapeLaw rows repeats (p.append (.step chosen q)) right) + (RecursiveSampler.law F2 repeats (.step chosen q) (LeafDomain (cutSlots p right))) + (fun tape => HierarchicalUsefulCollision.usefulAccepted native (upperNode p) lowerLevel + original arrays lowerEvent κ σ + (StoppedUsefulPairLaw.background rows repeats p chosen q native right projection + (StoppedUsefulPairLaw.readout rows repeats p chosen q native right projection tape).1) + (CutNodeRows.directionEquiv rows p a) + (CutNodeRows.bucketTapeEquiv rows p native + (StoppedUsefulPairLaw.readout rows repeats p chosen q native right projection tape).2)) + +end +end PerfectCompleteness.StoppedBucketUsefulProbability + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/StoppedProjectedGlobalLawLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/StoppedProjectedGlobalLawLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..717d24d4b06d01d2ced71c68d6a04741157280bd --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/StoppedProjectedGlobalLawLemmas.lean @@ -0,0 +1,273 @@ +import OAI.Computability.PerfectCompleteness.Foundations.StoppedProjectedArrays +import OAI.Computability.PerfectCompleteness.Foundations.StoppedProjectedContext + +namespace OAI + +section + +namespace PerfectCompleteness.StoppedProjectedGlobalLaw + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +variable {branch : Nat → Nat} {n i j t v m : Nat} + (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hupper : j + 1 ≤ n) (hij : i < j) (hi : i + 1 ≤ n) + (designated : Fin (branch i) → Slots branch i) + +abbrev Context := StoppedProjectedContext.Sample (branch := branch) (n := n) + (i := i) (t := t) (m := m) rows + +abbrev Outer := StoppedProjectedExperiment.Outer (branch := branch) (n := n) + (j := j) (t := t) (m := m) + +def projectedSlots (x : Context (branch := branch) (n := n) (i := i) (t := t) (m := m) rows) := + StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated + (StoppedProjectedContext.splitEquiv rows hupper hij x).1 + (StoppedProjectedContext.splitEquiv rows hupper hij x).2 + +theorem projectedSlots_eq + (x : Context (branch := branch) (n := n) (i := i) (t := t) (m := m) rows) : + projectedSlots clauses rows hupper hij designated x = + CutSlotAssembly.fill (GeometricCutSplit.prefixPath hi x.1.2.1) + (sourceSlots clauses (PreliminarySampler.endpoints x.1.1)) + (SourceProjectedTag.mixedInside clauses designated + (fun leaf a => x.1.1 ((GeometricCutSplit.prefixPath hi x.1.2.1).slotEmbedding leaf) a) + x.2.1 x.2.2) := by + unfold projectedSlots StoppedProjectedExperiment.projectedSlots + StoppedProjectedExperiment.cutQuestions + rw [StoppedProjectedContext.stoppedPath_split rows hupper hij hi x] + rfl + +abbrev Sample := + (x : Context (branch := branch) (n := n) (i := i) (t := t) (m := m) rows) × + WholeArraySampler.Tape rows repeats (GeometricCutSplit.prefixPath hi x.1.2.1) + (projectedSlots clauses rows hupper hij designated x) + +abbrev ExperimentSample := + (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) × + HierarchicalProjectedExperiment.Sample (rows := rows) (repeats := repeats) + (StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated o) + (StoppedProjectedExperiment.upper hupper o) + (StoppedProjectedExperiment.lower rows hupper hij o) + (StoppedProjectedExperiment.cut rows hupper hij o) + +def read (sample : Sample (t := t) clauses rows repeats hupper hij hi designated) : + ExperimentSample (t := t) clauses rows repeats hupper hij designated := + let parts := StoppedProjectedContext.splitEquiv rows hupper hij sample.1 + ⟨parts.1, ⟨parts.2, StoppedOwnInputGeometry.pathTapeEquiv rows repeats + (projectedSlots clauses rows hupper hij designated sample.1) + (StoppedProjectedContext.fullPath_split_spec rows hupper hij hi sample.1).symm sample.2⟩⟩ + +variable [NeZero m] (hbranch : ∀ k < n, 0 < branch k) + (hrows : ∀ k, 0 < rows (k + 1)) + (flag : Fin (branch i) → FiniteDistribution Bool) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + +def law : FiniteDistribution (Sample (t := t) clauses rows repeats hupper hij hi designated) := + CompletionSoundness.sigmaLaw + ((StoppedSharedSampler.contextLaw (t := t) (m := m) (cut := i) hi hbranch hrows).product + (SourceProjectedTag.law (t := t) flag)) + (fun x => WholeArraySampler.tapeLaw rows repeats + (GeometricCutSplit.prefixPath hi x.1.2.1) (projectedSlots clauses rows hupper hij designated x)) + +abbrev experiment (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) := + StoppedProjectedExperiment.experiment clauses rows repeats hupper hij designated + (fun k hk => hbranch k (Nat.lt_of_lt_of_le hk hupper)) hrows flag σ o + +def experimentLaw : FiniteDistribution (ExperimentSample (t := t) clauses rows repeats hupper hij designated) := + CompletionSoundness.sigmaLaw (StoppedProjectedExperiment.outerLaw (t := t) (m := m) hupper hbranch) + (fun o => (experiment clauses rows repeats hupper hij designated hbranch hrows flag σ o).original) + +omit [NeZero m] in +theorem fiber_probability + (x : Context (branch := branch) (n := n) (i := i) (t := t) (m := m) rows) + (event : ExperimentSample (t := t) clauses rows repeats hupper hij designated → Bool) : + (WholeArraySampler.tapeLaw rows repeats (GeometricCutSplit.prefixPath hi x.1.2.1) + (projectedSlots clauses rows hupper hij designated x)).probability + (fun tape => event (read clauses rows repeats hupper hij hi designated ⟨x, tape⟩)) = + (WholeArraySampler.tapeLaw rows repeats + (WholeArrayInteriorOwnInputLaw.fullPath + (StoppedProjectedExperiment.upper hupper (StoppedProjectedContext.splitEquiv rows hupper hij x).1) + (StoppedProjectedExperiment.lower rows hupper hij + (StoppedProjectedContext.splitEquiv rows hupper hij x).1 + (StoppedProjectedContext.splitEquiv rows hupper hij x).2) + (StoppedProjectedExperiment.cut rows hupper hij + (StoppedProjectedContext.splitEquiv rows hupper hij x).1 + (StoppedProjectedContext.splitEquiv rows hupper hij x).2)) + (projectedSlots clauses rows hupper hij designated x)).probability + (fun tape => event ⟨(StoppedProjectedContext.splitEquiv rows hupper hij x).1, + ⟨(StoppedProjectedContext.splitEquiv rows hupper hij x).2, tape⟩⟩) := by + let observed := fun tape => event + (⟨(StoppedProjectedContext.splitEquiv rows hupper hij x).1, + ⟨(StoppedProjectedContext.splitEquiv rows hupper hij x).2, tape⟩⟩ : + ExperimentSample (t := t) clauses rows repeats hupper hij designated) + have h := congrArg (fun μ => FiniteDistribution.probability μ observed) + (StoppedOwnInputGeometry.pathTapeEquiv_law rows repeats + (projectedSlots clauses rows hupper hij designated x) + (StoppedProjectedContext.fullPath_split_spec rows hupper hij hi x).symm) + exact (FiniteDistribution.probability_pushforward + (WholeArraySampler.tapeLaw rows repeats (GeometricCutSplit.prefixPath hi x.1.2.1) + (projectedSlots clauses rows hupper hij designated x)) + (StoppedOwnInputGeometry.pathTapeEquiv rows repeats + (projectedSlots clauses rows hupper hij designated x) + (StoppedProjectedContext.fullPath_split_spec rows hupper hij hi x).symm) + observed).symm.trans h + +theorem probability_read + (event : ExperimentSample (t := t) clauses rows repeats hupper hij designated → Bool) : + (law clauses rows repeats hupper hij hi designated hbranch hrows flag).probability + (fun sample => event (read clauses rows repeats hupper hij hi designated sample)) = + (experimentLaw clauses rows repeats hupper hij designated hbranch hrows flag σ).probability event := by + unfold law + rw [CompletionSoundness.sigmaLaw_probability] + let value := fun z : StoppedProjectedContext.SplitSample + (branch := branch) (n := n) (i := i) (j := j) (t := t) (m := m) rows => + (WholeArraySampler.tapeLaw rows repeats + (WholeArrayInteriorOwnInputLaw.fullPath (StoppedProjectedExperiment.upper hupper z.1) + (StoppedProjectedExperiment.lower rows hupper hij z.1 z.2) + (StoppedProjectedExperiment.cut rows hupper hij z.1 z.2)) + (StoppedProjectedExperiment.projectedSlots clauses rows hupper hij designated z.1 z.2)).probability + (fun tape => event ⟨z.1, ⟨z.2, tape⟩⟩) + calc + _ = ((StoppedSharedSampler.contextLaw (t := t) (m := m) (cut := i) hi hbranch hrows).product + (SourceProjectedTag.law (t := t) flag)).expectation + (fun x => value (StoppedProjectedContext.splitEquiv rows hupper hij x)) := by + apply FiniteDistribution.expectation_congr + intro x + exact fiber_probability clauses rows repeats hupper hij hi designated x event + _ = ((StoppedProjectedExperiment.outerLaw (t := t) (m := m) hupper hbranch).product + (StoppedProjectedExperiment.innerLaw rows hij + (fun k hk => hbranch k (Nat.lt_of_lt_of_le hk hupper)) hrows flag)).expectation value := + StoppedProjectedContext.expectation_split rows hupper hij hi hbranch hrows flag value + _ = _ := by + simp only [experimentLaw, experiment, StoppedProjectedExperiment.experiment, + HierarchicalProjectedExperiment.experiment, HierarchicalProjectedExperiment.originalLaw, + CompletionSoundness.sigmaLaw_probability, FiniteDistribution.expectation_product] + rfl + +theorem read_law : + (law clauses rows repeats hupper hij hi designated hbranch hrows flag).pushforward + (read clauses rows repeats hupper hij hi designated) = + experimentLaw clauses rows repeats hupper hij designated hbranch hrows flag σ := by + apply SigmaObservation.eq_of_probability_eq + intro event + rw [FiniteDistribution.probability_pushforward] + exact probability_read clauses rows repeats hupper hij hi designated hbranch hrows flag σ event + +omit [NeZero m] in +theorem arrays_read + (sample : Sample (t := t) clauses rows repeats hupper hij hi designated) : + (experiment clauses rows repeats hupper hij designated hbranch hrows flag σ + (read clauses rows repeats hupper hij hi designated sample).1).arrays + (read clauses rows repeats hupper hij hi designated sample).2 = + ChildBlockProjection.arraysPullback rows + (StoppedProjectedExperiment.projection clauses rows hupper hij designated + (StoppedProjectedContext.splitEquiv rows hupper hij sample.1).1 + (StoppedProjectedContext.splitEquiv rows hupper hij sample.1).2) + (WholeArraySampler.evaluate rows repeats (GeometricCutSplit.prefixPath hi sample.1.1.2.1) + (projectedSlots clauses rows hupper hij designated sample.1) sample.2) := + congrArg (ChildBlockProjection.arraysPullback rows + (StoppedProjectedExperiment.projection clauses rows hupper hij designated + (StoppedProjectedContext.splitEquiv rows hupper hij sample.1).1 + (StoppedProjectedContext.splitEquiv rows hupper hij sample.1).2)) + (StoppedOwnInputGeometry.evaluate_pathTapeEquiv rows repeats + (projectedSlots clauses rows hupper hij designated sample.1) + (StoppedProjectedContext.fullPath_split_spec rows hupper hij hi sample.1).symm sample.2) + +end +end PerfectCompleteness.StoppedProjectedGlobalLaw + +end + +section + +namespace PerfectCompleteness.StoppedProjectedPhysicalLaw + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games + +variable {branch : Nat → Nat} {n i j t v m : Nat} + (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hupper : j + 1 ≤ n) (hij : i < j) + (designated : Fin (branch i) → Slots branch i) + +abbrev Outer := StoppedProjectedExperiment.Outer (branch := branch) (n := n) + (j := j) (t := t) (m := m) + +abbrev Sample := + (o : Outer (branch := branch) (n := n) (j := j) (t := t) (m := m)) × + StoppedProjectedExperiment.PhysicalSample clauses rows repeats hupper hij designated o + +def read (sample : Sample (t := t) clauses rows repeats hupper hij designated) : + StoppedProjectedGlobalLaw.ExperimentSample (t := t) clauses rows repeats hupper hij designated := + ⟨sample.1, StoppedProjectedExperiment.physicalExperimentRead + clauses rows repeats hupper hij designated sample.1 sample.2⟩ + +variable [NeZero m] + (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) + (flag : Fin (branch i) → FiniteDistribution Bool) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) + +def law : FiniteDistribution (Sample (t := t) clauses rows repeats hupper hij designated) := + CompletionSoundness.sigmaLaw (StoppedProjectedExperiment.outerLaw (t := t) (m := m) hupper hbranch) + (StoppedProjectedExperiment.physicalLaw clauses rows repeats hupper hij designated + (fun k hk => hbranch k (Nat.lt_of_lt_of_le hk hupper)) hrows flag) + +theorem read_law : + (law clauses rows repeats hupper hij designated hbranch hrows flag).pushforward + (read clauses rows repeats hupper hij designated) = + StoppedProjectedGlobalLaw.experimentLaw clauses rows repeats hupper hij designated + hbranch hrows flag σ := by + unfold law read + rw [SigmaObservation.pushforward_fiber] + unfold StoppedProjectedGlobalLaw.experimentLaw + congr 1 + funext o + exact StoppedProjectedExperiment.physicalExperimentRead_law + clauses rows repeats hupper hij designated + (fun k hk => hbranch k (Nat.lt_of_lt_of_le hk hupper)) hrows flag σ o + +theorem expectation_read + (value : StoppedProjectedGlobalLaw.ExperimentSample (t := t) + clauses rows repeats hupper hij designated → ℝ) : + (law clauses rows repeats hupper hij designated hbranch hrows flag).expectation + (fun sample => value (read clauses rows repeats hupper hij designated sample)) = + (StoppedProjectedGlobalLaw.experimentLaw clauses rows repeats hupper hij designated + hbranch hrows flag σ).expectation value := by + rw [← read_law clauses rows repeats hupper hij designated hbranch hrows flag σ] + exact (FiniteDistribution.expectation_pushforward _ _ _).symm + +theorem probability_read + (event : StoppedProjectedGlobalLaw.ExperimentSample (t := t) + clauses rows repeats hupper hij designated → Bool) : + (law clauses rows repeats hupper hij designated hbranch hrows flag).probability + (fun sample => event (read clauses rows repeats hupper hij designated sample)) = + (StoppedProjectedGlobalLaw.experimentLaw clauses rows repeats hupper hij designated + hbranch hrows flag σ).probability event := by + rw [← read_law clauses rows repeats hupper hij designated hbranch hrows flag σ, + FiniteDistribution.probability_pushforward] + +omit [NeZero m] in +theorem arrays_read_heq (sample : Sample (t := t) clauses rows repeats hupper hij designated) : + HEq ((StoppedProjectedGlobalLaw.experiment clauses rows repeats hupper hij designated + hbranch hrows flag σ sample.1).arrays + (read clauses rows repeats hupper hij designated sample).2) + (StoppedProjectedArrays.physicalArrays clauses rows repeats hupper hij designated + sample.1 sample.2) := + StoppedProjectedArrays.arrays_physicalExperimentRead_heq + clauses rows repeats hupper hij designated + (fun k hk => hbranch k (Nat.lt_of_lt_of_le hk hupper)) hrows flag σ sample.1 sample.2 + +end +end PerfectCompleteness.StoppedProjectedPhysicalLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/StoppedProjectedMeetingLaw.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/StoppedProjectedMeetingLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..179d65928b813d80a8319d9356c25e0cd1c5aebd --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/StoppedProjectedMeetingLaw.lean @@ -0,0 +1,100 @@ +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalProjectedPredictionLemmas +import OAI.Computability.PerfectCompleteness.Foundations.StoppedProjectedPhysicalAdvice + +namespace OAI + +section + +namespace PerfectCompleteness.StoppedProjectedMeetingLaw + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) +attribute [local instance] linearMapFintype +attribute [local instance] StoppedProjectedPhysicalAdvice.adviceFintype + StoppedProjectedPhysicalAdvice.physicalAdviceFintype + StoppedProjectedPhysicalAdvice.rawFiberFintype + +variable {δ : ℚ} (plan : FixedRows.Plan δ) + +theorem rows_positive (k : Nat) : 0 < FixedRows.rows plan (k + 1) := + plan.rows_pos (plan.depth - (k + 1)) + +variable {branch : Nat → Nat} {i j t v m : Nat} + (clauses : Fin m → SourceClause.NormalizedClause v) + (hupper : j + 1 ≤ plan.depth) (hij : i < j) + (designated : Fin (branch i) → Slots branch i) + +abbrev Sample := StoppedProjectedPhysicalAdvice.Sample (t := t) clauses + (FixedRows.rows plan) (FixedRows.repeats plan) hupper hij designated plan.order + +abbrev RawSample := StoppedProjectedPhysicalAdvice.RawSample (t := t) clauses + (FixedRows.rows plan) (FixedRows.repeats plan) hupper hij designated plan.order + +variable [NeZero m] + (hbranch : ∀ k < plan.depth, 0 < branch k) + (flag : Fin (branch i) → FiniteDistribution Bool) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch plan.depth t)) + +def rawMeetingProbability + (sample : RawSample (t := t) plan clauses hupper hij designated) : ℝ := + HierarchicalProjectedAverage.meetingProbability plan + (StoppedProjectedExperiment.nativeSlots clauses sample.1) + (StoppedProjectedExperiment.projectedSlots clauses (FixedRows.rows plan) + hupper hij designated sample.1) + (StoppedProjectedExperiment.projection clauses (FixedRows.rows plan) + hupper hij designated sample.1) + (StoppedProjectedExperiment.upper hupper sample.1) (i + 1) + (StoppedProjectedExperiment.lower (FixedRows.rows plan) hupper hij sample.1) + (StoppedProjectedExperiment.cut (FixedRows.rows plan) hupper hij sample.1) + (StoppedProjectedExperiment.direction (FixedRows.rows plan) hupper hij sample.1) + (StoppedProjectedExperiment.innerLaw (FixedRows.rows plan) hij + (fun k hk => hbranch k (Nat.lt_of_lt_of_le hk hupper)) + (rows_positive plan) flag) σ sample.2 + +def meetingProbability + (sample : Sample (t := t) plan clauses hupper hij designated) : ℝ := + rawMeetingProbability plan clauses hupper hij designated hbranch flag σ + (StoppedProjectedPhysicalAdvice.read clauses (FixedRows.rows plan) + (FixedRows.repeats plan) hupper hij designated plan.order sample) + +abbrev expectedMeeting : ℝ := + HierarchicalProjectedOuterAverage.expectedMeeting plan + (StoppedProjectedExperiment.nativeSlots clauses) + (StoppedProjectedExperiment.projectedSlots clauses (FixedRows.rows plan) + hupper hij designated) + (StoppedProjectedExperiment.projection clauses (FixedRows.rows plan) + hupper hij designated) + (StoppedProjectedExperiment.upper hupper) (i + 1) + (StoppedProjectedExperiment.lower (FixedRows.rows plan) hupper hij) + (StoppedProjectedExperiment.cut (FixedRows.rows plan) hupper hij) + (StoppedProjectedExperiment.direction (FixedRows.rows plan) hupper hij) + (fun _ => StoppedProjectedExperiment.innerLaw (FixedRows.rows plan) hij + (fun k hk => hbranch k (Nat.lt_of_lt_of_le hk hupper)) + (rows_positive plan) flag) + (StoppedProjectedExperiment.outerLaw hupper hbranch) σ + +theorem expectation_meetingProbability : + (StoppedProjectedPhysicalAdvice.law clauses (FixedRows.rows plan) + (FixedRows.repeats plan) hupper hij designated hbranch + (rows_positive plan) flag plan.order).expectation + (meetingProbability plan clauses hupper hij designated hbranch flag σ) = + expectedMeeting plan clauses hupper hij designated hbranch flag σ := by + unfold meetingProbability + rw [StoppedProjectedPhysicalAdvice.expectation_read clauses (FixedRows.rows plan) + (FixedRows.repeats plan) hupper hij designated hbranch + (rows_positive plan) flag σ plan.order] + simp only [StoppedProjectedPhysicalAdvice.rawLaw, expectedMeeting, + HierarchicalProjectedOuterAverage.expectedMeeting, + CandidateCoupling.expectation_sigmaLaw, + HierarchicalProjectedAverage.expectedMeeting, rawMeetingProbability] + +end +end PerfectCompleteness.StoppedProjectedMeetingLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/StoppedProjectedUsefulProbability.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/StoppedProjectedUsefulProbability.lean new file mode 100644 index 0000000000000000000000000000000000000000..2b273cf727dc617722e6557fa5b5f527b7640376 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/StoppedProjectedUsefulProbability.lean @@ -0,0 +1,185 @@ +import OAI.Computability.PerfectCompleteness.Construction.HierarchicalBucketFamily +import OAI.Computability.PerfectCompleteness.Construction.StoppedProjectedBuckets +import OAI.Computability.PerfectCompleteness.Foundations.StoppedProjectedUsefulAverage +import OAI.Computability.PerfectCompleteness.Sampling.StoppedBucketUsefulProbability + +namespace OAI + +section + +namespace PerfectCompleteness.StoppedProjectedUsefulProbability + +noncomputable section + +open scoped Classical +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) + +attribute [local instance] linearMapFintype + +variable {branch : Nat → Nat} {n i j t v m : Nat} + (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hupper : j + 1 ≤ n) (hij : i < j) + (designated : Fin (branch i) → Slots branch i) + (hbranch : ∀ k < j + 1, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) + (flag : Fin (branch i) → FiniteDistribution Bool) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) (κ : ℝ) + +local notation "S" => StoppedProjectedExperiment.experiment clauses rows repeats hupper hij + designated hbranch hrows flag σ + +variable (o : StoppedProjectedExperiment.Outer + (branch := branch) (n := n) (j := j) (t := t) (m := m)) + +local instance nativeRowSpaceFintype : + Fintype (NodeEmbedding.RowSpace (StoppedProjectedExperiment.nativeSlots clauses o) + (StoppedProjectedExperiment.upper hupper o)) := Fintype.ofFinite _ + +theorem stepTape_law + (base : StoppedProjectedBucketIndex.Base (branch := branch) (i := i) (j := j) (t := t)) : + (StoppedProjectedBucketIndex.tapeLaw clauses rows repeats hupper hij designated hrows o base).pushforward + (fun tape => StoppedProjectedUsefulEvent.stepTape clauses rows repeats hupper hij designated o + ⟨StoppedProjectedBucketIndex.key (n := n) rows hrows base, tape⟩) = + WholeArraySampler.tapeLaw rows repeats + ((StoppedProjectedExperiment.upperPath hupper o).append + (.step (StoppedProjectedBuckets.chosen (n := n) rows hij hrows base) + (StoppedProjectedBuckets.continuation (n := n) rows hij hrows base))) + (StoppedProjectedBuckets.projected clauses rows hupper hij designated hrows o base) := + StoppedOwnInputGeometry.pathTapeEquiv_law rows repeats + (StoppedProjectedBuckets.projected clauses rows hupper hij designated hrows o base) + (congrArg (fun p : Path branch n (i + 1) => + (⟨i + 1, p⟩ : Σ height, Path branch n height)) + (StoppedProjectedUsefulEvent.stepPath_eq rows hupper hij o + (StoppedProjectedBucketIndex.key (n := n) rows hrows base))) + +theorem directionLaw_eq : + CanonicalDirections.levelLaw rows hrows (StoppedProjectedUsefulEvent.upperLevel hupper) = + StoppedUsefulPairLaw.directionLaw rows j (hrows j) := rfl + +theorem mean_eq_usefulProbability : + StoppedProjectedUsefulAverage.mean clauses rows repeats hupper hij designated + hbranch hrows flag σ κ o = + StoppedProjectedBuckets.usefulProbability clauses rows repeats hupper hij designated + hrows o hbranch flag σ κ := by + rw [StoppedProjectedBuckets.usefulProbability_eq_mean] + unfold StoppedProjectedUsefulAverage.mean + apply FiniteDistribution.expectation_congr + intro base + have hfixed := StoppedBucketUsefulProbability.useful_probability_eq rows repeats + (StoppedProjectedExperiment.upperPath hupper o) + (StoppedProjectedBuckets.chosen (n := n) rows hij hrows base) + (StoppedProjectedBuckets.continuation (n := n) rows hij hrows base) + (StoppedProjectedExperiment.nativeSlots clauses o) + (StoppedProjectedBuckets.projected clauses rows hupper hij designated hrows o base) + (StoppedProjectedBuckets.projection clauses rows hupper hij designated hrows o base) + (hrows j) (i + 1) (S o).original (S o).arrays + (HierarchicalAdviceExperiment.lowerEvent (S o)) κ σ + change _ = (HierarchicalUsefulCollision.law + (StoppedProjectedExperiment.nativeSlots clauses o) (StoppedProjectedExperiment.upper hupper o) + (StoppedProjectedBuckets.exteriorLaw clauses rows repeats hupper hij designated hrows o base) + (fun external => StoppedProjectedBuckets.scalarLaw clauses rows repeats hupper hij designated + hrows o ⟨base, external⟩) (StoppedProjectedBuckets.rows_positive rows hupper hrows o)).probability + (HierarchicalUsefulCollision.usefulEvent + (StoppedProjectedExperiment.nativeSlots clauses o) (StoppedProjectedExperiment.upper hupper o) + (i + 1) (S o).original (S o).arrays (HierarchicalAdviceExperiment.lowerEvent (S o)) κ σ + (fun external => StoppedProjectedBuckets.background clauses rows repeats hupper hij designated + hrows o ⟨base, external⟩)) + refine Eq.trans ?_ hfixed.symm + rw [directionLaw_eq rows hupper hrows] + apply FiniteDistribution.expectation_congr + intro direction + rw [← stepTape_law clauses rows repeats hupper hij designated hrows o base] + let event (tape : WholeArraySampler.Tape rows repeats + ((StoppedProjectedExperiment.upperPath hupper o).append + (.step (StoppedProjectedBuckets.chosen (n := n) rows hij hrows base) + (StoppedProjectedBuckets.continuation (n := n) rows hij hrows base))) + (StoppedProjectedBuckets.projected clauses rows hupper hij designated hrows o base)) : Bool := + let readout := StoppedUsefulPairLaw.readout rows repeats + (StoppedProjectedExperiment.upperPath hupper o) + (StoppedProjectedBuckets.chosen (n := n) rows hij hrows base) + (StoppedProjectedBuckets.continuation (n := n) rows hij hrows base) + (StoppedProjectedExperiment.nativeSlots clauses o) + (StoppedProjectedBuckets.projected clauses rows hupper hij designated hrows o base) + (StoppedProjectedBuckets.projection clauses rows hupper hij designated hrows o base) tape + HierarchicalUsefulCollision.usefulAccepted + (StoppedProjectedExperiment.nativeSlots clauses o) + (WholeArrayInteriorExterior.upperNode (StoppedProjectedExperiment.upperPath hupper o)) + (i + 1) (S o).original (S o).arrays (HierarchicalAdviceExperiment.lowerEvent (S o)) κ σ + (StoppedUsefulPairLaw.background rows repeats + (StoppedProjectedExperiment.upperPath hupper o) + (StoppedProjectedBuckets.chosen (n := n) rows hij hrows base) + (StoppedProjectedBuckets.continuation (n := n) rows hij hrows base) + (StoppedProjectedExperiment.nativeSlots clauses o) + (StoppedProjectedBuckets.projected clauses rows hupper hij designated hrows o base) + (StoppedProjectedBuckets.projection clauses rows hupper hij designated hrows o base) + readout.1) + (CutNodeRows.directionEquiv rows (StoppedProjectedExperiment.upperPath hupper o) direction) + (CutNodeRows.bucketTapeEquiv rows (StoppedProjectedExperiment.upperPath hupper o) + (StoppedProjectedExperiment.nativeSlots clauses o) readout.2) + have hp := FiniteDistribution.probability_pushforward + (Ω := StoppedProjectedBucketIndex.Tape clauses rows repeats hupper hij designated hrows o base) + (Γ := WholeArraySampler.Tape rows repeats + ((StoppedProjectedExperiment.upperPath hupper o).append + (.step (StoppedProjectedBuckets.chosen (n := n) rows hij hrows base) + (StoppedProjectedBuckets.continuation (n := n) rows hij hrows base))) + (StoppedProjectedBuckets.projected clauses rows hupper hij designated hrows o base)) + (StoppedProjectedBucketIndex.tapeLaw clauses rows repeats hupper hij designated hrows o base) + (fun tape => StoppedProjectedUsefulEvent.stepTape clauses rows repeats hupper hij designated o + ⟨StoppedProjectedBucketIndex.key (n := n) rows hrows base, tape⟩) event + have hevent : + StoppedProjectedUsefulAverage.bucketEvent clauses rows repeats hupper hij designated + hbranch hrows flag σ κ o base direction = + fun tape => event (StoppedProjectedUsefulEvent.stepTape clauses rows repeats hupper hij designated o + ⟨StoppedProjectedBucketIndex.key (n := n) rows hrows base, tape⟩) := by + funext tape + rfl + exact (congrArg + (StoppedProjectedBucketIndex.tapeLaw clauses rows repeats hupper hij designated hrows o base).probability + hevent).trans hp.symm + +theorem original_probability_eq_usefulProbability : + (S o).original.probability (fun x => HierarchicalUsefulFamily.usefulEvent S κ + (StoppedProjectedUsefulEvent.upperEvent clauses rows repeats hupper hij designated + hbranch hrows flag σ) ⟨o, x⟩) = + StoppedProjectedBuckets.usefulProbability clauses rows repeats hupper hij designated + hrows o hbranch flag σ κ := + (StoppedProjectedUsefulAverage.original_probability_eq_mean clauses rows repeats hupper hij + designated hbranch hrows flag σ κ o).trans + (mean_eq_usefulProbability clauses rows repeats hupper hij designated hbranch hrows flag σ κ o) + +local instance backgroundFintype (o : StoppedProjectedExperiment.Outer + (branch := branch) (n := n) (j := j) (t := t) (m := m)) : + Fintype (HierarchicalAdviceExperiment.Background (S o)) := + HierarchicalAdviceExperiment.backgroundFintype (S o) + +local instance rowSpaceFintype (o : StoppedProjectedExperiment.Outer + (branch := branch) (n := n) (j := j) (t := t) (m := m)) : + Fintype (NodeEmbedding.RowSpace (S o).slots (S o).upper) := Fintype.ofFinite _ + +theorem usefulMass_eq_original + (outer : FiniteDistribution (StoppedProjectedExperiment.Outer + (branch := branch) (n := n) (j := j) (t := t) (m := m))) : + HierarchicalBucketFamily.usefulMass S κ outer + (fun o => StoppedProjectedBuckets.externalLaw clauses rows repeats hupper hij designated + hrows o hbranch flag) + (fun o => StoppedProjectedBuckets.background clauses rows repeats hupper hij designated hrows o) + (fun o => StoppedProjectedBuckets.scalarLaw clauses rows repeats hupper hij designated hrows o) + (fun o => StoppedProjectedBuckets.rows_positive rows hupper hrows o) = + (HierarchicalUsefulFamily.originalLaw S outer).probability + (HierarchicalUsefulFamily.usefulEvent S κ + (StoppedProjectedUsefulEvent.upperEvent clauses rows repeats hupper hij designated + hbranch hrows flag σ)) := by + have hmean := FiniteDistribution.expectation_congr outer (fun context => + (original_probability_eq_usefulProbability clauses rows repeats hupper hij designated + hbranch hrows flag σ κ context).symm) + exact hmean.trans (HierarchicalUsefulFamily.useful_probability_eq_mean S outer κ + (StoppedProjectedUsefulEvent.upperEvent clauses rows repeats hupper hij designated + hbranch hrows flag σ)).symm + +end +end PerfectCompleteness.StoppedProjectedUsefulProbability + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/StoppedSharedLaw.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/StoppedSharedLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..2b18a35167b07229d37412c2d2b20f0d173a3808 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/StoppedSharedLaw.lean @@ -0,0 +1,120 @@ +import OAI.Computability.PerfectCompleteness.Foundations.DependentPredictionDifferenceLemmas +import OAI.Computability.PerfectCompleteness.Sampling.StoppedSharedSampler + +namespace OAI + +section + +namespace PerfectCompleteness.StoppedSharedLaw + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open PreliminarySampler StoppedSharedSampler +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +noncomputable section + +private theorem expectation_mixture {E X : Type*} [Fintype E] [Fintype X] + (μ : FiniteDistribution E) (ν : E → FiniteDistribution X) (f : X → ℝ) : + (μ.mixture ν).expectation f = + μ.expectation (fun e => (ν e).expectation f) := by + simp only [FiniteDistribution.expectation, FiniteDistribution.mixture, + Finset.sum_mul, Finset.mul_sum, mul_assoc] + rw [Finset.sum_comm] + +variable {v m n t cut : Nat} {branch : Nat → Nat} + +private theorem conditional_expectation + (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hcut : cut + 1 ≤ n) + (hrows : ∀ k, 0 < rows (k + 1)) + (q : Questions branch n t m) (leaf : Slots branch n) + (f : Record clauses branch n t cut rows → ℝ) : + (CandidateCoupling.conditionalSharedLaw clauses rows repeats hrows (q, leaf)).expectation + (fun sample => f (forgetSuffix clauses hcut ⟨(q, leaf), sample⟩)) = + (CanonicalDirections.law rows n hrows).expectation (fun directions => + (WholeArraySampler.law rows repeats (GeometricPath.leafPath leaf) + (sourceSlots clauses (endpoints q))).expectation (fun arrays => + f ⟨(q, ((GeometricCutSplit.splitEquiv hcut leaf).1, directions)), arrays⟩)) := by + rw [CandidateCoupling.conditionalSharedLaw, FiniteDistribution.expectation_product] + calc + _ = (WholeArraySampler.law rows repeats (GeometricPath.leafPath leaf) + (sourceSlots clauses (endpoints q))).expectation (fun arrays => + (CanonicalDirections.law rows n hrows).expectation (fun directions => + f ⟨(q, ((GeometricCutSplit.splitEquiv hcut leaf).1, directions)), arrays⟩)) := by + apply FiniteDistribution.expectation_congr + intro arrays + change (CandidateCoupling.directionsLaw leaf hrows).expectation + (fun directions => f ⟨(q, ((GeometricCutSplit.splitEquiv hcut leaf).1, + (CanonicalDirections.tupleEquiv rows leaf).symm directions)), arrays⟩) = _ + rw [← FiniteDistribution.expectation_pushforward + (CandidateCoupling.directionsLaw leaf hrows) + (CanonicalDirections.tupleEquiv rows leaf).symm + (fun directions => + f ⟨(q, ((GeometricCutSplit.splitEquiv hcut leaf).1, directions)), arrays⟩), + CanonicalDirections.directionsLaw_toCanonical] + _ = _ := FiniteDistribution.expectation_comm _ _ _ + +theorem originalLaw_expectation_eq_averagedLaw [NeZero m] + (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hcut : cut + 1 ≤ n) + (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) + (f : Record clauses branch n t cut rows → ℝ) : + (originalLaw clauses rows repeats hcut hbranch hrows).expectation f = + (averagedLaw clauses rows repeats hcut hbranch hrows).expectation f := by + rw [originalLaw, FiniteDistribution.expectation_pushforward, + CandidateCoupling.sharedLaw, CandidateCoupling.expectation_sigmaLaw, + averagedLaw, CandidateCoupling.expectation_sigmaLaw] + simp only [baseLaw, contextLaw, FiniteDistribution.expectation_product, + CutContinuationAveraging.originalArrayLaw, expectation_mixture] + apply FiniteDistribution.expectation_congr + intro q + let value (pref : GeometricCutSplit.Prefix branch n (cut + 1)) + (suffix : Slots branch (cut + 1)) (directions : CanonicalDirections.Tuple rows n) : ℝ := + (WholeArraySampler.law rows repeats + ((GeometricCutSplit.prefixPath hcut pref).append (GeometricPath.leafPath suffix)) + (sourceSlots clauses (endpoints q))).expectation (fun arrays => + f ⟨(q, (pref, directions)), arrays⟩) + calc + _ = (GeometricPath.law n hbranch).expectation (fun leaf => + (CanonicalDirections.law rows n hrows).expectation (fun directions => + value (GeometricCutSplit.splitEquiv hcut leaf).1 + (GeometricCutSplit.splitEquiv hcut leaf).2 directions)) := by + apply FiniteDistribution.expectation_congr + intro leaf + rw [conditional_expectation clauses rows repeats hcut hrows q leaf f] + apply FiniteDistribution.expectation_congr + intro directions + dsimp only [value] + rw [GeometricCutSplit.leafPath_split] + _ = (GeometricCutSplit.prefixLaw hcut hbranch).expectation (fun pref => + (GeometricPath.law (cut + 1) + (fun k hk => hbranch k (Nat.lt_of_lt_of_le hk hcut))).expectation (fun suffix => + (CanonicalDirections.law rows n hrows).expectation (value pref suffix))) := + GeometricCutSplit.expectation_split hcut hbranch + (fun pref suffix => (CanonicalDirections.law rows n hrows).expectation + (value pref suffix)) + _ = _ := by + apply FiniteDistribution.expectation_congr + intro pref + exact FiniteDistribution.expectation_comm _ _ (value pref) + +theorem originalLaw_eq_averagedLaw [NeZero m] + (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hcut : cut + 1 ≤ n) + (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) : + originalLaw (t := t) clauses rows repeats hcut hbranch hrows = + averagedLaw clauses rows repeats hcut hbranch hrows := by + apply SigmaObservation.eq_of_probability_eq + intro event + rw [CandidateCoupling.probability_eq_expectation, + CandidateCoupling.probability_eq_expectation] + exact originalLaw_expectation_eq_averagedLaw clauses rows repeats hcut hbranch hrows + (fun record => if event record then 1 else 0) + +end +end PerfectCompleteness.StoppedSharedLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/StoppedSharedSampler.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/StoppedSharedSampler.lean new file mode 100644 index 0000000000000000000000000000000000000000..f50c03c38f69145948103a061bbab9c4a3691267 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/StoppedSharedSampler.lean @@ -0,0 +1,71 @@ +import OAI.Computability.PerfectCompleteness.Foundations.CanonicalDirections +import OAI.Computability.PerfectCompleteness.Foundations.CutContinuationAveraging +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalFrozenTablesLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.StoppedSharedSampler + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open PreliminarySampler +open UniqueGamesTheorem.Foundations.Games + +noncomputable section + +variable {v m n t cut : Nat} {branch rows repeats : Nat → Nat} + +abbrev Context (branch : Nat → Nat) (n t m cut : Nat) (rows : Nat → Nat) := + Questions branch n t m × + (GeometricCutSplit.Prefix branch n (cut + 1) × CanonicalDirections.Tuple rows n) + +abbrev Record (clauses : Fin m → SourceClause.NormalizedClause v) + (branch : Nat → Nat) (n t cut : Nat) (rows : Nat → Nat) := + (context : Context branch n t m cut rows) × + Arrays (sourceSlots clauses (endpoints context.1)) rows + +def contextLaw [NeZero m] (hcut : cut + 1 ≤ n) + (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) : + FiniteDistribution (Context branch n t m cut rows) := + questionsLaw.product ((GeometricCutSplit.prefixLaw hcut hbranch).product + (CanonicalDirections.law rows n hrows)) + +def forgetSuffix (clauses : Fin m → SourceClause.NormalizedClause v) + (hcut : cut + 1 ≤ n) + (sample : CandidateCoupling.Shared clauses branch n t rows) : + Record clauses branch n t cut rows := + ⟨(sample.1.1, ((GeometricCutSplit.splitEquiv hcut sample.1.2).1, + (CanonicalDirections.tupleEquiv rows sample.1.2).symm sample.2.2)), sample.2.1⟩ + +def originalLaw [NeZero m] (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hcut : cut + 1 ≤ n) + (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) : + FiniteDistribution (Record clauses branch n t cut rows) := + (CandidateCoupling.sharedLaw clauses rows repeats hbranch hrows).pushforward + (forgetSuffix clauses hcut) + +def stoppedLaw [NeZero m] (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hcut : cut + 1 ≤ n) + (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) : + FiniteDistribution (Record clauses branch n t cut rows) := + CompletionSoundness.sigmaLaw (contextLaw hcut hbranch hrows) (fun context => + WholeArraySampler.law rows repeats (GeometricCutSplit.prefixPath hcut context.2.1) + (sourceSlots clauses (endpoints context.1))) + +def averagedLaw [NeZero m] (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hcut : cut + 1 ≤ n) + (hbranch : ∀ k < n, 0 < branch k) (hrows : ∀ k, 0 < rows (k + 1)) : + FiniteDistribution (Record clauses branch n t cut rows) := + CompletionSoundness.sigmaLaw (contextLaw hcut hbranch hrows) (fun context => + CutContinuationAveraging.originalArrayLaw rows repeats + (GeometricCutSplit.prefixPath hcut context.2.1) + (sourceSlots clauses (endpoints context.1)) + (fun k hk => hbranch k (Nat.lt_of_lt_of_le hk hcut))) + +end +end PerfectCompleteness.StoppedSharedSampler + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/StoppedSourcePairLaw.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/StoppedSourcePairLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..6779cb4194f0f3e81338ec3c3b42adfcffa8f454 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/StoppedSourcePairLaw.lean @@ -0,0 +1,183 @@ +import OAI.Computability.PerfectCompleteness.Decoding.ProjectedUpperPair +import OAI.Computability.PerfectCompleteness.Decoding.UpperCutTriangle +import OAI.Computability.PerfectCompleteness.Foundations.SourceProjectedWholeChoices +import OAI.Computability.PerfectCompleteness.Foundations.StoppedProjectedCoarseLemmas +import OAI.Computability.UniqueGames.Games.CompletedSamplingLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.StoppedSourcePairLaw + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCutTape WholeArrayInteriorExterior +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) +open scoped Classical + +noncomputable section + +attribute [local instance] linearMapFintype + +variable {branch : Nat → Nat} {n i j t v m : Nat} + +local instance backgroundFintype (rows : Nat → Nat) (p : Path branch n (j + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Fintype (HierarchicalAgreementMean.Background (rows := rows) slots (upperNode p)) := + Fintype.ofFinite _ + +local instance rowSpaceFintype (p : Path branch n (j + 1)) + (slots : Slots branch n → Fin t → MixedSupport.Slot) : + Fintype (NodeEmbedding.RowSpace slots (upperNode p)) := Fintype.ofFinite _ + +private theorem pair_law_congr (rows repeats : Nat → Nat) (p : Path branch n (j + 1)) + (r : Path branch (j + 1) (i + 1)) (hproper : i + 1 < j + 1) + (native right right' : Slots branch n → Fin t → MixedSupport.Slot) + (projection : ∀ s a, MixedSupport.Projection (native s a) (right s a)) + (projection' : ∀ s a, MixedSupport.Projection (native s a) (right' s a)) + (hright : right = right') (hprojection : HEq projection projection') + (directions : FiniteDistribution (BucketSampler.Direction (rows (j + 1)))) : + (directions.product ((WholeArraySampler.tapeLaw rows repeats (p.append r) right).product + (RecursiveSampler.law F2 repeats r (LeafDomain (cutSlots p right))))).pushforward + (UpperScalarCutProjection.stoppedProjectedPair rows repeats p r hproper native right projection) = + (directions.product ((WholeArraySampler.tapeLaw rows repeats (p.append r) right').product + (RecursiveSampler.law F2 repeats r (LeafDomain (cutSlots p right'))))).pushforward + (UpperScalarCutProjection.stoppedProjectedPair rows repeats p r hproper native right' projection') := by + subst right' + have hprojection' : projection = projection' := eq_of_heq hprojection + subst projection' + rfl + +private theorem mixture_product {A B X : Type*} [Fintype A] [Fintype B] [Fintype X] + (μ : FiniteDistribution A) (ν : FiniteDistribution B) + (P : A × B → FiniteDistribution X) : + (μ.product ν).mixture P = μ.mixture (fun a => ν.mixture (fun b => P (a, b))) := by + apply SigmaObservation.eq_of_probability_eq + intro event + simp only [FiniteDistribution.probability_mixture] + exact FiniteDistribution.expectation_product μ ν + (fun z : A × B => (P z).probability event) + +variable (clauses : Fin m → SourceClause.NormalizedClause v) + (rows repeats : Nat → Nat) (hupper : j + 1 ≤ n) (hij : i < j) + (designated : Fin (branch i) → Slots branch i) + (hrows : ∀ k, 0 < rows (k + 1)) + (o : StoppedProjectedExperiment.Outer + (branch := branch) (n := n) (j := j) (t := t) (m := m)) + +local instance nativeBackgroundFintype : + Fintype (HierarchicalAgreementMean.Background (rows := rows) + (StoppedProjectedExperiment.nativeSlots clauses o) + (StoppedProjectedExperiment.upper hupper o)) := + Fintype.ofFinite _ + +local instance nativeRowSpaceFintype : + Fintype (NodeEmbedding.RowSpace (StoppedProjectedExperiment.nativeSlots clauses o) + (StoppedProjectedExperiment.upper hupper o)) := + Fintype.ofFinite _ + +theorem fixed_choice_pair + (lowerPref : GeometricCutSplit.Prefix branch (j + 1) (i + 1)) + (choices : SourceProjectedChoices.Choices (branch := branch) (n := i) (t := t)) : + ((OriginalCutPairLaw.directionsLaw rows j (hrows j)).product + ((WholeArraySampler.tapeLaw rows repeats + ((StoppedProjectedExperiment.upperPath hupper o).append + (GeometricCutSplit.prefixPath (Nat.succ_le_succ hij.le) lowerPref)) + (ProjectedWholeCut.fullSlots + ((StoppedProjectedExperiment.upperPath hupper o).append + (GeometricCutSplit.prefixPath (Nat.succ_le_succ hij.le) lowerPref)) + (StoppedProjectedExperiment.nativeSlots clauses o) + (SourceProjectedWholeChoices.projected clauses hupper hij o lowerPref) choices)).product + (RecursiveSampler.law F2 repeats + (GeometricCutSplit.prefixPath (Nat.succ_le_succ hij.le) lowerPref) + (LeafDomain (cutSlots (StoppedProjectedExperiment.upperPath hupper o) + (ProjectedWholeCut.fullSlots + ((StoppedProjectedExperiment.upperPath hupper o).append + (GeometricCutSplit.prefixPath (Nat.succ_le_succ hij.le) lowerPref)) + (StoppedProjectedExperiment.nativeSlots clauses o) + (SourceProjectedWholeChoices.projected clauses hupper hij o lowerPref) choices)))))).pushforward + (UpperScalarCutProjection.stoppedProjectedPair rows repeats + (StoppedProjectedExperiment.upperPath hupper o) + (GeometricCutSplit.prefixPath (Nat.succ_le_succ hij.le) lowerPref) + (Nat.succ_lt_succ hij) (StoppedProjectedExperiment.nativeSlots clauses o) + (ProjectedWholeCut.fullSlots + ((StoppedProjectedExperiment.upperPath hupper o).append + (GeometricCutSplit.prefixPath (Nat.succ_le_succ hij.le) lowerPref)) + (StoppedProjectedExperiment.nativeSlots clauses o) + (SourceProjectedWholeChoices.projected clauses hupper hij o lowerPref) choices) + (ProjectedWholeCut.fullProjection + ((StoppedProjectedExperiment.upperPath hupper o).append + (GeometricCutSplit.prefixPath (Nat.succ_le_succ hij.le) lowerPref)) + (StoppedProjectedExperiment.nativeSlots clauses o) + (SourceProjectedWholeChoices.projected clauses hupper hij o lowerPref) + (SourceProjectedWholeChoices.projection clauses hupper hij o lowerPref) choices)) = + StoppedProjectedPairMean.fixedPair clauses rows repeats hupper hij designated hrows o + (lowerPref, SourceProjectedChoices.tagEquiv choices) := by + exact pair_law_congr rows repeats (StoppedProjectedExperiment.upperPath hupper o) + (GeometricCutSplit.prefixPath (Nat.succ_le_succ hij.le) lowerPref) (Nat.succ_lt_succ hij) + (StoppedProjectedExperiment.nativeSlots clauses o) _ _ _ _ + (SourceProjectedWholeChoices.fullSlots_eq clauses rows hupper hij designated hrows o lowerPref choices) + (SourceProjectedWholeChoices.fullProjection_heq clauses rows hupper hij designated hrows o lowerPref choices) + (OriginalCutPairLaw.directionsLaw rows j (hrows j)) + +theorem prefix_pair_law + (lowerPref : GeometricCutSplit.Prefix branch (j + 1) (i + 1)) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) : + UpperScalarPairComparison.pairLaw rows repeats (StoppedProjectedExperiment.upperPath hupper o) + (GeometricCutSplit.prefixPath (Nat.succ_le_succ hij.le) lowerPref) + (StoppedProjectedExperiment.nativeSlots clauses o) + (OriginalCutPairLaw.directionsLaw rows j (hrows j)) + (ProjectedPrefixComparison.assembledLaw + (UpperScalarCutCalls.count rows repeats n (j + 1) (i + 1)) rows + (cutSlots ((StoppedProjectedExperiment.upperPath hupper o).append + (GeometricCutSplit.prefixPath (Nat.succ_le_succ hij.le) lowerPref)) + (StoppedProjectedExperiment.nativeSlots clauses o)) + (SourceProjectedWholeChoices.projected clauses hupper hij o lowerPref) + (SourceProjectedWholeChoices.projection clauses hupper hij o lowerPref) + (SourceProjectedChoices.choiceLaw (t := t)) β hβ hβ') = + (SourceProjectedTag.law (t := t) + (fun _ : Fin (branch i) => ProjectionPosterior.bernoulli β hβ hβ')).mixture + (fun tag => StoppedProjectedPairMean.fixedPair clauses rows repeats hupper hij + designated hrows o (lowerPref, tag)) := by + rw [ProjectedUpperPair.reconstruct_assembled_law _ _ _ _ _ rows repeats + (Nat.succ_lt_succ hij)] + unfold ProjectedUpperPair.pairLaw + rw [← SourceProjectedChoices.tagLaw_choices β hβ hβ', + UniqueGamesTheorem.Foundations.Repetition.CompletedSampling.mixture_pushforward_base] + apply congrArg ((SourceProjectedTag.law (t := t) + (fun _ : Fin (branch i) => ProjectionPosterior.bernoulli β hβ hβ')).mixture) + funext tag + simpa only [Equiv.apply_symm_apply] using + fixed_choice_pair clauses rows repeats hupper hij designated hrows o lowerPref + (SourceProjectedChoices.tagEquiv.symm tag) + +theorem pairedLaw_eq_modified (hbranch : ∀ k < j + 1, 0 < branch k) + (β : ℝ) (hβ : 0 ≤ β) (hβ' : β ≤ 1) + (σ : KeyStrategy.Strategy (TreeCanonical.locationCount branch n t)) : + HierarchicalAdviceFromBuckets.pairedLaw + (StoppedProjectedBuckets.experiment clauses rows repeats hupper hij designated hrows o hbranch + (fun _ => ProjectionPosterior.bernoulli β hβ hβ') σ) + (StoppedProjectedBuckets.externalLaw clauses rows repeats hupper hij designated hrows o hbranch + (fun _ => ProjectionPosterior.bernoulli β hβ hβ')) + (StoppedProjectedBuckets.background clauses rows repeats hupper hij designated hrows o) + (StoppedProjectedBuckets.scalarLaw clauses rows repeats hupper hij designated hrows o) + (StoppedProjectedBuckets.rows_positive rows hupper hrows o) = + UpperCutTriangle.modifiedPairLaw rows repeats (StoppedProjectedExperiment.upperPath hupper o) + (Nat.succ_le_succ hij.le) (StoppedProjectedExperiment.nativeSlots clauses o) + hbranch (hrows j) (SourceProjectedWholeChoices.projected clauses hupper hij o) + (SourceProjectedWholeChoices.projection clauses hupper hij o) + (fun _ => SourceProjectedChoices.choiceLaw (t := t)) β hβ hβ' := by + rw [StoppedProjectedPairMean.pairedLaw_eq_mixture] + unfold StoppedProjectedBucketIndex.baseLaw UpperCutTriangle.modifiedPairLaw + rw [mixture_product] + apply congrArg ((GeometricCutSplit.prefixLaw (Nat.succ_le_succ hij.le) hbranch).mixture) + funext lowerPref + exact (prefix_pair_law clauses rows repeats hupper hij designated hrows o lowerPref β hβ hβ').symm + +end +end PerfectCompleteness.StoppedSourcePairLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/StoppedUsefulPairLaw.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/StoppedUsefulPairLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..5e1fcab7f18bddfdb8297f4d81711a313993b5e1 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/StoppedUsefulPairLaw.lean @@ -0,0 +1,452 @@ +import OAI.Computability.PerfectCompleteness.Construction.CutBucketTransportLemmas +import OAI.Computability.PerfectCompleteness.Construction.StoppedBucketRows +import OAI.Computability.PerfectCompleteness.Decoding.UpperScalarCutProjection +import OAI.Computability.PerfectCompleteness.Foundations.DependentPredictionDifferenceLemmas +import OAI.Computability.PerfectCompleteness.Sampling.BucketDescriptorLaw +import OAI.Computability.PerfectCompleteness.Sampling.WholeArrayBucketsLaw + +namespace OAI + +section + +namespace PerfectCompleteness.StoppedUsefulPairLaw + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open OriginalWholeCutTape WholeArrayInteriorExterior +open UniqueGamesTheorem.Foundations.Games +open UniqueGamesTheorem.Appendix.RankLevelFilter (linearMapFintype) +open scoped Classical + +noncomputable section + +attribute [local instance] linearMapFintype + +variable {branch : Nat → Nat} {N j i t : Nat} + +abbrev Descriptor (rows repeats : Nat → Nat) (p : Path branch N (j + 1)) + (chosen : Fin (branch j)) (q : Path branch j i) + (right : Slots branch N → Fin t → MixedSupport.Slot) := + WholeArrayInteriorHiddenLaw.Exterior rows repeats p chosen q right + +def externalLaw (rows repeats : Nat → Nat) (p : Path branch N (j + 1)) + (chosen : Fin (branch j)) (q : Path branch j i) + (right : Slots branch N → Fin t → MixedSupport.Slot) : + FiniteDistribution (Descriptor rows repeats p chosen q right) := + WholeArrayInteriorHiddenLaw.exteriorLaw rows repeats p chosen q right + +local instance rowSpaceFintype (p : Path branch N (j + 1)) + (native : Slots branch N → Fin t → MixedSupport.Slot) : + Fintype (NodeEmbedding.RowSpace native (upperNode p)) := Fintype.ofFinite _ + +local instance backgroundFintype (rows : Nat → Nat) (p : Path branch N (j + 1)) + (native : Slots branch N → Fin t → MixedSupport.Slot) : + Fintype (HierarchicalMatrixTable.Background (rows := rows) native (upperNode p)) := + Fintype.ofFinite _ + +def background (rows repeats : Nat → Nat) (p : Path branch N (j + 1)) + (chosen : Fin (branch j)) (q : Path branch j i) + (native right : Slots branch N → Fin t → MixedSupport.Slot) + (projection : ∀ s a, MixedSupport.Projection (native s a) (right s a)) + (external : Descriptor rows repeats p chosen q right) : + HierarchicalMatrixTable.Background (rows := rows) native (upperNode p) := + fun node row => HPullback (ChildBlockProjection.nodeProjection projection node.val) + (WholeArrayInteriorExterior.nodeArray rows repeats p chosen q right external node row) + +def scalarValue (repeats : Nat → Nat) (p : Path branch N (j + 1)) + (chosen : Fin (branch j)) (q : Path branch j i) + (native right : Slots branch N → Fin t → MixedSupport.Slot) + (projection : ∀ s a, MixedSupport.Projection (native s a) (right s a)) + (tape : WholeArrayInteriorHiddenLaw.ScalarTape repeats p chosen q right) : + H (cutSlots p native) := + HPullback (CutGroupedProjection.cutProjection p projection) + (RecursiveSampler.evaluate F2 repeats (.step chosen q) (LeafDomain (cutSlots p right)) tape) + +def nativeScalarLaw (repeats : Nat → Nat) (p : Path branch N (j + 1)) + (chosen : Fin (branch j)) (q : Path branch j i) + (native right : Slots branch N → Fin t → MixedSupport.Slot) + (projection : ∀ s a, MixedSupport.Projection (native s a) (right s a)) : + FiniteDistribution (H (cutSlots p native)) := + (RecursiveSampler.law F2 repeats (.step chosen q) (LeafDomain (cutSlots p right))).pushforward + (HPullback (CutGroupedProjection.cutProjection p projection)) + +def scalarLaw (rows repeats : Nat → Nat) (p : Path branch N (j + 1)) + (chosen : Fin (branch j)) (q : Path branch j i) + (native right : Slots branch N → Fin t → MixedSupport.Slot) + (projection : ∀ s a, MixedSupport.Projection (native s a) (right s a)) + (_external : Descriptor rows repeats p chosen q right) : + FiniteDistribution (NodeEmbedding.RowSpace native (upperNode p)) := + (nativeScalarLaw repeats p chosen q native right projection).pushforward + (CutNodeRows.cutRowEquiv p native) + +def readout (rows repeats : Nat → Nat) (p : Path branch N (j + 1)) + (chosen : Fin (branch j)) (q : Path branch j i) + (native right : Slots branch N → Fin t → MixedSupport.Slot) + (projection : ∀ s a, MixedSupport.Projection (native s a) (right s a)) := + WholeArrayBucketsLaw.readout rows repeats p chosen q right + (scalarValue repeats p chosen q native right projection) + (id : Descriptor rows repeats p chosen q right → _) + +theorem scalarValue_law (repeats : Nat → Nat) (p : Path branch N (j + 1)) + (chosen : Fin (branch j)) (q : Path branch j i) + (native right : Slots branch N → Fin t → MixedSupport.Slot) + (projection : ∀ s a, MixedSupport.Projection (native s a) (right s a)) : + (WholeArrayInteriorHiddenLaw.scalarLaw repeats p chosen q right).pushforward + (scalarValue repeats p chosen q native right projection) = + nativeScalarLaw repeats p chosen q native right projection := by + exact (FiniteDistribution.pushforward_comp + (RecursiveSampler.tapeLaw F2 repeats (.step chosen q) (LeafDomain (cutSlots p right))) + (RecursiveSampler.evaluate F2 repeats (.step chosen q) (LeafDomain (cutSlots p right))) + (HPullback (CutGroupedProjection.cutProjection p projection))).symm + +theorem readout_law (rows repeats : Nat → Nat) (p : Path branch N (j + 1)) + (chosen : Fin (branch j)) (q : Path branch j i) + (native right : Slots branch N → Fin t → MixedSupport.Slot) + (projection : ∀ s a, MixedSupport.Projection (native s a) (right s a)) : + (WholeArraySampler.tapeLaw rows repeats (p.append (.step chosen q)) right).pushforward + (readout rows repeats p chosen q native right projection) = + (externalLaw rows repeats p chosen q right).product + (BucketSampler.tapeLaw (rows (j + 1)) + (nativeScalarLaw repeats p chosen q native right projection)) := by + rw [readout, WholeArrayBucketsLaw.readout_law, + FiniteDistribution.pushforward_id, scalarValue_law] + rfl + +theorem background_readout (rows repeats : Nat → Nat) (p : Path branch N (j + 1)) + (chosen : Fin (branch j)) (q : Path branch j i) + (native right : Slots branch N → Fin t → MixedSupport.Slot) + (projection : ∀ s a, MixedSupport.Projection (native s a) (right s a)) + (tape : WholeArraySampler.Tape rows repeats (p.append (.step chosen q)) right) : + background rows repeats p chosen q native right projection + (readout rows repeats p chosen q native right projection tape).1 = + HierarchicalMatrixTable.backgroundOf native (upperNode p) + (ChildBlockProjection.arraysPullback rows projection + (WholeArraySampler.evaluate rows repeats (p.append (.step chosen q)) right tape)) := by + funext node row + change HPullback (ChildBlockProjection.nodeProjection projection node.val) + (WholeArrayInteriorExterior.nodeArray rows repeats p chosen q right + (WholeArrayInteriorExterior.read rows repeats p chosen q right tape) node row) = _ + rw [WholeArrayInteriorExterior.nodeArray_read] + rfl + +theorem matrix_readout (rows repeats : Nat → Nat) (p : Path branch N (j + 1)) + (chosen : Fin (branch j)) (q : Path branch j i) + (native right : Slots branch N → Fin t → MixedSupport.Slot) + (projection : ∀ s a, MixedSupport.Projection (native s a) (right s a)) + (tape : WholeArraySampler.Tape rows repeats (p.append (.step chosen q)) right) : + NodeEmbedding.matrix (ChildBlockProjection.arraysPullback rows projection + (WholeArraySampler.evaluate rows repeats (p.append (.step chosen q)) right tape)) + (upperNode p) = + BucketMatrixResampling.assembledMatrix (NodeEmbedding.RowSpace native (upperNode p)) + (rows (Nodes.height (upperNode p))) + (CutNodeRows.bucketTapeEquiv rows p native + (readout rows repeats p chosen q native right projection tape).2) := by + rw [← CutNodeRows.matrixOfRows_selectedRows rows p native] + have hrows := StoppedBucketRows.selectedRows_pullback_evaluate rows repeats p chosen q + native right projection tape + change SelectedArrayReplacement.selectedRows rows p native + (ChildBlockProjection.arraysPullback rows projection + (WholeArraySampler.evaluate rows repeats (p.append (.step chosen q)) right tape)) = + BucketSampler.evaluate (rows (j + 1)) id + (readout rows repeats p chosen q native right projection tape).2 at hrows + rw [hrows] + exact CutNodeRows.matrixOfRows_evaluate rows p native _ + +theorem assembled_arrays (rows repeats : Nat → Nat) (p : Path branch N (j + 1)) + (chosen : Fin (branch j)) (q : Path branch j i) + (native right : Slots branch N → Fin t → MixedSupport.Slot) + (projection : ∀ s a, MixedSupport.Projection (native s a) (right s a)) + (tape : WholeArraySampler.Tape rows repeats (p.append (.step chosen q)) right) : + HierarchicalMatrixTable.assemble native (upperNode p) + (background rows repeats p chosen q native right projection + (readout rows repeats p chosen q native right projection tape).1) + (BucketMatrixResampling.assembledMatrix (NodeEmbedding.RowSpace native (upperNode p)) + (rows (Nodes.height (upperNode p))) + (CutNodeRows.bucketTapeEquiv rows p native + (readout rows repeats p chosen q native right projection tape).2)) = + ChildBlockProjection.arraysPullback rows projection + (WholeArraySampler.evaluate rows repeats (p.append (.step chosen q)) right tape) := by + rw [background_readout, ← matrix_readout] + exact HierarchicalMatrixTable.assemble_original native (upperNode p) _ + +abbrev Sample (rows repeats : Nat → Nat) (p : Path branch N (j + 1)) + (chosen : Fin (branch j)) (q : Path branch j i) + (right : Slots branch N → Fin t → MixedSupport.Slot) := + BucketSampler.Direction (rows (j + 1)) × + (WholeArraySampler.Tape rows repeats (p.append (.step chosen q)) right × H (cutSlots p right)) + +def directionLaw (rows : Nat → Nat) (j : Nat) (hrows : 0 < rows (j + 1)) : + FiniteDistribution (BucketSampler.Direction (rows (j + 1))) := by + letI : Nonempty (BucketSampler.Direction (rows (j + 1))) := + ⟨BucketUniform.coordinateDirection ⟨0, hrows⟩⟩ + exact FiniteDistribution.uniform _ + +def actualLaw (rows repeats : Nat → Nat) (p : Path branch N (j + 1)) + (chosen : Fin (branch j)) (q : Path branch j i) + (right : Slots branch N → Fin t → MixedSupport.Slot) (hrows : 0 < rows (j + 1)) : + FiniteDistribution (Sample rows repeats p chosen q right) := + (directionLaw rows j hrows).product + ((WholeArraySampler.tapeLaw rows repeats (p.append (.step chosen q)) right).product + (RecursiveSampler.law F2 repeats (.step chosen q) (LeafDomain (cutSlots p right)))) + +def observe (rows repeats : Nat → Nat) (p : Path branch N (j + 1)) + (chosen : Fin (branch j)) (q : Path branch j i) + (native right : Slots branch N → Fin t → MixedSupport.Slot) + (projection : ∀ s a, MixedSupport.Projection (native s a) (right s a)) + (sample : Sample rows repeats p chosen q right) : + HierarchicalUsefulCollision.Sample (P := Descriptor rows repeats p chosen q right) + (rows := rows) native (upperNode p) := + let old := readout rows repeats p chosen q native right projection sample.2.1 + ⟨old.1, CutNodeRows.bucketSampleEquiv rows p native + (sample.1, (old.2, HPullback (CutGroupedProjection.cutProjection p projection) sample.2.2))⟩ + +private def liftFresh (rows repeats : Nat → Nat) (p : Path branch N (j + 1)) + (chosen : Fin (branch j)) (q : Path branch j i) + (native right : Slots branch N → Fin t → MixedSupport.Slot) + (projection : ∀ s a, MixedSupport.Projection (native s a) (right s a)) + (sample : Sample rows repeats p chosen q right) : + BucketSampler.Direction (rows (j + 1)) × + (WholeArraySampler.Tape rows repeats (p.append (.step chosen q)) right × H (cutSlots p native)) := + (sample.1, (sample.2.1, HPullback (CutGroupedProjection.cutProjection p projection) sample.2.2)) + +private theorem liftFresh_law (rows repeats : Nat → Nat) (p : Path branch N (j + 1)) + (chosen : Fin (branch j)) (q : Path branch j i) + (native right : Slots branch N → Fin t → MixedSupport.Slot) + (projection : ∀ s a, MixedSupport.Projection (native s a) (right s a)) + (hrows : 0 < rows (j + 1)) : + (actualLaw rows repeats p chosen q right hrows).pushforward + (liftFresh rows repeats p chosen q native right projection) = + (directionLaw rows j hrows).product + ((WholeArraySampler.tapeLaw rows repeats (p.append (.step chosen q)) right).product + (nativeScalarLaw repeats p chosen q native right projection)) := by + let μ := WholeArraySampler.tapeLaw rows repeats (p.append (.step chosen q)) right + let ρ := RecursiveSampler.law F2 repeats (.step chosen q) (LeafDomain (cutSlots p right)) + let f := HPullback (CutGroupedProjection.cutProjection p projection) + change ((directionLaw rows j hrows).product (μ.product ρ)).pushforward + (fun z => (id z.1, (id z.2.1, f z.2.2))) = _ + rw [FiniteDistribution.product_pushforward (directionLaw rows j hrows) (μ.product ρ) + id (fun z => (id z.1, f z.2)), FiniteDistribution.pushforward_id, + FiniteDistribution.product_pushforward μ ρ id f, FiniteDistribution.pushforward_id] + rfl + +private theorem descriptor_chain_law + {S D E T B V U : Type*} + [Fintype S] [Fintype D] [Fintype E] [Fintype T] + [Fintype B] [Fintype V] [Fintype U] + (μ : FiniteDistribution S) (δ : FiniteDistribution D) + (τ : FiniteDistribution T) (ν : FiniteDistribution E) + (β : FiniteDistribution B) (ρ : FiniteDistribution V) + (κ : FiniteDistribution U) + (lift : S → D × (T × V)) + (read : T → E × B) + (transport : D × (B × V) → U) + (hLift : μ.pushforward lift = δ.product (τ.product ρ)) + (hRead : τ.pushforward read = ν.product β) + (hTransport : (δ.product (β.product ρ)).pushforward transport = κ) : + μ.pushforward (fun s => + (⟨(read (lift s).2.1).1, + transport ((lift s).1, ((read (lift s).2.1).2, (lift s).2.2))⟩ : Σ _ : E, U)) = + CompletionSoundness.sigmaLaw ν (fun _ => κ) := by + let f : D × (T × V) → D × ((E × B) × V) := + fun z => (z.1, (read z.2.1, z.2.2)) + let r : D × ((E × B) × V) → (Σ _ : E, D × (B × V)) := + fun z => ⟨z.2.1.1, (z.1, (z.2.1.2, z.2.2))⟩ + let g : (Σ _ : E, D × (B × V)) → (Σ _ : E, U) := + fun z => ⟨z.1, transport z.2⟩ + have hInner : (τ.product ρ).pushforward + (fun z : T × V => (read z.1, z.2)) = (ν.product β).product ρ := by + simpa only [id_eq, FiniteDistribution.pushforward_id, hRead] using + FiniteDistribution.product_pushforward τ ρ read (id : V → V) + have hMap : (δ.product (τ.product ρ)).pushforward f = + δ.product ((ν.product β).product ρ) := by + simpa only [f, id_eq, FiniteDistribution.pushforward_id, hInner] using + FiniteDistribution.product_pushforward δ (τ.product ρ) (id : D → D) + (fun z : T × V => (read z.1, z.2)) + have hNative : ((μ.pushforward lift).pushforward f).pushforward r = + CompletionSoundness.sigmaLaw ν (fun _ => δ.product (β.product ρ)) := by + rw [hLift, hMap] + exact BucketDescriptorLaw.reorder_law δ ν β ρ + have hSigma : + (CompletionSoundness.sigmaLaw ν (fun _ => δ.product (β.product ρ))).pushforward g = + CompletionSoundness.sigmaLaw ν (fun _ => κ) := by + calc + _ = CompletionSoundness.sigmaLaw ν + (fun _ => (δ.product (β.product ρ)).pushforward transport) := + SigmaObservation.pushforward_fiber ν + (fun _ => δ.product (β.product ρ)) (fun _ => transport) + _ = _ := congrArg + (fun laws : E → FiniteDistribution U => CompletionSoundness.sigmaLaw ν laws) + (funext (fun _ => hTransport)) + calc + _ = (((μ.pushforward lift).pushforward f).pushforward r).pushforward g := + ((FiniteDistribution.pushforward_comp ((μ.pushforward lift).pushforward f) r g).trans + ((FiniteDistribution.pushforward_comp (μ.pushforward lift) f + (fun z : D × ((E × B) × V) => g (r z))).trans + (FiniteDistribution.pushforward_comp μ lift + (fun z : D × (T × V) => g (r (f z)))))).symm + _ = (CompletionSoundness.sigmaLaw ν + (fun _ => δ.product (β.product ρ))).pushforward g := + congrArg (fun law : FiniteDistribution (Σ _ : E, D × (B × V)) => + law.pushforward g) hNative + _ = _ := hSigma + +theorem observe_law (rows repeats : Nat → Nat) (p : Path branch N (j + 1)) + (chosen : Fin (branch j)) (q : Path branch j i) + (native right : Slots branch N → Fin t → MixedSupport.Slot) + (projection : ∀ s a, MixedSupport.Projection (native s a) (right s a)) + (hrows : 0 < rows (j + 1)) : + (actualLaw rows repeats p chosen q right hrows).pushforward + (observe rows repeats p chosen q native right projection) = + HierarchicalUsefulCollision.law native (upperNode p) + (externalLaw rows repeats p chosen q right) + (scalarLaw rows repeats p chosen q native right projection) + (by simpa only [upperNode_height] using hrows) := by + have h := descriptor_chain_law + (S := Sample rows repeats p chosen q right) + (D := BucketSampler.Direction (rows (j + 1))) + (E := Descriptor rows repeats p chosen q right) + (T := WholeArraySampler.Tape rows repeats (p.append (.step chosen q)) right) + (B := BucketSampler.Tape (rows (j + 1)) (H (cutSlots p native))) + (V := H (cutSlots p native)) + (U := HierarchicalAgreementMean.BucketSample (rows := rows) native (upperNode p)) + (actualLaw rows repeats p chosen q right hrows) + (directionLaw rows j hrows) + (WholeArraySampler.tapeLaw rows repeats (p.append (.step chosen q)) right) + (externalLaw rows repeats p chosen q right) + (BucketSampler.tapeLaw (rows (j + 1)) + (nativeScalarLaw repeats p chosen q native right projection)) + (nativeScalarLaw repeats p chosen q native right projection) + (HierarchicalUsefulCollision.bucketLaw native (upperNode p) + ((nativeScalarLaw repeats p chosen q native right projection).pushforward + (CutNodeRows.cutRowEquiv p native)) + (by simpa only [upperNode_height] using hrows)) + (liftFresh rows repeats p chosen q native right projection) + (readout rows repeats p chosen q native right projection) + (CutNodeRows.bucketSampleEquiv rows p native) + (liftFresh_law rows repeats p chosen q native right projection hrows) + (readout_law rows repeats p chosen q native right projection) + (CutBucketTransportActual.nativeLaw_pushforward rows p native + (nativeScalarLaw repeats p chosen q native right projection) hrows) + have hmap : observe rows repeats p chosen q native right projection = + (fun s : Sample rows repeats p chosen q right => + (⟨(readout rows repeats p chosen q native right projection + (liftFresh rows repeats p chosen q native right projection s).2.1).1, + CutNodeRows.bucketSampleEquiv rows p native + ((liftFresh rows repeats p chosen q native right projection s).1, + ((readout rows repeats p chosen q native right projection + (liftFresh rows repeats p chosen q native right projection s).2.1).2, + (liftFresh rows repeats p chosen q native right projection s).2.2))⟩ : + HierarchicalUsefulCollision.Sample (P := Descriptor rows repeats p chosen q right) + (rows := rows) native (upperNode p))) := by + funext s + rfl + exact (congrArg (fun f : Sample rows repeats p chosen q right → + HierarchicalUsefulCollision.Sample (P := Descriptor rows repeats p chosen q right) + (rows := rows) native (upperNode p) => + (actualLaw rows repeats p chosen q right hrows).pushforward f) hmap).trans h + +theorem replacement_matrix (rows : Nat → Nat) (p : Path branch N (j + 1)) + (native right : Slots branch N → Fin t → MixedSupport.Slot) + (projection : ∀ s a, MixedSupport.Projection (native s a) (right s a)) + (arrays : Arrays right rows) + (buckets : BucketSampler.Tape (rows (j + 1)) (H (cutSlots p right))) + (a : BucketSampler.Direction (rows (j + 1))) (fresh : H (cutSlots p right)) : + NodeEmbedding.matrix (ChildBlockProjection.arraysPullback rows projection + (SelectedArrayReplacement.replace rows p right arrays + (BucketSampler.evaluate (rows (j + 1)) id (Function.update buckets a fresh)))) + (upperNode p) = + BucketMatrixResampling.assembledMatrix (NodeEmbedding.RowSpace native (upperNode p)) + (rows (Nodes.height (upperNode p))) + (Function.update (CutNodeRows.bucketTapeEquiv rows p native + (fun direction => HPullback (CutGroupedProjection.cutProjection p projection) + (buckets direction))) (CutNodeRows.directionEquiv rows p a) + (CutNodeRows.cutRowEquiv p native + (HPullback (CutGroupedProjection.cutProjection p projection) fresh))) := by + rw [← SelectedArrayProjection.replace_pullback rows p native right projection] + rw [← CutNodeRows.matrixOfRows_selectedRows rows p native, + SelectedArrayReplacement.selectedRows_replace] + rw [← UpperScalarCutProjection.map_updated_buckets + (HPullback (CutGroupedProjection.cutProjection p projection)) buckets a fresh] + rw [CutNodeRows.matrixOfRows_evaluate, CutNodeRows.bucketTapeEquiv_update] + +def actualPair (rows repeats : Nat → Nat) (p : Path branch N (j + 1)) + (chosen : Fin (branch j)) (q : Path branch j i) + (native right : Slots branch N → Fin t → MixedSupport.Slot) + (projection : ∀ s a, MixedSupport.Projection (native s a) (right s a)) + (sample : Sample rows repeats p chosen q right) : + HierarchicalAgreementMean.PairRecord (rows := rows) native (upperNode p) := + UpperScalarCutProjection.projectedPair rows p native right projection + (WholeArraySampler.evaluate rows repeats (p.append (.step chosen q)) right sample.2.1) + (fun direction => RecursiveSampler.evaluate F2 repeats (.step chosen q) + (LeafDomain (cutSlots p right)) + ((WholeArrayBucketsLaw.split rows repeats p chosen q right sample.2.1).1 direction)) + sample.1 sample.2.2 + +theorem pairRecord_observe (rows repeats : Nat → Nat) (p : Path branch N (j + 1)) + (chosen : Fin (branch j)) (q : Path branch j i) + (native right : Slots branch N → Fin t → MixedSupport.Slot) + (projection : ∀ s a, MixedSupport.Projection (native s a) (right s a)) + (sample : Sample rows repeats p chosen q right) : + HierarchicalUsefulCollision.pairRecord native (upperNode p) + (background rows repeats p chosen q native right projection) + (observe rows repeats p chosen q native right projection sample) = + actualPair rows repeats p chosen q native right projection sample := by + apply Prod.ext + · exact background_readout rows repeats p chosen q native right projection sample.2.1 + · apply Prod.ext + · exact (matrix_readout rows repeats p chosen q native right projection sample.2.1).symm + · exact (replacement_matrix rows p native right projection + (WholeArraySampler.evaluate rows repeats (p.append (.step chosen q)) right sample.2.1) + (fun direction => RecursiveSampler.evaluate F2 repeats (.step chosen q) + (LeafDomain (cutSlots p right)) + ((WholeArrayBucketsLaw.split rows repeats p chosen q right sample.2.1).1 direction)) + sample.1 sample.2.2).symm + +theorem actualPair_law (rows repeats : Nat → Nat) (p : Path branch N (j + 1)) + (chosen : Fin (branch j)) (q : Path branch j i) + (native right : Slots branch N → Fin t → MixedSupport.Slot) + (projection : ∀ s a, MixedSupport.Projection (native s a) (right s a)) + (hrows : 0 < rows (j + 1)) : + (actualLaw rows repeats p chosen q right hrows).pushforward + (actualPair rows repeats p chosen q native right projection) = + HierarchicalUsefulCollision.pairLaw native (upperNode p) + (externalLaw rows repeats p chosen q right) + (background rows repeats p chosen q native right projection) + (scalarLaw rows repeats p chosen q native right projection) + (by simpa only [upperNode_height] using hrows) := by + rw [HierarchicalUsefulCollision.pairLaw, + ← observe_law rows repeats p chosen q native right projection hrows, + FiniteDistribution.pushforward_comp] + apply congrArg (FiniteDistribution.pushforward _) + funext sample + exact (pairRecord_observe rows repeats p chosen q native right projection sample).symm + +theorem stoppedProjectedPair_eq (rows repeats : Nat → Nat) (p : Path branch N (j + 1)) + (chosen : Fin (branch j)) (q : Path branch j (i + 1)) (hproper : i + 1 < j + 1) + (native right : Slots branch N → Fin t → MixedSupport.Slot) + (projection : ∀ s a, MixedSupport.Projection (native s a) (right s a)) + (sample : Sample rows repeats p chosen q right) : + UpperScalarCutProjection.stoppedProjectedPair rows repeats p (.step chosen q) hproper + native right projection sample = + actualPair rows repeats p chosen q native right projection sample := rfl + +theorem stoppedProjectedPair_law (rows repeats : Nat → Nat) (p : Path branch N (j + 1)) + (chosen : Fin (branch j)) (q : Path branch j (i + 1)) (hproper : i + 1 < j + 1) + (native right : Slots branch N → Fin t → MixedSupport.Slot) + (projection : ∀ s a, MixedSupport.Projection (native s a) (right s a)) + (hrows : 0 < rows (j + 1)) : + (actualLaw rows repeats p chosen q right hrows).pushforward + (UpperScalarCutProjection.stoppedProjectedPair rows repeats p (.step chosen q) hproper + native right projection) = + HierarchicalUsefulCollision.pairLaw native (upperNode p) + (externalLaw rows repeats p chosen q right) + (background rows repeats p chosen q native right projection) + (scalarLaw rows repeats p chosen q native right projection) + (by simpa only [upperNode_height] using hrows) := + actualPair_law rows repeats p chosen q native right projection hrows + +end +end PerfectCompleteness.StoppedUsefulPairLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/TaggedKernelRebuildLaw.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/TaggedKernelRebuildLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..97e8364b1fa2af97df65e46cc477b6690ee60d4b --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/TaggedKernelRebuildLaw.lean @@ -0,0 +1,134 @@ +import OAI.Computability.PerfectCompleteness.Foundations.DependentPredictionDifferenceLemmas +import OAI.Computability.PerfectCompleteness.Repetition.CleanConditioning +import OAI.Computability.UniqueGames.Foundations.ValueLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.TaggedKernelRebuildLaw + +open UniqueGamesTheorem.Foundations.Games CompletionSoundness + +noncomputable section + +private theorem probability_eq_expectation {X : Type*} [Fintype X] + (μ : FiniteDistribution X) (event : X → Bool) : + μ.probability event = μ.expectation (fun x => if event x then 1 else 0) := by + simp only [FiniteDistribution.probability, FiniteDistribution.expectation, + mul_ite, mul_one, mul_zero] + +private theorem expectation_sigmaLaw {B : Type*} [Fintype B] + {V : B → Type*} [∀ b, Fintype (V b)] + (β : FiniteDistribution B) (ν : (b : B) → FiniteDistribution (V b)) + (f : (Σ b, V b) → ℝ) : + (sigmaLaw β ν).expectation f = + β.expectation (fun b => (ν b).expectation (fun v => f ⟨b, v⟩)) := by + simp only [FiniteDistribution.expectation, sigmaLaw, + Fintype.sum_sigma, Finset.mul_sum, mul_assoc] + +private theorem expectation_kernelJoint {S R : Type*} [Fintype S] [Fintype R] + (μ : FiniteDistribution S) (P : S → FiniteDistribution R) (f : S × R → ℝ) : + (CleanConditioning.kernelJoint μ P).expectation f = + μ.expectation (fun s => (P s).expectation (fun r => f (s, r))) := by + simp only [FiniteDistribution.expectation, CleanConditioning.kernelJoint, + Fintype.sum_prod_type, Finset.mul_sum, mul_assoc] + +private theorem expectation_rebuild {R E B : Type*} + [Fintype R] [Fintype E] [Fintype B] + {V Y : B → Type*} [∀ b, Fintype (V b)] [∀ b, Fintype (Y b)] + (β : FiniteDistribution B) (δ : FiniteDistribution E) (P : FiniteDistribution R) + (ν : (b : B) → FiniteDistribution (V b)) + (Q : (b : B) → FiniteDistribution (Y b)) + (decode : R → Σ b, V b) (rebuild : (b : B) → E → V b → Y b) + (hdecode : P.pushforward decode = sigmaLaw β ν) + (hbuild : ∀ b, (δ.product (ν b)).pushforward + (fun x => rebuild b x.1 x.2) = Q b) + (f : (Σ b, Y b) → ℝ) : + (δ.product P).expectation + (fun x => f ⟨(decode x.2).1, rebuild _ x.1 (decode x.2).2⟩) = + (sigmaLaw β Q).expectation f := by + calc + _ = δ.expectation (fun e => (P.pushforward decode).expectation + (fun bv => f ⟨bv.1, rebuild bv.1 e bv.2⟩)) := by + rw [FiniteDistribution.expectation_product] + apply FiniteDistribution.expectation_congr + intro e + exact (FiniteDistribution.expectation_pushforward P decode + (fun bv => f ⟨bv.1, rebuild bv.1 e bv.2⟩)).symm + _ = δ.expectation (fun e => β.expectation + (fun b => (ν b).expectation (fun v => f ⟨b, rebuild b e v⟩))) := by + simp only [hdecode, expectation_sigmaLaw] + _ = β.expectation (fun b => δ.expectation + (fun e => (ν b).expectation (fun v => f ⟨b, rebuild b e v⟩))) := + FiniteDistribution.expectation_comm δ β _ + _ = β.expectation (fun b => (Q b).expectation (fun y => f ⟨b, y⟩)) := by + apply FiniteDistribution.expectation_congr + intro b + calc + _ = (δ.product (ν b)).expectation + (fun x => f ⟨b, rebuild b x.1 x.2⟩) := + (FiniteDistribution.expectation_product δ (ν b) _).symm + _ = ((δ.product (ν b)).pushforward + (fun x => rebuild b x.1 x.2)).expectation (fun y => f ⟨b, y⟩) := + (FiniteDistribution.expectation_pushforward + (δ.product (ν b)) (fun x => rebuild b x.1 x.2) + (fun y => f ⟨b, y⟩)).symm + _ = _ := by rw [hbuild b] + _ = _ := (expectation_sigmaLaw β Q f).symm + +theorem fiber_rebuild_law {R E B : Type*} + [Fintype R] [Fintype E] [Fintype B] + {V Y : B → Type*} [∀ b, Fintype (V b)] [∀ b, Fintype (Y b)] + (β : FiniteDistribution B) (δ : FiniteDistribution E) (P : FiniteDistribution R) + (ν : (b : B) → FiniteDistribution (V b)) + (Q : (b : B) → FiniteDistribution (Y b)) + (decode : R → Σ b, V b) (rebuild : (b : B) → E → V b → Y b) + (hdecode : P.pushforward decode = sigmaLaw β ν) + (hbuild : ∀ b, (δ.product (ν b)).pushforward + (fun x => rebuild b x.1 x.2) = Q b) : + (δ.product P).pushforward + (fun x => (⟨(decode x.2).1, rebuild _ x.1 (decode x.2).2⟩ : Σ b, Y b)) = + sigmaLaw β Q := by + apply SigmaObservation.eq_of_probability_eq + intro event + simp only [probability_eq_expectation, FiniteDistribution.expectation_pushforward] + exact expectation_rebuild β δ P ν Q decode rebuild hdecode hbuild + (fun x => if event x then 1 else 0) + +theorem rebuild_law {S R E B : Type*} + [Fintype S] [Fintype R] [Fintype E] [Fintype B] + {V Y : S → B → Type*} + [∀ s b, Fintype (V s b)] [∀ s b, Fintype (Y s b)] + (μ : FiniteDistribution S) (β : FiniteDistribution B) (δ : FiniteDistribution E) + (P : S → FiniteDistribution R) + (ν : (s : S) → (b : B) → FiniteDistribution (V s b)) + (Q : (s : S) → (b : B) → FiniteDistribution (Y s b)) + (decode : (s : S) → R → Σ b, V s b) + (rebuild : (s : S) → (b : B) → E → V s b → Y s b) + (hdecode : ∀ s, (P s).pushforward (decode s) = sigmaLaw β (ν s)) + (hbuild : ∀ s b, (δ.product (ν s b)).pushforward + (fun x => rebuild s b x.1 x.2) = Q s b) : + ((CleanConditioning.kernelJoint μ P).product δ).pushforward + (fun x => (⟨(x.1.1, (decode x.1.1 x.1.2).1), + rebuild x.1.1 _ x.2 (decode x.1.1 x.1.2).2⟩ : + Σ sb : S × B, Y sb.1 sb.2)) = + sigmaLaw (μ.product β) (fun sb => Q sb.1 sb.2) := by + apply SigmaObservation.eq_of_probability_eq + intro event + simp only [probability_eq_expectation, FiniteDistribution.expectation_pushforward, + FiniteDistribution.expectation_product, expectation_kernelJoint, expectation_sigmaLaw] + apply FiniteDistribution.expectation_congr + intro s + have h := expectation_rebuild β δ (P s) (ν s) (Q s) (decode s) (rebuild s) + (hdecode s) (hbuild s) + (fun bv => if event ⟨(s, bv.1), bv.2⟩ then 1 else 0) + rw [FiniteDistribution.expectation_product, expectation_sigmaLaw] at h + exact (FiniteDistribution.expectation_comm (P s) δ _).trans h + +end +end PerfectCompleteness.TaggedKernelRebuildLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/UniformChildSum.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/UniformChildSum.lean new file mode 100644 index 0000000000000000000000000000000000000000..388f0b2bc416156c4fb862a91b353ecdebbe475a --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/UniformChildSum.lean @@ -0,0 +1,92 @@ +import Mathlib.LinearAlgebra.DFinsupp +import OAI.Computability.PerfectCompleteness.Algebra.UniformLinearImage +import OAI.Computability.PerfectCompleteness.Foundations.RecursiveSpaces + +namespace OAI + + +namespace PerfectCompleteness.UniformChildSum + +open scoped BigOperators +open PointwiseSpaces RecursiveSpaces UniformLinearImage +open UniqueGamesTheorem.Foundations.Games + +noncomputable section + +variable {𝕜 X J : Type*} [Field 𝕜] [Fintype J] + {D : J → Type*} + +def childSum (r : ∀ i, X → D i) (H : ∀ i, Submodule 𝕜 (D i → 𝕜)) : + (∀ i, squareSpace (H i)) →ₗ[𝕜] childSpace r H where + toFun f := ⟨∑ i, pullback 𝕜 (r i) (f i), + Submodule.sum_mem_iSup (fun i => Submodule.mem_map_of_mem (f i).property)⟩ + map_add' f g := by + apply Subtype.ext + simp only [Pi.add_apply, Submodule.coe_add, map_add, Finset.sum_add_distrib] + map_smul' c f := by + apply Subtype.ext + simp only [Pi.smul_apply, Submodule.coe_smul, map_smul, Finset.smul_sum, + RingHom.id_apply] + +@[simp] theorem childSum_apply (r : ∀ i, X → D i) + (H : ∀ i, Submodule 𝕜 (D i → 𝕜)) (f : ∀ i, squareSpace (H i)) : + (childSum r H f).val = ∑ i, pullback 𝕜 (r i) (f i) := rfl + +theorem childSum_surjective (r : ∀ i, X → D i) + (H : ∀ i, Submodule 𝕜 (D i → 𝕜)) : Function.Surjective (childSum r H) := by + classical + intro u + let p : J → Submodule 𝕜 (X → 𝕜) := + fun i => (squareSpace (H i)).map (pullback 𝕜 (r i)) + have hu : (u : X → 𝕜) ∈ ⨆ i ∈ (Finset.univ : Finset J), p i := by + simpa [p, childSpace] using u.property + obtain ⟨v, hv⟩ := (Submodule.mem_iSup_finset_iff_exists_sum + (s := Finset.univ) p (u : X → 𝕜)).mp hu + have hx : ∀ i, ∃ w : squareSpace (H i), + pullback 𝕜 (r i) (w : D i → 𝕜) = (v i : X → 𝕜) := by + intro i + obtain ⟨w, hw, heq⟩ := Submodule.mem_map.mp (v i).property + exact ⟨⟨w, hw⟩, heq⟩ + choose w hw using hx + refine ⟨w, ?_⟩ + apply Subtype.ext + change (∑ i, pullback 𝕜 (r i) (w i : D i → 𝕜)) = (u : X → 𝕜) + calc + _ = ∑ i, (v i : X → 𝕜) := Finset.sum_congr rfl (fun i _ => hw i) + _ = _ := hv + +theorem uniform_childSum [DecidableEq J] (r : ∀ i, X → D i) + (H : ∀ i, Submodule 𝕜 (D i → 𝕜)) + [∀ i, Fintype (squareSpace (H i))] [Fintype (childSpace r H)] : + (FiniteProduct.law (fun i => FiniteDistribution.uniform (squareSpace (H i)))).pushforward + (childSum r H) = FiniteDistribution.uniform (childSpace r H) := + product_uniform_linear_image (childSum r H) (childSum_surjective r H) + + +variable {branch : Nat → Nat} {n : Nat} + +def recursiveSum (A : Slots branch (n + 1) → Type*) : + (∀ i : Fin (branch n), squareSpace (space 𝕜 branch n (childFamily A i))) →ₗ[𝕜] + space 𝕜 branch (n + 1) A := + childSum (childRestriction A) (fun i => space 𝕜 branch n (childFamily A i)) + +theorem recursiveSum_surjective (A : Slots branch (n + 1) → Type*) : + Function.Surjective (recursiveSum (𝕜 := 𝕜) A) := + childSum_surjective (childRestriction A) (fun i => space 𝕜 branch n (childFamily A i)) + +theorem uniform_recursiveSum (A : Slots branch (n + 1) → Type*) + [∀ i : Fin (branch n), Fintype (squareSpace (space 𝕜 branch n (childFamily A i)))] + [Fintype (space 𝕜 branch (n + 1) A)] : + (FiniteProduct.law (fun i : Fin (branch n) => + FiniteDistribution.uniform (squareSpace (space 𝕜 branch n (childFamily A i))))).pushforward + (recursiveSum (𝕜 := 𝕜) A) = FiniteDistribution.uniform (space 𝕜 branch (n + 1) A) := + product_uniform_linear_image + (I := Fin (branch n)) + (Ω := fun i => squareSpace (space 𝕜 branch n (childFamily A i))) + (R := 𝕜) (V := space 𝕜 branch (n + 1) A) + (recursiveSum (𝕜 := 𝕜) A) (recursiveSum_surjective (𝕜 := 𝕜) A) + +end +end PerfectCompleteness.UniformChildSum + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/UniformDensity.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/UniformDensity.lean new file mode 100644 index 0000000000000000000000000000000000000000..67abe2f3df6c6336e4679bb6f2997b4f941358e0 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/UniformDensity.lean @@ -0,0 +1,96 @@ +import OAI.Computability.PerfectCompleteness.Foundations.RecursiveSpaceEquivLemmas +import OAI.Computability.UniqueGames.Foundations.SamplingLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.UniformDensity + +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators + +noncomputable section + +variable {Ω : Type*} [Fintype Ω] [Nonempty Ω] + +def density (μ : FiniteDistribution Ω) (x : Ω) : ℝ := + (Fintype.card Ω : ℝ) * μ.weight x + +theorem weight_eq (μ : FiniteDistribution Ω) (x : Ω) : + μ.weight x = (FiniteDistribution.uniform Ω).weight x * density μ x := by + have hn : (Fintype.card Ω : ℝ) ≠ 0 := + Nat.cast_ne_zero.mpr Fintype.card_ne_zero + change μ.weight x = (1 / (Fintype.card Ω : ℝ)) * + ((Fintype.card Ω : ℝ) * μ.weight x) + rw [← mul_assoc, one_div, inv_mul_cancel₀ hn, one_mul] + +theorem mean_one (μ : FiniteDistribution Ω) : + (FiniteDistribution.uniform Ω).expectation (density μ) = 1 := by + change (∑ x, (FiniteDistribution.uniform Ω).weight x * density μ x) = 1 + simp_rw [← weight_eq μ] + exact μ.normalized + +omit [Nonempty Ω] in +theorem nonnegative (μ : FiniteDistribution Ω) (x : Ω) : + 0 ≤ density μ x := + mul_nonneg (Nat.cast_nonneg _) (μ.nonnegative x) + +omit [Nonempty Ω] in +private theorem weight_le_one (μ : FiniteDistribution Ω) (x : Ω) : + μ.weight x ≤ 1 := by + classical + calc + μ.weight x ≤ ∑ y, μ.weight y := + Finset.single_le_sum (fun y _ => μ.nonnegative y) (Finset.mem_univ x) + _ = 1 := μ.normalized + +omit [Nonempty Ω] in +theorem density_le_card (μ : FiniteDistribution Ω) (x : Ω) : + density μ x ≤ (Fintype.card Ω : ℝ) := by + simpa only [density, mul_one] using + mul_le_mul_of_nonneg_left (weight_le_one μ x) (Nat.cast_nonneg (Fintype.card Ω) : + (0 : ℝ) ≤ (Fintype.card Ω : ℝ)) + +theorem second_moment_le_card_sub_one (μ : FiniteDistribution Ω) : + (FiniteDistribution.uniform Ω).expectation (fun x => (density μ x - 1) ^ 2) ≤ + (Fintype.card Ω : ℝ) - 1 := by + have hpoint (x : Ω) : + (density μ x - 1) ^ 2 ≤ ((Fintype.card Ω : ℝ) - 2) * density μ x + 1 := by + have hmul := mul_le_mul_of_nonneg_right (density_le_card μ x) (nonnegative μ x) + nlinarith + have hexpectation : + (FiniteDistribution.uniform Ω).expectation + (fun x => ((Fintype.card Ω : ℝ) - 2) * density μ x + 1) = + ((Fintype.card Ω : ℝ) - 2) * + (FiniteDistribution.uniform Ω).expectation (density μ) + 1 := by + unfold FiniteDistribution.expectation + rw [Finset.mul_sum] + simp only [mul_add, mul_one, Finset.sum_add_distrib] + rw [(FiniteDistribution.uniform Ω).normalized] + congr 1 + apply Finset.sum_congr rfl + intro x _ + ring + calc + _ ≤ (FiniteDistribution.uniform Ω).expectation + (fun x => ((Fintype.card Ω : ℝ) - 2) * density μ x + 1) := + SmallBias.expectation_mono (FiniteDistribution.uniform Ω) hpoint + _ = ((Fintype.card Ω : ℝ) - 2) * + (FiniteDistribution.uniform Ω).expectation (density μ) + 1 := hexpectation + _ = (Fintype.card Ω : ℝ) - 1 := by rw [mean_one]; ring + +theorem second_moment_le (μ : FiniteDistribution Ω) (L : ℝ) + (hcard : (Fintype.card Ω : ℝ) ≤ L) : + (FiniteDistribution.uniform Ω).expectation (fun x => (density μ x - 1) ^ 2) ≤ + L ^ 2 := by + apply (second_moment_le_card_sub_one μ).trans + have hL : 0 ≤ L := (Nat.cast_nonneg (Fintype.card Ω)).trans hcard + nlinarith [sq_nonneg (L - 1)] + +end +end PerfectCompleteness.UniformDensity + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/UniformDifference.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/UniformDifference.lean new file mode 100644 index 0000000000000000000000000000000000000000..eea2e5b531d66671eeb5c1b5dc5fd36f3a13cfdf --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/UniformDifference.lean @@ -0,0 +1,66 @@ +import Mathlib.Algebra.BigOperators.Expect +import Mathlib.Algebra.Group.Equiv.Basic +import OAI.Computability.UniqueGames.Foundations.SamplingLemmas +import OAI.Computability.UniqueGames.Foundations.ValueLemmas +import OAI.Computability.UniqueGames.Games.FinishBoundsLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.UniformDifference + +noncomputable section + +open scoped BigOperators +open UniqueGamesTheorem.Foundations.Games + +variable {B H : Type*} [Fintype B] [Fintype H] [AddGroup H] + +def difference (old : B → H) (p : B × H) : B × H := (p.1, p.2 - old p.1) + +theorem expectation_difference (μ : FiniteDistribution B) (old : B → H) + (f : B × H → ℝ) : + (μ.product (FiniteDistribution.uniform H)).expectation + (fun p => f (difference old p)) = + (μ.product (FiniteDistribution.uniform H)).expectation f := by + rw [FiniteDistribution.expectation_product, FiniteDistribution.expectation_product] + apply FiniteDistribution.expectation_congr + intro b + rw [FiniteDistribution.expectation_uniform, FiniteDistribution.expectation_uniform] + simpa only [Fintype.expect_eq_sum_div_card, difference, sub_eq_add_neg] using + Fintype.expect_equiv (Equiv.addRight (-old b)) + (fun h : H => f (b, h - old b)) (fun h : H => f (b, h)) + (fun _ => by simp only [sub_eq_add_neg]; rfl) + +theorem difference_law (μ : FiniteDistribution B) (old : B → H) : + (μ.product (FiniteDistribution.uniform H)).pushforward (difference old) = + μ.product (FiniteDistribution.uniform H) := by + classical + apply FiniteDistribution.eq_of_weight_eq + intro z + have h := expectation_difference μ old (fun p => if p = z then (1 : ℝ) else 0) + rw [← FiniteDistribution.expectation_pushforward + (μ.product (FiniteDistribution.uniform H)) (difference old) + (fun p => if p = z then (1 : ℝ) else 0)] at h + simpa only [FiniteDistribution.expectation, mul_ite, mul_one, mul_zero, + Finset.sum_ite_eq', Finset.mem_univ, ite_true] using h + +theorem observed_difference_law {P : Type*} [Fintype P] + (μ : FiniteDistribution B) (old : B → H) (observe : B → P) : + (μ.product (FiniteDistribution.uniform H)).pushforward + (fun p => (observe p.1, p.2 - old p.1)) = + (μ.product (FiniteDistribution.uniform H)).pushforward + (fun p => (observe p.1, p.2)) := by + have h := congrArg + (fun ν : FiniteDistribution (B × H) => ν.pushforward (fun p => (observe p.1, p.2))) + (difference_law μ old) + rw [FiniteDistribution.pushforward_comp] at h + exact h + +end +end PerfectCompleteness.UniformDifference + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/UniformLatent.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/UniformLatent.lean new file mode 100644 index 0000000000000000000000000000000000000000..c4e55a35a8b24e15cd3bea8046a5df1e424d4707 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/UniformLatent.lean @@ -0,0 +1,125 @@ +import OAI.Computability.PerfectCompleteness.Repetition.CleanConditioning +import OAI.Computability.UniqueGames.Foundations.SamplingLemmas + +namespace OAI + + +namespace PerfectCompleteness.UniformLatent + +open scoped BigOperators +open UniqueGamesTheorem.Foundations.Games +open FiniteProduct CleanConditioning + +noncomputable section + +theorem probability_uniform_singleton {A : Type*} [Fintype A] [Nonempty A] + [DecidableEq A] (a : A) : + (FiniteDistribution.uniform A).probability (fun x => decide (x = a)) = + 1 / (Fintype.card A : ℝ) := by + simp [FiniteDistribution.probability, FiniteDistribution.uniform] + + +variable {S J : Type*} [Fintype S] [Fintype J] [DecidableEq J] + (Ω : S → J → Type*) [∀ s j, Fintype (Ω s j)] [∀ s j, Nonempty (Ω s j)] + +abbrev Raw := Σ s : S, (j : J) → Ω s j + +def latentKernel (s : S) : FiniteDistribution (Raw Ω) := + (law (fun j => FiniteDistribution.uniform (Ω s j))).pushforward + (fun x => (⟨s, x⟩ : Raw Ω)) + +variable [∀ s j, DecidableEq (Ω s j)] + +def zeroEvent (zero : (s : S) → (j : J) → Ω s j) (x : Raw Ω) : Bool := + decide (∀ j, x.2 j = zero x.1 j) + +theorem probability_latentKernel_zero (zero : (s : S) → (j : J) → Ω s j) (s : S) : + (latentKernel Ω s).probability (zeroEvent Ω zero) = + ∏ j, 1 / (Fintype.card (Ω s j) : ℝ) := by + rw [latentKernel, FiniteDistribution.probability_pushforward] + have hevent : (fun x => zeroEvent Ω zero (⟨s, x⟩ : Raw Ω)) = + allEvent (fun j a => decide (a = zero s j)) := by + funext x + apply Bool.eq_iff_iff.mpr + simp [zeroEvent, allEvent] + rw [hevent, probability_law_all] + apply Finset.prod_congr rfl + intro j _ + exact probability_uniform_singleton (zero s j) + +theorem probability_latentKernel_zero_pos (zero : (s : S) → (j : J) → Ω s j) + (s : S) : 0 < (latentKernel Ω s).probability (zeroEvent Ω zero) := by + rw [probability_latentKernel_zero] + apply Finset.prod_pos + intro j _ + exact one_div_pos.mpr (Nat.cast_pos.mpr Fintype.card_pos) + +theorem probability_latentKernel_zero_constant + (zero : (s : S) → (j : J) → Ω s j) (cardinality : J → Nat) + (same_cardinality : ∀ s j, Fintype.card (Ω s j) = cardinality j) (s : S) : + (latentKernel Ω s).probability (zeroEvent Ω zero) = + ∏ j, 1 / (cardinality j : ℝ) := by + rw [probability_latentKernel_zero] + simp only [same_cardinality] + + +variable {D : Type*} [Fintype D] + +def projectedKernel (flag : FiniteDistribution Bool) + (nonprojected : S → FiniteDistribution D) (s : S) : + FiniteDistribution (Sum D (Raw Ω)) := + flag.mixture (fun b => if b then + (latentKernel Ω s).pushforward Sum.inr else (nonprojected s).pushforward Sum.inl) + +def projectedZero (zero : (s : S) → (j : J) → Ω s j) : Sum D (Raw Ω) → Bool + | Sum.inl _ => false + | Sum.inr x => zeroEvent Ω zero x + +theorem probability_projectedKernel_zero (flag : FiniteDistribution Bool) + (nonprojected : S → FiniteDistribution D) + (zero : (s : S) → (j : J) → Ω s j) (s : S) : + (projectedKernel Ω flag nonprojected s).probability (projectedZero Ω zero) = + flag.weight true * (∏ j, 1 / (Fintype.card (Ω s j) : ℝ)) := by + simp [projectedKernel, FiniteDistribution.probability_mixture, + FiniteDistribution.probability_pushforward, projectedZero, + probability_latentKernel_zero] + +theorem probability_projectedKernel_zero_constant (flag : FiniteDistribution Bool) + (nonprojected : S → FiniteDistribution D) + (zero : (s : S) → (j : J) → Ω s j) (cardinality : J → Nat) + (same_cardinality : ∀ s j, Fintype.card (Ω s j) = cardinality j) (s : S) : + (projectedKernel Ω flag nonprojected s).probability (projectedZero Ω zero) = + flag.weight true * (∏ j, 1 / (cardinality j : ℝ)) := by + rw [probability_projectedKernel_zero] + simp only [same_cardinality] + +theorem probability_projectedKernel_zero_binary (flag : FiniteDistribution Bool) + (nonprojected : S → FiniteDistribution D) + (zero : (s : S) → (j : J) → Ω s j) (dimension : J → Nat) + (same_dimension : ∀ s j, Fintype.card (Ω s j) = 2 ^ dimension j) (s : S) : + (projectedKernel Ω flag nonprojected s).probability (projectedZero Ω zero) = + flag.weight true / (2 : ℝ) ^ (∑ j, dimension j) := by + rw [probability_projectedKernel_zero_constant Ω flag nonprojected zero + (fun j => 2 ^ dimension j) same_dimension] + simp only [Nat.cast_pow, Nat.cast_ofNat, Finset.prod_div_distrib, + Finset.prod_const_one, Finset.prod_pow_eq_pow_sum, mul_one_div] + +theorem source_condition_projected [DecidableEq S] (μ : FiniteDistribution S) + (flag : FiniteDistribution Bool) (nonprojected : S → FiniteDistribution D) + (zero : (s : S) → (j : J) → Ω s j) (cardinality : J → Nat) + (same_cardinality : ∀ s j, Fintype.card (Ω s j) = cardinality j) + (positive : 0 < (kernelJoint μ (projectedKernel Ω flag nonprojected)).probability + (fun x => projectedZero Ω zero x.2)) : + ((kernelJoint μ (projectedKernel Ω flag nonprojected)).condition + (fun x => projectedZero Ω zero x.2) positive).pushforward Prod.fst = μ := by + apply source_condition_of_constant μ _ _ + (flag.weight true * (∏ j, 1 / (cardinality j : ℝ))) _ positive + intro s + exact probability_projectedKernel_zero_constant Ω flag nonprojected zero + cardinality same_cardinality s + + +end +end PerfectCompleteness.UniformLatent + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/UniformLatentSupportLemmas.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/UniformLatentSupportLemmas.lean new file mode 100644 index 0000000000000000000000000000000000000000..848757fc110e521073707bac0bb973191b6b6372 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/UniformLatentSupportLemmas.lean @@ -0,0 +1,560 @@ +import OAI.Computability.PerfectCompleteness.Algebra.UniformLinearImage +import OAI.Computability.PerfectCompleteness.Foundations.QuarterBalanceLemmas +import OAI.Computability.PerfectCompleteness.Repetition.CutChildCleanLawLemmas +import OAI.Computability.PerfectCompleteness.Sampling.BucketUniformLemmas +import OAI.Computability.PerfectCompleteness.Sampling.RationalFiniteLawLemmas +import OAI.Computability.PerfectCompleteness.Sampling.UniformLatent + +namespace OAI + + +namespace PerfectCompleteness.UniformLatentSupport + +noncomputable section + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games + +section Latent + +variable {S J D : Type*} [Fintype S] [Fintype J] [DecidableEq J] [Fintype D] + (Ω : S → J → Type*) [∀ s j, Fintype (Ω s j)] [∀ s j, Nonempty (Ω s j)] + +theorem latentKernel_weight_zero_of_tag_ne (s : S) (raw : UniformLatent.Raw Ω) + (hne : raw.1 ≠ s) : (UniformLatent.latentKernel Ω s).weight raw = 0 := by + simp only [UniformLatent.latentKernel, FiniteDistribution.pushforward] + apply Finset.sum_eq_zero + intro x _ + have hx : (⟨s, x⟩ : UniformLatent.Raw Ω) ≠ raw := by + intro h + exact hne (congrArg (fun z : UniformLatent.Raw Ω => z.1) h).symm + simp only [ite_eq_right hx] + +theorem latentKernel_tag (s : S) (raw : UniformLatent.Raw Ω) + (hraw : (UniformLatent.latentKernel Ω s).weight raw ≠ 0) : raw.1 = s := by + by_contra hne + exact hraw (latentKernel_weight_zero_of_tag_ne Ω s raw hne) + +theorem projectedKernel_weight_inr (flag : FiniteDistribution Bool) + (nonprojected : S → FiniteDistribution D) (s : S) (raw : UniformLatent.Raw Ω) : + (UniformLatent.projectedKernel Ω flag nonprojected s).weight (Sum.inr raw) = + flag.weight true * (UniformLatent.latentKernel Ω s).weight raw := by + simp [UniformLatent.projectedKernel, FiniteDistribution.mixture, + FiniteDistribution.pushforward] + +theorem projectedKernel_tag (flag : FiniteDistribution Bool) + (nonprojected : S → FiniteDistribution D) (s : S) (raw : UniformLatent.Raw Ω) + (hraw : (UniformLatent.projectedKernel Ω flag nonprojected s).weight (Sum.inr raw) ≠ 0) : + raw.1 = s := by + apply latentKernel_tag Ω s raw + intro hz + apply hraw + rw [projectedKernel_weight_inr, hz, mul_zero] + +end Latent + + +variable {I : Type*} [Fintype I] [DecidableEq I] + {E R J D : I → Type*} + [∀ i, Fintype (E i)] [∀ i, Fintype (R i)] [∀ i, Fintype (J i)] [∀ i, Fintype (D i)] + [∀ i, DecidableEq (E i)] [∀ i, DecidableEq (R i)] + [∀ i, DecidableEq (J i)] [∀ i, DecidableEq (D i)] + (Ω : (i : I) → (E i × R i) → J i → Type*) + [∀ i s j, Fintype (Ω i s j)] [∀ i s j, Nonempty (Ω i s j)] + [∀ i s j, DecidableEq (Ω i s j)] + (μ : (i : I) → FiniteDistribution (E i)) + (ν : (i : I) → FiniteDistribution (R i)) + (flag : (i : I) → FiniteDistribution Bool) + (nonprojected : (i : I) → E i × R i → FiniteDistribution (D i)) + +def childLaw (i : I) : + FiniteDistribution (E i × (R i × UniformCleanSources.ChildRaw (D := D) Ω i)) := + CleanConditioning.kernelJoint (μ i) (fun e => + CleanConditioning.kernelJoint (ν i) (UniformCleanSources.childKernel Ω flag nonprojected i e)) + +omit [Fintype I] [DecidableEq I] [∀ i, DecidableEq (E i)] [∀ i, DecidableEq (R i)] + [∀ i, DecidableEq (D i)] [∀ i s j, DecidableEq (Ω i s j)] in +theorem childLaw_weight (i : I) + (x : E i × (R i × UniformCleanSources.ChildRaw (D := D) Ω i)) : + (childLaw Ω μ ν flag nonprojected i).weight x = + (μ i).weight x.1 * ((ν i).weight x.2.1 * + (UniformLatent.projectedKernel (Ω i) (flag i) (nonprojected i) (x.1, x.2.1)).weight + x.2.2) := rfl + +omit [Fintype I] [DecidableEq I] [∀ i, DecidableEq (E i)] [∀ i, DecidableEq (R i)] + [∀ i, DecidableEq (D i)] [∀ i s j, DecidableEq (Ω i s j)] in +theorem childLaw_projected_tag (i : I) + (x : E i × (R i × UniformCleanSources.ChildRaw (D := D) Ω i)) + (hx : (childLaw Ω μ ν flag nonprojected i).weight x ≠ 0) + (raw : UniformLatent.Raw (Ω i)) (hraw : x.2.2 = Sum.inr raw) : + raw.1 = (x.1, x.2.1) := by + apply projectedKernel_tag (Ω i) (flag i) (nonprojected i) (x.1, x.2.1) raw + intro hz + apply hx + rw [childLaw_weight, hraw, hz, mul_zero, mul_zero] + +omit [∀ i, DecidableEq (E i)] [∀ i, DecidableEq (R i)] + [∀ i, DecidableEq (D i)] [∀ i s j, DecidableEq (Ω i s j)] in +theorem childrenLaw_child_weight_ne_zero + (x : (i : I) → E i × (R i × UniformCleanSources.ChildRaw (D := D) Ω i)) + (hx : (UniformCleanSources.childrenLaw Ω μ ν flag nonprojected).weight x ≠ 0) + (i : I) : (childLaw Ω μ ν flag nonprojected i).weight (x i) ≠ 0 := by + intro hz + apply hx + change (∏ j, (childLaw Ω μ ν flag nonprojected j).weight (x j)) = 0 + exact Finset.prod_eq_zero (Finset.mem_univ i) hz + +omit [∀ i, DecidableEq (E i)] [∀ i, DecidableEq (R i)] + [∀ i, DecidableEq (D i)] [∀ i s j, DecidableEq (Ω i s j)] in +theorem childrenLaw_projected_tag + (x : (i : I) → E i × (R i × UniformCleanSources.ChildRaw (D := D) Ω i)) + (hx : (UniformCleanSources.childrenLaw Ω μ ν flag nonprojected).weight x ≠ 0) + (i : I) (raw : UniformLatent.Raw (Ω i)) (hraw : (x i).2.2 = Sum.inr raw) : + raw.1 = ((x i).1, (x i).2.1) := + childLaw_projected_tag Ω μ ν flag nonprojected i (x i) + (childrenLaw_child_weight_ne_zero Ω μ ν flag nonprojected x hx i) raw hraw + +omit [∀ i, DecidableEq (E i)] [∀ i, DecidableEq (R i)] + [∀ i, DecidableEq (D i)] [∀ i s j, DecidableEq (Ω i s j)] in +theorem conditioned_childrenLaw_projected_tag + (event : ((i : I) → E i × (R i × UniformCleanSources.ChildRaw (D := D) Ω i)) → Bool) + (positive : 0 < (UniformCleanSources.childrenLaw Ω μ ν flag nonprojected).probability event) + (x : (i : I) → E i × (R i × UniformCleanSources.ChildRaw (D := D) Ω i)) + (hx : ((UniformCleanSources.childrenLaw Ω μ ν flag nonprojected).condition event positive).weight x ≠ 0) + (i : I) (raw : UniformLatent.Raw (Ω i)) (hraw : (x i).2.2 = Sum.inr raw) : + raw.1 = ((x i).1, (x i).2.1) := by + apply childrenLaw_projected_tag Ω μ ν flag nonprojected x _ i raw hraw + intro hz + apply hx + simp only [FiniteDistribution.condition, hz, zero_div, ite_self] + +end +end PerfectCompleteness.UniformLatentSupport + + + +namespace PerfectCompleteness.NativeTaggedUniform + +noncomputable section + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games + +abbrev Raw {S : Type*} (Native : S → Type*) := Σ s, Native s + +def sourceTag {S J : Type*} (Native : S → Type*) (Ω : S → J → Type*) : + Raw Native ⊕ UniformLatent.Raw Ω → S + | .inl raw => raw.1 + | .inr raw => raw.1 + +section Native + +variable {S : Type*} [Fintype S] [DecidableEq S] + (Native : S → Type*) [∀ s, Fintype (Native s)] [∀ s, Nonempty (Native s)] + +def kernel (s : S) : FiniteDistribution (Raw Native) := + (FiniteDistribution.uniform (Native s)).pushforward (fun x => (⟨s, x⟩ : Raw Native)) + +omit [DecidableEq S] in +theorem kernel_weight_zero_of_tag_ne (s : S) (raw : Raw Native) (hne : raw.1 ≠ s) : + (kernel Native s).weight raw = 0 := by + unfold kernel FiniteDistribution.pushforward + apply Finset.sum_eq_zero + intro x _ + have hx : (⟨s, x⟩ : Raw Native) ≠ raw := by + intro h + exact hne (congrArg (fun z : Raw Native => z.1) h).symm + exact ite_eq_right hx + +theorem kernel_tag (s : S) (raw : Raw Native) + (hraw : (kernel Native s).weight raw ≠ 0) : raw.1 = s := by + by_contra hne + exact hraw (kernel_weight_zero_of_tag_ne Native s raw hne) + +end Native + +section Projection + +variable {S J : Type*} [Fintype S] [DecidableEq S] [Fintype J] [DecidableEq J] + (Native : S → Type*) [∀ s, Fintype (Native s)] [∀ s, Nonempty (Native s)] + (Ω : S → J → Type*) [∀ s j, Fintype (Ω s j)] [∀ s j, Nonempty (Ω s j)] + +theorem projectedKernel_weight_inl (flag : FiniteDistribution Bool) (s : S) + (raw : Raw Native) : + (UniformLatent.projectedKernel Ω flag (kernel Native) s).weight (.inl raw) = + flag.weight false * (kernel Native s).weight raw := by + simp [UniformLatent.projectedKernel, FiniteDistribution.mixture, + FiniteDistribution.pushforward] + +theorem projectedKernel_sourceTag (flag : FiniteDistribution Bool) (s : S) + (raw : Raw Native ⊕ UniformLatent.Raw Ω) + (hraw : (UniformLatent.projectedKernel Ω flag (kernel Native) s).weight raw ≠ 0) : + sourceTag Native Ω raw = s := by + cases raw with + | inl raw => + apply kernel_tag Native s raw + intro hz + apply hraw + rw [projectedKernel_weight_inl, hz, mul_zero] + | inr raw => + exact UniformLatentSupport.projectedKernel_tag Ω flag (kernel Native) s raw hraw + +end Projection + + +variable {I : Type*} [Fintype I] [DecidableEq I] + {E R J : I → Type*} + [∀ i, Fintype (E i)] [∀ i, Fintype (R i)] [∀ i, Fintype (J i)] + [∀ i, DecidableEq (E i)] [∀ i, DecidableEq (R i)] [∀ i, DecidableEq (J i)] + (Native : (i : I) → E i × R i → Type*) + [∀ i s, Fintype (Native i s)] [∀ i s, Nonempty (Native i s)] + (Ω : (i : I) → (E i × R i) → J i → Type*) + [∀ i s j, Fintype (Ω i s j)] [∀ i s j, Nonempty (Ω i s j)] + [∀ i s j, DecidableEq (Ω i s j)] + (μ : (i : I) → FiniteDistribution (E i)) + (ν : (i : I) → FiniteDistribution (R i)) + (flag : (i : I) → FiniteDistribution Bool) + +omit [Fintype I] [DecidableEq I] [∀ i s j, DecidableEq (Ω i s j)] in +theorem childLaw_sourceTag (i : I) + (x : E i × (R i × UniformCleanSources.ChildRaw (D := fun i => Raw (Native i)) Ω i)) + (hx : (UniformLatentSupport.childLaw Ω μ ν flag (fun i => kernel (Native i)) i).weight + x ≠ 0) : + sourceTag (Native i) (Ω i) x.2.2 = (x.1, x.2.1) := by + apply projectedKernel_sourceTag (Native i) (Ω i) (flag i) (x.1, x.2.1) x.2.2 + intro hz + apply hx + rw [UniformLatentSupport.childLaw_weight, hz, mul_zero, mul_zero] + +omit [∀ i s j, DecidableEq (Ω i s j)] in +theorem childrenLaw_sourceTag + (x : (i : I) → E i × + (R i × UniformCleanSources.ChildRaw (D := fun i => Raw (Native i)) Ω i)) + (hx : (UniformCleanSources.childrenLaw Ω μ ν flag (fun i => kernel (Native i))).weight + x ≠ 0) (i : I) : + sourceTag (Native i) (Ω i) (x i).2.2 = ((x i).1, (x i).2.1) := + childLaw_sourceTag Native Ω μ ν flag i (x i) + (UniformLatentSupport.childrenLaw_child_weight_ne_zero Ω μ ν flag + (fun i => kernel (Native i)) x hx i) + +omit [∀ i s j, DecidableEq (Ω i s j)] in +theorem childrenLaw_native_tag + (x : (i : I) → E i × + (R i × UniformCleanSources.ChildRaw (D := fun i => Raw (Native i)) Ω i)) + (hx : (UniformCleanSources.childrenLaw Ω μ ν flag (fun i => kernel (Native i))).weight + x ≠ 0) (i : I) (raw : Raw (Native i)) (hraw : (x i).2.2 = .inl raw) : + raw.1 = ((x i).1, (x i).2.1) := by + have h := childrenLaw_sourceTag Native Ω μ ν flag x hx i + rw [hraw] at h + exact h + +omit [∀ i s j, DecidableEq (Ω i s j)] in +theorem conditioned_childrenLaw_sourceTag + (event : ((i : I) → E i × + (R i × UniformCleanSources.ChildRaw (D := fun i => Raw (Native i)) Ω i)) → Bool) + (positive : 0 < (UniformCleanSources.childrenLaw Ω μ ν flag + (fun i => kernel (Native i))).probability event) + (x : (i : I) → E i × + (R i × UniformCleanSources.ChildRaw (D := fun i => Raw (Native i)) Ω i)) + (hx : ((UniformCleanSources.childrenLaw Ω μ ν flag (fun i => kernel (Native i))).condition + event positive).weight x ≠ 0) (i : I) : + sourceTag (Native i) (Ω i) (x i).2.2 = ((x i).1, (x i).2.1) := by + apply childrenLaw_sourceTag Native Ω μ ν flag x _ i + intro hz + apply hx + simp only [FiniteDistribution.condition, hz, zero_div, ite_self] + +end +end PerfectCompleteness.NativeTaggedUniform + + + +namespace PerfectCompleteness.QuarterBalance + +open UniqueGamesTheorem.Foundations.Games + +noncomputable section + +variable {V : Type*} [AddCommGroup V] [Module F2 V] [Fintype V] + +theorem nonzero_linear_surjective (f : V →ₗ[F2] F2) (hf : f ≠ 0) : + Function.Surjective f := by + classical + have hx : ∃ x, f x ≠ 0 := by + by_contra h + push Not at h + exact hf (LinearMap.ext h) + obtain ⟨x, hx⟩ := hx + intro b + refine ⟨(b / f x) • x, ?_⟩ + simp only [map_smul, smul_eq_mul] + exact div_mul_cancel₀ b hx + +theorem uniform_bit_probability (f : V →ₗ[F2] F2) (hf : f ≠ 0) (b : F2) : + (FiniteDistribution.uniform V).probability (fun x => decide (f x = b)) = (1 / 2 : ℝ) := by + have h := UniformLinearImage.uniform_pushforward_linearMap f (nonzero_linear_surjective f hf) + have hp := congrArg (fun μ : FiniteDistribution F2 => + μ.probability (fun y => decide (y = b))) h + rw [FiniteDistribution.probability_pushforward] at hp + rw [hp, UniformLatent.probability_uniform_singleton] + norm_num [F2, ZMod.card] + +theorem uniform_sign_expectation_eq_zero (f : V →ₗ[F2] F2) (hf : f ≠ 0) : + (FiniteDistribution.uniform V).expectation (fun x => sign (f x)) = 0 := by + rw [expectation_sign, uniform_bit_probability f hf] + norm_num + +theorem uniform_balanced : Balanced (FiniteDistribution.uniform V) := by + intro f hf b + rw [uniform_bit_probability f hf] + norm_num + +end +end PerfectCompleteness.QuarterBalance + + + +namespace PerfectCompleteness.RecursiveSamplerBias + +open scoped BigOperators +open UniqueGamesTheorem.Foundations.Games +open PointwiseSpaces RecursiveSpaces DescendantSpaces RecursiveSampler QuarterBalance +open RecursiveSamplerBiasAlgebra RecursiveSamplerBiasProducts + +noncomputable section + +universe u + +variable {branch : Nat → Nat} {n m : Nat} + +theorem sign_sum {I : Type*} [Fintype I] (a : I → F2) : + sign (∑ i, a i) = ∏ i, sign (a i) := by + classical + have h (s : Finset I) : sign (∑ i ∈ s, a i) = ∏ i ∈ s, sign (a i) := by + induction s using Finset.induction_on with + | empty => simp + | @insert i s hi ih => + rw [Finset.sum_insert hi, Finset.prod_insert hi, sign_add, ih] + exact h Finset.univ + +theorem abs_expectation_sign_le_one {Ω : Type*} [Fintype Ω] + (μ : FiniteDistribution Ω) (f : Ω → F2) : + |μ.expectation (fun x => sign (f x))| ≤ 1 := by + calc + _ ≤ ∑ x, |μ.weight x * sign (f x)| := Finset.abs_sum_le_sum_abs _ _ + _ = ∑ x, μ.weight x := by + apply Finset.sum_congr rfl + intro x _ + rw [abs_mul, abs_of_nonneg (μ.nonnegative x), abs_sign, mul_one] + _ = 1 := μ.normalized + +def ordinaryCharacterMean (repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) (A : Slots branch (n + 1) → Type u) + [∀ s, Finite (A s)] (f : space F2 branch (n + 1) A →ₗ[F2] F2) : ℝ := by + letI : ∀ j : OffPath i, Fintype (DrawSpace F2 repeats (.step i p) A (.inl j)) := + fun j => drawSpaceFintype F2 repeats (.step i p) A (.inl j) + letI : ∀ j : OffPath i, Nonempty (DrawSpace F2 repeats (.step i p) A (.inl j)) := + fun j => ⟨zeroDraw F2 repeats (.step i p) A (.inl j)⟩ + exact ∏ j : OffPath i, + (FiniteDistribution.uniform (DrawSpace F2 repeats (.step i p) A (.inl j))).expectation + (fun g => sign ((f.comp (childSquareLift F2 A j.val)) g)) + +def pairCharacterMean (repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) (A : Slots branch (n + 1) → Type u) + [∀ s, Finite (A s)] [Fintype (space F2 branch n (childFamily A i))] + (f : space F2 branch (n + 1) A →ₗ[F2] F2) : ℝ := + ((law F2 repeats p (childFamily A i)).product + (law F2 repeats p (childFamily A i))).expectation + (fun z => sign (childBilinear F2 A i f z.1 z.2)) + +theorem law_step_character (repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) (A : Slots branch (n + 1) → Type u) + [∀ s, Finite (A s)] [Fintype (space F2 branch n (childFamily A i))] + [Fintype (space F2 branch (n + 1) A)] + (f : space F2 branch (n + 1) A →ₗ[F2] F2) : + (law F2 repeats (.step i p) A).expectation (fun g => sign (f g)) = + ordinaryCharacterMean repeats i p A f * + pairCharacterMean repeats i p A f ^ repeats (n + 1) := by + classical + let : ∀ j : OffPath i, Fintype (DrawSpace F2 repeats (.step i p) A (.inl j)) := + fun j => drawSpaceFintype F2 repeats (.step i p) A (.inl j) + let : ∀ j : OffPath i, Nonempty (DrawSpace F2 repeats (.step i p) A (.inl j)) := + fun j => ⟨zeroDraw F2 repeats (.step i p) A (.inl j)⟩ + rw [law_step, FiniteDistribution.expectation_pushforward] + have hsign (z : OrdinaryTape F2 repeats i p A × + (CallIndex repeats n → space F2 branch n (childFamily A i))) : + sign (f (stepCombine F2 repeats i p A z)) = + (∏ j : OffPath i, sign ((f.comp (childSquareLift F2 A j.val)) (z.1 j))) * + ∏ h : Fin (repeats (n + 1)), + sign (childBilinear F2 A i f (z.2 (h, false)) (z.2 (h, true))) := by + have hm := map_combine F2 A i (repeats (n + 1)) f + (fun j : OffPath i => + (show squareSpace (space F2 branch n (childFamily A j.val)) from z.1 j)) + (fun h => z.2 (h, false)) (fun h => z.2 (h, true)) + calc + _ = sign ((∑ j : OffPath i, (f.comp (childSquareLift F2 A j.val)) (z.1 j)) + + ∑ h : Fin (repeats (n + 1)), + childBilinear F2 A i f (z.2 (h, false)) (z.2 (h, true))) := congrArg sign hm + _ = _ := by rw [sign_add, sign_sum, sign_sum] + have hord : (ordinaryLaw F2 repeats i p A).expectation + (fun o => ∏ j : OffPath i, sign ((f.comp (childSquareLift F2 A j.val)) (o j))) = + ordinaryCharacterMean repeats i p A f := + FiniteProduct.expectation_product + (I := OffPath i) + (Ω := fun j => DrawSpace F2 repeats (.step i p) A (.inl j)) + (fun j : OffPath i => + FiniteDistribution.uniform (DrawSpace F2 repeats (.step i p) A (.inl j))) + (fun j (g : DrawSpace F2 repeats (.step i p) A (.inl j)) => + sign ((f.comp (childSquareLift F2 A j.val)) g)) + have hpair : (callScalarLaw F2 repeats i p A).expectation + (fun x => ∏ h : Fin (repeats (n + 1)), + sign (childBilinear F2 A i f (x (h, false)) (x (h, true)))) = + pairCharacterMean repeats i p A f ^ repeats (n + 1) := + expectation_pairs (repeats (n + 1)) (law F2 repeats p (childFamily A i)) + (fun z => sign (childBilinear F2 A i f z.1 z.2)) + calc + _ = ((ordinaryLaw F2 repeats i p A).product + (callScalarLaw F2 repeats i p A)).expectation + (fun z => + (∏ j : OffPath i, sign ((f.comp (childSquareLift F2 A j.val)) (z.1 j))) * + ∏ h : Fin (repeats (n + 1)), + sign (childBilinear F2 A i f (z.2 (h, false)) (z.2 (h, true)))) := + FiniteDistribution.expectation_congr _ hsign + _ = (ordinaryLaw F2 repeats i p A).expectation + (fun o => ∏ j : OffPath i, sign ((f.comp (childSquareLift F2 A j.val)) (o j))) * + (callScalarLaw F2 repeats i p A).expectation + (fun x => ∏ h : Fin (repeats (n + 1)), + sign (childBilinear F2 A i f (x (h, false)) (x (h, true)))) := + expectation_product_mul + (V := OrdinaryTape F2 repeats i p A) + (W := CallIndex repeats n → space F2 branch n (childFamily A i)) + (ordinaryLaw F2 repeats i p A) (callScalarLaw F2 repeats i p A) + (fun o : OrdinaryTape F2 repeats i p A => + ∏ j : OffPath i, sign ((f.comp (childSquareLift F2 A j.val)) (o j))) + (fun x : CallIndex repeats n → space F2 branch n (childFamily A i) => + ∏ h : Fin (repeats (n + 1)), + sign (childBilinear F2 A i f (x (h, false)) (x (h, true)))) + _ = _ := congrArg₂ (fun a b : ℝ => a * b) hord hpair + +theorem abs_ordinaryCharacterMean_le_one (repeats : Nat → Nat) + (i : Fin (branch n)) (p : Path branch n m) + (A : Slots branch (n + 1) → Type u) [∀ s, Finite (A s)] + (f : space F2 branch (n + 1) A →ₗ[F2] F2) : + |ordinaryCharacterMean repeats i p A f| ≤ 1 := by + unfold ordinaryCharacterMean + rw [Finset.abs_prod] + apply Finset.prod_le_one₀ (fun _ _ => abs_nonneg _) + intro j _ + let : Fintype (DrawSpace F2 repeats (.step i p) A (.inl j)) := + drawSpaceFintype F2 repeats (.step i p) A (.inl j) + let : Nonempty (DrawSpace F2 repeats (.step i p) A (.inl j)) := + ⟨zeroDraw F2 repeats (.step i p) A (.inl j)⟩ + exact abs_expectation_sign_le_one + (FiniteDistribution.uniform (DrawSpace F2 repeats (.step i p) A (.inl j))) + (fun g => (f.comp (childSquareLift F2 A j.val)) g) + +theorem ordinaryCharacterMean_eq_zero (repeats : Nat → Nat) + (i : Fin (branch n)) (p : Path branch n m) + (A : Slots branch (n + 1) → Type u) [∀ s, Finite (A s)] + (f : space F2 branch (n + 1) A →ₗ[F2] F2) + (j : OffPath i) (hj : f.comp (childSquareLift F2 A j.val) ≠ 0) : + ordinaryCharacterMean repeats i p A f = 0 := by + classical + unfold ordinaryCharacterMean + apply Finset.prod_eq_zero (Finset.mem_univ j) + let : Fintype (squareSpace (space F2 branch n (childFamily A j.val))) := + drawSpaceFintype F2 repeats (.step i p) A (.inl j) + exact uniform_sign_expectation_eq_zero (f.comp (childSquareLift F2 A j.val)) hj + +theorem law_step_bias_le (repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) (A : Slots branch (n + 1) → Type u) + [∀ s, Finite (A s)] [Fintype (space F2 branch n (childFamily A i))] + [Fintype (space F2 branch (n + 1) A)] + (hchild : Balanced (law F2 repeats p (childFamily A i))) + (f : space F2 branch (n + 1) A →ₗ[F2] F2) (hf : f ≠ 0) : + |(law F2 repeats (.step i p) A).expectation (fun g => sign (f g))| ≤ + (7 / 8 : ℝ) ^ repeats (n + 1) := by + rw [law_step_character] + rcases ordinary_or_bilinear_ne_zero F2 A i f hf with ⟨j, hj⟩ | hB + · rw [ordinaryCharacterMean_eq_zero repeats i p A f j hj, zero_mul, abs_zero] + exact pow_nonneg (by norm_num) _ + · have hp : |pairCharacterMean repeats i p A f| ≤ (7 / 8 : ℝ) := + bilinear_bias _ _ hchild hchild (childBilinear F2 A i f) hB + rw [abs_mul, abs_pow] + calc + _ ≤ 1 * |pairCharacterMean repeats i p A f| ^ repeats (n + 1) := + mul_le_mul_of_nonneg_right + (abs_ordinaryCharacterMean_le_one repeats i p A f) (pow_nonneg (abs_nonneg _) _) + _ = |pairCharacterMean repeats i p A f| ^ repeats (n + 1) := one_mul _ + _ ≤ _ := pow_le_pow_left₀ (abs_nonneg _) hp _ + +def RepetitionsBalanced (repeats : Nat → Nat) : Prop := + ∀ k : Nat, (7 / 8 : ℝ) ^ repeats (k + 1) ≤ 1 / 2 + +theorem repetitionsBalanced_of_six_le (repeats : Nat → Nat) + (hrep : ∀ k : Nat, 6 ≤ repeats (k + 1)) : RepetitionsBalanced repeats := by + intro k + calc + (7 / 8 : ℝ) ^ repeats (k + 1) ≤ (7 / 8 : ℝ) ^ 6 := + pow_le_pow_of_le_one (by norm_num) (by norm_num) (hrep k) + _ ≤ 1 / 2 := by norm_num + +theorem law_balanced (repeats : Nat → Nat) (hrep : RepetitionsBalanced repeats) + (p : Path branch n m) : + ∀ (A : Slots branch n → Type u) [∀ s, Finite (A s)] + [Fintype (space F2 branch n A)], Balanced (law F2 repeats p A) := by + induction p with + | refl n => + intro A hA hH + rw [law_refl_uniform] + apply balanced_of_bias_le_half + intro f hf + rw [uniform_sign_expectation_eq_zero f hf, abs_zero] + norm_num + | @step n m i p ih => + intro A hA hH + let : Fintype (space F2 branch n (childFamily A i)) := Fintype.ofFinite _ + have hchild := ih (childFamily A i) + apply balanced_of_bias_le_half + intro f hf + exact (law_step_bias_le repeats i p A hchild f hf).trans (hrep n) + +theorem law_bias_le (repeats : Nat → Nat) (hrep : RepetitionsBalanced repeats) + (i : Fin (branch n)) (p : Path branch n m) + (A : Slots branch (n + 1) → Type u) [∀ s, Finite (A s)] + [Fintype (space F2 branch (n + 1) A)] + (f : space F2 branch (n + 1) A →ₗ[F2] F2) (hf : f ≠ 0) : + |(law F2 repeats (.step i p) A).expectation (fun g => sign (f g))| ≤ + (7 / 8 : ℝ) ^ repeats (n + 1) := by + let : Fintype (space F2 branch n (childFamily A i)) := Fintype.ofFinite _ + exact law_step_bias_le repeats i p A + (law_balanced repeats hrep p (childFamily A i)) f hf + +theorem law_bias_le_height (repeats : Nat → Nat) (hrep : RepetitionsBalanced repeats) + (p : Path branch n m) (A : Slots branch n → Type u) + [∀ s, Finite (A s)] [Fintype (space F2 branch n A)] + (f : space F2 branch n A →ₗ[F2] F2) (hf : f ≠ 0) : + |(law F2 repeats p A).expectation (fun g => sign (f g))| ≤ + (7 / 8 : ℝ) ^ repeats n := by + cases p with + | refl n => + rw [law_refl_uniform, uniform_sign_expectation_eq_zero f hf, abs_zero] + exact pow_nonneg (by norm_num) _ + | step i p => exact law_bias_le repeats hrep i p A f hf + +theorem tape_bias_le (repeats : Nat → Nat) (hrep : RepetitionsBalanced repeats) + (i : Fin (branch n)) (p : Path branch n m) + (A : Slots branch (n + 1) → Type u) [∀ s, Finite (A s)] + (f : space F2 branch (n + 1) A →ₗ[F2] F2) (hf : f ≠ 0) : + |(tapeLaw F2 repeats (.step i p) A).expectation + (fun t => sign (f (evaluate F2 repeats (.step i p) A t)))| ≤ + (7 / 8 : ℝ) ^ repeats (n + 1) := by + let : Fintype (space F2 branch (n + 1) A) := Fintype.ofFinite _ + have h := law_bias_le repeats hrep i p A f hf + rw [law, FiniteDistribution.expectation_pushforward] at h + exact h + +end +end PerfectCompleteness.RecursiveSamplerBias + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/WholeArrayBucketsLaw.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/WholeArrayBucketsLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..60ed365904bc2add2536a986e73ca2ddb0e23b11 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/WholeArrayBucketsLaw.lean @@ -0,0 +1,155 @@ +import OAI.Computability.PerfectCompleteness.Foundations.WholeArrayInteriorExteriorLemmas +import OAI.Computability.PerfectCompleteness.Sampling.RationalFiniteLawLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.WholeArrayBucketsLaw + +open RecursiveSpaces DescendantSpaces TreeSourceSpaces HierarchicalArrays +open WholeArraySampler WholeArraySubtreeSplit +open UniqueGamesTheorem.Foundations.Games +open scoped Classical + +noncomputable section + +private def reorder (A B C : Type*) : A × (B × C) ≃ B × (A × C) where + toFun z := (z.2.1, (z.1, z.2.2)) + invFun z := (z.2.1, (z.1, z.2.2)) + left_inv _ := rfl + right_inv _ := rfl + +private theorem product_reorder {A B C : Type*} [Fintype A] [Fintype B] [Fintype C] + (μ : FiniteDistribution A) (ν : FiniteDistribution B) (ρ : FiniteDistribution C) : + (μ.product (ν.product ρ)).pushforward (reorder A B C) = ν.product (μ.product ρ) := by + rw [← FiniteDistribution.transport_eq_pushforward] + apply FiniteDistribution.eq_of_weight_eq + intro z + exact mul_left_comm _ _ _ + +private theorem product_swap {A B : Type*} [Fintype A] [Fintype B] + (μ : FiniteDistribution A) (ν : FiniteDistribution B) : + (μ.product ν).pushforward (Equiv.prodComm A B) = ν.product μ := by + rw [← FiniteDistribution.transport_eq_pushforward] + apply FiniteDistribution.eq_of_weight_eq + intro z + exact mul_comm _ _ + +private theorem product_readout_swap {A B V W : Type*} + [Fintype A] [Fintype B] [Fintype V] [Fintype W] + (μ : FiniteDistribution A) (ν : FiniteDistribution B) (f : A → V) (g : B → W) : + (μ.product ν).pushforward (fun z => (g z.2, f z.1)) = + (ν.pushforward g).product (μ.pushforward f) := by + calc + _ = ((μ.product ν).pushforward (fun z : A × B => (f z.1, g z.2))).pushforward + (Equiv.prodComm V W) := + (FiniteDistribution.pushforward_comp (μ.product ν) + (fun z : A × B => (f z.1, g z.2)) (Equiv.prodComm V W)).symm + _ = ((μ.pushforward f).product (ν.pushforward g)).pushforward (Equiv.prodComm V W) := + congrArg (fun law : FiniteDistribution (V × W) => law.pushforward (Equiv.prodComm V W)) + (FiniteDistribution.product_pushforward μ ν f g) + _ = _ := product_swap (μ.pushforward f) (ν.pushforward g) + +variable {branch : Nat → Nat} {N n m t : Nat} + +def split (rows repeats : Nat → Nat) (p : Path branch N (n + 1)) + (chosen : Fin (branch n)) (q : Path branch n m) + (slots : Slots branch N → Fin t → MixedSupport.Slot) + (tape : WholeArraySampler.Tape rows repeats (p.append (.step chosen q)) slots) : + BucketSampler.Tape (rows (n + 1)) + (WholeArrayInteriorHiddenLaw.ScalarTape repeats p chosen q slots) × + WholeArrayInteriorHiddenLaw.Exterior rows repeats p chosen q slots := + let subtree := WholeArraySubtreeSplit.splitEquiv rows repeats p (.step chosen q) slots tape + (subtree.2 (.inl ()), (subtree.1, fun field => subtree.2 field.val)) + +@[simp] theorem split_fst (rows repeats : Nat → Nat) (p : Path branch N (n + 1)) + (chosen : Fin (branch n)) (q : Path branch n m) + (slots : Slots branch N → Fin t → MixedSupport.Slot) + (tape : WholeArraySampler.Tape rows repeats (p.append (.step chosen q)) slots) : + (split rows repeats p chosen q slots tape).1 = + (WholeArraySubtreeSplit.extract rows repeats p (.step chosen q) slots tape) (.inl ()) := rfl + +@[simp] theorem split_snd (rows repeats : Nat → Nat) (p : Path branch N (n + 1)) + (chosen : Fin (branch n)) (q : Path branch n m) + (slots : Slots branch N → Fin t → MixedSupport.Slot) + (tape : WholeArraySampler.Tape rows repeats (p.append (.step chosen q)) slots) : + (split rows repeats p chosen q slots tape).2 = + WholeArrayInteriorExterior.read rows repeats p chosen q slots tape := rfl + +theorem split_law (rows repeats : Nat → Nat) (p : Path branch N (n + 1)) + (chosen : Fin (branch n)) (q : Path branch n m) + (slots : Slots branch N → Fin t → MixedSupport.Slot) : + (WholeArraySampler.tapeLaw rows repeats (p.append (.step chosen q)) slots).pushforward + (split rows repeats p chosen q slots) = + (BucketSampler.tapeLaw (rows (n + 1)) + (WholeArrayInteriorHiddenLaw.scalarLaw repeats p chosen q slots)).product + (WholeArrayInteriorHiddenLaw.exteriorLaw rows repeats p chosen q slots) := by + let ancestor := WholeArraySubtreeSplit.complementLaw rows repeats p (.step chosen q) slots + let subtree := WholeArraySampler.tapeLaw rows repeats (.step chosen q) (subtreeSlots p slots) + let localSplit := WholeArrayHiddenLaw.splitRoot rows repeats chosen q (subtreeSlots p slots) + calc + _ = ((WholeArraySampler.tapeLaw rows repeats (p.append (.step chosen q)) slots).pushforward + (WholeArraySubtreeSplit.splitEquiv rows repeats p (.step chosen q) slots)).pushforward + (fun z => reorder _ _ _ (z.1, localSplit z.2)) := + (FiniteDistribution.pushforward_comp _ _ _).symm + _ = (ancestor.product subtree).pushforward (fun z => reorder _ _ _ (z.1, localSplit z.2)) := by + rw [WholeArraySubtreeSplit.splitEquiv_tapeLaw] + _ = ((ancestor.product subtree).pushforward (fun z => (z.1, localSplit z.2))).pushforward + (reorder _ _ _) := (FiniteDistribution.pushforward_comp _ _ _).symm + _ = (ancestor.product (subtree.pushforward localSplit)).pushforward (reorder _ _ _) := by + rw [WholeArrayHiddenLaw.product_read_second] + _ = _ := by + dsimp only [subtree, localSplit] + rw [WholeArrayHiddenLaw.splitRoot_law, product_reorder] + rfl + +def readout {V B : Type*} (rows repeats : Nat → Nat) (p : Path branch N (n + 1)) + (chosen : Fin (branch n)) (q : Path branch n m) + (slots : Slots branch N → Fin t → MixedSupport.Slot) + (value : WholeArrayInteriorHiddenLaw.ScalarTape repeats p chosen q slots → V) + (background : WholeArrayInteriorHiddenLaw.Exterior rows repeats p chosen q slots → B) + (tape : WholeArraySampler.Tape rows repeats (p.append (.step chosen q)) slots) : + B × BucketSampler.Tape (rows (n + 1)) V := + (background (split rows repeats p chosen q slots tape).2, + fun direction => value ((split rows repeats p chosen q slots tape).1 direction)) + +theorem readout_law {V B : Type*} [Fintype V] [Fintype B] + (rows repeats : Nat → Nat) (p : Path branch N (n + 1)) + (chosen : Fin (branch n)) (q : Path branch n m) + (slots : Slots branch N → Fin t → MixedSupport.Slot) + (value : WholeArrayInteriorHiddenLaw.ScalarTape repeats p chosen q slots → V) + (background : WholeArrayInteriorHiddenLaw.Exterior rows repeats p chosen q slots → B) : + (WholeArraySampler.tapeLaw rows repeats (p.append (.step chosen q)) slots).pushforward + (readout rows repeats p chosen q slots value background) = + ((WholeArrayInteriorHiddenLaw.exteriorLaw rows repeats p chosen q slots).pushforward background).product + (BucketSampler.tapeLaw (rows (n + 1)) + ((WholeArrayInteriorHiddenLaw.scalarLaw repeats p chosen q slots).pushforward value)) := by + let buckets := BucketSampler.tapeLaw (rows (n + 1)) + (WholeArrayInteriorHiddenLaw.scalarLaw repeats p chosen q slots) + let exterior := WholeArrayInteriorHiddenLaw.exteriorLaw rows repeats p chosen q slots + have hvalues : buckets.pushforward (fun tapes direction => value (tapes direction)) = + BucketSampler.tapeLaw (rows (n + 1)) + ((WholeArrayInteriorHiddenLaw.scalarLaw repeats p chosen q slots).pushforward value) := + FiniteProduct.pushforward_map + (fun _ : BucketSampler.Direction (rows (n + 1)) => + WholeArrayInteriorHiddenLaw.scalarLaw repeats p chosen q slots) + (fun _ => value) + calc + _ = ((WholeArraySampler.tapeLaw rows repeats (p.append (.step chosen q)) slots).pushforward + (split rows repeats p chosen q slots)).pushforward + (fun z => (background z.2, fun direction => value (z.1 direction))) := + (FiniteDistribution.pushforward_comp _ _ _).symm + _ = (buckets.product exterior).pushforward + (fun z => (background z.2, fun direction => value (z.1 direction))) := by rw [split_law] + _ = (exterior.pushforward background).product + (buckets.pushforward (fun tapes direction => value (tapes direction))) := + product_readout_swap buckets exterior (fun tapes direction => value (tapes direction)) background + _ = _ := by rw [hvalues] + +end +end PerfectCompleteness.WholeArrayBucketsLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/WholeArrayExteriorLaw.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/WholeArrayExteriorLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..674a9e9152a472ecf50186adc0ae62b159394ec8 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/WholeArrayExteriorLaw.lean @@ -0,0 +1,119 @@ +import OAI.Computability.PerfectCompleteness.Machines.OwnInputReferenceLemmas +import OAI.Computability.PerfectCompleteness.Sampling.WholeArrayHiddenLaw + +namespace OAI + +section + +namespace PerfectCompleteness.WholeArrayExteriorLaw + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games +open TreeSourceSpaces HierarchicalArrays DescendantSpaces WholeArraySampler +open WholeArrayHiddenLaw + +noncomputable section + +variable {branch : Nat → Nat} {n m t : Nat} + +instance exteriorFintype (rows : Nat → Nat) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (lower : Nodes branch (n + 1)) : + Fintype (OwnInputReference.Exterior slots rows (Sum.inl ()) lower) := + OwnInputReference.exteriorFintype (branch := branch) (n := n + 1) (t := t) + slots rows (Sum.inl ()) lower + +abbrev NonRoot (branch : Nat → Nat) (n : Nat) := + {node : Nodes branch (n + 1) // node ≠ Sum.inl ()} + +def children (rows repeats : Nat → Nat) (i : Fin (branch n)) (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (rest : RestTape rows repeats i p slots) : + (j : Fin (branch n)) → Arrays (childSlots slots j) rows := + WholeArraySampler.childrenAt slots rows i + (WholeArraySampler.evaluate rows repeats p (childSlots slots i) + (rest ⟨Sum.inr (Sum.inl ()), by simp⟩)) + (fun j => rest ⟨Sum.inr (Sum.inr j), by simp⟩) + +def nodeArray (rows repeats : Nat → Nat) (i : Fin (branch n)) (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (rest : RestTape rows repeats i p slots) (node : NonRoot branch n) : + Fin (rows (Nodes.height node.val)) → H (nodeSlots slots node.val) := + match node with + | ⟨.inl u, h⟩ => False.elim (h (by cases u; rfl)) + | ⟨.inr (j, child), _⟩ => children rows repeats i p slots rest j child + +theorem nodeArray_evaluate (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ω : Tape rows repeats (.step i p) slots) (node : NonRoot branch n) : + nodeArray rows repeats i p slots (splitRoot rows repeats i p slots ω).2 node = + WholeArraySampler.evaluate rows repeats (.step i p) slots ω node.val := by + rcases node with ⟨node, hnode⟩ + cases node with + | inl u => + cases u + exact False.elim (hnode rfl) + | inr pair => + rcases pair with ⟨j, child⟩ + rfl + +def exterior (rows repeats : Nat → Nat) (i : Fin (branch n)) (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (lower : Nodes branch (n + 1)) (hne : lower ≠ Sum.inl ()) + (rest : RestTape rows repeats i p slots) : + OwnInputReference.Exterior slots rows (Sum.inl ()) lower where + otherArrays node := nodeArray rows repeats i p slots rest ⟨node.val, node.property.1⟩ + lowerRows := nodeArray rows repeats i p slots rest ⟨lower, hne⟩ + +def readExterior (rows repeats : Nat → Nat) (i : Fin (branch n)) (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (lower : Nodes branch (n + 1)) + (ω : Tape rows repeats (.step i p) slots) : + OwnInputReference.Exterior slots rows (Sum.inl ()) lower where + otherArrays node := WholeArraySampler.evaluate rows repeats (.step i p) slots ω node.val + lowerRows := WholeArraySampler.evaluate rows repeats (.step i p) slots ω lower + +theorem exterior_read_splitRoot (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (lower : Nodes branch (n + 1)) (hne : lower ≠ Sum.inl ()) + (ω : Tape rows repeats (.step i p) slots) : + exterior rows repeats i p slots lower hne (splitRoot rows repeats i p slots ω).2 = + readExterior rows repeats i p slots lower ω := by + unfold exterior readExterior + congr 1 + · funext node + exact nodeArray_evaluate rows repeats i p slots ω ⟨node.val, node.property.1⟩ + · exact nodeArray_evaluate rows repeats i p slots ω ⟨lower, hne⟩ + +def exteriorLaw (rows repeats : Nat → Nat) (i : Fin (branch n)) (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (lower : Nodes branch (n + 1)) (hne : lower ≠ Sum.inl ()) : + FiniteDistribution (OwnInputReference.Exterior slots rows (Sum.inl ()) lower) := + (restLaw rows repeats i p slots).pushforward (exterior rows repeats i p slots lower hne) + +theorem split_exterior_law (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (lower : Nodes branch (n + 1)) (hne : lower ≠ Sum.inl ()) + (W : Submodule F2 (Fin (rows (n + 1)) → F2)) : + (WholeArraySampler.tapeLaw rows repeats (.step i p) slots).pushforward + (fun ω => ((split rows repeats i p slots W ω).1, + ((split rows repeats i p slots W ω).2.1, + readExterior rows repeats i p slots lower ω))) = + HiddenBucketBias.exposedLaw W (scalarLaw repeats i p slots) + (exteriorLaw rows repeats i p slots lower hne) := by + have hread (ω : Tape rows repeats (.step i p) slots) : + exterior rows repeats i p slots lower hne (split rows repeats i p slots W ω).2.2 = + readExterior rows repeats i p slots lower ω := + exterior_read_splitRoot rows repeats i p slots lower hne ω + simpa only [hread, exteriorLaw] using + split_readout_law rows repeats i p slots W (exterior rows repeats i p slots lower hne) + +end +end PerfectCompleteness.WholeArrayExteriorLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/WholeArrayHiddenLaw.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/WholeArrayHiddenLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..34407c6f949f94472c25005bec4a4002e2a2eea6 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/WholeArrayHiddenLaw.lean @@ -0,0 +1,226 @@ +import OAI.Computability.PerfectCompleteness.Construction.HiddenBucketBias +import OAI.Computability.PerfectCompleteness.Foundations.QuarterBalanceLemmas +import OAI.Computability.PerfectCompleteness.Sampling.RationalFiniteLawLemmas +import OAI.Computability.PerfectCompleteness.Sampling.WholeArraySampler + +namespace OAI + +section + +namespace PerfectCompleteness.WholeArrayHiddenLaw + +open scoped BigOperators Classical +open UniqueGamesTheorem.Foundations.Games +open TreeSourceSpaces HierarchicalArrays DescendantSpaces WholeArraySampler + +noncomputable section + +theorem product_assoc_pushforward {A B C : Type*} + [Fintype A] [Fintype B] [Fintype C] + (μ : FiniteDistribution A) (ν : FiniteDistribution B) (ρ : FiniteDistribution C) : + ((μ.product ν).product ρ).pushforward (fun z => (z.1.1, (z.1.2, z.2))) = + μ.product (ν.product ρ) := by + change ((μ.product ν).product ρ).pushforward (Equiv.prodAssoc A B C) = _ + rw [← FiniteDistribution.transport_eq_pushforward] + apply FiniteDistribution.eq_of_weight_eq + rintro ⟨a, b, c⟩ + exact mul_assoc _ _ _ + +theorem product_split_first {A B C D : Type*} + [Fintype A] [Fintype B] [Fintype C] [Fintype D] + (μ : FiniteDistribution A) (ν : FiniteDistribution B) + (hidden : FiniteDistribution C) (visible : FiniteDistribution D) + (split : A → C × D) (hsplit : μ.pushforward split = hidden.product visible) : + (μ.product ν).pushforward (fun z => ((split z.1).1, ((split z.1).2, z.2))) = + hidden.product (visible.product ν) := by + calc + _ = ((μ.product ν).pushforward (fun z => (split z.1, z.2))).pushforward + (fun z => (z.1.1, (z.1.2, z.2))) := by + rw [FiniteDistribution.pushforward_comp] + _ = (((μ.pushforward split).product (ν.pushforward id))).pushforward + (fun z => (z.1.1, (z.1.2, z.2))) := by + have hmap : (μ.product ν).pushforward (fun z => (split z.1, z.2)) = + (μ.pushforward split).product (ν.pushforward id) := by + simpa only [id_eq] using + FiniteDistribution.product_pushforward μ ν split (id : B → B) + rw [hmap] + _ = ((hidden.product visible).product ν).pushforward + (fun z => (z.1.1, (z.1.2, z.2))) := by + rw [hsplit, FiniteDistribution.pushforward_id] + _ = _ := product_assoc_pushforward hidden visible ν + +theorem product_read_second {A B C : Type*} + [Fintype A] [Fintype B] [Fintype C] + (μ : FiniteDistribution A) (ν : FiniteDistribution B) (read : B → C) : + (μ.product ν).pushforward (fun z => (z.1, read z.2)) = + μ.product (ν.pushforward read) := by + simpa only [id_eq, FiniteDistribution.pushforward_id] using + FiniteDistribution.product_pushforward μ ν (id : A → A) read + +variable {branch : Nat → Nat} {n m t : Nat} + +abbrev RestIndex (i : Fin (branch n)) := + {k : StepIndex i // k ≠ Sum.inl ()} + +abbrev Factor (rows repeats : Nat → Nat) (i : Fin (branch n)) (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) := + StepFactor (i := i) (RootTape rows repeats (.step i p) slots) + (Tape rows repeats p (childSlots slots i)) + (fun j => Arrays (childSlots slots j.val) rows) + +instance factorFintype (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) : + (k : StepIndex i) → Fintype (Factor rows repeats i p slots k) := + fun k => WholeArraySampler.stepFactorFintype _ _ _ k + +abbrev RestTape (rows repeats : Nat → Nat) (i : Fin (branch n)) (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) := + (k : RestIndex i) → Factor rows repeats i p slots k.val + +instance restFactorFintype (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) : + (k : RestIndex i) → Fintype (Factor rows repeats i p slots k.val) := + fun k => factorFintype rows repeats i p slots k.val + +instance restTapeFintype (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) : + Fintype (RestTape rows repeats i p slots) := by + letI : (k : RestIndex i) → Fintype (Factor rows repeats i p slots k.val) := + fun k => factorFintype rows repeats i p slots k.val + change Fintype ((k : RestIndex i) → Factor rows repeats i p slots k.val) + infer_instance + +abbrev ScalarTape (repeats : Nat → Nat) (i : Fin (branch n)) (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) := + RecursiveSampler.Tape F2 repeats (.step i p) (LeafDomain slots) + +instance scalarTapeFintype (repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) : + Fintype (ScalarTape repeats i p slots) := by + letI : (j : RecursiveSampler.DrawIndex repeats (.step i p)) → + Fintype (RecursiveSampler.DrawSpace F2 repeats (.step i p) (LeafDomain slots) j) := + fun j => RecursiveSampler.drawSpaceFintype F2 repeats (.step i p) (LeafDomain slots) j + change Fintype ((j : RecursiveSampler.DrawIndex repeats (.step i p)) → + RecursiveSampler.DrawSpace F2 repeats (.step i p) (LeafDomain slots) j) + infer_instance + +def scalarLaw (repeats : Nat → Nat) (i : Fin (branch n)) (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) : + FiniteDistribution (ScalarTape repeats i p slots) := + RecursiveSampler.tapeLaw F2 repeats (.step i p) (LeafDomain slots) + +def restLaw (rows repeats : Nat → Nat) (i : Fin (branch n)) (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) : + FiniteDistribution (RestTape rows repeats i p slots) := by + letI : (k : RestIndex i) → Fintype (Factor rows repeats i p slots k.val) := + fun k => factorFintype rows repeats i p slots k.val + exact FiniteProduct.law + (Ω := fun k : RestIndex i => Factor rows repeats i p slots k.val) + (fun k : RestIndex i => componentLaw rows repeats i p slots k.val) + +def splitRoot (rows repeats : Nat → Nat) (i : Fin (branch n)) (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ω : Tape rows repeats (.step i p) slots) : + RootTape rows repeats (.step i p) slots × RestTape rows repeats i p slots := + (ω (.inl ()), fun k => ω k.val) + +theorem splitRoot_law (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) : + (WholeArraySampler.tapeLaw rows repeats (.step i p) slots).pushforward + (splitRoot rows repeats i p slots) = + (BucketSampler.tapeLaw (rows (n + 1)) (scalarLaw repeats i p slots)).product + (restLaw rows repeats i p slots) := by + let : (k : StepIndex i) → Fintype (Factor rows repeats i p slots k) := + fun k => WholeArraySampler.stepFactorFintype _ _ _ k + exact SourceCoordinateSplit.coordinate_split_pushforward + (Ω := fun k : StepIndex i => Factor rows repeats i p slots k) + (componentLaw rows repeats i p slots) + (Sum.inl ()) + +def split (rows repeats : Nat → Nat) (i : Fin (branch n)) (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (W : Submodule F2 (Fin (rows (n + 1)) → F2)) + (ω : Tape rows repeats (.step i p) slots) : + HiddenBucketBias.HiddenTape W (ScalarTape repeats i p slots) × + (HiddenBucketBias.VisibleTape W (ScalarTape repeats i p slots) × + RestTape rows repeats i p slots) := + ((HiddenBucketBias.splitTape W _ (ω (.inl ()))).1, + ((HiddenBucketBias.splitTape W _ (ω (.inl ()))).2, fun k => ω k.val)) + +theorem split_law (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (W : Submodule F2 (Fin (rows (n + 1)) → F2)) : + (WholeArraySampler.tapeLaw rows repeats (.step i p) slots).pushforward + (split rows repeats i p slots W) = + (HiddenBucketBias.hiddenTapeLaw W (scalarLaw repeats i p slots)).product + ((HiddenBucketBias.visibleTapeLaw W (scalarLaw repeats i p slots)).product + (restLaw rows repeats i p slots)) := by + let buckets := HiddenBucketBias.splitTape W (ScalarTape repeats i p slots) + calc + _ = ((WholeArraySampler.tapeLaw rows repeats (.step i p) slots).pushforward + (splitRoot rows repeats i p slots)).pushforward + (fun z => ((buckets z.1).1, ((buckets z.1).2, z.2))) := by + rw [FiniteDistribution.pushforward_comp] + apply congrArg (fun f : Tape rows repeats (.step i p) slots → + HiddenBucketBias.HiddenTape W (ScalarTape repeats i p slots) × + (HiddenBucketBias.VisibleTape W (ScalarTape repeats i p slots) × + RestTape rows repeats i p slots) => + (WholeArraySampler.tapeLaw rows repeats (.step i p) slots).pushforward f) + rfl + _ = _ := by + rw [splitRoot_law] + exact product_split_first _ _ _ _ buckets + (HiddenBucketBias.split_tapeLaw_pushforward W (scalarLaw repeats i p slots)) + +theorem split_readout_law {E : Type*} [Fintype E] + (rows repeats : Nat → Nat) (i : Fin (branch n)) (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (W : Submodule F2 (Fin (rows (n + 1)) → F2)) + (read : RestTape rows repeats i p slots → E) : + (WholeArraySampler.tapeLaw rows repeats (.step i p) slots).pushforward + (fun ω => ((split rows repeats i p slots W ω).1, + ((split rows repeats i p slots W ω).2.1, + read (split rows repeats i p slots W ω).2.2))) = + HiddenBucketBias.exposedLaw W (scalarLaw repeats i p slots) + ((restLaw rows repeats i p slots).pushforward read) := by + rw [← FiniteDistribution.pushforward_comp + (WholeArraySampler.tapeLaw rows repeats (.step i p) slots) + (split rows repeats i p slots W) + (fun z => (z.1, (z.2.1, read z.2.2))), split_law] + let μ := HiddenBucketBias.hiddenTapeLaw W (scalarLaw repeats i p slots) + let ν := HiddenBucketBias.visibleTapeLaw W (scalarLaw repeats i p slots) + let ρ := restLaw rows repeats i p slots + have inner : + (ν.product ρ).pushforward + (fun z : HiddenBucketBias.VisibleTape W (ScalarTape repeats i p slots) × + RestTape rows repeats i p slots => (z.1, read z.2)) = + ν.product (ρ.pushforward read) := + product_read_second ν ρ read + have outer : + (μ.product (ν.product ρ)).pushforward + (fun z : HiddenBucketBias.HiddenTape W (ScalarTape repeats i p slots) × + (HiddenBucketBias.VisibleTape W (ScalarTape repeats i p slots) × + RestTape rows repeats i p slots) => (z.1, (z.2.1, read z.2.2))) = + μ.product ((ν.product ρ).pushforward + (fun z : HiddenBucketBias.VisibleTape W (ScalarTape repeats i p slots) × + RestTape rows repeats i p slots => (z.1, read z.2))) := + product_read_second μ (ν.product ρ) + (fun z : HiddenBucketBias.VisibleTape W (ScalarTape repeats i p slots) × + RestTape rows repeats i p slots => (z.1, read z.2)) + exact outer.trans (congrArg + (fun θ : FiniteDistribution + (HiddenBucketBias.VisibleTape W (ScalarTape repeats i p slots) × E) => μ.product θ) + inner) + +end +end PerfectCompleteness.WholeArrayHiddenLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/WholeArrayInteriorHiddenLaw.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/WholeArrayInteriorHiddenLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..afb619befe9ce5e8441b923e88cb7bcc86649c29 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/WholeArrayInteriorHiddenLaw.lean @@ -0,0 +1,206 @@ +import Mathlib.Tactic.Ring +import OAI.Computability.PerfectCompleteness.Foundations.WholeArraySubtreeSplit +import OAI.Computability.PerfectCompleteness.Sampling.WholeArrayHiddenLaw + +namespace OAI + +section + +namespace PerfectCompleteness.WholeArrayInteriorHiddenLaw + +open TreeSourceSpaces HierarchicalArrays DescendantSpaces WholeArraySampler +open WholeArraySubtreeSplit +open UniqueGamesTheorem.Foundations.Games +open scoped Classical + +noncomputable section + +private def reorder (A H V R : Type*) : + A × (H × (V × R)) ≃ H × (V × (A × R)) where + toFun z := (z.2.1, (z.2.2.1, (z.1, z.2.2.2))) + invFun z := (z.2.2.1, (z.1, (z.2.1, z.2.2.2))) + left_inv _ := rfl + right_inv _ := rfl + +private theorem product_reorder {A H V R : Type*} + [Fintype A] [Fintype H] [Fintype V] [Fintype R] + (μ : FiniteDistribution A) (hidden : FiniteDistribution H) + (visible : FiniteDistribution V) (rest : FiniteDistribution R) : + (μ.product (hidden.product (visible.product rest))).pushforward (reorder A H V R) = + hidden.product (visible.product (μ.product rest)) := by + rw [← FiniteDistribution.transport_eq_pushforward] + apply FiniteDistribution.eq_of_weight_eq + rintro ⟨h, v, a, r⟩ + change μ.weight a * (hidden.weight h * (visible.weight v * rest.weight r)) = + hidden.weight h * (visible.weight v * (μ.weight a * rest.weight r)) + ring + +private theorem product_split_second {A B H V R : Type*} + [Fintype A] [Fintype B] [Fintype H] [Fintype V] [Fintype R] + (μ : FiniteDistribution A) (ν : FiniteDistribution B) + (hidden : FiniteDistribution H) (visible : FiniteDistribution V) + (rest : FiniteDistribution R) (split : B → H × (V × R)) + (hsplit : ν.pushforward split = hidden.product (visible.product rest)) : + (μ.product ν).pushforward + (fun z => ((split z.2).1, ((split z.2).2.1, (z.1, (split z.2).2.2)))) = + hidden.product (visible.product (μ.product rest)) := by + calc + _ = ((μ.product ν).pushforward (fun z => (z.1, split z.2))).pushforward + (reorder A H V R) := by + rw [FiniteDistribution.pushforward_comp] + rfl + _ = (μ.product (ν.pushforward split)).pushforward (reorder A H V R) := by + rw [WholeArrayHiddenLaw.product_read_second] + _ = _ := by + rw [hsplit] + exact product_reorder μ hidden visible rest + +variable {branch : Nat → Nat} {N n m t : Nat} + +abbrev ScalarTape (repeats : Nat → Nat) (p : Path branch N (n + 1)) + (i : Fin (branch n)) (q : Path branch n m) + (slots : RecursiveSpaces.Slots branch N → Fin t → MixedSupport.Slot) := + WholeArrayHiddenLaw.ScalarTape repeats i q (subtreeSlots p slots) + +abbrev Exterior (rows repeats : Nat → Nat) (p : Path branch N (n + 1)) + (i : Fin (branch n)) (q : Path branch n m) + (slots : RecursiveSpaces.Slots branch N → Fin t → MixedSupport.Slot) := + Complement rows repeats p (.step i q) slots × + WholeArrayHiddenLaw.RestTape rows repeats i q (subtreeSlots p slots) + +def scalarLaw (repeats : Nat → Nat) (p : Path branch N (n + 1)) + (i : Fin (branch n)) (q : Path branch n m) + (slots : RecursiveSpaces.Slots branch N → Fin t → MixedSupport.Slot) : + FiniteDistribution (ScalarTape repeats p i q slots) := + WholeArrayHiddenLaw.scalarLaw repeats i q (subtreeSlots p slots) + +def exteriorLaw (rows repeats : Nat → Nat) (p : Path branch N (n + 1)) + (i : Fin (branch n)) (q : Path branch n m) + (slots : RecursiveSpaces.Slots branch N → Fin t → MixedSupport.Slot) : + FiniteDistribution (Exterior rows repeats p i q slots) := + (complementLaw rows repeats p (.step i q) slots).product + (WholeArrayHiddenLaw.restLaw rows repeats i q (subtreeSlots p slots)) + +def split (rows repeats : Nat → Nat) (p : Path branch N (n + 1)) + (i : Fin (branch n)) (q : Path branch n m) + (slots : RecursiveSpaces.Slots branch N → Fin t → MixedSupport.Slot) + (W : Submodule F2 (Fin (rows (n + 1)) → F2)) + (ω : Tape rows repeats (p.append (.step i q)) slots) : + HiddenBucketBias.HiddenTape W (ScalarTape repeats p i q slots) × + (HiddenBucketBias.VisibleTape W (ScalarTape repeats p i q slots) × + Exterior rows repeats p i q slots) := + let subtree := splitEquiv rows repeats p (.step i q) slots ω + let buckets := WholeArrayHiddenLaw.split rows repeats i q (subtreeSlots p slots) W subtree.2 + (buckets.1, (buckets.2.1, (subtree.1, buckets.2.2))) + +theorem split_hidden (rows repeats : Nat → Nat) (p : Path branch N (n + 1)) + (i : Fin (branch n)) (q : Path branch n m) + (slots : RecursiveSpaces.Slots branch N → Fin t → MixedSupport.Slot) + (W : Submodule F2 (Fin (rows (n + 1)) → F2)) + (ω : Tape rows repeats (p.append (.step i q)) slots) : + (split rows repeats p i q slots W ω).1 = + (WholeArrayHiddenLaw.split rows repeats i q (subtreeSlots p slots) W + (extract rows repeats p (.step i q) slots ω)).1 := rfl + +theorem split_law (rows repeats : Nat → Nat) (p : Path branch N (n + 1)) + (i : Fin (branch n)) (q : Path branch n m) + (slots : RecursiveSpaces.Slots branch N → Fin t → MixedSupport.Slot) + (W : Submodule F2 (Fin (rows (n + 1)) → F2)) : + (WholeArraySampler.tapeLaw rows repeats (p.append (.step i q)) slots).pushforward + (split rows repeats p i q slots W) = + (HiddenBucketBias.hiddenTapeLaw W (scalarLaw repeats p i q slots)).product + ((HiddenBucketBias.visibleTapeLaw W (scalarLaw repeats p i q slots)).product + (exteriorLaw rows repeats p i q slots)) := by + let localSplit := WholeArrayHiddenLaw.split rows repeats i q (subtreeSlots p slots) W + calc + _ = ((WholeArraySampler.tapeLaw rows repeats (p.append (.step i q)) slots).pushforward + (splitEquiv rows repeats p (.step i q) slots)).pushforward + (fun z => ((localSplit z.2).1, ((localSplit z.2).2.1, (z.1, (localSplit z.2).2.2)))) := by + rw [FiniteDistribution.pushforward_comp] + rfl + _ = _ := by + rw [WholeArraySubtreeSplit.splitEquiv_tapeLaw] + exact product_split_second + (complementLaw rows repeats p (.step i q) slots) + (WholeArraySampler.tapeLaw rows repeats (.step i q) (subtreeSlots p slots)) + (HiddenBucketBias.hiddenTapeLaw W (scalarLaw repeats p i q slots)) + (HiddenBucketBias.visibleTapeLaw W (scalarLaw repeats p i q slots)) + (WholeArrayHiddenLaw.restLaw rows repeats i q (subtreeSlots p slots)) localSplit + (WholeArrayHiddenLaw.split_law rows repeats i q (subtreeSlots p slots) W) + +theorem hidden_marginal (rows repeats : Nat → Nat) (p : Path branch N (n + 1)) + (i : Fin (branch n)) (q : Path branch n m) + (slots : RecursiveSpaces.Slots branch N → Fin t → MixedSupport.Slot) + (W : Submodule F2 (Fin (rows (n + 1)) → F2)) : + (WholeArraySampler.tapeLaw rows repeats (p.append (.step i q)) slots).pushforward + (fun ω => (split rows repeats p i q slots W ω).1) = + HiddenBucketBias.hiddenTapeLaw W (scalarLaw repeats p i q slots) := by + rw [← FiniteDistribution.pushforward_comp + (WholeArraySampler.tapeLaw rows repeats (p.append (.step i q)) slots) + (split rows repeats p i q slots W) Prod.fst, split_law, HiddenBucketBias.product_fst] + +theorem split_readout_law {E : Type*} [Fintype E] + (rows repeats : Nat → Nat) (p : Path branch N (n + 1)) + (i : Fin (branch n)) (q : Path branch n m) + (slots : RecursiveSpaces.Slots branch N → Fin t → MixedSupport.Slot) + (W : Submodule F2 (Fin (rows (n + 1)) → F2)) + (read : Exterior rows repeats p i q slots → E) : + (WholeArraySampler.tapeLaw rows repeats (p.append (.step i q)) slots).pushforward + (fun ω => ((split rows repeats p i q slots W ω).1, + ((split rows repeats p i q slots W ω).2.1, + read (split rows repeats p i q slots W ω).2.2))) = + HiddenBucketBias.exposedLaw W (scalarLaw repeats p i q slots) + ((exteriorLaw rows repeats p i q slots).pushforward read) := by + rw [← FiniteDistribution.pushforward_comp + (WholeArraySampler.tapeLaw rows repeats (p.append (.step i q)) slots) + (split rows repeats p i q slots W) + (fun z => (z.1, (z.2.1, read z.2.2))), split_law] + let μ := HiddenBucketBias.hiddenTapeLaw W (scalarLaw repeats p i q slots) + let ν := HiddenBucketBias.visibleTapeLaw W (scalarLaw repeats p i q slots) + let ρ := exteriorLaw rows repeats p i q slots + have inner : + (ν.product ρ).pushforward + (fun z : HiddenBucketBias.VisibleTape W (ScalarTape repeats p i q slots) × + Exterior rows repeats p i q slots => (z.1, read z.2)) = + ν.product (ρ.pushforward read) := + WholeArrayHiddenLaw.product_read_second ν ρ read + have outer : + (μ.product (ν.product ρ)).pushforward + (fun z : HiddenBucketBias.HiddenTape W (ScalarTape repeats p i q slots) × + (HiddenBucketBias.VisibleTape W (ScalarTape repeats p i q slots) × + Exterior rows repeats p i q slots) => (z.1, (z.2.1, read z.2.2))) = + μ.product ((ν.product ρ).pushforward + (fun z : HiddenBucketBias.VisibleTape W (ScalarTape repeats p i q slots) × + Exterior rows repeats p i q slots => (z.1, read z.2))) := + WholeArrayHiddenLaw.product_read_second μ (ν.product ρ) + (fun z : HiddenBucketBias.VisibleTape W (ScalarTape repeats p i q slots) × + Exterior rows repeats p i q slots => (z.1, read z.2)) + exact outer.trans (congrArg + (fun θ : FiniteDistribution + (HiddenBucketBias.VisibleTape W (ScalarTape repeats p i q slots) × E) => μ.product θ) + inner) + +theorem split_observation_law {E : Type*} [Fintype E] + (rows repeats : Nat → Nat) (p : Path branch N (n + 1)) + (i : Fin (branch n)) (q : Path branch n m) + (slots : RecursiveSpaces.Slots branch N → Fin t → MixedSupport.Slot) + (W : Submodule F2 (Fin (rows (n + 1)) → F2)) + (read : HiddenBucketBias.VisibleTape W (ScalarTape repeats p i q slots) × + Exterior rows repeats p i q slots → E) : + (WholeArraySampler.tapeLaw rows repeats (p.append (.step i q)) slots).pushforward + (fun ω => ((split rows repeats p i q slots W ω).1, + read (split rows repeats p i q slots W ω).2)) = + (HiddenBucketBias.hiddenTapeLaw W (scalarLaw repeats p i q slots)).product + (((HiddenBucketBias.visibleTapeLaw W (scalarLaw repeats p i q slots)).product + (exteriorLaw rows repeats p i q slots)).pushforward read) := by + rw [← FiniteDistribution.pushforward_comp + (WholeArraySampler.tapeLaw rows repeats (p.append (.step i q)) slots) + (split rows repeats p i q slots W) (fun z => (z.1, read z.2)), split_law] + exact WholeArrayHiddenLaw.product_read_second _ _ read + +end +end PerfectCompleteness.WholeArrayInteriorHiddenLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/WholeArrayProductLaw.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/WholeArrayProductLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..6022e961bce4a64165c11137cb5f2db527393068 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/WholeArrayProductLaw.lean @@ -0,0 +1,247 @@ +import Mathlib.Algebra.BigOperators.GroupWithZero.Finset +import OAI.Computability.PerfectCompleteness.Sampling.WholeArraySampler + +namespace OAI + +section + +namespace PerfectCompleteness.WholeArrayProductLaw + +open TreeSourceSpaces HierarchicalArrays DescendantSpaces WholeArraySampler +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +noncomputable section + +variable {branch : Nat → Nat} {n m t : Nat} + +abbrev NodeArray + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (rows : Nat → Nat) (node : Nodes branch n) := + Fin (rows (Nodes.height node)) → H (nodeSlots slots node) + +def nodeLaw (rows repeats : Nat → Nat) (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (node : Nodes branch n) : FiniteDistribution (NodeArray slots rows node) := + (WholeArraySampler.tapeLaw rows repeats p slots).pushforward + (fun ω => WholeArraySampler.evaluate rows repeats p slots ω node) + +theorem nodeLaw_refl (rows repeats : Nat → Nat) + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (node : Nodes branch n) : + nodeLaw rows repeats (.refl n) slots node = + FiniteDistribution.uniform (NodeArray slots rows node) := + WholeArraySampler.uniform_arrays_node slots rows node + +theorem nodeLaw_root (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) : + nodeLaw rows repeats (.step i p) slots (.inl ()) = + BucketSampler.law (rows (n + 1)) + (RecursiveSampler.tapeLaw F2 repeats (.step i p) (LeafDomain slots)) + (RecursiveSampler.evaluate F2 repeats (.step i p) (LeafDomain slots)) := + WholeArraySampler.root_array_marginal rows repeats i p slots + +theorem nodeLaw_selected (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (node : Nodes branch n) : + nodeLaw rows repeats (.step i p) slots (.inr (i, node)) = + nodeLaw rows repeats p (childSlots slots i) node := by + unfold nodeLaw + simp only [WholeArraySampler.evaluate_selected] + exact WholeArraySampler.component_image rows repeats i p slots (.inr (.inl ())) + (fun ω => WholeArraySampler.evaluate rows repeats p (childSlots slots i) ω node) + +theorem nodeLaw_ordinary (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (j : RecursiveSampler.OffPath i) (node : Nodes branch n) : + nodeLaw rows repeats (.step i p) slots (.inr (j.val, node)) = + FiniteDistribution.uniform (NodeArray (childSlots slots j.val) rows node) := + WholeArraySampler.ordinary_node_marginal rows repeats i p slots j node + +theorem prod_nodes (i : Fin (branch n)) (f : Nodes branch (n + 1) → ℝ) : + (∏ node, f node) = f (.inl ()) * + ((∏ node : Nodes branch n, f (.inr (i, node))) * + ∏ j : RecursiveSampler.OffPath i, ∏ node : Nodes branch n, f (.inr (j.val, node))) := by + let g : Unit ⊕ (Fin (branch n) × Nodes branch n) → ℝ := f + change (∏ node : Unit ⊕ (Fin (branch n) × Nodes branch n), g node) = g (.inl ()) * + ((∏ node : Nodes branch n, g (.inr (i, node))) * + ∏ j : RecursiveSampler.OffPath i, ∏ node : Nodes branch n, g (.inr (j.val, node))) + rw [Fintype.prod_sum_type, Fintype.prod_prod_type] + simp only [Fintype.prod_unique] + rw [Fintype.prod_eq_mul_prod_subtype_ne + (fun j : Fin (branch n) => ∏ node : Nodes branch n, g (.inr (j, node))) i] + +theorem prod_stepIndex (i : Fin (branch n)) (f : StepIndex i → ℝ) : + (∏ k, f k) = f (.inl ()) * + (f (.inr (.inl ())) * ∏ j : RecursiveSampler.OffPath i, f (.inr (.inr j))) := by + change (∏ k : Unit ⊕ (Unit ⊕ RecursiveSampler.OffPath i), f k) = _ + simp only [Fintype.prod_sum_type, Fintype.prod_unique] + +def stepObservable (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (f : (node : Nodes branch (n + 1)) → NodeArray slots rows node → ℝ) : + (k : StepIndex i) → StepFactor (RootTape rows repeats (.step i p) slots) + (Tape rows repeats p (childSlots slots i)) + (fun j => Arrays (childSlots slots j.val) rows) k → ℝ + | .inl _, ω => f (.inl ()) + (BucketSampler.recursiveEvaluate (rows (n + 1)) repeats (.step i p) (LeafDomain slots) ω) + | .inr (.inl _), ω => + ∏ node : Nodes branch n, f (.inr (i, node)) + (WholeArraySampler.evaluate rows repeats p (childSlots slots i) ω node) + | .inr (.inr j), arrays => + ∏ node : Nodes branch n, f (.inr (j.val, node)) (arrays node) + +theorem prod_evaluate_step (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (f : (node : Nodes branch (n + 1)) → NodeArray slots rows node → ℝ) + (ω : Tape rows repeats (.step i p) slots) : + (∏ node, f node (WholeArraySampler.evaluate rows repeats (.step i p) slots ω node)) = + ∏ k : StepIndex i, stepObservable rows repeats i p slots f k (ω k) := by + rw [prod_nodes i, prod_stepIndex i] + simp only [WholeArraySampler.evaluate_root, WholeArraySampler.evaluate_selected, + WholeArraySampler.evaluate_ordinary, stepObservable] + +theorem tape_expectation_product (rows repeats : Nat → Nat) (p : Path branch n m) : + ∀ (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (f : (node : Nodes branch n) → NodeArray slots rows node → ℝ), + (WholeArraySampler.tapeLaw rows repeats p slots).expectation + (fun ω => ∏ node, f node (WholeArraySampler.evaluate rows repeats p slots ω node)) = + ∏ node, (nodeLaw rows repeats p slots node).expectation (f node) := by + induction p with + | refl n => + intro slots f + calc + _ = (FiniteDistribution.uniform (Arrays slots rows)).expectation + (fun arrays => ∏ node, f node (arrays node)) := rfl + _ = ∏ node, (FiniteDistribution.uniform + (Fin (rows (Nodes.height node)) → H (nodeSlots slots node))).expectation (f node) := + WholeArraySampler.uniform_arrays_expectation_product slots rows f + _ = _ := by + apply Finset.prod_congr rfl + intro node _ + exact congrArg + (fun μ : FiniteDistribution (NodeArray slots rows node) => μ.expectation (f node)) + (nodeLaw_refl rows repeats slots node).symm + | @step n m i p ih => + intro slots f + calc + _ = (WholeArraySampler.tapeLaw rows repeats (.step i p) slots).expectation + (fun ω => ∏ k : StepIndex i, stepObservable rows repeats i p slots f k (ω k)) := + FiniteDistribution.expectation_congr _ (prod_evaluate_step rows repeats i p slots f) + _ = ∏ k : StepIndex i, (componentLaw rows repeats i p slots k).expectation + (stepObservable rows repeats i p slots f k) := + WholeArraySampler.components_expectation_product rows repeats i p slots _ + _ = _ := by + let L : StepIndex i → ℝ := fun k => + (componentLaw rows repeats i p slots k).expectation + (stepObservable rows repeats i p slots f k) + let R : Nodes branch (n + 1) → ℝ := fun node => + (nodeLaw rows repeats (.step i p) slots node).expectation (f node) + have hroot : L (.inl ()) = R (.inl ()) := by + calc + _ = (BucketSampler.law (rows (n + 1)) + (RecursiveSampler.tapeLaw F2 repeats (.step i p) (LeafDomain slots)) + (RecursiveSampler.evaluate F2 repeats (.step i p) (LeafDomain slots))).expectation + (f (.inl ())) := + (FiniteDistribution.expectation_pushforward + (BucketSampler.recursiveTapeLaw (rows (n + 1)) repeats (.step i p) (LeafDomain slots)) + (BucketSampler.recursiveEvaluate (rows (n + 1)) repeats (.step i p) (LeafDomain slots)) + (f (.inl ()))).symm + _ = _ := congrArg + (fun μ : FiniteDistribution (NodeArray slots rows (.inl ())) => + μ.expectation (f (.inl ()))) (nodeLaw_root rows repeats i p slots).symm + have hselected : L (.inr (.inl ())) = + ∏ node : Nodes branch n, R (.inr (i, node)) := by + calc + _ = ∏ node : Nodes branch n, + (nodeLaw rows repeats p (childSlots slots i) node).expectation + (fun a : NodeArray (childSlots slots i) rows node => f (.inr (i, node)) a) := + ih (childSlots slots i) (fun node a => f (.inr (i, node)) a) + _ = _ := by + apply Finset.prod_congr rfl + intro node _ + exact congrArg + (fun μ : FiniteDistribution (NodeArray (childSlots slots i) rows node) => + μ.expectation (fun a => f (.inr (i, node)) a)) + (nodeLaw_selected rows repeats i p slots node).symm + have hordinary (j : RecursiveSampler.OffPath i) : L (.inr (.inr j)) = + ∏ node : Nodes branch n, R (.inr (j.val, node)) := by + calc + _ = ∏ node : Nodes branch n, + (FiniteDistribution.uniform + (NodeArray (childSlots slots j.val) rows node)).expectation + (fun a : NodeArray (childSlots slots j.val) rows node => f (.inr (j.val, node)) a) := + WholeArraySampler.uniform_arrays_expectation_product + (childSlots slots j.val) rows (fun node a => f (.inr (j.val, node)) a) + _ = _ := by + apply Finset.prod_congr rfl + intro node _ + exact congrArg + (fun μ : FiniteDistribution (NodeArray (childSlots slots j.val) rows node) => + μ.expectation (fun a => f (.inr (j.val, node)) a)) + (nodeLaw_ordinary rows repeats i p slots j node).symm + have hordinaryProd : (∏ j : RecursiveSampler.OffPath i, L (.inr (.inr j))) = + ∏ j : RecursiveSampler.OffPath i, ∏ node : Nodes branch n, R (.inr (j.val, node)) := + Finset.prod_congr rfl (fun j _ => hordinary j) + exact (prod_stepIndex i L).trans + ((congrArg₂ (fun a b : ℝ => a * b) hroot + (congrArg₂ (fun a b : ℝ => a * b) hselected hordinaryProd)).trans + (prod_nodes i R).symm) + +theorem eq_law_of_expectation_product {I : Type*} [Fintype I] [DecidableEq I] + {Ω : I → Type*} [∀ i, Fintype (Ω i)] + (μ : FiniteDistribution (∀ i, Ω i)) (P : ∀ i, FiniteDistribution (Ω i)) + (h : ∀ f : ∀ i, Ω i → ℝ, + μ.expectation (fun x => ∏ i, f i (x i)) = ∏ i, (P i).expectation (f i)) : + μ = FiniteProduct.law P := by + apply FiniteDistribution.eq_of_weight_eq + intro y + calc + μ.weight y = μ.expectation (fun x => if x = y then 1 else 0) := by + simp [FiniteDistribution.expectation, mul_ite] + _ = μ.expectation (fun x => ∏ i, if x i = y i then 1 else 0) := by + apply FiniteDistribution.expectation_congr + intro x + simp only [Fintype.prod_boole, funext_iff] + _ = ∏ i, (P i).expectation (fun a => if a = y i then 1 else 0) := + h (fun i a => if a = y i then (1 : ℝ) else 0) + _ = (FiniteProduct.law P).weight y := by + simp [FiniteProduct.law, FiniteDistribution.expectation, mul_ite] + +theorem law_eq_product (rows repeats : Nat → Nat) (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) : + WholeArraySampler.law rows repeats p slots = + FiniteProduct.law (nodeLaw rows repeats p slots) := by + apply eq_law_of_expectation_product + intro f + rw [WholeArraySampler.law, FiniteDistribution.expectation_pushforward] + exact tape_expectation_product rows repeats p slots f + +theorem node_marginal (rows repeats : Nat → Nat) (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (node : Nodes branch n) : + (WholeArraySampler.law rows repeats p slots).pushforward (fun arrays => arrays node) = + nodeLaw rows repeats p slots node := by + rw [law_eq_product] + exact FiniteProduct.eval_pushforward _ node + +theorem law_eq_product_marginals (rows repeats : Nat → Nat) (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) : + WholeArraySampler.law rows repeats p slots = + FiniteProduct.law (fun node : Nodes branch n => + (WholeArraySampler.law rows repeats p slots).pushforward (fun arrays => arrays node)) := by + simp only [node_marginal] + exact law_eq_product rows repeats p slots + +end + +end PerfectCompleteness.WholeArrayProductLaw + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/WholeArraySampler.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/WholeArraySampler.lean new file mode 100644 index 0000000000000000000000000000000000000000..571f3cae1a879fe73731cf189e9cb2cfa7cd843a --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/WholeArraySampler.lean @@ -0,0 +1,363 @@ +import OAI.Computability.PerfectCompleteness.Foundations.HierarchicalArrays +import OAI.Computability.PerfectCompleteness.Sampling.BucketSampler +import OAI.Computability.UniqueGames.Games.FinishBoundsLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.WholeArraySampler + +open TreeSourceSpaces HierarchicalArrays DescendantSpaces +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +noncomputable section + +variable {branch : Nat → Nat} {n m t : Nat} + +abbrev StepIndex (i : Fin (branch n)) := + Unit ⊕ (Unit ⊕ RecursiveSampler.OffPath i) + +def StepFactor {i : Fin (branch n)} (Root Selected : Type) + (Ordinary : RecursiveSampler.OffPath i → Type) : StepIndex i → Type + | .inl _ => Root + | .inr (.inl _) => Selected + | .inr (.inr j) => Ordinary j + +instance stepFactorFintype {i : Fin (branch n)} (Root Selected : Type) + (Ordinary : RecursiveSampler.OffPath i → Type) + [Fintype Root] [Fintype Selected] [∀ j, Fintype (Ordinary j)] + (k : StepIndex i) : Fintype (StepFactor Root Selected Ordinary k) := by + rcases k with _ | (_ | j) <;> dsimp only [StepFactor] <;> infer_instance + +abbrev StepTape {i : Fin (branch n)} (Root Selected : Type) + (Ordinary : RecursiveSampler.OffPath i → Type) := + (k : StepIndex i) → StepFactor Root Selected Ordinary k + +noncomputable instance spaceFintype + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) : + Fintype (H slots) := Fintype.ofFinite _ + +abbrev RootTape (rows repeats : Nat → Nat) (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) := + BucketSampler.RecursiveTape (rows n) repeats p (LeafDomain slots) + +def Tape (rows repeats : Nat → Nat) : + {n m : Nat} → Path branch n m → + (RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) → Type + | _, _, .refl _, slots => Arrays slots rows + | _, _, .step i p, slots => + StepTape (i := i) (RootTape rows repeats (.step i p) slots) + (Tape rows repeats p (childSlots slots i)) + (fun j => Arrays (childSlots slots j.val) rows) + +@[instance_reducible] def tapeFintypeAux (rows repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n m) → + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) → + Fintype (Tape rows repeats p slots) + | _, _, .refl _, slots => inferInstanceAs (Fintype (Arrays slots rows)) + | _, _, .step i p, slots => + letI : Fintype (Tape rows repeats p (childSlots slots i)) := + tapeFintypeAux rows repeats p (childSlots slots i) + letI : (k : StepIndex i) → Fintype + (StepFactor (RootTape rows repeats (.step i p) slots) + (Tape rows repeats p (childSlots slots i)) + (fun j => Arrays (childSlots slots j.val) rows) k) := + fun k => stepFactorFintype _ _ _ k + inferInstanceAs (Fintype + (StepTape (i := i) (RootTape rows repeats (.step i p) slots) + (Tape rows repeats p (childSlots slots i)) + (fun j => Arrays (childSlots slots j.val) rows))) + +instance tapeFintype (rows repeats : Nat → Nat) (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) : + Fintype (Tape rows repeats p slots) := tapeFintypeAux rows repeats p slots + +def zeroTape (rows repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n m) → + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) → + Tape rows repeats p slots + | _, _, .refl _, _ => fun _ _ => 0 + | _, _, .step i p, slots => fun k => + match k with + | .inl _ => fun _ => + RecursiveSampler.zeroTape F2 repeats (.step i p) (LeafDomain slots) + | .inr (.inl _) => zeroTape rows repeats p (childSlots slots i) + | .inr (.inr _) => fun _ _ => 0 + +instance tapeNonempty (rows repeats : Nat → Nat) (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) : + Nonempty (Tape rows repeats p slots) := ⟨zeroTape rows repeats p slots⟩ + +def leafTapeEquivUnit (rows repeats : Nat → Nat) + (slots : RecursiveSpaces.Slots branch 0 → Fin t → MixedSupport.Slot) : + Tape rows repeats (.refl 0) slots ≃ Unit where + toFun _ := () + invFun _ := fun node => nomatch node + left_inv ω := by + funext node + exact nomatch node + right_inv u := by cases u; rfl + +def assemble (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (rows : Nat → Nat) (root : Fin (rows (n + 1)) → H slots) + (children : ∀ j, Arrays (childSlots slots j) rows) : Arrays slots rows + | .inl _ => root + | .inr (j, node) => children j node + +def childrenAt (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (rows : Nat → Nat) (i : Fin (branch n)) + (selected : Arrays (childSlots slots i) rows) + (ordinary : ∀ j : RecursiveSampler.OffPath i, Arrays (childSlots slots j.val) rows) + (j : Fin (branch n)) : Arrays (childSlots slots j) rows := + if h : j = i then h.symm ▸ selected else ordinary ⟨j, h⟩ + +@[simp] theorem childrenAt_selected + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (rows : Nat → Nat) (i : Fin (branch n)) + (selected : Arrays (childSlots slots i) rows) + (ordinary : ∀ j : RecursiveSampler.OffPath i, Arrays (childSlots slots j.val) rows) : + childrenAt slots rows i selected ordinary i = selected := by simp [childrenAt] + +@[simp] theorem childrenAt_ordinary + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (rows : Nat → Nat) (i : Fin (branch n)) + (selected : Arrays (childSlots slots i) rows) + (ordinary : ∀ j : RecursiveSampler.OffPath i, Arrays (childSlots slots j.val) rows) + (j : RecursiveSampler.OffPath i) : + childrenAt slots rows i selected ordinary j.val = ordinary j := by + simp [childrenAt, j.property] + +def evaluate (rows repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n m) → + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) → + Tape rows repeats p slots → Arrays slots rows + | _, _, .refl _, _, ω => ω + | n + 1, _, .step i p, slots, ω => + assemble slots rows + (BucketSampler.recursiveEvaluate (rows (n + 1)) repeats (.step i p) + (LeafDomain slots) (ω (.inl ()))) + (childrenAt slots rows i + (evaluate rows repeats p (childSlots slots i) (ω (.inr (.inl ())))) + (fun j => ω (.inr (.inr j)))) + +@[simp] theorem evaluate_refl (rows repeats : Nat → Nat) + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (ω : Tape rows repeats (.refl n) slots) : + evaluate rows repeats (.refl n) slots ω = ω := rfl + +@[simp] theorem evaluate_root (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ω : Tape rows repeats (.step i p) slots) : + evaluate rows repeats (.step i p) slots ω (.inl ()) = + BucketSampler.recursiveEvaluate (rows (n + 1)) repeats (.step i p) + (LeafDomain slots) (ω (.inl ())) := rfl + +@[simp] theorem evaluate_selected (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ω : Tape rows repeats (.step i p) slots) (node : Nodes branch n) : + evaluate rows repeats (.step i p) slots ω (.inr (i, node)) = + evaluate rows repeats p (childSlots slots i) (ω (.inr (.inl ()))) node := by + exact congrFun (childrenAt_selected slots rows i + (evaluate rows repeats p (childSlots slots i) (ω (.inr (.inl ())))) + (fun j => ω (.inr (.inr j)))) node + +@[simp] theorem evaluate_ordinary (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (ω : Tape rows repeats (.step i p) slots) (j : RecursiveSampler.OffPath i) + (node : Nodes branch n) : + evaluate rows repeats (.step i p) slots ω (.inr (j.val, node)) = + ω (.inr (.inr j)) node := by + exact congrFun (childrenAt_ordinary slots rows i + (evaluate rows repeats p (childSlots slots i) (ω (.inr (.inl ())))) + (fun j => ω (.inr (.inr j))) j) node + +def tapeLaw (rows repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n m) → + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) → + FiniteDistribution (Tape rows repeats p slots) + | _, _, .refl _, slots => FiniteDistribution.uniform (Arrays slots rows) + | n + 1, _, .step i p, slots => by + letI : (k : StepIndex i) → Fintype + (StepFactor (RootTape rows repeats (.step i p) slots) + (Tape rows repeats p (childSlots slots i)) + (fun j => Arrays (childSlots slots j.val) rows) k) := + fun k => stepFactorFintype _ _ _ k + exact FiniteProduct.law + (Ω := fun k : StepIndex i => StepFactor (RootTape rows repeats (.step i p) slots) + (Tape rows repeats p (childSlots slots i)) + (fun j => Arrays (childSlots slots j.val) rows) k) + (fun k : StepIndex i => match k with + | .inl _ => BucketSampler.recursiveTapeLaw (rows (n + 1)) repeats (.step i p) + (LeafDomain slots) + | .inr (.inl _) => tapeLaw rows repeats p (childSlots slots i) + | .inr (.inr j) => FiniteDistribution.uniform (Arrays (childSlots slots j.val) rows)) + +def componentLaw (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) : + (k : StepIndex i) → FiniteDistribution + (StepFactor (RootTape rows repeats (.step i p) slots) + (Tape rows repeats p (childSlots slots i)) + (fun j => Arrays (childSlots slots j.val) rows) k) + | .inl _ => BucketSampler.recursiveTapeLaw (rows (n + 1)) repeats (.step i p) + (LeafDomain slots) + | .inr (.inl _) => tapeLaw rows repeats p (childSlots slots i) + | .inr (.inr j) => FiniteDistribution.uniform (Arrays (childSlots slots j.val) rows) + +theorem component_marginal (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (k : StepIndex i) : + (tapeLaw rows repeats (.step i p) slots).pushforward (fun ω => ω k) = + componentLaw rows repeats i p slots k := by + let : (k : StepIndex i) → Fintype + (StepFactor (RootTape rows repeats (.step i p) slots) + (Tape rows repeats p (childSlots slots i)) + (fun j => Arrays (childSlots slots j.val) rows) k) := + fun k => stepFactorFintype _ _ _ k + exact FiniteProduct.eval_pushforward (componentLaw rows repeats i p slots) k + +theorem component_image (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (k : StepIndex i) {Y : Type*} [Fintype Y] + (f : StepFactor (RootTape rows repeats (.step i p) slots) + (Tape rows repeats p (childSlots slots i)) + (fun j => Arrays (childSlots slots j.val) rows) k → Y) : + (tapeLaw rows repeats (.step i p) slots).pushforward (fun ω => f (ω k)) = + (componentLaw rows repeats i p slots k).pushforward f := by + rw [← FiniteDistribution.pushforward_comp + (tapeLaw rows repeats (.step i p) slots) (fun ω => ω k) f, + component_marginal] + +theorem components_independent (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (k l : StepIndex i) (hne : k ≠ l) + (f : StepFactor (RootTape rows repeats (.step i p) slots) + (Tape rows repeats p (childSlots slots i)) + (fun j => Arrays (childSlots slots j.val) rows) k → ℝ) + (g : StepFactor (RootTape rows repeats (.step i p) slots) + (Tape rows repeats p (childSlots slots i)) + (fun j => Arrays (childSlots slots j.val) rows) l → ℝ) : + (tapeLaw rows repeats (.step i p) slots).expectation (fun ω => f (ω k) * g (ω l)) = + (componentLaw rows repeats i p slots k).expectation f * + (componentLaw rows repeats i p slots l).expectation g := by + let : (k : StepIndex i) → Fintype + (StepFactor (RootTape rows repeats (.step i p) slots) + (Tape rows repeats p (childSlots slots i)) + (fun j => Arrays (childSlots slots j.val) rows) k) := + fun k => stepFactorFintype _ _ _ k + exact FiniteProduct.expectation_eval_mul (componentLaw rows repeats i p slots) k l hne f g + +theorem components_expectation_product (rows repeats : Nat → Nat) + (i : Fin (branch n)) (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (f : (k : StepIndex i) → StepFactor (RootTape rows repeats (.step i p) slots) + (Tape rows repeats p (childSlots slots i)) + (fun j => Arrays (childSlots slots j.val) rows) k → ℝ) : + (tapeLaw rows repeats (.step i p) slots).expectation (fun ω => ∏ k, f k (ω k)) = + ∏ k, (componentLaw rows repeats i p slots k).expectation (f k) := by + let : (k : StepIndex i) → Fintype + (StepFactor (RootTape rows repeats (.step i p) slots) + (Tape rows repeats p (childSlots slots i)) + (fun j => Arrays (childSlots slots j.val) rows) k) := + fun k => stepFactorFintype _ _ _ k + exact FiniteProduct.expectation_product (componentLaw rows repeats i p slots) f + +def law (rows repeats : Nat → Nat) (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) : + FiniteDistribution (Arrays slots rows) := + (tapeLaw rows repeats p slots).pushforward (evaluate rows repeats p slots) + +theorem probability_law (rows repeats : Nat → Nat) (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (event : Arrays slots rows → Bool) : + (law rows repeats p slots).probability event = + (tapeLaw rows repeats p slots).probability + (fun ω => event (evaluate rows repeats p slots ω)) := + FiniteDistribution.probability_pushforward _ _ _ + +theorem root_array_marginal (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) : + (tapeLaw rows repeats (.step i p) slots).pushforward + (fun ω => evaluate rows repeats (.step i p) slots ω (.inl ())) = + BucketSampler.law (rows (n + 1)) + (RecursiveSampler.tapeLaw F2 repeats (.step i p) (LeafDomain slots)) + (RecursiveSampler.evaluate F2 repeats (.step i p) (LeafDomain slots)) := + component_image rows repeats i p slots (.inl ()) + (BucketSampler.recursiveEvaluate (rows (n + 1)) repeats (.step i p) (LeafDomain slots)) + +theorem selected_arrays_marginal (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) : + (tapeLaw rows repeats (.step i p) slots).pushforward + (fun ω node => evaluate rows repeats (.step i p) slots ω (.inr (i, node))) = + law rows repeats p (childSlots slots i) := by + simp only [evaluate_selected] + exact component_image rows repeats i p slots (.inr (.inl ())) + (evaluate rows repeats p (childSlots slots i)) + +theorem uniform_arrays_eq_product + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (rows : Nat → Nat) : + FiniteDistribution.uniform (Arrays slots rows) = + FiniteProduct.law (fun node : Nodes branch n => + FiniteDistribution.uniform (Fin (rows (Nodes.height node)) → H (nodeSlots slots node))) := + UniformLinearImage.law_uniform.symm + +theorem uniform_arrays_node + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (rows : Nat → Nat) (node : Nodes branch n) : + (FiniteDistribution.uniform (Arrays slots rows)).pushforward (fun arrays => arrays node) = + FiniteDistribution.uniform (Fin (rows (Nodes.height node)) → H (nodeSlots slots node)) := by + rw [uniform_arrays_eq_product] + exact FiniteProduct.eval_pushforward _ node + +theorem uniform_arrays_expectation_product + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (rows : Nat → Nat) + (f : (node : Nodes branch n) → + (Fin (rows (Nodes.height node)) → H (nodeSlots slots node)) → ℝ) : + (FiniteDistribution.uniform (Arrays slots rows)).expectation + (fun arrays => ∏ node, f node (arrays node)) = + ∏ node, (FiniteDistribution.uniform + (Fin (rows (Nodes.height node)) → H (nodeSlots slots node))).expectation (f node) := by + rw [uniform_arrays_eq_product] + exact FiniteProduct.expectation_product _ f + +theorem ordinary_node_marginal (rows repeats : Nat → Nat) (i : Fin (branch n)) + (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (j : RecursiveSampler.OffPath i) (node : Nodes branch n) : + (tapeLaw rows repeats (.step i p) slots).pushforward + (fun ω => evaluate rows repeats (.step i p) slots ω (.inr (j.val, node))) = + FiniteDistribution.uniform + (Fin (rows (Nodes.height node)) → H (nodeSlots (childSlots slots j.val) node)) := by + have hfun : + (fun ω : Tape rows repeats (.step i p) slots => + (evaluate rows repeats (.step i p) slots ω (.inr (j.val, node)) : + Fin (rows (Nodes.height node)) → H (nodeSlots (childSlots slots j.val) node))) = + (fun ω : Tape rows repeats (.step i p) slots => ω (.inr (.inr j)) node) := by + funext ω + exact evaluate_ordinary rows repeats i p slots ω j node + exact (congrArg + (fun f : Tape rows repeats (.step i p) slots → + (Fin (rows (Nodes.height node)) → H (nodeSlots (childSlots slots j.val) node)) => + (tapeLaw rows repeats (.step i p) slots).pushforward f) hfun).trans + ((component_image rows repeats i p slots (.inr (.inr j)) + (fun arrays => arrays node)).trans (uniform_arrays_node (childSlots slots j.val) rows node)) + +end + +end PerfectCompleteness.WholeArraySampler + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Sampling/WholeCutSampler.lean b/lean/OAI/Computability/PerfectCompleteness/Sampling/WholeCutSampler.lean new file mode 100644 index 0000000000000000000000000000000000000000..651dad4ec30b5a4930fc992ae0633647dfbe22cb --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Sampling/WholeCutSampler.lean @@ -0,0 +1,327 @@ +import OAI.Computability.PerfectCompleteness.Construction.CutChildGrouping +import OAI.Computability.PerfectCompleteness.Sampling.CutSamplerRefinement +import OAI.Computability.PerfectCompleteness.Sampling.RationalFiniteLawLemmas +import OAI.Computability.PerfectCompleteness.Sampling.WholeArraySampler + +namespace OAI + +section + +namespace PerfectCompleteness.WholeCutSampler + +open TreeSourceSpaces HierarchicalArrays DescendantSpaces +open UniqueGamesTheorem.Foundations.Games +open scoped BigOperators Classical + +abbrev F2 := ZMod 2 + +noncomputable section + +variable {branch : Nat → Nat} {n m t : Nat} + +abbrev RootTape (rows repeats : Nat → Nat) (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) := + BucketSampler.Direction (rows n) → + CutSamplerRefinement.Tape F2 repeats p (LeafDomain slots) + +def Tape (rows repeats : Nat → Nat) : + {n m : Nat} → Path branch n m → + (RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) → Type + | 0, _, .refl _, slots => Arrays slots rows + | n + 1, _, .refl _, slots => + CutChildGrouping.Raw (C := Fin (rows (n + 1))) slots rows + | _, _, .step i p, slots => + RootTape rows repeats (.step i p) slots × + (Tape rows repeats p (childSlots slots i) × + ((j : RecursiveSampler.OffPath i) → Arrays (childSlots slots j.val) rows)) + +@[instance_reducible] def tapeFintypeAux (rows repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n m) → + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) → + Fintype (Tape rows repeats p slots) + | 0, _, .refl _, slots => inferInstanceAs (Fintype (Arrays slots rows)) + | n + 1, _, .refl _, slots => + inferInstanceAs (Fintype (CutChildGrouping.Raw (C := Fin (rows (n + 1))) slots rows)) + | _, _, .step i p, slots => + letI : Fintype (Tape rows repeats p (childSlots slots i)) := + tapeFintypeAux rows repeats p (childSlots slots i) + inferInstanceAs (Fintype + (RootTape rows repeats (.step i p) slots × + (Tape rows repeats p (childSlots slots i) × + ((j : RecursiveSampler.OffPath i) → Arrays (childSlots slots j.val) rows)))) + +instance tapeFintype (rows repeats : Nat → Nat) (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) : + Fintype (Tape rows repeats p slots) := tapeFintypeAux rows repeats p slots + +def zeroTape (rows repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n m) → + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) → + Tape rows repeats p slots + | 0, _, .refl _, _ => fun node => nomatch node + | _ + 1, _, .refl _, _ => fun _ => (fun _ => 0, fun _ _ => 0) + | _, _, .step i p, slots => + (fun _ j => CutSamplerRefinement.zeroFactor F2 repeats (.step i p) (LeafDomain slots) j, + zeroTape rows repeats p (childSlots slots i), fun _ _ _ => 0) + +instance tapeNonempty (rows repeats : Nat → Nat) (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) : + Nonempty (Tape rows repeats p slots) := ⟨zeroTape rows repeats p slots⟩ + +def stepEquiv (i : Fin (branch n)) (Root Selected : Type) + (Ordinary : RecursiveSampler.OffPath i → Type) : + (Root × (Selected × ((j : RecursiveSampler.OffPath i) → Ordinary j))) ≃ + WholeArraySampler.StepTape (i := i) Root Selected Ordinary where + toFun x k := match k with + | .inl _ => x.1 + | .inr (.inl _) => x.2.1 + | .inr (.inr j) => x.2.2 j + invFun x := (x (.inl ()), x (.inr (.inl ())), fun j => x (.inr (.inr j))) + left_inv x := rfl + right_inv x := by + funext k + rcases k with u | (u | j) + · cases u + rfl + · cases u + rfl + · rfl + +def assembleArrays + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (rows : Nat → Nat) : + CutChildGrouping.Assembled (C := Fin (rows (n + 1))) slots rows →ₗ[F2] + Arrays slots rows where + toFun x := WholeArraySampler.assemble slots rows x.1 x.2 + map_add' x y := by + funext node + rcases node with u | ⟨i, node⟩ <;> rfl + map_smul' c x := by + funext node + rcases node with u | ⟨i, node⟩ <;> rfl + +theorem assembleArrays_surjective + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (rows : Nat → Nat) : Function.Surjective (assembleArrays slots rows) := by + intro arrays + refine ⟨(arrays (.inl ()), fun i node => arrays (.inr (i, node))), ?_⟩ + funext node + rcases node with u | ⟨i, node⟩ + · cases u + rfl + · rfl + +def collapseRoot (rows repeats : Nat → Nat) (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) : + RootTape rows repeats p slots → WholeArraySampler.RootTape rows repeats p slots := + fun x v => CutSamplerRefinement.collapse F2 repeats p (LeafDomain slots) (x v) + +def collapse (rows repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n m) → + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) → + Tape rows repeats p slots → WholeArraySampler.Tape rows repeats p slots + | 0, _, .refl _, _, x => x + | _ + 1, _, .refl _, slots, x => + assembleArrays slots rows (CutChildGrouping.assemble slots rows x) + | _, _, .step i p, slots, x => + stepEquiv i (WholeArraySampler.RootTape rows repeats (.step i p) slots) + (WholeArraySampler.Tape rows repeats p (childSlots slots i)) + (fun j => Arrays (childSlots slots j.val) rows) + (collapseRoot rows repeats (.step i p) slots x.1, + collapse rows repeats p (childSlots slots i) x.2.1, x.2.2) + +def rootLaw (rows repeats : Nat → Nat) (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) : + FiniteDistribution (RootTape rows repeats p slots) := + FiniteProduct.law (fun _ : BucketSampler.Direction (rows n) => + CutSamplerRefinement.tapeLaw F2 repeats p (LeafDomain slots)) + +def tapeLaw (rows repeats : Nat → Nat) : + {n m : Nat} → (p : Path branch n m) → + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) → + FiniteDistribution (Tape rows repeats p slots) + | 0, _, .refl _, slots => FiniteDistribution.uniform (Arrays slots rows) + | n + 1, _, .refl _, slots => + CutChildGrouping.rawLaw (C := Fin (rows (n + 1))) slots rows + | _, _, .step i p, slots => + (rootLaw rows repeats (.step i p) slots).product + ((tapeLaw rows repeats p (childSlots slots i)).product + (FiniteProduct.law (fun j : RecursiveSampler.OffPath i => + FiniteDistribution.uniform (Arrays (childSlots slots j.val) rows)))) + +theorem uniform_product {R S : Type*} [Fintype R] [Fintype S] + [Nonempty R] [Nonempty S] : + (FiniteDistribution.uniform R).product (FiniteDistribution.uniform S) = + FiniteDistribution.uniform (R × S) := by + apply FiniteDistribution.eq_of_weight_eq + intro x + simp only [FiniteDistribution.product, FiniteDistribution.uniform, + Fintype.card_prod, Nat.cast_mul, one_div_mul_one_div] + +theorem rootLaw_eq_uniform (rows repeats : Nat → Nat) (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) : + rootLaw rows repeats p slots = FiniteDistribution.uniform (RootTape rows repeats p slots) := by + unfold rootLaw CutSamplerRefinement.tapeLaw + simp only [UniformLinearImage.law_uniform] + +theorem tapeLaw_eq_uniform (rows repeats : Nat → Nat) (p : Path branch n m) : + ∀ (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot), + tapeLaw rows repeats p slots = FiniteDistribution.uniform (Tape rows repeats p slots) := by + induction p with + | refl n => + intro slots + cases n with + | zero => rfl + | succ n => exact UniformLinearImage.law_uniform + | @step n m i p ih => + intro slots + change (rootLaw rows repeats (.step i p) slots).product + ((tapeLaw rows repeats p (childSlots slots i)).product + (FiniteProduct.law (fun j : RecursiveSampler.OffPath i => + FiniteDistribution.uniform (Arrays (childSlots slots j.val) rows)))) = + FiniteDistribution.uniform + (RootTape rows repeats (.step i p) slots × + (Tape rows repeats p (childSlots slots i) × + ((j : RecursiveSampler.OffPath i) → Arrays (childSlots slots j.val) rows))) + rw [rootLaw_eq_uniform, ih, UniformLinearImage.law_uniform, + uniform_product + (R := Tape rows repeats p (childSlots slots i)) + (S := (j : RecursiveSampler.OffPath i) → Arrays (childSlots slots j.val) rows), + uniform_product + (R := RootTape rows repeats (.step i p) slots) + (S := Tape rows repeats p (childSlots slots i) × + ((j : RecursiveSampler.OffPath i) → Arrays (childSlots slots j.val) rows))] + +def stepComponent (i : Fin (branch n)) (Root Selected : Type) + (Ordinary : RecursiveSampler.OffPath i → Type) + [Fintype Root] [Fintype Selected] [∀ j, Fintype (Ordinary j)] + (μ : FiniteDistribution Root) (ν : FiniteDistribution Selected) + (P : (j : RecursiveSampler.OffPath i) → FiniteDistribution (Ordinary j)) : + (k : WholeArraySampler.StepIndex i) → FiniteDistribution + (WholeArraySampler.StepFactor Root Selected Ordinary k) + | .inl _ => μ + | .inr (.inl _) => ν + | .inr (.inr j) => P j + +theorem stepEquiv_law (i : Fin (branch n)) (Root Selected : Type) + (Ordinary : RecursiveSampler.OffPath i → Type) + [Fintype Root] [Fintype Selected] [∀ j, Fintype (Ordinary j)] + (μ : FiniteDistribution Root) (ν : FiniteDistribution Selected) + (P : (j : RecursiveSampler.OffPath i) → FiniteDistribution (Ordinary j)) : + (μ.product (ν.product (FiniteProduct.law P))).pushforward + (stepEquiv i Root Selected Ordinary) = + FiniteProduct.law (stepComponent i Root Selected Ordinary μ ν P) := by + rw [← FiniteDistribution.transport_eq_pushforward] + apply FiniteDistribution.eq_of_weight_eq + intro x + change μ.weight (x (.inl ())) * + (ν.weight (x (.inr (.inl ()))) * + ∏ j : RecursiveSampler.OffPath i, (P j).weight (x (.inr (.inr j)))) = + ∏ k : Unit ⊕ (Unit ⊕ RecursiveSampler.OffPath i), + (stepComponent i Root Selected Ordinary μ ν P k).weight (x k) + simp only [Fintype.prod_sum_type, Fintype.prod_unique, stepComponent] + +theorem collapseRoot_law (rows repeats : Nat → Nat) (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) : + (rootLaw rows repeats p slots).pushforward (collapseRoot rows repeats p slots) = + BucketSampler.recursiveTapeLaw (rows n) repeats p (LeafDomain slots) := by + unfold rootLaw collapseRoot + rw [CleanConditioning.pushforward_law] + simp_rw [CutSamplerRefinement.collapse_tapeLaw] + rfl + +theorem terminal_law + (slots : RecursiveSpaces.Slots branch (n + 1) → Fin t → MixedSupport.Slot) + (rows : Nat → Nat) : + (CutChildGrouping.rawLaw (C := Fin (rows (n + 1))) slots rows).pushforward + (fun x => assembleArrays slots rows (CutChildGrouping.assemble slots rows x)) = + FiniteDistribution.uniform (Arrays slots rows) := by + rw [← FiniteDistribution.pushforward_comp + (CutChildGrouping.rawLaw (C := Fin (rows (n + 1))) slots rows) + (CutChildGrouping.assemble slots rows) (assembleArrays slots rows), + CutChildGrouping.assemble_law] + exact UniformLinearImage.uniform_pushforward_linearMap + (R := F2) + (A := CutChildGrouping.Assembled (C := Fin (rows (n + 1))) slots rows) + (B := Arrays slots rows) + (assembleArrays slots rows) (assembleArrays_surjective slots rows) + +theorem collapse_tapeLaw (rows repeats : Nat → Nat) (p : Path branch n m) : + ∀ (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot), + (tapeLaw rows repeats p slots).pushforward (collapse rows repeats p slots) = + WholeArraySampler.tapeLaw rows repeats p slots := by + induction p with + | refl n => + intro slots + cases n with + | zero => + change (FiniteDistribution.uniform (Arrays slots rows)).pushforward + (id : Arrays slots rows → Arrays slots rows) = + FiniteDistribution.uniform (Arrays slots rows) + exact FiniteDistribution.pushforward_id + (FiniteDistribution.uniform (Arrays slots rows)) + | succ n => exact terminal_law slots rows + | @step n m i p ih => + intro slots + let R := WholeArraySampler.RootTape rows repeats (.step i p) slots + let S := WholeArraySampler.Tape rows repeats p (childSlots slots i) + let O := fun j : RecursiveSampler.OffPath i => Arrays (childSlots slots j.val) rows + let : (k : WholeArraySampler.StepIndex i) → Fintype + (WholeArraySampler.StepFactor R S O k) := + fun k => WholeArraySampler.stepFactorFintype R S O k + let μ : FiniteDistribution R := + BucketSampler.recursiveTapeLaw (rows (n + 1)) repeats (.step i p) (LeafDomain slots) + let ν : FiniteDistribution S := WholeArraySampler.tapeLaw rows repeats p (childSlots slots i) + let P : (j : RecursiveSampler.OffPath i) → FiniteDistribution (O j) := + fun j => FiniteDistribution.uniform (Arrays (childSlots slots j.val) rows) + let f : Tape rows repeats (.step i p) slots → R × (S × ((j : RecursiveSampler.OffPath i) → O j)) := + fun x => (collapseRoot rows repeats (.step i p) slots x.1, + collapse rows repeats p (childSlots slots i) x.2.1, x.2.2) + have hmap : (tapeLaw rows repeats (.step i p) slots).pushforward f = + μ.product (ν.product (FiniteProduct.law P)) := by + change ((rootLaw rows repeats (.step i p) slots).product + ((tapeLaw rows repeats p (childSlots slots i)).product (FiniteProduct.law P))).pushforward + (fun x => (collapseRoot rows repeats (.step i p) slots x.1, + (fun y => (collapse rows repeats p (childSlots slots i) y.1, id y.2)) x.2)) = _ + rw [FiniteDistribution.product_pushforward + (rootLaw rows repeats (.step i p) slots) + ((tapeLaw rows repeats p (childSlots slots i)).product (FiniteProduct.law P)) + (collapseRoot rows repeats (.step i p) slots) + (fun y => (collapse rows repeats p (childSlots slots i) y.1, id y.2))] + rw [FiniteDistribution.product_pushforward + (tapeLaw rows repeats p (childSlots slots i)) (FiniteProduct.law P) + (collapse rows repeats p (childSlots slots i)) id, + collapseRoot_law, ih, FiniteDistribution.pushforward_id (FiniteProduct.law P)] + change (tapeLaw rows repeats (.step i p) slots).pushforward + (fun x => stepEquiv i R S O (f x)) = _ + rw [← FiniteDistribution.pushforward_comp + (tapeLaw rows repeats (.step i p) slots) f (stepEquiv i R S O), hmap] + exact stepEquiv_law i R S O μ ν P + +def evaluate (rows repeats : Nat → Nat) (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) + (x : Tape rows repeats p slots) : Arrays slots rows := + WholeArraySampler.evaluate rows repeats p slots (collapse rows repeats p slots x) + +def law (rows repeats : Nat → Nat) (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) : + FiniteDistribution (Arrays slots rows) := + (tapeLaw rows repeats p slots).pushforward (evaluate rows repeats p slots) + +theorem evaluate_law (rows repeats : Nat → Nat) (p : Path branch n m) + (slots : RecursiveSpaces.Slots branch n → Fin t → MixedSupport.Slot) : + law rows repeats p slots = WholeArraySampler.law rows repeats p slots := by + change (tapeLaw rows repeats p slots).pushforward + (fun x => WholeArraySampler.evaluate rows repeats p slots (collapse rows repeats p slots x)) = _ + rw [← FiniteDistribution.pushforward_comp + (tapeLaw rows repeats p slots) (collapse rows repeats p slots) + (WholeArraySampler.evaluate rows repeats p slots), collapse_tapeLaw] + rfl + +end + +end PerfectCompleteness.WholeCutSampler + +end + +end OAI diff --git a/lean/OAI/Computability/PerfectCompleteness/Theorem11.lean b/lean/OAI/Computability/PerfectCompleteness/Theorem11.lean new file mode 100644 index 0000000000000000000000000000000000000000..a01231ded2e43551949ac614f6d7c48a7d1d1d66 --- /dev/null +++ b/lean/OAI/Computability/PerfectCompleteness/Theorem11.lean @@ -0,0 +1,32 @@ +import OAI.Computability.PerfectCompleteness.Machines.FixedBinaryGapReduction +import OAI.Computability.PerfectCompleteness.Reduction.FixedPreliminarySoundness +import OAI.Computability.PerfectCompleteness.Reduction.PreliminaryOutputLemmas + +namespace OAI + +section + +namespace PerfectCompleteness.Theorem11 + +noncomputable section + +theorem preliminary_value_le {δ : ℚ} {hδ : 0 < δ} + (parameters : FixedParameters.Parameters δ hδ) (input : List Bool) + (unsat : ¬BinaryLanguage.language input) : + FixedPreliminaryGame.value parameters input ≤ InitialParameters.epsilon δ := + FixedPreliminaryValue.value_le_of_no_large_strategy parameters input + (InitialParameters.epsilon δ) (fun strategy hsuccess => + FixedPreliminarySoundness.no_large_strategy parameters input unsat strategy hsuccess) + +theorem exists_reduction (δ : ℚ) (positive : 0 < δ) (less_than_one : δ < 1) : + Nonempty (BinaryGapReduction δ) := by + obtain ⟨parameters⟩ := FixedParameters.exists_parameters positive less_than_one + exact ⟨FixedBinaryGapReduction.ofPreliminarySoundness parameters + (preliminary_value_le parameters)⟩ + +end +end PerfectCompleteness.Theorem11 + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/AIGBitArithmeticEmission.lean b/lean/OAI/Computability/QuantumFactoring/AIGBitArithmeticEmission.lean new file mode 100644 index 0000000000000000000000000000000000000000..925678e9a6ea5371887abc77601ae24d6c64e5a1 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/AIGBitArithmeticEmission.lean @@ -0,0 +1,96 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.ArithmeticPredicates +import OAI.Computability.QuantumFactoring.AIGNetworkEmission +import OAI.Computability.QuantumFactoring.AIGNetworkProcedure +import OAI.Computability.QuantumFactoring.NativeAIGBinaryInputs + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.AIGNetworkEmission +open Std.Sat Std.Tactic.BVDecide.BVExpr.bitblast +open BitStackProgram BitStackProgram.Procedure NetworkEmission + +def binaryPack (op : NativeAIG.Graph→List NativeAIG.Ref→List NativeAIG.Ref→NativeAIG.Graph×List NativeAIG.Ref) + (w : ℕ) : Pack:= + let r:=op (NativeAIG.rawInputs (w+w)) (NativeAIG.rawWord 0 w) (NativeAIG.rawWord w w) + compilePack (w+w) r.1.decls r.2 +lemma binaryPack_value (op : NativeAIG.Graph→List NativeAIG.Ref→List NativeAIG.Ref→NativeAIG.Graph×List NativeAIG.Ref) + (w : ℕ) (res : AIG.RefVecEntry (Fin (w+w)) w) + (hr : NativeAIG.VecRel (op (NativeAIG.rawInputs (w+w)) (NativeAIG.rawWord 0 w) (NativeAIG.rawWord w w)) res) : + (binaryPack op w).val.value=erase (AIGCompiler.compileVec res.aig res.vec):=by + dsimp only [binaryPack] + rw [hr.2] + exact compilePack_value hr.1 _ +lemma addPack_value (w : ℕ) : (binaryPack NativeAIG.add w).val.value=erase (BitArithmetic.add w):=by + apply binaryPack_value + have hh:=NativeAIG.add_rel (NativeAIG.inputs_rel (w+w)) (BitArithmetic.binaryInputs w) + simpa only [NativeAIG.eraseVec_binaryInputs_lhs,NativeAIG.eraseVec_binaryInputs_rhs] using hh +lemma mulPack_value (w : ℕ) : (binaryPack NativeAIG.mul w).val.value=erase (BitArithmetic.mul w):=by + apply binaryPack_value + have hh:=NativeAIG.mul_rel (NativeAIG.inputs_rel (w+w)) (BitArithmetic.binaryInputs w) + simpa only [NativeAIG.eraseVec_binaryInputs_lhs,NativeAIG.eraseVec_binaryInputs_rhs] using hh +lemma subPack_value (w : ℕ) : (binaryPack NativeAIG.sub w).val.value=erase (BitArithmetic.sub w):=by + apply binaryPack_value + have hh:=NativeAIG.sub_rel (NativeAIG.inputs_rel (w+w)) (BitArithmetic.binaryInputs w) + simpa only [NativeAIG.eraseVec_binaryInputs_lhs,NativeAIG.eraseVec_binaryInputs_rhs] using hh +lemma divPack_value (w : ℕ) : (binaryPack NativeAIG.divide w).val.value=erase (BitArithmetic.div w):=by + apply binaryPack_value + have hh:=NativeAIG.divide_rel (NativeAIG.inputs_rel (w+w)) (BitArithmetic.binaryInputs w) + simpa only [NativeAIG.eraseVec_binaryInputs_lhs,NativeAIG.eraseVec_binaryInputs_rhs] using hh +lemma modPack_value (w : ℕ) : (binaryPack NativeAIG.remainder w).val.value=erase (BitArithmetic.mod w):=by + apply binaryPack_value + have hh:=NativeAIG.remainder_rel (NativeAIG.inputs_rel (w+w)) (BitArithmetic.binaryInputs w) + simpa only [NativeAIG.eraseVec_binaryInputs_lhs,NativeAIG.eraseVec_binaryInputs_rhs] using hh + +def ultPack (w : ℕ) : Pack:= + let r:=NativeAIG.ult (NativeAIG.rawInputs (w+w)) (NativeAIG.rawWord 0 w) (NativeAIG.rawWord w w) + compilePack (w+w) r.1.decls [r.2] +lemma ultPack_value (w : ℕ) : (ultPack w).val.value=erase (BitArithmetic.ult w):=by + have hr:=NativeAIG.ult_rel (NativeAIG.inputs_rel (w+w)) (BitArithmetic.binaryInputs w) + simp only [NativeAIG.eraseVec_binaryInputs_lhs,NativeAIG.eraseVec_binaryInputs_rhs] at hr + unfold ultPack BitArithmetic.ult + have hh:=compilePack_value hr.1 (fun _ : Fin 1=>(Std.Tactic.BVDecide.BVPred.mkUlt + (AIGCompiler.inputs (w+w)).1 (BitArithmetic.binaryInputs w)).ref) + simpa only [List.ofFn_succ,List.ofFn_zero,hr.2] using hh + +namespace Emission +noncomputable def binaryPackP + {op : NativeAIG.Graph→List NativeAIG.Ref→List NativeAIG.Ref→NativeAIG.Graph×List NativeAIG.Ref} + (p : Procedure unaryCode (prodCode NativeAIG.graphCode (listCode NativeAIG.refCode)) + (fun w=>op (NativeAIG.rawInputs (w+w)) (NativeAIG.rawWord 0 w) (NativeAIG.rawWord w w))) : + Procedure unaryCode packCode (binaryPack op):=by + let width:=unaryAdd.comp ((identity unaryCode).pair (identity unaryCode)) + let graph:=(first NativeAIG.graphCode (listCode NativeAIG.refCode)).comp p + let ds:=NativeAIG.Emission.decls.comp graph + let refs:=(second NativeAIG.graphCode (listCode NativeAIG.refCode)).comp p + exact compilePackP.comp ((width.pair ds).pair refs) +noncomputable def addPackP : Procedure unaryCode packCode (binaryPack NativeAIG.add):=binaryPackP NativeAIG.Emission.inputAddP +noncomputable def mulPackP : Procedure unaryCode packCode (binaryPack NativeAIG.mul):=binaryPackP NativeAIG.Emission.inputMulP +noncomputable def subPackP : Procedure unaryCode packCode (binaryPack NativeAIG.sub):=binaryPackP NativeAIG.Emission.inputSubP +noncomputable def divPackP : Procedure unaryCode packCode (binaryPack NativeAIG.divide):=binaryPackP NativeAIG.Emission.inputDivP +noncomputable def modPackP : Procedure unaryCode packCode (binaryPack NativeAIG.remainder):=binaryPackP NativeAIG.Emission.inputModP +noncomputable def inputUltP : Procedure unaryCode (prodCode NativeAIG.graphCode NativeAIG.refCode) + (fun w=>NativeAIG.ult (NativeAIG.rawInputs (w+w)) (NativeAIG.rawWord 0 w) (NativeAIG.rawWord w w)):=by + refine (NativeAIG.Emission.ultP.comp (((identity NativeAIG.addStateCode).precompose + (fun s:NativeAIG.BinaryState=>s.val)).comp NativeAIG.Emission.binaryInputP)).congrFun ?_ + intro w + change NativeAIG.ult (NativeAIG.binaryInput w).val.val.graph (NativeAIG.binaryInput w).val.val.lhs + (NativeAIG.binaryInput w).val.val.rhs=_ + congr 1 +noncomputable def ultPackP : Procedure unaryCode packCode ultPack:=by + let width:=unaryAdd.comp ((identity unaryCode).pair (identity unaryCode)) + let ds:=NativeAIG.Emission.decls.comp ((first NativeAIG.graphCode NativeAIG.refCode).comp inputUltP) + let ref:=(second NativeAIG.graphCode NativeAIG.refCode).comp inputUltP + let refs:=(listCons NativeAIG.refCode).comp (ref.pair (Procedure.constant _ (listCode NativeAIG.refCode) [])) + exact compilePackP.comp ((width.pair ds).pair refs) +end Emission +end ExactQuantumFactoring.AIGNetworkEmission + +end + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/AIGBounds.lean b/lean/OAI/Computability/QuantumFactoring/AIGBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..e6f9a747975bc56c824046bce8a585abd964f74c --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/AIGBounds.lean @@ -0,0 +1,187 @@ +import Mathlib + +namespace OAI + +section +open scoped BigOperators + + +namespace ExactQuantumFactoring.AIGBounds +open Std.Sat +open Std.Tactic.BVDecide.BVExpr.bitblast + +variable {α : Type} [Hashable α] [DecidableEq α] + +lemma cached_go_size (aig : AIG α) (input : AIG.BinaryInput aig) : + (AIG.mkGateCached.go aig input).aig.decls.size ≤ aig.decls.size + 1 := by + dsimp only [AIG.mkGateCached.go] + split + · simp + · split <;> try simp + split + · split <;> simp + · simp + +lemma cached_size (aig : AIG α) (input : AIG.BinaryInput aig) : + (aig.mkGateCached input).aig.decls.size ≤ aig.decls.size + 1 := by + dsimp only [AIG.mkGateCached] + split <;> apply cached_go_size + +lemma atom_size (aig : AIG α) (v : α) : + (aig.mkAtomCached v).aig.decls.size ≤ aig.decls.size + 1 := by + dsimp only [AIG.mkAtomCached] + split <;> simp + +lemma and_size (aig : AIG α) (input : AIG.BinaryInput aig) : + (aig.mkAndCached input).aig.decls.size ≤ aig.decls.size + 1 := cached_size _ _ + +lemma or_size (aig : AIG α) (input : AIG.BinaryInput aig) : + (aig.mkOrCached input).aig.decls.size ≤ aig.decls.size + 1 := cached_size _ _ + +lemma xor_size (aig : AIG α) (input : AIG.BinaryInput aig) : + (aig.mkXorCached input).aig.decls.size ≤ aig.decls.size + 3 := by + unfold AIG.mkXorCached + dsimp only + exact (cached_size _ _).trans (by + have := cached_size aig input + have := cached_size (aig.mkGateCached input).aig + ((input.cast (AIG.LawfulOperator.le_size ..)).invert true true) + omega) + +lemma fullAdderOut_size (aig : AIG α) (input : FullAdderInput aig) : + (mkFullAdderOut aig input).aig.decls.size ≤ aig.decls.size + 6 := by + unfold mkFullAdderOut + dsimp only + exact (xor_size _ _).trans (by + have := xor_size aig ⟨input.lhs,input.rhs⟩ + omega) + +lemma fullAdderCarry_size (aig : AIG α) (input : FullAdderInput aig) : + (mkFullAdderCarry aig input).aig.decls.size ≤ aig.decls.size + 6 := by + unfold mkFullAdderCarry + dsimp only + apply (or_size _ _).trans + apply Nat.add_le_add_right ?_ 1 + apply (and_size _ _).trans + apply Nat.add_le_add_right ?_ 1 + apply (and_size _ _).trans + apply Nat.add_le_add_right ?_ 1 + exact xor_size _ _ + +lemma fullAdder_size (aig : AIG α) (input : FullAdderInput aig) : + (mkFullAdder aig input).aig.decls.size ≤ aig.decls.size + 12 := by + unfold mkFullAdder + dsimp only + apply (fullAdderCarry_size _ _).trans + have := fullAdderOut_size aig input + omega + +lemma add_go_size {w : ℕ} (aig : AIG α) (lhs rhs : AIG.RefVec aig w) + (curr : ℕ) (hcurr : curr ≤ w) (cin : AIG.Ref aig) (s : AIG.RefVec aig curr) : + (blastAdd.go aig lhs rhs curr hcurr cin s).aig.decls.size ≤ + aig.decls.size + 12*(w-curr) := by + rw [blastAdd.go] + split + next h => + dsimp only + apply (add_go_size _ _ _ _ _ _ _).trans + have hh := fullAdder_size aig ⟨lhs.get curr h, rhs.get curr h, cin⟩ + omega + next h => simp +termination_by w-curr + +/-- A verified native ripple circuit has linear declaration count. The cache +can only decrease this upper bound. -/ +theorem add_size {w : ℕ} (aig : AIG α) (input : AIG.BinaryRefVec aig w) : + (blastAdd aig input).aig.decls.size ≤ aig.decls.size + 12*w := by + unfold blastAdd + split <;> unfold blastAdd.blast <;> apply add_go_size + +lemma if_size (aig : AIG α) (input : AIG.TernaryInput aig) : + (aig.mkIfCached input).aig.decls.size ≤ aig.decls.size + 3 := by + unfold AIG.mkIfCached + dsimp only + apply (or_size _ _).trans + apply Nat.add_le_add_right ?_ 1 + apply (and_size _ _).trans + apply Nat.add_le_add_right ?_ 1 + exact and_size _ _ + +lemma ite_go_size {w : ℕ} (aig : AIG α) (curr : ℕ) (hcurr : curr ≤ w) + (discr : AIG.Ref aig) (lhs rhs : AIG.RefVec aig w) (s : AIG.RefVec aig curr) : + (AIG.RefVec.ite.go aig curr hcurr discr lhs rhs s).aig.decls.size ≤ + aig.decls.size + 3*(w-curr) := by + rw [AIG.RefVec.ite.go] + split + next h => + dsimp only + apply (ite_go_size _ _ _ _ _ _ _).trans + have hh := if_size aig ⟨discr, lhs.get curr h, rhs.get curr h⟩ + omega + next h => simp +termination_by w-curr + +lemma ite_size {w : ℕ} (aig : AIG α) (input : AIG.RefVec.IfInput aig w) : + (AIG.RefVec.ite aig input).aig.decls.size ≤ aig.decls.size + 3*w := + ite_go_size _ 0 _ _ _ _ _ + +lemma shift_go_size {w : ℕ} (aig : AIG α) (input : AIG.RefVec aig w) + (distance curr : ℕ) (hcurr : curr ≤ w) (s : AIG.RefVec aig curr) : + (blastShiftLeftConst.go aig input distance curr hcurr s).aig.decls.size = aig.decls.size := by + rw [blastShiftLeftConst.go] + split + · split <;> apply shift_go_size + · simp +termination_by w-curr + +lemma shift_size {w : ℕ} (aig : AIG α) (input : AIG.ShiftTarget aig w) : + (blastShiftLeftConst aig input).aig.decls.size = aig.decls.size := shift_go_size .. + +lemma mul_go_size {w : ℕ} (aig : AIG α) (lhs rhs : AIG.RefVec aig w) + (curr : ℕ) (acc : AIG.RefVec aig w) : + (blastMul.go aig lhs rhs curr acc).aig.decls.size ≤ aig.decls.size + 15*w*(w-curr) := by + rw [blastMul.go] + split + next h => + split + · apply (mul_go_size _ _ _ _ _).trans + exact Nat.add_le_add_left (Nat.mul_le_mul_left _ (by omega)) _ + · dsimp only + apply (mul_go_size _ _ _ _ _).trans + have hshift := shift_size aig ⟨lhs,curr⟩ + refine (Nat.add_le_add_right (ite_size _ _) _).trans ?_ + have hadd : (blastAdd (blastShiftLeftConst aig ⟨lhs,curr⟩).aig + ⟨acc.cast (AIG.LawfulVecOperator.le_size ..), + (blastShiftLeftConst aig ⟨lhs,curr⟩).vec⟩).aig.decls.size ≤ aig.decls.size + 12*w := by + rw [← hshift] + apply add_size + have he : w-curr = (w-(curr+1))+1 := by omega + rw [he, Nat.mul_add, Nat.mul_one] + omega + next h => simp +termination_by w-curr + +lemma mul_blast_size {w : ℕ} (aig : AIG α) (input : AIG.BinaryRefVec aig w) : + (blastMul.blast aig input).aig.decls.size ≤ aig.decls.size + 15*w*w := by + unfold blastMul.blast + split + · simp_all + next h => + dsimp only + apply (mul_go_size _ _ _ _ _).trans + have hh := ite_size aig ⟨input.rhs.get 0 (by omega), input.lhs, blastConst aig 0⟩ + have he : w-1+1=w := by omega + nlinarith + +/-- The native shift-and-add multiplier has quadratic declaration count. -/ +theorem mul_size {w : ℕ} (aig : AIG α) (input : AIG.BinaryRefVec aig w) : + (blastMul aig input).aig.decls.size ≤ aig.decls.size + 15*w*w := by + unfold blastMul + split <;> apply mul_blast_size + +end ExactQuantumFactoring.AIGBounds + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/AIGCompiler.lean b/lean/OAI/Computability/QuantumFactoring/AIGCompiler.lean new file mode 100644 index 0000000000000000000000000000000000000000..257dd2eb77fe268ddd607320219ef6abb3235cc0 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/AIGCompiler.lean @@ -0,0 +1,179 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BooleanVector + +namespace OAI + +section +open scoped BigOperators + + +namespace ExactQuantumFactoring + +open BooleanNetwork Std.Sat + +namespace AIGCompiler + +variable {n : ℕ} (g : AIG (Fin n)) + +def graphWire (i : Fin g.decls.size) : Fin (n + g.decls.size) := Fin.natAdd n i + +def faninNet (f : AIG.Fanin) : BooleanNetwork (n + g.decls.size) 1 := + let v := if h : f.gate < g.decls.size then bit (graphWire g ⟨f.gate,h⟩) else constant false + if f.invert then v.bnot else v + +lemma fanin_count (f : AIG.Fanin) : (faninNet g f).net.count ≤ 2 := by + have hv : (if h : f.gate < g.decls.size then bit (graphWire g ⟨f.gate,h⟩) + else constant false : BooleanNetwork (n+g.decls.size) 1).net.count ≤ 1 := by + by_cases h : f.gate < g.decls.size + · rw [dite_eq_left h]; simp + · rw [dite_eq_right h]; simp + unfold faninNet + generalize (if h : f.gate < g.decls.size then bit (graphWire g ⟨f.gate,h⟩) + else constant false : BooleanNetwork (n+g.decls.size) 1) = v at * + cases hf : f.invert + · change v.net.count ≤ 2 + omega + · change v.bnot.net.count ≤ 2 + rw [count_bnot] + omega + +lemma fanin_eval (f : AIG.Fanin) (h : f.gate < g.decls.size) (x : Fin (n+g.decls.size) → Bool) : + (faninNet g f).eval x 0 = Bool.xor (x (graphWire g ⟨f.gate,h⟩)) f.invert := by + simp only [faninNet, dite_eq_left h] + cases f.invert <;> simp + +def nodeNet (i : Fin g.decls.size) : BooleanNetwork (n+g.decls.size) 1 := + match g.decls[i.val] with + | .false => constant false + | .atom v => bit (Fin.castAdd g.decls.size v) + | .gate a b => (faninNet g a).band (faninNet g b) + +lemma node_count (i : Fin g.decls.size) : (nodeNet g i).net.count ≤ 5 := by + unfold nodeNet + cases g.decls[i.val] with + | false => simp + | atom v => simp + | gate a b => + rw [count_band] + have := fanin_count g a + have := fanin_count g b + omega + +def nodeDenote (x : Fin n → Bool) (i : Fin g.decls.size) : Bool := + AIG.denote x ⟨g, ⟨i.val, false, i.isLt⟩⟩ + +lemma node_eval (i : Fin g.decls.size) (x : Fin n → Bool) + (y : Fin (n+g.decls.size) → Bool) + (hi : ∀ j, y (j.castAdd g.decls.size) = x j) + (hg : ∀ j : Fin g.decls.size, j.val < i.val → y (graphWire g j) = nodeDenote g x j) : + (nodeNet g i).eval y 0 = nodeDenote g x i := by + unfold nodeNet nodeDenote + cases h : g.decls[i.val] with + | false => simpa only [eval_constant] using (AIG.denote_idx_false (assign := x) (invert := false) h).symm + | atom v => simpa only [eval_bit, hi, Bool.xor_false] using (AIG.denote_idx_atom (assign := x) (invert := false) h).symm + | gate a b => + have hab := g.hdag i.isLt h + dsimp only + rw [eval_band, fanin_eval g a (by omega), fanin_eval g b (by omega), + hg ⟨a.gate, by omega⟩ hab.1, hg ⟨b.gate, by omega⟩ hab.2] + have he := (AIG.denote_idx_gate (assign := x) (invert := false) h).symm + simpa only [AIG.denote, nodeDenote, Bool.xor_false] using he + +def nodeStep (i : Fin g.decls.size) : BooleanNetwork (n+g.decls.size) (n+g.decls.size) := + assign (graphWire g i) (nodeNet g i) + +def partialGraph (g : AIG (Fin n)) : (k : ℕ) → k ≤ g.decls.size → + BooleanNetwork (n+g.decls.size) (n+g.decls.size) + | 0, _ => select id + | k+1, h => (partialGraph g k (by omega)).comp (nodeStep g ⟨k, by omega⟩) + +lemma graph_count (k : ℕ) (h : k ≤ g.decls.size) : (partialGraph g k h).net.count ≤ 5*k := by + induction k with + | zero => simp [partialGraph] + | succ k ih => + rw [partialGraph, count_comp, nodeStep, count_assign] + have := node_count g ⟨k, by omega⟩ + have := ih (by omega) + omega + +lemma graph_input (k : ℕ) (h : k ≤ g.decls.size) (x : Fin (n+g.decls.size) → Bool) (j : Fin n) : + (partialGraph g k h).eval x (j.castAdd g.decls.size) = x (j.castAdd g.decls.size) := by + induction k with + | zero => rfl + | succ k ih => + rw [partialGraph, eval_comp, nodeStep, eval_assign, Function.update_of_ne, ih] + intro he + have := congrArg Fin.val he + simp [graphWire] at this + omega + +lemma graph_value (k : ℕ) (h : k ≤ g.decls.size) (x : Fin (n+g.decls.size) → Bool) + (j : Fin g.decls.size) (hj : j.val < k) : + (partialGraph g k h).eval x (graphWire g j) = + nodeDenote g (fun i => x (i.castAdd g.decls.size)) j := by + induction k generalizing j with + | zero => omega + | succ k ih => + rw [partialGraph, eval_comp, nodeStep, eval_assign] + by_cases hjk : j.val = k + · have hj' : j = ⟨k, by omega⟩ := Fin.ext hjk + rw [hj', Function.update_self] + apply node_eval g + · exact fun i => graph_input g k (by omega) x i + · exact fun i hi => ih (by omega) i (by simpa using hi) + · rw [Function.update_of_ne] + · exact ih (by omega) j (by omega) + · intro he + have := congrArg Fin.val he + simp [graphWire] at this + omega + +/-- The circuit interpreter's own, already verified, AIG semantics is preserved +by a retained-trace network of at most five nodes per AIG declaration. -/ +theorem graph_correct (x : Fin (n+g.decls.size) → Bool) (j : Fin g.decls.size) : + (partialGraph g g.decls.size le_rfl).eval x (graphWire g j) = + nodeDenote g (fun i => x (i.castAdd g.decls.size)) j := + graph_value g _ le_rfl x j j.isLt + +/-- Compile designated references of an AIG, starting only with its input bits. +All graph slots and their retained evaluation traces are genuine ancillas. -/ +def compile {m : ℕ} (refs : Fin m → AIG.Ref g) : BooleanNetwork n m := + ((padRight n g.decls.size).comp (partialGraph g g.decls.size le_rfl)).comp + (vector (fun i => faninNet g (AIG.Fanin.mk (refs i).gate (refs i).invert))) + +lemma compile_count {m : ℕ} (refs : Fin m → AIG.Ref g) : + (compile g refs).net.count ≤ 6*g.decls.size + 2*m := by + rw [compile, count_comp, count_comp, count_padRight] + have hg := graph_count g g.decls.size le_rfl + have hv := count_vector_le (fun i => faninNet g (AIG.Fanin.mk (refs i).gate (refs i).invert)) + (fun i => fanin_count g (AIG.Fanin.mk (refs i).gate (refs i).invert)) + omega + +lemma compile_correct {m : ℕ} (refs : Fin m → AIG.Ref g) (x : Fin n → Bool) (i : Fin m) : + (compile g refs).eval x i = AIG.denote x ⟨g, refs i⟩ := by + rw [compile, eval_comp, eval_comp, eval_vector, fanin_eval g _ (by simpa using (refs i).hgate), + graph_correct, eval_padRight] + have he : (fun j : Fin n => Fin.append x (fun _ : Fin g.decls.size => false) + (j.castAdd g.decls.size)) = x := by funext j; exact Fin.append_left .. + rw [he] + simp only [nodeDenote, AIG.denote, Bool.xor_false, AIG.Fanin.gate_mk, AIG.Fanin.invert_mk] + +/-- The whole output BitVec of a native, already verified, arithmetic bitblaster +is now a Boolean network with a linear overhead in its AIG graph size. -/ +def compileVec {w : ℕ} (refs : AIG.RefVec g w) : BooleanNetwork n w := + compile g (fun i => refs.get i.val i.isLt) + +lemma compileVec_correct {w : ℕ} (refs : AIG.RefVec g w) (x : Fin n → Bool) (i : Fin w) : + (compileVec g refs).eval x i = AIG.denote x ⟨g, refs.get i.val i.isLt⟩ := + compile_correct .. + +lemma compileVec_count {w : ℕ} (refs : AIG.RefVec g w) : + (compileVec g refs).net.count ≤ 6*g.decls.size + 2*w := compile_count .. + +end AIGCompiler +end ExactQuantumFactoring + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/AIGDivisionBounds.lean b/lean/OAI/Computability/QuantumFactoring/AIGDivisionBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..82b4c4526455c1ff2fafce2ef13e8e0772bf3119 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/AIGDivisionBounds.lean @@ -0,0 +1,200 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.AIGBounds + +namespace OAI + +section +open scoped BigOperators + + +namespace ExactQuantumFactoring.AIGBounds +open Std.Sat Std.Tactic.BVDecide +open BVExpr.bitblast +variable {α : Type} [Hashable α] [DecidableEq α] + +lemma not_go_size {w : ℕ} (aig : AIG α) (i : ℕ) (hi : i ≤ w) + (s : AIG.RefVec aig i) (input : AIG.RefVec aig w) : + (AIG.RefVec.map.go aig i hi s input AIG.mkNotCached).aig.decls.size = aig.decls.size := by + rw [AIG.RefVec.map.go] + split + · dsimp only + rw [not_go_size] + rfl + · rfl +termination_by w-i + +lemma not_size {w : ℕ} (aig : AIG α) (input : AIG.RefVec aig w) : + (blastNot aig input).aig.decls.size = aig.decls.size := + not_go_size .. + +lemma neg_size {w : ℕ} (aig : AIG α) (input : AIG.RefVec aig w) : + (blastNeg aig input).aig.decls.size ≤ aig.decls.size+12*w := by + unfold blastNeg + have h := add_size (blastNot aig input).aig + ⟨(blastNot aig input).vec, blastConst (blastNot aig input).aig (1#w)⟩ + simpa only [not_size] using h + +lemma sub_size {w : ℕ} (aig : AIG α) (input : AIG.BinaryRefVec aig w) : + (blastSub aig input).aig.decls.size ≤ aig.decls.size+24*w := by + unfold blastSub + dsimp only + apply (add_size _ _).trans + have h := neg_size aig input.rhs + omega + +lemma overflow_go_size {w : ℕ} (aig : AIG α) (lhs rhs : AIG.RefVec aig w) + (curr : ℕ) (cin : AIG.Ref aig) : + (mkOverflowBit.go aig lhs rhs curr cin).aig.decls.size ≤ + aig.decls.size+6*(w-curr) := by + rw [mkOverflowBit.go] + split + next h => + dsimp only + apply (overflow_go_size _ _ _ _ _).trans + have hh := fullAdderCarry_size aig ⟨lhs.get curr h, rhs.get curr h, cin⟩ + omega + · simp +termination_by w-curr + +lemma overflow_size (aig : AIG α) (input : OverflowInput aig) : + (mkOverflowBit aig input).aig.decls.size ≤ aig.decls.size+6*input.w := + overflow_go_size .. + +lemma ult_size {w : ℕ} (aig : AIG α) (input : AIG.BinaryRefVec aig w) : + (BVPred.mkUlt aig input).aig.decls.size ≤ aig.decls.size+6*w := by + unfold BVPred.mkUlt + dsimp only + change (mkOverflowBit _ _).aig.decls.size ≤ _ + apply (overflow_size _ _).trans + simp only [not_size, le_refl] + +lemma extend_go_size (aig : AIG α) (w : ℕ) (input : AIG.RefVec aig w) + (newWidth curr : ℕ) (hcurr : curr ≤ newWidth) (s : AIG.RefVec aig curr) : + (blastZeroExtend.go aig w input newWidth curr hcurr s).aig.decls.size = aig.decls.size := by + rw [blastZeroExtend.go] + split + · dsimp only + split <;> apply extend_go_size + · rfl +termination_by newWidth-curr + +lemma extend_size {w : ℕ} (aig : AIG α) (input : AIG.ExtendTarget aig w) : + (blastZeroExtend aig input).aig.decls.size = aig.decls.size := extend_go_size .. + +lemma shiftConcat_size {w : ℕ} (aig : AIG α) (input : blastUdiv.ShiftConcatInput aig w) : + (blastUdiv.blastShiftConcat aig input).aig.decls.size = aig.decls.size := extend_size .. + +lemma div_step_size {w : ℕ} (aig : AIG α) (n d : AIG.RefVec aig w) + (wn wr : ℕ) (q r : AIG.RefVec aig w) : + (blastUdiv.blastDivSubtractShift aig n d wn wr q r).aig.decls.size ≤ + aig.decls.size+36*w := by + unfold blastUdiv.blastDivSubtractShift + dsimp only + apply (ite_size _ _).trans + apply (Nat.add_le_add_right (ite_size _ _) (3*w)).trans + apply (Nat.add_le_add_right (Nat.add_le_add_right (ult_size _ _) (3*w)) (3*w)).trans + apply (Nat.add_le_add_right (Nat.add_le_add_right + (Nat.add_le_add_right (sub_size _ _) (6*w)) (3*w)) (3*w)).trans + simp only [shiftConcat_size] + omega + +lemma div_go_size {w : ℕ} (aig : AIG α) (curr : ℕ) (n d : AIG.RefVec aig w) + (wn wr : ℕ) (q r : AIG.RefVec aig w) : + (blastUdiv.go aig curr n d wn wr q r).aig.decls.size ≤ aig.decls.size+36*w*curr := by + induction curr generalizing aig wn wr with + | zero => simp [blastUdiv.go] + | succ curr ih => + rw [blastUdiv.go] + dsimp only + apply (ih _ _ _ _ _ _ _).trans + have h := div_step_size aig n d wn wr q r + nlinarith + +lemma beq_size (aig : AIG α) (input : AIG.BinaryInput aig) : + (aig.mkBEqCached input).aig.decls.size ≤ aig.decls.size+3 := by + unfold AIG.mkBEqCached + dsimp only + apply (cached_size _ _).trans + apply (Nat.add_le_add_right (cached_size _ _) 1).trans + apply (Nat.add_le_add_right (Nat.add_le_add_right (cached_size _ _) 1) 1).trans + omega + +lemma zip_go_size (f : (aig : AIG α) → AIG.BinaryInput aig → AIG.Entrypoint α) + [AIG.LawfulOperator α AIG.BinaryInput f] [AIG.RefVec.LawfulZipOperator α f] + (c : ℕ) (hf : ∀ aig input, (f aig input).aig.decls.size ≤ aig.decls.size+c) + {w : ℕ} (aig : AIG α) (idx : ℕ) (s : AIG.RefVec aig idx) (hi : idx ≤ w) + (lhs rhs : AIG.RefVec aig w) : + (AIG.RefVec.zip.go aig idx s hi lhs rhs f).aig.decls.size ≤ aig.decls.size+c*(w-idx) := by + rw [AIG.RefVec.zip.go] + split + next h => + dsimp only + apply (zip_go_size f c hf _ _ _ _ _ _).trans + have hh := hf aig ⟨lhs.get idx h, rhs.get idx h⟩ + have he : w-idx = w-(idx+1)+1 := by omega + rw [he] + nlinarith + · simp +termination_by w-idx + +lemma zip_size (f : (aig : AIG α) → AIG.BinaryInput aig → AIG.Entrypoint α) + [AIG.LawfulOperator α AIG.BinaryInput f] [AIG.RefVec.LawfulZipOperator α f] + (c : ℕ) (hf : ∀ aig input, (f aig input).aig.decls.size ≤ aig.decls.size+c) + {w : ℕ} (aig : AIG α) (input : AIG.BinaryRefVec aig w) : + (AIG.RefVec.zip aig input f).aig.decls.size ≤ aig.decls.size+c*w := zip_go_size f c hf aig 0 _ (by omega) input.lhs input.rhs + +lemma fold_go_size (f : (aig : AIG α) → AIG.BinaryInput aig → AIG.Entrypoint α) + [AIG.LawfulOperator α AIG.BinaryInput f] + (c : ℕ) (hf : ∀ aig input, (f aig input).aig.decls.size ≤ aig.decls.size+c) + {w : ℕ} (aig : AIG α) (acc : AIG.Ref aig) (idx : ℕ) (input : AIG.RefVec aig w) : + (AIG.RefVec.fold.go aig acc idx w input f).aig.decls.size ≤ aig.decls.size+c*(w-idx) := by + rw [AIG.RefVec.fold.go] + split + next h => + dsimp only + apply (fold_go_size f c hf _ _ _ _).trans + have hh := hf aig ⟨acc, input.get idx h⟩ + have he : w-idx = w-(idx+1)+1 := by omega + rw [he] + nlinarith + · simp +termination_by w-idx + +lemma fold_size (f : (aig : AIG α) → AIG.BinaryInput aig → AIG.Entrypoint α) + [AIG.LawfulOperator α AIG.BinaryInput f] + (c : ℕ) (hf : ∀ aig input, (f aig input).aig.decls.size ≤ aig.decls.size+c) + {w : ℕ} (aig : AIG α) (input : AIG.RefVec aig w) : + (AIG.RefVec.fold aig input f).aig.decls.size ≤ aig.decls.size+c*w := fold_go_size f c hf aig (aig.mkConstCached true) 0 input + +lemma eq_size {w : ℕ} (aig : AIG α) (input : AIG.BinaryRefVec aig w) : + (BVPred.mkEq aig input).aig.decls.size ≤ aig.decls.size+4*w := by + unfold BVPred.mkEq + dsimp only + apply (fold_size _ 1 and_size _ _).trans + have hh := zip_size _ 3 beq_size aig input + omega + +lemma div_size {w : ℕ} (aig : AIG α) (input : AIG.BinaryRefVec aig w) : + (blastUdiv aig input).aig.decls.size ≤ aig.decls.size+36*w*w+7*w := by + unfold blastUdiv + dsimp only + apply (ite_size _ _).trans + apply (Nat.add_le_add_right (div_go_size _ _ _ _ _ _ _ _) (3*w)).trans + have hh := eq_size aig ⟨input.rhs, blastConst aig 0#w⟩ + omega + +lemma mod_size {w : ℕ} (aig : AIG α) (input : AIG.BinaryRefVec aig w) : + (blastUmod aig input).aig.decls.size ≤ aig.decls.size+36*w*w+7*w := by + unfold blastUmod + dsimp only + apply (ite_size _ _).trans + apply (Nat.add_le_add_right (div_go_size _ _ _ _ _ _ _ _) (3*w)).trans + have hh := eq_size aig ⟨input.rhs, blastConst aig 0#w⟩ + omega + +end ExactQuantumFactoring.AIGBounds + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/AIGInputs.lean b/lean/OAI/Computability/QuantumFactoring/AIGInputs.lean new file mode 100644 index 0000000000000000000000000000000000000000..058cb10b20fb11fc48de9ea5462537bc4c7f88a3 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/AIGInputs.lean @@ -0,0 +1,64 @@ +import Mathlib + +namespace OAI + +section +open scoped BigOperators + + +namespace ExactQuantumFactoring.AIGCompiler +open Std.Sat + +/-- One real AIG atom per input bit. The initial graph has one false node. -/ +def inputsPrefix (n : ℕ) : (k : ℕ) → k ≤ n → + (g : AIG (Fin n)) × (Fin k → AIG.Ref g) + | 0, _ => ⟨AIG.empty, Fin.elim0⟩ + | k+1, h => + let old := inputsPrefix n k (by omega) + let res := old.1.mkAtom ⟨k, by omega⟩ + ⟨res.aig, Fin.snoc (fun i => (old.2 i).cast (AIG.LawfulOperator.le_size (f := AIG.mkAtom) old.1 (⟨k, by omega⟩ : Fin n))) res.ref⟩ + +lemma inputsPrefix_size (n k : ℕ) (h : k ≤ n) : (inputsPrefix n k h).1.decls.size = k+1 := by + induction k with + | zero => simp [inputsPrefix, AIG.empty] + | succ k ih => simp [inputsPrefix, AIG.mkAtom, ih] + +lemma inputsPrefix_correct (n k : ℕ) (h : k ≤ n) (x : Fin n → Bool) (i : Fin k) : + AIG.denote x ⟨(inputsPrefix n k h).1, (inputsPrefix n k h).2 i⟩ = x (i.castLE h) := by + induction k with + | zero => exact Fin.elim0 i + | succ k ih => + refine Fin.lastCases ?_ (fun j => ?_) i + · simp only [inputsPrefix, Fin.snoc_last] + change AIG.denote x ((inputsPrefix n k (by omega)).1.mkAtom ⟨k, by omega⟩) = _ + rw [AIG.denote_mkAtom] + rfl + · simp only [inputsPrefix, Fin.snoc_castSucc] + rw [AIG.LawfulOperator.denote_cast_entry (f := @AIG.mkAtom (Fin n) _ _) + (entry := ⟨(inputsPrefix n k (by omega)).1, (inputsPrefix n k (by omega)).2 j⟩)] + exact ih (by omega) j + +def inputs (n : ℕ) := inputsPrefix n n le_rfl + +lemma inputs_size (n : ℕ) : (inputs n).1.decls.size = n+1 := inputsPrefix_size .. + +lemma inputs_correct (n : ℕ) (x : Fin n → Bool) (i : Fin n) : + AIG.denote x ⟨(inputs n).1, (inputs n).2 i⟩ = x i := inputsPrefix_correct .. + +/-- A vector of ordinary references; this constructor emits no graph nodes. -/ +def refVector {α : Type} [Hashable α] [DecidableEq α] {g : AIG α} {w : ℕ} + (f : Fin w → AIG.Ref g) : AIG.RefVec g w where + refs := Vector.ofFn (fun i => AIG.Fanin.mk (f i).gate (f i).invert) + hrefs := by intro i hi; simpa using (f ⟨i,hi⟩).hgate + +lemma refVector_get {α : Type} [Hashable α] [DecidableEq α] {g : AIG α} {w : ℕ} + (f : Fin w → AIG.Ref g) (i : ℕ) (hi : i < w) : + (refVector f).get i hi = f ⟨i,hi⟩ := by + simp [refVector, AIG.RefVec.get, AIG.Fanin.gate_mk, AIG.Fanin.invert_mk] + +end ExactQuantumFactoring.AIGCompiler + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/AIGNetworkEmission.lean b/lean/OAI/Computability/QuantumFactoring/AIGNetworkEmission.lean new file mode 100644 index 0000000000000000000000000000000000000000..b181eba8f8b6d296cd72d9b9cf6849b41046cac7 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/AIGNetworkEmission.lean @@ -0,0 +1,121 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.AIGCompiler +import OAI.Computability.QuantumFactoring.NetworkEmissionVector +import OAI.Computability.QuantumFactoring.NetworkEmissionRewire + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.AIGNetworkEmission +open Std.Sat BooleanNetwork +open NetworkEmission + +def faninPack (n gs : ℕ) (f : NativeAIG.Ref) : Pack:= + let v:=if f.1constantPack (n+gs) false + | .atom v=>bitPack (n+gs) v + | .gate a b=>bandPack (faninPack n gs a) (faninPack n gs b) +lemma nodePack_value {n : ℕ} (g : AIG (Fin n)) (i : Fin g.decls.size) : + (nodePack n g.decls.size (NativeAIG.eraseDecl g.decls[i.val])).val.value= + erase (AIGCompiler.nodeNet g i):=by + unfold AIGCompiler.nodeNet + cases h : g.decls[i.val] with + | false=>exact constantPack_value _ _ + | atom v=>exact bitPack_value (v.castAdd g.decls.size) + | gate a b=>exact bandPack_value _ _ _ _ (faninPack_value g a) (faninPack_value g b) + +def partialPack (n : ℕ) (ds : List NativeAIG.Decl) (k : ℕ) : Pack:= + ((List.range k).map (fun i=>assignPack (n+ds.length) (n+i) + (nodePack n ds.length ((ds.drop i).headD .zero)))).foldl compPack (identityPack (n+ds.length)) +lemma partialPack_value {n : ℕ} {r : NativeAIG.Graph} {g : AIG (Fin n)} + (hr : NativeAIG.Rel r g) (k : ℕ) (hk : k≤g.decls.size) : + (partialPack n r.decls k).val.value=erase (AIGCompiler.partialGraph g k hk):=by + have hl : r.decls.length=g.decls.size:=by rw [hr.1,List.length_map,Array.length_toList] + induction k with + | zero=>simpa only [partialPack,List.range_zero,List.map_nil,List.foldl_nil,hl,AIGCompiler.partialGraph] + using identityPack_value (n+g.decls.size) + | succ k ih=> + have hips:=ih (by omega) + have hd : (r.decls.drop k).headD .zero=NativeAIG.eraseDecl g.decls[k]:=by + rw [List.headD_eq_head?_getD,List.head?_drop,hr.1,List.getElem?_map,Array.getElem?_toList, + Array.getElem?_eq_getElem (by omega),Option.map_some,Option.getD_some] + have hn:=assignPack_value (AIGCompiler.graphWire g ⟨k,by omega⟩) _ _ (nodePack_value g ⟨k,by omega⟩) + simp only [AIGCompiler.graphWire,Fin.val_natAdd] at hn + unfold partialPack + rw [List.range_succ,List.map_append,List.map_cons,List.map_nil,List.foldl_append,List.foldl_cons,List.foldl_nil] + change (compPack (partialPack n r.decls k) (assignPack (n+r.decls.length) (n+k) + (nodePack n r.decls.length ((r.decls.drop k).headD .zero)))).val.value=_ + rw [compPack_value] + · rw [hips,hl,hd,hn] + exact (erase_comp _ _).symm + · rw [hips,hl,hd,hn] + simp [erase] + +def padPack (n gs : ℕ) : Pack:=vectorPack n ((List.range (n+gs)).map + (fun i=>if i((refs i).gate,(refs i).invert)))).val.value= + erase (AIGCompiler.compile g refs):=by + have hl : r.decls.length=g.decls.size:=by rw [hr.1,List.length_map,Array.length_toList] + have hp:=partialPack_value hr g.decls.size le_rfl + have hs : (compPack (padPack n r.decls.length) (partialPack n r.decls r.decls.length)).val.value= + erase ((BooleanNetwork.padRight n g.decls.size).comp (AIGCompiler.partialGraph g g.decls.size le_rfl)):=by + rw [compPack_value] + · rw [hl,padPack_value,hp,erase_comp] + · rw [hl,padPack_value,hp];simp [erase] + have hv : (vectorPack (n+r.decls.length) ((List.ofFn (fun i=>((refs i).gate,(refs i).invert))).map + (faninPack n r.decls.length))).val.value= + erase (BooleanNetwork.vector (fun i=>AIGCompiler.faninNet g (.mk (refs i).gate (refs i).invert))):=by + rw [hl,List.map_ofFn] + apply vectorPack_value + intro i + dsimp only [Function.comp_apply] + simpa only [AIG.Fanin.gate_mk,AIG.Fanin.invert_mk] using + faninPack_value g (.mk (refs i).gate (refs i).invert) + unfold compilePack + rw [compPack_value] + · rw [hs,hv];exact (erase_comp _ _).symm + · rw [hs,hv];simp [erase] +end ExactQuantumFactoring.AIGNetworkEmission + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/AIGNetworkProcedure.lean b/lean/OAI/Computability/QuantumFactoring/AIGNetworkProcedure.lean new file mode 100644 index 0000000000000000000000000000000000000000..b9042bb98e44e7ade9aed74a68decde41553d43d --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/AIGNetworkProcedure.lean @@ -0,0 +1,108 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.AIGNetworkEmission + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.AIGNetworkEmission +open BitStackProgram BitStackProgram.Procedure NetworkEmission +open NetworkEmission.Emission +namespace Emission +abbrev dimsCode:=prodCode unaryCode unaryCode +noncomputable def faninPackP : Procedure (prodCode dimsCode NativeAIG.refCode) packCode + (fun x=>faninPack x.1.1 x.1.2 x.2):=by + let e:=first dimsCode NativeAIG.refCode + let n:=(first unaryCode unaryCode).comp e + let gs:=(second unaryCode unaryCode).comp e + let w:=unaryAdd.comp (n.pair gs) + let ref:=second dimsCode NativeAIG.refCode + let idx:=(first Nat.bits boolCode).comp ref + let inv:=(second Nat.bits boolCode).comp ref + let off:=binaryAdd.comp ((unaryToBits.comp n).pair idx) + let v:=conditional (binaryLt.comp (idx.pair (unaryToBits.comp gs))) + (bitPackP.comp (w.pair off)) (constantPackP.comp (w.pair (Procedure.constant _ boolCode false))) + exact (conditional inv (bnotPackP.comp v) v).congrFun (by intro x;simp only [Function.comp_apply,id_eq,decide_eq_true_eq,faninPack]) + +def declTag : NativeAIG.Decl→ℕ | .zero=>0 | .atom _=>1 | .gate _ _=>2 +def declAtom : NativeAIG.Decl→ℕ | .atom i=>i | _=>0 +def declGate : NativeAIG.Decl→NativeAIG.Key | .gate a b=>(a,b) | _=>((0,false),(0,false)) +noncomputable def declTagP : Procedure NativeAIG.declCode Nat.bits declTag:= + ((casesSum (Procedure.constant emptyCode Nat.bits 0) + (casesSum (Procedure.constant Nat.bits Nat.bits 1) (Procedure.constant NativeAIG.keyCode Nat.bits 2))).precompose + NativeAIG.declView).congrFun (by intro d;cases d <;> rfl) +noncomputable def declAtomP : Procedure NativeAIG.declCode Nat.bits declAtom:= + ((casesSum (Procedure.constant emptyCode Nat.bits 0) + (casesSum (identity Nat.bits) (Procedure.constant NativeAIG.keyCode Nat.bits 0))).precompose + NativeAIG.declView).congrFun (by intro d;cases d <;> rfl) +noncomputable def declGateP : Procedure NativeAIG.declCode NativeAIG.keyCode declGate:= + ((casesSum (Procedure.constant emptyCode NativeAIG.keyCode ((0,false),(0,false))) + (casesSum (Procedure.constant Nat.bits NativeAIG.keyCode ((0,false),(0,false))) (identity NativeAIG.keyCode))).precompose + NativeAIG.declView).congrFun (by intro d;cases d <;> rfl) +noncomputable def nodePackP : Procedure (prodCode dimsCode NativeAIG.declCode) packCode + (fun x=>nodePack x.1.1 x.1.2 x.2):=by + let e:=first dimsCode NativeAIG.declCode + let w:=unaryAdd.comp e + let d:=second dimsCode NativeAIG.declCode + let tag:=declTagP.comp d + let z:=constantPackP.comp (w.pair (Procedure.constant _ boolCode false)) + let a:=bitPackP.comp (w.pair (declAtomP.comp d)) + let l:=(first NativeAIG.refCode NativeAIG.refCode).comp (declGateP.comp d) + let r:=(second NativeAIG.refCode NativeAIG.refCode).comp (declGateP.comp d) + let g:=bandPackP.comp ((faninPackP.comp (e.pair l)).pair (faninPackP.comp (e.pair r))) + exact (conditional (binaryEq.comp (tag.pair (Procedure.constant _ Nat.bits 0))) z + (conditional (binaryEq.comp (tag.pair (Procedure.constant _ Nat.bits 1))) a g)).congrFun (by + rintro ⟨e,d⟩;cases d <;> rfl) + +abbrev graphInputCode:=prodCode unaryCode (listCode NativeAIG.declCode) +noncomputable def partialPackP : Procedure (prodCode graphInputCode unaryCode) packCode + (fun x=>partialPack x.1.1 x.1.2 x.2):=by + let e:=second unaryCode graphInputCode + let n:=(first unaryCode (listCode NativeAIG.declCode)).comp e + let ds:=(second unaryCode (listCode NativeAIG.declCode)).comp e + let gs:=(NativeAIG.Emission.listUnaryLength NativeAIG.declCode .zero).comp ds + let w:=unaryAdd.comp (n.pair gs) + let i:=first unaryCode graphInputCode + let off:=binaryAdd.comp ((unaryToBits.comp n).pair (unaryToBits.comp i)) + let d:=(listGet NativeAIG.declCode .zero).comp ((unaryToBits.comp i).pair ds) + let node:=nodePackP.comp ((n.pair gs).pair d) + let step:=assignPackP.comp (w.pair (off.pair node)) + let input:=first graphInputCode unaryCode + let num:=second graphInputCode unaryCode + let parts:=(tabulate (f:=fun (x:ℕ×List NativeAIG.Decl) i=>assignPack (x.1+x.2.length) (x.1+i) + (nodePack x.1 x.2.length ((x.2.drop i).headD .zero))) emptyPack step).comp (num.pair input) + let nn:=(first unaryCode (listCode NativeAIG.declCode)).comp input + let gg:=(NativeAIG.Emission.listUnaryLength NativeAIG.declCode .zero).comp ((second unaryCode (listCode NativeAIG.declCode)).comp input) + exact foldCompP.comp (parts.pair (identityPackP.comp (unaryAdd.comp (nn.pair gg)))) +noncomputable def padPackP : Procedure dimsCode packCode (fun x=>padPack x.1 x.2):=by + let e:=second unaryCode dimsCode + let n:=(first unaryCode unaryCode).comp e + let i:=unaryToBits.comp (first unaryCode dimsCode) + let v:=conditional (binaryLt.comp (i.pair (unaryToBits.comp n))) + (bitPackP.comp (n.pair i)) (constantPackP.comp (n.pair (Procedure.constant _ boolCode false))) + let parts:=(tabulate (f:=fun (x:ℕ×ℕ) i=>if icompilePack x.1.1 x.1.2 x.2):=by + let e:=first graphInputCode (listCode NativeAIG.refCode) + let n:=(first unaryCode (listCode NativeAIG.declCode)).comp e + let ds:=(second unaryCode (listCode NativeAIG.declCode)).comp e + let gs:=(NativeAIG.Emission.listUnaryLength NativeAIG.declCode .zero).comp ds + let dim:=n.pair gs + let pad:=padPackP.comp dim + let graph:=partialPackP.comp (e.pair gs) + let refs:=second graphInputCode (listCode NativeAIG.refCode) + let parts:=(listMapWith (f:=fun (x:ℕ×ℕ) f=>faninPack x.1 x.2 f) (0,false) emptyPack faninPackP).comp (dim.pair refs) + let output:=vectorPackP.comp ((unaryAdd.comp dim).pair parts) + exact compPackP.comp ((compPackP.comp (pad.pair graph)).pair output) +end Emission +end ExactQuantumFactoring.AIGNetworkEmission + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/AKSBounds.lean b/lean/OAI/Computability/QuantumFactoring/AKSBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..f1265a00120bfb6bbffeb38d210e7e058426a771 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/AKSBounds.lean @@ -0,0 +1,70 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BoundedAKS + +namespace OAI + +section +open scoped BigOperators + + +namespace ExactQuantumFactoring.BitArithmetic +open BooleanNetwork + +abbrev aksBranchBound (n s w : ℕ) := + 216*w*w+154*w+27+1 + (n^2*(100*w+23+w*(3672*w*w+436*w+36))+1) + + (8*s*(216*w*w+203*w+38)+1) + (8*s*(cyclicTestBound s w+1)+1) + 3 + +lemma aksBranch_count (n s : ℕ) [NeZero s] : + (aksBranch n s).net.count ≤ aksBranchBound n s (rootWidth n) := by + have hd := dividesNet_count (rootWidth n) s + have ho := orderTests_count (rootWidth n) s (n^2) + have hs := noSmallDivisor_count (rootWidth n) (8*s) + have hc := allCongruences_count s (rootWidth n) + have hmul : (8*s-1)*(216*rootWidth n*rootWidth n+203*rootWidth n+38) ≤ + (8*s)*(216*rootWidth n*rootWidth n+203*rootWidth n+38) := by gcongr; omega + simp only [aksBranch,count_band,count_bnot] + dsimp [aksBranchBound] + omega + +lemma aksBranchBound_mono {n s s' w : ℕ} (hs : s ≤ s') : + aksBranchBound n s w ≤ aksBranchBound n s' w := by + unfold aksBranchBound + gcongr + exact cyclicTestBound_mono hs le_rfl + +lemma aksStaticBranch_count (n s : ℕ) (hs : s ≤ n^8) : + (aksStaticBranch n s).net.count ≤ aksBranchBound n (n^8) (rootWidth n) := by + by_cases hp : s.Prime + · let : NeZero s := ⟨hp.ne_zero⟩ + have he : aksStaticBranch n s = aksBranch n s := dite_eq_left hp + exact (congrArg (fun c : BooleanNetwork (rootWidth n) 1 => c.net.count) he).trans_le + ((aksBranch_count n s).trans (aksBranchBound_mono hs)) + · have he : aksStaticBranch n s = constant false := dite_eq_right hp + rw [he] + change 1 ≤ aksBranchBound n (n^8) (rootWidth n) + unfold aksBranchBound + omega + +abbrev primalityBound (n : ℕ) := + (n+1)*(perfectCheckBound n+4)+1+1 + + ((n^8+1)*(aksBranchBound n (n^8) (rootWidth n)+4)+1)+1 + +/-- Explicit polynomial size for the full exact primality network. -/ +theorem primalityNet_count (n : ℕ) : (primalityNet n).net.count ≤ primalityBound n := by + have hp := perfectPowerNet_count n + have ha := any_count (c := aksBranchBound n (n^8) (rootWidth n)) + (List.ofFn (fun s : Fin (n^8+1) => aksStaticBranch n s.val)) (by + intro c hc + obtain ⟨s,rfl⟩ := List.mem_ofFn.mp hc + exact aksStaticBranch_count n s.val (by omega)) + simp only [List.length_ofFn] at ha + simp only [primalityNet,count_band,count_bnot] + dsimp [primalityBound] + omega + +end ExactQuantumFactoring.BitArithmetic + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/AKSCriteria.lean b/lean/OAI/Computability/QuantumFactoring/AKSCriteria.lean new file mode 100644 index 0000000000000000000000000000000000000000..896bd6a43f9cf59e6c027a2311608320c113665c --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/AKSCriteria.lean @@ -0,0 +1,60 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.PrimalityCorrectness + +namespace OAI + +section + + +namespace ExactQuantumFactoring.Primality + +lemma prime_not_perfectPower {m : ℕ} (hm : m.Prime) : ¬ PerfectPower m := by + rintro ⟨b,e,hb,he,h⟩ + have hd : b ∣ m := by rw [← h]; exact dvd_pow_self b (by omega) + have hbm : b=m := (hm.eq_one_or_self_of_dvd b hd).resolve_left (by omega) + subst b + have hlt : m < m^e := by + simpa using Nat.pow_lt_pow_right (by omega : 1 < m) (by omega : 1 < e) + omega + +lemma order_tests_iff {m s k : ℕ} (hs : s.Prime) (hcop : s.Coprime m) : + (∀ j : ℕ, 1 ≤ j → j ≤ k → m^j%s ≠ 1) ↔ k < orderOf (m : ZMod s) := by + let : Fact s.Prime := ⟨hs⟩ + have ho : 0 < orderOf (m : ZMod s) := + ((ZMod.isUnit_iff_coprime m s).mpr hcop.symm).isOfFinOrder.orderOf_pos + have hp (j : ℕ) : m^j%s=1 ↔ (m : ZMod s)^j=1 := by + constructor + · intro h + have : ((m^j%s : ℕ) : ZMod s)=(1 : ZMod s) := by + simpa only [Nat.cast_one] using congrArg (fun a : ℕ => (a : ZMod s)) h + simpa only [ZMod.natCast_mod,Nat.cast_pow,Nat.cast_one] using this + · intro h + have := congrArg ZMod.val h + simpa only [← Nat.cast_pow,ZMod.val_natCast,ZMod.val_one] using this + constructor + · intro h + by_contra hn + exact h _ ho (by omega) ((hp _).mpr (pow_orderOf_eq_one (m : ZMod s))) + · intro h j hj hk hh + exact pow_ne_one_of_lt_orderOf (by omega) (hk.trans_lt h) ((hp j).mp hh) + +lemma prime_of_no_small_divisor {m B : ℕ} (hm : 2 ≤ m) (hb : m ≤ B) + (h : ∀ d : ℕ, 2 ≤ d → d ≤ B → d < m → ¬ d ∣ m) : m.Prime := by + rw [Nat.prime_def_lt] + refine ⟨hm,?_⟩ + intro d hd hdm + by_contra hne + have hd2 : 2 ≤ d := by + by_contra hn + have : d=0 := by omega + subst d + simp only [Nat.zero_dvd] at hdm + omega + exact h d hd2 (by omega) hd hdm + +end ExactQuantumFactoring.Primality + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/AKSNetworks.lean b/lean/OAI/Computability/QuantumFactoring/AKSNetworks.lean new file mode 100644 index 0000000000000000000000000000000000000000..8daa16e1ab49d121a5e4111b80afef2f3b076dea --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/AKSNetworks.lean @@ -0,0 +1,110 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BooleanFold +import OAI.Computability.QuantumFactoring.StaticPredicates + +namespace OAI + +section +open scoped BigOperators + + +namespace ExactQuantumFactoring.BooleanNetwork + +lemma all_ofFn_eval {n k : ℕ} (cs : Fin k → BooleanNetwork n 1) (x : Basis n) : + (all (List.ofFn cs)).eval x 0=true ↔ ∀ i, (cs i).eval x 0=true := by + rw [all_eval] + simp + +lemma any_ofFn_eval {n k : ℕ} (cs : Fin k → BooleanNetwork n 1) (x : Basis n) : + (any (List.ofFn cs)).eval x 0=true ↔ ∃ i, (cs i).eval x 0=true := by + rw [any_eval] + simp + +lemma bnot_value {n : ℕ} (c : BooleanNetwork n 1) (x : Basis n) : + c.bnot.eval x 0=true ↔ ¬ c.eval x 0=true := by simp + +end ExactQuantumFactoring.BooleanNetwork + +namespace ExactQuantumFactoring.BitArithmetic +open BooleanNetwork + +def orderTests (w s k : ℕ) : BooleanNetwork w 1 := + all (List.ofFn (fun i : Fin k => (powerOneNet w s (i.val+1)).bnot)) + +lemma orderTests_value (w s k : ℕ) (x : Basis w) (hs : 2 ≤ s) + (hsw : s < 2^w) (hkw : k < 2^w) : + (orderTests w s k).eval x 0=true ↔ + ∀ j : ℕ, 1 ≤ j → j ≤ k → (bitsValue x).toNat^j%s ≠ 1 := by + rw [orderTests,all_ofFn_eval] + constructor + · intro h j hj hjk + have hh := (bnot_value _ _).mp (h (⟨j-1,by omega⟩ : Fin k)) + rw [powerOneNet_value _ _ _ _ hs hsw (by omega)] at hh + simpa only [show j-1+1=j by omega] using hh + · intro h i + rw [bnot_value,powerOneNet_value _ _ _ _ hs hsw (by have := i.isLt;omega)] + exact h (i.val+1) (by omega) (by omega) + +lemma orderTests_count (w s k : ℕ) : (orderTests w s k).net.count ≤ + k*(100*w+23+w*(3672*w*w+436*w+36))+1 := by + have h := all_count (c := 100*w+22+w*(3672*w*w+436*w+36)) + (List.ofFn (fun i : Fin k => (powerOneNet w s (i.val+1)).bnot)) (by + intro c hc + obtain ⟨i,rfl⟩ := List.mem_ofFn.mp hc + rw [count_bnot] + have := powerOneNet_count w s (i.val+1) + omega) + convert h using 1 <;> simp only [orderTests,List.length_ofFn] + ring + +def properDivisor (w d : ℕ) : BooleanNetwork w 1 := + (dividesNet w d).band (wordLt (wordConstant (BitVec.ofNat w d)) (select id)) + +lemma properDivisor_value (w d : ℕ) (x : Basis w) (hd : d < 2^w) : + (properDivisor w d).eval x 0=true ↔ d ∣ (bitsValue x).toNat ∧ d < (bitsValue x).toNat := by + rw [properDivisor,eval_band,Bool.and_eq_true,dividesNet_value _ _ _ hd, + wordLt_eval,wordConstant_eval,eval_select,Function.comp_id,BitVec.toNat_ofNat, + Nat.mod_eq_of_lt hd,decide_eq_true_eq] + +lemma properDivisor_count (w d : ℕ) : + (properDivisor w d).net.count ≤ 216*w*w+203*w+36 := by + have h := wordLt_count (wordConstant (n := w) (BitVec.ofNat w d)) (select id) + rw [wordConstant_count,count_select] at h + have hd := dividesNet_count w d + rw [properDivisor,count_band] + omega + +def noSmallDivisor (w B : ℕ) : BooleanNetwork w 1 := + all (List.ofFn (fun i : Fin (B-1) => (properDivisor w (i.val+2)).bnot)) + +lemma noSmallDivisor_value (w B : ℕ) (x : Basis w) (hB : B < 2^w) : + (noSmallDivisor w B).eval x 0=true ↔ + ∀ d : ℕ, 2 ≤ d → d ≤ B → d < (bitsValue x).toNat → ¬ d ∣ (bitsValue x).toNat := by + rw [noSmallDivisor,all_ofFn_eval] + constructor + · intro h d hd hdB hdm hdiv + have hh := (bnot_value _ _).mp (h (⟨d-2,by omega⟩ : Fin (B-1))) + rw [properDivisor_value _ _ _ (by omega)] at hh + exact hh (by simpa [show d-2+2=d by omega] using And.intro hdiv hdm) + · intro h i + rw [bnot_value,properDivisor_value _ _ _ (by have := i.isLt;omega)] + rintro ⟨hd,hlt⟩ + exact h (i.val+2) (by omega) (by omega) hlt hd + +lemma noSmallDivisor_count (w B : ℕ) : (noSmallDivisor w B).net.count ≤ + (B-1)*(216*w*w+203*w+38)+1 := by + have h := all_count (c := 216*w*w+203*w+37) + (List.ofFn (fun i : Fin (B-1) => (properDivisor w (i.val+2)).bnot)) (by + intro c hc + obtain ⟨i,rfl⟩ := List.mem_ofFn.mp hc + rw [count_bnot] + have := properDivisor_count w (i.val+2) + omega) + simpa only [noSmallDivisor,List.length_ofFn] using h + +end ExactQuantumFactoring.BitArithmetic + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/ActualDivisorPolynomial.lean b/lean/OAI/Computability/QuantumFactoring/ActualDivisorPolynomial.lean new file mode 100644 index 0000000000000000000000000000000000000000..fd640788aaa8c50465e8388f71082e95ac232479 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/ActualDivisorPolynomial.lean @@ -0,0 +1,56 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.PhysicalSplitDecoder +import OAI.Computability.QuantumFactoring.OrderDecoderPolynomial +import OAI.Computability.QuantumFactoring.SplitDecoderPolynomial + +namespace OAI + + + +section + +namespace ExactQuantumFactoring +open BooleanNetwork BitArithmetic +namespace FixedSplit +lemma actualBaseNet_poly : NetworkAt (fun xi:Σn,Fin (n^5)=>xi.1) (fun xi=>actualBaseNet xi.2) := by + simpa only [NetworkAt,actualBaseNet,count_comp,launchWires,count_select,Nat.zero_add, + baseNet_count] using PolyAt.ofPoly PreparationPolynomial.listOutput (fun xi:Σn,Fin (n^5)=>xi.1) +lemma modulusNet_poly : NetworkAt id modulusNet := + (NetworkAt.select _).comp (NetworkAt.select _) +lemma actualOrderRawNet_poly : NetworkAt (fun xi:Σn,Fin (n^5)=>xi.1) (fun xi=>actualOrderRawNet xi.2) := + (NetworkAt.select _).comp (NetworkAt.select _) +lemma actualOrderNet_poly : NetworkAt (fun xi:Σn,Fin (n^5)=>xi.1) (fun xi=>actualOrderNet xi.2) := + OrderSlots.outputOn_poly actualBaseNet_poly (modulusNet_poly.pull Sigma.fst) actualOrderRawNet_poly +lemma liftedModulus_poly : NetworkAt id liftedModulus := + modulusNet_poly.comp (NetworkAt.resizeWord (PolyAt.self id) ((PolyAt.self id).add (PolyAt.const id 1))) +lemma roots_poly : NetworkAt id (fun n=>rootsOn n (liftedModulus n)) := + liftedModulus_poly.rootsOn (PolyAt.self id) +lemma ordersBits_poly : NetworkAt id (fun n=>ordersBits (liftedModulus n) (actualPairs n)) := by + let len : (Σn,Fin (n^5))→ℕ:=Sigma.fst + have hn:=PolyAt.self len + have hw:=hn.add (PolyAt.const len 1) + have hm:=liftedModulus_poly.pull (Sigma.fst (β:=fun n=>Fin (n^5))) + have he:=PolyAt.ofPoly PreparationPolynomial.transitionWidth len + obtain ⟨p,hp⟩:=((actualBaseNet_poly.comp (NetworkAt.resizeWord hn hw)).candidateBits hm + actualOrderNet_poly hw he) + apply NetworkAt.firstProperNet liftedModulus_poly + ((PolyAt.self id).add (PolyAt.const id 1)) + (by simpa only [actualPairs,List.length_map,List.length_ofFn,id_eq] using (PolyAt.self (id : ℕ→ℕ)).pow 5) + refine ⟨p,?_⟩ + intro n d hd + obtain ⟨ar,har,rfl⟩:=List.mem_map.mp hd + obtain ⟨i,rfl⟩:=List.mem_ofFn.mp har + exact hp ⟨n,i⟩ +lemma divisorNet_poly : NetworkPoly divisorNet := by + have hn:=PolyAt.self (id : ℕ→ℕ) + have hw:=hn.add (PolyAt.const id 1) + exact (liftedModulus_poly.evenOn hw).wordMux (NetworkAt.wordConstant _ hw) + ((liftedModulus_poly.properOn roots_poly hw).wordMux roots_poly ordersBits_poly hw) hw +end FixedSplit +end ExactQuantumFactoring + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/AdaptivePrepared.lean b/lean/OAI/Computability/QuantumFactoring/AdaptivePrepared.lean new file mode 100644 index 0000000000000000000000000000000000000000..7ecc88e9c728958f3f39a76a85c4b3468973aea4 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/AdaptivePrepared.lean @@ -0,0 +1,67 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.InitialOrderState +import OAI.Computability.QuantumFactoring.PreparedOracle + +namespace OAI + +section +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators + + +namespace ExactQuantumFactoring +open scoped BigOperators +open BooleanNetwork + +/-- A coherent fresh launch on an encoded old history. The local law refers +only to the actually computed Boolean initializer, never to a selected outcome. -/ +lemma preparedOracle_encode {α β : Type*} [Fintype α] [Fintype β] {p q r : ℕ} + (e : α→Basis p) (f : β→Basis q) (ψ : α→ℂ) (F : α→β→ℂ) + (c : BooleanNetwork p q) (hc : c.net.count ≤ r) (ops : List (Instruction q)) + (hlocal : ∀ a,(programMatrix ops).mulVec (basisVector (c.eval (e a)))=encodeState f (F a)) : + (programMatrix (preparedOracle c hc ops)).mulVec + (encodeState (fun a=>packed r (e a) (fun _=>false)) ψ)= + encodeState (fun ab : α×β=>packed r (e ab.1) (f ab.2)) (RecordedHistory.appendState ψ F) := by + rw [encodeState,Matrix.mulVec_sum] + simp only [Matrix.mulVec_smul,preparedOracle_basis,hlocal,encodeState_comp] + unfold encodeState RecordedHistory.appendState + rw [Fintype.sum_prod_type] + apply Finset.sum_congr rfl + intro a _ + rw [Finset.smul_sum] + apply Finset.sum_congr rfl + intro b _ + rw [smul_smul] + rfl + +def appendPrepared {p q r : ℕ} (A : List (Instruction p)) (c : BooleanNetwork p q) + (hc : c.net.count ≤ r) (ops : List (Instruction q)) : List (Instruction (p+q+r)) := + firstProgram q r A++preparedOracle c hc ops + +lemma appendPrepared_length {p q r : ℕ} (A : List (Instruction p)) (c : BooleanNetwork p q) + (hc : c.net.count ≤ r) (ops : List (Instruction q)) : + (appendPrepared A c hc ops).length ≤ A.length+4*c.net.count+2*q+ops.length := by + have h := preparedOracle_length c hc ops + simp only [appendPrepared,List.length_append,firstProgram_length] + omega + +lemma appendPrepared_state {α β : Type*} [Fintype α] [Fintype β] {p q r : ℕ} + (e : α→Basis p) (f : β→Basis q) (ψ : α→ℂ) (F : α→β→ℂ) + (A : List (Instruction p)) (v : Basis p) + (hA : (programMatrix A).mulVec (basisVector v)=encodeState e ψ) + (c : BooleanNetwork p q) (hc : c.net.count ≤ r) (ops : List (Instruction q)) + (hlocal : ∀ a,(programMatrix ops).mulVec (basisVector (c.eval (e a)))=encodeState f (F a)) : + (programMatrix (appendPrepared A c hc ops)).mulVec (basisVector (packed r v (fun _=>false)))= + encodeState (fun ab : α×β=>packed r (e ab.1) (f ab.2)) (RecordedHistory.appendState ψ F) := by + rw [appendPrepared,programMatrix_append,←Matrix.mulVec_mulVec,firstProgram_basis,hA,encodeState_comp] + exact preparedOracle_encode e f ψ F c hc ops hlocal + +end ExactQuantumFactoring + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/AppendRegister.lean b/lean/OAI/Computability/QuantumFactoring/AppendRegister.lean new file mode 100644 index 0000000000000000000000000000000000000000..66b554eb216ead534d3ce2645df9eb621bd84ee5 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/AppendRegister.lean @@ -0,0 +1,63 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.RegisterEncoded + +namespace OAI + +section +open scoped BigOperators + + +namespace ExactQuantumFactoring +open scoped BigOperators + +def rightRegister (p q : ℕ) : Register q (p+q) := ⟨Fin.natAdd p, Fin.natAdd_injective q p⟩ + +lemma append_rightRegister {p q : ℕ} (x : Basis p) (y : Basis q) : + Fin.append x y ∘ rightRegister p q = y := by + funext i + exact Fin.append_right _ _ i + +lemma append_right_injective {p q : ℕ} (x : Basis p) : + Function.Injective (Fin.append x : Basis q → Basis (p+q)) := by + intro y z h + have hh := congrArg (fun v => v ∘ rightRegister p q) h + simpa only [append_rightRegister] using hh + +lemma append_replace_right {p q : ℕ} (x : Basis p) (y z : Basis q) : + (rightRegister p q).replace (Fin.append x y) z = Fin.append x z := by + funext i + refine Fin.addCases (fun j => ?_) (fun j => ?_) i + · have hj : ∀ k, rightRegister p q k ≠ j.castAdd q := by + intro k h + have hh := congrArg Fin.val h + change p+k.val=j.val at hh + have := j.isLt + omega + rw [Register.replace_outside _ _ _ ⟨j.castAdd q,hj⟩] + simp only [Fin.append_left] + · change (rightRegister p q).replace (Fin.append x y) z (rightRegister p q j) = _ + rw [Register.replace_inside,Fin.append_right] + +def rightProgram {q : ℕ} (p : ℕ) (ops : List (Instruction q)) : + List (Instruction (p+q)) := ops.map (Instruction.place (rightRegister p q)) + +lemma rightProgram_basis {p q : ℕ} (ops : List (Instruction q)) (x : Basis p) (y : Basis q) : + (programMatrix (rightProgram p ops)).mulVec (basisVector (Fin.append x y)) = + encodeState (Fin.append x) ((programMatrix ops).mulVec (basisVector y)) := by + rw [rightProgram,Register.placed_basis_state,append_rightRegister] + congr 1 + funext z + exact append_replace_right x y z + +lemma rightProgram_entry {p q : ℕ} (ops : List (Instruction q)) (x : Basis p) (y z : Basis q) : + programMatrix (rightProgram p ops) (Fin.append x z) (Fin.append x y) = + programMatrix ops z y := by + have hh := congrFun (rightProgram_basis ops x y) (Fin.append x z) + simpa only [encodeState_at _ (append_right_injective x),matrix_basisVector] using hh + +end ExactQuantumFactoring + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/ArithmeticBounds.lean b/lean/OAI/Computability/QuantumFactoring/ArithmeticBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..ff44dd4d50aeab9e54ea6cdfe0f484faeac7fea4 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/ArithmeticBounds.lean @@ -0,0 +1,79 @@ +import Mathlib + +namespace OAI + +section +open scoped BigOperators + + +open scoped BigOperators +namespace ExactQuantumFactoring + +/-- The telescoping estimate for any distinct integers at least two. -/ +theorem prod_le_card_mul_pred_prod (s : Finset ℕ) (hs : ∀ p ∈ s, 2 ≤ p) : + (∏ p ∈ s, p) ≤ (s.card + 1) * ∏ p ∈ s, (p - 1) := by + induction s using Finset.induction_on_max with + | empty => simp + | insert a s hmax ih => + have ha : a ∉ s := fun h => (lt_irrefl a) (hmax a h) + have ha2 : 2 ≤ a := hs a (Finset.mem_insert_self _ _) + have hs2 : ∀ p ∈ s, 2 ≤ p := fun p hp => hs p (Finset.mem_insert_of_mem hp) + have hc : s.card + 2 ≤ a := by + have hass : s ⊆ Finset.Ico 2 a := fun p hp => Finset.mem_Ico.mpr ⟨hs2 p hp, hmax p hp⟩ + have := Finset.card_le_card hass + rw [Nat.card_Ico] at this + omega + have hstep : a * (s.card + 1) ≤ (s.card + 2) * (a - 1) := by + have : a - 1 + 1 = a := by omega + nlinarith + simp only [Finset.prod_insert ha, Finset.card_insert_of_notMem ha] + calc + a * ∏ p ∈ s, p ≤ a * ((s.card + 1) * ∏ p ∈ s, (p - 1)) := + Nat.mul_le_mul_left _ (ih hs2) + _ ≤ (s.card + 1 + 1) * (a - 1) * ∏ p ∈ s, (p - 1) := by + simpa [Nat.mul_assoc] using Nat.mul_le_mul_right (∏ p ∈ s, (p - 1)) hstep + _ = (s.card + 1 + 1) * ((a - 1) * ∏ p ∈ s, (p - 1)) := by ring + +/-- The number of distinct prime factors is less than a strict binary cutoff. -/ +theorem primeFactors_card_lt {d n : ℕ} (hd : 0 < d) (hb : d < 2 ^ n) : + d.primeFactors.card < n := by + have hp : 2 ^ d.primeFactors.card ≤ ∏ p ∈ d.primeFactors, p := by + rw [← Finset.prod_const] + exact Finset.prod_le_prod + (fun prime hprime => (Nat.prime_of_mem_primeFactors hprime).two_le) + have hp' : (∏ p ∈ d.primeFactors, p) ≤ d := + Nat.le_of_dvd hd (Nat.prod_primeFactors_dvd d) + exact (Nat.pow_lt_pow_iff_right (by decide : 1 < 2)).mp (hp.trans_lt (hp'.trans_lt hb)) + +/-- Integer form of (5.2), retaining the original global binary cutoff. -/ +theorem le_succ_mul_totient {d n : ℕ} (hd : 0 < d) (hb : d < 2 ^ n) : + d ≤ (n + 1) * Nat.totient d := by + have hp := prod_le_card_mul_pred_prod d.primeFactors + (fun p hp => (Nat.prime_of_mem_primeFactors hp).two_le) + have hprodpos : 0 < ∏ p ∈ d.primeFactors, (p - 1) := by + apply Finset.prod_pos + intro p hp + have := (Nat.prime_of_mem_primeFactors hp).two_le + omega + have hx := Nat.mul_le_mul_left (Nat.totient d) hp + rw [Nat.totient_mul_prod_primeFactors] at hx + have hbase : d ≤ (d.primeFactors.card + 1) * Nat.totient d := by + apply Nat.le_of_mul_le_mul_right (c := ∏ p ∈ d.primeFactors, (p - 1)) _ hprodpos + simpa [Nat.mul_assoc, Nat.mul_left_comm, Nat.mul_comm] using hx + exact hbase.trans (Nat.mul_le_mul_right _ (by have := primeFactors_card_lt hd hb; omega)) + +/-- Real ratio version, ready for the exact transition-probability bound. -/ +theorem totient_ratio_lower {d n : ℕ} (hd : 0 < d) (hb : d < 2 ^ n) : + 1 / ((n : ℝ) + 1) ≤ (Nat.totient d : ℝ) / d := by + have hn : 0 < (n : ℝ) + 1 := by positivity + have hd' : 0 < (d : ℝ) := by exact_mod_cast hd + rw [div_le_div_iff₀ hn hd'] + norm_num only [one_mul] + exact_mod_cast (le_succ_mul_totient hd hb).trans_eq (Nat.mul_comm _ _) + +end ExactQuantumFactoring + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/ArithmeticPredicates.lean b/lean/OAI/Computability/QuantumFactoring/ArithmeticPredicates.lean new file mode 100644 index 0000000000000000000000000000000000000000..eecde1204fe206d2377a54503d85627d3f56cc80 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/ArithmeticPredicates.lean @@ -0,0 +1,143 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.WordNetworks + +namespace OAI + +section +open scoped BigOperators + + +namespace ExactQuantumFactoring.BitArithmetic +open Std.Sat Std.Tactic.BVDecide +open AIGCompiler BooleanNetwork + +def ult (w : ℕ) : BooleanNetwork (w+w) 1 := + let r := BVPred.mkUlt (inputs (w+w)).1 (binaryInputs w) + compile r.aig (fun _ => r.ref) + +lemma ult_correct (w : ℕ) (a b : Basis w) : + (ult w).eval (Fin.append a b) 0 = + decide ((bitsValue a).toNat < (bitsValue b).toNat) := by + rw [ult,compile_correct] + have h := BVPred.mkUlt_denote_eq (inputs (w+w)).1 + (leftWord (Fin.append a b)) (rightWord (Fin.append a b)) + (binaryInputs w) (Fin.append a b) (binaryInputs_left w _) (binaryInputs_right w _) + simpa only [leftWord_append,rightWord_append,BitVec.ult] using h + +lemma ult_count (w : ℕ) : (ult w).net.count ≤ 48*w+8 := by + have h := compile_count (BVPred.mkUlt (inputs (w+w)).1 (binaryInputs w)).aig + (m := 1) (fun _ => (BVPred.mkUlt (inputs (w+w)).1 (binaryInputs w)).ref) + have hs := AIGBounds.ult_size (inputs (w+w)).1 (binaryInputs w) + rw [inputs_size] at hs + dsimp only [ult] + omega + +def wordLt {n w : ℕ} (a b : BooleanNetwork n w) : BooleanNetwork n 1 := + (a.pair b).comp (ult w) + +lemma wordLt_eval {n w : ℕ} (a b : BooleanNetwork n w) (x : Basis n) : + (wordLt a b).eval x 0 = decide ((bitsValue (a.eval x)).toNat < (bitsValue (b.eval x)).toNat) := by + rw [wordLt,eval_comp,eval_pair,ult_correct] + +lemma wordLt_count {n w : ℕ} (a b : BooleanNetwork n w) : + (wordLt a b).net.count ≤ a.net.count+b.net.count+48*w+8 := by + simp only [wordLt,count_comp,count_pair] + have := ult_count w + omega + +def wordLe {n w : ℕ} (a b : BooleanNetwork n w) : BooleanNetwork n 1 := + (wordLt b a).bnot + +lemma wordLe_eval {n w : ℕ} (a b : BooleanNetwork n w) (x : Basis n) : + (wordLe a b).eval x 0 = decide ((bitsValue (a.eval x)).toNat ≤ (bitsValue (b.eval x)).toNat) := by + rw [wordLe,eval_bnot,wordLt_eval] + by_cases h : (bitsValue (a.eval x)).toNat ≤ (bitsValue (b.eval x)).toNat + · simp [h,Nat.not_lt.mpr h] + · simp [h,Nat.lt_of_not_ge h] + +lemma wordLe_count {n w : ℕ} (a b : BooleanNetwork n w) : + (wordLe a b).net.count ≤ a.net.count+b.net.count+48*w+9 := by + simp only [wordLe,count_bnot] + have := wordLt_count b a + omega + +def wordEq (w : ℕ) : BooleanNetwork (w+w) 1 := + ((ult w).bor (((select (Fin.addCases (Fin.natAdd w) (Fin.castAdd w))).comp (ult w)))).bnot + +lemma wordEq_eval (w : ℕ) (a b : Basis w) : + (wordEq w).eval (Fin.append a b) 0 = decide (bitsValue a = bitsValue b) := by + have he : (select (Fin.addCases (Fin.natAdd w) (Fin.castAdd w))).eval (Fin.append a b) = + Fin.append b a := by + funext i + refine Fin.addCases (fun j => ?_) (fun j => ?_) i <;> + simp only [eval_select,Function.comp_apply,Fin.addCases_left,Fin.addCases_right, + Fin.append_left,Fin.append_right] + rw [wordEq,eval_bnot,eval_bor,eval_comp,he,ult_correct,ult_correct] + have hh : bitsValue a = bitsValue b ↔ (bitsValue a).toNat=(bitsValue b).toNat := by + constructor + · exact congrArg BitVec.toNat + · exact BitVec.eq_of_toNat_eq + simp only [hh] + cases h₁ : decide ((bitsValue a).toNat < (bitsValue b).toNat) <;> + cases h₂ : decide ((bitsValue b).toNat < (bitsValue a).toNat) <;> + simp_all <;> omega + +lemma wordEq_count (w : ℕ) : (wordEq w).net.count ≤ 96*w+21 := by + simp only [wordEq,count_bnot,count_bor,count_comp,count_select,zero_add] + have := ult_count w + omega + +/-- Static natural exponent, with retained accumulator and no repeated +construction of earlier expressions. This circuit has O(e w²) Boolean nodes. -/ +def staticPowerStep (w : ℕ) : BooleanNetwork (w+w) (w+w) := + (select (Fin.castAdd w)).pair (mul w) + +def staticPower (w e : ℕ) : BooleanNetwork w w := + ((select id).pair (wordConstant (BitVec.ofNat w 1))).comp + (((staticPowerStep w).iterate e).rewire (Fin.natAdd w)) + +lemma staticPowerStep_eval (w : ℕ) (a b : Basis w) : + (staticPowerStep w).eval (Fin.append a b) = + Fin.append a ((mul w).eval (Fin.append a b)) := by + simp only [staticPowerStep,eval_pair,eval_select] + congr 1 + funext i + exact Fin.append_left a b i + +lemma staticPower_iterate (w e : ℕ) (a b : Basis w) : + ∃ z : Basis w, + ((staticPowerStep w).iterate e).eval (Fin.append a b) = Fin.append a z ∧ + bitsValue z = bitsValue a^e * bitsValue b := by + induction e generalizing b with + | zero => refine ⟨b,?_,?_⟩ <;> simp [eval_iterate] + | succ e ih => + rw [eval_iterate,Function.iterate_succ_apply,staticPowerStep_eval] + have h := ih ((mul w).eval (Fin.append a b)) + rw [eval_iterate] at h + obtain ⟨z,hz,hv⟩ := h + refine ⟨z,hz,?_⟩ + rw [hv,mul_word,pow_succ] + exact (mul_assoc _ _ _).symm + +lemma staticPower_eval (w e : ℕ) (a : Basis w) : + bitsValue ((staticPower w e).eval a) = bitsValue a^e := by + simp only [staticPower,eval_comp,eval_pair,eval_select,Function.comp_id,eval_rewire] + obtain ⟨z,hz,hv⟩ := staticPower_iterate w e a ((wordConstant (BitVec.ofNat w 1)).eval a) + rw [hz] + have he : Fin.append a z ∘ Fin.natAdd w = z := by funext i; exact Fin.append_right _ _ i + rw [he,hv,wordConstant_eval] + simp + +lemma staticPower_count (w e : ℕ) : (staticPower w e).net.count ≤ + w+e*(90*w*w+14*w+6) := by + simp only [staticPower,count_comp,count_pair,count_select,wordConstant_count,zero_add, + count_rewire,count_iterate,staticPowerStep] + have h := mul_count w + exact Nat.add_le_add_left (Nat.mul_le_mul_left e h) w + +end ExactQuantumFactoring.BitArithmetic + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/ArithmeticSyntaxEmission.lean b/lean/OAI/Computability/QuantumFactoring/ArithmeticSyntaxEmission.lean new file mode 100644 index 0000000000000000000000000000000000000000..8068da3fc2fc43ef8186f0f2636460cde28d6127 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/ArithmeticSyntaxEmission.lean @@ -0,0 +1,89 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.RationalConditionals +import OAI.Computability.QuantumFactoring.RationalRounding +import OAI.Computability.QuantumFactoring.BitStackRationals +import OAI.Computability.QuantumFactoring.SignedSyntaxEmission + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.NetworkEmission.Emits +open BitStackProgram BitStackProgram.Emits +variable {α v : Type} {ea : α→List Bool} {ev : v→List Bool} +local notation "NEm" => BitStackProgram.Emits ea (exprCode ev) +local notation "IEm" => BitStackProgram.Emits ea (intExprCode ev) +local notation "REm" => BitStackProgram.Emits ea (ratExprCode ev) +lemma iOfNat {a : α→NatExpr v} (ha : NEm a) : IEm (fun x=>IntExpr.ofNat (a x)):= + imk ha (const _ _ (NatExpr.const 0)) +lemma iOfInt {a : α→ℤ} (ha : BitStackProgram.Emits ea intCode a) : IEm (fun x=>IntExpr.ofInt (a x)):=by + exact imk (nconst ((ofProcedure Emission.intToNatP).comp ha)) + (nconst ((ofProcedure Emission.intToNatP).comp ((ofProcedure Procedure.intNeg).comp ha))) +lemma iAdd {a b : α→IntExpr v} (ha : IEm a) (hb : IEm b) : IEm (fun x=>(a x).add (b x)):= + imk (nadd (ipos ha) (ipos hb)) (nadd (ineg ha) (ineg hb)) +lemma iNeg {a : α→IntExpr v} (ha : IEm a) : IEm (fun x=>(a x).negation):=imk (ineg ha) (ipos ha) +lemma iSub {a b : α→IntExpr v} (ha : IEm a) (hb : IEm b) : IEm (fun x=>(a x).sub (b x)):=iAdd ha (iNeg hb) +lemma iMul {a b : α→IntExpr v} (ha : IEm a) (hb : IEm b) : IEm (fun x=>(a x).mul (b x)):=by + unfold IntExpr.mul;expr_emit +lemma iScale {a : α→IntExpr v} {b : α→NatExpr v} (ha : IEm a) (hb : NEm b) : + IEm (fun x=>(a x).scale (b x)):=iMul ha (iOfNat hb) +lemma iToNat {a : α→IntExpr v} (ha : IEm a) : NEm (fun x=>(a x).toNat):=nsub (ipos ha) (ineg ha) +lemma iNatAbs {a : α→IntExpr v} (ha : IEm a) : NEm (fun x=>(a x).natAbs):= + nadd (nsub (ipos ha) (ineg ha)) (nsub (ineg ha) (ipos ha)) +lemma iIte {a b : α→NatExpr v} {c d : α→IntExpr v} (ha : NEm a) (hb : NEm b) (hc : IEm c) (hd : IEm d) : + IEm (fun x=>IntExpr.iteLe (a x) (b x) (c x) (d x)):=by unfold IntExpr.iteLe;expr_emit +lemma iIfLe {a b c d : α→IntExpr v} (ha : IEm a) (hb : IEm b) (hc : IEm c) (hd : IEm d) : + IEm (fun x=>IntExpr.ifLe (a x) (b x) (c x) (d x)):= + iIte (nadd (ipos ha) (ineg hb)) (nadd (ipos hb) (ineg ha)) hc hd +lemma rOfInt {a : α→IntExpr v} (ha : IEm a) : REm (fun x=>RatExpr.ofInt (a x)):=rmk ha (const _ _ (NatExpr.const 1)) +lemma rOfNat {a : α→NatExpr v} (ha : NEm a) : REm (fun x=>RatExpr.ofNat (a x)):=rOfInt (iOfNat ha) +lemma rConst {a : α→ℚ} (ha : BitStackProgram.Emits ea ratCode a) : REm (fun x=>RatExpr.const (a x)):= + rmk (iOfInt ((ofProcedure Procedure.ratNum).comp ha)) (nconst ((ofProcedure Procedure.ratDen).comp ha)) +lemma rNormalize {a : α→RatExpr v} (ha : REm a) : REm (fun x=>(a x).normalize):= + rmk (iIte (rden ha) (const _ _ (NatExpr.const 0)) (const _ _ (IntExpr.ofInt 0)) (rnum ha)) + (nite (rden ha) (const _ _ (NatExpr.const 0)) (const _ _ (NatExpr.const 1)) (rden ha)) +lemma rAdd {a b : α→RatExpr v} (ha : REm a) (hb : REm b) : REm (fun x=>(a x).add (b x)):=by + have hc:=rNormalize ha;have hd:=rNormalize hb + exact rmk (iAdd (iScale (rnum hc) (rden hd)) (iScale (rnum hd) (rden hc))) (nmul (rden hc) (rden hd)) +lemma rNeg {a : α→RatExpr v} (ha : REm a) : REm (fun x=>(a x).negation):=rmk (iNeg (rnum ha)) (rden ha) +lemma rSub {a b : α→RatExpr v} (ha : REm a) (hb : REm b) : REm (fun x=>(a x).sub (b x)):=rAdd ha (rNeg hb) +lemma rMul {a b : α→RatExpr v} (ha : REm a) (hb : REm b) : REm (fun x=>(a x).mul (b x)):= + rmk (iMul (rnum ha) (rnum hb)) (nmul (rden ha) (rden hb)) +lemma rInv {a : α→RatExpr v} (ha : REm a) : REm (fun x=>(a x).inverse):= + rmk (iScale (rnum ha) (rden ha)) (nmul (iNatAbs (rnum ha)) (iNatAbs (rnum ha))) +lemma rDiv {a b : α→RatExpr v} (ha : REm a) (hb : REm b) : REm (fun x=>(a x).div (b x)):=rMul ha (rInv hb) +lemma rPow {a : α→RatExpr v} (ha : REm a) (k : ℕ) : REm (fun x=>(a x).pow k):=by + induction k with + | zero=>exact const _ _ (RatExpr.const 1) + | succ k ih=>exact rMul ih ha +lemma rIfNatLe {a b : α→NatExpr v} {c d : α→RatExpr v} (ha : NEm a) (hb : NEm b) (hc : REm c) (hd : REm d) : + REm (fun x=>RatExpr.ifNatLe (a x) (b x) (c x) (d x)):= + rmk (iIte ha hb (rnum hc) (rnum hd)) (nite ha hb (rden hc) (rden hd)) +lemma rIfIntLe {a b : α→IntExpr v} {c d : α→RatExpr v} (ha : IEm a) (hb : IEm b) (hc : REm c) (hd : REm d) : + REm (fun x=>RatExpr.ifIntLe (a x) (b x) (c x) (d x)):= + rIfNatLe (nadd (ipos ha) (ineg hb)) (nadd (ipos hb) (ineg ha)) hc hd +lemma rIfLe {a b c d : α→RatExpr v} (ha : REm a) (hb : REm b) (hc : REm c) (hd : REm d) : + REm (fun x=>RatExpr.ifLe (a x) (b x) (c x) (d x)):=by + have he:=rNormalize ha;have hf:=rNormalize hb + exact rIfIntLe (iScale (rnum he) (rden hf)) (iScale (rnum hf) (rden he)) hc hd +lemma rIfLt {a b c d : α→RatExpr v} (ha : REm a) (hb : REm b) (hc : REm c) (hd : REm d) : + REm (fun x=>RatExpr.ifLt (a x) (b x) (c x) (d x)):=rIfLe hb ha hd hc +lemma rIfEq {a b c d : α→RatExpr v} (ha : REm a) (hb : REm b) (hc : REm c) (hd : REm d) : + REm (fun x=>RatExpr.ifEq (a x) (b x) (c x) (d x)):=rIfLe ha hb (rIfLe hb ha hc hd) hd +lemma rMax {a b : α→RatExpr v} (ha : REm a) (hb : REm b) : REm (fun x=>RatExpr.max (a x) (b x)):=rIfLe ha hb hb ha +lemma rMin {a b : α→RatExpr v} (ha : REm a) (hb : REm b) : REm (fun x=>RatExpr.min (a x) (b x)):=rIfLe ha hb ha hb +lemma iCeilRatio {a : α→IntExpr v} {b : α→NatExpr v} (ha : IEm a) (hb : NEm b) : + NEm (fun x=>(a x).ceilRatioNat (b x)):=ndiv (nsub (nadd (iToNat ha) hb) (const _ _ (NatExpr.const 1))) hb +lemma iFloorRatio {a : α→IntExpr v} {b : α→NatExpr v} (ha : IEm a) (hb : NEm b) : + IEm (fun x=>(a x).floorRatio (b x)):=iSub (iOfNat (ndiv (iToNat ha) hb)) (iOfNat (iCeilRatio (iNeg ha) hb)) +lemma rCeilNat {a : α→RatExpr v} (ha : REm a) : NEm (fun x=>(a x).ceilNat):=iCeilRatio (rnum ha) (rden ha) +lemma rFloor {a : α→RatExpr v} (ha : REm a) : IEm (fun x=>(a x).floor):=iFloorRatio (rnum ha) (rden ha) +lemma rCeil {a : α→RatExpr v} (ha : REm a) : IEm (fun x=>(a x).ceil):=iNeg (rFloor (rNeg ha)) +end ExactQuantumFactoring.NetworkEmission.Emits + +end + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/AuxiliaryData.lean b/lean/OAI/Computability/QuantumFactoring/AuxiliaryData.lean new file mode 100644 index 0000000000000000000000000000000000000000..a46aa1d76adeb8039c8d8023aec4f055f56aabb5 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/AuxiliaryData.lean @@ -0,0 +1,108 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.AuxiliaryTree + +namespace OAI + +section +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators + + +namespace ExactQuantumFactoring +open AuxiliaryTree + +/-- The source's distinct positive-exponent factor records. Finsupp stores each +prime once; its canonical serialization sorts its support in increasing order. -/ +abbrev FactorRecord := ℕ→₀ℕ + +def factorRecordList (f : FactorRecord) : List (ℕ×ℕ) := + (f.support.sort (· ≤ ·)).map (fun p => (p,f p)) + +def recordChildren (f : FactorRecord) : List ℕ := + ((f.support.filter (fun p => 2 < p)).sort (· ≤ ·)).map (·-1) + +inductive FactorData where + | node (label : ℕ) (factors : FactorRecord) (descendants : List FactorData) : FactorData + +def FactorData.label : FactorData→ℕ + | .node m _ _ => m + +def trueData (m : ℕ) : FactorData := + .node m m.factorization ((children m).attach.map (fun d => trueData d.val)) +termination_by m +decreasing_by exact (child_bounds d.property).2 + +lemma trueData_eq (m : ℕ) : trueData m = + .node m m.factorization ((children m).map trueData) := by + rw [trueData] + congr 1 + simp only [List.attach_map_val] + +@[simp] lemma trueData_label (m : ℕ) : (trueData m).label=m := by + rw [trueData_eq]; rfl + +lemma recordChildren_factorization (m : ℕ) : recordChildren m.factorization=children m := rfl + +/-- Complete-data acceptance. The local tests are finite prime checks and a +product check, followed by EXACT ordered children; no witness fields or advice. -/ +inductive FactorData.Valid : FactorData→Prop where + | node (m : ℕ) (f : FactorRecord) (ds : List FactorData) + (hm : 2 ≤ m) (hp : ∀ p∈f.support,p.Prime) (hprod : f.prod (·^·)=m) + (hlabels : ds.map FactorData.label=recordChildren f) + (hchildren : ∀ d∈ds, FactorData.Valid d) : FactorData.Valid (.node m f ds) + +lemma valid_factorRecord {m : ℕ} {f : FactorRecord} + (hp : ∀ p∈f.support,p.Prime) (hprod : f.prod (·^·)=m) : f=m.factorization := by + rw [← hprod,Nat.prod_pow_factorization_eq_self hp] + +/-- Unique prime factorization makes the entire ordered occurrence tree unique; +equal child labels under different parents remain separate list occurrences. -/ +theorem valid_eq_trueData {d : FactorData} (hd : d.Valid) : d=trueData d.label := by + induction hd with + | node m f ds hm hp hprod hlabels _ ih => + have hf := valid_factorRecord hp hprod + have hds : ds=(children m).map trueData := by + have hh : ds.map (fun d => trueData d.label)=ds := by + calc + _ = ds.map id := List.map_congr_left (fun d hd => (ih d hd).symm) + _ = ds := List.map_id ds + calc + ds = ds.map (fun d => trueData d.label) := hh.symm + _ = (ds.map FactorData.label).map trueData := List.map_map.symm + _ = (children m).map trueData := by rw [hlabels,hf,recordChildren_factorization] + rw [hf,hds] + exact (trueData_eq m).symm + +/-- The canonical data are always complete; recursion is justified by the +literal source decrease p−1 + rw [trueData_eq] + apply FactorData.Valid.node m m.factorization ((children m).map trueData) hm + · intro p hp + exact Nat.prime_of_mem_primeFactors hp + · exact Nat.prod_factorization_pow_eq_self (by omega) + · simp only [List.map_map,Function.comp_def,trueData_label,recordChildren_factorization] + exact List.map_id (children m) + · intro d hd + obtain ⟨a,ha,rfl⟩ := List.mem_map.mp hd + exact ih a (child_bounds ha).2 (child_bounds ha).1 + +theorem valid_iff_trueData {m : ℕ} (hm : 2 ≤ m) (d : FactorData) (hl : d.label=m) : + d.Valid ↔ d=trueData m := by + constructor + · intro hd + simpa only [hl] using valid_eq_trueData hd + · rintro rfl + exact trueData_valid hm + +end ExactQuantumFactoring + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/AuxiliaryProducer.lean b/lean/OAI/Computability/QuantumFactoring/AuxiliaryProducer.lean new file mode 100644 index 0000000000000000000000000000000000000000..27627f64357ff04e9f5c58a1fba6392365611b1a --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/AuxiliaryProducer.lean @@ -0,0 +1,122 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.PrimeRecords +import OAI.Computability.QuantumFactoring.LoggedExecution +import OAI.Computability.QuantumFactoring.ControllerQueries + +namespace OAI + +section +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators + + +namespace ExactQuantumFactoring +open AuxiliaryTree FactorController + +namespace DataProducer + +/-- Each occurrence carries its complete ancestral path. Equal labels under +separate parents are never identified or memoized. -/ +abbrev NodeKey := List ℕ × ℕ +abbrev Choices := NodeKey→ℕ→ℕ→ℕ + +def nodeRun (n : ℕ) (choose : Choices) (path : List ℕ) (m : ℕ) : Logged NodeKey (List ℕ) := + ⟨run (choose (path,m)) (2*n) 0 [m],[(path,m)]⟩ + +def NodeGood (n : ℕ) (choose : Choices) (k : NodeKey) : Prop := + ∀ im∈queries (choose k) (2*n) 0 [k.2], ProperDivisor im.2 (choose k im.1 im.2) + +/-- The source's factor-and-recurse producer, with a depth cap. The Finsupp is +only a representation of the multiplicities in the returned prime list; +`primeRecord` never computes an unknown prime factorization. -/ +noncomputable def build (n : ℕ) (choose : Choices) : ℕ→List ℕ→ℕ→Logged NodeKey FactorData + | 0, _, _ => Logged.abort + | depth+1, path, m => (nodeRun n choose path m).bind (fun ps => + (Logged.traverse (fun d => build n choose depth (path++[d]) d) + (recordChildren (primeRecord ps))).map (FactorData.node m (primeRecord ps))) + +lemma nodeRun_complete {m n : ℕ} (hm : 2 ≤ m) (hb : m<2^n) + (choose : Choices) (path : List ℕ) (hg : Logged.Good (NodeGood n choose) (nodeRun n choose path m)) : + ∃ ps, (nodeRun n choose path m).result=some ps := by + apply run_complete_on_queries (choose (path,m)) + · intro a ha + have he : a=m := by simpa using ha + subst a + exact hm + · have hw := splitWeight_bound (by omega) hb + simp only [weight,List.map_cons,List.map_nil,List.sum_cons,List.sum_nil,add_zero] + omega + · exact hg (path,m) (by simp [nodeRun]) + +lemma nodeRun_record {n m : ℕ} {choose : Choices} {path : List ℕ} {ps : List ℕ} + (h : (nodeRun n choose path m).result=some ps) : primeRecord ps=m.factorization := by + have hs := run_sound (choose (path,m)) h + have hp : ps.prod=m := by simpa using hs.2 + rw [primeRecord_eq_factorization ps hs.1,hp] + +lemma child_level_empty {m depth d : ℕ} (h : level m (depth+1)=[]) (hd : d∈children m) : + level d depth=[] := by + apply List.eq_nil_iff_forall_not_mem.mpr + intro e he + have hh : e∈level m (depth+1) := List.mem_flatMap.mpr ⟨d,hd,he⟩ + rw [h] at hh + exact List.not_mem_nil hh + +/-- Literal all-good completion follows the actual short-circuit trace. There +is no hypothesis about queries or child occurrences that this run never made. -/ +theorem build_complete (n : ℕ) (choose : Choices) (depth : ℕ) (path : List ℕ) (m : ℕ) + (hm : 2 ≤ m) (hb : m<2^n) (hd : level m depth=[]) + (hg : Logged.Good (NodeGood n choose) (build n choose depth path m)) : + (build n choose depth path m).result=some (trueData m) := by + induction depth generalizing path m with + | zero => simp only [level,List.cons_ne_self] at hd + | succ depth ih => + have hroot := Logged.good_bind_left (NodeGood n choose) _ _ hg + obtain ⟨ps,hps⟩ := nodeRun_complete hm hb choose path hroot + have hf := nodeRun_record hps + have hg' := Logged.good_bind_right (NodeGood n choose) _ _ hps hg + have hchildren := (Logged.good_map (NodeGood n choose) _ _).mp hg' + rw [hf,recordChildren_factorization] at hchildren + have hc : (Logged.traverse (fun d => build n choose depth (path++[d]) d) + (children m)).result=some ((children m).map trueData) := by + apply Logged.traverse_complete (NodeGood n choose) _ trueData _ ?_ hchildren + intro d hdm hgd + have hbounds := child_bounds hdm + exact ih _ _ hbounds.1 (hbounds.2.trans hb) (child_level_empty hd hdm) hgd + rw [build,Logged.bind_result_some _ _ hps,Logged.map_result,hf,recordChildren_factorization, + hc,Option.map_some,trueData_eq] + +/-- Even a bad run cannot produce false accepted data. Every successful local +prime list and all ordered descendants agree with the canonical occurrence tree. -/ +theorem build_sound (n : ℕ) (choose : Choices) (depth : ℕ) (path : List ℕ) (m : ℕ) + {d : FactorData} (hs : (build n choose depth path m).result=some d) : d=trueData m := by + induction depth generalizing path m d with + | zero => simp only [build,Logged.abort] at hs; contradiction + | succ depth ih => + cases hroot : (nodeRun n choose path m).result with + | none => simp only [build,Logged.bind,hroot] at hs; contradiction + | some ps => + have hf := nodeRun_record hroot + rw [build,Logged.bind_result_some _ _ hroot,Logged.map_result,hf,recordChildren_factorization] at hs + obtain ⟨ds,hds,he⟩ := Option.map_eq_some_iff.mp hs + have hcan := Logged.traverse_sound (fun a => build n choose depth (path++[a]) a) + trueData (children m) (fun a _ b hab => ih (path++[a]) a hab) hds + subst d + rw [hcan] + exact (trueData_eq m).symm + +theorem bounded_complete {m n : ℕ} (hm : 2 ≤ m) (hb : m<2^n) + (choose : Choices) (hg : Logged.Good (NodeGood n choose) (build n choose (2*n) [] m)) : + (build n choose (2*n) [] m).result=some (trueData m) ∧ (trueData m).Valid := + ⟨build_complete n choose (2*n) [] m hm hb (level_empty hm hb) hg,trueData_valid hm⟩ + +end DataProducer +end ExactQuantumFactoring + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/AuxiliaryTree.lean b/lean/OAI/Computability/QuantumFactoring/AuxiliaryTree.lean new file mode 100644 index 0000000000000000000000000000000000000000..6c46834b2b09cee1fdb2b5e7bdcc3c165dd70882 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/AuxiliaryTree.lean @@ -0,0 +1,200 @@ +import Mathlib + +namespace OAI + +section +open scoped BigOperators + + +/-! Occurrence-preserving bounds for the canonical p−1 auxiliary tree in +Section5. Equal labels under different parents remain separate list entries. -/ +namespace ExactQuantumFactoring.AuxiliaryTree +open scoped BigOperators + +def children (M : ℕ) : List ℕ := + ((M.primeFactors.filter (fun p => 2 2 2 Nat.sub_le _ _) + _ ≤ ∏ p ∈ M.primeFactors, p := Finset.prod_le_prod_of_subset_of_one_le + (Finset.filter_subset _ _) + (fun p hp _ => (Nat.prime_of_mem_primeFactors hp).one_lt.le) + _ ≤ M := Nat.le_of_dvd hM (Nat.prod_primeFactors_dvd M) + +/-- A level is a list, not a set: multiplicities of occurrences are retained. -/ +def level (M : ℕ) : ℕ → List ℕ + | 0 => [M] + | k+1 => (children M).flatMap (fun d => level d k) + +lemma level_bounds {M d k : ℕ} (hM : 2≤M) (hd : d ∈ level M k) : 2≤d ∧ d≤M := by + induction k generalizing M with + | zero => + have he : d=M := by simpa [level] using hd + subst d + exact ⟨hM,le_rfl⟩ + | succ k ih => + obtain ⟨e,he,hd⟩ := List.mem_flatMap.mp hd + have hb := child_bounds he + have hh := ih hb.1 hd + exact ⟨hh.1,hh.2.trans hb.2.le⟩ + +lemma level_two_step {M d k : ℕ} (hd : d ∈ level M (2*k)) : 2^k*d≤M := by + induction k generalizing M with + | zero => + have he : d=M := by simpa [level] using hd + simpa using he.le + | succ k ih => + have heq : 2*(k+1)=2*k+1+1 := by omega + rw [heq,level] at hd + obtain ⟨e,he,hd⟩ := List.mem_flatMap.mp hd + rw [level] at hd + obtain ⟨f,hf,hd⟩ := List.mem_flatMap.mp hd + have hx := ih hd + have hh := grandchild_half he hf + rw [pow_succ] + nlinarith + +lemma level_empty {M n : ℕ} (hM : 2≤M) (hbound : M<2^n) : level M (2*n)=[] := by + apply List.eq_nil_iff_forall_not_mem.mpr + intro d hd + have hx := level_two_step hd + have hy := (level_bounds hM hd).1 + have hp : 0<2^n := by positivity + nlinarith + +lemma prod_flatMap (f : ℕ→List ℕ) (xs : List ℕ) : + (xs.flatMap f).prod=(xs.map (fun x => (f x).prod)).prod := by + induction xs with + | nil => rfl + | cons x xs ih => simp [ih] + +lemma level_prod_le {M k : ℕ} (hM : 2≤M) : (level M k).prod≤M := by + induction k generalizing M with + | zero => simp [level] + | succ k ih => + rw [level,prod_flatMap] + calc + ((children M).map (fun d => (level d k).prod)).prod ≤ + ((children M).map id).prod := List.prod_map_le_prod_map₀ _ _ + (fun _ _ => Nat.zero_le _) (fun d hd => ih (child_bounds hd).1) + _ = (children M).prod := by simp + _ ≤ M := children_prod_le (by omega) + +lemma pow_length_le_prod (xs : List ℕ) (hxs : ∀ x ∈ xs, 2≤x) : 2^xs.length≤xs.prod := by + induction xs with + | nil => simp + | cons x xs ih => + have hx := hxs x (by simp) + have hi := ih (fun y hy => hxs y (by simp [hy])) + simp only [List.length_cons,List.prod_cons,pow_succ] + exact (Nat.mul_le_mul hi hx).trans_eq (Nat.mul_comm _ _) + +lemma level_length_lt {M n k : ℕ} (hM : 2≤M) (hbound : M<2^n) : + (level M k).length (level_bounds hM hd).1)).trans_lt + ((level_prod_le hM).trans_lt hbound) + +def splitWeight (M : ℕ) : ℕ := M.primeFactorsList.length + +lemma splitWeight_bound {M n : ℕ} (hM : 0 (Nat.prime_of_mem_primeFactorsList hp).two_le) + rw [Nat.prod_primeFactorsList hM.ne'] at hh + exact hh.trans_lt hbound + +lemma level_weight_lt {M n k : ℕ} (hM : 2≤M) (hbound : M<2^n) : + ((level M k).map splitWeight).sum rw [← List.map_id (level M k)] + apply List.map_congr_left + intro d hd + exact Nat.prod_primeFactorsList (by have := (level_bounds hM hd).1; omega) + have hlen : ps.length=((level M k).map splitWeight).sum := by + change (List.flatMap Nat.primeFactorsList (level M k)).length = _ + rw [List.length_flatMap] + rfl + have hp : 2^ps.length≤ps.prod := pow_length_le_prod ps (by + intro p hp + obtain ⟨d,_,hp⟩ := List.mem_flatMap.mp hp + exact (Nat.prime_of_mem_primeFactorsList hp).two_le) + rw [he,hlen] at hp + exact (Nat.pow_lt_pow_iff_right (by decide : 1<2)).mp + (hp.trans_lt ((level_prod_le hM).trans_lt hbound)) + +/-- The source's whole-tree task cap, expressed without real logarithms. -/ +def taskBound (M n : ℕ) : ℕ := + ∑ k ∈ Finset.range (2*n+2), ((level M k).map splitWeight).sum + +lemma taskBound_le {M n : ℕ} (hM : 2≤M) (hbound : M<2^n) : + taskBound M n ≤ (2*n+2)*n := by + unfold taskBound + calc + _ ≤ ∑ _k ∈ Finset.range (2*n+2), n := Finset.sum_le_sum + (fun k _ => (level_weight_lt (k:=k) hM hbound).le) + _ = _ := by simp + +lemma transitions_bound {n : ℕ} (hn : 2≤n) : (2*n+2)*n*(n^5+1)≤6*n^7 := by + have hnpos : 0 1 + | .cnot => 2 + | .toffoli => 3 + +def Primitive.code : Primitive → ℕ + | .not => 0 | .cnot => 1 | .toffoli => 2 | .hadamard => 3 | .phase => 4 + +/-- An inverse and/or one added control. This is a fixed set of 20 gate names, +not an unbounded-control or arbitrary-angle gate model. -/ +structure Gate where + primitive : Primitive + inverse : Bool + controlled : Bool + deriving DecidableEq + +def Gate.arity (g : Gate) : ℕ := g.primitive.arity + if g.controlled then 1 else 0 + +/-- Matrix entries are indexed by lists in wire order (row first, column second). +Entries on ill-sized lists are irrelevant and set to zero. -/ +noncomputable def Primitive.matrix : Primitive → List Bool → List Bool → ℂ + | .not, [a], [b] => if a = !b then 1 else 0 + | .cnot, [a,b], [c,d] => if a = c ∧ b = Bool.xor c d then 1 else 0 + | .toffoli, [a,b,c], [d,e,f] => + if a = d ∧ b = e ∧ c = Bool.xor f (d && e) then 1 else 0 + | .hadamard, [a], [b] => + (if a && b then -1 else 1) / (Real.sqrt 2 : ℂ) + | .phase, [a], [b] => if a = b then (if b then Complex.I else 1) else 0 + | _, _, _ => 0 + +noncomputable def Gate.baseMatrix (g : Gate) (a b : List Bool) : ℂ := + if g.inverse then star (g.primitive.matrix b a) else g.primitive.matrix a b + +noncomputable def Gate.matrix (g : Gate) (a b : List Bool) : ℂ := + if g.controlled then + match a, b with + | false :: a', false :: b' => if a' = b' then 1 else 0 + | true :: a', true :: b' => g.baseMatrix a' b' + | _, _ => 0 + else g.baseMatrix a b + +/-- A primitive is placed on distinct actual wires, with no operation of +unbounded arity hidden in a circuit instruction. -/ +structure Instruction (q : ℕ) where + gate : Gate + wire : Fin gate.arity → Fin q + distinct : Function.Injective wire + +abbrev Basis (q : ℕ) := Fin q → Bool +abbrev State (q : ℕ) := Basis q → ℂ + +noncomputable def Instruction.matrix {q : ℕ} (o : Instruction q) : + Matrix (Basis q) (Basis q) ℂ := by + classical + exact fun a b => + if ∀ i : Fin q, (∀ j, o.wire j ≠ i) → a i = b i then + o.gate.matrix (List.ofFn (a ∘ o.wire)) (List.ofFn (b ∘ o.wire)) + else 0 + +structure Circuit where + qubits : ℕ + instructions : List (Instruction qubits) + +noncomputable def Circuit.apply (c : Circuit) (ψ : State c.qubits) : State c.qubits := + c.instructions.foldl (fun v o => o.matrix.mulVec v) ψ + +/-- Input wires are first, least significant bit first; all other wires start zero. -/ +def inputBasis (q ℓ N : ℕ) : Basis q := + fun i => if i.val < ℓ then N.testBit i.val else false + +noncomputable def Circuit.outputState (c : Circuit) (ℓ N : ℕ) : State c.qubits := by + classical + exact c.apply (fun x => if x = inputBasis c.qubits ℓ N then 1 else 0) + +/-- The cutoff and padding are the standing parameters in Section 2. -/ +def paddedLength (ℓ : ℕ) : ℕ := max 128 ℓ + +def readBit {q : ℕ} (x : Basis q) (i : ℕ) : Bool := + if h : i < q then x ⟨i,h⟩ else false + +/-- n entries of n bits each, in the n² wires immediately after the input. -/ +def outputList {q : ℕ} (ℓ : ℕ) (x : Basis q) : List ℕ := + let n := paddedLength ℓ + List.ofFn (fun a : Fin n => + ∑ j ∈ Finset.range n, if readBit x (ℓ + a.val * n + j) then 2^j else 0) + +/-- Complete nondecreasing prime factorization, multiplicities included, +padded by zeros, as in Section 6. There is no primality oracle in the circuit. -/ +def CorrectEncoding (N n : ℕ) (xs : List ℕ) : Prop := + ∃ ps : List ℕ, (∀ p ∈ ps, Nat.Prime p) ∧ ps.Pairwise (· ≤ ·) ∧ + ps.prod = N ∧ ps.length ≤ n ∧ xs = ps ++ List.replicate (n - ps.length) 0 + +/-- Unnormalized Born sum on correct outputs; success is exactly one, +not positivity, postselection, or a limiting high probability. -/ +noncomputable def Circuit.correctProbability (c : Circuit) (ℓ N : ℕ) : ℝ := by + classical + exact ∑ x : Basis c.qubits, + if CorrectEncoding N (paddedLength ℓ) (outputList ℓ x) then + Complex.normSq (c.outputState ℓ N x) else 0 + +/-- Unary natural words with delimiters make the circuit description explicit. +Unary wire addresses cause at most polynomial overhead when width is polynomial. -/ +def natWord (k : ℕ) : List Bool := List.replicate k true ++ [false] + +def Instruction.encode {q : ℕ} (o : Instruction q) : List Bool := + natWord o.gate.primitive.code ++ [o.gate.inverse, o.gate.controlled] ++ + (List.ofFn (fun i => o.wire i |>.val)).flatMap natWord + +def Circuit.encode (c : Circuit) : List Bool := + natWord c.qubits ++ natWord c.instructions.length ++ + c.instructions.flatMap Instruction.encode + +/-- A single finite-alphabet classical generator receives only the INPUT LENGTH. +All stack alphabets, states and labels are finite: no large-integer unit-cost +oracle is hidden in TM2 push/branch functions. -/ +def Uniform (family : ℕ → Circuit) : Prop := + ∃ generator : Turing.TM2ComputableInPolyTime + (fun ℓ => List.replicate ℓ true) Circuit.encode family, + ∀ k, Finite (generator.tm.Γ k) + +def PolynomialResources (family : ℕ → Circuit) : Prop := + ∃ bound : Polynomial ℕ, ∀ ℓ, + (family ℓ).qubits ≤ bound.eval ℓ ∧ + (family ℓ).instructions.length ≤ bound.eval ℓ + +/-- Literal main endpoint: one length-uniform family, exact output for EVERY +binary integer N≥2, and worst-case polynomial gates AND qubits. -/ +def MainTheorem : Prop := + ∃ family : ℕ → Circuit, Uniform family ∧ PolynomialResources family ∧ + ∀ (ℓ N : ℕ), 2 ≤ N → N.size = ℓ → + ℓ + (paddedLength ℓ)^2 ≤ (family ℓ).qubits ∧ + (family ℓ).correctProbability ℓ N = 1 + +end ExactQuantumFactoring + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BinLabelCircuit.lean b/lean/OAI/Computability/QuantumFactoring/BinLabelCircuit.lean new file mode 100644 index 0000000000000000000000000000000000000000..75338ccd043248eeeee8fa6b3ab8a8900fc54a78 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BinLabelCircuit.lean @@ -0,0 +1,117 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.ExpressionPredicates +import OAI.Computability.QuantumFactoring.ContinuedFractionCircuit + +namespace OAI + +section +open scoped BigOperators +open scoped BigOperators + + +namespace ExactQuantumFactoring.OrderTrial +open BooleanNetwork BitArithmetic + +/-- Input order Q,B,k,d,j; coprimality is already guaranteed by the convergent +recurrence and does not require a second gcd computation. -/ +def binCheckExpr : NatExpr (Fin 5) := + let Q := NatExpr.var 0 + let B := NatExpr.var 1 + let k := NatExpr.var 2 + let d := NatExpr.var 3 + let j := NatExpr.var 4 + let bin := NatExpr.div (.add (.mul (.mul (.const 2) j) Q) d) (.mul (.const 2) d) + .iteLe (.const 1) d + (.iteLe (.add d (.const 1)) B + (.iteLe (.add j (.const 1)) d + (.testEq bin k (.const 1) (.const 0)) (.const 0)) (.const 0)) (.const 0) + +lemma binCheckExpr_eval (x : Fin 5 → ℕ) : + binCheckExpr.eval x=1 ↔ 0 by_cases hB : x 3+1≤x 1 <;> + by_cases hj : x 4+1≤x 3 <;> + by_cases he : (2*x 4*x 0+x 3)/(2*x 3)=x 2 <;> + simp [binCheckExpr,NatExpr.eval_testEq,NatExpr.eval,hd,hB,hj,he] <;> omega + +def checkedConvergent {n w : ℕ} (i : ℕ) (Q B k : BooleanNetwork n w) : BooleanNetwork n (w+w) := + let conv := (k.pair Q).comp (convergentNet w i) + let d := conv.comp (rootGuess w) + let j := conv.comp (rootModulus w) + let pass := binCheckExpr.isOne ![Q,B,k,d,j] + (wordMux pass d (wordConstant (BitVec.ofNat w 0))).pair + (wordMux pass j (wordConstant (BitVec.ofNat w 0))) + +def checkedPair (Q B k i : ℕ) : ℕ×ℕ := + let p := convergentPair k Q i + if IsBinLabel Q B k (p.2,p.1) then (p.2,p.1) else (0,0) + +lemma checkedConvergent_value {n s w : ℕ} (i : ℕ) (hw : cfWidth s i ≤ w) + (Q B k : BooleanNetwork n w) (x : Basis n) + (hQ : (bitsValue (Q.eval x)).toNat<2^s) (hk : (bitsValue (k.eval x)).toNat<2^s) : + ∃ d j : Basis w, + (checkedConvergent i Q B k).eval x=Fin.append d j ∧ + ((bitsValue d).toNat,(bitsValue j).toNat)=checkedPair + (bitsValue (Q.eval x)).toNat (bitsValue (B.eval x)).toNat (bitsValue (k.eval x)).toNat i := by + obtain ⟨p,q,hpq,he⟩ := convergentNet_value i hw (k.eval x) (Q.eval x) hk hQ + let cv := (k.pair Q).comp (convergentNet w i) + have hv : cv.eval x=Fin.append p q := by rw [eval_comp,eval_pair,hpq] + let den := cv.comp (rootGuess w) + let num := cv.comp (rootModulus w) + have hd : den.eval x=q := by rw [eval_comp,hv,rootGuess_eval] + have hj : num.eval x=p := by rw [eval_comp,hv,rootModulus_eval] + let pass := binCheckExpr.isOne ![Q,B,k,den,num] + have hc : pass.eval x 0=true ↔ IsBinLabel (bitsValue (Q.eval x)).toNat + (bitsValue (B.eval x)).toNat (bitsValue (k.eval x)).toNat + ((bitsValue q).toNat,(bitsValue p).toNat) := by + rw [NatExpr.isOne_eval,binCheckExpr_eval] + simp only [Matrix.cons_val_zero,Matrix.cons_val_one,Matrix.cons_val_two, + Matrix.cons_val_three,Matrix.cons_val_four,Matrix.vecHead,Matrix.vecTail, + Function.comp_apply,Matrix.cons_val_succ,hd,hj] + have hr := convergentPair_reduced (bitsValue (k.eval x)).toNat (bitsValue (Q.eval x)).toNat i + have hpv : (bitsValue p).toNat = (convergentPair (bitsValue (k.eval x)).toNat (bitsValue (Q.eval x)).toNat i).1 := congrArg Prod.fst he + have hqv : (bitsValue q).toNat = (convergentPair (bitsValue (k.eval x)).toNat (bitsValue (Q.eval x)).toNat i).2 := congrArg Prod.snd he + change 0<(bitsValue q).toNat ∧ (bitsValue q).toNat<(bitsValue (B.eval x)).toNat ∧ + (bitsValue p).toNat<(bitsValue q).toNat ∧ + bin (bitsValue (Q.eval x)).toNat (bitsValue q).toNat (bitsValue p).toNat=(bitsValue (k.eval x)).toNat ↔ _ + have hcop : Nat.Coprime (bitsValue p).toNat (bitsValue q).toNat := by + rw [hpv,hqv] + exact hr.2 + exact ⟨fun ⟨a,b,c,e⟩ => ⟨a,b,c,hcop,e⟩,fun ⟨a,b,c,_,e⟩ => ⟨a,b,c,e⟩⟩ + have he' : ((bitsValue q).toNat,(bitsValue p).toNat)= + ((convergentPair (bitsValue (k.eval x)).toNat (bitsValue (Q.eval x)).toNat i).2, + (convergentPair (bitsValue (k.eval x)).toNat (bitsValue (Q.eval x)).toNat i).1) := + congrArg Prod.swap he + let zero := (wordConstant (n:=n) (BitVec.ofNat w 0)).eval x + have hz : (bitsValue zero).toNat=0 := by simp [zero,wordConstant_eval] + by_cases hh : IsBinLabel (bitsValue (Q.eval x)).toNat (bitsValue (B.eval x)).toNat + (bitsValue (k.eval x)).toNat ((bitsValue q).toNat,(bitsValue p).toNat) + · refine ⟨q,p,?_,?_⟩ + · rw [checkedConvergent,eval_pair] + change Fin.append ((wordMux pass den _).eval x) ((wordMux pass num _).eval x)=_ + rw [wordMux_eval,wordMux_eval,ite_eq_left (hc.mpr hh),ite_eq_left (hc.mpr hh),hd,hj] + · rw [checkedPair,← he',ite_eq_left hh] + · refine ⟨zero,zero,?_,?_⟩ + · rw [checkedConvergent,eval_pair] + change Fin.append ((wordMux pass den _).eval x) ((wordMux pass num _).eval x)=_ + rw [wordMux_eval,wordMux_eval,ite_eq_right (fun h => hh (hc.mp h)),ite_eq_right (fun h => hh (hc.mp h))] + · rw [checkedPair,← he',ite_eq_right hh,hz] + +lemma checkedPair_nonzero_iff {Q B k i : ℕ} : + (checkedPair Q B k i).1≠0 ↔ + IsBinLabel Q B k ((convergentPair k Q i).2,(convergentPair k Q i).1) := by + dsimp only [checkedPair] + split_ifs with h + · exact ⟨fun _ => h,fun _ => Nat.ne_of_gt h.1⟩ + · simp [h] +lemma checkedPair_sound {Q B k i : ℕ} (h : (checkedPair Q B k i).1≠0) : + IsBinLabel Q B k (checkedPair Q B k i) := by + have hh := checkedPair_nonzero_iff.mp h + simp [checkedPair,hh] + +end ExactQuantumFactoring.OrderTrial + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BinaryRoots.lean b/lean/OAI/Computability/QuantumFactoring/BinaryRoots.lean new file mode 100644 index 0000000000000000000000000000000000000000..9fe616c9632fd5b465b2ae3528861c22d7c1c588 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BinaryRoots.lean @@ -0,0 +1,73 @@ +import Mathlib + +namespace OAI + +section +open scoped BigOperators + + +/-! Bounded binary-root search required by the appendix's perfect-power check. +The search uses only comparisons and powers with exponent at most the input +bit bound; no unbounded Nat.nthRoot primitive is used by the algorithm. -/ +namespace ExactQuantumFactoring.Primality + +def rootSearch (m e : ℕ) : (k guess : ℕ) → ℕ + | 0, guess => guess + | k+1, guess => + let next := guess+2^k + rootSearch m e k (if next^e ≤ m then next else guess) + +lemma rootSearch_spec {m e : ℕ} (_he : 0 < e) (k guess : ℕ) + (hlo : guess^e ≤ m) (hhi : m < (guess+2^k)^e) : + (rootSearch m e k guess)^e ≤ m ∧ m < (rootSearch m e k guess+1)^e := by + induction k generalizing guess with + | zero => simpa only [rootSearch,pow_zero] using And.intro hlo hhi + | succ k ih => + simp only [rootSearch] + by_cases hnext : (guess+2^k)^e ≤ m + · rw [ite_eq_left hnext] + apply ih _ hnext + have hh : guess+2^k+2^k=guess+2^(k+1) := by rw [pow_succ]; omega + rw [hh] + exact hhi + · rw [ite_eq_right hnext] + exact ih _ hlo (by omega) + +lemma rootSearch_eq {m e : ℕ} (he : 0 < e) (k guess b : ℕ) + (hlo : guess^e ≤ m) (hhi : m < (guess+2^k)^e) (hb : b^e=m) : + rootSearch m e k guess=b := by + obtain ⟨hl,hh⟩ := rootSearch_spec he k guess hlo hhi + have hl' : rootSearch m e k guess ≤ b := + (Nat.pow_le_pow_iff_left he.ne').mp (hl.trans_eq hb.symm) + have hh' : b < rootSearch m e k guess+1 := + (Nat.pow_lt_pow_iff_left he.ne').mp (hb ▸ hh) + omega + +def boundedRoot (m e n : ℕ) : ℕ := rootSearch m e n 0 + +lemma boundedRoot_spec {m e n : ℕ} (he : 0 < e) (hm : m < 2^n) : + (boundedRoot m e n)^e ≤ m ∧ m < (boundedRoot m e n+1)^e := by + apply rootSearch_spec he n 0 + · simp [Nat.ne_of_gt he] + · simp only [zero_add] + exact hm.trans_le (Nat.le_self_pow he.ne' (2^n)) + +lemma boundedRoot_pow_eq {m e n b : ℕ} (he : 0 < e) (hm : m < 2^n) (hb : b^e=m) : + boundedRoot m e n=b := by + apply rootSearch_eq he n 0 b + · simp [Nat.ne_of_gt he] + · simp only [zero_add] + exact hm.trans_le (Nat.le_self_pow he.ne' (2^n)) + · exact hb + +lemma perfectPower_exponent_lt {m n b e : ℕ} (hm : m < 2^n) (hb : 2 ≤ b) + (h : b^e=m) : e < n := by + have hh : 2^e < 2^n := (Nat.pow_le_pow_left hb e).trans_lt (h ▸ hm) + exact (Nat.pow_lt_pow_iff_right (by decide : 1 < 2)).mp hh + +end ExactQuantumFactoring.Primality + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitArithmetic.lean b/lean/OAI/Computability/QuantumFactoring/BitArithmetic.lean new file mode 100644 index 0000000000000000000000000000000000000000..a155f0dd4a486f82d7e7521af17d6994fa50784f --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitArithmetic.lean @@ -0,0 +1,80 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.AIGCompiler +import OAI.Computability.QuantumFactoring.AIGBounds +import OAI.Computability.QuantumFactoring.AIGInputs +import OAI.Computability.QuantumFactoring.BitEncoding + +namespace OAI + +section +open scoped BigOperators + + +namespace ExactQuantumFactoring +namespace BitArithmetic +open Std.Sat Std.Tactic.BVDecide.BVExpr.bitblast +open AIGCompiler BooleanNetwork + +/-- The two actual little-endian input words of the bitblaster. -/ +def binaryInputs (w : ℕ) : AIG.BinaryRefVec (inputs (w+w)).1 w := + ⟨refVector (fun i => (inputs (w+w)).2 (i.castAdd w)), + refVector (fun i => (inputs (w+w)).2 (Fin.natAdd w i))⟩ + +def leftWord {w : ℕ} (x : Fin (w+w) → Bool) : BitVec w := + bitsValue (fun i => x (i.castAdd w)) +def rightWord {w : ℕ} (x : Fin (w+w) → Bool) : BitVec w := + bitsValue (fun i => x (Fin.natAdd w i)) + +lemma binaryInputs_left (w : ℕ) (x : Fin (w+w) → Bool) (i : ℕ) (hi : i < w) : + AIG.denote x ⟨(inputs (w+w)).1, (binaryInputs w).lhs.get i hi⟩ = + (leftWord x).getLsbD i := by + rw [binaryInputs, refVector_get, inputs_correct] + exact (bitsValue_bit (fun j => x (j.castAdd w)) ⟨i,hi⟩).symm + +lemma binaryInputs_right (w : ℕ) (x : Fin (w+w) → Bool) (i : ℕ) (hi : i < w) : + AIG.denote x ⟨(inputs (w+w)).1, (binaryInputs w).rhs.get i hi⟩ = + (rightWord x).getLsbD i := by + rw [binaryInputs, refVector_get, inputs_correct] + exact (bitsValue_bit (fun j => x (Fin.natAdd w j)) ⟨i,hi⟩).symm + +def add (w : ℕ) : BooleanNetwork (w+w) w := + let res := blastAdd (inputs (w+w)).1 (binaryInputs w) + compileVec res.aig res.vec + +lemma add_correct (w : ℕ) (x : Fin (w+w) → Bool) (i : Fin w) : + (add w).eval x i = (leftWord x + rightWord x).getLsbD i.val := by + rw [add, compileVec_correct] + exact denote_blastAdd _ _ _ _ _ (binaryInputs_left w x) (binaryInputs_right w x) _ _ + +def mul (w : ℕ) : BooleanNetwork (w+w) w := + let res := blastMul (inputs (w+w)).1 (binaryInputs w) + compileVec res.aig res.vec + +lemma mul_correct (w : ℕ) (x : Fin (w+w) → Bool) (i : Fin w) : + (mul w).eval x i = (leftWord x * rightWord x).getLsbD i.val := by + rw [mul, compileVec_correct] + exact denote_blastMul _ _ _ _ _ (binaryInputs_left w x) (binaryInputs_right w x) _ _ + +lemma add_count (w : ℕ) : (add w).net.count ≤ 86*w+6 := by + have h := compileVec_count (blastAdd (inputs (w+w)).1 (binaryInputs w)).aig + (blastAdd (inputs (w+w)).1 (binaryInputs w)).vec + have hs := AIGBounds.add_size (inputs (w+w)).1 (binaryInputs w) + rw [inputs_size] at hs + dsimp only [add] + omega + +lemma mul_count (w : ℕ) : (mul w).net.count ≤ 90*w*w+14*w+6 := by + have h := compileVec_count (blastMul (inputs (w+w)).1 (binaryInputs w)).aig + (blastMul (inputs (w+w)).1 (binaryInputs w)).vec + have hs := AIGBounds.mul_size (inputs (w+w)).1 (binaryInputs w) + rw [inputs_size] at hs + dsimp only [mul] + nlinarith + +end BitArithmetic +end ExactQuantumFactoring + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitArithmeticDivision.lean b/lean/OAI/Computability/QuantumFactoring/BitArithmeticDivision.lean new file mode 100644 index 0000000000000000000000000000000000000000..0f5df726831ed855a48a938ac840ad46c6f26c83 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitArithmeticDivision.lean @@ -0,0 +1,71 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitArithmetic +import OAI.Computability.QuantumFactoring.AIGDivisionBounds + +namespace OAI + +section +open scoped BigOperators + + +namespace ExactQuantumFactoring.BitArithmetic +open Std.Sat Std.Tactic.BVDecide.BVExpr.bitblast +open AIGCompiler BooleanNetwork + +def sub (w : ℕ) : BooleanNetwork (w+w) w := + let res := blastSub (inputs (w+w)).1 (binaryInputs w) + compileVec res.aig res.vec + +lemma sub_correct (w : ℕ) (x : Fin (w+w) → Bool) (i : Fin w) : + (sub w).eval x i = (leftWord x - rightWord x).getLsbD i.val := by + rw [sub, compileVec_correct] + exact denote_blastSub _ _ _ _ _ (binaryInputs_left w x) (binaryInputs_right w x) _ _ + +lemma sub_count (w : ℕ) : (sub w).net.count ≤ 158*w+6 := by + have h := compileVec_count (blastSub (inputs (w+w)).1 (binaryInputs w)).aig + (blastSub (inputs (w+w)).1 (binaryInputs w)).vec + have hs := AIGBounds.sub_size (inputs (w+w)).1 (binaryInputs w) + rw [inputs_size] at hs + dsimp only [sub] + nlinarith + +def div (w : ℕ) : BooleanNetwork (w+w) w := + let res := blastUdiv (inputs (w+w)).1 (binaryInputs w) + compileVec res.aig res.vec + +lemma div_correct (w : ℕ) (x : Fin (w+w) → Bool) (i : Fin w) : + (div w).eval x i = (leftWord x / rightWord x).getLsbD i.val := by + rw [div, compileVec_correct] + exact denote_blastUdiv _ _ _ _ _ (binaryInputs_left w x) (binaryInputs_right w x) _ _ + +lemma div_count (w : ℕ) : (div w).net.count ≤ 216*w*w+56*w+6 := by + have h := compileVec_count (blastUdiv (inputs (w+w)).1 (binaryInputs w)).aig + (blastUdiv (inputs (w+w)).1 (binaryInputs w)).vec + have hs := AIGBounds.div_size (inputs (w+w)).1 (binaryInputs w) + rw [inputs_size] at hs + dsimp only [div] + nlinarith + +def mod (w : ℕ) : BooleanNetwork (w+w) w := + let res := blastUmod (inputs (w+w)).1 (binaryInputs w) + compileVec res.aig res.vec + +lemma mod_correct (w : ℕ) (x : Fin (w+w) → Bool) (i : Fin w) : + (mod w).eval x i = (leftWord x % rightWord x).getLsbD i.val := by + rw [mod, compileVec_correct] + exact denote_blastUmod _ _ _ _ _ (binaryInputs_left w x) (binaryInputs_right w x) _ _ + +lemma mod_count (w : ℕ) : (mod w).net.count ≤ 216*w*w+56*w+6 := by + have h := compileVec_count (blastUmod (inputs (w+w)).1 (binaryInputs w)).aig + (blastUmod (inputs (w+w)).1 (binaryInputs w)).vec + have hs := AIGBounds.mod_size (inputs (w+w)).1 (binaryInputs w) + rw [inputs_size] at hs + dsimp only [mod] + nlinarith + +end ExactQuantumFactoring.BitArithmetic + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitEncoding.lean b/lean/OAI/Computability/QuantumFactoring/BitEncoding.lean new file mode 100644 index 0000000000000000000000000000000000000000..5efd90de9e3fdb5cae270e6c37af93fbc479e58e --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitEncoding.lean @@ -0,0 +1,61 @@ +import Mathlib + +namespace OAI + +section +open scoped BigOperators + + +namespace ExactQuantumFactoring + +/-- Little-endian computational wires, with the same bit ordering as the +manuscript and input/output interface. -/ +def bitsValue : {b : ℕ} → (Fin b → Bool) → BitVec b + | 0, _ => 0 + | b+1, x => BitVec.cons (x (Fin.last b)) (bitsValue (fun i => x i.castSucc)) + +lemma bitsValue_bit {b : ℕ} (x : Fin b → Bool) (i : Fin b) : + (bitsValue x).getLsbD i.val = x i := by + induction b with + | zero => exact Fin.elim0 i + | succ b ih => + refine Fin.lastCases ?_ (fun j => ?_) i + · simp only [bitsValue, Fin.val_last, BitVec.getLsbD_cons, ite_true] + · simp only [bitsValue, BitVec.getLsbD_cons, Fin.val_castSucc, + ite_eq_right (Nat.ne_of_lt j.isLt)] + exact ih _ j + +lemma bitsValue_bits {b : ℕ} (x : BitVec b) : + bitsValue (fun i : Fin b => x.getLsbD i.val) = x := by + apply BitVec.eq_of_getLsbD_eq + intro i hi + exact bitsValue_bit _ ⟨i,hi⟩ + +def bitsEquiv (b : ℕ) : (Fin b → Bool) ≃ BitVec b where + toFun := bitsValue + invFun := fun x i => x.getLsbD i.val + left_inv := by intro x; funext i; exact bitsValue_bit x i + right_inv := bitsValue_bits + +/-- The exact integer in the two most significant wires is the quarter-bin. -/ +lemma bitsValue_quarter (b : ℕ) (x : Fin (b+2) → Bool) : + (bitsValue x).toNat / 2^b = + 2*(x (Fin.last (b+1))).toNat + (x ((Fin.last b).castSucc)).toNat := by + have hlow := (bitsValue (fun i : Fin b => x i.castSucc.castSucc)).isLt + simp only [bitsValue, BitVec.toNat_cons', Nat.shiftLeft_eq] + have he : (x (Fin.last (b+1))).toNat * 2^(b+1) + + ((x ((Fin.last b).castSucc)).toNat * 2^b + + (bitsValue (fun i : Fin b => x i.castSucc.castSucc)).toNat) = + (2*(x (Fin.last (b+1))).toNat + (x ((Fin.last b).castSucc)).toNat) * 2^b + + (bitsValue (fun i : Fin b => x i.castSucc.castSucc)).toNat := by + rw [pow_succ] + ring + rw [he, Nat.mul_comm _ (2^b), Nat.mul_add_div (by positivity), + Nat.div_eq_of_lt hlow, Nat.add_zero] + +end ExactQuantumFactoring + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitNumbers.lean b/lean/OAI/Computability/QuantumFactoring/BitNumbers.lean new file mode 100644 index 0000000000000000000000000000000000000000..0f86129d86d564b85a06960bcc4e4ca4a46b7c07 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitNumbers.lean @@ -0,0 +1,33 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitEncoding + +namespace OAI + +section +open scoped BigOperators + + +namespace ExactQuantumFactoring +open scoped BigOperators + +lemma bitsValue_toNat {b : ℕ} (x : Fin b → Bool) : + (bitsValue x).toNat = ∑ i : Fin b, 2^i.val*(x i).toNat := by + induction b with + | zero => simp [bitsValue] + | succ b ih => + rw [bitsValue, BitVec.toNat_cons', Nat.shiftLeft_eq, ih, Fin.sum_univ_castSucc] + simp only [Fin.val_last, Fin.val_castSucc] + ring + +lemma bitsValue_ofFn {b : ℕ} (v : Fin (2^b)) : + (bitsValue (fun i : Fin b => v.val.testBit i.val)).toNat = v.val := by + have he : (fun i : Fin b => v.val.testBit i.val) = + (fun i : Fin b => (BitVec.ofNat b v.val).getLsbD i.val) := by simp + rw [he, bitsValue_bits, BitVec.toNat_ofNat, Nat.mod_eq_of_lt v.isLt] + +end ExactQuantumFactoring + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitResidue.lean b/lean/OAI/Computability/QuantumFactoring/BitResidue.lean new file mode 100644 index 0000000000000000000000000000000000000000..5cbc0eeac959fb6d318cd92e4506e1101a555afd --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitResidue.lean @@ -0,0 +1,61 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.PhasePreparationConnection + +namespace OAI + +section +open scoped BigOperators + + +namespace ExactQuantumFactoring + +/-- The fixed little-endian physical representation of a modular residue. -/ +def basisResidue (b : ℕ) : Basis b ≃ ZMod (2^b) := + (basisNumber b).trans (ZMod.finEquiv (2^b)).toEquiv + +lemma finEquiv_val {n : ℕ} [NeZero n] (z : Fin n) : + (ZMod.finEquiv n z).val = z.val := by + cases n with + | zero => exact False.elim (NeZero.ne 0 rfl) + | succ n => rfl + +lemma basisResidue_val (b : ℕ) (x : Basis b) : + (basisResidue b x).val = (bitsValue x).toNat := by + exact finEquiv_val _ + +lemma basisResidue_eq (b : ℕ) (x : Basis b) : + basisResidue b x = ((bitsValue x).toNat : ZMod (2^b)) := by + rw [← basisResidue_val, ZMod.natCast_zmod_val] + +lemma bitsValue_residue (b : ℕ) (z : ZMod (2^b)) : + (bitsValue ((basisResidue b).symm z)).toNat = z.val := by + rw [← basisResidue_val, Equiv.apply_symm_apply] + +lemma basisResidue_bits (b : ℕ) (v : BitVec b) : + basisResidue b (fun i => v.getLsbD i.val) = (v.toNat : ZMod (2^b)) := by + rw [basisResidue_eq, bitsValue_bits] + +lemma bitsValue_residue_add (b : ℕ) (z : ZMod (2^b)) (d : Basis b) : + (fun i : Fin b => (bitsValue ((basisResidue b).symm z)+bitsValue d).getLsbD i.val) = + (basisResidue b).symm (z+basisResidue b d) := by + apply (basisResidue b).injective + rw [basisResidue_bits, Equiv.apply_symm_apply, BitVec.toNat_add] + rw [ZMod.natCast_mod, Nat.cast_add, bitsValue_residue, ZMod.natCast_zmod_val, + basisResidue_eq] + +lemma basisResidue_zero (b : ℕ) : basisResidue b (fun _ => false) = 0 := by + rw [basisResidue_eq] + have h : bitsValue (fun _ : Fin b => false) = (0 : BitVec b) := by + apply BitVec.eq_of_getLsbD_eq + intro i hi + rw [show (bitsValue (fun _ : Fin b => false)).getLsbD i = false from bitsValue_bit _ ⟨i,hi⟩] + simp + rw [h] + simp + +end ExactQuantumFactoring + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackAdder.lean b/lean/OAI/Computability/QuantumFactoring/BitStackAdder.lean new file mode 100644 index 0000000000000000000000000000000000000000..4f95d73fb09757eb45c46a978efb3244850011cc --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackAdder.lean @@ -0,0 +1,162 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackBinaryBasics +import OAI.Computability.QuantumFactoring.BitStackUnary + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram + +/-- Literal full-adder truth tables, not an arithmetic oracle. -/ +def sumBit (a b c : Bool) : Bool := xor a (xor b c) +def carryBit (a b c : Bool) : Bool := (a && b) || (a && c) || (b && c) + +lemma sum_carry (a b c : Bool) : + a.toNat+b.toNat+c.toNat=(sumBit a b c).toNat+2*(carryBit a b c).toNat := by + cases a <;> cases b <;> cases c <;> decide + +abbrev AddState := List Bool × List Bool × Bool × List Bool +abbrev addStateCode : AddState→List Bool := + prodCode id (prodCode id (prodCode Procedure.boolCode id)) + +def addStep (s : AddState) : AddState := + (s.1.tail,s.2.1.tail, + carryBit (s.1.headD false) (s.2.1.headD false) s.2.2.1, + sumBit (s.1.headD false) (s.2.1.headD false) s.2.2.1 :: s.2.2.2) + +def addMeasure (s : AddState) : ℕ := s.1.length+s.2.1.length+s.2.2.1.toNat + +def residual (s : AddState) : ℕ := binaryValue s.1+binaryValue s.2.1+s.2.2.1.toNat + +def addInvariant (s : AddState) : ℕ := + binaryValue s.2.2.2.reverse+2^s.2.2.2.length*residual s + +lemma binaryValue_head_tail (xs : List Bool) : + binaryValue xs=(xs.headD false).toNat+2*binaryValue xs.tail := by + cases xs <;> rfl + +lemma addInvariant_step (s : AddState) : addInvariant (addStep s)=addInvariant s := by + have hx:=binaryValue_head_tail s.1 + have hy:=binaryValue_head_tail s.2.1 + have hh:=sum_carry (s.1.headD false) (s.2.1.headD false) s.2.2.1 + simp only [addInvariant,addStep,List.reverse_cons,binaryValue_append,List.length_reverse, + binaryValue,List.length_cons,pow_succ,residual] + rw [hx,hy] + nlinarith [congrArg (fun n : ℕ=>2^s.2.2.2.length*n) hh] + +lemma addMeasure_step (s : AddState) : addMeasure (addStep s)≤addMeasure s-1 := by + rcases s with ⟨xs,ys,c,zs⟩ + cases xs with + | nil=>cases ys with + | nil=>cases c <;> simp [addMeasure,addStep,carryBit] + | cons b bs=>cases b <;> cases c <;> simp [addMeasure,addStep,carryBit] + | cons a as=>cases ys with + | nil=>cases a <;> cases c <;> simp [addMeasure,addStep,carryBit] + | cons b bs=>cases a <;> cases b <;> cases c <;> + simp [addMeasure,addStep,carryBit] <;> omega + +lemma addMeasure_iterate (i : ℕ) (s : AddState) : + addMeasure (addStep^[i] s)≤addMeasure s-i := by + induction i with + | zero=>simp + | succ i ih=> + rw [Function.iterate_succ_apply'] + exact (addMeasure_step _).trans (by omega) + +lemma addInvariant_iterate (i : ℕ) (s : AddState) : + addInvariant (addStep^[i] s)=addInvariant s := by + induction i with + | zero=>rfl + | succ i ih=>rw [Function.iterate_succ_apply',addInvariant_step,ih] + +lemma residual_zero {s : AddState} (h : addMeasure s=0) : residual s=0 := by + have hx : s.1=[]:=List.length_eq_zero_iff.mp (by unfold addMeasure at h;omega) + have hy : s.2.1=[]:=List.length_eq_zero_iff.mp (by unfold addMeasure at h;omega) + have hc : s.2.2.1.toNat=0:=by unfold addMeasure at h;omega + simp [residual,hx,hy,hc,binaryValue] + +def wordAdd (x : List Bool×List Bool) : List Bool := + (addStep^[x.1.length+x.2.length+1] (x.1,x.2,false,[])).2.2.2.reverse + +lemma wordAdd_value (x : List Bool×List Bool) : + binaryValue (wordAdd x)=binaryValue x.1+binaryValue x.2 := by + let s : AddState:=(x.1,x.2,false,[]) + let i:=x.1.length+x.2.length+1 + have hz : addMeasure (addStep^[i] s)=0:=by + have hh:=addMeasure_iterate i s + simp only [s,i,addMeasure,Bool.toNat_false,Nat.add_zero] at hh + dsimp only [s,i,addMeasure] + omega + have hh:=addInvariant_iterate i s + simp only [addInvariant,residual_zero hz,Nat.mul_zero,Nat.add_zero] at hh + simpa [s,i,wordAdd,residual,binaryValue] using hh + +lemma addStep_size (s : AddState) : + (addStateCode (addStep s)).length≤(addStateCode s).length+1 := by + simp only [addStateCode,addStep,prodCode,pairBits_length,id_eq,Procedure.boolCode, + List.length_cons,List.length_tail] + omega + +namespace Procedure +variable {α : Type} {ea : α→List Bool} {f : α→α} + +noncomputable def iterateLinear (p : Procedure ea ea f) (c : ℕ) + (hg : ∀a,(ea (f a)).length≤(ea a).length+c) : + Procedure (prodCode unaryCode ea) ea (fun x=>f^[x.1] x.2) := by + have hh : ∀ i a,(ea (f^[i] a)).length≤(ea a).length+i*c:=by + intro i a + induction i with + | zero=>simp + | succ i ih=> + rw [Function.iterate_succ_apply'] + have h:=hg (f^[i] a) + nlinarith + exact p.iterate (Polynomial.C (c+1)*Polynomial.X) (by + intro n a i hi + have h:=hh i a + simp only [Polynomial.eval_mul,Polynomial.eval_C,Polynomial.eval_X] + nlinarith) + +noncomputable def addStepP : Procedure addStateCode addStateCode addStep := by + let x:=first (id : List Bool→List Bool) (prodCode id (prodCode boolCode id)) + let rem:=second (id : List Bool→List Bool) (prodCode id (prodCode boolCode id)) + let y:=(first (id : List Bool→List Bool) (prodCode boolCode id)).comp rem + let co:=(second (id : List Bool→List Bool) (prodCode boolCode id)).comp rem + let c:=(first boolCode (id : List Bool→List Bool)).comp co + let zs:=(second boolCode (id : List Bool→List Bool)).comp co + let bits:=(head.comp x).pair ((head.comp y).pair c) + let newc:=(ofBool₃ boolCode carryBit).comp bits + let newb:=(ofBool₃ boolCode sumBit).comp bits + exact ((tail.comp x).pair ((tail.comp y).pair + (newc.pair (cons.comp (newb.pair zs))))).congrFun (by intro s;rfl) + +noncomputable def wordAddP : Procedure (prodCode (id : List Bool→List Bool) id) id wordAdd := by + let x:=first (id : List Bool→List Bool) (id : List Bool→List Bool) + let y:=second (id : List Bool→List Bool) (id : List Bool→List Bool) + let len:=unarySuccessor.comp (unaryAdd.comp ((length.comp x).pair (length.comp y))) + let start:=x.pair (y.pair ((constant (prodCode id id) boolCode false).pair + (constant (prodCode id id) (id : List Bool→List Bool) []))) + let rep:=addStepP.iterateLinear 1 addStep_size + let co:=(second (id : List Bool→List Bool) (prodCode boolCode id)).comp + (second (id : List Bool→List Bool) (prodCode id (prodCode boolCode id))) + let zs:=(second boolCode (id : List Bool→List Bool)).comp co + exact (reverse.comp (zs.comp (rep.comp (len.pair start)))).congrFun (by intro x;rfl) + +noncomputable def binaryAdd : Procedure (prodCode Nat.bits Nat.bits) Nat.bits + (fun x=>x.1+x.2) := + ((normalize.comp wordAddP).precompose (fun x : ℕ×ℕ=>(x.1.bits,x.2.bits))).congrFun + (by + intro x + change binaryValue (wordAdd (x.1.bits,x.2.bits))=x.1+x.2 + rw [wordAdd_value,binaryValue_bits,binaryValue_bits]) + +end Procedure +end ExactQuantumFactoring.BitStackProgram + +end + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackAssociation.lean b/lean/OAI/Computability/QuantumFactoring/BitStackAssociation.lean new file mode 100644 index 0000000000000000000000000000000000000000..874d1510e52dc074892b4dff8f966ea184c46c7a --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackAssociation.lean @@ -0,0 +1,80 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackListOps +import OAI.Computability.QuantumFactoring.BitStackDivision +import OAI.Computability.QuantumFactoring.BitStackOptions + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram +variable {α β : Type} [DecidableEq α] +def assocLookup (k : α) : List (α×β)→Option β + | []=>none + | (a,v)::as=>if k=a then some v else assocLookup k as +def assocStep (x : (α×β)×(α×Option β)) : α×Option β := + (x.2.1,if x.2.1=x.1.1 then some x.1.2 else x.2.2) +lemma assocFold_reverse (xs : List (α×β)) (k : α) (o : Option β) : + xs.reverse.foldl (fun s a=>assocStep (a,s)) (k,o)= + (k,match assocLookup k xs with | none=>o | some b=>some b) := by + induction xs with + | nil=>rfl + | cons a as ih=> + rw [List.reverse_cons,List.foldl_append,List.foldl_cons,List.foldl_nil,ih] + by_cases h:k=a.1 <;> simp [assocStep,assocLookup,h] +lemma assocFold_size (ea : α→List Bool) (eb : β→List Bool) + (xs : List (α×β)) (s : α×Option β) : + (prodCode ea (optionCode eb) (xs.foldl (fun s a=>assocStep (a,s)) s)).length≤ + (prodCode ea (optionCode eb) s).length+(listCode (prodCode ea eb) xs).length := by + induction xs generalizing s with + | nil=>simp + | cons a as ih=> + have hh:=ih (assocStep (a,s)) + have hb : (prodCode ea (optionCode eb) (assocStep (a,s))).length≤ + (prodCode ea (optionCode eb) s).length+2*(prodCode ea eb a).length+2:=by + unfold assocStep + split <;> simp only [prodCode,pairBits_length,optionCode,List.length_cons] <;> omega + simp only [List.foldl_cons,listCode_length_cons] + omega + +namespace Procedure +variable {ea : α→List Bool} {eb : β→List Bool} +noncomputable def association (da : α) (db : β) + (eqp : Procedure (prodCode ea ea) boolCode (fun x=>decide (x.1=x.2))) : + Procedure (prodCode ea (listCode (prodCode ea eb))) (optionCode eb) + (fun x=>assocLookup x.1 x.2) := by + let ent:=prodCode ea eb + let st:=prodCode ea (optionCode eb) + let e:=first ent st + let s:=second ent st + let key:=(first ea (optionCode eb)).comp s + let ky:=(first ea eb).comp e + let value:=(second ea eb).comp e + let upd:=conditional (eqp.comp (key.pair ky)) ((optionSome eb).comp value) + ((second ea (optionCode eb)).comp s) + let step : Procedure (prodCode ent st) st (assocStep (α:=α) (β:=β)):= + (key.pair upd).congrFun (by intro x; simp only [assocStep,Function.comp_apply,decide_eq_true_eq]) + let fold:=foldList (da,db) step Polynomial.X (by + intro xs s i + have hh:=assocFold_size ea eb (xs.take i) s + have ht:=listCode_length_take_le ent i xs + simp only [Polynomial.eval_X] + dsimp only [ent,st] at ht ⊢ + omega) + let start:=((listReverse ent (da,db)).comp (second ea (listCode ent))).pair + ((first ea (listCode ent)).pair (constant (prodCode ea (listCode ent)) (optionCode eb) none)) + exact ((second ea (optionCode eb)).comp (fold.comp start)).congrFun (by + intro x + change (x.2.reverse.foldl (fun s a=>assocStep (a,s)) (x.1,none)).2=assocLookup x.1 x.2 + rw [assocFold_reverse] + cases assocLookup x.1 x.2 <;> rfl) +end Procedure +end ExactQuantumFactoring.BitStackProgram + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackBasicProcedures.lean b/lean/OAI/Computability/QuantumFactoring/BitStackBasicProcedures.lean new file mode 100644 index 0000000000000000000000000000000000000000..ffcea635cd7d243d46966654b3bd1ff7aaa82a2e --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackBasicProcedures.lean @@ -0,0 +1,96 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackProducts + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram +namespace Procedure +variable {α β γ : Type} {ea : α→List Bool} {eb : β→List Bool} {ec : γ→List Bool} + {f : α→β} {g : α→γ} + +/-- Duplicate the input word and quote the first copy to represent a pair. -/ +noncomputable def duplicate (ea : α→List Bool) : + Procedure ea (prodCode ea ea) (fun a=>(a,a)) where + K:=Fin 4 + finiteK:=inferInstance + decideK:=inferInstance + input:=0 + output:=3 + program:=.seq (duplicateReverse 0 1 2) (.seq (reverseMove 1 3) (quoteMove 0 3 1)) + bound:=Polynomial.C 14*Polynomial.X+Polynomial.C 8 + runs a:=by + let s : Store (Fin 4):=singletonStore 0 (ea a) + let u : Store (Fin 4):=Function.update s 1 (ea a).reverse + let v : Store (Fin 4):=Function.update s 3 (ea a) + have h1 : Runs (duplicateReverse 0 1 2) s u (5*(ea a).length+2) := by + have hh:=duplicateReverse_runs (0 : Fin 4) 1 2 (by decide) (by decide) (by decide) + s (by simp [s,singletonStore]) + simpa only [u,s,singletonStore,Function.update_self, + Function.update_of_ne (by decide : (1 : Fin 4)≠0),List.append_nil] using hh + have h2 : Runs (reverseMove 1 3) u v (2*(ea a).length+1) := by + have hh:=reverseMove_runs (1 : Fin 4) 3 (by decide) u + convert hh using 1 + · funext k; fin_cases k <;> simp [u,v,s,singletonStore,Function.update] + · simp [u] + have h3 : Runs (quoteMove 0 3 1) v + (singletonStore 3 (prodCode ea ea (a,a))) (7*(ea a).length+5) := by + have hh:=quoteMove_runs (0 : Fin 4) 3 1 (by decide) (by decide) (by decide) v + (by simp [v,s,singletonStore]) + convert hh using 1 + · funext k; fin_cases k <;> simp [v,s,singletonStore,Function.update,prodCode,pairBits] + · simp [v,s,singletonStore] + refine ⟨(7*(ea a).length+5)+(2*(ea a).length+1)+(5*(ea a).length+2),?_, + Runs.seq h1 (Runs.seq h2 h3)⟩ + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_C,Polynomial.eval_X] + omega + +noncomputable def pair (p : Procedure ea eb f) (q : Procedure ea ec g) : + Procedure ea (prodCode eb ec) (fun a=>(f a,g a)) := + (p.parallel q).comp (duplicate ea) + +/-- Projection parses the actual prefix code and explicitly clears its tail. -/ +noncomputable def first (ea : α→List Bool) (eb : β→List Bool) : + Procedure (prodCode ea eb) ea Prod.fst where + K:=Fin 4 + finiteK:=inferInstance + decideK:=inferInstance + input:=0 + output:=1 + program:=.seq (unquoteMove 0 1 2 3) (clear 0) + bound:=Polynomial.C 7*Polynomial.X+Polynomial.C 7 + runs x:=by + let s : Store (Fin 4):=singletonStore 0 (prodCode ea eb x) + let u : Store (Fin 4):=Function.update (singletonStore 0 (eb x.2)) 1 (ea x.1) + have h1 : Runs (unquoteMove 0 1 2 3) s u (7*(ea x.1).length+6) := by + have hh:=unquoteMove_runs (0 : Fin 4) 1 2 3 (by decide) (by decide) (by decide) + (by decide) (by decide) (by decide) (ea x.1) (eb x.2) s + (by simp [s,singletonStore,prodCode,pairBits]) + (by simp [s,singletonStore]) (by simp [s,singletonStore]) + convert hh using 1 + funext k; fin_cases k <;> simp [s,u,singletonStore,Function.update] + have h2 : Runs (clear 0) u (singletonStore 1 (ea x.1)) (2*(eb x.2).length+1) := by + have hh:=clear_runs (0 : Fin 4) u + convert hh using 1 + · funext k; fin_cases k <;> simp [u,singletonStore,Function.update] + · simp [u,singletonStore] + refine ⟨(2*(eb x.2).length+1)+(7*(ea x.1).length+6),?_,Runs.seq h1 h2⟩ + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_C,Polynomial.eval_X, + prodCode,pairBits_length] + omega + +noncomputable def second (ea : α→List Bool) (eb : β→List Bool) : + Procedure (prodCode ea eb) eb Prod.snd := + ((first eb ea).comp (swap ea eb)).congrFun (by intro x; rfl) + +end Procedure +end ExactQuantumFactoring.BitStackProgram + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackBinaryBasics.lean b/lean/OAI/Computability/QuantumFactoring/BitStackBinaryBasics.lean new file mode 100644 index 0000000000000000000000000000000000000000..25980d544a84db91dc2716a442dea0da9b0b12fb --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackBinaryBasics.lean @@ -0,0 +1,87 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackNaturals +import OAI.Computability.QuantumFactoring.BitStackFold + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram +lemma binaryValue_append (xs ys : List Bool) : + binaryValue (xs++ys)=binaryValue xs+2^xs.length*binaryValue ys := by + induction xs with + | nil=>simp [binaryValue] + | cons b bs ih=> + simp only [List.cons_append,List.length_cons,binaryValue,ih,pow_succ] + ring + +lemma bigEndian_value (xs : List Bool) (a : ℕ) : + xs.foldl (bitAction (fun n=>2*n) (fun n=>2*n+1)) a= + binaryValue xs.reverse+2^xs.length*a := by + induction xs generalizing a with + | nil=>simp [binaryValue] + | cons b bs ih=> + simp only [List.foldl_cons,ih,List.reverse_cons,binaryValue_append, + List.length_reverse,List.length_cons,pow_succ] + cases b <;> simp [bitAction,binaryValue] <;> ring + +lemma double_bits_length (n : ℕ) : (2*n).bits.length≤n.bits.length+1 := by + by_cases h : n=0 + · subst n;simp + · rw [Nat.bit0_bits n h,List.length_cons] +lemma doubleOne_bits_length (n : ℕ) : (2*n+1).bits.length≤n.bits.length+1 := by + rw [Nat.bit1_bits,List.length_cons] + +namespace Procedure +noncomputable def double : Procedure Nat.bits Nat.bits (fun n=>2*n) where + K:=Unit + finiteK:=inferInstance + decideK:=inferInstance + input:=() + output:=() + program:=.cases () .skip (.seq (.push () false) (.push () false)) + (.seq (.push () true) (.push () false)) + bound:=Polynomial.C 3 + runs n:=by + by_cases hn : n=0 + · subst n + refine ⟨2,by simp,?_⟩ + exact Runs.cases_nil (by simp [singletonStore]) (Runs.skip _) + · have he : n.bits≠[]:=by + intro h + have hv:=binaryValue_bits n + rw [h] at hv + exact hn hv.symm + cases hb : n.bits with + | nil=>exact (he hb).elim + | cons b bs=> + have hout : (2*n).bits=false::b::bs:=by rw [Nat.bit0_bits n hn,hb] + have hbody : Runs (.seq (.push () b) (.push () false)) + (singletonStore () bs) (singletonStore () (false::b::bs)) 2:=by + have hh:=Runs.seq (Runs.push (singletonStore () bs) () b) + (Runs.push (singletonStore () (b::bs)) () false) + simpa only [singletonStore,Function.update_self,Function.update_idem] using hh + refine ⟨3,by simp,?_⟩ + rw [hout] + cases b + · exact Runs.cases_false (xs:=bs) (by simp [singletonStore]) (by simpa [singletonStore] using hbody) + · exact Runs.cases_true (xs:=bs) (by simp [singletonStore]) (by simpa [singletonStore] using hbody) + +noncomputable def doubleOne : Procedure Nat.bits Nat.bits (fun n=>2*n+1) := + (prepend Nat.bits [true]).result (by intro n;simp only [List.singleton_append,Nat.bit1_bits,id_eq]) + +/-- Canonicalize a binary word, charging a linear-growth bit fold. -/ +noncomputable def normalize : Procedure (id : List Bool→List Bool) Nat.bits binaryValue := by + let p:=foldBitsLinear double doubleOne 1 double_bits_length doubleOne_bits_length + let start:=reverse.pair (constant (id : List Bool→List Bool) Nat.bits 0) + exact (p.comp start).congrFun (by intro xs;simp [bigEndian_value]) +end Procedure +end ExactQuantumFactoring.BitStackProgram + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackBooleans.lean b/lean/OAI/Computability/QuantumFactoring/BitStackBooleans.lean new file mode 100644 index 0000000000000000000000000000000000000000..7345358e0785f2d4077417e9bcefb2eb8ec25bfc --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackBooleans.lean @@ -0,0 +1,54 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackWords + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram.Procedure +variable {β : Type} + +/-- A truth table on one Boolean has two literal finite output words. This +performs no run-time computation in its Boolean branch labels. -/ +noncomputable def ofBool (eb : β→List Bool) (f : Bool→β) : + Procedure boolCode eb f := by + let p:=constant (fun _ : Unit=>[]) eb (f false) + let q:=constant (fun _ : Unit=>[]) eb (f true) + exact ((chooseBit p q).precompose (fun b=>(b,()))).congrFun + (by intro b;cases b <;> rfl) + +noncomputable def ofBool₂ (eb : β→List Bool) (f : Bool→Bool→β) : + Procedure (prodCode boolCode boolCode) eb (fun x=>f x.1 x.2) := + (choose (ofBool eb (f false)) (ofBool eb (f true))).congrFun + (by rintro ⟨b,c⟩;cases b <;> rfl) + +noncomputable def ofBool₃ (eb : β→List Bool) (f : Bool→Bool→Bool→β) : + Procedure (prodCode boolCode (prodCode boolCode boolCode)) eb + (fun x=>f x.1 x.2.1 x.2.2) := + (choose (ofBool₂ eb (f false)) (ofBool₂ eb (f true))).congrFun + (by rintro ⟨b,c,d⟩;cases b <;> rfl) + +noncomputable def boolNot : Procedure boolCode boolCode not := ofBool boolCode not +noncomputable def boolAnd : Procedure (prodCode boolCode boolCode) boolCode + (fun x=>x.1 && x.2) := ofBool₂ boolCode and +noncomputable def boolOr : Procedure (prodCode boolCode boolCode) boolCode + (fun x=>x.1 || x.2) := ofBool₂ boolCode or +noncomputable def boolXor : Procedure (prodCode boolCode boolCode) boolCode + (fun x=>xor x.1 x.2) := ofBool₂ boolCode xor + +noncomputable def cons : Procedure (prodCode boolCode (id : List Bool→List Bool)) id + (fun x=>x.1::x.2) := by + let pp : Procedure (id : List Bool→List Bool) id (fun xs=>false::xs):= + (prepend id [false]).result (by intro xs;rfl) + let qq : Procedure (id : List Bool→List Bool) id (fun xs=>true::xs):= + (prepend id [true]).result (by intro xs;rfl) + exact (choose pp qq).congrFun (by rintro ⟨b,xs⟩;cases b <;> rfl) +end ExactQuantumFactoring.BitStackProgram.Procedure + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackBoundedPrime.lean b/lean/OAI/Computability/QuantumFactoring/BitStackBoundedPrime.lean new file mode 100644 index 0000000000000000000000000000000000000000..8337b40888a8d17e73d2772346cc003cb949c8c9 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackBoundedPrime.lean @@ -0,0 +1,57 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackTabulate +import OAI.Computability.QuantumFactoring.BitStackDivision +import OAI.Computability.QuantumFactoring.BitStackOptions + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram +lemma boolFold_eq (xs : List Bool) (b : Bool) : + xs.foldl (fun b a=>a&&b) b=(xs.all id && b):=by + induction xs generalizing b with + | nil=>simp + | cons a xs ih=>simp only [List.foldl_cons,ih,List.all_cons,id_eq];cases a <;> cases b <;> simp +namespace Procedure +noncomputable def boolListAll : Procedure (listCode boolCode) boolCode (fun xs=>xs.all id):=by + let fold:=foldList false boolAnd (Polynomial.C 1) (by intro xs b i;simp only [boolCode,List.length_singleton,Polynomial.eval_C];rfl) + exact (fold.comp ((identity _).pair (constant _ boolCode true))).congrFun (by intro xs;change xs.foldl (fun b a=>a&&b) true=xs.all id;rw [boolFold_eq];simp) +noncomputable def unaryPrime : Procedure unaryCode boolCode (fun n=>decide (Nat.Prime n)):=by + let i:=(unaryToBits.comp (first unaryCode Nat.bits)) + let n:=second unaryCode Nat.bits + let small:=binaryLt.comp (i.pair (constant _ Nat.bits 2)) + let nondvd:=boolNot.comp (binaryEq.comp ((binaryMod.comp (n.pair i)).pair (constant _ Nat.bits 0))) + let test:=boolOr.comp (small.pair nondvd) + let table:=tabulate (f:=fun n i=>decide (i<2) || !decide (n%i=0)) false test + let all:=(boolListAll.comp table).comp ((identity unaryCode).pair unaryToBits) + let large:=boolNot.comp (binaryLt.comp (unaryToBits.pair (constant unaryCode Nat.bits 2))) + exact (boolAnd.comp (large.pair all)).congrFun (by + intro n + apply Bool.eq_iff_iff.mpr + change ((!decide (n<2)) && ((List.range n).map (fun i=>decide (i<2) || !decide (n%i=0))).all id)=true ↔ _ + simp only [Bool.and_eq_true,Bool.not_eq_true',decide_eq_false_iff_not,List.all_eq_true,List.mem_map, + id_eq,decide_eq_true_eq] + rw [Nat.prime_def_lt'] + constructor + · rintro ⟨hn,h⟩ + refine ⟨by omega,?_⟩ + intro m hm hmn hd + have ht:=h _ ⟨m,List.mem_range.mpr hmn,rfl⟩ + simp only [Bool.or_eq_true,decide_eq_true_eq,Bool.not_eq_true',decide_eq_false_iff_not] at ht + exact ht.elim (by omega) (fun h=>h (Nat.dvd_iff_mod_eq_zero.mp hd)) + · rintro ⟨hn,h⟩ + refine ⟨by omega,?_⟩ + rintro b ⟨m,hm,rfl⟩ + simp only [Bool.or_eq_true,decide_eq_true_eq,Bool.not_eq_true',decide_eq_false_iff_not] + by_cases hlt : m<2 + · exact Or.inl hlt + · exact Or.inr (fun hz=>h m (by omega) (List.mem_range.mp hm) (Nat.dvd_iff_mod_eq_zero.mpr hz))) +end Procedure + +end ExactQuantumFactoring.BitStackProgram +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackBoundedUnary.lean b/lean/OAI/Computability/QuantumFactoring/BitStackBoundedUnary.lean new file mode 100644 index 0000000000000000000000000000000000000000..534133a5565e7f43cbcaaaf248601c916470a54f --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackBoundedUnary.lean @@ -0,0 +1,55 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackDivision + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram + +def unaryDecodeStep (s : ℕ×ℕ) : ℕ×ℕ := if s.1=0 then s else (s.1-1,s.2+1) +lemma unaryDecodeStep_iterate (k : ℕ) (s : ℕ×ℕ) : + (unaryDecodeStep^[k]) s=(s.1-k,s.2+min k s.1) := by + induction k generalizing s with + | zero=>simp + | succ k ih=> + rw [Function.iterate_succ_apply,ih] + unfold unaryDecodeStep + split + · rename_i hz + apply Prod.ext <;> dsimp only <;> omega + · rename_i hz + apply Prod.ext <;> dsimp only <;> omega +namespace Procedure +noncomputable def unaryDecodeStepP : Procedure (prodCode Nat.bits unaryCode) (prodCode Nat.bits unaryCode) + unaryDecodeStep := by + let x:=first Nat.bits unaryCode + let y:=second Nat.bits unaryCode + let next:=(binarySub.comp (x.pair (Procedure.constant _ Nat.bits 1))).pair (unarySuccessor.comp y) + exact (conditional (binaryZero.comp x) (identity _) next).congrFun (by + intro s;unfold unaryDecodeStep;split <;> simp_all) +noncomputable def clippedUnary : Procedure (prodCode unaryCode Nat.bits) unaryCode (fun x=>min x.1 x.2) := by + let rep:=unaryDecodeStepP.iterate Polynomial.X (by + intro n s i hi + rw [unaryDecodeStep_iterate] + have hbits:=bits_length_mono (Nat.sub_le s.1 i) + simp only [prodCode,pairBits_length,unaryCode,List.length_replicate,Polynomial.eval_X] + omega) + let inp:=(first unaryCode Nat.bits).pair + ((second unaryCode Nat.bits).pair (Procedure.constant _ unaryCode 0)) + exact ((second Nat.bits unaryCode).comp (rep.comp inp)).congrFun (by + intro x;dsimp only [Function.comp_def];rw [unaryDecodeStep_iterate];simp) +noncomputable def boundedUnary {α : Type} {ea : α→List Bool} {f B : α→ℕ} + (p : Procedure ea Nat.bits f) (b : Procedure ea unaryCode B) (h : ∀a,f a ≤ B a) : + Procedure ea unaryCode f := + (clippedUnary.comp (b.pair p)).congrFun (by intro a;exact min_eq_right (h a)) +end Procedure +end ExactQuantumFactoring.BitStackProgram + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackChoice.lean b/lean/OAI/Computability/QuantumFactoring/BitStackChoice.lean new file mode 100644 index 0000000000000000000000000000000000000000..8dce567f5672e895547fac8cab9a6ca287c5a6b4 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackChoice.lean @@ -0,0 +1,162 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackProducts +import OAI.Computability.QuantumFactoring.BitStackConstants + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram + +def leftPublic (K L : Type) : (K ⊕ Fin 2) ↪ ((K ⊕ L) ⊕ Fin 2) where + toFun := fun k=>match k with | .inl i=>.inl (.inl i) | .inr i=>.inr i + inj' := by intro i j h; cases i <;> cases j <;> simp_all + +def rightPublic (K L : Type) : (L ⊕ Fin 2) ↪ ((K ⊕ L) ⊕ Fin 2) where + toFun := fun k=>match k with | .inl i=>.inl (.inr i) | .inr i=>.inr i + inj' := by intro i j h; cases i <;> cases j <;> simp_all + +namespace Procedure +variable {α β γ : Type} {ea : α→List Bool} {eb : β→List Bool} {f g : α→β} +/-- A same-wire interface, even when the input and output word encodings differ. -/ +noncomputable abbrev shared (p : Procedure ea eb f) : Procedure ea eb f where + K:=p.K ⊕ Fin 2 + finiteK:=inferInstance + decideK:=inferInstance + input:=Sum.inr 0 + output:=Sum.inr 0 + program:=.seq (moveWord (Sum.inr 0) (Sum.inl p.input) (Sum.inr 1)) + (.seq (p.program.relabel Sum.inl) + (moveWord (Sum.inl p.output) (Sum.inr 0) (Sum.inr 1))) + bound:=Polynomial.C 8*Polynomial.X+Polynomial.C 5*p.bound+Polynomial.C 4 + runs a:=by + obtain ⟨cp,hcp,hp⟩:=p.runs a + have h1:=moveWord_runs (Sum.inr 0 : p.K ⊕ Fin 2) (Sum.inl p.input) (Sum.inr 1) + (by simp) (by simp) (by simp) (ea a) + have h2:=hp.relabel (leftEmbed p.K (Fin 2)) (fun _=>[]) + simp only [overlay_singleton] at h2 + have h3:=moveWord_runs (Sum.inl p.output : p.K ⊕ Fin 2) (Sum.inr 0) (Sum.inr 1) + (by simp) (by simp) (by simp) (eb (f a)) + refine ⟨(4*(eb (f a)).length+2)+cp+(4*(ea a).length+2),?_, + Runs.seq h1 (Runs.seq h2 h3)⟩ + have hl:=p.output_length_le a + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_C,Polynomial.eval_X] + omega + +/-- Reinterpret the domain, with its entire previous encoding still on tape. -/ +def precompose (p : Procedure ea eb f) (h : γ→α) : + Procedure (fun a=>ea (h a)) eb (fun a=>f (h a)) where + K:=p.K + finiteK:=p.finiteK + decideK:=p.decideK + input:=p.input + output:=p.output + program:=p.program + bound:=p.bound + runs a:=p.runs (h a) + +def congrEncoding (p : Procedure ea eb f) {ec : α→List Bool} {ed : β→List Bool} + (ha : ∀a,ea a=ec a) (hb : ∀b,eb b=ed b) : Procedure ec ed f where + K:=p.K + finiteK:=p.finiteK + decideK:=p.decideK + input:=p.input + output:=p.output + program:=p.program + bound:=p.bound + runs a:=by simpa only [ha,hb] using p.runs a + +/-- Change the mathematical output only when its *actual encoded word* agrees. -/ +def result (p : Procedure ea eb f) {ec : γ→List Bool} {h : α→γ} + (hr : ∀a,eb (f a)=ec (h a)) : Procedure ea ec h where + K:=p.K + finiteK:=p.finiteK + decideK:=p.decideK + input:=p.input + output:=p.output + program:=p.program + bound:=p.bound + runs a:=by simpa only [hr a] using p.runs a + +noncomputable def unprefix (ea : α→List Bool) (b : Bool) : + Procedure (fun a=>b::ea a) ea id where + K:=Unit + finiteK:=inferInstance + decideK:=inferInstance + input:=() + output:=() + program:=.cases () .skip .skip .skip + bound:=Polynomial.C 2 + runs a:=by + refine ⟨2,by simp,?_⟩ + have hu : Function.update (singletonStore () (b::ea a)) () (ea a)= + singletonStore () (ea a):=by simp [singletonStore] + cases b + · exact hu ▸ Runs.cases_false (by simp [singletonStore]) (Runs.skip _) + · exact hu ▸ Runs.cases_true (by simp [singletonStore]) (Runs.skip _) + +noncomputable def chooseBit (p : Procedure ea eb f) (q : Procedure ea eb g) : + Procedure (fun x : Bool×α=>x.1::ea x.2) eb (fun x=>if x.1 then g x.2 else f x.2) where + K:=(p.K ⊕ q.K) ⊕ Fin 2 + finiteK:=inferInstance + decideK:=inferInstance + input:=Sum.inr 0 + output:=Sum.inr 0 + program:=.cases (Sum.inr 0) .skip + (p.shared.program.relabel (leftPublic p.K q.K)) + (q.shared.program.relabel (rightPublic p.K q.K)) + bound:=p.shared.bound+q.shared.bound+1 + runs x:=by + rcases x with ⟨b,a⟩ + have hpmono:=eval_nat_mono p.shared.bound (Nat.le_succ (ea a).length) + have hqmono:=eval_nat_mono q.shared.bound (Nat.le_succ (ea a).length) + cases b + · obtain ⟨c,hc,hd⟩:=p.shared.runs a + have hh:=hd.relabel (leftPublic p.K q.K) (fun _=>[]) + simp only [overlay_singleton] at hh + have he : leftPublic p.K q.K p.shared.input=Sum.inr 0:=rfl + rw [he] at hh + refine ⟨c+1,?_,?_⟩ + · rw [Polynomial.eval_add,Polynomial.eval_add,Polynomial.eval_one] + exact Nat.add_le_add_right ((hc.trans hpmono).trans (Nat.le_add_right _ _)) 1 + · have hu : Function.update (singletonStore (Sum.inr 0 : (p.K⊕q.K)⊕Fin 2) + (false::ea a)) (Sum.inr 0) (ea a)=singletonStore (Sum.inr 0) (ea a):=by + simp [singletonStore] + simpa only [hu] using Runs.cases_false (p:=Program.skip) + (r:=q.shared.program.relabel (rightPublic p.K q.K)) + (xs:=ea a) (s:=singletonStore (Sum.inr 0) (false::ea a)) (by simp [singletonStore]) + (by rw [hu];exact hh) + · obtain ⟨c,hc,hd⟩:=q.shared.runs a + have hh:=hd.relabel (rightPublic p.K q.K) (fun _=>[]) + simp only [overlay_singleton] at hh + have he : rightPublic p.K q.K q.shared.input=Sum.inr 0:=rfl + rw [he] at hh + refine ⟨c+1,?_,?_⟩ + · rw [Polynomial.eval_add,Polynomial.eval_add,Polynomial.eval_one] + exact Nat.add_le_add_right ((hc.trans hqmono).trans (Nat.le_add_left _ _)) 1 + · have hu : Function.update (singletonStore (Sum.inr 0 : (p.K⊕q.K)⊕Fin 2) + (true::ea a)) (Sum.inr 0) (ea a)=singletonStore (Sum.inr 0) (ea a):=by + simp [singletonStore] + simpa only [hu] using Runs.cases_true (p:=Program.skip) + (q:=p.shared.program.relabel (leftPublic p.K q.K)) + (xs:=ea a) (s:=singletonStore (Sum.inr 0) (true::ea a)) (by simp [singletonStore]) + (by rw [hu];exact hh) + +abbrev boolCode (b : Bool) : List Bool := [b] +noncomputable def choose (p : Procedure ea eb f) (q : Procedure ea eb g) : + Procedure (prodCode boolCode ea) eb (fun x=>if x.1 then g x.2 else f x.2) := by + let pp:=p.comp (unprefix ea false) + let qq:=q.comp (unprefix ea false) + exact ((chooseBit pp qq).comp + (unprefix (fun x : Bool×α=>x.1::false::ea x.2) true)).congrEncoding + (by intro x;rfl) (by intro b;rfl) +end Procedure +end ExactQuantumFactoring.BitStackProgram + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackComposition.lean b/lean/OAI/Computability/QuantumFactoring/BitStackComposition.lean new file mode 100644 index 0000000000000000000000000000000000000000..995d15fdf0e07f3d439a47c137a726411d0262d8 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackComposition.lean @@ -0,0 +1,95 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackRelabel +import OAI.Computability.QuantumFactoring.BitStackLists +import OAI.Computability.QuantumFactoring.BitStackProcedures + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram +variable {K L : Type} [DecidableEq K] [DecidableEq L] + +omit [DecidableEq K] [DecidableEq L] in +lemma overlay_empty (f : K ↪ L) : overlay f (fun _=>[]) (fun _=>[])=fun _=>[] := by + funext j + by_cases h : ∃ i,f i=j + · rcases h with ⟨i,rfl⟩; exact overlay_at f _ _ i + · exact overlay_outside f _ _ j (by simpa only [not_exists] using h) +lemma overlay_singleton (f : K ↪ L) (k : K) (xs : List Bool) : + overlay f (fun _=>[]) (singletonStore k xs)=singletonStore (f k) xs := by + rw [singletonStore,overlay_update,overlay_empty] + rfl + +/-- Move an entire word without reversing its order. Each symbol is pushed +and popped twice; this is not an atomic bulk-copy instruction. -/ +def moveWord (a b t : K) : Program K := .seq (reverseMove a t) (reverseMove t b) +lemma moveWord_runs (a b t : K) (hab : a≠b) (hat : a≠t) (hbt : b≠t) (xs : List Bool) : + Runs (moveWord a b t) (singletonStore a xs) (singletonStore b xs) (4*xs.length+2) := by + let s := singletonStore a xs + let u := Function.update (Function.update s a []) t ((s a).reverse++s t) + have hh := Runs.seq (reverseMove_runs a t hat s) (reverseMove_runs t b hbt.symm u) + change Runs (.seq _ _) _ _ _ + convert hh using 1 + · funext k + by_cases ha : k=a <;> by_cases hb : k=b <;> by_cases ht : k=t <;> + simp_all [u,s,singletonStore,Function.update,Ne.symm hat,Ne.symm hab,Ne.symm hbt] + · simp only [u,Function.update_self,s,singletonStore,Function.update_self] + simp only [Function.update_of_ne hat.symm,List.append_nil,List.length_reverse] + omega + +namespace Procedure +variable {α β γ : Type} {ea : α→List Bool} {eb : β→List Bool} {ec : γ→List Bool} + {f : α→β} {g : β→γ} + +def joinLeft (A B : Type) : A ↪ A ⊕ (B ⊕ Unit) := ⟨Sum.inl,Sum.inl_injective⟩ +def joinRight (A B : Type) : B ↪ A ⊕ (B ⊕ Unit) := + ⟨Sum.inr ∘ Sum.inl,Sum.inr_injective.comp Sum.inl_injective⟩ + +lemma eval_nat_mono (p : Polynomial ℕ) : Monotone p.eval := by + intro a b hab + change p.eval a ≤ p.eval b + rw [Polynomial.eval_eq_sum,Polynomial.eval_eq_sum] + exact Finset.sum_le_sum (fun i _ => Nat.mul_le_mul_left _ (Nat.pow_le_pow_left hab i)) + +/-- Checked composition for actual finite Boolean-stack procedures. This +constructs the combined program and accounts for the intermediate-word copy; +it does NOT invoke Mathlib's unproved TM2 polytime-composition declaration. -/ +noncomputable def comp (q : Procedure eb ec g) (p : Procedure ea eb f) : + Procedure ea ec (g ∘ f) where + K := p.K ⊕ (q.K ⊕ Unit) + finiteK := inferInstance + decideK := inferInstance + input := Sum.inl p.input + output := Sum.inr (Sum.inl q.output) + program := .seq (p.program.relabel (joinLeft p.K q.K)) + (.seq (moveWord (Sum.inl p.output) (Sum.inr (Sum.inl q.input)) (Sum.inr (Sum.inr ()))) + (q.program.relabel (joinRight p.K q.K))) + bound := p.bound+(Polynomial.C 4*(Polynomial.X+p.bound)+Polynomial.C 2)+ + q.bound.comp (Polynomial.X+p.bound) + runs a := by + obtain ⟨cp,hcp,hp⟩ := p.runs a + obtain ⟨cq,hcq,hq⟩ := q.runs (f a) + have hleft := hp.relabel (joinLeft p.K q.K) (fun _=>[]) + have hright := hq.relabel (joinRight p.K q.K) (fun _=>[]) + simp only [overlay_singleton] at hleft hright + have hmove := moveWord_runs (K:=p.K ⊕ (q.K ⊕ Unit)) (Sum.inl p.output) + (Sum.inr (Sum.inl q.input)) (Sum.inr (Sum.inr ())) + (by simp) (by simp) (by simp) (eb (f a)) + refine ⟨cq+(4*(eb (f a)).length+2)+cp,?_,Runs.seq hleft (Runs.seq hmove hright)⟩ + have hlen := p.output_length_le a + have hmono := eval_nat_mono q.bound hlen + dsimp only at hmono + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_C, + Polynomial.eval_X,Polynomial.eval_comp] + omega +end Procedure +end ExactQuantumFactoring.BitStackProgram + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackConstants.lean b/lean/OAI/Computability/QuantumFactoring/BitStackConstants.lean new file mode 100644 index 0000000000000000000000000000000000000000..d6b15e4b1f4a6797c74f71b666531e527f9f5f72 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackConstants.lean @@ -0,0 +1,110 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackProcedures +import OAI.Computability.QuantumFactoring.BitStackQuotation + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram +variable {K : Type} [DecidableEq K] +/-- A fixed finite list is part of the program, not a run-time oracle. -/ +def pushWord (k : K) : List Bool→Program K + | []=>.skip + | b::bs=>.seq (pushWord k bs) (.push k b) +lemma pushWord_runs (k : K) (xs : List Bool) (s : Store K) : + Runs (pushWord k xs) s (Function.update s k (xs++s k)) (xs.length+1) := by + induction xs with + | nil=>simpa [pushWord] using Runs.skip s + | cons b bs ih=> + have hh:=Runs.seq ih (Runs.push (Function.update s k (bs++s k)) k b) + simpa only [pushWord,Function.update_self,Function.update_idem,List.cons_append, + List.length_cons,Nat.add_comm] using hh +namespace Procedure +variable {α β : Type} (ea : α→List Bool) (eb : β→List Bool) +noncomputable def constant (b : β) : Procedure ea eb (fun _=>b) where + K:=Fin 1 + finiteK:=inferInstance + decideK:=inferInstance + input:=0 + output:=0 + program:=.seq (clear 0) (pushWord 0 (eb b)) + bound:=Polynomial.C 2*Polynomial.X+Polynomial.C ((eb b).length+2) + runs a:=by + let s : Store (Fin 1):=singletonStore 0 (ea a) + let u : Store (Fin 1):=Function.update s 0 [] + have hc:=clear_runs (0 : Fin 1) s + have hp:=pushWord_runs (0 : Fin 1) (eb b) u + have hh:=Runs.seq hc hp + refine ⟨((eb b).length+1)+(2*(ea a).length+1),by simp;omega,?_⟩ + convert hh using 1 + · funext k;fin_cases k;simp [u,s,singletonStore] + · simp [s,singletonStore] + +noncomputable def quote (ea : α→List Bool) : Procedure ea (fun a=>quoteBits (ea a)) id where + K:=Fin 3 + finiteK:=inferInstance + decideK:=inferInstance + input:=0 + output:=1 + program:=quoteMove 0 1 2 + bound:=Polynomial.C 7*Polynomial.X+Polynomial.C 5 + runs a:=by + have hh:=quoteMove_runs (0 : Fin 3) 1 2 (by decide) (by decide) (by decide) + (singletonStore 0 (ea a)) (by simp [singletonStore]) + refine ⟨7*(ea a).length+5,by simp,?_⟩ + convert hh using 1 + · funext k; fin_cases k <;> simp [singletonStore,Function.update] + · simp [singletonStore] + +/-- Count each actual symbol, returning a unary length. -/ +noncomputable def length : Procedure (id : List Bool→List Bool) + (fun n=>List.replicate n true) List.length where + K:=Fin 2 + finiteK:=inferInstance + decideK:=inferInstance + input:=0 + output:=1 + program:=.loop 0 (.push 1 true) (.push 1 true) + bound:=Polynomial.C 2*Polynomial.X+1 + runs xs:=by + have h : ∀ xs (s : Store (Fin 2)),s 0=xs→ + Runs (.loop 0 (.push 1 true) (.push 1 true)) s + (Function.update (Function.update s 0 []) 1 (List.replicate xs.length true++s 1)) + (2*xs.length+1) := by + intro ys; induction ys with + | nil=> + intro s hs + have he : Function.update (Function.update s 0 []) 1 + (List.replicate ([] : List Bool).length true++s 1)=s := by + simp only [List.length_nil,List.replicate_zero,List.nil_append] + rw [←hs,Function.update_eq_self,Function.update_eq_self] + rw [he];exact Runs.loop_nil hs + | cons y ys ih=> + intro s hs + let u:=Function.update s 0 ys + let v:=Function.update u 1 (true::u 1) + have hv : v 0=ys:=by simp [v,u] + have htail:=ih v hv + have hh : Runs (.loop 0 (.push 1 true) (.push 1 true)) s + (Function.update (Function.update v 0 []) 1 (List.replicate ys.length true++v 1)) + (2*ys.length+1+1+1) := by + cases y + · exact Runs.loop_false (a:=1) (b:=2*ys.length+1) hs (Runs.push u 1 true) htail + · exact Runs.loop_true (a:=1) (b:=2*ys.length+1) hs (Runs.push u 1 true) htail + convert hh using 1 + · funext k;fin_cases k <;> simp [u,v,Function.update,List.replicate_succ] + rw [←List.cons_append,←List.replicate_succ,List.replicate_succ',List.append_assoc] + rfl + refine ⟨2*xs.length+1,by simp,?_⟩ + convert h xs (singletonStore 0 xs) (by simp [singletonStore]) using 1 <;> + (funext k;fin_cases k <;> simp [singletonStore,Function.update]) +end Procedure +end ExactQuantumFactoring.BitStackProgram + +end + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackDependentChoice.lean b/lean/OAI/Computability/QuantumFactoring/BitStackDependentChoice.lean new file mode 100644 index 0000000000000000000000000000000000000000..538028bc7a9ed5f4dea60bdf7718688b145fc5a2 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackDependentChoice.lean @@ -0,0 +1,89 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.EmissionCombinators + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram.Procedure +variable {α β : Type} {ea : α→List Bool} {eb : β→List Bool} {f : α→β} +noncomputable def chooseBitD (c : α→Prop) [DecidablePred c] + (p : Procedure (fun x:{a // ¬c a}=>ea x.val) eb (fun x=>f x.val)) + (q : Procedure (fun x:{a // c a}=>ea x.val) eb (fun x=>f x.val)) : + Procedure (fun a=>decide (c a)::ea a) eb f where + K:=(p.K ⊕ q.K) ⊕ Fin 2 + finiteK:=inferInstance + decideK:=inferInstance + input:=Sum.inr 0 + output:=Sum.inr 0 + program:=.cases (Sum.inr 0) .skip + (p.shared.program.relabel (leftPublic p.K q.K)) + (q.shared.program.relabel (rightPublic p.K q.K)) + bound:=p.shared.bound+q.shared.bound+1 + runs a:=by + have hpmono:=eval_nat_mono p.shared.bound (Nat.le_succ (ea a).length) + have hqmono:=eval_nat_mono q.shared.bound (Nat.le_succ (ea a).length) + by_cases h:c a + · obtain ⟨t,ht,hd⟩:=q.shared.runs ⟨a,h⟩ + have hh:=hd.relabel (rightPublic p.K q.K) (fun _=>[]) + simp only [overlay_singleton] at hh + have he : rightPublic p.K q.K q.shared.input=Sum.inr 0:=rfl + rw [he] at hh + refine ⟨t+1,?_,?_⟩ + · simpa only [List.length_cons,Polynomial.eval_add,Polynomial.eval_one] using + Nat.add_le_add_right ((ht.trans hqmono).trans (Nat.le_add_left + (q.shared.bound.eval ((ea a).length+1)) (p.shared.bound.eval ((ea a).length+1)))) 1 + · simp only [h,decide_true] + have hu : Function.update (singletonStore (Sum.inr 0 : (p.K⊕q.K)⊕Fin 2) + (true::ea a)) (Sum.inr 0) (ea a)=singletonStore (Sum.inr 0) (ea a):=by + simp [singletonStore] + simpa only [hu] using Runs.cases_true (p:=Program.skip) + (q:=p.shared.program.relabel (leftPublic p.K q.K)) + (xs:=ea a) (s:=singletonStore (Sum.inr 0) (true::ea a)) (by simp [singletonStore]) + (by rw [hu];exact hh) + · obtain ⟨t,ht,hd⟩:=p.shared.runs ⟨a,h⟩ + have hh:=hd.relabel (leftPublic p.K q.K) (fun _=>[]) + simp only [overlay_singleton] at hh + have he : leftPublic p.K q.K p.shared.input=Sum.inr 0:=rfl + rw [he] at hh + refine ⟨t+1,?_,?_⟩ + · simpa only [List.length_cons,Polynomial.eval_add,Polynomial.eval_one] using + Nat.add_le_add_right ((ht.trans hpmono).trans (Nat.le_add_right + (p.shared.bound.eval ((ea a).length+1)) (q.shared.bound.eval ((ea a).length+1)))) 1 + · simp only [h,decide_false] + have hu : Function.update (singletonStore (Sum.inr 0 : (p.K⊕q.K)⊕Fin 2) + (false::ea a)) (Sum.inr 0) (ea a)=singletonStore (Sum.inr 0) (ea a):=by + simp [singletonStore] + simpa only [hu] using Runs.cases_false (p:=Program.skip) + (r:=q.shared.program.relabel (rightPublic p.K q.K)) + (xs:=ea a) (s:=singletonStore (Sum.inr 0) (false::ea a)) (by simp [singletonStore]) + (by rw [hu];exact hh) +noncomputable def splitOn (c : α→Prop) [DecidablePred c] + (test : Procedure ea boolCode (fun a=>decide (c a))) + (yes : Procedure (fun x:{a // c a}=>ea x.val) eb (fun x=>f x.val)) + (no : Procedure (fun x:{a // ¬c a}=>ea x.val) eb (fun x=>f x.val)) : Procedure ea eb f:=by + let p:=no.comp (unprefix (fun x:{a // ¬c a}=>ea x.val) false) + let q:=yes.comp (unprefix (fun x:{a // c a}=>ea x.val) false) + let choice:=(chooseBitD c p q).comp (unprefix (fun a=>decide (c a)::false::ea a) true) + let input:= (test.pair (identity ea)).result (ec:=fun a=>true::decide (c a)::false::ea a) + (h:=id) (by intro a;rfl) + exact choice.comp input +end ExactQuantumFactoring.BitStackProgram.Procedure + +namespace ExactQuantumFactoring.BitStackProgram.Emits +variable {α β : Type} {ea : α→List Bool} {eb : β→List Bool} {f : α→β} +lemma splitOn (c : α→Prop) [DecidablePred c] + (test : Emits ea Procedure.boolCode (fun a=>decide (c a))) + (yes : Emits (fun x:{a // c a}=>ea x.val) eb (fun x=>f x.val)) + (no : Emits (fun x:{a // ¬c a}=>ea x.val) eb (fun x=>f x.val)) : Emits ea eb f:=by + obtain ⟨p⟩:=test;obtain ⟨q⟩:=yes;obtain ⟨r⟩:=no + exact ⟨Procedure.splitOn c p q r⟩ +end ExactQuantumFactoring.BitStackProgram.Emits + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackDivision.lean b/lean/OAI/Computability/QuantumFactoring/BitStackDivision.lean new file mode 100644 index 0000000000000000000000000000000000000000..52656bd85e02f0c222c08856bc66ee6373759194 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackDivision.lean @@ -0,0 +1,152 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackMultiplier +import OAI.Computability.QuantumFactoring.Procedure + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram +namespace Procedure +variable {α β : Type} {ea : α→List Bool} {eb : β→List Bool} + {c : α→Bool} {f g : α→β} +noncomputable def conditional (test : Procedure ea boolCode c) + (yes : Procedure ea eb f) (no : Procedure ea eb g) : + Procedure ea eb (fun x=>if c x then f x else g x) := + (choose no yes).comp (test.pair (identity ea)) + +noncomputable def binaryZero : Procedure Nat.bits boolCode (fun n=>decide (n=0)) := + (isEmpty.precompose Nat.bits).congrFun (by + intro n + by_cases hn : n=0 + · subst n;rfl + · have hh : n.bits≠[]:=by + intro h + have hy:=binaryValue_bits n + rw [h] at hy + exact hn hy.symm + simp [hh,hn]) +end Procedure + +abbrev DivState := ℕ×ℕ×ℕ +abbrev divStateCode := prodCode Nat.bits (prodCode Nat.bits Nat.bits) + +def divStep (b : Bool) (x : DivState) : DivState := + let t:=2*x.2.2+b.toNat + if x.1≤t then (x.1,2*x.2.1+1,t-x.1) else (x.1,2*x.2.1,t) + +lemma divStep_fst (b : Bool) (x : DivState) : (divStep b x).1=x.1 := by + dsimp only [divStep];split <;> rfl + +lemma divStep_size (b : Bool) (x : DivState) : + (divStateCode (divStep b x)).length≤(divStateCode x).length+3 := by + have hq : (2*x.2.1+1).bits.length≤x.2.1.bits.length+1:=doubleOne_bits_length _ + have hq0:=double_bits_length x.2.1 + have hr : (2*x.2.2+b.toNat).bits.length≤x.2.2.bits.length+1:=by + cases b + · simpa using double_bits_length x.2.2 + · exact doubleOne_bits_length x.2.2 + have hs : (2*x.2.2+b.toNat-x.1).bits.length≤(2*x.2.2+b.toNat).bits.length:= + bits_length_mono (Nat.sub_le _ _) + simp only [divStateCode,divStep,prodCode,pairBits_length] + split <;> dsimp only <;> omega + +lemma divStep_spec (b : Bool) (x : DivState) (hr : x.2.2 decide + dsimp only [divStep] + split + · rename_i h + have ht:=Nat.sub_add_cancel h + dsimp only + constructor <;> nlinarith + · rename_i h + dsimp only + constructor <;> nlinarith + +lemma div_fold_spec (xs : List Bool) (x : DivState) (hr : x.2.2simp [binaryValue,hr] + | cons b bs ih=> + have he : bitAction (divStep false) (divStep true) x b=divStep b x:=by cases b <;> rfl + rw [List.foldl_cons,he] + have H:=divStep_spec b x hr + have hi:=ih (divStep b x) (by rw [divStep_fst];exact H.1) + simp only [divStep_fst] at hi + refine ⟨hi.1,hi.2.1,?_⟩ + rw [hi.2.2,H.2] + simp only [List.reverse_cons,binaryValue_append,List.length_reverse,List.length_cons, + binaryValue,pow_succ] + ring + +def divideRaw (x : List Bool×ℕ) : ℕ×ℕ := + (x.1.reverse.foldl (bitAction (divStep false) (divStep true)) (x.2,0,0)).2 + +lemma divideRaw_spec (x : List Bool×ℕ) (hp : 0 dsimp [divideRaw] <;> nlinarith [hh.2.1,hh.2.2] + have hm:=Nat.mod_add_div (binaryValue x.1) x.2 + rw [hq] at hm + apply Prod.ext + · exact hq.symm + · dsimp [divideRaw] at hm ⊢;nlinarith [hh.2.2] + +namespace Procedure +noncomputable def divStepP (b : Bool) : Procedure divStateCode divStateCode (divStep b) := by + let d:=first Nat.bits (prodCode Nat.bits Nat.bits) + let qr:=second Nat.bits (prodCode Nat.bits Nat.bits) + let q:=(first Nat.bits Nat.bits).comp qr + let r:=(second Nat.bits Nat.bits).comp qr + let db : Procedure Nat.bits Nat.bits (fun n=>2*n+b.toNat):=by + cases b + · exact double.congrFun (by intro n;simp) + · exact doubleOne + let t:=db.comp r + let test:=binaryLe.comp (d.pair t) + let yes:=d.pair ((doubleOne.comp q).pair (binarySub.comp (t.pair d))) + let no:=d.pair ((double.comp q).pair t) + exact (conditional test yes no).congrFun (by intro x;simp only [Function.comp_apply,divStep,decide_eq_true_eq]) + +noncomputable def divideRawP : Procedure (prodCode (id : List Bool→List Bool) Nat.bits) + (prodCode Nat.bits Nat.bits) divideRaw := by + let x:=first (id : List Bool→List Bool) Nat.bits + let d:=second (id : List Bool→List Bool) Nat.bits + let zero:=constant (prodCode (id : List Bool→List Bool) Nat.bits) Nat.bits 0 + let start:=(reverse.comp x).pair (d.pair (zero.pair zero)) + let fold:=foldBitsLinear (divStepP false) (divStepP true) 3 (divStep_size false) (divStep_size true) + exact ((second Nat.bits (prodCode Nat.bits Nat.bits)).comp (fold.comp start)).congrFun (by intro x;rfl) + +noncomputable def binaryDivMod : Procedure (prodCode Nat.bits Nat.bits) + (prodCode Nat.bits Nat.bits) (fun x=>(x.1/x.2,x.1%x.2)) := by + let raw:=(divideRawP.precompose (fun x : ℕ×ℕ=>(x.1.bits,x.2))) + let test:=binaryZero.comp (second Nat.bits Nat.bits) + let zerocase:=(constant (prodCode Nat.bits Nat.bits) Nat.bits 0).pair (first Nat.bits Nat.bits) + exact (conditional test zerocase raw).congrFun (by + intro x + change (if decide (x.2=0) then (0,x.1) else divideRaw (x.1.bits,x.2))=(x.1/x.2,x.1%x.2) + by_cases hz : x.2=0 + · simp [hz] + · simp only [hz,decide_false,Bool.false_eq_true,ite_false] + simpa only [binaryValue_bits] using divideRaw_spec (x.1.bits,x.2) (by omega)) + +noncomputable def binaryDiv : Procedure (prodCode Nat.bits Nat.bits) Nat.bits + (fun x=>x.1/x.2) := (first Nat.bits Nat.bits).comp binaryDivMod +noncomputable def binaryMod : Procedure (prodCode Nat.bits Nat.bits) Nat.bits + (fun x=>x.1%x.2) := (second Nat.bits Nat.bits).comp binaryDivMod +end Procedure +end ExactQuantumFactoring.BitStackProgram + +end + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackFold.lean b/lean/OAI/Computability/QuantumFactoring/BitStackFold.lean new file mode 100644 index 0000000000000000000000000000000000000000..f1de3cc52301f84eaae1889e8bf9f45efafc8792 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackFold.lean @@ -0,0 +1,96 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackBasicProcedures +import OAI.Computability.QuantumFactoring.BitStackBooleans +import OAI.Computability.QuantumFactoring.BitStackIteration + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram +variable {α : Type} +def scanStep (f g : α→α) : List Bool×α→List Bool×α + | ([],a)=>([],a) + | (b::bs,a)=>(bs,if b then g a else f a) + +def bitAction (f g : α→α) (a : α) (b : Bool) : α := if b then g a else f a + +lemma scanStep_iterate (f g : α→α) (i : ℕ) (xs : List Bool) (a : α) : + (scanStep f g)^[i] (xs,a)=(xs.drop i,(xs.take i).foldl (bitAction f g) a) := by + induction i generalizing xs a with + | zero=>simp + | succ i ih=> + rw [Function.iterate_succ_apply] + cases xs with + | nil=>simpa [scanStep] using ih [] a + | cons b bs=>simpa [scanStep,bitAction] using ih bs (if b then g a else f a) + +lemma foldl_measure {m : α→ℕ} {f g : α→α} {c : ℕ} + (hf : ∀a,m (f a)≤ m a+c) (hg : ∀a,m (g a)≤ m a+c) (xs : List Bool) (a : α) : + m (xs.foldl (bitAction f g) a)≤ m a+xs.length*c := by + induction xs generalizing a with + | nil=>simp + | cons b bs ih=> + simp only [List.foldl_cons,List.length_cons] + have hh : m (bitAction f g a b)≤ m a+c:=by cases b <;> simp [bitAction,hf,hg] + have hi:=ih (bitAction f g a b) + nlinarith + +namespace Procedure +variable {ea : α→List Bool} {f g : α→α} +noncomputable def scan (p : Procedure ea ea f) (q : Procedure ea ea g) : + Procedure (prodCode id ea) (prodCode id ea) (scanStep f g) := by + let fst:=first (id : List Bool→List Bool) ea + let snd:=second (id : List Bool→List Bool) ea + let upd:=(choose p q).comp ((head.comp fst).pair snd) + let body:=(tail.comp fst).pair upd + let pp:=(choose body (identity (prodCode id ea))).comp + ((isEmpty.comp fst).pair (identity (prodCode id ea))) + exact pp.congrFun (by + rintro ⟨xs,a⟩ + cases xs <;> rfl) + +/-- Fold a variable Boolean word. The bound covers every actual intermediate +state; all pairing, data movement and loop iterations are charged. -/ +noncomputable def foldBits (p : Procedure ea ea f) (q : Procedure ea ea g) + (bound : Polynomial ℕ) + (hsize : ∀ (xs : List Bool) a i,(ea ((xs.take i).foldl (bitAction f g) a)).length≤ + bound.eval (xs.length+(ea a).length)) : + Procedure (prodCode id ea) ea (fun x=>x.1.foldl (bitAction f g) x.2) := by + let s:=scan p q + let rep:=s.iterate (Polynomial.C 2*Polynomial.X+1+bound) (by + intro n x i _ + rw [scanStep_iterate] + simp only [prodCode,pairBits_length,id_eq,List.length_drop] + have hs:=hsize x.1 x.2 i + have hm:=eval_nat_mono bound (by omega : + x.1.length+(ea x.2).length≤n+(2*x.1.length+(ea x.2).length+1)) + dsimp only at hm + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_C, + Polynomial.eval_X,Polynomial.eval_one] + omega) + let start:=(length.comp (first (id : List Bool→List Bool) ea)).pair (identity (prodCode id ea)) + exact ((second (id : List Bool→List Bool) ea).comp (rep.comp start)).congrFun (by + rintro ⟨xs,a⟩ + change ((scanStep f g)^[xs.length] (xs,a)).2=xs.foldl (bitAction f g) a + rw [scanStep_iterate,List.take_length]) + +noncomputable def foldBitsLinear (p : Procedure ea ea f) (q : Procedure ea ea g) (c : ℕ) + (hf : ∀a,(ea (f a)).length≤(ea a).length+c) + (hg : ∀a,(ea (g a)).length≤(ea a).length+c) : + Procedure (prodCode id ea) ea (fun x=>x.1.foldl (bitAction f g) x.2) := + foldBits p q (Polynomial.C (c+1)*Polynomial.X) (by + intro xs a i + have hh:=foldl_measure (m:=fun a=>(ea a).length) (f:=f) (g:=g) (c:=c) hf hg (xs.take i) a + have hl : (xs.take i).length≤xs.length:=by simp only [List.length_take];omega + simp only [Polynomial.eval_mul,Polynomial.eval_C,Polynomial.eval_X] + nlinarith) +end Procedure +end ExactQuantumFactoring.BitStackProgram + +end + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackFrames.lean b/lean/OAI/Computability/QuantumFactoring/BitStackFrames.lean new file mode 100644 index 0000000000000000000000000000000000000000..4ba03a1e4739a1302195630d17b038a085f11e19 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackFrames.lean @@ -0,0 +1,76 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackRelabel +import OAI.Computability.QuantumFactoring.BitStackProcedures + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram +variable {K L : Type} +def sumStore (s : Store K) (t : Store L) : Store (K ⊕ L) := Sum.elim s t +@[simp] lemma sumStore_left (s : Store K) (t : Store L) (k : K) : + sumStore s t (Sum.inl k)=s k := rfl +@[simp] lemma sumStore_right (s : Store K) (t : Store L) (l : L) : + sumStore s t (Sum.inr l)=t l := rfl +lemma sumStore_empty : sumStore (fun _ : K=>[]) (fun _ : L=>[])=fun _=>[] := by + funext j; cases j <;> rfl + +def leftEmbed (K L : Type) : K ↪ K ⊕ L := ⟨Sum.inl,Sum.inl_injective⟩ +lemma overlay_left (s : Store K) (t : Store L) : + overlay (leftEmbed K L) (sumStore (fun _=>[]) t) s=sumStore s t := by + funext j + cases j with + | inl j => exact overlay_at _ _ _ j + | inr j => exact overlay_outside _ _ _ _ (by intro i; simp [leftEmbed]) + +variable [DecidableEq K] [DecidableEq L] +@[simp] lemma sumStore_update_left (s : Store K) (t : Store L) (k : K) (xs : List Bool) : + Function.update (sumStore s t) (Sum.inl k) xs=sumStore (Function.update s k xs) t := by + funext j; cases j <;> simp [Function.update,sumStore] +@[simp] lemma sumStore_update_right (s : Store K) (t : Store L) (k : L) (xs : List Bool) : + Function.update (sumStore s t) (Sum.inr k) xs=sumStore s (Function.update t k xs) := by + funext j; cases j <;> simp [Function.update,sumStore] +lemma sumStore_singleton_left (k : K) (xs : List Bool) : + singletonStore (Sum.inl k) xs=sumStore (singletonStore k xs) (fun _ : L=>[]) := by + rw [singletonStore,←sumStore_empty,sumStore_update_left]; rfl +lemma sumStore_singleton_right (k : L) (xs : List Bool) : + singletonStore (Sum.inr k) xs=sumStore (fun _ : K=>[]) (singletonStore k xs) := by + rw [singletonStore,←sumStore_empty,sumStore_update_right]; rfl +lemma Runs.left {p : Program K} {s u : Store K} {c : ℕ} (h : Runs p s u c) (t : Store L) : + Runs (p.relabel Sum.inl) (sumStore s t) (sumStore u t) c := by + have hh := h.relabel (leftEmbed K L) (sumStore (fun _=>[]) t) + rw [overlay_left,overlay_left] at hh + exact hh + +namespace Procedure +variable {α β : Type} {ea : α→List Bool} {eb : β→List Bool} {f g : α→β} +def congrFun (p : Procedure ea eb f) (h : ∀ a,f a=g a) : Procedure ea eb g where + K:=p.K + finiteK:=p.finiteK + decideK:=p.decideK + input:=p.input + output:=p.output + program:=p.program + bound:=p.bound + runs a:=by simpa only [h a] using p.runs a + +noncomputable def identity (ea : α→List Bool) : Procedure ea ea id where + K:=Unit + finiteK:=inferInstance + decideK:=inferInstance + input:=() + output:=() + program:=.skip + bound:=1 + runs a:=⟨1,by simp,Runs.skip _⟩ +end Procedure +end ExactQuantumFactoring.BitStackProgram + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackGCD.lean b/lean/OAI/Computability/QuantumFactoring/BitStackGCD.lean new file mode 100644 index 0000000000000000000000000000000000000000..7b840a613d9630157b96d230ac64ef4160eb86c0 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackGCD.lean @@ -0,0 +1,91 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackMultiplier + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram + +def gcdStep (x : ℕ×ℕ) : ℕ×ℕ := if x.2=0 then x else (x.2,x.1%x.2) +def gcdRound (x : ℕ×ℕ) : ℕ×ℕ := gcdStep (gcdStep x) + +lemma gcdStep_value (x : ℕ×ℕ) : (gcdStep x).1.gcd (gcdStep x).2=x.1.gcd x.2 := by + unfold gcdStep + split + · rfl + · dsimp only + rw [Nat.gcd_comm x.2] + exact (Nat.gcd_rec x.2 x.1).symm.trans (Nat.gcd_comm x.2 x.1) + +lemma mod_half {b r : ℕ} (hr : 0simp + | succ i ih=> + rw [Function.iterate_succ_apply'] + calc + (gcdRound (gcdRound^[i] x)).2≤(gcdRound^[i] x).2/2:=gcdRound_half _ + _≤(x.2/2^i)/2:=Nat.div_le_div_right ih + _=x.2/2^(i+1):=by rw [Nat.div_div_eq_div_mul,pow_succ] + +lemma gcdRound_iterate_value (i : ℕ) (x : ℕ×ℕ) : + (gcdRound^[i] x).1.gcd (gcdRound^[i] x).2=x.1.gcd x.2 := by + induction i with + | zero=>rfl + | succ i ih=>rw [Function.iterate_succ_apply',gcdRound_value,ih] + +lemma gcdRound_result (x : ℕ×ℕ) : (gcdRound^[x.2.bits.length] x).1=x.1.gcd x.2 := by + have hz : (gcdRound^[x.2.bits.length] x).2=0:=by + have hh:=gcdRound_iterate_bound x.2.bits.length x + have hzdiv : x.2/2^x.2.bits.length=0:=by + rw [Nat.size_eq_bits_len];exact Nat.div_eq_of_lt (Nat.lt_size_self x.2) + rw [hzdiv] at hh + omega + simpa only [hz,Nat.gcd_zero_right] using gcdRound_iterate_value x.2.bits.length x + +lemma gcdStep_sizeSum (x : ℕ×ℕ) : + (gcdStep x).1.bits.length+(gcdStep x).2.bits.length≤x.1.bits.length+x.2.bits.length := by + have hm:=bits_length_mono (Nat.mod_le x.1 x.2) + unfold gcdStep + split + · exact le_rfl + · change x.2.bits.length+(x.1%x.2).bits.length≤x.1.bits.length+x.2.bits.length + omega + +lemma gcdRound_iterate_sizeSum (i : ℕ) (x : ℕ×ℕ) : + (gcdRound^[i] x).1.bits.length+(gcdRound^[i] x).2.bits.length≤ + x.1.bits.length+x.2.bits.length := by + induction i with + | zero=>rfl + | succ i ih=> + rw [Function.iterate_succ_apply'] + exact ((gcdStep_sizeSum _).trans (gcdStep_sizeSum _)).trans ih + + +end ExactQuantumFactoring.BitStackProgram +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackIncrement.lean b/lean/OAI/Computability/QuantumFactoring/BitStackIncrement.lean new file mode 100644 index 0000000000000000000000000000000000000000..745cac80cd8824713fe7970f20acfeb855cdaea0 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackIncrement.lean @@ -0,0 +1,141 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackLists + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram + +/-- Little-endian evaluation; leading zeroes at the high end are allowed. -/ +def binaryValue : List Bool → ℕ + | [] => 0 + | b::xs => b.toNat+2*binaryValue xs + +def incrementWord : List Bool → List Bool + | [] => [true] + | false::xs => true::xs + | true::xs => false::incrementWord xs + +def carryTail : List Bool → List Bool + | [] => [true] + | false::xs => true::xs + | true::xs => carryTail xs + +def carryCount : List Bool → ℕ + | [] => 0 + | false::_ => 0 + | true::xs => carryCount xs+1 + +lemma incrementWord_value (xs : List Bool) : binaryValue (incrementWord xs)=binaryValue xs+1 := by + induction xs with + | nil => rfl + | cons x xs ih => cases x <;> simp [incrementWord,binaryValue,ih] <;> omega +lemma carryCount_le_length (xs : List Bool) : carryCount xs≤xs.length := by + induction xs with + | nil => rfl + | cons x xs ih => cases x <;> simp [carryCount,List.length_cons]; omega +lemma incrementWord_eq (xs : List Bool) : + incrementWord xs=List.replicate (carryCount xs) false++carryTail xs := by + induction xs with + | nil => rfl + | cons x xs ih => cases x <;> simp [incrementWord,carryCount,carryTail,ih,List.replicate_succ] +lemma incrementWord_length (xs : List Bool) : (incrementWord xs).length≤xs.length+1 := by + induction xs with + | nil => rfl + | cons x xs ih => cases x <;> simp [incrementWord,List.length_cons]; omega + +variable {K : Type} [DecidableEq K] +def rippleBody (a t c : K) : Program K := + .cases a (.push a true) (.push a true) (.seq (.push t false) (.push c true)) +def ripple (a t c : K) : Program K := .loop c (rippleBody a t c) (rippleBody a t c) +def increment (a t c : K) : Program K := + .seq (.push c true) (.seq (ripple a t c) (reverseMove t a)) + +lemma ripple_runs (a t c : K) (hat : a≠t) (hac : a≠c) (htc : t≠c) + (s : Store K) (hc : s c=[true]) : + Runs (ripple a t c) s + (Function.update (Function.update (Function.update s c []) a (carryTail (s a))) + t (List.replicate (carryCount (s a)) false++s t)) + (4*(carryCount (s a)+1)) := by + generalize hs : s a=xs at * + induction xs generalizing s with + | nil => + let u := Function.update s c [] + let v := Function.update u a [true] + have hua : u a=[] := by simp [u,hac,hs] + have hvc : v c=[] := by simp [v,u,hac.symm] + have body : Runs (rippleBody a t c) u v 2 := + Runs.cases_nil hua (by simpa only [hua] using Runs.push u a true) + have hh := Runs.loop_true (p:=rippleBody a t c) (a:=2) (b:=1) hc body (Runs.loop_nil hvc) + change Runs (.loop _ _ _) _ _ _ + convert hh using 1 + · simp only [carryCount,carryTail,List.replicate_zero,List.nil_append] + change Function.update v t (s t)=v + rw [← show v t=s t by simp [v,u,hat.symm,htc],Function.update_eq_self] + · rfl + | cons x xs ih => + cases x + · let u := Function.update s c [] + let w := Function.update u a xs + let v := Function.update w a (true::xs) + have hua : u a=false::xs := by simp [u,hac,hs] + have hvc : v c=[] := by simp [v,w,u,hac.symm] + have body : Runs (rippleBody a t c) u v 2 := + Runs.cases_false hua (by simpa only [w,Function.update_self] using Runs.push w a true) + have hh := Runs.loop_true (p:=rippleBody a t c) (a:=2) (b:=1) hc body (Runs.loop_nil hvc) + change Runs (.loop _ _ _) _ _ _ + convert hh using 1 + · funext k + by_cases ha : k=a <;> by_cases ht : k=t <;> by_cases hcc : k=c <;> + simp_all [v,w,u,Function.update,carryCount,carryTail] + · rfl + · let u := Function.update s c [] + let w := Function.update u a xs + let z := Function.update w t (false::w t) + let v := Function.update z c (true::z c) + have hua : u a=true::xs := by simp [u,hac,hs] + have hva : v a=xs := by simp [v,z,w,hac,hat] + have hvc : v c=[true] := by simp [v,z,w,u,htc.symm,hac.symm] + have body : Runs (rippleBody a t c) u v 3 := + Runs.cases_true (a:=2) hua (Runs.seq (Runs.push w t false) (Runs.push z c true)) + have hh := Runs.loop_true (p:=rippleBody a t c) (a:=3) (b:=4*(carryCount xs+1)) hc body (ih v hvc hva) + change Runs (.loop _ _ _) _ _ _ + convert hh using 1 + · funext k + by_cases ha : k=a <;> by_cases ht : k=t <;> by_cases hcc : k=c <;> + simp_all [v,z,w,u,Function.update,carryCount,carryTail,List.replicate_succ] + rw [← List.cons_append, ← List.replicate_succ, List.replicate_succ',List.append_assoc] + rfl + · simp only [carryCount]; omega + +lemma increment_runs (a t c : K) (hat : a≠t) (hac : a≠c) (htc : t≠c) + (s : Store K) (ht : s t=[]) (hc : s c=[]) : + Runs (increment a t c) s (Function.update s a (incrementWord (s a))) + (6*carryCount (s a)+6) := by + let u := Function.update s c [true] + have hua : u a=s a := by simp [u,hac] + have hut : u t=[] := by simp [u,ht,htc] + have huc : u c=[true] := by simp [u] + let v := Function.update (Function.update (Function.update u c []) a (carryTail (u a))) + t (List.replicate (carryCount (u a)) false++u t) + have hp : Runs (.push c true) s u 1 := by simpa only [hc] using Runs.push s c true + have hh := Runs.seq hp + (Runs.seq (ripple_runs a t c hat hac htc u huc) (reverseMove_runs t a hat.symm v)) + change Runs (.seq _ _) _ _ _ + convert hh using 1 + · funext k + by_cases ha : k=a <;> by_cases htk : k=t <;> by_cases hck : k=c <;> + simp_all [v,u,Function.update,incrementWord_eq] + · simp only [v,Function.update_self,hut,List.append_nil,List.length_replicate,hua] + omega + +end ExactQuantumFactoring.BitStackProgram + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackIntegers.lean b/lean/OAI/Computability/QuantumFactoring/BitStackIntegers.lean new file mode 100644 index 0000000000000000000000000000000000000000..e188129ef7df7b9420bd4e22c8c1fe1a9900eccc --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackIntegers.lean @@ -0,0 +1,117 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackDivision + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram + +def intData (z : ℤ) : Bool×ℕ := (decide (z<0),z.natAbs) +def intCode (z : ℤ) : List Bool := prodCode Procedure.boolCode Nat.bits (intData z) +def intOfSign (x : Bool×ℕ) : ℤ := if x.1 then -(x.2 : ℤ) else (x.2 : ℤ) + +lemma intOfSign_data (z : ℤ) : intOfSign (intData z)=z := by + by_cases h : z<0 + · simp only [intData,intOfSign,h,decide_true,ite_true] + exact (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simp only [intData,intOfSign,h,decide_false,Bool.false_eq_true,ite_false] + exact Int.natAbs_of_nonneg (le_of_not_gt h) + +lemma intData_ofSign (x : Bool×ℕ) : + intData (intOfSign x)=(x.1 && decide (x.2≠0),x.2) := by + rcases x with ⟨s,n⟩ + cases s <;> simp [intData,intOfSign,Nat.pos_iff_ne_zero] + +def signedAdd (x : (Bool×ℕ)×(Bool×ℕ)) : Bool×ℕ := + if x.1.1=x.2.1 then (x.1.1,x.1.2+x.2.2) + else if x.1.2≤x.2.2 then (x.2.1,x.2.2-x.1.2) else (x.1.1,x.1.2-x.2.2) + +lemma signedAdd_value (x : (Bool×ℕ)×(Bool×ℕ)) : + intOfSign (signedAdd x)=intOfSign x.1+intOfSign x.2 := by + rcases x with ⟨⟨s,a⟩,⟨t,b⟩⟩ + cases s <;> cases t <;> simp only [signedAdd,intOfSign,Bool.false_eq_true, + Bool.true_eq_false,ite_true,ite_false,Int.natCast_add] + all_goals first | omega | (split <;> simp only [ite_true,Bool.false_eq_true,ite_false] <;> omega) + +lemma signedMul_value (x : (Bool×ℕ)×(Bool×ℕ)) : + intOfSign (xor x.1.1 x.2.1,x.1.2*x.2.2)=intOfSign x.1*intOfSign x.2 := by + rcases x with ⟨⟨s,a⟩,⟨t,b⟩⟩ + cases s <;> cases t <;> simp [intOfSign] + +lemma intOfSign_not (x : Bool×ℕ) : intOfSign (!x.1,x.2) = -intOfSign x := by + rcases x with ⟨s,n⟩ + cases s <;> simp [intOfSign] + +namespace Procedure +noncomputable def intSign : Procedure intCode boolCode (fun z=>decide (z<0)) := + (first boolCode Nat.bits).precompose intData +noncomputable def intAbs : Procedure intCode Nat.bits Int.natAbs := + (second boolCode Nat.bits).precompose intData + +noncomputable def signedInt : Procedure (prodCode boolCode Nat.bits) intCode intOfSign := by + let s:=first boolCode Nat.bits + let a:=second boolCode Nat.bits + let nz:=boolNot.comp (binaryZero.comp a) + exact ((boolAnd.comp (s.pair nz)).pair a).result (by + intro x + change prodCode boolCode Nat.bits (x.1 && !decide (x.2=0),x.2)=intCode (intOfSign x) + rw [intCode,intData_ofSign] + simp only [decide_not]) + +noncomputable def natToInt : Procedure Nat.bits intCode (fun n=>(n : ℤ)) := + (signedInt.comp ((constant Nat.bits boolCode false).pair (identity Nat.bits))).congrFun (by intro n;rfl) + +noncomputable def intNeg : Procedure intCode intCode Neg.neg := + (signedInt.comp ((boolNot.comp intSign).pair intAbs)).congrFun (by + intro z + change intOfSign (!(intData z).1,(intData z).2) = -z + rw [intOfSign_not,intOfSign_data]) + +noncomputable def signedAddP : Procedure + (prodCode (prodCode boolCode Nat.bits) (prodCode boolCode Nat.bits)) + (prodCode boolCode Nat.bits) signedAdd := by + let a:=first (prodCode boolCode Nat.bits) (prodCode boolCode Nat.bits) + let b:=second (prodCode boolCode Nat.bits) (prodCode boolCode Nat.bits) + let s:=(first boolCode Nat.bits).comp a + let t:=(first boolCode Nat.bits).comp b + let m:=(second boolCode Nat.bits).comp a + let n:=(second boolCode Nat.bits).comp b + let eqs:=boolNot.comp (boolXor.comp (s.pair t)) + let same:=s.pair (binaryAdd.comp (m.pair n)) + let le:=binaryLe.comp (m.pair n) + let small:=t.pair (binarySub.comp (n.pair m)) + let large:=s.pair (binarySub.comp (m.pair n)) + exact (conditional eqs same (conditional le small large)).congrFun (by + rintro ⟨⟨s,m⟩,⟨t,n⟩⟩ + cases s <;> cases t <;> simp [signedAdd,Function.comp_apply]) + +noncomputable def intAdd : Procedure (prodCode intCode intCode) intCode (fun x=>x.1+x.2) := + ((signedInt.comp signedAddP).precompose (fun x : ℤ×ℤ=>(intData x.1,intData x.2))).congrFun + (by intro x;change intOfSign (signedAdd (intData x.1,intData x.2))=x.1+x.2 + rw [signedAdd_value,intOfSign_data,intOfSign_data]) + +noncomputable def intSub : Procedure (prodCode intCode intCode) intCode (fun x=>x.1-x.2) := + (intAdd.comp ((first intCode intCode).pair (intNeg.comp (second intCode intCode)))).congrFun + (by intro x;rfl) + +noncomputable def intMul : Procedure (prodCode intCode intCode) intCode (fun x=>x.1*x.2) := by + let a:=first intCode intCode + let b:=second intCode intCode + let sign:=boolXor.comp ((intSign.comp a).pair (intSign.comp b)) + let mag:=binaryMul.comp ((intAbs.comp a).pair (intAbs.comp b)) + exact (signedInt.comp (sign.pair mag)).congrFun (by + intro x + change intOfSign (xor (intData x.1).1 (intData x.2).1, + (intData x.1).2*(intData x.2).2)=x.1*x.2 + rw [signedMul_value (intData x.1,intData x.2),intOfSign_data,intOfSign_data]) +end Procedure +end ExactQuantumFactoring.BitStackProgram + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackIteration.lean b/lean/OAI/Computability/QuantumFactoring/BitStackIteration.lean new file mode 100644 index 0000000000000000000000000000000000000000..aa614cdc01b56fed33bfe86d866468265c6760dd --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackIteration.lean @@ -0,0 +1,203 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackProducts + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram +namespace Procedure +variable {α : Type} {ea : α→List Bool} {f : α→α} + +/-- Return the result to one fixed public register. Both word movements are +implemented by two reversals; no output-to-input renaming is a TM operation. -/ +noncomputable def inplace (p : Procedure ea ea f) : Procedure ea ea f where + K:=p.K ⊕ Fin 2 + finiteK:=inferInstance + decideK:=inferInstance + input:=Sum.inr 0 + output:=Sum.inr 0 + program:=.seq (moveWord (Sum.inr 0) (Sum.inl p.input) (Sum.inr 1)) + (.seq (p.program.relabel Sum.inl) + (moveWord (Sum.inl p.output) (Sum.inr 0) (Sum.inr 1))) + bound:=Polynomial.C 8*Polynomial.X+Polynomial.C 5*p.bound+Polynomial.C 4 + runs a:=by + obtain ⟨cp,hcp,hp⟩:=p.runs a + have h1:=moveWord_runs (Sum.inr 0 : p.K ⊕ Fin 2) (Sum.inl p.input) (Sum.inr 1) + (by simp) (by simp) (by simp) (ea a) + have h2:=hp.relabel (leftEmbed p.K (Fin 2)) (fun _=>[]) + simp only [overlay_singleton] at h2 + have h3:=moveWord_runs (Sum.inl p.output : p.K ⊕ Fin 2) (Sum.inr 0) (Sum.inr 1) + (by simp) (by simp) (by simp) (ea (f a)) + refine ⟨(4*(ea (f a)).length+2)+cp+(4*(ea a).length+2),?_, + Runs.seq h1 (Runs.seq h2 h3)⟩ + have hl:=p.output_length_le a + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_C,Polynomial.eval_X] + omega + +lemma inplace_register (p : Procedure ea ea f) : p.inplace.output=p.inplace.input := rfl + +/-- Literal repetition of an in-place subroutine by a unary counter. Each +iteration consumes one control token; the bound charges every subroutine step. -/ +lemma iterate_loop_runs {L : Type} [DecidableEq L] (p : Procedure ea ea f) + (he : p.output=p.input) (k : L) (n : ℕ) (a : α) (B : ℕ) + (hm : ∀ i≤n,(ea ((f^[i]) a)).length≤B) (s : Store L) + (hs : s k=List.replicate n true) : + ∃ c,c≤n*(p.bound.eval B+1)+1 ∧ + Runs (.loop (Sum.inr k) (p.program.relabel Sum.inl) (p.program.relabel Sum.inl)) + (sumStore (singletonStore p.input (ea a)) s) + (sumStore (singletonStore p.input (ea ((f^[n]) a))) (Function.update s k [])) c := by + induction n generalizing a s with + | zero => + have hk : Function.update s k []=s := by + simp only [List.replicate_zero] at hs + rw [←hs,Function.update_eq_self] + refine ⟨1,by simp,?_⟩ + rw [Function.iterate_zero_apply,hk] + apply Runs.loop_nil + exact hs + | succ n ih => + let t:=Function.update s k (List.replicate n true) + have ht : t k=List.replicate n true:=by simp [t] + have hm' : ∀ i≤n,(ea ((f^[i]) (f a))).length≤B := by + intro i hi + simpa only [Function.iterate_succ_apply] using hm (i+1) (by omega) + obtain ⟨ct,hct,hrt⟩:=ih (f a) hm' t ht + obtain ⟨cp,hcp,hrp⟩:=p.runs a + rw [he] at hrp + have hcall:=hrp.left t + have hcpB : cp≤p.bound.eval B:= + hcp.trans (eval_nat_mono p.bound (by simpa using hm 0 (by omega))) + have hhead : sumStore (singletonStore p.input (ea a)) s (Sum.inr k)= + true::List.replicate n true := by simpa only [sumStore_right,List.replicate_succ] using hs + have hbody : Runs (p.program.relabel Sum.inl) + (Function.update (sumStore (singletonStore p.input (ea a)) s) + (Sum.inr k) (List.replicate n true)) + (sumStore (singletonStore p.input (ea (f a))) t) cp := by + simpa only [sumStore_update_right] using hcall + have hh:=Runs.loop_true hhead hbody hrt + refine ⟨ct+cp+1,?_,?_⟩ + · nlinarith + · simpa only [t,Function.update_idem,Function.iterate_succ_apply] using hh + +/-- Input-length-bounded iteration. The extra hypothesis is solely a size +invariant along the already implemented iteration, not a computability oracle. -/ +noncomputable def iterate (p : Procedure ea ea f) (q : Polynomial ℕ) + (hgrowth : ∀ n a i,i≤n→(ea ((f^[i]) a)).length≤q.eval (n+(ea a).length)) : + Procedure (prodCode (fun n=>List.replicate n true) ea) ea (fun x=>(f^[x.1]) x.2) where + K:=p.inplace.K ⊕ Fin 4 + finiteK:=inferInstance + decideK:=inferInstance + input:=Sum.inr 0 + output:=Sum.inl p.inplace.input + program:=.seq (unquoteMove (Sum.inr 0) (Sum.inr 1) (Sum.inr 2) (Sum.inr 3)) + (.seq (moveWord (Sum.inr 0) (Sum.inl p.inplace.input) (Sum.inr 2)) + (.loop (Sum.inr 1) (p.inplace.program.relabel Sum.inl) (p.inplace.program.relabel Sum.inl))) + bound:=Polynomial.C 11*Polynomial.X+ + Polynomial.X*(p.inplace.bound.comp q+1)+Polynomial.C 9 + runs x:=by + let r:=p.inplace + let s : Store (r.K ⊕ Fin 4):=singletonStore (Sum.inr 0) + (prodCode (fun n=>List.replicate n true) ea x) + let u : Store (r.K ⊕ Fin 4):=Function.update (singletonStore (Sum.inr 0) (ea x.2)) + (Sum.inr 1) (List.replicate x.1 true) + let v : Store (r.K ⊕ Fin 4):=sumStore (singletonStore r.input (ea x.2)) + (singletonStore 1 (List.replicate x.1 true)) + have hparse : Runs (unquoteMove (Sum.inr 0) (Sum.inr 1) (Sum.inr 2) (Sum.inr 3)) s u + (7*x.1+6) := by + have hh:=unquoteMove_runs (Sum.inr 0 : r.K ⊕ Fin 4) (Sum.inr 1) (Sum.inr 2) (Sum.inr 3) + (by simp) (by simp) (by simp) (by simp) (by simp) (by simp) + (List.replicate x.1 true) (ea x.2) s (by simp [s,singletonStore,prodCode,pairBits]) + (by simp [s,singletonStore]) (by simp [s,singletonStore]) + convert hh using 1 + · funext k; cases k with + | inl k => simp [s,u,singletonStore,Function.update] + | inr k => fin_cases k <;> simp [s,u,singletonStore,Function.update] + · simp + have hmove : Runs (moveWord (Sum.inr 0) (Sum.inl r.input) (Sum.inr 2)) u v + (4*(ea x.2).length+2) := by + let emb : Fin 3 ↪ r.K ⊕ Fin 4 := + ⟨fun k=>if k=0 then Sum.inr 0 else if k=1 then Sum.inl r.input else Sum.inr 2, + by intro a b; fin_cases a <;> fin_cases b <;> simp⟩ + have emb0 : emb 0=Sum.inr 0 := rfl + have emb1 : emb 1=Sum.inl r.input := rfl + have emb2 : emb 2=Sum.inr 2 := rfl + have hh:=(moveWord_runs (0 : Fin 3) 1 2 (by decide) (by decide) (by decide) (ea x.2)).relabel + emb (singletonStore (Sum.inr 1) (List.replicate x.1 true)) + -- A framed move has the counter outside its three touched registers. + have hs' : overlay emb (singletonStore (Sum.inr 1) (List.replicate x.1 true)) + (singletonStore 0 (ea x.2))=u := by + funext k + cases k with + | inl k => + by_cases hk : k=r.input + · subst k + have h:=overlay_at emb (singletonStore (Sum.inr 1) (List.replicate x.1 true)) + (singletonStore 0 (ea x.2)) 1 + simpa [emb0,emb1,emb2,u,singletonStore] using h + · rw [overlay_outside _ _ _ _ (by intro i; fin_cases i <;> simp [emb0,emb1,emb2,Ne.symm hk])] + simp [u,singletonStore] + | inr k => + fin_cases k + · simpa [emb0,emb1,emb2,u,singletonStore] using overlay_at emb + (singletonStore (Sum.inr 1) (List.replicate x.1 true)) (singletonStore 0 (ea x.2)) 0 + · rw [overlay_outside _ _ _ _ (by intro i; fin_cases i <;> simp [emb0,emb1,emb2])] + simp [u,singletonStore] + · simpa [emb0,emb1,emb2,u,singletonStore] using overlay_at emb + (singletonStore (Sum.inr 1) (List.replicate x.1 true)) (singletonStore 0 (ea x.2)) 2 + · rw [overlay_outside _ _ _ _ (by intro i; fin_cases i <;> simp [emb0,emb1,emb2])] + simp [u,singletonStore] + have ht' : overlay emb (singletonStore (Sum.inr 1) (List.replicate x.1 true)) + (singletonStore 1 (ea x.2))=v := by + funext k + cases k with + | inl k => + by_cases hk : k=r.input + · subst k + simpa [emb0,emb1,emb2,v,singletonStore] using overlay_at emb + (singletonStore (Sum.inr 1) (List.replicate x.1 true)) (singletonStore 1 (ea x.2)) 1 + · rw [overlay_outside _ _ _ _ (by intro i; fin_cases i <;> simp [emb0,emb1,emb2,Ne.symm hk])] + simp [v,singletonStore,hk] + | inr k => + fin_cases k + · simpa [emb0,emb1,emb2,v,singletonStore] using overlay_at emb + (singletonStore (Sum.inr 1) (List.replicate x.1 true)) (singletonStore 1 (ea x.2)) 0 + · rw [overlay_outside _ _ _ _ (by intro i; fin_cases i <;> simp [emb0,emb1,emb2])] + simp [v,singletonStore] + · simpa [emb0,emb1,emb2,v,singletonStore] using overlay_at emb + (singletonStore (Sum.inr 1) (List.replicate x.1 true)) (singletonStore 1 (ea x.2)) 2 + · rw [overlay_outside _ _ _ _ (by intro i; fin_cases i <;> simp [emb0,emb1,emb2])] + simp [v,singletonStore] + rw [hs',ht'] at hh + simpa [moveWord,reverseMove,Program.relabel,emb0,emb1,emb2] using hh + obtain ⟨cl,hcl,hl⟩:=iterate_loop_runs r rfl (1 : Fin 4) x.1 x.2 + (q.eval (x.1+(ea x.2).length)) (hgrowth x.1 x.2) + (singletonStore 1 (List.replicate x.1 true)) (by simp [singletonStore]) + have hfinal : sumStore (singletonStore r.input (ea ((f^[x.1]) x.2))) + (Function.update (singletonStore (1 : Fin 4) (List.replicate x.1 true)) 1 [])= + singletonStore (Sum.inl r.input) (ea ((f^[x.1]) x.2)) := by + rw [sumStore_singleton_left] + congr 1 + funext k; fin_cases k <;> simp [singletonStore,Function.update] + rw [hfinal] at hl + refine ⟨cl+(4*(ea x.2).length+2)+(7*x.1+6),?_, + Runs.seq hparse (Runs.seq hmove hl)⟩ + let L:=(prodCode (fun n=>List.replicate n true) ea x).length + have hx : x.1+(ea x.2).length≤L:=by simp only [L,prodCode,pairBits_length,List.length_replicate]; omega + have hm:=eval_nat_mono r.bound (eval_nat_mono q hx) + dsimp only at hm + have hmul:=Nat.mul_le_mul (by omega : x.1≤L) (Nat.add_le_add_right hm 1) + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_C,Polynomial.eval_X, + Polynomial.eval_one,Polynomial.eval_comp] + change cl+(4*(ea x.2).length+2)+(7*x.1+6)≤11*L+L*(r.bound.eval (q.eval L)+1)+9 + omega +end Procedure +end ExactQuantumFactoring.BitStackProgram + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackListCode.lean b/lean/OAI/Computability/QuantumFactoring/BitStackListCode.lean new file mode 100644 index 0000000000000000000000000000000000000000..b397a9207b68e85462ead432ee3df491878557b2 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackListCode.lean @@ -0,0 +1,98 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackBasicProcedures +import OAI.Computability.QuantumFactoring.BitStackSums +import OAI.Computability.QuantumFactoring.BitStackWords + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram +variable {α β : Type} +def listCode (ea : α→List Bool) : List α→List Bool + | []=>[false] + | a::as=>true::pairBits (ea a) (listCode ea as) + +def emptyCode (_ : Unit) : List Bool := [] + +def listView : List α→Unit⊕(α×List α) + | []=>.inl () + | a::as=>.inr (a,as) + +lemma listCode_length_cons (ea : α→List Bool) (a : α) (as : List α) : + (listCode ea (a::as)).length=2*(ea a).length+2+(listCode ea as).length := by + simp [listCode,pairBits_length];omega + +lemma listCode_length_append (ea : α→List Bool) (xs ys : List α) : + (listCode ea (xs++ys)).length+1=(listCode ea xs).length+(listCode ea ys).length := by + induction xs with + | nil=>simp [listCode,Nat.add_comm] + | cons a as ih=>simp only [List.cons_append,listCode_length_cons];omega + +lemma listCode_length_rev (ea : α→List Bool) (xs : List α) : + (listCode ea xs.reverse).length=(listCode ea xs).length := by + induction xs with + | nil=>rfl + | cons a as ih=> + rw [List.reverse_cons] + have hh:=listCode_length_append ea as.reverse [a] + simp only [listCode_length_cons,ih] at hh ⊢ + have hz : (listCode ea []).length=1:=rfl + omega + +lemma listCode_length_pos (ea : α→List Bool) (xs : List α) : 0<(listCode ea xs).length := by + cases xs <;> simp [listCode] + +lemma list_length_le_code (ea : α→List Bool) (xs : List α) : xs.length≤(listCode ea xs).length := by + induction xs with + | nil=>simp + | cons a as ih=>simp only [List.length_cons,listCode_length_cons];omega + +lemma listCode_tail_le (ea : α→List Bool) (xs : List α) : + (listCode ea xs.tail).length≤(listCode ea xs).length := by + cases xs with + | nil=>rfl + | cons a as=>simp only [List.tail_cons,listCode_length_cons];omega + +lemma code_le_of_mem (ea : α→List Bool) {a : α} {xs : List α} (h : a∈xs) : + (ea a).length≤(listCode ea xs).length := by + induction xs with + | nil=>simp at h + | cons b bs ih=> + rw [List.mem_cons] at h + rw [listCode_length_cons] + rcases h with h|h + · subst b;omega + · have hh:=ih h;omega + +namespace Procedure +variable (ea : α→List Bool) +noncomputable def listUncons : Procedure (listCode ea) + (sumCode emptyCode (prodCode ea (listCode ea))) listView := + (identity (listCode ea)).result (by intro xs;cases xs <;> rfl) + +noncomputable def listCons : Procedure (prodCode ea (listCode ea)) (listCode ea) + (fun x=>x.1::x.2) := + (prepend (prodCode ea (listCode ea)) [true]).result (by intro x;rfl) + +noncomputable def listHead (d : α) : Procedure (listCode ea) ea (fun xs=>xs.headD d) := + ((casesSum (constant emptyCode ea d) (first ea (listCode ea))).comp (listUncons ea)).congrFun + (by intro xs;cases xs <;> rfl) + +noncomputable def listTail : Procedure (listCode ea) (listCode ea) List.tail := + ((casesSum (constant emptyCode (listCode ea) []) (second ea (listCode ea))).comp + (listUncons ea)).congrFun (by intro xs;cases xs <;> rfl) + +noncomputable def listEmpty : Procedure (listCode ea) boolCode List.isEmpty := + ((casesSum (constant emptyCode boolCode true) (constant (prodCode ea (listCode ea)) boolCode false)).comp + (listUncons ea)).congrFun (by intro xs;cases xs <;> rfl) +end Procedure +end ExactQuantumFactoring.BitStackProgram + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackListFlatten.lean b/lean/OAI/Computability/QuantumFactoring/BitStackListFlatten.lean new file mode 100644 index 0000000000000000000000000000000000000000..1ec31d132aa779d3b3bae47951cfe4a5c06906d4 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackListFlatten.lean @@ -0,0 +1,47 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackListOps + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram +variable {α : Type} +lemma fold_append_flatten (xss : List (List α)) (xs : List α) : + xss.foldl (fun xs ys=>xs++ys) xs=xs++xss.flatten:=by + induction xss generalizing xs with + | nil=>simp + | cons ys yss ih=>simp [ih,List.append_assoc] +lemma listCode_length_flatten_le (ea : α→List Bool) (xss : List (List α)) : + (listCode ea xss.flatten).length≤(listCode (listCode ea) xss).length:=by + induction xss with + | nil=>simp [listCode] + | cons xs xss ih=> + simp only [List.flatten_cons,listCode_length_cons] + have hh:=listCode_length_append ea xs xss.flatten + omega +namespace Procedure +noncomputable def listFlatten (ea : α→List Bool) (d : α) : + Procedure (listCode (listCode ea)) (listCode ea) List.flatten:=by + let step:=(listAppend ea d).comp ((second (listCode ea) (listCode ea)).pair + (first (listCode ea) (listCode ea))) + let p:=foldList [] step Polynomial.X (by + intro xss xs i + change (listCode ea ((xss.take i).foldl (fun xs ys=>xs++ys) xs)).length≤_ + rw [fold_append_flatten] + have hh:=listCode_length_append ea xs (xss.take i).flatten + have hl:=listCode_length_flatten_le ea (xss.take i) + have ht:=listCode_length_take_le (listCode ea) i xss + simp only [Polynomial.eval_X];omega) + exact (p.comp ((identity (listCode (listCode ea))).pair (constant _ (listCode ea) []))).congrFun (by + intro xss;exact fold_append_flatten xss []) +end Procedure +end ExactQuantumFactoring.BitStackProgram + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackListFold.lean b/lean/OAI/Computability/QuantumFactoring/BitStackListFold.lean new file mode 100644 index 0000000000000000000000000000000000000000..515dc164c5d3e28e9ad2a36cc00c5f505ee0c14d --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackListFold.lean @@ -0,0 +1,85 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackListCode +import OAI.Computability.QuantumFactoring.BitStackBooleans +import OAI.Computability.QuantumFactoring.BitStackIteration + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram +variable {α β : Type} + +def listScan (f : α×β→β) : List α×β→List α×β + | ([],b)=>([],b) + | (a::as,b)=>(as,f (a,b)) + +lemma listScan_iterate (f : α×β→β) (i : ℕ) (xs : List α) (b : β) : + (listScan f)^[i] (xs,b)=(xs.drop i,(xs.take i).foldl (fun b a=>f (a,b)) b) := by + induction i generalizing xs b with + | zero=>simp + | succ i ih=> + rw [Function.iterate_succ_apply] + cases xs with + | nil=>simpa [listScan] using ih [] b + | cons a as=>simpa [listScan] using ih as (f (a,b)) + +lemma listCode_length_drop_le (ea : α→List Bool) (i : ℕ) (xs : List α) : + (listCode ea (xs.drop i)).length≤(listCode ea xs).length := by + have hh:=listCode_length_append ea (xs.take i) (xs.drop i) + rw [List.take_append_drop] at hh + have hp:=listCode_length_pos ea (xs.take i) + omega + +lemma listCode_length_take_le (ea : α→List Bool) (i : ℕ) (xs : List α) : + (listCode ea (xs.take i)).length≤(listCode ea xs).length := by + have hh:=listCode_length_append ea (xs.take i) (xs.drop i) + rw [List.take_append_drop] at hh + have hp:=listCode_length_pos ea (xs.drop i) + omega + +namespace Procedure +variable {ea : α→List Bool} {eb : β→List Bool} {f : α×β→β} +noncomputable def listScanP (d : α) (p : Procedure (prodCode ea eb) eb f) : + Procedure (prodCode (listCode ea) eb) (prodCode (listCode ea) eb) (listScan f) := by + let xs:=first (listCode ea) eb + let b:=second (listCode ea) eb + let upd:=((listTail ea).comp xs).pair (p.comp (((listHead ea d).comp xs).pair b)) + exact ((choose upd (identity (prodCode (listCode ea) eb))).comp + (((listEmpty ea).comp xs).pair (identity (prodCode (listCode ea) eb)))).congrFun + (by rintro ⟨xs,b⟩;cases xs <;> rfl) + +noncomputable def foldList (d : α) (p : Procedure (prodCode ea eb) eb f) + (bound : Polynomial ℕ) + (hsize : ∀ (xs : List α) b i, + (eb ((xs.take i).foldl (fun b a=>f (a,b)) b)).length≤ + bound.eval ((listCode ea xs).length+(eb b).length)) : + Procedure (prodCode (listCode ea) eb) eb (fun x=>x.1.foldl (fun b a=>f (a,b)) x.2) := by + let s:=listScanP d p + let rep:=s.iterate (Polynomial.C 2*Polynomial.X+1+bound) (by + intro n x i _ + rw [listScan_iterate] + simp only [prodCode,pairBits_length] + have hs:=hsize x.1 x.2 i + have hl:=listCode_length_drop_le ea i x.1 + have hm:=eval_nat_mono bound (by omega : + (listCode ea x.1).length+(eb x.2).length≤n+(2*(listCode ea x.1).length+(eb x.2).length+1)) + dsimp only at hm + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_C, + Polynomial.eval_X,Polynomial.eval_one] + omega) + let wc:=(length.precompose (listCode ea)).comp (first (listCode ea) eb) + exact ((second (listCode ea) eb).comp (rep.comp (wc.pair (identity (prodCode (listCode ea) eb))))).congrFun + (by + rintro ⟨xs,b⟩ + change ((listScan f)^[(listCode ea xs).length] (xs,b)).2=xs.foldl (fun b a=>f (a,b)) b + rw [listScan_iterate,List.take_of_length_le (list_length_le_code ea xs)]) +end Procedure +end ExactQuantumFactoring.BitStackProgram + +end + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackListIndex.lean b/lean/OAI/Computability/QuantumFactoring/BitStackListIndex.lean new file mode 100644 index 0000000000000000000000000000000000000000..c3f7aea6b78843cbedbddf0109978329c8b620bd --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackListIndex.lean @@ -0,0 +1,67 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackListFold +import OAI.Computability.QuantumFactoring.BitStackDivision + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram +variable {α : Type} +def dropStep : ℕ×List α→ℕ×List α + | (n,xs)=>if n=0 then (n,xs) else (n-1,xs.tail) +lemma dropStep_iterate (i n : ℕ) (xs : List α) : + dropStep^[i] (n,xs)=(n-i,xs.drop (min i n)) := by + induction i generalizing n xs with + | zero=>simp + | succ i ih=> + rw [Function.iterate_succ_apply] + by_cases hn : n=0 + · subst n;simp [dropStep,ih] + · obtain ⟨n,rfl⟩:=Nat.exists_eq_succ_of_ne_zero hn + simp only [dropStep,Nat.succ_ne_zero,ite_false,Nat.succ_sub_one,ih] + rw [←List.drop_one,List.drop_drop] + congr 1 + · omega + · congr 1; omega + +namespace Procedure +variable (ea : α→List Bool) +noncomputable def listDrop : Procedure (prodCode Nat.bits (listCode ea)) (listCode ea) + (fun x=>x.2.drop x.1) := by + let en:=prodCode Nat.bits (listCode ea) + let n:=first Nat.bits (listCode ea) + let xs:=second Nat.bits (listCode ea) + let pred:=binarySub.comp (n.pair (constant en Nat.bits 1)) + let step:=(conditional (binaryZero.comp n) (identity en) + (pred.pair ((listTail ea).comp xs))).congrFun (by intro x;rfl) + have stepType : Procedure en en (dropStep (α:=α)):= + step.congrFun (by intro x;simp only [Function.comp_apply,decide_eq_true_eq,id_eq,dropStep]) + let rep:=stepType.iterate Polynomial.X (by + intro k x i _ + rw [dropStep_iterate] + simp only [en,prodCode,pairBits_length,Polynomial.eval_X] + have hn:=bits_length_mono (Nat.sub_le x.1 i) + have hl:=listCode_length_drop_le ea (min i x.1) x.2 + omega) + let times:=(length.precompose (listCode ea)).comp xs + exact (xs.comp (rep.comp (times.pair (identity en)))).congrFun (by + intro x + change (dropStep^[(listCode ea x.2).length] x).2=x.2.drop x.1 + rw [dropStep_iterate] + by_cases h:x.1≤(listCode ea x.2).length + · rw [Nat.min_eq_right h] + · have hlen:=list_length_le_code ea x.2 + rw [Nat.min_eq_left (by omega),List.drop_eq_nil_of_le (by omega),List.drop_eq_nil_of_le (by omega)]) +noncomputable def listGet (d : α) : Procedure (prodCode Nat.bits (listCode ea)) ea + (fun x=>(x.2.drop x.1).headD d) := (listHead ea d).comp (listDrop ea) +end Procedure +end ExactQuantumFactoring.BitStackProgram + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackListLength.lean b/lean/OAI/Computability/QuantumFactoring/BitStackListLength.lean new file mode 100644 index 0000000000000000000000000000000000000000..e89027627a91e8c9dab20437056456cecf5959e0 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackListLength.lean @@ -0,0 +1,37 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackListFold +import OAI.Computability.QuantumFactoring.BitStackNaturals + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram +variable {α : Type} +lemma fold_count (xs : List α) (n : ℕ) : xs.foldl (fun n _=>n+1) n=n+xs.length := by + induction xs generalizing n with + | nil=>simp + | cons a as ih=>simp only [List.foldl_cons,ih,List.length_cons];omega +namespace Procedure +noncomputable def listLength (ea : α→List Bool) (d : α) : + Procedure (listCode ea) Nat.bits List.length := by + let step:=unarySuccessor.comp (second ea unaryCode) + let rep:=foldList d step Polynomial.X (by + intro xs n i + change (unaryCode ((xs.take i).foldl (fun n _=>n+1) n)).length≤_ + rw [fold_count] + simp only [unaryCode,List.length_replicate,Polynomial.eval_X,List.length_take] + have hh:=list_length_le_code ea xs + omega) + let start:=(identity (listCode ea)).pair (constant (listCode ea) unaryCode 0) + exact (unaryToBits.comp (rep.comp start)).congrFun (by intro xs;simpa only [Function.comp_apply,id_eq,Nat.zero_add] using fold_count xs 0) +end Procedure +end ExactQuantumFactoring.BitStackProgram + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackListMapIdx.lean b/lean/OAI/Computability/QuantumFactoring/BitStackListMapIdx.lean new file mode 100644 index 0000000000000000000000000000000000000000..8732624044a19a2de59faeb3e2df41c87b1ca022 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackListMapIdx.lean @@ -0,0 +1,43 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackTabulate +import OAI.Computability.QuantumFactoring.NativeAIGAddWrapper + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram +variable {α β γ : Type} +lemma map_range_getD_index (xs : List β) (d : β) (f : ℕ→β→γ) : + (List.range xs.length).map (fun i=>f i ((xs.drop i).headD d))=xs.mapIdx f:=by + apply List.ext_getElem + · simp + · intro i h1 h2 + have hi : if x.1 x.2.1 x.2.2)) : + Procedure (prodCode ea (listCode eb)) (listCode ec) (fun x=>x.2.mapIdx (f x.1)):=by + let i:=unaryToBits.comp (first unaryCode (prodCode ea (listCode eb))) + let env:=second unaryCode (prodCode ea (listCode eb)) + let a:=(first ea (listCode eb)).comp env + let xs:=(second ea (listCode eb)).comp env + let get:=(listGet eb d).comp (i.pair xs) + let step:=p.comp (a.pair (i.pair get)) + let len:=(NativeAIG.Emission.listUnaryLength eb d).comp (second ea (listCode eb)) + exact ((tabulate (f:=fun (env : α×List β) i=>f env.1 i ((env.2.drop i).headD d)) e step).comp + (len.pair (identity (prodCode ea (listCode eb))))).congrFun (by + intro x;exact map_range_getD_index x.2 d (f x.1)) +end Procedure +end ExactQuantumFactoring.BitStackProgram + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackListMapWith.lean b/lean/OAI/Computability/QuantumFactoring/BitStackListMapWith.lean new file mode 100644 index 0000000000000000000000000000000000000000..dfc02028aa133e84ff0072d7ea2abeaa5c7a3bac --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackListMapWith.lean @@ -0,0 +1,42 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackTabulate +import OAI.Computability.QuantumFactoring.NativeAIGAddWrapper + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram +variable {α β γ : Type} +lemma map_range_getD (xs : List β) (d : β) (f : β→γ) : + (List.range xs.length).map (fun i=>f ((xs.drop i).headD d))=xs.map f := by + apply List.ext_getElem + · simp + · intro i h1 h2 + simp only [List.getElem_map,List.getElem_range] + have hi : if x.1 x.2)) : + Procedure (prodCode ea (listCode eb)) (listCode ec) (fun x=>x.2.map (f x.1)) := by + let i:=unaryToBits.comp (first unaryCode (prodCode ea (listCode eb))) + let env:=second unaryCode (prodCode ea (listCode eb)) + let a:=(first ea (listCode eb)).comp env + let xs:=(second ea (listCode eb)).comp env + let get:=(listGet eb d).comp (i.pair xs) + let step:=p.comp (a.pair get) + let len:=(NativeAIG.Emission.listUnaryLength eb d).comp (second ea (listCode eb)) + exact ((tabulate (f:=fun (env : α×List β) i=>f env.1 ((env.2.drop i).headD d)) e step).comp (len.pair (identity (prodCode ea (listCode eb))))).congrFun (by + intro x;exact map_range_getD x.2 d (f x.1)) +end Procedure +end ExactQuantumFactoring.BitStackProgram + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackListOps.lean b/lean/OAI/Computability/QuantumFactoring/BitStackListOps.lean new file mode 100644 index 0000000000000000000000000000000000000000..a77eb0ff75285c832e718214b552c615bfbaa96c --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackListOps.lean @@ -0,0 +1,100 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackListFold + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram +variable {α β : Type} + +lemma fold_cons_append (xs ys : List α) : xs.foldl (fun ys a=>a::ys) ys=xs.reverse++ys := by + induction xs generalizing ys with + | nil=>rfl + | cons a as ih=>simp only [List.foldl_cons,ih,List.reverse_cons,List.append_assoc,List.singleton_append] + +lemma fold_map_cons_append (f : α→β) (xs : List α) (ys : List β) : + xs.foldl (fun ys a=>f a::ys) ys=(xs.map f).reverse++ys := by + induction xs generalizing ys with + | nil=>rfl + | cons a as ih=>simp only [List.foldl_cons,ih,List.map_cons,List.reverse_cons, + List.append_assoc,List.singleton_append] + +lemma listCode_length_map_bound (eb : β→List Bool) (f : α→β) (xs : List α) (B : ℕ) + (h : ∀ a∈xs,(eb (f a)).length≤B) : + (listCode eb (xs.map f)).length≤xs.length*(2*B+2)+1 := by + induction xs with + | nil=>simp [listCode] + | cons a as ih=> + have ha:=h a (by simp) + have hb:=ih (by intro b hb;exact h b (by simp [hb])) + simp only [List.map_cons,listCode_length_cons,List.length_cons] + nlinarith + +namespace Procedure +variable (ea : α→List Bool) +noncomputable def listRevAppend (d : α) : Procedure (prodCode (listCode ea) (listCode ea)) + (listCode ea) (fun x=>x.1.reverse++x.2) := + (foldList d (listCons ea) Polynomial.X (by + intro xs ys i + rw [fold_cons_append] + have hh:=listCode_length_append ea (xs.take i).reverse ys + rw [listCode_length_rev] at hh + have ht:=listCode_length_take_le ea i xs + simp only [Polynomial.eval_X] + omega)).congrFun (by intro x;exact fold_cons_append x.1 x.2) + +noncomputable def listReverse (d : α) : Procedure (listCode ea) (listCode ea) List.reverse := + ((listRevAppend ea d).comp ((identity (listCode ea)).pair + (constant (listCode ea) (listCode ea) []))).congrFun (by intro xs;exact List.append_nil _) + +noncomputable def listAppend (d : α) : Procedure (prodCode (listCode ea) (listCode ea)) + (listCode ea) (fun x=>x.1++x.2) := + ((listRevAppend ea d).comp (((listReverse ea d).comp (first (listCode ea) (listCode ea))).pair + (second (listCode ea) (listCode ea)))).congrFun (by intro x;exact congrArg (fun xs=>xs++x.2) (List.reverse_reverse x.1)) + +variable {ea} {eb : β→List Bool} {f : α→β} +noncomputable def listMap (d : α) (e : β) (p : Procedure ea eb f) : + Procedure (listCode ea) (listCode eb) (List.map f) := by + let step:=(listCons eb).comp ((p.comp (first ea (listCode eb))).pair (second ea (listCode eb))) + let q:=Polynomial.X*(Polynomial.C 2*(Polynomial.X+p.bound)+Polynomial.C 2)+1+Polynomial.X + let fold:=foldList d step q (by + intro xs ys i + change (listCode eb ((xs.take i).foldl (fun ys a=>f a::ys) ys)).length≤_ + rw [fold_map_cons_append] + let L:=(listCode ea xs).length+(listCode eb ys).length + have hh:=listCode_length_append eb ((xs.take i).map f).reverse ys + rw [listCode_length_rev] at hh + have hm:(listCode eb ((xs.take i).map f)).length≤(xs.take i).length*(2*(L+p.bound.eval L)+2)+1:=by + apply listCode_length_map_bound + intro a ha + have hc:=(code_le_of_mem ea (List.mem_of_mem_take ha)).trans (Nat.le_add_right _ (listCode eb ys).length) + have ho:=p.output_length_le a + have hp:=eval_nat_mono p.bound hc + dsimp only [L] at * + omega + have ht : (xs.take i).length≤L:=by + have h1:=list_length_le_code ea xs + simp only [List.length_take] + dsimp [L];omega + have hm':=(Nat.mul_le_mul_right (2*(L+p.bound.eval L)+2) ht) + simp only [q,Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_C, + Polynomial.eval_X,Polynomial.eval_one] + change (listCode eb (((xs.take i).map f).reverse++ys)).length≤L*(2*(L+p.bound.eval L)+2)+1+L + dsimp only [L] at * + omega) + let start:=(identity (listCode ea)).pair (constant (listCode ea) (listCode eb) []) + exact ((listReverse eb e).comp (fold.comp start)).congrFun (by + intro xs + change (xs.foldl (fun ys a=>f a::ys) []).reverse=xs.map f + rw [fold_map_cons_append,List.append_nil,List.reverse_reverse]) +end Procedure +end ExactQuantumFactoring.BitStackProgram + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackListWords.lean b/lean/OAI/Computability/QuantumFactoring/BitStackListWords.lean new file mode 100644 index 0000000000000000000000000000000000000000..804c2511e701ace1f38a2a65354824ff1ccb9de5 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackListWords.lean @@ -0,0 +1,48 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackListOps + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram +lemma flatten_length_le_code (xs : List (List Bool)) : + xs.flatten.length ≤ (listCode (id : List Bool→List Bool) xs).length := by + induction xs with + | nil=>simp [listCode] + | cons x xs ih=> + simp only [List.flatten_cons,List.length_append,listCode_length_cons,id_eq] + omega +lemma fold_append_words (xs : List (List Bool)) (ys : List Bool) : + xs.foldl (fun ys x=>ys++x) ys=ys++xs.flatten := by + induction xs generalizing ys with + | nil=>simp + | cons x xs ih=>simp [ih,List.append_assoc] +namespace Procedure +noncomputable def listJoinWords : Procedure (listCode (id : List Bool→List Bool)) id List.flatten := by + let step:=(append.comp (swap (id : List Bool→List Bool) id)) + let rep:=foldList [] step Polynomial.X (by + intro xs ys i + change ((xs.take i).foldl (fun ys x=>ys++x) ys).length ≤ _ + rw [fold_append_words,List.length_append] + have hh:=flatten_length_le_code (xs.take i) + have ht:=listCode_length_take_le (id : List Bool→List Bool) i xs + simp only [Polynomial.eval_X,id_eq] + omega) + exact (rep.comp ((identity (listCode (id : List Bool→List Bool))).pair + (constant (listCode (id : List Bool→List Bool)) id []))).congrFun (by + intro xs;change xs.foldl (fun ys x=>ys++x) []=xs.flatten + simpa only [List.nil_append] using fold_append_words xs []) +noncomputable def listFlatMapWords {α : Type} {ea : α→List Bool} {f : α→List Bool} + (d : α) (p : Procedure ea id f) : Procedure (listCode ea) id (fun xs=>xs.flatMap f) := + (listJoinWords.comp (listMap d [] p)).congrFun (by intro xs;rfl) +end Procedure +end ExactQuantumFactoring.BitStackProgram + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackLists.lean b/lean/OAI/Computability/QuantumFactoring/BitStackLists.lean new file mode 100644 index 0000000000000000000000000000000000000000..fd3dbdcc464cc05aa2f949e1cb3c16dbc5f05a72 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackLists.lean @@ -0,0 +1,126 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackPrograms + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram +variable {K : Type} [DecidableEq K] + +/-- Reverse one stack onto another, preserving all symbols. -/ +def reverseMove (a b : K) : Program K := .loop a (.push b false) (.push b true) +def clear (a : K) : Program K := .loop a .skip .skip + +def duplicateReverse (a b t : K) : Program K := + .seq (.loop a (.seq (.push b false) (.push t false)) + (.seq (.push b true) (.push t true))) (reverseMove t a) + +lemma update_comm (s : Store K) (a b : K) (x y : List Bool) (hab : a≠b) : + Function.update (Function.update s a x) b y = + Function.update (Function.update s b y) a x := by + funext k + by_cases ha : k=a <;> by_cases hb : k=b <;> simp_all [Function.update] + +lemma clear_runs (a : K) (s : Store K) : + Runs (clear a) s (Function.update s a []) (2*(s a).length+1) := by + generalize hs : s a=xs at * + induction xs generalizing s with + | nil => + have he : Function.update s a []=s := by rw [←hs,Function.update_eq_self] + rw [he] + exact Runs.loop_nil hs + | cons x xs ih => + have ht : Function.update s a xs a=xs := by simp + have hh := ih (Function.update s a xs) ht + cases x + · have hr := Runs.loop_false hs (Runs.skip (Function.update s a xs)) hh + convert hr using 1 <;> first | rfl | simp only [Function.update_idem] + · have hr := Runs.loop_true hs (Runs.skip (Function.update s a xs)) hh + convert hr using 1 <;> first | rfl | simp only [Function.update_idem] + +lemma reverseMove_runs (a b : K) (hab : a≠b) (s : Store K) : + Runs (reverseMove a b) s + (Function.update (Function.update s a []) b ((s a).reverse++s b)) + (2*(s a).length+1) := by + generalize hs : s a=xs at * + induction xs generalizing s with + | nil => + have he : Function.update (Function.update s a []) b ([].reverse++s b)=s := by + rw [List.reverse_nil,List.nil_append,←hs,Function.update_eq_self,Function.update_eq_self] + rw [he] + exact Runs.loop_nil hs + | cons x xs ih => + let t := Function.update s a xs + let u := Function.update t b (x::t b) + have hua : u a=xs := by simp [u,t,hab] + have htail := ih u hua + have body : Runs (.push b x) t u 1 := Runs.push _ _ _ + have hr : Runs (reverseMove a b) s + (Function.update (Function.update u a []) b (xs.reverse++u b)) (2*xs.length+1+1+1) := by + cases x + · exact Runs.loop_false (a:=1) (b:=2*xs.length+1) hs body htail + · exact Runs.loop_true (a:=1) (b:=2*xs.length+1) hs body htail + convert hr using 1 + funext k + by_cases ha : k=a <;> by_cases hb : k=b <;> + simp_all [u,t,Function.update,List.reverse_cons,List.append_assoc] + +lemma duplicateReverse_loop_runs (a b t : K) (hab : a≠b) (hat : a≠t) (hbt : b≠t) + (s : Store K) : + Runs (.loop a (.seq (.push b false) (.push t false)) + (.seq (.push b true) (.push t true))) s + (Function.update (Function.update (Function.update s a []) b ((s a).reverse++s b)) + t ((s a).reverse++s t)) (3*(s a).length+1) := by + generalize hs : s a=xs at * + induction xs generalizing s with + | nil => + have he : Function.update (Function.update (Function.update s a []) b ([].reverse++s b)) + t ([].reverse++s t)=s := by + rw [List.reverse_nil,List.nil_append,List.nil_append,←hs,Function.update_eq_self, + Function.update_eq_self,Function.update_eq_self] + rw [he] + exact Runs.loop_nil hs + | cons x xs ih => + let u := Function.update s a xs + let w := Function.update u b (x::u b) + let v := Function.update w t (x::w t) + have hva : v a=xs := by simp [v,w,u,hab,hat] + have htail := ih v hva + have body : Runs (.seq (.push b x) (.push t x)) u v 2 := + Runs.seq (Runs.push _ _ _) (Runs.push _ _ _) + have hr : Runs (.loop a (.seq (.push b false) (.push t false)) + (.seq (.push b true) (.push t true))) s + (Function.update (Function.update (Function.update v a []) b (xs.reverse++v b)) + t (xs.reverse++v t)) (3*xs.length+1+2+1) := by + cases x + · exact Runs.loop_false (a:=2) (b:=3*xs.length+1) hs body htail + · exact Runs.loop_true (a:=2) (b:=3*xs.length+1) hs body htail + convert hr using 1 + funext k + by_cases ha : k=a <;> by_cases hb : k=b <;> by_cases ht : k=t <;> + simp_all [v,w,u,Function.update,List.reverse_cons,List.append_assoc] + +lemma duplicateReverse_runs (a b t : K) (hab : a≠b) (hat : a≠t) (hbt : b≠t) + (s : Store K) (ht : s t=[]) : + Runs (duplicateReverse a b t) s (Function.update s b ((s a).reverse++s b)) + (5*(s a).length+2) := by + let v := Function.update (Function.update (Function.update s a []) b ((s a).reverse++s b)) + t ((s a).reverse++s t) + have hr := reverseMove_runs t a hat.symm v + have hh := Runs.seq (duplicateReverse_loop_runs a b t hab hat hbt s) hr + change Runs (.seq _ _) _ _ _ + convert hh using 1 + · funext k + by_cases ha : k=a <;> by_cases hb : k=b <;> by_cases ht' : k=t <;> + simp_all [v,Function.update] + · simp only [v,Function.update_self,ht,List.append_nil,List.length_reverse]; omega + +end ExactQuantumFactoring.BitStackProgram + +end + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackMultiplier.lean b/lean/OAI/Computability/QuantumFactoring/BitStackMultiplier.lean new file mode 100644 index 0000000000000000000000000000000000000000..9ec1b0df9c3ffbf171eef109a330558b77a1aebf --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackMultiplier.lean @@ -0,0 +1,98 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackSubtractor + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram + +lemma bits_length_mono {a b : ℕ} (h : a≤b) : a.bits.length≤b.bits.length := by + simpa only [Nat.size_eq_bits_len] using Nat.size_le_size h + +lemma bits_length_value (xs : List Bool) : (binaryValue xs).bits.length≤xs.length := by + rw [Nat.size_eq_bits_len,Nat.size_le] + exact binaryValue_lt xs + +lemma bits_length_add (a b : ℕ) : (a+b).bits.length≤a.bits.length+b.bits.length+1 := by + rw [Nat.size_eq_bits_len,Nat.size_le] + have ha:=Nat.lt_size_self a + have hb:=Nat.lt_size_self b + have hap : 2^a.size≤2^(a.bits.length+b.bits.length):=by + apply Nat.pow_le_pow_right (by omega) + simp only [Nat.size_eq_bits_len];omega + have hbp : 2^b.size≤2^(a.bits.length+b.bits.length):=by + apply Nat.pow_le_pow_right (by omega) + simp only [Nat.size_eq_bits_len];omega + rw [pow_succ] + omega + +lemma bits_length_mul (a b : ℕ) : (a*b).bits.length≤a.bits.length+b.bits.length := by + rw [Nat.size_eq_bits_len,Nat.size_le,pow_add] + have h:=Nat.mul_lt_mul_of_lt_of_lt (Nat.lt_size_self a) (Nat.lt_size_self b) + simpa only [Nat.size_eq_bits_len] using h + +lemma bits_length_pow2 (n : ℕ) : (2^n).bits.length=n+1 := by + rw [Nat.size_eq_bits_len,Nat.size_pow] + +def mulZeroStep (x : ℕ×ℕ) : ℕ×ℕ := (x.1,2*x.2) +def mulOneStep (x : ℕ×ℕ) : ℕ×ℕ := (x.1,2*x.2+x.1) + +lemma mul_fold (xs : List Bool) (x : ℕ×ℕ) : + xs.foldl (bitAction mulZeroStep mulOneStep) x= + (x.1,x.1*binaryValue xs.reverse+2^xs.length*x.2) := by + induction xs generalizing x with + | nil=>simp [binaryValue] + | cons b bs ih=> + rw [List.foldl_cons,ih] + simp only [List.reverse_cons,binaryValue_append,List.length_reverse,List.length_cons, + binaryValue,pow_succ] + cases b <;> simp [bitAction,mulZeroStep,mulOneStep] <;> ring + +namespace Procedure +noncomputable def mulZeroStepP : Procedure (prodCode Nat.bits Nat.bits) + (prodCode Nat.bits Nat.bits) mulZeroStep := + ((first Nat.bits Nat.bits).pair (double.comp (second Nat.bits Nat.bits))).congrFun (by intro x;rfl) +noncomputable def mulOneStepP : Procedure (prodCode Nat.bits Nat.bits) + (prodCode Nat.bits Nat.bits) mulOneStep := by + let first:=first Nat.bits Nat.bits + let second:=second Nat.bits Nat.bits + exact (first.pair (binaryAdd.comp ((double.comp second).pair first))).congrFun (by intro x;rfl) + +noncomputable def mulFoldP : Procedure (prodCode id (prodCode Nat.bits Nat.bits)) + (prodCode Nat.bits Nat.bits) (fun x=>x.1.foldl (bitAction mulZeroStep mulOneStep) x.2) := + foldBits mulZeroStepP mulOneStepP (Polynomial.C 3*Polynomial.X+Polynomial.C 3) (by + intro xs x i + rw [mul_fold] + simp only [prodCode,pairBits_length] + have hs:=bits_length_add (x.1*binaryValue (xs.take i).reverse) (2^(xs.take i).length*x.2) + have hm:=bits_length_mul x.1 (binaryValue (xs.take i).reverse) + have hn:=bits_length_mul (2^(xs.take i).length) x.2 + have hv:=bits_length_value (xs.take i).reverse + rw [List.length_reverse] at hv + rw [bits_length_pow2] at hn + have hl : (xs.take i).length≤xs.length:=by simp only [List.length_take];omega + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_C,Polynomial.eval_X] + omega) + +noncomputable def binaryMul : Procedure (prodCode Nat.bits Nat.bits) Nat.bits + (fun x=>x.1*x.2) := by + let first:=first Nat.bits Nat.bits + let second:=second Nat.bits Nat.bits + let bits : Procedure Nat.bits (id : List Bool→List Bool) Nat.bits:= + (identity (id : List Bool→List Bool)).precompose Nat.bits + let start:=(reverse.comp (bits.comp second)).pair + (first.pair (constant (prodCode Nat.bits Nat.bits) Nat.bits 0)) + exact ((Procedure.second Nat.bits Nat.bits).comp (mulFoldP.comp start)).congrFun (by + intro x + simp [mul_fold,binaryValue_bits]) +end Procedure +end ExactQuantumFactoring.BitStackProgram + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackNaturals.lean b/lean/OAI/Computability/QuantumFactoring/BitStackNaturals.lean new file mode 100644 index 0000000000000000000000000000000000000000..b1008caa047c4a1272950fb623d661561eeb82a3 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackNaturals.lean @@ -0,0 +1,86 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackBasicProcedures +import OAI.Computability.QuantumFactoring.BitStackConstants +import OAI.Computability.QuantumFactoring.BitStackIncrement +import OAI.Computability.QuantumFactoring.BitStackIteration + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram +lemma binaryValue_bits (n : ℕ) : binaryValue n.bits=n := by + induction n using Nat.binaryRec' with + | zero => rfl + | bit b n hn ih => + rw [Nat.bits_append_bit n b hn] + cases b <;> simp [binaryValue,ih,Nat.bit,Nat.add_comm] + +lemma incrementWord_bits (n : ℕ) : incrementWord n.bits=(n+1).bits := by + induction n using Nat.binaryRec' with + | zero => rfl + | bit b n hn ih => + rw [Nat.bits_append_bit n b hn] + cases b + · simp only [incrementWord,Nat.bit_false,Nat.bit1_bits] + · simp only [incrementWord,ih,Nat.bit_true] + rw [show 2*n+1+1=2*(n+1) by omega,Nat.bit0_bits (n+1) (by omega)] + +abbrev unaryCode (n : ℕ) := List.replicate n true +namespace Procedure +noncomputable def successor : Procedure Nat.bits Nat.bits Nat.succ where + K:=Fin 3 + finiteK:=inferInstance + decideK:=inferInstance + input:=0 + output:=0 + program:=increment 0 1 2 + bound:=Polynomial.C 6*Polynomial.X+Polynomial.C 6 + runs n:=by + have hh:=increment_runs (0 : Fin 3) 1 2 (by decide) (by decide) (by decide) + (singletonStore 0 n.bits) (by simp [singletonStore]) (by simp [singletonStore]) + refine ⟨6*carryCount n.bits+6,?_,?_⟩ + · have hl:=carryCount_le_length n.bits + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_C,Polynomial.eval_X] + omega + · simpa [singletonStore,incrementWord_bits] using hh + +noncomputable def unarySuccessor : Procedure unaryCode unaryCode Nat.succ where + K:=Unit + finiteK:=inferInstance + decideK:=inferInstance + input:=() + output:=() + program:=.push () true + bound:=1 + runs n:=by + refine ⟨1,by simp,?_⟩ + simpa [singletonStore,unaryCode,List.replicate_succ] using + Runs.push (singletonStore () (unaryCode n)) () true + +/-- Unary-to-binary conversion charges every carry and all word moves. -/ +noncomputable def unaryToBits : Procedure unaryCode Nat.bits id := by + let p:=successor.iterate (Polynomial.X+1) (by + intro n a i hi + have hlen : (a+i).bits.length≤a.bits.length+i := by + clear hi + induction i with + | zero => simp + | succ i ih => + have h:=incrementWord_length (a+i).bits + rw [incrementWord_bits] at h + simpa only [Nat.add_assoc] using (h.trans (Nat.add_le_add_right ih 1)) + simpa only [Function.iterate_succ_apply',Function.iterate_succ_apply, + Nat.succ_iterate,Nat.size_eq_bits_len,Polynomial.eval_add, + Polynomial.eval_X,Polynomial.eval_one] using (hlen.trans (by omega : a.bits.length+i≤n+a.bits.length+1))) + exact (p.comp ((identity unaryCode).pair (constant unaryCode Nat.bits 0))).congrFun + (by intro n; simp [Nat.succ_iterate]) +end Procedure +end ExactQuantumFactoring.BitStackProgram + +end + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackOptions.lean b/lean/OAI/Computability/QuantumFactoring/BitStackOptions.lean new file mode 100644 index 0000000000000000000000000000000000000000..398f72b52e4a7f4dfb83f6473ea253584616eadc --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackOptions.lean @@ -0,0 +1,60 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackBooleans +import OAI.Computability.QuantumFactoring.BitStackListCode +import OAI.Computability.QuantumFactoring.Procedure + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram +variable {α β : Type} +def optionCode (ea : α→List Bool) : Option α→List Bool + | none=>[false] + | some a=>true::ea a +def optionView : Option α→Unit⊕α + | none=>.inl () + | some a=>.inr a +lemma optionCode_length_some (ea : α→List Bool) (a : α) : + (optionCode ea (some a)).length=(ea a).length+1 := rfl + +namespace Procedure +variable {ea : α→List Bool} {eb : β→List Bool} +noncomputable def optionSome (ea : α→List Bool) : Procedure ea (optionCode ea) some := + (prepend ea [true]).result (by intro a;rfl) +noncomputable def optionCases {f : Unit→β} {g : α→β} + (p : Procedure emptyCode eb f) (q : Procedure ea eb g) : + Procedure (optionCode ea) eb (fun x=>Sum.elim f g (optionView x)) := + ((casesSum p q).precompose optionView).congrEncoding + (by intro x;cases x <;> rfl) (by intro x;rfl) +noncomputable def optionGet (ea : α→List Bool) (d : α) : + Procedure (optionCode ea) ea (fun x=>x.getD d) := + (optionCases (constant emptyCode ea d) (identity ea)).congrFun + (by intro x;cases x <;> rfl) +noncomputable def optionIsSome (ea : α→List Bool) : + Procedure (optionCode ea) boolCode Option.isSome := + (optionCases (constant emptyCode boolCode false) (constant ea boolCode true)).congrFun + (by intro x;cases x <;> rfl) +noncomputable def binaryEq : Procedure (prodCode Nat.bits Nat.bits) boolCode + (fun x=>decide (x.1=x.2)) := by + let swap:=(second Nat.bits Nat.bits).pair (first Nat.bits Nat.bits) + exact (boolAnd.comp (binaryLe.pair (binaryLe.comp swap))).congrFun + (by intro x;apply Bool.eq_iff_iff.mpr;simp only [Function.comp_apply,Bool.and_eq_true,decide_eq_true_eq];omega) +noncomputable def prodEq [DecidableEq α] [DecidableEq β] + (pa : Procedure (prodCode ea ea) boolCode (fun x=>decide (x.1=x.2))) + (pb : Procedure (prodCode eb eb) boolCode (fun x=>decide (x.1=x.2))) : + Procedure (prodCode (prodCode ea eb) (prodCode ea eb)) boolCode + (fun x=>decide (x.1=x.2)) := by + let l:=first (prodCode ea eb) (prodCode ea eb) + let r:=second (prodCode ea eb) (prodCode ea eb) + let a:=pa.comp (((first ea eb).comp l).pair ((first ea eb).comp r)) + let b:=pb.comp (((second ea eb).comp l).pair ((second ea eb).comp r)) + exact (boolAnd.comp (a.pair b)).congrFun (by rintro ⟨⟨a,b⟩,⟨c,d⟩⟩;apply Bool.eq_iff_iff.mpr;simp only [Function.comp_apply,Bool.and_eq_true,decide_eq_true_eq,Prod.mk.injEq]) +end Procedure +end ExactQuantumFactoring.BitStackProgram + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackPowers.lean b/lean/OAI/Computability/QuantumFactoring/BitStackPowers.lean new file mode 100644 index 0000000000000000000000000000000000000000..aa65f94ee20946cd161ad6f8b4cb3cc9110d12ea --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackPowers.lean @@ -0,0 +1,57 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.EmissionCombinators + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram +lemma bits_length_pow (a k : ℕ) : (a^k).bits.length≤k*a.bits.length+1:=by + induction k with + | zero=>simp + | succ k ih=> + have h:=bits_length_mul (a^k) a + rw [pow_succ];nlinarith + +def powerStep (s : ℕ×ℕ) : ℕ×ℕ:=(s.1,s.2*s.1) +lemma powerStep_iterate (s : ℕ×ℕ) (i : ℕ) : (powerStep^[i]) s=(s.1,s.2*s.1^i):=by + induction i with + | zero=>simp + | succ i ih=>rw [Function.iterate_succ_apply',ih];simp [powerStep,pow_succ,Nat.mul_assoc] +namespace Procedure +noncomputable def binaryPow : Procedure (prodCode unaryCode Nat.bits) Nat.bits (fun x=>x.2^x.1):=by + let a:=first Nat.bits Nat.bits + let b:=second Nat.bits Nat.bits + let step : Procedure (prodCode Nat.bits Nat.bits) (prodCode Nat.bits Nat.bits) powerStep:= + a.pair (binaryMul.comp (b.pair a)) + let rep:=step.iterate (Polynomial.X^2+Polynomial.C 3*Polynomial.X+1) (by + intro n s i hi + rw [powerStep_iterate] + have hm:=bits_length_mul s.2 (s.1^i) + have hp:=bits_length_pow s.1 i + simp only [prodCode,pairBits_length,Polynomial.eval_add,Polynomial.eval_pow,Polynomial.eval_X, + Polynomial.eval_mul,Polynomial.eval_C,Polynomial.eval_one] + nlinarith) + let e:=first unaryCode Nat.bits + let x:=second unaryCode Nat.bits + exact ((second Nat.bits Nat.bits).comp (rep.comp (e.pair (x.pair (constant _ Nat.bits 1))))).congrFun (by + intro x;change ((powerStep^[x.1]) (x.2,1)).2=x.2^x.1 + rw [powerStep_iterate];simp) +end Procedure +namespace Emits +variable {α : Type} {ea : α→List Bool} +lemma natPow {f k : α→ℕ} (hf : Emits ea Nat.bits f) (hk : Emits ea unaryCode k) : + Emits ea Nat.bits (fun x=>(f x)^(k x)):=(ofProcedure Procedure.binaryPow).comp (hk.pair hf) +lemma natEven {f : α→ℕ} (hf : Emits ea Nat.bits f) : Emits ea Procedure.boolCode (fun x=>decide (Even (f x))):=by + have h:=(ofProcedure Procedure.binaryEq).comp ((hf.natMod (const _ _ 2)).pair (const _ _ 0)) + exact h.congr (by intro x;simp only [Nat.even_iff]) +end Emits +end ExactQuantumFactoring.BitStackProgram + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackProcedures.lean b/lean/OAI/Computability/QuantumFactoring/BitStackProcedures.lean new file mode 100644 index 0000000000000000000000000000000000000000..4e49de5be90d1a9bd8890c7848c9dede81d50c95 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackProcedures.lean @@ -0,0 +1,97 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackPrograms + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram +variable {K : Type} [DecidableEq K] + +lemma Runs.length_le {p : Program K} {s t : Store K} {c : ℕ} (h : Runs p s t c) (k : K) : + (t k).length ≤ (s k).length+c := by + induction h with + | skip s => omega + | push s a b => + by_cases hk : k=a + · subst k; simp only [Function.update_self,List.length_cons]; omega + · simp only [Function.update_of_ne hk]; omega + | seq hp hq ip iq => omega + | cases_nil hs hr ih => omega + | @cases_false a p q r s t xs c hs hr ih => + by_cases hk : k=a + · subst k; simp only [Function.update_self] at ih; rw [hs,List.length_cons]; omega + · simp only [Function.update_of_ne hk] at ih; omega + | @cases_true a p q r s t xs c hs hr ih => + by_cases hk : k=a + · subst k; simp only [Function.update_self] at ih; rw [hs,List.length_cons]; omega + · simp only [Function.update_of_ne hk] at ih; omega + | loop_nil hs => omega + | @loop_false a p q s t u xs c d hs hp hq ip iq => + by_cases hk : k=a + · subst k; simp only [Function.update_self] at ip; rw [hs,List.length_cons]; omega + · simp only [Function.update_of_ne hk] at ip; omega + | @loop_true a p q s t u xs c d hs hp hq ip iq => + by_cases hk : k=a + · subst k; simp only [Function.update_self] at ip; rw [hs,List.length_cons]; omega + · simp only [Function.update_of_ne hk] at ip; omega + +/-- A completely explicit finite-state Boolean-stack subroutine, with the +same clean input/output convention as the frozen TM2 uniformity target. -/ +structure Procedure {α β : Type} (ea : α → List Bool) (eb : β → List Bool) (f : α → β) where + K : Type + finiteK : Fintype K + decideK : DecidableEq K + input : K + output : K + program : Program K + bound : Polynomial ℕ + runs : ∀ a, ∃ c, c ≤ bound.eval (ea a).length ∧ + @Runs K decideK program (@singletonStore K decideK input (ea a)) (@singletonStore K decideK output (eb (f a))) c + +attribute [instance] Procedure.finiteK Procedure.decideK +namespace Procedure +variable {α β : Type} {ea : α → List Bool} {eb : β → List Bool} {f : α → β} + +lemma output_length_le (p : Procedure ea eb f) (a : α) : + (eb (f a)).length ≤ (ea a).length+p.bound.eval (ea a).length := by + obtain ⟨c,hc,hr⟩ := p.runs a + have h := hr.length_le p.output + simp only [singletonStore,Function.update_self] at h + by_cases he : p.output=p.input + · simp only [he,Function.update_self] at h; omega + · simp only [Function.update_of_ne he,List.length_nil,Nat.zero_add] at h; omega + +noncomputable def toTM2 (p : Procedure ea eb f) : Turing.TM2ComputableInPolyTime ea eb f where + tm := machine p.input p.output p.program + inputAlphabet := Equiv.refl _ + outputAlphabet := Equiv.refl _ + time := p.bound+1 + outputsFun a := by + classical + let c := Classical.choose (p.runs a) + have hc := (Classical.choose_spec (p.runs a)).1 + have hr := (Classical.choose_spec (p.runs a)).2 + have h := machine_outputs p.input p.output p.program (ea a) (eb (f a)) c hr + have ht : Turing.TM2OutputsInTime (machine p.input p.output p.program) + (ea a) (some (eb (f a))) (p.bound.eval (ea a).length+1) := + ⟨h.1, h.2.trans (Nat.add_le_add_right hc 1)⟩ + convert ht using 1 + simp only [Polynomial.eval_add,Polynomial.eval_one] + congr 1 + · exact List.map_id _ + · congr 1 + exact List.map_id _ + +lemma toTM2_finite (p : Procedure ea eb f) : ∀ k, Finite (p.toTM2.tm.Γ k) := + machine_alphabets_finite _ _ _ +end Procedure +end ExactQuantumFactoring.BitStackProgram + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackProducts.lean b/lean/OAI/Computability/QuantumFactoring/BitStackProducts.lean new file mode 100644 index 0000000000000000000000000000000000000000..844bdbf61446f2949a9af3f2f2108d22bbecbadb --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackProducts.lean @@ -0,0 +1,119 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackComposition +import OAI.Computability.QuantumFactoring.BitStackQuotation +import OAI.Computability.QuantumFactoring.BitStackFrames + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram + +def prodCode {α β : Type} (ea : α→List Bool) (eb : β→List Bool) (x : α×β) : List Bool := + pairBits (ea x.1) (eb x.2) + +namespace Procedure +variable {α β γ : Type} {ea : α→List Bool} {eb : β→List Bool} {ec : γ→List Bool} {f : α→β} + +/-- Run a procedure on the first component, keeping the second component +literally on a disjoint stack. Parsing and re-quoting are explicitly charged. -/ +noncomputable def left (p : Procedure ea eb f) (ec : γ→List Bool) : + Procedure (prodCode ea ec) (prodCode eb ec) (fun x=>(f x.1,x.2)) where + K:=p.K ⊕ Fin 3 + finiteK:=inferInstance + decideK:=inferInstance + input:=Sum.inr 0 + output:=Sum.inr 0 + program:=.seq (unquoteMove (Sum.inr 0) (Sum.inl p.input) (Sum.inr 1) (Sum.inr 2)) + (.seq (p.program.relabel Sum.inl) + (quoteMove (Sum.inl p.output) (Sum.inr 0) (Sum.inr 1))) + bound:=Polynomial.C 14*Polynomial.X+Polynomial.C 8*p.bound+Polynomial.C 11 + runs x:=by + obtain ⟨cp,hcp,hp⟩:=p.runs x.1 + let s : Store (p.K ⊕ Fin 3):=singletonStore (Sum.inr 0) (prodCode ea ec x) + let u : Store (p.K ⊕ Fin 3):=sumStore (singletonStore p.input (ea x.1)) + (singletonStore 0 (ec x.2)) + let v : Store (p.K ⊕ Fin 3):=sumStore (singletonStore p.output (eb (f x.1))) + (singletonStore 0 (ec x.2)) + have hparse : Runs (unquoteMove (Sum.inr 0) (Sum.inl p.input) (Sum.inr 1) (Sum.inr 2)) + s u (7*(ea x.1).length+6) := by + have hh:=unquoteMove_runs (Sum.inr 0 : p.K ⊕ Fin 3) (Sum.inl p.input) + (Sum.inr 1) (Sum.inr 2) (by simp) (by simp) (by simp) (by simp) (by simp) + (by simp) (ea x.1) (ec x.2) s (by simp [s,singletonStore,prodCode,pairBits]) + (by simp [s,singletonStore]) (by simp [s,singletonStore]) + convert hh using 1 + funext k + cases k with + | inl k => by_cases hk : k=p.input <;> simp_all [s,u,singletonStore,sumStore,Function.update] + | inr k => fin_cases k <;> simp [s,u,singletonStore,sumStore,Function.update] + have hcall : Runs (p.program.relabel Sum.inl) u v cp := hp.left (singletonStore (0 : Fin 3) (ec x.2)) + have hquote : Runs (quoteMove (Sum.inl p.output) (Sum.inr 0) (Sum.inr 1)) v + (singletonStore (Sum.inr 0) (pairBits (eb (f x.1)) (ec x.2))) + (7*(eb (f x.1)).length+5) := by + have hh:=quoteMove_runs (Sum.inl p.output : p.K ⊕ Fin 3) + (Sum.inr 0) (Sum.inr 1) (by simp) (by simp) (by simp) v (by simp [v,singletonStore]) + convert hh using 1 + · funext k + cases k with + | inl k => by_cases hk : k=p.output <;> + simp_all [v,singletonStore,sumStore,Function.update] + | inr k => fin_cases k <;> simp [v,singletonStore,sumStore,Function.update,pairBits] + · simp [v,singletonStore] + refine ⟨(7*(eb (f x.1)).length+5)+cp+(7*(ea x.1).length+6),?_, + Runs.seq hparse (Runs.seq hcall hquote)⟩ + have hlen:=p.output_length_le x.1 + have hx : (ea x.1).length≤(prodCode ea ec x).length := by + simp only [prodCode,pairBits_length]; omega + have hm:=eval_nat_mono p.bound hx + dsimp only at hm + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_C,Polynomial.eval_X] + omega + +/-- Exchange two quoted word fields, without a unit-cost tuple operation. -/ +noncomputable def swap (ea : α→List Bool) (eb : β→List Bool) : + Procedure (prodCode ea eb) (prodCode eb ea) Prod.swap where + K:=Fin 4 + finiteK:=inferInstance + decideK:=inferInstance + input:=0 + output:=1 + program:=.seq (unquoteMove 0 1 2 3) (quoteMove 0 1 2) + bound:=Polynomial.C 7*Polynomial.X+Polynomial.C 11 + runs x:=by + let s : Store (Fin 4):=singletonStore 0 (prodCode ea eb x) + let u : Store (Fin 4):=Function.update (singletonStore 0 (eb x.2)) 1 (ea x.1) + have h1 : Runs (unquoteMove 0 1 2 3) s u (7*(ea x.1).length+6) := by + have hh:=unquoteMove_runs (0 : Fin 4) 1 2 3 (by decide) (by decide) (by decide) + (by decide) (by decide) (by decide) (ea x.1) (eb x.2) s + (by simp [s,singletonStore,prodCode,pairBits]) + (by simp [s,singletonStore]) (by simp [s,singletonStore]) + convert hh using 1 + funext k; fin_cases k <;> simp [s,u,singletonStore,Function.update] + have h2 : Runs (quoteMove 0 1 2) u (singletonStore 1 (prodCode eb ea x.swap)) + (7*(eb x.2).length+5) := by + have hh:=quoteMove_runs (0 : Fin 4) 1 2 (by decide) (by decide) (by decide) u + (by simp [u,singletonStore]) + convert hh using 1 + · funext k; fin_cases k <;> simp [u,singletonStore,Function.update,prodCode,pairBits] + · simp [u,singletonStore] + refine ⟨(7*(eb x.2).length+5)+(7*(ea x.1).length+6),?_,Runs.seq h1 h2⟩ + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_C,Polynomial.eval_X, + prodCode,pairBits_length] + omega + +/-- Two arbitrary already verified subroutines acting independently on a pair. -/ +noncomputable def parallel {δ : Type} {ed : δ→List Bool} {g : γ→δ} + (p : Procedure ea eb f) (q : Procedure ec ed g) : + Procedure (prodCode ea ec) (prodCode eb ed) (fun x=>(f x.1,g x.2)) := + (((swap ed eb).comp ((q.left eb).comp ((swap eb ec).comp (p.left ec)))).congrFun + (by intro x; rfl)) +end Procedure +end ExactQuantumFactoring.BitStackProgram + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackPrograms.lean b/lean/OAI/Computability/QuantumFactoring/BitStackPrograms.lean new file mode 100644 index 0000000000000000000000000000000000000000..12de33d1f5beabd6857b17ed3d2f7282048fd34c --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackPrograms.lean @@ -0,0 +1,252 @@ +import Mathlib + +namespace OAI + + + +section + +/-! A literal finite Boolean-stack compiler for circuit descriptions. +Branches inspect and consume one symbol, not an entire encoded word. +Operational derivations below count actual finite-state TM2 transitions. +-/ +namespace ExactQuantumFactoring.BitStackProgram +open Turing.TM2 StateTransition + +inductive Program (K : Type) where + | skip + | push (k : K) (b : Bool) + | seq (p q : Program K) + | cases (k : K) (nil ff tt : Program K) + | loop (k : K) (ff tt : Program K) + +def Node {K : Type} : Program K → Type + | .skip | .push _ _ => Unit + | .seq p q => Node p ⊕ Node q + | .cases _ a b c => Unit ⊕ (Node a ⊕ (Node b ⊕ Node c)) + | .loop _ b c => Unit ⊕ (Node b ⊕ Node c) + +noncomputable instance nodeFintype {K : Type} (p : Program K) : Fintype (Node p) := by + induction p with + | skip => exact inferInstanceAs (Fintype Unit) + | push => exact inferInstanceAs (Fintype Unit) + | seq p q hp hq => letI := hp; letI := hq; exact inferInstanceAs (Fintype (Node p ⊕ Node q)) + | cases k a b c ha hb hc => + letI := ha; letI := hb; letI := hc + exact inferInstanceAs (Fintype (Unit ⊕ (Node a ⊕ (Node b ⊕ Node c)))) + | loop k b c hb hc => + letI := hb; letI := hc + exact inferInstanceAs (Fintype (Unit ⊕ (Node b ⊕ Node c))) + +def entry {K : Type} : (p : Program K) → Node p + | .skip | .push _ _ => () + | .seq p _ => .inl (entry p) + | .cases _ _ _ _ | .loop _ _ _ => .inl () + +abbrev Store (K : Type) := K → List Bool +abbrev Config (K Λ : Type) := Cfg (fun _ : K => Bool) Λ (Option Bool) +def configured {K Λ : Type} (l : Λ) (s : Store K) : Config K Λ := ⟨some l,none,s⟩ +def jump {K Λ : Type} (l : Λ) : Stmt (fun _ : K => Bool) Λ (Option Bool) := + .load (fun _ => none) (.goto (fun _ => l)) +def dispatch {K Λ : Type} (k : K) (nil ff tt : Λ) : + Stmt (fun _ : K => Bool) Λ (Option Bool) := + .pop k (fun _ b => b) (.branch Option.isSome + (.branch (fun b => b.getD false) (jump tt) (jump ff)) (jump nil)) + +def statement {K Λ : Type} : (p : Program K) → Λ → (Node p → Λ) → Node p → + Stmt (fun _ : K => Bool) Λ (Option Bool) + | .skip,e,_,_ => jump e + | .push k b,e,_,_ => .push k (fun _ => b) (jump e) + | .seq p q,_e,w,.inl i => statement p (w (.inr (entry q))) (w ∘ Sum.inl) i + | .seq _ q,e,w,.inr i => statement q e (w ∘ Sum.inr) i + | .cases k a b c,_,w,.inl _ => dispatch k + (w (.inr (.inl (entry a)))) (w (.inr (.inr (.inl (entry b))))) + (w (.inr (.inr (.inr (entry c))))) + | .cases _ a _ _,e,w,.inr (.inl i) => statement a e (w ∘ Sum.inr ∘ Sum.inl) i + | .cases _ _ b _,e,w,.inr (.inr (.inl i)) => + statement b e (w ∘ Sum.inr ∘ Sum.inr ∘ Sum.inl) i + | .cases _ _ _ c,e,w,.inr (.inr (.inr i)) => + statement c e (w ∘ Sum.inr ∘ Sum.inr ∘ Sum.inr) i + | .loop k b c,e,w,.inl _ => dispatch k e + (w (.inr (.inl (entry b)))) (w (.inr (.inr (entry c)))) + | .loop _ b _,_,w,.inr (.inl i) => + statement b (w (.inl ())) (w ∘ Sum.inr ∘ Sum.inl) i + | .loop _ _ c,_,w,.inr (.inr i) => + statement c (w (.inl ())) (w ∘ Sum.inr ∘ Sum.inr) i + +inductive Runs {K : Type} [DecidableEq K] : Program K → Store K → Store K → ℕ → Prop + | skip (s) : Runs .skip s s 1 + | push (s) (k) (b) : Runs (.push k b) s (Function.update s k (b :: s k)) 1 + | seq {p q s t u a b} : Runs p s t a → Runs q t u b → Runs (.seq p q) s u (b+a) + | cases_nil {k p q r s t a} : s k=[] → Runs p s t a → Runs (.cases k p q r) s t (a+1) + | cases_false {k p q r s t xs a} : s k=false::xs → + Runs q (Function.update s k xs) t a → Runs (.cases k p q r) s t (a+1) + | cases_true {k p q r s t xs a} : s k=true::xs → + Runs r (Function.update s k xs) t a → Runs (.cases k p q r) s t (a+1) + | loop_nil {k p q s} : s k=[] → Runs (.loop k p q) s s 1 + | loop_false {k p q s t u xs a b} : s k=false::xs → + Runs p (Function.update s k xs) t a → Runs (.loop k p q) t u b → + Runs (.loop k p q) s u (b+a+1) + | loop_true {k p q s t u xs a b} : s k=true::xs → + Runs q (Function.update s k xs) t a → Runs (.loop k p q) t u b → + Runs (.loop k p q) s u (b+a+1) + +lemma iterate_step {α : Type*} (f : α → Option α) (a b : α) (h : f a=some b) : + (flip bind f)^[1] (some a) = some b := h +lemma iterate_comp {α : Type*} (f : α → Option α) (a b c : α) (k l : ℕ) + (h : (flip bind f)^[k] (some a)=some b) + (g : (flip bind f)^[l] (some b)=some c) : + (flip bind f)^[l+k] (some a)=some c := by + rw [Function.iterate_add_apply,h,g] + +lemma dispatch_nil {K Λ : Type} [DecidableEq K] (s : Store K) (k : K) (a b c : Λ) + (hs : s k=[]) : stepAux (dispatch k a b c) none s = configured a s := by + simp only [dispatch,stepAux,hs,List.head?_nil,List.tail_nil,Option.isSome_none, + Bool.cond_false,jump] + rw [← hs,Function.update_eq_self] + rfl +lemma dispatch_false {K Λ : Type} [DecidableEq K] (s : Store K) (k : K) (a b c : Λ) + (xs : List Bool) (hs : s k=false::xs) : + stepAux (dispatch k a b c) none s = configured b (Function.update s k xs) := by + simp only [dispatch,stepAux,hs,List.head?_cons,List.tail_cons,Option.isSome_some, + Bool.cond_true,Option.getD_some,Bool.cond_false,jump] + rfl +lemma dispatch_true {K Λ : Type} [DecidableEq K] (s : Store K) (k : K) (a b c : Λ) + (xs : List Bool) (hs : s k=true::xs) : + stepAux (dispatch k a b c) none s = configured c (Function.update s k xs) := by + simp only [dispatch,stepAux,hs,List.head?_cons,List.tail_cons,Option.isSome_some, + Bool.cond_true,Option.getD_some,jump] + rfl + +theorem compile_runs {K : Type} [DecidableEq K] {p : Program K} + {s t : Store K} {c : ℕ} (h : Runs p s t c) : + ∀ {Λ : Type} (e : Λ) (w : Node p → Λ) + (M : Λ → Stmt (fun _ : K => Bool) Λ (Option Bool)), + (∀ i, M (w i) = statement p e w i) → + (flip bind (step M))^[c] (some (configured (w (entry p)) s)) = some (configured e t) := by + induction h with + | skip s => + intro Λ e w M hM + apply iterate_step + change some (stepAux (M (w ())) none s) = _ + rw [hM ()] + rfl + | push s k b => + intro Λ e w M hM + apply iterate_step + change some (stepAux (M (w ())) none s) = _ + rw [hM ()] + rfl + | @seq p q s t u a b hp hq ihp ihq => + intro Λ e w M hM + apply iterate_comp (step M) _ (configured (w (.inr (entry q))) t) _ a b + · exact ihp _ _ M (fun i => hM (.inl i)) + · exact ihq _ _ M (fun i => hM (.inr i)) + | @cases_nil k p q r s t a hs hp ih => + intro Λ e w M hM + apply iterate_comp (step M) _ (configured (w (.inr (.inl (entry p)))) s) _ 1 a + · apply iterate_step + change some (stepAux (M (w (.inl ()))) none s) = _ + rw [hM (.inl ()),statement,dispatch_nil _ _ _ _ _ hs] + · exact ih _ _ M (fun i => hM (.inr (.inl i))) + | @cases_false k p q r s t xs a hs hp ih => + intro Λ e w M hM + apply iterate_comp (step M) _ (configured (w (.inr (.inr (.inl (entry q))))) + (Function.update s k xs)) _ 1 a + · apply iterate_step + change some (stepAux (M (w (.inl ()))) none s) = _ + rw [hM (.inl ()),statement,dispatch_false _ _ _ _ _ _ hs] + · exact ih _ _ M (fun i => hM (.inr (.inr (.inl i)))) + | @cases_true k p q r s t xs a hs hp ih => + intro Λ e w M hM + apply iterate_comp (step M) _ (configured (w (.inr (.inr (.inr (entry r))))) + (Function.update s k xs)) _ 1 a + · apply iterate_step + change some (stepAux (M (w (.inl ()))) none s) = _ + rw [hM (.inl ()),statement,dispatch_true _ _ _ _ _ _ hs] + · exact ih _ _ M (fun i => hM (.inr (.inr (.inr i)))) + | @loop_nil k p q s hs => + intro Λ e w M hM + apply iterate_step + change some (stepAux (M (w (.inl ()))) none s) = _ + rw [hM (.inl ()),statement,dispatch_nil _ _ _ _ _ hs] + | @loop_false k p q s t u xs a b hs hp hq ihp ihq => + intro Λ e w M hM + apply iterate_comp (step M) _ (configured (w (.inr (.inl (entry p)))) + (Function.update s k xs)) _ 1 (b+a) + · apply iterate_step + change some (stepAux (M (w (.inl ()))) none s) = _ + rw [hM (.inl ()),statement,dispatch_false _ _ _ _ _ _ hs] + · apply iterate_comp (step M) _ (configured (w (.inl ())) t) _ a b + · exact ihp _ _ M (fun i => hM (.inr (.inl i))) + · exact ihq _ _ M hM + | @loop_true k p q s t u xs a b hs hp hq ihp ihq => + intro Λ e w M hM + apply iterate_comp (step M) _ (configured (w (.inr (.inr (entry q)))) + (Function.update s k xs)) _ 1 (b+a) + · apply iterate_step + change some (stepAux (M (w (.inl ()))) none s) = _ + rw [hM (.inl ()),statement,dispatch_true _ _ _ _ _ _ hs] + · apply iterate_comp (step M) _ (configured (w (.inl ())) t) _ a b + · exact ihp _ _ M (fun i => hM (.inr (.inr i))) + · exact ihq _ _ M hM + +noncomputable def machine {K : Type} [Fintype K] [DecidableEq K] (input output : K) (p : Program K) : + Turing.FinTM2 where + K := K + k₀ := input + k₁ := output + Γ _ := Bool + Λ := Option (Node p) + main := some (entry p) + σ := Option Bool + initialState := none + m + | none => .halt + | some i => statement p none some i + +lemma machine_alphabets_finite {K : Type} [Fintype K] [DecidableEq K] + (input output : K) (p : Program K) : ∀ k, Finite ((machine input output p).Γ k) := + fun _ => (inferInstance : Finite Bool) + +def singletonStore {K : Type} [DecidableEq K] (k : K) (v : List Bool) : Store K := + Function.update (fun _ => []) k v + +noncomputable def machine_outputs {K : Type} [Fintype K] [DecidableEq K] + (input output : K) (p : Program K) (s t : List Bool) (c : ℕ) + (h : Runs p (singletonStore input s) (singletonStore output t) c) : + Turing.TM2OutputsInTime (machine input output p) s (some t) (c+1) := by + let tm := machine input output p + have hi : Turing.initList tm s = configured (some (entry p)) (singletonStore input s) := by + change Turing.initList (machine input output p) s = _ + unfold machine Turing.initList configured singletonStore + congr 1 + funext k + by_cases hk : k=input + · subst k; simp + · simp [hk,Function.update] + have hf : Turing.haltList tm t = + (⟨none,none,singletonStore output t⟩ : Config K (Option (Node p))) := by + change Turing.haltList (machine input output p) t = _ + unfold machine Turing.haltList singletonStore + congr 1 + funext k + by_cases hk : k=output + · subst k; simp + · simp [hk,Function.update] + have hr := compile_runs h (none : Option (Node p)) some tm.m (fun _ => rfl) + refine ⟨⟨c+1,?_⟩,le_rfl⟩ + change (flip bind (step tm.m))^[c+1] (some (Turing.initList tm s)) = + some (Turing.haltList tm t) + rw [hi,hf] + have hend : step tm.m (configured (none : Option (Node p)) (singletonStore output t)) = + some (⟨none,none,singletonStore output t⟩ : Config K (Option (Node p))) := rfl + rw [Nat.add_comm c 1] + exact iterate_comp (step tm.m) _ _ _ c 1 hr (iterate_step _ _ _ hend) +end ExactQuantumFactoring.BitStackProgram + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackQuotation.lean b/lean/OAI/Computability/QuantumFactoring/BitStackQuotation.lean new file mode 100644 index 0000000000000000000000000000000000000000..17c607abefb69724d7d511295285f42cfb7fdd06 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackQuotation.lean @@ -0,0 +1,169 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackLists + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram + +/-- Prefix-free quoting for one Boolean word. Both constructor tags and payload +bits are literal stack symbols. It is used only by the classical generator. -/ +def quoteBits (xs : List Bool) : List Bool := + xs.flatMap (fun b=>[true,b]) ++ [false] +@[simp] lemma quoteBits_nil : quoteBits []=[false] := rfl +@[simp] lemma quoteBits_cons (b : Bool) (xs : List Bool) : + quoteBits (b::xs)=true::b::quoteBits xs := rfl +lemma quoteBits_length (xs : List Bool) : (quoteBits xs).length=2*xs.length+1 := by + induction xs with + | nil => rfl + | cons b xs ih => simp only [quoteBits_cons,List.length_cons,ih]; omega + +def pairBits (xs ys : List Bool) : List Bool := quoteBits xs++ys +lemma pairBits_length (xs ys : List Bool) : + (pairBits xs ys).length=2*xs.length+ys.length+1 := by + simp only [pairBits,List.length_append,quoteBits_length]; omega + +variable {K : Type} [DecidableEq K] +def quoteLoop (a t : K) : Program K := + .loop a (.seq (.push t true) (.push t false)) (.seq (.push t true) (.push t true)) +def quoteMove (a b t : K) : Program K := + .seq (quoteLoop a t) (.seq (.push t false) (reverseMove t b)) + +lemma quoteLoop_runs (a t : K) (hat : a≠t) (s : Store K) : + Runs (quoteLoop a t) s + (Function.update (Function.update s a []) t + (((s a).flatMap (fun b=>[true,b])).reverse++s t)) (3*(s a).length+1) := by + generalize hs : s a=xs at * + induction xs generalizing s with + | nil => + have h : Function.update (Function.update s a []) t + (([].flatMap (fun b=>[true,b])).reverse++s t)=s := by + simp only [List.flatMap_nil,List.reverse_nil,List.nil_append] + rw [←hs,Function.update_eq_self,Function.update_eq_self] + rw [h] + exact Runs.loop_nil hs + | cons x xs ih => + let u := Function.update s a xs + let v := Function.update u t (x::true::u t) + have hva : v a=xs := by simp [v,u,hat] + have hb : Runs (.seq (.push t true) (.push t x)) u v 2 := by + have hh := Runs.seq (Runs.push u t true) + (Runs.push (Function.update u t (true::u t)) t x) + simpa only [Function.update_self,Function.update_idem] using hh + have hh : Runs (quoteLoop a t) s + (Function.update (Function.update v a []) t + ((xs.flatMap (fun b=>[true,b])).reverse++v t)) (3*xs.length+1+2+1) := by + cases x + · exact Runs.loop_false (a:=2) (b:=3*xs.length+1) hs hb (ih v hva) + · exact Runs.loop_true (a:=2) (b:=3*xs.length+1) hs hb (ih v hva) + convert hh using 1 + · funext k + by_cases ha : k=a <;> by_cases ht : k=t <;> + simp_all [v,u,Function.update,List.reverse_cons,List.append_assoc] + +lemma quoteMove_runs (a b t : K) (hab : a≠b) (hat : a≠t) (hbt : b≠t) + (s : Store K) (ht : s t=[]) : + Runs (quoteMove a b t) s + (Function.update (Function.update s a []) b (quoteBits (s a)++s b)) + (7*(s a).length+5) := by + let u := Function.update (Function.update s a []) t + (((s a).flatMap (fun b=>[true,b])).reverse++s t) + let v := Function.update u t (false::u t) + have hh := Runs.seq (quoteLoop_runs a t hat s) + (Runs.seq (Runs.push u t false) (reverseMove_runs t b hbt.symm v)) + change Runs (.seq _ _) _ _ _ + convert hh using 1 + · funext k + by_cases ha : k=a <;> by_cases hb : k=b <;> by_cases ht' : k=t <;> + simp_all [u,v,Function.update,quoteBits,Ne.symm hat,Ne.symm hab,Ne.symm hbt] + · simp only [v,Function.update_self,u,Function.update_self,ht,List.append_nil, + List.length_cons,List.length_reverse] + have hl : ((s a).flatMap (fun b=>[true,b])).length=2*(s a).length := by + have h:=quoteBits_length (s a) + simp only [quoteBits,List.length_append,List.length_cons,List.length_nil] at h + omega + rw [hl]; omega + +def unquoteBody (a t c : K) : Program K := + .cases a .skip .skip + (.cases a .skip (.seq (.push t false) (.push c true)) + (.seq (.push t true) (.push c true))) +def unquoteLoop (a t c : K) : Program K := + .loop c (unquoteBody a t c) (unquoteBody a t c) +def unquoteMove (a b t c : K) : Program K := + .seq (.push c true) (.seq (unquoteLoop a t c) (reverseMove t b)) + +lemma unquoteLoop_runs (a t c : K) (hat : a≠t) (hac : a≠c) (htc : t≠c) + (xs ys : List Bool) (s : Store K) (ha : s a=quoteBits xs++ys) (hc : s c=[true]) : + Runs (unquoteLoop a t c) s + (Function.update (Function.update (Function.update s a ys) c []) t (xs.reverse++s t)) + (5*xs.length+4) := by + induction xs generalizing s with + | nil => + let u := Function.update s c [] + let v := Function.update u a ys + have hua : u a=false::ys := by simp [u,hac,ha] + have hvc : v c=[] := by simp [v,u,hac.symm] + have hb : Runs (unquoteBody a t c) u v 2 := Runs.cases_false hua (Runs.skip v) + have hh := Runs.loop_true (p:=unquoteBody a t c) hc hb (Runs.loop_nil hvc) + change Runs (.loop _ _ _) _ _ _ + convert hh using 1 + · funext k + by_cases ha' : k=a <;> by_cases hc' : k=c <;> by_cases ht' : k=t <;> + simp_all [v,u,Function.update,Ne.symm hat,Ne.symm hac,Ne.symm htc] + | cons x xs ih => + let u := Function.update s c [] + let v := Function.update u a (x::quoteBits xs++ys) + let w := Function.update v a (quoteBits xs++ys) + let z := Function.update (Function.update w t (x::w t)) c [true] + have hua : u a=true::x::quoteBits xs++ys := by simp [u,hac,ha] + have hva : v a=x::quoteBits xs++ys := by simp [v] + have hzc : z c=[true] := by simp [z] + have hza : z a=quoteBits xs++ys := by simp [z,w,v,hat,hac] + have hb : Runs (unquoteBody a t c) u z 4 := by + apply Runs.cases_true hua + have hh := Runs.seq (Runs.push w t x) + (Runs.push (Function.update w t (x::w t)) c true) + have hc0 : Function.update w t (x::w t) c=[] := by simp [w,v,u,htc.symm,hac.symm] + rw [hc0] at hh + cases x + · exact Runs.cases_false hva hh + · exact Runs.cases_true hva hh + have hh := Runs.loop_true hc hb (ih z hza hzc) + change Runs (.loop _ _ _) _ _ _ + convert hh using 1 + · funext k + by_cases ha' : k=a <;> by_cases hc' : k=c <;> by_cases ht' : k=t <;> + simp_all [z,w,v,u,Function.update,Ne.symm hat,Ne.symm hac,Ne.symm htc, + List.reverse_cons,List.append_assoc] + +lemma unquoteMove_runs (a b t c : K) (hab : a≠b) (hat : a≠t) (hac : a≠c) + (hbt : b≠t) (hbc : b≠c) (htc : t≠c) + (xs ys : List Bool) (s : Store K) (ha : s a=quoteBits xs++ys) + (ht : s t=[]) (hc : s c=[]) : + Runs (unquoteMove a b t c) s + (Function.update (Function.update s a ys) b (xs++s b)) (7*xs.length+6) := by + let u := Function.update s c [true] + let v := Function.update (Function.update (Function.update u a ys) c []) t (xs.reverse++u t) + have hua : u a=quoteBits xs++ys := by simp [u,hac,ha] + have huc : u c=[true] := by simp [u] + have hp : Runs (.push c true) s u 1 := by simpa only [hc] using Runs.push s c true + have hh := Runs.seq hp (Runs.seq (unquoteLoop_runs a t c hat hac htc xs ys u hua huc) + (reverseMove_runs t b hbt.symm v)) + change Runs (.seq _ _) _ _ _ + convert hh using 1 + · funext k + by_cases ha' : k=a <;> by_cases hb' : k=b <;> by_cases ht' : k=t <;> by_cases hc' : k=c <;> + simp_all [v,u,Function.update,Ne.symm hab,Ne.symm hat,Ne.symm hac,Ne.symm hbt, + Ne.symm hbc,Ne.symm htc] + · simp only [v,Function.update_self,u,Function.update_of_ne htc,ht,List.append_nil, + List.length_reverse]; omega +end ExactQuantumFactoring.BitStackProgram + +end + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackRationalDivision.lean b/lean/OAI/Computability/QuantumFactoring/BitStackRationalDivision.lean new file mode 100644 index 0000000000000000000000000000000000000000..7e454ea4503acfb64d62e779531a1f06cf2b9900 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackRationalDivision.lean @@ -0,0 +1,38 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackRationals + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram +namespace Procedure +noncomputable def ratInv : Procedure ratCode ratCode (fun q=>q⁻¹):=by + let num:=signedInt.comp ((intSign.comp ratNum).pair ratDen) + let den:=intAbs.comp ratNum + exact (makeRat.comp (num.pair den)).congrFun (by + intro q + change mkRat (intOfSign (decide (q.num<0),q.den)) q.num.natAbs=q⁻¹ + rw [Rat.mkRat_eq_div] + by_cases h:q.num<0 + · have hz:=Int.eq_neg_natAbs_of_nonpos h.le + simp only [h,decide_true,intOfSign,ite_true,Int.cast_neg,Int.cast_natCast] + conv_rhs=>rw [←Rat.num_div_den q,hz] + simp only [Int.cast_neg,Int.cast_natCast,neg_div,inv_neg,inv_div] + · have hz:=Int.natAbs_of_nonneg (le_of_not_gt h) + simp only [h,decide_false,intOfSign,Bool.false_eq_true,ite_false,Int.cast_natCast] + conv_rhs=>rw [←Rat.num_div_den q,←hz] + simp only [inv_div,Int.cast_natCast]) +noncomputable def ratDiv : Procedure (prodCode ratCode ratCode) ratCode (fun x=>x.1/x.2):= + (ratMul.comp ((first ratCode ratCode).pair (ratInv.comp (second ratCode ratCode)))).congrFun + (by intro x;exact (div_eq_mul_inv _ _).symm) +end Procedure +end ExactQuantumFactoring.BitStackProgram + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackRationalFloor.lean b/lean/OAI/Computability/QuantumFactoring/BitStackRationalFloor.lean new file mode 100644 index 0000000000000000000000000000000000000000..b4812b963d2ad435db3ef020fa811e93f8d933ac --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackRationalFloor.lean @@ -0,0 +1,41 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackRationals + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram.Procedure +noncomputable def ratFloor : Procedure ratCode intCode (fun q=>⌊q⌋):=by + let num:=ratNum + let den:=ratDen + let mag:=intAbs.comp num + let negmag:=binaryAdd.comp ((binaryDiv.comp + ((binarySub.comp (mag.pair (constant ratCode Nat.bits 1))).pair den)).pair + (constant ratCode Nat.bits 1)) + let pos:=natToInt.comp (binaryDiv.comp (mag.pair den)) + let neg:=intNeg.comp (natToInt.comp negmag) + exact (conditional (intSign.comp num) neg pos).congrFun (by + intro q + change (if decide (q.num<0) then -((((q.num.natAbs-1)/q.den+1):ℕ):ℤ) + else ((q.num.natAbs/q.den):ℤ))=⌊q⌋ + rw [Rat.floor_def'] + obtain ⟨d,hd⟩:=Nat.exists_eq_succ_of_ne_zero q.den_nz + rw [hd] + cases q.num with + | ofNat a=>simp + | negSucc a=> + simp only [Int.negSucc_lt_zero, decide_true, ite_true, Int.natAbs_negSucc, + Int.negSucc_ediv_ofNat_succ] + change -((((a+1-1)/(d+1)+1):ℕ):ℤ)=Int.negSucc (a/(d+1)) + simp only [Nat.add_sub_cancel] + rfl) +end ExactQuantumFactoring.BitStackProgram.Procedure + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackRationalPower.lean b/lean/OAI/Computability/QuantumFactoring/BitStackRationalPower.lean new file mode 100644 index 0000000000000000000000000000000000000000..01084fc5dd4c07f1ce21b8c102f0c296c7ac7837 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackRationalPower.lean @@ -0,0 +1,47 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackRationals +import OAI.Computability.QuantumFactoring.BitStackOptions +import OAI.Computability.QuantumFactoring.BitStackPowers + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram +lemma intOfSign_pow (z : ℤ) (k : ℕ) : + intOfSign (decide (z<0) && decide (k%2=1),z.natAbs^k)=z^k:=by + by_cases hz:z<0 + · have he:=Int.eq_neg_natAbs_of_nonpos hz.le + conv_rhs=>rw [he,neg_pow,neg_one_pow_eq_pow_mod_two] + have hk:=Nat.mod_lt k (by omega : 0<2) + have hp:k%2=0 ∨ k%2=1:=by omega + rcases hp with h|h <;> simp [intOfSign,hz,h] + · have he:=Int.natAbs_of_nonneg (le_of_not_gt hz) + simp only [hz,decide_false,Bool.false_and,intOfSign,Bool.false_eq_true,ite_false,Int.natCast_pow,he] +namespace Procedure +noncomputable def intPow : Procedure (prodCode unaryCode intCode) intCode (fun x=>x.2^x.1):=by + let k:=first unaryCode intCode + let z:=second unaryCode intCode + let odd:=binaryEq.comp ((binaryMod.comp ((unaryToBits.comp k).pair + (constant _ Nat.bits 2))).pair (constant _ Nat.bits 1)) + let s:=boolAnd.comp ((intSign.comp z).pair odd) + let a:=binaryPow.comp (k.pair (intAbs.comp z)) + exact (signedInt.comp (s.pair a)).congrFun (by intro x;exact intOfSign_pow x.2 x.1) +noncomputable def ratPow : Procedure (prodCode unaryCode ratCode) ratCode (fun x=>x.2^x.1):=by + let k:=first unaryCode ratCode + let q:=second unaryCode ratCode + let num:=intPow.comp (k.pair (ratNum.comp q)) + let den:=binaryPow.comp (k.pair (ratDen.comp q)) + exact (makeRat.comp (num.pair den)).congrFun (by + intro x + change mkRat (x.2.num^x.1) (x.2.den^x.1)=x.2^x.1 + rw [Rat.mkRat_eq_div,Int.cast_pow,Nat.cast_pow,←div_pow,Rat.num_div_den]) +end Procedure +end ExactQuantumFactoring.BitStackProgram + +end + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackRationals.lean b/lean/OAI/Computability/QuantumFactoring/BitStackRationals.lean new file mode 100644 index 0000000000000000000000000000000000000000..a8c41f2eeeb77fb2dfa45f054a2bd0ffac1156c3 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackRationals.lean @@ -0,0 +1,112 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackIntegers +import OAI.Computability.QuantumFactoring.ProcedureFurther + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram + +def ratCode (q : ℚ) : List Bool := prodCode intCode Nat.bits (q.num,q.den) + +def ratData (x : ℤ×ℕ) : ℤ×ℕ := + if x.2=0 then (0,1) else + (intOfSign (decide (x.1<0),x.1.natAbs/(x.2.gcd x.1.natAbs)), + x.2/(x.2.gcd x.1.natAbs)) + +lemma intOfSign_div (z : ℤ) (d : ℕ) (hd : d∣z.natAbs) : + intOfSign (decide (z<0),z.natAbs/d)=z/(d : ℤ) := by + by_cases h : z<0 + · have hz := Int.eq_neg_natAbs_of_nonpos (le_of_lt h) + have hdiv : (d : ℤ) ∣ (z.natAbs : ℤ) := Int.ofNat_dvd.mpr hd + simp only [h,decide_true,intOfSign,ite_true] + conv_rhs => rw [hz,Int.neg_ediv_of_dvd hdiv] + rw [Int.natCast_ediv] + · simp only [h,decide_false,intOfSign,Bool.false_eq_true,ite_false] + conv_rhs => rw [←Int.natAbs_of_nonneg (le_of_not_gt h)] + rw [Int.natCast_ediv] + +lemma ratData_spec (x : ℤ×ℕ) : ratData x=((mkRat x.1 x.2).num,(mkRat x.1 x.2).den) := by + rw [Rat.num_mkRat,Rat.den_mkRat] + unfold ratData + split + · rfl + · rw [intOfSign_div _ _ (Nat.gcd_dvd_right _ _)] + +namespace Procedure +noncomputable def ratNum : Procedure ratCode intCode Rat.num := + (first intCode Nat.bits).precompose (fun q : ℚ=>(q.num,q.den)) +noncomputable def ratDen : Procedure ratCode Nat.bits Rat.den := + (second intCode Nat.bits).precompose (fun q : ℚ=>(q.num,q.den)) + +noncomputable def makeRat : Procedure (prodCode intCode Nat.bits) ratCode + (fun x=>mkRat x.1 x.2) := by + let n:=first intCode Nat.bits + let d:=second intCode Nat.bits + let a:=intAbs.comp n + let g:=binaryGcd.comp (d.pair a) + let num:=signedInt.comp ((intSign.comp n).pair (binaryDiv.comp (a.pair g))) + let den:=binaryDiv.comp (d.pair g) + let zero:=constant (prodCode intCode Nat.bits) (prodCode intCode Nat.bits) (0,1) + let p:=conditional (binaryZero.comp d) zero (num.pair den) + exact p.result (by + intro x + simp only [Function.comp_apply,decide_eq_true_eq] + change prodCode intCode Nat.bits (ratData x)=ratCode (mkRat x.1 x.2) + rw [ratData_spec];rfl) + +noncomputable def intToRat : Procedure intCode ratCode (fun z=>(z : ℚ)) := + (makeRat.comp ((identity intCode).pair (constant intCode Nat.bits 1))).congrFun (by + intro z; simp [Rat.mkRat_eq_div]) +noncomputable def natToRat : Procedure Nat.bits ratCode (fun n=>(n : ℚ)) := + (intToRat.comp natToInt).congrFun (by intro n;simp) + +noncomputable def ratNeg : Procedure ratCode ratCode Neg.neg := + (makeRat.comp ((intNeg.comp ratNum).pair ratDen)).congrFun (by + intro q + change mkRat (-q.num) q.den = -q + rw [Rat.mkRat_eq_div,Int.cast_neg,neg_div,Rat.num_div_den]) + +noncomputable def ratAdd : Procedure (prodCode ratCode ratCode) ratCode + (fun x=>x.1+x.2) := by + let a:=first ratCode ratCode + let b:=second ratCode ratCode + let an:=ratNum.comp a + let bn:=ratNum.comp b + let ad:=ratDen.comp a + let bd:=ratDen.comp b + let num:=intAdd.comp ((intMul.comp (an.pair (natToInt.comp bd))).pair + (intMul.comp (bn.pair (natToInt.comp ad)))) + let den:=binaryMul.comp (ad.pair bd) + exact (makeRat.comp (num.pair den)).congrFun (by + intro x + change mkRat (x.1.num * (x.2.den : ℤ) + x.2.num * (x.1.den : ℤ)) + (x.1.den*x.2.den) = x.1+x.2 + rw [←Rat.mkRat_add_mkRat _ _ x.1.den_nz x.2.den_nz] + simp) + +noncomputable def ratMul : Procedure (prodCode ratCode ratCode) ratCode + (fun x=>x.1*x.2) := by + let a:=first ratCode ratCode + let b:=second ratCode ratCode + let num:=intMul.comp ((ratNum.comp a).pair (ratNum.comp b)) + let den:=binaryMul.comp ((ratDen.comp a).pair (ratDen.comp b)) + exact (makeRat.comp (num.pair den)).congrFun (by + intro x + change mkRat (x.1.num*x.2.num) (x.1.den*x.2.den)=x.1*x.2 + rw [←Rat.mkRat_mul_mkRat];simp) + +noncomputable def ratSub : Procedure (prodCode ratCode ratCode) ratCode + (fun x=>x.1-x.2) := + (ratAdd.comp ((first ratCode ratCode).pair (ratNeg.comp (second ratCode ratCode)))).congrFun + (by intro x;exact (sub_eq_add_neg _ _).symm) +end Procedure +end ExactQuantumFactoring.BitStackProgram + +end + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackRelabel.lean b/lean/OAI/Computability/QuantumFactoring/BitStackRelabel.lean new file mode 100644 index 0000000000000000000000000000000000000000..6ce2749662b5ac127fc6336d2027327f81e7e347 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackRelabel.lean @@ -0,0 +1,95 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackPrograms + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram + +variable {K L : Type} +def Program.relabel (f : K → L) : Program K → Program L + | .skip => .skip + | .push k b => .push (f k) b + | .seq p q => .seq (p.relabel f) (q.relabel f) + | .cases k p q r => .cases (f k) (p.relabel f) (q.relabel f) (r.relabel f) + | .loop k p q => .loop (f k) (p.relabel f) (q.relabel f) + +/-- An extension of a small register store with arbitrary untouched registers. -/ +noncomputable def overlay (f : K ↪ L) (base : Store L) (s : Store K) : Store L := by + classical + exact fun j => if h : ∃ i, f i=j then s (Classical.choose h) else base j + +lemma overlay_at (f : K ↪ L) (base : Store L) (s : Store K) (i : K) : + overlay f base s (f i)=s i := by + classical + unfold overlay + rw [dite_eq_left ⟨i,rfl⟩] + congr 1 + apply f.injective + exact Classical.choose_spec (show ∃ k, f k=f i from ⟨i,rfl⟩) + +lemma overlay_outside (f : K ↪ L) (base : Store L) (s : Store K) (j : L) + (h : ∀ i, f i≠j) : overlay f base s j=base j := by + classical + unfold overlay + exact dite_eq_right (by simpa only [not_exists] using h) + +variable [DecidableEq K] [DecidableEq L] + +lemma overlay_update (f : K ↪ L) (base : Store L) (s : Store K) (k : K) (xs : List Bool) : + overlay f base (Function.update s k xs)=Function.update (overlay f base s) (f k) xs := by + funext j + by_cases hj : ∃ i,f i=j + · rcases hj with ⟨i,rfl⟩ + rw [overlay_at] + by_cases h : i=k + · subst i; simp + · have hf : f i≠f k := fun h' => h (f.injective h') + simp only [Function.update_of_ne h,Function.update_of_ne hf,overlay_at] + · have h : ∀ i,f i≠j := by simpa only [not_exists] using hj + rw [overlay_outside f base _ j h,Function.update_of_ne (Ne.symm (h k)), + overlay_outside f base s j h] + +omit [DecidableEq K] [DecidableEq L] in +lemma overlay_self (f : K ↪ L) (s : Store L) : overlay f s (s ∘ f)=s := by + funext j + by_cases h : ∃ i,f i=j + · rcases h with ⟨i,rfl⟩ + exact overlay_at f s (s ∘ f) i + · exact overlay_outside f s (s ∘ f) j (by simpa only [not_exists] using h) + +/-- Exact-cost subroutine embedding. Scratch separation is proved, not assumed +as an extra TM operation. -/ +lemma Runs.relabel {p : Program K} {s t : Store K} {c : ℕ} + (h : Runs p s t c) (f : K ↪ L) (base : Store L) : + Runs (p.relabel f) (overlay f base s) (overlay f base t) c := by + induction h with + | skip s => exact Runs.skip _ + | push s k b => + rw [overlay_update] + simpa only [overlay_at, Program.relabel] using Runs.push (overlay f base s) (f k) b + | seq hp hq ip iq => exact Runs.seq ip iq + | @cases_nil k p q r s t a hs hr ih => + exact Runs.cases_nil (by rw [overlay_at,hs]) ih + | @cases_false k p q r s t xs a hs hr ih => + rw [overlay_update] at ih + exact Runs.cases_false (by rw [overlay_at,hs]) ih + | @cases_true k p q r s t xs a hs hr ih => + rw [overlay_update] at ih + exact Runs.cases_true (by rw [overlay_at,hs]) ih + | @loop_nil k p q s hs => exact Runs.loop_nil (by rw [overlay_at,hs]) + | @loop_false k p q s t u xs a b hs hp hq ip iq => + rw [overlay_update] at ip + exact Runs.loop_false (by rw [overlay_at,hs]) ip iq + | @loop_true k p q s t u xs a b hs hp hq ip iq => + rw [overlay_update] at ip + exact Runs.loop_true (by rw [overlay_at,hs]) ip iq +end ExactQuantumFactoring.BitStackProgram + +end + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackSubtractor.lean b/lean/OAI/Computability/QuantumFactoring/BitStackSubtractor.lean new file mode 100644 index 0000000000000000000000000000000000000000..d4d1283d6e0c6da901520ecfcfcc132200eda094 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackSubtractor.lean @@ -0,0 +1,118 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackAdder + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram + +def borrowBit (a b c : Bool) : Bool := (!a && b) || (!a && c) || (b && c) + +lemma difference_borrow (a b c : Bool) : + (a.toNat : ℤ)-b.toNat-c.toNat=(sumBit a b c).toNat-2*(borrowBit a b c).toNat := by + cases a <;> cases b <;> cases c <;> decide + +lemma binaryValue_lt (xs : List Bool) : binaryValue xs<2^xs.length := by + induction xs with + | nil=>simp [binaryValue] + | cons b bs ih=> + simp only [List.length_cons,binaryValue,pow_succ] + cases b <;> simp only [Bool.toNat_false,Bool.toNat_true] <;> omega + +abbrev SubState := AddState +abbrev subStateCode := addStateCode + +def subStep (s : SubState) : SubState := + (s.1.tail,s.2.1.tail, + borrowBit (s.1.headD false) (s.2.1.headD false) s.2.2.1, + sumBit (s.1.headD false) (s.2.1.headD false) s.2.2.1 :: s.2.2.2) + +def subInvariant (s : SubState) : ℤ := + (binaryValue s.2.2.2.reverse : ℤ)+2^s.2.2.2.length* + ((binaryValue s.1 : ℤ)-binaryValue s.2.1-s.2.2.1.toNat) + +lemma subInvariant_step (s : SubState) : subInvariant (subStep s)=subInvariant s := by + have hx:=binaryValue_head_tail s.1 + have hy:=binaryValue_head_tail s.2.1 + have hh:=difference_borrow (s.1.headD false) (s.2.1.headD false) s.2.2.1 + simp only [subInvariant,subStep,List.reverse_cons,binaryValue_append,List.length_reverse, + binaryValue,List.length_cons,pow_succ] + push_cast + have hx' : (binaryValue s.1 : ℤ)=(s.1.headD false).toNat+2*binaryValue s.1.tail:=by + exact_mod_cast hx + have hy' : (binaryValue s.2.1 : ℤ)=(s.2.1.headD false).toNat+2*binaryValue s.2.1.tail:=by + exact_mod_cast hy + rw [hx',hy'] + nlinarith [congrArg (fun n : ℤ=>2^s.2.2.2.length*n) hh] + +lemma subInvariant_iterate (i : ℕ) (s : SubState) : + subInvariant (subStep^[i] s)=subInvariant s := by + induction i with + | zero=>rfl + | succ i ih=>rw [Function.iterate_succ_apply',subInvariant_step,ih] + +lemma subStep_tapes (i : ℕ) (s : SubState) : + (subStep^[i] s).1=s.1.drop i ∧ (subStep^[i] s).2.1=s.2.1.drop i := by + induction i with + | zero=>simp + | succ i ih=> + rw [Function.iterate_succ_apply'] + simp only [subStep,ih.1,ih.2,List.tail_drop] + trivial + +def wordSubtract (x : List Bool×List Bool) : Bool×List Bool := + let s:=subStep^[x.1.length+x.2.length+1] (x.1,x.2,false,[]) + (s.2.2.1,s.2.2.2.reverse) + +lemma wordSubtract_spec (x : List Bool×List Bool) : + (binaryValue (wordSubtract x).2 : ℤ) - + 2^(wordSubtract x).2.length*((wordSubtract x).1.toNat : ℤ)= + (binaryValue x.1 : ℤ)-binaryValue x.2 := by + let s : SubState:=(x.1,x.2,false,[]) + let i:=x.1.length+x.2.length+1 + have hx : (subStep^[i] s).1=[]:=by + rw [(subStep_tapes i s).1] + exact List.drop_eq_nil_iff.mpr (by dsimp [s,i];omega) + have hy : (subStep^[i] s).2.1=[]:=by + rw [(subStep_tapes i s).2] + exact List.drop_eq_nil_iff.mpr (by dsimp [s,i];omega) + have hh:=subInvariant_iterate i s + simp only [subInvariant,hx,hy,binaryValue,Int.natCast_zero,zero_sub] at hh + simpa [wordSubtract,s,i,List.length_reverse,subInvariant,binaryValue,sub_eq_add_neg] using hh + +lemma wordSubtract_borrow (x : List Bool×List Bool) : + (wordSubtract x).1=decide (binaryValue x.1 simp only [hb,Bool.toNat_false,Bool.toNat_true, + Int.natCast_zero,Int.natCast_one,mul_zero,mul_one,sub_zero] at hh + · symm;apply decide_eq_false;omega + · symm;apply decide_eq_true;omega + +lemma wordSubtract_value (x : List Bool×List Bool) : + (if (wordSubtract x).1 then 0 else binaryValue (wordSubtract x).2)= + binaryValue x.1-binaryValue x.2 := by + have hh:=wordSubtract_spec x + have hb:=wordSubtract_borrow x + cases hc : (wordSubtract x).1 + · simp only [hc,Bool.false_eq_true,ite_false,Bool.toNat_false,Int.natCast_zero,mul_zero,sub_zero] at * + omega + · simp only [hc,ite_true,true_eq_decide_iff] at * + omega + +lemma subStep_size (s : SubState) : + (subStateCode (subStep s)).length≤(subStateCode s).length+1 := by + simp only [subStateCode,addStateCode,subStep,prodCode,pairBits_length,id_eq,Procedure.boolCode, + List.length_cons,List.length_tail] + omega + + +end ExactQuantumFactoring.BitStackProgram +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackSumInjection.lean b/lean/OAI/Computability/QuantumFactoring/BitStackSumInjection.lean new file mode 100644 index 0000000000000000000000000000000000000000..646f8ee29b3f768a1e2519a9177efae66bd9d60d --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackSumInjection.lean @@ -0,0 +1,23 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackSums +import OAI.Computability.QuantumFactoring.BitStackWords + +namespace OAI + + + +section +namespace ExactQuantumFactoring.BitStackProgram.Procedure +noncomputable def sumLeft {α β : Type} (ea : α→List Bool) (eb : β→List Bool) : + Procedure ea (sumCode ea eb) Sum.inl:= + (prepend ea [false]).result (by intro a;rfl) +noncomputable def sumRight {α β : Type} (ea : α→List Bool) (eb : β→List Bool) : + Procedure eb (sumCode ea eb) Sum.inr:= + (prepend eb [true]).result (by intro a;rfl) +end ExactQuantumFactoring.BitStackProgram.Procedure + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackSums.lean b/lean/OAI/Computability/QuantumFactoring/BitStackSums.lean new file mode 100644 index 0000000000000000000000000000000000000000..99e868ed4ccde05cfe8e12fadf43ea7db9af5d74 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackSums.lean @@ -0,0 +1,73 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackChoice + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram + +def sumCode {α β : Type} (ea : α→List Bool) (eb : β→List Bool) : α⊕β→List Bool + | .inl a=>false::ea a + | .inr b=>true::eb b + +namespace Procedure +variable {α β γ : Type} {ea : α→List Bool} {eb : β→List Bool} {ec : γ→List Bool} + {f : α→γ} {g : β→γ} +noncomputable def casesSum (p : Procedure ea ec f) (q : Procedure eb ec g) : + Procedure (sumCode ea eb) ec (Sum.elim f g) where + K:=(p.K ⊕ q.K) ⊕ Fin 2 + finiteK:=inferInstance + decideK:=inferInstance + input:=Sum.inr 0 + output:=Sum.inr 0 + program:=.cases (Sum.inr 0) .skip + (p.shared.program.relabel (leftPublic p.K q.K)) + (q.shared.program.relabel (rightPublic p.K q.K)) + bound:=p.shared.bound+q.shared.bound+1 + runs x:=by + cases x with + | inl a=> + have hpmono:=eval_nat_mono p.shared.bound (Nat.le_succ (ea a).length) + obtain ⟨c,hc,hd⟩:=p.shared.runs a + have hh:=hd.relabel (leftPublic p.K q.K) (fun _=>[]) + simp only [overlay_singleton] at hh + have he : leftPublic p.K q.K p.shared.input=Sum.inr 0:=rfl + rw [he] at hh + refine ⟨c+1,?_,?_⟩ + · rw [Polynomial.eval_add,Polynomial.eval_add,Polynomial.eval_one] + exact Nat.add_le_add_right ((hc.trans hpmono).trans (Nat.le_add_right _ _)) 1 + · have hu : Function.update (singletonStore (Sum.inr 0 : (p.K⊕q.K)⊕Fin 2) + (false::ea a)) (Sum.inr 0) (ea a)=singletonStore (Sum.inr 0) (ea a):=by + simp [singletonStore] + simpa only [hu,sumCode] using Runs.cases_false (p:=Program.skip) + (r:=q.shared.program.relabel (rightPublic p.K q.K)) + (xs:=ea a) (s:=singletonStore (Sum.inr 0) (false::ea a)) (by simp [singletonStore]) + (by rw [hu];exact hh) + | inr b=> + have hqmono:=eval_nat_mono q.shared.bound (Nat.le_succ (eb b).length) + obtain ⟨c,hc,hd⟩:=q.shared.runs b + have hh:=hd.relabel (rightPublic p.K q.K) (fun _=>[]) + simp only [overlay_singleton] at hh + have he : rightPublic p.K q.K q.shared.input=Sum.inr 0:=rfl + rw [he] at hh + refine ⟨c+1,?_,?_⟩ + · rw [Polynomial.eval_add,Polynomial.eval_add,Polynomial.eval_one] + exact Nat.add_le_add_right ((hc.trans hqmono).trans (Nat.le_add_left _ _)) 1 + · have hu : Function.update (singletonStore (Sum.inr 0 : (p.K⊕q.K)⊕Fin 2) + (true::eb b)) (Sum.inr 0) (eb b)=singletonStore (Sum.inr 0) (eb b):=by + simp [singletonStore] + simpa only [hu,sumCode] using Runs.cases_true (p:=Program.skip) + (q:=p.shared.program.relabel (leftPublic p.K q.K)) + (xs:=eb b) (s:=singletonStore (Sum.inr 0) (true::eb b)) (by simp [singletonStore]) + (by rw [hu];exact hh) +end Procedure +end ExactQuantumFactoring.BitStackProgram + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackTabulate.lean b/lean/OAI/Computability/QuantumFactoring/BitStackTabulate.lean new file mode 100644 index 0000000000000000000000000000000000000000..aabf4be379872310bee3fb545147899198f9b573 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackTabulate.lean @@ -0,0 +1,82 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackIteration +import OAI.Computability.QuantumFactoring.BitStackListOps +import OAI.Computability.QuantumFactoring.BitStackNaturals + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram +variable {α β : Type} +def tabStep (f : α→ℕ→β) (s : ℕ×(α×List β)) : ℕ×(α×List β) := + (s.1+1,s.2.1,f s.2.1 s.1::s.2.2) +def tabCode (ea : α→List Bool) (eb : β→List Bool) := prodCode unaryCode (prodCode ea (listCode eb)) +lemma tabStep_iterate (f : α→ℕ→β) (j i : ℕ) (a : α) (ys : List β) : + (tabStep f)^[j] (i,a,ys)=(i+j,a,((List.range' i j).map (f a)).reverse++ys) := by + induction j with + | zero=>simp + | succ j ih=> + rw [Function.iterate_succ_apply',ih] + simp only [tabStep,List.range'_1_concat,List.map_append,List.map_cons,List.map_nil, + List.reverse_append,List.reverse_cons,List.reverse_nil,List.nil_append,List.cons_append] + simp only [Nat.add_assoc] +namespace Procedure +variable {ea : α→List Bool} {eb : β→List Bool} {f : α→ℕ→β} +noncomputable def tabStepP (p : Procedure (prodCode unaryCode ea) eb (fun x=>f x.2 x.1)) : + Procedure (tabCode ea eb) (tabCode ea eb) (tabStep f) := by + let i:=first unaryCode (prodCode ea (listCode eb)) + let rest:=second unaryCode (prodCode ea (listCode eb)) + let a:=(first ea (listCode eb)).comp rest + let ys:=(second ea (listCode eb)).comp rest + exact ((unarySuccessor.comp i).pair + (a.pair ((listCons eb).comp ((p.comp (i.pair a)).pair ys)))).congrFun (by intro s;rfl) +noncomputable def tabulate (d : β) + (p : Procedure (prodCode unaryCode ea) eb (fun x=>f x.2 x.1)) : + Procedure (prodCode unaryCode ea) (listCode eb) + (fun x=>(List.range x.1).map (f x.2)) := by + let q:=(Polynomial.X+p.bound).comp (Polynomial.C 2*Polynomial.X+1) + have hval (a : α) (i : ℕ) : (eb (f a i)).length≤q.eval (i+(ea a).length) := by + have ho:=p.output_length_le (i,a) + have hm:=eval_nat_mono (Polynomial.X+p.bound) + (show (prodCode unaryCode ea (i,a)).length≤2*(i+(ea a).length)+1 by + simp only [prodCode,pairBits_length,unaryCode,List.length_replicate];omega) + simp only [Polynomial.eval_add,Polynomial.eval_X] at hm + simpa only [q,Polynomial.eval_comp,Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_C, + Polynomial.eval_X,Polynomial.eval_one] using ho.trans hm + let rep:=(tabStepP p).iterate (Polynomial.X*(Polynomial.C 2*q+Polynomial.C 5)) (by + rintro n ⟨i,a,ys⟩ j hj + rw [tabStep_iterate] + have len0 : (tabCode ea eb (i,a,ys)).length=2*i+2*(ea a).length+(listCode eb ys).length+2 := by + simp only [tabCode,prodCode,pairBits_length,unaryCode,List.length_replicate];omega + have hv : ∀ k∈List.range' i j,(eb (f a k)).length≤q.eval (n+(tabCode ea eb (i,a,ys)).length) := by + intro k hk + have hk':=List.mem_range'.mp hk + exact (hval a k).trans (eval_nat_mono q (by rw [len0];omega)) + have hmap:=listCode_length_map_bound eb (f a) (List.range' i j) _ hv + have happ:=listCode_length_append eb (((List.range' i j).map (f a)).reverse) ys + rw [listCode_length_rev] at happ + simp only [List.length_range'] at hmap + simp only [tabCode,prodCode,pairBits_length,unaryCode,List.length_replicate, + Polynomial.eval_mul,Polynomial.eval_add,Polynomial.eval_C,Polynomial.eval_X] at * + nlinarith) + let inputN:=first unaryCode ea + let inputA:=second unaryCode ea + let start:=(constant (prodCode unaryCode ea) unaryCode 0).pair + (inputA.pair (constant (prodCode unaryCode ea) (listCode eb) [])) + let result:=((second ea (listCode eb)).comp + (second unaryCode (prodCode ea (listCode eb)))).comp (rep.comp (inputN.pair start)) + exact ((listReverse eb d).comp result).congrFun (by + rintro ⟨n,a⟩ + change (((tabStep f)^[n] (0,a,[])).2.2).reverse=(List.range n).map (f a) + rw [tabStep_iterate,List.append_nil,List.reverse_reverse,List.range_eq_range']) +end Procedure +end ExactQuantumFactoring.BitStackProgram + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackTestBit.lean b/lean/OAI/Computability/QuantumFactoring/BitStackTestBit.lean new file mode 100644 index 0000000000000000000000000000000000000000..cc1f3438010f51a761444a164673801a77f91cba --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackTestBit.lean @@ -0,0 +1,48 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackChoice +import OAI.Computability.QuantumFactoring.BitStackNaturals +import OAI.Computability.QuantumFactoring.BitStackWords + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram +namespace Procedure +noncomputable def dropWord : Procedure (prodCode unaryCode (id : List Bool→List Bool)) id + (fun x=>x.2.drop x.1):=by + refine (tail.iterate Polynomial.X ?_).congrFun ?_ + · intro n xs i hi + have h : (List.tail^[i] xs).length≤xs.length:=by + induction i with + | zero=>rfl + | succ i ih=> + rw [Function.iterate_succ_apply'] + simp only [List.length_tail] + omega + simp only [Polynomial.eval_X,id_eq] + exact h.trans (Nat.le_add_left _ _) + · rintro ⟨n,xs⟩ + change List.tail^[n] xs=xs.drop n + induction n with + | zero=>rfl + | succ n ih=> rw [Function.iterate_succ_apply',ih,List.tail_drop] +noncomputable def testBit : Procedure (prodCode Nat.bits unaryCode) boolCode + (fun x=>x.1.testBit x.2):=by + let p:=head.comp (dropWord.comp + ((second Nat.bits unaryCode).pair ((identity (id : List Bool→List Bool)).precompose Nat.bits |>.comp + (first Nat.bits unaryCode)))) + refine p.congrFun ?_ + intro x + change (x.1.bits.drop x.2).headD false=x.1.testBit x.2 + rw [Nat.testBit_eq_inth,List.headD_eq_head?_getD,List.head?_drop] + rfl +end Procedure +end ExactQuantumFactoring.BitStackProgram + +end + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackUnary.lean b/lean/OAI/Computability/QuantumFactoring/BitStackUnary.lean new file mode 100644 index 0000000000000000000000000000000000000000..db75dac4c8bbd3a156ea511bce5ea97960557c31 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackUnary.lean @@ -0,0 +1,82 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackChoice +import OAI.Computability.QuantumFactoring.BitStackNaturals +import OAI.Computability.QuantumFactoring.BitStackWords + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram + +def addCounter (x : ℕ×ℕ) := (x.1,x.1+x.2) +lemma addCounter_iterate (i : ℕ) (x : ℕ×ℕ) : + addCounter^[i] x=(x.1,i*x.1+x.2) := by + induction i with + | zero=>simp + | succ i ih=> + rw [Function.iterate_succ_apply',ih] + simp only [addCounter,Prod.mk.injEq,true_and,Nat.succ_mul] + omega + +lemma pred_iterate_word (i n : ℕ) : (fun k=>k-1)^[i] n=n-i := by + induction i with + | zero=>simp + | succ i ih=> + rw [Function.iterate_succ_apply',ih,Nat.sub_sub] + +namespace Procedure +noncomputable def unaryAdd : Procedure (prodCode unaryCode unaryCode) unaryCode + (fun x=>x.1+x.2) := + (unarySuccessor.iterate Polynomial.X (by + intro n a i hi + simp only [Nat.succ_iterate,unaryCode,List.length_replicate,Polynomial.eval_X] + omega)).congrFun (by intro x;simp [Nat.succ_iterate,Nat.add_comm]) + +noncomputable def unaryMul : Procedure (prodCode unaryCode unaryCode) unaryCode + (fun x=>x.1*x.2) := by + let step : Procedure (prodCode unaryCode unaryCode) (prodCode unaryCode unaryCode) addCounter:= + ((first unaryCode unaryCode).pair unaryAdd).congrFun (by intro x;rfl) + let rep:=step.iterate (Polynomial.X^2+Polynomial.X) (by + intro n x i hi + rw [addCounter_iterate] + simp only [prodCode,pairBits_length,unaryCode,List.length_replicate, + Polynomial.eval_add,Polynomial.eval_pow,Polynomial.eval_X] + have hm : x.1≤n+(2*x.1+1+x.2):=by omega + have hii : i≤n+(2*x.1+1+x.2):=by omega + have hh:=Nat.mul_le_mul hii hm + nlinarith) + let fst:=first unaryCode unaryCode + let snd:=second unaryCode unaryCode + let start:=fst.pair (snd.pair (constant (prodCode unaryCode unaryCode) unaryCode 0)) + exact ((second unaryCode unaryCode).comp (rep.comp start)).congrFun (by + intro x + change (addCounter^[x.1] (x.2,0)).2=x.1*x.2 + simp [addCounter_iterate]) + +noncomputable def unaryPred : Procedure unaryCode unaryCode (fun n=>n-1) := + (tail.precompose unaryCode).result (by intro n;simp [unaryCode]) + +noncomputable def unarySub : Procedure (prodCode unaryCode unaryCode) unaryCode + (fun x=>x.1-x.2) := by + let p:=unaryPred.iterate Polynomial.X (by + intro n a i _ + simp only [pred_iterate_word,unaryCode,List.length_replicate,Polynomial.eval_X] + omega) + exact (p.comp (swap unaryCode unaryCode)).congrFun (by intro x;simp [pred_iterate_word]) + +noncomputable def unaryZero : Procedure unaryCode boolCode (fun n=>decide (n=0)) := + (isEmpty.precompose unaryCode).congrFun (by intro n;simp [unaryCode]) + +noncomputable def unaryLe : Procedure (prodCode unaryCode unaryCode) boolCode + (fun x=>decide (x.1≤x.2)) := + (unaryZero.comp unarySub).congrFun (by intro x;simp only [Function.comp_apply,decide_eq_decide];omega) +end Procedure +end ExactQuantumFactoring.BitStackProgram + +end + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BitStackWords.lean b/lean/OAI/Computability/QuantumFactoring/BitStackWords.lean new file mode 100644 index 0000000000000000000000000000000000000000..1f86742b143c376b39c82fee0d6fdce98aff13e9 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BitStackWords.lean @@ -0,0 +1,167 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackChoice + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram +namespace Procedure +variable {α : Type} +noncomputable def prepend (ea : α→List Bool) (xs : List Bool) : + Procedure ea (fun a=>xs++ea a) id where + K:=Unit + finiteK:=inferInstance + decideK:=inferInstance + input:=() + output:=() + program:=pushWord () xs + bound:=Polynomial.C (xs.length+1) + runs a:=by + refine ⟨xs.length+1,by simp,?_⟩ + simpa [singletonStore] using pushWord_runs () xs (singletonStore () (ea a)) + +noncomputable def reverse : Procedure (id : List Bool→List Bool) id List.reverse where + K:=Fin 2 + finiteK:=inferInstance + decideK:=inferInstance + input:=0 + output:=1 + program:=reverseMove 0 1 + bound:=Polynomial.C 2*Polynomial.X+1 + runs xs:=by + have hh:=reverseMove_runs (0 : Fin 2) 1 (by decide) (singletonStore 0 xs) + refine ⟨2*xs.length+1,by simp,?_⟩ + convert hh using 1 + · funext k;fin_cases k <;> simp [singletonStore,Function.update] + · simp [singletonStore] + · simp [singletonStore] + +noncomputable def tail : Procedure (id : List Bool→List Bool) id List.tail where + K:=Unit + finiteK:=inferInstance + decideK:=inferInstance + input:=() + output:=() + program:=.cases () .skip .skip .skip + bound:=Polynomial.C 2 + runs xs:=by + refine ⟨2,by simp,?_⟩ + cases xs with + | nil=>exact Runs.cases_nil (by simp [singletonStore]) (Runs.skip _) + | cons b bs=> + have hu : Function.update (singletonStore () (b::bs)) () bs=singletonStore () bs:=by + simp [singletonStore] + cases b + · exact hu ▸ Runs.cases_false (by simp [singletonStore]) (Runs.skip _) + · exact hu ▸ Runs.cases_true (by simp [singletonStore]) (Runs.skip _) + +noncomputable def isEmpty : Procedure (id : List Bool→List Bool) boolCode List.isEmpty where + K:=Unit + finiteK:=inferInstance + decideK:=inferInstance + input:=() + output:=() + program:=.cases () (.push () true) + (.seq (clear ()) (.push () false)) (.seq (clear ()) (.push () false)) + bound:=Polynomial.C 2*Polynomial.X+Polynomial.C 3 + runs xs:=by + cases xs with + | nil=> + refine ⟨2,by simp,?_⟩ + exact Runs.cases_nil (by simp [singletonStore]) (by + simpa [singletonStore,boolCode] using Runs.push (singletonStore () []) () true) + | cons b bs=> + let s:=singletonStore () bs + let u:=Function.update s () [] + have hc:=clear_runs () s + have hp:=Runs.push u () false + have hh:=Runs.seq hc hp + have hu : Function.update (singletonStore () (b::bs)) () bs=s:=by simp [s,singletonStore] + have hv : Function.update u () (false::u ())=singletonStore () [false]:=by + funext k;cases k;simp [u,s,singletonStore] + rw [hv] at hh + have ht : 1+(2*(s ()).length+1)=2*bs.length+2:=by simp [s,singletonStore];omega + rw [ht] at hh + refine ⟨2*bs.length+3,by simp,?_⟩ + cases b + · exact Runs.cases_false (xs:=bs) (by simp [singletonStore]) (by simpa only [id_eq,hu,boolCode,List.isEmpty_cons,List.headD_cons] using hh) + · exact Runs.cases_true (xs:=bs) (by simp [singletonStore]) (by simpa only [id_eq,hu,boolCode,List.isEmpty_cons,List.headD_cons] using hh) + +noncomputable def head : Procedure (id : List Bool→List Bool) boolCode (fun xs=>xs.headD false) where + K:=Unit + finiteK:=inferInstance + decideK:=inferInstance + input:=() + output:=() + program:=.cases () (.push () false) + (.seq (clear ()) (.push () false)) (.seq (clear ()) (.push () true)) + bound:=Polynomial.C 2*Polynomial.X+Polynomial.C 3 + runs xs:=by + cases xs with + | nil=> + refine ⟨2,by simp,?_⟩ + exact Runs.cases_nil (by simp [singletonStore]) (by + simpa [singletonStore,boolCode] using Runs.push (singletonStore () []) () false) + | cons b bs=> + let s:=singletonStore () bs + let u:=Function.update s () [] + have hc:=clear_runs () s + have hp:=Runs.push u () b + have hh:=Runs.seq hc hp + have hu : Function.update (singletonStore () (b::bs)) () bs=s:=by simp [s,singletonStore] + have hv : Function.update u () (b::u ())=singletonStore () [b]:=by + funext k;cases k;simp [u,s,singletonStore] + rw [hv] at hh + have ht : 1+(2*(s ()).length+1)=2*bs.length+2:=by simp [s,singletonStore];omega + rw [ht] at hh + refine ⟨2*bs.length+3,by simp,?_⟩ + cases b + · exact Runs.cases_false (xs:=bs) (by simp [singletonStore]) (by simpa only [id_eq,hu,boolCode,List.isEmpty_cons,List.headD_cons] using hh) + · exact Runs.cases_true (xs:=bs) (by simp [singletonStore]) (by simpa only [id_eq,hu,boolCode,List.isEmpty_cons,List.headD_cons] using hh) + +noncomputable def append : Procedure (prodCode (id : List Bool→List Bool) id) id + (fun x=>x.1++x.2) where + K:=Fin 4 + finiteK:=inferInstance + decideK:=inferInstance + input:=0 + output:=0 + program:=.seq (unquoteMove 0 1 2 3) (.seq (reverseMove 1 2) (reverseMove 2 0)) + bound:=Polynomial.C 11*Polynomial.X+Polynomial.C 8 + runs x:=by + let s : Store (Fin 4):=singletonStore 0 (prodCode id id x) + let u : Store (Fin 4):=Function.update (singletonStore 0 x.2) 1 x.1 + let v : Store (Fin 4):=Function.update (singletonStore 0 x.2) 2 x.1.reverse + have h1 : Runs (unquoteMove 0 1 2 3) s u (7*x.1.length+6):=by + have hh:=unquoteMove_runs (0 : Fin 4) 1 2 3 (by decide) (by decide) (by decide) + (by decide) (by decide) (by decide) x.1 x.2 s + (by simp [s,singletonStore,prodCode,pairBits]) + (by simp [s,singletonStore]) (by simp [s,singletonStore]) + convert hh using 1 + funext k;fin_cases k <;> simp [s,u,singletonStore,Function.update] + have h2 : Runs (reverseMove 1 2) u v (2*x.1.length+1):=by + have hh:=reverseMove_runs (1 : Fin 4) 2 (by decide) u + convert hh using 1 + · funext k;fin_cases k <;> simp [u,v,singletonStore,Function.update] + · simp [u] + have h3 : Runs (reverseMove 2 0) v (singletonStore 0 (x.1++x.2)) (2*x.1.length+1):=by + have hh:=reverseMove_runs (2 : Fin 4) 0 (by decide) v + convert hh using 1 + · funext k;fin_cases k <;> simp [v,singletonStore,Function.update] + · simp [v] + refine ⟨(2*x.1.length+1)+(2*x.1.length+1)+(7*x.1.length+6),?_, + Runs.seq h1 (Runs.seq h2 h3)⟩ + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_C,Polynomial.eval_X, + prodCode,pairBits_length,id_eq] + omega +end Procedure +end ExactQuantumFactoring.BitStackProgram + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BooleanAlgebra.lean b/lean/OAI/Computability/QuantumFactoring/BooleanAlgebra.lean new file mode 100644 index 0000000000000000000000000000000000000000..464e921b9036b80145a3e63392255cea2e9b6c2a --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BooleanAlgebra.lean @@ -0,0 +1,137 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BooleanNetworkFurther + +namespace OAI + +section + + +namespace ExactQuantumFactoring.BooleanNetwork + +/-- Wire routing is free: it refers to values already physically present. -/ +def rewire {n m l : ℕ} (c : BooleanNetwork n m) (f : Fin l → Fin m) : BooleanNetwork n l := + ⟨c.width, c.net, c.output ∘ f⟩ + +@[simp] lemma eval_rewire {n m l : ℕ} (c : BooleanNetwork n m) (f : Fin l → Fin m) + (x : Fin n → Bool) : (c.rewire f).eval x = c.eval x ∘ f := rfl + +@[simp] lemma count_rewire {n m l : ℕ} (c : BooleanNetwork n m) (f : Fin l → Fin m) : + (c.rewire f).net.count = c.net.count := rfl + +def bit {n : ℕ} (i : Fin n) : BooleanNetwork n 1 := select (fun _ => i) +def constant {n : ℕ} (b : Bool) : BooleanNetwork n 1 := node (.constant b) +def bnot {n : ℕ} (a : BooleanNetwork n 1) : BooleanNetwork n 1 := a.comp (node (.neg 0)) +def band {n : ℕ} (a b : BooleanNetwork n 1) : BooleanNetwork n 1 := + (a.pair b).comp (node (.conj 0 1)) +def bor {n : ℕ} (a b : BooleanNetwork n 1) : BooleanNetwork n 1 := (a.bnot.band b.bnot).bnot +def bxor {n : ℕ} (a b : BooleanNetwork n 1) : BooleanNetwork n 1 := + (a.band b.bnot).bor (a.bnot.band b) +def mux {n : ℕ} (c a b : BooleanNetwork n 1) : BooleanNetwork n 1 := + (c.band a).bor (c.bnot.band b) +def majority {n : ℕ} (a b c : BooleanNetwork n 1) : BooleanNetwork n 1 := + (a.band b).bor (c.band (a.bor b)) + +@[simp] lemma eval_bit {n : ℕ} (i : Fin n) (x : Fin n → Bool) (j : Fin 1) : + (bit i).eval x j = x i := rfl + +@[simp] lemma eval_constant {n : ℕ} (b : Bool) (x : Fin n → Bool) (j : Fin 1) : + (constant b).eval x j = b := eval_node _ _ _ + +@[simp] lemma eval_bnot {n : ℕ} (a : BooleanNetwork n 1) (x : Fin n → Bool) (j : Fin 1) : + a.bnot.eval x j = !(a.eval x 0) := by simp [bnot, eval_comp, BoolNode.eval] + +@[simp] lemma eval_band {n : ℕ} (a b : BooleanNetwork n 1) (x : Fin n → Bool) (j : Fin 1) : + (a.band b).eval x j = (a.eval x 0 && b.eval x 0) := by + simp only [band, eval_comp, eval_node, BoolNode.eval, eval_pair] + rfl + +@[simp] lemma eval_bor {n : ℕ} (a b : BooleanNetwork n 1) (x : Fin n → Bool) (j : Fin 1) : + (a.bor b).eval x j = (a.eval x 0 || b.eval x 0) := by + simp [bor] + +@[simp] lemma eval_bxor {n : ℕ} (a b : BooleanNetwork n 1) (x : Fin n → Bool) (j : Fin 1) : + (a.bxor b).eval x j = Bool.xor (a.eval x 0) (b.eval x 0) := by + simp only [bxor, eval_bor, eval_band, eval_bnot] + cases a.eval x 0 <;> cases b.eval x 0 <;> rfl + +@[simp] lemma eval_mux {n : ℕ} (c a b : BooleanNetwork n 1) (x : Fin n → Bool) (j : Fin 1) : + (mux c a b).eval x j = if c.eval x 0 then a.eval x 0 else b.eval x 0 := by + simp only [mux, eval_bor, eval_band, eval_bnot] + cases c.eval x 0 <;> simp + +@[simp] lemma eval_majority {n : ℕ} (a b c : BooleanNetwork n 1) (x : Fin n → Bool) (j : Fin 1) : + (majority a b c).eval x j = Bool.atLeastTwo (a.eval x 0) (b.eval x 0) (c.eval x 0) := by + simp only [majority, eval_bor, eval_band] + cases a.eval x 0 <;> cases b.eval x 0 <;> cases c.eval x 0 <;> rfl + +@[simp] lemma count_bit {n : ℕ} (i : Fin n) : (bit i).net.count = 0 := rfl +@[simp] lemma count_constant {n : ℕ} (b : Bool) : (constant (n := n) b).net.count = 1 := rfl +@[simp] lemma count_bnot {n : ℕ} (a : BooleanNetwork n 1) : a.bnot.net.count = a.net.count + 1 := by + simp [bnot, count_comp] +@[simp] lemma count_band {n : ℕ} (a b : BooleanNetwork n 1) : + (a.band b).net.count = a.net.count + b.net.count + 1 := by simp [band, count_comp, count_pair] +@[simp] lemma count_bor {n : ℕ} (a b : BooleanNetwork n 1) : + (a.bor b).net.count = a.net.count + b.net.count + 4 := by simp [bor]; omega +@[simp] lemma count_bxor {n : ℕ} (a b : BooleanNetwork n 1) : + (a.bxor b).net.count = 2 * a.net.count + 2 * b.net.count + 8 := by simp [bxor]; omega +@[simp] lemma count_mux {n : ℕ} (c a b : BooleanNetwork n 1) : + (mux c a b).net.count = 2 * c.net.count + a.net.count + b.net.count + 7 := by simp [mux]; omega +@[simp] lemma count_majority {n : ℕ} (a b c : BooleanNetwork n 1) : + (majority a b c).net.count = 2 * a.net.count + 2 * b.net.count + c.net.count + 10 := by + simp [majority]; omega + +/-- Logical assignment preserves the input values in the physical trace, but +provides the standard overwritten-state interface to the next computation. -/ +def assign {n : ℕ} (i : Fin n) (v : BooleanNetwork n 1) : BooleanNetwork n n := + ((select id).pair v).rewire (fun j => if j = i then Fin.natAdd n 0 else j.castAdd 1) + +lemma eval_assign {n : ℕ} (i : Fin n) (v : BooleanNetwork n 1) (x : Fin n → Bool) : + (assign i v).eval x = Function.update x i (v.eval x 0) := by + funext j + simp only [assign, eval_rewire, Function.comp_apply, eval_pair, eval_select] + by_cases hj : j = i + · subst j + simp + · simp [hj] + +@[simp] lemma count_assign {n : ℕ} (i : Fin n) (v : BooleanNetwork n 1) : + (assign i v).net.count = v.net.count := by simp [assign, count_pair] + +/-- Sequentially composed bounded logical updates compile by retained history. -/ +def sequence {n : ℕ} : List (BooleanNetwork n n) → BooleanNetwork n n + | [] => select id + | c :: cs => c.comp (sequence cs) + +lemma eval_sequence {n : ℕ} (cs : List (BooleanNetwork n n)) (x : Fin n → Bool) : + (sequence cs).eval x = cs.foldl (fun x c => c.eval x) x := by + induction cs generalizing x with + | nil => rfl + | cons c cs ih => rw [sequence, eval_comp, ih]; rfl + +lemma count_sequence {n : ℕ} (cs : List (BooleanNetwork n n)) : + (sequence cs).net.count = (cs.map (fun c => c.net.count)).sum := by + induction cs with + | nil => rfl + | cons c cs ih => simp [sequence, count_comp, ih] + +def iterate {n : ℕ} (c : BooleanNetwork n n) (k : ℕ) : BooleanNetwork n n := + sequence (List.replicate k c) + +lemma eval_iterate {n : ℕ} (c : BooleanNetwork n n) (k : ℕ) (x : Fin n → Bool) : + (iterate c k).eval x = (c.eval^[k]) x := by + induction k generalizing x with + | zero => rfl + | succ k ih => + change (c.comp (iterate c k)).eval x = _ + rw [eval_comp, ih, Function.iterate_succ_apply] + +lemma count_iterate {n : ℕ} (c : BooleanNetwork n n) (k : ℕ) : + (iterate c k).net.count = k * c.net.count := by + simp [iterate, count_sequence, List.sum_replicate] + +end ExactQuantumFactoring.BooleanNetwork + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BooleanCircuit.lean b/lean/OAI/Computability/QuantumFactoring/BooleanCircuit.lean new file mode 100644 index 0000000000000000000000000000000000000000..58e318f474bd4d33f06bbab35bc986a3f4ac5925 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BooleanCircuit.lean @@ -0,0 +1,169 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.CircuitSemantics +import OAI.Computability.QuantumFactoring.GateSemantics + +namespace OAI + +section + + +namespace ExactQuantumFactoring +open scoped BigOperators Kronecker + +noncomputable def basisVector {ι : Type*} [DecidableEq ι] (x : ι) : ι → ℂ := + fun y => if y = x then 1 else 0 + +lemma matrix_basisVector {ι κ : Type*} [Fintype ι] [DecidableEq ι] + (A : Matrix κ ι ℂ) (x : ι) : A.mulVec (basisVector x) = fun y => A y x := by + funext y + simp [Matrix.mulVec, dotProduct, basisVector] + +lemma permutationMatrix_basisVector {ι : Type*} [Fintype ι] [DecidableEq ι] + (e : Equiv.Perm ι) (x : ι) : + (permutationMatrix e).mulVec (basisVector x) = basisVector (e x) := by + rw [matrix_basisVector] + rfl + +/-- Lift a local classical reversible gate to the actual wires; this is not an +additional circuit instruction, just its classical semantics. -/ +noncomputable def Instruction.liftPerm {q : ℕ} (o : Instruction q) + (e : Equiv.Perm (Basis o.gate.arity)) : Equiv.Perm (Basis q) := + (o.splitBasis.trans (Equiv.prodCongr e (Equiv.refl _))).trans o.splitBasis.symm + +lemma Instruction.liftPerm_matrix {q : ℕ} (o : Instruction q) + (e : Equiv.Perm (Basis o.gate.arity)) + (he : o.gate.localMatrix = permutationMatrix e) : + o.matrix = permutationMatrix (o.liftPerm e) := by + classical + rw [o.matrix_eq_reindex, he] + ext x y + change ((if (o.splitBasis x).1 = e (o.splitBasis y).1 then (1:ℂ) else 0) * + if (o.splitBasis x).2 = (o.splitBasis y).2 then 1 else 0) = + if x = o.liftPerm e y then 1 else 0 + have hh : x = o.liftPerm e y ↔ + (o.splitBasis x).1 = e (o.splitBasis y).1 ∧ + (o.splitBasis x).2 = (o.splitBasis y).2 := by + rw [← o.splitBasis.injective.eq_iff] + simp [Instruction.liftPerm, Prod.ext_iff] + simp only [hh] + split_ifs <;> simp_all + +lemma Instruction.liftPerm_wire {q : ℕ} (o : Instruction q) + (e : Equiv.Perm (Basis o.gate.arity)) (x : Basis q) (i : Fin o.gate.arity) : + o.liftPerm e x (o.wire i) = e (x ∘ o.wire) i := by + have h := congrArg (fun z => z.1 i) (o.splitBasis.apply_symm_apply + ((Equiv.prodCongr e (Equiv.refl (o.Unused → Bool))) (o.splitBasis x))) + exact h + +lemma Instruction.liftPerm_unused {q : ℕ} (o : Instruction q) + (e : Equiv.Perm (Basis o.gate.arity)) (x : Basis q) (i : Fin q) + (hi : ∀ j, o.wire j ≠ i) : o.liftPerm e x i = x i := by + have h := congrArg (fun z => z.2 ⟨i,hi⟩) (o.splitBasis.apply_symm_apply + ((Equiv.prodCongr e (Equiv.refl (o.Unused → Bool))) (o.splitBasis x))) + exact h + +lemma Instruction.liftPerm_basisVector {q : ℕ} (o : Instruction q) + (e : Equiv.Perm (Basis o.gate.arity)) + (he : o.gate.localMatrix = permutationMatrix e) (x : Basis q) : + o.matrix.mulVec (basisVector x) = basisVector (o.liftPerm e x) := by + rw [o.liftPerm_matrix e he, permutationMatrix_basisVector] + +/-- No inverse/control flag is used in these elementary fresh-bit operations. -/ +abbrev plainGate (p : Primitive) : Gate := ⟨p,false,false⟩ + +lemma plainGate_arity (p : Primitive) : (plainGate p).arity = p.arity := by + simp [Gate.arity] + +lemma plainGate_localMatrix (p : Primitive) : + (plainGate p).localMatrix = p.localMatrix := rfl + +abbrev notAt {q : ℕ} (t : Fin q) : Instruction q := + ⟨plainGate .not, fun _ => t, by + change Function.Injective (fun _ : Fin 1 => t) + intro a b _ + exact Subsingleton.elim a b⟩ + +abbrev cnotAt {q : ℕ} (c t : Fin q) (hct : c ≠ t) : Instruction q := + ⟨plainGate .cnot, ![c,t], by + change Function.Injective (![c,t] : Fin 2 → Fin q) + intro i j he + fin_cases i <;> fin_cases j <;> simp_all⟩ + +abbrev toffoliAt {q : ℕ} (a b t : Fin q) (hab : a ≠ b) (hat : a ≠ t) (hbt : b ≠ t) : + Instruction q := + ⟨plainGate .toffoli, ![a,b,t], by + change Function.Injective (![a,b,t] : Fin 3 → Fin q) + intro i j he + fin_cases i <;> fin_cases j <;> simp_all⟩ + +lemma notAt_lift {q : ℕ} (t : Fin q) (x : Basis q) : + (notAt t).liftPerm notPerm x = Function.update x t (!x t) := by + classical + funext i + by_cases hi : t = i + · subst i + rw [Function.update_self] + exact (notAt t).liftPerm_wire notPerm x ⟨0,by change 0<1; decide⟩ + · rw [(notAt t).liftPerm_unused notPerm x i (by intro j; exact hi)] + simp [Function.update, Ne.symm hi] + +lemma cnotAt_lift {q : ℕ} (c t : Fin q) (hct : c ≠ t) (x : Basis q) : + (cnotAt c t hct).liftPerm cnotPerm x = + Function.update x t (Bool.xor (x c) (x t)) := by + classical + funext i + by_cases hi : t = i + · subst i + rw [Function.update_self] + exact (cnotAt c t hct).liftPerm_wire cnotPerm x ⟨1,by change 1<2; decide⟩ + · by_cases hc : c = i + · subst i + rw [Function.update_of_ne (Ne.symm hi)] + exact (cnotAt c t hct).liftPerm_wire cnotPerm x ⟨0,by change 0<2; decide⟩ + · rw [(cnotAt c t hct).liftPerm_unused cnotPerm x i (by + intro j; fin_cases j <;> simpa [cnotAt] using (by assumption : _))] + simp [Function.update, Ne.symm hi] + +lemma toffoliAt_lift {q : ℕ} (a b t : Fin q) + (hab : a ≠ b) (hat : a ≠ t) (hbt : b ≠ t) (x : Basis q) : + (toffoliAt a b t hab hat hbt).liftPerm toffoliPerm x = + Function.update x t (Bool.xor (x t) (x a && x b)) := by + classical + funext i + by_cases hi : t = i + · subst i + rw [Function.update_self] + exact (toffoliAt a b t hab hat hbt).liftPerm_wire toffoliPerm x ⟨2,by change 2<3; decide⟩ + · by_cases ha : a = i + · subst i + rw [Function.update_of_ne (Ne.symm hi)] + exact (toffoliAt a b t hab hat hbt).liftPerm_wire toffoliPerm x ⟨0,by change 0<3; decide⟩ + · by_cases hb : b = i + · subst i + rw [Function.update_of_ne (Ne.symm hi)] + exact (toffoliAt a b t hab hat hbt).liftPerm_wire toffoliPerm x ⟨1,by change 1<3; decide⟩ + · rw [(toffoliAt a b t hab hat hbt).liftPerm_unused toffoliPerm x i (by + intro j; fin_cases j <;> simpa [toffoliAt] using (by assumption : _))] + simp [Function.update, Ne.symm hi] + +lemma notAt_basis {q : ℕ} (t : Fin q) (x : Basis q) : + (notAt t).matrix.mulVec (basisVector x) = basisVector (Function.update x t (!x t)) := by + rw [Instruction.liftPerm_basisVector (notAt t) notPerm (by exact not_localMatrix), notAt_lift] + +lemma cnotAt_basis {q : ℕ} (c t : Fin q) (hct : c ≠ t) (x : Basis q) : + (cnotAt c t hct).matrix.mulVec (basisVector x) = + basisVector (Function.update x t (Bool.xor (x c) (x t))) := by + rw [Instruction.liftPerm_basisVector (cnotAt c t hct) cnotPerm (by exact cnot_localMatrix), cnotAt_lift] + +lemma toffoliAt_basis {q : ℕ} (a b t : Fin q) (hab : a ≠ b) (hat : a ≠ t) (hbt : b ≠ t) + (x : Basis q) : + (toffoliAt a b t hab hat hbt).matrix.mulVec (basisVector x) = + basisVector (Function.update x t (Bool.xor (x t) (x a && x b))) := by + rw [Instruction.liftPerm_basisVector (toffoliAt a b t hab hat hbt) toffoliPerm (by exact toffoli_localMatrix), toffoliAt_lift] + +end ExactQuantumFactoring + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BooleanFold.lean b/lean/OAI/Computability/QuantumFactoring/BooleanFold.lean new file mode 100644 index 0000000000000000000000000000000000000000..6e851e3ad1a51b935bd3dbd0351a82b78f585204 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BooleanFold.lean @@ -0,0 +1,58 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BooleanAlgebra + +namespace OAI + +section +open scoped BigOperators + + +namespace ExactQuantumFactoring.BooleanNetwork +open scoped BigOperators + +def any {n : ℕ} : List (BooleanNetwork n 1) → BooleanNetwork n 1 + | [] => constant false + | c::cs => c.bor (any cs) + +lemma any_eval {n : ℕ} (cs : List (BooleanNetwork n 1)) (x : Fin n → Bool) : + (any cs).eval x 0=true ↔ ∃ c ∈ cs, c.eval x 0=true := by + induction cs with + | nil => simp [any] + | cons c cs ih => simp [any,ih] + +lemma any_count {n c : ℕ} (cs : List (BooleanNetwork n 1)) + (h : ∀ a ∈ cs, a.net.count ≤ c) : (any cs).net.count ≤ cs.length*(c+4)+1 := by + induction cs with + | nil => simp [any] + | cons a cs ih => + have ha := h a (by simp) + have hc := ih (fun b hb => h b (by simp [hb])) + simp only [any,count_bor,List.length_cons] + nlinarith + +def all {n : ℕ} : List (BooleanNetwork n 1) → BooleanNetwork n 1 + | [] => constant true + | c::cs => c.band (all cs) + +lemma all_eval {n : ℕ} (cs : List (BooleanNetwork n 1)) (x : Fin n → Bool) : + (all cs).eval x 0=true ↔ ∀ c ∈ cs, c.eval x 0=true := by + induction cs with + | nil => simp [all] + | cons c cs ih => simp [all,ih] + +lemma all_count {n c : ℕ} (cs : List (BooleanNetwork n 1)) + (h : ∀ a ∈ cs, a.net.count ≤ c) : (all cs).net.count ≤ cs.length*(c+1)+1 := by + induction cs with + | nil => simp [all] + | cons a cs ih => + have ha := h a (by simp) + have hc := ih (fun b hb => h b (by simp [hb])) + simp only [all,count_band,List.length_cons] + nlinarith + +end ExactQuantumFactoring.BooleanNetwork + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BooleanNetwork.lean b/lean/OAI/Computability/QuantumFactoring/BooleanNetwork.lean new file mode 100644 index 0000000000000000000000000000000000000000..d802af1f90843fd113a7a080bc19a1175ed65a16 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BooleanNetwork.lean @@ -0,0 +1,206 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BooleanProgram + +namespace OAI + +section + + +namespace ExactQuantumFactoring + +/-- A bounded-fan-in Boolean node, with no hidden arithmetic operation. -/ +inductive BoolNode (n : ℕ) where + | constant (b : Bool) + | copy (i : Fin n) + | neg (i : Fin n) + | conj (i j : Fin n) + +namespace BoolNode + +def eval {n : ℕ} : BoolNode n → (Fin n → Bool) → Bool + | .constant b, _ => b + | .copy i, x => x i + | .neg i, x => !x i + | .conj i j, x => x i && x j + +def map {n m : ℕ} (f : Fin n → Fin m) : BoolNode n → BoolNode m + | .constant b => .constant b + | .copy i => .copy (f i) + | .neg i => .neg (f i) + | .conj i j => .conj (f i) (f j) + +lemma eval_map {n m : ℕ} (f : Fin n → Fin m) (o : BoolNode n) (x : Fin m → Bool) : + (o.map f).eval x = o.eval (x ∘ f) := by cases o <;> rfl + +/-- The new wire is distinct from every preexisting wire. -/ +def compileOp {n q : ℕ} (h : n + 1 ≤ q) (o : BoolNode n) : + BooleanOp q ⟨n, by omega⟩ := + match o with + | .constant b => .constant b + | .copy i => .copy (i.castLE (by omega)) (by intro he; have hh := congrArg Fin.val he; simp only [Fin.val_castLE] at hh; omega) + | .neg i => .neg (i.castLE (by omega)) (by intro he; have hh := congrArg Fin.val he; simp only [Fin.val_castLE] at hh; omega) + | .conj i j => .conj (i.castLE (by omega)) (j.castLE (by omega)) + (by intro he; have hh := congrArg Fin.val he; simp only [Fin.val_castLE] at hh; omega) + (by intro he; have hh := congrArg Fin.val he; simp only [Fin.val_castLE] at hh; omega) + +lemma compileOp_value {n q : ℕ} (h : n + 1 ≤ q) (o : BoolNode n) (x : Basis q) : + (o.compileOp h).value x = o.eval (fun i => x (i.castLE (by omega))) := by + cases o <;> rfl + +end BoolNode + +/-- Straight-line Boolean computation retaining its whole trace. Width increases +by exactly one per node, so there is no truth-table synthesis overhead. -/ +inductive BoolNet (n : ℕ) : ℕ → Type + | input : BoolNet n n + | add {k : ℕ} (p : BoolNet n k) (o : BoolNode k) : BoolNet n (k+1) + +namespace BoolNet + +def count {n k : ℕ} : BoolNet n k → ℕ + | .input => 0 + | .add p _ => p.count + 1 + +lemma width_eq {n k : ℕ} (p : BoolNet n k) : k = n + p.count := by + induction p with + | input => simp [count] + | add p o ih => simp only [count]; omega + +lemma input_le {n k : ℕ} (p : BoolNet n k) : n ≤ k := by rw [p.width_eq]; omega + +def eval {n k : ℕ} : BoolNet n k → (Fin n → Bool) → (Fin k → Bool) + | .input, x => x + | .add p o, x => Fin.snoc (p.eval x) (o.eval (p.eval x)) + +@[simp] lemma eval_add_castSucc {n k : ℕ} (p : BoolNet n k) (o : BoolNode k) + (x : Fin n → Bool) (i : Fin k) : (p.add o).eval x i.castSucc = p.eval x i := by + simp [eval] + +@[simp] lemma eval_add_last {n k : ℕ} (p : BoolNet n k) (o : BoolNode k) + (x : Fin n → Bool) : (p.add o).eval x (Fin.last k) = o.eval (p.eval x) := by + simp [eval] + +lemma eval_input {n k : ℕ} (p : BoolNet n k) (x : Fin n → Bool) (i : Fin n) : + p.eval x (i.castLE p.input_le) = x i := by + induction p with + | input => rfl + | add p o ih => + have he : i.castLE (p.add o).input_le = (i.castLE p.input_le).castSucc := rfl + rw [he, eval_add_castSucc, ih] + +def program {n k : ℕ} (p : BoolNet n k) {q : ℕ} (h : k ≤ q) : BooleanProgram q := + match p with + | .input => [] + | .add p o => p.program (by omega) ++ [⟨⟨_, by omega⟩, o.compileOp h⟩] + +lemma program_length {n k q : ℕ} (p : BoolNet n k) (h : k ≤ q) : + (p.program h).length = p.count := by + induction p with + | input => rfl + | add p o ih => simp [program, count, ih] + +lemma compile_length {n k q : ℕ} (p : BoolNet n k) (h : k ≤ q) : + (BooleanProgram.compile (p.program h)).length ≤ 2 * p.count := by + simpa only [program_length] using BooleanProgram.compile_length (p.program h) + +/-- Append a network whose inputs are arbitrary already-computed wires. +Repeated input sources are permitted and do not cause duplicated computation. -/ +def attach {n k m l : ℕ} (a : BoolNet n k) (ρ : Fin m → Fin k) (b : BoolNet m l) : + (j : ℕ) × BoolNet n j × (Fin l → Fin j) := + match b with + | .input => ⟨k, a, ρ⟩ + | .add b o => + let c := a.attach ρ b + ⟨c.1 + 1, c.2.1.add (o.map c.2.2), Fin.snoc (fun i => (c.2.2 i).castSucc) (Fin.last c.1)⟩ + +lemma attach_count {n k m l : ℕ} (a : BoolNet n k) (ρ : Fin m → Fin k) (b : BoolNet m l) : + (a.attach ρ b).2.1.count = a.count + b.count := by + induction b with + | input => simp [attach, count] + | add b o ih => simp only [attach, count, ih, Nat.add_assoc] + +lemma attach_eval {n k m l : ℕ} (a : BoolNet n k) (ρ : Fin m → Fin k) (b : BoolNet m l) + (x : Fin n → Bool) : + (a.attach ρ b).2.1.eval x ∘ (a.attach ρ b).2.2 = b.eval (a.eval x ∘ ρ) := by + induction b with + | input => rfl + | @add l b o ih => + funext i + refine Fin.lastCases ?_ (fun j => ?_) i + · simp only [attach, Function.comp_apply, Fin.snoc_last, eval_add_last, BoolNode.eval_map] + rw [ih] + · simp only [attach, Function.comp_apply, Fin.snoc_castSucc, eval_add_castSucc] + exact congrFun ih j + +lemma attach_width {n k m l : ℕ} (a : BoolNet n k) (ρ : Fin m → Fin k) (b : BoolNet m l) : + (a.attach ρ b).1 = k + b.count := by + have hw := (a.attach ρ b).2.1.width_eq + rw [attach_count, ← Nat.add_assoc, ← a.width_eq] at hw + exact hw + +lemma attach_le {n k m l : ℕ} (a : BoolNet n k) (ρ : Fin m → Fin k) (b : BoolNet m l) : + k ≤ (a.attach ρ b).1 := by rw [attach_width]; omega + +lemma attach_preserve {n k m l : ℕ} (a : BoolNet n k) (ρ : Fin m → Fin k) (b : BoolNet m l) + (x : Fin n → Bool) (i : Fin k) : + (a.attach ρ b).2.1.eval x (i.castLE (a.attach_le ρ b)) = a.eval x i := by + induction b with + | input => rfl + | add b o ih => + change ((a.attach ρ b).2.1.add (o.map (a.attach ρ b).2.2)).eval x + (i.castLE (a.attach_le ρ b)).castSucc = _ + rw [eval_add_castSucc, ih] + +/-- On fresh ancillas the compiled program realizes the network exactly, +including preservation of all unused wires. -/ +lemma program_eval {n k q : ℕ} (p : BoolNet n k) (h : k ≤ q) (x : Basis q) + (hfresh : ∀ i : Fin q, n ≤ i.val → x i = false) : + (∀ i : Fin k, (BooleanProgram.eval (p.program h) x) (i.castLE h) = + p.eval (fun j => x (j.castLE (p.input_le.trans h))) i) ∧ + (∀ i : Fin q, k ≤ i.val → (BooleanProgram.eval (p.program h) x) i = false) := by + induction p with + | input => exact ⟨fun _ => rfl, hfresh⟩ + | @add k p o ih => + have hk : k ≤ q := by omega + obtain ⟨hpre, hrest⟩ := ih hk + have hy : (BooleanProgram.eval (p.program hk) x) ⟨k, by omega⟩ = false := + hrest _ (by simp) + have hv : (o.compileOp h).value (BooleanProgram.eval (p.program hk) x) = + o.eval (p.eval (fun j => x (j.castLE (p.input_le.trans hk)))) := by + rw [BoolNode.compileOp_value] + congr 1 + funext i + exact hpre i + have heval : BooleanProgram.eval ((p.add o).program h) x = + Function.update (BooleanProgram.eval (p.program hk) x) ⟨k, by omega⟩ + (o.eval (p.eval (fun j => x (j.castLE (p.input_le.trans hk))))) := by + simp only [program, BooleanProgram.eval, List.foldl_append, List.foldl_cons, List.foldl_nil] + change (o.compileOp h).eval (BooleanProgram.eval (p.program hk) x) = _ + rw [BooleanOp.eval_fresh _ _ hy, hv] + rfl + rw [heval] + constructor + · intro i + refine Fin.lastCases ?_ (fun j => ?_) i + · rw [eval_add_last] + exact Function.update_self _ _ _ + · rw [eval_add_castSucc] + rw [Function.update_of_ne (by intro he; have hh := congrArg Fin.val he; change j.val = k at hh; omega)] + exact hpre j + · intro i hi + rw [Function.update_of_ne (by intro he; have hh := congrArg Fin.val he; change i.val = k at hh; omega)] + exact hrest i (by omega) + +end BoolNet + +/-- Typed interfaces for network composition, with explicitly retained workspace. -/ +structure BooleanNetwork (n m : ℕ) where + width : ℕ + net : BoolNet n width + output : Fin m → Fin width + + +end ExactQuantumFactoring +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BooleanNetworkFurther.lean b/lean/OAI/Computability/QuantumFactoring/BooleanNetworkFurther.lean new file mode 100644 index 0000000000000000000000000000000000000000..2fa8f6e74beacfb3d36c0daad6d2b6015b36e3e3 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BooleanNetworkFurther.lean @@ -0,0 +1,75 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BooleanNetwork + +namespace OAI + +section +namespace ExactQuantumFactoring + +namespace BooleanNetwork + +def eval {n m : ℕ} (c : BooleanNetwork n m) (x : Fin n → Bool) : Fin m → Bool := + c.net.eval x ∘ c.output + +def select {n m : ℕ} (f : Fin m → Fin n) : BooleanNetwork n m := ⟨n, .input, f⟩ + +def node {n : ℕ} (o : BoolNode n) : BooleanNetwork n 1 := + ⟨n+1, .add .input o, fun _ => Fin.last n⟩ + +def comp {n m l : ℕ} (a : BooleanNetwork n m) (b : BooleanNetwork m l) : BooleanNetwork n l := + let c := a.net.attach a.output b.net + ⟨c.1, c.2.1, c.2.2 ∘ b.output⟩ + +lemma eval_comp {n m l : ℕ} (a : BooleanNetwork n m) (b : BooleanNetwork m l) + (x : Fin n → Bool) : (a.comp b).eval x = b.eval (a.eval x) := by + change ((a.net.attach a.output b.net).2.1.eval x ∘ (a.net.attach a.output b.net).2.2) ∘ + b.output = _ + rw [BoolNet.attach_eval] + rfl + +lemma count_comp {n m l : ℕ} (a : BooleanNetwork n m) (b : BooleanNetwork m l) : + (a.comp b).net.count = a.net.count + b.net.count := BoolNet.attach_count _ _ _ + +/-- Parallel computations share the input but retain disjoint new traces. -/ +def pair {n m l : ℕ} (a : BooleanNetwork n m) (b : BooleanNetwork n l) : BooleanNetwork n (m+l) := + let ρ : Fin n → Fin a.width := fun i => i.castLE a.net.input_le + let c := a.net.attach ρ b.net + ⟨c.1, c.2.1, Fin.append (fun i => (a.output i).castLE (a.net.attach_le ρ b.net)) + (c.2.2 ∘ b.output)⟩ + +lemma eval_pair {n m l : ℕ} (a : BooleanNetwork n m) (b : BooleanNetwork n l) + (x : Fin n → Bool) : (a.pair b).eval x = Fin.append (a.eval x) (b.eval x) := by + funext i + refine Fin.addCases (fun j => ?_) (fun j => ?_) i + · simp only [pair, eval, Function.comp_apply, Fin.append_left] + exact BoolNet.attach_preserve _ _ _ _ _ + · simp only [pair, eval, Function.comp_apply, Fin.append_right] + have he := congrFun (BoolNet.attach_eval a.net (fun i => i.castLE a.net.input_le) b.net x) (b.output j) + have hi : a.net.eval x ∘ (fun i : Fin n => i.castLE a.net.input_le) = x := by + funext j + exact BoolNet.eval_input _ _ _ + rw [hi] at he + exact he + +lemma count_pair {n m l : ℕ} (a : BooleanNetwork n m) (b : BooleanNetwork n l) : + (a.pair b).net.count = a.net.count + b.net.count := BoolNet.attach_count _ _ _ + +@[simp] lemma eval_select {n m : ℕ} (f : Fin m → Fin n) (x : Fin n → Bool) : + (select f).eval x = x ∘ f := rfl + +@[simp] lemma count_select {n m : ℕ} (f : Fin m → Fin n) : + (select f).net.count = 0 := rfl + +@[simp] lemma eval_node {n : ℕ} (o : BoolNode n) (x : Fin n → Bool) (i : Fin 1) : + (node o).eval x i = o.eval x := by + exact BoolNet.eval_add_last _ _ _ + +@[simp] lemma count_node {n : ℕ} (o : BoolNode n) : (node o).net.count = 1 := rfl + +end BooleanNetwork +end ExactQuantumFactoring + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BooleanOracle.lean b/lean/OAI/Computability/QuantumFactoring/BooleanOracle.lean new file mode 100644 index 0000000000000000000000000000000000000000..9686003f3be375b52efd7c30b81518aba22e97a7 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BooleanOracle.lean @@ -0,0 +1,161 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BooleanNetworkFurther + +namespace OAI + +section +open scoped BigOperators + + +namespace ExactQuantumFactoring + +namespace BoolNet + +/-- Only the actual trace, not unrelated output registers, must start at zero. -/ +lemma program_eval_range {n k q : ℕ} (p : BoolNet n k) (h : k ≤ q) (x : Basis q) + (hfresh : ∀ i : Fin q, n ≤ i.val → i.val < k → x i = false) : + (∀ i : Fin k, (BooleanProgram.eval (p.program h) x) (i.castLE h) = + p.eval (fun j => x (j.castLE (p.input_le.trans h))) i) ∧ + (∀ i : Fin q, k ≤ i.val → (BooleanProgram.eval (p.program h) x) i = x i) := by + induction p with + | input => exact ⟨fun _ => rfl, fun _ _ => rfl⟩ + | @add k p o ih => + have hk : k ≤ q := by omega + obtain ⟨hpre, hrest⟩ := ih hk (fun i hi hik => hfresh i hi (by omega)) + have hy : (BooleanProgram.eval (p.program hk) x) ⟨k, by omega⟩ = false := by + rw [hrest _ (by simp)] + exact hfresh _ p.input_le (by simp) + have hv : (o.compileOp h).value (BooleanProgram.eval (p.program hk) x) = + o.eval (p.eval (fun j => x (j.castLE (p.input_le.trans hk)))) := by + rw [BoolNode.compileOp_value] + congr 1 + funext i + exact hpre i + have heval : BooleanProgram.eval ((p.add o).program h) x = + Function.update (BooleanProgram.eval (p.program hk) x) ⟨k, by omega⟩ + (o.eval (p.eval (fun j => x (j.castLE (p.input_le.trans hk))))) := by + simp only [program, BooleanProgram.eval, List.foldl_append, List.foldl_cons, List.foldl_nil] + change (o.compileOp h).eval (BooleanProgram.eval (p.program hk) x) = _ + rw [BooleanOp.eval_fresh _ _ hy, hv] + rfl + rw [heval] + constructor + · intro i + refine Fin.lastCases ?_ (fun j => ?_) i + · rw [eval_add_last] + exact Function.update_self _ _ _ + · rw [eval_add_castSucc] + rw [Function.update_of_ne (by intro he; have hh := congrArg Fin.val he; change j.val = k at hh; omega)] + exact hpre j + · intro i hi + rw [Function.update_of_ne (by intro he; have hh := congrArg Fin.val he; change i.val = k at hh; omega)] + exact hrest i (by omega) + +end BoolNet + +namespace BooleanNetwork + +/-- Copy disjoint source wires into a separate target register, by XOR. -/ +def copyPrefix {k m : ℕ} (source : Fin m → Fin k) : (t : ℕ) → t ≤ m → BooleanProgram (k+m) + | 0, _ => [] + | t+1, h => copyPrefix source t (by omega) ++ + [⟨Fin.natAdd k ⟨t, by omega⟩, .copy ((source ⟨t, by omega⟩).castAdd m) + (by intro he; have hh := congrArg Fin.val he; simp at hh; omega)⟩] + +lemma copyPrefix_length {k m : ℕ} (source : Fin m → Fin k) (t : ℕ) (h : t ≤ m) : + (copyPrefix source t h).length = t := by + induction t with + | zero => rfl + | succ t ih => simp [copyPrefix, ih] + +lemma copyPrefix_eval {k m : ℕ} (source : Fin m → Fin k) (t : ℕ) (h : t ≤ m) + (x : Basis (k+m)) (i : Fin (k+m)) : + (copyPrefix source t h).eval x i = + if hi : k ≤ i.val ∧ i.val < k+t then + Bool.xor (x i) (x ((source ⟨i.val-k, by omega⟩).castAdd m)) else x i := by + induction t generalizing i with + | zero => simp [copyPrefix, BooleanProgram.eval] + | succ t ih => + simp only [copyPrefix, BooleanProgram.eval, List.foldl_append, List.foldl_cons, List.foldl_nil] + change (BooleanOp.copy ((source ⟨t, by omega⟩).castAdd m) _).eval + ((copyPrefix source t (by omega)).eval x) i = _ + by_cases hit : i.val = k+t + · have he : i = Fin.natAdd k ⟨t, Nat.lt_of_succ_le h⟩ := Fin.ext hit + subst i + rw [BooleanOp.eval_at] + simp only [BooleanOp.value] + rw [ih, ih] + simp only [Fin.val_natAdd, Fin.val_castAdd] + rw [dite_eq_right (by omega), dite_eq_right (by have := (source ⟨t, by omega⟩).isLt; omega), + dite_eq_left (by omega)] + simp + · rw [BooleanOp.eval_away _ _ (by intro he; exact hit (congrArg Fin.val he))] + rw [ih] + by_cases hn : k ≤ i.val ∧ i.val < k+t + · rw [dite_eq_left hn, dite_eq_left (by omega)] + · rw [dite_eq_right hn, dite_eq_right (by omega)] + +/-- Actual fixed-gate compute/copy/uncompute, with all trace wires restored. -/ +def oracle {n m : ℕ} (c : BooleanNetwork n m) : List (Instruction (c.width+m)) := + let p := c.net.program (Nat.le_add_right c.width m) + p.compile ++ (copyPrefix c.output m le_rfl).compile ++ + p.compile.reverse.map Instruction.reverse + +lemma oracle_length {n m : ℕ} (c : BooleanNetwork n m) : + c.oracle.length ≤ 4*c.net.count + 2*m := by + unfold oracle + simp only [List.length_append, List.length_map, List.length_reverse] + have hp := c.net.compile_length (Nat.le_add_right c.width m) + have hc := BooleanProgram.compile_length (copyPrefix c.output m le_rfl) + rw [copyPrefix_length] at hc + omega + +/-- The basis-state whose trace is zero and whose target is toggled by c(x). -/ +def oracleOutput {n m : ℕ} (c : BooleanNetwork n m) (x : Basis (c.width+m)) : Basis (c.width+m) := + fun i => if h : c.width ≤ i.val then + Bool.xor (x i) (c.eval (fun j => x (j.castLE (c.net.input_le.trans (Nat.le_add_right _ _)))) + ⟨i.val-c.width, by omega⟩) else x i + +lemma oracle_basis {n m : ℕ} (c : BooleanNetwork n m) (x : Basis (c.width+m)) + (hfresh : ∀ i : Fin (c.width+m), n ≤ i.val → i.val < c.width → x i = false) : + (programMatrix c.oracle).mulVec (basisVector x) = basisVector (c.oracleOutput x) := by + let p := c.net.program (Nat.le_add_right c.width m) + have hx := c.net.program_eval_range (Nat.le_add_right c.width m) x hfresh + have hout (i : Fin (c.width+m)) (hi : i.val < c.width) : c.oracleOutput x i = x i := by + simp only [oracleOutput, dite_eq_right (Nat.not_le.mpr hi)] + have hy := c.net.program_eval_range (Nat.le_add_right c.width m) (c.oracleOutput x) + (fun i hin hik => (hout i hik).trans (hfresh i hin hik)) + have hin : (fun j : Fin n => c.oracleOutput x + (j.castLE (c.net.input_le.trans (Nat.le_add_right _ _)))) = + (fun j => x (j.castLE (c.net.input_le.trans (Nat.le_add_right _ _)))) := by + funext j + apply hout + change j.val < c.width + exact j.isLt.trans_le c.net.input_le + rw [hin] at hy + have he : (copyPrefix c.output m le_rfl).eval (p.eval x) = p.eval (c.oracleOutput x) := by + funext i + rw [copyPrefix_eval] + by_cases hi : c.width ≤ i.val + · rw [dite_eq_left ⟨hi, i.isLt⟩, hx.2 i hi, hy.2 i hi] + have hs : p.eval x ((c.output ⟨i.val-c.width, by omega⟩).castAdd m) = + c.net.eval (fun j => x (j.castLE (c.net.input_le.trans (Nat.le_add_right _ _)))) + (c.output ⟨i.val-c.width, by omega⟩) := hx.1 _ + rw [hs] + simp only [oracleOutput, dite_eq_left hi, eval, Function.comp_apply] + · rw [dite_eq_right (by tauto)] + have hik : i.val < c.width := by omega + exact (hx.1 ⟨i.val,hik⟩).trans (hy.1 ⟨i.val,hik⟩).symm + change (programMatrix (p.compile ++ (copyPrefix c.output m le_rfl).compile ++ + p.compile.reverse.map Instruction.reverse)).mulVec (basisVector x) = _ + rw [programMatrix_append, programMatrix_append, ← Matrix.mulVec_mulVec, + ← Matrix.mulVec_mulVec, BooleanProgram.compile_basis, BooleanProgram.compile_basis, he, + BooleanProgram.uncompute] + +end BooleanNetwork +end ExactQuantumFactoring + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BooleanProgram.lean b/lean/OAI/Computability/QuantumFactoring/BooleanProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..be50821130384f211b37510fb310208fca9476f1 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BooleanProgram.lean @@ -0,0 +1,141 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.CircuitSemantics +import OAI.Computability.QuantumFactoring.BooleanCircuit + +namespace OAI + +section + + +namespace ExactQuantumFactoring +open scoped BigOperators + +lemma programMatrix_nil {q : ℕ} : programMatrix ([] : List (Instruction q)) = 1 := rfl + +lemma programMatrix_cons {q : ℕ} (o : Instruction q) (ops : List (Instruction q)) : + programMatrix (o :: ops) = programMatrix ops * o.matrix := by + change ops.foldl (fun A (o : Instruction q) => o.matrix * A) (o.matrix * 1) = _ + rw [programMatrix_fold, Matrix.mul_one] + +lemma programMatrix_singleton {q : ℕ} (o : Instruction q) : + programMatrix [o] = o.matrix := by + rw [programMatrix_cons, programMatrix_nil, Matrix.one_mul] + +/-- A Boolean node is implemented by at most two of the named fixed gates. +The target is excluded from the sources, but repeated sources are permitted. +Its action toggles the target, so the semantics are reversible on all states. -/ +inductive BooleanOp (q : ℕ) (t : Fin q) where + | constant (b : Bool) + | copy (a : Fin q) (ha : a ≠ t) + | neg (a : Fin q) (ha : a ≠ t) + | conj (a b : Fin q) (ha : a ≠ t) (hb : b ≠ t) + +namespace BooleanOp + +def value {q : ℕ} {t : Fin q} : BooleanOp q t → Basis q → Bool + | .constant b, _ => b + | .copy a _, x => x a + | .neg a _, x => !x a + | .conj a b _ _, x => x a && x b + +def eval {q : ℕ} {t : Fin q} (o : BooleanOp q t) (x : Basis q) : Basis q := + Function.update x t (Bool.xor (x t) (o.value x)) + +def compile {q : ℕ} {t : Fin q} : BooleanOp q t → List (Instruction q) + | .constant false => [] + | .constant true => [notAt t] + | .copy a ha => [cnotAt a t ha] + | .neg a ha => [cnotAt a t ha, notAt t] + | .conj a b ha hb => if h : a = b then [cnotAt a t ha] + else [toffoliAt a b t h ha hb] + +lemma compile_length {q : ℕ} {t : Fin q} (o : BooleanOp q t) : + o.compile.length ≤ 2 := by + cases o with + | constant b => cases b <;> simp [compile] + | copy => simp [compile] + | neg => simp [compile] + | conj a b ha hb => simp only [compile]; split <;> simp + +lemma eval_at {q : ℕ} {t : Fin q} (o : BooleanOp q t) (x : Basis q) : + o.eval x t = Bool.xor (x t) (o.value x) := Function.update_self _ _ _ + +lemma eval_away {q : ℕ} {t i : Fin q} (o : BooleanOp q t) (x : Basis q) (hi : i ≠ t) : + o.eval x i = x i := Function.update_of_ne hi _ _ + +lemma eval_fresh {q : ℕ} {t : Fin q} (o : BooleanOp q t) (x : Basis q) (ht : x t = false) : + o.eval x = Function.update x t (o.value x) := by + simp [eval, ht] + +lemma compile_basis {q : ℕ} {t : Fin q} (o : BooleanOp q t) (x : Basis q) : + (programMatrix o.compile).mulVec (basisVector x) = basisVector (o.eval x) := by + cases o with + | constant b => + cases b + · simp [compile, programMatrix_nil, eval, value] + · rw [compile, programMatrix_singleton, notAt_basis] + simp [eval, value] + | copy a ha => + rw [compile, programMatrix_singleton, cnotAt_basis] + simp [eval, value, Bool.xor_comm] + | neg a ha => + rw [compile, programMatrix_cons, programMatrix_singleton, ← Matrix.mulVec_mulVec, + cnotAt_basis, notAt_basis] + congr 1 + simp only [Function.update_self, Function.update_idem, eval, value] + congr 1 + cases x a <;> cases x t <;> rfl + | conj a b ha hb => + simp only [compile] + split_ifs with hab + · rw [programMatrix_singleton, cnotAt_basis] + subst b + simp [eval, value, Bool.xor_comm] + · rw [programMatrix_singleton, toffoliAt_basis] + rfl + +end BooleanOp + +/-- The classical network explicitly retains all values already computed. +In a fresh-output DAG each node's target is a previously zero ancilla. -/ +abbrev BooleanProgram (q : ℕ) := List ((t : Fin q) × BooleanOp q t) + +def BooleanProgram.eval {q : ℕ} (p : BooleanProgram q) (x : Basis q) : Basis q := + p.foldl (fun x o => o.2.eval x) x + +def BooleanProgram.compile {q : ℕ} (p : BooleanProgram q) : List (Instruction q) := + p.flatMap (fun o => o.2.compile) + +lemma BooleanProgram.compile_basis {q : ℕ} (p : BooleanProgram q) (x : Basis q) : + (programMatrix p.compile).mulVec (basisVector x) = basisVector (p.eval x) := by + induction p generalizing x with + | nil => simp [compile, eval, programMatrix_nil] + | cons o p ih => + change (programMatrix (o.2.compile ++ BooleanProgram.compile p)).mulVec (basisVector x) = _ + rw [programMatrix_append, ← Matrix.mulVec_mulVec, BooleanOp.compile_basis, ih] + rfl + +lemma BooleanProgram.compile_length {q : ℕ} (p : BooleanProgram q) : + p.compile.length ≤ 2 * p.length := by + induction p with + | nil => simp [compile] + | cons o p ih => + change (o.2.compile ++ BooleanProgram.compile p).length ≤ 2 * (o :: p).length + rw [List.length_append, List.length_cons] + have h := o.2.compile_length + omega + +/-- Reversing the actual compiled gate list erases the complete retained trace, +not only its output. No irreversible erasure is used. -/ +lemma BooleanProgram.uncompute {q : ℕ} (p : BooleanProgram q) (x : Basis q) : + (programMatrix (p.compile.reverse.map Instruction.reverse)).mulVec + (basisVector (p.eval x)) = basisVector x := by + rw [← p.compile_basis x, programMatrix_reverse, Matrix.mulVec_mulVec, + Matrix.mem_unitaryGroup_iff'.mp (programMatrix_unitary _), Matrix.one_mulVec] + +end ExactQuantumFactoring + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BooleanVector.lean b/lean/OAI/Computability/QuantumFactoring/BooleanVector.lean new file mode 100644 index 0000000000000000000000000000000000000000..9068a842f34e1452dd44f906a99bf788472a620b --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BooleanVector.lean @@ -0,0 +1,78 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BooleanAlgebra + +namespace OAI + +section + + +open scoped BigOperators +namespace ExactQuantumFactoring.BooleanNetwork + +/-- Assemble an arbitrary vector of single-bit combinational outputs, retaining +separate traces. This is a finite circuit construction, not a truth table. -/ +def vector {n : ℕ} : {m : ℕ} → (Fin m → BooleanNetwork n 1) → BooleanNetwork n m + | 0, _ => select Fin.elim0 + | m+1, f => (vector (fun i => f i.castSucc)).pair (f (Fin.last m)) + +@[simp] lemma eval_vector {n m : ℕ} (f : Fin m → BooleanNetwork n 1) + (x : Fin n → Bool) (i : Fin m) : (vector f).eval x i = (f i).eval x 0 := by + induction m with + | zero => exact Fin.elim0 i + | succ m ih => + rw [vector, eval_pair, Fin.append_right_eq_snoc] + refine Fin.lastCases ?_ (fun j => ?_) i + · rw [Fin.snoc_last] + · rw [Fin.snoc_castSucc] + exact ih _ j + +@[simp] lemma count_vector {n m : ℕ} (f : Fin m → BooleanNetwork n 1) : + (vector f).net.count = ∑ i, (f i).net.count := by + induction m with + | zero => simp [vector] + | succ m ih => simp [vector, count_pair, ih, Fin.sum_univ_castSucc] + +lemma count_vector_le {n m c : ℕ} (f : Fin m → BooleanNetwork n 1) + (h : ∀ i, (f i).net.count ≤ c) : (vector f).net.count ≤ m*c := by + rw [count_vector] + calc + _ ≤ ∑ _ : Fin m, c := Finset.sum_le_sum (fun i _ => h i) + _ = _ := by simp + +/-- Add explicit zero slots, with <=m nodes. Duplicate outputs may share zero, +but the simple linear upper bound is sufficient for the compiler. -/ +def padRight (n m : ℕ) : BooleanNetwork n (n+m) := + vector (fun i => if h : i.val < n then bit ⟨i.val,h⟩ else constant false) + +lemma eval_padRight (n m : ℕ) (x : Fin n → Bool) : + (padRight n m).eval x = Fin.append x (fun _ => false) := by + funext i + rw [padRight, eval_vector] + refine Fin.addCases (fun j => ?_) (fun j => ?_) i + · simp [j.isLt] + · simp + +lemma count_padRight (n m : ℕ) : (padRight n m).net.count = m := by + rw [padRight, count_vector, Fin.sum_univ_add] + have h₁ : (∑ x : Fin n, (if h : x.val < n then bit (n := n) ⟨x.val,h⟩ + else constant false).net.count) = 0 := by + apply Finset.sum_eq_zero + intro x _ + rw [dite_eq_left x.isLt] + rfl + have h₂ : (∑ x : Fin m, (if h : n+x.val < n then bit (n := n) ⟨n+x.val,h⟩ + else constant false).net.count) = m := by + trans ∑ _ : Fin m, 1 + · apply Finset.sum_congr rfl + intro x _ + rw [dite_eq_right (by omega : ¬ n+x.val < n)] + rfl + · simp + exact (congrArg₂ (· + ·) h₁ h₂).trans (Nat.zero_add _) + +end ExactQuantumFactoring.BooleanNetwork + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BoundedAKS.lean b/lean/OAI/Computability/QuantumFactoring/BoundedAKS.lean new file mode 100644 index 0000000000000000000000000000000000000000..59bcf6cf1bda7b696ad60e4005e42d200224cddb --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BoundedAKS.lean @@ -0,0 +1,150 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.PrimalityAuxiliaryPrime +import OAI.Computability.QuantumFactoring.CyclicPrimality +import OAI.Computability.QuantumFactoring.AKSCriteria +import OAI.Computability.QuantumFactoring.AKSNetworks +import OAI.Computability.QuantumFactoring.CyclicTestBounds +import OAI.Computability.QuantumFactoring.PerfectPowerCircuit + +namespace OAI + +section +open scoped BigOperators + + +namespace ExactQuantumFactoring.BitArithmetic +open BooleanNetwork Primality + +/-- All static search parameters and constants fit polynomial-width words. -/ +lemma aks_constants_fit {n : ℕ} (hn : 128 ≤ n) : 8*n^8 < 2^(rootWidth n) := by + have hp : n < 2^n := Nat.lt_pow_self (by decide) + have hp8 : n^8 < (2^n)^8 := Nat.pow_lt_pow_left hp (by decide) + have he : 3+n*8 ≤ rootWidth n := by dsimp [rootWidth]; nlinarith + calc + 8*n^8 < 8*(2^n)^8 := Nat.mul_lt_mul_of_pos_left hp8 (by decide) + _ = 2^(3+n*8) := by rw [pow_add,pow_mul]; norm_num + _ ≤ 2^(rootWidth n) := Nat.pow_le_pow_right (by decide) he + +def allCongruences (s w : ℕ) [NeZero s] : BooleanNetwork w 1 := + all (List.ofFn (fun i : Fin (8*s) => cyclicTest s w (i.val+1))) + +lemma allCongruences_value (s w : ℕ) [NeZero s] (x : Basis w) (hw : 0 < w) + (hm : 2 ≤ (bitsValue x).toNat) (hs : 8*s < 2^w) : + (allCongruences s w).eval x 0=true ↔ + ∀ a : ℕ, 1 ≤ a → a ≤ 8*s → + (cyclicX (R := ZMod (bitsValue x).toNat) s+cyclicC s (a : ZMod (bitsValue x).toNat))^ + (bitsValue x).toNat=cyclicX s^(bitsValue x).toNat+cyclicC s (a : ZMod (bitsValue x).toNat) := by + rw [allCongruences,all_ofFn_eval] + constructor + · intro h a ha has + have hh := (cyclicTest_correct s w (a-1+1) x hw hm (by omega)).mp + (h (⟨a-1,by omega⟩ : Fin (8*s))) + simpa only [show a-1+1=a by omega] using hh + · intro h i + rw [cyclicTest_correct s w (i.val+1) x hw hm (by omega)] + exact h _ (by omega) (by omega) + +lemma allCongruences_count (s w : ℕ) [NeZero s] : + (allCongruences s w).net.count ≤ 8*s*(cyclicTestBound s w+1)+1 := by + simpa only [allCongruences,List.length_ofFn] using + all_count (List.ofFn (fun i : Fin (8*s) => cyclicTest s w (i.val+1))) (by + intro c hc + obtain ⟨i,rfl⟩ := List.mem_ofFn.mp hc + exact cyclicTest_count s w (i.val+1)) + +/-- The auxiliary modulus branch. The bounded small-divisor test is performed +before the congruences. Evaluating every modulus is a polynomial unrolling of +(the first qualifying modulus in) the manuscript's bounded search. -/ +def aksBranch (n s : ℕ) [NeZero s] : BooleanNetwork (rootWidth n) 1 := + let w := rootWidth n + ((dividesNet w s).bnot.band (orderTests w s (n^2))).band + ((noSmallDivisor w (8*s)).band (allCongruences s w)) + +lemma aksBranch_sound {n s : ℕ} [NeZero s] (hn : 128 ≤ n) (hs : s.Prime) (hsn : s ≤ n^8) + (x : Basis (rootWidth n)) (hm : 2 ≤ (bitsValue x).toNat) (hmb : (bitsValue x).toNat < 2^n) + (hpow : ¬ PerfectPower (bitsValue x).toNat) (h : (aksBranch n s).eval x 0=true) : + (bitsValue x).toNat.Prime := by + have hfit := aks_constants_fit hn + have hsfit : 8*s < 2^(rootWidth n) := (Nat.mul_le_mul_left 8 hsn).trans_lt hfit + have hsfit' : s < 2^(rootWidth n) := by omega + have hkfit : n^2 < 2^(rootWidth n) := by + have hh : rootWidth n < 2^(rootWidth n) := Nat.lt_pow_self (by decide) + dsimp [rootWidth] at * + nlinarith + rw [aksBranch,eval_band,Bool.and_eq_true,eval_band,Bool.and_eq_true, + eval_band,Bool.and_eq_true,bnot_value,dividesNet_value _ _ _ hsfit', + orderTests_value _ _ _ _ hs.two_le hsfit' hkfit, + noSmallDivisor_value _ _ _ hsfit, + allCongruences_value _ _ _ (by dsimp [rootWidth];omega) hm hsfit] at h + have hcop : s.Coprime (bitsValue x).toNat := hs.coprime_iff_not_dvd.mpr h.1.1 + have ho := (order_tests_iff hs hcop).mp h.1.2 + by_cases hb : (bitsValue x).toNat ≤ 8*s + · exact prime_of_no_small_divisor hm hb h.2.1 + · exact cyclic_large_branch_prime hn hm hmb hs hcop ho hpow + (fun d hd hdB => h.2.1 d hd hdB (by omega)) h.2.2 + +lemma aksBranch_complete {n s : ℕ} [NeZero s] (hn : 128 ≤ n) (hs : s.Prime) (hsn : s ≤ n^8) + (x : Basis (rootWidth n)) (hm : (bitsValue x).toNat.Prime) + (hcop : s.Coprime (bitsValue x).toNat) (ho : n^2 < orderOf ((bitsValue x).toNat : ZMod s)) : + (aksBranch n s).eval x 0=true := by + have hfit := aks_constants_fit hn + have hsfit : 8*s < 2^(rootWidth n) := (Nat.mul_le_mul_left 8 hsn).trans_lt hfit + have hsfit' : s < 2^(rootWidth n) := by omega + have hkfit : n^2 < 2^(rootWidth n) := by + have hh : rootWidth n < 2^(rootWidth n) := Nat.lt_pow_self (by decide) + dsimp [rootWidth] at * + nlinarith + rw [aksBranch,eval_band,Bool.and_eq_true,eval_band,Bool.and_eq_true, + eval_band,Bool.and_eq_true,bnot_value,dividesNet_value _ _ _ hsfit', + orderTests_value _ _ _ _ hs.two_le hsfit' hkfit, + noSmallDivisor_value _ _ _ hsfit, + allCongruences_value _ _ _ (by dsimp [rootWidth];omega) hm.two_le hsfit] + refine ⟨⟨hs.coprime_iff_not_dvd.mp hcop,(order_tests_iff hs hcop).mpr ho⟩,?_,?_⟩ + · intro d hd _hdb hdm hdiv + have := hm.eq_one_or_self_of_dvd d hdiv + omega + · intro a _ha _has + exact cyclic_prime_test hm a + +/-- The condition is on the compile-time parameter s≤n^8, not on the possibly +exponentially large input integer. Decidable primality here is a finite bounded +search; its generation-cost proof is separate from circuit size. -/ +def aksStaticBranch (n s : ℕ) : BooleanNetwork (rootWidth n) 1 := + if h : s.Prime then + letI : NeZero s := ⟨h.ne_zero⟩ + aksBranch n s + else constant false + +def primalityNet (n : ℕ) : BooleanNetwork (rootWidth n) 1 := + (perfectPowerNet n).bnot.band + (any (List.ofFn (fun s : Fin (n^8+1) => aksStaticBranch n s.val))) + +/-- Full exact bounded AKS primality circuit, not an assumed decision procedure. -/ +theorem primalityNet_correct {n : ℕ} (hn : 128 ≤ n) (x : Basis (rootWidth n)) + (hm : 2 ≤ (bitsValue x).toNat) (hmb : (bitsValue x).toNat < 2^n) : + (primalityNet n).eval x 0=true ↔ (bitsValue x).toNat.Prime := by + rw [primalityNet,eval_band,Bool.and_eq_true,bnot_value,perfectPowerNet_correct (by omega) _ hmb, + any_ofFn_eval] + constructor + · rintro ⟨hpow,s,h⟩ + by_cases hs : s.val.Prime + · let : NeZero s.val := ⟨hs.ne_zero⟩ + have he : aksStaticBranch n s.val=aksBranch n s.val := dite_eq_left hs + rw [he] at h + exact aksBranch_sound hn hs (by omega) x hm hmb hpow h + · simp [aksStaticBranch,hs] at h + · intro hp + obtain ⟨s,hs,hsn,hcop,ho⟩ := auxiliary_prime_exists hn hm hmb + let : NeZero s := ⟨hs.ne_zero⟩ + refine ⟨prime_not_perfectPower hp,⟨s,by omega⟩,?_⟩ + have he : aksStaticBranch n s=aksBranch n s := dite_eq_left hs + change (aksStaticBranch n s).eval x 0=true + rw [he] + exact aksBranch_complete hn hs hsn x hp hcop ho + +end ExactQuantumFactoring.BitArithmetic + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/BoundedStack.lean b/lean/OAI/Computability/QuantumFactoring/BoundedStack.lean new file mode 100644 index 0000000000000000000000000000000000000000..e382d697745a2ac6e26adc6121d94ed8597a03c9 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/BoundedStack.lean @@ -0,0 +1,123 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.WordBlocks + +namespace OAI + +section +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators + + +namespace ExactQuantumFactoring.BitArithmetic +open BooleanNetwork + +/-- A fixed-capacity little-endian word stack. No dynamic address or unbounded +list is part of the corresponding Boolean network. -/ +def stackEncoding (s w : ℕ) (xs : List (Basis w)) : Basis (s*w) := fun j => + let ij := finProdFinEquiv.symm j + (xs[ij.1.val]?.getD (fun _ => false)) ij.2 + +lemma block_stackEncoding (s w : ℕ) (xs : List (Basis w)) (i : Fin s) : + block (stackEncoding s w xs) i = xs[i.val]?.getD (fun _ => false) := by + funext j + simp [block,stackEncoding] + +/-- Pop the top, padding the empty end with zero. -/ +def stackPop (s w : ℕ) : BooleanNetwork (s*w) (s*w) := + wordBlocks (fun i : Fin s => if h : i.val+1 if h : i.val=0 then a + else v.comp (blockNet s w ⟨i.val-1,by omega⟩)) + +lemma stackPop_value {s w : ℕ} (x : Basis (s*w)) (i : Fin s) : + block ((stackPop s w).eval x) i = + if h : i.val+1 false) := by + rw [stackPop,wordBlocks_eval] + split_ifs + · rfl + · funext j + simp [wordConstant] + +lemma stackPush_value {k s w : ℕ} (a : BooleanNetwork k w) (v : BooleanNetwork k (s*w)) + (x : Basis k) (i : Fin s) : + block ((stackPush a v).eval x) i = + if _h : i.val=0 then a.eval x else block (v.eval x) ⟨i.val-1,by omega⟩ := by + rw [stackPush,wordBlocks_eval] + split_ifs <;> rfl + +lemma block_ext {s w : ℕ} {x y : Basis (s*w)} + (h : ∀ i : Fin s, block x i=block y i) : x=y := by + funext j + obtain ⟨⟨i,k⟩,rfl⟩ := finProdFinEquiv.surjective j + exact congrFun (h i) k + +lemma stackPop_encoding {s w : ℕ} (xs : List (Basis w)) (h : xs.length ≤ s) : + (stackPop s w).eval (stackEncoding s w xs)=stackEncoding s w xs.tail := by + apply block_ext + intro i + rw [stackPop_value,block_stackEncoding] + split_ifs with hi + · rw [block_stackEncoding] + cases xs <;> simp + · have hh : xs.tail[i.val]?=none := by + apply List.getElem?_eq_none + simp only [List.length_tail] + omega + rw [hh] + rfl + +lemma stackPush_encoding {k s w : ℕ} (a : BooleanNetwork k w) (v : BooleanNetwork k (s*w)) + (x : Basis k) (xs : List (Basis w)) (hv : v.eval x=stackEncoding s w xs) : + (stackPush a v).eval x=stackEncoding s w (a.eval x::xs) := by + apply block_ext + intro i + rw [stackPush_value,block_stackEncoding] + split_ifs with hi + · simp [hi] + · rw [hv,block_stackEncoding] + obtain ⟨j,hj⟩ := Nat.exists_eq_succ_of_ne_zero hi + simp [hj] + +lemma stackPop_count (s w : ℕ) : (stackPop s w).net.count ≤ s*w*w := by + apply wordBlocks_count + intro i + by_cases hi : i.val+1 c.net.count) he + rw [hh,blockNet_count] + omega + · have he : (if h : i.val+1 c.net.count) he + rw [hh,wordConstant_count] + +lemma stackPush_count {k s w : ℕ} (a : BooleanNetwork k w) (v : BooleanNetwork k (s*w)) : + (stackPush a v).net.count ≤ s*w*(a.net.count+v.net.count) := by + apply wordBlocks_count + intro i + by_cases hi : i.val=0 + · have he : (if h : i.val=0 then a else v.comp (blockNet s w ⟨i.val-1,by omega⟩))=a := dite_eq_left hi + have hh := congrArg (fun c : BooleanNetwork k w => c.net.count) he + rw [hh] + omega + · have he : (if h : i.val=0 then a else v.comp (blockNet s w ⟨i.val-1,by omega⟩))= + v.comp (blockNet s w ⟨i.val-1,by omega⟩) := dite_eq_right hi + have hh := congrArg (fun c : BooleanNetwork k w => c.net.count) he + rw [hh,count_comp,blockNet_count] + omega + +end ExactQuantumFactoring.BitArithmetic + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/CRTLevels.lean b/lean/OAI/Computability/QuantumFactoring/CRTLevels.lean new file mode 100644 index 0000000000000000000000000000000000000000..16368094fd6c7a4898a18310effb5efd77224eb3 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/CRTLevels.lean @@ -0,0 +1,134 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.LevelIndependence +import OAI.Computability.QuantumFactoring.PrimePowerLevels + +namespace OAI + +section +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators + + +open scoped BigOperators +namespace ExactQuantumFactoring + +abbrev Component (m : ℕ) := {p : ℕ // p ∈ m.primeFactors} + +instance componentNeZero (m : ℕ) (p : Component m) : + NeZero (p.val ^ m.factorization p.val) := + ⟨pow_ne_zero _ (Nat.mem_primeFactors.mp p.property).1.ne_zero⟩ + +abbrev ComponentUnits (m : ℕ) (p : Component m) := + (ZMod (p.val ^ m.factorization p.val))ˣ + +noncomputable def unitCRT (m : ℕ) (hm : m ≠ 0) : + (ZMod m)ˣ ≃* (∀ p : Component m, ComponentUnits m p) := + (Units.mapEquiv (ZMod.equivPi m hm).toMulEquiv).trans MulEquiv.piUnits + +lemma component_order_level_lt {m n : ℕ} (hm : m ≠ 0) (hmn : m < 2^n) + (p : Component m) (a : ComponentUnits m p) : padicValNat 2 (orderOf a) < n := by + have ho : 0 < orderOf a := orderOf_pos a + have hpow : 2^padicValNat 2 (orderOf a) ≤ orderOf a := Nat.le_of_dvd ho pow_padicValNat_dvd + have hcard : Nat.card (ComponentUnits m p) = (p.val ^ m.factorization p.val).totient := by + rw [Nat.card_eq_fintype_card, ZMod.card_units_eq_totient] + apply (Nat.pow_lt_pow_iff_right (by decide : 1 < 2)).mp + calc + _ ≤ orderOf a := hpow + _ ≤ Nat.card (ComponentUnits m p) := orderOf_le_card + _ = _ := hcard + _ ≤ p.val ^ m.factorization p.val := Nat.totient_le _ + _ ≤ m := Nat.le_of_dvd (Nat.pos_of_ne_zero hm) (Nat.ordProj_dvd _ _) + _ < 2^n := hmn + +noncomputable def componentLevel {m n : ℕ} (hm : m ≠ 0) (hmn : m < 2^n) + (p : Component m) (a : ComponentUnits m p) : Fin (n+1) := + ⟨padicValNat 2 (orderOf a), by have := component_order_level_lt hm hmn p a; omega⟩ + +lemma componentLevel_card {m n : ℕ} (hm : m ≠ 0) (hmn : m < 2^n) + (p : Component m) (t : Fin (n+1)) : + Fintype.card {a : ComponentUnits m p // componentLevel hm hmn p a = t} = + primePowerLevelCard p.val (m.factorization p.val) t.val := by + classical + rw [primePowerLevelCard, Nat.card_eq_fintype_card] + apply Fintype.card_congr + exact Equiv.subtypeEquivRight (fun a => Fin.ext_iff) + +/-- Closed form for the number of favorable unit residues. Only n+1 levels +and the prime-power factors occur; there is no modulo-m residue enumeration. -/ +def favorableCount (m n : ℕ) : ℕ := + m.totient - ∑ t : Fin (n+1), ∏ p : Component m, + closedLevelCount (primePowerUnitCount p.val (m.factorization p.val)) t.val + +noncomputable def FavorableUnit {m n : ℕ} (hm : m ≠ 0) (hmn : m < 2^n) + (p₀ : Component m) (a : (ZMod m)ˣ) : Prop := + ¬ ∀ p, componentLevel hm hmn p (unitCRT m hm a p) = + componentLevel hm hmn p₀ (unitCRT m hm a p₀) + +lemma equal_component_card {m n : ℕ} (hm : m ≠ 0) (hmn : m < 2^n) + (hodd : Odd m) (p₀ : Component m) : + Fintype.card {a : ∀ p : Component m, ComponentUnits m p // + ∀ p, componentLevel hm hmn p (a p) = componentLevel hm hmn p₀ (a p₀)} = + ∑ t : Fin (n+1), ∏ p : Component m, + closedLevelCount (primePowerUnitCount p.val (m.factorization p.val)) t.val := by + classical + rw [allEqualLevel_card p₀] + apply Finset.sum_congr rfl + intro t ht + apply Finset.prod_congr rfl + intro p hp + rw [componentLevel_card] + have pp := Nat.mem_primeFactors.mp p.property + exact primePowerLevelCard_eq pp.1 (by + intro h + apply (Nat.not_even_iff_odd.mpr hodd) + exact even_iff_two_dvd.mpr (h ▸ pp.2.1)) + (pp.1.factorization_pos_of_dvd hm pp.2.1) _ + +/-- The exact source F is the cardinality of the actual CRT favorable event. -/ +theorem favorableCount_eq_card {m n : ℕ} (hm : m ≠ 0) (hmn : m < 2^n) + (hodd : Odd m) (p₀ : Component m) : + favorableCount m n = Nat.card {a : (ZMod m)ˣ // FavorableUnit hm hmn p₀ a} := by + classical + let : NeZero m := ⟨hm⟩ + rw [Nat.card_eq_fintype_card] + unfold FavorableUnit + rw [Fintype.card_subtype_compl, ZMod.card_units_eq_totient] + unfold favorableCount + congr 1 + rw [← equal_component_card hm hmn hodd p₀] + exact (Fintype.card_congr ((unitCRT m hm).toEquiv.subtypeEquiv (fun _ => Iff.rfl))).symm + +/-- At least half the units are favorable whenever there are two distinct +odd prime-power components, exactly as in Section 5. -/ +theorem totient_le_twice_favorableCount {m n : ℕ} (hm : m ≠ 0) (hmn : m < 2^n) + (hodd : Odd m) (p₀ p₁ : Component m) (hne : p₁ ≠ p₀) : + m.totient ≤ 2 * favorableCount m n := by + classical + let : NeZero m := ⟨hm⟩ + have hhalf := twice_allEqualLevel_card_le p₀ p₁ hne (componentLevel hm hmn) (by + intro t + rw [componentLevel_card] + have pp := Nat.mem_primeFactors.mp p₀.property + have hpp := primePowerLevelCard_half pp.1 (by + intro h + apply (Nat.not_even_iff_odd.mpr hodd) + exact even_iff_two_dvd.mpr (h ▸ pp.2.1)) + (pp.1.factorization_pos_of_dvd hm pp.2.1) t.val + rw [ZMod.card_units_eq_totient, Nat.totient_prime_pow pp.1 + (pp.1.factorization_pos_of_dvd hm pp.2.1)] + simpa only [primePowerUnitCount, mul_comm] using hpp) + rw [equal_component_card hm hmn hodd p₀] at hhalf + have hc : Fintype.card (∀ p : Component m, ComponentUnits m p) = m.totient := by + rw [← Fintype.card_congr (unitCRT m hm).toEquiv, ZMod.card_units_eq_totient] + rw [hc] at hhalf + unfold favorableCount + omega + +end ExactQuantumFactoring + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/CanonicalResidueCircuit.lean b/lean/OAI/Computability/QuantumFactoring/CanonicalResidueCircuit.lean new file mode 100644 index 0000000000000000000000000000000000000000..4b482f07daed0da2024fee684f3c942511163e04 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/CanonicalResidueCircuit.lean @@ -0,0 +1,159 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.TablePrimeSupport + +namespace OAI + +section +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators + + +namespace ExactQuantumFactoring +open BooleanNetwork +namespace BitArithmetic +attribute [local instance] Classical.propDecidable + +def dividesOn {k n : ℕ} (p m : BooleanNetwork k n) : BooleanNetwork k 1 := + zeroWord ((m.pair p).comp (mod n)) +lemma dividesOn_value {k n : ℕ} (p m : BooleanNetwork k n) (x : Basis k) : + (dividesOn p m).eval x 0=true ↔ (bitsValue (p.eval x)).toNat∣(bitsValue (m.eval x)).toNat := by + rw [dividesOn,zeroWord_value,eval_comp,eval_pair,mod_word,BitVec.toNat_umod,Nat.dvd_iff_mod_eq_zero] +lemma dividesOn_count {k n : ℕ} (p m : BooleanNetwork k n) : + (dividesOn p m).net.count ≤ p.net.count+m.net.count+216*n*n+154*n+27 := by + have hh:=zeroWord_count ((m.pair p).comp (mod n)) + have hd:=mod_count n + simp only [count_comp,count_pair] at hh + exact hh.trans (by omega) + +def leastDivisorTest {k n : ℕ} (ps : List (BooleanNetwork k n)) (m p : BooleanNetwork k n) : + BooleanNetwork k 1 := all (ps.map (fun q=>(dividesOn q m).bnot.bor (wordLe p q))) + +lemma leastDivisorTest_value {k n : ℕ} (ps : List (BooleanNetwork k n)) + (m p : BooleanNetwork k n) (x : Basis k) : + (leastDivisorTest ps m p).eval x 0=true ↔ + leastDivisorIn (ps.map (fun q=>(bitsValue (q.eval x)).toNat)) + (bitsValue (m.eval x)).toNat (bitsValue (p.eval x)).toNat := by + simp only [leastDivisorTest,all_eval,List.forall_mem_map,eval_bor,Bool.or_eq_true, + bnot_value,dividesOn_value,wordLe_eval,decide_eq_true_eq,leastDivisorIn, + List.forall_mem_map,or_iff_not_imp_left,not_not] + +lemma leastDivisorTest_count {k n c : ℕ} (ps : List (BooleanNetwork k n)) + (m p : BooleanNetwork k n) (hps : ∀ q∈ps,q.net.count≤c) + (hm : m.net.count≤c) (hp : p.net.count≤c) : + (leastDivisorTest ps m p).net.count≤ps.length*(4*c+216*n*n+202*n+42)+1 := by + have hh:=all_count (ps.map (fun q=>(dividesOn q m).bnot.bor (wordLe p q))) + (c:=4*c+216*n*n+202*n+41) (by + intro b hb + obtain ⟨q,hq,rfl⟩:=List.mem_map.mp hb + have hd:=dividesOn_count q m + have hl:=wordLe_count p q + have hqc:=hps q hq + simp only [count_bor,count_bnot] + omega) + change (all (ps.map (fun q=>(dividesOn q m).bnot.bor (wordLe p q)))).net.count ≤ _ + simp only [List.length_map] at hh + omega + +def componentCongruence {k n : ℕ} (ps : List (BooleanNetwork k n)) + (a m p : BooleanNetwork k n) : BooleanNetwork k 1 := + let q:=primeComponent m p + equalOn ((a.pair q).comp (mod n)) (wordMux (leastDivisorTest ps m p) + (wordConstant (BitVec.ofNat n 1)) (natSubOn q (wordConstant (BitVec.ofNat n 1)))) + +lemma componentCongruence_value {k n : ℕ} (ps : List (BooleanNetwork k n)) + (a m p : BooleanNetwork k n) (x : Basis k) + (hm : 2≤(bitsValue (m.eval x)).toNat) (hp : ((bitsValue (p.eval x)).toNat).Prime) : + (componentCongruence ps a m p).eval x 0=true ↔ + (bitsValue (a.eval x)).toNat % Nat.gcd (bitsValue (m.eval x)).toNat + ((bitsValue (p.eval x)).toNat^n)= + if leastDivisorIn (ps.map (fun q=>(bitsValue (q.eval x)).toNat)) + (bitsValue (m.eval x)).toNat (bitsValue (p.eval x)).toNat + then 1 else Nat.gcd (bitsValue (m.eval x)).toNat ((bitsValue (p.eval x)).toNat^n)-1 := by + have h1 : 1<2^n := by have hh:=(bitsValue (m.eval x)).isLt;omega + have hq : (bitsValue ((primeComponent m p).eval x)).toNat= + Nat.gcd (bitsValue (m.eval x)).toNat ((bitsValue (p.eval x)).toNat^n) := by + rw [primeComponent_value m p x (by omega) hp, + prime_component_gcd (by omega) hp (bitsValue (m.eval x)).isLt.le] + rw [componentCongruence,equalOn_value,eval_comp,eval_pair,mod_word,BitVec.toNat_umod,hq,wordMux_eval] + by_cases ht : (leastDivisorTest ps m p).eval x 0=true + · rw [ite_eq_left ht,ite_eq_left ((leastDivisorTest_value ps m p x).mp ht),wordConstant_eval, + BitVec.toNat_ofNat,Nat.mod_eq_of_lt h1] + · rw [ite_eq_right ht,ite_eq_right (fun h=>ht ((leastDivisorTest_value ps m p x).mpr h)),natSubOn_value, + hq,wordConstant_eval,BitVec.toNat_ofNat,Nat.mod_eq_of_lt h1] + +def tableCanonicalNet {k n : ℕ} (ps : List (BooleanNetwork k n)) + (a m : BooleanNetwork k n) : BooleanNetwork k 1 := + (wordLt a m).band (all (ps.map (fun p=>(dividesOn p m).bnot.bor (componentCongruence ps a m p)))) + +lemma tableCanonicalNet_value {k n : ℕ} (ps : List (BooleanNetwork k n)) + (a m : BooleanNetwork k n) (x : Basis k) + (hm : 2≤(bitsValue (m.eval x)).toNat) + (hps : ∀ p∈ps,((bitsValue (p.eval x)).toNat).Prime) : + (tableCanonicalNet ps a m).eval x 0=true ↔ + tableCanonical (ps.map (fun p=>(bitsValue (p.eval x)).toNat)) + (bitsValue (a.eval x)).toNat (bitsValue (m.eval x)).toNat n := by + rw [tableCanonicalNet,eval_band,Bool.and_eq_true,wordLt_eval,decide_eq_true_eq,tableCanonical] + apply and_congr_right + intro _ + simp only [all_eval,List.forall_mem_map,eval_bor,Bool.or_eq_true,bnot_value,dividesOn_value] + constructor + · intro h p hp hpd + exact (componentCongruence_value ps a m p x hm (hps p hp)).mp ((h p hp).resolve_left (not_not.mpr hpd)) + · intro h p hp + by_cases hpd : (bitsValue (p.eval x)).toNat∣(bitsValue (m.eval x)).toNat + · exact Or.inr ((componentCongruence_value ps a m p x hm (hps p hp)).mpr + (h p hp hpd)) + · exact Or.inl hpd +def componentCongruenceBound (n l c : ℕ) : ℕ := + c+3*primeComponentBound n c+216*n*n+500*n+100+ + l*(4*c+216*n*n+202*n+42) + +lemma componentCongruence_count {k n c : ℕ} (ps : List (BooleanNetwork k n)) + (a m p : BooleanNetwork k n) (hps : ∀ q∈ps,q.net.count≤c) + (ha : a.net.count≤c) (hm : m.net.count≤c) (hp : p.net.count≤c) : + (componentCongruence ps a m p).net.count≤componentCongruenceBound n ps.length c := by + have hq:=primeComponent_count m p hm hp + have hl:=leastDivisorTest_count ps m p hps hm hp + have he:=equalOn_count ((a.pair (primeComponent m p)).comp (mod n)) + (wordMux (leastDivisorTest ps m p) (wordConstant (BitVec.ofNat n 1)) + (natSubOn (primeComponent m p) (wordConstant (BitVec.ofNat n 1)))) + have hs:=natSubOn_count (primeComponent m p) (wordConstant (BitVec.ofNat n 1)) + have hd:=mod_count n + simp only [count_comp,count_pair,wordMux_count,wordConstant_count] at he hs + change (equalOn _ _).net.count≤_ + dsimp only [componentCongruenceBound] + omega + +def tableCanonicalBound (n l c : ℕ) : ℕ := + 2*c+48*n+10+l*(2*c+216*n*n+154*n+33+componentCongruenceBound n l c)+2 + +lemma tableCanonicalNet_count {k n c : ℕ} (ps : List (BooleanNetwork k n)) + (a m : BooleanNetwork k n) (hps : ∀ q∈ps,q.net.count≤c) + (ha : a.net.count≤c) (hm : m.net.count≤c) : + (tableCanonicalNet ps a m).net.count≤tableCanonicalBound n ps.length c := by + have hl:=wordLt_count a m + have hall:=all_count (ps.map (fun p=>(dividesOn p m).bnot.bor (componentCongruence ps a m p))) + (c:=2*c+216*n*n+154*n+32+componentCongruenceBound n ps.length c) (by + intro b hb + obtain ⟨p,hp,rfl⟩:=List.mem_map.mp hb + have hc:=componentCongruence_count ps a m p hps ha hm (hps p hp) + have hd:=dividesOn_count p m + have hp':=hps p hp + simp only [count_bor,count_bnot] + omega) + simp only [List.length_map] at hall + have hr : 2*c+216*n*n+154*n+32+componentCongruenceBound n ps.length c+1 = + 2*c+216*n*n+154*n+33+componentCongruenceBound n ps.length c := by omega + rw [hr] at hall + simp only [tableCanonicalNet,count_band,tableCanonicalBound] + omega +end BitArithmetic +end ExactQuantumFactoring + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/CanonicalTableEmission.lean b/lean/OAI/Computability/QuantumFactoring/CanonicalTableEmission.lean new file mode 100644 index 0000000000000000000000000000000000000000..b19461ae7e80dd01be8e5ea840ad5ba572bcffd7 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/CanonicalTableEmission.lean @@ -0,0 +1,46 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.CanonicalResidueCircuit +import OAI.Computability.QuantumFactoring.TableArithmeticEmission + +namespace OAI + + + +section +namespace ExactQuantumFactoring.NetworkEmission.NetEmits +open BitStackProgram BitStackProgram.Emits BitArithmetic +variable {α : Type} {ea : α→List Bool} {k n : α→ℕ} +lemma dividesOn {p m : ∀x,BooleanNetwork (k x) (n x)} (hk : Emits ea unaryCode k) + (hn : Emits ea unaryCode n) (hp : NetEmits ea p) (hm : NetEmits ea m) : + NetEmits ea (fun x=>BitArithmetic.dividesOn (p x) (m x)):=zeroWord hk hn ((hm.pair hp).comp (mod hn)) +lemma leastDivisorTest {ps : ∀x,List (BooleanNetwork (k x) (n x))} {m p : ∀x,BooleanNetwork (k x) (n x)} + (hk : Emits ea unaryCode k) (hn : Emits ea unaryCode n) (hps : NetsEmits ea ps) + (hm : NetEmits ea m) (hp : NetEmits ea p) : NetEmits ea (fun x=>BitArithmetic.leastDivisorTest (ps x) (m x) (p x)):=by + have hx:=(BitStackProgram.Emits.id (prodCode unaryCode ea)).precompose (fun x:Σa,Fin ((ps a).length)=>(x.2.val,x.1)) + have ht:=(dividesOn (hk.comp hx.snd) (hn.comp hx.snd) hps.get (hm.compInput hx.snd)).bnot.bor + (wordLe (hp.compInput hx.snd) hps.get (hn.comp hx.snd)) + exact (hps.map (g:=fun x q=>(BitArithmetic.dividesOn q (m x)).bnot.bor (BitArithmetic.wordLe (p x) q)) ht).all hk +lemma componentCongruence {ps : ∀x,List (BooleanNetwork (k x) (n x))} {a m p : ∀x,BooleanNetwork (k x) (n x)} + (hk : Emits ea unaryCode k) (hn : Emits ea unaryCode n) (hps : NetsEmits ea ps) + (ha : NetEmits ea a) (hm : NetEmits ea m) (hp : NetEmits ea p) : + NetEmits ea (fun x=>BitArithmetic.componentCongruence (ps x) (a x) (m x) (p x)):=by + have hq:=primeComponent hk hn hm hp + have h1:=wordConst hk hn (const _ _ 1) + exact ((ha.pair hq).comp (mod hn)).equalOn + ((leastDivisorTest hk hn hps hm hp).wordMux h1 (natSubOn hk hn hq h1) hn) hn +lemma tableCanonical {ps : ∀x,List (BooleanNetwork (k x) (n x))} {a m : ∀x,BooleanNetwork (k x) (n x)} + (hk : Emits ea unaryCode k) (hn : Emits ea unaryCode n) (hps : NetsEmits ea ps) + (ha : NetEmits ea a) (hm : NetEmits ea m) : NetEmits ea (fun x=>BitArithmetic.tableCanonicalNet (ps x) (a x) (m x)):=by + have hx:=(BitStackProgram.Emits.id (prodCode unaryCode ea)).precompose (fun x:Σa,Fin ((ps a).length)=>(x.2.val,x.1)) + have hm':=hm.compInput hx.snd + have ht:=(dividesOn (hk.comp hx.snd) (hn.comp hx.snd) hps.get hm').bnot.bor + (componentCongruence (hk.comp hx.snd) (hn.comp hx.snd) (hps.comp hx.snd) (ha.compInput hx.snd) hm' hps.get) + exact (wordLt ha hm hn).band ((hps.map (g:=fun x p=>(BitArithmetic.dividesOn p (m x)).bnot.bor + (BitArithmetic.componentCongruence (ps x) (a x) (m x) p)) ht).all hk) +end ExactQuantumFactoring.NetworkEmission.NetEmits + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/CanonicalTransition.lean b/lean/OAI/Computability/QuantumFactoring/CanonicalTransition.lean new file mode 100644 index 0000000000000000000000000000000000000000..f629dcadc26871b127d837396f37f489facd4b35 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/CanonicalTransition.lean @@ -0,0 +1,37 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.ListTransition +import OAI.Computability.QuantumFactoring.FavorableSplit + +namespace OAI + +section +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators + + +namespace ExactQuantumFactoring +open scoped BigOperators +open Exactness RepeatedTrials + +noncomputable def canonicalList {m : ℕ} (hm : m≠0) (p₀ : Component m) (K : ℕ) : + Fin K→Basis (Nat.clog 2 m) := fun i => + (bitsEquiv _).symm (BitVec.ofNat (Nat.clog 2 m) (if i.val=0 then (canonicalUnit hm p₀ : ZMod m).val else 0)) + +lemma canonicalList_good {m n K : ℕ} (hm : m≠0) (hb : m<2^n) (hodd : Odd m) + (p₀ p₁ : Component m) (hne : p₁≠p₀) (hK : 0by + simp only [Function.comp_apply,natBasis_value,Nat.mod_eq_of_lt (hb a ha),id_eq]) + _ = xs := List.map_id xs + +lemma canonical_length (n : ℕ) (xs : List ℕ) : (canonicalWords n xs).length=xs.length := List.length_map (natBasis n) +lemma canonical_append (n : ℕ) (xs ys : List ℕ) : + canonicalWords n (xs++ys)=canonicalWords n xs++canonicalWords n ys := List.map_append + +end ExactQuantumFactoring.BitArithmetic + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/ChildQueue.lean b/lean/OAI/Computability/QuantumFactoring/ChildQueue.lean new file mode 100644 index 0000000000000000000000000000000000000000..a60cdd9de522094fd6f91fe4db113a0db8cc9d5b --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/ChildQueue.lean @@ -0,0 +1,131 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BooleanFold +import OAI.Computability.QuantumFactoring.SplitCandidate +import OAI.Computability.QuantumFactoring.BoundedStack + +namespace OAI + +section +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators + + +namespace ExactQuantumFactoring.BitArithmetic +open BooleanNetwork +namespace ChildQueue + +def predBits {w : ℕ} (a : Basis w) : Basis w := + (sub w).eval (Fin.append a (fun i => (BitVec.ofNat w 1).getLsbD i.val)) + +/-- Children from the distinct prime fields, ignoring zero padding and 2. +Repeated labels in DIFFERENT node records are not identified. -/ +def kids {w : ℕ} : List (Basis w) → List (Basis w) + | [] => [] + | a::as => if 2<(bitsValue a).toNat ∧ a∉as then predBits a::kids as else kids as + +def wordMember {k w : ℕ} (a : BooleanNetwork k w) (as : List (BooleanNetwork k w)) : + BooleanNetwork k 1 := any (as.map (fun b => (a.pair b).comp (wordEq w))) + +lemma wordMember_eval {k w : ℕ} (a : BooleanNetwork k w) (as : List (BooleanNetwork k w)) (x : Basis k) : + (wordMember a as).eval x 0=true ↔ a.eval x∈as.map (fun b=>b.eval x) := by + rw [wordMember,any_eval] + constructor + · rintro ⟨c,hc,ht⟩ + obtain ⟨b,hb,rfl⟩ := List.mem_map.mp hc + rw [eval_comp,eval_pair,wordEq_eval,decide_eq_true_eq] at ht + exact List.mem_map.mpr ⟨b,hb,((bitsEquiv w).injective ht).symm⟩ + · rintro hm + obtain ⟨b,hb,he⟩ := List.mem_map.mp hm + refine ⟨(a.pair b).comp (wordEq w),List.mem_map.mpr ⟨b,hb,rfl⟩,?_⟩ + rw [eval_comp,eval_pair,wordEq_eval,decide_eq_true_eq,he] + + +def source (k s w : ℕ) : BooleanNetwork (k+s*w) k := select (Fin.castAdd (s*w)) +def queue (k s w : ℕ) : BooleanNetwork (k+s*w) (s*w) := select (Fin.natAdd k) +def liftWord {k w : ℕ} (s : ℕ) (a : BooleanNetwork k w) := (source k s w).comp a + +def active {k w : ℕ} (a : BooleanNetwork k w) (as : List (BooleanNetwork k w)) : BooleanNetwork k 1 := + (wordLt (wordConstant (BitVec.ofNat w 2)) a).band (wordMember a as).bnot + +def pushOne {k w : ℕ} (s : ℕ) (a : BooleanNetwork k w) (as : List (BooleanNetwork k w)) : + BooleanNetwork (k+s*w) (k+s*w) := + (source k s w).pair + (wordMux ((source k s w).comp (active a as)) + (stackPush (((liftWord s a).pair (wordConstant (BitVec.ofNat w 1))).comp (sub w)) (queue k s w)) + (queue k s w)) + +/-- Tail before head: the recursive network occurs just ONCE in the syntax. +All original factor fields remain read-only while the bounded queue is updated. -/ +def pushAll {k w : ℕ} (s : ℕ) : List (BooleanNetwork k w) → BooleanNetwork (k+s*w) (k+s*w) + | [] => select id + | a::as => (pushAll s as).comp (pushOne s a as) + +lemma source_eval (k s w : ℕ) (x : Basis k) (y : Basis (s*w)) : + (source k s w).eval (Fin.append x y)=x := by + funext i + exact Fin.append_left _ _ _ +lemma queue_eval (k s w : ℕ) (x : Basis k) (y : Basis (s*w)) : + (queue k s w).eval (Fin.append x y)=y := by + funext i + exact Fin.append_right _ _ _ + +lemma active_eval {k w : ℕ} (hw : 2 ≤ w) (a : BooleanNetwork k w) + (as : List (BooleanNetwork k w)) (x : Basis k) : + (active a as).eval x 0=true ↔ 2<(bitsValue (a.eval x)).toNat ∧ a.eval x∉as.map (fun b=>b.eval x) := by + have hb : 2<2^w := (by norm_num : 2<2^2).trans_le (Nat.pow_le_pow_right (by decide) hw) + simp only [active,eval_band,Bool.and_eq_true,eval_bnot,Bool.not_eq_true',wordLt_eval, + wordConstant_eval,BitVec.toNat_ofNat,Nat.mod_eq_of_lt hb,decide_eq_true_eq] + have hm := wordMember_eval a as x + cases hh : (wordMember a as).eval x 0 <;> simp_all + +lemma pushOne_eval {k w : ℕ} (hw : 2 ≤ w) (s : ℕ) (a : BooleanNetwork k w) + (as : List (BooleanNetwork k w)) (x : Basis k) (ys : List (Basis w)) : + (pushOne s a as).eval (Fin.append x (stackEncoding s w ys))= + Fin.append x (stackEncoding s w + (if 2<(bitsValue (a.eval x)).toNat ∧ a.eval x∉as.map (fun b=>b.eval x) + then predBits (a.eval x)::ys else ys)) := by + have hv : ((((liftWord s a).pair (wordConstant (BitVec.ofNat w 1))).comp (sub w)).eval + (Fin.append x (stackEncoding s w ys)))=predBits (a.eval x) := by + rw [eval_comp,eval_pair,liftWord,eval_comp,source_eval] + unfold predBits + congr 2 + funext i + simp [wordConstant,eval_vector,eval_constant] + have hs := stackPush_encoding + (((liftWord s a).pair (wordConstant (BitVec.ofNat w 1))).comp (sub w)) + (queue k s w) (Fin.append x (stackEncoding s w ys)) ys (queue_eval k s w x _) + rw [hv] at hs + rw [pushOne,eval_pair,source_eval,wordMux_eval,eval_comp,source_eval,hs,queue_eval] + by_cases hc : 2<(bitsValue (a.eval x)).toNat ∧ a.eval x∉as.map (fun b=>b.eval x) + · rw [ite_eq_left ((active_eval hw a as x).mpr hc),ite_eq_left hc] + · rw [ite_eq_right (fun h=>hc ((active_eval hw a as x).mp h)),ite_eq_right hc] + +lemma pushAll_eval {k w : ℕ} (hw : 2 ≤ w) (s : ℕ) (as : List (BooleanNetwork k w)) + (x : Basis k) (ys : List (Basis w)) : + (pushAll s as).eval (Fin.append x (stackEncoding s w ys))= + Fin.append x (stackEncoding s w (kids (as.map (fun a=>a.eval x))++ys)) := by + induction as with + | nil => rfl + | cons a as ih => + rw [pushAll,eval_comp,ih,pushOne_eval hw,List.map_cons,kids] + split_ifs <;> rfl + +lemma predBits_value {w : ℕ} (hw : 1 ≤ w) (a : Basis w) (ha : 1 ≤ (bitsValue a).toNat) : + (bitsValue (predBits a)).toNat=(bitsValue a).toNat-1 := by + have hb : 1<2^w := Nat.one_lt_pow (by omega) (by decide) + rw [predBits,sub_word] + have hv : bitsValue (fun i : Fin w => (BitVec.ofNat w 1).getLsbD i.val)=BitVec.ofNat w 1 := bitsValue_bits _ + rw [hv,BitVec.toNat_sub_of_le] + · rw [BitVec.toNat_ofNat,Nat.mod_eq_of_lt hb] + · simpa only [BitVec.le_def,BitVec.toNat_ofNat,Nat.mod_eq_of_lt hb] using ha + +end ChildQueue +end ExactQuantumFactoring.BitArithmetic + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/ChildQueueBounds.lean b/lean/OAI/Computability/QuantumFactoring/ChildQueueBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..908a0030df5dac621eb0b815d725acfc4b9e2c45 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/ChildQueueBounds.lean @@ -0,0 +1,87 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.ChildQueue + +namespace OAI + +section +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators + + +namespace ExactQuantumFactoring.BitArithmetic.ChildQueue +open BooleanNetwork + +lemma wordMember_count {k w c : ℕ} (a : BooleanNetwork k w) (as : List (BooleanNetwork k w)) + (ha : a.net.count ≤ c) (hs : ∀ b∈as,b.net.count ≤ c) : + (wordMember a as).net.count ≤ as.length*(2*c+96*w+25)+1 := by + have h := any_count (as.map (fun b=>(a.pair b).comp (wordEq w))) (c:=2*c+96*w+21) (by + intro d hd + obtain ⟨b,hb,rfl⟩ := List.mem_map.mp hd + have hh := hs b hb + have he := wordEq_count w + simp only [count_comp,count_pair] + omega) + simpa only [wordMember,List.length_map,Nat.add_assoc] using h + +lemma active_count {k w c : ℕ} (a : BooleanNetwork k w) (as : List (BooleanNetwork k w)) + (ha : a.net.count ≤ c) (hs : ∀ b∈as,b.net.count ≤ c) : + (active a as).net.count ≤ c+49*w+11+as.length*(2*c+96*w+25) := by + have hm := wordMember_count a as ha hs + have hl := wordLt_count (wordConstant (n:=k) (BitVec.ofNat w 2)) a + rw [wordConstant_count] at hl + simp only [active,count_band,count_bnot] + omega + +def oneBound (s w c r : ℕ) := c+49*w+11+r*(2*c+96*w+25)+s*w*(c+159*w+6)+7*(s*w) + +lemma pushOne_count {k w c : ℕ} (s : ℕ) (a : BooleanNetwork k w) (as : List (BooleanNetwork k w)) + (ha : a.net.count ≤ c) (hs : ∀ b∈as,b.net.count ≤ c) : + (pushOne s a as).net.count ≤ oneBound s w c as.length := by + have hac := active_count a as ha hs + have hsub := sub_count w + have hh : ((((liftWord s a).pair (wordConstant (BitVec.ofNat w 1))).comp (sub w))).net.count ≤ + c+159*w+6 := by + simp only [count_comp,count_pair,liftWord,source,count_select,zero_add,wordConstant_count] + omega + have hpush := stackPush_count (((liftWord s a).pair (wordConstant (BitVec.ofNat w 1))).comp (sub w)) + (queue k s w) + simp only [queue,count_select,add_zero] at hpush + have hpush' := hpush.trans (Nat.mul_le_mul_left (s*w) hh) + simp only [pushOne,count_pair,wordMux_count,count_comp,source,queue,count_select,zero_add,add_zero] + dsimp only [oneBound] + omega + +lemma oneBound_mono (s w c : ℕ) {r t : ℕ} (h : r ≤ t) : oneBound s w c r ≤ oneBound s w c t := by + have hh := Nat.mul_le_mul_right (2*c+96*w+25) h + dsimp only [oneBound] + omega + +/-- The all-child queue update is quadratic in the number of prime fields, +not an exponentially duplicated expression. Bounds hold on ALL inputs. -/ +theorem pushAll_count {k w c : ℕ} (s : ℕ) (as : List (BooleanNetwork k w)) + (hs : ∀ b∈as,b.net.count ≤ c) : + (pushAll s as).net.count ≤ as.length*oneBound s w c as.length := by + induction as with + | nil=>simp [pushAll,count_select] + | cons a as ih=> + have ha := hs a (by simp) + have ht : ∀ b∈as,b.net.count ≤ c := fun b hb=> hs b (by simp [hb]) + have hi := ih ht + have hp := pushOne_count s a as ha ht + have hb := oneBound_mono s w c (Nat.le_succ as.length) + simp only [pushAll,count_comp,List.length_cons] + calc + _ ≤ as.length*oneBound s w c as.length+oneBound s w c as.length := Nat.add_le_add hi hp + _ ≤ as.length*oneBound s w c (as.length+1)+oneBound s w c (as.length+1) := + Nat.add_le_add (Nat.mul_le_mul_left _ hb) hb + _ = _ := by ring + +end ExactQuantumFactoring.BitArithmetic.ChildQueue + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/ChildQueueCorrect.lean b/lean/OAI/Computability/QuantumFactoring/ChildQueueCorrect.lean new file mode 100644 index 0000000000000000000000000000000000000000..60a87962f45ad7350d2350af50d50162815456d6 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/ChildQueueCorrect.lean @@ -0,0 +1,102 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.SortedEncoding +import OAI.Computability.QuantumFactoring.ChildQueue + +namespace OAI + +section +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators + + +namespace ExactQuantumFactoring.BitArithmetic.ChildQueue +open SortedWords + +def naturalKids (xs : List ℕ) : List ℕ := + (xs.dedup.filter (fun a=>2 by_cases ha : 2 + simp [naturalKids,hm,ha] + +lemma number_injective {w : ℕ} : Function.Injective (fun a : Basis w=>(bitsValue a).toNat) := by + intro a b h + exact (bitsEquiv w).injective (BitVec.eq_of_toNat_eq h) + +lemma kids_numbers {w : ℕ} (hw : 2 ≤ w) (xs : List (Basis w)) : + numbers (kids xs)=naturalKids (numbers xs) := by + induction xs with + | nil=>rfl + | cons a as ih=> + have hm : (bitsValue a).toNat∈numbers as ↔ a∈as := + List.mem_map_of_injective number_injective + simp only [numbers,List.map_cons] at ih ⊢ + rw [naturalKids_cons,kids] + by_cases hc : 2<(bitsValue a).toNat ∧ a∉as + · have hd : 2<(bitsValue a).toNat ∧ (bitsValue a).toNat∉numbers as := ⟨hc.1,fun h=>hc.2 (hm.mp h)⟩ + dsimp only [numbers] at hd + rw [ite_eq_left hc,ite_eq_left hd,List.map_cons,predBits_value (by omega) a (by omega),ih] + · have hd : ¬(2<(bitsValue a).toNat ∧ (bitsValue a).toNat∉numbers as) := by + rintro ⟨h1,h2⟩ + exact hc ⟨h1,fun h=>h2 (hm.mpr h)⟩ + dsimp only [numbers] at hd + rw [ite_eq_right hc,ite_eq_right hd,ih] + +/-- No factorization oracle is used in the queue circuit: the child list obtained +from the ACTUAL correct sorted prime fields is the source's exact ordered child +list, with distinct primes within one node and occurrence multiplicity outside it. -/ +lemma naturalKids_correct {N n : ℕ} {xs : List ℕ} (hN : 2 ≤ N) + (hx : CorrectEncoding N n xs) : naturalKids xs=AuxiliaryTree.children N := by + obtain ⟨ps,hp,hs,hprod,_,rfl⟩ := hx + let ys := (ps++List.replicate (n-ps.length) 0).dedup.filter (fun a=>222f ⟨d+i.val,by have:=i.isLt;omega⟩):=by + apply List.ext_getElem + · simp only [List.length_drop,List.length_ofFn] + · intro i h h' + simp only [List.getElem_drop,List.getElem_ofFn] +namespace NetEmits +variable {α : Type} {ea : α→List Bool} {k w K s : α→ℕ} +lemma wordMemberOfFn {a : ∀x,BooleanNetwork (k x) (w x)} {f : ∀x,Fin (K x)→BooleanNetwork (k x) (w x)} + (hk : Emits ea unaryCode k) (hw : Emits ea unaryCode w) (hK : Emits ea unaryCode K) + (ha : NetEmits ea a) + (hf : NetEmits (fun x:Σa,Fin (K a)=>prodCode unaryCode ea (x.2.val,x.1)) (fun x=>f x.1 x.2)) : + NetEmits ea (fun x=>BitArithmetic.ChildQueue.wordMember (a x) (List.ofFn (f x))):=by + simp only [BitArithmetic.ChildQueue.wordMember,List.map_ofFn] + apply anyOfFn hk hK + have hx:=(BitStackProgram.Emits.id (prodCode unaryCode ea)).precompose + (fun x:Σa,Fin (K a)=>(x.2.val,x.1)) + exact ((ha.compInput hx.snd).pair hf).comp (wordEq (hw.comp hx.snd)) +lemma wordMemberDrop {a : ∀x,BooleanNetwork (k x) (w x)} {f : ∀x,Fin (K x)→BooleanNetwork (k x) (w x)} + {d : α→ℕ} (hk : Emits ea unaryCode k) (hw : Emits ea unaryCode w) (hK : Emits ea unaryCode K) + (hd : Emits ea Nat.bits d) (ha : NetEmits ea a) + (hf : NetEmits (fun x:Σa,Fin (K a)=>prodCode unaryCode ea (x.2.val,x.1)) (fun x=>f x.1 x.2)) : + NetEmits ea (fun x=>BitArithmetic.ChildQueue.wordMember (a x) ((List.ofFn (f x)).drop (d x))):=by + have len:=(hK.unaryNat.natSub hd).boundedUnary hK (fun _=>Nat.sub_le _ _) + have hh : NetEmits ea (fun x=>BitArithmetic.ChildQueue.wordMember (a x) + (List.ofFn (fun i:Fin (K x-d x)=>f x ⟨d x+i.val,by have:=i.isLt;omega⟩))):=by + apply wordMemberOfFn hk hw len ha + have hx:=(BitStackProgram.Emits.id (prodCode unaryCode ea)).precompose + (fun x:Σa,Fin (K a-d a)=>(x.2.val,x.1)) + let inc:(Σa,Fin (K a-d a))→(Σa,Fin (K a)):=fun x=>⟨x.1,⟨d x.1+x.2.val,by have:=x.2.isLt;omega⟩⟩ + have hi:=((hd.comp hx.snd).natAdd hx.fst.unaryNat).boundedUnary (hK.comp hx.snd) (by + intro x;dsimp only;have:=x.2.isLt;omega) + exact hf.compInput ((hi.pair hx.snd).recode (by intros;rfl) : Emits _ _ inc) + exact hh.congr (fun x=>by rw [dropOfFn_eq]) +lemma childPushOneDrop {a : ∀x,BooleanNetwork (k x) (w x)} {f : ∀x,Fin (K x)→BooleanNetwork (k x) (w x)} + {d : α→ℕ} (hk : Emits ea unaryCode k) (hw : Emits ea unaryCode w) (hK : Emits ea unaryCode K) + (hs : Emits ea unaryCode s) (hd : Emits ea Nat.bits d) (ha : NetEmits ea a) + (hf : NetEmits (fun x:Σa,Fin (K a)=>prodCode unaryCode ea (x.2.val,x.1)) (fun x=>f x.1 x.2)) : + NetEmits ea (fun x=>BitArithmetic.ChildQueue.pushOne (s x) (a x) ((List.ofFn (f x)).drop (d x))):=by + have hsource:=left hk (hs.unaryMul hw) + have hqueue:=right hk (hs.unaryMul hw) + have hwidth:=hk.unaryAdd (hs.unaryMul hw) + have active:=((wordConst hk hw (const _ _ 2)).wordLt ha hw).band (wordMemberDrop hk hw hK hd ha hf).bnot + exact hsource.pair ((hsource.comp active).wordMux + (stackPush hwidth hs hw (((hsource.comp ha).pair (wordConst hwidth hw (const _ _ 1))).comp (sub hw)) hqueue) hqueue (hs.unaryMul hw)) +lemma childPushAll {f : ∀x,Fin (K x)→BooleanNetwork (k x) (w x)} + (hk : Emits ea unaryCode k) (hw : Emits ea unaryCode w) (hK : Emits ea unaryCode K) + (hs : Emits ea unaryCode s) + (hf : NetEmits (fun x:Σa,Fin (K a)=>prodCode unaryCode ea (x.2.val,x.1)) (fun x=>f x.1 x.2)) : + NetEmits ea (fun x=>BitArithmetic.ChildQueue.pushAll (s x) (List.ofFn (f x))):=by + let F:=fun x j=>BitArithmetic.ChildQueue.pushAll (s x) ((List.ofFn (f x)).drop (K x-j)) + have h0 : NetEmits ea (fun x=>F x 0):=by + refine (identity (hk.unaryAdd (hs.unaryMul hw))).congr ?_ + intro x + dsimp only [F] + rw [Nat.sub_zero,List.drop_eq_nil_of_le (by simp only [List.length_ofFn];exact le_rfl)] + rfl + have step : NetEmits (fun x:Σa,Fin (K a)=>prodCode ea (prodCode unaryCode packCode) + (x.1,(x.2.val,erasePack (F x.1 x.2.val)))) (fun x=>F x.1 (x.2.val+1)):=by + have hx:=(BitStackProgram.Emits.id (prodCode ea (prodCode unaryCode packCode))).precompose + (fun x:Σa,Fin (K a)=>(x.1,(x.2.val,erasePack (F x.1 x.2.val)))) + have hLen:=hK.comp hx.fst + let y : (Σa,Fin (K a))→(Σa,Fin (K a)):=fun x=>⟨x.1,⟨K x.1-(x.2.val+1),by have:=x.2.isLt;omega⟩⟩ + have hi:=(hLen.unaryNat.natSub (hx.snd.fst.unaryNat.natAdd (const _ _ 1))).boundedUnary hLen (fun _=>Nat.sub_le _ _) + have hy : Emits _ (fun x:Σa,Fin (K a)=>prodCode unaryCode ea (x.2.val,x.1)) y:= + (hi.pair hx.fst).recode (by intros;rfl) + have hfields : NetEmits (fun z:Σx:Σa,Fin (K a),Fin (K x.1)=>prodCode unaryCode + (fun x:Σa,Fin (K a)=>prodCode ea (prodCode unaryCode packCode) (x.1,(x.2.val,erasePack (F x.1 x.2.val)))) (z.2.val,z.1)) + (fun z=>f z.1.1 z.2):=by + have hz:=(BitStackProgram.Emits.id (prodCode unaryCode (prodCode ea (prodCode unaryCode packCode)))).precompose + (fun z:Σx:Σa,Fin (K a),Fin (K x.1)=>(z.2.val,(z.1.1,(z.1.2.val,erasePack (F z.1.1 z.1.2.val))))) + exact hf.compInput ((hz.fst.pair hz.snd.fst).recode (g:=fun z:Σx:Σa,Fin (K a),Fin (K x.1)=>(⟨z.1.1,z.2⟩ : Σa,Fin (K a))) (by intros;rfl)) + have hnew:=(ofCanonical hx.snd.snd).comp (childPushOneDrop (f:=fun x=>f x.1) (a:=fun x=>f (y x).1 (y x).2) (hk.comp hx.fst) (hw.comp hx.fst) + hLen (hs.comp hx.fst) (hLen.unaryNat.natSub hx.snd.fst.unaryNat) (hf.compInput hy) hfields) + convert hnew using 1 + funext x + dsimp only [F] + rw [dropOfFn_step _ x.2.isLt,BitArithmetic.ChildQueue.pushAll] + have hwidth:=(hk.unaryPoly.add (hs.unaryPoly.mul hw.unaryPoly)).pull (fun x:Σa,Fin (K a+1)=>x.1) + obtain ⟨p,hp⟩:=countPolyIndexed hK hf + have hc : PolyAt (fun x:Σa,Fin (K a+1)=>(ea x.1).length) (fun x=>p.eval (ea x.1).length):=⟨p,fun _=>le_rfl⟩ + have hS:=hs.unaryPoly.pull (fun x:Σa,Fin (K a+1)=>x.1) + have hW:=hw.unaryPoly.pull (fun x:Σa,Fin (K a+1)=>x.1) + have hL:=hK.unaryPoly.pull (fun x:Σa,Fin (K a+1)=>x.1) + have hone:=(((hc.add ((PolyAt.const _ 49).mul hW)).add (PolyAt.const _ 11)).add + (hL.mul ((((PolyAt.const _ 2).mul hc).add ((PolyAt.const _ 96).mul hW)).add (PolyAt.const _ 25)))).add + ((hS.mul hW).mul ((hc.add ((PolyAt.const _ 159).mul hW)).add (PolyAt.const _ 6))) |>.add + ((PolyAt.const _ 7).mul (hS.mul hW)) + have hb : NetworkAt (fun x:Σa,Fin (K a+1)=>(ea x.1).length) (fun x=>F x.1 x.2.val):=by + exact (hL.mul hone).of_le (by + intro x + have h:=BitArithmetic.ChildQueue.pushAll_count (s x.1) ((List.ofFn (f x.1)).drop (K x.1-x.2.val)) + (c:=p.eval (ea x.1).length) (by + intro b hb + obtain ⟨i,rfl⟩:=List.mem_ofFn.mp (List.mem_of_mem_drop hb) + exact hp ⟨x.1,i⟩) + have hl:((List.ofFn (f x.1)).drop (K x.1-x.2.val)).length≤K x.1:=by + simp only [List.length_drop,List.length_ofFn];omega + exact h.trans (Nat.mul_le_mul hl (BitArithmetic.ChildQueue.oneBound_mono _ _ _ hl))) + simpa only [F,Nat.sub_self,List.drop_zero] using boundedStages hK h0 step hwidth hwidth hb +end NetEmits +end ExactQuantumFactoring.NetworkEmission + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/CircuitBooleanEmission.lean b/lean/OAI/Computability/QuantumFactoring/CircuitBooleanEmission.lean new file mode 100644 index 0000000000000000000000000000000000000000..43a5b9d6bd282c773d01458c5c49d5bf1d9339e2 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/CircuitBooleanEmission.lean @@ -0,0 +1,85 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BooleanOracle +import OAI.Computability.QuantumFactoring.NetworkEmissionModel +import OAI.Computability.QuantumFactoring.CircuitEmissionModel + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.CircuitEmission +open NetworkEmission + +def notOp (t : ℕ) : Op:=⟨plainGate .not,[t]⟩ +def cnotOp (a t : ℕ) : Op:=⟨plainGate .cnot,[a,t]⟩ +def toffoliOp (a b t : ℕ) : Op:=⟨plainGate .toffoli,[a,b,t]⟩ +lemma erase_notAt {q : ℕ} (t : Fin q) : eraseOp (notAt t)=notOp t.val:=rfl +lemma erase_cnotAt {q : ℕ} (a t : Fin q) (h : a≠t) : eraseOp (cnotAt a t h)=cnotOp a.val t.val:=rfl +lemma erase_toffoliAt {q : ℕ} (a b t : Fin q) (h : a≠b) (ha : a≠t) (hb : b≠t) : + eraseOp (toffoliAt a b t h ha hb)=toffoliOp a.val b.val t.val:=rfl + +def nodeOps (t : ℕ) : Node→List Op + | .constant false=>[] + | .constant true=>[notOp t] + | .copy a=>[cnotOp a t] + | .neg a=>[cnotOp a t,notOp t] + | .conj a b=>if a=b then [cnotOp a t] else [toffoliOp a b t] +lemma erase_node_compile {n q : ℕ} (h : n+1≤q) (o : BoolNode n) : + (o.compileOp h).compile.map eraseOp=nodeOps n (eraseNode o):=by + cases o with + | constant b=>cases b <;> rfl + | copy a=>rfl + | neg a=>rfl + | conj a b=> + simp only [BoolNode.compileOp,BooleanOp.compile,eraseNode,nodeOps] + simp only [Fin.ext_iff,Fin.val_castLE] + split_ifs <;> rfl + +def netOps (n : ℕ) (xs : List Node) : List Op:= + (xs.mapIdx (fun i o=>nodeOps (n+i) o)).flatten +lemma netOps_append_one (n : ℕ) (xs : List Node) (o : Node) : + netOps n (xs++[o])=netOps n xs++nodeOps (n+xs.length) o:=by + simp [netOps] +lemma erase_net_compile {n k q : ℕ} (p : BoolNet n k) (h : k≤q) : + (p.program h).compile.map eraseOp=netOps n (eraseNet p):=by + induction p with + | input=>rfl + | @add k p o ih=> + simp only [BoolNet.program,BooleanProgram.compile,List.flatMap_append,List.flatMap_singleton, + List.map_append,eraseNet,netOps_append_one] + rw [←BooleanProgram.compile,ih,erase_node_compile,eraseNet_length,←p.width_eq] + +def copyOps (k : ℕ) (xs : List ℕ) : List Op:=xs.mapIdx (fun i a=>cnotOp a (k+i)) +lemma erase_copyPrefix {k m : ℕ} (f : Fin m→Fin k) (t : ℕ) (h : t ≤ m) : + (BooleanNetwork.copyPrefix f t h).compile.map eraseOp= + copyOps k (List.ofFn (fun i : Fin t=>(f (i.castLE h)).val)):=by + induction t with + | zero=>rfl + | succ t ih=> + simp only [BooleanNetwork.copyPrefix,BooleanProgram.compile,List.flatMap_append, + List.flatMap_singleton,List.map_append] + rw [←BooleanProgram.compile,ih] + rw [List.ofFn_succ',List.concat_eq_append] + simp only [copyOps,List.mapIdx_append_one,List.length_ofFn] + rfl + +def oracleOps (a : NetworkEmission.Data) : List Op:= + let p:=netOps a.inputs a.nodes + p++copyOps (a.inputs+a.nodes.length) a.outputs++p.reverse.map Op.reverse +lemma erase_oracle {n m : ℕ} (a : BooleanNetwork n m) : + a.oracle.map eraseOp=oracleOps (NetworkEmission.erase a):=by + simp only [BooleanNetwork.oracle,List.map_append,List.map_map,List.map_reverse] + have hr : (eraseOp ∘ (Instruction.reverse : Instruction (a.width+m)→_))=Op.reverse ∘ eraseOp:=rfl + rw [hr,←List.map_map,erase_net_compile,erase_copyPrefix] + have hw:=a.net.width_eq + simp only [oracleOps,NetworkEmission.erase,eraseNet_length,←hw,copyOps] + simp only [Fin.castLE_rfl,List.map_reverse,id_eq] +end ExactQuantumFactoring.CircuitEmission + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/CircuitCleanEmission.lean b/lean/OAI/Computability/QuantumFactoring/CircuitCleanEmission.lean new file mode 100644 index 0000000000000000000000000000000000000000..003752ebf282e840771451817449c2d7c898fbfb --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/CircuitCleanEmission.lean @@ -0,0 +1,79 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.Emits +import OAI.Computability.QuantumFactoring.CircuitFinalEmission +import OAI.Computability.QuantumFactoring.NetworkIndexedEmission + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram.Emits +open Procedure +variable {α β : Type} {ea : α→List Bool} {eb : β→List Bool} +lemma ite {c : α→Bool} {a b : α→β} (hc : Emits ea boolCode c) + (ha : Emits ea eb a) (hb : Emits ea eb b) : + Emits ea eb (fun x=>if c x then a x else b x):=by + obtain ⟨pc⟩:=hc;obtain ⟨pa⟩:=ha;obtain ⟨pb⟩:=hb + exact ofProcedure (Procedure.conditional pc pa pb) +end ExactQuantumFactoring.BitStackProgram.Emits + +namespace ExactQuantumFactoring.NetworkEmission +open BitStackProgram BitStackProgram.Emits +namespace NetEmits +variable {α β : Type} {ea : α→List Bool} {eb : β→List Bool} {n m : β→ℕ} +lemma input {f : ∀x,BooleanNetwork (n x) (m x)} (hf : NetEmits eb f) + {g : α→β} (hg : Emits ea eb g) : NetEmits ea (fun x=>f (g x)):=by + obtain ⟨p,hp,he⟩:=hf + exact ⟨fun x=>p (g x),hp.comp hg,fun x=>he (g x)⟩ +end NetEmits +namespace PhysicalTreeEmission +open PhysicalTree +lemma zeroNet {α : Type} {ea : α→List Bool} {n : α→ℕ} + (hn : Emits ea unaryCode n) (hw : Emits ea unaryCode (fun x=>quarterWidth (n x))) : + NetEmits ea (fun x=>PhysicalTree.zeroNet (n x)):=by + let p : α→ℕ→Pack:=fun x i=>if (1 ≤ i) ∧ (i < 1+n x) then constantPack (quarterWidth (n x)) true + else bnotPack (bitPack (quarterWidth (n x)) i) + have he:=BitStackProgram.Emits.id (prodCode unaryCode ea) + have hi:=he.fst.unaryNat + have hN:=hn.comp he.snd + have hW:=hw.comp he.snd + have hc:=((hi.natLt (const _ _ 1)).boolNot).boolAnd + (hi.natLt ((const _ _ 1).natAdd hN.unaryNat)) + have hp : Emits (prodCode unaryCode ea) packCode (fun x=>p x.2 x.1):=by + have ha:=(ofProcedure Emission.constantPackP).comp (hW.pair (const _ _ true)) + have hb:=(ofProcedure Emission.bnotPackP).comp + ((ofProcedure Emission.bitPackP).comp (hW.pair hi)) + exact (hc.ite ha hb).congr (by + intro x + simp only [p,Bool.and_eq_true,Bool.not_eq_true',decide_eq_false_iff_not,not_lt,decide_eq_true_eq]) + apply NetEmits.allIndexed hw hw p hp + intro x i + simp only [inputWires,Finset.mem_filter,Finset.mem_univ,true_and] + dsimp only [p] + split + · exact constantPack_value _ _ + · exact bnotPack_value _ _ (bitPack_value i) +end PhysicalTreeEmission +end ExactQuantumFactoring.NetworkEmission + +namespace ExactQuantumFactoring.UniformResources.PhysicalTree +open BitStackProgram BitStackProgram.Emits NetworkEmission CircuitEmission +open ExactQuantumFactoring.PhysicalTree +theorem uniform_of_quarter_emitters_clean + (hw : Emits unaryCode unaryCode (fun l=>quarterWidth (paddedLength l))) + (hp : OpsEmits unaryCode (fun l=>quarterProgram (paddedLength l))) + (hf : NetEmits unaryCode (fun l=>quarterFlag (paddedLength l) (paddedLength_pos l))) + (ho : NetEmits unaryCode (fun l=>quarterOutputNet (paddedLength l))) : + Uniform finalCircuit:=by + have hn : Emits unaryCode unaryCode paddedLength:= + (const unaryCode unaryCode 128).unaryMax (BitStackProgram.Emits.id unaryCode) + exact uniform_of_quarter_emitters hw hp hf (PhysicalTreeEmission.zeroNet hn hw) ho +end ExactQuantumFactoring.UniformResources.PhysicalTree + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/CircuitEmissionBasic.lean b/lean/OAI/Computability/QuantumFactoring/CircuitEmissionBasic.lean new file mode 100644 index 0000000000000000000000000000000000000000..1d87a4a592ccf39ba0067f1f53965ad8cef94bdd --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/CircuitEmissionBasic.lean @@ -0,0 +1,115 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.NetworkEmissionProcedures +import OAI.Computability.QuantumFactoring.BitStackListFlatten +import OAI.Computability.QuantumFactoring.CircuitBooleanEmission +import OAI.Computability.QuantumFactoring.CircuitEmissionEncoding +import OAI.Computability.QuantumFactoring.BitStackListMapIdx + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.CircuitEmission +open BitStackProgram BitStackProgram.Procedure +namespace Emission +noncomputable def opPackP : Procedure opPayload opCode (fun x=>Op.mk x.1 x.2):= + (identity opPayload).result (by intro x;rfl) +noncomputable def dataPackP : Procedure dataPayload dataCode (fun x=>Data.mk x.1 x.2):= + (identity dataPayload).result (by intro x;rfl) +noncomputable def gatePackP : Procedure gatePayload gateCode (fun x=>Gate.mk x.1 x.2.1 x.2.2):= + (identity gatePayload).result (by intro x;rfl) +noncomputable def gateReverseP : Procedure gateCode gateCode Gate.reverse:= + gatePackP.comp (gatePrimitiveP.pair ((boolNot.comp gateInverseP).pair gateControlledP)) +noncomputable def opReverseP : Procedure opCode opCode Op.reverse:= + opPackP.comp ((gateReverseP.comp opGateP).pair opWiresP) +noncomputable def opsReverseP : Procedure (listCode opCode) (listCode opCode) + (fun xs=>xs.reverse.map Op.reverse):= + (listMap ⟨plainGate .not,[]⟩ ⟨plainGate .not,[]⟩ opReverseP).comp (listReverse opCode ⟨plainGate .not,[]⟩) +noncomputable def opMapWith {α : Type} {ea : α→List Bool} {f : α→ℕ→ℕ} + (p : Procedure (prodCode ea Nat.bits) Nat.bits (fun x=>f x.1 x.2)) : + Procedure (prodCode ea opCode) opCode (fun x=>x.2.map (f x.1)):=by + let a:=first ea opCode + let o:=second ea opCode + exact opPackP.comp ((opGateP.comp o).pair (((listMapWith 0 0 p)).comp (a.pair (opWiresP.comp o)))) +noncomputable def opsMapWith {α : Type} {ea : α→List Bool} {f : α→ℕ→ℕ} + (p : Procedure (prodCode ea Nat.bits) Nat.bits (fun x=>f x.1 x.2)) : + Procedure (prodCode ea (listCode opCode)) (listCode opCode) (fun x=>x.2.map (Op.map (f x.1))):= + listMapWith (f:=fun (a : α) (o : Op)=>o.map (f a)) ⟨plainGate .not,[]⟩ ⟨plainGate .not,[]⟩ (opMapWith p) +noncomputable def opsAppendP : Procedure (prodCode (listCode opCode) (listCode opCode)) (listCode opCode) + (fun x=>x.1++x.2):=listAppend opCode ⟨plainGate .not,[]⟩ +noncomputable def notOpP : Procedure Nat.bits opCode notOp:=by + let wires:=(listCons Nat.bits).comp ((identity Nat.bits).pair (Procedure.constant _ (listCode Nat.bits) [])) + exact opPackP.comp ((Procedure.constant Nat.bits gateCode (plainGate .not)).pair wires) +noncomputable def cnotOpP : Procedure (prodCode Nat.bits Nat.bits) opCode (fun x=>cnotOp x.1 x.2):=by + let a:=first Nat.bits Nat.bits + let b:=second Nat.bits Nat.bits + let tail:=(listCons Nat.bits).comp (b.pair (Procedure.constant _ (listCode Nat.bits) [])) + let wires:=(listCons Nat.bits).comp (a.pair tail) + exact opPackP.comp ((Procedure.constant _ gateCode (plainGate .cnot)).pair wires) +noncomputable def toffoliOpP : Procedure (prodCode Nat.bits (prodCode Nat.bits Nat.bits)) opCode + (fun x=>toffoliOp x.1 x.2.1 x.2.2):=by + let a:=first Nat.bits (prodCode Nat.bits Nat.bits) + let rs:=second Nat.bits (prodCode Nat.bits Nat.bits) + let b:=(first Nat.bits Nat.bits).comp rs + let c:=(second Nat.bits Nat.bits).comp rs + let tail:=(listCons Nat.bits).comp (c.pair (Procedure.constant _ (listCode Nat.bits) [])) + let mid:=(listCons Nat.bits).comp (b.pair tail) + let wires:=(listCons Nat.bits).comp (a.pair mid) + exact opPackP.comp ((Procedure.constant _ gateCode (plainGate .toffoli)).pair wires) +noncomputable def opSingletonP : Procedure opCode (listCode opCode) (fun o=>[o]):= + (listCons opCode).comp ((identity opCode).pair (Procedure.constant opCode (listCode opCode) [])) +noncomputable def nodeOpsP : Procedure (prodCode Nat.bits NetworkEmission.nodeCode) (listCode opCode) + (fun x=>nodeOps x.1 x.2):=by + let t:=first Nat.bits NetworkEmission.nodeCode + let o:=second Nat.bits NetworkEmission.nodeCode + let tag:=NetworkEmission.Emission.nodeTagP.comp o + let eq (i : ℕ):=binaryEq.comp (tag.pair (Procedure.constant _ Nat.bits i)) + let a:=NetworkEmission.Emission.nodeLhsP.comp o + let b:=NetworkEmission.Emission.nodeRhsP.comp o + let n:=opSingletonP.comp (notOpP.comp t) + let c:=opSingletonP.comp (cnotOpP.comp (a.pair t)) + let neg:=opsAppendP.comp (c.pair n) + let conj:=conditional (binaryEq.comp (a.pair b)) c + (opSingletonP.comp (toffoliOpP.comp (a.pair (b.pair t)))) + let const:=conditional (NetworkEmission.Emission.nodeBoolP.comp o) n (Procedure.constant _ (listCode opCode) []) + exact (conditional (eq 0) const (conditional (eq 1) c (conditional (eq 2) neg conj))).congrFun (by + rintro ⟨t,o⟩ + cases o with + | constant b=>cases b <;> rfl + | copy i=>rfl + | neg i=>rfl + | conj a b=>simp only [Function.comp_apply,NetworkEmission.nodeView,decide_eq_true_eq,nodeOps];rfl) +noncomputable def netOpsP : Procedure (prodCode Nat.bits (listCode NetworkEmission.nodeCode)) (listCode opCode) + (fun x=>netOps x.1 x.2):=by + let n:=first Nat.bits (prodCode Nat.bits NetworkEmission.nodeCode) + let rs:=second Nat.bits (prodCode Nat.bits NetworkEmission.nodeCode) + let i:=(first Nat.bits NetworkEmission.nodeCode).comp rs + let o:=(second Nat.bits NetworkEmission.nodeCode).comp rs + let step:=nodeOpsP.comp ((binaryAdd.comp (n.pair i)).pair o) + let xs:=listMapIdxWith (f:=fun n i o=>nodeOps (n+i) o) (.constant false) [] step + exact (listFlatten opCode ⟨plainGate .not,[]⟩).comp xs +noncomputable def copyOpsP : Procedure (prodCode Nat.bits (listCode Nat.bits)) (listCode opCode) + (fun x=>copyOps x.1 x.2):=by + let n:=first Nat.bits (prodCode Nat.bits Nat.bits) + let rs:=second Nat.bits (prodCode Nat.bits Nat.bits) + let i:=(first Nat.bits Nat.bits).comp rs + let a:=(second Nat.bits Nat.bits).comp rs + let step:=cnotOpP.comp (a.pair (binaryAdd.comp (n.pair i))) + exact listMapIdxWith (f:=fun n i a=>cnotOp a (n+i)) 0 ⟨plainGate .not,[]⟩ step +noncomputable def oracleOpsP : Procedure NetworkEmission.dataCode (listCode opCode) oracleOps:=by + let n:=NetworkEmission.Emission.dataInputP + let xs:=NetworkEmission.Emission.dataNodesP + let os:=NetworkEmission.Emission.dataOutputsP + let w:=NetworkEmission.Emission.dataWidthP + let p:=netOpsP.comp (n.pair xs) + exact opsAppendP.comp ((opsAppendP.comp (p.pair (copyOpsP.comp (w.pair os)))).pair (opsReverseP.comp p)) +end Emission +end ExactQuantumFactoring.CircuitEmission + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/CircuitEmissionEncoding.lean b/lean/OAI/Computability/QuantumFactoring/CircuitEmissionEncoding.lean new file mode 100644 index 0000000000000000000000000000000000000000..7564d5bce0c59a997fd5e8376174e56c6f68762f --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/CircuitEmissionEncoding.lean @@ -0,0 +1,78 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackListMapWith +import OAI.Computability.QuantumFactoring.BitStackListWords +import OAI.Computability.QuantumFactoring.CircuitEmissionModel +import OAI.Computability.QuantumFactoring.BitStackBoundedUnary + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.CircuitEmission +open BitStackProgram BitStackProgram.Procedure +namespace Emission +noncomputable def natWordP : Procedure unaryCode id natWord := + ((append.comp ((identity (id : List Bool→List Bool)).pair + (Procedure.constant (id : List Bool→List Bool) id [false]))).precompose unaryCode).congrFun (by intro n;rfl) +noncomputable def gateViewP : Procedure gateCode gatePayload gateView:= + (identity gatePayload).precompose gateView +noncomputable def gatePrimitiveP : Procedure gateCode primitiveCode Gate.primitive:= + (first primitiveCode _).comp gateViewP +noncomputable def gateInverseP : Procedure gateCode boolCode Gate.inverse:= + (first boolCode boolCode).comp ((second primitiveCode _).comp gateViewP) +noncomputable def gateControlledP : Procedure gateCode boolCode Gate.controlled:= + (second boolCode boolCode).comp ((second primitiveCode _).comp gateViewP) +noncomputable def gateHeaderP : Procedure gateCode id + (fun g=>natWord g.primitive.code++[g.inverse,g.controlled]) := by + let primitiveWord:=(natWordP.precompose Primitive.code).comp gatePrimitiveP + let c:=cons.comp (gateControlledP.pair (Procedure.constant gateCode id [])) + let tail:=cons.comp (gateInverseP.pair c) + exact (append.comp (primitiveWord.pair tail)).congrFun (by intro g;rfl) +noncomputable def opViewP : Procedure opCode opPayload opView:= + (identity opPayload).precompose opView +noncomputable def opGateP : Procedure opCode gateCode Op.gate:= + (first gateCode (listCode Nat.bits)).comp opViewP +noncomputable def opWiresP : Procedure opCode (listCode Nat.bits) Op.wires:= + (second gateCode (listCode Nat.bits)).comp opViewP +noncomputable def wireWordsP : Procedure (prodCode unaryCode (listCode Nat.bits)) id + (fun x=>x.2.flatMap (fun i=>natWord (min x.1 i))) := + (listJoinWords.comp (listMapWith (f:=fun cap i=>natWord (min cap i)) 0 [] + (natWordP.comp clippedUnary))).congrFun (by intro x;rfl) +noncomputable def opEncodeClippedP : Procedure (prodCode unaryCode opCode) id + (fun x=>x.2.encodeClipped x.1) := by + let cap:=first unaryCode opCode + let o:=second unaryCode opCode + let header:=gateHeaderP.comp (opGateP.comp o) + let wires:=wireWordsP.comp (cap.pair (opWiresP.comp o)) + exact (append.comp (header.pair wires)).congrFun (by intro x;rfl) +noncomputable def dataViewP : Procedure dataCode dataPayload dataView:= + (identity dataPayload).precompose dataView +noncomputable def qubitsP : Procedure dataCode unaryCode Data.qubits:= + (first unaryCode (listCode opCode)).comp dataViewP +noncomputable def opsP : Procedure dataCode (listCode opCode) Data.ops:= + (second unaryCode (listCode opCode)).comp dataViewP +noncomputable def encodeClippedP : Procedure dataCode id Data.encodeClipped := by + let qword:=natWordP.comp qubitsP + let len:=(NativeAIG.Emission.listUnaryLength opCode ⟨plainGate .not,[]⟩).comp opsP + let nword:=natWordP.comp len + let words:=(listMapWith (f:=fun cap (o : Op)=>o.encodeClipped cap) + ⟨plainGate .not,[]⟩ [] opEncodeClippedP).comp (qubitsP.pair opsP) + let payload:=listJoinWords.comp words + exact (append.comp ((append.comp (qword.pair nword)).pair payload)).congrFun (by intro x;rfl) +end Emission + +/-- This reduction charges all unary description writing, including every wire. +It is useful only with an actual finite-stack emitter for the literal erased family. -/ +theorem uniform_of_emitter (family : ℕ→Circuit) + (p : Procedure unaryCode dataCode (fun n=>erase (family n))) : Uniform family := by + let pp : Procedure unaryCode Circuit.encode family:= + (Emission.encodeClippedP.comp p).result (by intro n;exact erase_encodeClipped (family n)) + exact ⟨pp.toTM2,pp.toTM2_finite⟩ +end ExactQuantumFactoring.CircuitEmission + +end + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/CircuitEmissionModel.lean b/lean/OAI/Computability/QuantumFactoring/CircuitEmissionModel.lean new file mode 100644 index 0000000000000000000000000000000000000000..fb789266cd0b41faab82a25170bfc471c9fa728b --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/CircuitEmissionModel.lean @@ -0,0 +1,73 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.RegisterCircuit +import OAI.Computability.QuantumFactoring.BitStackListCode +import OAI.Computability.QuantumFactoring.BitStackNaturals + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.CircuitEmission +structure Op where + gate : Gate + wires : List ℕ + +def eraseOp {q : ℕ} (o : Instruction q) : Op:=⟨o.gate,List.ofFn (fun i=>(o.wire i).val)⟩ +def Op.encode (o : Op) : List Bool:= + natWord o.gate.primitive.code++[o.gate.inverse,o.gate.controlled]++o.wires.flatMap natWord +lemma eraseOp_encode {q : ℕ} (o : Instruction q) : (eraseOp o).encode=o.encode := rfl + +def Op.map (f : ℕ→ℕ) (o : Op) : Op:=⟨o.gate,o.wires.map f⟩ +def Op.reverse (o : Op) : Op:=⟨o.gate.reverse,o.wires⟩ +lemma eraseOp_place {q r : ℕ} (w : Register q r) (o : Instruction q) (f : ℕ→ℕ) + (h : ∀i,(w i).val=f i.val) : eraseOp (o.place w)=(eraseOp o).map f := by + simp only [eraseOp,Instruction.place,Op.map,List.map_ofFn,Function.comp_apply,h] + rfl +lemma eraseOp_reverse {q : ℕ} (o : Instruction q) : eraseOp o.reverse=(eraseOp o).reverse := rfl + +structure Data where + qubits : ℕ + ops : List Op + +def erase (c : Circuit) : Data:=⟨c.qubits,c.instructions.map eraseOp⟩ +def Data.encode (c : Data) : List Bool:=natWord c.qubits++natWord c.ops.length++c.ops.flatMap Op.encode +lemma erase_encode (c : Circuit) : (erase c).encode=c.encode := by + simp only [erase,Data.encode,Circuit.encode,List.length_map,List.flatMap_map,eraseOp_encode] + +def primitiveCode (p : Primitive) : List Bool:=BitStackProgram.unaryCode p.code +def gateView (g : Gate):= (g.primitive,g.inverse,g.controlled) +def gatePayload:=BitStackProgram.prodCode primitiveCode + (BitStackProgram.prodCode BitStackProgram.Procedure.boolCode BitStackProgram.Procedure.boolCode) +def gateCode (g : Gate) : List Bool:=gatePayload (gateView g) +def opView (o : Op):=(o.gate,o.wires) +def opPayload:=BitStackProgram.prodCode gateCode (BitStackProgram.listCode Nat.bits) +def opCode (o : Op) : List Bool:=opPayload (opView o) +def dataView (c : Data):=(c.qubits,c.ops) +def dataPayload:=BitStackProgram.prodCode BitStackProgram.unaryCode (BitStackProgram.listCode opCode) +def dataCode (c : Data) : List Bool:=dataPayload (dataView c) + +def Op.encodeClipped (cap : ℕ) (o : Op) : List Bool:= + natWord o.gate.primitive.code++[o.gate.inverse,o.gate.controlled]++ + o.wires.flatMap (fun i=>natWord (min cap i)) +def Data.encodeClipped (c : Data) : List Bool:=natWord c.qubits++natWord c.ops.length++ + c.ops.flatMap (Op.encodeClipped c.qubits) +lemma eraseOp_encodeClipped {q : ℕ} (o : Instruction q) : + (eraseOp o).encodeClipped q=o.encode := by + unfold Op.encodeClipped eraseOp Instruction.encode + congr 1 + apply List.flatMap_congr + intro i hi + obtain ⟨j,rfl⟩:=List.mem_ofFn.mp hi + rw [min_eq_right (Nat.le_of_lt (o.wire j).isLt)] +lemma erase_encodeClipped (c : Circuit) : (erase c).encodeClipped=c.encode := by + simp only [erase,Data.encodeClipped,Circuit.encode,List.length_map,List.flatMap_map, + eraseOp_encodeClipped] +end ExactQuantumFactoring.CircuitEmission + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/CircuitEncodingSize.lean b/lean/OAI/Computability/QuantumFactoring/CircuitEncodingSize.lean new file mode 100644 index 0000000000000000000000000000000000000000..44976c9c25432017fdd5453997008da9994951b0 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/CircuitEncodingSize.lean @@ -0,0 +1,66 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.Basic + +namespace OAI + +section +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators + + +namespace ExactQuantumFactoring + +lemma natWord_length (k : ℕ) : (natWord k).length=k+1 := by + simp [natWord] + +lemma Gate.arity_le (g : Gate) : g.arity≤4 := by + rcases g with ⟨p,i,c⟩ + cases p <;> cases c <;> cases i <;> decide +lemma Primitive.code_le (p : Primitive) : p.code≤4 := by + cases p <;> decide + +lemma flatMap_length_bound {α β : Type*} (xs : List α) (f : α→List β) (b : ℕ) + (h : ∀ x∈xs, (f x).length≤b) : (xs.flatMap f).length≤xs.length*b := by + induction xs with + | nil=>simp + | cons x xs ih=> + have hx:=h x (List.mem_cons_self) + have ht:=ih (fun y hy=>h y (List.mem_cons_of_mem _ hy)) + simp only [List.flatMap_cons,List.length_append,List.length_cons,Nat.add_mul,Nat.one_mul] + omega + +/-- Addresses are unary in the frozen interface; bounded gate arity ensures +this encoding itself has only polynomial overhead in width and gate count. -/ +lemma Instruction.encode_length {q : ℕ} (o : Instruction q) : + o.encode.length≤7+4*q := by + have h:=flatMap_length_bound (List.ofFn (fun i=> (o.wire i).val)) natWord q (by + intro x hx + obtain ⟨i,rfl⟩:=List.mem_ofFn.mp hx + rw [natWord_length] + exact (o.wire i).isLt) + rw [List.length_ofFn] at h + have ha:=Nat.mul_le_mul_right q (Gate.arity_le o.gate) + have hc:=Primitive.code_le o.gate.primitive + simp only [Instruction.encode,List.length_append,natWord_length,List.length_cons,List.length_nil] + omega + +lemma Circuit.encode_length (c : Circuit) : + c.encode.length≤c.qubits+2+c.instructions.length*(8+4*c.qubits) := by + have h:=flatMap_length_bound c.instructions Instruction.encode (7+4*c.qubits) + (fun x _=>Instruction.encode_length x) + simp only [Circuit.encode,List.length_append,natWord_length] + nlinarith + +end ExactQuantumFactoring + + + + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/CircuitFinalEmission.lean b/lean/OAI/Computability/QuantumFactoring/CircuitFinalEmission.lean new file mode 100644 index 0000000000000000000000000000000000000000..998d1b408abca1ea344fb53582c1b9b2099e2a8e --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/CircuitFinalEmission.lean @@ -0,0 +1,110 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.FactoringCircuit +import OAI.Computability.QuantumFactoring.CircuitProgramEmission + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram.Emits +open Procedure +variable {α : Type} {ea : α→List Bool} +lemma unaryMax {f g : α→ℕ} (hf : Emits ea unaryCode f) (hg : Emits ea unaryCode g) : + Emits ea unaryCode (fun x=>max (f x) (g x)):=by + exact ((ofProcedure clippedUnary).comp ((hf.unaryAdd hg).pair + (hf.unaryNat.natMax hg.unaryNat))).congr (by intro x;exact min_eq_right (max_le (by omega) (by omega))) +lemma range {f : α→ℕ} (hf : Emits ea unaryCode f) : Emits ea (listCode Nat.bits) (fun x=>List.range (f x)):= + (ofProcedure NetworkEmission.Emission.rangeP).comp hf +end ExactQuantumFactoring.BitStackProgram.Emits + +namespace ExactQuantumFactoring.CircuitEmission +open BitStackProgram BitStackProgram.Procedure BitStackProgram.Emits +namespace OpsEmits +variable {α : Type} {ea : α→List Bool} {q r : α→ℕ} +lemma place {p : ∀x,List (Instruction (q x))} (hp : OpsEmits ea p) + (w : ∀x,Register (q x) (r x)) (f : α→ℕ→ℕ) + (hw : ∀x i,(w x i).val=f x i.val) + (hf : Emits (prodCode ea Nat.bits) Nat.bits (fun x=>f x.1 x.2)) : + OpsEmits ea (fun x=>(p x).map (Instruction.place (w x))):=by + obtain ⟨pf⟩:=hf + exact ((ofProcedure (Emission.opsMapWith pf)).comp ((BitStackProgram.Emits.id ea).pair hp)).congr (by + intro x + simp only [List.map_map] + apply List.map_congr_left + intro o ho + exact (eraseOp_place (w x) o (f x) (hw x)).symm) +end OpsEmits +namespace Emission +noncomputable def relocateValP : Procedure + (prodCode (prodCode Nat.bits (prodCode Nat.bits Nat.bits)) Nat.bits) Nat.bits + (fun x=>relocateVal x.1.1 x.1.2.1 x.1.2.2 x.2):=by + let e:=first (prodCode Nat.bits (prodCode Nat.bits Nat.bits)) Nat.bits + let i:=second (prodCode Nat.bits (prodCode Nat.bits Nat.bits)) Nat.bits + let a:=(first Nat.bits (prodCode Nat.bits Nat.bits)).comp e + let m:=(first Nat.bits Nat.bits).comp ((second Nat.bits (prodCode Nat.bits Nat.bits)).comp e) + let l:=(second Nat.bits Nat.bits).comp ((second Nat.bits (prodCode Nat.bits Nat.bits)).comp e) + let z:=binaryEq.comp (i.pair (constant _ Nat.bits 0)) + let il:=boolNot.comp (binaryLt.comp (l.pair i)) + let ia:=binaryLt.comp (i.pair a) + let iam:=binaryLt.comp (i.pair (binaryAdd.comp (a.pair m))) + let case0:=binaryAdd.comp (l.pair m) + let case1:=binarySub.comp (i.pair (constant _ Nat.bits 1)) + let case2:=binaryAdd.comp (i.pair m) + let case3:=binaryAdd.comp (l.pair (binarySub.comp (i.pair a))) + exact (conditional z case0 (conditional il case1 (conditional ia case2 (conditional iam case3 i)))).congrFun (by + intro x;simp only [Function.comp_apply,decide_eq_true_eq,relocateVal,Bool.not_eq_true',decide_eq_false_iff_not,not_lt]) +end Emission +end ExactQuantumFactoring.CircuitEmission + +namespace ExactQuantumFactoring.UniformResources.PhysicalTree +open BitStackProgram BitStackProgram.Emits NetworkEmission CircuitEmission +open ExactQuantumFactoring.PhysicalTree + +/-- A precise remaining syntax boundary. All post-quarter amplification, +clean oracle synthesis, readout, relocation, and unary serialization are actual +charged finite-stack procedures; none is a generation-time oracle. -/ +theorem uniform_of_quarter_emitters + (hw : Emits unaryCode unaryCode (fun l=>quarterWidth (paddedLength l))) + (hp : OpsEmits unaryCode (fun l=>quarterProgram (paddedLength l))) + (hf : NetEmits unaryCode (fun l=>quarterFlag (paddedLength l) (paddedLength_pos l))) + (hz : NetEmits unaryCode (fun l=>zeroNet (paddedLength l))) + (ho : NetEmits unaryCode (fun l=>quarterOutputNet (paddedLength l))) : + Uniform finalCircuit:=by + have hr : Emits unaryCode unaryCode (fun l=>reflectWork (paddedLength l) (paddedLength_pos l)):=hf.count.unaryMax hz.count + have ha : Emits unaryCode unaryCode (fun l=>amplifiedWidth (paddedLength l) (paddedLength_pos l)):=hw.unarySucc.unaryAdd hr + have hs : NetEmits unaryCode (fun l=>BooleanNetwork.select + (firstRegister (quarterWidth (paddedLength l)) 1 (reflectWork (paddedLength l) (paddedLength_pos l)))):=by + apply NetEmits.select ha + exact hw.range.congr (by intro l;change List.range (quarterWidth (paddedLength l))=List.ofFn (fun i:Fin (quarterWidth (paddedLength l))=>i.val);exact (ofFn_val_range _).symm) + have hao : NetEmits unaryCode (fun l=>amplifiedOutput (paddedLength l) (paddedLength_pos l)):=hs.comp ho + have hap : OpsEmits unaryCode (fun l=>amplifiedProgram (paddedLength l) (paddedLength_pos l)):= + hp.amplify hf hz (fun _=>Nat.le_max_left _ _) (fun _=>Nat.le_max_right _ _) + have hfact : OpsEmits unaryCode (fun l=>factoringProgram (paddedLength l) (paddedLength_pos l)):= + hap.readout hao (fun _=>le_rfl) + have hn : Emits unaryCode unaryCode paddedLength:= + (const unaryCode unaryCode 128).unaryMax (BitStackProgram.Emits.id unaryCode) + have hm:=hn.unaryMul hn + have hq : Emits unaryCode unaryCode (fun l=>readoutWidth (paddedLength l) (paddedLength_pos l)):= + (ha.unaryAdd hm).unaryAdd hao.count + have hrel : Emits (prodCode unaryCode Nat.bits) Nat.bits + (fun x=>relocateVal (amplifiedWidth (paddedLength x.1) (paddedLength_pos x.1)) + (paddedLength x.1*paddedLength x.1) x.1 x.2):=by + have he:=(BitStackProgram.Emits.id (prodCode unaryCode Nat.bits)).fst + have hi:=(BitStackProgram.Emits.id (prodCode unaryCode Nat.bits)).snd + exact (ofProcedure CircuitEmission.Emission.relocateValP).comp + (((ha.unaryNat.comp he).pair ((hm.unaryNat.comp he).pair he.unaryNat)).pair hi) + have hP : OpsEmits unaryCode (fun l=>(finalCircuit l).instructions):= + hfact.place finalRegister + (fun l i=>relocateVal (amplifiedWidth (paddedLength l) (paddedLength_pos l)) + (paddedLength l*paddedLength l) l i) (fun _ _=>rfl) hrel + obtain ⟨pp⟩:=(ofProcedure CircuitEmission.Emission.dataPackP).comp (hq.pair hP) + exact CircuitEmission.uniform_of_emitter finalCircuit pp +end ExactQuantumFactoring.UniformResources.PhysicalTree + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/CircuitPreparationEmission.lean b/lean/OAI/Computability/QuantumFactoring/CircuitPreparationEmission.lean new file mode 100644 index 0000000000000000000000000000000000000000..a135bbd7278cfd6f9517902d60380df56675f63e --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/CircuitPreparationEmission.lean @@ -0,0 +1,64 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.CircuitFinalEmission + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.CircuitEmission +open BitStackProgram BitStackProgram.Emits + +def hadamardOp (i : ℕ) : Op:=⟨plainGate .hadamard,[i]⟩ +lemma erase_hadamardAt {q : ℕ} (i : Fin q) : eraseOp (hadamardAt i)=hadamardOp i.val:=rfl +lemma erase_hadamardPrefix (q k : ℕ) (h : k≤q) : + (hadamardPrefix q k h).map eraseOp=(List.range k).map hadamardOp:=by + induction k with + | zero=>rfl + | succ k ih=>rw [hadamardPrefix,List.map_append,ih,List.range_succ,List.map_append];rfl +namespace Emission +open Procedure +noncomputable def hadamardOpP : Procedure Nat.bits opCode hadamardOp:=by + let wires:=(listCons Nat.bits).comp ((identity Nat.bits).pair (Procedure.constant _ (listCode Nat.bits) [])) + exact opPackP.comp ((Procedure.constant _ gateCode (plainGate .hadamard)).pair wires) +noncomputable def hadamardPrefixP : Procedure unaryCode (listCode opCode) + (fun k=>(List.range k).map hadamardOp):= + (listMap 0 (hadamardOp 0) hadamardOpP).comp NetworkEmission.Emission.rangeP +end Emission +namespace OpsEmits +variable {α : Type} {ea : α→List Bool} {q r m : α→ℕ} +lemma hadamards {k : α→ℕ} (hk : Emits ea unaryCode k) (h : ∀x,k x≤q x) : + OpsEmits ea (fun x=>hadamardPrefix (q x) (k x) (h x)):= + ((ofProcedure Emission.hadamardPrefixP).comp hk).congr (fun _=>(erase_hadamardPrefix _ _ _).symm) +lemma left {p : ∀x,List (Instruction (q x))} (hp : OpsEmits ea p) (r : α→ℕ) : + OpsEmits ea (fun x=>leftProgram (r x) (p x)):=by + exact place hp (fun x=>leftRegister (q x) (r x)) (fun _ i=>i) (by intros;rfl) + (BitStackProgram.Emits.id (prodCode ea Nat.bits)).snd +lemma right {p : ∀x,List (Instruction (q x))} (hp : OpsEmits ea p) (hr : Emits ea unaryCode r) : + OpsEmits ea (fun x=>rightProgram (r x) (p x)):=by + have he:=BitStackProgram.Emits.id (prodCode ea Nat.bits) + exact place hp (fun x=>rightRegister (r x) (q x)) (fun x i=>r x+i) (by intros;rfl) + ((hr.comp he.fst).unaryNat.natAdd he.snd) +lemma parallel {p : ∀x,List (Instruction (q x))} {s : ∀x,List (Instruction (r x))} + (hp : OpsEmits ea p) (hs : OpsEmits ea s) (hq : Emits ea unaryCode q) : + OpsEmits ea (fun x=>parallelProgram (p x) (s x)):= + (hp.left r).append (hs.right hq) +lemma target {p : ∀x,List (Instruction (q x))} (hp : OpsEmits ea p) (hm : Emits ea unaryCode m) (r : α→ℕ) : + OpsEmits ea (fun x=>targetProgram (m x) (r x) (p x)):=by + have he:=BitStackProgram.Emits.id (prodCode ea Nat.bits) + exact place hp (fun x=>targetRegister (m x) (q x) (r x)) (fun x i=>m x+i) (by intros;rfl) + ((hm.comp he.fst).unaryNat.natAdd he.snd) +lemma prepared {f : ∀x,BooleanNetwork (m x) (q x)} (hf : NetworkEmission.NetEmits ea f) + (hm : Emits ea unaryCode m) (h : ∀x,(f x).net.count≤r x) + {p : ∀x,List (Instruction (q x))} (hp : OpsEmits ea p) : + OpsEmits ea (fun x=>preparedOracle (f x) (h x) (p x)):= + (oracleOn hf h).append (hp.target hm r) +end OpsEmits +end ExactQuantumFactoring.CircuitEmission + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/CircuitProgramEmission.lean b/lean/OAI/Computability/QuantumFactoring/CircuitProgramEmission.lean new file mode 100644 index 0000000000000000000000000000000000000000..79bd0db8f3d57170c7298a1c0466daf96c42cd10 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/CircuitProgramEmission.lean @@ -0,0 +1,141 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.TreeReadout +import OAI.Computability.QuantumFactoring.CircuitEmissionBasic +import OAI.Computability.QuantumFactoring.NetworkExpressionEmission + +namespace OAI + + + +section + +namespace ExactQuantumFactoring +namespace NetworkEmission.NetEmits +open BitStackProgram BitStackProgram.Emits +variable {α : Type} {ea : α→List Bool} {n m : α→ℕ} +lemma data {f : ∀x,BooleanNetwork (n x) (m x)} (hf : NetEmits ea f) : + Emits ea dataCode (fun x=>erase (f x)):=by + obtain ⟨p,hp,he⟩:=hf + exact ((ofProcedure Emission.packValueP).comp hp).congr he +lemma count {f : ∀x,BooleanNetwork (n x) (m x)} (hf : NetEmits ea f) : + Emits ea unaryCode (fun x=>(f x).net.count):=by + exact ((ofProcedure ((NativeAIG.Emission.listUnaryLength nodeCode (.constant false)).comp + Emission.dataNodesP)).comp hf.data).congr (by intro x;exact eraseNet_length _) +lemma outLength {f : ∀x,BooleanNetwork (n x) (m x)} (hf : NetEmits ea f) : + Emits ea unaryCode m:=by + exact ((ofProcedure ((NativeAIG.Emission.listUnaryLength Nat.bits 0).comp + Emission.dataOutputsP)).comp hf.data).congr (by intro x;exact List.length_ofFn) +end NetworkEmission.NetEmits + +namespace CircuitEmission +open BitStackProgram BitStackProgram.Procedure BitStackProgram.Emits + +def oracleOnOps (a : NetworkEmission.Data) : List Op:= + (oracleOps a).map (Op.map (BooleanNetwork.oracleIndex a.inputs a.outputs.length a.width)) +lemma erase_oracleOn {n m r : ℕ} (a : BooleanNetwork n m) (hr : a.net.count≤r) : + (BooleanNetwork.oracleOn a hr).map eraseOp=oracleOnOps (NetworkEmission.erase a):=by + simp only [BooleanNetwork.oracleOn,List.map_map] + rw [show (eraseOp ∘ Instruction.place (BooleanNetwork.oraclePlacement a hr))= + (fun o=>(eraseOp o).map (BooleanNetwork.oracleIndex n m a.width)) by + funext o;exact eraseOp_place _ _ _ (fun _=>rfl)] + change List.map ((Op.map (BooleanNetwork.oracleIndex n m a.width)) ∘ eraseOp) a.oracle=_ + rw [←List.map_map,erase_oracle] + simp only [oracleOnOps,NetworkEmission.erase,List.length_ofFn,NetworkEmission.Data.width, + NetworkEmission.eraseNet_length,←a.net.width_eq] +lemma erase_firstProgram {n m r : ℕ} (ops : List (Instruction n)) : + (firstProgram m r ops).map eraseOp=ops.map eraseOp:=by + simp only [firstProgram,List.map_map] + apply List.map_congr_left + intro o ho + rw [Function.comp_apply,eraseOp_place _ _ id (fun _=>rfl)] + simp [Op.map] +lemma erase_reverseProgram {q : ℕ} (ops : List (Instruction q)) : + (ops.reverse.map Instruction.reverse).map eraseOp=(ops.map eraseOp).reverse.map Op.reverse:=by + simp only [List.map_map,List.map_reverse] + rfl + +def phaseOp (n : ℕ) : Op:=⟨plainGate .phase,[n]⟩ +lemma erase_phaseAt {q : ℕ} (i : Fin q) : eraseOp (phaseAt i)=phaseOp i.val:=rfl + +def phaseOps (a : NetworkEmission.Data) : List Op:= + oracleOnOps a++[phaseOp a.inputs,phaseOp a.inputs]++oracleOnOps a +lemma erase_phaseOracle {n r : ℕ} (a : BooleanNetwork n 1) (hr : a.net.count≤r) : + (BooleanNetwork.phaseOracle a hr).map eraseOp=phaseOps (NetworkEmission.erase a):=by + simp only [BooleanNetwork.phaseOracle,List.map_append,List.map_cons,List.map_nil,erase_oracleOn, + erase_phaseAt,BooleanNetwork.phaseTarget,phaseOps,NetworkEmission.erase] + +def amplifyOps (ps : List Op) (a z : NetworkEmission.Data) : List Op:= + ps++phaseOps a++ps.reverse.map Op.reverse++phaseOps z++ps +lemma erase_amplification {n r : ℕ} (ops : List (Instruction n)) + (a z : BooleanNetwork n 1) (ha : a.net.count≤r) (hz : z.net.count≤r) : + (amplificationProgram ops a z ha hz).map eraseOp= + amplifyOps (ops.map eraseOp) (NetworkEmission.erase a) (NetworkEmission.erase z):=by + simp only [amplificationProgram,List.map_append,erase_firstProgram,erase_phaseOracle, + erase_reverseProgram,amplifyOps] + +namespace Emission +noncomputable def oracleIndexP : Procedure + (prodCode (prodCode Nat.bits (prodCode Nat.bits Nat.bits)) Nat.bits) Nat.bits + (fun x=>BooleanNetwork.oracleIndex x.1.1 x.1.2.1 x.1.2.2 x.2):=by + let e:=first (prodCode Nat.bits (prodCode Nat.bits Nat.bits)) Nat.bits + let i:=second (prodCode Nat.bits (prodCode Nat.bits Nat.bits)) Nat.bits + let n:=(first Nat.bits (prodCode Nat.bits Nat.bits)).comp e + let m:=(first Nat.bits Nat.bits).comp ((second Nat.bits (prodCode Nat.bits Nat.bits)).comp e) + let w:=(second Nat.bits Nat.bits).comp ((second Nat.bits (prodCode Nat.bits Nat.bits)).comp e) + let input:=binaryLt.comp (i.pair n) + let work:=binaryLt.comp (i.pair w) + let wi:=binaryAdd.comp ((binaryAdd.comp (n.pair m)).pair (binarySub.comp (i.pair n))) + let oi:=binaryAdd.comp (n.pair (binarySub.comp (i.pair w))) + exact (conditional input i (conditional work wi oi)).congrFun (by intro x;simp [BooleanNetwork.oracleIndex]) +noncomputable def oracleOnOpsP : Procedure NetworkEmission.dataCode (listCode opCode) oracleOnOps:=by + let env:=NetworkEmission.Emission.dataInputP.pair + (((listLength Nat.bits 0).comp NetworkEmission.Emission.dataOutputsP).pair NetworkEmission.Emission.dataWidthP) + exact (opsMapWith (f:=fun (e:ℕ×ℕ×ℕ) i=>BooleanNetwork.oracleIndex e.1 e.2.1 e.2.2 i) oracleIndexP).comp (env.pair oracleOpsP) +noncomputable def phaseOpP : Procedure Nat.bits opCode phaseOp:= + opPackP.comp ((constant Nat.bits gateCode (plainGate .phase)).pair + ((listCons Nat.bits).comp ((identity Nat.bits).pair (constant Nat.bits (listCode Nat.bits) [])))) +noncomputable def phaseOpsP : Procedure NetworkEmission.dataCode (listCode opCode) phaseOps:=by + let p:=phaseOpP.comp NetworkEmission.Emission.dataInputP + let mid:=(listCons opCode).comp (p.pair ((listCons opCode).comp (p.pair (constant _ (listCode opCode) [])))) + exact opsAppendP.comp ((opsAppendP.comp (oracleOnOpsP.pair mid)).pair oracleOnOpsP) +end Emission + +abbrev OpsEmits {α : Type} (ea : α→List Bool) {q : α→ℕ} (p : ∀x,List (Instruction (q x))) : Prop:= + Emits ea (listCode opCode) (fun x=>(p x).map eraseOp) +namespace OpsEmits +variable {α : Type} {ea : α→List Bool} {q m r : α→ℕ} +lemma congr {p s : ∀x,List (Instruction (q x))} (hp : OpsEmits ea p) (h : ∀x,p x=s x) : OpsEmits ea s:= + BitStackProgram.Emits.congr hp (fun x=>congrArg (List.map eraseOp) (h x)) +lemma append {p s : ∀x,List (Instruction (q x))} (hp : OpsEmits ea p) (hs : OpsEmits ea s) : + OpsEmits ea (fun x=>p x++s x):= + (hp.listAppend ⟨plainGate .not,[]⟩ hs).congr (fun _=>List.map_append.symm) +lemma first {p : ∀x,List (Instruction (q x))} (hp : OpsEmits ea p) (m r : α→ℕ) : + OpsEmits ea (fun x=>firstProgram (m x) (r x) (p x)):=BitStackProgram.Emits.congr hp (fun _=>(erase_firstProgram _).symm) +lemma reverse {p : ∀x,List (Instruction (q x))} (hp : OpsEmits ea p) : + OpsEmits ea (fun x=>(p x).reverse.map Instruction.reverse):= + ((ofProcedure Emission.opsReverseP).comp hp).congr (fun _=>(erase_reverseProgram _).symm) +lemma oracleOn {f : ∀x,BooleanNetwork (q x) (m x)} (hf : NetworkEmission.NetEmits ea f) + (h : ∀x,(f x).net.count≤r x) : OpsEmits ea (fun x=>BooleanNetwork.oracleOn (f x) (h x)):= + ((ofProcedure Emission.oracleOnOpsP).comp hf.data).congr (fun _=>(erase_oracleOn _ _).symm) +lemma phase {f : ∀x,BooleanNetwork (q x) 1} (hf : NetworkEmission.NetEmits ea f) + (h : ∀x,(f x).net.count≤r x) : OpsEmits ea (fun x=>BooleanNetwork.phaseOracle (f x) (h x)):= + ((ofProcedure Emission.phaseOpsP).comp hf.data).congr (fun _=>(erase_phaseOracle _ _).symm) +lemma amplify {p : ∀x,List (Instruction (q x))} (hp : OpsEmits ea p) + {f g : ∀x,BooleanNetwork (q x) 1} (hf : NetworkEmission.NetEmits ea f) (hg : NetworkEmission.NetEmits ea g) + (h : ∀x,(f x).net.count≤r x) (j : ∀x,(g x).net.count≤r x) : + OpsEmits ea (fun x=>amplificationProgram (p x) (f x) (g x) (h x) (j x)):= + ((((hp.first (fun _=>1) r).append (hf |> fun hf=>phase hf h)).append + (hp.reverse.first (fun _=>1) r)).append (phase hg j)).append (hp.first (fun _=>1) r) +lemma readout {p : ∀x,List (Instruction (q x))} (hp : OpsEmits ea p) + {f : ∀x,BooleanNetwork (q x) (m x)} (hf : NetworkEmission.NetEmits ea f) + (h : ∀x,(f x).net.count≤r x) : OpsEmits ea (fun x=>readoutProgram (p x) (f x) (h x)):= + (hp.first m r).append (oracleOn hf h) +end OpsEmits +end CircuitEmission +end ExactQuantumFactoring + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/CircuitRecursionEmission.lean b/lean/OAI/Computability/QuantumFactoring/CircuitRecursionEmission.lean new file mode 100644 index 0000000000000000000000000000000000000000..d7cbff97782b953ace9992905ea4d351f4732d0f --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/CircuitRecursionEmission.lean @@ -0,0 +1,40 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.CircuitEncodingSize +import OAI.Computability.QuantumFactoring.CircuitEmissionModel +import OAI.Computability.QuantumFactoring.EmissionCombinators + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.CircuitEmission +open BitStackProgram BitStackProgram.Emits +lemma gateCode_bound (g : Gate) : (gateCode g).length≤20:=by + have h:=Primitive.code_le g.primitive + simp only [gateCode,gatePayload,gateView,prodCode, pairBits_length,primitiveCode,unaryCode,List.length_replicate, + Procedure.boolCode,List.length_cons,List.length_nil] + omega +lemma opCode_bound {q : ℕ} (o : Instruction q) : (opCode (eraseOp o)).length≤100+16*q:=by + have h:=NativeAIG.listCode_length_bound Nat.bits (List.ofFn (fun i=>(o.wire i).val)) q (by + intro i hi + obtain ⟨j,rfl⟩:=List.mem_ofFn.mp hi + exact (NativeAIG.nat_bits_length_bound _).trans (Nat.le_of_lt (o.wire j).isLt)) + rw [List.length_ofFn] at h + have hg:=gateCode_bound o.gate + have ha:=Gate.arity_le o.gate + change (prodCode gateCode (listCode Nat.bits) (o.gate,List.ofFn (fun i=>(o.wire i).val))).length≤_ + simp only [prodCode, pairBits_length] + nlinarith +lemma opsCode_bound {q : ℕ} (p : List (Instruction q)) : + (listCode opCode (p.map eraseOp)).length≤p.length*(202+32*q)+1:=by + have h:=NativeAIG.listCode_length_bound opCode (p.map eraseOp) (100+16*q) (by + intro o ho;obtain ⟨i,hi,rfl⟩:=List.mem_map.mp ho;exact opCode_bound i) + simp only [List.length_map] at h + nlinarith + +end ExactQuantumFactoring.CircuitEmission +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/CircuitSemantics.lean b/lean/OAI/Computability/QuantumFactoring/CircuitSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..48b5af9417b3dd90fdc7703e0eb97f4d94ca897e --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/CircuitSemantics.lean @@ -0,0 +1,225 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.ExactnessFurther +import OAI.Computability.QuantumFactoring.GateSemantics + +namespace OAI + +section + + +namespace ExactQuantumFactoring +open scoped BigOperators Kronecker + +abbrev Instruction.Unused {q : ℕ} (o : Instruction q) := + {i : Fin q // ∀ j, o.wire j ≠ i} + +/-- Reindex a full computational basis by the gate wires and all other wires. +This is only a proof equivalence; it introduces no new gate in the model. -/ +noncomputable def Instruction.splitBasis {q : ℕ} (o : Instruction q) : + Basis q ≃ Basis o.gate.arity × (o.Unused → Bool) := by + classical + refine { + toFun := fun x => (x ∘ o.wire, fun i => x i.val) + invFun := fun x i => if h : ∃ j, o.wire j = i then x.1 h.choose + else x.2 ⟨i, by simpa only [not_exists] using h⟩ + left_inv := ?_ + right_inv := ?_ } + · intro x + funext i + dsimp + split_ifs with h + · simp only [h.choose_spec] + · rfl + · intro x + apply Prod.ext + · funext j + dsimp + have h : ∃ j', o.wire j' = o.wire j := ⟨j, rfl⟩ + rw [dite_eq_left h] + exact congrArg x.1 (o.distinct h.choose_spec) + · funext i + dsimp + rw [dite_eq_right (by simpa only [not_exists] using i.property)] + +lemma tensor_unitary {ι κ : Type*} [Fintype ι] [Fintype κ] + [DecidableEq ι] [DecidableEq κ] (A : Matrix ι ι ℂ) (B : Matrix κ κ ℂ) + (hA : A ∈ Matrix.unitaryGroup ι ℂ) (hB : B ∈ Matrix.unitaryGroup κ ℂ) : + A ⊗ₖ B ∈ Matrix.unitaryGroup (ι × κ) ℂ := by + rw [Matrix.mem_unitaryGroup_iff'] at hA hB ⊢ + rw [Matrix.star_eq_conjTranspose, Matrix.conjTranspose_kronecker] + rw [← Matrix.mul_kronecker_mul] + change (star A * A) ⊗ₖ (star B * B) = 1 + rw [hA, hB, Matrix.one_kronecker_one] + +lemma Instruction.matrix_eq_reindex {q : ℕ} (o : Instruction q) : + o.matrix = Matrix.reindex o.splitBasis.symm o.splitBasis.symm + (o.gate.localMatrix ⊗ₖ (1 : Matrix (o.Unused → Bool) (o.Unused → Bool) ℂ)) := by + classical + ext x y + change (if ∀ i : Fin q, (∀ j, o.wire j ≠ i) → x i = y i then + o.gate.matrix (List.ofFn (x ∘ o.wire)) (List.ofFn (y ∘ o.wire)) else 0) = + o.gate.matrix (List.ofFn (x ∘ o.wire)) (List.ofFn (y ∘ o.wire)) * + if (fun i : o.Unused => x i.val) = (fun i : o.Unused => y i.val) then 1 else 0 + by_cases h : ∀ i : Fin q, (∀ j, o.wire j ≠ i) → x i = y i + · have he : (fun i : o.Unused => x i.val) = (fun i : o.Unused => y i.val) := + funext (fun i => h i.val i.property) + rw [ite_eq_left h, ite_eq_left he, mul_one] + · have he : (fun i : o.Unused => x i.val) ≠ (fun i : o.Unused => y i.val) := by + intro hh + apply h + intro i hi + exact congrFun hh ⟨i,hi⟩ + rw [ite_eq_right h, ite_eq_right he, mul_zero] + +lemma Instruction.unitary {q : ℕ} (o : Instruction q) : + o.matrix ∈ Matrix.unitaryGroup (Basis q) ℂ := by + classical + rw [o.matrix_eq_reindex] + exact unitary_reindex _ _ (tensor_unitary _ _ o.gate.local_unitary (one_mem _)) + +/-- Matrix of executing a list of instructions, in chronological order. -/ +noncomputable def programMatrix {q : ℕ} (ops : List (Instruction q)) : + Matrix (Basis q) (Basis q) ℂ := + ops.foldl (fun A (o : Instruction _) => o.matrix * A) 1 + +lemma programMatrix_fold {q : ℕ} (ops : List (Instruction q)) + (A : Matrix (Basis q) (Basis q) ℂ) : + ops.foldl (fun A (o : Instruction _) => o.matrix * A) A = programMatrix ops * A := by + induction ops generalizing A with + | nil => simp [programMatrix] + | cons o ops ih => + change ops.foldl (fun A (o : Instruction q) => o.matrix * A) (o.matrix * A) = + ops.foldl (fun A (o : Instruction q) => o.matrix * A) (o.matrix * 1) * A + rw [ih, ih, Matrix.mul_one, Matrix.mul_assoc] + +lemma programMatrix_unitary {q : ℕ} (ops : List (Instruction q)) : + programMatrix ops ∈ Matrix.unitaryGroup (Basis q) ℂ := by + classical + induction ops with + | nil => exact one_mem _ + | cons o ops ih => + change ops.foldl (fun A (o : Instruction _) => o.matrix * A) (o.matrix * 1) ∈ _ + rw [programMatrix_fold, Matrix.mul_one] + exact mul_mem ih o.unitary + +lemma Circuit.apply_eq_matrix (c : Circuit) (ψ : State c.qubits) : + c.apply ψ = (programMatrix c.instructions).mulVec ψ := by + suffices ∀ (ops : List (Instruction c.qubits)) (ψ : State c.qubits), + ops.foldl (fun v o => o.matrix.mulVec v) ψ = (programMatrix ops).mulVec ψ from + this c.instructions ψ + intro ops + induction ops with + | nil => intro ψ; simp [programMatrix] + | cons o ops ih => + intro ψ + rw [List.foldl_cons, ih] + change _ = (ops.foldl (fun A (o : Instruction _) => o.matrix * A) (o.matrix * 1)).mulVec ψ + rw [programMatrix_fold, Matrix.mul_one, Matrix.mulVec_mulVec] + +/-- Reversing a listed gate stays inside the same twenty gate names. -/ +def Gate.reverse (g : Gate) : Gate := {g with inverse := !g.inverse} + +lemma Gate.reverse_arity (g : Gate) : g.reverse.arity = g.arity := rfl + +lemma Gate.reverse_baseMatrix (g : Gate) (x y : List Bool) : + g.reverse.baseMatrix x y = star (g.baseMatrix y x) := by + cases h : g.inverse <;> simp [Gate.reverse, Gate.baseMatrix, h] + +lemma Gate.reverse_matrix (g : Gate) (x y : List Bool) : + g.reverse.matrix x y = star (g.matrix y x) := by + by_cases h : g.controlled = true + · cases x with + | nil => cases y <;> simp [Gate.matrix, Gate.reverse, h] + | cons a x => + cases y with + | nil => simp [Gate.matrix, Gate.reverse, h] + | cons b y => + cases a <;> cases b <;> simp [Gate.matrix, h, Gate.reverse] + · by_cases hh : x = y + · subst y; simp + · simp [hh, Ne.symm hh] + · simpa [Gate.reverse, h] using g.reverse_baseMatrix x y + · have hf : g.controlled = false := Bool.eq_false_iff.mpr h + simpa [Gate.matrix, hf, Gate.reverse] using g.reverse_baseMatrix x y + +def Instruction.reverse {q : ℕ} (o : Instruction q) : Instruction q := + ⟨o.gate.reverse, o.wire, o.distinct⟩ + +lemma Instruction.reverse_matrix {q : ℕ} (o : Instruction q) : + o.reverse.matrix = star o.matrix := by + classical + ext x y + change (if ∀ i : Fin q, (∀ j, o.wire j ≠ i) → x i = y i then + o.gate.reverse.matrix (List.ofFn (x ∘ o.wire)) (List.ofFn (y ∘ o.wire)) else 0) = + star (if ∀ i : Fin q, (∀ j, o.wire j ≠ i) → y i = x i then + o.gate.matrix (List.ofFn (y ∘ o.wire)) (List.ofFn (x ∘ o.wire)) else 0) + rw [Gate.reverse_matrix] + have he : (∀ i : Fin q, (∀ j, o.wire j ≠ i) → y i = x i) ↔ + (∀ i : Fin q, (∀ j, o.wire j ≠ i) → x i = y i) := by + apply forall_congr' + intro i + exact imp_congr_right (fun _ => eq_comm) + simp only [he] + split_ifs <;> simp + +lemma programMatrix_append {q : ℕ} (a b : List (Instruction q)) : + programMatrix (a ++ b) = programMatrix b * programMatrix a := by + unfold programMatrix + rw [List.foldl_append, programMatrix_fold] + rfl + +lemma programMatrix_reverse {q : ℕ} (ops : List (Instruction q)) : + programMatrix (ops.reverse.map Instruction.reverse) = star (programMatrix ops) := by + induction ops with + | nil => simp [programMatrix] + | cons o ops ih => + rw [List.reverse_cons, List.map_append, programMatrix_append, ih] + change programMatrix [o.reverse] * star (programMatrix ops) = + star (ops.foldl (fun A (o : Instruction q) => o.matrix * A) (o.matrix * 1)) + rw [programMatrix_fold] + simp [programMatrix, Instruction.reverse_matrix] + +def Circuit.reverse (c : Circuit) : Circuit := + ⟨c.qubits, c.instructions.reverse.map Instruction.reverse⟩ + +lemma unitary_finiteInner {ι : Type*} [Fintype ι] [DecidableEq ι] + (A : Matrix ι ι ℂ) (hA : A ∈ Matrix.unitaryGroup ι ℂ) (v w : ι → ℂ) : + Exactness.finiteInner (A.mulVec v) (A.mulVec w) = Exactness.finiteInner v w := by + change star (A.mulVec v) ⬝ᵥ A.mulVec w = star v ⬝ᵥ w + rw [Matrix.star_mulVec, ← Matrix.dotProduct_mulVec, Matrix.mulVec_mulVec] + rw [← Matrix.star_eq_conjTranspose, Matrix.mem_unitaryGroup_iff'.mp hA, + Matrix.one_mulVec] + +lemma unitary_mass {ι : Type*} [Fintype ι] [DecidableEq ι] + (A : Matrix ι ι ℂ) (hA : A ∈ Matrix.unitaryGroup ι ℂ) (v : ι → ℂ) : + (∑ x, Complex.normSq (A.mulVec v x)) = ∑ x, Complex.normSq (v x) := by + apply Complex.ofReal_injective + simpa [Exactness.finiteInner_self] using unitary_finiteInner A hA v v + +lemma Circuit.mass (c : Circuit) (ψ : State c.qubits) : + (∑ x, Complex.normSq (c.apply ψ x)) = ∑ x, Complex.normSq (ψ x) := by + rw [c.apply_eq_matrix] + exact unitary_mass _ (programMatrix_unitary _) _ + +lemma Circuit.output_normalized (c : Circuit) (ℓ N : ℕ) : + (∑ x, Complex.normSq (c.outputState ℓ N x)) = 1 := by + classical + unfold Circuit.outputState + rw [c.mass] + simp + +lemma Circuit.reverse_apply (c : Circuit) (ψ : State c.qubits) : + c.reverse.apply (c.apply ψ) = ψ := by + unfold Circuit.reverse + rw [Circuit.apply_eq_matrix, c.apply_eq_matrix] + change (programMatrix (c.instructions.reverse.map Instruction.reverse)).mulVec + ((programMatrix c.instructions).mulVec ψ) = ψ + rw [programMatrix_reverse, Matrix.mulVec_mulVec, + Matrix.mem_unitaryGroup_iff'.mp (programMatrix_unitary _), Matrix.one_mulVec] + +end ExactQuantumFactoring + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/CleanPermutation.lean b/lean/OAI/Computability/QuantumFactoring/CleanPermutation.lean new file mode 100644 index 0000000000000000000000000000000000000000..dab06ac17da4643699a3daf8d67a87a561fd9de6 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/CleanPermutation.lean @@ -0,0 +1,109 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.OracleLayout + +namespace OAI + +section +open scoped BigOperators + + +namespace ExactQuantumFactoring.BooleanNetwork + +lemma packed_single_swap {n r : ℕ} (x y : Basis n) (j : Fin n) : + packed r x y ∘ Equiv.swap (⟨j.val,by omega⟩ : Fin (n+n+r)) ⟨n+j.val,by omega⟩ = + packed r (Function.update x j (y j)) (Function.update y j (x j)) := by + funext i + by_cases ha : i.val = j.val + · have hi : i = (⟨j.val,by omega⟩ : Fin (n+n+r)) := Fin.ext ha + simp only [hi] + rw [Function.comp_apply, Equiv.swap_apply_left, packed_target] + simp [packed, j.isLt] + · by_cases hb : i.val = n+j.val + · have hi : i = (⟨n+j.val,by omega⟩ : Fin (n+n+r)) := Fin.ext hb + simp only [hi] + rw [Function.comp_apply, Equiv.swap_apply_right, packed_input] + simp [packed, j.isLt] + · rw [Function.comp_apply, Equiv.swap_apply_of_ne_of_ne + (by intro h; exact ha (congrArg Fin.val h)) + (by intro h; exact hb (congrArg Fin.val h))] + unfold packed + split_ifs with hn hnn + · rw [Function.update_of_ne] + intro h; exact ha (congrArg Fin.val h) + · rw [Function.update_of_ne] + intro h + have hh := congrArg Fin.val h + dsimp at hh + omega + · rfl + +def swapPrefix (n r : ℕ) : (k : ℕ) → k ≤ n → List (Instruction (n+n+r)) + | 0, _ => [] + | k+1, h => swapPrefix n r k (by omega) ++ + swapAt ⟨k,by omega⟩ ⟨n+k,by omega⟩ (by intro he; have hh := congrArg Fin.val he; dsimp at hh; omega) + +lemma swapPrefix_length (n r k : ℕ) (hk : k ≤ n) : + (swapPrefix n r k hk).length = 3*k := by + induction k with + | zero => rfl + | succ k ih => simp [swapPrefix, swapAt, ih (by omega)]; omega + +lemma swapPrefix_basis {n r : ℕ} (x y : Basis n) (k : ℕ) (hk : k ≤ n) : + (programMatrix (swapPrefix n r k hk)).mulVec (basisVector (packed r x y)) = + basisVector (packed r (fun i => if i.val if i.val simp [swapPrefix, programMatrix_nil] + | succ k ih => + rw [swapPrefix, programMatrix_append, ← Matrix.mulVec_mulVec, ih (by omega), + swapAt_basis, packed_single_swap _ _ (⟨k,by omega⟩ : Fin n)] + congr 1 + congr 1 <;> funext i + all_goals + by_cases hi : i.val=k + · have he : i = (⟨k,by omega⟩ : Fin n) := Fin.ext hi + simp only [he] + simp + · rw [Function.update_of_ne (by intro he; exact hi (congrArg Fin.val he))] + have he : (i.val < k+1) ↔ i.val funext i <;> simp [i.isLt] + +/-- The standard clean implementation of a bijection uses a verified forward +and inverse Boolean network, two work registers, and only the named gates. -/ +def cleanPermutation {n r : ℕ} (f g : BooleanNetwork n n) + (hf : f.net.count ≤ r) (hg : g.net.count ≤ r) : List (Instruction (n+n+r)) := + oracleOn f hf ++ swapPrefix n r n le_rfl ++ oracleOn g hg + +lemma cleanPermutation_basis {n r : ℕ} (f g : BooleanNetwork n n) + (hf : f.net.count ≤ r) (hg : g.net.count ≤ r) (x : Basis n) + (hfg : g.eval (f.eval x) = x) : + (programMatrix (cleanPermutation f g hf hg)).mulVec + (basisVector (packed r x (fun _ => false))) = + basisVector (packed r (f.eval x) (fun _ => false)) := by + rw [cleanPermutation, programMatrix_append, programMatrix_append, + ← Matrix.mulVec_mulVec, ← Matrix.mulVec_mulVec, oracleOn_basis] + simp only [Bool.false_xor] + rw [swapBlocks_basis, oracleOn_basis, hfg] + simp + +lemma cleanPermutation_length {n r : ℕ} (f g : BooleanNetwork n n) + (hf : f.net.count ≤ r) (hg : g.net.count ≤ r) : + (cleanPermutation f g hf hg).length ≤ 4*f.net.count+4*g.net.count+7*n := by + have h₁ := oracleOn_length f hf + have h₂ := oracleOn_length g hg + simp only [cleanPermutation, List.length_append, swapPrefix_length] + omega + +end ExactQuantumFactoring.BooleanNetwork + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/CleanPermutationEmission.lean b/lean/OAI/Computability/QuantumFactoring/CleanPermutationEmission.lean new file mode 100644 index 0000000000000000000000000000000000000000..7565c8c67333a3f8850d13ff20c17a511e1833c2 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/CleanPermutationEmission.lean @@ -0,0 +1,52 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.CircuitPreparationEmission +import OAI.Computability.QuantumFactoring.EmissionDependentLists + +namespace OAI + + + +section +namespace ExactQuantumFactoring.CircuitEmission +open BitStackProgram BitStackProgram.Emits + +def swapOps (n i : ℕ) : List Op:=[cnotOp i (n+i),cnotOp (n+i) i,cnotOp i (n+i)] +lemma erase_swapPrefix (n r k : ℕ) (h : k≤n) : + (BooleanNetwork.swapPrefix n r k h).map eraseOp=((List.range k).map (swapOps n)).flatten:=by + induction k with + | zero=>rfl + | succ k ih=> + rw [BooleanNetwork.swapPrefix,List.map_append,ih,List.range_succ,List.map_append,List.flatten_append] + rfl +noncomputable def swapOpsP : Procedure (prodCode Nat.bits Nat.bits) (listCode opCode) (fun x=>swapOps x.1 x.2):=by + have hx:=BitStackProgram.Emits.id (prodCode Nat.bits Nat.bits) + have hi:=hx.snd + have hj:=hx.fst.natAdd hi + have ha:=(ofProcedure Emission.cnotOpP).comp (hi.pair hj) + have hb:=(ofProcedure Emission.cnotOpP).comp (hj.pair hi) + exact Classical.choice (ha.listCons (hb.listCons (ha.listCons (const _ _ [])))) +namespace OpsEmits +variable {α : Type} {ea : α→List Bool} {n r : α→ℕ} +lemma swapBlocks (hn : Emits ea unaryCode n) : + OpsEmits ea (fun x=>BooleanNetwork.swapPrefix (n x) (r x) (n x) le_rfl):=by + have h:=(ofProcedure (Procedure.listMapWith (f:=swapOps) 0 [] swapOpsP)).comp (hn.unaryNat.pair hn.range) + exact (h.flatten (⟨plainGate .not,[]⟩ : Op)).congr (fun _=>(erase_swapPrefix _ _ _ _).symm) +lemma cleanPermutation {f g : ∀x,BooleanNetwork (n x) (n x)} + (hf : NetworkEmission.NetEmits ea f) (hg : NetworkEmission.NetEmits ea g) + (hn : Emits ea unaryCode n) (h : ∀x,(f x).net.count≤r x) (j : ∀x,(g x).net.count≤r x) : + OpsEmits ea (fun x=>BooleanNetwork.cleanPermutation (f x) (g x) (h x) (j x)):= + ((oracleOn hf h).append (swapBlocks hn)).append (oracleOn hg j) +lemma singletonHadamard (i : ∀x,Fin (n x)) (hi : Emits ea Nat.bits (fun x=>(i x).val)) : + OpsEmits ea (fun x=>[hadamardAt (i x)]):= + ((ofProcedure Emission.hadamardOpP).comp hi).listCons (const _ _ []) +lemma singletonPhase (i : ∀x,Fin (n x)) (hi : Emits ea Nat.bits (fun x=>(i x).val)) : + OpsEmits ea (fun x=>[phaseAt (i x)]):= + ((ofProcedure Emission.phaseOpP).comp hi).listCons (const _ _ []) +end OpsEmits +end ExactQuantumFactoring.CircuitEmission + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/CleanTranslation.lean b/lean/OAI/Computability/QuantumFactoring/CleanTranslation.lean new file mode 100644 index 0000000000000000000000000000000000000000..2fc4a94ffdf407a6a69128a43b535923a9ccb28b --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/CleanTranslation.lean @@ -0,0 +1,43 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.ControlledTranslation +import OAI.Computability.QuantumFactoring.CleanPermutation + +namespace OAI + +section +open scoped BigOperators + + +namespace ExactQuantumFactoring.ControlledTranslation +open BooleanNetwork + +/-- The clean finite-gate controlled-shift implementation derived from its +forward and inverse verified combinational networks. -/ +def circuit {p b : ℕ} (δ : BooleanNetwork p b) : + List (Instruction ((p+b)+(p+b)+(δ.net.count+158*b+6))) := + cleanPermutation (forward δ) (backward δ) + (by have := forward_count δ; omega) (backward_count δ) + +lemma circuit_basis {p b : ℕ} (δ : BooleanNetwork p b) (x : Basis (p+b)) : + (programMatrix (circuit δ)).mulVec + (basisVector (packed (δ.net.count+158*b+6) x (fun _ => false))) = + basisVector (packed (δ.net.count+158*b+6) + (translate (fun d => bitsValue (δ.eval d)) x) (fun _ => false)) := by + rw [circuit, cleanPermutation_basis _ _ _ _ x (forward_backward δ x), forward_correct] + +lemma circuit_length {p b : ℕ} (δ : BooleanNetwork p b) : + (circuit δ).length ≤ 8*δ.net.count+983*b+7*p+48 := by + have h := cleanPermutation_length (forward δ) (backward δ) + (show (forward δ).net.count ≤ δ.net.count+158*b+6 by have := forward_count δ; omega) + (backward_count δ) + have hf := forward_count δ + have hg := backward_count δ + change (cleanPermutation (forward δ) (backward δ) _ _).length ≤ _ + omega + +end ExactQuantumFactoring.ControlledTranslation + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/ClosedLevelCircuit.lean b/lean/OAI/Computability/QuantumFactoring/ClosedLevelCircuit.lean new file mode 100644 index 0000000000000000000000000000000000000000..d5bad1e60651a85cf66b30d275a745549c0b5ca2 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/ClosedLevelCircuit.lean @@ -0,0 +1,114 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.SplitCandidate +import OAI.Computability.QuantumFactoring.PrimePowerLevels +import OAI.Computability.QuantumFactoring.PrimeComponentCircuit +import OAI.Computability.QuantumFactoring.TwoAdicCircuit + +namespace OAI + +section +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators + + +namespace ExactQuantumFactoring +open BooleanNetwork +namespace BitArithmetic + +/-- Compute the odd part by a bounded gcd and exact integer division. -/ +def oddPartNet {k n : ℕ} (a : BooleanNetwork k n) : BooleanNetwork k n := + (a.pair (primeComponent a (wordConstant (BitVec.ofNat n 2)))).comp (div n) + +lemma oddPartNet_value {k n : ℕ} (hn : 2 ≤ n) (a : BooleanNetwork k n) + (x : Basis k) (ha : (bitsValue (a.eval x)).toNat≠0) : + (bitsValue ((oddPartNet a).eval x)).toNat= + (bitsValue (a.eval x)).toNat/2^padicValNat 2 (bitsValue (a.eval x)).toNat := by + have h2 : 2<2^n := lt_of_lt_of_le (by decide : 2<2^2) + (Nat.pow_le_pow_right (by decide : 0<2) hn) + have hc : (bitsValue ((wordConstant (n:=k) (BitVec.ofNat n 2)).eval x)).toNat=2 := by + rw [wordConstant_eval,BitVec.toNat_ofNat,Nat.mod_eq_of_lt h2] + have hh:=primeComponent_value a (wordConstant (BitVec.ofNat n 2)) x ha + (by rw [hc];exact Nat.prime_two) + rw [hc,Nat.factorization_def _ Nat.prime_two] at hh + rw [oddPartNet,eval_comp,eval_pair,div_word,BitVec.toNat_udiv,hh] + +/-- An exact level count, selected by the bounded divisibility predicate. +The branch at t≥n is zero since a is a nonzero n-bit word. -/ +def closedLevelNet {k n : ℕ} (a : BooleanNetwork k n) (t : ℕ) : BooleanNetwork k n := + if t=0 then oddPartNet a + else if the (hd.mp h)),ite_eq_right he,wordConstant_eval,BitVec.toNat_ofNat,Nat.zero_mod] + · rw [ite_eq_right htn,ite_eq_right (by omega),wordConstant_eval,BitVec.toNat_ofNat,Nat.zero_mod] + +def oddPartBound (n c : ℕ) : ℕ := c+primeComponentBound n (c+n)+216*n*n+56*n+6 +lemma oddPartNet_count {k n c : ℕ} (a : BooleanNetwork k n) (ha : a.net.count≤c) : + (oddPartNet a).net.count≤oddPartBound n c := by + have hp:=primeComponent_count a (wordConstant (BitVec.ofNat n 2)) + (c:=c+n) (by omega) (by rw [wordConstant_count];omega) + have hd:=div_count n + simp only [oddPartNet,count_comp,count_pair] + dsimp only [oddPartBound] + omega + +def closedLevelBound (n c : ℕ) : ℕ := oddPartBound n c+c+1000*n*n+1000*n+100 +lemma closedLevelNet_count {k n c : ℕ} (a : BooleanNetwork k n) (ha : a.net.count≤c) (t : ℕ) : + (closedLevelNet a t).net.count≤closedLevelBound n c := by + have ho:=oddPartNet_count a ha + have hd:=dividesNet_count n (2^t) + have hm:=mul_count n + rw [closedLevelNet] + by_cases ht : t=0 + · rw [ite_eq_left ht] + dsimp only [closedLevelBound];omega + · rw [ite_eq_right ht] + by_cases htn : t packed r x y) ψ (packed r z u) = if u=y then ψ z else 0 := by + classical + rw [encodeState_apply] + simp only [packed_eq_iff] + by_cases hu : u=y + · simp [hu] + · simp [hu] + +/-- Retain the modular value register while interfering the exponent register; +no copy of the exponent or hidden measurement is inserted. -/ +def sampleProgram {n m r : ℕ} (c : BooleanNetwork n m) (hr : c.net.count ≤ r) + (ops : List (Instruction n)) : List (Instruction (n+m+r)) := + oracleOn c hr ++ firstProgram m r ops + +lemma sampleProgram_length {n m r : ℕ} (c : BooleanNetwork n m) (hr : c.net.count ≤ r) + (ops : List (Instruction n)) : + (sampleProgram c hr ops).length ≤ 4*c.net.count+2*m+ops.length := by + have h := oracleOn_length c hr + simp only [sampleProgram,List.length_append,firstProgram_length] + omega + +lemma sampleProgram_amplitude {n m r : ℕ} (c : BooleanNetwork n m) + (hr : c.net.count ≤ r) (ops : List (Instruction n)) (ψ : State n) + (z : Basis n) (u : Basis m) : + (programMatrix (sampleProgram c hr ops)).mulVec + (encodeState (fun x => packed r x (fun _ => false)) ψ) (packed r z u) = + ∑ x, if c.eval x=u then programMatrix ops z x * ψ x else 0 := by + classical + rw [sampleProgram,programMatrix_append,← Matrix.mulVec_mulVec,oracleOn_state] + rw [encodeState,Matrix.mulVec_sum] + simp_rw [Matrix.mulVec_smul,firstProgram_basis] + simp only [Finset.sum_apply,Pi.smul_apply,smul_eq_mul,encoded_packed_coordinate, + matrix_basisVector] + apply Finset.sum_congr rfl + intro x _ + by_cases h : c.eval x=u + · simp only [h,ite_true] + ring + · simp only [h,ite_false,show u ≠ c.eval x from Ne.symm h,mul_zero] + +/-- Coherent sampling on an explicitly encoded logical subspace. Inactive +quantum registers stay present; normalization need not be inferred by analogy +with a stochastic oracle. -/ +lemma sampleProgram_encoded_amplitude {α : Type*} [Fintype α] + {n m r : ℕ} (e : α → Basis n) (c : BooleanNetwork n m) + (hr : c.net.count ≤ r) (ops : List (Instruction n)) (ψ : α → ℂ) + (z : Basis n) (u : Basis m) : + (programMatrix (sampleProgram c hr ops)).mulVec + (encodeState (fun x => packed r (e x) (fun _ => false)) ψ) (packed r z u) = + ∑ x, if c.eval (e x)=u then programMatrix ops z (e x) * ψ x else 0 := by + classical + rw [sampleProgram,programMatrix_append,← Matrix.mulVec_mulVec] + rw [encodeState,Matrix.mulVec_sum] + simp only [Matrix.mulVec_smul,oracleOn_basis,Bool.false_xor] + rw [Matrix.mulVec_sum] + simp_rw [Matrix.mulVec_smul,firstProgram_basis] + simp only [Finset.sum_apply,Pi.smul_apply,smul_eq_mul,encoded_packed_coordinate, + matrix_basisVector] + apply Finset.sum_congr rfl + intro x _ + by_cases h : c.eval (e x)=u + · simp only [h,ite_true] + ring + · simp only [h,ite_false,show u ≠ c.eval (e x) from Ne.symm h,mul_zero] + +end ExactQuantumFactoring + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/CompletedOrderSlots.lean b/lean/OAI/Computability/QuantumFactoring/CompletedOrderSlots.lean new file mode 100644 index 0000000000000000000000000000000000000000..2c980f2a33ec744d751a656d5c7f09647baf9747 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/CompletedOrderSlots.lean @@ -0,0 +1,143 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.TransitionEqualization +import OAI.Computability.QuantumFactoring.ProductStates + +namespace OAI + +section +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators + + +namespace ExactQuantumFactoring +open scoped BigOperators +open Exactness RepeatedTrials OrderTrial + +namespace Completion + +/-- Dummy slots retain their internal preparation too. Only the constant output +is visible to the controller; no branch-local normalization is performed. -/ +lemma dummy_passed_mass {α : Type*} [Fintype α] (ψ : α→ℂ) (n d : ℕ) + (hn : 128 ≤ n) (hψ : ∑ x,Complex.normSq (ψ x)=1) (y₀ : Basis (transitionWidth n)) : + outcomeMass (passed (fun _ => True) y₀ 1 (target n)) + (fresh ψ (transitionWidth n) (2*n) d)=(target n:ℝ) := by + apply passed_mass ψ _ y₀ 1 (target n) hψ + · simpa only [outcomeMass,ite_true,Rat.cast_one] using hψ + · exact DyadicAt.integer d 1 + · exact target_at n + · unfold coinBits; omega + · norm_num + · norm_num + · omega + · exact target_pos (by omega) + · apply target_le_ordinary (by omega : 1 ≤ n) + have hp : (0:ℚ) ≤ 1/(2:ℚ)^(2*n) := by positivity + linarith + +end Completion + +namespace OrderSlots + +abbrev sampleExponent (n : ℕ) := 16*n-2 +lemma sampleExponent_spec {n : ℕ} (hn : 128 ≤ n) : + 2^(sampleExponent n+2)=(2^n)^16 := by + rw [←pow_mul] + congr 1 + unfold sampleExponent + omega + +abbrev Result (n : ℕ) := Completion.Raw (Fin (n^5)→OrderTrial.Raw n (sampleExponent n) n) + (Completion.transitionWidth n) (2*n) ((n+10)*n^5) + +noncomputable instance resultFintype (n : ℕ) : Fintype (Result n) := inferInstance + +noncomputable def fresh (n : ℕ) (a m : Basis n) : Result n→ℂ := + Completion.fresh (tensorState (rawState (sampleExponent n) n a m) (n^5)) + (Completion.transitionWidth n) (2*n) ((n+10)*n^5) + +def Usable {n : ℕ} (a m : Basis n) : Prop := + (bitsValue a).toNat < (bitsValue m).toNat ∧ + IsUnit ((bitsValue a).toNat : ZMod (bitsValue m).toNat) + +noncomputable def unitOrder {n : ℕ} (a m : Basis n) : ℕ := by + classical + exact if h : Usable a m then orderOf h.2.unit else 0 + +noncomputable def canonical {n : ℕ} (a m : Basis n) : Basis (Completion.transitionWidth n) := + natBasis _ (unitOrder a m) + +noncomputable def ordinary {n : ℕ} (a m : Basis n) + (r : Fin (n^5)→OrderTrial.Raw n (sampleExponent n) n) : Basis (Completion.transitionWidth n) := by + classical + exact if Usable a m then + natBasis _ (orderResult (sampleExponent n) n a m (n^5) r) else natBasis _ 0 + +noncomputable def passed {n : ℕ} (a m : Basis n) : Result n→Prop := by + classical + exact if h : Usable a m then + Completion.passed (fun r => orderResult (sampleExponent n) n a m (n^5) r=orderOf h.2.unit) + (canonical a m) (Completion.orderSuccess (orderOf h.2.unit) (n^5)) (Completion.target n) + else Completion.passed (fun _ => True) (canonical a m) 1 (Completion.target n) + +noncomputable def output {n : ℕ} (a m : Basis n) : Result n→Basis (Completion.transitionWidth n) := + Completion.output (ordinary a m) + +lemma fresh_normalized (n : ℕ) (a m : Basis n) : + ∑ r,Complex.normSq (fresh n a m r)=1 := + Completion.fresh_normalized _ _ _ _ (tensor_normalized _ _ (raw_normalized _ _ a m)) + +lemma unitOrder_lt {n : ℕ} (a m : Basis n) (hm : 2 ≤ (bitsValue m).toNat) : + unitOrder a m < 2^n := by + classical + let : NeZero (bitsValue m).toNat := ⟨by omega⟩ + unfold unitOrder + split_ifs with h + · have hh := orderOf_le_card (x:=h.2.unit) + rw [Nat.card_eq_fintype_card,ZMod.card_units_eq_totient] at hh + exact (hh.trans (Nat.totient_le _)).trans_lt (bitsValue m).isLt + · positivity + +lemma passed_mass {n : ℕ} (hn : 128 ≤ n) (a m : Basis n) (hm : 2 ≤ (bitsValue m).toNat) : + outcomeMass (passed a m) (fresh n a m)=(Completion.target n:ℝ) := by + classical + unfold passed + split_ifs with h + · have hlt := unitOrder_lt a m hm + simp only [unitOrder,dite_eq_left h] at hlt + exact Completion.order_passed_mass hn (sampleExponent_spec hn) a m hm h.2.unit + h.2.unit_spec.symm hlt (canonical a m) + · exact Completion.dummy_passed_mass _ n _ hn + (tensor_normalized _ _ (raw_normalized _ _ a m)) (canonical a m) + +lemma passed_output {n : ℕ} (a m : Basis n) (r : Result n) (hp : passed a m r) : + output a m r=canonical a m := by + classical + unfold passed at hp + split_ifs at hp with h + · rcases hp with hp | hp + · simp only [output,Completion.output,ite_eq_right hp.1,ordinary,ite_eq_left h,canonical, + unitOrder,dite_eq_left h,hp.2.1] + · simp only [output,Completion.output,ite_eq_left hp.1,hp.2.1] + · rcases hp with hp | hp + · simp only [output,Completion.output,ite_eq_right hp.1,ordinary,ite_eq_right h,canonical, + unitOrder,dite_eq_right h] + · simp only [output,Completion.output,ite_eq_left hp.1,hp.2.1] + +/-- Every supplied base has exactly z retained mass. Out-of-range entries and nonunits are dummy slots, +not an assumption that a random list consists only of units. -/ +theorem all_passed_mass {n : ℕ} (hn : 128 ≤ n) (m : Basis n) (hm : 2 ≤ (bitsValue m).toNat) + (as : Fin (n^5)→Basis n) : + outcomeMass (fun r : Fin (n^5)→Result n => ∀ i,passed (as i) m (r i)) + (productState (fun i => fresh n (as i) m))=(Completion.target n:ℝ)^(n^5) := by + exact productState_constant_mass _ _ _ (fun _ => passed_mass hn _ _ hm) + +end OrderSlots +end ExactQuantumFactoring + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/CompletedSplit.lean b/lean/OAI/Computability/QuantumFactoring/CompletedSplit.lean new file mode 100644 index 0000000000000000000000000000000000000000..6d47d85a92cc89e1e0b1e0df13eed866676d9917 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/CompletedSplit.lean @@ -0,0 +1,126 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.CompletedOrderSlots +import OAI.Computability.QuantumFactoring.TransitionWords +import OAI.Computability.QuantumFactoring.ProvidedSplits + +namespace OAI + +section +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators + + +namespace ExactQuantumFactoring +open scoped BigOperators +open Exactness RepeatedTrials OrderTrial + +namespace OrderSlots + +lemma unitOrder_eq {n : ℕ} (a m : Basis n) (u : (ZMod (bitsValue m).toNat)ˣ) + (hlt : (bitsValue a).toNat < (bitsValue m).toNat) + (ha : ((bitsValue a).toNat : ZMod (bitsValue m).toNat)=(u : ZMod (bitsValue m).toNat)) : + unitOrder a m=orderOf u := by + classical + have hu : IsUnit ((bitsValue a).toNat : ZMod (bitsValue m).toNat) := ha.symm ▸ u.isUnit + have hva : Usable a m := ⟨hlt,hu⟩ + rw [unitOrder,dite_eq_left hva] + congr 1 + apply Units.ext + exact hu.unit_spec.trans ha + +lemma passed_value {n : ℕ} (a m : Basis n) (hm : 2 ≤ (bitsValue m).toNat) (r : Result n) + (hp : passed a m r) : (bitsValue (output a m r)).toNat=unitOrder a m := by + rw [passed_output a m r hp,canonical,natBasis_value,Nat.mod_eq_of_lt] + exact (unitOrder_lt a m hm).trans_le (TransitionWords.pow_width_le n (n^5)) + +lemma passed_order {n : ℕ} (a m : Basis n) (hm : 2 ≤ (bitsValue m).toNat) + (u : (ZMod (bitsValue m).toNat)ˣ) + (hlt : (bitsValue a).toNat < (bitsValue m).toNat) + (ha : ((bitsValue a).toNat : ZMod (bitsValue m).toNat)=(u : ZMod (bitsValue m).toNat)) + (r : Result n) (hp : passed a m r) : (bitsValue (output a m r)).toNat=orderOf u := by + rw [passed_value a m hm r hp,unitOrder_eq a m u hlt ha] + +end OrderSlots + +namespace CompletedSplit + +abbrev Raw {n : ℕ} (m : Basis n) := + ListSlots.Result n (bitsValue m).toNat × (Fin (n^5)→OrderSlots.Result n) + +noncomputable instance rawFintype {n : ℕ} (m : Basis n) : Fintype (Raw m) := inferInstance + +def bases {n : ℕ} (m : Basis n) (r : ListSlots.Result n (bitsValue m).toNat) : Fin (n^5)→Basis n := + TransitionWords.read (ListSlots.output (bitsValue m).isLt r) + +/-- Actual next fresh registers depend only on the completed list output, +including its rare guessing branch. Previous outcomes remain in the record. -/ +noncomputable def fresh {n : ℕ} (m : Basis n) : Raw m→ℂ := + RecordedHistory.appendState (ListSlots.fresh n (bitsValue m).toNat) + (fun l => productState (fun i => OrderSlots.fresh n (bases m l i) m)) + +noncomputable def passed {n : ℕ} (m : Basis n) (hm : (bitsValue m).toNat≠0) + (p₀ : Component (bitsValue m).toNat) (r : Raw m) : Prop := + ListSlots.passed hm (bitsValue m).isLt p₀ r.1 ∧ + ∀ i,OrderSlots.passed (bases m r.1 i) m (r.2 i) + +noncomputable def pairs {n : ℕ} (m : Basis n) (r : Raw m) : List (ℕ×ℕ) := + List.ofFn (fun i : Fin (n^5) => ((bitsValue (bases m r.1 i)).toNat, + (bitsValue (OrderSlots.output (bases m r.1 i) m (r.2 i))).toNat)) + +noncomputable def divisor {n : ℕ} (m : Basis n) (r : Raw m) : ℕ := + suppliedDivisor (bitsValue m).toNat n (pairs m r) + +lemma fresh_normalized {n : ℕ} (m : Basis n) : ∑ r,Complex.normSq (fresh m r)=1 := by + apply RecordedHistory.append_normalized + · exact ListSlots.fresh_normalized _ _ + · intro l + exact productState_normalized _ (fun _ => OrderSlots.fresh_normalized _ _ _) + +/-- One list transition followed by the K order/dummy transitions has exactly +z^(K+1) retained mass, unconditioned on the successful factor-data computation. -/ +theorem passed_mass {n : ℕ} (hn : 128 ≤ n) (m : Basis n) (hm : 2 ≤ (bitsValue m).toNat) + (hodd : Odd (bitsValue m).toNat) (p₀ p₁ : Component (bitsValue m).toNat) (hne : p₁≠p₀) : + outcomeMass (passed m (by omega) p₀) (fresh m)=(Completion.target n:ℝ)^(n^5+1) := by + change outcomeMass (fun r => ListSlots.passed (by omega) (bitsValue m).isLt p₀ r.1 ∧ + (fun l (rr : Fin (n^5)→OrderSlots.Result n) => ∀ i,OrderSlots.passed (bases m l i) m (rr i)) r.1 r.2) + (RecordedHistory.appendState _ _) = _ + rw [RecordedHistory.append_constant_mass _ _ _ _ ((Completion.target n:ℝ)^(n^5)) + (fun l _ => OrderSlots.all_passed_mass hn m hm (bases m l))] + rw [ListSlots.passed_mass hn hm (bitsValue m).isLt hodd p₀ p₁ hne] + exact (mul_comm _ _).trans (pow_succ (Completion.target n:ℝ) (n^5)).symm + +lemma passed_pair {n : ℕ} (hn : 128 ≤ n) (m : Basis n) (hm : 2 ≤ (bitsValue m).toNat) + (hodd : Odd (bitsValue m).toNat) (p₀ p₁ : Component (bitsValue m).toNat) (hne : p₁≠p₀) + (r : Raw m) (hp : passed m (by omega) p₀ r) : + ∃ u : (ZMod (bitsValue m).toNat)ˣ, + FavorableUnit (by omega : (bitsValue m).toNat≠0) (bitsValue m).isLt p₀ u ∧ + ((u : ZMod (bitsValue m).toNat).val,orderOf u)∈pairs m r := by + let : NeZero (bitsValue m).toNat := ⟨by omega⟩ + obtain ⟨i,u,ha,hf⟩ := ListSlots.passed_good hn (by omega) (bitsValue m).isLt hodd p₀ p₁ hne r.1 hp.1 + have haz : ((bitsValue (bases m r.1 i)).toNat : ZMod (bitsValue m).toNat)=u := by + rw [show (bitsValue (bases m r.1 i)).toNat=(u : ZMod (bitsValue m).toNat).val from ha] + exact ZMod.natCast_zmod_val _ + have ho := OrderSlots.passed_order (bases m r.1 i) m hm u (by change (bitsValue (TransitionWords.read (ListSlots.output (bitsValue m).isLt r.1) i)).toNat < _; rw [ha]; exact (u : ZMod (bitsValue m).toNat).val_lt) haz (r.2 i) (hp.2 i) + refine ⟨u,hf,?_⟩ + exact List.mem_ofFn.mpr ⟨i,Prod.ext ha ho⟩ + +/-- The output is the actual guarded even/root/order divisor scan, not a chosen +mathematical divisor. Both ordinary and guessed good list outputs are covered. -/ +theorem passed_divisor {n : ℕ} (hn : 128 ≤ n) (m : Basis n) (hm : 2 ≤ (bitsValue m).toNat) + (hc : ¬(bitsValue m).toNat.Prime) (hodd : Odd (bitsValue m).toNat) + (p₀ p₁ : Component (bitsValue m).toNat) (hne : p₁≠p₀) + (r : Raw m) (hp : passed m (by omega) p₀ r) : + FactorController.ProperDivisor (bitsValue m).toNat (divisor m r) := by + obtain ⟨u,hf,hu⟩ := passed_pair hn m hm hodd p₀ p₁ hne r hp + exact suppliedDivisor_good hm (bitsValue m).isLt hc (pairs m r) (fun _ _ => ⟨p₀,u,hf,hu⟩) + +end CompletedSplit +end ExactQuantumFactoring + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/CompletionEmission.lean b/lean/OAI/Computability/QuantumFactoring/CompletionEmission.lean new file mode 100644 index 0000000000000000000000000000000000000000..fa830a1c039f4a44fbbccb84098b70504fa5e827 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/CompletionEmission.lean @@ -0,0 +1,60 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.PhysicalCompletionOutput +import OAI.Computability.QuantumFactoring.NetworkPredicateEmission +import OAI.Computability.QuantumFactoring.NetworkModularEmission + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram.Emits +variable {α : Type} {ea : α→List Bool} {W t d q : α→ℕ} +lemma coinBits (hW : Emits ea unaryCode W) (ht : Emits ea unaryCode t) (hd : Emits ea unaryCode d) : + Emits ea unaryCode (fun x=>Completion.coinBits (W x) (t x) (d x)):= + (((hW.unaryAdd ht).unaryAdd (const _ _ 2)).unaryAdd ht).unaryAdd hd +lemma completionWidth (hq : Emits ea unaryCode q) (hW : Emits ea unaryCode W) + (ht : Emits ea unaryCode t) (hd : Emits ea unaryCode d) : + Emits ea unaryCode (fun x=>Completion.totalWidth (q x) (W x) (t x) (d x)):= + ht.unaryAdd (hq.unaryAdd (hW.unaryAdd (coinBits hW ht hd))) +end ExactQuantumFactoring.BitStackProgram.Emits + +namespace ExactQuantumFactoring.NetworkEmission +open BitStackProgram BitStackProgram.Emits +namespace NetEmits +variable {α : Type} {ea : α→List Bool} {q W t d : α→ℕ} +lemma rareWires (hq : Emits ea unaryCode q) (hW : Emits ea unaryCode W) + (ht : Emits ea unaryCode t) (hd : Emits ea unaryCode d) : + NetEmits ea (fun x=>Completion.rareWires (q x) (W x) (t x) (d x)):= + selectSlice (completionWidth hq hW ht hd) ht (const _ _ 0) _ (by intros;simp only [Fin.val_castAdd,Nat.zero_add]) +lemma ordinaryWires (hq : Emits ea unaryCode q) (hW : Emits ea unaryCode W) + (ht : Emits ea unaryCode t) (hd : Emits ea unaryCode d) : + NetEmits ea (fun x=>Completion.ordinaryWires (q x) (W x) (t x) (d x)):= + selectSlice (completionWidth hq hW ht hd) hq ht.unaryNat _ (by intros;rfl) +lemma guessWires (hq : Emits ea unaryCode q) (hW : Emits ea unaryCode W) + (ht : Emits ea unaryCode t) (hd : Emits ea unaryCode d) : + NetEmits ea (fun x=>Completion.guessWires (q x) (W x) (t x) (d x)):= + selectSlice (completionWidth hq hW ht hd) hW (ht.unaryNat.natAdd hq.unaryNat) _ (by intros;simp only [Fin.val_natAdd,Fin.val_castAdd];omega) +lemma retentionWires (hq : Emits ea unaryCode q) (hW : Emits ea unaryCode W) + (ht : Emits ea unaryCode t) (hd : Emits ea unaryCode d) : + NetEmits ea (fun x=>Completion.retentionWires (q x) (W x) (t x) (d x)):= + selectSlice (completionWidth hq hW ht hd) (coinBits hW ht hd) + ((ht.unaryNat.natAdd hq.unaryNat).natAdd hW.unaryNat) _ (by intros;simp only [Fin.val_natAdd];omega) +lemma rareNet (hq : Emits ea unaryCode q) (hW : Emits ea unaryCode W) + (ht : Emits ea unaryCode t) (hd : Emits ea unaryCode d) : + NetEmits ea (fun x=>Completion.rareNet (q x) (W x) (t x) (d x)):= + (rareWires hq hW ht hd).equalOn (wordConst (completionWidth hq hW ht hd) ht (const _ _ 0)) ht +lemma completionOutput {f : ∀x,BooleanNetwork (q x) (W x)} + (hq : Emits ea unaryCode q) (hW : Emits ea unaryCode W) + (ht : Emits ea unaryCode t) (hd : Emits ea unaryCode d) (hf : NetEmits ea f) : + NetEmits ea (fun x=>Completion.outputNet (f x) (t x) (d x)):= + wordMux (rareNet hq hW ht hd) (guessWires hq hW ht hd) ((ordinaryWires hq hW ht hd).comp hf) hW +end NetEmits +end ExactQuantumFactoring.NetworkEmission + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/CompletionFilterCircuit.lean b/lean/OAI/Computability/QuantumFactoring/CompletionFilterCircuit.lean new file mode 100644 index 0000000000000000000000000000000000000000..29bc505c1c055e94ad25f78cda2fbec593b25b42 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/CompletionFilterCircuit.lean @@ -0,0 +1,105 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.DyadicCompletion +import OAI.Computability.QuantumFactoring.RetentionCircuit + +namespace OAI + +section +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators + + +namespace ExactQuantumFactoring +open BooleanNetwork BitArithmetic +namespace Completion +namespace Expressions +variable {v : Type*} + +def ordinaryMass (t : ℕ) (s : RatExpr v) : RatExpr v := + (RatExpr.const (1-1/(2:ℚ)^t)).mul s + +def coefficient (W t : ℕ) (s z : RatExpr v) : RatExpr v := + (RatExpr.ofInt (((RatExpr.const ((2:ℚ)^(W+t+2))).mul + (z.div (ordinaryMass t s))).floor)).div (RatExpr.const ((2:ℚ)^(W+t+2))) + +def guess (W t : ℕ) (s z : RatExpr v) : RatExpr v := + ((z.sub ((coefficient W t s z).mul (ordinaryMass t s))).mul + (RatExpr.const ((2:ℚ)^W))).div (RatExpr.const (1/(2:ℚ)^t)) + +lemma ordinaryMass_value (x : v→ℕ) (t : ℕ) (s : RatExpr v) : + (ordinaryMass t s).eval x=(1-1/(2:ℚ)^t)*s.eval x := by + simp only [ordinaryMass,RatExpr.eval_mul,RatExpr.eval_const] +lemma coefficient_value (x : v→ℕ) (W t : ℕ) (s z : RatExpr v) : + (coefficient W t s z).eval x=coeff W t (s.eval x) (z.eval x) := by + simp only [coefficient,RatExpr.eval_div,RatExpr.eval_ofInt,RatExpr.eval_floor, + RatExpr.eval_mul,RatExpr.eval_const,ordinaryMass_value,coeff,Exactness.completionCoeff] +lemma guess_value (x : v→ℕ) (W t : ℕ) (s z : RatExpr v) : + (guess W t s z).eval x=guessRetention W t (s.eval x) (z.eval x) := by + simp only [guess,RatExpr.eval_div,RatExpr.eval_mul,RatExpr.eval_sub, + RatExpr.eval_const,coefficient_value,ordinaryMass_value, + guessRetention,Exactness.completionRemainder,coeff] + +end Expressions + +/-- Literal deferred completion filter on retained registers. The input s and +canonical-output circuits are to be computed from the verified full log; this +compiler does not smuggle those quantities into the preparation. -/ +def filterNet {v : Type*} {k b W t : ℕ} (d : ℕ) + (s z : RatExpr v) (vars : v→BooleanNetwork k b) + (branch : BooleanNetwork k t) (guess canonical : BooleanNetwork k W) + (coin : NatExpr v) (good : BooleanNetwork k 1) : BooleanNetwork k 1 := + let rare:=zeroWord branch + let ordinaryKeep:=retentionNet (coinBits W t d) (Expressions.coefficient W t s z) coin vars + let guessKeep:=retentionNet (coinBits W t d) (Expressions.guess W t s z) coin vars + ((rare.bnot).band (good.band ordinaryKeep)).bor + (rare.band ((equalOn guess canonical).band guessKeep)) + +lemma filterNet_value {v : Type*} {k b W t : ℕ} (d : ℕ) + (s z : RatExpr v) (vars : v→BooleanNetwork k b) + (branch : BooleanNetwork k t) (guess canonical : BooleanNetwork k W) + (coin : NatExpr v) (good : BooleanNetwork k 1) (x : Basis k) : + (filterNet d s z vars branch guess canonical coin good).eval x 0=true ↔ + ((bitsValue (branch.eval x)).toNat≠0 ∧ (good.eval x 0=true ∧ + coin.eval (fun i=>(bitsValue ((vars i).eval x)).toNat)< + (Int.floor (coeff W t (s.eval (fun i=>(bitsValue ((vars i).eval x)).toNat)) + (z.eval (fun i=>(bitsValue ((vars i).eval x)).toNat))*(2:ℚ)^(coinBits W t d))).toNat)) ∨ + ((bitsValue (branch.eval x)).toNat=0 ∧ (guess.eval x=canonical.eval x ∧ + coin.eval (fun i=>(bitsValue ((vars i).eval x)).toNat)< + (Int.floor (guessRetention W t (s.eval (fun i=>(bitsValue ((vars i).eval x)).toNat)) + (z.eval (fun i=>(bitsValue ((vars i).eval x)).toNat))*(2:ℚ)^(coinBits W t d))).toNat)) := by + have he : (bitsValue (guess.eval x)).toNat=(bitsValue (canonical.eval x)).toNat ↔ + guess.eval x=canonical.eval x := by + constructor + · intro h + exact (bitsEquiv W).injective (BitVec.eq_of_toNat_eq h) + · intro h; rw [h] + simp only [filterNet,eval_bor,Bool.or_eq_true,eval_band,Bool.and_eq_true, + bnot_value,zeroWord_value,retentionNet_value,Expressions.coefficient_value, + equalOn_value,Expressions.guess_value,he] + + +/-- On the very same retained record, the gate flag is exactly the §6 event. -/ +theorem filterNet_passed {α v : Type*} {k b W t d : ℕ} + (s z : RatExpr v) (vars : v→BooleanNetwork k b) + (branch : BooleanNetwork k t) (guess canonical : BooleanNetwork k W) + (coin : NatExpr v) (good : BooleanNetwork k 1) (P : α→Prop) + (x : Basis k) (r : Raw α W t d) (y₀ : Basis W) (S Z : ℚ) + (hbranch : branch.eval x=r.1) (hguess : guess.eval x=r.2.2.1) + (hcanonical : canonical.eval x=y₀) + (hcoin : coin.eval (fun i=>(bitsValue ((vars i).eval x)).toNat)=(bitsValue r.2.2.2).toNat) + (hgood : good.eval x 0=true ↔ P r.2.1) + (hs : s.eval (fun i=>(bitsValue ((vars i).eval x)).toNat)=S) + (hz : z.eval (fun i=>(bitsValue ((vars i).eval x)).toNat)=Z) : + (filterNet d s z vars branch guess canonical coin good).eval x 0=true ↔ passed P y₀ S Z r := by + rw [filterNet_value,hbranch,hguess,hcanonical,hcoin,hgood,hs,hz] + rfl +end Completion +end ExactQuantumFactoring + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/CompletionFilterPolynomial.lean b/lean/OAI/Computability/QuantumFactoring/CompletionFilterPolynomial.lean new file mode 100644 index 0000000000000000000000000000000000000000..cb182135be32aa79be1a1d97756c1367e85f50e9 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/CompletionFilterPolynomial.lean @@ -0,0 +1,78 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.RetainedListFilter +import OAI.Computability.QuantumFactoring.RetainedOrderFilter +import OAI.Computability.QuantumFactoring.RetentionExpressionResources +import OAI.Computability.QuantumFactoring.RationalHeightResources +import OAI.Computability.QuantumFactoring.ExpressionAt + +namespace OAI + + + +section + +namespace ExactQuantumFactoring +namespace RatExprPoly +lemma ofHeight {v : ℕ→Type*} {q : ℕ→ℚ} (h : RatHeightPoly q) : + RatExprPoly (fun n=>RatExpr.const (q n) : ∀n,RatExpr (v n)) := const h.1 h.2 +end RatExprPoly +namespace Completion.Expressions +variable {v : ℕ→Type*} {W t : ℕ→ℕ} {s z : ∀n,RatExpr (v n)} +lemma ordinaryMass_poly (ht : PolyBound t) (hs : RatExprPoly s) : + RatExprPoly (fun n=>ordinaryMass (t n) (s n)) := + (RatExprPoly.ofHeight ((RatHeightPoly.constant 1).sub + ((RatHeightPoly.constant 1).div ((RatHeightPoly.constant 2).pow ht)))).mul hs +lemma coefficient_poly (hW : PolyBound W) (ht : PolyBound t) + (hs : RatExprPoly s) (hz : RatExprPoly z) : + RatExprPoly (fun n=>coefficient (W n) (t n) (s n) (z n)) := by + have hp : RatExprPoly (fun n=>RatExpr.const ((2:ℚ)^(W n+t n+2)) : ∀n,RatExpr (v n)) := + RatExprPoly.ofHeight ((RatHeightPoly.constant 2).pow ((hW.add ht).add (PolyBound.const 2))) + exact (RatExprPoly.ofInt (hp.mul (hz.div (ordinaryMass_poly ht hs))).floor).div hp +lemma guess_poly (hW : PolyBound W) (ht : PolyBound t) + (hs : RatExprPoly s) (hz : RatExprPoly z) : + RatExprPoly (fun n=>guess (W n) (t n) (s n) (z n)) := + ((hz.sub ((coefficient_poly hW ht hs hz).mul (ordinaryMass_poly ht hs))).mul + (RatExprPoly.ofHeight ((RatHeightPoly.constant 2).pow hW))).div + (RatExprPoly.ofHeight ((RatHeightPoly.constant 1).div ((RatHeightPoly.constant 2).pow ht))) +lemma listRateCoin_poly : RatExprPoly (fun n=>listRateCoin n (n^5)) := + ((RatExprPoly.ofNat (NatExprPoly.var (fun _=>1))).div + (RatExprPoly.ofNat (OrderTrial.Expressions.coveringPow_poly + (NatExprPoly.var (fun _=>0)) PolyBound.id))).repeatedSuccess (PolyBound.id.pow 5) +lemma orderRateCoin_poly : RatExprPoly (fun n=>orderRateCoin n (n^5)) := + ((RatExprPoly.ofNat (NatExprPoly.var (fun _=>1))).mul + (OrderTrial.Expressions.lambdaE_poly PolyBound.id + (NatExprPoly.var (fun _=>0)))).repeatedSuccess (PolyBound.id.pow 5) +end Completion.Expressions +lemma retentionNet_at {α : Type*} {len a b : α→ℕ} {v : ℕ→Type*} {T : ℕ→ℕ} + {p : ∀n,RatExpr (v n)} {c : ∀n,NatExpr (v n)} + {vars : ∀x,v (len x)→BooleanNetwork (a x) (b x)} + (hT : PolyBound T) (hp : RatExprPoly p) (hc : NatExprPoly c) + (hb : PolyAt len b) (hv : ∃q : Polynomial ℕ,∀x i,(vars x i).net.count≤q.eval (len x)) : + NetworkAt len (fun x=>retentionNet (T (len x)) (p (len x)) (c (len x)) (vars x)) := + (NatExprAt.ofPoly (thresholdExpr_poly hT hp hc) len).isOne hb hv +namespace Completion +lemma predicateFilter_at {α : Type*} {len a b : α→ℕ} {v : ℕ→Type*} {W t d : ℕ→ℕ} + {s z : ∀n,RatExpr (v n)} {coin : ∀n,NatExpr (v n)} + {vars : ∀x,v (len x)→BooleanNetwork (a x) (b x)} + {branch : ∀x,BooleanNetwork (a x) (t (len x))} + {good guessGood : ∀x,BooleanNetwork (a x) 1} + (hW : PolyBound W) (ht : PolyBound t) (hd : PolyBound d) + (hs : RatExprPoly s) (hz : RatExprPoly z) (hc : NatExprPoly coin) + (hb : PolyAt len b) (hv : ∃q : Polynomial ℕ,∀x i,(vars x i).net.count≤q.eval (len x)) + (hbranch : NetworkAt len branch) (hgood : NetworkAt len good) (hguess : NetworkAt len guessGood) : + NetworkAt len (fun x=>predicateFilter (W:=W (len x)) (d (len x)) + (s (len x)) (z (len x)) (vars x) (branch x) (coin (len x)) (good x) (guessGood x)) := by + have hT : PolyBound (fun n=>coinBits (W n) (t n) (d n)) := by + unfold coinBits;poly_bound + have ho:=retentionNet_at hT (Expressions.coefficient_poly hW ht hs hz) hc hb hv + have hg:=retentionNet_at hT (Expressions.guess_poly hW ht hs hz) hc hb hv + have hr:=hbranch.zeroWord (PolyAt.ofPoly ht len) + exact (hr.bnot.band (hgood.band ho)).bor (hr.band (hguess.band hg)) +end Completion +end ExactQuantumFactoring + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/CompletionPredicateCircuit.lean b/lean/OAI/Computability/QuantumFactoring/CompletionPredicateCircuit.lean new file mode 100644 index 0000000000000000000000000000000000000000..99413354ea565e6458574e00bb31745f6755333e --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/CompletionPredicateCircuit.lean @@ -0,0 +1,71 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.RetrospectiveLists +import OAI.Computability.QuantumFactoring.CompletionFilterCircuit + +namespace OAI + +section +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators + + +namespace ExactQuantumFactoring +open BooleanNetwork BitArithmetic +namespace Completion + +/-- A deferred guess predicate, rather than a circuit that constructs the +canonical CRT string. Both branches use the same retained completion coin. -/ +def predicateFilter {v : Type*} {k b W t : ℕ} (d : ℕ) + (s z : RatExpr v) (vars : v→BooleanNetwork k b) + (branch : BooleanNetwork k t) (coin : NatExpr v) + (good guessGood : BooleanNetwork k 1) : BooleanNetwork k 1 := + let rare:=zeroWord branch + let ordinaryKeep:=retentionNet (coinBits W t d) (Expressions.coefficient W t s z) coin vars + let guessKeep:=retentionNet (coinBits W t d) (Expressions.guess W t s z) coin vars + ((rare.bnot).band (good.band ordinaryKeep)).bor + (rare.band (guessGood.band guessKeep)) + +lemma predicateFilter_value {v : Type*} {k b W t : ℕ} (d : ℕ) + (s z : RatExpr v) (vars : v→BooleanNetwork k b) + (branch : BooleanNetwork k t) (coin : NatExpr v) + (good guessGood : BooleanNetwork k 1) (x : Basis k) : + (predicateFilter (W:=W) d s z vars branch coin good guessGood).eval x 0=true ↔ + ((bitsValue (branch.eval x)).toNat≠0 ∧ (good.eval x 0=true ∧ + coin.eval (fun i=>(bitsValue ((vars i).eval x)).toNat)< + (Int.floor (coeff W t (s.eval (fun i=>(bitsValue ((vars i).eval x)).toNat)) + (z.eval (fun i=>(bitsValue ((vars i).eval x)).toNat))*(2:ℚ)^(coinBits W t d))).toNat)) ∨ + ((bitsValue (branch.eval x)).toNat=0 ∧ (guessGood.eval x 0=true ∧ + coin.eval (fun i=>(bitsValue ((vars i).eval x)).toNat)< + (Int.floor (guessRetention W t (s.eval (fun i=>(bitsValue ((vars i).eval x)).toNat)) + (z.eval (fun i=>(bitsValue ((vars i).eval x)).toNat))*(2:ℚ)^(coinBits W t d))).toNat)) := by + simp only [predicateFilter,eval_bor,Bool.or_eq_true,eval_band,Bool.and_eq_true, + bnot_value,zeroWord_value,retentionNet_value,Expressions.coefficient_value, + Expressions.guess_value] + +/-- Exact same-history predicate semantics: this theorem does not supply or +assume an algorithm for either of the two input Boolean tests. -/ +theorem predicateFilter_test {α v : Type*} {k b W t d : ℕ} + (s z : RatExpr v) (vars : v→BooleanNetwork k b) + (branch : BooleanNetwork k t) (coin : NatExpr v) + (good guessGood : BooleanNetwork k 1) (x : Basis k) + (P : α→Prop) (Q : Basis W→Prop) (r : Raw α W t d) (S Z : ℚ) + (hbranch : branch.eval x=r.1) + (hcoin : coin.eval (fun i=>(bitsValue ((vars i).eval x)).toNat)=(bitsValue r.2.2.2).toNat) + (hgood : good.eval x 0=true ↔ P r.2.1) + (hguess : guessGood.eval x 0=true ↔ Q r.2.2.1) + (hs : s.eval (fun i=>(bitsValue ((vars i).eval x)).toNat)=S) + (hz : z.eval (fun i=>(bitsValue ((vars i).eval x)).toNat)=Z) : + (predicateFilter (W:=W) d s z vars branch coin good guessGood).eval x 0=true ↔ + test P Q S Z r := by + rw [predicateFilter_value,hbranch,hcoin,hgood,hguess,hs,hz] + rfl +end Completion +end ExactQuantumFactoring + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/CompletionPredicateEmission.lean b/lean/OAI/Computability/QuantumFactoring/CompletionPredicateEmission.lean new file mode 100644 index 0000000000000000000000000000000000000000..77e64f7f106f0543c413702feb02a13008b4e97d --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/CompletionPredicateEmission.lean @@ -0,0 +1,53 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.CompletionPredicateCircuit +import OAI.Computability.QuantumFactoring.RationalEmission +import OAI.Computability.QuantumFactoring.ProperDivisorEmission + +namespace OAI + + + +section +namespace ExactQuantumFactoring.NetworkEmission.Emits +open BitStackProgram BitStackProgram.Emits +variable {α v : Type} {ea : α→List Bool} {ev : v→List Bool} {W t : α→ℕ} +local notation "REm" => BitStackProgram.Emits ea (ratExprCode ev) +lemma ordinaryMass {s : α→RatExpr v} (ht : BitStackProgram.Emits ea unaryCode t) (hs : REm s) : + REm (fun x=>Completion.Expressions.ordinaryMass (t x) (s x)):= + rMul (rConst ((const _ _ 1).ratSub ((const _ _ 1).ratDiv ((const _ _ 2).ratPow ht)))) hs +lemma completionCoefficient {s z : α→RatExpr v} (hW : BitStackProgram.Emits ea unaryCode W) + (ht : BitStackProgram.Emits ea unaryCode t) (hs : REm s) (hz : REm z) : + REm (fun x=>Completion.Expressions.coefficient (W x) (t x) (s x) (z x)):=by + have h2:=rConst ((const _ _ 2).ratPow ((hW.unaryAdd ht).unaryAdd (const _ _ 2))) (ev:=ev) + exact rDiv (rOfInt (rFloor (rMul h2 (rDiv hz (ordinaryMass ht hs))))) h2 +lemma completionGuess {s z : α→RatExpr v} (hW : BitStackProgram.Emits ea unaryCode W) + (ht : BitStackProgram.Emits ea unaryCode t) (hs : REm s) (hz : REm z) : + REm (fun x=>Completion.Expressions.guess (W x) (t x) (s x) (z x)):= + rDiv (rMul (rSub hz (rMul (completionCoefficient hW ht hs hz) (ordinaryMass ht hs))) + (rConst ((const _ _ 2).ratPow hW))) (rConst ((const _ _ 1).ratDiv ((const _ _ 2).ratPow ht))) +end ExactQuantumFactoring.NetworkEmission.Emits +namespace ExactQuantumFactoring.NetworkEmission.NetEmits +open BitStackProgram BitStackProgram.Emits +variable {α v : Type} {ea : α→List Bool} {k b W t d : α→ℕ} +lemma predicateFilter {K : ℕ} (en : Fin K ≃ v) {s z : α→RatExpr v} {coin : α→NatExpr v} + {vars : ∀x,v→BooleanNetwork (k x) (b x)} {branch : ∀x,BooleanNetwork (k x) (t x)} + {good guess : ∀x,BooleanNetwork (k x) 1} + (hk : Emits ea unaryCode k) (hb : Emits ea unaryCode b) (hW : Emits ea unaryCode W) + (ht : Emits ea unaryCode t) (hd : Emits ea unaryCode d) + (hs : Emits ea (ratExprCode (fun i:v=>(en.symm i).val.bits)) s) + (hz : Emits ea (ratExprCode (fun i:v=>(en.symm i).val.bits)) z) + (hc : Emits ea (exprCode (fun i:v=>(en.symm i).val.bits)) coin) + (hv : ∀i,NetEmits ea (fun x=>vars x i)) (hr : NetEmits ea branch) + (hg : NetEmits ea good) (hgg : NetEmits ea guess) : + NetEmits ea (fun x=>Completion.predicateFilter (W:=W x) (d x) (s x) (z x) (vars x) (branch x) (coin x) (good x) (guess x)):=by + have hrare:=zeroWord hk ht hr + have ho:=retention en hk hb (coinBits hW ht hd) (Emits.completionCoefficient hW ht hs hz) hc hv + have hguess:=retention en hk hb (coinBits hW ht hd) (Emits.completionGuess hW ht hs hz) hc hv + exact (hrare.bnot.band (hg.band ho)).bor (hrare.band (hgg.band hguess)) +end ExactQuantumFactoring.NetworkEmission.NetEmits + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/CompletionPreparationEmission.lean b/lean/OAI/Computability/QuantumFactoring/CompletionPreparationEmission.lean new file mode 100644 index 0000000000000000000000000000000000000000..97e708176167acc97a5705219c6f9ec271e363aa --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/CompletionPreparationEmission.lean @@ -0,0 +1,35 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.MachineWiringEmission +import OAI.Computability.QuantumFactoring.CompletionEmission + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.NetworkEmission.NetEmits +open BitStackProgram BitStackProgram.Emits +variable {α : Type} {ea : α→List Bool} {k q W t d : α→ℕ} +lemma completionInitial {f : ∀x,BooleanNetwork (k x) (q x)} + (hk : Emits ea unaryCode k) (hW : Emits ea unaryCode W) + (ht : Emits ea unaryCode t) (hd : Emits ea unaryCode d) (hf : NetEmits ea f) : + NetEmits ea (fun x=>Completion.initialNet (f x) (W x) (t x) (d x)):= + (zeros hk ht).pair (hf.pair ((zeros hk hW).pair (zeros hk (coinBits hW ht hd)))) +end ExactQuantumFactoring.NetworkEmission.NetEmits +namespace ExactQuantumFactoring.CircuitEmission.OpsEmits +open BitStackProgram BitStackProgram.Emits +variable {α : Type} {ea : α→List Bool} {q W t d : α→ℕ} +lemma completion {p : ∀x,List (Instruction (q x))} (hp : OpsEmits ea p) + (hq : Emits ea unaryCode q) (hW : Emits ea unaryCode W) + (ht : Emits ea unaryCode t) (hd : Emits ea unaryCode d) : + OpsEmits ea (fun x=>Completion.program (p x) (W x) (t x) (d x)):= + parallel (hadamards ht (fun _=>le_rfl)) (parallel hp + (parallel (hadamards hW (fun _=>le_rfl)) (hadamards (coinBits hW ht hd) (fun _=>le_rfl)) hW) hq) ht +end ExactQuantumFactoring.CircuitEmission.OpsEmits + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/ComponentLevelEmission.lean b/lean/OAI/Computability/QuantumFactoring/ComponentLevelEmission.lean new file mode 100644 index 0000000000000000000000000000000000000000..31d8b27b43b77274bd49449cb5abfb915b63ca04 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/ComponentLevelEmission.lean @@ -0,0 +1,42 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.ComponentPhiCircuit +import OAI.Computability.QuantumFactoring.CanonicalTableEmission + +namespace OAI + + + +section +namespace ExactQuantumFactoring.NetworkEmission.NetEmits +open BitStackProgram BitStackProgram.Emits BitArithmetic +variable {α : Type} {ea : α→List Bool} {k n t : α→ℕ} +lemma oddPart {a : ∀x,BooleanNetwork (k x) (n x)} (hk : Emits ea unaryCode k) + (hn : Emits ea unaryCode n) (ha : NetEmits ea a) : NetEmits ea (fun x=>BitArithmetic.oddPartNet (a x)):= + (ha.pair (primeComponent hk hn ha (wordConst hk hn (const _ _ 2)))).comp (div hn) +lemma closedLevel {a : ∀x,BooleanNetwork (k x) (n x)} (hk : Emits ea unaryCode k) + (hn : Emits ea unaryCode n) (ht : Emits ea unaryCode t) (ha : NetEmits ea a) : + NetEmits ea (fun x=>BitArithmetic.closedLevelNet (a x) (t x)):=by + have ht':=(ht.unaryNat.natSub (const _ _ 1)).boundedUnary ht (fun _=>Nat.sub_le ..) + have hb:=((ha.comp (divides hn (Emits.powTwo ht))).wordMux + (((oddPart hk hn ha).pair (wordConst hk hn (Emits.powTwo ht'))).comp (mul hn)) + (wordConst hk hn (const _ _ 0)) hn) + have h:=ite (ht.unaryNat.natEq (const _ _ 0)) (oddPart hk hn ha) + (ite (ht.unaryNat.natLt hn.unaryNat) hb (wordConst hk hn (const _ _ 0))) + exact h.congr (by intro x;simp only [decide_eq_true_eq];rfl) +lemma componentPhi {m p : ∀x,BooleanNetwork (k x) (n x)} (hk : Emits ea unaryCode k) + (hn : Emits ea unaryCode n) (hm : NetEmits ea m) (hp : NetEmits ea p) : + NetEmits ea (fun x=>BitArithmetic.componentPhiNet (m x) (p x)):=by + have hq:=primeComponent hk hn hm hp + exact natSubOn hk hn hq ((hq.pair hp).comp (div hn)) +lemma componentLevel {m p : ∀x,BooleanNetwork (k x) (n x)} (hk : Emits ea unaryCode k) + (hn : Emits ea unaryCode n) (ht : Emits ea unaryCode t) (hm : NetEmits ea m) (hp : NetEmits ea p) : + NetEmits ea (fun x=>BitArithmetic.componentLevelNet (m x) (p x) (t x)):= + (dividesOn hk hn hp hm).wordMux (closedLevel hk hn ht (componentPhi hk hn hm hp)) + (wordConst hk hn (const _ _ 1)) hn +end ExactQuantumFactoring.NetworkEmission.NetEmits + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/ComponentPhiCircuit.lean b/lean/OAI/Computability/QuantumFactoring/ComponentPhiCircuit.lean new file mode 100644 index 0000000000000000000000000000000000000000..39df41168462c6c35d40ba64e6dba3e8bcc9b558 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/ComponentPhiCircuit.lean @@ -0,0 +1,94 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.CanonicalResidueCircuit +import OAI.Computability.QuantumFactoring.ClosedLevelCircuit + +namespace OAI + +section +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators + + +namespace ExactQuantumFactoring +open BooleanNetwork +namespace BitArithmetic + +/-- Euler's prime-power formula, implemented by n-bit arithmetic on the +computed gcd component. Divisibility by p is a verified-call precondition. -/ +def componentPhiNet {k n : ℕ} (m p : BooleanNetwork k n) : BooleanNetwork k n := + let q:=primeComponent m p + natSubOn q ((q.pair p).comp (div n)) + +lemma componentPhiNet_value {k n : ℕ} (m p : BooleanNetwork k n) (x : Basis k) + (hm : (bitsValue (m.eval x)).toNat≠0) (hp : ((bitsValue (p.eval x)).toNat).Prime) + (hd : (bitsValue (p.eval x)).toNat∣(bitsValue (m.eval x)).toNat) : + (bitsValue ((componentPhiNet m p).eval x)).toNat= + primePowerUnitCount (bitsValue (p.eval x)).toNat + ((bitsValue (m.eval x)).toNat.factorization (bitsValue (p.eval x)).toNat) := by + have hq:=primeComponent_value m p x hm hp + have he:=hp.factorization_pos_of_dvd hm hd + rw [componentPhiNet,natSubOn_value,eval_comp,eval_pair,div_word,BitVec.toNat_udiv,hq] + obtain ⟨e,he'⟩:=Nat.exists_eq_succ_of_ne_zero (Nat.ne_of_gt he) + rw [he',primePowerUnitCount,Nat.succ_sub_one,pow_succ,Nat.mul_div_cancel _ hp.pos] + simpa only [Nat.mul_one,Nat.one_mul,Nat.mul_comm] using + (Nat.mul_sub_left_distrib ((bitsValue (p.eval x)).toNat^e) (bitsValue (p.eval x)).toNat 1).symm + +lemma componentPhiNet_ne_zero {k n : ℕ} (m p : BooleanNetwork k n) (x : Basis k) + (hm : (bitsValue (m.eval x)).toNat≠0) (hp : ((bitsValue (p.eval x)).toNat).Prime) + (hd : (bitsValue (p.eval x)).toNat∣(bitsValue (m.eval x)).toNat) : + (bitsValue ((componentPhiNet m p).eval x)).toNat≠0 := by + rw [componentPhiNet_value m p x hm hp hd,primePowerUnitCount] + exact Nat.ne_of_gt (Nat.mul_pos (by have := hp.two_le;omega) (Nat.pow_pos hp.pos)) + +def componentPhiBound (n c : ℕ) : ℕ := 4*primeComponentBound n c+2*c+1000*n*n+1000*n+100 +lemma componentPhiNet_count {k n c : ℕ} (m p : BooleanNetwork k n) + (hm : m.net.count≤c) (hp : p.net.count≤c) : + (componentPhiNet m p).net.count≤componentPhiBound n c := by + have hq:=primeComponent_count m p hm hp + have hd:=div_count n + have hs:=natSubOn_count (primeComponent m p) (((primeComponent m p).pair p).comp (div n)) + simp only [count_comp,count_pair] at hs + change (natSubOn _ _).net.count≤_ + dsimp only [componentPhiBound] + nlinarith + +def componentLevelNet {k n : ℕ} (m p : BooleanNetwork k n) (t : ℕ) : BooleanNetwork k n := + wordMux (dividesOn p m) (closedLevelNet (componentPhiNet m p) t) + (wordConstant (BitVec.ofNat n 1)) + +lemma componentLevelNet_value {k n : ℕ} (hn : 2≤n) (m p : BooleanNetwork k n) + (x : Basis k) (hm : (bitsValue (m.eval x)).toNat≠0) + (hp : ((bitsValue (p.eval x)).toNat).Prime) (t : ℕ) : + (bitsValue ((componentLevelNet m p t).eval x)).toNat= + if (bitsValue (p.eval x)).toNat∣(bitsValue (m.eval x)).toNat then + closedLevelCount (primePowerUnitCount (bitsValue (p.eval x)).toNat + ((bitsValue (m.eval x)).toNat.factorization (bitsValue (p.eval x)).toNat)) t + else 1 := by + rw [componentLevelNet,wordMux_eval] + by_cases hd : (bitsValue (p.eval x)).toNat∣(bitsValue (m.eval x)).toNat + · rw [ite_eq_left ((dividesOn_value p m x).mpr hd),ite_eq_left hd, + closedLevelNet_value hn _ x (componentPhiNet_ne_zero m p x hm hp hd), + componentPhiNet_value m p x hm hp hd] + · rw [ite_eq_right (fun h=>hd ((dividesOn_value p m x).mp h)),ite_eq_right hd, + wordConstant_eval,BitVec.toNat_ofNat,Nat.mod_eq_of_lt (Nat.one_lt_pow (by omega) (by decide))] + +def componentLevelBound (n c : ℕ) : ℕ := + 2*c+216*n*n+308*n+50+closedLevelBound n (componentPhiBound n c)+8*n +lemma componentLevelNet_count {k n c : ℕ} (m p : BooleanNetwork k n) + (hm : m.net.count≤c) (hp : p.net.count≤c) (t : ℕ) : + (componentLevelNet m p t).net.count≤componentLevelBound n c := by + have hc:=closedLevelNet_count (componentPhiNet m p) (componentPhiNet_count m p hm hp) t + have hd:=dividesOn_count p m + rw [componentLevelNet,wordMux_count,wordConstant_count] + dsimp only [componentLevelBound] + nlinarith +end BitArithmetic +end ExactQuantumFactoring + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/ConcreteExpressionResources.lean b/lean/OAI/Computability/QuantumFactoring/ConcreteExpressionResources.lean new file mode 100644 index 0000000000000000000000000000000000000000..a52c9f47a4ebcba8a789a4515ceca14b214d4934 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/ConcreteExpressionResources.lean @@ -0,0 +1,37 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.PolynomialExpressionResources + +namespace OAI + + + +section + +namespace ExactQuantumFactoring +namespace PolyExpr +variable {v : Type*} +lemma comp_X (a : PolyExpr v) : a.comp X=a := by + induction a with + | C c => rfl + | X => rfl + | add a b ia ib => simp only [comp,ia,ib] + | negation a ia => simp only [comp,ia] + | mul a b ia ib => simp only [comp,ia,ib] +lemma comp_comp (a b c : PolyExpr v) : (a.comp b).comp c=a.comp (b.comp c) := by + induction a with + | C r => rfl + | X => rfl + | add a b ia ib => simp only [comp,ia,ib] + | negation a ia => simp only [comp,ia] + | mul a b ia ib => simp only [comp,ia,ib] +end PolyExpr + +/-- Substitution-stable, fixed-depth polynomial schemas. In particular this +controls the literal syntax of every fixed coefficient, not just its denotation. -/ +def PolySchemaPoly {v : ℕ → Type*} (a : ∀ n, PolyExpr (v n)) : Prop := + ∀ b : ∀ n, PolyExpr (v n), PolyExprPoly b → PolyExprPoly (fun n => (a n).comp (b n)) + +end ExactQuantumFactoring +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/ContinuedFractionCircuit.lean b/lean/OAI/Computability/QuantumFactoring/ContinuedFractionCircuit.lean new file mode 100644 index 0000000000000000000000000000000000000000..4d729a52aceda4b7f16bdc90fff75bff36dc83fd --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/ContinuedFractionCircuit.lean @@ -0,0 +1,159 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.SplitCandidate +import OAI.Computability.QuantumFactoring.ContinuedFractionPairs + +namespace OAI + +section +open scoped BigOperators +open scoped BigOperators + + +namespace ExactQuantumFactoring.BitArithmetic +open BooleanNetwork +open OrderTrial + +abbrev cfWidth (s k : ℕ) := s*(k+1)+1 + +def cfHead (w : ℕ) : BooleanNetwork (w+(w+w)) w := select (Fin.castAdd (w+w)) +def cfTail (w : ℕ) : BooleanNetwork (w+(w+w)) (w+w) := select (Fin.natAdd w) +def cfP (w : ℕ) : BooleanNetwork (w+(w+w)) w := (cfTail w).comp (rootModulus w) +def cfQ (w : ℕ) : BooleanNetwork (w+(w+w)) w := (cfTail w).comp (rootGuess w) +def cfProduct (w : ℕ) : BooleanNetwork (w+(w+w)) w := + (((cfHead w).pair (cfP w)).comp (mul w)).pair (cfQ w) |>.comp (add w) +def cfCombine (w : ℕ) : BooleanNetwork (w+(w+w)) (w+w) := + let z := equalOn (cfP w) (wordConstant (BitVec.ofNat w 0)) + (wordMux z (cfHead w) (cfProduct w)).pair + (wordMux z (wordConstant (BitVec.ofNat w 1)) (cfP w)) + +def convergentNet (w : ℕ) : ℕ → BooleanNetwork (w+w) (w+w) + | 0 => (div w).pair (wordConstant (BitVec.ofNat w 1)) + | k+1 => + ((div w).pair ((rootGuess w).pair (mod w))).comp + ((cfHead w).pair ((cfTail w).comp (convergentNet w k))) |>.comp (cfCombine w) + +lemma cfHead_eval (w : ℕ) (h p q : Basis w) : + (cfHead w).eval (Fin.append h (Fin.append p q))=h := by + funext i + exact Fin.append_left h (Fin.append p q) i +lemma cfTail_eval (w : ℕ) (h : Basis w) (pq : Basis (w+w)) : + (cfTail w).eval (Fin.append h pq)=pq := by + funext i + exact Fin.append_right h pq i +lemma cfP_eval (w : ℕ) (h p q : Basis w) : + (cfP w).eval (Fin.append h (Fin.append p q))=p := by + rw [cfP,eval_comp,cfTail_eval,rootModulus_eval] +lemma cfQ_eval (w : ℕ) (h p q : Basis w) : + (cfQ w).eval (Fin.append h (Fin.append p q))=q := by + rw [cfQ,eval_comp,cfTail_eval,rootGuess_eval] + +lemma cfProduct_value (w : ℕ) (h p q : Basis w) : + (bitsValue ((cfProduct w).eval (Fin.append h (Fin.append p q)))).toNat= + ((bitsValue h).toNat*(bitsValue p).toNat+(bitsValue q).toNat)%2^w := by + simp only [cfProduct,eval_comp,eval_pair,add_word,mul_word,cfHead_eval,cfP_eval,cfQ_eval, + BitVec.toNat_add,BitVec.toNat_mul,Nat.mod_add_mod] + +lemma cfCombine_value {w : ℕ} (hw : 0 hp (hc.mp hh)),ite_eq_right (fun hh => hp (hc.mp hh)),cfP_eval] + · rw [ite_eq_right hp,cfProduct_value,Nat.mod_eq_of_lt hn] + +/-- One recursive circuit is used once per Euclidean level; no exponential +syntax duplication of earlier convergents. -/ +lemma convergentNet_value {s w : ℕ} (k : ℕ) (hw : cfWidth s k ≤ w) + (a b : Basis w) (ha : (bitsValue a).toNat<2^s) (hb : (bitsValue b).toNat<2^s) : + ∃ p q : Basis w, + (convergentNet w k).eval (Fin.append a b)=Fin.append p q ∧ + ((bitsValue p).toNat,(bitsValue q).toNat)=convergentPair (bitsValue a).toNat (bitsValue b).toNat k := by + induction k generalizing a b with + | zero => + refine ⟨(div w).eval (Fin.append a b),(wordConstant (n:=w+w) (BitVec.ofNat w 1)).eval + (Fin.append a b),eval_pair _ _ _,?_⟩ + simp only [div_word,BitVec.toNat_udiv,wordConstant_eval,BitVec.toNat_ofNat,convergentPair] + rw [Nat.mod_eq_of_lt (Nat.one_lt_two_pow (by dsimp [cfWidth] at hw; omega))] + | succ k ih => + let r := (mod w).eval (Fin.append a b) + let d := (div w).eval (Fin.append a b) + have hr : (bitsValue r).toNat=(bitsValue a).toNat%(bitsValue b).toNat := by + + change (bitsValue ((mod w).eval (Fin.append a b))).toNat=_ + rw [mod_word,BitVec.toNat_umod] + have hd : (bitsValue d).toNat=(bitsValue a).toNat/(bitsValue b).toNat := by + + change (bitsValue ((div w).eval (Fin.append a b))).toNat=_ + rw [div_word,BitVec.toNat_udiv] + have hwk : cfWidth s k ≤ w := by dsimp [cfWidth] at *; nlinarith + have hrb : (bitsValue r).toNat<2^s := by rw [hr]; exact (Nat.mod_le _ _).trans_lt ha + obtain ⟨p,q,hpq,he⟩ := ih hwk b r hb hrb + have hep := congrArg Prod.fst he + have heq := congrArg Prod.snd he + simp only [hr] at hep heq + have hn : (bitsValue d).toNat*(bitsValue p).toNat+(bitsValue q).toNat<2^w := by + rw [hd,hep,heq] + by_cases hp : (convergentPair (bitsValue b).toNat ((bitsValue a).toNat%(bitsValue b).toNat) k).1=0 + · rw [hp,mul_zero,zero_add] + have hh := (convergentPair_bound hb ((Nat.mod_le (bitsValue a).toNat (bitsValue b).toNat).trans_lt ha) k).2 + exact hh.trans_le (Nat.pow_le_pow_right (by omega) hwk) + · have hh := (convergentPair_bound ha hb (k+1)).1 + simp only [convergentPair,ite_eq_right hp] at hh + exact hh.trans_le (Nat.pow_le_pow_right (by omega) hw) + obtain ⟨u,v,huv,hun,hvn⟩ := cfCombine_value (by dsimp [cfWidth] at hw; omega) d p q hn + refine ⟨u,v,?_,?_⟩ + · simp only [convergentNet,eval_comp,eval_pair,rootGuess_eval,cfTail_eval] + change (cfCombine w).eval (Fin.append ((cfHead w).eval (Fin.append d (Fin.append b r))) + ((convergentNet w k).eval (Fin.append b r)))=Fin.append u v + rw [cfHead_eval,hpq,huv] + · simp only [hun,hvn,hd,hep,heq,convergentPair] + split_ifs <;> rfl + +lemma cfProduct_count (w : ℕ) : (cfProduct w).net.count ≤ 90*w*w+100*w+12 := by + simp only [cfProduct,count_comp,count_pair,cfHead,cfP,cfQ,cfTail,rootModulus,rootGuess, + count_select,zero_add,add_zero] + have := mul_count w + have := add_count w + omega + +lemma cfCombine_count (w : ℕ) : (cfCombine w).net.count ≤ 90*w*w+400*w+100 := by + have hc := equalOn_count (cfP w) (wordConstant (n:=w+(w+w)) (BitVec.ofNat w 0)) + simp only [cfP,cfTail,rootModulus,count_comp,count_select,wordConstant_count,zero_add] at hc + have hp := cfProduct_count w + simp only [cfCombine,count_pair,wordMux_count,cfHead,cfP,cfTail,rootModulus, + count_comp,count_select,wordConstant_count] + omega + +lemma convergentNet_count (w k : ℕ) : + (convergentNet w k).net.count ≤ (k+1)*(600*w*w+600*w+120) := by + induction k with + | zero => + simp only [convergentNet,count_pair,wordConstant_count] + have := div_count w + nlinarith + | succ k ih => + simp only [convergentNet,count_comp,count_pair,cfHead,cfTail,rootGuess,count_select] + have := div_count w + have := mod_count w + have := cfCombine_count w + nlinarith + +end ExactQuantumFactoring.BitArithmetic + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/ContinuedFractionEmission.lean b/lean/OAI/Computability/QuantumFactoring/ContinuedFractionEmission.lean new file mode 100644 index 0000000000000000000000000000000000000000..fed48841834dcb4bceb062ef6c22ef220944f722 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/ContinuedFractionEmission.lean @@ -0,0 +1,51 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.EmissionLengthBounds +import OAI.Computability.QuantumFactoring.NetworkAtArithmetic +import OAI.Computability.QuantumFactoring.NetworkRecursionEmission +import OAI.Computability.QuantumFactoring.RootCircuitEmission + +namespace OAI + + + +section +namespace ExactQuantumFactoring.NetworkEmission.NetEmits +open BitStackProgram BitStackProgram.Emits BitArithmetic +variable {α : Type} {ea : α→List Bool} {w K : α→ℕ} +lemma div (hw : Emits ea unaryCode w) : NetEmits ea (fun x=>BitArithmetic.div (w x)):= + ⟨fun x=>AIGNetworkEmission.binaryPack NativeAIG.divide (w x), + (ofProcedure AIGNetworkEmission.Emission.divPackP).comp hw,fun x=>AIGNetworkEmission.divPack_value (w x)⟩ +lemma cfHead (hw : Emits ea unaryCode w) : NetEmits ea (fun x=>BitArithmetic.cfHead (w x)):= + selectSlice (hw.unaryAdd (hw.unaryAdd hw)) hw (const _ _ 0) _ (by intros;simp only [Fin.val_castAdd,Nat.zero_add]) +lemma cfTail (hw : Emits ea unaryCode w) : NetEmits ea (fun x=>BitArithmetic.cfTail (w x)):= + selectSlice (hw.unaryAdd (hw.unaryAdd hw)) (hw.unaryAdd hw) hw.unaryNat _ (by intros;rfl) +lemma cfP (hw : Emits ea unaryCode w) : NetEmits ea (fun x=>BitArithmetic.cfP (w x)):= + (cfTail hw).comp (rootModulus hw) +lemma cfQ (hw : Emits ea unaryCode w) : NetEmits ea (fun x=>BitArithmetic.cfQ (w x)):= + (cfTail hw).comp (rootGuess hw) +lemma cfProduct (hw : Emits ea unaryCode w) : NetEmits ea (fun x=>BitArithmetic.cfProduct (w x)):= + ((((cfHead hw).pair (cfP hw)).comp (mul hw)).pair (cfQ hw)).comp (add hw) +lemma cfCombine (hw : Emits ea unaryCode w) : NetEmits ea (fun x=>BitArithmetic.cfCombine (w x)):=by + have hd:=cfP hw + have hc:=hd.equalOn (wordConst (hw.unaryAdd (hw.unaryAdd hw)) hw (const _ _ 0)) hw + exact (hc.wordMux (cfHead hw) (cfProduct hw) hw).pair + (hc.wordMux (wordConst (hw.unaryAdd (hw.unaryAdd hw)) hw (const _ _ 1)) hd hw) +lemma convergent (hw : Emits ea unaryCode w) (hK : Emits ea unaryCode K) : + NetEmits ea (fun x=>BitArithmetic.convergentNet (w x) (K x)):=by + apply boundedStages hK (f:=fun x j=>BitArithmetic.convergentNet (w x) j) + · exact (div hw).pair (wordConst (hw.unaryAdd hw) hw (const _ _ 1)) + · have hx:=(BitStackProgram.Emits.id (prodCode ea (prodCode unaryCode packCode))).precompose + (fun x:Σa,Fin (K a)=>(x.1,(x.2.val,erasePack (BitArithmetic.convergentNet (w x.1) x.2.val)))) + have h:=hw.comp hx.fst + exact (((div h).pair ((rootGuess h).pair (mod h))).comp + ((cfHead h).pair ((cfTail h).comp (ofCanonical hx.snd.snd)))).comp (cfCombine h) + · exact (hw.unaryPoly.add hw.unaryPoly).pull (fun x:Σa,Fin (K a+1)=>x.1) + · exact (hw.unaryPoly.add hw.unaryPoly).pull (fun x:Σa,Fin (K a+1)=>x.1) + · exact NetworkAt.convergentNet (hw.unaryPoly.pull (fun x:Σa,Fin (K a+1)=>x.1)) + ((hK.unaryPoly.pull (fun x:Σa,Fin (K a+1)=>x.1)).of_le (by intro x;have:=x.2.isLt;omega)) +end ExactQuantumFactoring.NetworkEmission.NetEmits + +end + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/ContinuedFractionPairs.lean b/lean/OAI/Computability/QuantumFactoring/ContinuedFractionPairs.lean new file mode 100644 index 0000000000000000000000000000000000000000..db0c19655dc902a2d828676b555d9fb4f346c6f5 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/ContinuedFractionPairs.lean @@ -0,0 +1,93 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.ContinuedFractionRecovery + +namespace OAI + +section +open scoped BigOperators +open scoped BigOperators + + +namespace ExactQuantumFactoring.OrderTrial + +/-- Reduced nonnegative numerator/positive denominator representation; the zero +case is essential because the total rational inverse sends zero to zero. -/ +def convergentPair (a b : ℕ) : ℕ → ℕ×ℕ + | 0 => (a/b,1) + | k+1 => + let p := convergentPair b (a%b) k + if p.1=0 then (a/b,1) else ((a/b)*p.1+p.2,p.1) + +lemma convergentPair_reduced (a b k : ℕ) : + 0<(convergentPair a b k).2 ∧ + Nat.Coprime (convergentPair a b k).1 (convergentPair a b k).2 := by + induction k generalizing a b with + | zero => simp [convergentPair] + | succ k ih => + have hh := ih b (a%b) + simp only [convergentPair] + split_ifs with h + · simp + · constructor + · exact Nat.pos_of_ne_zero h + · simpa [Nat.coprime_add_mul_left_left] using hh.2.symm + +lemma convergentPair_ratio (a b k : ℕ) : + ((convergentPair a b k).1:ℚ)/(convergentPair a b k).2=euclidConvergent a b k := by + induction k generalizing a b with + | zero => simp [convergentPair,euclidConvergent] + | succ k ih => + have hh := ih b (a%b) + by_cases h : (convergentPair b (a%b) k).1=0 + · have he : euclidConvergent b (a%b) k=0 := by rw [← hh,h]; simp + simp [convergentPair,h,euclidConvergent,he] + · have hp : ((convergentPair b (a%b) k).1:ℚ) ≠ 0 := by exact_mod_cast h + simp only [convergentPair,ite_eq_right h,Nat.cast_add,Nat.cast_mul,euclidConvergent] + rw [← hh,inv_div,add_div,mul_div_cancel_right₀ _ hp] + +lemma convergentPair_label (a b k : ℕ) : + rationalLabel (euclidConvergent a b k)= + ((convergentPair a b k).2,(convergentPair a b k).1) := by + rw [← convergentPair_ratio] + exact rationalLabel_reduced (convergentPair_reduced a b k).1 (convergentPair_reduced a b k).2 + +/-- Linear bit growth, rather than syntactic nested rational inverses. -/ +lemma convergentPair_bound {s a b : ℕ} (ha : a<2^s) (hb : b<2^s) (k : ℕ) : + (convergentPair a b k).1<2^(s*(k+1)+1) ∧ + (convergentPair a b k).2<2^(s*(k+1)+1) := by + induction k generalizing a b with + | zero => + have hp : 2^s ≤ 2^(s*1+1) := Nat.pow_le_pow_right (by omega) (by nlinarith) + have hone : 1<2^(s*1+1) := Nat.one_lt_two_pow (by omega) + exact ⟨(Nat.div_le_self a b).trans_lt (ha.trans_le hp),hone⟩ + | succ k ih => + have hm : a%b<2^s := (Nat.mod_le a b).trans_lt ha + obtain ⟨hn,hd⟩ := ih hb hm + have hdiv : a/b<2^s := (Nat.div_le_self a b).trans_lt ha + have hpow : 2^(s*(k+1)+1) ≤ 2^(s*(k+1+1)+1) := + Nat.pow_le_pow_right (by omega) (by nlinarith) + have ha' : a/b<2^(s*(k+1+1)+1) := hdiv.trans_le + (Nat.pow_le_pow_right (by omega) (by nlinarith)) + have hone : 1<2^(s*(k+1+1)+1) := Nat.one_lt_two_pow (by omega) + simp only [convergentPair] + split_ifs + · exact ⟨ha',hone⟩ + · refine ⟨?_,hn.trans_le hpow⟩ + have hs : a/b+1 ≤ 2^s := hdiv + have h₁ : (a/b)*(convergentPair b (a%b) k).1+(convergentPair b (a%b) k).2 < + (a/b+1)*2^(s*(k+1)+1) := by + have hx := Nat.mul_le_mul_left (a/b) hn.le + nlinarith + have h₂ := Nat.mul_le_mul_right (2^(s*(k+1)+1)) hs + apply h₁.trans_le + apply h₂.trans_eq + rw [← pow_add] + congr 1 + ring + +end ExactQuantumFactoring.OrderTrial + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/ContinuedFractionRecovery.lean b/lean/OAI/Computability/QuantumFactoring/ContinuedFractionRecovery.lean new file mode 100644 index 0000000000000000000000000000000000000000..f7cd866acc21e3046ba5c8531f8094430839898a --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/ContinuedFractionRecovery.lean @@ -0,0 +1,283 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.QuantumCore + +namespace OAI + +section +open scoped BigOperators + + +/-! Bounded Euclidean recovery of the manuscript's nearest-bin labels. +The denominator bound is logarithmic, never a search through B labels. -/ +namespace ExactQuantumFactoring.OrderTrial +open scoped BigOperators + +/-- Euclid's finite convergent recurrence, entirely natural/rational arithmetic. -/ +def euclidConvergent (a b : ℕ) : ℕ → ℚ + | 0 => (a/b:ℕ) + | k+1 => (a/b:ℕ)+(euclidConvergent b (a%b) k)⁻¹ + +lemma euclidConvergent_zero_pair (k : ℕ) : ∀ b, + euclidConvergent 0 b k=0 ∧ euclidConvergent b 0 k=0 := by + induction k with + | zero => intro b; simp [euclidConvergent] + | succ k ih => + intro b + constructor <;> simp [euclidConvergent,(ih b).1,(ih b).2] + +lemma euclidConvergent_zero_left (b k : ℕ) : euclidConvergent 0 b k=0 := + (euclidConvergent_zero_pair k b).1 + +lemma euclidConvergent_zero_right (a k : ℕ) : euclidConvergent a 0 k=0 := + (euclidConvergent_zero_pair k a).2 + +lemma real_floor_ratio (a b : ℕ) : ⌊(a:ℝ)/b⌋ = ((a/b:ℕ):ℤ) := by + have hf := Rat.floor_cast (α:=ℝ) ((a:ℚ)/b) + simp only [Rat.cast_div,Rat.cast_natCast] at hf + rw [hf,Rat.floor_natCast_div_natCast] + norm_cast + +lemma euclidConvergent_real (a b k : ℕ) : + euclidConvergent a b k = Real.convergent ((a:ℝ)/b) k := by + induction k generalizing a b with + | zero => + simp only [euclidConvergent,Real.convergent_zero,real_floor_ratio] + norm_cast + | succ k ih => + rw [euclidConvergent,Real.convergent_succ,real_floor_ratio, + Int.fract_div_natCast_eq_div_natCast_mod,inv_div,← ih] + congr 1 + +lemma ratio_euclid (a b : ℕ) : + (a:ℚ)/b = (a/b:ℕ)+((b:ℚ)/((a%b:ℕ):ℚ))⁻¹ := by + have h := Int.floor_add_fract ((a:ℚ)/b) + rw [Rat.floor_natCast_div_natCast,Int.fract_div_natCast_eq_div_natCast_mod] at h + simpa only [Int.cast_natCast,← Int.natCast_ediv,inv_div] using h.symm + +/-- Two Euclidean steps halve the denominator; the zero remainder is treated +separately, since natural remainder by zero is not zero. -/ +lemma euclid_two_halving {b r : ℕ} (hr : 0.trans + exact Nat.mod_eq_of_lt (by omega) + rw [hmod] + omega + +/-- At most twice the denominator bit bound suffices, including rational +termination and all later convergents. -/ +lemma euclidConvergent_terminal (s a b h : ℕ) (hb : b<2^s) : + euclidConvergent a b (2*s+h) = (a:ℚ)/b := by + induction s generalizing a b h with + | zero => + have : b=0 := by simpa using hb + subst b + simp [euclidConvergent_zero_right] + | succ s ih => + by_cases hb0 : b=0 + · subst b + simp [euclidConvergent_zero_right] + have hbpos : 0 nlinarith + +lemma bin_lt {Q d j : ℕ} (hd : 0 rationalLabel (euclidConvergent k Q i))).filter + (fun l => decide (IsBinLabel Q B k l)) + +lemma mem_recoveredLabels {s Q B k : ℕ} {l : ℕ×ℕ} : + l ∈ recoveredLabels s Q B k ↔ + IsBinLabel Q B k l ∧ ∃ i≤2*s, rationalLabel (euclidConvergent k Q i)=l := by + simp only [recoveredLabels,List.mem_filter,List.mem_map,List.mem_range,decide_eq_true_eq] + constructor + · rintro ⟨⟨i,hi,he⟩,hl⟩ + exact ⟨hl,i,by omega,he⟩ + · rintro ⟨hl,i,hi,he⟩ + exact ⟨⟨i,by omega,he⟩,hl⟩ + +lemma recoveredLabels_complete {s Q B k d j : ℕ} + (hQ : B^2≤Q) (hsize : Q<2^s) (hl : IsBinLabel Q B k (d,j)) : + (d,j) ∈ recoveredLabels s Q B k := by + obtain ⟨hd,hdB,hjd,hcop,hbin⟩ := hl + have hdQ : d^2 simp [he] at hm + | cons r rs => + have hr : IsBinLabel Q B k r := (mem_recoveredLabels.mp (by rw [he]; simp)).1 + simpa only [List.head?_cons] using congrArg some (hr.unique hQ hl) + +lemma recoverLabel_iff {s Q B k : ℕ} {l : ℕ×ℕ} + (hQ : B^2≤Q) (hsize : Q<2^s) : + recoverLabel s Q B k=some l ↔ IsBinLabel Q B k l := + ⟨recoverLabel_sound,recoverLabel_complete hQ hsize⟩ + +end ExactQuantumFactoring.OrderTrial + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/ControlledHadamard.lean b/lean/OAI/Computability/QuantumFactoring/ControlledHadamard.lean new file mode 100644 index 0000000000000000000000000000000000000000..6eda3a657ef3be670279e6599b93150c29c08066 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/ControlledHadamard.lean @@ -0,0 +1,116 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.PhysicalAmplification +import OAI.Computability.QuantumFactoring.ReadOnlyCircuit + +namespace OAI + +section +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators + + +namespace ExactQuantumFactoring +open scoped BigOperators + +/-- One of the literal fixed alphabet gates; the extra control is the first +wire and is never modified. -/ +abbrev controlledHadamardAt {q : ℕ} (c t : Fin q) (h : c≠t) : Instruction q := + ⟨⟨.hadamard,false,true⟩, ![c,t], by + change Function.Injective (![c,t] : Fin 2→Fin q) + intro i j he + fin_cases i <;> fin_cases j <;> simp_all⟩ + +lemma controlledHadamardAt_matrix {q : ℕ} (c t : Fin q) (h : c≠t) (x y : Basis q) : + (controlledHadamardAt c t h).matrix y x = + if x c then (hadamardAt t).matrix y x else if y=x then 1 else 0 := by + classical + have ho : (∀ i : Fin q,(∀ j : Fin 2, (![c,t] : Fin 2→Fin q) j≠i)→y i=x i) ↔ + (∀ i : Fin q, i≠c→i≠t→y i=x i) := by + constructor + · intro hh i hic hit + apply hh i + intro j + fin_cases j + · exact Ne.symm hic + · exact Ne.symm hit + · intro hh i hi + exact hh i (Ne.symm (hi 0)) (Ne.symm (hi 1)) + change (if ∀ i : Fin q,(∀ j : Fin 2, (![c,t] : Fin 2→Fin q) j≠i)→y i=x i then + (Gate.mk .hadamard false true).matrix + (List.ofFn (y∘(![c,t] : Fin 2→Fin q))) + (List.ofFn (x∘(![c,t] : Fin 2→Fin q))) else 0)=_ + simp only [ho,List.ofFn_succ,List.ofFn_zero,Function.comp_apply, + Matrix.cons_val_zero,Matrix.cons_val_succ] + rw [hadamardAt_matrix] + have hyc : (∀ i : Fin q,i≠t→y i=x i) ↔ y c=x c ∧ (∀ i : Fin q,i≠c→i≠t→y i=x i) := by + constructor + · exact fun hh => ⟨hh c h,fun i _ hit => hh i hit⟩ + · rintro ⟨hc,hh⟩ i hit + by_cases hic : i=c + · simpa [hic] using hc + · exact hh i hic hit + have heq : y=x ↔ y c=x c ∧ y t=x t ∧ (∀ i : Fin q,i≠c→i≠t→y i=x i) := by + constructor + · rintro rfl; simp + · rintro ⟨hc,ht,hh⟩ + funext i + by_cases hic : i=c + · simpa [hic] using hc + · by_cases hit : i=t + · simpa [hit] using ht + · exact hh i hic hit + simp only [hyc,heq] + cases xc : x c <;> cases yc : y c <;> + simp only [Gate.matrix,Gate.baseMatrix,Bool.true_eq,Bool.false_eq_true,ite_true,ite_false, + Primitive.matrix,List.cons.injEq, and_true] + all_goals split_ifs <;> simp_all + +lemma controlledHadamardAt_basis {q : ℕ} (c t : Fin q) (h : c≠t) (x : Basis q) : + (controlledHadamardAt c t h).matrix.mulVec (basisVector x)= + if x c then (hadamardAt t).matrix.mulVec (basisVector x) else basisVector x := by + classical + rw [matrix_basisVector] + funext y + rw [controlledHadamardAt_matrix] + cases hx : x c <;> simp [matrix_basisVector,basisVector] + +lemma controlledHadamardAt_target {q : ℕ} (c t : Fin q) (h : c≠t) : + (controlledHadamardAt c t h).target=t := rfl + +/-- On a sector with a fixed control, controlled H is H or the identity on an +arbitrary coherent state, including all old retained work. -/ +lemma controlledHadamardAt_sector {q : ℕ} (c t : Fin q) (h : c≠t) (b : Bool) + (ψ : State q) (hs : Supported (fun x => x c=b) ψ) : + (controlledHadamardAt c t h).matrix.mulVec ψ= + if b then (hadamardAt t).matrix.mulVec ψ else ψ := by + classical + funext y + change (∑ x,(controlledHadamardAt c t h).matrix y x*ψ x)=_ + simp_rw [controlledHadamardAt_matrix] + cases b + · simp only [Bool.false_eq_true,ite_false] + calc + _ = ∑ x : Basis q,(if y=x then (1 : ℂ) else 0)*ψ x := by + apply Finset.sum_congr rfl + intro x _ + by_cases hx : x c=false + · simp [hx] + · rw [hs x hx]; simp + _ = ψ y := by simp + · simp only [ite_true] + change _=∑ x,(hadamardAt t).matrix y x*ψ x + apply Finset.sum_congr rfl + intro x _ + by_cases hx : x c=true + · simp [hx] + · rw [hs x hx]; simp + +end ExactQuantumFactoring + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/ControlledTranslation.lean b/lean/OAI/Computability/QuantumFactoring/ControlledTranslation.lean new file mode 100644 index 0000000000000000000000000000000000000000..40dc8c0aedd4d13a89a4bd650ed802dff4f7d911 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/ControlledTranslation.lean @@ -0,0 +1,95 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitArithmeticDivision + +namespace OAI + +section +open scoped BigOperators + + +namespace ExactQuantumFactoring +open BooleanNetwork + +namespace ControlledTranslation + +def dataPart {p b : ℕ} (x : Basis (p+b)) : Basis p := fun i => x (i.castAdd b) +def phasePart {p b : ℕ} (x : Basis (p+b)) : Basis b := fun i => x (Fin.natAdd p i) + +def addInput {p b : ℕ} (δ : BooleanNetwork p b) : BooleanNetwork (p+b) (b+b) := + (select (Fin.natAdd p)).pair ((select (fun i => i.castAdd b)).comp δ) + +def forward {p b : ℕ} (δ : BooleanNetwork p b) : BooleanNetwork (p+b) (p+b) := + (select (fun i => i.castAdd b)).pair ((addInput δ).comp (BitArithmetic.add b)) + +def backward {p b : ℕ} (δ : BooleanNetwork p b) : BooleanNetwork (p+b) (p+b) := + (select (fun i => i.castAdd b)).pair ((addInput δ).comp (BitArithmetic.sub b)) + +def translate {p b : ℕ} (δ : Basis p → BitVec b) (x : Basis (p+b)) : Basis (p+b) := + Fin.append (dataPart x) (fun i => (bitsValue (phasePart x) + δ (dataPart x)).getLsbD i.val) + +def untranslate {p b : ℕ} (δ : Basis p → BitVec b) (x : Basis (p+b)) : Basis (p+b) := + Fin.append (dataPart x) (fun i => (bitsValue (phasePart x) - δ (dataPart x)).getLsbD i.val) + +lemma input_words {p b : ℕ} (δ : BooleanNetwork p b) (x : Basis (p+b)) : + BitArithmetic.leftWord ((addInput δ).eval x) = bitsValue (phasePart x) ∧ + BitArithmetic.rightWord ((addInput δ).eval x) = bitsValue (δ.eval (dataPart x)) := by + simp only [addInput, eval_pair, eval_comp, eval_select, BitArithmetic.leftWord, + BitArithmetic.rightWord, Function.comp_apply, Fin.append_left, Fin.append_right] + exact ⟨rfl,rfl⟩ + +lemma forward_correct {p b : ℕ} (δ : BooleanNetwork p b) (x : Basis (p+b)) : + (forward δ).eval x = translate (fun d => bitsValue (δ.eval d)) x := by + rw [forward, eval_pair, eval_comp] + unfold translate + congr 1 + funext i + rw [BitArithmetic.add_correct, (input_words δ x).1, (input_words δ x).2] + +lemma backward_correct {p b : ℕ} (δ : BooleanNetwork p b) (x : Basis (p+b)) : + (backward δ).eval x = untranslate (fun d => bitsValue (δ.eval d)) x := by + rw [backward, eval_pair, eval_comp] + unfold untranslate + congr 1 + funext i + rw [BitArithmetic.sub_correct, (input_words δ x).1, (input_words δ x).2] + +@[simp] lemma dataPart_append {p b : ℕ} (d : Basis p) (z : Basis b) : + dataPart (Fin.append d z) = d := by funext i; simp [dataPart] +@[simp] lemma phasePart_append {p b : ℕ} (d : Basis p) (z : Basis b) : + phasePart (Fin.append d z) = z := by funext i; simp [phasePart] + +lemma untranslate_translate {p b : ℕ} (δ : Basis p → BitVec b) (x : Basis (p+b)) : + untranslate δ (translate δ x) = x := by + simp only [untranslate, translate, dataPart_append, phasePart_append, bitsValue_bits, + BitVec.add_sub_cancel, bitsValue_bit] + exact Fin.append_castAdd_natAdd + +lemma translate_untranslate {p b : ℕ} (δ : Basis p → BitVec b) (x : Basis (p+b)) : + translate δ (untranslate δ x) = x := by + simp only [untranslate, translate, dataPart_append, phasePart_append, bitsValue_bits, + BitVec.sub_add_cancel, bitsValue_bit] + exact Fin.append_castAdd_natAdd + +lemma forward_backward {p b : ℕ} (δ : BooleanNetwork p b) (x : Basis (p+b)) : + (backward δ).eval ((forward δ).eval x) = x := by + rw [backward_correct, forward_correct, untranslate_translate] + +lemma forward_count {p b : ℕ} (δ : BooleanNetwork p b) : + (forward δ).net.count ≤ δ.net.count+86*b+6 := by + simp only [forward, addInput, count_pair, count_comp, count_select, Nat.zero_add] + have := BitArithmetic.add_count b + omega + +lemma backward_count {p b : ℕ} (δ : BooleanNetwork p b) : + (backward δ).net.count ≤ δ.net.count+158*b+6 := by + simp only [backward, addInput, count_pair, count_comp, count_select, Nat.zero_add] + have := BitArithmetic.sub_count b + omega + +end ControlledTranslation +end ExactQuantumFactoring + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/ControllerQueries.lean b/lean/OAI/Computability/QuantumFactoring/ControllerQueries.lean new file mode 100644 index 0000000000000000000000000000000000000000..484ecc6c74d62afa62f60e02c8d2074aa5758cbf --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/ControllerQueries.lean @@ -0,0 +1,149 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.ProvidedSplits + +namespace OAI + +section +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators + + +namespace ExactQuantumFactoring.FactorController + +/-- The actual queried moduli, in chronological order. A rejected divisor +aborts and does not query nonexistent later work. -/ +def queries (choose : ℕ→ℕ→ℕ) : ℕ→ℕ→List ℕ→List (ℕ×ℕ) + | _, _, [] => [] + | 0, _, _::_ => [] + | fuel+1, i, m::ms => + if m.Prime then queries choose fuel (i+1) ms + else (i,m)::(if ProperDivisor m (choose i m) then + queries choose fuel (i+1) (choose i m::m/choose i m::ms) else []) + +lemma queries_length (choose : ℕ→ℕ→ℕ) (fuel i : ℕ) (ms : List ℕ) : + (queries choose fuel i ms).length ≤ fuel := by + induction fuel generalizing i ms with + | zero => cases ms <;> simp [queries] + | succ fuel ih => + cases ms with + | nil => simp [queries] + | cons m ms => + simp only [queries] + split_ifs with hp hd + · exact (ih _ _).trans (by omega) + · simpa only [List.length_cons] using Nat.succ_le_succ (ih (i+1) _) + · simp + +/-- All-good is required ONLY at queries of this very run, not at a table of +counterfactual future requests. Exhaustion is excluded by the split weight. -/ +theorem run_complete_on_queries (choose : ℕ→ℕ→ℕ) {fuel i : ℕ} {ms : List ℕ} + (hms : ∀ m∈ms, 2 ≤ m) (hw : weight ms ≤ fuel) + (hg : ∀ im∈queries choose fuel i ms, ProperDivisor im.2 (choose im.1 im.2)) : + ∃ ps, run choose fuel i ms=some ps := by + induction fuel generalizing i ms with + | zero => + cases ms with + | nil => exact ⟨[],rfl⟩ + | cons m ms => + have hp := splitWeight_pos (hms m (by simp)) + simp only [weight,List.map_cons,List.sum_cons] at hw + omega + | succ fuel ih => + cases ms with + | nil => exact ⟨[],rfl⟩ + | cons m ms => + have hm := hms m (by simp) + have ht : ∀ a∈ms,2 ≤ a := fun a ha => hms a (by simp [ha]) + by_cases hp : m.Prime + · have hw' : weight ms ≤ fuel := by rw [weight_prime m ms hp] at hw; omega + have hg' : ∀ im∈queries choose fuel (i+1) ms, ProperDivisor im.2 (choose im.1 im.2) := by + intro im hi + exact hg im (by simpa only [queries,ite_eq_left hp] using hi) + obtain ⟨ps,hps⟩ := ih ht hw' hg' + exact ⟨m::ps,by simp only [run,ite_eq_left hp,hps,Option.map_some]⟩ + · have hd := hg (i,m) (by simp only [queries,ite_eq_right hp,List.mem_cons]; exact Or.inl trivial) + have hd' : ProperDivisor m (choose i m) := hd + have hq := hd'.quotient + have hw' : weight (choose i m::m/choose i m::ms) ≤ fuel := by + rw [weight_split hd' ms] at hw + omega + have hm' : ∀ a∈choose i m::m/choose i m::ms,2 ≤ a := by + intro a ha + rcases List.mem_cons.mp ha with rfl | ha + · have := hd'.1; omega + · rcases List.mem_cons.mp ha with rfl | ha + · exact hq.1 + · exact ht a ha + have hg' : ∀ im∈queries choose fuel (i+1) (choose i m::m/choose i m::ms), + ProperDivisor im.2 (choose im.1 im.2) := by + intro im hi + exact hg im (by simp only [queries,ite_eq_right hp,ite_eq_left hd',List.mem_cons]; exact Or.inr hi) + obtain ⟨ps,hps⟩ := ih hm' hw' hg' + exact ⟨ps,by simp only [run,ite_eq_right hp,ite_eq_left hd',hps]⟩ + +lemma queries_bounded (choose : ℕ→ℕ→ℕ) {fuel i N : ℕ} {ms : List ℕ} + (hms : ∀ m∈ms,2 ≤ m ∧ m ≤ N) : + ∀ im∈queries choose fuel i ms, 2 ≤ im.2 ∧ im.2 ≤ N ∧ ¬im.2.Prime := by + induction fuel generalizing i ms with + | zero => cases ms <;> simp [queries] + | succ fuel ih => + cases ms with + | nil => simp [queries] + | cons m ms => + have hm := hms m (by simp) + have ht : ∀ a∈ms,2 ≤ a ∧ a ≤ N := fun a ha => hms a (by simp [ha]) + simp only [queries] + split_ifs with hp hd + · exact ih ht + · intro im hi + rcases List.mem_cons.mp hi with rfl | hi + · exact ⟨hm.1,hm.2,hp⟩ + · apply ih (ms:=choose i m::m/choose i m::ms) ?_ im hi + intro a ha + rcases List.mem_cons.mp ha with rfl | ha + · exact ⟨by have := hd.1; omega,hd.2.1.le.trans hm.2⟩ + · rcases List.mem_cons.mp ha with rfl | ha + · exact ⟨hd.quotient.1,hd.quotient.2.1.le.trans hm.2⟩ + · exact ht a ha + · intro im hi + have he : im=(i,m) := by simpa only [List.mem_singleton] using hi + subst im + exact ⟨hm.1,hm.2,hp⟩ + +/-- Instantiate the local event with the source's favorable list and actual +true-order outputs. Only recorded queries, no counterfactual oracle inputs. -/ +theorem supplied_node_complete_on_queries {N n : ℕ} (hN : 2 ≤ N) (hb : N < 2^n) + (outputs : ℕ→ℕ→List (ℕ×ℕ)) + (hg : ∀ im∈queries (fun i m => suppliedDivisor m n (outputs i m)) (2*n) 0 [N], + ∀ (hm : 2 ≤ im.2) (hle : im.2 ≤ N), Odd im.2 → ¬Primality.PerfectPower im.2 → + ∃ (p₀ : Component im.2) (u : (ZMod im.2)ˣ), + FavorableUnit (by omega : im.2≠0) (hle.trans_lt hb) p₀ u ∧ + ((u : ZMod im.2).val,orderOf u)∈outputs im.1 im.2) : + ∃ ps, run (fun i m => suppliedDivisor m n (outputs i m)) (2*n) 0 [N]=some ps := by + apply run_complete_on_queries _ (by + intro m hm + have he : m=N := by simpa using hm + subst m + exact hN) + · have hh := AuxiliaryTree.splitWeight_bound (by omega) hb + simp only [weight,List.map_cons,List.map_nil,List.sum_cons,List.sum_nil,add_zero] + omega + · intro im hi + have hbounds := queries_bounded (fun i m => suppliedDivisor m n (outputs i m)) + (N:=N) (by + intro m hm + have he : m=N := by simpa using hm + subst m + exact ⟨hN,le_rfl⟩) im hi + exact suppliedDivisor_good hbounds.1 (hbounds.2.1.trans_lt hb) hbounds.2.2 _ + (hg im hi hbounds.1 hbounds.2.1) + +end ExactQuantumFactoring.FactorController + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/CoveringPowerEmission.lean b/lean/OAI/Computability/QuantumFactoring/CoveringPowerEmission.lean new file mode 100644 index 0000000000000000000000000000000000000000..ada530605098f1f3ee874faa98d6d4f9c504d47f --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/CoveringPowerEmission.lean @@ -0,0 +1,120 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.BitStackPowers +import OAI.Computability.QuantumFactoring.ExpressionPowerEmission + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.NetworkEmission +open BitStackProgram BitStackProgram.Procedure +variable {v : Type} (ev : v→List Bool) +lemma bits_length_max_le (a b : ℕ) : (max a b).bits.length≤a.bits.length+b.bits.length:=by + rcases le_total a b with h|h + · rw [max_eq_right h];omega + · rw [max_eq_left h];omega +lemma tokenCode_length_append (a b : List (ExprToken v)) : + (listCode (exprTokenCode ev) (a++b)).length=(listCode (exprTokenCode ev) a).length+(listCode (exprTokenCode ev) b).length-1:=by + have h:=listCode_length_append (exprTokenCode ev) a b;omega +lemma exprCode_ite_le (a b c d : NatExpr v) : + (exprCode ev (.iteLe a b c d)).length≤(exprCode ev a).length+(exprCode ev b).length+ + (exprCode ev c).length+(exprCode ev d).length+100:=by + have h1:=bits_length_max_le a.maxConst b.maxConst + have h2:=bits_length_max_le c.maxConst d.maxConst + have h3:=bits_length_max_le (max a.maxConst b.maxConst) (max c.maxConst d.maxConst) + simp only [exprCode_length,NatExpr.size,NatExpr.maxConst,exprTokens,muxTokens,leTokens] + have hpair : (listCode (exprTokenCode ev) [pairToken]).length=7:=rfl + have ho5 : (listCode (exprTokenCode ev) [opToken 5,compToken]).length=21:=rfl + have ho6 : (listCode (exprTokenCode ev) [opToken 6,compToken]).length=23:=rfl + have ho7 : (listCode (exprTokenCode ev) [opToken 7,compToken]).length=23:=rfl + simp only [tokenCode_length_append,hpair,ho5,ho6,ho7] + omega + +def coveringStep (s : ℕ×(NatExpr v×NatExpr v)) : ℕ×(NatExpr v×NatExpr v):= + (s.1*2,s.2.1,.iteLe s.2.1 (.const s.1) s.2.2 (.const (s.1*2))) +lemma coveringStep_pow (s : ℕ×(NatExpr v×NatExpr v)) (i : ℕ) : + ((coveringStep^[i]) s).1=s.1*2^i:=by + induction i with + | zero=>simp + | succ i ih=>rw [Function.iterate_succ_apply'];change ((coveringStep^[i]) s).1*2=_ + rw [ih,pow_succ,Nat.mul_assoc] +lemma coveringStep_base (s : ℕ×(NatExpr v×NatExpr v)) (i : ℕ) : + ((coveringStep^[i]) s).2.1=s.2.1:=by + induction i with + | zero=>rfl + | succ i ih=>rw [Function.iterate_succ_apply'];exact ih +lemma coveringStep_pow_size (s : ℕ×(NatExpr v×NatExpr v)) (i : ℕ) : + (((coveringStep^[i]) s).1).bits.length≤(s.1).bits.length+2*i+1:=by + rw [coveringStep_pow] + have hm:=bits_length_mul s.1 (2^i) + have hp:=bits_length_pow 2 i + have ht : (2:ℕ).bits.length=2:=rfl + rw [ht] at hp;omega +lemma coveringStep_expr_bound (s : ℕ×(NatExpr v×NatExpr v)) (i : ℕ) : + (exprCode ev ((coveringStep^[i]) s).2.2).length≤(exprCode ev s.2.2).length+ + i*((exprCode ev s.2.1).length+8*(s.1).bits.length+16*i+200):=by + induction i with + | zero=>simp + | succ i ih=> + have hh:=exprCode_ite_le ev ((coveringStep^[i]) s).2.1 (.const ((coveringStep^[i]) s).1) + ((coveringStep^[i]) s).2.2 (.const (((coveringStep^[i]) s).1*2)) + rw [exprCode_const,exprCode_const,coveringStep_base] at hh + have hp:=coveringStep_pow_size s i + have h2:=bits_length_mul ((coveringStep^[i]) s).1 2 + have ht : (2:ℕ).bits.length=2:=rfl + rw [ht] at h2 + rw [Function.iterate_succ_apply'] + change (exprCode ev (.iteLe _ _ _ _)).length≤_ + rw [coveringStep_base] + nlinarith +lemma coveringStep_start (d : NatExpr v) (i : ℕ) : + (coveringStep^[i]) (1,d,.const 1)=(2^i,d,OrderTrial.Expressions.coveringPow d i):=by + induction i with + | zero=>rfl + | succ i ih=>rw [Function.iterate_succ_apply',ih];simp only [coveringStep,pow_succ,OrderTrial.Expressions.coveringPow] +namespace Emission +noncomputable def coveringPowP : Procedure (prodCode unaryCode (exprCode ev)) (exprCode ev) + (fun x=>OrderTrial.Expressions.coveringPow x.2 x.1):=by + let ecode:=prodCode (exprCode ev) (exprCode ev) + let scode:=prodCode Nat.bits ecode + let p:=first Nat.bits ecode + let r:=second Nat.bits ecode + let d:=(first (exprCode ev) (exprCode ev)).comp r + let a:=(second (exprCode ev) (exprCode ev)).comp r + let p2:=binaryMul.comp (p.pair (Procedure.constant scode Nat.bits 2)) + let expr:=(exprIteP ev).comp (d.pair (((exprConstP ev).comp p).pair + (a.pair ((exprConstP ev).comp p2)))) + let step : Procedure scode scode coveringStep:=p2.pair (d.pair expr) + let rep:=step.iterate (Polynomial.C 100*Polynomial.X^2+Polynomial.C 205*Polynomial.X+2) (by + intro n s i hi + have hp:=coveringStep_pow_size s i + have he:=coveringStep_expr_bound ev s i + simp only [scode,ecode,prodCode,pairBits_length,coveringStep_base, + Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_pow,Polynomial.eval_X,Polynomial.eval_C, + Polynomial.eval_ofNat] + nlinarith) + let k:=first unaryCode (exprCode ev) + let d:=second unaryCode (exprCode ev) + let start:=(Procedure.constant _ Nat.bits 1).pair (d.pair (Procedure.constant _ (exprCode ev) (.const 1))) + let out:=(second (exprCode ev) (exprCode ev)).comp (second Nat.bits ecode) + exact (out.comp (rep.comp (k.pair start))).congrFun (by + intro x;change ((coveringStep^[x.1]) (1,x.2,.const 1)).2.2=_ + rw [coveringStep_start]) +end Emission +namespace Emits +open BitStackProgram.Emits +variable {α : Type} {ea : α→List Bool} {ev : v→List Bool} +lemma coveringPow {d : α→NatExpr v} {k : α→ℕ} (hd : BitStackProgram.Emits ea (exprCode ev) d) + (hk : BitStackProgram.Emits ea unaryCode k) : + BitStackProgram.Emits ea (exprCode ev) (fun x=>OrderTrial.Expressions.coveringPow (d x) (k x)):= + (ofProcedure (Emission.coveringPowP ev)).comp (hk.pair hd) +end Emits +end ExactQuantumFactoring.NetworkEmission + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/CyclicAlgebra.lean b/lean/OAI/Computability/QuantumFactoring/CyclicAlgebra.lean new file mode 100644 index 0000000000000000000000000000000000000000..461bdda682308b54483d7a8a5d0343be52043276 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/CyclicAlgebra.lean @@ -0,0 +1,96 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.Primality + +namespace OAI + +section + + +namespace ExactQuantumFactoring.Primality +open scoped BigOperators + +/-- Exactly s coefficients with cyclic convolution, the concrete algebra +(Z/mZ)[X]/(X^s-1) used in the appendix. -/ +abbrev Cyclic (R : Type*) [Semiring R] (s : ℕ) := AddMonoidAlgebra R (Fin s) + +noncomputable def cyclicOf {R : Type*} [Semiring R] {s : ℕ} (v : Fin s → R) : Cyclic R s := + AddMonoidAlgebra.ofCoeff (Finsupp.equivFunOnFinite.symm v) + +@[simp] lemma cyclicOf_coeff {R : Type*} [Semiring R] {s : ℕ} (v : Fin s → R) (i : Fin s) : + (cyclicOf v).coeff i = v i := rfl + +lemma cyclic_mul_coeff {R : Type*} [Semiring R] {s : ℕ} [NeZero s] + (a b : Cyclic R s) (k : Fin s) : + (a*b).coeff k = ∑ i : Fin s, a.coeff i * b.coeff (k-i) := by + rw [AddMonoidAlgebra.coeff_mul_apply_left,Finsupp.sum_fintype] + · congr 1 + ext i + rw [sub_eq_add_neg,add_comm k] + · intro i + simp + +/-- The residue class of X. No exponentially long polynomial is constructed. -/ +noncomputable def cyclicX {R : Type*} [Semiring R] (s : ℕ) [NeZero s] : Cyclic R s := + AddMonoidAlgebra.single 1 1 + +noncomputable def cyclicC {R : Type*} [Semiring R] (s : ℕ) [NeZero s] (a : R) : Cyclic R s := + AddMonoidAlgebra.single 0 a + +lemma cyclicC_nat {R : Type*} [Semiring R] (s : ℕ) [NeZero s] (a : ℕ) : + cyclicC s (a : R) = (a : Cyclic R s) := by + induction a with + | zero => simp [cyclicC] + | succ a ih => + rw [Nat.cast_succ,Nat.cast_succ,← ih] + simp [cyclicC,AddMonoidAlgebra.single_add,AddMonoidAlgebra.one_def] + +/-- Primes satisfy the literal cyclic-array test by characteristic-p Frobenius. -/ +lemma cyclic_prime_test {m s : ℕ} [NeZero s] (hm : m.Prime) (a : ℕ) : + (cyclicX (R := ZMod m) s + cyclicC s (a : ZMod m))^m = + cyclicX s ^m + cyclicC s (a : ZMod m) := by + let : Fact m.Prime := ⟨hm⟩ + let : CharP (Cyclic (ZMod m) s) m := + charP_of_injective_ringHom (f := AddMonoidAlgebra.singleZeroRingHom) + AddMonoidAlgebra.single_right_injective m + rw [cyclicC_nat,add_pow_char,natCast_frobenius] + +noncomputable def rootPower {F : Type*} [CommRing F] {s : ℕ} [NeZero s] + (z : F) (hz : z^s=1) : Multiplicative (Fin s) →* F where + toFun i := z^i.toAdd.val + map_one' := by simp + map_mul' i j := by + change z^((i.toAdd+j.toAdd).val)=z^i.toAdd.val*z^j.toAdd.val + rw [Fin.val_add,← pow_eq_pow_mod _ hz,pow_add] + +noncomputable def cyclicEval {R F : Type*} [Semiring R] [CommRing F] + {s : ℕ} [NeZero s] (f : R →+* F) (z : F) (hz : z^s=1) : Cyclic R s →+* F := + AddMonoidAlgebra.liftNCRingHom f (rootPower z hz) (fun _ _ => Commute.all _ _) + +lemma cyclicEval_X {R F : Type*} [Semiring R] [CommRing F] + {s : ℕ} [NeZero s] (hs : 2 ≤ s) (f : R →+* F) (z : F) (hz : z^s=1) : + cyclicEval f z hz (cyclicX s) = z := by + simp [cyclicEval,cyclicX,rootPower, Nat.mod_eq_of_lt (by omega : 1 < s)] + +lemma cyclicEval_C {R F : Type*} [Semiring R] [CommRing F] + {s : ℕ} [NeZero s] (f : R →+* F) (z : F) (hz : z^s=1) (a : R) : + cyclicEval f z hz (cyclicC s a) = f a := by + simp [cyclicEval,cyclicC,rootPower] + +/-- Equality of the two concrete coefficient arrays gives exactly the +introspective identity needed by the appendix's root-count contradiction. -/ +lemma cyclic_test_introspective {F : Type*} [Field F] {m s p a : ℕ} + [NeZero s] [CharP F p] (hs : 2 ≤ s) (hpm : p ∣ m) + (h : (cyclicX (R := ZMod m) s + cyclicC s (a : ZMod m))^m = + cyclicX s ^m + cyclicC s (a : ZMod m)) : + Introspective s m (Polynomial.X+Polynomial.C (a : F)) := by + intro z hz + have hh := congrArg (cyclicEval (ZMod.castHom hpm F) z hz) h + simpa only [map_pow,map_add,cyclicEval_X hs,cyclicEval_C,map_natCast, + Polynomial.eval_add,Polynomial.eval_X,Polynomial.eval_C,Polynomial.eval_natCast] using hh + +end ExactQuantumFactoring.Primality + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/CyclicCircuit.lean b/lean/OAI/Computability/QuantumFactoring/CyclicCircuit.lean new file mode 100644 index 0000000000000000000000000000000000000000..8cfe219eb9e86659cd284ae54da769fc606f1ddc --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/CyclicCircuit.lean @@ -0,0 +1,111 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.CyclicAlgebra +import OAI.Computability.QuantumFactoring.ModularMultiply +import OAI.Computability.QuantumFactoring.WordBlocks + +namespace OAI + +section +open scoped BigOperators + + +namespace ExactQuantumFactoring.BitArithmetic +open BooleanNetwork Primality +open scoped BigOperators + +noncomputable def decodeCyclic {s w : ℕ} (m : ℕ) (x : Basis (s*w)) : Cyclic (ZMod m) s := + cyclicOf (fun i => ((bitsValue (block x i)).toNat : ZMod m)) + +@[simp] lemma decodeCyclic_coeff {s w : ℕ} (m : ℕ) (x : Basis (s*w)) (i : Fin s) : + (decodeCyclic m x).coeff i=((bitsValue (block x i)).toNat : ZMod m) := rfl + +def cyclicTerm {n s w : ℕ} [NeZero s] (a b : BooleanNetwork n (s*w)) + (m : BooleanNetwork n w) (k i : Fin s) : BooleanNetwork n w := + mulMod (a.comp (blockNet s w i)) (b.comp (blockNet s w (k-i))) m + +def cyclicMulNet {n s w : ℕ} [NeZero s] (a b : BooleanNetwork n (s*w)) + (m : BooleanNetwork n w) : BooleanNetwork n (s*w) := + wordBlocks (fun k => sumMod m (List.ofFn (cyclicTerm a b m k))) + +lemma cyclicMulNet_value {n s w : ℕ} [NeZero s] (a b : BooleanNetwork n (s*w)) + (m : BooleanNetwork n w) (x : Basis n) (hm : 0 < (bitsValue (m.eval x)).toNat) + (k : Fin s) : + (bitsValue (block ((cyclicMulNet a b m).eval x) k)).toNat = + (∑ i : Fin s, (bitsValue (block (a.eval x) i)).toNat * + (bitsValue (block (b.eval x) (k-i))).toNat) % (bitsValue (m.eval x)).toNat := by + rw [cyclicMulNet,wordBlocks_eval,sumMod_value _ _ _ hm] + simp only [List.map_ofFn,List.sum_ofFn] + have hh : ∀ i : Fin s, (bitsValue ((cyclicTerm a b m k i).eval x)).toNat = + ((bitsValue (block (a.eval x) i)).toNat * + (bitsValue (block (b.eval x) (k-i))).toNat) % (bitsValue (m.eval x)).toNat := by + intro i + rw [cyclicTerm,mulMod_word _ _ _ _ hm] + simp only [eval_comp,blockNet_eval] + simp only [Function.comp_apply] + simp_rw [hh] + exact (Finset.sum_nat_mod _ _ _).symm + +lemma cyclicMulNet_correct {n s w : ℕ} [NeZero s] (a b : BooleanNetwork n (s*w)) + (m : BooleanNetwork n w) (x : Basis n) (hm : 0 < (bitsValue (m.eval x)).toNat) : + decodeCyclic (bitsValue (m.eval x)).toNat ((cyclicMulNet a b m).eval x) = + decodeCyclic (bitsValue (m.eval x)).toNat (a.eval x)* + decodeCyclic (bitsValue (m.eval x)).toNat (b.eval x) := by + ext k + rw [decodeCyclic_coeff,cyclicMulNet_value _ _ _ _ hm,cyclic_mul_coeff] + simp only [ZMod.natCast_mod,Nat.cast_sum,Nat.cast_mul,decodeCyclic_coeff] + +abbrev cyclicMulBound (s w ac bc mc : ℕ) : ℕ := + s*w*(w+s*(ac+bc+2*mc+(1224*w*w+143*w+12)+216*(w+1)^2+142*(w+1)+15)) + +lemma cyclicTerm_count {n s w : ℕ} [NeZero s] (a b : BooleanNetwork n (s*w)) + (m : BooleanNetwork n w) (k i : Fin s) : + (cyclicTerm a b m k i).net.count ≤ a.net.count+b.net.count+m.net.count+ + (1224*w*w+143*w+12) := by + have h := mulMod_count (a.comp (blockNet s w i)) (b.comp (blockNet s w (k-i))) m + simpa only [cyclicTerm,count_comp,blockNet_count,add_zero] using h + +lemma cyclicMulNet_count {n s w : ℕ} [NeZero s] (a b : BooleanNetwork n (s*w)) + (m : BooleanNetwork n w) : (cyclicMulNet a b m).net.count ≤ + cyclicMulBound s w a.net.count b.net.count m.net.count := by + apply wordBlocks_count + intro k + have h := sumMod_count m (List.ofFn (cyclicTerm a b m k)) (by + intro c hc + obtain ⟨i,rfl⟩ := List.mem_ofFn.mp hc + exact cyclicTerm_count a b m k i) + simp only [List.length_ofFn] at h + + nlinarith + +/-- Canonical representatives permit exact word comparison of arrays. -/ +def CanonicalCyclic {s w : ℕ} (m : ℕ) (x : Basis (s*w)) : Prop := + ∀ i : Fin s, (bitsValue (block x i)).toNat < m + +lemma cyclicMulNet_canonical {n s w : ℕ} [NeZero s] (a b : BooleanNetwork n (s*w)) + (m : BooleanNetwork n w) (x : Basis n) (hm : 0 < (bitsValue (m.eval x)).toNat) : + CanonicalCyclic (bitsValue (m.eval x)).toNat ((cyclicMulNet a b m).eval x) := by + intro k + rw [cyclicMulNet_value _ _ _ _ hm] + exact Nat.mod_lt _ hm + +lemma decodeCyclic_injective {s w m : ℕ} (hm : 0 < m) {a b : Basis (s*w)} + (ha : CanonicalCyclic m a) (hb : CanonicalCyclic m b) + (hh : decodeCyclic m a=decodeCyclic m b) : a=b := by + let : NeZero m := ⟨by omega⟩ + have hv : ∀ i : Fin s, bitsValue (block a i)=bitsValue (block b i) := by + intro i + have he := congrArg (fun c : Cyclic (ZMod m) s => (c.coeff i).val) hh + simp only [decodeCyclic_coeff,ZMod.val_natCast,Nat.mod_eq_of_lt (ha i), + Nat.mod_eq_of_lt (hb i)] at he + exact BitVec.eq_of_toNat_eq he + funext k + obtain ⟨⟨i,j⟩,rfl⟩ := finProdFinEquiv.surjective k + have he := congrArg (fun v : BitVec w => v.getLsbD j.val) (hv i) + simpa only [bitsValue_bit,block] using he + +end ExactQuantumFactoring.BitArithmetic + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/CyclicConstants.lean b/lean/OAI/Computability/QuantumFactoring/CyclicConstants.lean new file mode 100644 index 0000000000000000000000000000000000000000..4dc1d207dbc07fc1cddc3b2d300def79927bd949 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/CyclicConstants.lean @@ -0,0 +1,89 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.CyclicCircuit + +namespace OAI + +section +open scoped BigOperators + + +namespace ExactQuantumFactoring.BitArithmetic +open BooleanNetwork Primality +open scoped BigOperators + +def arrayConstant {n : ℕ} (s w : ℕ) (f : Fin s → ℕ) : BooleanNetwork n (s*w) := + wordBlocks (fun i => wordConstant (BitVec.ofNat w (f i))) + +lemma arrayConstant_value {n s w : ℕ} (f : Fin s → ℕ) (x : Basis n) (i : Fin s) : + (bitsValue (block ((arrayConstant s w f).eval x) i)).toNat = f i % 2^w := by + rw [arrayConstant,wordBlocks_eval,wordConstant_eval,BitVec.toNat_ofNat] + +lemma arrayConstant_count {n s w : ℕ} (f : Fin s → ℕ) : + (arrayConstant (n := n) s w f).net.count ≤ s*w*w := by + apply wordBlocks_count + intro i + exact (wordConstant_count _).le + +def cyclicOne {n : ℕ} (s w : ℕ) [NeZero s] : BooleanNetwork n (s*w) := + arrayConstant s w (fun i => if i=0 then 1 else 0) + +lemma cyclicOne_value {n s w m : ℕ} [NeZero s] (hw : 0 < w) (x : Basis n) : + decodeCyclic m ((cyclicOne s w).eval x)=1 := by + have hp : 1 < 2^w := Nat.one_lt_pow (by omega) (by decide) + ext i + rw [decodeCyclic_coeff,cyclicOne,arrayConstant_value,AddMonoidAlgebra.one_def] + simp only [AddMonoidAlgebra.coeff_single,Finsupp.single_apply] + split_ifs <;> simp_all [Nat.mod_eq_of_lt hp] + +lemma cyclicOne_canonical {n s w m : ℕ} [NeZero s] (hm : 2 ≤ m) (x : Basis n) : + CanonicalCyclic m ((cyclicOne s w).eval x) := by + intro i + rw [cyclicOne,arrayConstant_value] + split_ifs + · exact (Nat.mod_le _ _).trans_lt (by omega) + · simp only [Nat.zero_mod] + omega + +def cyclicAddNet {n s w : ℕ} (a b : BooleanNetwork n (s*w)) + (m : BooleanNetwork n w) : BooleanNetwork n (s*w) := + wordBlocks (fun i => addMod (a.comp (blockNet s w i)) (b.comp (blockNet s w i)) m) + +lemma cyclicAddNet_value {n s w : ℕ} (a b : BooleanNetwork n (s*w)) + (m : BooleanNetwork n w) (x : Basis n) (hm : 0 < (bitsValue (m.eval x)).toNat) + (i : Fin s) : + (bitsValue (block ((cyclicAddNet a b m).eval x) i)).toNat = + ((bitsValue (block (a.eval x) i)).toNat+(bitsValue (block (b.eval x) i)).toNat)% + (bitsValue (m.eval x)).toNat := by + rw [cyclicAddNet,wordBlocks_eval,addMod_value _ _ _ _ hm] + simp only [eval_comp,blockNet_eval] + +lemma cyclicAddNet_correct {n s w : ℕ} (a b : BooleanNetwork n (s*w)) + (m : BooleanNetwork n w) (x : Basis n) (hm : 0 < (bitsValue (m.eval x)).toNat) : + decodeCyclic (bitsValue (m.eval x)).toNat ((cyclicAddNet a b m).eval x) = + decodeCyclic (bitsValue (m.eval x)).toNat (a.eval x)+ + decodeCyclic (bitsValue (m.eval x)).toNat (b.eval x) := by + ext i + rw [decodeCyclic_coeff,cyclicAddNet_value _ _ _ _ hm] + simp [ZMod.natCast_mod,decodeCyclic_coeff] + +lemma cyclicAddNet_canonical {n s w : ℕ} (a b : BooleanNetwork n (s*w)) + (m : BooleanNetwork n w) (x : Basis n) (hm : 0 < (bitsValue (m.eval x)).toNat) : + CanonicalCyclic (bitsValue (m.eval x)).toNat ((cyclicAddNet a b m).eval x) := by + intro i + rw [cyclicAddNet_value _ _ _ _ hm] + exact Nat.mod_lt _ hm + +lemma cyclicAddNet_count {n s w : ℕ} (a b : BooleanNetwork n (s*w)) + (m : BooleanNetwork n w) : (cyclicAddNet a b m).net.count ≤ + s*w*(a.net.count+b.net.count+m.net.count+216*(w+1)^2+142*(w+1)+15) := by + apply wordBlocks_count + intro i + have h := addMod_count (a.comp (blockNet s w i)) (b.comp (blockNet s w i)) m + simpa only [count_comp,blockNet_count,add_zero] using h + +end ExactQuantumFactoring.BitArithmetic + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/CyclicEmission.lean b/lean/OAI/Computability/QuantumFactoring/CyclicEmission.lean new file mode 100644 index 0000000000000000000000000000000000000000..d0b0ed67b3dd69a523274c05c4049b2033cc10ff --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/CyclicEmission.lean @@ -0,0 +1,59 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.ModularSumEmission + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.NetworkEmission +open BitStackProgram BitStackProgram.Emits BitArithmetic +namespace NetEmits +variable {α : Type} {ea : α→List Bool} {n s w : α→ℕ} +lemma cyclicMul {a b : ∀x,BooleanNetwork (n x) (s x*w x)} + {m : ∀x,BooleanNetwork (n x) (w x)} [∀x,NeZero (s x)] + (hn : Emits ea unaryCode n) (hs : Emits ea unaryCode s) (hw : Emits ea unaryCode w) + (ha : NetEmits ea a) (hb : NetEmits ea b) (hm : NetEmits ea m) : + NetEmits ea (fun x=>cyclicMulNet (a x) (b x) (m x)):=by + apply wordBlocks hn hs hw + have hx:=(BitStackProgram.Emits.id (prodCode unaryCode ea)).precompose + (fun x:Σa,Fin (s a)=>(x.2.val,x.1)) + apply sumModOfFn (hn.comp hx.snd) (hw.comp hx.snd) (hs.comp hx.snd) (hm.input hx.snd) + have hy:=(BitStackProgram.Emits.id (prodCode unaryCode (fun x:Σa,Fin (s a)=>prodCode unaryCode ea (x.2.val,x.1)))).precompose + (fun x:Σa:Σa,Fin (s a),Fin (s a.1)=>(x.2.val,x.1)) + have ho:=hx.snd.comp hy.snd + have hS:=hs.comp ho + have hW:=hw.comp ho + have hi:=hy.fst.unaryNat + have hk:=hx.fst.comp hy.snd + have hj:=((hS.unaryNat.natSub hi).natAdd hk.unaryNat).natMod hS.unaryNat + have hleft:=blockNet hS hW (fun x=>x.2) hi + have hright:=blockNet hS hW (fun x=>x.1.2-x.2) hj + exact mulMod ((ha.input ho).comp hleft) ((hb.input ho).comp hright) (hm.input ho) hW +lemma cyclicOne (hn : Emits ea unaryCode n) (hs : Emits ea unaryCode s) + (hw : Emits ea unaryCode w) [∀x,NeZero (s x)] : + NetEmits ea (fun x=>BitArithmetic.cyclicOne (n:=n x) (s x) (w x)):=by + have hx:=(BitStackProgram.Emits.id (prodCode unaryCode ea)).precompose + (fun x:Σa,Fin (s a)=>(x.2.val,x.1)) + have hc:=hx.fst.unaryNat.natEq (const _ _ 0) + apply arrayConstant hn hs hw + exact (hc.ite (const _ _ 1) (const _ _ 0)).congr (by intro x;simp only [Fin.ext_iff,Fin.val_zero,decide_eq_true_eq]) +lemma cyclicAdd {a b : ∀x,BooleanNetwork (n x) (s x*w x)} + {m : ∀x,BooleanNetwork (n x) (w x)} + (hn : Emits ea unaryCode n) (hs : Emits ea unaryCode s) (hw : Emits ea unaryCode w) + (ha : NetEmits ea a) (hb : NetEmits ea b) (hm : NetEmits ea m) : + NetEmits ea (fun x=>cyclicAddNet (a x) (b x) (m x)):=by + apply wordBlocks hn hs hw + have hx:=(BitStackProgram.Emits.id (prodCode unaryCode ea)).precompose + (fun x:Σa,Fin (s a)=>(x.2.val,x.1)) + have hp:=blockNet (hs.comp hx.snd) (hw.comp hx.snd) (fun x=>x.2) hx.fst.unaryNat + exact addMod ((ha.input hx.snd).comp hp) ((hb.input hx.snd).comp hp) (hm.input hx.snd) (hw.comp hx.snd) +end NetEmits +end ExactQuantumFactoring.NetworkEmission + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/CyclicPowerCircuit.lean b/lean/OAI/Computability/QuantumFactoring/CyclicPowerCircuit.lean new file mode 100644 index 0000000000000000000000000000000000000000..e0ceb989a2342ab2d3b596cd7b3bbd6780c589e3 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/CyclicPowerCircuit.lean @@ -0,0 +1,193 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.ModularPower +import OAI.Computability.QuantumFactoring.CyclicConstants + +namespace OAI + +section +open scoped BigOperators + + +namespace ExactQuantumFactoring.BitArithmetic +open BooleanNetwork Primality + +abbrev cyclicPowerWidth (s w b : ℕ) := ((s*w+w)+b)+s*w + +def cyclicPack {s w b : ℕ} (a : Basis (s*w)) (m : Basis w) (e : Basis b) + (z : Basis (s*w)) : Basis (cyclicPowerWidth s w b) := + Fin.append (Fin.append (Fin.append a m) e) z + +def cyclicBase (s w b : ℕ) : BooleanNetwork (cyclicPowerWidth s w b) (s*w) := + select (fun i => ((i.castAdd w).castAdd b).castAdd (s*w)) +def cyclicMod (s w b : ℕ) : BooleanNetwork (cyclicPowerWidth s w b) w := + select (fun i => ((Fin.natAdd (s*w) i).castAdd b).castAdd (s*w)) +def cyclicAcc (s w b : ℕ) : BooleanNetwork (cyclicPowerWidth s w b) (s*w) := + select (Fin.natAdd ((s*w+w)+b)) +def cyclicBit (s w : ℕ) {b : ℕ} (i : Fin b) : BooleanNetwork (cyclicPowerWidth s w b) 1 := + bit ((Fin.natAdd (s*w+w) i).castAdd (s*w)) + +@[simp] lemma cyclicBase_eval {s w b : ℕ} (a : Basis (s*w)) (m : Basis w) (e : Basis b) + (z : Basis (s*w)) : (cyclicBase s w b).eval (cyclicPack a m e z)=a := by + funext i + simp only [cyclicBase,eval_select,Function.comp_apply,cyclicPack,Fin.append_left] +@[simp] lemma cyclicMod_eval {s w b : ℕ} (a : Basis (s*w)) (m : Basis w) (e : Basis b) + (z : Basis (s*w)) : (cyclicMod s w b).eval (cyclicPack a m e z)=m := by + funext i + simp only [cyclicMod,eval_select,Function.comp_apply,cyclicPack,Fin.append_left,Fin.append_right] +@[simp] lemma cyclicAcc_eval {s w b : ℕ} (a : Basis (s*w)) (m : Basis w) (e : Basis b) + (z : Basis (s*w)) : (cyclicAcc s w b).eval (cyclicPack a m e z)=z := by + funext i + simp only [cyclicAcc,eval_select,Function.comp_apply,cyclicPack,Fin.append_right] +@[simp] lemma cyclicBit_eval {s w b : ℕ} (a : Basis (s*w)) (m : Basis w) (e : Basis b) + (z : Basis (s*w)) (i : Fin b) : (cyclicBit s w i).eval (cyclicPack a m e z) 0=e i := by + simp only [cyclicBit,eval_bit,cyclicPack,Fin.append_left,Fin.append_right] + +def cyclicNew (s w : ℕ) [NeZero s] {b : ℕ} (i : Fin b) : + BooleanNetwork (cyclicPowerWidth s w b) (s*w) := + let sq := cyclicMulNet (cyclicAcc s w b) (cyclicAcc s w b) (cyclicMod s w b) + wordMux (cyclicBit s w i) (cyclicMulNet sq (cyclicBase s w b) (cyclicMod s w b)) sq + +def cyclicStep (s w : ℕ) [NeZero s] {b : ℕ} (i : Fin b) : + BooleanNetwork (cyclicPowerWidth s w b) (cyclicPowerWidth s w b) := + (select (Fin.castAdd (s*w))).pair (cyclicNew s w i) + +lemma cyclicStep_pack {s w b : ℕ} [NeZero s] (a : Basis (s*w)) (m : Basis w) (e : Basis b) + (z : Basis (s*w)) (i : Fin b) : + (cyclicStep s w i).eval (cyclicPack a m e z)= + cyclicPack a m e ((cyclicNew s w i).eval (cyclicPack a m e z)) := by + simp only [cyclicStep,eval_pair,eval_select,cyclicPack] + congr 1 + funext j + exact Fin.append_left _ _ j + +lemma cyclicNew_value {s w b : ℕ} [NeZero s] (a : Basis (s*w)) (m : Basis w) (e : Basis b) + (z : Basis (s*w)) (i : Fin b) (hm : 0 < (bitsValue m).toNat) : + decodeCyclic (bitsValue m).toNat ((cyclicNew s w i).eval (cyclicPack a m e z)) = + if e i then decodeCyclic (bitsValue m).toNat z ^ 2 * decodeCyclic (bitsValue m).toNat a + else decodeCyclic (bitsValue m).toNat z ^ 2 := by + have hm' : 0 < (bitsValue ((cyclicMod s w b).eval (cyclicPack a m e z))).toNat := by + simpa only [cyclicMod_eval] using hm + have hs := cyclicMulNet_correct (cyclicAcc s w b) (cyclicAcc s w b) + (cyclicMod s w b) (cyclicPack a m e z) hm' + have hp := cyclicMulNet_correct + (cyclicMulNet (cyclicAcc s w b) (cyclicAcc s w b) (cyclicMod s w b)) + (cyclicBase s w b) (cyclicMod s w b) (cyclicPack a m e z) hm' + rw [cyclicMod_eval] at hs hp + simp only [cyclicAcc_eval,cyclicBase_eval] at hs hp + rw [cyclicNew,wordMux_eval,cyclicBit_eval] + split + · rw [hp,hs,pow_two] + · rw [hs,pow_two] + +lemma cyclicNew_canonical {s w b : ℕ} [NeZero s] (a : Basis (s*w)) (m : Basis w) (e : Basis b) + (z : Basis (s*w)) (i : Fin b) (hm : 0 < (bitsValue m).toNat) : + CanonicalCyclic (bitsValue m).toNat ((cyclicNew s w i).eval (cyclicPack a m e z)) := by + have hm' : 0 < (bitsValue ((cyclicMod s w b).eval (cyclicPack a m e z))).toNat := by + simpa only [cyclicMod_eval] using hm + rw [cyclicNew,wordMux_eval,cyclicBit_eval] + split <;> + simpa only [cyclicMod_eval] using (cyclicMulNet_canonical _ _ _ _ hm') + +lemma cyclicMulBound_mono {s w a b c a' b' c' : ℕ} + (ha : a ≤ a') (hb : b ≤ b') (hc : c ≤ c') : + cyclicMulBound s w a b c ≤ cyclicMulBound s w a' b' c' := by + dsimp [cyclicMulBound] + gcongr + +abbrev cyclicStepBound (s w : ℕ) := + cyclicMulBound s w (cyclicMulBound s w 0 0 0) 0 0 + cyclicMulBound s w 0 0 0+7*(s*w) + +lemma cyclicNew_count (s w : ℕ) [NeZero s] {b : ℕ} (i : Fin b) : + (cyclicNew s w i).net.count ≤ cyclicStepBound s w := by + let sq := cyclicMulNet (cyclicAcc s w b) (cyclicAcc s w b) (cyclicMod s w b) + have hs : sq.net.count ≤ cyclicMulBound s w 0 0 0 := cyclicMulNet_count _ _ _ + have hh : (cyclicMulNet sq (cyclicBase s w b) (cyclicMod s w b)).net.count ≤ + cyclicMulBound s w (cyclicMulBound s w 0 0 0) 0 0 := + (cyclicMulNet_count sq (cyclicBase s w b) (cyclicMod s w b)).trans + (cyclicMulBound_mono hs (by rfl) (by rfl)) + simp only [cyclicNew,wordMux_count,cyclicBit,count_bit,zero_add] + change (cyclicMulNet sq (cyclicBase s w b) (cyclicMod s w b)).net.count + + sq.net.count + 7*(s*w) ≤ cyclicStepBound s w + dsimp [cyclicStepBound] + omega + +lemma cyclicStep_count (s w : ℕ) [NeZero s] {b : ℕ} (i : Fin b) : + (cyclicStep s w i).net.count ≤ cyclicStepBound s w := by + simpa only [cyclicStep,count_pair,count_select,zero_add] using cyclicNew_count s w i + +def cyclicPrefix (s w b : ℕ) [NeZero s] : (k : ℕ) → k ≤ b → + BooleanNetwork (cyclicPowerWidth s w b) (cyclicPowerWidth s w b) + | 0,_ => select id + | k+1,h => (cyclicPrefix s w b k (by omega)).comp (cyclicStep s w ⟨k,by omega⟩) + +lemma cyclicPrefix_count (s w b k : ℕ) [NeZero s] (hk : k ≤ b) : + (cyclicPrefix s w b k hk).net.count ≤ k*cyclicStepBound s w := by + induction k with + | zero => simp [cyclicPrefix] + | succ k ih => + have h := cyclicStep_count s w (⟨k,by omega⟩ : Fin b) + have hi := ih (by omega) + simp only [cyclicPrefix,count_comp] + nlinarith + +lemma cyclicPrefix_value {s w b : ℕ} [NeZero s] (a : Basis (s*w)) (m : Basis w) (e : Basis b) + (z₀ : Basis (s*w)) (hm : 0 < (bitsValue m).toNat) + (h₀ : decodeCyclic (bitsValue m).toNat z₀=1) (hc : CanonicalCyclic (bitsValue m).toNat z₀) + (k : ℕ) (hk : k ≤ b) : + ∃ z : Basis (s*w), (cyclicPrefix s w b k hk).eval (cyclicPack a m e z₀)=cyclicPack a m e z ∧ + decodeCyclic (bitsValue m).toNat z=decodeCyclic (bitsValue m).toNat a ^horner e k hk ∧ + CanonicalCyclic (bitsValue m).toNat z := by + induction k with + | zero => exact ⟨z₀,by simp [cyclicPrefix],by simpa only [horner,pow_zero] using h₀,hc⟩ + | succ k ih => + obtain ⟨z,hz,hv,_hzc⟩ := ih (by omega) + refine ⟨(cyclicNew s w ⟨k,by omega⟩).eval (cyclicPack a m e z),?_,?_, + cyclicNew_canonical _ _ _ _ _ hm⟩ + · rw [cyclicPrefix,eval_comp,hz,cyclicStep_pack] + · rw [cyclicNew_value _ _ _ _ _ hm,hv] + cases he : e (⟨k,by omega⟩ : Fin b) + · simp only [horner,he,Bool.false_eq_true,ite_false,Bool.toNat_false,Nat.add_zero] + rw [← pow_mul,Nat.mul_comm (horner e k _) 2] + · simp only [horner,he,ite_true,Bool.toNat_true] + rw [← pow_mul,pow_succ,Nat.mul_comm (horner e k _) 2] + +/-- n-bit repeated squaring in the coefficient array; no exponential polynomial +or algebraic root is part of the computation. -/ +def cyclicPower (s w b : ℕ) [NeZero s] : BooleanNetwork ((s*w+w)+b) (s*w) := + ((select id).pair (cyclicOne s w)).comp + ((cyclicPrefix s w b b le_rfl).rewire (Fin.natAdd ((s*w+w)+b))) + +lemma cyclicPower_count (s w b : ℕ) [NeZero s] : + (cyclicPower s w b).net.count ≤ s*w*w+b*cyclicStepBound s w := by + have h₁ := arrayConstant_count (n := (s*w+w)+b) (s := s) (w := w) (fun i => if i=0 then 1 else 0) + have h₂ := cyclicPrefix_count s w b b le_rfl + simp only [cyclicPower,count_comp,count_pair,count_select,count_rewire,zero_add] + change (arrayConstant s w _).net.count + _ ≤ _ + omega + +lemma cyclicPower_value {s w b : ℕ} [NeZero s] (a : Basis (s*w)) (m : Basis w) (e : Basis b) + (hw : 0 < w) (hm : 2 ≤ (bitsValue m).toNat) : + decodeCyclic (bitsValue m).toNat ((cyclicPower s w b).eval (Fin.append (Fin.append a m) e))= + decodeCyclic (bitsValue m).toNat a ^ horner e b le_rfl ∧ + CanonicalCyclic (bitsValue m).toNat ((cyclicPower s w b).eval (Fin.append (Fin.append a m) e)) := by + let input := Fin.append (Fin.append a m) e + obtain ⟨z,hz,hv,hc⟩ := cyclicPrefix_value a m e ((cyclicOne s w).eval input) + (by omega) (cyclicOne_value hw input) (cyclicOne_canonical hm input) b le_rfl + have he : (cyclicPower s w b).eval input=z := by + simp only [cyclicPower,eval_comp,eval_rewire,eval_pair,eval_select,Function.comp_id] + change ((cyclicPrefix s w b b le_rfl).eval + (cyclicPack a m e ((cyclicOne s w).eval input))) ∘ Fin.natAdd ((s*w+w)+b)=z + rw [hz] + funext i + exact Fin.append_right _ _ i + change decodeCyclic (bitsValue m).toNat ((cyclicPower s w b).eval input)=_ ∧ + CanonicalCyclic (bitsValue m).toNat ((cyclicPower s w b).eval input) + rw [he] + exact ⟨hv,hc⟩ + +end ExactQuantumFactoring.BitArithmetic + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/CyclicPowerEmission.lean b/lean/OAI/Computability/QuantumFactoring/CyclicPowerEmission.lean new file mode 100644 index 0000000000000000000000000000000000000000..e999c2be64a8cdf19c042f5d40e9308b19212c3a --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/CyclicPowerEmission.lean @@ -0,0 +1,73 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.CyclicEmission + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.NetworkEmission +open BitStackProgram BitStackProgram.Emits BitArithmetic +namespace NetEmits +variable {α : Type} {ea : α→List Bool} {s w b : α→ℕ} [∀x,NeZero (s x)] +lemma cyclicStep (hs : Emits ea unaryCode s) (hw : Emits ea unaryCode w) (hb : Emits ea unaryCode b) + (i : ∀x,Fin (b x)) (hi : Emits ea Nat.bits (fun x=>(i x).val)) : + NetEmits ea (fun x=>BitArithmetic.cyclicStep (s x) (w x) (i x)):=by + have hA:=hs.unaryMul hw + have hI:=(hA.unaryAdd hw).unaryAdd hb + have hW:=hI.unaryAdd hA + have hbase : NetEmits ea (fun x=>cyclicBase (s x) (w x) (b x)):= + selectSlice hW hA (const _ _ 0) _ (by intros;simp only [Fin.val_castAdd,Nat.zero_add]) + have hmod : NetEmits ea (fun x=>cyclicMod (s x) (w x) (b x)):= + selectSlice hW hw hA.unaryNat _ (by intros;simp only [Fin.val_castAdd,Fin.val_natAdd]) + have hacc : NetEmits ea (fun x=>cyclicAcc (s x) (w x) (b x)):= + selectSlice hW hA hI.unaryNat _ (by intros;simp only [Fin.val_natAdd]) + have hbit : NetEmits ea (fun x=>cyclicBit (s x) (w x) (i x)):= + bit hW _ ((hA.unaryAdd hw).unaryNat.natAdd hi) + have hkeep : NetEmits ea (fun x=>BooleanNetwork.select + (Fin.castAdd (s x*w x) : Fin ((s x*w x+w x)+b x)→Fin (cyclicPowerWidth (s x) (w x) (b x)))):= + selectSlice hW hI (const _ _ 0) _ (by intros;simp only [Fin.val_castAdd,Nat.zero_add]) + have hsq:=cyclicMul hW hs hw hacc hacc hmod + have hprod:=cyclicMul hW hs hw hsq hbase hmod + exact hkeep.pair (wordMux hbit hprod hsq hA) +lemma cyclicPrefix (hs : Emits ea unaryCode s) (hw : Emits ea unaryCode w) (hb : Emits ea unaryCode b) : + NetEmits ea (fun x=>BitArithmetic.cyclicPrefix (s x) (w x) (b x) (b x) le_rfl):=by + have hx:=(BitStackProgram.Emits.id (prodCode unaryCode ea)).precompose + (fun x:Σa,Fin (b a)=>(x.2.val,x.1)) + obtain ⟨p,hp,ep⟩:=cyclicStep (hs.comp hx.snd) (hw.comp hx.snd) (hb.comp hx.snd) (fun x=>x.2) hx.fst.unaryNat + obtain ⟨q,hq,eq⟩:=extendPack hb p hp + obtain ⟨pp⟩:=hq + have hps:=(ofProcedure (Procedure.tabulate (f:=q) emptyPack pp)).comp (hb.pair (id ea)) + have hA:=hs.unaryMul hw + have hW:=((hA.unaryAdd hw).unaryAdd hb).unaryAdd hA + let Q:=fun x j=>((List.range j).map (q x)).foldl compPack (identityPack (cyclicPowerWidth (s x) (w x) (b x))) + have hQ : Emits ea packCode (fun x=>Q x (b x)):= + (ofProcedure Emission.foldCompP).comp (hps.pair ((ofProcedure Emission.identityPackP).comp hW)) + refine ⟨fun x=>Q x (b x),hQ,?_⟩ + intro x + suffices ∀j (hj:j≤b x),(Q x j).val.value=erase (BitArithmetic.cyclicPrefix (s x) (w x) (b x) j hj) from this _ le_rfl + intro j + induction j with + | zero=>intro hj;exact identityPack_value _ + | succ j ih=> + intro hj + dsimp only [Q] + rw [List.range_succ,List.map_append,List.foldl_append,List.map_singleton,List.foldl_cons,List.foldl_nil] + apply compPack_spec _ _ _ _ (ih (by omega)) + rw [eq x ⟨j,by omega⟩] + exact ep ⟨x,⟨j,by omega⟩⟩ +lemma cyclicPower (hs : Emits ea unaryCode s) (hw : Emits ea unaryCode w) (hb : Emits ea unaryCode b) : + NetEmits ea (fun x=>BitArithmetic.cyclicPower (s x) (w x) (b x)):=by + have hA:=hs.unaryMul hw + have hI:=(hA.unaryAdd hw).unaryAdd hb + have hstart:=(identity hI).pair (cyclicOne hI hs hw) + exact hstart.comp ((cyclicPrefix hs hw hb).rewireSlice hA hI.unaryNat _ (by intros;rfl)) +end NetEmits +end ExactQuantumFactoring.NetworkEmission + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/CyclicPrimality.lean b/lean/OAI/Computability/QuantumFactoring/CyclicPrimality.lean new file mode 100644 index 0000000000000000000000000000000000000000..f1179c5a83969b0c430adb7caa8ce3b7e1e70aac --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/CyclicPrimality.lean @@ -0,0 +1,49 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.PrimalityCorrectness +import OAI.Computability.QuantumFactoring.CyclicAlgebra + +namespace OAI + +section + + +namespace ExactQuantumFactoring.Primality + +theorem cyclic_large_branch_prime {n m s : ℕ} (hn : 128 ≤ n) (hm : 2 ≤ m) (hmb : m < 2^n) + [NeZero s] (hs : s.Prime) (hcop : s.Coprime m) (horder : n^2 < orderOf (m : ZMod s)) + (hpow : ¬ PerfectPower m) + (hsmall : ∀ d : ℕ, 2 ≤ d → d ≤ 8*s → ¬ d ∣ m) + (htest : ∀ a : ℕ, 1 ≤ a → a ≤ 8*s → + (cyclicX (R := ZMod m) s+cyclicC s (a : ZMod m))^m= + cyclicX s^m+cyclicC s (a : ZMod m)) : m.Prime := by + by_contra hcom + obtain ⟨p,hp,hpm⟩ := Nat.exists_prime_and_dvd (by omega : m ≠ 1) + obtain ⟨q,hq,hqm,hpq⟩ := other_prime_divisor hm hcom hpow hp hpm + let : Fact s.Prime := ⟨hs⟩ + let : Fact p.Prime := ⟨hp⟩ + have hpbig : 8*s < p := by + by_contra h + exact hsmall p hp.two_le (by omega) hpm + have hms : (m : ZMod s) ≠ 0 := by + rw [Ne, ZMod.natCast_eq_zero_iff] + exact (hs.coprime_iff_not_dvd).mp hcop + have hps : (p : ZMod s) ≠ 0 := by + rw [Ne, ZMod.natCast_eq_zero_iff] + intro hd + have := (Nat.prime_dvd_prime_iff_eq hs hp).mp hd + nlinarith [hs.two_le] + have hsp : (s : ZMod p) ≠ 0 := by + rw [Ne, ZMod.natCast_eq_zero_iff] + exact Nat.not_dvd_of_pos_of_lt hs.pos (by nlinarith) + let : NeZero (s : ZMod p) := ⟨hsp⟩ + obtain ⟨w,hw⟩ := HasEnoughRootsOfUnity.exists_primitiveRoot (AlgebraicClosure (ZMod p)) s + exact root_count_contradiction (by omega) hm hmb hms hps hpbig hpm hq hqm hpq horder hw + (fun a ha hb => cyclic_test_introspective hs.two_le hpm (htest a ha hb)) + + +end ExactQuantumFactoring.Primality + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/CyclicTestBounds.lean b/lean/OAI/Computability/QuantumFactoring/CyclicTestBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..ffe95c78e4126f1cff3e2a3a5ea452ed31e42bf1 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/CyclicTestBounds.lean @@ -0,0 +1,71 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.CyclicTestCircuit + +namespace OAI + +section +open scoped BigOperators + + +namespace ExactQuantumFactoring.BitArithmetic +open BooleanNetwork + +abbrev cyclicAddBound (s w ac bc mc : ℕ) := + s*w*(ac+bc+mc+216*(w+1)^2+142*(w+1)+15) + +lemma cyclicAddBound_mono {s w a b c a' b' c' : ℕ} + (ha : a ≤ a') (hb : b ≤ b') (hc : c ≤ c') : + cyclicAddBound s w a b c ≤ cyclicAddBound s w a' b' c' := by + dsimp [cyclicAddBound] + gcongr + +abbrev cyclicTestBound (s w : ℕ) := + cyclicAddBound s w (s*w*w) (s*w*w) 0+s*w*w+w*cyclicStepBound s w+ + cyclicAddBound s w (2*(s*w*w)+w*cyclicStepBound s w) (s*w*w) 0+96*(s*w)+21 + +lemma cyclicTest_count (s w a : ℕ) [NeZero s] : + (cyclicTest s w a).net.count ≤ cyclicTestBound s w := by + let m : BooleanNetwork w w := select id + let e : BooleanNetwork w w := select Fin.rev + let X : BooleanNetwork w (s*w) := cyclicXNet s w + let C : BooleanNetwork w (s*w) := cyclicCNet s w a + let lhs := cyclicPowerOn (cyclicAddNet X C m) m e + let rhs := cyclicAddNet (cyclicPowerOn X m e) C m + have hx : X.net.count ≤ s*w*w := arrayConstant_count _ + have hc : C.net.count ≤ s*w*w := arrayConstant_count _ + have hm : m.net.count=0 := rfl + have he : e.net.count=0 := rfl + have ha : (cyclicAddNet X C m).net.count ≤ cyclicAddBound s w (s*w*w) (s*w*w) 0 := + (cyclicAddNet_count X C m).trans (cyclicAddBound_mono hx hc (by rfl)) + have hl := cyclicPowerOn_count (cyclicAddNet X C m) m e + rw [hm,he] at hl + have hp : (cyclicPowerOn X m e).net.count ≤ 2*(s*w*w)+w*cyclicStepBound s w := by + have h := cyclicPowerOn_count X m e + rw [hm,he] at h + omega + have hr : rhs.net.count ≤ cyclicAddBound s w (2*(s*w*w)+w*cyclicStepBound s w) (s*w*w) 0 := + (cyclicAddNet_count (cyclicPowerOn X m e) C m).trans + (cyclicAddBound_mono hp hc (by rfl)) + have hq := wordEq_count (s*w) + change ((lhs.pair rhs).comp (wordEq (s*w))).net.count ≤ _ + rw [count_comp,count_pair] + change (cyclicPowerOn (cyclicAddNet X C m) m e).net.count+rhs.net.count+_ ≤ _ + dsimp [cyclicTestBound] + omega + +lemma cyclicStepBound_mono {s w s' w' : ℕ} (hs : s ≤ s') (hw : w ≤ w') : + cyclicStepBound s w ≤ cyclicStepBound s' w' := by + unfold cyclicStepBound cyclicMulBound + gcongr + +lemma cyclicTestBound_mono {s w s' w' : ℕ} (hs : s ≤ s') (hw : w ≤ w') : + cyclicTestBound s w ≤ cyclicTestBound s' w' := by + unfold cyclicTestBound cyclicAddBound + gcongr <;> exact cyclicStepBound_mono hs hw + +end ExactQuantumFactoring.BitArithmetic + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/CyclicTestCircuit.lean b/lean/OAI/Computability/QuantumFactoring/CyclicTestCircuit.lean new file mode 100644 index 0000000000000000000000000000000000000000..dad91bc597be87e33396369dac4f18cd78207429 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/CyclicTestCircuit.lean @@ -0,0 +1,131 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.HornerEncoding +import OAI.Computability.QuantumFactoring.ArithmeticPredicates +import OAI.Computability.QuantumFactoring.CyclicPowerCircuit + +namespace OAI + +section +open scoped BigOperators + + +namespace ExactQuantumFactoring.BitArithmetic +open BooleanNetwork Primality + +lemma arrayConstant_decode {n s w m : ℕ} (f : Fin s → ℕ) + (hf : ∀ i, f i < 2^w) (x : Basis n) : + decodeCyclic m ((arrayConstant s w f).eval x)=cyclicOf (fun i => (f i : ZMod m)) := by + ext i + rw [decodeCyclic_coeff,arrayConstant_value,cyclicOf_coeff,Nat.mod_eq_of_lt (hf i)] + +def cyclicXNet {n : ℕ} (s w : ℕ) [NeZero s] : BooleanNetwork n (s*w) := + arrayConstant s w (fun i => if i=1 then 1 else 0) +def cyclicCNet {n : ℕ} (s w a : ℕ) [NeZero s] : BooleanNetwork n (s*w) := + arrayConstant s w (fun i => if i=0 then a else 0) + +lemma cyclicXNet_value {n s w m : ℕ} [NeZero s] (hw : 0 < w) (x : Basis n) : + decodeCyclic m ((cyclicXNet s w).eval x)=cyclicX s := by + have hp : 1 < 2^w := Nat.one_lt_pow (by omega) (by decide) + unfold cyclicXNet + rw [arrayConstant_decode _ (by intro i; split_ifs <;> omega)] + ext i + simp only [cyclicOf_coeff,cyclicX,AddMonoidAlgebra.coeff_single,Finsupp.single_apply] + split_ifs <;> simp_all + +lemma cyclicCNet_value {n s w m a : ℕ} [NeZero s] (ha : a < 2^w) (x : Basis n) : + decodeCyclic m ((cyclicCNet s w a).eval x)=cyclicC s (a : ZMod m) := by + unfold cyclicCNet + rw [arrayConstant_decode _ (by intro i; split_ifs <;> omega)] + ext i + simp only [cyclicOf_coeff,cyclicC,AddMonoidAlgebra.coeff_single,Finsupp.single_apply] + split_ifs <;> simp_all + +def cyclicPowerOn {n s w b : ℕ} [NeZero s] (a : BooleanNetwork n (s*w)) + (m : BooleanNetwork n w) (e : BooleanNetwork n b) : BooleanNetwork n (s*w) := + ((a.pair m).pair e).comp (cyclicPower s w b) + +lemma cyclicPowerOn_value {n s w b : ℕ} [NeZero s] (a : BooleanNetwork n (s*w)) + (m : BooleanNetwork n w) (e : BooleanNetwork n b) (x : Basis n) + (hw : 0 < w) (hm : 2 ≤ (bitsValue (m.eval x)).toNat) : + decodeCyclic (bitsValue (m.eval x)).toNat ((cyclicPowerOn a m e).eval x)= + decodeCyclic (bitsValue (m.eval x)).toNat (a.eval x)^horner (e.eval x) b le_rfl ∧ + CanonicalCyclic (bitsValue (m.eval x)).toNat ((cyclicPowerOn a m e).eval x) := by + simpa only [cyclicPowerOn,eval_comp,eval_pair] using + cyclicPower_value (a.eval x) (m.eval x) (e.eval x) hw hm + +lemma cyclicPowerOn_count {n s w b : ℕ} [NeZero s] (a : BooleanNetwork n (s*w)) + (m : BooleanNetwork n w) (e : BooleanNetwork n b) : + (cyclicPowerOn a m e).net.count ≤ a.net.count+m.net.count+e.net.count+ + s*w*w+b*cyclicStepBound s w := by + have h := cyclicPower_count s w b + simp only [cyclicPowerOn,count_comp,count_pair] + omega + +lemma horner_reverse {w : ℕ} (x : Basis w) : + horner (x ∘ Fin.rev) w le_rfl = (bitsValue x).toNat := by + rw [horner_full,Triangular.inputNumber_reverse] + congr 2 + funext i + simp [reverseBits] + +/-- Literal 8s AKS congruence on s coefficient words, m in the input word. -/ +def cyclicTest (s w a : ℕ) [NeZero s] : BooleanNetwork w 1 := + let m := select id + let e := select Fin.rev + let X := cyclicXNet s w + let C := cyclicCNet s w a + let lhs := cyclicPowerOn (cyclicAddNet X C m) m e + let rhs := cyclicAddNet (cyclicPowerOn X m e) C m + (lhs.pair rhs).comp (wordEq (s*w)) + +lemma cyclicTest_correct (s w a : ℕ) [NeZero s] (x : Basis w) + (hw : 0 < w) (hm : 2 ≤ (bitsValue x).toNat) (ha : a < 2^w) : + (cyclicTest s w a).eval x 0=true ↔ + (cyclicX s+cyclicC s (a : ZMod (bitsValue x).toNat) : Cyclic (ZMod (bitsValue x).toNat) s)^ + (bitsValue x).toNat = cyclicX s^(bitsValue x).toNat+cyclicC s (a : ZMod (bitsValue x).toNat) := by + let m : BooleanNetwork w w := select id + let e : BooleanNetwork w w := select Fin.rev + let X : BooleanNetwork w (s*w) := cyclicXNet s w + let C : BooleanNetwork w (s*w) := cyclicCNet s w a + let lhs := cyclicPowerOn (cyclicAddNet X C m) m e + let rhs := cyclicAddNet (cyclicPowerOn X m e) C m + have hm' : 2 ≤ (bitsValue (m.eval x)).toNat := hm + have hl := cyclicPowerOn_value (cyclicAddNet X C m) m e x hw hm' + have hX := cyclicPowerOn_value X m e x hw hm' + have ha' := cyclicAddNet_correct X C m x (by omega) + have hr := cyclicAddNet_correct (cyclicPowerOn X m e) C m x (by omega) + have hrc := cyclicAddNet_canonical (cyclicPowerOn X m e) C m x (by omega) + have he : horner (e.eval x) w le_rfl=(bitsValue x).toNat := horner_reverse x + have hx : decodeCyclic (bitsValue (m.eval x)).toNat (X.eval x)=cyclicX s := cyclicXNet_value hw x + have hc : decodeCyclic (bitsValue x).toNat (C.eval x)=cyclicC s (a : ZMod (bitsValue x).toNat) := + cyclicCNet_value ha x + have hmval : m.eval x=x := by simp [m] + rw [hmval] at hl hX ha' hr hrc hx + have hleft : decodeCyclic (bitsValue x).toNat (lhs.eval x)= + (cyclicX s+cyclicC s (a : ZMod (bitsValue x).toNat))^(bitsValue x).toNat := by + change decodeCyclic (bitsValue x).toNat ((cyclicPowerOn (cyclicAddNet X C m) m e).eval x)=_ + rw [hl.1,ha',hx,hc,he] + have hright : decodeCyclic (bitsValue x).toNat (rhs.eval x)= + cyclicX s^(bitsValue x).toNat+cyclicC s (a : ZMod (bitsValue x).toNat) := by + change decodeCyclic (bitsValue x).toNat ((cyclicAddNet (cyclicPowerOn X m e) C m).eval x)=_ + rw [hr,hX.1,hx,hc,he] + change ((lhs.pair rhs).comp (wordEq (s*w))).eval x 0=true ↔ _ + rw [eval_comp,eval_pair,wordEq_eval,decide_eq_true_eq] + rw [show bitsValue (lhs.eval x)=bitsValue (rhs.eval x) ↔ lhs.eval x=rhs.eval x from + (bitsEquiv (s*w)).injective.eq_iff] + constructor + · intro h + have hh := congrArg (decodeCyclic (bitsValue x).toNat) h + simpa only [hleft,hright] using hh + · intro h + apply decodeCyclic_injective (by omega) hl.2 hrc + change decodeCyclic (bitsValue x).toNat (lhs.eval x)=decodeCyclic (bitsValue x).toNat (rhs.eval x) + rw [hleft,hright] + exact h + +end ExactQuantumFactoring.BitArithmetic + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/CyclicTestEmission.lean b/lean/OAI/Computability/QuantumFactoring/CyclicTestEmission.lean new file mode 100644 index 0000000000000000000000000000000000000000..04d6722617f3744e0ab7debff6cc9945311167eb --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/CyclicTestEmission.lean @@ -0,0 +1,65 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.CyclicPowerEmission + +namespace OAI + + + +section + +namespace ExactQuantumFactoring.BitStackProgram.Emits +variable {α β : Type} {ea : α→List Bool} {eb : β→List Bool} +lemma ofFnNat (d : β) {k : α→ℕ} {f : α→ℕ→β} + (hk : Emits ea unaryCode k) (hf : Emits (prodCode unaryCode ea) eb (fun x=>f x.2 x.1)) : + Emits ea (listCode eb) (fun x=>List.ofFn (fun i:Fin (k x)=>f x i.val)):=by + obtain ⟨p⟩:=hf + exact ((ofProcedure (Procedure.tabulate (f:=f) d p)).comp (hk.pair (id ea))).congr + (by intro x;exact (NetworkEmission.ofFn_nat_eq_map _ _).symm) +end ExactQuantumFactoring.BitStackProgram.Emits + +namespace ExactQuantumFactoring.NetworkEmission +open BitStackProgram BitStackProgram.Emits BitArithmetic +namespace NetEmits +variable {α : Type} {ea : α→List Bool} {n s w a : α→ℕ} +lemma reverseWord {f : ∀x,BooleanNetwork (n x) (w x)} (hf : NetEmits ea f) + (hw : Emits ea unaryCode w) : NetEmits ea (fun x=>(f x).rewire Fin.rev):=by + have hx:=BitStackProgram.Emits.id (prodCode unaryCode ea) + have hi:=(hw.comp hx.snd).unaryNat.natSub hx.fst.unarySucc.unaryNat + exact hf.rewire _ (ofFnNat (eb:=Nat.bits) (f:=fun x i=>w x-(i+1)) 0 hw hi) +lemma cyclicX (hn : Emits ea unaryCode n) (hs : Emits ea unaryCode s) (hw : Emits ea unaryCode w) + [∀x,NeZero (s x)] : NetEmits ea (fun x=>cyclicXNet (n:=n x) (s x) (w x)):=by + have hx:=(BitStackProgram.Emits.id (prodCode unaryCode ea)).precompose + (fun x:Σa,Fin (s a)=>(x.2.val,x.1)) + have hc:=hx.fst.unaryNat.natEq ((const _ _ 1).natMod (hs.comp hx.snd).unaryNat) + apply arrayConstant hn hs hw + exact (hc.ite (const _ _ 1) (const _ _ 0)).congr (by intro x;simp only [Fin.ext_iff,Fin.val_one',decide_eq_true_eq]) +lemma cyclicC (hn : Emits ea unaryCode n) (hs : Emits ea unaryCode s) (hw : Emits ea unaryCode w) + (ha : Emits ea Nat.bits a) [∀x,NeZero (s x)] : NetEmits ea (fun x=>cyclicCNet (n:=n x) (s x) (w x) (a x)):=by + have hx:=(BitStackProgram.Emits.id (prodCode unaryCode ea)).precompose + (fun x:Σa,Fin (s a)=>(x.2.val,x.1)) + have hc:=hx.fst.unaryNat.natEq (const _ _ 0) + apply arrayConstant hn hs hw + exact (hc.ite (ha.comp hx.snd) (const _ _ 0)).congr (by intro x;simp only [Fin.ext_iff,Fin.val_zero,decide_eq_true_eq]) +lemma cyclicPowerOn {b : α→ℕ} {f : ∀x,BooleanNetwork (n x) (s x*w x)} + {m : ∀x,BooleanNetwork (n x) (w x)} {e : ∀x,BooleanNetwork (n x) (b x)} + [∀x,NeZero (s x)] (hs : Emits ea unaryCode s) (hw : Emits ea unaryCode w) (hb : Emits ea unaryCode b) + (hf : NetEmits ea f) (hm : NetEmits ea m) (he : NetEmits ea e) : + NetEmits ea (fun x=>BitArithmetic.cyclicPowerOn (f x) (m x) (e x)):= + ((hf.pair hm).pair he).comp (cyclicPower hs hw hb) +lemma cyclicTest (hs : Emits ea unaryCode s) (hw : Emits ea unaryCode w) (ha : Emits ea Nat.bits a) + [∀x,NeZero (s x)] : NetEmits ea (fun x=>BitArithmetic.cyclicTest (s x) (w x) (a x)):=by + have hm:=identity hw + have he:=hm.reverseWord hw + have hX:=cyclicX hw hs hw + have hC:=cyclicC hw hs hw ha + have hl:=cyclicPowerOn hs hw hw (cyclicAdd hw hs hw hX hC hm) hm he + have hr:=cyclicAdd hw hs hw (cyclicPowerOn hs hw hw hX hm he) hC hm + exact hl.equalOn hr (hs.unaryMul hw) +end NetEmits +end ExactQuantumFactoring.NetworkEmission + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/DescendingFilter.lean b/lean/OAI/Computability/QuantumFactoring/DescendingFilter.lean new file mode 100644 index 0000000000000000000000000000000000000000..1887bf556068877dc85cc7fb71e1aec97facd4be --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/DescendingFilter.lean @@ -0,0 +1,92 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.EmissionCombinators + +namespace OAI + + + +section +namespace ExactQuantumFactoring.NetworkEmission +open BooleanNetwork BitStackProgram BitStackProgram.Emits +structure FilterState (k : ℕ) (w : ℕ→ℕ) where + depth : ℕ + raw : BooleanNetwork k (w depth) + pending : List (BooleanNetwork k 1) +def filterStep {k : ℕ} {w : ℕ→ℕ} (prev : ∀s,BooleanNetwork (w (s+1)) (w s)) + (keep : ∀s,BooleanNetwork k (w (s+1))→BooleanNetwork k 1) : FilterState k w→FilterState k w + | ⟨0,v,ps⟩ => ⟨0,v,ps⟩ + | ⟨s+1,v,ps⟩ => ⟨s,v.comp (prev s),keep s v::ps⟩ +def FilterState.code {k : ℕ} {w : ℕ→ℕ} (s : FilterState k w) : ℕ×Pack×List Pack:= + (s.depth,erasePack s.raw,s.pending.map erasePack) +def filterPrefix {k : ℕ} {w : ℕ→ℕ} (prev : ∀s,BooleanNetwork (w (s+1)) (w s)) + (keep : ∀s,BooleanNetwork k (w (s+1))→BooleanNetwork k 1) : ∀s,BooleanNetwork k (w s)→BooleanNetwork k 1 + | 0,_=>BooleanNetwork.constant true + | s+1,v=>(filterPrefix prev keep s (v.comp (prev s))).band (keep s v) +lemma filterStep_depth {k : ℕ} {w : ℕ→ℕ} (prev : ∀s,BooleanNetwork (w (s+1)) (w s)) + (keep : ∀s,BooleanNetwork k (w (s+1))→BooleanNetwork k 1) (s : FilterState k w) : + (filterStep prev keep s).depth=s.depth-1:=by cases s with | mk d v ps=>cases d <;> rfl +lemma filterRun_depth {k : ℕ} {w : ℕ→ℕ} (prev : ∀s,BooleanNetwork (w (s+1)) (w s)) + (keep : ∀s,BooleanNetwork k (w (s+1))→BooleanNetwork k 1) (s : FilterState k w) (i : ℕ) : + ((filterStep prev keep)^[i] s).depth=s.depth-i:=by + induction i with + | zero=>simp + | succ i ih=>rw [Function.iterate_succ_apply',filterStep_depth,ih,Nat.sub_sub] +lemma filterStep_value {k : ℕ} {w : ℕ→ℕ} (prev : ∀s,BooleanNetwork (w (s+1)) (w s)) + (keep : ∀s,BooleanNetwork k (w (s+1))→BooleanNetwork k 1) (s : FilterState k w) : + (filterStep prev keep s).pending.foldl BooleanNetwork.band + (filterPrefix prev keep (filterStep prev keep s).depth (filterStep prev keep s).raw)= + s.pending.foldl BooleanNetwork.band (filterPrefix prev keep s.depth s.raw):=by + cases s with | mk d v ps=>cases d <;> rfl +lemma filterRun_value {k : ℕ} {w : ℕ→ℕ} (prev : ∀s,BooleanNetwork (w (s+1)) (w s)) + (keep : ∀s,BooleanNetwork k (w (s+1))→BooleanNetwork k 1) (s : FilterState k w) (i : ℕ) : + ((filterStep prev keep)^[i] s).pending.foldl BooleanNetwork.band + (filterPrefix prev keep ((filterStep prev keep)^[i] s).depth ((filterStep prev keep)^[i] s).raw)= + s.pending.foldl BooleanNetwork.band (filterPrefix prev keep s.depth s.raw):=by + induction i with + | zero=>rfl + | succ i ih=>rw [Function.iterate_succ_apply',filterStep_value,ih] +lemma filterRun_result {k : ℕ} {w : ℕ→ℕ} (prev : ∀s,BooleanNetwork (w (s+1)) (w s)) + (keep : ∀s,BooleanNetwork k (w (s+1))→BooleanNetwork k 1) (s : ℕ) (v : BooleanNetwork k (w s)) : + ((filterStep prev keep)^[s] ⟨s,v,[]⟩).pending.foldl BooleanNetwork.band (BooleanNetwork.constant true)= + filterPrefix prev keep s v:=by + have h:=filterRun_value prev keep (⟨s,v,[]⟩ : FilterState k w) s + have hd:=filterRun_depth prev keep (⟨s,v,[]⟩ : FilterState k w) s + dsimp only at hd + rw [Nat.sub_self] at hd + generalize he : ((filterStep prev keep)^[s] ⟨s,v,[]⟩)=r at * + cases r with | mk d a ps=> + dsimp only [FilterState.depth] at hd + subst d + exact h +lemma filterRun_bounds {k : ℕ} {w : ℕ→ℕ} (prev : ∀s,BooleanNetwork (w (s+1)) (w s)) + (keep : ∀s,BooleanNetwork k (w (s+1))→BooleanNetwork k 1) + (hp : ∀s,(prev s).net.count=0) (S B C : ℕ) + (hc : ∀s,S>s→∀v: BooleanNetwork k (w (s+1)),v.net.count≤B→(keep s v).net.count≤C) + (v : BooleanNetwork k (w S)) (hv : v.net.count≤B) (i : ℕ) : + let r := ((filterStep prev keep)^[i] ⟨S,v,[]⟩); + r.depth ≤ S ∧ r.raw.net.count ≤ B ∧ r.pending.length ≤ i ∧ (∀ a ∈ r.pending, a.net.count ≤ C) := by + induction i with + | zero=>exact ⟨le_rfl,hv,le_rfl,by simp⟩ + | succ i ih=> + rw [Function.iterate_succ_apply'] + generalize he : ((filterStep prev keep)^[i] ⟨S,v,[]⟩)=r at * + rcases ih with ⟨hd,hv,hl,hc'⟩ + cases r with | mk d a ps=> + cases d with + | zero=>exact ⟨hd,hv,hl.trans (by omega),hc'⟩ + | succ d=> + dsimp only [FilterState.depth,FilterState.raw,FilterState.pending] at hd hv hl hc' + refine ⟨by dsimp only [filterStep];omega,?_,?_,?_⟩ + · simpa only [filterStep,BooleanNetwork.count_comp,hp,Nat.add_zero] using hv + · dsimp only [filterStep];simp only [List.length_cons];omega + · intro a ha + rcases List.mem_cons.mp ha with h|h + · subst a;exact hc d (by omega) _ hv + · exact hc' a h +end ExactQuantumFactoring.NetworkEmission + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/DescendingFilterEmission.lean b/lean/OAI/Computability/QuantumFactoring/DescendingFilterEmission.lean new file mode 100644 index 0000000000000000000000000000000000000000..08e4a599baea1a43ebd506c94f7c4e65a9a21ef0 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/DescendingFilterEmission.lean @@ -0,0 +1,103 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.EmissionGeneralStages +import OAI.Computability.QuantumFactoring.NetworkListOperationsEmission +import OAI.Computability.QuantumFactoring.DescendingFilter + +namespace OAI + + + +section +namespace ExactQuantumFactoring.BitStackProgram.Emits +lemma recode {α β γ : Type} {ea : α→List Bool} {eb : β→List Bool} {ec : γ→List Bool} + {f : α→β} {g : α→γ} (h : Emits ea eb f) (he : ∀x,eb (f x)=ec (g x)) : Emits ea ec g:=by + obtain ⟨p⟩:=h;exact ⟨p.result he⟩ +end ExactQuantumFactoring.BitStackProgram.Emits +namespace ExactQuantumFactoring.NetworkEmission +open BooleanNetwork BitStackProgram BitStackProgram.Emits +abbrev filterCode := prodCode unaryCode (prodCode packCode (listCode packCode)) +def FilterState.positiveView {k : ℕ} {w : ℕ→ℕ} (r : FilterState k w) (h : 0cases d with + | zero=>exact False.elim (Nat.not_lt_zero _ h) + | succ s=>exact ⟨s,v,ps⟩ +lemma FilterState.positiveView_eq {k : ℕ} {w : ℕ→ℕ} (r : FilterState k w) (h : 0cases d with + | zero=>exact False.elim (Nat.not_lt_zero _ h) + | succ s=>rfl +namespace NetsEmits +lemma foldlBand {α : Type} {ea : α→List Bool} {k : α→ℕ} + {f : ∀x,List (BooleanNetwork (k x) 1)} (hk : Emits ea unaryCode k) (hf : NetsEmits ea f) : + NetEmits ea (fun x=>(f x).foldl BooleanNetwork.band (BooleanNetwork.constant true)):=by + let p:=Emission.foldRightPack (f:=fun a b=>bandPack b a) 4 (by intro a b; dsimp [bandPack,compPack,pairPack,nodePack]; omega) + (Emission.bandPackP.comp ((Procedure.second packCode packCode).pair (Procedure.first packCode packCode))) + have hi:=(ofProcedure Emission.constantPackP).comp (hk.pair (const _ _ true)) + have hr:=(ofProcedure (Procedure.listReverse packCode emptyPack)).comp hf + refine ⟨fun x=>((f x).map erasePack).foldl bandPack (constantPack (k x) true), + ((ofProcedure p).comp (hr.pair hi)).congr (fun x=>by dsimp only;rw [List.foldr_reverse]),?_⟩ + intro x + dsimp only + have hgen : ∀(fs:List (BooleanNetwork (k x) 1)) (a:Pack) (b:BooleanNetwork (k x) 1),a.val.value=erase b→ + ((fs.map erasePack).foldl bandPack a).val.value=erase (fs.foldl BooleanNetwork.band b):=by + intro fs + induction fs with + | nil=>intro a b h;exact h + | cons c cs ih=>intro a b h;exact ih _ _ (bandPack_value _ _ _ _ h rfl) + exact hgen _ _ _ (constantPack_value _ true) +end NetsEmits +lemma filterPrefixEmitter {α : Type} {ea : α→List Bool} {k S B C W : α→ℕ} {w : α→ℕ→ℕ} + (prev : ∀x s,BooleanNetwork (w x (s+1)) (w x s)) + (keep : ∀x s,BooleanNetwork (k x) (w x (s+1))→BooleanNetwork (k x) 1) + (hp : ∀x s,(prev x s).net.count=0) + (hc : ∀x s,s(ea x).length) B) (hC : PolyAt (fun x=>(ea x).length) C) + (hW : PolyAt (fun x=>(ea x).length) W) + (hstep : Emits (fun x:Σa,{r:FilterState (k a) (w a) // 0prodCode ea filterCode (x.1,x.2.val.code)) + filterCode (fun x=>(filterStep (prev x.1) (keep x.1) x.2.val).code)) : + NetEmits ea (fun x=>filterPrefix (prev x) (keep x) (S x) (v x)):=by + let R:=fun x i=>(filterStep (prev x) (keep x))^[i] (⟨S x,v x,[]⟩ : FilterState (k x) (w x)) + have h0 : Emits ea filterCode (fun x=>(R x 0).code):= + hS.pair (hV.canonical.pair (const _ _ [])) + have hs : Emits (fun x:Σa,Fin (S a)=>prodCode ea (prodCode unaryCode filterCode) (x.1,(x.2.val,(R x.1 x.2.val).code))) + filterCode (fun x=>(R x.1 (x.2.val+1)).code):=by + have hx:=(BitStackProgram.Emits.id (prodCode ea (prodCode unaryCode filterCode))).precompose + (fun x:Σa,Fin (S a)=>(x.1,(x.2.val,(R x.1 x.2.val).code))) + let g : (Σa,Fin (S a))→Σa,{r:FilterState (k a) (w a) // 0⟨x.1,R x.1 x.2.val,by + dsimp only [R];rw [filterRun_depth];dsimp only;exact Nat.sub_pos_of_lt x.2.isLt⟩ + have hh:=hstep.comp ((hx.fst.pair hx.snd.snd).recode (g:=g) (fun _=>rfl)) + exact hh.congr (fun x=>by dsimp only [g,R];rw [Function.iterate_succ_apply']) + have hb : PolyAt (fun x:Σa,Fin (S a+1)=>(ea x.1).length) (fun x=>(filterCode (R x.1 x.2.val).code).length):=by + have hs:=hS.unaryPoly + have hh:=hk.unaryPoly + let P:= (PolyAt.const _ 104).mul ((((hh.add hB).add hW).add (PolyAt.const _ 1)).pow 2) + let Q:= (PolyAt.const _ 104).mul ((((hh.add hC).add (PolyAt.const _ 1)).add (PolyAt.const _ 1)).pow 2) + apply (((PolyAt.const _ 2).mul hs).add (((PolyAt.const _ 2).mul P).add + ((hs.mul (((PolyAt.const _ 2).mul Q).add (PolyAt.const _ 2))).add (PolyAt.const _ 5)))).pull + (fun x:Σa,Fin (S a+1)=>x.1) |>.of_le + intro x + obtain ⟨hd,hr,hl,hls⟩:=filterRun_bounds (prev x.1) (keep x.1) (hp x.1) (S x.1) (B x.1) (C x.1) (hc x.1) (v x.1) (hv x.1) x.2.val + have ht:=hw x.1 (R x.1 x.2.val).depth hd + have hraw:=packCode_bound (erasePack (R x.1 x.2.val).raw) + have hraw' : (packCode (erasePack (R x.1 x.2.val).raw)).length≤104*(k x.1+B x.1+W x.1+1)^2:= + hraw.trans (Nat.mul_le_mul_left _ (Nat.pow_le_pow_left (by dsimp only [erasePack,R] at *;omega) 2)) + have hlist:=listCode_length_bound packCode ((R x.1 x.2.val).pending.map erasePack) (104*(k x.1+C x.1+1+1)^2) (by + intro a ha;obtain ⟨b,hb,rfl⟩:=List.mem_map.mp ha + exact (packCode_bound _).trans (Nat.mul_le_mul_left _ (Nat.pow_le_pow_left (by + have hh:=hls b hb;dsimp only [erasePack];omega) 2))) + simp only [filterCode,FilterState.code,prodCode,pairBits_length,unaryCode,List.length_replicate,List.length_map] at hlist ⊢ + dsimp only [R] at * + have hi:=x.2.isLt + nlinarith + have hf:=BitStackProgram.Emits.stages (F:=fun x i=>(R x i).code) hS h0 hs hb + exact (NetsEmits.foldlBand hk hf.snd.snd).congr (fun x=>filterRun_result (prev x) (keep x) (S x) (v x)) +end ExactQuantumFactoring.NetworkEmission + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/DescendingPrefixAutomatic.lean b/lean/OAI/Computability/QuantumFactoring/DescendingPrefixAutomatic.lean new file mode 100644 index 0000000000000000000000000000000000000000..1ad20dec74ef53fc8121cc18808c5ff84816d454 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/DescendingPrefixAutomatic.lean @@ -0,0 +1,52 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.DescendingStepEmission + +namespace OAI + + + +section +namespace ExactQuantumFactoring.NetworkEmission +open BitStackProgram BitStackProgram.Emits +lemma filterPrefixEmits {α : Type} {ea : α→List Bool} {k S W : α→ℕ} {w : α→ℕ→ℕ} + (prev : ∀x s,BooleanNetwork (w x (s+1)) (w x s)) + (keep : ∀x s,BooleanNetwork (k x) (w x (s+1))→BooleanNetwork (k x) 1) + (hp : ∀x s,(prev x s).net.count=0) + (hw : ∀x s,s≤S x→w x s≤W x) + (v : ∀x,BooleanNetwork (k x) (w x (S x))) + (hS : Emits ea unaryCode S) (hk : Emits ea unaryCode k) (hV : NetEmits ea v) + (hW : PolyAt (fun x=>(ea x).length) W) + (hep : NetEmits (prodCode ea unaryCode) (fun x=>prev x.1 x.2)) + (hec : NetEmits (fun x:Σa,Σs,BooleanNetwork (k a) (w a (s+1))=> + prodCode ea (prodCode unaryCode packCode) (x.1,(x.2.1,erasePack x.2.2))) (fun x=>keep x.1 x.2.1 x.2.2)) : + NetEmits ea (fun x=>filterPrefix (prev x) (keep x) (S x) (v x)):=by + let ix:=Σa,Σs:Fin (S a),{r:BooleanNetwork (k a) (w a (s.val+1)) // r.net.count≤(v a).net.count} + let enc:ix→List Bool:=fun x=>prodCode ea (prodCode unaryCode packCode) (x.1,(x.2.1.val,erasePack x.2.2.val)) + have hx:=(BitStackProgram.Emits.id (prodCode ea (prodCode unaryCode packCode))).precompose + (fun x:ix=>(x.1,(x.2.1.val,erasePack x.2.2.val))) + let g:ix→Σa,Σs,BooleanNetwork (k a) (w a (s+1)):=fun x=>⟨x.1,x.2.1.val,x.2.2.val⟩ + have he:=hec.compInput (hx.recode (g:=g) (fun _=>rfl)) + have hb : PolyAt (fun x:ix=>(ea x.1).length) (fun x=>(enc x).length):=by + have hbound:=(PolyAt.const _ 104).mul ((((hk.unaryPoly.add hV.countPoly).add hW).add (PolyAt.const _ 1)).pow 2) + apply ((((PolyAt.const _ 2).mul (PolyAt.self _)).add + (((PolyAt.const _ 2).mul hS.unaryPoly).add hbound)).add (PolyAt.const _ 2)).pull (fun x:ix=>x.1) |>.of_le + intro x + have hs:=x.2.1.isLt + have hc:=x.2.2.property + have hw':=hw x.1 (x.2.1.val+1) (by omega) + have hp':=(packCode_bound (erasePack x.2.2.val)).trans + (Nat.mul_le_mul_left 104 (Nat.pow_le_pow_left (show k x.1+x.2.2.val.net.count+w x.1 (x.2.1.val+1)+1≤ + k x.1+(v x.1).net.count+W x.1+1 by omega) 2)) + simp only [enc,prodCode,pairBits_length,unaryCode,List.length_replicate] + omega + obtain ⟨p,hp'⟩:=he.countPoly.rebase hb + exact filterPrefixEmitter (C:=fun x=>p.eval (ea x).length) prev keep hp + (fun x s hs r hr=>hp' ⟨x,⟨s,hs⟩,r,hr⟩) hw v (fun _=>le_rfl) hS hk hV + hV.countPoly ⟨p,fun _=>le_rfl⟩ hW (filterStepEmitter prev keep hep hec) +end ExactQuantumFactoring.NetworkEmission + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/DescendingStepEmission.lean b/lean/OAI/Computability/QuantumFactoring/DescendingStepEmission.lean new file mode 100644 index 0000000000000000000000000000000000000000..c8b9d8c377897dfc8a2082e4afc11961b51a11b8 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/DescendingStepEmission.lean @@ -0,0 +1,49 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.DescendingFilterEmission + +namespace OAI + + + +section +namespace ExactQuantumFactoring.NetworkEmission +open BitStackProgram BitStackProgram.Emits +lemma filterStepEmitter {α : Type} {ea : α→List Bool} {k : α→ℕ} {w : α→ℕ→ℕ} + (prev : ∀x s,BooleanNetwork (w x (s+1)) (w x s)) + (keep : ∀x s,BooleanNetwork (k x) (w x (s+1))→BooleanNetwork (k x) 1) + (hp : NetEmits (prodCode ea unaryCode) (fun x=>prev x.1 x.2)) + (hc : NetEmits (fun x:Σa,Σs,BooleanNetwork (k a) (w a (s+1))=> + prodCode ea (prodCode unaryCode packCode) (x.1,(x.2.1,erasePack x.2.2))) (fun x=>keep x.1 x.2.1 x.2.2)) : + Emits (fun x:Σa,{r:FilterState (k a) (w a) // 0prodCode ea filterCode (x.1,x.2.val.code)) + filterCode (fun x=>(filterStep (prev x.1) (keep x.1) x.2.val).code):=by + let ix:=Σa,Σs,BooleanNetwork (k a) (w a (s+1)) × List (BooleanNetwork (k a) 1) + let enc:ix→List Bool:=fun x=>prodCode ea filterCode (x.1,(x.2.1+1,erasePack x.2.2.1,x.2.2.2.map erasePack)) + have hx:=(BitStackProgram.Emits.id (prodCode ea filterCode)).precompose + (fun x:ix=>(x.1,(x.2.1+1,erasePack x.2.2.1,x.2.2.2.map erasePack))) + have hd: Emits enc unaryCode (fun x=>x.2.1):= + ((hx.snd.fst.unaryNat.natSub (const _ _ 1)).boundedUnary hx.snd.fst (fun _=>Nat.sub_le _ _)).congr (fun _=>by dsimp only;omega) + have hp':=hp.compInput (hx.fst.pair hd) + have hr:=NetEmits.ofCanonical hx.snd.snd.fst + have hraw:=(hr.comp hp').canonical + let g:ix→Σa,Σs,BooleanNetwork (k a) (w a (s+1)):=fun x=>⟨x.1,x.2.1,x.2.2.1⟩ + have hk:=hc.canonical.comp ((hx.fst.pair (hd.pair hx.snd.snd.fst)).recode (g:=g) (fun _=>rfl)) + have hs:=hd.pair (hraw.pair (hk.listCons hx.snd.snd.snd)) + let view:(Σa,{r:FilterState (k a) (w a) // 0⟨x.1,x.2.val.positiveView x.2.property⟩ + have h:=hs.precompose view + have he : (fun x=>enc (view x))=(fun x:Σa,{r:FilterState (k a) (w a) // 0prodCode ea filterCode (x.1,x.2.val.code)):=by + funext x + have hv:=x.2.val.positiveView_eq x.2.property + exact congrArg (fun r=>prodCode ea filterCode (x.1,r.code)) hv + change Emits (fun x=>enc (view x)) filterCode _ at h + rw [he] at h + exact h.congr (by + intro x + have hv:=x.2.val.positiveView_eq x.2.property + exact congrArg (fun r=>(filterStep (prev x.1) (keep x.1) r).code) hv) +end ExactQuantumFactoring.NetworkEmission + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/DistinctProductCircuit.lean b/lean/OAI/Computability/QuantumFactoring/DistinctProductCircuit.lean new file mode 100644 index 0000000000000000000000000000000000000000..e05beeaa06380aba7a1efa7a5ab003b47278ce10 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/DistinctProductCircuit.lean @@ -0,0 +1,98 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.ModularMultiply +import OAI.Computability.QuantumFactoring.ArithmeticPredicates +import OAI.Computability.QuantumFactoring.BooleanFold + +namespace OAI + +section +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators + + +namespace ExactQuantumFactoring +open BooleanNetwork +open scoped BigOperators +namespace BitArithmetic + +/-- Equality is tested on runtime word values, not on network syntax. -/ +def occursLater {k n : ℕ} (p : BooleanNetwork k n) (ps : List (BooleanNetwork k n)) : + BooleanNetwork k 1 := any (ps.map (fun q=>(p.pair q).comp (wordEq n))) + +lemma occursLater_value {k n : ℕ} (p : BooleanNetwork k n) (ps : List (BooleanNetwork k n)) + (x : Basis k) : (occursLater p ps).eval x 0=true ↔ + (bitsValue (p.eval x)).toNat∈ps.map (fun q=>(bitsValue (q.eval x)).toNat) := by + simp only [occursLater,any_eval,List.mem_map,exists_exists_and_eq_and, + eval_comp,eval_pair,wordEq_eval,decide_eq_true_eq] + constructor + · rintro ⟨q,hq,he⟩ + exact ⟨q,hq,(congrArg BitVec.toNat he).symm⟩ + · rintro ⟨q,hq,he⟩ + exact ⟨q,hq,BitVec.eq_of_toNat_eq he.symm⟩ + +/-- A quadratic comparison scan counts every runtime prime only once. +No sorting primitive or mathematical finset operation is used by the circuit. -/ +def distinctProductNet {k n : ℕ} (value : BooleanNetwork k n→BooleanNetwork k n) : + List (BooleanNetwork k n)→BooleanNetwork k n + | []=>wordConstant 1 + | p::ps=>(wordMux (occursLater p ps) (wordConstant 1) (value p)).pair + (distinctProductNet value ps) |>.comp (mul n) + +lemma distinctProductNet_value {k n : ℕ} (value : BooleanNetwork k n→BooleanNetwork k n) + (ps : List (BooleanNetwork k n)) (x : Basis k) (f : ℕ→ℕ) + (hv : ∀ p∈ps,(bitsValue ((value p).eval x)).toNat=f (bitsValue (p.eval x)).toNat%2^n) : + (bitsValue ((distinctProductNet value ps).eval x)).toNat= + (∏ p∈(ps.map (fun q=>(bitsValue (q.eval x)).toNat)).toFinset,f p)%2^n := by + induction ps with + | nil=>simp [distinctProductNet,wordConstant_eval] + | cons p ps ih=> + have hp:=hv p (by simp) + have hi:=ih (fun q hq=>hv q (by simp [hq])) + rw [distinctProductNet,eval_comp,eval_pair,mul_word,BitVec.toNat_mul, + wordMux_eval,hi,List.map_cons,List.toFinset_cons] + by_cases he : (bitsValue (p.eval x)).toNat∈ps.map (fun q=>(bitsValue (q.eval x)).toNat) + · rw [ite_eq_left ((occursLater_value p ps x).mpr he),wordConstant_eval, + Finset.insert_eq_of_mem (List.mem_toFinset.mpr he),show (1 : BitVec n).toNat=1%2^n from rfl,Nat.mod_mul_mod,Nat.mul_mod_mod,one_mul] + · rw [ite_eq_right (fun h=>he ((occursLater_value p ps x).mp h)),hp, + Finset.prod_insert (by simpa only [List.mem_toFinset] using he),Nat.mod_mul_mod,Nat.mul_mod_mod] + +lemma occursLater_count {k n c : ℕ} (p : BooleanNetwork k n) (ps : List (BooleanNetwork k n)) + (hp : p.net.count≤c) (hps : ∀ q∈ps,q.net.count≤c) : + (occursLater p ps).net.count≤ps.length*(2*c+96*n+25)+1 := by + have hh:=any_count (ps.map (fun q=>(p.pair q).comp (wordEq n))) + (c:=2*c+96*n+21) (by + intro q hq + obtain ⟨b,hb,rfl⟩:=List.mem_map.mp hq + have h:=hps b hb + have hw:=wordEq_count n + rw [count_comp,count_pair] + omega) + simpa only [occursLater,List.length_map,Nat.add_assoc] using hh + +lemma distinctProductNet_count {k n c d : ℕ} (value : BooleanNetwork k n→BooleanNetwork k n) + (ps : List (BooleanNetwork k n)) + (hp : ∀ p∈ps,p.net.count≤c) (hv : ∀ p∈ps,(value p).net.count≤d) : + (distinctProductNet value ps).net.count≤ + ps.length*(d+90*n*n+22*n+7+ps.length*(2*c+96*n+25))+n := by + induction ps with + | nil=>simp [distinctProductNet,wordConstant_count] + | cons p ps ih=> + have hps:=fun q hq=>hp q (List.mem_cons_of_mem p hq) + have hvs:=fun q hq=>hv q (List.mem_cons_of_mem p hq) + have hi:=ih hps hvs + have ho:=occursLater_count p ps (hp p (by simp)) hps + have hd:=hv p (by simp) + have hm:=mul_count n + simp only [distinctProductNet,count_comp,count_pair,wordMux_count,wordConstant_count, + List.length_cons] + nlinarith +end BitArithmetic +end ExactQuantumFactoring + + +end + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/DistinctProductEmission.lean b/lean/OAI/Computability/QuantumFactoring/DistinctProductEmission.lean new file mode 100644 index 0000000000000000000000000000000000000000..7c6868237f76044284f47a1d80c5f95f39eb33b9 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/DistinctProductEmission.lean @@ -0,0 +1,91 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.DistinctProductCircuit +import OAI.Computability.QuantumFactoring.FirstProperEmission +import OAI.Computability.QuantumFactoring.TableArithmeticEmission + +namespace OAI + + + +section +namespace ExactQuantumFactoring.NetworkEmission +open BitStackProgram BitStackProgram.Emits +namespace NetsEmits +variable {α : Type} {ea : α→List Bool} {k n : α→ℕ} +lemma drop {a : α→ℕ} {ps : ∀x,List (BooleanNetwork (k x) (n x))} + (ha : Emits ea Nat.bits a) (hp : NetsEmits ea ps) : NetsEmits ea (fun x=>(ps x).drop (a x)):=by + exact ((ofProcedure (Procedure.listDrop packCode)).comp (ha.pair hp)).congr + (fun x=>(List.map_drop ..).symm) +end NetsEmits +namespace NetEmits +open BitArithmetic +variable {α : Type} {ea : α→List Bool} {k n K : α→ℕ} +lemma occursLater {p : ∀x,BooleanNetwork (k x) (n x)} {ps : ∀x,List (BooleanNetwork (k x) (n x))} + (hk : Emits ea unaryCode k) (hn : Emits ea unaryCode n) (hp : NetEmits ea p) (hps : NetsEmits ea ps) : + NetEmits ea (fun x=>BitArithmetic.occursLater (p x) (ps x)):=by + have hx:=(BitStackProgram.Emits.id (prodCode unaryCode ea)).precompose (fun x:Σa,Fin ((ps a).length)=>(x.2.val,x.1)) + exact (hps.map (g:=fun x q=>((p x).pair q).comp (BitArithmetic.wordEq (n x))) + (((hp.compInput hx.snd).pair hps.get).comp (wordEq (hn.comp hx.snd)))).any hk +lemma distinctProductOfFn {f : ∀x,Fin (K x)→BooleanNetwork (k x) (n x)} + {value : ∀x,BooleanNetwork (k x) (n x)→BooleanNetwork (k x) (n x)} + (hk : Emits ea unaryCode k) (hn : Emits ea unaryCode n) (hK : Emits ea unaryCode K) + (hf : NetEmits (fun x:Σa,Fin (K a)=>prodCode unaryCode ea (x.2.val,x.1)) (fun x=>f x.1 x.2)) + (hv : NetEmits (fun x:Σa,Fin (K a)=>prodCode unaryCode ea (x.2.val,x.1)) (fun x=>value x.1 (f x.1 x.2))) : + NetEmits ea (fun x=>BitArithmetic.distinctProductNet (value x) (List.ofFn (f x))):=by + let F:=fun x j=>BitArithmetic.distinctProductNet (value x) ((List.ofFn (f x)).drop (K x-j)) + have h0 : NetEmits ea (fun x=>F x 0):=by + have h:=wordConst hk hn (const _ _ 1) + exact h.congr (by intro x;dsimp only [F];rw [Nat.sub_zero,List.drop_eq_nil_of_le (by simp)];rfl) + have hs : NetEmits (fun x:Σa,Fin (K a)=>prodCode ea (prodCode unaryCode packCode) + (x.1,(x.2.val,erasePack (F x.1 x.2.val)))) (fun x=>F x.1 (x.2.val+1)):=by + have hx:=(BitStackProgram.Emits.id (prodCode ea (prodCode unaryCode packCode))).precompose + (fun x:Σa,Fin (K a)=>(x.1,(x.2.val,erasePack (F x.1 x.2.val)))) + let y : (Σa,Fin (K a))→(Σa,Fin (K a)):=fun x=>⟨x.1,⟨K x.1-(x.2.val+1),by have:=x.2.isLt;omega⟩⟩ + have hi:=((hK.comp hx.fst).unaryNat.natSub (hx.snd.fst.unaryNat.natAdd (const _ _ 1))).boundedUnary + (hK.comp hx.fst) (fun _=>Nat.sub_le _ _) + have hy : Emits (fun x:Σa,Fin (K a)=>prodCode ea (prodCode unaryCode packCode) + (x.1,(x.2.val,erasePack (F x.1 x.2.val)))) + (fun x:Σa,Fin (K a)=>prodCode unaryCode ea (x.2.val,x.1)) y:= + (hi.pair hx.fst).recode (by intros;rfl) + have htail:=NetsEmits.drop ((hK.comp hx.fst).unaryNat.natSub hx.snd.fst.unaryNat) + ((NetsEmits.ofFn hK hf).comp hx.fst) + have hstep:=(((occursLater (hk.comp hx.fst) (hn.comp hx.fst) (hf.compInput (g:=y) hy) htail).wordMux + (wordConst (hk.comp hx.fst) (hn.comp hx.fst) (const _ _ 1)) (hv.compInput (g:=y) hy) (hn.comp hx.fst)).pair + (ofCanonical hx.snd.snd)).comp (mul (hn.comp hx.fst)) + convert hstep using 1 + funext x + dsimp only [F] + rw [dropOfFn_step _ x.2.isLt,BitArithmetic.distinctProductNet] + rfl + obtain ⟨pc,hpc⟩:=countPolyIndexed hK hf + obtain ⟨pv,hpv⟩:=countPolyIndexed (f:=fun x i=>value x (f x i)) hK hv + let len:=fun x:Σa,Fin (K a+1)=>(ea x.1).length + have hC : PolyAt len (fun x=>pc.eval (len x)):=⟨pc,fun _=>le_rfl⟩ + have hV : PolyAt len (fun x=>pv.eval (len x)):=⟨pv,fun _=>le_rfl⟩ + have hW:=hn.unaryPoly.pull (fun x:Σa,Fin (K a+1)=>x.1) + have hL:=hK.unaryPoly.pull (fun x:Σa,Fin (K a+1)=>x.1) + have hc : NetworkAt len (fun x=>F x.1 x.2.val):=by + apply (hL.mul ((((hV.add ((PolyAt.const len 90).mul (hW.pow 2))).add + ((PolyAt.const len 22).mul hW)).add (PolyAt.const len 7)).add + (hL.mul (((PolyAt.const len 2).mul hC).add ((PolyAt.const len 96).mul hW) |>.add (PolyAt.const len 25)))) |>.add hW).of_le + intro x + have hb:=BitArithmetic.distinctProductNet_count (value x.1) ((List.ofFn (f x.1)).drop (K x.1-x.2.val)) + (c:=pc.eval (len x)) (d:=pv.eval (len x)) + (by intro p hp;obtain ⟨i,rfl⟩:=List.mem_ofFn.mp (List.mem_of_mem_drop hp);exact hpc ⟨x.1,i⟩) + (by intro p hp;obtain ⟨i,rfl⟩:=List.mem_ofFn.mp (List.mem_of_mem_drop hp);exact hpv ⟨x.1,i⟩) + dsimp only [F] + refine hb.trans ?_ + have hlen : ((List.ofFn (f x.1)).drop (K x.1-x.2.val)).length≤K x.1:=by simp only [List.length_drop,List.length_ofFn];omega + nlinarith [Nat.mul_le_mul_left (2*pc.eval (len x)+96*n x.1+25) hlen, + Nat.mul_le_mul hlen (Nat.add_le_add_left (Nat.mul_le_mul_right (2*pc.eval (len x)+96*n x.1+25) hlen) + (pv.eval (len x)+90*n x.1*n x.1+22*n x.1+7))] + simpa only [F,Nat.sub_self,List.drop_zero] using boundedStages hK h0 hs + (hk.unaryPoly.pull (fun x:Σa,Fin (K a+1)=>x.1)) hW hc +end NetEmits +end ExactQuantumFactoring.NetworkEmission + +end + + + +end OAI diff --git a/lean/OAI/Computability/QuantumFactoring/DivisorData.lean b/lean/OAI/Computability/QuantumFactoring/DivisorData.lean new file mode 100644 index 0000000000000000000000000000000000000000..1bbfbad50ad704d456574966cbf9c5f91a6cc018 --- /dev/null +++ b/lean/OAI/Computability/QuantumFactoring/DivisorData.lean @@ -0,0 +1,198 @@ +import Mathlib +import OAI.Computability.QuantumFactoring.RetrospectiveOrder +import OAI.Computability.QuantumFactoring.PrimeRecords + +namespace OAI + +section +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators +open scoped BigOperators + + +namespace ExactQuantumFactoring +open scoped BigOperators +open AuxiliaryTree + +/-- Expand ONLY the supplied exponent record. No factoring operation is hidden +in the list used by the retrospective controller. -/ +def recordPrimes (f : FactorRecord) : List ℕ := + (f.support.sort (· ≤ ·)).flatMap (fun p => List.replicate (f p) p) + +lemma recordPrimes_prime {f : FactorRecord} (hp : ∀ p∈f.support,p.Prime) : + ∀ p∈recordPrimes f,p.Prime := by + intro p h + obtain ⟨q,hq,hp'⟩ := List.mem_flatMap.mp h + have he : p=q := (List.mem_replicate.mp hp').2 + subst p + exact hp q ((Finset.mem_sort (· ≤ ·)).mp hq) + +lemma recordPrimes_prod (f : FactorRecord) : (recordPrimes f).prod=f.prod (·^·) := by + rw [recordPrimes,prod_flatMap] + simp only [List.prod_replicate] + rw [←List.prod_toFinset _ (Finset.sort_nodup _ _),Finset.sort_toFinset] + rfl + +lemma recordPrimes_length (f : FactorRecord) : (recordPrimes f).length=f.sum (fun _ e => e) := by + rw [recordPrimes,List.length_flatMap] + simp only [List.length_replicate] + rw [←List.sum_toFinset _ (Finset.sort_nodup _ _),Finset.sort_toFinset] + rfl + +/-- Divide a subfactor from the parent's prime list, in bounded time: there is +at most one division per prime occurrence in the already supplied list. -/ +def divisorPrimes : ℕ→List ℕ→List ℕ + | _, [] => [] + | m, p::ps => if p∣m then p::divisorPrimes (m/p) ps else divisorPrimes m ps + +lemma divisorPrimes_length (m : ℕ) (ps : List ℕ) : (divisorPrimes m ps).length ≤ ps.length := by + induction ps generalizing m with + | nil => simp [divisorPrimes] + | cons p ps ih => + rw [divisorPrimes] + split_ifs + · exact Nat.succ_le_succ (ih _) + · exact (ih _).trans (by simp) + +lemma divisorPrimes_prime (m : ℕ) (ps : List ℕ) (hp : ∀ p∈ps,p.Prime) : + ∀ p∈divisorPrimes m ps,p.Prime := by + induction ps generalizing m with + | nil => simp [divisorPrimes] + | cons p ps ih => + have htail : ∀ q∈ps,q.Prime := fun q hq => hp q (by simp [hq]) + rw [divisorPrimes] + split_ifs + · intro q hq + rcases List.mem_cons.mp hq with he | hq + · subst q; exact hp p (by simp) + · exact ih _ htail q hq + · exact ih _ htail + +lemma divisorPrimes_prod (ps : List ℕ) (hp : ∀ p∈ps,p.Prime) {m : ℕ} (hd : m∣ps.prod) : + (divisorPrimes m ps).prod=m := by + induction ps generalizing m with + | nil => + have hm := Nat.dvd_one.mp hd + simp [divisorPrimes,hm] + | cons p ps ih => + have hprime := hp p (by simp) + have htail : ∀ q∈ps,q.Prime := fun q hq => hp q (by simp [hq]) + rw [divisorPrimes] + split_ifs with hdiv + · rw [List.prod_cons,ih htail (quotient_dvd_tail hprime.pos hdiv hd),Nat.mul_div_cancel' hdiv] + · exact ih htail ((hprime.coprime_iff_not_dvd.mpr hdiv).symm.dvd_of_dvd_mul_left hd) + +/-- Literal stored record projection, used only after complete-data validation. -/ +def FactorData.factors : FactorData→FactorRecord + | .node _ f _ => f + +def FactorData.descendants : FactorData→List FactorData + | .node _ _ ds => ds + +@[simp] lemma trueData_factors (m : ℕ) : (trueData m).factors=m.factorization := by + rw [trueData_eq]; rfl +@[simp] lemma trueData_descendants (m : ℕ) : (trueData m).descendants=(children m).map trueData := by + rw [trueData_eq]; rfl + +def dataDivisorPrimes (data : FactorData) (m : ℕ) : List ℕ := + divisorPrimes m (recordPrimes data.factors) + +lemma dataDivisorPrimes_correct {M m : ℕ} (hM : 0 Nat.prime_of_mem_primeFactors) + have hprod : (recordPrimes M.factorization).prod=M := by + rw [recordPrimes_prod,Nat.prod_factorization_pow_eq_self hM.ne'] + refine ⟨?_,?_⟩ + · simpa only [dataDivisorPrimes,trueData_factors] using divisorPrimes_prime m _ hp + · simpa only [dataDivisorPrimes,trueData_factors] using divisorPrimes_prod _ hp (show m∣(recordPrimes M.factorization).prod by rw [hprod]; exact hd) + +/-- Child lookup takes the first matching stored occurrence. It does not compute +new children. Distinct parents deliberately retain separate occurrence data. -/ +def dataChildPrimes (data : FactorData) (label : ℕ) : List ℕ := + match data.descendants.find? (fun d => decide (d.label=label)) with + | none => [] + | some d => recordPrimes d.factors + +lemma dataChildPrimes_correct {M label : ℕ} (h : label∈children M) : + (∀ p∈dataChildPrimes (trueData M) label,p.Prime) ∧ + (dataChildPrimes (trueData M) label).prod=label := by + have hex : ∃ d, ((children M).map trueData).find? (fun d => decide (d.label=label))=some d := by + cases hf : ((children M).map trueData).find? (fun d => decide (d.label=label)) with + | none => + have hh := List.find?_eq_none.mp hf (trueData label) (List.mem_map.mpr ⟨label,h,rfl⟩) + simp only [trueData_label,decide_true] at hh + contradiction + | some d => exact ⟨d,rfl⟩ + obtain ⟨d,hd⟩ := hex + obtain ⟨l,hl,rfl⟩ := List.mem_map.mp (List.mem_of_find?_eq_some hd) + have he : l=label := by simpa only [trueData_label,decide_eq_true_eq] using List.find?_some hd + subst l + have hlabel := (child_bounds h).1 + simp only [dataChildPrimes,trueData_descendants,hd,trueData_factors] + refine ⟨recordPrimes_prime (fun _ => Nat.prime_of_mem_primeFactors),?_⟩ + rw [recordPrimes_prod,Nat.prod_factorization_pow_eq_self (by omega)] + +/-- phi factors are reconstructed from division against the supplied parent +record and the supplied p−1 children. The p=2 contribution requires no child. -/ +noncomputable def dataTotientPrimes (data : FactorData) (m : ℕ) : List ℕ := + let f := primeRecord (dataDivisorPrimes data m) + (f.support.sort (· ≤ ·)).flatMap (fun p => + List.replicate (f p-1) p ++ if p=2 then [] else dataChildPrimes data (p-1)) + +lemma dataTotientPrimes_correct {M m : ℕ} (hM : 0 p^(m.factorization p-1)*(p-1))).prod := by + congr 1 + apply List.map_congr_left + intro p hp + rw [List.prod_append,List.prod_replicate] + split_ifs with h2 + · subst p + simp + · rw [(dataChildPrimes_correct (hchild p ((Finset.mem_sort (· ≤ ·)).mp hp) h2)).2] + _ = m.factorization.prod (fun p e => p^(e-1)*(p-1)) := by + rw [←List.prod_toFinset _ (Finset.sort_nodup _ _),Finset.sort_toFinset] + rfl + _ = m.totient := (Nat.totient_eq_prod_factorization hm.ne').symm + +/-- Section5's retrospective order algorithm instantiated with the **actual +supplied auxiliary data**, not with a hypothesized factorization of phi. -/ +theorem data_strip_order {M m : ℕ} (hM : 0